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 CHANGED
@@ -116,13 +116,13 @@ $DSH_HOME/session-memory/toolSequence/
116
116
  <script> the file that actually runs (.sh / .js .mjs .cjs / .ps1 / .bat .cmd)
117
117
  README.md generated from the manifest at install time, for humans
118
118
  <notes>.md read-only notes: pitfalls, paths, benchmarks (never executed)
119
- _runs/ full logs of output that exceeded the cap
119
+ _runs/ full stdout/stderr log of every run (not only when over a cap)
120
120
  <id>.bak-<timestamp>/ previous directory kept on reinstall or import
121
121
  ~~~
122
122
 
123
123
  ### How the model learns about it
124
124
 
125
- The end of the system prompt gains a toolSequence block: at most 24 entries, and the whole block (header + guide + entries) is capped at 1600 characters, one line each — `· id (title): purpose|entry <entry>|args <p1> <p2>`. After sealing you never have to remind the model that the tool exists.
125
+ The end of the system prompt gains a toolSequence block: every sealed toolScript is listed (0.4.11 removed the entry and character caps), one line each — `· id (title): purpose|entry <entry>|args <p1> <p2>`. The purpose is shown in full. After sealing you never have to remind the model that the tool exists.
126
126
 
127
127
  When that list refreshes (option **When the list is refreshed**):
128
128
 
@@ -143,7 +143,7 @@ Changing that mode refreshes every remembered session to the current list — so
143
143
 
144
144
  - Calling `session_tool_call` without arguments lists every tool script.
145
145
  - `dryRun: true` echoes the arguments and cwd without running.
146
- - `calls: []` runs up to 20 entries in order, reporting exit code, duration, stdout and stderr per entry.
146
+ - `calls: []` runs the entries in order (no 20-entry cap since 0.4.11), reporting exit code, duration, stdout and stderr per entry.
147
147
 
148
148
  ### Validation when sealing
149
149
 
@@ -152,10 +152,10 @@ Changing that mode refreshes every remembered session to the current list — so
152
152
  | `id` | starts with a lowercase letter, 2–41 chars, only `a-z0-9-` |
153
153
  | file name | starts alphanumeric, no leading dot, no path separators, up to 61 chars |
154
154
  | `run` vs extension | bash→`.sh`; node→`.js/.mjs/.cjs`; ps1→`.ps1`; cmd→`.bat/.cmd` |
155
- | size | one script ≤ 64 KB; one tool script (scripts + docs) ≤ 512 KB |
156
- | `title` / `purpose` | non-empty; purpose ≤ 600 bytes (it enters the prompt; display truncates at 80 chars) |
155
+ | size | no cap (0.4.11 removed the 64 KB and 512 KB limits) |
156
+ | `title` / `purpose` | non-empty; any length, shown in full in the prompt |
157
157
  | `entry` / `steps` | must name files in `scripts`; entry defaults to the first script |
158
- | `timeoutMs` | 1000–600000, default 120000 |
158
+ | `timeoutMs` | any positive ms, clamped at run time to the host maxTimeoutMs |
159
159
  | docs | must be `.md`, may not be called `README.md`, no duplicates |
160
160
  | script body | non-empty; must not contain `<!--ovr:` (it would break review markers) |
161
161
  | same id exists | refused without `replace`; the error quotes the first 12 hex chars of the manifest sha256 |
@@ -170,8 +170,8 @@ Changing that mode refreshes every remembered session to the current list — so
170
170
  | argv | interpreter arguments + absolute script path + your args, passed as an array, never through a shell |
171
171
  | cwd | `workspace` (session workspace), `toolScript` (the script directory), or an absolute path inside either |
172
172
  | environment | inherits `process.env`, plus `TOOL_NAME`, `TOOL_SCRIPT`, `TOOL_ROOT`, `DSH_HOME` |
173
- | timeout | 120 s by default, 600 s maximum; SIGTERM → 2 s → SIGKILL; process group on POSIX, `taskkill /T /F` on Windows |
174
- | output | 64 KB default, 1 MB maximum, stdout and stderr share the budget; overflow goes in full to `_runs/` and the reply carries the head plus the file path |
173
+ | timeout | follows the DSH terminal settings (120 s default, capped by DSH maxTimeoutMs); on expiry the process is NOT killed, it moves to the background and the reply carries pid and the log path; explicit stop: SIGTERM → 2 s → SIGKILL; process group on POSIX, `taskkill /T /F` on Windows |
174
+ | output | defaults to DSH maxOutputBytes, no extra 1 MB ceiling; stdout/stderr go straight into `_runs/` and the reply carries the head plus the file path, and overflow is never dropped |
175
175
  | result | `{ exitCode, signal, timedOut, stdout, stderr, truncated, spill }`; success is not judged for the caller |
