Skip to content

refactor(agent-core-v2): converge loop llm requester and unify provider catalog - #5541

Merged
sailist merged 24 commits into
mainfrom
refact-402-11-19-loop-llm-requester-convergence
Nov 26, 2026
Merged

sailist merged 24 commits into
mainfrom
refact-402-11-19-loop-llm-requester-convergence

Conversation

@sailist

@sailist sailist commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

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 完成。

概念

概念 回答什么问题 本 PR 之后
ProviderCatalogService 谁负责模型/供应商配置 CRUD、目录查询与 requester 初始化 唯一 App 作用域服务,内部用共享 ConfigurationRecordStore<T> 管理记录;旧 IModelService / IProviderService / IModelCatalog / IProviderCatalogRuntime / IProviderRequesterFactory / IProtocolAdapterRegistry 全部删除
loop.requester 正常 Turn 与旁路请求如何共用同一请求底座 createLoop({ requester }) 接收完整 core requester;loopService.requester 直接暴露 raw loop.requester,旁路调用 .with({ model, content, attributes, policy }).generate()
mergeLlmPolicies 派生 requester 时如何叠加策略 partialRequester.with() 通过它按序拼接 resolvers / recoveries / retryables 并合并 retry,不再覆盖底座策略
LoopLlmRunObserver 观测如何同时覆盖正常 Turn 与旁路请求 core 在每次请求开始时调用 start(request) 生成按请求隔离的 LoopLlmRunObservation,替代 decorateTurnRequester 与 AsyncLocalStorage
LlmRequest.attributes 请求归因信息如何随请求传递 携带 kind / 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]
Loading

正常 Turn 与旁路请求最终都进入同一个 core 执行管线,区别只在输入维度与 attributes,不再有 v2 侧的装饰器分叉。

关键决策

决策 选择 没选 理由
目录与初始化归属 单一 App 作用域 ProviderCatalogService,配置 CRUD 使用显式 record/config 命名 保留六个旧 Service 的 alias 或私有 delegate 消除双份配置解析与协议选路逻辑,目录 DTO 与 record API 不再互相冲突
策略与观测接入 策略注册进 loop.policy,观测实现 core LoopLlmRunObserver 保留 decorateRequester / operationRequester / AgentRequesterBinder 旁路请求天然获得与正常 Turn 相同的策略与观测,避免 monkey-patch 和跨请求闭包共享
旁路请求配置时机 loopService.requester.with(...) 实时读取最新底座 保留 prepareOperation 准备期冻结快照 对齐 refact-237 loop.requester 契约;正常 Turn 仍由 core 在 Turn 开始时捕获 requester
klient 内存传输兼容 memory dispatcher 将 modelService / providerService / modelResolver 映射到同一 ProviderCatalogService 删除旧 RPC 路由或新增第二 Service 保持既有 klient 客户端契约与事件名不变,服务端内部仍只有一份实现

请求路径变化

 AgentLoopService
-  coreRequester / prepareOperation / decorateRequester / AgentRequesterBinder
-    ├─ Turn step → 私有快照 + 装饰器链 → core requester
-    └─ prediction / compaction → prepareOperation 冻结快照 → core requester
+  syncRequester() → ProviderCatalogService.createRequester() → loop.setRequester()
+    ├─ Turn step → core Loop 捕获 requester + loop.policy + llmObserver
+    └─ prediction / compaction → loopService.requester.with(...).generate() + loop.policy + llmObserver

阅读指南

  1. packages/agent-core-v2/src/provider-catalog/providerCatalogService.ts 与 configuration-store.ts:看统一后的目录服务边界、配置 CRUD 与 createRequester 初始化。
  2. packages/agent-core-v2/src/agent/loop/loopService.ts:看 syncRequester() / bindRequester() 如何把 Profile、预算、策略与观测接到 core Loop。
  3. packages/core/src/loop/requester.ts、request.ts、turn/create-turn.ts 与 packages/core/src/llm/policy/policy.ts:看 core 侧 loop.requester、mergeLlmPolicies 与 LoopLlmRunObserver。
  4. packages/agent-core-v2/src/agent/loop/requestObservation.ts、mediaPolicy.ts、requestMetadata.ts:看每次请求的观测生命周期、媒体策略与归因请求头。
  5. packages/klient/src/transports/memory/dispatcher.ts:看既有 RPC 路由如何映射到统一目录服务。

