@restregular/dsh-memory 0.4.1 → 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.
@@ -1,224 +1,373 @@
1
- /**
2
- * Tool implementations as plain data + functions. Keeping them free of both
3
- * cordis and dsh-tools imports lets us unit-test the exact argument/response
4
- * contracts standalone; the DSH entry (apply.ts) wraps them with defineTool.
5
- */
6
-
7
-
8
- /** Shape each tool shares: JSON-schema parameters + canonical output value. */
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
- export class MemoryToolError extends Error {
24
- code
25
-
26
- constructor(code , message ) {
27
- super(message)
28
- this.code = code
29
- }
30
- }
31
-
32
- function svc(opts ) {
33
- const s = opts.getService()
34
- if (!s) throw new MemoryToolError('SERVICE_UNAVAILABLE', 'memory service is not loaded; check that dsh-memory-local is enabled')
35
- return s
36
- }
37
-
38
- function scopeOr(opts , scope ) {
39
- if (scope === 'global') return 'global'
40
- if (typeof scope === 'string' && scope.startsWith('project:')) return scope
41
- if (scope === 'project') return opts.defaultScope()
42
- return opts.defaultScope()
43
- }
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
-
53
-
54
-
55
-
56
-
57
-
58
-
59
-
60
- export function memorySaveTool(opts ) {
61
- return {
62
- name: 'memory_save',
63
- description: 'Save a durable memory (fact, decision, preference, procedure) for future sessions.',
64
- parameters: {
65
- content: { type: 'string', description: 'Self-contained declarative sentence, readable without context', required: true },
66
- scope: { type: 'string', enum: ['global', 'project'], description: 'global = all projects; project = current workspace' },
67
- kind: { type: 'string', enum: ['fact', 'decision', 'preference', 'procedure', 'note'] },
68
- tags: { type: 'array', items: { type: 'string' } },
69
- importance: { type: 'number', description: '0~1, higher = more important' },
70
- supersedes: { type: 'string', description: 'Record id this corrects/replaces' },
71
- },
72
- async execute(args ) {
73
- if (typeof args.content !== 'string' || args.content.trim().length === 0) {
74
- throw new MemoryToolError('CONTENT_EMPTY', 'content must be a non-empty string')
75
- }
76
- if (args.importance !== undefined && (args.importance < 0 || args.importance > 1)) {
77
- throw new MemoryToolError('IMPORTANCE_RANGE', 'importance must be between 0 and 1')
78
- }
79
- const record = await svc(opts).save({
80
- scope: scopeOr(opts, args.scope),
81
- kind: args.kind ?? 'note',
82
- content: args.content.trim(),
83
- ...(args.tags ? { tags: args.tags } : {}),
84
- ...(args.importance !== undefined ? { importance: args.importance } : {}),
85
- ...(args.supersedes ? { supersedes: args.supersedes } : {}),
86
- source: { origin: 'explicit' },
87
- })
88
- return { id: record.id, scope: record.scope, deduped: false }
89
- },
90
- }
91
- }
92
-
93
-
94
-
95
-
96
-
97
-
98
-
99
-
100
-
101
-
102
-
103
-
104
-
105
-
106
-
107
-
108
-
109
-
110
-
111
-
112
- export function memorySearchTool(opts ) {
113
- return {
114
- name: 'memory_search',
115
- description: 'Search saved memories by keyword or meaning (lexical + local vector recall).',
116
- parameters: {
117
- query: { type: 'string', required: true },
118
- scope: { type: 'string', enum: ['global', 'project'] },
119
- topK: { type: 'number', description: '1~20' },
120
- },
121
- async execute(args ) {
122
- if (typeof args.query !== 'string' || args.query.trim().length === 0) {
123
- throw new MemoryToolError('QUERY_EMPTY', 'query must be a non-empty string')
124
- }
125
- const hits = await svc(opts).search({
126
- text: args.query,
127
- ...(args.scope ? { scope: scopeOr(opts, args.scope) } : {}),
128
- ...(args.topK !== undefined ? { topK: args.topK } : {}),
129
- })
130
- return {
131
- records: hits.map((h) => ({
132
- id: h.record.id,
133
- score: h.score,
134
- scope: h.record.scope,
135
- kind: h.record.kind,
136
- updatedAt: h.record.updatedAt,
137
- content: h.record.content,
138
- })),
139
- }
140
- },
141
- }
142
- }
143
-
144
-
145
-
146
-
147
-
148
-
149
-
150
-
151
-
152
-
153
-
154
-
155
- export function memoryForgetTool(opts ) {
156
- return {
157
- name: 'memory_forget',
158
- description: 'Delete a memory by id, or all memories matching a query in one scope.',
159
- parameters: {
160
- id: { type: 'string', description: 'Exact record id' },
161
- query: { type: 'string', description: 'Substring match within one scope' },
162
- scope: { type: 'string', enum: ['global', 'project'] },
163
- },
164
- async execute(args ) {
165
- if (!args.id && !args.query) throw new MemoryToolError('TARGET_REQUIRED', 'provide id or query')
166
- if (args.id && args.query) throw new MemoryToolError('TARGET_AMBIGUOUS', 'provide id or query, not both')
167
- return svc(opts).forget({
168
- ...(args.id ? { id: args.id } : {}),
169
- ...(args.query ? { query: args.query } : {}),
170
- ...(args.scope ? { scope: scopeOr(opts, args.scope) } : {}),
171
- })
172
- },
173
- }
174
- }
175
-
176
-
177
-
178
-
179
-
180
-
181
-
182
-
183
-
184
-
185
-
186
- export function memoryListTool(opts ) {
187
- return {
188
- name: 'memory_list',
189
- description: 'List saved memories, most recently updated first.',
190
- parameters: {
191
- scope: { type: 'string', enum: ['global', 'project'] },
192
- kind: { type: 'string' },
193
- limit: { type: 'number', description: '1~200' },
194
- },
195
- async execute(args ) {
196
- const records = await svc(opts).list({
197
- ...(args.scope ? { scope: scopeOr(opts, args.scope) } : {}),
198
- ...(args.kind ? { kind: args.kind } : {}),
199
- ...(args.limit !== undefined ? { limit: args.limit } : {}),
200
- })
201
- return {
202
- records: records.map((r) => ({
203
- id: r.id,
204
- scope: r.scope,
205
- kind: r.kind,
206
- updatedAt: r.updatedAt,
207
- content: r.content,
208
- })),
209
- }
210
- },
211
- }
212
- }
213
-
214
- export function memoryTools(opts ) {
215
- return {
216
- memory_save: memorySaveTool(opts),
217
- memory_search: memorySearchTool(opts),
218
- memory_forget: memoryForgetTool(opts),
219
- memory_list: memoryListTool(opts),
220
- }
221
- }
1
+ /**
2
+ * Tool implementations as plain data + functions. Keeping them free of both
3
+ * cordis and dsh-tools imports lets us unit-test the exact argument/response
4
+ * contracts standalone; the DSH entry (apply.ts) wraps them with defineTool.
5
+ *
6
+ * scope 语义(0.5.0 起):
7
+ * - 省略 scope:写 → 当前会话;读 → 会话 + 项目 + global 三路合并(provider 决定具体键);
8
+ * - 'global' / 'project' / 任意自定义名 / 'session:<id>' / 'project:<path>' 都是显式 pin;
9
+ * - 'all'(或 '*')只对读路径有效,写路径报 SCOPE_NOT_WRITABLE。
10
+ * 解析全部交给 `memory-local/scope.ts` 的 normalizeScopeInput + provider 的
11
+ * resolveReadScopes/resolveWriteScope —— 这里**不再**有任何"smoothing over"式的静默回退。
12
+ */
13
+
14
+ import { normalizeScopeInput, resolveScopeRef } from '../provider/scope.js'
15
+
16
+ /** Shape each tool shares: JSON-schema parameters + canonical output value. */
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+ /** 只有这一层需要的能力子集(provider 在宿主里提供,测试里可以 mock)。 */
25
+
26
+
27
+
28
+
29
+
30
+                 
31
+
32
+                         
33
+
34
+                     
35
+
36
+                
37
+
38
+
39
+
40
+
41
+
42
+
43
+             
44
+
45
+             
46
+
47
+
48
+
49
+ const SCOPE_DESCRIPTION =
50
+ "省略=当前会话;'global'=所有项目共享;'project'=当前工作区;其他任意名称=自定义作用域"
51
+ + "(memory_save 时不存在则自动创建)。读取时可用 'all' 跨所有作用域。"
52
+
53
+ export class MemoryToolError extends Error {
54
+ code
55
+
56
+ constructor(code , message ) {
57
+ super(message)
58
+ this.code = code
59
+ }
60
+ }
61
+
62
+ function svc(opts ) {
63
+ const s = opts.getService()
64
+ if (!s) throw new MemoryToolError('SERVICE_UNAVAILABLE', 'memory service is not loaded; check that dsh-memory-local is enabled')
65
+ return s
66
+ }
67
+
68
+ function toolError(error ) {
69
+ if (error instanceof MemoryToolError) return error
70
+ const code = (error )?.code
71
+ const message = error instanceof Error ? error.message : String(error)
72
+ return new MemoryToolError(typeof code === 'string' ? code : 'MEMORY_ERROR', message)
73
+ }
74
+
75
+ /** 供 apply.ts 使用的实例内 agent(宿主 exec.agent)。 */
76
+ function agentOf(exec ) {
77
+ return (exec )?.agent
78
+ }
79
+
80
+ /** 当前项目 key:配置优先,其次 process.cwd()(与 provider 的缺省一致)。 */
81
+ function projectKey(opts ) {
82
+ return (opts.projectScope ?? `project:${process.cwd()}`)
83
+ }
84
+
85
+ /** 该服务/配置下"当前会话 + 当前项目 + global"的合并读取集合(去重)。 */
86
+ function readScopes(opts , service , agent ) {
87
+ const provided = service.resolveReadScopes?.(agent)
88
+ if (Array.isArray(provided) && provided.length > 0) return [...new Set(provided)]
89
+ // 服务没提供(测试 mock / 旧 provider):退回 defaultScope 口径
90
+ const fallback = opts.defaultScope === 'global' ? 'global' : projectKey(opts)
91
+ return [...new Set([fallback, 'global'])]
92
+ }
93
+
94
+ /** 写路径默认口径;provider 不支持时退回 project。 */
95
+ function writeDefault(opts ) {
96
+ return opts.defaultScope ?? 'session'
97
+ }
98
+
99
+ /** 规范化 + 落到具体 key(或 all)。 */
100
+ function resolveScope(
101
+ opts ,
102
+ service ,
103
+ exec ,
104
+ raw ,
105
+ mode ,
106
+ ) {
107
+ const normalized = normalizeScopeInput(raw)
108
+ if (!normalized.ok) throw new MemoryToolError('SCOPE_INVALID', normalized.message)
109
+ if (normalized.kind === 'global') return { scope: 'global' }
110
+ const agent = agentOf(exec)
111
+ const project = projectKey(opts)
112
+ // 当前会话 key 由 provider 解析(只有它知道 scopes.session 开关与子代理共享父会话的规则);
113
+ // provider 不在(测试 mock / 旧版本)时不给 session —— 写路径会回退 project,读路径回到合并集合。
114
+ const session = service.resolveReadScopes?.(agent)?.find((s) => s.startsWith('session:'))
115
+ const refs = { project, ...(session !== undefined ? { session } : {}) }
116
+ const resolved = resolveScopeRef(normalized, refs, {
117
+ mode,
118
+ defaultScope: writeDefault(opts),
119
+ // provider 的合并集合里没有会话 scope ⇒ scopes.session 关着(或拿不到会话);此时
120
+ // 省略 scope 要干净地回退项目 scope,而不是撞 SCOPE_DISABLED。provider 根本没提供
121
+ // 合并集合(测试 mock / 只实现 save 的旧 provider)时不带这一项:交给它的 save 兜底。
122
+ ...(service.resolveReadScopes !== undefined ? { sessionEnabled: session !== undefined } : {}),
123
+ })
124
+ if (!resolved.ok) throw new MemoryToolError(resolved.code, resolved.message)
125
+ if (resolved.all) return { all: true }
126
+ return resolved.scope !== undefined ? { scope: resolved.scope } : {}
127
+ }
128
+
129
+
130
+
131
+
132
+
133
+
134
+
135
+
136
+
137
+
138
+
139
+
140
+
141
+
142
+
143
+
144
+ export function memorySaveTool(opts ) {
145
+ return {
146
+ name: 'memory_save',
147
+ description: 'Save a durable memory (fact, decision, preference, procedure) for future sessions.',
148
+ parameters: {
149
+ content: { type: 'string', description: 'Self-contained declarative sentence, readable without context', required: true },
150
+ scope: { type: 'string', description: SCOPE_DESCRIPTION },
151
+ kind: { type: 'string', enum: ['fact', 'decision', 'preference', 'procedure', 'note'] },
152
+ tags: { type: 'array', items: { type: 'string' } },
153
+ importance: { type: 'number', description: '0~1, higher = more important' },
154
+ supersedes: { type: 'string', description: 'Record id this corrects/replaces' },
155
+ },
156
+ async execute(args , exec ) {
157
+ const service = svc(opts)
158
+ if (typeof args.content !== 'string' || args.content.trim().length === 0) {
159
+ throw new MemoryToolError('CONTENT_EMPTY', 'content must be a non-empty string')
160
+ }
161
+ if (args.importance !== undefined && (args.importance < 0 || args.importance > 1)) {
162
+ throw new MemoryToolError('IMPORTANCE_RANGE', 'importance must be between 0 and 1')
163
+ }
164
+ // 写路径:省略 scope → provider 按 tools.defaultScope(缺省 session,拿不到会话回退
165
+ // project)。默认值的最终权威是 provider 的 `save` —— 省略时干脆不带 scope 字段,
166
+ // 但要把会话上下文(exec.agent)带过去,否则它没法知道"当前会话"是谁。
167
+ const requested = args.scope?.trim()
168
+ const explicit = requested === undefined || requested === ''
169
+ ? undefined
170
+ : resolveScope(opts, service, exec, requested, 'write').scope
171
+ if (requested !== undefined && requested !== '' && explicit === undefined) {
172
+ throw new MemoryToolError('SCOPE_INVALID', 'scope could not be resolved')
173
+ }
174
+ const agent = agentOf(exec)
175
+ try {
176
+ const record = await service.save({
177
+ ...(explicit !== undefined ? { scope: explicit } : {}),
178
+ ...(agent !== undefined ? { agent } : {}),
179
+ kind: args.kind ?? 'note',
180
+ content: args.content.trim(),
181
+ ...(args.tags ? { tags: args.tags } : {}),
182
+ ...(args.importance !== undefined ? { importance: args.importance } : {}),
183
+ ...(args.supersedes ? { supersedes: args.supersedes } : {}),
184
+ source: { origin: 'explicit' },
185
+ })
186
+ return { id: record.id, scope: record.scope, deduped: false }
187
+ } catch (error) {
188
+ throw toolError(error)
189
+ }
190
+ },
191
+ }
192
+ }
193
+
194
+
195
+
196
+
197
+
198
+
199
+
200
+
201
+
202
+
203
+
204
+
205
+
206
+
207
+
208
+
209
+
210
+
211
+
212
+
213
+ export function memorySearchTool(opts ) {
214
+ return {
215
+ name: 'memory_search',
216
+ description: 'Search saved memories by keyword or meaning (lexical + local vector recall).',
217
+ parameters: {
218
+ query: { type: 'string', required: true },
219
+ scope: { type: 'string', description: SCOPE_DESCRIPTION },
220
+ topK: { type: 'number', description: '1~20' },
221
+ },
222
+ async execute(args , exec ) {
223
+ const service = svc(opts)
224
+ if (typeof args.query !== 'string' || args.query.trim().length === 0) {
225
+ throw new MemoryToolError('QUERY_EMPTY', 'query must be a non-empty string')
226
+ }
227
+ const resolved = resolveScope(opts, service, exec, args.scope, 'read')
228
+ let scopes
229
+ if (resolved.all) {
230
+ // 'all' = 所有已发现作用域;scopeStats() 自身会先做 discovery(带限流)。
231
+ scopes = (service.scopeStats?.() ?? []).map((s) => s.scope)
232
+ service.discoverScopes?.()
233
+ } else if (resolved.scope === undefined) {
234
+ // 省略 scope:三路合并(会话 + 项目 + global)
235
+ scopes = readScopes(opts, service, agentOf(exec))
236
+ }
237
+ try {
238
+ const hits = await service.search({
239
+ text: args.query,
240
+ ...(resolved.scope !== undefined ? { scope: resolved.scope } : {}),
241
+ ...(scopes !== undefined ? { scopes } : {}),
242
+ ...(args.topK !== undefined ? { topK: args.topK } : {}),
243
+ })
244
+ return {
245
+ records: hits.map((h) => ({
246
+ id: h.record.id,
247
+ score: h.score,
248
+ scope: h.record.scope,
249
+ kind: h.record.kind,
250
+ updatedAt: h.record.updatedAt,
251
+ content: h.record.content,
252
+ })),
253
+ }
254
+ } catch (error) {
255
+ throw toolError(error)
256
+ }
257
+ },
258
+ }
259
+ }
260
+
261
+
262
+
263
+
264
+
265
+
266
+
267
+
268
+
269
+
270
+
271
+
272
+ export function memoryForgetTool(opts ) {
273
+ return {
274
+ name: 'memory_forget',
275
+ description: 'Delete a memory by id (any scope), or all memories matching a query in one scope (default: current session).',
276
+ parameters: {
277
+ id: { type: 'string', description: 'Exact record id' },
278
+ query: { type: 'string', description: 'Substring match; by default only the current session scope' },
279
+ scope: { type: 'string', description: "省略=当前会话;显式指定只删那一个作用域。'all' 不能与 query 同用(防批量误删)。" },
280
+ },
281
+ async execute(args , exec ) {
282
+ const service = svc(opts)
283
+ if (!args.id && !args.query) throw new MemoryToolError('TARGET_REQUIRED', 'provide id or query')
284
+ if (args.id && args.query) throw new MemoryToolError('TARGET_AMBIGUOUS', 'provide id or query, not both')
285
+ // id 路径本来就跨 scope(精确 id 不会误删),不解析 scope。
286
+ if (args.id) {
287
+ try {
288
+ return await service.forget({ id: args.id })
289
+ } catch (error) {
290
+ throw toolError(error)
291
+ }
292
+ }
293
+ const resolved = resolveScope(opts, service, exec, args.scope, 'read')
294
+ if (resolved.all) {
295
+ throw new MemoryToolError('SCOPE_NOT_WRITABLE', "scope 'all' cannot be combined with query; name the scope you mean")
296
+ }
297
+ const scope = resolved.scope ?? readScopes(opts, service, agentOf(exec))[0]
298
+ try {
299
+ return await service.forget({ query: args.query, ...(scope !== undefined ? { scope } : {}) })
300
+ } catch (error) {
301
+ throw toolError(error)
302
+ }
303
+ },
304
+ }
305
+ }
306
+
307
+
308
+
309
+
310
+
311
+
312
+
313
+
314
+
315
+                                
316
+
317
+
318
+
319
+ export function memoryListTool(opts ) {
320
+ return {
321
+ name: 'memory_list',
322
+ description: 'List saved memories, most recently updated first.',
323
+ parameters: {
324
+ scope: { type: 'string', description: "省略=当前会话;'all'=所有作用域;其他值只列该作用域。" },
325
+ kind: { type: 'string' },
326
+ limit: { type: 'number', description: '1~200' },
327
+ },
328
+ async execute(args , exec ) {
329
+ const service = svc(opts)
330
+ const resolved = resolveScope(opts, service, exec, args.scope, 'read')
331
+ let scopes
332
+ if (resolved.all) {
333
+ scopes = (service.scopeStats?.() ?? []).map((s) => s.scope)
334
+ service.discoverScopes?.()
335
+ } else if (resolved.scope === undefined) {
336
+ // 省略 scope:默认**只列当前会话**(按需求;读全部请显式 'all')
337
+ scopes = readScopes(opts, service, agentOf(exec)).slice(0, 1)
338
+ }
339
+ let records
340
+ try {
341
+ const raw = await service.list({
342
+ ...(resolved.scope !== undefined ? { scope: resolved.scope } : {}),
343
+ ...(scopes !== undefined ? { scopes } : {}),
344
+ ...(args.kind ? { kind: args.kind } : {}),
345
+ ...(args.limit !== undefined ? { limit: args.limit } : {}),
346
+ })
347
+ records = raw.map((r) => ({
348
+ id: r.id,
349
+ scope: r.scope,
350
+ kind: r.kind,
351
+ updatedAt: r.updatedAt,
352
+ content: r.content,
353
+ }))
354
+ } catch (error) {
355
+ throw toolError(error)
356
+ }
357
+ const stats = service.scopeStats?.()
358
+ return stats !== undefined ? { records, scopeStats: stats } : { records }
359
+ },
360
+ }
361
+ }
362
+
363
+ export function memoryTools(opts ) {
364
+ return {
365
+ memory_save: memorySaveTool(opts),
366
+ memory_search: memorySearchTool(opts),
367
+ memory_forget: memoryForgetTool(opts),
368
+ memory_list: memoryListTool(opts),
369
+ }
370
+ }
222
371
 
223
372
 
224
373
  //# sourceURL=source/tool-memory/src/index.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restregular/dsh-memory",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "DeepSeek Harness 本地长期记忆(单包单入口):JSONL 存储 + 本地向量检索(BGE-M3)+ 四个模型工具 + 自动召回注入 + 管理面板。",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",