@sema-agent/core
Version:
Stateless, task-oriented AI agent core
67 lines (66 loc) • 2.7 kB
JavaScript
import { isTerminalWorkflowStatus, resumedFromOf, workflowRunCreationIdOf } from "../core/workflow-run-store.js";
import { boundedStoreRead, isContinuationOf, readWorkflowRunIn, WORKFLOW_TREE_RUNS_MAX } from "./workflow-park-adoption.js";
import { WORKFLOW_STORE_WAIT_BOUND_MS } from "./workflow-types.js";
export function workflowRunTreeIdOf(run) {
const v = run.treeId;
return typeof v === "string" ? v : undefined;
}
export function* treeIdWalk(run) {
let cur = run;
const seen = new Set([run.id]);
for (;;) {
if (cur.resumeAdmissionIncomplete === true)
return "no_tree";
const own = workflowRunTreeIdOf(cur);
if (own !== undefined)
return { treeId: own };
const up = resumedFromOf(cur);
if (up === undefined)
return { treeId: cur.id };
const source = yield up;
if (source === "unreadable")
return "unreadable";
if (source === null || !isContinuationOf(source, cur))
return "no_tree";
if (seen.has(up))
return "unreadable";
if (seen.size >= WORKFLOW_TREE_RUNS_MAX)
return "over_bound";
seen.add(up);
cur = source;
}
}
export async function treeIdOf(store, run, scope, within) {
return driveAsync(treeIdWalk(run), (id) => readWorkflowRunIn(store, id, scope, within));
}
async function driveAsync(walk, read) {
let step = walk.next();
while (step.done !== true)
step = walk.next(await read(step.value));
return step.value;
}
export function* treeIdStampWalk(run) {
if (workflowRunTreeIdOf(run) !== undefined)
return { kind: "skip", why: "stamped" };
if (!isTerminalWorkflowStatus(run.status))
return { kind: "skip", why: "running" };
if (run.resumeAdmissionIncomplete === true)
return { kind: "skip", why: "admission_incomplete" };
const tree = yield* treeIdWalk(run);
if (tree === "no_tree")
return { kind: "skip", why: "no_tree" };
if (typeof tree === "string")
return tree;
return { kind: "stamp", treeId: tree.treeId, expect: { rev: typeof run.rev === "number" ? run.rev : 0, creationId: workflowRunCreationIdOf(run) }, cause: "tree_id_stamp" };
}
export function workflowTreeIdStampOf(store, run, scope) {
const within = boundedStoreRead(WORKFLOW_STORE_WAIT_BOUND_MS);
return driveAsync(treeIdStampWalk(run), (id) => readWorkflowRunIn(store, id, scope, within));
}
export function workflowTreeIdStampInHand(run, read) {
const walk = treeIdStampWalk(run);
let step = walk.next();
while (step.done !== true)
step = walk.next(read(step.value));
return step.value;
}