Skip to content

refactor(llm): legalize deferred tools in the resolver - #5237

Merged
sailist merged 1 commit into
mainfrom
loop-421-stack/04-legalize-deferred-tools
Nov 23, 2026
Merged

sailist merged 1 commit into
mainfrom
loop-421-stack/04-legalize-deferred-tools

Conversation

@sailist

@sailist sailist commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

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-select experimental flag: deferred-tool disclosure is now gated solely by the model's dynamically_loaded_tools and tool_use capabilities, 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_tools and 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 separate dynamicTools branch for main Loop and side requests. This split ownership made legalization depend on the request path and allowed historical schemas to be copied back into profile.tools.

The new request-preview path added in #5058 also called the older four-argument requestTools interface, 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

  • Add legalize-tools after model legalization: retain deferred metadata 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.
  • Merge protocol capabilities once at the encode-pipeline entry and convert every declaration retained by the resolver/legalization stages.
  • For dynamic loading, remove deferred entries in the ToolSelect resolver, rebuild the initial tool-name snapshot at the start of projected messages, and retain runtime added/removed deltas.
  • For non-dynamic loading, remove select_tools and dynamic system schemas and strip deferred metadata in the ToolSelect resolver without copying those schemas into the top-level tools or rewriting the frozen baseline.
  • Remove the dynamic / dynamicTools branches so main Loop and side requests use the same resolver and capability shaping.
  • Add shapeToolSelectRequest() to compute deferred entries, resolved tools, and projected messages in one place; use it from both the main resolver and previewRequestContent().
  • Keep the Loop baseline frozen: selected schemas are delivered by 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.
  • Hash the full request tool list (including deferred tools) in request observability, and document the resolver/legalization timing on the LLM run events.
  • Remove the tool-select experimental 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.
  • Migrate the mid-loop active-tool verification test to the shared testkit (testkitAgentFixtures + model.script), including the compaction-lane scripting.
  • Assert desktop browser tool disclosure in the request view (via the resolver's production functions 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.
  • Update English and Chinese LLM/MCP documentation and protocol/ToolSelect/preview regression coverage.

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, and packages/agent-core-v2/src/agent/loop/loopService.ts.

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Dynamic deferred declarations Deferred entries reached the encoder and were filtered there The ToolSelect resolver removes them and announces their names; select_tools supplies schemas through reminders Dynamic-loading models, deferred MCP/user tools No alternate mode; use resolver-driven disclosure
Non-dynamic deferred declarations Deferred tools could be dropped during conversion The ToolSelect resolver strips deferred metadata and keeps initial deferred tools as ordinary declarations; core legalization remains the fallback for other request entry points Models without dynamic loading No alternate mode; this restores direct use
Non-dynamic selected schemas Historical system schemas could be merged into profile.tools System schemas and select_tools are removed without promotion into the top-level list Model switches and side requests Start a dynamic-capable session when on-demand loading is required
Request paths Main Loop used a dynamic-only branch while side requests used separate prefiltering All requests use the same ToolSelect resolver Main Loop, compaction, cache probes, and other side requests No request-type flag remains
Request previews Preview used the older four-argument ToolSelect interface and did not share all resolver shaping Preview returns the unresolved system prompt, baseline tools, and stored messages Context usage views and session context inspection routes No alternate preview path; the projected view remains what the model receives
Context route items Items showed the shaped view: tool results adjacent to their calls, synthesized placeholder results, decorated tool texts Items show the raw stored messages and the baseline tools without deferred entries API consumers reading /context/items The model-facing shaping still happens in the projection layer; the route now exposes storage
Mid-loop active-tool changes in side requests Side requests intersected the frozen baseline with the current active-tool overlay Side requests retain the frozen baseline, preserving request-prefix cache alignment; execution policy still vetoes disabled tools Full compaction, prompt prediction, Tower/userTool active-tool overlays No alternate mode; execution policy remains the permission boundary
tool-select experimental flag KIMI_CODE_EXPERIMENTAL_TOOL_SELECT or [experimental] tool-select forced disclosure on or off The flag, env var, and config key are removed; disclosure follows the model's dynamically_loaded_tools + tool_use capabilities Users who forced the feature on for models without declared capabilities Declare dynamically_loaded_tools in the model's capabilities in config.toml
Desktop embedded server env Forced KIMI_CODE_EXPERIMENTAL_TOOL_SELECT=1 for the embedded server The environment is passed through unchanged Desktop users on models without dynamic loading Same capability declaration as above
Request observability toolsHash Excluded tools marked deferred: true Covers the full request tool list Hash-based request comparison in observability None
Runtime userTool unregister Silent unless the experimental flag was on Emits a persisted <tools_removed> delta announcement for dynamic-loading models Sessions with dynamic-loading models that unregister user tools mid-loop None
Duplicate declarations Conversion filtered deferred tools before producing native declarations Top-level declarations win, older duplicates emit aggregated notices and warnings Tools declared both in profiles and system messages Resolver-level deduplication can still run earlier
Initial and runtime announcements Initial snapshots could be persisted independently of the resolver view Initial snapshots are rebuilt per request; runtime deltas remain persisted; an empty initial deferred set stays silent Tool discovery, policy changes, compaction/restoration No migration; runtime deltas are retained
Execution permission Dynamic disclosure was not an execution permission gate Unchanged: disclosure still controls request view, not tool execution permission Direct deferred-tool execution and validation No behavior change

Validation

  • Latest head: 13 focused test files (ToolSelect service/e2e, core Loop, dynamic active tools, full compaction, LLM requester, tool contract, KAP meta/context, desktop main) — 563/566 passed. The 3 failures are subagent-deadline cases that also time out locally on the loop-refact base (macOS-only; green in refactor(core): run loop turns on an independent state machine #5211's CI).
  • Typecheck: agent-core-v2, core, kap-server, migration-legacy, and desktop (including renderer) all pass.
  • Lint: comments, oxlint, import boundaries, ratchet, instructions, and test-doubles pass locally with the task's Git root. The guards (jsPlugins) and quarantine checks report only pre-existing local environment diffs; this PR changes no oxlint config or baselines.
  • The mid-loop active-tool verification test was migrated to the testkit and passes 2/2, covering frozen baselines for turn and operation requests plus compaction-style prefix alignment.
  • Earlier rounds: 9 focused protocol/ToolSelect/Loop requester/preview files passed 204/204; remote m0-dev run of ToolSelect/e2e/Loop/active-tool files passed 131/131.

Checklist

@changeset-bot

changeset-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 59cea24

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 changesets to release 2 packages
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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 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-23T05:40:11.140223Z 59cea24 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.

@pkg-pr-new

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

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

commit: 59cea24

@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: 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".

Comment on lines 109 to +110
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;

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 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.

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

@7Sageer 7Sageer mentioned this pull request Nov 23, 2026
6 tasks done

@7Sageer 7Sageer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

能力门控的统一方向符合目标,发布信息与真实请求视图还有两处需要补齐。deferred 参数校验的组合缺口已归到 #5234,因为该校验由前一 PR 引入。

---

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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 ?? [],
};
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] PR 的 Bug Reproduction Steps 和 Code Changes 仍声称 preview 会移除 deferred、保留初始公告并与下一 provider 请求一致,最终实现及 changeset 已经改为 raw baseline 视图。请同步正文,明确 context routes 的展示契约也已变化,避免 SDK/API 使用者按旧预览语义接入。

