Skip to content

fix(agent-core-v2): wait for subagent quiescence - #4953

Merged
sailist merged 3 commits into
bug-370-11-15-release-fixesfrom
bug-374-11-15-subagent-turn-tracking
Nov 15, 2026
Merged

sailist merged 3 commits into
bug-370-11-15-release-fixesfrom
bug-374-11-15-subagent-turn-tracking

Conversation

@sailist

@sailist sailist commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

后台子 Agent 可能在仍有后续 turn 或 detached 后台任务时,被客户端提前标记为完成或失败,导致 TUI 状态、运行计数与实际执行不一致。这个 PR 把子 Agent 的完成条件统一为稳定 quiescent:Loop idle 且子 Agent 自己拥有的活动后台任务清零,正常、失败和取消都在达到这个状态后才能结束。

Bug Reproduction Steps

本 PR 覆盖两条相互关联的复现路径:

  1. 通知续跑被误判失败:turn 0 只产生工具调用、没有 assistant 文本,loop.notify 结束 turn 0 并启动 turn 1;旧实现只等待 turn 0,立即抛出 Subagent turn ended without a final message,而 turn 1 或 detached 任务仍在运行。
  2. 取消后 replay 丢失部分输出:子 Agent 已流式输出 draft,父 Agent 停止它;如果 run.completion 在取消请求发出时立即结束,session close 可能先于子 Loop 的部分输出回收与 wire flush,导致 resume replay 缺少 draft。

回归测试使用真实 Loop、工具执行、后台任务与 SDK session 覆盖上述场景。

Root Cause

turn.result 只代表一个 turn,Loop 的 settled() 也只表示 Loop idle;两者都没有覆盖 detached 后台任务。另一方面,取消请求只开始取消,并不表示取消收尾、部分输出回收和 wire 持久化已经完成。第一版修复中使用 abortable 立即拒绝 run.completion,进一步放大了这个收尾竞态。

这是根本修复:子 Agent 以固定点等待达到稳定 quiescent,而不是用延迟、重试或单次状态猜测。取消时同时停止 Loop 与子 Agent 后台任务,等待清理与持久化完成,再发布取消结果。

等待 Loop idle
  ↓
子 Agent 活动后台任务为 0?
  ├─ 否 → 等任务终态 → 任务通知可能启动新 turn → 重新等待 Loop idle
  └─ 是 → 稳定 quiescent → 结算成功、真实失败或取消

Code Changes

  • 统一完成路径:prompt 与 retry 共用 awaitRunCompletion。等待首个 turn.result 后,固定点循环 loop.settled() 与子 Agent tasks.list(true);有活动任务就等待终态,再重新等待 Loop,直到没有后续通知、turn 或新任务。
  • 保留原始结果分类:IAgentLoopService.settled() 返回空闲时最后一个原始 TurnResult,用于失败分类、stop reason 与最终文本;真正无续跑、无后台任务且无最终文本时仍返回 AGENT_NO_FINAL_MESSAGE。
  • 取消级联清理:abort 取消当前活动 turn,按 task id 停止子 Agent 的活动任务,turn 收尾后补扫,覆盖取消期间新注册的任务;不再通过 abortable 立即结束运行。
  • 通知抑制:IAgentLoopService.suppressTaskNotifications(taskIds) 移除已排队通知;Core 在 prompt.notified 和 mailbox 入队前跳过被抑制任务,同时保留 tool.async_ended 与 TaskTerminated 历史。抑制仅针对被取消 task id,不影响父 Agent 的 killed 通知或后续 resume 的新任务通知。
  • 回归覆盖:Loop idle 但后台任务运行、取消清理完成前 completion 不结束、真实 killed 通知抑制,以及 cancelled subagent replay 的 wire 持久化。测试声明数量净零。
  • 添加 @moonshot-ai/kimi-code 的 patch changeset。

