UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

740 lines (739 loc) • 37.6 kB
import { types } from "node:util"; import { engineVersion } from "../version.js"; import { askPerModelAuth } from "../../brain/route-adjudicator.js"; import { resolveModel, resolveTaskModel } from "../roles.js"; import { brainToRuntime } from "../runtime.js"; import { deliverEngineNotice } from "../engine-notice.js"; import { foreignLine } from "../protocol-http-auth.js"; import { askApproverIdentity, describeThrown, ownArgs } from "../tool-policy.js"; import { agentIdOf } from "../leg-identity.js"; import { admitMods, expandOnSide } from "./kernel/index.js"; import { legBusOf } from "./extension-call.js"; import { validateOverlay } from "../../prompt-assembly/overlay.js"; import { isBlankInput, steeringTextDefect, steeringTextDefectClause } from "../input-author.js"; import { modsInvalid } from "./kernel/registration.js"; import { isPlainRecord } from "./kernel/receive.js"; import { NEXT_IN_FLIGHT } from "./kernel/site-rules.js"; import { matcherUnderView } from "../tool-name-aliases.js"; import { engineMethodBottoms } from "./dollar.js"; import { modsReportToOnError, registrationRefusedNotice } from "./host.js"; import { recordStationRaise } from "./station-receipt.js"; export { listLegModSeats } from "./host.js"; import { scopedLegBus, skillScopeRecord, standingBus } from "./spec-seats.js"; import { modelLaneBrainOf } from "../runner/model-lane-seat.js"; import { observingBrain } from "../runner/prefix-ledger.js"; import { judgeRowForSeat, readJudgedRow } from "../runner/delegation-owner.js"; export const ENGINE_CORE_ANSWER = Object.freeze({}); export function engineCore() { return ENGINE_CORE_ANSWER; } export function seatHears(binding, event) { return binding !== undefined && binding.bus.hasHandlers(event); } export function legNoticeTaskId(leg) { return { taskId: leg.taskId }; } const TOP_LEVEL_LEG = Object.freeze({ stop: "classic.Stop", display: "classic.MessageDisplay" }); const DELEGATED_LEG = Object.freeze({ start: "classic.SubagentStart", stop: "classic.SubagentStop" }); export function legEventsOf(identity) { return identity?.isDelegatedChild === true ? DELEGATED_LEG : TOP_LEVEL_LEG; } export function judgedInputOf(args) { const owned = ownArgs(args); return owned.ok ? owned.value : args; } export function admittedChainOf(bus, spec, deps) { const offered = new Map(); for (const r of [...(deps.mods ?? []), ...(spec.mods ?? [])]) offered.set(r.name, r); const hung = bus.mounted(); const links = []; for (const rec of bus.records) { if ("refusedBy" in rec) continue; const registration = offered.get(rec.name); if (registration !== undefined) links.push(Object.freeze({ registration, handlers: Object.freeze(hung.filter((h) => h.plugin === rec.name)) })); } return Object.freeze(links); } const ADMITTED_CHAINS = new WeakMap(); function recordAdmittedChain(bus, seats) { const chain = admittedChainOf(bus, { ...(seats.task !== undefined ? { mods: [...seats.task] } : {}) }, { ...(seats.deployment !== undefined ? { mods: [...seats.deployment] } : {}) }); ADMITTED_CHAINS.set(bus, chain); return chain; } export function chainOfBus(bus) { return ADMITTED_CHAINS.get(bus); } const sameMatcher = (a, b) => { if (a === undefined || b === undefined) return a === b; const ka = Object.keys(a).sort(); const kb = Object.keys(b).sort(); return ka.length === kb.length && ka.every((k, i) => k === kb[i] && a[k] === b[k]); }; const sameHandler = (a, b) => a.seat === b.seat && a.pattern === b.pattern && a.observe === b.observe && a.caught === b.caught && sameMatcher(a.matcher, b.matcher); function sameModLink(a, b) { return a.registration === b.registration && a.handlers.length === b.handlers.length && a.handlers.every((h, j) => sameHandler(h, b.handlers[j])); } export function sameModChain(a, b) { return a.length === b.length && a.every((l, i) => sameModLink(l, b[i])); } const judgesCall = (p) => !p.observe; export function chainJudges(bus) { return bus.hasHandlers("classic.PreToolUse", judgesCall) || bus.hasHandlers("tool.check", judgesCall); } export function sameInstallation(pc, leg) { const bus = pc.installation; const chain = bus !== undefined ? chainOfBus(bus) : undefined; return (chain !== undefined && sameModChain(chain, leg.chain) && askApproverIdentity(pc.onAsk) === askApproverIdentity(leg.onAsk) && (pc.durableMandate === true) === leg.durableMandate && (pc.contentMandate === true) === leg.contentMandate && pc.hookEnv === leg.hookEnv && pc.autoMode?.decider === leg.decider); } export function standsInFor(pc, leg, legChainJudges) { return legChainJudges && sameInstallation(pc, { ...leg, durableMandate: false, contentMandate: false }); } export function chainEntryFault(entries) { for (const [i, pc] of entries.entries()) { const policy = pc.policy !== undefined; const installation = pc.installation; if (policy === (installation !== undefined)) return `inherited chain entry ${i} carries ${policy ? "both a policy and an installation" : "neither a policy nor an installation"} — an entry is either a caller policy or a screening installation`; if (installation !== undefined && chainOfBus(installation) === undefined) return `inherited chain entry ${i}'s installation is not a chain an engine admission mounted — rebuild it with admitModChain over the same registrations`; } return undefined; } const judges = (p) => judgesCall(p); export function inheritedInstallations(entries, standsIn, envOf, settleOf, standingOf) { const fault = chainEntryFault(entries); if (fault !== undefined) throw modsInvalid(fault); const installations = []; for (const pc of entries) { const bus = pc.installation; if (bus === undefined || standsIn(pc) || !chainJudges(bus)) continue; const env = envOf(pc); installations.push(Object.freeze({ bus, judges, ...(env !== undefined ? { env } : {}), settle: settleOf(pc), ...(standingOf !== undefined ? { standing: standingOf(pc) } : {}) })); } return Object.freeze(installations); } export function classicEventBase(identity, permissionMode) { const agentId = agentIdOf(identity); return { ...(identity !== undefined ? { identity } : {}), ...(agentId !== undefined ? { agentId } : {}), ...(permissionMode !== undefined ? { permissionMode } : {}), }; } export async function observeClassic(bus, event, e, signal) { if (!bus.hasHandlers(event)) return; try { await bus.dispatch(event, e, { bottom: engineCore, ...(signal !== undefined ? { signal } : {}) }); } catch { } } export async function dispatchClassic(bus, event, e, options) { if (!bus.hasHandlers(event, options.participant)) return undefined; const check = options.checkAnswer; return await bus.dispatch(event, e, { bottom: engineCore, ...(options.raisedUnder !== undefined ? { frames: options.raisedUnder.frames, origin: options.raisedUnder.origin } : {}), ...(options.participant !== undefined ? { participant: options.participant } : {}), ...(options.signal !== undefined ? { signal: options.signal } : {}), ...(check !== undefined ? { checkAnswer: (a, ce, by, below, run) => (a === ENGINE_CORE_ANSWER ? undefined : check(a, ce, by, below, run)) } : {}), ...(options.ranks !== undefined ? { ranks: options.ranks } : {}), }); } export function stringMembersAnswer(event, members) { return (answer) => { if (answer === null || answer === false) return undefined; if (typeof answer !== "object") return `answered ${typeof answer}; ${event} takes { ${members.map((m) => `${m}?`).join(", ")} }`; for (const m of members) { const v = Reflect.get(answer, m); if (v !== undefined && typeof v !== "string") return `answered a ${typeof v} "${m}"; it is a string`; } return undefined; }; } export function stringMembersOf(answer, members) { const out = {}; if (typeof answer !== "object" || answer === null) return out; for (const m of members) { const v = Reflect.get(answer, m); if (typeof v === "string") out[m] = v; } return out; } const FAILURE_CLAUSE = Object.freeze({ threw: (who, tail) => `crashed (extension "${who}"${tail})`, timeout: (who, tail) => `did not answer (extension "${who}"${tail})`, violation: (who, tail) => `gave an answer the station cannot take (extension "${who}"${tail})`, reentry: (who, tail) => `was skipped on re-entry and its .catch did not answer (extension "${who}"${tail})`, }); export function failedHandlerClause(f) { return FAILURE_CLAUSE[f.cause](foreignLine(f.registration, 80), ` ${foreignLine(f.reason, 200)}`); } export async function observePermissionDenied(input) { const { payload, host } = input; const e = { ...payload, ...classicEventBase(payload.identity, payload.permissionMode) }; if (input.legBus?.hasHandlers("classic.PermissionDenied") === true) await observeClassic(input.legBus, "classic.PermissionDenied", e, input.signal); if (host === undefined) return; const own = await admitModChain({ deployment: [ { name: "toolGate.permissionDenied", tier: "user", uses: { events: ["classic.PermissionDenied"], calls: [] }, register: (on) => on("classic.PermissionDenied", async () => void (await host.observe(payload)), { observe: true }), }, ], }, host.onFailure); await observeClassic(own, "classic.PermissionDenied", e, input.signal); } const USER_PROMPT_RANKS = Object.freeze({ of: (a) => (stringMembersOf(a, ["block"]).block ? 1 : 0), top: 1 }); export function textChanges(original) { const changers = []; const note = (by) => { if (!changers.includes(by)) changers.push(by); }; let before = original; return { handedOn: (by, text, refuse) => { if (text === before) return undefined; const refusal = refuse?.(text); if (refusal !== undefined) return refusal; note(by); before = text; return undefined; }, answered: (by, text, handed, below, refuse) => { if (text === (below ?? handed)) return undefined; const refusal = refuse?.(text); if (refusal !== undefined) return refusal; note(by); return undefined; }, rewrittenBy: () => Object.freeze([...changers]), }; } export const PROMPT_SCREEN_STATIONS = Object.freeze(["prompt.submit", "classic.UserPromptSubmit"]); function promptScreenHeard(hears) { return PROMPT_SCREEN_STATIONS.some(hears); } export function promptScreenHasHandlers(bus) { return promptScreenHeard((station) => bus.hasHandlers(station)); } export function promptScreenDeclaredBy(registrations) { const selected = new Set(); for (const registration of registrations) { const patterns = registration?.uses?.events; if (!Array.isArray(patterns)) continue; for (const pattern of patterns) { const expanded = expandOnSide(pattern, "engine"); if ("names" in expanded) for (const name of expanded.names) selected.add(name); } } return promptScreenHeard((station) => selected.has(station)); } const PROMPT_ENTRANCES = Object.freeze({ objective: Object.freeze({ replyable: "always", steering: false }), steer: Object.freeze({ replyable: "later", steering: true }), resume_message: Object.freeze({ replyable: "never", steering: true }), followUp: Object.freeze({ replyable: "never", steering: true }), parked_redelivery: Object.freeze({ replyable: "never", steering: true }), system: Object.freeze({ replyable: "later", steering: true }), }); function entranceOf(source) { return typeof source === "string" && Object.hasOwn(PROMPT_ENTRANCES, source) ? PROMPT_ENTRANCES[source] : undefined; } function entranceReplyable(source, tier) { const row = entranceOf(source)?.replyable; return row === "always" || (row === "later" && tier === "later"); } function changedTextClause(source, text) { if (entranceOf(source)?.steering !== true) return undefined; const defect = steeringTextDefect(text); if (defect !== undefined) return steeringTextDefectClause(defect); return isBlankInput(text) ? "says nothing (only whitespace and control characters; answer { drop: <reason> } to refuse an input)" : undefined; } const PROMPT_SUBMIT_FORM = "prompt.submit takes { text } (a string), { reply } (a non-empty string, where e.replyable is true) or { drop: <reason> }"; function readSubmitAnswer(a) { if (!isPlainRecord(a)) return { why: PROMPT_SUBMIT_FORM }; const keys = Object.keys(a); if (keys.length === 1 && keys[0] === "drop") { const r = a["drop"]; return typeof r === "string" && r.trim() !== "" ? { drop: r } : { why: "a drop that is not a reason (a non-empty string)" }; } if (keys.length === 1 && keys[0] === "reply") { const r = a["reply"]; if (typeof r !== "string" || isBlankInput(r)) return { why: "a reply that is not a non-empty string" }; const defect = steeringTextDefect(r); return defect === undefined ? { reply: r } : { why: `a reply that ${steeringTextDefectClause(defect)}` }; } if (keys.length === 1 && keys[0] === "text") { const t = a["text"]; return typeof t === "string" ? { text: t } : { why: "a text that is not a string" }; } return { why: PROMPT_SUBMIT_FORM }; } const PROMPT_SUBMIT_RANKS = Object.freeze({ of: (a) => (!isPlainRecord(a) ? 0 : Object.hasOwn(a, "drop") ? 2 : Object.hasOwn(a, "reply") ? 1 : 0), top: 2, }); const OPERATOR_SCREEN = Object.freeze({ author: "operator" }); export async function screenUserPrompt(bus, e, signal, input = OPERATOR_SCREEN) { if (!promptScreenHasHandlers(bus)) return undefined; const { prompt, ...classicFacts } = e; const replyable = entranceReplyable(e.source, input.tier); const facts = { ...classicFacts, author: input.author, ...(input.extension !== undefined ? { extension: input.extension } : {}), replyable }; const raisedUnder = input.raisedUnder; const changes = textChanges(prompt); const refusedWith = (lead) => (text) => { const clause = changedTextClause(e.source, text); return clause === undefined ? undefined : `${lead} ${clause}`; }; const checkHandOn = (handed, by) => { const t = handed["text"]; if (typeof t !== "string") return "next() handed on a text that is not a string"; return changes.handedOn(by.plugin, t, refusedWith("next() handed on a text that")); }; const seen = {}; const bottom = async (handed) => { const text = handed["text"]; const classic = await screenClassicPrompt(bus, { ...e, prompt: text }, signal, raisedUnder); if (classic !== undefined) seen.classic = classic; if (classic === undefined || (classic.kind === "answered" && !classic.block)) return Object.freeze({ text }); return Object.freeze({ drop: classic.kind === "answered" ? classic.block : "the classic.UserPromptSubmit screen did not clear the prompt" }); }; const replyEnters = new WeakMap(); const checkAnswer = (a, handed, by, below) => { const read = readSubmitAnswer(a); if ("why" in read) return read.why; if ("reply" in read && !replyable) return `answered { reply } at the ${e.source} entrance, which takes none (e.replyable is false): answer { text } or { drop }`; const last = below.length > 0 ? below[below.length - 1] : undefined; if ("reply" in read && below.includes(NEXT_IN_FLIGHT)) return "answered { reply } while its next(e) still ran — the text the input enters as was not settled"; const up = last !== undefined ? readSubmitAnswer(last) : undefined; if ("text" in read) { const refused = changes.answered(by.plugin, read.text, handed["text"], up !== undefined && "text" in up ? up.text : undefined, refusedWith("a text that")); if (refused !== undefined) return refused; } if ("reply" in read && isPlainRecord(a)) { const carried = up !== undefined && "reply" in up && isPlainRecord(last) ? replyEnters.get(last) : undefined; replyEnters.set(a, carried ?? (up !== undefined && "text" in up ? up.text : handed["text"])); } return undefined; }; let outcome; const raise = () => bus.dispatch("prompt.submit", { ...facts, text: prompt }, { bottom, checkAnswer, checkHandOn, ranks: PROMPT_SUBMIT_RANKS, ...(signal !== undefined ? { signal } : {}), ...(raisedUnder !== undefined ? { frames: raisedUnder.frames, origin: raisedUnder.origin } : {}) }); try { outcome = await (input.whileScreened === undefined ? raise() : input.whileScreened({ source: e.source, ...(e.inputId !== undefined ? { inputId: e.inputId } : {}) }, raise)); } catch (err) { return { kind: "failed", registration: "engine", cause: "threw", reason: `could not raise the screen: ${describeThrown(err)}`, skipped: [] }; } const classic = seen.classic; if (classic !== undefined && (classic.kind !== "answered" || classic.block)) return classic.kind === "answered" ? { ...classic, text: prompt } : classic; if (outcome.kind !== "answered") return outcome; const read = readSubmitAnswer(outcome.answer); const by = outcome.answeredBy ?? "engine"; const context = classic?.kind === "answered" && classic.additionalContext !== undefined ? { additionalContext: classic.additionalContext } : {}; if ("drop" in read) return { kind: "answered", text: prompt, block: read.drop }; if ("why" in read) return { kind: "failed", registration: by, cause: "violation", reason: read.why, skipped: [] }; if ("reply" in read) { const entered = isPlainRecord(outcome.answer) ? replyEnters.get(outcome.answer) : undefined; if (entered === undefined) return { kind: "failed", registration: "engine", cause: "threw", reason: "a reply the screen did not judge", skipped: [] }; return { kind: "answered", text: entered, ...(entered !== prompt ? { rewrittenBy: changes.rewrittenBy() } : {}), reply: { text: read.reply, by }, ...context }; } if (read.text === prompt) return { kind: "answered", text: prompt, ...context }; return { kind: "answered", text: read.text, rewrittenBy: changes.rewrittenBy(), ...context }; } async function screenClassicPrompt(bus, e, signal, raisedUnder) { let outcome; try { outcome = await dispatchClassic(bus, "classic.UserPromptSubmit", e, { ...(signal !== undefined ? { signal } : {}), ...(raisedUnder !== undefined ? { raisedUnder } : {}), checkAnswer: stringMembersAnswer("classic.UserPromptSubmit", ["block", "additionalContext"]), ranks: USER_PROMPT_RANKS, }); } catch (err) { return { kind: "failed", registration: "engine", cause: "threw", reason: `could not raise the screen: ${describeThrown(err)}`, skipped: [] }; } if (outcome === undefined) return undefined; if (outcome.kind !== "answered") return outcome; return { kind: "answered", ...stringMembersOf(outcome.answer, ["block", "additionalContext"]) }; } const subagentStartMembers = stringMembersAnswer("classic.SubagentStart", ["additionalContext"]); function subagentStartAnswer(answer) { const refused = subagentStartMembers(answer); if (refused !== undefined) return refused; if (typeof answer === "object" && answer !== null && Reflect.get(answer, "block") !== undefined) { return `answered "block"; classic.SubagentStart cannot keep a subagent from starting (it starts all the same) — a deployment refuses the delegating call at classic.PreToolUse`; } return undefined; } export async function openSubagent(bus, identity, permissionMode, signal) { const e = { ...classicEventBase(identity, permissionMode), agentId: identity.taskId, ...(identity.agentType !== undefined ? { agentType: identity.agentType } : {}), }; let outcome; try { outcome = await dispatchClassic(bus, "classic.SubagentStart", e, { ...(signal !== undefined ? { signal } : {}), checkAnswer: subagentStartAnswer }); } catch { return undefined; } recordStationRaise(bus, "classic.SubagentStart", [outcome]); return outcome?.kind === "answered" ? stringMembersOf(outcome.answer, ["additionalContext"]) : undefined; } export const TOOL_CHECK_DECISIONS = Object.freeze(["allow", "ask", "deny"]); const isToolCheckDecision = (v) => TOOL_CHECK_DECISIONS.some((d) => d === v); const TOOL_CHECK_RANKS = Object.freeze({ of: (a) => { const read = readToolCheckAnswer(a); return typeof read === "string" ? 0 : read.decision === "deny" ? 2 : read.decision === "ask" ? 1 : 0; }, top: 2, }); function readToolCheckAnswer(answer) { if (typeof answer !== "object" || answer === null) return `answered ${answer === null ? "null" : typeof answer}; tool.check takes { decision, reason? }`; const decision = Reflect.get(answer, "decision"); const reason = Reflect.get(answer, "reason"); if (!isToolCheckDecision(decision)) return `no { decision } (one of ${TOOL_CHECK_DECISIONS.join(", ")})`; if (reason !== undefined && typeof reason !== "string") return `answered a ${typeof reason} "reason"; it is a string`; return { decision, ...(reason !== undefined ? { reason } : {}) }; } export async function raiseToolCheck(bus, e, projection, signal, judges) { if (!bus.hasHandlers("tool.check", judges)) return undefined; let outcome; try { outcome = await bus.dispatch("tool.check", e, { bottom: () => projection, ...(judges !== undefined ? { participant: judges } : {}), ...(signal !== undefined ? { signal } : {}), checkAnswer: (a) => { const read = readToolCheckAnswer(a); return typeof read === "string" ? read : undefined; }, ranks: TOOL_CHECK_RANKS, }); } catch (err) { return { kind: "failed", registration: "engine", cause: "threw", reason: `could not raise the check: ${describeThrown(err)}`, skipped: [] }; } if (outcome.kind !== "answered") return outcome; const read = readToolCheckAnswer(outcome.answer); if (typeof read === "string") return { kind: "failed", registration: outcome.answeredBy ?? "engine", cause: "violation", reason: read, skipped: outcome.skipped }; return { kind: "answered", ...read, ...(outcome.answeredBy !== undefined ? { by: outcome.answeredBy } : {}) }; } const NO_COMPOSE = Object.freeze({ deploy: Object.freeze([]), task: Object.freeze([]), warnings: Object.freeze([]) }); function composeOverlaysOf(answer) { if (!isPlainRecord(answer)) return `answered ${answer === null ? "null" : Array.isArray(answer) ? "an array" : typeof answer}; prompt.compose takes { overlays }`; const stray = Object.keys(answer).filter((k) => k !== "overlays"); if (stray.length > 0) return `the answer carries ${stray.slice(0, 5).map((k) => JSON.stringify(foreignLine(k, 40))).join(", ")} (overlays only)`; const overlays = answer["overlays"]; return Array.isArray(overlays) ? overlays : "the answer's overlays is not an array"; } export async function raisePromptCompose(bus, e, options) { if (!bus.hasHandlers("prompt.compose")) return NO_COMPOSE; const sourceOf = (seat) => (seat === "deployment" ? "deploy" : "task"); const bottom = Object.freeze({ overlays: Object.freeze([]) }); const taken = new WeakMap([[bottom, Object.freeze([])]]); const HEAD = "the answer does not carry what next() returned unchanged at its head (a handler adds overlays; it never rewrites or removes another's)"; let outcome; try { outcome = await bus.dispatch("prompt.compose", e, { bottom: () => bottom, ...(options.signal !== undefined ? { signal: options.signal } : {}), checkAnswer: (answer, _e, by, below) => { if (typeof answer === "object" && answer !== null && taken.has(answer)) return undefined; const mine = composeOverlaysOf(answer); if (typeof mine === "string") return mine; const returned = below[below.length - 1]; const lower = typeof returned === "object" && returned !== null ? taken.get(returned) : undefined; if (lower === undefined) { return below.length === 0 ? "it answered without next(e) — prompt.compose collects: a handler awaits next(e) and adds after what it returned" : "next() is still running; prompt.compose answers after it"; } if (mine.length < lower.length) return HEAD; const out = [...lower]; for (let i = 0; i < mine.length; i++) { const under = lower[i]; const v = validateOverlay(mine[i], { source: sourceOf(under?.by.seat ?? by.seat), event: "prompt.compose", lowerAdds: options.lowerAdds }); if (under !== undefined) { if ("violation" in v || JSON.stringify(v.overlay) !== JSON.stringify(under.overlay)) return HEAD; continue; } if ("violation" in v) return v.violation; out.push(Object.freeze({ overlay: v.overlay, by: Object.freeze({ plugin: by.plugin, seat: by.seat }) })); } taken.set(answer, Object.freeze(out)); return undefined; }, }); } catch (err) { return { deploy: [], task: [], warnings: [`prompt.compose could not be raised (${describeThrown(err)}); no mods overlay applies this run`] }; } const warnings = (outcome.kind === "aborted" ? [] : outcome.skipped).map((s) => `prompt.compose: extension "${foreignLine(s.registration, 80)}" ${s.cause === "violation" ? "gave an answer the station cannot take" : s.cause}: ${foreignLine(s.reason, 300)} — that answer is skipped; what is below it stands`); if (outcome.kind !== "answered") return { deploy: [], task: [], warnings }; const answer = outcome.answer; const contributions = typeof answer === "object" && answer !== null ? taken.get(answer) : undefined; if (contributions === undefined) return { deploy: [], task: [], warnings: [...warnings, "prompt.compose: the chain's answer is not one the station took; no mods overlay applies this run"] }; const blocks = []; for (const { overlay, by } of contributions) { const item = { overlay, origin: { source: sourceOf(by.seat), by: by.plugin } }; const last = blocks[blocks.length - 1]; if (last !== undefined && last.by.plugin === by.plugin && last.by.seat === by.seat) last.items.push(item); else blocks.push({ by, items: [item] }); } const inChainOrder = blocks.reverse().flatMap((b) => b.items); return { deploy: Object.freeze(inChainOrder.filter((o) => o.origin.source === "deploy")), task: Object.freeze(inChainOrder.filter((o) => o.origin.source === "task")), warnings, }; } function lateView() { let seats; const need = (method) => { if (seats === undefined) throw new Error(`${method}: the engine facade is not available before the leg is prepared`); return seats; }; const view = { env: { exec: (command, options) => need("process.run").exec(command, options) }, complete: (request, signal) => need("model.complete").complete(request, signal), book: (reply) => need("model.complete").book(reply), session: { id: () => need("session.id").sessionId, cwd: () => need("session.cwd").cwd(), root: () => need("session.root").root(), model: () => need("session.model").model(), messages: () => need("session.messages").messages(), agentMessages: (agentId) => need("session.messages").agentMessages(agentId), turns: () => need("session.turns").turns(), usage: () => need("session.usage").usage(), version: () => need("session.version").version(), }, turn: { abort: (turn, by) => need("turn.abort").turnAbort(turn, by) }, now: () => need("clock.now").now(), tools: () => need("tool.list").tools(), agents: () => need("agent.list").agents(), }; return { view, entries: { "tool.call": (args, ctx) => need("tool.call").toolCall(args, ctx), "agent.spawn": (args, ctx) => need("agent.spawn").agentSpawn(args, ctx), "session.append": (args, ctx) => need("session.append").sessionAppend(args, ctx), "session.send": (args, ctx) => need("session.send").sessionSend(args, ctx), "session.compact": (args, ctx) => need("session.compact").sessionCompact(args, ctx), "prompt.submit": (args, ctx) => need("prompt.submit").promptSubmit(args, ctx), }, bind: (s) => { seats = s; }, }; } export async function admitLegMods(input) { const late = lateView(); const { seats, skillSeats, admitted } = input.listed; const report = modsReportToOnError(input.deps.onError, input.sessionId); const life = new AbortController(); let kernelBus; try { const view = input.retiredNames; kernelBus = await admitMods({ side: "engine", seats: admitted, bottoms: engineMethodBottoms(late.view), entries: late.entries, report, describeThrown, isProxy: types.isProxy, lifetime: life.signal, ...(view !== undefined ? { readMatcher: (m) => matcherUnderView(m, view) } : {}) }); } catch (err) { life.abort(new Error("the leg's admission failed")); throw err; } const skillScopes = skillScopeRecord(skillSeats.owners, input.reopenedSkills); const bus = legBusOf(scopedLegBus(kernelBus, skillScopes), report); const standing = standingBus(bus, skillScopes); for (const record of bus.records) { if ("refusedBy" in record) deliverEngineNotice(input.deps.onNotice, registrationRefusedNotice(record, input.sessionId)); } const chain = recordAdmittedChain(bus, seats); if (standing !== bus) ADMITTED_CHAINS.set(standing, chain); return { bus, standing, chain, skillScopes, report, bindFacade: late.bind, end: () => life.abort(new Error("the leg stopped")) }; } async function agentRowsOf(seat, agentId) { const refused = (why) => new Error(`session.messages: agent ${agentId}: ${why}`); if (seat === undefined) throw refused("there is no task list here — a session-level pass has no run, so no subagents"); const anchor = seat.registry.anchoredSession(agentId, seat.access); if (anchor === undefined) throw refused("not one of this leg's subagents (no task list row this leg reaches has that id)"); if (anchor === null) throw refused("its row names no session — not a subagent's row, or its session is not bound yet or was released"); const store = anchor.store; if (store === undefined) throw refused("its session was bound without the store that holds it"); const notOurs = () => refused("its row names no session — not a subagent's row, or its session is not bound yet or was released"); const verdict = await judgeRowForSeat(store, { sessionId: anchor.sessionId }, seat.owner, seat.signal); if (!verdict.open && verdict.kind === "store") throw Object.assign(refused(`its session could not be judged for this conversation — ${verdict.why}`), { code: verdict.code }); if (!verdict.open) throw notOurs(); let read; try { read = await readJudgedRow(store, anchor.sessionId, verdict, (held) => held.session.getBranch(), seat.signal); } catch (err) { if (seat.signal?.aborted === true) throw err; throw refused(`its session could not be read (${describeThrown(err)})`); } if ("refused" in read) { if (read.refused.kind === "store") throw Object.assign(refused(`its session could not be judged for this conversation — ${read.refused.why}`), { code: read.refused.code }); throw notOurs(); } return read.read.flatMap((e) => (e.type === "message" ? [e.message] : [])); } const NO_REQUEST_RUNNING = Object.freeze({ kind: "none" }); function replyText(reply) { return reply.content.flatMap((c) => (c.type === "text" ? [c.text] : [])).join(""); } export function legFacadeSeats(input) { const runtime = brainToRuntime(observingBrain(modelLaneBrainOf(input.deps), input.observeSideRequest)); const answeredBy = new Map(); const byUsage = new WeakMap(); return { exec: (command, options) => { const readFloor = input.readFloor(undefined); return input.executionEnv.exec(command, { ...options, ...(readFloor !== undefined ? { readFloor } : {}) }); }, complete: async (request, signal) => { const model = request.model !== undefined ? resolveModel(request.model, input.deps.models) : input.model; answeredBy.set(model.id, model); const auth = await askPerModelAuth(input.spec.getApiKeyAndHeaders, model, input.spec); const reply = await runtime.completeSimple(model, { ...request.context, messages: [...request.context.messages] }, { signal, maxTokens: request.maxTokens, reasoning: resolveTaskModel({ model }, {}).thinking, ...auth }); if (reply.stopReason === "error" || reply.stopReason === "aborted") throw new Error(`model.complete: ${reply.errorMessage ?? reply.stopReason}`); if (reply.usage !== undefined) byUsage.set(reply.usage, { model, stopReason: reply.stopReason, ...(reply.diagnostics !== undefined ? { diagnostics: reply.diagnostics } : {}), ...(reply.partialFinalized === true ? { partialFinalized: true } : {}) }); return Object.freeze({ text: replyText(reply), model: model.id, ...(reply.usage !== undefined ? { usage: reply.usage } : {}) }); }, sessionId: input.sessionId, book: (reply) => { const seen = reply.usage !== undefined ? byUsage.get(reply.usage) : undefined; const record = seen !== undefined && seen.model.id === reply.model ? seen : undefined; const model = record?.model ?? answeredBy.get(reply.model); if (model === undefined) throw new Error(`model.complete: the reply names model "${reply.model}", which no call of this leg resolved; it is not booked`); input.book(model, { usage: reply.usage, ...(record?.diagnostics !== undefined ? { diagnostics: record.diagnostics } : {}), ...(record !== undefined ? { stopReason: record.stopReason, ...(record.partialFinalized === true ? { partialFinalized: true } : {}) } : {}) }); }, cwd: () => input.cwdRef?.current ?? input.taskRoot, root: () => input.taskRoot, model: () => input.model.id, messages: () => input.lastSentRequest()?.messages ?? [], agentMessages: (agentId) => agentRowsOf(input.agentSessions, agentId), turns: () => input.turns(), usage: () => Object.freeze(input.measure.context !== undefined ? { context: input.measure.context } : {}), version: () => Object.freeze({ version: engineVersion() }), turnAbort: (turn, by) => input.turnAbort.seat?.(turn, by) ?? NO_REQUEST_RUNNING, now: () => (input.deps.now ?? Date.now)(), tools: () => [...input.activeTools], agents: () => (input.agentListing?.entries ?? []).map((e) => e.name), toolCall: input.toolCall, agentSpawn: input.agentSpawn, sessionAppend: input.sessionAppend, sessionSend: input.sessionSend, sessionCompact: input.sessionCompact, promptSubmit: input.promptSubmit, }; } export async function admitModChain(seats, onError) { const bus = await admitMods({ side: "engine", seats, bottoms: engineMethodBottoms(lateView().view), report: (err) => { try { onError?.(err); } catch { } }, describeThrown, isProxy: types.isProxy, lifetime: OUTSIDE_ANY_LEG, }); recordAdmittedChain(bus, seats); return bus; } const OUTSIDE_ANY_LEG = AbortSignal.abort(new Error("admitted outside any leg"));