Skip to content

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

Merged
7Sageer merged 4 commits into
mainfrom
loop-421-stack/06-truncate-detach-output
Nov 23, 2026
Merged

7Sageer merged 4 commits into
mainfrom
loop-421-stack/06-truncate-detach-output

Conversation

@sailist

@sailist sailist commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

Part 6/7 of the loop stack onto main. Identical diff to #5218, previously reviewed and merged into the loop integration branch. Stacked on #5238; the shown diff contains only this PR's own changes.

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.

@changeset-bot

changeset-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1107a2f

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

This PR includes changesets to release 4 packages
Name Type
@moonshot-ai/kimi-code Patch
@moonshot-ai/agent-core-v2 Patch
@moonshot-ai/core Patch
@moonshot-ai/kap-server 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 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-23T04:56:29.112353Z 1107a2f 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.

@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: 555d762cda

ℹ️ 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".

Comment on lines +484 to +485
const fullOutputHint = this.allowBackground()
? `use TaskOutput(task_id="${taskId}") to read the full output, including output produced after this message`

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 Make the TaskOutput guidance consistent

When a foreground task is detached after producing more than 50,000 characters, the acknowledgement first includes nextStepLines() telling the model to “do NOT ... call TaskOutput,” then this new notice tells it to use TaskOutput to read the omitted output. These mutually exclusive instructions occur in the same tool result and can prevent the model from retrieving the truncated content or prompt unnecessary polling; make the detach next-step conditional on truncation or align the new hint with the existing guidance.

Useful? React with 👍 / 👎.

'@moonshot-ai/kimi-code': patch
---

Fix commands moved to the background after a foreground timeout flooding the conversation context with their full accumulated output.

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 every affected product and detach path in changesets

The implementation changes acknowledgements for both timeout-driven and user-requested foreground detaches, and apps/desktop directly consumes @moonshot-ai/agent-core-v2, but the only product changeset describes the CLI timeout path. This leaves manual “To background” behavior undocumented and omits the required kimi-code-app release entry even though desktop users receive the same visible truncation; update the CLI sentence to cover both detach paths and add a desktop product changeset.

AGENTS.md reference: AGENTS.md:L169-L170

Useful? React with 👍 / 👎.

@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@1107a2f
npx https://pkg.pr.new/@moonshot-ai/kimi-code@1107a2f

commit: 1107a2f

@7Sageer 7Sageer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

截断边界和完整日志读取路径已核对,建议补齐同一条 acknowledgement 的模型指引及产品发布记录。

let truncationNotice = '';
if (foregroundOutput.length < retainedOutput.length) {
const fullOutputHint = this.allowBackground()
? `use TaskOutput(task_id="${taskId}") to read the full output, including output produced after this message`

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] 同一条 metadata 的 nextStepLines() 仍要求 do NOT ... call TaskOutput,新增说明又要求用 TaskOutput 读取完整输出。两个互斥指令会妨碍模型获取被截掉的输出。请按是否发生截断生成 next_step,例如保留「继续当前工作、等待完成通知」,同时允许按需读取完整日志。

'@moonshot-ai/kimi-code': patch
---

Fix commands moved to the background after a foreground timeout flooding the conversation context with their full accumulated output.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] 此函数覆盖自动超时和手动 To background 两条路径,CLI changeset 目前只写超时;apps/desktop 直接使用同一 agent-core-v2 实现,也需要对应产品 changeset。请补 desktop 的 patch 条目,并让 CLI 文案覆盖两种 detach 入口。

7Sageer
7Sageer previously approved these changes Nov 23, 2026
@sailist
sailist changed the base branch from loop-421-stack/05-recover-empty-text-compaction to main November 23, 2026 04:38
@sailist
sailist dismissed 7Sageer’s stale review November 23, 2026 04:38

The base branch was changed.

* 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(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.
* 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
@sailist
sailist force-pushed the loop-421-stack/06-truncate-detach-output branch from 555d762 to 1107a2f Compare November 23, 2026 04:49
@sailist
sailist changed the base branch from main to loop-421-stack/05-recover-empty-text-compaction November 23, 2026 04:49
@chatgpt-codex-connector

Copy link
Copy Markdown

💡 Codex Review

enabled(capabilities: ToolSelectCapabilities | undefined = this.profile.getModelCapabilities()): boolean {
return capabilities?.dynamically_loaded_tools === true && capabilities.tool_use === true;

P1 Badge Preserve the explicit tool-selection opt-out

When a model advertises dynamically_loaded_tools, this now enables progressive disclosure unconditionally, so existing [experimental] tool-select = false or KIMI_CODE_EXPERIMENTAL_TOOL_SELECT=0 settings are silently ignored and deferred MCP schemas disappear from the ordinary top-level list. This flips an experimental default for every capable model without an escape hatch; retain an opt-out or obtain explicit approval and document the lost behavior as required for default flips.

AGENTS.md reference: AGENTS.md:L195-L197



P1 Badge Keep loaded MCP tools across model capability switches

After a session loads a deferred or runtime MCP tool and switches from a dynamic-capable model to one without dynamic loading, base is the frozen loop baseline and does not contain those loaded schemas. The new path only shapes that baseline while shapeUnsupportedDynamicToolContext() removes the historical schema messages, leaving the request with no declaration for tools that remain registered; the previous implementation merged collectLoadedDynamicTools(messages) in this case. Preserve those loaded declarations so an in-session model switch does not make working MCP tools unavailable.


messages[index] = { ...message, tools: kept };

P1 Badge Remove messages emptied by tool deduplication

When a system message contains only a tool declaration that is duplicated by a later or top-level declaration, this replacement leaves it with tools: [] and empty content. Structural cleanup has already run before legalizeTools, and OpenAI lowering only suppresses an empty system message while it still has nonempty tools, so the encoded request contains { role: 'system', content: '' }; strict OpenAI-compatible gateways can reject the entire request. Drop messages that become structurally empty here or run structural cleanup again after deduplication.

ℹ️ 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".

7Sageer
7Sageer previously approved these changes Nov 23, 2026
Base automatically changed from loop-421-stack/05-recover-empty-text-compaction to main November 23, 2026 05:44
@7Sageer
7Sageer dismissed their stale review November 23, 2026 05:44

The base branch was changed.

@7Sageer
7Sageer merged commit b53e7a8 into main Nov 23, 2026
39 of 40 checks passed
@7Sageer
7Sageer deleted the loop-421-stack/06-truncate-detach-output branch November 23, 2026 05:45
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
…nowledgement

Port of upstream b53e7a8 (MoonshotAI#5239). The fork keeps the acknowledgement in
shellToolResults.ts after the bashTool refactor: slice the model-visible
foreground output at DEFAULT_TOOL_RESULT_MAX_CHARS, name the produced
character count in the truncation notice, and keep TaskOutput out of the
hint when background task tools are disabled. The full log stays in the
task output; both upstream changesets are ported, and the bash suite covers
the noisy detach, user detach, timeout detach, exact-cap boundary and
disabled-tools cases.
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