建议先读 packages/agent-core-v2/src/session/subagent/runAgentTurn.ts 理解固定点等待与取消清理,再读 loopService.ts 和 Core loop-actor.ts 的通知抑制位置;其余是接口类型、回归测试与测试桩适配。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
子 Agent 的 notify 自动续跑 turn 0 无文本时可能被标记失败,后续 turn 脱离跟踪 等待最后一个 turn 后返回最终成功或真实失败 使用 TUI、desktop、web 与 SDK 子 Agent 任务状态的用户;旧行为是状态不一致 无;未移除有效行为
Loop idle 但子 Agent 仍有 detached 后台任务 子 Agent 可能提前结束,后台工作继续运行 保持 running,直到子 Agent 活动后台任务清零 使用 Bash、后台子 Agent 等 detached 任务的用户 无;这是本 PR 明确的生命周期修正
后台任务完成通知触发新 turn 只检查一次 Loop idle,可能漏掉新工作 固定点重新等待 Loop 与任务,直到稳定空闲 依赖任务完成通知与 resume 的客户端 无;保留正常通知机制
取消子 Agent 可能只取消旧 turn,detached 任务继续运行;取消通知也可能先于 wire flush 结束 停止当前 turn 与子任务,抑制其通知再次唤醒子 Agent,并等待清理和持久化完成 停止后台子 Agent 的 TUI、desktop、web 与 SDK 用户 无;恢复取消与 replay 一致性
被取消任务的历史与通知 终态历史与通知可能不一致,或通知再次启动模型调用 保留 TaskTerminated 历史,跳过对应 prompt.notified / mailbox 通知 查看任务历史的客户端与后续 resume 无;仅抑制被取消 task id,不影响新任务
真正无续跑、无任务且无最终文本、max tokens、普通失败 使用既有错误分类 在稳定 quiescent 后使用相同错误分类 依赖子 Agent 错误处理的 CLI、TUI 与 SDK 调用方 不需要;旧行为有回归覆盖
IAgentLoopService.settled() 解析为 void 解析为最后一个 TurnResult | undefined,等待条件不变 只等待空闲的内部 Loop 调用方 不需要;不读取返回值的调用方不受影响

受影响模块与覆盖:

  • 子 Agent 固定点完成:runAgentTurn.test.ts 覆盖 Loop 与后台任务双等待、取消清理时序和原有错误分类。
  • Loop 与通知:loop.test.ts 覆盖真实工具 turn 0 → notify → turn 1;idle-notification-repro.test.ts 覆盖子任务 killed 历史、通知抑制和父 Agent 通知保持。
  • SDK replay:session-prompt-events.test.ts 覆盖取消输出在 session close 前写入 wire,以及 resume 仅在显式请求时包含子 Agent replay。
  • 测试桩:toolSelectService.test.ts 与 agentLifecycle.test.ts 验证接口扩展不改变原有调用语义。
验证详情与限制
  • agent-core 的 runAgentTurn、Loop、idle-notification、toolSelect、agentLifecycle 五个测试文件:247/247 通过。
  • node-sdk session-prompt-events.test.ts:18/18 通过,包括此前在 CI 连续失败的 cancelled subagent replay 场景。
  • @moonshot-ai/agent-core-v2 与 @moonshot-ai/kimi-code-sdk typecheck 通过;根 corepack pnpm run build 成功。
  • 改动文件 oxlint 为 0 errors;测试声明数量净零。
  • 远程测试未执行:m0-dev 的 SSH 主机密钥与本机记录不一致,coding-win 连接超时;未绕过主机校验。
  • lint:imports 仍有 4 个既有违规,均位于本 PR 未修改的文件。

Checklist

  • I have read the CONTRIBUTING document.
  • 本仓库内部 PR 无单独 issue;已在上文提供直接复现步骤。
  • I have added regression tests that prove this fix works.
  • The behavior-change table above is complete;后台任务完成条件的生命周期变化已明确列出。
  • Ran gen-changesets skill and committed the confirmed patch changeset.
  • This PR needs no doc update.

@changeset-bot

changeset-bot Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 53c4f27

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

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code 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 15, 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-15T07:22:37.740585Z 53c4f27 Manual request
ℹ️ 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 15, 2026 •

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

commit: 53c4f27

@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: 2a96ff56cb

ℹ️ 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 initialResult = await abortable(turn.result, controller.signal);
controller.signal.throwIfAborted();
const initial = classifyTurnResult(initialResult);
const lastResult = await abortable(loop.settled(), controller.signal);

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 Collect partial output from notification continuations

When loop.notify starts a continuation turn, this new wait keeps the run active through that turn, but collectRunOutput remains permanently bound to the initial turn and ignores every event with a different turnId. If the continuation emits useful text and then times out, is cancelled, or fails, AgentTool.writePartialOutput() therefore reports no output (or only turn-0 text), even though the continuation is now part of the same tracked run; update the collector to include the continuation turns.

Useful? React with 👍 / 👎.

Comment on lines +128 to +131
const lastResult = await abortable(loop.settled(), controller.signal);
controller.signal.throwIfAborted();
const result = classifyTurnResult(lastResult ?? initial);
const summary = latestAssistantText(loop.history());

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 Keep settlement scoped to the initiating run

