agentfootprint 7.10.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.
@@ -0,0 +1,272 @@
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 { type FlowchartCheckpoint, type RunOptions, type StructureRecorder } from 'footprintjs';
119
+ import type { RunnerPauseOutcome } from '../core/pause.js';
120
+ import type { Runner } from '../core/runner.js';
121
+ import { RunnerBase } from '../core/RunnerBase.js';
122
+ /**
123
+ * One node of the graph: an id, the runner that does the work, and — when
124
+ * the node has more than one parent — how to merge what those parents
125
+ * produced into this node's input.
126
+ */
127
+ export interface GraphNode<I = unknown, O = unknown> {
128
+ /** Unique within the graph. Used as the results key and the chart node id. */
129
+ readonly id: string;
130
+ /** The work. Any Runner: LLMCall, Agent, a Sequence, another graph. */
131
+ readonly runner: Runner<I, O>;
132
+ /**
133
+ * Merge upstream outputs into this node's input. `upstream` is keyed by
134
+ * PARENT NODE ID, and each value is that parent's output, unchanged.
135
+ *
136
+ * Optional for a node with 0 or 1 parents (a single parent's output is
137
+ * passed through). **REQUIRED when a node has 2+ parents** — a silent
138
+ * merge is a wrong merge, so the build refuses and names the node.
139
+ */
140
+ readonly join?: (upstream: Readonly<Record<string, unknown>>) => I;
141
+ /** Human-friendly label for events + topology. Default: the node id. */
142
+ readonly name?: string;
143
+ }
144
+ /** A directed dependency: `from` must finish before `to` starts. */
145
+ export interface GraphEdge {
146
+ readonly from: string;
147
+ readonly to: string;
148
+ }
149
+ export interface GraphOptions {
150
+ /** The nodes. Ids must be unique; at least one is required. */
151
+ readonly nodes: readonly GraphNode<any, any>[];
152
+ /** The dependencies. Every endpoint must name a declared node. */
153
+ readonly edges: readonly GraphEdge[];
154
+ /** Human-friendly name for events + topology. Default `'Graph'`. */
155
+ readonly name?: string;
156
+ /** Stable id used for topology + events. Default `'graph'`. */
157
+ readonly id?: string;
158
+ /**
159
+ * Optional build-time recorders passed through to footprintjs's
160
+ * `flowChart()` factory — they observe this graph's OWN nodes (Seed +
161
+ * one mount per graph node + one join per level + Finalize). Not
162
+ * propagated into the mounted node charts; attach them to each node
163
+ * runner for full coverage.
164
+ */
165
+ readonly structureRecorders?: readonly StructureRecorder[];
166
+ }
167
+ /** The graph's own input — handed to every ROOT node (one with no parents). */
168
+ export type GraphInput = Record<string, unknown>;
169
+ /** Outputs keyed by node id. Every node that ran contributes one entry. */
170
+ export type GraphOutput = Record<string, unknown>;
171
+ /**
172
+ * Kahn levelization: group nodes so that everything in level N depends
173
+ * only on levels < N. Nodes within a level are independent BY
174
+ * CONSTRUCTION, which is exactly the licence to run them concurrently.
175
+ *
176
+ * Declaration order is preserved inside each level so a graph's chart —
177
+ * and therefore its trace — is deterministic.
178
+ *
179
+ * Throws (naming the offender) on: an unknown edge endpoint, a duplicate
180
+ * node id, a cycle, or a fan-in > 1 with no `join`.
181
+ */
182
+ export declare function levelize(nodes: readonly GraphNode<any, any>[], edges: readonly GraphEdge[]): readonly (readonly GraphNode<any, any>[])[];
183
+ /**
184
+ * A fixed DAG of runners. Build one with {@link graph}.
185
+ */
186
+ export declare class Graph extends RunnerBase<GraphInput, GraphOutput> {
187
+ readonly name: string;
188
+ readonly id: string;
189
+ private readonly nodes;
190
+ private readonly levels;
191
+ private readonly parentsOf;
192
+ private readonly opts;
193
+ private currentRunContext;
194
+ /**
195
+ * Per-node first-error records for the current run. footprintjs's
196
+ * `SubflowExecutor` swallows a subflow error into the parent's debug
197
+ * bag and skips the `outputMapper`, so the message never reaches parent
198
+ * scope on its own. An internal recorder captures it here; the level
199
+ * join reads it to name what actually went wrong. Mirrors Parallel's
200
+ * `branchErrors`, epoch-guarded for the same reason.
201
+ */
202
+ private readonly nodeErrors;
203
+ /** Monotonic run token — see Parallel's `runEpoch`. */
204
+ private runEpoch;
205
+ constructor(opts: GraphOptions);
206
+ /** How the graph was levelized — level 0 first. Stable post-construction. */
207
+ getLevels(): readonly (readonly string[])[];
208
+ run(input: GraphInput, options?: RunOptions): Promise<GraphOutput | RunnerPauseOutcome>;
209
+ resume(checkpoint: FlowchartCheckpoint, input?: unknown, options?: RunOptions): Promise<GraphOutput | RunnerPauseOutcome>;
210
+ /**
211
+ * Give a RAW rejection the same node-naming shape the level join
212
+ * produces.
213
+ *
214
+ * A node in a SEQUENTIAL (single-node) level rejects the run with its
215
+ * own error — the level join never runs, so nothing has attributed it to
216
+ * a node yet. The error recorder did see it, so correlate (by identity
217
+ * first, then bare message) and rename. Anything that does not correlate
218
+ * — including the join's own already-attributed error — is rethrown
219
+ * untouched.
220
+ */
221
+ private rethrowWithNodeAttribution;
222
+ private createExecutor;
223
+ /**
224
+ * Capture the first error per node. The node id is the first segment of
225
+ * the engine-prefixed `stageId` (`orders/call-llm` → node `orders`) —
226
+ * the same correlation Parallel uses, and the only one that survives a
227
+ * node mounting subflows of its own.
228
+ */
229
+ private makeNodeErrorRecorder;
230
+ private finalizeResult;
231
+ private buildChart;
232
+ /**
233
+ * What one node receives. Roots get the graph's own input; a single
234
+ * parent is passed through; 2+ parents go through the node's `join`
235
+ * (which the build already guaranteed exists).
236
+ *
237
+ * `parent` here is the RAW parent state the engine hands an
238
+ * `inputMapper` — not a TypedScope — so structured upstream values read
239
+ * back intact.
240
+ */
241
+ private inputForNode;
242
+ }
243
+ /**
244
+ * Build a fixed DAG of runners. Independent nodes run concurrently; the
245
+ * result is every node's output, keyed by node id.
246
+ *
247
+ * The shape is checked at BUILD time — a cycle, an edge pointing at an
248
+ * unknown node, a duplicate id, or a 2+-parent node with no `join` throws
249
+ * here, naming the offender, rather than misbehaving mid-run.
250
+ *
251
+ * @example a fan-out with a merge
252
+ * ```ts
253
+ * const pipeline = graph({
254
+ * nodes: [
255
+ * { id: 'plan', runner: planner },
256
+ * { id: 'search', runner: searcher },
257
+ * { id: 'recall', runner: memory },
258
+ * { id: 'answer', runner: writer, join: (u) => ({ ...u }) },
259
+ * ],
260
+ * edges: [
261
+ * { from: 'plan', to: 'search' },
262
+ * { from: 'plan', to: 'recall' },
263
+ * { from: 'search', to: 'answer' },
264
+ * { from: 'recall', to: 'answer' },
265
+ * ],
266
+ * });
267
+ *
268
+ * const out = await pipeline.run({ message: 'what changed last week?' });
269
+ * console.log(out.answer);
270
+ * ```
271
+ */
272
+ export declare function graph(opts: GraphOptions): Graph;