Skip to content

refactor(agent-core-v2): port agent loop runtime core - #4630

Merged
sailist merged 25 commits into
mainfrom
refact-323-11-02-agent-loop-runtime
Nov 11, 2026
Merged

sailist merged 25 commits into
mainfrom
refact-323-11-02-agent-loop-runtime

Conversation

@sailist

@sailist sailist commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

Agent 执行状态此前分散在生命周期 actor、旧 machine 与 AgentLoopService 之间,turn/step/tool、恢复和关闭路径需要跨多个状态所有者协调。本 PR 将 Loop 运行时迁入 agent-core-v2,由 AgentLoopService 统一创建和驱动 Core Loop,并收敛排队消息、取消、后台任务、撤销和会话恢复中的行为分叉。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

核心思路是让 Core Loop 成为唯一的执行状态机:它独立于 DI、Wire 和 XState,负责 turn/step/tool、normal/notify/remind 三队列、hooks 与异步完成;AgentLoopService 只承担请求装配、工具、持久化、事件和生命周期适配。旧 machine 执行路径及专用 attach 协议被一次性移除,不保留双跑。

flowchart TD
    Lifecycle[AgentLifecycleService<br/>Agent scope / restore / dispose] --> Host[AgentLoopService<br/>宿主与适配]
    Host --> Core[Core Loop<br/>唯一执行状态]
    Host --> Factory[AgentLoopRequestFactory<br/>配置 / 工具 / policy]
    Host --> Observer[AgentLoopRequestObserver<br/>日志 / usage / telemetry]
    Host --> Tools[Tool adapter]
    Host --> Journal[LoopJournal<br/>原 Wire schema]
    Core --> Events[LoopEmitted<br/>FIFO]
    Events --> Journal
    Events --> Clients[Prompt / Turn / telemetry 投影]
Loading

生命周期层不再传 turn/store/tool logic,Core Loop 也不反向依赖宿主。请求配置在 Turn 起点冻结,Step 继续读取最新 durable history;side request 使用独立配置,避免覆盖活动 Turn。

决策 选择 没选 理由
执行核心 一次性切换到 Core Loop 新旧 machine 双跑 避免两个状态源和重复工具执行
历史所有权 Core Loop 统一维护三队列与消息历史 保留 ContextMemory 双向同步 消除平行队列和历史修补逻辑
持久化 继续读写原 wire.jsonl schema 磁盘协议升级或双写 保持既有会话恢复、undo/fork 与 replay 兼容
请求边界 TurnExecution 冻结 Turn 配置,Observer 统一观测 LoopService 与 Requester 各持一份 Turn 状态 避免重试、工具视图和 telemetry 分叉
后台任务 Core detached tool + Wire 历史 旧 JSON 读模型与额外通知状态机 保持任务事实、输出和恢复通知来自同一条链路

