Skip to content

feat(agent-core-v2): prepend wall-time header to persisted tool results - #3966

Merged
sailist merged 1 commit into
MoonshotAI:mainfrom
sailist:feat-261-09-21-tool-call-duration-in-result
Sep 22, 2026
Merged

sailist merged 1 commit into
MoonshotAI:mainfrom
sailist:feat-261-09-21-tool-call-duration-in-result

Conversation

@sailist

@sailist sailist commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Related Issue

N/A — internal feature task.

Problem

The model has no way to perceive how long a tool call took. Kimi Code already measures per-call durationMs in the tool executor, but only forwards it to telemetry, so the agent cannot reason about execution latency (e.g. telling "this command ran for 30 s" apart from an instant result). OpenAI's codex CLI addresses this by prepending a Wall time: N seconds header only in the model-bound tool-result payload while every UI surface keeps rendering the raw output; this PR brings the same architecture to Kimi Code, including for background tasks.

What changed

  • Duration plumbing: the per-call durationMs already measured in the executor is now carried on ToolExecutionResult, passed through the machine engine's onToolResult callback into the loop, and persisted as a numeric field on the tool.result loop event and ContextMessage.
  • Model-only wall-time header: the persisted tool output stays the tool's raw text. When the context projector builds the model-bound payload, renderToolResultForModel prepends Wall time: N.NNN seconds (merged into the first text part, or as a leading text part for non-text results) whenever the message carries a measured durationMs. Synthetic results (failed calls, abort backfills) carry no duration and no header. The behavior is not gated — it applies to every real tool execution.
  • UI surfaces untouched: the live transcript (executor events) and cold transcript reads after resume (folded from the persisted records) both see the raw output, so no UI ever displays the header — same separation as codex's response_payload vs raw event rendering. The empty-output <system> marker now survives intact, since the sentinel text is no longer overwritten.
  • Background task timing in the same Wall time: N.NNN seconds wording: TaskList / TaskOutput / WaitFor outputs (and the active-background-task reminder) previously rendered raw started_at / ended_at epoch milliseconds the model could not relate to anything; they now drop those fields and lead with a single Wall time: N.NNN seconds line computed from them. The persisted task schema is unchanged. Being tool-authored content, this line also appears in the TUI (same as codex's code-mode output).
  • Completion notifications carry the duration too: automatic background-task terminal notifications (completed / failed / timed out / stopped) now open with a Wall time: N.NNN seconds line computed from the task's start/end timestamps, instead of only an output-file path.
  • Unchanged surfaces: executor-level observable tool.result events and telemetry output are untouched, and old sessions replay byte-identically (records without durationMs render exactly as before).
  • Tests: existing executor / machine-tools / context-fold / projector / task-tools / notification cases and end-to-end snapshots extended to cover the behavior (repo rule: net-zero test count); the snapshot harness normalizes the volatile duration to <duration>; state/wire manifests regenerated.

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue — none; internal feature task.
  • I have added tests that prove my feature works — existing tests extended per the repo's net-zero test-count rule.
  • Ran gen-changesets skill, or this PR needs no changeset — concluded no changeset is needed.
  • Ran gen-docs skill, or this PR needs no doc update — no doc surface (behavior is automatic and model-facing only).

@changeset-bot

changeset-bot Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 9509a89

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

@sailist
sailist force-pushed the feat-261-09-21-tool-call-duration-in-result branch from d6df4a9 to 5e042b6 Compare September 21, 2026 11:40
@pkg-pr-new

pkg-pr-new Bot commented Sep 21, 2026 •

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

commit: 9509a89

@sailist
sailist force-pushed the feat-261-09-21-tool-call-duration-in-result branch 4 times, most recently from 18208d4 to 0c18643 Compare September 21, 2026 12:15
@sailist

sailist commented Sep 21, 2026

Copy link
Copy Markdown
Collaborator Author

@codex

@sailist
sailist force-pushed the feat-261-09-21-tool-call-duration-in-result branch 4 times, most recently from 085fbb5 to 592a5aa Compare September 21, 2026 12:47
@sailist
sailist force-pushed the feat-261-09-21-tool-call-duration-in-result branch from 592a5aa to 262f413 Compare September 21, 2026 13:25
@sailist
sailist force-pushed the feat-261-09-21-tool-call-duration-in-result branch from 262f413 to 9509a89 Compare September 22, 2026 02:05
@RealKai42

Copy link
Copy Markdown
Collaborator

@codex

@sailist
sailist merged commit 0dc4d4f into MoonshotAI:main Sep 22, 2026
15 checks passed
7723qqq added a commit to 7723qqq/kimi-code that referenced this pull request Sep 22, 2026
Port of upstream MoonshotAI#3966 (agent-core-v2), all three observable pieces:

- Tool results: the scheduler measures each call's duration (after the
  permit acquire, mirroring v2's executor) and returns it index-aligned
  with the results via ScheduledToolOutcome; run_turn prepends a
  `Wall time: X.XXX seconds` line at the tool-result message site for
  the v2 set (Agent, AgentSwarm, Bash, FetchURL, Glob, Grep, WebSearch)
  plus every mcp__ tool. The persisted/model-facing history carries the
  header; the raw tool.native event does not.
- Task records: format_task_record replaces startedAt/endedAt with the
  wall-time line (endedAt falling back to now), routed through
  render_task_entry so TaskList entries, TaskOutput metadata, WaitFor's
  [finished] and [still_running] all carry it; TaskStop's two branches
  prepend the line when the response carries timing.
- Notifications: TaskNotification gains started_at and
  render_task_notifications opens each block with the wall-time line
  (the tower wake keeps its early return).

Not ported: v2's durationMs manifest fields — the fork bakes the header
into content and LLMMessage carries no timing field. The delta gate
records the verdict (ported=17); ROADMAP §6.6 reference in the
allowlist note.
7723qqq added a commit to 7723qqq/kimi-code that referenced this pull request Oct 3, 2026
…rker

v2 runs every role:"tool" message through renderToolResultForModel
(contextMemory/toolResultRender.ts, called from projection.ts:342) in three
steps: the status wrapper, a wall-time header, and a trailing note. The fork had
ported only the middle step (upstream MoonshotAI#3966), and is_error fed the event stream
alone — so a failed call and a successful call with nothing to say reached the
model as the same empty text. That marker is how the model tells the two apart.

turn_loop/tool_result_render.rs ports the status step, v2-verbatim: an error is
prefixed with <system>ERROR: Tool execution failed.</system>, an error with no
output gets the combined marker, and a non-error with no output gets
<system>Tool output is empty.</system>. The call site composes it in v2's order
— status first, wall-time header prepended on top — so a failed Bash call reads
"Wall time: X.XXX seconds\n<system>ERROR: …</system>\n{content}".

Two asymmetries are copied deliberately, because they are v2's behaviour rather
than an oversight: the error arm tests the raw length, so whitespace-only content
survives verbatim after the marker, while the non-error arm trims and also treats
the literal "Tool output is empty." as empty.

The four new literals go through scan:hardcoded:rust, which fails until each is
recorded. seedReason already routes the three <system>…</system> markers to
format-scaffolding, matching the existing entry for
<system>No lines read from file. …</system>. The fourth is a sentinel that
render_status matches and replaces — its display text is produced elsewhere — so
deferred ("a real TODO") would mislabel it; it is recorded as wire-token with
manual: true, which --seed preserves. --seed's diff here is +20/-0 lines: the
four entries, with no churn across the other 1755.

The markers stay English. AGENTS.md lists <system>{}</system> under format
scaffolding — "no prose to translate" — and v2 hardcodes these same strings, so
the unused emptyOutput catalog key is not the source and stays orphan debt.

Deliberately not ported here, both recorded in ROADMAP §10.28: the trailing note
(this engine overloads note as an internal provenance tag — "tool_policy",
"tool_select", "native_subagent" — so v2's unconditional append would write those
tags into the model's context), and Read's rendered-length truncation budget.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Oct 5, 2026
Step 9 of the incremental sync to 2.1.1: 24 upstream commits over 321
files. The step brings the TUI mode setting, the jump-to-bottom
indicator, click-to-toggle transcript folds, banner audience targeting
and the workspace-trust hardening.

Upstream's changes in this step, all absorbed:
- add a TUI mode setting for the fullscreen layout (MoonshotAI#4004)
- add a jump-to-bottom indicator and a steady status row (MoonshotAI#3989)
- toggle one transcript fold block with a click (MoonshotAI#3990)
- support audience targeting for startup banners (MoonshotAI#3868)
- harden workspace trust boundaries across git, file tools and the
  local web server (MoonshotAI#3964)
- turn off filesystem watch by default (MoonshotAI#3931)
- add the auto_session_title config option (MoonshotAI#3962)
- prepend a wall-time header to persisted tool results (MoonshotAI#3966)
- report enabled plugins and plugin toggles in telemetry (MoonshotAI#3963)
- include step timing and usage in cold-folded steps (MoonshotAI#3938)
- restore swarm members from persisted lifecycle events (MoonshotAI#3970)
- enforce tower protocol invariants and deny AgentSwarm (MoonshotAI#3976)
- inherit titleKind for default fork titles (MoonshotAI#3974)
- request offline_access in MCP OAuth when the authorization server
  advertises it (MoonshotAI#3979)
- cut CLI startup time and memory in the native binary and config reads
  (MoonshotAI#3975)
- avoid a stack overflow when caching large wire files (MoonshotAI#3957)
- reject non-ASCII mission titles and record token usage (MoonshotAI#3847)
- pick the credential slot and relay from the login region (MoonshotAI#3969)
- add the KIMI_CODE_REPEAT_BREAKER env switch (MoonshotAI#3995)
- update the kimi-webbridge plugin to the 2.0.11 skill (MoonshotAI#3961)
- restructure the PR template and add the write-pr and review-pr skills
  (MoonshotAI#3992)

Fork behaviour that had to survive:
- the TUI controller split: upstream's rewritten activity-pane logic
  (braille thinking/composing spinners, the shared loading-tip kind) was
  ported into the fork's ActivityPaneController, and KimiTUI keeps
  delegating to it
- the i18n layer: the new TUI mode setting, its picker, the restart
  notice and the settings entry all go through `t()` with en/zh entries
- the fork's node-local → host rename: the upstream test files that
  still imported `#/os/backends/node-local/hostFsService` now point at
  `#/os/backends/host/hostFsService`
- the fork's inline media reading: upstream's realpath guard for the
  media tool is covered by a ReadTool-based symlink-escape test
- the fork's removePlugin deletes the plugin root from disk, so the new
  toggle-telemetry fixture keeps its root inside the managed directory
- the Bun toolchain: the retired Node SEA chain stays retired

Verified: typecheck clean across every package and app; full suite
17831 passed / 0 failed / 81 skipped / 1 todo, plus kimi-inspect's own
115 tests; lint 0 errors.
raitoxlol pushed a commit to raitoxlol/hermes-agent that referenced this pull request Nov 23, 2026
… kimi-code#3966)

Port from MoonshotAI/kimi-code#3966: the model could not perceive tool latency.
The executor already measured every real tool call's duration but only forwarded
it to hooks, telemetry and UI callbacks, so a 30 s command and an instant result
looked identical on the wire.

The measured duration now rides on the tool message as ``duration_ms`` (its own
messages column; schema reconciliation adds it to live DBs) and
``build_api_messages`` prepends ``Wall time: N.NNN seconds`` to the model-bound
copy only. Persisted content stays the raw tool output, so the loop guardrails
(byte-identical result streaks, duplicate-result stubs), the JSON-parsing error
classifiers, the compression summariser and every UI surface keep seeing the
unchanged bytes; the header is deterministic from the stored number, so replays
(next iteration, resume) stay byte-stable for the prompt cache. The token
estimator's wire shadow prices the header too. Blocked/synthetic results carry
no duration and no header.

Why not display_metadata: that sidecar must never influence provider bytes
(tests/agent/test_inline_edit_persistence.py invariant); the first cut stored the
number there and broke it, hence the dedicated column.
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.

3 participants