@hyperwindmill/caretaker-cli 0.29.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/agents/dispatch.d.ts.map +1 -1
  2. package/dist/agents/dispatch.js +4 -1
  3. package/dist/cli/web/server.d.ts.map +1 -1
  4. package/dist/cli/web/server.js +29 -7
  5. package/dist/cli/web/session_scope.d.ts +11 -0
  6. package/dist/cli/web/session_scope.d.ts.map +1 -0
  7. package/dist/cli/web/session_scope.js +13 -0
  8. package/dist/cli/web/turn_guard.d.ts +9 -0
  9. package/dist/cli/web/turn_guard.d.ts.map +1 -0
  10. package/dist/cli/web/turn_guard.js +18 -0
  11. package/dist/cli/web/voice_backend.d.ts +4 -0
  12. package/dist/cli/web/voice_backend.d.ts.map +1 -1
  13. package/dist/cli/web/voice_backend.js +14 -3
  14. package/dist/cli/web/voice_builtin.d.ts +3 -0
  15. package/dist/cli/web/voice_builtin.d.ts.map +1 -0
  16. package/dist/cli/web/voice_builtin.js +74 -0
  17. package/dist/cli/web/voice_proxy.d.ts +36 -1
  18. package/dist/cli/web/voice_proxy.d.ts.map +1 -1
  19. package/dist/cli/web/voice_proxy.js +201 -30
  20. package/dist/commands/loader.js +2 -2
  21. package/dist/harness/tools/builtin/index.d.ts.map +1 -1
  22. package/dist/harness/tools/builtin/index.js +4 -0
  23. package/dist/harness/tools/builtin/set_workspace.d.ts +3 -0
  24. package/dist/harness/tools/builtin/set_workspace.d.ts.map +1 -0
  25. package/dist/harness/tools/builtin/set_workspace.js +71 -0
  26. package/dist/plugins/manifest.d.ts +1 -1
  27. package/dist/plugins/manifest.js +1 -1
  28. package/dist/session/store.d.ts +6 -0
  29. package/dist/session/store.d.ts.map +1 -1
  30. package/dist/session/store.js +11 -0
  31. package/dist/session/types.d.ts +5 -0
  32. package/dist/session/types.d.ts.map +1 -1
  33. package/dist/store/db.d.ts.map +1 -1
  34. package/dist/store/db.js +3 -1
  35. package/dist/voice/pocket/catalog.d.ts +24 -0
  36. package/dist/voice/pocket/catalog.d.ts.map +1 -0
  37. package/dist/voice/pocket/catalog.js +152 -0
  38. package/dist/voice/pocket/engine.d.ts +17 -0
  39. package/dist/voice/pocket/engine.d.ts.map +1 -0
  40. package/dist/voice/pocket/engine.js +145 -0
  41. package/dist/voice/pocket/inference.d.ts +36 -0
  42. package/dist/voice/pocket/inference.d.ts.map +1 -0
  43. package/dist/voice/pocket/inference.js +228 -0
  44. package/dist/voice/pocket/install.d.ts +68 -0
  45. package/dist/voice/pocket/install.d.ts.map +1 -0
  46. package/dist/voice/pocket/install.js +329 -0
  47. package/dist/voice/pocket/tokenizer.d.ts +42 -0
  48. package/dist/voice/pocket/tokenizer.d.ts.map +1 -0
  49. package/dist/voice/pocket/tokenizer.js +279 -0
  50. package/dist/voice/pocket/voices.d.ts +9 -0
  51. package/dist/voice/pocket/voices.d.ts.map +1 -0
  52. package/dist/voice/pocket/voices.js +88 -0
  53. package/dist/voice/pronunciation.d.ts +16 -0
  54. package/dist/voice/pronunciation.d.ts.map +1 -0
  55. package/dist/voice/pronunciation.js +54 -0
  56. package/dist/voice/whisper/catalog.d.ts +15 -0
  57. package/dist/voice/whisper/catalog.d.ts.map +1 -0
  58. package/dist/voice/whisper/catalog.js +53 -0
  59. package/dist/voice/whisper/decoder.d.ts +3 -0
  60. package/dist/voice/whisper/decoder.d.ts.map +1 -0
  61. package/dist/voice/whisper/decoder.js +48 -0
  62. package/dist/voice/whisper/engine.d.ts +8 -0
  63. package/dist/voice/whisper/engine.d.ts.map +1 -0
  64. package/dist/voice/whisper/engine.js +77 -0
  65. package/dist/voice/whisper/features.d.ts +10 -0
  66. package/dist/voice/whisper/features.d.ts.map +1 -0
  67. package/dist/voice/whisper/features.js +149 -0
  68. package/dist/voice/whisper/inference.d.ts +17 -0
  69. package/dist/voice/whisper/inference.d.ts.map +1 -0
  70. package/dist/voice/whisper/inference.js +257 -0
  71. package/dist/voice/whisper/wav.d.ts +5 -0
  72. package/dist/voice/whisper/wav.d.ts.map +1 -0
  73. package/dist/voice/whisper/wav.js +48 -0
  74. package/dist/webview/standalone.js +1777 -743
  75. package/dist/webview/standalone.js.map +4 -4
  76. package/package.json +3 -3
