@hncode/hncode 0.8.4 → 0.8.6
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 +1 -1
- package/src/context-bar.js +18 -6
- package/src/i18n.js +16 -0
- package/src/keybindings.js +3 -2
- package/src/rows-tool-result.js +17 -0
- package/src/screen-diff.js +14 -1
- package/src/screen.js +14 -18
- package/src/term.js +80 -41
- package/src/tool-line.js +13 -6
- package/src/tui.js +168 -23
- package/src/voice.js +575 -0
package/package.json
CHANGED
package/src/context-bar.js
CHANGED
|
@@ -149,7 +149,7 @@ export function renderContextBar(segments, usedTokens, window, width, readout) {
|
|
|
149
149
|
if (barWidth <= 0) {
|
|
150
150
|
// Too narrow for a bar AND a gap: the readout has the row to itself. Padded to exactly
|
|
151
151
|
// `width` because every row of the frame is, and a short one shifts everything below it.
|
|
152
|
-
return { text: text ? C.white + text
|
|
152
|
+
return { text: text ? C.white + padToWidth(text, width) : ' '.repeat(width), hits: [] };
|
|
153
153
|
}
|
|
154
154
|
|
|
155
155
|
const free = Math.max(0, window - usedTokens);
|
|
@@ -174,6 +174,18 @@ export function renderContextBar(segments, usedTokens, window, width, readout) {
|
|
|
174
174
|
* any fill — so it is legible at every fill level, including a completely full bar.
|
|
175
175
|
* @param {number} width the whole row, bar plus readout.
|
|
176
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
|
+
}
|
|
177
189
|
function paintBar(cols, freeCols, _unused, values, readout, width) {
|
|
178
190
|
let out = '';
|
|
179
191
|
let at = 0; // visible column the next segment starts at
|
|
@@ -190,11 +202,11 @@ function paintBar(cols, freeCols, _unused, values, readout, width) {
|
|
|
190
202
|
// own fill, which reads as if the label belonged to the segment before it. The first
|
|
191
203
|
// segment's left column is the row's own margin, so both cost the same.
|
|
192
204
|
const room = n - 2;
|
|
193
|
-
const inner = room >= label.full
|
|
205
|
+
const inner = room >= visualWidth(label.full)
|
|
194
206
|
? label.full
|
|
195
|
-
: (room >= label.name
|
|
207
|
+
: (room >= visualWidth(label.name) ? label.name : '');
|
|
196
208
|
// `room` columns of label, a blank on the left and one on the right: `n`.
|
|
197
|
-
out += seg.fill + (inner ? ' ' + C.white + inner
|
|
209
|
+
out += seg.fill + (inner ? ' ' + C.white + padToWidth(inner, room) + ' ' : ' '.repeat(n));
|
|
198
210
|
hits.push({ col0: at, col1: at + n - 1, data: seg.key });
|
|
199
211
|
at += n;
|
|
200
212
|
}
|
|
@@ -226,8 +238,8 @@ export function formatReadout(used, window, freeCols) {
|
|
|
226
238
|
// The thresholds match the renderer's own condition exactly (`freeCols >= length`). They
|
|
227
239
|
// used to ask for one more, which is how the bar came up a column short: the readout was
|
|
228
240
|
// accepted HERE and then not written THERE.
|
|
229
|
-
if (freeCols >= full
|
|
230
|
-
if (freeCols >= pct
|
|
241
|
+
if (freeCols >= visualWidth(full)) return full;
|
|
242
|
+
if (freeCols >= visualWidth(pct)) return pct;
|
|
231
243
|
return '';
|
|
232
244
|
}
|
|
233
245
|
|
package/src/i18n.js
CHANGED
|
@@ -1396,6 +1396,22 @@ export const NOTICE_ZH = {
|
|
|
1396
1396
|
"or set one directly: /set <key> <value>": "或直接设置:/set <key> <value>",
|
|
1397
1397
|
"WebSearch keys cleared — searches use keyless mode (rate-limited per IP).": "WebSearch 密钥已清除 — 搜索改用无密钥模式(按 IP 限流)",
|
|
1398
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.": "没有找到语音识别引擎",
|
|
1399
1415
|
};
|
|
1400
1416
|
|
|
1401
1417
|
// The UI's active language, shared with the render modules (rows, panels, file tree)
|
package/src/keybindings.js
CHANGED
|
@@ -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.', '',
|
|
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
|
|
250
|
+
out.push('', `${uiText('Problems')}:`, ...loaded.errors.map((e) => ` ! ${e}`));
|
|
250
251
|
}
|
|
251
252
|
return out;
|
|
252
253
|
}
|
package/src/rows-tool-result.js
CHANGED
|
@@ -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
|
//
|
package/src/screen-diff.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
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
|
@@ -62,6 +62,15 @@ export function strWidth(s) {
|
|
|
62
62
|
// * everything else is memoised (see WIDTH_CACHE_MAX). Rows are re-measured
|
|
63
63
|
// every frame while a reply streams, and the same substrings come back
|
|
64
64
|
// again and again.
|
|
65
|
+
/** Matches any escape sequence, for the width walk to skip. */
|
|
66
|
+
const ESC_RE = /\x1b/;
|
|
67
|
+
function stripEscapes(s) {
|
|
68
|
+
return String(s)
|
|
69
|
+
.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '')
|
|
70
|
+
.replace(/\x1b\[[0-9;?]* [a-zA-Z]/g, '')
|
|
71
|
+
.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '');
|
|
72
|
+
}
|
|
73
|
+
|
|
65
74
|
export function visualWidth(s) {
|
|
66
75
|
if (!s) return 0;
|
|
67
76
|
const str = typeof s === 'string' ? s : String(s);
|
|
@@ -69,7 +78,17 @@ export function visualWidth(s) {
|
|
|
69
78
|
if (isPrintableAscii(str)) return str.length;
|
|
70
79
|
const hit = widthCache.get(str);
|
|
71
80
|
if (hit !== undefined) return hit;
|
|
72
|
-
|
|
81
|
+
|
|
82
|
+
// ANSI ESCAPES ARE NOT GLYPHS.
|
|
83
|
+
//
|
|
84
|
+
// This measured the raw string, so every colour sequence counted as its own characters:
|
|
85
|
+
// `col('● ', orange)` — `ESC[38;2;240;160;80m` + `● ` + `ESC[0m` — came out TWENTY-TWO
|
|
86
|
+
// columns wide instead of two. Every styled row in the frame was therefore measured far
|
|
87
|
+
// wider than it draws, which put `fitAnsi` short, pushed the scrollbar off the edge, and
|
|
88
|
+
// made the row/column arithmetic in the mouse mapping disagree with the screen by however
|
|
89
|
+
// much styling that row happened to carry — an offset that changes from place to place.
|
|
90
|
+
const plain = ESC_RE.test(str) ? stripEscapes(str) : str;
|
|
91
|
+
const w = clusterWidth(plain);
|
|
73
92
|
if (widthCache.size >= WIDTH_CACHE_MAX) {
|
|
74
93
|
// Cheap eviction: drop the oldest insertion (Map preserves order).
|
|
75
94
|
const oldest = widthCache.keys().next().value;
|
|
@@ -218,51 +237,71 @@ const AMBIGUOUS = [
|
|
|
218
237
|
[0x2103, 0x2103], [0x2105, 0x2105], [0x2109, 0x2109], [0x2113, 0x2113],
|
|
219
238
|
[0x2116, 0x2116], [0x2121, 0x2122], [0x2126, 0x2126], [0x212B, 0x212B],
|
|
220
239
|
[0x2153, 0x2154], [0x215B, 0x215E], [0x2160, 0x216B], [0x2170, 0x2179],
|
|
221
|
-
[0x2189, 0x2189], [0x2190,
|
|
222
|
-
[
|
|
223
|
-
[
|
|
224
|
-
[
|
|
225
|
-
[
|
|
226
|
-
[
|
|
227
|
-
[
|
|
228
|
-
[
|
|
229
|
-
[
|
|
230
|
-
[
|
|
231
|
-
[
|
|
232
|
-
[
|
|
233
|
-
[
|
|
234
|
-
[
|
|
235
|
-
[
|
|
236
|
-
[
|
|
237
|
-
[
|
|
238
|
-
[
|
|
239
|
-
[
|
|
240
|
-
[
|
|
241
|
-
[
|
|
242
|
-
[
|
|
243
|
-
[
|
|
244
|
-
[
|
|
245
|
-
[
|
|
246
|
-
[
|
|
247
|
-
[
|
|
240
|
+
[0x2189, 0x2189], [0x2190, 0x219B], [0x219E, 0x21A0], [0x21A3, 0x21A3],
|
|
241
|
+
[0x21A6, 0x21A6], [0x21A9, 0x21AA], [0x21AE, 0x21AE], [0x21B0, 0x21B1],
|
|
242
|
+
[0x21B3, 0x21B4], [0x21B6, 0x21B9], [0x21BC, 0x21BD], [0x21C0, 0x21C1],
|
|
243
|
+
[0x21C4, 0x21C5], [0x21C7, 0x21C9], [0x21CB, 0x21CC], [0x21CE, 0x21CF],
|
|
244
|
+
[0x21D2, 0x21D2], [0x21D4, 0x21D4], [0x21DA, 0x21DB], [0x21DD, 0x21DD],
|
|
245
|
+
[0x21E0, 0x21E1], [0x21E4, 0x21E5], [0x21E7, 0x21E7], [0x21EA, 0x21ED],
|
|
246
|
+
[0x21F4, 0x21F4], [0x2200, 0x2200], [0x2202, 0x2203], [0x2207, 0x2208],
|
|
247
|
+
[0x220B, 0x220B], [0x220F, 0x220F], [0x2211, 0x2211], [0x2215, 0x2215],
|
|
248
|
+
[0x221A, 0x221A], [0x221D, 0x2220], [0x2223, 0x2223], [0x2225, 0x2225],
|
|
249
|
+
[0x2227, 0x222C], [0x222E, 0x222E], [0x2234, 0x2237], [0x223C, 0x223D],
|
|
250
|
+
[0x2248, 0x2248], [0x224C, 0x224C], [0x2252, 0x2252], [0x2260, 0x2261],
|
|
251
|
+
[0x2264, 0x2267], [0x226A, 0x226B], [0x226E, 0x226F], [0x2282, 0x2283],
|
|
252
|
+
[0x2286, 0x2287], [0x2295, 0x2295], [0x2299, 0x2299], [0x22A5, 0x22A5],
|
|
253
|
+
[0x22BF, 0x22BF], [0x2312, 0x2312], [0x2460, 0x24E9], [0x24EB, 0x254B],
|
|
254
|
+
[0x2550, 0x2573], [0x2580, 0x258F], [0x2592, 0x2595], [0x25A0, 0x25A1],
|
|
255
|
+
[0x25A3, 0x25A9], [0x25B2, 0x25B3], [0x25B6, 0x25B7], [0x25BC, 0x25BD],
|
|
256
|
+
[0x25C0, 0x25C1], [0x25C6, 0x25C8], [0x25CB, 0x25CB], [0x25CE, 0x25D1],
|
|
257
|
+
[0x25E2, 0x25E5], [0x25EF, 0x25EF], [0x2605, 0x2606], [0x2609, 0x2609],
|
|
258
|
+
[0x260E, 0x260F], [0x261C, 0x261C], [0x261E, 0x261E], [0x2640, 0x2640],
|
|
259
|
+
[0x2642, 0x2642], [0x2660, 0x2661], [0x2663, 0x2665], [0x2667, 0x266A],
|
|
260
|
+
[0x266C, 0x266D], [0x266F, 0x266F], [0x269E, 0x269F], [0x26C6, 0x26CD],
|
|
261
|
+
[0x26CF, 0x26D3], [0x26D5, 0x26E1], [0x26E3, 0x26E3], [0x26E8, 0x26E9],
|
|
262
|
+
[0x26EB, 0x26F1], [0x26F4, 0x26F4], [0x26F6, 0x26F9], [0x26FB, 0x26FC],
|
|
263
|
+
[0x26FE, 0x26FF], [0x273D, 0x273D], [0x2761, 0x2761], [0x2776, 0x277F],
|
|
264
|
+
[0x2B56, 0x2B59], [0x3248, 0x324F], [0xE000, 0xF8FF], [0xFE00, 0xFE0F],
|
|
265
|
+
[0xFFFD, 0xFFFD], [0x1F100, 0x1F10A], [0x1F110, 0x1F12D], [0x1F130, 0x1F169],
|
|
266
|
+
[0x1F170, 0x1F19A],
|
|
248
267
|
];
|
|
249
268
|
|
|
250
|
-
// EAW=Ambiguous code points that
|
|
269
|
+
// EAW=Ambiguous code points that a terminal still draws ONE column wide.
|
|
270
|
+
//
|
|
271
|
+
// THIS IS THE WHOLE SYMBOL RANGE, AND THAT IS THE POINT.
|
|
272
|
+
//
|
|
273
|
+
// A CJK locale makes far more code points "ambiguous" than a reader expects: every arrow,
|
|
274
|
+
// every box-drawing character, every geometric shape, every dingbat. In practice terminals
|
|
275
|
+
// draw all of them one column wide — they are used for BORDERS, BULLETS and SPINNERS, and a
|
|
276
|
+
// glyph that is a border cannot be two columns wide or it does not meet its neighbour.
|
|
277
|
+
//
|
|
278
|
+
// What IS two columns wide is the thing the Unicode tables and the terminals agree on:
|
|
279
|
+
// ideographs and full-width punctuation, which `WIDE` covers.
|
|
280
|
+
//
|
|
281
|
+
// Getting this wrong is not subtle. Measured on a Chinese terminal:
|
|
251
282
|
//
|
|
252
|
-
//
|
|
253
|
-
//
|
|
254
|
-
//
|
|
255
|
-
// the space it was given — the frames they compose came apart.
|
|
283
|
+
// ● U+25CF measured 2, drawn 1 — every tool row one column too wide
|
|
284
|
+
// ─ U+2500 measured 2, drawn 1 — every panel and table frame
|
|
285
|
+
// … U+2026 measured 2, drawn 1 — every truncated title
|
|
256
286
|
//
|
|
257
|
-
//
|
|
258
|
-
//
|
|
259
|
-
//
|
|
260
|
-
//
|
|
287
|
+
// A row that measures wider than it draws pushes the frame's last column off the screen,
|
|
288
|
+
// and that is the column the scrollbar lives in: the rail came out broken into pieces, and
|
|
289
|
+
// the extra column shifted the diff's write range so a rewritten row could repeat a
|
|
290
|
+
// character. `● Using Screenshot` came out `● Using SScreenshot`.
|
|
261
291
|
const AMBIGUOUS_ALWAYS_NARROW = [
|
|
262
|
-
[
|
|
263
|
-
[
|
|
264
|
-
[
|
|
265
|
-
[
|
|
292
|
+
[0x00A7, 0x00A7], // §
|
|
293
|
+
[0x00B0, 0x00B1], // ° ±
|
|
294
|
+
[0x00B6, 0x00B7], // ¶ ·
|
|
295
|
+
[0x00D7, 0x00D7], // ×
|
|
296
|
+
[0x00F7, 0x00F7], // ÷
|
|
297
|
+
[0x2010, 0x2027], // hyphens, quotes, ellipsis, bullet
|
|
298
|
+
[0x2030, 0x205E], // per-mille, primes, primes-like marks
|
|
299
|
+
[0x2190, 0x21FF], // arrows, including `↳` and `↑↓`
|
|
300
|
+
[0x2200, 0x22FF], // mathematical operators
|
|
301
|
+
[0x2300, 0x23FF], // technical marks
|
|
302
|
+
[0x2500, 0x25FF], // box drawing, block elements, geometric shapes (`● ○ ◐ ▪`)
|
|
303
|
+
[0x2600, 0x27BF], // misc symbols and dingbats (`✓ ✗ ★ ☆`)
|
|
304
|
+
[0x2B00, 0x2BFF], // additional arrows and shapes
|
|
266
305
|
];
|
|
267
306
|
|
|
268
307
|
/**
|
package/src/tool-line.js
CHANGED
|
@@ -55,7 +55,7 @@ const MAX_ARG = 60;
|
|
|
55
55
|
* of characters, and printing it whole wrapped the row across the screen for every call. Ctrl+O is the escape hatch —
|
|
56
56
|
* whoever expands tool output to read it wants to see the command they are reading the output OF.
|
|
57
57
|
*/
|
|
58
|
-
export function keyArgument(name, args, workspace, expanded = false) {
|
|
58
|
+
export function keyArgument(name, args, workspace, expanded = false, budget = MAX_ARG) {
|
|
59
59
|
if (!args || typeof args !== 'object') return '';
|
|
60
60
|
const keys = KEY_ARG[name] || Object.keys(args);
|
|
61
61
|
// Expanded: the whole value, with newlines kept, so a multi-line script shows as the lines it was written as rather
|
|
@@ -81,15 +81,15 @@ export function keyArgument(name, args, workspace, expanded = false) {
|
|
|
81
81
|
while (valueLines.length > 1 && valueLines[valueLines.length - 1].trim() === '') valueLines.pop();
|
|
82
82
|
let text = valueLines[0];
|
|
83
83
|
const rest = valueLines.length > 1 ? valueLines.length - 1 : 0;
|
|
84
|
-
if (text.length >
|
|
84
|
+
if (text.length > budget) {
|
|
85
85
|
text = (k === 'path' || k === 'file_path')
|
|
86
|
-
? '…' + text.slice(text.length - (
|
|
87
|
-
: text.slice(0,
|
|
86
|
+
? '…' + text.slice(text.length - (budget - 1))
|
|
87
|
+
: text.slice(0, budget - 1) + '…';
|
|
88
88
|
} else if (rest) {
|
|
89
89
|
// Make room for the marker before adding it, so the row never overflows: the count is dropped first because the
|
|
90
90
|
// ellipsis already carries the important half of the message.
|
|
91
91
|
const withCount = `… (+${rest} line${rest === 1 ? '' : 's'})`;
|
|
92
|
-
text += text.length + withCount.length <=
|
|
92
|
+
text += text.length + withCount.length <= budget
|
|
93
93
|
? withCount
|
|
94
94
|
: '…';
|
|
95
95
|
}
|
|
@@ -109,7 +109,14 @@ export function keyArgument(name, args, workspace, expanded = false) {
|
|
|
109
109
|
*/
|
|
110
110
|
export function formatToolLine(msg, workspace, spin, pulseStart, shimmerEdge, expanded = false, reducedMotion = false, width = 0) {
|
|
111
111
|
const name = msg.toolName || '';
|
|
112
|
-
|
|
112
|
+
// THE ARGUMENT IS CUT TO WHAT IS LEFT OF THE ROW.
|
|
113
|
+
//
|
|
114
|
+
// It was cut to a hardcoded 60 characters, so `● Using Bash (…)` measured 13 + 60 = 73
|
|
115
|
+
// columns on every terminal. Anything narrower than that was wrapped BY THE TERMINAL,
|
|
116
|
+
// taking two display rows where the frame counted one, and every row below moved down.
|
|
117
|
+
// `width` is the row the caller has; the verb and the name come out of it first.
|
|
118
|
+
const argBudget = Math.max(8, (width || 0) - (msg.pending ? 'Using' : 'Used').length - 1 - name.length - 3);
|
|
119
|
+
const arg = keyArgument(name, msg.toolArgs, workspace, expanded, argBudget);
|
|
113
120
|
const verb = msg.pending ? 'Using' : 'Used';
|
|
114
121
|
let nameDisplay;
|
|
115
122
|
if (msg.pending) {
|
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
|
|
|
@@ -1468,9 +1469,23 @@ function messageLines(msg, width, workspace, expanded, spin, pulseStart, rawMode
|
|
|
1468
1469
|
// is not a continuation and gets no mark — the break is already unmistakable.
|
|
1469
1470
|
const wrapped = [];
|
|
1470
1471
|
for (const segment of segments) {
|
|
1471
|
-
|
|
1472
|
+
// THE CONTINUATION MARK NEEDS A COLUMN OF ITS OWN, AND ONLY ONCE.
|
|
1473
|
+
//
|
|
1474
|
+
// `parts[i]` fills the row exactly, so appending `…` made the row ONE COLUMN WIDER than
|
|
1475
|
+
// the terminal. The terminal then wraps it itself, taking two display rows where this
|
|
1476
|
+
// function counted one — and every row below shifts by one, which is why the offset
|
|
1477
|
+
// moved around instead of being a constant.
|
|
1478
|
+
//
|
|
1479
|
+
// And only when the segment does not already end in one: `keyArgument` truncates the
|
|
1480
|
+
// argument it was handed, so a wrapped command could come out `… …` — two marks and a
|
|
1481
|
+
// space between them, on a row that was already at its limit.
|
|
1482
|
+
const willBreak = visualCol(segment) > bodyW;
|
|
1483
|
+
const room = willBreak ? Math.max(1, bodyW - 1) : bodyW;
|
|
1484
|
+
const parts = wrapAnsiWords(segment, room);
|
|
1472
1485
|
for (let i = 0; i < parts.length; i++) {
|
|
1473
|
-
|
|
1486
|
+
const last = i === parts.length - 1;
|
|
1487
|
+
const alreadyMarked = /…\s*$/.test(stripAnsi(parts[i]));
|
|
1488
|
+
wrapped.push(last || alreadyMarked ? parts[i] : parts[i] + col('…', C.gray));
|
|
1474
1489
|
}
|
|
1475
1490
|
}
|
|
1476
1491
|
const out = wrapped.map((t, i) => ({
|
|
@@ -1536,7 +1551,7 @@ function messageLines(msg, width, workspace, expanded, spin, pulseStart, rawMode
|
|
|
1536
1551
|
// the one unreadable thing on the screen while the finished result's arrow (rows-tool-result.js, which
|
|
1537
1552
|
// does use `C.marker`) was bright. Same glyph, two colours, depending on whether the command had
|
|
1538
1553
|
// finished.
|
|
1539
|
-
const marker = firstLive ? C.marker +
|
|
1554
|
+
const marker = firstLive ? C.marker + TOOL_MARKER_PREFIX + C.reset : TOOL_MARKER_INDENT;
|
|
1540
1555
|
const rowW = bodyW;
|
|
1541
1556
|
out.push({ text: C.termBg + fitAnsi(surfaced, rowW) + C.bgReset, ind: marker, raw: true });
|
|
1542
1557
|
}
|
|
@@ -1623,8 +1638,8 @@ function messageLines(msg, width, workspace, expanded, spin, pulseStart, rawMode
|
|
|
1623
1638
|
// machine, and every continuation row started a column early — a ragged gutter that
|
|
1624
1639
|
// only showed up there. Both are built from the marker's own measured width instead,
|
|
1625
1640
|
// so the block is square wherever it is drawn.
|
|
1626
|
-
const markerRaw =
|
|
1627
|
-
const contRaw =
|
|
1641
|
+
const markerRaw = TOOL_MARKER_PREFIX;
|
|
1642
|
+
const contRaw = TOOL_MARKER_INDENT;
|
|
1628
1643
|
lines.slice(0, MAX).forEach((ln, i) => {
|
|
1629
1644
|
const num = String(i + 1).padStart(wNum);
|
|
1630
1645
|
// A LINE LONGER THAN THE PANEL IS CUT, not wrapped. `raw: true` means the renderer does not wrap it for us,
|
|
@@ -11556,7 +11571,7 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
|
|
|
11556
11571
|
const want = a === 'on' ? true : a === 'off' ? false : !(cfg.promptCache !== false);
|
|
11557
11572
|
cfg.promptCache = want;
|
|
11558
11573
|
try { setConfigString('prompt_cache', want ? 'true' : 'false'); } catch { /* best-effort persist */ }
|
|
11559
|
-
app(
|
|
11574
|
+
app(`${uiText('Prompt caching')}: ${want ? uiText('ON') : uiText('OFF')}`);
|
|
11560
11575
|
sayPanel(want
|
|
11561
11576
|
? 'The stable prefix (tools + system + conversation head) is marked cacheable.\n'
|
|
11562
11577
|
+ 'Providers bill cached input at a fraction of the normal rate. Effective\n'
|
|
@@ -11795,6 +11810,9 @@ function setPermission(state, mode) { state.mode = mode; }
|
|
|
11795
11810
|
// are a long switch. The list is the REACHABLE set, so a plugin is warned about the ones a
|
|
11796
11811
|
// user would notice losing; the switch's internal cursor keys are deliberately absent,
|
|
11797
11812
|
// because a plugin claiming those is not something to guard against.
|
|
11813
|
+
// ---- speech input -----------------------------------------------------------
|
|
11814
|
+
|
|
11815
|
+
|
|
11798
11816
|
const BUILTIN_KEYS = new Set([
|
|
11799
11817
|
'c-c', // interrupt / quit
|
|
11800
11818
|
'c-b', // background a running Bash command
|
|
@@ -11810,6 +11828,7 @@ const BUILTIN_KEYS = new Set([
|
|
|
11810
11828
|
'c-x', // (reserved; Ctrl+Shift+X is paste-and-run)
|
|
11811
11829
|
'c-s-c', // copy the selection or last answer
|
|
11812
11830
|
'c-s-v', // paste as a bracketed paste
|
|
11831
|
+
'c-s-m', // hold to dictate into the composer
|
|
11813
11832
|
'c-up', 'c-down', // scroll the output area
|
|
11814
11833
|
'escape',
|
|
11815
11834
|
'tab', 's-tab',
|
|
@@ -12339,7 +12358,16 @@ export function tokenize(str) {
|
|
|
12339
12358
|
// movement speeds up as if the user were holding it. The event type says which it is: `repeat` marks the
|
|
12340
12359
|
// terminal's own auto-repeat, `release` means the key came back up, `press` is a real hit.
|
|
12341
12360
|
const eventType = ku[3] ? parseInt(ku[3], 10) : 1;
|
|
12342
|
-
|
|
12361
|
+
// THE ONE RELEASE THAT IS REPORTED. Dictation is a HOLD: the key going down opens the
|
|
12362
|
+
// microphone and letting it up closes it, so that release has to reach the handler.
|
|
12363
|
+
// Every other key drops its release here, because a second event per press is how a
|
|
12364
|
+
// menu opens twice from one tap.
|
|
12365
|
+
if (eventType === 3) {
|
|
12366
|
+
const ch = ctrlLetter(ku[1] ? parseInt(ku[1], 10) : 0);
|
|
12367
|
+
if (ctrl && shift && ch === 'm') out.push({ key: 'c-s-m-up' });
|
|
12368
|
+
i += ku[0].length;
|
|
12369
|
+
continue;
|
|
12370
|
+
}
|
|
12343
12371
|
// `held` is true only for the terminal's auto-repeat. A caller that accelerates on a held key uses it; two
|
|
12344
12372
|
// quick taps arrive as two presses and stay two steps.
|
|
12345
12373
|
const held = eventType === 2;
|
|
@@ -12380,7 +12408,12 @@ export function tokenize(str) {
|
|
|
12380
12408
|
// made Ctrl+Shift+C indistinguishable from Ctrl+C, so "copy" ran the
|
|
12381
12409
|
// interrupt / exit-confirmation path instead.
|
|
12382
12410
|
const ch = ctrlLetter(cp);
|
|
12383
|
-
|
|
12411
|
+
// `held` TRAVELS WITH THE TOKEN. A key held down arrives once as a press and then
|
|
12412
|
+
// as the terminal's own auto-repeat; without the flag every repeat looks like a
|
|
12413
|
+
// fresh press, and a handler that starts something (dictation opens a microphone)
|
|
12414
|
+
// does it again on every repeat — which is the notice that fills the screen while
|
|
12415
|
+
// the key is held.
|
|
12416
|
+
if (ch) { out.push(held ? { key: 'c-s-' + ch, held: true } : { key: 'c-s-' + ch }); i += ku[0].length; continue; }
|
|
12384
12417
|
}
|
|
12385
12418
|
if (ctrl && !alt) {
|
|
12386
12419
|
const ch = ctrlLetter(cp);
|
|
@@ -14194,6 +14227,21 @@ export async function startTUI(opts) {
|
|
|
14194
14227
|
// consumer follow (see `replaceSession`).
|
|
14195
14228
|
state.session = session;
|
|
14196
14229
|
|
|
14230
|
+
// SPEECH INPUT, BUILT ON FIRST USE. `Dictation` owns the microphone and the recogniser, so
|
|
14231
|
+
// the key handler only has to say "down" and "up". A session that never dictates pays
|
|
14232
|
+
// nothing for the engine lookup or the temporary directory.
|
|
14233
|
+
let voice = null;
|
|
14234
|
+
const ensureVoice = () => {
|
|
14235
|
+
if (voice) return voice;
|
|
14236
|
+
// The recogniser is told the language the interface is already in: it is far more
|
|
14237
|
+
// accurate when it expects the right one, and the user has expressed a preference.
|
|
14238
|
+
voice = new Dictation({ lang: cfg.lang === 'zh' ? 'zh-CN' : 'en-US' });
|
|
14239
|
+
return voice;
|
|
14240
|
+
};
|
|
14241
|
+
// The key handler is module-level and cannot see this closure, so it reaches the object
|
|
14242
|
+
// through the host it already has.
|
|
14243
|
+
state._ensureVoice = ensureVoice;
|
|
14244
|
+
|
|
14197
14245
|
cfg.effort = state.reasoning ? state.effort : '';
|
|
14198
14246
|
// Price the session's restored tokens against the model it is about to use, so
|
|
14199
14247
|
// /cost and the status badge are right before the first new request.
|
|
@@ -14778,6 +14826,16 @@ export async function startTUI(opts) {
|
|
|
14778
14826
|
tail: JSON.stringify(out.slice(-80)),
|
|
14779
14827
|
newlines: (out.match(/\n/g) || []).length,
|
|
14780
14828
|
height: dims().rows,
|
|
14829
|
+
// EACH ROW, AS THE TERMINAL WILL RECEIVE IT.
|
|
14830
|
+
//
|
|
14831
|
+
// A duplicated or misplaced character on screen can only be explained by what was
|
|
14832
|
+
// actually written, so the trace carries the full text of every row and the
|
|
14833
|
+
// character in its LAST column — the rail lives there, and a row whose last
|
|
14834
|
+
// column is not a rail glyph is a row the rail lost.
|
|
14835
|
+
rowText: (frame.lines || []).map((l, y) => {
|
|
14836
|
+
const plain = String(l).replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '');
|
|
14837
|
+
return `${y}:${plain.length ? plain[plain.length - 1] : ' '}:${plain}`;
|
|
14838
|
+
}),
|
|
14781
14839
|
}) + '\n');
|
|
14782
14840
|
} catch { /* tracing must never break a paint */ }
|
|
14783
14841
|
}
|
|
@@ -17265,13 +17323,25 @@ export async function startTUI(opts) {
|
|
|
17265
17323
|
// frame and only the body branch sets it).
|
|
17266
17324
|
if (!allowHidden && state._bodyScreenTop == null) return '';
|
|
17267
17325
|
const { cols } = dims();
|
|
17268
|
-
//
|
|
17269
|
-
//
|
|
17270
|
-
//
|
|
17271
|
-
//
|
|
17272
|
-
//
|
|
17273
|
-
//
|
|
17274
|
-
|
|
17326
|
+
// THE SAME RENDER THE SCREEN USED.
|
|
17327
|
+
//
|
|
17328
|
+
// `selection.row` is an index into the ROW ARRAY, and that array is built by
|
|
17329
|
+
// renderChatLines. Two calls with the same state can still disagree about how many rows
|
|
17330
|
+
// the transcript has: windowed, a message far from the viewport is counted from its cached
|
|
17331
|
+
// `_count`; rendered whole, every message is laid out for real, and a message whose rows
|
|
17332
|
+
// come out empty — a `tool_result` with no tool name, of which a long session has dozens —
|
|
17333
|
+
// counts differently.
|
|
17334
|
+
//
|
|
17335
|
+
// Measured on a real 2677-message session: windowed 10576 rows, whole 10604. The frame's
|
|
17336
|
+
// `_bodyTop` comes from the windowed count, so indexing the whole one put every copy 28
|
|
17337
|
+
// rows off — further down the transcript, further off, which is exactly "it depends where
|
|
17338
|
+
// I click".
|
|
17339
|
+
//
|
|
17340
|
+
// So the copy asks for the SAME array the frame asked for, with the same viewport.
|
|
17341
|
+
const bodyH = state._bodyH || 0;
|
|
17342
|
+
const rawChat = state._forceFullRender || !bodyH
|
|
17343
|
+
? renderChatLines(state, cols)
|
|
17344
|
+
: renderChatLines(state, cols, { bodyH, scroll: state.scroll || 0 });
|
|
17275
17345
|
const a = sel.anchor, h = sel.head;
|
|
17276
17346
|
const start = (h.row < a.row || (h.row === a.row && h.col < a.col)) ? h : a;
|
|
17277
17347
|
const end = start === a ? h : a;
|
|
@@ -17314,10 +17384,17 @@ export async function startTUI(opts) {
|
|
|
17314
17384
|
return out.join('\n');
|
|
17315
17385
|
}
|
|
17316
17386
|
function slicePlainByCol(text, c0, c1) {
|
|
17317
|
-
// A
|
|
17318
|
-
// width, and
|
|
17319
|
-
//
|
|
17320
|
-
|
|
17387
|
+
// A slice that runs TO THE END OF THE ROW loses the right padding. The row is padded to
|
|
17388
|
+
// the terminal width, and that padding is not content — the highlight stops at the last
|
|
17389
|
+
// character, so the copy has to as well, or the clipboard comes back with a line of
|
|
17390
|
+
// invisible spaces that were never selected.
|
|
17391
|
+
//
|
|
17392
|
+
// `c0 === 0` USED TO BE PART OF THIS TEST, and that was the bug: a selection whose first
|
|
17393
|
+
// row starts at column 1 — which is every row, since column 0 is the margin the copy
|
|
17394
|
+
// skips — took the other path and kept its padding. Dragging across two or more rows and
|
|
17395
|
+
// pasting gave the first line followed by thirty-odd spaces.
|
|
17396
|
+
const toEnd = c1 === Infinity;
|
|
17397
|
+
if (c0 === 0 && toEnd) return text.replace(/\s+$/, '');
|
|
17321
17398
|
let out = '';
|
|
17322
17399
|
let col = 0;
|
|
17323
17400
|
const s = String(text || '');
|
|
@@ -17325,12 +17402,12 @@ export async function startTUI(opts) {
|
|
|
17325
17402
|
const cp = s.codePointAt(i);
|
|
17326
17403
|
const ch = String.fromCodePoint(cp);
|
|
17327
17404
|
const cw = visualWidth(ch);
|
|
17328
|
-
if (col >= c0 && (
|
|
17405
|
+
if (col >= c0 && (toEnd || col < c1)) out += ch;
|
|
17329
17406
|
col += cw;
|
|
17330
17407
|
i += cp > 0xffff ? 2 : 1;
|
|
17331
|
-
if (
|
|
17408
|
+
if (!toEnd && col >= c1) break;
|
|
17332
17409
|
}
|
|
17333
|
-
return out;
|
|
17410
|
+
return toEnd ? out.replace(/\s+$/, '') : out;
|
|
17334
17411
|
}
|
|
17335
17412
|
function copyToClipboard(text) {
|
|
17336
17413
|
// Empty text is NOT a success. `copyText` returns false without touching the
|
|
@@ -18308,6 +18385,74 @@ export async function startTUI(opts) {
|
|
|
18308
18385
|
return;
|
|
18309
18386
|
}
|
|
18310
18387
|
|
|
18388
|
+
if (t.key === 'c-s-m' && t.held) return; // the terminal's auto-repeat, not a new press
|
|
18389
|
+
if (t.key === 'c-s-m') {
|
|
18390
|
+
// Ctrl+Shift+M, HELD: the key going down opens the microphone and letting it up
|
|
18391
|
+
// closes it. A hold rather than a tap because the user knows when they have
|
|
18392
|
+
// finished speaking, and a recogniser guessing at the pause either cuts them off or
|
|
18393
|
+
// waits.
|
|
18394
|
+
//
|
|
18395
|
+
// The text lands AT THE CARET, not over the draft. Dictating a correction into a
|
|
18396
|
+
// half-written message is the common case, and replacing what is already there is
|
|
18397
|
+
// the one thing a dictation key must never do.
|
|
18398
|
+
const voice = state._ensureVoice ? state._ensureVoice() : null;
|
|
18399
|
+
if (!voice || !voice.available) {
|
|
18400
|
+
notice(uiText('Speech input is unavailable'), 'warn');
|
|
18401
|
+
const hint = (voice && voice.hint) || uiText('No speech engine was found.');
|
|
18402
|
+
for (const line of String(hint).split('\n')) notice(line, 'info');
|
|
18403
|
+
return;
|
|
18404
|
+
}
|
|
18405
|
+
// Remember where the caret was when the key went down: the user may move it while
|
|
18406
|
+
// speaking, and the words belong where they started.
|
|
18407
|
+
state._voiceCaret = Math.max(0, Math.min(state.input.length, state.caret || 0));
|
|
18408
|
+
state._voiceBusy = true;
|
|
18409
|
+
notice(uiText('Listening… release to insert'), 'info');
|
|
18410
|
+
renderFrame();
|
|
18411
|
+
void (async () => {
|
|
18412
|
+
const started = await voice.start();
|
|
18413
|
+
if (!started.ok) {
|
|
18414
|
+
state._voiceBusy = false;
|
|
18415
|
+
notice(started.error || tr('voice.failed', 'Speech input failed'), 'warn');
|
|
18416
|
+
if (started.hint) for (const line of String(started.hint).split('\n')) notice(line, 'info');
|
|
18417
|
+
renderFrame();
|
|
18418
|
+
}
|
|
18419
|
+
})();
|
|
18420
|
+
return;
|
|
18421
|
+
}
|
|
18422
|
+
|
|
18423
|
+
if (t.key === 'c-s-m-up') {
|
|
18424
|
+
// The key came up: stop the microphone and insert what it heard.
|
|
18425
|
+
if (!state._voiceBusy) return;
|
|
18426
|
+
const voice = state._ensureVoice ? state._ensureVoice() : null;
|
|
18427
|
+
if (!voice) return;
|
|
18428
|
+
void (async () => {
|
|
18429
|
+
try {
|
|
18430
|
+
const r = await voice.stop();
|
|
18431
|
+
if (r.ok && r.text) {
|
|
18432
|
+
const at = Math.max(0, Math.min(state.input.length, state._voiceCaret || 0));
|
|
18433
|
+
// A space only when the insertion point is not already at one, so a dictated
|
|
18434
|
+
// word joins the sentence instead of starting a new one.
|
|
18435
|
+
const glue = at > 0 && !/\s$/.test(state.input.slice(0, at)) ? ' ' : '';
|
|
18436
|
+
const add = glue + r.text;
|
|
18437
|
+
state.input = state.input.slice(0, at) + add + state.input.slice(at);
|
|
18438
|
+
state.caret = at + add.length;
|
|
18439
|
+
notice(tr('voice.inserted', 'Inserted {n} characters', { n: r.text.length }), 'info');
|
|
18440
|
+
} else {
|
|
18441
|
+
// The HINT is the point: "speech failed" leaves the user with nowhere to go.
|
|
18442
|
+
notice(r.error || tr('voice.failed', 'Speech input failed'), 'warn');
|
|
18443
|
+
if (r.hint) for (const line of String(r.hint).split('\n')) notice(line, 'info');
|
|
18444
|
+
}
|
|
18445
|
+
} catch (e) {
|
|
18446
|
+
notice(tr('voice.failed', 'Speech input failed') + ': ' + ((e && e.message) || e), 'warn');
|
|
18447
|
+
} finally {
|
|
18448
|
+
state._voiceBusy = false;
|
|
18449
|
+
state._voiceCaret = 0;
|
|
18450
|
+
renderFrame();
|
|
18451
|
+
}
|
|
18452
|
+
})();
|
|
18453
|
+
return;
|
|
18454
|
+
}
|
|
18455
|
+
|
|
18311
18456
|
if (t.key === 'c-v') {
|
|
18312
18457
|
// Ctrl+V: paste. Many terminals translate Ctrl+V in raw mode to the raw
|
|
18313
18458
|
// 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
|
+
}
|