@agentproto/workflow-mastra 0.1.11 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +85 -8
- package/dist/index.d.ts +33 -2
- package/dist/index.mjs +135 -11
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -11,13 +11,24 @@ codegen — same one-level-up relationship
|
|
|
11
11
|
## Usage
|
|
12
12
|
|
|
13
13
|
```ts
|
|
14
|
+
import { Mastra } from "@mastra/core"
|
|
14
15
|
import { compileWorkflowManifest } from "@agentproto/workflow-runtime"
|
|
15
16
|
import { toMastraWorkflow } from "@agentproto/workflow-mastra"
|
|
16
17
|
|
|
17
18
|
const compiled = compileWorkflowManifest(workflowMdSource, { tools, candidates })
|
|
18
|
-
const mastraWorkflow = toMastraWorkflow(compiled, {
|
|
19
|
+
const mastraWorkflow = toMastraWorkflow(compiled, {
|
|
20
|
+
agents: mySessionHost,
|
|
21
|
+
// The manifest's own `inputs` block (shorthand or JSON Schema) — a compiled
|
|
22
|
+
// `RuntimeWorkflow` doesn't carry it forward, so pass it through to get
|
|
23
|
+
// real `invalid-input` rejection instead of `z.any()`.
|
|
24
|
+
inputsSchema: parsedManifest.inputs,
|
|
25
|
+
})
|
|
19
26
|
|
|
20
|
-
|
|
27
|
+
// suspend/resume needs storage to look its run snapshot up from — register
|
|
28
|
+
// with a `Mastra` instance (any adapter; the default in-memory store is fine
|
|
29
|
+
// for a process-local run) if the workflow has a top-level `suspend`/`approval` step.
|
|
30
|
+
const mastra = new Mastra({ workflows: { [mastraWorkflow.id]: mastraWorkflow } })
|
|
31
|
+
const run = await mastra.getWorkflow(mastraWorkflow.id).createRun()
|
|
21
32
|
const result = await run.start({ inputData: { chatId: "…" } })
|
|
22
33
|
```
|
|
23
34
|
|
|
@@ -25,20 +36,86 @@ const result = await run.start({ inputData: { chatId: "…" } })
|
|
|
25
36
|
|
|
26
37
|
| `RunStep.kind` | Mastra primitive |
|
|
27
38
|
|---|---|
|
|
28
|
-
| `tool` | `createStep({execute})` wrapping the same `runTool` dispatch the engine itself uses |
|
|
39
|
+
| `tool` | `createStep({execute})` wrapping the same `runTool` dispatch the engine itself uses; `outputSchema` is the TOOL contract's real `outputSchema` (or its JSON-Schema `outputs`, converted) when declared |
|
|
29
40
|
| `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) |
|
|
41
|
+
| `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); when the step declares an `outputSchema`, the Mastra step's `outputSchema` is `{ sessionId, output: <declared> }` — the REAL shape `execute()` returns, not the bare declared schema |
|
|
31
42
|
| `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
43
|
| `branch` | `.branch([[cond, thenStep], [negatedCond, elseStep]])` |
|
|
33
44
|
| `parallel` | `.parallel([...branchSteps])` |
|
|
34
45
|
| `map` | `.foreach(bodyStep, { concurrency })` |
|
|
35
46
|
| `loop` | `.dowhile(bodyStep, condition)` — `condition` combines `LoopStep.while` with Mastra's native `iterationCount`, so `maxIterations` is enforced without a synthetic counter step |
|
|
36
47
|
| `subworkflow` | delegates to `runWorkflow` for the child (isolated bindings, matching `SubworkflowStep`'s own documented semantics) |
|
|
37
|
-
| `suspend
|
|
48
|
+
| `suspend` (top-level only) | native Mastra `suspend()`/`resume()` — see [Suspend and approval](#suspend-and-approval) |
|
|
49
|
+
| `approval` (top-level only) | native Mastra `suspend()`/`resume()`, then runs `onApprove`/`onReject` through the local walker — see below |
|
|
50
|
+
| `suspend`, `approval` (nested inside a `branch`/`parallel`/`loop`/`map`/`group`) | **not projectable** — no per-step Mastra suspend boundary to attach to inside an enclosing opaque step; throws `WorkflowProjectionError` eagerly |
|
|
51
|
+
| `gate` | **not projectable** — see [Gate](#gate) |
|
|
52
|
+
| `pipeline` | **not projectable** — a `workflow-runtime`-only fan-out kind not covered by the design spec this package implements; NOT silently downgraded to `map` semantics it doesn't have |
|
|
38
53
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
54
|
+
### Schemas
|
|
55
|
+
|
|
56
|
+
The projected workflow's own `inputSchema` (on `createWorkflow`) is built from
|
|
57
|
+
`opts.inputsSchema` (the manifest's `inputs` block) via
|
|
58
|
+
`normalizeWorkflowInputsSchema` + a small local JSON-Schema→zod converter
|
|
59
|
+
(`json-schema-to-zod.ts`; object/string/number/boolean/enum/array/required —
|
|
60
|
+
falls back to `z.any()` for anything it can't represent faithfully, e.g.
|
|
61
|
+
`oneOf`/`$ref`). `run.start()` rejects invalid `inputData` against it BEFORE
|
|
62
|
+
any step's `execute` runs — the same `invalid-input` semantics as
|
|
63
|
+
`validateWorkflowInput`; `mapMastraInputError` translates Mastra's own thrown
|
|
64
|
+
`MastraError` (`id: "WORKFLOW_SCHEMA_VALIDATION_FAILED"`) back to that shape.
|
|
65
|
+
Object conversion is deliberately LOOSE (`z.looseObject`, not `z.object`):
|
|
66
|
+
Mastra's `inputSchema` re-parses `inputData`, and a strict object schema
|
|
67
|
+
would silently strip any input field the manifest's `inputs` block doesn't
|
|
68
|
+
declare — before a single step ever reads it via `$input.*`.
|
|
69
|
+
|
|
70
|
+
Every PER-STEP `inputSchema` stays `z.any()`, regardless of kind — this is
|
|
71
|
+
deliberate, not an oversight. Mastra validates a step's `inputSchema` against
|
|
72
|
+
`params.inputData`, which is the MECHANICALLY preceding Mastra step's raw
|
|
73
|
+
output; every wrapper in this package computes its real input from the run's
|
|
74
|
+
shared `bindings` via a selector instead (the whole point of the AIP-16 IO
|
|
75
|
+
seam — non-linear `$steps.<id>` reads), so `inputData` never corresponds to a
|
|
76
|
+
step's actual input once a workflow has more than one step. Setting a real
|
|
77
|
+
`inputSchema` there doesn't add safety, it breaks chaining (verified: Mastra
|
|
78
|
+
throws `WORKFLOW_STEP_INPUT_VALIDATION_FAILED` on the very first multi-step
|
|
79
|
+
fixture). `runTool` already validates a tool's real input at the correct
|
|
80
|
+
layer, before dispatch.
|
|
81
|
+
|
|
82
|
+
### Suspend and approval
|
|
83
|
+
|
|
84
|
+
A top-level `suspend`/`approval` step (a direct child of the workflow, not
|
|
85
|
+
nested in a `branch`/`parallel`/`loop`/`map`/`group`) gets its own Mastra step
|
|
86
|
+
with real `suspendSchema`/`resumeSchema`, using Mastra's native
|
|
87
|
+
`params.suspend()` / `run.resume({ step, resumeData })` — no more re-running
|
|
88
|
+
the whole workflow from a persisted `WorkflowSuspendedError`. `suspend`
|
|
89
|
+
resumes with the raw resume payload (bound under the step's id, matching
|
|
90
|
+
`run-workflow.ts`'s own `ctx.resume({stepId, on})` contract); `approval`
|
|
91
|
+
resumes with an `{approved, who, note?}` decision and then runs
|
|
92
|
+
`onApprove`/`onReject` through the local walker, merging their outputs into
|
|
93
|
+
the shared `$steps` bindings exactly like `run-workflow.ts`'s own `"approval"`
|
|
94
|
+
case. Unlike the plain runtime (which auto-approves when no `approve` hook is
|
|
95
|
+
given), the projected `approval` step ALWAYS suspends — Mastra has no
|
|
96
|
+
per-projection equivalent of a per-run `approve` callback to fall back to; a
|
|
97
|
+
caller wanting auto-approve resumes immediately with
|
|
98
|
+
`{approved: true, who: "host"}` itself.
|
|
99
|
+
|
|
100
|
+
`run.resume()` looks its run up from storage, so a workflow with a top-level
|
|
101
|
+
suspend/approval needs to be registered with a `Mastra` instance (see
|
|
102
|
+
Usage above) — `toMastraWorkflow` builds the workflow but deliberately
|
|
103
|
+
doesn't own storage or other host wiring.
|
|
104
|
+
|
|
105
|
+
Nested inside a composite, `suspend`/`approval` stay refused: they'd run
|
|
106
|
+
through the local step-walker inside an ENCLOSING opaque step's `execute`,
|
|
107
|
+
which has no Mastra step of its own to call `suspend()` from.
|
|
108
|
+
|
|
109
|
+
### Gate
|
|
110
|
+
|
|
111
|
+
`kind: "gate"` is refused, everywhere, with an explicit reason — not faked.
|
|
112
|
+
`run-workflow.ts`'s real `GateStep` executor resolves `$input`/`$item`/
|
|
113
|
+
`$steps.<id>` ref-string args and cwd, and drives its `onFail.reprompt` retry
|
|
114
|
+
through the SAME private machinery (`resolveRefString`, the default
|
|
115
|
+
`execFile`-backed command runner) — none of it is a public seam this package
|
|
116
|
+
can import and reuse. Re-implementing that resolution grammar here, separate
|
|
117
|
+
from the canonical implementation, would silently drift from it rather than
|
|
118
|
+
run the identical gate a daemon run would.
|
|
42
119
|
|
|
43
120
|
## Known limitations
|
|
44
121
|
|
package/dist/index.d.ts
CHANGED
|
@@ -9,6 +9,25 @@ import { AgentSessionHost, RuntimeWorkflow } from '@agentproto/workflow-runtime'
|
|
|
9
9
|
declare class WorkflowProjectionError extends Error {
|
|
10
10
|
constructor(message: string);
|
|
11
11
|
}
|
|
12
|
+
/** AIP-58 §10 shape for a rejected run's input — mirrors (without importing,
|
|
13
|
+
* to avoid a hard dependency loop) `@agentproto/workflow-runtime`'s own
|
|
14
|
+
* `WorkflowInputValidation`'s failure case. */
|
|
15
|
+
interface MastraInputValidationError {
|
|
16
|
+
code: "invalid-input";
|
|
17
|
+
fields: readonly string[];
|
|
18
|
+
message: string;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Map the error `run.start()` throws when the projected workflow's own
|
|
22
|
+
* `inputSchema` (see {@link toMastraWorkflow}'s `inputsSchema` option)
|
|
23
|
+
* rejects `inputData`, to the same `{ code: "invalid-input", fields, message
|
|
24
|
+
* }` shape `validateWorkflowInput` produces — so a caller doesn't need to
|
|
25
|
+
* know Mastra threw a `MastraError` with id `WORKFLOW_SCHEMA_VALIDATION_FAILED`
|
|
26
|
+
* and parse its message by hand. `undefined` for any other error (including a
|
|
27
|
+
* step-level failure, which this projector never wants confused with a
|
|
28
|
+
* rejected run).
|
|
29
|
+
*/
|
|
30
|
+
declare function mapMastraInputError(err: unknown): MastraInputValidationError | undefined;
|
|
12
31
|
|
|
13
32
|
/**
|
|
14
33
|
* @agentproto/workflow-mastra — project a compiled AIP-15 {@link RuntimeWorkflow}
|
|
@@ -31,14 +50,26 @@ interface ToMastraWorkflowOptions {
|
|
|
31
50
|
cwd?: string;
|
|
32
51
|
/** Workspace slug for spawned agent sessions. */
|
|
33
52
|
workspaceSlug?: string;
|
|
53
|
+
/**
|
|
54
|
+
* The AIP-16 `inputs` block off the source WORKFLOW.md's frontmatter
|
|
55
|
+
* (shorthand flat map or canonical JSON Schema — same shape
|
|
56
|
+
* `normalizeWorkflowInputsSchema` accepts). A compiled {@link RuntimeWorkflow}
|
|
57
|
+
* doesn't carry this forward on its own (`compileWorkflowManifest` discards
|
|
58
|
+
* the manifest once it's compiled the step graph), so the caller re-supplies
|
|
59
|
+
* it here to get real `invalid-input` rejection at the Mastra layer instead
|
|
60
|
+
* of `z.any()`. Omit for a workflow that accepts anything.
|
|
61
|
+
*/
|
|
62
|
+
inputsSchema?: unknown;
|
|
34
63
|
}
|
|
35
64
|
type AnyWorkflowBuilder = any;
|
|
36
65
|
/**
|
|
37
66
|
* Project a compiled {@link RuntimeWorkflow} onto a Mastra `createWorkflow`.
|
|
38
67
|
* Throws {@link WorkflowProjectionError} eagerly — before building any Mastra
|
|
39
68
|
* primitive — if the step graph (including nested `subworkflow` children)
|
|
40
|
-
* contains a `
|
|
69
|
+
* contains a `gate`, `pipeline`, or a NESTED `suspend`/`approval`; see the
|
|
70
|
+
* README for why. A top-level `suspend`/`approval` now projects to native
|
|
71
|
+
* Mastra suspend/resume instead.
|
|
41
72
|
*/
|
|
42
73
|
declare function toMastraWorkflow(compiled: RuntimeWorkflow, opts?: ToMastraWorkflowOptions): AnyWorkflowBuilder;
|
|
43
74
|
|
|
44
|
-
export { type ToMastraWorkflowOptions, WorkflowProjectionError, toMastraWorkflow };
|
|
75
|
+
export { type MastraInputValidationError, type ToMastraWorkflowOptions, WorkflowProjectionError, mapMastraInputError, toMastraWorkflow };
|
package/dist/index.mjs
CHANGED
|
@@ -1,31 +1,38 @@
|
|
|
1
1
|
import { createWorkflow, createStep } from '@mastra/core/workflows';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
+
import { normalizeWorkflowInputsSchema, runWorkflow } from '@agentproto/workflow-runtime';
|
|
4
|
+
import { MastraError } from '@mastra/core/error';
|
|
3
5
|
import { runTool } from '@agentproto/driver';
|
|
4
|
-
import { runWorkflow } from '@agentproto/workflow-runtime';
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* @agentproto/workflow-mastra v0.1.0-alpha
|
|
8
9
|
* AIP-15 WORKFLOW.md → Mastra createWorkflow projection.
|
|
9
10
|
*/
|
|
10
11
|
|
|
11
|
-
|
|
12
|
-
// src/errors.ts
|
|
13
12
|
var WorkflowProjectionError = class extends Error {
|
|
14
13
|
constructor(message) {
|
|
15
14
|
super(`toMastraWorkflow: ${message}`);
|
|
16
15
|
this.name = "WorkflowProjectionError";
|
|
17
16
|
}
|
|
18
17
|
};
|
|
18
|
+
function mapMastraInputError(err) {
|
|
19
|
+
if (!(err instanceof MastraError) || err.id !== "WORKFLOW_SCHEMA_VALIDATION_FAILED") return void 0;
|
|
20
|
+
const fields = [...new Set([...err.message.matchAll(/\n-\s*([^:]+):/g)].map((m) => m[1].trim()))];
|
|
21
|
+
return { code: "invalid-input", fields, message: err.message };
|
|
22
|
+
}
|
|
19
23
|
|
|
20
24
|
// src/assert-projectable.ts
|
|
21
|
-
var
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
+
var ALWAYS_UNPROJECTABLE_REASON = {
|
|
26
|
+
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.",
|
|
27
|
+
gate: "GateStep's real executor (run-workflow.ts's execGateStep) resolves `$input|$item|$steps.<id>` ref-string args/cwd and drives its onFail reprompt through the same private machinery \u2014 none of it is a public seam this package can reuse, and re-implementing that resolution grammar here would silently drift from the canonical semantics rather than run the SAME gate a daemon run would. Not faked."
|
|
28
|
+
};
|
|
29
|
+
var NESTED_ONLY_UNPROJECTABLE_REASON = {
|
|
30
|
+
suspend: "nested inside a branch/parallel/loop/map/group, a SuspendStep runs through the local step-walker, which has no Mastra step of its own to call `suspend()` from \u2014 only a step that is a direct top-level child of the workflow gets native Mastra suspend/resume.",
|
|
31
|
+
approval: "nested inside a branch/parallel/loop/map/group, an ApprovalStep runs through the local step-walker, which has no Mastra step of its own to call `suspend()` from \u2014 only a step that is a direct top-level child of the workflow gets native Mastra suspend/resume."
|
|
25
32
|
};
|
|
26
33
|
function assertProjectable(steps, path = "") {
|
|
27
34
|
for (const step of steps) {
|
|
28
|
-
const reason =
|
|
35
|
+
const reason = ALWAYS_UNPROJECTABLE_REASON[step.kind] ?? (path !== "" ? NESTED_ONLY_UNPROJECTABLE_REASON[step.kind] : void 0);
|
|
29
36
|
if (reason) {
|
|
30
37
|
throw new WorkflowProjectionError(
|
|
31
38
|
`step '${path}${step.id}' (kind '${step.kind}') is not projectable to Mastra \u2014 ${reason}`
|
|
@@ -156,11 +163,46 @@ async function runLocalStep(step, bindings, acc, ctx) {
|
|
|
156
163
|
case "suspend":
|
|
157
164
|
case "approval":
|
|
158
165
|
case "pipeline":
|
|
166
|
+
case "gate":
|
|
159
167
|
throw new WorkflowProjectionError(
|
|
160
168
|
`step '${step.id}' (kind '${step.kind}') reached the local walker \u2014 this should have been rejected by assertProjectable first`
|
|
161
169
|
);
|
|
162
170
|
}
|
|
163
171
|
}
|
|
172
|
+
var isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
173
|
+
function jsonSchemaToZod(schema) {
|
|
174
|
+
if (!isPlainObject(schema)) return z.any();
|
|
175
|
+
if (Array.isArray(schema["enum"])) {
|
|
176
|
+
const values = schema["enum"];
|
|
177
|
+
if (values.length > 0 && values.every((v) => typeof v === "string")) {
|
|
178
|
+
return z.enum(values);
|
|
179
|
+
}
|
|
180
|
+
return z.any();
|
|
181
|
+
}
|
|
182
|
+
switch (schema["type"]) {
|
|
183
|
+
case "object": {
|
|
184
|
+
const properties = isPlainObject(schema["properties"]) ? schema["properties"] : {};
|
|
185
|
+
const required = new Set(Array.isArray(schema["required"]) ? schema["required"] : []);
|
|
186
|
+
const shape = {};
|
|
187
|
+
for (const [key, propSchema] of Object.entries(properties)) {
|
|
188
|
+
const propType = jsonSchemaToZod(propSchema);
|
|
189
|
+
shape[key] = required.has(key) ? propType : propType.optional();
|
|
190
|
+
}
|
|
191
|
+
return z.looseObject(shape);
|
|
192
|
+
}
|
|
193
|
+
case "string":
|
|
194
|
+
return z.string();
|
|
195
|
+
case "number":
|
|
196
|
+
case "integer":
|
|
197
|
+
return z.number();
|
|
198
|
+
case "boolean":
|
|
199
|
+
return z.boolean();
|
|
200
|
+
case "array":
|
|
201
|
+
return z.array(schema["items"] !== void 0 ? jsonSchemaToZod(schema["items"]) : z.any());
|
|
202
|
+
default:
|
|
203
|
+
return z.any();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
164
206
|
|
|
165
207
|
// src/index.ts
|
|
166
208
|
function bindingsFromParams(params) {
|
|
@@ -171,11 +213,25 @@ async function mergeStateSteps(params, patch) {
|
|
|
171
213
|
const prior = params.state?.steps ?? {};
|
|
172
214
|
await params.setState({ steps: { ...prior, ...patch } });
|
|
173
215
|
}
|
|
216
|
+
function atomicOutputSchema(step) {
|
|
217
|
+
switch (step.kind) {
|
|
218
|
+
case "tool": {
|
|
219
|
+
const tool = step.tool;
|
|
220
|
+
if (tool.outputSchema) return tool.outputSchema;
|
|
221
|
+
if (tool.outputs) return jsonSchemaToZod(tool.outputs);
|
|
222
|
+
return z.any();
|
|
223
|
+
}
|
|
224
|
+
case "agent":
|
|
225
|
+
return step.outputSchema ? z.object({ sessionId: z.string(), output: step.outputSchema }) : z.any();
|
|
226
|
+
default:
|
|
227
|
+
return z.any();
|
|
228
|
+
}
|
|
229
|
+
}
|
|
174
230
|
function atomicWrapper(step, ctx) {
|
|
175
231
|
return createStep({
|
|
176
232
|
id: step.id,
|
|
177
233
|
inputSchema: z.any(),
|
|
178
|
-
outputSchema:
|
|
234
|
+
outputSchema: atomicOutputSchema(step),
|
|
179
235
|
execute: async (params) => {
|
|
180
236
|
const bindings = bindingsFromParams(params);
|
|
181
237
|
const acc = { ...bindings.steps };
|
|
@@ -185,6 +241,68 @@ function atomicWrapper(step, ctx) {
|
|
|
185
241
|
}
|
|
186
242
|
});
|
|
187
243
|
}
|
|
244
|
+
function suspendWrapper(step) {
|
|
245
|
+
return createStep({
|
|
246
|
+
id: step.id,
|
|
247
|
+
inputSchema: z.any(),
|
|
248
|
+
outputSchema: z.any(),
|
|
249
|
+
resumeSchema: z.any(),
|
|
250
|
+
suspendSchema: z.object({ reason: z.literal("suspend"), prompt: z.string(), on: z.array(z.string()) }),
|
|
251
|
+
execute: async (params) => {
|
|
252
|
+
if (params.resumeData !== void 0) {
|
|
253
|
+
await mergeStateSteps(params, { [step.id]: params.resumeData });
|
|
254
|
+
return params.resumeData;
|
|
255
|
+
}
|
|
256
|
+
return params.suspend({
|
|
257
|
+
reason: "suspend",
|
|
258
|
+
prompt: `workflow suspended at step '${step.id}' awaiting [${step.on.join(", ")}]`,
|
|
259
|
+
on: step.on
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
var approvalResumeSchema = z.object({
|
|
265
|
+
approved: z.boolean(),
|
|
266
|
+
who: z.string(),
|
|
267
|
+
note: z.string().optional()
|
|
268
|
+
});
|
|
269
|
+
function approvalWrapper(step, ctx) {
|
|
270
|
+
return createStep({
|
|
271
|
+
id: step.id,
|
|
272
|
+
inputSchema: z.any(),
|
|
273
|
+
outputSchema: z.any(),
|
|
274
|
+
resumeSchema: approvalResumeSchema,
|
|
275
|
+
suspendSchema: z.object({
|
|
276
|
+
reason: z.literal("approval"),
|
|
277
|
+
prompt: z.string(),
|
|
278
|
+
approvers: z.array(z.string()),
|
|
279
|
+
artifacts: z.array(z.string()).optional()
|
|
280
|
+
}),
|
|
281
|
+
execute: async (params) => {
|
|
282
|
+
const bindings = bindingsFromParams(params);
|
|
283
|
+
if (params.resumeData === void 0) {
|
|
284
|
+
return params.suspend({
|
|
285
|
+
reason: "approval",
|
|
286
|
+
prompt: step.prompt(bindings),
|
|
287
|
+
approvers: step.approvers ?? [],
|
|
288
|
+
...step.artifacts !== void 0 ? { artifacts: step.artifacts } : {}
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
const decision = params.resumeData;
|
|
292
|
+
const followups = decision.approved ? step.onApprove ?? [] : step.onReject ?? [];
|
|
293
|
+
const acc = { ...bindings.steps };
|
|
294
|
+
await runLocalSteps(followups, bindings, acc, ctx);
|
|
295
|
+
const output = {
|
|
296
|
+
approved: decision.approved,
|
|
297
|
+
who: decision.who,
|
|
298
|
+
...decision.note !== void 0 ? { note: decision.note } : {}
|
|
299
|
+
};
|
|
300
|
+
acc[step.id] = output;
|
|
301
|
+
await mergeStateSteps(params, acc);
|
|
302
|
+
return output;
|
|
303
|
+
}
|
|
304
|
+
});
|
|
305
|
+
}
|
|
188
306
|
function bindResultStep(id) {
|
|
189
307
|
return createStep({
|
|
190
308
|
id: `${id}__bind`,
|
|
@@ -304,6 +422,12 @@ function attachStep(wf, step, ctx) {
|
|
|
304
422
|
return attachMap(wf, step, ctx);
|
|
305
423
|
case "loop":
|
|
306
424
|
return attachLoop(wf, step, ctx);
|
|
425
|
+
// Only reachable at the TOP level — assertProjectable already rejected a
|
|
426
|
+
// nested suspend/approval before attachStep ever sees one.
|
|
427
|
+
case "suspend":
|
|
428
|
+
return wf.then(suspendWrapper(step));
|
|
429
|
+
case "approval":
|
|
430
|
+
return wf.then(approvalWrapper(step, ctx));
|
|
307
431
|
default:
|
|
308
432
|
return wf.then(atomicWrapper(step, ctx));
|
|
309
433
|
}
|
|
@@ -314,7 +438,7 @@ function toMastraWorkflow(compiled, opts = {}) {
|
|
|
314
438
|
let wf = createWorkflow({
|
|
315
439
|
id: compiled.id,
|
|
316
440
|
description: compiled.description,
|
|
317
|
-
inputSchema:
|
|
441
|
+
inputSchema: jsonSchemaToZod(normalizeWorkflowInputsSchema(opts.inputsSchema)),
|
|
318
442
|
outputSchema: z.any()
|
|
319
443
|
});
|
|
320
444
|
for (const step of compiled.steps) {
|
|
@@ -323,6 +447,6 @@ function toMastraWorkflow(compiled, opts = {}) {
|
|
|
323
447
|
return wf.commit();
|
|
324
448
|
}
|
|
325
449
|
|
|
326
|
-
export { WorkflowProjectionError, toMastraWorkflow };
|
|
450
|
+
export { WorkflowProjectionError, mapMastraInputError, toMastraWorkflow };
|
|
327
451
|
//# sourceMappingURL=index.mjs.map
|
|
328
452
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +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,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AAI,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"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/assert-projectable.ts","../src/local-walker.ts","../src/json-schema-to-zod.ts","../src/index.ts"],"names":["z"],"mappings":";;;;;;;;;;;AAQO,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;AAqBO,SAAS,oBAAoB,GAAA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,IACtB,WAAA,EAAa,eAAA,CAAgB,6BAAA,CAA8B,IAAA,CAAK,YAAY,CAAC,CAAA;AAAA,IAC7E,YAAA,EAAcA,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":["import { MastraError } from \"@mastra/core/error\"\n\n/**\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\n/** AIP-58 §10 shape for a rejected run's input — mirrors (without importing,\n * to avoid a hard dependency loop) `@agentproto/workflow-runtime`'s own\n * `WorkflowInputValidation`'s failure case. */\nexport interface MastraInputValidationError {\n code: \"invalid-input\"\n fields: readonly string[]\n message: string\n}\n\n/**\n * Map the error `run.start()` throws when the projected workflow's own\n * `inputSchema` (see {@link toMastraWorkflow}'s `inputsSchema` option)\n * rejects `inputData`, to the same `{ code: \"invalid-input\", fields, message\n * }` shape `validateWorkflowInput` produces — so a caller doesn't need to\n * know Mastra threw a `MastraError` with id `WORKFLOW_SCHEMA_VALIDATION_FAILED`\n * and parse its message by hand. `undefined` for any other error (including a\n * step-level failure, which this projector never wants confused with a\n * rejected run).\n */\nexport function mapMastraInputError(err: unknown): MastraInputValidationError | undefined {\n if (!(err instanceof MastraError) || err.id !== \"WORKFLOW_SCHEMA_VALIDATION_FAILED\") return undefined\n const fields = [...new Set([...err.message.matchAll(/\\n-\\s*([^:]+):/g)].map((m) => m[1]!.trim()))]\n return { code: \"invalid-input\", fields, message: err.message }\n}\n","import type { RunStep } from \"@agentproto/workflow-runtime\"\nimport { WorkflowProjectionError } from \"./errors.js\"\n\n/** Unprojectable everywhere — top-level or nested, no exception. */\nconst ALWAYS_UNPROJECTABLE_REASON: Partial<Record<RunStep[\"kind\"], string>> = {\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 gate:\n \"GateStep's real executor (run-workflow.ts's execGateStep) resolves \" +\n \"`$input|$item|$steps.<id>` ref-string args/cwd and drives its onFail \" +\n \"reprompt through the same private machinery — none of it is a public \" +\n \"seam this package can reuse, and re-implementing that resolution grammar \" +\n \"here would silently drift from the canonical semantics rather than run \" +\n \"the SAME gate a daemon run would. Not faked.\",\n}\n\n/**\n * Unprojectable ONLY when nested inside a branch/parallel/loop/map/group\n * (i.e. reachable only through the local step-walker, not a real Mastra\n * step). A DIRECT top-level child of the workflow gets its own `createStep`\n * and so a real Mastra `suspend`/`resume` pair — see `suspendWrapper` /\n * `approvalWrapper` in `index.ts`. Nested, there is no per-step suspend\n * boundary to attach to: the local walker calling `params.suspend()` from\n * inside an ENCLOSING opaque step's `execute` would suspend the wrong step.\n */\nconst NESTED_ONLY_UNPROJECTABLE_REASON: Partial<Record<RunStep[\"kind\"], string>> = {\n suspend:\n \"nested inside a branch/parallel/loop/map/group, a SuspendStep runs \" +\n \"through the local step-walker, which has no Mastra step of its own to \" +\n \"call `suspend()` from — only a step that is a direct top-level child of \" +\n \"the workflow gets native Mastra suspend/resume.\",\n approval:\n \"nested inside a branch/parallel/loop/map/group, an ApprovalStep runs \" +\n \"through the local step-walker, which has no Mastra step of its own to \" +\n \"call `suspend()` from — only a step that is a direct top-level child of \" +\n \"the workflow gets native Mastra suspend/resume.\",\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 =\n ALWAYS_UNPROJECTABLE_REASON[step.kind] ?? (path !== \"\" ? NESTED_ONLY_UNPROJECTABLE_REASON[step.kind] : undefined)\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 case \"gate\":\n // Unreachable: assertProjectable rejects `gate`/`pipeline` everywhere,\n // and `suspend`/`approval` everywhere EXCEPT top-level (where they get\n // their own Mastra step in index.ts and never reach this walker at all).\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 * A small, deliberately partial JSON Schema to zod converter for projecting a\n * workflow's (or a manifest-only tool's) declared AIP-16 IO schema onto a\n * Mastra step/workflow inputSchema/outputSchema. Not a general JSON Schema\n * compiler -- object (with properties/required), string, number/integer,\n * boolean, array, and a string-only top-level enum are converted; anything\n * else (oneOf/anyOf/$ref/tuple items/etc.) falls back to z.any() rather than\n * guessing at a shape it can't represent faithfully. The repo's\n * json-schema-to-zod devDependency emits a STRING of zod source for codegen\n * (scripts/scaffold-aip.mjs) -- no use here, where a live ZodType is needed\n * for a schema only known at projection time.\n *\n * Object conversion is deliberately LOOSE (z.looseObject, not z.object):\n * Mastra's workflow-level inputSchema doesn't just validate run.start()'s\n * inputData, it re-parses it, and a plain z.object() strips any key not\n * listed in properties -- silently dropping workflow input fields the\n * manifest's inputs block never declared, before a single step ever reads\n * them via $input.*. A strict schema here would be actively destructive.\n */\n\nimport { z, type ZodTypeAny } from \"zod\"\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v)\n\n/** Convert one JSON Schema node to a zod type. Unsupported shapes fall back to `z.any()`. */\nexport function jsonSchemaToZod(schema: unknown): ZodTypeAny {\n if (!isPlainObject(schema)) return z.any()\n\n if (Array.isArray(schema[\"enum\"])) {\n const values = schema[\"enum\"]\n if (values.length > 0 && values.every((v): v is string => typeof v === \"string\")) {\n return z.enum(values as [string, ...string[]])\n }\n return z.any()\n }\n\n switch (schema[\"type\"]) {\n case \"object\": {\n const properties = isPlainObject(schema[\"properties\"]) ? schema[\"properties\"] : {}\n const required = new Set(Array.isArray(schema[\"required\"]) ? (schema[\"required\"] as unknown[]) : [])\n const shape: Record<string, ZodTypeAny> = {}\n for (const [key, propSchema] of Object.entries(properties)) {\n const propType = jsonSchemaToZod(propSchema)\n shape[key] = required.has(key) ? propType : propType.optional()\n }\n return z.looseObject(shape)\n }\n case \"string\":\n return z.string()\n case \"number\":\n case \"integer\":\n return z.number()\n case \"boolean\":\n return z.boolean()\n case \"array\":\n return z.array(schema[\"items\"] !== undefined ? jsonSchemaToZod(schema[\"items\"]) : z.any())\n default:\n return z.any()\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 ApprovalDecision,\n ApprovalStep,\n BranchStep,\n Bindings,\n LoopStep,\n MapStep,\n ParallelStep,\n RunStep,\n RuntimeWorkflow,\n SuspendStep,\n} from \"@agentproto/workflow-runtime\"\nimport { normalizeWorkflowInputsSchema } from \"@agentproto/workflow-runtime\"\n\nimport { assertProjectable } from \"./assert-projectable.js\"\nimport { runLocalStep, runLocalSteps, type LocalWalkerCtx } from \"./local-walker.js\"\nimport { jsonSchemaToZod } from \"./json-schema-to-zod.js\"\n\nexport { WorkflowProjectionError, mapMastraInputError, type MastraInputValidationError } 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 * The AIP-16 `inputs` block off the source WORKFLOW.md's frontmatter\n * (shorthand flat map or canonical JSON Schema — same shape\n * `normalizeWorkflowInputsSchema` accepts). A compiled {@link RuntimeWorkflow}\n * doesn't carry this forward on its own (`compileWorkflowManifest` discards\n * the manifest once it's compiled the step graph), so the caller re-supplies\n * it here to get real `invalid-input` rejection at the Mastra layer instead\n * of `z.any()`. Omit for a workflow that accepts anything.\n */\n inputsSchema?: unknown\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/**\n * The Mastra `outputSchema` an atomic step should declare for a `RunStep` —\n * real, when the schema exists AND the wrapper's `execute` genuinely returns\n * a value of that shape; `z.any()` otherwise. Never set from a schema the\n * wrapper doesn't actually satisfy: `inputSchema` stays `z.any()` for every\n * atomic step regardless of kind (see the module doc), because Mastra\n * validates a step's `inputSchema` against `params.inputData` — the\n * MECHANICALLY preceding Mastra step's raw output — not against this step's\n * real, selector-computed input; the two are unrelated once a workflow has\n * more than one step; `runTool` already validates a tool's real input at the\n * correct layer.\n */\nfunction atomicOutputSchema(step: RunStep) {\n switch (step.kind) {\n case \"tool\": {\n const tool = step.tool\n if (tool.outputSchema) return tool.outputSchema\n if (tool.outputs) return jsonSchemaToZod(tool.outputs)\n return z.any()\n }\n case \"agent\":\n // `execAgentStep`'s actual return is `{ sessionId, output, ... }`, not\n // the bare declared schema — wrap it so the declared shape matches what\n // `execute()` really produces (Mastra doesn't enforce `outputSchema` at\n // runtime today, but a projected step's schema should still describe\n // its real output, not just echo the contract).\n return step.outputSchema ? z.object({ sessionId: z.string(), output: step.outputSchema }) : z.any()\n default:\n return z.any()\n }\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: atomicOutputSchema(step),\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/**\n * Top-level `SuspendStep` — native Mastra suspend/resume. First entry (no\n * `resumeData` yet): suspend with `{ reason, prompt, on }`, the same `on`\n * signal names `WorkflowSuspendedError` carries in the plain runtime. Resume\n * re-enters this SAME step's `execute` with `resumeData` populated — its\n * value binds under this step's id, matching `run-workflow.ts`'s own\n * `ctx.resume({stepId, on})` contract (the resume payload IS the step's\n * output). No declared schema exists on `SuspendStep` to narrow `resumeSchema`\n * with (unlike `ApprovalStep`'s well-known `{approved,who,note}` shape) — stays\n * `z.any()` per the \"keep z.any() only where nothing is declared\" rule.\n */\nfunction suspendWrapper(step: SuspendStep): AnyWorkflowBuilder {\n return createStep({\n id: step.id,\n inputSchema: z.any(),\n outputSchema: z.any(),\n resumeSchema: z.any(),\n suspendSchema: z.object({ reason: z.literal(\"suspend\"), prompt: z.string(), on: z.array(z.string()) }),\n execute: async (params: AnyStepParams) => {\n if (params.resumeData !== undefined) {\n await mergeStateSteps(params, { [step.id]: params.resumeData })\n return params.resumeData\n }\n return params.suspend({\n reason: \"suspend\" as const,\n prompt: `workflow suspended at step '${step.id}' awaiting [${step.on.join(\", \")}]`,\n on: step.on,\n })\n },\n })\n}\n\nconst approvalResumeSchema = z.object({\n approved: z.boolean(),\n who: z.string(),\n note: z.string().optional(),\n})\n\n/**\n * Top-level `ApprovalStep` — suspends with the approval request, then resumes\n * with an {@link ApprovalDecision}, running `onApprove`/`onReject` through the\n * local walker exactly like `run-workflow.ts`'s own `\"approval\"` case (same\n * shared-bindings merge as `branchArm`). Unlike the plain runtime (which\n * auto-approves when no `approve` hook is given), this ALWAYS suspends —\n * Mastra has no per-projection equivalent of a per-run `approve` callback, so\n * there's no default to fall back to; a caller wanting auto-approve resumes\n * immediately with `{approved: true, who: \"host\"}` itself. Documented in the\n * README, not silently changed behavior.\n */\nfunction approvalWrapper(step: ApprovalStep, ctx: LocalWalkerCtx): AnyWorkflowBuilder {\n return createStep({\n id: step.id,\n inputSchema: z.any(),\n outputSchema: z.any(),\n resumeSchema: approvalResumeSchema,\n suspendSchema: z.object({\n reason: z.literal(\"approval\"),\n prompt: z.string(),\n approvers: z.array(z.string()),\n artifacts: z.array(z.string()).optional(),\n }),\n execute: async (params: AnyStepParams) => {\n const bindings = bindingsFromParams(params)\n if (params.resumeData === undefined) {\n return params.suspend({\n reason: \"approval\" as const,\n prompt: step.prompt(bindings),\n approvers: step.approvers ?? [],\n ...(step.artifacts !== undefined ? { artifacts: step.artifacts } : {}),\n })\n }\n const decision = params.resumeData as ApprovalDecision\n const followups = decision.approved ? (step.onApprove ?? []) : (step.onReject ?? [])\n const acc: Record<string, unknown> = { ...bindings.steps }\n await runLocalSteps(followups, bindings, acc, ctx)\n const output = {\n approved: decision.approved,\n who: decision.who,\n ...(decision.note !== undefined ? { note: decision.note } : {}),\n }\n acc[step.id] = output\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 // Only reachable at the TOP level — assertProjectable already rejected a\n // nested suspend/approval before attachStep ever sees one.\n case \"suspend\":\n return wf.then(suspendWrapper(step))\n case \"approval\":\n return wf.then(approvalWrapper(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 `gate`, `pipeline`, or a NESTED `suspend`/`approval`; see the\n * README for why. A top-level `suspend`/`approval` now projects to native\n * Mastra suspend/resume instead.\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: jsonSchemaToZod(normalizeWorkflowInputsSchema(opts.inputsSchema)),\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
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentproto/workflow-mastra",
|
|
3
|
-
"version": "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,
|
|
3
|
+
"version": "0.2.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/agent steps carry their real declared schemas, tool steps dispatch through the same `runTool` resolver the engine itself uses, control-flow kinds (branch/parallel/map/loop/subworkflow) map onto Mastra's native `.branch()/.parallel()/.foreach()/.dowhile()` combinators, and a top-level `suspend`/`approval` projects to native Mastra suspend/resume. Kinds with no clean Mastra target (`gate`, `pipeline`, a NESTED `suspend`/`approval`) fail loud instead of silently dropping.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentproto",
|
|
7
7
|
"aip-15",
|
|
@@ -42,9 +42,9 @@
|
|
|
42
42
|
"access": "public"
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@agentproto/driver": "0.2.
|
|
46
|
-
"@agentproto/
|
|
47
|
-
"@agentproto/
|
|
45
|
+
"@agentproto/driver": "0.2.4",
|
|
46
|
+
"@agentproto/tool": "0.3.1",
|
|
47
|
+
"@agentproto/workflow-runtime": "0.13.0"
|
|
48
48
|
},
|
|
49
49
|
"peerDependencies": {
|
|
50
50
|
"@mastra/core": "*",
|