akm-cli
Version:
akm (Agent Knowledge Manager) — a portable, local-first capability library for AI agents. Discover, load, share, and improve reusable skills, scripts, workflows, and knowledge across any shell-capable coding agent, including Claude Code, OpenCode, and Cur
794 lines (793 loc) • 38.1 kB
JavaScript
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
/**
* Native executor — executes one frozen step subgraph (`WorkflowPlanStep.root`)
* locally: fan-out through the scheduler, structured output through
* `structuredLoop`, per-unit journaling through the serialized writer queue,
* and `workflow_unit_*` events. It never writes step rows; advancing the spine
* is `run-workflow.ts`'s job.
*
* - Data flow: instructions are the step's prose byte-exact; data reaches a
* unit as attached context.
* - An empty successful free-text output is journaled as absent, so a live
* run and a resume promote the same artifact.
* - A declared step `output` schema is validated before the step completes;
* a mismatch fails the step with `artifactSchemaFailure`, which the gate
* loop may retry.
* - Unit ids are content-derived (`<node>:<sha(item)>` / `<node>:solo`), so a
* resume reuses every completed row whatever the item order; retries and
* gate loops journal under `~r<n>` / `~l<n>`.
* - `onError: "fail"` fails on any unit failure, `"continue"` lets the gate
* decide; `retry: { max, on }` re-dispatches listed failure reasons.
* - Run `budget` ceilings are consumed per actual dispatch and abort the step
* when crossed, regardless of `on_error`.
*/
import { resolveRefToken } from "../../commands/env/env-binding.js";
import { isInstalledBundle } from "../../core/env-secret-ref.js";
import { NotFoundError } from "../../core/errors.js";
import { validateJsonSchemaSubset } from "../../core/json-schema.js";
import { substituteRefTokens } from "../../core/ref-token.js";
import { warn } from "../../core/warn.js";
import { mergeNotices } from "../../execution/notices.js";
import { isRefused, jsonParser, structuredLoop } from "../../llm/structured.js";
import { withWorkflowRunsConnection, withWorkflowRunsRepo, } from "../../storage/repositories/workflow-runs-repository.js";
import { WORKFLOW_UNIT_DIAGNOSTIC_CLIP } from "../resource-limits.js";
import { resolveRunBundleRoot } from "../runtime/workflow-asset-loader.js";
// The ONE child-workflow drive — publishes and drives a
// `child-workflow`-targeted unit; this module's dispatch seam is its only
// production caller.
import { driveChildWorkflowUnit } from "./child-workflow.js";
// The unit outcome scrub. Consumers import the leaf directly — this module is
// not a second front door onto the seam.
import { collectWorkflowDispatchSensitiveValues, redactUnitOutcome } from "./dispatch-redaction.js";
import { materializeFrozenWorkflowEnvironment } from "./environment.js";
// The exec (shell) unit runner — a leaf that owns argv spawning, containment,
// and the process-outcome → failure-reason mapping.
import { runExecUnit } from "./exec-unit.js";
import { secretShapedParamValues } from "./param-secrets.js";
import { scheduleUnits } from "./scheduler.js";
// Shared step semantics — the ONE implementation consumed by the engine
// (this module + run-workflow.ts) on both the fresh-execution and the resume
// path. This module dispatches; step-work.ts owns the pure decisions.
import { clip, computeStepWorkList, reduceEmptyStep, reduceStepOutcomes, stepOutputsFromEvidence, unitOutcomeFromRow, } from "./step-work.js";
import { dispatchWorkflowExecution, } from "./unit-dispatch.js";
import { enqueueUnitWrite } from "./unit-writer.js";
/**
* Per-step dispatch budget against the run's `budget` ceilings, seeded from
* the journal and consumed per actual dispatch (never by a reused row).
* Crossing a ceiling fires `onExceeded` once, aborting pending dispatches.
*/
class DispatchBudget {
used;
/** Run-total tokens: journal-seeded input + this step's dispatch usage. */
tokens;
/** Set (once) when a declared budget ceiling was hit; the step fails hard with it. */
budgetMessage;
maxUnits;
maxTokens;
onExceeded;
constructor(alreadyDispatched, opts) {
this.used = alreadyDispatched;
this.tokens = opts?.tokensUsed ?? 0;
this.maxUnits = opts?.budget?.maxUnits;
this.maxTokens = opts?.budget?.maxTokens;
this.onExceeded = opts?.onExceeded;
}
/** Consume one dispatch slot; false (and a sticky message) when a ceiling or the cap is hit. */
tryConsume() {
if (this.budgetMessage !== undefined)
return false;
if (this.maxUnits !== undefined && this.used >= this.maxUnits) {
this.exceed(`budget exceeded (max_units ceiling): ${this.used} unit(s) already dispatched for this run ` +
`against the workflow's declared budget.max_units of ${this.maxUnits} — refusing further dispatch.`);
return false;
}
if (this.maxTokens !== undefined && this.tokens >= this.maxTokens) {
this.exceed(`budget exceeded (max_tokens ceiling): ${this.tokens} token(s) already spent for this run ` +
`against the workflow's declared budget.max_tokens of ${this.maxTokens} — refusing further dispatch.`);
return false;
}
this.used++;
return true;
}
/** Record one dispatch's reported usage; crossing `maxTokens` trips the ceiling. */
addTokens(tokens) {
this.tokens += tokens;
if (this.budgetMessage === undefined && this.maxTokens !== undefined && this.tokens >= this.maxTokens) {
this.exceed(`budget exceeded (max_tokens ceiling): ${this.tokens} token(s) spent for this run, ` +
`reaching the workflow's declared budget.max_tokens of ${this.maxTokens} — aborting pending dispatches.`);
}
}
exceed(message) {
this.budgetMessage = message;
this.onExceeded?.();
}
}
function classifyUnitReuse(workUnit, completedRows) {
// Scan EVERY journaled attempt row of this unit (`<base>` / `<base>~r<N>`
// for ANY N), not just the attempts the CURRENT retry policy allows: a run
// re-invoked with a lowered retry.max must still find the `~rN` row a prior
// invocation completed beyond the new max, never re-dispatch finished work.
// The row's `input_hash` is informational — resume skips completed units.
const prior = completedRows?.get(workUnit.journalBaseId)?.[0];
return prior ? { kind: "reuse", row: prior } : { kind: "dispatch" };
}
function indexCompletedRows(rows) {
const index = new Map();
for (const row of rows) {
if (row.status !== "completed")
continue;
const base = row.unit_id.replace(/~r\d+$/, "");
const forBase = index.get(base);
if (forBase)
forBase.push(row);
else
index.set(base, [row]);
}
return index;
}
/**
* Execute one step plan natively. Never throws for unit-level failures. The
* whole step shares one state.db connection scope ({@link withWorkflowRunsConnection}).
*/
export function executeStepPlan(plan, ctx) {
return withWorkflowRunsConnection(() => executeStepPlanInConnection(plan, ctx));
}
/**
* Open the step's dispatch budget and the abort signal it trips: with a
* declared budget, dispatch runs under an AbortController chained onto
* `ctx.signal`. The caller must call `unchainSignal` when dispatch finishes.
*/
function openDispatchBudget(ctx, dispatched) {
const declaredBudget = ctx.budget && (ctx.budget.maxUnits !== undefined || ctx.budget.maxTokens !== undefined) ? ctx.budget : undefined;
let signal = ctx.signal;
let onExceeded;
let unchainSignal;
if (declaredBudget) {
const controller = new AbortController();
const upstream = ctx.signal;
if (upstream) {
if (upstream.aborted) {
controller.abort();
}
else {
const onUpstreamAbort = () => controller.abort();
upstream.addEventListener("abort", onUpstreamAbort, { once: true });
unchainSignal = () => upstream.removeEventListener("abort", onUpstreamAbort);
}
}
signal = controller.signal;
onExceeded = () => controller.abort();
}
const budget = new DispatchBudget(dispatched, {
tokensUsed: ctx.tokensUsed ?? 0,
...(declaredBudget ? { budget: declaredBudget } : {}),
...(onExceeded ? { onExceeded } : {}),
});
return { signal, budget, unchainSignal };
}
/** Resolve the live-at-dispatch prerequisites once, after durable-row reuse is known. */
async function prepareStepDispatchPrerequisites(input) {
const { plan, ctx, workUnits, willDispatch, dispatched } = input;
let env;
let sensitiveValues;
// The run's bundle is found again here, never frozen: a bundle update moves it to a new directory.
let cwd = ctx.bundleRootOverride;
if (willDispatch && cwd === undefined) {
try {
cwd = resolveRunBundleRoot(ctx.workflowRef);
}
catch (err) {
return {
ok: false,
result: failedStep(dispatched, `Step "${plan.stepId}" cannot run: ${message(err).replace(/\.$/, "")}.`),
};
}
}
const frozenEnvironment = workUnits[0]?.environment;
if (willDispatch && frozenEnvironment && frozenEnvironment.length > 0) {
try {
const materialized = materializeFrozenWorkflowEnvironment(frozenEnvironment);
env = materialized.values;
sensitiveValues = materialized.sensitiveValues;
}
catch (err) {
return {
ok: false,
result: failedStep(dispatched, `Step "${plan.stepId}" frozen environment preflight failed: ${message(err)}`),
};
}
}
return {
ok: true,
...(cwd !== undefined ? { cwd } : {}),
...(env ? { env } : {}),
...(sensitiveValues ? { sensitiveValues } : {}),
};
}
async function executeStepPlanInConnection(plan, ctx) {
const dispatched = ctx.unitsDispatched ?? 0;
// The work list is the shared pure decision (step-work.ts), so a resume
// recomputes the identical list and matches journaled rows.
const workList = computeStepWorkList(plan, {
runId: ctx.runId,
params: ctx.params,
stepOutputs: stepOutputsFromEvidence(ctx.evidence),
...(ctx.gateLoop !== undefined ? { gateLoop: ctx.gateLoop } : {}),
...(ctx.gateFeedback ? { gateFeedback: ctx.gateFeedback } : {}),
});
if (!workList.ok) {
return failedStep(dispatched, workList.error);
}
const { template, reducer, isFanOut, items, units: workUnits } = workList.list;
if (items.length === 0) {
// Empty fan-out: the promoted artifact is the degenerate empty value, honored
// against the step's declared output schema. `reduceEmptyStep` (step-work.ts)
// owns that decision so a zero-unit step promotes the identical artifact +
// schema verdict every time the spine reaches it.
return { ...reduceEmptyStep(plan, reducer), unitsDispatched: dispatched };
}
const dispatcher = ctx.dispatcher ?? defaultUnitDispatcher;
// Load journaled rows first: a completed unit is reused, never re-dispatched.
const completedRows = indexCompletedRows(await withWorkflowRunsRepo((repo) => repo.getUnitsForStep(ctx.runId, plan.stepId)));
// Env resolution runs only when some unit will dispatch, so a fully-journaled
// step resumes even if an env asset is gone. Every unit is classified once;
// the preflight and dispatch share it.
const reuseDecisions = workUnits.map((unit) => classifyUnitReuse(unit, completedRows));
const willDispatch = reuseDecisions.some((decision) => decision.kind === "dispatch");
const prerequisites = await prepareStepDispatchPrerequisites({
plan,
ctx,
workUnits,
willDispatch,
dispatched,
});
if (!prerequisites.ok)
return prerequisites.result;
const { cwd, env, sensitiveValues } = prerequisites;
// Budget ceilings + lifetime-cap accounting, and the budget-chained abort
// signal they trip. Extracted verbatim (behavior-identical) — see
// {@link openDispatchBudget}.
const { signal, budget, unchainSignal } = openDispatchBudget(ctx, dispatched);
let outcomes;
const frozenTargetConcurrency = template.frozenTarget.kind === "command" ? template.frozenTarget.concurrency : undefined;
try {
outcomes = await scheduleUnits(workUnits, (workUnit, index) => runUnit({
plan,
workUnit,
cwd,
env,
sensitiveValues,
ctx,
signal,
dispatcher,
reuse: reuseDecisions[index],
budget,
}), {
concurrency: workList.list.concurrency,
signal,
maxConcurrency: ctx.maxConcurrency,
...(frozenTargetConcurrency !== undefined ? { llmConcurrency: frozenTargetConcurrency } : {}),
});
}
finally {
unchainSignal?.();
}
// Capture live-only diagnostics BEFORE any hard reduction replaces the unit
// list with a failed-step envelope. Budget/cap and journal-write failures
// must not erase notices already observed from real dispatches; durable row
// reuses naturally contribute none.
const notices = mergeNotices(...outcomes.map((outcome) => outcome?.notices));
// A declared budget ceiling is a hard backstop: a step that hit one FAILS
// regardless of on_error policy (a capped run must never quietly pass its
// gate). The budget message names WHICH ceiling tripped.
if (budget.budgetMessage) {
return { ...failedStep(budget.used, budget.budgetMessage, notices), tokensUsed: budget.tokens };
}
const units = outcomes.map((outcome, index) => outcome ?? {
unitId: workUnits[index].unitId,
ok: false,
failureReason: "aborted",
error: "unit was not dispatched (aborted or scheduler failure)",
});
// A journal-write failure fails the step regardless of on_error: the unit ran
// but its result could not be persisted, so no artifact can be promoted.
const unjournaled = units.filter((u) => u.failureReason === "journal_write_failed");
if (unjournaled.length > 0) {
return {
...failedStep(budget.used, unjournaled.map((u) => u.error ?? `unit "${u.unitId}" result could not be journaled`).join(" "), notices),
tokensUsed: budget.tokens,
};
}
// Failure policy, reducer, and artifact schema check: the shared `reduceStepOutcomes`.
const reduced = reduceStepOutcomes(plan, reducer, isFanOut, template.onError, units);
return {
...reduced,
...(notices ? { notices } : {}),
unitsDispatched: budget.used,
tokensUsed: budget.tokens,
};
}
async function runUnit(input) {
const { plan, workUnit, cwd, env, sensitiveValues, ctx, dispatcher } = input;
const unitId = workUnit.unitId;
// Target validity is a WHOLE-LIST invariant, never a per-unit condition:
// computeStepWorkList rejects a step before building any unit when its sole
// frozen target is invalid, so every unit below carries one executable
// command/agent/SDK/direct-LLM target.
// The prompt (and therefore the input hash) was built once with the BASE
// unit id by computeStepWorkList: a retry re-dispatches the SAME input, the
// `~r<n>` suffix is journal bookkeeping only.
const { prompt, inputHash } = workUnit;
const request = {
runId: ctx.runId,
stepId: plan.stepId,
unitId,
nodeId: workUnit.nodeId,
prompt,
frozenTarget: workUnit.frozenTarget,
...(workUnit.execContext ? { execContext: workUnit.execContext } : {}),
...(cwd !== undefined ? { cwd } : {}),
timeoutMs: workUnit.timeoutMs,
...(workUnit.schema ? { schema: workUnit.schema } : {}),
...(env ? { env } : {}),
...(sensitiveValues ? { sensitiveValues } : {}),
...(input.signal ? { signal: input.signal } : {}),
// F-1: forwarded to exec-unit.ts's childEnv for a
// "shell" unit, and to dispatchWorkflowExecution's
// runExecution eventSource option (unit-dispatch.ts)
// for a "command" unit — both arms observe it.
...(ctx.eventSource !== undefined ? { eventSource: ctx.eventSource } : {}),
};
// One content-derived unit id is retained across every retry; the append-only
// attempt table supplies the 1-based attempt identity.
const retry = workUnit.retry;
const maxAttempts = 1 + Math.max(0, retry?.max ?? 0);
const journalBaseId = workUnit.journalBaseId;
const attemptIdFor = (_attempt) => journalBaseId;
// Durable-row reuse — literally the decision executeStepPlan's preflight gate
// counted, handed down rather than recomputed, so the gate cannot disagree
// with what happens here. A completed row IS the result: return it without
// touching rows, dispatching, or re-emitting events (a crash-resume must
// never double-issue work). Failed/running/missing rows dispatch live.
const reuse = input.reuse;
if (reuse.kind === "reuse") {
// Identity in the durable step evidence is the CONTENT-derived base id, not
// the `~r<n>` attempt row it was reused from — the work list only ever knows
// base ids, so evidence.units[].unitId stays stable across retries+resumes.
return reuseCompletedUnit(unitId, reuse.row, workUnit.schema !== undefined);
}
let outcome;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
if (input.signal?.aborted) {
return (outcome ?? {
unitId,
ok: false,
failureReason: "aborted",
error: "unit was not dispatched because the workflow invocation was interrupted",
});
}
const attemptId = attemptIdFor(attempt);
// Declared budget ceilings, consumed per ACTUAL dispatch (reuses above
// returned before reaching here). Refusal fails this unit without
// journaling a row — nothing was dispatched — and the sticky
// budgetMessage fails the step.
if (!input.budget.tryConsume()) {
return (outcome ?? {
unitId,
ok: false,
failureReason: "budget_exceeded",
error: input.budget.budgetMessage ?? "budget exceeded",
});
}
outcome = await dispatchJournaledAttempt({
plan,
workUnit,
ctx,
dispatcher,
request: { ...request, unitId: attemptId },
attemptId,
inputHash,
});
// Attempts use `~r<n>` journal suffixes while durable step evidence remains
// attached to the content-derived base identity.
outcome.unitId = unitId;
// Budget token accounting: every actual dispatch's reported
// usage counts against the run's max_tokens ceiling; crossing it aborts
// pending dispatches via the chained controller. Reuses never reach here
// (their tokens are already in the journal-seeded total).
if (outcome.tokens !== undefined)
input.budget.addTokens(outcome.tokens);
if (outcome.ok)
return outcome;
if (input.signal?.aborted)
return outcome;
const reason = outcome.failureReason;
if (!retry || reason === undefined || !retry.on.includes(reason))
return outcome;
}
// maxAttempts >= 1, so outcome is always set by the loop above.
return outcome;
}
/**
* What an attempt journals as the unit row's `result_json` (what `status
* --units` shows): a success's promoted value, or a failure's diagnostic plus
* any partial output. The caller passes an already-redacted outcome; clipped
* to {@link WORKFLOW_UNIT_DIAGNOSTIC_CLIP}.
*/
function journaledUnitResultJson(outcome) {
if (outcome.result !== undefined)
return JSON.stringify(outcome.result);
if (outcome.ok)
return outcome.text ? JSON.stringify(outcome.text) : null;
const parts = [outcome.error, outcome.text].filter((part) => Boolean(part?.trim()));
if (parts.length === 0)
return null;
return JSON.stringify(clip(parts.join("\n--- unit output ---\n"), WORKFLOW_UNIT_DIAGNOSTIC_CLIP));
}
async function reserveJournaledDispatch(input, startedAt) {
const { plan, workUnit, ctx, attemptId, inputHash } = input;
let durableAttempt;
await enqueueUnitWrite(async () => {
await withWorkflowRunsRepo((repo) => {
const target = workUnit.frozenTarget;
durableAttempt = repo.reserveUnitAttempt({
runId: ctx.runId,
unitId: attemptId,
stepId: plan.stepId,
nodeId: workUnit.nodeId,
parentUnitId: workUnit.isFanOut ? `${plan.stepId}.map` : null,
phase: "unit",
runner: workUnit.runner,
engine: target.kind === "command" ? target.request.target.name : null,
model: target.kind === "command" ? (target.request.model?.model ?? null) : null,
inputHash,
now: startedAt,
}).attempt;
});
});
if (!durableAttempt)
throw new Error(`unit "${attemptId}" did not reserve a durable attempt`);
return durableAttempt;
}
async function finishJournaledDispatch(input) {
const { attempt: source, durableAttempt, finishedAt, outcome } = input;
const { ctx, attemptId } = source;
await enqueueUnitWrite(() => withWorkflowRunsRepo((repo) => {
const finished = repo.finishUnitAttempt({
runId: ctx.runId,
unitId: attemptId,
attempt: durableAttempt.attempt,
dispatchId: durableAttempt.dispatch_id,
status: outcome.ok ? "completed" : "failed",
resultJson: journaledUnitResultJson(outcome),
tokens: outcome.tokens ?? null,
failureReason: outcome.failureReason ?? null,
sessionId: outcome.sessionId ?? null,
finishedAt,
});
if (!finished) {
if (repo.getUnitAttempts(ctx.runId, attemptId).length === 0) {
throw new Error(`finishUnitAttempt updated no row: no durable attempt "${attemptId}" exists for run "${ctx.runId}".`);
}
warn(`Workflow unit ${attemptId} (run ${ctx.runId}) ${outcome.ok ? "completed" : `failed (${outcome.failureReason ?? "error"})`}, ` +
"but its durable attempt was already finished — refusing a duplicate terminal write. " +
"This dispatch's result is not journaled.");
}
}));
}
/** Journal one dispatch attempt: insert row, events, dispatch, finish row. */
async function dispatchJournaledAttempt(input) {
const { workUnit, ctx, dispatcher, attemptId } = input;
let { request } = input;
const startedAt = new Date().toISOString();
let durableAttempt;
try {
durableAttempt = await reserveJournaledDispatch(input, startedAt);
}
catch (err) {
// A failed dispatch-row insert means NOTHING dispatched (the row is the
// dispatch's precondition) — fail the unit with the real cause instead of
// letting the throw escape into the scheduler, where a swallowed worker
// error is indistinguishable from "never claimed" and would be
// misreported as an aborted, never-dispatched unit.
return {
unitId: request.unitId,
ok: false,
failureReason: "dispatch_error",
error: `unit "${attemptId}" could not journal its dispatch row (nothing was dispatched): ${message(err)}`,
};
}
request = {
...request,
attempt: durableAttempt.attempt,
dispatchId: durableAttempt.dispatch_id,
};
// A child-workflow unit goes to the child executor instead of the
// dispatcher, after its attempt row is reserved, so it journals like any unit.
const resolvedSecrets = new Set();
const dispatched = request.frozenTarget.kind === "child-workflow"
? await driveChildWorkflowUnit({
request,
target: request.frozenTarget,
ctx,
childParams: workUnit.childParams ?? {},
inputHash: input.inputHash,
dispatcher,
})
: await dispatchUnit(request, dispatcher, resolvedSecrets);
// Credential and passthrough values are intentionally sampled only AFTER
// the default dispatcher has lowered the frozen request and
// materialized credentials at its terminal dispatch boundary. Custom test
// dispatchers receive the same post-dispatch journal scrub. Secret-shaped
// run params join the set: they must reach the prompt in clear (the unit
// needs them), but nothing about them needs to reach the journal. So do the
// secrets the dispatcher resolved itself (an exec unit's argv/cwd tokens).
const sensitiveValues = collectWorkflowDispatchSensitiveValues({
...(request.frozenTarget.kind === "command" ? { runner: request.frozenTarget.runner } : {}),
sensitiveValues: [...(request.sensitiveValues ?? []), ...resolvedSecrets, ...secretShapedParamValues(ctx.params)],
});
const outcome = redactUnitOutcome(dispatched, sensitiveValues);
const finishedAt = new Date().toISOString();
// A dispatched unit's outcome is NEVER silently discarded: the attempt is
// finished with the real result even when the run went non-active
// mid-flight — dropping it would leave the row `running` and make a later
// resume re-dispatch side-effecting work that already ran and already spent
// tokens. Persisting a unit result never advances the run; that is
// completeWorkflowStep's job.
let journalError;
try {
await finishJournaledDispatch({
attempt: input,
durableAttempt,
finishedAt,
outcome,
});
}
catch (err) {
journalError = err;
}
// A journal-write failure AFTER a successful dispatch is its own loud
// failure class: the unit's work ran (and may have succeeded), but its
// terminal state could not be recorded, so the row may be stuck `running`.
// It must never masquerade as "not dispatched" — the outcome names the unit
// and the real cause, and executeStepPlan fails the step hard on it
// (out-of-taxonomy reason, so retry.on can never re-dispatch the work).
if (journalError !== undefined) {
return {
unitId: request.unitId,
ok: false,
failureReason: "journal_write_failed",
error: `unit "${attemptId}" dispatched and ${outcome.ok ? "completed" : `failed (${outcome.failureReason ?? "error"})`}, ` +
`but its result could not be journaled: ${message(journalError)}`,
...(outcome.tokens !== undefined ? { tokens: outcome.tokens } : {}),
...(outcome.sessionId !== undefined ? { sessionId: outcome.sessionId } : {}),
...(outcome.notices ? { notices: outcome.notices } : {}),
};
}
return outcome;
}
/**
* Strict JSON parse for an `exec` unit's declared-schema output: stdout must be
* EXACTLY one JSON value (leading/trailing whitespace tolerated, nothing else).
*
* Deliberately NOT `parseEmbeddedJsonResponse` — that scan strips code fences
* and hunts for a JSON island inside prose, which is the right forgiving
* behavior for an LLM and the wrong one for a command, where it would silently
* promote a JSON fragment found in unrelated log noise as the typed artifact.
* Returning `undefined` makes the structured loop report `parse_error` (a real
* member of the retry taxonomy), so `retry.on: [parse_error]` still works.
*/
function parseExecJson(raw) {
const trimmed = raw.trim();
if (!trimmed)
return undefined;
try {
return JSON.parse(trimmed);
}
catch {
return undefined;
}
}
async function dispatchUnit(request, dispatcher,
/** Receives the secret values the dispatcher resolved, for the caller's journal scrub. */
resolvedSecrets) {
let tokens = 0;
let sawUsage = false;
let loweringNotices;
// Harness-native session id revealed by dispatch. Captured across
// structured-output retries (last one wins) so it survives into the
// UnitOutcome and gets journaled by finishUnitAttempt — the seam's
// contract ("stored opportunistically on the unit row for resume").
let sessionId;
const dispatchOnce = async (feedback) => {
const result = await dispatcher(request, feedback);
for (const value of result.sensitiveValues ?? [])
resolvedSecrets.add(value);
if (result.usage) {
sawUsage = true;
tokens +=
(result.usage.inputTokens ?? 0) + (result.usage.outputTokens ?? 0) + (result.usage.reasoningTokens ?? 0);
}
loweringNotices = mergeNotices(loweringNotices, result.notices);
// Capture before the ok-check: a failed attempt can still have configured
// a session (e.g. codex `session_configured` then a tool crash).
if (result.sessionId !== undefined)
sessionId = result.sessionId;
if (!result.ok) {
return {
ok: false,
failureReason: result.failureReason ?? "dispatch_error",
error: result.error ?? "unit dispatch failed",
text: result.text,
};
}
return { ok: true, raw: result.text };
};
const transportFailed = (failure) => ({
unitId: request.unitId,
ok: false,
failureReason: failure.failureReason,
error: failure.error,
text: failure.text,
...captured(),
});
const captured = () => ({
...(sawUsage ? { tokens } : {}),
...(sessionId !== undefined ? { sessionId } : {}),
...(loweringNotices ? { notices: loweringNotices } : {}),
});
try {
if (request.schema) {
const schema = request.schema;
const validate = (candidate) => {
const errors = validateJsonSchemaSubset(candidate, schema);
return errors.length === 0
? { ok: true, value: candidate }
: { ok: false, errors, reason: "validation_error" };
};
const structured = await structuredLoop({
dispatch: (correction) => dispatchOnce(correction?.text),
// A command is not re-promptable. Its stdout must be EXACTLY one JSON
// value: the default embedded-JSON scan (fences, think-blocks, "find the
// JSON inside the prose") is right for an LLM and wrong for a command,
// where it would pluck a JSON fragment out of unrelated log noise and
// promote it as the typed artifact. And it gets exactly ONE attempt:
// the loop's corrective retry re-dispatches with feedback, which
// for a command means running a SIDE-EFFECTING process a second time
// with byte-identical argv: it cannot produce different output, and it
// can produce a second deployment. Declared `retry:` still applies (the
// executor's own loop), because that is a policy the author opted into
// per failure reason.
...(request.frozenTarget.kind !== "command"
? {
attempts: 1,
parse: (raw) => {
const candidate = parseExecJson(raw);
return candidate === undefined
? { ok: false, errors: ["no JSON structure found in response"], reason: "parse_error" }
: validate(candidate);
},
}
: { parse: jsonParser(validate) }),
});
if (structured.ok) {
return { unitId: request.unitId, ok: true, result: structured.value, ...captured() };
}
if (!isRefused(structured))
return transportFailed(structured);
return {
unitId: request.unitId,
ok: false,
// NOTE: `validation_error` is deliberately outside PROGRAM_RETRY_REASONS,
// so no `retry.on:` can name it and a schema-violating unit is not
// re-run — see "fails with `validation_error` and is NOT re-run" in
// tests/integration/workflows/exec-unit.test.ts. It is intentionally not
// mapped onto `llm_invalid_json` (which the parser accepts but this path
// never emits).
failureReason: structured.reason,
error: structured.errors.join("; "),
text: structured.raw,
...captured(),
};
}
const dispatched = await dispatchOnce();
if (!dispatched.ok)
return transportFailed(dispatched);
const text = dispatched.raw;
// Normalize an EMPTY successful output to "no text". `finishUnitAttempt` journals
// result_json = NULL for a falsy text, so durable-reuse rehydrates NO text
// from the row (unitOutcomeFromRow). Preserving `text: ""` only in this live
// outcome would make the LIVE step artifact ("") diverge from the artifact a
// resume rebuilds from the row (null) — the exact byte-identical-graph
// violation the cardinal rule forbids. Treating empty as absent keeps live
// dispatch and engine resume identical.
return { unitId: request.unitId, ok: true, ...(text ? { text } : {}), ...captured() };
}
catch (err) {
return {
unitId: request.unitId,
ok: false,
failureReason: "dispatch_error",
error: message(err),
...captured(),
};
}
}
// ── Default dispatcher (production substrate) ───────────────────────────────
/**
* Dispatch a frozen connection or harness through the common prepare → lower → dispatch seam.
* No live profile/default/model map is consulted, and credentials remain
* symbolic until the final dispatch boundary.
*/
export const defaultUnitDispatcher = async (request, feedback) => {
const frozenTarget = request.frozenTarget;
if (frozenTarget.kind === "shell") {
if (request.cwd === undefined) {
throw new Error(`exec unit "${request.unitId}" was dispatched with no working directory.`);
}
const { exec, secretValues } = substituteExecRefs(request.unitId, frozenTarget.exec);
const outcome = await runExecUnit({
unitId: request.unitId,
exec,
baseDir: request.cwd,
...(request.env ? { env: request.env } : {}),
...(request.execContext ? { context: request.execContext } : {}),
...(request.schema ? { hasOutputSchema: true } : {}),
timeoutMs: request.timeoutMs,
...(request.signal ? { signal: request.signal } : {}),
...(request.eventSource !== undefined ? { eventSource: request.eventSource } : {}),
});
// A secret substituted into argv joins the redaction set, like one bound through an env asset: the
// executor scrubs after the structured parse, so a quoted or numeric secret is not missed or corrupted.
return { ...outcome, sensitiveValues: secretValues };
}
return dispatchWorkflowExecution(request, feedback);
};
/**
* Replace the `${ref}` tokens in an exec unit's argv and `cwd` (prompts are not substituted): a
* `secrets/` ref with the secret's value, any other asset ref with its absolute path. A ref no
* bundle owns fails the unit before anything is spawned.
*/
function substituteExecRefs(unitId, exec) {
const slots = Object.fromEntries(exec.command.entries());
if (exec.cwd !== undefined)
slots.cwd = exec.cwd;
const { values, missing, secretValues } = substituteRefTokens(slots, resolveRefToken, isInstalledBundle);
if (missing.length > 0) {
throw new NotFoundError(`exec unit "${unitId}" references asset(s) that no bundle owns: ${missing.join(", ")}. Nothing was run.`, "FILE_NOT_FOUND", "Write each `${ref}` as a full akm ref that exists, e.g. `${team//scripts/run.sh}`.");
}
return {
exec: {
...exec,
command: exec.command.map((_, index) => values[index]),
...(exec.cwd !== undefined ? { cwd: values.cwd } : {}),
},
secretValues,
};
}
// ── Small helpers ────────────────────────────────────────────────────────────
/**
* Rehydrate a journaled completed unit row into a UnitOutcome (durable-row
* reuse). Delegates to the shared {@link unitOutcomeFromRow} — the reuse path
* only reaches here for completed rows (the caller guards `status ===
* "completed"`), so a reused unit contributes exactly what its original
* dispatch did.
*/
function reuseCompletedUnit(unitId, row, hasSchema) {
return unitOutcomeFromRow(unitId, row, hasSchema);
}
function failedStep(dispatched, reason, notices) {
return {
ok: false,
units: [],
...(notices ? { notices } : {}),
evidence: { error: reason },
summary: reason,
unitsDispatched: dispatched,
};
}
function message(err) {
return err instanceof Error ? err.message : String(err);
}