@@ -0,0 +1,257 @@
1
+ // Own inference loop over a Whisper ONNX export (HF/optimum layout): 16 kHz audio ->
2
+ // log-mel (features.ts) -> encoder over the fixed 30 s window -> greedy decoding on the
3
+ // merged decoder with KV cache (`use_cache_branch`) -> GPT-2 byte decoding (decoder.ts).
4
+ // The ONNX runtime is passed in (downloaded at runtime, never a package dependency).
5
+ import { existsSync } from 'node:fs';
6
+ import { readFile } from 'node:fs/promises';
7
+ import { join } from 'node:path';
8
+ import { byteDecode, parseVocab } from './decoder.js';
9
+ import { logMel, N_FRAMES, N_MELS, N_SAMPLES, SAMPLE_RATE } from './features.js';
10
+ // int8 encoder + q4 decoder: the int8 decoder is ~2.5x slower per token on CPUs without
11
+ // VNNI, encoder speed is the same across variants (spike measurements).
12
+ export const WHISPER_GRAPHS = {
13
+ encoder: 'encoder_model_quantized.onnx',
14
+ decoder: 'decoder_model_merged_q4.onnx',
15
+ };
16
+ export const WHISPER_FILES = [
17
+ 'config.json',
18
+ 'generation_config.json',
19
+ 'added_tokens.json',
20
+ 'vocab.json',
21
+ ];
22
+ // Half the decoder's 448 positions, as openai-whisper / HF generate.
23
+ export const MAX_NEW_TOKENS = 224;
24
+ // Peak amplitude below which a window is silence (-60 dBFS): Whisper hallucinates on
25
+ // silence ("Thanks for watching"), so it is never fed to the model.
26
+ const SILENCE_PEAK = 1e-3;
27
+ const WINDOW_SECONDS = 30;
28
+ const CUT_SEARCH_SECONDS = 5;
29
+ const CUT_SPAN_SECONDS = 0.5;
30
+ // A model directory holds the HF layout (graphs under onnx/) or everything flat.
31
+ export function modelFile(dir, name) {
32
+ for (const path of [join(dir, 'onnx', name), join(dir, name)])
33
+ if (existsSync(path))
34
+ return path;
35
+ throw new Error(`Whisper model file ${name} is missing in ${dir}`);
36
+ }
37
+ const readJson = async (dir, name) => JSON.parse(await readFile(modelFile(dir, name), 'utf8'));
38
+ export async function createWhisperModel(ort, dir, opts) {
39
+ const config = await readJson(dir, 'config.json');
40
+ const gen = await readJson(dir, 'generation_config.json');
41
+ const added = await readJson(dir, 'added_tokens.json');
42
+ const vocab = parseVocab(await readJson(dir, 'vocab.json'), Object.values(added));
43
+ const sessionOptions = {
44
+ intraOpNumThreads: Math.max(1, opts.threads),
45
+ interOpNumThreads: 1,
46
+ executionMode: 'sequential',
47
+ };
48
+ const encoder = await ort.InferenceSession.create(modelFile(dir, WHISPER_GRAPHS.encoder), sessionOptions);
49
+ let decoder;
50
+ try {
51
+ decoder = await ort.InferenceSession.create(modelFile(dir, WHISPER_GRAPHS.decoder), sessionOptions);
52
+ }
53
+ catch (err) {
54
+ await encoder.release().catch(() => { });
55
+ throw err;
56
+ }
57
+ return new Model(ort, config, gen, Object.values(added), vocab, encoder, decoder);
58
+ }
59
+ class Model {
60
+ ort;
61
+ config;
62
+ gen;
63
+ specialIds;
64
+ vocab;
65
+ encoder;
66
+ decoder;
67
+ closed = false;
68
+ // Suppression masks (1 = never emitted), sized from the first logits seen.
69
+ masks = null;
70
+ constructor(ort, config, gen, specialIds, vocab, encoder, decoder) {
71
+ this.ort = ort;
72
+ this.config = config;
73
+ this.gen = gen;
74
+ this.specialIds = specialIds;
75
+ this.vocab = vocab;
76
+ this.encoder = encoder;
77
+ this.decoder = decoder;
78
+ }
79
+ async transcribe(audio, lang, signal) {
80
+ if (this.closed)
81
+ throw new Error('Whisper model is closed');
82
+ if (audio.length > N_SAMPLES)
83
+ throw new Error('Whisper window longer than 30 s; split it with splitWindows');
84
+ signal.throwIfAborted();
85
+ if (peak(audio) < SILENCE_PEAK)
86
+ return '';
87
+ const { ort, gen } = this;
88
+ const features = new ort.Tensor('float32', logMel(audio), [1, N_MELS, N_FRAMES]);
89
+ const { last_hidden_state: hidden } = await this.encoder.run({ input_features: features });
90
+ signal.throwIfAborted();
91
+ const tail = [gen.task_to_id.transcribe, gen.no_timestamps_token_id];
92
+ let langId = lang ? gen.lang_to_id[`<|${lang.toLowerCase().split(/[-_]/)[0]}|>`] : undefined;
93
+ if (langId === undefined) {
94
+ // Auto-detect: the language token Whisper itself would emit after SOT, in a pass of
95
+ // its own like faster-whisper. Continuing that pass with the rest of the prompt on
96
+ // the cache branch was measured to change the transcript.
97
+ const logits = await this.pass(hidden)([gen.decoder_start_token_id]);
98
+ langId = argmaxOf(logits, Object.values(gen.lang_to_id));
99
+ signal.throwIfAborted();
100
+ }
101
+ const step = this.pass(hidden);
102
+ let feed = [gen.decoder_start_token_id, langId, ...tail];
103
+ const tokens = [];
104
+ for (let n = 0; n < MAX_NEW_TOKENS; n++) {
105
+ signal.throwIfAborted();
106
+ const logits = await step(feed);
107
+ const masks = this.suppression(logits.length);
108
+ const token = argmaxUnmasked(logits, n === 0 ? masks.first : masks.any);
109
+ if (token === gen.eos_token_id || token < 0)
110
+ break;
111
+ tokens.push(token);
112
+ feed = [token];
113
+ }
114
+ return byteDecode(tokens, this.vocab).trim();
115
+ }
116
+ async close() {
117
+ if (this.closed)
118
+ return;
119
+ this.closed = true;
120
+ await Promise.allSettled([this.encoder.release(), this.decoder.release()]);
121
+ }
122
+ // A decoding pass: each call returns the logits of the last position for `ids` and
123
+ // advances the pass's own KV cache.
124
+ pass(hidden) {
125
+ const { ort } = this;
126
+ const past = this.emptyPast();
127
+ let cached = false;
128
+ return async (ids) => {
129
+ const out = await this.decoder.run({
130
+ input_ids: new ort.Tensor('int64', BigInt64Array.from(ids, BigInt), [1, ids.length]),
131
+ encoder_hidden_states: hidden,
132
+ use_cache_branch: new ort.Tensor('bool', Uint8Array.of(cached ? 1 : 0), [1]),
133
+ ...past,
134
+ });
135
+ for (let l = 0; l < this.config.decoder_layers; l++) {
136
+ for (const kind of ['decoder.key', 'decoder.value']) {
137
+ past[`past_key_values.${l}.${kind}`] = output(out, `present.${l}.${kind}`);
138
+ }
139
+ // The cross-attention cache is computed by the no-cache branch only; the cache
140
+ // branch passes it through.
141
+ if (!cached) {
142
+ for (const kind of ['encoder.key', 'encoder.value']) {
143
+ past[`past_key_values.${l}.${kind}`] = output(out, `present.${l}.${kind}`);
144
+ }
145
+ }
146
+ }
147
+ cached = true;
148
+ const logits = output(out, 'logits');
149
+ const size = logits.dims[2];
150
+ const data = logits.data;
151
+ return data.subarray(data.length - size);
152
+ };
153
+ }
154
+ // Step 0 runs the no-cache branch, which still requires the past inputs: empty
155
+ // [1, heads, 0, headDim] tensors.
156
+ emptyPast() {
157
+ const { decoder_attention_heads: heads, d_model, decoder_layers } = this.config;
158
+ const empty = new this.ort.Tensor('float32', new Float32Array(0), [
159
+ 1,
160
+ heads,
161
+ 0,
162
+ d_model / heads,
163
+ ]);
164
+ const past = {};
165
+ for (let l = 0; l < decoder_layers; l++) {
166
+ for (const kind of ['decoder.key', 'decoder.value', 'encoder.key', 'encoder.value']) {
167
+ past[`past_key_values.${l}.${kind}`] = empty;
168
+ }
169
+ }
170
+ return past;
171
+ }
172
+ // Special tokens (timestamps, languages, tasks: everything in added_tokens.json but
173
+ // EOT) and generation_config's suppress_tokens; the first sampled token also excludes
174
+ // begin_suppress_tokens (a leading space, EOT).
175
+ suppression(size) {
176
+ if (this.masks?.any.length === size)
177
+ return this.masks;
178
+ const any = new Uint8Array(size);
179
+ const set = (mask, ids) => {
180
+ for (const id of ids)
181
+ if (id >= 0 && id < size)
182
+ mask[id] = 1;
183
+ };
184
+ set(any, this.specialIds);
185
+ set(any, this.gen.suppress_tokens ?? []);
186
+ any[this.gen.eos_token_id] = 0;
187
+ const first = any.slice();
188
+ set(first, this.gen.begin_suppress_tokens ?? []);
189
+ this.masks = { any, first };
190
+ return this.masks;
191
+ }
192
+ }
193
+ function output(out, name) {
194
+ const t = out[name];
195
+ if (!t)
196
+ throw new Error(`Whisper decoder output ${name} is missing`);
197
+ return t;
198
+ }
199
+ function peak(audio) {
200
+ let max = 0;
201
+ for (const v of audio) {
202
+ const a = Math.abs(v);
203
+ if (a > max)
204
+ max = a;
205
+ }
206
+ return max;
207
+ }
208
+ function argmaxUnmasked(logits, mask) {
209
+ let best = -1;
210
+ let bestValue = -Infinity;
211
+ for (let i = 0; i < logits.length; i++) {
212
+ if (mask[i] || !(logits[i] > bestValue))
213
+ continue;
214
+ bestValue = logits[i];
215
+ best = i;
216
+ }
217
+ return best;
218
+ }
219
+ function argmaxOf(logits, ids) {
220
+ let best = ids[0];
221
+ for (const id of ids)
222
+ if (logits[id] > logits[best])
223
+ best = id;
224
+ return best;
225
+ }
226
+ // Splits audio longer than 30 s into consecutive windows of at most 30 s, each cut in
227
+ // the middle of the quietest 0.5 s within its last 5 s, so a cut rarely lands mid-word.
228
+ // The windows are views on `audio` and cover every sample, in order.
229
+ export function splitWindows(audio, rate = SAMPLE_RATE) {
230
+ const max = Math.floor(WINDOW_SECONDS * rate);
231
+ const span = Math.max(1, Math.round(CUT_SPAN_SECONDS * rate));
232
+ const search = Math.round(CUT_SEARCH_SECONDS * rate);
233
+ const windows = [];
234
+ let start = 0;
235
+ while (audio.length - start > max) {
236
+ // Candidate spans [s, s + span) with s + span <= start + max.
237
+ const from = start + max - search;
238
+ const to = start + max - span;
239
+ let energy = 0;
240
+ for (let i = from; i < from + span; i++)
241
+ energy += audio[i] * audio[i];
242
+ let best = from;
243
+ let bestEnergy = energy;
244
+ for (let s = from + 1; s <= to; s++) {
245
+ energy += audio[s + span - 1] * audio[s + span - 1] - audio[s - 1] * audio[s - 1];
246
+ if (energy < bestEnergy - 1e-9) {
247
+ bestEnergy = energy;
248
+ best = s;
249
+ }
250
+ }
251
+ const cut = best + Math.floor(span / 2);
252
+ windows.push(audio.subarray(start, cut));
253
+ start = cut;
254
+ }
255
+ windows.push(audio.subarray(start));
256
+ return windows;
257
+ }
@@ -0,0 +1,5 @@
1
+ /** Parse a RIFF/WAVE file that is exactly what the Whisper engine consumes:
2
+ * 16 kHz, mono, 16-bit integer PCM. Anything else throws a readable Error —
3
+ * the server has no resampler and must never feed garbage to the model. */
4
+ export declare function parseWav16kMono(buf: Uint8Array): Float32Array;
5
+ //# sourceMappingURL=wav.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wav.d.ts","sourceRoot":"","sources":["../../../src/voice/whisper/wav.ts"],"names":[],"mappings":"AAAA;;4EAE4E;AAC5E,wBAAgB,eAAe,CAAC,GAAG,EAAE,UAAU,GAAG,YAAY,CAmC7D"}
@@ -0,0 +1,48 @@
1
+ /** Parse a RIFF/WAVE file that is exactly what the Whisper engine consumes:
2
+ * 16 kHz, mono, 16-bit integer PCM. Anything else throws a readable Error —
3
+ * the server has no resampler and must never feed garbage to the model. */
4
+ export function parseWav16kMono(buf) {
5
+ if (buf.length < 12)
6
+ throw new Error('Not a WAV file: too short.');
7
+ const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
8
+ const tag = (o) => String.fromCharCode(buf[o], buf[o + 1], buf[o + 2], buf[o + 3]);
9
+ if (tag(0) !== 'RIFF' || tag(8) !== 'WAVE')
10
+ throw new Error('Not a WAV file: missing RIFF/WAVE header.');
11
+ let fmt = null;
12
+ let pos = 12;
13
+ while (pos + 8 <= buf.length) {
14
+ const id = tag(pos);
15
+ const size = dv.getUint32(pos + 4, true);
16
+ const body = pos + 8;
17
+ if (id === 'fmt ') {
18
+ if (size < 16 || body + 16 > buf.length)
19
+ throw new Error('Invalid WAV: truncated fmt chunk.');
20
+ fmt = {
21
+ format: dv.getUint16(body, true),
22
+ channels: dv.getUint16(body + 2, true),
23
+ rate: dv.getUint32(body + 4, true),
24
+ bits: dv.getUint16(body + 14, true),
25
+ };
26
+ }
27
+ else if (id === 'data') {
28
+ if (!fmt)
29
+ throw new Error('Invalid WAV: data chunk before fmt chunk.');
30
+ if (fmt.format !== 1)
31
+ throw new Error(`Unsupported WAV: expected integer PCM, got format ${fmt.format}.`);
32
+ if (fmt.bits !== 16)
33
+ throw new Error(`Unsupported WAV: expected 16-bit samples, got ${fmt.bits}-bit.`);
34
+ if (fmt.channels !== 1)
35
+ throw new Error(`Unsupported WAV: expected mono, got ${fmt.channels} channels.`);
36
+ if (fmt.rate !== 16000)
37
+ throw new Error(`Unsupported WAV: expected 16000 Hz, got ${fmt.rate} Hz.`);
38
+ const end = Math.min(body + size, buf.length);
39
+ const n = Math.floor((end - body) / 2);
40
+ const out = new Float32Array(n);
41
+ for (let i = 0; i < n; i++)
42
+ out[i] = dv.getInt16(body + i * 2, true) / 32768;
43
+ return out;
44
+ }
45
+ pos = body + size + (size % 2);
46
+ }
47
+ throw new Error(fmt ? 'Invalid WAV: no data chunk.' : 'Invalid WAV: no fmt chunk.');
48
+ }