Repository navigation
refactor(agent-core-v2): port agent loop runtime core - #4630
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: 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'); |
There was a problem hiding this comment.
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'); |
There was a problem hiding this comment.
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 }], | |||
There was a problem hiding this comment.
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, | |||
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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({ |
There was a problem hiding this comment.
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) }, |
There was a problem hiding this comment.
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 👍 / 👎.
| if (entry.record.type === 'turn.prompt') { | ||
| reIncluded.push(entry); | ||
| continue; | ||
| } |
There was a problem hiding this comment.
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 👍 / 👎.
ca1f4ad to
522de3c
Compare
There was a problem hiding this comment.
💡 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; |
There was a problem hiding this comment.
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 👍 / 👎.
| case 'prompt.submitted': | ||
| this.normal.push(event.entry); | ||
| return; |
There was a problem hiding this comment.
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 👍 / 👎.
| } | ||
| return undefined; |
There was a problem hiding this comment.
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 👍 / 👎.
| private trackTaskStarted(entry: ManagedTask): void { | ||
| if (entry.startedTracked) return; | ||
| entry.startedTracked = true; | ||
| const info = this.toInfo(entry); | ||
| this.telemetry.track2('background_task_created', { |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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 👍 / 👎.
| this.terminalStates.set(waiter.id, state); | ||
| this.promptWaiters.delete(waiter.id); | ||
| this.steered.delete(waiter.id); |
There was a problem hiding this comment.
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 👍 / 👎.
8c2f965 to
deaacef
Compare
There was a problem hiding this comment.
💡 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, |
There was a problem hiding this comment.
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; | |||
There was a problem hiding this comment.
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 }); |
There was a problem hiding this comment.
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 👍 / 👎.
| # 323 Loop 回归 Review(2026-11-03) | ||
|
|
||
| ## 结论 | ||
|
|
||
| **323 相对 `main@origin` 存在多组确定的行为回归,目前不建议合并,也不能视为等价重构。** |
There was a problem hiding this comment.
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 👍 / 👎.
| case 'context.append_message': | ||
| context = foldAppendMessage(context, record['message'] as ContextMessage); |
There was a problem hiding this comment.
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 👍 / 👎.
| 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); |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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 👍 / 👎.
| detach: (input) => this.detach(slot, typeof input === 'string' ? input : input.text), | ||
| }); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
| if (tool === undefined) { | ||
| input.onAdjudicated?.(input.toolCall); | ||
| return { | ||
| content: [{ type: 'text', text: `unknown tool: ${input.toolCall.name}` }], | ||
| isError: true, | ||
| }; |
There was a problem hiding this comment.
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 👍 / 👎.
| 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 }; |
There was a problem hiding this comment.
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 👍 / 👎.
| const journalEvent = this.journalEvent(event); | ||
| this.projectLoopEvent(event); | ||
| this.journal.append(journalEvent); |
There was a problem hiding this comment.
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'); |
There was a problem hiding this comment.
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 👍 / 👎.
| private ensureLoop(): void { | ||
| if (this.loop !== undefined) return; | ||
| this.createLoopFromSnapshot(this.journal.snapshot()); | ||
| this.initialized = false; |
There was a problem hiding this comment.
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 👍 / 👎.
| 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); |
There was a problem hiding this comment.
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 👍 / 👎.
b7063e3 to
713a200
Compare
There was a problem hiding this comment.
💡 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".
| this._register(dispatcher.hooks.onDidRestore.register('task.history', async (_ctx, next) => { | ||
| const { journal } = await wire.readRestoreChains(); | ||
| this.restored.restore(journal); |
There was a problem hiding this comment.
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(), | |||
There was a problem hiding this comment.
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 👍 / 👎.
| this.loop?.cancel(target.promptId); | ||
| this.prompts.cancel(target.promptId); |
There was a problem hiding this comment.
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 👍 / 👎.
| await turnEnded; | ||
| await this.options.dispatcher.flush(); | ||
| await turn.started; | ||
| turn.result.resolve(result); |
There was a problem hiding this comment.
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(), |
There was a problem hiding this comment.
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 👍 / 👎.
| if (!slot.detached) continue; | ||
| pending = true; | ||
| void slot.handler.stop(CLOSED); |
There was a problem hiding this comment.
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 👍 / 👎.
| this.instantiation.invokeFunction((accessor) => accessor.get(IAgentFullCompactionService)), | ||
| ); | ||
|
|
||
| this.registerTaskHooks( | ||
| this.instantiation.invokeFunction((accessor) => accessor.get(IAgentTaskService)), | ||
| ); | ||
| } |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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 👍 / 👎.
05da35e to
3c8e06b
Compare
There was a problem hiding this comment.
💡 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, | |||
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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()), |
There was a problem hiding this comment.
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`); |
There was a problem hiding this comment.
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
3c8e06b to
c64f5c3
Compare
There was a problem hiding this comment.
💡 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); |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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 👍 / 👎.
| constructor( | ||
| @IAgentToolExecutorService private readonly toolExecutor: IAgentToolExecutorService, | ||
| @IAgentTaskHistoryService private readonly history: IAgentTaskHistoryService, | ||
| @IAgentTaskOutputService private readonly outputs: IAgentTaskOutputService, | ||
| ) { |
There was a problem hiding this comment.
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 👍 / 👎.
| constructor( | ||
| @IAgentToolExecutorService private readonly toolExecutor: IAgentToolExecutorService, | ||
| @IAgentTaskHistoryService private readonly history: IAgentTaskHistoryService, | ||
| @IAgentTaskOutputService private readonly outputs: IAgentTaskOutputService, | ||
| ) { |
There was a problem hiding this comment.
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 👍 / 👎.
| submit: { | ||
| input: z.tuple([promptPayloadSchema]), | ||
| output: maybe(promptLaunchResultSchema), | ||
| }, | ||
| notifyClient: { |
There was a problem hiding this comment.
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 👍 / 👎.
| this.originalCallIndex.set(toolCallId, index); | ||
| this.recordTurnRepeat(toolCallId, toolName, args, key, trace); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
💡 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".
| resolveModel(model: string): ProfileSetModelResult; | ||
| resolveThinkingLevel(level: string, current?: ProfileBindingSnapshot): string; |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
严重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 秒耗在深复制上,所以不是纯猜测,已经证明能造成严重卡顿。
… 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.
* 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.
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.
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.
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.
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.
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 投影]生命周期层不再传 turn/store/tool logic,Core Loop 也不反向依赖宿主。请求配置在 Turn 起点冻结,Step 继续读取最新 durable history;side request 使用独立配置,避免覆盖活动 Turn。
wire.jsonlschema阅读顺序建议:先看
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
tasks/*.json,另有通知投递状态output.log,完成结果经 Core detached tool 投递context.*/turn.*Wire recordsagent.*记录不参与恢复没有 UI/UX 变化。旧
wire.jsonl、公开 Prompt/Turn 事件和主要 SDK facade 的兼容路径均有保留;直接内部 machine/prompt 装配协议以及上述已确认的消息合并、message-anchor undo 行为不再保留。验证结论:
agent-core-v2typecheck 与 build 通过,ToolDedupe 57/57 通过;最后的接口注释修改也通过了 Core typecheck 和聚焦 oxlint。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.ts16/16、Core typecheck 通过;生产改动后的根构建通过。新 head 的 CI 以 GitHub checks 为准。Checklist
/approve).gen-changesetsskill; no changeset is included by explicit request.gen-docsskill, or this PR needs no doc update.