dsh-lean-router 2.2.3 → 2.2.5
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 +10 -2
- package/docs/changelog.en.md +25 -1
- package/docs/changelog.md +25 -1
- package/lib/lean/history-budget.js +295 -0
- package/lib/lean/persona-text.js +5 -1
- package/lib/toolface/executor.js +10 -3
- package/package.json +1 -1
- package/presets/base/frag-lean.patch.yml +5 -1
- package/presets/base/frag-preset.patch.yml +5 -1
- package/test/history-budget.test.mjs +208 -0
- package/test/lean-modules.test.mjs +23 -0
package/cordis.patch.yml
CHANGED
|
@@ -93,9 +93,13 @@
|
|
|
93
93
|
|
|
94
94
|
5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file
|
|
95
95
|
(no cat/head/tail/sed -n/find/ls -R). Piping a command's own output through head is fine.
|
|
96
|
-
6. Output budget.
|
|
96
|
+
6. Output budget. Pipe or redirect long output
|
|
97
97
|
(| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
|
|
98
98
|
Never print a dump you could grep.
|
|
99
|
+
PARALLEL CALLS (tool calls sent together run concurrently)
|
|
100
|
+
read-only read/grep/glob/read_image: independent calls in ONE message overlap truly.
|
|
101
|
+
pwsh/edit/write run serially, yet batched they still cost one round trip.
|
|
102
|
+
Never batch a masked tool name: it rejects the whole batch, siblings never run.
|
|
99
103
|
7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE
|
|
100
104
|
run_code program; a single call may still go through a one-line program so its noise stays out
|
|
101
105
|
of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on
|
|
@@ -616,9 +620,13 @@
|
|
|
616
620
|
|
|
617
621
|
5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file
|
|
618
622
|
(no cat/head/tail/sed -n/find/ls -R). Piping a command's own output through head is fine.
|
|
619
|
-
6. Output budget.
|
|
623
|
+
6. Output budget. Pipe or redirect long output
|
|
620
624
|
(| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
|
|
621
625
|
Never print a dump you could grep.
|
|
626
|
+
PARALLEL CALLS (tool calls sent together run concurrently)
|
|
627
|
+
read-only read/grep/glob/read_image: independent calls in ONE message overlap truly.
|
|
628
|
+
pwsh/edit/write run serially, yet batched they still cost one round trip.
|
|
629
|
+
Never batch a masked tool name: it rejects the whole batch, siblings never run.
|
|
622
630
|
7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE
|
|
623
631
|
run_code program; a single call may still go through a one-line program so its noise stays out
|
|
624
632
|
of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on
|
package/docs/changelog.en.md
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
> English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.2.
|
|
3
|
+
> English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.2.5).
|
|
4
|
+
|
|
5
|
+
## 2.2.5 (2026-11-29)
|
|
6
|
+
|
|
7
|
+
### Changed
|
|
8
|
+
|
|
9
|
+
- **Concrete parallel-call guidance**: the generic "Batch independent calls into one step" line in persona rule 6 proved ineffective in practice — across 22165 assistant messages in the corpus, 91.65% carried a single tool call and only 4.68% carried two or more (10.88% under the lean-router preset). It is replaced by a 306-character block: independent `read`/`grep`/`glob`/`read_image` calls in one message really do overlap; `pwsh`/`edit`/`write` are serialized within a batch but still cost only one round trip; and a masked tool name must never be batched, because it rejects the whole batch and no sibling call runs.
|
|
10
|
+
- **No façade tool added**: tool calls are already a first-class batch primitive in the host (array input, default concurrency cap 10, results written back in model order) and nothing in this repo restricts parallelism, so this release changes guidance text only.
|
|
11
|
+
- persona suffix grows from 3862 to 4130 characters (+268), still inside the 4200-character ceiling.
|
|
12
|
+
|
|
13
|
+
### Tests
|
|
14
|
+
|
|
15
|
+
- 12 new assertions (four read-only tool names, three write-oriented names, masked-name whole-batch rejection, block ≤320 characters, suffix ≤4200); the full suite is 240 tests, 239 passing, 0 failing, 1 skipped.
|
|
16
|
+
|
|
17
|
+
## 2.2.4 (2026-11-29)
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
|
|
21
|
+
- **History size budget**: tool results now get a 12000-character ceiling before they enter the conversation history — anything larger keeps the first 60% and last 40%, with the middle replaced by a single marker that reports how many characters were elided and tells the model to re-read via offset/limit or a narrower query. Whole lines in the dropped middle that match error/failure/exit-code/conclusion patterns are carried back, at most 20 lines. Valid JSON is never truncated (stays parseable), and the result is always shorter than the input and idempotent. It runs as a second stage after the existing output compaction (`lib/toolface/executor.js`), still touching only content and never the value.
|
|
22
|
+
- **Why this target**: measured across 221 sessions and 21844 usage records on this machine — 96.6% of prompt tokens are cacheRead (131.8k per turn), fresh input is only 4.6k per turn and output 1.0k; the first-turn prompt (static base) has a median of 23.4k and history accounts for roughly 83% of each turn's prompt. This release therefore attacks history size rather than squeezing the 17% static base further.
|
|
23
|
+
|
|
24
|
+
### Tests
|
|
25
|
+
|
|
26
|
+
- New `test/history-budget.test.mjs` adds 13 cases; the full suite is 239 tests, 238 passing, 0 failing, 1 skipped, and `verify` passes.
|
|
27
|
+
- Production-shaped recheck: a 128k-character sample collapses to 12000 (-90.6%), head and tail preserved verbatim, and a second call returns the same reference.
|
|
4
28
|
|
|
5
29
|
## 2.2.3 (2026-11-29)
|
|
6
30
|
|
package/docs/changelog.md
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
# 变更记录(changelog)
|
|
2
2
|
|
|
3
|
-
> 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.2.
|
|
3
|
+
> 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.2.5)。
|
|
4
|
+
|
|
5
|
+
## 2.2.5 (2026-11-29)
|
|
6
|
+
|
|
7
|
+
### 变更
|
|
8
|
+
|
|
9
|
+
- **并行调用引导具体化**:persona 第 6 条里那句泛泛的 "Batch independent calls into one step" 实测无效——全语料 22165 条 assistant 消息中 91.65% 只携带一个工具调用,带两个及以上的仅 4.68%(lean-router 预设下 10.88%)。现改为一段 306 字符的具体引导:只读工具 `read`/`grep`/`glob`/`read_image` 的独立调用放进同一条消息可以真正重叠执行;`pwsh`/`edit`/`write` 同批虽被串行,但仍只花一次往返;不要把被遮挡的工具名混进同一批,否则整批被拒、兄弟调用都不执行。
|
|
10
|
+
- **不新增 façade 工具**:宿主侧 tool-calls 本身就是批量原语(数组入参、默认并发上限 10、结果按模型顺序写回),仓库侧没有任何代码限制并行,因此这一版只改引导文本。
|
|
11
|
+
- persona suffix 3862 → 4130 字符(+268),仍在 4200 字符上限内。
|
|
12
|
+
|
|
13
|
+
### 测试
|
|
14
|
+
|
|
15
|
+
- 新增 12 条断言(四个只读工具名、三个写向工具名、遮挡整批拒绝、并行块 ≤320 字符、suffix ≤4200);全量 240 项、239 通过、0 失败、1 skip。
|
|
16
|
+
|
|
17
|
+
## 2.2.4 (2026-11-29)
|
|
18
|
+
|
|
19
|
+
### 新增
|
|
20
|
+
|
|
21
|
+
- **历史体积预算**:工具结果进入会话历史前施加 12000 字符上限——超出时保留头 60% 与尾部 40%,中段替换为一行标记,标记含被省略字符数并提示用 offset/limit 或更窄查询回读;被丢弃中段里命中错误/失败/异常/退出码/结论特征的整行最多带回 20 行。合法 JSON 不截断(保持可解析),结果恒短于原文且幂等。它接在既有输出压缩之后串联执行(`lib/toolface/executor.js`),仍只改 content 不改 value。
|
|
22
|
+
- **选点依据**:本机 221 个会话、21844 轮 usage 实测——prompt 的 96.6% 是 cacheRead(每轮均值 131.8k),fresh input 仅 4.6k/轮、output 1.0k/轮;首轮 prompt(静态底座)中位数 23.4k,历史部分约占每轮 83%。因此这一版打在历史体积上,而不是继续压只占 17% 的静态文本。
|
|
23
|
+
|
|
24
|
+
### 测试
|
|
25
|
+
|
|
26
|
+
- 新增 `test/history-budget.test.mjs` 13 条;全量 239 项、238 通过、0 失败、1 skip,verify 全 PASS。
|
|
27
|
+
- 生产形状复测:128k 字符样本压到 12000(-90.6%),头尾逐字保留,二次调用返回同一引用。
|
|
4
28
|
|
|
5
29
|
## 2.2.3 (2026-11-29)
|
|
6
30
|
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
// dsh-lean-router · lib/lean/history-budget.js —— 机制 6:工具结果的会话历史体积预算(同步纯函数)
|
|
2
|
+
//
|
|
3
|
+
// 口径(ticket: history_budget):
|
|
4
|
+
// - 实测本机 21844 轮 usage:prompt 的 96.6% 是 cacheRead(每轮均值 131.8k),
|
|
5
|
+
// 历史部分约占每轮 prompt 的 83%,静态底座只占约 17%。也就是说,压底座
|
|
6
|
+
// 每轮只赚 17% 的零头,而历史会在之后每一轮被反复计费——压历史的边际收益
|
|
7
|
+
// 高一个数量级。
|
|
8
|
+
// - 杠杆点选在「工具结果进入会话历史之前」:一条 50k 字符的搜索结果一旦入历史,
|
|
9
|
+
// 后续每一轮都要为它付一次 50k;改成入历史前就砍到预算内,之后的每一轮都省。
|
|
10
|
+
//
|
|
11
|
+
// 与 lib/lean/output-slim.js 的分工(两者串行,不互相替代):
|
|
12
|
+
// - slim 只折叠「相邻完全相同的行」,判据极保守,对「长但每行都不同」的输出无效;
|
|
13
|
+
// - budget 负责「超长就砍中段」,保留头尾,并把中间的错误行带回来。
|
|
14
|
+
// 调用方(lib/toolface/executor.js)先 slim 再 budget:先折叠省掉廉价的部分,
|
|
15
|
+
// 再对仍然超长的结果砍中段,两步都只改 content、不改 value。
|
|
16
|
+
//
|
|
17
|
+
// 三条不可退让的红线(为什么这样设计):
|
|
18
|
+
// 1. 合法 JSON 绝不截断。工具结果里最常见的形状就是 JSON(code_run 的 content
|
|
19
|
+
// 恒为 JSON 文本),而「砍中段」几乎必然把它变成不可解析的残句。模型随后
|
|
20
|
+
// 每次 parse 都失败、被迫重读,省下的字符立刻以更多轮次还回去。既有事实
|
|
21
|
+
// GT-18「JSON 必须保持可解析」已经钉住这条约束,这里保持一致:宁可放弃
|
|
22
|
+
// 这次压缩,让这条结果超预算,也不交出一份 parse 不了的 JSON。
|
|
23
|
+
// 2. 错误行永不丢弃。错误 / 异常 / traceback / 退出码 / 失败结论是「为什么失败」
|
|
24
|
+
// 的唯一线索;把它砍掉,模型只能原样重跑同一条命令——那一轮 prompt 的代价
|
|
25
|
+
// 远高于带回这几十行。所以砍中段之前先扫一遍,最多带回 20 行、总长不超过
|
|
26
|
+
// 预算的 10%,附在 marker 后面。
|
|
27
|
+
// 3. 结果恒短于原文,且幂等。恒短保证压缩不会让历史变大;幂等保证重复 finalize
|
|
28
|
+
// (或多个包装器叠加)不会在文本里堆出第二个、第三个省略标记。幂等由两道
|
|
29
|
+
// 机制保证:结果长度已落进预算时直接早退,以及「文本里已有本模块 marker」
|
|
30
|
+
// 时的兜底早退(自定义模板同样适用)。
|
|
31
|
+
//
|
|
32
|
+
// 零依赖、同步、纯函数:不读会话、不碰宿主上下文,可脱离宿主单测。
|
|
33
|
+
// 注意:本模块只产出「模型可见文本」,值的处理在其调用方(lib/toolface/executor.js)。
|
|
34
|
+
|
|
35
|
+
/** 默认体积预算(字符数,按 UTF-16 code unit 计,与 String#length 同口径)。 */
|
|
36
|
+
export const HISTORY_BUDGET_CHARS = 12000;
|
|
37
|
+
|
|
38
|
+
/** 头部保留比例:0.6。 */
|
|
39
|
+
export const HEAD_RATIO = 0.6;
|
|
40
|
+
|
|
41
|
+
/** 尾部保留比例:0.4。 */
|
|
42
|
+
export const TAIL_RATIO = 0.4;
|
|
43
|
+
|
|
44
|
+
/** 尾部至少保留的字符数(预算极小时按比例退让,见 resolveTailFloor)。 */
|
|
45
|
+
export const TAIL_MIN_CHARS = 400;
|
|
46
|
+
|
|
47
|
+
/** 带回的错误行条数上限。 */
|
|
48
|
+
export const ERROR_LINE_LIMIT = 20;
|
|
49
|
+
|
|
50
|
+
/** 带回的错误行总长度上限(占预算的比例)。 */
|
|
51
|
+
export const ERROR_BUDGET_RATIO = 0.1;
|
|
52
|
+
|
|
53
|
+
/** 省略标记里的占位符:渲染时替换成被省略的字符数。 */
|
|
54
|
+
export const ELIDED_PLACEHOLDER = '{elided}';
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 默认省略标记。必须同时给出「被省略了多少字符」与「怎么拿回来」:
|
|
58
|
+
* 前者让模型知道是否值得重读,后者让它知道恢复手段是 offset/limit 或更窄的查询,
|
|
59
|
+
* 否则它只会把同一条命令原样再跑一次。
|
|
60
|
+
*/
|
|
61
|
+
export const DEFAULT_MARKER_TEMPLATE = '[... {elided} chars elided by lean history budget; '
|
|
62
|
+
+ 're-read the omitted range (offset/limit) or run a narrower query ...]';
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 「这一行不能随便丢」的判据:错误、异常、traceback、失败、退出码、以及结论行。
|
|
66
|
+
* 与 output-slim.js 的保护行判据同源(那边用于「不折叠」,这边用于「中段带回」),
|
|
67
|
+
* 但这里不复制文件路径判据:路径行在长输出里太多,会吃光 10% 的错误行额度。
|
|
68
|
+
*/
|
|
69
|
+
const ERROR_LINE_PATTERNS = [
|
|
70
|
+
// 英文:错误 / 异常 / 堆栈 / 失败
|
|
71
|
+
/\b(?:error|errors|exception|exceptions|traceback)\b/i,
|
|
72
|
+
/\bfail(?:ed|ure|ures|ing)?\b/i,
|
|
73
|
+
/\b(?:fatal|panic|crash|denied|refused|stderr)\b/i,
|
|
74
|
+
// 退出码 / 非零状态
|
|
75
|
+
/\bexit\s*(?:code|status)\b/i,
|
|
76
|
+
/\b(?:exited\s+with|non-?zero)\b/i,
|
|
77
|
+
// 中文口径
|
|
78
|
+
/(?:错误|异常|失败|退出码|无法|抛出)/,
|
|
79
|
+
// 结论行:整行以结论词开头,或直接出现结论词
|
|
80
|
+
/^\s*(?:summary|conclusion|result|verdict|totals?)\b/i,
|
|
81
|
+
/(?:结论|总结)/,
|
|
82
|
+
];
|
|
83
|
+
|
|
84
|
+
/** 预算解析:非正数 / 非数字回落到默认值。 */
|
|
85
|
+
function resolveBudget(options) {
|
|
86
|
+
const value = options?.budgetChars;
|
|
87
|
+
return Number.isFinite(value) && value > 0 ? Math.floor(value) : HISTORY_BUDGET_CHARS;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** 模板解析:非空字符串才生效,回落到默认模板。 */
|
|
91
|
+
function resolveTemplate(options) {
|
|
92
|
+
const value = options?.markerTemplate;
|
|
93
|
+
return typeof value === 'string' && value.length > 0 ? value : DEFAULT_MARKER_TEMPLATE;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 渲染省略标记:占位符替换成数字;模板没留占位符时补一段计数,保证标记永远带得出字数。 */
|
|
97
|
+
function renderMarker(template, elided) {
|
|
98
|
+
if (template.includes(ELIDED_PLACEHOLDER)) {
|
|
99
|
+
return template.split(ELIDED_PLACEHOLDER).join(String(elided));
|
|
100
|
+
}
|
|
101
|
+
return `${template} (${elided} chars elided)`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** 正则元字符转义(用于把 marker 模板变成「是否已截断」的检测式)。 */
|
|
105
|
+
function escapeRegExp(value) {
|
|
106
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 「文本里已经有本模块的 marker」的检测式。
|
|
111
|
+
* 占位符换成 `\d+`,因此同一模板在不同省略字数下生成的标记都能命中;
|
|
112
|
+
* 自定义模板(含没留占位符的)走同一套逻辑,不需要额外分支。
|
|
113
|
+
*/
|
|
114
|
+
function markerPattern(template) {
|
|
115
|
+
return new RegExp(template.split(ELIDED_PLACEHOLDER).map(escapeRegExp).join('\\d+'));
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 该行是否属于「必须带回」的错误 / 结论行。 */
|
|
119
|
+
export function isErrorLine(line) {
|
|
120
|
+
return typeof line === 'string' && ERROR_LINE_PATTERNS.some((pattern) => pattern.test(line));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* 从即将被丢弃的中段里挑回错误 / 结论行。
|
|
125
|
+
*
|
|
126
|
+
* 额度两道:行数上限 {@link ERROR_LINE_LIMIT},总长上限占预算 {@link ERROR_BUDGET_RATIO}。
|
|
127
|
+
* 单行比整个额度还长时裁到额度上限(保留最左,错误类型与首个原因通常在最左),
|
|
128
|
+
* 并立刻停止——宁可少带几行,也不能让一行撑爆额度、把结果顶回预算之上。
|
|
129
|
+
*
|
|
130
|
+
* @param segment - 即将被省略的中段原文。
|
|
131
|
+
* @param cap - 错误行总长度上限(字符数)。
|
|
132
|
+
* @returns 带回的行(不含换行符);没有命中时为空数组。
|
|
133
|
+
*/
|
|
134
|
+
function collectErrorLines(segment, cap) {
|
|
135
|
+
if (segment.length === 0 || cap <= 0) return [];
|
|
136
|
+
const lines = segment.split(/\r?\n/);
|
|
137
|
+
const kept = [];
|
|
138
|
+
let used = 0;
|
|
139
|
+
for (const line of lines) {
|
|
140
|
+
if (kept.length >= ERROR_LINE_LIMIT) break;
|
|
141
|
+
if (!isErrorLine(line)) continue;
|
|
142
|
+
// 行间换行符也计入额度,保证拼接后的错误块整体不超过 cap。
|
|
143
|
+
const separator = kept.length > 0 ? 1 : 0;
|
|
144
|
+
const room = cap - used - separator;
|
|
145
|
+
if (room <= 0) break;
|
|
146
|
+
if (line.length > room) {
|
|
147
|
+
kept.push(line.slice(0, room));
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
kept.push(line);
|
|
151
|
+
used += line.length + separator;
|
|
152
|
+
}
|
|
153
|
+
return kept;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* 尾部下限:默认 {@link TAIL_MIN_CHARS},但不超过可用额度的一半。
|
|
158
|
+
* 预算被调用方调到很小(测试 / 预检)时按比例退让,否则尾巴会把头挤成负数。
|
|
159
|
+
*/
|
|
160
|
+
function resolveTailFloor(available) {
|
|
161
|
+
return Math.min(TAIL_MIN_CHARS, Math.max(1, Math.floor(available / 2)));
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 按 0.6 / 0.4 把可用额度分成头尾两段(尾部不低于下限)。 */
|
|
165
|
+
function splitBudget(available, total) {
|
|
166
|
+
const tail = Math.min(
|
|
167
|
+
Math.max(Math.round(available * TAIL_RATIO), resolveTailFloor(available)),
|
|
168
|
+
total,
|
|
169
|
+
);
|
|
170
|
+
const head = Math.min(Math.max(available - tail, 0), Math.max(total - tail, 0));
|
|
171
|
+
return { head, tail };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* 把一段超预算文本砍成「头 + marker + 错误行 + 尾」。
|
|
176
|
+
*
|
|
177
|
+
* marker 与错误行本身也占预算,所以不能直接按 budget 分头尾:先把当前头尾下
|
|
178
|
+
* marker 与错误行的实际开销量出来,再把剩下的额度重分给头尾,迭代收敛。
|
|
179
|
+
* marker 长度只在省略字数的位数变化时变(最多两三个字符),错误行取自随头尾
|
|
180
|
+
* 收缩而只增不减的中段,因此 3 轮足够稳定。
|
|
181
|
+
*
|
|
182
|
+
* @param text - 已确认超过预算、且不是合法 JSON 的文本。
|
|
183
|
+
* @param budget - 体积预算。
|
|
184
|
+
* @param template - 省略标记模板。
|
|
185
|
+
* @returns 截断后的文本;无法真正缩短时返回 `undefined`,由调用方保留原文。
|
|
186
|
+
*/
|
|
187
|
+
function truncateMiddle(text, budget, template) {
|
|
188
|
+
const total = text.length;
|
|
189
|
+
const eol = text.includes('\r\n') ? '\r\n' : '\n';
|
|
190
|
+
const errorCap = Math.max(1, Math.floor(budget * ERROR_BUDGET_RATIO));
|
|
191
|
+
|
|
192
|
+
let { head, tail } = splitBudget(budget, total);
|
|
193
|
+
for (let pass = 0; pass < 3; pass += 1) {
|
|
194
|
+
const middle = text.slice(head, total - tail);
|
|
195
|
+
const marker = renderMarker(template, middle.length);
|
|
196
|
+
const errorLines = collectErrorLines(middle, errorCap);
|
|
197
|
+
const errorBlock = errorLines.length > 0 ? errorLines.join(eol).length + eol.length : 0;
|
|
198
|
+
// 头尾之外还有:marker、错误块、以及 join 用的换行(最多两条)。
|
|
199
|
+
const overhead = marker.length + errorBlock + eol.length * 2;
|
|
200
|
+
const next = splitBudget(Math.max(0, budget - overhead), total);
|
|
201
|
+
if (next.head === head && next.tail === tail) break;
|
|
202
|
+
head = next.head;
|
|
203
|
+
tail = next.tail;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const middleStart = head;
|
|
207
|
+
const middleEnd = total - tail;
|
|
208
|
+
if (middleEnd <= middleStart) return undefined;
|
|
209
|
+
|
|
210
|
+
// 按最终头尾重算一次,保证标记里的省略字数与真正被砍掉的中段一致。
|
|
211
|
+
const marker = renderMarker(template, middleEnd - middleStart);
|
|
212
|
+
const errorLines = collectErrorLines(text.slice(middleStart, middleEnd), errorCap);
|
|
213
|
+
const parts = [text.slice(0, middleStart), marker];
|
|
214
|
+
if (errorLines.length > 0) parts.push(errorLines.join(eol));
|
|
215
|
+
if (tail > 0) parts.push(text.slice(middleEnd));
|
|
216
|
+
return parts.join(eol);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* 判断一段文本是不是「可解析的 JSON 文档」(trim 后以 `{` / `[` 开头且 parse 成功)。
|
|
221
|
+
* 这条判据的意义:可解析的 JSON 一旦被砍中段就永久不可解析,模型后续每次读取都会
|
|
222
|
+
* 失败,所以这类文本直接放过(见文件头红线 1)。
|
|
223
|
+
*/
|
|
224
|
+
function isParsableJson(text) {
|
|
225
|
+
const trimmed = text.trim();
|
|
226
|
+
if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return false;
|
|
227
|
+
try {
|
|
228
|
+
JSON.parse(text);
|
|
229
|
+
return true;
|
|
230
|
+
} catch {
|
|
231
|
+
return false;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* 给一段工具输出加体积上限。
|
|
237
|
+
*
|
|
238
|
+
* - 非字符串、空串、长度未超过预算:原样返回(同一引用,便于调用方判断未改动);
|
|
239
|
+
* - 合法 JSON:原样返回,不截断(GT-18「JSON 必须保持可解析」);
|
|
240
|
+
* - 超预算的普通文本:保留头部(60%)与尾部(40%,至少 400 字符),中段换成一行
|
|
241
|
+
* marker,marker 后附上从中段里挑回的错误 / 结论行(至多 20 行、至多预算的 10%);
|
|
242
|
+
* - 任何情况下结果都严格短于原文;对已截断的结果再调用不会产生第二个 marker。
|
|
243
|
+
*
|
|
244
|
+
* 预算的下限是 marker 本身的长度:若调用方把 `budgetChars` 压到比 marker 还小,
|
|
245
|
+
* 结果会超过该预算(marker 与尾部下限不可再压),但仍然严格短于原文,且依然幂等。
|
|
246
|
+
*
|
|
247
|
+
* @param text - 待加预算的工具输出文本。
|
|
248
|
+
* @param options - `budgetChars` 覆盖预算;`markerTemplate` 覆盖省略标记(用
|
|
249
|
+
* `{elided}` 占位被省略的字符数,缺占位符时会自动补一段计数)。
|
|
250
|
+
* @returns 加预算后的文本;不需要或无法压缩时返回原值。
|
|
251
|
+
*/
|
|
252
|
+
export function budgetToolOutput(text, options) {
|
|
253
|
+
if (typeof text !== 'string' || text.length === 0) return text;
|
|
254
|
+
const budget = resolveBudget(options);
|
|
255
|
+
if (text.length <= budget) return text;
|
|
256
|
+
|
|
257
|
+
// 幂等兜底:已带本模块 marker 的文本不再二次截断。
|
|
258
|
+
// 主机制是「结果长度落进预算 → 上面那行早退」,这条只在自定义模板把预算压到
|
|
259
|
+
// 极小、或外部拼接的文本里已含 marker 时起保险作用。
|
|
260
|
+
const template = resolveTemplate(options);
|
|
261
|
+
if (markerPattern(template).test(text)) return text;
|
|
262
|
+
|
|
263
|
+
// JSON 不截断:宁可超预算,也不交出 parse 不了的 JSON。
|
|
264
|
+
if (isParsableJson(text)) return text;
|
|
265
|
+
|
|
266
|
+
const budgeted = truncateMiddle(text, budget, template);
|
|
267
|
+
// 恒短:没有真正变短(极端小预算、中段太短等)就保留原文。
|
|
268
|
+
if (budgeted === undefined || budgeted.length >= text.length) return text;
|
|
269
|
+
return budgeted;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* 给一条 content 数组里的文本块加体积预算。
|
|
274
|
+
*
|
|
275
|
+
* 只改 `type === 'text'` 且 `text` 是字符串的块,块上的其他字段原样保留;
|
|
276
|
+
* 非 text 块(图片等)与整段无变化时返回**原数组引用**,让调用方可以据此判断
|
|
277
|
+
* 是否改动(与 output-slim.js 的 slimContentBlocks 同一语义)。
|
|
278
|
+
*
|
|
279
|
+
* @param blocks - 工具结果的内容块;非数组原样返回。
|
|
280
|
+
* @param options - 透传给 {@link budgetToolOutput}。
|
|
281
|
+
* @returns 加预算后的数组,或未发生变化时的原数组。
|
|
282
|
+
*/
|
|
283
|
+
export function budgetContentBlocks(blocks, options) {
|
|
284
|
+
if (!Array.isArray(blocks)) return blocks;
|
|
285
|
+
let changed = false;
|
|
286
|
+
const next = blocks.map((block) => {
|
|
287
|
+
if (block === null || typeof block !== 'object') return block;
|
|
288
|
+
if (block.type !== 'text' || typeof block.text !== 'string') return block;
|
|
289
|
+
const budgeted = budgetToolOutput(block.text, options);
|
|
290
|
+
if (budgeted === block.text) return block;
|
|
291
|
+
changed = true;
|
|
292
|
+
return { ...block, text: budgeted };
|
|
293
|
+
});
|
|
294
|
+
return changed ? next : blocks;
|
|
295
|
+
}
|
package/lib/lean/persona-text.js
CHANGED
|
@@ -56,9 +56,13 @@ export const LEAN_PERSONA_SUFFIX = [
|
|
|
56
56
|
'',
|
|
57
57
|
'5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file',
|
|
58
58
|
' (no cat/head/tail/sed -n/find/ls -R). Piping a command\'s own output through head is fine.',
|
|
59
|
-
'6. Output budget.
|
|
59
|
+
'6. Output budget. Pipe or redirect long output',
|
|
60
60
|
' (| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\\out.log in cmd, /tmp/out.log on POSIX).',
|
|
61
61
|
' Never print a dump you could grep.',
|
|
62
|
+
'PARALLEL CALLS (tool calls sent together run concurrently)',
|
|
63
|
+
' read-only read/grep/glob/read_image: independent calls in ONE message overlap truly.',
|
|
64
|
+
' pwsh/edit/write run serially, yet batched they still cost one round trip.',
|
|
65
|
+
' Never batch a masked tool name: it rejects the whole batch, siblings never run.',
|
|
62
66
|
'7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE',
|
|
63
67
|
' run_code program; a single call may still go through a one-line program so its noise stays out',
|
|
64
68
|
' of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on',
|
package/lib/toolface/executor.js
CHANGED
|
@@ -42,6 +42,7 @@
|
|
|
42
42
|
|
|
43
43
|
import { isMaskedName } from './rules.js';
|
|
44
44
|
import { slimContentBlocks } from '../lean/output-slim.js';
|
|
45
|
+
import { budgetContentBlocks } from '../lean/history-budget.js';
|
|
45
46
|
|
|
46
47
|
/**
|
|
47
48
|
* [dsh-lean-router ticket context_output_compactor] Proof that a definition's
|
|
@@ -86,12 +87,18 @@ export function wrapFinalizeContent(definition) {
|
|
|
86
87
|
if (definition[SLIM_FINALIZER_MARK] === true) return definition;
|
|
87
88
|
|
|
88
89
|
const original = typeof definition.finalizeContent === 'function' ? definition.finalizeContent : undefined;
|
|
89
|
-
const wrapped = function
|
|
90
|
+
const wrapped = function finalizeContentWithLeanOutput(exec, result) {
|
|
90
91
|
const finalized = original === undefined ? undefined : original.call(this, exec, result);
|
|
91
92
|
const current = finalized === undefined ? result?.content : finalized;
|
|
93
|
+
// [dsh-lean-router ticket history_budget] 两段串联,顺序固定:先 slim(折叠相邻
|
|
94
|
+
// 相同的行,判据最保守),再 budget(对仍然超长的结果砍中段、带回错误行)。
|
|
95
|
+
// 反过来不行:budget 砍出的中段会让相邻重复行断开,slim 之后就再无可折叠处。
|
|
96
|
+
// 两段都只改 content、不改 value;都返回「原引用表示未改动」,因此下面仍可以
|
|
97
|
+
// 用最后一次调用的引用判定整条链路是否真的改过内容(含 undefined 原样透传)。
|
|
92
98
|
const slimmed = slimContentBlocks(current);
|
|
93
|
-
|
|
94
|
-
return
|
|
99
|
+
const budgeted = budgetContentBlocks(slimmed);
|
|
100
|
+
if (budgeted === current) return finalized;
|
|
101
|
+
return budgeted;
|
|
95
102
|
};
|
|
96
103
|
|
|
97
104
|
try {
|
package/package.json
CHANGED
|
@@ -46,9 +46,13 @@
|
|
|
46
46
|
|
|
47
47
|
5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file
|
|
48
48
|
(no cat/head/tail/sed -n/find/ls -R). Piping a command's own output through head is fine.
|
|
49
|
-
6. Output budget.
|
|
49
|
+
6. Output budget. Pipe or redirect long output
|
|
50
50
|
(| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
|
|
51
51
|
Never print a dump you could grep.
|
|
52
|
+
PARALLEL CALLS (tool calls sent together run concurrently)
|
|
53
|
+
read-only read/grep/glob/read_image: independent calls in ONE message overlap truly.
|
|
54
|
+
pwsh/edit/write run serially, yet batched they still cost one round trip.
|
|
55
|
+
Never batch a masked tool name: it rejects the whole batch, siblings never run.
|
|
52
56
|
7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE
|
|
53
57
|
run_code program; a single call may still go through a one-line program so its noise stays out
|
|
54
58
|
of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on
|
|
@@ -36,9 +36,13 @@
|
|
|
36
36
|
|
|
37
37
|
5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file
|
|
38
38
|
(no cat/head/tail/sed -n/find/ls -R). Piping a command's own output through head is fine.
|
|
39
|
-
6. Output budget.
|
|
39
|
+
6. Output budget. Pipe or redirect long output
|
|
40
40
|
(| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
|
|
41
41
|
Never print a dump you could grep.
|
|
42
|
+
PARALLEL CALLS (tool calls sent together run concurrently)
|
|
43
|
+
read-only read/grep/glob/read_image: independent calls in ONE message overlap truly.
|
|
44
|
+
pwsh/edit/write run serially, yet batched they still cost one round trip.
|
|
45
|
+
Never batch a masked tool name: it rejects the whole batch, siblings never run.
|
|
42
46
|
7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE
|
|
43
47
|
run_code program; a single call may still go through a one-line program so its noise stays out
|
|
44
48
|
of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// dsh-lean-router 票 history_budget —— 会话历史体积预算纯函数单测(宿主纯 node --test 可跑)
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import assert from "node:assert/strict";
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
DEFAULT_MARKER_TEMPLATE,
|
|
7
|
+
ELIDED_PLACEHOLDER,
|
|
8
|
+
ERROR_LINE_LIMIT,
|
|
9
|
+
HISTORY_BUDGET_CHARS,
|
|
10
|
+
budgetContentBlocks,
|
|
11
|
+
budgetToolOutput,
|
|
12
|
+
} from "../lib/lean/history-budget.js";
|
|
13
|
+
|
|
14
|
+
// ===== 公共样例 =====
|
|
15
|
+
// 2000 行 × 约 63 字符 ≈ 126k 字符:远超默认预算 12000,且每行都不同,
|
|
16
|
+
// 因此 output-slim 的「相邻重复行折叠」对它无效——这正是 budget 要处理的形状。
|
|
17
|
+
|
|
18
|
+
/** 一行普通输出(刻意不含任何错误 / 路径关键字)。 */
|
|
19
|
+
function plainLine(index) {
|
|
20
|
+
return `row ${String(index).padStart(4, "0")} lorem ipsum dolor sit amet consectetur 0123456789`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 2000 行普通输出(约 126k 字符)。 */
|
|
24
|
+
const BIG = Array.from({ length: 2000 }, (_, index) => plainLine(index)).join("\n");
|
|
25
|
+
|
|
26
|
+
/** 省略标记里的被省略字符数。 */
|
|
27
|
+
function elidedCount(text) {
|
|
28
|
+
const match = /chars elided by lean history budget/.test(text)
|
|
29
|
+
? /\.\.\. (\d+) chars elided by lean history budget/.exec(text)
|
|
30
|
+
: null;
|
|
31
|
+
return match === null ? null : Number(match[1]);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
test("预算与标记的默认值:12000 字符、marker 带 {elided} 占位符", () => {
|
|
35
|
+
assert.equal(HISTORY_BUDGET_CHARS, 12000);
|
|
36
|
+
assert.ok(DEFAULT_MARKER_TEMPLATE.includes(ELIDED_PLACEHOLDER), "默认模板留了占位符");
|
|
37
|
+
assert.ok(/offset\/limit/.test(DEFAULT_MARKER_TEMPLATE), "marker 提示恢复方式");
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("预算内的短文本原样返回,且是同一引用", () => {
|
|
41
|
+
const short = "short tool output";
|
|
42
|
+
assert.equal(budgetToolOutput(short), short);
|
|
43
|
+
assert.equal(budgetToolOutput(short, { budgetChars: 12 }), short, "恰好等于预算也不截断");
|
|
44
|
+
// 恰好等于默认预算也原样返回。
|
|
45
|
+
const exact = "x".repeat(HISTORY_BUDGET_CHARS);
|
|
46
|
+
assert.equal(budgetToolOutput(exact), exact);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("超预算被截断:结果更短、不超过预算、带 marker 与被省略字符数", () => {
|
|
50
|
+
const budgeted = budgetToolOutput(BIG);
|
|
51
|
+
assert.ok(BIG.length > HISTORY_BUDGET_CHARS, "样例确实超预算");
|
|
52
|
+
assert.ok(budgeted.length < BIG.length, "结果严格短于原文");
|
|
53
|
+
assert.ok(budgeted.length <= HISTORY_BUDGET_CHARS, "结果落进预算");
|
|
54
|
+
|
|
55
|
+
const elided = elidedCount(budgeted);
|
|
56
|
+
assert.ok(elided !== null, "marker 存在");
|
|
57
|
+
assert.ok(elided > 0 && elided < BIG.length, "省略字符数是正数且小于总长");
|
|
58
|
+
assert.ok(elided >= BIG.length - HISTORY_BUDGET_CHARS, "省略的字符数覆盖了超出预算的部分");
|
|
59
|
+
assert.ok(budgeted.includes("re-read the omitted range (offset/limit)"), "marker 提示恢复方式");
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("头部与尾部内容原样保留,被省略的只有中段", () => {
|
|
63
|
+
const budgeted = budgetToolOutput(BIG);
|
|
64
|
+
assert.ok(budgeted.startsWith(plainLine(0)), "第一行保留");
|
|
65
|
+
assert.ok(budgeted.startsWith(BIG.slice(0, 1000)), "头部前 1000 字符原样保留");
|
|
66
|
+
assert.ok(budgeted.endsWith(BIG.slice(-400)), "尾部最后 400 字符原样保留");
|
|
67
|
+
assert.ok(budgeted.endsWith(plainLine(1999)), "最后一行保留");
|
|
68
|
+
// 中段确实被砍掉:样例里段中某一行不应出现。
|
|
69
|
+
assert.ok(!budgeted.includes(plainLine(1000)), "中段行被省略");
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test("中段里的错误行被带回,非错误行被丢弃", () => {
|
|
73
|
+
const head = Array.from({ length: 200 }, (_, index) => `head line ${index} plain without keywords`);
|
|
74
|
+
const middle = [
|
|
75
|
+
"ERROR: connection refused at hop 7 [boom-token-42]",
|
|
76
|
+
"Traceback (most recent call last): KeyError boom-token-43",
|
|
77
|
+
"filler middle line that must disappear [vanish-token-99]",
|
|
78
|
+
...Array.from({ length: 200 }, (_, index) => `middle filler line ${index} plain without keywords`),
|
|
79
|
+
];
|
|
80
|
+
const tail = "TAILMARK last line must survive intact";
|
|
81
|
+
const text = [...head, ...middle, tail].join("\n");
|
|
82
|
+
|
|
83
|
+
assert.ok(text.length > HISTORY_BUDGET_CHARS, "样例确实超预算");
|
|
84
|
+
const budgeted = budgetToolOutput(text);
|
|
85
|
+
assert.ok(budgeted.length <= HISTORY_BUDGET_CHARS);
|
|
86
|
+
assert.ok(budgeted.includes("boom-token-42"), "英文错误行被带回");
|
|
87
|
+
assert.ok(budgeted.includes("boom-token-43"), "traceback 行被带回");
|
|
88
|
+
assert.ok(!budgeted.includes("vanish-token-99"), "中间的非错误行被丢弃");
|
|
89
|
+
assert.ok(budgeted.includes(tail), "尾部完整保留");
|
|
90
|
+
// 错误行必须出现在 marker 之后(属于「附在标记后」的补充信息)。
|
|
91
|
+
assert.ok(budgeted.indexOf("boom-token-42") > budgeted.indexOf("chars elided"), "带回的错误行在 marker 之后");
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test("错误行带回有条数上限:最多 20 行", () => {
|
|
95
|
+
// 样例要足够大:错误行必须全部落在被丢弃的中段,才能测到「带回」的条数上限。
|
|
96
|
+
// 若文本只比预算略长,部分错误行会落在保留下来的尾部——那是「保留」不是「带回」。
|
|
97
|
+
const head = Array.from({ length: 400 }, (_, index) => `head line ${index} plain without keywords`);
|
|
98
|
+
const errors = Array.from({ length: 30 }, (_, index) => `ERROR: sampled failure number ${index}`);
|
|
99
|
+
const text = [...head, ...errors, ...Array.from({ length: 400 }, (_, index) => `tail filler ${index} plain`)].join("\n");
|
|
100
|
+
|
|
101
|
+
const budgeted = budgetToolOutput(text);
|
|
102
|
+
const kept = budgeted.match(/ERROR: sampled failure number \d+/g) ?? [];
|
|
103
|
+
assert.ok(kept.length > 0, "至少带回了错误行");
|
|
104
|
+
assert.ok(kept.length <= ERROR_LINE_LIMIT, "带回错误行不超过上限,实际 " + kept.length);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test("超预算的合法 JSON 原样返回,不截断(GT-18 可解析)", () => {
|
|
108
|
+
const payload = {
|
|
109
|
+
rows: Array.from({ length: 600 }, (_, index) => ({ id: index, text: plainLine(index) })),
|
|
110
|
+
};
|
|
111
|
+
const json = JSON.stringify(payload);
|
|
112
|
+
assert.ok(json.length > HISTORY_BUDGET_CHARS, "样例确实超预算");
|
|
113
|
+
assert.equal(budgetToolOutput(json), json, "同一引用原样返回");
|
|
114
|
+
assert.doesNotThrow(() => JSON.parse(budgetToolOutput(json)), "仍然可解析");
|
|
115
|
+
|
|
116
|
+
const arrayJson = JSON.stringify(Array.from({ length: 600 }, (_, index) => plainLine(index)));
|
|
117
|
+
assert.ok(arrayJson.length > HISTORY_BUDGET_CHARS);
|
|
118
|
+
assert.equal(budgetToolOutput(arrayJson), arrayJson, "JSON 数组同样不截断");
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test("幂等:对已截断结果再调用不再变化、也不再新增 marker", () => {
|
|
122
|
+
const once = budgetToolOutput(BIG);
|
|
123
|
+
const twice = budgetToolOutput(once);
|
|
124
|
+
assert.equal(twice, once, "第二次调用返回同一引用");
|
|
125
|
+
assert.equal(twice, budgetToolOutput(twice), "第三次同样稳定");
|
|
126
|
+
assert.equal((once.match(/chars elided by lean history budget/g) ?? []).length, 1, "只有一个 marker");
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test("非字符串与空串原样返回", () => {
|
|
130
|
+
assert.equal(budgetToolOutput(undefined), undefined);
|
|
131
|
+
assert.equal(budgetToolOutput(null), null);
|
|
132
|
+
assert.equal(budgetToolOutput(42), 42);
|
|
133
|
+
assert.equal(budgetToolOutput(""), "");
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test("预算与标记模板可被 options 覆盖", () => {
|
|
137
|
+
const short = "y".repeat(300) + "TAIL-MARKER";
|
|
138
|
+
const custom = "z".repeat(300) + "TAIL-MARKER";
|
|
139
|
+
const budgeted = budgetToolOutput(custom, { budgetChars: 100, markerTemplate: "<< {elided} chars elided >>" });
|
|
140
|
+
assert.ok(budgeted.length < custom.length);
|
|
141
|
+
assert.ok(budgeted.includes("chars elided >>"), "自定义模板生效");
|
|
142
|
+
assert.ok(!budgeted.includes("lean history budget"), "默认文案不再出现");
|
|
143
|
+
assert.ok(budgeted.endsWith("TAIL-MARKER"), "尾部仍保留");
|
|
144
|
+
// 没留占位符的模板:自动补一段计数,保证 marker 永远带得出字数。
|
|
145
|
+
const noPlaceholder = budgetToolOutput(custom, { budgetChars: 100, markerTemplate: "<elided>" });
|
|
146
|
+
assert.ok(/<elided> \(\d+ chars elided\)/.test(noPlaceholder), "缺占位符时补计数");
|
|
147
|
+
// 未超预算的短文本在自定义预算下同样原样返回。
|
|
148
|
+
assert.equal(budgetToolOutput(short, { budgetChars: 10_000 }), short);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
// ===== budgetContentBlocks =====
|
|
152
|
+
|
|
153
|
+
test("budgetContentBlocks 对非数组原样返回", () => {
|
|
154
|
+
assert.equal(budgetContentBlocks(undefined), undefined);
|
|
155
|
+
assert.equal(budgetContentBlocks(null), null);
|
|
156
|
+
assert.equal(budgetContentBlocks("text"), "text");
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
test("budgetContentBlocks 只改 text 块;非 text 块与无变化时返回原引用", () => {
|
|
160
|
+
const untouched = [{ type: "image", source: { data: "x" } }, { type: "text", text: "short" }];
|
|
161
|
+
assert.equal(budgetContentBlocks(untouched), untouched, "无变化返回原数组引用");
|
|
162
|
+
|
|
163
|
+
const blocks = [
|
|
164
|
+
{ type: "text", text: BIG, name: "pwsh" },
|
|
165
|
+
{ type: "text", text: "tail" },
|
|
166
|
+
{ type: "image", source: { data: "zzz" } },
|
|
167
|
+
];
|
|
168
|
+
const budgeted = budgetContentBlocks(blocks);
|
|
169
|
+
assert.notEqual(budgeted, blocks, "有变化时返回新数组");
|
|
170
|
+
assert.ok(budgeted[0].text.length < blocks[0].text.length);
|
|
171
|
+
assert.equal(budgeted[0].name, "pwsh", "同一 block 的其他字段保留");
|
|
172
|
+
assert.equal(budgeted[1], blocks[1], "未变化的块保持原引用");
|
|
173
|
+
assert.equal(budgeted[2], blocks[2], "非 text 块保持原引用");
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
// ===== 与 executor 的串联(先 slim 再 budget,只改 content 不改 value)=====
|
|
177
|
+
|
|
178
|
+
test("executor 串联:slim 之后仍超长的结果继续走 budget,value 保持原引用", async () => {
|
|
179
|
+
const { SLIM_FINALIZER_MARK, wrapFinalizeContent } = await import("../lib/toolface/executor.js");
|
|
180
|
+
|
|
181
|
+
// 每行都不同的超长文本:slim 折不动,只能靠 budget 压。
|
|
182
|
+
const value = { settled: true };
|
|
183
|
+
const definition = {
|
|
184
|
+
finalizeContent() {
|
|
185
|
+
return [{ type: "text", text: BIG }];
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
const wrapped = wrapFinalizeContent(definition);
|
|
189
|
+
assert.equal(wrapped, definition, "就地包装,返回同一定义");
|
|
190
|
+
const first = definition.finalizeContent({ callId: "c1" }, { value, content: [] });
|
|
191
|
+
assert.ok(first[0].text.includes("chars elided by lean history budget"), "budget 那一步接上了");
|
|
192
|
+
assert.ok(first[0].text.length < BIG.length, "结果确实变短");
|
|
193
|
+
assert.equal(definition[SLIM_FINALIZER_MARK], true, "保留既有的幂等标记");
|
|
194
|
+
|
|
195
|
+
// 重复包装不叠加(否则标记会嵌套、内容被压两遍)。
|
|
196
|
+
const fnOnce = definition.finalizeContent;
|
|
197
|
+
wrapFinalizeContent(definition);
|
|
198
|
+
assert.equal(definition.finalizeContent, fnOnce, "第二次包装是 no-op");
|
|
199
|
+
|
|
200
|
+
// 没有自身 finalizeContent 且 result.content 未变化时,仍原样返回 undefined。
|
|
201
|
+
const plain = { finalizeContent: undefined };
|
|
202
|
+
wrapFinalizeContent(plain);
|
|
203
|
+
assert.equal(plain.finalizeContent({ callId: "c2" }, { value }), undefined, "无变化时透传 undefined");
|
|
204
|
+
|
|
205
|
+
// frozen 定义:包装失败也不能让定义坏掉。
|
|
206
|
+
const frozen = Object.freeze({ name: "frozen" });
|
|
207
|
+
assert.equal(wrapFinalizeContent(frozen), frozen, "frozen 定义原样返回");
|
|
208
|
+
});
|
|
@@ -50,6 +50,29 @@ test('persona-text.js 独立加载:lean 13 条 + 2 软门 + 自检题钩子 +
|
|
|
50
50
|
assert.equal(m.PERSONA_PREFIX, 'You are a coding agent powered by the {{model}} model.');
|
|
51
51
|
});
|
|
52
52
|
|
|
53
|
+
test('persona 并行调用引导:只读并发 + 写向同批省往返 + 遮挡整批拒绝(块 <=320,suffix <=4200)', async () => {
|
|
54
|
+
const m = await mod('persona-text.js');
|
|
55
|
+
const s = m.LEAN_PERSONA_SUFFIX;
|
|
56
|
+
// 事实 1:只读工具可真正重叠执行(tool-concurrency.js 给 glob/grep 打了 isConcurrencySafe)
|
|
57
|
+
for (const t of ['read', 'grep', 'glob', 'read_image']) {
|
|
58
|
+
assert.ok(s.includes(t), '并行引导缺只读工具名:' + t);
|
|
59
|
+
}
|
|
60
|
+
// 事实 2:写向/独占工具同批仍只算一次往返
|
|
61
|
+
for (const t of ['pwsh', 'edit', 'write']) {
|
|
62
|
+
assert.ok(s.includes(t), '并行引导缺写向工具名:' + t);
|
|
63
|
+
}
|
|
64
|
+
// 事实 3:混入被遮挡(masked)名字会让整批被拒、兄弟调用不执行
|
|
65
|
+
assert.ok(s.includes('masked'), '需提醒不要在同批混入被遮挡(masked)工具名');
|
|
66
|
+
// 体积上界:引导块本身极度精简,且 suffix 总长受控
|
|
67
|
+
const start = s.indexOf('PARALLEL CALLS');
|
|
68
|
+
assert.ok(start >= 0, '需有并行调用引导块');
|
|
69
|
+
const end = s.indexOf('7. Programmatic tool mode');
|
|
70
|
+
assert.ok(end > start, '并行引导块须位于规则 6 与规则 7 之间');
|
|
71
|
+
const block = s.slice(start, end).replace(/\n+$/, '');
|
|
72
|
+
assert.ok(block.length <= 320, '并行引导块须 <=320 字符,实为 ' + block.length);
|
|
73
|
+
assert.ok(s.length <= 4200, 'persona suffix 总长须 <=4200,实为 ' + s.length);
|
|
74
|
+
});
|
|
75
|
+
|
|
53
76
|
test('plan-mode.js 独立加载:v1 政策段原文要点', async () => {
|
|
54
77
|
const m = await mod('plan-mode.js');
|
|
55
78
|
for (const needle of ['You are in plan mode.', 'exit_plan_mode', 'Do not use todo_write to track this planning phase', 'Make the plan decision-complete']) {
|