UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

251 lines (250 loc) • 13 kB
import { describeRejectedValue } from "../tool-search-setting.js"; import { readCompactionActiveTools } from "../../internal/harness.js"; import { toolsToFingerprintInputs } from "../prefix-declaration.js"; import { survivorsByName } from "../tool-roster.js"; import { deliverEngineNotice } from "../types.js"; import { TOOL_SEARCH_NAME, buildDeferredRegistry, extractDiscoveredToolNames, createPlaceholderTool, createToolSearchTool, staticSchemaRenderable } from "./tool-disclosure.js"; import { createDeferralCensus } from "./deferral-census.js"; import { mcpFailureRemembered } from "../mcp-server-unavailable-notice.js"; import { REFRESH_MCP_TOOLS_TOOL_NAME } from "../tool-catalog-entries.js"; import { inlineUntrusted } from "../untrusted-text.js"; import { refusalAbout } from "../config-refusal-input.js"; import { projectToolManifest } from "../../prompt-assembly/tool-catalog.js"; import { protocolOf } from "@sema-agent/primitives"; let announcedMaterializeEnvBySink = new WeakMap(); const announcedMaterializeEnvConsole = new Set(); function materializeEnvLedger(onNotice) { if (typeof onNotice !== "function") return announcedMaterializeEnvConsole; let lines = announcedMaterializeEnvBySink.get(onNotice); if (lines === undefined) { lines = new Set(); announcedMaterializeEnvBySink.set(onNotice, lines); } return lines; } export function compactionActivationSnapshot(branch) { const names = new Set(); for (const entry of branch) { if (entry.type !== "compaction" || entry.fromHook === true) continue; for (const n of readCompactionActiveTools(entry.details)) names.add(n); } return [...names]; } export function __resetMaterializeEnvAnnouncements() { announcedMaterializeEnvBySink = new WeakMap(); announcedMaterializeEnvConsole.clear(); } function emitMaterializeEnvNotice(onNotice, message, detail) { const ledger = materializeEnvLedger(onNotice); if (ledger.has(message)) return; ledger.add(message); deliverEngineNotice(onNotice, { code: "config.materialize_env_discarded", message, detail }); } export async function prepareToolDisclosureMount(input) { const { spec, deps, session, resume, deferred, tools, perTurnStart, onceLedger, mcp, promptManifest, offloadReachableToolsRef, contentOriginWrapRef, rebuildHarnessToolsRef, harnessRef, toolSearchPolicy } = input; let toolDisclosureSeat; const activeTools = new Set(); const turnSnapshotRef = {}; const toolTableViewRef = {}; let harnessTools = tools; let toolSearchMounted; const withRemoteWords = deps.crossBoundaryPosture !== "multi_tenant"; const failedMcpServers = onceLedger.mcpFailuresToAnnounce(mcp.statuses, mcpFailureRemembered(mcp.warnings), withRemoteWords); const waitTool = tools.some((t) => t.name === REFRESH_MCP_TOOLS_TOOL_NAME) ? { waitTool: REFRESH_MCP_TOOLS_TOOL_NAME } : {}; const connectingMcpServers = mcp.statuses.filter((s) => s.status === "pending").map((s) => ({ name: inlineUntrusted(s.name, 160), connecting: true, ...waitTool })); const mcpUnavailable = failedMcpServers.length + connectingMcpServers.length > 0 ? { pending: [...failedMcpServers, ...connectingMcpServers] } : undefined; let toolsDeltaRef; let toolMaterializeStatic = false; let deferDirectCall = false; const staticFaceForRef = {}; if (deferred.size > 0) toolsDeltaRef = { pending: [], pendingRemoved: [], pendingReadded: [] }; const listingRideRef = {}; { const raw = process.env.SEMA_TOOL_MATERIALIZE_STRATEGY; if (raw !== undefined && raw !== "swap" && raw !== "static" && deferred.size === 0) { const line = `SEMA_TOOL_MATERIALIZE_STRATEGY=${JSON.stringify(raw)} is not "swap" or "static" — inert on this task (no deferred tools), but a deferring task WITHOUT an explicit spec strategy will refuse to prepare under it (an explicit legal spec outranks and discards it, loudly). Fix or unset the flag.`; emitMaterializeEnvNotice(deps.onNotice, line, { raw }); } } if (deferred.size > 0) { if (deferred.has(TOOL_SEARCH_NAME) || tools.some((t) => t.name === TOOL_SEARCH_NAME)) { const e = new Error(`Tool name "${TOOL_SEARCH_NAME}" is reserved when deferred tools are present.`); e.code = "config.reserved_tool_name"; throw refusalAbout("taskConfig", e); } const registry = buildDeferredRegistry(deferred, tools); const rawEnvStrategy = process.env.SEMA_TOOL_MATERIALIZE_STRATEGY; const envStrategyInvalid = rawEnvStrategy !== undefined && rawEnvStrategy !== "swap" && rawEnvStrategy !== "static"; if (envStrategyInvalid && spec.toolMaterializeStrategy === undefined) { const e = new Error(`SEMA_TOOL_MATERIALIZE_STRATEGY must be "swap" or "static" (got ${describeRejectedValue(rawEnvStrategy)}).`); e.code = "config.tool_materialize_invalid"; throw refusalAbout("deps", e); } if (envStrategyInvalid) { const line = `SEMA_TOOL_MATERIALIZE_STRATEGY=${JSON.stringify(rawEnvStrategy)} was ignored — not "swap" or "static", and the task spec pins toolMaterializeStrategy=${JSON.stringify(spec.toolMaterializeStrategy)} which outranks it. Fix or unset the env flag.`; emitMaterializeEnvNotice(deps.onNotice, line, { raw: rawEnvStrategy, specStrategy: spec.toolMaterializeStrategy }); } const envStrategy = envStrategyInvalid ? undefined : rawEnvStrategy; const requestedStrategy = spec.toolMaterializeStrategy ?? envStrategy ?? "swap"; const laneDegrade = requestedStrategy === "static" && spec.deferSelfResolve === false; const materializeStatic = requestedStrategy === "static" && !laneDegrade; toolMaterializeStatic = materializeStatic; deferDirectCall = spec.deferSelfResolve !== false; promptManifest.toolDisclosure = { deferredTools: deferred.size, strategy: materializeStatic ? "static" : "swap", source: laneDegrade ? "degraded_no_direct_lane" : spec.toolMaterializeStrategy !== undefined ? "spec" : envStrategy !== undefined ? "env" : "default", }; const census = createDeferralCensus(deferred, toolSearchPolicy); toolDisclosureSeat = census.seat; const publishCensus = () => census.publish(activeTools); const everExempt = new Set(); const answering = (name) => survivorsByName(tools).get(name); const staticFaceFor = (name) => { if (!materializeStatic) return false; if (everExempt.has(name)) return false; if (staticSchemaRenderable(answering(name)?.parameters)) return true; everExempt.add(name); return false; }; staticFaceForRef.current = staticFaceFor; let activationChain = Promise.resolve(); const serializeActivation = (section) => { const p = activationChain.then(section); activationChain = p.then(() => undefined, () => undefined); return p; }; const directCallFor = (member) => { if (spec.deferSelfResolve === false) return undefined; const name = member.name; const executionMode = member.executionMode; return { real: { get parameters() { return member.parameters; }, invoke: (toolCallId, params, signal, onUpdate) => member.execute(toolCallId, params, signal, onUpdate), }, ...(executionMode !== undefined ? { executionMode } : {}), staticFace: () => staticFaceFor(name), activate: async () => serializeActivation(async () => { if (activeTools.has(name)) return undefined; activeTools.add(name); try { await rematerialize(activeTools); } catch (e) { activeTools.delete(name); throw e; } publishCensus(); return listingRideRef.current?.([name]); }), }; }; const placeholders = new WeakMap(); const placeholderOf = (member) => { let p = placeholders.get(member); if (p === undefined) placeholders.set(member, (p = createPlaceholderTool(registry.get(member.name), directCallFor(member)))); return p; }; const { messages } = await session.buildContext(); for (const n of extractDiscoveredToolNames(messages, registry)) { if (deferred.has(n)) activeTools.add(n); } for (const n of compactionActivationSnapshot(await session.getBranch())) { if (deferred.has(n)) activeTools.add(n); } if (resume) { for (const n of resume.seed.activeTools) if (deferred.has(n)) activeTools.add(n); } const callableToolNames = () => { const s = new Set(tools.map((t) => t.name)); for (const n of deferred) if (!activeTools.has(n)) s.delete(n); s.add(TOOL_SEARCH_NAME); return s; }; offloadReachableToolsRef.current = callableToolNames; let toolSearch; const buildToolList = (active) => { const list = tools.map((t) => (deferred.has(t.name) && (staticFaceFor(t.name) || !active.has(t.name)) ? placeholderOf(t) : t)); list.splice(perTurnStart(), 0, toolSearch); return list; }; const announcedTools = new Set(activeTools); const withdrawnTools = new Set(); const deltaRef = toolsDeltaRef; const rematerialize = async (active, source = "activation") => { contentOriginWrapRef.current?.(); const list = buildToolList(active); await harnessRef.current.setTools(list, list.map((t) => t.name)); turnSnapshotRef.current?.refreshTools(toolsToFingerprintInputs(list), source); const live = new Set(list.map((t) => t.name)); for (const n of [...announcedTools]) { if (!live.has(n)) { announcedTools.delete(n); withdrawnTools.add(n); deltaRef.pendingRemoved.push(n); } } for (const n of active) { if (!live.has(n)) continue; if (!announcedTools.has(n)) { announcedTools.add(n); if (withdrawnTools.delete(n)) deltaRef.pendingReadded.push(n); else deltaRef.pending.push(n); } } }; rebuildHarnessToolsRef.current = () => rematerialize(activeTools, "roster"); toolSearch = createToolSearchTool({ registry, active: activeTools, rematerialize, listingRide: (newly) => listingRideRef.current?.(newly), mountedNames: callableToolNames, directCallEnabled: spec.deferSelfResolve !== false, isMounted: (name) => tools.some((t) => t.name === name), ...(materializeStatic ? { staticSchemaFor: (name) => (staticFaceFor(name) ? answering(name)?.parameters : undefined) } : {}), onActivationCommitted: publishCensus, serializeActivation, inView: (name) => toolTableViewRef.current?.shows(name) !== false, }); harnessTools = buildToolList(activeTools); const rows = promptManifest.tools ?? [], at = perTurnStart(); promptManifest.tools = [...rows.slice(0, at), ...projectToolManifest([toolSearch], (t) => protocolOf(t.name)?.id ?? "caller"), ...rows.slice(at)]; publishCensus(); toolSearchMounted = toolSearch; } else { rebuildHarnessToolsRef.current = async () => { contentOriginWrapRef.current?.(); const list = [...tools]; await harnessRef.current.setTools(list, list.map((t) => t.name)); turnSnapshotRef.current?.refreshTools(toolsToFingerprintInputs(list), "roster"); }; } return { activeTools, turnSnapshotRef, harnessTools, toolsDeltaRef, mcpUnavailable, toolMaterializeStatic, deferDirectCall, staticFaceForRef, listingRideRef, toolTableViewRef, ...(toolSearchMounted !== undefined ? { toolSearch: toolSearchMounted } : {}), ...(toolDisclosureSeat !== undefined ? { toolDisclosureSeat } : {}) }; }