When another prompt is queued on the same subagent loop—for example, two parallel Agent(resume=...) calls can both pass the non-atomic idle check, and the server also accepts prompts targeting an agent_id—loop.settled() waits through all of that work and returns the loop-wide last result, while latestAssistantText() reads the loop-wide latest history. Run A therefore completes with run B's status and summary rather than its own; aborting A during this wait can also cancel B because cancellation targets whichever turn is currently active. Scope settlement to the initiating prompt and its notification continuations rather than the entire loop.

AGENTS.md reference: AGENTS.md:L110-L112

Useful? React with 👍 / 👎.

@sailist sailist changed the title fix(agent-core-v2): track subagent notification continuations fix(agent-core-v2): wait for subagent quiescence Nov 15, 2026

@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: 14fa9d3c6d

ℹ️ 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 +150 to +152
const active = tasks.list(true);
if (active.length === 0) return result;
await Promise.all(active.map((task) => tasks.wait(task.taskId)));

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 Do not block the handoff on every background task

When a subagent intentionally starts a detached Bash watcher or server with run_in_background=true—especially with disable_timeout=true—this loop treats that task as work that must finish before the Agent call can settle. This contradicts the Bash contract in packages/agent-core-v2/src/agent/tools/os/bash/bashTool.ts:41-42, which explicitly reserves background mode for work the conversation should not wait on; a foreground Agent invocation can now hang indefinitely instead of delivering its already-written final summary. Track only notification continuations belonging to this run rather than waiting for every active task.

AGENTS.md reference: AGENTS.md:L110-L112

Useful? React with 👍 / 👎.

