Skip to content

fix(agent-core-v2): record measured tool durations in tool message attributes - #5266

Merged
sailist merged 2 commits into
mainfrom
bug-425-11-23-tool-wall-time-content
Nov 23, 2026
Merged

sailist merged 2 commits into
mainfrom
bug-425-11-23-tool-wall-time-content

Conversation

@sailist

@sailist sailist commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

Tool results lost their measured duration on live turn requests. Since the agent loop runtime port (#4630), live tool messages are created by the core runtime, whose tool result contract had no duration field — so the request-time rendering pipeline saw attributes.durationMs on compaction and resumed requests (enriched from the journal) but never on the live path. The same tool result produced byte-different request content depending on the path, which broke prompt-cache prefix sharing between turn and compaction requests (observed as an 18.86% cache hit rate on a manual compaction).

Bug Reproduction Steps

N/A (internal fix; root cause below was confirmed by diffing turn vs compaction request payloads byte-for-byte on a real session)

Root Cause

The executor-measured duration (prepared.durationMs, the same monotonic value the journal records on tool.ended) had no channel into the core tool result contract: ToolReturn/ToolResult carried no duration, so toolOutcomeMessage could not write attributes.durationMs for live messages. This is a fundamental fix: it connects the missing channel instead of re-deriving the value downstream.

Code Changes

  • @moonshot-ai/core contract: optional durationMs on ToolReturn, ToolResult, and ToolMessageAttributes; ToolStoppingContext.abandon gains an optional second parameter so abandoning without a result can still report the measured duration.
  • Core executor (tool-executor.ts): returned() and abandon() thread the duration through every result shape; the two post-execution failure replacements (output-close failure, afterExecute hook throw) carry the discarded result's duration inline; journal/fold/projection are untouched.
  • toolOutcomeMessage writes attributes.durationMs (detach acknowledgements carry none, matching the journal).
  • LegacyExecutableToolAdapter fills the duration on all paths: execute (measured), synthetic (0), and the three abandon paths — the value is frozen at abandon time so the live message and the journal-enriched value are the same number.
  • Tests: core executor threading + abandon shapes; adapter paths asserting result.durationMs === legacyToolDurationMs(snapshot) (live value equals the journal source); a three-path consistency test asserting turn, compaction, and resumed requests render one identical tool result (measured and 0ms forms).

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Live turn/compaction request content for duration-reporting tools No duration header rendered live; header present on resume The measured duration renders identically on all three paths (restores pre-#4630 behavior) None known — this restores the intended rendering N/A
Abandoned tool results Journal recorded a duration; live message had none Live message carries the same frozen value None N/A
ToolStoppingContext.abandon (result?) (result?, durationMs?) — additive, existing callers unaffected Tool authors N/A
Token usage snapshots on live requests with such tools Slightly lower +~6 tokens per rendered duration (plan tests updated accordingly) None N/A

Coverage: packages/core 387/387; on this base, packages/agent-core-v2 focused suites — fullCompaction.test.ts 119/119 (including the new three-path consistency case), toolExecutor + plan 90/90; tests/scenarios/conversation.test.ts 24/25, the single failure being the manual-mode approval case (item.ended double-fire), which also reproduces on a clean main checkout locally and is unrelated to this change. Typecheck for packages/core and packages/agent-core-v2 clean; oxlint --type-aware 0/0. The product code is byte-identical to the previous CI-green head of this PR, whose full-suite run (7717 passed, 10 failures all attributed to pre-existing/environmental causes) is in the PR history.

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve). (internal PR, N/A)
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T10:24:09.611106Z 74c2119 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@changeset-bot

changeset-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 74c2119

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
@moonshot-ai/agent-core-v2 Patch
@moonshot-ai/core Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@pkg-pr-new

pkg-pr-new Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@74c2119
npx https://pkg.pr.new/@moonshot-ai/kimi-code@74c2119

commit: 74c2119

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

const replaced = await this.host.hook?.afterExecute?.(hookContext);
if (replaced !== undefined) result = reconcile(result, replaced, this.call.id);

P1 Badge Preserve duration across afterExecute replacements

When an afterExecute hook returns a replacement without durationMs, reconcile replaces the timed result and silently drops its duration. This occurs in production paths such as legacyRejectedResult used by dynamic-tool selection and desktop browser guidance, which construct fresh untimed ToolResult objects. The journal remains enriched from the adapter snapshot, so those tool results again render differently live versus during compaction/resume; retain the previous duration when the replacement does not supply one.

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

const finalized = await this.finalize(context.call.id, coerceLegacyResult(result, this.name));
prepared.result = finalized;
return legacyResult(finalized, this.name);
return { ...legacyResult(finalized, this.name), durationMs: prepared.durationMs };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Propagate durations when legacy tool execution throws

When execution.execute(...) or the legacy result finalizer throws, this return statement is bypassed: the adapter records prepared.durationMs in finally, but the core executor converts the exception to an untimed failure result. The live tool message therefore has no wall-time header, while turnProjection.ts later enriches the journal from legacyToolDurationMs(snapshot), so compaction and resumed requests still differ from the live request for failed tools—the cache-prefix inconsistency this change is intended to eliminate. Ensure the measured duration is also attached to exception results.

Useful? React with 👍 / 👎.

@sailist
sailist changed the base branch from refact-419-11-22-drop-prepare-capability-filter to main November 23, 2026 08:34
@sailist
sailist force-pushed the bug-425-11-23-tool-wall-time-content branch from 429abf3 to 517a403 Compare November 23, 2026 08:34

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 517a40311f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

type: 'synthetic',
prepared: { kind: 'synthetic', result, durationMs: 0 },
result: legacyResult(result, this.name),
result: { ...legacyResult(result, this.name), durationMs: 0 },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Attach a duration when legacy preparation rejects

When resolveExecution(...) rejects, execution never reaches this timed synthetic return and the core executor creates an untimed failure message. However, turnProjection.ts later persists legacyToolDurationMs(snapshot) as 0, so the live follow-up omits the wall-time header while compaction or resume renders Wall time: 0.000 seconds, recreating the cache-prefix mismatch for tools whose execution resolution fails. Ensure preparation failures also produce a result carrying duration 0.

Useful? React with 👍 / 👎.

7Sageer
7Sageer previously approved these changes Nov 23, 2026
@sailist
sailist force-pushed the bug-425-11-23-tool-wall-time-content branch from 517a403 to a5ea08f Compare November 23, 2026 09:24

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a5ea08fb13

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

isError: failed ? true : undefined,
stopTurn: 'stopTurn' in result && result.stopTurn === true ? true : undefined,
detached,
durationMs: 'durationMs' in result ? result.durationMs : undefined,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Cover pre-execution failures with a zero duration

When a tool call fails before adapter execution—for example because its JSON is malformed, the tool is unknown or invalid, or a starting/permitting hook vetoes it—the core executor produces a ToolResult without durationMs, so this line omits the timing header from the live follow-up. AgentTurnProjection nevertheless persists legacyToolDurationMs(snapshot), which is 0 when no preparation duration exists, so compaction or resume later renders Wall time: 0.000 seconds and changes the cache prefix. Ensure these pre-execution failure results carry the same zero duration and cover these additional trigger paths.

AGENTS.md reference: AGENTS.md:L60-L60

Useful? React with 👍 / 👎.

@sailist
sailist force-pushed the bug-425-11-23-tool-wall-time-content branch from a5ea08f to 74c2119 Compare November 23, 2026 10:21
@sailist
sailist merged commit 1655099 into main Nov 23, 2026
28 checks passed
@sailist
sailist deleted the bug-425-11-23-tool-wall-time-content branch November 23, 2026 11:10
@github-actions github-actions Bot mentioned this pull request Nov 24, 2026
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 24, 2026
Record MoonshotAI#5247 ported and MoonshotAI#5258, MoonshotAI#5259 and MoonshotAI#5266 equivalent to the fork's
own sidebar, composer and tool-duration implementations, each with an
executable probe.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants