@hugesb/dsh-stream-agent 0.0.0-stage → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/CHANGELOG.md +622 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +202 -0
  4. package/README.en.md +349 -0
  5. package/README.md +300 -3
  6. package/cordis.patch.yml +77 -0
  7. package/dist/entry/action-gate.js +206 -0
  8. package/dist/entry/adapter-kit.js +192 -0
  9. package/dist/entry/context-render.js +119 -0
  10. package/dist/entry/control-bar-cli.js +289 -0
  11. package/dist/entry/control-bar.js +123 -0
  12. package/dist/entry/control-session.js +115 -0
  13. package/dist/entry/control-state.js +125 -0
  14. package/dist/entry/cordis-compat.js +95 -0
  15. package/dist/entry/eval-probe.js +112 -0
  16. package/dist/entry/intent-log.js +121 -0
  17. package/dist/entry/json-persistence.js +306 -0
  18. package/dist/entry/loop.js +4163 -0
  19. package/dist/entry/mock-provider.js +549 -0
  20. package/dist/entry/obs-broker.js +178 -0
  21. package/dist/entry/ptc-bridge.js +405 -0
  22. package/dist/entry/state-handle.js +217 -0
  23. package/dist/entry/takeover-registry.js +60 -0
  24. package/dist/kernel/control-bar.js +559 -0
  25. package/dist/kernel/final.js +62 -0
  26. package/dist/kernel/gate.js +464 -0
  27. package/dist/kernel/modes.js +253 -0
  28. package/dist/kernel/obs.js +517 -0
  29. package/dist/kernel/parser.js +1081 -0
  30. package/dist/kernel/render.js +466 -0
  31. package/dist/kernel/state.js +416 -0
  32. package/dist/version.js +9 -0
  33. package/docs/TEST-PROPOSITIONS.md +139 -0
  34. package/docs/adr-001-segment-boundary.md +61 -0
  35. package/docs/architecture.md +104 -0
  36. package/docs/desktop-ui-feasibility.md +277 -0
  37. package/docs/disabled-lines-audit.md +53 -0
  38. package/docs/limitations.md +181 -0
  39. package/docs/protocol.md +99 -0
  40. package/docs/v0.4.0-plan.md +50 -0
  41. package/eval/METRICS.md +128 -0
  42. package/eval/RESULTS.md +246 -0
  43. package/eval/tasks/fixtures/big-report.md +298 -0
  44. package/eval/tasks/fixtures/build-manifest.txt +5 -0
  45. package/eval/tasks/fixtures/deploy.yaml +4 -0
  46. package/eval/tasks/fixtures/error.log +200 -0
  47. package/eval/tasks/fixtures/features.yaml +4 -0
  48. package/eval/tasks/fixtures/pipeline.yaml +4 -0
  49. package/eval/tasks/fixtures/sales-q1.csv +61 -0
  50. package/eval/tasks/fixtures/settings.yaml +4 -0
  51. package/eval/tasks/fixtures/users-roster.json +304 -0
  52. package/eval/tasks/fixtures/users-scores.json +20 -0
  53. package/eval/tasks/gen-fixtures.cjs +80 -0
  54. package/eval/tasks/tasks.json +150 -0
  55. package/eval/tools/f6-kill-drill.cjs +176 -0
  56. package/eval/tools/f6-kill-drill.worker.cjs +131 -0
  57. package/eval/tools/gen-results.cjs +191 -0
  58. package/eval/tools/machine-test.cjs +200 -0
  59. package/eval/tools/manual-code-scenarios.md +59 -0
  60. package/eval/tools/replay-check.cjs +311 -0
  61. package/eval/tools/runner.cjs +219 -0
  62. package/eval/tools/session-log.cjs +106 -0
  63. package/eval/tools/summarize.cjs +185 -0
  64. package/eval/tools/t3-cells.cjs +173 -0
  65. package/package.json +73 -6
  66. package/patches/adapters-smoke.yml +41 -0
  67. package/patches/eval-account.yml +36 -0
  68. package/patches/eval-baseline.yml +33 -0
  69. package/patches/eval-stream-code-off.yml +46 -0
  70. package/patches/eval-stream-code-on.yml +47 -0
  71. package/patches/eval-stream.yml +54 -0
  72. package/patches/takeover.yml +42 -0
  73. package/patches/test-preset.yml +23 -0
  74. package/preset/stream/cordis.patch.yml +39 -0
  75. package/preset/stream/package.json +13 -0
  76. package/preset.yml +56 -0
  77. package/profiles/stream/README.md +66 -0
  78. package/profiles/stream/cordis.patch.yml +12 -0
  79. package/profiles/stream/package.json +17 -0
  80. package/profiles/stream-headless/package.json +16 -0
  81. package/scripts/build.mjs +103 -0
  82. package/scripts/check-consistency.mjs +146 -0
  83. package/scripts/gate.mjs +138 -0
  84. package/scripts/install-check.mjs +116 -0
  85. package/scripts/install-cycle.mjs +88 -0
  86. package/scripts/release.mjs +428 -0
  87. package/scripts/repair-session-logs.mjs +498 -0
  88. package/src/entry/action-gate.ts +206 -0
  89. package/src/entry/adapter-kit.ts +192 -0
  90. package/src/entry/context-render.ts +119 -0
  91. package/src/entry/control-bar-cli.ts +289 -0
  92. package/src/entry/control-bar.ts +123 -0
  93. package/src/entry/control-session.ts +115 -0
  94. package/src/entry/control-state.ts +125 -0
  95. package/src/entry/cordis-compat.ts +95 -0
  96. package/src/entry/eval-probe.ts +112 -0
  97. package/src/entry/intent-log.ts +121 -0
  98. package/src/entry/json-persistence.ts +306 -0
  99. package/src/entry/loop.ts +4163 -0
  100. package/src/entry/mock-provider.ts +549 -0
  101. package/src/entry/obs-broker.ts +178 -0
  102. package/src/entry/ptc-bridge.ts +405 -0
  103. package/src/entry/state-handle.ts +217 -0
  104. package/src/entry/takeover-registry.ts +60 -0
  105. package/src/kernel/control-bar.ts +559 -0
  106. package/src/kernel/final.ts +62 -0
  107. package/src/kernel/gate.ts +464 -0
  108. package/src/kernel/modes.ts +253 -0
  109. package/src/kernel/obs.ts +517 -0
  110. package/src/kernel/parser.ts +1081 -0
  111. package/src/kernel/render.ts +466 -0
  112. package/src/kernel/state.ts +416 -0
  113. package/src/version.ts +9 -0
  114. package/test/activation.test.ts +187 -0
  115. package/test/adapters.test.ts +676 -0
  116. package/test/control-bar.test.ts +486 -0
  117. package/test/desktop-ui.test.ts +359 -0
  118. package/test/eval-probe.test.ts +139 -0
  119. package/test/f5-plan.test.ts +221 -0
  120. package/test/f6-intent.test.ts +168 -0
  121. package/test/f7-segment.test.ts +190 -0
  122. package/test/fix-limits.test.ts +599 -0
  123. package/test/gate.test.ts +380 -0
  124. package/test/helpers/stub-loop.ts +240 -0
  125. package/test/host-conformance.test.ts +418 -0
  126. package/test/kernel/obs.test.ts +329 -0
  127. package/test/kernel/parser.test.ts +451 -0
  128. package/test/loop.test.ts +1393 -0
  129. package/test/mock-provider.test.ts +386 -0
  130. package/test/ptc-bridge.test.ts +356 -0
  131. package/test/render.test.ts +418 -0
  132. package/test/s2-install-check.test.ts +46 -0
  133. package/test/scenarios/3-file-basic.json +13 -0
  134. package/test/scenarios/5-file-basic.json +22 -0
  135. package/test/scenarios/burn-more.json +9 -0
  136. package/test/scenarios/degraded-final.json +10 -0
  137. package/test/scenarios/fault-abort-xml.json +11 -0
  138. package/test/scenarios/fault-malformed-command.json +12 -0
  139. package/test/scenarios/fault-midstream-abort.json +11 -0
  140. package/test/scenarios/fault-saturating-output.json +9 -0
  141. package/test/scenarios/fault-timeout.json +9 -0
  142. package/test/scenarios/peek-first.json +11 -0
  143. package/test/scenarios/peek-second.json +11 -0
  144. package/test/scenarios/peek-third.json +10 -0
  145. package/test/scenarios/recover-final.json +10 -0
  146. package/test/scenarios/reroute-first.json +17 -0
  147. package/test/scenarios/reroute-second.json +16 -0
  148. package/test/scenarios/starvation-final.json +10 -0
  149. package/test/scenarios/starvation-promote.json +11 -0
  150. package/test/scenarios/wait-tools-continue.json +10 -0
  151. package/test/scenarios/wait-tools-xml.json +22 -0
  152. package/test/scenarios/wait-tools.json +15 -0
  153. package/test/session-format.test.ts +234 -0
  154. package/test/state.test.ts +335 -0
  155. package/test/stream-v02.test.ts +264 -0
  156. package/test/v031-display.test.ts +333 -0
  157. package/test/v032-conflict.test.ts +191 -0
  158. package/test/v032-truncation.test.ts +291 -0
  159. package/ui/client.js +576 -0
  160. package/ui/index.js +282 -0
  161. package/ui/package.json +26 -0
