@chatpanel/gateway 0.8.6 → 0.9.1

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.
package/README.md CHANGED
@@ -194,6 +194,33 @@ Streaming (SSE) is supported on all three: placeholders are restored on the fly,
194
194
  holding back a tail so a token split across chunks (`[[PER` … `SON_1]]`) still
195
195
  restores cleanly.
196
196
 
197
+ ### Who may call what
198
+
199
+ The gateway binds to loopback, refuses any non-loopback `Host` (no DNS rebinding) and any
200
+ web `Origin` not in `allowedOrigins` (no drive-by page). Beyond that, callers are told
201
+ apart by two honest signals — the browser's `Origin` header and a per-install token —
202
+ into four levels (`@chatpanel/pii/trust.js`, the same classifier the bridge applies):
203
+
204
+ | Caller | How it's recognised | May |
205
+ |---|---|---|
206
+ | **pinned** | ChatPanel's published Chrome/Edge extension id in `Origin` (+ `allowedExtensionIds`) | everything |
207
+ | **token** | `Authorization: Bearer` / `X-ChatPanel-Token` = `~/.chatpanel/gateway-token` (0600) — the desktop, `chatpanel-gateway mcp`, channels, a paired browser | everything |
208
+ | **unpaired** | any other extension or a `localhost` page | chat through an *agent* capped to the conversational tier (no files, shell, web, workspace or credentials); API destinations as normal; no admin |
209
+ | **local** | no `Origin`, no token — some process | API destinations (the proxy is the product); **not** an agent destination, **not** admin |
210
+
211
+ An **agent destination spawns a process on your machine**, so it needs a paired caller.
212
+ An OpenAI-compatible client sends the token as its API key
213
+ (`OPENAI_API_KEY=$(cat ~/.chatpanel/gateway-token)`); the refusal (`401
214
+ agent_lane_token_required`) says so. `bridge.openAgentLane: true` restores the pre-0.9.0
215
+ behaviour for a trusted machine — the startup log calls it out.
216
+
217
+ **Pairing** a browser the gateway does not recognise (ChatPanel's Firefox build, whose
218
+ origin is a per-profile UUID; a dev build): `chatpanel-gateway pair` prints a one-time
219
+ code (5 minutes, 5 attempts); enter it in ChatPanel → Settings → Agent Tools. The exchange
220
+ (`POST /pair`) hands over the gateway token and, when this machine has one, the bridge
221
+ token — one code covers both. `POST /whoami` → `{ trust, paired }` tells a client where
222
+ it stands.
223
+
197
224
  ## Use it as an MCP server (Codex, Claude Code, any MCP client)
198
225
 
