Skip to content

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

Merged
sailist merged 9 commits into
loop-refactfrom
bug-403-11-19-deferred-tool-resolver
Nov 22, 2026
Merged

sailist merged 9 commits into
loop-refactfrom
bug-403-11-19-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 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.

The base branch is loop-refact (#5211); this PR is stacked on it and the shown diff contains only this PR's own changes.

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 19, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: b2d05e3

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 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-22T02:23:52.769822Z b2d05e3 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 19, 2026 •

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

commit: b2d05e3

@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: b778df8579

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

import { IAgentToolSelectService } from '#/agent/toolSelect/toolSelect';

export function createToolSelectResolver(toolSelect: IAgentToolSelectService, dynamic = false): LlmResolver {
export function shapeToolSelectRequest(

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 changesets for the modified libraries

This commit changes runtime behavior in both @moonshot-ai/core and @moonshot-ai/agent-core-v2, but contains no .changeset entry, so these packages will not be versioned or receive changelog records for the deferred-tool changes. Add patch changesets for both libraries and a CLI product entry because experimental ToolSelect/MCP users can observe the new behavior.

AGENTS.md reference: AGENTS.md:L168-L169

Useful? React with 👍 / 👎.

Comment on lines +14 to +17
if (dynamic || tool.deferred !== true) return tool;
changed = true;
const { deferred: _deferred, ...description } = tool;
return description;

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 Hash deferred tools after legalization

When a caller uses the core requester without the agent ToolSelect resolver and targets a non-dynamic protocol, this pass strips deferred and the encoder now sends the tool, while llmRequestedEvent() still computes toolsHash from the pre-legalized profile after filtering every deferred tool. Requests that differ only by such declarations therefore emit the same toolsHash despite sending different provider payloads; compute the request summary from the legalized tools or make its filtering capability-aware.

Useful? React with 👍 / 👎.

Comment on lines +527 to +528
const deferredNames = new Set(deferred.map((tool) => tool.name));
const initialTools = this.initialToolInfos().filter((info) => deferredNames.has(info.name));

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 Exclude removed deferred tools from rebuilt snapshots

In a dynamic-loading session where an initially deferred MCP tool is removed and its persisted removal announcement is later discarded by compaction, this rebuild uses the frozen initial registry and baseline names, so it announces the removed tool again. The post-compaction reminder cannot reconstruct a removal from the compacted history because the synthetic snapshot was never persisted, leaving the model to repeatedly select a tool that is no longer registered; build the snapshot from the currently loadable set or retain the corresponding removal delta.

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

Useful? React with 👍 / 👎.

Comment on lines 30 to +32
model: {
...request.model,
spec: withProtocolCapabilities(request.model.spec, request.protocol.base),
spec: request.model.spec,

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 inferred capabilities for custom protocol consumers

When a core requester uses a custom Protocol implementation—or a protocol patched with a custom decoder—and the model spec omits explicit capabilities, this change no longer passes the protocol-inferred capabilities to that encoder or decoder. The replacement merge occurs only inside runPipeline, so it covers defineProtocol encoding but cannot affect an independently implemented encode function and is lost again when generate() invokes base.decoder(module, sink) with this original module; preserve the merge at the request boundary as well as the direct pipeline entry.

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

Useful? React with 👍 / 👎.

@sailist
sailist force-pushed the bug-403-11-19-deferred-tool-resolver branch from b778df8 to 4e7d0b2 Compare November 21, 2026 04:43

@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: 4e7d0b2e39

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

const dynamic = module.model.spec.capability?.dynamically_loaded_tools === true;
let changed = false;
const normalize = (tool: ToolDescription): ToolDescription => {
if (dynamic || tool.deferred !== true) return 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 Keep deferred tools out of direct dynamic requests

When a caller uses @moonshot-ai/core directly, declares dynamically_loaded_tools: true, and supplies a top-level tool marked deferred, this branch preserves the declaration and convert() now maps it into the provider payload as an ordinary tool. Without the agent ToolSelect resolver there is no selection announcement or other pass that removes it, so deferred tools become immediately callable; retain the previous omission at this boundary or require an equivalent resolver before encoding.

AGENTS.md reference: AGENTS.md:L207-L209

Useful? React with 👍 / 👎.

Comment on lines +249 to +250
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.

P2 Badge Continue filtering operation tools by active policy

When activeToolNames, disallowedTools, or a session/global disabled-tool list changes after loop initialization, full compaction and prompt prediction call prepareOperation without explicit tools and this now forwards the frozen loop baseline unchanged. The removed operationTools() path filtered that baseline through the current ToolSelect policy; the resolver only removes deferred or select_tools entries, so disabled inline schemas—and disabled deferred names in the projected snapshot—are advertised to these side requests, which can make them return unavailable tool calls instead of a summary or prediction.

AGENTS.md reference: AGENTS.md:L207-L209

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
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.
- compute toolsHash over every input tool, including deferred ones
- note the resolver and legalization timing on the llm run events
@sailist
sailist force-pushed the bug-403-11-19-deferred-tool-resolver branch from 4e7d0b2 to a390b81 Compare November 22, 2026 02:08
@sailist
sailist changed the base branch from main to loop-refact November 22, 2026 02:09
- 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
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.
@sailist
sailist force-pushed the bug-403-11-19-deferred-tool-resolver branch from a390b81 to b2d05e3 Compare November 22, 2026 02:17

@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: b2d05e3b75

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

P2 Badge Preserve the ToolSelect opt-out

For users who set KIMI_CODE_EXPERIMENTAL_TOOL_SELECT=0 or [experimental] tool-select = false while using a dynamic-capable model and deferred MCP tools, this capability-only check now silently enables ToolSelect and removes their previous opt-out. The replacement suggested in the behavior table only helps users enable the feature on custom models; it does not restore ordinary declarations for users who deliberately disabled it. Retain a config/env escape hatch, or obtain the required explicit maintainer sign-off and document the lost behavior in a changeset.

AGENTS.md reference: AGENTS.md:L195-L197

Useful? React with 👍 / 👎.

systemPrompt: this.loop?.state.profile.systemPrompt || this.getSystemPrompt(),
tools: mediaInput ? tools : tools.filter((tool) => tool.name !== READ_MEDIA_FILE_TOOL_NAME),
messages: project(mediaInput ? messages : hideReadMediaFile(messages)),
tools: this.baselineTools(),

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 Keep non-dynamic deferred tools in context previews

When the current model does not support dynamic loading, the resolver strips deferred and sends those baseline tools as ordinary callable definitions, but this raw baseline still carries deferred: true. packages/kap-server/src/routes/context.ts:367 consequently filters the definitions out of /context/summary and /context/items, so API consumers inspecting a non-dynamic session see neither the callable tools nor their token cost even though the provider request contains them. Make the preview or route filtering capability-aware.

Useful? React with 👍 / 👎.

@sailist
sailist merged commit ba093b8 into loop-refact Nov 22, 2026
22 of 23 checks passed
@sailist
sailist deleted the bug-403-11-19-deferred-tool-resolver branch November 22, 2026 02:24
7Sageer pushed a commit that referenced this pull request Nov 23, 2026
* 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.
sailist added a commit that referenced this pull request Nov 23, 2026
* 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 pushed a commit that referenced this pull request Nov 23, 2026
* refactor(core): run loop turns on an independent state machine (#5211)

* refactor(core): run loop turns on an independent state machine

- add an actor runtime for loop and turn execution
- unify turn hooks and asynchronous lifecycle settlement
- simplify loop contracts and cover turn lifecycle behavior

* fix(core): park recorded notifications until intake

* fix(core): settle forced aborts past stuck hooks and tools

* docs(core): document loop emitted events and public API

* fix(agent-core-v2): skip onDidFinishStep hooks for aborted steps

* refactor(llm): legalize deferred tools in the resolver (#5142)

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

* fix(core): recover compaction from empty text history (#5214)

* test(core): cover empty text request recovery

* fix(core): clean empty text before request encoding

* chore: add empty text recovery changesets

* test(core): cover cross-provider signed empty text

* fix(core): drop unsupported signed blank text
7Sageer pushed a commit that referenced this pull request Nov 23, 2026
…edgement (#5239)

* refactor(core): run loop turns on an independent state machine (#5211)

* refactor(core): run loop turns on an independent state machine

- add an actor runtime for loop and turn execution
- unify turn hooks and asynchronous lifecycle settlement
- simplify loop contracts and cover turn lifecycle behavior

* fix(core): park recorded notifications until intake

* fix(core): settle forced aborts past stuck hooks and tools

* docs(core): document loop emitted events and public API

* fix(agent-core-v2): skip onDidFinishStep hooks for aborted steps

* refactor(llm): legalize deferred tools in the resolver (#5142)

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

* fix(core): recover compaction from empty text history (#5214)

* test(core): cover empty text request recovery

* fix(core): clean empty text before request encoding

* chore: add empty text recovery changesets

* test(core): cover cross-provider signed empty text

* fix(core): drop unsupported signed blank text

* fix(agent-core-v2): truncate foreground output in bash detach acknowledgement (#5218)
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.

1 participant