@restregular/dsh-memory 0.5.6 → 0.6.1

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/lib/panel.js CHANGED
@@ -35,9 +35,16 @@ function writeJson(res, body, status = 200) {
35
35
  } catch { /* 客户端已断开 */ }
36
36
  }
37
37
 
38
+ /** provider 侧的"调用方输入有问题"错误码 → 400;其余未标注的仍算 500。 */
39
+ const CLIENT_ERROR_CODES = new Set([
40
+ 'SCOPE_INVALID', 'SCOPE_DISABLED', 'CONTENT_EMPTY', 'CONTENT_TOO_LONG',
41
+ 'SECRET_DETECTED', 'IMPORT_INVALID', 'IMPORT_TOO_LARGE', 'KIND_INVALID',
42
+ ])
43
+
38
44
  function writeError(res, error) {
39
- const status = Number(error?.status) || 500
40
- writeJson(res, { ok: false, error: { code: error?.code || 'internal', message: error?.message || String(error) } }, status)
45
+ const code = typeof error?.code === 'string' ? error.code : 'internal'
46
+ const status = Number(error?.status) || (CLIENT_ERROR_CODES.has(code) ? 400 : code === 'SCOPE_LIMIT' ? 409 : 500)
47
+ writeJson(res, { ok: false, error: { code, message: error?.message || String(error) } }, status)
41
48
  }
42
49
 
