@spendgraph/graph 0.4.0 → 0.6.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 spendgraph
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -2,153 +2,42 @@
2
2
 
3
3
  Wire nodes into a graph, run it, and get back a rollout with every step.
4
4
 
5
- ```sh
5
+ ```bash
6
6
  npm install @spendgraph/graph
7
7
  ```
8
8
 
9
- Four things are exported. Everything else hangs off what they return.
10
-
11
- ```ts
12
- import { graph, node, edge, end } from "@spendgraph/graph";
13
- ```
14
-
15
- ## A node
16
-
17
- One unit of work. `input` is what makes it reusable: the node says what it
18
- needs, the graph says where it comes from. Without that, every node has to know
19
- about the whole run.
20
-
21
9
  ```ts
22
- const classify = node({
23
- name: "classify",
24
- args: [
25
- { name: "text", type: "string", required: true },
26
- { name: "top_k", type: "number", required: false },
27
- ] as const,
28
- input: (ctx) => ({ text: ctx.values.question }),
29
- run: ({ text, top_k }) => model.classify(text, top_k ?? 3),
30
- });
31
- ```
32
-
33
- **Write `as const` and `run` types itself** from the args — `text` a string,
34
- `top_k` a number, optionals optional. Rename an argument and the handler stops
35
- compiling, rather than being handed `undefined` halfway through a graph, which
36
- is the most expensive place to find a typo.
37
-
38
- Args are validated before `run` does any work. A node name must be letters,
39
- digits and underscores starting with a letter, and that is checked at import
40
- rather than on the first run.
41
-
42
- ## Wiring
10
+ import { edge, end, graph, node } from "@spendgraph/graph";
43
11
 
44
- ```ts
45
12
  const flow = graph({
46
- entry: "classify",
47
- nodes: [classify, lookup, answer],
48
- edges: [
49
- edge("classify", "lookup", (ctx) => ctx.outputs.classify === "billing"),
50
- edge("classify", "answer"),
51
- edge("lookup", "answer"),
52
- end("answer"),
53
- ],
13
+ entry: "parse",
14
+ nodes: [parse, divide, format],
15
+ edges: [edge("parse", "divide"), edge("divide", "format"), end("format")],
54
16
  });
55
17
 
