@spendgraph/graph 0.2.0 → 0.3.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/README.md CHANGED
@@ -35,16 +35,19 @@ const classify = node({
35
35
  compiling, rather than being handed `undefined` halfway through a graph, which
36
36
  is the most expensive place to find a typo.
37
37
 
38
- Args are validated before `run` does any work.
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.
39
41
 
40
42
  ## Wiring
41
43
 
42
44
  ```ts
43
45
  const flow = graph({
44
- start: "classify",
46
+ entry: "classify",
45
47
  nodes: [classify, lookup, answer],
46
48
  edges: [
47
- edge("classify", (ctx) => (ctx.outputs.classify === "billing" ? "lookup" : "answer")),
49
+ edge("classify", "lookup", (ctx) => ctx.outputs.classify === "billing"),
50
+ edge("classify", "answer"),
48
51
  edge("lookup", "answer"),
49
52
  end("answer"),
50
53
  ],
@@ -53,18 +56,66 @@ const flow = graph({
53
56
  const result = await flow.execute({ question: "Why was I charged twice?" });
54
57
  ```
55
58
 
56
- An edge says what runs next; a node's `input` says on what. Compilation checks
57
- the wiring — an edge to a node that does not exist, a node nothing reaches, a
58
- cycle before anything runs.
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.
59
108
 
60
109
  ## What comes back
61
110
 
62
111
  ```ts
63
112
  result.status; // "completed" | "failed"
64
- result.output; // the last node's return, stringified
113
+ result.output; // the last node's return, stringified; "" on a failure
65
114
  result.steps; // every node that ran, in order
66
115
  result.outputs; // each node's return, by name
67
116
  result.latencyMs;
117
+ result.inputTokens; // summed across every step, nested ones included
118
+ result.outputTokens;
68
119
  ```
69
120
 
70
121
  A graph run is a rollout with several steps, so `GraphResult` hands straight to
@@ -85,3 +136,19 @@ ctx.values; // what execute() was called with
85
136
  ctx.outputs; // what each finished node returned, by name
86
137
  ctx.steps; // the steps so far; a copy, so writing to it does nothing
87
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
+ ```
151
+
152
+ ## License
153
+
154
+ MIT
@@ -1,6 +1,5 @@
1
1
  import { executeGraph, streamGraph } from "../execute/index.js";
2
2
  import { assertAllReachable, indexEdges, indexNodes } from "./validate.js";
3
- /** Compiles a graph, refusing one that cannot run as written. */
4
3
  export function graph(spec, opts = {}) {
5
4
  const now = opts.now ?? (() => Date.now());
6
5
  const maxSteps = Math.max(1, spec.maxSteps ?? 25);
@@ -10,22 +9,9 @@ export function graph(spec, opts = {}) {
10
9
  return {
11
10
  entry: spec.entry,
12
11
  maxSteps,
13
- /** Every node, in declaration order. */
14
12
  nodes: () => [...byName.values()],
15
- /** Edges leaving a node, in the order they will be tried. */
16
13
  edgesFrom: (name) => [...(edgesFrom.get(name) ?? [])],
17
- /**
18
- * Runs it once. Never throws — the result carries every step taken, so a
19
- * run that stopped at node three still says which three and why.
20
- */
21
14
  execute: (values = {}) => executeGraph(byName, edgesFrom, spec.entry, maxSteps, values, now),
22
- /**
23
- * The same run, narrated. Yields a node's start and end, whatever its nodes
24
- * emit while running, and the finished result last.
25
- *
26
- * The run begins on the call, not on the first read, so `result` is there
27
- * for the caller who wants the rollout and not the commentary.
28
- */
29
15
  stream: (values = {}) => streamGraph(byName, edgesFrom, spec.entry, maxSteps, values, now),
30
16
  };
31
17
  }
@@ -1,10 +1,3 @@
1
- /**
2
- * Everything about a graph that is wrong without running it.
3
- *
4
- * The argument for a graph over a hand-written loop: the shape is data, so it
5
- * can be wrong at build time rather than on the branch nobody exercised. What
6
- * no static check catches is a loop that never exits — that is `maxSteps`.
7
- */
8
1
  export function indexNodes(spec) {
9
2
  if (spec.nodes.length === 0)
10
3
  throw new Error("A graph needs at least one node.");
@@ -29,8 +22,6 @@ export function indexEdges(edges, byName) {
29
22
  throw new Error(`An edge from "${e.from}" points at "${e.to}", which is not a node in this graph.`);
30
23
  }
31
24
  const list = edgesFrom.get(e.from) ?? [];
32
- // First match wins, so anything after an unconditional edge is dead. The
33
- // graph would look like it handles a case it does not.
34
25
  const open = list.find((prior) => !prior.when);
35
26
  if (open) {
36
27
  throw new Error(`The edge from "${e.from}" to "${open.to ?? "the end"}" has no condition, so the edge ` +
@@ -41,12 +32,6 @@ export function indexEdges(edges, byName) {
41
32
  }
42
33
  return edgesFrom;
43
34
  }
44
- /**
45
- * Refuses a node nothing reaches.
46
- *
47
- * Refused rather than warned about: the usual cause is a typo in an edge, and
48
- * the usual symptom is a branch that quietly never runs.
49
- */
50
35
  export function assertAllReachable(entry, byName, edgesFrom) {
51
36
  const reached = new Set([entry]);
52
37
  const queue = [entry];
@@ -4,20 +4,6 @@ import { failedStep, message } from "./step.js";
4
4
  function ended(node, index, status, latencyMs, output, error) {
5
5
  return { type: "node_end", node, index, status, output, error, latencyMs };
6
6
  }
7
- /**
8
- * Runs a compiled graph.
9
- *
10
- * Never throws, for the reason `invoke` never throws: an exception discards the
11
- * two steps that worked along with the evidence of where it stopped. Every exit
12
- * here is a `GraphResult` carrying the steps taken.
13
- *
14
- * A failed node halts the run. Continuing would leave every later node reading
15
- * `outputs` for something that is not there.
16
- *
17
- * `sink` is how a run narrates itself. It is called as the run proceeds and its
18
- * absence changes nothing, so the streamed and unstreamed paths stay one piece
19
- * of code rather than two that drift.
20
- */
21
7
  export async function executeGraph(byName, edgesFrom, entry, maxSteps, values, now, sink = () => { }) {
22
8
  const startedAt = now();
23
9
  const steps = [];
@@ -87,8 +73,6 @@ export async function executeGraph(byName, edgesFrom, entry, maxSteps, values, n
87
73
  });
88
74
  steps.push(...nestedSteps(value, steps.length, node.name));
89
75
  sink(ended(node.name, index, "completed", now() - startedNode, value));
90
- // First match wins, so an unconditional edge is the default branch. No match
91
- // is an end, which is what a node with no outgoing edges already means.
92
76
  let next = null;
93
77
  try {
94
78
  const after = context(node.name);
@@ -8,18 +8,10 @@ function isOutcome(value) {
8
8
  typeof v.outputTokens === "number" ||
9
9
  Array.isArray(v.steps));
10
10
  }
11
- /** The text a step should carry: an outcome's own output, or the whole value. */
12
11
  export function outputOf(value) {
13
12
  const outcome = isOutcome(value) ? value : undefined;
14
13
  return outcome && typeof outcome.output === "string" ? outcome.output : stringify(value);
15
14
  }
16
- /**
17
- * The token counts a node reported, or nothing when it reported none.
18
- *
19
- * A node that also returns nested steps reports none here: its own totals are
20
- * the sum of those steps, and counting both makes a graph inside a graph cost
21
- * exactly twice what it did.
22
- */
23
15
  export function tokensOf(value) {
24
16
  if (!isOutcome(value))
25
17
  return {};
@@ -32,12 +24,6 @@ export function tokensOf(value) {
32
24
  ...(value.model ? { model: value.model } : {}),
33
25
  };
34
26
  }
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
- */
41
27
  export function nestedSteps(value, from, source) {
42
28
  if (!isOutcome(value) || !Array.isArray(value.steps))
43
29
  return [];
@@ -47,7 +33,6 @@ export function nestedSteps(value, from, source) {
47
33
  source: `${source}.${step.source}`,
48
34
  }));
49
35
  }
50
- /** What every step in a run adds up to. */
51
36
  export function totalTokens(steps) {
52
37
  let inputTokens = 0;
53
38
  let outputTokens = 0;
@@ -1,4 +1,3 @@
1
- /** Same convention as a tool result: a string is itself, anything else is JSON. */
2
1
  export function stringify(value) {
3
2
  if (value === undefined || value === null)
4
3
  return "";
@@ -1,11 +1,4 @@
1
1
  import { executeGraph } from "./execute.js";
2
- /**
3
- * Events held between the run and whoever is reading them.
4
- *
5
- * A queue rather than a callback because the two sides move at different
6
- * speeds: a graph does not wait for a slow reader, and a reader must not miss
7
- * what arrived before it asked.
8
- */
9
2
  class Events {
10
3
  waiting = [];
11
4
  wake = null;
@@ -36,13 +29,6 @@ class Events {
36
29
  }
37
30
  }
38
31
  }
39
- /**
40
- * Runs a compiled graph, narrating it as it goes.
41
- *
42
- * The run starts immediately rather than on the first read: a caller who only
43
- * wants the result should not have to iterate to get one, and a client that
44
- * connects late should see what already happened.
45
- */
46
32
  export function streamGraph(byName, edgesFrom, entry, maxSteps, values, now) {
47
33
  const events = new Events();
48
34
  const result = (async () => {
package/dist/node/edge.js CHANGED
@@ -1,13 +1,6 @@
1
- /**
2
- * An edge from one node to the next, or to the end of the run.
3
- *
4
- * A helper so the argument order is fixed by something other than memory:
5
- * `edge("a", "b")` reads in the direction the run travels.
6
- */
7
1
  export function edge(from, to, when) {
8
2
  return when ? { from, to, when } : { from, to };
9
3
  }
10
- /** Ends the run after `from`. The same as `edge(from, null)`, said out loud. */
11
4
  export function end(from, when) {
12
5
  return edge(from, null, when);
13
6
  }
package/dist/node/node.js CHANGED
@@ -1,12 +1,4 @@
1
- /** Names that read back cleanly in a step record and a compile error. */
2
1
  const VALID_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
3
- /**
4
- * Declares a node, checking what a graph cannot check later.
5
- *
6
- * The same argument as `tool()`: a duplicated argument silently loses one, and a
7
- * hyphenated name reads badly in the step record that is the only trace of a
8
- * failed run.
9
- */
10
2
  export function node(spec) {
11
3
  if (!VALID_NAME.test(spec.name)) {
12
4
  throw new Error(`Node name "${spec.name}" must be letters, digits and underscores, starting with a letter.`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spendgraph/graph",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Wire nodes into a graph, run it, and get back a rollout with every step.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -34,11 +34,11 @@
34
34
  "README.md"
35
35
  ],
36
36
  "scripts": {
37
- "build": "tsc -p tsconfig.json",
37
+ "build": "tsc -p tsconfig.json --emitDeclarationOnly && tsc -p tsconfig.json --declaration false --removeComments",
38
38
  "test": "vitest run"
39
39
  },
40
40
  "dependencies": {
41
- "@spendgraph/sdk": "^0.2.0"
41
+ "@spendgraph/sdk": "^0.3.0"
42
42
  },
43
43
  "devDependencies": {
44
44
  "typescript": "^5"