UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

184 lines • 9.22 kB
// Tier-B adaptive exposure wiring (todo 32). // // Completes exposure:"auto": a server whose filtered tool count exceeds // searchThreshold enters SEARCH mode — the full catalog is registered but only // directTools stay active. The shared tool-search builtin owns tool_search and // MCP feeds its searchable documents and activation hook into that service. import { Text } from "@earendil-works/pi-tui"; import { Type } from "typebox"; import { getDispatchIdentity, registerDispatchIdentity } from "../../permission-system/dispatch-metadata.js"; import { deriveMcpRegistrationId } from "../../tool-search/engine/marker.js"; import { registerToolsPreservingActiveSet } from "../active-set.js"; import { createMcpProxyTool } from "./proxy.js"; import { buildMcpToolDefinitions, mapMcpCatalogNames, } from "./register.js"; const managedNamesByRegistrar = new WeakMap(); // Names a by-name call already promoted from stub to full. A cold lazy server's // background connect re-registers the whole catalog; without this memory that // refresh would hand the promoted tool back to the model as a stub. const promotedNamesByRegistrar = new WeakMap(); /** Register MCP tools honouring Tier-B search mode + prompt-cache mitigations. */ export function registerMcpTierBTools(pi, input, toolSearchService, warn) { const named = mapMcpCatalogNames(input.registeredEntries, warn); const searchable = named.map(({ entry, name }) => ({ name, toolName: entry.tool, description: entry.description, server: entry.server, })); const documents = named.map(({ entry, name }) => ({ name, label: entry.tool, aliases: [entry.tool], description: entry.description, keywords: [], source: "mcp", group: entry.server, ownerLabel: entry.server, registrationId: deriveMcpRegistrationId(entry.server, entry.tool), })); const fullDefs = buildMcpToolDefinitions(input.registeredEntries, warn); const fullByName = new Map(fullDefs.map((def) => [def.name, def])); const promoted = promotedNamesByRegistrar.get(pi) ?? new Set(); promotedNamesByRegistrar.set(pi, promoted); const gatewayNames = []; const serverGatewayNames = []; for (const gateway of input.proxyGateways ?? []) { const tool = createMcpProxyTool(gateway.server, gateway.entries); pi.registerTool(tool); gatewayNames.push(tool.name); serverGatewayNames.push(tool.name); } for (const tool of input.utilityTools ?? []) { pi.registerTool(tool); gatewayNames.push(tool.name); } const activeMcpNames = [ ...mapMcpCatalogNames(input.activeEntries).map(({ name }) => name), ...fullDefs.filter((def) => input.searchMode && promoted.has(def.name)).map((def) => def.name), ...gatewayNames, ]; const managedNames = new Set([...fullDefs.map((def) => def.name), ...gatewayNames]); const previousManagedNames = managedNamesByRegistrar.get(pi) ?? new Set(); managedNamesByRegistrar.set(pi, managedNames); const stubSwap = input.searchMode && input.settings.stubSwap === true; const stubbed = new Set(); const registeredNames = new Set(fullDefs.map((def) => def.name)); // Per-server MCP names sort by name like shared-catalog members: in direct mode they are not // in the search catalog, and keeping their reference order made the tool list follow // which server finished connecting first (#5289). The fixed utility tools keep their // reference place ahead of them; their position never depended on connect order. const catalogNames = new Set([ ...toolSearchService.getCatalog().map((doc) => doc.name), ...fullDefs.map((def) => def.name), ...serverGatewayNames, ]); const activate = (names) => { const known = [...new Set(names.filter((name) => registeredNames.has(name)))]; if (known.length === 0) return; for (const name of known) promoted.add(name); if (stubSwap) swapStubsToFull(pi, known, stubbed, fullByName); const current = pi.getActiveTools(); pi.setActiveTools(orderActiveSet(unionStable(current, known), current, catalogNames)); }; toolSearchService.feed("mcp", input.searchMode ? documents : [], { activate }); for (const doc of toolSearchService.getCatalog()) catalogNames.add(doc.name); const reference = pi.getActiveTools(); // MCP owns only names from its previous/current registration generation. // Everything else is a base tool, regardless of naming convention. const currentBase = reference.filter((name) => !isLegacyMcpRegistrationName(name) && !previousManagedNames.has(name) && !managedNames.has(name)); if (!input.searchMode) { registerToolsPreservingActiveSet(pi, fullDefs, orderActiveSet([...currentBase, ...activeMcpNames], reference, catalogNames)); return { activate, searchable }; } if (!stubSwap) { // Default search mode: full defs registered, only directTools plus the // shared service-managed tool_search are active. Promotions append on the // activation turn (an accepted cache miss). const active = orderActiveSet([...currentBase, ...activeMcpNames], reference, catalogNames); registerToolsPreservingActiveSet(pi, fullDefs, active); return { activate, searchable }; } // stubSwap: every search-mode tool is registered as a tiny stub and kept // active so the tools array is length-stable; direct tools stay full. const directActive = new Set(activeMcpNames); const toRegister = fullDefs.map((def) => { if (directActive.has(def.name) || promoted.has(def.name)) return def; stubbed.add(def.name); return buildMcpStubDefinition(def.name, { full: def, promote: () => activate([def.name]) }); }); const active = orderActiveSet([...currentBase, ...fullDefs.map((def) => def.name)], reference, catalogNames); registerToolsPreservingActiveSet(pi, toRegister, active); return { activate, searchable }; } function swapStubsToFull(pi, names, stubbed, fullByName) { for (const name of names) { if (!stubbed.has(name)) continue; const full = fullByName.get(name); if (full === undefined) continue; pi.registerTool(full); stubbed.delete(name); promotedNamesByRegistrar.get(pi)?.add(name); } } /** Order the active set deterministically without disturbing base tools. * Base tools retain reference order; every shared-catalog member sorts by * canonical name so consecutive promotions remain byte-stable. */ export function orderActiveSet(names, reference, catalogNames) { const unique = [...new Set(names)]; const rank = new Map(reference.map((name, index) => [name, index])); const base = unique .filter((name) => !catalogNames.has(name)) .sort((a, b) => (rank.get(a) ?? Number.MAX_SAFE_INTEGER) - (rank.get(b) ?? Number.MAX_SAFE_INTEGER)); const catalog = unique.filter((name) => catalogNames.has(name)).sort(); return [...base, ...catalog]; } function unionStable(current, added) { return [...new Set([...current, ...added])]; } /** Preserve the existing stale-generation cleanup for active sets created * before MCP catalog ownership was tracked. Ordering itself is catalog-based. */ function isLegacyMcpRegistrationName(name) { return name.startsWith("mcp_"); } /** A 30-70 token placeholder for an inactive search-mode tool. Keeps the tools * array length-stable under stubSwap. Calling it by name promotes the full * definition and runs the call in the same turn, so the model never needs a * tool_search round trip; without a promotion hook it only points at tool_search. */ export function buildMcpStubDefinition(name, promotion) { const parameters = Type.Object({}, { additionalProperties: true }); if (promotion !== undefined) { registerDispatchIdentity(parameters, (input) => getDispatchIdentity(promotion.full.parameters, input)); } return { name, label: name, description: promotion === undefined ? `Inactive MCP tool. Run tool_search to activate ${name}, then call it on your next turn.` : `Deferred MCP tool. Call ${name} with its real arguments; it activates and runs on this first call (tool_search lists its schema).`, parameters, executionMode: "parallel", async execute(toolCallId, params, signal, onUpdate, ctx) { if (promotion === undefined) { return { content: [ { type: "text", text: `${name} is not active. Use tool_search to activate it, then call it.` }, ], details: undefined, }; } promotion.promote(); return promotion.full.execute(toolCallId, params, signal, onUpdate, ctx); }, renderCall(_args, theme) { return new Text(theme.fg("toolOutput", `${name} (deferred stub)`), 0, 0); }, }; } //# sourceMappingURL=tier-b.js.map