Skip to content

refactor(agent-core-v2): decouple tool disclosure from execution - #4538

Merged
sailist merged 13 commits into
mainfrom
refact-313-10-28-llm-loop-requester
Oct 30, 2026
Merged

sailist merged 13 commits into
mainfrom
refact-313-10-28-llm-loop-requester

Conversation

@sailist

@sailist sailist commented Oct 30, 2026

Copy link
Copy Markdown
Collaborator

Requirement or Bug

统一 Agent LLM 请求所有权,删除平行的 requester / projector Service,同时保持 turn、compaction、media 和 klient direct-generate 的既有调用契约。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

 Agent 请求链路
- ModelCatalog、AgentLLMRequesterService、AgentContextProjectorService 多层包装
+ LoopService 唯一持有 core LlmRequester
+ ToolSelect → MediaTool → Structure → Media Resolver
+ structure / media recovery ledger

 动态工具加载
- pendingLoaded 与 current model enabled 门禁
+ loop.remind 独立队列,loaded 仅从 history 推导
+ 不支持动态加载的模型自动降级为普通 tools[]

 媒体、恢复与诊断
- Loop 手工媒体投影、即时上传和跨 attempt 的通用 traceId
+ MediaService put/get 与 kimi-file 引用,policy 驱动上传和恢复
+ protocol diagnoseError 与统一 requestId
+ response usage 驱动的 cache_hit_rate

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Agent requester 所有权 ModelRequester、AgentLLMRequesterService、Projector Service 分层持有请求能力 LoopService 唯一长期持有 core requester,其他 Service 经 Loop 门面获取请求能力 agent-core-v2 内部模块;klient direct-generate 公开输入、事件形状与顺序不变 内部旧 Service 不提供兼容层;typecheck、build、klient memory / IPC 与真实 turn 验证
动态工具加载与执行 pendingLoaded 暂存 schema,执行时按 current model 的 enabled 拒绝 select_tools 或未加载工具 SelectTools 经 loop.remind 写 schema,执行不再读取模型门禁;不支持动态加载的模型使用普通 tools[] 开启 tool-select 的用户、turn 中切换模型或配置自定义模型的用户 不支持动态加载时自动展开 deferred tools;select_tools 94/94、远程相关聚焦 276/276,含 mid-turn alias 切换 E2E
媒体生成与上传 ReadMediaFile 执行时按模型能力拒绝并立即上传 执行时 put 并生成 kimi-file,后续请求由 Media Resolver 决定 file-id、base64 或能力提示;不支持媒体的 calls/results 被隐藏 使用图片、视频、MCP 媒体工具的用户 保留 inline base64、上传认证错误和媒体恢复;media、read-media、klient memory / IPC 聚焦测试通过
错误诊断 通用 traceId 可跨 attempt 保存并向外传递 当前 attempt 由 protocol diagnoseError 生成诊断;成功响应与 telemetry 使用 requestId api_error、请求日志及遥测消费方 不再提供通用 traceId;保留 provider requestId;诊断、取消和错误分类聚焦测试通过
缓存诊断 lastTurnRequest 保存快照并比较 history / tools / systemPrompt 前缀 full compaction 与 fork 只根据本次 response usage 计算 cache_hit_rate;缺 usage 或总输入为 0 时未知 prompt_cache_probe 看板与诊断消费者 删除旧前缀比较及 parent 基线字段;usage、compaction、fork 聚焦测试通过
内部状态 toolSelect.pendingLoaded 与媒体恢复快照用于 inspect pendingLoaded 删除,媒体恢复使用 recovery ledger 仅内部 inspect / replay 工具;无公开迁移需求 state manifest 已更新,恢复、undo、compaction 测试通过

公开 klient direct-generate 输入、事件形状和顺序保持不变;除表内明确调整外,既有 wire 事件名称与持久化行为未作额外变更。

验证:agent-core-v2、klient、product typecheck,agent-core build、comment-free、完整 lint(0 errors)通过;本地 select_tools 94/94,远程聚焦 276/276。远程全量 17877 passed / 11 failed / 26 skipped,修正后失败文件复跑剩 8 个既有失败(config 1、Loop 快照 3、plan 快照 2、tool 快照 1、已知子代理中断 1),requester、stateManifest 与 session-import 均恢复通过。lint:imports 仍只有 main 基线已有的 human/agent/origin.ts 违规。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (本 PR 为上述架构要求的直接实现,无关联 issue).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default has an escape hatch or was explicitly approved in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset(任务作者已确认不写).
  • 已同步更新中英文 LLM 文档。

