Skip to content

fix(agent-core-v2): truncate foreground output in bash detach acknowledgement - #5218

Merged
sailist merged 1 commit into
loop-refactfrom
bug-418-11-22-bash-detach-ack-truncation
Nov 22, 2026
Merged

sailist merged 1 commit into
loop-refactfrom
bug-418-11-22-bash-detach-ack-truncation

Conversation

@sailist

@sailist sailist commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator

Requirement or Bug

前台 Bash 命令超时自动转后台、或被用户手动转到后台时,detach acknowledgement 会把截至转后台时刻积累的全部输出(上限 1,000 万字符)原样带进模型上下文;输出较大时,后续请求直接超过 1,048,576 token 上限,会话无法继续。本 PR 让 acknowledgement 中的前台输出遵守既有的 50,000 字符工具结果上限,完整输出仍可通过任务输出日志和 TaskOutput 读取。

Bug Reproduction Steps

  1. 运行一个前台 Bash 命令,在超时前产生超过 50,000 字符的输出。
  2. 等待命令超时自动转入后台(或点击 "To background" 手动转后台)。
  3. 观察随 acknowledgement 进入会话的 tool 消息:包含全部已积累输出,无任何截断。

Root Cause

BashTool.backgroundStartedResult() 把 ToolOutputAccumulator 截至 detach 时刻的全部 retained 输出原样拼进 acknowledgement 的 foreground_output: 段;自动超时与手动转后台两条路径共用这一拼接。detach 通道(legacy adapter 的 detach/onDetach → core CallControl.detach)不经过正常完成路径上的 finalize() → truncateForModel(),50,000 字符截断因此被绕过。

这是根本修复:在拼接处同步截断模型可见内容。截断刻意不做落盘——detach 不冻结 ctx.write 的输出通道,全量输出(含转后台后新增部分)本就持续写入任务输出日志;任务在后台结束时,既有 addOutputReference + truncateForModel 已用同一日志指针统一收口,模型收到的完成通知只带引用、不内联输出。detach 时再写 spill 文件只会重复落盘。

Code Changes

改动集中在一个函数(自动超时与手动转后台共用,一处生效):

 BashTool.backgroundStartedResult()
   metadata = task_id / pid / status / next_step / ...
-  foreground_output = accumulator 全部 retained 输出(≤1000 万字符)
+  foreground_output = retained 输出按码点边界截断到 50,000 字符
+  if 发生截断
+    段尾追加一行截断说明:已产生总量、仅显示前 50,000、
+    任务仍在后台运行且输出继续增长
+    任务工具可用时附 TaskOutput(task_id=...) 读取完整输出的提示,
+    不可用时改为「完成时自动通知」措辞
  • run_in_background=true 直接后台启动的场景 accumulator 为空,行为不变;前台正常结束路径完全不动。
  • 截断说明行的措辞与完成时 truncateForModel 的「已保存到文件」提示刻意区分,明确任务仍在运行,避免模型误以为任务已结束。
  • 恰好等于 50,000 字符时不截断,与完成路径 addOutputReference 的 <= 边界一致。

测试(packages/agent-core-v2/test/os/backends/node-local/tools/bash.test.ts):

  • 原 keeps task metadata independent when noisy foreground output is detached 钉住的是旧的(有 bug 的)全量输出行为,改写为新契约 truncates noisy foreground output in the detach acknowledgement while keeping metadata and the full task log,并补「完整输出经任务输出日志可读」断言。
  • 新增 4 个用例:手动 detach 大输出(含 detach 后新增输出仍完整可读)、自动超时 detach 大输出、恰好 50,000 字符边界不截断、任务工具禁用时省略 TaskOutput 提示。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
detach acknowledgement 中的 foreground_output 截至转后台时刻的全部输出(≤1,000 万字符)原样进入模型上下文 截断到前 50,000 字符,段尾附截断说明行 依赖 acknowledgement 内联完整输出的会话——实践中输出超过上下文上限时后续请求直接报错,无人可依赖 完整输出经任务输出日志 / TaskOutput 读取,无信息丢失
detach acknowledgement 文本 无截断说明行 截断时新增一行说明(含 TaskOutput 提示或自动通知措辞) 无(新增文本;按字符串匹配 acknowledgement 的外部脚本会看到新增行) N/A

受影响模块:agent-core-v2 Bash 工具。CLI(TUI 后台任务)、desktop/web(内嵌 kap-server 的同一工具实现)行为同步变化。

