UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

261 lines (260 loc) • 14.6 kB
export const KERNEL_CONTRACT_VERSION = 13; export const MOD_TIERS = Object.freeze(["prepend", "user", "append", "builtin", "core"]); export const MOD_SEATS = Object.freeze(["deployment", "task"]); export const MOD_EVENT_SIDES = Object.freeze(["engine", "surface", "both"]); export const MOD_FAILURE_ANSWERS = Object.freeze(["refuse", "skip", "refuse_until_run"]); export function failureRefuses(failure) { return failure !== "skip"; } export const MOD_ABORT_POSTURES = Object.freeze(["immediate", "grace", "caller"]); export const NEXT_TO_TABLE = Object.freeze({ prepend: Object.freeze(["append", "builtin", "core"]), user: Object.freeze([]), append: Object.freeze(["core"]), builtin: Object.freeze([]), core: Object.freeze([]), }); const CONTINUABLE = NEXT_TO_TABLE.prepend; export function nextToRefusal(from, to) { const allowed = NEXT_TO_TABLE[from]; const named = CONTINUABLE.find((t) => t === to); if (named === undefined) return `next.to names ${describe(to)}, which is not a tier a dispatch continues at (${CONTINUABLE.join(", ")})`; if (allowed.length === 0) return `next.to is available to prepend and append handlers only, not to a ${from} handler`; if (!allowed.includes(named)) return `next.to("${named}") skips nothing from ${from}; a ${from} handler may continue at ${allowed.join(", ")}`; return undefined; } export const SEAT_TIER_TABLE = Object.freeze({ deployment: Object.freeze({ declared: "required", tiers: Object.freeze(["prepend", "user", "append"]) }), task: Object.freeze({ declared: "optional", tiers: Object.freeze(["user"]) }), }); const station = (failure, abort, pinned = [], more = {}) => Object.freeze({ failure, abort, pinned: Object.freeze([...pinned]), ...(more.call === true ? { call: Object.freeze({ pausesCallerBudget: true }) } : {}), ...(more.budgetMs !== undefined ? { budgetMs: more.budgetMs } : {}), ...(more.env !== undefined ? { env: more.env } : {}), ...(more.ownerOnly === true ? { ownerOnly: true } : {}), ...(more.closed === true ? { closed: true } : {}), ...(more.answers !== undefined ? { answers: Object.freeze([...more.answers]) } : {}), }); const method = (pausesCallerBudget, more = {}) => Object.freeze({ failure: "skip", abort: "caller", pinned: Object.freeze([]), method: Object.freeze({ pausesCallerBudget }), ...(more.env !== undefined ? { env: more.env } : {}) }); const timer = (repeats) => Object.freeze({ failure: "skip", abort: "caller", pinned: Object.freeze([]), method: Object.freeze({ pausesCallerBudget: false, timer: Object.freeze({ repeats }) }) }); const engine = (s) => Object.freeze(s === undefined ? { side: "engine" } : { side: "engine", station: s }); const surface = (s) => Object.freeze(s === undefined ? { side: "surface" } : { side: "surface", station: s }); const RENDER_PINNED = ["surface", "component", "requestId", "viewport"]; const ELEMENT_PINNED = ["plugin", "element", "component", "requestId", "surface"]; const PROMPT_EDIT_BUDGET_MS = 50; const AGENT_SPAWN_PINNED = [ "tool_use_id", "name", "fork", "isTeammate", "workflow", "parentModel", "permissionMode", "parentAgentId", "provider", "prompt", "description", "subagentType", "model", "background", "cwd", "identity", ]; export const MOD_EVENT_TABLE = Object.freeze({ "classic.PreToolUse": engine(station("refuse", "immediate", ["tool", "tool_use_id", "agentId", "input"], { env: "face" })), "classic.PostToolUse": engine(station("skip", "grace", [], { env: "face" })), "classic.PostToolUseFailure": engine(station("skip", "grace", [], { env: "face" })), "classic.PostToolBatch": engine(station("skip", "grace")), "classic.Notification": engine(), "classic.UserPromptSubmit": engine(station("refuse", "immediate", ["source", "inputId", "actor", "prompt"])), "classic.UserPromptExpansion": engine(), "classic.SessionStart": engine(station("skip", "grace", [], { env: "payload" })), "classic.SessionEnd": engine(station("skip", "grace")), "classic.Stop": engine(station("skip", "immediate")), "classic.StopFailure": engine(station("skip", "grace")), "classic.SubagentStart": engine(station("skip", "immediate", ["agentId", "agentType"])), "classic.SubagentStop": engine(station("skip", "immediate")), "classic.PreCompact": engine(station("skip", "grace")), "classic.PostCompact": engine(station("skip", "grace")), "classic.PreModelSwitch": engine(), "classic.PostModelSwitch": engine(), "classic.PermissionRequest": engine(), "classic.PermissionDenied": engine(station("skip", "grace")), "classic.Setup": engine(), "classic.TeammateIdle": engine(station("skip", "immediate")), "classic.TaskCreated": engine(station("skip", "immediate")), "classic.TaskCompleted": engine(station("skip", "immediate")), "classic.Elicitation": engine(), "classic.ElicitationResult": engine(), "classic.ConfigChange": engine(), "classic.WorktreeCreate": engine(), "classic.WorktreeRemove": engine(), "classic.InstructionsLoaded": engine(), "classic.CwdChanged": engine(), "classic.FileChanged": engine(), "classic.DirectoryAdded": engine(), "classic.MessageDisplay": engine(station("skip", "immediate", ["messageId", "turn", "index", "final", "agentId"], { budgetMs: 10_000 })), "tool.call": engine(station("refuse_until_run", "immediate", ["tool", "tool_use_id", "agentId", "input"], { call: true })), "tool.check": engine(station("refuse", "immediate", ["tool", "input", "tool_use_id", "agentId", "ceiling"])), "ui.render": surface(station("skip", "grace", RENDER_PINNED)), "ui.resolve": surface(station("skip", "grace", ["surface", "component"])), "ui.press": surface(station("skip", "grace", ELEMENT_PINNED)), "ui.input": surface(station("skip", "grace", ELEMENT_PINNED)), "ui.select": surface(station("skip", "grace", ELEMENT_PINNED)), "ui.message": surface(station("skip", "grace", ["surface", "component", "requestId", "element", "module"], { ownerOnly: true, closed: true, answers: ["props"] })), "ui.fault": surface(station("skip", "grace", ["surface", "component", "requestId", "element", "module", "phase", "reason"], { ownerOnly: true, closed: true, answers: [] })), "ui.scroll": surface(station("skip", "grace", ["component", "requestId", "by", "bodyRows", "contentRows", "origin", "pointer"], { call: true })), "ui.focus": surface(station("skip", "grace", ["component", "requestId", "plugin", "origin", "element"], { call: true })), "agent.offer": engine(station("skip", "grace", ["agent", "provider"])), "agent.spawn": engine(station("refuse_until_run", "immediate", AGENT_SPAWN_PINNED, { call: true })), "prompt.submit": engine(station("refuse", "immediate", ["source", "inputId", "actor", "author", "extension", "replyable"], { call: true })), "prompt.fill": surface(station("skip", "grace", ["origin", "mode"], { call: true })), "prompt.suggest": surface(station("skip", "grace", ["origin"], { call: true })), "prompt.edit": surface(station("skip", "grace", ["origin", "key"], { budgetMs: PROMPT_EDIT_BUDGET_MS })), "prompt.change": surface(), "prompt.autocomplete": surface(), "prompt.section": engine(station("skip", "grace", ["name", "key", "mountedTools"])), "prompt.context": engine(), "prompt.attachment": engine(), "prompt.mention": engine(station("refuse", "immediate", ["mention", "agentId"])), "prompt.compose": engine(station("skip", "grace", ["model", "catalog", "selectors"])), "tool.describe": engine(), "command.run": surface(station("skip", "grace", ["command", "presentation", "origin"], { call: true })), "command.describe": surface(station("skip", "grace", ["command", "immediate", "provider"])), "config.set": surface(station("refuse", "immediate", ["key", "previous", "provider", "origin"], { call: true })), "config.describe": surface(station("skip", "grace", ["key", "provider"])), "telemetry.log": engine(), "telemetry.mark": engine(), "skill.prompt": engine(), "attribution.text": engine(), "session.start": engine(station("skip", "grace", ["cwd", "sessionId", "agentId"], { env: "payload" })), "session.receive": engine(station("refuse", "immediate", ["origin", "event", "agentId"])), "session.append": engine(station("skip", "grace", ["door", "origin", "agentId"], { call: true })), "session.send": engine(station("refuse_until_run", "immediate", ["origin", "agentId", "to", "text"], { call: true })), "session.compact": engine(station("refuse_until_run", "immediate", ["trigger", "agentId", "instructions"], { call: true })), "session.attach": engine(), "session.detach": engine(), "session.measure": engine(station("skip", "grace", ["context", "changed", "agentId"])), "session.end": engine(station("skip", "grace", ["reason", "sessionId", "agentId"])), "plugin.register": Object.freeze({ side: "both", station: station("refuse", "immediate", ["name", "seat", "tier", "uses"]) }), "turn.start": engine(station("skip", "grace", ["turn", "agentId"])), "turn.step": engine(), "turn.complete": engine(station("skip", "grace", ["answer", "agentId", "turn"])), "engine.create": engine(), "model.complete": engine(method(true)), "model.classify": engine(), "model.fork": engine(), "audio.play": surface(), "audio.speak": surface(), "mcp.call": engine(), "mcp.connect": engine(), "session.cwd": engine(method(true, { env: "bottom" })), "session.root": engine(method(true, { env: "bottom" })), "session.model": engine(method(true)), "session.turns": engine(method(true)), "session.id": engine(method(true)), "session.messages": engine(method(true)), "session.repo": engine(), "session.surface": engine(), "session.surfaces": engine(), "session.authorize": engine(), "session.identity": engine(), "session.usage": engine(method(true)), "session.version": engine(method(true)), "turn.abort": engine(method(false)), "prompt.read": surface(method(true)), "prompt.paint": surface(), "flag.value": engine(), "tool.list": engine(method(true)), "tool.register": engine(), "command.list": surface(method(true)), "command.register": surface(method(true)), "config.list": surface(method(true)), "agent.list": engine(method(true)), "agent.register": engine(), "theme.set": surface(method(true)), "theme.clear": surface(method(true)), "decision.ask": engine(), "ui.toast": surface(method(true)), "ui.status": surface(method(true)), "ui.log": surface(method(true)), "ui.notice": surface(method(true)), "ui.invalidate": surface(method(true)), "ui.open": surface(method(true)), "ui.close": surface(method(true)), "ui.panes": surface(method(true)), "ui.place": surface(method(true)), "ui.selection": surface(method(true)), "ui.copy": surface(method(true)), "ui.view": surface(method(true)), "ui.notify": surface(method(true)), "ui.cancelNotify": surface(method(true)), "ui.blit": surface(method(true)), "fs.read": engine(), "fs.write": engine(), "fs.list": engine(), "fs.exists": engine(), "fs.stat": engine(), "fs.ancestors": engine(), "store.get": engine(), "store.set": engine(), "store.delete": engine(), "store.keys": engine(), "state.get": engine(), "state.set": engine(), "clock.now": engine(method(false)), "clock.sleep": engine(method(false)), "clock.after": engine(timer(false)), "clock.every": engine(timer(true)), "http.fetch": engine(), "process.run": engine(method(true, { env: "bottom" })), "process.spawn": engine(), "settings.read": engine(), "env.get": engine(), "env.set": engine(), }); const EVENT_NAMES = Object.freeze(Object.keys(MOD_EVENT_TABLE).filter(isModEventName)); export function isModEventName(name) { return typeof name === "string" && Object.prototype.hasOwnProperty.call(MOD_EVENT_TABLE, name); } export function stationOn(name, side) { const row = MOD_EVENT_TABLE[name]; return row.side === side || row.side === "both" ? row.station : undefined; } export function envReach(name, field) { const row = MOD_EVENT_TABLE[name]; const env = row.station?.env; if (field === "calls") return env === "bottom" ? "always" : undefined; return env === "payload" ? "always" : env === "face" ? "on_call" : undefined; } export const MOD_EVENTS_HANDING_ENV = Object.freeze(Object.keys(MOD_EVENT_TABLE).filter((n) => envReach(n, "events") === "on_call")); export function readOnSide(name, side) { const row = MOD_EVENT_TABLE[name]; return row.side === side || row.side === "both"; } export function expandModPattern(pattern) { if (typeof pattern !== "string" || pattern === "") return { refusal: `${describe(pattern)} is not an event name or a "<prefix>.*" pattern` }; if (pattern.endsWith(".*")) { const prefix = pattern.slice(0, -2); if (prefix === "" || prefix.includes("*")) return { refusal: `"${pattern}" is not an event name or a "<prefix>.*" pattern` }; const names = EVENT_NAMES.filter((n) => n.startsWith(`${prefix}.`)); return names.length > 0 ? { names } : { refusal: `"${pattern}" selects no event` }; } return isModEventName(pattern) ? { names: [pattern] } : { refusal: `"${pattern}" is not an event` }; } export function expandOnSide(pattern, side) { const expanded = expandModPattern(pattern); if ("refusal" in expanded) return expanded; const own = expanded.names.filter((n) => readOnSide(n, side)); if (own.length > 0) return { names: own }; const named = String(pattern); return named.endsWith(".*") ? { refusal: `"${named}" selects no event the ${side} bus reads (${expanded.names.length === 1 ? "its one name is" : "its names are"} the ${MOD_EVENT_TABLE[expanded.names[0]].side} side's)` } : { refusal: `"${named}" is a ${MOD_EVENT_TABLE[expanded.names[0]].side} event, read on that side's bus only — never on the ${side} bus` }; } export function describe(value) { if (typeof value === "string") return `"${value}"`; if (typeof value === "number" || typeof value === "boolean") return String(value); if (value === null) return "null"; return typeof value === "object" ? (Array.isArray(value) ? "an array" : "an object") : typeof value; }