@agentproto/workflow-runtime 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -2
- package/dist/index.d.ts +6 -3
- package/dist/index.mjs +106 -14
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -93,6 +93,12 @@ final message against it, **re-prompting on mismatch** up to `maxRetries`
|
|
|
93
93
|
(default 2). The step's bound output is `{ sessionId, output }` where `output`
|
|
94
94
|
is the parsed, schema-valid value.
|
|
95
95
|
|
|
96
|
+
Without `outputSchema`, an agent step whose host implements `readFinalMessage`
|
|
97
|
+
binds `{ sessionId, text }`, where `text` is the session's final assistant
|
|
98
|
+
message. The runtime uses that `text` to thread prior agent-step output into
|
|
99
|
+
later agent prompts automatically, so multi-step workflows can share context
|
|
100
|
+
without manual selector plumbing.
|
|
101
|
+
|
|
96
102
|
```ts
|
|
97
103
|
const Verdict = z.object({
|
|
98
104
|
verdict: z.enum(["real", "false-positive"]),
|
|
@@ -218,6 +224,21 @@ await runWorkflow({ workflow: wf, cache, cacheKey: "nightly-review" }) // run 2:
|
|
|
218
224
|
Both `cache` and `cacheKey` must be set for any caching to happen. Supply your
|
|
219
225
|
own `StepCache` (`{ get, set }`) for an in-memory or custom-backed journal.
|
|
220
226
|
|
|
227
|
+
### Step lifecycle callbacks
|
|
228
|
+
|
|
229
|
+
Pass `onStepStart` and `onStepComplete` to `runWorkflow` to observe progress in
|
|
230
|
+
real time. The callbacks fire for every step kind; for `agent` steps, start fires
|
|
231
|
+
before spawn and complete fires after the turn (and any output-schema retry loop)
|
|
232
|
+
finishes.
|
|
233
|
+
|
|
234
|
+
```ts
|
|
235
|
+
await runWorkflow({
|
|
236
|
+
workflow: wf,
|
|
237
|
+
onStepStart: (stepId) => console.log("starting", stepId),
|
|
238
|
+
onStepComplete: (stepId, output) => console.log("done", stepId, output),
|
|
239
|
+
})
|
|
240
|
+
```
|
|
241
|
+
|
|
221
242
|
## AgentSessionHost — the host seam
|
|
222
243
|
|
|
223
244
|
The runtime has **no** knowledge of concrete session registries or event buses.
|
|
@@ -225,11 +246,22 @@ The runtime has **no** knowledge of concrete session registries or event buses.
|
|
|
225
246
|
|
|
226
247
|
```ts
|
|
227
248
|
interface AgentSessionHost {
|
|
228
|
-
spawn(
|
|
249
|
+
spawn(
|
|
250
|
+
adapter: string,
|
|
251
|
+
opts: {
|
|
252
|
+
cwd?
|
|
253
|
+
workspaceSlug?
|
|
254
|
+
stepId?
|
|
255
|
+
/** AIP-36 sandbox ref (provider slug or inline spec). */
|
|
256
|
+
sandbox?
|
|
257
|
+
/** Adapter option id → value, e.g. for an app-scoped agent resolution. */
|
|
258
|
+
options?: Record<string, boolean | number | string>
|
|
259
|
+
},
|
|
260
|
+
): Promise<string>
|
|
229
261
|
sendPromptAndWait(sessionId: string, prompt: string): Promise<void>
|
|
230
262
|
resolveByLabel(stepId: string): string | undefined // for sessionRef reuse
|
|
231
263
|
onAwaitingInput?(sessionId, policy): Promise<void>
|
|
232
|
-
readFinalMessage?(sessionId): Promise<string> // required for outputSchema
|
|
264
|
+
readFinalMessage?(sessionId): Promise<string> // required for outputSchema; also supplies `text` output
|
|
233
265
|
readCostUsd?(sessionId): Promise<number> // required for maxTotalCostUsd
|
|
234
266
|
}
|
|
235
267
|
```
|
package/dist/index.d.ts
CHANGED
|
@@ -383,9 +383,12 @@ declare function runWorkflow(args: RunWorkflowArgs): Promise<WorkflowRunResult>;
|
|
|
383
383
|
*
|
|
384
384
|
* Scope: the **linear / structured subset** of AIP-15 — steps run in document
|
|
385
385
|
* order; `map`/`loop`/`parallel` nest their child step lists. Non-linear `next`
|
|
386
|
-
* gotos
|
|
387
|
-
*
|
|
388
|
-
*
|
|
386
|
+
* gotos are rejected with a clear diagnostic. `kind:"branch"` compiles in its
|
|
387
|
+
* **forward-only** form: every `branches[].next`/`default` must name a later
|
|
388
|
+
* sibling in the SAME step list (not backward, not into a nested map/loop/
|
|
389
|
+
* parallel body) — see `compileBranchChain` below. Compiling a full goto graph
|
|
390
|
+
* (backward jumps, cross-scope targets) is a separable follow-up; hand-author
|
|
391
|
+
* a `loop` step for retry-style control flow instead.
|
|
389
392
|
*/
|
|
390
393
|
|
|
391
394
|
interface CompileWorkflowOptions {
|
package/dist/index.mjs
CHANGED
|
@@ -458,6 +458,37 @@ function assertLinear(steps) {
|
|
|
458
458
|
}
|
|
459
459
|
});
|
|
460
460
|
}
|
|
461
|
+
function collectStepIds(steps, ids = /* @__PURE__ */ new Set()) {
|
|
462
|
+
for (const s of steps) {
|
|
463
|
+
if (typeof s?.id === "string") ids.add(s.id);
|
|
464
|
+
if (Array.isArray(s?.steps)) collectStepIds(s.steps, ids);
|
|
465
|
+
if (Array.isArray(s?.branches)) {
|
|
466
|
+
for (const br of s.branches) {
|
|
467
|
+
if (Array.isArray(br?.steps)) collectStepIds(br.steps, ids);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
return ids;
|
|
472
|
+
}
|
|
473
|
+
function assertKnownStepRefs(node, knownStepIds, label) {
|
|
474
|
+
if (typeof node === "string") {
|
|
475
|
+
if (node.startsWith("$$")) return;
|
|
476
|
+
const m = node.match(/^\$steps\.([^.]+)/);
|
|
477
|
+
if (m && !knownStepIds.has(m[1])) {
|
|
478
|
+
throw new WorkflowCompileError(
|
|
479
|
+
`${label} references unknown step '${m[1]}' via '${node}' \u2014 no step with that id exists in this workflow`
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
if (Array.isArray(node)) {
|
|
485
|
+
node.forEach((n) => assertKnownStepRefs(n, knownStepIds, label));
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
if (node && typeof node === "object") {
|
|
489
|
+
for (const v of Object.values(node)) assertKnownStepRefs(v, knownStepIds, label);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
461
492
|
function compileWorkflow(handle, opts) {
|
|
462
493
|
const steps = handle.steps;
|
|
463
494
|
if (handle.start && handle.start !== steps[0]?.id) {
|
|
@@ -465,22 +496,69 @@ function compileWorkflow(handle, opts) {
|
|
|
465
496
|
`start='${handle.start}' is not the first step \u2014 structured-subset runs in order`
|
|
466
497
|
);
|
|
467
498
|
}
|
|
468
|
-
|
|
499
|
+
const ctx = { opts, knownStepIds: collectStepIds(steps) };
|
|
469
500
|
const result = handle.result;
|
|
470
501
|
const output = result !== void 0 ? (b) => resolveValue(result, b) : void 0;
|
|
471
502
|
return {
|
|
472
503
|
id: handle.id,
|
|
473
504
|
description: handle.description,
|
|
474
|
-
steps: steps
|
|
505
|
+
steps: compileSiblingsToSteps(steps, ctx),
|
|
475
506
|
...output ? { output } : {}
|
|
476
507
|
};
|
|
477
508
|
}
|
|
478
|
-
function
|
|
509
|
+
function compileSiblingsToSteps(steps, ctx) {
|
|
479
510
|
assertLinear(steps);
|
|
480
|
-
|
|
481
|
-
|
|
511
|
+
const out = [];
|
|
512
|
+
for (let i = 0; i < steps.length; i++) {
|
|
513
|
+
const s = steps[i];
|
|
514
|
+
if (s.kind === "branch") {
|
|
515
|
+
out.push(compileBranchChain(steps, i, ctx));
|
|
516
|
+
return out;
|
|
517
|
+
}
|
|
518
|
+
out.push(compileStep(s, ctx));
|
|
519
|
+
}
|
|
520
|
+
return out;
|
|
521
|
+
}
|
|
522
|
+
function compileStepList(steps, id, ctx) {
|
|
523
|
+
const compiled = compileSiblingsToSteps(steps, ctx);
|
|
524
|
+
if (compiled.length === 1) return compiled[0];
|
|
525
|
+
return { kind: "group", id, steps: compiled };
|
|
482
526
|
}
|
|
483
|
-
function
|
|
527
|
+
function compileBranchChain(steps, i, ctx) {
|
|
528
|
+
const branchStep = steps[i];
|
|
529
|
+
const branches = f(branchStep, "branches");
|
|
530
|
+
const defaultTarget = f(branchStep, "default");
|
|
531
|
+
const resolveTarget = (targetId, label) => {
|
|
532
|
+
const idx = steps.findIndex((s) => s.id === targetId);
|
|
533
|
+
if (idx === -1 || idx <= i) {
|
|
534
|
+
throw new WorkflowCompileError(
|
|
535
|
+
`branch '${branchStep.id}' ${label} targets '${targetId}', which is not a sibling later in this step list \u2014 the forward-only branch compiler only supports jumping to a later sibling in the SAME list (not backward, and not into a nested map/loop/parallel body). Hand-author a 'loop' step for retry-style control flow instead.`
|
|
536
|
+
);
|
|
537
|
+
}
|
|
538
|
+
return idx;
|
|
539
|
+
};
|
|
540
|
+
const defaultIdx = defaultTarget !== void 0 ? resolveTarget(defaultTarget, "default") : i + 1;
|
|
541
|
+
let otherwise = compileSiblingsToSteps(steps.slice(defaultIdx), ctx);
|
|
542
|
+
for (let k = branches.length - 1; k >= 0; k--) {
|
|
543
|
+
const br = branches[k];
|
|
544
|
+
const targetIdx = resolveTarget(br.next, `branches[${k}].next`);
|
|
545
|
+
const thenSteps = compileSiblingsToSteps(steps.slice(targetIdx), ctx);
|
|
546
|
+
const condExpr = br.when;
|
|
547
|
+
const nodeId = k === 0 ? branchStep.id : `${branchStep.id}__branch${k}`;
|
|
548
|
+
otherwise = [
|
|
549
|
+
{
|
|
550
|
+
kind: "branch",
|
|
551
|
+
id: nodeId,
|
|
552
|
+
cond: (b) => evalPredicate(condExpr, b),
|
|
553
|
+
then: thenSteps,
|
|
554
|
+
...otherwise.length > 0 ? { otherwise } : {}
|
|
555
|
+
}
|
|
556
|
+
];
|
|
557
|
+
}
|
|
558
|
+
return otherwise[0];
|
|
559
|
+
}
|
|
560
|
+
function compileAgentStep(step, id, ctx) {
|
|
561
|
+
const opts = ctx.opts;
|
|
484
562
|
const prompt = f(step, "prompt");
|
|
485
563
|
if (typeof prompt !== "string" || prompt.length === 0) {
|
|
486
564
|
throw new WorkflowCompileError(`agent step '${id}' needs a non-empty 'prompt'`);
|
|
@@ -514,7 +592,8 @@ function compileAgentStep(step, id, opts) {
|
|
|
514
592
|
...step.maxRetries !== void 0 ? { maxRetries: step.maxRetries } : {}
|
|
515
593
|
});
|
|
516
594
|
}
|
|
517
|
-
function compileStep(step,
|
|
595
|
+
function compileStep(step, ctx) {
|
|
596
|
+
const opts = ctx.opts;
|
|
518
597
|
const id = step.id;
|
|
519
598
|
switch (step.kind) {
|
|
520
599
|
case "tool": {
|
|
@@ -524,6 +603,7 @@ function compileStep(step, opts) {
|
|
|
524
603
|
if (!tool)
|
|
525
604
|
throw new WorkflowCompileError(`no tool registered for '${toolId}'`);
|
|
526
605
|
const inputs = f(step, "inputs") ?? {};
|
|
606
|
+
assertKnownStepRefs(inputs, ctx.knownStepIds, `tool step '${id}' inputs`);
|
|
527
607
|
return {
|
|
528
608
|
kind: "tool",
|
|
529
609
|
id,
|
|
@@ -535,13 +615,15 @@ function compileStep(step, opts) {
|
|
|
535
615
|
}
|
|
536
616
|
case "map": {
|
|
537
617
|
const over = f(step, "over");
|
|
538
|
-
const inner = compileStepList(f(step, "steps"), `${id}__body`,
|
|
618
|
+
const inner = compileStepList(f(step, "steps"), `${id}__body`, ctx);
|
|
619
|
+
const onError = f(step, "onError");
|
|
539
620
|
return {
|
|
540
621
|
kind: "map",
|
|
541
622
|
id,
|
|
542
623
|
parallelism: f(step, "parallelism"),
|
|
543
624
|
over: (b) => resolveRef(over, b),
|
|
544
|
-
body: () => inner
|
|
625
|
+
body: () => inner,
|
|
626
|
+
...onError !== void 0 ? { onError } : {}
|
|
545
627
|
};
|
|
546
628
|
}
|
|
547
629
|
case "loop": {
|
|
@@ -551,7 +633,7 @@ function compileStep(step, opts) {
|
|
|
551
633
|
id,
|
|
552
634
|
maxIterations: f(step, "max_iterations"),
|
|
553
635
|
while: (b) => evalPredicate(whileExpr, b),
|
|
554
|
-
body: [compileStepList(f(step, "steps"), `${id}__body`,
|
|
636
|
+
body: [compileStepList(f(step, "steps"), `${id}__body`, ctx)]
|
|
555
637
|
};
|
|
556
638
|
}
|
|
557
639
|
case "parallel": {
|
|
@@ -561,7 +643,7 @@ function compileStep(step, opts) {
|
|
|
561
643
|
id,
|
|
562
644
|
branches: branches.map((br) => ({
|
|
563
645
|
id: br.id,
|
|
564
|
-
steps: [compileStepList(br.steps, `${id}__${br.id}`,
|
|
646
|
+
steps: [compileStepList(br.steps, `${id}__${br.id}`, ctx)]
|
|
565
647
|
}))
|
|
566
648
|
};
|
|
567
649
|
}
|
|
@@ -589,14 +671,24 @@ function compileStep(step, opts) {
|
|
|
589
671
|
`subworkflow '${wfId}' not found \u2014 pass it in opts.workflows`
|
|
590
672
|
);
|
|
591
673
|
const compiledChild = compileWorkflow(child, opts);
|
|
592
|
-
|
|
674
|
+
const inputs = f(step, "inputs");
|
|
675
|
+
if (inputs === void 0) {
|
|
676
|
+
return { kind: "subworkflow", id, workflow: compiledChild };
|
|
677
|
+
}
|
|
678
|
+
assertKnownStepRefs(inputs, ctx.knownStepIds, `subworkflow step '${id}' inputs`);
|
|
679
|
+
return {
|
|
680
|
+
kind: "subworkflow",
|
|
681
|
+
id,
|
|
682
|
+
workflow: compiledChild,
|
|
683
|
+
input: (b) => resolveValue(inputs, b)
|
|
684
|
+
};
|
|
593
685
|
}
|
|
594
686
|
case "agent": {
|
|
595
687
|
if (typeof step.prompt === "function") {
|
|
596
688
|
const passthrough = step;
|
|
597
689
|
return passthrough;
|
|
598
690
|
}
|
|
599
|
-
return compileAgentStep(step, id,
|
|
691
|
+
return compileAgentStep(step, id, ctx);
|
|
600
692
|
}
|
|
601
693
|
case "transform": {
|
|
602
694
|
const passthrough = step;
|
|
@@ -604,7 +696,7 @@ function compileStep(step, opts) {
|
|
|
604
696
|
}
|
|
605
697
|
case "branch":
|
|
606
698
|
throw new WorkflowCompileError(
|
|
607
|
-
`
|
|
699
|
+
`internal: branch step '${id}' reached compileStep directly \u2014 branch steps must be compiled via the sibling-list walker`
|
|
608
700
|
);
|
|
609
701
|
default:
|
|
610
702
|
throw new WorkflowCompileError(
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/run-workflow.ts","../src/build-agent-step.ts","../src/compile-workflow.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AA0B,IAAA,CAAK,IAAI,CAAA,SAAA,EAAY,EAAE,CAAA,EAAA;AAAA,OACnD;AAAA;AAEN;ACvWO,SAAS,uBAAA,CACd,QACA,IAAA,EACiB;AACjB,EAAA,MAAM,QAAA,GAAW,sBAAsB,MAAM,CAAA;AAC7C,EAAA,MAAM,MAAA,GAAS,qBAAqB,QAAQ,CAAA;AAC5C,EAAA,OAAO,eAAA,CAAgB,QAAQ,IAAI,CAAA;AACrC","file":"index.mjs","sourcesContent":["/**\n * The step-walker. Executes a {@link RuntimeWorkflow} top-to-bottom, threading\n * each step's output into a run-scoped binding bag, and dispatching `tool`\n * steps through `@agentproto/driver` `runTool` (resolve DRIVER → validate input\n * + context → execute body → validate output). Composite steps (`map` /\n * `branch` / `loop` / `parallel` / `approval` / `subworkflow`) recurse over the\n * same bindings; `suspend` defers to the host's resume hook.\n */\n\nimport { runTool } from \"@agentproto/driver\"\nimport { createHash } from \"node:crypto\"\nimport type { ZodError } from \"zod\"\nimport type {\n AgentStep,\n Bindings,\n FanOutOutcome,\n RunStep,\n RunWorkflowArgs,\n RuntimeWorkflow,\n TolerantFanOutResult,\n WorkflowRunResult,\n} from \"./types.js\"\n\n/** Thrown by a `suspend` step when no host `resume` hook is provided. */\nexport class WorkflowSuspendedError extends Error {\n constructor(\n readonly stepId: string,\n readonly on: readonly string[],\n ) {\n super(\n `workflow suspended at step '${stepId}' awaiting [${on.join(\", \")}] — ` +\n `no resume hook supplied`,\n )\n this.name = \"WorkflowSuspendedError\"\n }\n}\n\ninterface RunState {\n readonly input: unknown\n readonly steps: Record<string, unknown>\n readonly maxTotalCostUsd?: number\n /** Last-known cost per session id; summed to get the run's total spend.\n * A Map (not a running delta) so a session reused across steps via\n * sessionRef is counted once, not double-counted. */\n readonly costBySession: Map<string, number>\n}\n\ninterface RunCtx {\n readonly state: RunState\n readonly approve?: RunWorkflowArgs[\"approve\"]\n readonly resume?: RunWorkflowArgs[\"resume\"]\n readonly signal?: AbortSignal\n readonly agents?: RunWorkflowArgs[\"agents\"]\n readonly cwd?: string\n readonly workspaceSlug?: string\n readonly cache?: RunWorkflowArgs[\"cache\"]\n readonly cacheKey?: RunWorkflowArgs[\"cacheKey\"]\n readonly onStepStart?: RunWorkflowArgs[\"onStepStart\"]\n readonly onStepComplete?: RunWorkflowArgs[\"onStepComplete\"]\n}\n\nfunction view(state: RunState, item?: unknown, index?: number): Bindings {\n return { input: state.input, steps: state.steps, item, index }\n}\n\n/** Resolve a value that is either a static string or a binding selector. */\nfunction resolveSel(sel: string | ((bindings: Bindings) => string), b: Bindings): string {\n return typeof sel === \"function\" ? sel(b) : sel\n}\n\n/** Extract a JSON candidate from raw assistant text:\n * 1. last ```json fenced block if present, else\n * 2. last generic ``` fenced block if present, else\n * 3. the whole trimmed string. */\nfunction extractJsonCandidate(raw: string): string {\n const jsonFence = /```json\\s*([\\s\\S]*?)```/g\n const lastJson = lastMatch(jsonFence, raw)\n if (lastJson !== undefined) return lastJson\n\n const anyFence = /```\\s*([\\s\\S]*?)```/g\n const lastAny = lastMatch(anyFence, raw)\n if (lastAny !== undefined) return lastAny\n\n return raw.trim()\n}\n\nfunction lastMatch(re: RegExp, s: string): string | undefined {\n let m: RegExpExecArray | null\n let last: RegExpExecArray | null = null\n while ((m = re.exec(s)) !== null) last = m\n return last ? last[1]?.trim() : undefined\n}\n\nfunction spentUsd(state: RunState): number {\n let total = 0\n for (const c of state.costBySession.values()) total += c\n return total\n}\n\n/** Deterministic content hash of a step's resolved inputs. */\nfunction hashResolvedInputs(kind: string, resolved: unknown): string {\n return createHash(\"sha256\")\n .update(`${kind}\\u0000${JSON.stringify(resolved) ?? \"undefined\"}`)\n .digest(\"hex\")\n}\n\n/** Namespaced journal key for a step under a run's cacheKey. */\nfunction stepJournalKey(cacheKey: string, step: RunStep): string {\n return `${cacheKey}\\u0000${step.id}\\u0000${step.kind}`\n}\n\n/** True when this step should consult/populate the journal. */\nfunction isCacheEnabled(ctx: RunCtx, step: { cacheable?: boolean }): boolean {\n return step.cacheable === true && ctx.cache !== undefined && ctx.cacheKey !== undefined\n}\n\n/** Read the journal; on a hit return the output, else the key+hash to write on miss. */\nasync function readStepCache(\n ctx: RunCtx,\n step: RunStep,\n resolvedInputs: unknown,\n): Promise<{ hit: true; output: unknown } | { hit: false; key: string; hash: string }> {\n const key = stepJournalKey(ctx.cacheKey!, step)\n const hash = hashResolvedInputs(step.kind, resolvedInputs)\n const entry = await ctx.cache!.get(key)\n if (entry !== undefined && entry.resolvedInputHash === hash) {\n return { hit: true, output: entry.output }\n }\n return { hit: false, key, hash }\n}\n\n/** `err.message` if `err` is an `Error`, else its string coercion. */\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\nfunction formatZodError(err: ZodError): string {\n return err.issues\n .map((i) => `${i.path.length > 0 ? i.path.join(\".\") + \": \" : \"\"}${i.message}`)\n .join(\", \")\n}\n\n/** Run an ordered list of steps, binding each output under its id; return last. */\nasync function runSequence(\n steps: readonly RunStep[],\n ctx: RunCtx,\n item: unknown,\n index: number | undefined,\n): Promise<unknown> {\n let last: unknown\n for (const s of steps) {\n const out = await execStep(s, ctx, item, index)\n ctx.state.steps[s.id] = out\n ctx.onStepComplete?.(s.id, out)\n last = out\n }\n return last\n}\n\n/** Execute the full AgentStep body — spawn, prompt, policy, budget, outputSchema retry loop. */\nasync function execAgentStep(step: AgentStep, ctx: RunCtx, b: Bindings): Promise<unknown> {\n // Notify step start before any execution\n ctx.onStepStart?.(step.id)\n\n if (\n step.adapter &&\n ctx.state.maxTotalCostUsd !== undefined &&\n spentUsd(ctx.state) >= ctx.state.maxTotalCostUsd\n ) {\n throw new Error(\n `step '${step.id}': budget_exceeded — run spend $${spentUsd(ctx.state).toFixed(4)} >= cap $${ctx.state.maxTotalCostUsd}`,\n )\n }\n const cwd = step.cwd ? resolveSel(step.cwd, b) : ctx.cwd\n // Sandbox ref: a selector resolves per-run (undefined ⇒ host spawn); a\n // literal (slug string or inline spec object) passes through as-is.\n const sandbox =\n typeof step.sandbox === \"function\" ? step.sandbox(b) : step.sandbox\n const sessionId = step.adapter\n ? await ctx.agents!.spawn(resolveSel(step.adapter, b), {\n cwd,\n workspaceSlug: ctx.workspaceSlug,\n stepId: step.id,\n ...(sandbox !== undefined ? { sandbox } : {}),\n ...(step.options !== undefined ? { options: step.options } : {}),\n })\n : ctx.agents!.resolveByLabel(step.sessionRef!)\n if (!sessionId) throw new Error(`step '${step.id}': no session (adapter and sessionRef both unresolved)`)\n await ctx.agents!.sendPromptAndWait(sessionId, step.prompt(b))\n if (step.policy && ctx.agents!.onAwaitingInput) {\n await ctx.agents!.onAwaitingInput(sessionId, step.policy)\n }\n\n if (ctx.agents!.readCostUsd) {\n ctx.state.costBySession.set(sessionId, await ctx.agents!.readCostUsd(sessionId))\n }\n\n if (!step.outputSchema) {\n let text: string | undefined\n if (ctx.agents!.readFinalMessage) {\n try {\n text = await ctx.agents!.readFinalMessage(sessionId)\n } catch {\n // ignore\n }\n }\n return { sessionId, ...(text !== undefined ? { text } : {}) }\n }\n\n // Validate-and-retry loop\n if (!ctx.agents!.readFinalMessage) {\n throw new Error(`step '${step.id}': outputSchema requires a host with readFinalMessage`)\n }\n const maxRetries = step.maxRetries ?? 2\n let lastErr = \"\"\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const raw = await ctx.agents!.readFinalMessage(sessionId)\n const candidate = extractJsonCandidate(raw)\n let value: unknown\n try {\n value = JSON.parse(candidate)\n } catch {\n lastErr = \"not valid JSON\"\n if (attempt < maxRetries) {\n await ctx.agents!.sendPromptAndWait(\n sessionId,\n `Your previous reply did not match the required schema: ${lastErr}. ` +\n `Reply again with ONLY a JSON object that matches. No prose, no code fence needed.`,\n )\n }\n continue\n }\n const res = step.outputSchema.safeParse(value)\n if (res.success) return { sessionId, output: res.data }\n lastErr = formatZodError(res.error)\n if (attempt < maxRetries) {\n await ctx.agents!.sendPromptAndWait(\n sessionId,\n `Your previous reply did not match the required schema: ${lastErr}. ` +\n `Reply again with ONLY a JSON object that matches. No prose, no code fence needed.`,\n )\n }\n }\n throw new Error(`step '${step.id}': output_invalid — final message never matched outputSchema (${lastErr})`)\n}\n\nasync function execStep(\n step: RunStep,\n ctx: RunCtx,\n item: unknown,\n index: number | undefined,\n): Promise<unknown> {\n const { state, signal } = ctx\n const b = view(state, item, index)\n\n // Notify step start for non-agent steps (agent steps notify in execAgentStep)\n if (step.kind !== \"agent\") {\n ctx.onStepStart?.(step.id)\n }\n\n switch (step.kind) {\n case \"tool\": {\n const input = step.input(b)\n const runIt = (): Promise<unknown> =>\n runTool({\n tool: step.tool,\n candidates: step.candidates,\n input,\n context: step.context ? step.context(b) : undefined,\n resolverContext: step.resolverContext,\n secrets: step.secrets,\n signal,\n })\n if (!isCacheEnabled(ctx, step)) return runIt()\n const c = await readStepCache(ctx, step, input)\n if (c.hit) return c.output\n const out = await runIt()\n await ctx.cache!.set(c.key, { output: out, resolvedInputHash: c.hash })\n return out\n }\n\n case \"transform\":\n return step.compute(b)\n\n case \"map\": {\n const arr = [...step.over(b)]\n const parallelism = Math.max(1, step.parallelism ?? 1)\n const tolerant = step.onError === \"collect\"\n const results: unknown[] = new Array(arr.length)\n for (let i = 0; i < arr.length; i += parallelism) {\n const chunk = arr.slice(i, i + parallelism)\n if (!tolerant) {\n const outs = await Promise.all(\n chunk.map((el, j) => {\n const idx = i + j\n const inner = step.body(el, idx, view(state, el, idx))\n return execStep(inner, ctx, el, idx)\n }),\n )\n for (let j = 0; j < outs.length; j++) results[i + j] = outs[j]\n continue\n }\n const settled = await Promise.allSettled(\n chunk.map((el, j) => {\n const idx = i + j\n const inner = step.body(el, idx, view(state, el, idx))\n return execStep(inner, ctx, el, idx)\n }),\n )\n settled.forEach((s, j) => {\n const idx = i + j\n results[idx] =\n s.status === \"fulfilled\"\n ? { status: \"fulfilled\", index: idx, value: s.value }\n : { status: \"rejected\", index: idx, item: chunk[j], error: errorMessage(s.reason) }\n })\n }\n if (!tolerant) return results\n const outcomes = results as FanOutOutcome[]\n return {\n results: outcomes,\n succeeded: outcomes.filter((r) => r.status === \"fulfilled\").length,\n failed: outcomes.filter((r) => r.status === \"rejected\").length,\n } satisfies TolerantFanOutResult\n }\n\n case \"pipeline\": {\n const items = [...step.over(b)]\n const tolerant = step.onError === \"collect\"\n if (items.length === 0) return tolerant ? { results: [], succeeded: 0, failed: 0 } : []\n const cap = Math.max(1, step.concurrency ?? items.length)\n const results: unknown[] = new Array(items.length)\n let next = 0\n const runItem = async (idx: number): Promise<void> => {\n let prev: unknown = undefined\n try {\n for (const stage of step.stages) {\n prev = await execStep(stage(items[idx], idx, prev, view(state, items[idx], idx)), ctx, items[idx], idx)\n }\n results[idx] = tolerant ? { status: \"fulfilled\", index: idx, value: prev } : prev\n } catch (err) {\n if (!tolerant) throw err\n results[idx] = { status: \"rejected\", index: idx, item: items[idx], error: errorMessage(err) }\n }\n }\n const worker = async (): Promise<void> => {\n while (next < items.length) {\n const idx = next++\n await runItem(idx)\n }\n }\n await Promise.all(Array.from({ length: Math.min(cap, items.length) }, () => worker()))\n if (!tolerant) return results\n const outcomes = results as FanOutOutcome[]\n return {\n results: outcomes,\n succeeded: outcomes.filter((r) => r.status === \"fulfilled\").length,\n failed: outcomes.filter((r) => r.status === \"rejected\").length,\n } satisfies TolerantFanOutResult\n }\n\n case \"branch\": {\n const chosen = step.cond(b) ? step.then : (step.otherwise ?? [])\n return runSequence(chosen, ctx, item, index)\n }\n\n case \"loop\": {\n let iterations = 0\n let last: unknown\n while (\n iterations < step.maxIterations &&\n step.while(view(state, item, index))\n ) {\n last = await runSequence(step.body, ctx, item, index)\n iterations++\n }\n return last\n }\n\n case \"parallel\": {\n const outs = await Promise.all(\n step.branches.map((br) =>\n runSequence(br.steps, ctx, item, index).then((last) => ({\n id: br.id,\n last,\n })),\n ),\n )\n const record: Record<string, unknown> = {}\n for (const { id, last } of outs) record[id] = last\n return record\n }\n\n case \"approval\": {\n const prompt = step.prompt(b)\n const approvers = step.approvers ?? []\n const approved = ctx.approve\n ? await ctx.approve({ stepId: step.id, prompt, approvers })\n : true\n const followups = approved\n ? (step.onApprove ?? [])\n : (step.onReject ?? [])\n await runSequence(followups, ctx, item, index)\n return { approved }\n }\n\n case \"suspend\": {\n if (!ctx.resume) throw new WorkflowSuspendedError(step.id, step.on)\n return ctx.resume({ stepId: step.id, on: step.on })\n }\n\n case \"group\":\n return runSequence(step.steps, ctx, item, index)\n\n case \"subworkflow\": {\n const childInput = step.input ? step.input(b) : state.input\n const child = await runWorkflowInner(step.workflow, childInput, {\n approve: ctx.approve,\n resume: ctx.resume,\n signal,\n agents: ctx.agents,\n cwd: ctx.cwd,\n workspaceSlug: ctx.workspaceSlug,\n cache: ctx.cache,\n cacheKey: ctx.cacheKey,\n })\n return child.output\n }\n\n case \"agent\": {\n if (!ctx.agents) throw new Error(`step '${step.id}': AgentStep requires a host agents implementation`)\n if (!isCacheEnabled(ctx, step)) return execAgentStep(step, ctx, b)\n const resolved = {\n prompt: step.prompt(b),\n adapter: step.adapter ? resolveSel(step.adapter, b) : undefined,\n sessionRef: step.sessionRef,\n }\n const c = await readStepCache(ctx, step, resolved)\n if (c.hit) return c.output // cache hit ⇒ NO spawn, NO budget spend\n const out = await execAgentStep(step, ctx, b)\n await ctx.cache!.set(c.key, { output: out, resolvedInputHash: c.hash })\n return out\n }\n }\n}\n\nasync function runWorkflowInner(\n workflow: RuntimeWorkflow,\n input: unknown,\n hooks: Pick<RunCtx, \"approve\" | \"resume\" | \"signal\" | \"agents\" | \"cwd\" | \"workspaceSlug\" | \"cache\" | \"cacheKey\" | \"onStepStart\" | \"onStepComplete\">,\n maxTotalCostUsd?: number,\n): Promise<WorkflowRunResult> {\n const state: RunState = { input, steps: {}, costBySession: new Map(), maxTotalCostUsd }\n const ctx: RunCtx = { state, ...hooks }\n let lastId: string | undefined\n for (const step of workflow.steps) {\n const out = await execStep(step, ctx, undefined, undefined)\n state.steps[step.id] = out\n ctx.onStepComplete?.(step.id, out)\n lastId = step.id\n }\n const bindings = view(state)\n const output = workflow.output\n ? workflow.output(bindings)\n : lastId !== undefined\n ? state.steps[lastId]\n : undefined\n return { output, bindings }\n}\n\nexport async function runWorkflow(\n args: RunWorkflowArgs,\n): Promise<WorkflowRunResult> {\n return runWorkflowInner(args.workflow, args.input, {\n approve: args.approve,\n resume: args.resume,\n signal: args.signal,\n agents: args.agents,\n cwd: args.cwd,\n workspaceSlug: args.workspaceSlug,\n cache: args.cache,\n cacheKey: args.cacheKey,\n onStepStart: args.onStepStart,\n onStepComplete: args.onStepComplete,\n }, args.maxTotalCostUsd)\n}\n","/**\n * Shared `AgentStep` construction — the one place that applies AgentStep's\n * defaults (`policy` → `{ awaiting: \"fail\" }`, a literal `prompt` wrapped as\n * a `Selector`). Used by both `compileWorkflow`'s declarative `kind:\"agent\"`\n * step and `@agentproto/runtime`'s `translateStages` (the `workflow_start` /\n * `WorkflowRunner` path), so the two authoring surfaces stay byte-identical\n * instead of drifting apart.\n */\n\nimport type { AgentSandboxRef, AgentStep, Bindings, Selector } from \"./types.js\"\n\nexport interface AgentStepFields {\n /** A literal prompt string, or a per-run selector (declarative manifest\n * steps resolve `$steps.*` refs into one before calling this). */\n prompt: string | Selector<string>\n adapter?: string\n sessionRef?: string\n sandbox?: AgentSandboxRef\n cacheable?: boolean\n policy?: AgentStep[\"policy\"]\n outputSchema?: AgentStep[\"outputSchema\"]\n maxRetries?: number\n options?: Record<string, boolean | number | string>\n}\n\n/** Build a runtime {@link AgentStep} from field values, applying the same\n * defaults everywhere: `policy` defaults to `{ awaiting: \"fail\" }`. */\nexport function buildAgentStep(id: string, fields: AgentStepFields): AgentStep {\n const prompt = fields.prompt\n return {\n kind: \"agent\",\n id,\n ...(fields.adapter !== undefined ? { adapter: fields.adapter } : {}),\n ...(fields.sessionRef !== undefined ? { sessionRef: fields.sessionRef } : {}),\n ...(fields.sandbox !== undefined ? { sandbox: fields.sandbox } : {}),\n ...(fields.cacheable ? { cacheable: true } : {}),\n ...(fields.options !== undefined ? { options: fields.options } : {}),\n prompt: typeof prompt === \"function\" ? prompt : ((_b: Bindings) => prompt),\n policy: fields.policy ?? { awaiting: \"fail\" as const },\n ...(fields.outputSchema !== undefined ? { outputSchema: fields.outputSchema } : {}),\n ...(fields.maxRetries !== undefined ? { maxRetries: fields.maxRetries } : {}),\n }\n}\n","/**\n * Compile a declarative AIP-15 `WorkflowHandle` into a runnable\n * {@link RuntimeWorkflow} for {@link runWorkflow}. This is the bridge that makes\n * an authored WORKFLOW.md actually execute.\n *\n * AIP-15 leaves the IO seam (`step.inputs`, `map.over`, `loop.while`) to a\n * meta-validator. This compiler pins a concrete, minimal **reference grammar**\n * for it — the convention a manifest author writes:\n *\n * - data refs: `$input` · `$input.a.b` · `$steps.<id>` · `$steps.<id>.a`\n * · `$item` · `$item.a` · `$index` (`$$` escapes a literal `$`)\n * - `step.inputs`: a JSON object whose leaf strings may be refs (resolved\n * recursively); non-`$` strings are literals\n * - `map.over`: a ref to an array\n * - `loop.while` / approval prompt: `<ref> <op> <literal>` (`== != < <= > >=`)\n * or a bare ref (truthiness)\n *\n * Scope: the **linear / structured subset** of AIP-15 — steps run in document\n * order; `map`/`loop`/`parallel` nest their child step lists. Non-linear `next`\n * gotos and goto-style `branch` routing are rejected with a clear diagnostic\n * (hand-author a structured `BranchStep`, or nest). Compiling the full goto\n * graph is a separable follow-up.\n */\n\nimport type { WorkflowHandle } from \"@agentproto/workflow\"\nimport type { DriverHandle } from \"@agentproto/driver\"\nimport type { ToolHandle } from \"@agentproto/tool\"\nimport type { AgentRefResolution, AgentStep, Bindings, RunStep, RuntimeWorkflow } from \"./types.js\"\nimport { buildAgentStep } from \"./build-agent-step.js\"\n\nexport interface CompileWorkflowOptions {\n /** TOOL contracts by id — each `tool` step resolves its handle here. */\n tools: ReadonlyMap<string, ToolHandle> | Record<string, ToolHandle>\n /** DRIVER candidates the resolver dispatches over for every tool step. */\n candidates: readonly DriverHandle[]\n /** Resolve a tool step's injected context (live capabilities) from bindings. */\n contextFor?: (toolId: string, bindings: Bindings) => unknown\n /** Sub-workflows by id, for `subworkflow` steps. */\n workflows?:\n | ReadonlyMap<string, WorkflowHandle>\n | Record<string, WorkflowHandle>\n /** App-scoped agent ids for a declarative `kind:\"agent\"` step's\n * `agent.ref` — e.g. `{ \"@app/reviewer\": { adapter: \"mastra-agent\",\n * options: { agent: \"<dir>/.agentproto/agents/reviewer/AGENT.md\" } } }`.\n * Built by the host from its own app-install state (see\n * `@agentproto/runtime`'s `resolveAgentRefsForWorkflow`). A step using\n * `agent.ref` with this unset, or naming a ref this map doesn't have,\n * fails compilation — never the runtime. */\n agentRefs?: ReadonlyMap<string, AgentRefResolution> | Record<string, AgentRefResolution>\n}\n\nexport class WorkflowCompileError extends Error {\n constructor(message: string) {\n super(`compileWorkflow: ${message}`)\n this.name = \"WorkflowCompileError\"\n }\n}\n\n// ── reference + predicate resolution (the AIP-16 IO seam) ────────────\n\nconst get = <T>(\n m: ReadonlyMap<string, T> | Record<string, T>,\n key: string,\n): T | undefined =>\n m instanceof Map ? m.get(key) : (m as Record<string, T>)[key]\n\nfunction dig(value: unknown, path: readonly string[]): unknown {\n let v = value\n for (const seg of path) {\n if (v == null) return undefined\n v = (v as Record<string, unknown>)[seg]\n }\n return v\n}\n\n/** Resolve a single `$…` reference string against the run bindings. */\nexport function resolveRef(ref: string, b: Bindings): unknown {\n if (ref === \"$index\") return b.index\n const m = ref.match(/^\\$(input|item|steps)((?:\\.[^.]+)*)$/)\n if (!m) throw new WorkflowCompileError(`bad reference '${ref}'`)\n const segs = m[2] ? m[2].slice(1).split(\".\") : []\n switch (m[1]) {\n case \"input\":\n return dig(b.input, segs)\n case \"item\":\n return dig(b.item, segs)\n case \"steps\": {\n const [stepId, ...rest] = segs\n if (!stepId) throw new WorkflowCompileError(`'$steps' needs a step id`)\n return dig(b.steps[stepId], rest)\n }\n }\n}\n\n/** Recursively resolve a value node: refs in strings, into arrays/objects. */\nexport function resolveValue(node: unknown, b: Bindings): unknown {\n if (typeof node === \"string\") {\n if (node.startsWith(\"$$\")) return node.slice(1) // $$ → literal $\n if (node.startsWith(\"$\")) return resolveRef(node, b)\n return node\n }\n if (Array.isArray(node)) return node.map((n) => resolveValue(n, b))\n if (node && typeof node === \"object\") {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(node as Record<string, unknown>))\n out[k] = resolveValue(v, b)\n return out\n }\n return node\n}\n\nconst COMPARATORS: Record<string, (a: number, b: number) => boolean> = {\n \"<\": (a, c) => a < c,\n \"<=\": (a, c) => a <= c,\n \">\": (a, c) => a > c,\n \">=\": (a, c) => a >= c,\n}\n\nfunction literal(token: string, b: Bindings): unknown {\n if (token.startsWith(\"$\")) return resolveRef(token, b)\n if (token === \"true\") return true\n if (token === \"false\") return false\n if (token === \"null\") return null\n if (/^-?\\d+(\\.\\d+)?$/.test(token)) return Number(token)\n return token.replace(/^['\"]|['\"]$/g, \"\")\n}\n\n/** Evaluate a `while`/`when` predicate string against the bindings. */\nexport function evalPredicate(expr: string, b: Bindings): boolean {\n const m = expr.match(/^(.+?)\\s*(==|!=|<=|>=|<|>)\\s*(.+)$/)\n if (!m) return Boolean(literal(expr.trim(), b)) // bare ref → truthiness\n const left = literal(m[1]!.trim(), b)\n const right = literal(m[3]!.trim(), b)\n switch (m[2]) {\n case \"==\":\n return left === right\n case \"!=\":\n return left !== right\n default: {\n const cmp = COMPARATORS[m[2]!]!\n return cmp(Number(left), Number(right))\n }\n }\n}\n\n// ── step compilation ─────────────────────────────────────────────────\n\n/** AIP step ids may be paths/refs; the runtime key is the last segment. */\nfunction normalizeToolId(ref: string): string {\n let s = ref.trim()\n if (s.endsWith(\"/TOOL.md\")) s = s.slice(0, -\"/TOOL.md\".length)\n const slash = s.lastIndexOf(\"/\")\n return slash === -1 ? s : s.slice(slash + 1)\n}\n\n// AIP step frontmatter leaves IO fields as opaque `{}`; read them dynamically.\nconst f = <T>(step: object, key: string): T =>\n (step as Record<string, unknown>)[key] as T\n\nfunction assertLinear(steps: readonly { id: string; kind: string; next?: string }[]): void {\n steps.forEach((s, i) => {\n const next = (s as { next?: string }).next\n const followingId = steps[i + 1]?.id\n if (next && next !== followingId) {\n throw new WorkflowCompileError(\n `step '${s.id}' has a non-linear next='${next}' — the structured-subset ` +\n `compiler only runs steps in document order. Hand-author a BranchStep ` +\n `or nest structurally.`,\n )\n }\n })\n}\n\nexport function compileWorkflow(\n handle: WorkflowHandle,\n opts: CompileWorkflowOptions,\n): RuntimeWorkflow {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const steps = handle.steps as unknown as any[]\n if (handle.start && handle.start !== steps[0]?.id) {\n throw new WorkflowCompileError(\n `start='${handle.start}' is not the first step — structured-subset runs in order`,\n )\n }\n assertLinear(steps)\n // `result` is the optional output value-expression (AIP-15): map it through\n // the same ref grammar as a step's inputs. Absent ⇒ no output selector, so\n // runWorkflow falls back to the final step's result.\n const result = (handle as { result?: unknown }).result\n const output =\n result !== undefined ? (b: Bindings) => resolveValue(result, b) : undefined\n return {\n id: handle.id,\n description: handle.description,\n steps: steps.map((s) => compileStep(s, opts)),\n ...(output ? { output } : {}),\n }\n}\n\nfunction compileStepList(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n steps: any[],\n id: string,\n opts: CompileWorkflowOptions,\n): RunStep {\n assertLinear(steps)\n if (steps.length === 1) return compileStep(steps[0], opts)\n return { kind: \"group\", id, steps: steps.map((s) => compileStep(s, opts)) }\n}\n\n/**\n * Compile a declarative `kind:\"agent\"` manifest step — `{ agent: { ref },\n * prompt, adapter?, sessionRef?, sandbox?, cacheable?, policy?, outputSchema?,\n * maxRetries? }` — into a real {@link AgentStep}. `prompt` runs through the\n * same `$input`/`$steps.<id>` ref grammar as a `tool` step's `inputs`.\n * `agent.ref` resolves via `opts.agentRefs` — unresolvable (no map, or an id\n * the map doesn't have) fails HERE, at compile time, never at the runtime\n * spawn.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileAgentStep(step: any, id: string, opts: CompileWorkflowOptions): AgentStep {\n const prompt = f<string>(step, \"prompt\")\n if (typeof prompt !== \"string\" || prompt.length === 0) {\n throw new WorkflowCompileError(`agent step '${id}' needs a non-empty 'prompt'`)\n }\n\n let adapter: string | undefined = typeof step.adapter === \"string\" ? step.adapter : undefined\n let options: Record<string, boolean | number | string> | undefined =\n step.options !== undefined ? step.options : undefined\n\n const agentRef: unknown = step.agent?.ref\n if (agentRef !== undefined) {\n if (typeof agentRef !== \"string\" || agentRef.trim().length === 0) {\n throw new WorkflowCompileError(`agent step '${id}' has an empty 'agent.ref'`)\n }\n const resolved = opts.agentRefs ? get(opts.agentRefs, agentRef) : undefined\n if (!resolved) {\n const available = opts.agentRefs\n ? opts.agentRefs instanceof Map\n ? [...opts.agentRefs.keys()]\n : Object.keys(opts.agentRefs)\n : []\n throw new WorkflowCompileError(\n `agent step '${id}' references unknown agent ref '${agentRef}'` +\n (available.length > 0\n ? ` — available refs: ${available.join(\", \")}`\n : \" — no agent refs are configured for this compile (not running in an app context?)\"),\n )\n }\n adapter = resolved.adapter\n options = resolved.options\n }\n\n return buildAgentStep(id, {\n prompt: (b: Bindings) => String(resolveValue(prompt, b)),\n ...(adapter !== undefined ? { adapter } : {}),\n ...(step.sessionRef !== undefined ? { sessionRef: step.sessionRef } : {}),\n ...(step.sandbox !== undefined ? { sandbox: step.sandbox } : {}),\n ...(step.cacheable ? { cacheable: true } : {}),\n ...(options !== undefined ? { options } : {}),\n policy: step.policy,\n ...(step.outputSchema !== undefined ? { outputSchema: step.outputSchema } : {}),\n ...(step.maxRetries !== undefined ? { maxRetries: step.maxRetries } : {}),\n })\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileStep(step: any, opts: CompileWorkflowOptions): RunStep {\n const id: string = step.id\n switch (step.kind) {\n case \"tool\": {\n const ref = typeof step.tool === \"string\" ? step.tool : step.tool.entry\n const toolId = normalizeToolId(ref)\n const tool = get(opts.tools, toolId)\n if (!tool)\n throw new WorkflowCompileError(`no tool registered for '${toolId}'`)\n const inputs = f<unknown>(step, \"inputs\") ?? {}\n return {\n kind: \"tool\",\n id,\n tool,\n candidates: opts.candidates,\n input: (b) => resolveValue(inputs, b),\n context: opts.contextFor\n ? (b) => opts.contextFor!(toolId, b)\n : undefined,\n }\n }\n\n case \"map\": {\n const over = f<string>(step, \"over\")\n const inner = compileStepList(f(step, \"steps\"), `${id}__body`, opts)\n return {\n kind: \"map\",\n id,\n parallelism: f<number | undefined>(step, \"parallelism\"),\n over: (b) => resolveRef(over, b) as readonly unknown[],\n body: () => inner,\n }\n }\n\n case \"loop\": {\n const whileExpr = f<string>(step, \"while\")\n return {\n kind: \"loop\",\n id,\n maxIterations: f<number>(step, \"max_iterations\"),\n while: (b) => evalPredicate(whileExpr, b),\n body: [compileStepList(f(step, \"steps\"), `${id}__body`, opts)],\n }\n }\n\n case \"parallel\": {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const branches = f<any[]>(step, \"branches\")\n return {\n kind: \"parallel\",\n id,\n branches: branches.map((br) => ({\n id: br.id,\n steps: [compileStepList(br.steps, `${id}__${br.id}`, opts)],\n })),\n }\n }\n\n case \"approval\": {\n const prompt = f<string>(step, \"prompt\")\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const approvers = (f<any[]>(step, \"approvers\") ?? []).map(\n (a) => a.role ?? a.userId ?? String(a),\n )\n return {\n kind: \"approval\",\n id,\n approvers,\n prompt: (b) => String(resolveValue(prompt, b)),\n }\n }\n\n case \"suspend\": {\n const resume = f<{ on: string[]; timeout_ms?: number }>(step, \"resume\")\n return { kind: \"suspend\", id, on: resume.on, timeoutMs: resume.timeout_ms }\n }\n\n case \"subworkflow\": {\n const wfId = f<string>(step, \"workflow\")\n const child = opts.workflows ? get(opts.workflows, wfId) : undefined\n if (!child)\n throw new WorkflowCompileError(\n `subworkflow '${wfId}' not found — pass it in opts.workflows`,\n )\n const compiledChild = compileWorkflow(child, opts)\n return { kind: \"subworkflow\", id, workflow: compiledChild }\n }\n\n case \"agent\": {\n // Two shapes reach here under the same `kind:\"agent\"`: an ENTRY-based\n // handle's already-built runtime AgentStep (function-valued `prompt`\n // selector — nothing declarative left to resolve, pass through\n // unchanged), or a purely-declarative manifest step (`prompt` is a\n // plain string) that this compiler must turn into a real AgentStep,\n // the same way `translateStages` does for `workflow_start`.\n if (typeof step.prompt === \"function\") {\n const passthrough: RunStep = step\n return passthrough\n }\n return compileAgentStep(step, id, opts)\n }\n\n case \"transform\": {\n // Not a declarative manifest kind — no string expression language for\n // `compute` — so it only reaches the compiler from an ENTRY-based\n // handle, already built as a runtime TransformStep (function-valued\n // `compute`). Passes through unchanged: this is what lets an entry.mjs\n // step shape/serialize an earlier tool step's output (e.g.\n // `JSON.stringify` a prior `$steps.<id>` value) for a later tool step\n // to consume as a plain string input, something the `$steps.*` ref\n // grammar alone can't do. `step` is `any`, so no cast is needed.\n const passthrough: RunStep = step\n return passthrough\n }\n\n case \"branch\":\n throw new WorkflowCompileError(\n `goto-style 'branch' (step '${id}') is unsupported in the structured ` +\n `subset — hand-author a structured BranchStep, or nest.`,\n )\n\n default:\n throw new WorkflowCompileError(\n `unsupported step kind '${step.kind}' (step '${id}')`,\n )\n }\n}\n","/**\n * compileWorkflowManifest — the connective step between an authored\n * `WORKFLOW.md` and a runnable workflow.\n *\n * AIP-15 ships every piece needed to run a declarative manifest except the\n * seam that joins them: `parseWorkflowManifest` (md + frontmatter → manifest)\n * and `workflowFromManifest` (manifest → `WorkflowHandle`) live in\n * `@agentproto/workflow`; `compileWorkflow` (handle → `RuntimeWorkflow`) lives\n * here. Without this chain an authored `WORKFLOW.md` parses and validates but\n * never reaches the executor. This joins the three so a manifest source string\n * compiles straight to a runnable workflow — no hand-built handle.\n *\n * Framework-pure: the caller owns reading the file off disk (this package does\n * no I/O), and passes the source string in. The tool registry + driver\n * candidates are injected via {@link CompileWorkflowOptions}, same as the\n * hand-built path.\n */\n\nimport {\n parseWorkflowManifest,\n workflowFromManifest,\n} from \"@agentproto/workflow/manifest\"\n\nimport { compileWorkflow } from \"./compile-workflow.js\"\nimport type { CompileWorkflowOptions } from \"./compile-workflow.js\"\nimport type { RuntimeWorkflow } from \"./types.js\"\n\n/**\n * Compile a `WORKFLOW.md` source string into a {@link RuntimeWorkflow} ready\n * for `runWorkflow`. Parses + validates the frontmatter against the AIP-15\n * schema, lifts it to a `WorkflowHandle`, then compiles its step graph against\n * the injected tool registry. Throws on invalid frontmatter (the parser's\n * diagnostic) or an unresolved tool / non-linear step (the compiler's).\n */\nexport function compileWorkflowManifest(\n source: string,\n opts: CompileWorkflowOptions,\n): RuntimeWorkflow {\n const manifest = parseWorkflowManifest(source)\n const handle = workflowFromManifest(manifest)\n return compileWorkflow(handle, opts)\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/run-workflow.ts","../src/build-agent-step.ts","../src/compile-workflow.ts","../src/load-workflow.ts"],"names":[],"mappings":";;;;;;;;;AAwBO,IAAM,sBAAA,GAAN,cAAqC,KAAA,CAAM;AAAA,EAChD,WAAA,CACW,QACA,EAAA,EACT;AACA,IAAA,KAAA;AAAA,MACE,+BAA+B,MAAM,CAAA,YAAA,EAAe,EAAA,CAAG,IAAA,CAAK,IAAI,CAAC,CAAA,gCAAA;AAAA,KAEnE;AANS,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,EAAA,GAAA,EAAA;AAMT,IAAA,IAAA,CAAK,IAAA,GAAO,wBAAA;AAAA,EACd;AAAA,EARW,MAAA;AAAA,EACA,EAAA;AAQb;AA0BA,SAAS,IAAA,CAAK,KAAA,EAAiB,IAAA,EAAgB,KAAA,EAA0B;AACvE,EAAA,OAAO,EAAE,OAAO,KAAA,CAAM,KAAA,EAAO,OAAO,KAAA,CAAM,KAAA,EAAO,MAAM,KAAA,EAAM;AAC/D;AAGA,SAAS,UAAA,CAAW,KAAgD,CAAA,EAAqB;AACvF,EAAA,OAAO,OAAO,GAAA,KAAQ,UAAA,GAAa,GAAA,CAAI,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AAA,EAA0B,IAAA,CAAK,IAAI,CAAA,SAAA,EAAY,EAAE,CAAA,EAAA;AAAA,OACnD;AAAA;AAEN;ACxfO,SAAS,uBAAA,CACd,QACA,IAAA,EACiB;AACjB,EAAA,MAAM,QAAA,GAAW,sBAAsB,MAAM,CAAA;AAC7C,EAAA,MAAM,MAAA,GAAS,qBAAqB,QAAQ,CAAA;AAC5C,EAAA,OAAO,eAAA,CAAgB,QAAQ,IAAI,CAAA;AACrC","file":"index.mjs","sourcesContent":["/**\n * The step-walker. Executes a {@link RuntimeWorkflow} top-to-bottom, threading\n * each step's output into a run-scoped binding bag, and dispatching `tool`\n * steps through `@agentproto/driver` `runTool` (resolve DRIVER → validate input\n * + context → execute body → validate output). Composite steps (`map` /\n * `branch` / `loop` / `parallel` / `approval` / `subworkflow`) recurse over the\n * same bindings; `suspend` defers to the host's resume hook.\n */\n\nimport { runTool } from \"@agentproto/driver\"\nimport { createHash } from \"node:crypto\"\nimport type { ZodError } from \"zod\"\nimport type {\n AgentStep,\n Bindings,\n FanOutOutcome,\n RunStep,\n RunWorkflowArgs,\n RuntimeWorkflow,\n TolerantFanOutResult,\n WorkflowRunResult,\n} from \"./types.js\"\n\n/** Thrown by a `suspend` step when no host `resume` hook is provided. */\nexport class WorkflowSuspendedError extends Error {\n constructor(\n readonly stepId: string,\n readonly on: readonly string[],\n ) {\n super(\n `workflow suspended at step '${stepId}' awaiting [${on.join(\", \")}] — ` +\n `no resume hook supplied`,\n )\n this.name = \"WorkflowSuspendedError\"\n }\n}\n\ninterface RunState {\n readonly input: unknown\n readonly steps: Record<string, unknown>\n readonly maxTotalCostUsd?: number\n /** Last-known cost per session id; summed to get the run's total spend.\n * A Map (not a running delta) so a session reused across steps via\n * sessionRef is counted once, not double-counted. */\n readonly costBySession: Map<string, number>\n}\n\ninterface RunCtx {\n readonly state: RunState\n readonly approve?: RunWorkflowArgs[\"approve\"]\n readonly resume?: RunWorkflowArgs[\"resume\"]\n readonly signal?: AbortSignal\n readonly agents?: RunWorkflowArgs[\"agents\"]\n readonly cwd?: string\n readonly workspaceSlug?: string\n readonly cache?: RunWorkflowArgs[\"cache\"]\n readonly cacheKey?: RunWorkflowArgs[\"cacheKey\"]\n readonly onStepStart?: RunWorkflowArgs[\"onStepStart\"]\n readonly onStepComplete?: RunWorkflowArgs[\"onStepComplete\"]\n}\n\nfunction view(state: RunState, item?: unknown, index?: number): Bindings {\n return { input: state.input, steps: state.steps, item, index }\n}\n\n/** Resolve a value that is either a static string or a binding selector. */\nfunction resolveSel(sel: string | ((bindings: Bindings) => string), b: Bindings): string {\n return typeof sel === \"function\" ? sel(b) : sel\n}\n\n/** Extract a JSON candidate from raw assistant text:\n * 1. last ```json fenced block if present, else\n * 2. last generic ``` fenced block if present, else\n * 3. the whole trimmed string. */\nfunction extractJsonCandidate(raw: string): string {\n const jsonFence = /```json\\s*([\\s\\S]*?)```/g\n const lastJson = lastMatch(jsonFence, raw)\n if (lastJson !== undefined) return lastJson\n\n const anyFence = /```\\s*([\\s\\S]*?)```/g\n const lastAny = lastMatch(anyFence, raw)\n if (lastAny !== undefined) return lastAny\n\n return raw.trim()\n}\n\nfunction lastMatch(re: RegExp, s: string): string | undefined {\n let m: RegExpExecArray | null\n let last: RegExpExecArray | null = null\n while ((m = re.exec(s)) !== null) last = m\n return last ? last[1]?.trim() : undefined\n}\n\nfunction spentUsd(state: RunState): number {\n let total = 0\n for (const c of state.costBySession.values()) total += c\n return total\n}\n\n/** Deterministic content hash of a step's resolved inputs. */\nfunction hashResolvedInputs(kind: string, resolved: unknown): string {\n return createHash(\"sha256\")\n .update(`${kind}\\u0000${JSON.stringify(resolved) ?? \"undefined\"}`)\n .digest(\"hex\")\n}\n\n/** Namespaced journal key for a step under a run's cacheKey. */\nfunction stepJournalKey(cacheKey: string, step: RunStep): string {\n return `${cacheKey}\\u0000${step.id}\\u0000${step.kind}`\n}\n\n/** True when this step should consult/populate the journal. */\nfunction isCacheEnabled(ctx: RunCtx, step: { cacheable?: boolean }): boolean {\n return step.cacheable === true && ctx.cache !== undefined && ctx.cacheKey !== undefined\n}\n\n/** Read the journal; on a hit return the output, else the key+hash to write on miss. */\nasync function readStepCache(\n ctx: RunCtx,\n step: RunStep,\n resolvedInputs: unknown,\n): Promise<{ hit: true; output: unknown } | { hit: false; key: string; hash: string }> {\n const key = stepJournalKey(ctx.cacheKey!, step)\n const hash = hashResolvedInputs(step.kind, resolvedInputs)\n const entry = await ctx.cache!.get(key)\n if (entry !== undefined && entry.resolvedInputHash === hash) {\n return { hit: true, output: entry.output }\n }\n return { hit: false, key, hash }\n}\n\n/** `err.message` if `err` is an `Error`, else its string coercion. */\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\nfunction formatZodError(err: ZodError): string {\n return err.issues\n .map((i) => `${i.path.length > 0 ? i.path.join(\".\") + \": \" : \"\"}${i.message}`)\n .join(\", \")\n}\n\n/** Run an ordered list of steps, binding each output under its id; return last. */\nasync function runSequence(\n steps: readonly RunStep[],\n ctx: RunCtx,\n item: unknown,\n index: number | undefined,\n): Promise<unknown> {\n let last: unknown\n for (const s of steps) {\n const out = await execStep(s, ctx, item, index)\n ctx.state.steps[s.id] = out\n ctx.onStepComplete?.(s.id, out)\n last = out\n }\n return last\n}\n\n/** Execute the full AgentStep body — spawn, prompt, policy, budget, outputSchema retry loop. */\nasync function execAgentStep(step: AgentStep, ctx: RunCtx, b: Bindings): Promise<unknown> {\n // Notify step start before any execution\n ctx.onStepStart?.(step.id)\n\n if (\n step.adapter &&\n ctx.state.maxTotalCostUsd !== undefined &&\n spentUsd(ctx.state) >= ctx.state.maxTotalCostUsd\n ) {\n throw new Error(\n `step '${step.id}': budget_exceeded — run spend $${spentUsd(ctx.state).toFixed(4)} >= cap $${ctx.state.maxTotalCostUsd}`,\n )\n }\n const cwd = step.cwd ? resolveSel(step.cwd, b) : ctx.cwd\n // Sandbox ref: a selector resolves per-run (undefined ⇒ host spawn); a\n // literal (slug string or inline spec object) passes through as-is.\n const sandbox =\n typeof step.sandbox === \"function\" ? step.sandbox(b) : step.sandbox\n const sessionId = step.adapter\n ? await ctx.agents!.spawn(resolveSel(step.adapter, b), {\n cwd,\n workspaceSlug: ctx.workspaceSlug,\n stepId: step.id,\n ...(sandbox !== undefined ? { sandbox } : {}),\n ...(step.options !== undefined ? { options: step.options } : {}),\n })\n : ctx.agents!.resolveByLabel(step.sessionRef!)\n if (!sessionId) throw new Error(`step '${step.id}': no session (adapter and sessionRef both unresolved)`)\n await ctx.agents!.sendPromptAndWait(sessionId, step.prompt(b))\n if (step.policy && ctx.agents!.onAwaitingInput) {\n await ctx.agents!.onAwaitingInput(sessionId, step.policy)\n }\n\n if (ctx.agents!.readCostUsd) {\n ctx.state.costBySession.set(sessionId, await ctx.agents!.readCostUsd(sessionId))\n }\n\n if (!step.outputSchema) {\n let text: string | undefined\n if (ctx.agents!.readFinalMessage) {\n try {\n text = await ctx.agents!.readFinalMessage(sessionId)\n } catch {\n // ignore\n }\n }\n return { sessionId, ...(text !== undefined ? { text } : {}) }\n }\n\n // Validate-and-retry loop\n if (!ctx.agents!.readFinalMessage) {\n throw new Error(`step '${step.id}': outputSchema requires a host with readFinalMessage`)\n }\n const maxRetries = step.maxRetries ?? 2\n let lastErr = \"\"\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const raw = await ctx.agents!.readFinalMessage(sessionId)\n const candidate = extractJsonCandidate(raw)\n let value: unknown\n try {\n value = JSON.parse(candidate)\n } catch {\n lastErr = \"not valid JSON\"\n if (attempt < maxRetries) {\n await ctx.agents!.sendPromptAndWait(\n sessionId,\n `Your previous reply did not match the required schema: ${lastErr}. ` +\n `Reply again with ONLY a JSON object that matches. No prose, no code fence needed.`,\n )\n }\n continue\n }\n const res = step.outputSchema.safeParse(value)\n if (res.success) return { sessionId, output: res.data }\n lastErr = formatZodError(res.error)\n if (attempt < maxRetries) {\n await ctx.agents!.sendPromptAndWait(\n sessionId,\n `Your previous reply did not match the required schema: ${lastErr}. ` +\n `Reply again with ONLY a JSON object that matches. No prose, no code fence needed.`,\n )\n }\n }\n throw new Error(`step '${step.id}': output_invalid — final message never matched outputSchema (${lastErr})`)\n}\n\nasync function execStep(\n step: RunStep,\n ctx: RunCtx,\n item: unknown,\n index: number | undefined,\n): Promise<unknown> {\n const { state, signal } = ctx\n const b = view(state, item, index)\n\n // Notify step start for non-agent steps (agent steps notify in execAgentStep)\n if (step.kind !== \"agent\") {\n ctx.onStepStart?.(step.id)\n }\n\n switch (step.kind) {\n case \"tool\": {\n const input = step.input(b)\n const runIt = (): Promise<unknown> =>\n runTool({\n tool: step.tool,\n candidates: step.candidates,\n input,\n context: step.context ? step.context(b) : undefined,\n resolverContext: step.resolverContext,\n secrets: step.secrets,\n signal,\n })\n if (!isCacheEnabled(ctx, step)) return runIt()\n const c = await readStepCache(ctx, step, input)\n if (c.hit) return c.output\n const out = await runIt()\n await ctx.cache!.set(c.key, { output: out, resolvedInputHash: c.hash })\n return out\n }\n\n case \"transform\":\n return step.compute(b)\n\n case \"map\": {\n const arr = [...step.over(b)]\n const parallelism = Math.max(1, step.parallelism ?? 1)\n const tolerant = step.onError === \"collect\"\n const results: unknown[] = new Array(arr.length)\n for (let i = 0; i < arr.length; i += parallelism) {\n const chunk = arr.slice(i, i + parallelism)\n if (!tolerant) {\n const outs = await Promise.all(\n chunk.map((el, j) => {\n const idx = i + j\n const inner = step.body(el, idx, view(state, el, idx))\n return execStep(inner, ctx, el, idx)\n }),\n )\n for (let j = 0; j < outs.length; j++) results[i + j] = outs[j]\n continue\n }\n const settled = await Promise.allSettled(\n chunk.map((el, j) => {\n const idx = i + j\n const inner = step.body(el, idx, view(state, el, idx))\n return execStep(inner, ctx, el, idx)\n }),\n )\n settled.forEach((s, j) => {\n const idx = i + j\n results[idx] =\n s.status === \"fulfilled\"\n ? { status: \"fulfilled\", index: idx, value: s.value }\n : { status: \"rejected\", index: idx, item: chunk[j], error: errorMessage(s.reason) }\n })\n }\n if (!tolerant) return results\n const outcomes = results as FanOutOutcome[]\n return {\n results: outcomes,\n succeeded: outcomes.filter((r) => r.status === \"fulfilled\").length,\n failed: outcomes.filter((r) => r.status === \"rejected\").length,\n } satisfies TolerantFanOutResult\n }\n\n case \"pipeline\": {\n const items = [...step.over(b)]\n const tolerant = step.onError === \"collect\"\n if (items.length === 0) return tolerant ? { results: [], succeeded: 0, failed: 0 } : []\n const cap = Math.max(1, step.concurrency ?? items.length)\n const results: unknown[] = new Array(items.length)\n let next = 0\n const runItem = async (idx: number): Promise<void> => {\n let prev: unknown = undefined\n try {\n for (const stage of step.stages) {\n prev = await execStep(stage(items[idx], idx, prev, view(state, items[idx], idx)), ctx, items[idx], idx)\n }\n results[idx] = tolerant ? { status: \"fulfilled\", index: idx, value: prev } : prev\n } catch (err) {\n if (!tolerant) throw err\n results[idx] = { status: \"rejected\", index: idx, item: items[idx], error: errorMessage(err) }\n }\n }\n const worker = async (): Promise<void> => {\n while (next < items.length) {\n const idx = next++\n await runItem(idx)\n }\n }\n await Promise.all(Array.from({ length: Math.min(cap, items.length) }, () => worker()))\n if (!tolerant) return results\n const outcomes = results as FanOutOutcome[]\n return {\n results: outcomes,\n succeeded: outcomes.filter((r) => r.status === \"fulfilled\").length,\n failed: outcomes.filter((r) => r.status === \"rejected\").length,\n } satisfies TolerantFanOutResult\n }\n\n case \"branch\": {\n const chosen = step.cond(b) ? step.then : (step.otherwise ?? [])\n return runSequence(chosen, ctx, item, index)\n }\n\n case \"loop\": {\n let iterations = 0\n let last: unknown\n while (\n iterations < step.maxIterations &&\n step.while(view(state, item, index))\n ) {\n last = await runSequence(step.body, ctx, item, index)\n iterations++\n }\n return last\n }\n\n case \"parallel\": {\n const outs = await Promise.all(\n step.branches.map((br) =>\n runSequence(br.steps, ctx, item, index).then((last) => ({\n id: br.id,\n last,\n })),\n ),\n )\n const record: Record<string, unknown> = {}\n for (const { id, last } of outs) record[id] = last\n return record\n }\n\n case \"approval\": {\n const prompt = step.prompt(b)\n const approvers = step.approvers ?? []\n const approved = ctx.approve\n ? await ctx.approve({ stepId: step.id, prompt, approvers })\n : true\n const followups = approved\n ? (step.onApprove ?? [])\n : (step.onReject ?? [])\n await runSequence(followups, ctx, item, index)\n return { approved }\n }\n\n case \"suspend\": {\n if (!ctx.resume) throw new WorkflowSuspendedError(step.id, step.on)\n return ctx.resume({ stepId: step.id, on: step.on })\n }\n\n case \"group\":\n return runSequence(step.steps, ctx, item, index)\n\n case \"subworkflow\": {\n const childInput = step.input ? step.input(b) : state.input\n const child = await runWorkflowInner(step.workflow, childInput, {\n approve: ctx.approve,\n resume: ctx.resume,\n signal,\n agents: ctx.agents,\n cwd: ctx.cwd,\n workspaceSlug: ctx.workspaceSlug,\n cache: ctx.cache,\n cacheKey: ctx.cacheKey,\n })\n return child.output\n }\n\n case \"agent\": {\n if (!ctx.agents) throw new Error(`step '${step.id}': AgentStep requires a host agents implementation`)\n if (!isCacheEnabled(ctx, step)) return execAgentStep(step, ctx, b)\n const resolved = {\n prompt: step.prompt(b),\n adapter: step.adapter ? resolveSel(step.adapter, b) : undefined,\n sessionRef: step.sessionRef,\n }\n const c = await readStepCache(ctx, step, resolved)\n if (c.hit) return c.output // cache hit ⇒ NO spawn, NO budget spend\n const out = await execAgentStep(step, ctx, b)\n await ctx.cache!.set(c.key, { output: out, resolvedInputHash: c.hash })\n return out\n }\n }\n}\n\nasync function runWorkflowInner(\n workflow: RuntimeWorkflow,\n input: unknown,\n hooks: Pick<RunCtx, \"approve\" | \"resume\" | \"signal\" | \"agents\" | \"cwd\" | \"workspaceSlug\" | \"cache\" | \"cacheKey\" | \"onStepStart\" | \"onStepComplete\">,\n maxTotalCostUsd?: number,\n): Promise<WorkflowRunResult> {\n const state: RunState = { input, steps: {}, costBySession: new Map(), maxTotalCostUsd }\n const ctx: RunCtx = { state, ...hooks }\n let lastId: string | undefined\n for (const step of workflow.steps) {\n const out = await execStep(step, ctx, undefined, undefined)\n state.steps[step.id] = out\n ctx.onStepComplete?.(step.id, out)\n lastId = step.id\n }\n const bindings = view(state)\n const output = workflow.output\n ? workflow.output(bindings)\n : lastId !== undefined\n ? state.steps[lastId]\n : undefined\n return { output, bindings }\n}\n\nexport async function runWorkflow(\n args: RunWorkflowArgs,\n): Promise<WorkflowRunResult> {\n return runWorkflowInner(args.workflow, args.input, {\n approve: args.approve,\n resume: args.resume,\n signal: args.signal,\n agents: args.agents,\n cwd: args.cwd,\n workspaceSlug: args.workspaceSlug,\n cache: args.cache,\n cacheKey: args.cacheKey,\n onStepStart: args.onStepStart,\n onStepComplete: args.onStepComplete,\n }, args.maxTotalCostUsd)\n}\n","/**\n * Shared `AgentStep` construction — the one place that applies AgentStep's\n * defaults (`policy` → `{ awaiting: \"fail\" }`, a literal `prompt` wrapped as\n * a `Selector`). Used by both `compileWorkflow`'s declarative `kind:\"agent\"`\n * step and `@agentproto/runtime`'s `translateStages` (the `workflow_start` /\n * `WorkflowRunner` path), so the two authoring surfaces stay byte-identical\n * instead of drifting apart.\n */\n\nimport type { AgentSandboxRef, AgentStep, Bindings, Selector } from \"./types.js\"\n\nexport interface AgentStepFields {\n /** A literal prompt string, or a per-run selector (declarative manifest\n * steps resolve `$steps.*` refs into one before calling this). */\n prompt: string | Selector<string>\n adapter?: string\n sessionRef?: string\n sandbox?: AgentSandboxRef\n cacheable?: boolean\n policy?: AgentStep[\"policy\"]\n outputSchema?: AgentStep[\"outputSchema\"]\n maxRetries?: number\n options?: Record<string, boolean | number | string>\n}\n\n/** Build a runtime {@link AgentStep} from field values, applying the same\n * defaults everywhere: `policy` defaults to `{ awaiting: \"fail\" }`. */\nexport function buildAgentStep(id: string, fields: AgentStepFields): AgentStep {\n const prompt = fields.prompt\n return {\n kind: \"agent\",\n id,\n ...(fields.adapter !== undefined ? { adapter: fields.adapter } : {}),\n ...(fields.sessionRef !== undefined ? { sessionRef: fields.sessionRef } : {}),\n ...(fields.sandbox !== undefined ? { sandbox: fields.sandbox } : {}),\n ...(fields.cacheable ? { cacheable: true } : {}),\n ...(fields.options !== undefined ? { options: fields.options } : {}),\n prompt: typeof prompt === \"function\" ? prompt : ((_b: Bindings) => prompt),\n policy: fields.policy ?? { awaiting: \"fail\" as const },\n ...(fields.outputSchema !== undefined ? { outputSchema: fields.outputSchema } : {}),\n ...(fields.maxRetries !== undefined ? { maxRetries: fields.maxRetries } : {}),\n }\n}\n","/**\n * Compile a declarative AIP-15 `WorkflowHandle` into a runnable\n * {@link RuntimeWorkflow} for {@link runWorkflow}. This is the bridge that makes\n * an authored WORKFLOW.md actually execute.\n *\n * AIP-15 leaves the IO seam (`step.inputs`, `map.over`, `loop.while`) to a\n * meta-validator. This compiler pins a concrete, minimal **reference grammar**\n * for it — the convention a manifest author writes:\n *\n * - data refs: `$input` · `$input.a.b` · `$steps.<id>` · `$steps.<id>.a`\n * · `$item` · `$item.a` · `$index` (`$$` escapes a literal `$`)\n * - `step.inputs`: a JSON object whose leaf strings may be refs (resolved\n * recursively); non-`$` strings are literals\n * - `map.over`: a ref to an array\n * - `loop.while` / approval prompt: `<ref> <op> <literal>` (`== != < <= > >=`)\n * or a bare ref (truthiness)\n *\n * Scope: the **linear / structured subset** of AIP-15 — steps run in document\n * order; `map`/`loop`/`parallel` nest their child step lists. Non-linear `next`\n * gotos are rejected with a clear diagnostic. `kind:\"branch\"` compiles in its\n * **forward-only** form: every `branches[].next`/`default` must name a later\n * sibling in the SAME step list (not backward, not into a nested map/loop/\n * parallel body) — see `compileBranchChain` below. Compiling a full goto graph\n * (backward jumps, cross-scope targets) is a separable follow-up; hand-author\n * a `loop` step for retry-style control flow instead.\n */\n\nimport type { WorkflowHandle } from \"@agentproto/workflow\"\nimport type { DriverHandle } from \"@agentproto/driver\"\nimport type { ToolHandle } from \"@agentproto/tool\"\nimport type { AgentRefResolution, AgentStep, Bindings, RunStep, RuntimeWorkflow } from \"./types.js\"\nimport { buildAgentStep } from \"./build-agent-step.js\"\n\nexport interface CompileWorkflowOptions {\n /** TOOL contracts by id — each `tool` step resolves its handle here. */\n tools: ReadonlyMap<string, ToolHandle> | Record<string, ToolHandle>\n /** DRIVER candidates the resolver dispatches over for every tool step. */\n candidates: readonly DriverHandle[]\n /** Resolve a tool step's injected context (live capabilities) from bindings. */\n contextFor?: (toolId: string, bindings: Bindings) => unknown\n /** Sub-workflows by id, for `subworkflow` steps. */\n workflows?:\n | ReadonlyMap<string, WorkflowHandle>\n | Record<string, WorkflowHandle>\n /** App-scoped agent ids for a declarative `kind:\"agent\"` step's\n * `agent.ref` — e.g. `{ \"@app/reviewer\": { adapter: \"mastra-agent\",\n * options: { agent: \"<dir>/.agentproto/agents/reviewer/AGENT.md\" } } }`.\n * Built by the host from its own app-install state (see\n * `@agentproto/runtime`'s `resolveAgentRefsForWorkflow`). A step using\n * `agent.ref` with this unset, or naming a ref this map doesn't have,\n * fails compilation — never the runtime. */\n agentRefs?: ReadonlyMap<string, AgentRefResolution> | Record<string, AgentRefResolution>\n}\n\nexport class WorkflowCompileError extends Error {\n constructor(message: string) {\n super(`compileWorkflow: ${message}`)\n this.name = \"WorkflowCompileError\"\n }\n}\n\n// ── reference + predicate resolution (the AIP-16 IO seam) ────────────\n\nconst get = <T>(\n m: ReadonlyMap<string, T> | Record<string, T>,\n key: string,\n): T | undefined =>\n m instanceof Map ? m.get(key) : (m as Record<string, T>)[key]\n\nfunction dig(value: unknown, path: readonly string[]): unknown {\n let v = value\n for (const seg of path) {\n if (v == null) return undefined\n v = (v as Record<string, unknown>)[seg]\n }\n return v\n}\n\n/** Resolve a single `$…` reference string against the run bindings. */\nexport function resolveRef(ref: string, b: Bindings): unknown {\n if (ref === \"$index\") return b.index\n const m = ref.match(/^\\$(input|item|steps)((?:\\.[^.]+)*)$/)\n if (!m) throw new WorkflowCompileError(`bad reference '${ref}'`)\n const segs = m[2] ? m[2].slice(1).split(\".\") : []\n switch (m[1]) {\n case \"input\":\n return dig(b.input, segs)\n case \"item\":\n return dig(b.item, segs)\n case \"steps\": {\n const [stepId, ...rest] = segs\n if (!stepId) throw new WorkflowCompileError(`'$steps' needs a step id`)\n return dig(b.steps[stepId], rest)\n }\n }\n}\n\n/** Recursively resolve a value node: refs in strings, into arrays/objects. */\nexport function resolveValue(node: unknown, b: Bindings): unknown {\n if (typeof node === \"string\") {\n if (node.startsWith(\"$$\")) return node.slice(1) // $$ → literal $\n if (node.startsWith(\"$\")) return resolveRef(node, b)\n return node\n }\n if (Array.isArray(node)) return node.map((n) => resolveValue(n, b))\n if (node && typeof node === \"object\") {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(node as Record<string, unknown>))\n out[k] = resolveValue(v, b)\n return out\n }\n return node\n}\n\nconst COMPARATORS: Record<string, (a: number, b: number) => boolean> = {\n \"<\": (a, c) => a < c,\n \"<=\": (a, c) => a <= c,\n \">\": (a, c) => a > c,\n \">=\": (a, c) => a >= c,\n}\n\nfunction literal(token: string, b: Bindings): unknown {\n if (token.startsWith(\"$\")) return resolveRef(token, b)\n if (token === \"true\") return true\n if (token === \"false\") return false\n if (token === \"null\") return null\n if (/^-?\\d+(\\.\\d+)?$/.test(token)) return Number(token)\n return token.replace(/^['\"]|['\"]$/g, \"\")\n}\n\n/** Evaluate a `while`/`when` predicate string against the bindings. */\nexport function evalPredicate(expr: string, b: Bindings): boolean {\n const m = expr.match(/^(.+?)\\s*(==|!=|<=|>=|<|>)\\s*(.+)$/)\n if (!m) return Boolean(literal(expr.trim(), b)) // bare ref → truthiness\n const left = literal(m[1]!.trim(), b)\n const right = literal(m[3]!.trim(), b)\n switch (m[2]) {\n case \"==\":\n return left === right\n case \"!=\":\n return left !== right\n default: {\n const cmp = COMPARATORS[m[2]!]!\n return cmp(Number(left), Number(right))\n }\n }\n}\n\n// ── step compilation ─────────────────────────────────────────────────\n\n/** AIP step ids may be paths/refs; the runtime key is the last segment. */\nfunction normalizeToolId(ref: string): string {\n let s = ref.trim()\n if (s.endsWith(\"/TOOL.md\")) s = s.slice(0, -\"/TOOL.md\".length)\n const slash = s.lastIndexOf(\"/\")\n return slash === -1 ? s : s.slice(slash + 1)\n}\n\n// AIP step frontmatter leaves IO fields as opaque `{}`; read them dynamically.\nconst f = <T>(step: object, key: string): T =>\n (step as Record<string, unknown>)[key] as T\n\nfunction assertLinear(steps: readonly { id: string; kind: string; next?: string }[]): void {\n steps.forEach((s, i) => {\n const next = (s as { next?: string }).next\n const followingId = steps[i + 1]?.id\n if (next && next !== followingId) {\n throw new WorkflowCompileError(\n `step '${s.id}' has a non-linear next='${next}' — the structured-subset ` +\n `compiler only runs steps in document order. Hand-author a BranchStep ` +\n `or nest structurally.`,\n )\n }\n })\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction collectStepIds(steps: any[], ids: Set<string> = new Set()): Set<string> {\n for (const s of steps) {\n if (typeof s?.id === \"string\") ids.add(s.id)\n if (Array.isArray(s?.steps)) collectStepIds(s.steps, ids)\n if (Array.isArray(s?.branches)) {\n for (const br of s.branches) {\n if (Array.isArray(br?.steps)) collectStepIds(br.steps, ids)\n }\n }\n }\n return ids\n}\n\n/** Statically reject a `$steps.<id>` reference to a step id that doesn't\n * exist anywhere in this workflow — the same typo class an unresolved\n * reference would otherwise silently pass through as `undefined` at\n * runtime. */\nfunction assertKnownStepRefs(node: unknown, knownStepIds: ReadonlySet<string>, label: string): void {\n if (typeof node === \"string\") {\n if (node.startsWith(\"$$\")) return\n const m = node.match(/^\\$steps\\.([^.]+)/)\n if (m && !knownStepIds.has(m[1]!)) {\n throw new WorkflowCompileError(\n `${label} references unknown step '${m[1]}' via '${node}' — no step with that id exists in this workflow`,\n )\n }\n return\n }\n if (Array.isArray(node)) {\n node.forEach((n) => assertKnownStepRefs(n, knownStepIds, label))\n return\n }\n if (node && typeof node === \"object\") {\n for (const v of Object.values(node as Record<string, unknown>)) assertKnownStepRefs(v, knownStepIds, label)\n }\n}\n\n/** Per-compile context: the public options plus the full set of step ids\n * declared anywhere in THIS workflow (recomputed fresh for each nested\n * `subworkflow` child, which has its own id namespace). */\ninterface Ctx {\n opts: CompileWorkflowOptions\n knownStepIds: ReadonlySet<string>\n}\n\nexport function compileWorkflow(\n handle: WorkflowHandle,\n opts: CompileWorkflowOptions,\n): RuntimeWorkflow {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const steps = handle.steps as unknown as any[]\n if (handle.start && handle.start !== steps[0]?.id) {\n throw new WorkflowCompileError(\n `start='${handle.start}' is not the first step — structured-subset runs in order`,\n )\n }\n const ctx: Ctx = { opts, knownStepIds: collectStepIds(steps) }\n // `result` is the optional output value-expression (AIP-15): map it through\n // the same ref grammar as a step's inputs. Absent ⇒ no output selector, so\n // runWorkflow falls back to the final step's result.\n const result = (handle as { result?: unknown }).result\n const output =\n result !== undefined ? (b: Bindings) => resolveValue(result, b) : undefined\n return {\n id: handle.id,\n description: handle.description,\n steps: compileSiblingsToSteps(steps, ctx),\n ...(output ? { output } : {}),\n }\n}\n\n/**\n * Compile a sibling step list in document order. A `kind:\"branch\"` step\n * swallows every sibling after it at this level (they're reachable only\n * through its arms — see {@link compileBranchChain}), so this stops emitting\n * as soon as it hits one.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileSiblingsToSteps(steps: any[], ctx: Ctx): RunStep[] {\n assertLinear(steps)\n const out: RunStep[] = []\n for (let i = 0; i < steps.length; i++) {\n const s = steps[i]\n if (s.kind === \"branch\") {\n out.push(compileBranchChain(steps, i, ctx))\n return out\n }\n out.push(compileStep(s, ctx))\n }\n return out\n}\n\nfunction compileStepList(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n steps: any[],\n id: string,\n ctx: Ctx,\n): RunStep {\n const compiled = compileSiblingsToSteps(steps, ctx)\n if (compiled.length === 1) return compiled[0]!\n return { kind: \"group\", id, steps: compiled }\n}\n\n/**\n * Compile a forward-only goto `kind:\"branch\"` step (index `i` in `steps`)\n * into a nested runtime {@link BranchStep} chain: `branches[]` evaluate in\n * order, the first truthy `when` jumps to its `next` sibling and falls\n * through in document order from there; no match jumps to `default` (or\n * falls through to `i + 1`). Every target MUST be a later sibling in this\n * SAME list — an unknown id, a backward target, or a target inside a nested\n * map/loop/parallel body all fail compilation here.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileBranchChain(steps: any[], i: number, ctx: Ctx): RunStep {\n const branchStep = steps[i]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const branches = f<{ when: string; next: string }[]>(branchStep, \"branches\")\n const defaultTarget = f<string | undefined>(branchStep, \"default\")\n\n const resolveTarget = (targetId: string, label: string): number => {\n const idx = steps.findIndex((s) => s.id === targetId)\n if (idx === -1 || idx <= i) {\n throw new WorkflowCompileError(\n `branch '${branchStep.id}' ${label} targets '${targetId}', which is not a sibling later in this ` +\n `step list — the forward-only branch compiler only supports jumping to a later sibling in the ` +\n `SAME list (not backward, and not into a nested map/loop/parallel body). Hand-author a 'loop' ` +\n `step for retry-style control flow instead.`,\n )\n }\n return idx\n }\n\n const defaultIdx = defaultTarget !== undefined ? resolveTarget(defaultTarget, \"default\") : i + 1\n let otherwise: RunStep[] = compileSiblingsToSteps(steps.slice(defaultIdx), ctx)\n\n for (let k = branches.length - 1; k >= 0; k--) {\n const br = branches[k]!\n const targetIdx = resolveTarget(br.next, `branches[${k}].next`)\n const thenSteps = compileSiblingsToSteps(steps.slice(targetIdx), ctx)\n const condExpr = br.when\n const nodeId = k === 0 ? branchStep.id : `${branchStep.id}__branch${k}`\n otherwise = [\n {\n kind: \"branch\",\n id: nodeId,\n cond: (b: Bindings) => evalPredicate(condExpr, b),\n then: thenSteps,\n ...(otherwise.length > 0 ? { otherwise } : {}),\n },\n ]\n }\n return otherwise[0]!\n}\n\n/**\n * Compile a declarative `kind:\"agent\"` manifest step — `{ agent: { ref },\n * prompt, adapter?, sessionRef?, sandbox?, cacheable?, policy?, outputSchema?,\n * maxRetries? }` — into a real {@link AgentStep}. `prompt` runs through the\n * same `$input`/`$steps.<id>` ref grammar as a `tool` step's `inputs`.\n * `agent.ref` resolves via `opts.agentRefs` — unresolvable (no map, or an id\n * the map doesn't have) fails HERE, at compile time, never at the runtime\n * spawn.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileAgentStep(step: any, id: string, ctx: Ctx): AgentStep {\n const opts = ctx.opts\n const prompt = f<string>(step, \"prompt\")\n if (typeof prompt !== \"string\" || prompt.length === 0) {\n throw new WorkflowCompileError(`agent step '${id}' needs a non-empty 'prompt'`)\n }\n\n let adapter: string | undefined = typeof step.adapter === \"string\" ? step.adapter : undefined\n let options: Record<string, boolean | number | string> | undefined =\n step.options !== undefined ? step.options : undefined\n\n const agentRef: unknown = step.agent?.ref\n if (agentRef !== undefined) {\n if (typeof agentRef !== \"string\" || agentRef.trim().length === 0) {\n throw new WorkflowCompileError(`agent step '${id}' has an empty 'agent.ref'`)\n }\n const resolved = opts.agentRefs ? get(opts.agentRefs, agentRef) : undefined\n if (!resolved) {\n const available = opts.agentRefs\n ? opts.agentRefs instanceof Map\n ? [...opts.agentRefs.keys()]\n : Object.keys(opts.agentRefs)\n : []\n throw new WorkflowCompileError(\n `agent step '${id}' references unknown agent ref '${agentRef}'` +\n (available.length > 0\n ? ` — available refs: ${available.join(\", \")}`\n : \" — no agent refs are configured for this compile (not running in an app context?)\"),\n )\n }\n adapter = resolved.adapter\n options = resolved.options\n }\n\n return buildAgentStep(id, {\n prompt: (b: Bindings) => String(resolveValue(prompt, b)),\n ...(adapter !== undefined ? { adapter } : {}),\n ...(step.sessionRef !== undefined ? { sessionRef: step.sessionRef } : {}),\n ...(step.sandbox !== undefined ? { sandbox: step.sandbox } : {}),\n ...(step.cacheable ? { cacheable: true } : {}),\n ...(options !== undefined ? { options } : {}),\n policy: step.policy,\n ...(step.outputSchema !== undefined ? { outputSchema: step.outputSchema } : {}),\n ...(step.maxRetries !== undefined ? { maxRetries: step.maxRetries } : {}),\n })\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileStep(step: any, ctx: Ctx): RunStep {\n const opts = ctx.opts\n const id: string = step.id\n switch (step.kind) {\n case \"tool\": {\n const ref = typeof step.tool === \"string\" ? step.tool : step.tool.entry\n const toolId = normalizeToolId(ref)\n const tool = get(opts.tools, toolId)\n if (!tool)\n throw new WorkflowCompileError(`no tool registered for '${toolId}'`)\n const inputs = f<unknown>(step, \"inputs\") ?? {}\n assertKnownStepRefs(inputs, ctx.knownStepIds, `tool step '${id}' inputs`)\n return {\n kind: \"tool\",\n id,\n tool,\n candidates: opts.candidates,\n input: (b) => resolveValue(inputs, b),\n context: opts.contextFor\n ? (b) => opts.contextFor!(toolId, b)\n : undefined,\n }\n }\n\n case \"map\": {\n const over = f<string>(step, \"over\")\n const inner = compileStepList(f(step, \"steps\"), `${id}__body`, ctx)\n const onError = f<\"throw\" | \"collect\" | undefined>(step, \"onError\")\n return {\n kind: \"map\",\n id,\n parallelism: f<number | undefined>(step, \"parallelism\"),\n over: (b) => resolveRef(over, b) as readonly unknown[],\n body: () => inner,\n ...(onError !== undefined ? { onError } : {}),\n }\n }\n\n case \"loop\": {\n const whileExpr = f<string>(step, \"while\")\n return {\n kind: \"loop\",\n id,\n maxIterations: f<number>(step, \"max_iterations\"),\n while: (b) => evalPredicate(whileExpr, b),\n body: [compileStepList(f(step, \"steps\"), `${id}__body`, ctx)],\n }\n }\n\n case \"parallel\": {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const branches = f<any[]>(step, \"branches\")\n return {\n kind: \"parallel\",\n id,\n branches: branches.map((br) => ({\n id: br.id,\n steps: [compileStepList(br.steps, `${id}__${br.id}`, ctx)],\n })),\n }\n }\n\n case \"approval\": {\n const prompt = f<string>(step, \"prompt\")\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const approvers = (f<any[]>(step, \"approvers\") ?? []).map(\n (a) => a.role ?? a.userId ?? String(a),\n )\n return {\n kind: \"approval\",\n id,\n approvers,\n prompt: (b) => String(resolveValue(prompt, b)),\n }\n }\n\n case \"suspend\": {\n const resume = f<{ on: string[]; timeout_ms?: number }>(step, \"resume\")\n return { kind: \"suspend\", id, on: resume.on, timeoutMs: resume.timeout_ms }\n }\n\n case \"subworkflow\": {\n const wfId = f<string>(step, \"workflow\")\n const child = opts.workflows ? get(opts.workflows, wfId) : undefined\n if (!child)\n throw new WorkflowCompileError(\n `subworkflow '${wfId}' not found — pass it in opts.workflows`,\n )\n const compiledChild = compileWorkflow(child, opts)\n // `inputs` is an optional projection into the child's `$input` — the\n // same ref grammar as a `tool` step's `inputs` (refs resolved against\n // THIS (parent) workflow's bindings). Absent ⇒ today's behavior: the\n // child runs with the parent's own workflow input, unchanged.\n const inputs = f<unknown>(step, \"inputs\")\n if (inputs === undefined) {\n return { kind: \"subworkflow\", id, workflow: compiledChild }\n }\n assertKnownStepRefs(inputs, ctx.knownStepIds, `subworkflow step '${id}' inputs`)\n return {\n kind: \"subworkflow\",\n id,\n workflow: compiledChild,\n input: (b) => resolveValue(inputs, b),\n }\n }\n\n case \"agent\": {\n // Two shapes reach here under the same `kind:\"agent\"`: an ENTRY-based\n // handle's already-built runtime AgentStep (function-valued `prompt`\n // selector — nothing declarative left to resolve, pass through\n // unchanged), or a purely-declarative manifest step (`prompt` is a\n // plain string) that this compiler must turn into a real AgentStep,\n // the same way `translateStages` does for `workflow_start`.\n if (typeof step.prompt === \"function\") {\n const passthrough: RunStep = step\n return passthrough\n }\n return compileAgentStep(step, id, ctx)\n }\n\n case \"transform\": {\n // Not a declarative manifest kind — no string expression language for\n // `compute` — so it only reaches the compiler from an ENTRY-based\n // handle, already built as a runtime TransformStep (function-valued\n // `compute`). Passes through unchanged: this is what lets an entry.mjs\n // step shape/serialize an earlier tool step's output (e.g.\n // `JSON.stringify` a prior `$steps.<id>` value) for a later tool step\n // to consume as a plain string input, something the `$steps.*` ref\n // grammar alone can't do. `step` is `any`, so no cast is needed.\n const passthrough: RunStep = step\n return passthrough\n }\n\n case \"branch\":\n // Unreachable through the normal entry points: `compileSiblingsToSteps`\n // intercepts every `branch` step and routes it to `compileBranchChain`\n // before it would ever reach here (that's what makes the forward-only\n // swallow-the-rest-of-the-list semantics work). A direct call would be\n // an internal invariant violation, not a manifest problem.\n throw new WorkflowCompileError(\n `internal: branch step '${id}' reached compileStep directly — branch ` +\n `steps must be compiled via the sibling-list walker`,\n )\n\n default:\n throw new WorkflowCompileError(\n `unsupported step kind '${step.kind}' (step '${id}')`,\n )\n }\n}\n","/**\n * compileWorkflowManifest — the connective step between an authored\n * `WORKFLOW.md` and a runnable workflow.\n *\n * AIP-15 ships every piece needed to run a declarative manifest except the\n * seam that joins them: `parseWorkflowManifest` (md + frontmatter → manifest)\n * and `workflowFromManifest` (manifest → `WorkflowHandle`) live in\n * `@agentproto/workflow`; `compileWorkflow` (handle → `RuntimeWorkflow`) lives\n * here. Without this chain an authored `WORKFLOW.md` parses and validates but\n * never reaches the executor. This joins the three so a manifest source string\n * compiles straight to a runnable workflow — no hand-built handle.\n *\n * Framework-pure: the caller owns reading the file off disk (this package does\n * no I/O), and passes the source string in. The tool registry + driver\n * candidates are injected via {@link CompileWorkflowOptions}, same as the\n * hand-built path.\n */\n\nimport {\n parseWorkflowManifest,\n workflowFromManifest,\n} from \"@agentproto/workflow/manifest\"\n\nimport { compileWorkflow } from \"./compile-workflow.js\"\nimport type { CompileWorkflowOptions } from \"./compile-workflow.js\"\nimport type { RuntimeWorkflow } from \"./types.js\"\n\n/**\n * Compile a `WORKFLOW.md` source string into a {@link RuntimeWorkflow} ready\n * for `runWorkflow`. Parses + validates the frontmatter against the AIP-15\n * schema, lifts it to a `WorkflowHandle`, then compiles its step graph against\n * the injected tool registry. Throws on invalid frontmatter (the parser's\n * diagnostic) or an unresolved tool / non-linear step (the compiler's).\n */\nexport function compileWorkflowManifest(\n source: string,\n opts: CompileWorkflowOptions,\n): RuntimeWorkflow {\n const manifest = parseWorkflowManifest(source)\n const handle = workflowFromManifest(manifest)\n return compileWorkflow(handle, opts)\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentproto/workflow-runtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Reference step-walker for AIP-15 WORKFLOW composition: executes a typed step graph (tool / map / branch / loop / transform) over @agentproto/driver runTool, threading each step's output into a run-scoped binding bag (the AIP-16 IO seam, expressed as typed selectors). The missing executor that makes 'composition = config' runnable.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentproto",
|
|
@@ -39,16 +39,16 @@
|
|
|
39
39
|
"access": "public"
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@agentproto/driver": "0.2.
|
|
43
|
-
"@agentproto/tool": "0.2.
|
|
44
|
-
"@agentproto/workflow": "0.
|
|
42
|
+
"@agentproto/driver": "0.2.1",
|
|
43
|
+
"@agentproto/tool": "0.2.2",
|
|
44
|
+
"@agentproto/workflow": "0.3.1"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@types/node": "^25.6.2",
|
|
48
48
|
"tsup": "^8.5.1",
|
|
49
49
|
"typescript": "^5.9.3",
|
|
50
50
|
"vitest": "^3.2.4",
|
|
51
|
-
"zod": "^4.4
|
|
51
|
+
"zod": "^4.5.4",
|
|
52
52
|
"@agentproto/tooling": "0.1.0-alpha.0"
|
|
53
53
|
},
|
|
54
54
|
"scripts": {
|