@changeset-bot

changeset-bot Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 84c8adf

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-30T09:32:01.896189Z 84c8adf New commits
ℹ️ 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: 312444662e

ℹ️ 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".

durationMs: z.number().optional(),
stopReason: z.string().optional(),
traceId: z.string().optional(),
requestId: z.string().optional(),

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 the legacy traceId field on turn-ended events

When replaying a session written by the previous release, durable turn.ended records contain traceId, while this schema now accepts and emits only requestId; the updated survey recovery consequently drops the identifier, and existing Klient/SDK consumers reading traceId also receive no value despite the PR claiming public event shapes remain unchanged. Emit both fields during the compatibility window and read requestId with a traceId fallback for persisted records.

AGENTS.md reference: AGENTS.md:L111-L113

Useful? React with 👍 / 👎.

Comment thread todo.md
@@ -0,0 +1,264 @@
# AgentLoopRequester 职责清单

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 Remove the committed requester planning notes

Delete todo.md from the commit: it is a root-level work-in-progress responsibility checklist containing discussion conclusions, accepted exceptions, and validation notes rather than maintained product documentation. Keeping this exploratory artifact makes stale implementation notes appear authoritative and directly violates the repository rule against staging agent working notes or other throwaway scratch files.

AGENTS.md reference: AGENTS.md:L94-L97

Useful? React with 👍 / 👎.

const alreadyDegraded = appliedRecoveries.some(
(recovery) => recovery.strategy === MEDIA_RECOVERY_ID && recovery.action === 'degraded',
);
if (count === 0 && alreadyDegraded) return undefined;

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 Skip media recoveries that cannot rewrite the request

When a request-too-large response occurs with no media, or with at most the two media parts retained by degradation, this condition returns a degraded proposal whose rewrite is undefined; proposeFirst accepts it, so the requester resends the identical request, and stripEntry repeats the same no-op behavior when there is no media. This adds up to two guaranteed duplicate provider calls before the real error surfaces and delays actual stripping for requests with one or two media parts, whereas the old path skipped recoveries that could not change the projection. Return undefined whenever the recovery has nothing to rewrite.

AGENTS.md reference: AGENTS.md:L127-L129

Useful? React with 👍 / 👎.

