@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
@@ -1,58 +1 @@
1
- // Node-side SSRF-hardened fetch (M1). The shared @chatpanel/pii/net.js classifier is
2
- // browser-safe and can only match on the URL's HOSTNAME string — so a public name
3
- // whose A/AAAA record resolves to a private/metadata IP (DNS-rebinding at the fetch
4
- // layer) slips past it. Node CAN resolve DNS, so here we additionally validate every
5
- // RESOLVED address against the same policy, and revalidate on each redirect hop.
6
- //
7
- // Policy defaults to the ENDPOINT context (loopback + LAN allowed — Ollama / a LAN
8
- // model box are legitimate gateway upstreams — but cloud metadata never). So in
9
- // practice the DNS check blocks a hostname that resolves to cloud metadata; the
10
- // redirect revalidation blocks a public upstream that 3xx-redirects to a blocked host.
11
- //
12
- // Residual (documented): we validate the resolved IPs but do NOT pin the socket to
13
- // them, so a sub-second TOCTOU window between lookup and connect remains. Closing it
14
- // fully needs a custom undici dispatcher; the resolved-IP check already removes the
15
- // easy DNS-rebinding cases, which is the point of M1.
16
-
17
- import { lookup as dnsLookup } from 'node:dns/promises';
18
- import { assertEndpointUrl, isBlockedHost } from '@chatpanel/pii';
19
-
20
- const ENDPOINT_POLICY = { allowLoopback: true, allowPrivate: true };
21
- const isLiteralIp = (h) => /^\d{1,3}(\.\d{1,3}){3}$/.test(h) || h.includes(':');
22
-
23
- // Reject if ANY resolved address is blocked under `policy`. A literal-IP host is
24
- // already covered by the URL check, so skip DNS for it. A resolution failure is left
25
- // for fetch() to surface (don't mask a real network error as a security error).
26
- async function assertResolvedIps(hostname, policy, lookupFn) {
27
- if (isLiteralIp(hostname)) return;
28
- let addrs;
29
- try { addrs = await lookupFn(hostname, { all: true }); } catch { return; }
30
- for (const { address } of addrs) {
31
- if (isBlockedHost(address, policy)) {
32
- throw new Error(`refusing to reach ${hostname} — it resolves to a blocked address (${address})`);
33
- }
34
- }
35
- }
36
-
37
- // secureFetch(url, { policy?, maxRedirects?, lookupFn?, fetchFn?, ...init })
38
- // Validates the URL (scheme + host policy) AND its resolved IPs before each request,
39
- // following redirects manually so every hop is re-checked. Returns the final Response.
40
- // `...init` forwards any standard fetch options (method, headers, body, signal, …).
41
- /**
42
- * @param {string|URL} url
43
- * @param {any} [opts]
44
- */
45
- export async function secureFetch(url, {
46
- policy = ENDPOINT_POLICY, maxRedirects = 5, lookupFn = dnsLookup, fetchFn = fetch, ...init
47
- } = {}) {
48
- let current = assertEndpointUrl(url, policy);
49
- for (let hop = 0; ; hop++) {
50
- await assertResolvedIps(current.hostname, policy, lookupFn);
51
- const res = await fetchFn(current.toString(), { ...init, redirect: 'manual' });
52
- const loc = res.status >= 300 && res.status < 400 ? res.headers.get('location') : null;
53
- if (!loc) return res;
54
- if (hop >= maxRedirects) throw new Error('too many redirects');
55
- current = assertEndpointUrl(new URL(loc, current).toString(), policy); // revalidate the hop
56
- try { res.body?.cancel?.(); } catch { /* free the redirect body */ }
57
- }
58
- }
1
+ import{lookup as u}from"node:dns/promises";import{assertEndpointUrl as l,isBlockedHost as f}from"@chatpanel/pii";const w={allowLoopback:!0,allowPrivate:!0},p=t=>/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||t.includes(":");async function h(t,r,n){if(p(t))return;let o;try{o=await n(t,{all:!0})}catch{return}for(const{address:s}of o)if(f(s,r))throw new Error(`refusing to reach ${t} — it resolves to a blocked address (${s})`)}async function L(t,{policy:r=w,maxRedirects:n=5,lookupFn:o=u,fetchFn:s=fetch,...d}={}){let a=l(t,r);for(let c=0;;c++){await h(a.hostname,r,o);const e=await s(a.toString(),{...d,redirect:"manual"}),i=e.status>=300&&e.status<400?e.headers.get("location"):null;if(!i)return e;if(c>=n)throw new Error("too many redirects");a=l(new URL(i,a).toString(),r);try{e.body?.cancel?.()}catch{}}}export{L as secureFetch};
@@ -1,184 +1 @@
1
- // A minimal SentencePiece (Unigram) tokenizer — parse the .model protobuf and
2
- // encode with Viterbi.
3
- //
4
- // Why not a library: the reference implementation for pocket-tts ships a 4 MB
5
- // WASM-bundled sentencepiece build aimed at browsers. This gateway is
6
- // zero-runtime-dependency by design and also compiles into a Bun single-file
7
- // binary, so a 4 MB WASM blob for what is fundamentally a shortest-path search
8
- // over a 4,000-entry vocabulary is the wrong trade.
9
- //
10
- // Scope is deliberately narrow: UNIGRAM models with byte fallback, which is what
11
- // pocket-tts uses (4,000 pieces, each with a log-probability score, plus the 256
12
- // <0xNN> byte pieces). A BPE model would need a different algorithm and is
13
- // rejected at load rather than silently mis-tokenized.
14
-
15
- const UNK = 0, NORMAL_TYPE = 1, CONTROL = 3, BYTE = 6;
16
- // SentencePiece represents a space as U+2581 LOWER ONE EIGHTH BLOCK.
17
- const SPACE = '▁';
18
-
19
- function readVarint(buf, i) {
20
- let result = 0, shift = 0;
21
- for (;;) {
22
- const b = buf[i++];
23
- result += (b & 0x7f) * 2 ** shift;
24
- if ((b & 0x80) === 0) return [result, i];
25
- shift += 7;
26
- if (shift > 49) throw new Error('varint too long');
27
- }
28
- }
29
-
30
- // ModelProto { repeated SentencePiece pieces = 1; ... }
31
- // SentencePiece { string piece = 1; float score = 2; Type type = 3; }
32
- function parseModelProto(buf) {
33
- const pieces = [];
34
- let i = 0;
35
- while (i < buf.length) {
36
- let key;
37
- [key, i] = readVarint(buf, i);
38
- const field = key >> 3, wire = key & 7;
39
- if (wire === 2) {
40
- let len;
41
- [len, i] = readVarint(buf, i);
42
- const chunk = buf.subarray(i, i + len);
43
- i += len;
44
- if (field === 1) pieces.push(parsePiece(chunk));
45
- } else if (wire === 0) {
46
- [, i] = readVarint(buf, i);
47
- } else if (wire === 5) {
48
- i += 4;
49
- } else if (wire === 1) {
50
- i += 8;
51
- } else {
52
- throw new Error(`unsupported protobuf wire type ${wire}`);
53
- }
54
- }
55
- return pieces;
56
- }
57
-
58
- function parsePiece(buf) {
59
- let i = 0, piece = '', score = 0, type = NORMAL_TYPE;
60
- while (i < buf.length) {
61
- let key;
62
- [key, i] = readVarint(buf, i);
63
- const field = key >> 3, wire = key & 7;
64
- if (wire === 2) {
65
- let len;
66
- [len, i] = readVarint(buf, i);
67
- const val = buf.subarray(i, i + len);
68
- i += len;
69
- if (field === 1) piece = new TextDecoder().decode(val);
70
- } else if (wire === 5) {
71
- if (field === 2) score = new DataView(buf.buffer, buf.byteOffset + i, 4).getFloat32(0, true);
72
- i += 4;
73
- } else if (wire === 0) {
74
- let v;
75
- [v, i] = readVarint(buf, i);
76
- if (field === 3) type = v;
77
- } else {
78
- break;
79
- }
80
- }
81
- return { piece, score, type };
82
- }
83
-
84
- export class SentencePieceUnigram {
85
- constructor(modelBytes) {
86
- const pieces = parseModelProto(modelBytes);
87
- if (!pieces.length) throw new Error('sentencepiece model contains no pieces');
88
- // A unigram model scores every piece; a BPE model does not. Rejecting here
89
- // beats producing plausible-looking but wrong token ids.
90
- if (!pieces.some((p) => p.score !== 0)) {
91
- throw new Error('this looks like a BPE sentencepiece model — only unigram is supported');
92
- }
93
- this.pieces = pieces;
94
- this.vocab = new Map();
95
- this.byteId = new Array(256).fill(-1);
96
- this.unkId = 0;
97
- for (let id = 0; id < pieces.length; id++) {
98
- const { piece, type } = pieces[id];
99
- if (type === UNK) this.unkId = id;
100
- if (type === BYTE) {
101
- const m = /^<0x([0-9A-Fa-f]{2})>$/.exec(piece);
102
- if (m) this.byteId[parseInt(m[1], 16)] = id;
103
- continue;
104
- }
105
- // Control pieces (<s>, </s>, <pad>) are addressable by id but must never be
106
- // produced by encoding text — they are inserted by the caller if wanted.
107
- if (type === CONTROL) continue;
108
- if (!this.vocab.has(piece)) this.vocab.set(piece, id);
109
- }
110
- this.maxPieceLen = Math.max(...[...this.vocab.keys()].map((p) => p.length), 1);
111
- }
112
-
113
- get vocabSize() { return this.pieces.length; }
114
-
115
- /** Text → token ids. Viterbi over piece scores, byte fallback for the rest. */
116
- encodeIds(text) {
117
- const norm = SPACE + String(text ?? '').normalize('NFKC').replace(/ /g, SPACE);
118
- const n = norm.length;
119
- // best[i] = { score, from, id } for the best segmentation of norm[0..i)
120
- const best = new Array(n + 1).fill(null);
121
- best[0] = { score: 0, from: -1, id: -1, bytes: null };
122
-
123
- for (let i = 0; i < n; i++) {
124
- if (!best[i]) continue;
125
- let matched = false; // kept for readability of the fallback comment below
126
- const limit = Math.min(n, i + this.maxPieceLen);
127
- for (let j = i + 1; j <= limit; j++) {
128
- const id = this.vocab.get(norm.slice(i, j));
129
- if (id === undefined) continue;
130
- matched = true;
131
- const score = best[i].score + this.pieces[id].score;
132
- if (!best[j] || score > best[j].score) best[j] = { score, from: i, id, bytes: null };
133
- }
134
- // Byte fallback is ALWAYS offered as an alternative, not only when nothing
135
- // matched: a character can be in the vocabulary and still be the wrong split
136
- // for the sentence around it. The per-byte penalty is far worse than any real
137
- // piece's score, so Viterbi picks it only when it genuinely has to.
138
- void matched;
139
- {
140
- const ch = String.fromCodePoint(norm.codePointAt(i));
141
- const j = i + ch.length;
142
- const bytes = new TextEncoder().encode(ch);
143
- if (bytes.every((b) => this.byteId[b] >= 0)) {
144
- const score = best[i].score + bytes.length * -10;
145
- if (!best[j] || score > best[j].score) best[j] = { score, from: i, id: -1, bytes };
146
- }
147
- }
148
- }
149
-
150
- if (!best[n]) return [this.unkId];
151
- const out = [];
152
- for (let i = n; i > 0;) {
153
- const node = best[i];
154
- if (node.bytes) for (let k = node.bytes.length - 1; k >= 0; k--) out.push(this.byteId[node.bytes[k]]);
155
- else out.push(node.id);
156
- i = node.from;
157
- }
158
- return out.reverse();
159
- }
160
-
161
- /** Token ids → text. Byte pieces are reassembled before decoding as UTF-8. */
162
- decodeIds(ids) {
163
- const parts = [];
164
- let pending = [];
165
- const flush = () => {
166
- if (!pending.length) return;
167
- parts.push(new TextDecoder().decode(Uint8Array.from(pending)));
168
- pending = [];
169
- };
170
- for (const id of ids) {
171
- const p = this.pieces[id];
172
- if (!p) continue;
173
- if (p.type === BYTE) {
174
- const m = /^<0x([0-9A-Fa-f]{2})>$/.exec(p.piece);
175
- if (m) { pending.push(parseInt(m[1], 16)); continue; }
176
- }
177
- flush();
178
- if (p.type === CONTROL || p.type === UNK) continue;
179
- parts.push(p.piece);
180
- }
181
- flush();
182
- return parts.join('').replace(new RegExp(SPACE, 'g'), ' ').replace(/^ /, '');
183
- }
184
- }
1
+ const g=0,m=1,w=3,E=6,b="▁";function p(c,o){let t=0,n=0;for(;;){const i=c[o++];if(t+=(i&127)*2**n,(i&128)===0)return[t,o];if(n+=7,n>49)throw new Error("varint too long")}}function u(c){const o=[];let t=0;for(;t<c.length;){let n;[n,t]=p(c,t);const i=n>>3,s=n&7;if(s===2){let e;[e,t]=p(c,t);const r=c.subarray(t,t+e);t+=e,i===1&&o.push(y(r))}else if(s===0)[,t]=p(c,t);else if(s===5)t+=4;else if(s===1)t+=8;else throw new Error(`unsupported protobuf wire type ${s}`)}return o}function y(c){let o=0,t="",n=0,i=1;for(;o<c.length;){let s;[s,o]=p(c,o);const e=s>>3,r=s&7;if(r===2){let l;[l,o]=p(c,o);const f=c.subarray(o,o+l);o+=l,e===1&&(t=new TextDecoder().decode(f))}else if(r===5)e===2&&(n=new DataView(c.buffer,c.byteOffset+o,4).getFloat32(0,!0)),o+=4;else if(r===0){let l;[l,o]=p(c,o),e===3&&(i=l)}else break}return{piece:t,score:n,type:i}}class x{constructor(o){const t=u(o);if(!t.length)throw new Error("sentencepiece model contains no pieces");if(!t.some(n=>n.score!==0))throw new Error("this looks like a BPE sentencepiece model — only unigram is supported");this.pieces=t,this.vocab=new Map,this.byteId=new Array(256).fill(-1),this.unkId=0;for(let n=0;n<t.length;n++){const{piece:i,type:s}=t[n];if(s===0&&(this.unkId=n),s===6){const e=/^<0x([0-9A-Fa-f]{2})>$/.exec(i);e&&(this.byteId[parseInt(e[1],16)]=n);continue}s!==3&&(this.vocab.has(i)||this.vocab.set(i,n))}this.maxPieceLen=Math.max(...[...this.vocab.keys()].map(n=>n.length),1)}get vocabSize(){return this.pieces.length}encodeIds(o){const t="▁"+String(o??"").normalize("NFKC").replace(/ /g,"▁"),n=t.length,i=new Array(n+1).fill(null);i[0]={score:0,from:-1,id:-1,bytes:null};for(let e=0;e<n;e++){if(!i[e])continue;let r=!1;const l=Math.min(n,e+this.maxPieceLen);for(let f=e+1;f<=l;f++){const h=this.vocab.get(t.slice(e,f));if(h===void 0)continue;r=!0;const a=i[e].score+this.pieces[h].score;(!i[f]||a>i[f].score)&&(i[f]={score:a,from:e,id:h,bytes:null})}{const f=String.fromCodePoint(t.codePointAt(e)),h=e+f.length,a=new TextEncoder().encode(f);if(a.every(d=>this.byteId[d]>=0)){const d=i[e].score+a.length*-10;(!i[h]||d>i[h].score)&&(i[h]={score:d,from:e,id:-1,bytes:a})}}}if(!i[n])return[this.unkId];const s=[];for(let e=n;e>0;){const r=i[e];if(r.bytes)for(let l=r.bytes.length-1;l>=0;l--)s.push(this.byteId[r.bytes[l]]);else s.push(r.id);e=r.from}return s.reverse()}decodeIds(o){const t=[];let n=[];const i=()=>{n.length&&(t.push(new TextDecoder().decode(Uint8Array.from(n))),n=[])};for(const s of o){const e=this.pieces[s];if(e){if(e.type===6){const r=/^<0x([0-9A-Fa-f]{2})>$/.exec(e.piece);if(r){n.push(parseInt(r[1],16));continue}}i(),!(e.type===3||e.type===0)&&t.push(e.piece)}}return i(),t.join("").replace(new RegExp("▁","g")," ").replace(/^ /,"")}}export{x as SentencePieceUnigram};