@sema-agent/core
Version:
Stateless, task-oriented AI agent core
1,181 lines • 71.7 kB
JavaScript
import { createHash, randomUUID } from "node:crypto";
import { resumedFromOf, workflowRunCreationIdOf } from "../core/workflow-run-store.js";
import { journalKeepsLaunches, readKeptLaunch, RESUME_CLAIM_REMAINING_MS_MAX } from "../core/workflow-journal-store.js";
import { parentConstraintChainVerdict } from "../core/runner/resume-checkpoint-screen.js";
import { judgeCheckpointRow } from "../core/checkpoint-row-verdict.js";
import { readMember, thrownName, thrownText } from "../core/thrown-value.js";
import { inlineUntrusted } from "../core/untrusted-text.js";
import { egressText } from "../core/untrusted-egress.js";
import { foreignLine } from "../core/protocol-http-auth.js";
import { WORKFLOW_AGENT_PARKED_ERROR_CODE, WORKFLOW_PARK_DECISION_MARK_BYTES_MAX, WORKFLOW_PARK_SETTLED_DECISIONS_MAX, WORKFLOW_STORE_WAIT_BOUND_MS, parkHolderAmong, workflowParkHolderOf } from "./workflow-types.js";
export const WORKFLOW_PARK_UNUSED_REASONS = Object.freeze([
"workflow_not_mounted",
"entry_unreadable",
"record_unreadable",
"not_holder",
"not_pending",
"decision_spent",
"launch_unrecorded",
"launch_unreadable",
"host_changed",
"denied",
"ask_unanswerable",
"call_changed",
"launch_refused",
"continuing_elsewhere",
"card_unresumable",
"waiting_elsewhere",
"run_not_ended",
"workflow_stopped",
]);
function frozenRows(table) {
for (const row of Object.values(table))
Object.freeze(row);
return Object.freeze(table);
}
export const WORKFLOW_PARK_UNUSED_REASON_CLASS = frozenRows({
workflow_not_mounted: { kept: "deliverable" },
entry_unreadable: { kept: "decide_again" },
record_unreadable: { kept: "deliverable" },
not_holder: { kept: "deliverable" },
not_pending: { kept: "withdraw" },
decision_spent: { spent: "decide_again" },
launch_unrecorded: { kept: "deliverable" },
launch_unreadable: { spent: "start_over" },
host_changed: { kept: "deliverable" },
denied: { kept: "deliverable", spent: "decide_again", spentWhen: "explicit" },
ask_unanswerable: { kept: "deliverable" },
call_changed: { kept: "deliverable" },
launch_refused: { kept: "deliverable" },
continuing_elsewhere: { kept: "deliverable" },
card_unresumable: { kept: "deliverable", spent: "start_over", spentWhen: "terminal" },
waiting_elsewhere: { kept: "deliverable" },
run_not_ended: { kept: "deliverable" },
workflow_stopped: { kept: "withdraw" },
});
export function workflowParkUnusedClassOf(reason, spent) {
if (typeof spent !== "boolean" || typeof reason !== "string" || !Object.hasOwn(WORKFLOW_PARK_UNUSED_REASON_CLASS, reason))
return undefined;
const row = WORKFLOW_PARK_UNUSED_REASON_CLASS[reason];
return spent ? row.spent : row.kept;
}
const SETTLING = new Set(WORKFLOW_PARK_UNUSED_REASONS.filter((r) => WORKFLOW_PARK_UNUSED_REASON_CLASS[r].spent !== undefined));
const UNMARKED_REASONS = new Set(["workflow_not_mounted", "entry_unreadable", "record_unreadable", "run_not_ended", "not_pending", "not_holder", "workflow_stopped"]);
function settlesDecision(o) {
if (!Object.hasOwn(WORKFLOW_PARK_UNUSED_REASON_CLASS, o.reason))
return false;
const row = WORKFLOW_PARK_UNUSED_REASON_CLASS[o.reason];
return row.spent !== undefined && (row.kept === undefined || o[row.spentWhen] === true);
}
const UNUSED_REASONS = new Set(WORKFLOW_PARK_UNUSED_REASONS);
function parkEntriesOn(token, records) {
const out = [];
for (const r of records) {
if (!Array.isArray(r.parks))
continue;
for (const entry of r.parks)
if (isObject(entry) && entry.token === token)
out.push({ runId: r.id, entry });
}
return out;
}
function holderEntriesOn(token, records) {
const holder = parkHolderAmong(token, records);
const ids = holder.kind === "held" ? [holder.runId] : holder.kind === "fork" ? holder.runIds : [];
return parkEntriesOn(token, records).filter(({ runId, entry }) => ids.includes(runId) && entry.parkedBy === runId);
}
function markKindOf(m) {
if (!isObject(m) || typeof m.decisionId !== "string" || typeof m.reason !== "string")
return undefined;
if (m.condition === undefined)
return SETTLING.has(m.reason) ? "final" : undefined;
return typeof m.condition === "string" && m.condition !== "" && UNUSED_REASONS.has(m.reason) ? "recoverable" : undefined;
}
function holderMarkOf(token, decisionId, records) {
for (const { runId, entry } of parkEntriesOn(token, records)) {
const m = Array.isArray(entry.settledDecisions) ? entry.settledDecisions.find((s) => markKindOf(s) === "final" && s.decisionId === decisionId) : undefined;
if (m !== undefined)
return { kind: "spent", runId, reason: m.reason, ...(typeof m.code === "string" ? { code: m.code } : {}), by: "mark" };
}
for (const { runId, entry } of holderEntriesOn(token, records)) {
const m = Array.isArray(entry.settledDecisions) ? entry.settledDecisions.find((s) => markKindOf(s) === "recoverable" && s.decisionId === decisionId) : undefined;
if (m === undefined)
continue;
const inputs = Array.isArray(m.inputs) ? m.inputs.filter((k) => HOST_FOLD_INPUTS.includes(k)) : [];
return { kind: "blocked", runId, reason: m.reason, ...(typeof m.code === "string" ? { code: m.code } : {}), ...(inputs.length > 0 ? { inputs } : {}), condition: m.condition };
}
return undefined;
}
export function workflowParkDecisionOf(token, decisionId, tree, card) {
if (card !== undefined && !PARK_CARD_STATES.has(card))
throw new TypeError(`workflowParkDecisionOf: card (${typeof card === "string" ? JSON.stringify(card) : `a ${typeof card}`}) is not one of ${[...PARK_CARD_STATES].join("/")}`);
const state = decisionStateOf(token, decisionId, tree);
if (card === undefined || card === "pending")
return state;
if (card !== "unread")
return { ...state, class: "withdraw" };
if (!("class" in state))
return state;
const { class: _class, ...rest } = state;
return rest;
}
const PARK_CARD_STATES = new Set(["pending", "resolved", "expired", "absent", "unread"]);
function decisionStateOf(token, decisionId, tree) {
const records = tree.records;
const callKeys = new Set(parkEntriesOn(token, records).map(({ entry }) => entry.callKey).filter((k) => typeof k === "string"));
let driven;
let refused;
let carried;
for (const r of records) {
const rows = r.decisions;
if (!Array.isArray(rows))
continue;
for (const d of rows) {
if (!isObject(d) || d.decisionId !== decisionId || typeof d.callKey !== "string" || !callKeys.has(d.callKey))
continue;
if (d.result === "driven")
driven ??= { kind: "driven", runId: r.id };
else if (d.result === "refused")
refused ??= { kind: "spent", runId: r.id, reason: "decision_spent", ...(typeof d.code === "string" ? { code: d.code } : {}), by: "drive" };
else if (d.result === "not_reached")
carried ??= { kind: "carried", runId: r.id };
}
}
const mark = holderMarkOf(token, decisionId, records);
return classed(driven ?? (mark?.kind === "spent" ? mark : undefined) ?? refused ?? carried ?? (mark?.kind === "blocked" ? mark : undefined) ?? { kind: "open" });
}
function classed(state) {
if (state.kind !== "spent" && state.kind !== "blocked")
return state;
const c = workflowParkUnusedClassOf(state.reason, state.kind === "spent");
return c === undefined ? state : { ...state, class: c };
}
export function claimRemainingOf(answer, now) {
let remaining;
try {
remaining = answer.remainingMs;
}
catch {
return { kind: "unreadable" };
}
if (remaining === undefined)
return { kind: "unsaid" };
if (typeof remaining !== "number" || !Number.isSafeInteger(remaining) || remaining < 1 || remaining > RESUME_CLAIM_REMAINING_MS_MAX)
return { kind: "unreadable" };
const at = now + remaining;
return claimLapseInstant(at) === undefined ? { kind: "unreadable" } : { kind: "at", at };
}
const ANSWER_RECORD_CLAIM_HOLDER_PREFIX = "answer-record:";
export function answerRecordClaimHolder() {
return `${ANSWER_RECORD_CLAIM_HOLDER_PREFIX}${randomUUID()}`;
}
export function isAnswerRecordClaimHolder(holder) {
return holder !== undefined && holder.startsWith(ANSWER_RECORD_CLAIM_HOLDER_PREFIX);
}
export function claimHeldOf(verdict) {
if (verdict.stopped !== undefined)
return { stoppedBy: verdict.stopped.by };
const lapse = verdict.lapse;
return {
...(isAnswerRecordClaimHolder(verdict.holder) ? { heldForAnswer: true } : verdict.holder !== undefined ? { holder: verdict.holder } : {}),
...(lapse?.kind === "at" ? { claimExpiresAt: lapse.at } : lapse?.kind === "unreadable" ? { claimLapseUnreadable: true } : {}),
};
}
export const CLAIM_REMAINING_UNREADABLE_NOTE = "the journal store answered a remaining time for the claim that does not read, so no time is named";
export function claimLapseInstant(expiresAt) {
if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt))
return undefined;
const at = new Date(expiresAt);
return Number.isNaN(at.getTime()) ? undefined : at.toISOString();
}
export const HOST_FOLD_INPUTS = Object.freeze(["tools", "baseline", "allowed_models", "agent_limits", "permissions", "model", "endpoint", "thinking", "account"]);
export function hostFoldStampOf(digests) {
return `v2;${HOST_FOLD_INPUTS.map((k) => `${k}=${digests[k]}`).join(";")}`;
}
function hostFoldChanges(was, now) {
const parts = (s) => {
const [v, ...rest] = s.split(";");
if (v !== "v2" || rest.length !== HOST_FOLD_INPUTS.length)
return undefined;
const m = new Map(rest.map((p) => [p.slice(0, p.indexOf("=")), p.slice(p.indexOf("=") + 1)]));
return HOST_FOLD_INPUTS.every((k) => m.has(k)) ? m : undefined;
};
const a = parts(was);
const b = parts(now);
return a === undefined || b === undefined ? undefined : HOST_FOLD_INPUTS.filter((k) => a.get(k) !== b.get(k));
}
const HOST_FOLD_INPUT_WORDS = {
tools: "the tools the deployment gives workflow agents",
baseline: "the deployment's other settings for workflow agents (their rules and tool lists)",
allowed_models: "the models workflows may use",
agent_limits: "the limits each workflow agent runs under (time, cost, tokens or turns)",
permissions: "this session's permission limits or approval posture",
model: "the model the workflow was launched with (its name now names another model object or configuration)",
endpoint: "the address the workflow's model is served from",
thinking: "the thinking level the workflow was launched with",
account: "the account the workflow runs for",
};
export function resumedWorkflowCallOf(pendingCall, outcome, toolName) {
if (pendingCall === undefined || pendingCall.toolName !== toolName || !isObject(pendingCall.args))
return undefined;
const id = pendingCall.args.resumeFromRunId;
if (typeof id !== "string" || id === "")
return undefined;
const approved = outcome?.gate === "policy_ask" && outcome.decision === "allow";
return { runId: id, toolCallId: pendingCall.toolCallId, approved };
}
export const WORKFLOW_TREE_RUNS_MAX = 4096;
export function storeErrorClassOf(err) {
const raw = thrownName(err);
if (raw === undefined || raw === "")
return typeof err;
const code = readMember(err, "code");
return `${foreignLine(raw, 64)}${typeof code === "string" ? `/${foreignLine(code, 64)}` : ""}`;
}
export function storeFaultReport(what, err) {
return new Error(egressText("same-principal", `${what}: ${thrownText(err)}`));
}
export function boundedStoreRead(ms) {
return (p) => new Promise((resolve) => {
const t = setTimeout(() => resolve({ ok: false }), ms);
p.then((value) => (clearTimeout(t), resolve({ ok: true, value })), () => (clearTimeout(t), resolve({ ok: false })));
});
}
export async function readWorkflowRunIn(store, id, scope, within) {
const got = await within(Promise.resolve().then(() => store.get(id)));
if (!got.ok)
return "unreadable";
return got.value !== null && got.value.scope === scope ? got.value : null;
}
export function isContinuationOf(a, b) {
if (resumedFromOf(b) !== a.id)
return false;
const named = b.resume?.fromCreationId;
return typeof named !== "string" || workflowRunCreationIdOf(a) === named;
}
const WORKFLOW_RUN_TREE = Symbol("WorkflowRunTree");
const mintTree = (root, records, sourceRecreated) => ({ root, records, ...(sourceRecreated !== undefined ? { sourceRecreated } : {}), [WORKFLOW_RUN_TREE]: true });
export function workflowRunTreeOfOne(run) {
return mintTree(run, [run]);
}
export function workflowClaimKeysOf(tree) {
const root = tree.root;
const recorded = root.treeId;
const named = typeof recorded === "string" ? recorded : resumedFromOf(root) === undefined ? root.id : undefined;
const treeId = named !== undefined && named === tree.sourceRecreated ? undefined : named;
return { keys: treeId === undefined || treeId === root.id ? [root.id] : [root.id, treeId], fragment: treeId === undefined };
}
export function parkBindingFault(key, row) {
if (key.token === "" || key.sessionId === "")
return "the record names no token or no session for it";
if (row === undefined)
return undefined;
if (row.token !== key.token)
return "the checkpoint store answered a row under another token";
if (row.sessionId !== key.sessionId)
return "the checkpoint belongs to another session than the parked row";
return undefined;
}
export function sameClaimKeys(a, b) {
return a.length === b.length && a.every((k, i) => k === b[i]);
}
export function workflowRunInTree(tree, id) {
return tree.records.find((r) => r.id === id);
}
export function workflowRunsBelow(tree, id) {
const below = new Set([id]);
const out = [];
for (const r of tree.records) {
if (r === tree.root)
continue;
const up = resumedFromOf(r);
if (up !== undefined && below.has(up) && !below.has(r.id)) {
below.add(r.id);
out.push(r);
}
}
return out;
}
export function workflowRunChildrenIn(tree, id) {
return tree.records.filter((r) => r !== tree.root && resumedFromOf(r) === id);
}
export function workflowRunLineIn(tree, id) {
const line = [];
const byId = new Map(tree.records.map((r) => [r.id, r]));
let at = byId.get(id);
while (at !== undefined && line.length < tree.records.length) {
line.push(at.id);
if (at === tree.root)
break;
at = byId.get(resumedFromOf(at) ?? "");
}
return line;
}
export function workflowLineTailOf(tree, runId) {
let at = runId;
for (let n = 0; n <= tree.records.length; n++) {
const next = workflowRunChildrenIn(tree, at);
if (next.length === 0)
return { kind: "tail", runId: at };
if (next.length > 1) {
const below = workflowRunsBelow(tree, runId);
return { kind: "fork", leaves: below.filter((r) => workflowRunChildrenIn(tree, r.id).length === 0).map((r) => r.id) };
}
at = next[0].id;
}
return { kind: "tail", runId: at };
}
const FORK_LEAVES_NAMED_MAX = 4;
export function workflowLineForkReason(leaves) {
const shown = leaves.slice(0, FORK_LEAVES_NAMED_MAX).map((l) => `"${l}"`);
return `that run was already continued, and the runs that continued it split into ${leaves.length} lines, so which one to continue is not one answer. The last run of each line is ${shown.join(", ")}${leaves.length > shown.length ? `, and ${leaves.length - shown.length} more` : ""}: resume from the one you mean (resumeFromRunId set to it), or start the workflow again`;
}
export function readWorkflowRunTree(store, runId, scope) {
return readWorkflowRunTreeWithin(store, runId, scope, boundedStoreRead(WORKFLOW_STORE_WAIT_BOUND_MS));
}
export async function readWorkflowRunTreeWithin(store, runId, scope, within, self) {
const read = (id) => (self !== undefined && id === self.id ? Promise.resolve(self) : readWorkflowRunIn(store, id, scope, within));
const line = [];
let at = await read(runId);
if (at === "unreadable" || at === null)
return "unreadable";
let sourceRecreated;
for (;;) {
line.push(at);
const up = resumedFromOf(at);
if (up === undefined)
break;
if (line.some((r) => r.id === up))
return "unreadable";
const source = await read(up);
if (source === "unreadable")
return "unreadable";
if (source === null || !isContinuationOf(source, at)) {
if (source !== null)
sourceRecreated = up;
break;
}
if (line.length >= WORKFLOW_TREE_RUNS_MAX)
return "over_bound";
at = source;
}
const root = line[line.length - 1];
const records = [root];
const seen = new Set([root.id]);
let frontier = [root];
while (frontier.length > 0) {
const next = [];
for (const parent of frontier) {
const listed = await within(Promise.resolve().then(() => store.listByScope(scope, { resumedFrom: parent.id })));
if (!listed.ok)
return "unreadable";
const ids = [];
for (const s of listed.value) {
if ("rowVerdict" in s)
return "unreadable";
if (s.resumedFrom === parent.id)
ids.push(s.id);
}
if (self !== undefined && self.id !== root.id && resumedFromOf(self) === parent.id && !ids.includes(self.id))
ids.push(self.id);
for (const id of ids) {
const r = await read(id);
if (r === "unreadable")
return "unreadable";
if (r === null || !isContinuationOf(parent, r))
continue;
if (seen.has(r.id))
return "unreadable";
seen.add(r.id);
records.push(r);
next.push(r);
if (records.length > WORKFLOW_TREE_RUNS_MAX)
return "over_bound";
}
}
frontier = next;
}
for (const r of line) {
if (r === self)
continue;
const down = records.find((d) => d.id === r.id);
if (down === undefined || workflowRunCreationIdOf(down) !== workflowRunCreationIdOf(r))
return "unreadable";
}
return mintTree(root, records, sourceRecreated);
}
export async function otherWaitingLine(tree, parkStore, fromRunId, within) {
const records = tree.records;
const onLine = new Set(workflowRunLineIn(tree, fromRunId));
const parentOf = new Map(records.map((r) => [r.id, r === tree.root ? undefined : resumedFromOf(r)]));
const below = (id, top) => {
for (let up = parentOf.get(id), n = 0; up !== undefined && n <= records.length; up = parentOf.get(up), n++)
if (up === top)
return true;
return false;
};
const waitOf = async (r) => {
if (r.errorCode !== WORKFLOW_AGENT_PARKED_ERROR_CODE)
return undefined;
const own = (token) => (r.agents.some((a) => a.parkedCheckpointToken === token) ? 0 : 1);
for (const p of [...(r.parks ?? [])].sort((a, b) => own(a.token) - own(b.token))) {
if (p.parkedBy !== r.id)
continue;
const holder = workflowParkHolderOf(p.token, tree);
const counts = (holder.kind === "held" && holder.runId === r.id) || (holder.kind === "fork" && holder.runIds.includes(r.id) && (onLine.has(r.id) || !holder.runIds.some((id) => onLine.has(id))));
if (!counts)
continue;
if (parkStore === undefined)
return "unreadable";
const read = await within(Promise.resolve().then(() => parkStore.get(p.token)).then((row) => ({ row, state: parkCardStateOf(row, p.token) })));
if (!read.ok || read.value.state === "unread")
return "unreadable";
if (read.value.state !== "pending")
continue;
const row = read.value.row;
const label = r.agents.find((a) => a.parkedCheckpointToken === p.token)?.label;
const checkpointId = row.checkpointId;
return { runId: r.id, ...(label !== undefined ? { label } : {}), ...(typeof checkpointId === "string" ? { checkpointId } : {}), ...(row.gate.kind === "resource_limit" ? { yielded: true } : {}) };
}
return undefined;
};
const self = records.find((r) => r.id === fromRunId);
const selfWaits = self === undefined ? undefined : await waitOf(self);
if (selfWaits === "unreadable")
return { kind: "unreadable" };
const holding = [];
for (const r of records) {
if (onLine.has(r.id) || (selfWaits !== undefined && !below(r.id, fromRunId)))
continue;
const w = await waitOf(r);
if (w === "unreadable")
return { kind: "unreadable" };
if (w !== undefined)
holding.push(w);
}
const heads = holding.filter((h) => !holding.some((o) => o !== h && below(o.runId, h.runId)));
return heads.length === 0 ? { kind: "none", root: tree.root.id } : { kind: "waiting", root: tree.root.id, lines: heads };
}
export function runThatDrove(records, token, callKey) {
return records.find((r) => (r.parks ?? []).some((p) => isObject(p) && p.token === token) && r.decisions?.some((d) => d.callKey === callKey && d.result === "driven") === true);
}
export function workflowParkWaitOf(token, runId, tree, card) {
const present = tree.records;
const own = present.find((r) => r.id === runId);
const entry = own?.parks?.find((p) => isObject(p) && p.token === token && p.parkedBy === runId);
if (own === undefined || entry === undefined)
return { kind: "unknown", why: "chain_incomplete" };
const drove = runThatDrove(present.filter((r) => r.id !== runId), token, entry.callKey);
if (drove !== undefined)
return { kind: "moved_on", runIds: [drove.id] };
const holder = workflowParkHolderOf(token, tree);
if (holder.kind === "held" && holder.runId !== runId)
return { kind: "moved_on", runIds: [holder.runId] };
if (holder.kind === "fork" && !holder.runIds.includes(runId))
return { kind: "moved_on", runIds: holder.runIds };
if (holder.kind === "none")
return { kind: "unknown", why: "chain_incomplete" };
if (card === "unread")
return { kind: "unknown", why: "card_unread" };
if (card !== "pending")
return { kind: "lapsed", card };
let top = -1;
let again = [];
for (const r of workflowRunsBelow(tree, runId)) {
for (const p of r.parks ?? []) {
if (!isObject(p) || p.callKey !== entry.callKey || p.token === token || p.parkedBy !== r.id || !Number.isSafeInteger(p.generation))
continue;
const g = p.generation;
if (g > top)
(top = g), (again = [r.id]);
else if (g === top && !again.includes(r.id))
again.push(r.id);
}
}
return again.length > 0 ? { kind: "moved_on", runIds: again.sort() } : { kind: "waiting" };
}
export async function readWorkflowParkWaits(seats, runId, scope) {
const within = boundedStoreRead(WORKFLOW_STORE_WAIT_BOUND_MS);
const tree = await readWorkflowRunTreeWithin(seats.runStore, runId, scope, within);
if (typeof tree === "string")
return tree;
const own = workflowRunInTree(tree, runId);
const tokens = [...new Set((own.parks ?? []).filter((p) => isObject(p) && p.parkedBy === runId && typeof p.token === "string").map((p) => p.token))];
const cardOf = async (token) => {
const read = await within(Promise.resolve()
.then(() => seats.checkpointStore.get(token))
.then((row) => ((s) => (s === "status_unknown" ? "unread" : s))(parkCardStateOf(row, token))));
return read.ok ? read.value : "unread";
};
const cards = await Promise.all(tokens.map(cardOf));
return new Map(tokens.map((token, i) => [token, workflowParkWaitOf(token, runId, tree, cards[i])]));
}
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
function parkCardStateOf(row, token) {
if (row === null)
return "absent";
if (row.token !== token)
return "unread";
const status = row.status;
return status === "pending" || status === "resolved" || status === "expired" ? status : "status_unknown";
}
const decisionOf = (entry) => ({ token: entry.token, outcome: entry.outcome, decisionId: entry.decisionId, ...(entry.inheritedGate !== undefined ? { inheritedGate: entry.inheritedGate } : {}) });
function readDecisions(raw) {
const usable = [];
const unreadable = [];
for (const e of raw) {
const runId = isObject(e) && typeof e.runId === "string" ? e.runId : "";
const decisionId = isObject(e) && typeof e.decisionId === "string" && e.decisionId !== "" ? e.decisionId : undefined;
if (!isObject(e) || runId === "" || typeof e.token !== "string" || e.token === "" || decisionId === undefined || !isObject(e.outcome)) {
unreadable.push({ runId, ...(decisionId !== undefined ? { decisionId } : {}) });
continue;
}
const outcome = e.outcome;
const inheritedGate = e.inheritedGate;
usable.push({ runId, token: e.token, decisionId, outcome: outcome, ...(isObject(e.inheritedGate) ? { inheritedGate: inheritedGate } : {}) });
}
return { usable, unreadable };
}
const SETTLE_ATTEMPTS = 3;
export function conditionOf(o) {
const holder = holderDetailOf(o).holder;
const said = [o.reason, o.code ?? null, o.changed ?? null, o.inputs ?? null, holder === undefined ? null : typeof holder === "string" ? holder : [...holder].sort(), o.why ?? null, o.rowReason ?? null, o.terminal === true, ...(o.heldForAnswer === true ? ["held_for_answer"] : [])];
return createHash("sha256").update(JSON.stringify(said)).digest("hex").slice(0, 32);
}
function placeMark(kept, m) {
const mark = { decisionId: m.decisionId, reason: m.reason, ...(m.code !== undefined ? { code: m.code } : {}), ...(m.inputs !== undefined && m.inputs.length > 0 ? { inputs: [...m.inputs] } : {}), ...(m.condition !== undefined ? { condition: m.condition } : {}) };
if (new TextEncoder().encode(JSON.stringify(mark)).length > WORKFLOW_PARK_DECISION_MARK_BYTES_MAX)
return "skipped";
const ofThis = (s) => s.decisionId === m.decisionId;
if (kept.some((s) => ofThis(s) && markKindOf(s) === "final"))
return "recorded";
const was = kept.findIndex((s) => ofThis(s) && markKindOf(s) === "recoverable");
if (was >= 0 && m.condition !== undefined && kept[was].condition === m.condition)
return "recorded";
const without = (at) => [...kept.slice(0, at), ...kept.slice(at + 1)];
if (was >= 0)
return [...without(was), mark];
if (kept.length < WORKFLOW_PARK_SETTLED_DECISIONS_MAX)
return [...kept, mark];
const oldest = m.condition === undefined ? kept.findIndex((s) => markKindOf(s) === "recoverable") : -1;
return oldest < 0 ? "skipped" : [...without(oldest), mark];
}
export function createWorkflowParkAdopter(seats) {
const within = boundedStoreRead(seats.waitBoundMs);
const readRun = async (id, scope) => (seats.store === undefined ? "unreadable" : readWorkflowRunIn(seats.store, id, scope, within));
const readTree = async (id, scope) => (seats.store === undefined ? "unreadable" : readWorkflowRunTreeWithin(seats.store, id, scope, within));
const settleOn = async (tree, scope, all, named) => {
const others = new Set();
const store = seats.store;
if (store === undefined)
return others;
let marks = all.filter((m, i) => all.findIndex((o) => o.token === m.token && o.decisionId === m.decisionId) === i);
let judged = tree;
for (let judgment = 0; judgment < 2 && marks.length > 0; judgment++) {
const byHolder = new Map();
for (const m of marks) {
const holder = workflowParkHolderOf(m.token, judged);
const home = holder.kind === "held" ? holder.runId : holder.kind === "fork" && holder.runIds.includes(named) ? named : undefined;
if (home !== undefined)
byHolder.set(home, [...(byHolder.get(home) ?? []), m]);
}
const moved = [];
for (const [holderId, ofHolder] of byHolder) {
const record = workflowRunInTree(judged, holderId);
if (record !== undefined)
moved.push(...(await settleOnHolder(store, record, scope, ofHolder, others)));
}
if (moved.length === 0 || judgment === 1)
break;
const again = await readTree(tree.root.id, scope);
if (typeof again === "string")
break;
judged = again;
marks = moved;
}
return others;
};
const settleOnHolder = async (store, held, scope, marks, others) => {
const runId = held.id;
let mineMayHaveLanded = false;
const creationId = workflowRunCreationIdOf(held);
for (let attempt = 0; attempt < SETTLE_ATTEMPTS; attempt++) {
const now = await readRun(runId, scope);
if (now === "unreadable" || now === null || now.status === "running" || workflowRunCreationIdOf(now) !== creationId)
return [];
const next = structuredClone(now);
let added = false;
const moved = [];
for (const m of marks) {
const entry = next.parks?.find((p) => isObject(p) && p.token === m.token && p.parkedBy === runId);
if (entry === undefined)
continue;
if (entry.passedTo !== undefined) {
moved.push(m);
continue;
}
const placed = placeMark(Array.isArray(entry.settledDecisions) ? entry.settledDecisions.filter((s) => isObject(s)) : [], m);
if (placed === "recorded") {
if (!mineMayHaveLanded)
others.add(m.decisionId);
continue;
}
if (placed === "skipped")
continue;
entry.settledDecisions = placed;
added = true;
}
if (!added)
return moved;
const won = await within(Promise.resolve().then(() => store.update(runId, scope, next, { rev: now.rev ?? 0, creationId }, { cause: "park_decision_settled" })));
if (won.ok && won.value)
return moved;
if (!won.ok)
mineMayHaveLanded = true;
}
return [];
};
const cardOf = async (parkStore, token) => {
if (parkStore === undefined)
return { state: "unread" };
const read = await within(Promise.resolve().then(() => parkStore.get(token)).then((row) => ({ row, state: parkCardStateOf(row, token) })));
if (!read.ok)
return { state: "unread" };
return read.value.state === "pending" ? { state: "pending", row: read.value.row } : { state: read.value.state };
};
const judgeCards = async (x, tree, parkStore, entries, settle, quiet) => {
const records = tree.records;
const carried = [];
const own = [];
const ownOf = (entry, reason, more = {}) => void own.push({ kind: "unused", runId: x.id, decisionIds: [entry.decisionId], reason, ...more });
let unresumable;
for (const entry of entries) {
const card = await cardOf(parkStore, entry.token);
const was = workflowParkDecisionOf(entry.token, entry.decisionId, tree, card.state === "status_unknown" ? "unread" : card.state);
if (was.kind === "spent" && was.by === "mark")
quiet.add(entry.decisionId);
if (card.state === "unread") {
ownOf(entry, "record_unreadable", { cardUnread: true });
continue;
}
const key = x.parks?.find((p) => p.token === entry.token);
if (card.state !== "pending") {
const continuedAs = key === undefined ? undefined : runThatDrove(records, entry.token, key.callKey)?.id;
ownOf(entry, "not_pending", continuedAs !== undefined ? { continuedAs } : {});
continue;
}
const holder = workflowParkHolderOf(entry.token, tree);
if (holder.kind === "held" ? holder.runId !== x.id : holder.kind === "fork" ? !holder.runIds.includes(x.id) : true) {
ownOf(entry, "not_holder", holder.kind === "held" ? { holder: holder.runId } : holder.kind === "fork" ? { holder: holder.runIds } : {});
continue;
}
const row = judgeCheckpointRow(card.row);
if (row.kind !== "ok") {
const facts = { code: row.code, ...(row.reason !== undefined ? { rowReason: row.reason } : {}), rowSentence: row.sentence };
unresumable ??= facts;
ownOf(entry, "card_unresumable", { ...facts, ...(row.terminal === true ? { terminal: true } : {}) });
if (row.terminal === true)
settle(entry, "card_unresumable", row.code);
continue;
}
if (was.kind === "spent") {
if (quiet.has(entry.decisionId))
continue;
ownOf(entry, "decision_spent", was.code !== undefined ? { code: was.code } : {});
settle(entry, "decision_spent", was.code);
continue;
}
carried.push({ entry, state: card.row.state });
}
return { carried, own, ...(unresumable !== undefined ? { unresumable } : {}) };
};
const adoptOne = async (runId, entries, leg, quiet, asides, approvedCall) => {
const own = [];
const toolCallId = leg.mintCallId();
const ctx = leg.ctxOf(toolCallId);
const scope = seats.scopeOf(ctx);
const tree = await readTree(runId, scope);
const x = typeof tree === "string" ? tree : workflowRunInTree(tree, runId);
const parkStore = seats.parkStoreOf(ctx);
const cardsFirst = async (reason) => {
for (const entry of entries) {
const card = await cardOf(parkStore, entry.token);
own.push({ kind: "unused", runId, decisionIds: [entry.decisionId], ...(card.state === "pending" ? { reason } : card.state === "unread" ? { reason: "record_unreadable", cardUnread: true } : { reason: "not_pending" }) });
}
for (const o of groupedByAnswer(own))
asides.push(o);
return "settled_before";
};
if (typeof tree === "string" || typeof x === "string" || x.resumeAdmissionIncomplete === true)
return cardsFirst("record_unreadable");
if (x.status === "running")
return cardsFirst("run_not_ended");
const settling = [];
const settle = (entry, reason, code) => {
if (approvedCall === undefined && !quiet.has(entry.decisionId))
settling.push({ token: entry.token, decisionId: entry.decisionId, reason, ...(code !== undefined ? { code } : {}) });
};
let judgedTree = tree;
const told = async (o) => {
if (o.kind !== "unused" || approvedCall !== undefined)
return o;
if (settlesDecision(o)) {
const marks = settling.filter((m) => m.reason === o.reason && m.code === o.code && o.decisionIds.includes(m.decisionId));
if (marks.length > 0)
for (const id of await settleOn(judgedTree, scope, marks, runId))
quiet.add(id);
return o;
}
if (UNMARKED_REASONS.has(o.reason))
return o;
const condition = conditionOf(o);
const marks = [];
for (const id of o.decisionIds) {
const entry = entries.find((e) => e.decisionId === id);
if (entry === undefined || quiet.has(id))
continue;
marks.push({ token: entry.token, decisionId: id, reason: o.reason, ...(o.code !== undefined ? { code: o.code } : {}), ...(o.inputs !== undefined ? { inputs: o.inputs } : {}), condition });
}
if (marks.length > 0)
for (const id of await settleOn(judgedTree, scope, marks, runId))
quiet.add(id);
return o;
};
const answer = await (async () => {
const judged = await judgeCards(x, tree, parkStore, entries, settle, quiet);
own.push(...judged.own);
if (judged.carried.length === 0)
return "settled_before";
let carried = judged.carried;
const carriedIdsOf = () => carried.map((c) => c.entry.decisionId);
const unusedCarried = (reason, more = {}) => ({ kind: "unused", runId, decisionIds: carriedIdsOf(), reason, ...more });
if (judged.unresumable !== undefined)
return told(unusedCarried("card_unresumable", { ...judged.unresumable, otherCard: true }));
const settledCarried = (reason, more = {}) => {
for (const { entry } of carried)
settle(entry, reason, more.code);
return told(unusedCarried(reason, more));
};
const lineOf = async (over) => {
const line = await otherWaitingLine(over, parkStore, x.id, within);
return line.kind === "unreadable" ? unusedCarried("record_unreadable") : line.kind === "waiting" ? unusedCarried("waiting_elsewhere", { waiting: line.lines }) : line.root;
};
const line0 = await lineOf(tree);
if (typeof line0 !== "string")
return told(line0);
const claimKeys = workflowClaimKeysOf(tree).keys;
const sameTree = (over) => sameClaimKeys(workflowClaimKeysOf(over).keys, claimKeys);
if (x.errorCode !== WORKFLOW_AGENT_PARKED_ERROR_CODE)
return unusedCarried("record_unreadable");
let launch;
if (journalKeepsLaunches(seats.journalStore)) {
const launchRead = await readKeptLaunch(seats.journalStore, runId, scope, seats.waitBoundMs);
if (launchRead.kind === "failed") {
if (launchRead.cause !== undefined)
seats.reportStoreFault?.(`the launch record of workflow run ${JSON.stringify(runId)} could not be read by the engine's continuation`, launchRead.cause.err);
return unusedCarried("record_unreadable");
}
if (launchRead.kind === "defect")
return settledCarried("launch_unreadable", { code: launchRead.member });
if (launchRead.kind === "record")
launch = launchRead.record;
}
if (launch !== undefined || x.hostFoldDigest !== undefined) {
let fold;
try {
fold = seats.hostFoldDigest(ctx, launch);
}
catch {
fold = undefined;
}
if (fold === undefined || x.hostFoldDigest === undefined || fold !== x.hostFoldDigest) {
const inputs = fold === undefined || x.hostFoldDigest === undefined ? undefined : hostFoldChanges(x.hostFoldDigest, fold);
return told(unusedCarried("host_changed", { changed: "identity", ...(inputs !== undefined && inputs.length > 0 ? { inputs } : {}) }));
}
}
for (const { entry, state } of carried) {
const verdict = parentConstraintChainVerdict(state, entry.inheritedGate?.parentConstraints ?? seats.chainToHand(ctx));
if (verdict !== undefined)
return told(unusedCarried("host_changed", { changed: "parent_chain", code: verdict.code }));
}
if (approvedCall !== undefined) {
seats.holdForCall(runId, approvedCall, { decisions: carried.map(({ entry }) => decisionOf(entry)) });
return "carried";
}
if (launch === undefined)
return told(unusedCarried("launch_unrecorded"));
let superseded;
const rejudge = async () => {
const now = await readTree(runId, scope);
const xNow = typeof now === "string" ? undefined : workflowRunInTree(now, runId);
if (typeof now === "string" || xNow === undefined || xNow.status === "running" || xNow.resumeAdmissionIncomplete === true) {
superseded = unusedCarried("record_unreadable");
return false;
}
judgedTree = now;
const again = await judgeCards(xNow, now, parkStore, carried.map((c) => c.entry), settle, quiet);
own.push(...again.own);
const lost = carried.filter((c) => !again.carried.some((a) => a.entry === c.entry) && !quiet.has(c.entry.decisionId)).length;
carried = again.carried;
if (carried.length === 0)
superseded = "settled_before";
return { lost, ...(again.unresumable !== undefined ? { unresumable: again.unresumable } : {}) };
};
const confirm = async () => {
const again = await rejudge();
if (again === false || carried.length === 0)
return false;
if (again.unresumable !== undefined || again.lost > 0) {
superseded = again.unresumable !== undefined ? unusedCarried("card_unresumable", { ...again.unresumable, otherCard: true }) : unusedCarried("record_unreadable");
return false;
}
const line = await lineOf(judgedTree);
if (typeof line !== "string")
superseded = line;
else if (!sameTree(judgedTree))
superseded = unusedCarried("record_unreadable");
return superseded === undefined ? carried.map(({ entry }) => decisionOf(entry)) : false;
};
const deniedUnderClaim = async (layer) => {
if ((await rejudge()) === false || carried.length === 0)
return undefined;
if (!sameTree(judgedTree)) {
superseded = unusedCarried("record_unreadable");
return undefined;
}
const o = await settledCarried("denied", { code: layer, explicit: true });
if (o.kind !== "unused")
return o;
const after = await readTree(runId, scope);
const stands = (id) => {
const entry = carried.find((c) => c.entry.decisionId === id)?.entry;
if (typeof after === "string" || entry === undefined)
return false;
const was = workflowParkDecisionOf(entry.token, id, after);
return was.kind === "spent" && was.by === "mark" && was.reason === "denied" && was.code === layer;
};
const unrecorded = o.decisionIds.filter((id) => !stands(id));
if (unrecorded.length === 0)
return o;
own.push({ kind: "unused", runId, decisionIds: unrecorded, reason: "record_unreadable", answerUnrecorded: true });
const recorded = o.decisionIds.filter((id) => !unrecorded.includes(id));
return recorded.length > 0 ? { ...o, decisionIds: recorded } : "settled_before";
};
const supersededAnswer = () => (superseded === "settled_before" ? superseded : told(superseded ?? unusedCarried("record_unreadable")));
const name = launch.callArgs.name;
const input = { script: launch.script, ...(launch.effectiveArgs !== undefined ? { args: launch.effectiveArgs } : {}), ...(typeof name === "string" ? { name } : {}), resumeFromRunId: runId };
const byPerson = carried.every((c) => isObject(c.entry.outcome) && isObject(c.entry.outcome.hostDecision) && c.entry.outcome.hostDecision.decidedBy === "person");
if (leg.gate !== undefined) {
let judged;
try {
judged = await leg.gate.judge({ toolCallId, toolName: seats.toolName, input }, byPerson ? "person" : "none");
}
catch {
judged = { kind: "ask_unanswerable" };
}
if (judged.kind === "denied" && judged.explicit) {
const layer = judged.layer;
const under = await seats.underClaim(claimKeys, scope, () => deniedUnderClaim(layer));
if ("claimHeld" in under && under.claimHeld.stoppedBy !== undefined)
return unusedCarried("workflow_stopped", { stoppedBy: under.claimHeld.stoppedBy });
if ("claimHeld" in under)
return unusedCarried("continuing_elsewhere", { ...under.claimHeld, answerUnrecorded: true });
if ("refused" in under)
return unusedCarried("record_unreadable", { answerUnrecorded: true });
return under.value ?? supersededAnswer();
}
if (judged.kind === "denied")
return settledCarried("denied", { code: judged.layer });
if (judged.kind === "ask_unanswerable")
return told(unusedCarried("ask_unanswerable", judged.code !== undefined ? { code: judged.code } : {}));
if (judged.kind === "call_changed")
return told(unusedCarried("call_changed"));
}
let started;
try {
started = await seats.launch({ fromRunId: runId, launch, decisions: carried.map(({ entry }) => decisionOf(entry)), claimKeys }, ctx, confirm);
}
catch (e) {
started = { refused: `the continuation's launch threw ${storeErrorClassOf(e)}` };
seats.reportStoreFault?.(`the continuation's launch of workflow run ${JSON.stringify(runId)} threw`, e);
}
if ("refused" in started)
return told(unusedCarried("launch_refused", { why: neutral(started.refused, WHY_ECHO_MAX) }));
if ("claimHeld" in started)
return told(started.claimHeld.stoppedBy !== undefined ? unusedCarried("workflow_stopped", { stoppedBy: started.claimHeld.stoppedBy }) : unusedCarried("continuing_elsewhere", started.claimHeld));
if ("superseded" in started)
return supersededAnswer();
const stepDenied = carried.some((c) => isObject(c.entry.outcome) && c.entry.outcome.decision === "deny");
return { kind: "started", runId, decisionIds: carriedIdsOf(), continuedAs: started.runId, ...(stepDenied ? { stepDenied: true } : {}) };
})();
for (const o of groupedByAnswer(own))
asides.push(await told(o));
return answer;
};
return async (leg) => {
const { usable, unreadable } = readDecisions(seats.decisions);
const out = [];
const byRun = new Map();
for (const e of usable) {
const was = byRun.get(e.runId) ?? [];
if (!was.some((s) => s.token === e.token && s.decisionId === e.decisionId))
byRun.set(e.runId, [...was, e]);
}
const unreadableRuns = new Map();
for (const u of unreadable) {
const was = unreadableRuns.get(u.runId) ?? [];
unreadableRuns.set(u.runId, u.decisionId !== undefined && !was.includes(u.decisionId) ? [...was, u.decisionId] : was);
}
for (const [runId, ids] of unreadableRuns)
if (!byRun.has(runId))
out.push({ kind: "unused", runId, decisionIds: ids, reason: "entry_unreadable" });
for (const [runId, entries] of byRun) {
const resumed = leg.resumedCall?.runId === runId ? leg.resumedCall : undefined;
if (resumed !== undefined) {
if (resumed.approved) {
try {
const own = [];
const adopted = await adoptOne(runId, entries, leg, new Set(), own, resumed.toolCallId);
const answered = own.find((o) => o.kind === "unused" && o.reason === "card_unresumable") ?? (adopted === "settled_before" ? own[0] : adopted);
const refusal = answered === undefined || answered === "carried" ? undefined : resumedCallRefusalOf(answered);
if (refusal !== undefined)
seats.holdForCall(runId, resumed.toolCallId, { refusal });
}
catch {
}
}
continue;
}
try {
const quiet = new Set();
const asides = [];
const adopted = await adoptOne(runId, entries, leg, quiet, asides);
for (const o of adopted === "carried" || adopted === "settled_before" ? asides : [adopted, ...asides]) {
const kept = o.kind === "unused" ? o.decisionIds.filter((id) => !quiet.has(id)) : [];
if (o.kind !== "unused" || kept.length === o.decisionIds.length)
out.push(o);
else if (kept.length > 0)
out.push({ ...o, decisionIds: kept });
}
}
catch {
out.push({ kind: "unused", runId, decisionIds: entries.map((e) => e.decisionId), reason: "record_unreadable" });
}
}
return out;
};
}
const adopters = new WeakMap();
export function registerWorkflowParkAdopter(tool, adopter) {
adopters.set(tool, adopter);
}
export function workflowParkAdopterOf(tool) {
return adopters.get(tool);
}
export function unmountedWorkflowParkAdoptions(raw) {
const byRun = new Map();
for (const e of raw) {
const runId = isObject(e) && typeof e.runId === "string" ? e.runId : "";
const id = isObject(e) && typeof e.decisionId === "string" ? [e.decisionId] : [];
byRun.set(runId, [...(byRun.get(runId) ?? []), ...id]);
}
return [...byRun].map(([runId, decisionIds]) => ({ kind: "unused", runId, decisionIds, reason: "workflow_not_mounted" }));
}
export function workflowParkUnusedSentence(o) {
const echo = (s) => `"${neutral(s)}"`;
const waiting = "The approval card is still waiting";
switch (o.reason) {
case "workflow_stopped":
return `the workflow was stopped${o.stoppedBy !== undefined ? ` (by ${echo(o.stoppedBy)})` : ""}: it does not run another step, so this decision continues nothing and nothing was started. Nothing is left to do for this decision; to run the work again, start the workflow again`;
case "workflow_not_mounted":
return `this run of the session cannot start workflows. ${waiting}, and the decision is kept for a later run of the session that can`;
case "entry_unreadable":
return `the deployment handed the decision over without its decision id or its outcome. ${waiting}; decide it again, and report the defect to the deployment if this repeats`;
case "record_unreadable":
if (o.cardUnread === true)
return `the approval card could not be read right now, so whether it is still waiting is not known; the next run of this session tries again`;
if (o.answerUnrecorded === true)
return `a person answered no when asked to continue the workflow, and the engine could not confirm that it recorded that answer, so nothing was started and the same decision may be asked about again. If the approval card is still waiting, decide it again (a new decision) to continue the run, or start the workflow again`;
return `the workflow run's record could not be read right now, or the run did not stop on an approval. ${waiting}; the next run of this session tries again. If the answer stays the same, the workflow may have more runs than the ${WORKFLOW_TREE_RUNS_MAX} the engine reads to judge a continuation (every continuation of a run adds one): then start the workflow again — it runs from its first step`;
case "run_not_ended":
return `the run that holds the approval card has not written down how it ended — its record still says it is running — so the engine cannot continue it from this decision and nothing was started. ${waiting}; if that run is still running, decide again once it has ended, and if it stopped without writing its end, nothing continues it from this card: start the workflow again — it runs from its first step`;
case "not_holder": {
const holder = o.holder === undefined ? "" : typeof o.holder === "string" ? ` (${echo(o.holder)})` : ` (${o.holder.slice(0, 2).map(echo).join(", ")}${o.holder.length > 2 ? ", …" : ""})`;
return `the card now belongs to a later run of the workflow${holder}, so this decision named the wrong run. ${waiting}; the decision is to be handed to the run that holds it`;
}
case "not_pending":
return o.continuedAs !== undefined
? `the approval card was already used to continue the run, as run ${echo(o.continuedAs)}, and no longer waits for a decision; run ${echo(o.continuedAs)}'s completion notification and record tell what came of it. Nothing is left to do for this decision`
: "the approval card is no longer waiting for a decision (it was decided elsewhere, it expired, or it was removed). Nothing is left to do for this decision";
case "continuing_elsewhere": {
const self = typeof o.holder === "string" && o.holder === o.runId;
const holderRun = typeof o.holder === "string" ? `run ${echo(o.holder)}` : undefined;
const recording = "another leg of this workflow, recording a person's answer to continuing it";
const at = claimLapseInstant(o.claimExpiresAt);
const when = at !== undefined ? `at ${at} at the latest` : o.claimLapseUnreadable === true ? CLAIM_REMAINING_UNREADABLE_NOTE : undefined;
const lapse = `or once the claim lapses${when !== undefined ? ` (${when})` : ""} if its process stopped without giving it back`;
const mayHaveUsed = o.heldForAnswer !== true && !self;
const whatCame = `${mayHaveUsed && holderRun !== undefined ? `If ${holderRun} was started, its completion notification and record tell what came of it. ` : ""}The workflow's run records tell whether the run was continued, and the approval card tells whether it still waits for a decision`;
if (o.answerUnrecorded === true) {
const holderSaid = o.heldForAnswer === true ? `${recording},` : self ? `run ${echo(o.runId)} itself (it is still running, or has just stopped and not yet given the claim back)` : holderRun ?? "another leg of this workflow";
return `a person answered no when asked to continue the workflow, and that answer was not recorded: ${holderSaid} held the workflow's resume claim at that moment${mayHaveUsed ? " and may have continued the run with this same decision" : ""}, so this leg started nothing. ${whatCame}`;
}
const who = o.heldForAnswer === true ? `${recording}, holds the claim to continue this workflow` : self ? `run ${echo(o.runId)} itself holds the claim to continue this workflow right now (it is still running, or has just stopped and not yet given the claim back)` : `another run${holderRun !== undefined ? ` (${holderRun})` : ""} holds the claim to continue this workflow right now`;
if (o.heldForAnswer === true) {
const back = `The claim comes free when that leg gives it back, ${lapse}`;
return `${who}, so ${o.decisionIds.length > 0
? `this leg did not use this decision; what that leg records about it is read the next time the decision is handed over. ${back}`
: `nothing was started. ${back}; the run's approval card then tells whether the run waits for a decision`}`;
}
return `${who}, so ${o.decisionIds.length > 0
? `this decision was not used this time${mayHaveUsed ? "; that run may be continuing the run with this same decision" : ""}. ${whatCame}. The claim comes free when that run gives it back, ${lapse}`
: self
? `nothing was started; it can be continued once it has ended and given the claim back, ${lapse}`
: `nothing was started. If you were told that the engine continues this run${holderRun !== undefined ? ` as ${holderRun}` : ""}, do not call again: ${holderRun !== undefined ? `${holderRun}'s` : "that continuation's"} completion notification tells what came of it. If you were not told that, ${holderRun ?? "the run that holds the claim"} is another continuation of this workflow, and this run cannot be continued while that run holds the claim, which comes free when that run gives it back, ${lapse}`}`;
}
case "waiting_elsewhere": {
const lines = o.waiting ?? [];
const kept = o.decisionIds.length > 0;
const runOf = (l) => `run ${echo(l.runId)}`;
const stopped = (l) => {
const at = `${l.label !== undefined ? ` at agent ${echo(l.label)}` : ""}${l.checkpointId !== undefined ? ` (checkpoint ${echo(l.checkpointId)})` : ""}`;
return l.yielded === true ? `${runOf(l)} yielded${at} and waits to be continued` : `${runOf(l)} stopped on an approval card${at}`;
};
if (lines.length <= 1) {
const l = lines[0];
const run = l !== undefined ? runOf(l) : "another run of it";
const what = l !== undefined ? stopped(l) : `${run} stopped on an approval card`;
const wayOut = l?.yielded === true ? `continue ${run} first` : `decide that card first, or continue ${run} instead`;
return `another line of this workflow is waiting: ${what}, and a workflow runs or waits on one line at a time. ${kept ? `${waiting}; ${wayOut}, then decide this card again to continue the run` : `Nothing was started; ${wayOut}`}`;
}
const shown = lines.slice(0, WAITING_LINES_NAMED_MAX);
const list = `${shown.map(stopped).join("; ")}${lines.length > shown.length ? `; and ${lines.length - shown.length} more` : ""}`;
const anyCard = lines.some((l) => l.yielded !== true);
const wayOut = anyCard ? "decide any one of those cards first, or continue one of those runs instead" : "continue one of those runs first";
return `other lines of this workflow are waiting: ${list}, and a workflow runs or waits on one line at a time. ${kept ? `${waiting}; ${wayOut} — each moves its own line —, then decide this card again once none of them waits` : `Nothing was started; ${wayOut}`}`;
}
case "card_unresumable":
if (o.otherCard === true)
return `another approval card of this workflow run is one this engine cannot resume${unresumableCode(o)}: ${o.rowSentence ?? ""} A continuation would stop on that card, so none was started. ${waiting}: handed over again without that card's decision, this decision continues the run (which then stops on that card once more)`;
return o.terminal === true
? `the approval card's checkpoint is one no engine release resumes${unresumableCode(o)}: ${o.rowSentence ?? ""} The workflow run cannot be continued from this card; start the workflow again`
: `this engine cannot resume the approval card's checkpoint${unresumableCode(o)}: ${o.rowSentence ?? ""} This engine cannot continue the workflow run from this card. If the deployment still runs a worker whose engine release reads the card, the decision can continue the run there; otherwise cancel the run and start the workflow again`;
case "decision_spent":
return `this decision was already used once to continue the run, and that continuation refused it${o.code !== undefined ? ` (${neutral(o.code)})` : ""}. ${waiting}; decide it again — a new decision — to continue the run`;
case "launch_unrecorded":
return `this run has no record of what the workflow was started with (it was stopped before this deployment kept one, or the record is gone), so the engine cannot continue it on its own. ${waiting}: the session's model continues the run by calling the Workflow tool with the run's original script and resumeFromRunId — where that call needs an approval, the approved call carries the decision and continues the run; where it does not, the run stops on the same card once more, under a new run, and deciding that card again continues it`;
case "launch_unreadable":
return `the record of what the workflow was started with does not read back in the shape it was written in${o.code !== undefined ? ` (${neutral(o.code)})` : ""}, so the run cannot be continued here. Start the workflow again, and report the defect to the deployment`;
case "host_changed":
return o.changed === "parent_chain"
? `the permission rules the workflow's agents were stopped under have changed since. ${waiting}: once those rules are back to what they were, deciding the card again continues the run — or start the workflow again`
: o.inputs !== undefined
? `what the workflow's agents run under has changed since the workflow stopped: ${o.inputs.map((k) => HOST_FOLD_INPUT_WORDS[k]).join("; ")}. ${waiting}: once ${o.inputs.length === 1 ? "it is back to what it was" : "they are back to what they were"}, deciding the card again continues the run — or start the workflow again`
: `what the workflow's agents run under (the deployment's settings for workflow agents, this session's permission limits, the workflow's model, or the account it runs for) has changed since the workflow stopped. ${waiting}: once it is back to what it was, deciding the card again continues the run — or start the workflow again`;
case "denied":
return o.explicit === true
? `a person answered no when asked to continue the workflow. ${waiting}; decide the card again (a new decision) to continue the run, or start the workflow again`
: `this session's permission settings now refuse to run the workflow${o.code !== undefined ? ` (${neutral(o.code)})` : ""}. ${waiting}: once ${o.code === "persisted_rule" ? "that deny rule for the Workflow tool is removed" : o.code === "mode" ? "the session is out of that permission mode" : "the Workflow tool is allowed again"}, deciding the card again continues the run — or start the workflow again`;
case "call_changed":
return `the Workflow call that continues the run came back changed when it was judged (an approver's edit, or a policy's or a hook's rewrite of its arguments), and the engine's continuation runs only what the workflow was started with, so nothing was started. ${waiting}: the session's model can call the Workflow tool with resumeFromRunId itself — that call is judged on its own card, where the change can be made again; it runs as approved and stops on the same approval step once more, under a new run, and deciding that step's card continues it`;
case "ask_unanswerable":
return `continuing the workflow needs a person's approval that ${o.code === "approval_window_expired" ? "was asked for, and the approval window for it closed with no one answering it" : "nobody can give in this session right now"}. ${waiting}: the session's model can ask for that approval as a new card, or the card can be decided again where a person can approve`;
case "launch_refused":
return `the workflow could not be started${o.why !== undefined ? `: ${neutral(o.why, WHY_ECHO_MAX)}` : ""}. ${waiting}: once the cause clears, deciding the card again continues the run; if it does not clear, start the workflow again`;
}
}
const settledForGood = (o) => workflowParkUnusedClassOf(o.reason, settlesDecision(o)) !== "deliverable";
export function notContinuedRefusalOf(runId, reason, more = {}) {
const { decisionIds = [], ...rest } = more;
return `workflow run "${neutral(runId)}" is not continued: ${workflowParkUnusedSentence({ kind: "unused", runId, decisionIds, reason, ...rest })}.`;
}
export const WORKFLOW_TREE_OVER_BOUND_REASON = `its workflow has more runs than the ${WORKFLOW_TREE_RUNS_MAX} the engine reads to judge a continuation (every continuation of a run adds one), so it is not continued and nothing was started. Start the workflow again — it runs from its first step`;
export function workflowTreeOverBoundSentence(runId) {
return `workflow run "${neutral(runId)}" is not continued: ${WORKFLOW_TREE_OVER_BOUND_REASON}.`;
}
const unresumableCode = (o) => o.code === undefined ? "" : ` (${neutral(o.code)}${o.rowReason !== undefined ? `, ${neutral(o.rowReason)}` : ""})`;
export function resumedCallRefusalOf(o) {
if (o.kind !== "unused")
return undefined;
if (o.reason === "not_pending" && o.continuedAs !== undefined) {
return `workflow run "${neutral(o.runId)}" was already continued from its approval card by the engine, as run "${neutral(o.continuedAs)}" — the parked step ran there with the person's decision, so this call does not continue it again. What came of it is in run "${neutral(o.continuedAs)}"'s completion notification and record.`;
}
if (o.reason === "card_unresumable" || o.reason === "waiting_elsewhere")
return `workflow run "${neutral(o.runId)}" is not continued: ${workflowParkUnusedSentence(o)}.`;
return undefined;
}
const ECHO_MAX = 64;
const WAITING_LINES_NAMED_MAX = 3;
const WHY_ECHO_MAX = 160;
const neutral = (s, max = ECHO_MAX) => inlineUntrusted(s, max);
function decisionKeyOf(runId, decisionIds) {
return createHash("sha256").update(JSON.stringify([runId, [...new Set(decisionIds)].sort()])).digest("hex").slice(0, 32);
}
export function workflowParksContributor(input) {
const decisions = input.decisions;
if (decisions === undefined || decisions.length === 0)
return undefined;
return async () => {
const outcomes = input.adopter !== undefined ? await input.adopter({ gate: input.gate, mintCallId: input.mintCallId, ctxOf: input.ctxOf, ...(input.resumedCall !== undefined ? { resumedCall: input.resumedCall } : {}) }) : unmountedWorkflowParkAdoptions(decisions);
for (const o of outcomes) {
if (o.kind === "started") {
try {
input.deliver({
code: "workflow.parked_decision_used",
message: `the approval decision for workflow run "${neutral(o.runId)}" was used to continue it, as run "${neutral(o.continuedAs)}".`,
detail: { runId: o.runId, decisionIds: [...o.decisionIds], decisionKey: decisionKeyOf(o.runId, o.decisionIds), continuedAs: o.continuedAs },
});
}
catch {
}
continue;
}
try {
input.deliver({
code: "workflow.parked_decision_unused",
message: `the approval decision for workflow run "${neutral(o.runId)}" was not used to continue it: ${workflowParkUnusedSentence(o)}.`,
detail: { runId: o.runId, decisionIds: [...o.decisionIds], decisionKey: decisionKeyOf(o.runId, o.decisionIds), reason: o.reason, ...holderDetailOf(o), ...(o.code !== undefined ? { code: o.code } : {}), ...(o.changed !== undefined ? { changed: o.changed } : {}), ...(o.inputs !== undefined ? { inputs: [...o.inputs] } : {}), ...(o.why !== undefined ? { why: o.why } : {}), ...(o.rowReason !== undefined ? { rowReason: o.rowReason } : {}), ...(o.terminal === true ? { terminal: true } : {}), ...(o.continuedAs !== undefined ? { continuedAs: o.continuedAs } : {}), spent: settlesDecision(o) },
});
}
catch {
}
}
return workflowContinuationFrameBody(outcomes, input.toolName, input.say);
};
}
function groupedByAnswer(answers) {
const groups = new Map();
for (const o of answers) {
if (o.kind !== "unused")
continue;
const { decisionIds, ...rest } = o;
const key = JSON.stringify(Object.entries(rest).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
const g = groups.get(key);
groups.set(key, g === undefined ? o : { ...g, decisionIds: [...g.decisionIds, ...decisionIds] });
}
return [...groups.values()];
}
function holderDetailOf(o) {
const holder = o.waiting !== undefined && o.waiting.length > 0 ? (o.waiting.length === 1 ? o.waiting[0].runId : o.waiting.map((l) => l.runId)) : o.holder;
return holder === undefined ? {} : { holder: typeof holder === "string" ? holder : [...holder] };
}
export function workflowContinuationFrameBody(outcomes, toolName, say) {
if (outcomes.length === 0)
return undefined;
const id = (s) => neutral(s, FRAME_RUN_ID_ECHO_MAX);
const tool = id(toolName);
const shown = outcomes.slice(0, FRAME_RUNS_MAX);
const lines = shown.map((o) => o.kind === "started"
? say(o.stepDenied === true ? "core/event.workflow-continuation.started-denied" : "core/event.workflow-continuation.started", { run: id(o.runId), as: id(o.continuedAs), tool })
: o.reason === "ask_unanswerable"
? say("core/event.workflow-continuation.ask", { run: id(o.runId), sentence: workflowParkUnusedSentence(o), tool })
: o.reason === "launch_unrecorded"
? say("core/event.workflow-continuation.model-continues", { run: id(o.runId), sentence: workflowParkUnusedSentence(o), tool })
: say(settledForGood(o) ? "core/event.workflow-continuation.settled" : "core/event.workflow-continuation.not-applied", { run: id(o.runId), sentence: workflowParkUnusedSentence(o) }));
if (outcomes.length > shown.length)
lines.push(say("core/event.workflow-continuation.more", { count: String(outcomes.length - shown.length) }));
return lines.join("\n");
}
const FRAME_RUNS_MAX = 3;
const FRAME_RUN_ID_ECHO_MAX = ECHO_MAX;