UNPKG

@code-yeongyu/senpi

Version:

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

302 lines • 13.1 kB
import { AsyncLocalStorage } from "node:async_hooks"; import { extensionLoadKey } from "../../extension-load-key.js"; import { buildBm25Index, DEFAULT_BM25_PRECISION, normalizeToolName, tokenizeToolText, } from "./engine/bm25.js"; import { rehydrate } from "./engine/marker.js"; import { activationMarkerCandidates } from "./engine/marker-candidates.js"; import { extensionDocument } from "./extension-document.js"; import { TOOL_SEARCH_TOOL_NAME } from "./tool.js"; /** Session-scoped owner of the live generalized tool-search catalog. */ export class ToolSearchService { #runtime; #feeds = new Map(); #extensionDocs = []; #extensionFingerprint = ""; #registryGeneration = 0; #historyScannedGeneration = -1; #registerToolSearch; #removedToolHints = () => ({}); #disposed; constructor(runtime) { this.#runtime = runtime; this.#feeds.set("extension", { docs: [], hooks: { activate: (names) => this.#promoteExtensionTools(names) }, }); } #nativeInjectionFailure = null; get isDisposed() { return this.#disposed !== undefined; } /** Retire this service with its session or extension generation; every later use throws. */ dispose(sessionId, reason) { this.#disposed ??= { sessionId, reason }; sessionServices.delete(this); } #assertLive() { if (this.#disposed === undefined) return; const { sessionId, reason } = this.#disposed; throw new Error(`The tool-search service of session ${sessionId} is disposed (${reason}). Resolve the live session's own tool-search service instead of a retained one.`); } /** Record that a native-injected request was rejected; the session consumes it once. */ noteNativeInjectionFailure(reason) { this.#assertLive(); this.#nativeInjectionFailure = reason; } /** Consume the pending native-injection failure, if any (one-shot). */ takeNativeInjectionFailure() { this.#assertLive(); const reason = this.#nativeInjectionFailure; this.#nativeInjectionFailure = null; return reason; } bindRuntime(runtime) { this.#runtime = runtime; } bindActivationRuntime(runtime) { this.#runtime = { ...this.#runtime, ...runtime }; } /** Register the resident search tool only after a searchable catalog exists. */ bindToolRegistrar(register) { this.#registerToolSearch = register; } /** Let the host expose its removed-tool hints so a search for a hidden tool answers with the redirect. */ bindRemovedToolHints(provider) { this.#removedToolHints = provider; } /** Hints for every hidden tool the query names, in query order. */ hiddenToolHints(query) { this.#assertLive(); const hints = this.#removedToolHints(); const byNormalizedName = new Map(Object.entries(hints).map(([name, hint]) => [normalizeToolName(name), { hint, name }])); if (byNormalizedName.size === 0) return []; const seen = new Set(); const matched = []; for (const candidate of [normalizeToolName(query), ...tokenizeToolText(query)]) { const entry = byNormalizedName.get(candidate); if (entry === undefined || seen.has(entry.name)) continue; seen.add(entry.name); matched.push(entry); } return matched; } /** Parameter schema of a registered tool, active or not, so a search result can be called by name. */ getToolParameters(name) { this.#assertLive(); return this.#runtime.getAllTools().find((tool) => tool.name === name)?.parameters; } beginSession() { this.#assertLive(); this.#feeds.delete("mcp"); this.#registryGeneration += 1; this.#historyScannedGeneration = -1; this.#refreshExtensionDocs(); this.#syncToolSearchLifecycle(); } /** Replace one source's catalog generation and activation hook. */ feed(source, docs, hooks) { this.#assertLive(); const validDocs = docs.filter((doc) => isValidDocument(doc, source)); this.#feeds.set(source, { docs: validDocs, hooks }); this.#registryGeneration += 1; this.#syncToolSearchLifecycle(); } getCatalog() { this.#assertLive(); this.#refreshExtensionDocs(); return [...(this.#feeds.get("mcp")?.docs ?? []), ...this.#extensionDocs]; } search(query, limit = 10, options = {}) { return buildBm25Index(this.getCatalog()).search(query, limit, { precision: DEFAULT_BM25_PRECISION, ...options }); } /** * Rank the tools the session routes through eval only (senpi#6886). They are never catalog entries, so no feeder * can activate them; a model reaches them as `tool.<name>(...)` inside an eval cell. */ searchEvalOnly(query, limit = 10, options = {}) { const catalogNames = new Set(this.getCatalog().map((doc) => doc.name)); const docs = this.#runtime .getAllTools() .filter((tool) => tool.evalOnly === true && !catalogNames.has(tool.name)) .map(extensionDocument) .filter((doc) => doc !== undefined); return buildBm25Index(docs).search(query, limit, { precision: DEFAULT_BM25_PRECISION, ...options }); } /** Route all matches through their owning feeder, even when already active. */ activate(matches) { this.#assertLive(); const namesBySource = new Map(); for (const match of matches) { const names = namesBySource.get(match.doc.source) ?? []; names.push(match.name); namesBySource.set(match.doc.source, names); } for (const [source, names] of namesBySource) { this.#feeds.get(source)?.hooks.activate(names); } const active = new Set(this.#runtime.getActiveTools()); return matches.map(({ name }) => name).filter((name) => active.has(name)); } activateTool(name) { const doc = this.getCatalog().find((candidate) => candidate.name === name); if (doc === undefined) return false; this.#feeds.get(doc.source)?.hooks.activate([name]); return this.#runtime.getActiveTools().includes(name); } /** Replay ownership-aware and legacy MCP history once per catalog generation. */ maybeRehydrateFromHistory(messages) { // Reading the catalog first may refresh it into a new generation, which must be scanned. const catalog = this.getCatalog(); if (this.#historyScannedGeneration === this.#registryGeneration) return []; this.#historyScannedGeneration = this.#registryGeneration; return this.#rehydrate(messages, catalog); } /** * `maybeRehydrateFromHistory` for a whole session's entries: the candidate scan yields to the * event loop, so a large transcript does not hold a shared host while it opens (senpi#3518). */ async maybeRehydrateFromHistoryInSlices(messages, slicer) { this.getCatalog(); if (this.#historyScannedGeneration === this.#registryGeneration) return []; const generation = this.#registryGeneration; this.#historyScannedGeneration = generation; const candidates = await activationMarkerCandidates(messages, slicer); // A catalog change while scanning is replayed by the next context build against the new generation. if (this.isDisposed || generation !== this.#registryGeneration) return []; return this.#rehydrate(candidates, this.getCatalog()); } #rehydrate(messages, catalog) { const docsByName = new Map(catalog.map((doc) => [ doc.name, { name: doc.name, registrationId: doc.registrationId, source: doc.source, allowLazyActivation: true, }, ])); const restored = rehydrate(messages, docsByName); if (restored.length > 0) this.#activateNames(restored, catalog); return restored; } #refreshExtensionDocs() { const docs = this.#runtime .getAllTools() .filter((tool) => tool.exposure === "search" && tool.allowLazyActivation) .map(extensionDocument) .filter((doc) => doc !== undefined) .sort((left, right) => left.name.localeCompare(right.name)); const fingerprint = JSON.stringify(docs); if (fingerprint === this.#extensionFingerprint) return; this.#extensionDocs = docs; this.#extensionFingerprint = fingerprint; this.#feeds.set("extension", { docs, hooks: { activate: (names) => this.#promoteExtensionTools(names) }, }); this.#registryGeneration += 1; this.#syncToolSearchLifecycle(); } #activateNames(names, catalog = this.getCatalog()) { const sourceByName = new Map(catalog.map((doc) => [doc.name, doc.source])); const namesBySource = new Map(); for (const name of names) { const source = sourceByName.get(name); if (source === undefined) continue; const sourceNames = namesBySource.get(source) ?? []; sourceNames.push(name); namesBySource.set(source, sourceNames); } for (const [source, sourceNames] of namesBySource) this.#feeds.get(source)?.hooks.activate(sourceNames); } #syncToolSearchLifecycle() { const hasDocuments = this.#extensionDocs.length > 0 || (this.#feeds.get("mcp")?.docs.length ?? 0) > 0; if (hasDocuments) this.#registerToolSearch?.(); const current = this.#runtime.getActiveTools(); const isActive = current.includes(TOOL_SEARCH_TOOL_NAME); if (hasDocuments === isActive) return; this.#runtime.setActiveTools(hasDocuments ? [...current, TOOL_SEARCH_TOOL_NAME] : current.filter((name) => name !== TOOL_SEARCH_TOOL_NAME)); } #promoteExtensionTools(names) { if (names.length === 0) return; const current = this.#runtime.getActiveTools(); const active = new Set(current); const added = [...new Set(names.filter((name) => !active.has(name)))].sort(); this.#runtime.setActiveTools([...current, ...added]); } } function isValidDocument(doc, source) { return doc.source === source && doc.name.length > 0 && doc.registrationId.length > 0; } const scopedService = new AsyncLocalStorage(); let servicesByExtensionLoad = new WeakMap(); const sessionServices = new Set(); let sessionlessService = null; /** Make a session-owned service visible to later builtins loaded in the same provider scope. */ export function installScopedToolSearchService(value) { scopedService.enterWith(value); } /** Own `value` as the tool-search service of the extension load that created `pi`. */ export function registerToolSearchServiceForExtensionLoad(pi, value) { const load = extensionLoadKey(pi); if (load !== undefined) servicesByExtensionLoad.set(load, value); } /** The tool-search service owned by the extension load that created `pi`. */ export function getToolSearchServiceForExtension(pi) { const load = extensionLoadKey(pi); return load === undefined ? undefined : servicesByExtensionLoad.get(load); } /** A session takes the service its extension load (keyed by that load's runtime) created. */ export function adoptToolSearchServiceForSession(extensionLoad) { const value = servicesByExtensionLoad.get(extensionLoad); if (value !== undefined) sessionServices.add(value); return value; } /** * Resolve a service for a caller that holds no session: the provider scope's service, else the * only live session's service. With several live sessions there is no right answer, so it throws. * With none, a standalone service serves session-free callers. */ export function getToolSearchService(runtime) { const scoped = scopedService.getStore(); if (scoped !== undefined) { if (runtime !== undefined) scoped.bindRuntime(runtime); return scoped; } if (sessionServices.size === 1) return [...sessionServices][0]; if (sessionServices.size > 1) { throw new Error(`getToolSearchService() cannot choose between ${sessionServices.size} live sessions; resolve the service through the session that owns it`); } if (sessionlessService === null) { if (runtime === undefined) throw new Error("ToolSearchService runtime is not bound"); sessionlessService = new ToolSearchService(runtime); } else if (runtime !== undefined) { sessionlessService.bindRuntime(runtime); } return sessionlessService; } export function resetToolSearchServiceForTests() { sessionlessService = null; sessionServices.clear(); servicesByExtensionLoad = new WeakMap(); } //# sourceMappingURL=service.js.map