@chatpanel/gateway 0.6.110 → 0.8.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 (81) 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 +2 -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/policy.js +2 -0
  47. package/src/prefs-store.js +1 -149
  48. package/src/project-store.js +1 -139
  49. package/src/project.js +1 -171
  50. package/src/recruit.js +3 -424
  51. package/src/recruiting.js +1 -93
  52. package/src/redact.js +2 -123
  53. package/src/responses.js +2 -80
  54. package/src/router.js +1 -292
  55. package/src/rrf.js +1 -93
  56. package/src/scorecard-store.js +1 -92
  57. package/src/scorecard.js +1 -336
  58. package/src/search-index.js +2 -134
  59. package/src/secure-fetch.js +1 -58
  60. package/src/sentencepiece.js +1 -184
  61. package/src/server.js +10 -2296
  62. package/src/service.js +11 -189
  63. package/src/shape.js +5 -121
  64. package/src/sqlite-store.js +3 -212
  65. package/src/stream.js +5 -182
  66. package/src/structured.js +4 -902
  67. package/src/stt-engine.js +1 -486
  68. package/src/stt-models.js +1 -144
  69. package/src/subject-kinds.js +1 -6
  70. package/src/subject-name.js +1 -97
  71. package/src/team-board.js +6 -338
  72. package/src/team-record.js +1 -226
  73. package/src/team-store.js +1 -261
  74. package/src/team.js +1 -303
  75. package/src/toolrelay.js +3 -122
  76. package/src/tts-engine.js +1 -453
  77. package/src/tts-models.js +1 -254
  78. package/src/tts-remote.js +1 -109
  79. package/src/tts-voice-resolve.js +1 -78
  80. package/src/tts-voices.js +1 -192
  81. package/src/update.js +1 -305
