@lzn1998/dsh-langgraph 0.0.0-stage → 0.5.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.
@@ -0,0 +1,520 @@
1
+ /**
2
+ * Durable LangGraph checkpoints over the DSH `storageDomain` service.
3
+ *
4
+ * LangGraph's own `MemorySaver` keeps threads in process memory, so a run is lost
5
+ * with the Host process. This saver stores the same data — one record per checkpoint,
6
+ * one record per checkpoint's pending writes — in a schema-validated DSH storage
7
+ * domain, which is the sanctioned place for plugin-owned durable data. Reads are
8
+ * synchronous from the domain's validated in-memory state; every write is durable
9
+ * before it resolves.
10
+ *
11
+ * Values are serialized with the saver's own `serde` (LangChain's `JsonPlusSerializer`)
12
+ * and kept as base64 so LangChain classes such as messages survive the round trip;
13
+ * only the record envelopes are plain JSON.
14
+ * @module dsh-langgraph/checkpointer
15
+ */
16
+
17
+ import {
18
+ BaseCheckpointSaver,
19
+ WRITES_IDX_MAP,
20
+ compareWritesSortKeys,
21
+ copyCheckpoint,
22
+ writesSortKey,
23
+ } from '@langchain/langgraph-checkpoint'
24
+ import { z } from 'zod'
25
+
26
+ /** Keys that mutate `Object.prototype` when assigned through bracket notation. */
27
+ const POLLUTION_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
28
+
29
+ /** One serialized value: LangChain's serialization tag plus base64 payload. */
30
+ const encodedValue = z.object({ type: z.string(), data: z.string() })
31
+
32
+ /**
33
+ * Declared storage domain. `per-record` keeps each checkpoint and write-set its own
34
+ * document, so a superstep rewrites only what it changed.
35
+ * @type {Readonly<{ name: string, version: number, layout: 'per-record', tables: Record<string, { valueSchema: import('zod').ZodType }> }>}
36
+ */
37
+ export const DOMAIN = Object.freeze({
38
+ name: 'langgraph_checkpoints',
39
+ version: 1,
40
+ layout: 'per-record',
41
+ tables: {
42
+ checkpoints: {
43
+ valueSchema: z.object({
44
+ checkpoint: encodedValue,
45
+ metadata: encodedValue,
46
+ parent: z.string().nullable(),
47
+ createdAt: z.number(),
48
+ }),
49
+ },
50
+ writes: {
51
+ valueSchema: z.object({
52
+ entries: z.array(z.object({
53
+ taskPath: z.string(),
54
+ taskId: z.string(),
55
+ idx: z.number(),
56
+ channel: z.string(),
57
+ value: encodedValue,
58
+ })),
59
+ }),
60
+ },
61
+ threads: {
62
+ valueSchema: z.object({
63
+ graph: z.string().nullable(),
64
+ sessionId: z.string().nullable(),
65
+ createdAt: z.number(),
66
+ updatedAt: z.number(),
67
+ checkpoints: z.number(),
68
+ writes: z.number(),
69
+ }),
70
+ },
71
+ },
72
+ })
73
+
74
+ /**
75
+ * Reject a value that is unsafe as a storage key.
76
+ * @param {string} field - configurable field name, for the message.
77
+ * @param {unknown} value - candidate key.
78
+ * @param {{ allowEmpty?: boolean }} [options] - whether the empty string is permitted.
79
+ */
80
+ function assertSafeKey(field, value, options = {}) {
81
+ if (typeof value !== 'string') {
82
+ throw new Error(`checkpointer: configurable "${field}" must be a string, got ${value === null ? 'null' : typeof value}`)
83
+ }
84
+ if (options.allowEmpty !== true && value === '') {
85
+ throw new Error(`checkpointer: configurable "${field}" must not be the empty string`)
86
+ }
87
+ if (POLLUTION_KEYS.has(value)) {
88
+ throw new Error(`checkpointer: configurable "${field}" uses the reserved value "${value}"`)
89
+ }
90
+ }
91
+
92
+ /** @param {Uint8Array} bytes - serialized bytes. @returns {string} base64 text. */
93
+ function toBase64(bytes) {
94
+ return Buffer.from(bytes).toString('base64')
95
+ }
96
+
97
+ /** @param {string} text - base64 text. @returns {Uint8Array} serialized bytes. */
98
+ function fromBase64(text) {
99
+ return new Uint8Array(Buffer.from(text, 'base64'))
100
+ }
101
+
102
+ /**
103
+ * Record keys must be path-safe for the per-record layout (JSON documents, one file
104
+ * per record), so a key is the base64url of its JSON parts rather than raw JSON.
105
+ * @param {string[]} parts - the key components.
106
+ * @returns {string} a key matching `[A-Za-z0-9_-]+`.
107
+ */
108
+ function encodeKey(parts) {
109
+ return Buffer.from(JSON.stringify(parts), 'utf8').toString('base64url')
110
+ }
111
+
112
+ /**
113
+ * Read back the parts of one record key. A key this saver did not write decodes to
114
+ * something that is not a parts array, and callers treat that as a foreign record.
115
+ * @param {string} key - the record key.
116
+ * @returns {string[]} the key components.
117
+ */
118
+ function decodeKey(key) {
119
+ const parsed = JSON.parse(Buffer.from(key, 'base64url').toString('utf8'))
120
+ if (!Array.isArray(parsed) || parsed.some(part => typeof part !== 'string')) {
121
+ throw new Error('not a checkpoint key')
122
+ }
123
+ return parsed
124
+ }
125
+
126
+ /** @param {string} thread - thread id. @param {string} ns - checkpoint namespace. @param {string} id - checkpoint id. */
127
+ function checkpointKey(thread, ns, id) {
128
+ return encodeKey(['c', thread, ns, id])
129
+ }
130
+
131
+ /** @param {string} key - a checkpoint record key. @returns {[string, string, string]} thread, namespace, id. */
132
+ function parseCheckpointKey(key) {
133
+ const parsed = decodeKey(key)
134
+ if (parsed.length !== 4 || parsed[0] !== 'c') throw new Error('not a checkpoint key')
135
+ return [parsed[1], parsed[2], parsed[3]]
136
+ }
137
+
138
+ /** @param {string} thread - thread id. @param {string} ns - checkpoint namespace. @param {string} id - checkpoint id. */
139
+ function writesKey(thread, ns, id) {
140
+ return encodeKey(['w', thread, ns, id])
141
+ }
142
+
143
+ /** @param {string} key - a writes record key. @returns {[string, string, string]} thread, namespace, id. */
144
+ function parseWritesKey(key) {
145
+ const parsed = decodeKey(key)
146
+ if (parsed.length !== 4 || parsed[0] !== 'w') throw new Error('not a writes key')
147
+ return [parsed[1], parsed[2], parsed[3]]
148
+ }
149
+
150
+ /** @param {string} thread - thread id. @returns {string} its record key. */
151
+ function threadKey(thread) {
152
+ return encodeKey(['t', thread])
153
+ }
154
+
155
+ /** @param {string} key - a thread record key. @returns {string} the thread id. */
156
+ function parseThreadKey(key) {
157
+ const parsed = decodeKey(key)
158
+ if (parsed.length !== 2 || parsed[0] !== 't') throw new Error('not a thread key')
159
+ return parsed[1]
160
+ }
161
+
162
+ /**
163
+ * A `BaseCheckpointSaver` whose threads live in a DSH storage domain.
164
+ *
165
+ * It also keeps the small amount of thread bookkeeping a run tool needs — which graph
166
+ * and session a thread belongs to, and how much it holds — so listing threads does not
167
+ * have to read every checkpoint.
168
+ */
169
+ export class DshCheckpointSaver extends BaseCheckpointSaver {
170
+ /**
171
+ * @param {object} domain - an open storage domain shaped by {@link DOMAIN}.
172
+ */
173
+ constructor(domain) {
174
+ super()
175
+ /** @type {object} */
176
+ this.domain = domain
177
+ }
178
+
179
+ /** @param {'checkpoints' | 'writes' | 'threads'} table - table name. @returns {any} the table handle. */
180
+ table(table) {
181
+ return this.domain.table(table)
182
+ }
183
+
184
+ /**
185
+ * Serialize one value for storage.
186
+ * @param {unknown} value - value to store.
187
+ * @returns {Promise<{ type: string, data: string }>} the encoded value.
188
+ */
189
+ async encode(value) {
190
+ const [type, bytes] = await this.serde.dumpsTyped(value)
191
+ return { type, data: toBase64(bytes) }
192
+ }
193
+
194
+ /**
195
+ * Deserialize one stored value.
196
+ * @param {{ type: string, data: string }} encoded - the encoded value.
197
+ * @returns {Promise<unknown>} the value.
198
+ */
199
+ async decode(encoded) {
200
+ return await this.serde.loadsTyped(encoded.type, fromBase64(encoded.data))
201
+ }
202
+
203
+ /**
204
+ * Read the pending writes of one checkpoint, in the order live execution applies them.
205
+ * @param {string} thread - thread id.
206
+ * @param {string} ns - checkpoint namespace.
207
+ * @param {string} id - checkpoint id.
208
+ * @returns {Promise<Array<[string, string, unknown]>>} `[taskId, channel, value]`, sorted.
209
+ */
210
+ async pendingWrites(thread, ns, id) {
211
+ const record = this.table('writes').get(writesKey(thread, ns, id))
212
+ if (record === undefined) return []
213
+ const ordered = [...record.entries].sort((left, right) => compareWritesSortKeys(
214
+ writesSortKey(left.taskPath, left.taskId, left.idx),
215
+ writesSortKey(right.taskPath, right.taskId, right.idx),
216
+ ))
217
+ return await Promise.all(ordered.map(async entry => [entry.taskId, entry.channel, await this.decode(entry.value)]))
218
+ }
219
+
220
+ /**
221
+ * Build one checkpoint tuple from its stored record.
222
+ * @param {string} thread - thread id.
223
+ * @param {string} ns - checkpoint namespace.
224
+ * @param {string} id - checkpoint id.
225
+ * @param {{ checkpoint: object, metadata: object, parent: string | null }} record - stored record.
226
+ * @returns {Promise<object>} the `CheckpointTuple`.
227
+ */
228
+ async tuple(thread, ns, id, record) {
229
+ const checkpoint = await this.decode(record.checkpoint)
230
+ const tuple = {
231
+ config: { configurable: { thread_id: thread, checkpoint_ns: ns, checkpoint_id: id } },
232
+ checkpoint,
233
+ metadata: await this.decode(record.metadata),
234
+ pendingWrites: await this.pendingWrites(thread, ns, id),
235
+ }
236
+ if (record.parent !== null) {
237
+ tuple.parentConfig = { configurable: { thread_id: thread, checkpoint_ns: ns, checkpoint_id: record.parent } }
238
+ }
239
+ return tuple
240
+ }
241
+
242
+ /**
243
+ * The newest checkpoint of one thread and namespace.
244
+ * @param {string} thread - thread id.
245
+ * @param {string} ns - checkpoint namespace.
246
+ * @returns {{ id: string, record: object } | undefined} the newest checkpoint.
247
+ */
248
+ latest(thread, ns) {
249
+ let best
250
+ for (const [key, record] of this.table('checkpoints').entries()) {
251
+ let parsed
252
+ try {
253
+ parsed = parseCheckpointKey(key)
254
+ } catch {
255
+ continue
256
+ }
257
+ if (parsed[0] !== thread || parsed[1] !== ns) continue
258
+ if (best === undefined || parsed[2] > best.id) best = { id: parsed[2], record }
259
+ }
260
+ return best
261
+ }
262
+
263
+ /** @param {import('@langchain/core/runnables').RunnableConfig} config - a runnable config. */
264
+ async getTuple(config) {
265
+ const thread = config.configurable?.thread_id
266
+ const ns = config.configurable?.checkpoint_ns ?? ''
267
+ assertSafeKey('checkpoint_ns', ns, { allowEmpty: true })
268
+ if (thread === undefined) return undefined
269
+ assertSafeKey('thread_id', thread)
270
+ const requested = config.configurable?.checkpoint_id
271
+ if (typeof requested === 'string' && requested !== '') {
272
+ assertSafeKey('checkpoint_id', requested)
273
+ const record = this.table('checkpoints').get(checkpointKey(thread, ns, requested))
274
+ return record === undefined ? undefined : await this.tuple(thread, ns, requested, record)
275
+ }
276
+ const newest = this.latest(thread, ns)
277
+ return newest === undefined ? undefined : await this.tuple(thread, ns, newest.id, newest.record)
278
+ }
279
+
280
+ /**
281
+ * Yield stored checkpoints newest first, honoring the standard list options.
282
+ * @param {import('@langchain/core/runnables').RunnableConfig} config - a runnable config.
283
+ * @param {{ limit?: number, before?: object, filter?: Record<string, unknown> }} [options] - paging and filter.
284
+ */
285
+ async *list(config, options = {}) {
286
+ const wantedThread = config.configurable?.thread_id
287
+ const wantedNs = config.configurable?.checkpoint_ns
288
+ const wantedId = config.configurable?.checkpoint_id
289
+ const before = options.before?.configurable?.checkpoint_id
290
+ let limit = options.limit
291
+ const rows = []
292
+ for (const [key, record] of this.table('checkpoints').entries()) {
293
+ let thread, ns, id
294
+ try {
295
+ [thread, ns, id] = parseCheckpointKey(key)
296
+ } catch {
297
+ continue
298
+ }
299
+ if (wantedThread !== undefined && thread !== wantedThread) continue
300
+ if (wantedNs !== undefined && ns !== wantedNs) continue
301
+ if (wantedId !== undefined && id !== wantedId) continue
302
+ if (before !== undefined && id >= before) continue
303
+ rows.push([thread, ns, id, record])
304
+ }
305
+ rows.sort((left, right) => (left[2] < right[2] ? 1 : left[2] > right[2] ? -1 : 0))
306
+ for (const [thread, ns, id, record] of rows) {
307
+ if (limit !== undefined && limit <= 0) break
308
+ const tuple = await this.tuple(thread, ns, id, record)
309
+ if (options.filter !== undefined && !Object.entries(options.filter).every(([key, value]) => tuple.metadata?.[key] === value)) continue
310
+ if (limit !== undefined) limit -= 1
311
+ yield tuple
312
+ }
313
+ }
314
+
315
+ /** @param {object} config - a runnable config. @param {object} checkpoint - the checkpoint. @param {object} metadata - checkpoint metadata. */
316
+ async put(config, checkpoint, metadata) {
317
+ const thread = config.configurable?.thread_id
318
+ const ns = config.configurable?.checkpoint_ns ?? ''
319
+ if (thread === undefined) {
320
+ throw new Error('checkpointer: put needs a "thread_id" in config.configurable')
321
+ }
322
+ assertSafeKey('thread_id', thread)
323
+ assertSafeKey('checkpoint_ns', ns, { allowEmpty: true })
324
+ assertSafeKey('checkpoint_id', checkpoint.id)
325
+ const prepared = copyCheckpoint(checkpoint)
326
+ const [encodedCheckpoint, encodedMetadata] = await Promise.all([this.encode(prepared), this.encode(metadata ?? {})])
327
+ const parent = config.configurable?.checkpoint_id
328
+ await this.table('checkpoints').put(checkpointKey(thread, ns, checkpoint.id), {
329
+ checkpoint: encodedCheckpoint,
330
+ metadata: encodedMetadata,
331
+ parent: typeof parent === 'string' && parent !== '' ? parent : null,
332
+ createdAt: Date.now(),
333
+ })
334
+ await this.touchThread(thread, 'checkpoints')
335
+ return { configurable: { thread_id: thread, checkpoint_ns: ns, checkpoint_id: checkpoint.id } }
336
+ }
337
+
338
+ /** @param {object} config - a runnable config. @param {Array<[string, unknown]>} writes - channel writes. @param {string} taskId - the writing task. @param {string} [taskPath] - the task path. */
339
+ async putWrites(config, writes, taskId, taskPath) {
340
+ const thread = config.configurable?.thread_id
341
+ const ns = config.configurable?.checkpoint_ns ?? ''
342
+ const id = config.configurable?.checkpoint_id
343
+ if (thread === undefined) {
344
+ throw new Error('checkpointer: putWrites needs a "thread_id" in config.configurable')
345
+ }
346
+ if (id === undefined) {
347
+ throw new Error('checkpointer: putWrites needs a "checkpoint_id" in config.configurable')
348
+ }
349
+ assertSafeKey('thread_id', thread)
350
+ assertSafeKey('checkpoint_ns', ns, { allowEmpty: true })
351
+ assertSafeKey('checkpoint_id', id)
352
+ assertSafeKey('task_id', taskId)
353
+ const key = writesKey(thread, ns, id)
354
+ const path = taskPath ?? ''
355
+ const incoming = await Promise.all(writes.map(async ([channel, value], index) => ({
356
+ taskPath: path,
357
+ taskId,
358
+ idx: WRITES_IDX_MAP[channel] ?? index,
359
+ channel,
360
+ value: await this.encode(value),
361
+ })))
362
+ const table = this.table('writes')
363
+ const existing = table.get(key)
364
+ if (existing === undefined) {
365
+ await table.put(key, { entries: incoming })
366
+ } else {
367
+ await table.update(key, current => {
368
+ const merged = new Map(current.entries.map(entry => [`${entry.taskId},${entry.idx}`, entry]))
369
+ for (const entry of incoming) {
370
+ // A reserved index (error, scheduled, interrupt, resume) may be rewritten;
371
+ // a regular index belongs to the first write that claimed it.
372
+ if (entry.idx >= 0 && merged.has(`${entry.taskId},${entry.idx}`)) continue
373
+ merged.set(`${entry.taskId},${entry.idx}`, entry)
374
+ }
375
+ return { entries: [...merged.values()] }
376
+ })
377
+ }
378
+ await this.touchThread(thread, 'writes')
379
+ }
380
+
381
+ /** @param {string} thread - thread id to erase. */
382
+ async deleteThread(thread) {
383
+ assertSafeKey('thread_id', thread)
384
+ await this.forgetThreadRecords(thread)
385
+ }
386
+
387
+ /**
388
+ * Remove every checkpoint, write set, and thread record of one thread.
389
+ * @param {string} thread - thread id.
390
+ */
391
+ async forgetThreadRecords(thread) {
392
+ const checkpointKeys = []
393
+ for (const key of this.table('checkpoints').keys()) {
394
+ try {
395
+ if (parseCheckpointKey(key)[0] === thread) checkpointKeys.push(key)
396
+ } catch { /* not one of ours */ }
397
+ }
398
+ const writeKeys = []
399
+ for (const key of this.table('writes').keys()) {
400
+ try {
401
+ if (parseWritesKey(key)[0] === thread) writeKeys.push(key)
402
+ } catch { /* not one of ours */ }
403
+ }
404
+ if (checkpointKeys.length > 0) await this.table('checkpoints').deleteMany(checkpointKeys)
405
+ if (writeKeys.length > 0) await this.table('writes').deleteMany(writeKeys)
406
+ await this.table('threads').delete(threadKey(thread))
407
+ }
408
+
409
+ /**
410
+ * Record which graph and session own a thread, creating the record when absent.
411
+ * @param {string} thread - thread id.
412
+ * @param {{ graph: string, sessionId?: string }} meta - owner facts.
413
+ */
414
+ async claimThread(thread, meta) {
415
+ assertSafeKey('thread_id', thread)
416
+ const table = this.table('threads')
417
+ const now = Date.now()
418
+ const key = threadKey(thread)
419
+ const existing = table.get(key)
420
+ if (existing === undefined) {
421
+ await table.put(key, {
422
+ graph: meta.graph,
423
+ sessionId: meta.sessionId ?? null,
424
+ createdAt: now,
425
+ updatedAt: now,
426
+ checkpoints: 0,
427
+ writes: 0,
428
+ })
429
+ return
430
+ }
431
+ if (existing.sessionId !== null && meta.sessionId !== undefined && existing.sessionId !== meta.sessionId) {
432
+ throw new Error(`thread "${thread}" belongs to another session`)
433
+ }
434
+ if (existing.graph !== null && existing.graph !== meta.graph) {
435
+ throw new Error(`thread "${thread}" belongs to graph "${existing.graph}", not "${meta.graph}"`)
436
+ }
437
+ await table.update(key, current => ({
438
+ ...current,
439
+ graph: meta.graph,
440
+ sessionId: meta.sessionId ?? current.sessionId,
441
+ updatedAt: now,
442
+ }))
443
+ }
444
+
445
+ /**
446
+ * Bump the counters and timestamp of one thread record.
447
+ * @param {string} thread - thread id.
448
+ * @param {'checkpoints' | 'writes'} field - counter to increment.
449
+ */
450
+ async touchThread(thread, field) {
451
+ const table = this.table('threads')
452
+ const now = Date.now()
453
+ const key = threadKey(thread)
454
+ const existing = table.get(key)
455
+ if (existing === undefined) {
456
+ await table.put(key, {
457
+ graph: null,
458
+ sessionId: null,
459
+ createdAt: now,
460
+ updatedAt: now,
461
+ checkpoints: field === 'checkpoints' ? 1 : 0,
462
+ writes: field === 'writes' ? 1 : 0,
463
+ })
464
+ return
465
+ }
466
+ await table.update(key, current => ({ ...current, updatedAt: now, [field]: current[field] + 1 }))
467
+ }
468
+
469
+ /**
470
+ * List known threads, newest first.
471
+ * @param {{ sessionId?: string, graph?: string, limit?: number }} [options] - filters.
472
+ * @returns {Array<{ thread: string, graph: string | null, sessionId: string | null, createdAt: number, updatedAt: number, checkpoints: number, writes: number }>} threads.
473
+ */
474
+ listThreads(options = {}) {
475
+ const rows = []
476
+ for (const [key, record] of this.table('threads').entries()) {
477
+ let thread
478
+ try {
479
+ thread = parseThreadKey(key)
480
+ } catch {
481
+ continue
482
+ }
483
+ if (options.sessionId !== undefined && record.sessionId !== options.sessionId) continue
484
+ if (options.graph !== undefined && record.graph !== options.graph) continue
485
+ rows.push({ thread, ...record })
486
+ }
487
+ rows.sort((left, right) => right.updatedAt - left.updatedAt)
488
+ return options.limit === undefined ? rows : rows.slice(0, options.limit)
489
+ }
490
+
491
+ /**
492
+ * Whether one thread holds at least one checkpoint.
493
+ * @param {string} thread - thread id.
494
+ * @returns {boolean} true when the thread can be continued.
495
+ */
496
+ hasThread(thread) {
497
+ return this.table('threads').get(threadKey(thread)) !== undefined
498
+ }
499
+
500
+ /**
501
+ * Read one thread's ownership and counters.
502
+ * @param {string} thread - thread id.
503
+ * @returns {object | undefined} the thread record, or undefined.
504
+ */
505
+ threadMeta(thread) {
506
+ assertSafeKey('thread_id', thread)
507
+ return this.table('threads').get(threadKey(thread))
508
+ }
509
+ }
510
+
511
+ /**
512
+ * Open the checkpoint domain.
513
+ * @param {object} storageDomain - the `storageDomain` service.
514
+ * @returns {Promise<{ saver: DshCheckpointSaver, close: () => Promise<void> }>} the open store.
515
+ */
516
+ export async function openCheckpointStore(storageDomain) {
517
+ const domain = await storageDomain.open(DOMAIN)
518
+ const saver = new DshCheckpointSaver(domain)
519
+ return { saver, close: () => domain.close() }
520
+ }
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
+ }