阅读顺序建议:先看 agent/loop/core/create-loop.ts 和 core/loop-actor.ts 理解执行核心,再看 loopService.ts 的宿主职责、requester.ts/requestObservation.ts 的请求边界、toolAdapter.ts 的工具语义、journal.ts 的原 Wire 往返映射,最后看 agentLifecycleService.ts 的生命周期收缩。其余改动主要是消费方迁移、旧实现删除和测试对齐。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Agent 执行状态所有权 生命周期 actor、旧 machine 和 LoopService 共同承载 AgentLoopService 持有唯一 Core Loop TUI、print、desktop/web、ACP 与 SDK 的 Prompt/Turn 调用 公开 AgentFacade 调用与事件形状保持
Steer 与排队消息 部分路径合并消息或由外层维护队列 已有消息按 ID 逐条移动队列,新输入直接 notify,并由实际消费它的新 Turn 结算 TUI、desktop/web、SDK 的 steer 与 Skill 提交 公开 prompt/steer 入口保持;不再提供消息合并行为
用户取消 内部 Skill 或通知可能在取消后继续驱动 Loop 用户取消保持内部工作停止,显式跟踪的用户续跑按队列语义恢复 取消生成后仍期待排队用户消息可继续的客户端 无;程序性 abort 的继续语义不变
Goal 与重复工具收尾 Goal outcome 可由空 notify 另起总结 Turn;重复工具达到阈值后走 handoff Goal 在当前 Turn 自然收尾;第 12 次重复调用写入提醒,第 13 次起直接停止 使用 Goal 和重复工具阻断的会话 无;max-steps 耗尽时仍不强行总结
后台任务历史与通知 任务历史读取 tasks/*.json,另有通知投递状态 历史来自 Wire 的 task 记录,输出保留 output.log,完成结果经 Core detached tool 投递 恢复后台任务、读取任务输出和等待完成通知的客户端 旧 Wire 继续读取;无 live handle 的 running 任务恢复为 lost
Undo 切割位置 context-only 输入可用 message 锚点回退 统一使用持久化 Turn 边界 TUI、desktop/web、SDK 的 undo/fork 与旧会话 无;按确认的新边界执行
会话磁盘格式 原公共 context.* / turn.* Wire records 继续写原 schema;本任务未发布过的 agent.* 记录不参与恢复 读取旧版本会话、执行 resume/replay/undo/fork 的用户和客户端 无需迁移,旧文件继续按原格式读取
Prompt 内部装配入口 独立 AgentPromptChannel 与 machine attach 协议 客户端输入由 LoopService submit/notifyClient 承接,旧内部入口删除 agent-core-v2 内部生命周期与直接内部 RPC 调用方 公开 AgentFacade 保持;直接内部 RPC 不保留兼容别名

没有 UI/UX 变化。旧 wire.jsonl、公开 Prompt/Turn 事件和主要 SDK facade 的兼容路径均有保留;直接内部 machine/prompt 装配协议以及上述已确认的消息合并、message-anchor undo 行为不再保留。

验证结论:

  • 最近的行为修改后,agent-core-v2 typecheck 与 build 通过,ToolDedupe 57/57 通过;最后的接口注释修改也通过了 Core typecheck 和聚焦 oxlint。
  • 合并后曾通过远程根 build,以及 kap-server RPC 40/40、undo 35/35、klient facade 32/32、FullCompaction 120/120、TurnExecution 234/234、工具返工 299/299 等聚焦场景。
  • 最近一轮合并后的 24 文件组合记录为 775 passed / 28 failed,公开 prompts API 为 39 passed / 35 failed;剩余失败涉及 Loop、Prompt、vis、FullCompaction、requester 和 core record。后续聚焦修复不能据此宣称这些失败已全部消除。
  • 此前 head deaacefb 的手动 GitHub CI已完成但未通过:build、release-workflow-tests 和 test-pi-tui 通过;typecheck、lint、test (1–5) 和 test-vscode-legacy 失败。主要错误包括 kap-server 测试仍导入已删除的 IAgentContextMemoryService、VS Code 集成调用 agentContextMemoryService.get 返回 method not found,以及 lint 的 3 个错误;完整细节见对应 job 日志。
  • 最新交付提交为 05da35ea;本轮补齐默认 Profile 恢复、in-flight Prompt 队列计数和 Turn 有效 entry 投影,并修复普通测试 Agent 启动与 Wire 测试预期。m0-dev 上 Loop/Wire/Prompt/CoreLoopService/Reminder/Skill 八文件 187/187、完整 index.test.ts 16/16、Core typecheck 通过;生产改动后的根构建通过。新 head 的 CI 以 GitHub checks 为准。

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 removed behaviors have an escape hatch or were explicitly approved during the task.
  • Ran gen-changesets skill; no changeset is included by explicit request.
  • Ran gen-docs skill, or this PR needs no doc update.

@changeset-bot

changeset-bot Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 7bef91b

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 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-10T17:44:16.854801Z 7bef91b 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.

@pkg-pr-new

pkg-pr-new Bot commented Nov 3, 2026 •

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

commit: 7bef91b

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

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

void this.dispatcher.dispatch(new SwarmModeExit({ agentId: this.agentCtx.agentId }));
this.telemetry.track2('swarm_mode_exited', { trigger });
this.context.publishTrailingRemoval(history);
this.context.replaceHistory(historyFromContext(history.slice(0, -1)), 'swarm_mode.exit');

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 Preserve non-swarm history when exiting swarm mode

When swarm mode exits after a completed turn, the trailing entry is normally the assistant response or a tool result, but this unconditional slice(0, -1) deletes it. The previous popSwarmModeReminder path removed an entry only when the tail was specifically the swarm_mode injection; manual and automatic exits can now silently lose conversation history and leave the live history inconsistent with replay, where swarm_mode.exit still performs the conditional removal.

AGENTS.md reference: AGENTS.md:L126-L132

Useful? React with 👍 / 👎.

* (the prompt service's own `clear` would additionally abort prompts).
*/
override async clearContext(input: SessionIdRpcInput): Promise<void> {
const agent = await this.agentScope(input.sessionId);
agent.accessor.get(IAgentContextMemoryService).clear();
await agent.accessor.get(IEventDispatcher).dispatch(new ContextClear({ agentId: agentContextOf(agent).agentId }));
agent.accessor.get(IAgentLoopService).replaceHistory([], 'clear');

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 Handle rejected context clears during active turns

When an SDK caller clears context while an LLM request or tool execution is active, replaceHistory returns false because the core loop is not editable, but that result is ignored and the RPC reports success after a durable ContextClear was already dispatched. The live turn therefore continues with the old history while restart replay sees it cleared, silently creating divergent and potentially lost context; either ensure the live replacement succeeds or reject before persisting the clear.

AGENTS.md reference: AGENTS.md:L126-L132

Useful? React with 👍 / 👎.

@@ -129,7 +128,7 @@ function handleWith(
cancel: () => true,
},
],
[IAgentContextMemoryService, { get: () => messages }],
[IAgentLoopService, { get: () => messages }],

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 the complete loop stub under one service key

Every test using handleWith inserts IAgentLoopService into this Map twice, so this second entry overwrites the object containing submit, promptHandle, and cancel. runAgentTurn consequently receives { get: ... } and fails at loop.submit(...) before any assertion; merge history: () => messages into the first stub instead of registering the duplicate key.

Useful? React with 👍 / 👎.

@@ -729,7 +888,7 @@ export class AgentLoopService extends Disposable implements IAgentLoopService {
promptId: input.promptId,
content: stripBundledSkillBlocks(input.message),
clientMetadata: input.origin.clientMetadata,
queueLength: (this.engine?.snapshot().queue.length ?? 0) + 1,
queueLength: this.snapshot().queue.length,

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 Include the newly queued prompt in queueLength

When a prompt is submitted while another turn is running, this event is published before the new entry is inserted into the machine queue, so the snapshot omits the prompt being announced. The first queued prompt therefore reports queueLength: 0 and every later event is off by one, including the value forwarded to UserPromptQueued hook scripts; retain the previous + 1 behavior or enqueue before publishing.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

}
const turn = this.active;
if (turn === undefined) return;
void this.finishTurn(turn, outcome);

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 Emit TurnEnded before starting the queued turn

When another prompt is queued, the core schedules its next turn in the same transaction that emits turn.ended, while this fire-and-forget handler waits for persisted work before dispatching the public TurnEnded. The next public TurnStarted can consequently arrive first, violating the established started(N), ended(N), started(N+1) sequence and causing consumers that track one active turn to associate events with the wrong turn; serialize completion projection before exposing the next turn.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

