dsh-seal-scripts 0.0.0-stage → 0.4.7

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.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +318 -0
  3. package/README.md +342 -2
  4. package/cordis.patch.yml +6 -0
  5. package/index.js +12 -0
  6. package/lib/client.js +1465 -0
  7. package/lib/core/assembly.js +321 -0
  8. package/lib/core/catalog-snapshot.js +78 -0
  9. package/lib/core/diary.js +100 -0
  10. package/lib/core/health.js +72 -0
  11. package/lib/core/index.js +491 -0
  12. package/lib/core/inject.js +146 -0
  13. package/lib/core/lang.js +251 -0
  14. package/lib/core/locale.js +56 -0
  15. package/lib/core/memory-file.js +214 -0
  16. package/lib/core/migrate.js +97 -0
  17. package/lib/core/path-guard.js +43 -0
  18. package/lib/core/project-key.js +52 -0
  19. package/lib/core/render.js +228 -0
  20. package/lib/core/schema-runner.js +281 -0
  21. package/lib/core/schema-tools.js +794 -0
  22. package/lib/core/schema.js +493 -0
  23. package/lib/core/search.js +254 -0
  24. package/lib/core/settings.js +158 -0
  25. package/lib/core/store.js +408 -0
  26. package/lib/core/tool-transfer.js +249 -0
  27. package/lib/core/tool.js +602 -0
  28. package/lib/core/zip.js +226 -0
  29. package/lib/core/zstd-js.js +705 -0
  30. package/lib/core/zstd.js +103 -0
  31. package/lib/host/api.js +9 -0
  32. package/lib/host/capabilities.js +155 -0
  33. package/lib/host/compact-delete.js +76 -0
  34. package/lib/host/delete.js +136 -0
  35. package/lib/host/host-contract.js +73 -0
  36. package/lib/host/http-util.js +82 -0
  37. package/lib/host/lifecycle.js +66 -0
  38. package/lib/host/register.js +63 -0
  39. package/lib/host/routes/memories.js +102 -0
  40. package/lib/host/routes/options.js +46 -0
  41. package/lib/host/routes/sessions.js +194 -0
  42. package/lib/host/routes/tools.js +103 -0
  43. package/lib/host/summary.js +71 -0
  44. package/package.json +60 -4
