Skip to content

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

Closed
sailist wants to merge 4 commits into
mainfrom
refact-393-11-18-deferred-tool-resolver
Closed

sailist wants to merge 4 commits into
mainfrom
refact-393-11-18-deferred-tool-resolver

Conversation

@sailist

@sailist sailist commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

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 moves deferred handling into the ToolSelect resolver and the LLM legalization boundary, with the same request-view rules for every request path.

Bug Reproduction Steps

For dynamic-loading models, register deferred tools and verify that they are removed from the 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.

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 fix centralizes capability-specific disclosure in the resolver and keeps only metadata legalization and duplicate handling in the encoder; it is not a compatibility workaround.

Code Changes

  • Add legalize-tools after model legalization: remove deferred metadata for models without dynamic loading, 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 without copying those schemas into the top-level tools.
  • Remove the dynamic / dynamicTools branches so main Loop and side requests use the same resolver and capability shaping.
  • Keep the Loop baseline frozen: selected schemas are still delivered by loop.remind, and runtime changes are disclosed through reminders rather than by rewriting the initial tool list.
  • Update English and Chinese LLM/MCP documentation and protocol/ToolSelect regression coverage.

Start with packages/core/src/llm/protocol/rules/tools.ts, packages/agent-core-v2/src/agent/loop/toolSelectPolicy.ts, and packages/agent-core-v2/src/agent/toolSelect/toolSelectService.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 the resolver-driven disclosure
Non-dynamic deferred declarations Deferred tools could be dropped during conversion Initial deferred tools remain as ordinary declarations after deferred metadata is stripped 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
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 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

After rebasing onto the merged engineering PR:

  • 9 focused protocol, ToolSelect, and Loop requester test files: 203/203 passed.
  • packages/core and packages/agent-core-v2 typecheck passed.
  • Standard pnpm lint passed, including comment, oxlint, import-boundary, guard, ratchet, and instruction checks.

Checklist

  • I have read the CONTRIBUTING document.
  • The requirement, reproduction coverage, and scope are described above; no external issue is linked.
  • I have added and updated tests for dynamic and non-dynamic disclosure, model switches, duplicate declarations, and request-path consistency.
  • The behavior-change table above is complete; no changeset is included for this split PR, consistent with the original task's delivery decision.
  • Changeset handling is explicitly stated above.
  • English and Chinese LLM/MCP documentation is updated.

@changeset-bot

changeset-bot Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 7f31628

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 Nov 19, 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-19T13:59:57.067570Z 7f31628 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: 39b6487952

ℹ️ 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 242 to +243
const baseline = options.tools ?? this.loop.state.profile.tools;
const visible = options.tools === undefined && baseline !== undefined
? this.operationTools(baseline, config.resolved.model.capability)
: baseline;
const tools = await this.prepareTools(signal, config.resolved.model.capability, visible);
const tools = await this.prepareTools(signal, config.resolved.model.capability, baseline);

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 Restore policy filtering for side-request baselines

When the active tool policy or profile allowlist changes after the Loop baseline is captured, prompt prediction and full compaction call prepareOperation without explicit tools, so this now passes the frozen baseline through unchanged. The removed operationTools path filtered that baseline against the current defaultTools, while the replacement resolver only removes deferred tools or select_tools and does not filter ordinary inactive tools. Consequently, newly disallowed tools are disclosed again in these side requests and can make prediction or compaction return an unusable tool call; reapply the current-policy filter before constructing the operation requester.

AGENTS.md reference: AGENTS.md:L206-L208

Useful? React with 👍 / 👎.

Comment on lines +160 to +164
const tools = base ?? [];
const drop = disclosure
? (tool: Tool) => tool.deferred === true
: (tool: Tool) => tool.name === SELECT_TOOLS_TOOL_NAME;
return tools.some(drop) ? tools.filter((tool) => !drop(tool)) : tools;

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 Populate non-dynamic requests after deferred MCP discovery

When deferred MCP tools finish asynchronous discovery after the Loop has frozen its initial tool baseline, prepareForRequest updates the ToolSelect catalog but this method only filters the stale base array and never adds those newly discovered declarations. A session starting directly with a model that lacks dynamically_loaded_tools therefore still sends no schema for those deferred MCP tools, even though this change is intended to retain them as ordinary declarations; legalize-tools can strip metadata only from tools that are already present. Merge the reconciled initial deferred declarations into the non-disclosure request view before returning it.

AGENTS.md reference: AGENTS.md:L206-L208

Useful? React with 👍 / 👎.

- 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
- 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
- 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
- reuse deferred shaping in the resolver and request preview
- preserve initial tool announcements in request previews
- cover preview parity with deferred tools
@sailist
sailist force-pushed the refact-393-11-18-deferred-tool-resolver branch from 39b6487 to 7f31628 Compare November 19, 2026 13:56
@pkg-pr-new

pkg-pr-new Bot commented Nov 19, 2026

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

commit: 7f31628

@sailist

sailist commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #5142.

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.

1 participant