@spendgraph/graph 0.5.0 → 0.7.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 (82) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +25 -134
  3. package/dist/compile/ceiling.d.ts +3 -0
  4. package/dist/compile/ceiling.js +1 -0
  5. package/dist/compile/compile.d.ts +6 -15
  6. package/dist/compile/compile.js +1 -17
  7. package/dist/compile/covered.d.ts +3 -0
  8. package/dist/compile/covered.js +1 -0
  9. package/dist/compile/edges.d.ts +5 -0
  10. package/dist/compile/edges.js +1 -0
  11. package/dist/compile/errors.d.ts +14 -0
  12. package/dist/compile/errors.js +1 -0
  13. package/dist/compile/index.d.ts +2 -0
  14. package/dist/compile/index.js +1 -1
  15. package/dist/compile/nodes.d.ts +4 -0
  16. package/dist/compile/nodes.js +1 -0
  17. package/dist/compile/reachable.d.ts +9 -0
  18. package/dist/compile/reachable.js +1 -0
  19. package/dist/execute/context.d.ts +4 -0
  20. package/dist/execute/context.js +1 -0
  21. package/dist/execute/errors.d.ts +6 -0
  22. package/dist/execute/errors.js +1 -0
  23. package/dist/execute/index.d.ts +3 -3
  24. package/dist/execute/index.js +1 -2
  25. package/dist/execute/outcome.d.ts +5 -30
  26. package/dist/execute/outcome.js +1 -44
  27. package/dist/execute/resume.d.ts +16 -0
  28. package/dist/execute/resume.js +1 -0
  29. package/dist/execute/run.d.ts +33 -0
  30. package/dist/execute/run.js +1 -0
  31. package/dist/execute/steps.d.ts +7 -0
  32. package/dist/execute/steps.js +1 -0
  33. package/dist/execute/visit.d.ts +10 -0
  34. package/dist/execute/visit.js +1 -0
  35. package/dist/execute/walk.d.ts +4 -0
  36. package/dist/execute/walk.js +1 -0
  37. package/dist/index.d.ts +5 -3
  38. package/dist/index.js +1 -2
  39. package/dist/node/edge.d.ts +1 -6
  40. package/dist/node/edge.js +1 -6
  41. package/dist/node/index.js +1 -2
  42. package/dist/node/node.d.ts +1 -7
  43. package/dist/node/node.js +1 -25
  44. package/dist/stream/events.d.ts +22 -0
  45. package/dist/stream/events.js +1 -0
  46. package/dist/stream/index.d.ts +2 -0
  47. package/dist/stream/index.js +1 -0
  48. package/dist/stream/stream.d.ts +9 -0
  49. package/dist/stream/stream.js +1 -0
  50. package/dist/types/args.d.ts +2 -15
  51. package/dist/types/args.js +0 -1
  52. package/dist/types/context.d.ts +39 -14
  53. package/dist/types/context.js +0 -1
  54. package/dist/types/edge.d.ts +1 -4
  55. package/dist/types/edge.js +0 -1
  56. package/dist/types/event.d.ts +17 -7
  57. package/dist/types/event.js +0 -1
  58. package/dist/types/index.d.ts +3 -2
  59. package/dist/types/index.js +1 -1
  60. package/dist/types/node.d.ts +2 -10
  61. package/dist/types/node.js +0 -1
  62. package/dist/types/result.d.ts +15 -6
  63. package/dist/types/result.js +0 -1
  64. package/dist/types/spec.d.ts +14 -5
  65. package/dist/types/spec.js +0 -1
  66. package/dist/types/wait.d.ts +24 -0
  67. package/dist/types/wait.js +1 -0
  68. package/docs/nodes.mdx +59 -0
  69. package/docs/overview.mdx +96 -0
  70. package/docs/pausing.mdx +109 -0
  71. package/docs/running.mdx +71 -0
  72. package/docs/streaming.mdx +62 -0
  73. package/docs/wiring.mdx +76 -0
  74. package/package.json +11 -8
  75. package/dist/compile/validate.d.ts +0 -17
  76. package/dist/compile/validate.js +0 -51
  77. package/dist/execute/execute.d.ts +0 -16
  78. package/dist/execute/execute.js +0 -92
  79. package/dist/execute/step.d.ts +0 -5
  80. package/dist/execute/step.js +0 -19
  81. package/dist/execute/stream.d.ts +0 -19
  82. package/dist/execute/stream.js +0 -49
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,44 @@
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.
29
+ - **A failed node can route somewhere** — `onFailure` names the node that runs
30
+ instead of the run ending, for a workflow whose earlier steps have to be undone.
129
31
 
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.
32
+ ## Docs
133
33
 
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
- ```
34
+ | | |
35
+ | --- | --- |
36
+ | [Overview](https://spendgraph.locusgraph.com/docs/graph/overview) | Four exports, and the whole thing in one example |
37
+ | [Nodes](https://spendgraph.locusgraph.com/docs/graph/nodes) | One unit of work, typed from its args |
38
+ | [Wiring](https://spendgraph.locusgraph.com/docs/graph/wiring) | Edges, branching, and what compilation refuses |
39
+ | [Running a graph](https://spendgraph.locusgraph.com/docs/graph/running) | Failure, the step ceiling, what comes back |
40
+ | [Streaming](https://spendgraph.locusgraph.com/docs/graph/streaming) | The same run, narrated |
41
+ | [Pausing](https://spendgraph.locusgraph.com/docs/graph/pausing) | Stopping to ask a person, and picking it back up |
151
42
 
152
43
  ## License
153
44
 
154
- MIT
45
+ Apache-2.0
@@ -0,0 +1,3 @@
1
+ export declare const DEFAULT_MAX_STEPS = 25;
2
+ /** How many nodes a run may visit, refusing NaN and Infinity since a run would never stop at either. */
3
+ export declare function ceilingFor(maxSteps: number | undefined): number;
@@ -0,0 +1 @@
1
+ import{notACeiling as n}from"./errors.js";const r=25;function t(i){if(i===void 0)return r;if(!Number.isFinite(i))throw n(i,r);return Math.max(1,Math.floor(i))}export{r as DEFAULT_MAX_STEPS,t as ceilingFor};
@@ -1,5 +1,5 @@
1
- import { type GraphStream } from "../execute/index.js";
2
- import type { Edge, GraphResult, GraphSpec, Node } from "../types/index.js";
1
+ import { type GraphStream } from "../stream/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;
@@ -12,18 +12,9 @@ export declare function graph(spec: GraphSpec, opts?: GraphOptions): {
12
12
  nodes: () => Node<never>[];
13
13
  /** Edges leaving a node, in the order they will be tried. */
14
14
  edgesFrom: (name: string) => Edge[];
15
- /**
16
- * Runs it once. Never throws the result carries every step taken, so a
17
- * run that stopped at node three still says which three and why.
18
- */
19
- execute: (values?: Record<string, unknown>) => Promise<GraphResult>;
20
- /**
21
- * The same run, narrated. Yields a node's start and end, whatever its nodes
22
- * emit while running, and the finished result last.
23
- *
24
- * The run begins on the call, not on the first read, so `result` is there
25
- * for the caller who wants the rollout and not the commentary.
26
- */
27
- stream: (values?: Record<string, unknown>) => GraphStream;
15
+ /** Runs it once. Never throws — the result carries every step taken. */
16
+ execute: (values?: Record<string, unknown>, runOpts?: GraphRunOptions) => Promise<GraphResult>;
17
+ /** The same run, narrated as it goes; `result` is there whether or not anyone reads. */
18
+ stream: (values?: Record<string, unknown>, runOpts?: GraphRunOptions) => GraphStream;
28
19
  };
29
20
  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 i}from"../execute/index.js";import{streamGraph as l}from"../stream/index.js";import{ceilingFor as s}from"./ceiling.js";import{assertEveryBranchIsCovered as u}from"./covered.js";import{indexEdges as d}from"./edges.js";import{unknownFailureNode as F}from"./errors.js";import{indexNodes as f}from"./nodes.js";import{assertAllReachable as x}from"./reachable.js";function E(r,m={}){const e=f(r),t=d(r.edges??[],e);if(r.onFailure&&!e.has(r.onFailure))throw F(r.onFailure,[...e.keys()]);x(r.entry,e,t,r.onFailure),u(t);const n={entry:r.entry,maxSteps:s(r.maxSteps),nodes:e,edgesFrom:t,...r.onFailure?{onFailure:r.onFailure}:{},now:m.now??(()=>Date.now())};return{entry:n.entry,maxSteps:n.maxSteps,nodes:()=>[...e.values()],edgesFrom:o=>[...t.get(o)??[]],execute:(o={},a={})=>i(n,o,a),stream:(o={},a={})=>l(n,o,a)}}export{E as graph};
@@ -0,0 +1,3 @@
1
+ import type { EdgesFrom } from "./edges.js";
2
+ /** Refuses a node whose edges are all conditional: a run where none match would stop and report success. */
3
+ export declare function assertEveryBranchIsCovered(edgesFrom: EdgesFrom): void;
@@ -0,0 +1 @@
1
+ import{onlyConditionalEdges as o}from"./errors.js";function f(r){const n=[...r.entries()].filter(([,e])=>e.length>0&&e.every(t=>t.when)).map(([e])=>e);if(n.length>0)throw o(n)}export{f as assertEveryBranchIsCovered};
@@ -0,0 +1,5 @@
1
+ import type { Edge } from "../types/index.js";
2
+ import { type NodesByName } from "./nodes.js";
3
+ export type EdgesFrom = Map<string, Edge[]>;
4
+ /** Edges grouped by the node they leave, in the order they will be tried. */
5
+ export declare function indexEdges(edges: Edge[], nodes: NodesByName): EdgesFrom;
@@ -0,0 +1 @@
1
+ import{edgeAfterDefault as i,edgeFromUnknown as a,edgeToUnknown as g}from"./errors.js";import{namesOf as m}from"./nodes.js";function h(s,e){const t=new Map,f=new Map;for(const o of s){if(!e.has(o.from))throw a(o.from,m(e));if(o.to!==null&&!e.has(o.to))throw g(o.from,o.to,m(e));const r=f.get(o.from);if(r)throw i(o.from,r.to,o.to);o.when||f.set(o.from,o);const n=t.get(o.from);n?n.push(o):t.set(o.from,[o])}return t}export{h as indexEdges};
@@ -0,0 +1,14 @@
1
+ /** A graph refused at compile time: something about its shape cannot run as written. */
2
+ export declare class GraphSpecError extends Error {
3
+ constructor(message: string);
4
+ }
5
+ export declare const noNodes: () => GraphSpecError;
6
+ export declare const duplicateNode: (name: string) => GraphSpecError;
7
+ export declare const unknownEntry: (entry: string, known: string[]) => GraphSpecError;
8
+ export declare const edgeFromUnknown: (from: string, known: string[]) => GraphSpecError;
9
+ export declare const edgeToUnknown: (from: string, to: string, known: string[]) => GraphSpecError;
10
+ export declare const edgeAfterDefault: (from: string, defaultTo: string | null, to: string | null) => GraphSpecError;
11
+ export declare const notACeiling: (maxSteps: number, fallback: number) => GraphSpecError;
12
+ export declare const onlyConditionalEdges: (names: string[]) => GraphSpecError;
13
+ export declare const unreachable: (orphans: string[], entry: string) => GraphSpecError;
14
+ export declare const unknownFailureNode: (name: string, known: string[]) => GraphSpecError;
@@ -0,0 +1 @@
1
+ class o extends Error{constructor(n){super(n),this.name="GraphSpecError"}}const r=e=>e.map(n=>`"${n}"`).join(", "),a=()=>new o("A graph needs at least one node."),s=e=>new o(`Two nodes are called "${e}".`),i=(e,n)=>new o(`The entry node "${e}" is not in this graph. Known: ${n.join(", ")}.`),d=(e,n)=>new o(`An edge starts at "${e}", which is not a node in this graph. Known: ${n.join(", ")}.`),h=(e,n,t)=>new o(`An edge from "${e}" points at "${n}", which is not a node in this graph. Known: ${t.join(", ")}.`),c=(e,n,t)=>new o(`The edge from "${e}" to "${n??"the end"}" has no condition, so the edge to "${t??"the end"}" declared after it can never be taken. Put the unconditional edge last.`),p=(e,n)=>new o(`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 ${n}.`),w=e=>new o(`${r(e)} ${e.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("${e[0]}") to stop there on purpose.`),l=(e,n)=>new o(`Nothing reaches ${r(e)} from "${n}". Add an edge, or take the node out.`),u=(e,n)=>new o(`onFailure names "${e}", which is not a node in this graph. Known: ${n.join(", ")}.`);export{o as GraphSpecError,s as duplicateNode,c as edgeAfterDefault,d as edgeFromUnknown,h as edgeToUnknown,a as noNodes,p as notACeiling,w as onlyConditionalEdges,i as unknownEntry,u as unknownFailureNode,l as unreachable};
@@ -1 +1,3 @@
1
+ export { ceilingFor, DEFAULT_MAX_STEPS } from "./ceiling.js";
1
2
  export { type Graph, type GraphOptions, graph } from "./compile.js";
3
+ export { GraphSpecError } from "./errors.js";
@@ -1 +1 @@
1
- export { graph } from "./compile.js";
1
+ import{ceilingFor as p,DEFAULT_MAX_STEPS as e}from"./ceiling.js";import{graph as m}from"./compile.js";import{GraphSpecError as x}from"./errors.js";export{e as DEFAULT_MAX_STEPS,x as GraphSpecError,p as ceilingFor,m as graph};
@@ -0,0 +1,4 @@
1
+ import type { GraphSpec, Node } from "../types/index.js";
2
+ export type NodesByName = Map<string, Node<never>>;
3
+ export declare const namesOf: (nodes: NodesByName) => string[];
4
+ export declare function indexNodes(spec: GraphSpec): NodesByName;
@@ -0,0 +1 @@
1
+ import{duplicateNode as t,noNodes as r,unknownEntry as s}from"./errors.js";const d=n=>[...n.keys()];function f(n){if(n.nodes.length===0)throw r();const o=new Map;for(const e of n.nodes){if(o.has(e.name))throw t(e.name);o.set(e.name,e)}if(!o.has(n.entry))throw s(n.entry,d(o));return o}export{f as indexNodes,d as namesOf};
@@ -0,0 +1,9 @@
1
+ import type { EdgesFrom } from "./edges.js";
2
+ import { type NodesByName } from "./nodes.js";
3
+ /**
4
+ * Refuses a node nothing reaches from the entry, since the usual cause is a typo in an edge.
5
+ *
6
+ * A failure node is a second root: nothing points an edge at it, and the walk
7
+ * still reaches it from anywhere that falls over.
8
+ */
9
+ export declare function assertAllReachable(entry: string, nodes: NodesByName, edgesFrom: EdgesFrom, onFailure?: string): void;
@@ -0,0 +1 @@
1
+ import{unreachable as l}from"./errors.js";import{namesOf as i}from"./nodes.js";function d(e,h,c,a){const f=a?[e,a]:[e],r=new Set(f),s=[...f];for(let o=0;o<s.length;o++)for(const t of c.get(s[o])??[])t.to&&!r.has(t.to)&&(r.add(t.to),s.push(t.to));const n=i(h).filter(o=>!r.has(o));if(n.length)throw l(n,e)}export{d as assertAllReachable};
@@ -0,0 +1,4 @@
1
+ import type { GraphContext } from "../types/index.js";
2
+ import type { Run } from "./run.js";
3
+ /** What a node sees: the run so far, with a copy of the steps and an emit tagged with its name. */
4
+ export declare function contextFor(run: Run, node: string): GraphContext;
@@ -0,0 +1 @@
1
+ function a(t,o){return{values:t.values,outputs:t.outputs,from:t.cameFrom,failure:t.failure,steps:[...t.steps],emit:e=>t.narrate({type:"token",node:o,text:e}),note:e=>t.narrate({type:"note",node:o,data:e})}}export{a as contextFor};
@@ -0,0 +1,6 @@
1
+ export declare const nowhereToStart: (start: string, known: string[]) => string;
2
+ export declare const hitTheCeiling: (maxSteps: number, at: string) => string;
3
+ export declare const inputThrew: (node: string, why: string) => string;
4
+ export declare const givenBadArgs: (node: string, why: string) => string;
5
+ export declare const nodeFailed: (node: string, why: string) => string;
6
+ export declare const choosingThrew: (node: string, why: string) => string;
@@ -0,0 +1 @@
1
+ const n=(e,t)=>`No node is called "${e}", so there is nowhere to start. \`entry\` names where a resumed run picks up. Known: ${t.join(", ")}.`,o=(e,t)=>`Ran ${e} nodes without reaching an end, stopping at "${t}". Raising the ceiling is the last thing to try: a cycle that never exits is what it is here to stop. Otherwise a conditional edge never turns false, or the graph is genuinely longer than ${e} nodes.`,i=(e,t)=>`Building the input for "${e}" threw: ${t}`,r=(e,t)=>`"${e}" was given ${t}`,s=(e,t)=>`"${e}" failed: ${t}`,h=(e,t)=>`Choosing what runs after "${e}" threw: ${t}`;export{h as choosingThrew,r as givenBadArgs,o as hitTheCeiling,i as inputThrew,s as nodeFailed,n as nowhereToStart};
@@ -1,4 +1,4 @@
1
- export { executeGraph } from "./execute.js";
2
1
  export type { NodeOutcome } from "./outcome.js";
3
- export type { GraphStream } from "./stream.js";
4
- export { streamGraph } from "./stream.js";
2
+ export { resumingAt } from "./resume.js";
3
+ export type { Compiled, Narrator } from "./run.js";
4
+ export { executeGraph } from "./walk.js";
@@ -1,2 +1 @@
1
- export { executeGraph } from "./execute.js";
2
- export { streamGraph } from "./stream.js";
1
+ import{resumingAt as o}from"./resume.js";import{executeGraph as m}from"./walk.js";export{m as executeGraph,o as resumingAt};
@@ -1,13 +1,4 @@
1
1
  import type { RolloutStep } from "@spendgraph/sdk";
2
- /**
3
- * What a node returned, when it returned the shape a model call produces.
4
- *
5
- * Recognised structurally rather than declared: a node may return anything, and
6
- * a plain object is the common case. But a node that called a model, ran a
7
- * prompt or nested another workflow returns tokens and sometimes its own steps,
8
- * and both used to be flattened into the output string and lost — which made a
9
- * graph run report as costing nothing.
10
- */
11
2
  export interface NodeOutcome {
12
3
  output?: string;
13
4
  model?: string;
@@ -17,30 +8,14 @@ export interface NodeOutcome {
17
8
  outputTokens?: number;
18
9
  cacheReadTokens?: number;
19
10
  cacheWriteTokens?: number;
20
- /** A nested run's own steps, spliced in rather than stringified away. */
11
+ citationTokens?: number;
12
+ reasoningTokens?: number;
21
13
  steps?: RolloutStep[];
22
14
  }
23
- /** The text a step should carry: an outcome's own output, or the whole value. */
24
15
  export declare function outputOf(value: unknown): string;
25
- /**
26
- * The token counts a node reported, or nothing when it reported none.
27
- *
28
- * A node that also returns nested steps reports none here: its own totals are
29
- * the sum of those steps, and counting both makes a graph inside a graph cost
30
- * exactly twice what it did.
31
- */
32
- export declare function tokensOf(value: unknown): Pick<RolloutStep, "inputTokens" | "outputTokens"> & {
16
+ export declare function tokensOf(value: unknown): Pick<RolloutStep, "inputTokens" | "outputTokens" | "cacheReadTokens" | "cacheWriteTokens" | "citationTokens" | "reasoningTokens"> & {
33
17
  model?: string;
34
18
  };
35
- /**
36
- * A nested run's steps, renumbered to sit in this run's sequence.
37
- *
38
- * Prefixed with the node that produced them, so a step from a refine loop
39
- * inside a router still says which branch it came from.
40
- */
19
+ /** A nested run's steps, renumbered into this run and named for the node they came from. */
41
20
  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
- };
21
+ export { totalTokens } from "@spendgraph/sdk";