UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

323 lines (322 loc) • 15.4 kB
import { answeredWithoutModel } from "../../internal/llm.js"; import { noteHostRewrite } from "../frame-settlement.js"; import { describeThrown } from "../tool-policy.js"; import { foreignLine } from "../protocol-http-auth.js"; import { stampUserRowOrigin } from "../user-row-origin.js"; import { isPlainRecord } from "./kernel/receive.js"; import { NEXT_IN_FLIGHT, receiveEvent, sameModData } from "./kernel/site-rules.js"; import { classicEventBase, seatHears } from "./stations.js"; export const SESSION_APPEND_DOORS = Object.freeze(["prompt", "note", "delivery", "attachment", "response", "tool-result"]); export const SESSION_APPEND_ORIGIN_KINDS = Object.freeze(["host", "engine", "model", "tool", "plugin"]); export function doorOf(row) { switch (row.role) { case "assistant": return "response"; case "toolResult": return "tool-result"; case "user": if (row.attachment !== undefined) return "attachment"; if (row.engineNoteKey !== undefined) return "delivery"; return row.provenance === "engine-note" || row.engineMinted === true ? "note" : "prompt"; default: return "note"; } } export function promptCountOf(branch) { let n = 0; for (const entry of branch) if (entry.type === "message" && doorOf(entry.message) === "prompt") n += 1; return n; } const HOST = Object.freeze({ kind: "host" }); const ENGINE = Object.freeze({ kind: "engine" }); export function originOf(row) { switch (row.role) { case "assistant": return answeredWithoutModel(row) ? Object.freeze({ kind: "plugin", name: row.answeredBy }) : Object.freeze({ kind: "model", model: row.model }); case "toolResult": return Object.freeze({ kind: "tool", tool: row.toolName }); case "user": return doorOf(row) === "prompt" || (row.attachment !== undefined && row.attachment.origin === undefined) ? HOST : ENGINE; default: return ENGINE; } } function viewOf(row) { switch (row.role) { case "user": case "assistant": return { role: row.role, content: row.content }; case "toolResult": return { role: row.role, toolCallId: row.toolCallId, toolName: row.toolName, content: row.content, isError: row.isError }; case "custom": return { role: row.role, customType: row.customType, content: row.content }; default: return { role: row.role }; } } const NAMING_MEMBERS = ["role", "toolCallId", "toolName", "customType"]; function contentHeldWhy(row) { if (row.role === "user") { if (row.attachment !== undefined) return "its attachment record indexes its content"; if (row.enginePrefixChars !== undefined || row.engineSegments !== undefined || row.engineMinted === true) return "the engine's frames in it are read by their exact text"; } return undefined; } const PINNED_BLOCKS = "its blocks other than text are pinned (the same blocks, in the same order)"; function rewrittenContent(original, handed) { if (typeof original === "string") { if (typeof handed !== "string") return { why: "its content is a string, and a rewrite keeps the content's form" }; return handed.trim() === "" ? { why: "its text is blank" } : { content: handed }; } if (!Array.isArray(handed) || handed.length === 0) return { why: "its content is a list of blocks, and a rewrite keeps the content's form" }; const blocks = Array.isArray(original) ? original : []; const others = blocks.filter((b) => b.type !== "text"); const texts = blocks.filter((b) => b.type === "text"); const out = []; let other = 0; let text = 0; const items = handed; for (const b of items) { if (!isPlainRecord(b)) return { why: "its content is a list of blocks, and a rewrite keeps the content's form" }; if (b["type"] === "text") { const was = texts[text++]; const t = b["text"]; if (was !== undefined && was["text"] === t) out.push(was); else if (typeof t === "string" && t.trim() !== "") out.push({ type: "text", text: t }); else return { why: "a text block's text is blank" }; continue; } const was = others[other++]; if (was === undefined || !sameModData(was, b)) return { why: PINNED_BLOCKS }; out.push(was); } return other === others.length ? { content: out } : { why: PINNED_BLOCKS }; } function rewrite(row, view, handed, by) { const held = contentHeldWhy(row); if (held !== undefined) return held; for (const k of new Set([...Object.keys(view), ...Object.keys(handed)])) { if (k !== "content" && !sameModData(view[k], handed[k])) return Object.hasOwn(view, k) ? `its ${k} is pinned` : `a row has no ${k} to set`; } if (!Object.hasOwn(view, "content")) return "it has no content to rewrite"; const next = rewrittenContent(view["content"], handed["content"]); if ("why" in next) return next.why; const target = row; target.content = next.content; target.rewrittenBy = Object.freeze([...by]); return undefined; } function keptAnswer(row) { const received = receiveEvent({ message: viewOf(row) }); if ("refusal" in received) throw new TypeError(`session.append: the kept row cannot be handed up: ${received.refusal}`); return received.payload; } const isDeny = (a) => isPlainRecord(a) && Object.hasOwn(a, "deny"); function keepAsMade(row, raised) { if (raised !== undefined) raised.outcome = { kind: "kept", answer: keptAnswer(row) }; return true; } export function createRowSeat() { let bound; const raisings = new WeakMap(); const admitOne = async (row, raised) => { const keep = () => keepAsMade(row, raised); const binding = bound; if (!seatHears(binding, "session.append")) return keep(); const door = raised !== undefined ? "note" : doorOf(row); try { const view = viewOf(row); const origin = raised !== undefined ? Object.freeze({ kind: "plugin", name: raised.ctx.origin.plugin }) : originOf(row); const e = { ...classicEventBase(binding.identity), door, origin, message: view }; const handOns = []; let kept; const checkHandOn = (payload, by) => { const message = payload["message"]; if (!isPlainRecord(message)) return "next() handed on a message that is not a row"; const changed = NAMING_MEMBERS.find((k) => !sameModData(view[k], message[k])); if (changed !== undefined) return `a changed message.${changed}`; const content = message["content"]; if (Object.hasOwn(view, "content") && typeof content !== "string" && !(Array.isArray(content) && content.every((b) => isPlainRecord(b) && typeof b["type"] === "string"))) { return "next() handed on a content that is neither a string nor a list of blocks"; } handOns.push({ by: by.plugin, message }); return undefined; }; const bottom = (handed) => { if (kept !== undefined) return kept; const message = handed["message"]; if (isPlainRecord(message) && !sameModData(view, message)) { const by = []; let before = view; for (const h of handOns) { if (!sameModData(before, h.message) && !by.includes(h.by)) by.push(h.by); before = h.message; } const why = rewrite(row, view, message, by); if (why === undefined && row.role === "toolResult" && binding.frameSettlement !== undefined) noteHostRewrite(binding.frameSettlement, row.toolCallId); if (why !== undefined) { binding.report(new Error(`session.append: a rewrite of a ${door} row is not kept (${why}); the row is kept as made — rewritten by ${by.map((b) => `"${foreignLine(b, 80)}"`).join(", ") || "an extension"}`)); } } kept = keptAnswer(row); return kept; }; const checkAnswer = (a, _e, _by, below) => { if (kept !== undefined && a === kept) return undefined; if (isDeny(a)) { const reason = a["deny"]; if (Object.keys(a).length !== 1) return "session.append takes next(e), the row next answered, or { deny: <reason> }"; if (below.some((b) => !isDeny(b))) return "a deny after next kept the row (refuse in place of next)"; if (below.some((b) => isDeny(b) && b["deny"] === reason)) return undefined; if (raised === undefined) return "a deny of a row the engine adds (only an extension's own note is refused)"; return typeof reason === "string" && reason.trim() !== "" ? undefined : "a deny with no reason (a non-empty string)"; } if (below.length === 0) return "an answer without next (the row is kept; next(e) keeps it)"; let last; for (let i = below.length - 1; i >= 0 && last === undefined; i--) if (!isDeny(below[i])) last = below[i]; if (last === undefined) return "a row after next refused it (nothing was kept)"; if (last === NEXT_IN_FLIGHT) return "a row while its next(e) still runs (the answer is the row as kept)"; return sameModData(a, last) ? undefined : "a row other than what next answered (the answer is the row as kept)"; }; let outcome; try { outcome = await binding.bus.dispatch("session.append", e, { bottom, checkAnswer, checkHandOn, ...(raised !== undefined ? { frames: raised.ctx.frames, origin: raised.ctx.origin, signal: raised.ctx.signal } : {}), }); } catch (err) { binding.report(new Error(`session.append: the ${door} row is kept as made — the dispatch could not be raised (${describeThrown(err)})`)); return keep(); } if (kept !== undefined) { if (raised !== undefined) raised.outcome = { kind: "kept", answer: kept }; return true; } if (raised !== undefined && outcome.kind === "answered" && isDeny(outcome.answer)) { raised.outcome = { kind: "denied", reason: String(outcome.answer["deny"]) }; return false; } if (raised !== undefined && outcome.kind === "aborted") { raised.outcome = { kind: "cancelled" }; return false; } if (outcome.kind === "failed") binding.report(new Error(`session.append: the ${door} row is kept as made — ${outcome.reason}`)); return keep(); } catch (err) { binding.report(new Error(`session.append: the ${door} row is kept as made — ${describeThrown(err)}`)); return keep(); } }; const admitAll = async (rows, raised) => { const out = []; for (const row of rows) if (await admitOne(row, raised)) out.push(row); return out; }; return { admitRows: (rows, raising) => { for (const row of rows) stampUserRowOrigin(row); const raised = raising !== undefined ? raisings.get(raising) : undefined; if (seatHears(bound, "session.append")) return admitAll(rows, raised); return new Promise((resolve) => resolve(rows.filter((row) => keepAsMade(row, raised)))); }, bind: (binding) => { bound = binding; }, raise: (ctx) => { const token = Object.freeze({ door: "note" }); raisings.set(token, { ctx }); return token; }, outcomeOf: (raising) => raisings.get(raising)?.outcome, }; } function noteContentOf(args, agentId, by) { const refuse = (why) => new TypeError(`${by}: $.session.append: refused: ${why}`); const extra = Object.keys(args).find((k) => k !== "message" && k !== "agentId"); if (extra !== undefined) throw refuse(`takes { message, agentId? }; "${foreignLine(extra, 40)}" is not one`); if (Object.hasOwn(args, "agentId") && (agentId === undefined || args["agentId"] !== agentId)) throw refuse("agentId names a leg other than this one"); const message = args["message"]; if (!isPlainRecord(message)) throw refuse("takes message, { role: \"user\", content }"); if (message["role"] === "system") throw refuse("a system row (the engine keeps no row outside the conversation the model reads)"); if (message["role"] !== "user" || Object.keys(message).some((k) => k !== "role" && k !== "content")) throw refuse("takes message, { role: \"user\", content }"); const content = message["content"]; if (typeof content === "string") { if (content.trim() === "") throw refuse("the note's text is blank"); return content; } if (!Array.isArray(content) || content.length === 0) throw refuse("content is a string or a non-empty list of text blocks"); return content.map((b) => { if (!isPlainRecord(b) || b["type"] !== "text" || typeof b["text"] !== "string" || Object.keys(b).some((k) => k !== "type" && k !== "text")) throw refuse("each block is { type: \"text\", text }"); if (b["text"].trim() === "") throw refuse("a block's text is blank"); return { type: "text", text: b["text"] }; }); } export function createSessionAppendEntry(input) { return async (args, ctx) => { const by = ctx.origin.plugin; const content = noteContentOf(args, input.agentId, by); const row = { role: "user", content, timestamp: input.now(), provenance: "engine-note" }; const raising = input.seat.raise(ctx); await input.harness.appendMessage(row, raising); const outcome = input.seat.outcomeOf(raising); if (outcome === undefined) throw new Error(`${by}: $.session.append: the note was not admitted`); if (outcome.kind === "cancelled") throw new Error(`${by}: $.session.append: aborted`); return outcome.kind === "denied" ? Object.freeze({ deny: outcome.reason }) : outcome.answer; }; }