其余改动主要是 llm-adapter 到 provider-catalog / session/tokenCounting / wire 的模块归位、各消费方 DI 接线更新、测试迁移与中英文 llm.md 同步,可略读。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
正常 Turn 请求组装与观测 经 coreRequester 私有门面与 decorateTurnRequester 组装 直接使用 core loop.requester + loop.policy + LoopLlmRunObserver TUI、print、Desktop/Web、VS Code、ACP、SDK、KAP 全端 无(内部路径替换,外部契约不变)
旁路请求(prediction / full compaction)的配置读取时机 prepareOperation 准备期冻结模型、systemPrompt、params loop.requester.with(...) 实时解析最新配置(config-state.test.ts 同步更新) 开启 prompt prediction 或触发自动/手动压缩的各端会话 无(对齐 237 契约)
请求策略派生合并 loop.policy.asPolicy() 覆盖底座 recoveries/resolvers partialRequester.with() 经 mergeLlmPolicies 追加合并策略列表 使用共享底座恢复策略的 Turn 与旁路请求 无(修复覆盖隐患)
内部模型/供应商 DI 标识 IModelService / IProviderService / IModelCatalog / IProviderCatalogRuntime / IProviderRequesterFactory / IProtocolAdapterRegistry 六个标识 统一为 IProviderCatalogService(getDefaultModelId 等显式命名) 直接注入旧内部标识的测试与内部扩展代码;KAP REST 与 klient RPC 外部契约不变 改注入 IProviderCatalogService
human 目录独立 ping human/provider-catalog 维护独立 ping/requester 组合与失败标记 删除独立 ping/requester 路径,保留目录刷新与双源模型合并 无生产或公开契约消费者 无
晚挂载请求归因 回放可能覆盖 activeTurn 归因 resolver 等待 RequestMetadataTracker.ready 回合中途挂载/恢复的客户端 无(修复既有竞态)
已知待跟进:回合进行中切换模型/供应商时的策略与用量归因 基线中当前 Turn 后续步骤的媒体能力判断与 byModel 记账保持冻结模型 当前提交中 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 时清空。
  • 凭据恢复、结构化恢复、媒体降级与上传失败重试、ToolSelect 与媒体工具顺序:按原顺序注册进 loop.policy。
  • 请求归因请求头(仅声明 requestMetadata 的 provider 发送):由 request.attributes.modelAlias 判定,保持原行为。
  • PromptCacheGuard:改为包装 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 准备期冻结快照」用例按 237 loop.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 例通过;klient memory/IPC 64 例、node-sdk 9 例、CLI v2-run-print 52 例、vis context-projector 58 例通过。
  • kap-server 受影响 8 文件 378 例中 377 例通过,sessions.test.ts 的 minidb 启动读取用例在并行负载下超时,单独复跑通过(既有 flake)。
  • 未验证:m0-dev 依赖安装超时、Windows 无 pnpm,故远程 Linux/Windows 全量 agent-core-v2 / klient 与真实供应商 V01 请求链未验证;custom-e2e/loop-requester-convergence 暴露的回合中切换配置归因/媒体问题正在独立跟进。

Checklist

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-26T12:48:56.532266Z 2a6c37c PR opened
ℹ️ About Codex in GitHub

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

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

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +225 to +228
this._register(this.config.onDidSectionChange(({ domain }) => {
if (REQUEST_CONFIG_SECTIONS.has(domain)) this.syncRequester();
}));
this._register(this.providerCatalog.onChanged(() => this.syncRequester()));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment on lines +153 to +156
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');

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment on lines +61 to +62
with: ((next: LlmRequestPart | FullLoopLlmRequester) =>
accumulate(mergeFields(part as Fields, contentsOf(next) as Fields) as LlmRequestPart)) as FullLoopLlmRequester['with'],

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment on lines +298 to +301
get requester(): FullLoopLlmRequester {
const loop = this.loop;
if (loop === undefined) throw new BugIndicatingError('Agent loop is not started');
return loop.requester;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment on lines +579 to +582
case 'llm.ended': {
const outcome = event.outcome;
const errorRequestId = outcome.type === 'failed' ? apiRequestId(outcome.error) : undefined;
this.activeRequestId = outcome.requestId ?? errorRequestId ?? this.activeRequestId;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@sailist
sailist force-pushed the refact-402-11-19-loop-llm-requester-convergence branch from 2a6c37c to 54bfafe Compare November 26, 2026 12:51
@changeset-bot

changeset-bot Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 4332337

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/agent-core-v2 Patch

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

@sailist
sailist force-pushed the refact-402-11-19-loop-llm-requester-convergence branch from 54bfafe to f0e81df Compare November 26, 2026 12:58
@pkg-pr-new

pkg-pr-new Bot commented Nov 26, 2026 •

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

commit: 4332337

… 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.
@sailist
sailist merged commit c9ab894 into main Nov 26, 2026
21 checks passed
@sailist
sailist deleted the refact-402-11-19-loop-llm-requester-convergence branch November 26, 2026 14:06
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 26, 2026
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.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 26, 2026
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.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 26, 2026
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.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 26, 2026
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.
@7Sageer 7Sageer mentioned this pull request Nov 27, 2026
6 tasks done
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants