@agentproto/workflow-runtime 0.5.0 → 0.7.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/dist/index.d.ts CHANGED
@@ -236,6 +236,22 @@ interface AgentStep {
236
236
  * adapter + sessionRef are hashed. Default false — most agent steps have
237
237
  * side effects. */
238
238
  cacheable?: boolean;
239
+ /** Manifest-declared adapter option id → value, forwarded to a NEW spawn's
240
+ * `startSession({ options })` — e.g. mastra-agent's `agent` option, set by
241
+ * {@link CompileWorkflowOptions.agentRefs} resolution when this step's
242
+ * declarative `agent.ref` names an app-scoped agent. Only meaningful with
243
+ * `adapter`; ignored on a `sessionRef` reuse. */
244
+ options?: Record<string, boolean | number | string>;
245
+ }
246
+ /** What a declarative agent-step's `agent.ref` resolves to — the adapter to
247
+ * spawn under plus any adapter options that pick which concrete agent runs
248
+ * (e.g. mastra-agent's `agent` option, an emitted AGENT.md path). Built by
249
+ * the host from its own app-install state; the compiler only consumes it. */
250
+ interface AgentRefResolution {
251
+ /** Adapter slug to spawn (e.g. "mastra-agent"). */
252
+ adapter: string;
253
+ /** Adapter option id → value merged onto the compiled step's `options`. */
254
+ options?: Record<string, boolean | number | string>;
239
255
  }
240
256
  /**
241
257
  * The element generics on `ToolStep` are erased to `any` so heterogeneous
@@ -273,6 +289,8 @@ interface AgentSessionHost {
273
289
  workspaceSlug?: string;
274
290
  stepId?: string;
275
291
  sandbox?: AgentSandboxRef;
292
+ /** Adapter option id → value for this spawn (see {@link AgentStep.options}). */
293
+ options?: Record<string, boolean | number | string>;
276
294
  }): Promise<string>;
277
295
  /** Send a prompt to an existing session and wait for its turn to end. */
278
296
  sendPromptAndWait(sessionId: string, prompt: string): Promise<void>;
@@ -319,6 +337,10 @@ interface RunWorkflowArgs {
319
337
  /** Namespacing label for this run's cache lookups (the workflow_start cacheKey).
320
338
  * Both `cache` and `cacheKey` must be set for any caching to happen. */
321
339
  cacheKey?: string;
340
+ /** Called when a step begins execution (before spawn/prompt). */
341
+ onStepStart?: (stepId: string) => void;
342
+ /** Called when a step completes execution, with its output. */
343
+ onStepComplete?: (stepId: string, output: unknown) => void;
322
344
  }