56
- const result = await flow.execute({ question: "Why was I charged twice?" });
57
- ```
58
-
59
- An edge says what runs next; a node's `input` says on what.
60
-
61
- **Branching is several edges, not one clever edge.** `edge(from, to, when)`
62
- takes a predicate, and the edges leaving a node are tried in declaration order
63
- with the first match winning — so an unconditional edge is the default branch
64
- and belongs last. `end(from)` is `edge(from, null)` said out loud.
65
-
66
- Compilation checks the wiring — an edge to a node that does not exist, an entry
67
- that is not a node, two nodes with the same name, a node nothing reaches —
68
- before anything runs. Those are the one place this package throws.
69
-
70
- ## When a node fails
71
-
72
- A run never throws. A node that throws, or is handed an argument that does not
73
- validate, halts the run and comes back as a result:
74
-
75
- ```ts
76
- result.status; // "failed"
77
- result.error; // '"lookup" failed: contract MSA 2.4 not found'
78
- result.steps; // the steps that did run, with the failed one last
79
- ```
80
-
81
- Continuing would leave every later node reading an output that was never
82
- written. Stopping with the steps intact is what lets a failed run say which
83
- three nodes ran and where it stopped, which a thrown exception cannot.
84
-
85
- `maxSteps` bounds the run and defaults to 25. A backwards edge is a feature and
86
- also how a graph hangs, and nothing tells the two apart statically, so the guard
87
- is a count and a clear failure rather than a hung process.
88
-
89
- ## Watching it run
90
-
91
- `stream` is the same run, narrated — a node's start and end, whatever its nodes
92
- emit while running, and the finished result last.
93
-
94
- ```ts
95
- const running = flow.stream({ question });
96
-
97
- for await (const event of running) {
98
- if (event.type === "token") process.stdout.write(event.text);
99
- }
100
-
101
- const result = await running.result;
102
- ```
103
-
104
- A node writes into the stream through the `emit` it is handed, so a node that
105
- wraps a streaming model call can forward deltas without the graph knowing what a
106
- token is. The run begins on the call rather than on the first read, so
107
- `result` is there for a caller who wants the rollout and not the commentary.
108
-
109
- ## What comes back
110
-
111
- ```ts
112
- result.status; // "completed" | "failed"
113
- result.output; // the last node's return, stringified; "" on a failure
114
- result.steps; // every node that ran, in order
115
- result.outputs; // each node's return, by name
116
- result.latencyMs;
117
- result.inputTokens; // summed across every step, nested ones included
118
- result.outputTokens;
18
+ const result = await flow.execute({ expression: "12 / 4" });
119
19
  ```
120
20
 
121
- A graph run is a rollout with several steps, so `GraphResult` hands straight to
122
- `@spendgraph/prompt`'s `report` and `call` without being translated first:
123
-
124
- ```ts
125
- await prompt.call(values, () => flow.execute(values));
126
- ```
21
+ ## What you get
127
22
 
128
- ## Context
23
+ - **A run comes back as a rollout** — every step, in order, ready to report.
24
+ - **Compilation refuses what would fail at run time**: an unreachable node, an
25
+ edge to nothing, a graph with no way out.
26
+ - **Handlers typed from their args**, the same inference `tools` uses.
27
+ - **A node can stop to ask a person**, and the graph reports the question rather
28
+ than walking past it.
129
29
 
130
- `outputs` is the only channel between nodes. A shared mutable bag would let node
131
- four depend on a key node two happens to set — a dependency the graph does not
132
- declare and compilation cannot check.
30
+ ## Docs
133
31
 
134
- ```ts
135
- ctx.values; // what execute() was called with
136
- ctx.outputs; // what each finished node returned, by name
137
- ctx.steps; // the steps so far; a copy, so writing to it does nothing
138
- ```
139
-
140
- ## Inspecting one
141
-
142
- A compiled graph answers questions about itself, which is what the workflows in
143
- `@spendgraph/harness` build on.
144
-
145
- ```ts
146
- flow.entry; // where a run starts
147
- flow.maxSteps;
148
- flow.nodes(); // every node, in declaration order
149
- flow.edgesFrom("classify"); // the edges leaving it, in the order they are tried
150
- ```
32
+ | | |
33
+ | --- | --- |
34
+ | [Overview](https://spendgraph.locusgraph.com/docs/graph/overview) | Four exports, and the whole thing in one example |
35
+ | [Nodes](https://spendgraph.locusgraph.com/docs/graph/nodes) | One unit of work, typed from its args |
36
+ | [Wiring](https://spendgraph.locusgraph.com/docs/graph/wiring) | Edges, branching, and what compilation refuses |
37
+ | [Running a graph](https://spendgraph.locusgraph.com/docs/graph/running) | Failure, the step ceiling, what comes back |
38
+ | [Streaming](https://spendgraph.locusgraph.com/docs/graph/streaming) | The same run, narrated |
39
+ | [Pausing](https://spendgraph.locusgraph.com/docs/graph/pausing) | Stopping to ask a person, and picking it back up |
151
40
 
152
41
  ## License
153
42
 
154
- MIT
43
+ Apache-2.0
@@ -1,5 +1,5 @@
1
1
  import { type GraphStream } from "../execute/index.js";
2
- import type { Edge, GraphResult, GraphSpec, Node } from "../types/index.js";
2
+ import type { Edge, GraphResult, GraphRunOptions, GraphSpec, Node } from "../types/index.js";
3
3
  export interface GraphOptions {
4
4
  /** Injectable clock, so tests do not measure real time. */
5
5
  now?: () => number;
@@ -16,7 +16,7 @@ export declare function graph(spec: GraphSpec, opts?: GraphOptions): {
16
16
  * Runs it once. Never throws — the result carries every step taken, so a
17
17
  * run that stopped at node three still says which three and why.
18
18
  */
19
- execute: (values?: Record<string, unknown>) => Promise<GraphResult>;
19
+ execute: (values?: Record<string, unknown>, opts?: GraphRunOptions) => Promise<GraphResult>;
20
20
  /**
21
21
  * The same run, narrated. Yields a node's start and end, whatever its nodes
22
22
  * emit while running, and the finished result last.
@@ -24,6 +24,6 @@ export declare function graph(spec: GraphSpec, opts?: GraphOptions): {
24
24
  * The run begins on the call, not on the first read, so `result` is there
25
25
  * for the caller who wants the rollout and not the commentary.
26
26
  */
27
- stream: (values?: Record<string, unknown>) => GraphStream;
27
+ stream: (values?: Record<string, unknown>, opts?: GraphRunOptions) => GraphStream;
28
28
  };
29
29
  export type Graph = ReturnType<typeof graph>;
@@ -1,17 +1 @@
1
- import { executeGraph, streamGraph } from "../execute/index.js";
2
- import { assertAllReachable, indexEdges, indexNodes } from "./validate.js";
3
- export function graph(spec, opts = {}) {
4
- const now = opts.now ?? (() => Date.now());
5
- const maxSteps = Math.max(1, spec.maxSteps ?? 25);
6
- const byName = indexNodes(spec);
7
- const edgesFrom = indexEdges(spec.edges ?? [], byName);
8
- assertAllReachable(spec.entry, byName, edgesFrom);
9
- return {
10
- entry: spec.entry,
11
- maxSteps,
12
- nodes: () => [...byName.values()],
13
- edgesFrom: (name) => [...(edgesFrom.get(name) ?? [])],
14
- execute: (values = {}) => executeGraph(byName, edgesFrom, spec.entry, maxSteps, values, now),
15
- stream: (values = {}) => streamGraph(byName, edgesFrom, spec.entry, maxSteps, values, now),
16
- };
17
- }
1
+ import{executeGraph as m,streamGraph as i}from"../execute/index.js";import{assertAllReachable as g,assertEveryBranchIsCovered as x,ceilingFor as y,indexEdges as u,indexNodes as h}from"./validate.js";function f(e,d={}){const s=d.now??(()=>Date.now()),o=y(e.maxSteps),r=h(e),t=u(e.edges??[],r);return g(e.entry,r,t),x(t),{entry:e.entry,maxSteps:o,nodes:()=>[...r.values()],edgesFrom:n=>[...t.get(n)??[]],execute:(n={},a={})=>m(r,t,e.entry,o,n,s,void 0,a),stream:(n={},a={})=>i(r,t,e.entry,o,n,s,a)}}export{f as graph};
@@ -1 +1 @@
1
- export { graph } from "./compile.js";
1
+ import{graph as p}from"./compile.js";export{p as graph};
@@ -8,6 +8,38 @@ import type { Edge, GraphSpec, Node } from "../types/index.js";
8
8
  */
9
9
  export declare function indexNodes(spec: GraphSpec): Map<string, Node<never>>;
10
10
  export declare function indexEdges(edges: Edge[], byName: Map<string, Node<never>>): Map<string, Edge[]>;
11
+ /** The default when a spec names no ceiling. */
12
+ export declare const DEFAULT_MAX_STEPS = 25;
13
+ /**
14
+ * The step ceiling, refusing one that would not be a ceiling.
15
+ *
16
+ * `NaN` is the case worth catching: `Math.max(1, NaN)` is `NaN`, and
17
+ * `steps.length >= NaN` is false forever, so the one guard against a runaway
18
+ * quietly turns off. A cyclic graph then spins with no way to interrupt it —
19
+ * a synchronous node starves the event loop with microtasks, so not even a
20
+ * timer fires. `Number(process.env.MAX_STEPS)` on an unset variable is `NaN`,
21
+ * which is how a config gets here without anyone writing it.
22
+ *
23
+ * `Infinity` is refused too, and deliberately. It reads as "no limit", and the
24
+ * limit is the point: a graph is a DAG whose ceiling exists to stop a cycle.
25
+ */
26
+ export declare function ceilingFor(maxSteps: number | undefined): number;
27
+ /**
28
+ * Refuses a node whose way out is only half specified.
29
+ *
30
+ * A node with **no** edges is the end of a run — the author wrote none, and
31
+ * meant it. A node with edges that are **all conditional** is a different thing:
32
+ * a run arriving there with every condition false has nowhere to go, stops, and
33
+ * reports `completed`. The graph skipped the rest of its work and called it
34
+ * success, which is the answer nobody wants and nobody asked for.
35
+ *
36
+ * So the line is between saying nothing and saying half of it. Declaring where a
37
+ * run goes is a decision; declaring it only for some cases is the decision left
38
+ * unfinished, and this is the same argument as `assertAllReachable` one step
39
+ * later — a node nothing reaches is a typo caught at build time, a node nothing
40
+ * *leaves* is the same typo caught on the branch nobody exercised.
41
+ */
42
+ export declare function assertEveryBranchIsCovered(edgesFrom: Map<string, Edge[]>): void;
11
43
  /**
12
44
  * Refuses a node nothing reaches.
13
45
  *
@@ -1,51 +1 @@
1
- export function indexNodes(spec) {
2
- if (spec.nodes.length === 0)
3
- throw new Error("A graph needs at least one node.");
4
- const byName = new Map();
5
- for (const n of spec.nodes) {
6
- if (byName.has(n.name))
7
- throw new Error(`Two nodes are called "${n.name}".`);
8
- byName.set(n.name, n);
9
- }
10
- if (!byName.has(spec.entry)) {
11
- throw new Error(`The entry node "${spec.entry}" is not in this graph. Known: ${[...byName.keys()].join(", ")}.`);
12
- }
13
- return byName;
14
- }
15
- export function indexEdges(edges, byName) {
16
- const edgesFrom = new Map();
17
- for (const e of edges) {
18
- if (!byName.has(e.from)) {
19
- throw new Error(`An edge starts at "${e.from}", which is not a node in this graph.`);
20
- }
21
- if (e.to !== null && !byName.has(e.to)) {
22
- throw new Error(`An edge from "${e.from}" points at "${e.to}", which is not a node in this graph.`);
23
- }
24
- const list = edgesFrom.get(e.from) ?? [];
25
- const open = list.find((prior) => !prior.when);
26
- if (open) {
27
- throw new Error(`The edge from "${e.from}" to "${open.to ?? "the end"}" has no condition, so the edge ` +
28
- `to "${e.to ?? "the end"}" declared after it can never be taken. Put the unconditional edge last.`);
29
- }
30
- list.push(e);
31
- edgesFrom.set(e.from, list);
32
- }
33
- return edgesFrom;
34
- }
35
- export function assertAllReachable(entry, byName, edgesFrom) {
36
- const reached = new Set([entry]);
37
- const queue = [entry];
38
- while (queue.length) {
39
- for (const e of edgesFrom.get(queue.shift()) ?? []) {
40
- if (e.to && !reached.has(e.to)) {
41
- reached.add(e.to);
42
- queue.push(e.to);
43
- }
44
- }
45
- }
46
- const orphans = [...byName.keys()].filter((n) => !reached.has(n));
47
- if (orphans.length) {
48
- throw new Error(`Nothing reaches ${orphans.map((n) => `"${n}"`).join(", ")} from "${entry}". ` +
49
- `Add an edge, or take the node out.`);
50
- }
51
- }
1
+ function d(e){if(e.nodes.length===0)throw new Error("A graph needs at least one node.");const n=new Map;for(const o of e.nodes){if(n.has(o.name))throw new Error(`Two nodes are called "${o.name}".`);n.set(o.name,o)}if(!n.has(e.entry))throw new Error(`The entry node "${e.entry}" is not in this graph. Known: ${s(n)}.`);return n}function s(e){return[...e.keys()].join(", ")}function f(e,n){const o=new Map;for(const t of e){if(!n.has(t.from))throw new Error(`An edge starts at "${t.from}", which is not a node in this graph. Known: ${s(n)}.`);if(t.to!==null&&!n.has(t.to))throw new Error(`An edge from "${t.from}" points at "${t.to}", which is not a node in this graph. Known: ${s(n)}.`);const i=o.get(t.from)??[],h=i.find(r=>!r.when);if(h)throw new Error(`The edge from "${t.from}" to "${h.to??"the end"}" has no condition, so the edge to "${t.to??"the end"}" declared after it can never be taken. Put the unconditional edge last.`);i.push(t),o.set(t.from,i)}return o}const a=25;function c(e){if(e===void 0)return a;if(!Number.isFinite(e))throw new Error(`maxSteps is ${e}, which is not a ceiling \u2014 a run would never stop at it. Give it a finite number, or leave it out for the default of 25.`);return Math.max(1,Math.floor(e))}function w(e){const n=[...e.entries()].filter(([,o])=>o.length>0&&o.every(t=>t.when)).map(([o])=>o);if(n.length!==0)throw new Error(`${n.map(o=>`"${o}"`).join(", ")} ${n.length===1?"has":"have"} only conditional edges, so a run where none of them match stops there and reports success. Add an unconditional edge as the default, or end("${n[0]}") to stop there on purpose.`)}function l(e,n,o){const t=new Set([e]),i=[e];for(;i.length;)for(const r of o.get(i.shift())??[])r.to&&!t.has(r.to)&&(t.add(r.to),i.push(r.to));const h=[...n.keys()].filter(r=>!t.has(r));if(h.length)throw new Error(`Nothing reaches ${h.map(r=>`"${r}"`).join(", ")} from "${e}". Add an edge, or take the node out.`)}export{a as DEFAULT_MAX_STEPS,l as assertAllReachable,w as assertEveryBranchIsCovered,c as ceilingFor,f as indexEdges,d as indexNodes};
@@ -1,4 +1,4 @@
1
- import type { Edge, GraphEvent, GraphResult, Node } from "../types/index.js";
1
+ import type { Edge, GraphEvent, GraphResult, GraphRunOptions, Node } from "../types/index.js";
2
2
  /**
3
3
  * Runs a compiled graph.
4
4
  *
@@ -13,4 +13,4 @@ import type { Edge, GraphEvent, GraphResult, Node } from "../types/index.js";
13
13
  * absence changes nothing, so the streamed and unstreamed paths stay one piece
14
14
  * of code rather than two that drift.
15
15
  */
16
- export declare function executeGraph(byName: Map<string, Node<never>>, edgesFrom: Map<string, Edge[]>, entry: string, maxSteps: number, values: Record<string, unknown>, now: () => number, sink?: (event: GraphEvent) => void): Promise<GraphResult>;
16
+ export declare function executeGraph(byName: Map<string, Node<never>>, edgesFrom: Map<string, Edge[]>, entry: string, maxSteps: number, values: Record<string, unknown>, now: () => number, sink?: (event: GraphEvent) => void, opts?: GraphRunOptions): Promise<GraphResult>;
@@ -1,92 +1 @@
1
- import { FieldValidationError, validateFields } from "@spendgraph/sdk";
2
- import { nestedSteps, outputOf, tokensOf, totalTokens } from "./outcome.js";
3
- import { failedStep, message } from "./step.js";
4
- function ended(node, index, status, latencyMs, output, error) {
5
- return { type: "node_end", node, index, status, output, error, latencyMs };
6
- }
7
- export async function executeGraph(byName, edgesFrom, entry, maxSteps, values, now, sink = () => { }) {
8
- const startedAt = now();
9
- const steps = [];
10
- const outputs = {};
11
- const context = (node) => ({
12
- values,
13
- outputs,
14
- steps: [...steps],
15
- emit: (text) => sink({ type: "token", node, text }),
16
- });
17
- const finish = (status, error) => ({
18
- status,
19
- output: status === "completed" ? (steps.at(-1)?.output ?? "") : "",
20
- error,
21
- steps,
22
- outputs,
23
- latencyMs: now() - startedAt,
24
- ...totalTokens(steps),
25
- });
26
- let current = entry;
27
- while (current) {
28
- if (steps.length >= maxSteps) {
29
- return finish("failed", `Ran ${maxSteps} steps without reaching an end, stopping at "${current}". ` +
30
- `Either a conditional edge never turns false, or maxSteps is too low for this graph.`);
31
- }
32
- const node = byName.get(current);
33
- const startedNode = now();
34
- const ctx = context(current);
35
- const index = steps.length;
36
- let input;
37
- try {
38
- input = node.input ? node.input(ctx) : values;
39
- }
40
- catch (err) {
41
- steps.push(failedStep(index, node.name, {}, now() - startedNode, message(err)));
42
- sink(ended(node.name, index, "failed", now() - startedNode, undefined, message(err)));
43
- return finish("failed", `Building the input for "${node.name}" threw: ${message(err)}`);
44
- }
45
- sink({ type: "node_start", node: node.name, index, input });
46
- if (node.args?.length) {
47
- const errors = validateFields(input, node.args);
48
- if (errors.length > 0) {
49
- const detail = new FieldValidationError(errors).message;
50
- steps.push(failedStep(index, node.name, input, now() - startedNode, detail));
51
- sink(ended(node.name, index, "failed", now() - startedNode, undefined, detail));
52
- return finish("failed", `"${node.name}" was given ${detail}`);
53
- }
54
- }
55
- let value;
56
- try {
57
- value = await node.run(input, ctx);
58
- }
59
- catch (err) {
60
- steps.push(failedStep(index, node.name, input, now() - startedNode, message(err)));
61
- sink(ended(node.name, index, "failed", now() - startedNode, undefined, message(err)));
62
- return finish("failed", `"${node.name}" failed: ${message(err)}`);
63
- }
64
- outputs[node.name] = value;
65
- steps.push({
66
- index,
67
- source: node.name,
68
- input,
69
- output: outputOf(value),
70
- status: "completed",
71
- latencyMs: now() - startedNode,
72
- ...tokensOf(value),
73
- });
74
- steps.push(...nestedSteps(value, steps.length, node.name));
75
- sink(ended(node.name, index, "completed", now() - startedNode, value));
76
- let next = null;
77
- try {
78
- const after = context(node.name);
79
- for (const e of edgesFrom.get(node.name) ?? []) {
80
- if (e.when && !e.when(after))
81
- continue;
82
- next = e.to;
83
- break;
84
- }
85
- }
86
- catch (err) {
87
- return finish("failed", `Choosing what runs after "${node.name}" threw: ${message(err)}`);
88
- }
89
- current = next;
90
- }
91
- return finish("completed");
92
- }
1
+ import{FieldValidationError as _,validateFields as j}from"@spendgraph/sdk";import{pausedInside as B}from"../types/index.js";import{nestedSteps as C,outputOf as G,tokensOf as K,totalTokens as R}from"./outcome.js";import{failedStep as F,message as m,sealed as g}from"./step.js";function w(r,t,i,u,h,n){return{type:"node_end",node:r,index:t,status:i,output:h,error:n,latencyMs:u}}function T(r,t){if(!r.args?.length)return null;const i=j(t,r.args);return i.length>0?new _(i).message:null}function V(r,t){let i;for(const u of r)if(!u.when||(i??=t(),u.when(i)))return u.to;return null}function q(r,t,i,u,h){return h({type:"paused",node:i,index:u,waitingOn:t.waitingOn,...t.runId?{runId:t.runId}:{}}),{...r,waitingOn:t.waitingOn,...t.runId?{waitingFor:t.runId}:{}}}async function L(r,t,i,u,h,n,c=()=>{},x={}){const S=n(),v=(x.steps??[]).map(g),a=[...v],I={...x.outputs},E=e=>({values:h,outputs:I,steps:[...a],emit:o=>c({type:"token",node:e,text:o})}),l=(e,o)=>({status:e,output:e==="completed"?a.at(-1)?.output??"":"",error:o,steps:a,outputs:I,latencyMs:n()-S,...R(a)}),O=x.entry??i;if(!r.has(O))return l("failed",`No node is called "${O}", so there is nowhere to start. \`entry\` names where a resumed run picks up. Known: ${[...r.keys()].join(", ")}.`);let $=O;for(;$;){if(a.length-v.length>=u)return l("failed",`Ran ${u} steps without reaching an end, stopping at "${$}". Either a conditional edge never turns false, or maxSteps is too low for this graph.`);const e=r.get($),o=n(),A=E($),s=a.length;let p;try{p=e.input?e.input(A):h}catch(d){return a.push(g(F(s,e.name,{},n()-o,m(d)))),c(w(e.name,s,"failed",n()-o,void 0,m(d))),l("failed",`Building the input for "${e.name}" threw: ${m(d)}`)}c({type:"node_start",node:e.name,index:s,input:p});const y=T(e,p);if(y)return a.push(g(F(s,e.name,p,n()-o,y))),c(w(e.name,s,"failed",n()-o,void 0,y)),l("failed",`"${e.name}" was given ${y}`);let f;try{f=await e.run(p,A)}catch(d){return a.push(g(F(s,e.name,p,n()-o,m(d)))),c(w(e.name,s,"failed",n()-o,void 0,m(d))),l("failed",`"${e.name}" failed: ${m(d)}`)}I[e.name]=f,a.push(g({index:s,source:e.name,input:p,output:G(f),status:"completed",latencyMs:n()-o,...K(f)})),a.push(...C(f,a.length,e.name).map(g)),c(w(e.name,s,"completed",n()-o,f));const M=B(f);if(M)return q(l("completed"),M,e.name,s,c);try{$=V(t.get(e.name)??[],()=>E(e.name))}catch(d){return l("failed",`Choosing what runs after "${e.name}" threw: ${m(d)}`)}}return l("completed")}export{L as executeGraph};
@@ -1,2 +1 @@
1
- export { executeGraph } from "./execute.js";
2
- export { streamGraph } from "./stream.js";
1
+ import{executeGraph as o}from"./execute.js";import{streamGraph as t}from"./stream.js";export{o as executeGraph,t as streamGraph};
@@ -39,8 +39,4 @@ export declare function tokensOf(value: unknown): Pick<RolloutStep, "inputTokens
39
39
  * inside a router still says which branch it came from.
