@restregular/dsh-memory 0.23.1 → 0.24.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,215 @@
1
+ /**
2
+ * 作用域元数据(scope meta)。
3
+ *
4
+ * 为什么需要它:作用域键本身只说明"叫什么",不说明"用来做什么"。Agent 在申请
5
+ * 范围外作用域之前,必须先能看见它的用途;用户也需要一个地方写"这个作用域只放
6
+ * 什么"。这些信息不属于任何一条记忆:记录会被 supersede / forget / 过期,而作用域
7
+ * 的生命周期更长。
8
+ *
9
+ * 存储选择:**每个作用域一个文件**(`<root>/scope-meta/<sha1(scope)>.json`),
10
+ * 而不是一份全局 map。原因和 `visibility/<session>.json` 一样:
11
+ * - 同一个 storeDir 可能被多个进程共用(宿主 + 面板 + 多个 agent);
12
+ * - 全局 map 的读改写会互相覆盖,而 `scopes.json` 现在就没锁;
13
+ * - 按作用域分文件后,创建 / 更新只碰自己那份,天然并发安全(原子 rename)。
14
+ *
15
+ * 兼容:没有元数据的旧作用域照常工作;`get()` 返回 undefined,调用方按
16
+ * "未填写用途" 处理,绝不因为升级就要求补齐。项目作用域的显示名仍以
17
+ * `scopes.json`(ScopeNames)为准,这里只存可选的覆盖名。
18
+ */
19
+ import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
20
+ import { createHash, randomUUID } from 'node:crypto'
21
+ import { join } from 'node:path'
22
+ import { scopeKind, } from './scope.js'
23
+
24
+ export const SCOPE_META_VERSION = 1
25
+
26
+ /** 用途说明的长度上限。太长就不是"一句话用途"而是又一条记忆了。 */
27
+ export const MAX_SCOPE_DESCRIPTION_CHARS = 500
28
+
29
+
30
+
31
+ /** 初始化流程状态:pending = 元数据已落盘、初始记录可能还没写完。 */
32
+
33
+
34
+
35
+
36
+                                
37
+
38
+                          
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+                          
47
+                           
48
+
49
+
50
+
51
+
52
+
53
+ /** 作用域键 → 元数据文件名(与记录文件同款 SHA-1 寻址,不暴露路径/名称)。 */
54
+ export function scopeMetaFileName(scope ) {
55
+ return `${createHash('sha1').update(scope).digest('hex')}.json`
56
+ }
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+ function asString(value ) {
66
+ return typeof value === 'string' && value.length > 0 ? value : undefined
67
+ }
68
+
69
+ function asTime(value ) {
70
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0
71
+ }
72
+
73
+ /**
74
+ * 读盘校验。坏文件 / 形状不符一律当"没有元数据",绝不把异常抛回检索或保存链路。
75
+ * `scope` 字段必须与请求的键一致,防止文件被挪动后张冠李戴。
76
+ */
77
+ function parseMeta(raw , wanted ) {
78
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined
79
+ const value = raw
80
+ const scope = asString(value.scope)
81
+ if (scope === undefined) return undefined
82
+ if (wanted !== undefined && scope !== wanted) return undefined
83
+ const description = typeof value.description === 'string' ? value.description : ''
84
+ const originRaw = value.origin
85
+ const origin = originRaw === 'global' || originRaw === 'project' || originRaw === 'session' || originRaw === 'custom'
86
+ ? originRaw
87
+ : scopeKind(scope)
88
+ const generation = asString(value.generation) ?? randomUUID()
89
+ const status = value.status === 'pending' ? 'pending' : 'ready'
90
+ const createdAt = asTime(value.createdAt) || Date.now()
91
+ return {
92
+ schemaVersion: SCOPE_META_VERSION,
93
+ scope,
94
+ ...(asString(value.name) !== undefined ? { name: asString(value.name) } : {}),
95
+ description,
96
+ origin,
97
+ createdBy: asString(value.createdBy) ?? 'unknown',
98
+ createdAt,
99
+ updatedAt: asTime(value.updatedAt) || createdAt,
100
+ generation,
101
+ status,
102
+ }
103
+ }
104
+
105
+
106
+               
107
+
108
+
109
+
110
+ export class ScopeMetaStore {
111
+ dir
112
+
113
+ constructor(options ) {
114
+ this.dir = join(options.root, 'scope-meta')
115
+ }
116
+
117
+ fileFor(scope ) {
118
+ return join(this.dir, scopeMetaFileName(scope))
119
+ }
120
+
121
+ /** 读取元数据;没有 / 坏文件 → undefined(不触发任何写入)。 */
122
+ get(scope ) {
123
+ let text
124
+ try {
125
+ text = readFileSync(this.fileFor(scope), 'utf8')
126
+ } catch {
127
+ return undefined
128
+ }
129
+ try {
130
+ return parseMeta(JSON.parse(text) , scope)
131
+ } catch {
132
+ return undefined
133
+ }
134
+ }
135
+
136
+ has(scope ) {
137
+ try {
138
+ return statSync(this.fileFor(scope)).isFile()
139
+ } catch {
140
+ return false
141
+ }
142
+ }
143
+
144
+ /** 已落盘的全部元数据(供目录工具 / 面板枚举)。坏文件跳过。 */
145
+ list() {
146
+ let entries
147
+ try {
148
+ entries = readdirSync(this.dir)
149
+ } catch {
150
+ return []
151
+ }
152
+ const out = []
153
+ for (const entry of entries) {
154
+ if (!entry.endsWith('.json')) continue
155
+ let text
156
+ try {
157
+ text = readFileSync(join(this.dir, entry), 'utf8')
158
+ } catch {
159
+ continue
160
+ }
161
+ try {
162
+ const meta = parseMeta(JSON.parse(text) )
163
+ if (meta !== undefined) out.push(meta)
164
+ } catch {
165
+ // 坏文件跳过:元数据不是权威数据,不能因此让目录工具失败
166
+ }
167
+ }
168
+ return out
169
+ }
170
+
171
+ /**
172
+ * 写入(新建或更新)。已存在时保留 `createdAt` / `generation` / `createdBy`,
173
+ * 只更新 `description` / `name` / `status` / `updatedAt`。
174
+ * 原子写:tmp + rename,别的进程要么看到旧版本,要么看到新版本。
175
+ */
176
+ put(scope , input ) {
177
+ const existing = this.get(scope)
178
+ const now = Date.now()
179
+ const name = input.name ?? existing?.name
180
+ const meta = {
181
+ schemaVersion: SCOPE_META_VERSION,
182
+ scope,
183
+ ...(name !== undefined ? { name } : {}),
184
+ description: input.description,
185
+ origin: scopeKind(scope),
186
+ createdBy: existing?.createdBy ?? input.createdBy,
187
+ createdAt: existing?.createdAt ?? now,
188
+ updatedAt: now,
189
+ generation: existing?.generation ?? randomUUID(),
190
+ status: input.status ?? existing?.status ?? 'ready',
191
+ }
192
+ this.write(meta)
193
+ return meta
194
+ }
195
+
196
+ /** 删除元数据(回滚未完成的初始化 / 未来的显式作用域删除)。 */
197
+ remove(scope ) {
198
+ try {
199
+ rmSync(this.fileFor(scope), { force: true })
200
+ } catch {
201
+ // 删不掉就留着;下次写入会覆盖
202
+ }
203
+ }
204
+
205
+ write(meta ) {
206
+ mkdirSync(this.dir, { recursive: true })
207
+ const file = this.fileFor(meta.scope)
208
+ const tmp = `${file}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`
209
+ writeFileSync(tmp, `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
210
+ renameSync(tmp, file)
211
+ }
212
+ }
213
+
214
+
215
+ //# sourceURL=source/memory-local/src/scope-meta.ts
@@ -784,6 +784,10 @@ export class MemoryStore {
784
784
  // 同一内容重写 = 刷新状态:TLL 重新计时;显式去掉过期时间时一并清掉。
785
785
  if (input.expiredAt !== undefined) rec.expiredAt = input.expiredAt
786
786
  else delete rec.expiredAt
787
+ // 初始化流程重试时,去重命中的旧记录也要补上 initial 来源标记。
788
+ if ((input ).initial === true) {
789
+ ;(rec ).initial = true
790
+ }
787
791
  // 流程触发词是可编辑元数据:重写同一条流程时跟着更新。
788
792
  const triggers = (input ).triggers
789
793
  if (Array.isArray(triggers)) (rec ).triggers = triggers.map(String)
@@ -809,6 +813,8 @@ export class MemoryStore {
809
813
  ...(Array.isArray((input ).triggers)
810
814
  ? { triggers: ((input ).triggers ).map(String) }
811
815
  : {}),
816
+ // 0.24.0:初始化流程创建的记录带来源标记(可选字段,旧记录缺省 = 非初始)。
817
+ ...((input ).initial === true ? { initial: true } : {}),
812
818
  }
813
819
  if (record.kind === 'state' && record.expiredAt === undefined) {
814
820
  // provider 已经按默认 TTL 算出 expiredAt;这里只兜底直接调 store 的调用方。
@@ -20,7 +20,7 @@ import {
20
20
 
21
21
 
22
22
  } from './index.js'
23
- import { renderGetResult, renderListResult, renderSearchResult } from './render.js'
23
+ import { renderGetResult, renderListResult, renderScopesResult, renderSearchResult } from './render.js'
24
24
  import { resolveCurrentScopes, scopeKind, } from '../provider/scope.js'
25
25
 
26
26
  export const name = 'dsh-tool-memory'
@@ -159,6 +159,11 @@ export function apply(ctx , config = {}) {
159
159
  return [body, summary].filter((part) => part !== '').join('\n')
160
160
  })
161
161
 
162
+ register(tools.memory_scopes, (value, _args, exec) => {
163
+ const agent = (exec )?.agent
164
+ return renderScopesResult(value, (scope) => renderScope(scope, agent))
165
+ })
166
+
162
167
  register(tools.memory_get, (value, _args, exec) => {
163
168
  const agent = (exec )?.agent
164
169
  return renderGetResult(value, (scope) => renderScope(scope, agent))