@oakgreencc/cambium 0.0.8 → 0.0.9

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
@@ -316,6 +316,26 @@ const { transitions, reason, node, input } = await advance(g, { node: 'open-pr',
316
316
  - **`toMermaid(graph)`** renders a flowchart: boxes for steps, hexagons for waits, conditional edges labelled with `when`'s function name.
317
317
  - **`opts.instrument(visit, step)`** (optional) wraps each node visit: `visit` is `{ node, kind: 'node' | 'wait', input }`; `step(extraCtx?)` runs the node (or poll) and picks the edge, returning the transition, or `null` for a wait that is not ready, and throws on a node error. `extraCtx` is merged into that node's `ctx`. Return what `step` returned. Without it, `advance` behaves exactly as before. [`advanceHooks`](#tracing) is the tracing implementation.
318
318
 
319
+ ### LangGraph interop
320
+
321
+ `@oakgreencc/cambium/graph/langgraph` converts graphs to and from [LangGraph](https://docs.langchain.com/oss/javascript/langgraph/overview). LangGraph is not a cambium dependency: install `@langchain/langgraph` and `@langchain/core` yourself (an optional peer dependency). The module does not import LangGraph at load time; `toLangGraph` imports it when called, or takes the module as `{ langgraph }`.
322
+
323
+ ```js
324
+ import { Command, MemorySaver } from '@langchain/langgraph'
325
+ import { fromLangGraph, pollWait, toLangGraph } from '@oakgreencc/cambium/graph/langgraph'
326
+
327
+ const app = (await toLangGraph(g)).compile({ checkpointer: new MemorySaver() })
328
+ const config = { configurable: { thread_id: 'owner/repo#42' }, context: ctx }
329
+ let out = await app.invoke({ subject, last: { issue: 7 } }, config)
330
+ const waiting = out.__interrupt__?.[0]?.value // { waiting: 'ci', input: { pr: 1 } }
331
+ const polled = await pollWait(g, waiting, ctx)
332
+ if (polled.ready) out = await app.invoke(new Command({ resume: polled.output }), config)
333
+ ```
334
+
335
+ - **`toLangGraph(graph, { langgraph }?)`** resolves to an uncompiled `StateGraph` over `{ subject, last, outputs }`: `last` is the next node's input, `outputs` each node's latest output by name, and `subject` what edges see (it is checkpointed, so keep it serializable). Nodes get the run's `context` (plus `signal`) as `ctx`. Each node is `addNode(name, fn, { input })`, its input schema being the node's own on `last`; `fn` validates, runs, picks the edge and applies its `map`, so `last` is already the next input. A wait calls `interrupt({ waiting, input })`; resume it with the ready poll's `output` (`pollWait` runs the poll; a not-ready poll never reaches LangGraph). Edges are `addConditionalEdges`, trying `when` in order; `END` is LangGraph's `END`. Errors are `GraphNodeError`s.
336
+ - **`fromLangGraph(compiled, { name, input, output })`** is a `defineNode` whose `run` invokes the compiled graph with the validated input as its input state and validates the final state against `output`. An imported graph cannot wait: `interrupt()` inside it fails the node with an error saying so.
337
+ - Not carried over: `entry.queue`, `version` and the task graph's per-node declarations (`queue`, `running`, `enter`, `pollOnEntry`, `recover`), which belong to cambium's runtime; a driver applies them around the interrupts, as the differential test in `test/langgraph.test.mjs` does.
338
+
319
339
  ## Tracing
320
340
 
321
341
  `src/tracing.mjs` is OpenTelemetry for cambium, configured only by the standard `OTEL_*` variables with `service.name=cambium`. It reuses mycelium's `createTracing` (same packages, same on/off rule): **on only when `OTEL_EXPORTER_OTLP_ENDPOINT` or `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` is set**, unless `OTEL_SDK_DISABLED=true` or `OTEL_TRACES_EXPORTER=none`; otherwise nothing is imported and every call is a no-op. Metrics follow the same rule for their signal (`OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`, `OTEL_METRICS_EXPORTER`). With an endpoint but no collector, shutdown can take ~8 s; set `OTEL_EXPORTER_OTLP_TIMEOUT=2000` for the daemon.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oakgreencc/cambium",
3
- "version": "0.0.8",
3
+ "version": "0.0.9",
4
4
  "description": "The scheduler daemon: reads the q:* queues from GitHub every tick, runs headless claude workers in their own worktrees up to a cap, and makes every queue transition itself.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
@@ -26,6 +26,7 @@
26
26
  },
27
27
  "exports": {
28
28
  "./graph": "./src/graph/index.mjs",
29
+ "./graph/langgraph": "./src/graph/langgraph.mjs",
29
30
  "./package.json": "./package.json"
30
31
  },
31
32
  "files": [
@@ -50,7 +51,19 @@
50
51
  "@opentelemetry/sdk-metrics": "^3.1.1",
51
52
  "@opentelemetry/sdk-trace": "^3.1.1",
52
53
  "zod": "^4.6.7",
53
- "@oakgreencc/mycelium": "0.0.0"
54
+ "@oakgreencc/mycelium": "0.0.6"
55
+ },
56
+ "devDependencies": {
57
+ "@langchain/core": "^1.4.1",
58
+ "@langchain/langgraph": "^1.7.5"
59
+ },
60
+ "peerDependencies": {
61
+ "@langchain/langgraph": "^1.7.5"
62
+ },
63
+ "peerDependenciesMeta": {
64
+ "@langchain/langgraph": {
65
+ "optional": true
66
+ }
54
67
  },
55
68
  "scripts": {
56
69
  "lint": "biome check .",
@@ -16,7 +16,7 @@ import { check, END, GraphNodeError } from './define.mjs'
16
16
  */
17
17
 
18
18
  /** @param {unknown} err @param {string} node @param {'run' | 'poll' | 'edge'} phase */
19
- const asNodeError = (err, node, phase) =>
19
+ export const asNodeError = (err, node, phase) =>
20
20
  err instanceof GraphNodeError
21
21
  ? err
22
22
  : new GraphNodeError(node, phase, String(/** @type {any} */ (err)?.message ?? err), { cause: err })
@@ -94,7 +94,7 @@ export async function advance(graph, at, ctx = {}, opts = {}) {
94
94
  * The first edge out of `from` whose `when` matches `output`; a node with no outgoing edges goes to END.
95
95
  * @param {import('./define.mjs').Graph} graph @param {string} from @param {unknown} output @param {unknown} subject
96
96
  */
97
- function pick(graph, from, output, subject) {
97
+ export function pick(graph, from, output, subject) {
98
98
  let any = false
99
99
  for (const [i, [f, to, when, map]] of graph.edges.entries()) {
100
100
  if (f !== from) continue
@@ -0,0 +1,200 @@
1
+ // @ts-check
2
+ /**
3
+ * `@oakgreencc/cambium/graph/langgraph`: LangGraph interop for cambium graphs.
4
+ *
5
+ * LangGraph is not a dependency of cambium: install `@langchain/langgraph` (and its peer `@langchain/core`)
6
+ * yourself to use this module. Nothing here imports it at load time; {@link toLangGraph} imports it when called,
7
+ * unless you pass the module in as `{ langgraph }`.
8
+ *
9
+ * - Export, {@link toLangGraph}: a cambium graph as an uncompiled `StateGraph` whose state is
10
+ * `{ subject, last, outputs }`. A wait node calls `interrupt({ waiting, input })`; resume it with what its
11
+ * `poll` returned as `output` ({@link pollWait} runs the poll for you).
12
+ * - Import, {@link fromLangGraph}: a compiled LangGraph graph as one cambium step node.
13
+ */
14
+ import { randomUUID } from 'node:crypto'
15
+ import { asNodeError, pick } from './advance.mjs'
16
+ import { check, defineNode, END, GraphNodeError } from './define.mjs'
17
+
18
+ /**
19
+ * @typedef {import('./define.mjs').Graph} Graph
20
+ * @typedef {import('./define.mjs').StandardSchema} StandardSchema
21
+ * @typedef {{ subject: unknown, last: unknown, outputs: Record<string, unknown> }} State
22
+ * `last` is the input of the node about to run: the previous node's output, through its edge's `map`.
23
+ * `outputs` holds each node's latest output, by node name.
24
+ * @typedef {{ waiting: string, input: unknown }} Waiting The value a wait node passes to `interrupt()`.
25
+ * @typedef {typeof import('@langchain/langgraph')} LangGraphModule
26
+ */
27
+
28
+ /** @param {LangGraphModule | undefined} injected @returns {Promise<LangGraphModule>} */
29
+ async function load(injected) {
30
+ if (injected) return injected
31
+ try {
32
+ return await import('@langchain/langgraph')
33
+ } catch (err) {
34
+ throw new Error('toLangGraph needs @langchain/langgraph (and @langchain/core): install them alongside cambium', {
35
+ cause: err,
36
+ })
37
+ }
38
+ }
39
+
40
+ /**
41
+ * The ctx a node gets: LangGraph's run `context` (`invoke(input, { context })`), with the run's `signal`.
42
+ * @param {any} config @returns {Record<string, unknown>}
43
+ */
44
+ const ctxOf = (config) => {
45
+ const ctx = config?.context ?? {}
46
+ return { ...ctx, signal: config?.signal ?? ctx.signal }
47
+ }
48
+
49
+ /**
50
+ * `graph` as an uncompiled LangGraph `StateGraph`. Compile it with a checkpointer when the graph has waits.
51
+ *
52
+ * - State: `{ subject, last, outputs }`. Start a run with `{ subject, last: <entry input> }`; `subject` is what
53
+ * edge `when`/`map` see (cambium's advance passes `ctx.subject`), so it is checkpointed and must be serializable.
54
+ * - Nodes get `{ ...context, signal }` as ctx, where `context` is the run's `invoke(…, { context })`.
55
+ * - A step node validates `last`, runs, validates its output, picks its edge as advance does, and writes
56
+ * `outputs[name]` and `last` (the chosen edge's `map` is applied here: a LangGraph router cannot write state).
57
+ * - A wait node validates `last` and calls `interrupt({ waiting: name, input })`; the resume value is the
58
+ * ready poll's `output`, validated against the wait's output schema. Not-ready polls never reach LangGraph:
59
+ * poll outside ({@link pollWait}) and resume only when ready.
60
+ * - Edges: `addConditionalEdges(from, router)`, the router trying `when` in order on `outputs[from]`; a node with
61
+ * no outgoing edges goes to LangGraph's END. Errors are thrown as cambium's `GraphNodeError`.
62
+ *
63
+ * @param {Graph} graph
64
+ * @param {{ langgraph?: LangGraphModule }} [opts] the `@langchain/langgraph` module, instead of importing it
65
+ */
66
+ export async function toLangGraph(graph, opts = {}) {
67
+ const lg = await load(opts.langgraph)
68
+ const { Annotation, StateGraph, START, interrupt } = lg
69
+ const LG_END = lg.END
70
+ const State = Annotation.Root({
71
+ subject: Annotation(),
72
+ last: Annotation(),
73
+ outputs: Annotation({
74
+ reducer: (/** @type {Record<string, unknown>} */ a, /** @type {Record<string, unknown>} */ b) => ({ ...a, ...b }),
75
+ default: () => ({}),
76
+ }),
77
+ })
78
+ const sg = new StateGraph(State)
79
+ const Any = {
80
+ '~standard': { version: 1, vendor: 'cambium', validate: (/** @type {unknown} */ value) => ({ value }) },
81
+ }
82
+
83
+ for (const node of graph.nodes) {
84
+ const { name } = node
85
+ /** @param {unknown} output @param {unknown} subject */
86
+ const settle = (output, subject) => {
87
+ let next
88
+ try {
89
+ ;({ next } = pick(graph, name, output, subject))
90
+ } catch (err) {
91
+ throw asNodeError(err, name, 'edge')
92
+ }
93
+ return { last: next, outputs: { [name]: output } }
94
+ }
95
+ /** @param {State} state @param {any} config */
96
+ const fn =
97
+ node.kind === 'wait'
98
+ ? async (state) => {
99
+ const input = await check(node.input, state.last, name, 'input')
100
+ const resumed = interrupt(/** @type {Waiting} */ ({ waiting: name, input }))
101
+ return settle(await check(node.output, resumed, name, 'output'), state.subject)
102
+ }
103
+ : async (state, config) => {
104
+ const input = await check(node.input, state.last, name, 'input')
105
+ let out
106
+ try {
107
+ out = await node.run(input, ctxOf(config))
108
+ } catch (err) {
109
+ throw asNodeError(err, name, 'run')
110
+ }
111
+ return settle(await check(node.output, out, name, 'output'), state.subject)
112
+ }
113
+ sg.addNode(name, fn, { input: new lg.StateSchema({ subject: Any, last: node.input }) })
114
+ }
115
+
116
+ sg.addEdge(START, /** @type {any} */ (graph.entry.node))
117
+ /** @type {Map<string, import('./define.mjs').Edge[]>} */
118
+ const out = new Map()
119
+ for (const e of graph.edges) out.set(e[0], [...(out.get(e[0]) ?? []), e])
120
+ const target = (/** @type {string} */ to) => (to === END ? LG_END : to)
121
+ for (const node of graph.nodes) {
122
+ const edges = out.get(node.name)
123
+ if (!edges) {
124
+ sg.addEdge(/** @type {any} */ (node.name), LG_END)
125
+ continue
126
+ }
127
+ const ends = [...new Set(edges.map(([, to]) => target(to)))]
128
+ /** @param {State} state */
129
+ const router = (state) => {
130
+ const o = state.outputs[node.name]
131
+ for (const [, to, when] of edges) if (!when || when(o, state.subject)) return target(to)
132
+ throw new GraphNodeError(node.name, 'edge', 'no edge matched the output')
133
+ }
134
+ sg.addConditionalEdges(/** @type {any} */ (node.name), router, /** @type {any} */ (ends))
135
+ }
136
+ return sg
137
+ }
138
+
139
+ /**
140
+ * Poll the wait a LangGraph run is interrupted at: `{ ready: true, output }` means resume with
141
+ * `new Command({ resume: output })`; `{ ready: false }` means leave the thread where it is.
142
+ * @param {Graph} graph @param {Waiting} waiting the interrupt's value @param {Record<string, unknown>} [ctx]
143
+ * @returns {Promise<import('./define.mjs').PollResult>}
144
+ */
145
+ export async function pollWait(graph, waiting, ctx = {}) {
146
+ const node = graph.nodes.find((n) => n.name === waiting?.waiting)
147
+ if (node?.kind !== 'wait') throw new Error(`graph "${graph.name}" has no wait node "${waiting?.waiting}"`)
148
+ const input = await check(node.input, waiting.input, node.name, 'input')
149
+ let polled
150
+ try {
151
+ polled = await node.poll(input, ctx)
152
+ } catch (err) {
153
+ throw asNodeError(err, node.name, 'poll')
154
+ }
155
+ if (typeof polled?.ready !== 'boolean')
156
+ throw new GraphNodeError(node.name, 'poll', 'poll must return { ready: false } or { ready: true, output }')
157
+ return polled
158
+ }
159
+
160
+ /** @param {unknown} err */
161
+ const isInterrupt = (err) =>
162
+ /** @type {any} */ (err)?.name === 'GraphInterrupt' ||
163
+ /** @type {any} */ (err)?.lc_error_code === 'MISSING_CHECKPOINTER'
164
+
165
+ /**
166
+ * A compiled LangGraph graph as one cambium step node: `run` invokes it with the node's validated input as the
167
+ * graph's input state (passing ctx's `signal`), and its final state is validated against `output`.
168
+ *
169
+ * An imported graph cannot wait: an `interrupt()` inside it fails the node with an error saying so (with or
170
+ * without a checkpointer). Its own nodes stay opaque; they are closures over its state.
171
+ *
172
+ * @param {{ invoke: (input: any, config?: any) => Promise<any> }} compiled
173
+ * @param {{ name: string, input: StandardSchema, output: StandardSchema }} def
174
+ */
175
+ export function fromLangGraph(compiled, { name, input, output }) {
176
+ if (typeof compiled?.invoke !== 'function') throw new Error(`fromLangGraph "${name}": expected a compiled graph`)
177
+ const interrupted = () =>
178
+ new Error(
179
+ `imported LangGraph graph "${name}" called interrupt(); cambium runs imported graphs to completion and cannot resume them, so model the wait as a cambium wait node instead`,
180
+ )
181
+ return defineNode({
182
+ name,
183
+ input,
184
+ output,
185
+ run: async (value, ctx) => {
186
+ let result
187
+ try {
188
+ result = await compiled.invoke(value, {
189
+ signal: ctx?.signal,
190
+ configurable: { thread_id: `cambium:${name}:${randomUUID()}` },
191
+ })
192
+ } catch (err) {
193
+ if (isInterrupt(err)) throw interrupted()
194
+ throw err
195
+ }
196
+ if (Array.isArray(result?.__interrupt__) && result.__interrupt__.length) throw interrupted()
197
+ return result
198
+ },
199
+ })
200
+ }