7Sageer
7Sageer previously approved these changes Nov 23, 2026
@sailist
sailist changed the base branch from loop-421-stack/03-turn-state-machine to main November 23, 2026 04:38
@sailist
sailist dismissed 7Sageer’s stale review November 23, 2026 04:38

The base branch was changed.

@sailist
sailist force-pushed the loop-421-stack/04-legalize-deferred-tools branch from ba3ff00 to aff4491 Compare November 23, 2026 04:49
@sailist
sailist changed the base branch from main to loop-421-stack/03-turn-state-machine November 23, 2026 04:49
@chatgpt-codex-connector

Copy link
Copy Markdown

💡 Codex Review


P1 Badge Preserve released intake when recording notifications

When reconcileTasks() records a restored background-task completion while a turn is active after another prompt has already been queued, submit() has released intake, but this assignment flips held back to true. After the active turn ends, the scheduler therefore leaves both the queued prompt and notification parked indefinitely until another user action releases intake; recordNotification should avoid waking an otherwise-held loop without re-holding one that is already released.

AGENTS.md reference: AGENTS.md:L111-L115

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

Base automatically changed from loop-421-stack/03-turn-state-machine to main November 23, 2026 05:23
* 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.
@7Sageer
7Sageer force-pushed the loop-421-stack/04-legalize-deferred-tools branch from aff4491 to 59cea24 Compare November 23, 2026 05:24

@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: 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 ?? [];

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

@sailist
sailist merged commit 253212d into main Nov 23, 2026
25 checks passed
@sailist
sailist deleted the loop-421-stack/04-legalize-deferred-tools branch November 23, 2026 05:43
wbxl2000 added a commit that referenced this pull request Nov 25, 2026
)

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.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
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.
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.

3 participants