UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

158 lines (157 loc) • 9.07 kB
import { ENGINE_ORIGIN } from "./kernel/index.js"; import { isPlainRecord } from "./kernel/receive.js"; import { NEXT_IN_FLIGHT } from "./kernel/site-rules.js"; import { describeThrown } from "../tool-policy.js"; import { foreignLine } from "../protocol-http-auth.js"; import { declaredDelegationNameOf } from "../delegation-name.js"; import { failedHandlerClause, seatHears } from "./stations.js"; import { agentIdOf } from "../leg-identity.js"; import { extensionCallOf, noteExtensionCallLaunched, requesterOf, runExtensionCall } from "./extension-call.js"; import { isExtensionCallId, mintExtensionCallId } from "../extension-call-id.js"; import { resultText } from "./tool-call.js"; const ENGINE_PROVIDER = Object.freeze({ plugin: ENGINE_ORIGIN.plugin, tier: ENGINE_ORIGIN.tier }); const OFFERED = Object.freeze({ isOffered: true }); function offerAnswer(answer) { if (!isPlainRecord(answer) || typeof answer["isOffered"] !== "boolean" || Object.keys(answer).some((k) => k !== "isOffered")) return "agent.offer takes next(e) or { isOffered: <boolean> }"; return undefined; } export async function offeredAgents(seat, agents, signal) { if (agents.length === 0 || !seatHears(seat, "agent.offer")) return agents; const out = []; for (const a of agents) { let outcome; try { outcome = await seat.bus.dispatch("agent.offer", { agent: a.name, description: a.description, provider: ENGINE_PROVIDER }, { bottom: () => OFFERED, checkAnswer: offerAnswer, ...(signal !== undefined ? { signal } : {}) }); } catch { out.push(a); continue; } if (outcome.kind === "answered" && isPlainRecord(outcome.answer) && outcome.answer["isOffered"] === false) continue; out.push(a); } return out; } export async function offeredAgentListing(seat, listing, signal) { if (listing === undefined) return undefined; const entries = await offeredAgents(seat, listing.entries, signal); return entries === listing.entries || entries.length === listing.entries.length ? listing : { ...listing, entries }; } export function spawnedModel(model) { return model ?? "inherit"; } const GO = Object.freeze({ go: true }); const FORM = "agent.spawn takes next(e) or { deny: <reason> } (every member is pinned: a spawn is refused, never rewritten)"; const denyOf = (a) => isPlainRecord(a) && Object.keys(a).length === 1 && typeof a["deny"] === "string" && a["deny"] !== "" ? a["deny"] : undefined; const RANKS = Object.freeze({ of: (a) => (denyOf(a) !== undefined ? 1 : 0), top: 1 }); export function createAgentStations(input) { return { listens: (event) => seatHears(input, event), offered: (agents, signal) => offeredAgents(input, agents, signal), extensionSpawn: (toolCallId) => { if (!isExtensionCallId(toolCallId)) return undefined; const call = extensionCallOf(input.bus, toolCallId); const requestedBy = requesterOf(input.bus, toolCallId).requestedBy; if (call === undefined || call.door !== "agent.spawn" || requestedBy === undefined) return undefined; return { by: call.caller.origin.plugin, requestedBy, launched: (agentId, model) => noteExtensionCallLaunched(input.bus, toolCallId, { agentId, model: spawnedModel(model) }) }; }, spawn: async (facts, signal) => { if (!seatHears(input, "agent.spawn")) return GO; const parentAgentId = agentIdOf(input.identity); const permissionMode = input.permissionMode(); const e = { ...(input.identity !== undefined ? { identity: input.identity } : {}), tool_use_id: facts.toolCallId, prompt: facts.prompt, description: facts.description, subagentType: facts.subagentType, provider: ENGINE_PROVIDER, ...(facts.model !== undefined ? { model: facts.model } : {}), ...(facts.parentModel !== undefined ? { parentModel: facts.parentModel } : {}), ...(parentAgentId !== undefined ? { parentAgentId } : {}), ...(permissionMode !== undefined ? { permissionMode } : {}), background: facts.background, fork: facts.fork, isTeammate: facts.name !== undefined, ...(facts.name !== undefined ? { name: facts.name } : {}), ...(facts.cwd !== undefined ? { cwd: facts.cwd } : {}), ...(facts.workflow === true ? { workflow: true } : {}), }; const started = Object.freeze({ model: spawnedModel(facts.model) }); const checkAnswer = (a, _e, _by, below, ran) => { if (a === started) return undefined; const reason = denyOf(a); if (reason === undefined) return FORM; if (ran.bottomStarted) return "a deny after the subagent was let start (once it starts, only its own run stands)"; if (below.includes(NEXT_IN_FLIGHT) || below.some((b) => denyOf(b) === undefined)) return "a deny while its next(e) still runs or after it was answered (deny in place of next)"; return undefined; }; let outcome; try { outcome = await input.bus.dispatch("agent.spawn", e, { bottom: () => started, checkAnswer, ranks: RANKS, ...(signal !== undefined ? { signal } : {}) }); } catch (err) { return { go: false, by: ENGINE_ORIGIN.plugin, reason: `the agent.spawn station could not be raised (${describeThrown(err)}); no subagent was started (fail-closed)` }; } if (outcome.kind === "aborted") return outcome.bottomStarted === true ? GO : { go: false, by: ENGINE_ORIGIN.plugin, reason: "the delegation was cancelled before its subagent started" }; if (outcome.kind === "failed") return { go: false, by: outcome.registration, reason: `an agent.spawn extension ${failedHandlerClause(outcome)} before the subagent started; no subagent was started (fail-closed)` }; if (outcome.answer === started) return GO; const by = outcome.answeredBy ?? ENGINE_ORIGIN.plugin; const reason = denyOf(outcome.answer); return { go: false, by, reason: reason !== undefined ? `extension "${foreignLine(by, 80)}" refused this delegation before its subagent started: ${foreignLine(reason, 300)}` : `extension "${foreignLine(by, 80)}" answered this delegation in a form agent.spawn does not take; no subagent was started (fail-closed)`, }; }, }; } const DESCRIPTION_WORDS = 5; function delegationInput(args, prompt) { return { prompt, description: args["description"] ?? prompt.split(/\s+/).slice(0, DESCRIPTION_WORDS).join(" "), run_in_background: true, ...(args["model"] !== undefined ? { model: args["model"] } : {}), ...(args["subagentType"] !== undefined ? { subagent_type: args["subagentType"] } : {}), ...(args["name"] !== undefined ? { name: args["name"] } : {}), ...(args["cwd"] !== undefined ? { cwd: args["cwd"] } : {}), }; } export function createAgentSpawnEntry(input) { return async (args, ctx) => { const by = ctx.origin.plugin; const prompt = args["prompt"]; if (typeof prompt !== "string" || prompt.trim() === "") throw new TypeError(`${by}: $.agent.spawn takes { prompt, ... } (a non-empty prompt)`); const tools = input.mounted().filter((name) => declaredDelegationNameOf(input.specOf(name)) !== undefined); const tool = tools[0]; if (tool === undefined) throw new TypeError(`${by}: $.agent.spawn: this run mounts no delegation tool`); if (tools.length > 1) throw new TypeError(`${by}: $.agent.spawn: this run mounts ${tools.length} delegation tools (${tools.map((n) => `"${foreignLine(n, 80)}"`).join(", ")}) and a spawn names none of them`); const toolCallId = mintExtensionCallId(); return runExtensionCall(input.bus, toolCallId, "agent.spawn", ctx, async (call) => { const finalized = await input.harness.callTool({ type: "toolCall", id: toolCallId, name: tool, arguments: delegationInput(args, prompt) }, ctx.signal, () => undefined); if (call.launched !== undefined) return Object.freeze({ model: call.launched.model, agentId: call.launched.agentId }); if (call.denied || finalized.isError) return Object.freeze({ deny: resultText(finalized.result.content) || "no subagent was started" }); return Object.freeze({ model: spawnedModel(typeof args["model"] === "string" ? args["model"] : undefined) }); }); }; }