Skip to content

Commit 27f62f3

Browse files
authored
fix(codex): verify native patches and honor fast mode (#114907)
1 parent dae1817 commit 27f62f3

9 files changed

Lines changed: 1064 additions & 27 deletions

‎extensions/codex/src/app-server/event-projector-tool-transcript.ts‎

Lines changed: 202 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import path from "node:path";
12
import {
23
embeddedAgentLog,
34
runAgentHarnessAfterToolCallHook,
@@ -38,6 +39,7 @@ import { resolveCodexLocalRuntimeAttribution } from "./local-runtime-attribution
3839
import type {
3940
CodexDynamicToolCallOutputContentItem,
4041
CodexThreadItem,
42+
JsonObject,
4143
JsonValue,
4244
} from "./protocol.js";
4345
import { readCodexMirroredSessionHistoryMessages } from "./session-history.js";
@@ -56,6 +58,64 @@ const ZERO_USAGE: Usage = {
5658

5759
const MISSING_TOOL_RESULT_ERROR =
5860
"OpenClaw recorded a native Codex tool.call without a matching tool.result before the turn completed.";
61+
const NATIVE_PATCH_REJECTION_RE =
62+
/^\s*patch rejected:\s*writing outside of the project;\s*rejected by user approval settings\s*$/iu;
63+
const CODE_MODE_NATIVE_PATCH_SOURCE_RE =
64+
/^\s*(?:\/\/[^\r\n]*\r?\n\s*)?(?:const|let)\s+([A-Za-z_$][\w$]*)\s*=\s*await\s+tools\.apply_patch\(\s*("(?:\\[\s\S]|[^"\\])*")\s*\)\s*;?\s*text\(\s*\1\s*\)\s*;?\s*$/u;
65+
const CODE_MODE_NATIVE_PATCH_RESULT_RE =
66+
/^\s*Script (completed|failed)\s*\r?\nWall time\s+\d+(?:\.\d+)?\s+seconds\s*\r?\nOutput:\s*([\s\S]*?)\s*$/iu;
67+
68+
function readCodeModeNativePatchInput(source: unknown): string | undefined {
69+
if (typeof source !== "string") {
70+
return undefined;
71+
}
72+
const match = CODE_MODE_NATIVE_PATCH_SOURCE_RE.exec(source);
73+
if (!match?.[2]) {
74+
return undefined;
75+
}
76+
try {
77+
const patch: unknown = JSON.parse(match[2]);
78+
return typeof patch === "string" &&
79+
/^\*\*\* Begin Patch\r?\n[\s\S]*\r?\n\*\*\* End Patch(?:\r?\n)?$/u.test(patch)
80+
? patch
81+
: undefined;
82+
} catch {
83+
return undefined;
84+
}
85+
}
86+
87+
function readInterceptedNativePatchInput(
88+
command: unknown,
89+
): { input: string; cwd?: string } | undefined {
90+
if (typeof command !== "string") {
91+
return undefined;
92+
}
93+
const lines = command.replace(/\r\n?/gu, "\n").split("\n");
94+
const patchStart = lines.indexOf("*** Begin Patch");
95+
// Nested heredocs and shell expansion can hide extra commands. Trust only
96+
// a top-level patch, an inert cd, and a single-quoted matching delimiter.
97+
const invocation =
98+
/^[\t ]*(?:cd[\t ]+(?:'([^'\n]+)'|([A-Za-z0-9_./-]+))[\t ]+&&[\t ]+)?apply_patch[\t ]*<<-?[\t ]*'([^'\n]+)'[\t ]*$/u.exec(
99+
lines[0] ?? "",
100+
);
101+
if (!invocation || patchStart !== 1) {
102+
return undefined;
103+
}
104+
const patchEnd = lines.indexOf("*** End Patch", patchStart + 1);
105+
const cwd = invocation[1] ?? invocation[2];
106+
const delimiter = invocation[3];
107+
if (
108+
patchEnd < 0 ||
109+
lines[patchEnd + 1] !== delimiter ||
110+
lines.slice(patchEnd + 2).some((line) => line.trim().length > 0)
111+
) {
112+
return undefined;
113+
}
114+
return {
115+
input: `${lines.slice(patchStart, patchEnd + 1).join("\n")}\n`,
116+
...(cwd ? { cwd } : {}),
117+
};
118+
}
59119

60120
export class CodexToolTranscriptProjection {
61121
private readonly messages: AgentMessage[] = [];
@@ -69,6 +129,8 @@ export class CodexToolTranscriptProjection {
69129
private readonly afterToolCallObservedItemIds = new Set<string>();
70130
private readonly nativeMcpAppResultDetails = new Map<string, unknown>();
71131
private readonly nativeMcpAppResultDetailsAttempted = new Set<string>();
132+
private readonly rawNativeToolOutputByCallId = new Map<string, string>();
133+
private readonly codeModeNativePatchInputsByCallId = new Map<string, string>();
72134

73135
constructor(
74136
private readonly params: EmbeddedRunAttemptParams,
@@ -130,13 +192,152 @@ export class CodexToolTranscriptProjection {
130192
this.recordToolResult({
131193
id: item.id,
132194
name,
133-
text: itemTranscriptResultText(item, this.progress.outputTextByItem),
195+
text:
196+
this.rawNativeToolOutputByCallId.get(item.id) ??
197+
itemTranscriptResultText(item, this.progress.outputTextByItem),
134198
isError: isNonSuccessItemStatus(itemStatus(item)),
135199
details,
136200
});
137201
}
138202
}
139203

204+
recordRawNativeToolItem(item: JsonObject): void {
205+
const type = typeof item.type === "string" ? item.type : undefined;
206+
const callId =
207+
typeof item.call_id === "string"
208+
? item.call_id
209+
: typeof item.callId === "string"
210+
? item.callId
211+
: undefined;
212+
if (!callId) {
213+
return;
214+
}
215+
if (
216+
(type === "custom_tool_call" || type === "function_call") &&
217+
(item.name === "apply_patch" || item.name === "exec_command" || item.name === "exec")
218+
) {
219+
let args: Record<string, unknown> | undefined;
220+
if (
221+
type === "custom_tool_call" &&
222+
item.name === "apply_patch" &&
223+
typeof item.input === "string"
224+
) {
225+
args = { input: item.input };
226+
} else if (type === "custom_tool_call" && item.name === "exec") {
227+
const input = readCodeModeNativePatchInput(item.input);
228+
if (input) {
229+
// Successful code-mode patches already emit their own FileChange;
230+
// retain only the outer call so a pre-emission denial can be linked.
231+
this.codeModeNativePatchInputsByCallId.set(callId, input);
232+
}
233+
return;
234+
} else if (type === "function_call" && typeof item.arguments === "string") {
235+
try {
236+
const parsed: unknown = JSON.parse(item.arguments);
237+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
238+
const parsedArguments = parsed as Record<string, unknown>;
239+
if (item.name === "apply_patch") {
240+
args = parsedArguments;
241+
} else {
242+
const command =
243+
typeof parsedArguments.cmd === "string"
244+
? parsedArguments.cmd
245+
: typeof parsedArguments.command === "string"
246+
? parsedArguments.command
247+
: undefined;
248+
const patch = readInterceptedNativePatchInput(command);
249+
if (patch) {
250+
const workdir =
251+
typeof parsedArguments.workdir === "string"
252+
? parsedArguments.workdir
253+
: typeof parsedArguments.cwd === "string"
254+
? parsedArguments.cwd
255+
: undefined;
256+
const cwd = patch.cwd
257+
? workdir && !path.isAbsolute(patch.cwd)
258+
? path.join(workdir, patch.cwd)
259+
: patch.cwd
260+
: workdir;
261+
args = { input: patch.input, ...(cwd ? { cwd } : {}) };
262+
}
263+
}
264+
}
265+
} catch {
266+
return;
267+
}
268+
}
269+
if (args) {
270+
this.recordToolCall({ id: callId, name: "apply_patch", arguments: args });
271+
}
272+
return;
273+
}
274+
if (
275+
(type !== "custom_tool_call_output" && type !== "function_call_output") ||
276+
(this.namesById.get(callId) !== "apply_patch" &&
277+
!this.codeModeNativePatchInputsByCallId.has(callId))
278+
) {
279+
return;
280+
}
281+
const text =
282+
typeof item.output === "string"
283+
? item.output
284+
: Array.isArray(item.output)
285+
? collectDynamicToolContentText(item.output as CodexThreadItem["contentItems"])
286+
: "";
287+
if (!text.trim()) {
288+
return;
289+
}
290+
const codeModePatchInput = this.codeModeNativePatchInputsByCallId.get(callId);
291+
if (codeModePatchInput) {
292+
this.codeModeNativePatchInputsByCallId.delete(callId);
293+
const execution = CODE_MODE_NATIVE_PATCH_RESULT_RE.exec(text);
294+
if (execution?.[1]?.toLowerCase() === "completed" && execution[2]?.trim() === "{}") {
295+
// The canonical nested FileChange already owns successful patch audit.
296+
return;
297+
}
298+
if (execution?.[1]?.toLowerCase() === "failed") {
299+
const failure = execution[2]?.replace(/^Script error:\s*/iu, "").trim() || text;
300+
this.recordToolCall({
301+
id: callId,
302+
name: "apply_patch",
303+
arguments: { input: codeModePatchInput },
304+
});
305+
this.recordToolResult({ id: callId, name: "apply_patch", text: failure, isError: true });
306+
}
307+
return;
308+
}
309+
this.rawNativeToolOutputByCallId.set(callId, text);
310+
const result = this.messages.find(
311+
(message) =>
312+
message.role === "toolResult" &&
313+
(message as unknown as { toolCallId?: unknown }).toolCallId === callId,
314+
);
315+
if (!result) {
316+
if (NATIVE_PATCH_REJECTION_RE.test(text)) {
317+
// Only the upstream's explicit rejection can settle without a native
318+
// FileChange status; unknown outcomes must remain failed-closed.
319+
this.recordToolResult({
320+
id: callId,
321+
name: "apply_patch",
322+
text,
323+
isError: true,
324+
});
325+
}
326+
return;
327+
}
328+
// Codex publishes its canonical FileChange terminal item before the
329+
// model-visible raw output; preserve its authoritative success status.
330+
const replacement = this.createToolResultMessage({
331+
id: callId,
332+
name: "apply_patch",
333+
text,
334+
isError: (result as unknown as { isError?: unknown }).isError === true,
335+
});
336+
(result as unknown as { content: unknown }).content = (
337+
replacement as unknown as { content: unknown }
338+
).content;
339+
}
340+
140341
async recordNativeToolResultWithDetails(item: CodexThreadItem | undefined): Promise<void> {
141342
this.recordNativeToolResult(item, await this.prepareNativeMcpAppResultDetails(item));
142343
}

0 commit comments

Comments
 (0)