@sema-agent/core
Version:
Stateless, task-oriented AI agent core
156 lines (155 loc) • 7.5 kB
JavaScript
import { boundedRedactedSummary } from "./untrusted-egress.js";
import { delimitUntrusted } from "./untrusted-text.js";
import { thrownText } from "./thrown-value.js";
import { settledRunOf } from "./workflow-settled-run.js";
import { workflowMembersOf } from "../orchestration/workflow-types.js";
import { assertOwnership, canAccessWorkflowRun, formatWorkflowRun, sleepPollStep, activityStamp, stampActivity, occupantStamp, } from "./task-registry-shared.js";
export function registerWorkflowLane(core, input) {
assertOwnership(input, "registerWorkflow");
const id = input.runId;
if (core.handles.has(id))
throw new Error(`TaskRegistry: task id already registered: ${id}`);
const now = input.now ?? Date.now();
const originatingSessionId = input.originatingSessionId;
const handle = {
id,
type: "workflow",
status: "running",
...occupantStamp(input),
...(input.description !== undefined ? { description: input.description } : {}),
...(input.owner !== undefined ? { owner: input.owner } : {}),
...(input.scope !== undefined ? { scope: input.scope } : {}),
...(input.toolUseId !== undefined ? { toolUseId: input.toolUseId } : {}),
createdAt: now,
...activityStamp(now),
runId: id,
handle: input.handle,
...(input.store !== undefined ? { store: input.store } : {}),
...(originatingSessionId !== undefined ? { originatingSessionId, sessionScoped: true } : {}),
...(input.yieldIntent !== undefined ? { yieldIntent: input.yieldIntent } : {}),
...(input.parentTaskId !== undefined ? { parentTaskId: input.parentTaskId } : {}),
};
core.handles.set(id, handle);
const holdMembers = (run) => {
if (run !== undefined && Array.isArray(run.agents))
handle.members = workflowMembersOf(run);
};
void input.handle.done.then((res) => {
handle.status = "completed";
const run = res?.run;
const r = run?.resultFull ?? run?.result;
if (typeof r === "string")
handle.result = r;
if (run?.completionId !== undefined)
handle.completionId = run.completionId;
holdMembers(run);
stampActivity(handle);
core.pokeYieldDrains();
}, (err) => {
if (handle.status !== "cancelled")
handle.status = "failed";
const settledRun = settledRunOf(input.handle.done);
const settleId = settledRun?.completionId;
holdMembers(settledRun);
handle.error = boundedRedactedSummary(thrownText(err), 500);
if (settleId !== undefined)
handle.completionId = settleId;
stampActivity(handle);
core.pokeYieldDrains();
});
return id;
}
export async function workflowParkWaitsOf(run, runStore, seat, signal) {
if (runStore === undefined || seat === undefined || seat === "disabled" || signal?.aborted === true || run.status === "running" || !run.agents.some((a) => a.status === "parked"))
return undefined;
const { readWorkflowParkWaits } = await import("../orchestration/workflow-park-adoption.js");
const read = await readWorkflowParkWaits({ runStore, checkpointStore: seat }, run.id, run.scope);
return typeof read === "string" ? undefined : read;
}
export async function pollWorkflowLane(handle, access, deadline, signal, checkpointSeat) {
const store = handle.store;
if (store) {
for (;;) {
const run = await store.get(handle.runId);
if (!run || !canAccessWorkflowRun(run, access))
break;
if (run.status !== "running" || deadline === undefined || Date.now() >= deadline || signal?.aborted) {
const out = formatWorkflowRun(run, undefined, await workflowParkWaitsOf(run, store, checkpointSeat, signal));
if (run.status === "running" && deadline !== undefined && Date.now() >= deadline)
out.details.retrieval_status = "timeout";
return out;
}
await sleepPollStep(deadline, signal);
}
}
while (handle.status === "running" && deadline !== undefined && Date.now() < deadline && !signal?.aborted) {
await sleepPollStep(deadline, signal);
}
return {
content: JSON.stringify({
task_id: handle.id,
runId: handle.id,
type: "workflow",
status: handle.status,
...(handle.status === "completed" && handle.result !== undefined
? { result: delimitUntrusted("workflow result", handle.result) }
: {}),
...((handle.status === "failed" || handle.status === "killed") && handle.error !== undefined
? { error: delimitUntrusted("workflow error", handle.error) }
: {}),
note: handle.status === "running"
? "still running — poll again shortly."
: handle.status === "completed"
? handle.result !== undefined
? "completed — `result` above is the workflow's return value."
: "completed — its result was delivered on the completion notification."
: handle.status === "failed" && handle.error !== undefined
? "failed — see error."
: handle.status === "killed" && handle.error !== undefined
? "stopped — see error."
: "workflow reached a terminal state.",
}),
details: {
task_id: handle.id,
type: "workflow",
status: handle.status,
retrieval_status: handle.status === "running" && deadline !== undefined && Date.now() >= deadline ? "timeout" : "success",
...(handle.completionId !== undefined ? { completionId: handle.completionId } : {}),
},
};
}
export async function stopWorkflowLane(handle, source) {
const ended = handle.status !== "running";
if (!ended) {
handle.status = "cancelled";
stampActivity(handle);
}
if (source === undefined)
handle.handle.cancel("TaskStop requested");
else
handle.handle.cancel("TaskStop requested", { stoppedBy: source });
if (ended) {
return {
content: JSON.stringify({
task_id: handle.id,
runId: handle.id,
type: "workflow",
status: handle.status,
stopped: false,
note: `workflow already ${handle.status} — its row is unchanged; any of its agents still running were signalled to stop. Its completion notification carries its final state.`,
}),
details: { task_id: handle.id, type: "workflow", status: handle.status, retrieval_status: "success" },
};
}
return {
content: JSON.stringify({
task_id: handle.id,
runId: handle.id,
type: "workflow",
status: "cancelled",
stopped: true,
note: `workflow cancelled: what was running was stopped. Its record keeps the outcome the run settles with (a script that returns after its stopped agents' results come back is recorded as completed), and it can be continued with resumeFromRunId: "${handle.id}".`,
}),
details: { task_id: handle.id, type: "workflow", status: "cancelled", retrieval_status: "success" },
};
}