private appendShellInput(command: string): void {
const text = `<bash-input>\n${escapeXml(command)}\n</bash-input>`;
this.context.append({
this.loop.remind(historyEntryFromContext({

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 Commit foreground shell history before returning

For an idle foreground shell command, remind only puts this entry into the loop inbox and run never flushes those reminders, so it returns while both the command and its output are absent from history(). If the caller then submits a prompt, the prompt is placed ahead of these older shell entries, reversing the model-visible chronology compared with the previous immediate append behavior; flush or directly append the shell exchange before returning.

AGENTS.md reference: AGENTS.md:L126-L132

Useful? React with 👍 / 👎.

{ point: 'turn.starting', hook: (event, signal) => this.turnStarting(event, signal) },
{ point: 'message.appending', hook: (event, signal) => this.messageAppending(event, signal) },
{ point: 'step.starting', hook: (event, signal) => this.stepStarting(event, signal) },
{ point: 'step.stopping', hook: (event, signal) => this.stepStopping(event, 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.

P1 Badge Run after-step hooks for continuing tool-call steps

When an assistant response contains tool calls, the core classifies the step draft as continue, so it invokes only step.continuing; this adapter runs the legacy onDidFinishStep hooks exclusively from step.stopping. Those hooks are therefore skipped for every tool-call step, preventing stopTurn from halting after tool execution and bypassing feature logic such as goal and dedupe bookkeeping; invoke the legacy hook from the continuing path as well.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

Comment on lines +122 to +125
if (entry.record.type === 'turn.prompt') {
reIncluded.push(entry);
continue;
}

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 Exclude abandoned turn prompts from branch replay

After an undo creates a new branch, this unconditionally re-adds every off-chain turn.prompt, including prompts from the abandoned branch, while restorableChain filters the paired context.undo and context.undone records. On restore, turnKey consequently rebuilds anchorTurnIds with turns that no longer exist in history; a subsequent undo detects the count mismatch, omits fromTurnId, and can leave the session outcome mirror pointing at an undone turn. Preserve the old turn IDs separately without replaying abandoned prompts as live anchors.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

@sailist
sailist force-pushed the refact-323-11-02-agent-loop-runtime branch from ca1f4ad to 522de3c Compare November 4, 2026 06:41

@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: 522de3c75f

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

if (origin.variant === SWARM_MODE_INJECTION_VARIANT) return 'active';
}
return undefined;
if (trigger === null || trigger === 'tool' || this.options.isReminderDelivered()) return undefined;

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 Restore exit guidance after leaving swarm mode

When a manual or automatic exit occurs after the enter reminder was delivered, trigger === null makes this return without adding corrective guidance, while the active reminder remains in history and explicitly tells the model that it is still in Swarm Mode. Subsequent requests from swarm users can therefore continue following the high-fan-out delegation workflow even though AgentSwarm is inactive; append the former exit reminder or remove/neutralize the active reminder on exit.

AGENTS.md reference: AGENTS.md:L118-L120

Useful? React with 👍 / 👎.

Comment on lines +279 to +281
case 'prompt.submitted':
this.normal.push(event.entry);
return;

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 Persist the queued inbox before acknowledging inputs

When a prompt is accepted while another turn is running, this case keeps it only in the in-memory normal array and writes no wire record; restoreLoopJournal explicitly recreates normal, notify, and remind as empty arrays. A process restart before the queued turn begins therefore silently drops an already acknowledged user prompt (and the analogous notification/reminder cases), whereas the previous engine journal persisted submitted inbox events for replay.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

Comment on lines +831 to +832
}
return undefined;

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 Replace superseded environment reminders

When the active environment or project working directory changes more than once, reminder entries fall through here and are appended without removing the previous environment_binding or project_context injection. The removed context-memory path explicitly replaced those two variants, so the model now retains conflicting stale environment and AGENTS.md instructions even after the new reminder says the old context no longer applies; restore variant-based replacement before appending these reminders.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

Comment on lines +955 to +959
private trackTaskStarted(entry: ManagedTask): void {
if (entry.startedTracked) return;
entry.startedTracked = true;
const info = this.toInfo(entry);
this.telemetry.track2('background_task_created', {

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 Persist non-core background task lifecycle

For detached tasks that are not core-detached tools—such as the tasks registered by Tower spawn and background swarm members—this replacement records only telemetry, and terminal handling likewise no longer dispatches TaskStarted or TaskTerminated. Since restoreAfterReplay now rebuilds task history exclusively from those durable events, these tasks disappear from task history after restart and cannot produce the previous lost/completed-task recovery state; retain lifecycle dispatch/persistence for the non-core path.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

delete message.llmTiming;
delete message.note;
delete message.durationMs;
delete message.toolCallDisplays;

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 Preserve tool-call displays in loop history

After any tool call carrying a ToolInputDisplay, this conversion deletes toolCallDisplays without placing it in entry metadata, so converting the history back to ContextMessage can never recover the field. Consequently SDK getContext() callers and clients that reload context lose the structured command/input display metadata that the previous context-memory history retained; carry the display map through the new history representation.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Comment on lines +756 to +757
this.terminalStates.set(waiter.id, state);
this.promptWaiters.delete(waiter.id);
this.steered.delete(waiter.id);

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 Release completed prompt waiters

After every normally completed prompt, this settles the promises and records a terminal state but never removes the waiter from promptWaiters; settleSteeredPromptLaunched has the same omission. In a long-lived session the map therefore grows once per prompt while retaining fulfilled promises and their Turn/result values, unlike the previous loop implementation which deleted each waiter after completion; remove completed waiters once their promises are settled.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

@sailist
sailist force-pushed the refact-323-11-02-agent-loop-runtime branch from 8c2f965 to deaacef Compare November 4, 2026 10:59

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

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

agentLoopService: IAgentLoopService,
agentPermissionModeService: IAgentPermissionModeService,
agentCommandService: IAgentCommandService,
agentEnvironmentBindingService: IAgentEnvironmentBindingService,
agentContextMemoryService: IAgentContextMemoryService,
agentContextMemoryService: IAgentLoopService,

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 Route context reads through the loop compatibility view

Any Klient or node-sdk getContext() call still invokes agentContextMemoryService.get, but this mapping now exposes the raw IAgentLoopService, which provides history() rather than get(); only the separately named agentLoopService receives the compatibility view. Both memory and IPC/server-backed clients therefore fail at runtime with a method-not-found error instead of returning session context.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

@@ -1749,219 +1583,168 @@ export class AgentLoopService extends Disposable implements IAgentLoopService {
turn.current = undefined;

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 the current step projection across request retries

When a provider attempt retries or applies a recovery, the Core loop continues the same step and does not emit another step.started, but this handler clears turn.current. All later streaming usage, assistant-message, tool-completion, timing, and after-step projections for the successful retry then see no current step and are skipped, leaving public events and feature hooks inconsistent with the execution that actually completed.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

...pending.flatMap((item) => item.kind === 'remind' ? [item.entry] : []),
...inbox.remind,
];
patch(tx, { inbox: { ...inbox, remind: [] }, held: true });

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 Release the queue after a prompt gate rejection

When turn.starting blocks or fails while another prompt is already queued, this leaves the loop held; finishTurnTx() subsequently calls schedule(), which immediately returns while held is true. Nothing releases the loop unless another input arrives, so the already acknowledged trailing prompt can remain queued indefinitely after the rejected prompt.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

Comment thread todo.md
Comment on lines +268 to +272
# 323 Loop 回归 Review(2026-11-03)

## 结论

**323 相对 `main@origin` 存在多组确定的行为回归,目前不建议合并,也不能视为等价重构。**

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 Remove the committed agent review notes

This addition commits temporary agent-generated review conclusions, test logs, and pending design notes into the repository-root todo.md. These are working notes rather than product documentation and include stale commit-specific findings; remove this section or keep it under the ignored .tmp/ area as required by the repository workflow.

AGENTS.md reference: AGENTS.md:L93-L96

Useful? React with 👍 / 👎.

Comment on lines +126 to +127
case 'context.append_message':
context = foldAppendMessage(context, record['message'] as ContextMessage);

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 Rehydrate offloaded media before restoring loop history

After a session containing an inline image, audio, or video larger than the blob threshold is restarted, persistence has replaced its data URL with a blobref: URL, but restoreLoopJournal() folds that raw persisted message directly into the new loop. Unlike the removed contextMemoryKey replay state, this path has no loadParts rehydration step, so subsequent model requests receive the internal blob reference instead of the media data and silently lose the attachment.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

Comment on lines +284 to +286
void this.usage.record(this.scopeContext.agentContext, request.modelAlias, usage, request.source);
if (usage !== undefined) {
this.tokenCounting.measured(this.scopeContext.agentContext, request.messages, [message], usage);

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 Preserve live-history identity when recording measured usage

For normal turn requests, request.messages contains messages produced from HistoryMessage entries and projection, while TokenCountingAgentModel.measured() accepts a measurement only when every input message is the same object reference as the current ContextMessage history. Those references never match after this port, so this call becomes a no-op after successful requests and measured token anchors stop advancing; context budgeting, automatic compaction thresholds, and reported context usage then rely on stale or estimated values.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

this.states.get(turnKey).nextTurnId,
);
if (this.pendingReminders.length > 0) loop.remind(...this.pendingReminders.splice(0));
for (const nudge of this.nudges.slice(this.nudgeCursor)) this.sendNudge(nudge);

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 Honor dropped nudges before they reach the Core inbox

When a caller drops a pending notification—such as Tower exiting or TaskWait suppressing an already-delivered task completion—the handle only marks the outer Nudge as dropped, while this drain still sends every nudge and an already-sent entry is never removed from the Core inbox. The supposedly cancelled message can therefore be appended later and start an unexpected turn; skip dropped entries here and provide a way to retract entries that were already enqueued.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

Comment on lines +1004 to +1005
detach: (input) => this.detach(slot, typeof input === 'string' ? input : input.text),
});

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 Pass the loop task waiter into tool executions

When a tool using the new ToolExecuteInput.waitForTasks capability runs through this Core loop, the callback is always absent because executeTool() supplies detach and the event callbacks but never the waitForTasks instance constructed by AgentMachine. The built-in human WaitFor tool consequently returns “requires background task support” even while this same loop owns detached tools; include waitForTasks: this.waitForTasks in the execution input.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

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

ℹ️ 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 284 to 289
if (tool === undefined) {
input.onAdjudicated?.(input.toolCall);
return {
content: [{ type: 'text', text: `unknown tool: ${input.toolCall.name}` }],
isError: true,
};

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 Route unknown calls through the real tool executor

When the model calls a tool omitted from the current Core definition set—particularly a deferred or inactive MCP tool—this branch returns a generic error without invoking IAgentToolExecutorService. The previous loop detected this canned result and retried through the real executor, which applies the registered missing-tool describer, tool hooks, finalization, and telemetry; without that fallback the model loses the guidance needed to activate the tool and external hooks never observe the attempt.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

Comment on lines +240 to +244
onBatchError: (error) => {
const turn = this.active;
const step = turn?.current;
if (turn === undefined || step === undefined || step.signal.aborted) return;
turn.failedStep ??= { number: step.number, uuid: step.uuid, error };

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 Abort the step when the tool executor rejects

When the executor's async result stream throws, runBatch converts every pending call into fulfilled error results and this callback only records failedStep; Core consequently treats the tool batch as settled and proceeds through step.continuing, which is a no-op, issuing another LLM request before the failure is eventually noticed. The replaced machine path emitted toolBatchFailed and aborted the current step immediately, so executor failures now cause unintended model calls and can expose a response based on synthetic tool errors.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

Comment on lines +427 to +429
const journalEvent = this.journalEvent(event);
this.projectLoopEvent(event);
this.journal.append(journalEvent);

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 Persist the projected turn outcome

When compatibility logic reclassifies a Core outcome—such as turning a provider-filtered done result or a max-step blocked result into a failed turn—this listener still sends the original Core event to LoopJournal, while projectLoopEvent independently emits the corrected public TurnEnded. The wire can therefore record reason: "completed" or "blocked" for a turn whose live result was failed, so replay rebuilds turnKey.lastEnded and session outcome state differently after restart.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

step.messageId = meta?.messageId ?? step.messageId;
this.lastRequestId = this.activeRequestTrace?.requestId;
const toolCalls = step.entry.message.toolCalls;
if (toolCalls.length === 0) this.endOrInterruptStep(turn, step, step.providerFinishReason ?? 'completed');

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 Normalize empty tool-call finishes to other

When a provider reports finishReason: "tool_calls" but decodes to an assistant message with no tool calls, this now forwards tool_calls unchanged; the replaced path explicitly converted that combination to other. The incorrect value makes the external-hook adapter skip its Stop hook and publishes TurnStepCompleted.finishReason as tool_use even though no tool ran, breaking hook scripts and event consumers for this provider response shape.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Comment on lines +307 to +310
private ensureLoop(): void {
if (this.loop !== undefined) return;
this.createLoopFromSnapshot(this.journal.snapshot());
this.initialized = false;

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 the loop dormant until replay finishes

When a caller reaches history() or remind() after the scope is published but before IEventDispatcher.restore() completes, ensureLoop() constructs and drains a runnable Core loop from the not-yet-replayed journal. A prompt already parked through submit() can therefore start against empty or stale history; initializeLoop() then drops the service's reference and creates a second loop without closing the first, allowing the early request to keep emitting alongside the restored loop. Gate loop creation on restoration instead of creating this temporary live loop.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

Comment on lines +715 to +719
remind(...entries: readonly HistoryMessage[]): void {
if (this.disposing) throw abortError('Agent loop disposed');
this.ensureLoop();
if (this.loop !== undefined && this.quiescenceDepth === 0) this.loop.remind(...entries);
else this.pendingReminders.push(...entries);

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 Count queued reminders before auto-compaction

When a feature adds a reminder during an active step, this leaves it only in Core's reminder inbox until after the next step.starting hooks run. The auto-compaction hook therefore checks the token ledger without the reminder, so a large project, environment, or feature reminder can push the ensuing LLM request over the model limit even though the old immediate ContextMemory append would have triggered proactive compaction; include pending reminders in the token check or flush them before that hook.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

@sailist sailist closed this Nov 9, 2026
@sailist
sailist force-pushed the refact-323-11-02-agent-loop-runtime branch from b7063e3 to 713a200 Compare November 9, 2026 17:54
@sailist sailist reopened this Nov 9, 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: 05da35ea77

ℹ️ 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 +108 to +110
this._register(dispatcher.hooks.onDidRestore.register('task.history', async (_ctx, next) => {
const { journal } = await wire.readRestoreChains();
this.restored.restore(journal);

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 Restore legacy task metadata during session replay

When opening a session written by versions that persisted task metadata only under tasks/*.json, this hook now rebuilds task history exclusively from TaskStarted/TaskTerminated wire records. Those legacy sessions have no corresponding wire events, so list() and getTask() return nothing; because output reads first require a known task, the saved background-task output also becomes unreachable after upgrade. Read or migrate the legacy task documents before falling back to the wire-only history.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

@@ -201,7 +196,7 @@ export const toolCallItemSchema = z.object({
output: z.string().optional(),
media: z.array(mediaSchema).optional(),
error: z.string().optional(),
progress: toolProgressSchema.optional(),
fields: toolFieldsSchema.optional(),

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 Preserve progress for existing conversation clients

When a desktop, web, or API client built against the previous conversation contract consumes a turn page or item.updated frame, it looks for the documented progress field; this schema and the feed now emit only fields, with the old progress data nested under it. Such clients silently stop displaying tool status, percentage, and custom progress updates, so emit the legacy projection alongside fields until released clients can migrate.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Comment on lines +848 to +849
this.loop?.cancel(target.promptId);
this.prompts.cancel(target.promptId);

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 Abort prompts canceled during the starting gate

When a caller cancels a prompt while its asynchronous turn.starting hook is still running, the prompt has already been removed from the mailbox but has not yet become activePrompt(). This call therefore removes nothing, marks the public handle cancelled, and lets Core continue into the model request after the gate completes, so a client can receive a successful cancellation while the supposedly cancelled prompt still executes. Detect the matching pending turn and abort it rather than only cancelling mailbox entries.

Useful? React with 👍 / 👎.

Comment on lines +893 to +896
await turnEnded;
await this.options.dispatcher.flush();
await turn.started;
turn.result.resolve(result);

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 Settle the turn result when event persistence fails

When TurnEnded dispatch or the following dispatcher flush rejects—for example because the session journal cannot be written—execution leaves this method before turn.result.resolve(result). The projection has already cleared its active turn, while SDK, print-mode, and subagent callers continue awaiting the unresolved result indefinitely; settle or reject the result in a guaranteed cleanup path when final event persistence fails.

Useful? React with 👍 / 👎.


export const AgentTaskConfigSchema = z.object({
maxRunningTasks: z.number().int().min(1).optional(),
keepAliveOnExit: z.boolean().optional(),

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 enforcing the configured task concurrency cap

When users set [task].max_running_tasks, legacy [background].max_running_tasks, or KIMI_CODE_BACKGROUND_MAX_RUNNING_TASKS, the schema now drops that field and its environment binding, while the replacement task path performs no capacity check. Background Bash commands and subagents can therefore exceed the configured resource cap, and Tower silently falls back to its hard-coded budget instead of honoring the same limit; restore the field, binding, and enforcement.

AGENTS.md reference: AGENTS.md:L126-L132

Useful? React with 👍 / 👎.

Comment on lines +1951 to +1953
if (!slot.detached) continue;
pending = true;
void slot.handler.stop(CLOSED);

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 Honor keep-alive when closing detached tasks

When a session closes with [task].keep_alive_on_exit = true (or its environment override), this path still stops every detached handler unconditionally. Long-running Bash commands and subagents that users explicitly requested to preserve are therefore killed on SDK/TUI session close—or after a bounded print drain—whereas the replaced task service skipped shutdown in this configuration; pass the policy into loop closure before stopping detached slots.

AGENTS.md reference: AGENTS.md:L126-L132

Useful? React with 👍 / 👎.

Comment on lines 182 to 185
this.instantiation.invokeFunction((accessor) => accessor.get(IAgentFullCompactionService)),
);

this.registerTaskHooks(
this.instantiation.invokeFunction((accessor) => accessor.get(IAgentTaskService)),
);
}

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 Restore external hooks for background task events

When hook scripts configure TaskStarted or Notification, background task launches and delivered completions no longer invoke them because the constructor no longer registers the task-event subscriptions and the TaskNotified projection was removed. The task events still occur, but hook-based monitoring and automation silently receive nothing; register equivalent subscriptions over the new task lifecycle and completion-delivery events.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

}
const completions: UserEntry[] = [];
for (const info of history.list(false)) {
if (info.status === 'lost' || !TERMINAL_STATUSES.has(info.status)) continue;

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 Surface interrupted background tasks after restart

When a session restarts with tasks whose last durable record is TaskStarted, history.restore() reclassifies them as lost, but this branch drops every such entry instead of adding the previous task_resume_termination reminder. The model receives no indication that background work was interrupted and no subagent resume guidance, so acknowledged work can be silently forgotten unless the user manually inspects TaskList; restore one non-turn-starting lost-task reminder during replay.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

@sailist
sailist force-pushed the refact-323-11-02-agent-loop-runtime branch from 05da35e to 3c8e06b Compare November 10, 2026 07:01

@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: 3c8e06b11f

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

@@ -40,10 +40,8 @@ export type { HookResultEvent } from '@moonshot-ai/agent-core-v2/features/extern
export type {
ToolCallStartedEvent,
ToolCallDeltaEvent,
ToolProgressEvent,
ToolUpdatedEvent,

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 Preserve the published tool.progress event

Existing Klient and node-sdk consumers subscribe to tool.progress and import ToolProgressEvent/ToolUpdate, but this replacement registers and exports only tool.updated. Previously released JavaScript clients will therefore silently stop receiving progress callbacks, while TypeScript clients fail when rebuilt; retain a compatibility projection or alias while introducing the new event.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

}
handler.observe((event) => {
if (event.type !== 'output') return;
stdout += event.text;

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 Preserve stderr in shell command results

For any ! command that writes to stderr, the new executor adapter exposes an undifferentiated output event and this line unconditionally appends it to stdout (the corresponding live event is also labeled stdout). Thus even printf error >&2 returns stderr: '', and mixed or failing commands lose the stdout/stderr separation that runShellCommand() and shell.output previously guaranteed; retain the stream kind through the executor or collect the original updates separately.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

const scopeHandle: IAgentScopeHandle = {
id: agentId,
kind: LifecycleScope.Agent,
accessor: {
get: (id) => container.invokeFunction((accessor) => accessor.get(id)),
},
dispose: () => container.disposeAsync(),
dispose: () => loop.close().then(() => container.disposeAsync()),

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 Dispose the scope even if loop closing fails

When loop.close() rejects, such as after a journal or wire persistence failure, removeManaged() catches that initial rejection and proceeds with cleanup, but this wrapper invokes the same cached rejecting close promise before container.disposeAsync(). The agent consequently remains in the roster with closing set, its container and event-bus resources are not released, and onDidClose never fires; perform container disposal in a guaranteed cleanup path and rethrow the saved close error afterward.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

this.tools.set(tool.name, candidate);
return this.registration(candidate, 'active');
if (this.tools.has(tool.name)) {
throw new Error(`Tool "${tool.name}" is already registered; unregister it before registering again`);

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 Reject colliding user tools before persisting them

When AgentUserToolService.register() receives a name already occupied by a built-in tool, it persists ToolsRegisterUserTool before reaching this new exception, so the caller sees a failure while the registration remains in durable state. On reload, user tools are restored before built-in activation, allowing the supposedly rejected user tool to register and causing activation to skip the built-in with that name; validate the collision before dispatching the state event or roll the event back when registration fails.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

Keep the current loop actor and task runtime tree while preserving the existing pull request history.
- separate prompt, turn, notification, and profile projections from the loop service
- unify tool handlers and task execution across foreground and background tools
- preserve live tool handlers during in-place loop resets
- apply conditional reminders at model execution boundaries
- restore configured default models when profile bindings are incomplete
- preserve in-flight prompt queue positions and effective turn entries
- align the test runtime and wire expectations with live-only events
- carry turn entries and tool durations through live and restored projections
- avoid duplicate first-restore projections and redelivered WaitFor notifications
- migrate affected tests to the current loop runtime contracts
- add explicit steered outcomes and per-step cancellation for steer requests
- keep user prompts separate and preserve partial tool-call state
- propagate interrupted step metadata through journal and clients
@sailist
sailist force-pushed the refact-323-11-02-agent-loop-runtime branch from 3c8e06b to c64f5c3 Compare November 10, 2026 13:12

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

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

seen.add(task.taskId);
suppressions.push(taskService.suppressTerminalNotification(task.taskId));
const remaining = Math.max(1, deadline - Date.now());
const waiter = taskService.wait(task.taskId, remaining);

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 task completions in print drain mode

When print_background_mode is "drain" (including the keep_alive_on_exit fallback), this loop now waits without suppressing terminal notifications; detached completion handling consequently queues the result and schedules another model turn. The same suppression was removed from SDKRpcClientV2.drainBackgroundTasksOnPrint, so both print paths can start a turn that cleanup immediately cancels, wasting a request and mutating the conversation despite the documented promise to drain without feeding results back. Restore suppression before waiting in both implementations.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

if (origin.variant === SWARM_MODE_INJECTION_VARIANT) return 'active';
}
return undefined;
if (trigger === null || trigger === 'tool' || this.options.isReminderDelivered()) return undefined;

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 Clear stale swarm guidance when leaving swarm mode

When a manually activated swarm exits after its enter reminder has been delivered, this branch now returns no inactive reminder while the active reminder remains in history; the deleted exit text was what told the model that the swarm workflow and AgentSwarm were no longer available. Subsequent ordinary requests therefore still include the stale active-mode instructions and can continue following the swarm workflow or calling an unavailable tool; replace or remove the active reminder, or restore explicit exit guidance.

AGENTS.md reference: AGENTS.md:L118-L120

Useful? React with 👍 / 👎.

Comment on lines +138 to +142
constructor(
@IAgentToolExecutorService private readonly toolExecutor: IAgentToolExecutorService,
@IAgentTaskHistoryService private readonly history: IAgentTaskHistoryService,
@IAgentTaskOutputService private readonly outputs: IAgentTaskOutputService,
) {

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 Restore the subagent background-task reminder

For every non-main agent with WaitFor enabled, this replacement no longer registers the subagent_background_task reminder that warned the model not to finish its final handoff while child work it needs is still running. A subagent can therefore end its turn with a required detached task outstanding, after which its completion notification has no live consumer and the result is silently lost; restore the conditional reminder registration in the new task path.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

Comment on lines +138 to +142
constructor(
@IAgentToolExecutorService private readonly toolExecutor: IAgentToolExecutorService,
@IAgentTaskHistoryService private readonly history: IAgentTaskHistoryService,
@IAgentTaskOutputService private readonly outputs: IAgentTaskOutputService,
) {

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 Restore active-task guidance after compaction

When context compaction removes the exchange that launched a still-running detached task, this replacement no longer observes ContextSpliced or registers the background_task_status reminder. The next request therefore receives neither the active-task list nor the instruction to avoid restarting that work, so the model can silently forget or duplicate live tasks after compaction; restore the compaction-triggered provider around the handler-backed task service.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

Comment on lines +41 to +45
submit: {
input: z.tuple([promptPayloadSchema]),
output: maybe(promptLaunchResultSchema),
},
notifyClient: {

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 Preserve the legacy prompt RPC service

When a released Klient or node-sdk client connects using the previous contract, prompts still target agentPromptService.submit and steering targets agentPromptService.submitSteer, but this moves both methods to agentLoopService and removes the old service from the global contract and dispatcher. Those clients now receive a service/method-not-found error for every prompt instead of starting a turn; retain an alias for the old service and translate submitSteer to notifyClient.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Comment on lines 350 to +351
this.originalCallIndex.set(toolCallId, index);
this.recordTurnRepeat(toolCallId, toolName, args, key, trace);

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 Deduplicate identical tool calls within a step

When a provider emits the same tool name and arguments twice in one response, checkToolCall now records both calls as originals and the replacement executor runs both independently; the removed deferred/synthetic path executed the operation once and shared its result. This reopens duplicate side effects for calls such as Bash or file edits, despite the published behavior that identical same-step calls do not execute multiple times; restore the same-step duplicate lookup before admitting the second execution.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

Drop the bindBootstrap permission-rule copy that referenced undefined symbols; configured rules are read live. Clear the unused-symbol lint errors, remove maxRunningTasks from the published config, and restore code-point task output truncation.

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

ℹ️ 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 +146 to +147
resolveModel(model: string): ProfileSetModelResult;
resolveThinkingLevel(level: string, current?: ProfileBindingSnapshot): string;

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 Route profile mutations to the loop service

When a Klient consumer calls setModel() or setThinking() through kap-server's generic agent RPC, the facade still dispatches agentProfileService.setModel/setThinking (packages/klient/src/core/facade/agent.ts:168-173), but this change removes both methods from IAgentProfileService and replaces them with non-mutating resolvers. Kap-server resolves the actual DI service directly, unlike the memory transport's compatibility alias, so both calls now return method not found and remote clients cannot change model or thinking level. Route these contract methods to agentLoopService or retain compatible profile-service methods.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

@WilliamLambertCN WilliamLambertCN 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.

严重BUG 确认。

新版新增了逐条深复制。官方 2.5.2、2.5.3 都直接使用已有状态;到 2.6.0,循环里多了 structuredClone(...)。引入它的具体提交是官方 PR #4630。

核对了这三个版本实际发布的官方代码,区别就在 attachLateNow() 的历史循环里:

// 2.5.2、2.5.3
produce(attachment.getState(), ...)
// 2.6.0
produce(structuredClone(attachment.getState()), ...)

这意味着:处理下一条历史记录之前,先把已经累积的整份状态再复制一遍。 历史越多,重复劳动越大。隔离测试的 88.9 秒里,有 67.9 秒耗在深复制上,所以不是纯猜测,已经证明能造成严重卡顿。

7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 15, 2026
… retry row

Port upstream MoonshotAI#4831 (partial).

- Report a failed attempt's usage, message id and timing through a new
  ModelRequestParams.onAttemptFailure callback into the machine retrying
  event, so the retried step's step.end is populated while the partial
  content stays in the wire and history without a duplicate assistant
  message.
- Dedupe replayed turn.step.started events in SubagentActivityStore and
  reuse the failed attempt's row when the retry opens a new step number,
  clearing the retrying marker on the next start.
- Probe the task half as already equivalent: onDidChangeTask pushes every
  registration, detach and terminal change to SessionTaskFeed, and settle
  releases the foreground release, handle subscription and timeout. No
  production change.
- Ledger MoonshotAI#4831 stays partial: the upstream loop-core restructure is
  blocked on unlanded MoonshotAI#4630.
RealKai42 added a commit that referenced this pull request Nov 17, 2026
* chore: reject comments in JS/TS code with a lint check

Add scripts/check-comments.mjs and run it before oxlint in `pnpm lint`
and in lint-staged. It parses every JS/TS file with oxc-parser and
rejects any comment except tool directives, the shebang,
`/// <reference>`, and single-tag JSDoc `@type` casts in JS files. A
file it cannot parse is reported instead of skipped.

Paths listed in .commentignore (gitignore syntax) are exempt. A full run
also reports entries that no longer match a file with comments, so the
list only shrinks.

`--fix` deletes the reported comments and writes a file only when its
AST is unchanged.

* chore: stop lint-staged from auto-fixing staged files

The pre-commit hook ran `oxlint --fix` over every staged file and folded
the result into the commit. Its fixes are not always safe: on main it
renames a catch parameter in packages/core/src/tool/runtime/tool-executor.ts
into a redeclared `error`, and rewrites `opts.match(event)` in
packages/core/src/utils/wait.ts as `event.test(opts)`. Any commit that
touched those files would fail or silently ship the rewrite.

The hook now only checks. Commits no longer get fixable problems
repaired automatically; run `pnpm lint:fix` to apply oxlint fixes by
hand.

* chore: remove existing comments from JS/TS code

Generated with `node scripts/check-comments.mjs --fix`. Every rewritten
file parses to the same AST as before, apart from removed JSX comment
containers (`{/* ... */}`).

Two parts were not produced by `--fix` alone:

- The six files under "Kept for now" in .commentignore keep only the
  comments introduced in #4630, and packages/node-sdk/src keeps its
  JSDoc. Their other comments were removed with the same stripping logic.
- apps/kimi-code/scripts/native/native-deps.mjs drops a `@type` cast that
  referred to the removed `NativeDepDescriptor` typedef.

* chore: align the root ignore version with agent-core-v2

sherif rejects a dependency declared at different versions in the workspace. agent-core-v2 already depends on ignore ^5.3.2, and the root check script only uses its add/ignores API, which 5.x provides.

* build(nix): update pnpm deps hash

* chore: refuse --fix rewrites that change JSX text children

The --fix safety check merged adjacent JSX text before normalizing its
whitespace, while the JSX transform cleans each text node on its own.
Removing a comment that sits on its own line between two lines of text,
as in `<span>a\n {/* x */}\n b</span>`, turns children ["a", "b"] into
"a b", yet the check reported no change and wrote the file.

Normalize each JSX text node separately and drop empty ones, matching the
compiler. Such removals, and inline comments inside JSX text, are now
reported for manual deletion instead of being rewritten.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 23, 2026
Use the package root for the MCP management schemas so the engine's
deep-import gate passes, add the top-level cwd to the legacy klient
session fixture, and record the 2.7.0 prompt-prediction, request-metadata,
release-sync and core rows in the upstream ledger and playbook.

Verified: root typecheck and check:lint pass; the prompt-prediction and
subagent-activity suites pass 22/22. The full agent-core-v2 suite is 9379
pass / 102 skip / 2 fail; both failures are the upstream loop adapter
cases recorded under MoonshotAI#4630 (machine-loop max-steps bypass and detached
handlerForCall). The loop adoption itself lives on
wip/2.7-loop-runtime-adoption and is not merge-ready.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 24, 2026
Merge backup/wip-2.7-loop-runtime-adoption-6e7adb5932 into remerge/2.7.0. The upstream loop/core runtime is now the product loop; the machine loop files are retired and the fork contracts are restored.

Fix the max-steps bypass handoff: a bypass notification in the mailbox now marks the new turn and its next step, and the test's turnScoped:false contract is restored. coreLoopService.test.ts passes 19/19.

The targeted loop/compaction/telemetry set is 347 pass / 9 fail. Ledger MoonshotAI#4630 is partial until fullCompaction, loop.test.ts ordering/stopTurn, turn telemetry, toolAdapter and forkParity pass.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 24, 2026
Keep stopTurn ahead of empty continuation notifications, drop queued notifications when a turn stops, and restore the empty-notify next-turn contract. Seed the loop from the compacted context memory and flush the dispatcher before replaceHistory so deferred prompts see the summary. Update the loop snapshots for the reminder-inclusive context. Allowlist the upstream machineTools test, which toolAdapter covers. Ledger MoonshotAI#4630 now records the three remaining targeted failures.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 24, 2026
The 2.7 loop starts one tool call at a time; the fork's sibling-concurrency case now stops the running call before the next starts. Record the accepted behavior change in the playbook and update ledger MoonshotAI#4630 to the two remaining targeted failures.
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