43
50
  class ApiError extends Error {
@@ -241,11 +248,50 @@ async function handle(ctx, routePath, req, res) {
241
248
  let embedServer = null
242
249
  // older providers have no lifecycle API — the panel simply omits the card
243
250
  try { embedServer = (await memory.embedServerStatus?.()) ?? null } catch { embedServer = null }
244
- writeJson(res, { ok: true, value: { scopes, embedServer } })
251
+ let rules = null
252
+ try { rules = typeof memory.ruleStats === 'function' ? memory.ruleStats() : null } catch { rules = null }
253
+ writeJson(res, { ok: true, value: { scopes, embedServer, rules } })
254
+ return
255
+ }
256
+ if (method === 'GET' && path === '/settings') {
257
+ if (typeof memory.injectSettings !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供注入设置接口(请升级 @restregular/dsh-memory)')
258
+ writeJson(res, { ok: true, value: memory.injectSettings() })
259
+ return
260
+ }
261
+ if (method === 'POST' && path === '/settings') {
262
+ if (typeof memory.updateInjectSettings !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供注入设置接口(请升级 @restregular/dsh-memory)')
263
+ const body = await readJsonBody(req)
264
+ writeJson(res, { ok: true, value: memory.updateInjectSettings(body) })
265
+ return
266
+ }
267
+ if (method === 'POST' && path === '/create') {
268
+ if (typeof memory.createRecord !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供新建接口(请升级 @restregular/dsh-memory)')
269
+ const body = await readJsonBody(req)
270
+ const record = await memory.createRecord({
271
+ ...(typeof body.scope === 'string' ? { scope: body.scope } : {}),
272
+ ...(typeof body.kind === 'string' ? { kind: body.kind } : {}),
273
+ ...(typeof body.content === 'string' ? { content: body.content } : {}),
274
+ ...(Array.isArray(body.tags) ? { tags: body.tags.map(String) } : {}),
275
+ ...(typeof body.importance === 'number' ? { importance: body.importance } : {}),
276
+ })
277
+ console.log(`[dsh-memory-panel] 新建 ${record.kind} @ ${record.scope}: ${record.id}`)
278
+ writeJson(res, { ok: true, value: { record } })
279
+ return
280
+ }
281
+ if (method === 'GET' && path === '/export') {
282
+ if (typeof memory.exportAll !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供导出接口(请升级 @restregular/dsh-memory)')
283
+ writeJson(res, { ok: true, value: memory.exportAll() })
284
+ return
285
+ }
286
+ if (method === 'POST' && path === '/import') {
287
+ if (typeof memory.importRecords !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供导入接口(请升级 @restregular/dsh-memory)')
288
+ const body = await readJsonBody(req)
289
+ const result = await memory.importRecords(body)
290
+ console.log(`[dsh-memory-panel] 导入完成: 新增 ${result.imported} / 跳过 ${result.skipped} / 失败 ${result.rejected}`)
291
+ writeJson(res, { ok: true, value: result })
245
292
  return
246
293
  }
247
- if (method === 'GET' && path === '/embed/status') {
248
- if (typeof memory.embedServerStatus !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
294
+ if (method === 'GET' && path === '/embed/status') { if (typeof memory.embedServerStatus !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
249
295
  writeJson(res, { ok: true, value: await memory.embedServerStatus() })
250
296
  return
251
297
  }
@@ -120,6 +120,50 @@ export class CordisMemoryService extends Service {
120
120
  return this.impl.list(input)
121
121
  }
122
122
 
123
+ /** memory_get:按 id 批量取记录。 */
124
+ getByIds(ids ) {
125
+ return this.impl.getByIds(ids)
126
+ }
127
+
128
+ /** 面板新建记忆 / 规则。 */
129
+ createRecord(input ) {
130
+ return this.impl.createRecord(input)
131
+ }
132
+
133
+ /** 面板导出:纯文本 + 元数据,不含向量。 */
134
+ exportAll() {
135
+ return this.impl.exportAll()
136
+ }
137
+
138
+ /** 面板导入:逐条 save(自动重新嵌入),失败不中断。 */
139
+ importRecords(input ) {
140
+ return this.impl.importRecords(input)
141
+ }
142
+
143
+ /** 设置页显示规则条数。 */
144
+ ruleStats() {
145
+ return this.impl.ruleStats()
146
+ }
147
+
148
+ /** 同步列记录(系统提示里的规则段用,不能等异步 list)。 */
149
+ listSync(input ) {
150
+ return this.impl.listSync(input)
151
+ }
152
+
153
+ /** 注入设置(面板「设置」标签页读它)。 */
154
+ injectSettings() {
155
+ return this.impl.injectSettings()
156
+ }
157
+
158
+ /** 面板改设置:落盘后广播,注入半边下一步就能按新设置跑。 */
159
+ updateInjectSettings(patch ) {
160
+ const next = this.impl.updateInjectSettings(patch)
161
+ try {
162
+ this.ctx.emit('memory/inject-settings', next)
163
+ } catch { /* 广播失败不影响设置本身 */ }
164
+ return next
165
+ }
166
+
123
167
  /**
124
168
  * 当前 agent 上下文 → 默认合并读取范围(会话 + 项目 + global,按开关与 key 去重)。
125
169
  * 工具与召回注入都走它,保证与 `resolveWriteScope` 是同一套口径。
@@ -17,12 +17,14 @@
17
17
  import { MemoryStore, scopeFileName, } from './store.js'
18
18
  import {
19
19
  isCustomScope,
20
+ normalizeScopeInput,
20
21
  resolveCurrentScopes,
21
22
  scopeKind,
22
23
  scopeTier,
23
24
  writeScopeForDefault,
24
25
 
25
26
  } from './scope.js'
27
+ import { mergeInjectSettings, normalizeInjectSettings, } from './inject-settings.js'
26
28
  import { buildStats, lexicalScore, recordScore, tokenize, cosine, normalizeInPlace, hasStrongHit } from './scoring.js'
27
29
  import { EmbedClient } from './embed.js'
28
30
  import { DailyBudget, blendScores, rerank, } from './rerank.js'
@@ -487,9 +489,12 @@ export class LocalMemoryService {
487
489
  projectScope
488
490
  /** 上次发现磁盘 scope 的时间(限流用;0 = 还没发现过)。 */
489
491
  discoveredAt = 0
492
+ /** 注入设置(面板「设置」标签页可改;落盘在 <storeDir>/settings.json)。 */
493
+ inject
490
494
 
491
495
  constructor(config = {}) {
492
496
  this.cfg = resolveConfig(config)
497
+ this.inject = this.loadInjectSettings((config ).inject)
493
498
  this.rerankBudget = new DailyBudget(this.cfg.llm.dailyBudgetTokens)
494
499
  this.store = new MemoryStore(this.cfg.storeDir, { onWarn: (m) => console.warn(`[dsh-memory-local] ${m}`) })
495
500
  // Identity BEFORE the eager load (issue #1): ScopeStore skips its sidecar
@@ -517,8 +522,63 @@ export class LocalMemoryService {
517
522
  this.startEmbedServer()
518
523
  }
519
524
 
520
- /** Own the embedding backend's lifetime: spawn on activation, stop on dispose. */
521
- startEmbedServer() {
525
+ /** 设置文件:与记忆数据同目录,便于一起备份/清理。 */
526
+ get settingsPath() {
527
+ return join(this.cfg.storeDir, 'settings.json')
528
+ }
529
+
530
+ /** 读取注入设置(归一化后的快照)。 */
531
+ injectSettings() {
532
+ return normalizeInjectSettings(this.inject, this.inject)
533
+ }
534
+
535
+ /** 面板改设置:合并补丁 → 落盘 → 返回新值。写盘失败只告警,不影响运行中的设置。 */
536
+ updateInjectSettings(patch ) {
537
+ this.inject = mergeInjectSettings(this.inject, patch)
538
+ try {
539
+ mkdirSync(this.cfg.storeDir, { recursive: true })
540
+ writeFileSync(this.settingsPath, `${JSON.stringify(this.inject, null, 2)}\n`, 'utf8')
541
+ } catch (error) {
542
+ console.warn(`[dsh-memory-local] 无法写入注入设置 ${this.settingsPath}: ${error instanceof Error ? error.message : String(error)}`)
543
+ }
544
+ return this.injectSettings()
545
+ }
546
+
547
+ /** 配置先给底,磁盘上的 settings.json 覆盖它;坏文件忽略而不是启动失败。 */
548
+ loadInjectSettings(fromConfig ) {
549
+ const base = normalizeInjectSettings(fromConfig)
550
+ try {
551
+ if (existsSync(this.settingsPath)) {
552
+ return mergeInjectSettings(base, JSON.parse(readFileSync(this.settingsPath, 'utf8')))
553
+ }
554
+ } catch (error) {
555
+ console.warn(`[dsh-memory-local] 忽略损坏的注入设置 ${this.settingsPath}: ${error instanceof Error ? error.message : String(error)}`)
556
+ }
557
+ return base
558
+ }
559
+
560
+ /**
561
+ * 同步列记录(只读、不触发磁盘发现)。系统提示里的「硬性规则」段每步都要
562
+ * 渲染,必须是同步的;这里直接读已加载 scope 的内存快照。
563
+ */
564
+ listSync(input = {}) {
565
+ const seen = new Set ()
566
+ const out = []
567
+ for (const scope of input.scopes ?? []) {
568
+ if (seen.has(scope)) continue
569
+ seen.add(scope)
570
+ const s = this.store.peek(scope)
571
+ if (!s) continue
572
+ for (const rec of s.records.values()) {
573
+ if (input.kind !== undefined && rec.kind !== input.kind) continue
574
+ out.push(rec)
575
+ }
576
+ }
577
+ out.sort((a, b) => b.updatedAt - a.updatedAt)
578
+ return out.slice(0, input.limit ?? 100)
579
+ }
580
+
581
+ /** Own the embedding backend's lifetime: spawn on activation, stop on dispose. */ startEmbedServer() {
522
582
  // Nothing configured and retrieval switched off → do not even build the
523
583
  // manager, so no probe, no spawn attempt, no misleading panel state.
524
584
  if (!this.cfg.vector.enabled || !this.cfg.vector.configured) return
@@ -1414,6 +1474,151 @@ export class LocalMemoryService {
1414
1474
  return records.slice(0, input.limit ?? 50)
1415
1475
  }
1416
1476
 
1477
+ /**
1478
+ * 按 id 批量取记录(memory_get)。接受完整 id,也接受摘要里给出的前 8 位前缀
1479
+ * (前缀命中多条时全部返回,由调用方/模型自行判断)。取全文不需要再检索。
1480
+ */
1481
+ getByIds(ids ) {
1482
+ this.discoverScopes()
1483
+ const scopes = this.store.allScopes()
1484
+ const out = []
1485
+ const seen = new Set ()
1486
+ for (const token of ids) {
1487
+ if (typeof token !== 'string' || token.length === 0) continue
1488
+ for (const s of scopes) {
1489
+ for (const rec of s.records.values()) {
1490
+ if (seen.has(rec.id)) continue
1491
+ if (rec.id === token || rec.id.startsWith(token)) {
1492
+ seen.add(rec.id)
1493
+ out.push(rec)
1494
+ }
1495
+ }
1496
+ }
1497
+ }
1498
+ return out
1499
+ }
1500
+
1501
+ /**
1502
+ * 面板新建一条记忆 / 规则。scope 必须是**明确的键**(global / project:<路径> /
1503
+ * session:<id> / 自定义名)—— 面板拿不到会话上下文,'project'/'session' 这种
1504
+ * 相对写法没法解析,直接拒绝比猜一个错的强。
1505
+ */
1506
+ async createRecord(input
1507
+
1508
+
1509
+
1510
+
1511
+
1512
+ ) {
1513
+ const normalized = normalizeScopeInput(input.scope)
1514
+ if (!normalized.ok) throw memoryError('SCOPE_INVALID', normalized.message)
1515
+ if (normalized.scope === undefined) {
1516
+ throw memoryError('SCOPE_INVALID', '面板写入需要明确的 scope(global / project:<路径> / session:<id> / 自定义名)')
1517
+ }
1518
+ return this.save({
1519
+ scope: normalized.scope ,
1520
+ kind: (input.kind ?? 'note') ,
1521
+ content: String(input.content ?? ''),
1522
+ ...(input.tags !== undefined ? { tags: input.tags } : {}),
1523
+ ...(input.importance !== undefined ? { importance: input.importance } : {}),
1524
+ })
1525
+ }
1526
+
1527
+ /**
1528
+ * 导出全部记忆为**纯文本**文档(不含向量)。向量在导入时按当前模型重新算,
1529
+ * 所以换过模型也照样导得回去。
1530
+ */
1531
+ exportAll(now = Date.now())
1532
+
1533
+
1534
+
1535
+
1536
+
1537
+
1538
+
1539
+
1540
+
1541
+
1542
+
1543
+ {
1544
+ this.discoverScopes()
1545
+ const records = []
1546
+ for (const s of this.store.allScopes()) {
1547
+ for (const rec of s.records.values()) {
1548
+ records.push({
1549
+ scope: rec.scope,
1550
+ kind: rec.kind,
1551
+ content: rec.content,
1552
+ tags: rec.tags,
1553
+ importance: rec.importance,
1554
+ createdAt: rec.createdAt,
1555
+ updatedAt: rec.updatedAt,
1556
+ })
1557
+ }
1558
+ }
1559
+ records.sort((a, b) => a.scope.localeCompare(b.scope) || a.createdAt - b.createdAt)
1560
+ return { version: 1, exportedAt: now, records }
1561
+ }
1562
+
1563
+ /**
1564
+ * 导入文本记忆。逐条走 `save()`(凭据扫描 / 上限 / 去重 / 向量回填都在那条路上),
1565
+ * 所以导入的记录会自动按当前模型重新嵌入。返回计数,失败不中断其余条目。
1566
+ */
1567
+ async importRecords(input ) {
1568
+ const list = Array.isArray(input)
1569
+ ? input
1570
+ : (input && typeof input === 'object' && Array.isArray((input ).records))
1571
+ ? (input ).records
1572
+ : null
1573
+ if (list === null) throw memoryError('IMPORT_INVALID', '导入格式不对:需要 {version, records:[...]} 或记录数组')
1574
+ if (list.length > 5000) throw memoryError('IMPORT_TOO_LARGE', `一次最多导入 5000 条(收到 ${list.length} 条)`)
1575
+
1576
+ let imported = 0
1577
+ let skipped = 0
1578
+ let rejected = 0
1579
+ const errors = []
1580
+ for (const [index, raw] of list.entries()) {
1581
+ try {
1582
+ const rec = raw
1583
+ const content = typeof rec.content === 'string' ? rec.content : ''
1584
+ if (content.trim().length === 0) throw new Error('content 为空')
1585
+ const normalized = normalizeScopeInput(typeof rec.scope === 'string' ? rec.scope : undefined)
1586
+ if (!normalized.ok) throw new Error(normalized.message)
1587
+ if (normalized.scope === undefined) throw new Error('缺少明确的 scope')
1588
+ const scope = normalized.scope
1589
+ if (this.store.hasContent(scope, content)) {
1590
+ skipped += 1
1591
+ continue
1592
+ }
1593
+ await this.save({
1594
+ scope,
1595
+ kind: (typeof rec.kind === 'string' && rec.kind.length > 0 ? rec.kind : 'note') ,
1596
+ content,
1597
+ ...(Array.isArray(rec.tags) ? { tags: rec.tags.map(String) } : {}),
1598
+ ...(typeof rec.importance === 'number' ? { importance: rec.importance } : {}),
1599
+ })
1600
+ imported += 1
1601
+ } catch (error) {
1602
+ rejected += 1
1603
+ if (errors.length < 20) errors.push(`#${index}: ${error instanceof Error ? error.message : String(error)}`)
1604
+ }
1605
+ }
1606
+ this.store.scheduleFlush()
1607
+ return { imported, skipped, rejected, errors }
1608
+ }
1609
+
1610
+ /** 规则条数(面板设置页显示;只数已加载/已发现的作用域)。 */
1611
+ ruleStats() {
1612
+ this.discoverScopes()
1613
+ let total = 0
1614
+ let scopes = 0
1615
+ for (const s of this.store.allScopes()) {
1616
+ const n = [...s.records.values()].filter((r) => r.kind === 'rule').length
1617
+ if (n > 0) { total += n; scopes += 1 }
1618
+ }
1619
+ return { total, scopes }
1620
+ }
1621
+
1417
1622
  /**
1418
1623
  * 作用域清单(名字 + 条数 + 待嵌入 + 最近活跃时间),给面板 /status 与 memory_list 的尾部清单用。
1419
1624
  *
@@ -0,0 +1,142 @@
1
+ /**
2
+ * 注入相关的运行时设置 —— 面板「记忆 → 设置」里能开关的那些东西。
3
+ *
4
+ * 为什么放在 provider 侧:设置要落盘(进程重启后还在)、要能通过面板 HTTP
5
+ * 接口读写,而注入半边只是一组纯函数 + 一个 pre-step 监听器。所以 provider
6
+ * 负责存与发事件,注入半边只负责"每步读一次"。
7
+ */
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+         
17
+
18
+
19
+
20
+
21
+
22
+                                
23
+
24
+
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
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+ export const defaultInjectSettings = {
60
+ recall: { enabled: true, topK: 5, tokenBudget: 500 },
61
+ digest: { enabled: true, topK: 8, tokenBudget: 400 },
62
+ impression: { enabled: true, chars: 120 },
63
+ policy: { enabled: true },
64
+ rules: { enabled: true, maxItems: 10, tokenBudget: 300 },
65
+ turnEnd: { enabled: false },
66
+ sidebar: { enabled: false },
67
+ }
68
+
69
+ const clampInt = (value , min , max , fallback ) => {
70
+ const n = typeof value === 'number' ? value : Number(value)
71
+ if (!Number.isFinite(n)) return fallback
72
+ return Math.min(max, Math.max(min, Math.round(n)))
73
+ }
74
+
75
+ const bool = (value , fallback ) =>
76
+ typeof value === 'boolean' ? value : fallback
77
+
78
+ /** 容错读取:未知字段忽略、越界值夹紧,配置/面板发来脏数据也不该把注入搞崩。 */
79
+ export function normalizeInjectSettings(raw , base = defaultInjectSettings) {
80
+ let r = (raw && typeof raw === 'object' ? raw : {})
81
+ // 0.5.x 的 inject 小节只有 enabled / topK / tokenBudget(召回),继续认它们。
82
+ const legacy = r
83
+ if (legacy.enabled !== undefined || legacy.topK !== undefined || legacy.tokenBudget !== undefined) {
84
+ r = {
85
+ ...r,
86
+ recall: {
87
+ ...(legacy.enabled !== undefined ? { enabled: legacy.enabled } : {}),
88
+ ...(legacy.topK !== undefined ? { topK: legacy.topK } : {}),
89
+ ...(legacy.tokenBudget !== undefined ? { tokenBudget: legacy.tokenBudget } : {}),
90
+ ...((r.recall && typeof r.recall === 'object' ? r.recall : {}) ),
91
+ },
92
+ }
93
+ }
94
+ const section = (key ) => {
95
+ const value = r[key]
96
+ return (value && typeof value === 'object' ? value : {})
97
+ }
98
+ const recall = section('recall')
99
+ const digest = section('digest')
100
+ const impression = section('impression')
101
+ const policy = section('policy')
102
+ const rules = section('rules')
103
+ const turnEnd = section('turnEnd')
104
+ const sidebar = section('sidebar')
105
+ return {
106
+ recall: {
107
+ enabled: bool(recall.enabled, base.recall.enabled),
108
+ topK: clampInt(recall.topK, 1, 20, base.recall.topK),
109
+ tokenBudget: clampInt(recall.tokenBudget, 50, 4000, base.recall.tokenBudget),
110
+ },
111
+ digest: {
112
+ enabled: bool(digest.enabled, base.digest.enabled),
113
+ topK: clampInt(digest.topK, 1, 30, base.digest.topK),
114
+ tokenBudget: clampInt(digest.tokenBudget, 50, 4000, base.digest.tokenBudget),
115
+ },
116
+ impression: {
117
+ enabled: bool(impression.enabled, base.impression.enabled),
118
+ chars: clampInt(impression.chars, 40, 800, base.impression.chars),
119
+ },
120
+ policy: { enabled: bool(policy.enabled, base.policy.enabled) },
121
+ rules: {
122
+ enabled: bool(rules.enabled, base.rules.enabled),
123
+ maxItems: clampInt(rules.maxItems, 1, 40, base.rules.maxItems),
124
+ tokenBudget: clampInt(rules.tokenBudget, 50, 4000, base.rules.tokenBudget),
125
+ },
126
+ turnEnd: { enabled: bool(turnEnd.enabled, base.turnEnd.enabled) },
127
+ sidebar: { enabled: bool(sidebar.enabled, base.sidebar.enabled) },
128
+ }
129
+ }
130
+
131
+ /** 把面板发来的补丁合并进当前设置(只认已知字段,其余忽略)。 */
132
+ export function mergeInjectSettings(current , patch ) {
133
+ const p = (patch && typeof patch === 'object' ? patch : {})
134
+ const merged = { ...current }
135
+ for (const key of Object.keys(defaultInjectSettings) ) {
136
+ if (p[key] && typeof p[key] === 'object') merged[key] = { ...current[key], ...(p[key] ) }
137
+ }
138
+ return normalizeInjectSettings(merged, current)
139
+ }
140
+
141
+
142
+ //# sourceURL=source/memory-local/src/inject-settings.ts
@@ -528,6 +528,17 @@ export class MemoryStore {
528
528
  return { record, deduped: false }
529
529
  }
530
530
 
531
+ /** 该 scope 里是否已有相同内容(导入去重计数用;只读,不建文件)。 */
532
+ hasContent(scope , content ) {
533
+ const s = this.peek(scope)
534
+ if (!s) return false
535
+ const hash = contentHash(scope, content)
536
+ for (const rec of s.records.values()) {
537
+ if (contentHash(rec.scope, rec.content) === hash) return true
538
+ }
539
+ return false
540
+ }
541
+
531
542
  /** Substring match over normalized content, used by forget-by-query. */
532
543
  findIdsByQuery(scope , query ) {
533
544
  // 读/删路径:用 peek,不存在的 scope 返回空,绝不创建。
@@ -33,6 +33,8 @@ import { normalizeScopeInput, resolveScopeRef } from '../provider/scope.js'
33
33
 
34
34
                      
35
35
 
36
+                           
37
+
36
38
                 
37
39
 
38
40
 
@@ -157,11 +159,11 @@ function resolveScope(
157
159
  export function memorySaveTool(opts ) {
158
160
  return {
159
161
  name: 'memory_save',
160
- description: 'Save a durable memory (fact, decision, preference, procedure) for future sessions.',
162
+ description: 'Save a durable memory (fact, decision, preference, procedure, rule) for future sessions.',
161
163
  parameters: {
162
164
  content: { type: 'string', description: 'Self-contained declarative sentence, readable without context', required: true },
163
165
  scope: { type: 'string', description: SCOPE_DESCRIPTION },
164
- kind: { type: 'string', enum: ['fact', 'decision', 'preference', 'procedure', 'note'] },
166
+ kind: { type: 'string', enum: ['fact', 'decision', 'preference', 'procedure', 'note', 'rule'] },
165
167
  tags: { type: 'array', items: { type: 'string' } },
166
168
  importance: { type: 'number', description: '0~1, higher = more important' },
167
169
  supersedes: { type: 'string', description: 'Record id this corrects/replaces' },
@@ -373,12 +375,51 @@ export function memoryListTool(opts )
373
375
  }
374
376
  }
375
377
 
378
+
379
+
380
+
381
+
382
+
383
+
384
+ export function memoryGetTool(opts ) {
385
+ return {
386
+ name: 'memory_get',
387
+ description: 'Fetch memories by id or by the 8-char id prefix shown in recall/digest summaries. Fast path: no retrieval needed.',
388
+ parameters: {
389
+ ids: { type: 'array', items: { type: 'string' }, description: '记忆 id 或摘要开头的 8 位前缀,1~50 个', required: true },
390
+ },
391
+ async execute(args ) {
392
+ const service = svc(opts)
393
+ const ids = Array.isArray(args.ids)
394
+ ? [...new Set(args.ids.map(String).filter((id) => id.trim() !== ''))].slice(0, 50)
395
+ : []
396
+ if (ids.length === 0) throw toolError(new Error('ids 不能为空'))
397
+ if (typeof service.getByIds !== 'function') {
398
+ throw toolError(new Error('当前 provider 不支持 memory_get(请升级 @restregular/dsh-memory)'))
399
+ }
400
+ try {
401
+ const found = service.getByIds(ids)
402
+ return {
403
+ records: found.map((r) => ({
404
+ id: r.id, scope: r.scope, kind: r.kind, content: r.content,
405
+ tags: r.tags, importance: r.importance, updatedAt: r.updatedAt,
406
+ })),
407
+ missing: ids.filter((token) => !found.some((r) => r.id === token || r.id.startsWith(token))),
408
+ }
409
+ } catch (error) {
410
+ throw toolError(error)
411
+ }
412
+ },
413
+ }
414
+ }
415
+
376
416
  export function memoryTools(opts ) {
377
417
  return {
378
418
  memory_save: memorySaveTool(opts),
379
419
  memory_search: memorySearchTool(opts),
380
420
  memory_forget: memoryForgetTool(opts),
381
421
  memory_list: memoryListTool(opts),
422
+ memory_get: memoryGetTool(opts),
382
423
  }
383
424
  }
384
425
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restregular/dsh-memory",
3
- "version": "0.5.6",
3
+ "version": "0.6.1",
4
4
  "description": "DeepSeek Harness 本地长期记忆(单包单入口):JSONL 存储 + 本地向量检索(BGE-M3)+ 四个模型工具 + 自动召回注入 + 管理面板。",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",