40
40
  */
41
41
  export declare function nestedSteps(value: unknown, from: number, source: string): RolloutStep[];
42
- /** What every step in a run adds up to. */
43
- export declare function totalTokens(steps: RolloutStep[]): {
44
- inputTokens: number;
45
- outputTokens: number;
46
- };
42
+ export { totalTokens } from "@spendgraph/sdk";
@@ -1,44 +1 @@
1
- import { stringify } from "./step.js";
2
- function isOutcome(value) {
3
- if (!value || typeof value !== "object" || Array.isArray(value))
4
- return false;
5
- const v = value;
6
- return (typeof v.output === "string" ||
7
- typeof v.inputTokens === "number" ||
8
- typeof v.outputTokens === "number" ||
9
- Array.isArray(v.steps));
10
- }
11
- export function outputOf(value) {
12
- const outcome = isOutcome(value) ? value : undefined;
13
- return outcome && typeof outcome.output === "string" ? outcome.output : stringify(value);
14
- }
15
- export function tokensOf(value) {
16
- if (!isOutcome(value))
17
- return {};
18
- const nested = Array.isArray(value.steps) && value.steps.length > 0;
19
- return {
20
- ...(!nested && typeof value.inputTokens === "number" ? { inputTokens: value.inputTokens } : {}),
21
- ...(!nested && typeof value.outputTokens === "number"
22
- ? { outputTokens: value.outputTokens }
23
- : {}),
24
- ...(value.model ? { model: value.model } : {}),
25
- };
26
- }
27
- export function nestedSteps(value, from, source) {
28
- if (!isOutcome(value) || !Array.isArray(value.steps))
29
- return [];
30
- return value.steps.map((step, at) => ({
31
- ...step,
32
- index: from + at,
33
- source: `${source}.${step.source}`,
34
- }));
35
- }
36
- export function totalTokens(steps) {
37
- let inputTokens = 0;
38
- let outputTokens = 0;
39
- for (const step of steps) {
40
- inputTokens += step.inputTokens ?? 0;
41
- outputTokens += step.outputTokens ?? 0;
42
- }
43
- return { inputTokens, outputTokens };
44
- }
1
+ import{stringify as u}from"./step.js";function r(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;const n=t;return typeof n.output=="string"||typeof n.inputTokens=="number"||typeof n.outputTokens=="number"||Array.isArray(n.steps)}function f(t){const n=r(t)?t:void 0;return n&&typeof n.output=="string"?n.output:u(t)}function s(t){if(!(typeof t!="number"||!Number.isFinite(t)||t<0))return Math.trunc(t)}function d(t){if(!r(t))return{};const n=Array.isArray(t.steps)&&t.steps.length>0,o=n?void 0:s(t.inputTokens),e=n?void 0:s(t.outputTokens);return{...o===void 0?{}:{inputTokens:o},...e===void 0?{}:{outputTokens:e},...t.model?{model:t.model}:{}}}function c(t,n,o){return!r(t)||!Array.isArray(t.steps)?[]:t.steps.filter(e=>!!e&&typeof e=="object").map((e,i)=>({...e,index:n+i,source:`${o}.${e.source??"step"}`}))}import{totalTokens as k}from"@spendgraph/sdk";export{c as nestedSteps,f as outputOf,d as tokensOf,k as totalTokens};
@@ -1,5 +1,37 @@
1
1
  import type { RolloutStep } from "@spendgraph/sdk";