Comment on lines +919 to +922
suppressTaskNotifications(taskIds: readonly string[]): void {
for (const taskId of taskIds) {
this.suppressedTaskNotifications.add(taskId);
this.dropTaskNotification(taskId);

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 Persist cancellation notification suppression

When cancellation stops an active child task, its notification is suppressed only by this in-memory set. The ensuing TaskTerminated record at lines 501-507 does not set terminalNotificationSuppressed, so after the agent scope or session is recreated, restoreTaskCompletions treats the killed task as an undelivered terminal completion and appends it back to the notify inbox. The notification deliberately dropped during cancellation therefore reappears on the next resume and can drive an extra LLM turn; persist the suppression in the terminal task record or mark the notification as delivered.

AGENTS.md reference: AGENTS.md:L110-L112

Useful? React with 👍 / 👎.

@sailist
sailist force-pushed the bug-374-11-15-subagent-turn-tracking branch from 14fa9d3 to f2bbe86 Compare November 15, 2026 06:49

@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: f2bbe86c17

ℹ️ 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 +116 to +120
let lastResult = await awaitQuiescent(target, loop);
if (controller.signal.aborted) {
const reason = controller.signal.reason ?? userCancellationReason();
await abortCleanup;
await stopChildTasks(target, loop, reason);

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 Stop late child tasks before waiting for quiescence

When cancellation races with a child task being registered while the active turn unwinds, the first stopChildTasks snapshot misses that task. Control then enters awaitQuiescent, which waits for every active task, so the intended second sweep at line 120 cannot run until the missed task has already terminated; a watcher or server started with timeouts disabled can therefore leave cancellation and run.completion pending indefinitely. Perform the follow-up stop sweep before this wait, or make the quiescence loop stop newly observed tasks while cancellation is active.

Useful? React with 👍 / 👎.

Comment on lines +124 to +125
const initial = classifyTurnResult(first);
const result = classifyTurnResult(lastResult ?? initial);

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 Classify only the final available turn result

When the initiating turn fails after spawning detached work but that task's completion notification produces a successful continuation, awaitQuiescent returns the continuation's completed result. This unconditional classification of first throws before the later result is inspected, so the overall run is still reported as the initiating failure despite completing its continuation successfully. Classify the initial result only when no later result exists.

Useful? React with 👍 / 👎.

Comment on lines +162 to +165
const tasks = target.accessor.get(IAgentTaskService);
const active = tasks.list(true);
if (active.length === 0) return;
loop.suppressTaskNotifications(active.map((task) => task.taskId));

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 Suppress queued terminal-task notifications on cancellation

When a detached child task reaches a terminal state immediately before the parent run is cancelled but its completion notification is still queued, tasks.list(true) omits that task and no suppression is installed for its ID. loop.cancel(undefined, reason) cancels only the active turn rather than clearing the notify inbox, so the queued task notification can start another LLM turn after cancellation and keep run.completion pending until that turn finishes. Include terminal tasks with undelivered notifications in the cancellation sweep, or clear their queued notifications directly.

Useful? React with 👍 / 👎.

@sailist
sailist force-pushed the bug-374-11-15-subagent-turn-tracking branch from f2bbe86 to 14fa9d3 Compare November 15, 2026 07:03
@sailist
sailist force-pushed the bug-374-11-15-subagent-turn-tracking branch from 14fa9d3 to 53c4f27 Compare November 15, 2026 07:14
@sailist

sailist commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

@codex

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 53c4f27bbc

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

@sailist
sailist merged commit a22bba6 into bug-370-11-15-release-fixes Nov 15, 2026
14 checks passed
@sailist
sailist deleted the bug-374-11-15-subagent-turn-tracking branch November 15, 2026 07:59
sailist added a commit that referenced this pull request Nov 16, 2026
* fix(agent-core-v2): track subagent notification continuations

* chore: add changeset for subagent continuation tracking

* fix(agent-core-v2): wait for subagent quiescence
sailist added a commit that referenced this pull request Nov 16, 2026
* fix(agent-core-v2): track subagent notification continuations

* chore: add changeset for subagent continuation tracking

* fix(agent-core-v2): wait for subagent quiescence
wbxl2000 pushed a commit that referenced this pull request Nov 17, 2026
* fix: resume sessions with removed default models (#4982)

* fix(node-sdk): resume sessions with missing default model

* fix(cli): check auth for the resumed session model

* chore: add changeset for unavailable model recovery

* fix(agent-core-v2): stop rebuilding mismatched session indexes (#4980)

* fix(agent-core-v2): reject repeated model responses (#4977)

* fix(agent-core-v2): reject repeated model responses

* chore: add changeset for repeated model responses

---------

Co-authored-by: 7Sageer <[email protected]>

* fix(agent-core-v2): inline deferred tools without dynamic loading (#4971)

* fix(agent-core-v2): record restored task notifications without model requests (#4949) (#4989)

* fix(agent-core-v2): record restored task notifications without model requests

- queue restored task notifications as prompt-only turns after loop initialization
- preserve interrupted and queued turns during resume and fork
- complete reconciliation before initialization and reset return to keep Wire reads ordered
- run loop and container cleanup when reconciliation fails
- surface restored notification persistence failures

* chore: add changeset for restored task notifications

* fix(agent-core-v2): restore overflow recovery after LLM retries (#4950) (#4990)

* fix(agent-core-v2): restore step state after LLM retries

* test(agent-core-v2): scope retry event to overflow regression

* fix(config): allow sessions with invalid user config (#4951) (#4991)

* fix(agent-core-v2): tolerate config read failures for permission rules

* chore: add changeset for permission config recovery

* docs: document permission config recovery

* docs: qualify permission config recovery scope

* fix(config): surface read error diagnostics

* fix(config): allow sessions with invalid user config

* fix(config): preserve valid values and replay diagnostics

* fix(config): remove startup diagnostic replay

* fix(agent-core-v2): ignore non-user prompts during Tower wake (#4952) (#4992)

* fix(agent-core-v2): ignore non-user prompts during Tower wake

* chore: add Tower notification fix changeset

* fix(agent-core-v2): preserve slash prompts during Tower wake

* fix(agent-core-v2): route foreground shell events by origin (#4954) (#4994)

* fix(agent-core-v2): route foreground shell events by origin

* test(agent-core-v2): expect tool event origins in snapshots

* fix(klient): accept tool events from pre-origin hosts

* fix(agent-core-v2): run external Stop hooks after turn completion (#4956) (#4995)

* fix(agent-core-v2): run external Stop hooks after turn completion

* chore: add changeset for external Stop hooks

* docs: clarify post-turn Stop hook timing

* fix(agent-core-v2): wait for subagent quiescence (#4953) (#4993)

* fix(agent-core-v2): reject incomplete model streams (#5006)

* fix(agent-core-v2): preserve choice-level OpenAI token usage (#5017)

* fix(capability): confirm stopping WebBridge before Windows updates (#4999)

* fix(capability): confirm stopping WebBridge before Windows updates

* fix(capability): harden WebBridge update recovery

* fix(capability): restore WebBridge after startup failure

* fix(capability): wait for WebBridge process exit

* fix(capability): handle WebBridge confirmation edge cases

---------

Co-authored-by: kimi-agent-bot <[email protected]>
Co-authored-by: kimi-agent-bot <[email protected]>

* chore: sync release 2.6.3 back to main

* chore: finish release 2.6.3 backsync

* chore: sync node-sdk lockfile importer

* fix(sdk): preserve main core type dependencies

* fix: complete release 2.6.3 backsync

---------

Co-authored-by: Haozhe <[email protected]>
Co-authored-by: 7Sageer <[email protected]>
Co-authored-by: kimi-agent-bot <[email protected]>
Co-authored-by: kimi-agent-bot <[email protected]>
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