Skip to content

Commit cf4cb0a

Browse files
authored
feat(agents): report per-run stats (code-mode engagement, round trips, cost) in agent JSON envelopes (#114688)
* feat(agents): add per-run stats to embedded agent run meta Adds codeModeEngaged, assistantTurns, bridgeCalls, and costUsd to EmbeddedAgentRunMeta.agentMeta and mirrors them on the agent exec --json envelope. Code-mode engagement is stamped from the tool-surface truth, round trips accumulate across attempts beside usage, bridge counts come from the run's tool-search catalog counters, and cost reuses the shared model pricing helpers (cache tiers included, omitted without cost data). * fix(agents): accumulate bridge call counts across run attempts Attempt cleanup clears the per-attempt tool-search catalog, so retries and fallbacks discarded earlier bridge counts. Fold each attempt's bridgeCalls into the run accumulator beside assistantTurns and stamp the cumulative totals into agentMeta, matching the documented per-run contract.
1 parent e1ced6d commit cf4cb0a

19 files changed

Lines changed: 374 additions & 3 deletions

‎docs/cli/agent.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,10 @@ Plain output writes only the final assistant text to stdout. Diagnostics use std
5252
"final": "The focused tests pass.",
5353
"payloads": [{ "text": "The focused tests pass." }],
5454
"usage": { "input": 120, "output": 8, "total": 128 },
55+
"costUsd": 0.0021,
56+
"codeModeEngaged": false,
57+
"assistantTurns": 2,
58+
"bridgeCalls": { "search": 1, "describe": 0, "call": 3 },
5559
"model": "gpt-5.6-sol",
5660
"provider": "openai",
5761
"sessionId": "019..."
@@ -60,6 +64,15 @@ Plain output writes only the final assistant text to stdout. Diagnostics use std
6064

6165
`status` is `ok`, `error`, or `timeout`. `usage` is omitted when unavailable. Failed envelopes add `error: { message, kind }`; `model` and `provider` are `null` when failure happens before model selection.
6266

67+
Run-stat fields are additive and may be absent:
68+
69+
- `costUsd`: estimated USD cost of the run's accumulated usage, including cache read/write pricing; omitted when the model has no cost data.
70+
- `codeModeEngaged`: `true` only when [code mode](/tools/code-mode) actually owned the model tool surface for the run. `tools.codeMode.enabled=true` alone does not guarantee engagement; models routed through a native harness surface can leave it `false`.
71+
- `assistantTurns`: completed assistant/provider round trips in the run; omitted when none completed.
72+
- `bridgeCalls`: inner tool-search/code-mode bridge call counts (`search`/`describe`/`call`). These are invisible to the provider; outer tool calls stay in `meta.toolSummary.calls` of the full run metadata.
73+
74+
The same fields appear on `meta.agentMeta` in the `openclaw agent --json` response.
75+
6376
### `agent exec` options
6477

6578
- `[message]`: positional prompt text

‎docs/tools/code-mode.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -971,6 +971,24 @@ breakdown (`openclaw`/`mcp`/`client` counts), cumulative search/describe/call
971971
counts for the run's catalog, and the model-visible tool names (`exec`,
972972
`wait`, and retained direct-only tools).
973973

974+
The run metadata (`meta.agentMeta` in `openclaw agent --json`, mirrored on the
975+
`agent exec --json` envelope) adds per-run stats:
976+
977+
- `codeModeEngaged`: `true` only when code mode actually owned the model tool
978+
surface. This is the reliable engagement signal — do not infer engagement
979+
from config or tool names: the shell tool is also named `exec`, the
980+
`"auto"` tier engages per model capability, and a model routed through a
981+
native harness surface (for example OpenAI-family models on their harness)
982+
reports `codeModeEngaged: false` even with `tools.codeMode.enabled=true`,
983+
making the silent no-op observable.
984+
- `assistantTurns`: completed assistant/provider round trips across the run.
985+
- `bridgeCalls`: the run's cumulative inner bridge counts
986+
(`{ search, describe, call }`). These calls never reach the provider;
987+
provider-visible outer tool calls remain in `meta.toolSummary.calls`.
988+
- `costUsd`: estimated USD cost from the run's accumulated usage and the
989+
model's cost config (cache read/write tiers included); omitted when the
990+
model has no cost data.
991+
974992
Telemetry must not include secrets, raw environment values, or unredacted
975993
tool inputs beyond existing OpenClaw trajectory policy.
976994