176
176
  | argument count | more arguments than `params` declares fails before running (they would shift); fewer is fine |
177
177
  | drift | sha256 is compared first; mismatch refuses, `allowDrift: true` allows it and marks the result |
@@ -179,7 +179,7 @@ Changing that mode refreshes every remembered session to the current list — so
179
179
 
180
180
  ### Import / export
181
181
 
182
- - **Export**: Sealed tools tab → Export. Packs `toolSequence.zip` (store, no compression) straight into the current session workspace and returns the real path — no browser download. Over 24 MB is refused.
182
+ - **Export**: Sealed tools tab → Export. Packs `toolSequence.zip` (store, no compression) straight into the current session workspace and returns the real path — no browser download. No size limit since 0.4.11: entries are streamed to disk, so memory does not grow with the toolset.
183
183
  - **Import**: pick a zip → `dryRun` preview of what will be installed, overwritten and skipped → confirm to write. An existing directory is kept as `.bak-<timestamp>`.
184
184
  - `_index.json` inside the package is not trusted; the index is rebuilt from the files on disk. `_runs`, backup directories, escaping paths and invalid ids are skipped.
185
185
  - Limits: 64 MB per entry, 128 MB total; zip64 and encrypted archives are not supported.
@@ -225,6 +225,19 @@ At level 1 or 0 the model sees the diary or the keywords — both written by the
225
225
  - The preview box on the Reviews tab runs the same assembly function as the real injection: what you see is what that turn receives (selecting one review shows only that one).
226
226
  - If assembly fails (a review too large) it does not silently become no reviews; the model gets a diagnostic: how many, total size, the largest file, what to do.
227
227
 
