Repository navigation
refactor(agent-core-v2): converge loop llm requester and unify provider catalog - #5541
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2a6c37cc05
ℹ️ 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(this.config.onDidSectionChange(({ domain }) => { | ||
| if (REQUEST_CONFIG_SECTIONS.has(domain)) this.syncRequester(); | ||
| })); | ||
| this._register(this.providerCatalog.onChanged(() => this.syncRequester())); |
There was a problem hiding this comment.
Refresh requester on model and provider config changes
When an existing session reloads or edits models, providers, or the default provider, the new stores only mark the catalog dirty, while this listener waits for the catalog's onChanged event—which cannot fire until something separately calls sync() or resync(). Unlike the old per-request path, subsequent turns therefore keep using the previously bound endpoint, credentials, and wire model indefinitely; production has no corresponding resync call, and the new config-state test has to invoke one manually. Subscribe to the record/default-provider events or eagerly synchronize the catalog before rebinding.
AGENTS.md reference: AGENTS.md:L211-L213
Useful? React with 👍 / 👎.
| start(request: LlmRequest): AgentRequestObservation { | ||
| const { binding, historyRevision, infiniteRetry } = this.loopContext(); | ||
| const source = requestSourceOf(request.attributes); | ||
| if (binding === undefined) throw new Error('llm request has no bound model'); |
There was a problem hiding this comment.
Keep the active turn binding aligned with its requester
When a model or provider is switched or deleted between steps of a tool-using turn, the turn continues with the requester captured at turn start, but this observer reads the mutable latest currentBinding. A deletion makes the binding undefined and throws before the next request despite the captured requester remaining valid; a switch attributes usage and resolves media through the new model while sending the LLM request through the old one. Capture or derive the binding together with the request rather than consulting loop-global state.
AGENTS.md reference: AGENTS.md:L207-L209
Useful? React with 👍 / 👎.
| with: ((next: LlmRequestPart | FullLoopLlmRequester) => | ||
| accumulate(mergeFields(part as Fields, contentsOf(next) as Fields) as LlmRequestPart)) as FullLoopLlmRequester['with'], |
There was a problem hiding this comment.
Merge policies when chaining raw loop requesters
When a caller derives a side requester in multiple stages, such as .with({ policy: { recoveries: [a] } }).with({ policy: { recoveries: [b] } }), this generic mergeFields call replaces the first policy list with the second. That contradicts the policy-aware chaining implemented by the underlying LlmRequester.with, so recoveries, resolvers, or retryables silently disappear depending on how an otherwise equivalent request is composed. Use the same mergeLlmPolicies behavior here.
Useful? React with 👍 / 👎.
| get requester(): FullLoopLlmRequester { | ||
| const loop = this.loop; | ||
| if (loop === undefined) throw new BugIndicatingError('Agent loop is not started'); | ||
| return loop.requester; |
There was a problem hiding this comment.
Preserve lazy startup for side requesters
When code obtains a newly created or restored agent scope and issues a side request before explicitly starting the loop, this getter now throws BugIndicatingError('Agent loop is not started'). The previous prepareOperation() path automatically awaited start(), and the migrated requester test now has to add await loop.start(), demonstrating the new runtime precondition. Retain an always-available facade that starts lazily, or explicitly version and document this breaking lifecycle requirement.
AGENTS.md reference: AGENTS.md:L90-L90
Useful? React with 👍 / 👎.
| case 'llm.ended': { | ||
| const outcome = event.outcome; | ||
| const errorRequestId = outcome.type === 'failed' ? apiRequestId(outcome.error) : undefined; | ||
| this.activeRequestId = outcome.requestId ?? errorRequestId ?? this.activeRequestId; |
There was a problem hiding this comment.
Clear the tracked request ID before each retry attempt
When an LLM attempt emits a request ID and is then retried or recovered, a later successful attempt that emits no ID leaves activeRequestId pointing at the failed attempt because this fallback preserves the previous value. The old shared request trace was cleared by recordAttempt() before every attempt; now only the observer's private ID is cleared, so turn.ended, reply-model attribution, and telemetry can publish the wrong upstream request ID. Clear the projection's ID on the next llm.requested attempt boundary or propagate the observer reset.
AGENTS.md reference: AGENTS.md:L207-L209
Useful? React with 👍 / 👎.
2a6c37c to
54bfafe
Compare
🦋 Changeset detectedLatest commit: 4332337 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 |
54bfafe to
f0e81df
Compare
commit: |
… request Read model identity, thinking effort, system prompt, and request metadata from the frozen LlmRequest instead of the mutable currentBinding, and clear activeRequestId on every llm.requested attempt so retries without a new request id do not reuse the failed attempt id.
Compaction (MoonshotAI#5538): - Send the whole history to the summary request, drop the pre-shrink and the drop-oldest retries, shrink a truncated summary only when the window squeezed its output, and retry empty or thinking-only summaries with the same history. Keep flushReminders, applyCompactionRound and historyFromContextPreservingToolNotes. - Fix two pre-existing 2.7-alignment gaps the suite exposed: recognise the serialized { kind: 'context_overflow' } payload in shouldRecoverFromContextOverflow, and remove the duplicate runWithCredentialRecovery around the requester's own credential recovery so a replayed 401 surfaces instead of being retried. - fullCompaction 124 pass / 0 fail; agent-core-v2 typecheck clean. Built-in tool settings (MoonshotAI#5489): - Keep MoonshotAI#5351's KAP catalog/config/agent-state fields, the four mode guards and the desktop/Web UI as a fork-only capability. - Replace the 22 per-tool userConfigurable flags with the central USER_CONFIGURABLE_BUILTIN_TOOL_NAMES list in kap-server. The catalog still returns the same 39 entries (26 core + 13 Tower), now pinned by tools.test.ts. - Ledger: MoonshotAI#5351 marked fork-only, MoonshotAI#5489 not-applicable with the keep-both approval, both in B2; the PLAYBOOK records the invariant. - kap-server tools 8 pass; agent-core-v2 and kap-server typecheck clean. Loop baseline: - max_steps no longer marks a completed step as interrupted. - Goal creation accepts UpdateGoal when it is loadable through isToolActiveForDisclosure. - Refresh the three loop inline snapshots for the intentional continuation, loadable-tools and step.begin shape. - test/agent/loop 175 pass / 3 fail; the three remaining failures are the pre-existing cancelled-partial preservation, recorded as the first acceptance of the MoonshotAI#5541 requester migration. Ledger refresh adds 87 upstream rows; MoonshotAI#5538 and MoonshotAI#5489 are triaged, 85 remain pending.
Port MoonshotAI#5541's requester union onto the fork's loop structure. The fork has no upstream turn/ split, so the union lives on the existing loop-actor turn path: LoopRequester = LoopLlmRequester | FullLoopLlmRequester, Loop.baseRequester, and the snapshot cast in the per-turn requester derivation. Add the core requester compatibility test with bun:test. Verified: core requester test 2 pass; core typecheck clean.
Port MoonshotAI#5541's side requester: createLoopRequester exposes the loop's live messages, profile and policy through loop.requester with a lazy full-base lookup; add requestProfileOf and isFullLoopRequester. The legacy per-turn snapshot keeps its own loop-actor field, so a legacy base never feeds the side requester. Verified: core requester test 5 pass; core typecheck clean.
Port MoonshotAI#5541's turn requester decoration onto the fork's loop-actor turn path: CreateLoopOptions.decorateTurnRequester wraps a full per-turn requester once at turn start, while the side requester stays raw. Verified: core requester test 6 pass; core typecheck clean.
Requirement or Bug
LoopService -> core Loop -> core LLM的请求链此前由六个分散的模型/供应商服务、llm-adapter目录以及coreRequester/prepareOperation/decorateRequester私有门面分段拼装,正常 Turn 与 prediction、compaction 等旁路请求走不同的组合路径。本 PR 将配置解析、目录查询、协议元数据与 requester 初始化收口到单一的 App 作用域ProviderCatalogService,让正常 Turn 与旁路请求共用同一个完整 core requester、loop.policy和运行期观测钩子。Bug Reproduction Steps
N/A
Root Cause
N/A
Code Changes
核心思路
参照 refact-237 的 requester 所有权边界:core
Loop直接持有完整 core requester,v2 不再包装第二请求门面。ProviderCatalogService成为唯一的配置与初始化所有者;AgentLoopService.syncRequester()将 Profile 覆盖、模型预算与共享 execution context 合成不可变底座并调用loop.setRequester();工具选择、媒体、结构化恢复与归因请求头注册为loop.policy;请求追踪、用量与遥测由 core 每次运行调用的LoopLlmRunObserver完成。概念
ProviderCatalogServiceConfigurationRecordStore<T>管理记录;旧IModelService/IProviderService/IModelCatalog/IProviderCatalogRuntime/IProviderRequesterFactory/IProtocolAdapterRegistry全部删除loop.requestercreateLoop({ requester })接收完整 core requester;loopService.requester直接暴露 rawloop.requester,旁路调用.with({ model, content, attributes, policy }).generate()mergeLlmPoliciespartialRequester.with()通过它按序拼接resolvers/recoveries/retryables并合并retry,不再覆盖底座策略LoopLlmRunObserverstart(request)生成按请求隔离的LoopLlmRunObservation,替代decorateTurnRequester与AsyncLocalStorageLlmRequest.attributeskind/turnId/step/modelAlias/logFields/promptCacheProbe,并填充llm.requested预留字段结构图
flowchart TD Config[Config / Profile / models.dev] --> Catalog[ProviderCatalogService<br/>App 作用域唯一目录与初始化] Catalog -->|createRequester| Sync[AgentLoopService.syncRequester<br/>合成 Profile、预算与共享 execution] Sync -->|setRequester| Loop[core Loop] Policies[Agent 策略<br/>ToolSelect / 媒体 / 结构 / 归因请求头 / 恢复] -->|注册| Policy[loop.policy] Loop --> Turn[正常 Turn<br/>Turn 开始时捕获 requester] Loop --> Side[旁路请求<br/>prediction / compaction<br/>loop.requester.with...] Turn --> Core[core runLlmRequest<br/>mergeLlmPolicies + LoopLlmRunObserver] Side --> Core Policy --> Core Core --> Obs[AgentLoopRequestObserver<br/>requestId / step timing / usage / telemetry]正常 Turn 与旁路请求最终都进入同一个 core 执行管线,区别只在输入维度与
attributes,不再有 v2 侧的装饰器分叉。关键决策
ProviderCatalogService,配置 CRUD 使用显式 record/config 命名loop.policy,观测实现 coreLoopLlmRunObserverdecorateRequester/operationRequester/AgentRequesterBinderloopService.requester.with(...)实时读取最新底座prepareOperation准备期冻结快照loop.requester契约;正常 Turn 仍由 core 在 Turn 开始时捕获 requestermodelService/providerService/modelResolver映射到同一ProviderCatalogService请求路径变化
阅读指南
packages/agent-core-v2/src/provider-catalog/providerCatalogService.ts与configuration-store.ts:看统一后的目录服务边界、配置 CRUD 与createRequester初始化。packages/agent-core-v2/src/agent/loop/loopService.ts:看syncRequester()/bindRequester()如何把 Profile、预算、策略与观测接到 coreLoop。packages/core/src/loop/requester.ts、request.ts、turn/create-turn.ts与packages/core/src/llm/policy/policy.ts:看 core 侧loop.requester、mergeLlmPolicies与LoopLlmRunObserver。packages/agent-core-v2/src/agent/loop/requestObservation.ts、mediaPolicy.ts、requestMetadata.ts:看每次请求的观测生命周期、媒体策略与归因请求头。packages/klient/src/transports/memory/dispatcher.ts:看既有 RPC 路由如何映射到统一目录服务。其余改动主要是
llm-adapter到provider-catalog/session/tokenCounting/wire的模块归位、各消费方 DI 接线更新、测试迁移与中英文llm.md同步,可略读。Behavior Changes and Affected Users
coreRequester私有门面与decorateTurnRequester组装loop.requester+loop.policy+LoopLlmRunObserverprepareOperation准备期冻结模型、systemPrompt、paramsloop.requester.with(...)实时解析最新配置(config-state.test.ts同步更新)loop.policy.asPolicy()覆盖底座 recoveries/resolverspartialRequester.with()经mergeLlmPolicies追加合并策略列表IModelService/IProviderService/IModelCatalog/IProviderCatalogRuntime/IProviderRequesterFactory/IProtocolAdapterRegistry六个标识IProviderCatalogService(getDefaultModelId等显式命名)IProviderCatalogServicehuman/provider-catalog维护独立 ping/requester 组合与失败标记activeTurnRequestMetadataTracker.readybyModel记账保持冻结模型mediaPolicy与requestObservation.start仍读取最新currentBinding(发往上游的模型仍冻结在旧模型,但第 2 步图片会按新模型降级、用量记到新模型)旧路径功能清单核对
KIMI_MODEL_MAX_COMPLETION_TOKENS硬上限与 opt-out:保留在共用的completion-budget.ts/resolveMaxOutputTokens()。KIMI_MODEL_*全局请求覆盖(如KIMI_MODEL_TEMPERATURE)、KIMI_CODE_INFINITE_RETRY:保留在requestConfigSnapshot()/bindRequester()。execution/ recovery memory 与 Loop reset 清理:保留,requesterExecution由AgentLoopService持有并在 reset 时清空。loop.policy。requestMetadata的 provider 发送):由request.attributes.modelAlias判定,保持原行为。observer.start并按LlmRequest弱引用隔离,去掉AsyncLocalStorage与 monkey-patch。删测说明
test/llm-adapter/**(10 个文件):随模块归位迁移至test/provider-catalog/**与test/session/tokenCounting/usage-tokens.test.ts,原有目录、鉴权、预算、协议与错误契约由对应新文件继续覆盖;protocolAdapterRegistry.test.ts/modelService.test.ts/providerService.test.ts由providerCatalogService*.test.ts覆盖统一后的服务。test/human/provider-catalog.test.ts中 5 个独立 ping 用例:因独立 ping/requester 路径删除且无生产消费者而移除;目录刷新与双源合并契约保留。test/agent/profile/config-state.test.ts:原「operation 准备期冻结快照」用例按 237loop.requester实时解析契约改写。验证结果
pnpm lint(lint-pool 对86e5769a运行,含check:duplication对7f717170零新增重复):全部通过。tsc --noEmit:core、agent-core-v2、kap-server、klient、node-sdk、acp-server、product、apps/kimi-code全部通过。@moonshot-ai/core全量 38 文件 / 408 例通过;agent-core-v2受影响范围 60 文件 / 1653 例通过;klientmemory/IPC 64 例、node-sdk9 例、CLIv2-run-print52 例、viscontext-projector58 例通过。kap-server受影响 8 文件 378 例中 377 例通过,sessions.test.ts的 minidb 启动读取用例在并行负载下超时,单独复跑通过(既有 flake)。agent-core-v2/klient与真实供应商 V01 请求链未验证;custom-e2e/loop-requester-convergence暴露的回合中切换配置归因/媒体问题正在独立跟进。Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.