Repository navigation
fix(agent-core-v2): initialize loop after profile and mode selection - #5141
Conversation
🦋 Changeset detectedLatest commit: 321dbdf The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3eb6c2c8c8
ℹ️ 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 (this.startRequested) return this.startPromise; | ||
| this.startRequested = true; | ||
| if (this.loop !== undefined) return; | ||
| this.startPromise ??= this.initializeLoop(undefined, tools).finally(() => { | ||
| this.startPromise = undefined; |
There was a problem hiding this comment.
Allow loop initialization to retry after rejection
If initializeLoop() rejects during a fresh agent's first operation, the finally clears startPromise but leaves startRequested true, so every later start() returns undefined without creating this.loop. A subsequent requester then dereferences an absent loop, while callers such as importContext() can queue reminders and report success even though flushReminders() is a no-op, silently losing the imported context; reset the requested state after failure or gate this fast path on a successfully initialized loop.
AGENTS.md reference: AGENTS.md:L210-L212
Useful? React with 👍 / 👎.
| // Restored agents have all initial inputs and start immediately. New agents | ||
| // start on their first submission or operation, after initial mode selection. | ||
| if (hasPersistedState) await loop.start(opts.initialTools); |
There was a problem hiding this comment.
Start the loop before standalone shell commands
When an SDK user creates a fresh session and calls runShellCommand() before submitting a prompt, this branch now leaves the loop uninitialized and the shell-command path never calls start(). Its input/output records are therefore left only in pendingReminders; history() cannot see them, flushReminders() returns immediately, and closing the session discards them, breaking the existing shell-command history contract for that client flow.
AGENTS.md reference: AGENTS.md:L190-L192
Useful? React with 👍 / 👎.
| // Restored agents have all initial inputs and start immediately. New agents | ||
| // start on their first submission or operation, after initial mode selection. | ||
| if (hasPersistedState) await loop.start(opts.initialTools); |
There was a problem hiding this comment.
Preserve explicit initial tools across deferred startup
For a newly forked agent, fork() supplies sourceLoop.baselineTools() through opts.initialTools, but hasPersistedState is false and this is now the only place that forwards those tools to start(). The later initializeHistory() or first submission starts without the argument and recomputes tools from current policy, so a parent whose frozen baseline differs from the current profile/registry produces a child with a different LLM tool schema instead of fork parity; retain the supplied baseline until deferred startup.
AGENTS.md reference: AGENTS.md:L206-L208
Useful? React with 👍 / 👎.
|
我在 Kimi Code (macOS app)里遇到同样的问题。 以下是我的 agent 在我本地环境里的验证: 已确认:本会话确实命中了 PR #5141 描述的工具基线问题,不是工具被配置禁用。 本会话
事件顺序也坐实了触发机制:
这与 PR #5141 的根因描述一致:Tower 后续激活改变了运行时 overlay,但没有重建模型静态工具 baseline。 因此当前会话继续等待或重试不会补挂这些工具。有效规避方式是:新建会话,先执行 |
3eb6c2c to
f0d43c4
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f0d43c429c
ℹ️ 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 loop.start(opts.initialTools); | ||
| // Restored agents have all initial inputs and start immediately. New agents | ||
| // start on their first submission or operation, after initial mode selection. | ||
| if (hasPersistedState) await loop.start(opts.initialTools); |
There was a problem hiding this comment.
Start after queuing pre-restore submissions
When an onDidCreateScope listener submits or notifies synchronously, admit() sees that restoration is not ready and only queues the input; hasPersistedState does not include these in-memory queues, so this branch skips startup and the prompt never launches unless another input happens to arrive later. The old unconditional startup drained this supported creation-time path, so startup should also be triggered when pending in-memory requests exist after restoration.
AGENTS.md reference: AGENTS.md:L191-L193
Useful? React with 👍 / 👎.
| this.startPromise ??= this.initializeLoop(undefined, tools).finally(() => { | ||
| this.startPromise = undefined; |
There was a problem hiding this comment.
Serialize close with deferred initialization
When a client submits the first prompt and immediately closes or deletes the session, admit() starts this asynchronous initialization without awaiting it, while close() does not wait for startPromise. If initialization has not assigned this.loop yet, shutdown skips loop.close(), clears the admitted prompt, and can then race with initializeLoop() installing a loop after the scope has been closed; startup must be cancelled or awaited before shutdown finishes.
Useful? React with 👍 / 👎.
| if (!this.isActive && this.loop.started) return { entered: false, reason: 'loop-already-started' }; | ||
| const owner = await this.resolveTowerOwner(); |
There was a problem hiding this comment.
Make Tower activation atomic with first startup
When two clients share a fresh session, or a background notification arrives while /tower on is resolving its owner or preparing the base, the loop can start after this one-time check but before the Tower tools are added at the end of resolveEnter(). The command then reports success and persists Tower mode, yet initialization has already frozen a baseline without TowerSpawn and the other Tower schemas, recreating the failure this change is intended to prevent; recheck or reserve startup across the awaited activation sequence.
AGENTS.md reference: AGENTS.md:L111-L116
Useful? React with 👍 / 👎.
5a0c98a to
55e63e5
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 55e63e5a16
ℹ️ 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 HEAD is detached (no branch is checked out), or you need to change the base, run `/tower <base-branch>` instead, for example `/tower feature/my-objective`. | ||
|
|
||
| Activate Tower before sending the first task in a session. After work has started, `/tower on` and `/tower <base-branch>` cannot newly enable Tower; create a new session and activate Tower before sending work. |
There was a problem hiding this comment.
Update Tower re-entry guidance for the new restriction
When Tower exits via /tower off or because Goal, Plan, or swarm mode is activated, the new startup gate makes /tower on fail for the rest of that session, but this guide still says at line 118 that users can return later with /tower on, and packages/agent-core-v2/src/features/tower/injection/tower-mode-exit-reminder.md explicitly tells them to re-enter that way. Update both messages so Tower users are not directed into a recovery path that is now guaranteed to fail.
AGENTS.md reference: AGENTS.md:L199-L201
Useful? React with 👍 / 👎.
| --- | ||
| '@moonshot-ai/agent-core-v2': patch | ||
| --- |
There was a problem hiding this comment.
Add changesets for the affected products
This only records an @moonshot-ai/agent-core-v2 library release, although the new Tower activation and re-entry restriction is directly visible to CLI and desktop/web users through their /tower and session-configuration flows. Add product changesets for @moonshot-ai/kimi-code and kimi-code-app; otherwise their release notes omit the workflow-breaking requirement to enable Tower before the loop starts.
AGENTS.md reference: AGENTS.md:L169-L170
Useful? React with 👍 / 👎.
| await this.wire.drainPersisted().catch(() => undefined); | ||
| const snapshot = this.journal.snapshot(); | ||
| this.profileAdapter.restore(snapshot); | ||
| // Capture the baseline once; createLoopFromSnapshot stores it in the loop profile. |
There was a problem hiding this comment.
Remove the newly added implementation comments
This commit adds implementation narration here and in profileAdapter.ts, toolActivationService.ts, evaluate.ts, toolSelectService.ts, towerService.ts, agentLifecycleService.ts, and sdk-rpc-client-v2.ts, despite the repository-wide rule that JS/TS code must not contain explanatory comments and should express these constraints through naming, types, tests, or lint rules instead. These paths being present in .commentignore only prevents the automated check from catching the violation; remove the newly introduced comments rather than relying on that exemption.
AGENTS.md reference: AGENTS.md:L79-L82
Useful? React with 👍 / 👎.
55e63e5 to
94c4150
Compare
94c4150 to
4006756
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ed430b6199
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const registration = this.toolRegistry.register(accessor.get(tool.id), { | ||
| disclosure: 'deferred', | ||
| }); |
There was a problem hiding this comment.
Keep Tower tools active for restricted main profiles
When KAP session creation selects a restricted main profile such as coder or explore together with tower_mode, enter() now only registers these tools; it no longer calls addActiveTool() as the previous implementation did. AgentToolSelectService.activeEntries() and execution policy subsequently filter every Tower tool because those profiles do not list them, so Tower reports successful activation while exposing no usable orchestration tools. Preserve the activation overlay or otherwise make Tower tools active for every profile from which enter() is supported.
AGENTS.md reference: AGENTS.md:L191-L193
Useful? React with 👍 / 👎.
| this.unregisterTowerTools(); | ||
| void this.dispatcher.dispatch(new TowerModeExit({ agentId: this.agentCtx.agentId })); |
There was a problem hiding this comment.
Stop advertising unloaded Tower tools to static-tool models
If Tower was enabled before startup on a model without dynamic tool loading, its deferred schemas are frozen into the loop baseline; after /tower off, this unregisters the executors but requestTools(..., false) still strips only the deferred marker and sends those schemas on later requests. The model can therefore keep selecting tools that now fail as unavailable, contrary to the new exit reminder and changeset claiming they were unloaded; retain executors for that capability or filter the static baseline when exiting.
AGENTS.md reference: AGENTS.md:L191-L193
Useful? React with 👍 / 👎.
| await loop.start(); | ||
| loop.remind(historyEntryFromContext(message)); | ||
| loop.flushReminders(); |
There was a problem hiding this comment.
Recheck import idleness after starting the loop
When two SDK clients share a fresh session, one can call importContext() while the other submits the first prompt: the import passes the busy check, yields here while deferred initialization runs, and the prompt can start a turn before this await resolves. The import then appends and flushes its context into that live turn instead of returning TURN_AGENT_BUSY, violating the method's existing busy contract; start before checking or repeat the busy check after this await.
AGENTS.md reference: AGENTS.md:L111-L116
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: df95ddcb3a
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const registration = this.toolRegistry.register(accessor.get(tool.id), { | ||
| disclosure: 'deferred', | ||
| }); |
There was a problem hiding this comment.
Skip Tower tools already registered by the active profile
When a KAP or SDK caller creates the main agent with the tower-worker profile, tool activation has already registered the six worker-shared Tower tools contributed in towerFeature.ts. /tower on then registers the main-only tools but throws when it reaches the existing TowerSend entry because the registry rejects duplicate names. This leaves Tower inactive after adoptTowerRoster() has claimed workspace ownership and after several partial registrations; reuse existing registrations or register only currently absent tools.
AGENTS.md reference: AGENTS.md:L191-L193
Useful? React with 👍 / 👎.
Start new agents on their first submission or operation while restoring persisted agents immediately. Gate Tower activation after startup so its tools enter the initial baseline.
Derive startup state from the loop and its initialization promise, allow failed starts to retry, and start source agents before forking. Preserve initial tool baselines and align reminder and history initialization tests.
Start loops before driving reminder hooks and seeding browser histories so deferred initialization cannot leave reminder assertions empty.
df95ddc to
19a302e
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 19a302e7df
ℹ️ 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 context.runtime.get(IAgentLoopService).start(); | ||
| launchContinuationTurn(context, state.goalId); |
There was a problem hiding this comment.
Recheck goal idleness after loop startup
When a fresh session has a paused or blocked goal and one KAP client resumes it with continuation while another client submits the first prompt, canLaunchContinuation() can pass before this await, but start() yields long enough for the prompt to begin a turn. launchContinuationTurn() then queues a separate goal-continuation prompt instead of attaching continuation state to the now-live turn, causing the user turn and an unintended follow-up continuation to run sequentially; recheck idleness after startup before launching.
AGENTS.md reference: AGENTS.md:L112-L117
Useful? React with 👍 / 👎.
| stage = 'start'; | ||
| await loop.start(opts.initialTools); | ||
| if (shouldStartImmediately) await loop.start(opts.initialTools); |
There was a problem hiding this comment.
Wait for MCP discovery before serving context tools
For a newly created session with configured MCP servers, this branch skips loop.start(), so an immediate KAP GET .../context/summary or GET .../context/items reads previewRequestContent() without awaiting ISessionMcpHandle.ready. Because MCP schemas are registered only as servers become connected, these endpoints can omit tool definitions and undercount the context even though creation previously awaited startup and MCP discovery; preserve that readiness guarantee for context readers without necessarily starting a turn.
AGENTS.md reference: AGENTS.md:L192-L194
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 321dbdf0c2
ℹ️ 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 admit(input: UserMessage): { readonly id: string; readonly entry: UserMessage } { | ||
| if (this.disposing) throw abortError('Agent loop disposed'); | ||
| if (this.dispatcher.restorePhase === 'ready') { | ||
| void this.start().catch(() => this.close().catch(() => undefined)); |
There was a problem hiding this comment.
Propagate first-start failures to prompt callers
When deferred initialization rejects—for example because MCP readiness or task-history reconciliation fails—this fire-and-forget catch discards the error and closes the loop. prompts.close() then resolves the admitted prompt's launched promise as undefined, so submitClient() and the REST gateway can return without an error even though the first prompt was cancelled and never ran. Await startup as part of submission or otherwise propagate its rejection to the caller instead of converting it into a silent close.
AGENTS.md reference: AGENTS.md:L212-L214
Useful? React with 👍 / 👎.
fed5d09 to
321dbdf
Compare
…minal (#5345) (#5369) * fix(agent-core-v2): initialize loop after profile and mode selection (#5141) * docs: clarify tool registration and filtering * fix(agent-core-v2): initialize loop after profile and mode selection Start new agents on their first submission or operation while restoring persisted agents immediately. Gate Tower activation after startup so its tools enter the initial baseline. * fix(agent-core-v2): restore deferred loop initialization Derive startup state from the loop and its initialization promise, allow failed starts to retry, and start source agents before forking. Preserve initial tool baselines and align reminder and history initialization tests. * test(desktop): initialize loops for browser reminder tests Start loops before driving reminder hooks and seeding browser histories so deferred initialization cannot leave reminder assertions empty. * feat(agent-core-v2): toggle tower mode mid-session with deferred tools * test(agent-core-v2): cover tower deferred tools end to end * test(agent-core-v2): script tower tests with the testkit model * refactor(core): replace loop.drained/loop.idle with loop end info on turn.ended (#5337) * fix(llm): validate deferred tool arguments against the visible tool view (#5231) * fix(desktop): resolve ssh.exe absolute path on Windows for remote terminal (#5345) --------- Co-authored-by: Haozhe <[email protected]>
…minal (#5345) (#5369) * fix(agent-core-v2): initialize loop after profile and mode selection (#5141) * docs: clarify tool registration and filtering * fix(agent-core-v2): initialize loop after profile and mode selection Start new agents on their first submission or operation while restoring persisted agents immediately. Gate Tower activation after startup so its tools enter the initial baseline. * fix(agent-core-v2): restore deferred loop initialization Derive startup state from the loop and its initialization promise, allow failed starts to retry, and start source agents before forking. Preserve initial tool baselines and align reminder and history initialization tests. * test(desktop): initialize loops for browser reminder tests Start loops before driving reminder hooks and seeding browser histories so deferred initialization cannot leave reminder assertions empty. * feat(agent-core-v2): toggle tower mode mid-session with deferred tools * test(agent-core-v2): cover tower deferred tools end to end * test(agent-core-v2): script tower tests with the testkit model * refactor(core): replace loop.drained/loop.idle with loop end info on turn.ended (#5337) * fix(llm): validate deferred tool arguments against the visible tool view (#5231) * fix(desktop): resolve ssh.exe absolute path on Windows for remote terminal (#5345) --------- Co-authored-by: Haozhe <[email protected]>
…minal (#5345) (#5369) * fix(agent-core-v2): initialize loop after profile and mode selection (#5141) * docs: clarify tool registration and filtering * fix(agent-core-v2): initialize loop after profile and mode selection Start new agents on their first submission or operation while restoring persisted agents immediately. Gate Tower activation after startup so its tools enter the initial baseline. * fix(agent-core-v2): restore deferred loop initialization Derive startup state from the loop and its initialization promise, allow failed starts to retry, and start source agents before forking. Preserve initial tool baselines and align reminder and history initialization tests. * test(desktop): initialize loops for browser reminder tests Start loops before driving reminder hooks and seeding browser histories so deferred initialization cannot leave reminder assertions empty. * feat(agent-core-v2): toggle tower mode mid-session with deferred tools * test(agent-core-v2): cover tower deferred tools end to end * test(agent-core-v2): script tower tests with the testkit model * refactor(core): replace loop.drained/loop.idle with loop end info on turn.ended (#5337) * fix(llm): validate deferred tool arguments against the visible tool view (#5231) * fix(desktop): resolve ssh.exe absolute path on Windows for remote terminal (#5345) --------- Co-authored-by: Haozhe <[email protected]>
…oonshotAI#5141) Port upstream de1a3b6: the loop starts lazily only when persisted state, a profile or tools require it; Tower registers its tools as deferred disclosures on enter and unregisters them on exit; profile tool tables and Tower reminders move to the deferred contract.
Requirement or Bug
本地 SDK / TUI 新建会话时,Loop 会在默认 profile 绑定前启动,使初始工具 baseline 没有按 profile 过滤。启动后再进入 Tower 也只改变 active-tool overlay,导致
TowerSpawn等工具未进入模型的静态工具列表。本 PR 让 profile 与初始模式选择先于工具 baseline 初始化,同时保留旧会话恢复后 pending 工作自动继续的语义。
Bug Reproduction Steps
Root Cause
根因是初始化顺序:新建 agent 过早启动 Loop,而 Tower 后续激活只扩大运行时策略,不会也不应该在请求期重建工具 baseline。
这是生命周期修复,不是在请求期合并新增工具的绕过方案。新建会话延迟到首次实际工作才启动;恢复会话因输入与 profile 已齐全而立即启动;未激活的 Tower 在启动后禁止新的 enter。
Code Changes
核心思路是让工具 baseline 只在信息齐全时初始化一次,而不是在后续请求中修补它。
flowchart TD A[创建 agent] --> B{存在持久化状态} B -- 否 --> C[绑定 profile 并选择初始模式] C --> D[首次 submit / notify / operation] B -- 是 --> E[恢复后立即启动] D --> F[初始化一次工具 baseline] E --> F F --> G{Tower 是否已启动前激活} G -- 是 --> H[Tower 工具进入初始 baseline] G -- 否 --> I[拒绝 loop-already-started]主要改动:
loop-already-started,并补充 telemetry 原因与中英文指南。@moonshot-ai/agent-core-v2的 patch changeset。阅读顺序:先看
agentLifecycleService.ts的创建与恢复分流,再看loopService.ts的启动入口,最后看towerService.ts的启动门禁。其余为测试、注释、文档和 changeset。Behavior Changes and Affected Users
loop-already-started验证结果:
pnpm lint:通过,包括注释检查、oxlint、导入边界和仓库守卫。agent-core-v2、kap-server、kimi-code-sdk三个包 typecheck:通过。pnpm -C docs run build:通过,中英文 Tower 指南已同步。Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.