Skip to content

Unify deferred tool loading (PR #30) and tool source economy (PR #34) into one mechanism #37

Closed

Description

@Astro-Han

Problem

PR #30 (deferred tool loading, Layer 1 of #15) and PR #34 (tool source economy) independently solve the same core concern: control which tool schemas enter the provider-visible set, so heavy schemas stay off the wire until needed. They currently ship as two parallel mechanisms — two activation paths, two catalogs, two diagnostics surfaces. That is tech debt: every future change to "which tools the model sees" has to be made twice and reconciled.

This issue proposes converging them into one mechanism, following @likun666661's principle from the group chat: 一个机制一个策略 (one mechanism, one policy).

Current state (after PR #30 merged)

PR #30 was rebased onto PR #34, so today they coexist through a thin, intentional bridge in ai-sdk-backend.ts:

  • ToolSourceEconomyRuntime.selectTools() picks the base tool surface (economy layer: which sources are visible).
  • The deferred layer then seeds the loaded-set on top of that selection — canonicalizeToolSet(baseTools, invalid, seedLoadedNames) + buildDeferredPrepareStep.
  • toolCount diagnostics were unified to the active (wire-visible) subset — it now excludes the invalid fallback, deferred-unloaded, and economy-hidden schemas. This required updating three economy test assertions (see PR feat: Layer 1 deferred (on-demand) tool loading — defer heavy schemas via load_tool #30).

This bridge keeps both mechanisms green while we design the merge. It is not the end state — it is exactly the two-implementations debt this issue exists to remove.

The two mechanisms side by side

Concern A — deferred (PR #30) B — economy (PR #34)
Opt-in deferredCatalog present toolSourceEconomy.mode === 'source_economy'
Hidden-tool tag exposure: 'deferred' per tool toolSource: { id } grouping
Connector load_tool (permission-free) connect_tool_source (permission-free)
Activation timing same-turn — prepareStep activates at step N+1 after a load at step N, + execute-boundary guard next-request — the enabled set only applies to a later send()
Persistence durable cross-turn seed from the RuntimeEvent ledger instance-local Set (not durable)
Diagnostics active-subset recompute, honest same-turn cost reduction fields: enabledSourceIds, availableSources, toolSchemaChangeReason

Neutral head-to-head verdict (Codex, component-level)

  • A wins: selection path, connector, activation (same-turn beats next-request), execute-boundary guard, persistence (durable ledger seed).
  • B wins: diagnostics shell (richer reduction fields), catalog metadata model (source grouping with labels).

Proposed unified design: one ToolAvailabilityRuntime

One runtime owns "which tools are model-visible this step":

  1. One catalog model. A group has id, toolNames, initiallyActive (bool), sourceMetadata (label, etc.). This subsumes both today's tags: exposure: 'deferred' becomes a group with initiallyActive: false; toolSource: { id } becomes a group with initiallyActive: true.
  2. One connector — a single permission-free tool that activates a group on demand (merges load_tool + connect_tool_source).
  3. One activation policy — same-turn prepareStep + execute-boundary guard. next-request is dropped: it was economy's implementation limitation (no prepareStep), not a design value.
  4. One canonicalize path — canonicalizeToolSet(tools, invalid, activeSet).
  5. One diagnostics — economy's reduction-field shell, fed by A's active-subset recompute. toolCount = active (already done in PR feat: Layer 1 deferred (on-demand) tool loading — defer heavy schemas via load_tool #30).
  6. Ledger persistence — A's durable cross-turn seed, so an activated group survives turns.

The real config dimension

Per @likun666661: timing is not the knob (it is always same-turn). The real per-group dimension is initiallyActive:

  • initiallyActive: true, economy-gated → "source economy" behavior (visible unless economy mode hides it; connect to re-enable).
  • initiallyActive: false → "deferred" behavior (hidden until loaded — heavy schemas).

One catalog, one policy, one knob.

Migration sketch

  1. Introduce ToolAvailabilityRuntime wrapping the unified catalog + same-turn activation + guard + ledger seed (mostly A's engine).
  2. Port economy's diagnostics shell (reduction fields) onto it.
  3. Map both exposure: 'deferred' and toolSource: { id } onto the unified group model.
  4. Collapse load_tool + connect_tool_source into one connector.
  5. Remove the coexist bridge in ai-sdk-backend.ts (the selectTools() → deferred seed two-step).
  6. Delete the second runtime.

Open questions for @likun666661

  • Does this match your "一个机制一个策略" intent end-to-end?
  • Connector naming: keep load_tool, keep connect_tool_source, or a new neutral name?
  • For a group that is "visible by default but economy can hide it", how should initiallyActive + economy-gating compose in the catalog config?
  • Anything in B's next-request semantics that carries value beyond the implementation limitation?

Refs: #15 (parent), PR #30 (deferred), PR #34 (tool source economy).

Activity

  1. added
    enhancement
    on Jun 17, 2026
  2. likun666661 commented on Jun 17, 2026

    @likun666661
    Member

    I agree with the direction of this issue. My read is that PR #34 and PR #30 solved adjacent parts of the same problem, but at different abstraction levels and with different maturity.

    The reason PR #34 introduced toolSource / source definitions / source-economy diagnostics was not to create a second dynamic-loader policy. It was solving the DeepSeek cost-runtime question at the source/group level:

    • cost attribution: when the prefix/request shape changes, we need to know which source group caused the schema expansion, not just that tool_schema_changed happened;
    • model-facing capability inventory: a connector needs to expose available capability groups such as core, files.write, shell, web, browser, office, or rive, rather than forcing the model to infer individual tool names;
    • telemetry/UI explainability: enabledSourceIds, availableSourceIds, visibleToolNamesBySource, connector name, tool counts, and schema-char reductions are useful product/diagnostic fields;
    • configuration boundary: the real product knob is group-level availability, for example core always visible, heavy/browser/office/Rive groups hidden until needed.

    That part is still valuable and should be retained.

    The part I would not preserve as final policy is PR #34's next-request activation semantics. That was a minimal first implementation of source economy before the deferred-loader work had proven the prepareStep path. PR #30 has the stronger runtime mechanics: same-turn activation, an execute-boundary guard, current-step active snapshots, honest active-subset diagnostics, and durable RuntimeEvent seeding.

    So the unified design I would aim for is:

    1. Introduce a single ToolAvailabilityRuntime as the only owner of provider-visible tool availability.
    2. Use one catalog model: each group has id, toolNames, initiallyActive, and optional metadata such as label / description.
    3. Map today's two metadata forms into that catalog:
      • exposure: 'deferred' => a group with initiallyActive: false;
      • toolSource: { id, label, description } / sourceDefinitions => source/group metadata in the same catalog.
    4. Use one connector exposed to the model. I lean toward keeping load_tool as the canonical name because it matches the same-turn semantics better. connect_tool_source should be accepted for historical RuntimeEvent seeding/backcompat, but not remain a separate provider-visible connector.
    5. Use one activation policy: same-turn prepareStep plus execute-boundary guard. I would not make same-turn vs next-request a configuration knob; next-request was an implementation limitation, not a product value.
    6. Use one diagnostics source: keep the source-economy diagnostic shell, but populate it from the unified runtime's active snapshot. toolCount, schema chars, prefix/request-shape hashes, enabledSourceIds, availableSourceIds, and visible tool names should all describe the same provider-visible active set.
    7. Preserve durable seeding from the RuntimeEvent ledger, and seed from both historical load_tool and connect_tool_source calls so existing sessions do not regress.

    A good migration boundary would be to make AiSdkBackend stop doing the current two-step bridge:

    ToolSourceEconomyRuntime.selectTools()
      -> canonicalizeToolSet(baseTools, invalid, seedLoadedNames)
      -> buildDeferredPrepareStep(...)

    and instead ask one runtime for:

    {
      providerTools,
      activeTools,
      prepareStep,
      currentRepairToolNames,
      diagnostics,
      setStepActivation,
    }

    The important invariant is "one mechanism, one policy": tool availability should have one catalog, one connector, one active snapshot, one diagnostics source, and one place where prefix/tool-schema changes are classified.

  3. Astro-Han commented on Jun 17, 2026

    @Astro-Han
    ContributorAuthor

    Thanks for the detailed response. We agree on direction. Here's where I want to push further.

    Drop initiallyActive, use a global switch

    The issue proposes a per-group initiallyActive boolean. I think we can go simpler: one global economy toggle (on by default) + a configurable core set.

    • Economy on (default): only core tools are provider-visible. Everything else is behind the connector.
    • Economy off: all tools visible, no connector.
    • Core is a configurable list. files.write tools belong in core; browser / office don't.

    Why no per-group flag: it will interact with other dimensions (permission modes, deployment contexts), and each interaction is a new edge case. A global switch with a tunable core boundary covers the same ground without the combinatorial blowup. Want a group always visible? Put its tools in core. Otherwise economy hides it.

    This lines up with your framing: the real config boundary is group-level availability (core always visible, heavy groups hidden until needed), not per-group activation policy.

    Grouping: only for natural clusters

    Groups pull their weight for product semantics (capability inventory, cost attribution). But only when tools actually cluster together. Rules:

    • Only create groups for tools that always load together (browser's 15 tools, office's 10 tools).
    • Ungrouped tools go in core (always visible). Not every tool needs a named group.
    • Start with 3–5 groups. If a new tool doesn't fit, leave it ungrouped until a cluster forms.

    Long-term, ToolSearch-style semantic lookup replaces "load this group" with "find me the tool for X." Groups as product semantics (capability inventory, diagnostic attribution) stick around. Keep the group count small and membership obvious, and the "where does this tool go?" problem doesn't come up.

    Connector: load_tools

    Rename load_tool → load_tools (plural):

    • Reflects that it activates a group, not one tool.
    • One-character diff from existing ledger entries, easy backcompat mapping.
    • connect_tool_source stays as a historical alias for RuntimeEvent seeding. Not exposed as a separate provider-visible connector.

    Open questions

    1. 一个机制一个策略? Yes: one catalog, one connector, one activation policy (same-turn), one diagnostics source. The only knob is the global economy switch + core list.
    2. Connector naming: load_tools.
    3. initiallyActive + economy-gating composition: Gone. No per-group flag, just "in core or not."
    4. Next-request semantics value? None. It was an implementation limitation. Same-turn prepareStep + execute-boundary guard is the only policy.

    Catalog model

    interface ToolGroup {
      id: string;
      toolNames: readonly string[];
      label?: string;
      description?: string;
    }
    
    interface ToolAvailabilityConfig {
      economy: boolean;            // true = only core visible; false = all visible
      coreToolNames: string[];     // always-visible tools (ungrouped tools default here)
      groups: ToolGroup[];         // natural clusters (browser, office, shell, …)
    }

    No initiallyActive on groups. Visibility is set by the global economy flag: on → hidden (unless in coreToolNames); off → visible.

    Migration

    1. Introduce ToolAvailabilityRuntime with this config + PR feat: Layer 1 deferred (on-demand) tool loading — defer heavy schemas via load_tool #30's engine (same-turn activation, guard, ledger seed).
    2. Port PR Add Tool Source Economy v1 #34's diagnostic fields onto the unified runtime's active snapshot.
    3. Map both load_tool and connect_tool_source historical events for ledger seeding.
    4. Collapse both connectors into load_tools.
    5. Remove the coexist bridge in ai-sdk-backend.ts.
    6. Delete ToolSourceEconomyRuntime.

    If this looks right, I'll start building.

  4. Astro-Han commented on Jun 17, 2026

    @Astro-Han
    ContributorAuthor

    已按本 issue 收敛的方案实现并提交:PR #41 (Closes #37,合并后自动关闭本 issue)。

    落地要点(一个机制、一个策略):

    验证:typecheck 全绿;core 624/624、storage 82/82、runtime 535/536、desktop 1491/1491(runtime 唯一未过的是既有的 network/proxy-test 环境用例,在 main 上同样失败,本次未触及)。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions