Skip to content

refactor(core): run loop turns on an independent state machine and actor runtime - #5195

Closed
sailist wants to merge 5 commits into
loop-refactfrom
refact-405-11-20-turn-state-machine
Closed

sailist wants to merge 5 commits into
loop-refactfrom
refact-405-11-20-turn-state-machine

Conversation

@sailist

@sailist sailist commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

Requirement or Bug

当前 LoopActor 同时承担 MailBox、history 投影、Turn/Step 推进、LLM 请求、前台工具、abort 与恢复调度,Turn 生命周期散落在三十余种内部消息处理中,createTurn 只是数据工厂。本 PR 把 Turn 的状态机独立抽出,并引入一个通用 actor 运行时承接 Loop 与 Turn 共有的事件派发、协程调度与生命周期管理,让 Turn 独占自身状态迁移和前台执行闭环。这是 turn 状态机重构的第一段提交栈,后续还有 Loop 接口整理。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

核心思路:Turn 独占自身状态迁移和前台执行闭环;Loop 独占启动/终止权、MailBox、history、恢复调度、requester template 和工具实例管理。两者通过预注册的宿主 hook 与注入的运行时端口协作,Loop 与 Turn 各自持有独立的 actor 实例,不再共享私有消息队列。

概念 回答什么问题 本 PR 之后
Turn 状态机 Turn 自身的状态迁移和前台执行闭环归谁管 独立 createTurn,显式 phase/state,线性 async/await 推进 prompt / continue / resume / step / tool / ending / terminal
actor 运行时 Loop 与 Turn 共有的事件派发、协程、取消、idle、close 语义 抽到 packages/core/src/actor:同步原子 act、受控串行协程(spawn/step/checkpoint/waitUntil)、非重入事件派发、幂等 close;Loop 与 Turn 各持独立实例
Turn 宿主 hook Loop 在 Turn 生命周期关键点要做什么 Loop 初始化时一次性注册 starting/requesting/continuing/ending,创建 Turn 只注入同一 hook 视图
flowchart TD
    subgraph Loop["LoopActor(Loop 侧宿主)"]
      MB[MailBox / history 投影 / 恢复调度]
      REQ[requester template]
      TOOLS[工具实例 map / detached completion]
    end
    subgraph Turn["Turn(独立状态机)"]
      SM[显式 phase/state<br/>线性 async/await 推进]
    end
    ACTOR["actor 运行时(Loop 与 Turn 各持独立实例)"]
    MB -->|"唯一入口 activate:同一时刻最多一个 active Turn"| SM
    SM -->|"宿主 hook:starting / requesting / continuing / ending"| MB
    SM -->|"批次端口:executeBatch / abortBatch"| TOOLS
    SM --> REQ
    MB --- ACTOR
    SM --- ACTOR
Loading
决策 选择 没选 理由
Turn 内部控制流 线性 async/await + 显式状态快照 初版方案的大批内部中转消息和状态守卫 线性推进保持可读性,显式状态仍可观测
工具管理 Turn 内无 tool map,批次执行经注入的 ToolRuntime 端口 Turn 自持工具注册表 工具实例生命周期、stop/detach、detached completion 归 Loop
宿主 hook 注册 Loop 初始化时一次性注册,重复注册抛错 每次创建 Turn 注册 / 可链式多次注册 契约要求单点注册,避免逐 Turn 注册与多点覆盖
事件时序 同步 hook 与无等待 completion 走同步快路径 全部包进 actor 协程 多包一层协程会增加恢复微任务,导致 token_counting 等事件顺序漂移

阅读指南:

  1. packages/core/src/actor/actor.ts — actor 运行时全部语义(act / spawn / step / checkpoint / waitUntil、事件派发、取消与 close)。
  2. packages/core/src/loop/turn/ — Turn 公开契约、状态机与 Step 执行、宿主 hook registry、批次工具端口。
  3. packages/core/src/loop/loop-actor.ts — Loop 如何经唯一 activate 创建与终止 Turn,以及保留的 MailBox / history / 工具宿主职责。
  4. packages/agent-core-v2/test/agent/loop/core/{wait,hooks}.test.ts — Turn 生命周期对抗用例与宿主 hook 单点注册用例。

可略读:index 导出接线、oxlint 棘轮基线调整(promise/no-callback-in-promise 1→0)。

Behavior Changes and Affected Users

None — Loop/v2 外部行为、事件顺序和消息契约不变:

Behavior Before After Who relies on the old behavior Escape hatch
Loop/v2 外部行为、事件顺序、消息契约 现状 不变:turn.starting → started → message.appending → step 顺序、单条 user prompt 契约(hook parts 合入同一条 prompt)、notify / resume / detached completion / abort grace 行为均保持 所有 Loop/v2 消费方 N/A
core 库 turn host hook 注册 API addTurnHook 可链式多次注册 registerTurnHooks 单次注册,重复注册抛错 无外部消费方(全仓库唯一注册方是 loop-actor 自身) 不适用(库内部 API)

