@lzn1998/dsh-langgraph 1.0.1 → 1.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,218 @@
1
+ /**
2
+ * Immutable, session-owned graph specs in the `langgraph_specs` domain.
3
+ *
4
+ * A composed graph is identified by a content hash of its normalized IR, so the
5
+ * same spec is idempotent and any edit produces a new id. Specs are never
6
+ * mutated: a changed graph is a new spec and a new thread, which keeps recovery
7
+ * auditable. Without a `storageDomain` a process-local store keeps the same API;
8
+ * those specs end with the Host process.
9
+ */
10
+
11
+ import { createHash } from 'node:crypto'
12
+ import { z } from 'zod'
13
+ import { assertSpec } from './schema.js'
14
+ import { stableStringify } from './template.js'
15
+
16
+ /** Prefix of a composed graph id. */
17
+ export const SPEC_PREFIX = 'lg_adhoc_'
18
+
19
+ /** Compiler version recorded with each spec, for future migrations. */
20
+ export const COMPILER_VERSION = 1
21
+
22
+ /** Per-session cap. A spec past the cap is rejected, never evicted. */
23
+ export const MAX_SPECS_PER_SESSION = 64
24
+
25
+ /** One stored spec record. */
26
+ const storedSpec = z.object({
27
+ spec: z.record(z.string(), z.unknown()),
28
+ source: z.unknown().nullable(),
29
+ sessionId: z.string().nullable(),
30
+ createdAt: z.number(),
31
+ compilerVersion: z.number(),
32
+ })
33
+
34
+ /** Declared DSH storage domain. */
35
+ export const SPEC_DOMAIN = Object.freeze({
36
+ name: 'langgraph_specs',
37
+ version: 1,
38
+ layout: 'per-record',
39
+ tables: {
40
+ specs: { valueSchema: storedSpec },
41
+ },
42
+ })
43
+
44
+ /** Whether a graph id has the composed-spec prefix. */
45
+ export function isSpecId(id) {
46
+ return typeof id === 'string' && id.startsWith(SPEC_PREFIX)
47
+ }
48
+
49
+ /**
50
+ * Content id of a spec: `lg_adhoc_` plus 24 hex of the sha256 of its normalized
51
+ * JSON. Object keys are sorted; array order is preserved; `ir` is included.
52
+ * @param {object} spec - a GraphSpec.
53
+ * @returns {string} the spec id.
54
+ */
55
+ export function specId(spec) {
56
+ const digest = createHash('sha256').update(stableStringify(spec)).digest('hex')
57
+ return `${SPEC_PREFIX}${digest.slice(0, 24)}`
58
+ }
59
+
60
+ /** Deep-copy a JSON value, so a caller cannot mutate a stored spec. */
61
+ function clone(value) {
62
+ return structuredClone(value)
63
+ }
64
+
65
+ /** A store over a table-shaped object (a DSH domain or an in-memory Map). */
66
+ export class SpecStore {
67
+ /** @param {{ get: Function, put: Function, delete: Function, entries: Function, keys: Function }} table - the specs table. */
68
+ constructor(table) {
69
+ this.specs = table
70
+ }
71
+
72
+ /** The table for tests and diagnostics. */
73
+ table() {
74
+ return this.specs
75
+ }
76
+
77
+ /** All records owned by one session, newest first. */
78
+ records(sessionId) {
79
+ const owner = sessionId ?? null
80
+ const rows = []
81
+ for (const [id, record] of this.specs.entries()) {
82
+ if (record?.sessionId !== owner) continue
83
+ rows.push({ id, record })
84
+ }
85
+ rows.sort((left, right) => right.record.createdAt - left.record.createdAt || left.id.localeCompare(right.id))
86
+ return rows
87
+ }
88
+
89
+ /**
90
+ * Save one spec. The same content is idempotent for its owner; an id owned by
91
+ * another session is a conflict, because the table key is the content id.
92
+ * @param {object} spec - a validated GraphSpec.
93
+ * @param {{ sessionId?: string, source?: unknown }} [options] - owner and audit source.
94
+ * @returns {Promise<{ id: string, created: boolean }>} the content id.
95
+ */
96
+ async save(spec, options = {}) {
97
+ assertSpec(spec)
98
+ const id = specId(spec)
99
+ const sessionId = options.sessionId ?? null
100
+ const existing = this.specs.get(id)
101
+ if (existing !== undefined) {
102
+ if ((existing.sessionId ?? null) !== sessionId) {
103
+ throw new Error(`spec "${id}" belongs to another session`)
104
+ }
105
+ return { id, created: false }
106
+ }
107
+ if (this.records(sessionId).length >= MAX_SPECS_PER_SESSION) {
108
+ throw new Error(`this session already has ${MAX_SPECS_PER_SESSION} composed graphs; delete one before composing another`)
109
+ }
110
+ await this.specs.put(id, {
111
+ spec: clone(spec),
112
+ source: options.source === undefined ? null : clone(options.source),
113
+ sessionId,
114
+ createdAt: Date.now(),
115
+ compilerVersion: COMPILER_VERSION,
116
+ })
117
+ return { id, created: true }
118
+ }
119
+
120
+ /**
121
+ * Read one record with an owner check. A record with a null owner is readable
122
+ * by any session; `allSessions` is for the owner-only Web panel, not for a
123
+ * model tool.
124
+ * @param {string} id - spec id.
125
+ * @param {string | undefined} sessionId - calling session.
126
+ * @param {{ allSessions?: boolean }} [options] - skip the session check.
127
+ * @returns {object | undefined} a cloned record.
128
+ */
129
+ getRecord(id, sessionId, options = {}) {
130
+ const record = this.specs.get(id)
131
+ if (record === undefined) return undefined
132
+ const owner = record.sessionId ?? null
133
+ if (options.allSessions !== true && owner !== null && owner !== (sessionId ?? null)) {
134
+ return undefined
135
+ }
136
+ return clone(record)
137
+ }
138
+
139
+ /**
140
+ * Read one spec with an owner check.
141
+ * @param {string} id - spec id.
142
+ * @param {string | undefined} sessionId - calling session.
143
+ * @param {{ allSessions?: boolean }} [options] - skip the session check.
144
+ * @returns {object | undefined} a cloned spec.
145
+ */
146
+ getSpec(id, sessionId, options = {}) {
147
+ return this.getRecord(id, sessionId, options)?.spec
148
+ }
149
+
150
+ /**
151
+ * List one session's specs, newest first.
152
+ * @param {string | undefined} sessionId - calling session.
153
+ * @param {{ limit?: number }} [options] - maximum rows.
154
+ * @returns {object[]} summaries.
155
+ */
156
+ listSpecs(sessionId, options = {}) {
157
+ const limit = Number.isInteger(options.limit) && options.limit > 0
158
+ ? Math.min(options.limit, MAX_SPECS_PER_SESSION)
159
+ : 20
160
+ return this.records(sessionId).slice(0, limit).map(({ id, record }) => ({
161
+ id,
162
+ ...(typeof record.spec?.name === 'string' ? { name: record.spec.name } : {}),
163
+ ...(typeof record.spec?.description === 'string' ? { description: record.spec.description } : {}),
164
+ createdAt: record.createdAt,
165
+ }))
166
+ }
167
+
168
+ /**
169
+ * Delete one spec after an owner check. Threads are checked by the compose
170
+ * tool, which can see the checkpoint saver.
171
+ * @param {string} id - spec id.
172
+ * @param {string | undefined} sessionId - calling session.
173
+ * @returns {Promise<{ deleted: boolean, reason?: string }>} what happened.
174
+ */
175
+ async deleteSpec(id, sessionId) {
176
+ const record = this.specs.get(id)
177
+ if (record === undefined) return { deleted: false, reason: 'missing' }
178
+ if ((record.sessionId ?? null) !== (sessionId ?? null)) return { deleted: false, reason: 'owner' }
179
+ await this.specs.delete(id)
180
+ return { deleted: true }
181
+ }
182
+
183
+ /** Number of specs owned by one session. */
184
+ count(sessionId) {
185
+ return this.records(sessionId).length
186
+ }
187
+ }
188
+
189
+ /** An in-memory table with the same shape as a DSH domain table. */
190
+ function memoryTable() {
191
+ const records = new Map()
192
+ return {
193
+ get: key => records.get(key),
194
+ entries: () => records.entries(),
195
+ keys: () => records.keys(),
196
+ async put(key, value) {
197
+ records.set(key, structuredClone(value))
198
+ },
199
+ async delete(key) {
200
+ return records.delete(key)
201
+ },
202
+ }
203
+ }
204
+
205
+ /** A process-local store for profiles without a storage domain. */
206
+ export function createMemorySpecStore() {
207
+ return new SpecStore(memoryTable())
208
+ }
209
+
210
+ /**
211
+ * Open the durable spec domain.
212
+ * @param {object} storageDomain - the `storageDomain` service.
213
+ * @returns {Promise<{ store: SpecStore, close: () => Promise<void> }>} the open store.
214
+ */
215
+ export async function openSpecStore(storageDomain) {
216
+ const domain = await storageDomain.open(SPEC_DOMAIN)
217
+ return { store: new SpecStore(domain.table('specs')), close: () => domain.close() }
218
+ }
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Value handling for the GraphSpec IR: state references, prompt parts and the
3
+ * small transforms that turn a node result into a typed state value.
4
+ *
5
+ * Everything here is deterministic. A state reference is exactly
6
+ * `{ "$state": "field" }` or `{ "$state": "field.path" }`; dotted paths read into
7
+ * a `json` field. Literal objects may not use the `$state` key.
8
+ */
9
+
10
+ /** Whether a value is a plain JSON object (not null, not an array). */
11
+ export function isPlainObject(value) {
12
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
13
+ }
14
+
15
+ /** Whether a value is an object carrying the reserved `$state` key. */
16
+ export function hasStateKey(value) {
17
+ return isPlainObject(value) && Object.prototype.hasOwnProperty.call(value, '$state')
18
+ }
19
+
20
+ /** Whether a value is a well-formed state reference. */
21
+ export function isStateRef(value) {
22
+ return hasStateKey(value)
23
+ && Object.keys(value).length === 1
24
+ && typeof value.$state === 'string'
25
+ && value.$state !== ''
26
+ }
27
+
28
+ /**
29
+ * Read a dotted state path. A missing path, a non-object hop, or a bad array
30
+ * index yields `undefined` instead of throwing; guards treat that as false.
31
+ * @param {object | undefined} state - the current graph state.
32
+ * @param {string} path - a field name or a dotted path into a json field.
33
+ * @returns {unknown} the value, or undefined.
34
+ */
35
+ export function readState(state, path) {
36
+ if (typeof path !== 'string' || path === '') return undefined
37
+ let current = state
38
+ for (const part of path.split('.')) {
39
+ if (current === null || current === undefined) return undefined
40
+ if (Array.isArray(current)) {
41
+ if (!/^(0|[1-9]\d*)$/.test(part)) return undefined
42
+ current = current[Number(part)]
43
+ } else if (typeof current === 'object') {
44
+ if (!Object.prototype.hasOwnProperty.call(current, part)) return undefined
45
+ current = current[part]
46
+ } else {
47
+ return undefined
48
+ }
49
+ }
50
+ return current
51
+ }
52
+
53
+ /**
54
+ * Resolve state references inside one tool argument or set value. Arrays and
55
+ * plain objects are walked recursively; everything else is returned as is.
56
+ * @param {unknown} value - a literal or a state reference.
57
+ * @param {object} state - the current graph state.
58
+ * @returns {unknown} the resolved value.
59
+ */
60
+ export function resolveValue(value, state) {
61
+ if (isStateRef(value)) return readState(state, value.$state)
62
+ if (Array.isArray(value)) return value.map(item => resolveValue(item, state))
63
+ if (isPlainObject(value)) {
64
+ const resolved = {}
65
+ for (const [key, item] of Object.entries(value)) resolved[key] = resolveValue(item, state)
66
+ return resolved
67
+ }
68
+ return value
69
+ }
70
+
71
+ /** Render one state value inside a prompt. Arrays join with newlines. */
72
+ function stringifyPart(value) {
73
+ if (value === undefined || value === null) return ''
74
+ if (typeof value === 'string') return value
75
+ if (Array.isArray(value)) {
76
+ return value
77
+ .map(item => (typeof item === 'string' ? item : JSON.stringify(item)))
78
+ .join('\n')
79
+ }
80
+ if (typeof value === 'object') return JSON.stringify(value)
81
+ return String(value)
82
+ }
83
+
84
+ /**
85
+ * Render a prompt from its parts. Parts are concatenated exactly as written, so
86
+ * `["Find files: ", { "$state": "pattern" }]` keeps its spacing.
87
+ * @param {Array<string | { $state: string }>} parts - the prompt parts.
88
+ * @param {object} state - the current graph state.
89
+ * @returns {string} the rendered prompt.
90
+ */
91
+ export function renderParts(parts, state) {
92
+ return parts
93
+ .map(part => (typeof part === 'string' ? part : stringifyPart(readState(state, part.$state))))
94
+ .join('')
95
+ }
96
+
97
+ /** Split text into lines, normalizing CRLF and dropping trailing empty lines. */
98
+ export function splitLines(text) {
99
+ const lines = String(text).replace(/\r\n/g, '\n').split('\n')
100
+ while (lines.length > 0 && lines[lines.length - 1] === '') lines.pop()
101
+ return lines
102
+ }
103
+
104
+ /**
105
+ * Parse JSON text. A fenced code block is accepted; prose around it is not,
106
+ * because the model is told to answer with JSON only.
107
+ * @param {string} text - candidate JSON.
108
+ * @returns {unknown} the parsed value.
109
+ */
110
+ export function parseJsonText(text) {
111
+ let source = String(text).trim()
112
+ if (source.startsWith('```')) {
113
+ const firstNewline = source.indexOf('\n')
114
+ const lastFence = source.lastIndexOf('```')
115
+ if (firstNewline !== -1 && lastFence > firstNewline) {
116
+ source = source.slice(firstNewline + 1, lastFence).trim()
117
+ }
118
+ }
119
+ try {
120
+ return JSON.parse(source)
121
+ } catch (error) {
122
+ throw new Error(`expected JSON: ${error?.message ?? error}`)
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Apply one IR transform to a node result.
128
+ * @param {unknown} value - the node's base value (text, resume value, array, …).
129
+ * @param {string} kind - the transform name from the IR.
130
+ * @returns {unknown} the transformed value.
131
+ */
132
+ export function transform(value, kind) {
133
+ switch (kind) {
134
+ case 'text':
135
+ if (value === undefined || value === null) return ''
136
+ return typeof value === 'string' ? value.trim() : String(value)
137
+ case 'lines':
138
+ if (Array.isArray(value)) return value.map(item => (typeof item === 'string' ? item : String(item)))
139
+ return splitLines(value)
140
+ case 'json':
141
+ if (typeof value === 'string') return parseJsonText(value)
142
+ if (isJsonValue(value)) return value
143
+ throw new Error('cannot read JSON from a non-JSON value')
144
+ case 'bool': {
145
+ if (typeof value === 'boolean') return value
146
+ if (typeof value === 'string') {
147
+ const text = value.trim().toLowerCase()
148
+ if (text === 'true') return true
149
+ if (text === 'false') return false
150
+ }
151
+ throw new Error('expected a boolean or the text "true"/"false"')
152
+ }
153
+ case 'number': {
154
+ if (typeof value === 'number' && Number.isFinite(value)) return value
155
+ if (typeof value === 'string' && value.trim() !== '') {
156
+ const number = Number(value.trim())
157
+ if (Number.isFinite(number)) return number
158
+ }
159
+ throw new Error('expected a finite number')
160
+ }
161
+ case 'first': {
162
+ const lines = Array.isArray(value)
163
+ ? value
164
+ : typeof value === 'string' ? splitLines(value) : undefined
165
+ if (lines === undefined) throw new Error('expected text or an array')
166
+ if (lines.length === 0) throw new Error('cannot take the first item of an empty value')
167
+ return typeof lines[0] === 'string' ? lines[0] : String(lines[0])
168
+ }
169
+ case 'count':
170
+ if (Array.isArray(value)) return value.length
171
+ if (typeof value === 'string') return splitLines(value).length
172
+ throw new Error('expected text or an array')
173
+ default:
174
+ throw new Error(`unknown transform "${kind}"`)
175
+ }
176
+ }
177
+
178
+ /** Text of the last message a prebuilt agent returned. */
179
+ export function messageText(message) {
180
+ const content = message?.content
181
+ if (typeof content === 'string') return content
182
+ if (Array.isArray(content)) {
183
+ return content
184
+ .map(part => {
185
+ if (typeof part === 'string') return part
186
+ if (typeof part?.text === 'string') return part.text
187
+ return ''
188
+ })
189
+ .join('')
190
+ }
191
+ if (content === undefined || content === null) return ''
192
+ return String(content)
193
+ }
194
+
195
+ /** JSON kind of a value, or undefined when it is not JSON. */
196
+ export function jsonKind(value) {
197
+ if (value === null) return 'null'
198
+ if (Array.isArray(value)) return 'array'
199
+ const type = typeof value
200
+ if (type === 'string' || type === 'boolean') return type
201
+ if (type === 'number') return Number.isFinite(value) ? 'number' : undefined
202
+ if (type === 'object') return 'object'
203
+ return undefined
204
+ }
205
+
206
+ /** Whether a value is a JSON value (finite numbers only, no cycles). */
207
+ export function isJsonValue(value, stack = new Set()) {
208
+ const kind = jsonKind(value)
209
+ if (kind === undefined) return false
210
+ if (kind !== 'array' && kind !== 'object') return true
211
+ if (stack.has(value)) return false
212
+ stack.add(value)
213
+ const values = kind === 'array' ? value : Object.values(value)
214
+ const ok = values.every(item => isJsonValue(item, stack))
215
+ stack.delete(value)
216
+ return ok
217
+ }
218
+
219
+ /** Whether a literal matches one declared state type. */
220
+ export function matchesStateType(value, type) {
221
+ switch (type) {
222
+ case 'string':
223
+ return typeof value === 'string'
224
+ case 'number':
225
+ return typeof value === 'number' && Number.isFinite(value)
226
+ case 'boolean':
227
+ return typeof value === 'boolean'
228
+ case 'json':
229
+ return isJsonValue(value)
230
+ case 'string[]':
231
+ return Array.isArray(value) && value.every(item => typeof item === 'string')
232
+ case 'number[]':
233
+ return Array.isArray(value) && value.every(item => typeof item === 'number' && Number.isFinite(item))
234
+ default:
235
+ return false
236
+ }
237
+ }
238
+
239
+ /** Deep equality over JSON values. */
240
+ export function deepEqual(left, right) {
241
+ if (left === right) return true
242
+ if (typeof left !== typeof right) return false
243
+ if (left === null || right === null || typeof left !== 'object') return false
244
+ if (Array.isArray(left) !== Array.isArray(right)) return false
245
+ if (Array.isArray(left)) {
246
+ return left.length === right.length && left.every((item, index) => deepEqual(item, right[index]))
247
+ }
248
+ const leftKeys = Object.keys(left)
249
+ const rightKeys = Object.keys(right)
250
+ return leftKeys.length === rightKeys.length
251
+ && leftKeys.every(key => Object.prototype.hasOwnProperty.call(right, key) && deepEqual(left[key], right[key]))
252
+ }
253
+
254
+ /** JSON with object keys sorted, so equal specs produce equal text. */
255
+ export function stableStringify(value) {
256
+ if (value === null || typeof value !== 'object') return JSON.stringify(value)
257
+ if (Array.isArray(value)) return `[${value.map(item => stableStringify(item)).join(',')}]`
258
+ const keys = Object.keys(value).sort()
259
+ return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`
260
+ }