@hyperwindmill/caretaker-cli 0.28.0 → 0.30.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 (62) 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/scheduler/telegram.d.ts +27 -0
  4. package/dist/cli/web/scheduler/telegram.d.ts.map +1 -1
  5. package/dist/cli/web/scheduler/telegram.js +133 -78
  6. package/dist/cli/web/scheduler/telegram_media.d.ts +73 -0
  7. package/dist/cli/web/scheduler/telegram_media.d.ts.map +1 -0
  8. package/dist/cli/web/scheduler/telegram_media.js +90 -0
  9. package/dist/cli/web/scheduler/telegram_window.d.ts +68 -0
  10. package/dist/cli/web/scheduler/telegram_window.d.ts.map +1 -0
  11. package/dist/cli/web/scheduler/telegram_window.js +144 -0
  12. package/dist/cli/web/server.d.ts.map +1 -1
  13. package/dist/cli/web/server.js +29 -7
  14. package/dist/cli/web/session_scope.d.ts +11 -0
  15. package/dist/cli/web/session_scope.d.ts.map +1 -0
  16. package/dist/cli/web/session_scope.js +13 -0
  17. package/dist/cli/web/turn_guard.d.ts +9 -0
  18. package/dist/cli/web/turn_guard.d.ts.map +1 -0
  19. package/dist/cli/web/turn_guard.js +18 -0
  20. package/dist/cli/web/voice_builtin.d.ts +3 -0
  21. package/dist/cli/web/voice_builtin.d.ts.map +1 -0
  22. package/dist/cli/web/voice_builtin.js +55 -0
  23. package/dist/cli/web/voice_proxy.d.ts +33 -1
  24. package/dist/cli/web/voice_proxy.d.ts.map +1 -1
  25. package/dist/cli/web/voice_proxy.js +173 -27
  26. package/dist/commands/loader.js +2 -2
  27. package/dist/harness/tools/builtin/index.d.ts.map +1 -1
  28. package/dist/harness/tools/builtin/index.js +4 -0
  29. package/dist/harness/tools/builtin/set_workspace.d.ts +3 -0
  30. package/dist/harness/tools/builtin/set_workspace.d.ts.map +1 -0
  31. package/dist/harness/tools/builtin/set_workspace.js +49 -0
  32. package/dist/plugins/manifest.d.ts +1 -1
  33. package/dist/plugins/manifest.js +1 -1
  34. package/dist/session/store.d.ts +6 -0
  35. package/dist/session/store.d.ts.map +1 -1
  36. package/dist/session/store.js +8 -0
  37. package/dist/session/types.d.ts +4 -0
  38. package/dist/session/types.d.ts.map +1 -1
  39. package/dist/voice/pocket/catalog.d.ts +24 -0
  40. package/dist/voice/pocket/catalog.d.ts.map +1 -0
  41. package/dist/voice/pocket/catalog.js +152 -0
  42. package/dist/voice/pocket/engine.d.ts +17 -0
  43. package/dist/voice/pocket/engine.d.ts.map +1 -0
  44. package/dist/voice/pocket/engine.js +145 -0
  45. package/dist/voice/pocket/inference.d.ts +36 -0
  46. package/dist/voice/pocket/inference.d.ts.map +1 -0
  47. package/dist/voice/pocket/inference.js +228 -0
  48. package/dist/voice/pocket/install.d.ts +54 -0
  49. package/dist/voice/pocket/install.d.ts.map +1 -0
  50. package/dist/voice/pocket/install.js +275 -0
  51. package/dist/voice/pocket/tokenizer.d.ts +42 -0
  52. package/dist/voice/pocket/tokenizer.d.ts.map +1 -0
  53. package/dist/voice/pocket/tokenizer.js +279 -0
  54. package/dist/voice/pocket/voices.d.ts +9 -0
  55. package/dist/voice/pocket/voices.d.ts.map +1 -0
  56. package/dist/voice/pocket/voices.js +88 -0
  57. package/dist/voice/pronunciation.d.ts +16 -0
  58. package/dist/voice/pronunciation.d.ts.map +1 -0
  59. package/dist/voice/pronunciation.js +51 -0
  60. package/dist/webview/standalone.js +1508 -701
  61. package/dist/webview/standalone.js.map +4 -4
  62. package/package.json +3 -3
