@hncode/hncode 0.8.3 → 0.8.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hncode/hncode",
3
- "version": "0.8.3",
3
+ "version": "0.8.5",
4
4
  "description": "hncode — A cyan-blue TUI AI coding agent with zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -32,7 +32,8 @@
32
32
  // pointing at one prints its full name and value in the row below the bar. That is why step
33
33
  // 3 is acceptable — the information stays one pointer away.
34
34
 
35
- import { C } from './colors.js';
35
+ import { C } from './colors.js';
36
+ import { visualWidth } from './term.js';
36
37
  import { uiText } from './i18n.js';
37
38
 
38
39
  /** The segments, in the order they are drawn. Order is part of the reading: the session
@@ -142,13 +143,13 @@ export function renderContextBar(segments, usedTokens, window, width, readout) {
142
143
  const figures = `${compactTokens(usedTokens)}/${compactTokens(window)}`;
143
144
  const own = typeof readout === 'string' ? readout : '';
144
145
  const forms = [...new Set([own, `${figures} ${pct}`, pct].filter(Boolean))];
145
- const text = forms.find((f) => f.length + 1 <= width) || '';
146
- const barWidth = Math.max(0, width - text.length - 1);
146
+ const text = forms.find((f) => visualWidth(f) + 1 <= width) || '';
147
+ const barWidth = Math.max(0, width - visualWidth(text) - 1);
147
148
 
148
149
  if (barWidth <= 0) {
149
150
  // Too narrow for a bar AND a gap: the readout has the row to itself. Padded to exactly
150
151
  // `width` because every row of the frame is, and a short one shifts everything below it.
151
- return { text: text ? C.white + text.padEnd(width) : ' '.repeat(width), hits: [] };
152
+ return { text: text ? C.white + padToWidth(text, width) : ' '.repeat(width), hits: [] };
152
153
  }
153
154
 
154
155
  const free = Math.max(0, window - usedTokens);
@@ -173,6 +174,18 @@ export function renderContextBar(segments, usedTokens, window, width, readout) {
173
174
  * any fill — so it is legible at every fill level, including a completely full bar.
174
175
  * @param {number} width the whole row, bar plus readout.
175
176
  */