323
345
  interface WorkflowRunResult {
324
346
  output: unknown;
@@ -375,6 +397,14 @@ interface CompileWorkflowOptions {
375
397
  contextFor?: (toolId: string, bindings: Bindings) => unknown;
376
398
  /** Sub-workflows by id, for `subworkflow` steps. */
377
399
  workflows?: ReadonlyMap<string, WorkflowHandle> | Record<string, WorkflowHandle>;
400
+ /** App-scoped agent ids for a declarative `kind:"agent"` step's
401
+ * `agent.ref` — e.g. `{ "@app/reviewer": { adapter: "mastra-agent",
402
+ * options: { agent: "<dir>/.agentproto/agents/reviewer/AGENT.md" } } }`.
403
+ * Built by the host from its own app-install state (see
404
+ * `@agentproto/runtime`'s `resolveAgentRefsForWorkflow`). A step using
405
+ * `agent.ref` with this unset, or naming a ref this map doesn't have,
406
+ * fails compilation — never the runtime. */
407
+ agentRefs?: ReadonlyMap<string, AgentRefResolution> | Record<string, AgentRefResolution>;
378
408
  }
379
409
  declare class WorkflowCompileError extends Error {
380
410
  constructor(message: string);
@@ -414,4 +444,30 @@ declare function compileWorkflow(handle: WorkflowHandle, opts: CompileWorkflowOp
414
444
  */
415
445
  declare function compileWorkflowManifest(source: string, opts: CompileWorkflowOptions): RuntimeWorkflow;
416
446
 
417
- export { type AgentSandboxRef, type AgentSessionHost, type AgentStep, type ApprovalRequest, type ApprovalStep, type Bindings, type BranchStep, type CompileWorkflowOptions, type FanOutOutcome, type GroupStep, type LoopStep, type MapStep, type ParallelStep, type PipelineStep, type ResumeRequest, type RunStep, type RunWorkflowArgs, type RuntimeWorkflow, type Selector, type StepCache, type StepCacheEntry, type SubworkflowStep, type SuspendStep, type TolerantFanOutResult, type ToolStep, type TransformStep, WorkflowCompileError, type WorkflowRunResult, WorkflowSuspendedError, compileWorkflow, compileWorkflowManifest, evalPredicate, resolveRef, resolveValue, runWorkflow };
447
+ /**
448
+ * Shared `AgentStep` construction — the one place that applies AgentStep's
449
+ * defaults (`policy` → `{ awaiting: "fail" }`, a literal `prompt` wrapped as
450
+ * a `Selector`). Used by both `compileWorkflow`'s declarative `kind:"agent"`
451
+ * step and `@agentproto/runtime`'s `translateStages` (the `workflow_start` /
452
+ * `WorkflowRunner` path), so the two authoring surfaces stay byte-identical
453
+ * instead of drifting apart.
454
+ */
455
+
456
+ interface AgentStepFields {
457
+ /** A literal prompt string, or a per-run selector (declarative manifest
458
+ * steps resolve `$steps.*` refs into one before calling this). */
459
+ prompt: string | Selector<string>;
460
+ adapter?: string;
461
+ sessionRef?: string;
462
+ sandbox?: AgentSandboxRef;
463
+ cacheable?: boolean;
464
+ policy?: AgentStep["policy"];
465
+ outputSchema?: AgentStep["outputSchema"];
466
+ maxRetries?: number;
467
+ options?: Record<string, boolean | number | string>;
468
+ }
469
+ /** Build a runtime {@link AgentStep} from field values, applying the same
470
+ * defaults everywhere: `policy` defaults to `{ awaiting: "fail" }`. */
471
+ declare function buildAgentStep(id: string, fields: AgentStepFields): AgentStep;
472
+
473
+ export { type AgentRefResolution, type AgentSandboxRef, type AgentSessionHost, type AgentStep, type AgentStepFields, type ApprovalRequest, type ApprovalStep, type Bindings, type BranchStep, type CompileWorkflowOptions, type FanOutOutcome, type GroupStep, type LoopStep, type MapStep, type ParallelStep, type PipelineStep, type ResumeRequest, type RunStep, type RunWorkflowArgs, type RuntimeWorkflow, type Selector, type StepCache, type StepCacheEntry, type SubworkflowStep, type SuspendStep, type TolerantFanOutResult, type ToolStep, type TransformStep, WorkflowCompileError, type WorkflowRunResult, WorkflowSuspendedError, buildAgentStep, compileWorkflow, compileWorkflowManifest, evalPredicate, resolveRef, resolveValue, runWorkflow };
package/dist/index.mjs CHANGED
@@ -74,11 +74,13 @@ async function runSequence(steps, ctx, item, index) {
74
74
  for (const s of steps) {
75
75
  const out = await execStep(s, ctx, item, index);
76
76
  ctx.state.steps[s.id] = out;
77
+ ctx.onStepComplete?.(s.id, out);
77
78
  last = out;
78
79
  }
79
80
  return last;
80
81
  }
81
82
  async function execAgentStep(step, ctx, b) {
83
+ ctx.onStepStart?.(step.id);
82
84
  if (step.adapter && ctx.state.maxTotalCostUsd !== void 0 && spentUsd(ctx.state) >= ctx.state.maxTotalCostUsd) {
83
85
  throw new Error(
84
86
  `step '${step.id}': budget_exceeded \u2014 run spend $${spentUsd(ctx.state).toFixed(4)} >= cap $${ctx.state.maxTotalCostUsd}`
@@ -90,7 +92,8 @@ async function execAgentStep(step, ctx, b) {
90
92
  cwd,
91
93
  workspaceSlug: ctx.workspaceSlug,
92
94
  stepId: step.id,
93
- ...sandbox !== void 0 ? { sandbox } : {}
95
+ ...sandbox !== void 0 ? { sandbox } : {},
96
+ ...step.options !== void 0 ? { options: step.options } : {}
94
97
  }) : ctx.agents.resolveByLabel(step.sessionRef);
95
98
  if (!sessionId) throw new Error(`step '${step.id}': no session (adapter and sessionRef both unresolved)`);
96
99
  await ctx.agents.sendPromptAndWait(sessionId, step.prompt(b));
@@ -100,7 +103,16 @@ async function execAgentStep(step, ctx, b) {
100
103
  if (ctx.agents.readCostUsd) {
101
104
  ctx.state.costBySession.set(sessionId, await ctx.agents.readCostUsd(sessionId));
102
105
  }
103
- if (!step.outputSchema) return { sessionId };
106
+ if (!step.outputSchema) {
107
+ let text;
108
+ if (ctx.agents.readFinalMessage) {
109
+ try {
110
+ text = await ctx.agents.readFinalMessage(sessionId);
111
+ } catch {
112
+ }
113
+ }
114
+ return { sessionId, ...text !== void 0 ? { text } : {} };
115
+ }
104
116
  if (!ctx.agents.readFinalMessage) {
105
117
  throw new Error(`step '${step.id}': outputSchema requires a host with readFinalMessage`);
106
118
  }
@@ -137,6 +149,9 @@ async function execAgentStep(step, ctx, b) {
137
149
  async function execStep(step, ctx, item, index) {
138
150
  const { state, signal } = ctx;
139
151
  const b = view(state, item, index);
152
+ if (step.kind !== "agent") {
153
+ ctx.onStepStart?.(step.id);
154
+ }
140
155
  switch (step.kind) {
141
156
  case "tool": {
142
157
  const input = step.input(b);
@@ -307,6 +322,7 @@ async function runWorkflowInner(workflow, input, hooks, maxTotalCostUsd) {
307
322
  for (const step of workflow.steps) {
308
323
  const out = await execStep(step, ctx, void 0, void 0);
309
324
  state.steps[step.id] = out;
325
+ ctx.onStepComplete?.(step.id, out);
310
326
  lastId = step.id;
311
327
  }
312
328
  const bindings = view(state);
@@ -322,10 +338,30 @@ async function runWorkflow(args) {
322
338
  cwd: args.cwd,
323
339
  workspaceSlug: args.workspaceSlug,
324
340
  cache: args.cache,
325
- cacheKey: args.cacheKey
341
+ cacheKey: args.cacheKey,
342
+ onStepStart: args.onStepStart,
343
+ onStepComplete: args.onStepComplete
326
344
  }, args.maxTotalCostUsd);
327
345
  }
328
346
 
347
+ // src/build-agent-step.ts
348
+ function buildAgentStep(id, fields) {
349
+ const prompt = fields.prompt;
350
+ return {
351
+ kind: "agent",
352
+ id,
353
+ ...fields.adapter !== void 0 ? { adapter: fields.adapter } : {},
354
+ ...fields.sessionRef !== void 0 ? { sessionRef: fields.sessionRef } : {},
355
+ ...fields.sandbox !== void 0 ? { sandbox: fields.sandbox } : {},
356
+ ...fields.cacheable ? { cacheable: true } : {},
357
+ ...fields.options !== void 0 ? { options: fields.options } : {},
358
+ prompt: typeof prompt === "function" ? prompt : ((_b) => prompt),
359
+ policy: fields.policy ?? { awaiting: "fail" },
360
+ ...fields.outputSchema !== void 0 ? { outputSchema: fields.outputSchema } : {},
361
+ ...fields.maxRetries !== void 0 ? { maxRetries: fields.maxRetries } : {}
362
+ };
363
+ }
364
+
329
365
  // src/compile-workflow.ts
330
366
  var WorkflowCompileError = class extends Error {
331
367
  constructor(message) {
@@ -444,6 +480,40 @@ function compileStepList(steps, id, opts) {
444
480
  if (steps.length === 1) return compileStep(steps[0], opts);
445
481
  return { kind: "group", id, steps: steps.map((s) => compileStep(s, opts)) };
446
482
  }
483
+ function compileAgentStep(step, id, opts) {
484
+ const prompt = f(step, "prompt");
485
+ if (typeof prompt !== "string" || prompt.length === 0) {
486
+ throw new WorkflowCompileError(`agent step '${id}' needs a non-empty 'prompt'`);
487
+ }
488
+ let adapter = typeof step.adapter === "string" ? step.adapter : void 0;
489
+ let options = step.options !== void 0 ? step.options : void 0;
490
+ const agentRef = step.agent?.ref;
491
+ if (agentRef !== void 0) {
492
+ if (typeof agentRef !== "string" || agentRef.trim().length === 0) {
493
+ throw new WorkflowCompileError(`agent step '${id}' has an empty 'agent.ref'`);
494
+ }
495
+ const resolved = opts.agentRefs ? get(opts.agentRefs, agentRef) : void 0;
496
+ if (!resolved) {
497
+ const available = opts.agentRefs ? opts.agentRefs instanceof Map ? [...opts.agentRefs.keys()] : Object.keys(opts.agentRefs) : [];
498
+ throw new WorkflowCompileError(
499
+ `agent step '${id}' references unknown agent ref '${agentRef}'` + (available.length > 0 ? ` \u2014 available refs: ${available.join(", ")}` : " \u2014 no agent refs are configured for this compile (not running in an app context?)")
500
+ );
501
+ }
502
+ adapter = resolved.adapter;
503
+ options = resolved.options;
504
+ }
505
+ return buildAgentStep(id, {
506
+ prompt: (b) => String(resolveValue(prompt, b)),
507
+ ...adapter !== void 0 ? { adapter } : {},
508
+ ...step.sessionRef !== void 0 ? { sessionRef: step.sessionRef } : {},
509
+ ...step.sandbox !== void 0 ? { sandbox: step.sandbox } : {},
510
+ ...step.cacheable ? { cacheable: true } : {},
511
+ ...options !== void 0 ? { options } : {},
512
+ policy: step.policy,
513
+ ...step.outputSchema !== void 0 ? { outputSchema: step.outputSchema } : {},
514
+ ...step.maxRetries !== void 0 ? { maxRetries: step.maxRetries } : {}
515
+ });
516
+ }
447
517
  function compileStep(step, opts) {
448
518
  const id = step.id;
449
519
  switch (step.kind) {
@@ -522,8 +592,15 @@ function compileStep(step, opts) {
522
592
  return { kind: "subworkflow", id, workflow: compiledChild };
523
593
  }
524
594
  case "agent": {
525
- const agent = step;
526
- return agent;
595
+ if (typeof step.prompt === "function") {
596
+ const passthrough = step;
597
+ return passthrough;
598
+ }
599
+ return compileAgentStep(step, id, opts);
600
+ }
601
+ case "transform": {
602
+ const passthrough = step;
603
+ return passthrough;
527
604
  }
528
605
  case "branch":
529
606
  throw new WorkflowCompileError(
@@ -541,6 +618,6 @@ function compileWorkflowManifest(source, opts) {
541
618
  return compileWorkflow(handle, opts);
542
619
  }
543
620
 
544
- export { WorkflowCompileError, WorkflowSuspendedError, compileWorkflow, compileWorkflowManifest, evalPredicate, resolveRef, resolveValue, runWorkflow };
621
+ export { WorkflowCompileError, WorkflowSuspendedError, buildAgentStep, compileWorkflow, compileWorkflowManifest, evalPredicate, resolveRef, resolveValue, runWorkflow };
545
622
  //# sourceMappingURL=index.mjs.map
546
623
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/run-workflow.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;AAwBA,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,CAAC,CAAA,GAAI,GAAA;AAC9C;AAMA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,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}\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 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 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 })\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) return { sessionId }\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 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\">,\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 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 }, args.maxTotalCostUsd)\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 { Bindings, RunStep, RuntimeWorkflow } from \"./types.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}\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// 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 // `agent` is not a declarative manifest kind — it only reaches the\n // compiler from an ENTRY-based handle, where it is already a runtime\n // AgentStep (function-valued adapter/cwd/prompt selectors). There is\n // nothing declarative to resolve, so pass it through unchanged. This is\n // what lets a WORKFLOW.md whose entry.mjs is a chain of agent steps run\n // via startFromFile. `step` is `any`, so no cast is needed.\n const agent: RunStep = step\n return agent\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,CAAC,CAAA,GAAI,GAAA;AAC9C;AAMA,SAAS,qBAAqB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,IAAI,OAAO,IAAA,CAAK,MAAA,KAAW,UAAA,EAAY;AACrC,QAAA,MAAM,WAAA,GAAuB,IAAA;AAC7B,QAAA,OAAO,WAAA;AAAA,MACT;AACA,MAAA,OAAO,gBAAA,CAAiB,IAAA,EAAM,EAAA,EAAI,IAAI,CAAA;AAAA,IACxC;AAAA,IAEA,KAAK,WAAA,EAAa;AAShB,MAAA,MAAM,WAAA,GAAuB,IAAA;AAC7B,MAAA,OAAO,WAAA;AAAA,IACT;AAAA,IAEA,KAAK,QAAA;AACH,MAAA,MAAM,IAAI,oBAAA;AAAA,QACR,8BAA8B,EAAE,CAAA,+FAAA;AAAA,OAElC;AAAA,IAEF;AACE,MAAA,MAAM,IAAI,oBAAA;AAAA,QACR,CAAA,uBAAA,EAA0B,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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentproto/workflow-runtime",
3
- "version": "0.5.0",
3
+ "version": "0.7.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,9 +39,9 @@
39
39
  "access": "public"
40
40
  },
41
41
  "dependencies": {
42
- "@agentproto/driver": "0.1.3",
42
+ "@agentproto/driver": "0.2.0",
43
43
  "@agentproto/tool": "0.2.1",
44
- "@agentproto/workflow": "0.1.0"
44
+ "@agentproto/workflow": "0.2.0"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@types/node": "^25.6.2",