package/src/stream.js CHANGED
@@ -1,184 +1,7 @@
1
- // Protocol-agnostic stream restorer.
2
- //
3
- // Both OpenAI and Anthropic stream Server-Sent Events whose payloads embed the
4
- // model's text (and tool-call argument JSON) as plain strings. Our placeholders
5
- // are literal, well-formed substrings ([[TYPE_n]]) wherever they appear — inside
6
- // "delta.content", inside a streamed "arguments" JSON string, anywhere. So we can
7
- // restore them with a single pass over the raw outgoing bytes, regardless of
8
- // protocol, holding back a tail when a token might be split across chunks.
9
- //
10
- // Note on pseudonyms: a dictionary `alias` is substituted at REDACTION time (the
11
- // upstream already sees the alias, never a placeholder), so it flows back to the
12
- // agent unchanged — its defined "permanent substitution" behavior. Only reversible
13
- // [[TYPE_n]] tokens are restored here.
1
+ import{restoreText as g,restoreWithAliases as A}from"@chatpanel/pii";function S(t){const e=t.lastIndexOf("[[");return e!==-1&&!t.slice(e).includes("]]")?[t.slice(0,e),t.slice(e)]:t.endsWith("[")?[t.slice(0,-1),"["]:[t,""]}function T(t){let e="";return{push(n){if(!t)return n||"";e+=n||"";let r;return[r,e]=S(e),g(r,t)},flush(){const n=t?g(e,t):e;return e="",n}}}function j(t,e){if(!e)return t;if(typeof t=="string")return g(t,e);if(Array.isArray(t))return t.map(n=>j(n,e));if(t&&typeof t=="object"){const n={};for(const r of Object.keys(t))n[r]=j(t[r],e);return n}return t}function D(t,e){if(!e)return t;if(typeof t=="string")return A(t,e);if(Array.isArray(t))return t.map(n=>D(n,e));if(t&&typeof t=="object"){const n={};for(const r of Object.keys(t))n[r]=D(t[r],e);return n}return t}function N(t,e){let n="";return{push(r){n+=r||"";let f;return[f,n]=S(n),e(f,t)},flush(){const r=e(n,t);return n="",r}}}async function R(t,e,n,r=null){const f=t.getReader(),x=new TextDecoder;let s="";const h=N(n,g),p=new Map,y=new Map,l=u=>(o,i)=>r?r.toTool(y.get(u)||"",o):A(o,i),O=u=>{const o=[];for(const i of u.split(`
2
+ `)){if(!i.startsWith("data:")){o.push(i);continue}const w=i.slice(5).replace(/^\s/,"");if(!w){o.push(i);continue}if(w==="[DONE]"){const m=h.flush();m&&o.push(`data: ${JSON.stringify({choices:[{index:0,delta:{content:m},finish_reason:null}]})}`),o.push(i);continue}let k;try{k=JSON.parse(w)}catch{o.push(i);continue}for(const m of k.choices||[]){const a=m.delta;if(a){typeof a.content=="string"&&(a.content=h.push(a.content));for(const c of a.tool_calls||[]){const d=typeof c.index=="number"?c.index:0;c.function&&typeof c.function.name=="string"&&c.function.name&&y.set(d,c.function.name),c.function&&typeof c.function.arguments=="string"&&(p.has(d)||p.set(d,N(n,l(d))),c.function.arguments=p.get(d).push(c.function.arguments))}}}o.push(`data: ${JSON.stringify(k)}`)}return o.join(`
3
+ `)};try{for(;;){const{done:u,value:o}=await f.read();if(u)break;s+=x.decode(o,{stream:!0});let i;for(;(i=s.indexOf(`
14
4
 
15
- import { restoreText, restoreWithAliases } from '@chatpanel/pii';
5
+ `))!==-1;)e.write(O(s.slice(0,i))+`
16
6
 
17
- // Returns a TransformStream-free chunk transformer: feed it decoded string chunks,
18
- // it returns the prefix that's safe to forward now and buffers a possibly-partial
19
- // trailing token. Call flush() at end-of-stream.
20
- /**
21
- * Split `buf` into what is safe to forward now and what may still be the start of a token.
22
- *
23
- * Two shapes are held back: an unterminated "[[" (a token mid-way), and a trailing SINGLE
24
- * "[" — a model tokenizes "[[ORG_1]]" as "[" + "[ORG_1]]" often enough that forwarding the
25
- * lone bracket left every restored name wearing one: "[NVIDIA designs GPUs". "[[" cannot
26
- * legitimately appear except as a token open, and a lone "[" at a chunk edge costs nothing to
27
- * wait one chunk for.
28
- */
29
- function splitSafe(buf) {
30
- const open = buf.lastIndexOf('[[');
31
- if (open !== -1 && !buf.slice(open).includes(']]')) return [buf.slice(0, open), buf.slice(open)];
32
- if (buf.endsWith('[')) return [buf.slice(0, -1), '['];
33
- return [buf, ''];
34
- }
35
-
36
- export function makeTokenRestorer(vault) {
37
- let buf = '';
38
- return {
39
- push(chunk) {
40
- if (!vault) return chunk || '';
41
- buf += chunk || '';
42
- let safe;
43
- [safe, buf] = splitSafe(buf);
44
- return restoreText(safe, vault);
45
- },
46
- flush() {
47
- const out = vault ? restoreText(buf, vault) : buf;
48
- buf = '';
49
- return out;
50
- },
51
- };
52
- }
53
-
54
- // Deep-restore a parsed value (non-streaming responses): tool-call argument
55
- // objects hold placeholders inside their string fields. Walks strings/arrays/
56
- // objects, restoring reversible tokens. (Streaming uses makeTokenRestorer; this
57
- // is only for the buffered/non-stream path.)
58
- export function restoreDeep(value, vault) {
59
- if (!vault) return value;
60
- if (typeof value === 'string') return restoreText(value, vault);
61
- if (Array.isArray(value)) return value.map((v) => restoreDeep(v, vault));
62
- if (value && typeof value === 'object') {
63
- const out = {};
64
- for (const k of Object.keys(value)) out[k] = restoreDeep(value[k], vault);
65
- return out;
66
- }
67
- return value;
68
- }
69
-
70
- // Deep-restore for tool-call argument values (non-stream), undoing aliases too —
71
- // so a client running tools LOCALLY gets the REAL value (pseudonyms included),
72
- // while the model stays blinded. Mirrors the extension's restoreDeep.
73
- export function restoreDeepAliases(value, vault) {
74
- if (!vault) return value;
75
- if (typeof value === 'string') return restoreWithAliases(value, vault);
76
- if (Array.isArray(value)) return value.map((v) => restoreDeepAliases(v, vault));
77
- if (value && typeof value === 'object') {
78
- const out = {};
79
- for (const k of Object.keys(value)) out[k] = restoreDeepAliases(value[k], vault);
80
- return out;
81
- }
82
- return value;
83
- }
84
-
85
- // A per-field tail-buffered restorer (holds a partial trailing [[token). `restoreFn`
86
- // is restoreText for VISIBLE text (keep pseudonyms) or restoreWithAliases for
87
- // TOOL-CALL args (real values).
88
- function makeFieldRestorer(vault, restoreFn) {
89
- let buf = '';
90
- return {
91
- push(chunk) {
92
- buf += chunk || '';
93
- let safe;
94
- [safe, buf] = splitSafe(buf);
95
- return restoreFn(safe, vault);
96
- },
97
- flush() { const out = restoreFn(buf, vault); buf = ''; return out; },
98
- };
99
- }
100
-
101
- // OpenAI streaming restorer that restores VISIBLE content with restoreText (the
102
- // model + user keep the pseudonym) but TOOL-CALL argument deltas with
103
- // restoreWithAliases (the client runs the tool on the REAL value). Passes through
104
- // any non-JSON event untouched.
105
- export async function pipeRestoredOpenAIStream(upstreamBody, nodeRes, vault, harness = null) {
106
- const reader = upstreamBody.getReader();
107
- const decoder = new TextDecoder();
108
- let buf = '';
109
- const contentR = makeFieldRestorer(vault, restoreText);
110
- const argRs = new Map(); // tool_call index -> field restorer
111
- const toolNames = new Map(); // tool_call index -> name (for redact-remote decisions)
112
- // Tool args go through the shared harness (real, or kept-redacted for remote MCP
113
- // under redactRemote); without a harness, default to real values (aliases undone).
114
- const argFn = (idx) => (text, v) => (harness ? harness.toTool(toolNames.get(idx) || '', text) : restoreWithAliases(text, v));
115
-
116
- const handleBlock = (block) => {
117
- const out = [];
118
- for (const line of block.split('\n')) {
119
- if (!line.startsWith('data:')) { out.push(line); continue; }
120
- const payload = line.slice(5).replace(/^\s/, '');
121
- if (!payload) { out.push(line); continue; }
122
- if (payload === '[DONE]') {
123
- const tail = contentR.flush();
124
- if (tail) out.push(`data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: tail }, finish_reason: null }] })}`);
125
- out.push(line);
126
- continue;
127
- }
128
- let evt; try { evt = JSON.parse(payload); } catch { out.push(line); continue; }
129
- for (const choice of evt.choices || []) {
130
- const d = choice.delta;
131
- if (!d) continue;
132
- if (typeof d.content === 'string') d.content = contentR.push(d.content);
133
- for (const tc of d.tool_calls || []) {
134
- const idx = typeof tc.index === 'number' ? tc.index : 0;
135
- if (tc.function && typeof tc.function.name === 'string' && tc.function.name) toolNames.set(idx, tc.function.name);
136
- if (tc.function && typeof tc.function.arguments === 'string') {
137
- if (!argRs.has(idx)) argRs.set(idx, makeFieldRestorer(vault, argFn(idx)));
138
- tc.function.arguments = argRs.get(idx).push(tc.function.arguments);
139
- }
140
- }
141
- }
142
- out.push(`data: ${JSON.stringify(evt)}`);
143
- }
144
- return out.join('\n');
145
- };
146
-
147
- try {
148
- for (;;) {
149
- const { done, value } = await reader.read();
150
- if (done) break;
151
- buf += decoder.decode(value, { stream: true });
152
- let i;
153
- while ((i = buf.indexOf('\n\n')) !== -1) {
154
- nodeRes.write(handleBlock(buf.slice(0, i)) + '\n\n');
155
- buf = buf.slice(i + 2);
156
- }
157
- }
158
- if (buf) nodeRes.write(handleBlock(buf));
159
- } finally {
160
- nodeRes.end();
161
- }
162
- }
163
-
164
- // Pipe a fetch Response body (web ReadableStream) through the restorer into a
165
- // Node response. Works on raw bytes decoded as UTF-8 — fine because placeholders
166
- // are ASCII, so even if a multibyte char is split the token bytes are intact.
167
- export async function pipeRestoredStream(upstreamBody, nodeRes, vault) {
168
- const restorer = makeTokenRestorer(vault);
169
- const decoder = new TextDecoder();
170
- const reader = upstreamBody.getReader();
171
- try {
172
- for (;;) {
173
- const { done, value } = await reader.read();
174
- if (done) break;
175
- const text = decoder.decode(value, { stream: true });
176
- const out = restorer.push(text);
177
- if (out) nodeRes.write(out);
178
- }
179
- const tail = restorer.push(decoder.decode()) + restorer.flush();
180
- if (tail) nodeRes.write(tail);
181
- } finally {
182
- nodeRes.end();
183
- }
184
- }
7
+ `),s=s.slice(i+2)}s&&e.write(O(s))}finally{e.end()}}async function J(t,e,n){const r=T(n),f=new TextDecoder,x=t.getReader();try{for(;;){const{done:h,value:p}=await x.read();if(h)break;const y=f.decode(p,{stream:!0}),l=r.push(y);l&&e.write(l)}const s=r.push(f.decode())+r.flush();s&&e.write(s)}finally{e.end()}}export{T as makeTokenRestorer,R as pipeRestoredOpenAIStream,J as pipeRestoredStream,j as restoreDeep,D as restoreDeepAliases};