@lzn1998/dsh-langgraph 0.5.0 → 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
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Ask one question through DSH's native question UI, then report the answer.
3
+ *
4
+ * This is the human-in-the-loop path that needs no custom client: the node calls
5
+ * `helpers.askUser`, which runs the stock `ask_user_question` tool in this
6
+ * session, so the user sees the same question card as a model-asked question.
7
+ */
8
+ export const id = 'ask-user'
9
+ export const description = 'Ask the user one question in the native question UI and return the answer.'
10
+ export const input = {
11
+ type: 'object',
12
+ properties: {
13
+ question: { type: 'string', description: 'The question to put to the user.' },
14
+ options: {
15
+ type: 'array',
16
+ items: { type: 'string' },
17
+ description: 'Optional answer labels; omit for a free-text answer.',
18
+ },
19
+ multiSelect: { type: 'boolean', description: 'Allow more than one option (default false).' },
20
+ },
21
+ required: ['question'],
22
+ additionalProperties: false,
23
+ }
24
+
25
+ export function build({ StateGraph, Annotation, START, END, helpers }) {
26
+ const State = Annotation.Root({
27
+ question: Annotation({ reducer: (_left, right) => right, default: () => '' }),
28
+ options: Annotation({ reducer: (_left, right) => right, default: () => [] }),
29
+ multiSelect: Annotation({ reducer: (_left, right) => right, default: () => false }),
30
+ answer: Annotation({ reducer: (_left, right) => right, default: () => '' }),
31
+ selected: Annotation({ reducer: (_left, right) => right, default: () => [] }),
32
+ })
33
+
34
+ return new StateGraph(State)
35
+ .addNode('ask', async state => {
36
+ const options = Array.isArray(state.options) ? state.options.filter(option => typeof option === 'string') : []
37
+ const { answers } = await helpers.askUser([{
38
+ id: 'answer',
39
+ question: state.question,
40
+ ...(options.length === 0 ? {} : { options }),
41
+ multi_select: state.multiSelect === true,
42
+ }])
43
+ const reply = answers.find(answer => answer.id === 'answer')
44
+ return {
45
+ answer: reply?.custom ?? reply?.selected?.join(', ') ?? '',
46
+ selected: reply?.selected ?? [],
47
+ }
48
+ })
49
+ .addEdge(START, 'ask')
50
+ .addEdge('ask', END)
51
+ }
package/index.d.ts CHANGED
@@ -11,8 +11,8 @@
11
11
  * export function build({ StateGraph, Annotation, START, END, helpers }: GraphApi) { ... }
12
12
  * ```
13
13
  */
14
- import { Annotation, END, START, StateGraph, interrupt } from '@langchain/langgraph'
15
- import type { BaseCheckpointSaver } from '@langchain/langgraph-checkpoint'
14
+ import { Annotation, END, START, StateGraph, getStore, interrupt } from '@langchain/langgraph'
15
+ import type { BaseCheckpointSaver, BaseStore } from '@langchain/langgraph-checkpoint'
16
16
  import type { BaseChatModel } from '@langchain/core/language_models/chat_models'
17
17
 
18
18
  /** Route options accepted by the model bridges. */
@@ -47,6 +47,34 @@ export interface SubagentOptions {
47
47
  schema?: Record<string, unknown>
48
48
  }
49
49
 
50
+ /** One selectable answer offered to the user. */
51
+ export interface AskUserOption {
52
+ label: string
53
+ description?: string
54
+ }
55
+
56
+ /** One question for the native DSH question UI. */
57
+ export interface AskUserQuestion {
58
+ /** Stable id, echoed in the answer; defaults to `q1`, `q2`, … */
59
+ id?: string
60
+ question: string
61
+ header?: string
62
+ options?: Array<string | AskUserOption>
63
+ multi_select?: boolean
64
+ }
65
+
66
+ /** The user's answer to one question; empty `selected` with no `custom` means skip. */
67
+ export interface AskUserAnswer {
68
+ id: string
69
+ selected: string[]
70
+ custom?: string
71
+ }
72
+
73
+ /** The result of one `askUser` call. */
74
+ export interface AskUserResult {
75
+ answers: AskUserAnswer[]
76
+ }
77
+
50
78
  /** The result of one DSH subagent delegation. */
51
79
  export interface SubagentResult {
52
80
  /** Concatenated text blocks of the child's final output. */
@@ -86,8 +114,12 @@ export interface GraphHelpers {
86
114
  callModel(prompt: string, options?: CallModelOptions): Promise<{ text: string; usage?: unknown }>
87
115
  /** Run one DSH tool in the calling agent's scope and return its text content. */
88
116
  callTool(name: string, args?: Record<string, unknown>): Promise<string>
117
+ /** Ask the user through DSH's native question UI and wait for the answers. */
118
+ askUser(questions: AskUserQuestion[]): Promise<AskUserResult>
89
119
  /** Delegate one task to a DSH subagent and await its final output. */
90
120
  subagent(prompt: string, options?: SubagentOptions): Promise<SubagentResult>
121
+ /** The run's LangGraph long-term store; undefined when `config.store` is false. */
122
+ store(): BaseStore | undefined
91
123
  }
92
124
 
93
125
  /** The API object passed to a graph module's `build(api)`. */
@@ -97,9 +129,13 @@ export interface GraphApi {
97
129
  readonly START: typeof START
98
130
  readonly END: typeof END
99
131
  readonly interrupt: typeof interrupt
132
+ /** LangGraph's config-scoped store accessor; nodes use `getStore(config)`. */
133
+ readonly getStore: typeof getStore
100
134
  readonly helpers: GraphHelpers
101
135
  /** The durable checkpointer the plugin compiles the graph with. */
102
136
  readonly checkpointer: BaseCheckpointSaver
137
+ /** The run's long-term store; undefined when `config.store` is false. */
138
+ readonly store: BaseStore | undefined
103
139
  readonly [key: string]: unknown
104
140
  }
105
141