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.
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 +71 -4
@@ -0,0 +1,493 @@
1
+ /**
2
+ * 工具组(0.3.0):把回顾原文里的操作固化成「工具脚本」——一个目录、一份清单、若干脚本。
3
+ *
4
+ * 装起来像一个小插件,跑起来像插件自带的工具:不新增任何插件,
5
+ * 也不让模型每次现写代码,只把入口挂在系统提示词里(catalogText),命令住在磁盘上。
6
+ *
7
+ * 目录:$DSH_HOME/session-memory/toolSequence/ ← 机器级,一个机器上装的所有工具脚本共用
8
+ * _index.json 总索引(查找、哈希、注入都读它)
9
+ * <id>/toolScript.json 这个工具脚本自己的清单(入口、步骤、参数、出处、验证状态)
10
+ * <id>/README.md 从清单自动生成,给人看
11
+ * <id>/<脚本文件>
12
+ * _runs/ 输出溢写(超过单条上限才落,不删)
13
+ *
14
+ * 只依赖 node 内置模块;写盘走「先写临时目录,最后一次 rename」,
15
+ * 不给读的人看到装到一半的文件。
16
+ */
17
+
18
+ import fs from 'node:fs'
19
+ import fsp from 'node:fs/promises'
20
+ import path from 'node:path'
21
+ import crypto from 'node:crypto'
22
+
23
+ /** 工具组目录名(在记忆根下,和 session-memory/<工作区 key>/ 平级)。 */
24
+ export const TOOL_SEQUENCE_DIR = 'toolSequence'
25
+
26
+ /** 总索引文件名。 */
27
+ export const INDEX_FILE = '_index.json'
28
+
29
+ /** 单个工具脚本的清单文件名。 */
30
+ export const TOOL_SCRIPT_FILE = 'toolScript.json'
31
+
32
+ /** 输出溢写目录。 */
33
+ export const RUNS_DIR = '_runs'
34
+
35
+ /** 索引格式版本。 */
36
+ const INDEX_VERSION = 1
37
+
38
+ /** 工具脚本 id:小写、数字、连字符,开头顶一个字母。 */
39
+ export const BUNDLE_ID_RE = /^[a-z][a-z0-9-]{1,40}$/
40
+
41
+ /** 脚本文件名:不许带路径分隔符,不许点开头。 */
42
+ export const FILE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,60}$/
43
+
44
+ /** 每种执行方式允许的扩展名。 */
45
+ export const RUN_EXT = {
46
+ bash: ['.sh'],
47
+ node: ['.js', '.mjs', '.cjs'],
48
+ ps1: ['.ps1'],
49
+ cmd: ['.bat', '.cmd']
50
+ }
51
+
52
+ /** 执行方式的中文名(报错与 README 用)。 */
53
+ export const RUN_LABEL = { bash: 'bash 脚本', node: 'node 脚本', ps1: 'PowerShell 脚本', cmd: '批处理' }
54
+
55
+ /** 单脚本上限 64 KB;一次装一个工具脚本的上限 512 KB。 */
56
+ export const MAX_SCRIPT_BYTES = 64 * 1024
57
+ export const MAX_TOOL_SCRIPT_BYTES = 512 * 1024
58
+
59
+ /** 注入到系统提示词里的清单上限。 */
60
+ export const CATALOG_MAX_LINES = 24
61
+ export const CATALOG_MAX_CHARS = 1600
62
+
63
+ /**
64
+ * 工具组根目录。
65
+ * @param {string} dshHome
66
+ * @returns {string}
67
+ */
68
+ export function toolSequenceRoot(dshHome) {
69
+ return path.join(String(dshHome), 'session-memory', TOOL_SEQUENCE_DIR)
70
+ }
71
+
72
+ /**
73
+ * 某个工具脚本的目录。
74
+ * @param {string} dshHome
75
+ * @param {string} id
76
+ * @returns {string}
77
+ */
78
+ export function toolScriptDir(dshHome, id) {
79
+ return path.join(toolSequenceRoot(dshHome), id)
80
+ }
81
+
82
+ /** 索引文件路径。 */
83
+ export function indexPath(dshHome) {
84
+ return path.join(toolSequenceRoot(dshHome), INDEX_FILE)
85
+ }
86
+
87
+ /**
88
+ * 把工具组目录建好(插件一启动就调用)。
89
+ *
90
+ * 为什么非要建:目录只在第一次装工具脚本时才出现,用户去 session-memory 下找一个
91
+ * 「工具文件夹」就会扑空。空目录也建,看得见才算放着。
92
+ * @param {string} dshHome
93
+ * @returns {Promise<string>} 工具组根目录
94
+ */
95
+ export async function ensureToolSequenceDir(dshHome) {
96
+ const root = toolSequenceRoot(dshHome)
97
+ await fsp.mkdir(root, { recursive: true })
98
+ return root
99
+ }
100
+
101
+ /** 溢写目录路径。 */
102
+ export function runsDir(dshHome) {
103
+ return path.join(toolSequenceRoot(dshHome), RUNS_DIR)
104
+ }
105
+
106
+ /**
107
+ * id 合法性:不合格直接抛,不静默改名。
108
+ * @param {string} id
109
+ * @returns {string}
110
+ */
111
+ export function assertToolScriptId(id) {
112
+ const s = String(id ?? '').trim()
113
+ if (!BUNDLE_ID_RE.test(s)) {
114
+ throw new Error('toolScript.id 要写成小写字母开头的短名(a-z 0-9 -,2~41 位):' + (s || '(空)'))
115
+ }
116
+ return s
117
+ }
118
+
119
+ /**
120
+ * 把脚本文件名收干净:不许路径、不许点开头。
121
+ * @param {string} name
122
+ * @returns {string}
123
+ */
124
+ export function assertFileName(name) {
125
+ const s = String(name ?? '').trim()
126
+ if (!FILE_NAME_RE.test(s)) throw new Error('脚本文件名不合法(只许字母数字 . _ -,不许带路径):' + (s || '(空)'))
127
+ return s
128
+ }
129
+
130
+ /**
131
+ * 执行方式与扩展名要对得上:bash 配 .sh、node 配 .js/.mjs/.cjs……
132
+ * @param {string} name
133
+ * @param {string} run
134
+ * @returns {string}
135
+ */
136
+ export function assertRunMatches(name, run) {
137
+ if (!RUN_EXT[run]) throw new Error('run 只收 bash / node / ps1 / cmd:' + String(run))
138
+ const ext = path.extname(name).toLowerCase()
139
+ if (!RUN_EXT[run].includes(ext)) {
140
+ throw new Error(name + ' 的扩展名是 ' + (ext || '(无)') + ',和 run=' + run +
141
+ ' 对不上;应该是 ' + RUN_EXT[run].join(' / '))
142
+ }
143
+ return run
144
+ }
145
+
146
+ /** 文件 sha256(小写十六进制)。 */
147
+ export function sha256OfFile(file) {
148
+ return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex')
149
+ }
150
+
151
+ /**
152
+ * 在某个目录里解析一个相对路径;越界直接抛。
153
+ * @param {string} dir
154
+ * @param {string} rel
155
+ * @returns {string}
156
+ */
157
+ export function resolveInside(dir, rel) {
158
+ const raw = String(rel ?? '').trim()
159
+ if (raw === '') throw new Error('文件名为空')
160
+ const base = path.resolve(dir)
161
+ const abs = path.resolve(base, raw)
162
+ const r = path.relative(base, abs)
163
+ if (r === '' || r.startsWith('..') || path.isAbsolute(r)) {
164
+ throw new Error('只能操作这个工具脚本目录里的文件:' + raw)
165
+ }
166
+ return abs
167
+ }
168
+
169
+ /**
170
+ * 读索引;没装过、坏了都给空。同步版给注入路径用(systemPrompt.section 的 text 是同步求值)。
171
+ * @param {string} dshHome
172
+ * @returns {{version:number, toolScripts:Record<string, object>}}
173
+ */
174
+ export function readIndexSync(dshHome) {
175
+ try {
176
+ const raw = fs.readFileSync(indexPath(dshHome), 'utf8')
177
+ const parsed = JSON.parse(raw)
178
+ if (!parsed || typeof parsed !== 'object' || !parsed.toolScripts || typeof parsed.toolScripts !== 'object') {
179
+ return { version: INDEX_VERSION, toolScripts: {} }
180
+ }
181
+ return { version: parsed.version ?? INDEX_VERSION, toolScripts: parsed.toolScripts }
182
+ } catch {
183
+ return { version: INDEX_VERSION, toolScripts: {} }
184
+ }
185
+ }
186
+
187
+ /** 读索引(异步版给工具用)。 */
188
+ export async function readIndex(dshHome) {
189
+ try {
190
+ const raw = await fsp.readFile(indexPath(dshHome), 'utf8')
191
+ const parsed = JSON.parse(raw)
192
+ if (!parsed || typeof parsed !== 'object' || !parsed.toolScripts || typeof parsed.toolScripts !== 'object') {
193
+ return { version: INDEX_VERSION, toolScripts: {} }
194
+ }
195
+ return { version: parsed.version ?? INDEX_VERSION, toolScripts: parsed.toolScripts }
196
+ } catch {
197
+ return { version: INDEX_VERSION, toolScripts: {} }
198
+ }
199
+ }
200
+
201
+ /** 原子写索引:临时文件 + rename(Windows 失败就退避重试)。 */
202
+ export async function writeIndex(dshHome, index) {
203
+ const dir = toolSequenceRoot(dshHome)
204
+ await fsp.mkdir(dir, { recursive: true })
205
+ const file = indexPath(dshHome)
206
+ const tmp = file + '.tmp-' + process.pid + '-' + Math.random().toString(36).slice(2, 8)
207
+ await fsp.writeFile(tmp, JSON.stringify({ version: INDEX_VERSION, toolScripts: index.toolScripts ?? {} }, null, 2) + '\n', 'utf8')
208
+ let lastError = null
209
+ for (let i = 0; i < 6; i++) {
210
+ try { await fsp.rename(tmp, file); return } catch (err) {
211
+ lastError = err
212
+ await new Promise((r) => setTimeout(r, 12 * (i + 1)))
213
+ }
214
+ }
215
+ try {
216
+ await fsp.rm(file, { force: true })
217
+ await fsp.rename(tmp, file)
218
+ } catch (err) {
219
+ await fsp.rm(tmp, { force: true }).catch(() => {})
220
+ throw lastError ?? err
221
+ }
222
+ }
223
+
224
+ /**
225
+ * 列出所有工具脚本(已装的那些)。
226
+ * @param {string} dshHome
227
+ * @returns {Promise<Array<{id:string,title:string,purpose:string,entry:string,params:string[],steps:string[]}>>}
228
+ */
229
+ export async function listToolScripts(dshHome) {
230
+ const { toolScripts } = await readIndex(dshHome)
231
+ const out = []
232
+ for (const [id, meta] of Object.entries(toolScripts)) {
233
+ if (!meta || typeof meta !== 'object') continue
234
+ out.push({
235
+ id,
236
+ title: String(meta.title ?? id),
237
+ purpose: String(meta.purpose ?? ''),
238
+ entry: String(meta.entry ?? ''),
239
+ params: Array.isArray(meta.params) ? meta.params.map(String) : [],
240
+ steps: Array.isArray(meta.steps) ? meta.steps.map(String) : []
241
+ })
242
+ }
243
+ return out.sort((a, b) => a.id.localeCompare(b.id))
244
+ }
245
+
246
+ /**
247
+ * 读一个工具脚本的清单。
248
+ * @param {string} dshHome
249
+ * @param {string} id
250
+ * @returns {Promise<{manifest:object, dir:string}>}
251
+ */
252
+ export async function loadToolScript(dshHome, id) {
253
+ const clean = assertToolScriptId(id)
254
+ const dir = toolScriptDir(dshHome, clean)
255
+ let raw
256
+ try {
257
+ raw = await fsp.readFile(path.join(dir, TOOL_SCRIPT_FILE), 'utf8')
258
+ } catch {
259
+ throw new Error('没有这个工具脚本:' + clean + '(装过的工具脚本:不带参数调用 session_tool_call 看名单)')
260
+ }
261
+ let manifest
262
+ try { manifest = JSON.parse(raw) } catch { throw new Error('这个工具脚本的 toolScript.json 坏了:' + clean) }
263
+ if (!manifest || typeof manifest !== 'object') throw new Error('这个工具脚本的 toolScript.json 不是对象:' + clean)
264
+ return { manifest, dir }
265
+ }
266
+
267
+ /**
268
+ * 校验并补齐一个工具脚本的规格(不碰磁盘)。故意不做「猜名字」之类的兜底:错就报错。
269
+ * @param {object} spec
270
+ * @returns {object} 规范化后的工具脚本规格
271
+ */
272
+ export function normalizeToolScript(spec) {
273
+ if (spec === null || typeof spec !== 'object' || Array.isArray(spec)) throw new Error('toolScript 必须是对象')
274
+ const id = assertToolScriptId(spec.id)
275
+ const title = String(spec.title ?? '').trim()
276
+ if (title === '') throw new Error('toolScript.title 不能为空:一句话说这个工具脚本叫什么')
277
+ const purpose = String(spec.purpose ?? '').trim()
278
+ if (purpose === '') throw new Error('toolScript.purpose 不能为空:一句话说这个工具脚本干什么')
279
+ if (Buffer.byteLength(purpose, 'utf8') > 600) throw new Error('toolScript.purpose 太长了(600 字节以内),它会上系统提示词')
280
+
281
+ const scriptsIn = Array.isArray(spec.scripts) ? spec.scripts : []
282
+ const docsIn = Array.isArray(spec.docs) ? spec.docs : []
283
+ if (scriptsIn.length === 0) throw new Error('toolScript.scripts 不能是空的:至少要有一个能跑的脚本')
284
+
285
+ let total = 0
286
+ const seen = new Set()
287
+ const scripts = scriptsIn.map((s, i) => {
288
+ if (s === null || typeof s !== 'object' || Array.isArray(s)) throw new Error('scripts[' + i + '] 必须是对象')
289
+ const name = assertFileName(s.name)
290
+ const run = assertRunMatches(name, s.run)
291
+ const content = String(s.content ?? '')
292
+ if (content.trim() === '') throw new Error(name + ' 的内容是空的')
293
+ const bytes = Buffer.byteLength(content, 'utf8')
294
+ if (bytes > MAX_SCRIPT_BYTES) throw new Error(name + ' 超过 64 KB(' + bytes + ' 字节);拆成两个脚本')
295
+ if (content.includes('<!--ovr:')) throw new Error(name + ' 里出现了回顾文件的分区标记 <!--ovr:,会污染解析,删掉它')
296
+ if (seen.has(name)) throw new Error('同一个脚本名出现了两次:' + name)
297
+ seen.add(name)
298
+ total += bytes
299
+ return { name, run, content, params: Array.isArray(s.params) ? s.params.map(String) : [] }
300
+ })
301
+ const docSeen = new Set()
302
+ const docs = docsIn.map((d, i) => {
303
+ if (d === null || typeof d !== 'object' || Array.isArray(d)) throw new Error('docs[' + i + '] 必须是对象')
304
+ const name = assertFileName(d.name)
305
+ if (path.extname(name).toLowerCase() !== '.md') throw new Error(name + ' 是说明文件,扩展名要写 .md')
306
+ if (name.toLowerCase() === 'readme.md') {
307
+ throw new Error(name + ' 和安装时自动生成的 README.md 同名,装进去会被静默覆盖;换个名字(比如 ' + (i === 0 ? 'notes.md' : 'notes-' + i + '.md') + ')')
308
+ }
309
+ if (docSeen.has(name)) throw new Error('docs 里同名出现了两次:' + name + '(第二份会覆盖第一份)')
310
+ docSeen.add(name)
311
+ const content = String(d.content ?? '')
312
+ if (content.trim() === '') throw new Error(name + ' 的内容是空的')
313
+ const bytes = Buffer.byteLength(content, 'utf8')
314
+ if (bytes > MAX_SCRIPT_BYTES) throw new Error(name + ' 超过 64 KB')
315
+ total += bytes
316
+ return { name, content }
317
+ })
318
+ if (total > MAX_TOOL_SCRIPT_BYTES) throw new Error('这个工具脚本超过 512 KB(' + total + ' 字节);拆成两个')
319
+
320
+ const entry = assertFileName(spec.entry ?? scripts[0].name)
321
+ if (!seen.has(entry)) throw new Error('toolScript.entry 必须是 scripts 里的一个文件:' + entry)
322
+ const steps = (Array.isArray(spec.steps) ? spec.steps : []).map((s) => assertFileName(s))
323
+ for (const s of steps) if (!seen.has(s)) throw new Error('toolScript.steps 里的 ' + s + ' 不在 scripts 里')
324
+
325
+ const timeoutMs = spec.timeoutMs === undefined ? 120000 : Number(spec.timeoutMs)
326
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 1000 || timeoutMs > 600000) {
327
+ throw new Error('toolScript.timeoutMs 要在 1000~600000 之间(默认 120000)')
328
+ }
329
+
330
+ const provenance = spec.provenance && typeof spec.provenance === 'object'
331
+ ? {
332
+ memory: spec.provenance.memory === undefined ? '' : String(spec.provenance.memory),
333
+ line: Number.isInteger(spec.provenance.line) ? spec.provenance.line : null,
334
+ seq: Number.isInteger(spec.provenance.seq) ? spec.provenance.seq : null
335
+ }
336
+ : { memory: '', line: null, seq: null }
337
+
338
+ return {
339
+ version: 1,
340
+ id, title, purpose,
341
+ params: Array.isArray(spec.params) ? spec.params.map(String) : [],
342
+ entry, steps, timeoutMs, provenance,
343
+ createdAt: new Date().toISOString(),
344
+ verified: spec.verified && typeof spec.verified === 'object' ? spec.verified : null,
345
+ scripts, docs
346
+ }
347
+ }
348
+
349
+ /** 从清单生成人看的 README.md。 */
350
+ export function renderToolScriptReadme(manifest) {
351
+ const lines = [
352
+ '# ' + manifest.title + '(' + manifest.id + ')',
353
+ '',
354
+ manifest.purpose,
355
+ '',
356
+ '- 入口:' + manifest.entry,
357
+ ...(manifest.params.length > 0 ? ['- 参数:' + manifest.params.join('、')] : []),
358
+ ...(manifest.steps.length > 0 ? ['- 步骤:' + manifest.steps.join(' → ')] : []),
359
+ ...(manifest.provenance.memory ? ['- 出处:' + manifest.provenance.memory + (manifest.provenance.line ? (' 第 ' + manifest.provenance.line + ' 行') : '')] : []),
360
+ '- 验证:' + (manifest.verified && manifest.verified.at ? (manifest.verified.at + ' exit ' + manifest.verified.exitCode) : '还没跑过'),
361
+ '',
362
+ '## 文件',
363
+ ''
364
+ ]
365
+ for (const s of manifest.scripts) lines.push('- ' + s.name + '(' + RUN_LABEL[s.run] + ')')
366
+ for (const d of manifest.docs) lines.push('- ' + d.name + '(说明,不执行)')
367
+ lines.push('', '用 session_tool_call 直接跑:toolScript 写 ' + manifest.id + ';先看一眼 argv 就加 dryRun: true。')
368
+ return lines.join('\n') + '\n'
369
+ }
370
+
371
+ /**
372
+ * 装一个工具脚本:先写临时目录,再整体 rename 进来。
373
+ * @param {{dshHome:string, spec:object, replace?:boolean}} p
374
+ * @returns {Promise<{id:string, dir:string, files:Array<{name:string,bytes:number,sha256:string,kind:string}>, indexPath:string, backup:string}>}
375
+ */
376
+ export async function installToolScript({ dshHome, spec, replace = false }) {
377
+ const manifest = normalizeToolScript(spec)
378
+ const root = toolSequenceRoot(dshHome)
379
+ await fsp.mkdir(root, { recursive: true })
380
+ const dir = toolScriptDir(dshHome, manifest.id)
381
+ const exists = fs.existsSync(dir)
382
+ if (exists && !replace) {
383
+ const abs = path.join(dir, TOOL_SCRIPT_FILE)
384
+ const sha = fs.existsSync(abs) ? sha256OfFile(abs) : ''
385
+ throw new Error('这个工具脚本已经装过了:' + manifest.id + '(' + dir + (sha ? ',清单 sha256 ' + sha.slice(0, 12) : '') +
386
+ ');要重装就传 replace: true,旧目录会留一份 .bak-<时间戳>')
387
+ }
388
+
389
+ const stage = path.join(root, manifest.id + '.tmp-' + process.pid + '-' + Math.random().toString(36).slice(2, 8))
390
+ await fsp.rm(stage, { recursive: true, force: true })
391
+ await fsp.mkdir(stage, { recursive: true })
392
+ const files = []
393
+ try {
394
+ for (const s of manifest.scripts) {
395
+ const file = path.join(stage, s.name)
396
+ await fsp.writeFile(file, s.content, 'utf8')
397
+ files.push({ name: s.name, bytes: Buffer.byteLength(s.content, 'utf8'), sha256: sha256OfFile(file), kind: 'script' })
398
+ }
399
+ for (const d of manifest.docs) {
400
+ const file = path.join(stage, d.name)
401
+ await fsp.writeFile(file, d.content, 'utf8')
402
+ files.push({ name: d.name, bytes: Buffer.byteLength(d.content, 'utf8'), sha256: sha256OfFile(file), kind: 'doc' })
403
+ }
404
+ manifest.hashes = Object.fromEntries(files.map((f) => [f.name, f.sha256]))
405
+ await fsp.writeFile(path.join(stage, TOOL_SCRIPT_FILE), JSON.stringify(manifest, null, 2) + '\n', 'utf8')
406
+ await fsp.writeFile(path.join(stage, 'README.md'), renderToolScriptReadme(manifest), 'utf8')
407
+ } catch (err) {
408
+ await fsp.rm(stage, { recursive: true, force: true }).catch(() => {})
409
+ throw err
410
+ }
411
+
412
+ let backup = ''
413
+ try {
414
+ if (exists) {
415
+ backup = dir + '.bak-' + Date.now()
416
+ await fsp.rename(dir, backup)
417
+ }
418
+ await fsp.rename(stage, dir)
419
+ } catch (err) {
420
+ await fsp.rm(stage, { recursive: true, force: true }).catch(() => {})
421
+ if (backup) {
422
+ await fsp.rename(backup, dir).catch(() => {})
423
+ backup = ''
424
+ }
425
+ throw err
426
+ }
427
+
428
+ const index = await readIndex(dshHome)
429
+ index.toolScripts[manifest.id] = {
430
+ title: manifest.title,
431
+ purpose: manifest.purpose,
432
+ entry: manifest.entry,
433
+ params: manifest.params,
434
+ steps: manifest.steps,
435
+ dir: manifest.id,
436
+ timeoutMs: manifest.timeoutMs,
437
+ updatedAt: new Date().toISOString(),
438
+ hashes: Object.fromEntries(files.map((f) => [f.name, f.sha256]))
439
+ }
440
+ await writeIndex(dshHome, index)
441
+
442
+ return { id: manifest.id, dir, files, indexPath: indexPath(dshHome), backup }
443
+ }
444
+
445
+ /**
446
+ * 注入到系统提示词的那几行:短、按 id 排、有上限。
447
+ * 每次装配时现读索引(同步),装/删工具脚本后下一轮就变——这是它唯一会动缓存的地方。
448
+ * @param {string} dshHome
449
+ * @param {'zh'|'en'|string} lang
450
+ * @returns {string}
451
+ */
452
+ export function catalogText(dshHome, lang = 'zh') {
453
+ const { toolScripts } = readIndexSync(dshHome)
454
+ const entries = Object.entries(toolScripts)
455
+ .filter(([, m]) => m && typeof m === 'object')
456
+ .sort((a, b) => String(a[0]).localeCompare(String(b[0])))
457
+ const en = String(lang).toLowerCase().startsWith('en')
458
+ // 「自创工具 = 工具脚本」的词表桥接。模型在决定「产物该是什么」时看的是这一段,
459
+ // 而不是某个工具的描述——0.3.6 的新句放进了 create_write 描述里,实测仍未被采纳。
460
+ const runHint = en ? 'Look before running: pass "dryRun": true to session_tool_call. ' : '跑之前想看命令,就给 session_tool_call 加 dryRun: true。'
461
+ const guide = en
462
+ ? 'When the user asks to turn a working setup into a reusable procedure (summarize it into a toolScript / seal it as a workflow / do it this way next time), the artifact is a toolScript — the exact commands to run again, not a markdown note and not a skill that only states a method. Write it with session_tool_create_write: from the steps you just ran, from a recall original via session_tool_create_read, or from material already in the workspace. Call session_tool_create_write only with a script that already ran clean, never a draft; editing after installing re-sends the whole context.'
463
+ : '用户说「把那套总结成工具 / 封装成流程 / 以后照这个做」时,要的产物就是工具脚本——能直接跑的脚本,不是 md 笔记,也不是教方法的 skill。用 session_tool_create_write 写下来:命令来自刚跑通的步骤、经 session_tool_create_read 翻出的回顾原文,或工作区里现成的材料。调用 session_tool_create_write 之前,脚本必须已经跑通;写进去的就是跑通的那一份,不是装好再改的草稿。装完再改,等于把整段上下文重发一遍。'
464
+ // 空工具组也要留一句:否则模型根本不知道有写侧工具,更不会把工具脚本当成候选产物。
465
+ if (entries.length === 0) {
466
+ return (en ? '【ToolSequence · empty】Nothing sealed yet. ' : '【工具组 · 空】还没有固化任何工具脚本。') + guide
467
+ }
468
+ const lines = []
469
+ lines.push(en
470
+ ? '【ToolSequence · ' + entries.length + ' toolScript(s)】Whole scripts, sealed: the exact commands from paths that worked. Run them with session_tool_call — do not rewrite them, do not re-derive commands.'
471
+ : '【工具组 · ' + entries.length + ' 个工具脚本】已经固化好的脚本,直接用 session_tool_call 跑;不用自己写代码,也不用重新找命令。')
472
+ // 指引紧跟标题、排在工具脚本条目之前:一旦触发 CATALOG_MAX_CHARS 截断,被截掉的应是条目,不是这段词表。
473
+ lines.push(runHint + guide)
474
+ let shown = 0
475
+ for (const [id, m] of entries) {
476
+ if (shown >= CATALOG_MAX_LINES) {
477
+ lines.push(en ? '…(more: run session_tool_call without arguments)'
478
+ : '…(还有 ' + (entries.length - CATALOG_MAX_LINES) + ' 个,不带参数调用 session_tool_call 看全名单)')
479
+ break
480
+ }
481
+ const title = String(m.title ?? id)
482
+ const purpose = String(m.purpose ?? '').replace(/\s+/g, ' ')
483
+ const short = purpose.length > 80 ? purpose.slice(0, 78) + '…' : purpose
484
+ const params = Array.isArray(m.params) && m.params.length > 0 ? '|' + (en ? 'args ' : '参数 ') + m.params.join(' ') : ''
485
+ lines.push(en
486
+ ? '· ' + id + ' (' + title + '): ' + short + '|entry ' + String(m.entry ?? '') + params
487
+ : '· ' + id + '(' + title + '):' + short + '|入口 ' + String(m.entry ?? '') + params)
488
+ shown++
489
+ }
490
+ const chars = Array.from(lines.join('\n'))
491
+ if (chars.length > CATALOG_MAX_CHARS) return chars.slice(0, CATALOG_MAX_CHARS - 1).join('') + '…'
492
+ return chars.join('')
493
+ }