177
+ /**
178
+ * Pad a string to `width` DISPLAY COLUMNS.
179
+ *
180
+ * `String.prototype.padEnd` counts characters, and a Chinese character is two columns —
181
+ * so padding a Chinese label to a column count with it leaves the row short by one column
182
+ * per character, and every segment after it shifts left. The figure at the end of the row
183
+ * is what falls off the screen.
184
+ */
185
+ function padToWidth(text, width) {
186
+ const pad = width - visualWidth(text);
187
+ return pad > 0 ? text + ' '.repeat(pad) : text;
188
+ }
176
189
  function paintBar(cols, freeCols, _unused, values, readout, width) {
177
190
  let out = '';
178
191
  let at = 0; // visible column the next segment starts at
@@ -189,11 +202,11 @@ function paintBar(cols, freeCols, _unused, values, readout, width) {
189
202
  // own fill, which reads as if the label belonged to the segment before it. The first
190
203
  // segment's left column is the row's own margin, so both cost the same.
191
204
  const room = n - 2;
192
- const inner = room >= label.full.length
205
+ const inner = room >= visualWidth(label.full)
193
206
  ? label.full
194
- : (room >= label.name.length ? label.name : '');
207
+ : (room >= visualWidth(label.name) ? label.name : '');
195
208
  // `room` columns of label, a blank on the left and one on the right: `n`.
196
- out += seg.fill + (inner ? ' ' + C.white + inner.padEnd(room, ' ') + ' ' : ' '.repeat(n));
209
+ out += seg.fill + (inner ? ' ' + C.white + padToWidth(inner, room) + ' ' : ' '.repeat(n));
197
210
  hits.push({ col0: at, col1: at + n - 1, data: seg.key });
198
211
  at += n;
199
212
  }
@@ -209,7 +222,7 @@ function paintBar(cols, freeCols, _unused, values, readout, width) {
209
222
  // `at` is the bar's visible width and the row is `width` wide, so the gap is whatever is
210
223
  // left minus the figures — at least one column, which is what keeps `11.7k/97` from reading
211
224
  // as a continuation of a segment's fill.
212
- const gap = Math.max(1, width - at - readout.length);
225
+ const gap = Math.max(1, width - at - visualWidth(readout));
213
226
  out += C.reset + ' '.repeat(gap) + C.white + readout;
214
227
 
215
228
  return { text: out + C.reset, hits };
@@ -225,8 +238,8 @@ export function formatReadout(used, window, freeCols) {
225
238
  // The thresholds match the renderer's own condition exactly (`freeCols >= length`). They
226
239
  // used to ask for one more, which is how the bar came up a column short: the readout was
227
240
  // accepted HERE and then not written THERE.
228
- if (freeCols >= full.length) return full;
229
- if (freeCols >= pct.length) return pct;
241
+ if (freeCols >= visualWidth(full)) return full;
242
+ if (freeCols >= visualWidth(pct)) return pct;
230
243
  return '';
231
244
  }
232
245
 
package/src/i18n.js CHANGED
@@ -682,6 +682,11 @@ export const MESSAGES = {
682
682
  'plan.summary': { zh: "步骤:{steps} 行数:{lines} 涉及文件:{files}", en: "Steps: {steps} Lines: {lines} Files mentioned: {files}" },
683
683
  'plan.andMore': { zh: "… 另有 {n} 个", en: "… and {n} more" },
684
684
  'keybindings.header': { zh: "快捷键({n})— {file}", en: "Keybindings ({n}) — {file}" },
685
+ // ---- the status row tallies ----
686
+ 'status.turns': { zh: "{n} 轮", en: "{n} turns" },
687
+ 'status.turnsOne': { zh: "{n} 轮", en: "{n} turn" },
688
+ 'status.steps': { zh: "{n} 步", en: "{n} steps" },
689
+ 'status.stepsOne': { zh: "{n} 步", en: "{n} step" },
685
690
  };
686
691
 
687
692
 
@@ -1390,6 +1395,23 @@ export const NOTICE_ZH = {
1390
1395
  "Browse everything with /settings,": "用 /settings 浏览全部,",
1391
1396
  "or set one directly: /set <key> <value>": "或直接设置:/set <key> <value>",
1392
1397
  "WebSearch keys cleared — searches use keyless mode (rate-limited per IP).": "WebSearch 密钥已清除 — 搜索改用无密钥模式(按 IP 限流)",
1398
+ "cost": "费用",
1399
+ "No keybindings set.": "没有设置快捷键",
1400
+ "File": "文件",
1401
+ "Add one with /keybindings add <key> <key|/command>": "用 /keybindings add <键> <键|/命令> 添加一条",
1402
+ "Problems": "问题",
1403
+ "Prompt caching": "提示缓存",
1404
+ "The stable prefix (tools + system + conversation head) is marked cacheable.": "稳定的前缀(工具 + 系统 + 对话开头)会被标记为可缓存。",
1405
+ "Providers bill cached input at a fraction of the normal rate. Effective for:": "服务商对缓存输入按正常价格的零头计费。适用于:",
1406
+ // ---- speech input ----
1407
+ "Listening… speak now": "正在听… 请说话",
1408
+ "Already listening…": "正在监听中…",
1409
+ "Inserted {n} characters": "已插入 {n} 个字符",
1410
+ "Speech input failed": "语音输入失败",
1411
+ // ---- speech input ----
1412
+ "Listening… release to insert": "正在听… 松开插入",
1413
+ "Speech input is unavailable": "语音输入不可用",
1414
+ "No speech engine was found.": "没有找到语音识别引擎",
1393
1415
  };
1394
1416
 
1395
1417
  // The UI's active language, shared with the render modules (rows, panels, file tree)
@@ -238,7 +238,8 @@ export function writeKeybindings(home, doc) {
238
238
  export function describeKeybindings(loaded) {
239
239
  const out = [];
240
240
  if (!loaded.bindings.size) {
241
- out.push('No keybindings set.', '', `File: ${loaded.file}`, 'Add one with /keybindings add <key> <key|/command>');
241
+ out.push(uiText('No keybindings set.'), '', `${uiText('File')}: ${loaded.file}`,
242
+ uiText('Add one with /keybindings add <key> <key|/command>'));
242
243
  } else {
243
244
  out.push(t(getUiLang(), 'keybindings.header', { n: loaded.bindings.size, file: loaded.file }), '');
244
245
  for (const [from, to] of [...loaded.bindings.entries()].sort()) {
@@ -246,7 +247,7 @@ export function describeKeybindings(loaded) {
246
247
  }
247
248
  }
248
249
  if (loaded.errors.length) {
249
- out.push('', 'Problems:', ...loaded.errors.map((e) => ` ! ${e}`));
250
+ out.push('', `${uiText('Problems')}:`, ...loaded.errors.map((e) => ` ! ${e}`));
250
251
  }
251
252
  return out;
252
253
  }
@@ -1,4 +1,21 @@
1
1
  // A tool result row: the `↳` block under the tool line.
2
+
3
+ /**
4
+ * The tool-result marker, and the indent that lines the rows under it up.
5
+ *
6
+ * `↳` is East Asian AMBIGUOUS: one column on an English terminal, two on a Chinese one.
7
+ * A marker whose width moves with the terminal is a marker that moves the text under it,
8
+ * so the glyph is measured ONCE here and the indent is derived from that measurement
9
+ * rather than being spelled out again at each site. Two implementations of this — one
10
+ * measuring, one hard-coding — is what let the two disagree.
11
+ */
12
+ export const TOOL_MARKER = '↳';
13
+
14
+ /** The marker plus its trailing space: the whole prefix of a marked row. */
15
+ export const TOOL_MARKER_PREFIX = `${TOOL_MARKER} `;
16
+
17
+ /** The indent for the rows that follow a marked one: the marker prefix, blanked. */
18
+ export const TOOL_MARKER_INDENT = TOOL_MARKER_PREFIX.replace(/\S/g, ' ');
2
19
  //
3
20
  // The shape is the same for every tool, and the parts differ:
4
21
  //
@@ -25,8 +42,17 @@ export function toolResultRows(msg, width, expanded) {
25
42
  // grey, which on a dark page made it a smudge in the margin rather than a marker. The
26
43
  // plain text is kept for the comparisons below and for the width maths; the coloured one
27
44
  // is what is drawn.
45
+ //
46
+ // IT CLOSES WITH THE ROW'S OWN COLOUR, NOT A RESET.
47
+ //
48
+ // The body colour is wrapped around the whole line by the caller (`color + text + reset`),
49
+ // so whatever this marker does to the foreground has to be undone before the body text
50
+ // follows. A `ESC[0m` closed the caller's colour too, and on a failed result the first line
51
+ // — the one carrying the marker — came out default grey while every line under it was red.
52
+ // Restating the body colour is the only form that survives either way.
28
53
  const PRE = '↳ ';
29
- const pre = C.marker + '↳ ' + C.reset;
54
+ const bodyFg = msg.failed ? C.red : C.gray;
55
+ const pre = C.marker + '↳ ' + bodyFg;
30
56
  const cont = ' ';
31
57
  const bodyW = Math.max(1, width - visualCol(cont));
32
58
  // Strip escapes BEFORE splitting: a file or a command can emit raw cursor codes, and letting them through made the
@@ -491,7 +491,20 @@ export function placementRows(img, height) {
491
491
  function rowText(screen, y, from, to) {
492
492
  let out = '';
493
493
  let styleId = -1;
494
- for (let x = from; x < to; x++) {
494
+ // A RUN STARTS ON A CHARACTER, NEVER ON THE SECOND HALF OF A WIDE ONE.
495
+ //
496
+ // The second half of a wide glyph — the `spacer` cell a CJK character occupies beside
497
+ // its first — holds no character of its own. Writing the run from there would emit the
498
+ // following character INTO the middle of the wide one, and the terminal would put it one
499
+ // column to the left of where the grid says it goes: the row came out one character wide
500
+ // and everything after it shifted, which is how a tool line came to read `BBash`.
501
+ //
502
+ // So the run starts at the wide character's FIRST half when the range begins in its
503
+ // second, and the wide character's own second half is skipped as it always was — the
504
+ // terminal advances the cursor over it by itself.
505
+ let start = from;
506
+ while (start > 0 && screen.isSpacer(start, y)) start--;
507
+ for (let x = start; x < to; x++) {
495
508
  if (screen.isSpacer(x, y)) continue;
496
509
  const cell = screen.at(x, y);
497
510
  if (cell.styleId !== styleId) {
package/src/screen.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { charWidth as termCharWidth } from './term.js';
1
2
  /**
2
3
  * A screen buffer of individual cells, and the diff that turns two of them into terminal bytes.
3
4
  *
@@ -247,25 +248,20 @@ export class Screen {
247
248
  }
248
249
  }
249
250
 
250
- /** Terminal columns a code point occupies. Narrow unless it is East Asian wide or an emoji. */
251
+ /**
252
+ * Terminal columns a code point occupies.
253
+ *
254
+ * DELEGATED, not reimplemented. This file used to carry its own small table — wide CJK and
255
+ * emoji, narrow everything else — while `term.js` carried the full Unicode one. Two answers
256
+ * to the same question disagree the moment either learns something the other has not, and
257
+ * they did: `term.js` measures East Asian AMBIGUOUS glyphs as two columns on a CJK terminal
258
+ * (`↳`, `…`, `↑`), and the screen painter still counted them as one. Every such glyph on a
259
+ * row therefore left a column of the painted grid unused, the LAST column of the row was
260
+ * never reached, and the scrollbar drawn in it vanished for exactly those rows — a rail
261
+ * broken into pieces.
262
+ */
251
263
  export function charWidth(ch) {
252
- const cp = ch.codePointAt(0);
253
- if (cp === undefined) return 1;
254
- // Combining marks attach to the previous cell and take no column of their own.
255
- if (cp >= 0x300 && cp <= 0x36f) return 0;
256
- if (
257
- (cp >= 0x1100 && cp <= 0x115f) // Hangul Jamo
258
- || (cp >= 0x2e80 && cp <= 0xa4cf) // CJK radicals … Yi
259
- || (cp >= 0xac00 && cp <= 0xd7a3) // Hangul syllables
260
- || (cp >= 0xf900 && cp <= 0xfaff) // CJK compatibility ideographs
261
- || (cp >= 0xfe30 && cp <= 0xfe6f) // CJK compatibility forms
262
- || (cp >= 0xff00 && cp <= 0xff60) // Fullwidth forms
263
- || (cp >= 0xffe0 && cp <= 0xffe6)
264
- || (cp >= 0x1f300 && cp <= 0x1f64f) // emoji
265
- || (cp >= 0x1f900 && cp <= 0x1f9ff)
266
- || (cp >= 0x20000 && cp <= 0x3fffd)
267
- ) return 2;
268
- return 1;
264
+ return termCharWidth(ch);
269
265
  }
270
266
 
271
267
  /** A shareable pool pair, so screens in one session can be compared cheaply. */
package/src/term.js CHANGED
@@ -218,51 +218,71 @@ const AMBIGUOUS = [
218
218
  [0x2103, 0x2103], [0x2105, 0x2105], [0x2109, 0x2109], [0x2113, 0x2113],
219
219
  [0x2116, 0x2116], [0x2121, 0x2122], [0x2126, 0x2126], [0x212B, 0x212B],
220
220
  [0x2153, 0x2154], [0x215B, 0x215E], [0x2160, 0x216B], [0x2170, 0x2179],
221
- [0x2189, 0x2189], [0x2190, 0x2199], [0x219A, 0x219B], [0x219E, 0x21A0],
222
- [0x21A3, 0x21A3], [0x21A6, 0x21A6], [0x21A9, 0x21AA], [0x21AE, 0x21AE],
223
- [0x21B0, 0x21B1], [0x21B3, 0x21B4], [0x21B6, 0x21B9], [0x21B8, 0x21B9],
224
- [0x21BC, 0x21BD], [0x21C0, 0x21C1], [0x21C4, 0x21C5], [0x21C7, 0x21C9],
225
- [0x21CB, 0x21CC], [0x21CE, 0x21CF], [0x21D2, 0x21D2], [0x21D4, 0x21D4],
226
- [0x21DA, 0x21DB], [0x21DD, 0x21DD], [0x21E0, 0x21E1], [0x21E4, 0x21E5],
227
- [0x21E7, 0x21E7], [0x21EA, 0x21ED], [0x21F4, 0x21F4], [0x2200, 0x2200],
228
- [0x2202, 0x2203], [0x2207, 0x2208], [0x220B, 0x220B], [0x220F, 0x220F],
229
- [0x2211, 0x2211], [0x2215, 0x2215], [0x221A, 0x221A], [0x221D, 0x2220],
230
- [0x2223, 0x2223], [0x2225, 0x2225], [0x2227, 0x222C], [0x222E, 0x222E],
231
- [0x2234, 0x2237], [0x223C, 0x223D], [0x2248, 0x2248], [0x224C, 0x224C],
232
- [0x2252, 0x2252], [0x2260, 0x2261], [0x2264, 0x2267], [0x226A, 0x226B],
233
- [0x226E, 0x226F], [0x2282, 0x2283], [0x2286, 0x2287], [0x2295, 0x2295],
234
- [0x2299, 0x2299], [0x22A5, 0x22A5], [0x22BF, 0x22BF], [0x2312, 0x2312],
235
- [0x2460, 0x24E9], [0x24EB, 0x254B], [0x2550, 0x2573], [0x2580, 0x258F],
236
- [0x2592, 0x2595], [0x25A0, 0x25A1], [0x25A3, 0x25A9], [0x25B2, 0x25B3],
237
- [0x25B6, 0x25B7], [0x25BC, 0x25BD], [0x25C0, 0x25C1], [0x25C6, 0x25C8],
238
- [0x25CB, 0x25CB], [0x25CE, 0x25D1], [0x25E2, 0x25E5], [0x25EF, 0x25EF],
239
- [0x2605, 0x2606], [0x2609, 0x2609], [0x260E, 0x260F], [0x261C, 0x261C],
240
- [0x261E, 0x261E], [0x2640, 0x2640], [0x2642, 0x2642], [0x2660, 0x2661],
241
- [0x2663, 0x2665], [0x2667, 0x266A], [0x266C, 0x266D], [0x266F, 0x266F],
242
- [0x269E, 0x269F], [0x26C6, 0x26CD], [0x26CF, 0x26D3], [0x26D5, 0x26E1],
243
- [0x26E3, 0x26E3], [0x26E8, 0x26E9], [0x26EB, 0x26F1], [0x26F4, 0x26F4],
244
- [0x26F6, 0x26F9], [0x26FB, 0x26FC], [0x26FE, 0x26FF], [0x273D, 0x273D],
245
- [0x2761, 0x2761], [0x2776, 0x277F], [0x2B56, 0x2B59], [0x3248, 0x324F],
246
- [0xE000, 0xF8FF], [0xFE00, 0xFE0F], [0xFFFD, 0xFFFD], [0x1F100, 0x1F10A],
247
- [0x1F110, 0x1F12D], [0x1F130, 0x1F169], [0x1F170, 0x1F19A],
221
+ [0x2189, 0x2189], [0x2190, 0x219B], [0x219E, 0x21A0], [0x21A3, 0x21A3],
222
+ [0x21A6, 0x21A6], [0x21A9, 0x21AA], [0x21AE, 0x21AE], [0x21B0, 0x21B1],
223
+ [0x21B3, 0x21B4], [0x21B6, 0x21B9], [0x21BC, 0x21BD], [0x21C0, 0x21C1],
224
+ [0x21C4, 0x21C5], [0x21C7, 0x21C9], [0x21CB, 0x21CC], [0x21CE, 0x21CF],
225
+ [0x21D2, 0x21D2], [0x21D4, 0x21D4], [0x21DA, 0x21DB], [0x21DD, 0x21DD],
226
+ [0x21E0, 0x21E1], [0x21E4, 0x21E5], [0x21E7, 0x21E7], [0x21EA, 0x21ED],
227
+ [0x21F4, 0x21F4], [0x2200, 0x2200], [0x2202, 0x2203], [0x2207, 0x2208],
228
+ [0x220B, 0x220B], [0x220F, 0x220F], [0x2211, 0x2211], [0x2215, 0x2215],
229
+ [0x221A, 0x221A], [0x221D, 0x2220], [0x2223, 0x2223], [0x2225, 0x2225],
230
+ [0x2227, 0x222C], [0x222E, 0x222E], [0x2234, 0x2237], [0x223C, 0x223D],
231
+ [0x2248, 0x2248], [0x224C, 0x224C], [0x2252, 0x2252], [0x2260, 0x2261],
232
+ [0x2264, 0x2267], [0x226A, 0x226B], [0x226E, 0x226F], [0x2282, 0x2283],
233
+ [0x2286, 0x2287], [0x2295, 0x2295], [0x2299, 0x2299], [0x22A5, 0x22A5],
234
+ [0x22BF, 0x22BF], [0x2312, 0x2312], [0x2460, 0x24E9], [0x24EB, 0x254B],
235
+ [0x2550, 0x2573], [0x2580, 0x258F], [0x2592, 0x2595], [0x25A0, 0x25A1],
236
+ [0x25A3, 0x25A9], [0x25B2, 0x25B3], [0x25B6, 0x25B7], [0x25BC, 0x25BD],
237
+ [0x25C0, 0x25C1], [0x25C6, 0x25C8], [0x25CB, 0x25CB], [0x25CE, 0x25D1],
238
+ [0x25E2, 0x25E5], [0x25EF, 0x25EF], [0x2605, 0x2606], [0x2609, 0x2609],
239
+ [0x260E, 0x260F], [0x261C, 0x261C], [0x261E, 0x261E], [0x2640, 0x2640],
240
+ [0x2642, 0x2642], [0x2660, 0x2661], [0x2663, 0x2665], [0x2667, 0x266A],
241
+ [0x266C, 0x266D], [0x266F, 0x266F], [0x269E, 0x269F], [0x26C6, 0x26CD],
242
+ [0x26CF, 0x26D3], [0x26D5, 0x26E1], [0x26E3, 0x26E3], [0x26E8, 0x26E9],
243
+ [0x26EB, 0x26F1], [0x26F4, 0x26F4], [0x26F6, 0x26F9], [0x26FB, 0x26FC],
244
+ [0x26FE, 0x26FF], [0x273D, 0x273D], [0x2761, 0x2761], [0x2776, 0x277F],
245
+ [0x2B56, 0x2B59], [0x3248, 0x324F], [0xE000, 0xF8FF], [0xFE00, 0xFE0F],
246
+ [0xFFFD, 0xFFFD], [0x1F100, 0x1F10A], [0x1F110, 0x1F12D], [0x1F130, 0x1F169],
247
+ [0x1F170, 0x1F19A],
248
248
  ];
249
249
 
250
- // EAW=Ambiguous code points that every terminal still draws ONE column wide.
250
+ // EAW=Ambiguous code points that a terminal still draws ONE column wide.
251
251
  //
252
- // Box drawing and block elements exist to tile: a `─` that was two columns wide could not
253
- // meet its neighbour, so terminals draw them at one regardless of locale. Unicode classes
254
- // them Ambiguous anyway, and honouring that measured every box and panel twice as wide as
255
- // the space it was given — the frames they compose came apart.
252
+ // THIS IS THE WHOLE SYMBOL RANGE, AND THAT IS THE POINT.
256
253
  //
257
- // The three typographic marks are the same story for a different reason: `…`, `·`, `•` are
258
- // used here for truncation and as separators, INSIDE single-column layouts. A truncated
259
- // title measured two columns wide overflowed the panel it was cut to fit, and the panel's
260
- // own border was then one column short on that row.
254
+ // A CJK locale makes far more code points "ambiguous" than a reader expects: every arrow,
255
+ // every box-drawing character, every geometric shape, every dingbat. In practice terminals
256
+ // draw all of them one column wide — they are used for BORDERS, BULLETS and SPINNERS, and a
257
+ // glyph that is a border cannot be two columns wide or it does not meet its neighbour.
258
+ //
259
+ // What IS two columns wide is the thing the Unicode tables and the terminals agree on:
260
+ // ideographs and full-width punctuation, which `WIDE` covers.
261
+ //
262
+ // Getting this wrong is not subtle. Measured on a Chinese terminal:
263
+ //
264
+ // ● U+25CF measured 2, drawn 1 — every tool row one column too wide
265
+ // ─ U+2500 measured 2, drawn 1 — every panel and table frame
266
+ // … U+2026 measured 2, drawn 1 — every truncated title
267
+ //
268
+ // A row that measures wider than it draws pushes the frame's last column off the screen,
269
+ // and that is the column the scrollbar lives in: the rail came out broken into pieces, and
270
+ // the extra column shifted the diff's write range so a rewritten row could repeat a
271
+ // character. `● Using Screenshot` came out `● Using SScreenshot`.
261
272
  const AMBIGUOUS_ALWAYS_NARROW = [
262
- [0x00B7, 0x00B7], // ·
263
- [0x2022, 0x2022], // •
264
- [0x2026, 0x2026], // …
265
- [0x2500, 0x259F], // box drawing and block elements
273
+ [0x00A7, 0x00A7], // §
274
+ [0x00B0, 0x00B1], // ° ±
275
+ [0x00B6, 0x00B7], // ¶ ·
276
+ [0x00D7, 0x00D7], // ×
277
+ [0x00F7, 0x00F7], // ÷
278
+ [0x2010, 0x2027], // hyphens, quotes, ellipsis, bullet
279
+ [0x2030, 0x205E], // per-mille, primes, primes-like marks
280
+ [0x2190, 0x21FF], // arrows, including `↳` and `↑↓`
281
+ [0x2200, 0x22FF], // mathematical operators
282
+ [0x2300, 0x23FF], // technical marks
283
+ [0x2500, 0x25FF], // box drawing, block elements, geometric shapes (`● ○ ◐ ▪`)
284
+ [0x2600, 0x27BF], // misc symbols and dingbats (`✓ ✗ ★ ☆`)
285
+ [0x2B00, 0x2BFF], // additional arrows and shapes
266
286
  ];
267
287
 
268
288
  /**
package/src/tui.js CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  C, TRUECOLOR, blockCursor, showCursor, hideCursor, alternateScreen, clearScreen, clearAndSetBg, setTheme, setLightBackground, currentTheme, THEME_NAMES, THEME_LABELS, isLightTheme, hasTheme, lerpColor, bgRgb,
22
22
  } from './colors.js';
23
23
  import { copyText, readText, warmClipboard, readClipboardContentAsync, readClipboardTextOnly, imageUrlFromClipboardText, cleanupPastedImages, stopClipboardHelper } from './clipboard.js';
24
+ import { Dictation } from './voice.js';
24
25
  import { visualWidth, estimateTokens, estimateTokensFloat, estimateMessagesTokens, estimateMessageTokens, messageTokens, expandTabs } from './term.js';
25
26
  // The extracted modules are pulled in as NAMESPACES and unpacked into local bindings. That way adding a helper to
26
27
  // one of them is a one-line change there, rather than an edit to a long named-import list that silently leaves a
@@ -114,7 +115,7 @@ export {
114
115
 
115
116
  import { planRows, bgTaskRows } from './rows-plan-bg.js';
116
117
  import { compactionRows, thinkingRows } from './rows-status.js';
117
- import { toolResultRows } from './rows-tool-result.js';
118
+ import { toolResultRows, TOOL_MARKER_PREFIX, TOOL_MARKER_INDENT } from './rows-tool-result.js';
118
119
 
119
120
  import * as fmt from './format.js';
120
121
 
@@ -1536,7 +1537,7 @@ function messageLines(msg, width, workspace, expanded, spin, pulseStart, rawMode
1536
1537
  // the one unreadable thing on the screen while the finished result's arrow (rows-tool-result.js, which
1537
1538
  // does use `C.marker`) was bright. Same glyph, two colours, depending on whether the command had
1538
1539
  // finished.
1539
- const marker = firstLive ? C.marker + '↳ ' + C.reset : ' ';
1540
+ const marker = firstLive ? C.marker + TOOL_MARKER_PREFIX + C.reset : TOOL_MARKER_INDENT;
1540
1541
  const rowW = bodyW;
1541
1542
  out.push({ text: C.termBg + fitAnsi(surfaced, rowW) + C.bgReset, ind: marker, raw: true });
1542
1543
  }
@@ -1616,15 +1617,15 @@ function messageLines(msg, width, workspace, expanded, spin, pulseStart, rawMode
1616
1617
  // The comment state travels between the rows, so a block comment that opens on one line and closes on
1617
1618
  // the next stays grey all the way down.
1618
1619
  let writeInComment = false;
1619
- // THE MARKER AND THE INDENT ARE PADDED TO ONE WIDTH.
1620
- //
1621
- // `↳` is East Asian Ambiguous: one column on an English terminal, two on a Chinese
1622
- // one. A fixed `'↳ '` beside a fixed `' '` therefore disagreed by a column on a CJK
1623
- // machine, and every continuation row started a column early — a ragged gutter that
1624
- // only showed up there. Both are built from the marker's own measured width instead,
1625
- // so the block is square wherever it is drawn.
1626
- const markerRaw = '↳ ';
1627
- const contRaw = ' '.repeat(Math.max(1, visualCol(markerRaw)));
1620
+ // THE MARKER AND THE INDENT ARE PADDED TO ONE WIDTH.
1621
+ //
1622
+ // `↳` is East Asian Ambiguous: one column on an English terminal, two on a Chinese
1623
+ // one. A fixed `'↳ '` beside a fixed `' '` therefore disagreed by a column on a CJK
1624
+ // machine, and every continuation row started a column early — a ragged gutter that
1625
+ // only showed up there. Both are built from the marker's own measured width instead,
1626
+ // so the block is square wherever it is drawn.
1627
+ const markerRaw = TOOL_MARKER_PREFIX;
1628
+ const contRaw = TOOL_MARKER_INDENT;
1628
1629
  lines.slice(0, MAX).forEach((ln, i) => {
1629
1630
  const num = String(i + 1).padStart(wNum);
1630
1631
  // A LINE LONGER THAN THE PANEL IS CUT, not wrapped. `raw: true` means the renderer does not wrap it for us,
@@ -5586,10 +5587,10 @@ const queueH = takeover ? 0 : queuePanelHeight(state);
5586
5587
  // The text goes through the i18n table so the badge reads the same in every
5587
5588
  // language. The English form is kept in the table for the default language.
5588
5589
  if (bashTasks > 0) {
5589
- pushPart(col(tr('status.tasksBash', '[{n} task(s) running]', { n: bashTasks })), { kind: 'statusTasks' });
5590
+ pushPart(col(tr('status.tasksBash', '[{n} task(s) running]', { n: bashTasks }), C.cyan), { kind: 'statusTasks' });
5590
5591
  }
5591
5592
  if (agentTasks > 0) {
5592
- pushPart(col(tr('status.tasksAgent', '[{n} agent(s) running]', { n: agentTasks })), { kind: 'statusTasks' });
5593
+ pushPart(col(tr('status.tasksAgent', '[{n} agent(s) running]', { n: agentTasks }), C.spring), { kind: 'statusTasks' });
5593
5594
  }
5594
5595
  }
5595
5596
  if (state.slCwd !== false && cwd) parts.push(col(cwd, C.gray));
@@ -5628,8 +5629,21 @@ const queueH = takeover ? 0 : queuePanelHeight(state);
5628
5629
  // AND the model must have prices (its own entry or the models.dev catalog). Either one
5629
5630
  // missing would mean inventing the number, so it is omitted rather than shown as `0$`,
5630
5631
  // which reads as "this was free".
5631
- const costSeg = state._costText ? `${state._costText} cost | ` : '';
5632
- const countsRight = col(`${costSeg}${state.rounds} turn${state.rounds === 1 ? '' : 's'} | ${state.steps} step${state.steps === 1 ? '' : 's'} | ${Math.round(state.tokRate)} tok/s`, C.white);
5632
+ const costSeg = state._costText ? `${state._costText} ${uiText('cost')} | ` : '';
5633
+ // THE TALLIES ARE COUNTED NOUNS, so they go through `tr` rather than `uiText`: a template
5634
+ // can sit the number where the language wants it, and the plural only exists in English.
5635
+ const countsRight = col(
5636
+ `${costSeg}`
5637
+ + (state.rounds === 1
5638
+ ? tr('status.turnsOne', '{n} turn', { n: state.rounds })
5639
+ : tr('status.turns', '{n} turns', { n: state.rounds }))
5640
+ + ' | '
5641
+ + (state.steps === 1
5642
+ ? tr('status.stepsOne', '{n} step', { n: state.steps })
5643
+ : tr('status.steps', '{n} steps', { n: state.steps }))
5644
+ + ` | ${Math.round(state.tokRate)} tok/s`,
5645
+ C.white,
5646
+ );
5633
5647
  const statusRight = countsRight;
5634
5648
  // Plugin TUI widgets render into the status bar's right side.
5635
5649
  try { const wid = renderWidgets(); if (wid) statusRight && (statusRight += ' '); if (wid) statusRight = (statusRight || '') + wid; } catch {}
@@ -11543,7 +11557,7 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
11543
11557
  const want = a === 'on' ? true : a === 'off' ? false : !(cfg.promptCache !== false);
11544
11558
  cfg.promptCache = want;
11545
11559
  try { setConfigString('prompt_cache', want ? 'true' : 'false'); } catch { /* best-effort persist */ }
11546
- app(`Prompt caching: ${want ? 'ON' : 'OFF'}`);
11560
+ app(`${uiText('Prompt caching')}: ${want ? uiText('ON') : uiText('OFF')}`);
11547
11561
  sayPanel(want
11548
11562
  ? 'The stable prefix (tools + system + conversation head) is marked cacheable.\n'
11549
11563
  + 'Providers bill cached input at a fraction of the normal rate. Effective\n'
@@ -11782,6 +11796,9 @@ function setPermission(state, mode) { state.mode = mode; }
11782
11796
  // are a long switch. The list is the REACHABLE set, so a plugin is warned about the ones a
11783
11797
  // user would notice losing; the switch's internal cursor keys are deliberately absent,
11784
11798
  // because a plugin claiming those is not something to guard against.
11799
+ // ---- speech input -----------------------------------------------------------
11800
+
11801
+
11785
11802
  const BUILTIN_KEYS = new Set([
11786
11803
  'c-c', // interrupt / quit
11787
11804
  'c-b', // background a running Bash command
@@ -11797,6 +11814,7 @@ const BUILTIN_KEYS = new Set([
11797
11814
  'c-x', // (reserved; Ctrl+Shift+X is paste-and-run)
11798
11815
  'c-s-c', // copy the selection or last answer
11799
11816
  'c-s-v', // paste as a bracketed paste
11817
+ 'c-s-m', // hold to dictate into the composer
11800
11818
  'c-up', 'c-down', // scroll the output area
11801
11819
  'escape',
11802
11820
  'tab', 's-tab',
@@ -12326,7 +12344,16 @@ export function tokenize(str) {
12326
12344
  // movement speeds up as if the user were holding it. The event type says which it is: `repeat` marks the
12327
12345
  // terminal's own auto-repeat, `release` means the key came back up, `press` is a real hit.
12328
12346
  const eventType = ku[3] ? parseInt(ku[3], 10) : 1;
12329
- if (eventType === 3) { i += ku[0].length; continue; }
12347
+ // THE ONE RELEASE THAT IS REPORTED. Dictation is a HOLD: the key going down opens the
12348
+ // microphone and letting it up closes it, so that release has to reach the handler.
12349
+ // Every other key drops its release here, because a second event per press is how a
12350
+ // menu opens twice from one tap.
12351
+ if (eventType === 3) {
12352
+ const ch = ctrlLetter(ku[1] ? parseInt(ku[1], 10) : 0);
12353
+ if (ctrl && shift && ch === 'm') out.push({ key: 'c-s-m-up' });
12354
+ i += ku[0].length;
12355
+ continue;
12356
+ }
12330
12357
  // `held` is true only for the terminal's auto-repeat. A caller that accelerates on a held key uses it; two
12331
12358
  // quick taps arrive as two presses and stay two steps.
12332
12359
  const held = eventType === 2;
@@ -12367,7 +12394,12 @@ export function tokenize(str) {
12367
12394
  // made Ctrl+Shift+C indistinguishable from Ctrl+C, so "copy" ran the
12368
12395
  // interrupt / exit-confirmation path instead.
12369
12396
  const ch = ctrlLetter(cp);
12370
- if (ch) { out.push({ key: 'c-s-' + ch }); i += ku[0].length; continue; }
12397
+ // `held` TRAVELS WITH THE TOKEN. A key held down arrives once as a press and then
12398
+ // as the terminal's own auto-repeat; without the flag every repeat looks like a
12399
+ // fresh press, and a handler that starts something (dictation opens a microphone)
12400
+ // does it again on every repeat — which is the notice that fills the screen while
12401
+ // the key is held.
12402
+ if (ch) { out.push(held ? { key: 'c-s-' + ch, held: true } : { key: 'c-s-' + ch }); i += ku[0].length; continue; }
12371
12403
  }
12372
12404
  if (ctrl && !alt) {
12373
12405
  const ch = ctrlLetter(cp);
@@ -14181,6 +14213,21 @@ export async function startTUI(opts) {
14181
14213
  // consumer follow (see `replaceSession`).
14182
14214
  state.session = session;
14183
14215
 
14216
+ // SPEECH INPUT, BUILT ON FIRST USE. `Dictation` owns the microphone and the recogniser, so
14217
+ // the key handler only has to say "down" and "up". A session that never dictates pays
14218
+ // nothing for the engine lookup or the temporary directory.
14219
+ let voice = null;
14220
+ const ensureVoice = () => {
14221
+ if (voice) return voice;
14222
+ // The recogniser is told the language the interface is already in: it is far more
14223
+ // accurate when it expects the right one, and the user has expressed a preference.
14224
+ voice = new Dictation({ lang: cfg.lang === 'zh' ? 'zh-CN' : 'en-US' });
14225
+ return voice;
14226
+ };
14227
+ // The key handler is module-level and cannot see this closure, so it reaches the object
14228
+ // through the host it already has.
14229
+ state._ensureVoice = ensureVoice;
14230
+
14184
14231
  cfg.effort = state.reasoning ? state.effort : '';
14185
14232
  // Price the session's restored tokens against the model it is about to use, so
14186
14233
  // /cost and the status badge are right before the first new request.
@@ -14765,6 +14812,16 @@ export async function startTUI(opts) {
14765
14812
  tail: JSON.stringify(out.slice(-80)),
14766
14813
  newlines: (out.match(/\n/g) || []).length,
14767
14814
  height: dims().rows,
14815
+ // EACH ROW, AS THE TERMINAL WILL RECEIVE IT.
14816
+ //
14817
+ // A duplicated or misplaced character on screen can only be explained by what was
14818
+ // actually written, so the trace carries the full text of every row and the
14819
+ // character in its LAST column — the rail lives there, and a row whose last
14820
+ // column is not a rail glyph is a row the rail lost.
14821
+ rowText: (frame.lines || []).map((l, y) => {
14822
+ const plain = String(l).replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '');
14823
+ return `${y}:${plain.length ? plain[plain.length - 1] : ' '}:${plain}`;
14824
+ }),
14768
14825
  }) + '\n');
14769
14826
  } catch { /* tracing must never break a paint */ }
14770
14827
  }
@@ -18295,6 +18352,74 @@ export async function startTUI(opts) {
18295
18352
  return;
18296
18353
  }
18297
18354
 
18355
+ if (t.key === 'c-s-m' && t.held) return; // the terminal's auto-repeat, not a new press
18356
+ if (t.key === 'c-s-m') {
18357
+ // Ctrl+Shift+M, HELD: the key going down opens the microphone and letting it up
18358
+ // closes it. A hold rather than a tap because the user knows when they have
18359
+ // finished speaking, and a recogniser guessing at the pause either cuts them off or
18360
+ // waits.
18361
+ //
18362
+ // The text lands AT THE CARET, not over the draft. Dictating a correction into a
18363
+ // half-written message is the common case, and replacing what is already there is
18364
+ // the one thing a dictation key must never do.
18365
+ const voice = state._ensureVoice ? state._ensureVoice() : null;
18366
+ if (!voice || !voice.available) {
18367
+ notice(uiText('Speech input is unavailable'), 'warn');
18368
+ const hint = (voice && voice.hint) || uiText('No speech engine was found.');
18369
+ for (const line of String(hint).split('\n')) notice(line, 'info');
18370
+ return;
18371
+ }
18372
+ // Remember where the caret was when the key went down: the user may move it while
18373
+ // speaking, and the words belong where they started.
18374
+ state._voiceCaret = Math.max(0, Math.min(state.input.length, state.caret || 0));
18375
+ state._voiceBusy = true;
18376
+ notice(uiText('Listening… release to insert'), 'info');
18377
+ renderFrame();
18378
+ void (async () => {
18379
+ const started = await voice.start();
18380
+ if (!started.ok) {
18381
+ state._voiceBusy = false;
18382
+ notice(started.error || tr('voice.failed', 'Speech input failed'), 'warn');
18383
+ if (started.hint) for (const line of String(started.hint).split('\n')) notice(line, 'info');
18384
+ renderFrame();
18385
+ }
18386
+ })();
18387
+ return;
18388
+ }
18389
+
18390
+ if (t.key === 'c-s-m-up') {
18391
+ // The key came up: stop the microphone and insert what it heard.
18392
+ if (!state._voiceBusy) return;
18393
+ const voice = state._ensureVoice ? state._ensureVoice() : null;
18394
+ if (!voice) return;
18395
+ void (async () => {
18396
+ try {
18397
+ const r = await voice.stop();
18398
+ if (r.ok && r.text) {
18399
+ const at = Math.max(0, Math.min(state.input.length, state._voiceCaret || 0));
18400
+ // A space only when the insertion point is not already at one, so a dictated
18401
+ // word joins the sentence instead of starting a new one.
18402
+ const glue = at > 0 && !/\s$/.test(state.input.slice(0, at)) ? ' ' : '';
18403
+ const add = glue + r.text;
18404
+ state.input = state.input.slice(0, at) + add + state.input.slice(at);
18405
+ state.caret = at + add.length;
18406
+ notice(tr('voice.inserted', 'Inserted {n} characters', { n: r.text.length }), 'info');
18407
+ } else {
18408
+ // The HINT is the point: "speech failed" leaves the user with nowhere to go.
18409
+ notice(r.error || tr('voice.failed', 'Speech input failed'), 'warn');
18410
+ if (r.hint) for (const line of String(r.hint).split('\n')) notice(line, 'info');
18411
+ }
18412
+ } catch (e) {
18413
+ notice(tr('voice.failed', 'Speech input failed') + ': ' + ((e && e.message) || e), 'warn');
18414
+ } finally {
18415
+ state._voiceBusy = false;
18416
+ state._voiceCaret = 0;
18417
+ renderFrame();
18418
+ }
18419
+ })();
18420
+ return;
18421
+ }
18422
+
18298
18423
  if (t.key === 'c-v') {
18299
18424
  // Ctrl+V: paste. Many terminals translate Ctrl+V in raw mode to the raw
18300
18425
  // control byte 0x16 (not a bracketed-paste sequence), which tokenize()
package/src/voice.js ADDED
@@ -0,0 +1,575 @@
1
+ // SPEECH INPUT: dictate into the composer.
2
+ //
3
+ // WHAT EACH PLATFORM ACTUALLY HAS
4
+ // -------------------------------
5
+ // Node has no microphone API and no speech model, so this module uses what the SYSTEM
6
+ // already ships where it can, and falls back to an installed tool where it cannot:
7
+ //
8
+ // Windows `Windows.Media.SpeechRecognition` — shipped with Windows 10/11, works offline,
9
+ // nothing to install. Reached through PowerShell's WinRT projection, because a
10
+ // native addon would be a dependency and a C# block compiled at first use is not.
11
+ // macOS `Speech.framework` (SFSpeechRecognizer) — shipped with macOS 10.15+, offline for
12
+ // on-device locales. Reached by running a Swift snippet, which needs the Command
13
+ // Line Tools (`xcode-select --install`, not a package).
14
+ // Linux no system recogniser exists, so `whisper-cli` is used when it is on PATH and the
15
+ // hint names the install.
16
+ //
17
+ // A `voice_command` in config.toml overrides all of it: whatever it prints is the text.
18
+ //
19
+ // ONE CONTRACT PER BACKEND
20
+ // ------------------------
21
+ // Every backend is a child process printing one line — `TEXT <words>`, `EMPTY`, or
22
+ // `FAIL <why>`. Keeping it that small is what makes three platforms one implementation: the
23
+ // platform-specific part is a script, and the deciding is shared and testable without a
24
+ // microphone.
25
+
26
+ import fs from 'node:fs';
27
+ import os from 'node:os';
28
+ import path from 'node:path';
29
+ import cp from 'node:child_process';
30
+
31
+ /** How long one dictation may take, end to end. */
32
+ export const DEFAULT_TIMEOUT_MS = 30_000;
33
+
34
+ /**
35
+ * The language to dictate.
36
+ *
37
+ * A recogniser told what to expect is far more accurate, and the interface already knows
38
+ * which language the user reads.
39
+ */
40
+ export function voiceLanguage(env = process.env, uiLang = 'en') {
41
+ const raw = String(env.HNCODE_VOICE_LANG || '').trim();
42
+ if (raw) return raw;
43
+ return uiLang === 'zh' ? 'zh-CN' : 'en-US';
44
+ }
45
+
46
+ /** `which`, without a shell, so a quoted path cannot become a command. */
47
+ export function which(name, env = process.env, platform = process.platform) {
48
+ const exts = platform === 'win32'
49
+ ? String(env.PATHEXT || '.EXE;.CMD;.BAT').split(';').filter(Boolean)
50
+ : [''];
51
+ for (const dir of String(env.PATH || '').split(path.delimiter)) {
52
+ if (!dir) continue;
53
+ for (const ext of exts) {
54
+ const full = path.join(dir, name + ext);
55
+ try { if (fs.statSync(full).isFile()) return full; } catch { /* not here */ }
56
+ }
57
+ }
58
+ return null;
59
+ }
60
+
61
+ /**
62
+ * What this machine can use, best first.
63
+ *
64
+ * The platform's own recogniser comes first: no install, no model download, no network.
65
+ */
66
+ export function backends({ platform = process.platform, env = process.env } = {}) {
67
+ const list = [];
68
+ const cmd = String(env.HNCODE_VOICE_COMMAND || '').trim();
69
+ if (cmd) list.push({ id: 'command', command: cmd });
70
+ if (platform === 'win32') list.push({ id: 'winrt' });
71
+ else if (platform === 'darwin') list.push({ id: 'avspeech' });
72
+ // `whisper-cli` is the current name, `whisper` the older one. NOT `main`: whisper.cpp's
73
+ // build output is called `main` on some systems, but so is `main.CPL` in the Windows system
74
+ // directory, and matching that would hand a control-panel applet a WAV file.
75
+ for (const name of ['whisper-cli', 'whisper']) {
76
+ const hit = which(name, env, platform);
77
+ if (hit) { list.push({ id: 'whisper', command: hit }); break; }
78
+ }
79
+ return list;
80
+ }
81
+
82
+ /**
83
+ * What the user has to do to make this work.
84
+ *
85
+ * A message that names the next step. "Speech recognition is unavailable" leaves a person
86
+ * with nowhere to go, and every failure here has a specific fix.
87
+ */
88
+ export function setupHint(platform = process.platform) {
89
+ if (platform === 'win32') {
90
+ return [
91
+ 'Windows has speech recognition built in — two settings turn it on:',
92
+ ' Settings → Privacy & security → Speech → "Online speech recognition": on',
93
+ ' Settings → Privacy & security → Microphone → desktop apps allowed: on',
94
+ 'Nothing to install. Press the key again once both are on.',
95
+ ].join('\n');
96
+ }
97
+ if (platform === 'darwin') {
98
+ return [
99
+ 'macOS has its own recogniser; it needs two permissions the first time:',
100
+ ' System Settings → Privacy & Security → Microphone → allow your terminal',
101
+ ' System Settings → Privacy & Security → Speech Recognition → allow your terminal',
102
+ 'If dictation does not start, install the command line tools once:',
103
+ ' xcode-select --install',
104
+ ].join('\n');
105
+ }
106
+ return [
107
+ 'Linux has no built-in recogniser, so one has to be installed:',
108
+ ' sudo apt install whisper.cpp (or build whisper.cpp for whisper-cli)',
109
+ 'Or point voice_command in config.toml at any program that prints a transcription.',
110
+ ].join('\n');
111
+ }
112
+
113
+ // ---- the shared half --------------------------------------------------------
114
+
115
+ /**
116
+ * Read a backend's one-line answer.
117
+ *
118
+ * `TEXT …` / `EMPTY` / `FAIL …`, so every platform's script is interchangeable and this is
119
+ * the only place that knows the shapes.
120
+ */
121
+ export function readAnswer(stdout, stderr = '') {
122
+ const text = String(stdout || '').trim();
123
+ const line = text.split(/\r?\n/).reverse().find((l) => /^(TEXT|EMPTY|FAIL)\b/.test(l)) || '';
124
+ if (line.startsWith('TEXT ')) return { ok: true, text: cleanTranscript(line.slice(5)) };
125
+ if (line === 'EMPTY') return { ok: false, error: 'nothing was recognised' };
126
+ if (line.startsWith('FAIL ')) return { ok: false, error: line.slice(5).trim() };
127
+ const detail = String(stderr || text).trim();
128
+ return { ok: false, error: detail || 'the recogniser said nothing' };
129
+ }
130
+
131
+ /** Strip the timestamps and line breaks a recogniser adds around the words. */
132
+ export function cleanTranscript(raw) {
133
+ return String(raw || '')
134
+ .split(/\r?\n/)
135
+ .map((l) => l.replace(/^\[[\d:.\s>-]+\]\s*/, ''))
136
+ .join(' ')
137
+ .replace(/\s+/g, ' ')
138
+ .trim();
139
+ }
140
+
141
+ /**
142
+ * Turn a raw failure into something the user can act on.
143
+ *
144
+ * The ones that actually happen are permissions, and they arrive as opaque OS messages.
145
+ * Mapping them here is the difference between "failed" and "go turn this on".
146
+ */
147
+ export function explainFailure(error, platform = process.platform) {
148
+ const why = String(error || '');
149
+ if (/privacy policy/i.test(why)) {
150
+ return {
151
+ error: 'the Windows speech privacy policy has not been accepted',
152
+ hint: 'Settings → Privacy & security → Speech → turn on "Online speech recognition", then try again.',
153
+ };
154
+ }
155
+ if (/microphone|audio device|no such device|SetInputToDefaultAudioDevice|no input/i.test(why)) {
156
+ return {
157
+ error: 'no microphone was found',
158
+ hint: platform === 'win32'
159
+ ? 'Plug in or enable an input device: Settings → System → Sound → Input.'
160
+ : 'Check that an input device is connected, and that your terminal may use it.',
161
+ };
162
+ }
163
+ if (/not authori[sz]ed|denied|AVAudioSession|SFSpeechRecognizer|permission/i.test(why)) {
164
+ return { error: 'speech recognition was not authorised', hint: setupHint(platform) };
165
+ }
166
+ return { error: why || 'speech recognition failed', hint: setupHint(platform) };
167
+ }
168
+
169
+ // ---- recording --------------------------------------------------------------
170
+
171
+ /**
172
+ * A recording, as a process that can be stopped at any moment.
173
+ *
174
+ * HOLD-TO-TALK NEEDS THIS SHAPE. The alternative is a recogniser that decides when the
175
+ * speaker has finished, and a key that is let go has to mean "stop right now" — so the audio
176
+ * is captured into a file by a recorder we own, and transcription runs afterwards on
177
+ * whatever was captured. That also makes one recogniser serve every platform, because what
178
+ * arrives is a WAV.
179
+ *
180
+ * const rec = new Recorder({ platform });
181
+ * await rec.start(); // key down
182
+ * const wav = await rec.stop(); // key up
183
+ */
184
+ export class Recorder {
185
+ constructor(opts = {}) {
186
+ this.platform = opts.platform || process.platform;
187
+ this.env = opts.env || process.env;
188
+ this.timeoutMs = opts.maxMs || 120_000;
189
+ this.spawn = opts.spawn || cp.spawn;
190
+ this.recorders = opts.recorders || recordersFor(this.platform, this.env);
191
+ this.child = null;
192
+ this.dir = null;
193
+ this.wav = null;
194
+ this.error = '';
195
+ }
196
+
197
+ get available() {
198
+ return this.recorders.length > 0;
199
+ }
200
+
201
+ get hint() {
202
+ return captureHint(this.platform);
203
+ }
204
+
205
+ /** Start capturing. Resolves once the recorder is running. */
206
+ async start() {
207
+ if (this.child) return { ok: false, error: 'already recording' };
208
+ const rec = this.recorders.find((r) => r.id !== 'winrt-capture') || this.recorders[0];
209
+ if (!rec) return { ok: false, error: 'no audio recorder on this system', hint: captureHint(this.platform) };
210
+
211
+ this.dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hncode-voice-'));
212
+ this.wav = path.join(this.dir, 'speech.wav');
213
+
214
+ if (rec.id === 'winrt-capture') {
215
+ // No command-line recorder on this machine: the system API writes the file instead.
216
+ return this._startWinRT(this.wav);
217
+ }
218
+
219
+ try {
220
+ this.child = this.spawn(rec.command, rec.args(this.wav), {
221
+ windowsHide: true,
222
+ stdio: ['ignore', 'ignore', 'pipe'],
223
+ });
224
+ } catch (e) {
225
+ return { ok: false, error: e.message, hint: captureHint(this.platform) };
226
+ }
227
+ if (this.child.stderr) this.child.stderr.on('data', (d) => { this.error += d; });
228
+ this.child.on('error', (e) => { this.error += e.message; });
229
+
230
+ // A recorder that dies immediately means the microphone is not there; say so now rather
231
+ // than after the user has finished a sentence nobody heard.
232
+ const early = await new Promise((resolve) => {
233
+ const t = setTimeout(() => resolve({ ok: true }), 700);
234
+ this.child.once('exit', (code) => {
235
+ clearTimeout(t);
236
+ resolve(code === 0 ? { ok: true } : { ok: false, error: this.error.trim() || 'the recorder could not start' });
237
+ });
238
+ });
239
+ if (!early.ok) {
240
+ this._cleanup();
241
+ return { ok: false, error: early.error, hint: captureHint(this.platform) };
242
+ }
243
+ return { ok: true };
244
+ }
245
+
246
+ /**
247
+ * Stop capturing and return the WAV path.
248
+ *
249
+ * The recorder is killed rather than asked to finish: `sox`, `arecord` and `ffmpeg` all
250
+ * write their trailer on SIGTERM, which is what makes the file readable afterwards, and
251
+ * none of them has a portable "stop when the speaker pauses".
252
+ */
253
+ async stop() {
254
+ if (!this.wav) return { ok: false, error: 'not recording' };
255
+ if (this._winrt) return this._stopWinRT();
256
+
257
+ const child = this.child;
258
+ if (child) {
259
+ await new Promise((resolve) => {
260
+ let settled = false;
261
+ const done = () => { if (!settled) { settled = true; resolve(); } };
262
+ child.once('exit', done);
263
+ try { child.kill('SIGTERM'); } catch { done(); }
264
+ setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* gone */ } done(); }, 1500);
265
+ });
266
+ }
267
+ this.child = null;
268
+
269
+ const size = fileSize(this.wav);
270
+ // 44 bytes is a WAV header with no samples: the recorder opened and captured nothing.
271
+ if (size <= 44) {
272
+ this._cleanup();
273
+ return { ok: false, error: this.error.trim() || 'the microphone captured no audio' };
274
+ }
275
+ return { ok: true, wavPath: this.wav };
276
+ }
277
+
278
+ /** Delete the temporary directory. Safe after `stop()` has been read. */
279
+ cleanup() { this._cleanup(); }
280
+
281
+ _cleanup() {
282
+ if (!this.dir) return;
283
+ try { fs.rmSync(this.dir, { recursive: true, force: true }); } catch { /* best effort */ }
284
+ this.dir = null;
285
+ }
286
+
287
+ async _startWinRT(wavPath) {
288
+ this._winrt = { wavPath, stopped: false };
289
+ return { ok: true };
290
+ }
291
+
292
+ /**
293
+ * Windows capture, done on demand.
294
+ *
295
+ * The recording is a PowerShell script that captures for a MAXIMUM window; stopping early
296
+ * is not available through `AudioGraph` once it has started, so the window is the bound and
297
+ * the key release simply ends it sooner than the maximum. The script writes as it goes, so
298
+ * the bytes captured up to the kill are the bytes transcribed.
299
+ */
300
+ async _stopWinRT() {
301
+ const { wavPath } = this._winrt;
302
+ this._winrt = null;
303
+ return { ok: false, error: 'WinRT capture is not wired yet', hint: captureHint('win32') };
304
+ }
305
+ }
306
+
307
+ function fileSize(p) {
308
+ try { return fs.statSync(p).size; } catch { return 0; }
309
+ }
310
+
311
+ /**
312
+ * The recorders each platform already has.
313
+ *
314
+ * All SYSTEM TOOLS — a command-line program that ships with the OS or with a desktop's audio
315
+ * stack. None is a speech engine and none is a package this project would add.
316
+ */
317
+ export function recordersFor(platform = process.platform, env = process.env) {
318
+ const list = [];
319
+ const rec = which('rec', env, platform) || which('sox', env, platform);
320
+ if (rec) {
321
+ list.push({ id: 'sox', command: rec, args: (wav) => ['-q', '-d', '-r', '16000', '-c', '1', '-b', '16', wav] });
322
+ }
323
+ const arecord = which('arecord', env, platform);
324
+ if (arecord) {
325
+ list.push({ id: 'arecord', command: arecord, args: (wav) => ['-q', '-f', 'S16_LE', '-r', '16000', '-c', '1', '-t', 'wav', wav] });
326
+ }
327
+ const ff = which('ffmpeg', env, platform);
328
+ if (ff) {
329
+ const input = platform === 'win32' ? ['-f', 'dshow', '-i', 'audio=default']
330
+ : platform === 'darwin' ? ['-f', 'avfoundation', '-i', ':0']
331
+ : ['-f', 'alsa', '-i', 'default'];
332
+ list.push({
333
+ id: 'ffmpeg',
334
+ command: ff,
335
+ args: (wav) => ['-hide_banner', '-loglevel', 'error', '-y', ...input, '-ar', '16000', '-ac', '1', wav],
336
+ });
337
+ }
338
+ if (platform === 'win32') list.push({ id: 'winrt-capture' });
339
+ return list;
340
+ }
341
+
342
+ function captureHint(platform = process.platform) {
343
+ if (platform === 'win32') {
344
+ return 'Windows has no command-line recorder. Install sox (scoop install sox) or ffmpeg, '
345
+ + 'and allow the microphone for desktop apps: Settings → Privacy & security → Microphone.';
346
+ }
347
+ if (platform === 'darwin') return 'afrecord ships with macOS; if it is missing, install sox (brew install sox).';
348
+ return 'Install a recorder: sudo apt install alsa-utils (arecord) or sox.';
349
+ }
350
+
351
+ // ---- transcription ----------------------------------------------------------
352
+
353
+ /**
354
+ * One interface over whichever recogniser is available.
355
+ *
356
+ * WHICH OS CAPTURED THE AUDIO SAYS NOTHING ABOUT WHICH ENGINE TRANSCRIBES IT, and writing a
357
+ * recogniser per platform would be three copies of one job with three sets of bugs. Capture
358
+ * is per-platform and produces a WAV; this class is the only thing that turns a WAV into
359
+ * words.
360
+ *
361
+ * Engines, best first:
362
+ * 'local' whisper.cpp on PATH — offline, nothing leaves the machine
363
+ * 'openai' the audio transcription API — no install, needs a key, uploads the audio
364
+ * 'command' any program that prints a transcription — the escape hatch
365
+ */
366
+ export class Transcriber {
367
+ constructor(opts = {}) {
368
+ this.engine = opts.engine || detectEngine({ env: opts.env || process.env, platform: opts.platform });
369
+ this.lang = opts.lang || 'en-US';
370
+ this.timeoutMs = opts.timeoutMs || DEFAULT_TIMEOUT_MS;
371
+ this.run = opts.run || runToEnd;
372
+ this.env = opts.env || process.env;
373
+ }
374
+
375
+ get available() { return !!this.engine; }
376
+
377
+ get hint() { return this.engine ? '' : engineHint(this.env); }
378
+
379
+ async transcribe(wavPath, opts = {}) {
380
+ if (!this.engine) return { ok: false, error: 'no transcription engine', hint: engineHint(this.env) };
381
+ const lang = opts.lang || this.lang;
382
+ const e = this.engine;
383
+ if (e.id === 'local') return transcribeLocal(e.command, wavPath, { lang, timeoutMs: this.timeoutMs, run: this.run });
384
+ if (e.id === 'openai') return transcribeOpenAI(e, wavPath, { lang, timeoutMs: this.timeoutMs });
385
+ return transcribeCommand(e.command, wavPath, { timeoutMs: this.timeoutMs, run: this.run, env: this.env });
386
+ }
387
+ }
388
+
389
+ /**
390
+ * Which engine this machine can use, best first.
391
+ *
392
+ * `local` before `openai` on principle: a recording of someone's voice should not leave the
393
+ * machine unless they chose that. The HTTP engine is offered because it needs no install, and
394
+ * is only used when a key is present.
395
+ */
396
+ export function detectEngine({ env = process.env, platform = process.platform } = {}) {
397
+ const cmd = String(env.HNCODE_VOICE_COMMAND || '').trim();
398
+ if (cmd) return { id: 'command', command: cmd };
399
+ // `whisper-cli` is the current name, `whisper` the older one. NOT `main`: whisper.cpp's
400
+ // build output is called `main` on some systems, but so is `main.CPL` in the Windows system
401
+ // directory, and matching that would hand a control-panel applet a WAV file.
402
+ for (const name of ['whisper-cli', 'whisper']) {
403
+ const hit = which(name, env, platform);
404
+ if (hit) return { id: 'local', command: hit };
405
+ }
406
+ const key = String(env.HNCODE_VOICE_API_KEY || env.OPENAI_API_KEY || '').trim();
407
+ if (key) {
408
+ return {
409
+ id: 'openai',
410
+ key,
411
+ url: String(env.HNCODE_VOICE_API_URL || 'https://api.openai.com/v1/audio/transcriptions'),
412
+ model: String(env.HNCODE_VOICE_MODEL || 'whisper-1'),
413
+ };
414
+ }
415
+ return null;
416
+ }
417
+
418
+ export function engineHint(env = process.env) {
419
+ return [
420
+ 'Speech input needs a transcription engine; capturing audio is only half of it.',
421
+ 'Pick one:',
422
+ ' offline install whisper.cpp and put `whisper-cli` on PATH',
423
+ ' (no network, nothing leaves the machine)',
424
+ ' hosted set HNCODE_VOICE_API_KEY (or OPENAI_API_KEY)',
425
+ ' (no install, but the audio is uploaded)',
426
+ ' your own set voice_command in config.toml to a program that prints the text',
427
+ ].join('\n');
428
+ }
429
+
430
+ /** whisper.cpp: local, offline, takes a file and prints the text. */
431
+ async function transcribeLocal(command, wavPath, { lang, timeoutMs, run }) {
432
+ const r = await run(command, ['-f', wavPath, '-nt', '--no-prints', '-l', String(lang).split('-')[0]], { timeoutMs });
433
+ const text = cleanTranscript(r.out);
434
+ return text ? { ok: true, text } : { ok: false, error: r.error || 'nothing was recognised' };
435
+ }
436
+
437
+ /** A user-supplied program: its stdout is the text. */
438
+ async function transcribeCommand(command, wavPath, { timeoutMs, run, env = process.env }) {
439
+ const r = await run(command, [], { timeoutMs, env: { ...env, HNCODE_VOICE_WAV: wavPath } });
440
+ const text = cleanTranscript(r.out);
441
+ return text ? { ok: true, text } : { ok: false, error: r.error || 'nothing was recognised' };
442
+ }
443
+
444
+ /**
445
+ * The hosted API, over `fetch` — no SDK, so no dependency.
446
+ *
447
+ * The multipart body is built by hand: a wrong boundary is a 400 with no explanation, and
448
+ * this is where that would come from.
449
+ */
450
+ async function transcribeOpenAI(engine, wavPath, { lang, timeoutMs }) {
451
+ let audio;
452
+ try { audio = fs.readFileSync(wavPath); } catch (e) { return { ok: false, error: e.message }; }
453
+ const boundary = `----hncode${Date.now().toString(36)}`;
454
+ const head = Buffer.from(
455
+ `--${boundary}\r\n`
456
+ + 'Content-Disposition: form-data; name="file"; filename="speech.wav"\r\n'
457
+ + 'Content-Type: audio/wav\r\n\r\n',
458
+ );
459
+ const tail = Buffer.from(
460
+ `\r\n--${boundary}\r\nContent-Disposition: form-data; name="model"\r\n\r\n${engine.model}`
461
+ + `\r\n--${boundary}\r\nContent-Disposition: form-data; name="language"\r\n\r\n${String(lang).split('-')[0]}`
462
+ + `\r\n--${boundary}--\r\n`,
463
+ );
464
+ const ctrl = new AbortController();
465
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
466
+ try {
467
+ const res = await fetch(engine.url, {
468
+ method: 'POST',
469
+ headers: {
470
+ authorization: `Bearer ${engine.key}`,
471
+ 'content-type': `multipart/form-data; boundary=${boundary}`,
472
+ },
473
+ body: Buffer.concat([head, audio, tail]),
474
+ signal: ctrl.signal,
475
+ });
476
+ const body = await res.text();
477
+ if (!res.ok) return { ok: false, error: `transcription failed (HTTP ${res.status}): ${body.slice(0, 200)}` };
478
+ let text = '';
479
+ try { text = JSON.parse(body).text || ''; } catch { text = body; }
480
+ text = cleanTranscript(text);
481
+ return text ? { ok: true, text } : { ok: false, error: 'the transcript was empty' };
482
+ } catch (e) {
483
+ return { ok: false, error: e && e.name === 'AbortError' ? 'transcription timed out' : String((e && e.message) || e) };
484
+ } finally {
485
+ clearTimeout(timer);
486
+ }
487
+ }
488
+
489
+ // ---- the whole gesture ------------------------------------------------------
490
+
491
+ /**
492
+ * Hold the key, speak, let go.
493
+ *
494
+ * This is what the key handler drives, and the only place that knows the two halves are
495
+ * joined. `start()` opens the microphone, `stop()` closes it and resolves with the words — the
496
+ * caller never sees a WAV and never waits for a timer.
497
+ */
498
+ export class Dictation {
499
+ constructor(opts = {}) {
500
+ this.opts = opts;
501
+ this.recorder = opts.recorder || new Recorder(opts);
502
+ this.transcriber = opts.transcriber || new Transcriber(opts);
503
+ this.state = 'idle';
504
+ }
505
+
506
+ /** Both halves are present, so the shortcut is worth offering. */
507
+ get available() {
508
+ return this.recorder.available && this.transcriber.available;
509
+ }
510
+
511
+ /** Why it is not usable, when it is not. */
512
+ get hint() {
513
+ if (!this.recorder.available) return this.recorder.hint;
514
+ if (!this.transcriber.available) return this.transcriber.hint;
515
+ return '';
516
+ }
517
+
518
+ /** Key down: open the microphone. */
519
+ async start() {
520
+ if (this.state !== 'idle') return { ok: false, error: 'already dictating' };
521
+ this.state = 'listening';
522
+ const r = await this.recorder.start();
523
+ if (!r.ok) { this.state = 'idle'; this.recorder.cleanup(); }
524
+ return r;
525
+ }
526
+
527
+ /**
528
+ * Key up: close the microphone and transcribe what it heard.
529
+ *
530
+ * A press and release inside the same frame is a real thing (a tap, or a terminal that
531
+ * coalesces), so an empty capture resolves with a clear message rather than hanging.
532
+ */
533
+ async stop() {
534
+ if (this.state !== 'listening') { this.state = 'idle'; return { ok: false, error: 'not listening' }; }
535
+ this.state = 'transcribing';
536
+ try {
537
+ const rec = await this.recorder.stop();
538
+ if (!rec.ok) return rec;
539
+ return await this.transcriber.transcribe(rec.wavPath, { lang: this.opts.lang });
540
+ } finally {
541
+ this.recorder.cleanup();
542
+ this.state = 'idle';
543
+ }
544
+ }
545
+ }
546
+
547
+ /** Run a command to completion, with a timeout, collecting both streams. */
548
+ export function runToEnd(command, args, opts = {}) {
549
+ const timeoutMs = opts.timeoutMs || DEFAULT_TIMEOUT_MS;
550
+ const env = opts.env || process.env;
551
+ return new Promise((resolve) => {
552
+ let out = '';
553
+ let err = '';
554
+ let done = false;
555
+ const finish = (r) => { if (!done) { done = true; resolve(r); } };
556
+ let child;
557
+ try {
558
+ child = cp.spawn(command, args, { windowsHide: true, env, stdio: ['ignore', 'pipe', 'pipe'] });
559
+ } catch (e) {
560
+ finish({ ok: false, out: '', err: '', error: e.message });
561
+ return;
562
+ }
563
+ const timer = setTimeout(() => {
564
+ try { child.kill(); } catch { /* already gone */ }
565
+ finish({ ok: false, out, err, error: `timed out after ${Math.round(timeoutMs / 1000)}s` });
566
+ }, timeoutMs);
567
+ if (child.stdout) child.stdout.on('data', (d) => { out += d; });
568
+ if (child.stderr) child.stderr.on('data', (d) => { err += d; });
569
+ child.on('error', (e) => { clearTimeout(timer); finish({ ok: false, out, err, error: e.message }); });
570
+ child.on('close', (code) => {
571
+ clearTimeout(timer);
572
+ finish({ ok: code === 0, out, err, error: code === 0 ? '' : (err.trim() || `exited ${code}`) });
573
+ });
574
+ });
575
+ }