@sema-agent/core
Version:
Stateless, task-oriented AI agent core
1,402 lines • 93.3 kB
JavaScript
import { Type } from "typebox";
import { defineTool, errorResult } from "../core/tools.js";
import { adoptHostPromise } from "../core/host-promise.js";
import { governanceBaselineError, receiveGovernanceBaseline } from "./governance-baseline-validity.js";
import { isWorkflowRunId, resumedFromOf, WORKFLOW_RUN_ID_CHARACTERS } from "../core/workflow-run-store.js";
import { occupantStamp } from "../core/task-registry-shared.js";
import { workflowRecordPickupOf } from "./workflow-record-artifact.js";
import { admitsBackgroundLaunch, oweTerminalDelivery, resolveCompletionSink } from "../core/task-notification.js";
import { egressText, egressThrownText, boundedRedactedSummary, redactThenCut } from "../core/untrusted-egress.js";
import { foreignLine } from "../core/protocol-http-auth.js";
import { withDelegationProvenance } from "../core/tool-policy.js";
import { LAUNCH_RECEIPT_OWN_WORDS_CLAUSE, launchReceiptNoQuoteClause } from "../agents/launch-receipt-contract.js";
import { createHash, randomUUID } from "node:crypto";
import { startWorkflow, WORKFLOW_STORE_WAIT_BOUND_MS, takeWorkflowResumeClaims, releaseWorkflowResumeClaims } from "./workflow.js";
import { workflowStopOf } from "./workflow-stop.js";
import { assertJournalStoreGivesClaimsBack, journalKeepsLaunches } from "../core/workflow-journal-store.js";
import { boundedStoreRead, createWorkflowParkAdopter, otherWaitingLine, readWorkflowRunTree, readWorkflowRunTreeWithin, registerWorkflowParkAdopter, sameClaimKeys, workflowClaimKeysOf, workflowLineForkReason, workflowLineTailOf, workflowTreeOverBoundSentence } from "./workflow-park-adoption.js";
import { settledRunOf } from "../core/workflow-settled-run.js";
import { WORKFLOW_AGENT_PARKED_ERROR_CODE, WORKFLOW_STEP_ASKED_AGAIN, firstFailedAgentCodeOf, parkedAgentsOf, workflowMembersOf, workflowParkHolderOf, workflowRejectedWordOf } from "./workflow-types.js";
import { memberLedgerClause, memberRefusalsText } from "../core/member-outcome.js";
import { checkpointStoreOfSeat } from "../core/checkpoint-seat.js";
import { buildWorkflowPrimitives } from "./workflow-primitives.js";
import { fanOutPlaces } from "./workflow-fan-out-places.js";
import { stripSpawnTurnQuestionFace } from "../core/ask-question.js";
import { parentSpecSeatOfCtx } from "../core/parent-spec-seat.js";
import { CLAMP_SEATS, CLAMP_SET, assertClampRecord, clampRecordError, clampSourceOf, foldClampSources } from "../core/child-clamp-seats.js";
import { assertNoRetiredKeys } from "../core/retired-keys.js";
import { recordCarried, snapshotDefinitionLists } from "../agents/agent-definition.js";
const RETIRED_RUN_WORKFLOW_TOOL_DEPS_KEYS = {
principal: "the host run's principal rides `RunWorkflowToolDeps.parentSpecSeat.principal` (the parent SPEC seat the host's prepare mints), never a seat of its own",
oneShot: "the host run's one-shot fact rides `RunWorkflowToolDeps.parentSpecSeat.oneShot` (only `true` travels), never a seat of its own",
builtinWorkflows: "the engine ships no built-in named workflows — `{name}` resolves only the deployment's workflow catalog (this mount's `catalog` seat, built by `createWorkflowCatalog` from its layers); save any named workflow there, or pass `script` inline",
"scriptStore.resolveName": "saved workflows are the workflow catalog's (this mount's `catalog` seat: `createWorkflowCatalog` over directory layers — the deployment's saved `<name>.js` files are its deployment layer, named by `meta.name`; a `.args.json` sidecar is not read — its arguments become a preset under a name of its own, as the catalog's `args_sidecar_retired` notice spells for each file); the script store keeps per-run scripts only",
"scriptStore.list": "the saved-workflow listing is the workflow catalog's `list()` (this mount's `catalog` seat); the script store keeps per-run scripts only",
parentExcludeTools: "the host run's tool selector layers ride `RunWorkflowToolDeps.parentToolCeiling` (`ToolExecuteContext.toolSelector.layers`, the host's prepare-time selector) and bound every agent the workflow spawns as its ceiling — an exclusion list is no longer handed down by name",
parentPromptProfile: "the host run's prompt shape rides `RunWorkflowToolDeps.parentPromptLean` (`ToolExecuteContext.promptLean`: `false` for the long shape), never a profile word",
...Object.fromEntries(CLAMP_SEATS.filter((seat) => CLAMP_SET[seat].carrier === "clamp").map((seat) => [
`parent${seat.charAt(0).toUpperCase()}${seat.slice(1)}`,
`the host's tighten-only clamps ride ONE getter, \`RunWorkflowToolDeps.parentClamps\` (every clamp row, present keys) — return \`${seat}\` from it`,
])),
parentDurableApproval: "the host run's durable-approval opt-in object is `RunWorkflowToolDeps.parentDurableApprovalForChildren` (the same value, renamed after its context twin `durableApprovalForChildren`); the host's `durableApproval: false` rides `RunWorkflowToolDeps.parentClamps`",
parkedResume: "a model's Workflow call no longer carries the host's park decisions: hand them as `RunWorkflowToolDeps.parkedDecisions` (each with its `decisionId` and `outcome`) and the engine continues the decided run itself at the leg's opening",
};
import { parseWorkflowMeta, splitWorkflowMeta, workflowScriptReadsClockOrRandom } from "./workflow-meta.js";
import { workflowScriptRunInput } from "./workflow-script-runner.js";
import { mergeWorkflowArgs, normalizeStringArg } from "./workflow-script-store.js";
import { isWorkflowCatalog, WORKFLOW_CATALOG_ENTRY_DOORS, WORKFLOW_CATALOG_HELD_CODE } from "./workflow-catalog.js";
import { workflowCatalogRowsOf, workflowRequirementGaps, workflowRequirementsUnmetSentence, WORKFLOW_REQUIREMENTS_UNMET_CODE } from "./workflow-requirements.js";
import { workflowSizeGuidelineSection } from "./workflow-size-guideline.js";
import { mountRuleFace, toolFace } from "../core/tool-catalog-entries.js";
import { codedRefusal, readMember, thrownText } from "../core/thrown-value.js";
import { ANONYMOUS_SCOPE, callScopeOf } from "../core/isolation-scope.js";
import { readKeptLaunch } from "../core/workflow-journal-store.js";
import { isThinkingLevel } from "../brain/reasoning.js";
import { inlineUntrusted } from "../core/untrusted-text.js";
import { answerRecordClaimHolder, claimHeldOf, HOST_FOLD_INPUTS, hostFoldStampOf, notContinuedRefusalOf, storeErrorClassOf, storeFaultReport } from "./workflow-park-adoption.js";
import { createSafeNotifier, observeThenableRejection } from "../core/safe-notify.js";
export const RUN_WORKFLOW_TOOL_NAME = "Workflow";
const WORKFLOW_RUN_QUESTION = "Review dynamic workflow before running";
const CATALOG_HELD = "workflow.catalog_held";
const REQUIREMENTS_UNMET = "workflow.requirements_unmet";
export const WORKFLOW_NO_COMPLETION_CHANNEL = "a workflow run is not available here — no completion would come back from one on this mount (no notification channel and no deployment notifier is wired), and a workflow has no synchronous form. Do the work directly instead.";
function stripCodeFences(s) {
const t = s.trim();
const m = /^```[A-Za-z]*\r?\n([\s\S]*?)\r?\n?```$/.exec(t);
return m ? m[1] : s;
}
const DEFAULTS = {
maxScriptChars: 100_000,
maxAgents: 50,
totalTimeoutMs: 600_000,
maxResultChars: 100_000,
maxLogChars: 10_000,
};
function completionSummary(name, run) {
const cleanName = name?.replace(/[^\p{L}\p{N} _.:/-]/gu, "").replace(/\s+/g, " ").trim().slice(0, 60);
const ledger = workflowMembersOf(run);
const done = ledger.counts.completed ?? 0;
const clause = memberLedgerClause(ledger);
const secs = run.endedAt !== undefined ? Math.max(0, Math.round((run.endedAt - run.startedAt) / 1000)) : undefined;
const elapsed = secs === undefined ? "" : secs >= 60 ? ` in ${Math.floor(secs / 60)}m${secs % 60}s` : ` in ${secs}s`;
const resumeClause = run.resume === undefined
? ""
: run.resume.journalEntries === 0
? "; resume found NO journal entries — nothing replayed, the whole script re-ran live"
: `; resume: replayed ${run.resume.replayed} of ${run.resume.journalEntries} journaled results${resumeStepsClause(run)}`;
return withUnusedDecisions(`workflow${cleanName ? ` "${cleanName}"` : ""} completed${elapsed} — agents ${done}/${run.agents.length} done` +
`${clause !== "" ? ` (${clause})` : ""}${resumeClause}${continuedFromClause(run)}`, run);
}
function resumeStepsClause(run) {
const rows = run.agents.length;
if (rows === 0)
return "";
const taken = run.agents.filter((a) => a.replayed === true).length;
const anew = rows - taken;
if (anew === 0)
return `; no step was done anew: ${rows === 1 ? "the 1 step was" : `all ${rows} steps were`} taken from the earlier run's results`;
if (taken === 0)
return `; ${rows === 1 ? "the 1 step was" : `all ${rows} steps were`} done anew: none could be taken from the earlier run's results`;
return `; ${anew} of ${rows} steps ${anew === 1 ? "was" : "were"} done anew, ${taken} taken from the earlier run's results`;
}
function continuedFromClause(run) {
const resume = run.resume;
if (resume === undefined || typeof resume.fromRunId !== "string")
return "";
const driven = (run.decisions ?? []).filter((d) => d.result === "driven");
const label = (d) => {
const own = run.agents.find((a) => a.callKey === d.callKey)?.label;
return own === undefined ? "" : ` (agent "${boundedRedactedSummary(own, 80)}" in this run)`;
};
const applied = driven.map((d) => `decision "${boundedRedactedSummary(d.decisionId, 80)}" at step #${d.ordinal}${label(d)}`).join(", ");
return ` — asked to resume run "${boundedRedactedSummary(resume.fromRunId, 80)}"${driven.length === 0 ? "" : `, applying ${applied}`}`;
}
function rootOccupantSeat(rootId, ctx, d) {
if (rootId === undefined)
return {};
const byCtx = rootId === (ctx.rootSessionId ?? ctx.sessionId), byDeps = rootId === d.rootSessionId;
const occupant = (byCtx ? ctx.rootSessionIncarnation : undefined) ?? (byDeps ? d.rootSessionIncarnation?.() : undefined);
const scope = (byCtx ? ctx.rootSessionScope : undefined) ?? (byDeps ? d.rootSessionScope : undefined);
const principal = (byCtx ? ctx.rootPrincipal : undefined) ?? (byDeps ? d.rootPrincipal : undefined);
return { ...(occupant !== undefined ? { rootSessionIncarnation: occupant } : {}), ...(scope !== undefined ? { rootSessionScope: scope } : {}), ...(principal !== undefined ? { rootPrincipal: principal } : {}) };
}
const WORKFLOW_NOTIFY_ROWS_MAX = 5;
function workflowRecordTeach(run, recordLine) {
const refusalsOf = (a) => {
const text = memberRefusalsText(a.outcome?.refused);
return text !== "" ? ` [${boundedRedactedSummary(text, 240)}]` : "";
};
const notDone = run.agents.filter((a) => a.status !== "completed");
const rows = notDone
.slice(0, WORKFLOW_NOTIFY_ROWS_MAX)
.map((a) => `${a.label}: ${a.status}${a.errorMessage !== undefined ? ` — ${boundedRedactedSummary(a.errorMessage, 160)}` : ""}${refusalsOf(a)}`);
const rowsTeach = notDone.length === 0
? ""
: `Agents that did not complete (${notDone.length} of ${run.agents.length}${notDone.length > rows.length ? `, first ${rows.length} shown` : ""}): ${rows.join("; ")}. `;
const refusedDone = run.agents.filter((a) => a.status === "completed" && a.outcome?.refused !== undefined);
const refusedRows = refusedDone.slice(0, WORKFLOW_NOTIFY_ROWS_MAX).map((a) => `${a.label}:${refusalsOf(a)}`);
const refusedTeach = refusedDone.length === 0
? ""
: `Agents that completed with something refused (${refusedDone.length} of ${run.agents.length}${refusedDone.length > refusedRows.length ? `, first ${refusedRows.length} shown` : ""}): ${refusedRows.join("; ")}. `;
return `${rowsTeach}${refusedTeach}${recordLine}`;
}
function workflowUsageBlock(run) {
const agents = run.agents;
const parked = parkedAgentsOf(agents);
return {
...run.stats,
agent_count: agents.length,
agents_done: agents.filter((a) => a.status === "completed").length,
agents_error: agents.filter((a) => a.status === "failed").length,
...(parked.length > 0 ? { agents_parked: parked.length } : {}),
agents_empty_result: agents.filter((a) => a.status === "completed" && (a.output === undefined || a.output === "")).length,
agents_replayed: run.resume?.replayed ?? 0,
...(run.journalSkips !== undefined && run.journalSkips > 0 ? { journal_skipped: run.journalSkips } : {}),
...(run.resume !== undefined ? { resume_journal_entries: run.resume.journalEntries } : {}),
subagent_tokens: run.stats.tokens + run.stats.nested.tokens,
tool_uses: agents.reduce((n, a) => n + (a.toolCalls ?? 0), 0),
...(run.endedAt !== undefined ? { duration_ms: run.endedAt - run.startedAt } : {}),
};
}
function workflowDiagnostics(runId, journalRef, resumeMiss, record, held, stoppedBy) {
const journalTeach = journalRef === undefined
? ""
: journalRef.includes("://")
? ` Full journal (the step log resumeFromRunId replays): ${journalRef}.`
: ` Full journal (the step log resumeFromRunId replays): ${journalRef} (a deployment data path — it may be outside the paths Read can reach).`;
const resumeMissTeach = resumeMiss
? ` NOTE: this was a resume, but the prior run's journal was not usable under this scope — verify the runId and that this deployment wires a journalStore; the results above are from a full live re-run.`
: "";
return ((record ?? "") +
journalTeach +
resumeMissTeach +
(stoppedBy !== undefined
? ` ${workflowStoppedSentence(stoppedBy)}.`
: held !== undefined
? ` ${heldStepSentence(held)}.`
: ` To continue after editing the script: re-invoke with resumeFromRunId: "${runId}" (completed agents replay from the journal; only new/changed calls run).`)).trimStart();
}
const workflowStoppedSentence = (stoppedBy) => `The workflow was stopped (by ${JSON.stringify(boundedRedactedSummary(stoppedBy, 64))}): no run of it starts another step, so resuming it (resumeFromRunId) is refused — to run the work again, start the workflow again`;
const heldStepSentence = (held) => held.holder !== undefined
? `The parked step still belongs to run "${held.holder}": with a person's decision on its card, that run continues from the step; ` +
`if the card is no longer waiting (expired, removed, or decided elsewhere), a resume of "${held.holder}" records the step as failed and its script continues`
: `A parked step this run inherited is not this run's: continuing from this run would only fail again at that step, and which run holds it could not be read here — ` +
`a person's decision on its card continues the run that holds it`;
export async function heldStepOf(run, store) {
if (run?.resume === undefined || run.status === "running" || run.status === "completed" || run.errorCode === WORKFLOW_AGENT_PARKED_ERROR_CODE)
return undefined;
const inherited = run.parks?.find((p) => p.parkedBy !== undefined && p.parkedBy !== run.id);
if (inherited === undefined)
return undefined;
if (store === undefined)
return {};
const tree = await readWorkflowRunTree(store, inherited.parkedBy, run.scope);
if (typeof tree === "string")
return {};
const holder = workflowParkHolderOf(inherited.token, tree);
return holder.kind === "held" ? { holder: holder.runId } : {};
}
export function workflowFrameStatusOf(run) {
return run === undefined || run.status === "running" ? "failed" : run.status;
}
export function workflowNotifierStatusOf(status) {
return status === "completed" || status === "killed" ? status : "failed";
}
export function workflowNotifiedCodeOf(run) {
return run.errorCode === WORKFLOW_AGENT_PARKED_ERROR_CODE ? WORKFLOW_AGENT_PARKED_ERROR_CODE : firstFailedAgentCodeOf(run.agents);
}
const SCRIPT_ERROR_CODES = new Set([
"workflow.script_error",
"workflow.parked_call_changed",
"workflow.nesting",
"workflow.model_not_allowed",
"workflow.agent_schema",
"workflow.max_agents",
"workflow.result_too_large",
"workflow.budget_exceeded",
]);
function failureSummary(err, runId, run, held, stoppedBy) {
return withUnusedDecisions(failureSummaryOf(err, runId, run, held, stoppedBy), run);
}
const RESUME_REFUSAL_CODES = new Set(["workflow.parked_call_changed", "workflow.park_truth_unreadable", "workflow.park_binding_broken", "workflow.park_requires_run_store"]);
function withUnusedDecisions(summary, run) {
const unused = run?.decisions?.filter((d) => d.result === "not_reached") ?? [];
if (unused.length === 0)
return summary;
const code = unused[0].code;
const cause = code === undefined
? run?.status === "completed"
? "the script ended without reaching it"
: "the run ended before reaching it"
: RESUME_REFUSAL_CODES.has(code)
? `this continuation was refused (${code}) before it got there`
: code === WORKFLOW_AGENT_PARKED_ERROR_CODE
? "an earlier step stopped on an approval again and is waiting for a decision"
: `the run ended (${code}) before reaching it`;
const steps = unused.map((d) => `#${d.ordinal}`).join(", ");
const one = unused.length === 1;
const card = `${one ? "Its approval card is" : "Their approval cards are"} left as ${one ? "it was" : "they were"}, waiting for a decision`;
const wayOut = code === WORKFLOW_AGENT_PARKED_ERROR_CODE
? `, and the decision is not spent: decide the approval that earlier step is waiting for first, then hand ${one ? "this decision" : "these decisions"} over again — before that, handing ${one ? "it" : "them"} over does not continue the workflow`
: `, and the same decision can be handed over again to continue the workflow`;
return `${summary}. The approval decision carried for the parked step${one ? "" : "s"} (agent ${steps}) was not used: ${cause}. ${card}${wayOut}`;
}
function continuedBeforeSentence(run) {
const before = run?.resume?.continuedBefore;
if (before === undefined || typeof before.runId !== "string")
return "";
const ended = `${before.status}${before.errorCode !== undefined ? ` (${before.errorCode})` : ""}`;
return ` — run "${boundedRedactedSummary(run.resume.fromRunId, 80)}" had already been continued as run "${boundedRedactedSummary(before.runId, 80)}", which ended ${ended}; this run continued from that earlier point, so the steps after it that had not completed there ran again here`;
}
function failureSummaryOf(err, runId, run, held, stoppedBy) {
const codeWord = readMember(err, "code");
const thrownCode = typeof codeWord === "string" && codeWord !== WORKFLOW_AGENT_PARKED_ERROR_CODE ? codeWord : undefined;
const code = run !== undefined ? run.errorCode : thrownCode;
const refused = code === WORKFLOW_AGENT_PARKED_ERROR_CODE ? run?.decisions?.find((d) => d.result === "refused") : undefined;
if (refused !== undefined) {
const label = run?.agents.find((a) => a.callKey === refused.callKey)?.label ?? `#${refused.ordinal}`;
return `workflow parked again: the approval decision for "${boundedRedactedSummary(label, 80)}" was not applied${refused.code !== undefined ? ` (${refused.code})` : ""} — the run is parked at the same step and needs a new decision`;
}
if (code === WORKFLOW_AGENT_PARKED_ERROR_CODE) {
const parkedWords = readMember(err, "message");
const msg = typeof parkedWords === "string" ? egressText("same-principal", parkedWords) : "";
if (readMember(err, "gateKind") === "resource_limit" && readMember(err, "limitReason") === "preempt") {
return (`workflow yielded (${code}): ${msg.length > 200 ? `${msg.slice(0, 200)}…` : msg} — it did not fail and is not finished` +
(runId ? `; the diagnostics below name its record (the yielded agent's row reads status "parked")` : "") +
`; to continue it, re-invoke with resumeFromRunId${runId ? `: "${runId}"` : ""} and the same script — completed agents replay and the yielded call continues with no decision`);
}
return (`workflow parked (${code}): ${msg.length > 200 ? `${msg.slice(0, 200)}…` : msg}` +
(readMember(err, "askedAgain") === true ? ` — ${WORKFLOW_STEP_ASKED_AGAIN}` : "") +
` — it did not fail and is not finished` +
(runId ? `; the diagnostics below name its record (the parked agent's row reads status "parked")` : "") +
`; do not re-issue the same call — once a person decides the approval, the decision continues this run from the parked call; you do not resume it, and if it cannot be continued you are told then`);
}
const guide = stoppedBy !== undefined
? `; ${workflowStoppedSentence(stoppedBy)}`
: held !== undefined
? `; which agents failed is in the diagnostics below. ${heldStepSentence(held)}`
: runId
? `; which agents failed is in the diagnostics below; after fixing, re-invoke with resumeFromRunId: "${runId}" (completed agents replay from the journal)`
: "";
const scriptWords = code && SCRIPT_ERROR_CODES.has(code) ? readMember(err, "message") : undefined;
if (code && typeof scriptWords === "string") {
const msg = egressText("same-principal", scriptWords);
return `workflow failed (${code}): ${msg.length > 200 ? `${msg.slice(0, 200)}…` : msg}${guide}`;
}
return `${code && code.startsWith("workflow.") ? `workflow failed (${code})` : "workflow failed"}${guide}`;
}
export function workflowWhenToUseText(m) {
return (m.whenToUse || m.description) || undefined;
}
export function renderNamedWorkflowListing(entries) {
const offered = entries.filter((e) => WORKFLOW_CATALOG_ENTRY_DOORS[e.kind] === "workflow_tool");
if (offered.length === 0)
return undefined;
const lines = offered.map((e) => {
const w = workflowWhenToUseText(e);
return `- ${e.name} (${e.source}${e.kind === "preset" ? ", preset" : ""})${w ? `: ${w}` : ""}`;
});
return ("Saved workflows you can run by {name} (a preset runs its workflow with its own arguments merged UNDER your `args`; a top-level key you pass wins wholesale):\n" +
lines.join("\n"));
}
export function workflowCallSubject(args) {
if (args === null || typeof args !== "object" || Array.isArray(args))
return undefined;
const a = args;
const text = (v) => (typeof v === "string" && v.length > 0 ? v : undefined);
const scriptPath = text(a.scriptPath);
if (scriptPath !== undefined)
return { form: "scriptPath", scriptPath };
const name = text(a.name);
const script = text(a.script);
if (name !== undefined) {
const contentHash = text(a.contentHash);
return { form: "named", name, ...(contentHash !== undefined ? { contentHash } : {}), ...(script !== undefined ? { edited: script } : {}) };
}
return script !== undefined ? { form: "script", script } : undefined;
}
function prepareWorkflowArgs(args, hashOf) {
const subject = workflowCallSubject(args);
if (subject?.form !== "named")
return args;
if (subject.contentHash !== undefined)
return args;
const { script: _modelScript, contentHash: _unreadable, ...rest } = args;
const contentHash = hashOf(subject.name);
if (contentHash === undefined && _modelScript === undefined && _unreadable === undefined)
return args;
return { ...rest, ...(contentHash !== undefined ? { contentHash } : {}) };
}
async function readCatalogAtMount(catalog, mount) {
if (catalog === undefined)
return { roster: [], read: new Map(), shadowed: new Map() };
try {
const snapshot = await catalog.snapshot();
const listing = await snapshot.list();
const shadowed = new Map();
for (const n of listing.notices)
if (n.code === "shadowed" && n.name !== undefined && !(shadowed.get(n.name) ?? []).includes(n.source))
shadowed.set(n.name, [...(shadowed.get(n.name) ?? []), n.source]);
return { roster: workflowCatalogRowsOf(listing, mount).rows.filter((r) => r.gaps.length === 0), read: new Map(listing.entries.map((e) => [e.name, e])), shadowed, snapshot };
}
catch {
return { roster: [], read: new Map(), shadowed: new Map() };
}
}
const modelWordOf = (pick) => (typeof pick.modelRef === "string" ? pick.modelRef : pick.model.id);
function claimWithin(p, late) {
return new Promise((resolve, reject) => {
let settled = false;
const t = setTimeout(() => {
settled = true;
resolve("timeout");
}, WORKFLOW_STORE_WAIT_BOUND_MS);
p.then((v) => {
if (settled)
return late(v);
settled = true;
clearTimeout(t);
resolve(v);
}, (e) => {
if (settled)
return;
settled = true;
clearTimeout(t);
reject(e);
});
});
}
async function takeToolResumeClaim(journal, args, what, runId, reportStoreFault, carriesDecision = false) {
const who = what === "record" ? "record of a person's answer" : what;
let verdict;
try {
verdict = await claimWithin(takeWorkflowResumeClaims(journal, args.keys, args.newRunId, args.scope, carriesDecision), (late) => void (late.granted ? releaseWorkflowResumeClaims(journal, args.keys, args.newRunId, args.scope, late.fallback) : undefined));
}
catch (err) {
reportStoreFault?.(`the ${who}'s resume claim on workflow run ${JSON.stringify(runId)} could not be taken`, err);
return { refused: `the ${who}'s resume claim could not be taken (the journal store threw ${storeErrorClassOf(err)}) — not started` };
}
if (verdict === "timeout")
return { refused: `the ${who}'s resume claim was not answered within ${WORKFLOW_STORE_WAIT_BOUND_MS}ms — not started` };
if (verdict.granted)
return { granted: { args, fallback: verdict.fallback } };
const held = claimHeldOf(verdict);
if (held.claimLapseUnreadable === true) {
reportStoreFault?.(`the journal store's refusal of the ${who}'s resume claim on workflow run ${JSON.stringify(runId)} answered a remaining time that does not read`, new Error("remainingMs is not a whole number of milliseconds from 1 to 86400000"));
}
return { held };
}
function launchRefusalText(content) {
const text = typeof content === "string" ? content : Array.isArray(content) ? content.map((c) => (c !== null && typeof c === "object" && typeof c.text === "string" ? c.text : "")).join("") : "";
try {
const parsed = JSON.parse(text);
if (parsed !== null && typeof parsed === "object" && typeof parsed.error === "string")
return parsed.error;
}
catch {
}
return text !== "" ? text : "the launch started no run";
}
function canonicalFoldData(root) {
const seen = new WeakSet();
const walk = (v) => {
if (typeof v === "function" || typeof v === "symbol" || v === undefined)
return undefined;
if (v === null || typeof v !== "object")
return typeof v === "bigint" ? v.toString() : v;
if (seen.has(v))
return "[cycle]";
seen.add(v);
try {
if (v instanceof Set)
return [...v].map((e) => walk(e)).map((e) => JSON.stringify(e)).sort();
if (v instanceof Map)
return [...v.entries()].map(([k, e]) => [String(k), walk(e)]).sort((a, b) => String(a[0]).localeCompare(String(b[0])));
if (Array.isArray(v))
return v.map((e) => walk(e));
const o = v;
if (typeof o.name === "string" && typeof o.execute === "function")
return { tool: o.name };
const out = {};
for (const k of Object.keys(o).sort()) {
const c = walk(o[k]);
if (c !== undefined)
out[k] = c;
}
return out;
}
finally {
seen.delete(v);
}
};
return walk(root);
}
function workflowHostIdentityOf(fold) {
const pick = fold.model?.();
const model = pick === undefined ? undefined : modelWordOf(pick);
const thinking = fold.thinking?.();
return { ...(typeof model === "string" && model !== "" ? { model, ...(typeof pick?.modelRef !== "string" ? { modelPinned: true } : {}) } : {}), ...(typeof thinking === "string" ? { thinking } : {}) };
}
function workflowHostFoldDigest(fold) {
const pick = fold.model?.();
const { baseUrl, api, provider, ...modelRest } = (pick?.model ?? {});
const baseline = fold.governance.baseline;
const withoutTools = (slot) => (slot === undefined ? undefined : { ...slot, tools: undefined });
const inputs = {
tools: { base: baseline.base?.tools, worktreeBase: baseline.worktreeBase?.tools },
baseline: { ...baseline, base: withoutTools(baseline.base), worktreeBase: withoutTools(baseline.worktreeBase), workflowModelAllowlist: undefined },
allowed_models: { catalog: fold.governance.models, allowlist: baseline.workflowModelAllowlist },
agent_limits: fold.governance.caps,
permissions: { clamps: fold.clamps(), posture: fold.posture() },
model: pick === undefined ? undefined : { model: modelRest, modelRef: pick.modelRef },
endpoint: pick === undefined ? undefined : { baseUrl, api, provider },
thinking: fold.thinking?.(),
account: { principal: fold.seat?.principal, isolationScope: fold.seat?.isolationScope },
};
const digestOf = (v) => createHash("sha256").update(JSON.stringify(canonicalFoldData(v)) ?? "").digest("hex").slice(0, 32);
return hostFoldStampOf(Object.fromEntries(HOST_FOLD_INPUTS.map((k) => [k, digestOf(inputs[k])])));
}
export function createRunWorkflowTool(d) {
assertNoRetiredKeys(d, RETIRED_RUN_WORKFLOW_TOOL_DEPS_KEYS, "RunWorkflowToolDeps");
assertJournalStoreGivesClaimsBack(d.journalStore, "RunWorkflowToolDeps.journalStore");
if (d.parentClamps !== undefined && typeof d.parentClamps !== "function") {
throw clampRecordError(`RunWorkflowToolDeps.parentClamps must be a getter returning the host's clamp source, got ${typeof d.parentClamps}`);
}
if (d.catalog !== undefined && !isWorkflowCatalog(d.catalog)) {
throw codedRefusal("config.invalid_argument", "RunWorkflowToolDeps.catalog must be a workflow catalog (createWorkflowCatalog's: list, resolve, readByHash and snapshot) — a catalog without one of them cannot answer this mount's read");
}
return mountRunWorkflowTool(d);
}
async function mountRunWorkflowTool(d) {
if (d.scriptRunner.safeForUntrustedScripts !== true) {
throw new Error("createRunWorkflowTool: refusing to mount run_workflow on a runner that is not safeForUntrustedScripts (fail-closed) — mount it with a script runner that isolates the scripts it runs and declares safeForUntrustedScripts: true");
}
const faultSink = createSafeNotifier();
const sink = d.onStoreFault;
const reportStoreFault = sink === undefined ? undefined : (what, err) => void faultSink.notify(() => observeThenableRejection(sink(storeFaultReport(what, err)), faultSink, "onStoreFault"), "onStoreFault");
const agents = d.agents?.map(snapshotDefinitionLists);
const lim = d.limits ?? {};
const maxScriptChars = lim.maxScriptChars ?? DEFAULTS.maxScriptChars;
const childCaps = {
perAgentMaxWalltimeMs: lim.perAgentMaxWalltimeMs,
childMaxCostUsd: lim.childMaxCostUsd,
childMaxTokens: lim.childMaxTokens,
childMaxTurns: lim.childMaxTurns,
};
const receipt = receiveGovernanceBaseline(d.governanceBaseline);
if ("problem" in receipt)
throw governanceBaselineError(receipt.problem);
const received = receipt.baseline;
const FACE_LIST_FIELDS = ["allowTools", "excludeTools", "deferTools", "alwaysLoadTools"];
const dropNullFaces = (slot) => {
let out = slot;
for (const field of FACE_LIST_FIELDS) {
if (slot[field] !== null)
continue;
out = { ...out };
delete out[field];
}
return out;
};
const dropNullishOnAsk = (slot) => {
if (!("onAsk" in slot) || (slot.onAsk !== undefined && slot.onAsk !== null))
return slot;
const { onAsk: _absent, ...rest } = slot;
return rest;
};
const sanitizedBaseline = {
...received,
base: dropNullishOnAsk(dropNullFaces(received.base)),
...(received.worktreeBase === undefined ? {} : { worktreeBase: dropNullishOnAsk(dropNullFaces(received.worktreeBase)) }),
};
const unionFaceList = (own, parent) => own === undefined ? [...new Set(parent)] : [...new Set([...own, ...parent])];
const mountFace = {
...(d.parentDeferTools !== undefined ? { deferTools: [...d.parentDeferTools] } : {}),
...(d.parentAlwaysLoadTools !== undefined ? { alwaysLoadTools: [...d.parentAlwaysLoadTools] } : {}),
...(d.parentRestoreGatedTools !== undefined ? { restoreGatedTools: d.parentRestoreGatedTools === true ? true : [...d.parentRestoreGatedTools] } : {}),
...(d.parentPromptLean !== undefined ? { promptLean: d.parentPromptLean } : {}),
};
const withParentFace = (face, base, inherit) => ({
...base,
...(face.deferTools?.length
? { deferTools: unionFaceList(base.deferTools ?? inherit?.deferTools, face.deferTools) }
: {}),
...(face.alwaysLoadTools?.length
? { alwaysLoadTools: unionFaceList(base.alwaysLoadTools ?? inherit?.alwaysLoadTools, face.alwaysLoadTools) }
: {}),
...(() => {
const parent = face.restoreGatedTools;
if (parent !== true && !(Array.isArray(parent) && parent.length > 0))
return {};
const own = base.restoreGatedTools !== undefined ? base.restoreGatedTools : inherit?.restoreGatedTools;
return {
restoreGatedTools: parent === true || own === true
? true
: own === undefined
? parent
: Array.isArray(own)
? [...new Set([...own, ...parent])]
: own,
};
})(),
});
const withParentLean = (face, base) => face.promptLean !== undefined && base.promptLean === undefined ? { ...base, promptLean: face.promptLean } : base;
const governanceOf = (face) => ({
baseline: (face.deferTools?.length ?? 0) > 0 || (face.alwaysLoadTools?.length ?? 0) > 0 || face.promptLean !== undefined || face.restoreGatedTools !== undefined
? {
...sanitizedBaseline,
base: withParentLean(face, withParentFace(face, sanitizedBaseline.base)),
...(sanitizedBaseline.worktreeBase !== undefined
? { worktreeBase: withParentFace(face, sanitizedBaseline.worktreeBase, sanitizedBaseline.base) }
: {}),
}
: sanitizedBaseline,
models: d.models,
caps: childCaps,
onNotice: d.onNotice,
});
const governance = governanceOf(mountFace);
const requirementMount = { governanceBaseline: governance.baseline, ...(d.models !== undefined ? { models: d.models } : {}), ...(d.agents !== undefined ? { agents: d.agents } : {}), ...(d.builtinAgents !== undefined ? { builtinAgents: d.builtinAgents } : {}) };
const catalogAtMount = await readCatalogAtMount(d.catalog, requirementMount);
const namedWorkflowSection = renderNamedWorkflowListing(catalogAtMount.roster);
const mountHashOf = (name) => {
const e = catalogAtMount.read.get(name);
return e !== undefined && WORKFLOW_CATALOG_ENTRY_DOORS[e.kind] === "workflow_tool" ? e.contentHash : undefined;
};
const resolveNamedCall = async (subject) => {
const catalog = d.catalog;
if (catalog === undefined)
return { refusal: "named workflows require a deployment workflow catalog — none is wired; pass `script` inline" };
const elsewhere = catalogAtMount.read.get(subject.name);
if (elsewhere !== undefined && WORKFLOW_CATALOG_ENTRY_DOORS[elsewhere.kind] !== "workflow_tool") {
const name = inlineUntrusted(subject.name, 120), under = catalogAtMount.shadowed.get(subject.name) ?? [];
const shadows = under.length > 0 ? `; it shadows the ${under.join(" and ")} layer's entry of the same name, which this name does not run while the team holds it` : "";
return { refusal: `"${name}" is a team, not a workflow: it is not run by this tool — a team runs as a run of its own, one whose spec names it (team: "${name}")${shadows}. Nothing was started.` };
}
const read = async (from) => {
try {
return { resolved: await from.resolve(subject.name) };
}
catch (err) {
if (readMember(err, "code") === CATALOG_HELD)
return { refusal: { error: egressThrownText("same-principal", err).slice(0, 600), code: CATALOG_HELD } };
return { refusal: `failed to read the workflow catalog: ${egressThrownText("same-principal", err).slice(0, 300)}` };
}
};
const first = await read(catalogAtMount.snapshot ?? catalog);
if ("refusal" in first)
return first;
const unknown = () => {
const names = [...catalogAtMount.read.values()].filter((e) => WORKFLOW_CATALOG_ENTRY_DOORS[e.kind] === "workflow_tool").slice(0, 50).map((e) => inlineUntrusted(e.name, 120));
return { refusal: `Workflow "${inlineUntrusted(subject.name, 120)}" not found. Available: ${names.length > 0 ? names.join(", ") : "(none)"}` };
};
if (first.resolved === undefined)
return unknown();
if (subject.contentHash === undefined || first.resolved.contentHash === subject.contentHash)
return { resolved: first.resolved };
const now = catalogAtMount.snapshot !== undefined ? await read(catalog) : first;
if ("refusal" in now)
return now;
if (now.resolved !== undefined && now.resolved.contentHash === subject.contentHash)
return { resolved: now.resolved };
return {
refusal: `the saved workflow "${inlineUntrusted(subject.name, 120)}" does not hold the content this call was prepared with (contentHash ${inlineUntrusted(subject.contentHash, 80)}): ` +
"it was edited, replaced or removed since — or, where the deployment runs several replicas, their workflow directories differ. Not started; call it again by name to run what it holds now.",
};
};
const sizeGuidelineSection = workflowSizeGuidelineSection(d.sizeGuideline ?? lim.sizeGuideline);
const structuredError = (message) => errorResult(JSON.stringify(typeof message === "string" ? { error: message } : message));
const detachedSeatOf = (ctx) => {
const hostSeat = parentSpecSeatOfCtx(ctx) ?? d.parentSpecSeat;
return hostSeat !== undefined ? stripSpawnTurnQuestionFace(hostSeat) : undefined;
};
const hostFoldOf = (ctx, seat, hostOnAsk, inherited) => {
const g = inherited.face === mountFace ? governance : governanceOf(inherited.face);
return {
governance: hostOnAsk !== undefined && g.baseline.base.onAsk === undefined
? { ...g, baseline: { ...g.baseline, base: { ...g.baseline.base, onAsk: withDelegationProvenance(hostOnAsk, { parentToolCallId: ctx.toolCallId, depth: 1 }) } } }
: g,
clamps: () => {
const host = d.parentClamps?.();
assertClampRecord(host, "RunWorkflowToolDeps.parentClamps()", "clamp");
return clampSourceOf(foldClampSources(clampSourceOf(ctx, "clamp"), host), "clamp");
},
posture: () => ctx.interactionPosture ?? d.parentInteractionPosture,
model: inherited.model,
thinking: inherited.thinking,
seat,
face: inherited.face,
};
};
const mountInherited = { face: mountFace, model: d.parentModel, thinking: d.parentThinking };
const inheritedOf = (launch) => {
if (launch === undefined)
return mountInherited;
const host = launch.host;
const word = host?.model;
const recordedModel = () => {
if (word === undefined)
return undefined;
if (host?.modelPinned !== true && d.resolveModelWord !== undefined)
return d.resolveModelWord(word);
const current = d.parentModel?.();
if (current === undefined)
return undefined;
return host?.modelPinned === true ? (typeof current.modelRef !== "string" && current.model.id === word ? current : undefined) : current.modelRef === word ? current : undefined;
};
return {
face: launch.face ?? mountFace,
model: host === undefined ? d.parentModel : recordedModel,
thinking: host === undefined ? d.parentThinking : () => (isThinkingLevel(host.thinking) ? host.thinking : undefined),
};
};
const launchHostUnavailable = (launch, inherited) => {
const host = launch?.host;
if (host === undefined)
return undefined;
let pick;
try {
pick = inherited.model?.();
}
catch {
pick = undefined;
}
if (host.model !== undefined && pick === undefined) {
return host.modelPinned === true
? `the model it was launched with ("${inlineUntrusted(host.model, 64)}", handed to the session as a model object rather than a catalog name) is not the session's model now`
: `the model it was launched with ("${inlineUntrusted(host.model, 64)}") is not one this deployment serves any more`;
}
if (host.thinking !== undefined && !isThinkingLevel(host.thinking))
return `its recorded thinking level ("${foreignLine(host.thinking, 32)}") is not one`;
return undefined;
};
const adopterHostFold = (ctx, launch) => hostFoldOf(ctx, detachedSeatOf(ctx)?.spec, ctx.onAsk ?? d.parentOnAsk, inheritedOf(launch));
const heldForCall = new Map();
const resumeNotes = new Map();
const RESUME_NOTES_MAX = 64;
const noteResumedLine = async (args) => {
const named = args?.resumeFromRunId;
if (!isWorkflowRunId(named))
return;
resumeNotes.delete(named);
if (d.store === undefined)
return;
try {
const tree = await readWorkflowRunTreeWithin(d.store, named, callScopeOf(undefined, d, d.parentSpecSeat) ?? ANONYMOUS_SCOPE, boundedStoreRead(WORKFLOW_STORE_WAIT_BOUND_MS));
if (typeof tree === "string")
return;
const tail = workflowLineTailOf(tree, named);
const last = tail.kind === "tail" ? tree.records.find((r) => r.id === tail.runId) : undefined;
if (last === undefined || resumedFromOf(last) === undefined || last.status !== "completed" || !isWorkflowRunId(last.id))
return;
resumeNotes.set(named, `This workflow line already has a completed resume (run "${last.id}"); approving starts another run.`);
if (resumeNotes.size > RESUME_NOTES_MAX)
resumeNotes.delete(resumeNotes.keys().next().value);
}
catch {
}
};
const resumeNoteOf = (raw) => {
const named = raw?.resumeFromRunId;
const note = typeof named === "string" ? resumeNotes.get(named) : undefined;
return note === undefined ? {} : { resumeNote: note };
};
const carryKey = (runId, toolCallId) => `${runId}\u0000${toolCallId}`;
const takeHeldForCall = (runId, toolCallId) => {
if (runId === undefined || toolCallId === undefined)
return undefined;
const key = carryKey(runId, toolCallId);
const held = heldForCall.get(key);
heldForCall.delete(key);
return held;
};
const callPreviewOf = (raw) => {
const f = workflowCallSubject(raw);
const hasArgs = raw?.args !== undefined ? { hasArgs: true } : {};
if (f === undefined)
return undefined;
if (f.form === "named" && f.edited === undefined) {
const e = catalogAtMount.read.get(f.name);
const held = e !== undefined && (f.contentHash === undefined || e.contentHash === f.contentHash) ? e : undefined;
return {
form: "named",
workflow: f.name,
...(f.contentHash !== undefined ? { contentHash: f.contentHash } : {}),
...(held !== undefined ? { kind: held.kind, source: held.source, location: held.location, description: held.description, contentHash: held.contentHash } : {}),
...hasArgs,
};
}
if (f.form === "scriptPath")
return { form: "scriptPath", scriptPath: f.scriptPath, ...hasArgs };
const script = f.form === "named" ? f.edited : f.script;
const editedFrom = f.form === "named" ? { editedFrom: { name: f.name, ...(f.contentHash !== undefined ? { contentHash: f.contentHash } : {}) } } : {};
try {
const meta = parseWorkflowMeta(script);
return {
form: "script",
name: meta.name,
description: meta.description,
...(meta.phases !== undefined ? { phases: meta.phases.map((ph) => ({ title: ph.title, ...(ph.detail !== undefined ? { detail: ph.detail } : {}) })) } : {}),
scriptChars: script.length,
...editedFrom,
...hasArgs,
};
}
catch (e) {
return { form: "script", parseError: redactThenCut(thrownText(e), 300), scriptChars: script.length, ...editedFrom };
}
};
const tool = defineTool({
name: RUN_WORKFLOW_TOOL_NAME,
...toolFace("workflow"),
ruleFace: mountRuleFace("workflow"),
startsAgents: true,
permissionSeat: "passthrough",
approvalPreview: (raw) => {
const projection = callPreviewOf(raw);
return projection === undefined ? undefined : { ...projection, ...resumeNoteOf(raw) };
},
prepareArguments: (args) => prepareWorkflowArgs(args, mountHashOf),
validateInput: async (args) => {
await noteResumedLine(args);
const subject = workflowCallSubject(args);
if (subject?.form !== "named")
return undefined;
const r = await resolveNamedCall(subject);
if (!("refusal" in r))
return { ok: true };
return typeof r.refusal === "string" ? { ok: false, message: r.refusal } : { ok: false, message: r.refusal.error, code: r.refusal.code };
},
description: "Author and run your own deterministic JS WORKFLOW that spawns and coordinates sub-agents. Pass `script` " +
"(begins with `export const meta = {...}`, then an async body) and optional `args` (a JSON value). Returns a " +
"runId immediately; the workflow runs asynchronously and you are notified on completion. Use for a " +
"SUBSTANTIAL task that genuinely decomposes.\n" +
"ONLY call this tool when multi-agent orchestration was explicitly opted into: the user/operator asked " +
"for a workflow or fan-out in their own words, a skill or task directive requests it, or your standing " +
"instructions authorize self-orchestration. For any other task — even one that would clearly benefit " +
"from parallelism — do NOT call this tool: delegate individual sub-agents instead, or briefly describe " +
"what a workflow could do and ask first. A task merely LOOKING decomposable does not count.\n" +
"Pick the MINIMAL primitive that fits — do NOT reach for parallel by default:\n" +
"• agent(spec): ONE sub-agent (sequential when awaited). The DEFAULT — use it for any single coherent task. " +
"Both forms work: agent({ objective: '…' }, { label: '…', phase: '…' }) and agent('prompt string', opts?). " +
"ALWAYS pass a short kebab-case label naming what THIS agent does (e.g. { label: 'fix-lint-errors' }) — " +
"label/phase go in OPTS (the second argument), never inside spec, where they are ignored; unlabeled " +
"agents render as anonymous agent-N rows. " +
"Do NOT split a task into parallel agents unless its parts are GENUINELY INDEPENDENT.\n" +
"• parallel(thunks): run agents concurrently with a BARRIER (await ALL). ONLY for INDEPENDENT fan-out whose " +
"results you need together. If the parts share state, depend on each other, or just 'feel like multiple " +
"things', it is NOT parallel. A flat independent fan-out IS parallel — not workflow (and if those agents " +
"WRITE the same repo, it is isolation, below).\n" +
"• pipeline(items, ...stages): each item flows through the stages on its own chain (no barrier). Use for " +
"per-item STAGED processing of many items (e.g. for each file: lint → test → report).\n" +
"• agent(spec, { isolation: \"worktree\" }): run the agent in an ISOLATED git worktree. Use specifically when " +
"concurrent agents WRITE THE SAME FILES/REPO and must not clobber each other — even as a parallel fan-out " +
"(plain parallel would clobber); this takes precedence over plain parallel. A separate-working-copy need, " +
"NOT merely 'several agents'.\n" +
"• resumeFromRunId (this tool's arg): RESUME a prior/crashed run — replay its completed agents, run only new work " +
"(a run that could park must have finished — a crashed park-capable run is decided through the deployment's approval channel, not resumed; " +
"a run parked on an approval is continued by the person's decision, not by you).\n" +
"• scriptPath / name (this tool's args): when a script store is wired, every run persists its script and " +
"returns its scriptPath — to iterate, EDIT that file and re-invoke with {scriptPath} instead of resending " +
"the full script; {name} runs a saved workflow.\n" +
"• budget: SCALE the number/depth of agents to a token/cost CEILING — use whenever the task names a budget. " +
"Guard budget-driven loops on budget.total: with no budget set, budget.remaining() returns Infinity and a " +
"while-loop runs straight into the agent cap — add a hard iteration cap or pass a budget.\n" +
"\n" +
"Environment facts (read before writing the script):\n" +
"• Sub-agents may run in an isolated working directory — when a task concerns specific files/repos, put " +
"ABSOLUTE paths in the agent's objective; never assume it sees your cwd.\n" +
"• The script itself has NO host APIs: no require/import, no process/fs/fetch, no setTimeout (schedule " +
"time-based work outside the workflow). Only agent/parallel/pipeline/phase/log/budget/args exist.\n" +
"• Scripts must be DETERMINISTIC: `Date.now()`/`Math.random()`/argless `new Date()` throw (they would " +
"break resume) — pass timestamps in via `args`, stamp results after the workflow returns, and for " +
"randomness vary the agent prompt/label by index.\n" +
"• schema: if an agent's result is consumed by CODE or a downstream stage (a scorer, a file writer, the " +
"next pipeline stage, your own JSON.parse), pass opts.schema to FORCE structured output — prose transfer " +
"silently loses fields. Only results a human/LLM reads as narrative may omit schema. Standard JSON Schema " +
'applies, unions included — a nullable field is {"type":["string","null"]} (or anyOf). Cross-agent ' +
"assertions belong in the SCRIPT body: compare/validate agent results in plain JS between stages.\n" +
"• RETURN SHAPE (differs from Claude Code): agent() ALWAYS returns the full TaskResult — never the bare " +
"validated object. With schema, the validated object rides `r.structuredOutput` (read fields as " +
"`r.structuredOutput.bugs`, NOT `r.bugs`); `r.result` keeps the text form. A schema'd agent that " +
"completes in prose THROWS (fail-loud) instead of returning undefined.\n" +
"• Research/audit workflows: document and file claims are HYPOTHESES, not evidence — add a VERIFY " +
"stage whose agents EXECUTE (run the command, the test, the reproducer) and cross-check claims " +
"against actual output before the synthesis stage reports them as fact.\n" +
"• r.terminal.kind: agent() does NOT throw when the sub-agent FAILS — it RETURNS the result with r.terminal " +
"({ kind: 'completed' } on success; kind 'failed' (with r.terminal.code / r.terminal.message) / 'blocked' (r.terminal.reason) / 'paused' otherwise, " +
"with any failure text also in r.result). ALWAYS check r.terminal.kind before building on a result, and GATE later phases on it — e.g. " +
"`const impl = await agent({ objective: '…' }, { label: 'implement-fix' }); if (impl.terminal.kind !== 'completed') return { failed: 'implement', why: impl.result }` " +
"— running later phases on a failed prerequisite burns tokens on garbage.\n" +
"• phase (two forms, both fine): bare marker — phase('Scan'); groups every later agent() under 'Scan' " +
"until the next phase() call. Scoped — await phase('Fix', async () => { ...agents... }); groups just the " +
"body (equivalently, pass { phase: 'Fix' } in an agent's opts). Give each stage a phase so progress " +
"renders as stage groups; use the same titles you declared in meta.phases.\n" +
"• spec.modelName works only when the deployment configured a workflow model allowlist, and its legal " +
"values are the names on THAT allowlist which the deployment's model CATALOG KEYS also hold — a name " +
"off the allowlist, and a listed name the catalog lacks, are both refused rather than approximated. " +
"Generic tier words ('opus'/'sonnet'/'haiku'/'pro'/'flash'/'best') are not a separate namespace: on a " +
"deployment that configured tier bindings they become ordinary catalog keys, but only the ones its " +
"bindings actually resolve; on one that did not they are simply absent, unless its catalog happens to " +
"declare that literal name. Either way the allowlist is the gate, so a tier word is legal here only " +
"when this deployment allowlisted it, never as a shortcut around it. " +
"It also goes on the SPEC (the first argument), never in an agent()'s options object; `model` is accepted " +
"there as an alias for the same field. If unsure, omit it and the agent runs on the deployment's default " +
"role.\n" +
"\n" +
"Don't race. After launching, you know nothing about what the workflow found. Never fabricate or predict its " +
"results in any format — not as prose, summary, or structured output. END YOUR TURN and wait — the completion " +
"notification carries the result and each agent's outcome (the launch note says how it reaches you). If the " +
"user asks a follow-up before it lands, give status, not a guess." +
(namedWorkflowSection !== undefined ? `\n\n${namedWorkflowSection}` : "") +
sizeGuidelineSection,
parameters: Type.Object({
script: Type.Optional(Type.String({
description: "Self-contained workflow script. Must begin with `export const meta = { name, description, phases }` " +
"(pure literal, no computed values) followed by the script body using agent()/parallel()/pipeline()/phase(). " +
"`phases` is an ARRAY OF OBJECTS — e.g. `phases: [{ title: 'Scan', detail: 'grep the logs' }, { title: 'Fix' }]` " +
"(one entry per phase() call, titles matched exactly; `detail`/`model` optional; never bare strings).",
})),
name: Type.Optional(Type.String({
description: "Name of a saved workflow or preset (see the saved-workflow list in this tool's description). Runs " +
"that saved script — a `script` passed beside `name` is dropped, not run; a preset's own arguments merge under your `args`. " +
"Takes precedence over `script`.",
})),
scriptPath: Type.Optional(Type.String({
description: "Path to a workflow script file persisted by a prior invocation (each run's tool result carries its " +
"scriptPath when the deployment wires a script store). To iterate, edit that file and re-invoke with the " +
"same `scriptPath` instead of re-sending the full script. Takes precedence over `script` and `name`.",
})),
args: Type.Optional(Type.Unknown()),
resumeFromRunId: Type.Optional(Type.String({
description: "Resume a PRIOR run of the SAME script — replays the longest unchanged prefix of " +
"its agent results from the journal and runs only the first changed/new call + everything after live. " +
"Requires a journal-backed deployment; omit for a fresh run.",
})),
}),
execute: (rawArgs, ctx) => launch(rawArgs, ctx),
});
tool.permissionQuestion = WORKFLOW_RUN_QUESTION;
const journalLocatorOf = (runId, scope) => {
try {
return d.journalStore?.locator?.(runId, scope);
}
catch {
return undefined;
}
};
const launch = async (rawArgs, ctx, continuation) => {
const preparedArgs = continuation === undefined ? prepareWorkflowArgs(rawArgs, mountHashOf) : rawArgs;
const subject = workflowCallSubject(preparedArgs);
const scriptArgs = rawArgs.args;
const rawResume = rawArgs.resumeFromRunId;
if (continuation === undefined && rawResume !== undefined && !isWorkflowRunId(rawResume)) {
return structuredError({
error: `resumeFromRunId ${JSON.stringify(String(rawResume).slice(0, 80))} is not a workflow run id — a run id is ${WORKFLOW_RUN_ID_CHARACTERS}. To continue a run, pass the runId its Workflow call returned (the tool result and the completion notification name it); to start fresh, leave resumeFromRunId out. Not started.`,
code: "config.invalid_argument",
});
}
const namedResume = continuation !== undefined ? continuation.fromRunId : rawResume;
const held = continuation === undefined ? takeHeldForCall(namedResume, ctx.toolCallId) : undefined;
let resumeFromRunId = namedResume;
if (held !== undefined && "refusal" in held)
return structuredError(held.refusal);
const sourceTaskId = ctx.taskId ?? d.sourceTaskId;
const completionSink = resolveCompletionSink(ctx.onTaskNotification, d.taskNotification);
if (!admitsBackgroundLaunch(completionSink, d.notifier !== undefined))
return structuredError(WORKFLOW_NO_COMPLETION_CHANNEL);
const detachedSeat = detachedSeatOf(ctx);
const parentSpecSeat = detachedSeat?.spec;
const principal = parentSpecSeat?.principal;
const taskScope = callScopeOf(ctx, d, parentSpecSeat);
const runScope = taskScope ?? ANONYMOUS_SCOPE;
let script;
let editedFrom;
let registeredDefaultArgs;
let registeredStringArgKey;
let namedEntry;
if (continuation !== undefined) {
script = continuation.launch.script;
}
else if (subject?.form === "scriptPath") {
if (!d.scriptStore)
return structuredError("scriptPath requires a deployment workflow script store — none is wired; pass `script` inline");
if (d.scriptStore.scopePartitioned !== true) {
return structuredError("the wired workflow script store predates the scope-partition contract (scopePartitioned marker absent) — upgrade the store implementation");
}
try {
script = await d.scriptStore.load(subject.scriptPath, runScope);
}
catch (err) {
return structuredError(`failed to read workflow script at scriptPath: ${egressThrownText("same-principal", err).slice(0, 300)}`);
}
}
else if (subject?.form === "script") {
script = stripCodeFences(subject.script);
}
else if (subject?.form === "named") {
const named = await resolveNamedCall(subject);
if ("refusal" in named)
return structuredError(named.refusal);
const resolved = named.resolved;
if (subject.edited !== undefined && subject.edited !== resolved.script) {
script = subject.edited;
editedFrom = { name: resolved.entry.name, contentHash: resolved.contentHash };
}
else {
script = resolved.script;
namedEntry = resolved.entry;
}
if (resolved.defaultArgs !== undefined)
registeredDefaultArgs = resolved.defaultArgs;
if (resolved.stringArgKey !== undefined)
registeredStringArgKey = resolved.stringArgKey;
}
else {
return structuredError("Must provide script, name, or scriptPath");
}
const effectiveArgs = continuation !== undefined ? continuation.launch.effectiveArgs : mergeWorkflowArgs(normalizeStringArg(scriptArgs, registeredDefaultArgs, registeredStringArgKey), registeredDefaultArgs);
const callArgs = continuation !== undefined ? { ...continuation.launch.callArgs } : { ...(preparedArgs !== null && typeof preparedArgs === "object" ? preparedArgs : {}) };
if (continuation === undefined) {
delete callArgs["resumeFromRunId"];
delete callArgs["script"];
delete callArgs["args"];
}
if (script.length > maxScriptChars) {
return structuredError(`script too large: ${script.length} chars > max ${maxScriptChars}`);
}
let meta;
try {
meta = parseWorkflowMeta(script);
}
catch (err) {
return structuredError(thrownText(err));
}
if (continuation === undefined) {
const gaps = workflowRequirementGaps(namedEntry !== undefined ? namedEntry.requires : meta.requires, requirementMount);
if (gaps.length > 0) {
return structuredError({ error: boundedRedactedSummary(workflowRequirementsUnmetSentence(namedEntry?.name ?? meta.name, gaps), 2000), code: REQUIREMENTS_UNMET, missing: gaps.slice(0, 64) });
}
}
try {
const { body } = splitWorkflowMeta(script);
new Function(`return (async function(agent, parallel, pipeline, phase, log, budget, args) {\n${body}\n})`);
if (workflowScriptReadsClockOrRandom(body)) {
return structuredError("Workflow scripts must be deterministic: Date.now()/Math.random()/new Date() are unavailable (breaks resume). " +
"Stamp results after the workflow returns, or pass timestamps via args.");
}
}
catch (err) {
return structuredError(`workflow script failed to compile: ${thrownText(err)}`);
}
const hostOnAsk = ctx.onAsk ?? d.parentOnAsk;
const hostDurableApproval = ctx.durableApprovalForChildren ?? d.parentDurableApprovalForChildren;
const childParkSeat = ctx.checkpointStoreForChildren ?? d.parentCheckpointStore;
const parkStore = checkpointStoreOfSeat(childParkSeat);
const resumeScope = runScope;
const heldDecisionIds = held !== undefined && "decisions" in held ? held.decisions.map((x) => x.decisionId) : [];
const within = boundedStoreRead(WORKFLOW_STORE_WAIT_BOUND_MS);
const modelLineRefusal = async () => {
if (continuation !== undefined || namedResume === undefined || d.store === undefined)
return undefined;
const tree = await readWorkflowRunTreeWithin(d.store, namedResume, resumeScope, within);
if (tree === "unreadable")
return `the records of workflow run "${inlineUntrusted(namedResume, 64)}"'s workflow could not be read (the run store did not answer, or holds no record of that run under this scope) — not started; check the run id, or resume again once the run store answers`;
if (tree === "over_bound")
return workflowTreeOverBoundSentence(namedResume);
let target = namedResume;
if (heldDecisionIds.length === 0) {
const tail = workflowLineTailOf(tree, namedResume);
if (tail.kind === "fork")
return `workflow run "${inlineUntrusted(namedResume, 64)}" is not continued: ${workflowLineForkReason(tail.leaves.map((l) => inlineUntrusted(l, 64)))}. Nothing was started.`;
target = tail.runId;
}
const line = await otherWaitingLine(tree, parkStore, target, within);
if (line.kind === "unreadable")
return `an approval card of workflow run "${inlineUntrusted(target, 64)}"'s workflow could not be read — not started; resume again once the checkpoint store answers`;
if (line.kind === "waiting")
return notContinuedRefusalOf(namedResume, "waiting_elsewhere", { waiting: line.lines, decisionIds: heldDecisionIds });
return { keys: workflowClaimKeysOf(tree).keys, target };
};
const firstLine = await modelLineRefusal();
if (typeof firstLine === "string")
return structuredError(firstLine);
if (firstLine !== undefined)
resumeFromRunId = firstLine.target;
const claimKeys = continuation !== undefined ? continuation.claimKeys : firstLine?.keys;
let sourceLaunch = continuation?.launch;
if (continuation === undefined && resumeFromRunId !== undefined && journalKeepsLaunches(d.journalStore)) {
const scope = runScope;
const read = await readKeptLaunch(d.journalStore, resumeFromRunId, scope, WORKFLOW_STORE_WAIT_BOUND_MS);
if (read.kind === "failed" && read.cause !== undefined)
reportStoreFault?.(`the launch record of workflow run ${JSON.stringify(resumeFromRunId)} could not be read`, read.cause.err);
if (read.kind === "failed")
return structuredError(`the launch record of workflow run "${inlineUntrusted(resumeFromRunId, 64)}" could not be read (${(read.cause === undefined ? `the journal store did not answer within ${WORKFLOW_STORE_WAIT_BOUND_MS}ms` : storeErrorClassOf(read.cause.err)).slice(0, 160)}) — its agents could not be seated on what it was launched with; not started`);
if (read.kind === "defect")
return structuredError(notContinuedRefusalOf(resumeFromRunId, "launch_unreadable", { code: read.member }));
if (read.kind === "record")
sourceLaunch = read.record;
}
const inherited = inheritedOf(sourceLaunch);
const unseatable = launchHostUnavailable(sourceLaunch, inherited);
if (unseatable !== undefined)
return structuredError(`workflow run "${inlineUntrusted(resumeFromRunId ?? "", 64)}" cannot be continued: ${unseatable.slice(0, 300)} — its agents stay on what the run was launched with; start the workflow again`);
const hostFold = hostFoldOf(ctx, parentSpecSeat, hostOnAsk, inherited);
const scriptFn = (wfCtx) => {
const primitives = buildWorkflowPrimitives(wfCtx, hostFold.governance, d.onAgentSpawn, childParkSeat, hostFold.clamps, hostFold.posture);
const fanOut = fanOutPlaces(wfCtx, primitives.agent);
return d.scriptRunner.run(workflowScriptRunInput({ scriptSource: script, primitives, scriptArgs: effectiveArgs, signal: wfCtx.signal }, fanOut)).then((r) => r.result);
};
if (ctx.signal?.aborted) {
return structuredError("the launching tool call was aborted before the workflow could start — not started");
}
let handle;
const workflowTaskId = d.taskRegistry?.mintTaskId("workflow");
const launchRunId = workflowTaskId ?? (resumeFromRunId !== undefined ? randomUUID() : undefined);
const yieldIntent = d.taskRegistry !== undefined && d.store !== undefined && parkStore !== undefined ? new AbortController() : undefined;
const autoModeReview = ctx.autoModeReview ?? d.autoModeReview?.();
const agentStations = ctx.agentStations ?? d.agentStations?.();
const centerFromCtx = ctx.centerArtifactDigest !== undefined;
const parentCenterArtifactDigest = centerFromCtx ? ctx.centerArtifactDigest : d.parentCenterArtifactDigest?.();
const parentCenterSourceRevision = centerFromCtx ? ctx.centerSourceRevision : d.parentCenterSourceRevision?.();
let continuationClaim;
let continuationDecisions = continuation?.decisions;
const releaseContinuationClaim = () => {
if (continuationClaim !== undefined && d.journalStore !== undefined)
void releaseWorkflowResumeClaims(d.journalStore, continuationClaim.args.keys, continuationClaim.args.newRunId, continuationClaim.args.scope, continuationClaim.fallback);
};
if (resumeFromRunId !== undefined && claimKeys !== undefined && d.journalStore !== undefined && launchRunId !== undefined) {
const journal = d.journalStore;
const args = { keys: claimKeys, newRunId: launchRunId, scope: resumeScope };
const taken = await takeToolResumeClaim(journal, args, continuation !== undefined ? "continuation" : "resume", resumeFromRunId, reportStoreFault, continuation !== undefined || heldDecisionIds.length > 0);
if ("refused" in taken)
return structuredError(taken.refused);
if ("held" in taken) {
if (continuation === undefined)
return structuredError(notContinuedRefusalOf(namedResume ?? resumeFromRunId, taken.held.stoppedBy !== undefined ? "workflow_stopped" : "continuing_elsewhere", { ...taken.held, decisionIds: heldDecisionIds }));
continuation.onClaimHeld(taken.held);
return structuredError("another run already holds this run's resume claim — not started");
}
continuationClaim = taken.granted;
if (continuation === undefined) {
let again;
try {
again = await modelLineRefusal();
}
catch {
again = `the records of workflow run "${inlineUntrusted(resumeFromRunId, 64)}"'s workflow could not be read — not started`;
}
if (again !== undefined && typeof again !== "string" && (!sameClaimKeys(again.keys, claimKeys) || again.target !== resumeFromRunId)) {
again = `the records of workflow run "${inlineUntrusted(namedResume ?? "", 64)}"'s workflow changed while this call took its resume claim (a run of it was continued, removed or created again meanwhile) — not started; call again to continue from what they say now`;
}
if (typeof again === "string") {
releaseContinuationClaim();
return structuredError(again);
}
}
else {
let confirmed;
try {
confirmed = await continuation.confirm();
}
catch {
confirmed = false;
}
if (confirmed === false) {
releaseContinuationClaim();
continuation.onSuperseded();
return structuredError("the approval card changed while this continuation waited for its resume claim — not started");
}
continuationDecisions = confirmed;
}
if (ctx.signal?.aborted) {
releaseContinuationClaim();
return structuredError("the launching tool call was aborted before the workflow could start — not started");
}
}
try {
handle = startWorkflow(d.runner, scriptFn, {
store: d.store,
...(d.taskArtifacts !== undefined ? { taskArtifacts: d.taskArtifacts } : {}),
...(parkStore !== undefined ? { checkpointStore: parkStore } : {}),
...(agents !== undefined ? { agents } : {}),
...(d.builtinAgents !== undefined ? { builtinAgents: d.builtinAgents } : {}),
name: meta.name,
...(meta.description !== undefined ? { description: meta.description } : {}),
...(editedFrom !== undefined ? { editedFrom } : {}),
...(meta.phases !== undefined ? { phases: meta.phases } : {}),
...((record) => ({
...(journalKeepsLaunches(d.journalStore) ? { launch: record } : {}),
hostFoldDigest: () => workflowHostFoldDigest(hostFoldOf(ctx, parentSpecSeat, hostOnAsk, inheritedOf(record))),
}))({ script, ...(effectiveArgs !== undefined ? { effectiveArgs } : {}), callArgs, host: workflowHostIdentityOf(hostFold), face: hostFold.face }),
...(sourceTaskId !== undefined ? { sourceTaskId } : {}),
...(d.originatingSessionId !== undefined ? { originatingSessionId: d.originatingSessionId } : {}),
...((ctx.rootSessionId ?? d.rootSessionId ?? d.originatingSessionId) !== undefined ? { rootSessionId: ctx.rootSessionId ?? d.rootSessionId ?? d.originatingSessionId } : {}),
...rootOccupantSeat(ctx.rootSessionId ?? d.rootSessionId ?? d.originatingSessionId, ctx, d),
...((ctx.placementRoot ?? d.placementRoot) !== undefined ? { placementRoot: ctx.placementRoot ?? d.placementRoot } : {}),
...((ctx.placementTarget ?? d.placementTarget) !== undefined ? { placementTarget: ctx.placementTarget ?? d.placementTarget } : {}),
...((ctx.crossBoundaryTreeForChildren ?? d.crossBoundaryTree) !== undefined ? { crossBoundaryTree: ctx.crossBoundaryTreeForChildren ?? d.crossBoundaryTree } : {}),
...((ctx.delegationOwner ?? d.delegationOwner) !== undefined ? { delegationOwner: ctx.delegationOwner ?? d.delegationOwner } : {}),
...(launchRunId !== undefined ? { runId: launchRunId } : {}),
...(yieldIntent !== undefined ? { preemptSignal: yieldIntent.signal } : {}),
journalStore: d.journalStore,
...(resumeFromRunId !== undefined ? { resumeFromRunId } : {}),
...(d.onBackgroundChildEvent !== undefined ? { onBackgroundChildEvent: d.onBackgroundChildEvent } : {}),
scope: runScope,
budget: lim.budget,
maxAgents: lim.maxAgents ?? DEFAULTS.maxAgents,
totalTimeoutMs: lim.totalTimeoutMs ?? DEFAULTS.totalTimeoutMs,
maxResultChars: lim.maxResultChars ?? DEFAULTS.maxResultChars,
maxLogChars: lim.maxLogChars ?? DEFAULTS.maxLogChars,
...(d.parentCwd !== undefined ? { parentCwd: d.parentCwd } : {}),
...(d.callerRoot !== undefined ? { callerRoot: d.callerRoot } : {}),
...(ctx.spendSeat !== undefined ? { spendParent: { seat: ctx.spendSeat, link: "session" } } : {}),
parentToolCallId: ctx.toolCallId,
...(sourceTaskId !== undefined ? { parentTaskId: sourceTaskId } : {}),
...((ctx.interactionPosture ?? d.parentInteractionPosture) !== undefined ? { interactionPosture: (ctx.interactionPosture ?? d.parentInteractionPosture) } : {}),
...(() => {
if ("memoryCaptureOptedOut" in ctx) {
return {
parentMemoryCaptureState: () => {
const o = ctx.memoryCaptureOptedOut ?? false;
const i = ctx.memoryCaptureIndeterminate ?? false;
const build = (optedOut, indeterminate) => ({
optedOut: optedOut === true,
indeterminate: indeterminate === true,
...(ctx.memoryCaptureControlDir !== undefined ? { controlDir: ctx.memoryCaptureControlDir } : {}),
...(ctx.memoryCaptureAncestors !== undefined ? { ancestors: ctx.memoryCaptureAncestors } : {}),
});
const oAsync = adoptHostPromise(o), iAsync = oAsync === undefined ? adoptHostPromise(i) : undefined;
return oAsync !== undefined || iAsync !== undefined ? Promise.all([oAsync ?? o, iAsync ?? i]).then(([ov, iv]) => build(ov, iv)) : build(o, i);
},
};
}
return d.parentMemoryCaptureState !== undefined ? { parentMemoryCaptureState: d.parentMemoryCaptureState } : {};
})(),
...(hostFold.model !== undefined ? { defaultModel: hostFold.model } : {}),
...(hostFold.thinking !== undefined ? { defaultThinking: hostFold.thinking } : {}),
...(d.parentGetApiKeyAndHeaders !== undefined ? { defaultGetApiKeyAndHeaders: d.parentGetApiKeyAndHeaders } : {}),
...(parentSpecSeat !== undefined ? { parentSpecSeat } : {}),
...(detachedSeat?.internalsFlag.questionFaceStripped === true || ctx.questionFaceStripped === true || d.parentQuestionFaceStripped === true ? { questionFaceStripped: true } : {}),
...(hostDurableApproval === undefined || d.store === undefined || parkStore === undefined ? {} : journalKeepsLaunches(d.journalStore) ? { defaultDurableApproval: { ...hostDurableApproval } } : { durableApprovalWithheld: ["launch_records"] }),
...(() => {
const carried = continuation !== undefined ? continuationDecisions : held !== undefined && "decisions" in held ? held.decisions : undefined;
return carried !== undefined && carried.length > 0 ? { parkedResume: carried.map((e) => ({ ...e })) } : {};
})(),
...(d.holder !== undefined ? { holder: d.holder } : {}), ...((ctx.treeHolder ?? d.treeHolder) !== undefined ? { treeHolder: (ctx.treeHolder ?? d.treeHolder) } : {}),
...(parentCenterArtifactDigest !== undefined ? { parentCenterArtifactDigest } : {}),
...(parentCenterSourceRevision !== undefined ? { parentCenterSourceRevision } : {}),
...((ctx.forwardEvent ?? d.forwardEvent) !== undefined ? { onForwardEvent: (ctx.forwardEvent ?? d.forwardEvent) } : {}),
...((ctx.inheritedGateForChildren ?? d.inheritedGateForChildren) !== undefined
? { inheritedGate: (ctx.inheritedGateForChildren ?? d.inheritedGateForChildren)() }
: {}),
...(autoModeReview !== undefined ? { autoModeReview } : {}),
...(agentStations !== undefined ? { agentStations } : {}),
}, {
workflowDepth: d.workflowDepth,
launchingTool: tool,
...((ctx.toolSelector?.layers ?? d.parentToolCeiling) !== undefined ? { toolCeiling: (ctx.toolSelector?.layers ?? d.parentToolCeiling) } : {}),
...(continuationClaim !== undefined && continuationClaim.args.keys[0] !== undefined ? { resumeClaimKey: continuationClaim.args.keys[0] } : {}),
...(namedResume !== undefined && resumeFromRunId !== namedResume ? { resumeAsked: namedResume } : {}),
});
}
catch (err) {
releaseContinuationClaim();
return structuredError(thrownText(err));
}
if (continuationClaim !== undefined)
void handle.done.then(releaseContinuationClaim, releaseContinuationClaim);
void handle.done.catch(() => undefined);
const runId = handle.runId;
if (d.taskRegistry) {
const taskOwner = ctx.taskId ?? d.taskOwner ?? d.sourceTaskId;
d.taskRegistry.registerWorkflow({
runId,
handle,
store: d.store,
description: meta.name ?? meta.description,
toolUseId: ctx.toolCallId,
...(taskOwner !== undefined ? { owner: taskOwner } : {}),
...(sourceTaskId !== undefined && sourceTaskId !== (ctx.sessionId ?? d.originatingSessionId) ? { parentTaskId: sourceTaskId } : {}),
scope: runScope,
...(d.originatingSessionId !== undefined ? { originatingSessionId: d.originatingSessionId } : {}),
...occupantStamp(rootOccupantSeat(ctx.rootSessionId ?? d.rootSessionId ?? d.originatingSessionId, ctx, d)),
...(yieldIntent !== undefined ? { yieldIntent } : {}),
});
}
let persistedScriptPath;
if (continuation === undefined && d.scriptStore && d.scriptStore.scopePartitioned === true && (await handle.recordLanded?.()) !== false) {
const store = d.scriptStore;
persistedScriptPath = await new Promise((resolve) => {
const t = setTimeout(() => resolve(undefined), WORKFLOW_STORE_WAIT_BOUND_MS);
Promise.resolve()
.then(() => store.persist(runId, script, runScope))
.then((path) => (clearTimeout(t), resolve(path)), () => (clearTimeout(t), resolve(undefined)));
});
}
oweTerminalDelivery(completionSink, { task_id: runId, task_type: "workflow" });
{
let notified = false;
const fire = (notification) => {
if (notified)
return;
notified = true;
try {
completionSink?.(notification, { priority: "next" });
}
catch {
}
if (!d.notifier)
return;
void Promise.resolve()
.then(() => d.notifier.notify({
runId,
task_id: notification.task_id,
task_type: "workflow",
...(notification.toolUseId !== undefined ? { toolUseId: notification.toolUseId } : {}),
sourceTaskId,
...(d.originatingSessionId !== undefined ? { originatingSessionId: d.originatingSessionId } : {}),
principal,
scope: runScope,
status: workflowNotifierStatusOf(notification.status),
summary: egressText("human", notification.summary),
...(notification.result !== undefined ? { result: egressText("human", notification.result) } : {}),
...(notification.usage !== undefined ? { usage: notification.usage } : {}),
...(notification.diagnostics !== undefined ? { diagnostics: egressText("human", notification.diagnostics) } : {}),
...(notification.completionId !== undefined ? { completionId: notification.completionId } : {}),
...(notification.members !== undefined ? { members: notification.members } : {}),
...(notification.errorCode !== undefined ? { errorCode: notification.errorCode } : {}),
...(notification.stoppedBy !== undefined ? { stoppedBy: egressText("human", notification.stoppedBy) } : {}),
}))
.catch(() => { });
};
const recordOf = (run) => {
const pickup = workflowRecordPickupOf(run.recordArtifact);
if (pickup.ref !== undefined)
d.taskRegistry?.recordArtifactRef(runId, pickup.ref, run.completionId);
return workflowRecordTeach(run, pickup.line);
};
handle.done
.then(async (res) => fire({
task_id: runId,
task_type: "workflow",
...(ctx.toolCallId !== undefined ? { toolUseId: ctx.toolCallId } : {}),
status: workflowFrameStatusOf(res.run),
summary: completionSummary(meta.name, res.run) + continuedBeforeSentence(res.run),
result: boundedRedactedSummary(res.result, 4000),
usage: workflowUsageBlock(res.run),
diagnostics: workflowDiagnostics(runId, journalLocatorOf(runId, res.run.scope), res.run.resume?.journalEntries === 0, recordOf(res.run), undefined, workflowStopOf(handle)),
completionId: res.run.completionId,
members: workflowMembersOf(res.run),
}), async (err) => {
let parts = {
summary: failureSummary(undefined, runId),
diagnostics: workflowDiagnostics(runId, undefined, undefined, workflowRecordPickupOf(undefined).line),
};
try {
const failedRun = settledRunOf(handle.done);
const word = workflowRejectedWordOf(failedRun);
const runStopper = word === "killed" ? failedRun?.stoppedBy : undefined;
const record = failedRun !== undefined ? recordOf(failedRun) : workflowRecordPickupOf(undefined).line;
const held = await heldStepOf(failedRun, d.store);
const stoppedBy = workflowStopOf(handle);
const summary = failureSummary(err, runId, failedRun, held, stoppedBy) + continuedBeforeSentence(failedRun);
const settleId = failedRun?.completionId;
parts = {
status: word,
...(runStopper !== undefined ? { stoppedBy: runStopper } : {}),
summary,
diagnostics: workflowDiagnostics(runId, undefined, undefined, record, held, stoppedBy),
...(settleId !== undefined ? { completionId: settleId } : {}),
...(failedRun !== undefined ? { members: workflowMembersOf(failedRun) } : {}),
...((code) => (code !== undefined ? { errorCode: code } : {}))(failedRun === undefined ? undefined : workflowNotifiedCodeOf(failedRun)),
};
}
catch {
}
fire({
task_id: runId,
task_type: "workflow",
...(ctx.toolCallId !== undefined ? { toolUseId: ctx.toolCallId } : {}),
status: "failed",
...parts,
});
})
.catch(() => { });
}
return {
details: { type: "workflow-run", status: "backgrounded", workflowRunId: runId, task_id: runId },
content: JSON.stringify({
runId,
task_id: runId,
status: "started",
...(persistedScriptPath !== undefined ? { scriptPath: persistedScriptPath } : {}),
...(namedResume !== undefined && resumeFromRunId !== undefined && resumeFromRunId !== namedResume
? { resumedFrom: resumeFromRunId, resumeNote: `run "${inlineUntrusted(namedResume, 64)}" had already been continued, so this call continues the last run of its line, "${inlineUntrusted(resumeFromRunId, 64)}": its completed steps replay and only what it did not reach runs live. To continue this run later, resume from "${runId}".` }
: {}),
handling: `${launchReceiptNoQuoteClause(" (the ids above, and scriptPath when present)")} ${LAUNCH_RECEIPT_OWN_WORDS_CLAUSE}`,
note: (() => {
const journalRef = journalLocatorOf(runId, runScope);
const carries = ` The completion notification carries its result AND per-agent rows — read them${journalRef !== undefined ? ` (full journal: ${journalRef})` : ""} before assuming an empty or unexpected result.`;
if (d.notifier) {
return `The workflow runs asynchronously. You will be NOTIFIED when it completes (the notification carries the result). End your turn and wait — do not poll.${carries}`;
}
return `The workflow runs asynchronously. Its completion is delivered to this session (its next turn, if this one has ended) — end your turn and wait.${carries}`;
})(),
}),
};
};
registerWorkflowParkAdopter(tool, createWorkflowParkAdopter({
decisions: d.parkedDecisions ?? [],
scopeOf: (ctx) => callScopeOf(ctx, d, detachedSeatOf(ctx)?.spec) ?? ANONYMOUS_SCOPE,
store: d.store,
journalStore: d.journalStore,
parkStoreOf: (ctx) => checkpointStoreOfSeat(ctx.checkpointStoreForChildren ?? d.parentCheckpointStore),
hostFoldDigest: (ctx, launch) => workflowHostFoldDigest(adopterHostFold(ctx, launch)),
chainToHand: (ctx) => (ctx.inheritedGateForChildren ?? d.inheritedGateForChildren)?.().parentConstraints,
launch: async (decided, ctx, confirm) => {
const claim = {};
const continuation = { ...decided, onClaimHeld: (held) => void (claim.held = held), confirm, onSuperseded: () => void (claim.superseded = true) };
const out = await launch({}, ctx, continuation);
if (claim.held !== undefined)
return { claimHeld: claim.held };
if (claim.superseded === true)
return { superseded: true };
const details = typeof out === "object" && out !== null ? out : undefined;
if (details?.isError === true || typeof details?.details?.workflowRunId !== "string")
return { refused: launchRefusalText(details?.content) };
return { runId: details.details.workflowRunId };
},
underClaim: async (claimKeys, scope, body) => {
const journal = d.journalStore;
if (journal === undefined)
return { refused: "no journal store holds this workflow's resume claim" };
const args = { keys: claimKeys, newRunId: answerRecordClaimHolder(), scope };
const taken = await takeToolResumeClaim(journal, args, "record", claimKeys[0] ?? "", reportStoreFault);
if ("refused" in taken)
return { refused: taken.refused };
if ("held" in taken)
return { claimHeld: taken.held };
try {
return { value: await body() };
}
finally {
void releaseWorkflowResumeClaims(journal, args.keys, args.newRunId, args.scope, taken.granted.fallback);
}
},
waitBoundMs: WORKFLOW_STORE_WAIT_BOUND_MS,
...(reportStoreFault !== undefined ? { reportStoreFault } : {}),
toolName: RUN_WORKFLOW_TOOL_NAME,
holdForCall: (runId, toolCallId, held) => {
heldForCall.set(carryKey(runId, toolCallId), held);
},
}));
const handed = [governance.baseline.base, governance.baseline.worktreeBase];
return recordCarried(tool, {
mcp: handed.flatMap((slot) => slot?.mcp ?? []),
a2a: handed.flatMap((slot) => slot?.a2a ?? []),
agents: [...(agents ?? []), ...handed.flatMap((slot) => slot?.agents ?? [])],
tools: handed.flatMap((slot) => slot?.tools ?? []),
});
}