Skip to content

Commit 1f537c3

Browse files
authored
fix(agents): expose CLI tool summaries in terminal results (#115797)
* fix(agents): preserve CLI tool summaries * fix(agents): cover Codex collaboration tools
1 parent 6dc55fa commit 1f537c3

15 files changed

Lines changed: 363 additions & 3 deletions

‎src/agents/cli-output.ts‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import type {
1414
MessagingToolSend,
1515
MessagingToolSourceReplyPayload,
1616
} from "./embedded-agent-messaging.types.js";
17+
import type { ToolSummaryTrace } from "./embedded-agent-runner/types.js";
1718

1819
export type CliUsage = {
1920
input?: number;
@@ -51,6 +52,7 @@ export type CliOutput = {
5152
usage?: CliUsage;
5253
/** Terminal cumulative turn usage for diagnostics; reply accounting keeps using `usage`. */
5354
diagnosticUsage?: CliUsage;
55+
toolSummary?: ToolSummaryTrace;
5456
errorText?: string;
5557
terminalFailure?: CliTerminalFailure;
5658
diagnostics?: {
@@ -154,6 +156,11 @@ function isGeminiCliProvider(providerId: string): boolean {
154156
return normalizeLowercaseStringOrEmpty(providerId) === "google-gemini-cli";
155157
}
156158

159+
function isCodexExecJsonlProvider(providerId: string): boolean {
160+
const normalized = normalizeLowercaseStringOrEmpty(providerId);
161+
return normalized === "codex" || normalized === "codex-cli";
162+
}
163+
157164
function isGeminiStreamJsonDialect(params: {
158165
backend: CliBackendConfig;
159166
providerId: string;
@@ -1167,6 +1174,128 @@ function dispatchGeminiCliStreamingToolEvent(params: {
11671174
}
11681175
}
11691176

1177+
type CodexToolEvent = {
1178+
toolCallId: string;
1179+
name: string;
1180+
kind: CliToolUseStartDelta["kind"];
1181+
args: Record<string, unknown>;
1182+
result?: unknown;
1183+
isError: boolean;
1184+
};
1185+
1186+
function readCodexToolEvent(item: Record<string, unknown>): CodexToolEvent | null {
1187+
const toolCallId = typeof item.id === "string" ? item.id.trim() : "";
1188+
if (!toolCallId) {
1189+
return null;
1190+
}
1191+
const type = normalizeLowercaseStringOrEmpty(item.type);
1192+
if (type === "command_execution") {
1193+
return {
1194+
toolCallId,
1195+
name: "bash",
1196+
kind: "tool_use",
1197+
args: typeof item.command === "string" ? { command: item.command } : {},
1198+
result: item.aggregated_output,
1199+
isError: item.status === "failed" || item.status === "declined",
1200+
};
1201+
}
1202+
if (type === "file_change") {
1203+
return {
1204+
toolCallId,
1205+
name: "apply_patch",
1206+
kind: "tool_use",
1207+
args: Array.isArray(item.changes) ? { changes: item.changes } : {},
1208+
result: item.changes,
1209+
isError: item.status === "failed",
1210+
};
1211+
}
1212+
if (type === "web_search") {
1213+
return {
1214+
toolCallId,
1215+
name: "web_search",
1216+
kind: "server_tool_use",
1217+
args: typeof item.query === "string" ? { query: item.query } : {},
1218+
result: item.query,
1219+
isError: false,
1220+
};
1221+
}
1222+
if (type !== "mcp_tool_call") {
1223+
if (type !== "collab_tool_call") {
1224+
return null;
1225+
}
1226+
const tool = typeof item.tool === "string" ? item.tool.trim() : "";
1227+
if (!tool) {
1228+
return null;
1229+
}
1230+
return {
1231+
toolCallId,
1232+
name: `collab.${tool}`,
1233+
kind: "server_tool_use",
1234+
args: {
1235+
...(typeof item.sender_thread_id === "string"
1236+
? { sender_thread_id: item.sender_thread_id }
1237+
: {}),
1238+
...(Array.isArray(item.receiver_thread_ids)
1239+
? { receiver_thread_ids: item.receiver_thread_ids }
1240+
: {}),
1241+
...(typeof item.prompt === "string" ? { prompt: item.prompt } : {}),
1242+
},
1243+
result: item.agents_states,
1244+
isError: item.status === "failed",
1245+
};
1246+
}
1247+
const server = typeof item.server === "string" ? item.server.trim() : "";
1248+
const tool = typeof item.tool === "string" ? item.tool.trim() : "";
1249+
if (!tool) {
1250+
return null;
1251+
}
1252+
return {
1253+
toolCallId,
1254+
name: server ? `${server}.${tool}` : tool,
1255+
kind: "mcp_tool_use",
1256+
args: isRecord(item.arguments) ? item.arguments : {},
1257+
result: item.status === "failed" ? item.error : item.result,
1258+
isError: item.status === "failed",
1259+
};
1260+
}
1261+
1262+
function dispatchCodexCliStreamingToolEvent(params: {
1263+
providerId: string;
1264+
parsed: Record<string, unknown>;
1265+
tracker: ToolUseTracker;
1266+
onToolUseStart?: (delta: CliToolUseStartDelta) => void;
1267+
onToolResult?: (delta: CliToolResultDelta) => void;
1268+
}): void {
1269+
if (
1270+
!isCodexExecJsonlProvider(params.providerId) ||
1271+
(params.parsed.type !== "item.started" && params.parsed.type !== "item.completed") ||
1272+
!isRecord(params.parsed.item)
1273+
) {
1274+
return;
1275+
}
1276+
const event = readCodexToolEvent(params.parsed.item);
1277+
if (!event) {
1278+
return;
1279+
}
1280+
emitToolStartOnce(
1281+
params.tracker,
1282+
event.toolCallId,
1283+
event.name,
1284+
event.kind,
1285+
event.args,
1286+
params.onToolUseStart,
1287+
);
1288+
if (params.parsed.type === "item.completed") {
1289+
emitToolResultOnce(
1290+
params.tracker,
1291+
event.toolCallId,
1292+
event.isError,
1293+
event.result,
1294+
params.onToolResult,
1295+
);
1296+
}
1297+
}
1298+
11701299
const GEMINI_CLI_ERROR_EVENT_FALLBACK = "Gemini CLI emitted an error event.";
11711300
const GEMINI_CLI_RESULT_ERROR_FALLBACK = "Gemini CLI result status was error.";
11721301

@@ -1398,6 +1527,13 @@ export function createCliJsonlStreamingParser(params: {
13981527
}
13991528

14001529
if (params.onToolUseStart || params.onToolResult) {
1530+
dispatchCodexCliStreamingToolEvent({
1531+
providerId: params.providerId,
1532+
parsed,
1533+
tracker: toolTracker,
1534+
onToolUseStart: params.onToolUseStart,
1535+
onToolResult: params.onToolResult,
1536+
});
14011537
dispatchGeminiCliStreamingToolEvent({
14021538
backend: params.backend,
14031539
providerId: params.providerId,

‎src/agents/cli-runner.before-agent-reply-cron.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,21 @@ describe("runCliAgent before_agent_reply seam", () => {
217217
expect(executePreparedCliRunMock).toHaveBeenCalledOnce();
218218
});
219219

220+
it("projects CLI tool summaries onto terminal run metadata", async () => {
221+
executePreparedCliRunMock.mockResolvedValue({
222+
text: "done",
223+
toolSummary: { calls: 1, tools: ["github.search"], failures: 0 },
224+
});
225+
226+
const result = await runCliAgent(baseRunParams);
227+
228+
expect(result.meta.toolSummary).toEqual({
229+
calls: 1,
230+
tools: ["github.search"],
231+
failures: 0,
232+
});
233+
});
234+
220235
it("preserves the send phase when execution fails before successful cleanup", async () => {
221236
executePreparedCliRunMock.mockRejectedValueOnce(new Error("CLI process failed"));
222237

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
/** Tests Codex exec JSONL tool-summary projection through the CLI process boundary. */
2+
import { readFileSync } from "node:fs";
3+
import { beforeEach, describe, expect, it } from "vitest";
4+
import {
5+
buildPreparedCliRunContext,
6+
type PreparedCliRunContextOverrides,
7+
} from "./cli-runner.test-helpers.js";
8+
import { createManagedRun, supervisorSpawnMock } from "./cli-runner.test-support.js";
9+
import { executePreparedCliRun } from "./cli-runner/execute.js";
10+
11+
const CODEX_BACKEND: PreparedCliRunContextOverrides["backend"] = {
12+
output: "jsonl",
13+
sessionIdFields: ["thread_id"],
14+
systemPromptFileConfigArg: undefined,
15+
};
16+
17+
function queueCodexFixture(name: string) {
18+
supervisorSpawnMock.mockResolvedValueOnce(
19+
createManagedRun({
20+
reason: "exit",
21+
exitCode: 0,
22+
exitSignal: null,
23+
durationMs: 10,
24+
stdout: readFileSync(`test/fixtures/cli/${name}.jsonl`, "utf8"),
25+
stderr: "",
26+
timedOut: false,
27+
noOutputTimedOut: false,
28+
}),
29+
);
30+
}
31+
32+
async function runCodexFixture(name: string) {
33+
queueCodexFixture(name);
34+
return await executePreparedCliRun(
35+
buildPreparedCliRunContext({
36+
provider: "codex-cli",
37+
model: "gpt-5.5",
38+
backend: CODEX_BACKEND,
39+
}),
40+
);
41+
}
42+
43+
beforeEach(() => {
44+
supervisorSpawnMock.mockReset();
45+
});
46+
47+
describe("Codex CLI tool summaries", () => {
48+
it("emits an explicit empty summary for a successful zero-tool turn", async () => {
49+
const output = await runCodexFixture("codex-tool-summary-zero");
50+
51+
expect(output.toolSummary).toEqual({ calls: 0, tools: [], failures: 0 });
52+
});
53+
54+
it("counts paired MCP lifecycle events once", async () => {
55+
const output = await runCodexFixture("codex-tool-summary-paired-mcp");
56+
57+
expect(output.toolSummary).toEqual({ calls: 1, tools: ["github.search"], failures: 0 });
58+
});
59+
60+
it("projects terminal-only MCP and native items in first-observed order", async () => {
61+
const output = await runCodexFixture("codex-tool-summary-terminal-only");
62+
63+
expect(output.toolSummary).toEqual({
64+
calls: 4,
65+
tools: ["lookup", "bash", "apply_patch", "web_search"],
66+
failures: 0,
67+
});
68+
});
69+
70+
it("counts a typed failed terminal MCP item", async () => {
71+
const output = await runCodexFixture("codex-tool-summary-failed-mcp");
72+
73+
expect(output.toolSummary).toEqual({ calls: 1, tools: ["docs.read"], failures: 1 });
74+
});
75+
76+
it("counts a declined command terminal as a failure", async () => {
77+
const output = await runCodexFixture("codex-tool-summary-declined-command");
78+
79+
expect(output.toolSummary).toEqual({ calls: 1, tools: ["bash"], failures: 1 });
80+
});
81+
82+
it.each([
83+
{
84+
fixture: "codex-tool-summary-collab-paired",
85+
tool: "collab.spawn_agent",
86+
failures: 0,
87+
},
88+
{
89+
fixture: "codex-tool-summary-collab-terminal-only",
90+
tool: "collab.wait",
91+
failures: 0,
92+
},
93+
{
94+
fixture: "codex-tool-summary-collab-failed",
95+
tool: "collab.send_input",
96+
failures: 1,
97+
},
98+
{
99+
fixture: "codex-tool-summary-collab-close-agent",
100+
tool: "collab.close_agent",
101+
failures: 0,
102+
},
103+
])("projects $fixture lifecycle metadata", async ({ fixture, tool, failures }) => {
104+
const output = await runCodexFixture(fixture);
105+
106+
expect(output.toolSummary).toEqual({ calls: 1, tools: [tool], failures });
107+
});
108+
});

‎src/agents/cli-runner.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1209,6 +1209,9 @@ export async function runPreparedCliAgent(
12091209
stopReason,
12101210
refusal: false,
12111211
},
1212+
...(resultParams.output.toolSummary
1213+
? { toolSummary: resultParams.output.toolSummary }
1214+
: {}),
12121215
agentMeta: {
12131216
sessionId: agentSessionId,
12141217
provider: params.provider,

0 commit comments

Comments
 (0)