228
+ ### The two review tools
229
+
230
+ With Auto review on, the plugin installs two more tools; with the switch off they do not appear.
231
+
232
+ | Tool | Purpose | Key arguments |
233
+ |---|---|---|
234
+ | `session_mem_read` | find a review from one clue: this workspace → children → (with permission) siblings and parents; one hit per call | `need` (required, the user's own words), `skip` (files already read), `allowOuter` (search sibling and parent workspaces) |
235
+ | `session_mem_write` | read one review's original dialogue; write keywords and diary, many at once | `file` or `date`+`nth`; `keywords`, `diary`; batch with `writes[]` |
236
+
237
+ - Locator only, no content = that review's Original section: dialogue only, tool calls (▸/◂ and their output) stripped.
238
+ - Writing many uses `writes[]`: all-or-nothing — one bad entry and the batch is not written.
239
+ - Neither tool changes depth: only a read that hits this workspace's own review raises it one level and pins it.
240
+
228
241
  ### How it relates to sealing
229
242
 
230
243
  In one line: reviews are the raw-material store for sealing. Across sessions and machines the model uses `session_tool_create_read` to find the original commands and arguments, then `session_tool_create_write` to seal them. You do not need to tune the review side — turn on Auto review and keep the defaults.
package/README.md CHANGED
@@ -127,13 +127,13 @@ $DSH_HOME/session-memory/toolSequence/
127
127
  <脚本> 真正执行的文件(.sh / .js .mjs .cjs / .ps1 / .bat .cmd)
128
128
  README.md 安装时按清单自动生成,给人看
129
129
  <说明>.md 只读说明:坑、路径、速度基准(不会被执行)
130
- _runs/ 输出超限时的全量日志
130
+ _runs/ 每次执行的 stdout/stderr 全量日志(不是只在超限时才写)
131
131
  <id>.bak-<时间戳>/ 覆盖安装 / 导入时保留的旧目录
132
132
  ~~~
133
133
 
134
134
  ### 模型怎么知道有这个工具
135
135
 
136
- 系统提示词末尾会多一段「工具组」:条目最多 24 条,整段(标题 + 引导句 + 条目)上限 1600 字符,每条一行——`id(标题):用途 | 入口 | 参数`。所以封存之后不需要你提醒它有这个工具。
136
+ 系统提示词末尾会多一段「工具组」:装了几个就列几个(0.4.11 起没有条数与字数上限),每条一行——`id(标题):用途 | 入口 | 参数`,purpose 原样全文显示。所以封存之后不需要你提醒它有这个工具。
137
137
 
138
138
  清单什么时候换新(选项「清单词刷新时刻」):
139
139
 
@@ -154,19 +154,19 @@ $DSH_HOME/session-memory/toolSequence/
154
154
 
155
155
  - 不带参数调用 `session_tool_call`:列全部工具脚本名单。
156
156
  - `dryRun: true`:只回显参数与 cwd,不执行。
157
- - `calls: []`:最多 20 条顺序执行,逐条报退出码、耗时、stdout、stderr。
157
+ - `calls: []`:按给的顺序全跑(0.4.11 起不再限 20 条),逐条报退出码、耗时、stdout、stderr。
158
158
 
159
159
  ### 封存时的校验
160
160
 
161
161
  | 项 | 规则 |
162
162
  |---|---|
163
- | `id` | 小写字母开头,2–41 位,只允许 `a-z0-9-` |
164
- | 文件名 | 首字符字母数字,不许点开头、不许路径分隔符,最长 61 |
163
+ | `id` | 小写字母开头(0.4.11 起不限长度),只允许 `a-z0-9-` |
164
+ | 文件名 | 首字符字母数字,只许字母数字与 . _ -,不许路径、不许点开头,不限长度 |
165
165
  | `run` 与扩展名 | bash→`.sh`;node→`.js/.mjs/.cjs`;ps1→`.ps1`;cmd→`.bat/.cmd` |
166
- | 体积 | 单脚本 ≤ 64 KB;一个工具脚本(脚本+说明)≤ 512 KB |
167
- | `title` / `purpose` | 非空;purpose ≤ 600 字节(它进系统提示词,展示时超 80 字符截断) |
166
+ | 体积 | 不设上限(0.4.11 删掉了 64 KB / 512 KB 两个死数) |
167
+ | `title` / `purpose` | 非空;purpose 不限字数,进系统提示词时全文显示 |
168
168
  | `entry` / `steps` | 必须是 `scripts` 里的文件;entry 缺省取第一个脚本 |
169
- | `timeoutMs` | 1000–600000,默认 120000 |
169
+ | `timeoutMs` | 正数即可(毫秒);运行时只夹到 DSH 的 maxTimeoutMs,默认取 DSH 的 timeoutMs |
170
170
  | 说明文件 | 必须 `.md`,不许叫 `README.md`,不许重名 |
171
171
  | 脚本正文 | 不许空;不许出现 `<!--ovr:`(会破坏回顾分区) |
172
172
  | 同名已存在 | 无 `replace` 直接拒绝,并给出清单 sha256 前 12 位 |
@@ -181,19 +181,19 @@ $DSH_HOME/session-memory/toolSequence/
181
181
  | argv | 解释器参数 + 脚本绝对路径 + 你的 args,数组传递,不经过 shell |
182
182
  | cwd | `workspace`(会话工作区)、`toolScript`(脚本目录),或落在两者之内的绝对路径 |
183
183
  | 环境变量 | 继承 `process.env`,另加 `TOOL_NAME`、`TOOL_SCRIPT`、`TOOL_ROOT`、`DSH_HOME` |
184
- | 超时 | 默认 120 s,上限 600 s;SIGTERM → 2 s → SIGKILL;POSIX 杀进程组,Windows 走 `taskkill /T /F` |
185
- | 输出 | 默认 64 KB、上限 1 MB,stdout 与 stderr 共用额度;超限时全量写进 `_runs/`,返回值给前一段加文件路径 |
186
- | 返回值 | `{ exitCode, signal, timedOut, stdout, stderr, truncated, spill }`,不替调用方判成败 |
184
+ | 超时 | 跟随 DSH 终端设置(默认 120 s,天花板是 DSH 的 maxTimeoutMs);到点不杀进程,转后台继续跑并返回 pid 与日志路径;显式停机仍是 SIGTERM → 2 s → SIGKILL;POSIX 杀进程组,Windows 走 `taskkill /T /F` |
185
+ | 输出 | 默认取 DSH 的 maxOutputBytes,不再另设 1 MB 封顶;每次执行都写进 `_runs/`,返回值给前一段加文件路径,超限也不丢内容 |
186
+ | 返回值 | `{ exitCode, signal, timedOut, background, pid, logFile, stdout, stderr, truncated, spill }`,不替调用方判成败 |
187
187
  | 参数个数 | 实参多于 `params` 声明的数量 → 开跑前失败(会错位);少传合法 |
188
188
  | 漂移 | 跑前比对清单 sha256,不一致拒绝;`allowDrift: true` 放行并在结果里标 `drift` |
189
189
  | 越界 | 只跑工具脚本目录内的文件;清单里没有的脚本名直接拒绝 |
190
190
 
191
191
  ### 导入 / 导出
192
192
 
193
- - **导出**:自创工具页 → 导出。打成 `toolSequence.zip`(store,不压缩),直接写进当前会话的工作区目录并回真实路径,不走浏览器下载;超过 24 MB 直接拒绝。
193
+ - **导出**:自创工具页 → 导出。打成 `toolSequence.zip`(store,不压缩),直接写进当前会话的工作区目录并回真实路径,不走浏览器下载;0.4.11 起不限大小,边读边写盘(内存占用与工具组大小无关)。
194
194
  - **导入**:选 zip → 先 `dryRun` 预览「会装哪些 / 会盖哪些 / 跳过哪些」→ 确认才写;同名目录留 `.bak-<时间戳>`。
195
195
  - 包内的 `_index.json` 不采信,索引按落地文件重建;`_runs`、备份目录、越界路径、非法 id 一律跳过。
196
- - 限制:单文件 ≤ 64 MB、合计 ≤ 128 MB,不支持 zip64 与加密包。
196
+ - 大小:不设死上限。0.4.11 起导入先把请求体流式落盘、再逐条解进 staging(不吃内存),解压炸弹按「解压后总字节 + 16 MB 余量 vs 磁盘可用空间」判——装不下才拒绝。不支持 zip64 与加密包。
197
197
  <a name="sec-reviews"></a>
198
198
 
199
199
 
@@ -238,6 +238,19 @@ $DSH_HOME/session-memory/toolSequence/
238
238
  - 设置页「回顾」页的预览框与真实注入走同一个装配函数:框里看到的就是这一轮会送进去的文字(选中某条时只看那条)。
239
239
  - 装配失败(例如回顾太大)不会静默变成「没有回顾」,而是给模型一段诊断:几份、合计多大、最大那份是谁、怎么处理。
240
240
 
241
+ ### 两个回顾工具
242
+
243
+ 打开「自动回顾」后,插件会另外装这两个工具;总闸关着时它们不出现。
244
+
245
+ | 工具 | 作用 | 关键参数 |
246
+ |---|---|---|
247
+ | `session_mem_read` | 用一句线索找回顾:本工作区 → 子级 →(许可后)平级与上级,一次只交一条命中 | `need`(必填,用户原话里的线索)、`skip`(已读过的文件,避免重复)、`allowOuter`(放行外圈) |
248
+ | `session_mem_write` | 读某一份回顾的对话原文;写关键词与日记,可一次多份 | `file` 或 `date`+`nth` 定位;`keywords`、`diary`;批量用 `writes[]` |
249
+
250
+ - 只给定位、不给内容 = 读那份的「原文」区:只留对话,工具调用(▸/◂ 及其输出)整块剔除。
251
+ - 写多份用 `writes[]`:全部合格才落盘,任一份不合格整批都不写。
252
+ - 深度不由这两个工具改:只有 `session_mem_read` 真的读到「本工作区自己」那份时,才升一级并锁定。
253
+
241
254
  ### 和脚本固存的关系
242
255
 
243
256
  一句话:回顾是固存的原料库。跨会话、换机器时,模型靠 `session_tool_create_read` 从回顾里翻出当初的命令与参数,再 `session_tool_create_write` 封存。回顾本身的细节不需要你调——打开「自动回顾」,其余用默认值即可。
package/lib/client.js CHANGED
@@ -832,24 +832,13 @@ window.__ModuleLoader__.load({
832
832
  } catch (e) { setErr(String(e.message || e)) }
833
833
  }
834
834
 
835
- /** 0.4.3:文件读成 base64。分块转,几 MB 的包也不会把调用栈撑爆。 */
836
- function readFileAsBase64(file) {
837
- return new Promise(function (yes, no) {
838
- var reader = new FileReader()
839
- reader.onerror = function () { no(new Error('读不到这个文件:' + (file && file.name ? file.name : ''))) }
840
- reader.onload = function () {
841
- try {
842
- var bytes = new Uint8Array(reader.result)
843
- var chunk = 0x8000
844
- var parts = []
845
- for (var i = 0; i < bytes.length; i += chunk) {
846
- parts.push(String.fromCharCode.apply(null, bytes.subarray(i, i + chunk)))
847
- }
848
- yes(window.btoa(parts.join('')))
849
- } catch (e) { no(e) }
850
- }
851
- reader.readAsArrayBuffer(file)
852
- })
835
+ /**
836
+ * 0.4.11:导入不再把文件读成 base64 再塞进 JSON,直接把 File 当请求体发过去。
837
+ * 服务端流式落盘再逐条解包,包多大都不吃内存。
838
+ */
839
+ function importUrl(name, dryRun) {
840
+ return API + 'toolSequence/import?name=' + encodeURIComponent(name || 'toolSequence.zip') +
841
+ (dryRun ? '&dryRun=1' : '')
853
842
  }
854
843
 
855
844
  /** 点「导入」:先把隐藏的 file 选择框清空再点,选同一个文件也要能触发。 */
@@ -866,15 +855,14 @@ window.__ModuleLoader__.load({
866
855
  if (!file) return
867
856
  setBusy(true); setErr(''); setImportNote(''); setImportPlan(null); setImportFile(null)
868
857
  try {
869
- var data = await readFileAsBase64(file)
870
- var res = await fetch(API + 'toolSequence/import', {
858
+ var res = await fetch(importUrl(file.name, true), {
871
859
  method: 'POST',
872
- headers: { 'Content-Type': 'application/json' },
873
- body: JSON.stringify({ name: file.name, data: data, dryRun: true })
860
+ headers: { 'Content-Type': 'application/zip' },
861
+ body: file
874
862
  })
875
863
  var json = await res.json()
876
864
  if (!res.ok) throw new Error((json.error && json.error.message) || ('HTTP ' + res.status))
877
- setImportFile({ name: file.name, data: data })
865
+ setImportFile({ name: file.name, file: file })
878
866
  setImportPlan({ imported: json.imported || [], overwritten: json.overwritten || [], skipped: json.skipped || [] })
879
867
  } catch (e) {
880
868
  setErr(String(e.message || e))
@@ -886,10 +874,10 @@ window.__ModuleLoader__.load({
886
874
  if (isBusy || !importFile) return
887
875
  setBusy(true); setErr(''); setImportNote('')
888
876
  try {
889
- var res = await fetch(API + 'toolSequence/import', {
877
+ var res = await fetch(importUrl(importFile.name, false), {
890
878
  method: 'POST',
891
- headers: { 'Content-Type': 'application/json' },
892
- body: JSON.stringify({ name: importFile.name, data: importFile.data, dryRun: false })
879
+ headers: { 'Content-Type': 'application/zip' },
880
+ body: importFile.file
893
881
  })
894
882
  var json = await res.json()
895
883
  if (!res.ok) throw new Error((json.error && json.error.message) || ('HTTP ' + res.status))
@@ -20,8 +20,10 @@
20
20
 
21
21
  import { catalogText } from './schema.js'
22
22
 
23
- /** 最多记住多少个会话的清单,超出按插入顺序丢最旧的(Map 保序)。 */
24
- export const MAX_SNAPSHOTS = 64
23
+ /*
24
+ * 0.4.11:删掉「最多记 64 个会话」这个死上限。快照就是一个会话一条短字符串,
25
+ * 内存 Map 不淘汰也不会出事;淘汰反而会让老会话重新现算,白白多一次缓存未命中。
26
+ */
25
27
 
26
28
  /** @type {Map<string, {text: string, lang: string}>} */
27
29
  const snapshots = new Map()
@@ -39,14 +41,9 @@ export function catalogTextForSession(dshHome, lang, sessionId) {
39
41
  const hit = snapshots.get(key)
40
42
  if (hit !== undefined && hit.lang === lang) return hit.text
41
43
  const text = catalogText(dshHome, lang)
42
- // 覆盖已有键时要先删再插:Map 的插入顺序决定谁先被挤出去,重算过的会话应排到队尾。
44
+ // 覆盖已有键时要先删再插,让重算过的会话排到队尾(集合没有上限,只是保持一个确定的次序)。
43
45
  snapshots.delete(key)
44
46
  snapshots.set(key, { text, lang })
45
- while (snapshots.size > MAX_SNAPSHOTS) {
46
- const oldest = snapshots.keys().next()
47
- if (oldest.done) break
48
- snapshots.delete(oldest.value)
49
- }
50
47
  return text
51
48
  }
52
49
 
@@ -0,0 +1,219 @@
1
+ /**
2
+ * 跟着 DSH 走(0.4.11):超时与单流输出上限不再由插件自己写死,只从宿主的终端设置里读。
3
+ *
4
+ * 为什么要这一层:0.4.10 及以前插件里有三个死数——
5
+ * DEFAULT_TIMEOUT_MS = 120000、MAX_TIMEOUT_MS = 600000、DEFAULT_MAX_OUTPUT = 64KB + 1MB 封顶。
6
+ * 用户在设置页把「命令超时」调成别的值,插件的脚本执行完全不理,还是按 12 万毫秒走。
7
+ * 这不是「限制」的问题,是「设置不生效」的问题;所以这里改成三档取值:
8
+ *
9
+ * 1. ctx.shell(dsh-bash-local / dsh-bash-sandbox 注册的执行器)的 live config —— 最准,
10
+ * 它就是真正在跑命令的那个实例;schemastery 的字段是 ref,读 .get()。
11
+ * 2. ctx.settings(SettingsForms)的 describe() 里 bash-sandbox 那一行的 value ——
12
+ * 同一条设置的另一份投影(设置页显示的就是它)。
13
+ * 3. 都不在(老宿主,或服务还没起来):退回 DSH 自己的默认值 120000 / 600000 / 64000,
14
+ * 并**记下来原因**。绝不退回一个比 DSH 更小的数——那等于偷偷把上限压回去。
15
+ *
16
+ * 三项分开取:某一项读到就用读到的,读不到的项各自降级,不会因为少一项就整组丢掉。
17
+ */
18
+
19
+ /** DSH 自己的默认值(@deepseek-ai/dsh-bash-local 的 Config:timeoutMs 12e4 / maxTimeoutMs 6e5 / maxOutputBytes 64e3)。 */
20
+ export const DSH_DEFAULTS = Object.freeze({
21
+ timeoutMs: 120000,
22
+ maxTimeoutMs: 600000,
23
+ maxOutputBytes: 64000
24
+ })
25
+
26
+ /** 设置页上「终端」那一段在宿主里的命名空间(bash / pwsh / 老名字)。 */
27
+ const SETTINGS_NS = ['bash-sandbox', 'pwsh-sandbox', 'shell']
28
+
29
+ /** 三项的名字(一次性取,避免每处各写一遍)。 */
30
+ export const LIMIT_KEYS = Object.freeze(['timeoutMs', 'maxTimeoutMs', 'maxOutputBytes'])
31
+
32
+ /** 绑定的宿主上下文(apply 时绑一次)。 */
33
+ let boundCtx = null
34
+
35
+ /** 解析结果的缓存;宿主设置变了之后由 apply 里收到的事件清掉。 */
36
+ let cached = null
37
+
38
+ /**
39
+ * 把宿主上下文绑上来,之后所有解析都走它。
40
+ * @param {object} ctx cordis 上下文
41
+ * @returns {() => void} 解绑(插件 dispose 时调用)
42
+ */
43
+ export function bindHostLimits(ctx) {
44
+ boundCtx = ctx ?? null
45
+ cached = null
46
+ return () => {
47
+ if (boundCtx === ctx) boundCtx = null
48
+ cached = null
49
+ }
50
+ }
51
+
52
+ /** 设置变了就下一次重新读(设置页改完立刻生效,不用重启)。 */
53
+ export function invalidateHostLimits() {
54
+ cached = null
55
+ }
56
+
57
+ /** 测试用:清掉绑定与缓存。 */
58
+ export function resetHostLimits() {
59
+ boundCtx = null
60
+ cached = null
61
+ }
62
+
63
+ /**
64
+ * 把 schematic 的 ref / 函数 / 字符串数字之类的值收成一个正数。
65
+ * 读不出来给 undefined(由调用方决定降级),绝不猜。
66
+ * @param {unknown} value
67
+ * @returns {number|undefined}
68
+ */
69
+ export function positiveNumberOf(value) {
70
+ let raw = value
71
+ try {
72
+ if (typeof raw === 'function') raw = raw()
73
+ else if (raw !== null && typeof raw === 'object' && typeof raw.get === 'function') raw = raw.get()
74
+ } catch {
75
+ return undefined
76
+ }
77
+ if (typeof raw === 'string') {
78
+ const text = raw.trim()
79
+ if (text === '') return undefined
80
+ raw = Number(text)
81
+ }
82
+ const n = Number(raw)
83
+ return Number.isFinite(n) && n > 0 ? n : undefined
84
+ }
85
+
86
+ /** 从一个配置对象里取三项(读不到的项为 undefined)。 */
87
+ function pickLimits(cfg) {
88
+ const out = {}
89
+ if (cfg === null || typeof cfg !== 'object') return out
90
+ for (const key of LIMIT_KEYS) {
91
+ if (!(key in cfg)) continue
92
+ const n = positiveNumberOf(cfg[key])
93
+ if (n !== undefined) out[key] = n
94
+ }
95
+ return out
96
+ }
97
+
98
+ /** 来源一:ctx.shell(真正在跑命令的执行器)的 live config。 */
99
+ function fromShell(ctx) {
100
+ let shell
101
+ try { shell = typeof ctx?.get === 'function' ? ctx.get('shell') : undefined } catch { return {} }
102
+ if (shell === null || shell === undefined) return {}
103
+ // 执行器把 schemastery 的结果挂在 this.config 上(LocalBashExecutor 的构造里就是 this.config = config)。
104
+ for (const holder of [shell.config, shell.options, shell]) {
105
+ const picked = pickLimits(holder)
106
+ if (Object.keys(picked).length > 0) return picked
107
+ }
108
+ return {}
109
+ }
110
+
111
+ /** 来源二:ctx.settings.describe() 里终端那一行。 */
112
+ function fromSettings(ctx) {
113
+ let rows
114
+ try {
115
+ const settings = typeof ctx?.get === 'function' ? ctx.get('settings') : undefined
116
+ if (!settings || typeof settings.describe !== 'function') return {}
117
+ rows = settings.describe()
118
+ } catch {
119
+ return {}
120
+ }
121
+ if (!Array.isArray(rows)) return {}
122
+ for (const ns of SETTINGS_NS) {
123
+ const row = rows.find((r) => r && r.ns === ns && r.value && typeof r.value === 'object')
124
+ if (!row) continue
125
+ const picked = pickLimits(row.value)
126
+ if (Object.keys(picked).length > 0) return picked
127
+ }
128
+ return {}
129
+ }
130
+
131
+ /**
132
+ * 读当前生效的三项。
133
+ *
134
+ * @param {{ctx?:object, force?:boolean}} [p]
135
+ * @returns {{timeoutMs:number, maxTimeoutMs:number, maxOutputBytes:number, followed:string[], missed:string[], source:string, note:string}}
136
+ */
137
+ export function readHostLimits({ ctx = null, force = false } = {}) {
138
+ if (!force && cached !== null && ctx === null) return cached
139
+ const target = ctx ?? boundCtx
140
+
141
+ const shell = fromShell(target)
142
+ const settings = Object.keys(shell).length === LIMIT_KEYS.length ? {} : fromSettings(target)
143
+ const followed = []
144
+ const missed = []
145
+ const sources = new Set()
146
+ const out = { ...DSH_DEFAULTS }
147
+
148
+ for (const key of LIMIT_KEYS) {
149
+ if (shell[key] !== undefined) {
150
+ out[key] = shell[key]
151
+ followed.push(key)
152
+ sources.add('ctx.shell')
153
+ continue
154
+ }
155
+ if (settings[key] !== undefined) {
156
+ out[key] = settings[key]
157
+ followed.push(key)
158
+ sources.add('ctx.settings')
159
+ continue
160
+ }
161
+ missed.push(key)
162
+ }
163
+
164
+ const source = sources.size === 0 ? 'dsh-defaults' : [...sources].join('+')
165
+ const note = missed.length === 0
166
+ ? '跟随宿主终端设置(' + source + ')'
167
+ : (sources.size === 0
168
+ ? '读不到宿主终端设置(没有 ctx.shell.config,也没有 settings.describe().' + SETTINGS_NS[0] + '),这一轮按 DSH 默认值走'
169
+ : '部分跟随宿主终端设置(' + source + ');未读到:' + missed.join('、') + ',这几项按 DSH 默认值走')
170
+
171
+ const result = {
172
+ timeoutMs: out.timeoutMs,
173
+ maxTimeoutMs: out.maxTimeoutMs,
174
+ maxOutputBytes: out.maxOutputBytes,
175
+ followed,
176
+ missed,
177
+ source,
178
+ note
179
+ }
180
+ // 只有三项全都读到时才缓存:读不全就下一次重读,
181
+ // 免得某个服务晚一步起来就把「降级值」永久钉住。
182
+ if (ctx === null && missed.length === 0) cached = result
183
+ return result
184
+ }
185
+
186
+ /** 一行的说明,给日志与 dryRun 回报用。 */
187
+ export function describeHostLimits(limits = readHostLimits()) {
188
+ return limits.note + ':超时默认 ' + limits.timeoutMs + 'ms,上限 ' + limits.maxTimeoutMs +
189
+ 'ms,单流输出 ' + limits.maxOutputBytes + ' 字节'
190
+ }
191
+
192
+ /**
193
+ * 把一次请求的超时收成宿主允许的值。
194
+ *
195
+ * 优先级(0.4.10 定的,不动):单条 → 顶层 → 清单 → 默认。
196
+ * 收口(0.4.11 改的):只夹上界(宿主 maxTimeoutMs)与 1ms 下界。
197
+ * 以前的下界 1000ms 也是死数,一并去掉。
198
+ *
199
+ * @param {unknown} value
200
+ * @param {object} [limits]
201
+ * @returns {number}
202
+ */
203
+ export function clampTimeoutToHost(value, limits = readHostLimits()) {
204
+ const n = Number(value)
205
+ if (!Number.isFinite(n) || n <= 0) return limits.timeoutMs
206
+ return Math.min(Math.max(Math.trunc(n), 1), limits.maxTimeoutMs)
207
+ }
208
+
209
+ /**
210
+ * 把输出上限收成宿主允许的值:默认值来自宿主,不再另设封顶。
211
+ * @param {unknown} value
212
+ * @param {object} [limits]
213
+ * @returns {number}
214
+ */
215
+ export function clampOutputToHost(value, limits = readHostLimits()) {
216
+ const n = Number(value)
217
+ if (!Number.isFinite(n) || n <= 0) return limits.maxOutputBytes
218
+ return Math.trunc(n)
219
+ }
package/lib/core/index.js CHANGED
@@ -21,6 +21,7 @@ import { bumpHits } from './search.js'
21
21
  import { buildReadToolDefinition, buildWriteToolDefinition, listMemories, readMemorySection, writeMemory, estimateTokens, READ_TOOL_NAME, WRITE_TOOL_NAME } from './tool.js'
22
22
  import { buildToolCreateReadDefinition, buildToolCreateWriteDefinition, buildToolCallToolDefinition, catalogText } from './schema-tools.js'
23
23
  import { ensureToolSequenceDir } from './schema.js'
24
+ import { bindHostLimits, invalidateHostLimits, readHostLimits, describeHostLimits } from './host-limits.js'
24
25
  import { installLifecycle } from '../host/lifecycle.js'
25
26
  import { registerApi } from '../host/api.js'
26
27
  import { deleteSessionPermanently, sessionDirOf } from '../host/delete.js'
@@ -194,6 +195,22 @@ export function apply(ctx, config = {}) {
194
195
  // ── 宿主能力探测(E1):缺哪块关哪块,其余照常 ──────────────
195
196
  // cordis 的 ctx.get 只看「已经就绪」的服务;apply 刚进来时宿主服务多半还没起来,
196
197
  // 所以这里先探到 zstd(进程级),其余各项在各自的 inject 回调里再探、合并。
198
+ // ── 0.4.11:超时与输出上限跟着宿主的终端设置走 ──────────────
199
+ // 这里只绑上下文,真正取值在每次跑脚本时现读(设置页一改,下一次执行就生效)。
200
+ ctx.effect(() => bindHostLimits(ctx), 'dsh-seal-scripts: 绑定宿主终端设置')
201
+ ctx.on('settings/document-updated', () => { invalidateHostLimits() })
202
+ // shell 服务起来之后读一次并写日志:跟随成功/失败都留一句,用户重启后能在日志里看见原因。
203
+ ctx.inject(['shell'], () => {
204
+ try {
205
+ const limits = readHostLimits({ force: true })
206
+ const line = describeHostLimits(limits)
207
+ if (limits.missed.length === 0) logger.info?.('终端设置:' + line)
208
+ else logger.warn?.('终端设置:' + line)
209
+ } catch (err) {
210
+ logger.warn?.('读宿主终端设置失败:' + (err?.message ?? err))
211
+ }
212
+ })
213
+
197
214
  const capabilities = createCapabilityProbe(ctx)
198
215
  // 只探 zstd:宿主服务此刻多半还没起来,探全表会把「还没看到」误报成「没有」。
199
216
  capabilities.probe(undefined, { only: ['zstd.decompress'] })