@nylorun/harness 0.22.1-beta → 0.23.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 (55) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/HOST_CONTRACT.md +17 -19
  3. package/README.md +5 -30
  4. package/dist/api/executors.d.ts +5 -4
  5. package/dist/api/harness.d.ts +0 -10
  6. package/dist/api/harness.js +1 -52
  7. package/dist/api/host.d.ts +2 -8
  8. package/dist/api/host.js +3 -15
  9. package/dist/api/run.d.ts +0 -11
  10. package/dist/api/run.js +1 -11
  11. package/dist/compatibility.d.ts +4 -12
  12. package/dist/compatibility.js +3 -11
  13. package/dist/definition/agent-definition.d.ts +0 -3
  14. package/dist/definition/agent-definition.js +0 -2
  15. package/dist/flow/checkpoint.d.ts +16 -0
  16. package/dist/flow/checkpoint.js +6 -2
  17. package/dist/flow/context.d.ts +19 -10
  18. package/dist/flow/context.js +36 -20
  19. package/dist/flow/engine.d.ts +25 -7
  20. package/dist/flow/engine.js +304 -38
  21. package/dist/flow/index.d.ts +3 -5
  22. package/dist/flow/index.js +3 -5
  23. package/dist/flow/paths.d.ts +1 -8
  24. package/dist/flow/paths.js +1 -12
  25. package/dist/flow/tool.d.ts +14 -0
  26. package/dist/flow/tool.js +67 -0
  27. package/dist/flow/types.d.ts +30 -3
  28. package/dist/flow/types.js +14 -1
  29. package/dist/loop/run.js +5 -134
  30. package/dist/loop/state.js +2 -22
  31. package/dist/loop/step/run.d.ts +1 -10
  32. package/dist/loop/step/run.js +2 -101
  33. package/dist/loop/step/runtime.d.ts +0 -17
  34. package/dist/run/durable.d.ts +7 -11
  35. package/dist/run/durable.js +14 -33
  36. package/dist/run/index.d.ts +3 -4
  37. package/dist/run/index.js +1 -2
  38. package/dist/types/execution.d.ts +5 -18
  39. package/package.json +2 -2
  40. package/dist/flow/chain.d.ts +0 -8
  41. package/dist/flow/chain.js +0 -27
  42. package/dist/flow/loop.d.ts +0 -35
  43. package/dist/flow/loop.js +0 -238
  44. package/dist/flow/map.d.ts +0 -7
  45. package/dist/flow/map.js +0 -64
  46. package/dist/flow/node.d.ts +0 -31
  47. package/dist/flow/node.js +0 -113
  48. package/dist/flow/parallel.d.ts +0 -7
  49. package/dist/flow/parallel.js +0 -47
  50. package/dist/flow/switch.d.ts +0 -8
  51. package/dist/flow/switch.js +0 -35
  52. package/dist/flow/v2.d.ts +0 -12
  53. package/dist/flow/v2.js +0 -370
  54. package/dist/loop/step/hooks.d.ts +0 -56
  55. package/dist/loop/step/hooks.js +0 -191