2
- /** Same convention as a tool result: a string is itself, anything else is JSON. */
2
+ /**
3
+ * Same convention as a tool result: a string is itself, anything else is JSON.
4
+ *
5
+ * `JSON.stringify` throws on a circular object, on a `BigInt`, and on anything
6
+ * whose own `toJSON` throws — and recording a step happens outside the guard
7
+ * around the node, so that exception escaped `executeGraph`, which is
8
+ * documented never to throw. It took the steps that had worked with it, which
9
+ * is the loss that guard exists to prevent.
10
+ *
11
+ * A circular object is not exotic: any value with a parent backlink is one.
12
+ *
13
+ * What comes back when it cannot be written is a note saying so, never `""` —
14
+ * an empty output reads as a node that produced nothing, and this is a node
15
+ * that produced something unrecordable. The same distinction as a token count
16
+ * that is absent rather than nought.
17
+ */
3
18
  export declare function stringify(value: unknown): string;
4
19
  export declare function failedStep(index: number, source: string, input: Record<string, unknown>, latencyMs: number, error: string): RolloutStep;
5
20
  export declare function message(err: unknown): string;
21
+ /**
22
+ * A step, sealed against the nodes that will be handed it.
23
+ *
24
+ * `GraphContext.steps` is documented as "a copy; writing to it does nothing",
25
+ * and the copy is shallow — so pushing onto the array was ignored while editing
26
+ * a step *object* went straight into the run's record. A node could rewrite an
27
+ * earlier step's output, or its token counts, and the run's totals with them.
28
+ *
29
+ * Frozen once here rather than deep-copied per context: the copy is already
30
+ * O(n) on every node, and deep-copying would make that worse to buy the same
31
+ * property. In an ES module a write to a frozen object throws, so an accident
32
+ * announces itself rather than quietly rewriting history.
33
+ *
34
+ * Nothing edits a step in place — harness replaces one with `{ ...step, … }` —
35
+ * so sealing costs nothing that is being used.
36
+ */
37
+ export declare function sealed(step: RolloutStep): RolloutStep;
@@ -1,19 +1 @@
1
- export function stringify(value) {
2
- if (value === undefined || value === null)
3
- return "";
4
- return typeof value === "string" ? value : JSON.stringify(value);
5
- }
6
- export function failedStep(index, source, input, latencyMs, error) {
7
- return {
8
- index,
9
- source,
10
- input,
11
- output: "",
12
- status: "failed",
13
- error,
14
- latencyMs,
15
- };
16
- }
17
- export function message(err) {
18
- return err instanceof Error ? err.message : String(err);
19
- }
1
+ function i(t){if(t==null)return"";if(typeof t=="string")return t;try{const n=JSON.stringify(t);return n===void 0?`[not recordable: ${typeof t}]`:n}catch(n){return`[not recordable: ${n instanceof Error?n.message:String(n)}]`}}function f(t,n,r,e,o){return{index:t,source:n,input:r,output:"",status:"failed",error:o,latencyMs:e}}function s(t){return t instanceof Error?t.message:String(t)}function c(t){return Object.freeze(t)}export{f as failedStep,s as message,c as sealed,i as stringify};
@@ -1,5 +1,11 @@
1
- import type { Edge, GraphEvent, GraphResult, Node } from "../types/index.js";
2
- /** A run as it happens, and the same run once it is over. */
1
+ import type { Edge, GraphEvent, GraphResult, GraphRunOptions, Node } from "../types/index.js";
2
+ /**
3
+ * A run as it happens, and the same run once it is over.
4
+ *
5
+ * One reader. Events are handed out and dropped, so a second iterator takes
6
+ * half of them rather than seeing the same run twice — fan out downstream of
7
+ * this, not by iterating it twice.
8
+ */
3
9
  export interface GraphStream extends AsyncIterable<GraphEvent> {
4
10
  /**
5
11
  * The finished run.
@@ -16,4 +22,4 @@ export interface GraphStream extends AsyncIterable<GraphEvent> {
16
22
  * wants the result should not have to iterate to get one, and a client that
17
23
  * connects late should see what already happened.
18
24
  */
19
- export declare function streamGraph(byName: Map<string, Node<never>>, edgesFrom: Map<string, Edge[]>, entry: string, maxSteps: number, values: Record<string, unknown>, now: () => number): GraphStream;
25
+ export declare function streamGraph(byName: Map<string, Node<never>>, edgesFrom: Map<string, Edge[]>, entry: string, maxSteps: number, values: Record<string, unknown>, now: () => number, opts?: GraphRunOptions): GraphStream;
@@ -1,49 +1 @@
1
- import { executeGraph } from "./execute.js";
2
- class Events {
3
- waiting = [];
4
- wake = null;
5
- closed = false;
6
- push(event) {
7
- this.waiting.push(event);
8
- this.release();
9
- }
10
- close() {
11
- this.closed = true;
12
- this.release();
13
- }
14
- release() {
15
- const wake = this.wake;
16
- this.wake = null;
17
- wake?.();
18
- }
19
- async *drain() {
20
- while (true) {
21
- while (this.waiting.length > 0) {
22
- yield this.waiting.shift();
23
- }
24
- if (this.closed)
25
- return;
26
- await new Promise((resolve) => {
27
- this.wake = resolve;
28
- });
29
- }
30
- }
31
- }
32
- export function streamGraph(byName, edgesFrom, entry, maxSteps, values, now) {
33
- const events = new Events();
34
- const result = (async () => {
35
- try {
36
- const finished = await executeGraph(byName, edgesFrom, entry, maxSteps, values, now, (e) => events.push(e));
37
- events.push({ type: "result", result: finished });
38
- return finished;
39
- }
40
- finally {
41
- events.close();
42
- }
43
- })();
44
- void result.catch(() => { });
45
- return {
46
- result,
47
- [Symbol.asyncIterator]: () => events.drain(),
48
- };
49
- }
1
+ import{executeGraph as u}from"./execute.js";class w{waiting=[];wake=null;closed=!1;push(e){this.waiting.push(e),this.release()}close(){this.closed=!0,this.release()}release(){const e=this.wake;this.wake=null,e?.()}async*drain(){for(;;){for(;this.waiting.length>0;)yield this.waiting.shift();if(this.closed)return;await new Promise(e=>{this.wake=e})}}}function d(s,e,n,r,l,h,c={}){const t=new w,i=(async()=>{try{const a=await u(s,e,n,r,l,h,o=>t.push(o),c);return t.push({type:"result",result:a}),a}finally{t.close()}})();return i.catch(()=>{}),{result:i,[Symbol.asyncIterator]:()=>t.drain()}}export{d as streamGraph};
package/dist/index.d.ts CHANGED
@@ -2,4 +2,5 @@ export { type Graph, type GraphOptions, graph } from "./compile/index.js";
2
2
  export type { GraphStream } from "./execute/index.js";
3
3
  export type { NodeSpec } from "./node/index.js";
4
4
  export { edge, end, node } from "./node/index.js";
5
- export type { ArgSpec, ArgsOf, ArgValue, Edge, Emit, GraphContext, GraphEvent, GraphResult, GraphSpec, Node, } from "./types/index.js";
5
+ export type { ArgSpec, ArgsOf, ArgValue, Edge, Emit, GraphContext, GraphEvent, GraphResult, GraphRunOptions, GraphSpec, Node, Paused, Wait, } from "./types/index.js";
6
+ export { pausedInside } from "./types/index.js";
package/dist/index.js CHANGED
@@ -1,2 +1 @@
1
- export { graph } from "./compile/index.js";
2
- export { edge, end, node } from "./node/index.js";
1
+ import{graph as r}from"./compile/index.js";import{edge as p,end as f,node as m}from"./node/index.js";import{pausedInside as t}from"./types/index.js";export{p as edge,f as end,r as graph,m as node,t as pausedInside};
package/dist/node/edge.js CHANGED
@@ -1,6 +1 @@
1
- export function edge(from, to, when) {
2
- return when ? { from, to, when } : { from, to };
3
- }
4
- export function end(from, when) {
5
- return edge(from, null, when);
6
- }
1
+ function t(n,e,r){return r?{from:n,to:e,when:r}:{from:n,to:e}}function u(n,e){return t(n,null,e)}export{t as edge,u as end};
@@ -1,2 +1 @@
1
- export { edge, end } from "./edge.js";
2
- export { node } from "./node.js";
1
+ import{edge as r,end as d}from"./edge.js";import{node as m}from"./node.js";export{r as edge,d as end,m as node};
package/dist/node/node.js CHANGED
@@ -1,25 +1 @@
1
- const VALID_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
2
- export function node(spec) {
3
- if (!VALID_NAME.test(spec.name)) {
4
- throw new Error(`Node name "${spec.name}" must be letters, digits and underscores, starting with a letter.`);
5
- }
6
- const seen = new Set();
7
- for (const arg of spec.args ?? []) {
8
- if (!VALID_NAME.test(arg.name)) {
9
- throw new Error(`Node "${spec.name}" argument "${arg.name}" is not a usable name.`);
10
- }
11
- if (seen.has(arg.name)) {
12
- throw new Error(`Node "${spec.name}" declares "${arg.name}" twice.`);
13
- }
14
- seen.add(arg.name);
15
- if (arg.type === "enum" && !arg.options?.length) {
16
- throw new Error(`Node "${spec.name}" argument "${arg.name}" is an enum with no options, so nothing can satisfy it.`);
17
- }
18
- }
19
- return {
20
- name: spec.name,
21
- args: spec.args?.map((a) => ({ ...a, options: a.options ? [...a.options] : undefined })),
22
- input: spec.input,
23
- run: spec.run,
24
- };
25
- }
1
+ const o=/^[A-Za-z_][A-Za-z0-9_]*$/;function r(e){if(!o.test(e.name))throw new Error(`Node name "${e.name}" must be letters, digits and underscores, starting with a letter.`);const t=new Set;for(const n of e.args??[]){if(!o.test(n.name))throw new Error(`Node "${e.name}" argument "${n.name}" is not a usable name.`);if(t.has(n.name))throw new Error(`Node "${e.name}" declares "${n.name}" twice.`);if(t.add(n.name),n.type==="enum"&&!n.options?.length)throw new Error(`Node "${e.name}" argument "${n.name}" is an enum with no options, so nothing can satisfy it.`)}return{name:e.name,args:e.args?.map(n=>({...n,options:n.options?[...n.options]:void 0})),input:e.input,run:e.run}}export{r as node};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1,4 +1,5 @@
1
1
  import type { GraphResult } from "./result.js";
2
+ import type { Wait } from "./wait.js";
2
3
  /**
3
4
  * What a run says about itself while it is still running.
4
5
  *
@@ -24,6 +25,17 @@ export type GraphEvent = {
24
25
  output?: unknown;
25
26
  error?: string;
26
27
  latencyMs: number;
28
+ } | {
29
+ /**
30
+ * A node returned a run that stopped to ask. The walk stops here, so
31
+ * nothing downstream runs against an answer nobody has given yet.
32
+ */
33
+ type: "paused";
34
+ node: string;
35
+ index: number;
36
+ waitingOn: Wait;
37
+ /** The nested run to resume, where it named one. */
38
+ runId?: string;
27
39
  } | {
28
40
  type: "result";
29
41
  result: GraphResult;
@@ -1 +0,0 @@
1
- export {};
@@ -3,5 +3,6 @@ export type { GraphContext } from "./context.js";
3
3
  export type { Edge } from "./edge.js";
4
4
  export type { Emit, GraphEvent } from "./event.js";
5
5
  export type { Node } from "./node.js";
6
- export type { GraphResult } from "./result.js";
6
+ export type { GraphResult, GraphRunOptions } from "./result.js";
7
7
  export type { GraphSpec } from "./spec.js";
8
+ export { type Paused, pausedInside, type Wait } from "./wait.js";
@@ -1 +1 @@
1
- export {};
1
+ import{pausedInside as o}from"./wait.js";export{o as pausedInside};
@@ -1 +0,0 @@
1
- export {};
@@ -1,4 +1,5 @@
1
1
  import type { RolloutStep } from "@spendgraph/sdk";
2
+ import type { Wait } from "./wait.js";
2
3
  /**
3
4
  * What one run produced, in the shape of a rollout.
4
5
  *
@@ -17,4 +18,52 @@ export interface GraphResult {
17
18
  /** Summed across every step, nested ones included. */
18
19
  inputTokens: number;
19
20
  outputTokens: number;
21
+ /**
22
+ * The question a node stopped to ask, where one did.
23
+ *
24
+ * Carried rather than said with a status: `status` reports whether the graph
25
+ * itself ran, and a paused run ran correctly as far as it got. Every workflow
26
+ * in this repo signals a pause the same way, by carrying the question.
27
+ */
28
+ waitingOn?: Wait;
29
+ /** The nested run to resume, where it named one. */
30
+ waitingFor?: string;
31
+ }
32
+ /** What a run may be given beyond its values. */
33
+ export interface GraphRunOptions {
34
+ /**
35
+ * What nodes that already ran returned, for a graph picking up where an
36
+ * earlier run left off.
37
+ *
38
+ * Seeded into `outputs` before the entry node, so a node resuming mid-flow
39
+ * reads what came before it rather than an empty bag. The seeded nodes are
40
+ * not re-run and record no steps of their own — they already did.
41
+ */
42
+ outputs?: Record<string, unknown>;
43
+ /**
44
+ * Steps an earlier run already took, for the same graph picking up again.
45
+ *
46
+ * Seeded into `steps` before the entry node, so `ctx.steps` reads the whole
47
+ * run rather than only what has happened since the resume: an edge counting
48
+ * steps counts them all, `index` carries on instead of restarting at 0, and
49
+ * the result comes back as one rollout a caller need not renumber.
50
+ *
51
+ * `maxSteps` still counts this run alone — seeded steps are history, not
52
+ * budget.
53
+ */
54
+ steps?: RolloutStep[];
55
+ /**
56
+ * Where the walk starts, instead of the compiled entry.
57
+ *
58
+ * For resuming: a run that stopped to ask says which node it stopped at, and
59
+ * without this that node name is a resume point nobody can use — the walk
60
+ * would begin at the entry again and re-run everything before it.
61
+ *
62
+ * Reachability is checked from the compiled entry at build time. A node this
63
+ * names only has to exist: whatever it made unreachable has already run.
64
+ *
65
+ * `maxSteps` counts this run alone, so a resumed one starts its budget over.
66
+ * A caller resuming a cyclic graph repeatedly is the one holding the ceiling.
67
+ */
68
+ entry?: string;
20
69
  }