验证结论:

  • 不变性回归:m0-dev 上 packages/core + test/agent/loop + test/features/externalHooks + test/agent/prompt 合计 52 文件 627/627 通过,其中原有事件顺序 snapshot 未修改即通过。
  • 新增覆盖:actor 合约测试 18 例(本地与 m0-dev 均通过,actor.ts 的 V8 Statements / Branches / Functions / Lines 均 100%);Turn 生命周期对抗用例(重复 start、force abort、late outcome、finished 后不再执行);宿主 hook 单点注册用例。
  • core 与 agent-core-v2 tsc --noEmit 通过;仓库标准 pnpm lint 全部通过。
  • 未验证:全 monorepo 测试未跑;本改动无 Windows 专属路径,未做 Windows 验证。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

@changeset-bot

changeset-bot Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 0320214

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 20, 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-21T10:24:26.245172Z 0320214 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4d12d05464

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


constructor(private readonly input: TurnInput, private readonly runtime: TurnRuntime) {
this.id = input.id;
this.scope = withAbort(runtime.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 Honor the per-turn abort signal

For direct callers of the newly exported createTurn API, aborting the TurnInput.signal has no effect because the turn scope is derived only from runtime.signal and input.signal is never observed. Consequently, even an initially aborted input can start hooks and an LLM request, and an in-flight turn continues instead of resolving as aborted; Loop.runTurn only avoids this through its separate outer listener. Compose the input signal into this scope or register an abort listener inside ActorTurn.

Useful? React with 👍 / 👎.


private async executeBatch(proc: TurnProcess, step: TurnStep): Promise<boolean> {
this.setPhase(proc, 'batching');
const starting = await proc.step(() => this.batchStarting(step));

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 Skip batch-starting hooks after an in-flight abort

When a turn is aborted during an LLM request but the requester ignores the signal and still resolves within the grace period with tool calls, this.outcome is already aborted, yet the new path invokes batchStarting before checking that outcome. The previous startBatch checked for an aborted turn first and skipped the hook, so configured batch hooks—such as the swarm policy hook—now run after cancellation and an asynchronous hook can delay the aborted turn even though tool execution is subsequently replaced with aborted outcomes. Check the aborted outcome before invoking the hook.

AGENTS.md reference: AGENTS.md:L111-L115

Useful? React with 👍 / 👎.

@sailist
sailist changed the base branch from main to loop-refact November 21, 2026 07:23
- add scoped synchronous controls, cooperative processes, and lifecycle management
- cover actor scheduling, cancellation, event delivery, and close semantics
- replace loop-actor's private queues and manual idle/close with actor scheduling
- track turn phase/step in a per-turn actor with step-scoped streaming callbacks
- register turn host hooks once at loop init and reject repeated registration
@sailist
sailist force-pushed the refact-405-11-20-turn-state-machine branch from 4d12d05 to 0320214 Compare November 21, 2026 10:16
@pkg-pr-new

pkg-pr-new Bot commented Nov 21, 2026

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

commit: 0320214

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

ℹ️ 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 +685 to +688
this.runtime.host.transition(() => {
this.emit(this.endedStep(step));
});
this.currentStep = 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.

P2 Badge Finalize turn state before emitting step.ended

When a synchronous loop subscriber calls abort() from a step.ended callback—as the new reentrant-abort test does—runtime.host.transition delivers this event before currentStep is cleared. The abort therefore re-enters finishTurn, sees the same active step, and calls finalizeStep again, emitting a duplicate step.ended; after the callback unwinds, this outer invocation can also overwrite the aborted state with its captured pre-abort outcome. Commit the step and turn state before exposing the event, as the previous loop implementation did.

AGENTS.md reference: AGENTS.md:L111-L115

Useful? React with 👍 / 👎.

timers.clear();
const registered = cleanups.splice(0).toReversed();
try {
for (const cleanup of registered) cleanup();

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 Settle the step when an exit cleanup throws

If any callback registered with step.onExit throws while a step completes or is cancelled, cleanupStep() escapes after finishStep() has set settled = true but before either doneGate or the suspended process gate is settled. The task's catch then calls finishStep('reject', error) again, but the settled guard makes that call a no-op, leaving the runner suspended forever and causing ProcessHandle.done, waitForIdle(), and close() to hang. Capture cleanup failures while still settling the gates, rejecting the step with the cleanup error.

Useful? React with 👍 / 👎.

Comment on lines +833 to +834
} catch (error) {
completion.reject(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.

P2 Badge Finish closing after a scheduler error

If onSchedule throws during the initial kick() in close(), this catch only rejects the close promise: the queued close command remains pending, closing remains false, and closeCompletion permanently retains the rejected promise. A subsequent close() therefore cannot retry or drive that command, leaving the actor open; a later unrelated act() can then unexpectedly execute the stale close command even though the caller's close promise already failed. Convert this failure into a terminal close error or remove the pending close attempt so the actor is not stranded between open and closed states.

Useful? React with 👍 / 👎.

@sailist

sailist commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #5211.

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