Repository navigation
refactor(llm): legalize deferred tools in the resolver - #5237
Conversation
|
| Name | Type |
|---|---|
| @moonshot-ai/kap-server | Patch |
| @moonshot-ai/agent-core-v2 | Patch |
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
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: ba3ff00734
ℹ️ 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".
| enabled(capabilities: ToolSelectCapabilities | undefined = this.profile.getModelCapabilities()): boolean { | ||
| return ( | ||
| capabilities?.dynamically_loaded_tools === true && | ||
| capabilities.tool_use === true && | ||
| this.featureEnabled() | ||
| ); | ||
| return capabilities?.dynamically_loaded_tools === true && capabilities.tool_use === true; |
There was a problem hiding this comment.
Preserve an opt-out for capability-gated ToolSelect
For official models that automatically declare dynamically_loaded_tools, this now enables progressive disclosure even when a user explicitly configured KIMI_CODE_EXPERIMENTAL_TOOL_SELECT=0 or [experimental] tool-select = false. Because model capabilities can only be added and never removed, these users have no way to recover the former direct-tool behavior; retain a negative override or another explicit escape hatch when removing the experimental gate.
AGENTS.md reference: AGENTS.md:L195-L197
Useful? React with 👍 / 👎.
| --- | ||
|
|
||
| Add `GET /api/v1/sessions/{session_id}/context/summary`, `/context/items`, and `/context/items/{item_id}`, which return the system prompt, tool definitions, and messages of the agent's next model request, built from a read-only preview that applies the same tool selection, media-tool hiding, and projection steps as the real request. | ||
| Add `GET /api/v1/sessions/{session_id}/context/summary`, `/context/items`, and `/context/items/{item_id}`, which return an unresolved read-only snapshot of the agent's system prompt, baseline tool definitions, and raw messages for context inspection and token estimation. |
There was a problem hiding this comment.
Add a changeset entry for activating ToolSelect
This changeset still describes only the context-inspection endpoints, while the same commit turns progressive tool disclosure on by default for capable CLI/desktop models and removes the tool-select environment/config switch. Since release notes are generated from changesets, users upgrading agent-core-v2 will not be told that their model-facing tool list and configuration contract changed; add a concise user-facing entry covering the activation and removed switch.
AGENTS.md reference: AGENTS.md:L169-L170
Useful? React with 👍 / 👎.
| --- | ||
|
|
||
| Add `GET /api/v1/sessions/{session_id}/context/summary`, `/context/items`, and `/context/items/{item_id}`, which return the system prompt, tool definitions, and messages of the agent's next model request, built from a read-only preview that applies the same tool selection, media-tool hiding, and projection steps as the real request. | ||
| Add `GET /api/v1/sessions/{session_id}/context/summary`, `/context/items`, and `/context/items/{item_id}`, which return an unresolved read-only snapshot of the agent's system prompt, baseline tool definitions, and raw messages for context inspection and token estimation. |
There was a problem hiding this comment.
[P1] 此 PR 还会为支持动态加载的官方模型默认启用 progressive disclosure,并删除显式关闭它的 [experimental] tool-select / env 开关;受影响用户只读 capabilities 已自动声明、此前设 false 的人群也无法恢复直接工具列表。当前 changeset 仅描述 context preview,发布记录不会覆盖这个行为变化。请补产品 patch changeset,写明默认启用及开关移除,并在 PR 中记录维护者对无退路变化的确认。
| messages: this.loop?.state.messages ?? this.journal.snapshot().input.messages ?? [], | ||
| }; | ||
| } | ||
|
|
There was a problem hiding this comment.
[P2] PR 的 Bug Reproduction Steps 和 Code Changes 仍声称 preview 会移除 deferred、保留初始公告并与下一 provider 请求一致,最终实现及 changeset 已经改为 raw baseline 视图。请同步正文,明确 context routes 的展示契约也已变化,避免 SDK/API 使用者按旧预览语义接入。
ba3ff00 to
aff4491
Compare
💡 Codex ReviewWhen AGENTS.md reference: AGENTS.md:L111-L115 ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
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". |
* refactor(core): unify llm event stream and harden behavior tests - unify run boundaries, request summaries, delta events, retries, and outcomes - migrate Loop, agent-core-v2, and klient consumers to the unified event vocabulary - add aimock-backed transport coverage and restore historical LLM behavior tests - update the Nix dependency hash and affected snapshots * refactor(llm): legalize deferred tools in the resolver - strip deferred metadata during legalize for models without dynamic loading - stop convert from dropping deferred tools and dedupe declarations with top-level priority - merge protocol capabilities once at the encode pipeline entry - remove deferred tools in the dynamic loop resolver and announce their names first * refactor(llm): unify deferred tool request views - remove dynamic-only request branching from ToolSelect resolution - keep non-dynamic system schemas out of top-level tools - preserve baseline tools for side requests before capability shaping * refactor(llm): share the tool select request view - reuse deferred shaping in the resolver and request preview - preserve initial tool announcements in request previews - cover preview parity with deferred tools * refactor(llm): strip deferred metadata in tool select Remove deferred metadata from non-disclosure ToolSelect request views while preserving the loop baseline. Keep core legalization as the fallback for requests that bypass ToolSelect. * refactor(llm): contain tool disclosure in resolver * refactor(llm): hash the full request tool list - compute toolsHash over every input tool, including deferred ones - note the resolver and legalization timing on the llm run events * refactor(llm): remove the tool select experimental flag - drop the tool-select flag, env var, and [experimental] config entry - gate deferred tool disclosure solely on model capabilities - remove the desktop forced env and update the MCP and env-var docs - cover mid-loop active-tool requests with an empirical loop test * test(desktop): assert browser tool disclosure in the request view The previous assertions called loadableToolsAnnouncement() with no arguments, a calling form no production code uses; the model-facing disclosure is built per request by the ToolSelect resolver. Assert the request view instead: requestTools strips the deferred browser tool from the request tool list, shapeHistory injects the snapshot announcement naming it, and a reminder step after the control switch turns the removal into a <tools_removed> delta.
aff4491 to
59cea24
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 59cea24453
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (names.has(tool.name)) continue; | ||
| tools.push({ ...tool, deferred: undefined }); | ||
| names.add(tool.name); | ||
| const tools = base ?? []; |
There was a problem hiding this comment.
Retain loaded schemas when falling back to non-dynamic models
When the loop starts before MCP discovery, a deferred MCP tool is later loaded on a dynamic-capable model, and the still-connected server is used after switching to a model without dynamic loading, base still omits that tool. This path no longer promotes its loaded schema from history, while shapeUnsupportedDynamicToolContext removes the historical schema message, so the fallback model receives neither tool nor schema and cannot invoke the active tool. Preserve loaded schemas in the fallback request or keep their historical declarations available.
AGENTS.md reference: AGENTS.md:L207-L209
Useful? React with 👍 / 👎.
) The tool-select experimental flag was removed in #5237, but the /experiments telemetry test still used it as its sample flag. Use prompt_prediction, a current flag with no special handling on apply, so the test keeps checking only the reported flag set.
Port the deferred-tool half of upstream 253212d (MoonshotAI#5142 stack); the LLM event-stream half is already the ledger row for MoonshotAI#5130. - core: `convert` keeps every declared tool instead of dropping deferred ones; `runPipeline` applies `withProtocolCapabilities` at the encode entry and `generate.ts` drops its duplicate merge; `legalizeTools` was already ported, so it is unchanged; `llm.started` toolsHash and the persisted llm.tools_snapshot hash every tool, deferred included. - resolver: `requestTools(base, disclosure)` removes deferred entries when disclosing and otherwise removes `select_tools` and strips the `deferred` metadata. The loop request calls it with the baseline when a request carries no profile tools, and `dynamicTools` is removed from the requester contract. - flags: the `tool_select` flag, `KIMI_CODE_EXPERIMENTAL_TOOL_SELECT`, the desktop forced env, the Agent tool gate, the `[experimental]` doc rows and the reference/MCP prose are removed; disclosure is capability-only. The fork's flag defaulted to true, so this is behaviourally neutral for capable models and only drops an explicit opt-out. - `toolSelectPolicy` is ported to upstream's typed `shapeToolSelectRequest`; it stays upstream-dead per test/lint/unreachable-modules.txt, but its test double now uses the real two-argument signature. Fork adaptations: - The step reminder provider keeps supplying the initial loadable-tools announcement; upstream projects that snapshot from the resolver instead. `shapeHistory` still projects it for callers that pass the pre-shaping deferred baseline (request previews and the browser request-view test). - Because the provider is the production source, snapshot announcements that list tools are suppressed when disclosure is off and baseline names are excluded from legacy deltas, so a model that cannot load tools is not told about a catalog it cannot use. The empty-set snapshot is kept: the loop history tests assert it. - The fork-only MCP retrieval shortlist and its announcement are untouched. - kap-server meta tests move to `notify_user`; `subagent_fork` no longer exists here. - Comment gates: no comment added inside agent-core-v2; the response.ts timing comment is allowlisted in .commentignore. Verification (targeted, one suite at a time): - packages/core: 71 pass / 0 fail across test/llm/lifecycle/run.test.ts and the anthropic/openai/openai-responses/google-genai/kimi encode suites. - agent-core-v2 test/agent/toolSelect: 133 pass / 0 fail. - toolSelect.e2e: 11 pass / 1 fail — the inline-tool wire assertion fails at HEAD too, and the file is excluded from the default run by bunfig. - fullCompaction: 130 pass / 0 fail. llmRequester + coreLoopService + dynamicActiveTools + undo: 79 pass / 0 fail. tool.test: 151 pass / 1 fail — the loadable-tools snapshot wrapper case fails at HEAD too. - test/agent/loop + test/session/subagent: 292 pass / 7 fail, exactly the seven failures HEAD reports (four turn.ended.loopEnd snapshots, three 5s subagent timeouts). - kap-server meta + context: 23 pass / 0 fail. desktop vitest (browser, embedded-server, shell-env, ipc register): 109 pass / 1 fail — the browser loadableToolsAnnouncement assertion fails at HEAD too. - typecheck clean: core, agent-core-v2, kap-server, apps/kimi-code. apps/desktop reports one unrelated pre-existing TS2488 in tests/main/browser/browser-aot.test.ts. - bun run lint: 0 errors. check:no-comments, check:locale-keys and check:t-coverage: OK.
Part 4/7 of the loop stack onto
main. Identical diff to #5142, previously reviewed and merged into the loop integration branch. Stacked on #5236; the shown diff contains only this PR's own changes.Requirement or Bug
Deferred-tool behavior was split between protocol conversion and ToolSelect resolution. Models without dynamic loading could lose deferred declarations entirely, while main Loop and side requests could derive different tool views and promote selected system schemas into the top-level tool list.
This PR centralizes deferred handling in the ToolSelect resolver and the LLM legalization boundary, and makes request previews use that same view. It supersedes #5136 with the complete implementation rebased onto current main; the already-merged LLM event-stream work is not repeated here.
The PR also removes the
tool-selectexperimental flag: deferred-tool disclosure is now gated solely by the model'sdynamically_loaded_toolsandtool_usecapabilities, with no env var or config key left to force it.Bug Reproduction Steps
For dynamic-loading models, register deferred tools and verify that they are removed from resolved top-level tools, announced by name, and loaded into system messages through
select_tools.For models without dynamic loading, verify that initial deferred declarations remain callable as ordinary declarations after their metadata is stripped, while
select_toolsand historical dynamic system schemas are removed rather than promoted into the top-level list.For request previews, register a deferred tool and verify that the preview removes it from top-level tools but retains its initial
<tools_added>announcement, with the preview matching the next provider request.Root Cause
convert()used to drop deferred tools during protocol encoding, while the resolver used a separatedynamicToolsbranch for main Loop and side requests. This split ownership made legalization depend on the request path and allowed historical schemas to be copied back intoprofile.tools.The new request-preview path added in #5058 also called the older four-argument
requestToolsinterface, so the unified resolver interface and preview had to be converged rather than only deleting parameters.This is a fundamental ownership fix rather than a compatibility workaround.
Code Changes
legalize-toolsafter model legalization: retaindeferredmetadata cleanup as the boundary fallback for requests that bypass ToolSelect, deduplicate declarations with top-level priority, and emit aggregated notices and warnings for removed duplicates.select_toolsand dynamic system schemas and stripdeferredmetadata in the ToolSelect resolver without copying those schemas into the top-level tools or rewriting the frozen baseline.dynamic/dynamicToolsbranches so main Loop and side requests use the same resolver and capability shaping.shapeToolSelectRequest()to compute deferred entries, resolved tools, and projected messages in one place; use it from both the main resolver andpreviewRequestContent().loop.remind, and runtime changes are disclosed through reminders rather than by rewriting the initial tool list. Execution policy continues to veto disabled tools independently of request disclosure.tool-selectexperimental flag,KIMI_CODE_EXPERIMENTAL_TOOL_SELECT, and[experimental] tool-select; the desktop embedded server no longer force-enables the feature, and the MCP/env-var docs now describe capability-only gating.testkitAgentFixtures+model.script), including the compaction-lane scripting.requestTools/shapeHistory) instead of a service calling form no production code uses; the context route test now pins the raw stored view per the preview contract.Start with
packages/core/src/llm/protocol/rules/tools.ts,packages/agent-core-v2/src/agent/loop/toolSelectPolicy.ts,packages/agent-core-v2/src/agent/toolSelect/toolSelectService.ts, andpackages/agent-core-v2/src/agent/loop/loopService.ts.Behavior Changes and Affected Users
select_toolssupplies schemas through remindersdeferredmetadata and keeps initial deferred tools as ordinary declarations; core legalization remains the fallback for other request entry pointsprofile.toolsselect_toolsare removed without promotion into the top-level listdeferredentries/context/itemstool-selectexperimental flagKIMI_CODE_EXPERIMENTAL_TOOL_SELECTor[experimental] tool-selectforced disclosure on or offdynamically_loaded_tools+tool_usecapabilitiesdynamically_loaded_toolsin the model'scapabilitiesinconfig.tomlKIMI_CODE_EXPERIMENTAL_TOOL_SELECT=1for the embedded serverdeferred: true<tools_removed>delta announcement for dynamic-loading modelsValidation
loop-refactbase (macOS-only; green in refactor(core): run loop turns on an independent state machine #5211's CI).agent-core-v2,core,kap-server,migration-legacy, and desktop (including renderer) all pass.jsPlugins) and quarantine checks report only pre-existing local environment diffs; this PR changes no oxlint config or baselines.Checklist