@@ -0,0 +1,275 @@
1
+ // On-demand installer for the built-in voice: the ONNX runtime (npm registry tarballs,
2
+ // never a package dependency, never `postinstall`) and the per-language Pocket bundles
3
+ // (Hugging Face, pinned revision). Every install goes through a tmp sibling dir + rename
4
+ // and leaves nothing behind on failure.
5
+ //
6
+ // Runtime layout (what `runtimeEntry()` points into):
7
+ // <runtimeDir>/node_modules/onnxruntime-node/{package.json, dist/, bin/napi-v6/<platform>/<arch>/}
8
+ // <runtimeDir>/node_modules/onnxruntime-common/...
9
+ // so `require('onnxruntime-common')` from the binding resolves by plain node resolution.
10
+ import { createHash } from 'node:crypto';
11
+ import { createReadStream, createWriteStream, existsSync } from 'node:fs';
12
+ import { mkdir, rename, rm } from 'node:fs/promises';
13
+ import { dirname, join, resolve, sep } from 'node:path';
14
+ import { createGunzip } from 'node:zlib';
15
+ import { dataDir } from '../../store/json.js';
16
+ import { DEFAULT_PRONUNCIATION } from '../pronunciation.js';
17
+ import { ORT_TARBALLS, ORT_VERSION, POCKET_BASE_URL, POCKET_LANGUAGES, POCKET_REVISION, POCKET_VOICES, } from './catalog.js';
18
+ const REAL_CATALOG = {
19
+ languages: POCKET_LANGUAGES,
20
+ tarballs: ORT_TARBALLS,
21
+ ortVersion: ORT_VERSION,
22
+ revision: POCKET_REVISION,
23
+ baseUrl: POCKET_BASE_URL,
24
+ };
25
+ let cat = REAL_CATALOG;
26
+ export function __setCatalogForTest(c) {
27
+ cat = { ...REAL_CATALOG, ...c };
28
+ }
29
+ let doFetch = (i, init) => fetch(i, init);
30
+ export function __setFetch(f) {
31
+ doFetch = f;
32
+ }
33
+ export function __resetFetch() {
34
+ doFetch = (i, init) => fetch(i, init);
35
+ cat = REAL_CATALOG;
36
+ }
37
+ const runtimeRoot = () => join(dataDir(), 'voice', 'runtime', 'onnxruntime');
38
+ export function runtimeDir() {
39
+ return join(runtimeRoot(), cat.ortVersion);
40
+ }
41
+ /** Absolute path of onnxruntime-node's entry file, for `createRequire(...)`. */
42
+ export function runtimeEntry() {
43
+ return join(runtimeDir(), 'node_modules', 'onnxruntime-node', 'dist', 'index.js');
44
+ }
45
+ export function bundleDir(lang) {
46
+ return join(dataDir(), 'voice', 'pocket', cat.languages[lang].dir, cat.revision);
47
+ }
48
+ const tmpName = (p) => `${p}.tmp-${process.pid}`;
49
+ /** Streams `url` to `dest`, verifying the digest. `expected` is a sha256 hex string or an
50
+ * npm `sha512-<base64>` integrity string. Removes `dest` and throws on any failure. */
51
+ async function* download(url, dest, expected, label, knownBytes) {
52
+ const [algo, want, enc] = expected.startsWith('sha512-')
53
+ ? ['sha512', expected.slice(7), 'base64']
54
+ : ['sha256', expected, 'hex'];
55
+ await mkdir(dirname(dest), { recursive: true });
56
+ const out = createWriteStream(dest);
57
+ const failed = new Promise((_, rej) => out.once('error', rej));
58
+ failed.catch(() => { });
59
+ try {
60
+ const res = await doFetch(url);
61
+ if (!res.ok || !res.body)
62
+ throw new Error(`HTTP ${res.status} for ${url}`);
63
+ const total = Number(res.headers.get('content-length')) || knownBytes;
64
+ const hash = createHash(algo);
65
+ let received = 0;
66
+ let lastYield = 0;
67
+ yield { received, total };
68
+ const reader = res.body.getReader();
69
+ for (;;) {
70
+ const { done, value } = await reader.read();
71
+ if (done)
72
+ break;
73
+ hash.update(value);
74
+ received += value.length;
75
+ if (!out.write(value))
76
+ await Promise.race([new Promise((r) => out.once('drain', () => r())), failed]);
77
+ if (received - lastYield >= 1 << 20) {
78
+ lastYield = received;
79
+ yield { received, total };
80
+ }
81
+ }
82
+ await Promise.race([new Promise((r) => out.end(r)), failed]);
83
+ if (hash.digest(enc) !== want)
84
+ throw new Error(`Integrity check failed for ${label}`);
85
+ yield { received, total: received };
86
+ }
87
+ catch (e) {
88
+ out.destroy();
89
+ await rm(dest, { force: true });
90
+ throw e;
91
+ }
92
+ }
93
+ // ---------------------------------------------------------------- tar
94
+ /** Minimal ustar reader: extracts the regular files `accept` wants (names already stripped
95
+ * of the leading `package/`) under `dest`. Applies pax `path` and GNU long-name entries. */
96
+ async function untar(src, dest, accept) {
97
+ const it = src[Symbol.asyncIterator]();
98
+ let buf = Buffer.alloc(0);
99
+ const fill = async (n) => {
100
+ while (buf.length < n) {
101
+ const r = await it.next();
102
+ if (r.done)
103
+ return false;
104
+ buf = Buffer.concat([buf, r.value]);
105
+ }
106
+ return true;
107
+ };
108
+ const str = (b, o, l) => {
109
+ const s = b.subarray(o, o + l);
110
+ const z = s.indexOf(0);
111
+ return s.subarray(0, z < 0 ? l : z).toString('utf8');
112
+ };
113
+ const skip = async (n) => {
114
+ while (n > 0) {
115
+ if (!(await fill(1)))
116
+ throw new Error('Truncated tar archive');
117
+ const t = Math.min(n, buf.length);
118
+ buf = buf.subarray(t);
119
+ n -= t;
120
+ }
121
+ };
122
+ const root = resolve(dest) + sep;
123
+ let longName = null;
124
+ for (;;) {
125
+ if (!(await fill(512)))
126
+ return;
127
+ const h = buf.subarray(0, 512);
128
+ buf = buf.subarray(512);
129
+ if (h.every((x) => x === 0))
130
+ return;
131
+ const size = parseInt(str(h, 124, 12).trim() || '0', 8);
132
+ const type = String.fromCharCode(h[156] || 48);
133
+ const pad = (512 - (size % 512)) % 512;
134
+ if (type === 'x' || type === 'L') {
135
+ if (!(await fill(size)))
136
+ throw new Error('Truncated tar archive');
137
+ const body = buf.subarray(0, size).toString('utf8');
138
+ buf = buf.subarray(size);
139
+ await skip(pad);
140
+ if (type === 'L')
141
+ longName = body.replace(/\0.*$/s, '');
142
+ else {
143
+ const m = /(?:^|\n)\d+ path=([^\n]*)\n/.exec(body);
144
+ if (m)
145
+ longName = m[1];
146
+ }
147
+ continue;
148
+ }
149
+ let name = longName ?? [str(h, 345, 155), str(h, 0, 100)].filter(Boolean).join('/');
150
+ longName = null;
151
+ name = name.replace(/^package\//, '');
152
+ const wanted = (type === '0' || type === '7') && accept(name);
153
+ if (!wanted) {
154
+ await skip(size + pad);
155
+ continue;
156
+ }
157
+ const target = resolve(dest, name);
158
+ if (!target.startsWith(root))
159
+ throw new Error(`Unsafe path in archive: ${name}`);
160
+ await mkdir(dirname(target), { recursive: true });
161
+ const out = createWriteStream(target);
162
+ const failed = new Promise((_, rej) => out.once('error', rej));
163
+ failed.catch(() => { });
164
+ let left = size;
165
+ while (left > 0) {
166
+ if (!(await fill(1)))
167
+ throw new Error('Truncated tar archive');
168
+ const t = Math.min(left, buf.length);
169
+ const chunk = buf.subarray(0, t);
170
+ buf = buf.subarray(t);
171
+ left -= t;
172
+ if (!out.write(chunk))
173
+ await Promise.race([new Promise((r) => out.once('drain', () => r())), failed]);
174
+ }
175
+ await Promise.race([new Promise((r) => out.end(r)), failed]);
176
+ await skip(pad);
177
+ }
178
+ }
179
+ async function extractTgz(file, dest, accept) {
180
+ const gz = createReadStream(file).pipe(createGunzip());
181
+ await untar(gz, dest, accept);
182
+ }
183
+ // ---------------------------------------------------------------- install
184
+ async function* installRuntime() {
185
+ if (existsSync(runtimeEntry()))
186
+ return;
187
+ const dir = runtimeDir();
188
+ const tmp = tmpName(dir);
189
+ await rm(tmp, { recursive: true, force: true });
190
+ try {
191
+ const bin = `bin/napi-v6/${process.platform}/${process.arch}/`;
192
+ const parts = [
193
+ { key: 'node', pkg: 'onnxruntime-node', accept: (r) => r === 'package.json' || r.startsWith('dist/') || r.startsWith(bin) },
194
+ { key: 'common', pkg: 'onnxruntime-common', accept: (r) => r === 'package.json' || r.startsWith('dist/') },
195
+ ];
196
+ for (const p of parts) {
197
+ const t = cat.tarballs[p.key];
198
+ const tgz = join(tmp, `${p.pkg}.tgz`);
199
+ for await (const g of download(t.url, tgz, t.integrity, p.pkg, 0)) {
200
+ yield { step: 'runtime', file: p.pkg, ...g };
201
+ }
202
+ await extractTgz(tgz, join(tmp, 'node_modules', p.pkg), p.accept);
203
+ await rm(tgz, { force: true });
204
+ }
205
+ await mkdir(dirname(dir), { recursive: true });
206
+ await rm(dir, { recursive: true, force: true });
207
+ await rename(tmp, dir);
208
+ }
209
+ catch (e) {
210
+ await rm(tmp, { recursive: true, force: true });
211
+ throw e;
212
+ }
213
+ }
214
+ async function* installBundle(lang) {
215
+ const dir = bundleDir(lang);
216
+ if (existsSync(dir))
217
+ return;
218
+ const spec = cat.languages[lang];
219
+ const tmp = tmpName(dir);
220
+ await rm(tmp, { recursive: true, force: true });
221
+ try {
222
+ for (const f of spec.files) {
223
+ const url = `${cat.baseUrl}/${cat.revision}/${spec.dir}/${f.name}`;
224
+ for await (const g of download(url, join(tmp, f.name), f.sha256, f.name, f.bytes)) {
225
+ yield { step: 'bundle', file: f.name, ...g };
226
+ }
227
+ }
228
+ await rename(tmp, dir);
229
+ }
230
+ catch (e) {
231
+ await rm(tmp, { recursive: true, force: true });
232
+ throw e;
233
+ }
234
+ }
235
+ export async function* installBuiltinVoice(lang) {
236
+ try {
237
+ if (!cat.languages[lang])
238
+ throw new Error(`Unknown language: ${lang}`);
239
+ yield* installRuntime();
240
+ yield* installBundle(lang);
241
+ yield { step: 'done', status: await builtinVoiceStatus() };
242
+ }
243
+ catch (e) {
244
+ yield { step: 'error', message: e instanceof Error ? e.message : String(e) };
245
+ }
246
+ }
247
+ async function anyBundleInstalled() {
248
+ return Object.keys(cat.languages).some((l) => existsSync(bundleDir(l)));
249
+ }
250
+ /** Removes the language's bundle(s); removes the runtime too once no bundle remains,
251
+ * unless `keepRuntime` (the native binding is loaded in this process: Windows refuses
252
+ * to delete it, and a half-deleted runtime would break reinstalling). */
253
+ export async function deleteBuiltinVoice(lang, opts = {}) {
254
+ await rm(dirname(bundleDir(lang)), { recursive: true, force: true });
255
+ if (!opts.keepRuntime && !(await anyBundleInstalled()))
256
+ await rm(runtimeRoot(), { recursive: true, force: true });
257
+ }
258
+ export async function builtinVoiceStatus() {
259
+ const defaults = {};
260
+ for (const [code, entries] of Object.entries(DEFAULT_PRONUNCIATION)) {
261
+ defaults[code] = entries.map((e) => ({ ...e }));
262
+ }
263
+ return {
264
+ runtime: { installed: existsSync(runtimeEntry()), version: cat.ortVersion },
265
+ languages: Object.entries(cat.languages).map(([id, s]) => ({
266
+ id,
267
+ code: s.code,
268
+ nativeVoice: s.nativeVoice,
269
+ installed: existsSync(bundleDir(id)),
270
+ bytes: s.files.reduce((n, f) => n + f.bytes, 0),
271
+ })),
272
+ voices: [...POCKET_VOICES],
273
+ defaults,
274
+ };
275
+ }
@@ -0,0 +1,42 @@
1
+ type TokenizerJson = {
2
+ model: {
3
+ type: string;
4
+ unk_id: number;
5
+ byte_fallback?: boolean;
6
+ vocab: [string, number][];
7
+ };
8
+ };
9
+ export declare class UnigramTokenizer {
10
+ private readonly pieces;
11
+ private readonly scores;
12
+ private readonly byteIds;
13
+ private readonly unkId;
14
+ private readonly unkScore;
15
+ private readonly maxPieceLen;
16
+ private readonly vocab;
17
+ constructor(json: TokenizerJson);
18
+ encode(text: string): number[];
19
+ private encodeWord;
20
+ decode(ids: readonly number[]): string;
21
+ }
22
+ export type TextPrepConfig = {
23
+ replace_characters?: Record<string, string> | null;
24
+ remove_semicolons: boolean;
25
+ append_terminal_punctuation: boolean;
26
+ capitalize_first_letter: boolean;
27
+ pad_with_spaces_for_short_inputs: boolean;
28
+ max_token_per_chunk: number;
29
+ };
30
+ export declare function prepareTextPrompt(input: string, cfg: TextPrepConfig): {
31
+ text: string;
32
+ framesAfterEosGuess: number;
33
+ };
34
+ export declare function splitIntoChunks(text: string, tok: UnigramTokenizer, cfg: TextPrepConfig): string[];
35
+ export type PreparedChunk = {
36
+ text: string;
37
+ tokenIds: number[];
38
+ framesAfterEos: number;
39
+ };
40
+ export declare function prepareChunks(text: string, tok: UnigramTokenizer, cfg: TextPrepConfig): PreparedChunk[];
41
+ export {};
42
+ //# sourceMappingURL=tokenizer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tokenizer.d.ts","sourceRoot":"","sources":["../../../src/voice/pocket/tokenizer.ts"],"names":[],"mappings":"AASA,KAAK,aAAa,GAAG;IACnB,KAAK,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,aAAa,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAAA;KAAE,CAAC;CAC7F,CAAC;AAEF,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA6B;IACpD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAW;IAClC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAgB;IACxC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAC/B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAW;gBAErB,IAAI,EAAE,aAAa;IAuB/B,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE;IAY9B,OAAO,CAAC,UAAU;IAqDlB,MAAM,CAAC,GAAG,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM;CAyBvC;AAWD,MAAM,MAAM,cAAc,GAAG;IAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAAC;IACnD,iBAAiB,EAAE,OAAO,CAAC;IAC3B,2BAA2B,EAAE,OAAO,CAAC;IACrC,uBAAuB,EAAE,OAAO,CAAC;IACjC,gCAAgC,EAAE,OAAO,CAAC;IAC1C,mBAAmB,EAAE,MAAM,CAAC;CAC7B,CAAC;AAkBF,wBAAgB,iBAAiB,CAC/B,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,cAAc,GAClB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,mBAAmB,EAAE,MAAM,CAAA;CAAE,CAmB/C;AAsDD,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,gBAAgB,EACrB,GAAG,EAAE,cAAc,GAClB,MAAM,EAAE,CAqCV;AAED,MAAM,MAAM,aAAa,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAC;IAAC,cAAc,EAAE,MAAM,CAAA;CAAE,CAAC;AAIzF,wBAAgB,aAAa,CAC3B,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,gBAAgB,EACrB,GAAG,EAAE,cAAc,GAClB,aAAa,EAAE,CAKjB"}
@@ -0,0 +1,279 @@
1
+ // Text front end of a Pocket TTS schema-3 bundle: the HF `tokenizers` Unigram model of
2
+ // tokenizer.json (Prepend "▁" normalizer, Metaspace pre-tokenizer, byte fallback, no
3
+ // post-processor) and upstream's prompt preparation and sentence chunking
4
+ // (pocket_tts/models/text_chunking.py at the bundle's upstream commit), ported literally.
5
+ const SPACE = '▁';
6
+ // HF tokenizers' unigram K_UNK_PENALTY.
7
+ const UNK_PENALTY = 10;
8
+ export class UnigramTokenizer {
9
+ pieces = new Map();
10
+ scores;
11
+ byteIds = [];
12
+ unkId;
13
+ unkScore;
14
+ maxPieceLen;
15
+ vocab;
16
+ constructor(json) {
17
+ const m = json.model;
18
+ if (m.type !== 'Unigram')
19
+ throw new Error(`unsupported tokenizer model: ${m.type}`);
20
+ this.vocab = m.vocab.map(([p]) => p);
21
+ this.scores = m.vocab.map(([, s]) => s);
22
+ this.unkId = m.unk_id;
23
+ this.unkScore = Math.min(...this.scores) - UNK_PENALTY;
24
+ let maxLen = 1;
25
+ m.vocab.forEach(([piece], id) => {
26
+ const byte = /^<0x([0-9A-F]{2})>$/.exec(piece);
27
+ if (byte) {
28
+ this.byteIds[parseInt(byte[1], 16)] = id;
29
+ return;
30
+ }
31
+ // Special pieces (<unk>, <s>, …) are never matched inside text. Divergence from HF,
32
+ // which would split them out as added tokens: irrelevant for speech input.
33
+ if (/^<.*>$/.test(piece) && this.scores[id] === 0)
34
+ return;
35
+ this.pieces.set(piece, id);
36
+ maxLen = Math.max(maxLen, piece.length);
37
+ });
38
+ this.maxPieceLen = maxLen;
39
+ }
40
+ encode(text) {
41
+ if (text === '')
42
+ return [];
43
+ // Prepend normalizer, then Metaspace (spaces -> ▁, no second ▁ since one is there,
44
+ // split before every ▁).
45
+ const normalized = SPACE + text.replace(/ /g, SPACE);
46
+ const ids = [];
47
+ for (const word of normalized.match(/▁[^▁]*|[^▁]+/g) ?? [])
48
+ this.encodeWord(word, ids);
49
+ return ids;
50
+ }
51
+ // Viterbi over one pre-token: maximize the summed piece scores. Positions are UTF-16
52
+ // indices kept on code-point boundaries; ties keep the earlier (shorter) candidate, as HF.
53
+ encodeWord(word, out) {
54
+ const n = word.length;
55
+ const best = new Float64Array(n + 1).fill(-Infinity);
56
+ const from = new Int32Array(n + 1).fill(-1);
57
+ const via = new Int32Array(n + 1).fill(-1);
58
+ best[0] = 0;
59
+ for (let start = 0; start < n; start = nextBoundary(word, start)) {
60
+ const charEnd = nextBoundary(word, start);
61
+ let single = false;
62
+ for (let end = start + 1; end <= Math.min(n, start + this.maxPieceLen); end++) {
63
+ if (end < n && isLowSurrogate(word.charCodeAt(end)))
64
+ continue;
65
+ const id = this.pieces.get(word.slice(start, end));
66
+ if (id === undefined)
67
+ continue;
68
+ const score = best[start] + this.scores[id];
69
+ if (from[end] < 0 || score > best[end]) {
70
+ best[end] = score;
71
+ from[end] = start;
72
+ via[end] = id;
73
+ }
74
+ if (end === charEnd)
75
+ single = true;
76
+ }
77
+ if (!single) {
78
+ const score = best[start] + this.unkScore;
79
+ if (from[charEnd] < 0 || score > best[charEnd]) {
80
+ best[charEnd] = score;
81
+ from[charEnd] = start;
82
+ via[charEnd] = this.unkId;
83
+ }
84
+ }
85
+ }
86
+ // Backtrack; consecutive unknown spans are fused (HF fuse_unk) and then byte-encoded.
87
+ const tokens = [];
88
+ for (let end = n; end > 0; end = from[end]) {
89
+ const id = via[end];
90
+ const text = word.slice(from[end], end);
91
+ const last = tokens[tokens.length - 1];
92
+ if (id === this.unkId && last?.id === this.unkId)
93
+ last.text = text + last.text;
94
+ else
95
+ tokens.push({ id, text });
96
+ }
97
+ for (let i = tokens.length - 1; i >= 0; i--) {
98
+ const t = tokens[i];
99
+ if (t.id !== this.unkId) {
100
+ out.push(t.id);
101
+ continue;
102
+ }
103
+ const bytes = Buffer.from(t.text, 'utf8');
104
+ const byteIds = [...bytes].map((b) => this.byteIds[b]);
105
+ if (byteIds.every((id) => id !== undefined))
106
+ out.push(...byteIds);
107
+ else
108
+ out.push(this.unkId);
109
+ }
110
+ }
111
+ // Decoder chain Metaspace + ByteFallback + Fuse.
112
+ decode(ids) {
113
+ let out = '';
114
+ let bytes = [];
115
+ const flush = () => {
116
+ if (bytes.length === 0)
117
+ return;
118
+ try {
119
+ out += new TextDecoder('utf-8', { fatal: true }).decode(Uint8Array.from(bytes));
120
+ }
121
+ catch {
122
+ out += '�'.repeat(bytes.length);
123
+ }
124
+ bytes = [];
125
+ };
126
+ ids.forEach((id, i) => {
127
+ const piece = this.vocab[id] ?? '';
128
+ const byte = /^<0x([0-9A-F]{2})>$/.exec(piece);
129
+ if (byte) {
130
+ bytes.push(parseInt(byte[1], 16));
131
+ return;
132
+ }
133
+ flush();
134
+ out += i === 0 ? piece.split(SPACE).join('') : piece.split(SPACE).join(' ');
135
+ });
136
+ flush();
137
+ return out;
138
+ }
139
+ }
140
+ function isLowSurrogate(c) {
141
+ return c >= 0xdc00 && c <= 0xdfff;
142
+ }
143
+ function nextBoundary(s, i) {
144
+ return i + 1 < s.length && isLowSurrogate(s.charCodeAt(i + 1)) ? i + 2 : i + 1;
145
+ }
146
+ const TERMINAL = '.!?…';
147
+ const WEAK = ',;:-–—';
148
+ const CLOSERS = '"\'”’)]»';
149
+ // Python str.split() with no argument.
150
+ function pySplit(s) {
151
+ return s.split(/\s+/).filter(Boolean);
152
+ }
153
+ function rstripChars(s, chars) {
154
+ let end = s.length;
155
+ while (end > 0 && chars.includes(s[end - 1]))
156
+ end--;
157
+ return s.slice(0, end);
158
+ }
159
+ // upstream prepare_text_prompt: returns the prompt and the frames-after-EOS guess.
160
+ export function prepareTextPrompt(input, cfg) {
161
+ let text = input.trim();
162
+ const map = cfg.replace_characters ?? {};
163
+ if (Object.keys(map).length > 0) {
164
+ text = pySplit([...text].map((c) => map[c] ?? c).join('')).join(' ');
165
+ text = text.replace(/([.!?…])\s*[,;:]/g, '$1');
166
+ }
167
+ if (text === '')
168
+ throw new Error('Text prompt cannot be empty');
169
+ text = text.replace(/\n/g, ' ').replace(/\r/g, ' ').split(' ').join(' ');
170
+ if (cfg.remove_semicolons)
171
+ text = text.replace(/;/g, ',');
172
+ const framesAfterEosGuess = pySplit(text).length <= 4 ? 3 : 1;
173
+ // Python's `if not text[0].isupper(): upper()` is the same as always upper-casing.
174
+ if (cfg.capitalize_first_letter) {
175
+ const first = String.fromCodePoint(text.codePointAt(0));
176
+ text = first.toUpperCase() + text.slice(first.length);
177
+ }
178
+ if (cfg.append_terminal_punctuation)
179
+ text = ensureTerminalPunctuation(text);
180
+ if (cfg.pad_with_spaces_for_short_inputs && pySplit(text).length < 5)
181
+ text = ' '.repeat(8) + text;
182
+ return { text, framesAfterEosGuess };
183
+ }
184
+ function ensureTerminalPunctuation(text) {
185
+ const core = rstripChars(text, CLOSERS + ' ');
186
+ const closers = text.slice(core.length).trim();
187
+ if (!core || TERMINAL.includes(core[core.length - 1]))
188
+ return text;
189
+ if (WEAK.includes(core[core.length - 1]))
190
+ return rstripChars(core, WEAK + ' ') + '.' + closers;
191
+ return text + '.';
192
+ }
193
+ function isDigit(c) {
194
+ return c !== undefined && /^\p{Nd}$/u.test(c);
195
+ }
196
+ function boundaryIndices(tokens, boundary, tok) {
197
+ const out = [0];
198
+ let previousWasBoundary = false;
199
+ tokens.forEach((t, idx) => {
200
+ if (boundary.has(t)) {
201
+ previousWasBoundary = true;
202
+ return;
203
+ }
204
+ if (previousWasBoundary) {
205
+ let decimal = false;
206
+ if (tok) {
207
+ const prefix = tok.decode(tokens.slice(0, idx));
208
+ const suffix = tok.decode(tokens.slice(idx));
209
+ decimal =
210
+ prefix.length >= 2 &&
211
+ prefix.endsWith('.') &&
212
+ isDigit(prefix[prefix.length - 2]) &&
213
+ isDigit(suffix[0]);
214
+ }
215
+ if (!decimal)
216
+ out.push(idx);
217
+ }
218
+ previousWasBoundary = false;
219
+ });
220
+ out.push(tokens.length);
221
+ return out;
222
+ }
223
+ function segments(tokens, bounds, tok) {
224
+ const out = [];
225
+ for (let i = 0; i < bounds.length - 1; i++) {
226
+ out.push([bounds[i + 1] - bounds[i], tok.decode(tokens.slice(bounds[i], bounds[i + 1]))]);
227
+ }
228
+ return out;
229
+ }
230
+ // upstream split_into_best_sentences.
231
+ export function splitIntoChunks(text, tok, cfg) {
232
+ const prepared = prepareTextPrompt(text, cfg).text.trim();
233
+ const tokens = tok.encode(prepared);
234
+ const sentenceEnd = new Set(tok.encode('.!...?').slice(1));
235
+ const sentences = segments(tokens, boundaryIndices(tokens, sentenceEnd, tok), tok);
236
+ const fallback = new Set(tok.encode(',;:').slice(1));
237
+ const refined = [];
238
+ for (const [count, sentence] of sentences) {
239
+ if (count <= cfg.max_token_per_chunk) {
240
+ refined.push([count, sentence]);
241
+ continue;
242
+ }
243
+ const sub = tok.encode(sentence.trim());
244
+ const parts = segments(sub, boundaryIndices(sub, fallback, null), tok);
245
+ if (parts.length > 1)
246
+ refined.push(...parts);
247
+ else
248
+ refined.push([count, sentence]);
249
+ }
250
+ const chunks = [];
251
+ let current = '';
252
+ let currentCount = 0;
253
+ for (const [count, sentence] of refined) {
254
+ if (current === '') {
255
+ current = sentence;
256
+ currentCount = count;
257
+ }
258
+ else if (currentCount + count > cfg.max_token_per_chunk) {
259
+ chunks.push(current.trim());
260
+ current = sentence;
261
+ currentCount = count;
262
+ }
263
+ else {
264
+ current += ' ' + sentence;
265
+ currentCount += count;
266
+ }
267
+ }
268
+ if (current !== '')
269
+ chunks.push(current.trim());
270
+ return chunks;
271
+ }
272
+ // What the model is fed: every chunk is prepared again (upstream does so in
273
+ // generate_audio_stream) and gets two extra frames after EOS on top of the guess.
274
+ export function prepareChunks(text, tok, cfg) {
275
+ return splitIntoChunks(text, tok, cfg).map((chunk) => {
276
+ const { text: prompt, framesAfterEosGuess } = prepareTextPrompt(chunk, cfg);
277
+ return { text: prompt, tokenIds: tok.encode(prompt), framesAfterEos: framesAfterEosGuess + 2 };
278
+ });
279
+ }
@@ -0,0 +1,9 @@
1
+ export type VoiceTensor = {
2
+ dtype: 'float32' | 'int64';
3
+ dims: number[];
4
+ data: Float32Array | BigInt64Array;
5
+ };
6
+ export type VoiceStates = Map<string, Map<string, VoiceTensor>>;
7
+ export declare function parseVoices(buf: Uint8Array): VoiceStates;
8
+ export declare function padInto(src: VoiceTensor, dims: readonly number[]): Float32Array | BigInt64Array;
9
+ //# sourceMappingURL=voices.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"voices.d.ts","sourceRoot":"","sources":["../../../src/voice/pocket/voices.ts"],"names":[],"mappings":"AAQA,MAAM,MAAM,WAAW,GAAG;IACxB,KAAK,EAAE,SAAS,GAAG,OAAO,CAAC;IAC3B,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,IAAI,EAAE,YAAY,GAAG,aAAa,CAAC;CACpC,CAAC;AAGF,MAAM,MAAM,WAAW,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC;AAIhE,wBAAgB,WAAW,CAAC,GAAG,EAAE,UAAU,GAAG,WAAW,CAkDxD;AAKD,wBAAgB,OAAO,CAAC,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,YAAY,GAAG,aAAa,CAqB/F"}