diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d649b0b..3dcbb3f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,6 +34,7 @@ jobs: with: filters: | global: + - 'crates/codexcw/tests/fixtures/streams/**' - 'devbox.json' - 'devbox.lock' - 'package.json' diff --git a/Cargo.lock b/Cargo.lock index 95c4496..0fd9f58 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -41,6 +41,7 @@ dependencies = [ "napi", "napi-build", "napi-derive", + "serde_json", "tokio", "tokio-stream", ] @@ -51,6 +52,7 @@ version = "0.7.0" dependencies = [ "codexcw", "pyo3", + "serde_json", "tokio", "tokio-stream", ] @@ -250,6 +252,8 @@ dependencies = [ "napi-sys", "nohash-hasher", "rustc-hash", + "serde", + "serde_json", "tokio", ] diff --git a/bindings/node/Cargo.toml b/bindings/node/Cargo.toml index a28b455..dc3c7b3 100644 --- a/bindings/node/Cargo.toml +++ b/bindings/node/Cargo.toml @@ -12,8 +12,9 @@ publish = false crate-type = ["cdylib"] [dependencies] +serde_json.workspace = true codexcw.workspace = true -napi = { version = "3", default-features = false, features = ["napi8", "tokio_rt"] } +napi = { version = "3", default-features = false, features = ["napi8", "tokio_rt", "serde-json"] } napi-derive = "3" tokio.workspace = true tokio-stream.workspace = true diff --git a/bindings/node/__test__/smoke.test.mjs b/bindings/node/__test__/smoke.test.mjs index b7f8f12..43529f9 100644 --- a/bindings/node/__test__/smoke.test.mjs +++ b/bindings/node/__test__/smoke.test.mjs @@ -238,6 +238,7 @@ test('claude agent normalizes stream-json events', async () => { { inputTokens: 18, outputTokens: 380, + reasoningOutputTokens: 0, cacheReadInputTokens: 45921, cacheCreationInputTokens: 3944, webSearchRequests: 0, @@ -632,3 +633,57 @@ test( assert.match(result.finalMessage.toUpperCase(), /OK/) }, ) + +test('replays agent stream contracts through the public binding', async () => { + const fixtures = join(here, '../../../crates/codexcw/tests/fixtures/streams') + async function replay(agent, request, expectedFlag) { + const runner = new Runner({ + agent, + executable: join(fixtures, 'replay.sh'), + env: { STREAM_FIXTURE: join(fixtures, agent + '.jsonl'), EXPECT_FLAG: expectedFlag }, + }) + return runner.run({ prompt: 'replay', ...request }) + } + + const codex = await replay('codex', { forkId: 'previous' }, 'fork') + assert.equal(codex.finalMessage, 'DONE') + assert.equal(codex.sessionUsage.cacheCreationInputTokens, 3) + assert.equal(codex.invocationUsage, undefined) + assert.equal(codex.events.find(e => e.type === 'item.updated').item.todos[0].completed, true) + const mcp = codex.events.find(e => e.item?.id === 'mcp').item.mcp + assert.deepEqual(mcp.result.structuredContent, { color: 'GOLD' }) + const searches = codex.events.filter(e => e.item?.webSearch).map(e => e.item.webSearch) + assert.equal(searches[0].results, undefined) + assert.equal(searches[1].results[0].title, 'Example') + assert.deepEqual(searches[2].results, []) + + const claude = await replay('claude', { includePartialMessages: true }, '--include-partial-messages') + assert.equal(claude.finalMessage, 'finished') + assert.deepEqual(claude.structuredOutput, { ok: true }) + assert.equal(claude.invocationUsage.totalTokens, 24) + assert.equal(claude.sessionUsage.totalTokens, 84) + assert.ok(claude.events.some(e => e.delta)) + assert.equal(claude.events.at(-1).structuredOutput, undefined) + assert.deepEqual(claude.events.filter(e => e.item?.type === 'agent_message').map(e => e.item.text), + ['waiting', 'child answer', 'finished']) + const task = claude.events.find(e => e.task?.usage).task + assert.equal(task.summary, 'Sample checked') + assert.deepEqual(task.usage, { durationMs: 120, toolUses: 2, totalTokens: 17 }) + + const grok = await replay('grok', { includePartialMessages: true }, '--include-partial-messages') + assert.equal(grok.events.find(e => e.item?.exitCode === 7).item.status, 'failed') + assert.deepEqual(grok.structuredOutput, { ok: true }) +}) + +test('Claude startup failures retain the provider reason', async () => { + const fixtures = join(here, '../../../crates/codexcw/tests/fixtures/streams') + const runner = new Runner({ + agent: 'claude', + executable: join(fixtures, 'replay.sh'), + env: { STREAM_FIXTURE: join(fixtures, 'startup-failure.jsonl'), STREAM_EXIT: '1' }, + }) + await assert.rejects(runner.run({ prompt: 'replay', resumeId: 'missing' }), { + kind: 'claude', + failureReason: 'resume_target_not_found', + }) +}) diff --git a/bindings/node/binding.d.ts b/bindings/node/binding.d.ts index 5292bf1..c9f7bde 100644 --- a/bindings/node/binding.d.ts +++ b/bindings/node/binding.d.ts @@ -176,6 +176,7 @@ export interface JsConfigOverride { /** A typed run error. */ export interface JsError { + failureReason?: string /** * One of: `promptRequired`, `invalidRequest`, `exit`, `decode`, `codex`, * `claude`, `grok`, `handler`, `cancelled`, `process`. @@ -189,6 +190,14 @@ export interface JsError { /** One decoded agent event. */ export interface JsEvent { + structuredOutput?: any + invocationUsage?: JsUsage + sessionUsage?: JsUsage + parentToolUseId: string + resultIndex?: number + failureReason: string + delta?: JsStreamDelta + task?: JsTaskUpdate type: string runId: string threadId: string @@ -214,6 +223,10 @@ export interface JsGroupResult { /** A typed projection of an agent item. */ export interface JsItem { + phase?: string + webSearch?: JsWebSearch + mcp?: JsMcpCall + todos?: Array id: string type: string status: string @@ -235,8 +248,25 @@ export interface JsManyOptions { eventBuffer?: number } +/** McpCall projection from the core event model. */ +export interface JsMcpCall { + server: string + tool: string + arguments?: any + result?: JsMcpResult + error?: string +} + +/** McpResult projection from the core event model. */ +export interface JsMcpResult { + content: Array + structuredContent?: any + meta?: any +} + /** Per-model usage reported by an agent. */ export interface JsModelUsage { + reasoningOutputTokens: number inputTokens: number outputTokens: number cacheReadInputTokens: number @@ -283,6 +313,8 @@ export interface JsRequest { dangerouslyBypassSandbox?: boolean dangerouslyBypassHooks?: boolean env?: Record + includePartialMessages?: boolean + forkId?: string resumeId?: string resumeLast?: boolean resumeAll?: boolean @@ -310,6 +342,9 @@ export interface JsRunnerOptions { /** Summary of a completed run. */ export interface JsRunResult { + structuredOutput?: any + invocationUsage?: JsUsage + sessionUsage?: JsUsage runId: string threadId: string finalMessage: string @@ -320,6 +355,38 @@ export interface JsRunResult { finishedAtMs: number } +/** StreamDelta projection from the core event model. */ +export interface JsStreamDelta { + kind: string + text: string + index?: number +} + +/** TaskUpdate projection from the core event model. */ +export interface JsTaskUpdate { + description: string + summary: string + usage?: JsTaskUsage + kind: string + id: string + runId: string + toolUseId: string + status: string +} + +/** Counters reported on a task notification. */ +export interface JsTaskUsage { + durationMs: number + toolUses: number + totalTokens: number +} + +/** TodoStep projection from the core event model. */ +export interface JsTodoStep { + text: string + completed: boolean +} + /** Token usage reported by an agent. */ export interface JsUsage { inputTokens: number @@ -331,3 +398,30 @@ export interface JsUsage { totalCostUsd: number modelUsage: Record } + +/** WebSearch projection from the core event model. */ +export interface JsWebSearch { + query: string + action?: JsWebSearchAction + results?: Array +} + +/** WebSearchAction projection from the core event model. */ +export interface JsWebSearchAction { + kind: string + query?: string + queries: Array + url?: string + pattern?: string +} + +/** WebSearchResult projection from the core event model. */ +export interface JsWebSearchResult { + kind?: string + title?: string + url?: string + domain?: string + snippet?: string + refId?: string + raw: any +} diff --git a/bindings/node/index.d.ts b/bindings/node/index.d.ts index e4b073f..7060dce 100644 --- a/bindings/node/index.d.ts +++ b/bindings/node/index.d.ts @@ -54,6 +54,7 @@ export interface ConfigOverride { /** Per-model usage reported by an agent. */ export interface ModelUsage { + reasoningOutputTokens: number inputTokens: number outputTokens: number cacheReadInputTokens: number @@ -181,6 +182,72 @@ export interface AccountTokenUsageDailyBucket { tokens: string } +export interface StreamDelta { + kind: string + text: string + index?: number +} + +export interface TaskUsage { + durationMs: number + toolUses: number + totalTokens: number +} + +export interface TaskUpdate { + description: string + summary: string + usage?: TaskUsage + kind: string + id: string + runId: string + toolUseId: string + status: string +} + +export interface WebSearchAction { + kind: string + query?: string + queries: string[] + url?: string + pattern?: string +} + +export interface WebSearchResult { + kind?: string + title?: string + url?: string + domain?: string + snippet?: string + refId?: string + raw: unknown +} + +export interface WebSearch { + query: string + action?: WebSearchAction + results?: WebSearchResult[] +} + +export interface McpResult { + content: unknown[] + structuredContent?: unknown + meta?: unknown +} + +export interface McpCall { + server: string + tool: string + arguments?: unknown + result?: McpResult + error?: string +} + +export interface TodoStep { + text: string + completed: boolean +} + /** One file edit inside a `file_change` item. */ export interface FileChange { path: string @@ -189,6 +256,10 @@ export interface FileChange { /** A typed projection of an agent item. */ export interface Item { + phase?: string + webSearch?: WebSearch + mcp?: McpCall + todos?: TodoStep[] id: string type: string status: string @@ -206,14 +277,22 @@ export interface Item { /** One decoded agent event. */ export interface CodexEvent { + structuredOutput?: unknown + invocationUsage?: Usage + sessionUsage?: Usage + parentToolUseId: string + resultIndex?: number + failureReason: string + delta?: StreamDelta + task?: TaskUpdate type: string runId: string threadId: string /** The original JSON event text. */ raw: string - /** Set for `item.started` and `item.completed`. */ + /** Set for item start, update and completion events. */ item?: Item - /** Set for `turn.completed`. */ + /** Usage on completed and failed turns. */ usage?: Usage /** Set for `error` and `turn.failed`. */ error?: string @@ -221,6 +300,9 @@ export interface CodexEvent { /** Summary of a completed run. */ export interface RunResult { + structuredOutput?: unknown + invocationUsage?: Usage + sessionUsage?: Usage runId: string threadId: string finalMessage: string @@ -233,6 +315,8 @@ export interface RunResult { /** An agent run request. All fields are optional except prompt or stdin. */ export interface Request { + includePartialMessages?: boolean + forkId?: string prompt?: string stdin?: string dir?: string @@ -323,6 +407,7 @@ export type ErrorKind = /** A typed agent run error. */ export declare class CodexcwError extends Error { + failureReason?: string kind: ErrorKind /** Process exit code, for `exit` errors. */ code?: number diff --git a/bindings/node/index.js b/bindings/node/index.js index 34f7b48..4d8f865 100644 --- a/bindings/node/index.js +++ b/bindings/node/index.js @@ -30,6 +30,7 @@ class CodexcwError extends Error { this.name = 'CodexcwError' /** @type {string} */ this.kind = info.kind + if (info.failureReason) this.failureReason = info.failureReason if (info.code != null) this.code = info.code if (info.stderr != null) this.stderr = info.stderr if (info.line != null) this.line = info.line diff --git a/bindings/node/src/lib.rs b/bindings/node/src/lib.rs index 138fab6..fb41329 100644 --- a/bindings/node/src/lib.rs +++ b/bindings/node/src/lib.rs @@ -33,9 +33,94 @@ use codexcw::{ // Plain-object types crossing the FFI boundary. // --------------------------------------------------------------------------- +/// StreamDelta projection from the core event model. +#[napi(object)] +pub struct JsStreamDelta { + pub kind: String, + pub text: String, + pub index: Option, +} + +/// Counters reported on a task notification. +#[napi(object)] +pub struct JsTaskUsage { + pub duration_ms: i64, + pub tool_uses: i64, + pub total_tokens: i64, +} + +/// TaskUpdate projection from the core event model. +#[napi(object)] +pub struct JsTaskUpdate { + pub description: String, + pub summary: String, + pub usage: Option, + pub kind: String, + pub id: String, + pub run_id: String, + pub tool_use_id: String, + pub status: String, +} + +/// WebSearchAction projection from the core event model. +#[napi(object)] +pub struct JsWebSearchAction { + pub kind: String, + pub query: Option, + pub queries: Vec, + pub url: Option, + pub pattern: Option, +} + +/// WebSearchResult projection from the core event model. +#[napi(object)] +pub struct JsWebSearchResult { + pub kind: Option, + pub title: Option, + pub url: Option, + pub domain: Option, + pub snippet: Option, + pub ref_id: Option, + pub raw: serde_json::Value, +} + +/// WebSearch projection from the core event model. +#[napi(object)] +pub struct JsWebSearch { + pub query: String, + pub action: Option, + pub results: Option>, +} + +/// McpResult projection from the core event model. +#[napi(object)] +pub struct JsMcpResult { + pub content: Vec, + pub structured_content: Option, + pub meta: Option, +} + +/// McpCall projection from the core event model. +#[napi(object)] +pub struct JsMcpCall { + pub server: String, + pub tool: String, + pub arguments: Option, + pub result: Option, + pub error: Option, +} + +/// TodoStep projection from the core event model. +#[napi(object)] +pub struct JsTodoStep { + pub text: String, + pub completed: bool, +} + /// Per-model usage reported by an agent. #[napi(object)] pub struct JsModelUsage { + pub reasoning_output_tokens: i64, pub input_tokens: i64, pub output_tokens: i64, pub cache_read_input_tokens: i64, @@ -70,6 +155,10 @@ pub struct JsFileChange { /// A typed projection of an agent item. #[napi(object)] pub struct JsItem { + pub phase: Option, + pub web_search: Option, + pub mcp: Option, + pub todos: Option>, pub id: String, #[napi(js_name = "type")] pub kind: String, @@ -89,6 +178,14 @@ pub struct JsItem { /// One decoded agent event. #[napi(object)] pub struct JsEvent { + pub structured_output: Option, + pub invocation_usage: Option, + pub session_usage: Option, + pub parent_tool_use_id: String, + pub result_index: Option, + pub failure_reason: String, + pub delta: Option, + pub task: Option, #[napi(js_name = "type")] pub kind: String, pub run_id: String, @@ -103,6 +200,9 @@ pub struct JsEvent { #[napi(object)] #[derive(Default)] pub struct JsRunResult { + pub structured_output: Option, + pub invocation_usage: Option, + pub session_usage: Option, pub run_id: String, pub thread_id: String, pub final_message: String, @@ -116,6 +216,7 @@ pub struct JsRunResult { /// A typed run error. #[napi(object)] pub struct JsError { + pub failure_reason: Option, /// One of: `promptRequired`, `invalidRequest`, `exit`, `decode`, `codex`, /// `claude`, `grok`, `handler`, `cancelled`, `process`. pub kind: String, @@ -334,6 +435,8 @@ pub struct JsRequest { pub dangerously_bypass_sandbox: Option, pub dangerously_bypass_hooks: Option, pub env: Option>, + pub include_partial_messages: Option, + pub fork_id: Option, pub resume_id: Option, pub resume_last: Option, pub resume_all: Option, @@ -401,6 +504,7 @@ fn invalid_request(message: String) -> JsError { message, code: None, stderr: None, + failure_reason: None, line: None, } } @@ -452,6 +556,8 @@ fn to_core_request(req: JsRequest) -> Result { dangerously_bypass_sandbox: req.dangerously_bypass_sandbox.unwrap_or(false), dangerously_bypass_hooks: req.dangerously_bypass_hooks.unwrap_or(false), env: req.env.unwrap_or_default().into_iter().collect(), + fork_id: req.fork_id, + include_partial_messages: req.include_partial_messages.unwrap_or(false), resume_id: req.resume_id, resume_last: req.resume_last.unwrap_or(false), resume_all: req.resume_all.unwrap_or(false), @@ -528,6 +634,7 @@ fn to_js_usage(usage: &Usage) -> JsUsage { fn to_js_model_usage(usage: &CoreModelUsage) -> JsModelUsage { JsModelUsage { + reasoning_output_tokens: usage.reasoning_output_tokens, input_tokens: usage.input_tokens, output_tokens: usage.output_tokens, cache_read_input_tokens: usage.cache_read_input_tokens, @@ -539,8 +646,98 @@ fn to_js_model_usage(usage: &CoreModelUsage) -> JsModelUsage { } } +fn to_js_stream_delta(v: &codexcw::StreamDelta) -> JsStreamDelta { + JsStreamDelta { + kind: v.kind.clone(), + text: v.text.clone(), + index: v.index, + } +} + +fn to_js_task_update(v: &codexcw::TaskUpdate) -> JsTaskUpdate { + JsTaskUpdate { + description: v.description.clone(), + summary: v.summary.clone(), + usage: v.usage.as_ref().map(|usage| JsTaskUsage { + duration_ms: usage.duration_ms, + tool_uses: usage.tool_uses, + total_tokens: usage.total_tokens, + }), + kind: v.kind.clone(), + id: v.id.clone(), + run_id: v.run_id.clone(), + tool_use_id: v.tool_use_id.clone(), + status: v.status.clone(), + } +} + +fn to_js_web_search_action(v: &codexcw::WebSearchAction) -> JsWebSearchAction { + JsWebSearchAction { + kind: v.kind.clone(), + query: v.query.clone(), + queries: v.queries.clone(), + url: v.url.clone(), + pattern: v.pattern.clone(), + } +} + +fn to_js_web_search_result(v: &codexcw::WebSearchResult) -> JsWebSearchResult { + JsWebSearchResult { + kind: v.kind.clone(), + title: v.title.clone(), + url: v.url.clone(), + domain: v.domain.clone(), + snippet: v.snippet.clone(), + ref_id: v.ref_id.clone(), + raw: v.raw.clone(), + } +} + +fn to_js_web_search(v: &codexcw::WebSearch) -> JsWebSearch { + JsWebSearch { + query: v.query.clone(), + action: v.action.as_ref().map(to_js_web_search_action), + results: v + .results + .as_ref() + .map(|entries| entries.iter().map(to_js_web_search_result).collect()), + } +} + +fn to_js_mcp_result(v: &codexcw::McpResult) -> JsMcpResult { + JsMcpResult { + content: v.content.clone(), + structured_content: v.structured_content.clone(), + meta: v.meta.clone(), + } +} + +fn to_js_mcp_call(v: &codexcw::McpCall) -> JsMcpCall { + JsMcpCall { + server: v.server.clone(), + tool: v.tool.clone(), + arguments: v.arguments.clone(), + result: v.result.as_ref().map(to_js_mcp_result), + error: v.error.clone(), + } +} + +fn to_js_todo_step(v: &codexcw::TodoStep) -> JsTodoStep { + JsTodoStep { + text: v.text.clone(), + completed: v.completed, + } +} + fn to_js_item(item: &Item) -> JsItem { JsItem { + phase: item.phase.clone(), + web_search: item.web_search.as_ref().map(to_js_web_search), + mcp: item.mcp.as_ref().map(to_js_mcp_call), + todos: item + .todos + .as_ref() + .map(|entries| entries.iter().map(to_js_todo_step).collect()), id: item.id.clone(), kind: item.kind.as_str().to_string(), status: item.status.clone(), @@ -569,7 +766,9 @@ fn to_js_event(event: &Event) -> JsEvent { let mut usage = None; let mut error = None; match &event.payload { - EventPayload::ItemStarted(i) | EventPayload::ItemCompleted(i) => item = Some(to_js_item(i)), + EventPayload::ItemStarted(i) + | EventPayload::ItemUpdated(i) + | EventPayload::ItemCompleted(i) => item = Some(to_js_item(i)), EventPayload::TurnCompleted { usage: u } => usage = Some(to_js_usage(u)), EventPayload::TurnFailed { error: e, usage: u } => { error = Some(e.message.clone()); @@ -579,6 +778,14 @@ fn to_js_event(event: &Event) -> JsEvent { _ => {} } JsEvent { + structured_output: event.structured_output.clone(), + invocation_usage: event.invocation_usage.as_ref().map(to_js_usage), + session_usage: event.session_usage.as_ref().map(to_js_usage), + parent_tool_use_id: event.parent_tool_use_id.clone(), + result_index: event.result_index, + failure_reason: event.failure_reason.clone(), + delta: event.delta.as_ref().map(to_js_stream_delta), + task: event.task.as_ref().map(to_js_task_update), kind: event.kind.as_str().to_string(), run_id: event.run_id.clone(), thread_id: event.thread_id.clone(), @@ -591,6 +798,9 @@ fn to_js_event(event: &Event) -> JsEvent { fn to_js_result(result: &RunResult) -> JsRunResult { JsRunResult { + structured_output: result.structured_output.clone(), + invocation_usage: result.invocation_usage.as_ref().map(to_js_usage), + session_usage: result.session_usage.as_ref().map(to_js_usage), run_id: result.run_id.clone(), thread_id: result.thread_id.clone(), final_message: result.final_message.clone(), @@ -610,6 +820,7 @@ fn to_js_error(error: &codexcw::Error) -> JsError { message: error.to_string(), code: None, stderr: None, + failure_reason: None, line: None, }, InvalidRequest(_) => invalid_request(error.to_string()), @@ -622,6 +833,7 @@ fn to_js_error(error: &codexcw::Error) -> JsError { message: error.to_string(), code: Some(*code), stderr: Some(stderr.clone()), + failure_reason: None, line: None, }, Decode { line, .. } => JsError { @@ -629,27 +841,34 @@ fn to_js_error(error: &codexcw::Error) -> JsError { message: error.to_string(), code: None, stderr: None, + failure_reason: None, line: Some(*line as u32), }, - Codex { .. } => JsError { + Codex { event, .. } => JsError { kind: "codex".to_string(), message: error.to_string(), code: None, stderr: None, + failure_reason: (!event.failure_reason.is_empty()) + .then(|| event.failure_reason.clone()), line: None, }, - Claude { .. } => JsError { + Claude { event, .. } => JsError { kind: "claude".to_string(), message: error.to_string(), code: None, stderr: None, + failure_reason: (!event.failure_reason.is_empty()) + .then(|| event.failure_reason.clone()), line: None, }, - Grok { .. } => JsError { + Grok { event, .. } => JsError { kind: "grok".to_string(), message: error.to_string(), code: None, stderr: None, + failure_reason: (!event.failure_reason.is_empty()) + .then(|| event.failure_reason.clone()), line: None, }, Handler(_) => JsError { @@ -657,6 +876,7 @@ fn to_js_error(error: &codexcw::Error) -> JsError { message: error.to_string(), code: None, stderr: None, + failure_reason: None, line: None, }, Cancelled => JsError { @@ -664,6 +884,7 @@ fn to_js_error(error: &codexcw::Error) -> JsError { message: error.to_string(), code: None, stderr: None, + failure_reason: None, line: None, }, Process(_) => JsError { @@ -671,6 +892,7 @@ fn to_js_error(error: &codexcw::Error) -> JsError { message: error.to_string(), code: None, stderr: None, + failure_reason: None, line: None, }, } @@ -935,6 +1157,7 @@ fn clone_js_error(error: &JsError) -> JsError { message: error.message.clone(), code: error.code, stderr: error.stderr.clone(), + failure_reason: error.failure_reason.clone(), line: error.line, } } diff --git a/bindings/python/Cargo.toml b/bindings/python/Cargo.toml index 8a4426e..e3d971b 100644 --- a/bindings/python/Cargo.toml +++ b/bindings/python/Cargo.toml @@ -13,6 +13,7 @@ name = "_codexcw" crate-type = ["cdylib"] [dependencies] +serde_json.workspace = true codexcw.workspace = true pyo3 = { version = "0.29", features = ["extension-module", "abi3-py39"] } tokio.workspace = true diff --git a/bindings/python/python/codexcw/__init__.py b/bindings/python/python/codexcw/__init__.py index 3ca9d5c..8386634 100644 --- a/bindings/python/python/codexcw/__init__.py +++ b/bindings/python/python/codexcw/__init__.py @@ -34,6 +34,15 @@ from ._codexcw import PyClaudeAccountUsageWindow as ClaudeAccountUsageWindow from ._codexcw import PyEvent as Event from ._codexcw import PyFileChange as FileChange +from ._codexcw import PyStreamDelta as StreamDelta +from ._codexcw import PyTaskUsage as TaskUsage +from ._codexcw import PyTaskUpdate as TaskUpdate +from ._codexcw import PyWebSearchAction as WebSearchAction +from ._codexcw import PyWebSearchResult as WebSearchResult +from ._codexcw import PyWebSearch as WebSearch +from ._codexcw import PyMcpResult as McpResult +from ._codexcw import PyMcpCall as McpCall +from ._codexcw import PyTodoStep as TodoStep from ._codexcw import PyItem as Item from ._codexcw import PyModelUsage as ModelUsage from ._codexcw import PyRunEvent as RunEvent @@ -77,6 +86,15 @@ "FileChange", "Group", "GroupResult", + "StreamDelta", + "TaskUpdate", + "TaskUsage", + "WebSearchAction", + "WebSearchResult", + "WebSearch", + "McpResult", + "McpCall", + "TodoStep", "Item", "ModelUsage", "Request", @@ -137,6 +155,7 @@ class CodexcwError(Exception): def __init__(self, info: "_codexcw.PyError") -> None: super().__init__(info.message) self.kind: str = info.kind + self.failure_reason: Optional[str] = info.failure_reason self.code: Optional[int] = info.code self.stderr: Optional[str] = info.stderr self.line: Optional[int] = info.line @@ -157,6 +176,7 @@ def _account_usage_or_raise(outcome): message="account usage result missing", code=None, stderr=None, + failure_reason=None, line=None, ) ) @@ -248,6 +268,8 @@ class Request: # unchecked; the grok agent receives --reasoning-effort. Appended last to keep positional # construction of earlier fields stable. effort: Optional[str] = None + include_partial_messages: bool = False + fork_id: Optional[str] = None @dataclass @@ -332,6 +354,7 @@ def __init__( message=f"unknown agent: {agent}", code=None, stderr=None, + failure_reason=None, line=None, ) ) diff --git a/bindings/python/python/codexcw/_codexcw.pyi b/bindings/python/python/codexcw/_codexcw.pyi index 70051e6..146cbef 100644 --- a/bindings/python/python/codexcw/_codexcw.pyi +++ b/bindings/python/python/codexcw/_codexcw.pyi @@ -3,6 +3,7 @@ from typing import Iterator, List, Optional class PyModelUsage: + reasoning_output_tokens: int input_tokens: int output_tokens: int cache_read_input_tokens: int @@ -22,11 +23,72 @@ class PyUsage: total_cost_usd: float model_usage: dict[str, PyModelUsage] +class PyStreamDelta: + kind: str + text: str + index: Optional[int] + +class PyTaskUsage: + duration_ms: int + tool_uses: int + total_tokens: int + +class PyTaskUpdate: + description: str + summary: str + usage: Optional[PyTaskUsage] + kind: str + id: str + run_id: str + tool_use_id: str + status: str + +class PyWebSearchAction: + kind: str + query: Optional[str] + queries: List[str] + url: Optional[str] + pattern: Optional[str] + +class PyWebSearchResult: + kind: Optional[str] + title: Optional[str] + url: Optional[str] + domain: Optional[str] + snippet: Optional[str] + ref_id: Optional[str] + raw: object + +class PyWebSearch: + query: str + action: Optional[PyWebSearchAction] + results: Optional[List[PyWebSearchResult]] + +class PyMcpResult: + content: List[object] + structured_content: Optional[object] + meta: Optional[object] + +class PyMcpCall: + server: str + tool: str + arguments: Optional[object] + result: Optional[PyMcpResult] + error: Optional[str] + +class PyTodoStep: + text: str + completed: bool + class PyFileChange: path: str kind: str class PyItem: + phase: Optional[str] + web_search: Optional[PyWebSearch] + mcp: Optional[PyMcpCall] + todos: Optional[List[PyTodoStep]] id: str type: str status: str @@ -42,6 +104,14 @@ class PyItem: receiver_thread_ids: List[str] class PyEvent: + structured_output: Optional[object] + invocation_usage: Optional[PyUsage] + session_usage: Optional[PyUsage] + parent_tool_use_id: str + result_index: Optional[int] + failure_reason: str + delta: Optional[PyStreamDelta] + task: Optional[PyTaskUpdate] type: str run_id: str thread_id: str @@ -51,6 +121,9 @@ class PyEvent: error: Optional[str] class PyRunResult: + structured_output: Optional[object] + invocation_usage: Optional[PyUsage] + session_usage: Optional[PyUsage] run_id: str thread_id: str final_message: str @@ -61,6 +134,7 @@ class PyRunResult: finished_at_ms: float class PyError: + failure_reason: Optional[str] kind: str message: str code: Optional[int] diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index e1f1c33..1b0cd22 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -44,10 +44,205 @@ fn runtime() -> &'static Runtime { // Output value types. // --------------------------------------------------------------------------- +/// StreamDelta projection from the core event model. +#[pyclass(frozen, skip_from_py_object)] +#[derive(Clone)] +pub struct PyStreamDelta { + #[pyo3(get)] + kind: String, + #[pyo3(get)] + text: String, + #[pyo3(get)] + index: Option, +} + +/// Counters reported on a task notification. +#[pyclass(frozen, skip_from_py_object)] +#[derive(Clone)] +pub struct PyTaskUsage { + #[pyo3(get)] + duration_ms: i64, + #[pyo3(get)] + tool_uses: i64, + #[pyo3(get)] + total_tokens: i64, +} + +/// TaskUpdate projection from the core event model. +#[pyclass(frozen, skip_from_py_object)] +#[derive(Clone)] +pub struct PyTaskUpdate { + #[pyo3(get)] + description: String, + #[pyo3(get)] + summary: String, + #[pyo3(get)] + usage: Option, + #[pyo3(get)] + kind: String, + #[pyo3(get)] + id: String, + #[pyo3(get)] + run_id: String, + #[pyo3(get)] + tool_use_id: String, + #[pyo3(get)] + status: String, +} + +/// WebSearchAction projection from the core event model. +#[pyclass(frozen, skip_from_py_object)] +#[derive(Clone)] +pub struct PyWebSearchAction { + #[pyo3(get)] + kind: String, + #[pyo3(get)] + query: Option, + #[pyo3(get)] + queries: Vec, + #[pyo3(get)] + url: Option, + #[pyo3(get)] + pattern: Option, +} + +/// WebSearchResult projection from the core event model. +#[pyclass(frozen, skip_from_py_object)] +#[derive(Clone)] +pub struct PyWebSearchResult { + #[pyo3(get)] + kind: Option, + #[pyo3(get)] + title: Option, + #[pyo3(get)] + url: Option, + #[pyo3(get)] + domain: Option, + #[pyo3(get)] + snippet: Option, + #[pyo3(get)] + ref_id: Option, + raw: serde_json::Value, +} + +#[pymethods] +impl PyWebSearchResult { + #[getter] + fn raw(&self, py: Python<'_>) -> PyResult> { + decode_json(py, self.raw.to_string()) + } +} + +/// WebSearch projection from the core event model. +#[pyclass(frozen, skip_from_py_object)] +#[derive(Clone)] +pub struct PyWebSearch { + #[pyo3(get)] + query: String, + #[pyo3(get)] + action: Option, + #[pyo3(get)] + results: Option>, +} + +/// McpResult projection from the core event model. +#[pyclass(frozen, skip_from_py_object)] +#[derive(Clone)] +pub struct PyMcpResult { + content: Vec, + structured_content: Option, + meta: Option, +} + +#[pymethods] +impl PyMcpResult { + #[getter] + fn content(&self, py: Python<'_>) -> PyResult> { + decode_json( + py, + serde_json::to_string(&self.content).expect("JSON value serialization"), + ) + } + #[getter] + fn structured_content(&self, py: Python<'_>) -> PyResult> { + let Some(value) = &self.structured_content else { + return Ok(py.None()); + }; + decode_json(py, value.to_string()) + } + #[getter] + fn meta(&self, py: Python<'_>) -> PyResult> { + let Some(value) = &self.meta else { + return Ok(py.None()); + }; + decode_json(py, value.to_string()) + } +} + +/// McpCall projection from the core event model. +#[pyclass(frozen, skip_from_py_object)] +#[derive(Clone)] +pub struct PyMcpCall { + #[pyo3(get)] + server: String, + #[pyo3(get)] + tool: String, + arguments: Option, + #[pyo3(get)] + result: Option, + #[pyo3(get)] + error: Option, +} + +#[pymethods] +impl PyMcpCall { + #[getter] + fn arguments(&self, py: Python<'_>) -> PyResult> { + let Some(value) = &self.arguments else { + return Ok(py.None()); + }; + decode_json(py, value.to_string()) + } +} + +/// TodoStep projection from the core event model. +#[pyclass(frozen, skip_from_py_object)] +#[derive(Clone)] +pub struct PyTodoStep { + #[pyo3(get)] + text: String, + #[pyo3(get)] + completed: bool, +} + +#[pymethods] +impl PyRunResult { + #[getter] + fn structured_output(&self, py: Python<'_>) -> PyResult> { + let Some(value) = &self.structured_output else { + return Ok(py.None()); + }; + decode_json(py, value.to_string()) + } +} + +#[pymethods] +impl PyEvent { + #[getter] + fn structured_output(&self, py: Python<'_>) -> PyResult> { + let Some(value) = &self.structured_output else { + return Ok(py.None()); + }; + decode_json(py, value.to_string()) + } +} + /// Per-model usage reported by an agent. #[pyclass(frozen, skip_from_py_object)] #[derive(Clone)] pub struct PyModelUsage { + #[pyo3(get)] + reasoning_output_tokens: i64, #[pyo3(get)] input_tokens: i64, #[pyo3(get)] @@ -102,6 +297,14 @@ pub struct PyFileChange { #[pyclass(frozen, skip_from_py_object)] #[derive(Clone)] pub struct PyItem { + #[pyo3(get)] + phase: Option, + #[pyo3(get)] + web_search: Option, + #[pyo3(get)] + mcp: Option, + #[pyo3(get)] + todos: Option>, #[pyo3(get)] id: String, #[pyo3(get, name = "type")] @@ -134,6 +337,21 @@ pub struct PyItem { #[pyclass(frozen, skip_from_py_object)] #[derive(Clone)] pub struct PyEvent { + structured_output: Option, + #[pyo3(get)] + invocation_usage: Option, + #[pyo3(get)] + session_usage: Option, + #[pyo3(get)] + parent_tool_use_id: String, + #[pyo3(get)] + result_index: Option, + #[pyo3(get)] + failure_reason: String, + #[pyo3(get)] + delta: Option, + #[pyo3(get)] + task: Option, #[pyo3(get, name = "type")] kind: String, #[pyo3(get)] @@ -154,6 +372,11 @@ pub struct PyEvent { #[pyclass(frozen, skip_from_py_object)] #[derive(Clone, Default)] pub struct PyRunResult { + structured_output: Option, + #[pyo3(get)] + invocation_usage: Option, + #[pyo3(get)] + session_usage: Option, #[pyo3(get)] run_id: String, #[pyo3(get)] @@ -176,6 +399,8 @@ pub struct PyRunResult { #[pyclass(frozen, skip_from_py_object)] #[derive(Clone)] pub struct PyError { + #[pyo3(get)] + failure_reason: Option, #[pyo3(get)] kind: String, #[pyo3(get)] @@ -438,6 +663,8 @@ struct ReqData { dangerously_bypass_sandbox: Option, dangerously_bypass_hooks: Option, env: Option>, + include_partial_messages: Option, + fork_id: Option, resume_id: Option, resume_last: Option, resume_all: Option, @@ -491,6 +718,8 @@ impl ReqData { dangerously_bypass_sandbox: self.dangerously_bypass_sandbox.unwrap_or(false), dangerously_bypass_hooks: self.dangerously_bypass_hooks.unwrap_or(false), env: self.env.unwrap_or_default().into_iter().collect(), + fork_id: self.fork_id, + include_partial_messages: self.include_partial_messages.unwrap_or(false), resume_id: self.resume_id, resume_last: self.resume_last.unwrap_or(false), resume_all: self.resume_all.unwrap_or(false), @@ -584,6 +813,7 @@ fn invalid_request(message: String) -> PyError { message, code: None, stderr: None, + failure_reason: None, line: None, } } @@ -606,6 +836,10 @@ fn parse_account_usage_timeout(timeout: f64) -> Result { }) } +fn decode_json(py: Python<'_>, text: String) -> PyResult> { + Ok(py.import("json")?.call_method1("loads", (text,))?.unbind()) +} + fn to_py_usage(usage: &Usage) -> PyUsage { PyUsage { input_tokens: usage.input_tokens, @@ -625,6 +859,7 @@ fn to_py_usage(usage: &Usage) -> PyUsage { fn to_py_model_usage(usage: &CoreModelUsage) -> PyModelUsage { PyModelUsage { + reasoning_output_tokens: usage.reasoning_output_tokens, input_tokens: usage.input_tokens, output_tokens: usage.output_tokens, cache_read_input_tokens: usage.cache_read_input_tokens, @@ -636,8 +871,98 @@ fn to_py_model_usage(usage: &CoreModelUsage) -> PyModelUsage { } } +fn to_py_stream_delta(v: &codexcw::StreamDelta) -> PyStreamDelta { + PyStreamDelta { + kind: v.kind.clone(), + text: v.text.clone(), + index: v.index, + } +} + +fn to_py_task_update(v: &codexcw::TaskUpdate) -> PyTaskUpdate { + PyTaskUpdate { + description: v.description.clone(), + summary: v.summary.clone(), + usage: v.usage.as_ref().map(|usage| PyTaskUsage { + duration_ms: usage.duration_ms, + tool_uses: usage.tool_uses, + total_tokens: usage.total_tokens, + }), + kind: v.kind.clone(), + id: v.id.clone(), + run_id: v.run_id.clone(), + tool_use_id: v.tool_use_id.clone(), + status: v.status.clone(), + } +} + +fn to_py_web_search_action(v: &codexcw::WebSearchAction) -> PyWebSearchAction { + PyWebSearchAction { + kind: v.kind.clone(), + query: v.query.clone(), + queries: v.queries.clone(), + url: v.url.clone(), + pattern: v.pattern.clone(), + } +} + +fn to_py_web_search_result(v: &codexcw::WebSearchResult) -> PyWebSearchResult { + PyWebSearchResult { + kind: v.kind.clone(), + title: v.title.clone(), + url: v.url.clone(), + domain: v.domain.clone(), + snippet: v.snippet.clone(), + ref_id: v.ref_id.clone(), + raw: v.raw.clone(), + } +} + +fn to_py_web_search(v: &codexcw::WebSearch) -> PyWebSearch { + PyWebSearch { + query: v.query.clone(), + action: v.action.as_ref().map(to_py_web_search_action), + results: v + .results + .as_ref() + .map(|entries| entries.iter().map(to_py_web_search_result).collect()), + } +} + +fn to_py_mcp_result(v: &codexcw::McpResult) -> PyMcpResult { + PyMcpResult { + content: v.content.clone(), + structured_content: v.structured_content.clone(), + meta: v.meta.clone(), + } +} + +fn to_py_mcp_call(v: &codexcw::McpCall) -> PyMcpCall { + PyMcpCall { + server: v.server.clone(), + tool: v.tool.clone(), + arguments: v.arguments.clone(), + result: v.result.as_ref().map(to_py_mcp_result), + error: v.error.clone(), + } +} + +fn to_py_todo_step(v: &codexcw::TodoStep) -> PyTodoStep { + PyTodoStep { + text: v.text.clone(), + completed: v.completed, + } +} + fn to_py_item(item: &Item) -> PyItem { PyItem { + phase: item.phase.clone(), + web_search: item.web_search.as_ref().map(to_py_web_search), + mcp: item.mcp.as_ref().map(to_py_mcp_call), + todos: item + .todos + .as_ref() + .map(|entries| entries.iter().map(to_py_todo_step).collect()), id: item.id.clone(), kind: item.kind.as_str().to_string(), status: item.status.clone(), @@ -666,7 +991,9 @@ fn to_py_event(event: &Event) -> PyEvent { let mut usage = None; let mut error = None; match &event.payload { - EventPayload::ItemStarted(i) | EventPayload::ItemCompleted(i) => item = Some(to_py_item(i)), + EventPayload::ItemStarted(i) + | EventPayload::ItemUpdated(i) + | EventPayload::ItemCompleted(i) => item = Some(to_py_item(i)), EventPayload::TurnCompleted { usage: u } => usage = Some(to_py_usage(u)), EventPayload::TurnFailed { error: e, usage: u } => { error = Some(e.message.clone()); @@ -676,6 +1003,14 @@ fn to_py_event(event: &Event) -> PyEvent { _ => {} } PyEvent { + structured_output: event.structured_output.clone(), + invocation_usage: event.invocation_usage.as_ref().map(to_py_usage), + session_usage: event.session_usage.as_ref().map(to_py_usage), + parent_tool_use_id: event.parent_tool_use_id.clone(), + result_index: event.result_index, + failure_reason: event.failure_reason.clone(), + delta: event.delta.as_ref().map(to_py_stream_delta), + task: event.task.as_ref().map(to_py_task_update), kind: event.kind.as_str().to_string(), run_id: event.run_id.clone(), thread_id: event.thread_id.clone(), @@ -688,6 +1023,9 @@ fn to_py_event(event: &Event) -> PyEvent { fn to_py_result(result: &RunResult) -> PyRunResult { PyRunResult { + structured_output: result.structured_output.clone(), + invocation_usage: result.invocation_usage.as_ref().map(to_py_usage), + session_usage: result.session_usage.as_ref().map(to_py_usage), run_id: result.run_id.clone(), thread_id: result.thread_id.clone(), final_message: result.final_message.clone(), @@ -707,6 +1045,7 @@ fn to_py_error(error: &codexcw::Error) -> PyError { message: error.to_string(), code: None, stderr: None, + failure_reason: None, line: None, }, InvalidRequest(_) => invalid_request(error.to_string()), @@ -715,6 +1054,7 @@ fn to_py_error(error: &codexcw::Error) -> PyError { message: error.to_string(), code: Some(*code), stderr: Some(stderr.clone()), + failure_reason: None, line: None, }, Decode { line, .. } => PyError { @@ -722,27 +1062,34 @@ fn to_py_error(error: &codexcw::Error) -> PyError { message: error.to_string(), code: None, stderr: None, + failure_reason: None, line: Some(*line as u32), }, - Codex { .. } => PyError { + Codex { event, .. } => PyError { kind: "codex".to_string(), message: error.to_string(), code: None, stderr: None, + failure_reason: (!event.failure_reason.is_empty()) + .then(|| event.failure_reason.clone()), line: None, }, - Claude { .. } => PyError { + Claude { event, .. } => PyError { kind: "claude".to_string(), message: error.to_string(), code: None, stderr: None, + failure_reason: (!event.failure_reason.is_empty()) + .then(|| event.failure_reason.clone()), line: None, }, - Grok { .. } => PyError { + Grok { event, .. } => PyError { kind: "grok".to_string(), message: error.to_string(), code: None, stderr: None, + failure_reason: (!event.failure_reason.is_empty()) + .then(|| event.failure_reason.clone()), line: None, }, Handler(_) => PyError { @@ -750,6 +1097,7 @@ fn to_py_error(error: &codexcw::Error) -> PyError { message: error.to_string(), code: None, stderr: None, + failure_reason: None, line: None, }, Cancelled => PyError { @@ -757,6 +1105,7 @@ fn to_py_error(error: &codexcw::Error) -> PyError { message: error.to_string(), code: None, stderr: None, + failure_reason: None, line: None, }, Process(_) => PyError { @@ -764,6 +1113,7 @@ fn to_py_error(error: &codexcw::Error) -> PyError { message: error.to_string(), code: None, stderr: None, + failure_reason: None, line: None, }, } @@ -1299,6 +1649,15 @@ fn _codexcw(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; diff --git a/bindings/python/tests/test_smoke.py b/bindings/python/tests/test_smoke.py index 4f1b8e9..7794569 100644 --- a/bindings/python/tests/test_smoke.py +++ b/bindings/python/tests/test_smoke.py @@ -643,3 +643,57 @@ def test_live_get_account_usage_and_fast_mode(tmp_path): ) assert "OK" in result.final_message.upper() + + +def test_replay_agent_stream_contracts(): + fixtures = Path(__file__).resolve().parents[3] / "crates/codexcw/tests/fixtures/streams" + + def replay(agent, flag, **options): + runner = Runner( + agent=agent, + executable=str(fixtures / "replay.sh"), + env={"STREAM_FIXTURE": str(fixtures / (agent + ".jsonl")), "EXPECT_FLAG": flag}, + ) + return runner.run(Request(prompt="replay", **options)) + + codex = replay("codex", "fork", fork_id="previous") + assert codex.final_message == "DONE" + assert codex.invocation_usage is None + assert codex.session_usage.cache_creation_input_tokens == 3 + assert next(e.item for e in codex.events if e.type == "item.updated").todos[0].completed + mcp = next(e.item.mcp for e in codex.events if e.item and e.item.id == "mcp") + assert mcp.result.structured_content == {"color": "GOLD"} + searches = [e.item.web_search for e in codex.events if e.item and e.item.web_search] + assert searches[0].results is None + assert searches[1].results[0].title == "Example" + assert searches[2].results == [] + + claude = replay("claude", "--include-partial-messages", include_partial_messages=True) + assert claude.final_message == "finished" + assert claude.structured_output == {"ok": True} + assert claude.invocation_usage.total_tokens == 24 + assert claude.session_usage.total_tokens == 84 + assert any(e.delta for e in claude.events) + assert claude.events[-1].structured_output is None + assert [e.item.text for e in claude.events if e.item and e.item.type == "agent_message"] == [ + "waiting", "child answer", "finished", + ] + task = next(e.task for e in claude.events if e.task and e.task.usage) + assert task.summary == "Sample checked" + assert (task.usage.duration_ms, task.usage.tool_uses, task.usage.total_tokens) == (120, 2, 17) + + grok = replay("grok", "--include-partial-messages", include_partial_messages=True) + assert next(e.item for e in grok.events if e.item and e.item.exit_code == 7).status == "failed" + assert grok.structured_output == {"ok": True} + + +def test_claude_failure_reason_without_init(): + fixtures = Path(__file__).resolve().parents[3] / "crates/codexcw/tests/fixtures/streams" + runner = Runner( + agent="claude", + executable=str(fixtures / "replay.sh"), + env={"STREAM_FIXTURE": str(fixtures / "startup-failure.jsonl"), "STREAM_EXIT": "1"}, + ) + with pytest.raises(CodexcwError) as caught: + runner.run(Request(prompt="test", resume_id="missing")) + assert caught.value.failure_reason == "resume_target_not_found" diff --git a/claude.go b/claude.go index 119b3d4..fe34df8 100644 --- a/claude.go +++ b/claude.go @@ -62,6 +62,9 @@ func (r *Runner) prepareClaude(req Request) (_ []string, _ io.Reader, cleanup fu } args := []string{"-p", "--output-format", "stream-json", "--verbose"} + if req.IncludePartialMessages { + args = append(args, "--include-partial-messages") + } if req.Model != "" { args = append(args, "--model", req.Model) } @@ -128,6 +131,7 @@ func validateClaudeRequest(req Request) error { {req.RequireGitRepo, "require git repo"}, {req.OutputLastMessagePath != "", "output last message path"}, {req.DangerouslyBypassHooks, "dangerously bypass hooks"}, + {req.ForkID != "", "fork id"}, {req.ResumeAll, "resume all"}, } for _, field := range unsupported { @@ -143,14 +147,24 @@ func validateClaudeRequest(req Request) error { type claudeEventDecoder struct { agent Agent pending map[string]Item - lastAgentText string + deliveredText map[claudeMessageText]bool blockSequences map[string]uint64 + invocation Usage + seenResults map[int]bool +} + +// Result frames can replay a message from before the latest assistant block. +type claudeMessageText struct { + parentToolUseID string + text string } func newClaudeEventDecoder() *claudeEventDecoder { return &claudeEventDecoder{ agent: AgentClaude, + seenResults: make(map[int]bool), pending: make(map[string]Item), + deliveredText: make(map[claudeMessageText]bool), blockSequences: make(map[string]uint64), } } @@ -159,11 +173,27 @@ func newGrokEventDecoder() *claudeEventDecoder { return &claudeEventDecoder{ agent: AgentGrok, pending: make(map[string]Item), + deliveredText: make(map[claudeMessageText]bool), blockSequences: make(map[string]uint64), } } type claudeWireEvent struct { + Description string `json:"description"` + Summary string `json:"summary"` + ParentToolUseID string `json:"parent_tool_use_id"` + ResultIndex *int `json:"result_index"` + DeltaEvent json.RawMessage `json:"event"` + TaskID string `json:"task_id"` + RunID string `json:"run_id"` + ToolUseID string `json:"tool_use_id"` + Status json.RawMessage `json:"status"` + TaskPatch json.RawMessage `json:"patch"` + StructuredOutput json.RawMessage `json:"structured_output"` + StartupFailureReason string `json:"startup_failure_reason"` + TerminalReason string `json:"terminal_reason"` + ModelUsageDelta map[string]claudeWireModelUsage `json:"model_usage_since_last_result"` + Type string `json:"type"` Subtype string `json:"subtype"` SessionID string `json:"session_id"` @@ -171,7 +201,7 @@ type claudeWireEvent struct { IsError bool `json:"is_error"` Result string `json:"result"` Errors []string `json:"errors"` - Usage claudeWireUsage `json:"usage"` + Usage *claudeWireUsage `json:"usage"` TotalCostUSD float64 `json:"total_cost_usd"` ModelUsage map[string]claudeWireModelUsage `json:"modelUsage"` ToolUseResult json.RawMessage `json:"tool_use_result"` @@ -195,6 +225,10 @@ type claudeWireBlock struct { } type claudeWireUsage struct { + TaskUsage + OutputDetails struct { + ThinkingTokens int64 `json:"thinking_tokens"` + } `json:"output_tokens_details"` InputTokens int64 `json:"input_tokens"` CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"` CacheReadInputTokens int64 `json:"cache_read_input_tokens"` @@ -202,6 +236,7 @@ type claudeWireUsage struct { } type claudeWireModelUsage struct { + ReasoningOutputTokens int64 `json:"thinkingTokens"` InputTokens int64 `json:"inputTokens"` OutputTokens int64 `json:"outputTokens"` CacheReadInputTokens int64 `json:"cacheReadInputTokens"` @@ -223,13 +258,32 @@ func (d *claudeEventDecoder) decode(line []byte, runID, threadID string, now tim return nil, fmt.Errorf("missing event type") } - base := Event{RunID: runID, ThreadID: threadID, ReceivedAt: now, Raw: raw} + base := Event{RunID: runID, ThreadID: threadID, ReceivedAt: now, Raw: raw, ParentToolUseID: wire.ParentToolUseID} if wire.SessionID != "" { base.ThreadID = wire.SessionID } switch wire.Type { + case "stream_event": + base.Delta = claudeStreamDelta(wire.DeltaEvent) + return []Event{claudePassthrough(base, wire.Type)}, nil case "system": + if strings.HasPrefix(wire.Subtype, "task_") { + var status string + _ = json.Unmarshal(wire.Status, &status) + if status == "" { + var patch struct{ Status string } + _ = json.Unmarshal(wire.TaskPatch, &patch) + status = patch.Status + } + base.Task = &TaskUpdate{ + Kind: wire.Subtype, ID: wire.TaskID, RunID: wire.RunID, ToolUseID: wire.ToolUseID, + Status: status, Description: wire.Description, Summary: wire.Summary, + } + if wire.Usage != nil { + base.Task.Usage = &wire.Usage.TaskUsage + } + } if wire.Subtype != "init" { return []Event{claudePassthrough(base, wire.Type)}, nil } @@ -251,6 +305,37 @@ func (d *claudeEventDecoder) decode(line []byte, runID, threadID string, now tim } } +func claudeStreamDelta(raw json.RawMessage) *StreamDelta { + var stream struct { + Type string + Index *int + Delta struct { + Type, Text, Thinking, Signature string + PartialJSON string `json:"partial_json"` + } + } + if json.Unmarshal(raw, &stream) == nil && stream.Type != "" { + delta := stream.Delta + var text string + switch delta.Type { + case "text_delta": + text = delta.Text + case "thinking_delta": + text = delta.Thinking + case "signature_delta": + text = delta.Signature + case "input_json_delta": + text = delta.PartialJSON + } + kind := stream.Type + if stream.Type == "content_block_delta" && delta.Type != "" { + kind = delta.Type + } + return &StreamDelta{Kind: kind, Text: text, Index: stream.Index} + } + return nil +} + func (d *claudeEventDecoder) decodeAssistant(base Event, wire *claudeWireEvent) ([]Event, error) { var events []Event for _, rawBlock := range claudeContentBlocks(wire.Message) { @@ -260,7 +345,7 @@ func (d *claudeEventDecoder) decodeAssistant(base Event, wire *claudeWireEvent) } switch block.Type { case "text": - d.lastAgentText = block.Text + d.deliveredText[claudeMessageText{wire.ParentToolUseID, block.Text}] = true events = append(events, claudeItemCompleted(base, Item{ ID: d.claudeBlockID(wire.Message.ID), Type: ItemAgentMessage, @@ -328,6 +413,9 @@ func (d *claudeEventDecoder) decodeUser(base Event, wire *claudeWireEvent) ([]Ev } if item.Type == ItemCommandExecution { item.ExitCode = claudeCommandExitCode(block.Content, wire.ToolUseResult, d.agent) + if d.agent == AgentGrok && item.ExitCode != nil && *item.ExitCode != 0 { + item.Status = "failed" + } if item.ExitCode == nil && !block.IsError { exitCode := 0 item.ExitCode = &exitCode @@ -353,7 +441,36 @@ func (d *claudeEventDecoder) decodeUser(base Event, wire *claudeWireEvent) ([]Ev func (d *claudeEventDecoder) decodeResult(base Event, wire *claudeWireEvent) []Event { usage := claudeResultUsage(wire) + base.ResultIndex = wire.ResultIndex + base.StructuredOutput = optionalJSON(wire.StructuredOutput) + if d.agent == AgentGrok && (wire.Usage != nil || wire.ModelUsage != nil) { + base.InvocationUsage = &usage + } + if d.agent == AgentClaude { + if wire.ModelUsage != nil { + session := modelTotals(wire.ModelUsage, nil) + session.TotalCostUSD = wire.TotalCostUSD + base.SessionUsage = &session + } + if wire.ModelUsageDelta != nil { + if wire.ResultIndex == nil || !d.seenResults[*wire.ResultIndex] { + d.invocation = modelTotals(wire.ModelUsageDelta, d.invocation.ModelUsage) + if wire.ResultIndex != nil { + d.seenResults[*wire.ResultIndex] = true + } + } + snapshot := d.invocation + base.InvocationUsage = &snapshot + } + } if wire.IsError { + base.FailureReason = wire.StartupFailureReason + if base.FailureReason == "" { + base.FailureReason = wire.TerminalReason + } + if base.FailureReason == "" && wire.Subtype != "success" { + base.FailureReason = wire.Subtype + } message := wire.Result if message == "" && len(wire.Errors) > 0 { message = strings.Join(wire.Errors, "; ") @@ -374,7 +491,9 @@ func (d *claudeEventDecoder) decodeResult(base Event, wire *claudeWireEvent) []E } var events []Event - if wire.Result != "" && wire.Result != d.lastAgentText { + key := claudeMessageText{wire.ParentToolUseID, wire.Result} + if wire.Result != "" && !d.deliveredText[key] { + d.deliveredText[key] = true events = append(events, claudeItemCompleted(base, Item{ ID: "result", Type: ItemAgentMessage, @@ -395,13 +514,17 @@ func claudeResultUsage(wire *claudeWireEvent) Usage { modelUsage[model] = ModelUsage(usage) } + root := wire.Usage + if root == nil { + root = &claudeWireUsage{} + } // result.usage covers the root agent only; modelUsage and the cost also // cover subagents. The full-run total comes from modelUsage when the agent // reports it. - totalTokens := wire.Usage.InputTokens + - wire.Usage.CacheCreationInputTokens + - wire.Usage.CacheReadInputTokens + - wire.Usage.OutputTokens + totalTokens := root.InputTokens + + root.CacheCreationInputTokens + + root.CacheReadInputTokens + + root.OutputTokens if len(modelUsage) > 0 { totalTokens = 0 for _, usage := range modelUsage { @@ -413,16 +536,53 @@ func claudeResultUsage(wire *claudeWireEvent) Usage { } return Usage{ - InputTokens: wire.Usage.InputTokens, - CachedInputTokens: wire.Usage.CacheReadInputTokens, - CacheCreationInputTokens: wire.Usage.CacheCreationInputTokens, - OutputTokens: wire.Usage.OutputTokens, + ReasoningOutputTokens: root.OutputDetails.ThinkingTokens, + InputTokens: root.InputTokens, + CachedInputTokens: root.CacheReadInputTokens, + CacheCreationInputTokens: root.CacheCreationInputTokens, + OutputTokens: root.OutputTokens, TotalTokens: totalTokens, TotalCostUSD: wire.TotalCostUSD, ModelUsage: modelUsage, } } +// Each result delta is disjoint, even when consecutive session totals are identical. +// Copy the previous map so an already-delivered event remains a stable snapshot. +func modelTotals(delta map[string]claudeWireModelUsage, previous map[string]ModelUsage) Usage { + result := Usage{ModelUsage: make(map[string]ModelUsage, len(previous)+len(delta))} + for name, m := range previous { + result.ModelUsage[name] = m + } + for name, m := range delta { + v := result.ModelUsage[name] + v.InputTokens += m.InputTokens + v.OutputTokens += m.OutputTokens + v.ReasoningOutputTokens += m.ReasoningOutputTokens + v.CacheReadInputTokens += m.CacheReadInputTokens + v.CacheCreationInputTokens += m.CacheCreationInputTokens + v.WebSearchRequests += m.WebSearchRequests + v.CostUSD += m.CostUSD + if m.ContextWindow != 0 { + v.ContextWindow = m.ContextWindow + } + if m.MaxOutputTokens != 0 { + v.MaxOutputTokens = m.MaxOutputTokens + } + result.ModelUsage[name] = v + } + for _, v := range result.ModelUsage { + result.InputTokens += v.InputTokens + result.OutputTokens += v.OutputTokens + result.CachedInputTokens += v.CacheReadInputTokens + result.CacheCreationInputTokens += v.CacheCreationInputTokens + result.ReasoningOutputTokens += v.ReasoningOutputTokens + result.TotalCostUSD += v.CostUSD + } + result.TotalTokens = result.InputTokens + result.CachedInputTokens + result.CacheCreationInputTokens + result.OutputTokens + return result +} + func claudeAgentID(toolUseResult, content json.RawMessage, agent Agent) string { raw := toolUseResult if len(raw) == 0 && agent == AgentGrok { diff --git a/claude_test.go b/claude_test.go index 0a67dd0..97a44b2 100644 --- a/claude_test.go +++ b/claude_test.go @@ -442,3 +442,126 @@ func TestLiveClaudeRunNormalizesBashExitAndUsage(t *testing.T) { } assert.True(t, found, "expected a completed Bash item") } + +func TestMessagesContractFixtures(t *testing.T) { + for _, agent := range []Agent{AgentClaude, AgentGrok} { + t.Run(string(agent), func(t *testing.T) { + path, err := filepath.Abs(filepath.Join("crates/codexcw/tests/fixtures/streams", string(agent)+".jsonl")) + require.NoError(t, err) + fake := writeFakeCodex(t, `cat "$STREAM_FIXTURE"`) + result, err := New(WithAgent(agent), WithExecutable(fake), WithEnv("STREAM_FIXTURE="+path)).Run(context.Background(), Request{Prompt: "x", ResumeID: "session"}) + require.NoError(t, err) + assert.JSONEq(t, `{"ok":true}`, string(result.StructuredOutput)) + var texts []string + for _, ev := range result.Events { + if ev.Delta != nil { + texts = append(texts, ev.Delta.Text) + } + } + assert.Contains(t, texts, "fin") + require.NotNil(t, result.InvocationUsage) + if agent == AgentClaude { + assert.Equal(t, "finished", result.FinalMessage) + require.NotNil(t, result.SessionUsage) + assert.EqualValues(t, 84, result.SessionUsage.TotalTokens) + assert.EqualValues(t, 24, result.InvocationUsage.TotalTokens) + assert.EqualValues(t, 3, result.Usage.ReasoningOutputTokens) + assert.EqualValues(t, 4, result.InvocationUsage.ModelUsage["model"].ReasoningOutputTokens) + var child, task bool + for _, ev := range result.Events { + child = child || ev.ParentToolUseID == "call" + if ev.Task != nil && ev.Task.Status == "completed" { + task = true + assert.Equal(t, "Sample checked", ev.Task.Summary) + require.Equal(t, &TaskUsage{DurationMS: 120, ToolUses: 2, TotalTokens: 17}, ev.Task.Usage) + } + } + assert.True(t, child) + assert.True(t, task) + } else { + assert.Equal(t, "done", result.FinalMessage) + assert.Nil(t, result.SessionUsage) + var command *Item + for _, ev := range result.Events { + if ev.ItemCompleted != nil && ev.ItemCompleted.Item.Type == ItemCommandExecution { + command = &ev.ItemCompleted.Item + } + } + require.NotNil(t, command) + assert.Equal(t, "failed", command.Status) + require.NotNil(t, command.ExitCode) + assert.Equal(t, 7, *command.ExitCode) + assert.Equal(t, "ok", command.AggregatedOutput) + } + }) + } +} + +func TestScopedUsageAvailability(t *testing.T) { + for _, agent := range []Agent{AgentCodex, AgentGrok} { + t.Run(string(agent), func(t *testing.T) { + terminal := `{"type":"turn.completed"` + if agent == AgentGrok { + terminal = `{"type":"result","subtype":"success"` + } + fake := writeFakeCodex(t, "cat >/dev/null\n"+"printf '%s\\n' '"+terminal+"}' '"+terminal+",\"usage\":{\"output_tokens\":0}}' '"+terminal+"}'") + result, err := New(WithAgent(agent), WithExecutable(fake)).Run(context.Background(), Request{Prompt: "x"}) + require.NoError(t, err) + require.Len(t, result.Events, 3) + assert.Nil(t, result.Events[0].InvocationUsage) + require.NotNil(t, result.Events[1].InvocationUsage) + assert.EqualValues(t, 0, result.Events[1].InvocationUsage.TotalTokens) + assert.Nil(t, result.Events[2].InvocationUsage) + require.NotNil(t, result.InvocationUsage) + }) + } +} + +func TestClaudeResultTextHistoryByParent(t *testing.T) { + decoder := newClaudeEventDecoder() + for _, tt := range []struct { + line string + wantItems int + }{ + {`{"type":"assistant","message":{"content":[{"type":"text","text":"older"}]}}`, 1}, + {`{"type":"assistant","message":{"content":[{"type":"text","text":"latest"}]}}`, 1}, + {`{"type":"result","result":"older"}`, 0}, + {`{"type":"result","result":"new"}`, 1}, + {`{"type":"result","result":"new"}`, 0}, + {`{"type":"result","result":"new","parent_tool_use_id":"child"}`, 1}, + {`{"type":"result","result":"new","parent_tool_use_id":"child"}`, 0}, + {`{"type":"assistant","message":{"content":[{"type":"text","text":"child only"}]},"parent_tool_use_id":"child"}`, 1}, + {`{"type":"result","result":"child only"}`, 1}, + } { + events, err := decoder.decode([]byte(tt.line), "run", "", time.Now()) + require.NoError(t, err) + count := 0 + for _, event := range events { + if event.ItemCompleted != nil { + count++ + } + } + assert.Equal(t, tt.wantItems, count, tt.line) + } +} + +func TestClaudeResultFailureReasons(t *testing.T) { + decoder := newClaudeEventDecoder() + for _, tt := range []struct { + line string + failed bool + reason string + }{ + {`{"type":"result","is_error":false,"subtype":"success","terminal_reason":"completed"}`, false, ""}, + {`{"type":"result","is_error":true,"subtype":"success"}`, true, ""}, + {`{"type":"result","is_error":true,"subtype":"error_max_turns","terminal_reason":"","startup_failure_reason":""}`, true, "error_max_turns"}, + {`{"type":"result","is_error":true,"subtype":"error_during_execution","startup_failure_reason":"","terminal_reason":"max_turns"}`, true, "max_turns"}, + {`{"type":"result","is_error":true,"subtype":"error_during_execution","startup_failure_reason":"resume_target_not_found","terminal_reason":"other"}`, true, "resume_target_not_found"}, + } { + events, err := decoder.decode([]byte(tt.line), "run", "", time.Now()) + require.NoError(t, err) + require.Len(t, events, 1) + assert.Equal(t, tt.failed, events[0].TurnFailed != nil, tt.line) + assert.Equal(t, tt.reason, events[0].FailureReason, tt.line) + } +} diff --git a/codex_items.go b/codex_items.go new file mode 100644 index 0000000..65af670 --- /dev/null +++ b/codex_items.go @@ -0,0 +1,96 @@ +package codexcw + +import ( + "encoding/json" + "errors" +) + +// WebSearch describes a Codex web search and its available results. +type WebSearch struct { + // Query is the search query reported on the item. + Query string `json:"query"` + // Action is the search or page operation. + Action *WebSearchAction `json:"action"` + // Results is nil when the agent omits results, and empty for an empty result set. + Results []WebSearchResult `json:"results"` +} + +// WebSearchAction describes the operation requested by the model. +type WebSearchAction struct { + // Type is the wire action type. + Type string `json:"type"` + // Query is a single search query. + Query string `json:"query"` + // Queries holds multiple search queries when available. + Queries []string `json:"queries"` + // URL is the target of a page operation. + URL string `json:"url"` + // Pattern is the text sought within a page. + Pattern string `json:"pattern"` +} + +// WebSearchResult is a typed projection of one result. Raw preserves any result shape. +type WebSearchResult struct { + // Type is the result type. + Type string `json:"type"` + // Title is the source title. + Title string `json:"title"` + // URL is the source address. + URL string `json:"url"` + // Domain identifies the source website. + Domain string `json:"domain"` + // Snippet is the returned excerpt. + Snippet string `json:"snippet"` + // RefID is the provider's source reference. + RefID string `json:"ref_id"` + // Raw is the provider's complete JSON result. + Raw json.RawMessage `json:"-"` +} + +// UnmarshalJSON preserves arbitrary provider results alongside recognized text fields. +func (result *WebSearchResult) UnmarshalJSON(data []byte) error { + type fields WebSearchResult + var parsed fields + // The upstream allows arbitrary JSON here, including non-object error results. + if err := json.Unmarshal(data, &parsed); err != nil { + var shape *json.UnmarshalTypeError + if !errors.As(err, &shape) { + return err + } + } + *result = WebSearchResult(parsed) + result.Raw = append(json.RawMessage(nil), data...) + return nil +} + +// MCPCall describes a Codex MCP tool invocation. +type MCPCall struct { + // Server is the configured MCP server name. + Server string `json:"server"` + // Tool is the name of the called tool. + Tool string `json:"tool"` + // Arguments is the tool-specific input JSON. + Arguments json.RawMessage `json:"arguments"` + // Result is the tool response when available. + Result *MCPResult `json:"result"` + // Error describes an unsuccessful tool invocation. + Error string `json:"-"` +} + +// MCPResult contains the data returned by an MCP tool. +type MCPResult struct { + // Content holds tool-defined MCP content blocks. + Content []json.RawMessage `json:"content"` + // StructuredContent is the optional structured response. + StructuredContent json.RawMessage `json:"structured_content"` + // Meta holds optional MCP response metadata. + Meta json.RawMessage `json:"_meta"` +} + +// TodoStep is one task in a Codex plan snapshot. +type TodoStep struct { + // Text is the task description. + Text string `json:"text"` + // Completed indicates that the task has finished. + Completed bool `json:"completed"` +} diff --git a/codex_items_test.go b/codex_items_test.go new file mode 100644 index 0000000..2e2d705 --- /dev/null +++ b/codex_items_test.go @@ -0,0 +1,91 @@ +package codexcw + +import ( + "os" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCodexStreamProjections(t *testing.T) { + capture, err := os.ReadFile("crates/codexcw/tests/fixtures/streams/codex.jsonl") + require.NoError(t, err) + var events []Event + for _, line := range strings.Split(strings.TrimSpace(string(capture)), "\n") { + event, decodeErr := decodeEvent([]byte(line), "run", "", time.Now()) + require.NoError(t, decodeErr) + assert.Equal(t, line, string(event.Raw)) + events = append(events, event) + } + assert.Equal(t, []TodoStep{{Text: "Find source", Completed: true}}, events[3].ItemUpdated.Item.Todos) + assert.Nil(t, events[4].ItemStarted.Item.WebSearch.Results) + search := events[5].ItemCompleted.Item.WebSearch + assert.Equal(t, "search", search.Action.Type) + assert.Equal(t, "Example", search.Results[0].Title) + assert.Contains(t, string(search.Results[1].Raw), "unavailable") + assert.NotNil(t, events[6].ItemCompleted.Item.WebSearch.Results) + assert.Empty(t, events[6].ItemCompleted.Item.WebSearch.Results) + mcp := events[7].ItemCompleted.Item.MCP + assert.Equal(t, "probe", mcp.Server) + assert.JSONEq(t, `{"color":"GOLD"}`, string(mcp.Result.StructuredContent)) + assert.Equal(t, "approval required", events[8].ItemCompleted.Item.MCP.Error) + assert.Equal(t, "final_answer", events[10].ItemCompleted.Item.Phase) + assert.Equal(t, int64(3), events[12].TurnCompleted.Usage.CacheCreationInputTokens) + assert.Equal(t, int64(25), events[12].TurnCompleted.Usage.TotalTokens) +} + +func TestCodexForkArgsAndValidation(t *testing.T) { + runner := New() + args, _, _, err := runner.prepare(Request{ForkID: "parent", Prompt: "go"}) + require.NoError(t, err) + assert.Equal(t, []string{"exec", "fork"}, args[:2]) + assert.Equal(t, []string{"parent", "-"}, args[len(args)-2:]) + assert.Contains(t, args, `sandbox_mode="read-only"`) + assert.NotContains(t, args, "--color") + for _, req := range []Request{{ForkID: "p", ResumeID: "r"}, {ForkID: "p", ResumeLast: true}, {ForkID: "p", ResumeAll: true}, {ForkID: "p", Dir: "."}, {IncludePartialMessages: true}} { + req.Prompt = "x" + _, _, _, err := runner.prepare(req) + assert.ErrorIs(t, err, ErrInvalidRequest) + } +} + +func TestCodexUsagePresence(t *testing.T) { + for _, tc := range []struct { + line string + reported bool + }{ + {`{"type":"turn.failed","error":{"message":"boom"}}`, false}, + {`{"type":"turn.completed","usage":null}`, false}, + {`{"type":"turn.completed","usage":{}}`, true}, + } { + event, err := decodeEvent([]byte(tc.line), "run", "", time.Now()) + require.NoError(t, err) + assert.Equal(t, tc.reported, event.SessionUsage != nil) + } +} + +func TestCodexOptionalMCPJSON(t *testing.T) { + fake := writeFakeCodex(t, `cat >/dev/null +cat <<'JSONL' +{"type":"item.completed","item":{"type":"mcp_tool_call","arguments":null,"result":{"structured_content":null,"_meta":null}}} +{"type":"item.completed","item":{"type":"mcp_tool_call","result":{}}} +{"type":"item.completed","item":{"type":"mcp_tool_call","arguments":[],"result":{"structured_content":false,"_meta":{}}}} +JSONL`) + result, err := New(WithExecutable(fake)).Run(t.Context(), Request{Prompt: "decode"}) + require.NoError(t, err) + require.Len(t, result.Events, 3) + for _, event := range result.Events[:2] { + mcp := event.ItemCompleted.Item.MCP + assert.Nil(t, mcp.Arguments) + assert.Nil(t, mcp.Result.StructuredContent) + assert.Nil(t, mcp.Result.Meta) + } + assert.Contains(t, string(result.Events[0].ItemCompleted.Item.Raw), `"structured_content":null`) + mcp := result.Events[2].ItemCompleted.Item.MCP + assert.JSONEq(t, "[]", string(mcp.Arguments)) + assert.JSONEq(t, "false", string(mcp.Result.StructuredContent)) + assert.JSONEq(t, "{}", string(mcp.Result.Meta)) +} diff --git a/crates/codexcw/src/args.rs b/crates/codexcw/src/args.rs index 81ac589..ffb4f9d 100644 --- a/crates/codexcw/src/args.rs +++ b/crates/codexcw/src/args.rs @@ -46,6 +46,8 @@ pub(crate) fn prepare( let mut args = vec!["exec".to_string()]; if req.is_resume() { args.push("resume".to_string()); + } else if nonempty(&req.fork_id).is_some() { + args.push("fork".to_string()); } append_common_args( @@ -62,10 +64,8 @@ pub(crate) fn prepare( if req.resume_all { args.push("--all".to_string()); } - if let Some(id) = &req.resume_id { - if !id.is_empty() { - args.push(id.clone()); - } + if let Some(id) = nonempty(&req.resume_id).or_else(|| nonempty(&req.fork_id)) { + args.push(id); } args.push("-".to_string()); @@ -107,17 +107,26 @@ pub(crate) fn validate_request(req: &Request) -> Result<(), Error> { "resume id and resume last are mutually exclusive", )); } + let fork = nonempty(&req.fork_id).is_some(); + if req.include_partial_messages { + return Err(Error::invalid( + "partial messages are not supported by codex", + )); + } + if fork && (resume || req.resume_all) { + return Err(Error::invalid("fork and resume are mutually exclusive")); + } if req.resume_all && !resume { return Err(Error::invalid( "resume all requires resume id or resume last", )); } - if resume { + if resume || fork { let dir = req.dir.as_deref().is_some_and(|d| !d.is_empty()); let profile = req.profile.as_deref().is_some_and(|p| !p.is_empty()); if dir || !req.add_dirs.is_empty() || profile { return Err(Error::invalid( - "dir, add dirs, and profile are not supported by codex exec resume", + "dir, add dirs, and profile are not supported by codex exec resume or fork", )); } } @@ -131,10 +140,10 @@ fn append_common_args( default_sandbox: SandboxMode, default_approval: ApprovalPolicy, ) { - let resume = req.is_resume(); + let continuation = req.is_resume() || nonempty(&req.fork_id).is_some(); args.push("--json".to_string()); - if !resume { + if !continuation { args.push("--color".to_string()); args.push("never".to_string()); } @@ -149,7 +158,7 @@ fn append_common_args( args.push("-c".to_string()); args.push(format!("model_reasoning_effort={}", toml_string(&effort))); } - if !resume { + if !continuation { if let Some(profile) = nonempty(&req.profile) { args.push("-p".to_string()); args.push(profile); @@ -187,7 +196,7 @@ fn append_common_args( args.push("--dangerously-bypass-approvals-and-sandbox".to_string()); } else { let sandbox = req.sandbox.unwrap_or(default_sandbox); - if resume { + if continuation { args.push("-c".to_string()); args.push(format!("sandbox_mode=\"{}\"", sandbox.as_str())); } else { @@ -201,7 +210,7 @@ fn append_common_args( if req.dangerously_bypass_hooks { args.push("--dangerously-bypass-hook-trust".to_string()); } - if !resume { + if !continuation { if let Some(dir) = nonempty(&req.dir) { args.push("-C".to_string()); args.push(dir); @@ -261,6 +270,34 @@ mod tests { (SandboxMode::ReadOnly, ApprovalPolicy::Never) } + #[test] + fn forks_explicit_parent() { + let (sandbox, approval) = defaults(); + let req = Request { + fork_id: Some("parent".into()), + ..Request::new("go") + }; + let args = prepare(&req, sandbox, approval).unwrap().args; + assert_eq!(&args[..2], &["exec", "fork"]); + assert_eq!(&args[args.len() - 2..], &["parent", "-"]); + assert!(args.iter().any(|arg| arg == r#"sandbox_mode="read-only""#)); + assert!(validate_request(&Request { + resume_last: true, + ..req.clone() + }) + .is_err()); + assert!(validate_request(&Request { + resume_all: true, + ..req + }) + .is_err()); + assert!(validate_request(&Request { + include_partial_messages: true, + ..Request::new("go") + }) + .is_err()); + } + #[test] fn builds_safe_defaults() { let (s, a) = defaults(); diff --git a/crates/codexcw/src/claude.rs b/crates/codexcw/src/claude.rs index ce8cd9f..b21babc 100644 --- a/crates/codexcw/src/claude.rs +++ b/crates/codexcw/src/claude.rs @@ -1,7 +1,7 @@ //! The claude agent: `claude -p` argument building and normalization of its //! stream-json events into the shared [`Event`] model. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::time::SystemTime; use serde::Deserialize; @@ -10,7 +10,8 @@ use serde_json::value::RawValue; use crate::args::{nonempty, prompt_bytes, Prepared}; use crate::error::Error; use crate::event::{ - ErrorPayload, Event, EventKind, EventPayload, FileChange, Item, ItemKind, ModelUsage, Usage, + ErrorPayload, Event, EventKind, EventPayload, FileChange, Item, ItemKind, ModelUsage, + StreamDelta, TaskUpdate, TaskUsage, Usage, }; use crate::request::Request; @@ -30,6 +31,9 @@ pub(crate) fn prepare_claude(req: &Request) -> Result { "stream-json".to_string(), "--verbose".to_string(), ]; + if req.include_partial_messages { + args.push("--include-partial-messages".to_string()); + } if let Some(model) = nonempty(&req.model) { args.push("--model".to_string()); args.push(model); @@ -101,7 +105,7 @@ pub(crate) fn validate_claude_request(req: &Request) -> Result<(), Error> { )); } - let unsupported: [(bool, &str); 15] = [ + let unsupported: [(bool, &str); 16] = [ (!req.images.is_empty(), "images"), ( req.profile.as_deref().is_some_and(|p| !p.is_empty()), @@ -124,6 +128,7 @@ pub(crate) fn validate_claude_request(req: &Request) -> Result<(), Error> { "output last message path", ), (req.dangerously_bypass_hooks, "dangerously bypass hooks"), + (nonempty(&req.fork_id).is_some(), "fork id"), (req.resume_all, "resume all"), ]; for (set, name) in unsupported { @@ -141,7 +146,9 @@ pub(crate) struct ClaudeDecoder { dialect: MessageDialect, pending: HashMap, block_indexes: HashMap, - last_agent_text: String, + delivered_text: HashSet<(String, String)>, + invocation: Usage, + seen_results: HashSet, } #[derive(Clone, Copy, Default, PartialEq, Eq)] @@ -166,13 +173,30 @@ impl Default for ClaudeDecoder { dialect: MessageDialect::Claude, pending: HashMap::new(), block_indexes: HashMap::new(), - last_agent_text: String::new(), + delivered_text: HashSet::new(), + invocation: Usage::default(), + seen_results: HashSet::new(), } } } #[derive(Deserialize)] struct WireEvent { + description: Option, + summary: Option, + parent_tool_use_id: Option, + result_index: Option, + structured_output: Option, + model_usage_since_last_result: Option>, + startup_failure_reason: Option, + terminal_reason: Option, + event: Option, + task_id: Option, + run_id: Option, + tool_use_id: Option, + status: Option, + patch: Option, + #[serde(rename = "type")] kind: Option, #[serde(default)] @@ -188,11 +212,11 @@ struct WireEvent { #[serde(default)] errors: Vec, #[serde(default)] - usage: WireUsage, + usage: Option, #[serde(default)] total_cost_usd: f64, #[serde(default, rename = "modelUsage")] - model_usage: HashMap, + model_usage: Option>, #[serde(default)] tool_use_result: Option>, } @@ -229,6 +253,9 @@ struct WireBlock { #[derive(Deserialize, Default)] struct WireUsage { + #[serde(flatten)] + task: TaskUsage, + output_tokens_details: Option, #[serde(default)] input_tokens: i64, #[serde(default)] @@ -282,12 +309,37 @@ impl ClaudeDecoder { received_at: now, raw, payload: EventPayload::Other, + parent_tool_use_id: wire.parent_tool_use_id.clone().unwrap_or_default(), + ..Event::default() }; if !wire.session_id.is_empty() { base.thread_id = wire.session_id.clone(); } match kind.as_str() { + "stream_event" => { + base.delta = wire.event.as_ref().and_then(stream_delta); + Ok(vec![base]) + } + "system" if wire.subtype.starts_with("task_") => { + base.task = Some(TaskUpdate { + description: wire.description.unwrap_or_default(), + summary: wire.summary.unwrap_or_default(), + usage: wire.usage.map(|u| u.task), + kind: wire.subtype, + id: wire.task_id.unwrap_or_default(), + run_id: wire.run_id.unwrap_or_default(), + tool_use_id: wire.tool_use_id.unwrap_or_default(), + status: wire + .status + .as_ref() + .and_then(|v| v.as_str()) + .or_else(|| wire.patch.as_ref().and_then(|v| v["status"].as_str())) + .unwrap_or_default() + .into(), + }); + Ok(vec![base]) + } "system" if wire.subtype == "init" => { let mut started = base.clone(); started.kind = EventKind::ThreadStarted; @@ -314,7 +366,8 @@ impl ClaudeDecoder { serde_json::from_str(raw_block.get()).map_err(|err| err.to_string())?; match block.kind.as_str() { "text" => { - self.last_agent_text = block.text.clone(); + self.delivered_text + .insert((base.parent_tool_use_id.clone(), block.text.clone())); events.push(item_completed( &base, Item { @@ -393,6 +446,11 @@ impl ClaudeDecoder { item.exit_code = command_exit_code(wire.tool_use_result.as_deref(), &block, self.dialect) .or((!block.is_error).then_some(0)); + if self.dialect == MessageDialect::Grok + && item.exit_code.is_some_and(|code| code != 0) + { + item.status = "failed".into(); + } } if item.kind == ItemKind::FileChange && !item.changes.is_empty() { if let Some(kind) = file_change_kind(wire.tool_use_result.as_deref()) { @@ -416,10 +474,60 @@ impl ClaudeDecoder { Ok(events) } - fn decode_result(&mut self, base: Event, wire: &WireEvent) -> Vec { + fn decode_result(&mut self, mut base: Event, wire: &WireEvent) -> Vec { let result_text = wire.result.clone().unwrap_or_default(); let usage = result_usage(wire); + base.result_index = wire.result_index; + base.structured_output = wire.structured_output.clone(); + if self.dialect == MessageDialect::Grok + && (wire.usage.is_some() || wire.model_usage.is_some()) + { + base.invocation_usage = Some(usage.clone()); + } + if self.dialect == MessageDialect::Claude { + if let Some(models) = &wire.model_usage { + let mut session = model_totals(models.clone()); + session.total_cost_usd = wire.total_cost_usd; + base.session_usage = Some(session); + } + if let Some(delta) = &wire.model_usage_since_last_result { + if wire + .result_index + .is_none_or(|index| self.seen_results.insert(index)) + { + let mut models = std::mem::take(&mut self.invocation.model_usage); + for (key, m) in delta { + let v = models.entry(key.clone()).or_default(); + v.input_tokens += m.input_tokens; + v.output_tokens += m.output_tokens; + v.reasoning_output_tokens += m.reasoning_output_tokens; + v.cache_read_input_tokens += m.cache_read_input_tokens; + v.cache_creation_input_tokens += m.cache_creation_input_tokens; + v.web_search_requests += m.web_search_requests; + v.cost_usd += m.cost_usd; + if m.context_window != 0 { + v.context_window = m.context_window; + } + if m.max_output_tokens != 0 { + v.max_output_tokens = m.max_output_tokens; + } + } + self.invocation = model_totals(models); + } + base.invocation_usage = Some(self.invocation.clone()); + } + } if wire.is_error { + base.failure_reason = [ + wire.startup_failure_reason.as_deref(), + wire.terminal_reason.as_deref(), + (wire.subtype != "success").then_some(wire.subtype.as_str()), + ] + .into_iter() + .flatten() + .find(|s| !s.is_empty()) + .unwrap_or_default() + .to_owned(); let message = if !result_text.is_empty() { result_text } else if !wire.errors.is_empty() { @@ -440,7 +548,11 @@ impl ClaudeDecoder { } let mut events = Vec::new(); - if !result_text.is_empty() && result_text != self.last_agent_text { + if !result_text.is_empty() + && self + .delivered_text + .insert((base.parent_tool_use_id.clone(), result_text.clone())) + { events.push(item_completed( &base, Item { @@ -471,17 +583,61 @@ impl ClaudeDecoder { } } +fn stream_delta(stream: &serde_json::Value) -> Option { + let native = stream["type"].as_str()?; + let delta = &stream["delta"]; + let kind = if native == "content_block_delta" { + delta["type"].as_str().unwrap_or(native) + } else { + native + }; + let field = match kind { + "text_delta" => "text", + "thinking_delta" => "thinking", + "input_json_delta" => "partial_json", + "signature_delta" => "signature", + _ => "", + }; + Some(StreamDelta { + kind: kind.into(), + text: delta[field].as_str().unwrap_or_default().into(), + index: stream["index"].as_i64().and_then(|i| i32::try_from(i).ok()), + }) +} + +fn model_totals(models: HashMap) -> Usage { + let mut result = Usage { + model_usage: models, + ..Default::default() + }; + for m in result.model_usage.values() { + result.input_tokens += m.input_tokens; + result.output_tokens += m.output_tokens; + result.cached_input_tokens += m.cache_read_input_tokens; + result.cache_creation_input_tokens += m.cache_creation_input_tokens; + result.reasoning_output_tokens += m.reasoning_output_tokens; + result.total_cost_usd += m.cost_usd; + } + result.total_tokens = result.input_tokens + + result.output_tokens + + result.cached_input_tokens + + result.cache_creation_input_tokens; + result +} + fn result_usage(wire: &WireEvent) -> Usage { + let empty = WireUsage::default(); + let root = wire.usage.as_ref().unwrap_or(&empty); + let model_usage = wire.model_usage.clone().unwrap_or_default(); // result.usage covers the root agent only; modelUsage and the cost also // cover subagents. The full-run total comes from modelUsage when the agent // reports it. - let mut total_tokens = wire.usage.input_tokens - + wire.usage.cache_creation_input_tokens - + wire.usage.cache_read_input_tokens - + wire.usage.output_tokens; - if !wire.model_usage.is_empty() { - total_tokens = wire - .model_usage + let mut total_tokens = root.input_tokens + + root.cache_creation_input_tokens + + root.cache_read_input_tokens + + root.output_tokens; + if !model_usage.is_empty() { + total_tokens = model_usage .values() .map(|usage| { usage.input_tokens @@ -493,14 +649,18 @@ fn result_usage(wire: &WireEvent) -> Usage { } Usage { - input_tokens: wire.usage.input_tokens, - cache_creation_input_tokens: wire.usage.cache_creation_input_tokens, - cached_input_tokens: wire.usage.cache_read_input_tokens, - output_tokens: wire.usage.output_tokens, + input_tokens: root.input_tokens, + cache_creation_input_tokens: root.cache_creation_input_tokens, + cached_input_tokens: root.cache_read_input_tokens, + output_tokens: root.output_tokens, total_tokens, total_cost_usd: wire.total_cost_usd, - model_usage: wire.model_usage.clone(), - reasoning_output_tokens: 0, + model_usage, + reasoning_output_tokens: root + .output_tokens_details + .as_ref() + .and_then(|v| v["thinking_tokens"].as_i64()) + .unwrap_or_default(), } } @@ -1156,6 +1316,88 @@ mod tests { assert_eq!(events[0].kind, EventKind::TurnCompleted); } + #[test] + fn result_text_history_by_parent() { + let mut decoder = ClaudeDecoder::default(); + for (line, expected) in [ + ( + r#"{"type":"assistant","message":{"content":[{"type":"text","text":"older"}]}}"#, + 1, + ), + ( + r#"{"type":"assistant","message":{"content":[{"type":"text","text":"latest"}]}}"#, + 1, + ), + (r#"{"type":"result","result":"older"}"#, 0), + (r#"{"type":"result","result":"new"}"#, 1), + (r#"{"type":"result","result":"new"}"#, 0), + ( + r#"{"type":"result","result":"new","parent_tool_use_id":"child"}"#, + 1, + ), + ( + r#"{"type":"result","result":"new","parent_tool_use_id":"child"}"#, + 0, + ), + ( + r#"{"type":"assistant","message":{"content":[{"type":"text","text":"child only"}]},"parent_tool_use_id":"child"}"#, + 1, + ), + (r#"{"type":"result","result":"child only"}"#, 1), + ] { + let events = decoder + .decode(line.as_bytes(), "run", "", SystemTime::UNIX_EPOCH) + .unwrap(); + assert_eq!( + events + .iter() + .filter(|ev| ev.item_completed().is_some()) + .count(), + expected, + "{line}" + ); + } + } + + #[test] + fn result_failure_reasons() { + let mut decoder = ClaudeDecoder::default(); + for (line, failed, reason) in [ + ( + r#"{"type":"result","is_error":false,"subtype":"success","terminal_reason":"completed"}"#, + false, + "", + ), + ( + r#"{"type":"result","is_error":true,"subtype":"success"}"#, + true, + "", + ), + ( + r#"{"type":"result","is_error":true,"subtype":"error_max_turns","terminal_reason":"","startup_failure_reason":""}"#, + true, + "error_max_turns", + ), + ( + r#"{"type":"result","is_error":true,"subtype":"error_during_execution","startup_failure_reason":"","terminal_reason":"max_turns"}"#, + true, + "max_turns", + ), + ( + r#"{"type":"result","is_error":true,"subtype":"error_during_execution","startup_failure_reason":"resume_target_not_found","terminal_reason":"other"}"#, + true, + "resume_target_not_found", + ), + ] { + let events = decoder + .decode(line.as_bytes(), "run", "", SystemTime::UNIX_EPOCH) + .unwrap(); + assert_eq!(events.len(), 1); + assert_eq!(events[0].kind == EventKind::TurnFailed, failed); + assert_eq!(events[0].failure_reason, reason, "{line}"); + } + } + #[test] fn unknown_events_pass_through() { let mut decoder = ClaudeDecoder::default(); diff --git a/crates/codexcw/src/codex_items.rs b/crates/codexcw/src/codex_items.rs new file mode 100644 index 0000000..62563d6 --- /dev/null +++ b/crates/codexcw/src/codex_items.rs @@ -0,0 +1,127 @@ +//! Structured details from Codex JSONL items. + +use serde::Deserialize; +use serde_json::Value; + +/// A web search invocation and its optional result set. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct WebSearch { + /// Search query reported on the item. + pub query: String, + /// Operation requested by the model. + pub action: Option, + /// Results when supplied by the provider, including an explicit empty list. + pub results: Option>, +} + +/// A search, page open, find-in-page or future action. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct WebSearchAction { + /// Wire action type. + #[serde(rename = "type")] + pub kind: String, + /// Single search query. + pub query: Option, + /// Multiple search queries. + #[serde(deserialize_with = "nullable_list")] + pub queries: Vec, + /// Address for page operations. + pub url: Option, + /// Text sought in a page. + pub pattern: Option, +} + +pub(crate) fn nullable_list<'de, D, T>(de: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, + T: Deserialize<'de>, +{ + Ok(Option::>::deserialize(de)?.unwrap_or_default()) +} + +/// A structured search result. Unknown and non-object results retain their JSON value. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(from = "Value")] +pub struct WebSearchResult { + /// Wire result type. + pub kind: Option, + /// Source title. + pub title: Option, + /// Source URL. + pub url: Option, + /// Source domain. + pub domain: Option, + /// Text excerpt. + pub snippet: Option, + /// Source reference identifier. + pub ref_id: Option, + /// Full result, including provider-specific data. + pub raw: Value, +} + +impl From for WebSearchResult { + fn from(raw: Value) -> Self { + let field = |name: &str| raw.get(name).and_then(Value::as_str).map(str::to_owned); + Self { + kind: field("type"), + title: field("title"), + url: field("url"), + domain: field("domain"), + snippet: field("snippet"), + ref_id: field("ref_id"), + raw, + } + } +} + +/// A Codex MCP tool invocation. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct McpCall { + /// Name of the configured server. + pub server: String, + /// Name of the called tool. + pub tool: String, + /// Tool-specific input. + pub arguments: Option, + /// Returned tool data. + pub result: Option, + /// Error message supplied by a failed call. + #[serde(deserialize_with = "mcp_error_message")] + pub error: Option, +} + +fn mcp_error_message<'de, D: serde::Deserializer<'de>>(de: D) -> Result, D::Error> { + #[derive(Deserialize)] + struct McpError { + message: Option, + } + + Ok(Option::::deserialize(de)?.and_then(|error| error.message)) +} + +/// A successful MCP response. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct McpResult { + /// Tool content blocks with provider-specific JSON shapes. + #[serde(deserialize_with = "nullable_list")] + pub content: Vec, + /// Optional structured response. + pub structured_content: Option, + /// Optional MCP metadata. + #[serde(rename = "_meta")] + pub meta: Option, +} + +/// One task in a Codex checklist snapshot. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct TodoStep { + /// Description of the task. + pub text: String, + /// Whether the task has completed. + pub completed: bool, +} diff --git a/crates/codexcw/src/decoder.rs b/crates/codexcw/src/decoder.rs index 4e98352..da99f3b 100644 --- a/crates/codexcw/src/decoder.rs +++ b/crates/codexcw/src/decoder.rs @@ -17,7 +17,7 @@ struct WireEvent { #[serde(default)] thread_id: String, #[serde(default)] - usage: Usage, + usage: Option, #[serde(default)] item: Option>, #[serde(default)] @@ -26,6 +26,23 @@ struct WireEvent { message: String, } +#[derive(Deserialize)] +struct WireUsage { + #[serde(flatten)] + usage: Usage, + cache_write_input_tokens: Option, +} + +impl WireUsage { + fn normalize(self) -> Usage { + let mut usage = self.usage; + if let Some(write) = self.cache_write_input_tokens { + usage.cache_creation_input_tokens = write; + } + normalize_codex_usage(usage) + } +} + #[derive(Deserialize)] struct WireItem { #[serde(default)] @@ -37,6 +54,8 @@ struct WireItem { #[serde(default)] text: String, #[serde(default)] + phase: Option, + #[serde(default)] message: String, #[serde(default)] command: String, @@ -44,13 +63,13 @@ struct WireItem { aggregated_output: String, #[serde(default)] exit_code: Option, - #[serde(default)] + #[serde(default, deserialize_with = "crate::codex_items::nullable_list")] changes: Vec, #[serde(default)] tool: String, #[serde(default)] sender_thread_id: String, - #[serde(default)] + #[serde(default, deserialize_with = "crate::codex_items::nullable_list")] receiver_thread_ids: Vec, } @@ -79,8 +98,12 @@ pub(crate) fn decode_event( received_at: now, raw, payload: EventPayload::Other, + ..Default::default() }; + if matches!(event.kind, EventKind::TurnCompleted | EventKind::TurnFailed) { + event.session_usage = wire.usage.map(WireUsage::normalize); + } event.payload = match event.kind { EventKind::ThreadStarted => { event.thread_id = wire.thread_id.clone(); @@ -90,12 +113,13 @@ pub(crate) fn decode_event( } EventKind::TurnStarted => EventPayload::TurnStarted, EventKind::TurnCompleted => EventPayload::TurnCompleted { - usage: normalize_codex_usage(wire.usage), + usage: event.session_usage.clone().unwrap_or_default(), }, EventKind::TurnFailed => EventPayload::TurnFailed { error: decode_event_error(wire.error.as_deref()), - usage: normalize_codex_usage(wire.usage), + usage: event.session_usage.clone().unwrap_or_default(), }, + EventKind::ItemUpdated => EventPayload::ItemUpdated(decode_item(wire.item.as_deref())?), EventKind::ItemStarted => EventPayload::ItemStarted(decode_item(wire.item.as_deref())?), EventKind::ItemCompleted => EventPayload::ItemCompleted(decode_item(wire.item.as_deref())?), EventKind::Error => { @@ -113,7 +137,7 @@ pub(crate) fn decode_event( raw: raw_error, }) } - EventKind::Other(_) => EventPayload::Other, + _ => EventPayload::Other, }; Ok(event) @@ -126,12 +150,13 @@ fn decode_item(raw: Option<&RawValue>) -> Result { return Err("missing item payload".to_string()); } let wire: WireItem = serde_json::from_str(text).map_err(|err| err.to_string())?; - Ok(Item { + let mut item = Item { id: wire.id, kind: ItemKind::from_wire(&wire.kind), status: wire.status, raw: text.to_string(), text: wire.text, + phase: wire.phase, message: wire.message, command: wire.command, aggregated_output: wire.aggregated_output, @@ -140,7 +165,27 @@ fn decode_item(raw: Option<&RawValue>) -> Result { tool: wire.tool, sender_thread_id: wire.sender_thread_id, receiver_thread_ids: wire.receiver_thread_ids, - }) + ..Default::default() + }; + match item.kind { + ItemKind::WebSearch => { + item.web_search = Some(serde_json::from_str(text).map_err(|e| e.to_string())?) + } + ItemKind::McpToolCall => { + item.mcp = Some(serde_json::from_str(text).map_err(|e| e.to_string())?) + } + ItemKind::TodoList => { + #[derive(Deserialize)] + struct TodoList { + items: Option>, + } + item.todos = serde_json::from_str::(text) + .map_err(|e| e.to_string())? + .items; + } + _ => {} + } + Ok(item) } /// Derives the total when Codex omits `total_tokens`. `cached_input_tokens` @@ -181,6 +226,73 @@ fn decode_event_error(raw: Option<&RawValue>) -> ErrorPayload { mod tests { use super::*; + #[test] + fn decodes_codex_stream_projections() { + let source = include_str!("../tests/fixtures/streams/codex.jsonl"); + let events: Vec<_> = source + .lines() + .map(|line| decode_event(line.as_bytes(), "run", "", SystemTime::now()).unwrap()) + .collect(); + assert!(events[3].item_updated().unwrap().todos.as_ref().unwrap()[0].completed); + let search = |i: usize| { + events[i] + .item_completed() + .unwrap() + .web_search + .as_ref() + .unwrap() + }; + assert!(events[4] + .item_started() + .unwrap() + .web_search + .as_ref() + .unwrap() + .results + .is_none()); + assert_eq!( + search(5).results.as_ref().unwrap()[0].title.as_deref(), + Some("Example") + ); + assert_eq!( + search(5).results.as_ref().unwrap()[1].raw["reason"], + "unavailable" + ); + assert_eq!(search(6).results.as_ref().unwrap().len(), 0); + let mcp = events[7].item_completed().unwrap().mcp.as_ref().unwrap(); + assert_eq!( + mcp.result + .as_ref() + .unwrap() + .structured_content + .as_ref() + .unwrap()["color"], + "GOLD" + ); + assert_eq!( + events[8] + .item_completed() + .unwrap() + .mcp + .as_ref() + .unwrap() + .error + .as_deref(), + Some("approval required") + ); + assert_eq!( + events[10].item_completed().unwrap().phase.as_deref(), + Some("final_answer") + ); + let EventPayload::TurnCompleted { usage } = &events[12].payload else { + panic!("expected turn.completed") + }; + assert_eq!( + (usage.cache_creation_input_tokens, usage.total_tokens), + (3, 25) + ); + } + #[test] fn decodes_thread_started_and_backfills_thread_id() { let event = decode_event( diff --git a/crates/codexcw/src/event.rs b/crates/codexcw/src/event.rs index a8f079c..e3b3aac 100644 --- a/crates/codexcw/src/event.rs +++ b/crates/codexcw/src/event.rs @@ -1,5 +1,6 @@ //! Decoded agent events and their typed payloads. +use crate::codex_items::{McpCall, TodoStep, WebSearch}; use std::collections::HashMap; use std::time::SystemTime; @@ -19,6 +20,8 @@ pub enum EventKind { TurnFailed, /// `item.started` — the agent started a streamed item. ItemStarted, + /// `item.updated` — an existing item changed. + ItemUpdated, /// `item.completed` — the agent completed a streamed item. ItemCompleted, /// `error` — a top-level Codex error. @@ -36,6 +39,7 @@ impl EventKind { EventKind::TurnCompleted => "turn.completed", EventKind::TurnFailed => "turn.failed", EventKind::ItemStarted => "item.started", + EventKind::ItemUpdated => "item.updated", EventKind::ItemCompleted => "item.completed", EventKind::Error => "error", EventKind::Other(value) => value, @@ -49,6 +53,7 @@ impl EventKind { "turn.completed" => EventKind::TurnCompleted, "turn.failed" => EventKind::TurnFailed, "item.started" => EventKind::ItemStarted, + "item.updated" => EventKind::ItemUpdated, "item.completed" => EventKind::ItemCompleted, "error" => EventKind::Error, other => EventKind::Other(other.to_string()), @@ -79,6 +84,8 @@ pub enum ItemKind { McpToolCall, /// `web_search` — a web search operation. WebSearch, + /// `todo_list` — the current Codex plan snapshot. + TodoList, /// `plan_update` — an agent plan update. PlanUpdate, /// `tool_call` — a generic tool call from an agent. @@ -102,6 +109,7 @@ impl ItemKind { ItemKind::FileChange => "file_change", ItemKind::McpToolCall => "mcp_tool_call", ItemKind::WebSearch => "web_search", + ItemKind::TodoList => "todo_list", ItemKind::PlanUpdate => "plan_update", ItemKind::ToolCall => "tool_call", ItemKind::CollabToolCall => "collab_tool_call", @@ -118,6 +126,7 @@ impl ItemKind { "file_change" => ItemKind::FileChange, "mcp_tool_call" => ItemKind::McpToolCall, "web_search" => ItemKind::WebSearch, + "todo_list" => ItemKind::TodoList, "plan_update" => ItemKind::PlanUpdate, "tool_call" => ItemKind::ToolCall, "collab_tool_call" => ItemKind::CollabToolCall, @@ -139,7 +148,7 @@ pub struct Usage { /// Number of input tokens consumed. #[serde(default)] pub input_tokens: i64, - /// Number of input tokens written to Claude's prompt cache. + /// Number of input tokens written to the agent's prompt cache. #[serde(default)] pub cache_creation_input_tokens: i64, /// Number of cached input tokens. @@ -151,7 +160,7 @@ pub struct Usage { /// Number of reasoning output tokens. #[serde(default)] pub reasoning_output_tokens: i64, - /// Total token count for the full run, subagents included. When the + /// Total token count for this usage snapshot, subagents included. When the /// agent omits an explicit total it is derived: input plus output tokens /// for Codex, and per-model sums when Claude or Grok reports model usage. #[serde(default)] @@ -168,6 +177,9 @@ pub struct Usage { #[derive(Clone, Debug, Default, PartialEq, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelUsage { + /// Number of reported thinking tokens within output tokens. + #[serde(default, rename = "thinkingTokens")] + pub reasoning_output_tokens: i64, /// Number of input tokens consumed. #[serde(default)] pub input_tokens: i64, @@ -216,6 +228,14 @@ pub struct Item { pub status: String, /// Original nested item payload as JSON text. pub raw: String, + /// Model-reported agent-message phase, when available. + pub phase: Option, + /// Action and available results for a web search. + pub web_search: Option, + /// MCP invocation, result or tool error. + pub mcp: Option, + /// Current Codex plan snapshot. + pub todos: Option>, /// Assistant text for `agent_message` items. pub text: String, /// Error text for `error` items. @@ -285,6 +305,8 @@ pub enum EventPayload { }, /// Payload for `item.started`. ItemStarted(Item), + /// Payload for `item.updated`. + ItemUpdated(Item), /// Payload for `item.completed`. ItemCompleted(Item), /// Payload for a top-level `error`. @@ -296,6 +318,22 @@ pub enum EventPayload { /// One decoded agent event. #[derive(Clone, Debug, PartialEq)] pub struct Event { + /// Structured result reported by the agent. + pub structured_output: Option, + /// Usage attributable to this invocation when available. + pub invocation_usage: Option, + /// Cumulative session usage when reported. + pub session_usage: Option, + /// Parent tool call for a nested message. + pub parent_tool_use_id: String, + /// Native result index when present. + pub result_index: Option, + /// Machine-readable reason for termination. + pub failure_reason: String, + /// Partial Messages stream payload. + pub delta: Option, + /// Task lifecycle update. + pub task: Option, /// Normalized top-level event type. pub kind: EventKind, /// Wrapper-assigned run id. @@ -319,6 +357,14 @@ impl Event { } } + /// Returns the updated item for an `item.updated` event. + pub fn item_updated(&self) -> Option<&Item> { + match &self.payload { + EventPayload::ItemUpdated(item) => Some(item), + _ => None, + } + } + /// Returns the started item when this is an `item.started` event. pub fn item_started(&self) -> Option<&Item> { match &self.payload { @@ -327,3 +373,68 @@ impl Event { } } } + +/// A partial Messages stream event. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct StreamDelta { + /// Native event or delta kind. + pub kind: String, + /// Incremental text, thinking, or JSON argument fragment. + pub text: String, + /// Content block index when supplied. + pub index: Option, +} + +/// A task lifecycle event. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TaskUpdate { + /// Task description supplied at startup. + pub description: String, + /// Completion summary supplied by the agent. + pub summary: String, + /// Counters for this task when reported. + pub usage: Option, + /// Native event or delta kind. + pub kind: String, + /// Task identifier. + pub id: String, + /// Identifier of the task run. + pub run_id: String, + /// Tool call associated with this task. + pub tool_use_id: String, + /// Native task status. + pub status: String, +} + +impl Default for Event { + fn default() -> Self { + Self { + kind: EventKind::Other(String::new()), + run_id: String::new(), + thread_id: String::new(), + received_at: SystemTime::UNIX_EPOCH, + raw: String::new(), + payload: EventPayload::Other, + structured_output: Default::default(), + invocation_usage: Default::default(), + session_usage: Default::default(), + parent_tool_use_id: Default::default(), + result_index: Default::default(), + failure_reason: Default::default(), + delta: Default::default(), + task: Default::default(), + } + } +} + +/// Native counters scoped to a single agent task. +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Deserialize)] +#[serde(default)] +pub struct TaskUsage { + /// Task duration in milliseconds. + pub duration_ms: i64, + /// Number of tool uses attributed to this task. + pub tool_uses: i64, + /// Number of tokens attributed to this task. + pub total_tokens: i64, +} diff --git a/crates/codexcw/src/grok.rs b/crates/codexcw/src/grok.rs index 4665c48..9c079b3 100644 --- a/crates/codexcw/src/grok.rs +++ b/crates/codexcw/src/grok.rs @@ -50,6 +50,9 @@ pub(crate) fn prepare_grok( args.push("--cwd".to_string()); args.push(dir); } + if req.include_partial_messages { + args.push("--include-partial-messages".to_string()); + } if let Some(model) = nonempty(&req.model) { args.push("--model".to_string()); args.push(model); @@ -145,7 +148,7 @@ fn validate_grok_request(req: &Request) -> Result<(), Error> { )); } - let unsupported: [(bool, &str); 13] = [ + let unsupported: [(bool, &str); 14] = [ (!req.add_dirs.is_empty(), "add dirs"), (!req.images.is_empty(), "images"), (!req.config.is_empty(), "config overrides"), @@ -163,6 +166,7 @@ fn validate_grok_request(req: &Request) -> Result<(), Error> { "output last message path", ), (req.dangerously_bypass_hooks, "dangerously bypass hooks"), + (nonempty(&req.fork_id).is_some(), "fork id"), (req.resume_all, "resume all"), ]; for (set, name) in unsupported { diff --git a/crates/codexcw/src/lib.rs b/crates/codexcw/src/lib.rs index 881e1e4..672491d 100644 --- a/crates/codexcw/src/lib.rs +++ b/crates/codexcw/src/lib.rs @@ -59,6 +59,7 @@ mod account_usage; mod args; mod claude; mod claude_account_usage; +mod codex_items; mod decoder; mod error; mod event; @@ -78,10 +79,11 @@ pub use claude_account_usage::{ get_claude_account_usage, ClaudeAccountUsage, ClaudeAccountUsageRequest, ClaudeAccountUsageWindow, }; +pub use codex_items::{McpCall, McpResult, TodoStep, WebSearch, WebSearchAction, WebSearchResult}; pub use error::{Error, GroupError}; pub use event::{ CodexErrorEvent, ErrorPayload, Event, EventKind, EventPayload, FileChange, Item, ItemKind, - ModelUsage, Usage, + ModelUsage, StreamDelta, TaskUpdate, TaskUsage, Usage, }; pub use group::{Group, GroupResult, ManyOptions, RunEvent}; pub use request::{ diff --git a/crates/codexcw/src/request.rs b/crates/codexcw/src/request.rs index 787dfc3..e4356e2 100644 --- a/crates/codexcw/src/request.rs +++ b/crates/codexcw/src/request.rs @@ -151,6 +151,10 @@ impl ConfigOverride { /// `..Default::default()`. #[derive(Clone, Debug, Default)] pub struct Request { + /// Codex thread to fork into a new thread. + pub fork_id: Option, + /// Request incremental Messages events from Claude or Grok. + pub include_partial_messages: bool, /// User instruction sent to the agent. pub prompt: String, /// Additional prompt input, or extra context when `prompt` is set. diff --git a/crates/codexcw/src/runner.rs b/crates/codexcw/src/runner.rs index 0f5e676..1c2c78c 100644 --- a/crates/codexcw/src/runner.rs +++ b/crates/codexcw/src/runner.rs @@ -249,6 +249,9 @@ impl Runner { temp_files: prepared.temp_files, decoder: EventDecoder::for_agent(self.inner.agent), agent: self.inner.agent, + resumed: req.resume_id.as_ref().is_some_and(|s| !s.is_empty()) + || req.resume_last + || req.fork_id.as_ref().is_some_and(|s| !s.is_empty()), })); Ok(Session { @@ -390,6 +393,7 @@ struct CollectCtx { temp_files: Vec, decoder: EventDecoder, agent: Agent, + resumed: bool, } pub(crate) async fn drain_stderr(mut stderr: ChildStderr, tail: Arc) { @@ -429,13 +433,18 @@ async fn collect(ctx: CollectCtx) { temp_files, mut decoder, agent, + resumed, } = ctx; let started_at = SystemTime::now(); let mut events: Vec = Vec::new(); let mut last_event: Option = None; let mut final_message = String::new(); + let mut has_final_answer = false; let mut usage = Usage::default(); + let mut invocation_usage = None; + let mut session_usage = None; + let mut structured_output = None; let mut current_thread = String::new(); let mut run_err: Option = None; @@ -502,20 +511,34 @@ async fn collect(ctx: CollectCtx) { event.thread_id = current_thread.clone(); } if let EventPayload::ItemCompleted(item) = &event.payload { - if item.kind == ItemKind::AgentMessage { - final_message = item.text.clone(); + let is_final_answer = item.phase.as_deref() == Some("final_answer"); + if item.kind == ItemKind::AgentMessage + && event.parent_tool_use_id.is_empty() + && (is_final_answer || !has_final_answer) + { + final_message.clone_from(&item.text); + has_final_answer = is_final_answer; } } - if let EventPayload::TurnCompleted { usage: turn_usage } = &event.payload { - usage = turn_usage.clone(); - } - if let EventPayload::TurnFailed { + if let EventPayload::TurnCompleted { usage: turn_usage } + | EventPayload::TurnFailed { usage: turn_usage, .. } = &event.payload { usage = turn_usage.clone(); + if event.invocation_usage.is_none() && !resumed { + event.invocation_usage = event.session_usage.clone(); + } + if let Some(snapshot) = &event.invocation_usage { + invocation_usage = Some(snapshot.clone()); + } + if let Some(snapshot) = &event.session_usage { + session_usage = Some(snapshot.clone()); + } + if let Some(output) = &event.structured_output { + structured_output = Some(output.clone()); + } } - last_event = Some(event.clone()); events.push(event.clone()); @@ -541,6 +564,9 @@ async fn collect(ctx: CollectCtx) { let finished_at = SystemTime::now(); let report = RunResult { + invocation_usage, + session_usage, + structured_output, run_id, thread_id: current_thread, final_message, diff --git a/crates/codexcw/src/session.rs b/crates/codexcw/src/session.rs index 3299446..5cb3b30 100644 --- a/crates/codexcw/src/session.rs +++ b/crates/codexcw/src/session.rs @@ -14,13 +14,19 @@ use crate::event::{Event, Usage}; /// Summary of a completed agent invocation. #[derive(Clone, Debug)] pub struct RunResult { + /// Structured result reported by the agent. + pub structured_output: Option, + /// Usage attributable to this invocation when available. + pub invocation_usage: Option, + /// Cumulative session usage when reported. + pub session_usage: Option, /// Wrapper-assigned run id. pub run_id: String, /// Agent thread or session id once known. pub thread_id: String, /// Last completed `agent_message` text. pub final_message: String, - /// Token usage from the last `turn.completed`. + /// Legacy counters from the last terminal turn event. pub usage: Usage, /// Every decoded event retained by the run. pub events: Vec, diff --git a/crates/codexcw/tests/fixtures/streams/claude.jsonl b/crates/codexcw/tests/fixtures/streams/claude.jsonl new file mode 100644 index 0000000..50b9193 --- /dev/null +++ b/crates/codexcw/tests/fixtures/streams/claude.jsonl @@ -0,0 +1,11 @@ +{"type":"system","subtype":"init","session_id":"session"} +{"type":"assistant","message":{"content":[{"type":"text","text":"waiting"}]}} +{"type":"system","subtype":"task_started","description":"Check the sample","task_id":"child","tool_use_id":"call","run_id":"task-run"} +{"type":"assistant","message":{"content":[{"type":"text","text":"child answer"}]},"parent_tool_use_id":"call"} +{"type":"system","subtype":"task_notification","summary":"Sample checked","usage":{"duration_ms":120,"tool_uses":2,"total_tokens":17},"task_id":"child","tool_use_id":"call","status":"completed"} +{"type":"system","subtype":"init","session_id":"session"} +{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"fin"}}} +{"type":"assistant","message":{"content":[{"type":"text","text":"finished"}]}} +{"type":"result","subtype":"success","result":"waiting","result_index":0,"usage":{"input_tokens":8,"output_tokens":4,"output_tokens_details":{"thinking_tokens":1}},"modelUsage":{"model":{"inputTokens":60,"outputTokens":18,"thinkingTokens":1,"costUSD":0.08}},"model_usage_since_last_result":{"model":{"inputTokens":12,"outputTokens":6,"thinkingTokens":1,"costUSD":0.01}},"total_cost_usd":0.08,"structured_output":{"ok":true}} +{"type":"result","subtype":"success","result":"waiting","result_index":0,"usage":{"input_tokens":8,"output_tokens":4,"output_tokens_details":{"thinking_tokens":1}},"modelUsage":{"model":{"inputTokens":60,"outputTokens":18,"thinkingTokens":1,"costUSD":0.08}},"model_usage_since_last_result":{"model":{"inputTokens":12,"outputTokens":6,"thinkingTokens":1,"costUSD":0.01}},"total_cost_usd":0.08,"structured_output":{"ok":true}} +{"type":"result","subtype":"success","result":"finished","result_index":1,"usage":{"input_tokens":4,"output_tokens":4,"output_tokens_details":{"thinking_tokens":3}},"modelUsage":{"model":{"inputTokens":62,"outputTokens":22,"thinkingTokens":4,"costUSD":0.09}},"model_usage_since_last_result":{"model":{"inputTokens":2,"outputTokens":4,"thinkingTokens":3,"costUSD":0.01}},"total_cost_usd":0.09} diff --git a/crates/codexcw/tests/fixtures/streams/codex-commentary.jsonl b/crates/codexcw/tests/fixtures/streams/codex-commentary.jsonl new file mode 100644 index 0000000..f37d8b6 --- /dev/null +++ b/crates/codexcw/tests/fixtures/streams/codex-commentary.jsonl @@ -0,0 +1,3 @@ +{"type":"item.completed","item":{"type":"agent_message","phase":"commentary","text":"Starting"}} +{"type":"item.completed","item":{"type":"agent_message","phase":"commentary","text":"Checked two files"}} +{"type":"turn.completed","usage":{"input_tokens":5,"output_tokens":2}} diff --git a/crates/codexcw/tests/fixtures/streams/codex.jsonl b/crates/codexcw/tests/fixtures/streams/codex.jsonl new file mode 100644 index 0000000..adc134d --- /dev/null +++ b/crates/codexcw/tests/fixtures/streams/codex.jsonl @@ -0,0 +1,13 @@ +{"type":"thread.started","thread_id":"thread-demo"} +{"type":"turn.started"} +{"type":"item.started","item":{"id":"plan","type":"todo_list","items":[{"text":"Find source","completed":false}]}} +{"type":"item.updated","item":{"id":"plan","type":"todo_list","items":[{"text":"Find source","completed":true}]}} +{"type":"item.started","item":{"id":"search","type":"web_search","query":"","action":{"type":"other","queries":null}}} +{"type":"item.completed","item":{"id":"search","type":"web_search","query":"sample","action":{"type":"search","query":"sample"},"results":[{"type":"search_result","domain":"example.org","ref_id":"ref-demo","snippet":"Excerpt","title":"Example","url":"https://example.org/"},{"type":"error","reason":"unavailable"}]}} +{"type":"item.completed","item":{"id":"empty","type":"web_search","query":"sample","action":{"type":"open_page","url":"https://example.org/"},"results":[]}} +{"type":"item.completed","item":{"id":"mcp","type":"mcp_tool_call","server":"probe","tool":"color","arguments":{},"result":{"content":[{"type":"text","text":"GOLD"}],"structured_content":{"color":"GOLD"},"_meta":{"source":"demo"}},"error":null,"status":"completed"}} +{"type":"item.completed","item":{"id":"denied","type":"mcp_tool_call","server":"probe","tool":"color","arguments":{},"result":null,"error":{"message":"approval required"},"status":"failed"}} +{"type":"item.completed","item":{"id":"plan","type":"todo_list","items":[{"text":"Find source","completed":true}]}} +{"type":"item.completed","item":{"id":"response","type":"agent_message","text":"DONE","phase":"final_answer"}} +{"type":"item.completed","item":{"id":"aside","type":"agent_message","text":"Later note","phase":"commentary"}} +{"type":"turn.completed","usage":{"input_tokens":20,"cached_input_tokens":8,"cache_write_input_tokens":3,"output_tokens":5,"reasoning_output_tokens":1}} diff --git a/crates/codexcw/tests/fixtures/streams/grok.jsonl b/crates/codexcw/tests/fixtures/streams/grok.jsonl new file mode 100644 index 0000000..79bcebe --- /dev/null +++ b/crates/codexcw/tests/fixtures/streams/grok.jsonl @@ -0,0 +1,6 @@ +{"type":"system","subtype":"init","session_id":"session"} +{"type":"assistant","message":{"content":[{"type":"tool_use","id":"shell","name":"run_terminal_command","input":{"command":"exit 7"}}]}} +{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"shell","is_error":false,"content":"{\"type\":\"Bash\",\"exit_code\":7,\"output\":[111,107]}"}]}} +{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"fin"}}} +{"type":"assistant","message":{"content":[{"type":"text","text":"done"}]}} +{"type":"result","subtype":"success","is_error":false,"result":"done","structured_output":{"ok":true},"usage":{"input_tokens":10,"output_tokens":2}} diff --git a/crates/codexcw/tests/fixtures/streams/replay.sh b/crates/codexcw/tests/fixtures/streams/replay.sh new file mode 100755 index 0000000..79db9f1 --- /dev/null +++ b/crates/codexcw/tests/fixtures/streams/replay.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Replay an agent capture while verifying the caller's optional CLI flag. +set -eu +if [ -n "${EXPECT_FLAG:-}" ]; then + found=false + for arg do + if [ "$arg" = "$EXPECT_FLAG" ]; then found=true; fi + done + "$found" || exit 2 +fi +cat "$STREAM_FIXTURE" +exit "${STREAM_EXIT:-0}" diff --git a/crates/codexcw/tests/fixtures/streams/startup-failure.jsonl b/crates/codexcw/tests/fixtures/streams/startup-failure.jsonl new file mode 100644 index 0000000..21ec80f --- /dev/null +++ b/crates/codexcw/tests/fixtures/streams/startup-failure.jsonl @@ -0,0 +1 @@ +{"type":"result","subtype":"error_during_execution","is_error":true,"startup_failure_reason":"resume_target_not_found","errors":["Session not found"]} diff --git a/crates/codexcw/tests/runner_it.rs b/crates/codexcw/tests/runner_it.rs index 788223d..5d2f051 100644 --- a/crates/codexcw/tests/runner_it.rs +++ b/crates/codexcw/tests/runner_it.rs @@ -662,3 +662,116 @@ done assert_eq!(result.events[0].kind.as_str(), "burst.0"); assert_eq!(result.events[4095].kind.as_str(), "burst.4095"); } + +#[tokio::test] +async fn messages_contract_fixtures() { + use codexcw::Agent; + for agent in [Agent::Claude, Agent::Grok] { + let fake = write_fake_codex(r#"cat "$STREAM_FIXTURE""#); + let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/streams") + .join(format!("{}.jsonl", agent.as_str())); + let result = Runner::builder() + .agent(agent) + .executable(fake.executable()) + .env("STREAM_FIXTURE", fixture.to_str().unwrap()) + .build() + .run(Request::new("x")) + .await + .unwrap(); + assert_eq!( + result.structured_output, + Some(serde_json::json!({"ok":true})) + ); + assert!(result + .events + .iter() + .any(|ev| ev.delta.as_ref().is_some_and(|d| d.text == "fin"))); + if agent == Agent::Claude { + assert_eq!(result.final_message, "finished"); + assert_eq!(result.session_usage.unwrap().total_tokens, 84); + assert_eq!(result.invocation_usage.unwrap().total_tokens, 24); + assert_eq!(result.usage.reasoning_output_tokens, 3); + assert!(result + .events + .iter() + .any(|ev| ev.parent_tool_use_id == "call")); + assert!(result + .events + .iter() + .any(|ev| ev.task.as_ref().is_some_and(|t| t.status == "completed"))); + } else { + assert_eq!(result.final_message, "done"); + assert!(result.session_usage.is_none()); + let shell = result + .events + .iter() + .filter_map(|ev| ev.item_completed()) + .find(|item| item.exit_code == Some(7)) + .unwrap(); + assert_eq!( + (shell.status.as_str(), shell.aggregated_output.as_str()), + ("failed", "ok") + ); + } + } +} + +#[tokio::test] +async fn codex_nullable_item_arrays_keep_the_stream_decodable() { + let fake = write_fake_codex( + r#"cat >/dev/null +cat <<'JSONL' +{"type":"item.started","item":{"type":"web_search","action":{"type":"search","query":"sample","queries":null},"results":null}} +{"type":"item.completed","item":{"type":"mcp_tool_call","result":{"content":null}}} +{"type":"item.updated","item":{"type":"todo_list","items":null}} +{"type":"item.completed","item":{"type":"collab_tool_call","receiver_thread_ids":null}} +{"type":"item.completed","item":{"type":"file_change","changes":null}} +JSONL"#, + ); + let result = runner_for(&fake).run(Request::new("decode")).await.unwrap(); + let first = result.events[0].item_started().unwrap(); + let search = first.web_search.as_ref().unwrap(); + assert!(search.action.as_ref().unwrap().queries.is_empty()); + assert!(search.results.is_none()); + assert!(first.raw.contains(r#""queries":null"#)); + let mcp = result.events[1] + .item_completed() + .unwrap() + .mcp + .as_ref() + .unwrap(); + assert!(mcp.result.as_ref().unwrap().content.is_empty()); + assert!(result.events[2].item_updated().unwrap().todos.is_none()); + assert!(result.events[3] + .item_completed() + .unwrap() + .receiver_thread_ids + .is_empty()); + assert!(result.events[4] + .item_completed() + .unwrap() + .changes + .is_empty()); +} + +#[tokio::test] +async fn codex_final_message_phases() { + let fake = write_fake_codex(r#"cat "$STREAM_FIXTURE""#); + for (name, expected) in [ + ("codex-commentary.jsonl", "Checked two files"), + ("codex.jsonl", "DONE"), + ] { + let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/streams") + .join(name); + let result = Runner::builder() + .executable(fake.executable()) + .env("STREAM_FIXTURE", fixture.to_str().unwrap()) + .build() + .run(Request::new("x")) + .await + .unwrap(); + assert_eq!(result.final_message, expected); + } +} diff --git a/decoder.go b/decoder.go index 8d2c899..8f6dfcd 100644 --- a/decoder.go +++ b/decoder.go @@ -7,18 +7,22 @@ import ( ) type wireEvent struct { - Type EventType `json:"type"` - ThreadID string `json:"thread_id"` - Usage Usage `json:"usage"` - Item json.RawMessage `json:"item"` - Error json.RawMessage `json:"error"` - Message string `json:"message"` + Type EventType `json:"type"` + ThreadID string `json:"thread_id"` + Usage *struct { + Usage + CacheWrite *int64 `json:"cache_write_input_tokens"` + } `json:"usage"` + Item json.RawMessage `json:"item"` + Error json.RawMessage `json:"error"` + Message string `json:"message"` } type wireItem struct { ID string `json:"id"` Type ItemType `json:"type"` Status string `json:"status"` + Phase string `json:"phase"` Text string `json:"text"` Message string `json:"message"` Command string `json:"command"` @@ -49,6 +53,15 @@ func decodeEvent(line []byte, runID string, threadID string, now time.Time) (Eve Raw: raw, } + var usage Usage + if wire.Usage != nil && (wire.Type == EventTurnCompleted || wire.Type == EventTurnFailed) { + usage = wire.Usage.Usage + if wire.Usage.CacheWrite != nil { + usage.CacheCreationInputTokens = *wire.Usage.CacheWrite + } + usage = normalizeCodexUsage(usage) + event.SessionUsage = &usage + } switch wire.Type { case EventThreadStarted: event.ThreadID = wire.ThreadID @@ -56,11 +69,11 @@ func decodeEvent(line []byte, runID string, threadID string, now time.Time) (Eve case EventTurnStarted: event.TurnStarted = &TurnStartedEvent{} case EventTurnCompleted: - event.TurnCompleted = &TurnCompletedEvent{Usage: normalizeCodexUsage(wire.Usage)} + event.TurnCompleted = &TurnCompletedEvent{Usage: usage} case EventTurnFailed: event.TurnFailed = &TurnFailedEvent{ Error: decodeEventError(wire.Error), - Usage: normalizeCodexUsage(wire.Usage), + Usage: usage, } case EventItemStarted: item, err := decodeItem(wire.Item) @@ -68,6 +81,12 @@ func decodeEvent(line []byte, runID string, threadID string, now time.Time) (Eve return Event{}, err } event.ItemStarted = &ItemEvent{Item: item} + case EventItemUpdated: + item, err := decodeItem(wire.Item) + if err != nil { + return Event{}, err + } + event.ItemUpdated = &ItemEvent{Item: item} case EventItemCompleted: item, err := decodeItem(wire.Item) if err != nil { @@ -92,7 +111,8 @@ func decodeItem(raw json.RawMessage) (Item, error) { if err := json.Unmarshal(raw, &wire); err != nil { return Item{}, err } - return Item{ + item := Item{ + Phase: wire.Phase, ID: wire.ID, Type: wire.Type, Status: wire.Status, @@ -106,7 +126,43 @@ func decodeItem(raw json.RawMessage) (Item, error) { Tool: wire.Tool, SenderThreadID: wire.SenderThreadID, ReceiverThreadIDs: wire.ReceiverThreadIDs, - }, nil + } + var err error + switch item.Type { + case ItemWebSearch: + err = json.Unmarshal(raw, &item.WebSearch) + case ItemMCPToolCall: + var call struct { + MCPCall + Error *ErrorPayload `json:"error"` + } + err = json.Unmarshal(raw, &call) + if call.Error != nil { + call.MCPCall.Error = call.Error.Message + } + call.Arguments = optionalJSON(call.Arguments) + if call.Result != nil { + call.Result.StructuredContent = optionalJSON(call.Result.StructuredContent) + call.Result.Meta = optionalJSON(call.Result.Meta) + } + item.MCP = &call.MCPCall + case ItemTodoList: + var list struct { + Items []TodoStep `json:"items"` + } + err = json.Unmarshal(raw, &list) + item.Todos = list.Items + } + return item, err +} + +// RawMessage keeps a literal JSON null as four bytes. Optional projections +// treat it as absent while Item.Raw preserves the full wire representation. +func optionalJSON(value json.RawMessage) json.RawMessage { + if string(value) == "null" { + return nil + } + return value } // normalizeCodexUsage derives the total when Codex omits total_tokens. diff --git a/docs/architecture.md b/docs/architecture.md index 5082656..d6d993b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -45,6 +45,36 @@ implements all of it for the Rust crate and the FFI bindings: The core depends on no FFI crate, so `cargo publish -p codexcw` ships a clean library and the public API never leaks `napi`/`pyo3` types. +## Reading stream results + +`usage` contains the token counters from the terminal event. For accounting, +use the latest `invocation_usage` snapshot for a single call or the latest +`session_usage` snapshot for the cumulative total. Both fields are optional. + +| Agent | Available usage snapshots | +| --- | --- | +| Codex | `session_usage` counts tokens across the thread, including cache writes. A new thread also exposes this balance as `invocation_usage`. | +| Claude | `invocation_usage` sums per-model deltas across distinct result indices. A new session can also use its session totals. `session_usage` includes subagents. Output tokens include thinking tokens. | +| Grok | `invocation_usage` contains the counters from the terminal Messages result. | + +Claude and Grok accept `include_partial_messages`. A partial event carries a +delta kind, block index and text or JSON fragment. Applications can render those +fragments while a tool call is in progress. The completed message still arrives. +Use the completed block for persistence. The raw event retains stream boundaries +and provider-specific fields. Claude's parent tool-use ID and task updates link +child messages to the tool that launched them. A Claude task notification may +include its summary, duration, tool count and token count. A failed result can also carry a +machine-readable failure reason before the first session event. When the CLI +returns a structured result, the terminal event exposes its JSON value. The run +report retains the most recent structured value across result frames. + +Codex emits checklist snapshots on `item.updated` and exposes web-search actions, +optional results and MCP arguments, results and errors on items. A search +result list is optional. An empty list represents a search with zero results. +A failed shell or MCP item may belong to a successful turn. The report uses the +latest root `final_answer` when present and falls back to the last completed +root message. The event stream includes messages from every phase. + ## Bindings Both bindings translate the core to their ecosystem and reuse the same diff --git a/docs/examples/csharp.md b/docs/examples/csharp.md index 54349f4..35098c2 100644 --- a/docs/examples/csharp.md +++ b/docs/examples/csharp.md @@ -310,6 +310,20 @@ await runner.RunAsync(new Request }); ``` +## Reading stream results + +Set `IncludePartialMessages` on a Claude or Grok request to receive incremental +content blocks. The completed assistant message still arrives. With a Claude or +Grok output schema, read `StructuredOutput` on the run result for the agent's JSON +value. Use `InvocationUsage` to account for this call and `SessionUsage` +to display cumulative usage when the CLI supplies it. Grok's native +`streaming-json` format can report `reasoning_tokens`. The wrapper uses +`streaming-messages-json` for its message and tool blocks. + +For Codex, pass `ForkId` with a prompt to branch from an existing thread. +The result carries the new thread ID. Resume and fork requests inherit prior +usage, so only the session total is available for them. + ## Reasoning effort `Effort` sets the reasoning effort for one run. Codex receives it as diff --git a/docs/examples/go.md b/docs/examples/go.md index 2546e1e..00a1b54 100644 --- a/docs/examples/go.md +++ b/docs/examples/go.md @@ -291,6 +291,20 @@ _, _ = runner.Run(ctx, codexcw.Request{ }) ``` +## Reading stream results + +Set `IncludePartialMessages` on a Claude or Grok request to receive incremental +content blocks. The completed assistant message still arrives. With a Claude or +Grok output schema, read `StructuredOutput` on the run result for the agent's JSON +value. Use `InvocationUsage` to account for this call and `SessionUsage` +to display cumulative usage when the CLI supplies it. Grok's native +`streaming-json` format can report `reasoning_tokens`. The wrapper uses +`streaming-messages-json` for its message and tool blocks. + +For Codex, pass `ForkID` with a prompt to branch from an existing thread. +The result carries the new thread ID. Resume and fork requests inherit prior +usage, so only the session total is available for them. + ## Reasoning effort `Effort` sets the reasoning effort for one run. Codex receives it as diff --git a/docs/examples/python.md b/docs/examples/python.md index 421759a..868c61c 100644 --- a/docs/examples/python.md +++ b/docs/examples/python.md @@ -264,6 +264,20 @@ runner.run(req) await runner.run(req) ``` +## Reading stream results + +Set `include_partial_messages` on a Claude or Grok request to receive incremental +content blocks. The completed assistant message still arrives. With a Claude or +Grok output schema, read `structured_output` on the run result for the agent's JSON +value. Use `invocation_usage` to account for this call and `session_usage` +to display cumulative usage when the CLI supplies it. Grok's native +`streaming-json` format can report `reasoning_tokens`. The wrapper uses +`streaming-messages-json` for its message and tool blocks. + +For Codex, pass `fork_id` with a prompt to branch from an existing thread. +The result carries the new thread ID. Resume and fork requests inherit prior +usage, so only the session total is available for them. + ## Reasoning effort `effort` sets the reasoning effort for one run. Codex receives it as diff --git a/docs/examples/rust.md b/docs/examples/rust.md index 573f374..29879c3 100644 --- a/docs/examples/rust.md +++ b/docs/examples/rust.md @@ -300,6 +300,20 @@ runner.run(Request { }).await?; ``` +## Reading stream results + +Set `include_partial_messages` on a Claude or Grok request to receive incremental +content blocks. The completed assistant message still arrives. With a Claude or +Grok output schema, read `structured_output` on the run result for the agent's JSON +value. Use `invocation_usage` to account for this call and `session_usage` +to display cumulative usage when the CLI supplies it. Grok's native +`streaming-json` format can report `reasoning_tokens`. The wrapper uses +`streaming-messages-json` for its message and tool blocks. + +For Codex, pass `fork_id` with a prompt to branch from an existing thread. +The result carries the new thread ID. Resume and fork requests inherit prior +usage, so only the session total is available for them. + ## Reasoning effort `effort` sets the reasoning effort for one run. Codex receives it as diff --git a/docs/examples/typescript.md b/docs/examples/typescript.md index 0257a4b..81b4afe 100644 --- a/docs/examples/typescript.md +++ b/docs/examples/typescript.md @@ -210,6 +210,20 @@ await runner.run({ await runner.run({ prompt: '...', model: 'o3', profile: 'work' }) ``` +## Reading stream results + +Set `includePartialMessages` on a Claude or Grok request to receive incremental +content blocks. The completed assistant message still arrives. With a Claude or +Grok output schema, read `structuredOutput` on the run result for the agent's JSON +value. Use `invocationUsage` to account for this call and `sessionUsage` +to display cumulative usage when the CLI supplies it. Grok's native +`streaming-json` format can report `reasoning_tokens`. The wrapper uses +`streaming-messages-json` for its message and tool blocks. + +For Codex, pass `forkId` with a prompt to branch from an existing thread. +The result carries the new thread ID. Resume and fork requests inherit prior +usage, so only the session total is available for them. + ## Reasoning effort `effort` sets the reasoning effort for one run. Codex receives it as diff --git a/dotnet/Codexcw.Tests/ArgsTests.cs b/dotnet/Codexcw.Tests/ArgsTests.cs index e54bda9..6c318b8 100644 --- a/dotnet/Codexcw.Tests/ArgsTests.cs +++ b/dotnet/Codexcw.Tests/ArgsTests.cs @@ -7,6 +7,19 @@ public sealed class CodexArgsTests private static PreparedRun Prepare(Request request) => CodexArgs.Prepare(request, SandboxMode.ReadOnly, ApprovalPolicy.Never); + [Fact] + public void ForkUsesExplicitParent() + { + var request = new Request { Prompt = "go", ForkId = "parent" }; + var args = Prepare(request).Args; + Assert.Equal(new[] { "exec", "fork" }, args.Take(2)); + Assert.Equal(new[] { "parent", "-" }, args.TakeLast(2)); + Assert.Contains("sandbox_mode=\"read-only\"", args); + Assert.Throws(() => Prepare(request with { ResumeLast = true })); + Assert.Throws(() => Prepare(request with { ResumeAll = true })); + Assert.Throws(() => Prepare(new Request { Prompt = "go", IncludePartialMessages = true })); + } + [Fact] public void DefaultsAreAutomationFriendly() { diff --git a/dotnet/Codexcw.Tests/ClaudeDecoderTests.cs b/dotnet/Codexcw.Tests/ClaudeDecoderTests.cs index 182d400..13f78f8 100644 --- a/dotnet/Codexcw.Tests/ClaudeDecoderTests.cs +++ b/dotnet/Codexcw.Tests/ClaudeDecoderTests.cs @@ -5,6 +5,100 @@ public sealed class ClaudeDecoderTests private static IReadOnlyList Decode(ClaudeDecoder decoder, string line, string threadId = "") => decoder.Decode(line, "run-1", threadId, DateTimeOffset.Now); + [UnixOnlyFact] + public async Task MessagesContractFixtures() + { + using var dir = new FakeAgentDir(); + var fake = dir.WriteFakeCodex("cat \"$STREAM_FIXTURE\""); + foreach (var agent in new[] { Agent.Claude, Agent.Grok }) + { + var name = agent == Agent.Claude ? "claude" : "grok"; + var fixture = Path.Combine(AppContext.BaseDirectory, "fixtures", name + ".jsonl"); + var runner = new Runner(new RunnerOptions { Agent = agent, Executable = fake, Env = [$"STREAM_FIXTURE={fixture}"] }); + var result = await runner.RunAsync(new Request { Prompt = "x" }); + Assert.True(result.StructuredOutput!.Value.GetProperty("ok").GetBoolean()); + Assert.Contains(result.Events, e => e.Delta?.Text == "fin"); + if (agent == Agent.Claude) + { + Assert.Equal("finished", result.FinalMessage); + Assert.Equal(84, result.SessionUsage!.TotalTokens); + Assert.Equal(24, result.InvocationUsage!.TotalTokens); + Assert.Equal(3, result.Usage.ReasoningOutputTokens); + Assert.Contains(result.Events, e => e.ParentToolUseId == "call"); + Assert.Contains(result.Events, e => e.Task?.Status == "completed"); + } + else + { + Assert.Equal("done", result.FinalMessage); + Assert.Null(result.SessionUsage); + Assert.Contains(result.Events, e => e.ItemCompleted?.Item is + { Status: "failed", ExitCode: 7, AggregatedOutput: "ok" }); + } + } + } + + [UnixOnlyFact] + public async Task MalformedFailureReasonReportsSourceLine() + { + using var dir = new FakeAgentDir(); + const string malformed = """{"type":"result","is_error":true,"startup_failure_reason":5}"""; + var fake = dir.WriteFakeCodex($$""" + cat >/dev/null + cat <<'JSON' + {"type":"system","subtype":"init","session_id":"probe"} + {{malformed}} + JSON + """); + var error = await Assert.ThrowsAsync(() => + dir.NewRunner(fake, Agent.Claude).RunAsync(new Request { Prompt = "hi" })); + Assert.Equal(2, error.Line); + Assert.Equal(malformed, error.Raw); + Assert.IsType(error.InnerException); + } + + [Fact] + public void ResultTextHistoryByParent() + { + var decoder = new ClaudeDecoder(); + (string Line, int ExpectedItems)[] frames = + [ + ("""{"type":"assistant","message":{"content":[{"type":"text","text":"older"}]}}""", 1), + ("""{"type":"assistant","message":{"content":[{"type":"text","text":"latest"}]}}""", 1), + ("""{"type":"result","result":"older"}""", 0), + ("""{"type":"result","result":"new"}""", 1), + ("""{"type":"result","result":"new"}""", 0), + ("""{"type":"result","result":"new","parent_tool_use_id":"child"}""", 1), + ("""{"type":"result","result":"new","parent_tool_use_id":"child"}""", 0), + ("""{"type":"assistant","message":{"content":[{"type":"text","text":"child only"}]},"parent_tool_use_id":"child"}""", 1), + ("""{"type":"result","result":"child only"}""", 1), + ]; + foreach (var (line, expectedItems) in frames) + { + Assert.Equal(expectedItems, Decode(decoder, line).Count(e => e.ItemCompleted is not null)); + } + } + + [Theory] + [InlineData("""{"type":"result","is_error":false,"subtype":"success","terminal_reason":"completed"}""", false, "")] + [InlineData("""{"type":"result","is_error":true,"subtype":"success"}""", true, "")] + [InlineData("""{"type":"result","is_error":true,"subtype":"error_max_turns","terminal_reason":"","startup_failure_reason":""}""", true, "error_max_turns")] + [InlineData("""{"type":"result","is_error":true,"subtype":"error_during_execution","startup_failure_reason":"","terminal_reason":"max_turns"}""", true, "max_turns")] + [InlineData("""{"type":"result","is_error":true,"subtype":"error_during_execution","startup_failure_reason":"resume_target_not_found","terminal_reason":"other"}""", true, "resume_target_not_found")] + public void ResultFailureReasons(string line, bool failed, string reason) + { + var result = Assert.Single(Decode(new ClaudeDecoder(), line)); + Assert.Equal(failed, result.TurnFailed is not null); + Assert.Equal(reason, result.FailureReason); + } + + [Theory] + [InlineData("""{"type":"result","is_error":true,"startup_failure_reason":42}""")] + [InlineData("""{"type":"result","is_error":true,"terminal_reason":{}}""")] + public void InvalidReasonTypeRaisesFormatException(string line) + { + Assert.Throws(() => Decode(new ClaudeDecoder(), line)); + } + [Fact] public void InitEmitsThreadStartedAndTurnStarted() { diff --git a/dotnet/Codexcw.Tests/CodexDecoderTests.cs b/dotnet/Codexcw.Tests/CodexDecoderTests.cs index 5aeeb03..d966bef 100644 --- a/dotnet/Codexcw.Tests/CodexDecoderTests.cs +++ b/dotnet/Codexcw.Tests/CodexDecoderTests.cs @@ -9,6 +9,49 @@ private static Event DecodeOne(string line, string threadId = "") return events[0]; } + [UnixOnlyFact] + public async Task MalformedCodexArraysReportTheOffendingStreamLine() + { + using var dir = new FakeAgentDir(); + foreach (var item in new[] + { + """{"type":"todo_list","items":{}}""", + """{"type":"web_search","results":false}""", + """{"type":"mcp_tool_call","result":{"content":"bad"}}""", + }) + { + var line = $$"""{"type":"item.completed","item":{{item}}}"""; + var fake = dir.WriteFakeCodex($$""" + cat >/dev/null + printf '%s\n' '{"type":"thread.started","thread_id":"test"}' '{{line}}' + """); + var error = await Assert.ThrowsAsync(() => + dir.NewRunner(fake).RunAsync(new Request { Prompt = "decode" })); + Assert.Equal(2, error.Line); + Assert.Equal(line, error.Raw); + Assert.Contains("expected array", error.Message, StringComparison.Ordinal); + } + } + + [Fact] + public void DecodesCodexStreamProjections() + { + var events = File.ReadLines(Path.Combine(AppContext.BaseDirectory, "fixtures", "codex.jsonl")) + .Select(line => DecodeOne(line)).ToList(); + Assert.True(Assert.Single(events[3].ItemUpdated!.Item.Todos!).Completed); + Assert.Null(events[4].ItemStarted!.Item.WebSearch!.Results); + var results = events[5].ItemCompleted!.Item.WebSearch!.Results!; + Assert.Equal("Example", results[0].Title); + Assert.Equal("unavailable", results[1].Raw.GetProperty("reason").GetString()); + Assert.Empty(events[6].ItemCompleted!.Item.WebSearch!.Results!); + var mcp = events[7].ItemCompleted!.Item.Mcp!; + Assert.Equal("GOLD", mcp.Result!.StructuredContent!.Value.GetProperty("color").GetString()); + Assert.Equal("approval required", events[8].ItemCompleted!.Item.Mcp!.Error); + Assert.Equal("final_answer", events[10].ItemCompleted!.Item.Phase); + Assert.Equal(3, events[12].TurnCompleted!.Usage.CacheCreationInputTokens); + Assert.Equal(25, events[12].TurnCompleted!.Usage.TotalTokens); + } + [Fact] public void DecodesThreadStarted() { diff --git a/dotnet/Codexcw.Tests/Codexcw.Tests.csproj b/dotnet/Codexcw.Tests/Codexcw.Tests.csproj index dc2463f..2917f34 100644 --- a/dotnet/Codexcw.Tests/Codexcw.Tests.csproj +++ b/dotnet/Codexcw.Tests/Codexcw.Tests.csproj @@ -16,6 +16,7 @@ + diff --git a/dotnet/Codexcw.Tests/RunnerTests.cs b/dotnet/Codexcw.Tests/RunnerTests.cs index 245c085..0b190d3 100644 --- a/dotnet/Codexcw.Tests/RunnerTests.cs +++ b/dotnet/Codexcw.Tests/RunnerTests.cs @@ -6,6 +6,19 @@ public sealed class RunnerTests : IDisposable public void Dispose() => _dir.Dispose(); + [UnixOnlyFact] + public async Task CodexFinalMessagePhases() + { + var fake = _dir.WriteFakeCodex("cat \"$STREAM_FIXTURE\""); + foreach (var (name, expected) in new[] { ("codex-commentary.jsonl", "Checked two files"), ("codex.jsonl", "DONE") }) + { + var fixture = Path.Combine(AppContext.BaseDirectory, "fixtures", name); + var runner = new Runner(new RunnerOptions { Executable = fake, Env = [$"STREAM_FIXTURE={fixture}"] }); + var result = await runner.RunAsync(new Request { Prompt = "x" }); + Assert.Equal(expected, result.FinalMessage); + } + } + [UnixOnlyFact] public async Task RunDecodesEventsAndUsesSafeDefaults() { diff --git a/dotnet/Codexcw/ClaudeArgs.cs b/dotnet/Codexcw/ClaudeArgs.cs index a58cf70..ead3e18 100644 --- a/dotnet/Codexcw/ClaudeArgs.cs +++ b/dotnet/Codexcw/ClaudeArgs.cs @@ -20,6 +20,10 @@ public static PreparedRun Prepare(Request request) } var args = new List { "-p", "--output-format", "stream-json", "--verbose" }; + if (request.IncludePartialMessages) + { + args.Add("--include-partial-messages"); + } if (!string.IsNullOrEmpty(request.Model)) { args.Add("--model"); @@ -110,6 +114,7 @@ private static void Validate(Request request) (request.RequireGitRepo, "require git repo"), (!string.IsNullOrEmpty(request.OutputLastMessagePath), "output last message path"), (request.DangerouslyBypassHooks, "dangerously bypass hooks"), + (!string.IsNullOrEmpty(request.ForkId), "fork id"), (request.ResumeAll, "resume all"), }; foreach (var (set, name) in unsupported) diff --git a/dotnet/Codexcw/ClaudeDecoder.cs b/dotnet/Codexcw/ClaudeDecoder.cs index 02bf23b..cd10939 100644 --- a/dotnet/Codexcw/ClaudeDecoder.cs +++ b/dotnet/Codexcw/ClaudeDecoder.cs @@ -12,7 +12,9 @@ internal sealed class ClaudeDecoder : IEventDecoder private readonly Agent _agent; private readonly Dictionary _pending = []; private readonly Dictionary _blockSequences = []; - private string _lastAgentText = ""; + private Usage _invocation = new(); + private readonly HashSet _seenResults = []; + private readonly HashSet<(string ParentToolUseId, string Text)> _deliveredText = []; public ClaudeDecoder(Agent agent = Agent.Claude) { @@ -38,11 +40,13 @@ public IReadOnlyList Decode(string line, string runId, string threadId, D ThreadId = sessionId.Length > 0 ? sessionId : threadId, ReceivedAt = now, Raw = line, + ParentToolUseId = root.GetString("parent_tool_use_id"), }; return type switch { "system" => DecodeSystem(baseEvent, root, sessionId), + "stream_event" => [DecodeStream(baseEvent, root)], "assistant" => DecodeAssistant(baseEvent, root), "user" => DecodeUser(baseEvent, root), "result" => DecodeResult(baseEvent, root), @@ -50,9 +54,58 @@ public IReadOnlyList Decode(string line, string runId, string threadId, D }; } + private static Event DecodeStream(Event baseEvent, JsonElement root) + { + if (root.GetObject("event") is not { } stream || stream.GetString("type") is not { Length: > 0 } native) + { + return baseEvent; + } + var delta = stream.GetObject("delta"); + var kind = native == "content_block_delta" && delta?.GetString("type") is { Length: > 0 } deltaKind ? deltaKind : native; + var field = kind switch + { + "text_delta" => "text", + "thinking_delta" => "thinking", + "input_json_delta" => "partial_json", + "signature_delta" => "signature", + _ => "", + }; + return baseEvent with + { + Delta = new StreamDelta + { + Kind = kind, + Text = delta?.GetString(field) ?? "", + Index = stream.GetStrictNullableInt("index"), + }, + }; + } + private static IReadOnlyList DecodeSystem(Event baseEvent, JsonElement root, string sessionId) { - if (root.GetStrictString("subtype") != "init") + var subtype = root.GetStrictString("subtype"); + if (subtype.StartsWith("task_", StringComparison.Ordinal)) + { + var status = root.GetString("status"); + var task = new TaskUpdate + { + Description = root.GetString("description"), + Summary = root.GetString("summary"), + Usage = root.GetObject("usage") is { } usage ? new TaskUsage + { + DurationMs = usage.GetStrictLong("duration_ms"), + ToolUses = usage.GetStrictLong("tool_uses"), + TotalTokens = usage.GetStrictLong("total_tokens"), + } : null, + Kind = subtype, + Id = root.GetString("task_id"), + RunId = root.GetString("run_id"), + ToolUseId = root.GetString("tool_use_id"), + Status = status.Length > 0 ? status : root.GetObject("patch")?.GetString("status") ?? "", + }; + return [baseEvent with { Task = task }]; + } + if (subtype != "init") { return [baseEvent]; } @@ -82,7 +135,7 @@ private List DecodeAssistant(Event baseEvent, JsonElement root) switch (block.GetString("type")) { case "text": - _lastAgentText = block.GetString("text"); + _deliveredText.Add((baseEvent.ParentToolUseId, block.GetString("text"))); events.Add(ItemCompleted(baseEvent, new Item { Id = NextBlockId(messageId), @@ -165,7 +218,7 @@ private List DecodeUser(Event baseEvent, JsonElement root) { exitCode = 0; } - item = item with { ExitCode = exitCode }; + item = item with { ExitCode = exitCode, Status = _agent == Agent.Grok && exitCode is not null and not 0 ? "failed" : item.Status }; } if (item.Kind == ItemKind.FileChange && item.Changes.Count > 0) { @@ -203,9 +256,56 @@ private List DecodeUser(Event baseEvent, JsonElement root) private List DecodeResult(Event baseEvent, JsonElement root) { + var startupReason = root.GetStrictString("startup_failure_reason"); + var terminalReason = root.GetStrictString("terminal_reason"); var usage = ResultUsage(root); + var index = root.GetStrictNullableInt("result_index"); + baseEvent = baseEvent with { ResultIndex = index, StructuredOutput = root.GetElement("structured_output")?.Clone() }; + if (_agent == Agent.Grok && (root.GetObject("usage") is not null || root.GetObject("modelUsage") is not null)) + { + baseEvent = baseEvent with { InvocationUsage = usage }; + } + if (_agent == Agent.Claude && root.GetObject("modelUsage") is not null) + { + baseEvent = baseEvent with { SessionUsage = ModelTotals(usage.ModelUsage) with { TotalCostUsd = usage.TotalCostUsd } }; + } + if (_agent == Agent.Claude && root.GetObject("model_usage_since_last_result") is { } delta) + { + if (index is null || _seenResults.Add(index.Value)) + { + var models = new Dictionary(_invocation.ModelUsage); + foreach (var (name, m) in ReadModels(delta)) + { + var old = models.GetValueOrDefault(name) ?? new ModelUsage(); + models[name] = m with + { + InputTokens = old.InputTokens + m.InputTokens, + OutputTokens = old.OutputTokens + m.OutputTokens, + ReasoningOutputTokens = old.ReasoningOutputTokens + m.ReasoningOutputTokens, + CacheReadInputTokens = old.CacheReadInputTokens + m.CacheReadInputTokens, + CacheCreationInputTokens = old.CacheCreationInputTokens + m.CacheCreationInputTokens, + WebSearchRequests = old.WebSearchRequests + m.WebSearchRequests, + CostUsd = old.CostUsd + m.CostUsd, + ContextWindow = m.ContextWindow == 0 ? old.ContextWindow : m.ContextWindow, + MaxOutputTokens = m.MaxOutputTokens == 0 ? old.MaxOutputTokens : m.MaxOutputTokens + }; + } + _invocation = ModelTotals(models); + } + baseEvent = baseEvent with { InvocationUsage = _invocation }; + } if (root.GetStrictBool("is_error")) { + var subtype = root.GetStrictString("subtype"); + var failureReason = startupReason; + if (failureReason.Length == 0) + { + failureReason = terminalReason; + } + if (failureReason.Length == 0 && subtype != "success") + { + failureReason = subtype; + } var message = root.GetStrictString("result"); if (message.Length == 0 && root.GetElement("errors") is { ValueKind: JsonValueKind.Array } errors) @@ -222,6 +322,7 @@ private List DecodeResult(Event baseEvent, JsonElement root) [ baseEvent with { + FailureReason = failureReason, Kind = EventKind.TurnFailed, Type = EventTypes.TurnFailed, TurnFailed = new TurnFailedPayload( @@ -233,7 +334,7 @@ baseEvent with var events = new List(); var result = root.GetStrictString("result"); - if (result.Length > 0 && result != _lastAgentText) + if (result.Length > 0 && _deliveredText.Add((baseEvent.ParentToolUseId, result))) { events.Add(ItemCompleted(baseEvent, new Item { @@ -262,25 +363,7 @@ private static Usage ResultUsage(JsonElement root) var cacheRead = wire?.GetStrictLong("cache_read_input_tokens") ?? 0; var outputTokens = wire?.GetStrictLong("output_tokens") ?? 0; - var modelUsage = new Dictionary(); - if (root.GetObject("modelUsage") is { } models) - { - foreach (var entry in models.EnumerateObject()) - { - var model = entry.Value; - modelUsage[entry.Name] = new ModelUsage - { - InputTokens = model.GetStrictLong("inputTokens"), - OutputTokens = model.GetStrictLong("outputTokens"), - CacheReadInputTokens = model.GetStrictLong("cacheReadInputTokens"), - CacheCreationInputTokens = model.GetStrictLong("cacheCreationInputTokens"), - WebSearchRequests = model.GetStrictLong("webSearchRequests"), - CostUsd = model.GetStrictDouble("costUSD"), - ContextWindow = model.GetStrictLong("contextWindow"), - MaxOutputTokens = model.GetStrictLong("maxOutputTokens"), - }; - } - } + var modelUsage = ReadModels(root.GetObject("modelUsage")); // result.usage covers the root agent only; modelUsage and the cost // also cover subagents. The full-run total comes from modelUsage when @@ -297,6 +380,7 @@ private static Usage ResultUsage(JsonElement root) return new Usage { + ReasoningOutputTokens = wire?.GetObject("output_tokens_details")?.GetLong("thinking_tokens") ?? 0, InputTokens = inputTokens, CachedInputTokens = cacheRead, CacheCreationInputTokens = cacheCreation, @@ -307,6 +391,47 @@ private static Usage ResultUsage(JsonElement root) }; } + private static Dictionary ReadModels(JsonElement? container) + { + var modelUsage = new Dictionary(); + if (container is { } models) + { + foreach (var entry in models.EnumerateObject()) + { + var model = entry.Value; + modelUsage[entry.Name] = new ModelUsage + { + ReasoningOutputTokens = model.GetStrictLong("thinkingTokens"), + InputTokens = model.GetStrictLong("inputTokens"), + OutputTokens = model.GetStrictLong("outputTokens"), + CacheReadInputTokens = model.GetStrictLong("cacheReadInputTokens"), + CacheCreationInputTokens = model.GetStrictLong("cacheCreationInputTokens"), + WebSearchRequests = model.GetStrictLong("webSearchRequests"), + CostUsd = model.GetStrictDouble("costUSD"), + ContextWindow = model.GetStrictLong("contextWindow"), + MaxOutputTokens = model.GetStrictLong("maxOutputTokens"), + }; + } + } + + return modelUsage; + } + + private static Usage ModelTotals(IReadOnlyDictionary models) + { + var totals = new Usage + { + ModelUsage = models, + InputTokens = models.Values.Sum(m => m.InputTokens), + OutputTokens = models.Values.Sum(m => m.OutputTokens), + CachedInputTokens = models.Values.Sum(m => m.CacheReadInputTokens), + CacheCreationInputTokens = models.Values.Sum(m => m.CacheCreationInputTokens), + ReasoningOutputTokens = models.Values.Sum(m => m.ReasoningOutputTokens), + TotalCostUsd = models.Values.Sum(m => m.CostUsd) + }; + return totals with { TotalTokens = totals.InputTokens + totals.OutputTokens + totals.CachedInputTokens + totals.CacheCreationInputTokens }; + } + private Item ToolItem(JsonElement block) { var name = block.GetString("name"); diff --git a/dotnet/Codexcw/CodexArgs.cs b/dotnet/Codexcw/CodexArgs.cs index 50ec12a..9a0eb5f 100644 --- a/dotnet/Codexcw/CodexArgs.cs +++ b/dotnet/Codexcw/CodexArgs.cs @@ -47,8 +47,12 @@ public static PreparedRun Prepare(Request request, SandboxMode defaultSandbox, A { args.Add("resume"); } + else if (!string.IsNullOrEmpty(request.ForkId)) + { + args.Add("fork"); + } - AppendCommonArgs(args, request, schemaPath, resume, defaultSandbox, defaultApproval); + AppendCommonArgs(args, request, schemaPath, resume || !string.IsNullOrEmpty(request.ForkId), defaultSandbox, defaultApproval); if (request.ResumeLast) { @@ -62,6 +66,10 @@ public static PreparedRun Prepare(Request request, SandboxMode defaultSandbox, A { args.Add(request.ResumeId); } + else if (!string.IsNullOrEmpty(request.ForkId)) + { + args.Add(request.ForkId); + } args.Add("-"); return new PreparedRun(args, null, schemaTempPath); @@ -88,14 +96,23 @@ private static void Validate(Request request) { throw new InvalidRequestException("resume id and resume last are mutually exclusive"); } + var fork = !string.IsNullOrEmpty(request.ForkId); + if (request.IncludePartialMessages) + { + throw new InvalidRequestException("partial messages are not supported by codex"); + } + if (fork && (resume || request.ResumeAll)) + { + throw new InvalidRequestException("fork and resume are mutually exclusive"); + } if (request.ResumeAll && !resume) { throw new InvalidRequestException("resume all requires resume id or resume last"); } - if (resume && + if ((resume || fork) && (!string.IsNullOrEmpty(request.Dir) || request.AddDirs.Count > 0 || !string.IsNullOrEmpty(request.Profile))) { - throw new InvalidRequestException("dir, add dirs, and profile are not supported by codex exec resume"); + throw new InvalidRequestException("dir, add dirs, and profile are not supported by codex exec resume or fork"); } _ = request.CyberAccessProgram?.ToWire(); } @@ -104,12 +121,12 @@ private static void AppendCommonArgs( List args, Request request, string? schemaPath, - bool resume, + bool continuation, SandboxMode defaultSandbox, ApprovalPolicy defaultApproval) { args.Add("--json"); - if (!resume) + if (!continuation) { args.Add("--color"); args.Add("never"); @@ -128,7 +145,7 @@ private static void AppendCommonArgs( args.Add("-c"); args.Add($"model_reasoning_effort={TomlString(request.Effort)}"); } - if (!string.IsNullOrEmpty(request.Profile) && !resume) + if (!string.IsNullOrEmpty(request.Profile) && !continuation) { args.Add("-p"); args.Add(request.Profile); @@ -176,7 +193,7 @@ private static void AppendCommonArgs( else { var sandbox = (request.Sandbox ?? defaultSandbox).ToWire(); - if (resume) + if (continuation) { args.Add("-c"); args.Add($"sandbox_mode=\"{sandbox}\""); @@ -194,7 +211,7 @@ private static void AppendCommonArgs( { args.Add("--dangerously-bypass-hook-trust"); } - if (!resume) + if (!continuation) { if (!string.IsNullOrEmpty(request.Dir)) { diff --git a/dotnet/Codexcw/CodexDecoder.cs b/dotnet/Codexcw/CodexDecoder.cs index aff6272..0927517 100644 --- a/dotnet/Codexcw/CodexDecoder.cs +++ b/dotnet/Codexcw/CodexDecoder.cs @@ -33,6 +33,8 @@ internal static Event DecodeEvent(string line, string runId, string threadId, Da Raw = line, }; + var usage = type is EventTypes.TurnFailed or EventTypes.TurnCompleted && UsageObject(root) is { } reported + ? ParseUsage(reported) : null; return type switch { EventTypes.ThreadStarted => @event with @@ -46,18 +48,24 @@ internal static Event DecodeEvent(string line, string runId, string threadId, Da }, EventTypes.TurnCompleted => @event with { - TurnCompleted = new TurnCompletedPayload(ParseUsage(UsageObject(root))), + SessionUsage = usage, + TurnCompleted = new TurnCompletedPayload(usage ?? new Usage()), }, EventTypes.TurnFailed => @event with { + SessionUsage = usage, TurnFailed = new TurnFailedPayload( ParseErrorPayload(root.GetElement("error")), - ParseUsage(UsageObject(root))), + usage ?? new Usage()), }, EventTypes.ItemStarted => @event with { ItemStarted = new ItemPayload(DecodeItem(root.GetElement("item"))), }, + EventTypes.ItemUpdated => @event with + { + ItemUpdated = new ItemPayload(DecodeItem(root.GetElement("item"))), + }, EventTypes.ItemCompleted => @event with { ItemCompleted = new ItemPayload(DecodeItem(root.GetElement("item"))), @@ -101,6 +109,10 @@ internal static Item DecodeItem(JsonElement? item) Type = type, Status = wire.GetStrictString("status"), Raw = wire.GetRawText(), + Phase = OptionalString(wire, "phase"), + WebSearch = type == ItemTypes.WebSearch ? ParseSearch(wire) : null, + Mcp = type == ItemTypes.McpToolCall ? ParseMcp(wire) : null, + Todos = type == ItemTypes.TodoList ? OptionalArray(wire, "items")?.Select(step => new TodoStep(step.GetStrictString("text"), step.GetStrictBool("completed"))).ToList() : null, Text = wire.GetStrictString("text"), Message = wire.GetStrictString("message"), Command = wire.GetStrictString("command"), @@ -113,6 +125,45 @@ internal static Item DecodeItem(JsonElement? item) }; } + private static JsonElement.ArrayEnumerator? OptionalArray(JsonElement element, string key) + { + if (element.GetElement(key) is not { } value) + { + return null; + } + if (value.ValueKind != JsonValueKind.Array) + { + throw new FormatException($"field {key}: expected array"); + } + return value.EnumerateArray(); + } + + private static string? OptionalString(JsonElement element, string key) => + element.GetElement(key) is { ValueKind: JsonValueKind.String } value ? value.GetString() : null; + + private static WebSearch ParseSearch(JsonElement item) + { + var action = item.GetObject("action") is { } op + ? new WebSearchAction(op.GetStrictString("type"), OptionalString(op, "query"), + op.GetStrictStringList("queries"), OptionalString(op, "url"), OptionalString(op, "pattern")) + : null; + var results = OptionalArray(item, "results")?.Select(result => + new WebSearchResult(OptionalString(result, "type"), OptionalString(result, "title"), + OptionalString(result, "url"), OptionalString(result, "domain"), OptionalString(result, "snippet"), + OptionalString(result, "ref_id"), result.Clone())).ToList(); + return new WebSearch(item.GetStrictString("query"), action, results); + } + + private static McpCall ParseMcp(JsonElement item) + { + var result = item.GetObject("result") is { } response + ? new McpResult(OptionalArray(response, "content")?.Select(block => block.Clone()).ToList() ?? [], + response.GetElement("structured_content")?.Clone(), response.GetElement("_meta")?.Clone()) + : null; + return new McpCall(item.GetStrictString("server"), item.GetStrictString("tool"), + item.GetElement("arguments")?.Clone(), result, item.GetObject("error")?.GetStrictString("message")); + } + private static List ParseChanges(JsonElement? changes) { if (changes is null) @@ -171,7 +222,8 @@ internal static Usage ParseUsage(JsonElement? usage) { InputTokens = wire.GetStrictLong("input_tokens"), CachedInputTokens = wire.GetStrictLong("cached_input_tokens"), - CacheCreationInputTokens = wire.GetStrictLong("cache_creation_input_tokens"), + CacheCreationInputTokens = wire.GetElement("cache_write_input_tokens") is not null + ? wire.GetStrictLong("cache_write_input_tokens") : wire.GetStrictLong("cache_creation_input_tokens"), OutputTokens = wire.GetStrictLong("output_tokens"), ReasoningOutputTokens = wire.GetStrictLong("reasoning_output_tokens"), TotalTokens = wire.GetStrictLong("total_tokens"), diff --git a/dotnet/Codexcw/CodexItems.cs b/dotnet/Codexcw/CodexItems.cs new file mode 100644 index 0000000..71a2615 --- /dev/null +++ b/dotnet/Codexcw/CodexItems.cs @@ -0,0 +1,46 @@ +using System.Text.Json; + +namespace C3OSS.Codexcw; + +/// Describes a Codex web search and its optional result set. +/// Search query reported on the item. +/// Operation requested by the model. +/// Results, or null when omitted by the provider. +public sealed record WebSearch(string Query, WebSearchAction? Action, IReadOnlyList? Results); + +/// Describes a search, page open, find-in-page or future action. +/// Wire action type. +/// Single search query. +/// Multiple search queries. +/// Address of the target page. +/// Text sought in the page. +public sealed record WebSearchAction(string Type, string? Query, IReadOnlyList Queries, string? Url, string? Pattern); + +/// A provider-specific result with its original JSON value. +/// Wire result type. +/// Source title. +/// Source address. +/// Source domain. +/// Text excerpt. +/// Provider reference. +/// Full provider-specific JSON value. +public sealed record WebSearchResult(string? Type, string? Title, string? Url, string? Domain, string? Snippet, string? RefId, JsonElement Raw); + +/// A Codex MCP invocation. +/// Configured server name. +/// Name of the called tool. +/// Tool-specific input JSON. +/// Returned tool data. +/// Error message provided by an unsuccessful call. +public sealed record McpCall(string Server, string Tool, JsonElement? Arguments, McpResult? Result, string? Error); + +/// Data returned by an MCP tool. +/// Provider-specific content blocks. +/// Optional structured response. +/// Optional MCP metadata. +public sealed record McpResult(IReadOnlyList Content, JsonElement? StructuredContent, JsonElement? Meta); + +/// One task in a Codex plan snapshot. +/// Task description. +/// Whether the task is complete. +public sealed record TodoStep(string Text, bool Completed); diff --git a/dotnet/Codexcw/Events.cs b/dotnet/Codexcw/Events.cs index 414829e..00c24ab 100644 --- a/dotnet/Codexcw/Events.cs +++ b/dotnet/Codexcw/Events.cs @@ -26,6 +26,9 @@ public enum EventKind /// An event type this library does not model; keeps the wire string. Other, + + /// An existing item was updated. + ItemUpdated, } /// The normalized item kind inside item.started and item.completed. @@ -63,11 +66,38 @@ public enum ItemKind /// An item type this library does not model; keeps the wire string. Other, + + /// A Codex plan snapshot. + TodoList, } /// One decoded or normalized agent JSONL event. public sealed record Event { + /// Structured result reported by the agent. + public System.Text.Json.JsonElement? StructuredOutput { get; init; } + + /// Usage attributable to this invocation when available. + public Usage? InvocationUsage { get; init; } + + /// Cumulative session usage when reported. + public Usage? SessionUsage { get; init; } + + /// Parent tool call for a nested message. + public string ParentToolUseId { get; init; } = ""; + + /// Native result index when present. + public int? ResultIndex { get; init; } + + /// Machine-readable reason for termination. + public string FailureReason { get; init; } = ""; + + /// Partial Messages stream payload. + public StreamDelta? Delta { get; init; } + + /// Task lifecycle update. + public TaskUpdate? Task { get; init; } + /// The normalized top-level event kind. public required EventKind Kind { get; init; } @@ -101,6 +131,9 @@ public sealed record Event /// Set for . public ItemPayload? ItemStarted { get; init; } + /// Set for . + public ItemPayload? ItemUpdated { get; init; } + /// Set for . public ItemPayload? ItemCompleted { get; init; } @@ -156,6 +189,18 @@ public sealed record Item /// The original nested item payload. public string Raw { get; init; } = ""; + /// Model-reported agent-message phase. + public string? Phase { get; init; } + + /// Action and available results for a web search. + public WebSearch? WebSearch { get; init; } + + /// MCP invocation, result or tool error. + public McpCall? Mcp { get; init; } + + /// Current Codex plan snapshot. + public IReadOnlyList? Todos { get; init; } + /// Assistant text for agent_message items. public string Text { get; init; } = ""; @@ -198,7 +243,7 @@ public sealed record Usage /// The number of cached input tokens. public long CachedInputTokens { get; init; } - /// The number of tokens written to Claude's cache. + /// The number of tokens written to the agent's prompt cache. public long CacheCreationInputTokens { get; init; } /// The number of output tokens produced. @@ -208,13 +253,13 @@ public sealed record Usage public long ReasoningOutputTokens { get; init; } /// - /// The total token count for the full run, subagents included. When the + /// The total token count for this usage snapshot, subagents included. When the /// agent omits an explicit total it is derived: input plus output tokens /// for Codex, and the per-model sums when Claude or Grok reports model usage. /// public long TotalTokens { get; init; } - /// The total agent-reported run cost in US dollars. + /// The agent-reported cost of this snapshot in US dollars. public double TotalCostUsd { get; init; } /// Agent-reported usage grouped by model identifier. @@ -225,6 +270,9 @@ public sealed record Usage /// Usage and cost information for one model. public sealed record ModelUsage { + /// The number of reported thinking tokens within output tokens. + public long ReasoningOutputTokens { get; init; } + /// The number of input tokens consumed. public long InputTokens { get; init; } @@ -256,6 +304,7 @@ internal static class EventTypes public const string TurnStarted = "turn.started"; public const string TurnCompleted = "turn.completed"; public const string TurnFailed = "turn.failed"; + public const string ItemUpdated = "item.updated"; public const string ItemStarted = "item.started"; public const string ItemCompleted = "item.completed"; public const string Error = "error"; @@ -266,6 +315,7 @@ internal static class EventTypes TurnStarted => EventKind.TurnStarted, TurnCompleted => EventKind.TurnCompleted, TurnFailed => EventKind.TurnFailed, + ItemUpdated => EventKind.ItemUpdated, ItemStarted => EventKind.ItemStarted, ItemCompleted => EventKind.ItemCompleted, Error => EventKind.Error, @@ -281,6 +331,7 @@ internal static class ItemTypes public const string FileChange = "file_change"; public const string McpToolCall = "mcp_tool_call"; public const string WebSearch = "web_search"; + public const string TodoList = "todo_list"; public const string PlanUpdate = "plan_update"; public const string ToolCall = "tool_call"; public const string CollabToolCall = "collab_tool_call"; @@ -294,6 +345,7 @@ internal static class ItemTypes FileChange => ItemKind.FileChange, McpToolCall => ItemKind.McpToolCall, WebSearch => ItemKind.WebSearch, + TodoList => ItemKind.TodoList, PlanUpdate => ItemKind.PlanUpdate, ToolCall => ItemKind.ToolCall, CollabToolCall => ItemKind.CollabToolCall, @@ -309,6 +361,7 @@ internal static class ItemTypes ItemKind.FileChange => FileChange, ItemKind.McpToolCall => McpToolCall, ItemKind.WebSearch => WebSearch, + ItemKind.TodoList => TodoList, ItemKind.PlanUpdate => PlanUpdate, ItemKind.ToolCall => ToolCall, ItemKind.CollabToolCall => CollabToolCall, @@ -316,3 +369,57 @@ internal static class ItemTypes _ => "", }; } + +/// A partial Messages stream event. +public sealed record StreamDelta +{ + /// Native event or delta kind. + public string Kind { get; init; } = ""; + + /// Incremental text, thinking, or JSON argument fragment. + public string Text { get; init; } = ""; + + /// Content block index when supplied. + public int? Index { get; init; } +} + +/// A task lifecycle event. +public sealed record TaskUpdate +{ + /// The task description supplied at startup. + public string Description { get; init; } = ""; + + /// The task completion summary. + public string Summary { get; init; } = ""; + + /// Counters for this task when reported. + public TaskUsage? Usage { get; init; } + + /// Native event or delta kind. + public string Kind { get; init; } = ""; + + /// Task identifier. + public string Id { get; init; } = ""; + + /// Identifier of the task run. + public string RunId { get; init; } = ""; + + /// Tool call associated with this task. + public string ToolUseId { get; init; } = ""; + + /// Native task status. + public string Status { get; init; } = ""; +} + +/// Native counters scoped to a single agent task. +public sealed record TaskUsage +{ + /// Task duration in milliseconds. + public long DurationMs { get; init; } + + /// The number of tool uses attributed to the task. + public long ToolUses { get; init; } + + /// The number of tokens attributed to the task. + public long TotalTokens { get; init; } +} diff --git a/dotnet/Codexcw/GrokArgs.cs b/dotnet/Codexcw/GrokArgs.cs index 9ee76f9..a0719b1 100644 --- a/dotnet/Codexcw/GrokArgs.cs +++ b/dotnet/Codexcw/GrokArgs.cs @@ -52,6 +52,10 @@ public static PreparedRun Prepare( args.Add("--cwd"); args.Add(request.Dir); } + if (request.IncludePartialMessages) + { + args.Add("--include-partial-messages"); + } if (!string.IsNullOrEmpty(request.Model)) { args.Add("--model"); @@ -154,6 +158,7 @@ private static void Validate(Request request) (request.RequireGitRepo, "require git repo"), (!string.IsNullOrEmpty(request.OutputLastMessagePath), "output last message path"), (request.DangerouslyBypassHooks, "dangerously bypass hooks"), + (!string.IsNullOrEmpty(request.ForkId), "fork id"), (request.ResumeAll, "resume all"), }; foreach (var (set, name) in unsupported) diff --git a/dotnet/Codexcw/Request.cs b/dotnet/Codexcw/Request.cs index a562728..d6254bd 100644 --- a/dotnet/Codexcw/Request.cs +++ b/dotnet/Codexcw/Request.cs @@ -109,6 +109,12 @@ public override string ToString() => /// Describes one selected-agent invocation. public sealed record Request { + /// Codex thread to fork into a new thread. + public string? ForkId { get; init; } + + /// Request incremental Messages events from Claude or Grok. + public bool IncludePartialMessages { get; init; } + /// The user instruction sent to the selected agent. public string Prompt { get; init; } = ""; diff --git a/dotnet/Codexcw/Runner.cs b/dotnet/Codexcw/Runner.cs index 80d0268..d1f6aa9 100644 --- a/dotnet/Codexcw/Runner.cs +++ b/dotnet/Codexcw/Runner.cs @@ -129,7 +129,7 @@ public Session Start( ? WriteStdinAsync(process, request, session.Token) : CloseStdin(process); session.StartForwarding(); - _ = CollectAsync(session, process, prepared, options?.Handler, stdinTask); + _ = CollectAsync(session, process, prepared, options?.Handler, stdinTask, request.ResumeLast || !string.IsNullOrEmpty(request.ResumeId) || !string.IsNullOrEmpty(request.ForkId)); return session; } @@ -369,12 +369,14 @@ private async Task CollectAsync( Process process, PreparedRun prepared, Func? handler, - Task stdinTask) + Task stdinTask, bool resumed) { var startedAt = DateTimeOffset.Now; var events = new List(); Event? lastEvent = null; var finalMessage = ""; + var hasFinalAnswer = false; + Usage? invocationUsage = null; Usage? sessionUsage = null; System.Text.Json.JsonElement? structuredOutput = null; var usage = new Usage(); var threadId = ""; Exception? runError = null; @@ -423,9 +425,11 @@ private async Task CollectAsync( { @event = @event with { ThreadId = threadId }; } - if (@event.ItemCompleted?.Item is { Kind: ItemKind.AgentMessage } message) + if (@event.ParentToolUseId.Length == 0 && @event.ItemCompleted?.Item is { Kind: ItemKind.AgentMessage } message + && (message.Phase == "final_answer" || !hasFinalAnswer)) { finalMessage = message.Text; + hasFinalAnswer = message.Phase == "final_answer"; } if (@event.TurnCompleted is not null) { @@ -436,6 +440,16 @@ private async Task CollectAsync( usage = @event.TurnFailed.Usage; } + if (@event.TurnCompleted is not null || @event.TurnFailed is not null) + { + if (@event.InvocationUsage is null && !resumed) + { + @event = @event with { InvocationUsage = @event.SessionUsage }; + } + invocationUsage = @event.InvocationUsage ?? invocationUsage; + sessionUsage = @event.SessionUsage ?? sessionUsage; + structuredOutput = @event.StructuredOutput ?? structuredOutput; + } lastEvent = @event; events.Add(@event); session.InternalWriter.TryWrite(@event); @@ -501,6 +515,9 @@ private async Task CollectAsync( RunId = session.Id, ThreadId = threadId, FinalMessage = finalMessage, + InvocationUsage = invocationUsage, + SessionUsage = sessionUsage, + StructuredOutput = structuredOutput, Usage = usage, Events = events, Stderr = stderrTail.ToString(), @@ -526,6 +543,9 @@ private async Task CollectAsync( RunId = session.Id, ThreadId = threadId, FinalMessage = finalMessage, + InvocationUsage = invocationUsage, + SessionUsage = sessionUsage, + StructuredOutput = structuredOutput, Usage = usage, Events = events, Stderr = stderrTail.ToString(), diff --git a/dotnet/Codexcw/Session.cs b/dotnet/Codexcw/Session.cs index ccd6d35..9d92710 100644 --- a/dotnet/Codexcw/Session.cs +++ b/dotnet/Codexcw/Session.cs @@ -6,6 +6,15 @@ namespace C3OSS.Codexcw; /// Summarizes a completed agent invocation. public sealed record RunResult { + /// Structured result reported by the agent. + public System.Text.Json.JsonElement? StructuredOutput { get; init; } + + /// Usage attributable to this invocation when available. + public Usage? InvocationUsage { get; init; } + + /// Cumulative session usage when reported. + public Usage? SessionUsage { get; init; } + /// The wrapper-assigned run id. public string RunId { get; init; } = ""; @@ -15,7 +24,7 @@ public sealed record RunResult /// The last completed agent_message text. public string FinalMessage { get; init; } = ""; - /// The last turn.completed usage payload. + /// Legacy counters from the last terminal turn event. public Usage Usage { get; init; } = new(); /// Every decoded event retained by the run. diff --git a/events.go b/events.go index 2e3eb4a..eece07a 100644 --- a/events.go +++ b/events.go @@ -24,6 +24,9 @@ const ( // EventItemStarted is emitted when an agent starts a streamed item. EventItemStarted EventType = "item.started" + // EventItemUpdated is emitted when a streamed item changes. + EventItemUpdated EventType = "item.updated" + // EventItemCompleted is emitted when an agent completes a streamed item. EventItemCompleted EventType = "item.completed" @@ -53,6 +56,9 @@ const ( // ItemWebSearch carries a web search operation. ItemWebSearch ItemType = "web_search" + // ItemTodoList carries a Codex plan snapshot. + ItemTodoList ItemType = "todo_list" + // ItemPlanUpdate carries a Codex plan update. ItemPlanUpdate ItemType = "plan_update" @@ -69,6 +75,22 @@ const ( // Event is one decoded or normalized agent JSONL event. type Event struct { + // StructuredOutput holds the structured result reported by the agent. + StructuredOutput json.RawMessage + // InvocationUsage reports usage attributable to this invocation when available. + InvocationUsage *Usage + // SessionUsage reports cumulative session usage when reported. + SessionUsage *Usage + // ParentToolUseID holds the parent tool call for a nested message. + ParentToolUseID string + // ResultIndex holds the native result index when present. + ResultIndex *int + // FailureReason holds the machine-readable reason for termination. + FailureReason string + // Delta holds the partial Messages stream payload. + Delta *StreamDelta + // Task holds the task lifecycle update. + Task *TaskUpdate // Type is the normalized top-level event type. Type EventType @@ -99,6 +121,9 @@ type Event struct { // ItemStarted is set for EventItemStarted. ItemStarted *ItemEvent + // ItemUpdated is set for EventItemUpdated. + ItemUpdated *ItemEvent + // ItemCompleted is set for EventItemCompleted. ItemCompleted *ItemEvent @@ -156,7 +181,7 @@ type Usage struct { // CachedInputTokens is the number of cached input tokens. CachedInputTokens int64 `json:"cached_input_tokens"` - // CacheCreationInputTokens is the number of tokens written to Claude's cache. + // CacheCreationInputTokens is the number of tokens written to the agent's prompt cache. CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"` // OutputTokens is the number of output tokens produced. @@ -165,13 +190,13 @@ type Usage struct { // ReasoningOutputTokens is the number of reasoning output tokens. ReasoningOutputTokens int64 `json:"reasoning_output_tokens"` - // TotalTokens is the total token count for the full run, subagents + // TotalTokens is the total token count for this usage snapshot, subagents // included. When the agent omits an explicit total it is derived: input // plus output tokens for Codex, and the per-model sums when Claude or Grok // reports model usage. TotalTokens int64 `json:"total_tokens"` - // TotalCostUSD is the total agent-reported run cost in US dollars. + // TotalCostUSD is the agent-reported cost of this snapshot in US dollars. TotalCostUSD float64 `json:"total_cost_usd"` // ModelUsage contains agent-reported usage grouped by model identifier. @@ -180,6 +205,9 @@ type Usage struct { // ModelUsage is usage and cost information for one model. type ModelUsage struct { + // ReasoningOutputTokens counts reported thinking tokens within output tokens. + ReasoningOutputTokens int64 `json:"reasoning_output_tokens"` + // InputTokens is the number of input tokens consumed. InputTokens int64 `json:"input_tokens"` @@ -225,6 +253,18 @@ type Item struct { // Raw is the original nested item payload. Raw json.RawMessage + // Phase is the optional agent-message phase, such as final_answer. + Phase string + + // WebSearch holds the action and available results of a Codex web search. + WebSearch *WebSearch + + // MCP holds the details of a Codex MCP tool invocation. + MCP *MCPCall + + // Todos holds the current checklist snapshot for a Codex todo_list. + Todos []TodoStep + // Text is assistant text for agent_message items. Text string @@ -263,3 +303,43 @@ type FileChange struct { // Kind is the normalized change kind reported by the agent. Kind string `json:"kind"` } + +// StreamDelta describes a partial messages stream event. +type StreamDelta struct { + // Kind holds the native event or delta kind. + Kind string + // Text holds incremental text, thinking, or JSON argument fragment. + Text string + // Index holds the content block index when supplied. + Index *int +} + +// TaskUpdate describes a task lifecycle event. +type TaskUpdate struct { + // Description holds the task description emitted at startup. + Description string + // Summary holds the task completion summary. + Summary string + // Usage holds counters for this task when reported. + Usage *TaskUsage + // Kind holds the native event or delta kind. + Kind string + // ID holds the task identifier. + ID string + // RunID holds the identifier of the task run. + RunID string + // ToolUseID holds the tool call associated with this task. + ToolUseID string + // Status holds the native task status. + Status string +} + +// TaskUsage contains native counters scoped to a single agent task. +type TaskUsage struct { + // DurationMS is the task duration in milliseconds. + DurationMS int64 `json:"duration_ms"` + // ToolUses counts tools used by this task. + ToolUses int64 `json:"tool_uses"` + // TotalTokens counts tokens attributed to this task. + TotalTokens int64 `json:"total_tokens"` +} diff --git a/grok.go b/grok.go index b7d3a3a..68c7b3f 100644 --- a/grok.go +++ b/grok.go @@ -50,6 +50,9 @@ func (r *Runner) prepareGrok(req Request) (_ []string, _ io.Reader, cleanup func if req.Dir != "" { args = append(args, "--cwd", req.Dir) } + if req.IncludePartialMessages { + args = append(args, "--include-partial-messages") + } if req.Model != "" { args = append(args, "--model", req.Model) } @@ -138,6 +141,7 @@ func validateGrokRequest(req Request) error { {req.RequireGitRepo, "require git repo"}, {req.OutputLastMessagePath != "", "output last message path"}, {req.DangerouslyBypassHooks, "dangerously bypass hooks"}, + {req.ForkID != "", "fork id"}, {req.ResumeAll, "resume all"}, } for _, field := range unsupported { diff --git a/request.go b/request.go index 28f4c65..6134121 100644 --- a/request.go +++ b/request.go @@ -68,6 +68,10 @@ func (c ConfigOverride) String() string { // Request describes one selected-agent invocation. type Request struct { + // ForkID selects the Codex thread to fork into a new thread. + ForkID string + // IncludePartialMessages requests incremental Messages events from Claude or Grok. + IncludePartialMessages bool // Prompt is the user instruction sent to the selected agent. Prompt string diff --git a/runner.go b/runner.go index 98d7722..879f87a 100644 --- a/runner.go +++ b/runner.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "io" + "maps" "os" "os/exec" "strings" @@ -174,6 +175,12 @@ func WithHandler(handler Handler) RunOption { // Result summarizes a completed agent invocation. type Result struct { + // StructuredOutput holds the structured result reported by the agent. + StructuredOutput json.RawMessage + // InvocationUsage reports usage attributable to this invocation when available. + InvocationUsage *Usage + // SessionUsage reports cumulative session usage when reported. + SessionUsage *Usage // RunID is the wrapper-assigned run id. RunID string @@ -183,7 +190,7 @@ type Result struct { // FinalMessage is the last completed agent_message text. FinalMessage string - // Usage is the last turn.completed usage payload. + // Usage contains legacy counters from the last terminal turn event. Usage Usage // Events contains every decoded event retained by Wait. @@ -315,7 +322,7 @@ func (r *Runner) Start(ctx context.Context, req Request, opts ...RunOption) (*Se return nil, err } - go r.collect(runCtx, session, cmd, stdout, stderrTail, cleanup, cfg.handler) + go r.collect(runCtx, session, cmd, stdout, stderrTail, cleanup, cfg.handler, req.ResumeID != "" || req.ResumeLast || req.ForkID != "") return session, nil } @@ -365,15 +372,19 @@ func (r *Runner) collect( stderrTail *tailBuffer, cleanup func(), handler Handler, + resumed bool, ) { startedAt := r.now() var ( - events []Event - lastEvent *Event - finalMessage string - usage Usage - threadID string - runErr error + events []Event + lastEvent *Event + invocationUsage, sessionUsage *Usage + structuredOutput json.RawMessage + finalMessage string + hasFinalAnswer bool + usage Usage + threadID string + runErr error ) scanner := bufio.NewScanner(stdout) @@ -403,8 +414,12 @@ scan: if event.ThreadID == "" { event.ThreadID = threadID } - if event.ItemCompleted != nil && event.ItemCompleted.Item.Type == ItemAgentMessage { - finalMessage = event.ItemCompleted.Item.Text + if event.ItemCompleted != nil && event.ItemCompleted.Item.Type == ItemAgentMessage && event.ParentToolUseID == "" { + item := event.ItemCompleted.Item + if item.Phase == "final_answer" || !hasFinalAnswer { + finalMessage = item.Text + hasFinalAnswer = item.Phase == "final_answer" + } } if event.TurnCompleted != nil { usage = event.TurnCompleted.Usage @@ -413,6 +428,23 @@ scan: usage = event.TurnFailed.Usage } + if event.TurnCompleted != nil || event.TurnFailed != nil { + if event.InvocationUsage == nil && !resumed && event.SessionUsage != nil { + snapshot := *event.SessionUsage + snapshot.ModelUsage = maps.Clone(snapshot.ModelUsage) + event.InvocationUsage = &snapshot + } + if event.InvocationUsage != nil { + invocationUsage = event.InvocationUsage + } + if event.SessionUsage != nil { + sessionUsage = event.SessionUsage + } + if event.StructuredOutput != nil { + structuredOutput = event.StructuredOutput + } + } + eventCopy := event lastEvent = &eventCopy events = append(events, event) @@ -449,8 +481,9 @@ scan: finishedAt := r.now() result := &Result{ - RunID: session.ID, - ThreadID: threadID, + RunID: session.ID, + ThreadID: threadID, + InvocationUsage: invocationUsage, SessionUsage: sessionUsage, StructuredOutput: structuredOutput, FinalMessage: finalMessage, Usage: usage, Events: events, @@ -555,6 +588,8 @@ func (r *Runner) prepare(req Request) (_ []string, _ io.Reader, cleanup func(), args := []string{"exec"} if req.ResumeID != "" || req.ResumeLast { args = append(args, "resume") + } else if req.ForkID != "" { + args = append(args, "fork") } args = r.appendCommonArgs(args, req, schemaPath) @@ -568,6 +603,8 @@ func (r *Runner) prepare(req Request) (_ []string, _ io.Reader, cleanup func(), if req.ResumeID != "" { args = append(args, req.ResumeID) + } else if req.ForkID != "" { + args = append(args, req.ForkID) } args = append(args, "-") @@ -588,12 +625,18 @@ func validateRequest(req Request) error { if req.ResumeID != "" && req.ResumeLast { return fmt.Errorf("%w: resume id and resume last are mutually exclusive", ErrInvalidRequest) } + if req.IncludePartialMessages { + return fmt.Errorf("%w: partial messages are not supported by codex", ErrInvalidRequest) + } + if req.ForkID != "" && (resume || req.ResumeAll) { + return fmt.Errorf("%w: fork and resume are mutually exclusive", ErrInvalidRequest) + } if req.ResumeAll && !resume { return fmt.Errorf("%w: resume all requires resume id or resume last", ErrInvalidRequest) } - if resume { + if resume || req.ForkID != "" { if req.Dir != "" || len(req.AddDirs) > 0 || req.Profile != "" { - return fmt.Errorf("%w: dir, add dirs, and profile are not supported by codex exec resume", ErrInvalidRequest) + return fmt.Errorf("%w: dir, add dirs, and profile are not supported by codex exec resume or fork", ErrInvalidRequest) } } switch req.CyberAccessProgram { @@ -605,10 +648,10 @@ func validateRequest(req Request) error { } func (r *Runner) appendCommonArgs(args []string, req Request, schemaPath string) []string { - resume := req.ResumeID != "" || req.ResumeLast + continuation := req.ResumeID != "" || req.ResumeLast || req.ForkID != "" args = append(args, "--json") - if !resume { + if !continuation { args = append(args, "--color", "never") } if req.StrictConfig { @@ -620,7 +663,7 @@ func (r *Runner) appendCommonArgs(args []string, req Request, schemaPath string) if req.Effort != "" { args = append(args, "-c", "model_reasoning_effort="+tomlString(req.Effort)) } - if req.Profile != "" && !resume { + if req.Profile != "" && !continuation { args = append(args, "-p", req.Profile) } for _, feature := range req.Enable { @@ -654,7 +697,7 @@ func (r *Runner) appendCommonArgs(args []string, req Request, schemaPath string) if sandbox == "" { sandbox = r.defaultSandbox } - if resume { + if continuation { args = append(args, "-c", fmt.Sprintf("sandbox_mode=%q", string(sandbox))) } else { args = append(args, "--sandbox", string(sandbox)) @@ -668,7 +711,7 @@ func (r *Runner) appendCommonArgs(args []string, req Request, schemaPath string) if req.DangerouslyBypassHooks { args = append(args, "--dangerously-bypass-hook-trust") } - if !resume { + if !continuation { if req.Dir != "" { args = append(args, "-C", req.Dir) } diff --git a/runner_test.go b/runner_test.go index 260bf38..c575178 100644 --- a/runner_test.go +++ b/runner_test.go @@ -616,3 +616,31 @@ func readArgs(t *testing.T, path string) []string { require.NoError(t, err) return strings.Split(strings.TrimSpace(string(bytes)), "\n") } + +func TestCodexFinalMessagePhases(t *testing.T) { + for _, tc := range []struct{ fixture, message string }{ + {"codex-commentary.jsonl", "Checked two files"}, + {"codex.jsonl", "DONE"}, + } { + t.Run(tc.fixture, func(t *testing.T) { + fixture, err := filepath.Abs(filepath.Join("crates/codexcw/tests/fixtures/streams", tc.fixture)) + require.NoError(t, err) + fake := writeFakeCodex(t, `cat "$STREAM_FIXTURE"`) + result, err := New(WithExecutable(fake), WithEnv("STREAM_FIXTURE="+fixture)).Run(context.Background(), Request{Prompt: "x"}) + require.NoError(t, err) + assert.Equal(t, tc.message, result.FinalMessage) + }) + } +} + +func TestFreshThreadUsageSnapshotsAreIndependent(t *testing.T) { + fake := writeFakeCodex(t, `echo '{"type":"turn.completed","usage":{"input_tokens":5,"model_usage":{"model":{"input_tokens":5}}}}'`) + result, err := New(WithExecutable(fake)).Run(context.Background(), Request{Prompt: "x"}) + require.NoError(t, err) + require.NotNil(t, result.InvocationUsage) + require.NotNil(t, result.SessionUsage) + result.InvocationUsage.InputTokens = 0 + delete(result.InvocationUsage.ModelUsage, "model") + assert.EqualValues(t, 5, result.SessionUsage.InputTokens) + assert.EqualValues(t, 5, result.SessionUsage.ModelUsage["model"].InputTokens) +}