dsh-seal-scripts 0.4.10 → 0.4.12
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/README.en.md +22 -9
- package/README.md +26 -13
- package/lib/client.js +14 -26
- package/lib/core/catalog-snapshot.js +5 -8
- package/lib/core/host-limits.js +219 -0
- package/lib/core/index.js +17 -0
- package/lib/core/schema-runner.js +230 -128
- package/lib/core/schema-tools.js +105 -36
- package/lib/core/schema.js +59 -48
- package/lib/core/tool-transfer.js +174 -85
- package/lib/core/zip.js +328 -8
- package/lib/host/http-util.js +67 -24
- package/lib/host/routes/tools.js +69 -32
- package/package.json +1 -1
package/lib/core/schema-tools.js
CHANGED
|
@@ -21,6 +21,29 @@ import {
|
|
|
21
21
|
toolSequenceRoot, TOOL_SCRIPT_FILE, sha256OfFile
|
|
22
22
|
} from './schema.js'
|
|
23
23
|
import { runScript, normalizeTimeout, normalizeMaxOutput, interpreterOf } from './schema-runner.js'
|
|
24
|
+
import { readHostLimits, describeHostLimits } from './host-limits.js'
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 把返回值收成「能无损过 JSON」的形态(0.4.11 修正)。
|
|
28
|
+
*
|
|
29
|
+
* 宿主要求工具返回值是 lossless JSON:对象里带一个 undefined 就会整次调用失败
|
|
30
|
+
* (实测报错 "value is not lossless JSON")——正常跑完的那条 runs[i].pid 就是 undefined。
|
|
31
|
+
* 这里递归丢掉 undefined,其它值原样保留(null 保留,它和「没有这个字段」语义不同)。
|
|
32
|
+
* @param {unknown} value
|
|
33
|
+
* @returns {unknown}
|
|
34
|
+
*/
|
|
35
|
+
export function jsonSafe(value) {
|
|
36
|
+
if (Array.isArray(value)) return value.map((item) => jsonSafe(item))
|
|
37
|
+
if (value !== null && typeof value === 'object') {
|
|
38
|
+
const out = {}
|
|
39
|
+
for (const [key, item] of Object.entries(value)) {
|
|
40
|
+
if (item === undefined) continue
|
|
41
|
+
out[key] = jsonSafe(item)
|
|
42
|
+
}
|
|
43
|
+
return out
|
|
44
|
+
}
|
|
45
|
+
return value
|
|
46
|
+
}
|
|
24
47
|
|
|
25
48
|
export const TOOL_CREATE_READ_NAME = 'session_tool_create_read'
|
|
26
49
|
export const TOOL_CREATE_WRITE_NAME = 'session_tool_create_write'
|
|
@@ -143,11 +166,13 @@ export function parseBlocks(body) {
|
|
|
143
166
|
/**
|
|
144
167
|
* 骨架:按「工具名 + 第一个参数行」去重,给行号与成败。
|
|
145
168
|
* 一份 1 MB 的回顾实测 468 次调用 → 去重后 288 条,够模型看出跑过哪些活。
|
|
169
|
+
* 0.4.11:默认不再截到 400 条(那是个纯数值天花板),要看多少给多少;
|
|
170
|
+
* 显式 maxItems 才限制。
|
|
146
171
|
* @param {Array<object>} blocks
|
|
147
172
|
* @param {{maxItems?:number}} options
|
|
148
173
|
* @returns {{calls:number, failures:number, distinct:number, groups:Array<object>}}
|
|
149
174
|
*/
|
|
150
|
-
export function outlineOf(blocks, { maxItems =
|
|
175
|
+
export function outlineOf(blocks, { maxItems = Infinity } = {}) {
|
|
151
176
|
const groups = new Map()
|
|
152
177
|
for (const b of blocks) {
|
|
153
178
|
const key = b.name + '|' + b.firstArg.slice(0, 120)
|
|
@@ -174,7 +199,7 @@ export function outlineOf(blocks, { maxItems = 400 } = {}) {
|
|
|
174
199
|
for (const g of [...groups.values()].sort((a, b) => b.count - a.count)) {
|
|
175
200
|
const items = [...g.items.values()].sort((a, b) => a.line - b.line)
|
|
176
201
|
distinct += items.length
|
|
177
|
-
const room = Math.max(0, maxItems - printed)
|
|
202
|
+
const room = maxItems === Infinity ? items.length : Math.max(0, maxItems - printed)
|
|
178
203
|
const shown = items.slice(0, room)
|
|
179
204
|
printed += shown.length
|
|
180
205
|
out.push({
|
|
@@ -227,8 +252,9 @@ function validateReadArgs(args) {
|
|
|
227
252
|
throw new Error('这个工具只读;装工具脚本用 ' + TOOL_CREATE_WRITE_NAME)
|
|
228
253
|
}
|
|
229
254
|
if (args.cursor !== undefined && (!Number.isInteger(args.cursor) || args.cursor < 0)) throw new Error('cursor 是 0 起的字符偏移')
|
|
230
|
-
|
|
231
|
-
|
|
255
|
+
// 0.4.11:去掉 1000~200000 的死区间——分页只要求「是个正整数」。
|
|
256
|
+
if (args.chars !== undefined && (!Number.isInteger(args.chars) || args.chars <= 0)) {
|
|
257
|
+
throw new Error('chars 要是正整数(每页字符数,默认 40000)')
|
|
232
258
|
}
|
|
233
259
|
if (args.line !== undefined && (!Number.isInteger(args.line) || args.line < 1)) throw new Error('line 是 1 起的正文行号(用骨架里的 L 后面的数字)')
|
|
234
260
|
if (args.span !== undefined && (!Number.isInteger(args.span) || args.span < 0)) throw new Error('span 是 0 起的整数(block 里多带几行)')
|
|
@@ -278,10 +304,10 @@ export function buildToolCreateReadDefinition({ dshHome, logger }) {
|
|
|
278
304
|
nth: { type: 'integer', description: 'Which recall of that date (default 1, by compaction time).' },
|
|
279
305
|
mode: { type: 'string', enum: ['outline', 'raw', 'block'], description: 'Read mode (default outline).' },
|
|
280
306
|
cursor: { type: 'integer', description: 'raw: character offset to continue from (returned as nextCursor).' },
|
|
281
|
-
chars: { type: 'integer', description: 'raw: chunk size in characters
|
|
307
|
+
chars: { type: 'integer', description: 'raw: chunk size in characters (positive; default 40000).' },
|
|
282
308
|
line: { type: 'integer', description: 'block: 1-based body line from the outline (the number after L).' },
|
|
283
309
|
span: { type: 'integer', description: 'block: extra lines to include after that block (default 0).' },
|
|
284
|
-
maxItems: { type: 'integer', description: 'outline: max distinct calls to list (default
|
|
310
|
+
maxItems: { type: 'integer', description: 'outline: max distinct calls to list (default: all).' }
|
|
285
311
|
}
|
|
286
312
|
},
|
|
287
313
|
output: {
|
|
@@ -319,13 +345,13 @@ export function buildToolCreateReadDefinition({ dshHome, logger }) {
|
|
|
319
345
|
const slice = body.slice(cursor, cursor + chars)
|
|
320
346
|
const next = cursor + slice.length
|
|
321
347
|
const done = next >= body.length
|
|
322
|
-
return {
|
|
348
|
+
return jsonSafe({
|
|
323
349
|
mode: 'raw', file: one.file, path: one.path,
|
|
324
350
|
text: slice,
|
|
325
351
|
nextCursor: done ? body.length : next,
|
|
326
352
|
totalChars: body.length,
|
|
327
353
|
done
|
|
328
|
-
}
|
|
354
|
+
})
|
|
329
355
|
}
|
|
330
356
|
|
|
331
357
|
const blocks = parseBlocks(body)
|
|
@@ -353,19 +379,19 @@ export function buildToolCreateReadDefinition({ dshHome, logger }) {
|
|
|
353
379
|
parts.push(capped.join('\n'))
|
|
354
380
|
if (target.resultText.length > capped.length) parts.push('…(还有 ' + (target.resultText.length - capped.length) + ' 行,用 mode=raw 按行号取)')
|
|
355
381
|
}
|
|
356
|
-
return {
|
|
382
|
+
return jsonSafe({
|
|
357
383
|
mode: 'block', file: one.file, path: one.path,
|
|
358
384
|
text: parts.join('\n')
|
|
359
|
-
}
|
|
385
|
+
})
|
|
360
386
|
}
|
|
361
387
|
|
|
362
388
|
// ── 读:骨架(默认) ──
|
|
363
|
-
const outline = outlineOf(blocks, { maxItems: args.maxItems === undefined ?
|
|
364
|
-
return {
|
|
389
|
+
const outline = outlineOf(blocks, { maxItems: args.maxItems === undefined ? Infinity : args.maxItems })
|
|
390
|
+
return jsonSafe({
|
|
365
391
|
mode: 'outline', file: one.file, path: one.path,
|
|
366
392
|
calls: outline.calls, failures: outline.failures, distinct: outline.distinct,
|
|
367
393
|
text: renderOutline({ file: one.file, filePath: one.path, body, outline })
|
|
368
|
-
}
|
|
394
|
+
})
|
|
369
395
|
},
|
|
370
396
|
presentCall: (args) => ({
|
|
371
397
|
card: 'generic',
|
|
@@ -408,6 +434,7 @@ export function buildToolCreateWriteDefinition({ dshHome, logger }) {
|
|
|
408
434
|
'- Copy what ran, do not invent it. Seal only what repeats: the whole repeated chain, not only its tail.',
|
|
409
435
|
'- Fixed parts into scripts; per-run choices into params argv; secrets never into a script, read at run time.',
|
|
410
436
|
'- Keep scripts quiet: one conclusion line, the platform error text on failure.',
|
|
437
|
+
'- Exit code is the verdict: a failing script must exit non-zero.',
|
|
411
438
|
'Pass only a script that already ran clean, never a draft: retries re-send the whole context.',
|
|
412
439
|
'Installs immediately.'
|
|
413
440
|
].join(' '),
|
|
@@ -423,13 +450,13 @@ export function buildToolCreateWriteDefinition({ dshHome, logger }) {
|
|
|
423
450
|
type: 'object',
|
|
424
451
|
description: 'The toolScript to install: the whole chain as scripts.',
|
|
425
452
|
properties: {
|
|
426
|
-
id: { type: 'string', description: 'Slug id: a-z0-9- only, starts with a letter,
|
|
453
|
+
id: { type: 'string', description: 'Slug id: a-z0-9- only, starts with a letter, no length limit.' },
|
|
427
454
|
title: { type: 'string', description: 'What this toolScript is called, in the user language.' },
|
|
428
455
|
purpose: { type: 'string', description: 'One line: what it does. Shows in the system prompt, so keep it short.' },
|
|
429
456
|
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).' },
|
|
430
457
|
entry: { type: 'string', description: 'Entry script file name; defaults to the first script.' },
|
|
431
458
|
steps: { type: 'array', items: { type: 'string' }, description: 'Script names in pipeline order.' },
|
|
432
|
-
timeoutMs: { type: 'integer', description: 'Per-step timeout
|
|
459
|
+
timeoutMs: { type: 'integer', description: 'Per-step timeout in ms (default: the host timeoutMs; clamped to the host maxTimeoutMs).' },
|
|
433
460
|
provenance: {
|
|
434
461
|
type: 'object',
|
|
435
462
|
description: 'Where it came from: recall file, body line, seq.',
|
|
@@ -446,7 +473,7 @@ export function buildToolCreateWriteDefinition({ dshHome, logger }) {
|
|
|
446
473
|
properties: {
|
|
447
474
|
name: { type: 'string', description: 'Script file name; must match the extension of run.' },
|
|
448
475
|
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).' },
|
|
449
|
-
content: { type: 'string', description: 'The script itself
|
|
476
|
+
content: { type: 'string', description: 'The script itself; no recall section markers (## Summary / ## Original / ## Diary) inside.' },
|
|
450
477
|
params: { type: 'array', items: { type: 'string' }, description: 'Same argv order for this step; omit when the step takes no arguments.' }
|
|
451
478
|
}
|
|
452
479
|
}
|
|
@@ -636,7 +663,7 @@ export function buildToolCallToolDefinition({ dshHome, logger }) {
|
|
|
636
663
|
'- More args than the step declares fails before anything runs; fewer is fine.',
|
|
637
664
|
'- Do not rewrite the scripts or re-derive their commands: they are the record of what worked.',
|
|
638
665
|
'- Only files inside the toolScript dir run; args go as argv, never through a shell.',
|
|
639
|
-
'
|
|
666
|
+
'Timeout and per-stream output cap follow the host terminal settings; a run that hits its timeout is NOT killed — it moves to the background and keeps writing to a log file (pid and path are returned; stop it with the shell tool).'
|
|
640
667
|
].join(' '),
|
|
641
668
|
parameters: {
|
|
642
669
|
type: 'object',
|
|
@@ -647,8 +674,8 @@ export function buildToolCallToolDefinition({ dshHome, logger }) {
|
|
|
647
674
|
args: { type: 'array', items: { type: 'string' }, description: 'Arguments for the script (argv); more than the step declares fails before running, fewer is allowed.' },
|
|
648
675
|
stdin: { type: 'string', description: 'Written to the script stdin when given.' },
|
|
649
676
|
cwd: { type: 'string', description: 'workspace (default) | toolScript | a path inside either.' },
|
|
650
|
-
timeoutMs: { type: 'integer', description: 'Per-step timeout
|
|
651
|
-
maxOutputBytes: { type: 'integer', description: 'Per-step stdout+stderr cap (default
|
|
677
|
+
timeoutMs: { type: 'integer', description: 'Per-step timeout in ms (default: toolScript setting; capped at the host maxTimeoutMs).' },
|
|
678
|
+
maxOutputBytes: { type: 'integer', description: 'Per-step stdout+stderr cap (default: the host maxOutputBytes).' },
|
|
652
679
|
dryRun: { type: 'boolean', description: 'Print argv without executing.' },
|
|
653
680
|
allowDrift: { type: 'boolean', description: 'Run even if the script no longer matches the manifest hash.' },
|
|
654
681
|
stopOnError: { type: 'boolean', description: 'Stop the batch at the first failure (default false: run all, report each).' },
|
|
@@ -679,7 +706,12 @@ export function buildToolCallToolDefinition({ dshHome, logger }) {
|
|
|
679
706
|
text: { type: 'string' },
|
|
680
707
|
runs: { type: 'array', items: { type: 'object' } },
|
|
681
708
|
failed: { type: 'number' },
|
|
682
|
-
skipped: { type: 'number' }
|
|
709
|
+
skipped: { type: 'number' },
|
|
710
|
+
// 0.4.11 起:超时转后台时带这一项(有几条转后台了)。
|
|
711
|
+
// 宿主按 additionalProperties: false 校验输出,这一项不声明就会让整次调用判失败。
|
|
712
|
+
background: { type: 'number' },
|
|
713
|
+
// 宿主终端设置没读全时的说明(只在读不全时出现)。
|
|
714
|
+
limitsNote: { type: 'string' }
|
|
683
715
|
}
|
|
684
716
|
},
|
|
685
717
|
render: (_args, value) => [{ type: 'text', text: value.text ?? '' }]
|
|
@@ -699,7 +731,7 @@ export function buildToolCallToolDefinition({ dshHome, logger }) {
|
|
|
699
731
|
(b.params.length > 0 ? '|参数 ' + b.params.join(' ') : '') +
|
|
700
732
|
(b.steps.length > 0 ? '|步骤 ' + b.steps.join(' → ') : '')),
|
|
701
733
|
'', '跑法:session_tool_call({ toolScript: "<id>" });先看命令加 dryRun: true。'].join('\n')
|
|
702
|
-
return { mode: 'list', text }
|
|
734
|
+
return jsonSafe({ mode: 'list', text })
|
|
703
735
|
}
|
|
704
736
|
|
|
705
737
|
// 组装这一次要跑的清单
|
|
@@ -709,7 +741,7 @@ export function buildToolCallToolDefinition({ dshHome, logger }) {
|
|
|
709
741
|
throw new Error('给了 calls 就别再给顶层 toolScript / step:每一项自带')
|
|
710
742
|
}
|
|
711
743
|
if (args.calls.length === 0) throw new Error('calls 不能是空数组')
|
|
712
|
-
|
|
744
|
+
// 0.4.11:去掉「一次最多 20 条」的死上线,按给的顺序全跑。
|
|
713
745
|
args.calls.forEach((c, i) => { validateCallShape(c, 'calls[' + i + ']:'); requests.push(c) })
|
|
714
746
|
} else {
|
|
715
747
|
validateCallShape({ toolScript: args.toolScript, args: args.args, stdin: args.stdin, timeoutMs: args.timeoutMs, cwd: args.cwd }, '')
|
|
@@ -719,7 +751,11 @@ export function buildToolCallToolDefinition({ dshHome, logger }) {
|
|
|
719
751
|
const stopOnError = args.stopOnError === true
|
|
720
752
|
const dryRun = args.dryRun === true
|
|
721
753
|
const allowDrift = args.allowDrift === true
|
|
722
|
-
|
|
754
|
+
// 0.4.11:默认值与天花板都来自宿主终端设置(读不到时按 DSH 默认值并注明原因)。
|
|
755
|
+
const limits = readHostLimits()
|
|
756
|
+
const limitsNote = describeHostLimits(limits)
|
|
757
|
+
const limitsMissed = limits.missed.length > 0
|
|
758
|
+
const cap = normalizeMaxOutput(args.maxOutputBytes, limits)
|
|
723
759
|
|
|
724
760
|
// 0.4.7:点名要先点得着——所有 toolScript 先找齐,再动手跑。
|
|
725
761
|
// 这样「点到已删除的脚本」是一条硬拦截:抛错 → 这次调用失败,而且一条都不会跑,
|
|
@@ -745,11 +781,11 @@ export function buildToolCallToolDefinition({ dshHome, logger }) {
|
|
|
745
781
|
for (const p of planned) {
|
|
746
782
|
if (stopped) { skipped++; continue }
|
|
747
783
|
if (dryRun) {
|
|
748
|
-
runs.push({
|
|
784
|
+
runs.push(jsonSafe({
|
|
749
785
|
toolScript: p.id, step: p.step, run: p.script.run,
|
|
750
786
|
argv: [p.step, ...p.argvArgs],
|
|
751
|
-
cwd: p.runCwd, timeoutMs: p.timeoutMs, status: 'dry'
|
|
752
|
-
})
|
|
787
|
+
cwd: p.runCwd, timeoutMs: p.timeoutMs, maxOutputBytes: cap, limits: limitsNote, status: 'dry'
|
|
788
|
+
}))
|
|
753
789
|
continue
|
|
754
790
|
}
|
|
755
791
|
let res
|
|
@@ -767,24 +803,44 @@ export function buildToolCallToolDefinition({ dshHome, logger }) {
|
|
|
767
803
|
throw new Error('这条没跑起来,整次调用算失败:' + p.id + ' / ' + p.step + '\n' +
|
|
768
804
|
String(err?.message ?? err) + done, { cause: err })
|
|
769
805
|
}
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
806
|
+
// 0.4.11:超时不再杀进程,转后台继续跑——这不是失败,是「还没跑完」。
|
|
807
|
+
const background = res.background === true
|
|
808
|
+
const ok = !background && res.exitCode === 0 && !res.timedOut
|
|
809
|
+
runs.push(jsonSafe({
|
|
810
|
+
toolScript: p.id, step: p.step,
|
|
811
|
+
status: background ? 'background' : (ok ? 'ok' : 'fail'),
|
|
773
812
|
exitCode: res.exitCode, signal: res.signal, timedOut: res.timedOut,
|
|
813
|
+
background, pid: res.pid, logFile: res.logFile, stderrFile: res.stderrFile,
|
|
774
814
|
durationMs: res.durationMs, truncated: res.truncated, spill: res.spill,
|
|
775
|
-
drift: res.drift,
|
|
815
|
+
drift: res.drift, timeoutMs: p.timeoutMs, maxOutputBytes: cap,
|
|
776
816
|
stdout: res.stdout, stderr: res.stderr, argv: res.argv
|
|
777
|
-
})
|
|
778
|
-
if (!ok && stopOnError) stopped = true
|
|
817
|
+
}))
|
|
818
|
+
if (!ok && !background && stopOnError) stopped = true
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
// 0.4.12:脚本自己跑失败(非零退出码)也算失败——整次调用抛错(红)。
|
|
822
|
+
// 但输出一个字都不丢:异常正文里带上每条的 ✔/✗、exit code、stdout、stderr。
|
|
823
|
+
// 「超时转后台」不算失败:那是还没跑完,pid 与日志路径照常回传。
|
|
824
|
+
const crashed = runs.filter((r) => r.status === 'fail')
|
|
825
|
+
if (crashed.length > 0) {
|
|
826
|
+
const names = crashed.map((r) => r.toolScript + ' / ' + r.step +
|
|
827
|
+
'(exit ' + (r.exitCode === null ? 'null' : r.exitCode) + (r.timedOut ? ',超时被终止' : '') + ')').join('、')
|
|
828
|
+
throw new Error(
|
|
829
|
+
'【这次调用没成功】' + crashed.length + ' 条没跑成:' + names + '\n\n' +
|
|
830
|
+
renderRuns({ runs, dryRun: false, skipped })
|
|
831
|
+
)
|
|
779
832
|
}
|
|
780
833
|
|
|
781
834
|
const failed = runs.filter((r) => r.status === 'fail' || r.status === 'error').length
|
|
782
|
-
|
|
835
|
+
const background = runs.filter((r) => r.status === 'background').length
|
|
836
|
+
return jsonSafe({
|
|
783
837
|
mode: dryRun ? 'dry' : 'run',
|
|
784
838
|
failed, skipped,
|
|
839
|
+
...background > 0 ? { background } : {},
|
|
840
|
+
...limitsMissed && !dryRun ? { limitsNote } : {},
|
|
785
841
|
runs,
|
|
786
842
|
text: renderRuns({ runs, dryRun, skipped })
|
|
787
|
-
}
|
|
843
|
+
})
|
|
788
844
|
},
|
|
789
845
|
presentCall: (args) => ({
|
|
790
846
|
card: 'generic',
|
|
@@ -803,17 +859,30 @@ export function renderRuns({ runs, dryRun, skipped }) {
|
|
|
803
859
|
if (r.status === 'dry') {
|
|
804
860
|
lines.push('▸ ' + r.toolScript + ' / ' + r.step + '(' + r.run + ')')
|
|
805
861
|
lines.push(' argv: ' + JSON.stringify(r.argv))
|
|
806
|
-
lines.push(' cwd: ' + r.cwd + ' 超时: ' + r.timeoutMs + 'ms')
|
|
862
|
+
lines.push(' cwd: ' + r.cwd + ' 超时: ' + r.timeoutMs + 'ms 输出上限: ' + r.maxOutputBytes + ' 字节')
|
|
863
|
+
if (r.limits) lines.push(' ' + r.limits)
|
|
807
864
|
continue
|
|
808
865
|
}
|
|
809
866
|
if (r.status === 'error') {
|
|
810
867
|
lines.push('✗ ' + r.toolScript + (r.step ? (' / ' + r.step) : '') + ' 没跑起来:' + r.error)
|
|
811
868
|
continue
|
|
812
869
|
}
|
|
870
|
+
if (r.status === 'background') {
|
|
871
|
+
// 0.4.10 及以前这里是「超时已终止」;0.4.11 起进程活着,输出继续往日志里写。
|
|
872
|
+
lines.push('⏳ ' + r.toolScript + ' / ' + r.step + ' 【仍在运行 after ' + r.timeoutMs +
|
|
873
|
+
'ms; moved to background】pid ' + r.pid)
|
|
874
|
+
lines.push(' 它没有被杀,还在跑,后面会继续往这个文件里写:')
|
|
875
|
+
lines.push(' ' + r.logFile + (r.stderrFile ? '(stderr: ' + r.stderrFile + ')' : ''))
|
|
876
|
+
const head = String(r.stdout ?? '').replace(/\s+$/, '')
|
|
877
|
+
if (head !== '') lines.push(' —— 已经写出来的部分 ——', head)
|
|
878
|
+
const errHead = String(r.stderr ?? '').replace(/\s+$/, '')
|
|
879
|
+
if (errHead !== '') lines.push(' —— stderr ——', errHead)
|
|
880
|
+
lines.push(' 要看后续输出:读上面那个文件(tail 它);要停它:kill ' + r.pid)
|
|
881
|
+
continue
|
|
882
|
+
}
|
|
813
883
|
const head = (r.status === 'ok' ? '✔ ' : '✗ ') + r.toolScript + ' / ' + r.step +
|
|
814
884
|
' exit ' + (r.exitCode === null ? 'null' : r.exitCode) +
|
|
815
885
|
' ' + r.durationMs + 'ms' +
|
|
816
|
-
(r.timedOut ? ' 【超时已终止】' : '') +
|
|
817
886
|
(r.drift ? ' 【脚本和清单哈希不一致,这次是显式放行】' : '')
|
|
818
887
|
lines.push(head)
|
|
819
888
|
const out = String(r.stdout ?? '').replace(/\s+$/, '')
|
package/lib/core/schema.js
CHANGED
|
@@ -19,6 +19,7 @@ import fs from 'node:fs'
|
|
|
19
19
|
import fsp from 'node:fs/promises'
|
|
20
20
|
import path from 'node:path'
|
|
21
21
|
import crypto from 'node:crypto'
|
|
22
|
+
import { DSH_DEFAULTS } from './host-limits.js'
|
|
22
23
|
|
|
23
24
|
/** 工具组目录名(在记忆根下,和 session-memory/<工作区 key>/ 平级)。 */
|
|
24
25
|
export const TOOL_SEQUENCE_DIR = 'toolSequence'
|
|
@@ -35,11 +36,11 @@ export const RUNS_DIR = '_runs'
|
|
|
35
36
|
/** 索引格式版本。 */
|
|
36
37
|
const INDEX_VERSION = 1
|
|
37
38
|
|
|
38
|
-
/** 工具脚本 id:小写、数字、连字符,开头顶一个字母。 */
|
|
39
|
-
export const BUNDLE_ID_RE = /^[a-z][a-z0-9-]
|
|
39
|
+
/** 工具脚本 id:小写、数字、连字符,开头顶一个字母。0.4.11 起不再限长度,只留字符集。 */
|
|
40
|
+
export const BUNDLE_ID_RE = /^[a-z][a-z0-9-]*$/
|
|
40
41
|
|
|
41
|
-
/**
|
|
42
|
-
export const FILE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]
|
|
42
|
+
/** 脚本文件名:首字符字母数字,其余字母数字 . _ -;0.4.11 起不再限长度。 */
|
|
43
|
+
export const FILE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
|
|
43
44
|
|
|
44
45
|
/** 每种执行方式允许的扩展名。 */
|
|
45
46
|
export const RUN_EXT = {
|
|
@@ -52,13 +53,11 @@ export const RUN_EXT = {
|
|
|
52
53
|
/** 执行方式的中文名(报错与 README 用)。 */
|
|
53
54
|
export const RUN_LABEL = { bash: 'bash 脚本', node: 'node 脚本', ps1: 'PowerShell 脚本', cmd: '批处理' }
|
|
54
55
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
export const CATALOG_MAX_LINES = 24
|
|
61
|
-
export const CATALOG_MAX_CHARS = 1600
|
|
56
|
+
/*
|
|
57
|
+
* 0.4.11:单脚本 64 KB、整包 512 KB、清单 24 行 / 1600 字这四个死数全部删掉。
|
|
58
|
+
* 它们不防任何真实风险——脚本正文照样要过文件名白名单、<!--ovr: 分区标记与 sha256;
|
|
59
|
+
* 清单多长由设置页的开关管,用户明确接受这份 token 开销。
|
|
60
|
+
*/
|
|
62
61
|
|
|
63
62
|
/**
|
|
64
63
|
* 工具组根目录。
|
|
@@ -111,7 +110,7 @@ export function runsDir(dshHome) {
|
|
|
111
110
|
export function assertToolScriptId(id) {
|
|
112
111
|
const s = String(id ?? '').trim()
|
|
113
112
|
if (!BUNDLE_ID_RE.test(s)) {
|
|
114
|
-
throw new Error('toolScript.id
|
|
113
|
+
throw new Error('toolScript.id 要写成小写字母开头的短名(只许 a-z 0-9 -,不许路径、不许点开头):' + (s || '(空)'))
|
|
115
114
|
}
|
|
116
115
|
return s
|
|
117
116
|
}
|
|
@@ -184,15 +183,41 @@ export function readIndexSync(dshHome) {
|
|
|
184
183
|
}
|
|
185
184
|
}
|
|
186
185
|
|
|
187
|
-
/**
|
|
186
|
+
/**
|
|
187
|
+
* 严格读索引:**文件在但读不出来 / 解析不了就抛错**,不再静默当成「一个工具都没装」。
|
|
188
|
+
*
|
|
189
|
+
* 区分两件事:文件不存在 = 还没装过(空索引,正常);文件在却坏了 = 坏(抛)。
|
|
190
|
+
* 只有名单路径用严格版(用户/模型点开名单时该看见「索引坏了」);系统提示词那条同步路径
|
|
191
|
+
* 仍用宽松版 readIndexSync —— 索引坏了不能让整场会话装配崩掉。
|
|
192
|
+
* @param {string} dshHome
|
|
193
|
+
* @returns {Promise<{version:number, toolScripts:Record<string, object>}>}
|
|
194
|
+
*/
|
|
195
|
+
export async function readIndexStrict(dshHome) {
|
|
196
|
+
const file = indexPath(dshHome)
|
|
197
|
+
let raw
|
|
198
|
+
try {
|
|
199
|
+
raw = await fsp.readFile(file, 'utf8')
|
|
200
|
+
} catch (err) {
|
|
201
|
+
if (err && err.code === 'ENOENT') return { version: INDEX_VERSION, toolScripts: {} }
|
|
202
|
+
throw new Error('工具组索引读不出来:' + file + '(' + (err?.message ?? err) + ')')
|
|
203
|
+
}
|
|
204
|
+
let parsed
|
|
205
|
+
try {
|
|
206
|
+
parsed = JSON.parse(raw)
|
|
207
|
+
} catch {
|
|
208
|
+
throw new Error('工具组索引坏了(不是合法 JSON):' + file + '。' +
|
|
209
|
+
'它不是手改的文件——把它删掉,再重装任意一个工具脚本即可重建。')
|
|
210
|
+
}
|
|
211
|
+
if (!parsed || typeof parsed !== 'object' || !parsed.toolScripts || typeof parsed.toolScripts !== 'object') {
|
|
212
|
+
throw new Error('工具组索引格式不对(缺 toolScripts):' + file + '。删掉它,再重装任意一个工具脚本即可重建。')
|
|
213
|
+
}
|
|
214
|
+
return { version: parsed.version ?? INDEX_VERSION, toolScripts: parsed.toolScripts }
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** 宽松读索引(安装/导出等路径用):坏了就当空,绝不抛。严格版见 readIndexStrict。 */
|
|
188
218
|
export async function readIndex(dshHome) {
|
|
189
219
|
try {
|
|
190
|
-
|
|
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 }
|
|
220
|
+
return await readIndexStrict(dshHome)
|
|
196
221
|
} catch {
|
|
197
222
|
return { version: INDEX_VERSION, toolScripts: {} }
|
|
198
223
|
}
|
|
@@ -227,7 +252,8 @@ export async function writeIndex(dshHome, index) {
|
|
|
227
252
|
* @returns {Promise<Array<{id:string,title:string,purpose:string,entry:string,params:string[],steps:string[]}>>}
|
|
228
253
|
*/
|
|
229
254
|
export async function listToolScripts(dshHome) {
|
|
230
|
-
|
|
255
|
+
// 0.4.12:名单是用户/模型看得见的那一屏——索引坏了必须报红,不能显示成「工具组还是空的」。
|
|
256
|
+
const { toolScripts } = await readIndexStrict(dshHome)
|
|
231
257
|
const out = []
|
|
232
258
|
for (const [id, meta] of Object.entries(toolScripts)) {
|
|
233
259
|
if (!meta || typeof meta !== 'object') continue
|
|
@@ -276,13 +302,11 @@ export function normalizeToolScript(spec) {
|
|
|
276
302
|
if (title === '') throw new Error('toolScript.title 不能为空:一句话说这个工具脚本叫什么')
|
|
277
303
|
const purpose = String(spec.purpose ?? '').trim()
|
|
278
304
|
if (purpose === '') throw new Error('toolScript.purpose 不能为空:一句话说这个工具脚本干什么')
|
|
279
|
-
if (Buffer.byteLength(purpose, 'utf8') > 600) throw new Error('toolScript.purpose 太长了(600 字节以内),它会上系统提示词')
|
|
280
305
|
|
|
281
306
|
const scriptsIn = Array.isArray(spec.scripts) ? spec.scripts : []
|
|
282
307
|
const docsIn = Array.isArray(spec.docs) ? spec.docs : []
|
|
283
308
|
if (scriptsIn.length === 0) throw new Error('toolScript.scripts 不能是空的:至少要有一个能跑的脚本')
|
|
284
309
|
|
|
285
|
-
let total = 0
|
|
286
310
|
const seen = new Set()
|
|
287
311
|
const scripts = scriptsIn.map((s, i) => {
|
|
288
312
|
if (s === null || typeof s !== 'object' || Array.isArray(s)) throw new Error('scripts[' + i + '] 必须是对象')
|
|
@@ -290,12 +314,9 @@ export function normalizeToolScript(spec) {
|
|
|
290
314
|
const run = assertRunMatches(name, s.run)
|
|
291
315
|
const content = String(s.content ?? '')
|
|
292
316
|
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
317
|
if (content.includes('<!--ovr:')) throw new Error(name + ' 里出现了回顾文件的分区标记 <!--ovr:,会污染解析,删掉它')
|
|
296
318
|
if (seen.has(name)) throw new Error('同一个脚本名出现了两次:' + name)
|
|
297
319
|
seen.add(name)
|
|
298
|
-
total += bytes
|
|
299
320
|
return { name, run, content, params: Array.isArray(s.params) ? s.params.map(String) : [] }
|
|
300
321
|
})
|
|
301
322
|
const docSeen = new Set()
|
|
@@ -310,21 +331,20 @@ export function normalizeToolScript(spec) {
|
|
|
310
331
|
docSeen.add(name)
|
|
311
332
|
const content = String(d.content ?? '')
|
|
312
333
|
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
334
|
return { name, content }
|
|
317
335
|
})
|
|
318
|
-
if (total > MAX_TOOL_SCRIPT_BYTES) throw new Error('这个工具脚本超过 512 KB(' + total + ' 字节);拆成两个')
|
|
319
|
-
|
|
320
336
|
const entry = assertFileName(spec.entry ?? scripts[0].name)
|
|
321
337
|
if (!seen.has(entry)) throw new Error('toolScript.entry 必须是 scripts 里的一个文件:' + entry)
|
|
322
338
|
const steps = (Array.isArray(spec.steps) ? spec.steps : []).map((s) => assertFileName(s))
|
|
323
339
|
for (const s of steps) if (!seen.has(s)) throw new Error('toolScript.steps 里的 ' + s + ' 不在 scripts 里')
|
|
324
340
|
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
341
|
+
// 0.4.11:清单里的超时只收正数,天花板交给宿主的 maxTimeoutMs(运行时夹,见 host-limits.js)。
|
|
342
|
+
// 装工具脚本这一步不该依赖终端设置读没读到,所以这里既不夹、也不比宿主更严。
|
|
343
|
+
// 修:没给 timeoutMs 就不写这一项,运行时回落到宿主终端设置。
|
|
344
|
+
// 以前这里写死 DSH_DEFAULTS.timeoutMs(120000),会让设置页改的超时对新封存的工具不生效。
|
|
345
|
+
const timeoutMs = spec.timeoutMs === undefined ? undefined : Number(spec.timeoutMs)
|
|
346
|
+
if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) {
|
|
347
|
+
throw new Error('toolScript.timeoutMs 要是正数(毫秒);实际运行时还会夹到 DSH 的 maxTimeoutMs')
|
|
328
348
|
}
|
|
329
349
|
|
|
330
350
|
const provenance = spec.provenance && typeof spec.provenance === 'object'
|
|
@@ -443,7 +463,7 @@ export async function installToolScript({ dshHome, spec, replace = false }) {
|
|
|
443
463
|
}
|
|
444
464
|
|
|
445
465
|
/**
|
|
446
|
-
*
|
|
466
|
+
* 注入到系统提示词的那几行:按 id 排,全部列出,purpose 全文(0.4.11 起不再截断)。
|
|
447
467
|
* 每次装配时现读索引(同步),装/删工具脚本后下一轮就变——这是它唯一会动缓存的地方。
|
|
448
468
|
* @param {string} dshHome
|
|
449
469
|
* @param {'zh'|'en'|string} lang
|
|
@@ -469,25 +489,16 @@ export function catalogText(dshHome, lang = 'zh') {
|
|
|
469
489
|
lines.push(en
|
|
470
490
|
? '【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
491
|
: '【工具组 · ' + entries.length + ' 个工具脚本】已经固化好的脚本,直接用 session_tool_call 跑;不用自己写代码,也不用重新找命令。')
|
|
472
|
-
//
|
|
492
|
+
// 指引紧跟标题、排在工具脚本条目之前。
|
|
473
493
|
lines.push(runHint + guide)
|
|
474
|
-
|
|
494
|
+
// 0.4.11:不再有「还有 N 个」和 78 字截断——多少条都列全,purpose 原样显示。
|
|
475
495
|
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
496
|
const title = String(m.title ?? id)
|
|
482
497
|
const purpose = String(m.purpose ?? '').replace(/\s+/g, ' ')
|
|
483
|
-
const short = purpose.length > 80 ? purpose.slice(0, 78) + '…' : purpose
|
|
484
498
|
const params = Array.isArray(m.params) && m.params.length > 0 ? '|' + (en ? 'args ' : '参数 ') + m.params.join(' ') : ''
|
|
485
499
|
lines.push(en
|
|
486
|
-
? '· ' + id + ' (' + title + '): ' +
|
|
487
|
-
: '· ' + id + '(' + title + '):' +
|
|
488
|
-
shown++
|
|
500
|
+
? '· ' + id + ' (' + title + '): ' + purpose + '|entry ' + String(m.entry ?? '') + params
|
|
501
|
+
: '· ' + id + '(' + title + '):' + purpose + '|入口 ' + String(m.entry ?? '') + params)
|
|
489
502
|
}
|
|
490
|
-
|
|
491
|
-
if (chars.length > CATALOG_MAX_CHARS) return chars.slice(0, CATALOG_MAX_CHARS - 1).join('') + '…'
|
|
492
|
-
return chars.join('')
|
|
503
|
+
return lines.join('\n')
|
|
493
504
|
}
|