UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

289 lines (288 loc) • 14.7 kB
import { isWorkflowStopperWord, runParkedOf, WORKFLOW_ITEM_STATUSES, WORKFLOW_RUN_STATUSES } from "../orchestration/workflow-types.js"; import { receiveRetentionPolicy } from "./retention-policy.js"; import { assertDeletionSessionId } from "./retention.js"; import { isCount, isFiniteNumber, isListOf, isRecordOf, isRowCorrupt, isString, isWord, optional, pair, required, rowShapeReader, takesExit, } from "./row-shape.js"; export function summarizeWorkflowRun(run) { const latestPhase = run.phases.at(-1); return { id: run.id, scope: run.scope, ...(run.originatingSessionId !== undefined ? { originatingSessionId: run.originatingSessionId } : {}), ...(run.name !== undefined ? { name: run.name } : {}), ...(run.description !== undefined ? { description: run.description } : {}), status: run.status, ...(runParkedOf(run) ? { parked: true } : {}), ...(run.errorCode !== undefined ? { errorCode: run.errorCode } : {}), ...(run.agentFailures !== undefined ? { agentFailures: run.agentFailures } : {}), ...(run.budgetOvershoot !== undefined ? { budgetOvershoot: { ...run.budgetOvershoot } } : {}), ...(run.timeoutInterruption !== undefined ? { timeoutInterruption: { ...run.timeoutInterruption } } : {}), ...(latestPhase !== undefined ? { currentPhase: latestPhase.title } : {}), phaseCount: run.phases.length, agentCount: run.agents.length, tokens: run.stats.tokens + run.stats.nested.tokens, startedAt: run.startedAt, ...(run.endedAt !== undefined ? { endedAt: run.endedAt } : {}), createdAt: run.createdAt, ...(resumedFromOf(run) !== undefined ? { resumedFrom: resumedFromOf(run) } : {}), }; } export function resumedFromOf(run) { const from = run.resume?.fromRunId; return typeof from === "string" && from !== "" ? from : undefined; } const WORKFLOW_RUN_ID = /^[A-Za-z0-9_.-]{1,64}$/; export const WORKFLOW_RUN_ID_CHARACTERS = "1 to 64 of A-Z a-z 0-9 _ . -, and not \".\" or \"..\" alone"; export function isWorkflowRunId(id) { return typeof id === "string" && WORKFLOW_RUN_ID.test(id) && id !== "." && id !== ".."; } export const WORKFLOW_RUN_ROW_MALFORMED_CODE = "workflow_run.row_malformed"; const isTimeoutCount = isFiniteNumber; export const WORKFLOW_RUN_ROW_SHAPE = rowShapeReader({ family: "workflow-run", code: WORKFLOW_RUN_ROW_MALFORMED_CODE, sentence: "This workflow run's stored record does not read the way this engine reads a run — an earlier engine release wrote it before a member it now reads existed, or it was changed in storage. It stays as stored; repair the record, or delete it with its session.", exit: "list-damaged", segments: [ { name: "rowKey", entries: [required("id", isString)] }, { name: "members", entries: [ pair("id", (r, ctx) => (r.id === ctx.key ? undefined : "its id is not the key the store files it under")), required("scope", isString), required("status", isWord(WORKFLOW_RUN_STATUSES)), required("phases", isListOf(isRecordOf({ title: isString }))), required("agents", isListOf(isRecordOf({ status: isWord(WORKFLOW_ITEM_STATUSES) }))), required("stats", isRecordOf({ tokens: isFiniteNumber, nested: isRecordOf({ tokens: isFiniteNumber }) })), required("startedAt", isFiniteNumber), required("createdAt", isFiniteNumber), optional("endedAt", isFiniteNumber), optional("agentFailures", isFiniteNumber), optional("name", isString), optional("description", isString), optional("originatingSessionId", isString), optional("errorCode", isString), pair("stoppedBy", (r) => { const by = r.stoppedBy; if (by === undefined) return r.status === "killed" ? "it is killed and names no stopper (stoppedBy)" : undefined; return isWorkflowStopperWord(by) ? undefined : "its stoppedBy is not a stopper word (a non-blank string of at most 256 characters)"; }), optional("sourceTaskId", isString), optional("budgetOvershoot", isRecordOf({ budgetTokens: isFiniteNumber, spentTokens: isFiniteNumber, unsettledTokens: isFiniteNumber }, ["unsettledTokens"])), optional("timeoutInterruption", isRecordOf({ timeoutMs: isTimeoutCount, agentsCompleted: isTimeoutCount, agentsFailed: isTimeoutCount, agentsInFlight: isTimeoutCount, approvalWaitedMs: isTimeoutCount }, ["approvalWaitedMs"])), optional("rev", isCount), ], }, ], }); function workflowRunRefusal(corrupt) { return new WorkflowRunStoreError(WORKFLOW_RUN_ROW_MALFORMED_CODE, WORKFLOW_RUN_ROW_SHAPE.refusalText(corrupt)); } export function readStoredWorkflowRun(raw, ctx, disclose) { const answer = WORKFLOW_RUN_ROW_SHAPE.read(raw, ctx); if (!isRowCorrupt(answer)) return answer.row; disclose?.(`workflow run ${JSON.stringify(ctx.key)}: ${answer.why} — refused in ${WORKFLOW_RUN_ROW_MALFORMED_CODE}`); throw workflowRunRefusal(answer); } export function admitWorkflowRun(candidate, id) { const answer = WORKFLOW_RUN_ROW_SHAPE.admit(candidate, { key: id }); if (isRowCorrupt(answer)) throw workflowRunRefusal(answer); return answer.row; } export function summarizeStoredWorkflowRun(raw, ctx, scope) { const answer = WORKFLOW_RUN_ROW_SHAPE.read(raw, ctx); if (!isRowCorrupt(answer)) return summarizeWorkflowRun(answer.row); takesExit(answer, "list-damaged", "workflow run listing"); return { rowVerdict: WORKFLOW_RUN_ROW_SHAPE.damagedVerdict(answer), id: ctx.key, scope }; } export function isTerminalWorkflowStatus(status) { return status !== "running" && WORKFLOW_RUN_STATUSES.includes(status); } export class WorkflowRunStoreError extends Error { code; constructor(code, message) { super(message); this.code = code; this.name = "WorkflowRunStoreError"; } } export const WORKFLOW_RUN_UPDATE_CAUSES = Object.freeze(["park_pass", "park_decision_settled", "tree_id_stamp"]); export function workflowRunCreationIdOf(run) { const v = run.creationId; return typeof v === "string" ? v : null; } export function nextWorkflowRunOnUpdate(cur, id, scope, run, expect, disclose) { const wanted = expect?.creationId; if (wanted !== undefined && wanted !== null && typeof wanted !== "string") { throw new TypeError("WorkflowRunStore.update: expect.creationId is a string, null or absent — another value compares against nothing, so the write is refused"); } if (!cur || cur.scope !== scope) return null; const live = readStoredWorkflowRun(cur, { key: id }, disclose); if (expect !== undefined && (live.rev ?? 0) !== expect.rev) return null; if (wanted !== undefined && workflowRunCreationIdOf(live) !== wanted) return null; const next = structuredClone(run); next.id = id; next.scope = scope; next.rev = (live.rev ?? 0) + 1; const admitted = admitWorkflowRun(next, id); if (isTerminalWorkflowStatus(live.status) && !isTerminalWorkflowStatus(admitted.status)) return null; return admitted; } function orderKey(value) { return typeof value === "number" && Number.isFinite(value) ? value : -Infinity; } export function queryWorkflowRuns(runs, scope, opts, disclose) { const rows = [...runs].filter(([, r]) => r.scope === scope && (opts?.status === undefined || r.status === opts.status) && (opts?.session === undefined || r.originatingSessionId === opts.session) && (opts?.resumedFrom === undefined || resumedFromOf(r) === opts.resumedFrom)); rows.sort(([, a], [, b]) => { const [ka, kb] = [orderKey(a.createdAt), orderKey(b.createdAt)]; return ka === kb ? 0 : ka < kb ? 1 : -1; }); const limited = opts?.limit !== undefined ? rows.slice(0, Math.max(0, opts.limit)) : rows; return limited.map(([id, r]) => { const summary = summarizeStoredWorkflowRun(r, { key: id }, scope); if ("rowVerdict" in summary) disclose?.(`workflow run ${JSON.stringify(id)}: its record does not read (its ${summary.rowVerdict.member}) — listed as unreadable`); return summary; }); } export function workflowRunReapCandidates(runs, scope, disclose) { const out = []; for (const [id, r] of runs) { if (r.scope !== scope || r.status === "running") continue; const createdAt = r.createdAt; const endedAt = r.endedAt; const stamped = typeof createdAt === "number" && Number.isFinite(createdAt) && (endedAt === undefined || (typeof endedAt === "number" && Number.isFinite(endedAt))); if (!isTerminalWorkflowStatus(r.status) || !stamped) { disclose?.(`workflow run ${JSON.stringify(id)}: its status or stamps do not read — the retention sweep leaves it in place`); continue; } out.push({ id, createdAt: r.createdAt, age: r.endedAt ?? r.createdAt }); } return out.sort((a, b) => (a.createdAt === b.createdAt ? 0 : a.createdAt < b.createdAt ? 1 : -1)); } export function workflowRunsDoomed(candidates, now, policy) { const doomed = []; for (let i = 0; i < candidates.length; i++) { const r = candidates[i]; const tooOld = policy.maxAgeMs !== undefined && r.age < now - policy.maxAgeMs; const overKeep = policy.keep !== undefined && i >= policy.keep; if (tooOld || overKeep) doomed.push({ id: r.id, byAge: tooOld && !overKeep }); } return doomed; } export async function reapWorkflowRuns(stores, scope, now, opts) { const policy = receiveRetentionPolicy("reapWorkflowRuns", opts, WORKFLOW_RUN_REAP_KNOBS); const { workflowRunStore: runs, workflowJournalStore: journals, workflowScriptStore: scripts } = stores; for (const [name, store] of [["workflowRunStore", runs], ["workflowJournalStore", journals], ["workflowScriptStore", scripts]]) { if (store !== undefined && typeof store.deleteRun !== "function") { throw new TypeError(`reapWorkflowRuns: the ${name} it is handed carries no deleteRun — its part of a run could not be erased with the run, so nothing is reaped. Implement deleteRun on it (the bundled stores are the reference), or do not hand the sweep a journal or script store whose parts are to outlive their runs.`); } } if (policy.maxAgeMs === undefined && policy.keep === undefined) return { deleted: [], kept: [] }; const listed = (await runs.listByScope(scope)).flatMap((s) => ("rowVerdict" in s ? [] : [[s.id, s]])); const deleted = []; const kept = []; for (const { id, byAge } of workflowRunsDoomed(workflowRunReapCandidates(listed, scope), now, policy)) { const stillDoomed = async () => { const live = await runs.get(id); if (live === null || live.scope !== scope || !isTerminalWorkflowStatus(live.status)) return false; return !(byAge && policy.maxAgeMs !== undefined && (live.endedAt ?? live.createdAt) >= now - policy.maxAgeMs); }; const legs = [ ["workflowJournalStore", () => journals?.deleteRun(id, scope)], ["workflowScriptStore", () => scripts?.deleteRun(id, scope)], ["workflowRunStore", async () => { if (await runs.deleteRun(id, scope)) deleted.push(id); else if ((await runs.get(id)) !== null) throw new Error(`workflow run ${JSON.stringify(id)} was no longer a terminal run of the scope when its row's turn came — the journal and script legs before it had already run`); }], ]; try { if (!(await stillDoomed())) continue; } catch (cause) { kept.push({ runId: id, store: "workflowRunStore", cause }); break; } for (const [store, leg] of legs) { try { await leg(); } catch (cause) { kept.push({ runId: id, store, cause }); } } if (kept.length > 0) break; } await runs.settleErasure?.(); return { deleted, kept }; } export const WORKFLOW_RUN_REAP_KNOBS = Object.freeze(["maxAgeMs", "keep"]); export class InMemoryWorkflowRunStore { runs = new Map(); async put(id, run) { if (this.runs.has(id)) { throw new WorkflowRunStoreError("workflow_run.already_exists", `workflow run id already exists`); } const stored = structuredClone(run); stored.id = id; stored.rev = run.rev ?? 0; this.runs.set(id, admitWorkflowRun(stored, id)); } async get(id) { const run = this.runs.get(id); return run ? structuredClone(readStoredWorkflowRun(run, { key: id })) : null; } async update(id, scope, run, expect, _opts) { const next = nextWorkflowRunOnUpdate(this.runs.get(id), id, scope, run, expect); if (!next) return false; this.runs.set(id, next); return true; } async listByScope(scope, opts) { return queryWorkflowRuns(this.runs.entries(), scope, opts); } async reap(scope, now, opts) { const policy = receiveRetentionPolicy("WorkflowRunStore.reap", opts, WORKFLOW_RUN_REAP_KNOBS); if (policy.maxAgeMs === undefined && policy.keep === undefined) return 0; const doomed = workflowRunsDoomed(workflowRunReapCandidates(this.runs.entries(), scope), now, policy); for (const { id } of doomed) this.runs.delete(id); return doomed.length; } async deleteRun(runId, scope) { const r = this.runs.get(runId); if (r === undefined || r.scope !== scope || !isTerminalWorkflowStatus(r.status)) return false; return this.runs.delete(runId); } async deleteBySession(sessionId, scope) { assertDeletionSessionId(sessionId, "WorkflowRunStore.deleteBySession"); const doomed = [...this.runs.values()].filter((r) => r.scope === scope && r.originatingSessionId === sessionId && isTerminalWorkflowStatus(r.status)).map((r) => r.id); for (const id of doomed) this.runs.delete(id); return doomed; } get size() { return this.runs.size; } }