Repository navigation
fix(agent-core-v2): wait for subagent quiescence - #4953
Conversation
🦋 Changeset detectedLatest commit: 53c4f27 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
There was a problem hiding this comment.
💡 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); |
There was a problem hiding this comment.
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 👍 / 👎.
| const lastResult = await abortable(loop.settled(), controller.signal); | ||
| controller.signal.throwIfAborted(); | ||
| const result = classifyTurnResult(lastResult ?? initial); | ||
| const summary = latestAssistantText(loop.history()); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
| const active = tasks.list(true); | ||
| if (active.length === 0) return result; | ||
| await Promise.all(active.map((task) => tasks.wait(task.taskId))); |
There was a problem hiding this comment.
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 👍 / 👎.
| suppressTaskNotifications(taskIds: readonly string[]): void { | ||
| for (const taskId of taskIds) { | ||
| this.suppressedTaskNotifications.add(taskId); | ||
| this.dropTaskNotification(taskId); |
There was a problem hiding this comment.
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 👍 / 👎.
14fa9d3 to
f2bbe86
Compare
There was a problem hiding this comment.
💡 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".
| let lastResult = await awaitQuiescent(target, loop); | ||
| if (controller.signal.aborted) { | ||
| const reason = controller.signal.reason ?? userCancellationReason(); | ||
| await abortCleanup; | ||
| await stopChildTasks(target, loop, reason); |
There was a problem hiding this comment.
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 👍 / 👎.
| const initial = classifyTurnResult(first); | ||
| const result = classifyTurnResult(lastResult ?? initial); |
There was a problem hiding this comment.
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 👍 / 👎.
| const tasks = target.accessor.get(IAgentTaskService); | ||
| const active = tasks.list(true); | ||
| if (active.length === 0) return; | ||
| loop.suppressTaskNotifications(active.map((task) => task.taskId)); |
There was a problem hiding this comment.
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 👍 / 👎.
f2bbe86 to
14fa9d3
Compare
14fa9d3 to
53c4f27
Compare
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
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". |
* fix(agent-core-v2): track subagent notification continuations * chore: add changeset for subagent continuation tracking * fix(agent-core-v2): wait for subagent quiescence
* 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]>
Requirement or Bug
后台子 Agent 可能在仍有后续 turn 或 detached 后台任务时,被客户端提前标记为完成或失败,导致 TUI 状态、运行计数与实际执行不一致。这个 PR 把子 Agent 的完成条件统一为稳定 quiescent:Loop idle 且子 Agent 自己拥有的活动后台任务清零,正常、失败和取消都在达到这个状态后才能结束。
Bug Reproduction Steps
本 PR 覆盖两条相互关联的复现路径:
loop.notify结束 turn 0 并启动 turn 1;旧实现只等待 turn 0,立即抛出Subagent turn ended without a final message,而 turn 1 或 detached 任务仍在运行。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 后台任务,等待清理与持久化完成,再发布取消结果。
Code Changes
awaitRunCompletion。等待首个turn.result后,固定点循环loop.settled()与子 Agenttasks.list(true);有活动任务就等待终态,再重新等待 Loop,直到没有后续通知、turn 或新任务。IAgentLoopService.settled()返回空闲时最后一个原始TurnResult,用于失败分类、stop reason 与最终文本;真正无续跑、无后台任务且无最终文本时仍返回AGENT_NO_FINAL_MESSAGE。abortable立即结束运行。IAgentLoopService.suppressTaskNotifications(taskIds)移除已排队通知;Core 在prompt.notified和 mailbox 入队前跳过被抑制任务,同时保留tool.async_ended与TaskTerminated历史。抑制仅针对被取消 task id,不影响父 Agent 的 killed 通知或后续 resume 的新任务通知。@moonshot-ai/kimi-code的 patch changeset。建议先读
packages/agent-core-v2/src/session/subagent/runAgentTurn.ts理解固定点等待与取消清理,再读loopService.ts和 Coreloop-actor.ts的通知抑制位置;其余是接口类型、回归测试与测试桩适配。Behavior Changes and Affected Users
TaskTerminated历史,跳过对应prompt.notified/ mailbox 通知IAgentLoopService.settled()voidTurnResult | undefined,等待条件不变受影响模块与覆盖:
runAgentTurn.test.ts覆盖 Loop 与后台任务双等待、取消清理时序和原有错误分类。loop.test.ts覆盖真实工具 turn 0 → notify → turn 1;idle-notification-repro.test.ts覆盖子任务 killed 历史、通知抑制和父 Agent 通知保持。session-prompt-events.test.ts覆盖取消输出在 session close 前写入 wire,以及 resume 仅在显式请求时包含子 Agent replay。toolSelectService.test.ts与agentLifecycle.test.ts验证接口扩展不改变原有调用语义。验证详情与限制
runAgentTurn、Loop、idle-notification、toolSelect、agentLifecycle 五个测试文件:247/247 通过。session-prompt-events.test.ts:18/18 通过,包括此前在 CI 连续失败的 cancelled subagent replay 场景。@moonshot-ai/agent-core-v2与@moonshot-ai/kimi-code-sdktypecheck 通过;根corepack pnpm run build成功。lint:imports仍有 4 个既有违规,均位于本 PR 未修改的文件。Checklist
gen-changesetsskill and committed the confirmed patch changeset.