@nylorun/harness 0.22.0-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.
- package/CHANGELOG.md +96 -0
- package/HOST_CONTRACT.md +18 -21
- package/README.md +5 -30
- package/dist/api/executors.d.ts +5 -4
- package/dist/api/harness.d.ts +0 -10
- package/dist/api/harness.js +1 -52
- package/dist/api/host.d.ts +2 -8
- package/dist/api/host.js +3 -15
- package/dist/api/run.d.ts +0 -11
- package/dist/api/run.js +1 -11
- package/dist/compatibility.d.ts +4 -12
- package/dist/compatibility.js +3 -11
- package/dist/definition/agent-definition.d.ts +0 -3
- package/dist/definition/agent-definition.js +0 -2
- package/dist/flow/checkpoint.d.ts +16 -0
- package/dist/flow/checkpoint.js +6 -2
- package/dist/flow/context.d.ts +19 -10
- package/dist/flow/context.js +36 -20
- package/dist/flow/engine.d.ts +25 -7
- package/dist/flow/engine.js +304 -38
- package/dist/flow/index.d.ts +3 -5
- package/dist/flow/index.js +3 -5
- package/dist/flow/paths.d.ts +1 -8
- package/dist/flow/paths.js +1 -12
- package/dist/flow/tool.d.ts +14 -0
- package/dist/flow/tool.js +67 -0
- package/dist/flow/types.d.ts +30 -3
- package/dist/flow/types.js +14 -1
- package/dist/loop/run.js +5 -134
- package/dist/loop/state.js +2 -22
- package/dist/loop/step/run.d.ts +1 -10
- package/dist/loop/step/run.js +2 -101
- package/dist/loop/step/runtime.d.ts +0 -17
- package/dist/run/durable.d.ts +7 -11
- package/dist/run/durable.js +14 -33
- package/dist/run/index.d.ts +3 -4
- package/dist/run/index.js +1 -2
- package/dist/types/execution.d.ts +5 -18
- package/package.json +2 -2
- package/dist/flow/chain.d.ts +0 -8
- package/dist/flow/chain.js +0 -27
- package/dist/flow/loop.d.ts +0 -35
- package/dist/flow/loop.js +0 -238
- package/dist/flow/map.d.ts +0 -7
- package/dist/flow/map.js +0 -64
- package/dist/flow/node.d.ts +0 -31
- package/dist/flow/node.js +0 -113
- package/dist/flow/parallel.d.ts +0 -7
- package/dist/flow/parallel.js +0 -47
- package/dist/flow/switch.d.ts +0 -8
- package/dist/flow/switch.js +0 -35
- package/dist/flow/v2.d.ts +0 -12
- package/dist/flow/v2.js +0 -370
- package/dist/loop/step/hooks.d.ts +0 -56
- package/dist/loop/step/hooks.js +0 -191
package/dist/flow/engine.js
CHANGED
|
@@ -1,61 +1,327 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Flow engine for workflow manifest v3 (`flow-3`). A flow is data: every value a stage sees
|
|
3
|
+
* comes from the flow's input and the outputs of the agents and tools before it. Returns
|
|
4
|
+
* effects only (SD-I1).
|
|
5
|
+
*
|
|
6
|
+
* - The first stage gets the flow's input; every later stage gets the previous output.
|
|
7
|
+
* - A Switch reads the previous output: a string is the case name, and so is an object's
|
|
8
|
+
* `route` field. The chosen case gets the whole output.
|
|
9
|
+
* - A Map runs over the previous output when it is an array, or over its `items` array.
|
|
10
|
+
* - A Parallel gives every branch the same input; its output is keyed by branch.
|
|
11
|
+
* - A Loop runs its body, asks its verifier for a verdict, and stops on a pass or retries with
|
|
12
|
+
* the feedback, up to `max` attempts. The body keeps its session. A verifier agent gets
|
|
13
|
+
* `{ task, response, iteration }`; an HTTP verifier `{ input, output, iteration }`. A body
|
|
14
|
+
* that starts with an HTTP stage, which takes an object, is retried with the Loop's input.
|
|
15
|
+
* - An HTTP stage (a tool node with `http`) checks its input against its input schema, then
|
|
16
|
+
* runs as a `tool` effect the host makes through its Tool Gate. A failed request fails the
|
|
17
|
+
* stage with its code (`http.status`, `http.timeout`, `tool.invalid-output`, …).
|
|
18
|
+
* - Agent and tool sessions are named by leaf paths: the leaf's id, `[i]` per Map item,
|
|
19
|
+
* under nested flow agents' ids. Control stages add nothing.
|
|
20
|
+
* - Leaf agents come from the manifest's embedded `agents`; nested flow agents run inline
|
|
21
|
+
* with their own input. An agent effect carries its flow agent's input as `flowInput`
|
|
22
|
+
* when the stage's own input differs, so the host can show the agent the original request.
|
|
23
|
+
*/
|
|
24
|
+
import { HarnessError, ROOT_POSITION, canonical, childPosition, hashManifest, indexSuffix, isVerdict, isWorkflowManifest, leafPart, leafPath, schemaFromJSON, stageKey, } from "@nylorun/core/define";
|
|
2
25
|
import { WorkflowManifestSchema } from "@nylorun/core/contracts";
|
|
3
|
-
import { hashManifest } from "@nylorun/core/define";
|
|
4
26
|
import { HostSuspension } from "../loop/host-suspension.js";
|
|
5
|
-
import { CHECKPOINT_VERSION,
|
|
6
|
-
import { createFlowContext, failureOf, settleInFlight } from "./context.js";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
27
|
+
import { CHECKPOINT_VERSION, FLOW_ENGINE_VERSION } from "../compatibility.js";
|
|
28
|
+
import { createFlowContext, failureOf, markFailFastCancels, settleInFlight, suspendedResult, } from "./context.js";
|
|
29
|
+
import { assertLoopIteration, assertMapItemCount } from "./limits.js";
|
|
30
|
+
import { iterationsOf } from "./paths.js";
|
|
31
|
+
import { runToolEffect } from "./tool.js";
|
|
10
32
|
import { FlowNodeError } from "./types.js";
|
|
11
|
-
/**
|
|
12
|
-
* Deterministic flow interpreter for workflow manifests. v2 manifests run on the
|
|
13
|
-
* `flow-2` engine (`./v2.ts`); v1 manifests on `flow-1`, one module per primitive.
|
|
14
|
-
* Returns effects only (SD-I1).
|
|
15
|
-
*/
|
|
16
33
|
export async function runFlowDurable(options) {
|
|
17
|
-
const { manifest, checkpoint,
|
|
34
|
+
const { manifest, checkpoint, signal } = options;
|
|
18
35
|
WorkflowManifestSchema.parse(manifest);
|
|
19
36
|
if (checkpoint.version !== CHECKPOINT_VERSION ||
|
|
20
|
-
checkpoint.engineVersion !==
|
|
37
|
+
checkpoint.engineVersion !== FLOW_ENGINE_VERSION ||
|
|
21
38
|
checkpoint.manifestHash !== hashManifest(manifest))
|
|
22
39
|
throw new HarnessError("execution.incompatible", "Incompatible flow checkpoint");
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
40
|
+
const ctx = createFlowContext(options);
|
|
41
|
+
const scope = {
|
|
42
|
+
manifest,
|
|
43
|
+
flow: [],
|
|
44
|
+
pathPrefix: "",
|
|
45
|
+
keyPrefix: "",
|
|
46
|
+
pending: [],
|
|
47
|
+
indices: [],
|
|
48
|
+
iterations: [],
|
|
49
|
+
flowInput: checkpoint.input,
|
|
50
|
+
};
|
|
32
51
|
try {
|
|
33
52
|
if (signal?.aborted)
|
|
34
53
|
return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
|
|
35
|
-
const output = await runNode(ctx, root,
|
|
36
|
-
return {
|
|
37
|
-
status: "completed",
|
|
38
|
-
checkpoint,
|
|
39
|
-
result: { status: "completed", output },
|
|
40
|
-
};
|
|
54
|
+
const output = await runNode(ctx, scope, manifest.root, ROOT_POSITION, checkpoint.input);
|
|
55
|
+
return { status: "completed", checkpoint, result: { status: "completed", output } };
|
|
41
56
|
}
|
|
42
57
|
catch (error) {
|
|
43
58
|
await settleInFlight(ctx);
|
|
44
|
-
if (error instanceof HostSuspension)
|
|
45
|
-
return
|
|
46
|
-
status: [...ctx.pending.values()].includes("uncertain") ? "uncertain" : "waiting",
|
|
47
|
-
checkpoint,
|
|
48
|
-
effectIds: [...ctx.pending.keys()],
|
|
49
|
-
};
|
|
50
|
-
}
|
|
59
|
+
if (error instanceof HostSuspension)
|
|
60
|
+
return suspendedResult(ctx);
|
|
51
61
|
if (error instanceof FlowNodeError && error.failure.code === "cancelled")
|
|
52
62
|
return { status: "cancelled", checkpoint, result: { status: "cancelled" } };
|
|
53
|
-
const failure = failureOf(error, rootPath);
|
|
54
63
|
return {
|
|
55
64
|
status: "failed",
|
|
56
65
|
checkpoint,
|
|
57
|
-
result: { status: "failed", error:
|
|
66
|
+
result: { status: "failed", error: failureOf(error, manifest.id) },
|
|
58
67
|
...(ctx.cancelEffectIds.size > 0 ? { cancelEffectIds: [...ctx.cancelEffectIds] } : {}),
|
|
59
68
|
};
|
|
60
69
|
}
|
|
61
70
|
}
|
|
71
|
+
/** Where a node's effects are recorded: a leaf's path, or its stage key plus Map indices. */
|
|
72
|
+
function siteOf(scope, node, key) {
|
|
73
|
+
const part = leafPart(node);
|
|
74
|
+
return part === undefined
|
|
75
|
+
? `${key}${indexSuffix(scope.indices)}`
|
|
76
|
+
: leafPath(scope.pathPrefix, part, scope.pending);
|
|
77
|
+
}
|
|
78
|
+
async function runNode(ctx, scope, node, position, input, context = {}) {
|
|
79
|
+
const key = stageKey(node, position, scope.keyPrefix);
|
|
80
|
+
const site = siteOf(scope, node, key);
|
|
81
|
+
if ("agent" in node)
|
|
82
|
+
return runAgent(ctx, scope, node, key, site, input, context);
|
|
83
|
+
if ("tool" in node)
|
|
84
|
+
return runTool(ctx, scope, node.tool, key, site, input);
|
|
85
|
+
if ("chain" in node)
|
|
86
|
+
return runChain(ctx, scope, node.chain, position, input);
|
|
87
|
+
if ("switch" in node)
|
|
88
|
+
return runSwitch(ctx, scope, node.switch, site, position, input);
|
|
89
|
+
if ("parallel" in node)
|
|
90
|
+
return runParallel(ctx, scope, node.parallel, site, position, input);
|
|
91
|
+
if ("map" in node)
|
|
92
|
+
return runMap(ctx, scope, node.map.each, site, position, input);
|
|
93
|
+
if ("loop" in node)
|
|
94
|
+
return runLoop(ctx, scope, node.loop, site, position, input);
|
|
95
|
+
throw new HarnessError("execution.invalid-state", "Unknown workflow node kind");
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* An agent node: a leaf agent runs as one turn in its own session; a nested flow agent
|
|
99
|
+
* runs inline, under its own id, with its own input.
|
|
100
|
+
*/
|
|
101
|
+
async function runAgent(ctx, scope, node, key, site, input, context) {
|
|
102
|
+
const target = scope.manifest.agents[node.agent];
|
|
103
|
+
if (target === undefined)
|
|
104
|
+
throw new FlowNodeError({
|
|
105
|
+
code: "flow.unknown-agent",
|
|
106
|
+
message: `Agent '${node.agent}' is not embedded in flow agent '${scope.manifest.id}'`,
|
|
107
|
+
path: site,
|
|
108
|
+
});
|
|
109
|
+
if (isWorkflowManifest(target)) {
|
|
110
|
+
const flow = target;
|
|
111
|
+
const nested = {
|
|
112
|
+
manifest: flow,
|
|
113
|
+
flow: [...scope.flow, node.agent],
|
|
114
|
+
pathPrefix: site,
|
|
115
|
+
keyPrefix: key,
|
|
116
|
+
pending: [],
|
|
117
|
+
indices: scope.indices,
|
|
118
|
+
iterations: scope.iterations,
|
|
119
|
+
flowInput: input,
|
|
120
|
+
};
|
|
121
|
+
return runNode(ctx, nested, flow.root, ROOT_POSITION, input);
|
|
122
|
+
}
|
|
123
|
+
return (await ctx.effect("agent", {
|
|
124
|
+
agentId: node.agent,
|
|
125
|
+
input,
|
|
126
|
+
path: site,
|
|
127
|
+
...(scope.flow.length > 0 ? { flow: scope.flow } : {}),
|
|
128
|
+
...(canonical(input) === canonical(scope.flowInput) ? {} : { flowInput: scope.flowInput }),
|
|
129
|
+
}, { path: site, key, iterations: iterationsOf(scope.iterations) }, context));
|
|
130
|
+
}
|
|
131
|
+
async function runTool(ctx, scope, tool, key, site, input) {
|
|
132
|
+
if (tool.http && tool.inputSchema) {
|
|
133
|
+
const checked = schemaFromJSON(tool.inputSchema).validate(input);
|
|
134
|
+
if (!checked.ok)
|
|
135
|
+
throw new FlowNodeError({
|
|
136
|
+
code: "tool.invalid-input",
|
|
137
|
+
message: `HTTP stage '${tool.name}' got ${describe(input)}, which does not match its input schema: ${checked.issues.map((issue) => issue.message).join("; ")}`,
|
|
138
|
+
path: site,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
const value = await runToolEffect(ctx, tool.name, input, {
|
|
142
|
+
path: site,
|
|
143
|
+
key,
|
|
144
|
+
iterations: iterationsOf(scope.iterations),
|
|
145
|
+
});
|
|
146
|
+
return completedOutput(value, site);
|
|
147
|
+
}
|
|
148
|
+
/** The output of a settled tool outcome: `{ kind: "completed", output }`, or the value itself. */
|
|
149
|
+
function completedOutput(value, site) {
|
|
150
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
151
|
+
return value;
|
|
152
|
+
const outcome = value;
|
|
153
|
+
if (outcome.kind === "completed" && "output" in outcome)
|
|
154
|
+
return outcome.output ?? null;
|
|
155
|
+
if (outcome.kind === "denied")
|
|
156
|
+
throw new FlowNodeError({
|
|
157
|
+
code: "tool.denied",
|
|
158
|
+
message: typeof outcome.reason === "string" ? outcome.reason : "Tool call denied",
|
|
159
|
+
path: site,
|
|
160
|
+
});
|
|
161
|
+
return value;
|
|
162
|
+
}
|
|
163
|
+
/** Steps in order; each step's output is the next one's input. */
|
|
164
|
+
async function runChain(ctx, scope, steps, position, input) {
|
|
165
|
+
let current = input;
|
|
166
|
+
for (const [index, step] of steps.entries())
|
|
167
|
+
current = await runNode(ctx, scope, step, childPosition(position, index), current);
|
|
168
|
+
return current;
|
|
169
|
+
}
|
|
170
|
+
function isRecord(value) {
|
|
171
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
172
|
+
}
|
|
173
|
+
/** A short description of a value for a failure message. */
|
|
174
|
+
function describe(value) {
|
|
175
|
+
const text = JSON.stringify(value) ?? String(value);
|
|
176
|
+
return text.length > 80 ? `${text.slice(0, 77)}...` : text;
|
|
177
|
+
}
|
|
178
|
+
/** The case the previous output names: itself when a string, else its `route` field. */
|
|
179
|
+
async function runSwitch(ctx, scope, node, site, position, input) {
|
|
180
|
+
const name = typeof input === "string"
|
|
181
|
+
? input
|
|
182
|
+
: isRecord(input) && typeof input.route === "string"
|
|
183
|
+
? input.route
|
|
184
|
+
: undefined;
|
|
185
|
+
const chosen = name === undefined ? undefined : node.cases[name];
|
|
186
|
+
if (chosen)
|
|
187
|
+
return runNode(ctx, scope, chosen, childPosition(position, name), input);
|
|
188
|
+
if (node.default)
|
|
189
|
+
return runNode(ctx, scope, node.default, childPosition(position, "default"), input);
|
|
190
|
+
throw new FlowNodeError({
|
|
191
|
+
code: "switch.no-match",
|
|
192
|
+
message: name === undefined
|
|
193
|
+
? `Switch read ${describe(input)}, which names no case: the previous output must be a case name or an object with a string route field, and there is no default case`
|
|
194
|
+
: `Switch read the case name ${JSON.stringify(name)}, but no case has that name (cases: ${Object.keys(node.cases).join(", ")}) and there is no default case`,
|
|
195
|
+
path: site,
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
/** Run `tasks` together; fail fast on the first failure in declaration order. */
|
|
199
|
+
async function runTogether(ctx, tasks, pathOf) {
|
|
200
|
+
const outputs = new Array(tasks.length);
|
|
201
|
+
const suspensions = [];
|
|
202
|
+
const failures = [];
|
|
203
|
+
await Promise.all(tasks.map(async (task, index) => {
|
|
204
|
+
try {
|
|
205
|
+
outputs[index] = await task();
|
|
206
|
+
}
|
|
207
|
+
catch (error) {
|
|
208
|
+
if (error instanceof HostSuspension) {
|
|
209
|
+
suspensions.push(error);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
failures.push({
|
|
213
|
+
index,
|
|
214
|
+
error: error instanceof FlowNodeError
|
|
215
|
+
? error
|
|
216
|
+
: new FlowNodeError(failureOf(error, pathOf(index))),
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
}));
|
|
220
|
+
if (failures.length > 0) {
|
|
221
|
+
markFailFastCancels(ctx);
|
|
222
|
+
failures.sort((a, b) => a.index - b.index);
|
|
223
|
+
throw failures[0].error;
|
|
224
|
+
}
|
|
225
|
+
if (suspensions.length > 0)
|
|
226
|
+
throw suspensions[0];
|
|
227
|
+
return outputs;
|
|
228
|
+
}
|
|
229
|
+
/** Every branch gets the same input; the output is keyed by branch, in declaration order. */
|
|
230
|
+
async function runParallel(ctx, scope, branches, site, position, input) {
|
|
231
|
+
const names = Object.keys(branches);
|
|
232
|
+
const outputs = await runTogether(ctx, names.map((name) => () => runNode(ctx, scope, branches[name], childPosition(position, name), input)), () => site);
|
|
233
|
+
const result = {};
|
|
234
|
+
names.forEach((name, index) => {
|
|
235
|
+
result[name] = outputs[index];
|
|
236
|
+
});
|
|
237
|
+
return result;
|
|
238
|
+
}
|
|
239
|
+
/** Runs `each` once per item of the previous output, or of its `items`; output in item order. */
|
|
240
|
+
async function runMap(ctx, scope, each, site, position, input) {
|
|
241
|
+
const items = Array.isArray(input)
|
|
242
|
+
? input
|
|
243
|
+
: isRecord(input) && Array.isArray(input.items)
|
|
244
|
+
? input.items
|
|
245
|
+
: undefined;
|
|
246
|
+
if (!items)
|
|
247
|
+
throw new FlowNodeError({
|
|
248
|
+
code: "map.not-a-list",
|
|
249
|
+
message: `A Map runs over an array or { items: [...] }; got ${describe(input)}`,
|
|
250
|
+
path: site,
|
|
251
|
+
});
|
|
252
|
+
assertMapItemCount(items.length, ctx.limits, site);
|
|
253
|
+
if (items.length === 0)
|
|
254
|
+
return [];
|
|
255
|
+
const eachPosition = childPosition(position, "each");
|
|
256
|
+
return runTogether(ctx, items.map((item, index) => () => runNode(ctx, { ...scope, pending: [...scope.pending, index], indices: [...scope.indices, index] }, each, eachPosition, item)), (index) => `${site}[${index}]`);
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Run the body, ask the verifier agent, then stop on a pass or retry with the feedback. The
|
|
260
|
+
* body keeps its session across attempts; the verifier gets a fresh one per attempt.
|
|
261
|
+
*/
|
|
262
|
+
async function runLoop(ctx, scope, loop, site, position, input) {
|
|
263
|
+
const runPosition = childPosition(position, "run");
|
|
264
|
+
let current = input;
|
|
265
|
+
for (let iteration = 1;; iteration += 1) {
|
|
266
|
+
if (ctx.signal?.aborted)
|
|
267
|
+
throw new FlowNodeError({ code: "cancelled", message: "cancelled", path: site });
|
|
268
|
+
assertLoopIteration(iteration, ctx.limits, site);
|
|
269
|
+
const turn = { ...scope, iterations: [...scope.iterations, iteration] };
|
|
270
|
+
const loopContext = { loopPath: site, n: iteration };
|
|
271
|
+
const output = await runNode(ctx, turn, loop.run, runPosition, current, loopContext);
|
|
272
|
+
const verdict = await runVerify(ctx, turn, loop.verify, site, position, {
|
|
273
|
+
task: input,
|
|
274
|
+
response: output,
|
|
275
|
+
iteration,
|
|
276
|
+
context: loopContext,
|
|
277
|
+
});
|
|
278
|
+
if (verdict.pass)
|
|
279
|
+
return output;
|
|
280
|
+
if (iteration >= loop.max)
|
|
281
|
+
throw new FlowNodeError({
|
|
282
|
+
code: "loop.exhausted",
|
|
283
|
+
message: `Loop stopped after ${loop.max} attempt${loop.max === 1 ? "" : "s"}: ${verdict.feedback}`,
|
|
284
|
+
path: site,
|
|
285
|
+
});
|
|
286
|
+
current = startsWithHttpStage(loop.run) ? input : verdict.feedback;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
/** True when `node`'s first stage is an HTTP stage: it takes an object, never feedback text. */
|
|
290
|
+
function startsWithHttpStage(node) {
|
|
291
|
+
if ("chain" in node)
|
|
292
|
+
return node.chain.length > 0 && startsWithHttpStage(node.chain[0]);
|
|
293
|
+
return "tool" in node && node.tool.http !== undefined;
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* A verifier agent judges `{ task, response, iteration }`, an HTTP verifier
|
|
297
|
+
* `{ input, output, iteration }`; the output must be a verdict.
|
|
298
|
+
*/
|
|
299
|
+
async function runVerify(ctx, scope, verify, site, position, args) {
|
|
300
|
+
const at = childPosition(position, "verify");
|
|
301
|
+
let value;
|
|
302
|
+
try {
|
|
303
|
+
if ("http" in verify) {
|
|
304
|
+
const key = stageKey(verify, at, scope.keyPrefix);
|
|
305
|
+
const path = siteOf(scope, verify, key);
|
|
306
|
+
const raw = (await ctx.effect("tool", { input: args.task, output: args.response, iteration: args.iteration }, { path, key, iterations: iterationsOf(scope.iterations) }, { ...args.context, role: "verify-http" }));
|
|
307
|
+
value = completedOutput(raw, path);
|
|
308
|
+
}
|
|
309
|
+
else
|
|
310
|
+
value = await runNode(ctx, scope, verify, at, { task: args.task, response: args.response, iteration: args.iteration }, { ...args.context, role: "verify-agent" });
|
|
311
|
+
}
|
|
312
|
+
catch (error) {
|
|
313
|
+
if (error instanceof HostSuspension)
|
|
314
|
+
throw error;
|
|
315
|
+
const failure = failureOf(error, site);
|
|
316
|
+
if (failure.code === "loop.verify-failed")
|
|
317
|
+
throw error;
|
|
318
|
+
throw new FlowNodeError({ code: "loop.verify-failed", message: failure.message, path: site });
|
|
319
|
+
}
|
|
320
|
+
if (!isVerdict(value))
|
|
321
|
+
throw new FlowNodeError({
|
|
322
|
+
code: "loop.verify-failed",
|
|
323
|
+
message: `The verifier must return { pass: boolean, feedback?: string }, with feedback when pass is false; got ${describe(value)}`,
|
|
324
|
+
path: site,
|
|
325
|
+
});
|
|
326
|
+
return value;
|
|
327
|
+
}
|
package/dist/flow/index.d.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
export { createFlowCheckpoint, type FlowCheckpoint } from "./checkpoint.js";
|
|
1
|
+
export { createFlowCheckpoint, resumeFlowCheckpoint, type FlowCheckpoint, type FlowResume, } from "./checkpoint.js";
|
|
2
2
|
export { runFlowDurable } from "./engine.js";
|
|
3
|
-
export { runLoop, runLoopNode, agentTurnValue, AGENT_TURN_MARKER, type FlowDurableResult, type FlowRunResult, type AgentTurnValue, } from "./loop.js";
|
|
4
3
|
export { assertLoopIteration, assertMapItemCount, FLOW_OPERATOR_DEFAULTS, resolveOperatorLimits, type FlowOperatorLimits, } from "./limits.js";
|
|
5
|
-
export { flowEffectId, iterationsOf,
|
|
6
|
-
export {
|
|
7
|
-
export { FlowNodeError, failedValueOf } from "./types.js";
|
|
4
|
+
export { flowEffectId, iterationsOf, nodeKeyOf } from "./paths.js";
|
|
5
|
+
export { FlowNodeError, failedValueOf, type FlowDurableResult, type FlowInteraction, type FlowRunResult, } from "./types.js";
|
package/dist/flow/index.js
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
export { createFlowCheckpoint } from "./checkpoint.js";
|
|
1
|
+
export { createFlowCheckpoint, resumeFlowCheckpoint, } from "./checkpoint.js";
|
|
2
2
|
export { runFlowDurable } from "./engine.js";
|
|
3
|
-
export { runLoop, runLoopNode, agentTurnValue, AGENT_TURN_MARKER, } from "./loop.js";
|
|
4
3
|
export { assertLoopIteration, assertMapItemCount, FLOW_OPERATOR_DEFAULTS, resolveOperatorLimits, } from "./limits.js";
|
|
5
|
-
export { flowEffectId, iterationsOf,
|
|
6
|
-
export {
|
|
7
|
-
export { FlowNodeError, failedValueOf } from "./types.js";
|
|
4
|
+
export { flowEffectId, iterationsOf, nodeKeyOf } from "./paths.js";
|
|
5
|
+
export { FlowNodeError, failedValueOf, } from "./types.js";
|
package/dist/flow/paths.d.ts
CHANGED
|
@@ -1,18 +1,11 @@
|
|
|
1
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
2
|
/** Drop Map indices from a path to get the node key. */
|
|
9
3
|
export declare function nodeKeyOf(path: string): string;
|
|
10
4
|
/** Iteration vector string: enclosing Loop numbers outermost first, or "-" outside Loops. */
|
|
11
5
|
export declare function iterationsOf(vector: readonly number[]): string;
|
|
12
6
|
/**
|
|
13
7
|
* Effect id for a flow effect (workflows.md §10).
|
|
14
|
-
* `role` separates two effects of one kind on one path, e.g. a
|
|
15
|
-
* and the Map `over` or Switch `on` it wraps.
|
|
8
|
+
* `role` separates two effects of one kind on one path, e.g. a tool node's runs after it asked.
|
|
16
9
|
*/
|
|
17
10
|
export declare function flowEffectId(input: {
|
|
18
11
|
readonly turnId: string;
|
package/dist/flow/paths.js
CHANGED
|
@@ -1,14 +1,4 @@
|
|
|
1
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
2
|
/** Drop Map indices from a path to get the node key. */
|
|
13
3
|
export function nodeKeyOf(path) {
|
|
14
4
|
return path.replace(/\[\d+]/g, "");
|
|
@@ -19,8 +9,7 @@ export function iterationsOf(vector) {
|
|
|
19
9
|
}
|
|
20
10
|
/**
|
|
21
11
|
* Effect id for a flow effect (workflows.md §10).
|
|
22
|
-
* `role` separates two effects of one kind on one path, e.g. a
|
|
23
|
-
* and the Map `over` or Switch `on` it wraps.
|
|
12
|
+
* `role` separates two effects of one kind on one path, e.g. a tool node's runs after it asked.
|
|
24
13
|
*/
|
|
25
14
|
export function flowEffectId(input) {
|
|
26
15
|
const kind = input.role === undefined ? input.kind : `${input.kind}.${input.role}`;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { JsonValue } from "@nylorun/core/define";
|
|
2
|
+
import type { FlowContext } from "./context.js";
|
|
3
|
+
/**
|
|
4
|
+
* A tool node's settled value, through its waits. A tool that asks (`ctx.approve`, `ctx.ask`)
|
|
5
|
+
* settles `interaction-required` with a resume token: the flow pauses on it. Once the
|
|
6
|
+
* checkpoint holds the answer (`FlowCheckpoint.resumes`), the tool runs again as a new effect
|
|
7
|
+
* of the node (role `resume.<n>`) with the answer and the token. A rejected approval settles
|
|
8
|
+
* the node `denied` without running the tool again, as in the turn loop.
|
|
9
|
+
*/
|
|
10
|
+
export declare function runToolEffect(ctx: FlowContext, toolName: string, input: JsonValue, identity: {
|
|
11
|
+
readonly path: string;
|
|
12
|
+
readonly key: string;
|
|
13
|
+
readonly iterations: string;
|
|
14
|
+
}): Promise<JsonValue>;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { FlowNodeError } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* A tool node's settled value, through its waits. A tool that asks (`ctx.approve`, `ctx.ask`)
|
|
4
|
+
* settles `interaction-required` with a resume token: the flow pauses on it. Once the
|
|
5
|
+
* checkpoint holds the answer (`FlowCheckpoint.resumes`), the tool runs again as a new effect
|
|
6
|
+
* of the node (role `resume.<n>`) with the answer and the token. A rejected approval settles
|
|
7
|
+
* the node `denied` without running the tool again, as in the turn loop.
|
|
8
|
+
*/
|
|
9
|
+
export async function runToolEffect(ctx, toolName, input, identity) {
|
|
10
|
+
let context = { toolName };
|
|
11
|
+
for (let attempt = 0;; attempt += 1) {
|
|
12
|
+
const at = attempt === 0 ? identity : { ...identity, role: `resume.${attempt}` };
|
|
13
|
+
const value = (await ctx.effect("tool", input, at, context));
|
|
14
|
+
const asked = askedOf(value, identity.path);
|
|
15
|
+
if (!asked)
|
|
16
|
+
return value;
|
|
17
|
+
const invocationId = ctx.effectIdOf("tool", at);
|
|
18
|
+
const id = `${invocationId}:interaction`;
|
|
19
|
+
const answer = ctx.checkpoint.resumes?.[id];
|
|
20
|
+
if (!answer)
|
|
21
|
+
throw ctx.pause({
|
|
22
|
+
invocationId,
|
|
23
|
+
path: identity.path,
|
|
24
|
+
toolName,
|
|
25
|
+
interaction: { ...asked.interaction, id },
|
|
26
|
+
status: "interaction",
|
|
27
|
+
});
|
|
28
|
+
if (answer.kind === "approval" && !answer.approved)
|
|
29
|
+
return { kind: "denied", reason: "Approval rejected" };
|
|
30
|
+
context = {
|
|
31
|
+
toolName,
|
|
32
|
+
resume: {
|
|
33
|
+
interactionId: id,
|
|
34
|
+
...answer,
|
|
35
|
+
...(asked.token === undefined ? {} : { token: asked.token }),
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** The interaction an `interaction-required` outcome asks for, or undefined for any other value. */
|
|
41
|
+
function askedOf(raw, path) {
|
|
42
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
43
|
+
return undefined;
|
|
44
|
+
const value = raw;
|
|
45
|
+
if (value.kind !== "interaction-required")
|
|
46
|
+
return undefined;
|
|
47
|
+
const interaction = value.interaction;
|
|
48
|
+
if (!interaction ||
|
|
49
|
+
(interaction.kind !== "approval" && interaction.kind !== "response") ||
|
|
50
|
+
typeof interaction.prompt !== "string")
|
|
51
|
+
throw new FlowNodeError({
|
|
52
|
+
code: "tool.invalid-tool-result",
|
|
53
|
+
message: "Tool returned an invalid interaction",
|
|
54
|
+
path,
|
|
55
|
+
});
|
|
56
|
+
const metadata = interaction.metadata;
|
|
57
|
+
return {
|
|
58
|
+
interaction: {
|
|
59
|
+
kind: interaction.kind,
|
|
60
|
+
prompt: interaction.prompt,
|
|
61
|
+
...(metadata && typeof metadata === "object" && !Array.isArray(metadata)
|
|
62
|
+
? { metadata: metadata }
|
|
63
|
+
: {}),
|
|
64
|
+
},
|
|
65
|
+
...(value.token === undefined ? {} : { token: value.token }),
|
|
66
|
+
};
|
|
67
|
+
}
|
package/dist/flow/types.d.ts
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
|
-
import type { JsonValue } from "@nylorun/core/define";
|
|
1
|
+
import type { JsonObject, JsonValue } from "@nylorun/core/define";
|
|
2
|
+
import { HostSuspension } from "../loop/host-suspension.js";
|
|
2
3
|
import type { FlowCheckpoint } from "./checkpoint.js";
|
|
4
|
+
/**
|
|
5
|
+
* An interaction the flow itself waits on: a tool node that asked (`ctx.approve`, `ctx.ask`).
|
|
6
|
+
* The tool's resume token stays in its journaled outcome, never here.
|
|
7
|
+
*/
|
|
8
|
+
export type FlowInteraction = {
|
|
9
|
+
/** The effect of the tool run that asked. */
|
|
10
|
+
readonly invocationId: string;
|
|
11
|
+
/** The tool node's path. */
|
|
12
|
+
readonly path: string;
|
|
13
|
+
readonly toolName: string;
|
|
14
|
+
readonly interaction: {
|
|
15
|
+
readonly id: string;
|
|
16
|
+
readonly kind: "approval" | "response";
|
|
17
|
+
readonly prompt: string;
|
|
18
|
+
readonly metadata?: JsonObject;
|
|
19
|
+
};
|
|
20
|
+
readonly status: "interaction";
|
|
21
|
+
};
|
|
3
22
|
export type FlowRunResult = {
|
|
4
23
|
readonly status: "completed";
|
|
5
24
|
readonly output: JsonValue;
|
|
@@ -14,7 +33,7 @@ export type FlowRunResult = {
|
|
|
14
33
|
readonly status: "cancelled";
|
|
15
34
|
} | {
|
|
16
35
|
readonly status: "paused";
|
|
17
|
-
readonly pending:
|
|
36
|
+
readonly pending: readonly FlowInteraction[];
|
|
18
37
|
};
|
|
19
38
|
export type FlowDurableResult = {
|
|
20
39
|
readonly status: "waiting" | "uncertain";
|
|
@@ -41,5 +60,13 @@ export declare class FlowNodeError extends Error {
|
|
|
41
60
|
readonly failure: FlowFailure;
|
|
42
61
|
constructor(failure: FlowFailure);
|
|
43
62
|
}
|
|
44
|
-
/**
|
|
63
|
+
/**
|
|
64
|
+
* A tool node waits on an interaction. Unwinds like a suspension (siblings keep running), and
|
|
65
|
+
* the flow pauses once nothing else is pending.
|
|
66
|
+
*/
|
|
67
|
+
export declare class FlowPause extends HostSuspension {
|
|
68
|
+
readonly interaction: FlowInteraction;
|
|
69
|
+
constructor(interaction: FlowInteraction);
|
|
70
|
+
}
|
|
71
|
+
/** Completed effect value that encodes a curated failure (a tool's failure / agent settle). */
|
|
45
72
|
export declare function failedValueOf(value: unknown): FlowFailure | undefined;
|
package/dist/flow/types.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { HostSuspension } from "../loop/host-suspension.js";
|
|
1
2
|
/** Thrown when a node fails; unwinds to the engine root. */
|
|
2
3
|
export class FlowNodeError extends Error {
|
|
3
4
|
failure;
|
|
@@ -7,7 +8,19 @@ export class FlowNodeError extends Error {
|
|
|
7
8
|
this.name = "FlowNodeError";
|
|
8
9
|
}
|
|
9
10
|
}
|
|
10
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* A tool node waits on an interaction. Unwinds like a suspension (siblings keep running), and
|
|
13
|
+
* the flow pauses once nothing else is pending.
|
|
14
|
+
*/
|
|
15
|
+
export class FlowPause extends HostSuspension {
|
|
16
|
+
interaction;
|
|
17
|
+
constructor(interaction) {
|
|
18
|
+
super(interaction.invocationId, "pending");
|
|
19
|
+
this.interaction = interaction;
|
|
20
|
+
this.name = "FlowPause";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** Completed effect value that encodes a curated failure (a tool's failure / agent settle). */
|
|
11
24
|
export function failedValueOf(value) {
|
|
12
25
|
if (!value || typeof value !== "object")
|
|
13
26
|
return undefined;
|