Repository navigation
refactor(core): run loop turns on an independent state machine - #5211
Conversation
|
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: 07902efff7
ℹ️ 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".
| : await runItem('step.stopping', () => stoppingHook({ ...event, draft }, signal), isStepStoppingVerdict); | ||
| failures.push(...stopping.failures.map((failure) => ({ point: 'step.stopping' as const, failure }))); | ||
| if (draft.type === 'aborted') return { outcome: draft, failures }; |
There was a problem hiding this comment.
Skip completion hooks for aborted steps
When an active step is cancelled, the aborted draft now reaches step.stopping before the early return. In agent-core-v2, turnProjection.ts:324-343 maps that hook to every onDidFinishStep callback, and fullCompactionService.ts:188-190,517-548 may consequently start an automatic compaction/model request. For users whose context is above the compaction threshold, cancelling a turn can therefore incur another model request and later mutate the context after the cancelled work; previously aborted drafts skipped this hook. Return before invoking completion-only hooks, or explicitly prevent those hooks from doing post-completion work for aborted drafts.
AGENTS.md reference: AGENTS.md:L111-L115
Useful? React with 👍 / 👎.
| abort(reason?: unknown, options?: { readonly force?: boolean }): void { | ||
| if (this.closing || this.finished) return; |
There was a problem hiding this comment.
Honor force while the turn is finishing
After the first abort enters finishTurn, the phase becomes finishing, so this guard discards every subsequent abort—including the forced abort issued by Loop.close(). Because closeTurn awaits step.stopping and then the owner-ending hook without a timeout, any hook that ignores cancellation or never settles leaves runTurn(), close(), and subsequent scheduling stuck indefinitely, with repeated cancellation unable to recover. Allow a forced abort to cancel or bypass the finishing hook waits while preserving single terminal-event delivery.
AGENTS.md reference: AGENTS.md:L111-L115
Useful? React with 👍 / 👎.
| return this.actor.act(() => { | ||
| if (!this.open()) return undefined; | ||
| return this.mailbox.notify(normalized); | ||
| }); |
There was a problem hiding this comment.
Keep restored notifications parked until intake is released
Unlike the previous direct mailbox insertion, wrapping recordNotification in actor.act() causes kick() and onSchedule to run before this method returns. When the loop is idle after a turn and therefore already has held === false, a restored prompt-only background-task completion starts immediately. AgentLoopService calls this method immediately before drainPendingToLoop(), so submissions parked outside the core loop by a quiescence lease have not yet entered the normal queue and the restored notification can bypass that lease and run ahead of queued user work. Preserve the non-scheduling behavior here so the caller can drain normal admissions and explicitly release intake in the intended order.
AGENTS.md reference: AGENTS.md:L111-L115
Useful? React with 👍 / 👎.
07902ef to
55319e1
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 55319e11d4
ℹ️ 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".
| private abortToolBatch( | ||
| batch: TurnToolBatch, | ||
| reason: unknown, | ||
| _options?: { readonly force?: boolean }, |
There was a problem hiding this comment.
Honor force when aborting active tool batches
When Loop.close() or a repeated abort passes { force: true } while a foreground tool batch is active, this method ignores the flag, merely requests handler.stop(), and returns undefined. If a custom, MCP, or other tool does not settle after cancellation, completeAbortedBatch() is never reached and closeRuntime() waits on turn.machine.done indefinitely. The forced path should synthesize terminal outcomes and settle the active batch rather than depending on cooperative tool shutdown.
AGENTS.md reference: AGENTS.md:L111-L115
Useful? React with 👍 / 👎.
| this.record(event); | ||
| if (event.type === 'turn.ended' && this.turn?.machine.id === event.turnId) { | ||
| this.finishTurn(this.turn, event.outcome); |
There was a problem hiding this comment.
Finalize the turn before dispatching turn.ended
Because record() synchronously dispatches subscribers, turn.ended is delivered before finishTurn() changes the loop from running to idle. A terminal-event subscriber that immediately calls runTurn() now gets runTurn is only accepted while idle; more severely, if any subscriber throws and no onListenerError is configured, control never reaches finishTurn(), leaving the loop permanently attached to the ended turn. Complete the loop-side state transition before delivering the terminal event while preserving terminal-event ordering.
AGENTS.md reference: AGENTS.md:L111-L115
Useful? React with 👍 / 👎.
014fda3 to
ead84f0
Compare
- add an actor runtime for loop and turn execution - unify turn hooks and asynchronous lifecycle settlement - simplify loop contracts and cover turn lifecycle behavior
ead84f0 to
b2f45be
Compare
* refactor(core): run loop turns on an independent state machine - add an actor runtime for loop and turn execution - unify turn hooks and asynchronous lifecycle settlement - simplify loop contracts and cover turn lifecycle behavior * fix(core): park recorded notifications until intake * fix(core): settle forced aborts past stuck hooks and tools * docs(core): document loop emitted events and public API * fix(agent-core-v2): skip onDidFinishStep hooks for aborted steps
#5236) * refactor(core): run loop turns on an independent state machine - add an actor runtime for loop and turn execution - unify turn hooks and asynchronous lifecycle settlement - simplify loop contracts and cover turn lifecycle behavior * fix(core): park recorded notifications until intake * fix(core): settle forced aborts past stuck hooks and tools * docs(core): document loop emitted events and public API * fix(agent-core-v2): skip onDidFinishStep hooks for aborted steps
* refactor(core): run loop turns on an independent state machine (#5211) * refactor(core): run loop turns on an independent state machine - add an actor runtime for loop and turn execution - unify turn hooks and asynchronous lifecycle settlement - simplify loop contracts and cover turn lifecycle behavior * fix(core): park recorded notifications until intake * fix(core): settle forced aborts past stuck hooks and tools * docs(core): document loop emitted events and public API * fix(agent-core-v2): skip onDidFinishStep hooks for aborted steps * refactor(llm): legalize deferred tools in the resolver (#5142) * refactor(core): unify llm event stream and harden behavior tests - unify run boundaries, request summaries, delta events, retries, and outcomes - migrate Loop, agent-core-v2, and klient consumers to the unified event vocabulary - add aimock-backed transport coverage and restore historical LLM behavior tests - update the Nix dependency hash and affected snapshots * refactor(llm): legalize deferred tools in the resolver - strip deferred metadata during legalize for models without dynamic loading - stop convert from dropping deferred tools and dedupe declarations with top-level priority - merge protocol capabilities once at the encode pipeline entry - remove deferred tools in the dynamic loop resolver and announce their names first * refactor(llm): unify deferred tool request views - remove dynamic-only request branching from ToolSelect resolution - keep non-dynamic system schemas out of top-level tools - preserve baseline tools for side requests before capability shaping * refactor(llm): share the tool select request view - reuse deferred shaping in the resolver and request preview - preserve initial tool announcements in request previews - cover preview parity with deferred tools * refactor(llm): strip deferred metadata in tool select Remove deferred metadata from non-disclosure ToolSelect request views while preserving the loop baseline. Keep core legalization as the fallback for requests that bypass ToolSelect. * refactor(llm): contain tool disclosure in resolver * refactor(llm): hash the full request tool list - compute toolsHash over every input tool, including deferred ones - note the resolver and legalization timing on the llm run events * refactor(llm): remove the tool select experimental flag - drop the tool-select flag, env var, and [experimental] config entry - gate deferred tool disclosure solely on model capabilities - remove the desktop forced env and update the MCP and env-var docs - cover mid-loop active-tool requests with an empirical loop test * test(desktop): assert browser tool disclosure in the request view The previous assertions called loadableToolsAnnouncement() with no arguments, a calling form no production code uses; the model-facing disclosure is built per request by the ToolSelect resolver. Assert the request view instead: requestTools strips the deferred browser tool from the request tool list, shapeHistory injects the snapshot announcement naming it, and a reminder step after the control switch turns the removal into a <tools_removed> delta. * fix(core): recover compaction from empty text history (#5214) * test(core): cover empty text request recovery * fix(core): clean empty text before request encoding * chore: add empty text recovery changesets * test(core): cover cross-provider signed empty text * fix(core): drop unsupported signed blank text
…edgement (#5239) * refactor(core): run loop turns on an independent state machine (#5211) * refactor(core): run loop turns on an independent state machine - add an actor runtime for loop and turn execution - unify turn hooks and asynchronous lifecycle settlement - simplify loop contracts and cover turn lifecycle behavior * fix(core): park recorded notifications until intake * fix(core): settle forced aborts past stuck hooks and tools * docs(core): document loop emitted events and public API * fix(agent-core-v2): skip onDidFinishStep hooks for aborted steps * refactor(llm): legalize deferred tools in the resolver (#5142) * refactor(core): unify llm event stream and harden behavior tests - unify run boundaries, request summaries, delta events, retries, and outcomes - migrate Loop, agent-core-v2, and klient consumers to the unified event vocabulary - add aimock-backed transport coverage and restore historical LLM behavior tests - update the Nix dependency hash and affected snapshots * refactor(llm): legalize deferred tools in the resolver - strip deferred metadata during legalize for models without dynamic loading - stop convert from dropping deferred tools and dedupe declarations with top-level priority - merge protocol capabilities once at the encode pipeline entry - remove deferred tools in the dynamic loop resolver and announce their names first * refactor(llm): unify deferred tool request views - remove dynamic-only request branching from ToolSelect resolution - keep non-dynamic system schemas out of top-level tools - preserve baseline tools for side requests before capability shaping * refactor(llm): share the tool select request view - reuse deferred shaping in the resolver and request preview - preserve initial tool announcements in request previews - cover preview parity with deferred tools * refactor(llm): strip deferred metadata in tool select Remove deferred metadata from non-disclosure ToolSelect request views while preserving the loop baseline. Keep core legalization as the fallback for requests that bypass ToolSelect. * refactor(llm): contain tool disclosure in resolver * refactor(llm): hash the full request tool list - compute toolsHash over every input tool, including deferred ones - note the resolver and legalization timing on the llm run events * refactor(llm): remove the tool select experimental flag - drop the tool-select flag, env var, and [experimental] config entry - gate deferred tool disclosure solely on model capabilities - remove the desktop forced env and update the MCP and env-var docs - cover mid-loop active-tool requests with an empirical loop test * test(desktop): assert browser tool disclosure in the request view The previous assertions called loadableToolsAnnouncement() with no arguments, a calling form no production code uses; the model-facing disclosure is built per request by the ToolSelect resolver. Assert the request view instead: requestTools strips the deferred browser tool from the request tool list, shapeHistory injects the snapshot announcement naming it, and a reminder step after the control switch turns the removal into a <tools_removed> delta. * fix(core): recover compaction from empty text history (#5214) * test(core): cover empty text request recovery * fix(core): clean empty text before request encoding * chore: add empty text recovery changesets * test(core): cover cross-provider signed empty text * fix(core): drop unsupported signed blank text * fix(agent-core-v2): truncate foreground output in bash detach acknowledgement (#5218)
Port c6c7177. packages/core/src/hook/loop now owns the loop hook registry, chain runners, failure helpers and the max-steps builtin, and hook/index.ts is reachable through a new ./hook package entry. LoopActor takes Partial<LoopHooks> instead of building a per-loop registry; Loop.hooks, HookRegistration, HookInfo and HookLifecycleEvent are gone, and CreateLoopOptions.hooks became hook?: Partial<LoopHooks>. tool/hook-composer.ts is deleted in favor of createToolExecutorHookRegistry, and AgentToolExecutorService composes through that registry. Fork adaptations: - hook/result.ts only gains rewrittenBy; the fork's later (MoonshotAI#5211) HookFailure shape with suspend stays, and the chain failures suspend through it. - hook/loop/{failure,registry,run}.ts import Message from @moonshot-ai/core/llm/message like loop/contract/hook.ts already does: the agent-core-v2 tsconfig maps #/llm/message to src/human/llm/message, which would otherwise split the Message identity. - AgentLoopService registers turn.starting, message.appending, step.starting, step.stopping and max-steps once on a createLoopHookRegistry() field and keeps the fork's bypassStep max-steps condition; registerToolBatchStarting adds and removes by id. - AgentToolExecutorService keeps the fork-only forkHook in the chain. - test/harness/toolHooks.ts, the tool executor stubs and the hook-registry test were already ported; test/agent/task/stubs.ts needs no change because the fork carries no composeToolExecutorHooks there. Verified: - packages/core: typecheck clean; bun test --isolate test/tool/ 89 pass. - packages/agent-core-v2: typecheck clean and 25 pass (loop core hooks/record/requester/wait), 18 (hooks.test alone, including the new step.stopping block-policy case), 19 (coreLoopService), 64 (toolExecutor), 55 (toolScheduler + taskService), run through a temporary worktree-local node_modules junction so @moonshot-ai/core resolves to this worktree. - check:no-comments OK (2414 files), check-deep-imports OK, agent-core-v2 lint:imports OK (2058 files), scoped oxlint 0 errors. - test/agent/loop/loop.test.ts 65 pass / 3 fail: pre-existing snapshot drift (loopEnd missing from those snapshots, system-reminder wrapper text differs from src/agent/toolSelect/dynamicTools.ts), untouched by this port. - scripts/checks/ratchet.mjs aborts on pre-existing .oxlintrc vs .oxlintrc.ratchet.json ignorePatterns drift; both files are untouched here.
Requirement or Bug
LoopActor同时承担 MailBox、history 投影、Turn/Step 推进、LLM 请求、前台工具、abort 与恢复调度,Turn 生命周期散落在大量内部消息处理中,createTurn原本只是数据工厂。本 PR 将 405 的全部工作整合为单个提交:独立 Turn 状态机与通用 Actor 运行时,并统一内部契约、hook、abort 和关闭路径。本 PR 替代此前的 stacked PR #5195、#5208、#5209、#5210。
Bug Reproduction Steps
N/A
Root Cause
Turn 缺少独立且封闭的状态迁移边界,Loop 同时负责调度与执行细节,导致 hook 返回形态、abort 来源阶段和终局处理都依赖多条 continuation 路径,难以保证一致的生命周期语义。
Code Changes
packages/core/src/actor:同步原子act、受控串行协程(spawn/step/checkpoint/waitUntil)、非重入事件派发、取消、idle 和幂等 close;Loop 与 Turn 各持独立实例。createTurn:Turn 独占自身 phase/state、前台请求、工具批次、Step/Turn ending 和 done;Loop 保留 MailBox、history、active 调度、requester template 和工具实例管理。step.starting返回消息重写路径。await兼容。executeStep使用单函数线性async/await和 guard clause,所有等待统一经过proc.step;finishTurn启动唯一 close process,异步owner.ending后才发一次turn.ended并 resolve 一次done。step.ended重入 abort 的 outcome,避免局部 done 覆盖;append buffer 在 hook settle 后失效,晚到结果不能重新进入 Turn。jscpd:ignore-start/end,并在.commentignore中豁免create-turn.ts与loop-actor.ts;另应用户要求为 loop 模块公共面(create-loop.ts、contract/emitted.ts)补充 API 文档并加入豁免;这些注释不改变执行逻辑。recordNotification落账后置held驻留,由后续submit/notify/start经既有releaseIntake()释放,恢复「通知不越过 parked 普通消息」的入队顺序。forceCloseRequested与closeStep()解除对未 settle 的step.stopping/owner.ending的等待;active 工具批次仅为未完成 call 合成 aborted 结果、封闭晚到响应,保留真实与 detached 结果。turnProjection.stepStopping对 aborted draft 提前返回:aborted Step 不再触发onDidFinishStep链,goal/plan/toolDedupe/externalHooks 的 after-step 行为与 main 一致。Behavior Changes and Affected Users
owner.ending最后提交、turn.ended先于done、active 清理后再调度下一 Turnstep.stopping → step.ended → owner.ending → turn.ended → done,outcome 保持 aborted;onDidFinishStep链与 main 一样不为 aborted Step 执行step.starting通用消息重写Message[]并触发context.settledundefined/blockedreplaceHistory()/setContext()与 compaction/splice 通道保留验证:
tsc --noEmit通过。tool.test.ts无关 subagent 无 deadline 30s 超时(单独复验同现,路径不经本 PR 文件);coreLoopService21/21,相关 7 文件 393/393,test/agent/loop148/148。onDidFinishStepabort 用例修复前断言失败;recordNotification用例修复前观察到通知越过 normal。评审处理进展:
fullCompactionService通过ctx.signal.aborted识别并跳过,回归覆盖 aborted 不调用shouldCompact/begin、正常 Step 仍调用一次自动 compaction,完整 compaction 套件 118/118。onDidFinishStep链(goal/plan/toolDedupe/externalHooks)与 main 一样不为 aborted Step 执行;core 仍保留step.stopping事件面,signal.aborted守卫继续覆盖「abort 到达时 Step ending 已在飞」的竞态窗口。finishing/finished不再屏蔽 force;hook 不 settle 时 force 可放弃等待并正常发出 Step/Turn 终态事件与done;active 工具批次的未完成 call 合成 aborted 结果且晚到结果被封存。recordNotification提前调度——通知落账后held驻留,直到submit/notify/start释放 intake,保持 normal 优先于 prompt-only 通知。Checklist
/approve).