测试覆盖:表中第一行由「手动 detach 大输出」「自动超时 detach 大输出」两个用例钉住,边界由「恰好 50,000 字符不截断」钉住,第二行由「任务工具禁用措辞」用例钉住;小输出不回归由既有 detach 用例(can detach a foreground command through the background service 等断言 acknowledgement 原有内容不变)保证。

验证(macOS 本地,改动仅涉及字符串截断,不触及路径/子进程/终端语义):

  • 聚焦测试文件 61/61 通过;tsc -p packages/agent-core-v2/tsconfig.json --noEmit 通过。
  • check-comments(改动文件)、oxlint --type-aware、import-boundaries、guards、ratchet 通过。
  • agent-core-v2 全量 7,717 通过、3 失败:均为 test/tool/tool.test.ts 子代理 print 模式 deadline 用例的 30s 超时,与本改动无关(其中一例已在基线提交 38f4cf6 上复现同样失败)。
未验证项与环境说明
  • lint 的 test-doubles 环节在 loop-refact 分支上因既有基线漂移失败(报告条目均不涉及本 diff 文件);quarantine / instructions 环节在 jj 工作区(无 .git)内因检查脚本按 git root 解析路径而误扫外层目录(报「root AGENTS.md is missing」),均为分支/环境问题,CI 的真实 git checkout 不受影响。
  • desktop e2e bash-background.spec.ts 断言小输出(2 行)acknowledgement,不受截断影响,未在本地运行 desktop e2e。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • 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.

…edgement

- cap the model-visible foreground_output in backgroundStartedResult at DEFAULT_TOOL_RESULT_MAX_CHARS for both auto-timeout and manual detach
- append a truncation notice with the produced total, a still-running hint, and a TaskOutput pointer when task tools are active
- update the noisy-detach test to the new contract and add coverage for manual detach, auto-timeout detach, the exact cap boundary, and disabled task tools
@changeset-bot

changeset-bot Bot commented Nov 22, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 11fb540

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/kimi-code Patch
@moonshot-ai/agent-core-v2 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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 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-22T07:14:39.271043Z 11fb540 PR opened
ℹ️ 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.

@pkg-pr-new

pkg-pr-new Bot commented Nov 22, 2026

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

commit: 11fb540

@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: 11fb5409e0

ℹ️ 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 foregroundResult = builder.ok('');
const foregroundOutput = foregroundResult.output.length > 0 ? foregroundResult.output : '';
const retainedOutput = foregroundResult.output.length > 0 ? foregroundResult.output : '';
const foregroundOutput = sliceOnCodePointBoundary(retainedOutput, DEFAULT_TOOL_RESULT_MAX_CHARS);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep the acknowledgement below the result cap

When retained foreground output reaches 50,000 characters, only the payload is capped; the task metadata, foreground_output: label, and truncation notice are then appended outside that budget. The exact-boundary case is also considered untruncated even though the complete acknowledgement already exceeds DEFAULT_TOOL_RESULT_MAX_CHARS. Because detach acknowledgements bypass truncateForModel(), this still violates the intended cap and can overflow a context near its limit; reserve space for the serialized scaffolding or cap the completed acknowledgement.

Useful? React with 👍 / 👎.

Comment on lines +484 to +486
const fullOutputHint = this.allowBackground()
? `use TaskOutput(task_id="${taskId}") to read the full output, including output produced after this message`
: 'you will be automatically notified when it completes';

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid contradicting the TaskOutput instruction

When a foreground command is detached with more than 50,000 characters and task tools are enabled, this notice tells the model to call TaskOutput, while the metadata in the same acknowledgement says do NOT wait, poll, or call TaskOutput on it. The conflicting instructions make recovery of the omitted output ambiguous and may cause the model to poll despite the intended continuation behavior; align this hint with nextStepLines() or state when TaskOutput may be used.

Useful? React with 👍 / 👎.

@sailist

sailist commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

CI test (2) 分片失败说明(与本 PR 无关的既有问题)

失败用例:test/agent/loop/loop.test.ts > Agent loop > does not run loop error handlers for aborted turns。失败断言不在用例体内,而在 harness 的 afterEach ctx.expectResumeMatches()(恢复一致性校验):取消回合后期望恢复出的 context.history 含用户消息 go,实际为空——是 turn 提交后立即 cancel 时 wire journal 落账与取消竞态的恢复一致性问题。

