@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
@@ -1,181 +1 @@
1
- // Read/write the gateway's on-disk config so the extension's "Gateway" tab can
2
- // configure it live over the localhost API (GET/POST /config). The gateway stays
3
- // authoritative — the extension is just a UI client.
4
-
5
- import { writeFileSync, mkdirSync, chmodSync } from 'node:fs';
6
- import { join, dirname } from 'node:path';
7
- import os from 'node:os';
8
- import { usage } from './freegate.js';
9
-
10
- // Default to a writable per-user location, NOT process.cwd(): when the gateway
11
- // runs as a login service its cwd is "/" (read-only → EROFS on save).
12
- export function configPath(env = process.env) {
13
- return env.CHATPANEL_GATEWAY_CONFIG || join(os.homedir(), '.chatpanel', 'gateway.config.json');
14
- }
15
-
16
- // Persist the user-editable subset (not derived runtime state).
17
- export function persistConfig(cfg, path = configPath()) {
18
- // 0700 the dir + 0600 the file: this JSON holds per-destination apiKeys, the
19
- // detector key, and the entitlement/bridge tokens — same secret-at-rest posture
20
- // as the history key/secret files, so it isn't left world-readable on a shared host.
21
- mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
22
- // NOTE: this is an explicit allowlist, so a NEW config section does not persist
23
- // until it is added here — and the symptom is a setting that silently reverts on
24
- // restart, which reads as "the feature is broken" rather than "it was not saved".
25
- // tests/configstore.test.js fails if a key in DEFAULTS is neither listed here nor
26
- // deliberately excluded below.
27
- const out = {
28
- host: cfg.host, port: cfg.port, backend: cfg.backend,
29
- // Destinations (the configured agents + API models) MUST persist — otherwise a
30
- // restart drops them and every model falls back to the default OpenAI upstream.
31
- destinations: cfg.destinations,
32
- bridge: cfg.bridge, upstreams: cfg.upstreams, redaction: cfg.redaction,
33
- ner: cfg.ner, stt: cfg.stt, tts: cfg.tts, allowedOrigins: cfg.allowedOrigins, maxBodyBytes: cfg.maxBodyBytes,
34
- pro: cfg.pro, logRequests: cfg.logRequests, logDetail: cfg.logDetail, tools: cfg.tools,
35
- };
36
- // mode on writeFileSync only applies when CREATING the file; chmod after covers an
37
- // already-existing (pre-fix, possibly 0644) config too. Best-effort for non-POSIX.
38
- writeFileSync(path, JSON.stringify(out, null, 2), { mode: 0o600 });
39
- try { chmodSync(path, 0o600); } catch { /* platforms without POSIX perms */ }
40
- }
41
-
42
- // Safe view for GET /config — never leak secrets (the entitlement + bridge tokens
43
- // are write-only; the UI shows whether Pro is unlocked, not the token).
44
- export function publicConfig(cfg, { proUnlocked = false } = {}) {
45
- return {
46
- backend: cfg.backend,
47
- // Strip per-destination apiKey (write-only).
48
- destinations: (Array.isArray(cfg.destinations) ? cfg.destinations : []).map((d) => { const { apiKey, ...rest } = d; return { ...rest, hasKey: !!apiKey }; }),
49
- bridge: { url: cfg.bridge?.url, agent: cfg.bridge?.agent, hasToken: !!cfg.bridge?.token, permissionMode: cfg.bridge?.permissionMode || 'default', workingDir: cfg.bridge?.workingDir || '' },
50
- upstreams: cfg.upstreams,
51
- redaction: {
52
- tier: cfg.redaction?.tier,
53
- redactSystem: cfg.redaction?.redactSystem !== false,
54
- // Never echo the detector's apiKey back (write-only, like the tokens).
55
- detection: (() => { const { apiKey, ...d } = cfg.redaction?.detection || { backend: 'off' }; return d; })(),
56
- dictionary: Array.isArray(cfg.redaction?.dictionary) ? cfg.redaction.dictionary : [],
57
- },
58
- ner: cfg.ner,
59
- stt: cfg.stt,
60
- allowedOrigins: Array.isArray(cfg.allowedOrigins) ? cfg.allowedOrigins : [],
61
- // free = lifetime trial usage ({ used, cap, remaining }), read-only.
62
- pro: { unlocked: proUnlocked, hasToken: !!cfg.pro?.entitlementToken, free: usage(cfg) },
63
- logRequests: !!cfg.logRequests,
64
- logDetail: ['types', 'values'].includes(cfg.logDetail) ? cfg.logDetail : 'off',
65
- tools: {
66
- autoNarrow: cfg.tools?.autoNarrow !== false,
67
- maxPerTurn: Number(cfg.tools?.maxPerTurn) > 0 ? Number(cfg.tools.maxPerTurn) : 8,
68
- narrowAll: !!cfg.tools?.narrowAll,
69
- toolData: cfg.tools?.toolData === 'redactRemote' ? 'redactRemote' : 'real',
70
- },
71
- };
72
- }
73
-
74
- // Selecting a bundled NER model is an explicit request to use that detector, not
75
- // merely to remember its name. Older configs can carry autostart:false; leaving it
76
- // untouched makes the selected model work only until restart and then silently
77
- // falls back to deterministic-only redaction.
78
- export function applyNerModelSelection(cfg, id) {
79
- cfg.ner = cfg.ner || { allowDownload: true, enableFullTier: true };
80
- cfg.ner.model = id;
81
- cfg.ner.autostart = true;
82
- return cfg.ner;
83
- }
84
-
85
- // Merge an editable patch into the live cfg. Only known fields; ignores the rest.
86
- /**
87
- * Is this API destination the gateway itself? A loop: a turn routed there comes straight
88
- * back in. It arrived once from a backup import — the extension keeps the gateway in its own
89
- * endpoint list, and the desktop copied that list into the gateway's destinations — and its
90
- * model ids (the agents') then shadowed the real agents. Refused at the door, with a log line.
91
- */
92
- export function isSelfDestination(d, cfg = {}) {
93
- if (!d || d.type !== 'api') return false;
94
- let u;
95
- try { u = new URL(String(d.baseUrl || '')); } catch { return false; }
96
- const loop = /^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(u.hostname);
97
- const port = Number(u.port) || (u.protocol === 'https:' ? 443 : 80);
98
- return loop && port === (Number(cfg.port) || 4320);
99
- }
100
-
101
- export const PERMISSION_MODES = ['default', 'acceptEdits', 'bypassPermissions'];
102
-
103
- /** The per-turn options a gateway-driven agent receives — the bridge's own vocabulary. */
104
- export function bridgeAgentOptions(cfg, extra = {}) {
105
- const b = cfg?.bridge || {};
106
- return {
107
- ...(PERMISSION_MODES.includes(b.permissionMode) && b.permissionMode !== 'default' ? { permissionMode: b.permissionMode } : {}),
108
- ...(typeof b.workingDir === 'string' && b.workingDir.trim() ? { workingDir: b.workingDir.trim() } : {}),
109
- ...extra,
110
- };
111
- }
112
-
113
- export function applyConfigPatch(cfg, patch = {}) {
114
- if (patch.backend === 'bridge' || patch.backend === 'api') cfg.backend = patch.backend;
115
- if (Array.isArray(patch.destinations)) {
116
- // Preserve a destination's apiKey when the patch omits it (it's write-only —
117
- // publicConfig strips it, so the UI never round-trips it back).
118
- const prev = new Map((Array.isArray(cfg.destinations) ? cfg.destinations : []).map((d) => [d.id, d]));
119
- cfg.destinations = patch.destinations
120
- .filter((d) => d && typeof d.id === 'string' && (d.type === 'agent' || d.type === 'api'))
121
- .filter((d) => { const self = isSelfDestination(d, cfg); if (self) console.log(`[gateway] refusing destination "${d.id}": ${d.baseUrl} is this gateway — a loop`); return !self; })
122
- .map((d) => {
123
- const out = { id: d.id, type: d.type, models: Array.isArray(d.models) ? d.models.filter((m) => typeof m === 'string' && m) : [] };
124
- if (d.type === 'agent') out.agent = d.agent || d.id;
125
- if (d.type === 'api') {
126
- out.baseUrl = String(d.baseUrl || '');
127
- out.protocol = d.protocol === 'anthropic' ? 'anthropic' : 'openai';
128
- const key = (typeof d.apiKey === 'string' && d.apiKey) ? d.apiKey : prev.get(d.id)?.apiKey;
129
- if (key) out.apiKey = key;
130
- }
131
- return out;
132
- });
133
- }
134
- if (patch.bridge && typeof patch.bridge === 'object') {
135
- if (typeof patch.bridge.url === 'string') cfg.bridge.url = patch.bridge.url;
136
- if (typeof patch.bridge.agent === 'string') cfg.bridge.agent = patch.bridge.agent;
137
- if (PERMISSION_MODES.includes(patch.bridge.permissionMode)) cfg.bridge.permissionMode = patch.bridge.permissionMode;
138
- if (typeof patch.bridge.workingDir === 'string') cfg.bridge.workingDir = patch.bridge.workingDir.trim().slice(0, 1024);
139
- }
140
- // api backend: where redacted traffic is forwarded (the client still picks the
141
- // model + sends its own key).
142
- if (patch.upstreams && typeof patch.upstreams === 'object') {
143
- for (const k of ['openai', 'anthropic']) {
144
- const u = patch.upstreams[k];
145
- if (u && typeof u.baseUrl === 'string' && u.baseUrl.trim()) {
146
- cfg.upstreams[k] = { ...cfg.upstreams[k], baseUrl: u.baseUrl.trim() };
147
- }
148
- }
149
- }
150
- if (patch.redaction && typeof patch.redaction === 'object') {
151
- const r = patch.redaction;
152
- if (r.tier === 'basic' || r.tier === 'full') cfg.redaction.tier = r.tier;
153
- if ('redactSystem' in r) cfg.redaction.redactSystem = !!r.redactSystem;
154
- if (Array.isArray(r.dictionary)) cfg.redaction.dictionary = r.dictionary;
155
- if (r.detection && typeof r.detection === 'object') cfg.redaction.detection = r.detection;
156
- }
157
- if (Array.isArray(patch.allowedOrigins)) cfg.allowedOrigins = patch.allowedOrigins;
158
- if (patch.pro && typeof patch.pro === 'object') {
159
- if (typeof patch.pro.entitlementToken === 'string') cfg.pro.entitlementToken = patch.pro.entitlementToken;
160
- // The free allowance (freegate.FREE_TOTAL_CAP) and its `used` count are not
161
- // part of the editable patch.
162
- }
163
- // Local dictation toggle. The MODEL is switched via POST /stt/models (like the
164
- // NER manager), not patched here.
165
- if (patch.stt && typeof patch.stt === 'object') {
166
- cfg.stt = cfg.stt || { enabled: true, model: 'onnx-community/whisper-base', allowDownload: true };
167
- if ('enabled' in patch.stt) cfg.stt.enabled = !!patch.stt.enabled;
168
- if ('allowDownload' in patch.stt) cfg.stt.allowDownload = !!patch.stt.allowDownload;
169
- }
170
- if (typeof patch.logRequests === 'boolean') cfg.logRequests = patch.logRequests;
171
- if (['off', 'types', 'values'].includes(patch.logDetail)) cfg.logDetail = patch.logDetail;
172
- if (patch.tools && typeof patch.tools === 'object') {
173
- cfg.tools = cfg.tools || {};
174
- if ('autoNarrow' in patch.tools) cfg.tools.autoNarrow = !!patch.tools.autoNarrow;
175
- if ('narrowAll' in patch.tools) cfg.tools.narrowAll = !!patch.tools.narrowAll;
176
- if (patch.tools.toolData === 'real' || patch.tools.toolData === 'redactRemote') cfg.tools.toolData = patch.tools.toolData;
177
- const cap = Number(patch.tools.maxPerTurn);
178
- if (Number.isFinite(cap) && cap >= 1) cfg.tools.maxPerTurn = Math.floor(cap);
179
- }
180
- return cfg;
181
- }
1
+ import{writeFileSync as a,mkdirSync as l,chmodSync as d}from"node:fs";import{join as u,dirname as y}from"node:path";import m from"node:os";import{usage as b}from"./freegate.js";function p(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||u(m.homedir(),".chatpanel","gateway.config.json")}function g(e,o=p()){l(y(o),{recursive:!0,mode:448});const t={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,allowedOrigins:e.allowedOrigins,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools};a(o,JSON.stringify(t,null,2),{mode:384});try{d(o,384)}catch{}}function x(e,{proUnlocked:o=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(t=>{const{apiKey:r,...i}=t;return{...i,hasKey:!!r}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:t,...r}=e.redaction?.detection||{backend:"off"};return r})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],pro:{unlocked:o,hasToken:!!e.pro?.entitlementToken,free:b(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function N(e,o){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=o,e.ner.autostart=!0,e.ner}function w(e,o={}){if(!e||e.type!=="api")return!1;let t;try{t=new URL(String(e.baseUrl||""))}catch{return!1}const r=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(t.hostname),i=Number(t.port)||(t.protocol==="https:"?443:80);return r&&i===(Number(o.port)||4320)}const s=["default","acceptEdits","bypassPermissions"];function S(e,o={}){const t=e?.bridge||{};return{...s.includes(t.permissionMode)&&t.permissionMode!=="default"?{permissionMode:t.permissionMode}:{},...typeof t.workingDir=="string"&&t.workingDir.trim()?{workingDir:t.workingDir.trim()}:{},...o}}function M(e,o={}){if((o.backend==="bridge"||o.backend==="api")&&(e.backend=o.backend),Array.isArray(o.destinations)){const t=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(r=>[r.id,r]));e.destinations=o.destinations.filter(r=>r&&typeof r.id=="string"&&(r.type==="agent"||r.type==="api")).filter(r=>{const i=w(r,e);return i&&console.log(`[gateway] refusing destination "${r.id}": ${r.baseUrl} is this gateway — a loop`),!i}).map(r=>{const i={id:r.id,type:r.type,models:Array.isArray(r.models)?r.models.filter(n=>typeof n=="string"&&n):[]};if(r.type==="agent"&&(i.agent=r.agent||r.id),r.type==="api"){i.baseUrl=String(r.baseUrl||""),i.protocol=r.protocol==="anthropic"?"anthropic":"openai";const n=typeof r.apiKey=="string"&&r.apiKey?r.apiKey:t.get(r.id)?.apiKey;n&&(i.apiKey=n)}return i})}if(o.bridge&&typeof o.bridge=="object"&&(typeof o.bridge.url=="string"&&(e.bridge.url=o.bridge.url),typeof o.bridge.agent=="string"&&(e.bridge.agent=o.bridge.agent),s.includes(o.bridge.permissionMode)&&(e.bridge.permissionMode=o.bridge.permissionMode),typeof o.bridge.workingDir=="string"&&(e.bridge.workingDir=o.bridge.workingDir.trim().slice(0,1024))),o.upstreams&&typeof o.upstreams=="object")for(const t of["openai","anthropic"]){const r=o.upstreams[t];r&&typeof r.baseUrl=="string"&&r.baseUrl.trim()&&(e.upstreams[t]={...e.upstreams[t],baseUrl:r.baseUrl.trim()})}if(o.redaction&&typeof o.redaction=="object"){const t=o.redaction;(t.tier==="basic"||t.tier==="full")&&(e.redaction.tier=t.tier),"redactSystem"in t&&(e.redaction.redactSystem=!!t.redactSystem),Array.isArray(t.dictionary)&&(e.redaction.dictionary=t.dictionary),t.detection&&typeof t.detection=="object"&&(e.redaction.detection=t.detection)}if(Array.isArray(o.allowedOrigins)&&(e.allowedOrigins=o.allowedOrigins),o.pro&&typeof o.pro=="object"&&typeof o.pro.entitlementToken=="string"&&(e.pro.entitlementToken=o.pro.entitlementToken),o.stt&&typeof o.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in o.stt&&(e.stt.enabled=!!o.stt.enabled),"allowDownload"in o.stt&&(e.stt.allowDownload=!!o.stt.allowDownload)),typeof o.logRequests=="boolean"&&(e.logRequests=o.logRequests),["off","types","values"].includes(o.logDetail)&&(e.logDetail=o.logDetail),o.tools&&typeof o.tools=="object"){e.tools=e.tools||{},"autoNarrow"in o.tools&&(e.tools.autoNarrow=!!o.tools.autoNarrow),"narrowAll"in o.tools&&(e.tools.narrowAll=!!o.tools.narrowAll),(o.tools.toolData==="real"||o.tools.toolData==="redactRemote")&&(e.tools.toolData=o.tools.toolData);const t=Number(o.tools.maxPerTurn);Number.isFinite(t)&&t>=1&&(e.tools.maxPerTurn=Math.floor(t))}return e}export{s as PERMISSION_MODES,M as applyConfigPatch,N as applyNerModelSelection,S as bridgeAgentOptions,p as configPath,w as isSelfDestination,g as persistConfig,x as publicConfig};
@@ -1,179 +1,22 @@
1
- // connect-agents.js — wire the local CLI agents to the ChatPanel MCP server in one step.
2
- //
3
- // `chatpanel-gateway connect` detects the agent CLIs installed on this machine and points
4
- // each at `chatpanel-gateway mcp`, so a person gets their history + skills in every agent
5
- // without hand-editing four different config files in four different formats.
6
- //
7
- // Two rules keep this safe to run unattended:
8
- // • BACK UP then EDIT, and be IDEMPOTENT — running it twice changes nothing the second
9
- // time. A user's existing MCP servers are never touched.
10
- // • Only auto-write a format we can write CORRECTLY. Codex (TOML append), Claude Code
11
- // (its own CLI) and Gemini (plain JSON) are safe. For agents whose config is JSONC with
12
- // comments, or whose format we cannot verify, we PRINT the exact snippet instead of
13
- // risking a corrupted config. Guessing a format and clobbering a config is worse than
14
- // asking the user to paste four lines.
15
-
16
- import { readFileSync, writeFileSync, existsSync, copyFileSync, mkdirSync } from 'node:fs';
17
- import { execFileSync } from 'node:child_process';
18
- import { join } from 'node:path';
19
- import os from 'node:os';
20
-
21
- // The READ-ONLY tools the ChatPanel MCP server exposes (history, memory, skills). Named here
22
- // so the Codex approval blocks stay in step with what the server actually advertises.
23
- // `remember` and `forget` are deliberately absent: they WRITE to the user's memory store, and
24
- // pre-approving a write without the user seeing it once is not ours to decide.
25
- const TOOLS = [
26
- 'smart_search', 'search_history', 'get_record', 'find_related', 'list_history',
27
- 'recall',
28
- 'list_skills', 'open_skill', 'read_skill_file',
29
- ];
30
-
31
- // Resolve the command a config should launch. A bare name works when the client inherits a
32
- // normal PATH; an absolute path is the safe fallback when it does not.
33
- export function resolveServerCommand(which = whichSync) {
34
- const abs = which('chatpanel-gateway');
35
- return abs || 'chatpanel-gateway';
36
- }
37
-
38
- function whichSync(bin) {
39
- try {
40
- return execFileSync('which', [bin], { encoding: 'utf8' }).trim() || null;
41
- } catch {
42
- return null;
43
- }
44
- }
45
-
46
- function backup(path) {
47
- const b = `${path}.bak.chatpanel`;
48
- try { copyFileSync(path, b); return b; } catch { return null; }
49
- }
50
-
51
- // ── Codex ──────────────────────────────────────────────────────────────────────────────
52
- // ~/.codex/config.toml. TOML, and Node has no TOML writer — but the change is a pure
53
- // APPEND of a server block plus per-tool approval blocks, so a text append (guarded by a
54
- // presence check) is correct and non-destructive. The approval blocks matter: a corporate
55
- // Codex with `approvals_reviewer = "auto_review"` rejects a tool it cannot assess, and this
56
- // is how every other server on such a setup is pre-approved.
57
- function connectCodex({ cmd, dryRun, home }) {
58
- const dir = join(home, '.codex');
59
- const path = join(dir, 'config.toml');
60
- if (!existsSync(dir)) return { id: 'codex', status: 'absent' };
61
- const cur = existsSync(path) ? readFileSync(path, 'utf8') : '';
62
- if (/\[mcp_servers\.chatpanel\]/.test(cur)) return { id: 'codex', status: 'already', path };
63
-
64
- let block = '\n# ChatPanel — local history (redacted) + your installed skills, via one MCP server.\n';
65
- block += `[mcp_servers.chatpanel]\ncommand = ${JSON.stringify(cmd)}\nargs = ["mcp"]\n\n`;
66
- block += '# Read-only tools — pre-approved so a corporate auto_review guardian does not reject them.\n';
67
- for (const t of TOOLS) block += `[mcp_servers.chatpanel.tools.${t}]\napproval_mode = "approve"\n\n`;
68
-
69
- if (dryRun) return { id: 'codex', status: 'would', path, preview: block.trim() };
70
- const bak = backup(path);
71
- writeFileSync(path, `${cur.replace(/\s*$/, '')}\n${block}`);
72
- return { id: 'codex', status: 'configured', path, backup: bak };
73
- }
74
-
75
- // ── Claude Code ────────────────────────────────────────────────────────────────────────
76
- // Its own CLI owns ~/.claude.json, so use `claude mcp add` rather than editing it. --scope
77
- // user makes it available in every project.
78
- function connectClaude({ cmd, dryRun, which }) {
79
- const claude = which('claude');
80
- if (!claude) return { id: 'claude-code', status: 'absent' };
81
- // Already added? `claude mcp get` exits non-zero when it is not there.
82
- try { execFileSync(claude, ['mcp', 'get', 'chatpanel'], { stdio: 'ignore' }); return { id: 'claude-code', status: 'already' }; } catch { /* not present */ }
83
- if (dryRun) return { id: 'claude-code', status: 'would', preview: `claude mcp add --scope user chatpanel ${cmd} mcp` };
84
- try {
85
- execFileSync(claude, ['mcp', 'add', '--scope', 'user', 'chatpanel', cmd, 'mcp'], { stdio: 'ignore' });
86
- return { id: 'claude-code', status: 'configured' };
87
- } catch (e) {
88
- return { id: 'claude-code', status: 'error', message: e.message };
89
- }
90
- }
91
-
92
- // ── Gemini CLI / Antigravity ─────────────────────────────────────────────────────────────
93
- // ~/.gemini/settings.json — plain JSON, safe to parse and merge.
94
- function connectGemini({ cmd, dryRun, home }) {
95
- const dir = join(home, '.gemini');
96
- const path = join(dir, 'settings.json');
97
- if (!existsSync(dir)) return { id: 'gemini', status: 'absent' };
98
- let cfg = {};
99
- if (existsSync(path)) {
100
- try { cfg = JSON.parse(readFileSync(path, 'utf8')); } catch { return { id: 'gemini', status: 'error', message: 'settings.json is not valid JSON — left untouched', path }; }
101
- }
102
- cfg.mcpServers = cfg.mcpServers || {};
103
- if (cfg.mcpServers.chatpanel) return { id: 'gemini', status: 'already', path };
104
- const entry = { command: cmd, args: ['mcp'] };
105
- if (dryRun) return { id: 'gemini', status: 'would', path, preview: JSON.stringify({ mcpServers: { chatpanel: entry } }, null, 2) };
106
- const bak = existsSync(path) ? backup(path) : null;
107
- cfg.mcpServers.chatpanel = entry;
108
- mkdirSync(dir, { recursive: true });
109
- writeFileSync(path, `${JSON.stringify(cfg, null, 2)}\n`);
110
- return { id: 'gemini', status: 'configured', path, backup: bak };
111
- }
112
-
113
- // ── Agents we do NOT auto-write (JSONC with comments, or a format we can't verify) ───────
114
- // Detected and given the exact snippet, rather than risking a clobbered config.
115
- function manualAgent(id, present, snippet) {
116
- return present ? { id, status: 'manual', snippet } : { id, status: 'absent' };
117
- }
118
-
119
- function otherAgents({ cmd, home, which }) {
120
- const out = [];
121
- // OpenCode — opencode.json / .jsonc. JSONC keeps comments; we won't rewrite and drop them.
122
- out.push(manualAgent('opencode', existsSync(join(home, '.opencode')) || existsSync(join(home, '.config', 'opencode')),
123
- `Add to your opencode config (opencode.json):\n "mcp": { "chatpanel": { "type": "local", "command": [${JSON.stringify(cmd)}, "mcp"], "enabled": true } }`));
124
- // GitHub Copilot CLI.
125
- out.push(manualAgent('copilot', existsSync(join(home, '.copilot')),
126
- `Copilot CLI: add an MCP server named "chatpanel" running: ${cmd} mcp`));
127
- // Hermes.
128
- out.push(manualAgent('hermes', existsSync(join(home, '.hermes')) || !!which('hermes'),
129
- `Hermes: register an MCP server "chatpanel" with command ${cmd} mcp (see Hermes' MCP docs).`));
130
- // Pi.
131
- out.push(manualAgent('pi', existsSync(join(home, '.pi')) || !!which('pi'),
132
- `Pi: add an MCP server "chatpanel" running: ${cmd} mcp`));
133
- return out;
134
- }
135
-
136
- /**
137
- * Detect and (unless dryRun) configure every agent found. Returns one result per agent so a
138
- * caller can render a summary. Pure-ish: the only side effects are the config writes, and
139
- * dryRun suppresses them.
140
- */
141
- export function connectAgents({ dryRun = false, cmd, home = os.homedir(), which = whichSync } = {}) {
142
- const serverCmd = cmd || resolveServerCommand(which);
143
- const results = [
144
- connectCodex({ cmd: serverCmd, dryRun, home }),
145
- connectClaude({ cmd: serverCmd, dryRun, which }),
146
- connectGemini({ cmd: serverCmd, dryRun, home }),
147
- ...otherAgents({ cmd: serverCmd, home, which }),
148
- ];
149
- return { cmd: serverCmd, results };
150
- }
151
-
152
- const LABEL = {
153
- codex: 'Codex', 'claude-code': 'Claude Code', gemini: 'Gemini / Antigravity',
154
- opencode: 'OpenCode', copilot: 'GitHub Copilot', hermes: 'Hermes', pi: 'Pi',
155
- };
156
-
157
- /** Human summary for the CLI. */
158
- export function formatConnect({ cmd, results }, { dryRun = false } = {}) {
159
- const lines = [`ChatPanel MCP — connecting your agents to: ${cmd} mcp`, ''];
160
- const icon = { configured: '✓', already: '•', would: '→', manual: '✎', absent: '·', error: '✕' };
161
- for (const r of results) {
162
- const name = LABEL[r.id] || r.id;
163
- if (r.status === 'absent') continue; // don't list agents that aren't installed
164
- const head = ` ${icon[r.status] || '?'} ${name}`;
165
- if (r.status === 'configured') lines.push(`${head} — configured${r.backup ? ` (backup: ${r.backup})` : ''}`);
166
- else if (r.status === 'already') lines.push(`${head} — already connected`);
167
- else if (r.status === 'would') lines.push(`${head} — would configure:\n ${(r.preview || '').split('\n').join('\n ')}`);
168
- else if (r.status === 'manual') lines.push(`${head} — add it yourself:\n ${r.snippet.split('\n').join('\n ')}`);
169
- else if (r.status === 'error') lines.push(`${head} — ${r.message}`);
170
- }
171
- const configured = results.filter((r) => r.status === 'configured').length;
172
- lines.push('');
173
- if (dryRun) lines.push(' (dry run — nothing was written. Re-run without --dry-run to apply.)');
174
- else if (configured) lines.push(` Done. Restart the configured agent(s) to pick up the new server.`);
175
- else lines.push(' Nothing to change.');
176
- const anyManual = results.some((r) => r.status === 'manual');
177
- if (anyManual) lines.push(' Agents marked ✎ use a config format best edited by hand — the snippet above is exact.');
178
- return `${lines.join('\n')}\n`;
179
- }
1
+ import{readFileSync as f,writeFileSync as g,existsSync as c,copyFileSync as v,mkdirSync as $}from"node:fs";import{execFileSync as m}from"node:child_process";import{join as u}from"node:path";import b from"node:os";const C=["smart_search","search_history","get_record","find_related","list_history","recall","list_skills","open_skill","read_skill_file"];function S(t=h){return t("chatpanel-gateway")||"chatpanel-gateway"}function h(t){try{return m("which",[t],{encoding:"utf8"}).trim()||null}catch{return null}}function y(t){const s=`${t}.bak.chatpanel`;try{return v(t,s),s}catch{return null}}function w({cmd:t,dryRun:s,home:a}){const e=u(a,".codex"),n=u(e,"config.toml");if(!c(e))return{id:"codex",status:"absent"};const o=c(n)?f(n,"utf8"):"";if(/\[mcp_servers\.chatpanel\]/.test(o))return{id:"codex",status:"already",path:n};let i=`
2
+ # ChatPanel — local history (redacted) + your installed skills, via one MCP server.
3
+ `;i+=`[mcp_servers.chatpanel]
4
+ command = ${JSON.stringify(t)}
5
+ args = ["mcp"]
6
+
7
+ `,i+=`# Read-only tools — pre-approved so a corporate auto_review guardian does not reject them.
8
+ `;for(const p of C)i+=`[mcp_servers.chatpanel.tools.${p}]
9
+ approval_mode = "approve"
10
+
11
+ `;if(s)return{id:"codex",status:"would",path:n,preview:i.trim()};const r=y(n);return g(n,`${o.replace(/\s*$/,"")}
12
+ ${i}`),{id:"codex",status:"configured",path:n,backup:r}}function k({cmd:t,dryRun:s,which:a}){const e=a("claude");if(!e)return{id:"claude-code",status:"absent"};try{return m(e,["mcp","get","chatpanel"],{stdio:"ignore"}),{id:"claude-code",status:"already"}}catch{}if(s)return{id:"claude-code",status:"would",preview:`claude mcp add --scope user chatpanel ${t} mcp`};try{return m(e,["mcp","add","--scope","user","chatpanel",t,"mcp"],{stdio:"ignore"}),{id:"claude-code",status:"configured"}}catch(n){return{id:"claude-code",status:"error",message:n.message}}}function x({cmd:t,dryRun:s,home:a}){const e=u(a,".gemini"),n=u(e,"settings.json");if(!c(e))return{id:"gemini",status:"absent"};let o={};if(c(n))try{o=JSON.parse(f(n,"utf8"))}catch{return{id:"gemini",status:"error",message:"settings.json is not valid JSON — left untouched",path:n}}if(o.mcpServers=o.mcpServers||{},o.mcpServers.chatpanel)return{id:"gemini",status:"already",path:n};const i={command:t,args:["mcp"]};if(s)return{id:"gemini",status:"would",path:n,preview:JSON.stringify({mcpServers:{chatpanel:i}},null,2)};const r=c(n)?y(n):null;return o.mcpServers.chatpanel=i,$(e,{recursive:!0}),g(n,`${JSON.stringify(o,null,2)}
13
+ `),{id:"gemini",status:"configured",path:n,backup:r}}function l(t,s,a){return s?{id:t,status:"manual",snippet:a}:{id:t,status:"absent"}}function _({cmd:t,home:s,which:a}){const e=[];return e.push(l("opencode",c(u(s,".opencode"))||c(u(s,".config","opencode")),`Add to your opencode config (opencode.json):
14
+ "mcp": { "chatpanel": { "type": "local", "command": [${JSON.stringify(t)}, "mcp"], "enabled": true } }`)),e.push(l("copilot",c(u(s,".copilot")),`Copilot CLI: add an MCP server named "chatpanel" running: ${t} mcp`)),e.push(l("hermes",c(u(s,".hermes"))||!!a("hermes"),`Hermes: register an MCP server "chatpanel" with command ${t} mcp (see Hermes' MCP docs).`)),e.push(l("pi",c(u(s,".pi"))||!!a("pi"),`Pi: add an MCP server "chatpanel" running: ${t} mcp`)),e}function N({dryRun:t=!1,cmd:s,home:a=b.homedir(),which:e=h}={}){const n=s||S(e),o=[w({cmd:n,dryRun:t,home:a}),k({cmd:n,dryRun:t,which:e}),x({cmd:n,dryRun:t,home:a}),..._({cmd:n,home:a,which:e})];return{cmd:n,results:o}}const P={codex:"Codex","claude-code":"Claude Code",gemini:"Gemini / Antigravity",opencode:"OpenCode",copilot:"GitHub Copilot",hermes:"Hermes",pi:"Pi"};function J({cmd:t,results:s},{dryRun:a=!1}={}){const e=[`ChatPanel MCP — connecting your agents to: ${t} mcp`,""],n={configured:"✓",already:"•",would:"→",manual:"✎",absent:"·",error:"✕"};for(const r of s){const p=P[r.id]||r.id;if(r.status==="absent")continue;const d=` ${n[r.status]||"?"} ${p}`;r.status==="configured"?e.push(`${d} — configured${r.backup?` (backup: ${r.backup})`:""}`):r.status==="already"?e.push(`${d} — already connected`):r.status==="would"?e.push(`${d} — would configure:
15
+ ${(r.preview||"").split(`
16
+ `).join(`
17
+ `)}`):r.status==="manual"?e.push(`${d} — add it yourself:
18
+ ${r.snippet.split(`
19
+ `).join(`
20
+ `)}`):r.status==="error"&&e.push(`${d} — ${r.message}`)}const o=s.filter(r=>r.status==="configured").length;return e.push(""),a?e.push(" (dry run — nothing was written. Re-run without --dry-run to apply.)"):o?e.push(" Done. Restart the configured agent(s) to pick up the new server."):e.push(" Nothing to change."),s.some(r=>r.status==="manual")&&e.push(" Agents marked ✎ use a config format best edited by hand — the snippet above is exact."),`${e.join(`
21
+ `)}
22
+ `}export{N as connectAgents,J as formatConnect,S as resolveServerCommand};
@@ -1,188 +1 @@
1
- // Speaker diarization ("who said what") — in-process, same engine + model dir as
2
- // STT/NER. Two layers:
3
- // engine — load Xenova/wavlm-base-plus-sv and embed a segment of audio into a
4
- // 512-d x-vector (speaker fingerprint). Download-on-demand, fail-open.
5
- // Diarizer — online clustering: keep a running centroid per speaker; a new
6
- // segment joins the nearest centroid if cosine ≥ threshold, else it
7
- // starts a new speaker. Stable "Speaker N" labels within a session.
8
- //
9
- // Honest limits: embeddings separate DIFFERENT speakers well but same-gender / very
10
- // similar voices can merge (synthetic TTS especially). In meetings the mic channel
11
- // is anchored as "You" and clustering only splits the remote channel — so a merge
12
- // there is far less costly. Opt-in per session (diarize:true); off for dictation.
13
-
14
- import { ensureLib, modelRoot } from './ner-engine.js';
15
- import { join } from 'node:path';
16
- import { existsSync, readdirSync } from 'node:fs';
17
-
18
- export const DIARIZE_MODEL = 'Xenova/wavlm-base-plus-sv';
19
-
20
- let _state = 'off'; // 'off' | 'loading' | 'downloading' | 'ready' | 'error'
21
- let _model = null;
22
- let _processor = null;
23
- let _err = null;
24
- let _initPromise = null;
25
- let _progress = null;
26
-
27
- // WASM can't load some quantized exports (see stt runtimeDtype); fp32 is the safe
28
- // cross-runtime choice on the binary, q8 on native.
29
- function runtimeDtype() {
30
- return globalThis.__CHATPANEL_WASM_PATHS__ ? 'fp32' : 'q8';
31
- }
32
-
33
- export function state() { return _state; }
34
- export function isReady() { return _state === 'ready' && !!_model && !!_processor; }
35
- export function progress() { return _progress; }
36
- export function health() { return { configured: _state !== 'off', ok: isReady(), state: _state, model: _model, error: _err }; }
37
-
38
- export function modelOnDisk(modelId = DIARIZE_MODEL, dtype = runtimeDtype()) {
39
- const dir = join(modelRoot(), ...modelId.split('/'), 'onnx');
40
- if (!existsSync(dir)) return false;
41
- const suffix = dtype === 'fp32' ? '' : (dtype === 'q8' ? '_quantized' : `_${dtype}`);
42
- try { return readdirSync(dir).some((f) => f === `model${suffix}.onnx`); }
43
- catch { return false; }
44
- }
45
-
46
- /** @param {{ log?: (m: string) => void, allowDownload?: boolean }} [opts] */
47
- async function load({ log = () => {}, allowDownload = true } = {}) {
48
- let lib;
49
- try { lib = await ensureLib(); }
50
- catch (e) { _state = 'error'; _err = e.message; log(`[diarize] engine unavailable (${e.message})`); return false; }
51
-
52
- const haveLocal = modelOnDisk();
53
- lib.env.allowRemoteModels = haveLocal ? false : !!allowDownload;
54
- if (!haveLocal && !allowDownload) { _state = 'error'; _err = 'model not on disk and downloads disabled'; return false; }
55
-
56
- const prevHost = lib.env.remoteHost;
57
- if (!haveLocal) { try { lib.env.remoteHost = 'https://huggingface.co/'; } catch { /* wavlm isn't on the dl mirror */ } }
58
- _state = haveLocal ? 'loading' : 'downloading';
59
- if (!haveLocal) { _progress = { model: DIARIZE_MODEL, file: null, pct: 0 }; log(`[diarize] downloading ${DIARIZE_MODEL} (one-time)…`); }
60
-
61
- try {
62
- const { AutoModel, AutoProcessor } = lib;
63
- const cb = (p) => {
64
- if (!p) return;
65
- const pct = typeof p.progress === 'number' ? Math.round(p.progress) : (_progress?.pct ?? 0);
66
- if (p.status === 'progress' || p.status === 'download' || p.status === 'initiate') _progress = { model: DIARIZE_MODEL, file: p.file || _progress?.file || null, pct };
67
- };
68
- const processor = await AutoProcessor.from_pretrained(DIARIZE_MODEL, { progress_callback: cb });
69
- const model = await AutoModel.from_pretrained(DIARIZE_MODEL, { dtype: runtimeDtype(), progress_callback: cb });
70
- _processor = processor; _model = model; _state = 'ready'; _err = null; _progress = null;
71
- log(`[diarize] ready — ${DIARIZE_MODEL} @ ${runtimeDtype()}`);
72
- return true;
73
- } catch (e) {
74
- _err = e.message; _progress = null; _state = 'error';
75
- log(`[diarize] load failed (${e.message}) — diarization off`);
76
- return false;
77
- } finally {
78
- try { lib.env.remoteHost = prevHost; } catch { /* optional */ }
79
- }
80
- }
81
-
82
- export function init(cfg = {}) {
83
- // Retry after a FAILED attempt (single-flight only while loading/ready) — else a
84
- // transient failure (e.g. downloads were disabled, or the model wasn't on disk
85
- // yet) would be cached forever and never self-heal once the model is present.
86
- if (_initPromise && _state !== 'error') return _initPromise;
87
- _state = 'loading';
88
- _initPromise = load({ log: cfg.onLog, allowDownload: cfg.allowDownload !== false });
89
- return _initPromise;
90
- }
91
-
92
- // Explicit download (the Gateway-tab "Download" button): force the fetch even if
93
- // the config disabled auto-downloads, and clear any cached failure so it retries.
94
- /** @param {{ onLog?: (m: string) => void }} [opts] */
95
- export function download({ onLog } = {}) {
96
- _initPromise = null;
97
- _state = 'loading';
98
- _initPromise = load({ log: onLog, allowDownload: true });
99
- return _initPromise;
100
- }
101
-
102
- const SR = 16000;
103
-
104
- function l2norm(v) {
105
- let n = 0; for (const x of v) n += x * x;
106
- n = Math.sqrt(n) || 1;
107
- const o = new Float32Array(v.length);
108
- for (let i = 0; i < v.length; i++) o[i] = v[i] / n;
109
- return o;
110
- }
111
-
112
- async function embedOne(audio) {
113
- try {
114
- const inputs = await _processor(audio);
115
- const out = await _model(inputs);
116
- const t = out.embeddings ?? out.logits ?? out.last_hidden_state;
117
- return t?.data ? Float32Array.from(t.data) : null;
118
- } catch { return null; }
119
- }
120
-
121
- // Embed a mono 16 kHz Float32 segment → L2-normalized x-vector, or null if not
122
- // ready. For longer turns we embed several overlapping ~2 s windows and AVERAGE
123
- // the normalized vectors — a more stable speaker fingerprint than one embed of
124
- // the whole (noisy) segment. Cheap on the native runtime (runs once per turn).
125
- export async function embed(audio) {
126
- if (!isReady() || !(audio instanceof Float32Array) || !audio.length) return null;
127
- const win = 2 * SR;
128
- const hop = Math.round(1.3 * SR);
129
- if (audio.length <= Math.round(win * 1.4)) {
130
- const v = await embedOne(audio);
131
- return v ? l2norm(v) : null;
132
- }
133
- const vecs = [];
134
- for (let s = 0; s + win <= audio.length; s += hop) {
135
- const v = await embedOne(audio.subarray(s, s + win));
136
- if (v) vecs.push(l2norm(v));
137
- }
138
- if (!vecs.length) { const v = await embedOne(audio); return v ? l2norm(v) : null; }
139
- const avg = new Float32Array(vecs[0].length);
140
- for (const v of vecs) for (let i = 0; i < avg.length; i++) avg[i] += v[i];
141
- return l2norm(avg); // mean of unit vectors, renormalized
142
- }
143
-
144
- export function _reset() { _state = 'off'; _model = null; _processor = null; _err = null; _initPromise = null; _progress = null; }
145
- export function _setForTest(model, processor) { _model = model; _processor = processor; _state = model ? 'ready' : 'off'; }
146
-
147
- // ── Online speaker clustering ────────────────────────────────────────────────────
148
-
149
- function cosine(a, b) {
150
- let d = 0, na = 0, nb = 0;
151
- for (let i = 0; i < a.length; i++) { d += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; }
152
- const denom = Math.sqrt(na) * Math.sqrt(nb);
153
- return denom ? d / denom : 0;
154
- }
155
-
156
- // A per-session speaker tracker. NOT limited to 2 speakers — this is embedding +
157
- // online clustering, so it scales to N (a 10-person meeting is fine; accuracy just
158
- // softens as more voices sound alike). `threshold` = min cosine to be the SAME
159
- // speaker (lower → fewer speakers/more merging, higher → more speakers/more
160
- // splitting); `maxSpeakers` caps the roster (extra turns fold into the nearest).
161
- export class Diarizer {
162
- constructor({ threshold = 0.75, maxSpeakers = 12 } = {}) {
163
- this.threshold = threshold;
164
- this.maxSpeakers = maxSpeakers;
165
- this.centroids = []; // { id, label, vec: Float32Array, n }
166
- }
167
-
168
- // Assign an embedding to a speaker (nearest centroid ≥ threshold, else new).
169
- // `pinnedLabel` forces a label (used for the mic channel = "You" in meetings).
170
- assign(vec, { pinnedLabel = null } = {}) {
171
- if (!vec) return null;
172
- if (pinnedLabel) return this._merge(this._find(pinnedLabel) || this._create(pinnedLabel), vec);
173
- let best = null, bestSim = -1;
174
- for (const c of this.centroids) { const s = cosine(vec, c.vec); if (s > bestSim) { bestSim = s; best = c; } }
175
- if (best && bestSim >= this.threshold) return this._merge(best, vec);
176
- if (this.centroids.length >= this.maxSpeakers && best) return this._merge(best, vec); // cap: fold into nearest
177
- return this._merge(this._create(`Speaker ${this.centroids.length + 1}`), vec);
178
- }
179
-
180
- _find(label) { return this.centroids.find((c) => c.label === label) || null; }
181
- _create(label) { const c = { id: this.centroids.length + 1, label, vec: null, n: 0 }; this.centroids.push(c); return c; }
182
- _merge(c, vec) {
183
- if (!c.vec) { c.vec = Float32Array.from(vec); }
184
- else { for (let i = 0; i < c.vec.length; i++) c.vec[i] = (c.vec[i] * c.n + vec[i]) / (c.n + 1); } // running mean centroid
185
- c.n += 1;
186
- return { id: c.id, label: c.label };
187
- }
188
- }
1
+ import{ensureLib as S,modelRoot as k}from"./ner-engine.js";import{join as $}from"node:path";import{existsSync as z,readdirSync as D}from"node:fs";const f="Xenova/wavlm-base-plus-sv";let i="off",d=null,m=null,h=null,a=null,u=null;function p(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function T(){return i}function w(){return i==="ready"&&!!d&&!!m}function E(){return u}function L(){return{configured:i!=="off",ok:w(),state:i,model:d,error:h}}function q(r=f,t=p()){const n=$(k(),...r.split("/"),"onnx");if(!z(n))return!1;const e=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return D(n).some(l=>l===`model${e}.onnx`)}catch{return!1}}async function x({log:r=()=>{},allowDownload:t=!0}={}){let n;try{n=await S()}catch(o){return i="error",h=o.message,r(`[diarize] engine unavailable (${o.message})`),!1}const e=q();if(n.env.allowRemoteModels=e?!1:!!t,!e&&!t)return i="error",h="model not on disk and downloads disabled",!1;const l=n.env.remoteHost;if(!e)try{n.env.remoteHost="https://huggingface.co/"}catch{}i=e?"loading":"downloading",e||(u={model:f,file:null,pct:0},r(`[diarize] downloading ${f} (one-time)…`));try{const{AutoModel:o,AutoProcessor:s}=n,y=c=>{if(!c)return;const M=typeof c.progress=="number"?Math.round(c.progress):u?.pct??0;(c.status==="progress"||c.status==="download"||c.status==="initiate")&&(u={model:f,file:c.file||u?.file||null,pct:M})},v=await s.from_pretrained(f,{progress_callback:y}),A=await o.from_pretrained(f,{dtype:p(),progress_callback:y});return m=v,d=A,i="ready",h=null,u=null,r(`[diarize] ready — ${f} @ ${p()}`),!0}catch(o){return h=o.message,u=null,i="error",r(`[diarize] load failed (${o.message}) — diarization off`),!1}finally{try{n.env.remoteHost=l}catch{}}}function O(r={}){return a&&i!=="error"||(i="loading",a=x({log:r.onLog,allowDownload:r.allowDownload!==!1})),a}function I({onLog:r}={}){return a=null,i="loading",a=x({log:r,allowDownload:!0}),a}const b=16e3;function g(r){let t=0;for(const e of r)t+=e*e;t=Math.sqrt(t)||1;const n=new Float32Array(r.length);for(let e=0;e<r.length;e++)n[e]=r[e]/t;return n}async function _(r){try{const t=await m(r),n=await d(t),e=n.embeddings??n.logits??n.last_hidden_state;return e?.data?Float32Array.from(e.data):null}catch{return null}}async function j(r){if(!w()||!(r instanceof Float32Array)||!r.length)return null;const t=2*b,n=Math.round(1.3*b);if(r.length<=Math.round(t*1.4)){const o=await _(r);return o?g(o):null}const e=[];for(let o=0;o+t<=r.length;o+=n){const s=await _(r.subarray(o,o+t));s&&e.push(g(s))}if(!e.length){const o=await _(r);return o?g(o):null}const l=new Float32Array(e[0].length);for(const o of e)for(let s=0;s<l.length;s++)l[s]+=o[s];return g(l)}function C(){i="off",d=null,m=null,h=null,a=null,u=null}function N(r,t){d=r,m=t,i=r?"ready":"off"}function F(r,t){let n=0,e=0,l=0;for(let s=0;s<r.length;s++)n+=r[s]*t[s],e+=r[s]*r[s],l+=t[s]*t[s];const o=Math.sqrt(e)*Math.sqrt(l);return o?n/o:0}class W{constructor({threshold:t=.75,maxSpeakers:n=12}={}){this.threshold=t,this.maxSpeakers=n,this.centroids=[]}assign(t,{pinnedLabel:n=null}={}){if(!t)return null;if(n)return this._merge(this._find(n)||this._create(n),t);let e=null,l=-1;for(const o of this.centroids){const s=F(t,o.vec);s>l&&(l=s,e=o)}return e&&l>=this.threshold?this._merge(e,t):this.centroids.length>=this.maxSpeakers&&e?this._merge(e,t):this._merge(this._create(`Speaker ${this.centroids.length+1}`),t)}_find(t){return this.centroids.find(n=>n.label===t)||null}_create(t){const n={id:this.centroids.length+1,label:t,vec:null,n:0};return this.centroids.push(n),n}_merge(t,n){if(!t.vec)t.vec=Float32Array.from(n);else for(let e=0;e<t.vec.length;e++)t.vec[e]=(t.vec[e]*t.n+n[e])/(t.n+1);return t.n+=1,{id:t.id,label:t.label}}}export{f as DIARIZE_MODEL,W as Diarizer,C as _reset,N as _setForTest,I as download,j as embed,L as health,O as init,w as isReady,q as modelOnDisk,E as progress,T as state};
package/src/egress.js ADDED
@@ -0,0 +1,2 @@
1
+ import{isBlockedHost as f}from"@chatpanel/pii";const w=()=>new Date().toISOString();function g(t){try{const e=typeof t=="string"?new URL(t):t instanceof URL?t:new URL(t?.url);return{host:e.hostname,port:e.port||(e.protocol==="https:"?"443":e.protocol==="http:"?"80":""),scheme:e.protocol.replace(":","")}}catch{return null}}const d=t=>{const e=String(t||"").toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e==="[::1]"?!0:f(e,{allowLoopback:!1,allowPrivate:!1})&&!f(e,{allowLoopback:!0,allowPrivate:!0})};function m({clock:t=w}={}){const e=new Map;return{record(o){const s=g(o);if(!s||!s.host)return;const r=`${s.scheme}://${s.host}:${s.port}`,a=t(),n=e.get(r);if(n){n.count+=1,n.lastAt=a;return}e.set(r,{host:s.host,port:s.port,scheme:s.scheme,local:d(s.host),count:1,firstAt:a,lastAt:a})},snapshot(){return[...e.values()].sort((o,s)=>o.local===s.local?s.count-o.count:o.local?1:-1)},reset(){e.clear()}}}let b=null;function E(t=globalThis,{allow:e=null}={}){if(t.__chatpanelEgress)return e&&t.__chatpanelEgress.setGate(e),t.__chatpanelEgress;const o=m();let s=e;o.setGate=a=>{s=a},o.blocked=[];const r=t.fetch;return typeof r=="function"&&(t.fetch=function(n,i){let l=null;try{l=g(n),o.record(n)}catch{}if(s&&l?.host){let h=!0;try{h=s(`${l.scheme}://${l.host}:${l.port}`,{local:d(l.host)})}catch{h=!0}if(!h){const p=`${l.host}:${l.port}`;o.blocked.includes(p)||o.blocked.push(p);const u=new Error(`egress to ${l.host} is blocked by your organisation’s policy`);return u.code="EGRESS_POLICY",Promise.reject(u)}}return r.call(this,n,i)}),t.__chatpanelEgress=o,t===globalThis&&(b=o),o}function y(){return b||(globalThis.__chatpanelEgress??null)}function c(t){try{return new URL(t).host}catch{return String(t||"")}}function $(t={},e=process.env){const o=[],s=(n,i,{when:l="always",off:h=null,local:p=!1,data:u=""}={})=>{n&&o.push({host:n,purpose:i,when:l,off:h,local:p,data:u})};s("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),s("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),s("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),e.CHATPANEL_SELF_UPDATE!=="off"&&(s("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),s("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[n,i]of Object.entries(t.upstreams||{}))i?.baseUrl&&s(c(i.baseUrl),`model upstream "${n}" — chat requests (after redaction) go here`,{when:`a request addressed to ${n}`,off:`upstreams.${n}.baseUrl`,local:d(c(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const n of t.destinations||[])n?.baseUrl&&s(c(n.baseUrl),`destination "${n.id||n.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${n.id||"it"}`,off:"destinations[]",local:d(c(n.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});s("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),t.ner?.url&&s(c(t.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:d(c(t.ner.url).split(":")[0]),data:"the text being redacted"});const r=t.tts||{};if(r.provider==="openai"||r.provider==="elevenlabs"){const n=r.remote?.baseUrl?c(r.remote.baseUrl):r.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";s(n,`remote read-aloud voice (${r.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:r.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}const a=t.bridge?.url||"http://127.0.0.1:4319";return s(c(a),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),o}function k(t,{ledger:e=y(),version:o="",startedAt:s=null,env:r=process.env,managed:a=null}={}){return{ok:!0,version:o,since:s?new Date(s).toISOString():null,...a?{managed:a,blocked:e?.blocked||[]}:{},scope:"this gateway process’s own outbound requests. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:e?e.snapshot():[],declared:$(t,r)}}function L(t){const e=[];e.push(`ChatPanel Gateway ${t.version||""} — egress audit`.trim()),t.since&&e.push(`observed since ${t.since}`),e.push(""),e.push("OBSERVED — hosts this process has actually contacted"),t.observed?.length||e.push(" (none yet)");for(const o of t.observed||[])e.push(` ${o.local?"[local] ":""}${o.scheme}://${o.host}:${o.port} ×${o.count} last ${o.lastAt}`);e.push(""),e.push("DECLARED — hosts this configuration allows, and why");for(const o of t.declared||[])e.push(` ${o.local?"[local] ":""}${o.host}`),e.push(` ${o.purpose}`),e.push(` when: ${o.when}${o.off?` · off: ${o.off}`:""}`),o.data&&e.push(` sends: ${o.data}`);return t.managed&&(e.push(""),e.push(`POLICY — ${t.managed.name||t.managed.org||"managed"} (${t.managed.signed?"signed":"unsigned file"}, hash ${String(t.managed.policyHash||"").slice(0,12)}…)`),e.push(` enforcing: ${Object.entries(t.managed.enforces||{}).filter(([,o])=>o).map(([o,s])=>s===!0?o:`${o}=${s}`).join(", ")||"nothing yet"}`),e.push(` refused this session: ${t.blocked?.length?t.blocked.join(", "):"none"}`)),e.push(""),e.push(`Scope: ${t.scope}`),e.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),e.join(`
2
+ `)}export{m as createEgressLedger,$ as declaredEgress,k as egressAudit,y as egressLedger,L as formatAudit,E as installEgressLedger};