@chatpanel/gateway 0.6.110 → 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 -2296
  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/ner-engine.js CHANGED
@@ -1,318 +1 @@
1
- // In-process Named Entity Recognition — zero Python, zero second port.
2
- //
3
- // Replaces the old bundled spaCy microservice (a Python venv + uvicorn on :9009)
4
- // with an ONNX transformer model run IN-PROCESS via transformers.js. This is what
5
- // makes the gateway self-contained: nothing to install, no interpreter, no second
6
- // port — the same model runs identically on macOS / Windows / Linux, and offline
7
- // once the weights are on disk.
8
- //
9
- // Accuracy: the default (Xenova/bert-base-NER) matches or beats spaCy's
10
- // en_core_web_sm on PERSON / ORG / LOCATION. Numeric PII (phone/card/SSN) is NOT
11
- // the model's job — the deterministic regex layer in @chatpanel/pii handles that,
12
- // same as before.
13
- //
14
- // Fail-open by design: if the model can't load (e.g. first run with no network and
15
- // no cached weights), the gateway logs one line and runs deterministic-only.
16
-
17
- import os from 'node:os';
18
- import { join } from 'node:path';
19
- import { existsSync, mkdirSync } from 'node:fs';
20
- import { DEFAULT_MODEL, isMirroredModel } from './models.js';
21
- import { isLoopbackHost, isPrivateHost, isMetadataHost } from '@chatpanel/pii';
22
- import { verifyModelWeights } from './model-integrity.js';
23
-
24
- const DEFAULT_MODEL_HOST = 'https://dl.chatpanel.net/models/';
25
-
26
- // Where model weights are fetched from — ChatPanel's own edge-cached CDN by default,
27
- // so a clean install depends only on chatpanel.net. CHATPANEL_MODEL_BASE_URL can
28
- // override it (HF for dev, or an air-gapped LAN mirror) — but that env var is a
29
- // download-redirect vector: an attacker who sets it could serve a malicious ONNX
30
- // model into the runtime. So we VALIDATE the override before trusting it: http(s)
31
- // only, never cloud metadata, and no PLAINTEXT http to a PUBLIC host (a LAN/loopback
32
- // mirror on http is fine — that's the air-gap case). Anything else falls back to the
33
- // signed default and logs loudly. (True per-file checksum verification is the
34
- // remaining H3 step — needs a committed {model→sha256} manifest.)
35
- export function resolveModelHost() {
36
- const raw = process.env.CHATPANEL_MODEL_BASE_URL;
37
- if (!raw) return DEFAULT_MODEL_HOST;
38
- const fallback = (why) => {
39
- console.warn(`[models] ignoring CHATPANEL_MODEL_BASE_URL (${raw}): ${why} — using ${DEFAULT_MODEL_HOST}`);
40
- return DEFAULT_MODEL_HOST;
41
- };
42
- let u;
43
- try { u = new URL(raw); } catch { return fallback('not a valid URL'); }
44
- if (u.protocol !== 'http:' && u.protocol !== 'https:') return fallback(`scheme ${u.protocol} not allowed`);
45
- if (isMetadataHost(u.hostname)) return fallback('points at cloud metadata');
46
- const localish = isLoopbackHost(u.hostname) || isPrivateHost(u.hostname);
47
- if (u.protocol === 'http:' && !localish) return fallback('plaintext http:// to a public host (use https or a LAN/loopback mirror)');
48
- console.warn(`[models] ⚠ model weights will be downloaded from ${u.origin} (CHATPANEL_MODEL_BASE_URL override), not ${DEFAULT_MODEL_HOST}`);
49
- return raw.replace(/\/*$/, '/');
50
- }
51
-
52
- // Must end with '/' (transformers appends the model path template to it).
53
- const MODEL_HOST = resolveModelHost();
54
-
55
- let _state = 'off'; // 'off' | 'loading' | 'downloading' | 'ready' | 'error'
56
- let _model = null; // active model id, e.g. 'Xenova/bert-base-NER'
57
- let _pipe = null; // the loaded token-classification pipeline
58
- let _err = null; // last error message (for /status)
59
- let _initPromise = null; // single-flight init
60
- let _lib = null; // memoized { env, pipeline } from transformers (imported once)
61
- let _progress = null; // { model, file, pct } while a model is downloading, else null
62
-
63
- // Where model weights live ON DISK. A real, writable, persistent user dir — NOT
64
- // inside node_modules (wiped on reinstall, and absent entirely in a compiled
65
- // binary). The settings "download larger models" flow writes here too.
66
- export function modelRoot() {
67
- return process.env.CHATPANEL_MODELS_DIR || join(os.homedir(), '.chatpanel', 'models');
68
- }
69
-
70
- // Is the model already on disk? (q8 = the quantized weights we load.) When present
71
- // we load fully offline — no network, a hard privacy guarantee.
72
- export function modelOnDisk(modelId = _model || DEFAULT_MODEL) {
73
- const dir = join(modelRoot(), ...modelId.split('/'));
74
- return existsSync(join(dir, 'onnx', 'model_quantized.onnx')) || existsSync(join(dir, 'onnx', 'model.onnx'));
75
- }
76
-
77
- export function state() { return _state; }
78
- export function isReady() { return _state === 'ready' && !!_pipe; }
79
-
80
- // Shape the /status `ner` block consumes. `url` is reported by the server as the
81
- // public in-process contract (http://host:port/ner); we expose the model + state.
82
- export function health() {
83
- return {
84
- configured: _state !== 'off',
85
- ok: isReady(),
86
- state: _state,
87
- model: _model,
88
- error: _err,
89
- };
90
- }
91
-
92
- // PER/ORG/LOC/MISC come back as `entity_group`. We hand {value,type} straight to
93
- // @chatpanel/pii, whose normalizeEntities() maps PER->PERSON, ORG->ORG,
94
- // LOC->LOCATION and applies the user's category toggles — one source of truth.
95
- //
96
- // Subword healing: wordpiece tokenizers can occasionally split a name even with
97
- // aggregation on (e.g. "Acme" -> "A" + "##cme"). A leaked "##" fragment or a
98
- // 1-char head would NOT string-match the original text, leaving PII un-redacted.
99
- // So we stitch a `##` continuation back onto the previous same-type span. This is
100
- // belt-and-suspenders — most spans already arrive merged.
101
- export async function detect(text, { signal } = {}) {
102
- if (!isReady()) return [];
103
- if (signal?.aborted) return [];
104
- const src = String(text || '');
105
- const out = await _pipe(src, { aggregation_strategy: 'simple' });
106
- const ents = [];
107
- for (const e of out || []) {
108
- let word = String(e.word ?? '');
109
- const type = e.entity_group ?? e.entity ?? 'ENTITY';
110
- if (word.startsWith('##') && ents.length && ents[ents.length - 1].type === type) {
111
- // Continuation of the previous token (no space): "A" + "##cme Corp".
112
- ents[ents.length - 1].value += word.slice(2);
113
- continue;
114
- }
115
- word = word.replace(/##/g, '').trim();
116
- if (!word) continue;
117
- ents.push({ value: word, type });
118
- }
119
- // Heal subword truncation AFTER merging (expanding before would corrupt a span the
120
- // next "##" token still extends, e.g. "Sure"→"Suresh" then +"sh Kumar"). Then drop
121
- // 1-char noise + dedupe (expansion can make two spans collide).
122
- const seen = new Set();
123
- const out2 = [];
124
- for (const e of ents) {
125
- const value = expandToWord(src, e.value.trim());
126
- if (value.length <= 1) continue;
127
- const k = `${e.type}:${value.toLowerCase()}`;
128
- if (seen.has(k)) continue;
129
- seen.add(k);
130
- out2.push({ value, type: e.type });
131
- }
132
- return out2;
133
- }
134
-
135
- // Grow a detected span to its full surrounding word in the ORIGINAL text. A cased
136
- // model can truncate a name to a subword ("Suresh" → "Sure"), which would leave a
137
- // dangling fragment ("…[[PERSON]]sh") un-redacted — a leak. We extend across word
138
- // characters at both edges so the whole token is captured. Multi-word spans are
139
- // unaffected (their edges are already at spaces).
140
- function expandToWord(text, value) {
141
- if (!value) return value;
142
- const idx = text.indexOf(value);
143
- if (idx < 0) return value;
144
- const isWord = (c) => !!c && /[\p{L}\p{N}'’-]/u.test(c);
145
- let s = idx;
146
- let e = idx + value.length;
147
- while (s > 0 && isWord(text[s - 1])) s--;
148
- while (e < text.length && isWord(text[e])) e++;
149
- return text.slice(s, e);
150
- }
151
-
152
- // Lets @chatpanel/pii's existing `endpoint` detection backend call us with NO real
153
- // HTTP and NO second port: pii POSTs {text}->{entities} to a URL; we intercept by
154
- // being passed as `fetchImpl`, run the model in-process, and return a Response.
155
- // This reuses all of pii's caching / timeout / type-gating untouched.
156
- export async function fetchAdapter(_url, opts = {}) {
157
- let text = '';
158
- try { text = JSON.parse(opts.body || '{}').text || ''; } catch { /* empty */ }
159
- const entities = await detect(text, { signal: opts.signal });
160
- return new Response(JSON.stringify({ entities }), {
161
- status: 200,
162
- headers: { 'content-type': 'application/json' },
163
- });
164
- }
165
-
166
- // Live download progress for the model currently being fetched (or null). The
167
- // extension's model manager polls this. { model, file, pct }.
168
- export function progress() { return _progress; }
169
-
170
- // Import transformers ONCE and configure its env (model dir + WASM in a binary).
171
- // Exported so sibling engines (stt-engine.js) share the same configured lib —
172
- // one env, one cache dir, one WASM setup; never a second copy of this logic.
173
- export async function ensureLib() {
174
- if (_lib) return _lib;
175
- const root = modelRoot();
176
- try { mkdirSync(root, { recursive: true }); } catch { /* best effort */ }
177
-
178
- // In a Bun --compile single-file binary there is no native onnxruntime-node (its
179
- // dylib can't be embedded), so the binary entry embeds the onnxruntime-web WASM
180
- // runtime and hands us its paths via this global. When present we force the WASM
181
- // backend (transformers picks it when it doesn't see a Node env) BEFORE importing
182
- // transformers. The npm/Node path leaves this unset and uses the faster native
183
- // runtime.
184
- const wasmPaths = globalThis.__CHATPANEL_WASM_PATHS__ || null;
185
- if (wasmPaths) {
186
- try { Object.defineProperty(process, 'release', { value: { ...process.release, name: 'bun' }, configurable: true }); } catch { /* ignore */ }
187
- }
188
-
189
- const { env, pipeline, Tensor, AutoModel, AutoProcessor } = await import('@huggingface/transformers');
190
- env.cacheDir = root; // where remote downloads are cached
191
- env.localModelPath = root; // where local loads resolve — same dir, we control it
192
- try { env.remoteHost = MODEL_HOST; } catch { /* optional */ }
193
- try { env.backends.onnx.wasm.numThreads = 1; } catch { /* optional */ }
194
- if (wasmPaths) {
195
- // Single-thread + no proxy + preloaded wasm bytes — avoids the `blob:` ESM-scheme
196
- // failure when ORT-web runs outside a browser.
197
- try { env.backends.onnx.wasm.proxy = false; env.backends.onnx.wasm.wasmPaths = wasmPaths; } catch { /* optional */ }
198
- }
199
- _lib = { env, pipeline, Tensor, AutoModel, AutoProcessor };
200
- return _lib;
201
- }
202
-
203
- // (Re)load a specific model into _pipe. Downloads it first if missing (and allowed).
204
- // Reusable by init() and setModel(). Fail-open: on error, state='error', _pipe stays
205
- // whatever it was (so a failed SWITCH doesn't kill a working detector).
206
- /** @param {string} modelId @param {{ log?: (m: string) => void, allowDownload?: boolean }} [opts] */
207
- async function loadModel(modelId, { log = () => {}, allowDownload = true } = {}) {
208
- const prevPipe = _pipe;
209
- const prevModel = _model;
210
- let lib;
211
- try {
212
- lib = await ensureLib();
213
- } catch (e) {
214
- _state = 'error'; _err = `engine load failed: ${e.message}`;
215
- log(`[ner] transformers.js not available (${e.message}) — deterministic-only`);
216
- return false;
217
- }
218
-
219
- const haveLocal = modelOnDisk(modelId);
220
- // Offline if cached (fast + private); only reach the network when missing.
221
- lib.env.allowRemoteModels = haveLocal ? false : !!allowDownload;
222
- if (!haveLocal && !allowDownload) {
223
- _state = 'error'; _err = 'model not on disk and downloads disabled';
224
- log(`[ner] model ${modelId} not installed and downloads disabled — deterministic-only`);
225
- return false;
226
- }
227
-
228
- // Curated catalog models come from the private dl.chatpanel.net mirror
229
- // (ensureLib set that as remoteHost). A user's BYO id isn't mirrored, so fetch
230
- // it from Hugging Face directly — only for this load, then restore.
231
- const prevHost = lib.env.remoteHost;
232
- // Fetch from Hugging Face when the mirror cannot serve it — a user's own id, or a
233
- // catalogued model that has not been uploaded to the CDN yet (models.js `mirrored`).
234
- // Asking "is it in the catalogue" was the same question only while every catalogued
235
- // model happened to be mirrored, and a catalogued-but-unmirrored one would have 404'd.
236
- const isCustom = !isMirroredModel(modelId);
237
- if (!haveLocal && isCustom) { try { lib.env.remoteHost = 'https://huggingface.co/'; } catch { /* optional */ } }
238
-
239
- _state = haveLocal ? 'loading' : 'downloading';
240
- if (!haveLocal) { _progress = { model: modelId, file: null, pct: 0 }; log(`[ner] downloading model ${modelId} (one-time${isCustom ? ', from Hugging Face' : ''})…`); }
241
-
242
- try {
243
- const progress_callback = (p) => {
244
- if (!p) return;
245
- const pct = typeof p.progress === 'number' ? Math.round(p.progress) : (_progress?.pct ?? 0);
246
- if (p.status === 'progress' || p.status === 'download' || p.status === 'initiate') {
247
- _progress = { model: modelId, file: p.file || _progress?.file || null, pct };
248
- } else if (p.status === 'done' && p.file) {
249
- log(`[ner] fetched ${p.file}`);
250
- }
251
- };
252
- let pipe;
253
- try {
254
- pipe = await lib.pipeline('token-classification', modelId, { dtype: 'q8', progress_callback });
255
- } catch (e) {
256
- // Mirror gap → fall back to Hugging Face (same as stt-engine).
257
- if (haveLocal || isCustom || !allowDownload) throw e;
258
- log(`[ner] mirror fetch failed (${String(e.message).slice(0, 80)}) — retrying from Hugging Face…`);
259
- lib.env.remoteHost = 'https://huggingface.co/';
260
- lib.env.allowRemoteModels = true;
261
- pipe = await lib.pipeline('token-classification', modelId, { dtype: 'q8', progress_callback });
262
- }
263
- // H3: verify freshly-downloaded weights against committed hashes before we trust
264
- // this pipeline. On a mismatch, dispose it (never use its outputs) and let the
265
- // throw fall through to the catch (keeps the previous model / deterministic-only).
266
- // NOTE: transformers downloads+loads in one call, so this runs POST-load — it
267
- // prevents USING and PERSISTING a tampered model, not a hypothetical ORT
268
- // parse-time bug. Warn-and-allow when the model isn't in the hash manifest.
269
- if (!haveLocal) {
270
- try {
271
- verifyModelWeights(modelId, { modelsDir: modelRoot(), log });
272
- } catch (e) {
273
- try { await pipe.dispose?.(); } catch { /* ignore */ }
274
- throw e;
275
- }
276
- }
277
- // Swap in the new pipeline, dispose the old one (free its WASM/native session).
278
- _pipe = pipe; _model = modelId; _state = 'ready'; _err = null; _progress = null;
279
- if (prevPipe && prevPipe !== pipe) { try { await prevPipe.dispose?.(); } catch { /* ignore */ } }
280
- log(`[ner] ready — model ${modelId} (in-process, no Python) — entity detection active`);
281
- return true;
282
- } catch (e) {
283
- _err = e.message; _progress = null;
284
- // Keep any previously-working detector rather than going dark on a bad switch.
285
- if (prevPipe) { _pipe = prevPipe; _model = prevModel; _state = 'ready'; }
286
- else { _state = 'error'; }
287
- log(`[ner] model load failed (${e.message})${prevPipe ? ' — keeping previous model' : ' — deterministic-only'}`);
288
- return false;
289
- } finally {
290
- try { lib.env.remoteHost = prevHost; } catch { /* optional */ } // restore the mirror
291
- }
292
- }
293
-
294
- // Load the default/configured model once at startup. Returns a promise that
295
- // resolves when ready (or after a fail-open error). `cfg` = { model?, allowDownload?, onLog? }.
296
- export function init(cfg = {}) {
297
- if (_initPromise) return _initPromise;
298
- const log = typeof cfg.onLog === 'function' ? cfg.onLog : () => {};
299
- _model = cfg.model || DEFAULT_MODEL;
300
- _state = 'loading';
301
- _initPromise = loadModel(_model, { log, allowDownload: cfg.allowDownload !== false });
302
- return _initPromise;
303
- }
304
-
305
- // Switch to a different model (download it first if needed). Used by the model
306
- // manager. Returns true on success. A failed switch keeps the current detector.
307
- export async function setModel(modelId, opts = {}) {
308
- const log = typeof opts.onLog === 'function' ? opts.onLog : () => {};
309
- const allowDownload = opts.allowDownload !== false;
310
- if (!modelId) return false;
311
- if (modelId === _model && isReady()) return true;
312
- return loadModel(modelId, { log, allowDownload });
313
- }
314
-
315
- // Test hook: reset module state (used by unit tests).
316
- export function _reset() {
317
- _state = 'off'; _model = null; _pipe = null; _err = null; _initPromise = null; _lib = null; _progress = null;
318
- }
1
+ import $ from"node:os";import{join as _}from"node:path";import{existsSync as b,mkdirSync as E}from"node:fs";import{DEFAULT_MODEL as A,isMirroredModel as S}from"./models.js";import{isLoopbackHost as T,isPrivateHost as k,isMetadataHost as D}from"@chatpanel/pii";import{verifyModelWeights as P}from"./model-integrity.js";const L="https://dl.chatpanel.net/models/";function O(){const e=process.env.CHATPANEL_MODEL_BASE_URL;if(!e)return L;const t=s=>(console.warn(`[models] ignoring CHATPANEL_MODEL_BASE_URL (${e}): ${s} — using ${L}`),L);let n;try{n=new URL(e)}catch{return t("not a valid URL")}if(n.protocol!=="http:"&&n.protocol!=="https:")return t(`scheme ${n.protocol} not allowed`);if(D(n.hostname))return t("points at cloud metadata");const o=T(n.hostname)||k(n.hostname);return n.protocol==="http:"&&!o?t("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${n.origin} (CHATPANEL_MODEL_BASE_URL override), not ${L}`),e.replace(/\/*$/,"/"))}const R=O();let u="off",p=null,h=null,m=null,y=null,w=null,d=null;function x(){return process.env.CHATPANEL_MODELS_DIR||_($.homedir(),".chatpanel","models")}function N(e=p||A){const t=_(x(),...e.split("/"));return b(_(t,"onnx","model_quantized.onnx"))||b(_(t,"onnx","model.onnx"))}function Y(){return u}function v(){return u==="ready"&&!!h}function G(){return{configured:u!=="off",ok:v(),state:u,model:p,error:m}}async function C(e,{signal:t}={}){if(!v())return[];if(t?.aborted)return[];const n=String(e||""),o=await h(n,{aggregation_strategy:"simple"}),s=[];for(const f of o||[]){let l=String(f.word??"");const c=f.entity_group??f.entity??"ENTITY";if(l.startsWith("##")&&s.length&&s[s.length-1].type===c){s[s.length-1].value+=l.slice(2);continue}l=l.replace(/##/g,"").trim(),l&&s.push({value:l,type:c})}const r=new Set,i=[];for(const f of s){const l=U(n,f.value.trim());if(l.length<=1)continue;const c=`${f.type}:${l.toLowerCase()}`;r.has(c)||(r.add(c),i.push({value:l,type:f.type}))}return i}function U(e,t){if(!t)return t;const n=e.indexOf(t);if(n<0)return t;const o=i=>!!i&&/[\p{L}\p{N}'’-]/u.test(i);let s=n,r=n+t.length;for(;s>0&&o(e[s-1]);)s--;for(;r<e.length&&o(e[r]);)r++;return e.slice(s,r)}async function K(e,t={}){let n="";try{n=JSON.parse(t.body||"{}").text||""}catch{}const o=await C(n,{signal:t.signal});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function Q(){return d}async function W(){if(w)return w;const e=x();try{E(e,{recursive:!0})}catch{}const t=globalThis.__CHATPANEL_WASM_PATHS__||null;if(t)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}const{env:n,pipeline:o,Tensor:s,AutoModel:r,AutoProcessor:i}=await import("@huggingface/transformers");n.cacheDir=e,n.localModelPath=e;try{n.remoteHost=R}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(t)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=t}catch{}return w={env:n,pipeline:o,Tensor:s,AutoModel:r,AutoProcessor:i},w}async function M(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=h,s=p;let r;try{r=await W()}catch(c){return u="error",m=`engine load failed: ${c.message}`,t(`[ner] transformers.js not available (${c.message}) — deterministic-only`),!1}const i=N(e);if(r.env.allowRemoteModels=i?!1:!!n,!i&&!n)return u="error",m="model not on disk and downloads disabled",t(`[ner] model ${e} not installed and downloads disabled — deterministic-only`),!1;const f=r.env.remoteHost,l=!S(e);if(!i&&l)try{r.env.remoteHost="https://huggingface.co/"}catch{}u=i?"loading":"downloading",i||(d={model:e,file:null,pct:0},t(`[ner] downloading model ${e} (one-time${l?", from Hugging Face":""})…`));try{const c=a=>{if(!a)return;const H=typeof a.progress=="number"?Math.round(a.progress):d?.pct??0;a.status==="progress"||a.status==="download"||a.status==="initiate"?d={model:e,file:a.file||d?.file||null,pct:H}:a.status==="done"&&a.file&&t(`[ner] fetched ${a.file}`)};let g;try{g=await r.pipeline("token-classification",e,{dtype:"q8",progress_callback:c})}catch(a){if(i||l||!n)throw a;t(`[ner] mirror fetch failed (${String(a.message).slice(0,80)}) — retrying from Hugging Face…`),r.env.remoteHost="https://huggingface.co/",r.env.allowRemoteModels=!0,g=await r.pipeline("token-classification",e,{dtype:"q8",progress_callback:c})}if(!i)try{P(e,{modelsDir:x(),log:t})}catch(a){try{await g.dispose?.()}catch{}throw a}if(h=g,p=e,u="ready",m=null,d=null,o&&o!==g)try{await o.dispose?.()}catch{}return t(`[ner] ready — model ${e} (in-process, no Python) — entity detection active`),!0}catch(c){return m=c.message,d=null,o?(h=o,p=s,u="ready"):u="error",t(`[ner] model load failed (${c.message})${o?" — keeping previous model":" — deterministic-only"}`),!1}finally{try{r.env.remoteHost=f}catch{}}}function V(e={}){if(y)return y;const t=typeof e.onLog=="function"?e.onLog:()=>{};return p=e.model||A,u="loading",y=M(p,{log:t,allowDownload:e.allowDownload!==!1}),y}async function X(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{},o=t.allowDownload!==!1;return e?e===p&&v()?!0:M(e,{log:n,allowDownload:o}):!1}function Z(){u="off",p=null,h=null,m=null,y=null,w=null,d=null}export{Z as _reset,C as detect,W as ensureLib,K as fetchAdapter,G as health,V as init,v as isReady,N as modelOnDisk,x as modelRoot,Q as progress,O as resolveModelHost,X as setModel,Y as state};
package/src/ner.js CHANGED
@@ -1,113 +1 @@
1
- // Managed in-process NER. When cfg.ner.autostart is on, launching the gateway
2
- // loads the bundled ONNX entity detector (./ner-engine.js) and flips redaction to
3
- // full tier once it's ready — name/org redaction with a single command, no second
4
- // process, no second port, no Python.
5
- //
6
- // Fail-open by design: if the model can't load (e.g. first run, no network, no
7
- // cached weights), we log a one-line hint and the gateway keeps running with
8
- // deterministic-only redaction. redact.js consults the engine directly, so we do
9
- // NOT mutate cfg.redaction.detection here (that field is reserved for a user's own
10
- // external detector, which takes precedence — see below).
11
- //
12
- // `ensureNer` (bottom) is the same thing on demand, for the case autostart cannot cover:
13
- // a config that says autostart:false, weights already on disk, and a client asking for
14
- // detection right now.
15
-
16
- import * as engine from './ner-engine.js';
17
- import { persistConfig, configPath } from './configstore.js';
18
-
19
- export function startNer(cfg) {
20
- const n = cfg.ner;
21
- if (!n || !n.autostart) return null;
22
-
23
- // Migration: versions <0.6 persisted redaction.detection → the bundled spaCy
24
- // server on :9009 (now removed). That's NOT a user's external detector — left in
25
- // place it makes us skip the new in-process engine and probe a dead port. Clear
26
- // it (and the dead ner.port) so the engine loads, and persist the cleanup.
27
- const d = cfg.redaction?.detection;
28
- if (d && d.url && /127\.0\.0\.1:9009\/ner/.test(d.url)) {
29
- cfg.redaction.detection = { backend: 'off' };
30
- if (cfg.ner) delete cfg.ner.port;
31
- try { persistConfig(cfg, configPath()); } catch { /* best effort */ }
32
- console.log('[ner] migrated legacy spaCy detector config (:9009) → in-process engine');
33
- }
34
-
35
- // Respect a USER-configured external detector (a custom NER endpoint or a local
36
- // LLM): don't load the bundled engine — just apply the full-tier bump so their
37
- // detector is actually used.
38
- const det = cfg.redaction?.detection;
39
- if (det && det.backend && det.backend !== 'off') {
40
- if (n.enableFullTier && cfg.redaction.tier !== 'full') cfg.redaction.tier = 'full';
41
- console.log(`[ner] using configured detector (${det.backend} ${det.url || ''}) — full tier ${cfg.redaction.tier === 'full' ? 'on' : 'off'}`);
42
- return null;
43
- }
44
-
45
- let stopped = false;
46
- engine.init({
47
- model: n.model,
48
- allowDownload: n.allowDownload !== false,
49
- onLog: (m) => { if (!stopped) console.log(m); },
50
- }).then(() => {
51
- if (stopped) return;
52
- if (engine.isReady() && n.enableFullTier && cfg.redaction.tier !== 'full') {
53
- cfg.redaction.tier = 'full';
54
- console.log(`[ner] full tier on — name/org redaction active`);
55
- }
56
- }).catch((e) => { if (!stopped) console.log(`[ner] init error (${e.message}) — deterministic-only`); });
57
-
58
- // Nothing to kill (no child process); just stop logging after shutdown.
59
- return { stop() { stopped = true; } };
60
- }
61
-
62
- /**
63
- * START THE BUNDLED DETECTOR BECAUSE SOMEONE ASKED FOR DETECTION.
64
- *
65
- * `startNer` only runs at boot, and only when `ner.autostart` is on. Everything after that
66
- * assumed the engine was either running or deliberately not wanted — so a config carrying
67
- * `autostart:false` (older gateways wrote it, and it survives every upgrade) left POST /ner
68
- * answering 503 forever, with the weights sitting on disk the whole time. The extension's
69
- * composer showed "name detection is not answering", and every real turn quietly fell back
70
- * to deterministic-only redaction: names, organisations and places went to the model in full.
71
- *
72
- * A request for entity detection IS the intent to detect, so this starts the engine on that
73
- * request instead of waiting for a restart the user has no reason to perform.
74
- *
75
- * Two limits keep it from being a surprise. It never DOWNLOADS: weights arrive through the
76
- * model manager, which shows progress, so a preview keystroke can never kick off a hundred
77
- * megabytes. And it defers to a user's own external detector exactly as `startNer` does —
78
- * that field means "use mine", not "use mine if it happens to be up".
79
- *
80
- * Returns the engine state after the attempt; never throws.
81
- */
82
- export async function ensureNer(cfg, { log = (m) => console.log(m) } = {}) {
83
- const det = cfg?.redaction?.detection;
84
- if (det && det.backend && det.backend !== 'off') return 'external';
85
-
86
- const st = engine.state();
87
- if (st === 'ready') return st;
88
- // A load already in flight (or one that already failed) — join it rather than starting a
89
- // second one. engine.init() is single-flight, so this is just the wait.
90
- if (st === 'loading' || st === 'downloading' || st === 'error') {
91
- try { await engine.init(); } catch { /* fail-open: deterministic-only */ }
92
- return engine.state();
93
- }
94
-
95
- const n = cfg?.ner || {};
96
- const model = n.model || undefined;
97
- if (!engine.modelOnDisk(model)) return 'not-downloaded';
98
-
99
- try {
100
- await engine.init({ model, allowDownload: false, onLog: log });
101
- } catch (e) {
102
- log(`[ner] on-demand load failed (${e.message}) — deterministic-only`);
103
- return engine.state();
104
- }
105
- if (engine.isReady()) {
106
- log(`[ner] started on demand — model ${engine.health().model} — entity detection active`);
107
- if (n.enableFullTier !== false && cfg.redaction && cfg.redaction.tier !== 'full') {
108
- cfg.redaction.tier = 'full';
109
- log('[ner] full tier on — name/org redaction active');
110
- }
111
- }
112
- return engine.state();
113
- }
1
+ import*as o from"./ner-engine.js";import{persistConfig as d,configPath as c}from"./configstore.js";function u(e){const n=e.ner;if(!n||!n.autostart)return null;const r=e.redaction?.detection;if(r&&r.url&&/127\.0\.0\.1:9009\/ner/.test(r.url)){e.redaction.detection={backend:"off"},e.ner&&delete e.ner.port;try{d(e,c())}catch{}console.log("[ner] migrated legacy spaCy detector config (:9009) → in-process engine")}const t=e.redaction?.detection;if(t&&t.backend&&t.backend!=="off")return n.enableFullTier&&e.redaction.tier!=="full"&&(e.redaction.tier="full"),console.log(`[ner] using configured detector (${t.backend} ${t.url||""}) — full tier ${e.redaction.tier==="full"?"on":"off"}`),null;let i=!1;return o.init({model:n.model,allowDownload:n.allowDownload!==!1,onLog:l=>{i||console.log(l)}}).then(()=>{i||o.isReady()&&n.enableFullTier&&e.redaction.tier!=="full"&&(e.redaction.tier="full",console.log("[ner] full tier on — name/org redaction active"))}).catch(l=>{i||console.log(`[ner] init error (${l.message}) — deterministic-only`)}),{stop(){i=!0}}}async function f(e,{log:n=r=>console.log(r)}={}){const r=e?.redaction?.detection;if(r&&r.backend&&r.backend!=="off")return"external";const t=o.state();if(t==="ready")return t;if(t==="loading"||t==="downloading"||t==="error"){try{await o.init()}catch{}return o.state()}const i=e?.ner||{},l=i.model||void 0;if(!o.modelOnDisk(l))return"not-downloaded";try{await o.init({model:l,allowDownload:!1,onLog:n})}catch(a){return n(`[ner] on-demand load failed (${a.message}) — deterministic-only`),o.state()}return o.isReady()&&(n(`[ner] started on demand — model ${o.health().model} — entity detection active`),i.enableFullTier!==!1&&e.redaction&&e.redaction.tier!=="full"&&(e.redaction.tier="full",n("[ner] full tier on — name/org redaction active"))),o.state()}export{f as ensureNer,u as startNer};
@@ -1,123 +1 @@
1
- // VENDORED from @chatpanel/events/observability.js — edit there, then copy over.
2
- // The gateway keeps its dependency surface small; this one pure module is copied in
3
- // rather than pulling the whole events package, the same way the bridge vendors its
4
- // events files. Source of truth: chatpanel-events/observability.js.
5
- // observability.js — the contract for "who consumed what, when, and how much is stored".
6
- //
7
- // ChatPanel's data is reachable by more than one agent now: the side panel, and any CLI
8
- // (Codex, Claude Code, OpenCode…) wired to the gateway's MCP server. Once several agents
9
- // read your history and skills, you need to SEE that — which agent touched what, and how
10
- // much sits in each storage tier. That is one question with one answer shape, so it lives
11
- // here, not re-derived in every client. The extension renders it; the gateway records it;
12
- // a desktop/mobile app will do both against this same contract.
13
- //
14
- // Pure and dependency-free (the @chatpanel/events rule): identical code in browser ESM,
15
- // the gateway (Node) and a mobile JS runtime. No clock, no storage, no platform APIs —
16
- // the caller passes `ts`; the caller owns persistence.
17
- //
18
- // PRIVACY IS THE POINT of the redactor below. An access log that stored raw tool arguments
19
- // would quietly become a second copy of every search query — the exact PII we redact
20
- // everywhere else. So the note attached to each event is built from a per-tool WHITELIST of
21
- // non-sensitive fields; a search query's TEXT is never recorded, only that a search ran.
22
-
23
- export const ACCESS_LOG_VERSION = 1;
24
-
25
- // Default ring size — enough to see a working session's activity without unbounded growth.
26
- export const ACCESS_LOG_MAX = 500;
27
-
28
- // Per-tool whitelist: which argument fields are safe to keep in the human note. Anything not
29
- // listed here is dropped. Content-bearing fields (a search `query`) are deliberately ABSENT —
30
- // the tool name already says "a search happened"; the words searched are not logged.
31
- const SAFE_ARGS = {
32
- // Metadata filters are safe to keep (they are not content) and useful to see in the log:
33
- // "type=meeting since=7d". The search QUERY is deliberately absent — never recorded.
34
- search_history: ['type', 'since', 'before', 'limit', 'offset'],
35
- list_history: ['limit', 'offset'],
36
- get_record: ['id', 'maxChars', 'offset'], // opaque record id + paging, not content
37
- find_related: ['id', 'limit'], // graph navigation from an opaque id
38
- open_skill: ['skill'], // skill names are catalog identifiers, not PII
39
- read_skill_file: ['skill', 'path'],
40
- list_skills: ['limit'],
41
- };
42
-
43
- /**
44
- * A short, SAFE descriptor of a call's arguments for display. Never returns content that
45
- * could carry PII. Unknown tools get an empty note (the tool name is the only signal).
46
- */
47
- export function redactAccessArgs(tool, args) {
48
- const allow = SAFE_ARGS[tool];
49
- if (!allow || !args || typeof args !== 'object') return '';
50
- const parts = [];
51
- for (const key of allow) {
52
- const v = args[key];
53
- if (v === undefined || v === null || v === '') continue;
54
- // Cap any string field so a long id/path can't smuggle content or blow up the row.
55
- const s = typeof v === 'string' ? (v.length > 80 ? `${v.slice(0, 77)}…` : v) : String(v);
56
- parts.push(`${key}=${s}`);
57
- }
58
- return parts.join(' ');
59
- }
60
-
61
- /**
62
- * Normalize one access into the record everything stores and renders. `client` is the calling
63
- * agent's self-reported name (MCP clientInfo) — untrusted, so it's coerced to a short string.
64
- */
65
- export function makeAccessEvent({ ts, client, tool, ok = true, ms, args, error } = {}) {
66
- return {
67
- v: ACCESS_LOG_VERSION,
68
- ts: Number(ts) || 0,
69
- client: shortStr(client, 'unknown', 60),
70
- tool: shortStr(tool, 'unknown', 60),
71
- ok: !!ok,
72
- ms: Number.isFinite(ms) ? Math.max(0, Math.round(ms)) : null,
73
- note: redactAccessArgs(tool, args),
74
- error: error ? shortStr(error, '', 200) : '',
75
- };
76
- }
77
-
78
- function shortStr(v, fallback, max) {
79
- const s = (v == null ? '' : String(v)).trim() || fallback;
80
- return s.length > max ? `${s.slice(0, max - 1)}…` : s;
81
- }
82
-
83
- /**
84
- * A tiny fixed-capacity ring for access events. Pure and synchronous — the gateway keeps one
85
- * in memory and snapshots it for the dashboard; the caller decides whether/how to persist.
86
- */
87
- export function createAccessLog(max = ACCESS_LOG_MAX) {
88
- const cap = Math.max(1, max | 0);
89
- let buf = [];
90
- return {
91
- push(evt) { buf.push(evt); if (buf.length > cap) buf = buf.slice(buf.length - cap); return evt; },
92
- // Newest first, optionally limited — the order a dashboard wants.
93
- snapshot(limit) { const out = buf.slice().reverse(); return limit ? out.slice(0, limit) : out; },
94
- get size() { return buf.length; },
95
- clear() { buf = []; },
96
- };
97
- }
98
-
99
- // ── Storage tiers ────────────────────────────────────────────────────────────────────────
100
- // One descriptor per place data lives: hot (browser), warm (local gateway), cold (cloud,
101
- // future). The dashboard renders a row per tier; a tier that isn't configured says so.
102
-
103
- export function makeStorageTier({ tier, label, present = true, records = null, bytes = null, newest = null, note = '' } = {}) {
104
- return {
105
- tier: String(tier || ''),
106
- label: String(label || tier || ''),
107
- present: !!present,
108
- records: records == null ? null : Math.max(0, records | 0),
109
- bytes: bytes == null ? null : Math.max(0, Number(bytes) || 0),
110
- newest: newest == null ? null : Number(newest) || 0,
111
- note: String(note || ''),
112
- };
113
- }
114
-
115
- /** Human-friendly byte size. Binary units, one decimal above KB. */
116
- export function formatBytes(n) {
117
- const b = Number(n);
118
- if (!Number.isFinite(b) || b <= 0) return '0 B';
119
- const units = ['B', 'KB', 'MB', 'GB', 'TB'];
120
- let i = 0, v = b;
121
- while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }
122
- return `${i === 0 ? Math.round(v) : v.toFixed(1)} ${units[i]}`;
123
- }
1
+ const f=1,a=500,u={search_history:["type","since","before","limit","offset"],list_history:["limit","offset"],get_record:["id","maxChars","offset"],find_related:["id","limit"],open_skill:["skill"],read_skill_file:["skill","path"],list_skills:["limit"]};function c(l,n){const t=u[l];if(!t||!n||typeof n!="object")return"";const e=[];for(const r of t){const i=n[r];if(i==null||i==="")continue;const s=typeof i=="string"?i.length>80?`${i.slice(0,77)}…`:i:String(i);e.push(`${r}=${s}`)}return e.join(" ")}function h({ts:l,client:n,tool:t,ok:e=!0,ms:r,args:i,error:s}={}){return{v:1,ts:Number(l)||0,client:o(n,"unknown",60),tool:o(t,"unknown",60),ok:!!e,ms:Number.isFinite(r)?Math.max(0,Math.round(r)):null,note:c(t,i),error:s?o(s,"",200):""}}function o(l,n,t){const e=(l==null?"":String(l)).trim()||n;return e.length>t?`${e.slice(0,t-1)}…`:e}function p(l=500){const n=Math.max(1,l|0);let t=[];return{push(e){return t.push(e),t.length>n&&(t=t.slice(t.length-n)),e},snapshot(e){const r=t.slice().reverse();return e?r.slice(0,e):r},get size(){return t.length},clear(){t=[]}}}function S({tier:l,label:n,present:t=!0,records:e=null,bytes:r=null,newest:i=null,note:s=""}={}){return{tier:String(l||""),label:String(n||l||""),present:!!t,records:e==null?null:Math.max(0,e|0),bytes:r==null?null:Math.max(0,Number(r)||0),newest:i==null?null:Number(i)||0,note:String(s||"")}}function m(l){const n=Number(l);if(!Number.isFinite(n)||n<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let e=0,r=n;for(;r>=1024&&e<t.length-1;)r/=1024,e++;return`${e===0?Math.round(r):r.toFixed(1)} ${t[e]}`}export{a as ACCESS_LOG_MAX,f as ACCESS_LOG_VERSION,p as createAccessLog,m as formatBytes,h as makeAccessEvent,S as makeStorageTier,c as redactAccessArgs};