证据(本地,macOS):

  1. 本 PR 的 diff 只触及 BashTool.backgroundStartedResult() 与其测试文件,不涉及 turn 提交/取消/wire/resume 任何路径;该用例也不运行 Bash 工具。
  2. 在纯净基线 38f4cf6(不含本 PR 任何改动)上单跑该用例即复现同样失败:
    corepack pnpm exec vitest run packages/agent-core-v2/test/agent/loop/loop.test.ts -t 'does not run loop error handlers for aborted turns'
    → 1 failed(与 CI 完全相同的断言 diff)
    
  3. 同基线的 PR fix(agent-core-v2): pin the initial tool baseline after startup MCP discovery #5217 CI 该分片为绿、本 PR 全量套件本地运行时该用例也通过——是否触发取决于调度/时序,属 loop-refact 分支上 turn 状态机改造区域的既有时序敏感问题。

按仓库规则未在本 PR 内修复无关问题;是否重跑该分片或等待分支侧修复,请维护者定夺。

@sailist
sailist merged commit 134db39 into loop-refact Nov 22, 2026
22 of 23 checks passed
@sailist
sailist deleted the bug-418-11-22-bash-detach-ack-truncation branch November 22, 2026 08:45
7Sageer pushed a commit that referenced this pull request Nov 23, 2026
…edgement (#5239)

* refactor(core): run loop turns on an independent state machine (#5211)

* refactor(core): run loop turns on an independent state machine

- add an actor runtime for loop and turn execution
- unify turn hooks and asynchronous lifecycle settlement
- simplify loop contracts and cover turn lifecycle behavior

* fix(core): park recorded notifications until intake

* fix(core): settle forced aborts past stuck hooks and tools

* docs(core): document loop emitted events and public API

* fix(agent-core-v2): skip onDidFinishStep hooks for aborted steps

* refactor(llm): legalize deferred tools in the resolver (#5142)

* refactor(core): unify llm event stream and harden behavior tests

- unify run boundaries, request summaries, delta events, retries, and outcomes
- migrate Loop, agent-core-v2, and klient consumers to the unified event vocabulary
- add aimock-backed transport coverage and restore historical LLM behavior tests
- update the Nix dependency hash and affected snapshots

* refactor(llm): legalize deferred tools in the resolver

- strip deferred metadata during legalize for models without dynamic loading
- stop convert from dropping deferred tools and dedupe declarations with top-level priority
- merge protocol capabilities once at the encode pipeline entry
- remove deferred tools in the dynamic loop resolver and announce their names first

* refactor(llm): unify deferred tool request views

- remove dynamic-only request branching from ToolSelect resolution
- keep non-dynamic system schemas out of top-level tools
- preserve baseline tools for side requests before capability shaping

* refactor(llm): share the tool select request view

- reuse deferred shaping in the resolver and request preview
- preserve initial tool announcements in request previews
- cover preview parity with deferred tools

* refactor(llm): strip deferred metadata in tool select

Remove deferred metadata from non-disclosure ToolSelect request views while preserving the loop baseline.
Keep core legalization as the fallback for requests that bypass ToolSelect.

* refactor(llm): contain tool disclosure in resolver

* refactor(llm): hash the full request tool list

- compute toolsHash over every input tool, including deferred ones
- note the resolver and legalization timing on the llm run events

* refactor(llm): remove the tool select experimental flag

- drop the tool-select flag, env var, and [experimental] config entry
- gate deferred tool disclosure solely on model capabilities
- remove the desktop forced env and update the MCP and env-var docs
- cover mid-loop active-tool requests with an empirical loop test

* test(desktop): assert browser tool disclosure in the request view

The previous assertions called loadableToolsAnnouncement() with no
arguments, a calling form no production code uses; the model-facing
disclosure is built per request by the ToolSelect resolver. Assert the
request view instead: requestTools strips the deferred browser tool
from the request tool list, shapeHistory injects the snapshot
announcement naming it, and a reminder step after the control switch
turns the removal into a <tools_removed> delta.

* fix(core): recover compaction from empty text history (#5214)

* test(core): cover empty text request recovery

* fix(core): clean empty text before request encoding

* chore: add empty text recovery changesets

* test(core): cover cross-provider signed empty text

* fix(core): drop unsupported signed blank text

* fix(agent-core-v2): truncate foreground output in bash detach acknowledgement (#5218)
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.

1 participant