UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

442 lines (441 loc) • 24.5 kB
import { types } from "node:util"; import { CheckpointError } from "./checkpoint-features.js"; import { boundedThrownName } from "./thrown-value.js"; import { checkpointRowLabel, readGateIdentity } from "./checkpoint-identity.js"; import { facetOf, isGateKind, isPendingKind, PAUSE_REGISTRY } from "./pause-registry.js"; import { callerKey } from "./caller-text.js"; import { receiptRefusal, receiveOwnProperties } from "./own-property-receipt.js"; import { principalNameFault, RECORDED_PRINCIPAL_NAME_SPELLING, recordedPrincipalNameOf } from "./principal-name.js"; import { isSha16 } from "./canonical-json.js"; import { readUnreadableDeleteId, rowUnreadableAt } from "./session.js"; import { isRowCorrupt, isString, pair, required, rowShapeReader } from "./row-shape.js"; import { frozenHandleCopy } from "./remote-env.js"; export const CHECKPOINT_LIST_LIMITS = Object.freeze({ overdue: Object.freeze({ default: 100, max: 500 }), session: Object.freeze({ default: 100, max: 100 }), }); const FACETS = ["A", "B", "-"]; const STATUSES = ["pending", "resolved", "expired"]; const OVERDUE_MEMBERS = ["cutoff", "facet", "after", "limit", "maxAgeMs"]; const SESSION_MEMBERS = ["sessionId", "axis", "scope", "status", "gateKinds", "toolCallId", "createdSince", "order", "after", "limit"]; function receiveQuery(raw, subject, face, members) { if (typeof raw !== "object" || raw === null) throw receiptRefusal(`${face}: the query must be an object, got ${raw === null ? "null" : typeof raw}`); const got = receiveOwnProperties(raw, { subject, unit: "member", moment: `at ${face}` }); const own = Object.create(null); for (const name of Object.keys(got)) { if (!members.includes(name)) throw receiptRefusal(`${face}: the query carries ${callerKey(name)}, which is not a member of ${subject} — refused rather than answered without the filter it names`); own[name] = got[name]; } return own; } function readGateKinds(raw) { const refuse = () => receiptRefusal("CheckpointSessionQuery.gateKinds must be a dense array of registered gate kinds (no hole, no accessor, not a Proxy) when present"); if (typeof raw !== "object" || raw === null || types.isProxy(raw) || !Array.isArray(raw)) throw refuse(); const length = Object.getOwnPropertyDescriptor(raw, "length")?.value; if (typeof length !== "number") throw refuse(); const kinds = []; for (let i = 0; i < length; i++) { const d = Object.getOwnPropertyDescriptor(raw, i); if (d === undefined || !("value" in d) || !isGateKind(d.value)) throw refuse(); kinds.push(d.value); } return Object.freeze(kinds); } function readLimit(raw, subject, bound) { if (raw === undefined) return bound.default; if (typeof raw === "number" && Number.isSafeInteger(raw) && raw >= 1 && raw <= bound.max) return raw; throw receiptRefusal(`${subject}.limit must be an integer in 1..${bound.max} when present`); } function readCursor(raw, subject, key, face) { const got = receiveQuery(raw, `${subject}.after`, face, [key, "token"]); const value = got[key]; if (typeof value !== "number" || Number.isNaN(value) || value === Infinity) throw receiptRefusal(`${subject}.after.${key} must be a finite number or -Infinity (a cursor is the order key of the page before)`); if (typeof got.token !== "string") throw receiptRefusal(`${subject}.after.token must be a string`); return { [key]: value, token: got.token }; } export function readCheckpointOverdueQuery(raw) { const face = "CheckpointStore.listOverdue"; const got = receiveQuery(raw, "CheckpointOverdueQuery", face, OVERDUE_MEMBERS); const { cutoff, facet, after } = got; if (typeof cutoff !== "number" || !Number.isFinite(cutoff)) throw receiptRefusal("CheckpointOverdueQuery.cutoff must be a finite number (epoch ms)"); if (!FACETS.includes(facet)) throw receiptRefusal(`CheckpointOverdueQuery.facet must be one of ${FACETS.map((f) => JSON.stringify(f)).join(" / ")}`); const { maxAgeMs } = got; if (maxAgeMs !== undefined && (typeof maxAgeMs !== "number" || !Number.isSafeInteger(maxAgeMs) || maxAgeMs < 0)) throw receiptRefusal("CheckpointOverdueQuery.maxAgeMs must be a whole number of milliseconds, 0 or more, when present"); return { cutoff, facet: facet, ...(after !== undefined ? { after: readCursor(after, "CheckpointOverdueQuery", "deadline", face) } : {}), limit: readLimit(got.limit, "CheckpointOverdueQuery", CHECKPOINT_LIST_LIMITS.overdue), ...(maxAgeMs !== undefined ? { maxAgeMs } : {}), }; } export function readCheckpointSessionQuery(raw) { const face = "CheckpointStore.listBySession"; const got = receiveQuery(raw, "CheckpointSessionQuery", face, SESSION_MEMBERS); const { sessionId, axis, scope, status, gateKinds, toolCallId, createdSince, order, after } = got; if (typeof sessionId !== "string" || sessionId === "") throw receiptRefusal("CheckpointSessionQuery.sessionId must be a non-empty string"); if (axis !== undefined && axis !== "session" && axis !== "run") throw receiptRefusal('CheckpointSessionQuery.axis must be "session" or "run" when present'); if (scope !== undefined && typeof scope !== "string") throw receiptRefusal(`CheckpointSessionQuery.scope must be a string when present, got ${typeof scope}`); if (status !== undefined && !STATUSES.includes(status)) throw receiptRefusal(`CheckpointSessionQuery.status must be one of ${STATUSES.join(" / ")} when present`); if (toolCallId !== undefined && typeof toolCallId !== "string") throw receiptRefusal(`CheckpointSessionQuery.toolCallId must be a string when present, got ${typeof toolCallId}`); if (createdSince !== undefined && (typeof createdSince !== "number" || !Number.isFinite(createdSince))) throw receiptRefusal("CheckpointSessionQuery.createdSince must be a finite number when present"); if (order !== undefined && order !== "oldest" && order !== "newest") throw receiptRefusal('CheckpointSessionQuery.order must be "oldest" or "newest" when present'); const kinds = gateKinds === undefined ? undefined : readGateKinds(gateKinds); return { sessionId, ...(axis !== undefined ? { axis: axis } : {}), ...(scope !== undefined ? { scope } : {}), ...(status !== undefined ? { status: status } : {}), ...(kinds !== undefined ? { gateKinds: kinds } : {}), ...(toolCallId !== undefined ? { toolCallId } : {}), ...(createdSince !== undefined ? { createdSince } : {}), order: order === "newest" ? "newest" : "oldest", ...(after !== undefined ? { after: readCursor(after, "CheckpointSessionQuery", "createdAt", face) } : {}), limit: readLimit(got.limit, "CheckpointSessionQuery", CHECKPOINT_LIST_LIMITS.session), }; } export function readCheckpointDeleteGuard(sessionId, raw) { const face = "CheckpointStore.deleteSessionCheckpoints"; if (typeof sessionId !== "string" || sessionId === "") throw receiptRefusal(`${face}: the session id must be a non-empty string`); const got = receiveQuery(raw, "CheckpointDeleteGuard", face, ["owner"]); const owner = got.owner === null ? null : recordedPrincipalNameOf(got.owner); if (owner === undefined) throw receiptRefusal(`CheckpointDeleteGuard.owner must be null or the owner name a session row holds — ${RECORDED_PRINCIPAL_NAME_SPELLING} — got ${principalNameFault(got.owner)}`); return { sessionId, owner }; } export function deleteGuardAdmits(head, owner) { return head !== undefined && head.owner === owner; } export function ownerSessionRowsDelete(sessionId, guard, headOf) { const read = readCheckpointDeleteGuard(sessionId, guard); return { sessionId: read.sessionId, isAdmitted: async () => deleteGuardAdmits(await headOf(read.sessionId), read.owner) }; } export function unreadableSessionRowsDelete(sessionId, headOf) { const id = readUnreadableDeleteId("CheckpointStore.deleteUnreadableSessionCheckpoints", sessionId); return { sessionId: id, isAdmitted: () => rowUnreadableAt(() => headOf(id)) }; } export async function deleteSessionRowsAtStart(rows, request, remove) { const taken = []; for (const [token, cp] of rows) if (cp.sessionId === request.sessionId) taken.push([token, cp]); if (!(await request.isAdmitted())) return 0; let n = 0; for (const [token, cp] of taken) if (await remove(token, cp)) n++; return n; } export function checkpointDeadlinePassed(deadline, cutoff) { return deadline !== undefined && (typeof deadline === "number" && Number.isFinite(deadline) ? deadline <= cutoff : true); } export function checkpointDeadlineColumn(deadline) { if (deadline === undefined) return null; return typeof deadline === "number" && Number.isFinite(deadline) ? deadline : Number.MIN_SAFE_INTEGER; } export function checkpointOverdueAt(row, maxAgeMs) { const deadline = row.deadline; if (deadline !== undefined) return typeof deadline === "number" ? deadline : null; if (maxAgeMs === undefined) return undefined; return isFiniteNumber(row.createdAt) ? row.createdAt + maxAgeMs : Number.NaN; } const RUN_SESSION_OF_ENTRY = Object.freeze({ cascade: "host", verify: "own", repair: "host" }); export function checkpointRunSessionOf(row) { try { return runSessionReading(row); } catch { return undefined; } } function runSessionReading(row) { const own = row.sessionId; if (typeof own !== "string" || !isRecord(row.state)) return undefined; const leg = Object.prototype.hasOwnProperty.call(row.state, "compositionLeg") ? row.state.compositionLeg : undefined; if (leg === undefined) return own; if (!isRecord(leg)) return undefined; const entry = leg.entry; if (typeof entry !== "string" || !Object.prototype.hasOwnProperty.call(RUN_SESSION_OF_ENTRY, entry)) return undefined; if (RUN_SESSION_OF_ENTRY[entry] === "own") return own; const host = leg.hostSessionId; return typeof host === "string" && host !== "" ? host : undefined; } export function checkpointRowUnreadable(diagnostic, standing = "unknown", thrownName) { const message = `${standing === "pending" ? CHECKPOINT_ROW_DAMAGED_SENTENCE : CHECKPOINT_ROW_UNCONFIRMED_SENTENCE} Diagnostic: ${diagnostic}`; return thrownName === undefined ? new CheckpointError("checkpoint.invalid_outcome", message, { reason: "requirements_damaged" }) : new CheckpointError("checkpoint.invalid_outcome", message, { reason: "requirements_damaged", thrownName: thrownName }); } export function isCheckpointRowUnreadable(e) { try { return e instanceof CheckpointError && e.code === "checkpoint.invalid_outcome" && e.detail?.reason === "requirements_damaged"; } catch { return false; } } export function storedCheckpointRowRefusal(key, row) { let why; let status; let pending = false; try { const answer = CHECKPOINT_ROW_SHAPE.read(row, { key }, ["rowKey"]); status = isRecord(row) ? row.status : undefined; pending = status === "pending" && row.executionOutcome === undefined; if (isRowCorrupt(answer)) why = `the row filed under the token does not read as a row (${answer.member}: ${answer.why})`; else if (row.token !== key) why = "the row filed under the token carries another token member"; } catch (e) { return checkpointRowUnreadable("the row filed under the token could not be read (a member threw when read)", "unknown", boundedThrownName(e)); } if (why === undefined) return undefined; if (pending) return checkpointRowUnreadable(`${why}.`, "pending"); const recorded = status === "pending" ? " It records an execution outcome." : ""; return checkpointRowUnreadable(`${why}. Its stored status is ${isStatusWord(status) ? `"${status}"` : "not one of the three words"}.${recorded}`, "unknown"); } function orderKey(value) { return typeof value === "number" && Number.isFinite(value) ? value : -Infinity; } function membersOf(key, cp) { return { key, token: cp.token, sessionId: cp.sessionId, scope: cp.scope, status: cp.status, gate: cp.gate, pendingAction: cp.pendingAction, createdAt: cp.createdAt, deadline: cp.deadline, state: cp.state, checkpointId: cp.checkpointId, resourceLedger: cp.resourceLedger, parentSessionId: cp.parentSessionId, parentTaskId: cp.parentTaskId, rootSessionId: cp.rootSessionId, rootSessionIncarnation: cp.rootSessionIncarnation }; } const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value); function memberOf(value, key) { return isRecord(value) && key in value ? value[key] : undefined; } const isStatusWord = (v) => STATUSES.some((s) => s === v); const isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v); const isAbsentOrNonBlankString = (v) => v === undefined || (typeof v === "string" && v.trim() !== ""); const gateShape = (m) => (isGateKind(memberOf(m.gate, "kind")) ? undefined : "its gate is not an object of a registered gate kind"); function workspaceHandleShape(handle) { if (handle === undefined) return undefined; if (!isRecord(handle)) return "its state's workspace handle is not an object"; const copy = frozenHandleCopy(handle); const missing = ["sandboxId", "provider", "mountPath"].find((member) => typeof copy[member] !== "string"); return missing === undefined ? undefined : `its state's workspace handle names no ${missing} string`; } const ROW_MEMBER_SHAPES = Object.freeze([ ["gate", gateShape], [ "pendingAction", (m) => { const kind = memberOf(m.pendingAction, "kind"); if (!isPendingKind(kind)) return "its pending action is not an object of a registered pending kind"; const gateKind = memberOf(m.gate, "kind"); if (isGateKind(gateKind) && PAUSE_REGISTRY[gateKind].pending !== kind) return "its pending action is not the one its gate kind pairs with"; if (kind !== "tool_approval") return undefined; if (typeof memberOf(m.pendingAction, "toolCallId") !== "string") return "its tool approval carries no tool call id"; const capabilityId = memberOf(m.pendingAction, "capabilityId"); return capabilityId === undefined || isSha16(capabilityId) ? undefined : "its tool approval's capability id is not a digest the engine mints (sixteen lowercase hex digits)"; }, ], [ "state", (m) => !isRecord(m.state) ? "its state is not an object" : !((id) => id === undefined || typeof id === "string")(memberOf(m.state, "legTaskId")) ? "its state's leg task id is not a string" : workspaceHandleShape(memberOf(m.state, "workspaceHandle")), ], ["createdAt", (m) => (isFiniteNumber(m.createdAt) ? undefined : "its createdAt is not a finite number")], ["deadline", (m) => (m.deadline === undefined || isFiniteNumber(m.deadline) ? undefined : "its deadline is not a finite number")], ["resourceLedger", (m) => (m.resourceLedger === undefined || isRecord(m.resourceLedger) ? undefined : "its resource ledger is not an object")], ["checkpointId", (m) => (m.checkpointId === undefined || (typeof m.checkpointId === "string" && m.checkpointId.trim() !== "") ? undefined : "its checkpoint id is not a non-blank string")], ["parentSessionId", (m) => (isAbsentOrNonBlankString(m.parentSessionId) ? undefined : "its parent session id is not a non-blank string")], ["parentTaskId", (m) => (isAbsentOrNonBlankString(m.parentTaskId) ? undefined : "its parent task id is not a non-blank string")], ["rootSessionId", (m) => (isAbsentOrNonBlankString(m.rootSessionId) ? undefined : "its root session id is not a non-blank string")], ["rootSessionIncarnation", (m) => (isAbsentOrNonBlankString(m.rootSessionIncarnation) ? undefined : "its root session incarnation is not a non-blank string")], ]); export const CHECKPOINT_ROW_DAMAGED_SENTENCE = "This engine cannot resume this checkpoint: its content does not read the way it was recorded when it was parked — it was changed or lost in storage. The checkpoint stays pending and nothing was consumed. Expire it, then start the task again."; export const CHECKPOINT_ROW_UNCONFIRMED_SENTENCE = "This engine cannot read this checkpoint row: its stored content does not read as a row, so whether it was already settled — and whether the action it approved has already run — cannot be confirmed from it. The action may already have run: check what became of it before deciding whether to run the work again — running it again may repeat it."; const asShapeMembers = (row) => row; export const CHECKPOINT_ROW_SHAPE = rowShapeReader({ family: "checkpoint", code: "checkpoint.invalid_outcome", sentence: CHECKPOINT_ROW_DAMAGED_SENTENCE, exit: "list-damaged", segments: [ { name: "rowKey", entries: [required("token", isString), required("scope", isString), required("status", isString)] }, { name: "placement", entries: [ pair("token", (m, ctx) => (m.token !== ctx.key ? "its token member is not the key the store files it under" : undefined)), pair("scope", (m) => (typeof m.scope !== "string" ? "its scope is not a string" : undefined)), pair("status", (m) => (isStatusWord(m.status) ? undefined : "its status is not one of pending / resolved / expired")), pair("gate", (m) => gateShape(asShapeMembers(m))), ], }, { name: "members", entries: ROW_MEMBER_SHAPES.map(([member, shape]) => pair(member, (m) => shape(asShapeMembers(m)))) }, ], }); const ROW_MEMBER_NAMES = ROW_MEMBER_SHAPES.map(([member]) => member); function damageOf(m, segments) { const answer = CHECKPOINT_ROW_SHAPE.read(m, { key: m.key }, segments); return isRowCorrupt(answer) ? answer.why : undefined; } export function rowMemberProblem(cp) { const members = { gate: cp.gate, pendingAction: cp.pendingAction, state: cp.state, createdAt: cp.createdAt, deadline: cp.deadline, resourceLedger: cp.resourceLedger, checkpointId: cp.checkpointId, parentSessionId: cp.parentSessionId, parentTaskId: cp.parentTaskId, rootSessionId: cp.rootSessionId, rootSessionIncarnation: cp.rootSessionIncarnation }; const answer = CHECKPOINT_ROW_SHAPE.read(members, { key: "" }, ["members"]); if (!isRowCorrupt(answer)) return undefined; const member = ROW_MEMBER_NAMES.find((name) => name === answer.member); if (member === undefined) throw new Error(`checkpoint row shape: member ${answer.member} is not in the member-shape table`); return { member, problem: answer.why }; } function thrownName(e) { return e instanceof Error ? e.constructor.name : typeof e; } function rowName(m) { return `${checkpointRowLabel(readGateIdentity(m.checkpointId, m.key))} of session ${typeof m.sessionId === "string" ? JSON.stringify(m.sessionId) : "(unreadable)"}`; } function afterCursor(key, token, cursor, ascending) { if (key !== cursor.key) return ascending ? key > cursor.key : key < cursor.key; return ascending ? token > cursor.token : token < cursor.token; } function compareKeys(a, b) { if (a.key !== b.key) return a.key < b.key ? -1 : 1; return a.token < b.token ? -1 : a.token > b.token ? 1 : 0; } export function selectOverduePage(rows, query, project, disclose) { const hits = []; for (const [token, cp] of rows) { const m = membersOf(token, cp); const overdueAt = checkpointOverdueAt(m, query.maxAgeMs); if (m.status !== "pending" || !checkpointDeadlinePassed(overdueAt, query.cutoff)) continue; const damage = typeof m.sessionId !== "string" ? "its sessionId is not a string" : damageOf(m, ["placement"]); if (damage !== undefined) { disclose?.(`${rowName(m)}: ${damage} — the overdue listing cannot read it, so it leaves it out`); continue; } if (facetOf(m.gate) !== query.facet) continue; const key = orderKey(overdueAt); if (query.after !== undefined && !afterCursor(key, token, { key: query.after.deadline, token: query.after.token }, true)) continue; hits.push({ key, token, cp, m }); } hits.sort(compareKeys); const out = []; let last; let i = 0; for (; i < hits.length && out.length < query.limit; i++) { const hit = hits[i]; let summary; try { summary = project(hit.cp); } catch (e) { disclose?.(`${rowName(hit.m)}: its summary could not be projected (${thrownName(e)}) — the overdue listing leaves it out`); continue; } out.push(summary); last = hit; } return { rows: out, ...(i < hits.length && last !== undefined ? { next: { deadline: last.key, token: last.token } } : {}) }; } export function selectSessionPage(rows, query, clone, disclose) { const ascending = query.order === "oldest"; const hits = []; if (query.gateKinds !== undefined && query.gateKinds.length === 0) return { rows: [] }; for (const [token, cp] of rows) { const m = membersOf(token, cp); if (typeof m.sessionId !== "string") { disclose?.(`${rowName(m)}: its sessionId is not a string — no session listing can attribute it, so it is left out`); continue; } const keyed = query.axis === "run" ? checkpointRunSessionOf(m) : m.sessionId; if (keyed === undefined) { disclose?.(`${rowName(m)}: its run session cannot be read (its state or its composition leg does not read) — no run listing can attribute it, so it is left out`); continue; } if (keyed !== query.sessionId) continue; if (query.scope !== undefined && typeof m.scope === "string" && m.scope !== query.scope) continue; if (query.status !== undefined && isStatusWord(m.status) && m.status !== query.status) continue; const gateKind = memberOf(m.gate, "kind"); if (query.gateKinds !== undefined && isGateKind(gateKind) && !query.gateKinds.includes(gateKind)) continue; if (query.toolCallId !== undefined) { const actionKind = memberOf(m.pendingAction, "kind"); const callId = memberOf(m.pendingAction, "toolCallId"); if (typeof actionKind === "string" && actionKind !== "tool_approval") continue; if (actionKind === "tool_approval" && typeof callId === "string" && callId !== query.toolCallId) continue; } if (query.createdSince !== undefined && isFiniteNumber(m.createdAt) && m.createdAt < query.createdSince) continue; const key = orderKey(m.createdAt); if (query.after !== undefined && !afterCursor(key, token, { key: query.after.createdAt, token: query.after.token }, ascending)) continue; hits.push({ key, token, cp, m, damage: damageOf(m, ["placement", "members"]) }); } hits.sort((a, b) => (ascending ? 1 : -1) * compareKeys(a, b)); const page = hits.slice(0, query.limit); const last = page[page.length - 1]; return { rows: page.map((h) => readOut(h, clone, disclose)), ...(hits.length > query.limit && last !== undefined ? { next: { createdAt: last.key, token: last.token } } : {}), }; } function readOut(hit, clone, disclose) { const { token, cp, m, damage } = hit; if (damage === undefined) return { kind: "row", checkpoint: clone(cp) }; disclose?.(`${rowName(m)}: ${damage} — listed as unreadable`); return { kind: "unreadable", token: token, scope: typeof m.scope === "string" ? m.scope : null, sessionId: String(m.sessionId), status: typeof m.status === "string" ? m.status : `(${typeof m.status})`, createdAt: isFiniteNumber(m.createdAt) ? m.createdAt : null, problem: damage, }; }