agentfootprint 7.9.0 → 7.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +2 -2
  2. package/dist/core-flow/Graph.js +607 -0
  3. package/dist/core-flow/Graph.js.map +1 -0
  4. package/dist/core-flow/Workflow.js +210 -0
  5. package/dist/core-flow/Workflow.js.map +1 -0
  6. package/dist/esm/core-flow/Graph.d.ts +272 -0
  7. package/dist/esm/core-flow/Graph.js +601 -0
  8. package/dist/esm/core-flow/Graph.js.map +1 -0
  9. package/dist/esm/core-flow/Workflow.d.ts +146 -0
  10. package/dist/esm/core-flow/Workflow.js +205 -0
  11. package/dist/esm/core-flow/Workflow.js.map +1 -0
  12. package/dist/esm/index.d.ts +2 -0
  13. package/dist/esm/index.js +2 -0
  14. package/dist/esm/index.js.map +1 -1
  15. package/dist/esm/patterns/LlmRouter.d.ts +221 -0
  16. package/dist/esm/patterns/LlmRouter.js +400 -0
  17. package/dist/esm/patterns/LlmRouter.js.map +1 -0
  18. package/dist/esm/patterns/LlmSwarm.d.ts +100 -0
  19. package/dist/esm/patterns/LlmSwarm.js +109 -0
  20. package/dist/esm/patterns/LlmSwarm.js.map +1 -0
  21. package/dist/esm/patterns/index.d.ts +2 -0
  22. package/dist/esm/patterns/index.js +2 -0
  23. package/dist/esm/patterns/index.js.map +1 -1
  24. package/dist/index.js +7 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/patterns/LlmRouter.js +406 -0
  27. package/dist/patterns/LlmRouter.js.map +1 -0
  28. package/dist/patterns/LlmSwarm.js +113 -0
  29. package/dist/patterns/LlmSwarm.js.map +1 -0
  30. package/dist/patterns/index.js +6 -1
  31. package/dist/patterns/index.js.map +1 -1
  32. package/dist/types/core-flow/Graph.d.ts +273 -0
  33. package/dist/types/core-flow/Graph.d.ts.map +1 -0
  34. package/dist/types/core-flow/Workflow.d.ts +147 -0
  35. package/dist/types/core-flow/Workflow.d.ts.map +1 -0
  36. package/dist/types/index.d.ts +2 -0
  37. package/dist/types/index.d.ts.map +1 -1
  38. package/dist/types/patterns/LlmRouter.d.ts +222 -0
  39. package/dist/types/patterns/LlmRouter.d.ts.map +1 -0
  40. package/dist/types/patterns/LlmSwarm.d.ts +101 -0
  41. package/dist/types/patterns/LlmSwarm.d.ts.map +1 -0
  42. package/dist/types/patterns/index.d.ts +2 -0
  43. package/dist/types/patterns/index.d.ts.map +1 -1
  44. package/package.json +1 -1