@@ -0,0 +1,559 @@
1
+ // kernel/control-bar.ts —— 控制栏的纯渲染 + 按键状态机(v0.2.1)
2
+ //
3
+ // 三块职责,全部无副作用:
4
+ // ① 文案表:中文/英文成对出现(TextKey 由表自身推导);运行期缺 key 回退为 key 本身。
5
+ // 两个语言的输出必须结构性一致——同一份面板,只换文字。
6
+ // ② 渲染:状态条(单行)、面板(交互)、引导(首次装载)、帮助(全模式指南)、JSON。
7
+ // ③ 按键:把一次按键解释成意图(选模式 / 切语言 / 帮助 / 退出),由调用方落盘。
8
+ //
9
+ // 宽度纪律(终端排版的坑,实测踩过):
10
+ // · CJK 记 2 列;结构分隔符一律用 ASCII(| > -> * ),因为 · → ① … 这些
11
+ // "东亚宽度不确定字符"在 CJK 字体里是 2 列、在 Latin 字体里是 1 列,
12
+ // 同一份输出在两种终端会错位。盒子只用 ─│╭╮╰╯(公认 1 列)。
13
+ // · 长文案按显示列宽换行,不截断——中文没有空格,逐字符折行。
14
+ //
15
+ // 与宿主无关:本文件不 import 任何东西,node --test 直接可测。
16
+
17
+ import { AVAILABILITY_TEXT, DEFAULT_MODE, MODES, SAVING_TEXT, getMode, isModeId, modeByOrder, publicModeCatalog } from './modes.ts';
18
+ import type { ModeId, ModeSpec } from './modes.ts';
19
+
20
+ export type Lang = 'zh' | 'en';
21
+ export const LANGS: readonly Lang[] = ['zh', 'en'];
22
+ export const DEFAULT_LANG: Lang = 'zh';
23
+
24
+ export function isLang(value: unknown): value is Lang {
25
+ return value === 'zh' || value === 'en';
26
+ }
27
+
28
+ /** 另一门语言(用于 l 键与"切换语言"提示)。 */
29
+ export function otherLang(lang: Lang): Lang {
30
+ return lang === 'zh' ? 'en' : 'zh';
31
+ }
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // ① 文案表
35
+ // ---------------------------------------------------------------------------
36
+
37
+ const TEXT = {
38
+ barTitle: { zh: '控制栏', en: 'CONTROL BAR' },
39
+ active: { zh: '接管生效', en: 'TAKEOVER ACTIVE' },
40
+ inactive: { zh: '未接管', en: 'NOT TAKEN OVER' },
41
+ activeHint: {
42
+ zh: '单流协议已接管 agent 创建',
43
+ en: 'single-stream protocol owns agent creation',
44
+ },
45
+ inactiveHint: {
46
+ zh: '内建 agent-loop 仍在工作,检查 bundle 是否装载',
47
+ en: 'built-in agent-loop still running; check whether the bundle is mounted',
48
+ },
49
+ mode: { zh: '模式', en: 'Mode' },
50
+ current: { zh: '当前', en: 'Current' },
51
+ fits: { zh: '适合', en: 'Use when' },
52
+ cost: { zh: '代价', en: 'Trade-off' },
53
+ saving: { zh: '省 token', en: 'Token saving' },
54
+ availability: { zh: '可用性', en: 'Availability' },
55
+ note: { zh: '标注', en: 'Note' },
56
+ steps: { zh: '上手', en: 'Start' },
57
+ keys: { zh: '按键', en: 'Keys' },
58
+ commands: { zh: '命令', en: 'Commands' },
59
+ docs: { zh: '文档', en: 'Docs' },
60
+ status: { zh: '状态', en: 'Status' },
61
+ openBar: { zh: '打开控制栏', en: 'Open control bar' },
62
+ langLabel: { zh: '语言', en: 'Language' },
63
+ helpTitle: {
64
+ zh: '全模式指南(选错模式的代价比选错命令更高)',
65
+ en: 'Mode guide (picking the wrong mode costs more than the wrong command)',
66
+ },
67
+ helpHint: {
68
+ zh: '1-4 切模式,l 切语言,q 返回',
69
+ en: '1-4 pick mode, l language, q back',
70
+ },
71
+ panelHint: {
72
+ zh: '1-4 切模式 | Up/Down 移动 | Enter 应用 | l 中/英 | ? 帮助 | r 重置 | q 退出',
73
+ en: '1-4 mode | Up/Down move | Enter apply | l language | ? help | r reset | q quit',
74
+ },
75
+ bannerKeys: {
76
+ zh: '交互栏支持 1-4 切模式、l 切语言、? 看全模式指南',
77
+ en: 'Interactive bar: 1-4 mode, l language, ? full guide',
78
+ },
79
+ stepTitle: { zh: '上手四步', en: 'Four steps' },
80
+ step1: {
81
+ zh: '1 安装 dsh plugin --profile desktop add <包名或本地路径>',
82
+ en: '1 Install dsh plugin --profile desktop add <package or local path>',
83
+ },
84
+ step2: {
85
+ zh: '2 选模式 dsh-stream-agent mode lean(或在控制栏按 1-4)',
86
+ en: '2 Pick mode dsh-stream-agent mode lean (or press 1-4 in the bar)',
87
+ },
88
+ step3: {
89
+ zh: '3 下任务 直接说需求,模型在一次流里跑完 tf-* 命令',
90
+ en: '3 Ask describe the task; the model runs tf-* in one stream',
91
+ },
92
+ step4: {
93
+ zh: '4 核对 dsh-stream-agent status',
94
+ en: '4 Verify dsh-stream-agent status',
95
+ },
96
+ receipt: { zh: '回执', en: 'receipt' },
97
+ full: { zh: '全文', en: 'full' },
98
+ codeAuto: { zh: 'code 跟随宿主', en: 'code auto' },
99
+ codeOn: { zh: 'code 开', en: 'code on' },
100
+ codeOff: { zh: 'code 关', en: 'code off' },
101
+ parallel: { zh: '并行', en: 'parallel' },
102
+ budget: { zh: '预算', en: 'budget' },
103
+ saved: { zh: '已保存', en: 'saved' },
104
+ writeFailed: { zh: '状态写入失败(本次运行内仍生效)', en: 'state write failed (still active in this run)' },
105
+ noteLangZh: { zh: '已切换到中文(按 l 切回英文)', en: 'Switched to Chinese (press l for English)' },
106
+ noteLangEn: { zh: '已切换到英文(按 l 切回中文)', en: 'Switched to English (press l for Chinese)' },
107
+ notTty: {
108
+ zh: '当前不是交互终端,已输出一次性面板(--once 可强制)',
109
+ en: 'Not an interactive terminal; printed the one-shot panel (--once forces it)',
110
+ },
111
+ unknownMode: {
112
+ zh: '未知模式,可选值:balanced / lean / compat / power',
113
+ en: 'Unknown mode; valid: balanced / lean / compat / power',
114
+ },
115
+ unknownLang: { zh: '未知语言,可选值:zh / en', en: 'Unknown language; valid: zh / en' },
116
+ usage: { zh: '用法', en: 'Usage' },
117
+ stateFile: { zh: '状态文件', en: 'State file' },
118
+ } satisfies Record<string, { zh: string; en: string }>;
119
+
120
+ export type TextKey = keyof typeof TEXT;
121
+
122
+ /** 取一条文案;缺 key 时回退为 key 本身(绝不渲染出 undefined)。 */
123
+ export function t(key: TextKey, lang: Lang): string {
124
+ const entry = TEXT[key] as { zh?: string; en?: string } | undefined;
125
+ if (entry === undefined) return key;
126
+ const value = entry[lang];
127
+ return typeof value === 'string' && value !== '' ? value : entry.zh ?? entry.en ?? key;
128
+ }
129
+
130
+ export function textKeys(): TextKey[] {
131
+ return Object.keys(TEXT) as TextKey[];
132
+ }
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // ② 宽度 / 换行 / 盒子
136
+ // ---------------------------------------------------------------------------
137
+
138
+ /** 东亚宽字符记 2 列(与主流终端一致)。 */
139
+ export function charWidth(ch: string): number {
140
+ const code = ch.codePointAt(0) ?? 0;
141
+ const wide =
142
+ (code >= 0x1100 && code <= 0x115f)
143
+ || (code >= 0x2e80 && code <= 0xa4cf)
144
+ || (code >= 0xac00 && code <= 0xd7a3)
145
+ || (code >= 0xf900 && code <= 0xfaff)
146
+ || (code >= 0xfe30 && code <= 0xfe6f)
147
+ || (code >= 0xff00 && code <= 0xff60)
148
+ || (code >= 0xffe0 && code <= 0xffe6);
149
+ return wide ? 2 : 1;
150
+ }
151
+
152
+ export function displayWidth(text: string): number {
153
+ let width = 0;
154
+ for (const ch of text) width += charWidth(ch);
155
+ return width;
156
+ }
157
+
158
+ /** 按显示列宽截断,超出以 ... 收尾(ASCII,避免歧义宽度)。 */
159
+ export function truncate(text: string, max: number): string {
160
+ if (max <= 0) return '';
161
+ if (displayWidth(text) <= max) return text;
162
+ const ellipsis = max >= 3 ? '...' : '';
163
+ const room = max - ellipsis.length;
164
+ let out = '';
165
+ let width = 0;
166
+ for (const ch of text) {
167
+ const w = charWidth(ch);
168
+ if (width + w > room) break;
169
+ out += ch;
170
+ width += w;
171
+ }
172
+ return out + ellipsis;
173
+ }
174
+
175
+ export function padRight(text: string, width: number): string {
176
+ const gap = width - displayWidth(text);
177
+ return gap <= 0 ? text : `${text}${' '.repeat(gap)}`;
178
+ }
179
+
180
+ /**
181
+ * 断行单位:宽字符(CJK/全角)逐字可断;ASCII 连续非空白算一个整体,不切开单词。
182
+ *
183
+ * 旧实现按字符贪心、遇空格回退,英文短句没问题,但中文里夹着 `ctx.ptcRuntime`
184
+ * 这种 token 时会在空格处提前回退,行尾留下十几列空白——一屏里好几行右端参差,
185
+ * 看着像表格没对齐。改成"先切单位再贪心填充":中文能填满整行,英文单词不被打断。
186
+ *
187
+ * 闭合标点额外粘到前一个单位上:中文逐字断行时 `。` 极易被挤到下一行行首,
188
+ * 一屏里出现一个孤零零的句号。粘上之后,装不下就整对一起换行,最多让上一行
189
+ * 少 2 列,不会出现行首标点。
190
+ */
191
+ const CLOSING_PUNCT = new Set([...'。,、;:!?)〕]}》」』〉】,.;:!?)]}']);
192
+
193
+ function breakUnits(text: string): string[] {
194
+ const units: string[] = [];
195
+ let word = '';
196
+ for (const ch of text) {
197
+ // 闭合标点必须先判:中文标点本身也是宽字符,放到下面会被当成独立单位。
198
+ if (CLOSING_PUNCT.has(ch)) {
199
+ if (word !== '') {
200
+ // 英文标点本来就贴着单词,直接并进 word。
201
+ word += ch;
202
+ continue;
203
+ }
204
+ const last = units.length > 0 ? units[units.length - 1] : undefined;
205
+ if (last !== undefined && last !== ' ') {
206
+ units[units.length - 1] = last + ch;
207
+ continue;
208
+ }
209
+ units.push(ch);
210
+ continue;
211
+ }
212
+ if (ch === ' ' || charWidth(ch) > 1) {
213
+ if (word !== '') {
214
+ units.push(word);
215
+ word = '';
216
+ }
217
+ units.push(ch);
218
+ continue;
219
+ }
220
+ word += ch;
221
+ }
222
+ if (word !== '') units.push(word);
223
+ return units;
224
+ }
225
+
226
+ /** 按显示列宽折行:中文逐字断,英文按词断,行尾不留空白,末行不留孤字。 */
227
+ export function wrapText(text: string, width: number): string[] {
228
+ if (width <= 0) return [text];
229
+ if (displayWidth(text) <= width) return [text];
230
+ const lines: string[][] = [];
231
+ let current: string[] = [];
232
+ let lineWidth = 0;
233
+ const flush = (): void => {
234
+ if (current.length > 0) lines.push(current);
235
+ current = [];
236
+ lineWidth = 0;
237
+ };
238
+ for (const unit of breakUnits(text)) {
239
+ const w = displayWidth(unit);
240
+ if (unit === ' ') {
241
+ if (lineWidth === 0) continue; // 行首空格丢掉(上一条已 trimEnd)
242
+ current.push(unit);
243
+ lineWidth += w;
244
+ continue;
245
+ }
246
+ if (lineWidth > 0 && lineWidth + w > width) flush();
247
+ if (w > width) {
248
+ // 单个单位比整行还宽(超长路径/无空格长串):按列硬切,避免撑破盒子。
249
+ let piece = '';
250
+ let pieceWidth = 0;
251
+ for (const ch of unit) {
252
+ const cw = charWidth(ch);
253
+ if (pieceWidth > 0 && pieceWidth + cw > width) {
254
+ current.push(piece);
255
+ flush();
256
+ piece = '';
257
+ pieceWidth = 0;
258
+ }
259
+ piece += ch;
260
+ pieceWidth += cw;
261
+ }
262
+ if (piece !== '') {
263
+ current.push(piece);
264
+ lineWidth += pieceWidth;
265
+ }
266
+ continue;
267
+ }
268
+ current.push(unit);
269
+ lineWidth += w;
270
+ }
271
+ flush();
272
+ // 末行只剩一个单位时从上一行借一个下来:中文逐字断行很容易把"测。"单独留成
273
+ // 一行 4 列,一屏里出现这种孤字比行尾差几列更扎眼。
274
+ if (lines.length >= 2) {
275
+ const last = lines[lines.length - 1];
276
+ const prev = lines[lines.length - 2];
277
+ const borrow = prev[prev.length - 1];
278
+ if (last.length === 1 && prev.length > 2 && borrow !== undefined
279
+ && displayWidth(borrow) + displayWidth(last[0]) <= width) {
280
+ prev.pop();
281
+ last.unshift(borrow);
282
+ }
283
+ }
284
+ return lines
285
+ .map((line) => line.join('').replace(/\s+$/, ''))
286
+ .filter((line) => line !== '');
287
+ }
288
+
289
+ /** 终端列数 → 面板宽度(留 2 列边距;窄终端保底 56,宽终端最多 92)。 */
290
+ export function panelWidth(columns?: number): number {
291
+ if (columns === undefined || !Number.isFinite(columns) || columns <= 0) return 78;
292
+ return Math.max(56, Math.min(92, Math.floor(columns) - 2));
293
+ }
294
+
295
+ /** 画一个盒子:title 进顶边,lines 逐行补白(超宽才截断)。 */
296
+ export function box(title: string, lines: readonly string[], width: number): string[] {
297
+ const inner = Math.max(8, width - 4);
298
+ const titleText = truncate(` ${title} `, inner - 2);
299
+ const headFill = Math.max(0, width - 3 - displayWidth(titleText));
300
+ const out = [`╭─${titleText}${'─'.repeat(headFill)}╮`];
301
+ for (const line of lines) {
302
+ if (line === '') {
303
+ out.push(`│ ${' '.repeat(inner)} │`);
304
+ continue;
305
+ }
306
+ out.push(`│ ${padRight(truncate(line, inner), inner)} │`);
307
+ }
308
+ out.push(`╰${'─'.repeat(width - 2)}╯`);
309
+ return out;
310
+ }
311
+
312
+ /** 标签块:label + 折行正文(首行带标签,续行对齐缩进)。 */
313
+ /**
314
+ * 渲染"标签 + 值"的行,超宽按词折行,续行与首行的值列左对齐。
315
+ *
316
+ * `labelWidth` 传进来时把标签右补空格到该显示宽度:一屏里多个标签长度不同(中文
317
+ * "当前/合适/省 token",英文 "Note/Token saving"),不补空格右侧数值就会参差,
318
+ * 80 列下看起来像没对齐的表格。调用方用它传同一块里最长的标签宽度。
319
+ */
320
+ function labeled(label: string, value: string, width: number, labelWidth?: number): string[] {
321
+ const pad = labelWidth === undefined ? 0 : Math.max(0, labelWidth - displayWidth(label));
322
+ const prefix = `${label}${' '.repeat(pad)} `;
323
+ const room = Math.max(12, width - displayWidth(prefix));
324
+ const parts = wrapText(value, room);
325
+ const indent = ' '.repeat(displayWidth(prefix));
326
+ return parts.map((part, index) => (index === 0 ? `${prefix}${part}` : `${indent}${part}`));
327
+ }
328
+
329
+ // ---------------------------------------------------------------------------
330
+ // ③ 状态
331
+ // ---------------------------------------------------------------------------
332
+
333
+ export interface ControlState {
334
+ mode: ModeId;
335
+ lang: Lang;
336
+ }
337
+
338
+ export function createControlState(partial: Partial<ControlState> = {}): ControlState {
339
+ return {
340
+ mode: isModeId(partial.mode) ? partial.mode : DEFAULT_MODE,
341
+ lang: isLang(partial.lang) ? partial.lang : DEFAULT_LANG,
342
+ };
343
+ }
344
+
345
+ /** 模式的关键参数一句话(面板与状态条共用,中英一致)。 */
346
+ export function modeSummary(mode: ModeSpec, lang: Lang): string {
347
+ const feedback = mode.config.selfReadFeedback === 'receipt' ? t('receipt', lang) : t('full', lang);
348
+ const code = mode.config.enableCode === 'auto'
349
+ ? t('codeAuto', lang)
350
+ : mode.config.enableCode === true ? t('codeOn', lang) : t('codeOff', lang);
351
+ const parts = [feedback, code, `${t('parallel', lang)} ${mode.config.maxParallelToolCalls}`];
352
+ if (mode.config.budgetTokens !== undefined) {
353
+ parts.push(`${t('budget', lang)} ${Math.round(mode.config.budgetTokens / 1000)}k`);
354
+ }
355
+ return parts.join(' | ');
356
+ }
357
+
358
+ /**
359
+ * 模式的"省多少 + 能不能用"一句话标注(引导面板 / 帮助页每模式一行)。
360
+ *
361
+ * 这两件事是新人选模式时最先问的,所以放在同一行;定量口径与"未单独实测"写在
362
+ * `mode.note` 里,只在面板(当前模式详情)展开,避免帮助页变成一屏论文。
363
+ */
364
+ export function modeBadges(mode: ModeSpec, lang: Lang): string {
365
+ return `${SAVING_TEXT[mode.saving][lang]} | ${AVAILABILITY_TEXT[mode.availability][lang]}`;
366
+ }
367
+
368
+ /** 模式选择条:[1]*均衡 [2] 精简 [3] 兼容 [4] 增强(* = 已应用,> = 焦点) */
369
+ export function modeStrip(state: ControlState, focus?: ModeId): string {
370
+ return MODES.map((m) => {
371
+ const mark = m.id === state.mode ? '*' : focus === m.id ? '>' : ' ';
372
+ return `[${m.order}]${mark}${m.label[state.lang]}`;
373
+ }).join(' ');
374
+ }
375
+
376
+ // ---------------------------------------------------------------------------
377
+ // ④ 渲染
378
+ // ---------------------------------------------------------------------------
379
+
380
+ export interface RenderOptions {
381
+ version: string;
382
+ /** true = 接管生效;false = 未接管;undefined = 无从得知(CLI 独立进程:不臆断) */
383
+ active?: boolean;
384
+ /** 终端列数(process.stdout.columns);缺省 80 列布局 */
385
+ columns?: number;
386
+ /** 交互栏的焦点模式(未应用) */
387
+ focus?: ModeId;
388
+ }
389
+
390
+ /** 单行状态条:贴在任何输出上方都不喧哗。非 TTY(无 columns)不截断,交给调用方重定向。 */
391
+ export function renderStatusBar(state: ControlState, options: RenderOptions): string {
392
+ const { lang } = state;
393
+ const mode = getMode(state.mode);
394
+ const status = options.active === undefined
395
+ ? undefined
396
+ : options.active ? t('active', lang) : t('inactive', lang);
397
+ const parts = [`dsh-stream-agent ${options.version}`];
398
+ if (status !== undefined) parts.push(status);
399
+ parts.push(`${t('mode', lang)} ${mode.order} ${mode.label[lang]}`, modeSummary(mode, lang));
400
+ const line = parts.join(' | ');
401
+ const limit = options.columns === undefined ? Number.POSITIVE_INFINITY : panelWidth(options.columns);
402
+ return truncate(line, limit);
403
+ }
404
+
405
+ /** 首次装载的引导面板(stderr,一次性)。 */
406
+ export function renderBanner(state: ControlState, options: RenderOptions): string[] {
407
+ const { lang } = state;
408
+ const width = panelWidth(options.columns);
409
+ const mode = getMode(state.mode);
410
+ const colon = lang === 'zh' ? ':' : ': ';
411
+ const statusLine = options.active === undefined
412
+ ? undefined
413
+ : options.active
414
+ ? `* ${t('active', lang)}${colon}${t('activeHint', lang)}`
415
+ : `* ${t('inactive', lang)}${colon}${t('inactiveHint', lang)}`;
416
+ const lines = [
417
+ ...(statusLine === undefined ? [] : [statusLine]),
418
+ `${t('mode', lang)}: ${mode.order} ${mode.label[lang]} (${mode.id}) | ${modeSummary(mode, lang)}`,
419
+ ...labeled(t('fits', lang), mode.useWhen[lang], width - 4),
420
+ ...labeled(t('saving', lang), modeBadges(mode, lang), width - 4),
421
+ '',
422
+ t('stepTitle', lang),
423
+ ` ${t('step1', lang)}`,
424
+ ` ${t('step2', lang)}`,
425
+ ` ${t('step3', lang)}`,
426
+ ` ${t('step4', lang)}`,
427
+ '',
428
+ ...labeled(t('openBar', lang), 'dsh-stream-agent bar', width - 4),
429
+ ...labeled(t('keys', lang), t('bannerKeys', lang), width - 4),
430
+ `${t('docs', lang)}: README.md#control-bar`,
431
+ ];
432
+ return box(`dsh-stream-agent v${options.version} - ${t('barTitle', lang)}`, lines, width);
433
+ }
434
+
435
+ /** 交互面板:模式条 + 当前模式详情 + 键位 + 命令。 */
436
+ export function renderPanel(state: ControlState, options: RenderOptions): string[] {
437
+ const { lang } = state;
438
+ const width = panelWidth(options.columns);
439
+ const mode = getMode(state.mode);
440
+ const focus = options.focus === undefined ? mode : getMode(options.focus);
441
+ const statusLine = options.active === undefined
442
+ ? []
443
+ : [`${t('status', lang)}: ${options.active ? t('active', lang) : t('inactive', lang)}`];
444
+ // 整块共用同一标签宽度:中文最长是"省 token",英文是 "Token saving"。
445
+ const labelWidth = Math.max(
446
+ displayWidth(t('current', lang)),
447
+ displayWidth(t('fits', lang)),
448
+ displayWidth(t('cost', lang)),
449
+ displayWidth(t('saving', lang)),
450
+ displayWidth(t('availability', lang)),
451
+ displayWidth(t('note', lang)),
452
+ displayWidth(t('commands', lang)),
453
+ displayWidth(t('keys', lang)),
454
+ );
455
+ const lines = [
456
+ ...statusLine,
457
+ `${t('mode', lang)}: ${modeStrip(state, options.focus)}`,
458
+ ...labeled(t('current', lang), `${focus.order} ${focus.label[lang]} (${focus.id}) | ${modeSummary(focus, lang)}`, width - 4, labelWidth),
459
+ ...labeled(t('fits', lang), focus.useWhen[lang], width - 4, labelWidth),
460
+ ...labeled(t('cost', lang), focus.tradeoff[lang], width - 4, labelWidth),
461
+ ...labeled(t('saving', lang), SAVING_TEXT[focus.saving][lang], width - 4, labelWidth),
462
+ ...labeled(t('availability', lang), AVAILABILITY_TEXT[focus.availability][lang], width - 4, labelWidth),
463
+ ...labeled(t('note', lang), focus.note[lang], width - 4, labelWidth),
464
+ '',
465
+ ...labeled(t('commands', lang), 'dsh-stream-agent bar | status | mode <id> | lang <zh|en>', width - 4, labelWidth),
466
+ '',
467
+ ...labeled(t('keys', lang), t('panelHint', lang), width - 4, labelWidth),
468
+ `${t('langLabel', lang)}: ${state.lang} | ${t('docs', lang)}: README.md#control-bar`,
469
+ ];
470
+ return box(`dsh-stream-agent v${options.version} - ${t('barTitle', lang)}`, lines, width);
471
+ }
472
+
473
+ /** 全模式指南:四个模式逐一给出"适合 / 代价",并标出当前模式。 */
474
+ export function renderHelp(state: ControlState, options: RenderOptions): string[] {
475
+ const { lang } = state;
476
+ const width = panelWidth(options.columns);
477
+ const inner = width - 4;
478
+ const lines: string[] = [t('helpTitle', lang), ''];
479
+ // 四个模式共用同一标签宽度,纵向扫视时"适合/代价/省 token"的值列才在同一列。
480
+ const labelWidth = Math.max(
481
+ displayWidth(` ${t('fits', lang)}`),
482
+ displayWidth(` ${t('cost', lang)}`),
483
+ displayWidth(` ${t('saving', lang)}`),
484
+ );
485
+ for (const mode of MODES) {
486
+ const mark = mode.id === state.mode ? '*' : ' ';
487
+ lines.push(`[${mode.order}]${mark}${mode.label[lang]} (${mode.id}) | ${modeSummary(mode, lang)}`);
488
+ lines.push(...labeled('', mode.tagline[lang], inner).map((line) => ` ${line.trimStart()}`));
489
+ lines.push(...labeled(` ${t('fits', lang)}`, mode.useWhen[lang], inner, labelWidth));
490
+ lines.push(...labeled(` ${t('cost', lang)}`, mode.tradeoff[lang], inner, labelWidth));
491
+ lines.push(...labeled(` ${t('saving', lang)}`, modeBadges(mode, lang), inner, labelWidth));
492
+ lines.push('');
493
+ }
494
+ lines.push(t('helpHint', lang));
495
+ return box(`dsh-stream-agent v${options.version} - ${t('barTitle', lang)}`, lines, width);
496
+ }
497
+
498
+ /** 机器可读状态(--json / status --json)。 */
499
+ export function renderJson(state: ControlState, options: RenderOptions): string {
500
+ const mode = getMode(state.mode);
501
+ return JSON.stringify({
502
+ version: options.version,
503
+ active: options.active !== false,
504
+ mode: { id: mode.id, order: mode.order, label: mode.label[state.lang], config: mode.config },
505
+ lang: state.lang,
506
+ modes: publicModeCatalog(),
507
+ }, null, 2);
508
+ }
509
+
510
+ // ---------------------------------------------------------------------------
511
+ // ⑤ 按键 → 意图
512
+ // ---------------------------------------------------------------------------
513
+
514
+ export type KeyAction =
515
+ | { kind: 'quit' }
516
+ | { kind: 'toggle-help' }
517
+ | { kind: 'close-help' }
518
+ | { kind: 'toggle-lang' }
519
+ | { kind: 'reset' }
520
+ | { kind: 'move'; delta: 1 | -1 }
521
+ | { kind: 'apply' }
522
+ | { kind: 'select'; mode: ModeId }
523
+ | { kind: 'none' };
524
+
525
+ /** 把一次按键(原始终端序列)解释为控制栏意图。q 在帮助页是"返回",在面板是"退出"。 */
526
+ export function interpretKey(raw: string, context: { helpOpen?: boolean } = {}): KeyAction {
527
+ const key = raw;
528
+ if (key === 'q' || key === 'Q' || key === '\x03' /* Ctrl-C */ || key === '\x1b' /* Esc */) {
529
+ return context.helpOpen === true ? { kind: 'close-help' } : { kind: 'quit' };
530
+ }
531
+ if (key === '?' || key === 'h' || key === 'H') return { kind: 'toggle-help' };
532
+ if (key === 'l' || key === 'L') return { kind: 'toggle-lang' };
533
+ if (key === 'r' || key === 'R') return { kind: 'reset' };
534
+ if (key === '\x1b[A' || key === 'k' || key === 'K') return { kind: 'move', delta: -1 };
535
+ if (key === '\x1b[B' || key === 'j' || key === 'J') return { kind: 'move', delta: 1 };
536
+ if (/^[1-4]$/.test(key)) {
537
+ const mode = modeByOrder(Number(key));
538
+ if (mode !== undefined) return { kind: 'select', mode: mode.id };
539
+ }
540
+ if (key === '\r' || key === '\n' || key === ' ') return { kind: 'apply' };
541
+ return { kind: 'none' };
542
+ }
543
+
544
+ /** 焦点移动(↑↓):在 MODES 里环状移动。 */
545
+ export function moveFocus(focus: ModeId, delta: 1 | -1): ModeId {
546
+ const index = MODES.findIndex((m) => m.id === focus);
547
+ const base = index < 0 ? 0 : index;
548
+ return MODES[(base + delta + MODES.length) % MODES.length].id;
549
+ }
550
+
551
+ /** "应用焦点"的落点(Enter):返回焦点模式(越界回默认)。 */
552
+ export function selectFocus(focus: ModeId): ModeId {
553
+ return getMode(focus).id;
554
+ }
555
+
556
+ /** 渲染成可直接 write 的文本(CLI 与测试共用)。 */
557
+ export function renderToText(lines: readonly string[]): string {
558
+ return `${lines.join('\n')}\n`;
559
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * kernel/final.ts —— tf-final summary 质量闸(v0.3.1「任务半途截断」修复的内核半边)
3
+ *
4
+ * 背景(0.3.1 真机证据,会话 `session-84274277`):
5
+ * 模型在任务只走到第 4 步时输出 `<tf-final id="f1" summary="placeholder"/>`,
6
+ * 驱动器照单全收;随后模型又继续跑了 3 步,而这条**过期**的 final 仍是"最后一个
7
+ * ok 的 final",回合结束时被当作最终答案落盘——用户侧看到的就是"任务做一半被截断,
8
+ * 答案是一句 placeholder"。
9
+ *
10
+ * 本模块只做一件事:判定 summary 是否**根本不含最终答案**(空 / 占位词)。
11
+ * 判定刻意保守——只抓明确的占位形态,不猜"答案够不够详细":
12
+ * - 空 → 'empty'
13
+ * - placeholder / 占位 / TODO / TBD / N/A / 待补 / …… 之类 → 'placeholder'
14
+ * - 其它一律放行("done"、"已完成" 这类短答案不在拒绝面内:宁可放过,
15
+ * 也不把合法短答案判死——协议文本负责引导,驱动器只拦"根本没写答案"的形态)。
16
+ *
17
+ * 内核层纪律:纯函数、零 IO、无框架依赖。
18
+ */
19
+
20
+ export type FinalSummaryIssueKind = 'empty' | 'placeholder';
21
+
22
+ export interface FinalSummaryIssue {
23
+ kind: FinalSummaryIssueKind;
24
+ /** 结构化说明(直接拼进 [tf-stream:error] 注入给模型看,要求可执行)。 */
25
+ detail: string;
26
+ }
27
+
28
+ /** 明确的占位形态(整串匹配;大小写不敏感)。故意不含 done/已完成/null/none——
29
+ * 这些既可能是占位也可能是任务的真实短答案,判定权留给协议与人工。 */
30
+ const PLACEHOLDER_SUMMARY_RE =
31
+ /^(?:placeholder|placeholders|占位符?|todo|tbd|tba|n\/a|xxx+|待补充|待补|待填|待定|待完善|\.{2,}|…+|-+|—+|\?+|?+)$/i;
32
+
33
+ /** 去掉包裹引号/括号与尾部标点,得到用于判定的规范形(不改动原 summary)。 */
34
+ function normalizeSummary(summary: string): string {
35
+ return summary
36
+ .replace(/^[\s"'`「『(([]+/, '')
37
+ .replace(/[\s"'`」』))\]。,,、!!??~~::;;]+$/, '');
38
+ }
39
+
40
+ /**
41
+ * 检查 tf-final 的 summary。
42
+ * 返回 null = 可以收敛(内容是否足够好不是驱动器该判的事);否则给出可注入的结构化原因。
43
+ */
44
+ export function checkFinalSummary(summary: string | undefined): FinalSummaryIssue | null {
45
+ const raw = summary ?? '';
46
+ const norm = normalizeSummary(raw.trim());
47
+ if (norm === '') {
48
+ return {
49
+ kind: 'empty',
50
+ detail: raw.trim() === ''
51
+ ? 'summary 为空:tf-final 必须携带最终答案原文(数字/行内容/路径/结论)'
52
+ : `summary 只有标点或空白(${JSON.stringify(raw)}):tf-final 必须携带最终答案原文`,
53
+ };
54
+ }
55
+ if (PLACEHOLDER_SUMMARY_RE.test(norm)) {
56
+ return {
57
+ kind: 'placeholder',
58
+ detail: `summary 是占位内容(${JSON.stringify(raw)}):占位 final 不能作为交付答案,必须写出最终答案原文(数字/行内容/路径/结论);任务没做完就不要输出 tf-final`,
59
+ };
60
+ }
61
+ return null;
62
+ }