Skip to content

feat(agents): report per-run stats (code-mode engagement, round trips, cost) in agent JSON envelopes - #114688

Merged
steipete merged 2 commits into
mainfrom
feat/agent-run-stats-meta
Jul 28, 2026
Merged

steipete merged 2 commits into
mainfrom
feat/agent-run-stats-meta

Conversation

@steipete

@steipete steipete commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Agent runs report token usage today, but consumers of openclaw agent --json and openclaw agent exec --json cannot answer three practical questions about a run:

  • Did code mode actually own the model tool surface? With feat: per-model code-mode capability flags with an "auto" master-switch tier #114695's "auto" tier, engagement now also depends on per-model capability, and it is silently skipped for models routed through a native harness surface (for example OpenAI-family models on their harness). The shell tool is also named exec, so tool names cannot be trusted as an engagement signal.
  • How many assistant/provider round trips did the run take, and how do provider-visible outer tool calls split from code-mode inner bridge calls?
  • What did the run cost in USD, when the model catalog carries pricing?

Why This Change Was Made

The data already exists at run time — codeModeControlsEnabledForRun in the embedded tool-surface prepare (now computed via isCodeModeEngagedForModel from #114695), per-catalog search/describe/call counters in the tool-search runtime, per-message assistant completions in the subscription, and the shared pricing helpers in src/utils/usage-format.ts — it just was never projected into the run metadata. This change stamps it into EmbeddedAgentRunMeta.agentMeta additively:

  • codeModeEngaged: boolean — from the embedded attempt's tool-surface truth; plugin-harness attempts that do not report engagement intentionally read as false, which makes the config-enabled-but-unengaged case observable. The attempt-result field is an additive seam harnesses can adopt (the tool-surface bridge already exposes codeModeControlsEnabled).
  • assistantTurns — completed assistant round trips, accumulated across model attempts beside the existing usage accumulator so retried attempts stay counted like their tokens; omitted at zero.
  • bridgeCalls: { search, describe, call } — cumulative across every model attempt of the run: each attempt's catalog counters are read before attempt cleanup clears the catalog session, then folded into the run accumulator (mergeAttemptRunStatsIntoAccumulator), so retries/fallbacks do not discard earlier counts. Outer calls stay in the unchanged toolSummary.calls.
  • costUsd — computed with the existing resolveModelCostConfig + estimateUsageCost helpers (cache read/write pricing and tiered pricing included), omitted entirely when the model has no cost data — no zero sentinels.

No existing envelope/meta fields were removed or renamed; no config keys, env vars, SQLite, or gateway-protocol schema changes. The spec's optional "code mode enabled but not engaged" startup log was skipped: engagement truth is distributed across surfaces (the codex harness has its own native code mode), so a core-side log would fire in misleading places; codeModeEngaged in the run meta is the reliable signal.

User Impact

openclaw agent --json (meta.agentMeta) and openclaw agent exec --json (top-level envelope) now report codeModeEngaged, assistantTurns, bridgeCalls, and costUsd. Documented in docs/cli/agent.md and the code-mode telemetry section of docs/tools/code-mode.md. Existing consumers are unaffected (additive fields only).

Evidence

Focused tests (new coverage: codeModeEngaged engaged/not-engaged/unreported stamping, assistant-turn counting incl. transcript-only and non-assistant exclusions, cumulative bridge-call accumulation across retry/fallback attempts plus omission for catalog-less runs, costUsd math with cache pricing plus both omission cases):

node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/terminal-preparation.test.ts src/agents/embedded-agent-subscribe.handlers.messages.test.ts
 Test Files  2 passed (2)
      Tests  70 passed (70)

node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/terminal-preparation.test.ts src/agents/embedded-agent-runner/usage-accumulator.test.ts src/agents/embedded-agent-runner/run/attempt-result.test.ts
      Tests  10 passed (10)  (agents shard; accumulator + exec shards green)

node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/attempt-result.test.ts src/agents/embedded-agent-runner/usage-accumulator.test.ts src/commands/agent-exec.test.ts src/agents/embedded-agent-runner/run/helpers.test.ts
      Tests  23 passed (23)  (plus agent-exec shard green)

node scripts/check-changed.mjs full gate (delegated Blacksmith Testbox, exit 0, 24m47s): conflict markers, env ratchet, max-lines ratchet, formatting, plugin-SDK API manifest, deprecated API usage, plugin boundaries, core typecheck, and the full changed-lane test fan-out all green.

Autoreview (Codex, gpt-5.6-sol): clean on both the base change and the bridge-accumulation follow-up — "no accepted/actionable findings reported", "patch is correct (0.98)".

ClawSweeper rank-up moves: bridge-call accumulation across attempts is implemented in 41c2776 with a retry regression test. The redacted real-run JSON capture is skipped in this landing: the isolated landing environment has no provider credentials, and the envelope shape plus omission behavior are pinned by the focused unit tests above (agent-exec.test.ts exercises the envelope projection; terminal-preparation tests pin field presence/omission). Happy to attach a live capture in a follow-up from a credentialed setup.

@steipete
steipete marked this pull request as ready for review July 27, 2026 18:41
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation commands Command implementations agents Agent runtime and tooling size: M maintainer Maintainer-authored PR labels Jul 27, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Jul 27, 2026
@clawsweeper

clawsweeper Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 27, 2026, 10:43 PM ET / July 28, 2026, 02:43 UTC.

ClawSweeper review

What this changes

Adds additive codeModeEngaged, assistantTurns, bridgeCalls, and estimated costUsd fields to embedded-agent metadata and the openclaw agent exec --json envelope.

Merge readiness

⛔ Blocked until real behavior proof is added - 6 items remain

This PR is not ready to merge: costUsd prices all accumulated retry/fallback usage using the terminal model’s cost configuration, so a run that switches models can report an incorrect dollar cost. It also still needs redacted after-fix evidence from a real agent CLI JSON run; the maintainer label keeps the final direction and proof gate with a human reviewer.

Priority: P2
Reviewed head: 85d7a5f4ce39cf5726e3148fa54fecaa0d2ce51b
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The implementation has a concrete mixed-model cost defect and lacks the required real CLI behavior proof.
Proof confidence 🧂 unranked krab (1/6) Needs real behavior proof before merge: The PR explicitly omits a redacted after-fix real agent JSON run; focused tests and CI are supplemental, so add a redacted terminal capture showing fields and omission behavior before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The PR explicitly omits a redacted after-fix real agent JSON run; focused tests and CI are supplemental, so add a redacted terminal capture showing fields and omission behavior before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 5 items Mixed-model cost defect: The branch aggregates token usage across attempts, but terminal preparation calls estimateUsageCost once with the final reported provider/model. A retry or fallback to a differently priced model therefore prices earlier attempt usage at the terminal model’s rates.
Attempt aggregation path: The branch deliberately merges usage and run statistics per attempt in both normal attempt normalization and settled-turn finalization, confirming that the public fields represent a multi-attempt run rather than only the terminal attempt.
Prior review continuity: The latest completed ClawSweeper cycle already identified per-attempt model pricing as a P2 concern. The latest branch follow-up fixes bridge-call accumulation but does not add a per-attempt cost accumulator or a mixed-model pricing regression test.
Findings 1 actionable finding [P2] Price each model attempt before aggregating cost
Security None None.

How this fits together

The embedded agent runner can make multiple model attempts for one run, collecting usage and tool activity before terminal preparation produces metadata. The agent CLI then exposes selected metadata fields in its JSON result for automation and operator tooling.

flowchart LR
  A[Agent CLI request] --> B[Embedded model attempts]
  B --> C[Per-attempt usage and activity]
  C --> D[Run statistics accumulator]
  D --> E[Terminal agent metadata]
  E --> F[Agent CLI JSON envelope]
Loading

Decision needed

Question Recommendation
For a run that retries or falls back across models with different prices, should costUsd be an accurate sum of per-attempt pricing, or should it be omitted when a single model-cost figure would be misleading? Sum each attempt’s cost: Record cost when each attempt is normalized and expose the aggregate, which preserves the documented run-wide estimate.

Why: The current public field is described as the cost of accumulated run usage, but the implementation has only one terminal model cost configuration after usage from several models has been combined.

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The PR explicitly omits a redacted after-fix real agent JSON run; focused tests and CI are supplemental, so add a redacted terminal capture showing fields and omission behavior before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Price each model attempt before aggregating cost (P2) - usageMeta.usage contains tokens from every retry/fallback attempt, but this call resolves cost only for reportedModelRef, the terminal model. If an earlier attempt used a differently priced model, the emitted run-wide costUsd is wrong. Accumulate cost per attempt when its provider/model is still known, and cover a mixed-model retry case.
  • Resolve merge risk (P2) - A retry or fallback across differently priced models can produce an inaccurate public costUsd, because cumulative usage is priced once using the terminal model rather than each attempt’s resolved pricing.
  • Resolve merge risk (P1) - The public JSON fields are documented as run-wide telemetry, but no redacted real openclaw agent --json or openclaw agent exec --json output currently demonstrates field projection and omission behavior outside mocked tests.
  • Complete next step (P2) - The repair is mechanically clear, but the protected maintainer label, public mixed-model cost semantics, and missing contributor-run proof require human handling before merge.

Findings

  • [P2] Price each model attempt before aggregating cost — src/agents/embedded-agent-runner/run/terminal-preparation.ts:85-94
Agent review details

Security

None.

PR surface

Source +146, Tests +194, Docs +31. Total +371 across 19 files.

View PR surface stats
Area Files Added Removed Net
Source 13 149 3 +146
Tests 4 194 0 +194
Docs 2 31 0 +31
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 19 374 3 +371

Review metrics

Metric Value Why it matters
Public JSON telemetry fields 4 added The PR creates four documented CLI JSON contracts, so their omission and multi-attempt semantics need to be correct before merge.

Stored data model

Persistent data-model change detected: persistent cache schema: docs/cli/agent.md, persistent cache schema: docs/tools/code-mode.md, vector/embedding metadata: docs/cli/agent.md, vector/embedding metadata: docs/tools/code-mode.md. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Price usage per attempt before aggregation (recommended)
    Resolve and add each attempt’s cost before retry/fallback usage is merged, then add a regression test using differently priced models.
  2. Pause the cost field
    If maintainers do not want to define mixed-model cost semantics now, remove or defer costUsd while retaining independently correct telemetry fields.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Accumulate `costUsd` per model attempt using that attempt’s resolved pricing, cover a mixed-model retry/fallback case, and retain omission when cost data is unavailable.

Technical review

Best possible solution:

Accumulate monetary cost at each attempt using that attempt’s resolved provider/model pricing, preserve omission when no attempt has usable pricing, add mixed-model retry/fallback regression coverage, and attach a redacted real CLI JSON capture before merge.

Do we have a high-confidence way to reproduce the issue?

Yes, from source: construct a run with usage from an initial attempt and a retry/fallback using a differently priced final model; current terminal preparation prices the combined usage with only that final model’s cost config. A focused regression test can reproduce this without provider credentials.

Is this the best way to solve the issue?

No. The new public cost field should preserve pricing per attempt before usage is merged, or deliberately omit mixed-model cost; pricing all accumulated usage with the terminal model is not a reliable run-wide estimate.

Full review comments:

  • [P2] Price each model attempt before aggregating cost — src/agents/embedded-agent-runner/run/terminal-preparation.ts:85-94
    usageMeta.usage contains tokens from every retry/fallback attempt, but this call resolves cost only for reportedModelRef, the terminal model. If an earlier attempt used a differently priced model, the emitted run-wide costUsd is wrong. Accumulate cost per attempt when its provider/model is still known, and cover a mixed-model retry case.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 4273ca9dbd9b.

Labels

Label justifications:

  • P2: Incorrect cost telemetry affects automation and operator reporting but does not disrupt agent execution.
  • merge-risk: 🚨 other: A merged public costUsd field can misstate spend whenever one run contains differently priced retry or fallback attempts.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR explicitly omits a redacted after-fix real agent JSON run; focused tests and CI are supplemental, so add a redacted terminal capture showing fields and omission behavior before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Mixed-model cost defect: The branch aggregates token usage across attempts, but terminal preparation calls estimateUsageCost once with the final reported provider/model. A retry or fallback to a differently priced model therefore prices earlier attempt usage at the terminal model’s rates. (src/agents/embedded-agent-runner/run/terminal-preparation.ts:85, 85d7a5f4ce39)
  • Attempt aggregation path: The branch deliberately merges usage and run statistics per attempt in both normal attempt normalization and settled-turn finalization, confirming that the public fields represent a multi-attempt run rather than only the terminal attempt. (src/agents/embedded-agent-runner/run/attempt-normalization.ts:168, 85d7a5f4ce39)
  • Prior review continuity: The latest completed ClawSweeper cycle already identified per-attempt model pricing as a P2 concern. The latest branch follow-up fixes bridge-call accumulation but does not add a per-attempt cost accumulator or a mixed-model pricing regression test. (src/agents/embedded-agent-runner/usage-accumulator.ts:73, 85d7a5f4ce39)
  • Missing real behavior proof: The PR body explicitly says the redacted real-run JSON capture is skipped and supplies focused tests and hosted checks instead. Those are supplemental evidence, not an after-fix agent CLI run. (85d7a5f4ce39)
  • Related merged context: The merged code-mode capability PR supplies the adjacent engagement semantics that this PR reports, but it does not establish the new mixed-model cost calculation contract. (src/agents/embedded-agent-runner/types.ts:82, 7394262cd137)

Likely related people:

  • steipete: Authored the merged adjacent code-mode capability work and this PR’s agent-run telemetry changes, making them the strongest available routing candidate for the engagement and CLI metadata contract. (role: recent area contributor; confidence: medium; commits: 7394262cd137, 9c0025750fa6, 85d7a5f4ce39; files: src/agents/embedded-agent-runner/run/terminal-preparation.ts, src/agents/embedded-agent-runner/usage-accumulator.ts, src/commands/agent-exec.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Accumulate costUsd per model attempt and add a mixed-model retry/fallback regression test.
  • Attach redacted output from a real openclaw agent --json or openclaw agent exec --json run showing the new fields and at least one omission case.
  • Update the PR body after adding proof; that should trigger a fresh ClawSweeper review, or a maintainer can comment @clawsweeper re-review if needed.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-07-27T18:46:19.899Z sha c502e2c :: needs real behavior proof before merge. :: [P2] Accumulate cost at each model attempt | [P2] Carry bridge counts across retry attempts
  • reviewed 2026-07-27T23:31:24.982Z sha 141d505 :: needs real behavior proof before merge. :: [P2] Accumulate bridge counts across retry attempts
  • reviewed 2026-07-28T01:17:56.453Z sha 2046458 :: needs real behavior proof before merge. :: [P2] Accumulate cost using each attempt’s model pricing

@steipete
steipete force-pushed the feat/agent-run-stats-meta branch from c502e2c to 141d505 Compare July 27, 2026 23:26
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 27, 2026
@steipete
steipete force-pushed the feat/agent-run-stats-meta branch from 41c2776 to 2046458 Compare July 28, 2026 01:13
steipete added 2 commits July 27, 2026 19:37
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).
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.
@steipete
steipete force-pushed the feat/agent-run-stats-meta branch from 2046458 to 85d7a5f Compare July 28, 2026 02:38
@steipete
steipete merged commit cf4cb0a into main Jul 28, 2026
121 checks passed
@steipete
steipete deleted the feat/agent-run-stats-meta branch July 28, 2026 03:48
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 28, 2026
…, cost) in agent JSON envelopes (openclaw#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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling commands Command implementations docs Improvements or additions to documentation maintainer Maintainer-authored PR merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant