dsh-lean-router 2.1.0 → 2.2.0

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/cordis.patch.yml CHANGED
@@ -78,40 +78,37 @@
78
78
  LEAN OPERATING RULES (hard constraints; they override habit and tool default wording):
79
79
 
80
80
  BUDGET FIRST
81
- 1. Turn budget, not step budget. Target <=20 turns; turns are the measured cost (folding many calls
82
- into one turn is cheap, thrashing across turns is expensive). If a task passes 3x the expected
83
- turns (~60), stop and re-plan instead of repeating the same loop.
84
- 2. Deliberate briefly. Do not enumerate an exhaustive design before acting: one short
85
- deliberation, then run one cheap probe/command to learn the facts. Acting beats more planning.
81
+ 1. Turn budget, not step budget. Target <=20 turns; folding calls into one turn is cheap, thrashing
82
+ across turns is not. Past 3x the expected turns (~60), stop and re-plan instead of looping.
83
+ Re-check roughly every 10 turns that this is still the shortest path; if it is not, re-plan.
84
+ 2. Deliberate briefly. One short deliberation, then one cheap probe/command to learn the facts;
85
+ do not enumerate an exhaustive design before acting.
86
86
  3. Input/answer-type tasks (submit a file or an answer): produce the SMALLEST artifact that
87
87
  satisfies the stated constraints first; refine only while you are under the turn budget.
88
- 4. Gate before delivery, not after. If the task states hidden tests, a judge, or hard limits
89
- (time/memory/output), run ONE consolidated acceptance pass over every stated criterion at once (all
90
- samples, edge cases, largest legal scale) and quote the measured numbers; measure hard limits with
91
- the command the judge would use (/usr/bin/time -v, ulimit -v, ...), and treat over-limit as a failure
92
- even when the answer is otherwise correct. Otherwise ONE consolidated check per deliverable is enough:
93
- do not verify claim by claim, do not re-run a check that already passed, and name what you did not
94
- verify. Once the gate passes, stop testing and deliver: do not add extra randomized or stress rounds unless the gate itself failed.
88
+ 4. Gate before delivery, not after. Run ONE consolidated acceptance pass over every stated
89
+ criterion, quote the measured numbers, and name what you did not verify. Measure hard limits
90
+ with the command the judge would use (/usr/bin/time -v, ulimit -v). Over-limit is a failure even
91
+ when the answer is otherwise correct. Do not verify claim by claim, do not re-run a check that
92
+ already passed, and once the gate passes stop testing and deliver.
95
93
 
96
94
  5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file
97
- (no cat/head/tail/sed -n/find/ls -R); piping a command's own output through head is fine.
98
- 6. Output budget. Batch independent calls into one step. Pipe or redirect long output
99
- (| head -40; redirect to "$env:TEMP/out.log" in PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
95
+ (no cat/head/tail/sed -n/find/ls -R). Piping a command's own output through head is fine.
96
+ 6. Output budget. Batch independent calls into one step; pipe or redirect long output
97
+ (| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
100
98
  Never print a dump you could grep.
101
99
  7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE
102
- run_code program; a single-call step may still go through a one-line program so its noise stays
103
- out of context. Measured: folding pays off on multi-file/repo work (up to 8x fewer turns, 2-8x
104
- less wall clock) and is neutral on single-file algorithm tasks - there spend the budget on
105
- reasoning and testing, not on batching.
106
- 8. Context discipline (biggest measured lever). Read only what is new; rebuild derived
107
- answers from files with grep/scripts instead of re-reading them into context. Keep NOTES
108
- short and factual (<=60 lines).
109
- 9. Author incrementally: create a file once (skeleton), then extend it with edit. Never
110
- re-emit an unchanged file. After two failed shell patches, switch to the editor.
100
+ run_code program; a single call may still go through a one-line program so its noise stays out
101
+ of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on
102
+ single-file algorithm tasks - there spend the budget on reasoning and testing, not batching.
103
+ 8. Context discipline (biggest measured lever). Read only what is new; rebuild derived answers
104
+ from files with grep/scripts instead of re-reading them into context. Keep NOTES short and
105
+ factual (<=60 lines).
106
+ 9. Author incrementally: create a file once (skeleton), then extend it with edit. Never re-emit an
107
+ unchanged file. After two failed shell patches, switch to the editor.
111
108
 
112
109
  SAFETY
113
- 10. Answer in the user's language. Honour scope literally (new project => do not read or
114
- copy old-project files). Use subagents only when the user asks or the harness delegates; never spawn them to look busy.
110
+ 10. Honour scope literally (a new project means do not read or copy old-project files). Use
111
+ subagents only when the user asks or the harness delegates; never spawn them to look busy.
115
112
  11. Never put secrets, tokens or private raw material into the session; reference by path.
116
113
 
117
114
  WHEN BLOCKED
@@ -121,13 +118,11 @@
121
118
  prefer fewer, larger turns; on a low-latency route more probing is affordable. Never trade
122
119
  correctness for turn count.
123
120
 
124
- SOFT GATES (clarify -> plan -> deliver; each is one pause, never a stall)
121
+ SOFT GATES (each is one pause, never a stall)
125
122
  - CLARIFY: if goal, scope, or acceptance is ambiguous in a way that changes the result, ask one consolidated question round before acting; when a cheap read/probe settles it, probe instead of asking.
126
- - PLAN: work touching more than one file or more than ~8 steps starts from a numbered plan with a check per step; single-file small changes skip this gate.
127
- - DELIVER: run ONE consolidated acceptance pass over every stated criterion, quote measured numbers, name what was not verified, then stop (rule 4 is this gate's detail).
123
+ - PLAN: work touching more than one file or more than ~8 steps starts with a numbered plan with a check per step; single-file small changes skip this gate.
128
124
 
129
125
  SELF-CHECK HOOKS (questions answered to yourself; speak up only when a check fails)
130
- - Diligence (~every 10 turns): what changed since the last check, and is this still the shortest path to done? If not, re-plan; do not repeat the loop.
131
126
  - Close-the-book: could I redo the last step with the AI closed - do I actually know this fact, command, or path, or would I have to look it up again? If look-up, fetch it from the source of truth now instead of trusting recall.
132
127
 
133
128
  # [ticket-05] 路由分类指令由票 05 拼接(本行为占位:集成时替换为票 05 的 ROUTER_PROMPT 常量)
@@ -481,6 +476,18 @@
481
476
  config:
482
477
  toolConcurrency:
483
478
  enabled: true
479
+
480
+ # ============ 新增行:live Usage 账本挂载点(加料件)============
481
+ # 默认开启:订阅 session/event,采集带 usage 的 assistant/message(lib/token-ledger/live.js)。
482
+ # 斜杠命令 token-report([session|all])读账本,输出记录条数、prompt 总量、五项分项与最近一条 turn/step/seq;
483
+ # 无记录时返回 success 并提示尚未采集。插件实现 = lib/lean/usage-ledger.js;
484
+ # 插件行 name 为包内子路径,需 package.json exports 增加 ./lean/usage-ledger(master 集成)。
485
+
486
+ - insert:
487
+ - id: lean-usage-ledger
488
+ name: 'dsh-lean-router/lean/usage-ledger'
489
+ config:
490
+ enabled: true
484
491
  # dsh-lean-router frag-toolface.patch.yml — 票 04 工具遮蔽层
485
492
  # 由 scripts/build-bundle.mjs 拼在 presets/base/lean-router.patch.yml 之后(顶层列表续项)。
486
493
  # 形态与上游 dsh-codemode 0.3.x 样本一致(cordis patch 顶层 "- <op>:" 列表;本分片为
@@ -594,40 +601,37 @@
594
601
  LEAN OPERATING RULES (hard constraints; they override habit and tool default wording):
595
602
 
596
603
  BUDGET FIRST
597
- 1. Turn budget, not step budget. Target <=20 turns; turns are the measured cost (folding many calls
598
- into one turn is cheap, thrashing across turns is expensive). If a task passes 3x the expected
599
- turns (~60), stop and re-plan instead of repeating the same loop.
600
- 2. Deliberate briefly. Do not enumerate an exhaustive design before acting: one short
601
- deliberation, then run one cheap probe/command to learn the facts. Acting beats more planning.
604
+ 1. Turn budget, not step budget. Target <=20 turns; folding calls into one turn is cheap, thrashing
605
+ across turns is not. Past 3x the expected turns (~60), stop and re-plan instead of looping.
606
+ Re-check roughly every 10 turns that this is still the shortest path; if it is not, re-plan.
607
+ 2. Deliberate briefly. One short deliberation, then one cheap probe/command to learn the facts;
608
+ do not enumerate an exhaustive design before acting.
602
609
  3. Input/answer-type tasks (submit a file or an answer): produce the SMALLEST artifact that
603
610
  satisfies the stated constraints first; refine only while you are under the turn budget.
604
- 4. Gate before delivery, not after. If the task states hidden tests, a judge, or hard limits
605
- (time/memory/output), run ONE consolidated acceptance pass over every stated criterion at once (all
606
- samples, edge cases, largest legal scale) and quote the measured numbers; measure hard limits with
607
- the command the judge would use (/usr/bin/time -v, ulimit -v, ...), and treat over-limit as a failure
608
- even when the answer is otherwise correct. Otherwise ONE consolidated check per deliverable is enough:
609
- do not verify claim by claim, do not re-run a check that already passed, and name what you did not
610
- verify. Once the gate passes, stop testing and deliver: do not add extra randomized or stress rounds unless the gate itself failed.
611
+ 4. Gate before delivery, not after. Run ONE consolidated acceptance pass over every stated
612
+ criterion, quote the measured numbers, and name what you did not verify. Measure hard limits
613
+ with the command the judge would use (/usr/bin/time -v, ulimit -v). Over-limit is a failure even
614
+ when the answer is otherwise correct. Do not verify claim by claim, do not re-run a check that
615
+ already passed, and once the gate passes stop testing and deliver.
611
616
 
612
617
  5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file
613
- (no cat/head/tail/sed -n/find/ls -R); piping a command's own output through head is fine.
614
- 6. Output budget. Batch independent calls into one step. Pipe or redirect long output
615
- (| head -40; redirect to "$env:TEMP/out.log" in PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
618
+ (no cat/head/tail/sed -n/find/ls -R). Piping a command's own output through head is fine.
619
+ 6. Output budget. Batch independent calls into one step; pipe or redirect long output
620
+ (| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
616
621
  Never print a dump you could grep.
617
622
  7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE
618
- run_code program; a single-call step may still go through a one-line program so its noise stays
619
- out of context. Measured: folding pays off on multi-file/repo work (up to 8x fewer turns, 2-8x
620
- less wall clock) and is neutral on single-file algorithm tasks - there spend the budget on
621
- reasoning and testing, not on batching.
622
- 8. Context discipline (biggest measured lever). Read only what is new; rebuild derived
623
- answers from files with grep/scripts instead of re-reading them into context. Keep NOTES
624
- short and factual (<=60 lines).
625
- 9. Author incrementally: create a file once (skeleton), then extend it with edit. Never
626
- re-emit an unchanged file. After two failed shell patches, switch to the editor.
623
+ run_code program; a single call may still go through a one-line program so its noise stays out
624
+ of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on
625
+ single-file algorithm tasks - there spend the budget on reasoning and testing, not batching.
626
+ 8. Context discipline (biggest measured lever). Read only what is new; rebuild derived answers
627
+ from files with grep/scripts instead of re-reading them into context. Keep NOTES short and
628
+ factual (<=60 lines).
629
+ 9. Author incrementally: create a file once (skeleton), then extend it with edit. Never re-emit an
630
+ unchanged file. After two failed shell patches, switch to the editor.
627
631
 
628
632
  SAFETY
629
- 10. Answer in the user's language. Honour scope literally (new project => do not read or
630
- copy old-project files). Use subagents only when the user asks or the harness delegates; never spawn them to look busy.
633
+ 10. Honour scope literally (a new project means do not read or copy old-project files). Use
634
+ subagents only when the user asks or the harness delegates; never spawn them to look busy.
631
635
  11. Never put secrets, tokens or private raw material into the session; reference by path.
632
636
 
633
637
  WHEN BLOCKED
@@ -637,13 +641,11 @@
637
641
  prefer fewer, larger turns; on a low-latency route more probing is affordable. Never trade
638
642
  correctness for turn count.
639
643
 
640
- SOFT GATES (clarify -> plan -> deliver; each is one pause, never a stall)
644
+ SOFT GATES (each is one pause, never a stall)
641
645
  - CLARIFY: if goal, scope, or acceptance is ambiguous in a way that changes the result, ask one consolidated question round before acting; when a cheap read/probe settles it, probe instead of asking.
642
- - PLAN: work touching more than one file or more than ~8 steps starts from a numbered plan with a check per step; single-file small changes skip this gate.
643
- - DELIVER: run ONE consolidated acceptance pass over every stated criterion, quote measured numbers, name what was not verified, then stop (rule 4 is this gate's detail).
646
+ - PLAN: work touching more than one file or more than ~8 steps starts with a numbered plan with a check per step; single-file small changes skip this gate.
644
647
 
645
648
  SELF-CHECK HOOKS (questions answered to yourself; speak up only when a check fails)
646
- - Diligence (~every 10 turns): what changed since the last check, and is this still the shortest path to done? If not, re-plan; do not repeat the loop.
647
649
  - Close-the-book: could I redo the last step with the AI closed - do I actually know this fact, command, or path, or would I have to look it up again? If look-up, fetch it from the source of truth now instead of trusting recall.
648
650
 
649
651
  Routing: before acting on any new task, classify it - (build) create something new end-to-end, or (fix) diagnose and repair something broken - then adopt the matching style: build -> hands-on production; fix -> inspect-and-plan.
@@ -0,0 +1,18 @@
1
+ # 发布(release)
2
+
3
+ 一条命令发布:`node scripts/release.mjs <version>`。加 `--dry-run` 只跑测试与 verify,不改版本、不发布。
4
+
5
+ 脚本只做机械步骤:校验 semver 与工作树、跑 `npm test` 与 `npm run verify`、改 `package.json`、提交、`npm publish --registry https://registry.npmjs.org`、轮询可见性(最长 5 分钟)、临时目录 `npm install` 验证版本。
6
+
7
+ **changelog 必须先人工写。** 脚本会检查 `docs/changelog.md` 与 `docs/changelog.en.md` 都已有 `## <version>` 标题,缺一个就中止——中英两份都要写,不要只改中文。
8
+
9
+ ## 本机环境陷阱
10
+
11
+ - 默认 registry 是 `registry.npmmirror.com`,那是只读镜像。`npm whoami` 会因此返回 `ENEEDAUTH`,**不代表没登录**;用 `npm whoami --registry https://registry.npmjs.org` 复核。发布一律显式带 `--registry`。
12
+ - `npm pack --dry-run` / `npm publish` 把 notice 写到 stderr,PowerShell 会把它当错误并使退出码变成 1。用 `cmd /c "npm ... 2>&1"` 或只看 stdout 判断。
13
+ - `npm publish` 返回成功后 registry 仍要约 90 秒才可见,立刻 `npm view` 会 404。不要把 404 当发布失败。
14
+ - `npm.ps1` 在本机可能因 `npmNodeDir` 为空失败,一律用 `npm.cmd`。
15
+
16
+ ## 版本号判断
17
+
18
+ 新增功能发 minor,修复与内部优化发 patch;先 `npm view <pkg> version` 确认远端当前版本,避免重发已存在的号。
@@ -0,0 +1,18 @@
1
+ # 验证与复核(verification)
2
+
3
+ ## 子代理自报的数字必须复测
4
+
5
+ 子代理报告的字符数、压缩率、测试数都要用**生产形状**的样本独立复测一次,再写进提交说明或对外结论。
6
+
7
+ 只测"契约形状"不够:真实 `code_run` 的输出是 JSON,重复日志表现为 `logs` 字符串数组里的多个相同元素,而不是单个字符串内部的多行。用字符串内重复行去测,会得到漂亮的压缩率,却对真实输出零效果。
8
+
9
+ 复测的做法:从宿主类型定义或现有实现里确认真实结构,构造同样的形状跑一遍,对比前后长度、可解析性、关键字段是否保留。
10
+
11
+ ## arch 图操作复核
12
+
13
+ `.arch/` 是架构引擎自己的 shadow Git,不要 `git add` 进去;仓库已用 `.gitignore` 忽略,克隆后它不存在,需要时重新 `arch init`。
14
+
15
+ - `activate --node X --before Y` 只加 X→Y 这一条边,上游边不会自动出现。要落在两个节点之间,同时写 `--after A --before B`。
16
+ - `activate` 之后必须 `focus --node X` 核对 `upstream_edges` 与 `downstream_edges` 都不为空,再继续。
17
+ - 已经在主干的节点没有"只改接线"的命令;绕法是 `deactivate` 再 `activate`,但 `deactivate` 会把它移进迷雾区,之后要确认状态不是 `fog`。
18
+ - `collapse` 之后用 `focus` 确认 `spec` 已更新;如果仍显示旧 spec,说明写入没生效,不要假设成功。
@@ -1,6 +1,34 @@
1
1
  # Changelog
2
2
 
3
- > English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.1.0).
3
+ > English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.2.0).
4
+
5
+ ## 2.2.0 (2026-11-29)
6
+
7
+ ### Added
8
+
9
+ - **`/token-report` ledger command**: new `lib/lean/usage-ledger.js`, mounted as the top-level preset add-on `lean-usage-ledger`. It subscribes to the host's `session/event` feed and keeps only `assistant/message` events that carry `usage`. The command reports the record count, the `prompt` total (input+cacheRead+cacheWrite), all five usage fields, and the latest record's `turn/step/seq`; with no records it says so explicitly. Every failure path only warns, and unloading releases the subscription.
10
+
11
+ ### Improved
12
+
13
+ - **Lazy parameter schemas in `search`**: `code_tools_search` no longer returns the full `parameters` and `output` schemas, but a `params` array of argument names (`noParams` when nothing is enumerable); the complete schema comes from `code_tools_describe`. A full 8-row page measured 8380 to 1924 characters (-77%).
14
+ - **Lean persona no-op audit**: removed the language requirement the host already injects, the `DELIVER` gate duplicated by rule 4, and the `Diligence` hook overlapping rule 1, then tightened wording: 4581 to 3862 characters (-15.7%). All 13 numbered rules and their criteria remain.
15
+
16
+ ### Notes
17
+
18
+ - All three changes are static or output-side; real gains need a restart to be observed inside the host, and no device verification has been done yet.
19
+ - Since `search` now returns only argument names, call `describe` before invoking an unfamiliar tool; the SDK text has been rewritten to say so.
20
+
21
+ ## 2.1.1 (2026-11-29)
22
+
23
+ ### Improved
24
+
25
+ - **Static tool surface slimmed**: the `code_run` description drops from 459 to 298 characters and the SDK explanation from 2340 to 1738, for 3346 to 2526 in total (-24.5%). Required fields, enums, property names and the conditional `timeoutMs` semantics are all locked by new structural contract assertions, cutting roughly 820 characters of per-turn resident injection.
26
+ - **Conservative tool-output compaction**: new `lib/lean/output-slim.js`, wired into `lib/toolface/executor.js` by wrapping each visible definition's `finalizeContent` in place. Compaction only engages above 2000 characters: adjacent duplicate lines collapse, and adjacent duplicate elements of a string array collapse to the first element plus one marker element. Error, exception, failure, exit-code, path and conclusion lines are never folded. JSON output stays parseable with unchanged keys and types, only the model-visible content changes, the program-visible value never does, and any pre-existing `finalizeContent` is chained rather than replaced.
27
+
28
+ ### Notes
29
+
30
+ - Both changes are static or output-side; real gains need a restart to be observed inside the host, and no device verification has been done yet.
31
+ - Compaction pays off on repetitive log output (example: 3788 to 172 characters) and is a no-op for output without repetition.
4
32
 
5
33
  ## 2.1.0 (2026-11-29)
6
34
 
package/docs/changelog.md CHANGED
@@ -1,6 +1,34 @@
1
1
  # 变更记录(changelog)
2
2
 
3
- > 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.1.0)。
3
+ > 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.2.0)。
4
+
5
+ ## 2.2.0 (2026-11-29)
6
+
7
+ ### 新增
8
+
9
+ - **`/token-report` 账本命令**:新增 `lib/lean/usage-ledger.js`,以预设顶层加料件 `lean-usage-ledger` 生效,订阅宿主的 `session/event` 并只收 `assistant/message` 且带 `usage` 的事件。命令输出记录条数、`prompt` 总量(input+cacheRead+cacheWrite)、五项分项与最近一条的 `turn/step/seq`;没有任何记录时明确说明尚未采集。所有失败路径只 warn 不抛,卸载时释放订阅。
10
+
11
+ ### 优化
12
+
13
+ - **`search` 懒取参数 schema**:`code_tools_search` 不再返回完整 `parameters` 与 `output` schema,改为返回 `params` 参数名数组(无可枚举属性时给 `noParams`);完整 schema 由 `code_tools_describe` 提供。8 行满页实测输出 8380→1924 字符(-77%)。
14
+ - **lean persona no-op 审查**:删去宿主已注入的语言要求、与规则 4 重复的 `DELIVER` 软门、与规则 1 重叠的 `Diligence` 钩子并压缩措辞,4581→3862 字符(-15.7%);13 条规则编号与全部判据保留。
15
+
16
+ ### 说明
17
+
18
+ - 三项都是静态或输出侧改动,真实收益需重启后在宿主里观察,尚未做真机验证。
19
+ - `search` 只给参数名后,调用不熟悉参数形状的工具前应先 `describe`;SDK 文本已同步改写。
20
+
21
+ ## 2.1.1 (2026-11-29)
22
+
23
+ ### 优化
24
+
25
+ - **静态工具面瘦身**:`code_run` 的 description 459→298 字符、SDK 说明 2340→1738,合计 3346→2526(-24.5%);required/enum/属性名与 `timeoutMs` 条件语义均由新增的结构契约断言锁定,每轮常驻注入因此减少约 820 字符。
26
+ - **工具输出保守压缩**:新增 `lib/lean/output-slim.js`,并在 `lib/toolface/executor.js` 的 `describe()` 里给每个可见工具就地包装 `finalizeContent`。压缩只在输出超过 2000 字符时启用:折叠相邻重复行,以及字符串数组里相邻重复元素(保留首个 + 一个 marker 元素);错误、异常、失败、退出码、路径与结论行永不折叠。JSON 输出保持可解析、键与类型不变,只改模型可见 content,不改程序内 value;原有 `finalizeContent` 会被串联而不是覆盖。
27
+
28
+ ### 说明
29
+
30
+ - 两项都是静态或输出侧的改动,真实收益需重启后在宿主里观察,尚未做真机验证。
31
+ - 输出压缩对重复日志类输出收益明显(示例 3788→172 字符),对无重复的输出不生效。
4
32
 
