@nylorun/harness 0.19.2-beta → 0.21.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.
@@ -0,0 +1,370 @@
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
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Compaction (Model Calls §8): when history no longer fits the model's window, the engine
3
+ * asks the model to summarize the older part and keeps the rest verbatim.
4
+ *
5
+ * The cut rules and the summary format are adapted from the compaction in pi's
6
+ * `pi-agent-core` (MIT, Copyright (c) Earendil Works), rewritten for Nylorun's transcript.
7
+ */
8
+ import type { ModelAdapter, TranscriptCompactionEntry, TranscriptEntry } from "@nylorun/core/define";
9
+ export interface ContextBudget {
10
+ readonly contextWindow: number;
11
+ readonly reserve: number;
12
+ }
13
+ /**
14
+ * The window and output limit the adapter reported on the latest candidate
15
+ * (`evidence.extras.contextWindow`, `maxOutputTokens`). Undefined until a model has answered.
16
+ */
17
+ export declare function contextBudget(transcript: readonly TranscriptEntry[]): ContextBudget | undefined;
18
+ /**
19
+ * Tokens the next prompt needs: the last reported usage, which already counts the
20
+ * instructions, tools and everything before it, plus an estimate of what came after.
21
+ * Without usage, everything is estimated.
22
+ */
23
+ export declare function estimateTokens(transcript: readonly TranscriptEntry[]): number;
24
+ /** A rough token count of what one entry contributes to a prompt. */
25
+ export declare function entryTokens(entry: TranscriptEntry): number;
26
+ /**
27
+ * Where the kept tail starts. It keeps about `keepTokens` of the newest entries, never
28
+ * starts with tool results (their call stays with them), and never keeps the previous
29
+ * summary. Returns 0 or 1 when there is nothing older to summarize.
30
+ */
31
+ export declare function findCut(transcript: readonly TranscriptEntry[], keepTokens: number): number;
32
+ export interface CompactionInput {
33
+ readonly transcript: readonly TranscriptEntry[];
34
+ readonly executionId: string;
35
+ readonly turnId: string;
36
+ readonly stepId: string;
37
+ readonly trigger: "threshold" | "overflow";
38
+ readonly budget: ContextBudget | undefined;
39
+ readonly invoke: ModelAdapter;
40
+ readonly signal: AbortSignal;
41
+ }
42
+ /**
43
+ * Summarize everything before the cut with one model call and return the new transcript,
44
+ * or undefined when there is nothing older to summarize. The current turn's messages from
45
+ * the user stay verbatim even when the cut falls inside the turn.
46
+ */
47
+ export declare function compact(input: CompactionInput): Promise<readonly TranscriptEntry[] | undefined>;
48
+ /** How a compaction entry reaches the model: a user message ahead of the kept tail. */
49
+ export declare function summaryPrompt(entry: TranscriptCompactionEntry): string;