UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

174 lines (173 loc) • 10.9 kB
import { formatHookFeedback } from "../reminder-mint.js"; import { toolFace } from "../tool-catalog-entries.js"; import { declaredDelegationNameOf } from "../delegation-name.js"; import { describeThrown } from "../tool-policy.js"; import { foreignLine } from "../protocol-http-auth.js"; import { readHandedRequestMeta } from "../mcp-call-meta.js"; import { ENGINE_ORIGIN } from "./kernel/index.js"; import { isPlainRecord } from "./kernel/receive.js"; import { NEXT_IN_FLIGHT } from "./kernel/site-rules.js"; import { classicEventBase, failedHandlerClause, judgedInputOf } from "./stations.js"; import { runExtensionCall } from "./extension-call.js"; import { mintExtensionCallId } from "../extension-call-id.js"; import { settleWithheldResult } from "../frame-settlement.js"; const FORM = "tool.call takes next(e), { deny: <reason> } or { result } (a string, or a list of text blocks)"; const denyOf = (a) => !isPlainRecord(a) || !Object.hasOwn(a, "deny") ? undefined : typeof a["deny"] === "string" && a["deny"] !== "" ? { reason: a["deny"] } : {}; function substituteOf(a) { if (!isPlainRecord(a) || Object.keys(a).length !== 1 || !Object.hasOwn(a, "result")) return undefined; const r = a["result"]; if (typeof r === "string") return [{ type: "text", text: r }]; if (!Array.isArray(r) || r.length === 0) return undefined; const out = []; for (const b of r) { if (!isPlainRecord(b) || b["type"] !== "text" || typeof b["text"] !== "string" || Object.keys(b).some((k) => k !== "type" && k !== "text")) return undefined; out.push({ type: "text", text: b["text"] }); } return out; } function viewOf(result) { let blocks = []; try { const content = result.content; blocks = (Array.isArray(content) ? content : []).map((b) => Object.freeze(Object.fromEntries(Object.entries(typeof b === "object" && b !== null ? b : {}).filter(([, v]) => v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean")))); } catch { blocks = []; } return Object.freeze({ result: Object.freeze({ content: Object.freeze([...blocks]), isError: result.isError === true }) }); } function letGoUnasked(occurrences, toolCallId) { const latest = occurrences.get(toolCallId)?.gateRounds.at(-1); if (latest === undefined || latest.disposition.kind !== "allowed" || latest.settlement !== undefined) return false; return latest.disposition.released === undefined && latest.disposition.clearedBy === undefined; } const RANKS = Object.freeze({ of: (a) => (denyOf(a) !== undefined ? 1 : 0), top: 1 }); export function createToolCallStation(input) { if (!input.bus.hasHandlers("tool.call")) return undefined; const stationAnswer = (call, by, text) => { const content = [{ type: "text", text: formatHookFeedback(text, input.reminderMark) }]; if (by !== undefined) { if (input.occurrences.get(call.toolCallId) !== undefined) { input.occurrences.refuse(call.toolCallId, "hook", { extension: by }); input.occurrences.answeredInPlace(call.toolCallId, by); } input.blockedToolCalls.add(call.toolCallId); } else if (input.frameSettlement !== undefined) settleWithheldResult(input.frameSettlement, call.toolCallId, content); return { content, details: {}, isError: true }; }; return async (call, run, signal) => { const e = { ...classicEventBase(input.identity), tool: call.toolName, tool_use_id: call.toolCallId, input: judgedInputOf(call.args) }; const bodies = new Map(); let body; const judged = new WeakMap(); const checkHandOn = (payload) => { const read = readHandedRequestMeta(payload); if ("problem" in read) return `next() handed on a requestMeta the call cannot carry: ${read.problem}`; judged.set(payload, read.meta); return undefined; }; const bottom = async (handed) => { body = input.requestMeta.hold(call.toolCallId, judged.get(handed), run); const result = await body; const view = viewOf(result); bodies.set(view, result); return view; }; const checkAnswer = (a, _e, _by, below, ran) => { if (typeof a === "object" && a !== null && bodies.has(a)) return undefined; const denied = denyOf(a) !== undefined; if (!denied && substituteOf(a) === undefined) return FORM; if (denied && ran.bottomStarted) return below.some((b) => b !== NEXT_IN_FLIGHT) ? undefined : "a deny after the tool started with no answer from its next(e) to withhold (it still runs, or the tool threw: the throw stands)"; if (ran.bottomStarted) return "a result after the tool started (once the tool runs, nothing answers in its place)"; if (denied) return below.some((b) => denyOf(b) === undefined) ? "a deny while its next(e) still runs or after it was answered (deny in place of next)" : undefined; if (below.includes(NEXT_IN_FLIGHT)) return "a result while its next(e) still runs (result in place of next)"; return letGoUnasked(input.occurrences, call.toolCallId) ? undefined : "a result in place of a call someone was asked about (a person's or a rule's yes is a yes to running the tool, so only the tool answers it)"; }; let outcome; try { outcome = await input.bus.dispatch("tool.call", e, { bottom, checkAnswer, checkHandOn, ranks: RANKS, ...(signal !== undefined ? { signal } : {}) }); } catch (err) { if (body !== undefined) return body; return stationAnswer(call, ENGINE_ORIGIN.plugin, `the tool.call station could not be raised (${describeThrown(err)}); this call to "${foreignLine(call.toolName, 80)}" was NOT executed (fail-closed)`); } if (outcome.kind === "aborted") { if (body !== undefined) return body; return { content: [{ type: "text", text: "Operation aborted" }], details: {}, isError: true }; } if (outcome.kind === "failed") return stationAnswer(call, outcome.registration, `a tool.call extension ${failedHandlerClause(outcome)} before this call to "${foreignLine(call.toolName, 80)}" ran; the call was NOT executed (fail-closed)`); const answer = outcome.answer; const ran = typeof answer === "object" && answer !== null ? bodies.get(answer) : undefined; if (ran !== undefined) return ran; const by = outcome.answeredBy ?? ENGINE_ORIGIN.plugin; const deny = denyOf(answer); if (deny !== undefined) { if (deny.reason === undefined) input.report(new Error(`${by}: tool.call: its deny gave no readable reason (a reason is a non-empty string) — the deny stands`)); const why = deny.reason !== undefined ? `: ${foreignLine(deny.reason, 300)}` : " (it gave no readable reason)"; if (body !== undefined) return stationAnswer(call, undefined, `this call to "${foreignLine(call.toolName, 80)}" ran, and extension "${foreignLine(by, 80)}" withheld its result${why} — the call was executed and whatever it did has happened; it is only its result that is not shown`); return stationAnswer(call, by, `extension "${foreignLine(by, 80)}" refused this call to "${foreignLine(call.toolName, 80)}" before it ran${why}`); } const content = substituteOf(answer); if (content === undefined) return stationAnswer(call, by, `extension "${foreignLine(by, 80)}" answered this call in a form tool.call does not take; the call was NOT executed (fail-closed)`); if (input.occurrences.get(call.toolCallId) !== undefined) input.occurrences.answeredInPlace(call.toolCallId, by); input.blockedToolCalls.add(call.toolCallId); return { content, details: {} }; }; } const AGENT_DOOR = "runs the Agent tool: that is $.agent.spawn"; const OTHER_DOOR = new Map([ [toolFace("ask-user-question").contract.contractId, "runs the AskUserQuestion tool, which puts a question to the person: an extension's call does not ask the person"], [toolFace("workflow").contract.contractId, "runs the Workflow tool, whose agents run outside the tree's bound on agents running at once (RunnerDeps.delegationEntryCaps.maxConcurrent): $.agent.spawn is the door"], ]); export function createToolCallEntry(input) { return async (args, ctx) => { const by = ctx.origin.plugin; const { tool, ...callInput } = args; if (typeof tool !== "string" || tool === "") throw new TypeError(`${by}: $.tool.call takes the event's input: { tool, ...args }`); const toolCallId = mintExtensionCallId(); return runExtensionCall(input.bus, toolCallId, "tool.call", ctx, async (call) => { const finalized = await input.harness.callTool({ type: "toolCall", id: toolCallId, name: tool, arguments: { ...callInput } }, ctx.signal, (t) => { const contractId = input.faceOf(t.name)?.contractId; const door = declaredDelegationNameOf(input.specOf(t.name)) !== undefined ? AGENT_DOOR : contractId !== undefined ? OTHER_DOOR.get(contractId) : undefined; if (door !== undefined) throw new TypeError(`${by}: $.tool.call(${foreignLine(t.name, 80)}) ${door}`); }); if (call.denied) return Object.freeze({ deny: resultText(finalized.result.content) }); return viewOf({ ...finalized.result, isError: finalized.isError }); }); }; } export function extensionCallOverlap(input) { const others = input.occurrences.live().filter((o) => o.toolCallId !== input.toolCallId); if (!input.batchSafe(input.toolName, input.args)) { return others.length === 0 ? undefined : `${foreignLine(input.toolName, 80)}: an extension's call of a tool that has the run to itself cannot run while another call is in flight`; } const exclusive = others.find((o) => o.life === "released" && !input.batchSafe(o.wireName ?? o.spelledName, o.finalInput ?? o.args)); return exclusive === undefined ? undefined : `${foreignLine(input.toolName, 80)}: an extension's call cannot run beside "${foreignLine(exclusive.wireName ?? exclusive.spelledName, 80)}", which has the run to itself`; } export const resultText = (content) => (Array.isArray(content) ? content.map((b) => (isPlainRecord(b) && b["type"] === "text" && typeof b["text"] === "string" ? b["text"] : "")).join("") : "");