Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(openai-codex): skip trailing system messages on exec resume
Jack Rudenko4cb34e54ffc0
diff --git a/ai-docs/architecture/code-mode.md b/ai-docs/architecture/code-mode.mdindex 375d6408..5dc65259 100644--- a/ai-docs/architecture/code-mode.md+++ b/ai-docs/architecture/code-mode.md@@ -190,6 +190,15 @@ stored BEFORE 5d builds the input. Without it the builder rendered an unstored `that request and `Script completed` ("output unavailable after a claudish restart") on the next,for the same script.+**"The last message" means the last user or assistant message** (`conversationMessages` in+`code-mode/types.ts`), in 5r, in the input builder and in the turn-record anchor alike. Claude+Code sends `role: "system"` messages inside `messages` (SessionStart hook output, MCP server+instructions, the token reminder), and 2.1.303 ENDS requests with one: `user, system,+assistant(tool_use×3), user(tool_result×3), system`. Reading the raw last message, 5r found no+results on any request, so no script ever resumed and every answer took the lost path (Phase 7+V2a/V2b/V4/V8: 0 resumes across 39 relays). The same system message arrives as blocks while it is+last and as a string once a turn follows it, so it can never anchor a turn record either.+| Situation (the last user message answers nested ids) | Behaviour ||---|---|| suspended, owned by this session, expected batch | results resolve or reject by seq (`is_error` rejects with a plain string, as Codex); missing → "no tool_result returned"; blocked again → **synthetic reply**; done → output stored, the upstream turn continues and the input builder renders it |diff --git a/packages/cli/src/code-mode/input-builder.ts b/packages/cli/src/code-mode/input-builder.tsindex afac8eab..a965e4b6 100644--- a/packages/cli/src/code-mode/input-builder.ts+++ b/packages/cli/src/code-mode/input-builder.ts@@ -54,7 +54,12 @@ import { type ToolNameTable, normalizeToolIdent } from "./tool-names.js";import { imageUrlOf, toolResultImages, toolResultText } from "./tool-results.js";import { transliterateRound } from "./transliterate.js";import { turnAnchorFor } from "./turn-records.js";-import type { ClaudeContentBlock, ClaudeMessage, ResponsesItem } from "./types.js";+import {+ type ClaudeContentBlock,+ type ClaudeMessage,+ type ResponsesItem,+ conversationMessages,+} from "./types.js";/** Whose records a request may read. */export interface CodeModeKeys {@@ -546,8 +551,11 @@ export function buildCodeModeInput(keys: CodeModeKeys,options: BuildCodeModeInputOptions = {}): ResponsesItem[] {+ // The walk's neighbour rules (the message before an assistant message, the+ // first user message after a round) read the conversation only: Claude+ // Code's inline system messages were never rendered and sit between them.const builder = new InputBuilder(- Array.isArray(messages) ? messages : [],+ conversationMessages(messages),stores,keys,options.defaultMaxOutputTokens ?? DEFAULT_EXEC_MAX_OUTPUT_TOKENS,diff --git a/packages/cli/src/code-mode/relay.ts b/packages/cli/src/code-mode/relay.tsindex e267cfea..8fd40661 100644--- a/packages/cli/src/code-mode/relay.ts+++ b/packages/cli/src/code-mode/relay.ts@@ -71,7 +71,10 @@ export interface CodeModeTurnContext {allTools: readonly ExecToolMeta[];/** Output budget of an exec with no pragma (discovery's truncation limit). */defaultMaxOutputTokens: number;- /** The request's last message: what a text-only message answered (its anchor). */+ /**+ * The request's last user/assistant message (`conversationMessages`): what a+ * text-only message answered (its anchor). Never a trailing system message.+ */previousMessage: ClaudeMessage | undefined;/** Test seam: the sandbox module. Default `loadQuickJSModule`. */loadModule?: () => Promise<QuickJSModuleLease | undefined>;diff --git a/packages/cli/src/code-mode/resume.ts b/packages/cli/src/code-mode/resume.tsindex 819ecace..5a8fca61 100644--- a/packages/cli/src/code-mode/resume.ts+++ b/packages/cli/src/code-mode/resume.ts@@ -16,6 +16,10 @@* one-shot calls, and consuming a batch there would run the script's next tools* outside the turn that owns it; the next ordinary request resumes it.*+ * Every rule below reads the conversation's messages only (`conversationMessages`):+ * Claude Code's inline `role: "system"` messages, which 2.1.303 puts LAST, are+ * skipped, so "the last message" is the last user or assistant message.+ ** Entry: the last user message carries tool_results whose ids decode as nested* ids. Only a suspended record owned by this session is resumed:*@@ -61,7 +65,12 @@ import type { ExecRecord, ScriptStore } from "./script-store.js";import type { CodeModeStores } from "./stores.js";import { normalizeToolIdent } from "./tool-names.js";import { nestedResultFromToolResult, toolResultImages, toolResultText } from "./tool-results.js";-import type { ClaudeContentBlock, ClaudeMessage, NestedToolUse } from "./types.js";+import {+ type ClaudeContentBlock,+ type ClaudeMessage,+ type NestedToolUse,+ conversationMessages,+} from "./types.js";/** Claude Code's interrupt marker (2.1.290: a user text block beside the results). */export const INTERRUPT_MARKER = "[Request interrupted by user";@@ -640,7 +649,9 @@ export function resumeFromToolResults(// session's other scripts, or be answered with tool_use blocks.const tools = Array.isArray(req.tools) ? (req.tools as ClaudeToolLike[]) : [];if (tools.length === 0) return { kind: "none" };- const messages = Array.isArray(req.messages) ? (req.messages as ClaudeMessage[]) : [];+ // Only user/assistant: a trailing system message (Claude Code 2.1.303)+ // is never "the last message" that answers a batch.+ const messages = conversationMessages(req.messages);let active = stores;if (!active &&diff --git a/packages/cli/src/code-mode/turn-records.ts b/packages/cli/src/code-mode/turn-records.tsindex c13939a0..9a21a8c2 100644--- a/packages/cli/src/code-mode/turn-records.ts+++ b/packages/cli/src/code-mode/turn-records.ts@@ -57,8 +57,11 @@ function recordKey(sessionKey: string, anchor: string): string {* The anchor of an assistant message: its first tool_use id, else* `sha256(sessionKey ‖ sha256(canonical previous message) ‖ text blocks* trimmed and joined with "\n")`. `previousMessage` is the user message the- * assistant message answered — the last message of the request that produced- * it, which precedes it in every later history.+ * assistant message answered — the last conversation message of the request+ * that produced it, which precedes it in every later history's conversation+ * messages. Never a system message: Claude Code sends the same one as blocks+ * when it is last and as a string once a turn follows it, so its hash differs+ * between the request that stores a record and every request that reads it.*/export function turnAnchorFor(sessionKey: string,diff --git a/packages/cli/src/code-mode/types.ts b/packages/cli/src/code-mode/types.tsindex 7f061351..40a33c46 100644--- a/packages/cli/src/code-mode/types.ts+++ b/packages/cli/src/code-mode/types.ts@@ -31,6 +31,23 @@ export interface ClaudeMessage {content: string | ClaudeContentBlock[];}+/**+ * The conversation's own messages: `user` and `assistant`, in order.+ *+ * Claude Code also sends `role: "system"` messages INSIDE `messages` (the+ * SessionStart hook's output, MCP server instructions, the token reminder), and+ * 2.1.303 ENDS a request with one: `user, system, assistant(tool_use×3),+ * user(tool_result×3), system`. Code mode reasons about message ORDER — the+ * last message, the message before an assistant message, a message after a+ * batch — so it reads this view: a trailing system message hid every batch's+ * answer and no script ever resumed. The input builder never rendered a system+ * message, so dropping them changes no output.+ */+export function conversationMessages(messages: unknown): ClaudeMessage[] {+ if (!Array.isArray(messages)) return [];+ return messages.filter((m): m is ClaudeMessage => m?.role === "user" || m?.role === "assistant");+}+/** A nested tool call relayed to Claude Code as one tool_use block. */export interface NestedToolUse {/** `toolu_cx_<hex>_<seq>` (`encodeNestedId`). */diff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.tsindex 5dcb058b..31e399fb 100644--- a/packages/cli/src/handlers/composed-handler.ts+++ b/packages/cli/src/handlers/composed-handler.ts@@ -51,6 +51,7 @@ import {import { resumeFromToolResults } from "../code-mode/resume.js";import { loadQuickJSModule } from "../code-mode/sandbox/quickjs-loader.js";import { getCodeModeStores, peekCodeModeStores } from "../code-mode/stores.js";+import { conversationMessages } from "../code-mode/types.js";import {getLogLevel,log,@@ -2504,9 +2505,10 @@ export class ComposedHandler implements ModelHandler {names: codeModeTurn.names,allTools: codeModeTurn.allTools,defaultMaxOutputTokens: codeModeTurn.defaultMaxOutputTokens,- previousMessage: Array.isArray(claudeRequest?.messages)- ? claudeRequest.messages[claudeRequest.messages.length - 1]- : undefined,+ // The last user/assistant message, as the input builder reads+ // the message before a text-only answer (a trailing system+ // message would anchor the turn record where no render looks).+ previousMessage: conversationMessages(claudeRequest?.messages).at(-1),}): undefined,};