@@ -0,0 +1,491 @@
1
+ /**
2
+ * dsh-seal-scripts —— 压缩即回顾。
3
+ *
4
+ * 拆 压缩一结束就把被压掉的日志拆成回顾文件(纯代码,零模型调用)
5
+ * 装 按自然日衰减,每轮重算后作为 runtime-context 快照带进上下文
6
+ * 用 工具 session_mem_read(一个线索:按顺序一条条读出来)/ session_mem_write(读那一份的对话原文 · 一次 writes 批量写关键词与日记)
7
+ * 管 设置页:会话与回顾列表、删除、删除并回顾、按日期查
8
+ */
9
+
10
+ import { homedir } from 'node:os'
11
+ import path from 'node:path'
12
+ import { captureCompaction, memoryDir } from './store.js'
13
+ import { recordHealth } from './health.js'
14
+ import { buildMemoryContextOrDiagnostic, snapshotAssembly, describeLoad } from './assembly.js'
15
+ import { diaryReminder } from './diary.js'
16
+ import { planInjection, composeInjection, memoryAlreadyInjected } from './inject.js'
17
+ import { readOptionsSync, REMINDER_SYSTEM, DEFAULT_OPTIONS, REFRESH_REALTIME } from './settings.js'
18
+ import { catalogTextForSession, refreshCatalogSnapshots } from './catalog-snapshot.js'
19
+ import { readLocaleSync } from './locale.js'
20
+ import { bumpHits } from './search.js'
21
+ import { buildReadToolDefinition, buildWriteToolDefinition, listMemories, readMemorySection, writeMemory, estimateTokens, READ_TOOL_NAME, WRITE_TOOL_NAME } from './tool.js'
22
+ import { buildToolCreateReadDefinition, buildToolCreateWriteDefinition, buildToolCallToolDefinition, catalogText } from './schema-tools.js'
23
+ import { ensureToolSequenceDir } from './schema.js'
24
+ import { installLifecycle } from '../host/lifecycle.js'
25
+ import { registerApi } from '../host/api.js'
26
+ import { deleteSessionPermanently, sessionDirOf } from '../host/delete.js'
27
+ import { probeHostFormat } from '../host/host-contract.js'
28
+ import { createCapabilityProbe, describeMissing } from '../host/capabilities.js'
29
+
30
+ /** 插件名,也是日志名。 */
31
+ export const name = 'session-recall'
32
+
33
+ /** 运行期上下文条目的标识(它产出的是一条 runtime-context 快照消息,不是系统提示词)。 */
34
+ const CONTEXT_NAME = 'session-recall:memory'
35
+
36
+ /**
37
+ * 日记提醒在系统提示词里的段名与位置。
38
+ *
39
+ * 两个通道由设置页「选项 → 概括提醒」决定:
40
+ * 「在系统侧提醒」(默认关的那一档之外)—— 本段供货,提示词里才是指令;
41
+ * 「在上下文提醒」(0.2.0 的默认档)—— 并进回顾正文(0.1.46 的做法),本段返回空串。
42
+ *
43
+ * 注意 systemPrompt.context() 不是系统提示词:它渲染成 runtime-context 快照,
44
+ * 仍然是 user 消息(renderContextSnapshot)。只有 systemPrompt.section() 进
45
+ * assembly.sections,由 renderPrompt 拼成 system/message。
46
+ *
47
+ * 位置:从 DSH 自己的排序表(@deepseek-ai/dsh-system-prompt 的 SECTION_ORDERS)
48
+ * 取最后几节里最大的序号再 +1,所以这一段永远落在系统提示词末尾、紧挨着对话。
49
+ * 不写死数字:DSH 换了排序也只跟着它走;读不到表的老宿主退到 1e9,仍然是最后。
50
+ */
51
+ const DIARY_SECTION_NAME = 'session-recall:diary'
52
+
53
+ /**
54
+ * 工具组清单在系统提示词里的段名(0.3.0)。
55
+ *
56
+ * 它跟日记提醒同一套机制:systemPrompt.section(),紧跟在日记段后面。
57
+ * 装/删工具脚本才会变,平时稳定——所以它只在工具脚本变动后的第一轮让缓存未命中一次。
58
+ */
59
+ const TOOLKIT_SECTION_NAME = 'session-recall:toolSequence'
60
+
61
+ /** DSH 排序表里排在最后面的几节(探到哪个有就用哪个的最大值)。 */
62
+ const TAIL_SECTION_NAMES = ['DEPLOYMENT_PERSONA_SUFFIX', 'WEB_SURFACE', 'HARNESS_SOURCE', 'STRUCTURED_OUTPUT']
63
+
64
+ /**
65
+ * 日记提醒段该排第几:DSH 排序表里最后一节 + 1。
66
+ * @param {object|undefined} systemPrompt ctx.systemPrompt(带 getSectionOrder)
67
+ * @returns {number}
68
+ */
69
+ export function diarySectionOrder(systemPrompt) {
70
+ let max = Number.NEGATIVE_INFINITY
71
+ try {
72
+ if (systemPrompt && typeof systemPrompt.getSectionOrder === 'function') {
73
+ for (const name of TAIL_SECTION_NAMES) {
74
+ const value = systemPrompt.getSectionOrder(name)
75
+ if (typeof value === 'number' && Number.isFinite(value)) max = Math.max(max, value)
76
+ }
77
+ }
78
+ } catch { /* 表读不到就退回兜底 */ }
79
+ return Number.isFinite(max) ? max + 1 : 1e9
80
+ }
81
+
82
+ /**
83
+ * 这一段系统提示词要用的工具组清单(0.4.5)。
84
+ * 三条分支:开关关掉给空串;realtime 每轮现算;默认档按会话冻住快照。
85
+ * 抽成独立函数是为了能被直接调用验证——注册时只包一层 catch。
86
+ * @param {string} dshHome
87
+ * @param {object|null|undefined} promptContext systemPrompt.section 的 text 回调参数
88
+ * @returns {string}
89
+ */
90
+ export function toolListSectionText(dshHome, promptContext) {
91
+ const options = readOptionsSync(dshHome)
92
+ if (options.toolListEnabled === false) return ''
93
+ const lang = readLocaleSync(dshHome)
94
+ if (options.toolListRefresh === REFRESH_REALTIME) return catalogText(dshHome, lang)
95
+ return catalogTextForSession(dshHome, lang, sessionIdOf(promptContext))
96
+ }
97
+
98
+ /**
99
+ * 从装配上下文里取会话 id(0.4.5)。拿不到就给空串,调用方据此退回现算。
100
+ * 字段名照 DSH 的会话对象:id 在 session.id,个别版本放在 session.header.id。
101
+ * @param {object|null|undefined} promptContext systemPrompt.section 的 text 回调参数
102
+ * @returns {string}
103
+ */
104
+ export function sessionIdOf(promptContext) {
105
+ try {
106
+ const session = promptContext?.agent?.session
107
+ const id = session?.id ?? session?.header?.id
108
+ return typeof id === 'string' ? id : ''
109
+ } catch {
110
+ return ''
111
+ }
112
+ }
113
+
114
+ /**
115
+ * 回顾排在其他 runtime context 条目中间:设备/沙箱信息之后、harness 信息之前。
116
+ * 参照 system-prompt 自带的 CONTEXT_ORDERS(WORKING_DIRECTORY 100 … WEB_SURFACE 210)。
117
+ */
118
+ const CONTEXT_ORDER = 150
119
+
120
+ const splitWaiters = new Map()
121
+
122
+ /**
123
+ * 这一轮要交出去的整段回顾:正文 +(「在上下文提醒」档的)日记提醒。
124
+ *
125
+ * 选项每次现读,设置页一改,下一轮就按新选项装配,不用重启插件。
126
+ * 提醒在「在系统侧提醒」档不并进来——它走 systemPrompt.section(),
127
+ * 写在用户消息里会被当成背景资料,实测一个工具都不会调。
128
+ * @param {string} dshHome
129
+ * @param {string} cwd
130
+ * @param {Date} now
131
+ * @returns {{text:string, options:object}}
132
+ */
133
+ function composeMemoryText(dshHome, cwd, now = new Date()) {
134
+ const options = readOptionsSync(dshHome)
135
+ // 总开关关掉:回顾和提醒都不进上下文(0.2.8)。工具、回顾文件、设置都还在,
136
+ // 只是这一步不再往模型那边送任何东西。
137
+ if (options.injectEnabled === false) return { text: '', options }
138
+ const memoryText = buildMemoryContextOrDiagnostic(dshHome, cwd, now, options)
139
+ const diaryText = options.reminderChannel === REMINDER_SYSTEM
140
+ ? ''
141
+ : diaryReminder(dshHome, cwd, now, options)
142
+ return { text: composeInjection(memoryText, diaryText), options }
143
+ }
144
+
145
+ /**
146
+ * 等某一轮拆解落盘:删除并回顾要在压缩之后确认文件真的写出来了。
147
+ * @param {string} sessionId
148
+ * @param {number} timeoutMs
149
+ * @returns {Promise<object>}
150
+ */
151
+ export function waitForSplitOf(sessionId, timeoutMs = 120_000) {
152
+ return new Promise((resolve, reject) => {
153
+ const timer = setTimeout(() => {
154
+ splitWaiters.get(sessionId)?.delete(done)
155
+ reject(new Error('等拆回顾超时'))
156
+ }, timeoutMs)
157
+ const done = (value) => { clearTimeout(timer); resolve(value) }
158
+ if (!splitWaiters.has(sessionId)) splitWaiters.set(sessionId, new Set())
159
+ splitWaiters.get(sessionId).add(done)
160
+ })
161
+ }
162
+
163
+ function settleSplits(sessionId, value) {
164
+ const waiting = splitWaiters.get(sessionId)
165
+ if (waiting === undefined) return
166
+ splitWaiters.delete(sessionId)
167
+ for (const done of waiting) done(value)
168
+ }
169
+
170
+ /** 会话事件是订阅,不需要声明依赖;其余服务都在 ctx.inject 子 fiber 里取。 */
171
+ export const inject = []
172
+
173
+ /**
174
+ * 解析 DSH 主目录:显式配置 > $DSH_HOME > ~/.dsh。
175
+ * @param {string|undefined} configured
176
+ * @returns {string}
177
+ */
178
+ export function resolveDshHome(configured) {
179
+ if (typeof configured === 'string' && configured.trim() !== '') return configured.trim()
180
+ const env = process.env.DSH_HOME
181
+ if (typeof env === 'string' && env.trim() !== '') return env.trim()
182
+ return path.join(homedir(), '.dsh')
183
+ }
184
+
185
+ /**
186
+ * 插件入口。
187
+ * @param {object} ctx cordis 上下文
188
+ * @param {object} config 部署配置
189
+ */
190
+ export function apply(ctx, config = {}) {
191
+ const dshHome = resolveDshHome(config.dshHome)
192
+ const logger = typeof ctx.logger === 'function' ? ctx.logger('session-recall') : console
193
+
194
+ // ── 宿主能力探测(E1):缺哪块关哪块,其余照常 ──────────────
195
+ // cordis 的 ctx.get 只看「已经就绪」的服务;apply 刚进来时宿主服务多半还没起来,
196
+ // 所以这里先探到 zstd(进程级),其余各项在各自的 inject 回调里再探、合并。
197
+ const capabilities = createCapabilityProbe(ctx)
198
+ // 只探 zstd:宿主服务此刻多半还没起来,探全表会把「还没看到」误报成「没有」。
199
+ capabilities.probe(undefined, { only: ['zstd.decompress'] })
200
+ if (capabilities.state.table['zstd.decompress'] !== true) {
201
+ logger.warn?.('当前 Node 没有 zlib.zstdDecompressSync,会话标题读不出来(回顾本身不受影响)')
202
+ void recordHealth(dshHome, '(harness)', { ok: false, code: 'host-capability', message: '当前 Node 缺 zlib.zstdDecompressSync' })
203
+ }
204
+ // 每个 inject 回调里调用:只把「这次新发现缺的」写一次日志。
205
+ const reportMissing = (opts) => {
206
+ const fresh = capabilities.probe(undefined, opts)
207
+ if (fresh.length === 0) return capabilities.state
208
+ const text = describeMissing({ missing: fresh })
209
+ logger.warn?.('宿主能力不全,相关功能已降级:' + text)
210
+ void recordHealth(dshHome, '(harness)', { ok: false, code: 'host-capability', message: text })
211
+ return capabilities.state
212
+ }
213
+ const cap = () => capabilities.state.table
214
+
215
+ // 工具组目录一启动就建好:空目录也留在 $DSH_HOME/session-memory/ 下面,看得见。
216
+ void ensureToolSequenceDir(dshHome).catch((err) => {
217
+ logger.warn?.('建工具组目录失败:' + (err?.message ?? err))
218
+ })
219
+
220
+ // ── 拆:压缩一结束就落盘 ──────────────────────────────
221
+ ctx.on('session/event', (session, event) => {
222
+ if (!event || event.type !== 'compaction/summary') return
223
+ // 「自动回顾」关着(0.3.10):连检测都不做——不落盘、不建回顾文件。
224
+ // 放在最前面:不读会话、不看工作区,压缩事件进来就退回去。
225
+ if (readOptionsSync(dshHome).autoReviewEnabled === false) return
226
+ // 子代理不拆:它们的 cwd 与主会话相同,不挡住会往主工作区的回顾里塞脏数据。
227
+ const depth = session?.header?.delegationDepth
228
+ if (typeof depth === 'number' && depth > 0) return
229
+ const cwd = session?.header?.cwd
230
+ if (typeof cwd !== 'string' || cwd === '') {
231
+ logger.warn?.('压缩事件没有工作目录,跳过:' + (session?.id ?? '?'))
232
+ return
233
+ }
234
+ void captureCompaction({ dshHome, cwd, session, event, lang: readLocaleSync(dshHome) })
235
+ .then((res) => {
236
+ if (res.skipped === true) logger.info?.('这次压缩的内容已经记过,不重复落盘:' + res.reason)
237
+ else if (res.added) logger.info?.('拆出回顾 ' + res.file + '(' + res.bytes + ' 字节)→ ' + res.dir)
238
+ else logger.info?.('回顾已存在,跳过 ' + res.file)
239
+ void recordHealth(dshHome, cwd, { ok: true, file: res.file ?? '' })
240
+ // X2:拆解成功时顺手做一次极便宜的宿主格式探测(readdir + 最多 4 字节)。
241
+ // 宿主改了会话日志格式的话,这里留下 _health.json,设置页能看见,而不是「标题突然全空」。
242
+ try {
243
+ const persistence = typeof ctx.get === 'function' ? ctx.get('sessionPersistence') : undefined
244
+ const root = persistence?.config?.root
245
+ if (typeof root === 'string' && root !== '' && typeof session.id === 'string') {
246
+ const fmt = probeHostFormat(sessionDirOf(root, cwd, session.id))
247
+ if (fmt.ok === false) {
248
+ logger.warn?.('宿主会话格式可能有变:' + fmt.detail)
249
+ void recordHealth(dshHome, cwd, { ok: false, code: 'host-format-changed', message: fmt.detail })
250
+ }
251
+ }
252
+ } catch { /* 探测失败不连累拆回顾 */ }
253
+ settleSplits(session.id, res)
254
+ })
255
+ .catch((err) => {
256
+ logger.error?.('拆回顾失败:' + (err?.stack ?? err))
257
+ // 失败必须留下痕迹:用户看不到日志,只看得到设置页。
258
+ // recordHealth 自己吞掉所有异常(它就跑在 catch 里),不会把 settleSplits 带走。
259
+ void recordHealth(dshHome, cwd, { ok: false, code: err?.code ?? 'capture-failed', message: err?.message ?? String(err) })
260
+ settleSplits(session.id, { error: err })
261
+ })
262
+ })
263
+
264
+ // 工具装载的同步函数(0.4.0):tools 作用域建好后挂上来,每步开头调一次。
265
+ const toolGate = { sync: null }
266
+
267
+ // ── 装(主通道):自己的 kind,每步重算,变了自己替换自己 ──────
268
+ // 只在「回顾还没以自己的 kind 落过」时用 runtime-context,避免同一段文字存两份。
269
+ // 这一轮已经通过 decision.messages 交出去的回顾(新会话第一轮走那条路),
270
+ // runtime-context 兜底据此让位,免得同一段文字出两份。
271
+ const pendingDecisionInject = new Set()
272
+
273
+ ctx.on('agent/pre-step', async (payload, next) => {
274
+ const decision = await next()
275
+ try {
276
+ // 0.4.0:开关可能刚被设置页改过,工具按当前开关重装一遍(幂等,没变就什么都不做)。
277
+ try { toolGate.sync?.() } catch (err) { logger.warn?.('同步工具失败:' + (err?.message ?? err)) }
278
+ if (decision === null || typeof decision !== 'object') return decision
279
+ if (decision.kind === 'reject') return decision
280
+ const session = payload?.agent?.session
281
+ const cwd = session?.header?.cwd
282
+ if (typeof cwd !== 'string' || cwd === '') return decision
283
+ if (typeof session?.id === 'string') pendingDecisionInject.delete(session.id)
284
+ const messages = Array.isArray(decision.messages) ? [...decision.messages] : []
285
+ let touched = false
286
+
287
+ // 这里只注入回顾正文(外加「在上下文提醒」档的日记提醒)。
288
+ // 提醒放在系统侧时,写在用户消息里会被当成背景资料 —— 实测两个新会话都收下了提醒
289
+ // 却一个工具都没调,她把它读成了「用户给的上下文」,回了角色台词。
290
+ const { text } = composeMemoryText(dshHome, cwd)
291
+ const plan = planInjection(session, text)
292
+ if (plan.mode === 'decision') {
293
+ // 系统提示还没落盘:交给 loop 在它之后追加,否则会排到系统提示前面。
294
+ if (typeof session?.id === 'string') pendingDecisionInject.add(session.id)
295
+ messages.push(plan.message)
296
+ touched = true
297
+ } else if (plan.mode === 'direct' && plan.result.fallbackFrom !== undefined) {
298
+ logger.warn?.('回顾替换失败,退回追加:' + plan.result.fallbackFrom)
299
+ }
300
+
301
+ if (touched) return { ...decision, messages }
302
+ } catch (err) {
303
+ logger.error?.('回顾注入失败(本轮退回 runtime-context):' + (err?.stack ?? err))
304
+ }
305
+ return decision
306
+ })
307
+
308
+ // ── 装(兜底):只有在主通道还没落过时才供货 ──────────────
309
+ ctx.inject(['systemPrompt'], (scope) => {
310
+ reportMissing({ only: ['systemPrompt.context', 'systemPrompt.section', 'systemPrompt.getSectionOrder'] })
311
+ if (cap()['systemPrompt.context'] !== true) logger.warn?.('宿主没有 systemPrompt.context(),回顾注入已关闭')
312
+ if (cap()['systemPrompt.context'] === true) scope.systemPrompt.context({
313
+ name: CONTEXT_NAME,
314
+ order: CONTEXT_ORDER,
315
+ interpolate: false,
316
+ text: (promptContext) => {
317
+ const session = promptContext?.agent?.session
318
+ const cwd = session?.header?.cwd
319
+ if (typeof cwd !== 'string' || cwd === '') return ''
320
+ try {
321
+ if (memoryAlreadyInjected(session)) return ''
322
+ // 本轮已经交给 decision.messages 了:等 loop 追加完就算注入过。
323
+ if (typeof session?.id === 'string' && pendingDecisionInject.has(session.id)) return ''
324
+ } catch { /* 判断不了就当没注入过:宁可多一份,也不让回顾断供 */ }
325
+ return composeMemoryText(dshHome, cwd).text
326
+ }
327
+ })
328
+
329
+ // 日记提醒:系统提示词段。只有「概括提醒 = 在系统侧提醒」时供货;
330
+ // 另一档(默认)把它并进回顾正文,这里返回空串,renderPrompt 会把这个段整个滤掉。
331
+ if (cap()['systemPrompt.section'] !== true) logger.warn?.('宿主没有 systemPrompt.section(),日记提醒与工具组清单不出现')
332
+ if (cap()['systemPrompt.section'] === true) scope.systemPrompt.section({
333
+ name: DIARY_SECTION_NAME,
334
+ order: diarySectionOrder(scope.systemPrompt),
335
+ interpolate: false,
336
+ text: (promptContext) => {
337
+ const session = promptContext?.agent?.session
338
+ const cwd = session?.header?.cwd
339
+ if (typeof cwd !== 'string' || cwd === '') return ''
340
+ // 子代理不管日记:它们和主会话同一个工作目录,催了只会替主会话乱写。
341
+ const depth = session?.header?.delegationDepth
342
+ if (typeof depth === 'number' && depth > 0) return ''
343
+ try {
344
+ const options = readOptionsSync(dshHome)
345
+ // 总开关关掉:系统侧提醒段也不再供货(0.2.8)。
346
+ if (options.injectEnabled === false) return ''
347
+ if (options.reminderChannel !== REMINDER_SYSTEM) return ''
348
+ return diaryReminder(dshHome, cwd, new Date(), options)
349
+ } catch (err) {
350
+ logger.error?.('日记提醒失败:' + (err?.stack ?? err))
351
+ return ''
352
+ }
353
+ }
354
+ })
355
+
356
+ // 工具组清单(0.3.0):紧跟日记段之后。
357
+ // 0.3.1 起它有自己的开关 toolListEnabled:总开关只关回顾正文与日记提醒(B、C),
358
+ // 不连坐这一段(A)——选项页「工具固存」这一类单独管它。
359
+ // 0.4.5:多一个「清单词刷新时刻」。默认 newSession 按会话冻住快照,会话中途装/删工具
360
+ // 脚本不改系统提示词;realtime 才是 0.4.4 及以前的行为(每轮现算)。
361
+ if (cap()['systemPrompt.section'] === true) scope.systemPrompt.section({
362
+ name: TOOLKIT_SECTION_NAME,
363
+ order: diarySectionOrder(scope.systemPrompt) + 1,
364
+ interpolate: false,
365
+ text: (promptContext) => {
366
+ try {
367
+ return toolListSectionText(dshHome, promptContext)
368
+ } catch (err) {
369
+ logger.error?.('工具组清单失败:' + (err?.stack ?? err))
370
+ return ''
371
+ }
372
+ }
373
+ })
374
+ })
375
+
376
+ // ── 用:读对话原文 / 一次 writes 批量写关键词与日记 ────────────────────
377
+ ctx.inject(['tools'], (scope) => {
378
+ reportMissing({ only: ['tools.register'] })
379
+ if (cap()['tools.register'] !== true) {
380
+ logger.warn?.('宿主没有 tools.register(),回顾工具不装')
381
+ return
382
+ }
383
+ // 深度只在「read 工具真的把本工作区自己那份回顾读出去」时加一级,由插件侧记账:
384
+ // 0 -> 1 并锁定,1 -> 2 并锁定,2 或 3 不动。子级/平级/上级读了也不计。
385
+ const countHit = async (res) => {
386
+ if (res === null || res === undefined || res.local !== true || res.hitCount === 0) return
387
+ try {
388
+ await bumpHits(memoryDir(dshHome, res.workspace), res.workspace, res.hits.map((h) => h.file), new Date())
389
+ } catch (err) {
390
+ logger.error?.('回顾深度失败:' + (err?.stack ?? err))
391
+ }
392
+ }
393
+ // 0.4.0:两组工具分别跟着两个开关走,按需装载。
394
+ // 「自动回顾」开 → 拆/读回顾有用,装 mem 两个(读原文、写日记与关键词);
395
+ // 「注入工具组清单」开 → 工具组这条路有用,装 tool 三个(读原文、装脚本、跑脚本)。
396
+ // 两个都关 = 这个插件在这台机器上不提供任何工具(回顾不拆、清单不注入,本来就没事可做)。
397
+ const memTools = [
398
+ buildReadToolDefinition({ dshHome, onHit: countHit }),
399
+ buildWriteToolDefinition({ dshHome })
400
+ ]
401
+ // 0.3.3:读原文(session_tool_create_read)与装工具脚本(session_tool_create_write)拆成两个工具;
402
+ // 跑工具脚本仍是 session_tool_call。
403
+ const kitTools = [
404
+ buildToolCreateReadDefinition({ dshHome, logger }),
405
+ buildToolCreateWriteDefinition({ dshHome, logger }),
406
+ buildToolCallToolDefinition({ dshHome, logger })
407
+ ]
408
+ const live = new Map()
409
+
410
+ /**
411
+ * 按当前选项把工具装到与开关一致的状态。幂等:已经对上了就什么都不做。
412
+ * @returns {string[]} 当前装载的工具名
413
+ */
414
+ function syncTools() {
415
+ let options
416
+ try {
417
+ options = readOptionsSync(dshHome)
418
+ } catch {
419
+ options = DEFAULT_OPTIONS
420
+ }
421
+ const want = new Map()
422
+ if (options.autoReviewEnabled !== false) for (const d of memTools) want.set(d.name, d)
423
+ if (options.toolListEnabled !== false) for (const d of kitTools) want.set(d.name, d)
424
+ for (const [name, off] of [...live]) {
425
+ if (want.has(name)) continue
426
+ try { off() } catch (err) { logger.warn?.('卸载工具失败:' + name + ' ' + (err?.message ?? err)) }
427
+ live.delete(name)
428
+ logger.info?.('工具已卸载:' + name)
429
+ }
430
+ for (const [name, definition] of want) {
431
+ if (live.has(name)) continue
432
+ const off = scope.tools.register(definition)
433
+ live.set(name, typeof off === 'function' ? off : () => {})
434
+ logger.info?.('工具已装载:' + name)
435
+ }
436
+ return [...want.keys()]
437
+ }
438
+
439
+ toolGate.sync = syncTools
440
+ syncTools()
441
+ })
442
+
443
+ // ── 管:设置页用的 HTTP 端点 + 删除所需的生命周期捕获 ──
444
+ ctx.inject(['webServer', 'connection', 'agents'], (webCtx) => {
445
+ reportMissing({ only: ['webServer.register', 'connection.requestRejection', 'agents.create', 'agents.resume'] })
446
+ if (cap()['webServer.register'] !== true) {
447
+ logger.warn?.('宿主没有 webServer.register(),设置页接口不装')
448
+ return
449
+ }
450
+ // 缺 agents 的公开 create/resume 时:不装生命周期捕获(以前在这里 throw,
451
+ // 症状是设置页那半块整个没加载),只关掉「删除活会话 / 删除并回顾」;
452
+ // 列表与回顾管理照常——它们只依赖 persistence 与文件系统。
453
+ const canLifecycle = cap()['agents.create'] === true && cap()['agents.resume'] === true
454
+ if (canLifecycle) webCtx.effect(() => installLifecycle(webCtx.agents, logger), 'dsh-seal-scripts: 生命周期捕获')
455
+ else logger.warn?.('宿主缺 agents.create/resume,删除活会话与「删除并回顾」已关闭')
456
+ const getDeps = () => ({
457
+ persistence: webCtx.get('sessionPersistence'),
458
+ sessions: webCtx.get('sessions'),
459
+ agents: webCtx.get('agents'),
460
+ workspaceRegistry: webCtx.get('workspaceRegistry'),
461
+ compaction: webCtx.get('compaction')
462
+ })
463
+ // 0.4.1:选项一落盘就同步工具,赶在下一次 systemPrompt.assemble() 之前。
464
+ // 0.4.6:切「清单词刷新时刻」那一下,把所有已记住的会话刷新成此刻的现词。
465
+ registerApi(webCtx, {
466
+ dshHome, getDeps, waitForSplit: waitForSplitOf, onOptionsChanged: () => toolGate.sync?.(),
467
+ onToolListRefreshChanged: () => { refreshCatalogSnapshots(dshHome, readLocaleSync(dshHome)) },
468
+ canLifecycle, probe: () => capabilities.snapshot()
469
+ })
470
+ })
471
+ }
472
+
473
+ export {
474
+ captureCompaction, memoryDir, buildMemoryContextOrDiagnostic, snapshotAssembly, describeLoad, diaryReminder,
475
+ buildReadToolDefinition, buildWriteToolDefinition, listMemories, readMemorySection, writeMemory, estimateTokens, READ_TOOL_NAME, WRITE_TOOL_NAME,
476
+ deleteSessionPermanently
477
+ }
478
+
479
+ // 选项:设置页读写与注入路径共用同一套默认值与收紧规则。
480
+ export { DEFAULT_OPTIONS, FOLLOW_DEPTH, REMINDER_CONTEXT, REMINDER_SYSTEM, OPTIONS_FILE, optionsPath, normalizeOptions, applyAutoReview, readOptionsSync, writeOptions } from './settings.js'
481
+
482
+ // 语言:只跟 DSH 设置;文件里的中文标记是通配键,显示时按语言换字。
483
+ export { LOCALE_FILE, localePath, readLocaleSync, writeLocale } from './locale.js'
484
+ export { LANG_ZH, LANG_EN, normalizeLang, phrasesFor, localizeBody, isBlankDiary, isBlankKeywords } from './lang.js'
485
+
486
+ // 旧名继续可用:直接调用会抛;注入路径走 OrDiagnostic 版,失败时给出「回顾过大」诊断。
487
+ export { buildMemoryContext } from './assembly.js'
488
+ export { loadLevel, effectiveCount } from './assembly.js'
489
+ export { pendingDiaries } from './diary.js'
490
+ export { injectMemory, planInjection, composeInjection, needsDecisionPath, memoryAlreadyInjected, memoryNodeOnSurface, memoryMessage, MEMORY_SOURCE_KIND } from './inject.js'
491
+ export { listCandidates, knownWorkspaces, expansionOrder } from './search.js'
@@ -0,0 +1,146 @@
1
+ /**
2
+ * 回顾的注入通道:走自己的 kind,不走 runtime-context 快照。
3
+ *
4
+ * 为什么另起一条:runtime-context 快照归 agent-loop 所有,它只在文本变化时
5
+ * **追加**一条新快照,旧的要等下一次压缩的 replace 才被吞掉。实测一个会话里
6
+ * 同时挂着两份、合计 7.7 万字。自己起 kind 就能在文本变化时替换掉自己上一条,
7
+ * surface 上永远只有一份,而且是当场最新的那份。
8
+ */
9
+
10
+ import { randomUUID } from 'node:crypto'
11
+
12
+ /** 消息来源标识。GUI 把非 user 的 kind 都当「上下文」块渲染,不会变成用户气泡。 */
13
+ export const MEMORY_SOURCE_KIND = 'session-recall'
14
+
15
+ /** 分区名,写进 source.sections,方便以后按分区定位。 */
16
+ export const MEMORY_SECTION = 'session-recall:memory'
17
+
18
+ /**
19
+ * 拼一条模型侧的 user 消息。形状与 dsh-llm 的 createUserMessage 一致
20
+ * (role + id + content + source),全部是普通 JSON,能被 session.append 快照。
21
+ * @param {string} text
22
+ */
23
+ export function memoryMessage(text) {
24
+ const value = String(text ?? '')
25
+ return {
26
+ id: randomUUID(),
27
+ role: 'user',
28
+ content: [{ type: 'text', text: value }],
29
+ source: { kind: MEMORY_SOURCE_KIND, form: 'snapshot', sections: [{ name: MEMORY_SECTION, text: value }] }
30
+ }
31
+ }
32
+
33
+ /**
34
+ * 把回顾正文与日记提醒拼成同一条消息。
35
+ * 「概括提醒 = 在上下文提醒」时用它:提醒并进回顾正文(0.1.46 的做法),
36
+ * 日记写完 -> 正文不再带提醒 -> 整条被 replace -> 催促自动消失。
37
+ * 设置页预览也调它,保证框里和实况字字相同。
38
+ * @param {string} memoryText
39
+ * @param {string} diaryText
40
+ * @returns {string}
41
+ */
42
+ export function composeInjection(memoryText, diaryText) {
43
+ const memory = String(memoryText ?? '').trim()
44
+ const diary = String(diaryText ?? '').trim()
45
+ if (diary === '') return memory
46
+ if (memory === '') return diary
47
+ return memory + '\n\n' + diary
48
+ }
49
+
50
+ /** 这条消息是不是我们注入的。 */
51
+ export function isMemorySource(source) {
52
+ return source !== null && typeof source === 'object' && source.kind === MEMORY_SOURCE_KIND
53
+ }
54
+
55
+ /** 取一条消息的纯文本;不是「恰好一个 text 块」就给空串。 */
56
+ function textOf(message) {
57
+ const content = message?.content
58
+ if (!Array.isArray(content) || content.length !== 1) return ''
59
+ return typeof content[0]?.text === 'string' ? content[0].text : ''
60
+ }
61
+
62
+ /**
63
+ * surface 上我们注入的那一条(最新的一条);没有就是 null。
64
+ * 只看 surface,不看整本日志 —— 被压缩吞掉的旧条目不算数。
65
+ * @returns {null | {seq:number, text:string}}
66
+ */
67
+ export function memoryNodeOnSurface(session) {
68
+ const nodes = session?.surface?.nodes
69
+ if (!Array.isArray(nodes)) return null
70
+ for (let i = nodes.length - 1; i >= 0; i -= 1) {
71
+ const seq = nodes[i]
72
+ const event = session.eventAt(seq)
73
+ if (event === undefined || event === null) continue
74
+ if (event.type !== 'user/message') continue
75
+ if (!isMemorySource(event.data?.source)) continue
76
+ return { seq, text: textOf(event.data) }
77
+ }
78
+ return null
79
+ }
80
+
81
+ /** 回顾已经以自己的 kind 注入了吗(runtime-context 兜底那条据此决定要不要供货)。 */
82
+ export function memoryAlreadyInjected(session) {
83
+ return memoryNodeOnSurface(session) !== null
84
+ }
85
+
86
+ /**
87
+ * surface 上还没有系统提示吗?
88
+ *
89
+ * 系统提示是 agent-loop 在 step() 里提交的,而 pre-step 跑在它之前。所以全新会话
90
+ * 的第一轮如果这时直接 session.append,消息会排在系统提示**前面**,请求就变成
91
+ * [user, system, …]。这种时候必须把消息交给 decision.messages,让 loop 在系统
92
+ * 提示之后统一追加。
93
+ */
94
+ export function needsDecisionPath(session) {
95
+ const nodes = session?.surface?.nodes
96
+ if (!Array.isArray(nodes)) return false
97
+ for (const seq of nodes) {
98
+ if (session.eventAt(seq)?.type === 'system/message') return false
99
+ }
100
+ return true
101
+ }
102
+
103
+ /**
104
+ * 这一步该怎么注入:没文字就跳过;系统提示还没落盘就走 decision.messages;其余直接写。
105
+ * @param {object} session
106
+ * @param {string} text
107
+ * @returns {{mode:'skip'} | {mode:'decision', message:object} | {mode:'direct', result:object}}
108
+ */
109
+ export function planInjection(session, text) {
110
+ const value = String(text ?? '')
111
+ if (value === '') return { mode: 'skip' }
112
+ if (session === null || typeof session !== 'object') return { mode: 'skip' }
113
+ if (needsDecisionPath(session)) return { mode: 'decision', message: memoryMessage(value) }
114
+ return { mode: 'direct', result: injectMemory(session, value) }
115
+ }
116
+
117
+ /**
118
+ * 注入一条回顾:
119
+ * 文本没变 -> 不动;变了 -> 替换掉自己上一条;换不了 -> 追加。
120
+ * 更换失败(上一条已被压缩吞掉、或宿主拒绝替换)不能变成「这一轮没有回顾」。
121
+ * @param {object} session
122
+ * @param {string} text
123
+ * @returns {{action:'skip'|'append'|'replace', seq?:number, fallbackFrom?:string}}
124
+ */
125
+ export function injectMemory(session, text) {
126
+ const value = String(text ?? '')
127
+ if (session === null || typeof session !== 'object' || typeof session.append !== 'function') {
128
+ throw new Error('没有可写入的会话')
129
+ }
130
+ const previous = memoryNodeOnSurface(session)
131
+ if (previous !== null && previous.text === value) return { action: 'skip', seq: previous.seq }
132
+ if (previous !== null) {
133
+ try {
134
+ const event = session.append('user/message', memoryMessage(value), {
135
+ surfaceOp: { op: 'replace', startSeq: previous.seq, endSeq: previous.seq },
136
+ sourceEventSeqs: [previous.seq]
137
+ })
138
+ return { action: 'replace', seq: event.seq }
139
+ } catch (error) {
140
+ const event = session.append('user/message', memoryMessage(value), { surfaceOp: 'append' })
141
+ return { action: 'append', seq: event.seq, fallbackFrom: error?.message ?? String(error) }
142
+ }
143
+ }
144
+ const event = session.append('user/message', memoryMessage(value), { surfaceOp: 'append' })
145
+ return { action: 'append', seq: event.seq }
146
+ }