@agentproto/workflow-runtime 0.3.0 → 0.5.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/LICENSE CHANGED
@@ -1,21 +1,202 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Jeremy André and agentproto contributors
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -63,8 +63,8 @@ and binds its output under `id`.
63
63
  | `tool` | Resolve a TOOL contract against `candidates` and run it. Cacheable. |
64
64
  | `agent` | Spawn/reuse an agent session, send a prompt, wait for the turn. Cacheable. |
65
65
  | `transform` | Pure in-run compute — combine / filter / shape. No dispatch. |
66
- | `map` | Run a body once per array element (`bindings.item` / `index`); collect outputs. |
67
- | `pipeline` | Run N items through K sequential stages with **no cross-item barrier**. |
66
+ | `map` | Run a body once per array element (`bindings.item` / `index`); collect outputs. Fail-fast by default; `onError: "collect"` opts into per-item tolerance. |
67
+ | `pipeline` | Run N items through K sequential stages with **no cross-item barrier**. Same `onError: "collect"` opt-in as `map`. |
68
68
  | `parallel` | Run several named branches concurrently; outputs bind by branch id. |
69
69
  | `branch` | Pick `then` / `otherwise` from a boolean predicate. |
70
70
  | `loop` | Repeat a body while a predicate holds, up to `maxIterations`. |
@@ -158,6 +158,45 @@ is the previous stage's output **for that item** (undefined at stage 0). Use a
158
158
  `parallel` step instead only when a later stage genuinely needs *all* prior
159
159
  results at once (a barrier).
160
160
 
161
+ ### Per-item failure tolerance (`map` / `pipeline`)
162
+
163
+ By default, `map` and `pipeline` are **fail-fast**: the first item whose body
164
+ (or chain, for `pipeline`) throws aborts the whole step, and every other
165
+ in-flight item's result is discarded. That's correct when any failure should
166
+ halt the run — but wrong when failure is an expected per-item outcome (an
167
+ expired listing, a 404, a flaky endpoint) and the other N-1 items are still
168
+ useful output.
169
+
170
+ Set `onError: "collect"` to run every item to completion instead. The step's
171
+ bound output changes shape from a bare array to a `TolerantFanOutResult`:
172
+
173
+ ```ts
174
+ {
175
+ kind: "map", // or "pipeline"
176
+ id: "details",
177
+ over: (b) => b.input as string[],
178
+ onError: "collect",
179
+ body: (url) => ({ kind: "tool", id: "fetch", tool: fetchDetail, candidates,
180
+ input: () => ({ url }) }),
181
+ }
182
+ // → {
183
+ // results: [
184
+ // { status: "fulfilled", index: 0, value: {...} },
185
+ // { status: "rejected", index: 1, item: "https://…/410", error: "expired" },
186
+ // { status: "fulfilled", index: 2, value: {...} },
187
+ // ],
188
+ // succeeded: 2,
189
+ // failed: 1,
190
+ // }
191
+ ```
192
+
193
+ `succeeded` + `failed` answer "how many items failed" without scanning
194
+ `results`; each rejected entry carries the offending `item` and `error.message`
195
+ (or `String(reason)` for a non-`Error` throw) so a caller can answer "why"
196
+ without having watched the run. The default (`onError` omitted, or explicitly
197
+ `"throw"`) is byte-for-byte the old behavior — this is opt-in, not a breaking
198
+ change to existing workflows.
199
+
161
200
  ### Resume cache (journaled replay)
162
201
 
163
202
  Mark an idempotent `tool` or `agent` step `cacheable: true`, pass a `cache` and
package/dist/index.d.ts CHANGED
@@ -51,6 +51,32 @@ interface TransformStep {
51
51
  id: string;
52
52
  compute: Selector<unknown>;
53
53
  }
