Skip to content

Commit c034670

Browse files
authored
fix(codex): keep authenticated user identity in agent turns (#121511)
* fix(codex): preserve authenticated sender context * test(codex): type sender recorder fixture * fix(codex): scope sender context to user turns
1 parent 27d2af2 commit c034670

5 files changed

Lines changed: 140 additions & 0 deletions

File tree

‎extensions/codex/src/app-server/protocol.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,7 @@ type CodexTurnInterruptParams = JsonObject & {
365365
export type CodexTurnStartParams = JsonObject & {
366366
threadId: string;
367367
input: CodexUserInput[];
368+
additionalContext?: Record<string, { kind: "untrusted" | "application"; value: string }>;
368369
cwd?: string;
369370
model?: string;
370371
approvalPolicy?: CodexApprovalPolicy | null;

‎extensions/codex/src/app-server/run-attempt.test.ts‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5016,6 +5016,90 @@ describe("runCodexAppServerAttempt", () => {
50165016
const resumeRequestParams = resumeRequest?.params as Record<string, unknown> | undefined;
50175017
expect(resumeRequestParams?.developerInstructions).not.toContain(CODEX_GPT5_BEHAVIOR_CONTRACT);
50185018
});
5019+
it("sends the current recorded sender on successive turns of one resumed Codex thread", async () => {
5020+
const { sessionFile, workspaceDir } = createRunPaths();
5021+
await writeExistingBinding(sessionFile, workspaceDir, { dynamicToolsFingerprint: "[]" });
5022+
const turnIds = ["turn-ada", "turn-grace"] as const;
5023+
let nextTurnIndex = 0;
5024+
const harness = createAppServerHarness(async (method, params) => {
5025+
if (method === "thread/resume") {
5026+
return threadStartResult((params as { threadId?: string }).threadId ?? "thread-existing");
5027+
}
5028+
if (method === "turn/start") {
5029+
const turnId = turnIds[nextTurnIndex++];
5030+
if (!turnId) {
5031+
throw new Error("unexpected extra turn/start");
5032+
}
5033+
return turnStartResult(turnId);
5034+
}
5035+
return {};
5036+
});
5037+
5038+
const runTurn = async (sender: { id: string; name: string }, prompt: string, runId: string) => {
5039+
const expectedTurnStarts =
5040+
harness.requests.filter((request) => request.method === "turn/start").length + 1;
5041+
const params = createParams(sessionFile, workspaceDir, { prompt, runId });
5042+
params.trigger = "user";
5043+
const message = {
5044+
role: "user" as const,
5045+
content: prompt,
5046+
timestamp: Date.now(),
5047+
__openclaw: { senderId: sender.id, senderName: sender.name },
5048+
};
5049+
params.userTurnTranscriptRecorder = {
5050+
message,
5051+
resolveMessage: async () => message,
5052+
getAdmissionReceipt: () => undefined,
5053+
markRuntimePersistencePending() {},
5054+
markRuntimePersisted() {},
5055+
} as unknown as EmbeddedRunAttemptParams["userTurnTranscriptRecorder"];
5056+
const run = runCodexAppServerAttempt(params);
5057+
await vi.waitFor(
5058+
() =>
5059+
expect(
5060+
harness.requests.filter((request) => request.method === "turn/start"),
5061+
).toHaveLength(expectedTurnStarts),
5062+
fastWait,
5063+
);
5064+
await harness.completeTurn({
5065+
threadId: "thread-existing",
5066+
turnId: `turn-${sender.name.toLowerCase()}`,
5067+
});
5068+
await run;
5069+
};
5070+
5071+
await runTurn({ id: "profile-ada", name: "Ada" }, "first request", "run-ada");
5072+
await runTurn({ id: "profile-grace", name: "Grace" }, "second request", "run-grace");
5073+
5074+
expect(
5075+
harness.requests
5076+
.filter((request) =>
5077+
["thread/start", "thread/resume", "turn/start"].includes(request.method),
5078+
)
5079+
.map((request) => request.method),
5080+
).toEqual(["thread/resume", "turn/start", "turn/start"]);
5081+
expect(
5082+
harness.requests
5083+
.filter((request) => request.method === "turn/start")
5084+
.map(
5085+
(request) =>
5086+
(
5087+
request.params as {
5088+
additionalContext?: Record<string, { kind: string; value: string }>;
5089+
}
5090+
).additionalContext?.openclaw_current_sender,
5091+
),
5092+
).toEqual([
5093+
{
5094+
kind: "untrusted",
5095+
value: '{"sender":{"id":"profile-ada","name":"Ada"}}',
5096+
},
5097+
{
5098+
kind: "untrusted",
5099+
value: '{"sender":{"id":"profile-grace","name":"Grace"}}',
5100+
},
5101+
]);
5102+
});
50195103
it("starts a fresh Codex thread before resume when the native rollout reaches the fallback fuse", async () => {
50205104
const { sessionFile, workspaceDir, agentDir } = createRunPaths();
50215105
await writeExistingBinding(sessionFile, workspaceDir, { dynamicToolsFingerprint: "[]" });

‎extensions/codex/src/app-server/turn-params.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import type { EmbeddedRunAttemptParams } from "openclaw/plugin-sdk/agent-harness-runtime";
22
import { GPT5_HEARTBEAT_PROMPT_OVERLAY as CODEX_GPT5_HEARTBEAT_PROMPT_OVERLAY } from "openclaw/plugin-sdk/provider-model-shared";
3+
import {
4+
asOptionalRecord,
5+
normalizeOptionalString,
6+
} from "openclaw/plugin-sdk/string-coerce-runtime";
7+
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
38
import { codexSandboxPolicyForTurn, type CodexAppServerRuntimeOptions } from "./config.js";
49
import type {
510
CodexSandboxPolicy,
@@ -14,6 +19,37 @@ import {
1419
} from "./thread-model-selection.js";
1520
import { buildCodexUserInput } from "./user-input.js";
1621

22+
const CODEX_CURRENT_SENDER_FIELD_MAX_CHARS = 256;
23+
24+
function buildCodexCurrentSenderContextValue(params: EmbeddedRunAttemptParams): string | undefined {
25+
const metadata = asOptionalRecord(
26+
asOptionalRecord(params.userTurnTranscriptRecorder?.message as unknown)?.["__openclaw"],
27+
);
28+
const recorded = [
29+
normalizeOptionalString(metadata?.["senderId"]),
30+
normalizeOptionalString(metadata?.["senderName"]),
31+
normalizeOptionalString(metadata?.["senderUsername"]),
32+
] as const;
33+
const [id, name, username] = recorded.some(Boolean)
34+
? recorded
35+
: [
36+
normalizeOptionalString(params.senderId),
37+
normalizeOptionalString(params.senderName),
38+
normalizeOptionalString(params.senderUsername),
39+
];
40+
if (!id && !name && !username) {
41+
return undefined;
42+
}
43+
const bound = (value: string) => truncateUtf16Safe(value, CODEX_CURRENT_SENDER_FIELD_MAX_CHARS);
44+
return JSON.stringify({
45+
sender: {
46+
...(id ? { id: bound(id) } : {}),
47+
...(name ? { name: bound(name) } : {}),
48+
...(username ? { username: bound(username) } : {}),
49+
},
50+
});
51+
}
52+
1753
export function buildTurnStartParams(
1854
params: EmbeddedRunAttemptParams,
1955
options: {
@@ -43,9 +79,16 @@ export function buildTurnStartParams(
4379
config: params.config,
4480
});
4581
const useThreadPermissionProfile = options.appServer.networkProxy && !options.sandboxPolicy;
82+
const currentSenderContext =
83+
params.trigger === "user" ? buildCodexCurrentSenderContextValue(params) : undefined;
84+
// Untrusted context exposes authenticated attribution without promoting human-controlled labels.
85+
const additionalContext: CodexTurnStartParams["additionalContext"] = currentSenderContext
86+
? { openclaw_current_sender: { kind: "untrusted", value: currentSenderContext } }
87+
: undefined;
4688
return {
4789
threadId: options.threadId,
4890
input: buildCodexUserInput(options.promptText ?? params.prompt, params.images),
91+
...(additionalContext ? { additionalContext } : {}),
4992
cwd: options.cwd,
5093
approvalPolicy: options.appServer.approvalPolicy,
5194
approvalsReviewer: options.appServer.approvalsReviewer,

‎test/fixtures/agents/prompt-snapshots/codex-runtime-happy-path/discord-group-codex-message-tool.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,12 @@
132132

133133
```json
134134
{
135+
"additionalContext": {
136+
"openclaw_current_sender": {
137+
"kind": "untrusted",
138+
"value": "{\"sender\":{\"id\":\"424242\",\"name\":\"Pash\",\"username\":\"pash\"}}"
139+
}
140+
},
135141
"approvalPolicy": "never",
136142
"approvalsReviewer": "user",
137143
"collaborationMode": {

‎test/fixtures/agents/prompt-snapshots/codex-runtime-happy-path/telegram-direct-codex-message-tool.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,12 @@
132132

133133
```json
134134
{
135+
"additionalContext": {
136+
"openclaw_current_sender": {
137+
"kind": "untrusted",
138+
"value": "{\"sender\":{\"id\":\"1000001\",\"name\":\"Pash\",\"username\":\"pash\"}}"
139+
}
140+
},
135141
"approvalPolicy": "never",
136142
"approvalsReviewer": "user",
137143
"collaborationMode": {

0 commit comments

Comments
 (0)