199
226
  Point one MCP server at the gateway and any CLI agent can reach your **local history**
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- const a=process.argv[2];try{if(a==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(a==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(a==="mcp"){const{runMcpServer:t}=await import("../src/mcp.js");await t()}else if(a==="tools"||a==="call"){const{runMcpCli:t}=await import("../src/mcp-cli.js");process.exit(await t(process.argv.slice(2)))}else if(a==="policy"){const{loadPolicy:t,formatPolicy:o,PolicyLoadError:s}=await import("../src/policy.js");try{const e=await t();process.argv.includes("--json")?console.log(JSON.stringify(e?{...e,label:void 0}:null,null,2)):console.log(o(e))}catch(e){throw e instanceof s&&(console.error(`org policy: ${e.message}`),process.exit(78)),e}}else if(a==="--audit"){const{egressAudit:t,formatAudit:o}=await import("../src/egress.js"),{loadConfig:s}=await import("../src/config.js"),{readFileSync:e}=await import("node:fs"),{join:l}=await import("node:path"),c=await import("node:os"),g=s(),i=`http://127.0.0.1:${g.port||4320}`;let n=null,p=`no gateway running at ${i}`;try{const u=e(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||l(c.homedir(),".chatpanel","gateway-token"),"utf8").trim(),r=await fetch(`${i}/audit`,{headers:{authorization:`Bearer ${u}`},signal:AbortSignal.timeout(2500)});if(r.ok)n=await r.json();else if(r.status===404){const d=await fetch(`${i}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);p=`the gateway running at ${i}${d?.version?` (${d.version})`:""} predates --audit (0.7.0) — restart it after updating`}else p=`the gateway at ${i} refused the audit (HTTP ${r.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!n){const u=JSON.parse(e(new URL("../package.json",import.meta.url),"utf8")).version;n={...t(g,{ledger:null,version:u}),observed:[]},console.log(`(${p}; showing what the current config allows)
3
- `)}process.argv.includes("--json")?console.log(JSON.stringify(n,null,2)):console.log(o(n))}else if(a==="local"){const{localStatus:t,formatLocalStatus:o}=await import("../src/local-status.js");process.stdout.write(o(await t()))}else if(a==="connect"){const{connectAgents:t,formatConnect:o}=await import("../src/connect-agents.js"),s=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(o(t({dryRun:s}),{dryRun:s}))}else{const{start:t,VERSION:o}=await import("../src/server.js"),{installService:s,uninstallService:e,serviceStatus:l,stopService:c}=await import("../src/service.js");switch(a){case"--stop":c(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(o);break;case"--install":s(),console.log("ChatPanel Privacy Gateway: installed login auto-start and started it.");break;case"--uninstall":e(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(l()?"installed (auto-start registered)":"not installed");break;case void 0:await t();break;default:console.error(`unknown option: ${a}
4
- Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|policy|--audit|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(t){console.error(`error: ${t.message}`),process.exit(1)}
2
+ const a=process.argv[2];try{if(a==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(a==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(a==="mcp"){const{runMcpServer:t}=await import("../src/mcp.js");await t()}else if(a==="tools"||a==="call"){const{runMcpCli:t}=await import("../src/mcp-cli.js");process.exit(await t(process.argv.slice(2)))}else if(a==="policy"){const{loadPolicy:t,formatPolicy:o,PolicyLoadError:i}=await import("../src/policy.js");try{const e=await t();process.argv.includes("--json")?console.log(JSON.stringify(e?{...e,label:void 0}:null,null,2)):console.log(o(e))}catch(e){throw e instanceof i&&(console.error(`org policy: ${e.message}`),process.exit(78)),e}}else if(a==="--audit"){const{egressAudit:t,formatAudit:o}=await import("../src/egress.js"),{loadConfig:i}=await import("../src/config.js"),{readFileSync:e}=await import("node:fs"),{join:g}=await import("node:path"),r=await import("node:os"),l=i(),s=`http://127.0.0.1:${l.port||4320}`;let n=null,c=`no gateway running at ${s}`;try{const u=e(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||g(r.homedir(),".chatpanel","gateway-token"),"utf8").trim(),p=await fetch(`${s}/audit`,{headers:{authorization:`Bearer ${u}`},signal:AbortSignal.timeout(2500)});if(p.ok)n=await p.json();else if(p.status===404){const d=await fetch(`${s}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);c=`the gateway running at ${s}${d?.version?` (${d.version})`:""} predates --audit (0.7.0) — restart it after updating`}else c=`the gateway at ${s} refused the audit (HTTP ${p.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!n){const u=JSON.parse(e(new URL("../package.json",import.meta.url),"utf8")).version;n={...t(l,{ledger:null,version:u}),observed:[]},console.log(`(${c}; showing what the current config allows)
3
+ `)}process.argv.includes("--json")?console.log(JSON.stringify(n,null,2)):console.log(o(n))}else if(a==="pair"){const{loadConfig:t}=await import("../src/config.js"),{readFileSync:o}=await import("node:fs"),{join:i}=await import("node:path"),e=await import("node:os"),r=`http://127.0.0.1:${t().port||4320}`,l=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||i(e.homedir(),".chatpanel","gateway-token");try{const s=o(l,"utf8").trim(),n=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${s}`},signal:AbortSignal.timeout(2500)}),c=await n.json().catch(()=>({}));if(n.status===404)throw new Error(`the gateway at ${r} predates pairing (0.9.0) — update and restart it`);if(!n.ok)throw new Error(c.error||`HTTP ${n.status}`);console.log(`Pairing code: ${c.display||c.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(s){console.error(`could not get a pairing code from the gateway at ${r}: ${s?.message||s}${/ENOENT/.test(String(s?.message))?` (no token at ${l} — has the gateway started once?)`:""}`),process.exit(1)}}else if(a==="local"){const{localStatus:t,formatLocalStatus:o}=await import("../src/local-status.js");process.stdout.write(o(await t()))}else if(a==="connect"){const{connectAgents:t,formatConnect:o}=await import("../src/connect-agents.js"),i=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(o(t({dryRun:i}),{dryRun:i}))}else{const{start:t,VERSION:o}=await import("../src/server.js"),{installService:i,uninstallService:e,serviceStatus:g,stopService:r}=await import("../src/service.js");switch(a){case"--stop":r(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(o);break;case"--install":i(),console.log("ChatPanel Privacy Gateway: installed login auto-start and started it.");break;case"--uninstall":e(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(g()?"installed (auto-start registered)":"not installed");break;case void 0:await t();break;default:console.error(`unknown option: ${a}
4
+ Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|pair|policy|--audit|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(t){console.error(`error: ${t.message}`),process.exit(1)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.8.6",
3
+ "version": "0.9.1",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -21,9 +21,9 @@
21
21
  "node": ">=18"
22
22
  },
23
23
  "dependencies": {
24
- "@chatpanel/bridge": "^0.12.5",
24
+ "@chatpanel/bridge": "^0.13.1",
25
25
  "@chatpanel/events": "^0.108.0",
26
- "@chatpanel/pii": "^0.7.4",
26
+ "@chatpanel/pii": "^0.8.0",
27
27
  "@huggingface/transformers": "^4.2.0",
28
28
  "onnxruntime-web": "1.26.0-dev.20260416-b7804b056c",
29
29
  "phonemizer": "^1.2.1"
package/src/config.js CHANGED
@@ -1 +1 @@
1
- import{readFileSync as s,existsSync as p}from"node:fs";import{join as l}from"node:path";import A from"node:os";import{DEFAULT_MODEL as c}from"./models.js";import{DEFAULT_STT_MODEL as d}from"./stt-models.js";const a={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],maxBodyBytes:26214400,pro:{entitlementToken:"",free:{used:0}},bridge:{url:"http://127.0.0.1:4319",agent:"codex",token:"",permissionMode:"default",workingDir:""},upstreams:{openai:{baseUrl:"https://api.openai.com"},anthropic:{baseUrl:"https://api.anthropic.com"}},redaction:{tier:"basic",dictionary:[],detection:{backend:"off"},redactSystem:!0},ner:{autostart:!0,model:c,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:d,allowDownload:!0,diarize:!0},tts:{enabled:!0,provider:"local",model:"",voice:"",allowDownload:!0,remote:{baseUrl:"",model:"",voice:"",redact:!0}},logRequests:!0,logDetail:"off"};function o(e,t){if(Array.isArray(t))return t;if(t&&typeof t=="object"&&e&&typeof e=="object"){const i={...e};for(const r of Object.keys(t))i[r]=o(e[r],t[r]);return i}return t===void 0?e:t}function _(e=process.env){let t=a;const i=e.CHATPANEL_GATEWAY_CONFIG||l(A.homedir(),".chatpanel","gateway.config.json");if(p(i))try{t=o(t,JSON.parse(s(i,"utf8")))}catch(n){throw new Error(`bad config file ${i}: ${n.message}`)}e.CHATPANEL_GATEWAY_HOST&&(t=o(t,{host:e.CHATPANEL_GATEWAY_HOST})),e.CHATPANEL_GATEWAY_PORT&&(t=o(t,{port:Number(e.CHATPANEL_GATEWAY_PORT)})),e.OPENAI_BASE_URL&&(t=o(t,{upstreams:{openai:{baseUrl:e.OPENAI_BASE_URL}}})),e.ANTHROPIC_BASE_URL&&(t=o(t,{upstreams:{anthropic:{baseUrl:e.ANTHROPIC_BASE_URL}}})),e.CHATPANEL_REDACTION_TIER&&(t=o(t,{redaction:{tier:e.CHATPANEL_REDACTION_TIER}}));const r=Number(t.port);return(!Number.isInteger(r)||r<1||r>65535)&&(t.port!==a.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(t.port)} — using ${a.port}`),t=o(t,{port:a.port})),t}export{a as DEFAULTS,_ as loadConfig};
1
+ import{readFileSync as s,existsSync as l}from"node:fs";import{join as p}from"node:path";import A from"node:os";import{DEFAULT_MODEL as c}from"./models.js";import{DEFAULT_STT_MODEL as d}from"./stt-models.js";const a={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],maxBodyBytes:26214400,pro:{entitlementToken:"",free:{used:0}},bridge:{url:"http://127.0.0.1:4319",agent:"codex",token:"",permissionMode:"default",workingDir:"",openAgentLane:!1},upstreams:{openai:{baseUrl:"https://api.openai.com"},anthropic:{baseUrl:"https://api.anthropic.com"}},redaction:{tier:"basic",dictionary:[],detection:{backend:"off"},redactSystem:!0},ner:{autostart:!0,model:c,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:d,allowDownload:!0,diarize:!0},tts:{enabled:!0,provider:"local",model:"",voice:"",allowDownload:!0,remote:{baseUrl:"",model:"",voice:"",redact:!0}},logRequests:!0,logDetail:"off"};function o(e,t){if(Array.isArray(t))return t;if(t&&typeof t=="object"&&e&&typeof e=="object"){const i={...e};for(const r of Object.keys(t))i[r]=o(e[r],t[r]);return i}return t===void 0?e:t}function _(e=process.env){let t=a;const i=e.CHATPANEL_GATEWAY_CONFIG||p(A.homedir(),".chatpanel","gateway.config.json");if(l(i))try{t=o(t,JSON.parse(s(i,"utf8")))}catch(n){throw new Error(`bad config file ${i}: ${n.message}`)}e.CHATPANEL_GATEWAY_HOST&&(t=o(t,{host:e.CHATPANEL_GATEWAY_HOST})),e.CHATPANEL_GATEWAY_PORT&&(t=o(t,{port:Number(e.CHATPANEL_GATEWAY_PORT)})),e.OPENAI_BASE_URL&&(t=o(t,{upstreams:{openai:{baseUrl:e.OPENAI_BASE_URL}}})),e.ANTHROPIC_BASE_URL&&(t=o(t,{upstreams:{anthropic:{baseUrl:e.ANTHROPIC_BASE_URL}}})),e.CHATPANEL_REDACTION_TIER&&(t=o(t,{redaction:{tier:e.CHATPANEL_REDACTION_TIER}}));const r=Number(t.port);return(!Number.isInteger(r)||r<1||r>65535)&&(t.port!==a.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(t.port)} — using ${a.port}`),t=o(t,{port:a.port})),t}export{a as DEFAULTS,_ as loadConfig};
@@ -1 +1 @@
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
+ import{writeFileSync as l,mkdirSync as a,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()){a(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,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools};l(o,JSON.stringify(t,null,2),{mode:384});try{d(o,384)}catch{}}function S(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:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],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 f(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)),typeof o.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=o.bridge.openAgentLane)),Array.isArray(o.allowedExtensionIds)&&(e.allowedExtensionIds=o.allowedExtensionIds.map(t=>String(t).trim()).filter(t=>/^[a-p]{32}$/.test(t))),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,f as bridgeAgentOptions,p as configPath,w as isSelfDestination,g as persistConfig,S as publicConfig};
@@ -1 +1 @@
1
- import{randomBytes as s,timingSafeEqual as c}from"node:crypto";import{existsSync as a,readFileSync as m,writeFileSync as f,mkdirSync as u,chmodSync as d}from"node:fs";import{join as l,dirname as h}from"node:path";import y from"node:os";const g=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||l(y.homedir(),".chatpanel","gateway-token");let t="";function k(e=g){try{if(a(e)&&(t=m(e,"utf8").trim()),!t){t=s(32).toString("hex"),u(h(e),{recursive:!0,mode:448}),f(e,t,{mode:384});try{d(e,384)}catch{}}}catch(n){console.warn(`[gateway] could not initialise admin token: ${n?.message||n}`)}return t}function x(e){return typeof e=="string"&&(/^chrome-extension:\/\//.test(e)||/^moz-extension:\/\//.test(e))}function S(e){if(!t)return!1;const n=String(e?.authorization||""),r=(n.startsWith("Bearer ")?n.slice(7):String(e?.["x-chatpanel-token"]||"")).trim();if(!r)return!1;const o=Buffer.from(r),i=Buffer.from(t);return o.length===i.length&&c(o,i)}function w(e){return x(e.headers?.origin)||S(e.headers)}export{k as ensureGatewayToken,w as isAdminAuthorized,x as isExtensionOrigin};
1
+ import{randomBytes as u,randomInt as f,timingSafeEqual as m}from"node:crypto";import{callerTrust as d,isPaired as l,parseExtensionIds as r,createPairingStore as T}from"@chatpanel/pii";import{existsSync as p,readFileSync as A,writeFileSync as E,mkdirSync as S,chmodSync as h}from"node:fs";import{join as _,dirname as g}from"node:path";import x from"node:os";const N=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||_(x.homedir(),".chatpanel","gateway-token");let n="";function v(e=N){try{if(p(e)&&(n=A(e,"utf8").trim()),!n){n=u(32).toString("hex"),S(g(e),{recursive:!0,mode:448}),E(e,n,{mode:384});try{h(e,384)}catch{}}}catch(t){console.warn(`[gateway] could not initialise admin token: ${t?.message||t}`)}return n}let a=r(process.env.CHATPANEL_GATEWAY_EXTENSION_IDS);function C(){return n}function H(e){a=[...new Set([...r(process.env.CHATPANEL_GATEWAY_EXTENSION_IDS),...r((e||[]).join(","))])]}function y(e){return e.chatpanelTrust||(e.chatpanelTrust=d({origin:e.headers?.origin||"",hasToken:I(e.headers),extensionIds:a})),e.chatpanelTrust}const c=T({random:()=>f(0,1e6)/1e6});function B(){return c.issue()}function D(e){return c.claim(e)}function I(e){if(!n)return!1;const t=String(e?.authorization||""),o=(t.startsWith("Bearer ")?t.slice(7):String(e?.["x-chatpanel-token"]||"")).trim();if(!o)return!1;const i=Buffer.from(o),s=Buffer.from(n);return i.length===s.length&&m(i,s)}function W(e){return l(y(e))}export{y as callerTrustOf,D as claimPairingCode,C as currentGatewayToken,v as ensureGatewayToken,W as isAdminAuthorized,B as issuePairingCode,H as setPinnedExtensionIds};
package/src/server.js CHANGED
@@ -1,19 +1,19 @@
1
- import{createServer as dt}from"node:http";import{loadConfig as xe}from"./config.js";import{startEntitlementRefresh as ut,maybeRevalidate as mt}from"./entitlement-refresh.js";import{redactSegments as me,segment as Ae}from"./redact.js";import{pipeRestoredStream as pt,pipeRestoredOpenAIStream as yt,makeTokenRestorer as Pe,restoreDeep as ht}from"./stream.js";import{restoreText as ft,gatedDictionary as gt,narrowSpecs as bt,makeToolHarness as wt,placeholderToolNote as kt,placeholderNote as St,assertEndpointUrl as vt}from"@chatpanel/pii";import{ensureGatewayToken as $e,isAdminAuthorized as K}from"./gateway-token.js";import{installEgressLedger as Tt,egressAudit as _t}from"./egress.js";import{initPolicy as Ot,activePolicy as Et,applyPolicyToConfig as Ne,managedSummary as re,PolicyLoadError as xt}from"./policy.js";import{routeAllowed as Be,agentAllowed as At,egressAllowed as Pt}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as se}from"./bridge.js";import{secureFetch as Ce}from"./secure-fetch.js";import{streamBridgeChat as De,readBridgeToken as ae,openBridgeChat as $t}from"./bridge.js";import{createRelaySession as Nt,getRelaySession as je,endRelaySession as ie,pumpBridgeStream as Bt,deliverToolResult as Ct,toolsToSpecs as Dt,parseToolCallId as Ie,touchRelaySession as pe}from"./toolrelay.js";import{shaperFor as ye}from"./shape.js";import{startNer as jt,ensureNer as he}from"./ner.js";import{installTimestampedConsole as It}from"./log.js";import{saveBackupSecret as Mt,clearBackupSecret as Rt,loadBackupSecret as Me,hasBackupSecret as Re}from"./history-store.js";import{createMemoryStore as Lt}from"./memory-store.js";import{createPrefsStore as Gt}from"./prefs-store.js";import{createTeamStore as zt,loadOrCreateKey as fe}from"./team-store.js";import{createScorecardStore as Vt}from"./scorecard-store.js";import{createEngineLedgerStore as Jt}from"./engine-ledger-store.js";import{createProjectStore as Ht}from"./project-store.js";import{applicationsFor as Ut,recruitPass as Ft}from"./recruiting.js";import{ensureBridge as Wt}from"./bridge-supervisor.js";import{checkForUpdate as Kt,updateStatus as Zt,startUpdate as Yt,updateJob as Xt}from"./update.js";import{createHistoryStore as Qt}from"./sqlite-store.js";import{ingestBackups as ge}from"./backup-ingest.js";import*as B from"./ner-engine.js";import*as x from"./stt-engine.js";import*as P from"./diarize-engine.js";import{MODEL_CATALOG as qt,isKnownModel as eo,isValidCustomModelId as to}from"./models.js";import{STT_MODEL_CATALOG as oo,isKnownSttModel as ro,isValidCustomSttId as no,DEFAULT_STT_MODEL as be,STT_DTYPES as so,isValidDtype as ao}from"./stt-models.js";import*as S from"./tts-engine.js";import{TTS_MODEL_CATALOG as Le,TTS_VOICES as io,isKnownTtsModel as lo,isValidCustomTtsId as co,isKnownVoice as Ge,isValidVoiceId as ze,DEFAULT_TTS_MODEL as Ve,DEFAULT_TTS_VOICE as Y,TTS_DTYPES as uo,isValidTtsDtype as mo,MAX_TTS_CHARS as Je,ttsModelHasCustomVoices as po,resolveDefaultModel as He,POCKET_VOICES as yo,DEFAULT_POCKET_VOICE as le,isPocketVoice as ce,ttsModelEngine as de}from"./tts-models.js";import{ttsDestination as ho,synthesizeRemote as fo,isValidRemoteVoice as go}from"./tts-remote.js";import{rawOrtAvailable as we}from"./ort.js";import*as L from"./tts-voices.js";import{resolveTtsVoice as bo}from"./tts-voice-resolve.js";import{resolvePro as Q,checkQuota as wo,consume as ko,usage as So}from"./freegate.js";import{publicConfig as Ue,applyConfigPatch as vo,applyNerModelSelection as To,persistConfig as ee,configPath as q,bridgeAgentOptions as Fe}from"./configstore.js";import{resolveDestination as We,aggregateModelsAsync as _o,listDestinations as Oo}from"./router.js";import{makeAccessEvent as Ke}from"./observability.js";import{createPersistentAccessLog as Eo}from"./access-log-store.js";import{planQueries as xo,multiSearch as Ao}from"./rrf.js";import*as ke from"./openai.js";import*as Ze from"./responses.js";import*as Se from"./anthropic.js";const Z="0.8.6",$=await Qt(),J=await Lt(),F=Gt(),te=Vt({key:fe()}),oe=Jt({key:fe()}),G=Ht({key:fe()}),C=zt({scorecards:te,engines:oe}),ve=new Set,Ye=(t,l)=>{for(const d of ve)try{d({applied:t,by:l,revision:F.revision})}catch{}},Te=Eo(),Xe=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Po=16,$o=/^mcp[_-]/i,Qe=t=>t&&t.function&&t.function.name||t&&t.name||"",No=t=>t&&t.function&&t.function.description||t&&t.description||"";function qe(t){return typeof t=="string"?t:Array.isArray(t)?t.map(l=>typeof l=="string"?l:l&&(l.text||l.content)||"").join(" "):""}function Bo(t,l){if(!t)return"";if(l==="responses"){const r=t.input;return typeof r=="string"?r:Array.isArray(r)?r.map(o=>qe(o&&(o.content??o))).join(" "):""}const d=Array.isArray(t.messages)?t.messages:[];for(let r=d.length-1;r>=0;r--)if(d[r]&&d[r].role==="user")return qe(d[r].content);return""}const et=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function tt(t){if(!t)return!1;const l=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return l==="localhost"||l==="127.0.0.1"||l==="::1"}function Co(t,l){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(l.allowedOrigins)&&l.allowedOrigins.includes(t)}function Do(t,l){t.setHeader("Access-Control-Allow-Origin",l||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const ot=Date.now();function jo(t){if(!t)return"";const l={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(d=>`${l[d]||d} ${t[d]}ms`).join(" · ")}function Io(t){const l=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return l?{kind:l[1],id:l[2],...l[3]?{model:l[3]}:{}}:null}function Mo(t){const l=performance.now(),d={};let r=!1;const o=(u,c)=>{d[u]=Math.round(c*10)/10};return{meta:{},timings:d,mark:o,lap(u,c){o(u,performance.now()-c)},clock(){return performance.now()},commit(){if(r)return;r=!0,o("total",performance.now()-l);const u={...this.meta,timings:d};setImmediate(()=>{t(u),console.log(`[gateway] model=${u.model||"-"} → ${u.dest?`${u.dest}(${u.type})`:"none"} · ${u.redaction==="off"?"redaction OFF (client request)":`redacted ${u.redacted||0}`}${u.sanitized?` · scrubbed ${u.sanitized} hidden`:""}${u.narrowed?` · narrowed -${u.narrowed}`:""} · ${jo(d)}`)})}}}function rt(t,l){if(!t||!t.byToken||l!=="types"&&l!=="values")return;const d=[];for(const[r,o]of t.byToken){const u=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(r),c=u?u[1]:"PII",h=r.replace(/^\[\[|\]\]$/g,"");d.push(l==="values"?{token:h,type:c,value:o}:{token:h,type:c})}return d}function Ro(t,l,d){return Se.matches(t)||"anthropic-version"in l?{kind:"anthropic",adapter:Se,redactable:Se.matches(t),base:d.upstreams?.anthropic?.baseUrl}:Ze.matches(t)?{kind:"responses",adapter:Ze,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:ke,redactable:ke.matches(t),base:d.upstreams?.openai?.baseUrl}}function _e(t,l){const d=String(t||"");if(Xe.has(d))return{agent:d,agentModel:""};const r=d.indexOf("/");if(r>0){const o=d.slice(0,r);if(Xe.has(o))return{agent:o,agentModel:d.slice(r+1)}}return{agent:l.bridge.agent,agentModel:""}}function nt(t,l){return _e(t,l).agent}function Lo(t,l){if(l!=="openai"||!t)return!1;const d=ke.extractLatestToolResult(t);if(!d)return!1;const r=Ie(d.tool_call_id);return!!(r&&je(r.gwId))}function Go(t,l){try{const d=new URL(t),r=d.hostname.replace(/^\[|\]$/g,""),o=r==="127.0.0.1"||r==="localhost"||r==="::1",u=d.port||(d.protocol==="https:"?"443":"80");return o&&String(u)===String(l.port)}catch{return!1}}async function T(t,l){const d=[];let r=0;for await(const o of t){if(r+=o.length,l&&r>l){const u=new Error("payload too large");throw u.code=413,u}d.push(o)}return Buffer.concat(d)}function s(t,l,d){t.writeHead(l,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function st(t){const l=t.redaction?.detection?.url;return!l||t.redaction?.detection?.backend==="off"?null:l}function Oe(t){const l=t?.redaction?.detection,d=t?.redaction?.tier==="full"?"full":"basic";if(l&&l.backend&&l.backend!=="off")return{source:"external",backend:l.backend,state:"external",model:l.model||null,ready:!0,tier:d,coverage:d==="full"?"names":"patterns"};const r=B.health(),o=r.ok&&d==="full";return{source:"bundled",state:r.state,model:r.model||t?.ner?.model||null,installed:B.modelOnDisk(t?.ner?.model||void 0),error:r.error||null,ready:o,tier:d,coverage:o?"names":"patterns"}}async function at(t){if(B.state()!=="off"){const d=B.health();return{configured:d.configured,ok:d.ok,state:d.state,model:d.model,error:d.error||null,url:d.configured?`http://${t.host}:${t.port}/ner`:null}}const l=st(t);if(!l)return{configured:!1,ok:!1,url:null,model:null};try{const d=await Ce(l.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:l,model:null};const r=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:l,model:r.model||null}}catch{return{configured:!0,ok:!1,url:l,model:null}}}function zo(t,l){const d={};for(const[r,o]of Object.entries(t)){const u=r.toLowerCase();u.startsWith("x-chatpanel-")||et.has(u)||(d[r]=o)}d["accept-encoding"]="identity";try{d.host=new URL(l).host}catch{}return d}async function it(t,l,d,r){const o=Pe(l.vault),u=r?r.clock():0;let c=u,h=!0;const b=()=>{r&&h&&(r.lap("upstream",u),c=r.clock(),h=!1)};await Bt(l,{onText:E=>{b(),pe(l.id);const p=o.push(E);p&&t.write(d.sseDelta(p))},onToolRequest:({name:E,restoredArgs:p,toolId:M})=>{b(),pe(l.id);const A=o.flush();A&&t.write(d.sseDelta(A)),t.write(d.sseToolCalls([{id:M,name:E,arguments:JSON.stringify(p)}])),t.write(d.sseToolFinish()),r&&r.lap("stream",c),t.end(),r?.commit()},onDone:()=>{const E=o.flush();E&&t.write(d.sseDelta(E)),t.write(d.sseTail()),r&&r.lap("stream",c),t.end(),ie(l.id),r?.commit()},onError:E=>{t.write(`data: ${JSON.stringify({error:{message:E.message,type:"bridge_error"}})}
1
+ import{createServer as yt}from"node:http";import{loadConfig as Be}from"./config.js";import{startEntitlementRefresh as ht,maybeRevalidate as ft}from"./entitlement-refresh.js";import{redactSegments as fe,segment as Ce}from"./redact.js";import{pipeRestoredStream as gt,pipeRestoredOpenAIStream as bt,makeTokenRestorer as De,restoreDeep as wt}from"./stream.js";import{restoreText as kt,gatedDictionary as St,narrowSpecs as vt,makeToolHarness as Tt,placeholderToolNote as _t,placeholderNote as Ot,assertEndpointUrl as Et,capRunOptions as xt,isPaired as At}from"@chatpanel/pii";import{ensureGatewayToken as ge,currentGatewayToken as Pt,isAdminAuthorized as F,callerTrustOf as ce,setPinnedExtensionIds as $t,issuePairingCode as Nt,claimPairingCode as Bt}from"./gateway-token.js";import{installEgressLedger as Ct,egressAudit as Dt}from"./egress.js";import{initPolicy as It,activePolicy as jt,applyPolicyToConfig as Ie,managedSummary as ae,PolicyLoadError as Mt}from"./policy.js";import{routeAllowed as je,agentAllowed as Rt,egressAllowed as Lt}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as de}from"./bridge.js";import{secureFetch as Me}from"./secure-fetch.js";import{streamBridgeChat as Re,readBridgeToken as ie,openBridgeChat as Gt}from"./bridge.js";import{createRelaySession as zt,getRelaySession as Le,endRelaySession as ue,pumpBridgeStream as Vt,deliverToolResult as Jt,toolsToSpecs as Ht,parseToolCallId as Ge,touchRelaySession as be}from"./toolrelay.js";import{shaperFor as we}from"./shape.js";import{startNer as Ut,ensureNer as ke}from"./ner.js";import{installTimestampedConsole as Ft}from"./log.js";import{saveBackupSecret as Wt,clearBackupSecret as Kt,loadBackupSecret as ze,hasBackupSecret as Ve}from"./history-store.js";import{createMemoryStore as Zt}from"./memory-store.js";import{createPrefsStore as Yt}from"./prefs-store.js";import{createTeamStore as Xt,loadOrCreateKey as Se}from"./team-store.js";import{createScorecardStore as Qt}from"./scorecard-store.js";import{createEngineLedgerStore as qt}from"./engine-ledger-store.js";import{createProjectStore as eo}from"./project-store.js";import{applicationsFor as to,recruitPass as oo}from"./recruiting.js";import{ensureBridge as ro}from"./bridge-supervisor.js";import{checkForUpdate as no,updateStatus as so,startUpdate as ao,updateJob as io}from"./update.js";import{createHistoryStore as lo}from"./sqlite-store.js";import{ingestBackups as ve}from"./backup-ingest.js";import*as B from"./ner-engine.js";import*as x from"./stt-engine.js";import*as $ from"./diarize-engine.js";import{MODEL_CATALOG as co,isKnownModel as uo,isValidCustomModelId as mo}from"./models.js";import{STT_MODEL_CATALOG as po,isKnownSttModel as yo,isValidCustomSttId as ho,DEFAULT_STT_MODEL as Te,STT_DTYPES as fo,isValidDtype as go}from"./stt-models.js";import*as k from"./tts-engine.js";import{TTS_MODEL_CATALOG as Je,TTS_VOICES as bo,isKnownTtsModel as wo,isValidCustomTtsId as ko,isKnownVoice as He,isValidVoiceId as Ue,DEFAULT_TTS_MODEL as Fe,DEFAULT_TTS_VOICE as Y,TTS_DTYPES as So,isValidTtsDtype as vo,MAX_TTS_CHARS as We,ttsModelHasCustomVoices as To,resolveDefaultModel as Ke,POCKET_VOICES as _o,DEFAULT_POCKET_VOICE as me,isPocketVoice as pe,ttsModelEngine as ye}from"./tts-models.js";import{ttsDestination as Oo,synthesizeRemote as Eo,isValidRemoteVoice as xo}from"./tts-remote.js";import{rawOrtAvailable as _e}from"./ort.js";import*as L from"./tts-voices.js";import{resolveTtsVoice as Ao}from"./tts-voice-resolve.js";import{resolvePro as q,checkQuota as Po,consume as $o,usage as No}from"./freegate.js";import{publicConfig as Ze,applyConfigPatch as Bo,applyNerModelSelection as Co,persistConfig as te,configPath as ee,bridgeAgentOptions as Ye}from"./configstore.js";import{resolveDestination as Xe,aggregateModelsAsync as Do,listDestinations as Io}from"./router.js";import{makeAccessEvent as Qe}from"./observability.js";import{createPersistentAccessLog as jo}from"./access-log-store.js";import{planQueries as Mo,multiSearch as Ro}from"./rrf.js";import*as Oe from"./openai.js";import*as qe from"./responses.js";import*as Ee from"./anthropic.js";const W="0.9.1",N=await lo(),H=await Zt(),K=Yt(),oe=Qt({key:Se()}),re=qt({key:Se()}),G=eo({key:Se()}),C=Xt({scorecards:oe,engines:re}),xe=new Set,et=(t,i)=>{for(const d of xe)try{d({applied:t,by:i,revision:K.revision})}catch{}},Ae=jo(),tt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Lo=16,Go=/^mcp[_-]/i,ot=t=>t&&t.function&&t.function.name||t&&t.name||"",zo=t=>t&&t.function&&t.function.description||t&&t.description||"";function rt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(i=>typeof i=="string"?i:i&&(i.text||i.content)||"").join(" "):""}function Vo(t,i){if(!t)return"";if(i==="responses"){const r=t.input;return typeof r=="string"?r:Array.isArray(r)?r.map(o=>rt(o&&(o.content??o))).join(" "):""}const d=Array.isArray(t.messages)?t.messages:[];for(let r=d.length-1;r>=0;r--)if(d[r]&&d[r].role==="user")return rt(d[r].content);return""}const nt=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function st(t){if(!t)return!1;const i=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return i==="localhost"||i==="127.0.0.1"||i==="::1"}function Jo(t,i){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(i.allowedOrigins)&&i.allowedOrigins.includes(t)}function Ho(t,i){t.setHeader("Access-Control-Allow-Origin",i||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const at=Date.now();function Uo(t){if(!t)return"";const i={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(d=>`${i[d]||d} ${t[d]}ms`).join(" · ")}function Fo(t){const i=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return i?{kind:i[1],id:i[2],...i[3]?{model:i[3]}:{}}:null}function Wo(t){const i=performance.now(),d={};let r=!1;const o=(u,c)=>{d[u]=Math.round(c*10)/10};return{meta:{},timings:d,mark:o,lap(u,c){o(u,performance.now()-c)},clock(){return performance.now()},commit(){if(r)return;r=!0,o("total",performance.now()-i);const u={...this.meta,timings:d};setImmediate(()=>{t(u),console.log(`[gateway] model=${u.model||"-"} → ${u.dest?`${u.dest}(${u.type})`:"none"} · ${u.redaction==="off"?"redaction OFF (client request)":`redacted ${u.redacted||0}`}${u.sanitized?` · scrubbed ${u.sanitized} hidden`:""}${u.narrowed?` · narrowed -${u.narrowed}`:""} · ${Uo(d)}`)})}}}function it(t,i){if(!t||!t.byToken||i!=="types"&&i!=="values")return;const d=[];for(const[r,o]of t.byToken){const u=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(r),c=u?u[1]:"PII",y=r.replace(/^\[\[|\]\]$/g,"");d.push(i==="values"?{token:y,type:c,value:o}:{token:y,type:c})}return d}function Ko(t,i,d){return Ee.matches(t)||"anthropic-version"in i?{kind:"anthropic",adapter:Ee,redactable:Ee.matches(t),base:d.upstreams?.anthropic?.baseUrl}:qe.matches(t)?{kind:"responses",adapter:qe,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Oe,redactable:Oe.matches(t),base:d.upstreams?.openai?.baseUrl}}function Pe(t,i){const d=String(t||"");if(tt.has(d))return{agent:d,agentModel:""};const r=d.indexOf("/");if(r>0){const o=d.slice(0,r);if(tt.has(o))return{agent:o,agentModel:d.slice(r+1)}}return{agent:i.bridge.agent,agentModel:""}}function lt(t,i){return Pe(t,i).agent}function Zo(t,i){if(i!=="openai"||!t)return!1;const d=Oe.extractLatestToolResult(t);if(!d)return!1;const r=Ge(d.tool_call_id);return!!(r&&Le(r.gwId))}function Yo(t,i){try{const d=new URL(t),r=d.hostname.replace(/^\[|\]$/g,""),o=r==="127.0.0.1"||r==="localhost"||r==="::1",u=d.port||(d.protocol==="https:"?"443":"80");return o&&String(u)===String(i.port)}catch{return!1}}async function v(t,i){const d=[];let r=0;for await(const o of t){if(r+=o.length,i&&r>i){const u=new Error("payload too large");throw u.code=413,u}d.push(o)}return Buffer.concat(d)}function s(t,i,d){t.writeHead(i,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function ct(t){const i=t.redaction?.detection?.url;return!i||t.redaction?.detection?.backend==="off"?null:i}function $e(t){const i=t?.redaction?.detection,d=t?.redaction?.tier==="full"?"full":"basic";if(i&&i.backend&&i.backend!=="off")return{source:"external",backend:i.backend,state:"external",model:i.model||null,ready:!0,tier:d,coverage:d==="full"?"names":"patterns"};const r=B.health(),o=r.ok&&d==="full";return{source:"bundled",state:r.state,model:r.model||t?.ner?.model||null,installed:B.modelOnDisk(t?.ner?.model||void 0),error:r.error||null,ready:o,tier:d,coverage:o?"names":"patterns"}}async function dt(t){if(B.state()!=="off"){const d=B.health();return{configured:d.configured,ok:d.ok,state:d.state,model:d.model,error:d.error||null,url:d.configured?`http://${t.host}:${t.port}/ner`:null}}const i=ct(t);if(!i)return{configured:!1,ok:!1,url:null,model:null};try{const d=await Me(i.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:i,model:null};const r=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:i,model:r.model||null}}catch{return{configured:!0,ok:!1,url:i,model:null}}}function Xo(t,i){const d={};for(const[r,o]of Object.entries(t)){const u=r.toLowerCase();u.startsWith("x-chatpanel-")||nt.has(u)||(d[r]=o)}d["accept-encoding"]="identity";try{d.host=new URL(i).host}catch{}return d}async function ut(t,i,d,r){const o=De(i.vault),u=r?r.clock():0;let c=u,y=!0;const g=()=>{r&&y&&(r.lap("upstream",u),c=r.clock(),y=!1)};await Vt(i,{onText:E=>{g(),be(i.id);const m=o.push(E);m&&t.write(d.sseDelta(m))},onToolRequest:({name:E,restoredArgs:m,toolId:M})=>{g(),be(i.id);const A=o.flush();A&&t.write(d.sseDelta(A)),t.write(d.sseToolCalls([{id:M,name:E,arguments:JSON.stringify(m)}])),t.write(d.sseToolFinish()),r&&r.lap("stream",c),t.end(),r?.commit()},onDone:()=>{const E=o.flush();E&&t.write(d.sseDelta(E)),t.write(d.sseTail()),r&&r.lap("stream",c),t.end(),ue(i.id),r?.commit()},onError:E=>{t.write(`data: ${JSON.stringify({error:{message:E.message,type:"bridge_error"}})}
2
2
 
3
- `),t.end(),ie(l.id),r?.commit()}})}async function Vo(t,l,{kind:d,adapter:r,agent:o,run:u=null},c,h,b,E,p,M=null,A=null){const{messages:D,system:W}=r.toTurn(c),{agentModel:R}=_e(c?.model,b),I=Fe(b,{...R?{model:R}:{},...u||{}}),N=ae(b.bridge.token),O=ye(d,c?.model||o),j={tier:b.redaction.tier==="full"?"full":"basic",dictionary:gt(b.redaction,E),entities:[]},H=await se(b),v=Nt({vault:h,redactOpts:j,bridgeUrl:H,token:N,harness:M});let U;try{U=await $t({bridgeUrl:H,agent:o,token:N,messages:D,system:W,specs:Dt(p),options:I,signal:void 0})}catch(e){return ie(v.id),A?.commit(),s(l,502,{error:{message:`bridge: ${e.message}`,type:"bridge_error"}})}return v.reader=U.body.getReader(),l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write(O.sseHead()),it(l,v,O,A)}async function Jo(t,l,d,r,o=null){pe(l.id),l.rounds=(l.rounds||0)+1;try{const c=o?o.clock():0;await Ct(l,d),o&&o.lap("redact",c)}catch(c){return ie(l.id),o?.commit(),s(t,502,{error:{message:`tool-result: ${c.message}`,type:"bridge_error"}})}const u=ye("openai",r||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(u.sseHead()),it(t,l,u,o)}async function Ho(t,l,{kind:d,adapter:r,redactable:o,pathname:u,agentOverride:c,harness:h,trace:b,run:E=null},p,M,A,D){if(!o)return b?.commit(),s(l,404,{error:`endpoint ${u} not supported by the bridge backend`});if(d==="openai"){const i=r.extractLatestToolResult(p);if(i){const f=Ie(i.tool_call_id),y=f&&je(f.gwId);if(y)return Jo(l,y,i.content,p?.model,b)}const m=r.extractTools(p);if(m.length&&p?.stream===!0)return Vo(t,l,{kind:d,adapter:r,agent:c||nt(p?.model,A),run:E},p,M,A,D,m,h,b)}const{messages:W,system:R}=r.toTurn(p),I=c||nt(p?.model,A),N=p?.stream===!0,O=ye(d,p?.model||I),j=ae(A.bridge.token),H=new AbortController;l.on("close",()=>{l.writableFinished||H.abort()});const{agentModel:v}=_e(p?.model,A),U={bridgeUrl:await se(A),agent:I,token:j,messages:W,system:R,signal:H.signal,options:Fe(A,{...v?{model:v}:{},...E||{}})};if(!N)try{let i="";const m=b?b.clock():0;await De(U,k=>{i+=k}),b&&b.lap("upstream",m);const f=b?b.clock():0,y=O.full(ft(i,M));return b&&b.lap("restore",f),l.writeHead(200,{"content-type":O.contentType}),l.end(y),b?.commit()}catch(i){return b?.commit(),s(l,502,{error:{message:`bridge backend failed: ${i.message}`,type:"bridge_error"}})}l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write(O.sseHead());const e=Pe(M),n=b?b.clock():0;let a=n;try{let i=!0;await De(U,f=>{b&&i&&(b.lap("upstream",n),a=b.clock(),i=!1);const y=e.push(f);y&&l.write(O.sseDelta(y))},O.sseActivity?f=>{try{l.write(O.sseActivity(ht(f,M)))}catch{}}:null);const m=e.flush();m&&l.write(O.sseDelta(m)),l.write(O.sseTail())}catch(i){l.write(`data: ${JSON.stringify({error:{message:i.message,type:"bridge_error"}})}
3
+ `),t.end(),ue(i.id),r?.commit()}})}async function Qo(t,i,{kind:d,adapter:r,agent:o,run:u=null},c,y,g,E,m,M=null,A=null){const{messages:D,system:Z}=r.toTurn(c),{agentModel:R}=Pe(c?.model,g),j=Ye(g,{...R?{model:R}:{},...u||{}}),P=ie(g.bridge.token),O=we(d,c?.model||o),I={tier:g.redaction.tier==="full"?"full":"basic",dictionary:St(g.redaction,E),entities:[]},z=await de(g),T=zt({vault:y,redactOpts:I,bridgeUrl:z,token:P,harness:M});let U;try{U=await Gt({bridgeUrl:z,agent:o,token:P,messages:D,system:Z,specs:Ht(m),options:j,signal:void 0})}catch(X){return ue(T.id),A?.commit(),s(i,502,{error:{message:`bridge: ${X.message}`,type:"bridge_error"}})}return T.reader=U.body.getReader(),i.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),i.write(O.sseHead()),ut(i,T,O,A)}async function qo(t,i,d,r,o=null){be(i.id),i.rounds=(i.rounds||0)+1;try{const c=o?o.clock():0;await Jt(i,d),o&&o.lap("redact",c)}catch(c){return ue(i.id),o?.commit(),s(t,502,{error:{message:`tool-result: ${c.message}`,type:"bridge_error"}})}const u=we("openai",r||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(u.sseHead()),ut(t,i,u,o)}async function er(t,i,{kind:d,adapter:r,redactable:o,pathname:u,agentOverride:c,harness:y,trace:g,run:E=null},m,M,A,D){if(!o)return g?.commit(),s(i,404,{error:`endpoint ${u} not supported by the bridge backend`});if(d==="openai"){const e=r.extractLatestToolResult(m);if(e){const a=Ge(e.tool_call_id),l=a&&Le(a.gwId);if(l)return qo(i,l,e.content,m?.model,g)}const n=r.extractTools(m);if(n.length&&m?.stream===!0)return Qo(t,i,{kind:d,adapter:r,agent:c||lt(m?.model,A),run:E},m,M,A,D,n,y,g)}const{messages:Z,system:R}=r.toTurn(m),j=c||lt(m?.model,A),P=m?.stream===!0,O=we(d,m?.model||j),I=ie(A.bridge.token),z=new AbortController;i.on("close",()=>{i.writableFinished||z.abort()});const{agentModel:T}=Pe(m?.model,A),U={bridgeUrl:await de(A),agent:j,token:I,messages:Z,system:R,signal:z.signal,options:Ye(A,{...T?{model:T}:{},...E||{}})};if(!P)try{let e="";const n=g?g.clock():0;await Re(U,p=>{e+=p}),g&&g.lap("upstream",n);const a=g?g.clock():0,l=O.full(kt(e,M));return g&&g.lap("restore",a),i.writeHead(200,{"content-type":O.contentType}),i.end(l),g?.commit()}catch(e){return g?.commit(),s(i,502,{error:{message:`bridge backend failed: ${e.message}`,type:"bridge_error"}})}i.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),i.write(O.sseHead());const X=De(M),ne=g?g.clock():0;let se=ne;try{let e=!0;await Re(U,a=>{g&&e&&(g.lap("upstream",ne),se=g.clock(),e=!1);const l=X.push(a);l&&i.write(O.sseDelta(l))},O.sseActivity?a=>{try{i.write(O.sseActivity(wt(a,M)))}catch{}}:null);const n=X.flush();n&&i.write(O.sseDelta(n)),i.write(O.sseTail())}catch(e){i.write(`data: ${JSON.stringify({error:{message:e.message,type:"bridge_error"}})}
4
4
 
5
- `)}b&&b.lap("stream",a),l.end(),b?.commit()}function Uo(t,l,d=""){const r=String(t||"").replace(/\/+$/,""),o=String(l||"").split("/")[1];return o&&r.endsWith(`/${o}`)?r.slice(0,-(o.length+1))+l+d:r+l+d}const Fo=9e4;function Wo(t,l,d){if(l===d)return t;const r=l/d,o=new Float32Array(Math.floor(t.length/r));for(let u=0;u<o.length;u++){const c=u*r,h=Math.floor(c),b=Math.min(t.length-1,h+1),E=c-h;o[u]=t[h]*(1-E)+t[b]*E}return o}const Ko=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];async function Zo(t,l,{adapter:d,kind:r,pathname:o,search:u,base:c,destKey:h,destProtocol:b,harness:E,trace:p},M,A){let D;const W=p?p.clock():0;try{const O=zo(t.headers,c);h&&(b==="anthropic"?(O["x-api-key"]=h,delete O.authorization):O.authorization=`Bearer ${h}`);const j=vt(Uo(c,o,u)).toString();D=await fetch(j,{method:t.method,headers:O,body:["GET","HEAD"].includes(t.method)?void 0:M})}catch(O){return p?.commit(),s(l,502,{error:`upstream fetch failed: ${O.message}`})}const R=D.headers.get("content-type")||"",I={};if(D.headers.forEach((O,j)=>{et.has(j.toLowerCase())||(I[j]=O)}),R.includes("text/event-stream")&&D.body){p&&p.lap("upstream",W);const O=p?p.clock():0;l.writeHead(D.status,I);const j=r==="openai"?yt(D.body,l,A,E):pt(D.body,l,A);return Promise.resolve(j).finally(()=>{p&&p.lap("stream",O),p?.commit()})}const N=Buffer.from(await D.arrayBuffer());if(p&&p.lap("upstream",W),A&&R.includes("application/json"))try{const O=p?p.clock():0,j=d.restoreResponse(JSON.parse(N.toString("utf8")),A,E);return p&&p.lap("restore",O),l.writeHead(D.status,{...I,"content-type":"application/json"}),l.end(Buffer.from(JSON.stringify(j),"utf8")),p?.commit()}catch{}l.writeHead(D.status,I),l.end(N),p?.commit()}function Yo(t=xe()){const l=[],d=r=>{l.push(r),l.length>50&&l.shift()};return dt(async(r,o)=>{const u=new URL(r.url,"http://127.0.0.1"),c=u.pathname;if(!tt(r.headers.host))return s(o,403,{error:"loopback only"});if(!Co(r.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(r.headers.origin&&Do(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(c==="/admin/token"&&r.method==="POST")return K(r)?s(o,200,{token:$e()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(c==="/audit"&&r.method==="GET")return K(r)?s(o,200,_t(t,{version:Z,startedAt:ot,managed:re()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((c==="/config"||c==="/logs"||c==="/update")&&!K(r))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(c==="/update"&&r.method==="GET"){const e=await Kt(Z,{force:u.searchParams.get("force")==="1"}).catch(n=>({current:Z,updateAvailable:!1,error:String(n?.message||n)}));return s(o,200,{ok:!0,update:e,job:Xt()})}if(c==="/update"&&r.method==="POST"){const e=Yt(Z);return s(o,e.already?409:202,{ok:!0,job:e})}if((c==="/v1/history/key"||c==="/v1/history/ingest-backup")&&r.method==="POST"&&!K(r))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/history/ingest"||c==="/v1/history/clear")&&r.method==="POST"&&!K(r))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/memory/remember"||c==="/v1/memory/forget"||c==="/v1/memory/sync"||c==="/v1/memory/clear")&&r.method==="POST"&&!K(r))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/prefs"||c.startsWith("/v1/prefs/")||c.startsWith("/v1/teams")||c.startsWith("/v1/agents")||c.startsWith("/v1/projects"))&&!K(r))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(c.startsWith("/v1/observability")&&!K(r))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&c==="/health"){const e=x.health(),n=S.health();return s(o,200,{ok:!0,version:Z,backend:t.backend,tier:t.redaction.tier,...re()?{managed:re()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...ue?{bridge:ue.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||be,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Ve,voice:t.tts?.voice||Y,runtime:n.runtime,dtype:n.dtype}})}if(c==="/status"&&r.method==="GET"){mt(t);const e=await Q(t.pro?.entitlementToken),n=await at(t);return s(o,200,{ok:!0,version:Z,backend:t.backend,tier:t.redaction.tier,...re()?{managed:re()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:n.configured,ready:n.ok,model:n.model,url:n.url},detector:Oe(t),pro:{unlocked:e},usage:So(t),uptimeSeconds:Math.floor((Date.now()-ot)/1e3),update:Zt(Z)})}if(c==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},n=$.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:n})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/v1/prefs"&&r.method==="GET"){const e=String(u.searchParams.get("section")||"");return u.searchParams.get("stamps")?s(o,200,{ok:!0,revision:F.revision,stamps:F.stamps()}):s(o,200,{ok:!0,revision:F.revision,sections:F.get(e)})}if(c==="/v1/prefs"&&(r.method==="POST"||r.method==="PUT"))try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},n=F.put(e.sections||{},{by:e.by||""});return n.applied.length&&Ye(n.applied,e.by||""),s(o,200,{ok:!0,...n})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(c==="/v1/prefs"&&r.method==="DELETE"){const e=String(u.searchParams.get("section")||""),n=e?F.remove(e):!1;return n&&Ye([e],""),s(o,200,{ok:!0,removed:n})}if(c==="/v1/prefs/events"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=i=>o.write(`data: ${JSON.stringify(i)}
5
+ `)}g&&g.lap("stream",se),i.end(),g?.commit()}function tr(t,i,d=""){const r=String(t||"").replace(/\/+$/,""),o=String(i||"").split("/")[1];return o&&r.endsWith(`/${o}`)?r.slice(0,-(o.length+1))+i+d:r+i+d}const or=9e4;function rr(t,i,d){if(i===d)return t;const r=i/d,o=new Float32Array(Math.floor(t.length/r));for(let u=0;u<o.length;u++){const c=u*r,y=Math.floor(c),g=Math.min(t.length-1,y+1),E=c-y;o[u]=t[y]*(1-E)+t[g]*E}return o}const nr=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];async function sr(t,i,{adapter:d,kind:r,pathname:o,search:u,base:c,destKey:y,destProtocol:g,harness:E,trace:m},M,A){let D;const Z=m?m.clock():0;try{const O=Xo(t.headers,c);y&&(g==="anthropic"?(O["x-api-key"]=y,delete O.authorization):O.authorization=`Bearer ${y}`);const I=Et(tr(c,o,u)).toString();D=await fetch(I,{method:t.method,headers:O,body:["GET","HEAD"].includes(t.method)?void 0:M})}catch(O){return m?.commit(),s(i,502,{error:`upstream fetch failed: ${O.message}`})}const R=D.headers.get("content-type")||"",j={};if(D.headers.forEach((O,I)=>{nt.has(I.toLowerCase())||(j[I]=O)}),R.includes("text/event-stream")&&D.body){m&&m.lap("upstream",Z);const O=m?m.clock():0;i.writeHead(D.status,j);const I=r==="openai"?bt(D.body,i,A,E):gt(D.body,i,A);return Promise.resolve(I).finally(()=>{m&&m.lap("stream",O),m?.commit()})}const P=Buffer.from(await D.arrayBuffer());if(m&&m.lap("upstream",Z),A&&R.includes("application/json"))try{const O=m?m.clock():0,I=d.restoreResponse(JSON.parse(P.toString("utf8")),A,E);return m&&m.lap("restore",O),i.writeHead(D.status,{...j,"content-type":"application/json"}),i.end(Buffer.from(JSON.stringify(I),"utf8")),m?.commit()}catch{}i.writeHead(D.status,j),i.end(P),m?.commit()}function ar(t=Be()){$t(t.allowedExtensionIds||[]);const i=[],d=r=>{i.push(r),i.length>50&&i.shift()};return yt(async(r,o)=>{const u=new URL(r.url,"http://127.0.0.1"),c=u.pathname;if(!st(r.headers.host))return s(o,403,{error:"loopback only"});if(!Jo(r.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(r.headers.origin&&Ho(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(c==="/admin/token"&&r.method==="POST")return F(r)?s(o,200,{token:ge()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(c==="/pair/code"&&r.method==="POST"){if(!F(r))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Nt();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(c==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=Bt(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${ce(r)} caller`),s(o,403,{error:n.reason});console.log(`[gateway] paired a ${ce(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const a=ie(t.bridge?.token);return s(o,200,{ok:!0,token:Pt()||ge(),...a?{bridgeToken:a}:{}})}if(c==="/whoami"&&r.method==="POST"){const e=ce(r);return s(o,200,{ok:!0,trust:e,paired:At(e),version:W})}if(c==="/audit"&&r.method==="GET")return F(r)?s(o,200,Dt(t,{version:W,startedAt:at,managed:ae()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((c==="/config"||c==="/logs"||c==="/update")&&!F(r))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(c==="/update"&&r.method==="GET"){const e=await no(W,{force:u.searchParams.get("force")==="1"}).catch(n=>({current:W,updateAvailable:!1,error:String(n?.message||n)}));return s(o,200,{ok:!0,update:e,job:io()})}if(c==="/update"&&r.method==="POST"){const e=ao(W);return s(o,e.already?409:202,{ok:!0,job:e})}if((c==="/v1/history/key"||c==="/v1/history/ingest-backup")&&r.method==="POST"&&!F(r))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/history/ingest"||c==="/v1/history/clear")&&r.method==="POST"&&!F(r))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/memory/remember"||c==="/v1/memory/forget"||c==="/v1/memory/sync"||c==="/v1/memory/clear")&&r.method==="POST"&&!F(r))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/prefs"||c.startsWith("/v1/prefs/")||c.startsWith("/v1/teams")||c.startsWith("/v1/agents")||c.startsWith("/v1/projects"))&&!F(r))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(c.startsWith("/v1/observability")&&!F(r))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&c==="/health"){const e=x.health(),n=k.health();return s(o,200,{ok:!0,version:W,backend:t.backend,tier:t.redaction.tier,pairing:!0,...ae()?{managed:ae()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...he?{bridge:he.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Te,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Fe,voice:t.tts?.voice||Y,runtime:n.runtime,dtype:n.dtype}})}if(c==="/status"&&r.method==="GET"){ft(t);const e=await q(t.pro?.entitlementToken),n=await dt(t);return s(o,200,{ok:!0,version:W,backend:t.backend,tier:t.redaction.tier,...ae()?{managed:ae()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:n.configured,ready:n.ok,model:n.model,url:n.url},detector:$e(t),pro:{unlocked:e},usage:No(t),uptimeSeconds:Math.floor((Date.now()-at)/1e3),update:so(W)})}if(c==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=N.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:n})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/v1/prefs"&&r.method==="GET"){const e=String(u.searchParams.get("section")||"");return u.searchParams.get("stamps")?s(o,200,{ok:!0,revision:K.revision,stamps:K.stamps()}):s(o,200,{ok:!0,revision:K.revision,sections:K.get(e)})}if(c==="/v1/prefs"&&(r.method==="POST"||r.method==="PUT"))try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=K.put(e.sections||{},{by:e.by||""});return n.applied.length&&et(n.applied,e.by||""),s(o,200,{ok:!0,...n})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(c==="/v1/prefs"&&r.method==="DELETE"){const e=String(u.searchParams.get("section")||""),n=e?K.remove(e):!1;return n&&et([e],""),s(o,200,{ok:!0,removed:n})}if(c==="/v1/prefs/events"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
6
6
 
7
- `);e({type:"hello",revision:F.revision,stamps:F.stamps()});const n=i=>e({type:"changed",...i});ve.add(n);const a=setInterval(()=>{try{o.write(`: keep-alive
7
+ `);e({type:"hello",revision:K.revision,stamps:K.stamps()});const n=l=>e({type:"changed",...l});xe.add(n);const a=setInterval(()=>{try{o.write(`: keep-alive
8
8
 
9
- `)}catch{}},25e3);o.on("close",()=>{ve.delete(n),clearInterval(a)});return}if(c==="/v1/projects"&&r.method==="GET")return s(o,200,{ok:!0,projects:G.list({limit:u.searchParams.get("limit")||50,status:u.searchParams.get("status")||""})});if(c==="/v1/projects/jobs"&&r.method==="GET")return s(o,200,{ok:!0,jobs:G.openJobs()});if(c==="/v1/projects"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:G.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return s(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(c);if(e){const n=e[1],a=e[2]||"",i=e[3]||"",m=e[4]||"",f=()=>s(o,404,{error:{message:`no project ${n}`,type:"not_found"}});if(m){const y=G.get(n);if(!y)return f();const k=y.jobs.find(g=>g.id===i);if(!k)return s(o,404,{error:{message:`no job ${i}`,type:"not_found"}});const w={cfg:t,prefsStore:F,scorecards:te,engines:oe};if(m==="/applications"&&r.method==="GET"){const g=await Ut(k,{...w,reach:u.searchParams.get("reach")||"any",chatModel:u.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:k,...g})}if(m==="/recruit"&&r.method==="POST"){if(!["open","evaluating"].includes(k.status))return s(o,400,{error:{message:`job ${i} is ${k.status}; only an open job is recruited`,type:"project_error"}});try{const g=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},_=String(g.by||"evaluator").slice(0,80),z=await Ft(k,{...w,record:y,reach:g.reach||"any",chatModel:g.chatModel||null,evaluation:g.evaluation||null,text:g.text??null,by:_});let V=null;for(const X of z.events)X.type==="job.updated"?V=G.updateJob(n,i,X.job,{by:X.by||_}):V=G.append(n,[X]);return s(o,200,{ok:!0,project:V,decision:z.decision,applications:z.applications,evaluation:z.evaluation})}catch(g){return s(o,400,{error:{message:`recruit: ${g.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&r.method==="GET"){const y=G.get(n,{events:u.searchParams.get("events")==="1"});return y?s(o,200,{ok:!0,project:y}):f()}if(!a&&r.method==="DELETE")return s(o,200,{ok:!0,removed:G.remove(n)});if(r.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const y=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},k=String(y.by||"person").slice(0,80),w=a==="/events"?G.append(n,y.events||[]):i?G.updateJob(n,i,y.patch||y,{by:k}):G.postJob(n,y.job||y,{by:k});return s(o,200,{ok:!0,project:w})}catch(y){return s(o,y.message.startsWith("no ")?404:400,{error:{message:`project: ${y.message}`,type:"project_error"}})}if(a==="/events"&&r.method==="GET"){if(!G.get(n))return f();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const y=_=>o.write(`data: ${JSON.stringify(_)}
9
+ `)}catch{}},25e3);o.on("close",()=>{xe.delete(n),clearInterval(a)});return}if(c==="/v1/projects"&&r.method==="GET")return s(o,200,{ok:!0,projects:G.list({limit:u.searchParams.get("limit")||50,status:u.searchParams.get("status")||""})});if(c==="/v1/projects/jobs"&&r.method==="GET")return s(o,200,{ok:!0,jobs:G.openJobs()});if(c==="/v1/projects"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:G.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return s(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(c);if(e){const n=e[1],a=e[2]||"",l=e[3]||"",p=e[4]||"",S=()=>s(o,404,{error:{message:`no project ${n}`,type:"not_found"}});if(p){const h=G.get(n);if(!h)return S();const w=h.jobs.find(f=>f.id===l);if(!w)return s(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const b={cfg:t,prefsStore:K,scorecards:oe,engines:re};if(p==="/applications"&&r.method==="GET"){const f=await to(w,{...b,reach:u.searchParams.get("reach")||"any",chatModel:u.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:w,...f})}if(p==="/recruit"&&r.method==="POST"){if(!["open","evaluating"].includes(w.status))return s(o,400,{error:{message:`job ${l} is ${w.status}; only an open job is recruited`,type:"project_error"}});try{const f=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},_=String(f.by||"evaluator").slice(0,80),V=await oo(w,{...b,record:h,reach:f.reach||"any",chatModel:f.chatModel||null,evaluation:f.evaluation||null,text:f.text??null,by:_});let J=null;for(const Q of V.events)Q.type==="job.updated"?J=G.updateJob(n,l,Q.job,{by:Q.by||_}):J=G.append(n,[Q]);return s(o,200,{ok:!0,project:J,decision:V.decision,applications:V.applications,evaluation:V.evaluation})}catch(f){return s(o,400,{error:{message:`recruit: ${f.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&r.method==="GET"){const h=G.get(n,{events:u.searchParams.get("events")==="1"});return h?s(o,200,{ok:!0,project:h}):S()}if(!a&&r.method==="DELETE")return s(o,200,{ok:!0,removed:G.remove(n)});if(r.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const h=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},w=String(h.by||"person").slice(0,80),b=a==="/events"?G.append(n,h.events||[]):l?G.updateJob(n,l,h.patch||h,{by:w}):G.postJob(n,h.job||h,{by:w});return s(o,200,{ok:!0,project:b})}catch(h){return s(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(a==="/events"&&r.method==="GET"){if(!G.get(n))return S();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=_=>o.write(`data: ${JSON.stringify(_)}
10
10
 
11
- `);let k=u.searchParams.has("after")?Number(u.searchParams.get("after")):-1;y({seq:-1,type:"hello",at:Date.now(),payload:{project:G.get(n),after:k}});const w=G.watch(n,_=>{_.seq>k&&(k=_.seq,y(_))});for(const _ of G.eventsSince(n,k))k=_.seq,y(_);const g=setInterval(()=>{try{o.write(`: keep
11
+ `);let w=u.searchParams.has("after")?Number(u.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:G.get(n),after:w}});const b=G.watch(n,_=>{_.seq>w&&(w=_.seq,h(_))});for(const _ of G.eventsSince(n,w))w=_.seq,h(_);const f=setInterval(()=>{try{o.write(`: keep
12
12
 
13
- `)}catch{}},25e3);r.on("close",()=>{clearInterval(g),w()});return}}}if(c==="/v1/agents/scorecards"&&r.method==="GET")return s(o,200,{ok:!0,agents:te.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(c);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return s(o,200,{ok:!0,...await te.get(n)});if(r.method==="POST")try{const a=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},i=await te.append({agentId:n,kind:"rating",runId:a.runId,taskId:a.taskId,jobId:a.jobId,rating:{by:String(a.by||"person").slice(0,40),score:a.score,note:a.note,about:a.about},refs:a.refs});return oe.fromRating(te.chains.get(n)||[],{...i,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:i})}catch(a){return s(o,400,{error:{message:`scorecard: ${a.message}`,type:"scorecard_error"}})}}}if(c==="/v1/engines"&&r.method==="GET"){const e=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:oe.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(c);if(e){const n=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&r.method==="GET"){const a=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await oe.get(n,{entries:u.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&r.method==="POST")try{const a=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},i=a.engine||Io(n);if(!i)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const m=await oe.append({...a,engine:i,kind:a.kind||"call"});return m.key!==n?s(o,400,{error:{message:`model-ledger: entry is for ${m.key}, not ${n}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:m})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(c==="/v1/teams/runs"&&r.method==="GET")return s(o,200,{ok:!0,runs:C.list({limit:u.searchParams.get("limit")||50,team:u.searchParams.get("team")||""})});if(c==="/v1/teams/runs"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return s(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(c);if(e){const n=e[1],a=e[2]||"";if(!a&&r.method==="GET"){const i=C.get(n,{events:u.searchParams.get("events")==="1"});return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(!a&&r.method==="DELETE")return C.stop(n),s(o,200,{ok:!0,removed:C.remove(n)});if(a==="/stop"&&r.method==="POST"){const i=C.stop(n);return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(a==="/checkpoint"&&r.method==="GET")try{return s(o,200,{ok:!0,checkpoint:C.checkpoint(n)})}catch(i){return s(o,404,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&r.method==="POST")try{const i=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},m=a==="/handoff"?C.handoff(n,{taskId:i.taskId,model:i.model,by:i.by,reason:i.reason}):C.claim(n,{client:i.client});return s(o,200,{ok:!0,run:m})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&r.method==="DELETE")try{return s(o,200,{ok:!0,run:C.removeThread(n,{threadId:a.slice(9),by:"person"})})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&r.method==="POST")try{const i=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},m=String(i.by||"person").slice(0,40),f=a==="/answer"?C.answer(n,{threadId:i.threadId,text:i.text,by:m}):a==="/decide"?C.decide(n,{postId:i.postId,status:i.status,by:m}):C.post(n,{threadId:i.threadId,text:i.text,by:m,kind:i.kind,replyTo:i.replyTo});return s(o,200,{ok:!0,run:f})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="POST")try{const i=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.append(n,i.events||[])})}catch(i){return s(o,i.message.startsWith("no run")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="GET"){if(!C.get(n))return s(o,404,{error:{message:`no run ${n}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const i=w=>o.write(`data: ${JSON.stringify(w)}
13
+ `)}catch{}},25e3);r.on("close",()=>{clearInterval(f),b()});return}}}if(c==="/v1/agents/scorecards"&&r.method==="GET")return s(o,200,{ok:!0,agents:oe.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(c);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return s(o,200,{ok:!0,...await oe.get(n)});if(r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=await oe.append({agentId:n,kind:"rating",runId:a.runId,taskId:a.taskId,jobId:a.jobId,rating:{by:String(a.by||"person").slice(0,40),score:a.score,note:a.note,about:a.about},refs:a.refs});return re.fromRating(oe.chains.get(n)||[],{...l,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:l})}catch(a){return s(o,400,{error:{message:`scorecard: ${a.message}`,type:"scorecard_error"}})}}}if(c==="/v1/engines"&&r.method==="GET"){const e=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:re.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(c);if(e){const n=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&r.method==="GET"){const a=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await re.get(n,{entries:u.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},l=a.engine||Fo(n);if(!l)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const p=await re.append({...a,engine:l,kind:a.kind||"call"});return p.key!==n?s(o,400,{error:{message:`model-ledger: entry is for ${p.key}, not ${n}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:p})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(c==="/v1/teams/runs"&&r.method==="GET")return s(o,200,{ok:!0,runs:C.list({limit:u.searchParams.get("limit")||50,team:u.searchParams.get("team")||""})});if(c==="/v1/teams/runs"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return s(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(c);if(e){const n=e[1],a=e[2]||"";if(!a&&r.method==="GET"){const l=C.get(n,{events:u.searchParams.get("events")==="1"});return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(!a&&r.method==="DELETE")return C.stop(n),s(o,200,{ok:!0,removed:C.remove(n)});if(a==="/stop"&&r.method==="POST"){const l=C.stop(n);return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(a==="/checkpoint"&&r.method==="GET")try{return s(o,200,{ok:!0,checkpoint:C.checkpoint(n)})}catch(l){return s(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},p=a==="/handoff"?C.handoff(n,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):C.claim(n,{client:l.client});return s(o,200,{ok:!0,run:p})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&r.method==="DELETE")try{return s(o,200,{ok:!0,run:C.removeThread(n,{threadId:a.slice(9),by:"person"})})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},p=String(l.by||"person").slice(0,40),S=a==="/answer"?C.answer(n,{threadId:l.threadId,text:l.text,by:p}):a==="/decide"?C.decide(n,{postId:l.postId,status:l.status,by:p}):C.post(n,{threadId:l.threadId,text:l.text,by:p,kind:l.kind,replyTo:l.replyTo});return s(o,200,{ok:!0,run:S})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="POST")try{const l=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.append(n,l.events||[])})}catch(l){return s(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="GET"){if(!C.get(n))return s(o,404,{error:{message:`no run ${n}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=b=>o.write(`data: ${JSON.stringify(b)}
14
14
 
15
- `),m=u.searchParams.has("after")?Number(u.searchParams.get("after")):NaN;let f=Number.isFinite(m)?m:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:C.get(n),after:f}});const y=C.watch(n,w=>{w.seq==null?i(w):w.seq>f&&(f=w.seq,i(w))});for(const w of C.eventsSince(n,f))f=w.seq,i(w);const k=setInterval(()=>{try{o.write(`: keep-alive
15
+ `),p=u.searchParams.has("after")?Number(u.searchParams.get("after")):NaN;let S=Number.isFinite(p)?p:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:C.get(n),after:S}});const h=C.watch(n,b=>{b.seq==null?l(b):b.seq>S&&(S=b.seq,l(b))});for(const b of C.eventsSince(n,S))S=b.seq,l(b);const w=setInterval(()=>{try{o.write(`: keep-alive
16
16
 
17
- `)}catch{}},25e3);o.on("close",()=>{y(),clearInterval(k)});return}}}if(c==="/v1/memory/list"&&r.method==="GET")return s(o,200,{ok:!0,size:J.size,memories:J.list()});if(c==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},n=J.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return s(o,200,{ok:!0,size:J.size,...n})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},n=J.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return s(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:J.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=J.forget(String(e.query||""));return s(o,200,{ok:!0,removed:n,size:J.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},n=J.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...n,memories:J.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/clear"&&r.method==="POST")return s(o,200,{ok:!0,dropped:J.clear(),size:J.size});if(c==="/v1/history/clear"&&r.method==="POST"){const e=$.clear();return s(o,200,{ok:!0,dropped:e,size:$.size})}if(c==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},n=$.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return s(o,200,{ok:!0,size:$.size,newest:$.newest,results:n})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),a=xo(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),i={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},m=Math.min(30,Math.max(5,Number(e.limit)||10)*2),f=await Ao(a,k=>$.search(k,{limit:m,...i}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),y=i.type?f:[...f.filter(k=>k.type==="brief"),...f.filter(k=>k.type!=="brief")];return s(o,200,{ok:!0,size:$.size,newest:$.newest,queries:a,results:y})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/related"&&r.method==="GET"){const e=String(u.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(u.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:$.related(e,{limit:n})})}if(c==="/v1/history/status"&&r.method==="GET")return s(o,200,{ok:!0,size:$.size,newest:$.newest,bytes:$.bytes});if(c==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:$.size,bytes:$.bytes,newest:$.newest}},access:Te.snapshot(e)})}if(c==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{},n=Te.push(Ke({ts:Date.now(),...e}));return s(o,200,{ok:!0,event:n})}catch(e){return s(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(c==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||50)),n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=u.searchParams.get("type")||null;return s(o,200,{ok:!0,...$.list({limit:e,offset:n,type:a})})}if(c==="/v1/history/get"&&r.method==="GET"){const e=u.searchParams.get("maxChars")!=null?Math.max(1,Number(u.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=$.get(String(u.searchParams.get("id")||""),{maxChars:e,offset:n});return a?s(o,200,{ok:!0,record:a}):s(o,404,{error:{message:"no such record",type:"not_found"}})}if(c==="/v1/history/key"&&r.method==="GET")return s(o,200,{ok:!0,hasKey:Re()});if(c==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Mt(String(e.passphrase)):Rt();const n=e.passphrase?await ge($,String(e.passphrase)):{ok:!0,ingested:0};return s(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(c==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await ge($,Me());return s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/ner"){if(r.method==="GET"){const e=await at(t);return s(o,e.ok?200:503,e)}if(r.method==="POST"){if(await he(t),B.state()!=="off"){if(!B.isReady()){const n=B.health();return s(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await T(r,t.maxBodyBytes);let a="";try{a=JSON.parse(n.toString("utf8"))?.text||""}catch{}const i=await B.detect(a);return s(o,200,{entities:i})}catch(n){return s(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=st(t);if(!e){const n=B.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:B.state(),model:t.ner?.model||null})}try{const n=await T(r,t.maxBodyBytes),a=await Ce(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),i=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(i)}catch(n){return s(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(c==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Oe(t)});try{let n=e;const a=await Q(t.pro?.entitlementToken);await he(t);const i=await me([Ae(()=>n,m=>{n=m})],t.redaction,{isPro:a});return s(o,200,{text:n,count:i.count||0,sanitized:i.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:rt(i.vault,"types")||[],detector:Oe(t)})}catch(n){return s(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(c==="/ner/models"){if(r.method==="GET"){const e=B.health().model||t.ner?.model||null,n=qt.map(a=>({...a,installed:B.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",custom:!0,installed:B.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:B.state(),progress:B.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(eo(n)||to(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});To(t,n);try{ee(t,q())}catch{}return B.setModel(n,{onLog:a=>console.log(a)}).then(a=>{a&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),s(o,202,{accepted:!0,active:n,state:B.state(),progress:B.progress()})}}if(c==="/stt/models"){if(r.method==="GET"){const e=x.health().model||t.stt?.model||be,n=oo.map(a=>({...a,installed:x.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:x.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:x.state(),progress:x.progress(),available:n,dtype:t.stt?.dtype||"auto",loadedDtype:x.health().dtype,runtime:x.health().runtime,dtypes:so})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(ro(n)||no(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&ao(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{ee(t,q())}catch{}return x.setModel(n,{onLog:i=>console.log(i),dtype:a||t.stt.dtype||"auto"}),s(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:x.state(),progress:x.progress()})}}if(c==="/diarize/model"){if(r.method==="GET"){const e=P.health();return s(o,200,{active:P.DIARIZE_MODEL,state:e.state,progress:P.progress(),available:[{id:P.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:P.modelOnDisk()}]})}if(r.method==="POST")return P.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:P.DIARIZE_MODEL,state:P.state(),progress:P.progress()})}if(c==="/tts/models"){if(r.method==="GET"){const e=S.health().model||t.tts?.model||He(we()),n=we(),a=Le.find(m=>m.id===e)||null,i=Le.map(m=>({...m,installed:S.modelOnDisk(m.id),unavailable:m.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!i.some(m=>m.id===e)&&i.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:S.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:S.state(),progress:S.progress(),available:i,voice:t.tts?.voice||(de(e)==="pocket-tts"?le:Y),arch:S.arch(),supportsVoices:S.arch()?S.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:S.arch()?S.supportsCustomVoices():!!a?.customVoices,sampleRate:S.sampleRate(),voices:S.isPocket()||!S.arch()&&de(e)==="pocket-tts"?(S.builtinVoices().length?S.builtinVoices():yo).map(m=>({id:m,label:m[0].toUpperCase()+m.slice(1),lang:"en",installed:S.builtinVoices().includes(m)})):S.arch()&&S.arch()!=="style-tts2"?[]:io.map(m=>({...m,installed:S.voiceOnDisk(m.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:S.health().dtype,runtime:S.health().runtime,dtypes:uo})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(lo(n)||co(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=e&&typeof e.voice=="string"?e.voice.trim():null;if(a){const m=L.parseCustomVoice(a);if(!(m?!!L.getVoice(m):ce(a)||Ge(a)&&ze(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&mo(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Ve,voice:Y,allowDownload:!0}),n&&(t.tts.model=n),a&&(t.tts.voice=a),n&&!a){const m=po(n),f=L.parseCustomVoice(t.tts.voice||""),y=!!(f&&L.getVoice(f));if(m&&!y)if(de(n)==="pocket-tts")t.tts.voice=le;else{const w=L.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!m&&y&&(t.tts.voice=Y);const k=de(n)==="pocket-tts";k&&!L.parseCustomVoice(t.tts.voice||"")&&!ce(t.tts.voice)&&(t.tts.voice=le),!k&&ce(t.tts.voice)&&(t.tts.voice=Y)}i&&(t.tts.dtype=i==="auto"?null:i);try{ee(t,q())}catch{}return n&&S.setModel(n,{onLog:m=>console.log(m),dtype:i||t.tts.dtype||"auto"}),s(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:S.state(),progress:S.progress()})}}if(c==="/tts/voices"){if(r.method==="GET")return s(o,200,{voices:L.listVoices(),usable:S.supportsCustomVoices(),embedder:P.DIARIZE_MODEL,embedderReady:P.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,i=e&&typeof e.id=="string"?e.id.trim():"";if(i){if(!L.getVoice(i))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...L.renameVoice(i,n),usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.message,type:"rename_failed"}})}}if(a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!a||a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!P.isReady()){const g=P.download({onLog:V=>console.log(V)}),_=Symbol("timeout"),z=await Promise.race([g.then(()=>null).catch(V=>V),new Promise(V=>setTimeout(()=>V(_),Fo))]);if(z===_||!P.isReady())return s(o,503,{error:{message:z===_?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${P.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:P.progress()})}const m=Float32Array.from(a),f=await P.embed(m);let y=null;try{const g=await S.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:_=>console.log(_)});g&&(y=await g.encodeVoice(Wo(m,16e3,24e3)))}catch(g){console.log(`[tts] pocket conditioning unavailable for this voice (${g.message})`)}const k=i?L.replaceVoice(i,{vec:f,pocket:y}):L.saveVoice({name:n,vec:f,pocket:y}),w=i&&n&&n!==k.name?L.renameVoice(i,n):k;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${w.name}" (${(k.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...k,...w,usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=u.searchParams.get("id")||"",n=L.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const a=L.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:Y;try{ee(t,q())}catch{}}return s(o,200,{deleted:n,voice:t.tts?.voice})}}if((c==="/tts"||c==="/v1/audio/speech")&&r.method==="POST"){if(t.tts?.enabled===!1)return s(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Je)return s(o,413,{error:{message:`text too long (max ${Je} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=ho(t),m=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,f=m||(i?i.voice:t.tts?.voice||Y);if(i&&!go(f))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const y=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(y!=="wav"&&y!=="pcm")return s(o,400,{error:{message:`unsupported response_format "${y}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(i){const{audio:ne,contentType:lt,redacted:ct}=await fo({dest:i,text:n,voice:f,speed:a,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await Q(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":lt,"Content-Length":String(ne.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(ct)}),o.end(ne)}if(!await S.ready({onLog:ne=>console.log(ne),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||He(we()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:S.health().error||"tts model not ready",type:"tts_unavailable"}});const w=bo({requested:m,configured:f,engine:S,voices:L,isPocketVoice:ce,isKnownVoice:Ge,isValidVoiceId:ze,defaultVoice:Y,defaultPocketVoice:le});if(!w.ok)return s(o,w.status,{error:{message:w.message,type:w.type}});const{voice:g,customId:_,speakerEmbedding:z}=w,V=await S.synth(n,{voice:g,speed:a,speakerEmbedding:z}),X=S.sampleRate(),Ee=y==="pcm"?Buffer.from(new Float32Array(V).buffer):S.toWav(V,X);return o.writeHead(200,{"Content-Type":y==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(Ee.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(X),..._||S.isPocket()||S.supportsVoices()?{"X-Tts-Voice":g}:{}}),o.end(Ee)}catch(k){return s(o,500,{error:{message:k.message,type:"tts_failed"}})}}if(c==="/stt/sessions"&&r.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}x.isReady()||x.init({model:t.stt?.model||be,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,onLog:a=>console.log(a)});const n=e?.diarize===!0&&t.stt?.diarize!==!1;n&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,onLog:a=>console.log(a)});try{const{id:a}=x.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:n,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs});return s(o,201,{id:a,state:x.state()})}catch(a){return s(o,a.code==="too_many_sessions"?429:500,{error:{message:a.message,type:a.code||"stt_error"}})}}{const e=c.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1];if(e[2]==="/audio"&&r.method==="POST")try{const a=await T(r,t.maxBodyBytes);return x.pushAudio(n,x.toFloat32(a)),s(o,200,{ok:!0,state:x.state()})}catch(a){return s(o,a.code==="no_session"?404:400,{error:{message:a.message,type:a.code||"stt_error"}})}if(e[2]==="/events"&&r.method==="GET"){const a=x.getSession(n);if(!a)return s(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const i=g=>o.write(`data: ${JSON.stringify(g)}
17
+ `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(w)});return}}}if(c==="/v1/memory/list"&&r.method==="GET")return s(o,200,{ok:!0,size:H.size,memories:H.list()});if(c==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=H.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return s(o,200,{ok:!0,size:H.size,...n})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=H.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return s(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:H.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=H.forget(String(e.query||""));return s(o,200,{ok:!0,removed:n,size:H.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=H.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...n,memories:H.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/clear"&&r.method==="POST")return s(o,200,{ok:!0,dropped:H.clear(),size:H.size});if(c==="/v1/history/clear"&&r.method==="POST"){const e=N.clear();return s(o,200,{ok:!0,dropped:e,size:N.size})}if(c==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=N.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return s(o,200,{ok:!0,size:N.size,newest:N.newest,results:n})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),a=Mo(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},p=Math.min(30,Math.max(5,Number(e.limit)||10)*2),S=await Ro(a,w=>N.search(w,{limit:p,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?S:[...S.filter(w=>w.type==="brief"),...S.filter(w=>w.type!=="brief")];return s(o,200,{ok:!0,size:N.size,newest:N.newest,queries:a,results:h})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/related"&&r.method==="GET"){const e=String(u.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(u.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:N.related(e,{limit:n})})}if(c==="/v1/history/status"&&r.method==="GET")return s(o,200,{ok:!0,size:N.size,newest:N.newest,bytes:N.bytes});if(c==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:N.size,bytes:N.bytes,newest:N.newest}},access:Ae.snapshot(e)})}if(c==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Ae.push(Qe({ts:Date.now(),...e}));return s(o,200,{ok:!0,event:n})}catch(e){return s(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(c==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||50)),n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=u.searchParams.get("type")||null;return s(o,200,{ok:!0,...N.list({limit:e,offset:n,type:a})})}if(c==="/v1/history/get"&&r.method==="GET"){const e=u.searchParams.get("maxChars")!=null?Math.max(1,Number(u.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=N.get(String(u.searchParams.get("id")||""),{maxChars:e,offset:n});return a?s(o,200,{ok:!0,record:a}):s(o,404,{error:{message:"no such record",type:"not_found"}})}if(c==="/v1/history/key"&&r.method==="GET")return s(o,200,{ok:!0,hasKey:Ve()});if(c==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Wt(String(e.passphrase)):Kt();const n=e.passphrase?await ve(N,String(e.passphrase)):{ok:!0,ingested:0};return s(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(c==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await ve(N,ze());return s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/ner"){if(r.method==="GET"){const e=await dt(t);return s(o,e.ok?200:503,e)}if(r.method==="POST"){if(await ke(t),B.state()!=="off"){if(!B.isReady()){const n=B.health();return s(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await v(r,t.maxBodyBytes);let a="";try{a=JSON.parse(n.toString("utf8"))?.text||""}catch{}const l=await B.detect(a);return s(o,200,{entities:l})}catch(n){return s(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=ct(t);if(!e){const n=B.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:B.state(),model:t.ner?.model||null})}try{const n=await v(r,t.maxBodyBytes),a=await Me(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),l=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(l)}catch(n){return s(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(c==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:$e(t)});try{let n=e;const a=await q(t.pro?.entitlementToken);await ke(t);const l=await fe([Ce(()=>n,p=>{n=p})],t.redaction,{isPro:a});return s(o,200,{text:n,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:it(l.vault,"types")||[],detector:$e(t)})}catch(n){return s(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(c==="/ner/models"){if(r.method==="GET"){const e=B.health().model||t.ner?.model||null,n=co.map(a=>({...a,installed:B.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",custom:!0,installed:B.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:B.state(),progress:B.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(uo(n)||mo(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Co(t,n);try{te(t,ee())}catch{}return B.setModel(n,{onLog:a=>console.log(a)}).then(a=>{a&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),s(o,202,{accepted:!0,active:n,state:B.state(),progress:B.progress()})}}if(c==="/stt/models"){if(r.method==="GET"){const e=x.health().model||t.stt?.model||Te,n=po.map(a=>({...a,installed:x.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:x.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:x.state(),progress:x.progress(),available:n,dtype:t.stt?.dtype||"auto",loadedDtype:x.health().dtype,runtime:x.health().runtime,dtypes:fo})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(yo(n)||ho(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&go(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{te(t,ee())}catch{}return x.setModel(n,{onLog:l=>console.log(l),dtype:a||t.stt.dtype||"auto"}),s(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:x.state(),progress:x.progress()})}}if(c==="/diarize/model"){if(r.method==="GET"){const e=$.health();return s(o,200,{active:$.DIARIZE_MODEL,state:e.state,progress:$.progress(),available:[{id:$.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:$.modelOnDisk()}]})}if(r.method==="POST")return $.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:$.DIARIZE_MODEL,state:$.state(),progress:$.progress()})}if(c==="/tts/models"){if(r.method==="GET"){const e=k.health().model||t.tts?.model||Ke(_e()),n=_e(),a=Je.find(p=>p.id===e)||null,l=Je.map(p=>({...p,installed:k.modelOnDisk(p.id),unavailable:p.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(p=>p.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:k.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:k.state(),progress:k.progress(),available:l,voice:t.tts?.voice||(ye(e)==="pocket-tts"?me:Y),arch:k.arch(),supportsVoices:k.arch()?k.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:k.arch()?k.supportsCustomVoices():!!a?.customVoices,sampleRate:k.sampleRate(),voices:k.isPocket()||!k.arch()&&ye(e)==="pocket-tts"?(k.builtinVoices().length?k.builtinVoices():_o).map(p=>({id:p,label:p[0].toUpperCase()+p.slice(1),lang:"en",installed:k.builtinVoices().includes(p)})):k.arch()&&k.arch()!=="style-tts2"?[]:bo.map(p=>({...p,installed:k.voiceOnDisk(p.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:k.health().dtype,runtime:k.health().runtime,dtypes:So})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(wo(n)||ko(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=e&&typeof e.voice=="string"?e.voice.trim():null;if(a){const p=L.parseCustomVoice(a);if(!(p?!!L.getVoice(p):pe(a)||He(a)&&Ue(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&vo(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Fe,voice:Y,allowDownload:!0}),n&&(t.tts.model=n),a&&(t.tts.voice=a),n&&!a){const p=To(n),S=L.parseCustomVoice(t.tts.voice||""),h=!!(S&&L.getVoice(S));if(p&&!h)if(ye(n)==="pocket-tts")t.tts.voice=me;else{const b=L.listVoices();t.tts.voice=b.length?`custom:${b[0].id}`:""}else!p&&h&&(t.tts.voice=Y);const w=ye(n)==="pocket-tts";w&&!L.parseCustomVoice(t.tts.voice||"")&&!pe(t.tts.voice)&&(t.tts.voice=me),!w&&pe(t.tts.voice)&&(t.tts.voice=Y)}l&&(t.tts.dtype=l==="auto"?null:l);try{te(t,ee())}catch{}return n&&k.setModel(n,{onLog:p=>console.log(p),dtype:l||t.tts.dtype||"auto"}),s(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:k.state(),progress:k.progress()})}}if(c==="/tts/voices"){if(r.method==="GET")return s(o,200,{voices:L.listVoices(),usable:k.supportsCustomVoices(),embedder:$.DIARIZE_MODEL,embedderReady:$.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!L.getVoice(l))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...L.renameVoice(l,n),usable:k.supportsCustomVoices()})}catch(p){return s(o,400,{error:{message:p.message,type:"rename_failed"}})}}if(a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!a||a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!$.isReady()){const f=$.download({onLog:J=>console.log(J)}),_=Symbol("timeout"),V=await Promise.race([f.then(()=>null).catch(J=>J),new Promise(J=>setTimeout(()=>J(_),or))]);if(V===_||!$.isReady())return s(o,503,{error:{message:V===_?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${$.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:$.progress()})}const p=Float32Array.from(a),S=await $.embed(p);let h=null;try{const f=await k.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:_=>console.log(_)});f&&(h=await f.encodeVoice(rr(p,16e3,24e3)))}catch(f){console.log(`[tts] pocket conditioning unavailable for this voice (${f.message})`)}const w=l?L.replaceVoice(l,{vec:S,pocket:h}):L.saveVoice({name:n,vec:S,pocket:h}),b=l&&n&&n!==w.name?L.renameVoice(l,n):w;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${b.name}" (${(w.kinds||[]).join(" + ")}, sample discarded)`),s(o,l?200:201,{...w,...b,usable:k.supportsCustomVoices()})}catch(p){return s(o,400,{error:{message:p.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=u.searchParams.get("id")||"",n=L.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const a=L.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:Y;try{te(t,ee())}catch{}}return s(o,200,{deleted:n,voice:t.tts?.voice})}}if((c==="/tts"||c==="/v1/audio/speech")&&r.method==="POST"){if(t.tts?.enabled===!1)return s(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>We)return s(o,413,{error:{message:`text too long (max ${We} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Oo(t),p=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,S=p||(l?l.voice:t.tts?.voice||Y);if(l&&!xo(S))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return s(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:le,contentType:mt,redacted:pt}=await Eo({dest:l,text:n,voice:S,speed:a,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await q(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":mt,"Content-Length":String(le.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(pt)}),o.end(le)}if(!await k.ready({onLog:le=>console.log(le),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Ke(_e()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:k.health().error||"tts model not ready",type:"tts_unavailable"}});const b=Ao({requested:p,configured:S,engine:k,voices:L,isPocketVoice:pe,isKnownVoice:He,isValidVoiceId:Ue,defaultVoice:Y,defaultPocketVoice:me});if(!b.ok)return s(o,b.status,{error:{message:b.message,type:b.type}});const{voice:f,customId:_,speakerEmbedding:V}=b,J=await k.synth(n,{voice:f,speed:a,speakerEmbedding:V}),Q=k.sampleRate(),Ne=h==="pcm"?Buffer.from(new Float32Array(J).buffer):k.toWav(J,Q);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(Ne.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Q),..._||k.isPocket()||k.supportsVoices()?{"X-Tts-Voice":f}:{}}),o.end(Ne)}catch(w){return s(o,500,{error:{message:w.message,type:"tts_failed"}})}}if(c==="/stt/sessions"&&r.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}x.isReady()||x.init({model:t.stt?.model||Te,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,onLog:a=>console.log(a)});const n=e?.diarize===!0&&t.stt?.diarize!==!1;n&&!$.isReady()&&$.init({allowDownload:t.stt?.allowDownload!==!1,onLog:a=>console.log(a)});try{const{id:a}=x.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:n,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs});return s(o,201,{id:a,state:x.state()})}catch(a){return s(o,a.code==="too_many_sessions"?429:500,{error:{message:a.message,type:a.code||"stt_error"}})}}{const e=c.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1];if(e[2]==="/audio"&&r.method==="POST")try{const a=await v(r,t.maxBodyBytes);return x.pushAudio(n,x.toFloat32(a)),s(o,200,{ok:!0,state:x.state()})}catch(a){return s(o,a.code==="no_session"?404:400,{error:{message:a.message,type:a.code||"stt_error"}})}if(e[2]==="/events"&&r.method==="GET"){const a=x.getSession(n);if(!a)return s(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=f=>o.write(`data: ${JSON.stringify(f)}
18
18
 
19
- `),m=a.redact?await Q(t.pro?.entitlementToken):!0,f=async g=>{if(g.type!=="final"||!a.redact)return g;try{let _=g.text;return await me([Ae(()=>_,z=>{_=z})],t.redaction,{isPro:m}),{...g,text:_}}catch{return g}};i({type:"state",state:x.state()});const y=setInterval(()=>{const g=x.state();if(g==="downloading"||g==="loading"){i({type:"progress",state:g,...x.progress()||{}});return}if(g==="error"){i({type:"error",code:"model_failed",message:x.health().error||"model failed to load",fatal:!0}),clearInterval(y);return}if(a.diarize){const _=P.state();if(_==="downloading"||_==="loading"){i({type:"diarize-progress",state:_,...P.progress()||{}});return}}i({type:"state",state:g}),clearInterval(y)},500);y.unref?.();let k=Promise.resolve();const w=x.subscribe(n,g=>{k=k.then(async()=>{i(await f(g)),g.type==="end"&&(clearInterval(y),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(y),w?.()});return}if(!e[2]&&r.method==="DELETE")return await x.endSession(n),s(o,200,{ok:!0})}}if(c==="/logs"&&r.method==="GET")return s(o,200,{entries:[...l].reverse()});if(c==="/config"&&r.method==="GET"){const e=await Q(t.pro?.entitlementToken);return s(o,200,Ue(t,{proUnlocked:e}))}if(c==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await T(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});vo(t,e),Ne(t);try{ee(t,q())}catch(f){return s(o,500,{error:`could not persist config: ${f.message}`})}const n=t.redaction?.detection,a=!n||!n.backend||n.backend==="off",i=B.state();t.ner?.autostart&&a&&i!=="ready"&&i!=="loading"&&i!=="downloading"&&B.setModel(t.ner.model,{onLog:f=>console.log(f)}).then(f=>{f&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await Q(t.pro?.entitlementToken);return s(o,200,Ue(t,{proUnlocked:m}))}if(r.method==="GET"&&c==="/skills"){const e=await se(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=ae(t.bridge?.token);try{const a=await fetch(`${e}/skills`,{headers:{Accept:"application/json",...n?{Authorization:`Bearer ${n}`}:{}},signal:AbortSignal.timeout(8e3)}),i=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(i?.skills)?i.skills:[]}):s(o,a.status,{error:{message:i?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+$/.test(c)){const e=decodeURIComponent(c.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const n=await se(t);if(!n)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=ae(t.bridge?.token);try{const i=await fetch(`${n}/skills/${encodeURIComponent(e)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),m=await i.json().catch(()=>({}));return i.ok?s(o,200,{skill:m?.skill||null}):s(o,i.status,{error:{message:m?.error||`bridge ${i.status}`,type:"bridge_error"}})}catch(i){return s(o,502,{error:{message:`bridge unreachable: ${i.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/\/models$/.test(c))return s(o,200,await _o(t));if(Ko.some(e=>c===e||c.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${Z}) has no ${c} — update it to use this feature`,type:"unknown_endpoint"}});const h=Ro(c,r.headers,t);let b;try{b=await T(r,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let E=null,p=null,M=b,A=0,D=0,W=0,R=!1,I=!0;const N=t.logRequests&&h.redactable&&r.method==="POST"?Mo(d):null;if(h.redactable&&r.method==="POST"&&b.length){try{p=JSON.parse(b.toString("utf8"))}catch{p=null}if(p&&Lo(p,h.kind))M=b;else if(p){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(p.tools)&&p.tools.length){const w=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Po,g=e.narrowAll?null:z=>!$o.test(Qe(z)),_=p.tools.length;p.tools=bt(p.tools,Bo(p,h.kind),{cap:w,keep:g,name:Qe,description:No}),W=_-p.tools.length}I=await Q(t.pro?.entitlementToken);const n=wo(t,I);if(!n.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${n.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});R=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&K(r),R||await he(t);const a=R?[]:h.adapter.collectSegments(p,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const m=N?N.clock():0,{vault:f,count:y,sanitized:k}=R?{vault:null,count:0,sanitized:0}:await me(a,t.redaction,{signal:i.signal,isPro:I,onEgress:w=>Te.push(Ke({ts:Date.now(),client:"redaction",tool:`detect:${w.backend}@${w.host||"local"}`,ok:w.ok,ms:w.ms,error:w.error}))});if(N&&N.lap("redact",m),E=f,A=y,D=k||0,!I&&y>0){ko(t,I);try{ee(t,q())}catch{}}if(!R&&Array.isArray(p.tools)&&p.tools.length&&typeof h.adapter.injectSystemNote=="function"){const w=We(p?.model,t,h.kind,{destination:String(r.headers["x-chatpanel-destination"]||p?.chatpanel?.destination||"").trim()}),g=!(w&&w.type==="api");h.adapter.injectSystemNote(p,kt({toolData:t.tools?.toolData,ownTools:g}))}else!R&&y>0&&typeof h.adapter.injectSystemNote=="function"&&h.adapter.injectSystemNote(p,St());M=Buffer.from(JSON.stringify(p),"utf8")}}const O=wt({vault:E,toolData:t.tools?.toolData}),j=p&&typeof p.chatpanel=="object"&&p.chatpanel||null;j&&(delete p.chatpanel,M=Buffer.from(JSON.stringify(p),"utf8"));const H={destination:String(r.headers["x-chatpanel-destination"]||j?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||j?.reach||"").trim(),run:Xo(r.headers["x-chatpanel-run"],j?.run)},v=We(p?.model,t,h.kind,{destination:H.destination});if(H.destination&&(!v||v.id!==H.destination))return N?.commit(),s(o,404,{error:{message:`no destination "${H.destination}" is configured on this gateway`,type:"unknown_destination",known:Oo(t).map(e=>e.id)}});N&&(N.meta={t:Date.now(),model:p?.model||null,dest:v?v.id:null,type:v?v.type:null,redacted:A,sanitized:D,narrowed:W,detail:rt(E,t.logDetail),redaction:R?"off":t.redaction.tier||"basic"});const U=Et();if(U&&v){const e=v.type==="api"?Be(U,{model:p?.model||"",endpoint:v.baseUrl||""}):At(U,v.agent||v.id)?Be(U,{model:p?.model||""}):{ok:!1,reason:`agent "${v.agent||v.id}" is not allowed by your organisation’s policy`};if(!e.ok)return N?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}return v&&v.type==="api"?v.baseUrl?Go(v.baseUrl,t)?(N?.commit(),s(o,508,{error:{message:`destination "${v.id}" points back at the gateway (${v.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Zo(r,o,{...h,pathname:c,search:u.search,base:v.baseUrl,destKey:v.apiKey,destProtocol:v.protocol,harness:O,trace:N},M,E):(N?.commit(),s(o,502,{error:`destination "${v.id}" has no baseUrl`})):Ho(r,o,{...h,pathname:c,agentOverride:v?.agent,harness:O,trace:N,run:H.run},p,E,t,I)})}function Xo(t,l){let d=l&&typeof l=="object"?l:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const r={};if(Array.isArray(d.grants)&&(r.grants=d.grants.map(o=>String(o).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const o=d.workspace;r.workspace={repo:String(o.repo).slice(0,400),projectId:String(o.projectId||"").slice(0,120),jobId:String(o.jobId||"").slice(0,120),...o.base?{base:String(o.base).slice(0,120)}:{}}}return d.connectionId&&(r.connectionId=String(d.connectionId).slice(0,64)),Object.keys(r).length?r:null}let ue=null;async function Gr(t=xe()){It();let l=null;try{l=await Ot()}catch(h){throw h instanceof xt&&(console.error(`[chatpanel-gateway] org policy: ${h.message}`),process.exit(78)),h}const d=l?.policy||null;d&&(Ne(t,d),console.log(`[chatpanel-gateway] ${l.label} — ${l.signed?"signed":"unsigned"} policy from ${l.source}`)),Tt(globalThis,{allow:d?.egress?(h,{local:b})=>Pt(d,h,{local:b}):null}),$e();const r=Yo(t),o=jt(t),u=ut(t);r.on("error",h=>{h&&h.code==="EADDRINUSE"&&(console.error(`Port ${t.port} is already in use — another app (or a second gateway) has it.`),console.error(`Fix: free the port, or set a different one — edit "port" in ${q()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${h?.message||h}`),process.exit(1)}),r.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${Z} on http://${t.host}:${t.port}`),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),Wt(t).then(h=>{ue=h}).catch(h=>console.log(` bridge : not supervised (${h?.message||h})`)),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),tt(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),Re()&&ge($,Me()).then(h=>{h?.ok&&console.log(` warm : seeded ${h.ingested} records from ${h.file}`)}).catch(()=>{});const c=()=>{o?.stop(),u.stop(),ue?.stop(),r.close(()=>process.exit(0))};return process.on("SIGINT",c),process.on("SIGTERM",c),r}export{Z as VERSION,Yo as createGateway,Uo as joinUpstream,_e as parseAgentModel,Gr as start};
19
+ `),p=a.redact?await q(t.pro?.entitlementToken):!0,S=async f=>{if(f.type!=="final"||!a.redact)return f;try{let _=f.text;return await fe([Ce(()=>_,V=>{_=V})],t.redaction,{isPro:p}),{...f,text:_}}catch{return f}};l({type:"state",state:x.state()});const h=setInterval(()=>{const f=x.state();if(f==="downloading"||f==="loading"){l({type:"progress",state:f,...x.progress()||{}});return}if(f==="error"){l({type:"error",code:"model_failed",message:x.health().error||"model failed to load",fatal:!0}),clearInterval(h);return}if(a.diarize){const _=$.state();if(_==="downloading"||_==="loading"){l({type:"diarize-progress",state:_,...$.progress()||{}});return}}l({type:"state",state:f}),clearInterval(h)},500);h.unref?.();let w=Promise.resolve();const b=x.subscribe(n,f=>{w=w.then(async()=>{l(await S(f)),f.type==="end"&&(clearInterval(h),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(h),b?.()});return}if(!e[2]&&r.method==="DELETE")return await x.endSession(n),s(o,200,{ok:!0})}}if(c==="/logs"&&r.method==="GET")return s(o,200,{entries:[...i].reverse()});if(c==="/config"&&r.method==="GET"){const e=await q(t.pro?.entitlementToken);return s(o,200,Ze(t,{proUnlocked:e}))}if(c==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});Bo(t,e),Ie(t);try{te(t,ee())}catch(S){return s(o,500,{error:`could not persist config: ${S.message}`})}const n=t.redaction?.detection,a=!n||!n.backend||n.backend==="off",l=B.state();t.ner?.autostart&&a&&l!=="ready"&&l!=="loading"&&l!=="downloading"&&B.setModel(t.ner.model,{onLog:S=>console.log(S)}).then(S=>{S&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const p=await q(t.pro?.entitlementToken);return s(o,200,Ze(t,{proUnlocked:p}))}if(r.method==="GET"&&c==="/skills"){const e=await de(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=ie(t.bridge?.token);try{const a=await fetch(`${e}/skills`,{headers:{Accept:"application/json",...n?{Authorization:`Bearer ${n}`}:{}},signal:AbortSignal.timeout(8e3)}),l=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(l?.skills)?l.skills:[]}):s(o,a.status,{error:{message:l?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+$/.test(c)){const e=decodeURIComponent(c.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const n=await de(t);if(!n)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=ie(t.bridge?.token);try{const l=await fetch(`${n}/skills/${encodeURIComponent(e)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),p=await l.json().catch(()=>({}));return l.ok?s(o,200,{skill:p?.skill||null}):s(o,l.status,{error:{message:p?.error||`bridge ${l.status}`,type:"bridge_error"}})}catch(l){return s(o,502,{error:{message:`bridge unreachable: ${l.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/\/models$/.test(c))return s(o,200,await Do(t));if(nr.some(e=>c===e||c.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${W}) has no ${c} — update it to use this feature`,type:"unknown_endpoint"}});const y=Ko(c,r.headers,t);let g;try{g=await v(r,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let E=null,m=null,M=g,A=0,D=0,Z=0,R=!1,j=!0;const P=t.logRequests&&y.redactable&&r.method==="POST"?Wo(d):null;if(y.redactable&&r.method==="POST"&&g.length){try{m=JSON.parse(g.toString("utf8"))}catch{m=null}if(m&&Zo(m,y.kind))M=g;else if(m){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(m.tools)&&m.tools.length){const b=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Lo,f=e.narrowAll?null:V=>!Go.test(ot(V)),_=m.tools.length;m.tools=vt(m.tools,Vo(m,y.kind),{cap:b,keep:f,name:ot,description:zo}),Z=_-m.tools.length}j=await q(t.pro?.entitlementToken);const n=Po(t,j);if(!n.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${n.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});R=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&F(r),R||await ke(t);const a=R?[]:y.adapter.collectSegments(m,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const p=P?P.clock():0,{vault:S,count:h,sanitized:w}=R?{vault:null,count:0,sanitized:0}:await fe(a,t.redaction,{signal:l.signal,isPro:j,onEgress:b=>Ae.push(Qe({ts:Date.now(),client:"redaction",tool:`detect:${b.backend}@${b.host||"local"}`,ok:b.ok,ms:b.ms,error:b.error}))});if(P&&P.lap("redact",p),E=S,A=h,D=w||0,!j&&h>0){$o(t,j);try{te(t,ee())}catch{}}if(!R&&Array.isArray(m.tools)&&m.tools.length&&typeof y.adapter.injectSystemNote=="function"){const b=Xe(m?.model,t,y.kind,{destination:String(r.headers["x-chatpanel-destination"]||m?.chatpanel?.destination||"").trim()}),f=!(b&&b.type==="api");y.adapter.injectSystemNote(m,_t({toolData:t.tools?.toolData,ownTools:f}))}else!R&&h>0&&typeof y.adapter.injectSystemNote=="function"&&y.adapter.injectSystemNote(m,Ot());M=Buffer.from(JSON.stringify(m),"utf8")}}const O=Tt({vault:E,toolData:t.tools?.toolData}),I=m&&typeof m.chatpanel=="object"&&m.chatpanel||null;I&&(delete m.chatpanel,M=Buffer.from(JSON.stringify(m),"utf8"));const z={destination:String(r.headers["x-chatpanel-destination"]||I?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||I?.reach||"").trim(),run:ir(r.headers["x-chatpanel-run"],I?.run)},T=Xe(m?.model,t,y.kind,{destination:z.destination});if(z.destination&&(!T||T.id!==z.destination))return P?.commit(),s(o,404,{error:{message:`no destination "${z.destination}" is configured on this gateway`,type:"unknown_destination",known:Io(t).map(e=>e.id)}});P&&(P.meta={t:Date.now(),model:m?.model||null,dest:T?T.id:null,type:T?T.type:null,redacted:A,sanitized:D,narrowed:Z,detail:it(E,t.logDetail),redaction:R?"off":t.redaction.tier||"basic"});const U=jt();if(U&&T){const e=T.type==="api"?je(U,{model:m?.model||"",endpoint:T.baseUrl||""}):Rt(U,T.agent||T.id)?je(U,{model:m?.model||""}):{ok:!1,reason:`agent "${T.agent||T.id}" is not allowed by your organisation’s policy`};if(!e.ok)return P?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(T&&T.type==="api")return T.baseUrl?Yo(T.baseUrl,t)?(P?.commit(),s(o,508,{error:{message:`destination "${T.id}" points back at the gateway (${T.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):sr(r,o,{...y,pathname:c,search:u.search,base:T.baseUrl,destKey:T.apiKey,destProtocol:T.protocol,harness:O,trace:P},M,E):(P?.commit(),s(o,502,{error:`destination "${T.id}" has no baseUrl`}));const X=ce(r),ne=X==="local"&&t.bridge?.openAgentLane?"token":X;if(ne==="local")return P?.commit(),s(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const se=xt({...z.run||{},...z.reach?{reach:z.reach}:{}},ne);return er(r,o,{...y,pathname:c,agentOverride:T?.agent,harness:O,trace:P,run:Object.keys(se).length?se:null},m,E,t,j)})}function ir(t,i){let d=i&&typeof i=="object"?i:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const r={};if(Array.isArray(d.grants)&&(r.grants=d.grants.map(o=>String(o).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const o=d.workspace;r.workspace={repo:String(o.repo).slice(0,400),projectId:String(o.projectId||"").slice(0,120),jobId:String(o.jobId||"").slice(0,120),...o.base?{base:String(o.base).slice(0,120)}:{}}}return d.connectionId&&(r.connectionId=String(d.connectionId).slice(0,64)),Object.keys(r).length?r:null}let he=null;async function Yr(t=Be()){Ft();let i=null;try{i=await It()}catch(y){throw y instanceof Mt&&(console.error(`[chatpanel-gateway] org policy: ${y.message}`),process.exit(78)),y}const d=i?.policy||null;d&&(Ie(t,d),console.log(`[chatpanel-gateway] ${i.label} — ${i.signed?"signed":"unsigned"} policy from ${i.source}`)),Ct(globalThis,{allow:d?.egress?(y,{local:g})=>Lt(d,y,{local:g}):null}),ge();const r=ar(t),o=Ut(t),u=ht(t);r.on("error",y=>{y&&y.code==="EADDRINUSE"&&(console.error(`Port ${t.port} is already in use — another app (or a second gateway) has it.`),console.error(`Fix: free the port, or set a different one — edit "port" in ${ee()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${y?.message||y}`),process.exit(1)}),r.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${W} on http://${t.host}:${t.port}`),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token"),ro(t).then(y=>{he=y}).catch(y=>console.log(` bridge : not supervised (${y?.message||y})`)),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),st(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),Ve()&&ve(N,ze()).then(y=>{y?.ok&&console.log(` warm : seeded ${y.ingested} records from ${y.file}`)}).catch(()=>{});const c=()=>{o?.stop(),u.stop(),he?.stop(),r.close(()=>process.exit(0))};return process.on("SIGINT",c),process.on("SIGTERM",c),r}export{W as VERSION,ar as createGateway,tr as joinUpstream,Pe as parseAgentModel,Yr as start};
package/src/update.js CHANGED
@@ -1 +1 @@
1
- import I from"node:os";import l from"node:path";import{execFile as A}from"node:child_process";import{chmod as B,rename as v,mkdir as J,readFile as V,writeFile as U,rm as G}from"node:fs/promises";import{existsSync as K,readFileSync as W,realpathSync as Y}from"node:fs";import{restartService as q,serviceRegistered as y}from"./service.js";const h="@chatpanel/gateway",z="chatpanel/chatpanel-gateway",Q=`https://api.github.com/repos/${z}/releases/latest`,X=`https://registry.npmjs.org/${h}/latest`,C="https://registry.npmjs.org",P=360*60*1e3,j=600*1e3,Z=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),tt=15*6e4,D=20*6e4,E=process.env.CHATPANEL_UPDATE_CACHE||l.join(I.homedir(),".chatpanel","gateway-update-check.json"),_=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",k={"User-Agent":"chatpanel-gateway-updater"},et=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function at(t){try{const e=new URL(t);return e.protocol==="https:"&&et.has(e.hostname)}catch{return!1}}let p={at:0,error:""};function ht(){p={at:0,error:""}}function S(){const t=l.basename(process.execPath).toLowerCase();return!(t.startsWith("node")||t.startsWith("bun"))}function nt(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function g(t=""){const e=/(\d+(?:\.\d+){0,3})/.exec(t||"");return e?e[1]:null}function N(t,e){const n=String(t).split(".").map(Number),a=String(e).split(".").map(Number);for(let r=0;r<Math.max(n.length,a.length);r+=1){const s=(n[r]||0)-(a[r]||0);if(s)return s>0?1:-1}return 0}async function rt(){try{return JSON.parse(await V(E,"utf8"))}catch{return null}}async function ot(t){try{await J(l.dirname(E),{recursive:!0}),await U(E,JSON.stringify(t))}catch{}}async function L(t,e=Z){const n=new AbortController,a=setTimeout(()=>n.abort(),e);try{const r=await fetch(t,{headers:{Accept:"application/json, application/vnd.github+json",...k},signal:n.signal});if(!r.ok)throw new Error(r.status===403&&/github/.test(t)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${r.status}`);return await r.json()}catch(r){const s=r?.cause?.code||r?.cause?.message||r?.message||String(r);throw new Error(n.signal.aborted?`the update server did not answer within ${Math.round(e/1e3)}s`:`${new URL(t).hostname}: ${s}`)}finally{clearTimeout(a)}}function T(t=process.argv[1]){let e=t?l.resolve(t):"";try{e=Y(e)}catch{}const n=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(e);return n?n[1]:""}function st(){const t=T();if(!t)return"";try{return String(JSON.parse(W(l.join(t,"package.json"),"utf8")).version||"")}catch{return""}}function $(){const t=l.dirname(process.execPath);return[l.join(t,"..","lib","node_modules","npm","bin","npm-cli.js"),l.join(t,"node_modules","npm","bin","npm-cli.js")].find(n=>K(n))||""}function it(){const t=$(),e={...process.env,npm_config_registry:C,npm_config_fund:"false",npm_config_audit:"false"};delete e.ELECTRON_RUN_AS_NODE;const[n,a]=t?[process.execPath,[t,"install","-g",`${h}@latest`]]:["npm",["install","-g",`${h}@latest`]];return new Promise(r=>{A(n,a,{env:e,timeout:D,maxBuffer:8<<20,windowsHide:!0},(s,d,u)=>{const o=`${d||""}${u||""}`.trim();return s?s.killed&&!o?r({ok:!1,out:`npm was still running after ${Math.round(D/6e4)} minutes and was stopped`}):r({ok:!1,out:o||(t?s.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):r({ok:!0,out:o})})})}async function O(t,{force:e=!1}={}){const n=S()?"binary":"npm";if(_)return{current:t,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:n==="npm"?"npm":"release",service:!1,disabled:!0};const a=nt();let r=null,s=null,d=!1,u="",o=0;const i=await rt(),w=i&&i.mode===n,x=()=>{r=w&&i.latest||null,s=w&&i.assetUrl||null,o=w&&i.checkedAt||0,d=!0};if(!e&&w&&Date.now()-i.checkedAt<P)r=i.latest,s=i.assetUrl,o=i.checkedAt;else if(!e&&p.at&&Date.now()-p.at<j)u=p.error,x();else try{if(n==="npm"){const m=await L(X);r=g(m.version)}else{const m=await L(Q);r=g(m.tag_name)||g(m.name),s=a&&(m.assets||[]).find(F=>F.name===a)?.browser_download_url||null}o=Date.now(),await ot({checkedAt:o,mode:n,latest:r,assetUrl:s}),p={at:0,error:""}}catch(m){u=m.message,p={at:Date.now(),error:u},x()}const R=!!r&&N(r,t)>0,H=n==="binary"?!!s&&(process.platform!=="win32"||y()):!!T()&&(process.platform!=="win32"||y()&&!!$()),M=n==="npm"?process.platform==="win32"?`chatpanel-gateway --stop; npm i -g ${h}@latest; chatpanel-gateway --install`:`npm i -g ${h}@latest`:null;return{current:t,latest:r,updateAvailable:R,mode:n,canSelfUpdate:H,assetUrl:s,stale:d,error:u,npmCommand:M,channel:n==="npm"?"npm":"release",service:y(),checkedAt:o}}let f=null,b=null;function gt(t){const e=S()?"binary":"npm";return _?{current:t,latest:null,updateAvailable:!1,mode:e,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:e==="npm"?"npm":"release",service:!1,disabled:!0}:((!f||(f.stale?!(p.at&&Date.now()-p.at<j):Date.now()-f.seenAt>P))&&!b&&(b=O(t).then(a=>{f={...a,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{b=null})),f?{...f,seenAt:void 0,current:t}:{current:t,latest:null,updateAvailable:!1,mode:e,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:e==="npm"?"npm":"release",service:y()})}function yt(){f=null,b=null}async function lt(t){const e=process.execPath,n=l.dirname(e),a=l.join(n,`.chatpanel-gateway.new-${Date.now()}`),r=new AbortController,s=setTimeout(()=>r.abort(),tt);let d;try{const o=await fetch(t.assetUrl,{headers:k,redirect:"follow",signal:r.signal});if(!o.ok)throw new Error(`download failed (HTTP ${o.status})`);if(!at(o.url||t.assetUrl))throw new Error(`refused: the download was redirected to ${o.url}, which is not a ChatPanel release host`);d=Buffer.from(await o.arrayBuffer())}finally{clearTimeout(s)}if(d.length<5<<20)throw new Error(`the download was only ${(d.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await U(a,d),process.platform!=="win32"&&await B(a,493),process.platform==="darwin"&&await new Promise(o=>A("xattr",["-c",a],()=>o()));const u=await new Promise(o=>A(a,["--version"],{timeout:6e4,windowsHide:!0},(i,w)=>o(i?"":String(w||"").trim())));if(!g(u))throw await G(a,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await v(e,l.join(n,`chatpanel-gateway.old-${Date.now()}.exe`)),await v(a,e),g(u)}async function ct(t){if(_)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const e=await O(t,{force:!0});if(e.stale)throw new Error(`Could not reach the update server${e.error?` (${e.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!e.updateAvailable)throw new Error(`Already on the latest ${e.channel} version (v${t}).`);if(!e.canSelfUpdate)throw new Error(e.mode==="npm"?`This gateway cannot update itself here. Run: ${e.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(e.mode==="binary")return{from:t,to:await lt(e),mode:"binary"};if(process.platform==="win32")return{from:t,to:e.latest,mode:"npm",deferred:`"${process.execPath}" "${$()}" install -g ${h}@latest --registry=${C} --no-fund --no-audit`};const n=await it();if(!n.ok)throw new Error(`npm install failed: ${n.out.slice(0,800)}`);const a=st();if(!a||N(a,t)<=0)throw new Error(`npm ran, but the install at ${T()} is still ${a||"unreadable"} — the service launches a copy npm did not update. Run: ${e.npmCommand}`);return{from:t,to:a,mode:"npm"}}const c={state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0};function bt(){return{...c}}function At(t,{restart:e=q,apply:n=ct}={}){return c.state==="installing"||c.state==="restarting"?{...c,already:!0}:(Object.assign(c,{state:"installing",mode:S()?"binary":"npm",from:t,to:"",detail:"",startedAt:Date.now(),endedAt:0}),n(t).then(a=>{Object.assign(c,{state:"restarting",to:a.to,mode:a.mode,detail:a.deferred?`stopping to install v${a.to}, then relaunching`:`v${a.to} is installed; restarting the gateway into it`}),setTimeout(()=>{e({winInstall:a.deferred||""})||Object.assign(c,{state:"done",endedAt:Date.now(),detail:`v${a.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.`})},400)}).catch(a=>{Object.assign(c,{state:"failed",endedAt:Date.now(),detail:String(a?.message||a).slice(0,1200)})}),{...c})}function Et(){Object.assign(c,{state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0})}export{Et as _resetUpdateJob,yt as _resetUpdateStatus,O as checkForUpdate,N as cmpVersions,at as downloadHostAllowed,S as isCompiledBinary,T as npmPackageRoot,ht as resetUpdateBackoff,ct as selfUpdate,At as startUpdate,bt as updateJob,gt as updateStatus};
1
+ import J from"node:os";import l from"node:path";import{execFile as b}from"node:child_process";import{chmod as G,rename as P,mkdir as V,readFile as Y,writeFile as D,rm as K}from"node:fs/promises";import{existsSync as W,readFileSync as q,realpathSync as z}from"node:fs";import{restartService as Q,serviceRegistered as y}from"./service.js";const g="@chatpanel/gateway",ge="chatpanel/chatpanel-gateway",N="https://dl.chatpanel.net/version/gateway",E=(process.env.CHATPANEL_NPM_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/$/,""),X=`${E}/${g}/latest`,Z=e=>`https://dl.chatpanel.net/gateway/${e.replace(/^chatpanel-gateway-/,"")}`,L=360*60*1e3,j=600*1e3,ee=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),te=15*6e4,k=20*6e4,_=process.env.CHATPANEL_UPDATE_CACHE||l.join(J.homedir(),".chatpanel","gateway-update-check.json"),S=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",R={"User-Agent":"chatpanel-gateway-updater"},ae=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function ne(e){try{const t=new URL(e);return t.protocol==="https:"&&ae.has(t.hostname)}catch{return!1}}let m={at:0,error:""};function ye(){m={at:0,error:""}}function T(){const e=l.basename(process.execPath).toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}function re(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function f(e=""){const t=/(\d+(?:\.\d+){0,3})/.exec(e||"");return t?t[1]:null}function O(e,t){const r=String(e).split(".").map(Number),a=String(t).split(".").map(Number);for(let n=0;n<Math.max(r.length,a.length);n+=1){const o=(r[n]||0)-(a[n]||0);if(o)return o>0?1:-1}return 0}async function se(){try{return JSON.parse(await Y(_,"utf8"))}catch{return null}}async function oe(e){try{await V(l.dirname(_),{recursive:!0}),await D(_,JSON.stringify(e))}catch{}}async function v(e,t=ee){const r=new AbortController,a=setTimeout(()=>r.abort(),t);try{const n=await fetch(e,{headers:{Accept:"application/json, application/vnd.github+json",...R},signal:r.signal});if(!n.ok)throw new Error(n.status===403&&/github/.test(e)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${n.status}`);return await n.json()}catch(n){const o=n?.cause?.code||n?.cause?.message||n?.message||String(n);throw new Error(r.signal.aborted?`the update server did not answer within ${Math.round(t/1e3)}s`:`${new URL(e).hostname}: ${o}`)}finally{clearTimeout(a)}}function $(e=process.argv[1]){let t=e?l.resolve(e):"";try{t=z(t)}catch{}const r=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(t);return r?r[1]:""}function ie(){const e=$();if(!e)return"";try{return String(JSON.parse(q(l.join(e,"package.json"),"utf8")).version||"")}catch{return""}}function x(){const e=l.dirname(process.execPath);return[l.join(e,"..","lib","node_modules","npm","bin","npm-cli.js"),l.join(e,"node_modules","npm","bin","npm-cli.js")].find(r=>W(r))||""}function le(){const e=x(),t={...process.env,npm_config_registry:E,npm_config_fund:"false",npm_config_audit:"false"};delete t.ELECTRON_RUN_AS_NODE;const[r,a]=e?[process.execPath,[e,"install","-g",`${g}@latest`]]:["npm",["install","-g",`${g}@latest`]];return new Promise(n=>{b(r,a,{env:t,timeout:k,maxBuffer:8<<20,windowsHide:!0},(o,d,p)=>{const s=`${d||""}${p||""}`.trim();return o?o.killed&&!s?n({ok:!1,out:`npm was still running after ${Math.round(k/6e4)} minutes and was stopped`}):n({ok:!1,out:s||(e?o.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):n({ok:!0,out:s})})})}async function H(e,{force:t=!1}={}){const r=T()?"binary":"npm";if(S)return{current:e,latest:null,updateAvailable:!1,mode:r,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:r==="npm"?"npm":"release",service:!1,disabled:!0};const a=re();let n=null,o=null,d=!1,p="",s=0;const i=await se(),h=i&&i.mode===r,U=()=>{n=h&&i.latest||null,o=h&&i.assetUrl||null,s=h&&i.checkedAt||0,d=!0};if(!t&&h&&Date.now()-i.checkedAt<L)n=i.latest,o=i.assetUrl,s=i.checkedAt;else if(!t&&m.at&&Date.now()-m.at<j)p=m.error,U();else try{if(r==="npm"){let u;try{u=await v(X),n=f(u.version)}catch(B){const C=await v(N);if(n=f(C?.npm?.version)||f(C?.version),!n)throw B}}else{const u=await v(N);n=f(u.version)||f(u.release?.tag),o=a&&(u.release?.assets||[]).includes(a)?Z(a):null}s=Date.now(),await oe({checkedAt:s,mode:r,latest:n,assetUrl:o}),m={at:0,error:""}}catch(u){p=u.message,m={at:Date.now(),error:p},U()}const M=!!n&&O(n,e)>0,F=r==="binary"?!!o&&(process.platform!=="win32"||y()):!!$()&&(process.platform!=="win32"||y()&&!!x()),I=r==="npm"?process.platform==="win32"?`chatpanel-gateway --stop; npm i -g ${g}@latest; chatpanel-gateway --install`:`npm i -g ${g}@latest`:null;return{current:e,latest:n,updateAvailable:M,mode:r,canSelfUpdate:F,assetUrl:o,stale:d,error:p,npmCommand:I,channel:r==="npm"?"npm":"release",service:y(),checkedAt:s}}let w=null,A=null;function Ae(e){const t=T()?"binary":"npm";return S?{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:!1,disabled:!0}:((!w||(w.stale?!(m.at&&Date.now()-m.at<j):Date.now()-w.seenAt>L))&&!A&&(A=H(e).then(a=>{w={...a,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{A=null})),w?{...w,seenAt:void 0,current:e}:{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:y()})}function be(){w=null,A=null}async function ce(e){const t=process.execPath,r=l.dirname(t),a=l.join(r,`.chatpanel-gateway.new-${Date.now()}`),n=new AbortController,o=setTimeout(()=>n.abort(),te);let d;try{const s=await fetch(e.assetUrl,{headers:R,redirect:"follow",signal:n.signal});if(!s.ok)throw new Error(`download failed (HTTP ${s.status})`);if(!ne(s.url||e.assetUrl))throw new Error(`refused: the download was redirected to ${s.url}, which is not a ChatPanel release host`);d=Buffer.from(await s.arrayBuffer())}finally{clearTimeout(o)}if(d.length<5<<20)throw new Error(`the download was only ${(d.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await D(a,d),process.platform!=="win32"&&await G(a,493),process.platform==="darwin"&&await new Promise(s=>b("xattr",["-c",a],()=>s()));const p=await new Promise(s=>b(a,["--version"],{timeout:6e4,windowsHide:!0},(i,h)=>s(i?"":String(h||"").trim())));if(!f(p))throw await K(a,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await P(t,l.join(r,`chatpanel-gateway.old-${Date.now()}.exe`)),await P(a,t),f(p)}async function de(e){if(S)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const t=await H(e,{force:!0});if(t.stale)throw new Error(`Could not reach the update server${t.error?` (${t.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!t.updateAvailable)throw new Error(`Already on the latest ${t.channel} version (v${e}).`);if(!t.canSelfUpdate)throw new Error(t.mode==="npm"?`This gateway cannot update itself here. Run: ${t.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(t.mode==="binary")return{from:e,to:await ce(t),mode:"binary"};if(process.platform==="win32")return{from:e,to:t.latest,mode:"npm",deferred:`"${process.execPath}" "${x()}" install -g ${g}@latest --registry=${E} --no-fund --no-audit`};const r=await le();if(!r.ok)throw new Error(`npm install failed: ${r.out.slice(0,800)}`);const a=ie();if(!a||O(a,e)<=0)throw new Error(`npm ran, but the install at ${$()} is still ${a||"unreadable"} — the service launches a copy npm did not update. Run: ${t.npmCommand}`);return{from:e,to:a,mode:"npm"}}const c={state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0};function Ee(){return{...c}}function _e(e,{restart:t=Q,apply:r=de}={}){return c.state==="installing"||c.state==="restarting"?{...c,already:!0}:(Object.assign(c,{state:"installing",mode:T()?"binary":"npm",from:e,to:"",detail:"",startedAt:Date.now(),endedAt:0}),r(e).then(a=>{Object.assign(c,{state:"restarting",to:a.to,mode:a.mode,detail:a.deferred?`stopping to install v${a.to}, then relaunching`:`v${a.to} is installed; restarting the gateway into it`}),setTimeout(()=>{t({winInstall:a.deferred||""})||Object.assign(c,{state:"done",endedAt:Date.now(),detail:`v${a.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.`})},400)}).catch(a=>{Object.assign(c,{state:"failed",endedAt:Date.now(),detail:String(a?.message||a).slice(0,1200)})}),{...c})}function Se(){Object.assign(c,{state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0})}export{Se as _resetUpdateJob,be as _resetUpdateStatus,H as checkForUpdate,O as cmpVersions,ne as downloadHostAllowed,T as isCompiledBinary,$ as npmPackageRoot,ye as resetUpdateBackoff,de as selfUpdate,_e as startUpdate,Ee as updateJob,Ae as updateStatus};