Comment on lines +61 to +63
const uploaded = await files.upload(
{ ...input, kind: 'image' },
{ endpoint: await resolveEndpoint(contentsOf(request).endpoint), signal: signal ?? new AbortController().signal },

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 no-credential media upload fallbacks

When a Kimi-compatible model has no API key—for example an unauthenticated local proxy that accepts inline images—this new path still exposes an uploader because the endpoint advertises file support, then calls the OpenAI file client with its placeholder Bearer unused credential. If that file endpoint returns 401, the media resolver treats it as a terminal authentication error instead of falling back to inline image data or a video path; the previous KimiFiles implementation failed locally when the key was absent, which allowed those fallbacks to run. Treat an upload with no usable credential as unsupported before making the remote call so no-key sessions retain the old media behavior.

AGENTS.md reference: AGENTS.md:L127-L129

Useful? React with 👍 / 👎.

- replace model requester services with core requester initialization
- move media degradation into core recovery and simplify loop projection
- update client boundaries, tests, documentation, and the task plan
- run normal projection through a structure resolver
- recover structural rejections with a strict request rewrite
- keep media recovery composable without persisting strict repairs
- build default tools and shape history in a tool-select resolver
- evaluate dynamic tool support from each request's effective model
- record resolved tools and preserve recovery composition
- add content-addressed put/get and kimi-file media production
- resolve and upload media in the llm policy pipeline
- defer provider uploads and preserve recovery and cancellation behavior
- register ReadMediaFile independently of model capabilities and store references on execution
- hide unsupported media tool calls and results, then resolve references during requests
- preserve legacy image-format recovery and update focused coverage
- record implemented and accepted media behaviors
- separate undecided and unreviewed alignment items
- simplify compaction cache diagnostics using response usage
- restore provider error classification and abort-safe media metadata
- refresh inherited media recovery display paths
- add optional diagnoseError and failed-outcome diagnostics
- use requestId across successful responses and error telemetry
- update requester tests, documentation, and manifests
- replace pending tool schema state with loop reminders
- strip dynamic tool context for models without dynamic loading
- remove execution-time model gates and align tests and docs
- initialize tool disclosure once per agent session and persist runtime changes
- project initial and runtime tools according to model capabilities
- update wire renderers, manifests, and focused coverage
@sailist
sailist force-pushed the refact-313-10-28-llm-loop-requester branch from 3124446 to 25aa425 Compare October 30, 2026 07:03
@pkg-pr-new

pkg-pr-new Bot commented Oct 30, 2026 •

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

commit: 84c8adf

@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: 25aa425b77

ℹ️ 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 299 to +300
args.full_resolution === true &&
stat.size > this.inlineImageByteBudget
stat.size > imageDeliveryLimits.readByteBudget

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 Restore the full-resolution image budget

For default-configured ReadMediaFile users requesting full_resolution: true, this now applies the 256 KiB compression target as a hard limit. The parent instead allowed the provider-specific inline limit—3.75 MiB generally and 5 MiB for Kimi—so images between those thresholds previously retained native resolution but now return an error unless users override image.readByteBudget. Keep the provider limit, or introduce a separate full-resolution limit, rather than reusing the normal compressed-read budget.

AGENTS.md reference: AGENTS.md:L111-L113

Useful? React with 👍 / 👎.

Comment on lines +411 to +414
const reference = await this.attachmentStore.put({
bytes: mediaBytes,
mimeType: mediaMimeType,
filename: safePath.split(/[\\/]/).at(-1) ?? safePath,

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 conversion guidance for unsupported image formats

When an image-capable non-Kimi model reads a provider-unsupported format such as HEIC, this now stores the file and reports a successful media result without validating the selected provider. During the next request, resolveImageUncached rejects that MIME and substitutes only a local <image path> tag, so the model receives no image pixels and none of the conversion command that the previous implementation returned as an error. Validate the provider MIME before reporting tool success, or carry the conversion guidance through the resolver fallback.

AGENTS.md reference: AGENTS.md:L127-L129

Useful? React with 👍 / 👎.

@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: 84c8adfe98

ℹ️ 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 +316 to +318
private defaultToolsForDisclosure(disclosure: boolean): readonly Tool[] {
const entries = disclosure ? this.capableTools() : this.initialTools();
return this.shapeToolsForDisclosure(entries, disclosure).map((tool) => ({

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 Project live tools for non-disclosure models

When an MCP server reconnects or a plugin adds/removes a tool after the first request, and the active model lacks dynamically_loaded_tools, this branch always projects initialTools() rather than the current registry. Consequently, newly available tools are omitted while removed tools remain advertised; before this refactor, shapeTools() used the live registry even when disclosure was disabled. This contradicts the stated fallback to ordinary tools[] for such models, so use the reconciled current tool set when disclosure is off.

AGENTS.md reference: AGENTS.md:L127-L129

Useful? React with 👍 / 👎.

Comment on lines +473 to +474
const keep = isMcpToolName(tool.name)
? this.toolPolicy.isToolActive(tool.name, 'mcp')

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 Drop stale MCP schemas after schema changes

When an MCP server reconnects and re-registers a same-name tool with changed parameters or description, collectLoadedDynamicTools() invalidates the old version, but this MCP-specific branch retains its historical schema solely because the name remains active. The next request therefore still advertises the stale definition even though load() reports the current version as not loaded, and reselection can leave both definitions in history; apply the signature check when the MCP tool is currently registered, reserving name-only retention for disconnected servers.

AGENTS.md reference: AGENTS.md:L127-L129

Useful? React with 👍 / 👎.

@sailist
sailist merged commit d37f9cc into main Oct 30, 2026
16 checks passed
@sailist
sailist deleted the refact-313-10-28-llm-loop-requester branch October 30, 2026 09:32
wbxl2000 added a commit that referenced this pull request Oct 30, 2026
Stops before #4538 so the code-app branch can pin a commit that has both
this change and the server code code-app main runs on, without the
tool-select API change that desktop has not adapted to yet.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 3, 2026
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 4, 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