5
33
  ## 2.1.0 (2026-11-29)
6
34
 
@@ -0,0 +1,271 @@
1
+ // dsh-lean-router · lib/lean/output-slim.js —— 机制 5:工具输出的保守压缩(同步纯函数)
2
+ //
3
+ // 口径(ticket: context_output_compactor,GT-17「不改 JSON 结构」):
4
+ // - 只在文本超过阈值时启用,小输出一个字都不改;
5
+ // - 普通文本:只折叠「连续 >= 3 行完全相同」的块,保留一行并紧跟一行 marker;
6
+ // - 可 JSON.parse 的文本(code_run 的 content 恒为 JSON 文本):绝不按行折叠顶层。
7
+ // 改为两条保持结构的压缩:
8
+ // a) 字符串值内部做相邻重复行折叠(marker 作为字符串内容);
9
+ // b) 字符串数组折叠相邻相同元素——保留第一个,后面连续相同的 N 个(N >= 2)
10
+ // 替换为一个 marker 字符串,数组长度因此变短(预期行为)。
11
+ // 键与类型不变,再 JSON.stringify 输出;若 stringify 后不比原文短则返回原文;
12
+ // - 错误 / 异常 / 失败 / 退出码 / 文件路径 / 结论行永不折叠、永不删除(两种路径同判据);
13
+ // - 不做结构化摘要、不改值、不重排键。
14
+ //
15
+ // 与 lib/lean/pruner.js 的关系:pruner 按头 / 中 / 尾裁掉中段(宿主 pruner 的纯函数端口),
16
+ // 本模块只做「相邻重复行」的局部折叠,判据更保守,二者互不替代。
17
+ //
18
+ // 零依赖、同步、纯函数:不读会话、不碰 Cordis 上下文,可脱离宿主单测。
19
+ // 注意:本模块只产出「模型可见文本」,值的处理在其调用方(lib/toolface/executor.js)。
20
+
21
+ /** 启用压缩的最小文本长度(严格大于该值才启用,等于阈值不启用)。 */
22
+ export const SLIM_THRESHOLD_CHARS = 2000;
23
+
24
+ /** 连续相同行达到该数量才折叠;2 行重复保持原样。 */
25
+ export const COLLAPSE_MIN_LINES = 3;
26
+
27
+ /** 单次折叠的 marker 原文({collapsed} 为被折叠掉的行数,即 run 长度 - 1)。 */
28
+ export const COLLAPSE_MARKER = '[... {collapsed} identical lines collapsed]';
29
+
30
+ /** 压缩收益 marker 原文({saved} 为折叠本身节省的字符数,不含本 marker)。 */
31
+ export const SAVED_MARKER = '[... output compacted: {saved} chars saved ...]';
32
+
33
+ /**
34
+ * 受保护行的判据。任何命中一项的行都不折叠——宁可少折叠,也不把结论行吃掉。
35
+ * 覆盖:错误 / 异常 / 失败 / 退出码(含中文口径)、结论行、文件路径。
36
+ */
37
+ const PROTECTED_PATTERNS = [
38
+ // 错误 / 异常 / 失败 / 致命(含 stderr、非零退出等常见措辞)
39
+ /\b(?:error|errors|exception|exceptions|failed|failure|failures|fatal|panic|traceback|throw|throws|threw|stderr|denied|refused)\b/i,
40
+ // 退出码 / 退出状态
41
+ /\b(?:exit\s*(?:code|status))\b/i,
42
+ /\b(?:exited\s+with|non-?zero)\b/i,
43
+ // 中文口径的错误与结论
44
+ /(?:错误|异常|失败|退出码|结论|总结|原因|无法|抛出)/,
45
+ // 结论行:整行以结论词开头(大小写不敏感)
46
+ /^\s*(?:summary|conclusion|result|verdict|totals?)\b/i,
47
+ // 文件路径:盘符、UNC、POSIX 绝对路径、./ ../ 相对路径
48
+ /(?:^|[\s"'(<[=:])(?:[A-Za-z]:[\\/]|\\\\|\/|\.{1,2}\/)/,
49
+ // 文件路径:带已知扩展名的文件名
50
+ /(?:^|[\s"'(<[=:])[\w.@~+-]+\.(?:[cm]?[jt]sx?|jsonc?|py|rb|go|rs|java|kt|c|h|cc|cpp|hpp|cs|php|sh|bash|zsh|ps1|cmd|bat|md|markdown|txt|log|ya?ml|toml|ini|cfg|conf|xml|html?|css|scss|sql|db|lock|env|patch|diff)\b/i,
51
+ ];
52
+
53
+ /**
54
+ * 裸大整数 token(16 位以上):`JSON.parse` 会丢精度,遇到这类文档完全不碰,
55
+ * 宁可放弃这次压缩也不改写用户数据。
56
+ */
57
+ const BIG_INTEGER_TOKEN = /(?:^|[\s:,[{])-?\d{16,}(?=[\s,\]}]|$)/;
58
+
59
+ /** 解析阈值:非正数 / 非数字回落到默认值。 */
60
+ function resolveThreshold(options) {
61
+ const value = options?.thresholdChars;
62
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : SLIM_THRESHOLD_CHARS;
63
+ }
64
+
65
+ /** 该行是否必须原样保留。 */
66
+ export function isProtectedLine(line) {
67
+ return typeof line === 'string' && PROTECTED_PATTERNS.some((pattern) => pattern.test(line));
68
+ }
69
+
70
+ /** 折叠结果的可读 marker。 */
71
+ function collapseMarker(collapsed) {
72
+ return COLLAPSE_MARKER.replace('{collapsed}', String(collapsed));
73
+ }
74
+
75
+ /** 收益 marker。 */
76
+ function savedMarker(saved) {
77
+ return SAVED_MARKER.replace('{saved}', String(saved));
78
+ }
79
+
80
+ /**
81
+ * 按行折叠相邻重复块(不设阈值门、不加收益 marker):普通文本与 JSON 字符串值共用。
82
+ *
83
+ * @param text - 待折叠文本。
84
+ * @returns `{ eol, body, collapsedLines }`:换行风格、折叠正文、被折叠掉的总行数。
85
+ */
86
+ function foldLines(text) {
87
+ const eol = text.includes('\r\n') ? '\r\n' : '\n';
88
+ const lines = text.split(/\r?\n/);
89
+ const kept = [];
90
+ let collapsedLines = 0;
91
+
92
+ for (let index = 0; index < lines.length;) {
93
+ const line = lines[index];
94
+ let end = index + 1;
95
+ while (end < lines.length && lines[end] === line) end += 1;
96
+ const runLength = end - index;
97
+ // 受保护的行整段保留:连续相同的错误行也是每条都有信息。
98
+ if (runLength >= COLLAPSE_MIN_LINES && !isProtectedLine(line)) {
99
+ const collapsed = runLength - 1;
100
+ kept.push(line);
101
+ kept.push(collapseMarker(collapsed));
102
+ collapsedLines += collapsed;
103
+ } else {
104
+ for (let offset = index; offset < end; offset += 1) kept.push(line);
105
+ }
106
+ index = end;
107
+ }
108
+
109
+ return { eol, body: kept.join(eol), collapsedLines };
110
+ }
111
+
112
+ /**
113
+ * 折叠一段普通文本并在末尾补收益 marker;不值得改时返回原值。
114
+ * @param text - 已确认超过阈值的文本。
115
+ * @returns 折叠后的文本,或原值。
116
+ */
117
+ function slimPlainText(text) {
118
+ const folded = foldLines(text);
119
+ if (folded.collapsedLines === 0) return text;
120
+ const savedChars = text.length - folded.body.length;
121
+ // 负收益(折叠 marker 比省下的内容还长)就不动原文。
122
+ if (savedChars <= 0) return text;
123
+ return folded.body + folded.eol + savedMarker(savedChars);
124
+ }
125
+
126
+ /**
127
+ * 压缩 JSON 文档里的一个字符串值:只在字符串内部折叠相邻重复行。
128
+ * 未超过阈值的字符串(短值)不碰。
129
+ */
130
+ function slimJsonString(value, threshold) {
131
+ if (value.length <= threshold) return value;
132
+ const folded = foldLines(value);
133
+ if (folded.collapsedLines === 0) return value;
134
+ const savedChars = value.length - folded.body.length;
135
+ if (savedChars <= 0) return value;
136
+ return folded.body + folded.eol + savedMarker(savedChars);
137
+ }
138
+
139
+ /**
140
+ * 折叠字符串数组里相邻相同的元素:保留第一个,后面连续相同的 N 个(N >= 2)
141
+ * 替换成一个 marker 字符串。错误 / 路径 / 结论行元素永不折叠。
142
+ * 非字符串元素不参与折叠(类型与顺序都保持)。
143
+ *
144
+ * @param items - 已递归处理过的数组元素。
145
+ * @returns `{ items, collapsed }`:折叠后的数组与被折叠掉的元素总数。
146
+ */
147
+ function foldStringRuns(items) {
148
+ const kept = [];
149
+ let collapsed = 0;
150
+ for (let index = 0; index < items.length;) {
151
+ const item = items[index];
152
+ let end = index + 1;
153
+ if (typeof item === 'string') {
154
+ while (end < items.length && items[end] === item) end += 1;
155
+ }
156
+ const runLength = end - index;
157
+ // 保留首个,其余至少 2 个才折叠(单个 marker 才比被折叠的元素更短)。
158
+ if (typeof item === 'string' && runLength >= COLLAPSE_MIN_LINES && !isProtectedLine(item)) {
159
+ kept.push(item);
160
+ kept.push(collapseMarker(runLength - 1));
161
+ collapsed += runLength - 1;
162
+ } else {
163
+ for (let offset = index; offset < end; offset += 1) kept.push(items[offset]);
164
+ }
165
+ index = end;
166
+ }
167
+ return { items: kept, collapsed };
168
+ }
169
+
170
+ /**
171
+ * 递归压缩 JSON 值:字符串值内部折叠,字符串数组折叠相邻相同元素;键与类型不变。
172
+ * 数组长度可能变短(只在字符串数组的重复段上),这是预期行为。
173
+ * @returns `{ value, changed }`;`changed` 为 false 时 `value` 与入参结构等价。
174
+ */
175
+ function compactJsonStrings(node, threshold) {
176
+ let changed = false;
177
+ const walk = (current) => {
178
+ if (typeof current === 'string') {
179
+ const slimmed = slimJsonString(current, threshold);
180
+ if (slimmed === current) return current;
181
+ changed = true;
182
+ return slimmed;
183
+ }
184
+ if (Array.isArray(current)) {
185
+ const mapped = current.map(walk);
186
+ const folded = foldStringRuns(mapped);
187
+ if (folded.collapsed > 0) changed = true;
188
+ return folded.collapsed > 0 ? folded.items : mapped;
189
+ }
190
+ if (current !== null && typeof current === 'object') {
191
+ // Object.fromEntries 走 CreateDataProperty,`__proto__` 这类键不会被改写。
192
+ return Object.fromEntries(Object.entries(current).map(([key, child]) => [key, walk(child)]));
193
+ }
194
+ return current;
195
+ };
196
+ const value = walk(node);
197
+ return { value, changed };
198
+ }
199
+
200
+ /**
201
+ * JSON 文档路径:只压缩字符串值内部,结构不动。
202
+ *
203
+ * @param text - 已确认超过阈值的文本。
204
+ * @param threshold - 单字符串值启用折叠的长度阈值。
205
+ * @returns 压缩后的 JSON 文本;不是 JSON、无可压缩字符串、或 stringify 后不更短时返回原文。
206
+ */
207
+ function slimJsonDocument(text, threshold) {
208
+ const trimmed = text.trim();
209
+ if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return undefined;
210
+ if (BIG_INTEGER_TOKEN.test(text)) return text;
211
+ let parsed;
212
+ try {
213
+ parsed = JSON.parse(text);
214
+ } catch {
215
+ return undefined;
216
+ }
217
+ if (parsed === null || typeof parsed !== 'object') return undefined;
218
+ const { value, changed } = compactJsonStrings(parsed, threshold);
219
+ if (!changed) return text;
220
+ // 与 code_run 的 renderJson 同形(2 空格缩进),保证模型读到的排版一致。
221
+ const rendered = JSON.stringify(value, null, 2);
222
+ return rendered.length < text.length ? rendered : text;
223
+ }
224
+
225
+ /**
226
+ * 保守压缩一段模型可见文本。
227
+ *
228
+ * - 非字符串或空串:原样返回;
229
+ * - 未超过阈值:原样返回;
230
+ * - JSON 文本:递归压缩字符串值内部,并折叠字符串数组里相邻相同的元素(数组长度可变短),
231
+ * 键与类型不变;不短则原样返回;
232
+ * - 普通文本:行级折叠相邻重复块,受保护行不折叠。
233
+ *
234
+ * @param text - 待压缩文本。
235
+ * @param options - `thresholdChars` 覆盖阈值(仅供测试 / 预检)。
236
+ * @returns 压缩后的文本;任何情况下都不比原文长(JSON 路径保证),不需要压缩时返回原值。
237
+ */
238
+ export function slimToolOutput(text, options) {
239
+ if (typeof text !== 'string' || text.length === 0) return text;
240
+ const threshold = resolveThreshold(options);
241
+ if (text.length <= threshold) return text;
242
+
243
+ const json = slimJsonDocument(text, threshold);
244
+ if (json !== undefined) return json;
245
+
246
+ return slimPlainText(text);
247
+ }
248
+
249
+ /**
250
+ * 压缩一条 content 数组里的文本块。
251
+ *
252
+ * 只改 `type === 'text'` 且 `text` 是字符串的块,块上的其他字段原样保留;
253
+ * 非 text 块(图片等)与整段无变化时返回**原数组引用**,让调用方可以据此判断是否改动。
254
+ *
255
+ * @param blocks - 工具结果的内容块;非数组原样返回。
256
+ * @param options - 透传给 {@link slimToolOutput}。
257
+ * @returns 压缩后的数组,或未发生变化时的原数组。
258
+ */
259
+ export function slimContentBlocks(blocks, options) {
260
+ if (!Array.isArray(blocks)) return blocks;
261
+ let changed = false;
262
+ const next = blocks.map((block) => {
263
+ if (block === null || typeof block !== 'object') return block;
264
+ if (block.type !== 'text' || typeof block.text !== 'string') return block;
265
+ const slimmed = slimToolOutput(block.text, options);
266
+ if (slimmed === block.text) return block;
267
+ changed = true;
268
+ return { ...block, text: slimmed };
269
+ });
270
+ return changed ? next : blocks;
271
+ }