@@ -1 +0,0 @@
1
- export {};
@@ -1,7 +1,7 @@
1
1
  import type { Edge } from "./edge.js";
2
2
  import type { Node } from "./node.js";
3
3
  export interface GraphSpec {
4
- /** Where a run starts. */
4
+ /** Where a run starts, unless `GraphRunOptions.entry` names somewhere else. */
5
5
  entry: string;
6
6
  nodes: Node<never>[];
7
7
  edges?: Edge[];
@@ -1 +0,0 @@
1
- export {};
@@ -0,0 +1,32 @@
1
+ /**
2
+ * A run that stopped to ask something, and what it asked.
3
+ *
4
+ * Structural rather than imported: `@spendgraph/harness` owns durability and
5
+ * depends on this package, so the shape is declared here and its `Wait`
6
+ * satisfies it. The same arrangement as `llms`' `LlmReply` and the
7
+ * `TraceOutcome` that `prompt` accepts.
8
+ */
9
+ export interface Wait {
10
+ question: string;
11
+ /** Whatever answering it needs — options to pick from, a diff, an id. */
12
+ detail?: unknown;
13
+ }
14
+ /** A paused run found inside a node's return. */
15
+ export interface Paused {
16
+ waitingOn: Wait;
17
+ /** The id the inner run is stored under — the one a caller has to resume. */
18
+ runId?: string;
19
+ }
20
+ /**
21
+ * A node's return that is really a question, recognised by its shape.
22
+ *
23
+ * Structural because a node may return anything: asking callers to wrap a
24
+ * paused nested run in a marker would be a rule they learn by having the graph
25
+ * walk on past the question and report the run as done.
26
+ *
27
+ * Every node's return is put through this, so a node returning a `waitingOn`
28
+ * that is data rather than a question stops the run. Nothing else in a reply
29
+ * has that shape, and the alternative — trusting a marker — fails the other
30
+ * way, silently.
31
+ */
32
+ export declare function pausedInside(value: unknown): Paused | null;
@@ -0,0 +1 @@
1
+ function e(t){if(!t||typeof t!="object")return null;const r=t,n=r.waitingOn;return!n||typeof n!="object"||typeof n.question!="string"?null:{waitingOn:n,...typeof r.runId=="string"?{runId:r.runId}:{}}}export{e as pausedInside};
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@spendgraph/graph",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Wire nodes into a graph, run it, and get back a rollout with every step.",
5
- "license": "MIT",
5
+ "license": "Apache-2.0",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git+https://github.com/fnLog0/spendgraph.git",
@@ -34,11 +34,12 @@
34
34
  "README.md"
35
35
  ],
36
36
  "scripts": {
37
- "build": "tsc -p tsconfig.json --emitDeclarationOnly && tsc -p tsconfig.json --declaration false --removeComments",
38
- "test": "vitest run"
37
+ "build": "rm -rf dist && tsc -p tsconfig.json --emitDeclarationOnly && tsc -p tsconfig.json --declaration false --removeComments && node ../../scripts/minify.mjs dist",
38
+ "test": "npm run build && vitest run",
39
+ "typecheck": "tsc -p tsconfig.tests.json"
39
40
  },
40
41
  "dependencies": {
41
- "@spendgraph/sdk": "^0.4.0"
42
+ "@spendgraph/sdk": "^0.6.0"
42
43
  },
43
44
  "devDependencies": {
44
45
  "typescript": "^5"