@@ -0,0 +1,601 @@
1
+ /**
2
+ * graph() — a FIXED DAG of runners, levelized at build time.
3
+ *
4
+ * WHY this exists: `Sequence` and `workflow()` run steps in a line, and
5
+ * `Parallel` fans out ONCE and merges. Real pipelines are neither: an
6
+ * intake step feeds two independent lookups, and a writer waits for both.
7
+ * Expressing that with the existing compositions means nesting a Parallel
8
+ * inside a Sequence and threading values through by hand — and on this
9
+ * codebase that hand-off silently loses structured data (see "The trap"
10
+ * below). `graph()` states the shape once, as nodes and edges, and lets
11
+ * the engine work out what can run at the same time.
12
+ *
13
+ * What it gives you:
14
+ * - **Concurrency you did not have to schedule.** Kahn levelization at
15
+ * BUILD time groups nodes with no dependency between them; every node
16
+ * in a level runs at the same time.
17
+ * - **A shape checked before it runs.** A cycle, an edge pointing at a
18
+ * node that does not exist, or a duplicate id is refused at BUILD
19
+ * time, naming the offender. You cannot construct a broken graph.
20
+ * - **No silent merges.** A node with two or more parents MUST declare
21
+ * a `join` — a silent merge is a wrong merge, so the build refuses
22
+ * and names the node.
23
+ * - **Values, not text.** An edge's payload is the producer's OUTPUT
24
+ * handed to the consumer, unchanged. There is no shared mutable scope
25
+ * between nodes: a node reads exactly what its parents produced.
26
+ *
27
+ * Pattern: Adapter over footprintjs's subflow mounts — a level with
28
+ * several nodes becomes stacked `addSubFlowChart` calls (a fork,
29
+ * run concurrently); a level with one node is mounted
30
+ * sequentially (`addSubFlowChartNext`, which resumes cleanly
31
+ * across a pause). One join stage between levels.
32
+ * Role: core-flow/ layer, alongside Sequence/Parallel/Conditional/
33
+ * Loop/Workflow. Pure control flow — no LLM dependency.
34
+ * Emits: agentfootprint.composition.enter / exit, reported as kind
35
+ * `'Sequence'`. See "Why kind 'Sequence'" below.
36
+ *
37
+ * ## The trap this was built around (verified against footprintjs, not docs)
38
+ *
39
+ * The obvious sketch — `graph = Sequence(Parallel(level0), Parallel(level1), …)`
40
+ * — does NOT work on this codebase, for two independent reasons:
41
+ *
42
+ * 1. `Sequence`'s step contract is `{ message: string } -> string`, and
43
+ * its step `outputMapper` coerces a non-string step output to `''`.
44
+ * `workflow()` (v7.10.0) exists precisely because of this.
45
+ * 2. `Parallel` has the SAME limit one layer down: its branch type is
46
+ * `Runner<{ message: string }, string>` and its branch `outputMapper`
47
+ * coerces a non-string branch output to `''` (`Parallel.ts`, the
48
+ * `typeof sfOutput === 'string' ? sfOutput : ''` mapper). So a
49
+ * Parallel level cannot carry a structured value either.
50
+ *
51
+ * So `graph()` is built on the pass-through model `workflow()` established
52
+ * — its own composition, its own mappers, the same recorder wiring and the
53
+ * same `composition.enter` / `exit` events — rather than on top of
54
+ * Sequence/Parallel.
55
+ *
56
+ * ## Why kind 'Sequence'
57
+ *
58
+ * `CompositionKind` is a CLOSED public union (`'Sequence' | 'Parallel' |
59
+ * 'Conditional' | 'Loop'`). Widening it would break exhaustive switches in
60
+ * consumer code for no behavioural gain — the same call v7.10.0 made for
61
+ * `workflow()`. A graph's LEVELS are a sequence (level 0, then level 1, …),
62
+ * so `'Sequence'` is the honest member of that union: this composition runs
63
+ * its levels in order. The fan-out WITHIN a level is visible in the chart
64
+ * itself (a fork node per level), which is where a renderer reads it from.
65
+ *
66
+ * ## Honest limits (all verified against the engine, pinned in tests)
67
+ *
68
+ * 1. Only PLAIN DATA crosses a node boundary — the same limit
69
+ * `workflow()` documents. A value with a prototype (Date, Map, class
70
+ * instance) arrives as `{}`; `undefined` fields are dropped.
71
+ * 2. A node must RETURN its output: the value handed to its children is
72
+ * the node chart's traversal result.
73
+ * 3. A node that THROWS is always reported as
74
+ * `graph '<id>': node '<node>' failed: <reason>`, but it reaches that
75
+ * sentence by two different routes. In a CONCURRENT level footprintjs
76
+ * runs children under `Promise.allSettled`, so a failed child is
77
+ * simply ABSENT from the results and the level join turns that
78
+ * absence into the error. In a SEQUENTIAL (single-node) level the
79
+ * error rejects the run raw, and `rethrowWithNodeAttribution` renames
80
+ * it. Consumers see one shape either way.
81
+ * 4. A node that PAUSES surfaces as a pause — the engine halts the
82
+ * traversal before the level's join runs, so `run()` returns a
83
+ * `RunnerPauseOutcome`. `resume()` then carries on through the REST
84
+ * of the graph only when the paused node was ALONE in its level (a
85
+ * sequential mount). Resuming into a fork child completes that child
86
+ * and stops: the remaining levels do not run. Give a node that asks a
87
+ * human a level of its own. Both halves are pinned in tests.
88
+ *
89
+ * @example a diamond: A feeds B and C, D waits for both
90
+ * ```ts
91
+ * const pipeline = graph({
92
+ * nodes: [
93
+ * { id: 'intake', runner: intake },
94
+ * { id: 'orders', runner: lookupOrders },
95
+ * { id: 'billing', runner: lookupBilling },
96
+ * {
97
+ * id: 'reply',
98
+ * runner: writeReply,
99
+ * // Two parents ⇒ a join is REQUIRED. `upstream` is keyed by node id.
100
+ * join: (upstream) => ({
101
+ * orders: upstream.orders as OrderInfo,
102
+ * billing: upstream.billing as BillingInfo,
103
+ * }),
104
+ * },
105
+ * ],
106
+ * edges: [
107
+ * { from: 'intake', to: 'orders' },
108
+ * { from: 'intake', to: 'billing' },
109
+ * { from: 'orders', to: 'reply' },
110
+ * { from: 'billing', to: 'reply' },
111
+ * ],
112
+ * });
113
+ *
114
+ * const out = await pipeline.run({ message: 'where is my refund?' });
115
+ * // out = { intake: …, orders: …, billing: …, reply: … } — keyed by node id
116
+ * ```
117
+ */
118
+ import { FlowChartExecutor, flowChart, isFlowEvent, } from 'footprintjs';
119
+ import { RunnerBase, makeRunId } from '../core/RunnerBase.js';
120
+ import { agentRecorder } from '../recorders/core/AgentRecorder.js';
121
+ import { compositionRecorder } from '../recorders/core/CompositionRecorder.js';
122
+ import { ContextRecorder } from '../recorders/core/ContextRecorder.js';
123
+ import { streamRecorder } from '../recorders/core/StreamRecorder.js';
124
+ import { typedEmit } from '../recorders/core/typedEmit.js';
125
+ /**
126
+ * The one sentence every node failure is reported with, whatever mount the
127
+ * level used. A graph has two mount paths — a fork for concurrent levels, a
128
+ * sequential mount for single-node ones — and footprintjs surfaces failures
129
+ * differently through each (a fork child's error is swallowed into absence;
130
+ * a sequential child's rejects the run raw). Consumers should not have to
131
+ * know which one they got, so both are reported like this.
132
+ */
133
+ function nodeFailureMessage(graphId, nodeId, reason) {
134
+ return `graph '${graphId}': node '${nodeId}' failed: ${reason}`;
135
+ }
136
+ // ─── Build-time validation + levelization ────────────────────────────
137
+ /**
138
+ * Kahn levelization: group nodes so that everything in level N depends
139
+ * only on levels < N. Nodes within a level are independent BY
140
+ * CONSTRUCTION, which is exactly the licence to run them concurrently.
141
+ *
142
+ * Declaration order is preserved inside each level so a graph's chart —
143
+ * and therefore its trace — is deterministic.
144
+ *
145
+ * Throws (naming the offender) on: an unknown edge endpoint, a duplicate
146
+ * node id, a cycle, or a fan-in > 1 with no `join`.
147
+ */
148
+ export function levelize(nodes, edges) {
149
+ if (nodes.length === 0) {
150
+ throw new Error('graph: needs at least one node');
151
+ }
152
+ const byId = new Map();
153
+ for (const node of nodes) {
154
+ if (byId.has(node.id)) {
155
+ throw new Error(`graph: duplicate node id '${node.id}' — every node id must be unique (it is the results key).`);
156
+ }
157
+ byId.set(node.id, node);
158
+ }
159
+ const parents = new Map();
160
+ const children = new Map();
161
+ for (const node of nodes) {
162
+ parents.set(node.id, []);
163
+ children.set(node.id, []);
164
+ }
165
+ for (const edge of edges) {
166
+ if (!byId.has(edge.from)) {
167
+ throw new Error(`graph: edge '${edge.from}' -> '${edge.to}' references unknown node '${edge.from}'.`);
168
+ }
169
+ if (!byId.has(edge.to)) {
170
+ throw new Error(`graph: edge '${edge.from}' -> '${edge.to}' references unknown node '${edge.to}'.`);
171
+ }
172
+ parents.get(edge.to)?.push(edge.from);
173
+ children.get(edge.from)?.push(edge.to);
174
+ }
175
+ // Fan-in > 1 demands an explicit join. Checked BEFORE the cycle walk so
176
+ // the more actionable error wins on a graph that has both problems.
177
+ for (const node of nodes) {
178
+ const up = parents.get(node.id) ?? [];
179
+ if (up.length > 1 && node.join === undefined) {
180
+ throw new Error(`graph: node '${node.id}' has ${up.length} parents (${up.join(', ')}) but no join — ` +
181
+ 'a silent merge is a wrong merge. Give the node a join(upstream) that returns its input; ' +
182
+ 'upstream is keyed by parent node id.');
183
+ }
184
+ }
185
+ // Kahn: repeatedly take every node whose parents have all been placed.
186
+ const remainingParents = new Map();
187
+ for (const node of nodes)
188
+ remainingParents.set(node.id, (parents.get(node.id) ?? []).length);
189
+ const levels = [];
190
+ let frontier = nodes.filter((n) => remainingParents.get(n.id) === 0);
191
+ let placed = 0;
192
+ while (frontier.length > 0) {
193
+ levels.push(frontier);
194
+ placed += frontier.length;
195
+ const next = [];
196
+ for (const node of frontier) {
197
+ for (const childId of children.get(node.id) ?? []) {
198
+ const left = (remainingParents.get(childId) ?? 0) - 1;
199
+ remainingParents.set(childId, left);
200
+ if (left === 0) {
201
+ const child = byId.get(childId);
202
+ if (child !== undefined)
203
+ next.push(child);
204
+ }
205
+ }
206
+ }
207
+ // Restore declaration order — `next` is built in parent-visit order.
208
+ frontier = nodes.filter((n) => next.includes(n));
209
+ }
210
+ if (placed < nodes.length) {
211
+ const stuck = new Set(nodes.filter((n) => (remainingParents.get(n.id) ?? 0) > 0).map((n) => n.id));
212
+ throw new Error(`graph: cycle detected — edge '${findBackEdge(stuck, edges)}' closes a loop. A graph must be acyclic.`);
213
+ }
214
+ return levels;
215
+ }
216
+ /**
217
+ * Name ONE edge that closes a cycle, so the error can point at something
218
+ * the author can delete. Depth-first over the nodes Kahn could not place;
219
+ * the first edge back onto the current stack is the one reported.
220
+ */
221
+ function findBackEdge(stuck, edges) {
222
+ const out = new Map();
223
+ for (const edge of edges) {
224
+ if (stuck.has(edge.from) && stuck.has(edge.to)) {
225
+ const list = out.get(edge.from) ?? [];
226
+ list.push(edge.to);
227
+ out.set(edge.from, list);
228
+ }
229
+ }
230
+ const onStack = new Set();
231
+ const done = new Set();
232
+ let found;
233
+ const walk = (id) => {
234
+ if (found !== undefined)
235
+ return;
236
+ onStack.add(id);
237
+ for (const next of out.get(id) ?? []) {
238
+ if (found !== undefined)
239
+ return;
240
+ if (onStack.has(next)) {
241
+ found = `${id}' -> '${next}`;
242
+ return;
243
+ }
244
+ if (!done.has(next))
245
+ walk(next);
246
+ }
247
+ onStack.delete(id);
248
+ done.add(id);
249
+ };
250
+ for (const id of stuck) {
251
+ if (!done.has(id))
252
+ walk(id);
253
+ if (found !== undefined)
254
+ break;
255
+ }
256
+ // Every unplaced node is on a cycle, so a back edge always exists; the
257
+ // fallback keeps the error useful rather than throwing inside a thrower.
258
+ return found ?? [...stuck].join("' -> '");
259
+ }
260
+ /**
261
+ * Hand a producer's value to a consumer as its input args.
262
+ *
263
+ * `string` → `{ message }` (the house convention every LLM runner here
264
+ * speaks, identical to `workflow()`'s hand-off rule). Plain object →
265
+ * itself. Anything else is a broken hand-off and says so, naming both
266
+ * ends — the alternative is an empty input inside the consumer with
267
+ * nothing pointing back here.
268
+ */
269
+ function toNodeArgs(value, nodeId, source) {
270
+ if (typeof value === 'string')
271
+ return { message: value };
272
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
273
+ return { ...value };
274
+ }
275
+ const got = value === null ? 'null' : Array.isArray(value) ? 'an array' : typeof value;
276
+ throw new Error(`graph: ${source} handed node '${nodeId}' ${got}, but a node needs an object ` +
277
+ '(or a string, which arrives as { message }). Make each node return its output.');
278
+ }
279
+ // ─── The composition ─────────────────────────────────────────────────
280
+ /**
281
+ * A fixed DAG of runners. Build one with {@link graph}.
282
+ */
283
+ export class Graph extends RunnerBase {
284
+ name;
285
+ id;
286
+ nodes;
287
+ levels;
288
+ parentsOf;
289
+ opts;
290
+ currentRunContext = {
291
+ runStartMs: 0,
292
+ runId: 'pending',
293
+ compositionPath: [],
294
+ };
295
+ /**
296
+ * Per-node first-error records for the current run. footprintjs's
297
+ * `SubflowExecutor` swallows a subflow error into the parent's debug
298
+ * bag and skips the `outputMapper`, so the message never reaches parent
299
+ * scope on its own. An internal recorder captures it here; the level
300
+ * join reads it to name what actually went wrong. Mirrors Parallel's
301
+ * `branchErrors`, epoch-guarded for the same reason.
302
+ */
303
+ nodeErrors = new Map();
304
+ /** Monotonic run token — see Parallel's `runEpoch`. */
305
+ runEpoch = 0;
306
+ constructor(opts) {
307
+ super();
308
+ this.opts = opts;
309
+ this.name = opts.name ?? 'Graph';
310
+ this.id = opts.id ?? 'graph';
311
+ this.nodes = opts.nodes;
312
+ // Levelization VALIDATES — a broken graph throws here, at construction.
313
+ this.levels = levelize(opts.nodes, opts.edges);
314
+ const parents = new Map();
315
+ for (const node of opts.nodes)
316
+ parents.set(node.id, []);
317
+ for (const edge of opts.edges)
318
+ parents.get(edge.to)?.push(edge.from);
319
+ this.parentsOf = parents;
320
+ // Eager chart construction — see `RunnerBase.initChart` JSDoc.
321
+ this.initChart(() => this.buildChart());
322
+ }
323
+ /** How the graph was levelized — level 0 first. Stable post-construction. */
324
+ getLevels() {
325
+ return this.levels.map((level) => level.map((n) => n.id));
326
+ }
327
+ async run(input, options) {
328
+ const executor = this.createExecutor();
329
+ this.lastExecutor = executor;
330
+ let result;
331
+ try {
332
+ result = await executor.run({ input: { ...input }, ...(options ?? {}) });
333
+ }
334
+ catch (err) {
335
+ this.rethrowWithNodeAttribution(err);
336
+ }
337
+ return this.finalizeResult(executor, result);
338
+ }
339
+ async resume(checkpoint, input, options) {
340
+ this.emitPauseResume(checkpoint, input);
341
+ const executor = this.createExecutor();
342
+ this.lastExecutor = executor;
343
+ let result;
344
+ try {
345
+ result = await executor.resume(checkpoint, input, options);
346
+ }
347
+ catch (err) {
348
+ this.rethrowWithNodeAttribution(err);
349
+ }
350
+ return this.finalizeResult(executor, result);
351
+ }
352
+ /**
353
+ * Give a RAW rejection the same node-naming shape the level join
354
+ * produces.
355
+ *
356
+ * A node in a SEQUENTIAL (single-node) level rejects the run with its
357
+ * own error — the level join never runs, so nothing has attributed it to
358
+ * a node yet. The error recorder did see it, so correlate (by identity
359
+ * first, then bare message) and rename. Anything that does not correlate
360
+ * — including the join's own already-attributed error — is rethrown
361
+ * untouched.
362
+ */
363
+ rethrowWithNodeAttribution(err) {
364
+ const message = err instanceof Error ? err.message : String(err);
365
+ for (const [nodeId, record] of this.nodeErrors) {
366
+ if (record.raw === err || record.message === message) {
367
+ throw new Error(nodeFailureMessage(this.id, nodeId, record.message), { cause: err });
368
+ }
369
+ }
370
+ throw err;
371
+ }
372
+ createExecutor() {
373
+ this.currentRunContext = {
374
+ runStartMs: Date.now(),
375
+ runId: makeRunId(),
376
+ compositionPath: [`Graph:${this.id}`],
377
+ };
378
+ this.runEpoch += 1;
379
+ this.nodeErrors.clear();
380
+ const executor = new FlowChartExecutor(this.getSpec());
381
+ const dispatcher = this.getDispatcher();
382
+ const getRunCtx = () => this.currentRunContext;
383
+ executor.attachCombinedRecorder(new ContextRecorder({ dispatcher, getRunContext: getRunCtx }));
384
+ executor.attachCombinedRecorder(streamRecorder({ dispatcher, getRunContext: getRunCtx }));
385
+ executor.attachCombinedRecorder(agentRecorder({ dispatcher, getRunContext: getRunCtx }));
386
+ executor.attachCombinedRecorder(compositionRecorder({ dispatcher, getRunContext: getRunCtx }));
387
+ executor.attachCombinedRecorder(this.makeNodeErrorRecorder(this.runEpoch));
388
+ for (const r of this.attachedRecorders)
389
+ executor.attachCombinedRecorder(r);
390
+ return executor;
391
+ }
392
+ /**
393
+ * Capture the first error per node. The node id is the first segment of
394
+ * the engine-prefixed `stageId` (`orders/call-llm` → node `orders`) —
395
+ * the same correlation Parallel uses, and the only one that survives a
396
+ * node mounting subflows of its own.
397
+ */
398
+ makeNodeErrorRecorder(epoch) {
399
+ const nodeIds = new Set(this.nodes.map((n) => n.id));
400
+ return {
401
+ id: 'graph-node-errors',
402
+ onError: (event) => {
403
+ if (epoch !== this.runEpoch)
404
+ return; // straggler from a dead run
405
+ if (!isFlowEvent(event))
406
+ return;
407
+ const stageId = event.traversalContext?.stageId ?? '';
408
+ const slash = stageId.indexOf('/');
409
+ const nodeId = slash >= 0 ? stageId.slice(0, slash) : undefined;
410
+ if (nodeId === undefined || !nodeIds.has(nodeId))
411
+ return;
412
+ if (this.nodeErrors.has(nodeId))
413
+ return;
414
+ const structured = event.structuredError;
415
+ const message = structured?.message ??
416
+ (event.message.startsWith('Error: ')
417
+ ? event.message.slice('Error: '.length)
418
+ : event.message);
419
+ this.nodeErrors.set(nodeId, { message, raw: structured?.raw });
420
+ },
421
+ };
422
+ }
423
+ finalizeResult(executor, result) {
424
+ const paused = this.detectPause(executor, result);
425
+ if (paused)
426
+ return paused;
427
+ if (result instanceof Error)
428
+ throw result;
429
+ return (result ?? {});
430
+ }
431
+ buildChart() {
432
+ const compositionId = this.id;
433
+ const compositionName = this.name;
434
+ const nodeCount = this.nodes.length;
435
+ const levels = this.levels;
436
+ const nodeErrors = this.nodeErrors;
437
+ const seed = (scope) => {
438
+ // The graph's own input is what every ROOT node receives.
439
+ scope.graphInput = scope.$getArgs();
440
+ scope.results = {};
441
+ typedEmit(scope, 'agentfootprint.composition.enter', {
442
+ kind: 'Sequence',
443
+ id: compositionId,
444
+ name: compositionName,
445
+ childCount: nodeCount,
446
+ });
447
+ };
448
+ // Root description prefix `Sequence:` is the taxonomy marker every
449
+ // consumer (Lens, FlowchartRecorder.mapTopologyToSteps) already reads.
450
+ let builder = flowChart('Seed', seed, 'seed', {
451
+ ...(this.opts.structureRecorders !== undefined && {
452
+ structureRecorders: [...this.opts.structureRecorders],
453
+ }),
454
+ description: `Sequence: ${nodeCount}-node DAG in ${levels.length} level(s)`,
455
+ });
456
+ levels.forEach((level, levelIndex) => {
457
+ // A level with SEVERAL nodes is mounted on the SAME builder cursor —
458
+ // stacked `addSubFlowChart` calls produce a fork node, which
459
+ // footprintjs's ChildrenExecutor runs concurrently. That is the whole
460
+ // reason to levelize.
461
+ //
462
+ // A level with ONE node is mounted SEQUENTIALLY instead
463
+ // (`addSubFlowChartNext`). There is nothing to run it alongside, and
464
+ // the sequential mount is strictly better across a pause: resuming
465
+ // into a fork child completes THAT child and stops, whereas a
466
+ // sequential mount resumes and carries on through the rest of the
467
+ // graph. Verified against footprintjs; see the class JSDoc's
468
+ // "Honest limits".
469
+ const concurrent = level.length > 1;
470
+ for (const node of level) {
471
+ const mount = concurrent
472
+ ? builder.addSubFlowChart.bind(builder)
473
+ : builder.addSubFlowChartNext.bind(builder);
474
+ builder = mount(node.id, node.runner.getSpec(), node.name ?? node.id, {
475
+ // A THROW from an inputMapper (a broken hand-off, or a join that
476
+ // rejects what it got) is caught by footprintjs's SubflowExecutor
477
+ // and turned into a plain "this subflow did not run" — the reason
478
+ // never reaches parent scope. Record it first, so the level join
479
+ // can name what actually happened instead of 'unknown error'.
480
+ inputMapper: (parent) => {
481
+ try {
482
+ return this.inputForNode(node, parent);
483
+ }
484
+ catch (err) {
485
+ if (!nodeErrors.has(node.id)) {
486
+ nodeErrors.set(node.id, {
487
+ message: err instanceof Error ? err.message : String(err),
488
+ raw: err,
489
+ });
490
+ }
491
+ throw err;
492
+ }
493
+ },
494
+ // Untouched: whatever the node's chart returned is what its
495
+ // children (and the caller) receive. No string coercion — this
496
+ // is exactly what Sequence and Parallel cannot do.
497
+ outputMapper: (sfOutput) => ({ results: { [node.id]: sfOutput } }),
498
+ });
499
+ }
500
+ // The join stage does two jobs: it ADVANCES the builder cursor (so
501
+ // the next level forks from here instead of joining this level's
502
+ // fork), and it turns a failed node's ABSENCE into a loud error.
503
+ builder = builder.addFunction(`Level ${levelIndex} join`, (scope) => {
504
+ // Read through `$getValue`, never `scope.results`: values merged
505
+ // into parent state by a subflow outputMapper are present in
506
+ // shared state but do NOT enumerate through TypedScope's nested
507
+ // property proxy. Verified against footprintjs — the property
508
+ // read returns `{}` while `$getValue` returns the real record.
509
+ const results = scope.$getValue('results') ?? {};
510
+ const missing = level.map((n) => n.id).filter((id) => !(id in results));
511
+ if (missing.length > 0) {
512
+ typedEmit(scope, 'agentfootprint.composition.exit', {
513
+ kind: 'Sequence',
514
+ id: compositionId,
515
+ name: compositionName,
516
+ status: 'err',
517
+ durationMs: Date.now() - this.currentRunContext.runStartMs,
518
+ });
519
+ const reasonFor = (id) => nodeErrors.get(id)?.message ?? 'unknown error';
520
+ const firstMissing = missing[0] ?? '';
521
+ if (missing.length === 1) {
522
+ throw new Error(nodeFailureMessage(compositionId, firstMissing, reasonFor(firstMissing)));
523
+ }
524
+ const details = missing.map((id) => ` ${id}: ${reasonFor(id)}`).join('\n');
525
+ throw new Error(`graph '${compositionId}': ${missing.length} nodes failed in level ${levelIndex}:\n${details}`);
526
+ }
527
+ return undefined;
528
+ }, `level-${levelIndex}-join`, `Graph level ${levelIndex} join`);
529
+ });
530
+ builder = builder.addFunction('Finalize', (scope) => {
531
+ typedEmit(scope, 'agentfootprint.composition.exit', {
532
+ kind: 'Sequence',
533
+ id: compositionId,
534
+ name: compositionName,
535
+ status: 'ok',
536
+ durationMs: Date.now() - this.currentRunContext.runStartMs,
537
+ });
538
+ // `$getValue` for the same reason as the level join.
539
+ return scope.$getValue('results') ?? {};
540
+ }, 'finalize', 'Graph finalize');
541
+ return builder.build();
542
+ }
543
+ /**
544
+ * What one node receives. Roots get the graph's own input; a single
545
+ * parent is passed through; 2+ parents go through the node's `join`
546
+ * (which the build already guaranteed exists).
547
+ *
548
+ * `parent` here is the RAW parent state the engine hands an
549
+ * `inputMapper` — not a TypedScope — so structured upstream values read
550
+ * back intact.
551
+ */
552
+ inputForNode(node, parent) {
553
+ const results = parent.results ?? {};
554
+ const upstreamIds = this.parentsOf.get(node.id) ?? [];
555
+ if (upstreamIds.length === 0) {
556
+ return { ...(parent.graphInput ?? {}) };
557
+ }
558
+ if (node.join !== undefined) {
559
+ const upstream = {};
560
+ for (const id of upstreamIds)
561
+ upstream[id] = results[id];
562
+ return toNodeArgs(node.join(upstream), node.id, `join of node '${node.id}'`);
563
+ }
564
+ const only = upstreamIds[0] ?? '';
565
+ return toNodeArgs(results[only], node.id, `node '${only}'`);
566
+ }
567
+ }
568
+ // ─── The factory ─────────────────────────────────────────────────────
569
+ /**
570
+ * Build a fixed DAG of runners. Independent nodes run concurrently; the
571
+ * result is every node's output, keyed by node id.
572
+ *
573
+ * The shape is checked at BUILD time — a cycle, an edge pointing at an
574
+ * unknown node, a duplicate id, or a 2+-parent node with no `join` throws
575
+ * here, naming the offender, rather than misbehaving mid-run.
576
+ *
577
+ * @example a fan-out with a merge
578
+ * ```ts
579
+ * const pipeline = graph({
580
+ * nodes: [
581
+ * { id: 'plan', runner: planner },
582
+ * { id: 'search', runner: searcher },
583
+ * { id: 'recall', runner: memory },
584
+ * { id: 'answer', runner: writer, join: (u) => ({ ...u }) },
585
+ * ],
586
+ * edges: [
587
+ * { from: 'plan', to: 'search' },
588
+ * { from: 'plan', to: 'recall' },
589
+ * { from: 'search', to: 'answer' },
590
+ * { from: 'recall', to: 'answer' },
591
+ * ],
592
+ * });
593
+ *
594
+ * const out = await pipeline.run({ message: 'what changed last week?' });
595
+ * console.log(out.answer);
596
+ * ```
597
+ */
598
+ export function graph(opts) {
599
+ return new Graph(opts);
600
+ }
601
+ //# sourceMappingURL=Graph.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Graph.js","sourceRoot":"","sources":["../../../src/core-flow/Graph.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoHG;AAEH,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,WAAW,GAOZ,MAAM,aAAa,CAAC;AAIrB,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,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