54
+ /**
55
+ * One item's outcome inside a `map`/`pipeline` run with `onError: "collect"`.
56
+ * Mirrors `Promise.allSettled`'s fulfilled/rejected split so a caller can tell
57
+ * a legitimate `undefined` body output apart from a failure at that index.
58
+ */
59
+ type FanOutOutcome<T = unknown> = {
60
+ readonly status: "fulfilled";
61
+ readonly index: number;
62
+ readonly value: T;
63
+ } | {
64
+ readonly status: "rejected";
65
+ readonly index: number;
66
+ readonly item: unknown;
67
+ /** `err.message` if the throw was an `Error`, else `String(err)`. */
68
+ readonly error: string;
69
+ };
70
+ /**
71
+ * The bound output of a `map`/`pipeline` step run with `onError: "collect"`:
72
+ * every item's outcome, plus the counts a caller needs to answer "how many
73
+ * failed and why" without re-scanning `results`.
74
+ */
75
+ interface TolerantFanOutResult<T = unknown> {
76
+ readonly results: readonly FanOutOutcome<T>[];
77
+ readonly succeeded: number;
78
+ readonly failed: number;
79
+ }
54
80
  /**
55
81
  * Run a sub-step once per element of an array, optionally with bounded
56
82
  * concurrency. The element + index are exposed to the body via `bindings.item`
@@ -63,6 +89,15 @@ interface MapStep {
63
89
  /** Max concurrent bodies (default 1 = sequential). */
64
90
  parallelism?: number;
65
91
  body: (item: unknown, index: number, bindings: Bindings) => RunStep;
92
+ /**
93
+ * `"throw"` (default): the first item to throw aborts the whole map — the
94
+ * step's output is a bare array, one entry per item, same as before this
95
+ * field existed. `"collect"`: every item runs to completion; the step's
96
+ * output becomes a {@link TolerantFanOutResult} instead of a bare array, so
97
+ * a failure is visible to the caller rather than aborting or getting
98
+ * silently dropped.
99
+ */
100
+ onError?: "throw" | "collect";
66
101
  }
67
102
  /**
68
103
  * Run N items through K sequential stage bodies with NO cross-item barrier:
@@ -79,6 +114,11 @@ interface PipelineStep {
79
114
  /** Ordered stage bodies; each item flows through them in order. `prevOutput`
80
115
  * is the previous stage's output for THIS item (undefined for stage 0). */
81
116
  stages: readonly ((item: unknown, index: number, prevOutput: unknown, bindings: Bindings) => RunStep)[];
117
+ /** Same semantics as {@link MapStep.onError}: `"throw"` (default) aborts
118
+ * the whole pipeline on the first item whose chain throws at any stage;
119
+ * `"collect"` runs every item's chain to completion and binds a
120
+ * {@link TolerantFanOutResult} instead of a bare array. */
121
+ onError?: "throw" | "collect";
82
122
  }
83
123
  /** Run one of two branches based on a predicate over the bindings. */
