dsh-seal-scripts 0.0.0-stage → 0.4.8
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/LICENSE +21 -0
- package/README.en.md +318 -0
- package/README.md +342 -2
- package/cordis.patch.yml +6 -0
- package/index.js +12 -0
- package/lib/client.js +1465 -0
- package/lib/core/assembly.js +321 -0
- package/lib/core/catalog-snapshot.js +78 -0
- package/lib/core/diary.js +100 -0
- package/lib/core/health.js +72 -0
- package/lib/core/index.js +491 -0
- package/lib/core/inject.js +146 -0
- package/lib/core/lang.js +251 -0
- package/lib/core/locale.js +56 -0
- package/lib/core/memory-file.js +214 -0
- package/lib/core/migrate.js +97 -0
- package/lib/core/path-guard.js +43 -0
- package/lib/core/project-key.js +52 -0
- package/lib/core/render.js +228 -0
- package/lib/core/schema-runner.js +281 -0
- package/lib/core/schema-tools.js +794 -0
- package/lib/core/schema.js +493 -0
- package/lib/core/search.js +254 -0
- package/lib/core/settings.js +158 -0
- package/lib/core/store.js +408 -0
- package/lib/core/tool-transfer.js +249 -0
- package/lib/core/tool.js +602 -0
- package/lib/core/zip.js +226 -0
- package/lib/core/zstd-js.js +705 -0
- package/lib/core/zstd.js +103 -0
- package/lib/host/api.js +9 -0
- package/lib/host/capabilities.js +155 -0
- package/lib/host/compact-delete.js +76 -0
- package/lib/host/delete.js +136 -0
- package/lib/host/host-contract.js +73 -0
- package/lib/host/http-util.js +82 -0
- package/lib/host/lifecycle.js +66 -0
- package/lib/host/register.js +63 -0
- package/lib/host/routes/memories.js +102 -0
- package/lib/host/routes/options.js +46 -0
- package/lib/host/routes/sessions.js +194 -0
- package/lib/host/routes/tools.js +103 -0
- package/lib/host/summary.js +71 -0
- package/package.json +71 -4
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 落盘:目录布局、原子写、载入索引(每份回顾一个 .json 边车)。
|
|
3
|
+
*
|
|
4
|
+
* 目录:$DSH_HOME/session-memory/<工作区 key>/
|
|
5
|
+
* <stem>.json 载入索引的缓存(.md 才是唯一真相)
|
|
6
|
+
* 20261028-055942-96358e1b.md 一份压缩一份回顾
|
|
7
|
+
* _assembly.json.migrated-* 旧版单文件索引的迁移遗留(永不自动删)
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import fs from 'node:fs/promises'
|
|
11
|
+
import fsSync from 'node:fs'
|
|
12
|
+
import path from 'node:path'
|
|
13
|
+
import { projectKey } from './project-key.js'
|
|
14
|
+
import { buildMemoryFile, fileStemOf, parseMemory } from './memory-file.js'
|
|
15
|
+
import { renderTranscript, countTools } from './render.js'
|
|
16
|
+
import { sidecarName, listSidecars, listMemoryFiles, migrateIndex } from './migrate.js'
|
|
17
|
+
|
|
18
|
+
const ASSEMBLY_VERSION = 2
|
|
19
|
+
|
|
20
|
+
/** 回顾根目录。 */
|
|
21
|
+
export function memoryRoot(dshHome) {
|
|
22
|
+
return path.join(dshHome, 'session-memory')
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 某个工作区的回顾目录。 */
|
|
26
|
+
export function memoryDir(dshHome, cwd) {
|
|
27
|
+
return path.join(memoryRoot(dshHome), projectKey(cwd))
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 把内容块数组里的纯文本取出来。 */
|
|
31
|
+
function blocksText(blocks) {
|
|
32
|
+
if (!Array.isArray(blocks)) return ''
|
|
33
|
+
return blocks.filter((b) => b && b.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n')
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const RETRYABLE_RENAME = new Set(['EPERM', 'EBUSY', 'EACCES', 'ENOTEMPTY'])
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 把临时文件改名到目标。POSIX 上 rename 覆盖是原子的;Windows 上目标被别的句柄
|
|
40
|
+
* (杀毒、索引、并发写)占用时会抛 EPERM/EBUSY/EACCES,所以先退避重试,
|
|
41
|
+
* 实在不行才走"先删目标再改名"。
|
|
42
|
+
*
|
|
43
|
+
* 单独导出:批量写要自己造临时文件名(好在 finally 里清理残留),重试逻辑只有这一份。
|
|
44
|
+
* @param {string} tmp 已经写好的临时文件
|
|
45
|
+
* @param {string} file 目标路径
|
|
46
|
+
*/
|
|
47
|
+
export async function renameWithRetry(tmp, file) {
|
|
48
|
+
let lastError = null
|
|
49
|
+
for (let attempt = 0; attempt < 6; attempt++) {
|
|
50
|
+
try {
|
|
51
|
+
await fs.rename(tmp, file)
|
|
52
|
+
return
|
|
53
|
+
} catch (err) {
|
|
54
|
+
if (!RETRYABLE_RENAME.has(err.code)) {
|
|
55
|
+
await fs.rm(tmp, { force: true }).catch(() => {})
|
|
56
|
+
throw err
|
|
57
|
+
}
|
|
58
|
+
lastError = err
|
|
59
|
+
await new Promise((r) => setTimeout(r, 12 * (attempt + 1)))
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
// 还不行:删掉目标再改名(这一刻短暂失去原子性,只发生在失败路径)
|
|
63
|
+
try {
|
|
64
|
+
await fs.rm(file, { force: true })
|
|
65
|
+
await fs.rename(tmp, file)
|
|
66
|
+
} catch (err) {
|
|
67
|
+
await fs.rm(tmp, { force: true }).catch(() => {})
|
|
68
|
+
throw lastError ?? err
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 原子写:同目录临时文件 + renameWithRetry,避免读到半个文件。 */
|
|
73
|
+
export async function writeFileAtomic(file, content) {
|
|
74
|
+
const dir = path.dirname(file)
|
|
75
|
+
const tmp = path.join(dir, path.basename(file) + '.tmp-' + process.pid + '-' + Math.random().toString(36).slice(2, 10))
|
|
76
|
+
await fs.writeFile(tmp, content, 'utf8')
|
|
77
|
+
await renameWithRetry(tmp, file)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 读载入清单。
|
|
82
|
+
*
|
|
83
|
+
* 不变量:**磁盘上的 .md 就是清单**。边车只是它的缓存:
|
|
84
|
+
* · 有 .md、没边车 → 用文件 mtime 当 compactedAt,count 3、未锁定,**当场补写边车**;
|
|
85
|
+
* · 有边车、没 .md → 这份已经不存在了,**顺手清掉边车**(进程被杀留下的半截状态)。
|
|
86
|
+
* 于是「条目在、文件没了」「文件没了、条目又回来」这两类事故在结构上不可能发生。
|
|
87
|
+
*
|
|
88
|
+
* ⚠ 这个「读」带副作用:会补边车、清孤儿边车、顺手做旧索引迁移。
|
|
89
|
+
* 副作用全部 catch 掉——补写失败不影响读出来的内容。
|
|
90
|
+
*
|
|
91
|
+
* @returns {Promise<{version:number, workspace:string, entries:object[]}>}
|
|
92
|
+
*/
|
|
93
|
+
export async function readAssembly(dir, workspace) {
|
|
94
|
+
// 旧版单文件索引只迁一次;失败也不要紧:下面扫 .md 仍然读得出来。
|
|
95
|
+
try { await migrateIndex(dir, workspace) } catch { /* 迁移失败就有多少读多少 */ }
|
|
96
|
+
const entries = []
|
|
97
|
+
const sidecars = listSidecars(dir)
|
|
98
|
+
for (const file of listMemoryFiles(dir)) {
|
|
99
|
+
const want = sidecarName(file)
|
|
100
|
+
let one = null
|
|
101
|
+
if (sidecars.has(want)) {
|
|
102
|
+
try { one = JSON.parse(await fs.readFile(path.join(dir, want), 'utf8')) } catch { one = null }
|
|
103
|
+
}
|
|
104
|
+
if (one === null || one.file !== file) {
|
|
105
|
+
// 没边车 / 边车坏了:按文件自己的 mtime 补一份,不猜内容
|
|
106
|
+
let stat
|
|
107
|
+
try { stat = await fs.stat(path.join(dir, file)) } catch { continue }
|
|
108
|
+
one = {
|
|
109
|
+
version: 2, workspace, file,
|
|
110
|
+
compactedAt: new Date(stat.mtimeMs).toISOString(),
|
|
111
|
+
count: 3, pinned: false, seqStart: null, seqEnd: null, recoveredFrom: 'mtime'
|
|
112
|
+
}
|
|
113
|
+
await writeEntry(dir, workspace, one).catch(() => {})
|
|
114
|
+
}
|
|
115
|
+
entries.push({
|
|
116
|
+
file: one.file,
|
|
117
|
+
compactedAt: String(one.compactedAt),
|
|
118
|
+
count: typeof one.count === 'number' ? one.count : 3,
|
|
119
|
+
pinned: one.pinned === true,
|
|
120
|
+
seqStart: one.seqStart ?? null,
|
|
121
|
+
seqEnd: one.seqEnd ?? null
|
|
122
|
+
})
|
|
123
|
+
}
|
|
124
|
+
// 孤儿边车:.md 已经不在了,清掉
|
|
125
|
+
const alive = new Set(listMemoryFiles(dir).map(sidecarName))
|
|
126
|
+
for (const name of sidecars) {
|
|
127
|
+
if (!alive.has(name)) await fs.rm(path.join(dir, name), { force: true }).catch(() => {})
|
|
128
|
+
}
|
|
129
|
+
return { version: ASSEMBLY_VERSION, workspace, entries }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 同步读同一份清单(注入路径要同步求值,不能 await)。
|
|
134
|
+
* 只读:不补边车、不清孤儿;缺边车时按 .md 自己的 mtime 顶一下。
|
|
135
|
+
*/
|
|
136
|
+
export function readAssemblySync(dir, workspace) {
|
|
137
|
+
const entries = []
|
|
138
|
+
const sidecars = listSidecars(dir)
|
|
139
|
+
for (const file of listMemoryFiles(dir)) {
|
|
140
|
+
const want = sidecarName(file)
|
|
141
|
+
let one = null
|
|
142
|
+
if (sidecars.has(want)) {
|
|
143
|
+
try { one = JSON.parse(fsSync.readFileSync(path.join(dir, want), 'utf8')) } catch { one = null }
|
|
144
|
+
}
|
|
145
|
+
if (one === null || one.file !== file) {
|
|
146
|
+
let stat
|
|
147
|
+
try { stat = fsSync.statSync(path.join(dir, file)) } catch { continue }
|
|
148
|
+
one = {
|
|
149
|
+
version: 2, workspace, file,
|
|
150
|
+
compactedAt: new Date(stat.mtimeMs).toISOString(),
|
|
151
|
+
count: 3, pinned: false, seqStart: null, seqEnd: null, recoveredFrom: 'mtime'
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
entries.push({
|
|
155
|
+
file: one.file,
|
|
156
|
+
compactedAt: String(one.compactedAt),
|
|
157
|
+
count: typeof one.count === 'number' ? one.count : 3,
|
|
158
|
+
pinned: one.pinned === true,
|
|
159
|
+
seqStart: one.seqStart ?? null,
|
|
160
|
+
seqEnd: one.seqEnd ?? null
|
|
161
|
+
})
|
|
162
|
+
}
|
|
163
|
+
return { version: ASSEMBLY_VERSION, workspace, entries }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 写一份边车(原子)。只碰这一份,不需要锁。 */
|
|
167
|
+
export async function writeEntry(dir, workspace, entry) {
|
|
168
|
+
await fs.mkdir(dir, { recursive: true })
|
|
169
|
+
await writeFileAtomic(path.join(dir, sidecarName(entry.file)), JSON.stringify({
|
|
170
|
+
version: 2, workspace,
|
|
171
|
+
file: entry.file,
|
|
172
|
+
compactedAt: entry.compactedAt,
|
|
173
|
+
count: typeof entry.count === 'number' ? entry.count : 3,
|
|
174
|
+
pinned: entry.pinned === true,
|
|
175
|
+
seqStart: entry.seqStart ?? null,
|
|
176
|
+
seqEnd: entry.seqEnd ?? null,
|
|
177
|
+
updatedAt: new Date().toISOString()
|
|
178
|
+
}, null, 2) + '\n')
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** 删一份边车(删 .md 之后调)。 */
|
|
182
|
+
export async function removeEntry(dir, file) {
|
|
183
|
+
await fs.rm(path.join(dir, sidecarName(file)), { force: true })
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* 记一条新回顾:边车已存在就不写(幂等)。
|
|
188
|
+
* 以前这里要进目录锁读-改-写整份清单;现在只碰这一份。
|
|
189
|
+
* @returns {Promise<{entry: object, added: boolean}>}
|
|
190
|
+
*/
|
|
191
|
+
export async function upsertEntry(dir, workspace, entry) {
|
|
192
|
+
const file = path.join(dir, sidecarName(entry.file))
|
|
193
|
+
if (fsSync.existsSync(file)) {
|
|
194
|
+
try { return { entry: JSON.parse(await fs.readFile(file, 'utf8')), added: false } } catch { /* 坏边车:重写 */ }
|
|
195
|
+
}
|
|
196
|
+
await writeEntry(dir, workspace, entry)
|
|
197
|
+
return { entry, added: true }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* 一次压缩 -> 一份回顾文件 + 一条载入条目。
|
|
202
|
+
*
|
|
203
|
+
* 纯代码,零模型调用:摘要来自 compaction/summary 事件,原文由被压掉的会话事件渲染。
|
|
204
|
+
* @param {object} args
|
|
205
|
+
* @param {string} args.dshHome
|
|
206
|
+
* @param {string} args.cwd 会话的工作目录
|
|
207
|
+
* @param {object} args.session 会话对象(要能按 seq 取事件)
|
|
208
|
+
* @param {object} args.event compaction/summary 事件
|
|
209
|
+
* @returns {Promise<{file:string, dir:string, entry:object, added:boolean, bytes:number}>}
|
|
210
|
+
*/
|
|
211
|
+
/** 补齐边界之后那段时收哪些事件;只挑对话类,不把 step/turn 边界算进条数。 */
|
|
212
|
+
const TAIL_TYPES = new Set(['user/message', 'assistant/message', 'tool/call', 'tool/result'])
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* PTC 的内层调用:代码里 tools.xxx(...) 的那一次。
|
|
216
|
+
*
|
|
217
|
+
* 它们不在 shadowedSeqs 里(DSH 只列表面事件),只能按 shadowedRange 逐 seq 捞。
|
|
218
|
+
* 两种都收:start 写「发起」(参数在这一头,执行中断没有 dispatch 时也不丢),
|
|
219
|
+
* dispatch 只写「结果 + 成败」(发起已在 start 写过,不重复)。
|
|
220
|
+
* 两者 arguments 实测 1,633 对零差异,所以参数只取 start 那份。
|
|
221
|
+
*/
|
|
222
|
+
const PTC_TYPES = new Set(['tool/ptc-dispatch-start', 'tool/ptc-dispatch'])
|
|
223
|
+
|
|
224
|
+
/** 正文第一条非空行在整份文件里的位置(0 基):正文行号换算成整份文件的行号要用。 */
|
|
225
|
+
function bodyStartIndex(allLines) {
|
|
226
|
+
const at = allLines.findIndex((l) => l.includes(':body-->'))
|
|
227
|
+
if (at === -1) return 0
|
|
228
|
+
for (let i = at + 1; i < allLines.length; i++) {
|
|
229
|
+
const line = allLines[i].trim()
|
|
230
|
+
if (line === '' || line.startsWith('## ')) continue
|
|
231
|
+
return i
|
|
232
|
+
}
|
|
233
|
+
return at
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* 读工作区里已有回顾的正文,判断「这次要写的开头有多少已经记过」要用它。
|
|
238
|
+
* 同名文件要排除:那是本次即将写入的那一份,自己跟自己比永远全重合。
|
|
239
|
+
* @returns {Promise<{file:string, lines:string[], start:number}[]>}
|
|
240
|
+
*/
|
|
241
|
+
async function existingBodies(dir, cwd, excludeFile) {
|
|
242
|
+
const data = await readAssembly(dir, cwd)
|
|
243
|
+
const out = []
|
|
244
|
+
for (const entry of data.entries) {
|
|
245
|
+
if (entry.file === excludeFile) continue
|
|
246
|
+
let raw
|
|
247
|
+
try {
|
|
248
|
+
raw = await fs.readFile(path.join(dir, entry.file), 'utf8')
|
|
249
|
+
} catch {
|
|
250
|
+
continue
|
|
251
|
+
}
|
|
252
|
+
const all = raw.split('\n')
|
|
253
|
+
const body = parseMemory(raw).sections.body
|
|
254
|
+
out.push({ file: entry.file, lines: body === '' ? [] : body.split('\n'), start: bodyStartIndex(all) })
|
|
255
|
+
}
|
|
256
|
+
return out
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* 候选正文的开头有多少行已经记在别的回顾里。
|
|
261
|
+
*
|
|
262
|
+
* 判据是内容,不是 seq:seq 是每条会话自己的编号。复刻出来的会话与本体共享一段历史,
|
|
263
|
+
* 编号与内容都相同;fork 之后同一串编号指的东西已经不一样了。按内容对齐没有这个问题。
|
|
264
|
+
* 一份回顾存一段连续内容,所以从候选第一行起在每份回顾里找能接上的一段,匹配多长跳过多长,
|
|
265
|
+
* 跨几份回顾可以接着往下对。
|
|
266
|
+
* @param {string[]} candLines 候选正文行(原文形态,与 parseMemory 还原后的一致)
|
|
267
|
+
* @param {{file:string, lines:string[], start:number}[]} files 已有回顾
|
|
268
|
+
* @returns {{covered:number, anchors:{file:string, line:number, end:number}[]}}
|
|
269
|
+
*/
|
|
270
|
+
function coveredPrefix(candLines, files) {
|
|
271
|
+
const anchors = []
|
|
272
|
+
let i = 0
|
|
273
|
+
while (i < candLines.length) {
|
|
274
|
+
let best = null
|
|
275
|
+
for (const f of files) {
|
|
276
|
+
for (let p = 0; p < f.lines.length; p++) {
|
|
277
|
+
if (f.lines[p] !== candLines[i]) continue
|
|
278
|
+
let n = 0
|
|
279
|
+
while (i + n < candLines.length && p + n < f.lines.length && f.lines[p + n] === candLines[i + n]) n++
|
|
280
|
+
if (best === null || n > best.n) best = { n, f, p }
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (best === null) break
|
|
284
|
+
anchors.push({ file: best.f.file, line: best.f.start + best.p + best.n, end: i + best.n })
|
|
285
|
+
i += best.n
|
|
286
|
+
}
|
|
287
|
+
return { covered: i, anchors }
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* 拆一份回顾文件。
|
|
292
|
+
* @param {object} input
|
|
293
|
+
* @param {string} input.lang 拆解那一刻 DSH 的语言(决定文件头与分区标题写哪套字)
|
|
294
|
+
*/
|
|
295
|
+
export async function captureCompaction({ dshHome, cwd, session, event, lang = 'zh' }) {
|
|
296
|
+
const data = event.data ?? {}
|
|
297
|
+
const seqs = Array.isArray(data.shadowedSeqs) ? data.shadowedSeqs : []
|
|
298
|
+
const at = new Date(typeof event.time === 'number' ? event.time : Date.now())
|
|
299
|
+
const dir = memoryDir(dshHome, cwd)
|
|
300
|
+
const compactedAt = at.toISOString()
|
|
301
|
+
|
|
302
|
+
const pick = typeof session.eventAt === 'function'
|
|
303
|
+
? (seq) => session.eventAt(seq)
|
|
304
|
+
: (seq) => session.snapshotEvents?.(seq, seq + 1)?.[0]
|
|
305
|
+
// 按 seq 去重收事件。DSH 的 shadowedSeqs 只是「被压缩的那部分」,而压缩边界画在
|
|
306
|
+
// 最后一轮回复之前 —— 那条回复还在活跃上下文里,不会被压。拆日志是插件自己的事,
|
|
307
|
+
// 不能跟着那个边界把最后一段漏掉,所以从最大的 seq 往后补到压缩事件本身为止。
|
|
308
|
+
const collected = new Map()
|
|
309
|
+
for (const seq of seqs) {
|
|
310
|
+
const e = pick(seq)
|
|
311
|
+
if (e) collected.set(seq, e)
|
|
312
|
+
}
|
|
313
|
+
let lastSeq = -1
|
|
314
|
+
for (const seq of seqs) if (seq > lastSeq) lastSeq = seq
|
|
315
|
+
if (lastSeq >= 0) {
|
|
316
|
+
for (let seq = lastSeq + 1; ; seq++) {
|
|
317
|
+
const e = pick(seq)
|
|
318
|
+
if (!e || e.type === 'compaction/summary') break
|
|
319
|
+
if (TAIL_TYPES.has(e.type) || PTC_TYPES.has(e.type)) collected.set(seq, e)
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// PTC 内层调用:shadowedSeqs 里一条都没有,按区间自己捞一遍。
|
|
324
|
+
const range = data.shadowedRange ?? {}
|
|
325
|
+
if (Number.isInteger(range.start) && Number.isInteger(range.end)) {
|
|
326
|
+
for (let seq = range.start; seq <= range.end; seq++) {
|
|
327
|
+
if (collected.has(seq)) continue
|
|
328
|
+
const e = pick(seq)
|
|
329
|
+
if (e && PTC_TYPES.has(e.type)) collected.set(seq, e)
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// 逐条渲染,并记下每条事件占正文哪几行:裁切必须落在事件边界上。
|
|
334
|
+
const spans = []
|
|
335
|
+
const candLines = []
|
|
336
|
+
for (const seq of [...collected.keys()].sort((a, b) => a - b)) {
|
|
337
|
+
// 候选行保持原文形态:下面比对的是 parseMemory 还原后的正文,两边都在「原文」这一层,
|
|
338
|
+
// 转义只在落盘那一刻发生。
|
|
339
|
+
const rendered = renderTranscript([collected.get(seq)])
|
|
340
|
+
const lines = rendered === '' ? [] : rendered.split('\n')
|
|
341
|
+
spans.push({ seq, start: candLines.length, count: lines.length })
|
|
342
|
+
for (const line of lines) candLines.push(line)
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// 开头那段如果已经记在别的回顾里,就只写之后的:同一个工作区里复刻出来的会话与本体
|
|
346
|
+
// 共享一段历史,两边各记一遍没有意义,注入时还会重复一遍。
|
|
347
|
+
const file = fileStemOf(at, data.compactionId ?? String(data.compactionId)) + '.md'
|
|
348
|
+
const files = await existingBodies(dir, cwd, file)
|
|
349
|
+
const { covered, anchors } = coveredPrefix(candLines, files)
|
|
350
|
+
let cut = covered
|
|
351
|
+
// 不在一条事件的中间开刀:宁可多留一条(可能重复),也不能漏。
|
|
352
|
+
const straddle = spans.find((sp) => sp.count > 0 && sp.start < cut && sp.start + sp.count > cut)
|
|
353
|
+
if (straddle !== undefined) cut = straddle.start
|
|
354
|
+
// 裁切点之后的事件全留;正好落在裁切点上的空事件也留(不占正文,但算进覆盖区间)
|
|
355
|
+
const keptSpans = spans.filter((sp) => sp.start + sp.count > cut || (sp.count === 0 && sp.start >= cut))
|
|
356
|
+
const keptSeqs = keptSpans.map((sp) => sp.seq)
|
|
357
|
+
const used = anchors.filter((a) => a.end <= cut)
|
|
358
|
+
const anchor = used.length > 0 ? used[used.length - 1] : null
|
|
359
|
+
const branchFrom = anchor === null ? null : { file: anchor.file, line: anchor.line }
|
|
360
|
+
|
|
361
|
+
// 一条新内容都不剩:不写空壳文件,也不往载入文件里加条目。
|
|
362
|
+
if (cut > 0 && keptSpans.every((sp) => sp.count === 0)) {
|
|
363
|
+
const why = branchFrom === null ? '内容已经记过' : ('内容到 ' + branchFrom.file + ' 第 ' + branchFrom.line + ' 行为止都已记过')
|
|
364
|
+
return { file: null, dir, skipped: true, reason: why, branchFrom, covered: cut, bytes: 0 }
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const seqStart = keptSeqs.length > 0 ? keptSeqs[0] : (data.shadowedRange?.start ?? 0)
|
|
368
|
+
const seqEnd = keptSeqs.length > 0 ? keptSeqs[keptSeqs.length - 1] : (data.shadowedRange?.end ?? 0)
|
|
369
|
+
const body = candLines.slice(cut).join('\n')
|
|
370
|
+
const { calls, failures } = countTools(body)
|
|
371
|
+
const summary = blocksText(data.summary) || blocksText(data.rawOutput)
|
|
372
|
+
|
|
373
|
+
const text = buildMemoryFile({
|
|
374
|
+
date: at,
|
|
375
|
+
compactionId: data.compactionId,
|
|
376
|
+
seqStart,
|
|
377
|
+
seqEnd,
|
|
378
|
+
seqCount: keptSeqs.length,
|
|
379
|
+
branchFrom,
|
|
380
|
+
tokenCount: data.shadowedTokenCount ?? 0,
|
|
381
|
+
toolCalls: calls,
|
|
382
|
+
toolFailures: failures,
|
|
383
|
+
count: 3,
|
|
384
|
+
summary,
|
|
385
|
+
body
|
|
386
|
+
}, lang)
|
|
387
|
+
|
|
388
|
+
await fs.mkdir(dir, { recursive: true })
|
|
389
|
+
const target = path.join(dir, file)
|
|
390
|
+
const existed = await fs.access(target).then(() => true, () => false)
|
|
391
|
+
if (!existed) await writeFileAtomic(target, text)
|
|
392
|
+
|
|
393
|
+
const entry = { file, compactedAt, count: 3, pinned: false, seqStart, seqEnd }
|
|
394
|
+
if (existed) {
|
|
395
|
+
const data0 = await readAssembly(dir, cwd)
|
|
396
|
+
const found = data0.entries.find((e) => e.file === file)
|
|
397
|
+
if (found) return { file, dir, entry: found, added: false, bytes: Buffer.byteLength(text, 'utf8') }
|
|
398
|
+
}
|
|
399
|
+
const res = await upsertEntry(dir, cwd, entry)
|
|
400
|
+
return { file, dir, entry: res.entry, added: res.added, bytes: Buffer.byteLength(text, 'utf8') }
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** 读一份回顾文件并解析。 */
|
|
404
|
+
export async function readMemory(dir, file) {
|
|
405
|
+
const text = await fs.readFile(path.join(dir, file), 'utf8')
|
|
406
|
+
return { text, parsed: parseMemory(text) }
|
|
407
|
+
}
|
|
408
|
+
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 工具组的导入 / 导出(0.4.3)。
|
|
3
|
+
*
|
|
4
|
+
* 导出:把工具组根目录(toolSequence)下的内容原样打成一个 zip,**压缩率 0**(store),
|
|
5
|
+
* 文件名固定 toolSequence.zip。跳过两类东西:
|
|
6
|
+
* _runs/ 运行溢写(是输出,不是工具本身,可能很大)
|
|
7
|
+
* *.bak-* / *.tmp-* 重装留下的旧目录、装到一半的临时目录
|
|
8
|
+
* 其余的(_index.json 与每个 <id>/)都进包,解压出来就是一个能直接用的工具组目录。
|
|
9
|
+
*
|
|
10
|
+
* 导入:解包 → 每个顶层 <id>/ 先在临时目录里写全,再整体换上去(和安装同一套做法,
|
|
11
|
+
* 不让人看到装到一半的工具脚本)。包里的 _index.json 不采信:索引是本机的注册表,
|
|
12
|
+
* 直接盖会丢掉本机别的工具脚本,所以按落地后的文件重建这一份,别的一条不动。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import fs from 'node:fs'
|
|
16
|
+
import fsp from 'node:fs/promises'
|
|
17
|
+
import path from 'node:path'
|
|
18
|
+
import {
|
|
19
|
+
BUNDLE_ID_RE, INDEX_FILE, RUNS_DIR, TOOL_SCRIPT_FILE,
|
|
20
|
+
assertToolScriptId, readIndex, runsDir, sha256OfFile, toolScriptDir, toolSequenceRoot, writeIndex
|
|
21
|
+
} from './schema.js'
|
|
22
|
+
import { buildZip, readZip, safeEntryName } from './zip.js'
|
|
23
|
+
|
|
24
|
+
/** 导出包的名字(用户要的就是这个名字)。 */
|
|
25
|
+
export const EXPORT_NAME = 'toolSequence.zip'
|
|
26
|
+
|
|
27
|
+
/** 导出包上限:再大就不该塞进一个 HTTP 响应里了(先判后写,绝不写出去再报错)。 */
|
|
28
|
+
export const MAX_EXPORT_BYTES = 24 * 1024 * 1024
|
|
29
|
+
|
|
30
|
+
/** 打包时跳过、导入时也不收的路径片段。 */
|
|
31
|
+
function isTransientName(name) {
|
|
32
|
+
return name === RUNS_DIR || name.includes('.bak-') || name.includes('.tmp-')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 递归收集一个目录下的文件,名用 / 分隔。
|
|
37
|
+
* @param {string} root 绝对路径
|
|
38
|
+
* @param {string} prefix 包内前缀(不带结尾 /)
|
|
39
|
+
* @param {Array<{name:string,data?:Buffer,mtime?:Date}>} out
|
|
40
|
+
*/
|
|
41
|
+
async function collect(dir, prefix, out) {
|
|
42
|
+
let list
|
|
43
|
+
try { list = await fsp.readdir(dir, { withFileTypes: true }) } catch { return }
|
|
44
|
+
for (const item of list) {
|
|
45
|
+
const abs = path.join(dir, item.name)
|
|
46
|
+
const name = prefix === '' ? item.name : prefix + '/' + item.name
|
|
47
|
+
if (isTransientName(item.name)) continue
|
|
48
|
+
if (item.isDirectory()) {
|
|
49
|
+
const before = out.length
|
|
50
|
+
await collect(abs, name, out)
|
|
51
|
+
if (out.length === before) out.push({ name: name + '/' })
|
|
52
|
+
continue
|
|
53
|
+
}
|
|
54
|
+
if (!item.isFile()) continue // 软链之类一律不收
|
|
55
|
+
const stat = await fsp.stat(abs).catch(() => null)
|
|
56
|
+
if (stat === null) continue
|
|
57
|
+
out.push({ name, data: await fsp.readFile(abs), mtime: stat.mtime })
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 把工具组目录打成一个 zip(store,压缩率 0),**直接写进指定的工作区文件夹**。
|
|
64
|
+
*
|
|
65
|
+
* 为什么不回给浏览器下载:导出的东西本来就是给这台机器上的人(和下一次会话)用的,
|
|
66
|
+
* 落在工作区里能被 ls 到、能被下一轮直接读,比在手机上下载管理器里翻一个 zip 有用得多。
|
|
67
|
+
*
|
|
68
|
+
* @param {{dshHome:string, dir:string}} p dir 是工作区目录(绝对路径,必须已经是存在的目录)
|
|
69
|
+
* @returns {Promise<{name:string, file:string, dir:string, size:number, files:number, dirs:number, overwritten:boolean}>}
|
|
70
|
+
*/
|
|
71
|
+
export async function exportToolSequence({ dshHome, dir }) {
|
|
72
|
+
const target = String(dir === undefined || dir === null ? '' : dir).trim()
|
|
73
|
+
if (target === '') throw new Error('没有指定要导出到哪个工作区文件夹')
|
|
74
|
+
if (!path.isAbsolute(target)) throw new Error('工作区目录要是绝对路径:' + target)
|
|
75
|
+
let st
|
|
76
|
+
try { st = await fsp.stat(target) } catch { throw new Error('工作区目录不存在:' + target) }
|
|
77
|
+
if (!st.isDirectory()) throw new Error('这不是一个目录:' + target)
|
|
78
|
+
if (path.parse(target).root === target) throw new Error('不往磁盘根目录写:' + target)
|
|
79
|
+
|
|
80
|
+
const root = toolSequenceRoot(dshHome)
|
|
81
|
+
const entries = []
|
|
82
|
+
await collect(root, '', entries)
|
|
83
|
+
const buffer = buildZip(entries)
|
|
84
|
+
const files = entries.filter((e) => !String(e.name).endsWith('/'))
|
|
85
|
+
// 先判大小再动磁盘:超限了连临时文件都不留。
|
|
86
|
+
if (buffer.length > MAX_EXPORT_BYTES) {
|
|
87
|
+
throw new Error('工具组目录太大(' + buffer.length + ' 字节),超过导出上限 ' + MAX_EXPORT_BYTES + ' 字节')
|
|
88
|
+
}
|
|
89
|
+
const file = path.join(target, EXPORT_NAME)
|
|
90
|
+
const overwritten = fs.existsSync(file)
|
|
91
|
+
const tmp = file + '.tmp-' + process.pid + '-' + Math.random().toString(36).slice(2, 8)
|
|
92
|
+
await fsp.writeFile(tmp, buffer)
|
|
93
|
+
await fsp.rename(tmp, file)
|
|
94
|
+
return { name: EXPORT_NAME, file, dir: target, size: buffer.length, files: files.length, dirs: entries.length - files.length, overwritten }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* 从落地后的文件重建一条索引项;没有 toolScript.json 就返回 null(不成工具脚本)。
|
|
99
|
+
* @param {string} dshHome
|
|
100
|
+
* @param {string} id
|
|
101
|
+
* @param {Array<{name:string,size:number}>} files 这个 id 下的文件(相对 id 目录)
|
|
102
|
+
*/
|
|
103
|
+
function indexEntryFromDisk(dir, files) {
|
|
104
|
+
const manifestFile = path.join(dir, TOOL_SCRIPT_FILE)
|
|
105
|
+
let manifest
|
|
106
|
+
try { manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8')) } catch { return null }
|
|
107
|
+
if (!manifest || typeof manifest !== 'object') return null
|
|
108
|
+
const hashes = {}
|
|
109
|
+
for (const f of files) {
|
|
110
|
+
if (f.name.includes('/')) continue
|
|
111
|
+
const abs = path.join(dir, f.name)
|
|
112
|
+
try { hashes[f.name] = sha256OfFile(abs) } catch { /* 读不到就不进哈希表 */ }
|
|
113
|
+
}
|
|
114
|
+
return {
|
|
115
|
+
title: String(manifest.title === undefined ? '' : manifest.title).trim() || String(manifest.id || ''),
|
|
116
|
+
purpose: String(manifest.purpose === undefined ? '' : manifest.purpose),
|
|
117
|
+
entry: String(manifest.entry === undefined ? '' : manifest.entry),
|
|
118
|
+
params: Array.isArray(manifest.params) ? manifest.params.map(String) : [],
|
|
119
|
+
steps: Array.isArray(manifest.steps) ? manifest.steps.map(String) : [],
|
|
120
|
+
dir: String(manifest.id || ''),
|
|
121
|
+
timeoutMs: Number.isFinite(Number(manifest.timeoutMs)) ? Number(manifest.timeoutMs) : 120000,
|
|
122
|
+
updatedAt: new Date().toISOString(),
|
|
123
|
+
hashes
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 手工把 toolSequence 文件夹压成包时,包里面会多一层 toolSequence/。
|
|
129
|
+
* 只有「所有条目都在这一个顶层目录下、而且它就叫 toolSequence」时才剥——
|
|
130
|
+
* 别的单层目录不猜,免得把某个 id 名字当壳剥掉。
|
|
131
|
+
* @param {Array<{name:string}>} entries
|
|
132
|
+
* @returns {Array<{name:string}>}
|
|
133
|
+
*/
|
|
134
|
+
function stripWrapperDir(entries) {
|
|
135
|
+
const tops = new Set()
|
|
136
|
+
for (const entry of entries) {
|
|
137
|
+
const parts = String(entry.name).split('/').filter((x) => x !== '')
|
|
138
|
+
if (parts.length === 0) continue
|
|
139
|
+
tops.add(parts[0])
|
|
140
|
+
if (tops.size > 1) return entries
|
|
141
|
+
}
|
|
142
|
+
if (tops.size !== 1) return entries
|
|
143
|
+
const only = [...tops][0]
|
|
144
|
+
if (only.toLowerCase() !== 'toolsequence') return entries
|
|
145
|
+
const cut = only.length + 1
|
|
146
|
+
const out = []
|
|
147
|
+
for (const entry of entries) {
|
|
148
|
+
const name = String(entry.name)
|
|
149
|
+
if (name === only || name === only + '/') continue
|
|
150
|
+
out.push(Object.assign({}, entry, { name: name.slice(cut) }))
|
|
151
|
+
}
|
|
152
|
+
return out
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
*
|
|
157
|
+
* dryRun:只解析,不写盘——设置页先用它把「会装哪些、会盖哪些」念给用户听,点了确认才真装。
|
|
158
|
+
*
|
|
159
|
+
* @param {{dshHome:string, buffer:Buffer, dryRun?:boolean}} p
|
|
160
|
+
* @returns {Promise<{dryRun:boolean, imported:Array<{id:string,files:string[]}>, overwritten:string[], skipped:Array<{name:string,reason:string}>}>}
|
|
161
|
+
*/
|
|
162
|
+
export async function importToolSequence({ dshHome, buffer, dryRun = false }) {
|
|
163
|
+
const root = toolSequenceRoot(dshHome)
|
|
164
|
+
const entries = readZip(buffer)
|
|
165
|
+
const stripped = stripWrapperDir(entries)
|
|
166
|
+
|
|
167
|
+
/** @type {Map<string, Array<{rel:string, data:Buffer}>>} */
|
|
168
|
+
const byId = new Map()
|
|
169
|
+
const skipped = []
|
|
170
|
+
for (const entry of stripped) {
|
|
171
|
+
if (entry.isDir) continue
|
|
172
|
+
let safe
|
|
173
|
+
try { safe = safeEntryName(entry.name) } catch (err) { skipped.push({ name: entry.name, reason: String(err.message || err) }); continue }
|
|
174
|
+
const parts = safe.split('/')
|
|
175
|
+
const top = parts[0]
|
|
176
|
+
if (parts.length === 1 && top === INDEX_FILE) {
|
|
177
|
+
skipped.push({ name: entry.name, reason: '本机索引按落地后的文件重建,包里的 _index.json 不采信' })
|
|
178
|
+
continue
|
|
179
|
+
}
|
|
180
|
+
if (parts.length < 2) { skipped.push({ name: entry.name, reason: '不在任何工具脚本目录里' }); continue }
|
|
181
|
+
if (top === RUNS_DIR) { skipped.push({ name: entry.name, reason: '运行溢写目录,不收' }); continue }
|
|
182
|
+
if (!BUNDLE_ID_RE.test(top)) { skipped.push({ name: entry.name, reason: '目录名不是合法的工具脚本 id' }); continue }
|
|
183
|
+
if (isTransientName(parts[1])) { skipped.push({ name: entry.name, reason: '备份/临时目录,不收' }); continue }
|
|
184
|
+
const list = byId.get(top) || []
|
|
185
|
+
list.push({ rel: parts.slice(1).join('/'), data: entry.data })
|
|
186
|
+
byId.set(top, list)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (byId.size === 0) {
|
|
190
|
+
const why = skipped.length > 0 ? ('(' + skipped.slice(0, 3).map((s) => s.name + ':' + s.reason).join(';') + ')') : ''
|
|
191
|
+
throw new Error('这个包里没有工具脚本目录' + why)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const index = await readIndex(dshHome)
|
|
195
|
+
const imported = []
|
|
196
|
+
const overwritten = []
|
|
197
|
+
|
|
198
|
+
if (dryRun !== true) await fsp.mkdir(root, { recursive: true })
|
|
199
|
+
|
|
200
|
+
for (const [rawId, files] of byId) {
|
|
201
|
+
const id = assertToolScriptId(rawId)
|
|
202
|
+
const dest = toolScriptDir(dshHome, id)
|
|
203
|
+
const exists = fs.existsSync(dest)
|
|
204
|
+
if (exists) overwritten.push(id)
|
|
205
|
+
imported.push({ id, files: files.map((f) => f.rel) })
|
|
206
|
+
if (dryRun === true) continue
|
|
207
|
+
|
|
208
|
+
const stage = path.join(root, id + '.tmp-import-' + process.pid + '-' + Math.random().toString(36).slice(2, 8))
|
|
209
|
+
await fsp.rm(stage, { recursive: true, force: true })
|
|
210
|
+
await fsp.mkdir(stage, { recursive: true })
|
|
211
|
+
try {
|
|
212
|
+
for (const file of files) {
|
|
213
|
+
const target = path.join(stage, file.rel)
|
|
214
|
+
const rel = path.relative(stage, target)
|
|
215
|
+
if (rel === '' || rel === '..' || rel.startsWith('..' + path.sep) || path.isAbsolute(rel)) {
|
|
216
|
+
throw new Error('越界路径:' + file.rel)
|
|
217
|
+
}
|
|
218
|
+
await fsp.mkdir(path.dirname(target), { recursive: true })
|
|
219
|
+
await fsp.writeFile(target, file.data)
|
|
220
|
+
}
|
|
221
|
+
} catch (err) {
|
|
222
|
+
await fsp.rm(stage, { recursive: true, force: true }).catch(() => {})
|
|
223
|
+
throw err
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
let backup = ''
|
|
227
|
+
try {
|
|
228
|
+
if (exists) {
|
|
229
|
+
backup = dest + '.bak-' + Date.now()
|
|
230
|
+
await fsp.rename(dest, backup)
|
|
231
|
+
}
|
|
232
|
+
await fsp.rename(stage, dest)
|
|
233
|
+
} catch (err) {
|
|
234
|
+
await fsp.rm(stage, { recursive: true, force: true }).catch(() => {})
|
|
235
|
+
if (backup !== '') await fsp.rename(backup, dest).catch(() => {})
|
|
236
|
+
throw err
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const meta = indexEntryFromDisk(dest, files.map((f) => ({ name: f.rel, size: f.data.length })))
|
|
240
|
+
if (meta !== null) index.toolScripts[id] = meta
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
if (dryRun !== true && imported.length > 0) {
|
|
244
|
+
await writeIndex(dshHome, index)
|
|
245
|
+
await fsp.mkdir(runsDir(dshHome), { recursive: true }).catch(() => {})
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return { dryRun: dryRun === true, imported, overwritten, skipped }
|
|
249
|
+
}
|