UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

411 lines (410 loc) • 20.6 kB
import { terminalProjection } from "./runner/terminal-projection.js"; import { canonicalize, capturedJsonOf, describeBindingFault } from "./canonical-json.js"; import { codedRefusal, readMember, thrownIs } from "./thrown-value.js"; import { CORRUPT_BODY_FORMS } from "./store-contracts/read-back-shape-contract.js"; const isRecordShaped = (v) => v !== null && typeof v === "object" && !Array.isArray(v); const ownMember = (o, key) => (Object.hasOwn(o, key) ? o[key] : undefined); export function readWorkflowJournalEntry(raw) { if (!isRecordShaped(raw)) return { corrupt: "not-an-object", why: "is not a journal entry (not an object)" }; const callKey = ownMember(raw, "callKey"); if (callKey === undefined) return { corrupt: "missing-required", why: "carries no call key" }; if (typeof callKey !== "string") return { corrupt: "wrong-type", why: "has a call key that is not a string" }; const result = ownMember(raw, "result"); const parked = ownMember(raw, "parked"); const stopped = ownMember(raw, "stopped"); const arms = [ ["a result", result], ["a parked arm", parked], ["a stopped arm", stopped], ].filter(([, a]) => a !== undefined).map(([name]) => name); if (arms.length === 0) return { corrupt: "missing-required", why: "carries neither a result nor a parked arm (nor a stopped one)" }; if (arms.length > 1) return { corrupt: "wrong-type", why: `carries ${arms.length === 2 ? "both " : ""}${arms.slice(0, -1).join(", ")} and ${arms.at(-1)}` }; if (stopped !== undefined) { if (!isRecordShaped(stopped)) return { corrupt: "wrong-type", why: "is recorded as stopped but its stopped arm is not an object" }; const leg = ownMember(stopped, "result"); const by = ownMember(stopped, "stoppedBy"); if (leg === undefined || by === undefined) return { corrupt: "missing-required", why: "is recorded as stopped but carries no result or no stopper" }; if (!isRecordShaped(leg) || !isRecordShaped(ownMember(leg, "terminal")) || typeof by !== "string" || by === "") return { corrupt: "wrong-type", why: "is recorded as stopped but its result carries no terminal or its stopper is not a word" }; return { entry: { callKey, stopped: { result: leg, stoppedBy: by } } }; } if (parked === undefined) { if (!isRecordShaped(result)) return { corrupt: "wrong-type", why: "has a result that is not an object" }; return { entry: { callKey, result: result } }; } if (!isRecordShaped(parked)) return { corrupt: "wrong-type", why: "is recorded as parked but its parked arm is not an object" }; const terminal = ownMember(parked, "terminal"); if (terminal === undefined) return { corrupt: "missing-required", why: "is recorded as parked but its parked result carries no terminal" }; if (!isRecordShaped(terminal) || ownMember(terminal, "kind") !== "paused") { return { corrupt: "wrong-type", why: "is recorded as parked but its terminal is not a paused one" }; } const token = ownMember(terminal, "token"); if (token === undefined) return { corrupt: "missing-required", why: "is recorded as parked but its paused terminal carries no checkpoint token" }; if (typeof token !== "string" || token.length === 0) return { corrupt: "wrong-type", why: "is recorded as parked but its paused terminal carries no checkpoint token" }; return { entry: { callKey, parked: parked } }; } export function clampRunIdText(raw) { return raw.replace(/[^A-Za-z0-9_.:-]/g, "").slice(0, 64); } export const JOURNAL_INCOMPATIBLE_ERROR_CODE = "workflow.journal_incompatible"; export class WorkflowJournalIncompatibleError extends Error { ordinal; code = JOURNAL_INCOMPATIBLE_ERROR_CODE; fromRunId; constructor(fromRunId, ordinal, entry) { const runIdText = clampRunIdText(fromRunId); super(`workflow run "${runIdText}": ${refusedSubjectOf(ordinal, entry)} — this journal cannot be resumed. ${REPAIR_COST}`); this.ordinal = ordinal; this.fromRunId = runIdText; this.name = "WorkflowJournalIncompatibleError"; } static ledgerLine(fromRunId, line, form) { return new WorkflowJournalIncompatibleError(fromRunId, -1, { [LEDGER_LINE]: { line, form } }); } } const REPAIR_COST = "Deleting what is damaged does not repair it (whatever goes missing runs again, live); restoring it needs a copy of the ledger kept outside the engine; a fresh run executes every step again, side effects included."; const LEDGER_LINE = Symbol("ledgerLine"); function refusedSubjectOf(ordinal, entry) { const at = isRecordShaped(entry) ? entry[LEDGER_LINE] : undefined; if (at !== undefined) { const line = Number.isSafeInteger(at.line) && at.line > 0 ? at.line : "?"; const form = CORRUPT_BODY_FORMS.includes(at.form) ? at.form : "unreadable"; return `ledger line ${String(line)} is not one of the run's records (${String(form)})`; } const read = entry === undefined ? undefined : readWorkflowJournalEntry(entry); return `journal entry #${ordinal} ${read !== undefined && "corrupt" in read ? read.why : "carries no terminal cause (a journal written before TaskResult.terminal, or a malformed entry)"}`; } function readLaunchFace(raw) { if (!isRecordShaped(raw)) return { defect: "face" }; const names = (k) => { const v = ownMember(raw, k); if (v === undefined) return undefined; const keys = Array.isArray(v) ? Object.keys(v) : []; return Array.isArray(v) && keys.length === v.length && keys.every((key, i) => key === String(i) && typeof v[i] === "string") ? [...v] : { defect: `face.${k}` }; }; const deferTools = names("deferTools"); const alwaysLoadTools = names("alwaysLoadTools"); const restoreGatedTools = ownMember(raw, "restoreGatedTools") === true ? true : names("restoreGatedTools"); const promptLean = ownMember(raw, "promptLean"); for (const v of [deferTools, alwaysLoadTools, restoreGatedTools]) if (v !== undefined && v !== true && !Array.isArray(v)) return v; if (promptLean !== undefined && typeof promptLean !== "boolean") return { defect: "face.promptLean" }; return { ...(deferTools !== undefined ? { deferTools: deferTools } : {}), ...(alwaysLoadTools !== undefined ? { alwaysLoadTools: alwaysLoadTools } : {}), ...(restoreGatedTools !== undefined ? { restoreGatedTools: restoreGatedTools } : {}), ...(promptLean !== undefined ? { promptLean } : {}), }; } function readLaunchHost(raw) { if (!isRecordShaped(raw)) return { defect: "host" }; const model = ownMember(raw, "model"); const pinned = ownMember(raw, "modelPinned"); const thinking = ownMember(raw, "thinking"); if (model !== undefined && typeof model !== "string") return { defect: "host.model" }; if (thinking !== undefined && typeof thinking !== "string") return { defect: "host.thinking" }; if (pinned !== undefined && (pinned !== true || model === undefined)) return { defect: "host.modelPinned" }; return { ...(model !== undefined ? { model } : {}), ...(pinned === true ? { modelPinned: true } : {}), ...(thinking !== undefined ? { thinking } : {}) }; } export function readLaunchRecordVerdict(raw) { if (!isRecordShaped(raw)) return { defect: "record" }; const script = ownMember(raw, "script"); if (typeof script !== "string" || script.length === 0) return { defect: "script" }; const callArgs = ownMember(raw, "callArgs"); if (!isRecordShaped(callArgs)) return { defect: "callArgs" }; const effectiveArgs = ownMember(raw, "effectiveArgs"); const hostRaw = ownMember(raw, "host"); const host = hostRaw === undefined ? undefined : readLaunchHost(hostRaw); if (host !== undefined && "defect" in host) return host; const faceRaw = ownMember(raw, "face"); const face = faceRaw === undefined ? undefined : readLaunchFace(faceRaw); if (face !== undefined && "defect" in face) return face; const record = { script, ...(effectiveArgs !== undefined ? { effectiveArgs: structuredClone(effectiveArgs) } : {}), callArgs: structuredClone(callArgs), ...(host !== undefined ? { host } : {}), ...(face !== undefined ? { face } : {}) }; return { record }; } function launchRecordToKeep(raw) { if (!isRecordShaped(raw)) return { why: "it is not a record" }; const read = {}; for (const member of ["script", "effectiveArgs", "callArgs", "host", "face"]) { const value = ownMember(raw, member); if (value === undefined) continue; if (member !== "effectiveArgs" && member !== "callArgs") { read[member] = value; continue; } const held = { [member]: value }; const c = capturedJsonOf(held); if (!c.ok) return { why: `its ${member} hold ${describeBindingFault(held, c.fault).replace(/ at args\./, " at ")} — a value a store's JSON form cannot keep as it is` }; const form = c.value[member]; if (form !== undefined) read[member] = form; } const v = readLaunchRecordVerdict(read); return "defect" in v ? { why: `its ${v.defect} is not the shape a launch record's is` } : v; } export function readWorkflowLaunchRecord(raw) { const v = launchRecordToKeep(raw); return "record" in v ? v.record : undefined; } export function launchRecordToKeepOrThrow(runId, raw) { const v = launchRecordToKeep(raw); if ("why" in v) throw new Error(`workflow journal: the launch record for ${runId} is not one to keep — ${v.why}`); return v.record; } export const WORKFLOW_LAUNCH_UNREADABLE_CODE = "workflow.launch_unreadable"; export class WorkflowLaunchUnreadableError extends Error { runId; code = WORKFLOW_LAUNCH_UNREADABLE_CODE; member; constructor(runId, raw) { super(`workflow journal: run "${runId}"'s launch record does not read back in the shape it was written in (${launchDefectOf(raw)})`); this.runId = runId; this.member = launchDefectOf(raw); this.name = "WorkflowLaunchUnreadableError"; } } function launchDefectOf(raw) { const v = readLaunchRecordVerdict(raw); return "defect" in v ? v.defect : "record"; } export function readKeptLaunch(journal, runId, scope, boundMs) { return new Promise((resolve) => { const t = setTimeout(() => resolve({ kind: "failed" }), boundMs); Promise.resolve() .then(() => journal.loadLaunch(runId, scope)) .then((answer) => { if (answer === undefined) return { kind: "absent" }; const v = readLaunchRecordVerdict(answer); return "defect" in v ? { kind: "defect", member: v.defect } : { kind: "record", record: v.record }; }, (err) => { const member = thrownIs(err, WorkflowLaunchUnreadableError) || readMember(err, "code") === WORKFLOW_LAUNCH_UNREADABLE_CODE ? readMember(err, "member") : undefined; return typeof member === "string" ? { kind: "defect", member } : { kind: "failed", cause: { err } }; }) .then((read) => (clearTimeout(t), resolve(read)), (err) => (clearTimeout(t), resolve({ kind: "failed", cause: { err } }))); }); } export const WORKFLOW_LAUNCH_CONFLICT_CODE = "workflow.launch_conflict"; export class WorkflowLaunchConflictError extends Error { runId; code = WORKFLOW_LAUNCH_CONFLICT_CODE; constructor(runId) { super(`workflow journal: run "${runId}" already has a launch record with other content — refused, the stored record kept`); this.runId = runId; this.name = "WorkflowLaunchConflictError"; } } export const LAUNCH_RECORD_SUBJECT = "launch record"; export function assertLaunchRecordFits(record) { const serialized = JSON.stringify(record); if (oversizeJournalResult(serialized)) throw new WorkflowJournalOversizeError(LAUNCH_RECORD_SUBJECT, Buffer.byteLength(serialized, "utf8")); } export function sameLaunchRecord(a, b) { return canonicalize(a) === canonicalize(b); } export function assertJournalStoreGivesClaimsBack(store, seat) { if (store === undefined || store === null) return; if (typeof readMember(store, "resumeClaim") !== "function" || typeof readMember(store, "releaseResumeClaim") === "function") return; throw codedRefusal("config.invalid_argument", `${seat}: the workflow journal store takes resume claims (resumeClaim) but has no releaseResumeClaim — refused. The engine gives a workflow's resume claim back when the run that took it ends; the store's expiry only frees a claim whose engine died holding it, so on this store every continuation of a workflow would wait for the claim of the one before it to expire. Implement releaseResumeClaim (the in-tree stores are the reference), or neither member (the engine then holds claims in this process alone).`); } export function journalKeepsLaunches(store) { return typeof store?.recordLaunch === "function" && typeof store.loadLaunch === "function"; } export const RESUME_CLAIM_REMAINING_MS_MAX = 24 * 60 * 60 * 1000; export function resumeClaimRemainingMember(expiresAt, now) { const left = Math.ceil(expiresAt - now); return Number.isSafeInteger(left) && left >= 1 && left <= RESUME_CLAIM_REMAINING_MS_MAX ? { remainingMs: left } : {}; } export const MAX_JOURNAL_RESULT_BYTES = 5 * 1024 * 1024; export function oversizeJournalResult(serialized) { return Buffer.byteLength(serialized, "utf8") > MAX_JOURNAL_RESULT_BYTES; } export function callKeyOrdinal(callKey) { const i = callKey.indexOf(":"); const n = Number.parseInt(i >= 0 ? callKey.slice(0, i) : callKey, 10); return Number.isFinite(n) ? n : 0; } export const JOURNAL_OVERSIZE_ERROR_CODE = "workflow.journal_oversize"; export class WorkflowJournalOversizeError extends Error { callKey; bytes; cap; code = JOURNAL_OVERSIZE_ERROR_CODE; constructor(callKey, bytes, cap = MAX_JOURNAL_RESULT_BYTES) { super(`workflow journal: entry "${callKey}" is ${bytes} bytes, over the ${cap}-byte per-entry cap — refused, nothing journaled`); this.callKey = callKey; this.bytes = bytes; this.cap = cap; this.name = "WorkflowJournalOversizeError"; } } export function assertJournalEntryFits(entry) { const serialized = JSON.stringify(entry.parked !== undefined ? entry.parked : entry.stopped !== undefined ? entry.stopped : entry.result); if (oversizeJournalResult(serialized)) throw new WorkflowJournalOversizeError(entry.callKey, Buffer.byteLength(serialized, "utf8")); } export function journalOversizeTombstone(result, bytes, replay = "rerun") { const resume = replay === "stopped" ? "A resume replays this call as stopped (it does not run again) and continues after it." : "A resume re-runs this agent (and everything after it) live."; const message = `[journal] result omitted: ${bytes} bytes exceeds the ${MAX_JOURNAL_RESULT_BYTES}-byte per-entry journal cap; ` + `the agent's real terminal status was "${terminalProjection(result.terminal).status}". ${resume}`; return { taskId: result.taskId, sessionId: result.sessionId, terminal: { kind: "failed", code: JOURNAL_OVERSIZE_ERROR_CODE, message }, result: message, resultEntryIds: [], ...(result.continuesFrom !== undefined ? { continuesFrom: result.continuesFrom } : {}), stats: result.stats, }; } function snapshot(entry) { try { return structuredClone(entry); } catch { return JSON.parse(JSON.stringify(entry)); } } export const IN_MEMORY_RESUME_CLAIM_TTL_MS = 60 * 60 * 1000; export class InMemoryWorkflowJournalStore { runs = new Map(); resumeClaims = new Map(); claimsForScope(scope) { let m = this.resumeClaims.get(scope); if (m === undefined) { m = new Map(); this.resumeClaims.set(scope, m); } return m; } async resumeClaim(input) { const table = this.claimsForScope(input.scope); const now = Date.now(); const existing = table.get(input.sourceRunId); if (existing !== undefined) { if (existing.kind === "tombstone") { return { granted: false, stopped: { by: existing.stoppedBy } }; } if (existing.expiresAt > now && existing.holder !== input.newRunId) { return { granted: false, holder: existing.holder, ...resumeClaimRemainingMember(existing.expiresAt, now) }; } } const expiresAt = now + IN_MEMORY_RESUME_CLAIM_TTL_MS; table.set(input.sourceRunId, { kind: "claim", holder: input.newRunId, expiresAt }); return { granted: true, ...resumeClaimRemainingMember(expiresAt, now) }; } async releaseResumeClaim(input) { const table = this.resumeClaims.get(input.scope); if (table === undefined) return; const existing = table.get(input.sourceRunId); if (existing !== undefined && existing.kind === "claim" && existing.holder === input.newRunId) table.delete(input.sourceRunId); } async stopResumeClaim(input) { if (typeof input.stoppedBy !== "string" || input.stoppedBy === "") { throw new TypeError("workflow journal: stopResumeClaim requires a non-empty stoppedBy string"); } const table = this.claimsForScope(input.scope); const now = Date.now(); const existing = table.get(input.sourceRunId); if (existing !== undefined) { if (existing.kind === "tombstone") return { stopped: true }; const binds = existing.expiresAt > now; if (binds && (input.holder === undefined || existing.holder !== input.holder)) { return { stopped: false, holder: existing.holder }; } } table.set(input.sourceRunId, { kind: "tombstone", stoppedBy: input.stoppedBy, stoppedAt: now }); return { stopped: true }; } async deleteRun(runId, scope) { const launch = this.launches.get(runId); if (launch !== undefined && launch.scope === scope) this.launches.delete(runId); const rec = this.runs.get(runId); if (!rec || rec.scope !== scope) return launch !== undefined && launch.scope === scope; this.runs.delete(runId); return true; } launches = new Map(); async recordLaunch(runId, scope, launch) { const read = launchRecordToKeepOrThrow(runId, launch); assertLaunchRecordFits(read); const kept = this.launches.get(runId); if (kept !== undefined) { if (kept.scope === scope && sameLaunchRecord(kept.launch, read)) return; throw new WorkflowLaunchConflictError(runId); } this.launches.set(runId, { scope, launch: read }); } async loadLaunch(runId, scope) { const kept = this.launches.get(runId); if (kept === undefined || kept.scope !== scope) return undefined; const v = readLaunchRecordVerdict(kept.launch); if ("defect" in v) throw new WorkflowLaunchUnreadableError(runId, kept.launch); return v.record; } async load(runId, scope) { const rec = this.runs.get(runId); if (!rec || rec.scope !== scope) return []; const out = []; for (const [ordinal, e] of [...rec.byOrdinal.entries()].sort((a, b) => a[0] - b[0])) { const row = snapshot(e); const read = readWorkflowJournalEntry(row); if ("corrupt" in read) throw new WorkflowJournalIncompatibleError(runId, ordinal, row); out.push(read.entry); } return out; } async append(runId, scope, entry) { assertJournalEntryFits(entry); let rec = this.runs.get(runId); if (!rec) { rec = { scope, byOrdinal: new Map() }; this.runs.set(runId, rec); } else if (rec.scope !== scope) { throw new Error(`workflow journal: runId ${runId} already recorded under a different scope`); } rec.byOrdinal.set(callKeyOrdinal(entry.callKey), snapshot(entry)); } }