@nylorun/harness 0.17.0-beta → 0.19.0-beta

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.
Files changed (45) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/HOST_CONTRACT.md +28 -5
  3. package/dist/compatibility.d.ts +2 -0
  4. package/dist/compatibility.js +2 -0
  5. package/dist/flow/chain.d.ts +8 -0
  6. package/dist/flow/chain.js +27 -0
  7. package/dist/flow/checkpoint.d.ts +21 -0
  8. package/dist/flow/checkpoint.js +15 -0
  9. package/dist/flow/context.d.ts +39 -0
  10. package/dist/flow/context.js +100 -0
  11. package/dist/flow/engine.d.ts +17 -0
  12. package/dist/flow/engine.js +57 -0
  13. package/dist/flow/index.d.ts +7 -0
  14. package/dist/flow/index.js +7 -0
  15. package/dist/flow/limits.d.ts +22 -0
  16. package/dist/flow/limits.js +41 -0
  17. package/dist/flow/loop.d.ts +31 -0
  18. package/dist/flow/loop.js +236 -0
  19. package/dist/flow/map.d.ts +7 -0
  20. package/dist/flow/map.js +64 -0
  21. package/dist/flow/node.d.ts +31 -0
  22. package/dist/flow/node.js +90 -0
  23. package/dist/flow/parallel.d.ts +7 -0
  24. package/dist/flow/parallel.js +47 -0
  25. package/dist/flow/paths.d.ts +19 -0
  26. package/dist/flow/paths.js +23 -0
  27. package/dist/flow/switch.d.ts +8 -0
  28. package/dist/flow/switch.js +35 -0
  29. package/dist/flow/types.d.ts +45 -0
  30. package/dist/flow/types.js +22 -0
  31. package/dist/loop/delegation.d.ts +32 -0
  32. package/dist/loop/delegation.js +136 -0
  33. package/dist/loop/dispatch.js +56 -0
  34. package/dist/loop/invocation.d.ts +7 -1
  35. package/dist/loop/invocation.js +2 -0
  36. package/dist/loop/run.d.ts +2 -1
  37. package/dist/loop/run.js +2 -2
  38. package/dist/run/durable.d.ts +16 -2
  39. package/dist/run/durable.js +109 -81
  40. package/dist/run/index.d.ts +4 -0
  41. package/dist/run/index.js +2 -0
  42. package/dist/types/execution.d.ts +3 -1
  43. package/dist/utils/ids.d.ts +2 -0
  44. package/dist/utils/ids.js +5 -0
  45. package/package.json +2 -2
