@chatpanel/gateway 0.6.109 → 0.7.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 (80) hide show
  1. package/README.md +24 -4
  2. package/bin/chatpanel-gateway-bin.mjs +1 -24
  3. package/bin/chatpanel-gateway.js +3 -97
  4. package/package.json +1 -7
  5. package/src/access-log-store.js +1 -45
  6. package/src/agent.js +2 -256
  7. package/src/anthropic.js +3 -83
  8. package/src/backup-decrypt.js +1 -45
  9. package/src/backup-ingest.js +6 -120
  10. package/src/bridge-supervisor.js +3 -212
  11. package/src/bridge.js +4 -252
  12. package/src/budget.js +1 -117
  13. package/src/config.js +1 -209
  14. package/src/configstore.js +1 -181
  15. package/src/connect-agents.js +22 -179
  16. package/src/diarize-engine.js +1 -188
  17. package/src/egress.js +2 -0
  18. package/src/engine-ledger-store.js +1 -150
  19. package/src/engine.js +1 -132
  20. package/src/entitlement-refresh.js +1 -84
  21. package/src/entitlement.js +1 -76
  22. package/src/extraction.js +4 -294
  23. package/src/freegate.js +1 -47
  24. package/src/gate.js +1 -75
  25. package/src/gateway-token.js +1 -60
  26. package/src/history-store.js +1 -251
  27. package/src/job.js +3 -148
  28. package/src/knowledge.js +3 -215
  29. package/src/local-status.js +6 -102
  30. package/src/log.js +1 -21
  31. package/src/mcp-cli.js +19 -113
  32. package/src/mcp.js +34 -546
  33. package/src/memory-store.js +1 -176
  34. package/src/memory.js +2 -642
  35. package/src/model-integrity.js +1 -82
  36. package/src/model-ledger.js +1 -229
  37. package/src/model-runtime.js +1 -37
  38. package/src/models.js +1 -92
  39. package/src/ner-engine.js +1 -318
  40. package/src/ner.js +1 -113
  41. package/src/observability.js +1 -123
  42. package/src/openai.js +2 -84
  43. package/src/ort.js +1 -52
  44. package/src/parakeet-engine.js +2 -228
  45. package/src/pocket-tts-engine.js +1 -520
  46. package/src/prefs-store.js +1 -149
  47. package/src/project-store.js +1 -139
  48. package/src/project.js +1 -171
  49. package/src/recruit.js +3 -424
  50. package/src/recruiting.js +1 -93
  51. package/src/redact.js +2 -123
  52. package/src/responses.js +2 -80
  53. package/src/router.js +1 -292
  54. package/src/rrf.js +1 -93
  55. package/src/scorecard-store.js +1 -92
  56. package/src/scorecard.js +1 -336
  57. package/src/search-index.js +2 -134
  58. package/src/secure-fetch.js +1 -58
  59. package/src/sentencepiece.js +1 -184
  60. package/src/server.js +10 -2290
  61. package/src/service.js +11 -189
  62. package/src/shape.js +5 -121
  63. package/src/sqlite-store.js +3 -212
  64. package/src/stream.js +5 -182
  65. package/src/structured.js +4 -902
  66. package/src/stt-engine.js +1 -486
  67. package/src/stt-models.js +1 -144
  68. package/src/subject-kinds.js +1 -6
  69. package/src/subject-name.js +1 -97
  70. package/src/team-board.js +6 -338
  71. package/src/team-record.js +1 -226
  72. package/src/team-store.js +1 -261
  73. package/src/team.js +1 -303
  74. package/src/toolrelay.js +3 -122
  75. package/src/tts-engine.js +1 -453
  76. package/src/tts-models.js +1 -254
  77. package/src/tts-remote.js +1 -109
  78. package/src/tts-voice-resolve.js +1 -78
  79. package/src/tts-voices.js +1 -192
  80. package/src/update.js +1 -305