‎src/agents/embedded-agent-runner/run/attempt-normalization.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@ import { log } from "../logger.js";
77
import { createEmbeddedRunReplayState, observeReplayMetadata } from "../replay-state.js";
88
import type { EmbeddedAgentRunResult } from "../types.js";
99
import type { createUsageAccumulator } from "../usage-accumulator.js";
10-
import { mergeUsageIntoAccumulator } from "../usage-accumulator.js";
10+
import {
11+
mergeAttemptRunStatsIntoAccumulator,
12+
mergeUsageIntoAccumulator,
13+
} from "../usage-accumulator.js";
1114
import { applyEmbeddedAttemptSessionIdentity } from "./attempt-session-identity.js";
1215
import type { createEmbeddedRunContextRecoveryState } from "./context-recovery-state.js";
1316
import type { PreparedEmbeddedRunInput } from "./execution-context.js";
@@ -165,6 +168,7 @@ export async function normalizeEmbeddedRunAttempt(input: {
165168
});
166169
const attemptUsage = attempt.attemptUsage ?? callUsage.currentAttempt;
167170
mergeUsageIntoAccumulator(input.usageAccumulator, attemptUsage);
171+
mergeAttemptRunStatsIntoAccumulator(input.usageAccumulator, attempt);
168172
const lastRunPromptUsage = callUsage.latest;
169173
const lastTurnTotal = callUsage.latest?.total;
170174
const breakerStep = stepIdleTimeoutBreaker(input.idleTimeoutBreakerState, {

‎src/agents/embedded-agent-runner/run/attempt-result.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ function completeResult(params?: {
3434
didSendDeterministicApprovalPrompt: () => false,
3535
didSendViaMessagingTool: () => false,
3636
getAcceptedSessionSpawns: () => [],
37+
getAssistantTurnCount: () => 0,
3738
getCompactionCount: () => 0,
3839
getHeartbeatToolResponse: () => undefined,
3940
getItemLifecycle: () => undefined,

‎src/agents/embedded-agent-runner/run/attempt-result.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ export function completeEmbeddedAttemptResult(
150150
didSendDeterministicApprovalPrompt,
151151
didSendViaMessagingTool,
152152
getAcceptedSessionSpawns,
153+
getAssistantTurnCount,
153154
getCompactionCount,
154155
getHeartbeatToolResponse,
155156
getItemLifecycle,
@@ -376,6 +377,7 @@ export function completeEmbeddedAttemptResult(
376377
replayMetadata,
377378
currentAttemptReplayMetadata,
378379
itemLifecycle: getItemLifecycle(),
380+
assistantTurns: getAssistantTurnCount(),
379381
setTerminalLifecycleMeta,
380382
bootstrapPromptWarningSignaturesSeen: input.bootstrapPromptWarning.warningSignaturesSeen,
381383
bootstrapPromptWarningSignature: input.bootstrapPromptWarning.signature,

‎src/agents/embedded-agent-runner/run/attempt.spawn-workspace.test-support.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ function createSubscriptionMock(): SubscriptionMock {
158158
getLastToolError: () => undefined,
159159
getUsageTotals: () => undefined,
160160
getLastAssistantUsage: () => undefined,
161+
getAssistantTurnCount: () => 0,
161162
getCompactionCount: () => 0,
162163
getLastCompactionTokensAfter: () => undefined,
163164
getItemLifecycle: () => ({ startedCount: 0, completedCount: 0, activeCount: 0 }),

‎src/agents/embedded-agent-runner/run/attempt.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -406,7 +406,7 @@ export async function runEmbeddedAttempt(
406406
},
407407
},
408408
});
409-
return await runEmbeddedAttemptExecutionPhase({
409+
const executionResult = await runEmbeddedAttemptExecutionPhase({
410410
attempt: params,
411411
...(activeContextEngine ? { activeContextEngine } : {}),
412412
agentDir,
@@ -447,6 +447,22 @@ export async function runEmbeddedAttempt(
447447
},
448448
},
449449
});
450+
// Read catalog counters before the finally-phase cleanup clears the
451+
// run-scoped catalog session; afterwards the counts are gone.
452+
const catalogSession = toolSearchCatalogRef?.current;
453+
return {
454+
...executionResult,
455+
codeModeEngaged: codeModeControlsEnabledForRun,
456+
...(catalogSession
457+
? {
458+
bridgeCalls: {
459+
search: catalogSession.searchCount,
460+
describe: catalogSession.describeCount,
461+
call: catalogSession.callCount,
462+
},
463+
}
464+
: {}),
465+
};
450466
} finally {
451467
const terminal = projectAgentRunAttemptTerminal(executionState.terminal);
452468
await cleanupEmbeddedAttemptSessionPhase({

‎src/agents/embedded-agent-runner/run/settled-turn-finalization.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ import type {
55
AgentHarnessSettledTurnFinalizationResult,
66
} from "../../harness/types.js";
77
import { log } from "../logger.js";
8-
import { mergeUsageIntoAccumulator } from "../usage-accumulator.js";
8+
import {
9+
mergeAttemptRunStatsIntoAccumulator,
10+
mergeUsageIntoAccumulator,
11+
} from "../usage-accumulator.js";
912
import { runEmbeddedSettledTurnFinalizationWithBackend } from "./backend.js";
1013
import { EMBEDDED_RUN_LANE_HEARTBEAT_MS } from "./lane-runtime.js";
1114
import {
@@ -106,6 +109,7 @@ export async function prepareTerminalWithSettledTurnFinalization(input: {
106109
noteLaneTaskProgress: input.finalization.noteLaneTaskProgress,
107110
});
108111
mergeUsageIntoAccumulator(input.terminalBase.usageAccumulator, attempt.attemptUsage);
112+
mergeAttemptRunStatsIntoAccumulator(input.terminalBase.usageAccumulator, attempt);
109113
lastRunPromptUsage = attempt.attemptUsage ?? lastRunPromptUsage;
110114
lastTurnTotal = attempt.attemptUsage?.total ?? lastTurnTotal;
111115
// Successful isolated finalization owns a fresh terminal, never the original abort signal.

‎src/agents/embedded-agent-runner/run/terminal-preparation.test.ts‎

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,3 +109,138 @@ describe("prepareEmbeddedRunTerminal", () => {
109109
},
110110
);
111111
});
112+
113+
describe("prepareEmbeddedRunTerminal run stats", () => {
114+
type StatsInput = {
115+
attempt?: Partial<EmbeddedRunAttemptResult>;
116+
assistantTurns?: number;
117+
bridgeCalls?: { search: number; describe: number; call: number };
118+
config?: unknown;
119+
provider?: string;
120+
model?: string;
121+
usage?: Partial<
122+
Pick<
123+
ReturnType<typeof createUsageAccumulator>,
124+
"input" | "output" | "cacheRead" | "cacheWrite" | "total"
125+
>
126+
>;
127+
};
128+
129+
async function prepareStats(statsInput: StatsInput = {}) {
130+
const { prepareEmbeddedRunTerminal } = await import("./terminal-preparation.js");
131+
const provider = statsInput.provider ?? "cost-test-provider";
132+
const model = statsInput.model ?? "cost-model";
133+
const assistant = {
134+
...assistantMessage("stop"),
135+
provider,
136+
model,
137+
};
138+
const usageAccumulator = createUsageAccumulator();
139+
Object.assign(usageAccumulator, statsInput.usage);
140+
usageAccumulator.assistantTurns = statsInput.assistantTurns ?? 0;
141+
usageAccumulator.bridgeCalls = statsInput.bridgeCalls;
142+
return prepareEmbeddedRunTerminal({
143+
runParams: {
144+
sessionId: "session-1",
145+
runId: "run-1",
146+
workspaceDir: "/tmp/openclaw-test",
147+
prompt: "hi",
148+
trigger: "user",
149+
timeoutMs: 60_000,
150+
...(statsInput.config ? { config: statsInput.config as never } : {}),
151+
},
152+
attempt: attemptResult({
153+
lastAssistant: assistant,
154+
currentAttemptAssistant: assistant,
155+
currentAttemptCompletedAssistant: assistant,
156+
...statsInput.attempt,
157+
}),
158+
currentAttemptCompletedAssistant: assistant,
159+
provider,
160+
model,
161+
activeErrorContext: { provider, model },
162+
authProfileStore: { version: 1, profiles: {} },
163+
sessionIdUsed: "session-1",
164+
outerContextTokenMeta: {},
165+
usageAccumulator,
166+
contextRecoveryState: createEmbeddedRunContextRecoveryState(),
167+
resolvedToolResultFormat: "markdown",
168+
terminalState: {
169+
outcome: { reason: "completed", status: "ok", stopReason: "stop" },
170+
signalOwnedInterruption: false,
171+
},
172+
});
173+
}
174+
175+
const COST_CONFIG = {
176+
models: {
177+
providers: {
178+
"cost-test-provider": {
179+
models: [
180+
{
181+
id: "cost-model",
182+
cost: { input: 1, output: 2, cacheRead: 0.5, cacheWrite: 4 },
183+
},
184+
],
185+
},
186+
},
187+
},
188+
};
189+
190+
it.each([
191+
{ name: "engaged", codeModeEngaged: true, expected: true },
192+
{ name: "not engaged", codeModeEngaged: false, expected: false },
193+
{ name: "unreported (harness route)", codeModeEngaged: undefined, expected: false },
194+
])("stamps codeModeEngaged when $name", async ({ codeModeEngaged, expected }) => {
195+
const prepared = await prepareStats({ attempt: { codeModeEngaged } });
196+
expect(prepared.agentMeta.codeModeEngaged).toBe(expected);
197+
});
198+
199+
it("stamps assistantTurns from the run accumulator and omits zero", async () => {
200+
const counted = await prepareStats({ assistantTurns: 3 });
201+
expect(counted.agentMeta.assistantTurns).toBe(3);
202+
203+
const empty = await prepareStats({ assistantTurns: 0 });
204+
expect(empty.agentMeta).not.toHaveProperty("assistantTurns");
205+
});
206+
207+
it("stamps run-accumulated bridge call counts and omits them when absent", async () => {
208+
const withBridge = await prepareStats({
209+
bridgeCalls: { search: 2, describe: 1, call: 5 },
210+
});
211+
expect(withBridge.agentMeta.bridgeCalls).toEqual({ search: 2, describe: 1, call: 5 });
212+
213+
const withoutBridge = await prepareStats({});
214+
expect(withoutBridge.agentMeta).not.toHaveProperty("bridgeCalls");
215+
});
216+
217+
it("computes costUsd from accumulated usage including cache pricing", async () => {
218+
const prepared = await prepareStats({
219+
config: COST_CONFIG,
220+
usage: {
221+
input: 1_000_000,
222+
output: 500_000,
223+
cacheRead: 2_000_000,
224+
cacheWrite: 250_000,
225+
total: 3_750_000,
226+
},
227+
});
228+
// (1M*$1 + 0.5M*$2 + 2M*$0.5 + 0.25M*$4) per million tokens.
229+
expect(prepared.agentMeta.costUsd).toBeCloseTo(4, 10);
230+
});
231+
232+
it("omits costUsd when the model has no cost data", async () => {
233+
const prepared = await prepareStats({
234+
provider: "no-cost-provider",
235+
model: "uncosted-model",
236+
config: COST_CONFIG,
237+
usage: { input: 1_000_000, output: 500_000, total: 1_500_000 },
238+
});
239+
expect(prepared.agentMeta).not.toHaveProperty("costUsd");
240+
});
241+
242+
it("omits costUsd when the run reported no usage", async () => {
243+
const prepared = await prepareStats({ config: COST_CONFIG });
244+
expect(prepared.agentMeta).not.toHaveProperty("costUsd");
245+
});
246+
});

‎src/agents/embedded-agent-runner/run/terminal-preparation.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { copyReplyPayloadMetadata } from "../../../auto-reply/reply-payload.js";
22
import type { AssistantMessage } from "../../../llm/types.js";
3+
import { estimateUsageCost, resolveModelCostConfig } from "../../../utils/usage-format.js";
34
import { projectAgentRunAttemptTerminal } from "../../agent-run-terminal-outcome.js";
45
import type { AuthProfileStore } from "../../auth-profiles.js";
56
import type { NormalizedUsage, UsageLike } from "../../usage.js";
@@ -81,6 +82,20 @@ export function prepareEmbeddedRunTerminal(input: {
8182
const finalAssistantStopReason = (terminalAssistant?.stopReason ?? "").trim().toLowerCase();
8283
const terminalAssistantCanOwnFinalText =
8384
finalAssistantStopReason !== "error" && finalAssistantStopReason !== "aborted";
85+
// Total-only usage (lastTurnTotal override) carries no token split, so cost
86+
// math uses the accumulated input/output/cache fields untouched by it.
87+
const costUsd = estimateUsageCost({
88+
usage: usageMeta.usage,
89+
cost: resolveModelCostConfig({
90+
provider: reportedModelRef.provider,
91+
model: reportedModelRef.model,
92+
config: runParams.config,
93+
agentDir: runParams.agentDir,
94+
}),
95+
});
96+
// Attempt normalization already folded every attempt (terminal included)
97+
// into the accumulator, so read it directly instead of re-adding the attempt.
98+
const runAssistantTurns = input.usageAccumulator.assistantTurns;
8499
const agentMeta: EmbeddedAgentMeta = {
85100
sessionId: input.sessionIdUsed,
86101
sessionFile: input.sessionFileUsed,
@@ -99,6 +114,14 @@ export function prepareEmbeddedRunTerminal(input: {
99114
? input.contextRecoveryState.autoCompactionCount
100115
: undefined,
101116
compactionTokensAfter: input.contextRecoveryState.lastCompactionTokensAfter,
117+
// Absent attempt engagement (plugin harness routes) intentionally reads as
118+
// false so config-enabled-but-unengaged code mode is visible to consumers.
119+
codeModeEngaged: attempt.codeModeEngaged === true,
120+
...(runAssistantTurns > 0 ? { assistantTurns: runAssistantTurns } : {}),
121+
...(input.usageAccumulator.bridgeCalls
122+
? { bridgeCalls: { ...input.usageAccumulator.bridgeCalls } }
123+
: {}),
124+
...(costUsd !== undefined ? { costUsd } : {}),
102125
};
103126
const attemptFinalText = attempt.assistantTexts
104127
.toReversed()

0 commit comments

Comments
 (0)