@agentproto/workflow-mastra 0.1.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 ADDED
@@ -0,0 +1,202 @@
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 ADDED
@@ -0,0 +1,67 @@
1
+ # @agentproto/workflow-mastra
2
+
3
+ Project an AIP-15 `WORKFLOW.md`'s compiled [`RuntimeWorkflow`](../workflow-runtime)
4
+ onto a [Mastra](https://mastra.ai) `createWorkflow`. Runtime projection, not
5
+ codegen — same one-level-up relationship
6
+ [`toMastraTool`](../../adapters/mastra) has to `implementTool`.
7
+
8
+ > **Status: 0.1.0-alpha.** Design spec: `packages/workflow/README.md` §A in
9
+ > this repo's history (PR #672 / this package's PR).
10
+
11
+ ## Usage
12
+
13
+ ```ts
14
+ import { compileWorkflowManifest } from "@agentproto/workflow-runtime"
15
+ import { toMastraWorkflow } from "@agentproto/workflow-mastra"
16
+
17
+ const compiled = compileWorkflowManifest(workflowMdSource, { tools, candidates })
18
+ const mastraWorkflow = toMastraWorkflow(compiled, { agents: mySessionHost })
19
+
20
+ const run = await mastraWorkflow.createRunAsync()
21
+ const result = await run.start({ inputData: { chatId: "…" } })
22
+ ```
23
+
24
+ ## Step-kind mapping
25
+
26
+ | `RunStep.kind` | Mastra primitive |
27
+ |---|---|
28
+ | `tool` | `createStep({execute})` wrapping the same `runTool` dispatch the engine itself uses |
29
+ | `transform` | `createStep({execute})` calling the step's `compute` selector |
30
+ | `agent` | `createStep({execute})` delegating to `@agentproto/workflow-runtime`'s own `AgentStep` executor via a one-step sub-run (reuses the spawn/prompt/policy/outputSchema-retry logic instead of re-implementing it) |
31
+ | `group` | one wrapper `createStep` running the group's children through a local step-walker, so later top-level siblings still see their outputs (matches the engine's shared-bindings model) |
32
+ | `branch` | `.branch([[cond, thenStep], [negatedCond, elseStep]])` |
33
+ | `parallel` | `.parallel([...branchSteps])` |
34
+ | `map` | `.foreach(bodyStep, { concurrency })` |
35
+ | `loop` | `.dowhile(bodyStep, condition)` — `condition` combines `LoopStep.while` with Mastra's native `iterationCount`, so `maxIterations` is enforced without a synthetic counter step |
36
+ | `subworkflow` | delegates to `runWorkflow` for the child (isolated bindings, matching `SubworkflowStep`'s own documented semantics) |
37
+ | `suspend`, `approval` | **not projectable** — `toMastraWorkflow` throws `WorkflowProjectionError` eagerly, before building anything |
38
+
39
+ `pipeline` (a `workflow-runtime`-only fan-out kind not covered by the design
40
+ spec this package implements) also fails loud rather than silently
41
+ degrading to `map` semantics it doesn't have.
42
+
43
+ ## Known limitations
44
+
45
+ - Composite step bodies (`branch`/`map`/`loop`/`group`) run through a small
46
+ local step-walker rather than further Mastra sub-workflows, so a nested
47
+ body CAN read `$input` / `$item` / `$index` and any sibling bound earlier
48
+ in the SAME run.
49
+ - `parallel` branches run concurrently, and Mastra's per-run `state` has no
50
+ compare-and-swap — two branches merging into it at once would silently
51
+ lose one branch's write. So a `parallel` branch's own nested step ids are
52
+ visible to LATER steps within the SAME branch, but not to anything outside
53
+ the `parallel` block; only the branch's own final output (keyed by branch
54
+ id, via Mastra's own concurrency-safe result aggregation) binds under the
55
+ `ParallelStep`'s id.
56
+ - An `AgentStep`'s selectors (delegated to an isolated one-step `runWorkflow`
57
+ sub-run for full parity with the engine's own spawn/prompt/policy/retry
58
+ executor) only see `$input`, not `$steps.<id>`.
59
+ - `map` bodies don't get `$index` (Mastra's `.foreach()` doesn't expose the
60
+ element's index to the body step).
61
+
62
+ Flagged, not solved here — same spirit as the design spec's own documented
63
+ gaps (`packages/workflow/README.md`).
64
+
65
+ ## License
66
+
67
+ Apache-2.0 — see [LICENSE](./LICENSE).
@@ -0,0 +1,44 @@
1
+ import { AgentSessionHost, RuntimeWorkflow } from '@agentproto/workflow-runtime';
2
+
3
+ /**
4
+ * Thrown eagerly — before any Mastra primitive is built — when a compiled
5
+ * workflow's step graph contains a kind {@link toMastraWorkflow} can't
6
+ * represent. Never a silent drop: every unmappable step surfaces as one of
7
+ * these, naming the exact step id/kind/path that tripped it.
8
+ */
9
+ declare class WorkflowProjectionError extends Error {
10
+ constructor(message: string);
11
+ }
12
+
13
+ /**
14
+ * @agentproto/workflow-mastra — project a compiled AIP-15 {@link RuntimeWorkflow}
15
+ * onto a Mastra `createWorkflow`. Runtime projection (the compiled workflow
16
+ * already carries live `ToolHandle` + `DriverHandle[]` candidates per tool
17
+ * step — same inputs `runTool` already dispatches), not codegen: nothing
18
+ * here emits a `.ts` file to hand-edit, matching
19
+ * `packages/workflow/README.md`'s design spec for why WORKFLOW.md doesn't
20
+ * need the PROCEDURE.md → Mastra codegen precedent's "generated file meant
21
+ * to be hand-customized" shape — a WORKFLOW.md's steps run as declared.
22
+ *
23
+ * See the package README for the full step-kind → Mastra primitive table
24
+ * and the documented fidelity limitations.
25
+ */
26
+
27
+ interface ToMastraWorkflowOptions {
28
+ /** Host-injected agent session runtime. Required only if the workflow has `agent` steps. */
29
+ agents?: AgentSessionHost;
30
+ /** Working directory for spawned agent sessions / subworkflow runs. */
31
+ cwd?: string;
32
+ /** Workspace slug for spawned agent sessions. */
33
+ workspaceSlug?: string;
34
+ }
35
+ type AnyWorkflowBuilder = any;
36
+ /**
37
+ * Project a compiled {@link RuntimeWorkflow} onto a Mastra `createWorkflow`.
38
+ * Throws {@link WorkflowProjectionError} eagerly — before building any Mastra
39
+ * primitive — if the step graph (including nested `subworkflow` children)
40
+ * contains a `suspend`, `approval`, or `pipeline` step; see the README for why.
41
+ */
42
+ declare function toMastraWorkflow(compiled: RuntimeWorkflow, opts?: ToMastraWorkflowOptions): AnyWorkflowBuilder;
43
+
44
+ export { type ToMastraWorkflowOptions, WorkflowProjectionError, toMastraWorkflow };
package/dist/index.mjs ADDED
@@ -0,0 +1,328 @@
1
+ import { createWorkflow, createStep } from '@mastra/core/workflows';
2
+ import { z } from 'zod';
3
+ import { runTool } from '@agentproto/driver';
4
+ import { runWorkflow } from '@agentproto/workflow-runtime';
5
+
6
+ /**
7
+ * @agentproto/workflow-mastra v0.1.0-alpha
8
+ * AIP-15 WORKFLOW.md → Mastra createWorkflow projection.
9
+ */
10
+
11
+
12
+ // src/errors.ts
13
+ var WorkflowProjectionError = class extends Error {
14
+ constructor(message) {
15
+ super(`toMastraWorkflow: ${message}`);
16
+ this.name = "WorkflowProjectionError";
17
+ }
18
+ };
19
+
20
+ // src/assert-projectable.ts
21
+ var UNPROJECTABLE_REASON = {
22
+ suspend: "Mastra has no equivalent this projection wires up yet \u2014 a durable suspend/resume pair needs a host-level resume channel this projector doesn't have access to at build time. Hand-author the Mastra `.suspend()` step directly if you need this.",
23
+ approval: "there's no host-injected approve callback available at Mastra-build time to decide it \u2014 the engine's own ApprovalStep needs a live `RunWorkflowArgs.approve` hook, which only exists per-run, not per-projection.",
24
+ pipeline: "PipelineStep is a @agentproto/workflow-runtime-only fan-out kind not covered by the WORKFLOW.md \u2192 Mastra design spec this package implements \u2014 it is NOT silently downgraded to `map` semantics it doesn't have."
25
+ };
26
+ function assertProjectable(steps, path = "") {
27
+ for (const step of steps) {
28
+ const reason = UNPROJECTABLE_REASON[step.kind];
29
+ if (reason) {
30
+ throw new WorkflowProjectionError(
31
+ `step '${path}${step.id}' (kind '${step.kind}') is not projectable to Mastra \u2014 ${reason}`
32
+ );
33
+ }
34
+ const nextPath = `${path}${step.id}.`;
35
+ switch (step.kind) {
36
+ case "group":
37
+ assertProjectable(step.steps, nextPath);
38
+ break;
39
+ case "branch":
40
+ assertProjectable(step.then, nextPath);
41
+ if (step.otherwise) assertProjectable(step.otherwise, nextPath);
42
+ break;
43
+ case "parallel":
44
+ for (const branch of step.branches) assertProjectable(branch.steps, `${nextPath}${branch.id}.`);
45
+ break;
46
+ case "loop":
47
+ assertProjectable(step.body, nextPath);
48
+ break;
49
+ case "map": {
50
+ const shape = step.body(void 0, 0, { input: void 0, steps: {} });
51
+ assertProjectable([shape], nextPath);
52
+ break;
53
+ }
54
+ case "subworkflow":
55
+ assertProjectable(step.workflow.steps, nextPath);
56
+ break;
57
+ }
58
+ }
59
+ }
60
+ async function runLocalSteps(steps, bindings, acc, ctx) {
61
+ let last;
62
+ for (const step of steps) {
63
+ last = await runLocalStep(step, { ...bindings, steps: acc }, acc, ctx);
64
+ acc[step.id] = last;
65
+ }
66
+ return last;
67
+ }
68
+ async function runLocalStep(step, bindings, acc, ctx) {
69
+ switch (step.kind) {
70
+ case "tool":
71
+ return runTool({
72
+ tool: step.tool,
73
+ candidates: step.candidates,
74
+ input: step.input(bindings),
75
+ context: step.context ? step.context(bindings) : void 0,
76
+ resolverContext: step.resolverContext,
77
+ secrets: step.secrets,
78
+ signal: ctx.signal
79
+ });
80
+ case "transform":
81
+ return step.compute(bindings);
82
+ case "group":
83
+ return runLocalSteps(step.steps, bindings, acc, ctx);
84
+ case "branch": {
85
+ const chosen = step.cond(bindings) ? step.then : step.otherwise ?? [];
86
+ return runLocalSteps(chosen, bindings, acc, ctx);
87
+ }
88
+ case "parallel": {
89
+ const entries = await Promise.all(
90
+ step.branches.map(async (branch) => {
91
+ const branchAcc = {};
92
+ const last = await runLocalSteps(branch.steps, bindings, branchAcc, ctx);
93
+ Object.assign(acc, branchAcc);
94
+ return [branch.id, last];
95
+ })
96
+ );
97
+ return Object.fromEntries(entries);
98
+ }
99
+ case "map": {
100
+ const items = [...step.over(bindings)];
101
+ const parallelism = Math.max(1, step.parallelism ?? 1);
102
+ const results = new Array(items.length);
103
+ for (let i = 0; i < items.length; i += parallelism) {
104
+ const chunk = items.slice(i, i + parallelism);
105
+ const outs = await Promise.all(
106
+ chunk.map((item, j) => {
107
+ const idx = i + j;
108
+ const itemBindings = { ...bindings, item, index: idx };
109
+ const inner = step.body(item, idx, itemBindings);
110
+ return runLocalStep(inner, itemBindings, acc, ctx);
111
+ })
112
+ );
113
+ for (let j = 0; j < outs.length; j++) results[i + j] = outs[j];
114
+ }
115
+ return results;
116
+ }
117
+ case "loop": {
118
+ let iterations = 0;
119
+ let last;
120
+ let b = bindings;
121
+ while (iterations < step.maxIterations && step.while(b)) {
122
+ last = await runLocalSteps(step.body, b, acc, ctx);
123
+ b = { ...bindings, steps: acc };
124
+ iterations++;
125
+ }
126
+ return last;
127
+ }
128
+ case "agent": {
129
+ if (!ctx.agents) {
130
+ throw new Error(
131
+ `step '${step.id}': AgentStep requires an AgentSessionHost \u2014 pass opts.agents to toMastraWorkflow`
132
+ );
133
+ }
134
+ const result = await runWorkflow({
135
+ workflow: { id: `${step.id}__agent`, steps: [step] },
136
+ input: bindings.input,
137
+ agents: ctx.agents,
138
+ cwd: ctx.cwd,
139
+ workspaceSlug: ctx.workspaceSlug,
140
+ signal: ctx.signal
141
+ });
142
+ return result.output;
143
+ }
144
+ case "subworkflow": {
145
+ const childInput = step.input ? step.input(bindings) : bindings.input;
146
+ const result = await runWorkflow({
147
+ workflow: step.workflow,
148
+ input: childInput,
149
+ agents: ctx.agents,
150
+ cwd: ctx.cwd,
151
+ workspaceSlug: ctx.workspaceSlug,
152
+ signal: ctx.signal
153
+ });
154
+ return result.output;
155
+ }
156
+ case "suspend":
157
+ case "approval":
158
+ case "pipeline":
159
+ throw new WorkflowProjectionError(
160
+ `step '${step.id}' (kind '${step.kind}') reached the local walker \u2014 this should have been rejected by assertProjectable first`
161
+ );
162
+ }
163
+ }
164
+
165
+ // src/index.ts
166
+ function bindingsFromParams(params) {
167
+ const priorSteps = params.state?.steps ?? {};
168
+ return { input: params.getInitData(), steps: { ...priorSteps } };
169
+ }
170
+ async function mergeStateSteps(params, patch) {
171
+ const prior = params.state?.steps ?? {};
172
+ await params.setState({ steps: { ...prior, ...patch } });
173
+ }
174
+ function atomicWrapper(step, ctx) {
175
+ return createStep({
176
+ id: step.id,
177
+ inputSchema: z.any(),
178
+ outputSchema: z.any(),
179
+ execute: async (params) => {
180
+ const bindings = bindingsFromParams(params);
181
+ const acc = { ...bindings.steps };
182
+ const output = await runLocalSteps([step], bindings, acc, ctx);
183
+ await mergeStateSteps(params, acc);
184
+ return output;
185
+ }
186
+ });
187
+ }
188
+ function bindResultStep(id) {
189
+ return createStep({
190
+ id: `${id}__bind`,
191
+ inputSchema: z.any(),
192
+ outputSchema: z.any(),
193
+ execute: async (params) => {
194
+ await mergeStateSteps(params, { [id]: params.inputData });
195
+ return params.inputData;
196
+ }
197
+ });
198
+ }
199
+ function branchArm(step, armSteps, label, ctx) {
200
+ return createStep({
201
+ id: `${step.id}__${label}`,
202
+ inputSchema: z.any(),
203
+ outputSchema: z.any(),
204
+ execute: async (params) => {
205
+ const bindings = bindingsFromParams(params);
206
+ const acc = { ...bindings.steps };
207
+ const output = await runLocalSteps(armSteps, bindings, acc, ctx);
208
+ acc[step.id] = output;
209
+ await mergeStateSteps(params, acc);
210
+ return output;
211
+ }
212
+ });
213
+ }
214
+ function attachBranch(wf, step, ctx) {
215
+ const cond = (params) => step.cond(bindingsFromParams(params));
216
+ return wf.branch([
217
+ [(params) => cond(params), branchArm(step, step.then, "then", ctx)],
218
+ [(params) => !cond(params), branchArm(step, step.otherwise ?? [], "else", ctx)]
219
+ ]);
220
+ }
221
+ function parallelBranch(step, branch, ctx) {
222
+ return createStep({
223
+ id: `${step.id}__${branch.id}`,
224
+ inputSchema: z.any(),
225
+ outputSchema: z.any(),
226
+ execute: async (params) => {
227
+ const bindings = bindingsFromParams(params);
228
+ const acc = { ...bindings.steps };
229
+ return runLocalSteps(branch.steps, bindings, acc, ctx);
230
+ }
231
+ });
232
+ }
233
+ function finalizeParallel(step) {
234
+ return createStep({
235
+ id: `${step.id}__finalize`,
236
+ inputSchema: z.any(),
237
+ outputSchema: z.any(),
238
+ execute: async (params) => {
239
+ const raw = params.inputData ?? {};
240
+ const record = {};
241
+ for (const branch of step.branches) record[branch.id] = raw[`${step.id}__${branch.id}`];
242
+ await mergeStateSteps(params, { [step.id]: record });
243
+ return record;
244
+ }
245
+ });
246
+ }
247
+ function attachParallel(wf, step, ctx) {
248
+ return wf.parallel(step.branches.map((branch) => parallelBranch(step, branch, ctx))).then(finalizeParallel(step));
249
+ }
250
+ function computeMapItems(step) {
251
+ return createStep({
252
+ id: `${step.id}__items`,
253
+ inputSchema: z.any(),
254
+ outputSchema: z.any(),
255
+ execute: async (params) => [...step.over(bindingsFromParams(params))]
256
+ });
257
+ }
258
+ function mapBody(step, ctx) {
259
+ return createStep({
260
+ id: `${step.id}__body`,
261
+ inputSchema: z.any(),
262
+ outputSchema: z.any(),
263
+ execute: async (params) => {
264
+ const outer = bindingsFromParams(params);
265
+ const item = params.inputData;
266
+ const itemBindings = { ...outer, item, index: void 0 };
267
+ const acc = { ...outer.steps };
268
+ const inner = step.body(item, -1, itemBindings);
269
+ return runLocalStep(inner, itemBindings, acc, ctx);
270
+ }
271
+ });
272
+ }
273
+ function attachMap(wf, step, ctx) {
274
+ return wf.then(computeMapItems(step)).foreach(mapBody(step, ctx), step.parallelism ? { concurrency: step.parallelism } : void 0).then(bindResultStep(step.id));
275
+ }
276
+ function loopBody(step, ctx) {
277
+ return createStep({
278
+ id: `${step.id}__body`,
279
+ inputSchema: z.any(),
280
+ outputSchema: z.any(),
281
+ execute: async (params) => {
282
+ const bindings = bindingsFromParams(params);
283
+ if (!step.while(bindings)) return void 0;
284
+ const acc = { ...bindings.steps };
285
+ const output = await runLocalSteps(step.body, bindings, acc, ctx);
286
+ await mergeStateSteps(params, acc);
287
+ return output;
288
+ }
289
+ });
290
+ }
291
+ function attachLoop(wf, step, ctx) {
292
+ return wf.dowhile(loopBody(step, ctx), async (params) => {
293
+ const bindings = bindingsFromParams(params);
294
+ return step.while(bindings) && params.iterationCount < step.maxIterations;
295
+ }).then(bindResultStep(step.id));
296
+ }
297
+ function attachStep(wf, step, ctx) {
298
+ switch (step.kind) {
299
+ case "branch":
300
+ return attachBranch(wf, step, ctx);
301
+ case "parallel":
302
+ return attachParallel(wf, step, ctx);
303
+ case "map":
304
+ return attachMap(wf, step, ctx);
305
+ case "loop":
306
+ return attachLoop(wf, step, ctx);
307
+ default:
308
+ return wf.then(atomicWrapper(step, ctx));
309
+ }
310
+ }
311
+ function toMastraWorkflow(compiled, opts = {}) {
312
+ assertProjectable(compiled.steps);
313
+ const ctx = { agents: opts.agents, cwd: opts.cwd, workspaceSlug: opts.workspaceSlug };
314
+ let wf = createWorkflow({
315
+ id: compiled.id,
316
+ description: compiled.description,
317
+ inputSchema: z.any(),
318
+ outputSchema: z.any()
319
+ });
320
+ for (const step of compiled.steps) {
321
+ wf = attachStep(wf, step, ctx);
322
+ }
323
+ return wf.commit();
324
+ }
325
+
326
+ export { WorkflowProjectionError, toMastraWorkflow };
327
+ //# sourceMappingURL=index.mjs.map
328
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/assert-projectable.ts","../src/local-walker.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAMO,IAAM,uBAAA,GAAN,cAAsC,KAAA,CAAM;AAAA,EACjD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,CAAA,kBAAA,EAAqB,OAAO,CAAA,CAAE,CAAA;AACpC,IAAA,IAAA,CAAK,IAAA,GAAO,yBAAA;AAAA,EACd;AACF;;;ACRA,IAAM,oBAAA,GAAiE;AAAA,EACrE,OAAA,EACE,uPAAA;AAAA,EAIF,QAAA,EACE,wNAAA;AAAA,EAGF,QAAA,EACE;AAGJ,CAAA;AAQO,SAAS,iBAAA,CAAkB,KAAA,EAA2B,IAAA,GAAO,EAAA,EAAU;AAC5E,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,MAAM,MAAA,GAAS,oBAAA,CAAqB,IAAA,CAAK,IAAI,CAAA;AAC7C,IAAA,IAAI,MAAA,EAAQ;AACV,MAAA,MAAM,IAAI,uBAAA;AAAA,QACR,CAAA,MAAA,EAAS,IAAI,CAAA,EAAG,IAAA,CAAK,EAAE,CAAA,SAAA,EAAY,IAAA,CAAK,IAAI,CAAA,uCAAA,EAAqC,MAAM,CAAA;AAAA,O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;AAClG,EAAA,QAAQ,KAAK,IAAA;AAAM,IACjB,KAAK,QAAA;AACH,MAAA,OAAO,YAAA,CAAa,EAAA,EAAI,IAAA,EAAM,GAAG,CAAA;AAAA,IACnC,KAAK,UAAA;AACH,MAAA,OAAO,cAAA,CAAe,EAAA,EAAI,IAAA,EAAM,GAAG,CAAA;AAAA,IACrC,KAAK,KAAA;AACH,MAAA,OAAO,SAAA,CAAU,EAAA,EAAI,IAAA,EAAM,GAAG,CAAA;AAAA,IAChC,KAAK,MAAA;AACH,MAAA,OAAO,UAAA,CAAW,EAAA,EAAI,IAAA,EAAM,GAAG,CAAA;AAAA,IACjC;AAEE,MAAA,OAAO,EAAA,CAAG,IAAA,CAAK,aAAA,CAAc,IAAA,EAAM,GAAG,CAAC,CAAA;AAAA;AAE7C;AAQO,SAAS,gBAAA,CACd,QAAA,EACA,IAAA,GAAgC,EAAC,EACb;AACpB,EAAA,iBAAA,CAAkB,SAAS,KAAK,CAAA;AAChC,EAAA,MAAM,GAAA,GAAsB,EAAE,MAAA,EAAQ,IAAA,CAAK,MAAA,EAAQ,KAAK,IAAA,CAAK,GAAA,EAAK,aAAA,EAAe,IAAA,CAAK,aAAA,EAAc;AAEpG,EAAA,IAAI,KAAyB,cAAA,CAAe;AAAA,IAC1C,IAAI,QAAA,CAAS,EAAA;AAAA,IACb,aAAa,QAAA,CAAS,WAAA;AAAA,IACtB,WAAA,EAAa,EAAE,GAAA,EAAI;AAAA,IACnB,YAAA,EAAc,EAAE,GAAA;AAAI,GACrB,CAAA;AACD,EAAA,KAAA,MAAW,IAAA,IAAQ,SAAS,KAAA,EAAO;AACjC,IAAA,EAAA,GAAK,UAAA,CAAW,EAAA,EAAI,IAAA,EAAM,GAAG,CAAA;AAAA,EAC/B;AACA,EAAA,OAAO,GAAG,MAAA,EAAO;AACnB","file":"index.mjs","sourcesContent":["/**\n * Thrown eagerly — before any Mastra primitive is built — when a compiled\n * workflow's step graph contains a kind {@link toMastraWorkflow} can't\n * represent. Never a silent drop: every unmappable step surfaces as one of\n * these, naming the exact step id/kind/path that tripped it.\n */\nexport class WorkflowProjectionError extends Error {\n constructor(message: string) {\n super(`toMastraWorkflow: ${message}`)\n this.name = \"WorkflowProjectionError\"\n }\n}\n","import type { RunStep } from \"@agentproto/workflow-runtime\"\nimport { WorkflowProjectionError } from \"./errors.js\"\n\nconst UNPROJECTABLE_REASON: Partial<Record<RunStep[\"kind\"], string>> = {\n suspend:\n \"Mastra has no equivalent this projection wires up yet — a durable \" +\n \"suspend/resume pair needs a host-level resume channel this projector \" +\n \"doesn't have access to at build time. Hand-author the Mastra `.suspend()` \" +\n \"step directly if you need this.\",\n approval:\n \"there's no host-injected approve callback available at Mastra-build \" +\n \"time to decide it — the engine's own ApprovalStep needs a live \" +\n \"`RunWorkflowArgs.approve` hook, which only exists per-run, not per-projection.\",\n pipeline:\n \"PipelineStep is a @agentproto/workflow-runtime-only fan-out kind not \" +\n \"covered by the WORKFLOW.md → Mastra design spec this package implements \" +\n \"— it is NOT silently downgraded to `map` semantics it doesn't have.\",\n}\n\n/**\n * Walk every step (recursing into every composite kind's children) and\n * throw {@link WorkflowProjectionError} on the first unmappable kind. Called\n * BEFORE {@link toMastraWorkflow} builds anything, so a workflow that can't\n * be projected fails at wrap time, not partway through a run.\n */\nexport function assertProjectable(steps: readonly RunStep[], path = \"\"): void {\n for (const step of steps) {\n const reason = UNPROJECTABLE_REASON[step.kind]\n if (reason) {\n throw new WorkflowProjectionError(\n `step '${path}${step.id}' (kind '${step.kind}') is not projectable to Mastra — ${reason}`,\n )\n }\n const nextPath = `${path}${step.id}.`\n switch (step.kind) {\n case \"group\":\n assertProjectable(step.steps, nextPath)\n break\n case \"branch\":\n assertProjectable(step.then, nextPath)\n if (step.otherwise) assertProjectable(step.otherwise, nextPath)\n break\n case \"parallel\":\n for (const branch of step.branches) assertProjectable(branch.steps, `${nextPath}${branch.id}.`)\n break\n case \"loop\":\n assertProjectable(step.body, nextPath)\n break\n case \"map\": {\n // The body is a function of (item, index, bindings); compiler-produced\n // bodies ignore all three and return the same compiled step regardless\n // (see compile-workflow.ts's `map` case), so a placeholder call is\n // enough to inspect its shape without actually running anything.\n const shape = step.body(undefined, 0, { input: undefined, steps: {} })\n assertProjectable([shape], nextPath)\n break\n }\n case \"subworkflow\":\n assertProjectable(step.workflow.steps, nextPath)\n break\n default:\n break // tool / transform / agent: no children to walk\n }\n }\n}\n","/**\n * A small local step-walker used ONLY for what's inside a Mastra\n * combinator's single-step slot (a `.branch()` arm, a `.parallel()` branch,\n * a `.foreach()`/`.dowhile()` body, a `group`'s children). Mastra's own\n * combinators need exactly one `Step` per slot; when that slot holds more\n * than one engine step, this walker runs them in-process instead of\n * expressing each one as its own Mastra primitive.\n *\n * It mirrors `@agentproto/workflow-runtime`'s own (unexported) `execStep` —\n * same shared, mutable `steps` accumulator, same selector-evaluation order —\n * for one reason `runWorkflow`'s public entrypoint can't provide: `map`'s\n * `$item`/`$index` bindings are only ever produced by the engine's own\n * per-iteration loop, and `RunWorkflowArgs.input` has no seam for injecting\n * them into an isolated sub-run. Reusing the compiled step's own selectors\n * directly, in-process, is what keeps `$item`/`$index` (and `$steps.<id>`\n * for anything already bound in the SAME Mastra run) resolving correctly.\n */\n\nimport { runTool } from \"@agentproto/driver\"\nimport {\n runWorkflow,\n type AgentSessionHost,\n type Bindings,\n type RunStep,\n} from \"@agentproto/workflow-runtime\"\nimport { WorkflowProjectionError } from \"./errors.js\"\n\nexport interface LocalWalkerCtx {\n agents?: AgentSessionHost\n cwd?: string\n workspaceSlug?: string\n signal?: AbortSignal\n}\n\n/** Run an ordered list of steps, folding each output into the shared `acc` bag. */\nexport async function runLocalSteps(\n steps: readonly RunStep[],\n bindings: Bindings,\n acc: Record<string, unknown>,\n ctx: LocalWalkerCtx,\n): Promise<unknown> {\n let last: unknown\n for (const step of steps) {\n last = await runLocalStep(step, { ...bindings, steps: acc }, acc, ctx)\n acc[step.id] = last\n }\n return last\n}\n\n/** Run a single step; composite kinds recurse back into {@link runLocalSteps}. */\nexport async function runLocalStep(\n step: RunStep,\n bindings: Bindings,\n acc: Record<string, unknown>,\n ctx: LocalWalkerCtx,\n): Promise<unknown> {\n switch (step.kind) {\n case \"tool\":\n return runTool({\n tool: step.tool,\n candidates: step.candidates,\n input: step.input(bindings),\n context: step.context ? step.context(bindings) : undefined,\n resolverContext: step.resolverContext,\n secrets: step.secrets,\n signal: ctx.signal,\n })\n\n case \"transform\":\n return step.compute(bindings)\n\n case \"group\":\n return runLocalSteps(step.steps, bindings, acc, ctx)\n\n case \"branch\": {\n const chosen = step.cond(bindings) ? step.then : (step.otherwise ?? [])\n return runLocalSteps(chosen, bindings, acc, ctx)\n }\n\n case \"parallel\": {\n const entries = await Promise.all(\n step.branches.map(async (branch) => {\n const branchAcc: Record<string, unknown> = {}\n const last = await runLocalSteps(branch.steps, bindings, branchAcc, ctx)\n Object.assign(acc, branchAcc) // later top-level siblings see nested ids too\n return [branch.id, last] as const\n }),\n )\n return Object.fromEntries(entries)\n }\n\n case \"map\": {\n const items = [...step.over(bindings)]\n const parallelism = Math.max(1, step.parallelism ?? 1)\n const results: unknown[] = new Array(items.length)\n for (let i = 0; i < items.length; i += parallelism) {\n const chunk = items.slice(i, i + parallelism)\n const outs = await Promise.all(\n chunk.map((item, j) => {\n const idx = i + j\n const itemBindings: Bindings = { ...bindings, item, index: idx }\n const inner = step.body(item, idx, itemBindings)\n return runLocalStep(inner, itemBindings, acc, ctx)\n }),\n )\n for (let j = 0; j < outs.length; j++) results[i + j] = outs[j]\n }\n return results\n }\n\n case \"loop\": {\n let iterations = 0\n let last: unknown\n let b = bindings\n while (iterations < step.maxIterations && step.while(b)) {\n last = await runLocalSteps(step.body, b, acc, ctx)\n b = { ...bindings, steps: acc }\n iterations++\n }\n return last\n }\n\n case \"agent\": {\n if (!ctx.agents) {\n throw new Error(\n `step '${step.id}': AgentStep requires an AgentSessionHost — pass ` +\n `opts.agents to toMastraWorkflow`,\n )\n }\n // Delegate to workflow-runtime's own AgentStep executor (spawn / prompt /\n // policy / outputSchema-retry) via an isolated one-step sub-run, rather\n // than re-implementing that logic here. Trade-off: `$steps.<id>` refs in\n // this step's selectors won't resolve (the sub-run's bindings.steps\n // starts empty) — only `$input.*` is threaded through. See README.\n const result = await runWorkflow({\n workflow: { id: `${step.id}__agent`, steps: [step] },\n input: bindings.input,\n agents: ctx.agents,\n cwd: ctx.cwd,\n workspaceSlug: ctx.workspaceSlug,\n signal: ctx.signal,\n })\n return result.output\n }\n\n case \"subworkflow\": {\n // SubworkflowStep is documented as running \"with its own isolated\n // bindings\" — runWorkflow's own fresh sub-run IS that isolation, not a\n // gap to work around.\n const childInput = step.input ? step.input(bindings) : bindings.input\n const result = await runWorkflow({\n workflow: step.workflow,\n input: childInput,\n agents: ctx.agents,\n cwd: ctx.cwd,\n workspaceSlug: ctx.workspaceSlug,\n signal: ctx.signal,\n })\n return result.output\n }\n\n case \"suspend\":\n case \"approval\":\n case \"pipeline\":\n // Unreachable: assertProjectable rejects these before the walker ever runs.\n throw new WorkflowProjectionError(\n `step '${step.id}' (kind '${step.kind}') reached the local walker — ` +\n `this should have been rejected by assertProjectable first`,\n )\n }\n}\n","/**\n * @agentproto/workflow-mastra — project a compiled AIP-15 {@link RuntimeWorkflow}\n * onto a Mastra `createWorkflow`. Runtime projection (the compiled workflow\n * already carries live `ToolHandle` + `DriverHandle[]` candidates per tool\n * step — same inputs `runTool` already dispatches), not codegen: nothing\n * here emits a `.ts` file to hand-edit, matching\n * `packages/workflow/README.md`'s design spec for why WORKFLOW.md doesn't\n * need the PROCEDURE.md → Mastra codegen precedent's \"generated file meant\n * to be hand-customized\" shape — a WORKFLOW.md's steps run as declared.\n *\n * See the package README for the full step-kind → Mastra primitive table\n * and the documented fidelity limitations.\n */\n\nimport { createStep, createWorkflow } from \"@mastra/core/workflows\"\nimport { z } from \"zod\"\nimport type {\n AgentSessionHost,\n BranchStep,\n Bindings,\n LoopStep,\n MapStep,\n ParallelStep,\n RunStep,\n RuntimeWorkflow,\n} from \"@agentproto/workflow-runtime\"\n\nimport { assertProjectable } from \"./assert-projectable.js\"\nimport { runLocalStep, runLocalSteps, type LocalWalkerCtx } from \"./local-walker.js\"\n\nexport { WorkflowProjectionError } from \"./errors.js\"\n\nexport interface ToMastraWorkflowOptions {\n /** Host-injected agent session runtime. Required only if the workflow has `agent` steps. */\n agents?: AgentSessionHost\n /** Working directory for spawned agent sessions / subworkflow runs. */\n cwd?: string\n /** Workspace slug for spawned agent sessions. */\n workspaceSlug?: string\n}\n\n// Mastra's step/workflow generics are deeply parameterized on schema shape\n// (see @mastra/core/dist/workflows/{step,workflow}.d.ts) — this projector\n// deals in a dynamically-shaped step graph, so every step here declares\n// `z.any()` in/out and the builder chain is threaded as `any`, mirroring\n// @agentproto/adapter-ai-sdk's own documented `dynamicTool` escape hatch for\n// the same reason: the static generics can't be satisfied by a value whose\n// shape is only known at projection time, even though it's structurally valid.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyWorkflowBuilder = any\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyStepParams = any\n\n/** Read the run-scoped `input`/`steps` bindings back out of Mastra's own per-run `state`. */\nfunction bindingsFromParams(params: AnyStepParams): Bindings {\n const priorSteps = (params.state as { steps?: Record<string, unknown> } | undefined)?.steps ?? {}\n return { input: params.getInitData(), steps: { ...priorSteps } }\n}\n\n/** Merge a patch into Mastra's per-run `state.steps` bag (read-modify-write). */\nasync function mergeStateSteps(params: AnyStepParams, patch: Record<string, unknown>): Promise<void> {\n const prior = (params.state as { steps?: Record<string, unknown> } | undefined)?.steps ?? {}\n await params.setState({ steps: { ...prior, ...patch } })\n}\n\n/** Atomic Mastra step for a `tool` / `transform` / `agent` / `group` / `subworkflow` RunStep. */\nfunction atomicWrapper(step: RunStep, ctx: LocalWalkerCtx): AnyWorkflowBuilder {\n return createStep({\n id: step.id,\n inputSchema: z.any(),\n outputSchema: z.any(),\n execute: async (params: AnyStepParams) => {\n const bindings = bindingsFromParams(params)\n const acc: Record<string, unknown> = { ...bindings.steps }\n const output = await runLocalSteps([step], bindings, acc, ctx)\n await mergeStateSteps(params, acc)\n return output\n },\n })\n}\n\n/** Pass a value through and bind it into `state.steps[id]` — used after a Mastra\n * combinator (`.parallel()`/`.foreach()`/`.dowhile()`) whose own output shape\n * we don't rely on for anything but this final bookkeeping step. */\nfunction bindResultStep(id: string): AnyWorkflowBuilder {\n return createStep({\n id: `${id}__bind`,\n inputSchema: z.any(),\n outputSchema: z.any(),\n execute: async (params: AnyStepParams) => {\n await mergeStateSteps(params, { [id]: params.inputData })\n return params.inputData\n },\n })\n}\n\nfunction branchArm(step: BranchStep, armSteps: readonly RunStep[], label: string, ctx: LocalWalkerCtx): AnyWorkflowBuilder {\n return createStep({\n id: `${step.id}__${label}`,\n inputSchema: z.any(),\n outputSchema: z.any(),\n execute: async (params: AnyStepParams) => {\n const bindings = bindingsFromParams(params)\n const acc: Record<string, unknown> = { ...bindings.steps }\n const output = await runLocalSteps(armSteps, bindings, acc, ctx)\n acc[step.id] = output // bind under the ORIGINAL BranchStep's id, not the arm's synthetic one\n await mergeStateSteps(params, acc)\n return output\n },\n })\n}\n\nfunction attachBranch(wf: AnyWorkflowBuilder, step: BranchStep, ctx: LocalWalkerCtx): AnyWorkflowBuilder {\n const cond = (params: AnyStepParams) => step.cond(bindingsFromParams(params))\n return wf.branch([\n [(params: AnyStepParams) => cond(params), branchArm(step, step.then, \"then\", ctx)],\n [(params: AnyStepParams) => !cond(params), branchArm(step, step.otherwise ?? [], \"else\", ctx)],\n ])\n}\n\nfunction parallelBranch(step: ParallelStep, branch: ParallelStep[\"branches\"][number], ctx: LocalWalkerCtx): AnyWorkflowBuilder {\n return createStep({\n id: `${step.id}__${branch.id}`,\n inputSchema: z.any(),\n outputSchema: z.any(),\n execute: async (params: AnyStepParams) => {\n const bindings = bindingsFromParams(params)\n // A LOCAL-only `acc`, deliberately not merged into the shared Mastra\n // `state` from here: branches run concurrently, and `state`/`setState`\n // is a plain read-modify-write with no compare-and-swap, so two\n // branches merging at once silently lose one branch's write. Returning\n // the output and letting `finalizeParallel` read Mastra's OWN\n // concurrency-safe `.parallel()` result (proven correct by the same\n // aggregation `.foreach()` already relies on) avoids that race — the\n // documented trade-off is that a step id nested INSIDE one parallel\n // branch isn't visible to a step OUTSIDE the parallel block (it's\n // still visible to later steps within the SAME branch, via this local\n // `acc`).\n const acc: Record<string, unknown> = { ...bindings.steps }\n return runLocalSteps(branch.steps, bindings, acc, ctx)\n },\n })\n}\n\nfunction finalizeParallel(step: ParallelStep): AnyWorkflowBuilder {\n return createStep({\n id: `${step.id}__finalize`,\n inputSchema: z.any(),\n outputSchema: z.any(),\n execute: async (params: AnyStepParams) => {\n // `params.inputData` is Mastra's own safely-aggregated `.parallel()`\n // result, keyed by each branch step's (synthetic) Mastra step id.\n const raw = (params.inputData as Record<string, unknown> | undefined) ?? {}\n const record: Record<string, unknown> = {}\n for (const branch of step.branches) record[branch.id] = raw[`${step.id}__${branch.id}`]\n await mergeStateSteps(params, { [step.id]: record })\n return record\n },\n })\n}\n\nfunction attachParallel(wf: AnyWorkflowBuilder, step: ParallelStep, ctx: LocalWalkerCtx): AnyWorkflowBuilder {\n return wf.parallel(step.branches.map((branch) => parallelBranch(step, branch, ctx))).then(finalizeParallel(step))\n}\n\nfunction computeMapItems(step: MapStep): AnyWorkflowBuilder {\n return createStep({\n id: `${step.id}__items`,\n inputSchema: z.any(),\n outputSchema: z.any(),\n execute: async (params: AnyStepParams) => [...step.over(bindingsFromParams(params))],\n })\n}\n\nfunction mapBody(step: MapStep, ctx: LocalWalkerCtx): AnyWorkflowBuilder {\n return createStep({\n id: `${step.id}__body`,\n inputSchema: z.any(),\n outputSchema: z.any(),\n execute: async (params: AnyStepParams) => {\n const outer = bindingsFromParams(params)\n const item = params.inputData\n // `.foreach()` doesn't expose the element's index to the body step, so\n // `$index` isn't resolvable inside a projected map body — documented\n // in the README alongside the other fidelity gaps.\n const itemBindings: Bindings = { ...outer, item, index: undefined }\n const acc: Record<string, unknown> = { ...outer.steps }\n const inner = step.body(item, -1, itemBindings)\n return runLocalStep(inner, itemBindings, acc, ctx)\n // Deliberately not merged back into shared `state`: foreach iterations\n // run concurrently (a `setState` race), and per-item nested ids aren't\n // addressable from outside the map in the engine's own model either.\n },\n })\n}\n\nfunction attachMap(wf: AnyWorkflowBuilder, step: MapStep, ctx: LocalWalkerCtx): AnyWorkflowBuilder {\n return wf\n .then(computeMapItems(step))\n .foreach(mapBody(step, ctx), step.parallelism ? { concurrency: step.parallelism } : undefined)\n .then(bindResultStep(step.id))\n}\n\nfunction loopBody(step: LoopStep, ctx: LocalWalkerCtx): AnyWorkflowBuilder {\n return createStep({\n id: `${step.id}__body`,\n inputSchema: z.any(),\n outputSchema: z.any(),\n execute: async (params: AnyStepParams) => {\n const bindings = bindingsFromParams(params)\n // Mastra's `.dowhile()` checks its condition AFTER the body runs (do-\n // semantics); the engine's LoopStep checks `while` BEFORE every\n // iteration, including the first. Guarding here keeps the body's side\n // effects (tool calls) from firing on an already-false condition — the\n // `.dowhile()` condition below still fires once more to actually stop\n // the loop, but no step work happens on that trailing check.\n if (!step.while(bindings)) return undefined\n const acc: Record<string, unknown> = { ...bindings.steps }\n const output = await runLocalSteps(step.body, bindings, acc, ctx)\n await mergeStateSteps(params, acc)\n return output\n },\n })\n}\n\nfunction attachLoop(wf: AnyWorkflowBuilder, step: LoopStep, ctx: LocalWalkerCtx): AnyWorkflowBuilder {\n return wf\n .dowhile(loopBody(step, ctx), async (params: AnyStepParams) => {\n const bindings = bindingsFromParams(params)\n // `iterationCount` is Mastra's own native loop counter — enforcing\n // `maxIterations` here closes the gap `packages/workflow/README.md`'s\n // design spec flagged (\"no hard iteration cap ... not solved here\").\n return step.while(bindings) && params.iterationCount < step.maxIterations\n })\n .then(bindResultStep(step.id))\n}\n\nfunction attachStep(wf: AnyWorkflowBuilder, step: RunStep, ctx: LocalWalkerCtx): AnyWorkflowBuilder {\n switch (step.kind) {\n case \"branch\":\n return attachBranch(wf, step, ctx)\n case \"parallel\":\n return attachParallel(wf, step, ctx)\n case \"map\":\n return attachMap(wf, step, ctx)\n case \"loop\":\n return attachLoop(wf, step, ctx)\n default:\n // tool / transform / agent / group / subworkflow: one opaque step.\n return wf.then(atomicWrapper(step, ctx))\n }\n}\n\n/**\n * Project a compiled {@link RuntimeWorkflow} onto a Mastra `createWorkflow`.\n * Throws {@link WorkflowProjectionError} eagerly — before building any Mastra\n * primitive — if the step graph (including nested `subworkflow` children)\n * contains a `suspend`, `approval`, or `pipeline` step; see the README for why.\n */\nexport function toMastraWorkflow(\n compiled: RuntimeWorkflow,\n opts: ToMastraWorkflowOptions = {},\n): AnyWorkflowBuilder {\n assertProjectable(compiled.steps)\n const ctx: LocalWalkerCtx = { agents: opts.agents, cwd: opts.cwd, workspaceSlug: opts.workspaceSlug }\n\n let wf: AnyWorkflowBuilder = createWorkflow({\n id: compiled.id,\n description: compiled.description,\n inputSchema: z.any(),\n outputSchema: z.any(),\n })\n for (const step of compiled.steps) {\n wf = attachStep(wf, step, ctx)\n }\n return wf.commit()\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@agentproto/workflow-mastra",
3
+ "version": "0.1.0",
4
+ "description": "@agentproto/workflow-mastra — project an AIP-15 WORKFLOW.md's compiled RuntimeWorkflow onto a Mastra `createWorkflow`. Runtime projection (same one-level-up relationship `toMastraTool` has to `implementTool`): tool steps dispatch through the same `runTool` resolver the engine itself uses, and control-flow kinds (branch/parallel/map/loop/subworkflow) map onto Mastra's native `.branch()/.parallel()/.foreach()/.dowhile()` combinators. Kinds with no clean Mastra target (`suspend`, `approval`) fail loud instead of silently dropping.",
5
+ "keywords": [
6
+ "agentproto",
7
+ "aip-15",
8
+ "workflow",
9
+ "mastra",
10
+ "projection",
11
+ "adapter",
12
+ "open-standard"
13
+ ],
14
+ "homepage": "https://agentproto.sh/docs/aip-15",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/agentproto/ts",
18
+ "directory": "packages/workflow-mastra"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/agentproto/ts/issues"
22
+ },
23
+ "license": "Apache-2.0",
24
+ "type": "module",
25
+ "main": "dist/index.mjs",
26
+ "module": "dist/index.mjs",
27
+ "types": "dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.mjs",
32
+ "default": "./dist/index.mjs"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "README.md",
39
+ "LICENSE"
40
+ ],
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "dependencies": {
45
+ "@agentproto/driver": "0.2.0",
46
+ "@agentproto/tool": "0.2.1",
47
+ "@agentproto/workflow-runtime": "0.6.0"
48
+ },
49
+ "peerDependencies": {
50
+ "@mastra/core": "*",
51
+ "zod": "^4.0.0"
52
+ },
53
+ "devDependencies": {
54
+ "@mastra/core": "1.52.1",
55
+ "@types/node": "^25.6.2",
56
+ "tsup": "^8.5.1",
57
+ "typescript": "^5.9.3",
58
+ "vitest": "^3.2.4",
59
+ "zod": "^4.4.3",
60
+ "@agentproto/tooling": "0.1.0-alpha.0"
61
+ },
62
+ "scripts": {
63
+ "dev": "tsup --watch",
64
+ "build": "tsup",
65
+ "clean": "rm -rf dist",
66
+ "check-types": "tsc --noEmit",
67
+ "test": "vitest run",
68
+ "test:watch": "vitest"
69
+ }
70
+ }