package/src/openai.js CHANGED
@@ -1,85 +1,3 @@
1
- // OpenAI-protocol adapter: /v1/chat/completions (what opencode, codex, aider,
2
- // cursor, and most tools speak). Pulls every redactable text string out of the
3
- // request body as in-place segments, and restores tokens in a non-streaming
4
- // response. (Streaming is restored generically in stream.js.)
1
+ import{restoreText as f}from"@chatpanel/pii";import{segment as c}from"./redact.js";import{restoreDeepAliases as a}from"./stream.js";function g(t){return/\/chat\/completions$/.test(t)||/\/completions$/.test(t)}function p(t,r){if(!r||!t||!Array.isArray(t.messages))return t;const e=t.messages.find(n=>n&&n.role==="system");return e&&typeof e.content=="string"?e.content+=`
5
2
 
6
- import { restoreText } from '@chatpanel/pii';
7
- import { segment } from './redact.js';
8
- import { restoreDeepAliases } from './stream.js';
9
-
10
- export function matches(pathname) {
11
- return /\/chat\/completions$/.test(pathname) || /\/completions$/.test(pathname);
12
- }
13
-
14
- // Append a (non-redacted) instruction to the system prompt — e.g. the placeholder
15
- // note that tells the model placeholders are auto-restored for tools.
16
- export function injectSystemNote(body, note) {
17
- if (!note || !body || !Array.isArray(body.messages)) return body;
18
- const sys = body.messages.find((m) => m && m.role === 'system');
19
- if (sys && typeof sys.content === 'string') sys.content += `\n\n${note}`;
20
- else body.messages.unshift({ role: 'system', content: note });
21
- return body;
22
- }
23
-
24
- // Collect segments from messages[].content (string or multimodal parts). System
25
- // messages are included unless redactSystem is false.
26
- export function collectSegments(body, redactionCfg) {
27
- const segs = [];
28
- const messages = Array.isArray(body?.messages) ? body.messages : [];
29
- for (const m of messages) {
30
- if (!m) continue;
31
- if (m.role === 'system' && redactionCfg.redactSystem === false) continue;
32
- if (typeof m.content === 'string') {
33
- segs.push(segment(() => m.content, (v) => { m.content = v; }));
34
- } else if (Array.isArray(m.content)) {
35
- for (const part of m.content) {
36
- if (part && part.type === 'text' && typeof part.text === 'string') {
37
- segs.push(segment(() => part.text, (v) => { part.text = v; }));
38
- }
39
- }
40
- }
41
- }
42
- return segs;
43
- }
44
-
45
- // Extract the conversation for the bridge backend. OpenAI carries the system
46
- // prompt as a role:'system' message, so we pass messages through as-is.
47
- export function toTurn(body) {
48
- return { messages: Array.isArray(body?.messages) ? body.messages : [], system: '' };
49
- }
50
-
51
- // Tool-relay: the client's tool definitions, and (on a follow-up request) the
52
- // most recent tool result the client sent back.
53
- export function extractTools(body) {
54
- return Array.isArray(body?.tools) ? body.tools : [];
55
- }
56
- export function extractLatestToolResult(body) {
57
- const msgs = Array.isArray(body?.messages) ? body.messages : [];
58
- for (let i = msgs.length - 1; i >= 0; i--) {
59
- const m = msgs[i];
60
- if (m?.role === 'tool' && m.tool_call_id) {
61
- return { tool_call_id: m.tool_call_id, content: typeof m.content === 'string' ? m.content : JSON.stringify(m.content) };
62
- }
63
- }
64
- return null;
65
- }
66
-
67
- // Restore a buffered (non-streaming) response: assistant text + tool-call args.
68
- export function restoreResponse(json, vault, harness = null) {
69
- for (const choice of json?.choices || []) {
70
- const msg = choice?.message;
71
- if (!msg) continue;
72
- // Visible text keeps the pseudonym (restoreText); tool-call args go through the
73
- // shared harness — real values so the client runs the tool on real data, or the
74
- // redacted token kept for remote MCP tools under "redact remote".
75
- if (typeof msg.content === 'string') msg.content = restoreText(msg.content, vault);
76
- for (const tc of msg.tool_calls || []) {
77
- if (tc?.function && typeof tc.function.arguments === 'string') {
78
- tc.function.arguments = harness
79
- ? harness.toTool(tc.function.name, tc.function.arguments)
80
- : restoreDeepAliases(tc.function.arguments, vault);
81
- }
82
- }
83
- }
84
- return json;
85
- }
3
+ ${r}`:t.messages.unshift({role:"system",content:r}),t}function y(t,r){const e=[],n=Array.isArray(t?.messages)?t.messages:[];for(const o of n)if(o&&!(o.role==="system"&&r.redactSystem===!1)){if(typeof o.content=="string")e.push(c(()=>o.content,s=>{o.content=s}));else if(Array.isArray(o.content))for(const s of o.content)s&&s.type==="text"&&typeof s.text=="string"&&e.push(c(()=>s.text,i=>{s.text=i}))}return e}function x(t){return{messages:Array.isArray(t?.messages)?t.messages:[],system:""}}function A(t){return Array.isArray(t?.tools)?t.tools:[]}function _(t){const r=Array.isArray(t?.messages)?t.messages:[];for(let e=r.length-1;e>=0;e--){const n=r[e];if(n?.role==="tool"&&n.tool_call_id)return{tool_call_id:n.tool_call_id,content:typeof n.content=="string"?n.content:JSON.stringify(n.content)}}return null}function h(t,r,e=null){for(const n of t?.choices||[]){const o=n?.message;if(o){typeof o.content=="string"&&(o.content=f(o.content,r));for(const s of o.tool_calls||[])s?.function&&typeof s.function.arguments=="string"&&(s.function.arguments=e?e.toTool(s.function.name,s.function.arguments):a(s.function.arguments,r))}}return t}export{y as collectSegments,_ as extractLatestToolResult,A as extractTools,p as injectSystemNote,g as matches,h as restoreResponse,x as toTurn};
package/src/ort.js CHANGED
@@ -1,52 +1 @@
1
- // One place to get an onnxruntime, for the engines that drive raw ONNX graphs:
2
- // parakeet (STT) and pocket-tts (TTS). Transformers.js brings its own; these do
3
- // not, and they were each resolving it separately.
4
- //
5
- // KNOWN LIMITATION — raw ORT does not work inside the standalone binary.
6
- // The Bun build embeds the ORT runtime as a virtual path (.wasm) and a blob: URL
7
- // (.mjs), and onnxruntime-web reaches for both with fetch(), which serves neither.
8
- // Handing it the wasm BYTES, pointing wasmPaths at an extracted directory, and
9
- // importing the wasm-only bundle were all tried; each moves the failure without
10
- // removing it. Transformers.js works there because it configures its own bundled
11
- // copy through its own env.
12
- //
13
- // This is NOT new — parakeet has had it since it shipped; it simply failed as an
14
- // opaque "no available backend found" instead of saying so. Models that need this
15
- // runtime are now marked `requiresNative` in their catalogs and are not offered on
16
- // the binary, so the npm gateway is the answer rather than a broken download.
17
-
18
- let _promise = null;
19
-
20
- /** Is a raw-ONNX engine usable in this process? False inside the binary. */
21
- export function rawOrtAvailable() {
22
- return !globalThis.__CHATPANEL_WASM_PATHS__;
23
- }
24
-
25
- export function ortRuntimeName() {
26
- return globalThis.__CHATPANEL_WASM_PATHS__ ? 'wasm' : 'native';
27
- }
28
-
29
- // 'wasm' in the binary, 'cpu' on the native build. The wrong one makes ORT fall
30
- // through its provider list and report a confusing "no available backend".
31
- export function ortProviders() {
32
- return globalThis.__CHATPANEL_WASM_PATHS__ ? ['wasm'] : ['cpu'];
33
- }
34
-
35
- export function getOrt() {
36
- if (_promise) return _promise;
37
- _promise = (async () => {
38
- const wasmPaths = globalThis.__CHATPANEL_WASM_PATHS__ || null;
39
- if (!wasmPaths) {
40
- const mod = await import('onnxruntime-node');
41
- return mod.InferenceSession ? mod : (mod.default || mod);
42
- }
43
-
44
- // Say what is actually wrong. ORT's own message describes a failed fetch and
45
- // sends people looking for a corrupt download.
46
- throw new Error(
47
- 'this model needs the native onnxruntime, which the standalone binary does not carry — '
48
- + 'install the npm gateway instead (npm i -g @chatpanel/gateway), or pick a model that runs on the bundled runtime',
49
- );
50
- })();
51
- return _promise;
52
- }
1
+ let n=null;function r(){return!globalThis.__CHATPANEL_WASM_PATHS__}function a(){return globalThis.__CHATPANEL_WASM_PATHS__?"wasm":"native"}function o(){return globalThis.__CHATPANEL_WASM_PATHS__?["wasm"]:["cpu"]}function i(){return n||(n=(async()=>{if(!(globalThis.__CHATPANEL_WASM_PATHS__||null)){const t=await import("onnxruntime-node");return t.InferenceSession?t:t.default||t}throw new Error("this model needs the native onnxruntime, which the standalone binary does not carry — install the npm gateway instead (npm i -g @chatpanel/gateway), or pick a model that runs on the bundled runtime")})(),n)}export{i as getOrt,o as ortProviders,a as ortRuntimeName,r as rawOrtAvailable};
@@ -1,228 +1,2 @@
1
- // In-process speech-to-text — NVIDIA Parakeet TDT (transducer) via onnxruntime.
2
- //
3
- // Whisper (stt-engine.js) is an encoder-DECODER seq2seq model and loads through the
4
- // transformers.js `automatic-speech-recognition` pipeline. Parakeet is a *transducer*
5
- // (Token-and-Duration Transducer / TDT on a FastConformer encoder) — a fundamentally
6
- // different architecture the transformers.js pipeline can't drive (it errors with
7
- // `Unsupported model type "nemo-conformer-tdt"`). So we run the ONNX graphs directly
8
- // on the same onnxruntime the gateway already ships, with a hand-written greedy TDT
9
- // decode loop.
10
- //
11
- // Why bother: Parakeet-TDT-0.6b-v3 is multilingual (25 European languages, auto-
12
- // detected — no forced-language step) and runs ~35× realtime at int8 on CPU, several
13
- // times faster than Whisper at comparable accuracy. It's the fast local-dictation path.
14
- //
15
- // Model layout (istupakov/onnx-asr export, e.g. `istupakov/parakeet-tdt-0.6b-v3-onnx`):
16
- // nemo128.onnx mel preprocessor (waveforms → 128-bin log-mel features)
17
- // encoder-model[.int8].onnx FastConformer encoder (features → [B,D,T'] frames)
18
- // decoder_joint[.int8].onnx fused prediction-net (LSTM) + joint network
19
- // vocab.txt "<piece> <id>" per line; the last line is "<blk> <id>"
20
- //
21
- // This module owns ONE concern: load those graphs and turn 16 kHz mono Float32 PCM
22
- // into text. The streaming/session/redaction/diarization layer lives in stt-engine.js
23
- // and calls us through a tiny adapter, so nothing downstream needs to know the engine.
24
-
25
- import { join } from 'node:path';
26
- import { existsSync, mkdirSync, readFileSync, createWriteStream, renameSync, statSync } from 'node:fs';
27
- import { Readable } from 'node:stream';
28
- import { modelRoot } from './ner-engine.js';
29
- import { getOrt, ortProviders } from './ort.js';
30
-
31
- // transformers.js reports these `model_type`s for the transducer exports. Any of them
32
- // means "not a whisper pipeline model — route here instead".
33
- const TRANSDUCER_MODEL_TYPES = new Set([
34
- 'nemo-conformer-tdt', 'nemo-conformer-rnnt', 'parakeet_tdt', 'parakeet-tdt', 'parakeet_rnnt',
35
- ]);
36
- export function isTransducerModelType(mt) {
37
- return TRANSDUCER_MODEL_TYPES.has(String(mt || '').trim());
38
- }
39
-
40
- // Parakeet ships its own quantizations (standard QDQ/QOperator int8 — NOT whisper's
41
- // block-quantized q8, so it loads on BOTH the native and WASM runtimes). Default to
42
- // int8: ~690 MB total vs ~2.5 GB for fp32, with negligible accuracy loss for ASR.
43
- export const PARAKEET_DEFAULT_DTYPE = 'int8';
44
- export function parakeetDtype(d) {
45
- return d === 'fp32' ? 'fp32' : PARAKEET_DEFAULT_DTYPE; // only int8 | fp32 are exported
46
- }
47
-
48
- // The repo files this engine needs for a given precision. `encoder-model.onnx` (fp32)
49
- // carries its weights in a sibling `.onnx.data` external-data file that ORT loads
50
- // automatically when it sits next to the graph — so we must fetch it too.
51
- function filesFor(dtype) {
52
- const s = parakeetDtype(dtype) === 'fp32' ? '' : '.int8';
53
- const files = ['config.json', 'vocab.txt', 'nemo128.onnx', `encoder-model${s}.onnx`, `decoder_joint-model${s}.onnx`];
54
- if (!s) files.push('encoder-model.onnx.data'); // fp32 external weights
55
- return files;
56
- }
57
-
58
- export function parakeetDir(modelId) {
59
- return join(modelRoot(), ...String(modelId).split('/'));
60
- }
61
-
62
- // Present on disk = every required file exists and is non-empty (a truncated download
63
- // must not read as "installed"). Mirrors stt/ner `modelOnDisk` intent.
64
- export function parakeetOnDisk(modelId, dtype = PARAKEET_DEFAULT_DTYPE) {
65
- const dir = parakeetDir(modelId);
66
- if (!existsSync(dir)) return false;
67
- try {
68
- return filesFor(dtype).every((f) => { const p = join(dir, f); return existsSync(p) && statSync(p).size > 0; });
69
- } catch { return false; }
70
- }
71
-
72
- // ── onnxruntime, matching the gateway's runtime (native npm vs WASM binary) ──────────
73
- // The npm gateway uses native onnxruntime-node (fast). The standalone binary embeds the
74
- // onnxruntime-web WASM runtime and hands us its paths via __CHATPANEL_WASM_PATHS__ (the
75
- // same global ner-engine keys off) — configure ORT-web from it. Memoized once.
76
-
77
- // ── download (only when a model isn't already on disk) ───────────────────────────────
78
- // Custom/BYO STT ids aren't on the dl.chatpanel.net mirror, so — like stt-engine's
79
- // custom path — fetch straight from Hugging Face. Streamed to a .part file then renamed,
80
- // so an interrupted download never looks complete. `onProgress({ file, pct })` drives
81
- // the extension's model-manager UI.
82
- async function downloadFile(modelId, file, dir, { onProgress, log } = {}) {
83
- const url = `https://huggingface.co/${modelId}/resolve/main/${encodeURIComponent(file).replace(/%2F/g, '/')}`;
84
- const res = await fetch(url, { redirect: 'follow' });
85
- if (!res.ok || !res.body) throw new Error(`fetch ${file} → HTTP ${res.status}`);
86
- const total = Number(res.headers.get('content-length')) || 0;
87
- const tmp = join(dir, `${file}.part`);
88
- const out = createWriteStream(tmp);
89
- let got = 0, lastPct = -1;
90
- const src = Readable.fromWeb(res.body);
91
- src.on('data', (chunk) => {
92
- got += chunk.length;
93
- if (total) { const pct = Math.round((got / total) * 100); if (pct !== lastPct) { lastPct = pct; onProgress?.({ file, pct }); } }
94
- });
95
- await new Promise((resolve, reject) => {
96
- src.pipe(out);
97
- out.on('finish', resolve); out.on('error', reject); src.on('error', reject);
98
- });
99
- renameSync(tmp, join(dir, file));
100
- log?.(`[parakeet] fetched ${file}`);
101
- }
102
-
103
- async function ensureFiles(modelId, dtype, { onProgress, log } = {}) {
104
- const dir = parakeetDir(modelId);
105
- mkdirSync(dir, { recursive: true });
106
- for (const file of filesFor(dtype)) {
107
- const dest = join(dir, file);
108
- if (existsSync(dest) && statSync(dest).size > 0) continue;
109
- log?.(`[parakeet] downloading ${file}…`);
110
- await downloadFile(modelId, file, dir, { onProgress, log });
111
- }
112
- return dir;
113
- }
114
-
115
- // ── vocab / detokenize ───────────────────────────────────────────────────────────────
116
- // vocab.txt: "<piece> <id>" per line. SentencePiece marks a word boundary with ▁
117
- // (U+2581); replace it with a space. The final line "<blk> <id>" is the blank/SOS id.
118
- function loadVocab(dir) {
119
- const vocab = [];
120
- let blank = -1;
121
- for (const line of readFileSync(join(dir, 'vocab.txt'), 'utf8').split('\n')) {
122
- if (!line) continue;
123
- const sp = line.lastIndexOf(' ');
124
- if (sp < 0) continue;
125
- const id = parseInt(line.slice(sp + 1), 10);
126
- const tok = line.slice(0, sp);
127
- if (!Number.isFinite(id)) continue;
128
- vocab[id] = tok.replace(/▁/g, ' ');
129
- if (tok === '<blk>') blank = id;
130
- }
131
- if (blank < 0) blank = vocab.length - 1; // fall back to the last id (export convention)
132
- return { vocab, blank };
133
- }
134
-
135
- function argmax(arr, from, to) {
136
- let bi = from, bv = arr[from];
137
- for (let i = from + 1; i < to; i++) if (arr[i] > bv) { bv = arr[i]; bi = i; }
138
- return bi;
139
- }
140
-
141
- const DURATIONS = 5; // TDT duration head bins → advance 0..4 encoder frames
142
- const MAX_SYMBOLS = 10; // cap non-blank emissions per frame (anti-runaway)
143
-
144
- // ── recognizer ───────────────────────────────────────────────────────────────────────
145
- // Loads the three ONNX sessions once; `transcribe()` is stateless per call (fresh LSTM
146
- // state), so it's safe to call for every streaming segment. Serialize calls externally
147
- // (stt-engine already funnels decodes through one chain).
148
- export async function loadRecognizer({ modelId, dtype = PARAKEET_DEFAULT_DTYPE, allowDownload = true, onProgress, log = () => {} }) {
149
- const dt = parakeetDtype(dtype);
150
- const onDisk = parakeetOnDisk(modelId, dt);
151
- if (!onDisk && !allowDownload) throw new Error('model not on disk and downloads disabled');
152
- const dir = onDisk ? parakeetDir(modelId) : await ensureFiles(modelId, dt, { onProgress, log });
153
-
154
- const ort = await getOrt();
155
- const s = dt === 'fp32' ? '' : '.int8';
156
- const opts = { executionProviders: ortProviders(), graphOptimizationLevel: 'all', logSeverityLevel: 3 };
157
- const [prep, encoder, decoder] = await Promise.all([
158
- ort.InferenceSession.create(join(dir, 'nemo128.onnx'), opts),
159
- ort.InferenceSession.create(join(dir, `encoder-model${s}.onnx`), opts),
160
- ort.InferenceSession.create(join(dir, `decoder_joint-model${s}.onnx`), opts),
161
- ]);
162
- const { vocab, blank } = loadVocab(dir);
163
- const VOCAB = blank + 1; // token logits span [0, VOCAB); duration logits follow
164
- const Tensor = ort.Tensor;
165
-
166
- async function transcribe(float32) {
167
- if (!(float32 instanceof Float32Array) || float32.length < 400) return '';
168
- const n = float32.length;
169
-
170
- // 1) mel features (done in-graph — no manual DSP).
171
- const pr = await prep.run({
172
- waveforms: new Tensor('float32', float32, [1, n]),
173
- waveforms_lens: new Tensor('int64', BigInt64Array.from([BigInt(n)]), [1]),
174
- });
175
-
176
- // 2) FastConformer encoder → outputs [1, D, T'] (channels-first, TIME LAST).
177
- const er = await encoder.run({ audio_signal: pr.features, length: pr.features_lens });
178
- const enc = er.outputs;
179
- const [, D, T] = enc.dims;
180
- const encLen = Number(er.encoded_lengths.data[0]);
181
- const ed = enc.data; // element (0,d,t) at index d*T + t
182
-
183
- // 3) greedy TDT decode. Per encoder frame: run the fused prednet+joint on the
184
- // previous token + LSTM state; split the logits into token- and duration-heads.
185
- // Only a NON-BLANK emission appends a token and advances the LSTM state; the
186
- // duration argmax says how many frames to jump (0..4). duration==0 lets us emit
187
- // another symbol at the same frame (up to MAX_SYMBOLS) — this is what makes TDT
188
- // faster than plain RNN-T.
189
- let h = new Float32Array(2 * 640);
190
- let c = new Float32Array(2 * 640);
191
- const tokens = [];
192
- const frame = new Float32Array(D);
193
- let t = 0, emitted = 0;
194
- const guard = encLen * (MAX_SYMBOLS + 1) + 8; // hard stop; the loop always advances, but be safe
195
- for (let iter = 0; t < encLen && iter < guard; iter++) {
196
- for (let d = 0; d < D; d++) frame[d] = ed[d * T + t];
197
- const prev = tokens.length ? tokens[tokens.length - 1] : blank;
198
- const out = await decoder.run({
199
- encoder_outputs: new Tensor('float32', frame, [1, D, 1]),
200
- targets: new Tensor('int32', Int32Array.from([prev]), [1, 1]),
201
- target_length: new Tensor('int32', Int32Array.from([1]), [1]),
202
- input_states_1: new Tensor('float32', h, [2, 1, 640]),
203
- input_states_2: new Tensor('float32', c, [2, 1, 640]),
204
- });
205
- const logits = out.outputs.data;
206
- const tok = argmax(logits, 0, VOCAB);
207
- const durIdx = argmax(logits, VOCAB, VOCAB + DURATIONS) - VOCAB; // 0..4
208
- if (tok !== blank) {
209
- h = out.output_states_1.data; c = out.output_states_2.data; // advance state only on emit
210
- tokens.push(tok);
211
- emitted++;
212
- }
213
- if (durIdx > 0) { t += durIdx; emitted = 0; }
214
- else if (tok === blank || emitted >= MAX_SYMBOLS) { t += 1; emitted = 0; }
215
- // else duration==0 & non-blank & under cap → stay on this frame, emit again
216
- }
217
-
218
- let text = '';
219
- for (const id of tokens) text += vocab[id] ?? '';
220
- return text.replace(/^\s+/, '').replace(/\s+/g, ' ').trimEnd();
221
- }
222
-
223
- function dispose() {
224
- for (const sess of [prep, encoder, decoder]) { try { sess.release?.(); } catch { /* ignore */ } }
225
- }
226
-
227
- return { transcribe, dispose, dtype: dt, dir };
228
- }
1
+ import{join as c}from"node:path";import{existsSync as $,mkdirSync as Z,readFileSync as tt,createWriteStream as et,renameSync as nt,statSync as C}from"node:fs";import{Readable as ot}from"node:stream";import{modelRoot as rt}from"./ner-engine.js";import{getOrt as st,ortProviders as at}from"./ort.js";const ct=new Set(["nemo-conformer-tdt","nemo-conformer-rnnt","parakeet_tdt","parakeet-tdt","parakeet_rnnt"]);function yt(t){return ct.has(String(t||"").trim())}const D="int8";function Y(t){return t==="fp32"?"fp32":D}function V(t){const e=Y(t)==="fp32"?"":".int8",o=["config.json","vocab.txt","nemo128.onnx",`encoder-model${e}.onnx`,`decoder_joint-model${e}.onnx`];return e||o.push("encoder-model.onnx.data"),o}function E(t){return c(rt(),...String(t).split("/"))}function it(t,e=D){const o=E(t);if(!$(o))return!1;try{return V(e).every(s=>{const r=c(o,s);return $(r)&&C(r).size>0})}catch{return!1}}async function ft(t,e,o,{onProgress:s,log:r}={}){const n=`https://huggingface.co/${t}/resolve/main/${encodeURIComponent(e).replace(/%2F/g,"/")}`,a=await fetch(n,{redirect:"follow"});if(!a.ok||!a.body)throw new Error(`fetch ${e} → HTTP ${a.status}`);const i=Number(a.headers.get("content-length"))||0,l=c(o,`${e}.part`),u=et(l);let p=0,h=-1;const m=ot.fromWeb(a.body);m.on("data",g=>{if(p+=g.length,i){const f=Math.round(p/i*100);f!==h&&(h=f,s?.({file:e,pct:f}))}}),await new Promise((g,f)=>{m.pipe(u),u.on("finish",g),u.on("error",f),m.on("error",f)}),nt(l,c(o,e)),r?.(`[parakeet] fetched ${e}`)}async function lt(t,e,{onProgress:o,log:s}={}){const r=E(t);Z(r,{recursive:!0});for(const n of V(e)){const a=c(r,n);$(a)&&C(a).size>0||(s?.(`[parakeet] downloading ${n}…`),await ft(t,n,r,{onProgress:o,log:s}))}return r}function dt(t){const e=[];let o=-1;for(const s of tt(c(t,"vocab.txt"),"utf8").split(`
2
+ `)){if(!s)continue;const r=s.lastIndexOf(" ");if(r<0)continue;const n=parseInt(s.slice(r+1),10),a=s.slice(0,r);Number.isFinite(n)&&(e[n]=a.replace(/▁/g," "),a==="<blk>"&&(o=n))}return o<0&&(o=e.length-1),{vocab:e,blank:o}}function W(t,e,o){let s=e,r=t[e];for(let n=e+1;n<o;n++)t[n]>r&&(r=t[n],s=n);return s}const ut=5,H=10;async function _t({modelId:t,dtype:e=D,allowDownload:o=!0,onProgress:s,log:r=()=>{}}){const n=Y(e),a=it(t,n);if(!a&&!o)throw new Error("model not on disk and downloads disabled");const i=a?E(t):await lt(t,n,{onProgress:s,log:r}),l=await st(),u=n==="fp32"?"":".int8",p={executionProviders:at(),graphOptimizationLevel:"all",logSeverityLevel:3},[h,m,g]=await Promise.all([l.InferenceSession.create(c(i,"nemo128.onnx"),p),l.InferenceSession.create(c(i,`encoder-model${u}.onnx`),p),l.InferenceSession.create(c(i,`decoder_joint-model${u}.onnx`),p)]),{vocab:f,blank:_}=dt(i),x=_+1,d=l.Tensor;async function K(w){if(!(w instanceof Float32Array)||w.length<400)return"";const I=w.length,P=await h.run({waveforms:new d("float32",w,[1,I]),waveforms_lens:new d("int64",BigInt64Array.from([BigInt(I)]),[1])}),O=await m.run({audio_signal:P.features,length:P.features_lens}),R=O.outputs,[,A,q]=R.dims,L=Number(O.encoded_lengths.data[0]),G=R.data;let M=new Float32Array(2*640),N=new Float32Array(2*640);const y=[],z=new Float32Array(A);let b=0,k=0;const J=L*(H+1)+8;for(let S=0;b<L&&S<J;S++){for(let v=0;v<A;v++)z[v]=G[v*q+b];const Q=y.length?y[y.length-1]:_,T=await g.run({encoder_outputs:new d("float32",z,[1,A,1]),targets:new d("int32",Int32Array.from([Q]),[1,1]),target_length:new d("int32",Int32Array.from([1]),[1]),input_states_1:new d("float32",M,[2,1,640]),input_states_2:new d("float32",N,[2,1,640])}),U=T.outputs.data,F=W(U,0,x),j=W(U,x,x+ut)-x;F!==_&&(M=T.output_states_1.data,N=T.output_states_2.data,y.push(F),k++),j>0?(b+=j,k=0):(F===_||k>=H)&&(b+=1,k=0)}let B="";for(const S of y)B+=f[S]??"";return B.replace(/^\s+/,"").replace(/\s+/g," ").trimEnd()}function X(){for(const w of[h,m,g])try{w.release?.()}catch{}}return{transcribe:K,dispose:X,dtype:n,dir:i}}export{D as PARAKEET_DEFAULT_DTYPE,yt as isTransducerModelType,_t as loadRecognizer,E as parakeetDir,Y as parakeetDtype,it as parakeetOnDisk};