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,794 @@
1
+ /**
2
+ * 两个新工具(0.3.0):
3
+ *
4
+ * session_tool_create_read 回读回顾文件的「原文」区——含 ▸ 工具调用与 ◂ 结果,一个字节都不少——
5
+ * 三档读:骨架(去重)/ 分页(整段)/ 单块(一条调用连同它的结果);
6
+ * 带 toolScript 参数就写盘:把一条链固化成一整套工具脚本,装上工具组。
7
+ * session_tool_call 直接跑工具组里的工具脚本:一条或连着几条,顺序执行,逐条报退出码与输出。
8
+ *
9
+ * 定位复用 session_mem_write 那一套(file,或 date + nth),读原文不剥工具调用
10
+ * (session_mem_write 的窄读仍然只给对话,0.2.7 的取舍不动)。
11
+ */
12
+
13
+ import fsp from 'node:fs/promises'
14
+ import path from 'node:path'
15
+ import { resolveMemoryFile, resolveMemoryByDay, estimateTokens } from './tool.js'
16
+ import { parseMemory } from './memory-file.js'
17
+ import { MARK } from './render.js'
18
+ import {
19
+ installToolScript, listToolScripts, loadToolScript, catalogText, assertToolScriptId, resolveInside,
20
+ toolSequenceRoot, TOOL_SCRIPT_FILE
21
+ } from './schema.js'
22
+ import { runScript, normalizeTimeout, normalizeMaxOutput } from './schema-runner.js'
23
+
24
+ export const TOOL_CREATE_READ_NAME = 'session_tool_create_read'
25
+ export const TOOL_CREATE_WRITE_NAME = 'session_tool_create_write'
26
+ export const TOOL_CALL_TOOL_NAME = 'session_tool_call'
27
+
28
+ /** 原文里 ▸ 块的状态行前缀:render.js 写死了「报错:」。 */
29
+ const ERROR_PREFIX = MARK.result + '报错'
30
+
31
+ /* ────────────────────────── 读:原文 ────────────────────────── */
32
+
33
+ /**
34
+ * 读一份回顾的原文区(含工具调用)。
35
+ * @returns {Promise<{file:string, path:string, body:string, summary:string, meta:object}>}
36
+ */
37
+ export async function readBodyOf({ dshHome, cwd, file }) {
38
+ const abs = resolveMemoryFile(dshHome, cwd, file)
39
+ const text = await fsp.readFile(abs, 'utf8')
40
+ const parsed = parseMemory(text)
41
+ if (!parsed.id) throw new Error('这份文件没有回顾分区标记,不是回顾文件:' + file)
42
+ return {
43
+ file: path.basename(abs),
44
+ path: abs,
45
+ body: parsed.sections.body ?? '',
46
+ summary: parsed.sections.sum ?? '',
47
+ meta: parsed.meta ?? {}
48
+ }
49
+ }
50
+
51
+ /** 定位:file 或 date(+nth)。两个工具共用。 */
52
+ export async function locateMemory(args, { dshHome, cwd }) {
53
+ const hasFile = typeof args.file === 'string' && args.file.trim() !== ''
54
+ const hasDate = args.date !== undefined
55
+ if (!hasFile && !hasDate) {
56
+ throw new Error('要么给 file(回顾文件名),要么给 date(YYYY-MM-DD,默认第 1 份)来定位哪一份回顾')
57
+ }
58
+ if (hasFile && hasDate) throw new Error('file 与 date 只能给一个')
59
+ if (hasFile) return String(args.file).trim()
60
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(String(args.date).trim())) {
61
+ throw new Error('date 要写成 YYYY-MM-DD(本地日期):' + String(args.date))
62
+ }
63
+ return resolveMemoryByDay({
64
+ dshHome, cwd,
65
+ date: String(args.date).trim(),
66
+ nth: args.nth === undefined ? 1 : args.nth
67
+ })
68
+ }
69
+
70
+ /**
71
+ * 把原文切成「块」:一次 ▸ 调用 + 紧跟着的缩进行 + 配对的 ◂ 状态。
72
+ *
73
+ * 两个必须承认的事实(render.js 的写法决定的,不是偷懒):
74
+ *
75
+ * 1. ◂ 状态行在结果正文「之后」——render.js 先写结果正文,再写「◂ 完成 / ◂ 报错:…」。
76
+ * 所以一条调用的输出,落在它的 ◂ 之前,而不是之后。
77
+ * 2. 同一条模型消息里的多个调用先连着写(参数各占一段缩进),结果再按同样顺序出场;
78
+ * 于是第 2 条调用后面的缩进段,可能是第 1 条调用的输出。**文本层面分不开**,
79
+ * 这里不做猜测:块内保留「发起 + 紧随的缩进段」,另把 ◂ 之前那一段记作结果区,
80
+ * 重叠时也照记,宁可多给一段,不伪造配对。
81
+ *
82
+ * 配对只认先进先出:第一个 ◂ 配第一个还没结果的 ▸。
83
+ * @param {string} body
84
+ * @returns {Array<object>}
85
+ */
86
+ export function parseBlocks(body) {
87
+ const lines = String(body ?? '').split('\n')
88
+ const blocks = []
89
+ const pending = []
90
+ let cur = null
91
+ let run = [] // 自上一个结构行以来的缩进行(去掉两格前缀)
92
+ for (let i = 0; i < lines.length; i++) {
93
+ const line = lines[i]
94
+ if (line.startsWith(MARK.call)) {
95
+ const text = line.slice(MARK.call.length)
96
+ const at = text.indexOf(': ')
97
+ const name = (at === -1 ? text : text.slice(0, at)).trim()
98
+ const firstArg = at === -1 ? '' : text.slice(at + 2).trim()
99
+ cur = {
100
+ line: i + 1, endLine: i + 1, name, firstArg,
101
+ argLines: [], status: '', failed: false,
102
+ resultText: [], resultLine: null
103
+ }
104
+ blocks.push(cur)
105
+ pending.push(cur)
106
+ run = []
107
+ continue
108
+ }
109
+ if (line.startsWith(MARK.result)) {
110
+ const target = pending.shift() ?? null
111
+ if (target) {
112
+ target.status = line.slice(MARK.result.length).trim()
113
+ target.failed = line.startsWith(ERROR_PREFIX)
114
+ target.resultText = run.slice()
115
+ target.resultLine = i + 1
116
+ target.endLine = i + 1
117
+ }
118
+ cur = null
119
+ run = []
120
+ continue
121
+ }
122
+ if (line.startsWith(MARK.user) || line.startsWith(MARK.model)) {
123
+ cur = null
124
+ run = []
125
+ continue
126
+ }
127
+ if (line.startsWith(' ') || line.trim() === '') {
128
+ if (line.trim() !== '') {
129
+ const clean = line.replace(/^ /, '')
130
+ run.push(clean)
131
+ if (cur) {
132
+ cur.argLines.push(clean)
133
+ cur.endLine = i + 1
134
+ }
135
+ }
136
+ continue
137
+ }
138
+ }
139
+ return blocks
140
+ }
141
+
142
+ /**
143
+ * 骨架:按「工具名 + 第一个参数行」去重,给行号与成败。
144
+ * 一份 1 MB 的回顾实测 468 次调用 → 去重后 288 条,够模型看出跑过哪些活。
145
+ * @param {Array<object>} blocks
146
+ * @param {{maxItems?:number}} options
147
+ * @returns {{calls:number, failures:number, distinct:number, groups:Array<object>}}
148
+ */
149
+ export function outlineOf(blocks, { maxItems = 400 } = {}) {
150
+ const groups = new Map()
151
+ for (const b of blocks) {
152
+ const key = b.name + '|' + b.firstArg.slice(0, 120)
153
+ let g = groups.get(b.name)
154
+ if (!g) { g = { tool: b.name, count: 0, failed: 0, items: new Map() }; groups.set(b.name, g) }
155
+ g.count++
156
+ if (b.failed) g.failed++
157
+ const item = g.items.get(key)
158
+ if (item) {
159
+ item.count++
160
+ if (b.failed) item.failed++
161
+ } else {
162
+ g.items.set(key, {
163
+ line: b.line,
164
+ firstArg: b.firstArg.length > 160 ? b.firstArg.slice(0, 158) + '…' : b.firstArg,
165
+ failed: b.failed,
166
+ count: 1
167
+ })
168
+ }
169
+ }
170
+ const out = []
171
+ let printed = 0
172
+ let distinct = 0
173
+ for (const g of [...groups.values()].sort((a, b) => b.count - a.count)) {
174
+ const items = [...g.items.values()].sort((a, b) => a.line - b.line)
175
+ distinct += items.length
176
+ const room = Math.max(0, maxItems - printed)
177
+ const shown = items.slice(0, room)
178
+ printed += shown.length
179
+ out.push({
180
+ tool: g.tool,
181
+ count: g.count,
182
+ failed: g.failed,
183
+ distinct: items.length,
184
+ shown: shown.length,
185
+ omitted: items.length - shown.length,
186
+ items: shown
187
+ })
188
+ }
189
+ return {
190
+ calls: blocks.length,
191
+ failures: blocks.filter((b) => b.failed).length,
192
+ distinct,
193
+ groups: out
194
+ }
195
+ }
196
+
197
+ /** 骨架渲染成人读得懂的几段文字。 */
198
+ export function renderOutline({ file, body, outline, filePath }) {
199
+ const lines = []
200
+ lines.push('原文骨架 · ' + file + '(' + filePath + ')')
201
+ lines.push('正文 ' + Buffer.byteLength(body, 'utf8') + ' 字节 / ' + body.split('\n').length + ' 行' +
202
+ ';工具调用 ' + outline.calls + ' 次(失败 ' + outline.failures + ' 次);去重后 ' + outline.distinct + ' 条')
203
+ lines.push('')
204
+ for (const g of outline.groups) {
205
+ lines.push('▸ ' + g.tool + ' · 共 ' + g.count + ' 次' + (g.failed > 0 ? '(失败 ' + g.failed + ')' : '') +
206
+ ' · 去重 ' + g.distinct + ' 条' + (g.omitted > 0 ? '(这里显示 ' + g.shown + ' 条,其余没列)' : ''))
207
+ for (const it of g.items) {
208
+ lines.push(' L' + it.line + (it.failed ? ' [失败]' : '') + ' ' + (it.firstArg || '(无参数)') +
209
+ (it.count > 1 ? ' ×' + it.count : ''))
210
+ }
211
+ lines.push('')
212
+ }
213
+ lines.push('要看某一条的完整参数与结果:mode=block, line=<上面那个 L 后面的数字>。')
214
+ lines.push('要按原样读完整段:mode=raw(cursor 分页)。要固化:把 scripts 装进 toolScript。')
215
+ return lines.join('\n')
216
+ }
217
+
218
+ /* ─────────────────────── 工具一:session_tool_create_read ─────────────────────── */
219
+
220
+ /** 读这一侧的参数校验;写那一侧另有 validateWriteArgs(0.3.3 拆开)。 */
221
+ function validateReadArgs(args) {
222
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) throw new Error('参数必须是对象')
223
+ const mode = args.mode === undefined ? 'outline' : String(args.mode)
224
+ if (!['outline', 'raw', 'block'].includes(mode)) throw new Error('mode 只收 outline / raw / block:' + mode)
225
+ if (args.toolScript !== undefined || args.replace !== undefined) {
226
+ throw new Error('这个工具只读;装工具脚本用 ' + TOOL_CREATE_WRITE_NAME)
227
+ }
228
+ if (args.cursor !== undefined && (!Number.isInteger(args.cursor) || args.cursor < 0)) throw new Error('cursor 是 0 起的字符偏移')
229
+ if (args.chars !== undefined && (!Number.isInteger(args.chars) || args.chars < 1000 || args.chars > 200000)) {
230
+ throw new Error('chars 要在 1000~200000 之间(默认 40000)')
231
+ }
232
+ if (args.line !== undefined && (!Number.isInteger(args.line) || args.line < 1)) throw new Error('line 是 1 起的正文行号(用骨架里的 L 后面的数字)')
233
+ if (args.span !== undefined && (!Number.isInteger(args.span) || args.span < 0)) throw new Error('span 是 0 起的整数(block 里多带几行)')
234
+ if (args.maxItems !== undefined && (!Number.isInteger(args.maxItems) || args.maxItems < 1)) throw new Error('maxItems 要是正整数')
235
+ return mode
236
+ }
237
+
238
+ /** 写盘那一侧的返回文本。 */
239
+ function renderWriteResult(res) {
240
+ const lines = [
241
+ '已装好工具脚本:' + res.id,
242
+ '目录:' + res.dir,
243
+ '文件:',
244
+ ...res.files.map((f) => ' · ' + f.name + '(' + f.kind + ' · ' + f.bytes + ' 字节 · sha256 ' + f.sha256.slice(0, 12) + '…)'),
245
+ res.backup ? '旧版本留在:' + res.backup : '',
246
+ '索引:' + res.indexPath,
247
+ '',
248
+ '现在就能跑:session_tool_call({ toolScript: "' + res.id + '" });先看命令就加 dryRun: true。',
249
+ '这个工具脚本的名字与用途会在下一轮装配时进入系统提示词(工具组那一段)。'
250
+ ]
251
+ return lines.filter((l) => l !== '').join('\n')
252
+ }
253
+
254
+ /**
255
+ * 工具定义(读):只回读原文,三档,绝不写盘。
256
+ * @param {{dshHome:string, logger?:object}} options
257
+ * @returns {object}
258
+ */
259
+ export function buildToolCreateReadDefinition({ dshHome, logger }) {
260
+ return {
261
+ name: TOOL_CREATE_READ_NAME,
262
+ description: [
263
+ 'Read one recall of this workspace back as original text: every tool call with its arguments and result.',
264
+ 'Use when the user asks how something was done and those steps are no longer in context (compacted away, or an earlier session).',
265
+ 'Read it yourself instead of asking the user to repeat the steps.',
266
+ '- outline (default): calls deduplicated by tool name + first argument, with line numbers and failures.',
267
+ '- raw: the body verbatim, paged with cursor.',
268
+ '- block: one call with its args and result.',
269
+ 'To run those commands again, install them with ' + TOOL_CREATE_WRITE_NAME + '.'
270
+ ].join(' '),
271
+ parameters: {
272
+ type: 'object',
273
+ additionalProperties: false,
274
+ properties: {
275
+ file: { type: 'string', description: 'Recall file name in this workspace.' },
276
+ date: { type: 'string', description: 'Local date YYYY-MM-DD; use instead of file.' },
277
+ nth: { type: 'integer', description: 'Which recall of that date (default 1, by compaction time).' },
278
+ mode: { type: 'string', enum: ['outline', 'raw', 'block'], description: 'Read mode (default outline).' },
279
+ cursor: { type: 'integer', description: 'raw: character offset to continue from (returned as nextCursor).' },
280
+ chars: { type: 'integer', description: 'raw: chunk size in characters, 1000-200000 (default 40000).' },
281
+ line: { type: 'integer', description: 'block: 1-based body line from the outline (the number after L).' },
282
+ span: { type: 'integer', description: 'block: extra lines to include after that block (default 0).' },
283
+ maxItems: { type: 'integer', description: 'outline: max distinct calls to list (default 400).' }
284
+ }
285
+ },
286
+ output: {
287
+ schema: {
288
+ type: 'object',
289
+ additionalProperties: false,
290
+ required: ['mode'],
291
+ properties: {
292
+ mode: { type: 'string', enum: ['outline', 'raw', 'block'] },
293
+ file: { type: 'string' },
294
+ path: { type: 'string' },
295
+ text: { type: 'string' },
296
+ calls: { type: 'number' },
297
+ failures: { type: 'number' },
298
+ distinct: { type: 'number' },
299
+ nextCursor: { type: 'number' },
300
+ totalChars: { type: 'number' },
301
+ done: { type: 'boolean' }
302
+ }
303
+ },
304
+ render: (_args, value) => [{ type: 'text', text: value.text ?? '' }]
305
+ },
306
+ async execute(args, exec) {
307
+ const mode = validateReadArgs(args)
308
+ const cwd = exec?.agent?.session?.header?.cwd
309
+ if (typeof cwd !== 'string' || cwd === '') throw new Error(TOOL_CREATE_READ_NAME + ' 需要知道当前工作区')
310
+ const file = await locateMemory(args, { dshHome, cwd })
311
+ const one = await readBodyOf({ dshHome, cwd, file })
312
+ const body = one.body
313
+
314
+ // ── 读:整段分页 ──
315
+ if (mode === 'raw') {
316
+ const cursor = args.cursor === undefined ? 0 : args.cursor
317
+ const chars = args.chars === undefined ? 40000 : args.chars
318
+ const slice = body.slice(cursor, cursor + chars)
319
+ const next = cursor + slice.length
320
+ const done = next >= body.length
321
+ return {
322
+ mode: 'raw', file: one.file, path: one.path,
323
+ text: slice,
324
+ nextCursor: done ? body.length : next,
325
+ totalChars: body.length,
326
+ done
327
+ }
328
+ }
329
+
330
+ const blocks = parseBlocks(body)
331
+
332
+ // ── 读:单块展开 ──
333
+ if (mode === 'block') {
334
+ if (args.line === undefined) throw new Error('block 要给 line(骨架里 L 后面的数字)')
335
+ const lines = body.split('\n')
336
+ if (args.line > lines.length) throw new Error('line 超过正文行数(' + lines.length + '):' + args.line)
337
+ const target = pickBlockAt(blocks, args.line)
338
+ if (!target) throw new Error('L' + args.line + ' 附近没有工具调用;用 mode=outline 先看骨架')
339
+ const span = args.span === undefined ? 0 : Math.max(0, Number(args.span) || 0)
340
+ const from = target.line
341
+ const to = Math.min(lines.length, Math.max(target.endLine, args.line) + span)
342
+ const slice = lines.slice(from - 1, to).join('\n')
343
+ const head = 'L' + from + '–' + to + ' · ' + target.name +
344
+ (target.failed ? ' · 【这一条报错了】' : (target.status ? ' · ' + target.status : ' · 没有结果(执行中断)'))
345
+ const parts = [head, '', slice]
346
+ // 结果区:◂ 之前那一段。和块内的缩进段一致时就不再抄一遍(同一段字不写两次)。
347
+ const same = target.resultText.length === target.argLines.length &&
348
+ target.resultText.every((l, i) => l === target.argLines[i])
349
+ if (target.resultText.length > 0 && !same) {
350
+ const capped = target.resultText.slice(0, 40)
351
+ parts.push('', '【结果区】紧挨着 ◂ 之前的内容(同一段缩进里可能混着上一条调用的输出,文本分不开):')
352
+ parts.push(capped.join('\n'))
353
+ if (target.resultText.length > capped.length) parts.push('…(还有 ' + (target.resultText.length - capped.length) + ' 行,用 mode=raw 按行号取)')
354
+ }
355
+ return {
356
+ mode: 'block', file: one.file, path: one.path,
357
+ text: parts.join('\n')
358
+ }
359
+ }
360
+
361
+ // ── 读:骨架(默认) ──
362
+ const outline = outlineOf(blocks, { maxItems: args.maxItems === undefined ? 400 : args.maxItems })
363
+ return {
364
+ mode: 'outline', file: one.file, path: one.path,
365
+ calls: outline.calls, failures: outline.failures, distinct: outline.distinct,
366
+ text: renderOutline({ file: one.file, filePath: one.path, body, outline })
367
+ }
368
+ },
369
+ presentCall: (args) => ({
370
+ card: 'generic',
371
+ title: 'Read recall original',
372
+ kind: 'other',
373
+ rawInput: args && (args.file || args.date || args.mode || 'outline')
374
+ })
375
+ }
376
+ }
377
+
378
+ /* ─────────────────────── 工具二:session_tool_create_write ─────────────────────── */
379
+
380
+ /** 写这一侧的参数校验:只收 toolScript / replace / 可选定位(定位只用来记出处)。 */
381
+ function validateWriteArgs(args) {
382
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) throw new Error('参数必须是对象')
383
+ if (args.toolScript === undefined) throw new Error('要给 toolScript:{ id, title, purpose, entry, scripts }')
384
+ if (args.toolScript === null || typeof args.toolScript !== 'object' || Array.isArray(args.toolScript)) throw new Error('toolScript 必须是对象')
385
+ for (const k of ['mode', 'cursor', 'chars', 'line', 'span', 'maxItems']) {
386
+ if (args[k] !== undefined) throw new Error('装工具脚本不收 ' + k + ':那是 ' + TOOL_CREATE_READ_NAME + ' 的参数')
387
+ }
388
+ if (args.file !== undefined && typeof args.file !== 'string') throw new Error('file 必须是字符串(只有想记出处时才给)')
389
+ if (args.file !== undefined && args.date !== undefined) throw new Error('file 与 date 只能给一个')
390
+ if (args.date !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(String(args.date))) throw new Error('date 要写成 YYYY-MM-DD')
391
+ if (args.nth !== undefined && (!Number.isInteger(args.nth) || args.nth < 1)) throw new Error('nth 必须是 1 起的整数')
392
+ if (args.replace !== undefined && typeof args.replace !== 'boolean') throw new Error('replace 必须是布尔值')
393
+ }
394
+
395
+ /**
396
+ * 工具定义(写):把一条链装成一个工具脚本。**不需要**先有一份回顾文件——
397
+ * file/date 只是可选的「出处记账」,不给也能装。
398
+ */
399
+ export function buildToolCreateWriteDefinition({ dshHome, logger }) {
400
+ return {
401
+ name: TOOL_CREATE_WRITE_NAME,
402
+ description: [
403
+ 'Seal a proven command chain into a toolScript: scripts plus a manifest under $DSH_HOME/session-memory/toolSequence/<id>/.',
404
+ 'Use only when you just ran those commands here, ' + TOOL_CREATE_READ_NAME + ' read it back from a recall, or the user says the way is worth keeping. A recall is one source, not a prerequisite.',
405
+ 'Source can also be material the user handed over or a workspace procedure (skill, AGENTS.md, handover note): copy its commands as written. If the user wants the script itself, that is scripts[].',
406
+ '- The artifact is scripts; a markdown note is not runnable and is not the output.',
407
+ '- Copy what ran, do not invent it. Seal only what repeats: the whole repeated chain, not only its tail.',
408
+ '- Fixed parts into scripts; per-run choices into params argv; secrets never into a script, read at run time.',
409
+ '- Keep scripts quiet: one conclusion line, the platform error text on failure.',
410
+ 'Pass only a script that already ran clean, never a draft: retries re-send the whole context.',
411
+ 'Installs immediately.'
412
+ ].join(' '),
413
+ parameters: {
414
+ type: 'object',
415
+ additionalProperties: false,
416
+ required: ['toolScript'],
417
+ properties: {
418
+ file: { type: 'string', description: 'Optional: recall file name to record as provenance.' },
419
+ date: { type: 'string', description: 'Optional: local date YYYY-MM-DD for provenance; use instead of file.' },
420
+ nth: { type: 'integer', description: 'Optional: which recall of that date (default 1, by compaction time).' },
421
+ toolScript: {
422
+ type: 'object',
423
+ description: 'The toolScript to install: the whole chain as scripts.',
424
+ properties: {
425
+ id: { type: 'string', description: 'Slug id: a-z0-9- only, starts with a letter, 2-41 chars.' },
426
+ title: { type: 'string', description: 'What this toolScript is called, in the user language.' },
427
+ purpose: { type: 'string', description: 'One line: what it does. Shows in the system prompt, so keep it short.' },
428
+ params: { type: 'array', items: { type: 'string' }, description: 'argv order of the entry script; shown in the toolSequence catalog line so the next call knows what to pass. Not validated — a wrong order silently shifts the arguments (params: ["prompt","workdir"] reads as $1 and $2).' },
429
+ entry: { type: 'string', description: 'Entry script file name; defaults to the first script.' },
430
+ steps: { type: 'array', items: { type: 'string' }, description: 'Script names in pipeline order.' },
431
+ timeoutMs: { type: 'integer', description: 'Per-step timeout, 1000-600000 (default 120000).' },
432
+ provenance: {
433
+ type: 'object',
434
+ description: 'Where it came from: recall file, body line, seq.',
435
+ properties: {
436
+ memory: { type: 'string' },
437
+ line: { type: 'integer' },
438
+ seq: { type: 'integer' }
439
+ }
440
+ },
441
+ scripts: {
442
+ type: 'array',
443
+ items: {
444
+ type: 'object',
445
+ properties: {
446
+ name: { type: 'string', description: 'Script file name; must match the extension of run.' },
447
+ run: { type: 'string', enum: ['bash', 'node', 'ps1', 'cmd'], description: 'Must match the file extension: bash/.sh, node/.js/.mjs/.cjs, ps1/.ps1, cmd/.bat/.cmd. ps1 runs Windows PowerShell 5.1; node runs the host runtime (PATH has no node).' },
448
+ content: { type: 'string', description: 'The script itself, max 64 KB; no recall section markers (## Summary / ## Original / ## Diary) inside.' },
449
+ params: { type: 'array', items: { type: 'string' }, description: 'Same argv order for this step; omit when the step takes no arguments.' }
450
+ }
451
+ }
452
+ },
453
+ docs: {
454
+ type: 'array',
455
+ description: 'Read-only notes (paths, pitfalls, speed baselines) — stored, never executed. Names must be unique; README.md is reserved for the generated file.',
456
+ items: {
457
+ type: 'object',
458
+ properties: { name: { type: 'string' }, content: { type: 'string' } }
459
+ }
460
+ }
461
+ }
462
+ },
463
+ replace: { type: 'boolean', description: 'Required when the id is already installed: overwrite it (old dir kept as .bak-*).' }
464
+ }
465
+ },
466
+ output: {
467
+ schema: {
468
+ type: 'object',
469
+ additionalProperties: false,
470
+ required: ['mode'],
471
+ properties: {
472
+ mode: { type: 'string', enum: ['write'] },
473
+ id: { type: 'string' },
474
+ dir: { type: 'string' },
475
+ files: { type: 'array', items: { type: 'object' } },
476
+ catalog: { type: 'string' },
477
+ text: { type: 'string' }
478
+ }
479
+ },
480
+ render: (_args, value) => [{ type: 'text', text: value.text ?? '' }]
481
+ },
482
+ async execute(args, exec) {
483
+ validateWriteArgs(args)
484
+ const spec = { ...args.toolScript }
485
+ if (args.file !== undefined || args.date !== undefined) {
486
+ const cwd = exec?.agent?.session?.header?.cwd
487
+ if (typeof cwd !== 'string' || cwd === '') throw new Error(TOOL_CREATE_WRITE_NAME + ' 给了 file/date 就需要知道当前工作区')
488
+ const mem = await locateMemory(args, { dshHome, cwd })
489
+ const kept = spec.provenance && typeof spec.provenance === 'object' ? spec.provenance : {}
490
+ spec.provenance = { ...kept, memory: typeof kept.memory === 'string' && kept.memory !== '' ? kept.memory : mem }
491
+ }
492
+ const res = await installToolScript({ dshHome, spec, replace: args.replace === true })
493
+ let catalog = ''
494
+ try { catalog = catalogText(dshHome, 'zh') } catch { catalog = '' }
495
+ return {
496
+ mode: 'write', id: res.id, dir: res.dir,
497
+ files: res.files.map((f) => ({ name: f.name, bytes: f.bytes, sha256: f.sha256, kind: f.kind })),
498
+ text: renderWriteResult(res), catalog
499
+ }
500
+ },
501
+ presentCall: (args) => ({
502
+ card: 'generic',
503
+ title: 'Install toolScript',
504
+ kind: 'other',
505
+ rawInput: args && args.toolScript ? args.toolScript.id : undefined
506
+ })
507
+ }
508
+ }
509
+
510
+ /**
511
+ * 找到这一行所在的块:落在块之间就取最近的上一个块;
512
+ * 落在第一个块之前(用户先说了一句)就取第一个块——模型通常拿着骨架里的行号回来。
513
+ */
514
+ export function pickBlockAt(blocks, line) {
515
+ if (!Array.isArray(blocks) || blocks.length === 0) return null
516
+ let best = null
517
+ for (const b of blocks) {
518
+ if (b.line <= line && (!best || b.line > best.line)) best = b
519
+ }
520
+ return best ?? blocks[0]
521
+ }
522
+
523
+ /* ────────────────────────── 工具二:session_tool_call ────────────────────────── */
524
+
525
+ /** 把 cwd 说法收成绝对路径:workspace / toolScript / 明确路径(必须在两者之内)。 */
526
+ function resolveRunCwd(value, { cwd, dir }) {
527
+ const raw = value === undefined ? 'workspace' : String(value)
528
+ if (raw === 'workspace') return cwd
529
+ if (raw === 'toolScript') return dir
530
+ const abs = path.resolve(raw)
531
+ const inWorkspace = inside(cwd, abs)
532
+ const inToolScript = inside(dir, abs)
533
+ if (!inWorkspace && !inToolScript) throw new Error('cwd 只能是 workspace / toolScript,或落在两者之内的路径:' + raw)
534
+ return abs
535
+ }
536
+
537
+ /** a 是否等于 b 或 b 在 a 之内。 */
538
+ function inside(a, b) {
539
+ const rel = path.relative(path.resolve(a), path.resolve(b))
540
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
541
+ }
542
+
543
+ /** 校验一次调用的形状。 */
544
+ function validateCallShape(call, where) {
545
+ if (call === null || typeof call !== 'object' || Array.isArray(call)) throw new Error(where + '必须是对象')
546
+ if (typeof call.toolScript !== 'string' || call.toolScript.trim() === '') throw new Error(where + 'toolScript 不能为空')
547
+ if (call.args !== undefined && (!Array.isArray(call.args) || call.args.some((a) => typeof a !== 'string' && typeof a !== 'number'))) {
548
+ throw new Error(where + 'args 必须是字符串数组')
549
+ }
550
+ if (call.stdin !== undefined && typeof call.stdin !== 'string') throw new Error(where + 'stdin 必须是字符串')
551
+ if (call.timeoutMs !== undefined && !Number.isInteger(call.timeoutMs)) throw new Error(where + 'timeoutMs 必须是整数')
552
+ if (call.cwd !== undefined && typeof call.cwd !== 'string') throw new Error(where + 'cwd 必须是字符串')
553
+ }
554
+
555
+ /**
556
+ * 点名的工具脚本在磁盘上找不到时的报错(0.4.7)。
557
+ *
558
+ * 为什么必须抛:工具组清单按会话冻住(见 catalog-snapshot.js),删掉的脚本还会留在清单里,
559
+ * 模型就会照着清单点名它。0.4.6 只把「✗ 没跑起来」写进正文交差,这次调用仍然算成功——
560
+ * 模型会当成跑过,接着往下说。这里改成抛错:这次调用显示为失败,模型非知道不可。
561
+ * 文案三件事讲全:叫的是什么、为什么清单里还有、现在怎么拿到真名单。
562
+ * @param {string} id 模型点名的 toolScript id
563
+ * @param {string} detail 底层原因(找不到清单 / 清单坏了)
564
+ * @returns {string}
565
+ */
566
+ function missingToolScriptMessage(id, detail) {
567
+ return [
568
+ '【这次调用被拦下,一条都没跑】工具组里没有 ' + id + ' 这个工具脚本。',
569
+ '底层原因:' + detail,
570
+ '为什么清单(系统提示词)里还挂着它:清单按会话冻住——会话中途装/删工具脚本不改系统提示词,' +
571
+ '否则整份会话要当未缓存输入重发一遍。所以已删掉的脚本可能继续出现在清单里,直到清单重取或换会话。',
572
+ '现在怎么办:不带参数调用 ' + TOOL_CALL_TOOL_NAME + ' 看磁盘上的真名单;' +
573
+ '要让本会话的清单按磁盘现状重取,在设置页把「清单词刷新时刻」切一次,或者开一个新会话。'
574
+ ].join('\n')
575
+ }
576
+
577
+ /**
578
+ * 工具定义:直接跑工具组里的工具脚本(一条或连着几条)。
579
+ * @param {{dshHome:string, logger?:object}} options
580
+ * @returns {object}
581
+ */
582
+ export function buildToolCallToolDefinition({ dshHome, logger }) {
583
+ return {
584
+ name: TOOL_CALL_TOOL_NAME,
585
+ description: [
586
+ 'Run an installed toolScript as-is, from the scripts recorded when it worked.',
587
+ '- toolScript: run its entry. step: another script of that toolScript. calls[]: several in a row, sequentially, each with its own exit code and output.',
588
+ '- No arguments: lists the installed toolScripts.',
589
+ '- dryRun: true prints the argv without executing; use it when unsure.',
590
+ '- More args than the step declares fails before anything runs; fewer is fine.',
591
+ '- Do not rewrite the scripts or re-derive their commands: they are the record of what worked.',
592
+ '- Only files inside the toolScript dir run; args go as argv, never through a shell.',
593
+ 'Each run is capped at 64 KB of output and 120 s by default.'
594
+ ].join(' '),
595
+ parameters: {
596
+ type: 'object',
597
+ additionalProperties: false,
598
+ properties: {
599
+ toolScript: { type: 'string', description: 'The toolScript id (an installed one).' },
600
+ step: { type: 'string', description: 'Script file name inside the toolScript; defaults to its entry.' },
601
+ args: { type: 'array', items: { type: 'string' }, description: 'Arguments for the script (argv); more than the step declares fails before running, fewer is allowed.' },
602
+ stdin: { type: 'string', description: 'Written to the script stdin when given.' },
603
+ cwd: { type: 'string', description: 'workspace (default) | toolScript | a path inside either.' },
604
+ timeoutMs: { type: 'integer', description: 'Per-step timeout, 1000-600000 (default: toolScript setting).' },
605
+ maxOutputBytes: { type: 'integer', description: 'Per-step stdout+stderr cap (default 65536).' },
606
+ dryRun: { type: 'boolean', description: 'Print argv without executing.' },
607
+ allowDrift: { type: 'boolean', description: 'Run even if the script no longer matches the manifest hash.' },
608
+ stopOnError: { type: 'boolean', description: 'Stop the batch at the first failure (default false: run all, report each).' },
609
+ calls: {
610
+ type: 'array',
611
+ description: 'Several steps in a row: [{ toolScript, step?, args?, stdin?, timeoutMs?, cwd? }].',
612
+ items: {
613
+ type: 'object',
614
+ properties: {
615
+ toolScript: { type: 'string' },
616
+ step: { type: 'string' },
617
+ args: { type: 'array', items: { type: 'string' } },
618
+ stdin: { type: 'string' },
619
+ timeoutMs: { type: 'integer' },
620
+ cwd: { type: 'string' }
621
+ }
622
+ }
623
+ }
624
+ }
625
+ },
626
+ output: {
627
+ schema: {
628
+ type: 'object',
629
+ additionalProperties: false,
630
+ required: ['mode'],
631
+ properties: {
632
+ mode: { type: 'string', enum: ['list', 'run', 'dry'] },
633
+ text: { type: 'string' },
634
+ runs: { type: 'array', items: { type: 'object' } },
635
+ failed: { type: 'number' },
636
+ skipped: { type: 'number' }
637
+ }
638
+ },
639
+ render: (_args, value) => [{ type: 'text', text: value.text ?? '' }]
640
+ },
641
+ async execute(args, exec) {
642
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) throw new Error('参数必须是对象')
643
+ const cwd = exec?.agent?.session?.header?.cwd
644
+ if (typeof cwd !== 'string' || cwd === '') throw new Error(TOOL_CALL_TOOL_NAME + ' 需要知道当前工作区')
645
+
646
+ // 不带参数:列名单(注入被关掉时也能看见有什么)
647
+ if (args.toolScript === undefined && args.calls === undefined) {
648
+ const list = await listToolScripts(dshHome)
649
+ const text = list.length === 0
650
+ ? '工具组还是空的。要装一个工具脚本:把你刚跑通的那条链用 ' + TOOL_CREATE_WRITE_NAME + ' 写成 toolScript(命令可以来自当前上下文,也可以用 ' + TOOL_CREATE_READ_NAME + ' 从回顾原文里翻回来)。'
651
+ : ['工具组 · ' + list.length + ' 个工具脚本:', ...list.map((b) =>
652
+ '· ' + b.id + '(' + b.title + '):' + b.purpose + '|入口 ' + b.entry +
653
+ (b.params.length > 0 ? '|参数 ' + b.params.join(' ') : '') +
654
+ (b.steps.length > 0 ? '|步骤 ' + b.steps.join(' → ') : '')),
655
+ '', '跑法:session_tool_call({ toolScript: "<id>" });先看命令加 dryRun: true。'].join('\n')
656
+ return { mode: 'list', text }
657
+ }
658
+
659
+ // 组装这一次要跑的清单
660
+ const requests = []
661
+ if (Array.isArray(args.calls)) {
662
+ if (args.toolScript !== undefined || args.step !== undefined) {
663
+ throw new Error('给了 calls 就别再给顶层 toolScript / step:每一项自带')
664
+ }
665
+ if (args.calls.length === 0) throw new Error('calls 不能是空数组')
666
+ if (args.calls.length > 20) throw new Error('一次最多连着跑 20 条(' + args.calls.length + ' 条)')
667
+ args.calls.forEach((c, i) => { validateCallShape(c, 'calls[' + i + ']:'); requests.push(c) })
668
+ } else {
669
+ validateCallShape({ toolScript: args.toolScript, args: args.args, stdin: args.stdin, timeoutMs: args.timeoutMs, cwd: args.cwd }, '')
670
+ requests.push({ toolScript: args.toolScript, step: args.step, args: args.args, stdin: args.stdin, timeoutMs: args.timeoutMs, cwd: args.cwd })
671
+ }
672
+
673
+ const stopOnError = args.stopOnError === true
674
+ const dryRun = args.dryRun === true
675
+ const allowDrift = args.allowDrift === true
676
+ const cap = normalizeMaxOutput(args.maxOutputBytes)
677
+
678
+ // 0.4.7:点名要先点得着——所有 toolScript 先找齐,再动手跑。
679
+ // 这样「点到已删除的脚本」是一条硬拦截:抛错 → 这次调用失败,而且一条都不会跑,
680
+ // 不会出现「前两条跑了、第三条才说不存在」的半截状态。
681
+ const resolved = []
682
+ for (const req of requests) {
683
+ const id = assertToolScriptId(req.toolScript)
684
+ try {
685
+ resolved.push({ req, id, ...(await loadToolScript(dshHome, id)) })
686
+ } catch (err) {
687
+ throw new Error(missingToolScriptMessage(id, String(err?.message ?? err)), { cause: err })
688
+ }
689
+ }
690
+
691
+ const runs = []
692
+ let skipped = 0
693
+ let stopped = false
694
+
695
+ for (let i = 0; i < resolved.length; i++) {
696
+ if (stopped) { skipped++; continue }
697
+ const { req, id, manifest, dir } = resolved[i]
698
+ try {
699
+ const step = req.step === undefined ? manifest.entry : String(req.step)
700
+ const script = (manifest.scripts ?? []).find((s) => s.name === step)
701
+ if (!script) throw new Error('这个工具脚本里没有这个脚本:' + step + '(有:' + (manifest.scripts ?? []).map((s) => s.name).join('、') + ')')
702
+ const file = resolveInside(dir, step)
703
+ const runCwd = resolveRunCwd(req.cwd === undefined ? args.cwd : req.cwd, { cwd, dir })
704
+ const timeoutMs = normalizeTimeout(req.timeoutMs === undefined ? (args.timeoutMs === undefined ? manifest.timeoutMs : args.timeoutMs) : req.timeoutMs)
705
+ // 参数契约:只在声明了 params 时校验,且只拦「比声明的多」——少传是合法的(可选参数、脚本默认值)。
706
+ const declared = Array.isArray(script.params) && script.params.length > 0
707
+ ? script.params
708
+ : (Array.isArray(manifest.params) ? manifest.params : [])
709
+ const argvArgs = req.args ?? []
710
+ if (declared.length > 0 && argvArgs.length > declared.length) {
711
+ throw new Error('这次给了 ' + argvArgs.length + ' 个参数,但 ' + step + ' 只声明了 ' + declared.length +
712
+ ' 个(' + declared.join(' ') + ');多出来的会错位。要传就把它们写进 toolScript 的 params,别硬塞')
713
+ }
714
+
715
+ if (dryRun) {
716
+ runs.push({
717
+ toolScript: id, step, run: script.run,
718
+ argv: [step, ...argvArgs.map(String)],
719
+ cwd: runCwd, timeoutMs, status: 'dry'
720
+ })
721
+ continue
722
+ }
723
+
724
+ const res = await runScript({
725
+ dshHome, toolScriptId: id, dir, manifest, step,
726
+ args: argvArgs, stdin: req.stdin,
727
+ cwd: runCwd, timeoutMs, maxOutputBytes: cap, allowDrift
728
+ })
729
+ const ok = res.exitCode === 0 && !res.timedOut
730
+ runs.push({
731
+ toolScript: id, step, status: ok ? 'ok' : 'fail',
732
+ exitCode: res.exitCode, signal: res.signal, timedOut: res.timedOut,
733
+ durationMs: res.durationMs, truncated: res.truncated, spill: res.spill,
734
+ drift: res.drift,
735
+ stdout: res.stdout, stderr: res.stderr, argv: res.argv
736
+ })
737
+ if (!ok && stopOnError) stopped = true
738
+ } catch (err) {
739
+ runs.push({ toolScript: String(req.toolScript), step: String(req.step ?? ''), status: 'error', error: String(err?.message ?? err) })
740
+ if (stopOnError) stopped = true
741
+ }
742
+ }
743
+
744
+ const failed = runs.filter((r) => r.status === 'fail' || r.status === 'error').length
745
+ return {
746
+ mode: dryRun ? 'dry' : 'run',
747
+ failed, skipped,
748
+ runs,
749
+ text: renderRuns({ runs, dryRun, skipped })
750
+ }
751
+ },
752
+ presentCall: (args) => ({
753
+ card: 'generic',
754
+ title: args && Array.isArray(args.calls) ? 'Run ' + args.calls.length + ' toolSequence steps' : 'Run toolScript',
755
+ kind: 'other',
756
+ rawInput: args && (args.toolScript || (Array.isArray(args.calls) ? 'calls: ' + args.calls.length : 'list'))
757
+ })
758
+ }
759
+ }
760
+
761
+ /** 跑完之后的回报文本:一条一块,失败先说清楚在哪一步。 */
762
+ export function renderRuns({ runs, dryRun, skipped }) {
763
+ const lines = []
764
+ if (dryRun) lines.push('只回显不执行(dryRun)——看清 argv 再真跑。')
765
+ for (const r of runs) {
766
+ if (r.status === 'dry') {
767
+ lines.push('▸ ' + r.toolScript + ' / ' + r.step + '(' + r.run + ')')
768
+ lines.push(' argv: ' + JSON.stringify(r.argv))
769
+ lines.push(' cwd: ' + r.cwd + ' 超时: ' + r.timeoutMs + 'ms')
770
+ continue
771
+ }
772
+ if (r.status === 'error') {
773
+ lines.push('✗ ' + r.toolScript + (r.step ? (' / ' + r.step) : '') + ' 没跑起来:' + r.error)
774
+ continue
775
+ }
776
+ const head = (r.status === 'ok' ? '✔ ' : '✗ ') + r.toolScript + ' / ' + r.step +
777
+ ' exit ' + (r.exitCode === null ? 'null' : r.exitCode) +
778
+ ' ' + r.durationMs + 'ms' +
779
+ (r.timedOut ? ' 【超时已终止】' : '') +
780
+ (r.drift ? ' 【脚本和清单哈希不一致,这次是显式放行】' : '')
781
+ lines.push(head)
782
+ const out = String(r.stdout ?? '').replace(/\s+$/, '')
783
+ const err = String(r.stderr ?? '').replace(/\s+$/, '')
784
+ if (out !== '') lines.push(out)
785
+ if (err !== '') lines.push('--- stderr ---', err)
786
+ if (r.truncated) lines.push('(输出被截断,完整内容:' + (r.spill || '溢写失败') + ')')
787
+ }
788
+ if (skipped > 0) lines.push('还有 ' + skipped + ' 条没跑(前面失败,stopOnError 生效了)。')
789
+ return lines.join('\n')
790
+ }
791
+
792
+ /* ────────────────────────── 给注入与设置页复用 ────────────────────────── */
793
+
794
+ export { catalogText, toolSequenceRoot, TOOL_SCRIPT_FILE, estimateTokens }