@lzn1998/dsh-langgraph 0.0.0-stage → 0.13.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/dsh-store.js ADDED
@@ -0,0 +1,262 @@
1
+ /**
2
+ * A durable LangGraph `BaseStore` over the DSH `storageDomain` service.
3
+ *
4
+ * `InMemoryStore` disappears with the Host process, and a graph's long-term
5
+ * memories should not. This store keeps one validated record per
6
+ * `(namespace, key)` in the `langgraph_store` domain; every write is durable
7
+ * before it resolves.
8
+ *
9
+ * Only the filter/pagination part of `BaseStore` is implemented. Vector search
10
+ * (`search({ query })`) is deliberately rejected rather than silently returning
11
+ * unranked results: a graph that wants embeddings should configure a store that
12
+ * actually implements them.
13
+ * @module dsh-langgraph/store
14
+ */
15
+
16
+ import { BaseStore } from '@langchain/langgraph-checkpoint'
17
+ import { z } from 'zod'
18
+
19
+ const POLLUTION_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
20
+
21
+ /** One serialized store item. */
22
+ const storedItem = z.object({
23
+ namespace: z.array(z.string()),
24
+ key: z.string(),
25
+ value: z.record(z.string(), z.unknown()),
26
+ createdAt: z.number(),
27
+ updatedAt: z.number(),
28
+ })
29
+
30
+ /** Declared DSH storage domain. */
31
+ export const STORE_DOMAIN = Object.freeze({
32
+ name: 'langgraph_store',
33
+ version: 1,
34
+ layout: 'per-record',
35
+ tables: {
36
+ items: { valueSchema: storedItem },
37
+ },
38
+ })
39
+
40
+ /** @param {unknown} value - candidate namespace. @param {boolean} [allowEmpty] - permit `[]` for search. */
41
+ function assertNamespace(value, allowEmpty = false) {
42
+ if (!Array.isArray(value) || value.some(part => typeof part !== 'string' || part === '' || POLLUTION_KEYS.has(part))) {
43
+ throw new Error('store: namespace must be an array of non-empty strings')
44
+ }
45
+ if (!allowEmpty && value.length === 0) throw new Error('store: namespace must not be empty')
46
+ return value
47
+ }
48
+
49
+ /** @param {string[]} namespace - namespace. @param {string} key - item key. @returns {string} record key. */
50
+ function itemKey(namespace, key) {
51
+ return Buffer.from(JSON.stringify([namespace, key]), 'utf8').toString('base64url')
52
+ }
53
+
54
+ /**
55
+ * @param {string} encoded - record key.
56
+ * @returns {[string[], string]} namespace and key.
57
+ */
58
+ function parseItemKey(encoded) {
59
+ const parsed = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8'))
60
+ if (!Array.isArray(parsed) || parsed.length !== 2 || !Array.isArray(parsed[0]) || typeof parsed[1] !== 'string') {
61
+ throw new Error('not a store item key')
62
+ }
63
+ return [parsed[0], parsed[1]]
64
+ }
65
+
66
+ /** JSON-safe clone, or a clear error for a value the domain cannot store. */
67
+ function jsonValue(value) {
68
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
69
+ throw new Error('store: value must be a plain JSON object')
70
+ }
71
+ try {
72
+ return JSON.parse(JSON.stringify(value, (_key, item) => (typeof item === 'bigint' ? String(item) : item)))
73
+ } catch {
74
+ throw new Error('store: value must be JSON-serializable')
75
+ }
76
+ }
77
+
78
+ /** @param {object} record - stored item. @returns {object} `Item` with Date timestamps. */
79
+ function itemOf(record) {
80
+ return {
81
+ value: record.value,
82
+ key: record.key,
83
+ namespace: record.namespace,
84
+ createdAt: new Date(record.createdAt),
85
+ updatedAt: new Date(record.updatedAt),
86
+ }
87
+ }
88
+
89
+ /** Read a dotted field path from a value. */
90
+ function fieldOf(value, path) {
91
+ let cursor = value
92
+ for (const part of path.split('.')) {
93
+ if (cursor === null || typeof cursor !== 'object' || !(part in cursor)) return undefined
94
+ cursor = cursor[part]
95
+ }
96
+ return cursor
97
+ }
98
+
99
+ /** Compare one value against one filter operand, including the supported operators. */
100
+ function matchesOperand(actual, expected) {
101
+ if (expected !== null && typeof expected === 'object' && !Array.isArray(expected)) {
102
+ for (const [operator, operand] of Object.entries(expected)) {
103
+ if (operator === '$eq' && actual !== operand) return false
104
+ else if (operator === '$ne' && actual === operand) return false
105
+ else if (operator === '$gt' && !(actual > operand)) return false
106
+ else if (operator === '$gte' && !(actual >= operand)) return false
107
+ else if (operator === '$lt' && !(actual < operand)) return false
108
+ else if (operator === '$lte' && !(actual <= operand)) return false
109
+ else if (!operator.startsWith('$')) return false
110
+ }
111
+ return true
112
+ }
113
+ return actual === expected
114
+ }
115
+
116
+ /** Whether one item satisfies every filter field. */
117
+ function matchesFilter(value, filter) {
118
+ if (filter === undefined) return true
119
+ return Object.entries(filter).every(([path, expected]) => matchesOperand(fieldOf(value, path), expected))
120
+ }
121
+
122
+ /** Whether a namespace starts with a prefix. */
123
+ function startsWith(namespace, prefix) {
124
+ return prefix.length <= namespace.length && prefix.every((part, index) => part === namespace[index])
125
+ }
126
+
127
+ /** Match one wildcard path against a namespace prefix or suffix. */
128
+ function matchesPath(namespace, path, kind) {
129
+ if (path.length > namespace.length) return false
130
+ const offset = kind === 'suffix' ? namespace.length - path.length : 0
131
+ return path.every((part, index) => part === '*' || part === namespace[offset + index])
132
+ }
133
+
134
+ /** A durable `BaseStore` backed by one DSH storage domain. */
135
+ export class DshStore extends BaseStore {
136
+ /** @param {object} domain - an open storage domain shaped by {@link STORE_DOMAIN}. */
137
+ constructor(domain) {
138
+ super()
139
+ this.domain = domain
140
+ }
141
+
142
+ /** @returns {any} the items table. */
143
+ table() {
144
+ return this.domain.table('items')
145
+ }
146
+
147
+ /**
148
+ * Read one item.
149
+ * @param {{ namespace: string[], key: string }} operation - get operation.
150
+ * @returns {Promise<object | null>} the item or null.
151
+ */
152
+ async getOperation(operation) {
153
+ assertNamespace(operation.namespace, true)
154
+ if (typeof operation.key !== 'string' || operation.key === '') throw new Error('store: key must be a non-empty string')
155
+ const record = this.table().get(itemKey(operation.namespace, operation.key))
156
+ return record === undefined ? null : itemOf(record)
157
+ }
158
+
159
+ /**
160
+ * Put or delete one item.
161
+ * @param {{ namespace: string[], key: string, value: object | null }} operation - put operation.
162
+ * @returns {Promise<undefined>} nothing.
163
+ */
164
+ async putOperation(operation) {
165
+ assertNamespace(operation.namespace)
166
+ if (typeof operation.key !== 'string' || operation.key === '') throw new Error('store: key must be a non-empty string')
167
+ const key = itemKey(operation.namespace, operation.key)
168
+ if (operation.value === null) {
169
+ await this.table().delete(key)
170
+ return undefined
171
+ }
172
+ const now = Date.now()
173
+ const existing = this.table().get(key)
174
+ await this.table().put(key, {
175
+ namespace: operation.namespace,
176
+ key: operation.key,
177
+ value: jsonValue(operation.value),
178
+ createdAt: existing === undefined ? now : existing.createdAt,
179
+ updatedAt: now,
180
+ })
181
+ return undefined
182
+ }
183
+
184
+ /**
185
+ * Search items under a namespace prefix.
186
+ * @param {{ namespacePrefix: string[], filter?: object, limit?: number, offset?: number, query?: string }} operation - search operation.
187
+ * @returns {Promise<object[]>} matching items.
188
+ */
189
+ async searchOperation(operation) {
190
+ if (operation.query !== undefined) {
191
+ throw new Error('store: vector search is not implemented; omit `query` or use embeddings-backed store')
192
+ }
193
+ assertNamespace(operation.namespacePrefix, true)
194
+ const matched = []
195
+ for (const [key, record] of this.table().entries()) {
196
+ let namespace
197
+ try {
198
+ [namespace] = parseItemKey(key)
199
+ } catch {
200
+ continue
201
+ }
202
+ if (!startsWith(namespace, operation.namespacePrefix)) continue
203
+ if (!matchesFilter(record.value, operation.filter)) continue
204
+ matched.push(itemOf(record))
205
+ }
206
+ matched.sort((left, right) => right.updatedAt.getTime() - left.updatedAt.getTime() || left.key.localeCompare(right.key))
207
+ const offset = Number.isInteger(operation.offset) && operation.offset > 0 ? operation.offset : 0
208
+ const limit = Number.isInteger(operation.limit) && operation.limit >= 0 ? operation.limit : 10
209
+ return matched.slice(offset, offset + limit)
210
+ }
211
+
212
+ /**
213
+ * List namespaces, with prefix/suffix wildcard conditions.
214
+ * @param {{ matchConditions?: { matchType: 'prefix' | 'suffix', path: string[] }[], maxDepth?: number, limit?: number, offset?: number }} operation - list operation.
215
+ * @returns {Promise<string[][]>} namespaces.
216
+ */
217
+ async listNamespacesOperation(operation) {
218
+ const namespaces = new Map()
219
+ for (const key of this.table().keys()) {
220
+ let namespace
221
+ try {
222
+ [namespace] = parseItemKey(key)
223
+ } catch {
224
+ continue
225
+ }
226
+ if (operation.maxDepth !== undefined) namespace = namespace.slice(0, operation.maxDepth)
227
+ const conditions = operation.matchConditions ?? []
228
+ if (!conditions.every(condition => matchesPath(namespace, condition.path, condition.matchType))) continue
229
+ namespaces.set(JSON.stringify(namespace), namespace)
230
+ }
231
+ const rows = [...namespaces.values()].sort((left, right) => left.join('/').localeCompare(right.join('/')))
232
+ const offset = Number.isInteger(operation.offset) && operation.offset > 0 ? operation.offset : 0
233
+ const limit = Number.isInteger(operation.limit) && operation.limit >= 0 ? operation.limit : 100
234
+ return rows.slice(offset, offset + limit)
235
+ }
236
+
237
+ /**
238
+ * Execute a batch of LangGraph store operations.
239
+ * @param {object[]} operations - get/put/search/listNamespaces operations.
240
+ * @returns {Promise<unknown[]>} one result per operation.
241
+ */
242
+ async batch(operations) {
243
+ const results = []
244
+ for (const operation of operations) {
245
+ if (operation.namespacePrefix !== undefined) results.push(await this.searchOperation(operation))
246
+ else if ('value' in operation) results.push(await this.putOperation(operation))
247
+ else if (operation.namespace === undefined) results.push(await this.listNamespacesOperation(operation))
248
+ else results.push(await this.getOperation(operation))
249
+ }
250
+ return results
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Open the durable store domain.
256
+ * @param {object} storageDomain - the `storageDomain` service.
257
+ * @returns {Promise<{ store: DshStore, close: () => Promise<void> }>} the open store.
258
+ */
259
+ export async function openDshStore(storageDomain) {
260
+ const domain = await storageDomain.open(STORE_DOMAIN)
261
+ return { store: new DshStore(domain), close: () => domain.close() }
262
+ }
package/dsh-tools.js ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * DSH tools as LangChain tools.
3
+ *
4
+ * LangGraph's prebuilt agents only accept tools that are Runnables, so each DSH tool is
5
+ * wrapped with `tool()` and a zod schema converted from the DSH tool's own JSON schema.
6
+ * The original JSON schema stays on the wrapper as `dshParameters`, which is what the
7
+ * chat model sends to the provider.
8
+ * @module dsh-langgraph/tools
9
+ */
10
+
11
+ import { z } from 'zod'
12
+ import { tool } from '@langchain/core/tools'
13
+
14
+ /**
15
+ * Convert the JSON-schema subset DSH tool parameters use into a zod schema.
16
+ * @param {object} schema - JSON schema node.
17
+ * @returns {import('zod').ZodTypeAny} the zod schema.
18
+ */
19
+ export function zodFromJsonSchema(schema) {
20
+ if (schema === null || typeof schema !== 'object') return z.any()
21
+ const type = schema.type
22
+ if (type === 'string') return Array.isArray(schema.enum) ? z.enum(schema.enum) : z.string()
23
+ if (type === 'number') return z.number()
24
+ if (type === 'integer') return z.number().int()
25
+ if (type === 'boolean') return z.boolean()
26
+ if (type === 'null') return z.null()
27
+ if (type === 'array') return z.array(zodFromJsonSchema(schema.items ?? {}))
28
+ const properties = schema.properties
29
+ if (type === 'object' || (properties !== undefined && typeof properties === 'object')) {
30
+ const shape = {}
31
+ const required = new Set(Array.isArray(schema.required) ? schema.required : [])
32
+ for (const [key, value] of Object.entries(properties ?? {})) {
33
+ const inner = zodFromJsonSchema(value)
34
+ shape[key] = required.has(key) ? inner : inner.optional()
35
+ }
36
+ const object = z.object(shape)
37
+ return schema.additionalProperties === true ? object.passthrough() : object
38
+ }
39
+ return z.any()
40
+ }
41
+
42
+ /**
43
+ * Wrap one DSH tool definition as a LangChain tool.
44
+ * @param {{ name: string, description: string, parameters: object }} definition - DSH tool definition.
45
+ * @param {(name: string, args: object) => Promise<string>} callTool - runs the DSH tool.
46
+ * @returns {object} a LangChain tool carrying `dshParameters`.
47
+ */
48
+ export function langchainTool(definition, callTool) {
49
+ const wrapped = tool(async input => callTool(definition.name, input ?? {}), {
50
+ name: definition.name,
51
+ description: definition.description,
52
+ schema: zodFromJsonSchema(definition.parameters),
53
+ })
54
+ wrapped.dshParameters = definition.parameters
55
+ return wrapped
56
+ }
package/dsh-trace.js ADDED
@@ -0,0 +1,313 @@
1
+ /**
2
+ * LangGraph activity as DSH log-only trace events.
3
+ *
4
+ * DSH's Trajectory view renders a tool call and its nested sub-calls from
5
+ * `tool/ptc-dispatch-start` and `tool/ptc-dispatch`. Those two events are
6
+ * log-only: `deriveMessages()` ignores them, so a trace never enters the model
7
+ * context. They are also the only nested-call vocabulary the stock Trajectory
8
+ * view understands, which makes them the non-invasive bridge for a third-party
9
+ * plugin: neither DSH nor LangGraph is modified.
10
+ *
11
+ * Every event below has the shape the PTC executor writes. The outer tool call
12
+ * is the `langgraph_run` row; node boundaries, LangChain tool calls, and model
13
+ * calls are its nested sub-calls, so the whole graph is one expandable run.
14
+ * @module dsh-langgraph/trace
15
+ */
16
+
17
+ const MAX_TEXT = 4000
18
+ const MAX_MESSAGE_TEXT = 1500
19
+
20
+ /** JSON-safe value, or the fallback when the value cannot round-trip. */
21
+ function jsonValue(value, fallback = {}) {
22
+ try {
23
+ return JSON.parse(JSON.stringify(value, (_key, item) => (typeof item === 'bigint' ? String(item) : item)))
24
+ } catch {
25
+ return fallback
26
+ }
27
+ }
28
+
29
+ /** Concatenated text of a content value. */
30
+ function contentText(value) {
31
+ if (typeof value === 'string') return value
32
+ if (Array.isArray(value)) {
33
+ return value
34
+ .map(part => (typeof part === 'string' ? part : part?.type === 'text' ? part.text : ''))
35
+ .filter(Boolean)
36
+ .join('\n')
37
+ }
38
+ if (value === null || value === undefined) return ''
39
+ return JSON.stringify(jsonValue(value))
40
+ }
41
+
42
+ /** Bound one trace field so a large state or result cannot flood the log. */
43
+ function clip(text, limit = MAX_TEXT) {
44
+ const value = String(text ?? '')
45
+ return value.length <= limit ? value : `${value.slice(0, limit)}\n… [truncated ${value.length - limit} chars]`
46
+ }
47
+
48
+ /** Summarize the LangChain message batches of one model call. */
49
+ function summarizeMessages(messages) {
50
+ const flat = Array.isArray(messages) ? messages.flat(1) : []
51
+ return flat.map(message => ({
52
+ role: String(message?.getType?.() ?? message?._getType?.() ?? message?.role ?? 'message'),
53
+ text: clip(contentText(message?.content), MAX_MESSAGE_TEXT),
54
+ }))
55
+ }
56
+
57
+ /** Text of one `LLMResult`, falling back to the tool calls a model-only reply requested. */
58
+ function resultText(output) {
59
+ const generation = output?.generations?.[0]?.[0]
60
+ if (generation === undefined) return ''
61
+ if (typeof generation.text === 'string' && generation.text !== '') return generation.text
62
+ const content = contentText(generation.message?.content)
63
+ if (content !== '') return content
64
+ const toolCalls = generation.message?.tool_calls
65
+ return Array.isArray(toolCalls) && toolCalls.length > 0 ? JSON.stringify(jsonValue(toolCalls, [])) : ''
66
+ }
67
+
68
+ /**
69
+ * Create a tracer bound to one `langgraph_run` execution.
70
+ * @param {{ agent?: object, callId?: string, rootCallId?: string }} exec - the tool execution.
71
+ * @param {string} graphId - the graph being run.
72
+ * @param {boolean} [configured=true] - row config; false disables tracing.
73
+ * @param {(event: { phase: 'start' | 'end', name: string, isError?: boolean }) => void} [onEvent]
74
+ * optional progress sink for a background job's output ring.
75
+ * @returns {object} tracer with `callbacks`, `begin`, `finish`, and `currentNode`.
76
+ */
77
+ export function createTracer(exec, graphId, configured = true, onEvent) {
78
+ const session = exec?.agent?.session
79
+ const outerCallId = exec?.callId
80
+ const rootCallId = exec?.rootCallId ?? outerCallId
81
+ const enabled = configured && session !== undefined && typeof session.append === 'function'
82
+ && typeof outerCallId === 'string' && typeof rootCallId === 'string'
83
+ let live = enabled
84
+ let sequence = 0
85
+ /** runId -> trace handle for a node, inner chain, tool, or model call. */
86
+ const runs = new Map()
87
+ /** Active node traces in start order; the last one is the best-effort current node. */
88
+ const nodes = []
89
+
90
+ /**
91
+ * Append one trace event. A rejected append disables tracing for this run
92
+ * rather than risking the graph, which is the product work.
93
+ */
94
+ function append(type, data) {
95
+ if (!live) return false
96
+ try {
97
+ session.append(type, data)
98
+ return true
99
+ } catch {
100
+ live = false
101
+ return false
102
+ }
103
+ }
104
+
105
+ /** Report one trace transition to the optional background-job sink. */
106
+ function notify(event) {
107
+ if (onEvent === undefined) return
108
+ try {
109
+ onEvent(event)
110
+ } catch {
111
+ // A progress sink must never break the graph.
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Start one nested trace.
117
+ * @param {string} name - display name in Trajectory.
118
+ * @param {unknown} args - JSON-safe arguments shown by the inspector.
119
+ * @param {object} [parent] - explicit parent trace; defaults to the current node.
120
+ * @returns {object | undefined} a handle for `finish`, or undefined when tracing is off.
121
+ */
122
+ function begin(name, args, parent) {
123
+ if (!live) return undefined
124
+ // An omitted parent means "the current node"; null means "explicitly outer"
125
+ // (siblings under the root graph must not nest under the last active node).
126
+ const resolved = parent === undefined ? nodes.at(-1) : parent
127
+ const parentCallId = resolved === null ? outerCallId : resolved?.subCallId ?? outerCallId
128
+ const subCallId = `${outerCallId}:lg:${++sequence}`
129
+ const argumentsValue = jsonValue(args ?? {})
130
+ if (!append('tool/ptc-dispatch-start', {
131
+ rootCallId,
132
+ parentCallId,
133
+ subCallId,
134
+ name,
135
+ arguments: argumentsValue,
136
+ })) return undefined
137
+ notify({ phase: 'start', name })
138
+ return { rootCallId, parentCallId, subCallId, name, arguments: argumentsValue }
139
+ }
140
+
141
+ /**
142
+ * Settle one nested trace.
143
+ * @param {object | undefined} handle - the handle from `begin`.
144
+ * @param {{ content?: unknown[], isError?: boolean, error?: object, meta?: unknown }} [outcome] - trace outcome.
145
+ */
146
+ function finish(handle, outcome = {}) {
147
+ if (handle === undefined || !live) return
148
+ const { content = [], isError = false, error, meta } = outcome
149
+ if (!append('tool/ptc-dispatch', {
150
+ rootCallId: handle.rootCallId,
151
+ parentCallId: handle.parentCallId,
152
+ subCallId: handle.subCallId,
153
+ name: handle.name,
154
+ arguments: handle.arguments,
155
+ isError,
156
+ content: jsonValue(content, []),
157
+ ...(error === undefined ? {} : { error: jsonValue(error, {}) }),
158
+ ...(meta === undefined ? {} : { meta: jsonValue(meta, {}) }),
159
+ })) return
160
+ notify({ phase: 'end', name: handle.name, isError })
161
+ }
162
+
163
+ /**
164
+ * The trace a nested callback belongs to. An undefined parent run means the
165
+ * caller has no enclosing run and the current node is the right fallback; a
166
+ * defined but unmapped run (the graph root) must stay at the outer level so
167
+ * fan-out siblings do not nest under whichever node started last.
168
+ */
169
+ function parentOf(runId) {
170
+ if (runId === undefined) return undefined
171
+ return runs.get(runId) ?? null
172
+ }
173
+
174
+ /** Close a trace as a failure, or as a pause when LangGraph interrupted it. */
175
+ function closeError(handle, error) {
176
+ if (error?.name === 'GraphInterrupt' || error?.name === 'NodeInterrupt') {
177
+ finish(handle, {
178
+ isError: false,
179
+ content: [{ type: 'text', text: `interrupted: ${clip(error?.message ?? '')}` }],
180
+ })
181
+ return
182
+ }
183
+ finish(handle, {
184
+ isError: true,
185
+ content: [{ type: 'text', text: clip(error?.message ?? String(error ?? 'failed')) }],
186
+ error: {
187
+ name: error?.name ?? 'Error',
188
+ code: typeof error?.code === 'string' ? error.code : 'LANGGRAPH_ERROR',
189
+ },
190
+ })
191
+ }
192
+
193
+ /** Whether one chain run is an actual graph node rather than an inner runnable. */
194
+ function isNodeRun(node, tags) {
195
+ return typeof node === 'string' && node !== '' && node !== '__start__' && node !== '__end__'
196
+ && Array.isArray(tags) && tags.some(tag => typeof tag === 'string' && tag.startsWith('graph:step:'))
197
+ && !tags.includes('langsmith:hidden')
198
+ }
199
+
200
+ const handler = {
201
+ name: 'dsh-langgraph-trace',
202
+
203
+ handleChainStart(serialized, inputs, runId, parentRunId, tags, metadata) {
204
+ const node = metadata?.langgraph_node
205
+ if (isNodeRun(node, tags)) {
206
+ const handle = begin(`langgraph:node ${node}`, {
207
+ graph: graphId,
208
+ node,
209
+ step: metadata?.langgraph_step,
210
+ }, parentRunId === undefined ? null : parentOf(parentRunId))
211
+ if (handle !== undefined) {
212
+ const trace = { ...handle, kind: 'node', runId, node }
213
+ runs.set(runId, trace)
214
+ nodes.push(trace)
215
+ }
216
+ return
217
+ }
218
+ // Inner chains inherit their node's trace, so a tool/model event nested
219
+ // under a RunnableLambda still lands inside the node.
220
+ const inherited = runs.get(parentRunId)
221
+ if (inherited !== undefined) runs.set(runId, inherited)
222
+ },
223
+
224
+ handleChainEnd(outputs, runId) {
225
+ const trace = runs.get(runId)
226
+ if (trace === undefined) return
227
+ if (trace.kind === 'node' && trace.runId === runId) {
228
+ finish(trace, {
229
+ content: [{ type: 'text', text: clip(JSON.stringify(jsonValue(outputs))) }],
230
+ })
231
+ const index = nodes.lastIndexOf(trace)
232
+ if (index >= 0) nodes.splice(index, 1)
233
+ }
234
+ runs.delete(runId)
235
+ },
236
+
237
+ handleChainError(error, runId) {
238
+ const trace = runs.get(runId)
239
+ if (trace === undefined) return
240
+ if (trace.kind === 'node' && trace.runId === runId) {
241
+ closeError(trace, error)
242
+ const index = nodes.lastIndexOf(trace)
243
+ if (index >= 0) nodes.splice(index, 1)
244
+ }
245
+ runs.delete(runId)
246
+ },
247
+
248
+ handleToolStart(tool, input, runId, parentRunId) {
249
+ // Prebuilt ToolNode serializes a DynamicStructuredTool wrapper without a
250
+ // name; the DSH bridge traces the real name from the tool definition.
251
+ const name = typeof tool?.name === 'string' && tool.name !== '' ? tool.name : undefined
252
+ if (name === undefined) return
253
+ const handle = begin(`langgraph:tool ${name}`, input, parentOf(parentRunId))
254
+ if (handle !== undefined) runs.set(runId, { ...handle, kind: 'tool' })
255
+ },
256
+
257
+ handleToolEnd(output, runId) {
258
+ const trace = runs.get(runId)
259
+ if (trace === undefined) return
260
+ finish(trace, { content: [{ type: 'text', text: clip(contentText(output)) }] })
261
+ runs.delete(runId)
262
+ },
263
+
264
+ handleToolError(error, runId) {
265
+ const trace = runs.get(runId)
266
+ if (trace === undefined) return
267
+ closeError(trace, error)
268
+ runs.delete(runId)
269
+ },
270
+
271
+ handleChatModelStart(llm, messages, runId, parentRunId) {
272
+ const handle = begin('langgraph:model', {
273
+ model: llm?.model ?? llm?.name ?? llm?._llmType?.(),
274
+ messages: summarizeMessages(messages),
275
+ }, parentOf(parentRunId))
276
+ if (handle !== undefined) runs.set(runId, { ...handle, kind: 'model' })
277
+ },
278
+
279
+ handleLLMStart(llm, prompts, runId, parentRunId) {
280
+ const handle = begin('langgraph:model', {
281
+ model: llm?.model ?? llm?.name ?? llm?._llmType?.(),
282
+ prompts: (Array.isArray(prompts) ? prompts : []).map(prompt => clip(prompt, MAX_MESSAGE_TEXT)),
283
+ }, parentOf(parentRunId))
284
+ if (handle !== undefined) runs.set(runId, { ...handle, kind: 'model' })
285
+ },
286
+
287
+ handleLLMEnd(output, runId) {
288
+ const trace = runs.get(runId)
289
+ if (trace === undefined) return
290
+ const usage = output?.llmOutput?.tokenUsage
291
+ finish(trace, {
292
+ content: [{ type: 'text', text: clip(resultText(output)) }],
293
+ ...(usage === undefined ? {} : { meta: { usage } }),
294
+ })
295
+ runs.delete(runId)
296
+ },
297
+
298
+ handleLLMError(error, runId) {
299
+ const trace = runs.get(runId)
300
+ if (trace === undefined) return
301
+ closeError(trace, error)
302
+ runs.delete(runId)
303
+ },
304
+ }
305
+
306
+ return {
307
+ enabled,
308
+ callbacks: enabled ? [handler] : [],
309
+ begin,
310
+ finish,
311
+ currentNode: () => nodes.at(-1),
312
+ }
313
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Example workflow that pauses for a decision before doing any work.
3
+ *
4
+ * The gate node calls LangGraph's `interrupt(...)`: the run stops, the agent sees
5
+ * `status: "interrupted"` with the question, and `langgraph_run({ graph, thread,
6
+ * resume })` continues exactly at the same node with the answer.
7
+ */
8
+
9
+ /** Graph id used by the `langgraph_run` tool. */
10
+ export const id = 'approval-gate'
11
+
12
+ /** One-line description shown when the agent lists graphs. */
13
+ export const description = 'Ask before scanning: pause on a decision, then glob the approved pattern.'
14
+
15
+ /** JSON Schema of the initial state, shown to the agent when it lists graphs. */
16
+ export const input = {
17
+ type: 'object',
18
+ properties: {
19
+ pattern: { type: 'string', description: 'Glob pattern to scan once approved; defaults to **/*.js.' },
20
+ },
21
+ additionalProperties: false,
22
+ }
23
+
24
+ /** Interpret the resume value as an approve/reject decision. */
25
+ function approvedBy(answer) {
26
+ if (typeof answer === 'boolean') return answer
27
+ return /^(y|yes|ok|approve|approved|true)$/i.test(String(answer ?? '').trim())
28
+ }
29
+
30
+ /**
31
+ * Build the graph.
32
+ * @param {object} api - LangGraph API plus `helpers` bound to one run.
33
+ * @returns {object} an uncompiled StateGraph; the plugin compiles it with the checkpointer.
34
+ */
35
+ export function build({ StateGraph, Annotation, START, END, interrupt, helpers }) {
36
+ const State = Annotation.Root({
37
+ pattern: Annotation({ reducer: (_, next) => next, default: () => '**/*.js' }),
38
+ decision: Annotation({ reducer: (_, next) => next, default: () => '' }),
39
+ approved: Annotation({ reducer: (_, next) => next, default: () => false }),
40
+ listing: Annotation({ reducer: (_, next) => next, default: () => '' }),
41
+ })
42
+ return new StateGraph(State)
43
+ .addNode('confirm', async state => {
44
+ // Pauses the run; the value returned here is the `resume` value.
45
+ const answer = interrupt({ question: `Scan ${state.pattern} in this workspace?` })
46
+ return { decision: String(answer), approved: approvedBy(answer) }
47
+ })
48
+ .addNode('scan', async state => ({ listing: await helpers.callTool('glob', { pattern: state.pattern }) }))
49
+ .addEdge(START, 'confirm')
50
+ .addConditionalEdges('confirm', state => (state.approved ? 'scan' : END))
51
+ .addEdge('scan', END)
52
+ }