@chatpanel/gateway 0.46.4 → 0.52.3
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 +1 -1
- package/bin/chatpanel-gateway.js +4 -4
- package/package.json +4 -4
- package/src/bridge.js +4 -4
- package/src/config.js +1 -1
- package/src/diarize-engine.js +1 -1
- package/src/diarize-models.js +1 -0
- package/src/server.js +23 -23
- package/src/service.js +18 -17
- package/src/shape.js +5 -5
- package/src/stt-engine.js +1 -1
- package/src/toolrelay.js +2 -2
- package/src/version.js +1 -1
package/README.md
CHANGED
|
@@ -256,7 +256,7 @@ behaviour for a trusted machine — the startup log calls it out.
|
|
|
256
256
|
|
|
257
257
|
**Pairing** a browser the gateway does not recognise (ChatPanel's Firefox build, whose
|
|
258
258
|
origin is a per-profile UUID; a dev build): `chatpanel-gateway pair` prints a one-time
|
|
259
|
-
code (5 minutes, 5 attempts); enter it in ChatPanel → Settings →
|
|
259
|
+
code (5 minutes, 5 attempts); enter it in ChatPanel → Settings → Coding Agents. The exchange
|
|
260
260
|
(`POST /pair`) hands over the gateway token and, when this machine has one, the bridge
|
|
261
261
|
token — one code covers both. `POST /whoami` → `{ trust, paired }` tells a client where
|
|
262
262
|
it stands.
|
package/bin/chatpanel-gateway.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const
|
|
3
|
-
`)}process.argv.includes("--json")?console.log(JSON.stringify(
|
|
2
|
+
const s=process.argv[2],u={"--bridge":"chatpanel-bridge","--mcp-stdio":"chatpanel-bridge-mcp",mcp:"chatpanel-history-mcp","--extract-worker":"chatpanel-extract"};try{process.title=u[s]||"chatpanel-gateway"}catch{}try{if(s==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:e}=await import("../src/extract/worker.js");e()}else if(s==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(s==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(s==="mcp"){const{runMcpServer:e}=await import("../src/mcp.js");await e()}else if(s==="tools"||s==="call"){const{runMcpCli:e}=await import("../src/mcp-cli.js");process.exit(await e(process.argv.slice(2)))}else if(s==="policy"){const{loadPolicy:e,formatPolicy:a,PolicyLoadError:n}=await import("../src/policy.js");try{const r=await e();process.argv.includes("--json")?console.log(JSON.stringify(r?{...r,label:void 0}:null,null,2)):console.log(a(r))}catch(r){throw r instanceof n&&(console.error(`org policy: ${r.message}`),process.exit(78)),r}}else if(s==="--audit"){const{egressAudit:e,formatAudit:a}=await import("../src/egress.js"),{loadConfig:n}=await import("../src/config.js"),{readFileSync:r}=await import("node:fs"),{join:h}=await import("node:path"),l=await import("node:os"),c=n(),t=`http://127.0.0.1:${c.port||4320}`;let o=null,i=`no gateway running at ${t}`;try{const p=r(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||h(l.homedir(),".chatpanel","gateway-token"),"utf8").trim(),g=await fetch(`${t}/audit`,{headers:{authorization:`Bearer ${p}`},signal:AbortSignal.timeout(2500)});if(g.ok)o=await g.json();else if(g.status===404){const d=await fetch(`${t}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);i=`the gateway running at ${t}${d?.version?` (${d.version})`:""} predates --audit (0.7.0) — restart it after updating`}else i=`the gateway at ${t} refused the audit (HTTP ${g.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!o){const{VERSION:p}=await import("../src/server.js");o={...e(c,{ledger:null,version:p}),observed:[]},console.log(`(${i}; showing what the current config allows)
|
|
3
|
+
`)}process.argv.includes("--json")?console.log(JSON.stringify(o,null,2)):console.log(a(o))}else if(s==="sandbox"){const{srtModuleUrl:e}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&e()&&(process.env.CHATPANEL_SRT_MODULE=e());const{runSandboxCli:a}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await a(process.argv.slice(3)))}else if(s==="pair"){const{loadConfig:e}=await import("../src/config.js"),{readFileSync:a}=await import("node:fs"),{join:n}=await import("node:path"),r=await import("node:os"),l=`http://127.0.0.1:${e().port||4320}`,c=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||n(r.homedir(),".chatpanel","gateway-token");try{const t=a(c,"utf8").trim(),o=await fetch(`${l}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),i=await o.json().catch(()=>({}));if(o.status===404)throw new Error(`the gateway at ${l} predates pairing (0.9.0) — update and restart it`);if(!o.ok)throw new Error(i.error||`HTTP ${o.status}`);console.log(`Pairing code: ${i.display||i.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(t){console.error(`could not get a pairing code from the gateway at ${l}: ${t?.message||t}${/ENOENT/.test(String(t?.message))?` (no token at ${c} — has the gateway started once?)`:""}`),process.exit(1)}}else if(s==="local"){const{localStatus:e,formatLocalStatus:a}=await import("../src/local-status.js");process.stdout.write(a(await e()))}else if(s==="connect"){const{connectAgents:e,formatConnect:a}=await import("../src/connect-agents.js"),n=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(a(e({dryRun:n}),{dryRun:n}))}else{const{start:e,VERSION:a}=await import("../src/server.js"),{installService:n,uninstallService:r,serviceReport:h,stopService:l,pathWithDir:c}=await import("../src/service.js");switch(s){case"--stop":l(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(a);break;case"--install":{const t=await n({version:a}),o=t.health;if(t.ok){const i=t.deferredTo?` — the ${t.deferredTo} app's gateway (v${o.version}) is the one answering right now; this install takes over at the next login`:"",p=t.replaced?`, replacing v${t.replaced}`:"";console.log(`ChatPanel Privacy Gateway v${o.version}: running at ${o.url}${p}, starts at login${t.wsl?" (Windows login, through wsl.exe)":""}${i}.`)}else o.ok?(console.error(`ChatPanel Privacy Gateway: v${a} is registered to start at login, but v${o.version} still answers at ${o.url} 40 s later.`),console.error(" Something starts it back faster than it can be replaced — `chatpanel-gateway --status` says what holds the port; `--stop`, then `--install`, separates the two steps.")):(console.error(`ChatPanel Privacy Gateway: login auto-start is registered, but nothing answered at ${o.url} after 40 s.`),t.errLog&&console.error(` last of the error log:
|
|
4
4
|
${t.errLog.split(`
|
|
5
|
-
`).map(
|
|
6
|
-
`)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself.");try{const{pruneForeignPrebuilds:
|
|
5
|
+
`).map(i=>` ${i}`).join(`
|
|
6
|
+
`)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself."));t.shadow&&(console.log(` ⚠ ${t.shadow}/chatpanel-gateway comes first on your PATH, so typing \`chatpanel-gateway\` still runs THAT copy, not this v${a}.`),console.log(` Remove it, or run this one by its full path. (The service just registered is this v${a} either way.)`));try{const{pruneForeignPrebuilds:i,pruneLine:p}=await import("../src/prune-install.js"),g=p(i({log:d=>console.error(d)}));g&&console.log(g)}catch{}t.launcher==="powershell"&&console.log(" (VBScript is not installed here, so the login launcher is PowerShell — a console flashes for an instant at login.)"),t.path?.added?console.log(` Added ${t.path.dir} to your PATH — \`chatpanel-gateway\` works in a NEW terminal.`):t.path?.error?console.log(` Could not add ${t.path.dir} to your PATH (${t.path.error}) — add it yourself to run \`chatpanel-gateway\` by name.`):t.path?.dir&&t.wsl&&c(process.env.PATH||"",t.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${t.path.dir}:$PATH"`),o.ok||process.exit(1);break}case"--uninstall":r(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(await h());break;case void 0:await e();break;default:console.error(`unknown option: ${s}
|
|
7
7
|
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(e){console.error(`error: ${e.message}`),process.exit(1)}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.52.3",
|
|
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": {
|
|
@@ -22,9 +22,9 @@
|
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
25
|
-
"@chatpanel/bridge": "^0.
|
|
26
|
-
"@chatpanel/events": "^0.
|
|
27
|
-
"@chatpanel/pii": "^0.11.
|
|
25
|
+
"@chatpanel/bridge": "^0.27.2",
|
|
26
|
+
"@chatpanel/events": "^0.200.1",
|
|
27
|
+
"@chatpanel/pii": "^0.11.1",
|
|
28
28
|
"@huggingface/transformers": "^4.2.0",
|
|
29
29
|
"defuddle": "^0.19.4",
|
|
30
30
|
"fflate": "^0.8.3",
|
package/src/bridge.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{readFileSync as
|
|
2
|
-
`):""}function
|
|
3
|
-
`)){const
|
|
1
|
+
import{readFileSync as j,existsSync as C}from"node:fs";import{join as L}from"node:path";import N from"node:os";const S=L(N.homedir(),".chatpanel","bridge-token"),F="http://127.0.0.1:4319",v=1e4;let c={at:0,cfgUrl:"",url:"",fell:!1};async function A(t,e){try{return(await fetch(`${t}/health`,{signal:AbortSignal.timeout(e)})).ok}catch{return!1}}async function z(t,{fallback:e,timeoutMs:r=1500,now:o=Date.now()}={}){e===void 0&&(e=process.env.CHATPANEL_BRIDGE_FALLBACK==="off"?"":F);const s=String(t?.bridge?.url||"").replace(/\/$/,"");if(c.url&&c.cfgUrl===s&&o-c.at<v)return c.url;let i=s||e,l=!1;return e&&i!==e&&!await A(i,r)&&await A(e,r)&&(i=e,l=!0,(!c.fell||c.cfgUrl!==s)&&console.log(`[gateway] bridge.url ${s} is not answering; the bridge on ${e} is — using it (fix the address in Settings to silence this)`)),c={at:o,cfgUrl:s,url:i,fell:l},i}function M(){c={at:0,cfgUrl:"",url:"",fell:!1}}let y=!1;function R(t){try{if(C(t))return j(t,"utf8").trim()}catch{}return""}function J(t,e=S){const r=R(e);return!t||y&&r&&r!==t?r:t}function P(t,e=S){const r=R(e);return!r||r===t?"":(y||(y=!0,console.warn("[gateway] the bridge rejected bridge.token from gateway.config.json; using ~/.chatpanel/bridge-token (the bridge wrote it). Clear the config value to silence this.")),r)}function W(){y=!1}const G=t=>t===401||t===403;async function _(t,e,r,o,s){const i=a=>fetch(`${t.replace(/\/$/,"")}/chat`,{method:"POST",headers:{"content-type":"application/json",...a?{authorization:`Bearer ${a}`}:{}},body:r,signal:o}),l=J(e,s);let f=await i(l);if(G(f.status)){const a=P(l,s);a&&(await f.text().catch(()=>{}),f=await i(a))}return f}function H(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:typeof e?.text=="string"?e.text:"").filter(Boolean).join(`
|
|
2
|
+
`):""}function $(t){return(t||[]).filter(e=>e&&(e.role==="user"||e.role==="assistant"||e.role==="system")).map(e=>({role:e.role,content:H(e.content)}))}async function q({bridgeUrl:t,agent:e,token:r,messages:o,system:s,specs:i,options:l,signal:f,tokenPath:a,approvals:g=!1}){const u=await _(t,r,JSON.stringify({agent:e,messages:$(o),system:s||"",options:l||{},...Array.isArray(i)&&i.length?{pageTools:{specs:i}}:{},...g?{approvals:!0}:{}}),f,a);if(!u.ok||!u.body)throw new Error(await O(u));return u}async function O(t){const e=await t.text().catch(()=>"");let r="";try{const o=JSON.parse(e);r=String(o?.error?.message||o?.error||o?.message||"").trim()}catch{}return r?r.slice(0,600):`bridge /chat HTTP ${t.status}${e?`: ${e.slice(0,200)}`:""}`}async function Q({bridgeUrl:t,agent:e,token:r,messages:o,system:s,options:i,signal:l,tokenPath:f},a,g=null,u=null){const h=await _(t,r,JSON.stringify({agent:e,messages:$(o),system:s||"",options:i||{}}),l,f);if(!h.ok||!h.body)throw new Error(await O(h));const D=h.body.getReader(),U=new TextDecoder;let d="",w="",b=!1,x=null;const E=m=>{for(const B of m.split(`
|
|
3
|
+
`)){const p=B.trim();if(!p.startsWith("data:"))continue;const T=p.slice(5).trim();if(!T||T==="[DONE]")continue;let n;try{n=JSON.parse(T)}catch{continue}n.type==="delta"&&typeof n.text=="string"?(b=!0,w+=n.text,a(n.text)):n.type==="done"?!b&&typeof n.text=="string"&&n.text&&(w+=n.text,a(n.text)):n.type==="error"?x=new Error(n.error||"bridge error"):(n.type==="usage"&&u&&u(n),g&&g(n))}};for(;;){const{done:m,value:B}=await D.read();if(m)break;d+=U.decode(B,{stream:!0});let p;for(;(p=d.indexOf(`
|
|
4
4
|
|
|
5
|
-
`))!==-1;)
|
|
5
|
+
`))!==-1;)E(d.slice(0,p)),d=d.slice(p+2)}if(d.trim()&&E(d),x)throw x;return w}export{F as DEFAULT_BRIDGE_URL,O as bridgeRefusal,P as bridgeTokenRejected,q as openBridgeChat,J as readBridgeToken,M as resetBridgeResolution,W as resetBridgeTokenPreference,z as resolveBridgeUrl,Q as streamBridgeChat,$ as toBridgeMessages};
|
package/src/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as d,existsSync as p}from"node:fs";import{join as
|
|
1
|
+
import{readFileSync as d,existsSync as p}from"node:fs";import{join as A}from"node:path";import l from"node:os";import{DEFAULT_MODEL as c}from"./models.js";import{DEFAULT_STT_MODEL as E}from"./stt-models.js";import{DEFAULT_DIARIZE_MODEL as f}from"./diarize-models.js";const s={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],maxBodyBytes:26214400,pro:{entitlementToken:"",free:{used:0}},sandbox:{mode:"open",hosts:[],write:[],denyRead:[]},bridge:{url:"http://127.0.0.1:4319",agent:"codex",token:"",permissionMode:"default",workingDir:"",openAgentLane:!1},mcp:{ask:{maxReach:"device",defaultModel:"",delegate:{roots:[],permissionMode:"acceptEdits"}}},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,union:[],warmMs:15*6e4,caseRecovery:!0,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:E,allowDownload:!0,diarize:!0,diarizeModel:f,warmMs:15*6e4},read:{provider:"defuddle",remote:{url:"",key:""}},search:{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},capabilities:{},runtime:{services:{}},registries:{},fusions:[],tts:{enabled:!0,warmMs:15*6e4,provider:"local",model:"",voice:"",allowDownload:!0,remote:{baseUrl:"",model:"",voice:"",redact:!0}},logRequests:!0,logDetail:"off"};function t(r,e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&r&&typeof r=="object"){const i={...r};for(const o of Object.keys(e))i[o]=t(r[o],e[o]);return i}return e===void 0?r:e}function g(r=process.env){let e=s;const i=r.CHATPANEL_GATEWAY_CONFIG||A(l.homedir(),".chatpanel","gateway.config.json");if(p(i))try{e=t(e,JSON.parse(d(i,"utf8")))}catch(a){throw new Error(`bad config file ${i}: ${a.message}`)}r.CHATPANEL_GATEWAY_HOST&&(e=t(e,{host:r.CHATPANEL_GATEWAY_HOST})),r.CHATPANEL_GATEWAY_PORT&&(e=t(e,{port:Number(r.CHATPANEL_GATEWAY_PORT)})),r.OPENAI_BASE_URL&&(e=t(e,{upstreams:{openai:{baseUrl:r.OPENAI_BASE_URL}}})),r.ANTHROPIC_BASE_URL&&(e=t(e,{upstreams:{anthropic:{baseUrl:r.ANTHROPIC_BASE_URL}}})),r.CHATPANEL_REDACTION_TIER&&(e=t(e,{redaction:{tier:r.CHATPANEL_REDACTION_TIER}}));for(const[a,n]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[n]&&(e=t(e,{registries:{[a]:r[n]}}));if(e.registries?.models&&!r.CHATPANEL_REGISTRY_MODELS)try{process.env.CHATPANEL_REGISTRY_MODELS=e.registries.models}catch{}const o=Number(e.port);return(!Number.isInteger(o)||o<1||o>65535)&&(e.port!==s.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(e.port)} — using ${s.port}`),e=t(e,{port:s.port})),e}export{s as DEFAULTS,g as loadConfig};
|
package/src/diarize-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ensureLib as
|
|
1
|
+
import{ensureLib as R,modelRoot as P}from"./ner-engine.js";import{join as L}from"node:path";import{existsSync as O,readdirSync as I}from"node:fs";import{makeWarmTimer as z}from"./warm-timer.js";import{DEFAULT_DIARIZE_MODEL as k,diarizeThreshold as W,isKnownDiarizeModel as Z}from"./diarize-models.js";const Q=k;let s="off",c=k,h=null,w=null,g=null,u=null,f=null,a=null,y=0,M=0;function V(){return c}function v(){return W(c)}function D(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function X(){return s}function $(){return s==="ready"&&!!h&&!!w}function Y(){return f}function tt(){return{configured:s!=="off",ok:$(),state:s,model:c,loaded:!!h,threshold:v(),error:g,warmMs:a?.warmMs??null}}function et(){return!!a?.pending()}function rt(){y++,a?.disarm()}function nt(){y=Math.max(0,y-1),y===0&&M===0&&$()&&a?.arm()}function p(){return y>0||M>0||s==="loading"||s==="downloading"}async function b({log:e=()=>{}}={}){if(p())return!1;a?.disarm();const t=h;if(h=null,w=null,u=null,f=null,g=null,s="off",t){try{await t.dispose?.()}catch{}e("[diarize] idle — speaker model unloaded (reloads on the next diarizing session)")}return!0}function j(e=c,t=D()){const r=L(P(),...e.split("/"),"onnx");if(!O(r))return!1;const n=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return I(r).some(i=>i===`model${n}.onnx`)}catch{return!1}}async function T({log:e=()=>{},allowDownload:t=!0}={}){let r;try{r=await R()}catch(o){return s="error",g=o.message,e(`[diarize] engine unavailable (${o.message})`),!1}const n=c,i=j(n);if(r.env.allowRemoteModels=i?!1:!!t,!i&&!t)return s="error",g="model not on disk and downloads disabled",!1;const l=r.env.remoteHost;if(!i)try{r.env.remoteHost="https://huggingface.co/"}catch{}s=i?"loading":"downloading",i||(f={model:n,file:null,pct:0},e(`[diarize] downloading ${n} (one-time)…`));try{const{AutoModel:o,AutoProcessor:d}=r,_=m=>{if(!m)return;const H=typeof m.progress=="number"?Math.round(m.progress):f?.pct??0;(m.status==="progress"||m.status==="download"||m.status==="initiate")&&(f={model:n,file:m.file||f?.file||null,pct:H})},x=await d.from_pretrained(n,{progress_callback:_}),E=await o.from_pretrained(n,{dtype:D(),progress_callback:_});return w=x,h=E,s="ready",g=null,f=null,e(`[diarize] ready — ${n} @ ${D()} (speakers split at cosine ${v()})`),!0}catch(o){return g=o.message,f=null,s="error",e(`[diarize] load failed (${o.message}) — diarization off`),!1}finally{try{r.env.remoteHost=l}catch{}}}function ot(e={}){if(u&&s!=="error")return u;s="loading";const t=typeof e.onLog=="function"?e.onLog:()=>{};return a=z({warmMs:e.warmMs,busy:p,log:t,unload:()=>b({log:t})}),u=F(T({log:t,allowDownload:e.allowDownload!==!1})),u}function F(e){return e.then(t=>(t&&!p()&&a?.arm(),t))}async function lt(e,{log:t=()=>{}}={}){return Z(e)?e===c?!0:p()?!1:(await b({log:()=>{}}),c=e,t(`[diarize] speaker model set to ${e} (loads on the next diarizing session)`),!0):!1}function it({onLog:e}={}){return u=null,s="loading",a??=z({warmMs:void 0,busy:p,log:e||(()=>{}),unload:()=>b({log:e||(()=>{})})}),u=F(T({log:e,allowDownload:!0})),u}const q=16e3;function A(e){let t=0;for(const n of e)t+=n*n;t=Math.sqrt(t)||1;const r=new Float32Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]/t;return r}async function S(e){try{const t=await w(e),r=await h(t),n=r.embeddings??r.logits??r.last_hidden_state;return n?.data?Float32Array.from(n.data):null}catch{return null}}async function st(e){if(!$()||!(e instanceof Float32Array)||!e.length)return null;M++;try{return await C(e)}finally{M--,p()||a?.arm()}}async function C(e){const t=2*q,r=Math.round(1.3*q);if(e.length<=Math.round(t*1.4)){const l=await S(e);return l?A(l):null}const n=[];for(let l=0;l+t<=e.length;l+=r){const o=await S(e.subarray(l,l+t));o&&n.push(A(o))}if(!n.length){const l=await S(e);return l?A(l):null}const i=new Float32Array(n[0].length);for(const l of n)for(let o=0;o<i.length;o++)i[o]+=l[o];return A(i)}function at(){a?.disarm(),a=null,y=0,M=0,s="off",c=k,h=null,w=null,g=null,u=null,f=null}function ut(e,t,{warmMs:r=null}={}){h=e,w=t,s=e?"ready":"off",r!==null&&(a=z({warmMs:r,busy:p,unload:()=>b()}),e&&a.arm())}function K(e,t){let r=0,n=0,i=0;for(let o=0;o<e.length;o++)r+=e[o]*t[o],n+=e[o]*e[o],i+=t[o]*t[o];const l=Math.sqrt(n)*Math.sqrt(i);return l?r/l:0}class ft{constructor({threshold:t=v(),maxSpeakers:r=12}={}){this.threshold=t,this.maxSpeakers=r,this.centroids=[]}assign(t,{pinnedLabel:r=null,weak:n=!1,thin:i=!1}={}){if(!t)return null;if(r)return this._merge(this._find(r)||this._create(r),t);let l=null,o=-1;const d={};for(const _ of this.centroids){const x=K(t,_.vec);d[_.label]=Math.round(x*1e3)/1e3,x>o&&(o=x,l=_)}return n&&l?{...this._merge(l,t,{update:!1}),scores:d,weak:!0}:l&&o>=this.threshold?{...this._merge(l,t),scores:d}:this.centroids.length>=this.maxSpeakers&&l?{...this._merge(l,t),scores:d}:i&&l?{...this._merge(l,t,{update:!1}),scores:d,thin:!0}:{...this._merge(this._create(`Speaker ${this.centroids.length+1}`),t),scores:d,...n?{weak:!0}:{}}}_find(t){return this.centroids.find(r=>r.label===t)||null}_create(t){const r={id:this.centroids.length+1,label:t,vec:null,n:0};return this.centroids.push(r),r}_merge(t,r,{update:n=!0}={}){if(!t.vec)t.vec=Float32Array.from(r),t.n=1;else if(n){for(let i=0;i<t.vec.length;i++)t.vec[i]=(t.vec[i]*t.n+r[i])/(t.n+1);t.n+=1}return{id:t.id,label:t.label}}}export{Q as DIARIZE_MODEL,ft as Diarizer,at as _reset,ut as _setForTest,V as activeModel,v as activeThreshold,it as download,st as embed,tt as health,ot as init,$ as isReady,j as modelOnDisk,Y as progress,nt as release,rt as retain,lt as setModel,X as state,b as unload,et as warmPending};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o="onnx-community/wespeaker-voxceleb-resnet34-LM",t=[{id:"onnx-community/wespeaker-voxceleb-resnet34-LM",label:"WeSpeaker ResNet34 (recommended)",lang:"any",recommended:!0,approxMB:7,dim:256,threshold:.6,note:"Tells voices apart for meeting transcription (who said what). Small, fast, and the most accurate of the two."},{id:"Xenova/wavlm-base-plus-sv",label:"WavLM Base+ SV (previous default)",lang:"any",approxMB:102,dim:512,threshold:.75,note:"The earlier speaker model. Larger and slower, and it merges similar voices far more often — kept so an existing install can switch back."}];function r(e){return t.find(n=>n.id===e)||null}function a(e){return!!r(e)}function i(e){return(r(e)||r(o)).threshold}function s(e){return r(e)?.approxMB??null}export{o as DEFAULT_DIARIZE_MODEL,t as DIARIZE_MODEL_CATALOG,s as diarizeApproxMB,r as diarizeModelEntry,i as diarizeThreshold,a as isKnownDiarizeModel};
|
package/src/server.js
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
import{createServer as
|
|
2
|
-
data: ${
|
|
1
|
+
import{createServer as Xt}from"node:http";import{loadConfig as lt}from"./config.js";import{startEntitlementRefresh as qt,maybeRevalidate as eo}from"./entitlement-refresh.js";import{redactSegments as Ae,segment as Le}from"./redact.js";import{pipeRestoredStream as to,pipeRestoredOpenAIStream as oo,makeTokenRestorer as dt,restoreDeep as ro}from"./stream.js";import{restoreText as no,gatedDictionary as so,narrowSpecs as ao,makeToolHarness as io,placeholderToolNote as lo,placeholderNote as co,assertEndpointUrl as uo,capRunOptions as mo,isPaired as po}from"@chatpanel/pii";import{ensureGatewayToken as Je,currentGatewayToken as ho,isAdminAuthorized as U,callerTrustOf as Ne,setPinnedExtensionIds as yo,issuePairingCode as fo,claimPairingCode as go}from"./gateway-token.js";import{installEgressLedger as wo,egressAudit as bo}from"./egress.js";import{initPolicy as ko,activePolicy as vo,applyPolicyToConfig as ct,managedSummary as Te,PolicyLoadError as So}from"./policy.js";import{routeAllowed as ut,agentAllowed as To,egressAllowed as xo}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as xe}from"./bridge.js";import{secureFetch as Me}from"./secure-fetch.js";import{streamBridgeChat as mt,readBridgeToken as ge,openBridgeChat as Oo}from"./bridge.js";import{createRelaySession as _o,getRelaySession as pt,endRelaySession as Oe,pumpBridgeStream as Eo,deliverToolResult as $o,toolsToSpecs as Po,wantsApprovals as Ao,parseToolCallId as ht,touchRelaySession as Ge}from"./toolrelay.js";import{shaperFor as Ue}from"./shape.js";import{startNer as No,ensureNer as Be,unionForThisMachine as Mo,skippedCompanions as Bo}from"./ner.js";import{recommendDetector as yt}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Do}from"./log.js";import{saveBackupSecret as Co,clearBackupSecret as Ro,loadBackupSecret as He,hasBackupSecret as ft}from"./history-store.js";import{createMemoryStore as jo}from"./memory-store.js";import{createPrefsStore as Io}from"./prefs-store.js";import{createTeamStore as zo,loadOrCreateKey as Ve}from"./team-store.js";import{createScorecardStore as Lo}from"./scorecard-store.js";import{createEngineLedgerStore as Jo}from"./engine-ledger-store.js";import{createProjectStore as Go}from"./project-store.js";import{applicationsFor as Uo,recruitPass as Ho}from"./recruiting.js";import{ensureBridge as Vo}from"./bridge-supervisor.js";import{checkForUpdate as Fo,updateStatus as Wo,startUpdate as Ko,updateJob as Qo}from"./update.js";import{createHistoryStore as Yo}from"./sqlite-store.js";import{createEventStore as Zo}from"./event-store.js";import{ingestCloudEvents as Xo,cursorOf as gt}from"./event-sync.js";import{eventStats as qo,projectYear as er}from"./event-stats.js";import{toCloudEvent as Fe}from"./cloudevents.js";import{fusionsDocument as tr,resolveFusionModel as or}from"./fusions.js";import{ingestBackups as We}from"./backup-ingest.js";import{toSearchRecord as rr}from"@chatpanel/events/library.js";import{deriveBackupKey as nr,openRecord as sr,keyCache as ar,nodeCodec as ir}from"@chatpanel/events/backup-envelope.js";import lr from"node:zlib";import*as A from"./ner-engine.js";import wt from"node:os";import{capabilitiesDocument as dr,handleDetect as cr}from"./capabilities.js";import{createExtractService as ur}from"./extract/service.js";import{workerSandbox as mr,disposeWorkerSandbox as pr}from"./worker-sandbox.js";import{createRuntime as hr}from"./runtime.js";import{createCapabilityProxy as yr}from"./capability-proxy.js";import{handleExtract as fr}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as gr}from"./extract-capability.js";import{createReader as wr}from"./retrieval/read.js";import{createSearcher as br,toJinaSearch as kr,SEARCH_DEFAULTS as vr}from"./retrieval/search.js";import{createSearxng as Sr}from"./retrieval/search-searxng.js";import{toJinaText as Tr}from"./read-document.js";import*as N from"./stt-engine.js";import*as P from"./diarize-engine.js";import{DIARIZE_MODEL_CATALOG as xr,DEFAULT_DIARIZE_MODEL as Or,isKnownDiarizeModel as bt}from"./diarize-models.js";import{providerOf as kt}from"./providers.js";import{createRemoteTranscriber as vt}from"./stt-remote.js";import{parseMultipart as _r,decodeAudioFile as Er}from"./audio-file.js";import{MODEL_CATALOG as St,isKnownModel as Tt,isValidCustomModelId as xt,recommendFor as $r}from"./models.js";import{STT_MODEL_CATALOG as Pr,isKnownSttModel as Ar,isValidCustomSttId as Nr,DEFAULT_STT_MODEL as De,STT_DTYPES as Mr,isValidDtype as Br}from"./stt-models.js";import*as $ from"./tts-engine.js";import{TTS_MODEL_CATALOG as Ot,TTS_VOICES as Dr,isKnownTtsModel as Cr,isValidCustomTtsId as Rr,isKnownVoice as _t,isValidVoiceId as Et,DEFAULT_TTS_MODEL as $t,DEFAULT_TTS_VOICE as me,TTS_DTYPES as jr,isValidTtsDtype as Ir,MAX_TTS_CHARS as Pt,ttsModelHasCustomVoices as zr,resolveDefaultModel as At,POCKET_VOICES as Lr,DEFAULT_POCKET_VOICE as Ce,isPocketVoice as Re,ttsModelEngine as je}from"./tts-models.js";import{ttsDestination as Jr,synthesizeRemote as Gr,isValidRemoteVoice as Ur}from"./tts-remote.js";import{rawOrtAvailable as Ke}from"./ort.js";import*as Y from"./tts-voices.js";import{resolveTtsVoice as Hr}from"./tts-voice-resolve.js";import{resolvePro as ye,checkQuota as Vr,consume as Fr,usage as Wr}from"./freegate.js";import{publicConfig as Nt,applyConfigPatch as Kr,registryChildEnv as Qr,applyNerModelSelection as Mt,persistConfig as ae,configPath as re,bridgeAgentOptions as Bt,PERMISSION_MODES as Yr,sandboxEnvFor as Zr}from"./configstore.js";import Dt from"node:path";import{resolveDestination as Ct,aggregateModelsAsync as Xr,listDestinations as qr}from"./router.js";import{makeAccessEvent as Rt}from"./observability.js";import{createPersistentAccessLog as en}from"./access-log-store.js";import{planQueries as tn,multiSearch as on}from"./rrf.js";import*as Qe from"./openai.js";import*as jt from"./responses.js";import*as Ye from"./anthropic.js";import{closeAndExit as rn}from"./shutdown.js";import{VERSION as ee}from"./version.js";import{VERSION as Ws}from"./version.js";const M=await Yo(),ie=new Set;function Ie({ids:t=[]}={}){const d=M.lossless;if(!d||!ie.size)return;const c=JSON.stringify({newest:d.newest,size:d.size,ids:t.slice(0,50),at:Date.now()});for(const m of ie)try{m.write(`event: records
|
|
2
|
+
data: ${c}
|
|
3
3
|
|
|
4
|
-
`)}catch{
|
|
4
|
+
`)}catch{ie.delete(m)}}setInterval(()=>{for(const t of ie)try{t.write(`: ping
|
|
5
5
|
|
|
6
|
-
`)}catch{
|
|
7
|
-
data: ${JSON.stringify(
|
|
6
|
+
`)}catch{ie.delete(t)}},25e3).unref?.();const H=await Zo(),fe=new Set;H?.watch(t=>{if(!fe.size)return;const d=`event: cloudevent
|
|
7
|
+
data: ${JSON.stringify(Fe(t))}
|
|
8
8
|
|
|
9
|
-
`;for(const
|
|
9
|
+
`;for(const c of fe)try{c.write(d)}catch{fe.delete(c)}}),setInterval(()=>{for(const t of fe)try{t.write(`: ping
|
|
10
10
|
|
|
11
|
-
`)}catch{
|
|
12
|
-
data: ${
|
|
11
|
+
`)}catch{fe.delete(t)}},25e3).unref?.();const te=await jo(),oe=Io(),we=Lo({key:Ve()}),be=Jo({key:Ve()}),Z=Go({key:Ve()}),V=zo({scorecards:we,engines:be}),Ze=new Set,It=(t,d)=>{for(const m of Ze)try{m({applied:t,by:d,revision:oe.revision})}catch{}const c=JSON.stringify({revision:oe.revision,applied:(t||[]).slice(0,50),by:d||"",at:Date.now()});for(const m of ie)try{m.write(`event: prefs
|
|
12
|
+
data: ${c}
|
|
13
13
|
|
|
14
|
-
`)}catch{
|
|
14
|
+
`)}catch{ie.delete(m)}},Xe=en(),zt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),nn=16,sn=/^mcp[_-]/i,Lt=t=>t&&t.function&&t.function.name||t&&t.name||"",an=t=>t&&t.function&&t.function.description||t&&t.description||"";function Jt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(d=>typeof d=="string"?d:d&&(d.text||d.content)||"").join(" "):""}function ln(t,d){if(!t)return"";if(d==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(y=>Jt(y&&(y.content??y))).join(" "):""}const c=Array.isArray(t.messages)?t.messages:[];for(let m=c.length-1;m>=0;m--)if(c[m]&&c[m].role==="user")return Jt(c[m].content);return""}const Gt=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function Ut(t){if(!t)return!1;const d=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return d==="localhost"||d==="127.0.0.1"||d==="::1"}function dn(t,d){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(d.allowedOrigins)&&d.allowedOrigins.includes(t)}function cn(t,d){t.setHeader("Access-Control-Allow-Origin",d||"*"),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 Ht=Date.now();function un(t){if(!t)return"";const d={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(c=>`${d[c]||c} ${t[c]}ms`).join(" · ")}function mn(t){const d=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return d?{kind:d[1],id:d[2],...d[3]?{model:d[3]}:{}}:null}function pn(t){const d=performance.now(),c={};let m=!1;const y=(g,E)=>{c[g]=Math.round(E*10)/10};return{meta:{},timings:c,mark:y,lap(g,E){y(g,performance.now()-E)},clock(){return performance.now()},commit(){if(m)return;m=!0,y("total",performance.now()-d);const g={...this.meta,timings:c};setImmediate(()=>{t(g),console.log(`[gateway] model=${g.model||"-"} → ${g.dest?`${g.dest}(${g.type})`:"none"} · ${g.redaction==="off"?"redaction OFF (client request)":`redacted ${g.redacted||0}`}${g.sanitized?` · scrubbed ${g.sanitized} hidden`:""}${g.narrowed?` · narrowed -${g.narrowed}`:""} · ${un(c)}`)})}}}function Vt(t,d){if(!t||!t.byToken||d!=="types"&&d!=="values")return;const c=[];for(const[m,y]of t.byToken){const g=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),E=g?g[1]:"PII",v=m.replace(/^\[\[|\]\]$/g,"");c.push(d==="values"?{token:v,type:E,value:y}:{token:v,type:E})}return c}function hn(t,d,c){return Ye.matches(t)||"anthropic-version"in d?{kind:"anthropic",adapter:Ye,redactable:Ye.matches(t),base:c.upstreams?.anthropic?.baseUrl}:jt.matches(t)?{kind:"responses",adapter:jt,redactable:!0,base:c.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Qe,redactable:Qe.matches(t),base:c.upstreams?.openai?.baseUrl}}function qe(t,d){const c=String(t||"");if(zt.has(c))return{agent:c,agentModel:""};const m=c.indexOf("/");if(m>0){const y=c.slice(0,m);if(zt.has(y))return{agent:y,agentModel:c.slice(m+1)}}return{agent:d.bridge.agent,agentModel:""}}function Ft(t,d){return qe(t,d).agent}function yn(t,d){if(d!=="openai"||!t)return!1;const c=Qe.extractLatestToolResult(t);if(!c)return!1;const m=ht(c.tool_call_id);return!!(m&&pt(m.gwId))}function fn(t,d){try{const c=new URL(t),m=c.hostname.replace(/^\[|\]$/g,""),y=m==="127.0.0.1"||m==="localhost"||m==="::1",g=c.port||(c.protocol==="https:"?"443":"80");return y&&String(g)===String(d.port)}catch{return!1}}async function O(t,d){const c=[];let m=0;for await(const y of t){if(m+=y.length,d&&m>d){const g=new Error("payload too large");throw g.code=413,g}c.push(y)}return Buffer.concat(c)}function s(t,d,c){t.writeHead(d,{"content-type":"application/json"}),t.end(JSON.stringify(c))}function Wt(t){const d=t.redaction?.detection?.url;return!d||t.redaction?.detection?.backend==="off"?null:d}function et(t){const d=t?.redaction?.detection,c=t?.redaction?.tier==="full"?"full":"basic";if(d&&d.backend&&d.backend!=="off")return{source:"external",backend:d.backend,state:"external",model:d.model||null,ready:!0,tier:c,coverage:c==="full"?"names":"patterns"};const m=A.health(),y=m.ok&&c==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:A.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:y,tier:c,coverage:y?"names":"patterns"}}async function Kt(t){if(A.state()!=="off"){const c=A.health();return{configured:c.configured,ok:c.ok,state:c.state,model:c.model,error:c.error||null,url:c.configured?`http://${t.host}:${t.port}/ner`:null,stats:c.stats,companions:c.companions}}const d=Wt(t);if(!d)return{configured:!1,ok:!1,url:null,model:null};try{const c=await Me(d.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!c.ok)return{configured:!0,ok:!1,url:d,model:null};const m=await c.json().catch(()=>({}));return{configured:!0,ok:!0,url:d,model:m.model||null}}catch{return{configured:!0,ok:!1,url:d,model:null}}}function gn(t,d){const c={};for(const[m,y]of Object.entries(t)){const g=m.toLowerCase();g.startsWith("x-chatpanel-")||Gt.has(g)||(c[m]=y)}c["accept-encoding"]="identity";try{c.host=new URL(d).host}catch{}return c}async function Qt(t,d,c,m){const y=dt(d.vault),g=tt();t.on("close",()=>{t.writableFinished||Oe(d.id)});const E=m?m.clock():0;let v=E,x=!0;const C=()=>{m&&x&&(m.lap("upstream",E),v=m.clock(),x=!1)};await Eo(d,{onText:b=>{C(),Ge(d.id);const j=y.push(b);j&&t.write(c.sseDelta(j))},onToolRequest:({name:b,restoredArgs:j,toolId:I})=>{C(),Ge(d.id);const L=y.flush();L&&t.write(c.sseDelta(L)),t.write(c.sseToolCalls([{id:I,name:b,arguments:JSON.stringify(j)}])),t.write(c.sseToolFinish(g.value)),m&&m.lap("stream",v),t.end(),m?.commit()},onDone:()=>{const b=y.flush();b&&t.write(c.sseDelta(b)),t.write(c.sseTail(g.value)),m&&m.lap("stream",v),t.end(),Oe(d.id),m?.commit()},onError:b=>{t.write(`data: ${JSON.stringify({error:{message:b.message,type:"bridge_error"}})}
|
|
15
15
|
|
|
16
|
-
`),t.end(),
|
|
16
|
+
`),t.end(),Oe(d.id),m?.commit()},onUsage:b=>g.add(b)})}async function wn(t,d,{kind:c,adapter:m,agent:y,run:g=null},E,v,x,C,b,j=null,I=null){const{messages:L,system:le}=m.toTurn(E),{agentModel:ne}=qe(E?.model,x),n=Bt(x,{...ne?{model:ne}:{},...g||{}}),o=ge(x.bridge.token),p=Ue(c,E?.model||y),i={tier:x.redaction.tier==="full"?"full":"basic",dictionary:so(x.redaction,C),entities:[]},R=await xe(x),X=_o({vault:v,redactOpts:i,bridgeUrl:R,token:o,harness:j});let q;try{q=await Oo({bridgeUrl:R,agent:y,token:o,messages:L,system:le,specs:Po(b),options:n,signal:void 0,approvals:Ao(b)})}catch(S){return Oe(X.id),I?.commit(),s(d,502,{error:{message:`bridge: ${S.message}`,type:"bridge_error"}})}return X.reader=q.body.getReader(),d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(p.sseHead()),Qt(d,X,p,I)}async function bn(t,d,c,m,y=null){Ge(d.id),d.rounds=(d.rounds||0)+1;try{const E=y?y.clock():0;await $o(d,c),y&&y.lap("redact",E)}catch(E){return Oe(d.id),y?.commit(),s(t,502,{error:{message:`tool-result: ${E.message}`,type:"bridge_error"}})}const g=Ue("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(g.sseHead()),Qt(t,d,g,y)}function tt(){let t=!1;const d={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(c){t=!0;for(const m of Object.keys(d))d[m]+=Math.max(0,Number(c?.[m])||0)},get value(){return t?d:null}}}async function kn(t,d,{kind:c,adapter:m,redactable:y,pathname:g,agentOverride:E,harness:v,trace:x,run:C=null},b,j,I,L){if(!y)return x?.commit(),s(d,404,{error:`endpoint ${g} not supported by the bridge backend`});if(c==="openai"){const W=m.extractLatestToolResult(b);if(W){const F=ht(W.tool_call_id),z=F&&pt(F.gwId);if(z)return bn(d,z,W.content,b?.model,x)}const K=m.extractTools(b);if(K.length&&b?.stream===!0)return wn(t,d,{kind:c,adapter:m,agent:E||Ft(b?.model,I),run:C},b,j,I,L,K,v,x)}const{messages:le,system:ne}=m.toTurn(b),n=E||Ft(b?.model,I),o=b?.stream===!0,p=Ue(c,b?.model||n),i=ge(I.bridge.token),R=new AbortController;d.on("close",()=>{d.writableFinished||R.abort()});const{agentModel:X}=qe(b?.model,I),q={bridgeUrl:await xe(I),agent:n,token:i,messages:le,system:ne,signal:R.signal,options:Bt(I,{...X?{model:X}:{},...C||{}})};if(!o)try{let W="";const K=tt(),F=x?x.clock():0;await mt(q,ce=>{W+=ce},null,ce=>K.add(ce)),x&&x.lap("upstream",F);const z=x?x.clock():0,Ee=p.full(no(W,j),K.value);return x&&x.lap("restore",z),d.writeHead(200,{"content-type":p.contentType}),d.end(Ee),x?.commit()}catch(W){return x?.commit(),s(d,502,{error:{message:`bridge backend failed: ${W.message}`,type:"bridge_error"}})}d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(p.sseHead());const S=dt(j),de=x?x.clock():0;let ve=de;const Se=tt();try{let W=!0;await mt(q,F=>{x&&W&&(x.lap("upstream",de),ve=x.clock(),W=!1);const z=S.push(F);z&&d.write(p.sseDelta(z))},p.sseActivity?F=>{try{d.write(p.sseActivity(ro(F,j)))}catch{}}:null,F=>Se.add(F));const K=S.flush();K&&d.write(p.sseDelta(K)),d.write(p.sseTail(Se.value))}catch(W){d.write(`data: ${JSON.stringify({error:{message:W.message,type:"bridge_error"}})}
|
|
17
17
|
|
|
18
|
-
`)}x&&x.lap("stream",ve),c.end(),x?.commit()}function hn(t,c,d=""){const m=String(t||"").replace(/\/+$/,""),f=String(c||"").split("/")[1];return f&&m.endsWith(`/${f}`)?m.slice(0,-(f.length+1))+c+d:m+c+d}const yn=9e4;function fn(t,c,d){if(c===d)return t;const m=c/d,f=new Float32Array(Math.floor(t.length/m));for(let g=0;g<f.length;g++){const $=g*m,S=Math.floor($),x=Math.min(t.length-1,S+1),D=$-S;f[g]=t[S]*(1-D)+t[x]*D}return f}const gn=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];function Xe(t,c){const d=new URLSearchParams;for(const g of t.searchParams.getAll("dir"))g&&d.append("dir",g);const m=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();m&&d.set("workdir",m);const f=d.toString();return f?`?${f}`:""}async function wn(t,c,{adapter:d,kind:m,pathname:f,search:g,base:$,destKey:S,destProtocol:x,harness:D,trace:_},F,R){let L;const ie=_?_.clock():0;try{const p=dn(t.headers,$);S&&(x==="anthropic"?(p["x-api-key"]=S,delete p.authorization):p.authorization=`Bearer ${S}`);const l=so(hn($,f,g)).toString();L=await fetch(l,{method:t.method,headers:p,body:["GET","HEAD"].includes(t.method)?void 0:F})}catch(p){return _?.commit(),s(c,502,{error:`upstream fetch failed: ${p.message}`})}const re=L.headers.get("content-type")||"",n={};if(L.headers.forEach((p,l)=>{Rt.has(l.toLowerCase())||(n[l]=p)}),re.includes("text/event-stream")&&L.body){_&&_.lap("upstream",ie);const p=_?_.clock():0;c.writeHead(L.status,n);const l=m==="openai"?Yt(L.body,c,R,D):Zt(L.body,c,R);return Promise.resolve(l).finally(()=>{_&&_.lap("stream",p),_?.commit()})}const o=Buffer.from(await L.arrayBuffer());if(_&&_.lap("upstream",ie),R&&re.includes("application/json"))try{const p=_?_.clock():0,l=d.restoreResponse(JSON.parse(o.toString("utf8")),R,D);return _&&_.lap("restore",p),c.writeHead(L.status,{...n,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(l),"utf8")),_?.commit()}catch{}c.writeHead(L.status,n),c.end(o),_?.commit()}function bn(t=nt()){let c=null;const d=()=>{if(!c){const n=t.read||{};c=pr({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return c};let m=null;const f=()=>(m||(m=ar({wrap:(n,o,p,l)=>ir().wrap(n,o,p,l),onLog:n=>console.warn(`[extract worker] ${n}`)})),m);let g={at:0,fn:()=>"unknown"},$=null;async function S(){if(Date.now()-g.at<1e4)return g.fn;let n=new Map;try{const l=await D().health();for(const[C,Z]of Object.entries(l)){const q=(t.destinations||[]).filter(v=>v?.service===C).flatMap(v=>[v.id,...v.models||[]]);for(const v of[C,...q])n.set(v,Z)}}catch{n=new Map}const o=l=>n.get(l)||"unknown",p=new Map((t.destinations||[]).filter(l=>l?.service).map(l=>[l.id,l.service]));return o.window=l=>{try{return D().contextWindow(p.get(l)||l)}catch{return null}},o.card=l=>{try{return D().modelCard(p.get(l)||l)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),g={at:Date.now(),fn:o},g.fn}let x=null;const D=()=>(x||(x=cr({cfg:t,bridgeHealth:async()=>{const n=await ye(t);if(!n)return null;const o=de(t.bridge?.token),p=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return p.ok?p.json():null},persist:()=>{try{me(t,se())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Et.join(Et.dirname(se()),"runtime"),workers:()=>{const n=m?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),x),_=dr({cfg:t});let F=null;const R=()=>{if(!F){const n=t.search||{},o=n.searxng?.url?gr({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;F=hr({reader:d(),searxng:o,defaultProvider:n.provider||"auto",redact:async p=>{let l=p;return await $e([Re(()=>l,C=>{l=C})],{...t.redaction,tier:"basic"},{isPro:!0}),l}})}return F};co(t.allowedExtensionIds||[]);const L=[],ie=n=>{L.push(n),L.length>50&&L.shift()},re=Wt(async(n,o)=>{const p=new URL(n.url,"http://127.0.0.1"),l=p.pathname;if(!It(n.headers.host))return s(o,403,{error:"loopback only"});if(!tn(n.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(n.headers.origin&&on(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(l==="/admin/token"&&n.method==="POST")return X(n)?s(o,200,{token:Ie()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(l==="/pair/code"&&n.method==="POST"){if(!X(n))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=uo();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(l==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=mo(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Pe(n)} caller`),s(o,403,{error:r.reason});console.log(`[gateway] paired a ${Pe(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const a=de(t.bridge?.token);return s(o,200,{ok:!0,token:lo()||Ie(),...a?{bridgeToken:a}:{}})}if(l==="/whoami"&&n.method==="POST"){const e=Pe(n);return s(o,200,{ok:!0,trust:e,paired:io(e),version:ee})}if(l==="/audit"&&n.method==="GET")return X(n)?s(o,200,ho(t,{version:ee,startedAt:Lt,managed:ke()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((l==="/config"||l==="/logs"||l==="/update"&&n.method!=="GET")&&!X(n))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(l==="/update"&&n.method==="GET"){const e=await zo(ee,{force:p.searchParams.get("force")==="1"}).catch(r=>({current:ee,updateAvailable:!1,error:String(r?.message||r)}));return s(o,200,{ok:!0,update:e,job:Vo()})}if(l==="/update"&&n.method==="POST"){const e=Ho(ee);return s(o,e.already?409:202,{ok:!0,job:e})}if((l==="/v1/history/key"||l==="/v1/history/ingest-backup")&&n.method==="POST"&&!X(n))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(l==="/v1/history/records"&&n.method==="PUT"&&!X(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/history/ingest"||l==="/v1/history/clear")&&n.method==="POST"&&!X(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/memory/remember"||l==="/v1/memory/forget"||l==="/v1/memory/sync"||l==="/v1/memory/clear")&&n.method==="POST"&&!X(n))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/prefs"||l.startsWith("/v1/prefs/")||l.startsWith("/v1/teams")||l.startsWith("/v1/agents")||l.startsWith("/v1/projects"))&&!X(n))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/events"||l.startsWith("/v1/events/"))&&!X(n))return s(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(l.startsWith("/v1/observability")&&!X(n))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&l==="/health"){const e=A.health(),r=P.health();return s(o,200,{ok:!0,version:ee,backend:t.backend,tier:t.redaction.tier,pairing:!0,...ke()?{managed:ke()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...Te?{bridge:Te.status()}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Ne,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||Tt,voice:t.tts?.voice||ue,runtime:r.runtime,dtype:r.dtype},events:z?{count:z.count(),hosts:z.hosts().length}:null})}if(l==="/status"&&n.method==="GET"){Qt(t);const e=await fe(t.pro?.entitlementToken),r=await Ht(t);return s(o,200,{ok:!0,version:ee,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...ke()?{managed:ke()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:r.configured,ready:r.ok,model:r.model,url:r.url},detector:Ye(t),pro:{unlocked:e},usage:Jr(t),uptimeSeconds:Math.floor((Date.now()-Lt)/1e3),update:Go(ee)})}if(l==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=N.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:r})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(l==="/v1/prefs"&&n.method==="GET"){const e=String(p.searchParams.get("section")||"");return p.searchParams.get("stamps")?s(o,200,{ok:!0,revision:oe.revision,stamps:oe.stamps()}):s(o,200,{ok:!0,revision:oe.revision,sections:oe.get(e)})}if(l==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=oe.put(e.sections||{},{by:e.by||""});return r.applied.length&&Dt(r.applied,e.by||""),s(o,200,{ok:!0,...r})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(l==="/v1/prefs"&&n.method==="DELETE"){const e=String(p.searchParams.get("section")||""),r=e?oe.remove(e):!1;return r&&Dt([e],""),s(o,200,{ok:!0,removed:r})}if(l==="/v1/prefs/events"&&n.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)}
|
|
18
|
+
`)}x&&x.lap("stream",ve),d.end(),x?.commit()}function vn(t,d,c=""){const m=String(t||"").replace(/\/+$/,""),y=String(d||"").split("/")[1];return y&&m.endsWith(`/${y}`)?m.slice(0,-(y.length+1))+d+c:m+d+c}const Sn=9e4;function Tn(t,d,c){if(d===c)return t;const m=d/c,y=new Float32Array(Math.floor(t.length/m));for(let g=0;g<y.length;g++){const E=g*m,v=Math.floor(E),x=Math.min(t.length-1,v+1),C=E-v;y[g]=t[v]*(1-C)+t[x]*C}return y}const xn=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/redact","/config","/logs","/status","/admin"];function ot(t,{installing:d=!1}={}){return t.stt?.diarize===!1?"off":d&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function se(t,d,c,m,{method:y="GET",timeoutMs:g=8e3,pick:E=v=>v}={}){const v=await xe(c);if(!v)return s(d,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const x=ge(c.bridge?.token),C=y!=="GET"&&y!=="DELETE";try{const b=C?(await O(t,c.maxBodyBytes)).toString("utf8"):"",j=await fetch(`${v}${m}`,{method:y,headers:{Accept:"application/json",...C?{"content-type":"application/json"}:{},...x?{Authorization:`Bearer ${x}`}:{}},...C?{body:b||"{}"}:{},signal:AbortSignal.timeout(g)}),I=await j.json().catch(()=>({}));return j.ok?s(d,200,E(I)):s(d,j.status,{error:{message:I?.error||`bridge ${j.status}`,type:"bridge_error"}})}catch(b){return s(d,502,{error:{message:`bridge unreachable: ${b.message}`,type:"bridge_unreachable"}})}}function rt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function ke(t,d){const c=new URLSearchParams;for(const g of t.searchParams.getAll("dir"))g&&c.append("dir",g);const m=t.searchParams.get("workdir")||String(d?.bridge?.workingDir||"").trim();m&&c.set("workdir",m);const y=c.toString();return y?`?${y}`:""}async function On(t,d,{adapter:c,kind:m,pathname:y,search:g,base:E,destKey:v,destProtocol:x,harness:C,trace:b},j,I){let L;const le=b?b.clock():0;try{const p=gn(t.headers,E);v&&(x==="anthropic"?(p["x-api-key"]=v,delete p.authorization):p.authorization=`Bearer ${v}`);const i=uo(vn(E,y,g)).toString();L=await fetch(i,{method:t.method,headers:p,body:["GET","HEAD"].includes(t.method)?void 0:j})}catch(p){return b?.commit(),s(d,502,{error:`upstream fetch failed: ${p.message}`})}const ne=L.headers.get("content-type")||"",n={};if(L.headers.forEach((p,i)=>{Gt.has(i.toLowerCase())||(n[i]=p)}),ne.includes("text/event-stream")&&L.body){b&&b.lap("upstream",le);const p=b?b.clock():0;d.writeHead(L.status,n);const i=m==="openai"?oo(L.body,d,I,C):to(L.body,d,I);return Promise.resolve(i).finally(()=>{b&&b.lap("stream",p),b?.commit()})}const o=Buffer.from(await L.arrayBuffer());if(b&&b.lap("upstream",le),I&&ne.includes("application/json"))try{const p=b?b.clock():0,i=c.restoreResponse(JSON.parse(o.toString("utf8")),I,C);return b&&b.lap("restore",p),d.writeHead(L.status,{...n,"content-type":"application/json"}),d.end(Buffer.from(JSON.stringify(i),"utf8")),b?.commit()}catch{}d.writeHead(L.status,n),d.end(o),b?.commit()}function _n(t=lt()){t.stt?.diarizeModel&&t.stt.diarizeModel!==P.activeModel()&&(bt(t.stt.diarizeModel)?P.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${Or}`));let d=null;const c=()=>{if(!d){const n=t.read||{};d=wr({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return d};let m=null;const y=()=>(m||(m=ur({wrap:(n,o,p,i)=>mr().wrap(n,o,p,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),m);let g={at:0,fn:()=>"unknown"},E=null;async function v(){if(Date.now()-g.at<1e4)return g.fn;let n=new Map;try{const i=await C().health();for(const[R,X]of Object.entries(i)){const q=(t.destinations||[]).filter(S=>S?.service===R).flatMap(S=>[S.id,...S.models||[]]);for(const S of[R,...q])n.set(S,X)}}catch{n=new Map}const o=i=>n.get(i)||"unknown",p=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return C().contextWindow(p.get(i)||i)}catch{return null}},o.card=i=>{try{return C().modelCard(p.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),g={at:Date.now(),fn:o},g.fn}let x=null;const C=()=>(x||(x=hr({cfg:t,bridgeHealth:async()=>{const n=await xe(t);if(!n)return null;const o=ge(t.bridge?.token),p=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return p.ok?p.json():null},persist:()=>{try{ae(t,re())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Dt.join(Dt.dirname(re()),"runtime"),workers:()=>{const n=m?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),x),b=yr({cfg:t});let j=null;const I=()=>{if(!j){const n=t.search||{},o=n.searxng?.url?Sr({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;j=br({reader:c(),searxng:o,defaultProvider:n.provider||"auto",redact:async p=>{let i=p;return await Ae([Le(()=>i,R=>{i=R})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return j};yo(t.allowedExtensionIds||[]);const L=[],le=n=>{L.push(n),L.length>50&&L.shift()},ne=Xt(async(n,o)=>{const p=new URL(n.url,"http://127.0.0.1"),i=p.pathname;if(!Ut(n.headers.host))return s(o,403,{error:"loopback only"});if(!dn(n.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(n.headers.origin&&cn(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return U(n)?s(o,200,{token:Je()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!U(n))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=fo();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(i==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=go(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Ne(n)} caller`),s(o,403,{error:r.reason});console.log(`[gateway] paired a ${Ne(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const a=ge(t.bridge?.token);return s(o,200,{ok:!0,token:ho()||Je(),...a?{bridgeToken:a}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Ne(n);return s(o,200,{ok:!0,trust:e,paired:po(e),version:ee})}if(i==="/audit"&&n.method==="GET")return U(n)?s(o,200,bo(t,{version:ee,startedAt:Ht,managed:Te()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!U(n))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await Fo(ee,{force:p.searchParams.get("force")==="1"}).catch(r=>({current:ee,updateAvailable:!1,error:String(r?.message||r)}));return s(o,200,{ok:!0,update:e,job:Qo()})}if(i==="/update"&&n.method==="POST"){const e=Ko(ee);return s(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!U(n))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!U(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!U(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!U(n))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!U(n))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!U(n))return s(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!U(n))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/health"){const e=N.health(),r=$.health();return s(o,200,{ok:!0,version:ee,backend:t.backend,tier:t.redaction.tier,pairing:!0,...Te()?{managed:Te()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},..._e?{bridge:_e.status()}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||De,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||$t,voice:t.tts?.voice||me,runtime:r.runtime,dtype:r.dtype},events:H?{count:H.count(),hosts:H.hosts().length}:null})}if(i==="/status"&&n.method==="GET"){eo(t);const e=await ye(t.pro?.entitlementToken),r=await Kt(t);return s(o,200,{ok:!0,version:ee,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Te()?{managed:Te()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:r.configured,ready:r.ok,model:r.model,url:r.url},detector:et(t),pro:{unlocked:e},usage:Wr(t),uptimeSeconds:Math.floor((Date.now()-Ht)/1e3),update:Wo(ee)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=M.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:r})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&n.method==="GET"){const e=String(p.searchParams.get("section")||"");return p.searchParams.get("stamps")?s(o,200,{ok:!0,revision:oe.revision,stamps:oe.stamps()}):s(o,200,{ok:!0,revision:oe.revision,sections:oe.get(e)})}if(i==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=oe.put(e.sections||{},{by:e.by||""});return r.applied.length&&It(r.applied,e.by||""),s(o,200,{ok:!0,...r})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(i==="/v1/prefs"&&n.method==="DELETE"){const e=String(p.searchParams.get("section")||""),r=e?oe.remove(e):!1;return r&&It([e],""),s(o,200,{ok:!0,removed:r})}if(i==="/v1/prefs/events"&&n.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)}
|
|
19
19
|
|
|
20
|
-
`);e({type:"hello",revision:oe.revision,stamps:oe.stamps()});const r=
|
|
20
|
+
`);e({type:"hello",revision:oe.revision,stamps:oe.stamps()});const r=l=>e({type:"changed",...l});Ze.add(r);const a=setInterval(()=>{try{o.write(`: keep-alive
|
|
21
21
|
|
|
22
|
-
`)}catch{}},25e3);o.on("close",()=>{
|
|
22
|
+
`)}catch{}},25e3);o.on("close",()=>{Ze.delete(r),clearInterval(a)});return}if(i==="/v1/projects"&&n.method==="GET")return s(o,200,{ok:!0,projects:Z.list({limit:p.searchParams.get("limit")||50,status:p.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&n.method==="GET")return s(o,200,{ok:!0,jobs:Z.openJobs()});if(i==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:Z.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(i);if(e){const r=e[1],a=e[2]||"",l=e[3]||"",u=e[4]||"",k=()=>s(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(u){const f=Z.get(r);if(!f)return k();const T=f.jobs.find(h=>h.id===l);if(!T)return s(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const w={cfg:t,prefsStore:oe,scorecards:we,engines:be};if(u==="/applications"&&n.method==="GET"){const h=await Uo(T,{...w,reach:p.searchParams.get("reach")||"any",chatModel:p.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:T,...h})}if(u==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(T.status))return s(o,400,{error:{message:`job ${l} is ${T.status}; only an open job is recruited`,type:"project_error"}});try{const h=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},_=String(h.by||"evaluator").slice(0,80),J=await Ho(T,{...w,record:f,reach:h.reach||"any",chatModel:h.chatModel||null,evaluation:h.evaluation||null,text:h.text??null,by:_});let D=null;for(const Q of J.events)Q.type==="job.updated"?D=Z.updateJob(r,l,Q.job,{by:Q.by||_}):D=Z.append(r,[Q]);return s(o,200,{ok:!0,project:D,decision:J.decision,applications:J.applications,evaluation:J.evaluation})}catch(h){return s(o,400,{error:{message:`recruit: ${h.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&n.method==="GET"){const f=Z.get(r,{events:p.searchParams.get("events")==="1"});return f?s(o,200,{ok:!0,project:f}):k()}if(!a&&n.method==="DELETE")return s(o,200,{ok:!0,removed:Z.remove(r)});if(n.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const f=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},T=String(f.by||"person").slice(0,80),w=a==="/events"?Z.append(r,f.events||[]):l?Z.updateJob(r,l,f.patch||f,{by:T}):Z.postJob(r,f.job||f,{by:T});return s(o,200,{ok:!0,project:w})}catch(f){return s(o,f.message.startsWith("no ")?404:400,{error:{message:`project: ${f.message}`,type:"project_error"}})}if(a==="/events"&&n.method==="GET"){if(!Z.get(r))return k();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const f=_=>o.write(`data: ${JSON.stringify(_)}
|
|
23
23
|
|
|
24
|
-
`);let
|
|
24
|
+
`);let T=p.searchParams.has("after")?Number(p.searchParams.get("after")):-1;f({seq:-1,type:"hello",at:Date.now(),payload:{project:Z.get(r),after:T}});const w=Z.watch(r,_=>{_.seq>T&&(T=_.seq,f(_))});for(const _ of Z.eventsSince(r,T))T=_.seq,f(_);const h=setInterval(()=>{try{o.write(`: keep
|
|
25
25
|
|
|
26
|
-
`)}catch{}},25e3);n.on("close",()=>{clearInterval(h),
|
|
26
|
+
`)}catch{}},25e3);n.on("close",()=>{clearInterval(h),w()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return s(o,200,{ok:!0,agents:we.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return s(o,200,{ok:!0,...await we.get(r)});if(n.method==="POST")try{const a=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},l=await we.append({agentId:r,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 be.fromRating(we.chains.get(r)||[],{...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(i==="/v1/capabilities"&&n.method==="GET")return s(o,200,dr(t,{version:ee,reader:d,searcher:j,extract:y(),proxy:b}));if(i==="/v1/fusions"&&n.method==="GET"){const e={active:A.health().model||t.ner?.model||null,companions:A.companions()};let r=null;try{r=await C().status()}catch{r=null}return s(o,200,tr({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET")return s(o,200,await C().status());{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&n.method==="POST"){if(!U(n))return s(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const a=String(r.action||"start"),l=C(),u=e[1]==="engines"?a==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${a}`}:a==="start"?await l.startService(e[2]):a==="stop"?await l.stopService(e[2]):a==="model"?await l.setModel(e[2],r.model):a==="tune"?await l.setTunings(e[2],r.tunings):a==="profile"?await l.setProfile(e[2],r.profile):a==="pull"?await l.pullModel(e[2]):a==="install"?await l.installRunner(e[2]):a==="cancel"?l.cancelJob(e[2]):{ok:!1,error:`unknown action ${a}`};return s(o,u.ok?200:400,u)}}if((i==="/v1/rerank"||i==="/v1/decide")&&n.method==="POST"){const e=i.slice(4);let r;try{r=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const a=await b.call(e,r);return s(o,a.status,a.body)}if(i==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await cr(e,{ensure:()=>Be(t),model:A.health().model});return s(o,r.status,r.body)}catch(r){return s(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await O(n,Math.max(t.maxBodyBytes,Math.ceil(gr*4/3)+1024))).toString("utf8"))}catch{return s(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await fr(e,{service:y()});return s(o,r.status,r.body)}if(i==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await c().read(e);return s(o,r.status,r.body)}if(i==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}const r=await I().search(e);return s(o,r.status,r.body)}if(/^\/v1\/search\/./.test(i)&&n.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const r=p.searchParams.has("read")?Math.max(0,Math.min(10,Number(p.searchParams.get("read"))||0)):vr.aliasRead,a=await I().search({q:e,read:r,limit:Math.max(r,5)});return s(o,a.status,a.status===200?kr(a.body):a.body)}if(/^\/v1\/read\/./.test(i)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),a=/application\/json/i.test(n.headers.accept||""),l=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",u=await c().read({url:r,format:l});return u.status!==200||a?s(o,u.status,u.status===200?{code:200,status:2e4,data:u.body}:u.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":u.body.provider}),o.end(Tr(u.body)))}if(i==="/v1/engines"&&n.method==="GET"){const e=Number(p.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:be.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const a=Number(p.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await be.get(r,{entries:p.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&n.method==="POST")try{const a=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},l=a.engine||mn(r);if(!l)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const u=await be.append({...a,engine:l,kind:a.kind||"call"});return u.key!==r?s(o,400,{error:{message:`model-ledger: entry is for ${u.key}, not ${r}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:u})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/runs"&&n.method==="GET")return s(o,200,{ok:!0,runs:V.list({limit:p.searchParams.get("limit")||50,team:p.searchParams.get("team")||""})});if(i==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:V.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(i);if(e){const r=e[1],a=e[2]||"";if(!a&&n.method==="GET"){const l=V.get(r,{events:p.searchParams.get("events")==="1"});return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!a&&n.method==="DELETE")return V.stop(r),s(o,200,{ok:!0,removed:V.remove(r)});if(a==="/stop"&&n.method==="POST"){const l=V.stop(r);return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(a==="/checkpoint"&&n.method==="GET")try{return s(o,200,{ok:!0,checkpoint:V.checkpoint(r)})}catch(l){return s(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&n.method==="POST")try{const l=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},u=a==="/handoff"?V.handoff(r,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):V.claim(r,{client:l.client});return s(o,200,{ok:!0,run:u})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&n.method==="DELETE")try{return s(o,200,{ok:!0,run:V.removeThread(r,{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")&&n.method==="POST")try{const l=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},u=String(l.by||"person").slice(0,40),k=a==="/answer"?V.answer(r,{threadId:l.threadId,text:l.text,by:u}):a==="/decide"?V.decide(r,{postId:l.postId,status:l.status,by:u}):V.post(r,{threadId:l.threadId,text:l.text,by:u,kind:l.kind,replyTo:l.replyTo});return s(o,200,{ok:!0,run:k})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&n.method==="POST")try{const l=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:V.append(r,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"&&n.method==="GET"){if(!V.get(r))return s(o,404,{error:{message:`no run ${r}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=w=>o.write(`data: ${JSON.stringify(w)}
|
|
27
27
|
|
|
28
|
-
`),u=p.searchParams.has("after")?Number(p.searchParams.get("after")):NaN;let
|
|
28
|
+
`),u=p.searchParams.has("after")?Number(p.searchParams.get("after")):NaN;let k=Number.isFinite(u)?u:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:V.get(r),after:k}});const f=V.watch(r,w=>{w.seq==null?l(w):w.seq>k&&(k=w.seq,l(w))});for(const w of V.eventsSince(r,k))k=w.seq,l(w);const T=setInterval(()=>{try{o.write(`: keep-alive
|
|
29
29
|
|
|
30
|
-
`)}catch{}},25e3);o.on("close",()=>{
|
|
31
|
-
data: ${JSON.stringify({cursor:
|
|
30
|
+
`)}catch{}},25e3);o.on("close",()=>{f(),clearInterval(T)});return}}}if(i==="/v1/memory/list"&&n.method==="GET")return s(o,200,{ok:!0,size:te.size,memories:te.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.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:te.size,...r})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.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:r.action,record:r.record,replaced:r.replaces||null,size:te.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=te.forget(String(e.query||""));return s(o,200,{ok:!0,removed:r,size:te.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...r,memories:te.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&n.method==="POST")return s(o,200,{ok:!0,dropped:te.clear(),size:te.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=M.clear();return s(o,200,{ok:!0,dropped:e,size:M.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=M.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:M.size,newest:M.newest,results:r})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),a=tn(r,{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},u=Math.min(30,Math.max(5,Number(e.limit)||10)*2),k=await on(a,T=>M.search(T,{limit:u,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),f=l.type?k:[...k.filter(T=>T.type==="brief"),...k.filter(T=>T.type!=="brief")];return s(o,200,{ok:!0,size:M.size,newest:M.newest,queries:a,results:f})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/related"&&n.method==="GET"){const e=String(p.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(p.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:M.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return s(o,200,{ok:!0,size:M.size,newest:M.newest,bytes:M.bytes,lossless:M.lossless?{records:M.lossless.size,newest:M.lossless.newest}:null});if(i==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(p.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:M.size,bytes:M.bytes,newest:M.newest}},access:Xe.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=Xe.push(Rt({ts:Date.now(),...e}));return s(o,200,{ok:!0,event:r})}catch(e){return s(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&n.method==="PUT"){const e=M.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},a=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),u=[];let k=0;const f={upserts:[],removes:[]},T=w=>{if(!w||w.deletedAt){w?.id&&f.removes.push(w.id);return}try{const h=rr(w);h&&f.upserts.push(h)}catch{}};if(Array.isArray(r.records)){const w=e.upsert(r.records,{host:a,at:l});u.push(...w);for(const h of r.records)w.includes(h?.id)&&T(h)}if(Array.isArray(r.entries)){const w=He(),h=w?ar((D,Q)=>nr(w,{salt:D,iterations:Q})):null,_=async D=>{if(!h||!D.blob)return null;const Q=await h(D.blob),he=D.blob.compression&&D.blob.compression!=="none"?ir(lr,D.blob.compression):null;return sr(D.blob,Q,{codec:he})},J=await e.upsertEntries(r.entries,{open:_});u.push(...J.written),k+=J.sealed;for(const D of J.written)T(e.get(D))}return(f.upserts.length||f.removes.length)&&M.bulk(f),u.length&&Ie({ids:u}),s(o,200,{ok:!0,written:u.length,ids:u,sealed:k,size:e.size})}catch(r){return s(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&n.method==="POST"){if(!H)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{},r=Array.isArray(e)?e:e.events;if(!Array.isArray(r))return s(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(r.length>2e3)return s(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const a=Xo(H,r);return s(o,200,{ok:!0,appended:a.appended,duplicates:a.duplicates,rejected:a.rejected,cursor:H.cursor()})}catch(e){return s(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&n.method==="GET")return H?s(o,200,{ok:!0,cursor:H.cursor(),count:H.count()}):s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&n.method==="GET"){if(!H)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=qo(H.all());return s(o,200,{ok:!0,stats:e,year:er(e)})}if(i==="/v1/events"&&n.method==="GET"){if(!H)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=gt(JSON.parse(p.searchParams.get("cursor")||"{}"))}catch{return s(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=H.since(e,{limit:Number(p.searchParams.get("limit"))||void 0,host:p.searchParams.get("host")||null});return s(o,200,{ok:!0,events:r.events.map(a=>Fe(a)),cursor:r.cursor,more:r.more})}if(i==="/v1/events/stream"&&n.method==="GET"){if(!H)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(p.searchParams.has("cursor"))try{e=gt(JSON.parse(p.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
|
|
31
|
+
data: ${JSON.stringify({cursor:H.cursor(),count:H.count(),version:ee})}
|
|
32
32
|
|
|
33
|
-
`),
|
|
34
|
-
data: ${JSON.stringify(
|
|
33
|
+
`),fe.add(o),n.on("close",()=>fe.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=H.since(r.cursor);for(const a of r.events)o.write(`event: cloudevent
|
|
34
|
+
data: ${JSON.stringify(Fe(a))}
|
|
35
35
|
|
|
36
|
-
`)}}return}if(
|
|
36
|
+
`)}}return}if(i==="/v1/history/stream"&&n.method==="GET"){const e=M.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
|
|
37
37
|
data: ${JSON.stringify({newest:e.newest,size:e.size,version:ee,prefsRevision:oe.revision})}
|
|
38
38
|
|
|
39
|
-
`),ae.add(o),n.on("close",()=>ae.delete(o));return}if(l==="/v1/history/records"&&n.method==="GET"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(p.searchParams.get("since"))||0,cursor:p.searchParams.get("cursor")||"",limit:Number(p.searchParams.get("limit"))||200,kind:p.searchParams.get("kind")||null});return s(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(l==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(p.searchParams.get("limit"))||50)),r=Math.max(0,Number(p.searchParams.get("offset"))||0),a=p.searchParams.get("type")||null;return s(o,200,{ok:!0,...N.list({limit:e,offset:r,type:a})})}if(l==="/v1/history/get"&&n.method==="GET"){const e=p.searchParams.get("maxChars")!=null?Math.max(1,Number(p.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(p.searchParams.get("offset"))||0),a=N.get(String(p.searchParams.get("id")||""),{maxChars:e,offset:r});return a?s(o,200,{ok:!0,record:a}):s(o,404,{error:{message:"no such record",type:"not_found"}})}if(l==="/v1/history/key"&&n.method==="GET")return s(o,200,{ok:!0,hasKey:mt()});if(l==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Ao(String(e.passphrase)):No();const r=e.passphrase?await Ve(N,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ce(),s(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(l==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await Ve(N,ze());return e.ok&&e.whole&&Ce(),s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(l==="/ner"){if(n.method==="GET"){const e=await Ht(t);return s(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Ae(t),E.state()!=="off"){if(!E.isReady()){const r=E.health();return s(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await T(n,t.maxBodyBytes);let a="";try{a=JSON.parse(r.toString("utf8"))?.text||""}catch{}const i=await E.detect(a);return s(o,200,{entities:i})}catch(r){return s(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=Gt(t);if(!e){const r=E.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:E.state(),model:t.ner?.model||null})}try{const r=await T(n,t.maxBodyBytes),a=await Ee(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),i=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(i)}catch(r){return s(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(l==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ye(t)});try{let r=e;const a=await fe(t.pro?.entitlementToken);await Ae(t);const i=await $e([Re(()=>r,u=>{r=u})],t.redaction,{isPro:a});return s(o,200,{text:r,count:i.count||0,sanitized:i.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Jt(i.vault,"types")||[],detector:Ye(t)})}catch(r){return s(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(l==="/ner/models"){if(n.method==="GET"){const e=E.health().model||t.ner?.model||null,r=Math.round(ht.totalmem()/1048576),a=kr(gt,{totalRamMB:r}).map(i=>({...i,installed:E.modelOnDisk(i.id)}));for(const i of[e,...E.modelsOnDisk()])!i||a.some(u=>u.id===i)||a.push({id:i,label:i,lang:"—",custom:!0,installed:E.modelOnDisk(i),note:"Custom model (from Hugging Face)."});return s(o,200,{active:e,companions:E.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Po(),recommendation:ut(a,{totalRamMB:r},[]),state:E.state(),progress:E.progress(),available:a})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const a=Math.round(ht.totalmem()/1048576),i=ut(gt.map(u=>({...u,installed:E.modelOnDisk(u.id)})),{totalRamMB:a},[]);e={id:i.primary,union:i.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const a=[...new Set(e.union.map(u=>String(u||"").trim()).filter(Boolean))];for(const u of a)if(!(wt(u)||bt(u)))return s(o,400,{error:{message:`unknown or invalid model id in union: ${u}`,type:"bad_model"}});const i=r||t.ner?.model||E.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=a.filter(u=>u!==i),r&&$t(t,r);try{me(t,se())}catch{}return(async()=>{r&&await E.setModel(r,{onLog:w=>console.log(w)});const u=$o(t.ner,{log:w=>console.log(w)});for(const w of E.companions())u.includes(w.model)||await E.removeCompanion(w.model);for(const w of u)await E.addCompanion(w,{onLog:y=>console.log(y),allowDownload:t.ner.allowDownload!==!1});E.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),s(o,202,{accepted:!0,active:i,union:t.ner.union,companions:E.companions(),state:E.state()})}if(!r||!(wt(r)||bt(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});$t(t,r);try{me(t,se())}catch{}return E.setModel(r,{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:r,state:E.state(),progress:E.progress()})}}if(l==="/stt/models"){if(n.method==="GET"){const e=A.health().model||t.stt?.model||Ne,r=Sr.map(a=>({...a,installed:A.modelOnDisk(a.id)}));return e&&!r.some(a=>a.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:A.state(),progress:A.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:_r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(Tr(r)||xr(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&Or(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{me(t,se())}catch{}return A.setModel(r,{onLog:i=>console.log(i),dtype:a||t.stt.dtype||"auto",warmMs:t.stt.warmMs}),s(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress()})}}if(l==="/diarize/model"){if(n.method==="GET"){const e=j.health();return s(o,200,{active:j.DIARIZE_MODEL,state:e.state,progress:j.progress(),available:[{id:j.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:j.modelOnDisk()}]})}if(n.method==="POST")return j.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:j.DIARIZE_MODEL,state:j.state(),progress:j.progress()})}if(l==="/tts/models"){if(n.method==="GET"){const e=P.health().model||t.tts?.model||_t(Ue()),r=Ue(),a=vt.find(u=>u.id===e)||null,i=vt.map(u=>({...u,installed:P.modelOnDisk(u.id),unavailable:u.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!i.some(u=>u.id===e)&&i.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:P.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:P.state(),progress:P.progress(),available:i,voice:t.tts?.voice||(Me(e)==="pocket-tts"?Be:ue),arch:P.arch(),supportsVoices:P.arch()?P.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:P.arch()?P.supportsCustomVoices():!!a?.customVoices,sampleRate:P.sampleRate(),voices:P.isPocket()||!P.arch()&&Me(e)==="pocket-tts"?(P.builtinVoices().length?P.builtinVoices():Dr).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:P.builtinVoices().includes(u)})):P.arch()&&P.arch()!=="style-tts2"?[]:$r.map(u=>({...u,installed:P.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:P.health().dtype,runtime:P.health().runtime,dtypes:Ar})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(Pr(r)||Er(r)))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 u=K.parseCustomVoice(a);if(!(u?!!K.getVoice(u):De(a)||kt(a)&&St(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&Nr(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Tt,voice:ue,allowDownload:!0}),r&&(t.tts.model=r),a&&(t.tts.voice=a),r&&!a){const u=Br(r),w=K.parseCustomVoice(t.tts.voice||""),y=!!(w&&K.getVoice(w));if(u&&!y)if(Me(r)==="pocket-tts")t.tts.voice=Be;else{const b=K.listVoices();t.tts.voice=b.length?`custom:${b[0].id}`:""}else!u&&y&&(t.tts.voice=ue);const k=Me(r)==="pocket-tts";k&&!K.parseCustomVoice(t.tts.voice||"")&&!De(t.tts.voice)&&(t.tts.voice=Be),!k&&De(t.tts.voice)&&(t.tts.voice=ue)}i&&(t.tts.dtype=i==="auto"?null:i);try{me(t,se())}catch{}return r&&P.setModel(r,{onLog:u=>console.log(u),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:P.state(),progress:P.progress()})}}if(l==="/tts/voices"){if(n.method==="GET")return s(o,200,{voices:K.listVoices(),usable:P.supportsCustomVoices(),embedder:j.DIARIZE_MODEL,embedderReady:j.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=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(!K.getVoice(i))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!r)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...K.renameVoice(i,r),usable:P.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.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(!r)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(!j.isReady()){const h=j.download({onLog:M=>console.log(M)}),O=Symbol("timeout"),I=await Promise.race([h.then(()=>null).catch(M=>M),new Promise(M=>setTimeout(()=>M(O),yn))]);if(I===O||!j.isReady())return s(o,503,{error:{message:I===O?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${j.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:j.progress()})}const u=Float32Array.from(a),w=await j.embed(u);let y=null;try{const h=await P.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:O=>console.log(O)});h&&(y=await h.encodeVoice(fn(u,16e3,24e3)))}catch(h){console.log(`[tts] pocket conditioning unavailable for this voice (${h.message})`)}const k=i?K.replaceVoice(i,{vec:w,pocket:y}):K.saveVoice({name:r,vec:w,pocket:y}),b=i&&r&&r!==k.name?K.renameVoice(i,r):k;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${b.name}" (${(k.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...k,...b,usable:P.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=p.searchParams.get("id")||"",r=K.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const a=K.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:ue;try{me(t,se())}catch{}}return s(o,200,{deleted:r,voice:t.tts?.voice})}}if((l==="/tts"||l==="/v1/audio/speech")&&n.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(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>xt)return s(o,413,{error:{message:`text too long (max ${xt} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=Mr(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,w=u||(i?i.voice:t.tts?.voice||ue);if(i&&!jr(w))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:ce,contentType:J,redacted:je}=await Cr({dest:i,text:r,voice:w,speed:a,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await fe(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":J,"Content-Length":String(ce.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(je)}),o.end(ce)}if(!await P.ready({onLog:ce=>console.log(ce),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||_t(Ue()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:P.health().error||"tts model not ready",type:"tts_unavailable"}});const b=Rr({requested:u,configured:w,engine:P,voices:K,isPocketVoice:De,isKnownVoice:kt,isValidVoiceId:St,defaultVoice:ue,defaultPocketVoice:Be});if(!b.ok)return s(o,b.status,{error:{message:b.message,type:b.type}});const{voice:h,customId:O,speakerEmbedding:I}=b,M=await P.synth(r,{voice:h,speed:a,speakerEmbedding:I}),W=P.sampleRate(),he=y==="pcm"?Buffer.from(new Float32Array(M).buffer):P.toWav(M,W);return o.writeHead(200,{"Content-Type":y==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(he.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(W),...O||P.isPocket()||P.supportsVoices()?{"X-Tts-Voice":h}:{}}),o.end(he)}catch(k){return s(o,500,{error:{message:k.message,type:"tts_failed"}})}}if(l==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=br(await T(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(h){return s(o,h.code===413?413:415,{error:{message:h.message,type:"bad_request"}})}const r=h=>e.find(O=>O.name===h&&!O.filename)?.data.toString("utf8").trim()||"",a=e.find(h=>h.name==="file"&&h.filename)||e.find(h=>h.filename);if(!a?.data?.length)return s(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let i;try{i=await vr(a.data)}catch(h){return s(o,h.code===415?415:500,{error:{message:h.message,type:"unsupported_media"}})}const u=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",w=yt(t,"stt");let y=null;if(w.kind==="remote"||w.kind==="container")try{y=ft(w,{fetchImpl:Ee})}catch(h){return s(o,500,{error:{message:`stt provider: ${h.message}`,type:"bad_provider"}})}!y&&!A.isReady()&&A.init({model:t.stt?.model||Ne,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,onLog:h=>console.log(h)});const k=r("diarize")==="true"&&t.stt?.diarize!==!1;k&&!j.isReady()&&j.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:h=>console.log(h)});const b=Date.now();try{const{id:h}=A.createSession({lang:r("language")||void 0,diarize:k,interims:!1,remote:y}),O=[];let I=null;A.subscribe(h,J=>{J.type==="final"&&J.text?O.push(J):J.type==="language"&&(I=J.lang)});const M=16e3*5;for(let J=0;J<i.pcm.length;J+=M)A.pushAudio(h,i.pcm.subarray(J,Math.min(i.pcm.length,J+M)));await A.endSession(h);let W=0;const he=O.map((J,je)=>{const Ut=W,Ft=(J.durationMs||0)/1e3;return W+=Ft,{id:je,start:Math.round(Ut*100)/100,end:Math.round(W*100)/100,text:J.text,...J.speaker?{speaker:J.speaker}:{}}}),ce=he.map(J=>J.text).join(" ").replace(/\s+/g," ").trim();return u==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(ce)):u==="verbose_json"?s(o,200,{task:"transcribe",language:I||r("language")||null,duration:Math.round(i.seconds*100)/100,text:ce,segments:he,provider:w.kind,took_ms:Date.now()-b}):s(o,200,{text:ce})}catch(h){return s(o,h.code==="too_many_sessions"?429:500,{error:{message:h.message,type:h.code||"stt_error"}})}}if(l==="/stt/sessions"&&n.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(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=yt(t,"stt");let a=null;if(r.kind==="remote"||r.kind==="container")try{a=ft(r,{fetchImpl:Ee})}catch(u){return s(o,500,{error:{message:`stt provider: ${u.message}`,type:"bad_provider"}})}!a&&!A.isReady()&&A.init({model:t.stt?.model||Ne,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});const i=e?.diarize===!0&&t.stt?.diarize!==!1;i&&!j.isReady()&&j.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});try{const{id:u}=A.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:i,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:a});return s(o,201,{id:u,state:A.state()})}catch(u){return s(o,u.code==="too_many_sessions"?429:500,{error:{message:u.message,type:u.code||"stt_error"}})}}{const e=l.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1];if(e[2]==="/audio"&&n.method==="POST")try{const a=await T(n,t.maxBodyBytes);return A.pushAudio(r,A.toFloat32(a)),s(o,200,{ok:!0,state:A.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"&&n.method==="GET"){const a=A.getSession(r);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=h=>o.write(`data: ${JSON.stringify(h)}
|
|
39
|
+
`),ie.add(o),n.on("close",()=>ie.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=M.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(p.searchParams.get("since"))||0,cursor:p.searchParams.get("cursor")||"",limit:Number(p.searchParams.get("limit"))||200,kind:p.searchParams.get("kind")||null});return s(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(p.searchParams.get("limit"))||50)),r=Math.max(0,Number(p.searchParams.get("offset"))||0),a=p.searchParams.get("type")||null;return s(o,200,{ok:!0,...M.list({limit:e,offset:r,type:a})})}if(i==="/v1/history/get"&&n.method==="GET"){const e=p.searchParams.get("maxChars")!=null?Math.max(1,Number(p.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(p.searchParams.get("offset"))||0),a=M.get(String(p.searchParams.get("id")||""),{maxChars:e,offset:r});return a?s(o,200,{ok:!0,record:a}):s(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&n.method==="GET")return s(o,200,{ok:!0,hasKey:ft()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Co(String(e.passphrase)):Ro();const r=e.passphrase?await We(M,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ie(),s(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await We(M,He());return e.ok&&e.whole&&Ie(),s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(n.method==="GET"){const e=await Kt(t);return s(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Be(t),A.state()!=="off"){if(!A.isReady()){const r=A.health();return s(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await O(n,t.maxBodyBytes);let a="";try{a=JSON.parse(r.toString("utf8"))?.text||""}catch{}const l=await A.detect(a);return s(o,200,{entities:l})}catch(r){return s(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=Wt(t);if(!e){const r=A.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:A.state(),model:t.ner?.model||null})}try{const r=await O(n,t.maxBodyBytes),a=await Me(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),l=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(l)}catch(r){return s(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:et(t)});try{let r=e;const a=await ye(t.pro?.entitlementToken);await Be(t);const l=await Ae([Le(()=>r,u=>{r=u})],t.redaction,{isPro:a});return s(o,200,{text:r,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Vt(l.vault,"types")||[],detector:et(t)})}catch(r){return s(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(n.method==="GET"){const e=A.health().model||t.ner?.model||null,r=Math.round(wt.totalmem()/1048576),a=$r(St,{totalRamMB:r}).map(l=>({...l,installed:A.modelOnDisk(l.id)}));for(const l of[e,...A.modelsOnDisk()])!l||a.some(u=>u.id===l)||a.push({id:l,label:l,lang:"—",custom:!0,installed:A.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return s(o,200,{active:e,companions:A.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Bo(),recommendation:yt(a,{totalRamMB:r},[]),state:A.state(),progress:A.progress(),available:a})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const a=Math.round(wt.totalmem()/1048576),l=yt(St.map(u=>({...u,installed:A.modelOnDisk(u.id)})),{totalRamMB:a},[]);e={id:l.primary,union:l.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const a=[...new Set(e.union.map(u=>String(u||"").trim()).filter(Boolean))];for(const u of a)if(!(Tt(u)||xt(u)))return s(o,400,{error:{message:`unknown or invalid model id in union: ${u}`,type:"bad_model"}});const l=r||t.ner?.model||A.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=a.filter(u=>u!==l),r&&Mt(t,r);try{ae(t,re())}catch{}return(async()=>{r&&await A.setModel(r,{onLog:k=>console.log(k)});const u=Mo(t.ner,{log:k=>console.log(k)});for(const k of A.companions())u.includes(k.model)||await A.removeCompanion(k.model);for(const k of u)await A.addCompanion(k,{onLog:f=>console.log(f),allowDownload:t.ner.allowDownload!==!1});A.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),s(o,202,{accepted:!0,active:l,union:t.ner.union,companions:A.companions(),state:A.state()})}if(!r||!(Tt(r)||xt(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Mt(t,r);try{ae(t,re())}catch{}return A.setModel(r,{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:r,state:A.state(),progress:A.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=N.health().model||t.stt?.model||De,r=Pr.map(a=>({...a,installed:N.modelOnDisk(a.id)}));return e&&!r.some(a=>a.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:N.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:N.state(),progress:N.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:N.health().dtype,runtime:N.health().runtime,dtypes:Mr})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(Ar(r)||Nr(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&Br(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{ae(t,re())}catch{}return N.setModel(r,{onLog:l=>console.log(l),dtype:a||t.stt.dtype||"auto",warmMs:t.stt.warmMs,speaker:ot(t,{installing:!0})}),s(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:N.state(),progress:N.progress(),speaker:{id:P.activeModel(),state:P.state(),installed:P.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=P.activeModel(),r=xr.map(a=>({...a,installed:P.modelOnDisk(a.id)})).sort((a,l)=>(l.id===e?1:0)-(a.id===e?1:0));return s(o,200,{active:e,state:P.state(),threshold:P.activeThreshold(),progress:P.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!bt(r))return s(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await P.setModel(r,{log:a=>console.log(a)}))return s(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{ae(t,re())}catch{}return P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:a=>console.log(a)}),s(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}return P.download({onLog:a=>console.log(a)}),s(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=$.health().model||t.tts?.model||At(Ke()),r=Ke(),a=Ot.find(u=>u.id===e)||null,l=Ot.map(u=>({...u,installed:$.modelOnDisk(u.id),unavailable:u.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(u=>u.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:$.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:$.state(),progress:$.progress(),available:l,voice:t.tts?.voice||(je(e)==="pocket-tts"?Ce:me),arch:$.arch(),supportsVoices:$.arch()?$.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:$.arch()?$.supportsCustomVoices():!!a?.customVoices,sampleRate:$.sampleRate(),voices:$.isPocket()||!$.arch()&&je(e)==="pocket-tts"?($.builtinVoices().length?$.builtinVoices():Lr).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:$.builtinVoices().includes(u)})):$.arch()&&$.arch()!=="style-tts2"?[]:Dr.map(u=>({...u,installed:$.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:$.health().dtype,runtime:$.health().runtime,dtypes:jr})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(Cr(r)||Rr(r)))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 u=Y.parseCustomVoice(a);if(!(u?!!Y.getVoice(u):Re(a)||_t(a)&&Et(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&Ir(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:$t,voice:me,allowDownload:!0}),r&&(t.tts.model=r),a&&(t.tts.voice=a),r&&!a){const u=zr(r),k=Y.parseCustomVoice(t.tts.voice||""),f=!!(k&&Y.getVoice(k));if(u&&!f)if(je(r)==="pocket-tts")t.tts.voice=Ce;else{const w=Y.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!u&&f&&(t.tts.voice=me);const T=je(r)==="pocket-tts";T&&!Y.parseCustomVoice(t.tts.voice||"")&&!Re(t.tts.voice)&&(t.tts.voice=Ce),!T&&Re(t.tts.voice)&&(t.tts.voice=me)}l&&(t.tts.dtype=l==="auto"?null:l);try{ae(t,re())}catch{}return r&&$.setModel(r,{onLog:u=>console.log(u),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:$.state(),progress:$.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return s(o,200,{voices:Y.listVoices(),usable:$.supportsCustomVoices(),embedder:P.activeModel(),embedderReady:P.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=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(!Y.getVoice(l))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!r)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...Y.renameVoice(l,r),usable:$.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.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(!r)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 h=P.download({onLog:D=>console.log(D)}),_=Symbol("timeout"),J=await Promise.race([h.then(()=>null).catch(D=>D),new Promise(D=>setTimeout(()=>D(_),Sn))]);if(J===_||!P.isReady())return s(o,503,{error:{message:J===_?"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 u=Float32Array.from(a),k=await P.embed(u);let f=null;try{const h=await $.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:_=>console.log(_)});h&&(f=await h.encodeVoice(Tn(u,16e3,24e3)))}catch(h){console.log(`[tts] pocket conditioning unavailable for this voice (${h.message})`)}const T=l?Y.replaceVoice(l,{vec:k,pocket:f}):Y.saveVoice({name:r,vec:k,pocket:f}),w=l&&r&&r!==T.name?Y.renameVoice(l,r):T;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${w.name}" (${(T.kinds||[]).join(" + ")}, sample discarded)`),s(o,l?200:201,{...T,...w,usable:$.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=p.searchParams.get("id")||"",r=Y.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const a=Y.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:me;try{ae(t,re())}catch{}}return s(o,200,{deleted:r,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&n.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 O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>Pt)return s(o,413,{error:{message:`text too long (max ${Pt} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Jr(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,k=u||(l?l.voice:t.tts?.voice||me);if(l&&!Ur(k))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const f=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(f!=="wav"&&f!=="pcm")return s(o,400,{error:{message:`unsupported response_format "${f}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:ue,contentType:G,redacted:ze}=await Gr({dest:l,text:r,voice:k,speed:a,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ye(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":G,"Content-Length":String(ue.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(ze)}),o.end(ue)}if(!await $.ready({onLog:ue=>console.log(ue),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||At(Ke()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:$.health().error||"tts model not ready",type:"tts_unavailable"}});const w=Hr({requested:u,configured:k,engine:$,voices:Y,isPocketVoice:Re,isKnownVoice:_t,isValidVoiceId:Et,defaultVoice:me,defaultPocketVoice:Ce});if(!w.ok)return s(o,w.status,{error:{message:w.message,type:w.type}});const{voice:h,customId:_,speakerEmbedding:J}=w,D=await $.synth(r,{voice:h,speed:a,speakerEmbedding:J}),Q=$.sampleRate(),he=f==="pcm"?Buffer.from(new Float32Array(D).buffer):$.toWav(D,Q);return o.writeHead(200,{"Content-Type":f==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(he.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Q),..._||$.isPocket()||$.supportsVoices()?{"X-Tts-Voice":h}:{}}),o.end(he)}catch(T){return s(o,500,{error:{message:T.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=_r(await O(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(h){return s(o,h.code===413?413:415,{error:{message:h.message,type:"bad_request"}})}const r=h=>e.find(_=>_.name===h&&!_.filename)?.data.toString("utf8").trim()||"",a=e.find(h=>h.name==="file"&&h.filename)||e.find(h=>h.filename);if(!a?.data?.length)return s(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await Er(a.data)}catch(h){return s(o,h.code===415?415:500,{error:{message:h.message,type:"unsupported_media"}})}const u=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",k=kt(t,"stt");let f=null;if(k.kind==="remote"||k.kind==="container")try{f=vt(k,{fetchImpl:Me})}catch(h){return s(o,500,{error:{message:`stt provider: ${h.message}`,type:"bad_provider"}})}!f&&!N.isReady()&&N.init({model:t.stt?.model||De,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ot(t),onLog:h=>console.log(h)});const T=r("diarize")==="true"&&t.stt?.diarize!==!1;T&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:h=>console.log(h)});const w=Date.now();try{const{id:h}=N.createSession({lang:r("language")||void 0,diarize:T,interims:!1,remote:f}),_=[];let J=null;N.subscribe(h,G=>{G.type==="final"&&G.text?_.push(G):G.type==="language"&&(J=G.lang)});const D=16e3*5;for(let G=0;G<l.pcm.length;G+=D)N.pushAudio(h,l.pcm.subarray(G,Math.min(l.pcm.length,G+D)));await N.endSession(h);let Q=0;const he=_.map((G,ze)=>{const Yt=Q,Zt=(G.durationMs||0)/1e3;return Q+=Zt,{id:ze,start:Math.round(Yt*100)/100,end:Math.round(Q*100)/100,text:G.text,...G.speaker?{speaker:G.speaker}:{}}}),ue=he.map(G=>G.text).join(" ").replace(/\s+/g," ").trim();return u==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(ue)):u==="verbose_json"?s(o,200,{task:"transcribe",language:J||r("language")||null,duration:Math.round(l.seconds*100)/100,text:ue,segments:he,provider:k.kind,took_ms:Date.now()-w}):s(o,200,{text:ue})}catch(h){return s(o,h.code==="too_many_sessions"?429:500,{error:{message:h.message,type:h.code||"stt_error"}})}}if(i==="/stt/sessions"&&n.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 O(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=kt(t,"stt");let a=null;if(r.kind==="remote"||r.kind==="container")try{a=vt(r,{fetchImpl:Me})}catch(u){return s(o,500,{error:{message:`stt provider: ${u.message}`,type:"bad_provider"}})}!a&&!N.isReady()&&N.init({model:t.stt?.model||De,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ot(t),onLog:u=>console.log(u)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});try{const{id:u}=N.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:a});return s(o,201,{id:u,state:N.state()})}catch(u){return s(o,u.code==="too_many_sessions"?429:500,{error:{message:u.message,type:u.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1];if(e[2]==="/audio"&&n.method==="POST")try{const a=await O(n,t.maxBodyBytes);return N.pushAudio(r,N.toFloat32(a)),s(o,200,{ok:!0,state:N.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"&&n.method==="GET"){const a=N.getSession(r);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=h=>o.write(`data: ${JSON.stringify(h)}
|
|
40
40
|
|
|
41
|
-
`),u=a.redact?await fe(t.pro?.entitlementToken):!0,w=async h=>{if(h.type!=="final"||!a.redact)return h;try{let O=h.text;return await $e([Re(()=>O,I=>{O=I})],t.redaction,{isPro:u}),{...h,text:O}}catch{return h}};i({type:"state",state:a.remote?"ready":A.state()});const y=setInterval(()=>{const h=a.remote?"ready":A.state();if(h==="downloading"||h==="loading"){i({type:"progress",state:h,...A.progress()||{}});return}if(h==="error"){i({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(y);return}if(a.diarize){const O=j.state();if(O==="downloading"||O==="loading"){i({type:"diarize-progress",state:O,...j.progress()||{}});return}}i({type:"state",state:h}),clearInterval(y)},500);y.unref?.();let k=Promise.resolve();const b=A.subscribe(r,h=>{k=k.then(async()=>{i(await w(h)),h.type==="end"&&(clearInterval(y),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(y),b?.()});return}if(!e[2]&&n.method==="DELETE")return await A.endSession(r),s(o,200,{ok:!0})}}if(l==="/logs"&&n.method==="GET")return s(o,200,{entries:[...L].reverse()});if(l==="/config"&&n.method==="GET"){const e=await fe(t.pro?.entitlementToken);return s(o,200,Ot(t,{proUnlocked:e}))}if(l==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{zr(t,e)}catch(y){if(y?.code==="SHAPE")return s(o,400,{error:y.message});throw y}at(t),JSON.stringify(t.sandbox||null)!==r&&Te?.restart("sandbox settings changed");try{me(t,se())}catch(y){return s(o,500,{error:`could not persist config: ${y.message}`})}const a=t.redaction?.detection,i=!a||!a.backend||a.backend==="off",u=E.state();t.ner?.autostart&&i&&u!=="ready"&&u!=="loading"&&u!=="downloading"&&E.setModel(t.ner.model,{onLog:y=>console.log(y)}).then(y=>{y&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const w=await fe(t.pro?.entitlementToken);return s(o,200,Ot(t,{proUnlocked:w}))}if(n.method==="GET"&&l==="/skills"){const e=await ye(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=de(t.bridge?.token);try{const a=await fetch(`${e}/skills${Xe(p,t)}`,{headers:{Accept:"application/json",...r?{Authorization:`Bearer ${r}`}:{}},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(n.method==="GET"&&/^\/skills\/[^/]+$/.test(l)){const e=decodeURIComponent(l.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const r=await ye(t);if(!r)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=de(t.bridge?.token);try{const i=await fetch(`${r}/skills/${encodeURIComponent(e)}${Xe(p,t)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),u=await i.json().catch(()=>({}));return i.ok?s(o,200,{skill:u?.skill||null}):s(o,i.status,{error:{message:u?.error||`bridge ${i.status}`,type:"bridge_error"}})}catch(i){return s(o,502,{error:{message:`bridge unreachable: ${i.message}`,type:"bridge_unreachable"}})}}if(l==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(l)){if(!X(n))return s(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(l==="/channels"&&n.method==="GET"||l!=="/channels"&&n.method==="POST"))return s(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await ye(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=de(t.bridge?.token);try{const a=n.method==="POST"?(await T(n,t.maxBodyBytes)).toString("utf8"):"",i=await fetch(`${e}${l}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:a||"{}"}:{},signal:AbortSignal.timeout(15e3)}),u=await i.json().catch(()=>({}));return s(o,i.status,u)}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(l)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(l),r=decodeURIComponent(e[1]),a=e[2];if(!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a)))return s(o,400,{error:{message:"not a skill file",type:"invalid_request"}});const i=await ye(t);if(!i)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const u=de(t.bridge?.token);try{const w=await fetch(`${i}/skills/${encodeURIComponent(r)}/file/${a}${Xe(p,t)}`,{headers:{Accept:"application/json",...u?{Authorization:`Bearer ${u}`}:{}},signal:AbortSignal.timeout(8e3)}),y=await w.json().catch(()=>({}));return w.ok?s(o,200,y):s(o,w.status,{error:{message:y?.error||`bridge ${w.status}`,type:"bridge_error"}})}catch(w){return s(o,502,{error:{message:`bridge unreachable: ${w.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/\/models$/.test(l)){const e=await S(),r=e.sig!==void 0&&e.sig!==$;return $=e.sig,s(o,200,await Ur(t,{serviceHealth:async()=>e,fresh:r}))}if(gn.some(e=>l===e||l.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${ee}) has no ${l} — update it to use this feature`,type:"unknown_endpoint"}});const C=an(l,n.headers,t);let Z;try{Z=await T(n,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let q=null,v=null,le=Z,ve=0,V=0,ne=0,U=!1,Y=!0;const H=t.logRequests&&C.redactable&&n.method==="POST"?sn(ie):null;if(C.redactable&&n.method==="POST"&&Z.length){try{v=JSON.parse(Z.toString("utf8"))}catch{v=null}if(v&&ln(v,C.kind))le=Z;else if(v){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(v.tools)&&v.tools.length){const b=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Yr,h=e.narrowAll?null:I=>!Xr.test(Ct(I)),O=v.tools.length;v.tools=to(v.tools,en(v,C.kind),{cap:b,keep:h,name:Ct,description:qr}),ne=O-v.tools.length}Y=await fe(t.pro?.entitlementToken);const r=Ir(t,Y);if(!r.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${r.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});U=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&X(n),U||await Ae(t);const a=U?[]:C.adapter.collectSegments(v,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const u=H?H.clock():0,{vault:w,count:y,sanitized:k}=U?{vault:null,count:0,sanitized:0}:await $e(a,t.redaction,{signal:i.signal,isPro:Y,onEgress:b=>Qe.push(Nt({ts:Date.now(),client:"redaction",tool:`detect:${b.backend}@${b.host||"local"}`,ok:b.ok,ms:b.ms,error:b.error}))});if(H&&H.lap("redact",u),q=w,ve=y,V=k||0,y>0&&o.setHeader("x-chatpanel-redacted",String(y)),!Y&&y>0){Lr(t,Y);try{me(t,se())}catch{}}if(!U&&Array.isArray(v.tools)&&v.tools.length&&typeof C.adapter.injectSystemNote=="function"){const b=At(v?.model,t,C.kind,{destination:String(n.headers["x-chatpanel-destination"]||v?.chatpanel?.destination||"").trim(),down:O=>!!O.service&&g.fn(O.id)==="down"}),h=!(b&&b.type==="api");C.adapter.injectSystemNote(v,ro({toolData:t.tools?.toolData,ownTools:h}))}else!U&&y>0&&typeof C.adapter.injectSystemNote=="function"&&C.adapter.injectSystemNote(v,no());le=Buffer.from(JSON.stringify(v),"utf8")}}const qe=oo({vault:q,toolData:t.tools?.toolData}),xe=v&&typeof v.chatpanel=="object"&&v.chatpanel||null;if(xe&&(delete v.chatpanel,le=Buffer.from(JSON.stringify(v),"utf8")),typeof v?.model=="string"&&v.model.startsWith("fusion:")){const e=Yo(v.model,t,await S());if(e?.error)return H?.commit(),s(o,400,{error:{message:e.error,type:"fusion"}});e&&(v.model=e.model,le=Buffer.from(JSON.stringify(v),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const pe={destination:String(n.headers["x-chatpanel-destination"]||xe?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||xe?.reach||"").trim(),run:vn(n.headers["x-chatpanel-run"],xe?.run)},et=await S(),B=At(v?.model,t,C.kind,{destination:pe.destination,down:e=>!!e.service&&et(e.id)==="down"});if(B?.service&&et(B.id)==="down")return H?.commit(),s(o,503,{error:{message:`${B.id} is not running — the model ${JSON.stringify(v?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:B.service}});if(pe.destination&&(!B||B.id!==pe.destination))return H?.commit(),s(o,404,{error:{message:`no destination "${pe.destination}" is configured on this gateway`,type:"unknown_destination",known:Fr(t).map(e=>e.id)}});H&&(H.meta={t:Date.now(),model:v?.model||null,dest:B?B.id:null,type:B?B.type:null,redacted:ve,sanitized:V,narrowed:ne,detail:Jt(q,t.logDetail),redaction:U?"off":t.redaction.tier||"basic"});const _e=fo();if(_e&&B){const e=B.type==="api"?it(_e,{model:v?.model||"",endpoint:B.baseUrl||""}):wo(_e,B.agent||B.id)?it(_e,{model:v?.model||""}):{ok:!1,reason:`agent "${B.agent||B.id}" is not allowed by your organisation’s policy`};if(!e.ok)return H?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(B&&B.type==="api")return B.baseUrl?cn(B.baseUrl,t)?(H?.commit(),s(o,508,{error:{message:`destination "${B.id}" points back at the gateway (${B.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):wn(n,o,{...C,pathname:l,search:p.search,base:B.baseUrl,destKey:B.apiKey,destProtocol:B.protocol,harness:qe,trace:H},le,q):(H?.commit(),s(o,502,{error:`destination "${B.id}" has no baseUrl`}));const tt=Pe(n),ot=tt==="local"&&t.bridge?.openAgentLane?"token":tt;if(ot==="local")return H?.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 rt=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),Oe=ao({...pe.run||{},...pe.reach?{reach:pe.reach}:{},...rt?{askDepth:rt}:{}},ot);return Oe.reach&&o.setHeader("x-chatpanel-reach-used",Oe.reach),pn(n,o,{...C,pathname:l,agentOverride:B?.agent,harness:qe,trace:H,run:Object.keys(Oe).length?Oe:null},v,q,t,Y)});return re.on("close",()=>{m?.stop("closed"),lr()}),re}function vn(t,c){let d=c&&typeof c=="object"?c:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const m={};if(Array.isArray(d.grants)&&(m.grants=d.grants.map(f=>String(f).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const f=d.workspace;m.workspace={repo:String(f.repo).slice(0,400),projectId:String(f.projectId||"").slice(0,120),jobId:String(f.jobId||"").slice(0,120),...f.base?{base:String(f.base).slice(0,120)}:{}}}if(d.connectionId&&(m.connectionId=String(d.connectionId).slice(0,64)),typeof d.workingDir=="string"&&d.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(d.workingDir.trim())&&(m.workingDir=d.workingDir.trim().slice(0,1024)),Hr.includes(d.permissionMode)&&d.permissionMode!=="default"&&(m.permissionMode=d.permissionMode),d.sandbox&&typeof d.sandbox=="object"){const f=(Array.isArray(d.sandbox.hosts)?d.sandbox.hosts:String(d.sandbox.hosts||"").split(/[\s,;]+/)).map($=>String($).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),g=(Array.isArray(d.sandbox.write)?d.sandbox.write:[]).map($=>String($).slice(0,1024)).filter(Boolean).slice(0,32);(f.length||g.length)&&(m.sandbox={...f.length?{hosts:f}:{},...g.length?{write:g}:{}})}return Object.keys(m).length?m:null}let Te=null;async function js(t=nt()){Eo();let c=null;try{c=await yo()}catch(S){throw S instanceof go&&(console.error(`[chatpanel-gateway] org policy: ${S.message}`),process.exit(78)),S}const d=c?.policy||null;d&&(at(t,d),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`)),po(globalThis,{allow:d?.egress?(S,{local:x})=>bo(d,S,{local:x}):null}),Ie();const m=bn(t),f=Oo(t),g=Kt(t);m.on("error",S=>{S&&S.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 ${se()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${S?.message||S}`),process.exit(1)}),m.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${ee} 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"),Jo(t,{childEnv:()=>({...Vr(t),...Gr(t)})}).then(S=>{Te=S}).catch(S=>console.log(` bridge : not supervised (${S?.message||S})`)),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…)":"")),It(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.`)}),mt()&&Ve(N,ze()).then(S=>{S?.ok&&(console.log(` warm : seeded ${S.ingested} records from ${S.file}`),S.whole&&Ce())}).catch(()=>{});const $=()=>{f?.stop(),g.stop(),Te?.stop(),Zr(m)};return process.on("SIGINT",$),process.on("SIGTERM",$),m}export{Ls as VERSION,bn as createGateway,hn as joinUpstream,Ze as parseAgentModel,js as start};
|
|
41
|
+
`),u=a.redact?await ye(t.pro?.entitlementToken):!0,k=async h=>{if(h.type!=="final"||!a.redact)return h;try{let _=h.text;return await Ae([Le(()=>_,J=>{_=J})],t.redaction,{isPro:u}),{...h,text:_}}catch{return h}};l({type:"state",state:a.remote?"ready":N.state()});const f=setInterval(()=>{const h=a.remote?"ready":N.state();if(h==="downloading"||h==="loading"){l({type:"progress",state:h,...N.progress()||{}});return}if(h==="error"){l({type:"error",code:"model_failed",message:N.health().error||"model failed to load",fatal:!0}),clearInterval(f);return}if(a.diarize){const _=P.state();if(_==="downloading"||_==="loading"){l({type:"diarize-progress",state:_,...P.progress()||{}});return}}l({type:"state",state:h}),clearInterval(f)},500);f.unref?.();let T=Promise.resolve();const w=N.subscribe(r,h=>{T=T.then(async()=>{l(await k(h)),h.type==="end"&&(clearInterval(f),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(f),w?.()});return}if(!e[2]&&n.method==="DELETE")return await N.endSession(r),s(o,200,{ok:!0})}}if(i==="/logs"&&n.method==="GET")return s(o,200,{entries:[...L].reverse()});if(i==="/config"&&n.method==="GET"){const e=await ye(t.pro?.entitlementToken);return s(o,200,Nt(t,{proUnlocked:e}))}if(i==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{Kr(t,e)}catch(f){if(f?.code==="SHAPE")return s(o,400,{error:f.message});throw f}ct(t),JSON.stringify(t.sandbox||null)!==r&&_e?.restart("sandbox settings changed");try{ae(t,re())}catch(f){return s(o,500,{error:`could not persist config: ${f.message}`})}const a=t.redaction?.detection,l=!a||!a.backend||a.backend==="off",u=A.state();t.ner?.autostart&&l&&u!=="ready"&&u!=="loading"&&u!=="downloading"&&A.setModel(t.ner.model,{onLog:f=>console.log(f)}).then(f=>{f&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const k=await ye(t.pro?.entitlementToken);return s(o,200,Nt(t,{proUnlocked:k}))}if(n.method==="GET"&&i==="/skills")return se(n,o,t,`/skills${ke(p,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="GET"&&i==="/skills-quarantined")return se(n,o,t,`/skills-quarantined${ke(p,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&n.method==="POST")return U(n)?se(n,o,t,"/skills",{method:"POST",timeoutMs:15e3}):s(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(i)&&n.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return rt(e)?s(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):U(n)?se(n,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):s(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(i)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]);return rt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?s(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):U(n)?se(n,o,t,`/skills/${encodeURIComponent(r)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):s(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(n.method==="GET"&&i==="/agent-defs")return se(n,o,t,`/agent-defs${ke(p,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return rt(e)?s(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):se(n,o,t,`/agent-defs/${encodeURIComponent(e)}${ke(p,t)}`)}if(n.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return U(n)?se(n,o,t,i,{method:"POST",timeoutMs:15e3}):s(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?s(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):se(n,o,t,`/skills/${encodeURIComponent(e)}${ke(p,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!U(n))return s(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return s(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await xe(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=ge(t.bridge?.token);try{const a=n.method==="POST"?(await O(n,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:a||"{}"}:{},signal:AbortSignal.timeout(15e3)}),u=await l.json().catch(()=>({}));return s(o,l.status,u)}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]),a=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a))?s(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):se(n,o,t,`/skills/${encodeURIComponent(r)}/file/${a}${ke(p,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await v(),r=e.sig!==void 0&&e.sig!==E;return E=e.sig,s(o,200,await Xr(t,{serviceHealth:async()=>e,fresh:r}))}if(xn.some(e=>i===e||i.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${ee}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const R=hn(i,n.headers,t);let X;try{X=await O(n,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let q=null,S=null,de=X,ve=0,Se=0,W=0,K=!1,F=!0;const z=t.logRequests&&R.redactable&&n.method==="POST"?pn(le):null;if(R.redactable&&n.method==="POST"&&X.length){try{S=JSON.parse(X.toString("utf8"))}catch{S=null}if(S&&yn(S,R.kind))de=X;else if(S){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(S.tools)&&S.tools.length){const w=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):nn,h=e.narrowAll?null:J=>!sn.test(Lt(J)),_=S.tools.length;S.tools=ao(S.tools,ln(S,R.kind),{cap:w,keep:h,name:Lt,description:an}),W=_-S.tools.length}F=await ye(t.pro?.entitlementToken);const r=Vr(t,F);if(!r.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${r.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});K=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&U(n),K||await Be(t);const a=K?[]:R.adapter.collectSegments(S,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const u=z?z.clock():0,{vault:k,count:f,sanitized:T}=K?{vault:null,count:0,sanitized:0}:await Ae(a,t.redaction,{signal:l.signal,isPro:F,onEgress:w=>Xe.push(Rt({ts:Date.now(),client:"redaction",tool:`detect:${w.backend}@${w.host||"local"}`,ok:w.ok,ms:w.ms,error:w.error}))});if(z&&z.lap("redact",u),q=k,ve=f,Se=T||0,f>0&&o.setHeader("x-chatpanel-redacted",String(f)),!F&&f>0){Fr(t,F);try{ae(t,re())}catch{}}if(!K&&Array.isArray(S.tools)&&S.tools.length&&typeof R.adapter.injectSystemNote=="function"){const w=Ct(S?.model,t,R.kind,{destination:String(n.headers["x-chatpanel-destination"]||S?.chatpanel?.destination||"").trim(),down:_=>!!_.service&&g.fn(_.id)==="down"}),h=!(w&&w.type==="api");R.adapter.injectSystemNote(S,lo({toolData:t.tools?.toolData,ownTools:h}))}else!K&&f>0&&typeof R.adapter.injectSystemNote=="function"&&R.adapter.injectSystemNote(S,co());de=Buffer.from(JSON.stringify(S),"utf8")}}const Ee=io({vault:q,toolData:t.tools?.toolData}),ce=S&&typeof S.chatpanel=="object"&&S.chatpanel||null;if(ce&&(delete S.chatpanel,de=Buffer.from(JSON.stringify(S),"utf8")),typeof S?.model=="string"&&S.model.startsWith("fusion:")){const e=or(S.model,t,await v());if(e?.error)return z?.commit(),s(o,400,{error:{message:e.error,type:"fusion"}});e&&(S.model=e.model,de=Buffer.from(JSON.stringify(S),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const pe={destination:String(n.headers["x-chatpanel-destination"]||ce?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||ce?.reach||"").trim(),run:En(n.headers["x-chatpanel-run"],ce?.run)},nt=await v(),B=Ct(S?.model,t,R.kind,{destination:pe.destination,down:e=>!!e.service&&nt(e.id)==="down"});if(B?.service&&nt(B.id)==="down")return z?.commit(),s(o,503,{error:{message:`${B.id} is not running — the model ${JSON.stringify(S?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:B.service}});if(pe.destination&&(!B||B.id!==pe.destination))return z?.commit(),s(o,404,{error:{message:`no destination "${pe.destination}" is configured on this gateway`,type:"unknown_destination",known:qr(t).map(e=>e.id)}});z&&(z.meta={t:Date.now(),model:S?.model||null,dest:B?B.id:null,type:B?B.type:null,redacted:ve,sanitized:Se,narrowed:W,detail:Vt(q,t.logDetail),redaction:K?"off":t.redaction.tier||"basic"});const $e=vo();if($e&&B){const e=B.type==="api"?ut($e,{model:S?.model||"",endpoint:B.baseUrl||""}):To($e,B.agent||B.id)?ut($e,{model:S?.model||""}):{ok:!1,reason:`agent "${B.agent||B.id}" is not allowed by your organisation’s policy`};if(!e.ok)return z?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(B&&B.type==="api")return B.baseUrl?fn(B.baseUrl,t)?(z?.commit(),s(o,508,{error:{message:`destination "${B.id}" points back at the gateway (${B.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):On(n,o,{...R,pathname:i,search:p.search,base:B.baseUrl,destKey:B.apiKey,destProtocol:B.protocol,harness:Ee,trace:z},de,q):(z?.commit(),s(o,502,{error:`destination "${B.id}" has no baseUrl`}));const st=Ne(n),at=st==="local"&&t.bridge?.openAgentLane?"token":st;if(at==="local")return z?.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 it=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),Pe=mo({...pe.run||{},...pe.reach?{reach:pe.reach}:{},...it?{askDepth:it}:{}},at);return Pe.reach&&o.setHeader("x-chatpanel-reach-used",Pe.reach),kn(n,o,{...R,pathname:i,agentOverride:B?.agent,harness:Ee,trace:z,run:Object.keys(Pe).length?Pe:null},S,q,t,F)});return ne.on("close",()=>{m?.stop("closed"),pr()}),ne}function En(t,d){let c=d&&typeof d=="object"?d:null;if(!c&&t)try{c=JSON.parse(decodeURIComponent(String(t)))}catch{c=null}if(!c||typeof c!="object")return null;const m={};if(Array.isArray(c.grants)&&(m.grants=c.grants.map(y=>String(y).slice(0,80)).slice(0,32)),c.workspace&&typeof c.workspace=="object"&&c.workspace.repo){const y=c.workspace;m.workspace={repo:String(y.repo).slice(0,400),projectId:String(y.projectId||"").slice(0,120),jobId:String(y.jobId||"").slice(0,120),...y.base?{base:String(y.base).slice(0,120)}:{}}}if(c.connectionId&&(m.connectionId=String(c.connectionId).slice(0,64)),typeof c.workingDir=="string"&&c.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(c.workingDir.trim())&&(m.workingDir=c.workingDir.trim().slice(0,1024)),Yr.includes(c.permissionMode)&&c.permissionMode!=="default"&&(m.permissionMode=c.permissionMode),c.sandbox&&typeof c.sandbox=="object"){const y=(Array.isArray(c.sandbox.hosts)?c.sandbox.hosts:String(c.sandbox.hosts||"").split(/[\s,;]+/)).map(E=>String(E).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),g=(Array.isArray(c.sandbox.write)?c.sandbox.write:[]).map(E=>String(E).slice(0,1024)).filter(Boolean).slice(0,32);(y.length||g.length)&&(m.sandbox={...y.length?{hosts:y}:{},...g.length?{write:g}:{}})}return Object.keys(m).length?m:null}let _e=null;async function Hs(t=lt()){Do();let d=null;try{d=await ko()}catch(v){throw v instanceof So&&(console.error(`[chatpanel-gateway] org policy: ${v.message}`),process.exit(78)),v}const c=d?.policy||null;c&&(ct(t,c),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`)),wo(globalThis,{allow:c?.egress?(v,{local:x})=>xo(c,v,{local:x}):null}),Je();const m=_n(t),y=No(t),g=qt(t);m.on("error",v=>{v&&v.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 ${re()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${v?.message||v}`),process.exit(1)}),m.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${ee} 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"),Vo(t,{childEnv:()=>({...Zr(t),...Qr(t)})}).then(v=>{_e=v}).catch(v=>console.log(` bridge : not supervised (${v?.message||v})`)),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…)":"")),Ut(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.`)}),ft()&&We(M,He()).then(v=>{v?.ok&&(console.log(` warm : seeded ${v.ingested} records from ${v.file}`),v.whole&&Ie())}).catch(()=>{});const E=()=>{y?.stop(),g.stop(),_e?.stop(),rn(m)};return process.on("SIGINT",E),process.on("SIGTERM",E),m}export{Ws as VERSION,_n as createGateway,vn as joinUpstream,qe as parseAgentModel,Hs as start};
|
package/src/service.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import g from"node:os";import p from"node:path";import{mkdirSync as
|
|
2
|
-
`),l=Object.entries(r).map(([
|
|
1
|
+
import g from"node:os";import p from"node:path";import{mkdirSync as b,writeFileSync as E,readFileSync as pe,rmSync as w,existsSync as m,statSync as de,realpathSync as q}from"node:fs";import{spawnSync as fe,spawn as k}from"node:child_process";import{loadConfig as he}from"./config.js";import{VERSION as C}from"./version.js";const S="net.chatpanel.gateway",me="ChatPanel Privacy Gateway";function I(e,{real:t=q.native||q}={}){if(!e)return e;try{return t(e)}catch{return e}}function R({execPath:e=I(process.execPath),argv1:t=I(process.argv[1]||"")}={}){const n=p.basename(e).toLowerCase();return(n.startsWith("node")||n.startsWith("bun"))&&t?{program:e,args:[p.resolve(t)]}:{program:e,args:[]}}function v(){const e=p.join(g.homedir(),".chatpanel");return b(e,{recursive:!0}),{out:p.join(e,"gateway.log"),err:p.join(e,"gateway.err.log")}}function u(e,t,n={}){return fe(e,t,{encoding:"utf8",...n})}const j=()=>p.join(g.homedir(),"Library","LaunchAgents",`${S}.plist`),ge={MallocLargeCache:"0"};function we({program:e,args:t,out:n,err:s,env:r=ge,label:i=S}={}){const o=a=>String(a).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),c=[e,...t].map(a=>` <string>${o(a)}</string>`).join(`
|
|
2
|
+
`),l=Object.entries(r).map(([a,d])=>` <key>${o(a)}</key><string>${o(d)}</string>`).join(`
|
|
3
3
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
4
4
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
5
5
|
<plist version="1.0">
|
|
6
6
|
<dict>
|
|
7
|
-
<key>Label</key><string>${
|
|
7
|
+
<key>Label</key><string>${i}</string>
|
|
8
8
|
<key>ProgramArguments</key>
|
|
9
9
|
<array>
|
|
10
|
-
${
|
|
10
|
+
${c}
|
|
11
11
|
</array>
|
|
12
12
|
<key>EnvironmentVariables</key>
|
|
13
13
|
<dict>
|
|
@@ -15,27 +15,28 @@ ${l}
|
|
|
15
15
|
</dict>
|
|
16
16
|
<key>RunAtLoad</key><true/>
|
|
17
17
|
<key>KeepAlive</key><true/>
|
|
18
|
-
<key>StandardOutPath</key><string>${
|
|
19
|
-
<key>StandardErrorPath</key><string>${
|
|
18
|
+
<key>StandardOutPath</key><string>${o(n)}</string>
|
|
19
|
+
<key>StandardErrorPath</key><string>${o(s)}</string>
|
|
20
20
|
</dict>
|
|
21
21
|
</plist>
|
|
22
|
-
`}function
|
|
23
|
-
`,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const
|
|
22
|
+
`}function ye(){const{program:e,args:t}=R(),{out:n,err:s}=v(),r=we({program:e,args:t,out:n,err:s}),i=j();b(p.dirname(i),{recursive:!0}),E(i,r),u("launchctl",["unload",i]);const o=u("launchctl",["load","-w",i]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"launchctl load failed")}function xe(){const e=j();u("launchctl",["unload","-w",e]),m(e)&&w(e)}function $e(){return(u("launchctl",["list"]).stdout||"").includes(S)}function _({execPath:e=I(process.execPath),argv1:t=I(process.argv[1]||""),platform:n=process.platform,isFile:s=Z}={}){const r=n==="win32"?p.win32:p.posix,i=r.basename(e).toLowerCase();if(!(i.startsWith("node")||i.startsWith("bun")))return r.dirname(e);const o=n==="win32"?"chatpanel-gateway.cmd":"chatpanel-gateway";let c=r.dirname(r.resolve(t));for(let l=0;l<6;l++){const a=r.dirname(c);if(a===c)break;if(c=a,s(r.join(c,o)))return c;if(s(r.join(c,"bin",o)))return r.join(c,"bin")}return""}const Z=e=>{try{return de(e).isFile()}catch{return!1}};function N(e,t,{delimiter:n=p.delimiter,platform:s=process.platform,env:r=process.env}={}){const i=l=>s==="win32"?l.replace(/%([^%]+)%/g,(a,d)=>r[d]??r[d.toUpperCase()]??a):l,o=l=>{const a=i(l.trim()).replace(/[\\/]+$/,"");return s==="win32"?a.toLowerCase():a},c=String(e||"").split(n).filter(l=>l.trim());return c.some(l=>o(l)===o(t))?null:[...c,t].join(n)}function K({dir:e=_(),pathEnv:t=process.env.PATH||"",platform:n=process.platform,isFile:s=Z}={}){if(!e)return"";const r=n==="win32"?p.win32:p.posix,i=n==="win32"?";":":",o=l=>{const a=String(l).trim().replace(/[\\/]+$/,"");return n==="win32"?a.toLowerCase():a},c=n==="win32"?["chatpanel-gateway.cmd","chatpanel-gateway.exe"]:["chatpanel-gateway"];for(const l of String(t).split(i)){const a=l.trim();if(a){if(o(a)===o(e))return"";if(c.some(d=>s(r.join(a,d))))return a}}return""}const y="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",W="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",h="ChatPanelGateway",L=()=>p.join(g.homedir(),".chatpanel","gateway-launch.vbs"),Y=e=>Buffer.from(e,"utf16le").toString("base64");function U({systemRoot:e=process.env.SystemRoot||"C:\\Windows",exists:t=m}={}){return t(p.join(e,"System32","vbscript.dll"))}function z({program:e,args:t=[],out:n,err:s,vbs:r,vbscript:i=!0}){const o=f=>`"${f}"`;if(i){const f=`cmd.exe /c "${[e,...t].map(o).join(" ")} >> ${o(n)} 2>> ${o(s)}"`;return{kind:"vbs",file:r,text:`CreateObject("WScript.Shell").Run "${f.replace(/"/g,'""')}", 0, False\r
|
|
23
|
+
`,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const c=f=>`'${String(f).replace(/'/g,"''")}'`,l=t.length?` -ArgumentList @(${t.map(f=>c(o(f))).join(", ")})`:"",a=`Start-Process -WindowStyle Hidden -FilePath ${c(e)}${l} -RedirectStandardOutput ${c(n)} -RedirectStandardError ${c(s)}`,d=["powershell.exe","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",Y(a)];return{kind:"powershell",file:"",text:a,runValue:d.join(" "),argv:d}}function D(e=u){const t=e("reg",["query",y,"/v",h]);if(t.status!==0)return"";const n=new RegExp(`${h}\\s+REG_\\w+\\s+(.*)$`,"m").exec(t.stdout||"");return n?n[1].trim():""}function Se(e=u){const t=e("reg",["query",W,"/v",h]);if(t.status!==0)return!1;const n=/REG_BINARY\s+([0-9A-Fa-f]{2})/.exec(t.stdout||"");return!!n&&(parseInt(n[1],16)&1)===1}function X(e=u){const t=e("reg",["query","HKCU\\Environment","/v","Path"]),n=/\bPath\s+(REG_EXPAND_SZ|REG_SZ)\s+(.*)$/mi.exec(t.stdout||"");return n?{type:n[1],value:n[2].trim()}:{type:"REG_EXPAND_SZ",value:""}}const ve=`$sig = '[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);'
|
|
24
24
|
$t = Add-Type -MemberDefinition $sig -Name 'Env' -Namespace 'ChatPanelWin32' -PassThru
|
|
25
25
|
$r = [UIntPtr]::Zero
|
|
26
|
-
[void]$t::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$r)`;function
|
|
27
|
-
`)){const
|
|
28
|
-
Description=${
|
|
26
|
+
[void]$t::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$r)`;function Pe(e,{runImpl:t=u,env:n=process.env}={}){if(!e)return{added:!1,dir:e};const s=X(t),r=N(s.value,e,{delimiter:";",platform:"win32",env:n});if(r===null)return{added:!1,dir:e,onPath:!0};const i=t("reg",["add","HKCU\\Environment","/v","Path","/t",s.type,"/d",r,"/f"]);return i.status!==0?{added:!1,dir:e,error:(i.stderr||"").trim()||"reg add failed"}:(t("powershell.exe",["-NoProfile","-NonInteractive","-EncodedCommand",Y(ve)],{timeout:15e3}),{added:!0,dir:e,onPath:!0})}function Ae(e,{runImpl:t=u,env:n=process.env}={}){if(!e)return!0;const s=n.Path??n.PATH??"";return N(X(t).value,e,{delimiter:";",platform:"win32",env:n})===null||N(s,e,{delimiter:";",platform:"win32",env:n})===null}function be({pid:e=process.pid}={}){return`${`$keep = @(${e}, $PID); $p = Get-CimInstance Win32_Process -Filter 'ProcessId = ${e}'; $n = 0; while ($p -and $n++ -lt 8) { $keep += $p.ParentProcessId; $p = Get-CimInstance Win32_Process -Filter "ProcessId = $($p.ParentProcessId)" }`}; Get-CimInstance Win32_Process | Where-Object { $keep -notcontains $_.ProcessId -and (($_.Name -ieq 'chatpanel-gateway.exe') -or ($_.CommandLine -match '[\\\\/]chatpanel-gateway\\.js(["'' ]|$)')) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`}function Ee({pid:e=process.pid}={}){return[["powershell.exe",["-NoProfile","-NonInteractive","-Command",be({pid:e})]],["taskkill",["/F","/FI","IMAGENAME eq chatpanel-gateway.exe","/FI",`PID ne ${e}`]]]}function O(e=u){for(const[t,n]of Ee())e(t,n,{timeout:15e3})}function ke(){return process.platform==="win32"?O():(process.platform==="darwin"?u("launchctl",["bootout",`gui/${process.getuid?.()??""}/${S}`]):u("systemctl",["--user","stop","chatpanel-gateway.service"]),ee())}function Ie(){const{program:e,args:t}=R(),{out:n,err:s}=v(),r=z({program:e,args:t,out:n,err:s,vbs:L(),vbscript:U()});r.file?E(r.file,r.text):w(L(),{force:!0});const i=u("reg",["add",y,"/v",h,"/t","REG_SZ","/d",r.runValue,"/f"]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"reg add failed");u("reg",["delete",W,"/v",h,"/f"]);const o=Pe(_());return O(),u("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),u(r.argv[0],r.argv.slice(1),{windowsHide:!0,timeout:2e4}),{launcher:r.kind,path:o}}function Re(){u("reg",["delete",y,"/v",h,"/f"]),w(L(),{force:!0}),O()}function J(){return u("reg",["query",y,"/v",h]).status===0}function x({env:e=process.env,release:t=g.release(),platform:n=process.platform}={}){return n==="linux"&&(!!e.WSL_DISTRO_NAME||/microsoft/i.test(t))}function P(e=u){const t=["/mnt/c/Windows/System32/cmd.exe","cmd.exe"];let n=null;for(const a of t){if(n=e(a,["/c","echo %USERPROFILE%|%SystemRoot%"],{cwd:"/mnt/c",timeout:15e3}),n&&!n.error&&n.status===0)break;n=null}const[s,r]=(n?.stdout||"").trim().split("|");if(!/^[A-Za-z]:\\/.test(s||"")||!/^[A-Za-z]:\\/.test(r||""))return null;const i=a=>(e("wslpath",["-u",a]).stdout||"").trim(),o=i(r),c=i(s);if(!o||!c)return null;const l=p.posix.join(o,"System32");return{home:s,homeUnix:c,sysRoot:r,sysUnix:o,exe:{reg:p.posix.join(l,"reg.exe"),wscript:p.posix.join(l,"wscript.exe"),powershell:p.posix.join(l,"WindowsPowerShell","v1.0","powershell.exe")}}}const je=["^[^ ]*chatpanel-gateway( |$)","^[^ ]*(node|bun)[^ ]*( +-[^ ]+)* +[^ ]*chatpanel-gateway\\.js( |$)"];function Q(e,t=u){const n=t("ps",["-o","ppid=","-p",String(e)]);return Number((n.stdout||"").trim())||0}function _e({pid:e=process.pid,ppid:t=process.ppid,parentOf:n=Q,depth:s=8}={}){const r=new Set([e]);let i=t;for(let o=0;o<s&&i>1&&!r.has(i);o+=1)r.add(i),i=n(i);return r}function ee({runImpl:e=u,keep:t=null,kill:n=r=>process.kill(r,"SIGTERM"),patterns:s=je}={}){const r=t||_e({parentOf:c=>Q(c,e)}),i=[],o=new Set;for(const c of s){const l=e("pgrep",["-f",c]);for(const a of(l.stdout||"").split(`
|
|
27
|
+
`)){const d=Number(a.trim());if(!(!d||r.has(d)||o.has(d))){o.add(d);try{n(d),i.push(d)}catch{}}}}return i}const te=()=>ee(),ne=e=>({win:`${e.home}\\.chatpanel\\gateway-launch.vbs`,unix:p.posix.join(e.homeUnix,".chatpanel","gateway-launch.vbs")});function Ne(e,t){const[n,...s]=t.argv;return[n==="wscript.exe"?e.exe.wscript:e.exe.powershell,...s]}function Te(e){const{program:t,args:n}=R(),{out:s,err:r}=v(),i=$=>`'${String($).replace(/'/g,"'\\''")}'`,o=`exec ${[t,...n].map(i).join(" ")} >> ${i(s)} 2>> ${i(r)}`,c=process.env.WSL_DISTRO_NAME?["-d",process.env.WSL_DISTRO_NAME]:[],l=ne(e),a=z({program:"wsl.exe",args:[...c,"-u",g.userInfo().username,"--","bash","-lc",o],vbs:l.win,vbscript:U({systemRoot:e.sysUnix})});b(p.dirname(l.unix),{recursive:!0}),a.file?E(l.unix,a.text):w(l.unix,{force:!0});const d=u(e.exe.reg,["add",y,"/v",h,"/t","REG_SZ","/d",a.runValue,"/f"]);if(d.status!==0)throw new Error((d.stderr||"").trim()||"reg.exe add failed");u(e.exe.reg,["delete",W,"/v",h,"/f"]),te(),We(800);const f=Ne(e,a);return u(f[0],f.slice(1),{timeout:2e4}),{launcher:a.kind,wsl:!0,path:{added:!1,dir:_()}}}function Ce(e){u(e.exe.reg,["delete",y,"/v",h,"/f"]),w(ne(e).unix,{force:!0}),te()}function re(e){return u(e.exe.reg,["query",y,"/v",h]).status===0}function We(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{}}const B=()=>p.join(g.homedir(),".config","systemd","user","chatpanel-gateway.service");function Le({exec:e,display:t=me}={}){return`[Unit]
|
|
28
|
+
Description=${t}
|
|
29
29
|
After=network.target
|
|
30
30
|
|
|
31
31
|
[Service]
|
|
32
|
-
ExecStart=${
|
|
33
|
-
Restart=
|
|
32
|
+
ExecStart=${e}
|
|
33
|
+
Restart=always
|
|
34
|
+
RestartSec=2
|
|
34
35
|
|
|
35
36
|
[Install]
|
|
36
37
|
WantedBy=default.target
|
|
37
|
-
|
|
38
|
+
`}function Ue(){const e=x()?P():null;if(e)return Te(e);if(x()&&!m("/run/systemd/system"))throw new Error("WSL: Windows interop is off (cmd.exe cannot run from here) and systemd is not enabled in /etc/wsl.conf — nothing here can start the gateway at login. Enable one of them, or run `chatpanel-gateway` from a shell.");const{program:t,args:n}=R(),s=[t,...n].map(c=>/\s/.test(c)?`"${c}"`:c).join(" "),r=Le({exec:s}),i=B();b(p.dirname(i),{recursive:!0}),E(i,r),u("systemctl",["--user","daemon-reload"]);const o=u("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"systemctl enable failed")}function De(){const e=x()?P():null;e&&Ce(e),u("systemctl",["--user","disable","--now","chatpanel-gateway"]);const t=B();m(t)&&w(t)}function se(){const e=x()?P():null;return e&&re(e)?!0:(u("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function Oe({home:e=g.homedir(),platform:t=process.platform,env:n=process.env}={}){const s=t==="win32"?p.win32:p.posix;return t==="win32"?[s.join(n.LOCALAPPDATA||s.join(e,"AppData","Local"),"ChatPanel","chatpanel-bridge.exe")]:[s.join(e,".local","bin","chatpanel-bridge")]}const oe="net.chatpanel.bridge",G="ChatPanelBridge";function Be({platform:e=process.platform,runImpl:t=u,paths:n=Oe(),home:s=g.homedir()}={}){if(e==="win32"){t("reg",["delete",y,"/v",G,"/f"]),t("schtasks",["/End","/TN",G]),t("schtasks",["/Delete","/TN",G,"/F"]);for(const r of n){const i=`Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq '${r.replace(/'/g,"''")}' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;t("powershell.exe",["-NoProfile","-NonInteractive","-Command",i],{timeout:15e3})}return}if(e==="darwin"){t("launchctl",["bootout",`gui/${process.getuid?.()??""}/${oe}`]);const r=p.join(s,"Library","LaunchAgents",`${oe}.plist`);m(r)&&w(r,{force:!0})}else{t("systemctl",["--user","disable","--now","chatpanel-bridge.service"]);const r=p.join(s,".config","systemd","user","chatpanel-bridge.service");m(r)&&w(r,{force:!0})}for(const r of n)t("pkill",["-f",`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function T(e,t,n){if(process.platform==="darwin")return e();if(process.platform==="win32")return t();if(process.platform==="linux")return n();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`)}function Ge({env:e=process.env}={}){return{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:!0,env:e}}function Ye({winInstall:e=""}={}){try{if(process.platform==="darwin")return m(j())?(k("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${S}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux"){const t=x()?P():null;if(t&&re(t)){const n=D((r,i,o)=>u(r==="reg"?t.exe.reg:r,i,o));return n?(k("sh",["-c",`sleep 3; cd /mnt/c 2>/dev/null; exec cmd.exe /c ${(r=>`'${String(r).replace(/'/g,"'\\''")}'`)(n)}`],{detached:!0,stdio:"ignore"}).unref(),setTimeout(()=>process.exit(0),300),!0):!1}return m(B())?(k("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1}if(process.platform==="win32"){const t=D();if(!t)return!1;const n=p.dirname(process.execPath),s=`timeout /t 3 >nul & ${e?`${e} & `:""}${t} & del /q "${p.join(n,"chatpanel-gateway.old-*.exe")}" >nul 2>&1`,r={...process.env},i=Object.keys(r).find(o=>o.toLowerCase()==="path")||"Path";return r[i]=[n,...(r[i]||"").split(";").filter(Boolean)].filter((o,c,l)=>l.indexOf(o)===c).join(";"),k("cmd",["/c",s],Ge({env:r})).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function ze(){try{return T(()=>m(j()),J,se)}catch{return!1}}function ie(){try{return`http://127.0.0.1:${he().port||4320}`}catch{return"http://127.0.0.1:4320"}}async function ae(e=ie(),{timeoutMs:t=2e3}={}){try{const n=await fetch(`${e}/health`,{signal:AbortSignal.timeout(t)});if(!n.ok)return{ok:!1,url:e};const s=await n.json();return{ok:!0,url:e,version:String(s.version||""),managedBy:s.managedBy?String(s.managedBy):""}}catch{return{ok:!1,url:e}}}function ce(e=8){try{const t=pe(v().err,"utf8").trimEnd();return t?t.split(`
|
|
38
39
|
`).slice(-e).join(`
|
|
39
|
-
`):""}catch{return""}}async function
|
|
40
|
-
`).map(
|
|
41
|
-
`)}export{
|
|
40
|
+
`):""}catch{return""}}async function Xe({waitMs:e=4e4,version:t="",probe:n=ae,stop:s=ke,install:r=()=>T(ye,Ie,Ue),retire:i=Be,wait:o=l=>new Promise(a=>setTimeout(a,l)),now:c=()=>Date.now()}={}){i();const l=ie(),a=await n(l),d=a.ok&&a.managedBy&&a.managedBy!=="gateway"?a.managedBy:"",f=!!(a.ok&&t&&a.version&&a.version!==t),$=f&&!d;$&&(s(),await o(1200));const le=r()||{},H=$?t:"",F=V=>V.ok&&(!H||V.version===H),ue=c()+e;let A=await n(l);for(;!F(A)&&c()<ue;)await o(500),A=await n(l);const M=F(A);return{...le,health:A,ok:M,replaced:$?a.version:"",deferredTo:f?d:"",shadow:K(),errLog:M?"":ce()}}function Je(){return T(xe,Re,De)}function He(){return T($e,J,se)}async function Qe({platform:e=process.platform}={}){const t=[];let n=!1;try{n=He()}catch(c){t.push(`auto-start: ${c.message}`)}t.push(n?"auto-start: registered":"auto-start: not registered — `chatpanel-gateway --install`");const s=e==="linux"&&x()?P():null;if(e==="win32"||s){const c=s?(a,d,f)=>u(a==="reg"?s.exe.reg:a,d,f):u,l=n?D(c):"";l&&t.push(` launcher: ${l.length>120?`${l.slice(0,117)}…`:l}`),l.startsWith("wscript")&&!U(s?{systemRoot:s.sysUnix}:{})&&t.push(" ✕ VBScript is not installed on this Windows, so that launcher cannot run — `--install` again registers one that does not need it"),n&&Se(c)&&t.push(" ✕ switched off in Task Manager › Startup — `--install` again turns it back on"),s&&t.push(` WSL: starts at Windows login through wsl.exe (${process.env.WSL_DISTRO_NAME||"default distro"})`)}const r=_();r&&(e==="win32"?t.push(Ae(r)?`command: ${r} (on PATH)`:`command: ${r} — NOT on your PATH; \`--install\` adds it`):t.push(N(process.env.PATH||"",r,{platform:e})===null?`command: ${r} (on PATH)`:`command: ${r} — not on your PATH: export PATH="${r}:$PATH"`));const i=K({platform:e});i&&t.push(` ✕ ${i}/chatpanel-gateway is EARLIER on your PATH — that copy is what the name runs, not this v${C}`);const o=await ae();if(o.ok){const c=o.version===C?"":` — this command is v${C}; \`--install\` makes it the one that runs`;t.push(`running: v${o.version} at ${o.url}${o.managedBy?` (run by ${o.managedBy})`:""}${o.managedBy?"":c}`)}else{t.push(`running: nothing answers at ${o.url}`);const c=ce();c&&t.push(` last of ${v().err}:`,...c.split(`
|
|
41
|
+
`).map(l=>` ${l}`))}return t.join(`
|
|
42
|
+
`)}export{ge as DARWIN_LAUNCH_ENV,je as GATEWAY_ARGV_PATTERNS,_ as commandDir,ce as errLogTail,Xe as installService,x as isWsl,Le as linUnitText,we as macPlistText,K as pathShadow,N as pathWithDir,ae as probeHealth,Y as psEncode,I as realPath,R as resolveLaunch,Ye as restartService,Be as retireStandaloneBridge,_e as selfAndAncestors,ze as serviceRegistered,Qe as serviceReport,He as serviceStatus,Oe as standaloneCandidates,ee as stopOtherGateways,ke as stopService,Je as uninstallService,U as vbscriptAvailable,Ae as winCommandOnPath,Pe as winEnsureOnPath,z as winLauncher,Ge as winRelaunchOpts,Se as winStartupDisabled,Ee as winStopArgs,be as winStopScript};
|
package/src/shape.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
function
|
|
1
|
+
function c(e){return`${e}_${Date.now().toString(36)}${Math.random().toString(36).slice(2,10)}`}const u=()=>Math.floor(Date.now()/1e3),r=e=>`data: ${JSON.stringify(e)}
|
|
2
2
|
|
|
3
|
-
`,
|
|
4
|
-
`+
|
|
3
|
+
`,a=(e,o)=>`event: ${e}
|
|
4
|
+
`+r(o);function i(e){if(!e)return null;const o=p=>Math.max(0,Number(p)||0),n=o(e.cacheReadTokens),t=o(e.inputTokens)+n+o(e.cacheWriteTokens),s=o(e.outputTokens);return!t&&!s?null:{prompt_tokens:t,completion_tokens:s,total_tokens:t+s,...n?{prompt_tokens_details:{cached_tokens:n}}:{}}}function l(e){const o=c("chatcmpl"),n={id:o,object:"chat.completion.chunk",created:u(),model:e};return{contentType:"application/json",full(t,s){return JSON.stringify({id:o,object:"chat.completion",created:u(),model:e,choices:[{index:0,message:{role:"assistant",content:t},finish_reason:"stop"}],usage:i(s)||{}})},sseHead(){return r({...n,choices:[{index:0,delta:{role:"assistant"},finish_reason:null}]})},sseDelta(t){return r({...n,choices:[{index:0,delta:{content:t},finish_reason:null}]})},sseUsage(t){const s=i(t);return s?r({...n,choices:[],usage:s}):""},sseTail(t){return r({...n,choices:[{index:0,delta:{},finish_reason:"stop"}]})+this.sseUsage(t)+`data: [DONE]
|
|
5
5
|
|
|
6
|
-
`},sseActivity(
|
|
6
|
+
`},sseActivity(t){return r({...n,choices:[{index:0,delta:{},finish_reason:null}],chatpanel:{kind:"activity",event:t}})},sseToolCalls(t){return r({...n,choices:[{index:0,delta:{tool_calls:t.map((s,p)=>({index:p,id:s.id,type:"function",function:{name:s.name,arguments:s.arguments}}))},finish_reason:null}]})},sseToolFinish(t){return r({...n,choices:[{index:0,delta:{},finish_reason:"tool_calls"}]})+this.sseUsage(t)+`data: [DONE]
|
|
7
7
|
|
|
8
|
-
`}}}function
|
|
8
|
+
`}}}function _(e){const o=c("resp");return{contentType:"application/json",full(n,t){const s=i(t);return JSON.stringify({id:o,object:"response",created_at:u(),model:e,status:"completed",output:[{id:c("msg"),type:"message",role:"assistant",content:[{type:"output_text",text:n}]}],output_text:n,...s?{usage:{input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens,total_tokens:s.total_tokens}}:{}})},sseHead(){return a("response.created",{type:"response.created",response:{id:o,status:"in_progress",model:e}})},sseDelta(n){return a("response.output_text.delta",{type:"response.output_text.delta",delta:n})},sseTail(n){const t=i(n);return a("response.completed",{type:"response.completed",response:{id:o,status:"completed",model:e,...t?{usage:{input_tokens:t.prompt_tokens,output_tokens:t.completion_tokens,total_tokens:t.total_tokens}}:{}}})}}}function d(e){const o=c("msg");return{contentType:"application/json",full(n,t){const s=i(t);return JSON.stringify({id:o,type:"message",role:"assistant",model:e,content:[{type:"text",text:n}],stop_reason:"end_turn",stop_sequence:null,usage:s?{input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens}:{}})},sseHead(){return a("message_start",{type:"message_start",message:{id:o,type:"message",role:"assistant",model:e,content:[],stop_reason:null,usage:{}}})+a("content_block_start",{type:"content_block_start",index:0,content_block:{type:"text",text:""}})},sseDelta(n){return a("content_block_delta",{type:"content_block_delta",index:0,delta:{type:"text_delta",text:n}})},sseTail(n){const t=i(n);return a("content_block_stop",{type:"content_block_stop",index:0})+a("message_delta",{type:"message_delta",delta:{stop_reason:"end_turn"},usage:t?{input_tokens:t.prompt_tokens,output_tokens:t.completion_tokens}:{}})+a("message_stop",{type:"message_stop"})}}}function k(e,o){return e==="anthropic"?d(o):e==="responses"?_(o):l(o)}export{d as anthropicMessages,l as openaiChat,_ as openaiResponses,k as shaperFor,i as usageOf};
|
package/src/stt-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join as J}from"node:path";import{existsSync as Z,readdirSync as I}from"node:fs";import{randomUUID as ee}from"node:crypto";import{ensureLib as X,modelRoot as O}from"./ner-engine.js";import{runtimeDtype as D,runtimeName as B,DTYPE_SUFFIX as te}from"./model-runtime.js";import{verifyModelWeights as ne}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Y,isEnglishOnly as j,sttModelDtype as R,isKnownSttModel as re,sttModelEngine as z}from"./stt-models.js";import*as k from"./parakeet-engine.js";import*as L from"./diarize-engine.js";import{makeWarmTimer as H}from"./warm-timer.js";const p=16e3,oe=p,ie=2*p,ae=2,se=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function le(e,t){if(t>ae*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?se.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}let l="off",h=null,f=null,T=null,S=null,g=null,x=null,_=null;function ce(e=h||Y,t=R(e)||D()){if(z(e)==="parakeet-tdt")return k.parakeetOnDisk(e,k.parakeetDtype(t));const n=J(O(),...e.split("/"),"onnx");if(!Z(n))return!1;const r=te[t]??"";try{const o=I(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(a=>a===`decoder_model_merged${r}.onnx`||a===`decoder_model${r}.onnx`)}catch{return!1}}function Ne(){return l}function v(){return l==="ready"&&!!f}function Pe(){return g}function Fe(){return{configured:l!=="off",ok:v(),state:l,model:h,dtype:x,runtime:B(),error:T,warmMs:_?.warmMs??null}}function Re(){return!!_?.pending()}function A(){return M.size>0||l==="loading"||l==="downloading"}async function C({log:e=()=>{}}={}){if(A())return!1;_?.disarm();const t=f;if(f=null,S=null,x=null,g=null,T=null,l="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((_?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function W(e){return e.then(t=>(t&&!A()&&_?.arm(),t))}async function G(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(z(e)==="parakeet-tdt")return ue(e,{log:t,allowDownload:n,dtype:r});const o=f,a=h;let s;try{s=await X()}catch(m){return l="error",T=`engine load failed: ${m.message}`,t(`[stt] transformers.js not available (${m.message}) — dictation falls back to the browser engine`),!1}const i=(r&&r!=="auto"?r:null)||R(e)||D(),c=ce(e,i);if(s.env.allowRemoteModels=c?!1:!!n,!c&&!n)return l="error",T="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const y=s.env.remoteHost,w=!re(e);if(!c&&w)try{s.env.remoteHost="https://huggingface.co/"}catch{}l=c?"loading":"downloading",c||(g={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${w?", from Hugging Face":""})…`));try{const m=d=>{if(!d)return;const F=typeof d.progress=="number"?Math.round(d.progress):g?.pct??0;d.status==="progress"||d.status==="download"||d.status==="initiate"?g={model:e,file:d.file||g?.file||null,pct:F}:d.status==="done"&&d.file&&t(`[stt] fetched ${d.file}`)};let E;try{E=await s.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:m})}catch(d){if(c||w||!n)throw d;t(`[stt] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),s.env.remoteHost="https://huggingface.co/",s.env.allowRemoteModels=!0,E=await s.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:m})}if(!c)try{ne(e,{modelsDir:O(),log:t})}catch(d){try{await E.dispose?.()}catch{}throw d}if(f=E,h=e,l="ready",T=null,g=null,x=i,o&&o!==E)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (in-process, offline) — local dictation active`),!0}catch(m){return T=m.message,g=null,o?(f=o,h=a,l="ready"):l="error",t(`[stt] model load failed (${m.message})${o?" — keeping previous model":""}`),!1}finally{try{s.env.remoteHost=y}catch{}}}async function ue(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=f,a=h,s=k.parakeetDtype(r&&r!=="auto"?r:de()),u=k.parakeetOnDisk(e,s);if(!u&&!n)return l="error",T="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;l=u?"loading":"downloading",u||(g={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await k.loadRecognizer({modelId:e,dtype:s,allowDownload:n,log:t,onProgress:y=>{g={model:e,file:y.file||null,pct:typeof y.pct=="number"?y.pct:g?.pct??0}}}),c=async y=>({text:await i.transcribe(y)});if(c.__parakeet=!0,c.dispose=()=>i.dispose(),f=c,h=e,l="ready",T=null,g=null,x=s,o&&o!==c)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${s} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return T=i.message,g=null,o?(f=o,h=a,l="ready"):l="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}function de(){return k.PARAKEET_DEFAULT_DTYPE}function ze(e={}){if(S)return S;const t=typeof e.onLog=="function"?e.onLog:()=>{};return h=e.model||Y,l="loading",_=H({warmMs:e.warmMs,busy:A,log:t,unload:()=>C({log:t})}),S=W(G(h,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})),S}async function He(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;const r=z(e)==="parakeet-tdt"?k.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:k.PARAKEET_DEFAULT_DTYPE):t.dtype&&t.dtype!=="auto"?t.dtype:R(e)||D();return e===h&&v()&&x===r?!0:(_??=H({warmMs:t.warmMs,busy:A,log:n,unload:()=>C({log:n})}),W(G(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype})))}const fe=4,me=6e4,pe=1200,q=12,U=700,$=.008,he=30,M=new Map;let N=Promise.resolve();function Ce(){return M.size}const ge=300,ye=3e3;function _e(e){const t=Number(e);return Number.isFinite(t)?Math.min(ye,Math.max(ge,Math.round(t))):U}function Ue({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=U,interims:a=!0,remote:s=null}={}){if(M.size>=fe){const i=new Error("too many concurrent dictation sessions");throw i.code="too_many_sessions",i}const u={id:ee(),endSilenceMs:_e(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new L.Diarizer:null,remote:s||null,interims:a!==!1&&!s,chunks:[],samples:0,listeners:new Set,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return M.set(u.id,u),_?.disarm(),u.diarizer&&L.retain(),Q(u),{id:u.id}}function K(e){return M.get(String(e||""))||null}function Ke(e,t){const n=K(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function b(e,t){for(const n of e.listeners)try{n(t)}catch{}}function Q(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>Ee(e.id).catch(()=>{}),me),e.idleTimer.unref?.()}function Xe(e,t){const n=K(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,Q(n),we(n))}function Oe(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function we(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+pe-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,N=N.then(()=>V(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function Te(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function P(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let a=t;a<n;a++)r+=e[a]*e[a];return Math.sqrt(r/o)}function Me(e){const t=Math.round(.02*p);let n=0,r=e.length;for(let o=0;o+t<=e.length;o+=t)if(P(e,o,o+t)>=$){n=o;break}for(let o=e.length-t;o>=0;o-=t)if(P(e,o,o+t)>=$){r=o+t;break}return r>n?e.subarray(n,r):e}async function ke(e){try{const t=await X(),n=f?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>p*8?e.subarray(0,p*8):e,o=await f.processor(r),a=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),s=await f.model({...o,decoder_input_ids:a});let u=null,i=-1/0;for(const[c,y]of Object.entries(n.lang_to_id)){const w=Number(s.logits.data[y]);w>i&&(i=w,u=c)}return u?u.slice(2,-2):null}catch{return null}}async function V(e,{flush:t=!1}={}){if(e.closed&&!t||!e.remote&&!v()||!e.samples)return;e.lastDecodeAt=Date.now();const n=Te(e),r=Math.round((e.endSilenceMs||U)/1e3*p),o=n.length>r&&P(n,n.length-r)<$;if(P(n)<$){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(!e.interims&&!t&&!o&&n.length<q*p)return;if(!e.remote&&!e.lang&&!e.langTried&&!j(h)&&!f?.__parakeet&&n.length>=p){e.langTried=!0;const i=await ke(n);i&&(e.lang=i,b(e,{type:"language",lang:i}))}let a="";try{if(e.remote)a=(await e.remote.transcribe(n,{lang:e.lang})).text;else{const i=j(h)?{}:{language:e.lang||void 0,task:"transcribe"},c=await f(n,i);a=String(c?.text||"").trim()}}catch(i){b(e,{type:"error",code:"decode_failed",message:i.message,fatal:!1});return}if(!a)return;const s=n.length>=q*p,u=n.length>=he*p;if(t||o||s||u){const i=t?"flush":o?"silence":u?"overflow":"length",c=i==="flush"||i==="silence";e.chunks=[],e.samples=0,e.lastInterim="";const y=Me(n);if(le(a,y?y.length:0))return;let w=null;if(e.diarizer)try{const m=e.speakerLabel?null:y,E=m?await L.embed(m):null,d=!!m&&m.length<oe,F=!!m&&m.length<ie;w=e.diarizer.assign(E,{pinnedLabel:e.speakerLabel,weak:d,thin:F})}catch{}b(e,{type:"final",text:a,reason:i,endOfTurn:c,durationMs:Math.round(n.length/p*1e3),...w?{speaker:w}:{}})}else a!==e.lastInterim&&(e.lastInterim=a,b(e,{type:"interim",text:a}))}async function Ee(e){const t=K(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(N=N.then(()=>V(t,{flush:!0}).catch(()=>{})))}finally{b(t,{type:"end"}),t.listeners.clear(),M.delete(t.id),t.diarizer&&L.release(),M.size===0&&v()&&_?.arm()}return!0}function Be(){for(const e of M.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);M.clear(),_?.disarm(),_=null,l="off",h=null,f=null,T=null,S=null,g=null}function Ye(e,t="test/fake",{warmMs:n=null}={}){f=e,h=t,l=e?"ready":"off",n!==null&&(_=H({warmMs:n,busy:A,unload:()=>C()}),e&&_.arm())}export{p as SAMPLE_RATE,ie as THIN_SPEAKER_SAMPLES,oe as WEAK_SPEAKER_SAMPLES,Be as _reset,Ye as _setPipeForTest,_e as clampEndSilence,Ue as createSession,Ee as endSession,K as getSession,Fe as health,ze as init,v as isReady,le as looksHallucinated,ce as modelOnDisk,Pe as progress,Xe as pushAudio,D as runtimeDtype,B as runtimeName,Ce as sessionCount,He as setModel,Ne as state,Ke as subscribe,Oe as toFloat32,C as unload,Re as warmPending};
|
|
1
|
+
import{join as Z}from"node:path";import{existsSync as I,readdirSync as ee}from"node:fs";import{randomUUID as te}from"node:crypto";import{ensureLib as X,modelRoot as B}from"./ner-engine.js";import{runtimeDtype as L,runtimeName as Y,DTYPE_SUFFIX as ne}from"./model-runtime.js";import{verifyModelWeights as re}from"./model-integrity.js";import{DEFAULT_STT_MODEL as j,isEnglishOnly as W,sttModelDtype as R,isKnownSttModel as oe,sttModelEngine as z}from"./stt-models.js";import*as T from"./parakeet-engine.js";import*as E from"./diarize-engine.js";import{diarizeApproxMB as ie}from"./diarize-models.js";import{makeWarmTimer as H}from"./warm-timer.js";const p=16e3,ae=p,le=2*p,se=2,ce=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function ue(e,t){if(t>se*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?ce.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}let s="off",h=null,d=null,M=null,x=null,g=null,A=null,w=null;function fe(e=h||j,t=R(e)||L()){if(z(e)==="parakeet-tdt")return T.parakeetOnDisk(e,T.parakeetDtype(t));const n=Z(B(),...e.split("/"),"onnx");if(!I(n))return!1;const r=ne[t]??"";try{const o=ee(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(a=>a===`decoder_model_merged${r}.onnx`||a===`decoder_model${r}.onnx`)}catch{return!1}}function He(){return s}function v(){return s==="ready"&&!!d}function Ce(){return g}function Ue(){return{configured:s!=="off",ok:v(),state:s,model:h,dtype:A,runtime:Y(),error:M,warmMs:w?.warmMs??null}}function Ke(){return!!w?.pending()}function b(){return k.size>0||s==="loading"||s==="downloading"}async function C({log:e=()=>{}}={}){if(b())return!1;w?.disarm();const t=d;if(d=null,x=null,A=null,g=null,M=null,s="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((w?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function G(e){return e.then(t=>(t&&!b()&&w?.arm(),t))}async function q(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(z(e)==="parakeet-tdt")return de(e,{log:t,allowDownload:n,dtype:r});const o=d,a=h;let l;try{l=await X()}catch(m){return s="error",M=`engine load failed: ${m.message}`,t(`[stt] transformers.js not available (${m.message}) — dictation falls back to the browser engine`),!1}const i=(r&&r!=="auto"?r:null)||R(e)||L(),c=fe(e,i);if(l.env.allowRemoteModels=c?!1:!!n,!c&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const y=l.env.remoteHost,_=!oe(e);if(!c&&_)try{l.env.remoteHost="https://huggingface.co/"}catch{}s=c?"loading":"downloading",c||(g={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${_?", from Hugging Face":""})…`));try{const m=f=>{if(!f)return;const F=typeof f.progress=="number"?Math.round(f.progress):g?.pct??0;f.status==="progress"||f.status==="download"||f.status==="initiate"?g={model:e,file:f.file||g?.file||null,pct:F}:f.status==="done"&&f.file&&t(`[stt] fetched ${f.file}`)};let S;try{S=await l.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:m})}catch(f){if(c||_||!n)throw f;t(`[stt] mirror fetch failed (${String(f.message).slice(0,80)}) — retrying from Hugging Face…`),l.env.remoteHost="https://huggingface.co/",l.env.allowRemoteModels=!0,S=await l.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:m})}if(!c)try{re(e,{modelsDir:B(),log:t})}catch(f){try{await S.dispose?.()}catch{}throw f}if(d=S,h=e,s="ready",M=null,g=null,A=i,o&&o!==S)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (in-process, offline) — local dictation active`),!0}catch(m){return M=m.message,g=null,o?(d=o,h=a,s="ready"):s="error",t(`[stt] model load failed (${m.message})${o?" — keeping previous model":""}`),!1}finally{try{l.env.remoteHost=y}catch{}}}async function de(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=d,a=h,l=T.parakeetDtype(r&&r!=="auto"?r:me()),u=T.parakeetOnDisk(e,l);if(!u&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;s=u?"loading":"downloading",u||(g={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await T.loadRecognizer({modelId:e,dtype:l,allowDownload:n,log:t,onProgress:y=>{g={model:e,file:y.file||null,pct:typeof y.pct=="number"?y.pct:g?.pct??0}}}),c=async y=>({text:await i.transcribe(y)});if(c.__parakeet=!0,c.dispose=()=>i.dispose(),d=c,h=e,s="ready",M=null,g=null,A=l,o&&o!==c)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${l} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return M=i.message,g=null,o?(d=o,h=a,s="ready"):s="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}function me(){return T.PARAKEET_DEFAULT_DTYPE}const pe=30;function he({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:r=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof r=="number"&&r<=pe||e==="download"?{allowDownload:!0}:null}function U(e,{log:t=()=>{},warmMs:n}={}){const r=he({mode:e,onDisk:E.modelOnDisk(),ready:E.isReady(),approxMB:ie(E.activeModel())});r&&E.init({...r,warmMs:n,onLog:t})}function Oe(e={}){if(x)return x;const t=typeof e.onLog=="function"?e.onLog:()=>{};return h=e.model||j,s="loading",w=H({warmMs:e.warmMs,busy:b,log:t,unload:()=>C({log:t})}),x=G(q(h,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})).then(n=>(n&&U(e.speaker,{log:t,warmMs:e.warmMs}),n)),x}async function Xe(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;const r=z(e)==="parakeet-tdt"?T.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:T.PARAKEET_DEFAULT_DTYPE):t.dtype&&t.dtype!=="auto"?t.dtype:R(e)||L();if(e===h&&v()&&A===r)return U(t.speaker,{log:n,warmMs:t.warmMs}),!0;w??=H({warmMs:t.warmMs,busy:b,log:n,unload:()=>C({log:n})});const o=await G(q(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype}));return o&&U(t.speaker,{log:n,warmMs:t.warmMs}),o}const ge=4,ye=6e4,we=1200,Q=12,K=700,$=.008,_e=30,k=new Map;let P=Promise.resolve();function Be(){return k.size}const Me=300,ke=3e3;function Te(e){const t=Number(e);return Number.isFinite(t)?Math.min(ke,Math.max(Me,Math.round(t))):K}function Ye({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=K,interims:a=!0,remote:l=null}={}){if(k.size>=ge){const i=new Error("too many concurrent dictation sessions");throw i.code="too_many_sessions",i}const u={id:te(),endSilenceMs:Te(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new E.Diarizer:null,remote:l||null,interims:a!==!1&&!l,chunks:[],samples:0,listeners:new Set,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return k.set(u.id,u),w?.disarm(),u.diarizer&&E.retain(),V(u),{id:u.id}}function O(e){return k.get(String(e||""))||null}function je(e,t){const n=O(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function D(e,t){for(const n of e.listeners)try{n(t)}catch{}}function V(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>be(e.id).catch(()=>{}),ye),e.idleTimer.unref?.()}function We(e,t){const n=O(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,V(n),Ee(n))}function Ge(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function Ee(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+we-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,P=P.then(()=>J(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function Se(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function N(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let a=t;a<n;a++)r+=e[a]*e[a];return Math.sqrt(r/o)}function xe(e){const t=Math.round(.02*p);let n=0,r=e.length;for(let o=0;o+t<=e.length;o+=t)if(N(e,o,o+t)>=$){n=o;break}for(let o=e.length-t;o>=0;o-=t)if(N(e,o,o+t)>=$){r=o+t;break}return r>n?e.subarray(n,r):e}async function Ae(e){try{const t=await X(),n=d?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>p*8?e.subarray(0,p*8):e,o=await d.processor(r),a=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),l=await d.model({...o,decoder_input_ids:a});let u=null,i=-1/0;for(const[c,y]of Object.entries(n.lang_to_id)){const _=Number(l.logits.data[y]);_>i&&(i=_,u=c)}return u?u.slice(2,-2):null}catch{return null}}async function J(e,{flush:t=!1}={}){if(e.closed&&!t||!e.remote&&!v()||!e.samples)return;e.lastDecodeAt=Date.now();const n=Se(e),r=Math.round((e.endSilenceMs||K)/1e3*p),o=n.length>r&&N(n,n.length-r)<$;if(N(n)<$){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(!e.interims&&!t&&!o&&n.length<Q*p)return;if(!e.remote&&!e.lang&&!e.langTried&&!W(h)&&!d?.__parakeet&&n.length>=p){e.langTried=!0;const i=await Ae(n);i&&(e.lang=i,D(e,{type:"language",lang:i}))}let a="";try{if(e.remote)a=(await e.remote.transcribe(n,{lang:e.lang})).text;else{const i=W(h)?{}:{language:e.lang||void 0,task:"transcribe"},c=await d(n,i);a=String(c?.text||"").trim()}}catch(i){D(e,{type:"error",code:"decode_failed",message:i.message,fatal:!1});return}if(!a)return;const l=n.length>=Q*p,u=n.length>=_e*p;if(t||o||l||u){const i=t?"flush":o?"silence":u?"overflow":"length",c=i==="flush"||i==="silence";e.chunks=[],e.samples=0,e.lastInterim="";const y=xe(n);if(ue(a,y?y.length:0))return;let _=null;if(e.diarizer)try{const m=e.speakerLabel?null:y,S=m?await E.embed(m):null,f=!!m&&m.length<ae,F=!!m&&m.length<le;_=e.diarizer.assign(S,{pinnedLabel:e.speakerLabel,weak:f,thin:F})}catch{}D(e,{type:"final",text:a,reason:i,endOfTurn:c,durationMs:Math.round(n.length/p*1e3),..._?{speaker:_}:{}})}else a!==e.lastInterim&&(e.lastInterim=a,D(e,{type:"interim",text:a}))}async function be(e){const t=O(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(P=P.then(()=>J(t,{flush:!0}).catch(()=>{})))}finally{D(t,{type:"end"}),t.listeners.clear(),k.delete(t.id),t.diarizer&&E.release(),k.size===0&&v()&&w?.arm()}return!0}function qe(){for(const e of k.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);k.clear(),w?.disarm(),w=null,s="off",h=null,d=null,M=null,x=null,g=null}function Qe(e,t="test/fake",{warmMs:n=null,dtype:r=null}={}){d=e,h=t,s=e?"ready":"off",A=r,n!==null&&(w=H({warmMs:n,busy:b,unload:()=>C()}),e&&w.arm())}export{pe as AUTO_FETCH_MAX_MB,p as SAMPLE_RATE,le as THIN_SPEAKER_SAMPLES,ae as WEAK_SPEAKER_SAMPLES,qe as _reset,Qe as _setPipeForTest,Te as clampEndSilence,Ye as createSession,be as endSession,O as getSession,Ue as health,Oe as init,v as isReady,ue as looksHallucinated,fe as modelOnDisk,Ce as progress,We as pushAudio,L as runtimeDtype,Y as runtimeName,Be as sessionCount,Xe as setModel,he as speakerPlan,He as state,je as subscribe,Ge as toFloat32,C as unload,Ke as warmPending};
|
package/src/toolrelay.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{randomUUID as x}from"node:crypto";import{restoreDeep as f,redactText as m,createVault as I}from"@chatpanel/pii";import{PERMISSION_TOOL_NAME as T,isPermissionTool as y,permissionAllowed as w}from"@chatpanel/events/agent-permission.js";const a=new Map,g=(e,t)=>`gwtr_${e}_${t}`;function P(e){const t=/^gwtr_([^_]+)_(.+)$/.exec(String(e||""));return t?{gwId:t[1],toolId:t[2]}:null}function N(e){return(Array.isArray(e)?e:[]).filter(t=>t&&t.type==="function"&&t.function?.name&&!y(t.function.name)).map(t=>({name:t.function.name,description:t.function.description||"",parameters:t.function.parameters||{type:"object",properties:{}}}))}function $(e){return(Array.isArray(e)?e:[]).some(t=>t?.type==="function"&&y(t.function?.name))}const O=2e5;function k({vault:e,redactOpts:t,bridgeUrl:n,token:r,harness:l=null,idleMs:c=O}){const i=x().slice(0,8),s={id:i,reader:null,decoder:new TextDecoder,buf:"",bridgeSessionId:null,toolId:null,vault:e||I(),redactOpts:t||{tier:"basic"},bridgeUrl:n,token:r,harness:l,done:!1,idleMs:c,ttl:null,startedAt:Date.now(),rounds:0};return a.set(i,s),b(i),s}const q=e=>a.get(e);function b(e){const t=a.get(e);t&&(t.ttl&&clearTimeout(t.ttl),t.ttl=setTimeout(()=>
|
|
1
|
+
import{randomUUID as x}from"node:crypto";import{restoreDeep as f,redactText as m,createVault as I}from"@chatpanel/pii";import{PERMISSION_TOOL_NAME as T,isPermissionTool as y,permissionAllowed as w}from"@chatpanel/events/agent-permission.js";const a=new Map,g=(e,t)=>`gwtr_${e}_${t}`;function P(e){const t=/^gwtr_([^_]+)_(.+)$/.exec(String(e||""));return t?{gwId:t[1],toolId:t[2]}:null}function N(e){return(Array.isArray(e)?e:[]).filter(t=>t&&t.type==="function"&&t.function?.name&&!y(t.function.name)).map(t=>({name:t.function.name,description:t.function.description||"",parameters:t.function.parameters||{type:"object",properties:{}}}))}function $(e){return(Array.isArray(e)?e:[]).some(t=>t?.type==="function"&&y(t.function?.name))}const O=2e5;function k({vault:e,redactOpts:t,bridgeUrl:n,token:r,harness:l=null,idleMs:c=O}){const i=x().slice(0,8),s={id:i,reader:null,decoder:new TextDecoder,buf:"",bridgeSessionId:null,toolId:null,vault:e||I(),redactOpts:t||{tier:"basic"},bridgeUrl:n,token:r,harness:l,done:!1,idleMs:c,ttl:null,startedAt:Date.now(),rounds:0};return a.set(i,s),b(i),s}const q=e=>a.get(e);function b(e){const t=a.get(e);t&&(t.ttl&&clearTimeout(t.ttl),t.ttl=setTimeout(()=>_(e),t.idleMs),typeof t.ttl.unref=="function"&&t.ttl.unref())}function _(e){const t=a.get(e);if(t?.ttl&&clearTimeout(t.ttl),t?.reader)try{t.reader.cancel()}catch{}a.delete(e)}async function M(e,t){for(;;){let n;for(;(n=e.buf.indexOf(`
|
|
2
2
|
|
|
3
3
|
`))!==-1;){const c=e.buf.slice(0,n);e.buf=e.buf.slice(n+2);for(const i of c.split(`
|
|
4
|
-
`)){const s=i.trim();if(!s.startsWith("data:"))continue;const u=s.slice(5).trim();if(!u||u==="[DONE]")continue;let o;try{o=JSON.parse(u)}catch{continue}if(b(e.id),o.type==="delta"&&typeof o.text=="string")t.onText(o.text);else if(o.type==="permission_request"){e.bridgeSessionId=o.session,e.toolId=o.id,e.pendingPermission=!0;const{type:d,session:v,id:A,...p}=o,S={...p,input:f(p.input??{},e.vault)};return t.onToolRequest({name:T,restoredArgs:S,toolId:g(e.id,o.id)}),"parked"}else if(o.type==="tool_request"){e.bridgeSessionId=o.session,e.toolId=o.id,e.pendingPermission=!1;const d=e.harness?e.harness.toTool(o.name,o.input??{}):f(o.input??{},e.vault);return t.onToolRequest({name:o.name,restoredArgs:d,toolId:g(e.id,o.id)}),"parked"}else{if(o.type==="done")return e.done=!0,t.onDone?.(),"done";if(o.type==="error")return t.onError?.(new Error(o.error||"bridge error")),"done"}}}const{done:r,value:l}=await e.reader.read();if(r)return e.done=!0,t.onDone?.(),"done";e.buf+=e.decoder.decode(l,{stream:!0})}}async function J(e,t){const n=e.pendingPermission?
|
|
4
|
+
`)){const s=i.trim();if(!s.startsWith("data:"))continue;const u=s.slice(5).trim();if(!u||u==="[DONE]")continue;let o;try{o=JSON.parse(u)}catch{continue}if(b(e.id),o.type==="delta"&&typeof o.text=="string")t.onText(o.text);else if(o.type==="permission_request"){e.bridgeSessionId=o.session,e.toolId=o.id,e.pendingPermission=!0;const{type:d,session:v,id:A,...p}=o,S={...p,input:f(p.input??{},e.vault)};return t.onToolRequest({name:T,restoredArgs:S,toolId:g(e.id,o.id)}),"parked"}else if(o.type==="tool_request"){e.bridgeSessionId=o.session,e.toolId=o.id,e.pendingPermission=!1;const d=e.harness?e.harness.toTool(o.name,o.input??{}):f(o.input??{},e.vault);return t.onToolRequest({name:o.name,restoredArgs:d,toolId:g(e.id,o.id)}),"parked"}else{if(o.type==="done")return e.done=!0,t.onDone?.(),"done";if(o.type==="error")return t.onError?.(new Error(o.error||"bridge error")),"done";o.type==="usage"&&t.onUsage?.(o)}}}const{done:r,value:l}=await e.reader.read();if(r)return e.done=!0,t.onDone?.(),"done";e.buf+=e.decoder.decode(l,{stream:!0})}}async function J(e,t){const n=e.pendingPermission?h(t,e):m(typeof t=="string"?t:JSON.stringify(t),e.vault,e.redactOpts);e.pendingPermission=!1;const r=await fetch(`${e.bridgeUrl.replace(/\/$/,"")}/tool-result`,{method:"POST",headers:{"content-type":"application/json",...e.token?{authorization:`Bearer ${e.token}`}:{}},body:JSON.stringify({session:e.bridgeSessionId,id:e.toolId,result:n})});if(!r.ok)throw new Error(`bridge /tool-result HTTP ${r.status}`)}function h(e,t){let n=e;if(typeof n=="string")try{n=JSON.parse(n)}catch{n=null}if(!w(n)){const r=n&&typeof n=="object"&&typeof n.message=="string"&&n.message?m(n.message,t.vault,t.redactOpts):"";return{behavior:"deny",scope:"once",...r?{message:r}:{}}}return{behavior:"allow",scope:n.scope==="chat"?"chat":"once"}}export{O as RELAY_IDLE_MS,k as createRelaySession,J as deliverToolResult,_ as endRelaySession,q as getRelaySession,P as parseToolCallId,h as permissionResultOf,M as pumpBridgeStream,N as toolsToSpecs,b as touchRelaySession,$ as wantsApprovals};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.52.3";export{o as VERSION};
|