84
124
  interface BranchStep {
@@ -144,6 +184,17 @@ interface SubworkflowStep {
144
184
  /** Input for the child (default: the parent's workflow input). */
145
185
  input?: Selector<unknown>;
146
186
  }
187
+ /**
188
+ * Where an {@link AgentStep}'s session runs when not on the host: a sandbox
189
+ * provider slug (e.g. `"local"`, `"e2b"`) or an inline AIP-36 SandboxSpec-like
190
+ * object (`{ provider, config, env?, … }`). This runtime stays structural —
191
+ * the injected {@link AgentSessionHost} interprets the value (the daemon host
192
+ * forwards it to the same sandbox boot path `agent_start.sandbox` uses).
193
+ */
194
+ type AgentSandboxRef = string | {
195
+ provider: string;
196
+ [k: string]: unknown;
197
+ };
147
198
  /**
148
199
  * Spawn or reuse an agent session and send it a prompt, waiting for the
149
200
  * turn to complete. The host injects an {@link AgentSessionHost} — this
@@ -158,6 +209,13 @@ interface AgentStep {
158
209
  sessionRef?: string;
159
210
  /** Working directory for this spawn. Omit to fall back to the run-level `ctx.cwd`. */
160
211
  cwd?: Selector<string>;
212
+ /** Run this step's session inside a sandbox instead of on the host — a
213
+ * provider slug or inline spec (see {@link AgentSandboxRef}), or a selector
214
+ * resolving to one (`undefined` ⇒ host spawn, same as omitting the field).
215
+ * Only meaningful when `adapter` is set (a `sessionRef` reuse inherits the
216
+ * referenced session's placement). Hosts without sandbox support MUST fail
217
+ * the spawn loudly rather than silently running on the host. */
218
+ sandbox?: Selector<AgentSandboxRef | undefined> | AgentSandboxRef;
161
219
  /** Prompt to send. */
162
220
  prompt: Selector<string>;
163
221
  policy?: {
@@ -206,11 +264,15 @@ interface ResumeRequest {
206
264
  on: readonly string[];
207
265
  }
208
266
  interface AgentSessionHost {
209
- /** Spawn a new agent session and return its id. */
267
+ /** Spawn a new agent session and return its id. A `sandbox` ref asks the
268
+ * host to run the session inside that sandbox (provider slug or inline
269
+ * spec); hosts that can't MUST throw rather than silently spawn on the
270
+ * host. */
210
271
  spawn(adapter: string, opts: {
211
272
  cwd?: string;
212
273
  workspaceSlug?: string;
213
274
  stepId?: string;
275
+ sandbox?: AgentSandboxRef;
214
276
  }): Promise<string>;
215
277
  /** Send a prompt to an existing session and wait for its turn to end. */
216
278
  sendPromptAndWait(sessionId: string, prompt: string): Promise<void>;
@@ -352,4 +414,4 @@ declare function compileWorkflow(handle: WorkflowHandle, opts: CompileWorkflowOp
352
414
  */
353
415
  declare function compileWorkflowManifest(source: string, opts: CompileWorkflowOptions): RuntimeWorkflow;
354
416
 
355
- export { type AgentSessionHost, type AgentStep, type ApprovalRequest, type ApprovalStep, type Bindings, type BranchStep, type CompileWorkflowOptions, 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 ToolStep, type TransformStep, WorkflowCompileError, type WorkflowRunResult, WorkflowSuspendedError, compileWorkflow, compileWorkflowManifest, evalPredicate, resolveRef, resolveValue, runWorkflow };
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 };
package/dist/index.mjs CHANGED
@@ -63,6 +63,9 @@ async function readStepCache(ctx, step, resolvedInputs) {
63
63
  }
64
64
  return { hit: false, key, hash };
65
65
  }
66
+ function errorMessage(err) {
67
+ return err instanceof Error ? err.message : String(err);
68
+ }
66
69
  function formatZodError(err) {
67
70
  return err.issues.map((i) => `${i.path.length > 0 ? i.path.join(".") + ": " : ""}${i.message}`).join(", ");
68
71
  }
@@ -82,7 +85,13 @@ async function execAgentStep(step, ctx, b) {
82
85
  );
83
86
  }
84
87
  const cwd = step.cwd ? resolveSel(step.cwd, b) : ctx.cwd;
85
- const sessionId = step.adapter ? await ctx.agents.spawn(resolveSel(step.adapter, b), { cwd, workspaceSlug: ctx.workspaceSlug, stepId: step.id }) : ctx.agents.resolveByLabel(step.sessionRef);
88
+ const sandbox = typeof step.sandbox === "function" ? step.sandbox(b) : step.sandbox;
89
+ const sessionId = step.adapter ? await ctx.agents.spawn(resolveSel(step.adapter, b), {
90
+ cwd,
91
+ workspaceSlug: ctx.workspaceSlug,
92
+ stepId: step.id,
93
+ ...sandbox !== void 0 ? { sandbox } : {}
94
+ }) : ctx.agents.resolveByLabel(step.sessionRef);
86
95
  if (!sessionId) throw new Error(`step '${step.id}': no session (adapter and sessionRef both unresolved)`);
87
96
  await ctx.agents.sendPromptAndWait(sessionId, step.prompt(b));
88
97
  if (step.policy && ctx.agents.onAwaitingInput) {
@@ -152,32 +161,59 @@ async function execStep(step, ctx, item, index) {
152
161
  case "map": {
153
162
  const arr = [...step.over(b)];
154
163
  const parallelism = Math.max(1, step.parallelism ?? 1);
164
+ const tolerant = step.onError === "collect";
155
165
  const results = new Array(arr.length);
156
166
  for (let i = 0; i < arr.length; i += parallelism) {
157
167
  const chunk = arr.slice(i, i + parallelism);
158
- const outs = await Promise.all(
168
+ if (!tolerant) {
169
+ const outs = await Promise.all(
170
+ chunk.map((el, j) => {
171
+ const idx = i + j;
172
+ const inner = step.body(el, idx, view(state, el, idx));
173
+ return execStep(inner, ctx, el, idx);
174
+ })
175
+ );
176
+ for (let j = 0; j < outs.length; j++) results[i + j] = outs[j];
177
+ continue;
178
+ }
179
+ const settled = await Promise.allSettled(
159
180
  chunk.map((el, j) => {
160
181
  const idx = i + j;
161
182
  const inner = step.body(el, idx, view(state, el, idx));
162
183
  return execStep(inner, ctx, el, idx);
163
184
  })
164
185
  );
165
- for (let j = 0; j < outs.length; j++) results[i + j] = outs[j];
186
+ settled.forEach((s, j) => {
187
+ const idx = i + j;
188
+ results[idx] = s.status === "fulfilled" ? { status: "fulfilled", index: idx, value: s.value } : { status: "rejected", index: idx, item: chunk[j], error: errorMessage(s.reason) };
189
+ });
166
190
  }
167
- return results;
191
+ if (!tolerant) return results;
192
+ const outcomes = results;
193
+ return {
194
+ results: outcomes,
195
+ succeeded: outcomes.filter((r) => r.status === "fulfilled").length,
196
+ failed: outcomes.filter((r) => r.status === "rejected").length
197
+ };
168
198
  }
169
199
  case "pipeline": {
170
200
  const items = [...step.over(b)];
171
- if (items.length === 0) return [];
201
+ const tolerant = step.onError === "collect";
202
+ if (items.length === 0) return tolerant ? { results: [], succeeded: 0, failed: 0 } : [];
172
203
  const cap = Math.max(1, step.concurrency ?? items.length);
173
204
  const results = new Array(items.length);
174
205
  let next = 0;
175
206
  const runItem = async (idx) => {
176
207
  let prev = void 0;
177
- for (const stage of step.stages) {
178
- prev = await execStep(stage(items[idx], idx, prev, view(state, items[idx], idx)), ctx, items[idx], idx);
208
+ try {
209
+ for (const stage of step.stages) {
210
+ prev = await execStep(stage(items[idx], idx, prev, view(state, items[idx], idx)), ctx, items[idx], idx);
211
+ }
212
+ results[idx] = tolerant ? { status: "fulfilled", index: idx, value: prev } : prev;
213
+ } catch (err) {
214
+ if (!tolerant) throw err;
215
+ results[idx] = { status: "rejected", index: idx, item: items[idx], error: errorMessage(err) };
179
216
  }
180
- results[idx] = prev;
181
217
  };
182
218
  const worker = async () => {
183
219
  while (next < items.length) {
@@ -186,7 +222,13 @@ async function execStep(step, ctx, item, index) {
186
222
  }
187
223
  };
188
224
  await Promise.all(Array.from({ length: Math.min(cap, items.length) }, () => worker()));
189
- return results;
225
+ if (!tolerant) return results;
226
+ const outcomes = results;
227
+ return {
228
+ results: outcomes,
229
+ succeeded: outcomes.filter((r) => r.status === "fulfilled").length,
230
+ failed: outcomes.filter((r) => r.status === "rejected").length
231
+ };
190
232
  }
191
233
  case "branch": {
192
234
  const chosen = step.cond(b) ? step.then : step.otherwise ?? [];
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/run-workflow.ts","../src/compile-workflow.ts","../src/load-workflow.ts"],"names":[],"mappings":";;;;;;;;;AAsBO,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,SAAS,qBAAqB,GAAA,EAAqB;AACjD,EAAA,MAAM,SAAA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W,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 RunStep,\n RunWorkflowArgs,\n RuntimeWorkflow,\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\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 const sessionId = step.adapter\n ? await ctx.agents!.spawn(resolveSel(step.adapter, b), { cwd, workspaceSlug: ctx.workspaceSlug, stepId: step.id })\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 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 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 }\n return results\n }\n\n case \"pipeline\": {\n const items = [...step.over(b)]\n if (items.length === 0) return []\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 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] = prev\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 return results\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/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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AAA,uBAAA,EAA0B,IAAA,CAAK,IAAI,CAAA,SAAA,EAAY,EAAE,CAAA,EAAA;AAAA,OACnD;AAAA;AAEN;ACtRO,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}\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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentproto/workflow-runtime",
3
- "version": "0.3.0",
3
+ "version": "0.5.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",
@@ -17,7 +17,7 @@
17
17
  "type": "git",
18
18
  "url": "https://github.com/agentproto/ts"
19
19
  },
20
- "license": "MIT",
20
+ "license": "Apache-2.0",
21
21
  "type": "module",
22
22
  "main": "dist/index.mjs",
23
23
  "module": "dist/index.mjs",
@@ -39,9 +39,9 @@
39
39
  "access": "public"
40
40
  },
41
41
  "dependencies": {
42
- "@agentproto/tool": "0.2.0",
43
- "@agentproto/driver": "0.1.2",
44
- "@agentproto/workflow": "0.1.0-alpha.1"
42
+ "@agentproto/driver": "0.1.3",
43
+ "@agentproto/tool": "0.2.1",
44
+ "@agentproto/workflow": "0.1.0"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@types/node": "^25.6.2",