@@ -0,0 +1,236 @@
1
+ import { HarnessError, isVariantOf } from "@nylorun/core/define";
2
+ import { HostSuspension } from "../loop/host-suspension.js";
3
+ import { createFlowContext, failureOf, settleInFlight } from "./context.js";
4
+ import { assertLoopIteration } from "./limits.js";
5
+ import { joinPath, nodeKeyOf } from "./paths.js";
6
+ import { runNode, unwrapSlot } from "./node.js";
7
+ import { FlowNodeError } from "./types.js";
8
+ /** Host may wrap agent-effect outcomes so the Loop learns the turn's manifest. */
9
+ export const AGENT_TURN_MARKER = "__nylorunAgentTurn";
10
+ export function agentTurnValue(output, agent) {
11
+ return { [AGENT_TURN_MARKER]: 1, output, agent };
12
+ }
13
+ function readAgentTurn(value) {
14
+ if (value &&
15
+ typeof value === "object" &&
16
+ !Array.isArray(value) &&
17
+ value[AGENT_TURN_MARKER] === 1 &&
18
+ "output" in value &&
19
+ "agent" in value) {
20
+ return {
21
+ output: value.output,
22
+ agent: value.agent,
23
+ };
24
+ }
25
+ return { output: value };
26
+ }
27
+ function invalidAgent(path, message) {
28
+ throw new FlowNodeError({ code: "loop.invalid-agent", message, path });
29
+ }
30
+ /**
31
+ * Interpret a root Loop node. Returns effects only; the host journals outcomes.
32
+ */
33
+ export async function runLoop(options) {
34
+ const { manifest, checkpoint, host } = options;
35
+ const root = manifest.root;
36
+ if (!("loop" in root))
37
+ throw new HarnessError("execution.invalid-state", "runLoop expects a loop root");
38
+ const ctx = createFlowContext({
39
+ manifest,
40
+ checkpoint,
41
+ host,
42
+ signal: options.signal,
43
+ limits: options.limits,
44
+ });
45
+ try {
46
+ if (options.signal?.aborted)
47
+ return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
48
+ const output = await runLoopNode(ctx, root.loop, root.loop.id, checkpoint.input);
49
+ return {
50
+ status: "completed",
51
+ checkpoint,
52
+ result: { status: "completed", output },
53
+ };
54
+ }
55
+ catch (error) {
56
+ await settleInFlight(ctx);
57
+ if (error instanceof HostSuspension) {
58
+ return {
59
+ status: [...ctx.pending.values()].includes("uncertain") ? "uncertain" : "waiting",
60
+ checkpoint,
61
+ effectIds: [...ctx.pending.keys()],
62
+ };
63
+ }
64
+ if (error instanceof FlowNodeError && error.failure.code === "cancelled")
65
+ return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
66
+ const failure = failureOf(error, root.loop.id);
67
+ return {
68
+ status: "failed",
69
+ checkpoint,
70
+ result: { status: "failed", error: failure },
71
+ ...(ctx.cancelEffectIds.size > 0 ? { cancelEffectIds: [...ctx.cancelEffectIds] } : {}),
72
+ };
73
+ }
74
+ }
75
+ /**
76
+ * Nested or root Loop body: run → verify → decide until `{ output }` or stop.
77
+ * Agent turn pinning / decide patches (`decision.agent`) are L5.
78
+ */
79
+ export async function runLoopNode(ctx, loop, path, input) {
80
+ let iteration = 1;
81
+ let currentInput = input;
82
+ const history = [];
83
+ const loopInput = input;
84
+ const runIsAgent = "agent" in loop.run;
85
+ // Session pin (first turn's manifest) and the patch carried within this run.
86
+ let pinnedAgent;
87
+ let currentAgent;
88
+ for (;;) {
89
+ if (ctx.signal?.aborted)
90
+ throw new FlowNodeError({ code: "cancelled", message: "cancelled", path });
91
+ // Operator ceiling before starting this iteration (WF-L3 / LOOP-A8).
92
+ assertLoopIteration(iteration, ctx.limits, path);
93
+ ctx.iterations = [...ctx.iterations, iteration];
94
+ const iterations = ctx.iterationsString();
95
+ try {
96
+ let runOutput;
97
+ if (runIsAgent) {
98
+ const agentId = loop.run.agent;
99
+ const agentPath = runPath(path, loop.run);
100
+ const rawAgent = await ctx.effect("agent", {
101
+ agentId,
102
+ input: currentInput,
103
+ path: agentPath,
104
+ ...(currentAgent ? { manifest: currentAgent } : {}),
105
+ }, { path: agentPath, key: nodeKeyOf(agentPath), iterations }, { loopPath: path, n: iteration });
106
+ const turned = readAgentTurn(rawAgent);
107
+ runOutput = turned.output;
108
+ if (turned.agent) {
109
+ // First turn establishes the session pin; later turns may be variants.
110
+ pinnedAgent ??= turned.agent;
111
+ currentAgent = turned.agent;
112
+ }
113
+ }
114
+ else {
115
+ runOutput = await runNode(ctx, loop.run, runPath(path, loop.run), currentInput, {
116
+ ownerInput: loopInput,
117
+ });
118
+ }
119
+ const verdict = await runVerify(ctx, loop.verify, path, {
120
+ input: loopInput,
121
+ output: runOutput,
122
+ iteration,
123
+ });
124
+ let decision;
125
+ try {
126
+ decision = (await ctx.effect("fn", {
127
+ output: runOutput,
128
+ verdict,
129
+ iteration,
130
+ input: loopInput,
131
+ history,
132
+ ...(currentAgent ? { agent: currentAgent } : {}),
133
+ }, { path, key: `${nodeKeyOf(path)}/decide`, iterations }, { loopPath: path, n: iteration, role: "decide" }));
134
+ }
135
+ catch (error) {
136
+ if (error instanceof FlowNodeError && error.failure.code === "fn.failed") {
137
+ throw new FlowNodeError({
138
+ code: "loop.stopped",
139
+ message: error.failure.message,
140
+ path,
141
+ });
142
+ }
143
+ if (error instanceof Error &&
144
+ !(error instanceof HostSuspension) &&
145
+ !(error instanceof FlowNodeError)) {
146
+ throw new FlowNodeError({
147
+ code: "loop.stopped",
148
+ message: error.message,
149
+ path,
150
+ });
151
+ }
152
+ throw error;
153
+ }
154
+ if ("output" in decision && !("input" in decision))
155
+ return decision.output;
156
+ if (!("input" in decision))
157
+ throw new HarnessError("execution.invalid-state", "Decide returned neither input nor output");
158
+ const next = decision;
159
+ if (next.agent !== undefined) {
160
+ if (!runIsAgent) {
161
+ invalidAgent(path, "Decide returned agent but Loop.run is not an agent");
162
+ }
163
+ if (pinnedAgent && !isVariantOf(next.agent, pinnedAgent)) {
164
+ invalidAgent(path, "Decide returned a manifest that is not a variant of the pinned agent");
165
+ }
166
+ currentAgent = next.agent;
167
+ }
168
+ history.push({ iteration, output: runOutput, verdict });
169
+ currentInput = next.input;
170
+ iteration += 1;
171
+ }
172
+ finally {
173
+ ctx.iterations.pop();
174
+ }
175
+ }
176
+ }
177
+ function runPath(loopPath, run) {
178
+ const { part } = unwrapSlot(run);
179
+ return joinPath(loopPath, part);
180
+ }
181
+ async function runVerify(ctx, verify, loopPath, args) {
182
+ const iterations = ctx.iterationsString();
183
+ if ("fn" in verify) {
184
+ try {
185
+ return (await ctx.effect("verify", args, { path: loopPath, key: nodeKeyOf(loopPath), iterations }, { loopPath, n: args.iteration }));
186
+ }
187
+ catch (error) {
188
+ if (error instanceof FlowNodeError) {
189
+ if (error.failure.code === "loop.verify-failed")
190
+ throw error;
191
+ throw new FlowNodeError({
192
+ code: "loop.verify-failed",
193
+ message: error.failure.message,
194
+ path: loopPath,
195
+ });
196
+ }
197
+ throw error;
198
+ }
199
+ }
200
+ // Verifier agent (or slot wrapping one): input is { task, response, iteration }.
201
+ const judgePayload = {
202
+ task: args.input,
203
+ response: args.output,
204
+ iteration: args.iteration,
205
+ };
206
+ try {
207
+ if ("slot" in verify) {
208
+ const { part } = unwrapSlot(verify);
209
+ const verifyPath = joinPath(loopPath, part);
210
+ const value = await runNode(ctx, verify, verifyPath, judgePayload);
211
+ return value;
212
+ }
213
+ if ("agent" in verify) {
214
+ const verifyPath = joinPath(loopPath, verify.agent);
215
+ const value = await ctx.effect("agent", { agentId: verify.agent, input: judgePayload, path: verifyPath }, { path: verifyPath, key: nodeKeyOf(verifyPath), iterations }, { loopPath, n: args.iteration, role: "verify-agent" });
216
+ return value;
217
+ }
218
+ }
219
+ catch (error) {
220
+ if (error instanceof HostSuspension)
221
+ throw error;
222
+ if (error instanceof FlowNodeError) {
223
+ throw new FlowNodeError({
224
+ code: "loop.verify-failed",
225
+ message: error.failure.message,
226
+ path: loopPath,
227
+ });
228
+ }
229
+ throw new FlowNodeError({
230
+ code: "loop.verify-failed",
231
+ message: error instanceof Error ? error.message : String(error),
232
+ path: loopPath,
233
+ });
234
+ }
235
+ throw new HarnessError("execution.invalid-state", "Unsupported Loop.verify node");
236
+ }
@@ -0,0 +1,7 @@
1
+ import type { JsonValue } from "@nylorun/core/define";
2
+ import type { WorkflowMapNode } from "@nylorun/core";
3
+ import type { FlowContext } from "./context.js";
4
+ /**
5
+ * Map: journal `over`, run each item concurrently at `<map>[i]/<each id>`; fail-fast.
6
+ */
7
+ export declare function runMap(ctx: FlowContext, node: WorkflowMapNode["map"], path: string, input: JsonValue): Promise<JsonValue>;
@@ -0,0 +1,64 @@
1
+ import { HostSuspension } from "../loop/host-suspension.js";
2
+ import { failureOf, markFailFastCancels } from "./context.js";
3
+ import { assertMapItemCount } from "./limits.js";
4
+ import { FlowNodeError } from "./types.js";
5
+ import { mapItemPath, nodeKeyOf } from "./paths.js";
6
+ import { runNode, unwrapSlot } from "./node.js";
7
+ /**
8
+ * Map: journal `over`, run each item concurrently at `<map>[i]/<each id>`; fail-fast.
9
+ */
10
+ export async function runMap(ctx, node, path, input) {
11
+ const over = await ctx.effect("fn", input, { path, key: nodeKeyOf(path) }, { role: "map-over" });
12
+ if (!Array.isArray(over)) {
13
+ throw new FlowNodeError({
14
+ code: "map.not-a-list",
15
+ message: "Map.over did not return an array",
16
+ path,
17
+ });
18
+ }
19
+ const items = over;
20
+ // Operator ceiling before any item starts (WF-L2 / MAP-E2).
21
+ assertMapItemCount(items.length, ctx.limits, path);
22
+ // Runtime emits map.items { path, count } after over is journaled.
23
+ if (items.length === 0)
24
+ return [];
25
+ const { part: eachPart } = unwrapSlot(node.each);
26
+ const outputs = new Array(items.length);
27
+ const suspensions = [];
28
+ const failures = [];
29
+ await Promise.all(items.map(async (item, index) => {
30
+ const itemPath = mapItemPath(path, index, eachPart);
31
+ try {
32
+ const eachNode = node.each;
33
+ if ("slot" in eachNode && eachNode.slot.input) {
34
+ outputs[index] = await runNode(ctx, eachNode, itemPath, item, {
35
+ map: { item, mapInput: input, index },
36
+ });
37
+ }
38
+ else {
39
+ outputs[index] = await runNode(ctx, eachNode, itemPath, item);
40
+ }
41
+ }
42
+ catch (error) {
43
+ if (error instanceof HostSuspension) {
44
+ suspensions.push(error);
45
+ return;
46
+ }
47
+ failures.push(error instanceof FlowNodeError ? error : new FlowNodeError(failureOf(error, itemPath)));
48
+ }
49
+ }));
50
+ if (failures.length > 0) {
51
+ markFailFastCancels(ctx);
52
+ failures.sort((a, b) => indexFromPath(a.failure.path) - indexFromPath(b.failure.path));
53
+ throw failures[0];
54
+ }
55
+ if (suspensions.length > 0)
56
+ throw suspensions[0];
57
+ return outputs;
58
+ }
59
+ function indexFromPath(path) {
60
+ if (!path)
61
+ return Number.MAX_SAFE_INTEGER;
62
+ const match = path.match(/\[(\d+)\]/);
63
+ return match ? Number(match[1]) : Number.MAX_SAFE_INTEGER;
64
+ }
@@ -0,0 +1,31 @@
1
+ import type { JsonValue } from "@nylorun/core/define";
2
+ import type { WorkflowNode } from "@nylorun/core";
3
+ import type { FlowContext } from "./context.js";
4
+ import { joinPath, mapItemPath, nodeKeyOf } from "./paths.js";
5
+ /** Path part / id for a node among its siblings. */
6
+ export declare function nodePart(node: WorkflowNode): string;
7
+ export type SlotUnwrap = {
8
+ readonly run: WorkflowNode;
9
+ readonly inputFn: boolean;
10
+ readonly part: string;
11
+ };
12
+ export declare function unwrapSlot(node: WorkflowNode): SlotUnwrap;
13
+ export type RunNodeOptions = {
14
+ /**
15
+ * Input of the primitive that owns the slot (`workflows.md` §4).
16
+ * Defaults to `input` (the value the child would receive without a reshape).
17
+ */
18
+ readonly ownerInput?: JsonValue;
19
+ /** Map item: slot `input` receives `{ value: item, input: mapInput, results, index }`. */
20
+ readonly map?: {
21
+ readonly item: JsonValue;
22
+ readonly mapInput: JsonValue;
23
+ readonly index: number;
24
+ };
25
+ };
26
+ /**
27
+ * Run any workflow node at `path` with `input`.
28
+ * Slots: optional `fn` reshape, then the wrapped runnable.
29
+ */
30
+ export declare function runNode(ctx: FlowContext, node: WorkflowNode, path: string, input: JsonValue, options?: RunNodeOptions): Promise<JsonValue>;
31
+ export { joinPath, mapItemPath, nodeKeyOf };
@@ -0,0 +1,90 @@
1
+ import { HarnessError } from "@nylorun/core/define";
2
+ import { joinPath, mapItemPath, nodeKeyOf } from "./paths.js";
3
+ import { runChain } from "./chain.js";
4
+ import { runSwitch } from "./switch.js";
5
+ import { runParallel } from "./parallel.js";
6
+ import { runMap } from "./map.js";
7
+ import { runLoopNode } from "./loop.js";
8
+ /** Path part / id for a node among its siblings. */
9
+ export function nodePart(node) {
10
+ if ("agent" in node)
11
+ return node.agent;
12
+ if ("tool" in node)
13
+ return node.tool.name;
14
+ if ("chain" in node)
15
+ return node.chain.id;
16
+ if ("switch" in node)
17
+ return node.switch.id;
18
+ if ("parallel" in node)
19
+ return node.parallel.id;
20
+ if ("map" in node)
21
+ return node.map.id;
22
+ if ("loop" in node)
23
+ return node.loop.id;
24
+ if ("slot" in node)
25
+ return node.slot.id ?? nodePart(node.slot.run);
26
+ throw new HarnessError("execution.invalid-state", "Unknown workflow node kind");
27
+ }
28
+ export function unwrapSlot(node) {
29
+ if ("slot" in node) {
30
+ return {
31
+ run: node.slot.run,
32
+ inputFn: !!node.slot.input,
33
+ part: node.slot.id ?? nodePart(node.slot.run),
34
+ };
35
+ }
36
+ return { run: node, inputFn: false, part: nodePart(node) };
37
+ }
38
+ /**
39
+ * Run any workflow node at `path` with `input`.
40
+ * Slots: optional `fn` reshape, then the wrapped runnable.
41
+ */
42
+ export async function runNode(ctx, node, path, input, options = {}) {
43
+ if ("slot" in node) {
44
+ let childInput = input;
45
+ if (node.slot.input) {
46
+ const results = ctx.nearestResults();
47
+ const fnArgs = options.map
48
+ ? {
49
+ value: options.map.item,
50
+ input: options.map.mapInput,
51
+ results,
52
+ index: options.map.index,
53
+ }
54
+ : {
55
+ value: input,
56
+ input: options.ownerInput ?? input,
57
+ results,
58
+ };
59
+ childInput = (await ctx.effect("fn", fnArgs, { path, key: nodeKeyOf(path) }, { role: "slot-input" }));
60
+ }
61
+ return runRunnable(ctx, node.slot.run, path, childInput);
62
+ }
63
+ return runRunnable(ctx, node, path, input);
64
+ }
65
+ async function runRunnable(ctx, node, path, input) {
66
+ if ("slot" in node)
67
+ return runNode(ctx, node, path, input);
68
+ if ("agent" in node)
69
+ return runAgent(ctx, node.agent, path, input);
70
+ if ("tool" in node)
71
+ return runTool(ctx, node.tool.name, path, input);
72
+ if ("chain" in node)
73
+ return runChain(ctx, node.chain, path, input);
74
+ if ("switch" in node)
75
+ return runSwitch(ctx, node.switch, path, input);
76
+ if ("parallel" in node)
77
+ return runParallel(ctx, node.parallel, path, input);
78
+ if ("map" in node)
79
+ return runMap(ctx, node.map, path, input);
80
+ if ("loop" in node)
81
+ return runLoopNode(ctx, node.loop, path, input);
82
+ throw new HarnessError("execution.invalid-state", "Unknown workflow node kind");
83
+ }
84
+ async function runAgent(ctx, agentId, path, input) {
85
+ return (await ctx.effect("agent", { agentId, input, path }, { path, key: nodeKeyOf(path) }));
86
+ }
87
+ async function runTool(ctx, name, path, input) {
88
+ return (await ctx.effect("tool", input, { path, key: nodeKeyOf(path) }, { toolName: name }));
89
+ }
90
+ export { joinPath, mapItemPath, nodeKeyOf };
@@ -0,0 +1,7 @@
1
+ import type { JsonValue } from "@nylorun/core/define";
2
+ import type { WorkflowParallelNode } from "@nylorun/core";
3
+ import type { FlowContext } from "./context.js";
4
+ /**
5
+ * Parallel: all branches ready at once; output object in declaration order; fail-fast.
6
+ */
7
+ export declare function runParallel(ctx: FlowContext, node: WorkflowParallelNode["parallel"], path: string, input: JsonValue): Promise<JsonValue>;
@@ -0,0 +1,47 @@
1
+ import { HostSuspension } from "../loop/host-suspension.js";
2
+ import { failureOf, markFailFastCancels } from "./context.js";
3
+ import { FlowNodeError } from "./types.js";
4
+ import { joinPath } from "./paths.js";
5
+ import { runNode } from "./node.js";
6
+ /**
7
+ * Parallel: all branches ready at once; output object in declaration order; fail-fast.
8
+ */
9
+ export async function runParallel(ctx, node, path, input) {
10
+ const names = Object.keys(node.branches);
11
+ const outputs = {};
12
+ const suspensions = [];
13
+ const failures = [];
14
+ await Promise.all(names.map(async (name) => {
15
+ const branch = node.branches[name];
16
+ const branchPath = joinPath(path, name);
17
+ try {
18
+ outputs[name] = await runNode(ctx, branch, branchPath, input);
19
+ }
20
+ catch (error) {
21
+ if (error instanceof HostSuspension) {
22
+ suspensions.push(error);
23
+ return;
24
+ }
25
+ failures.push(error instanceof FlowNodeError ? error : new FlowNodeError(failureOf(error, branchPath)));
26
+ }
27
+ }));
28
+ if (failures.length > 0) {
29
+ markFailFastCancels(ctx);
30
+ // First failure in declaration order wins when several settle together.
31
+ const ordered = failures.sort((a, b) => {
32
+ const ai = names.findIndex((n) => (a.failure.path ?? "").includes(`/${n}`) || a.failure.path?.endsWith(n));
33
+ const bi = names.findIndex((n) => (b.failure.path ?? "").includes(`/${n}`) || b.failure.path?.endsWith(n));
34
+ return (ai === -1 ? names.length : ai) - (bi === -1 ? names.length : bi);
35
+ });
36
+ throw ordered[0];
37
+ }
38
+ if (suspensions.length > 0) {
39
+ // Re-throw one suspension; pending map already holds every branch effect id.
40
+ throw suspensions[0];
41
+ }
42
+ // Declaration order.
43
+ const result = {};
44
+ for (const name of names)
45
+ result[name] = outputs[name];
46
+ return result;
47
+ }
@@ -0,0 +1,19 @@
1
+ /** Path, node key and iteration-vector helpers (workflows.md §6). */
2
+ export declare function joinPath(parent: string, part: string): string;
3
+ /**
4
+ * Map item path: `<map path>[index]/<each id>` (workflows.md §6).
5
+ * Example: `implement[2]/code`.
6
+ */
7
+ export declare function mapItemPath(mapPath: string, index: number, eachId: string): string;
8
+ /** Drop Map indices from a path to get the node key. */
9
+ export declare function nodeKeyOf(path: string): string;
10
+ /** Iteration vector string: enclosing Loop numbers outermost first, or "-" outside Loops. */
11
+ export declare function iterationsOf(vector: readonly number[]): string;
12
+ /** Effect id for a flow effect (workflows.md §10). */
13
+ export declare function flowEffectId(input: {
14
+ readonly turnId: string;
15
+ readonly segment: number;
16
+ readonly path: string;
17
+ readonly kind: string;
18
+ readonly iterations: string;
19
+ }): string;
@@ -0,0 +1,23 @@
1
+ /** Path, node key and iteration-vector helpers (workflows.md §6). */
2
+ export function joinPath(parent, part) {
3
+ return parent ? `${parent}/${part}` : part;
4
+ }
5
+ /**
6
+ * Map item path: `<map path>[index]/<each id>` (workflows.md §6).
7
+ * Example: `implement[2]/code`.
8
+ */
9
+ export function mapItemPath(mapPath, index, eachId) {
10
+ return `${mapPath}[${index}]/${eachId}`;
11
+ }
12
+ /** Drop Map indices from a path to get the node key. */
13
+ export function nodeKeyOf(path) {
14
+ return path.replace(/\[\d+]/g, "");
15
+ }
16
+ /** Iteration vector string: enclosing Loop numbers outermost first, or "-" outside Loops. */
17
+ export function iterationsOf(vector) {
18
+ return vector.length === 0 ? "-" : vector.join(".");
19
+ }
20
+ /** Effect id for a flow effect (workflows.md §10). */
21
+ export function flowEffectId(input) {
22
+ return `${input.turnId}:${input.segment}:flow:${input.path}:${input.kind}:${input.iterations}`;
23
+ }
@@ -0,0 +1,8 @@
1
+ import type { JsonValue } from "@nylorun/core/define";
2
+ import type { WorkflowSwitchNode } from "@nylorun/core";
3
+ import type { FlowContext } from "./context.js";
4
+ /**
5
+ * Switch: `fn` effect for `on`, select case or fail `switch.no-match`, run chosen case.
6
+ * The key is journaled so replay always takes the same case.
7
+ */
8
+ export declare function runSwitch(ctx: FlowContext, node: WorkflowSwitchNode["switch"], path: string, input: JsonValue): Promise<JsonValue>;
@@ -0,0 +1,35 @@
1
+ import { FlowNodeError } from "./types.js";
2
+ import { joinPath, nodeKeyOf } from "./paths.js";
3
+ import { runNode } from "./node.js";
4
+ /**
5
+ * Switch: `fn` effect for `on`, select case or fail `switch.no-match`, run chosen case.
6
+ * The key is journaled so replay always takes the same case.
7
+ */
8
+ export async function runSwitch(ctx, node, path, input) {
9
+ const key = await ctx.effect("fn", input, { path, key: `${nodeKeyOf(path)}/on` }, { role: "switch-on" });
10
+ if (typeof key !== "string") {
11
+ throw new FlowNodeError({
12
+ code: "fn.failed",
13
+ message: `Switch.on must return a string, got ${typeof key}`,
14
+ path,
15
+ });
16
+ }
17
+ let caseNode = node.cases[key];
18
+ let casePart = key;
19
+ if (!caseNode) {
20
+ if (node.default) {
21
+ caseNode = node.default;
22
+ casePart = "default";
23
+ }
24
+ else {
25
+ throw new FlowNodeError({
26
+ code: "switch.no-match",
27
+ message: `No Switch case matched key ${JSON.stringify(key)}`,
28
+ path,
29
+ });
30
+ }
31
+ }
32
+ // Selection is implied by the journaled `on` result; Runtime emits switch.selected.
33
+ const casePath = joinPath(path, casePart);
34
+ return runNode(ctx, caseNode, casePath, input);
35
+ }
@@ -0,0 +1,45 @@
1
+ import type { JsonValue } from "@nylorun/core/define";
2
+ import type { FlowCheckpoint } from "./checkpoint.js";
3
+ export type FlowRunResult = {
4
+ readonly status: "completed";
5
+ readonly output: JsonValue;
6
+ } | {
7
+ readonly status: "failed";
8
+ readonly error: {
9
+ readonly code: string;
10
+ readonly message: string;
11
+ readonly path?: string;
12
+ };
13
+ } | {
14
+ readonly status: "cancelled";
15
+ } | {
16
+ readonly status: "paused";
17
+ readonly pending: unknown;
18
+ };
19
+ export type FlowDurableResult = {
20
+ readonly status: "waiting" | "uncertain";
21
+ readonly checkpoint: FlowCheckpoint;
22
+ readonly effectIds: readonly string[];
23
+ } | {
24
+ readonly status: "completed" | "paused" | "cancelled";
25
+ readonly checkpoint: FlowCheckpoint;
26
+ readonly result: FlowRunResult;
27
+ } | {
28
+ readonly status: "failed";
29
+ readonly checkpoint: FlowCheckpoint;
30
+ readonly result: FlowRunResult;
31
+ /** Pending sibling effect ids to cancel after Parallel/Map fail-fast. */
32
+ readonly cancelEffectIds?: readonly string[];
33
+ };
34
+ export type FlowFailure = {
35
+ readonly code: string;
36
+ readonly message: string;
37
+ readonly path?: string;
38
+ };
39
+ /** Thrown when a node fails; unwinds to the engine root. */
40
+ export declare class FlowNodeError extends Error {
41
+ readonly failure: FlowFailure;
42
+ constructor(failure: FlowFailure);
43
+ }
44
+ /** Completed effect value that encodes a curated failure (executor / agent settle). */
45
+ export declare function failedValueOf(value: unknown): FlowFailure | undefined;
@@ -0,0 +1,22 @@
1
+ /** Thrown when a node fails; unwinds to the engine root. */
2
+ export class FlowNodeError extends Error {
3
+ failure;
4
+ constructor(failure) {
5
+ super(failure.message);
6
+ this.failure = failure;
7
+ this.name = "FlowNodeError";
8
+ }
9
+ }
10
+ /** Completed effect value that encodes a curated failure (executor / agent settle). */
11
+ export function failedValueOf(value) {
12
+ if (!value || typeof value !== "object")
13
+ return undefined;
14
+ const record = value;
15
+ if (record.kind !== "failed" || typeof record.code !== "string")
16
+ return undefined;
17
+ return {
18
+ code: record.code,
19
+ message: typeof record.message === "string" ? record.message : record.code,
20
+ ...(typeof record.path === "string" ? { path: record.path } : {}),
21
+ };
22
+ }