@@ -1,31 +0,0 @@
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 };
package/dist/flow/node.js DELETED
@@ -1,113 +0,0 @@
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 { readAgentTurn, runLoopNode } from "./loop.js";
8
- import { FlowNodeError } from "./types.js";
9
- /** Path part / id for a node among its siblings. */
10
- export function nodePart(node) {
11
- if ("agent" in node)
12
- return node.agent;
13
- if ("tool" in node)
14
- return node.tool.name;
15
- if ("chain" in node)
16
- return node.chain.id;
17
- if ("switch" in node)
18
- return node.switch.id;
19
- if ("parallel" in node)
20
- return node.parallel.id;
21
- if ("map" in node)
22
- return node.map.id;
23
- if ("loop" in node)
24
- return node.loop.id;
25
- if ("slot" in node)
26
- return node.slot.id ?? nodePart(node.slot.run);
27
- throw new HarnessError("execution.invalid-state", "Unknown workflow node kind");
28
- }
29
- export function unwrapSlot(node) {
30
- if ("slot" in node) {
31
- return {
32
- run: node.slot.run,
33
- inputFn: !!node.slot.input,
34
- part: node.slot.id ?? nodePart(node.slot.run),
35
- };
36
- }
37
- return { run: node, inputFn: false, part: nodePart(node) };
38
- }
39
- /**
40
- * Run any workflow node at `path` with `input`.
41
- * Slots: optional `fn` reshape, then the wrapped runnable.
42
- */
43
- export async function runNode(ctx, node, path, input, options = {}) {
44
- if ("slot" in node) {
45
- let childInput = input;
46
- if (node.slot.input) {
47
- const results = ctx.nearestResults();
48
- const fnArgs = options.map
49
- ? {
50
- value: options.map.item,
51
- input: options.map.mapInput,
52
- results,
53
- index: options.map.index,
54
- }
55
- : {
56
- value: input,
57
- input: options.ownerInput ?? input,
58
- results,
59
- };
60
- childInput = (await ctx.effect("fn", fnArgs, { path, key: `${nodeKeyOf(path)}/input`, role: "slot-input" }, { role: "slot-input" }));
61
- }
62
- return runRunnable(ctx, node.slot.run, path, childInput);
63
- }
64
- return runRunnable(ctx, node, path, input);
65
- }
66
- async function runRunnable(ctx, node, path, input) {
67
- if ("slot" in node)
68
- return runNode(ctx, node, path, input);
69
- if ("agent" in node)
70
- return runAgent(ctx, node.agent, path, input);
71
- if ("tool" in node)
72
- return runTool(ctx, node.tool.name, path, input);
73
- if ("chain" in node)
74
- return runChain(ctx, node.chain, path, input);
75
- if ("switch" in node)
76
- return runSwitch(ctx, node.switch, path, input);
77
- if ("parallel" in node)
78
- return runParallel(ctx, node.parallel, path, input);
79
- if ("map" in node)
80
- return runMap(ctx, node.map, path, input);
81
- if ("loop" in node)
82
- return runLoopNode(ctx, node.loop, path, input);
83
- throw new HarnessError("execution.invalid-state", "Unknown workflow node kind");
84
- }
85
- async function runAgent(ctx, agentId, path, input) {
86
- // The host marks a linked agent's output with its turn manifest for Loops; a step
87
- // passes on the output only.
88
- return readAgentTurn(await ctx.effect("agent", { agentId, input, path }, { path, key: nodeKeyOf(path) })).output;
89
- }
90
- async function runTool(ctx, name, path, input) {
91
- const value = await ctx.effect("tool", input, { path, key: nodeKeyOf(path) }, { toolName: name });
92
- return toolNodeOutput(value, path);
93
- }
94
- /**
95
- * The Action endpoint settles a tool node like any tool: `{ kind: "completed", output }` or
96
- * `{ kind: "denied", reason }`. The flow passes on the output only. Failed values are
97
- * already raised by `ctx.effect`.
98
- */
99
- function toolNodeOutput(value, path) {
100
- if (!value || typeof value !== "object" || Array.isArray(value))
101
- return value;
102
- const outcome = value;
103
- if (outcome.kind === "completed" && "output" in outcome)
104
- return outcome.output ?? null;
105
- if (outcome.kind === "denied")
106
- throw new FlowNodeError({
107
- code: "tool.denied",
108
- message: typeof outcome.reason === "string" ? outcome.reason : "Tool call denied",
109
- path,
110
- });
111
- return value;
112
- }
113
- export { joinPath, mapItemPath, nodeKeyOf };
@@ -1,7 +0,0 @@
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>;
@@ -1,47 +0,0 @@
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
- }
@@ -1,8 +0,0 @@
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>;
@@ -1,35 +0,0 @@
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
- }
package/dist/flow/v2.d.ts DELETED
@@ -1,12 +0,0 @@
1
- import { type WorkflowManifestV2 } from "@nylorun/core/define";
2
- import type { DurableHost } from "../run/durable.js";
3
- import type { FlowCheckpoint } from "./checkpoint.js";
4
- import { type FlowOperatorLimits } from "./limits.js";
5
- import { type FlowDurableResult } from "./types.js";
6
- export declare function runFlowV2(options: {
7
- manifest: WorkflowManifestV2;
8
- checkpoint: FlowCheckpoint;
9
- host: DurableHost;
10
- signal?: AbortSignal;
11
- limits?: Partial<FlowOperatorLimits> | null;
12
- }): Promise<FlowDurableResult>;
package/dist/flow/v2.js DELETED
@@ -1,370 +0,0 @@
1
- /**
2
- * Flow engine for workflow manifest v2 (`flow-2`).
3
- *
4
- * Differences from v1 (`flow-1`), per the Flow Agents design:
5
- * - Agent and tool sessions are named by leaf paths: the leaf's id, `[i]` per Map
6
- * item, under nested flow agents' ids. Control stages add nothing.
7
- * - Functions are bound under stage keys (`route:on`, `@1.default.1:input`) and all
8
- * receive `{ input, results, flowInput }`; `flowInput` is the nearest Agent's input.
9
- * - Any node may carry `input`; there are no slots. A Map runs over its input.
10
- * - A Loop without `decide` passes on a pass verdict and retries with the feedback,
11
- * up to `max` attempts; `decide` returns `{ output }` or `{ retry, agent? }`.
12
- * - Leaf agents come from the manifest's embedded `agents`; nested flow agents run
13
- * inline with their own `flowInput` and `results`.
14
- */
15
- import { HarnessError, isVariantOf } from "@nylorun/core/define";
16
- import { ROOT_POSITION, childPosition, functionKey, indexSuffix, isWorkflowManifestV2, leafPart, leafPath, stageKey, } from "@nylorun/core/define";
17
- import { HostSuspension } from "../loop/host-suspension.js";
18
- import { createFlowContext, failureOf, markFailFastCancels, settleInFlight, } from "./context.js";
19
- import { assertLoopIteration, assertMapItemCount } from "./limits.js";
20
- import { iterationsOf } from "./paths.js";
21
- import { readAgentTurn } from "./loop.js";
22
- import { FlowNodeError } from "./types.js";
23
- export async function runFlowV2(options) {
24
- const { manifest, checkpoint, signal } = options;
25
- const ctx = createFlowContext(options);
26
- const scope = {
27
- manifest,
28
- flow: [],
29
- pathPrefix: "",
30
- keyPrefix: "",
31
- pending: [],
32
- indices: [],
33
- iterations: [],
34
- flowInput: checkpoint.input,
35
- results: {},
36
- };
37
- try {
38
- if (signal?.aborted)
39
- return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
40
- const output = await runNode(ctx, scope, manifest.root, ROOT_POSITION, checkpoint.input);
41
- return { status: "completed", checkpoint, result: { status: "completed", output } };
42
- }
43
- catch (error) {
44
- await settleInFlight(ctx);
45
- if (error instanceof HostSuspension)
46
- return {
47
- status: [...ctx.pending.values()].includes("uncertain") ? "uncertain" : "waiting",
48
- checkpoint,
49
- effectIds: [...ctx.pending.keys()],
50
- };
51
- if (error instanceof FlowNodeError && error.failure.code === "cancelled")
52
- return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
53
- return {
54
- status: "failed",
55
- checkpoint,
56
- result: { status: "failed", error: failureOf(error, manifest.id) },
57
- ...(ctx.cancelEffectIds.size > 0 ? { cancelEffectIds: [...ctx.cancelEffectIds] } : {}),
58
- };
59
- }
60
- }
61
- /** Where a node's effects are recorded: a leaf's path, or its stage key plus Map indices. */
62
- function siteOf(scope, node, key) {
63
- const part = leafPart(node);
64
- return part === undefined
65
- ? `${key}${indexSuffix(scope.indices)}`
66
- : leafPath(scope.pathPrefix, part, scope.pending);
67
- }
68
- async function runNode(ctx, scope, node, position, input, agentOptions = {}) {
69
- const key = stageKey(node, position, scope.keyPrefix);
70
- const site = siteOf(scope, node, key);
71
- let value = input;
72
- if (node.input)
73
- value = await callFn(ctx, scope, key, site, "input", stageArgs(scope, value));
74
- if ("agent" in node)
75
- return (await runAgent(ctx, scope, node, key, site, value, agentOptions)).output;
76
- if ("tool" in node)
77
- return runTool(ctx, scope, node.tool.name, key, site, value);
78
- if ("chain" in node)
79
- return runChain(ctx, scope, node.chain, position, value);
80
- if ("switch" in node)
81
- return runSwitch(ctx, scope, node.switch, key, site, position, value);
82
- if ("parallel" in node)
83
- return runParallel(ctx, scope, node.parallel, site, position, value);
84
- if ("map" in node)
85
- return runMap(ctx, scope, node.map.each, site, position, value);
86
- if ("loop" in node)
87
- return runLoop(ctx, scope, node.loop, key, site, position, value);
88
- throw new HarnessError("execution.invalid-state", "Unknown workflow node kind");
89
- }
90
- function stageArgs(scope, input) {
91
- return { input, results: scope.results, flowInput: scope.flowInput };
92
- }
93
- async function callFn(ctx, scope, key, site, role, args, context = {}) {
94
- return (await ctx.effect(role === "verify" ? "verify" : "fn", args, {
95
- path: `${site}:${role}`,
96
- key: functionKey(key, role),
97
- iterations: iterationsOf(scope.iterations),
98
- }, { role, ...context }));
99
- }
100
- /**
101
- * An agent node: a leaf agent runs as one turn in its own session; a nested flow agent
102
- * runs inline, under its own id, with its own `flowInput` and `results`.
103
- */
104
- async function runAgent(ctx, scope, node, key, site, input, options) {
105
- const target = scope.manifest.agents[node.agent];
106
- if (target === undefined)
107
- throw new FlowNodeError({
108
- code: "flow.unknown-agent",
109
- message: `Agent '${node.agent}' is not embedded in flow agent '${scope.manifest.id}'`,
110
- path: site,
111
- });
112
- if (isWorkflowManifestV2(target)) {
113
- const flow = target;
114
- const nested = {
115
- manifest: flow,
116
- flow: [...scope.flow, node.agent],
117
- pathPrefix: site,
118
- keyPrefix: key,
119
- pending: [],
120
- indices: scope.indices,
121
- iterations: scope.iterations,
122
- flowInput: input,
123
- results: {},
124
- };
125
- return { output: await runNode(ctx, nested, flow.root, ROOT_POSITION, input) };
126
- }
127
- const raw = await ctx.effect("agent", {
128
- agentId: node.agent,
129
- input,
130
- path: site,
131
- ...(scope.flow.length > 0 ? { flow: scope.flow } : {}),
132
- ...(options.manifest ? { manifest: options.manifest } : {}),
133
- }, { path: site, key, iterations: iterationsOf(scope.iterations) }, options.context ?? {});
134
- return readAgentTurn(raw);
135
- }
136
- async function runTool(ctx, scope, name, key, site, input) {
137
- const value = (await ctx.effect("tool", input, { path: site, key, iterations: iterationsOf(scope.iterations) }, { toolName: name }));
138
- if (!value || typeof value !== "object" || Array.isArray(value))
139
- return value;
140
- const outcome = value;
141
- if (outcome.kind === "completed" && "output" in outcome)
142
- return outcome.output ?? null;
143
- if (outcome.kind === "denied")
144
- throw new FlowNodeError({
145
- code: "tool.denied",
146
- message: typeof outcome.reason === "string" ? outcome.reason : "Tool call denied",
147
- path: site,
148
- });
149
- return value;
150
- }
151
- /** Steps in order; each step's output is the next one's input. `results` is lexical. */
152
- async function runChain(ctx, scope, steps, position, input) {
153
- const results = {};
154
- const inner = { ...scope, results };
155
- let current = input;
156
- for (const [index, step] of steps.entries()) {
157
- current = await runNode(ctx, inner, step, childPosition(position, index), current);
158
- const name = step.id ?? leafPart(step);
159
- if (name !== undefined)
160
- results[name] = current;
161
- }
162
- return current;
163
- }
164
- /** `on` picks a case; the key is journaled, so replay always takes the same case. */
165
- async function runSwitch(ctx, scope, node, key, site, position, input) {
166
- const chosen = await callFn(ctx, scope, key, site, "on", stageArgs(scope, input));
167
- if (typeof chosen !== "string")
168
- throw new FlowNodeError({
169
- code: "fn.failed",
170
- message: `Switch on must return a case name, got ${typeof chosen}`,
171
- path: site,
172
- });
173
- const caseNode = node.cases[chosen];
174
- if (caseNode)
175
- return runNode(ctx, scope, caseNode, childPosition(position, chosen), input);
176
- if (node.default)
177
- return runNode(ctx, scope, node.default, childPosition(position, "default"), input);
178
- throw new FlowNodeError({
179
- code: "switch.no-match",
180
- message: `No Switch case is named ${JSON.stringify(chosen)} and there is no default case`,
181
- path: site,
182
- });
183
- }
184
- /** Run `tasks` together; fail fast on the first failure in declaration order. */
185
- async function runTogether(ctx, tasks, pathOf) {
186
- const outputs = new Array(tasks.length);
187
- const suspensions = [];
188
- const failures = [];
189
- await Promise.all(tasks.map(async (task, index) => {
190
- try {
191
- outputs[index] = await task();
192
- }
193
- catch (error) {
194
- if (error instanceof HostSuspension) {
195
- suspensions.push(error);
196
- return;
197
- }
198
- failures.push({
199
- index,
200
- error: error instanceof FlowNodeError
201
- ? error
202
- : new FlowNodeError(failureOf(error, pathOf(index))),
203
- });
204
- }
205
- }));
206
- if (failures.length > 0) {
207
- markFailFastCancels(ctx);
208
- failures.sort((a, b) => a.index - b.index);
209
- throw failures[0].error;
210
- }
211
- if (suspensions.length > 0)
212
- throw suspensions[0];
213
- return outputs;
214
- }
215
- /** Every branch gets the same input; the output is keyed by branch, in declaration order. */
216
- async function runParallel(ctx, scope, branches, site, position, input) {
217
- const names = Object.keys(branches);
218
- const outputs = await runTogether(ctx, names.map((name) => () => runNode(ctx, scope, branches[name], childPosition(position, name), input)), () => site);
219
- const result = {};
220
- names.forEach((name, index) => {
221
- result[name] = outputs[index];
222
- });
223
- return result;
224
- }
225
- /** Runs `each` once per item of its input; the output is in item order. */
226
- async function runMap(ctx, scope, each, site, position, input) {
227
- if (!Array.isArray(input))
228
- throw new FlowNodeError({
229
- code: "map.not-a-list",
230
- message: `A Map runs over its input, which must be an array; got ${input === null ? "null" : typeof input}`,
231
- path: site,
232
- });
233
- assertMapItemCount(input.length, ctx.limits, site);
234
- if (input.length === 0)
235
- return [];
236
- const eachPosition = childPosition(position, "each");
237
- return runTogether(ctx, input.map((item, index) => () => runNode(ctx, { ...scope, pending: [...scope.pending, index], indices: [...scope.indices, index] }, each, eachPosition, item)), (index) => `${site}[${index}]`);
238
- }
239
- /** Run, verify, then stop or retry. The body keeps its session across attempts. */
240
- async function runLoop(ctx, scope, loop, key, site, position, input) {
241
- const history = [];
242
- const runPosition = childPosition(position, "run");
243
- const runIsLeaf = "agent" in loop.run &&
244
- !isWorkflowManifestV2(scope.manifest.agents[loop.run.agent]);
245
- let current = input;
246
- let pinned;
247
- let variant;
248
- for (let iteration = 1;; iteration += 1) {
249
- if (ctx.signal?.aborted)
250
- throw new FlowNodeError({ code: "cancelled", message: "cancelled", path: site });
251
- assertLoopIteration(iteration, ctx.limits, site);
252
- const turn = { ...scope, iterations: [...scope.iterations, iteration] };
253
- const loopContext = { loopPath: site, n: iteration };
254
- let output;
255
- if (runIsLeaf) {
256
- const node = loop.run;
257
- const runKey = stageKey(node, runPosition, scope.keyPrefix);
258
- const runSite = siteOf(turn, node, runKey);
259
- let value = current;
260
- if (node.input)
261
- value = await callFn(ctx, turn, runKey, runSite, "input", stageArgs(turn, value), loopContext);
262
- const result = await runAgent(ctx, turn, node, runKey, runSite, value, {
263
- context: loopContext,
264
- ...(variant ? { manifest: variant } : {}),
265
- });
266
- output = result.output;
267
- if (result.agent) {
268
- pinned ??= result.agent;
269
- variant = result.agent;
270
- }
271
- }
272
- else
273
- output = await runNode(ctx, turn, loop.run, runPosition, current);
274
- const verdict = await runVerify(ctx, turn, loop.verify, key, site, position, {
275
- input,
276
- output,
277
- iteration,
278
- loopContext,
279
- });
280
- let decision;
281
- if (loop.decide) {
282
- try {
283
- decision = (await callFn(ctx, turn, key, site, "decide", {
284
- input,
285
- output,
286
- verdict,
287
- iteration,
288
- history,
289
- ...(variant ? { agent: variant } : {}),
290
- results: turn.results,
291
- flowInput: turn.flowInput,
292
- }, loopContext));
293
- }
294
- catch (error) {
295
- if (error instanceof FlowNodeError && error.failure.code === "fn.failed")
296
- throw new FlowNodeError({
297
- code: "loop.stopped",
298
- message: error.failure.message,
299
- path: site,
300
- });
301
- throw error;
302
- }
303
- }
304
- else
305
- decision = verdict.pass ? { output } : { retry: verdict.feedback };
306
- if (!decision || typeof decision !== "object")
307
- throw new FlowNodeError({
308
- code: "loop.invalid-decision",
309
- message: "Loop decide must return { output } or { retry }",
310
- path: site,
311
- });
312
- if ("output" in decision)
313
- return decision.output;
314
- if (!("retry" in decision))
315
- throw new FlowNodeError({
316
- code: "loop.invalid-decision",
317
- message: "Loop decide must return { output } or { retry }",
318
- path: site,
319
- });
320
- if (loop.max !== undefined && iteration >= loop.max)
321
- throw new FlowNodeError({
322
- code: "loop.exhausted",
323
- message: `Loop stopped after ${loop.max} attempt${loop.max === 1 ? "" : "s"}` +
324
- (verdict.pass ? "" : `: ${verdict.feedback}`),
325
- path: site,
326
- });
327
- if (decision.agent !== undefined) {
328
- if (!runIsLeaf)
329
- throw new FlowNodeError({
330
- code: "loop.invalid-agent",
331
- message: "decide returned agent, but the Loop body is not an agent",
332
- path: site,
333
- });
334
- if (pinned && !isVariantOf(decision.agent, pinned))
335
- throw new FlowNodeError({
336
- code: "loop.invalid-agent",
337
- message: "decide returned a manifest that is not a variant of the body agent",
338
- path: site,
339
- });
340
- variant = decision.agent;
341
- }
342
- history.push({ iteration, output, verdict });
343
- current = decision.retry;
344
- }
345
- }
346
- async function runVerify(ctx, scope, verify, key, site, position, args) {
347
- try {
348
- if ("fn" in verify)
349
- return (await callFn(ctx, scope, key, site, "verify", {
350
- input: args.input,
351
- output: args.output,
352
- iteration: args.iteration,
353
- results: scope.results,
354
- flowInput: scope.flowInput,
355
- }, args.loopContext));
356
- // A verifier agent judges `{ task, response, iteration }` in a fresh session per attempt.
357
- const judged = { task: args.input, response: args.output, iteration: args.iteration };
358
- return (await runNode(ctx, scope, verify, childPosition(position, "verify"), judged, {
359
- context: { ...args.loopContext, role: "verify-agent" },
360
- }));
361
- }
362
- catch (error) {
363
- if (error instanceof HostSuspension)
364
- throw error;
365
- const failure = failureOf(error, site);
366
- if (failure.code === "loop.verify-failed")
367
- throw error;
368
- throw new FlowNodeError({ code: "loop.verify-failed", message: failure.message, path: site });
369
- }
370
- }