UNPKG

@code-yeongyu/senpi

Version:

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

133 lines • 5.87 kB
import { AsyncLocalStorage } from "node:async_hooks"; import { resolveRootObjectSchema } from "@earendil-works/pi-ai/utils/tool-schema-compat"; import { supportsAnthropicNativeToolSearch } from "./native-support.js"; // Anthropic Messages supports native BM25 tool search through request payload // injection alone. OpenAI native client-mode search remains intentionally out of // scope because it requires a provider-layer seam. export const ANTHROPIC_TOOL_SEARCH_TYPE = "tool_search_tool_bm25_20251119"; export const ANTHROPIC_TOOL_SEARCH_NAME = "tool_search_tool_bm25"; /** Anthropic caps a request at 10k tools; beyond that native search is invalid. */ export const ANTHROPIC_MAX_TOOLS = 10000; const scopedMcpNativeToolSearchGate = new AsyncLocalStorage(); let mcpNativeToolSearchGate = () => false; /** Bind the MCP-owned user setting without moving MCP configuration into the shared builtin. */ export function installMcpNativeToolSearchGate(gate) { mcpNativeToolSearchGate = gate; scopedMcpNativeToolSearchGate.enterWith(gate); } export function isMcpNativeToolSearchEnabled() { return (scopedMcpNativeToolSearchGate.getStore() ?? mcpNativeToolSearchGate)(); } function isRecord(value) { return typeof value === "object" && value !== null; } /** * Pure payload transform. Injects eligible inactive catalog schemas, adds exactly * one native search tool, and enforces Anthropic's HARD RULES: never defer the * local search tool, never combine defer_loading with cache_control, keep at * least one non-deferred tool, and skip entirely above the 10k tool cap. */ export function addAnthropicNativeToolSearch(target, payload, config) { if (!supportsAnthropicNativeToolSearch(target) || !isRecord(payload)) return payload; const tools = Array.isArray(payload.tools) ? payload.tools : []; const injected = injectInactiveCatalogTools(tools, config); if (injected.length > ANTHROPIC_MAX_TOOLS) return payload; const deferred = injected.map((tool) => maybeDefer(tool, config)); const hasSearchTool = deferred.some((tool) => isRecord(tool) && tool.type === ANTHROPIC_TOOL_SEARCH_TYPE); const nextTools = hasSearchTool ? deferred : [...deferred, { type: ANTHROPIC_TOOL_SEARCH_TYPE, name: ANTHROPIC_TOOL_SEARCH_NAME }]; if (nextTools.length > ANTHROPIC_MAX_TOOLS) return payload; return { ...payload, tools: nextTools }; } function injectInactiveCatalogTools(tools, config) { const catalog = config.getCatalog?.() ?? []; const residentNames = new Set(tools.flatMap((tool) => (isRecord(tool) && typeof tool.name === "string" ? [tool.name] : []))); const injected = [...tools]; for (const doc of catalog) { if (doc.name === config.searchToolName || residentNames.has(doc.name) || !config.isDeferrable(doc.name)) continue; const definition = config.getToolDefinition?.(doc.name); if (definition?.parameters === undefined) continue; injected.push({ name: doc.name, description: definition.description ?? doc.description ?? doc.label, input_schema: anthropicInputSchema(definition.parameters), defer_loading: true, }); residentNames.add(doc.name); } return injected; } /** * Anthropic requires `input_schema.type: "object"`. Resident tools get that shape in the provider's * `convertTools`; injected catalog tools bypass it, so a root union (`anyOf` with no top-level * `type`) would reject the whole request. Plain object schemas pass through unchanged. */ function anthropicInputSchema(parameters) { if (!isRecord(parameters) || parameters.type === "object") return parameters; const resolved = resolveRootObjectSchema(parameters); return resolved.type === "object" ? resolved : { ...resolved, type: "object" }; } function maybeDefer(tool, config) { if (!isRecord(tool)) return tool; const name = typeof tool.name === "string" ? tool.name : undefined; if (name === undefined) return tool; if (name === config.searchToolName) return tool; if (!config.isDeferrable(name)) return tool; if ("cache_control" in tool) return tool; if (tool.defer_loading === true) return tool; return { ...tool, defer_loading: true }; } /** * `tool_reference` blocks emitted inside a tool_result so the API expands the * referenced tools. Anthropic names the target through `tool_name`; a block * carrying `name` is rejected as a malformed content block. */ export function buildToolReferenceBlocks(names) { return names.map((name) => ({ type: "tool_reference", tool_name: name })); } /** Session-scoped request injector with permanent 400 fallback for the session. */ export class AnthropicNativeToolSearchAdapter { #disabled = false; #injectedLastRequest = false; #fallbackReason = null; #deps; constructor(deps) { this.#deps = deps; } applyBeforeRequest(target, payload) { this.#injectedLastRequest = false; if (this.#disabled || !this.#deps.enabled()) return payload; const next = addAnthropicNativeToolSearch(target, payload, this.#deps); this.#injectedLastRequest = next !== payload; return next; } noteResponseStatus(status) { if (status !== 400 || !this.#injectedLastRequest || this.#disabled) return; this.#disabled = true; this.#fallbackReason = "Anthropic returned 400 for native tool-search; disabled it and fell back to local tool_search for this session."; this.#deps.onFallback?.(this.#fallbackReason); } get disabled() { return this.#disabled; } get fallbackReason() { return this.#fallbackReason; } } //# sourceMappingURL=native-search.js.map