@chatpanel/gateway 0.99.0 → 0.100.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/native/darwin-arm64/chatpanel-apple-model +0 -0
- package/package.json +2 -2
- package/src/config.js +1 -1
- package/src/coreml-stt-engine.js +3 -0
- package/src/diarize-engine.js +1 -1
- package/src/ner-engine.js +1 -1
- package/src/segment-engine.js +1 -0
- package/src/server.js +31 -31
- package/src/stt-engine.js +1 -1
- package/src/stt-models.js +1 -1
- package/src/version.js +1 -1
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.100.0",
|
|
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": {
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
26
26
|
"@chatpanel/bridge": "^0.46.1",
|
|
27
|
-
"@chatpanel/events": "^0.
|
|
27
|
+
"@chatpanel/events": "^0.362.0",
|
|
28
28
|
"@chatpanel/pii": "^0.15.0",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
package/src/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as d,existsSync as l}from"node:fs";import{join as p}from"node:path";import A from"node:os";import{DEFAULT_MODEL as c}from"./models.js";import{DEFAULT_STT_MODEL as E}from"./stt-models.js";import{DEFAULT_DIARIZE_MODEL as m}from"./diarize-models.js";const s={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],maxBodyBytes:26214400,tls:{systemCa:!0},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:m,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 r(t,e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&t&&typeof t=="object"){const i={...t};for(const o of Object.keys(e))i[o]=r(t[o],e[o]);return i}return e===void 0?t:e}function
|
|
1
|
+
import{readFileSync as d,existsSync as l}from"node:fs";import{join as p}from"node:path";import A from"node:os";import{DEFAULT_MODEL as c}from"./models.js";import{DEFAULT_STT_MODEL as E}from"./stt-models.js";import{DEFAULT_DIARIZE_MODEL as m}from"./diarize-models.js";const s={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],maxBodyBytes:26214400,tls:{systemCa:!0},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:m,segment:!0,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 r(t,e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&t&&typeof t=="object"){const i={...t};for(const o of Object.keys(e))i[o]=r(t[o],e[o]);return i}return e===void 0?t:e}function R(t=process.env){let e=s;const i=t.CHATPANEL_GATEWAY_CONFIG||p(A.homedir(),".chatpanel","gateway.config.json");if(l(i))try{e=r(e,JSON.parse(d(i,"utf8")))}catch(a){throw new Error(`bad config file ${i}: ${a.message}`)}t.CHATPANEL_GATEWAY_HOST&&(e=r(e,{host:t.CHATPANEL_GATEWAY_HOST})),t.CHATPANEL_GATEWAY_PORT&&(e=r(e,{port:Number(t.CHATPANEL_GATEWAY_PORT)})),t.OPENAI_BASE_URL&&(e=r(e,{upstreams:{openai:{baseUrl:t.OPENAI_BASE_URL}}})),t.ANTHROPIC_BASE_URL&&(e=r(e,{upstreams:{anthropic:{baseUrl:t.ANTHROPIC_BASE_URL}}})),t.CHATPANEL_REDACTION_TIER&&(e=r(e,{redaction:{tier:t.CHATPANEL_REDACTION_TIER}}));for(const[a,n]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])t[n]&&(e=r(e,{registries:{[a]:t[n]}}));if(e.registries?.models&&!t.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=r(e,{port:s.port})),e}export{s as DEFAULTS,R as loadConfig};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{existsSync as A,statSync as C,mkdirSync as B,createWriteStream as W,renameSync as U}from"node:fs";import{join as k,dirname as J}from"node:path";import{spawn as V,execFile as _}from"node:child_process";import{Readable as G}from"node:stream";import{modelRoot as K}from"./ner-engine.js";import{findAppleHelper as Q}from"./apple-helper-fetch.js";const x="coreml/ane",L=Object.freeze(["BarkEncoder.mlpackage/Manifest.json","BarkEncoder.mlpackage/Data/com.apple.CoreML/model.mlmodel","BarkEncoder.mlpackage/Data/com.apple.CoreML/weights/weight.bin","decoder.npz","vocab.json"]),Y=Object.freeze(["coreml/LICENSE","coreml/NOTICE"]),P="0.4.0",q=10*6e4,I=16e3;function N(e){return k(K(),...String(e).split("/"))}function T(e){return k(N(e),...x.split("/"))}function X(e){const n=T(e);try{return L.every(o=>{const t=k(n,o);return A(t)&&C(t).size>0})}catch{return!1}}function Z(e,n=P){const o=/(\d+)\.(\d+)\.(\d+)/.exec(String(e||""));if(!o)return!1;const t=o.slice(1,4).map(Number),a=n.split(".").map(Number);for(let i=0;i<3;i++)if(t[i]!==a[i])return t[i]>a[i];return!0}function z(e,n=""){return e?`the Apple helper here is ${n||"older than "+P} and speech needs ${P} — run \`chatpanel-gateway --fetch-apple-helper\` (a source checkout: Install on the Apple on-device row rebuilds it)`:"the Apple helper is not installed — Install it on the Apple on-device row (Settings › Runtime), or run `chatpanel-gateway --fetch-apple-helper`"}async function ee(e,{fetchImpl:n=fetch}={}){const o=`https://huggingface.co/api/models/${e}/tree/main/${x}?recursive=true`,t=await n(o);if(!t.ok)throw new Error(`list ${x} → HTTP ${t.status}`);const a=await t.json(),i=`${x}/`,r=(Array.isArray(a)?a:[]).filter(s=>s&&s.type==="file"&&typeof s.path=="string"&&s.path.startsWith(i)&&!s.path.endsWith(".py")).map(s=>({path:s.path.slice(i.length),size:Number(s.size)||0})),c=L.filter(s=>!r.some(d=>d.path===s));if(c.length)throw new Error(`the repo's ${x} lacks ${c.join(", ")}`);return r}async function D(e,n,{onProgress:o,log:t,fetchImpl:a=fetch,label:i=n}={}){const r=await a(e,{redirect:"follow"});if(!r.ok||!r.body)throw new Error(`fetch ${i} → HTTP ${r.status}`);B(J(n),{recursive:!0});const c=Number(r.headers.get("content-length"))||0,s=`${n}.part`,d=W(s);let b=0,w=-1;const g=G.fromWeb(r.body);g.on("data",E=>{if(b+=E.length,c){const p=Math.round(b/c*100);p!==w&&(w=p,o?.({file:i,pct:p}))}}),await new Promise((E,p)=>{g.pipe(d),d.on("finish",E),d.on("error",p),g.on("error",p)}),U(s,n),t?.(`[speech] fetched ${i}`)}async function te(e,{onProgress:n,log:o,fetchImpl:t=fetch}={}){const a=T(e),i=await ee(e,{fetchImpl:t});for(const{path:r}of i){const c=k(a,r);A(c)&&C(c).size>0||(o?.(`[speech] downloading ${r}…`),await D(`https://huggingface.co/${e}/resolve/main/${x}/${r}`,c,{onProgress:n,log:o,fetchImpl:t,label:r}))}for(const r of Y){const c=k(N(e),...r.split("/"));if(!A(c))try{await D(`https://huggingface.co/${e}/resolve/main/${r}`,c,{log:o,fetchImpl:t,label:r})}catch(s){o?.(`[speech] no ${r} in the repo (${s.message})`)}}return a}function re(e,{execFileImpl:n=_}={}){return new Promise(o=>{try{n(e,["--version"],{timeout:1e4},(t,a)=>o(t?"":String(a||"").trim()))}catch{o("")}})}async function pe({modelId:e,allowDownload:n=!0,onProgress:o,log:t=()=>{},helper:a=Q(),units:i="ane",onExit:r=()=>{},spawnImpl:c=V,execFileImpl:s=_,fetchImpl:d=fetch,readyTimeoutMs:b=q}){if(!a)throw new Error(z(!1));const w=await re(a,{execFileImpl:s});if(!Z(w))throw new Error(z(!0,w));const g=X(e);if(!g&&!n)throw new Error("model not on disk and downloads disabled");const E=g?T(e):await te(e,{onProgress:o,log:t,fetchImpl:d}),p=c(a,["speech","--model",E,"--port","0","--units",i],{stdio:["ignore","pipe","pipe"]});let y="",M=!0,O=!1,R=!1;p.stderr?.on("data",u=>{for(const l of String(u).split(`
|
|
2
|
+
`))l.trim()&&(y=l.trim(),t(`[speech] ${y}`))});const v=await new Promise((u,l)=>{let m="";const $=setTimeout(()=>{try{p.kill()}catch{}l(new Error(`the speech helper did not come up within ${Math.round(b/6e4)} min${y?` (${y})`:""}`))},b);p.stdout?.on("data",f=>{m+=f;const h=m.indexOf(`
|
|
3
|
+
`);if(!(h<0)){clearTimeout($);try{const S=JSON.parse(m.slice(0,h));if(S&&S.ready&&S.port)return O=!0,u(S);l(new Error(`unexpected helper reply: ${m.slice(0,h)}`))}catch{l(new Error(`unexpected helper reply: ${m.slice(0,h)}`))}}}),p.on("error",f=>{clearTimeout($),l(new Error(`cannot start the speech helper: ${f.message}`))}),p.on("exit",f=>{clearTimeout($),M=!1;const h=`the speech helper exited (${f})${y?`: ${y}`:""}`;if(!O)return l(new Error(h));R||r(h)})}),H=`http://127.0.0.1:${v.port}`;async function j(u){if(!(u instanceof Float32Array)||u.length<400)return"";if(!M)throw new Error("the speech helper is not running");const l=Buffer.allocUnsafe(u.length*2);for(let f=0;f<u.length;f++){const h=Math.max(-1,Math.min(1,u[f]));l.writeInt16LE(h<0?Math.round(h*32768):Math.round(h*32767),f*2)}const m=await d(`${H}/v1/audio/transcriptions`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({pcm16:l.toString("base64"),sampleRate:I})}),$=await m.json().catch(()=>({}));if(!m.ok)throw new Error($?.error?.message||`speech helper → HTTP ${m.status}`);return String($.text||"").replace(/\s+/g," ").trim()}function F(){R=!0,M=!1;try{p.kill()}catch{}}return{transcribe:j,dispose:F,dir:E,windows:v.windows||[],port:v.port,pid:p.pid,version:w}}export{Y as COREML_LICENCE,x as COREML_PACKAGE,L as COREML_REQUIRED,q as READY_TIMEOUT_MS,I as SAMPLE_RATE,P as SPEECH_HELPER_MIN,N as coremlDir,X as coremlOnDisk,T as coremlPackageDir,te as ensureFiles,z as helperAdvice,re as helperVersion,Z as helperVersionOk,ee as listPackageFiles,pe as loadRecognizer};
|
package/src/diarize-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ensureLib as R,modelRoot as O}from"./ner-engine.js";import{join as
|
|
1
|
+
import{ensureLib as R,modelRoot as O,withModelSource as P}from"./ner-engine.js";import{join as q}from"node:path";import{existsSync as I,readdirSync as C}from"node:fs";import{makeWarmTimer as M}from"./warm-timer.js";import{createSpeakerClusterer as H}from"@chatpanel/events/speaker-cluster.js";import{DEFAULT_DIARIZE_MODEL as b,diarizeThreshold as N,isKnownDiarizeModel as W}from"./diarize-models.js";const V=b;let l="off",f=b,d=null,g=null,p=null,u=null,c=null,a=null,w=0,_=0;function X(){return f}function A(){return N(f)}function z(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function Y(){return l}function D(){return l==="ready"&&!!d&&!!g}function ee(){return c}function te(){return{configured:l!=="off",ok:D(),state:l,model:f,loaded:!!d,threshold:A(),error:p,warmMs:a?.warmMs??null}}function ne(){return!!a?.pending()}function re(){w++,a?.disarm()}function oe(){w=Math.max(0,w-1),w===0&&_===0&&D()&&a?.arm()}function h(){return w>0||_>0||l==="loading"||l==="downloading"}async function y({log:e=()=>{}}={}){if(h())return!1;a?.disarm();const t=d;if(d=null,g=null,u=null,c=null,p=null,l="off",t){try{await t.dispose?.()}catch{}e("[diarize] idle — speaker model unloaded (reloads on the next diarizing session)")}return!0}function Z(e=f,t=z()){const r=q(O(),...e.split("/"),"onnx");if(!I(r))return!1;const n=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return C(r).some(i=>i===`model${n}.onnx`)}catch{return!1}}async function $({log:e=()=>{},allowDownload:t=!0}={}){let r;try{r=await R()}catch(o){return l="error",p=o.message,e(`[diarize] engine unavailable (${o.message})`),!1}const n=f,i=Z(n);if(!i&&!t)return l="error",p="model not on disk and downloads disabled",!1;l=i?"loading":"downloading",i||(c={model:n,file:null,pct:0},e(`[diarize] downloading ${n} (one-time)…`));try{const{AutoModel:o,AutoProcessor:s}=r,k=m=>{if(!m)return;const L=typeof m.progress=="number"?Math.round(m.progress):c?.pct??0;(m.status==="progress"||m.status==="download"||m.status==="initiate")&&(c={model:n,file:m.file||c?.file||null,pct:L})},{processor:E,model:F}=await P({host:i?null:"https://huggingface.co/",allowRemote:!i},async()=>({processor:await s.from_pretrained(n,{progress_callback:k}),model:await o.from_pretrained(n,{dtype:z(),progress_callback:k})}));return g=E,d=F,l="ready",p=null,c=null,e(`[diarize] ready — ${n} @ ${z()} (speakers split at cosine ${A()})`),!0}catch(o){return p=o.message,c=null,l="error",e(`[diarize] load failed (${o.message}) — diarization off`),!1}}function le(e={}){if(u&&l!=="error")return u;l="loading";const t=typeof e.onLog=="function"?e.onLog:()=>{};return a=M({warmMs:e.warmMs,busy:h,log:t,unload:()=>y({log:t})}),u=S($({log:t,allowDownload:e.allowDownload!==!1})),u}function S(e){return e.then(t=>(t&&!h()&&a?.arm(),t))}async function ae(e,{log:t=()=>{}}={}){return W(e)?e===f?!0:h()?!1:(await y({log:()=>{}}),f=e,t(`[diarize] speaker model set to ${e} (loads on the next diarizing session)`),!0):!1}function ie({onLog:e}={}){return u=null,l="loading",a??=M({warmMs:void 0,busy:h,log:e||(()=>{}),unload:()=>y({log:e||(()=>{})})}),u=S($({log:e,allowDownload:!0})),u}const T=16e3;function x(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 v(e){try{const t=await g(e),r=await d(t),n=r.embeddings??r.logits??r.last_hidden_state;return n?.data?Float32Array.from(n.data):null}catch{return null}}async function se(e){if(!D()||!(e instanceof Float32Array)||!e.length)return null;_++;try{return await j(e)}finally{_--,h()||a?.arm()}}async function j(e){const t=2*T,r=Math.round(1.3*T);if(e.length<=Math.round(t*1.4)){const o=await v(e);return o?x(o):null}const n=[];for(let o=0;o+t<=e.length;o+=r){const s=await v(e.subarray(o,o+t));s&&n.push(x(s))}if(!n.length){const o=await v(e);return o?x(o):null}const i=new Float32Array(n[0].length);for(const o of n)for(let s=0;s<i.length;s++)i[s]+=o[s];return x(i)}function ue(){a?.disarm(),a=null,w=0,_=0,l="off",f=b,d=null,g=null,p=null,u=null,c=null}function ce(e,t,{warmMs:r=null}={}){d=e,g=t,l=e?"ready":"off",r!==null&&(a=M({warmMs:r,busy:h,unload:()=>y()}),e&&a.arm())}class fe{constructor({threshold:t=A(),maxSpeakers:r=12}={}){this.threshold=t,this.maxSpeakers=r,this._voices=H({threshold:t,maxSpeakers:r})}assign(t,r){return this._voices.assign(t,r)}get centroids(){return this._voices.toJSON().centroids}}export{V as DIARIZE_MODEL,fe as Diarizer,ue as _reset,ce as _setForTest,X as activeModel,A as activeThreshold,ie as download,se as embed,te as health,le as init,D as isReady,Z as modelOnDisk,ee as progress,oe as release,re as retain,ae as setModel,Y as state,y as unload,ne as warmPending};
|
package/src/ner-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import q from"node:os";import{join as O}from"node:path";import{existsSync as Q,mkdirSync as ct,readdirSync as K,readFileSync as ut}from"node:fs";import{DEFAULT_MODEL as V,isMirroredModel as ft}from"./models.js";import{isLoopbackHost as pt,isPrivateHost as dt,isMetadataHost as ht}from"@chatpanel/pii";import{recaseForDetection as mt}from"@chatpanel/pii/pii-detect.js";import{recasedSpanOk as gt}from"@chatpanel/pii/recased-spans.js";import{verifyModelWeights as yt}from"./model-integrity.js";import{runtimeName as wt}from"./model-runtime.js";import{nativeOrtFailure as _t}from"./ort.js";import{makeWarmTimer as X}from"./warm-timer.js";import{makeModelFileCache as xt}from"./model-file-cache.js";const C="https://dl.chatpanel.net/models/";function Mt(t=process.env){const e=t.CHATPANEL_MODEL_BASE_URL?"CHATPANEL_MODEL_BASE_URL":"registries.models",r=t.CHATPANEL_MODEL_BASE_URL||t.CHATPANEL_REGISTRY_MODELS;if(!r)return C;const n=c=>(console.warn(`[models] ignoring ${e} (${r}): ${c} — using ${C}`),C);let o;try{o=new URL(r)}catch{return n("not a valid URL")}if(o.protocol!=="http:"&&o.protocol!=="https:")return n(`scheme ${o.protocol} not allowed`);if(ht(o.hostname))return n("points at cloud metadata");const s=pt(o.hostname)||dt(o.hostname);return o.protocol==="http:"&&!s?n("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${o.origin} (${e}), not ${C}`),r.replace(/\/*$/,"/"))}const bt=Mt();let h="off",y=null,w=null,b=null,T=null,E=null,L=null,m=null,x=null,P=0,N=null;const g=new Map;function H(){return process.env.CHATPANEL_MODELS_DIR||O(q.homedir(),".chatpanel","models")}function R(t=y||V){const e=O(H(),...t.split("/"));return Q(O(e,"onnx","model_quantized.onnx"))||Q(O(e,"onnx","model.onnx"))}function Zt(){const t=H(),e=[];try{for(const r of K(t,{withFileTypes:!0}))if(r.isDirectory())for(const n of K(O(t,r.name),{withFileTypes:!0})){if(!n.isDirectory())continue;const o=`${r.name}/${n.name}`;R(o)&&Lt(O(t,r.name,n.name))&&e.push(o)}}catch{}return e}function Lt(t){try{return(JSON.parse(ut(O(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function It(){return h}function A(){return h==="ready"&&!!w}function te(){return{configured:h!=="off",ok:A(),state:h,model:y,error:b,runtime:wt(),dtype:w?"q8":null,stats:Pt(),companions:$t(),warmMs:x?.warmMs??null}}async function Tt(t,{signal:e,strict:r=!1}={}){if(!A())return[];if(e?.aborted)return[];const n=String(t||""),o=await Z(n,e);if(!o)return[];const s=[];for(const f of o||[]){if(I(f,r))continue;let i=String(f.word??"");const u=f.entity_group??f.entity??"ENTITY";if(i.startsWith("##")&&s.length&&s[s.length-1].type===u){s[s.length-1].value+=i.slice(2);continue}i=i.replace(/##/g,"").trim(),i&&s.push({value:i,type:u})}const c=new Set,l=[];for(const f of s){const i=Rt(n,Ht(n,f.value.trim()));if(i.length<=1)continue;const u=`${f.type}:${i.toLowerCase()}`;c.has(u)||(c.add(u),l.push({value:i,type:f.type}))}return l}async function Z(t,e){P++;try{return await St(t,e)}finally{P--,v()||x?.arm()}}async function St(t,e){const r=performance.now(),n=[],o=[{text:t,key:"orig"}];if(D){const s=mt(t);s.changed&&o.push({text:s.text,key:"recased"})}for(const{model:s,pipe:c}of nt())for(const l of o){let f=0;for(const i of Et(l.text,c.tokenizer)){if(e?.aborted)return null;const u=l.text.indexOf(i,f),d=await c(i,{aggregation_strategy:"simple"});for(const a of d||[])n.push({...a,_win:u<0?f:u,_winText:i,_model:s,_pass:l.key,_passText:l.text});u>=0&&(f=Math.max(f,u+1))}}return Ct(performance.now()-r,t.length,n.length),n}let D=!0;function ee(t){D=t!==!1}const I=(t,e)=>!e&&t._pass==="recased"&&!gt(String(t.word??"").replace(/##/g,""),t.entity_group??t.entity);async function ne(t,{signal:e,strict:r=!1}={}){if(!A())return[];const n=String(t||""),o=await Z(n,e);if(!o)return[];const s=[],c=new Set;let l=-1,f=-1,i=null,u=null;for(const a of o){if(I(a,r))continue;const p=String(a.word??"").replace(/##/g,"").trim();if(!p)continue;(a._win!==f||a._model!==i||a._pass!==u)&&(f=a._win,i=a._model,u=a._pass,l=a._win);const k=a._passText||n;let M=k.indexOf(p,l);if(M<0&&(M=k.indexOf(p,a._win)),M<0)continue;let S=M+p.length;l=S;const z=G=>!!G&&/[\p{L}\p{N}'’-]/u.test(G);for(;M>0&&z(n[M-1]);)M--;for(;S<n.length&&z(n[S]);)S++;const Y=String(a.entity_group??a.entity??"ENTITY"),B=`${M}:${S}:${Y}`;if(c.has(B))continue;c.add(B);const J=Number(a.score);s.push({value:n.slice(M,S),type:Y,start:M,end:S,score:Number.isFinite(J)?Math.max(0,Math.min(1,J)):1,model:a._model})}s.sort((a,p)=>a.start-p.start||a.end-p.end);const d=[];for(const a of s){const p=d[d.length-1];if(p&&p.type===a.type&&p.end===a.start){p.end=a.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,a.score);continue}d.push({...a})}return g.size||D?kt(d):d}const tt=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function Ot(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function F(t){const e=tt.indexOf(Ot(t.type));return e<0?tt.length:e}let $=[];function At(t){$=Array.isArray(t)?t.slice():[],m&&(m={...m,union:$.slice()})}function W(t){if(t.model===y)return-1;const e=$.indexOf(t.model);return e<0?$.length:e}function kt(t){const e=[...t].sort((n,o)=>n.start-o.start||o.end-n.end),r=[];for(const n of e){const o=r[r.length-1];if(o&&n.start<o.end){const s=l=>l.end-l.start;(F(n)<F(o)||F(n)===F(o)&&(s(n)>s(o)||s(n)===s(o)&&(W(n)<W(o)||W(n)===W(o)&&n.score>o.score)))&&(r[r.length-1]=n);continue}r.push(n)}return r}function oe(){const t=w?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const n=String(r).replace(/^[BIES]-/,"");n&&n!=="O"&&e.add(n)}return[...e]}function re(){const t=Number(w?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function $t(){return[...g].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function et(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===y)return!1;if(g.get(t)?.pipe)return!0;g.set(t,{pipe:null,state:R(t)?"loading":"downloading",error:null});try{const{pipe:o}=await st(t,{log:e,allowDownload:r});return g.set(t,{pipe:o,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(o){return g.set(t,{pipe:null,state:"error",error:o.message}),e(`[ner] companion ${t} failed to load (${o.message}) — the union runs without it`),!1}}async function se(t){const e=g.get(t);if(!e)return!1;g.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function nt(){const t=w?[{model:y,pipe:w}]:[];for(const[e,r]of g)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const vt=160,ot=256;function Et(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),o=Math.min(ot,Number.isFinite(r)&&r>0?r:ot)-8,s=i=>{try{return e(i).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=o)return[t];const c=[];let l=0,f=Math.max(64,Math.floor(o*3));for(;l<t.length;){let i=Math.min(t.length,l+f);if(i<t.length){const p=t.lastIndexOf(" ",i);p>l+f/2&&(i=p)}let u=t.slice(l,i);for(;s(u)>o&&u.length>32;){f=Math.max(32,Math.floor(u.length/2)),i=l+f;const p=t.lastIndexOf(" ",i);p>l+f/2&&(i=p),u=t.slice(l,i)}if(c.push(u),i>=t.length)break;const d=Math.max(l+1,i-vt),a=t.indexOf(" ",d);l=a>0&&a<i?a+1:i}return c}const Nt=200,_=[];function Ct(t,e,r){_.push({ms:t,chars:e,spans:r}),_.length>Nt&&_.shift()}function Pt(){if(!_.length)return{calls:0};const t=_.map(o=>o.ms).sort((o,s)=>o-s),e=o=>t[Math.min(t.length-1,Math.floor(o*t.length))],r=_.reduce((o,s)=>o+s.chars,0),n=_.reduce((o,s)=>o+s.ms,0);return{calls:_.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(_[_.length-1].ms),charsPerSec:n>0?Math.round(r/(n/1e3)):null}}function Ht(t,e){if(!e||t.includes(e))return e;const r=t.toLowerCase().indexOf(e.toLowerCase());return r<0?e:t.slice(r,r+e.length)}function Rt(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const n=c=>!!c&&/[\p{L}\p{N}'’-]/u.test(c);let o=r,s=r+e.length;for(;o>0&&n(t[o-1]);)o--;for(;s<t.length&&n(t[s]);)s++;return t.slice(o,s)}async function ie(t,e={}){let r="",n=!1;try{const s=JSON.parse(e.body||"{}");r=s.text||"",n=s.strict===!0}catch{}const o=await Tt(r,{signal:e.signal,strict:n});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function ae(){return L}async function rt(){if(E)return E;const t=H();try{ct(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}let r;try{r=await import("@huggingface/transformers")}catch(a){throw e?a:new Error(_t(a))}const{env:n,pipeline:o,Tensor:s,AutoModel:c,AutoProcessor:l,AutoTokenizer:f,AutoModelForSequenceClassification:i,LogLevel:u}=r;if(n.cacheDir=t,e&&u)try{n.logLevel=u.ERROR}catch{}n.localModelPath=t,e||(n.useCustomCache=!0,n.customCache=xt(t,{remoteHost:()=>n.remoteHost}));try{n.remoteHost=bt}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(e)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=e}catch{}return E={env:n,pipeline:(a,p,k={})=>o(a,p,k.progress_callback&&n.allowRemoteModels===!1?{...k,progress_callback:void 0}:k),Tensor:s,AutoModel:c,AutoProcessor:l,AutoTokenizer:f,AutoModelForSequenceClassification:i},E}function Dt({cores:t=q.availableParallelism?.()??q.cpus().length,wasm:e=!!globalThis.__CHATPANEL_WASM_PATHS__,env:r=process.env}={}){const n=Number(r.CHATPANEL_NER_THREADS);return{intraOpNumThreads:e?1:Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(8,t-1)),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}async function st(t,{log:e=()=>{},allowDownload:r=!0,onProgress:n=()=>{}}={}){const o=await rt(),s=R(t);if(o.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const c=o.env.remoteHost,l=!ft(t);if(!s&&l)try{o.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${l?", from Hugging Face":""})…`);try{const i={dtype:"q8",progress_callback:d=>{d&&(d.status==="progress"||d.status==="download"||d.status==="initiate"?n(d):d.status==="done"&&d.file&&e(`[ner] fetched ${d.file}`))},session_options:Dt()};let u;try{u=await o.pipeline("token-classification",t,i)}catch(d){if(s||l||!r)throw d;e(`[ner] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),o.env.remoteHost="https://huggingface.co/",o.env.allowRemoteModels=!0,u=await o.pipeline("token-classification",t,i)}if(!s)try{yt(t,{modelsDir:H(),log:e})}catch(d){try{await u.dispose?.()}catch{}throw d}return{pipe:u,haveLocal:s}}finally{try{o.env.remoteHost=c}catch{}}}async function it(t,{log:e=()=>{},allowDownload:r=!0}={}){const n=w,o=y;try{await rt()}catch(c){return h="error",b=`engine load failed: ${c.message}`,e(`[ner] transformers.js not available (${c.message}) — deterministic-only`),!1}const s=R(t);if(!s&&!r)return h="error",b="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;h=s?"loading":"downloading",s||(L={model:t,file:null,pct:0});try{const{pipe:c}=await st(t,{log:e,allowDownload:r,onProgress:l=>{L={model:t,file:l.file||L?.file||null,pct:typeof l.progress=="number"?Math.round(l.progress):L?.pct??0}}});if(w=c,y=t,h="ready",b=null,L=null,m&&(m={...m,model:t}),n&&n!==c)try{await n.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),v()||x?.arm(),!0}catch(c){return b=c.message,L=null,n?(w=n,y=o,h="ready"):h="error",e(`[ner] model load failed (${c.message})${n?" — keeping previous model":" — deterministic-only"}`),!1}}function Ft(t={}){if(T)return T;const e=typeof t.onLog=="function"?t.onLog:()=>{};m=t,y=t.model||V,h="loading";const r=t.allowDownload!==!1;return x=X({warmMs:t.warmMs,busy:v,log:e,unload:()=>at({log:e})}),T=it(y,{log:e,allowDownload:r}).then(async n=>{const o=Array.isArray(t.union)?t.union:[];At(o);for(const s of o)await et(s,{log:e,allowDownload:r});return A()&&!v()&&x?.arm(),n}),T}function v(){if(P>0||h==="loading"||h==="downloading")return!0;for(const t of g.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function at({log:t=()=>{}}={}){if(v())return!1;x?.disarm();const e=nt().map(r=>r.pipe);w=null,T=null,L=null,b=null,g.clear(),h=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((x?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function Wt(){try{h==="idle"&&(N||m)?await(N?N():Ft(m)):T&&await T,A()&&await lt()}catch{}return A()}let U=null;function lt(){const t=$.filter(e=>e&&e!==y&&!g.has(e));return t.length?(U||=(async()=>{const e=typeof m?.onLog=="function"?m.onLog:()=>{};for(const r of t)g.has(r)||(j?await j(r):await et(r,{log:e,allowDownload:m?.allowDownload!==!1}))})().catch(()=>{}).finally(()=>{U=null}),U):Promise.resolve()}let j=null;function le(t){j=t}async function ce(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},n=e.allowDownload!==!1;if(!t)return!1;if(t===y&&A())return!0;if(t===y&&h==="idle")return Wt();const o=g.get(t);if(o?.pipe){const c=w;if(w=o.pipe,y=t,h="ready",b=null,g.delete(t),c)try{await c.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),m&&(m={...m,model:t}),!0}const s=await it(t,{log:r,allowDownload:n});return s&&(m&&(m={...m,model:t}),await lt()),s}function ue(){h="off",y=null,w=null,b=null,T=null,E=null,L=null,_.length=0,g.clear(),D=!0,$=[],x?.disarm(),x=null,m=null,P=0,N=null,j=null,U=null}function fe(t,e){g.set(t,{pipe:e,state:"ready",error:null})}function pe(t,{model:e="test/model",warmMs:r=null,reload:n=null}={}){w=t,y=e,h="ready",b=null,_.length=0,n&&(N=n),r!==null&&(x=X({warmMs:r,busy:v,unload:()=>at()}),t&&x.arm())}export{ue as _reset,fe as _setCompanionForTest,le as _setCompanionLoaderForTest,pe as _setForTest,et as addCompanion,$t as companions,Tt as detect,ne as detectSpans,Wt as ensure,rt as ensureLib,ie as fetchAdapter,te as health,Ft as init,A as isReady,oe as labels,re as maxTokens,R as modelOnDisk,H as modelRoot,Zt as modelsOnDisk,ae as progress,se as removeCompanion,Mt as resolveModelHost,Dt as sessionOptionsFor,ee as setCaseRecovery,ce as setModel,At as setUnionOrder,It as state,Pt as stats,kt as unionSpans,at as unload,Et as windowsFor};
|
|
1
|
+
import q from"node:os";import{join as S}from"node:path";import{existsSync as K,mkdirSync as ut,readdirSync as V,readFileSync as ft}from"node:fs";import{DEFAULT_MODEL as X,isMirroredModel as pt}from"./models.js";import{isLoopbackHost as dt,isPrivateHost as mt,isMetadataHost as ht}from"@chatpanel/pii";import{recaseForDetection as gt}from"@chatpanel/pii/pii-detect.js";import{recasedSpanOk as yt}from"@chatpanel/pii/recased-spans.js";import{verifyModelWeights as wt}from"./model-integrity.js";import{runtimeName as _t}from"./model-runtime.js";import{nativeOrtFailure as Mt}from"./ort.js";import{makeWarmTimer as Z}from"./warm-timer.js";import{makeModelFileCache as xt}from"./model-file-cache.js";const H="https://dl.chatpanel.net/models/";function bt(t=process.env){const e=t.CHATPANEL_MODEL_BASE_URL?"CHATPANEL_MODEL_BASE_URL":"registries.models",r=t.CHATPANEL_MODEL_BASE_URL||t.CHATPANEL_REGISTRY_MODELS;if(!r)return H;const n=a=>(console.warn(`[models] ignoring ${e} (${r}): ${a} — using ${H}`),H);let o;try{o=new URL(r)}catch{return n("not a valid URL")}if(o.protocol!=="http:"&&o.protocol!=="https:")return n(`scheme ${o.protocol} not allowed`);if(ht(o.hostname))return n("points at cloud metadata");const s=dt(o.hostname)||mt(o.hostname);return o.protocol==="http:"&&!s?n("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${o.origin} (${e}), not ${H}`),r.replace(/\/*$/,"/"))}const Lt=bt();let m="off",y=null,w=null,b=null,T=null,C=null,L=null,h=null,M=null,N=0,E=null;const g=new Map;let I=Promise.resolve();function It({host:t=null,allowRemote:e=!1}={},r){const n=I.then(async()=>{const o=await z(),s=o.env.remoteHost,a=o.env.allowRemoteModels;try{o.env.allowRemoteModels=e,t&&(o.env.remoteHost=t)}catch{}try{return await r(o)}finally{try{o.env.remoteHost=s,o.env.allowRemoteModels=a}catch{}}});return I=n.catch(()=>{}),n}function P(){return process.env.CHATPANEL_MODELS_DIR||S(q.homedir(),".chatpanel","models")}function R(t=y||X){const e=S(P(),...t.split("/"));return K(S(e,"onnx","model_quantized.onnx"))||K(S(e,"onnx","model.onnx"))}function te(){const t=P(),e=[];try{for(const r of V(t,{withFileTypes:!0}))if(r.isDirectory())for(const n of V(S(t,r.name),{withFileTypes:!0})){if(!n.isDirectory())continue;const o=`${r.name}/${n.name}`;R(o)&&Tt(S(t,r.name,n.name))&&e.push(o)}}catch{}return e}function Tt(t){try{return(JSON.parse(ft(S(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function ee(){return m}function O(){return m==="ready"&&!!w}function ne(){return{configured:m!=="off",ok:O(),state:m,model:y,error:b,runtime:_t(),dtype:w?"q8":null,stats:Pt(),companions:$t(),warmMs:M?.warmMs??null}}async function At(t,{signal:e,strict:r=!1}={}){if(!O())return[];if(e?.aborted)return[];const n=String(t||""),o=await tt(n,e);if(!o)return[];const s=[];for(const f of o||[]){if(et(f,r))continue;let i=String(f.word??"");const u=f.entity_group??f.entity??"ENTITY";if(i.startsWith("##")&&s.length&&s[s.length-1].type===u){s[s.length-1].value+=i.slice(2);continue}i=i.replace(/##/g,"").trim(),i&&s.push({value:i,type:u})}const a=new Set,c=[];for(const f of s){const i=Ft(n,Rt(n,f.value.trim()));if(i.length<=1)continue;const u=`${f.type}:${i.toLowerCase()}`;a.has(u)||(a.add(u),c.push({value:i,type:f.type}))}return c}async function tt(t,e){N++;try{return await St(t,e)}finally{N--,$()||M?.arm()}}async function St(t,e){const r=performance.now(),n=[],o=[{text:t,key:"orig"}];if(F){const s=gt(t);s.changed&&o.push({text:s.text,key:"recased"})}for(const{model:s,pipe:a}of rt())for(const c of o){let f=0;for(const i of Et(c.text,a.tokenizer)){if(e?.aborted)return null;const u=c.text.indexOf(i,f),d=await a(i,{aggregation_strategy:"simple"});for(const l of d||[])n.push({...l,_win:u<0?f:u,_winText:i,_model:s,_pass:c.key,_passText:c.text});u>=0&&(f=Math.max(f,u+1))}}return Nt(performance.now()-r,t.length,n.length),n}let F=!0;function oe(t){F=t!==!1}const et=(t,e)=>!e&&t._pass==="recased"&&!yt(String(t.word??"").replace(/##/g,""),t.entity_group??t.entity);async function re(t,{signal:e,strict:r=!1}={}){if(!O())return[];const n=String(t||""),o=await tt(n,e);if(!o)return[];const s=[],a=new Set;let c=-1,f=-1,i=null,u=null;for(const l of o){if(et(l,r))continue;const p=String(l.word??"").replace(/##/g,"").trim();if(!p)continue;(l._win!==f||l._model!==i||l._pass!==u)&&(f=l._win,i=l._model,u=l._pass,c=l._win);const v=l._passText||n;let x=v.indexOf(p,c);if(x<0&&(x=v.indexOf(p,l._win)),x<0)continue;let A=x+p.length;c=A;const Y=Q=>!!Q&&/[\p{L}\p{N}'’-]/u.test(Q);for(;x>0&&Y(n[x-1]);)x--;for(;A<n.length&&Y(n[A]);)A++;const B=String(l.entity_group??l.entity??"ENTITY"),J=`${x}:${A}:${B}`;if(a.has(J))continue;a.add(J);const G=Number(l.score);s.push({value:n.slice(x,A),type:B,start:x,end:A,score:Number.isFinite(G)?Math.max(0,Math.min(1,G)):1,model:l._model})}s.sort((l,p)=>l.start-p.start||l.end-p.end);const d=[];for(const l of s){const p=d[d.length-1];if(p&&p.type===l.type&&p.end===l.start){p.end=l.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,l.score);continue}d.push({...l})}return g.size||F?kt(d):d}const nt=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function Ot(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function D(t){const e=nt.indexOf(Ot(t.type));return e<0?nt.length:e}let k=[];function vt(t){k=Array.isArray(t)?t.slice():[],h&&(h={...h,union:k.slice()})}function W(t){if(t.model===y)return-1;const e=k.indexOf(t.model);return e<0?k.length:e}function kt(t){const e=[...t].sort((n,o)=>n.start-o.start||o.end-n.end),r=[];for(const n of e){const o=r[r.length-1];if(o&&n.start<o.end){const s=c=>c.end-c.start;(D(n)<D(o)||D(n)===D(o)&&(s(n)>s(o)||s(n)===s(o)&&(W(n)<W(o)||W(n)===W(o)&&n.score>o.score)))&&(r[r.length-1]=n);continue}r.push(n)}return r}function se(){const t=w?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const n=String(r).replace(/^[BIES]-/,"");n&&n!=="O"&&e.add(n)}return[...e]}function ie(){const t=Number(w?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function $t(){return[...g].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function ot(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===y)return!1;if(g.get(t)?.pipe)return!0;g.set(t,{pipe:null,state:R(t)?"loading":"downloading",error:null});try{const{pipe:o}=await it(t,{log:e,allowDownload:r});return g.set(t,{pipe:o,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(o){return g.set(t,{pipe:null,state:"error",error:o.message}),e(`[ner] companion ${t} failed to load (${o.message}) — the union runs without it`),!1}}async function ae(t){const e=g.get(t);if(!e)return!1;g.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function rt(){const t=w?[{model:y,pipe:w}]:[];for(const[e,r]of g)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const Ct=160,st=256;function Et(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),o=Math.min(st,Number.isFinite(r)&&r>0?r:st)-8,s=i=>{try{return e(i).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=o)return[t];const a=[];let c=0,f=Math.max(64,Math.floor(o*3));for(;c<t.length;){let i=Math.min(t.length,c+f);if(i<t.length){const p=t.lastIndexOf(" ",i);p>c+f/2&&(i=p)}let u=t.slice(c,i);for(;s(u)>o&&u.length>32;){f=Math.max(32,Math.floor(u.length/2)),i=c+f;const p=t.lastIndexOf(" ",i);p>c+f/2&&(i=p),u=t.slice(c,i)}if(a.push(u),i>=t.length)break;const d=Math.max(c+1,i-Ct),l=t.indexOf(" ",d);c=l>0&&l<i?l+1:i}return a}const Ht=200,_=[];function Nt(t,e,r){_.push({ms:t,chars:e,spans:r}),_.length>Ht&&_.shift()}function Pt(){if(!_.length)return{calls:0};const t=_.map(o=>o.ms).sort((o,s)=>o-s),e=o=>t[Math.min(t.length-1,Math.floor(o*t.length))],r=_.reduce((o,s)=>o+s.chars,0),n=_.reduce((o,s)=>o+s.ms,0);return{calls:_.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(_[_.length-1].ms),charsPerSec:n>0?Math.round(r/(n/1e3)):null}}function Rt(t,e){if(!e||t.includes(e))return e;const r=t.toLowerCase().indexOf(e.toLowerCase());return r<0?e:t.slice(r,r+e.length)}function Ft(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const n=a=>!!a&&/[\p{L}\p{N}'’-]/u.test(a);let o=r,s=r+e.length;for(;o>0&&n(t[o-1]);)o--;for(;s<t.length&&n(t[s]);)s++;return t.slice(o,s)}async function le(t,e={}){let r="",n=!1;try{const s=JSON.parse(e.body||"{}");r=s.text||"",n=s.strict===!0}catch{}const o=await At(r,{signal:e.signal,strict:n});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function ce(){return L}async function z(){if(C)return C;const t=P();try{ut(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}let r;try{r=await import("@huggingface/transformers")}catch(l){throw e?l:new Error(Mt(l))}const{env:n,pipeline:o,Tensor:s,AutoModel:a,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:i,LogLevel:u}=r;if(n.cacheDir=t,e&&u)try{n.logLevel=u.ERROR}catch{}n.localModelPath=t,e||(n.useCustomCache=!0,n.customCache=xt(t,{remoteHost:()=>n.remoteHost}));try{n.remoteHost=Lt}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(e)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=e}catch{}return C={env:n,pipeline:(l,p,v={})=>o(l,p,v.progress_callback&&n.allowRemoteModels===!1?{...v,progress_callback:void 0}:v),Tensor:s,AutoModel:a,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:i,AutoModelForAudioFrameClassification:r.AutoModelForAudioFrameClassification},C}function Dt({cores:t=q.availableParallelism?.()??q.cpus().length,wasm:e=!!globalThis.__CHATPANEL_WASM_PATHS__,env:r=process.env}={}){const n=Number(r.CHATPANEL_NER_THREADS);return{intraOpNumThreads:e?1:Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(8,t-1)),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}async function it(t,{log:e=()=>{},allowDownload:r=!0,onProgress:n=()=>{}}={}){const o=await z(),s=R(t);if(o.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const a=o.env.remoteHost,c=!pt(t);if(!s&&c)try{o.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${c?", from Hugging Face":""})…`);try{const i={dtype:"q8",progress_callback:d=>{d&&(d.status==="progress"||d.status==="download"||d.status==="initiate"?n(d):d.status==="done"&&d.file&&e(`[ner] fetched ${d.file}`))},session_options:Dt()};let u;try{u=await o.pipeline("token-classification",t,i)}catch(d){if(s||c||!r)throw d;e(`[ner] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),o.env.remoteHost="https://huggingface.co/",o.env.allowRemoteModels=!0,u=await o.pipeline("token-classification",t,i)}if(!s)try{wt(t,{modelsDir:P(),log:e})}catch(d){try{await u.dispose?.()}catch{}throw d}return{pipe:u,haveLocal:s}}finally{try{o.env.remoteHost=a}catch{}}}async function at(t,{log:e=()=>{},allowDownload:r=!0}={}){const n=w,o=y;try{await z()}catch(a){return m="error",b=`engine load failed: ${a.message}`,e(`[ner] transformers.js not available (${a.message}) — deterministic-only`),!1}const s=R(t);if(!s&&!r)return m="error",b="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;m=s?"loading":"downloading",s||(L={model:t,file:null,pct:0});try{const{pipe:a}=await it(t,{log:e,allowDownload:r,onProgress:c=>{L={model:t,file:c.file||L?.file||null,pct:typeof c.progress=="number"?Math.round(c.progress):L?.pct??0}}});if(w=a,y=t,m="ready",b=null,L=null,h&&(h={...h,model:t}),n&&n!==a)try{await n.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),$()||M?.arm(),!0}catch(a){return b=a.message,L=null,n?(w=n,y=o,m="ready"):m="error",e(`[ner] model load failed (${a.message})${n?" — keeping previous model":" — deterministic-only"}`),!1}}function Wt(t={}){if(T)return T;const e=typeof t.onLog=="function"?t.onLog:()=>{};h=t,y=t.model||X,m="loading";const r=t.allowDownload!==!1;return M=Z({warmMs:t.warmMs,busy:$,log:e,unload:()=>lt({log:e})}),T=at(y,{log:e,allowDownload:r}).then(async n=>{const o=Array.isArray(t.union)?t.union:[];vt(o);for(const s of o)await ot(s,{log:e,allowDownload:r});return O()&&!$()&&M?.arm(),n}),T}function $(){if(N>0||m==="loading"||m==="downloading")return!0;for(const t of g.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function lt({log:t=()=>{}}={}){if($())return!1;M?.disarm();const e=rt().map(r=>r.pipe);w=null,T=null,L=null,b=null,g.clear(),m=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((M?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function Ut(){try{m==="idle"&&(E||h)?await(E?E():Wt(h)):T&&await T,O()&&await ct()}catch{}return O()}let U=null;function ct(){const t=k.filter(e=>e&&e!==y&&!g.has(e));return t.length?(U||=(async()=>{const e=typeof h?.onLog=="function"?h.onLog:()=>{};for(const r of t)g.has(r)||(j?await j(r):await ot(r,{log:e,allowDownload:h?.allowDownload!==!1}))})().catch(()=>{}).finally(()=>{U=null}),U):Promise.resolve()}let j=null;function ue(t){j=t}async function fe(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},n=e.allowDownload!==!1;if(!t)return!1;if(t===y&&O())return!0;if(t===y&&m==="idle")return Ut();const o=g.get(t);if(o?.pipe){const a=w;if(w=o.pipe,y=t,m="ready",b=null,g.delete(t),a)try{await a.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),h&&(h={...h,model:t}),!0}const s=await at(t,{log:r,allowDownload:n});return s&&(h&&(h={...h,model:t}),await ct()),s}function pe(){m="off",y=null,w=null,b=null,T=null,C=null,L=null,_.length=0,g.clear(),F=!0,k=[],M?.disarm(),M=null,h=null,N=0,E=null,j=null,U=null}function de(t,e){g.set(t,{pipe:e,state:"ready",error:null})}function me(t,{model:e="test/model",warmMs:r=null,reload:n=null}={}){w=t,y=e,m="ready",b=null,_.length=0,n&&(E=n),r!==null&&(M=Z({warmMs:r,busy:$,unload:()=>lt()}),t&&M.arm())}export{pe as _reset,de as _setCompanionForTest,ue as _setCompanionLoaderForTest,me as _setForTest,ot as addCompanion,$t as companions,At as detect,re as detectSpans,Ut as ensure,z as ensureLib,le as fetchAdapter,ne as health,Wt as init,O as isReady,se as labels,ie as maxTokens,R as modelOnDisk,P as modelRoot,te as modelsOnDisk,ce as progress,ae as removeCompanion,bt as resolveModelHost,Dt as sessionOptionsFor,oe as setCaseRecovery,fe as setModel,vt as setUnionOrder,ee as state,Pt as stats,kt as unionSpans,lt as unload,Et as windowsFor,It as withModelSource};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as $,readdirSync as D}from"node:fs";import{join as S}from"node:path";import{ensureLib as T,modelRoot as P,withModelSource as R}from"./ner-engine.js";import{runtimeDtype as x}from"./model-runtime.js";import{makeWarmTimer as M}from"./warm-timer.js";const A="onnx-community/pyannote-segmentation-3.0",N=6,O=16e3;let r="off",g=A,u=null,d=null,a=null,m=null,s=null,o=null,_=0,p=0,w=null;function B(){return g}function U(){return r}function h(){return r==="ready"&&!!u&&!!d}function W(){return s}function X(){return{configured:r!=="off",ok:h(),state:r,model:g,loaded:!!u,error:a,warmMs:o?.warmMs??null}}function y(){return _>0||p>0||r==="loading"||r==="downloading"}function H(){p++,o?.disarm()}function J(){p=Math.max(0,p-1),p===0&&_===0&&h()&&o?.arm()}async function b({log:e=()=>{}}={}){if(y())return!1;o?.disarm();const n=u;if(u=null,d=null,w=null,m=null,s=null,a=null,r="off",n){try{await n.dispose?.()}catch{}e("[segment] idle — model unloaded (reloads on the next diarizing session)")}return!0}function v(e=g,n=x()){const l=S(P(),...e.split("/"),"onnx");if(!$(l))return!1;const t=n==="fp32"?"":n==="q8"?"_quantized":`_${n}`;try{return D(l).some(f=>f===`model${t}.onnx`)}catch{return!1}}async function z({log:e=()=>{},allowDownload:n=!0}={}){let l;try{l=await T()}catch(i){return r="error",a=i.message,e(`[segment] engine unavailable (${i.message})`),!1}if(!l.AutoModelForAudioFrameClassification)return r="error",a="this transformers.js has no audio frame classification",e(`[segment] ${a}`),!1;const t=g,f=v(t);if(!f&&!n)return r="error",a="model not on disk and downloads disabled",!1;r=f?"loading":"downloading",f||(s={model:t,file:null,pct:0},e(`[segment] downloading ${t} (one-time)…`));try{const i=c=>{if(!c)return;const L=typeof c.progress=="number"?Math.round(c.progress):s?.pct??0;(c.status==="progress"||c.status==="download"||c.status==="initiate")&&(s={model:t,file:c.file||s?.file||null,pct:L})},{processor:k,model:E}=await R({host:f?null:"https://huggingface.co/",allowRemote:!f},async()=>({processor:await l.AutoProcessor.from_pretrained(t,{progress_callback:i}),model:await l.AutoModelForAudioFrameClassification.from_pretrained(t,{dtype:x(),progress_callback:i})}));return d=k,u=E,r="ready",a=null,s=null,e(`[segment] ready — ${t} @ ${x()} (speaker turns inside a segment)`),!0}catch(i){return a=i.message,s=null,r="error",e(`[segment] load failed (${i.message}) — one speaker per segment, as before`),!1}}function F(e){return e.then(n=>(n&&!y()&&o?.arm(),n))}function K(e={}){if(m&&r!=="error")return m;r="loading";const n=typeof e.onLog=="function"?e.onLog:()=>{};return o=M({warmMs:e.warmMs,busy:y,log:n,unload:()=>b({log:n})}),m=F(z({log:n,allowDownload:e.allowDownload!==!1})),m}async function Q(e){if(!h()||!(e instanceof Float32Array)||e.length<O/2)return null;_++;try{if(w)return await w(e);const n=await d(e),{logits:l}=await u(n),t=d.post_process_speaker_diarization(l,e.length);return Array.isArray(t?.[0])?t[0]:null}catch{return null}finally{_--,y()||o?.arm()}}function V(){o?.disarm(),o=null,p=0,_=0,r="off",g=A,u=null,d=null,a=null,m=null,s=null}function Y(e,{warmMs:n=null}={}){w=e||null,u=e?{dispose:async()=>{}}:null,d=e?{}:null,r=e?"ready":"off",n!==null&&(o=M({warmMs:n,busy:y,unload:()=>b()}),e&&o.arm())}export{A as DEFAULT_SEGMENT_MODEL,O as SAMPLE_RATE,N as SEGMENT_MODEL_APPROX_MB,V as _reset,Y as _setForTest,B as activeModel,X as health,K as init,h as isReady,v as modelOnDisk,W as progress,J as release,H as retain,Q as spans,U as state,b as unload};
|
package/src/server.js
CHANGED
|
@@ -1,64 +1,64 @@
|
|
|
1
|
-
import{createServer as
|
|
1
|
+
import{createServer as Fo}from"node:http";import{loadConfig as Jt}from"./config.js";import{startEntitlementRefresh as Wo,maybeRevalidate as Ko}from"./entitlement-refresh.js";import{redactSegments as Qe,segment as ct,rememberAnswer as zt}from"./redact.js";import{pipeRestoredStream as Qo,pipeRestoredOpenAIStream as Yo,makeTokenRestorer as Gt,restoreDeep as Zo}from"./stream.js";import{restoreText as Xo,gatedDictionary as qo,narrowSpecs as er,makeToolHarness as tr,placeholderToolNote as or,placeholderNote as rr,assertEndpointUrl as nr,capRunOptions as ar,isPaired as Ht}from"@chatpanel/pii";import{ensureGatewayToken as Oe,currentGatewayToken as De,isAdminAuthorized as V,callerTrustOf as Ce,setPinnedExtensionIds as sr,issuePairingCode as ir,claimPairingCode as lr}from"./gateway-token.js";import{createPairAsk as dr,nativeConfirm as cr}from"./pair-prompt.js";import{createEngineProbe as ur}from"./local-engine-probe.js";import{randomUUID as mr}from"node:crypto";import{installEgressLedger as pr,egressAudit as hr}from"./egress.js";import{trustSystemCertificates as yr,systemCaWanted as Ut,systemCaState as fr}from"./system-ca.js";import{initPolicy as gr,activePolicy as Ye,applyPolicyToConfig as Vt,managedSummary as Ie,PolicyLoadError as wr}from"./policy.js";import{routeAllowed as Ft,agentAllowed as br,egressAllowed as kr}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as Re}from"./bridge.js";import{secureFetch as Ze}from"./secure-fetch.js";import{fetchCard as Xe,forgetCard as vr,sendMessage as Sr,streamMessage as Tr,getTask as xr,cancelTask as _r,knownAgents as Or,A2AError as Wt}from"./a2a.js";import{streamBridgeChat as Kt,readBridgeToken as je,openBridgeChat as Er,acceptedBridgeToken as Qt}from"./bridge.js";import{createRelaySession as $r,getRelaySession as Yt,endRelaySession as Le,pumpBridgeStream as Pr,deliverToolResult as Zt,toolsToSpecs as Ar,wantsApprovals as Nr,parseToolCallId as Xt,touchRelaySession as qe}from"./toolrelay.js";import{shaperFor as ut}from"./shape.js";import{startNer as Br,ensureNer as et,unionForThisMachine as Mr,skippedCompanions as Dr}from"./ner.js";import{recommendDetector as qt}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Cr}from"./log.js";import{saveBackupSecret as Ir,clearBackupSecret as Rr,loadBackupSecret as mt,hasBackupSecret as eo}from"./history-store.js";import{createMemoryStore as jr}from"./memory-store.js";import{createPrefsStore as Lr}from"./prefs-store.js";import{agentCardFor as to,runHintFor as oo}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as Jr}from"@chatpanel/events/agent-thread.js";import{portClashPlan as zr,serviceManagerOf as Gr,STANDBY_POLL_MS as Hr}from"@chatpanel/events/service-standby.js";import{threadTarget as Ur,frameQuestion as Vr,wireMessages as Fr,appendExchange as Wr,MAX_MESSAGE as ro}from"@chatpanel/events/thread-send.js";import{researchStore as Kr,researchResponse as Qr}from"./research.js";import{createTeamStore as Yr,loadOrCreateKey as pt}from"./team-store.js";import{createScorecardStore as Zr}from"./scorecard-store.js";import{createEngineLedgerStore as Xr}from"./engine-ledger-store.js";import{createProjectStore as qr}from"./project-store.js";import{applicationsFor as en,recruitPass as tn}from"./recruiting.js";import{ensureBridge as on,holderOf as rn}from"./bridge-supervisor.js";import{checkForUpdate as nn,updateStatus as an,startUpdate as sn,updateJob as ln,installKind as dn}from"./update.js";import{confinedStatus as ht,confinedLine as cn}from"./confine.js";import{appleHelperWanted as un,findAppleHelper as yt}from"./apple-helper-fetch.js";import{createHistoryStore as mn}from"./sqlite-store.js";import{createEventStore as pn}from"./event-store.js";import{createLinkActivity as hn,linkSurface as yn,sseUsageTap as fn,usageOfBody as gn,GATEWAY_HOST as no}from"./link-activity.js";import{ingestCloudEvents as wn,cursorOf as ao}from"./event-sync.js";import{eventStats as bn,projectYear as kn}from"./event-stats.js";import{toCloudEvent as ft,ceHostOf as vn}from"./cloudevents.js";import{fusionsDocument as Sn,resolveFusionModel as Tn}from"./fusions.js";import{ingestBackups as gt}from"./backup-ingest.js";import{toSearchRecord as so}from"@chatpanel/events/library.js";import{deriveBackupKey as xn,openRecord as _n,keyCache as On,nodeCodec as En}from"@chatpanel/events/backup-envelope.js";import $n from"node:zlib";import*as R from"./ner-engine.js";import wt from"node:os";import{capabilitiesDocument as Pn,handleDetect as An}from"./capabilities.js";import{createExtractService as Nn}from"./extract/service.js";import{workerSandbox as Bn,disposeWorkerSandbox as Mn}from"./worker-sandbox.js";import{createRuntime as Dn,SERVICES as Cn}from"./runtime.js";import{createCapabilityProxy as In}from"./capability-proxy.js";import{createEmbeddedCapabilities as Rn}from"./capability-embedded.js";import{EMBEDDED_MODELS as jn,EMBEDDED_IDS as Ln}from"./embedded-models.js";import{handleExtract as Jn}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as zn}from"./extract-capability.js";import{createReader as Gn}from"./retrieval/read.js";import{createBrowserRelayHost as Hn}from"./browser-relay.js";import{createLinkHost as Un}from"./link-host.js";import{checkLinkRoute as Vn,tunnelHeader as Fn,LINK_TUNNEL_ROOM_PATH as Wn}from"@chatpanel/events/link-routes.js";import{linkCallerOf as io,linkDestinationAllowed as Kn,linkVia as Qn,partnerRunHint as Yn,PARTNER_APPROVAL_DECISIONS as lo,partnerFilePath as Zn}from"@chatpanel/events/link-scopes.js";import{listPartnerFiles as Xn,readPartnerFile as qn,writePartnerFile as ea,removePartnerFile as ta}from"./link-files.js";import{isPermissionTool as co}from"@chatpanel/events/agent-permission.js";import{createApprovalInbox as oa}from"./link-approvals.js";import{createSearcher as ra,toJinaSearch as na,SEARCH_DEFAULTS as aa}from"./retrieval/search.js";import{createSearxng as sa}from"./retrieval/search-searxng.js";import{searchEngines as ia}from"./retrieval/search-apis.js";import{toJinaText as la}from"./read-document.js";import*as P from"./stt-engine.js";import*as M from"./diarize-engine.js";import*as da from"./segment-engine.js";import{DIARIZE_MODEL_CATALOG as ca,DEFAULT_DIARIZE_MODEL as ua,isKnownDiarizeModel as uo}from"./diarize-models.js";import{providerOf as bt}from"./providers.js";import{createRemoteTranscriber as mo}from"./stt-remote.js";import{parseMultipart as ma,decodeAudioFile as pa}from"./audio-file.js";import{MODEL_CATALOG as po,isKnownModel as ho,isValidCustomModelId as yo,recommendFor as ha}from"./models.js";import{STT_MODEL_CATALOG as ya,isKnownSttModel as fa,isValidCustomSttId as ga,DEFAULT_STT_MODEL as tt,STT_DTYPES as wa,isValidDtype as ba,sttModel as ka,sttModelUnavailable as fo}from"./stt-models.js";import*as D from"./tts-engine.js";import{TTS_MODEL_CATALOG as go,TTS_VOICES as va,isKnownTtsModel as Sa,isValidCustomTtsId as Ta,isKnownVoice as wo,isValidVoiceId as bo,DEFAULT_TTS_MODEL as ko,DEFAULT_TTS_VOICE as _e,TTS_DTYPES as xa,isValidTtsDtype as _a,MAX_TTS_CHARS as vo,ttsModelHasCustomVoices as Oa,resolveDefaultModel as So,POCKET_VOICES as Ea,DEFAULT_POCKET_VOICE as ot,isPocketVoice as rt,ttsModelEngine as nt}from"./tts-models.js";import{ttsDestination as $a,synthesizeRemote as Pa,isValidRemoteVoice as Aa}from"./tts-remote.js";import{rawOrtAvailable as kt}from"./ort.js";import*as me from"./tts-voices.js";import{resolveTtsVoice as Na}from"./tts-voice-resolve.js";import{resolvePro as Te,checkQuota as Ba,consume as Ma,usage as Da}from"./freegate.js";import{publicConfig as To,applyConfigPatch as Ca,registryChildEnv as Ia,applyNerModelSelection as xo,persistConfig as ke,configPath as se,bridgeAgentOptions as _o,PERMISSION_MODES as Ra,sandboxEnvFor as ja,sandboxProblems as La}from"./configstore.js";import Je from"node:path";import{resolveDestination as at,aggregateModelsAsync as Ja,listDestinations as za,ensureModelCatalog as Ga,agentOwnsModel as Ha}from"./router.js";import{makeAccessEvent as Oo}from"./observability.js";import{createPersistentAccessLog as Ua}from"./access-log-store.js";import{planQueries as Va,multiSearch as Fa}from"./rrf.js";import*as vt from"./openai.js";import*as Eo from"./responses.js";import*as St from"./anthropic.js";import{closeAndExit as Wa}from"./shutdown.js";import{VERSION as ie}from"./version.js";import{VERSION as al}from"./version.js";const j=await mn(),xe=new Set;function ze({ids:t=[]}={}){const c=j.lossless;if(!c||!xe.size)return;const u=JSON.stringify({newest:c.newest,rev:c.rev,size:c.size,ids:t.slice(0,50),at:Date.now()});for(const m of xe)try{m.write(`event: records
|
|
2
2
|
data: ${u}
|
|
3
3
|
|
|
4
|
-
`)}catch{
|
|
4
|
+
`)}catch{xe.delete(m)}}setInterval(()=>{for(const t of xe)try{t.write(`: ping
|
|
5
5
|
|
|
6
|
-
`)}catch{
|
|
7
|
-
data: ${JSON.stringify(
|
|
6
|
+
`)}catch{xe.delete(t)}},25e3).unref?.();const Y=await pn(),Tt=hn({store:Y,log:t=>console.log(t)}),Ee=new Set;Y?.watch(t=>{if(!Ee.size)return;const c=`event: cloudevent
|
|
7
|
+
data: ${JSON.stringify(ft(t))}
|
|
8
8
|
|
|
9
|
-
`;for(const u of
|
|
9
|
+
`;for(const u of Ee)try{u.write(c)}catch{Ee.delete(u)}}),setInterval(()=>{for(const t of Ee)try{t.write(`: ping
|
|
10
10
|
|
|
11
|
-
`)}catch{
|
|
11
|
+
`)}catch{Ee.delete(t)}},25e3).unref?.();const ye=await jr(),le=Lr(),Ne=Zr({key:pt()}),Be=Xr({key:pt()}),pe=qr({key:pt()}),Z=Yr({scorecards:Ne,engines:Be}),xt=new Set,$o=(t,c)=>{for(const m of xt)try{m({applied:t,by:c,revision:le.revision})}catch{}const u=JSON.stringify({revision:le.revision,applied:(t||[]).slice(0,50),by:c||"",at:Date.now()});for(const m of xe)try{m.write(`event: prefs
|
|
12
12
|
data: ${u}
|
|
13
13
|
|
|
14
|
-
`)}catch{
|
|
14
|
+
`)}catch{xe.delete(m)}},_t=Ua(),Po=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Ka=16,Qa=/^mcp[_-]/i,Ao=t=>t&&t.function&&t.function.name||t&&t.name||"",Ya=t=>t&&t.function&&t.function.description||t&&t.description||"";function No(t){return typeof t=="string"?t:Array.isArray(t)?t.map(c=>typeof c=="string"?c:c&&(c.text||c.content)||"").join(" "):""}function Za(t,c){if(!t)return"";if(c==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(f=>No(f&&(f.content??f))).join(" "):""}const u=Array.isArray(t.messages)?t.messages:[];for(let m=u.length-1;m>=0;m--)if(u[m]&&u[m].role==="user")return No(u[m].content);return""}const Bo=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function st(t){if(!t)return!1;const c=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return c==="localhost"||c==="127.0.0.1"||c==="::1"}function Xa(t,c){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(c.allowedOrigins)&&c.allowedOrigins.includes(t)}function qa(t,c){t.setHeader("Access-Control-Allow-Origin",c||"*"),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 Mo=Date.now();function es(t){if(!t)return"";const c={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(u=>`${c[u]||u} ${t[u]}ms`).join(" · ")}function ts(t){const c=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return c?{kind:c[1],id:c[2],...c[3]?{model:c[3]}:{}}:null}function os(t){const c=performance.now(),u={};let m=!1;const f=(y,$)=>{u[y]=Math.round($*10)/10};return{meta:{},timings:u,mark:f,lap(y,$){f(y,performance.now()-$)},clock(){return performance.now()},commit(){if(m)return;m=!0,f("total",performance.now()-c);const y={...this.meta,timings:u};setImmediate(()=>{t(y),console.log(`[gateway] model=${y.model||"-"} → ${y.dest?`${y.dest}(${y.type})`:"none"} · ${y.redaction==="off"?"redaction OFF (client request)":`redacted ${y.redacted||0}`}${y.sanitized?` · scrubbed ${y.sanitized} hidden`:""}${y.narrowed?` · narrowed -${y.narrowed}`:""} · ${es(u)}`)})}}}function Do(t,c){if(!t||!t.byToken||c!=="types"&&c!=="values")return;const u=[];for(const[m,f]of t.byToken){const y=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),$=y?y[1]:"PII",B=m.replace(/^\[\[|\]\]$/g,"");u.push(c==="values"?{token:B,type:$,value:f}:{token:B,type:$})}return u}function rs(t,c,u){return St.matches(t)||"anthropic-version"in c?{kind:"anthropic",adapter:St,redactable:St.matches(t),base:u.upstreams?.anthropic?.baseUrl}:Eo.matches(t)?{kind:"responses",adapter:Eo,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:vt,redactable:vt.matches(t),base:u.upstreams?.openai?.baseUrl}}function Ot(t,c){const u=String(t||"");if(Po.has(u))return{agent:u,agentModel:""};const m=u.indexOf("/");if(m>0){const f=u.slice(0,m);if(Po.has(f))return{agent:f,agentModel:u.slice(m+1)}}return{agent:c.bridge.agent,agentModel:""}}function Co(t,c){return Ot(t,c).agent}function ns(t,c){if(c!=="openai"||!t)return!1;const u=vt.extractLatestToolResult(t);if(!u)return!1;const m=Xt(u.tool_call_id);return!!(m&&Yt(m.gwId))}function as(t,c){try{const u=new URL(t),m=u.hostname.replace(/^\[|\]$/g,""),f=m==="127.0.0.1"||m==="localhost"||m==="::1",y=u.port||(u.protocol==="https:"?"443":"80");return f&&String(y)===String(c.port)}catch{return!1}}const ss=25*1024*1024;async function T(t,c){const u=[];let m=0;for await(const f of t){if(m+=f.length,c&&m>c){const y=new Error("payload too large");throw y.code=413,y}u.push(f)}return Buffer.concat(u)}function a(t,c,u){t.writeHead(c,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function Io(t){const c=t.redaction?.detection?.url;return!c||t.redaction?.detection?.backend==="off"?null:c}function Et(t){const c=t?.redaction?.detection,u=t?.redaction?.tier==="full"?"full":"basic";if(c&&c.backend&&c.backend!=="off")return{source:"external",backend:c.backend,state:"external",model:c.model||null,ready:!0,tier:u,coverage:u==="full"?"names":"patterns"};const m=R.health(),f=m.ok&&u==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:R.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:f,tier:u,coverage:f?"names":"patterns"}}async function Ro(t){if(R.state()!=="off"){const u=R.health();return{configured:u.configured,ok:u.ok,state:u.state,model:u.model,error:u.error||null,url:u.configured?`http://${t.host}:${t.port}/ner`:null,stats:u.stats,companions:u.companions}}const c=Io(t);if(!c)return{configured:!1,ok:!1,url:null,model:null};try{const u=await Ze(c.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:c,model:null};const m=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:c,model:m.model||null}}catch{return{configured:!0,ok:!1,url:c,model:null}}}function is(t,c){const u={};for(const[m,f]of Object.entries(t)){const y=m.toLowerCase();y.startsWith("x-chatpanel-")||Bo.has(y)||(u[m]=f)}u["accept-encoding"]="identity";try{u.host=new URL(c).host}catch{}return u}async function jo(t,c,u,m){const f=Gt(c.vault),y=Pt();t.on("close",()=>{t.writableFinished||Le(c.id)});const $=c.linkTurn||null,B=m?m.clock():0;let O=B,v=!0;const _=()=>{m&&v&&(m.lap("upstream",B),O=m.clock(),v=!1)};let C="";const J=()=>{c.redaction&&C&&zt(C,c.redaction),C=""};let U=null;const E={onText:H=>{_(),qe(c.id);const z=f.push(H);z&&(C+=z,t.write(u.sseDelta(z)))},onToolRequest:({name:H,restoredArgs:z,toolId:oe})=>{if(_(),qe(c.id),c.ownerApprovals&&co(H)){U=z;return}const X=f.flush();X&&(C+=X,t.write(u.sseDelta(X))),t.write(u.sseToolCalls([{id:oe,name:H,arguments:JSON.stringify(z)}])),t.write(u.sseToolFinish(y.value)),m&&m.lap("stream",O),t.end(),m?.commit(),J()},onDone:()=>{const H=f.flush();H&&(C+=H,t.write(u.sseDelta(H))),t.write(u.sseTail(y.value)),m&&m.lap("stream",O),t.end(),$?.end("ok"),Le(c.id),m?.commit(),J(),$t(c)},onError:H=>{t.write(`data: ${JSON.stringify({error:{message:H.message,type:"bridge_error"}})}
|
|
15
15
|
|
|
16
|
-
`),t.end(),$?.end("error",{code:"bridge_error"}),Le(
|
|
16
|
+
`),t.end(),$?.end("error",{code:"bridge_error"}),Le(c.id),m?.commit(),$t(c)},onUsage:H=>{y.add(H),$?.add(H)}};for(;;){if(U=null,await Pr(c,E)!=="parked"||!U)return;const z=c.ownerApprovals,oe=new AbortController,X=()=>oe.abort();t.once("close",X);const K=setInterval(()=>{qe(c.id),t.writableEnded||t.write(`: waiting for the owner’s approval
|
|
17
17
|
|
|
18
|
-
`)},15e3);K.unref?.();let
|
|
18
|
+
`)},15e3);K.unref?.();let de;try{de=await z.inbox.ask(U,{partner:z.partner,device:z.device,conversation:z.conversation,signal:oe.signal})}finally{clearInterval(K),t.off("close",X)}if(oe.signal.aborted||t.writableEnded){$t(c);return}try{await Zt(c,JSON.stringify(de))}catch(Q){E.onError(Q);return}}}function $t(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function ls(t,c,{kind:u,adapter:m,agent:f,run:y=null,owner:$=null,linkTurn:B=null},O,v,_,C,J,U=null,E=null){const{messages:H,system:z}=m.toTurn(O),{agentModel:oe}=Ot(O?.model,_),X=_o(_,{...oe?{model:oe}:{},...y||{}}),K=je(_.bridge.token),de=ut(u,O?.model||f),Q={tier:_.redaction.tier==="full"?"full":"basic",dictionary:qo(_.redaction,C),entities:[]},F=await Re(_),I=$r({vault:v,redactOpts:Q,bridgeUrl:F,token:K,harness:U});$&&(I.ownerApprovals={...$,conversation:$.conversation||`partner.${$.device}.turn-${I.id}`,turnScoped:!$.conversation}),B&&(I.linkTurn=B,I.onEnd=()=>B.end("aborted")),v&&(I.redaction=_.redaction);let n;try{n=await Er({bridgeUrl:F,agent:f,token:K,messages:H,system:z,specs:Ar(J),options:X,signal:void 0,approvals:!!$||Nr(J)})}catch(o){return B?.end("error",{code:"bridge_error"}),Le(I.id),E?.commit(),a(c,502,{error:{message:`bridge: ${o.message}`,type:"bridge_error"}})}return I.reader=n.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(de.sseHead()),jo(c,I,de,E)}async function ds(t,c,u,m,f=null){qe(c.id),c.rounds=(c.rounds||0)+1;try{const $=f?f.clock():0;await Zt(c,u),f&&f.lap("redact",$)}catch($){return c.linkTurn?.end("error",{code:"tool_result"}),Le(c.id),f?.commit(),a(t,502,{error:{message:`tool-result: ${$.message}`,type:"bridge_error"}})}const y=ut("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(y.sseHead()),jo(t,c,y,f)}function Pt(){let t=!1;const c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const m of Object.keys(c))c[m]+=Math.max(0,Number(u?.[m])||0)},get value(){return t?c:null}}}async function cs(t,c,{kind:u,adapter:m,redactable:f,pathname:y,agentOverride:$,harness:B,trace:O,run:v=null,owner:_=null,link:C=null},J,U,E,H){if(!f)return O?.commit(),a(c,404,{error:`endpoint ${y} not supported by the bridge backend`});if(u==="openai"){const k=m.extractLatestToolResult(J);if(k){const ne=Xt(k.tool_call_id),he=ne&&Yt(ne.gwId);if(he)return ds(c,he,k.content,J?.model,O)}const re=m.extractTools(J);if((re.length||_)&&J?.stream===!0){const ne=$||Co(J?.model,E),he=C?Tt.begin({...C,agentId:ne}):null;return ls(t,c,{kind:u,adapter:m,agent:ne,run:v,owner:_,linkTurn:he},J,U,E,H,re,B,O)}}const{messages:z,system:oe}=m.toTurn(J),X=$||Co(J?.model,E),K=C?Tt.begin({...C,agentId:X}):null,de=J?.stream===!0,Q=ut(u,J?.model||X),F=je(E.bridge.token),I=new AbortController;c.on("close",()=>{c.writableFinished||I.abort()});const{agentModel:n}=Ot(J?.model,E),o={bridgeUrl:await Re(E),agent:X,token:F,messages:z,system:oe,signal:I.signal,options:_o(E,{...n?{model:n}:{},...v||{}})};if(!de)try{let k="";const re=Pt(),ne=O?O.clock():0;await Kt(o,we=>{k+=we},null,we=>re.add(we)),O&&O.lap("upstream",ne);const he=O?O.clock():0,He=Q.full(Xo(k,U),re.value);return O&&O.lap("restore",he),c.writeHead(200,{"content-type":Q.contentType}),c.end(He),K?.add(re.value),K?.end("ok"),O?.commit()}catch(k){return K?.end(I.signal.aborted?"aborted":"error",{code:"bridge_error"}),O?.commit(),a(c,502,{error:{message:`bridge backend failed: ${k.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(Q.sseHead());const g=Gt(U),l=O?O.clock():0;let fe=l;const W=Pt();let ge="",ce=!1;try{let k=!0;await Kt(o,ne=>{O&&k&&(O.lap("upstream",l),fe=O.clock(),k=!1);const he=g.push(ne);he&&(ge+=he,c.write(Q.sseDelta(he)))},Q.sseActivity?ne=>{try{c.write(Q.sseActivity(Zo(ne,U)))}catch{}}:null,ne=>W.add(ne));const re=g.flush();re&&(ge+=re,c.write(Q.sseDelta(re))),c.write(Q.sseTail(W.value))}catch(k){ce=!0,c.write(`data: ${JSON.stringify({error:{message:k.message,type:"bridge_error"}})}
|
|
19
19
|
|
|
20
|
-
`)}O&&O.lap("stream",fe),d.end(),K&&(K.add(W.value),K.end(I.signal.aborted?"aborted":ue?"error":"ok",{code:"bridge_error"})),O?.commit(),H&&ge&&jt(ge,E.redaction)}function ss(t,d,u=""){const m=String(t||"").replace(/\/+$/,""),f=String(d||"").split("/")[1];return f&&m.endsWith(`/${f}`)?m.slice(0,-(f.length+1))+d+u:m+d+u}const is=9e4;function ls(t,d,u){if(d===u)return t;const m=d/u,f=new Float32Array(Math.floor(t.length/m));for(let y=0;y<f.length;y++){const $=y*m,N=Math.floor($),O=Math.min(t.length-1,N+1),v=$-N;f[y]=t[N]*(1-v)+t[O]*v}return f}const Co=new WeakMap,ds=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function $t(t,{installing:d=!1}={}){return t.stt?.diarize===!1?"off":d&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ve(t,d,u,m,{method:f="GET",timeoutMs:y=8e3,pick:$=N=>N}={}){const N=await Re(u);if(!N)return a(d,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const O=je(u.bridge?.token),v=f!=="GET"&&f!=="DELETE";try{const x=v?(await T(t,u.maxBodyBytes)).toString("utf8"):"",C=await fetch(`${N}${m}`,{method:f,headers:{Accept:"application/json",...v?{"content-type":"application/json"}:{},...O?{Authorization:`Bearer ${O}`}:{}},...v?{body:x||"{}"}:{},signal:AbortSignal.timeout(y)}),J=await C.json().catch(()=>({}));return C.ok?a(d,200,$(J)):a(d,C.status,{error:{message:J?.error||`bridge ${C.status}`,type:"bridge_error"}})}catch(x){return a(d,502,{error:{message:`bridge unreachable: ${x.message}`,type:"bridge_unreachable"}})}}function Pt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Be(t,d){const u=new URLSearchParams;for(const y of t.searchParams.getAll("dir"))y&&u.append("dir",y);const m=t.searchParams.get("workdir")||String(d?.bridge?.workingDir||"").trim();m&&u.set("workdir",m);const f=u.toString();return f?`?${f}`:""}async function cs(t,d,{adapter:u,kind:m,pathname:f,search:y,base:$,destKey:N,destProtocol:O,harness:v,trace:x,link:C=null},J,H){let E;const G=x?x.clock():0,z=C?vt.begin(C):null;let oe=!1;z&&d.on("close",()=>{d.writableFinished||(oe=!0)});const q=(F,I)=>{z&&(z.add(I),z.end(oe?"aborted":F>=400?"error":"ok",{code:`http_${F}`}))};try{const F=os(t.headers,$);N&&(O==="anthropic"?(F["x-api-key"]=N,delete F.authorization):F.authorization=`Bearer ${N}`);const I=er(ss($,f,y)).toString();E=await fetch(I,{method:t.method,headers:F,body:["GET","HEAD"].includes(t.method)?void 0:J})}catch(F){return z?.end("error",{code:"upstream_unreachable"}),x?.commit(),a(d,502,{error:`upstream fetch failed: ${F.message}`})}const K=E.headers.get("content-type")||"",ce={};if(E.headers.forEach((F,I)=>{$o.has(I.toLowerCase())||(ce[I]=F)}),K.includes("text/event-stream")&&E.body){x&&x.lap("upstream",G);const F=x?x.clock():0;d.writeHead(E.status,ce);const I=z?pn():null,n=I?E.body.pipeThrough(I.stream):E.body,o=m==="openai"?Fo(n,d,H,v):Vo(n,d,H);return Promise.resolve(o).finally(()=>{x&&x.lap("stream",F),q(E.status,I?.usage()),x?.commit()})}const Q=Buffer.from(await E.arrayBuffer());if(x&&x.lap("upstream",G),z&&q(E.status,K.includes("json")?hn(Q.toString("utf8")):null),H&&K.includes("application/json"))try{const F=x?x.clock():0,I=u.restoreResponse(JSON.parse(Q.toString("utf8")),H,v);return x&&x.lap("restore",F),d.writeHead(E.status,{...ce,"content-type":"application/json"}),d.end(Buffer.from(JSON.stringify(I),"utf8")),x?.commit()}catch{}d.writeHead(E.status,ce),d.end(Q),x?.commit()}function us(t=Rt()){const d=ir({first:async n=>{const o=Number(new URL(n).port),g=Bn.find(l=>l.port===o&&(l.provides||[]).includes("chat"));return g&&(await J())(g.id)==="up"?{engine:g.id,label:g.label,models:null}:null}}),u=ar({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):sr(n),newId:()=>lr()}),m=Jn({version:le}),f=qn({log:n=>console.log(` ${n}`)}),y=t.link?.enabled===!1?null:zn({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:g,body:l,device:fe})=>fetch(`http://127.0.0.1:${I.address()?.port||t.port}${o}`,{method:n,body:l,headers:{...g,"x-chatpanel-token":Me()||_e(),"x-chatpanel-link-device":String(fe||"")}}),ownerIsPro:()=>Se(t.pro?.entitlementToken),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==D.activeModel()&&(io(t.stt.diarizeModel)?D.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${ia}`));let $=null;const N=()=>{if(!$){const n=t.read||{};$=Ln({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return $};let O=null;const v=()=>(O||(O=$n({wrap:(n,o,g,l)=>Pn().wrap(n,o,g,l),onLog:n=>console.warn(`[extract worker] ${n}`)})),O);let x={at:0,fn:()=>"unknown"},C=null;async function J(){if(Date.now()-x.at<1e4)return x.fn;let n=new Map;try{const l=await E().health();for(const[fe,W]of Object.entries(l)){const ge=(t.destinations||[]).filter(ue=>ue?.service===fe).flatMap(ue=>[ue.id,...ue.models||[]]);for(const ue of[fe,...ge])n.set(ue,W)}}catch{n=new Map}const o=l=>n.get(l)||"unknown",g=new Map((t.destinations||[]).filter(l=>l?.service).map(l=>[l.id,l.service]));return o.window=l=>{try{return E().contextWindow(g.get(l)||l)}catch{return null}},o.card=l=>{try{return E().modelCard(g.get(l)||l)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),x={at:Date.now(),fn:o},x.fn}let H=null;const E=()=>(H||(H=Nn({cfg:t,bridgeHealth:async()=>{const n=await Re(t);if(!n)return null;const o=je(t.bridge?.token),g=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return g.ok?g.json():null},persist:()=>{try{ke(t,ie())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Je.join(Je.dirname(ie()),"runtime"),workers:()=>{const n=O?.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)})),H),G=Number(t.runtime?.idleMinutes),z=Mn({warmMs:(Number.isFinite(G)&&G>=0?G:10)*6e4,log:n=>console.log(n)}),oe=Dn({cfg:t,wake:(n,o)=>E().wake(n,o),embedded:z}),q=()=>{t.search?.searxng?.url&&E().wake("searxng").catch(()=>{})};let K=null;const ce=()=>{if(!K){const n=t.search||{},o=n.searxng?.url?ra({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;K=ea({reader:N(),searxng:o,engines:()=>na(t),wakeSearxng:()=>E().wake("searxng"),defaultProvider:n.provider||"auto",redact:async g=>{let l=g;return await Ke([dt(()=>l,fe=>{l=fe})],{...t.redaction,tier:"basic"},{isPro:!0}),l}})}return K};or(t.allowedExtensionIds||[]);const Q=[],F=n=>{Q.push(n),Q.length>50&&Q.shift()},I=Go(async(n,o)=>{const g=new URL(n.url,"http://127.0.0.1"),l=g.pathname;if(!at(n.headers.host))return a(o,403,{error:"loopback only"});if(!Wa(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(at(t.host)&&Hn(n.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(n.headers.origin&&Ka(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(l==="/admin/token"&&n.method==="POST")return U(n)?a(o,200,{token:_e()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(l==="/pair/code"&&n.method==="POST"){if(!U(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=rr();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(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=nr(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Ce(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Ce(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:i}=await Ft(t);return i&&console.log(`[gateway] pairing: the bridge at ${i.url}${i.version?` (v${i.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Me()||_e(),...s?{bridgeToken:s}:{},...i?{bridgeRefused:i}:{}})}if(l==="/pair/ask"&&n.method==="POST"){const e=Ce(n);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(Jt(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let r=null;try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r=null}const s=u.ask({browser:r?.browser,who:n.headers.origin||""});if(!s.ok){const i=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:i,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${n.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(l==="/pair/ask/result"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:r}=u.result(e?.id,{who:n.headers.origin||""});if(r!=="allowed")return a(o,200,{ok:!0,status:r});console.log(`[gateway] paired ${n.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:i}=await Ft(t);return a(o,200,{ok:!0,status:r,token:Me()||_e(),...s?{bridgeToken:s}:{},...i?{bridgeRefused:i}:{}})}if(l==="/whoami"&&n.method==="POST"){const e=Ce(n);return a(o,200,{ok:!0,trust:e,paired:Jt(e),version:le})}if(l==="/audit"&&n.method==="GET")return U(n)?a(o,200,cr(t,{version:le,startedAt:Po,managed:Ie(),certificates:{...mr(),wanted:zt(t)},linkPartners:y?y.status().devices.filter(e=>e.kind==="partner"):[],confined:pt({stateDir:Je.dirname(ie())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((l==="/config"||l==="/logs"||l==="/update"&&n.method!=="GET")&&!U(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(l==="/update"&&n.method==="GET"){const e=await en(le,{force:g.searchParams.get("force")==="1"}).catch(r=>({current:le,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:rn()})}if(l==="/update"&&n.method==="POST"){const e=on(le);return a(o,e.already?409:202,{ok:!0,job:e})}if((l==="/v1/history/key"||l==="/v1/history/ingest-backup")&&n.method==="POST"&&!U(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(l==="/v1/history/records"&&n.method==="PUT"&&!U(n))return a(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"&&!U(n))return a(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"&&!U(n))return a(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"))&&!U(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/browser"||l.startsWith("/v1/browser/"))&&!U(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/link"||l.startsWith("/v1/link/"))&&!U(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/events"||l.startsWith("/v1/events/"))&&!U(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(l.startsWith("/v1/observability")&&!U(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&l==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${le} is running.
|
|
20
|
+
`)}O&&O.lap("stream",fe),c.end(),K&&(K.add(W.value),K.end(I.signal.aborted?"aborted":ce?"error":"ok",{code:"bridge_error"})),O?.commit(),U&&ge&&zt(ge,E.redaction)}function us(t,c,u=""){const m=String(t||"").replace(/\/+$/,""),f=String(c||"").split("/")[1];return f&&m.endsWith(`/${f}`)?m.slice(0,-(f.length+1))+c+u:m+c+u}const ms=9e4;function ps(t,c,u){if(c===u)return t;const m=c/u,f=new Float32Array(Math.floor(t.length/m));for(let y=0;y<f.length;y++){const $=y*m,B=Math.floor($),O=Math.min(t.length-1,B+1),v=$-B;f[y]=t[B]*(1-v)+t[O]*v}return f}const Lo=new WeakMap,hs=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function At(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ve(t,c,u,m,{method:f="GET",timeoutMs:y=8e3,pick:$=B=>B}={}){const B=await Re(u);if(!B)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const O=je(u.bridge?.token),v=f!=="GET"&&f!=="DELETE";try{const _=v?(await T(t,u.maxBodyBytes)).toString("utf8"):"",C=await fetch(`${B}${m}`,{method:f,headers:{Accept:"application/json",...v?{"content-type":"application/json"}:{},...O?{Authorization:`Bearer ${O}`}:{}},...v?{body:_||"{}"}:{},signal:AbortSignal.timeout(y)}),J=await C.json().catch(()=>({}));return C.ok?a(c,200,$(J)):a(c,C.status,{error:{message:J?.error||`bridge ${C.status}`,type:"bridge_error"}})}catch(_){return a(c,502,{error:{message:`bridge unreachable: ${_.message}`,type:"bridge_unreachable"}})}}function Nt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Me(t,c){const u=new URLSearchParams;for(const y of t.searchParams.getAll("dir"))y&&u.append("dir",y);const m=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();m&&u.set("workdir",m);const f=u.toString();return f?`?${f}`:""}async function ys(t,c,{adapter:u,kind:m,pathname:f,search:y,base:$,destKey:B,destProtocol:O,harness:v,trace:_,link:C=null},J,U){let E;const H=_?_.clock():0,z=C?Tt.begin(C):null;let oe=!1;z&&c.on("close",()=>{c.writableFinished||(oe=!0)});const X=(F,I)=>{z&&(z.add(I),z.end(oe?"aborted":F>=400?"error":"ok",{code:`http_${F}`}))};try{const F=is(t.headers,$);B&&(O==="anthropic"?(F["x-api-key"]=B,delete F.authorization):F.authorization=`Bearer ${B}`);const I=nr(us($,f,y)).toString();E=await fetch(I,{method:t.method,headers:F,body:["GET","HEAD"].includes(t.method)?void 0:J})}catch(F){return z?.end("error",{code:"upstream_unreachable"}),_?.commit(),a(c,502,{error:`upstream fetch failed: ${F.message}`})}const K=E.headers.get("content-type")||"",de={};if(E.headers.forEach((F,I)=>{Bo.has(I.toLowerCase())||(de[I]=F)}),K.includes("text/event-stream")&&E.body){_&&_.lap("upstream",H);const F=_?_.clock():0;c.writeHead(E.status,de);const I=z?fn():null,n=I?E.body.pipeThrough(I.stream):E.body,o=m==="openai"?Yo(n,c,U,v):Qo(n,c,U);return Promise.resolve(o).finally(()=>{_&&_.lap("stream",F),X(E.status,I?.usage()),_?.commit()})}const Q=Buffer.from(await E.arrayBuffer());if(_&&_.lap("upstream",H),z&&X(E.status,K.includes("json")?gn(Q.toString("utf8")):null),U&&K.includes("application/json"))try{const F=_?_.clock():0,I=u.restoreResponse(JSON.parse(Q.toString("utf8")),U,v);return _&&_.lap("restore",F),c.writeHead(E.status,{...de,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(I),"utf8")),_?.commit()}catch{}c.writeHead(E.status,de),c.end(Q),_?.commit()}function fs(t=Jt()){const c=ur({first:async n=>{const o=Number(new URL(n).port),g=Cn.find(l=>l.port===o&&(l.provides||[]).includes("chat"));return g&&(await J())(g.id)==="up"?{engine:g.id,label:g.label,models:null}:null}}),u=dr({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):cr(n),newId:()=>mr()}),m=Hn({version:ie}),f=oa({log:n=>console.log(` ${n}`)}),y=t.link?.enabled===!1?null:Un({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:g,body:l,device:fe})=>fetch(`http://127.0.0.1:${I.address()?.port||t.port}${o}`,{method:n,body:l,headers:{...g,"x-chatpanel-token":De()||Oe(),"x-chatpanel-link-device":String(fe||"")}}),ownerIsPro:()=>Te(t.pro?.entitlementToken),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==M.activeModel()&&(uo(t.stt.diarizeModel)?M.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${ua}`));let $=null;const B=()=>{if(!$){const n=t.read||{};$=Gn({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return $};let O=null;const v=()=>(O||(O=Nn({wrap:(n,o,g,l)=>Bn().wrap(n,o,g,l),onLog:n=>console.warn(`[extract worker] ${n}`)})),O);let _={at:0,fn:()=>"unknown"},C=null;async function J(){if(Date.now()-_.at<1e4)return _.fn;let n=new Map;try{const l=await E().health();for(const[fe,W]of Object.entries(l)){const ge=(t.destinations||[]).filter(ce=>ce?.service===fe).flatMap(ce=>[ce.id,...ce.models||[]]);for(const ce of[fe,...ge])n.set(ce,W)}}catch{n=new Map}const o=l=>n.get(l)||"unknown",g=new Map((t.destinations||[]).filter(l=>l?.service).map(l=>[l.id,l.service]));return o.window=l=>{try{return E().contextWindow(g.get(l)||l)}catch{return null}},o.card=l=>{try{return E().modelCard(g.get(l)||l)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),_={at:Date.now(),fn:o},_.fn}let U=null;const E=()=>(U||(U=Dn({cfg:t,bridgeHealth:async()=>{const n=await Re(t);if(!n)return null;const o=je(t.bridge?.token),g=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return g.ok?g.json():null},persist:()=>{try{ke(t,se())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Je.join(Je.dirname(se()),"runtime"),workers:()=>{const n=O?.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)})),U),H=Number(t.runtime?.idleMinutes),z=Rn({warmMs:(Number.isFinite(H)&&H>=0?H:10)*6e4,log:n=>console.log(n)}),oe=In({cfg:t,wake:(n,o)=>E().wake(n,o),embedded:z}),X=()=>{t.search?.searxng?.url&&E().wake("searxng").catch(()=>{})};let K=null;const de=()=>{if(!K){const n=t.search||{},o=n.searxng?.url?sa({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;K=ra({reader:B(),searxng:o,engines:()=>ia(t),wakeSearxng:()=>E().wake("searxng"),defaultProvider:n.provider||"auto",redact:async g=>{let l=g;return await Qe([ct(()=>l,fe=>{l=fe})],{...t.redaction,tier:"basic"},{isPro:!0}),l}})}return K};sr(t.allowedExtensionIds||[]);const Q=[],F=n=>{Q.push(n),Q.length>50&&Q.shift()},I=Fo(async(n,o)=>{const g=new URL(n.url,"http://127.0.0.1"),l=g.pathname;if(!st(n.headers.host))return a(o,403,{error:"loopback only"});if(!Xa(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(st(t.host)&&Fn(n.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(n.headers.origin&&qa(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(l==="/admin/token"&&n.method==="POST")return V(n)?a(o,200,{token:Oe()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(l==="/pair/code"&&n.method==="POST"){if(!V(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=ir();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(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=lr(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Ce(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Ce(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:i}=await Qt(t);return i&&console.log(`[gateway] pairing: the bridge at ${i.url}${i.version?` (v${i.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:De()||Oe(),...s?{bridgeToken:s}:{},...i?{bridgeRefused:i}:{}})}if(l==="/pair/ask"&&n.method==="POST"){const e=Ce(n);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(Ht(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let r=null;try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r=null}const s=u.ask({browser:r?.browser,who:n.headers.origin||""});if(!s.ok){const i=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:i,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${n.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(l==="/pair/ask/result"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:r}=u.result(e?.id,{who:n.headers.origin||""});if(r!=="allowed")return a(o,200,{ok:!0,status:r});console.log(`[gateway] paired ${n.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:i}=await Qt(t);return a(o,200,{ok:!0,status:r,token:De()||Oe(),...s?{bridgeToken:s}:{},...i?{bridgeRefused:i}:{}})}if(l==="/whoami"&&n.method==="POST"){const e=Ce(n);return a(o,200,{ok:!0,trust:e,paired:Ht(e),version:ie})}if(l==="/audit"&&n.method==="GET")return V(n)?a(o,200,hr(t,{version:ie,startedAt:Mo,managed:Ie(),certificates:{...fr(),wanted:Ut(t)},linkPartners:y?y.status().devices.filter(e=>e.kind==="partner"):[],confined:ht({stateDir:Je.dirname(se())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((l==="/config"||l==="/logs"||l==="/update"&&n.method!=="GET")&&!V(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(l==="/update"&&n.method==="GET"){const e=await nn(ie,{force:g.searchParams.get("force")==="1"}).catch(r=>({current:ie,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:ln()})}if(l==="/update"&&n.method==="POST"){const e=sn(ie);return a(o,e.already?409:202,{ok:!0,job:e})}if((l==="/v1/history/key"||l==="/v1/history/ingest-backup")&&n.method==="POST"&&!V(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(l==="/v1/history/records"&&n.method==="PUT"&&!V(n))return a(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"&&!V(n))return a(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"&&!V(n))return a(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"))&&!V(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/browser"||l.startsWith("/v1/browser/"))&&!V(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/link"||l.startsWith("/v1/link/"))&&!V(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/events"||l.startsWith("/v1/events/"))&&!V(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(l.startsWith("/v1/observability")&&!V(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&l==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${ie} is running.
|
|
21
21
|
|
|
22
22
|
This address is for ChatPanel's apps, not a web page — there is nothing to open here.
|
|
23
23
|
Use ChatPanel itself (the browser extension's Settings, or the desktop app).
|
|
24
24
|
In a terminal, \`chatpanel-gateway --status\` shows what is running.
|
|
25
|
-
`);if(n.method==="GET"&&l==="/health"){const e=
|
|
25
|
+
`);if(n.method==="GET"&&l==="/health"){const e=P.health(),r=D.health();return a(o,200,{ok:!0,version:ie,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...Ie()?{managed:Ie()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},install:dn(),confined:ht({stateDir:Je.dirname(se())}),...un({release:wt.release()})?{appleHelper:!!yt()}:{},...Ge?{bridge:Ge.status()}:it?{bridge:it}:{},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||tt,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||ko,voice:t.tts?.voice||_e,runtime:r.runtime,dtype:r.dtype},events:Y?{count:Y.count(),hosts:Y.hosts().length}:null,browser:m.health()})}if(l==="/status"&&n.method==="GET"){Ko(t);const e=await Te(t.pro?.entitlementToken),r=await Ro(t);return a(o,200,{ok:!0,version:ie,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Ie()?{managed:Ie()}:{},...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:Da(t),uptimeSeconds:Math.floor((Date.now()-Mo)/1e3),update:an(ie)})}if(l==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=j.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:r})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(l==="/v1/prefs"&&n.method==="GET"){const e=String(g.searchParams.get("section")||"");return g.searchParams.get("stamps")?a(o,200,{ok:!0,revision:le.revision,stamps:le.stamps()}):a(o,200,{ok:!0,revision:le.revision,sections:le.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=le.put(e.sections||{},{by:e.by||""});return r.applied.length&&$o(r.applied,e.by||""),a(o,200,{ok:!0,...r})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(l==="/v1/prefs"&&n.method==="DELETE"){const e=String(g.searchParams.get("section")||""),r=e?le.remove(e):!1;return r&&$o([e],""),a(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)}
|
|
26
26
|
|
|
27
|
-
`);e({type:"hello",revision:
|
|
27
|
+
`);e({type:"hello",revision:le.revision,stamps:le.stamps()});const r=i=>e({type:"changed",...i});xt.add(r);const s=setInterval(()=>{try{o.write(`: keep-alive
|
|
28
28
|
|
|
29
|
-
`)}catch{}},25e3);o.on("close",()=>{
|
|
29
|
+
`)}catch{}},25e3);o.on("close",()=>{xt.delete(r),clearInterval(s)});return}if(l==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:pe.list({limit:g.searchParams.get("limit")||50,status:g.searchParams.get("status")||""})});if(l==="/v1/projects/jobs"&&n.method==="GET")return a(o,200,{ok:!0,jobs:pe.openJobs()});if(l==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:pe.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return a(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(l);if(e){const r=e[1],s=e[2]||"",i=e[3]||"",d=e[4]||"",p=()=>a(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(d){const h=pe.get(r);if(!h)return p();const S=h.jobs.find(b=>b.id===i);if(!S)return a(o,404,{error:{message:`no job ${i}`,type:"not_found"}});const w={cfg:t,prefsStore:le,scorecards:Ne,engines:Be,engineAt:c.engineAt};if(d==="/applications"&&n.method==="GET"){const b=await en(S,{...w,reach:g.searchParams.get("reach")||"any",chatModel:g.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:S,...b})}if(d==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(S.status))return a(o,400,{error:{message:`job ${i} is ${S.status}; only an open job is recruited`,type:"project_error"}});try{const b=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},N=String(b.by||"evaluator").slice(0,80),x=await tn(S,{...w,record:h,reach:b.reach||"any",chatModel:b.chatModel||null,evaluation:b.evaluation||null,text:b.text??null,by:N});let L=null;for(const ue of x.events)ue.type==="job.updated"?L=pe.updateJob(r,i,ue.job,{by:ue.by||N}):L=pe.append(r,[ue]);return a(o,200,{ok:!0,project:L,decision:x.decision,applications:x.applications,evaluation:x.evaluation})}catch(b){return a(o,400,{error:{message:`recruit: ${b.message}`,type:"project_error"}})}}return a(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!s&&n.method==="GET"){const h=pe.get(r,{events:g.searchParams.get("events")==="1"});return h?a(o,200,{ok:!0,project:h}):p()}if(!s&&n.method==="DELETE")return a(o,200,{ok:!0,removed:pe.remove(r)});if(n.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const h=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},S=String(h.by||"person").slice(0,80),w=s==="/events"?pe.append(r,h.events||[]):i?pe.updateJob(r,i,h.patch||h,{by:S}):pe.postJob(r,h.job||h,{by:S});return a(o,200,{ok:!0,project:w})}catch(h){return a(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(s==="/events"&&n.method==="GET"){if(!pe.get(r))return p();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=N=>o.write(`data: ${JSON.stringify(N)}
|
|
30
30
|
|
|
31
|
-
`);let S=g.searchParams.has("after")?Number(g.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:pe.get(r),after:S}});const w=pe.watch(r,
|
|
31
|
+
`);let S=g.searchParams.has("after")?Number(g.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:pe.get(r),after:S}});const w=pe.watch(r,N=>{N.seq>S&&(S=N.seq,h(N))});for(const N of pe.eventsSince(r,S))S=N.seq,h(N);const b=setInterval(()=>{try{o.write(`: keep
|
|
32
32
|
|
|
33
|
-
`)}catch{}},25e3);n.on("close",()=>{clearInterval(b),w()});return}}}if(l==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:
|
|
33
|
+
`)}catch{}},25e3);n.on("close",()=>{clearInterval(b),w()});return}}}if(l==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:Ne.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(l);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return a(o,200,{ok:!0,...await Ne.get(r)});if(n.method==="POST")try{const s=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},i=await Ne.append({agentId:r,kind:"rating",runId:s.runId,taskId:s.taskId,jobId:s.jobId,rating:{by:String(s.by||"person").slice(0,40),score:s.score,note:s.note,about:s.about},refs:s.refs});return Be.fromRating(Ne.chains.get(r)||[],{...i,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:i})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(l==="/v1/capabilities"&&n.method==="GET")return a(o,200,Pn(t,{version:ie,reader:$,searcher:K,extract:v(),proxy:oe}));if(l==="/v1/fusions"&&n.method==="GET"){const e={active:R.health().model||t.ner?.model||null,companions:R.companions()};let r=null;try{r=await E().status()}catch{r=null}return a(o,200,Sn({cfg:t,ner:e,runtimeDoc:r}))}if(l==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(Ln.map(r=>{const s=bt(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:jn[r],threads:z.threads,...s.kind==="embedded"?z.health(r,s.model):{}}]}));return a(o,200,{...await E().status(),inProcess:e})}if(l==="/v1/runtime/plan"&&n.method==="GET"){const e=new URL(n.url,"http://x").searchParams,r=await E().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,r.ok?200:400,r)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(l);if(e&&n.method==="POST"){if(!V(n))return a(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const s=String(r.action||"start"),i=E(),d=e[1]==="engines"?s==="start"?await i.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await i.startService(e[2],{force:r.force===!0}):s==="stop"?await i.stopService(e[2]):s==="model"?await i.setModel(e[2],r.model):s==="tune"?await i.setTunings(e[2],r.tunings):s==="profile"?await i.setProfile(e[2],r.profile):s==="pull"?await i.pullModel(e[2]):s==="install"?await i.installRunner(e[2]):s==="cancel"?i.cancelJob(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,d.ok?200:400,d)}}if((l==="/v1/rerank"||l==="/v1/decide")&&n.method==="POST"){const e=l.slice(4);let r;try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await oe.call(e,r);return a(o,s.status,s.body)}if(l==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await An(e,{ensure:()=>et(t),model:R.health().model});return a(o,r.status,r.body)}catch(r){return a(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(l==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,Math.max(t.maxBodyBytes,Math.ceil(zn*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Jn(e,{service:v()});return a(o,r.status,r.body)}if(l==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await B().read(e);return a(o,r.status,r.body)}if(l==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}X();const r=await de().search(e);return a(o,r.status,r.body)}if(/^\/v1\/search\/./.test(l)&&n.method==="GET"){let e;try{e=decodeURIComponent(l.slice(11))}catch{e=l.slice(11)}const r=g.searchParams.has("read")?Math.max(0,Math.min(10,Number(g.searchParams.get("read"))||0)):aa.aliasRead;X();const s=await de().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?na(s.body):s.body)}if(/^\/v1\/read\/./.test(l)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(n.headers.accept||""),i=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",d=await B().read({url:r,format:i});return d.status!==200||s?a(o,d.status,d.status===200?{code:200,status:2e4,data:d.body}:d.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":d.body.provider}),o.end(la(d.body)))}if(l==="/v1/engines"&&n.method==="GET"){const e=Number(g.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:Be.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(l);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const s=Number(g.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await Be.get(r,{entries:g.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&n.method==="POST")try{const s=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},i=s.engine||ts(r);if(!i)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const d=await Be.append({...s,engine:i,kind:s.kind||"call"});return d.key!==r?a(o,400,{error:{message:`model-ledger: entry is for ${d.key}, not ${r}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:d})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(l==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=i=>{try{o.write(`data: ${JSON.stringify(i)}
|
|
34
34
|
|
|
35
|
-
`)}catch{}};e({type:"hello",at:Date.now()});const r=
|
|
35
|
+
`)}catch{}};e({type:"hello",at:Date.now()});const r=Z.watchAll(i=>e({type:"run",id:i.id,removed:!!i.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
|
|
36
36
|
|
|
37
|
-
`)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(l==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:
|
|
37
|
+
`)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(l==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:Z.list({limit:g.searchParams.get("limit")||50,team:g.searchParams.get("team")||""})});if(l==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:Z.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return a(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(l);if(e){const r=e[1],s=e[2]||"";if(!s&&n.method==="GET"){const i=Z.get(r,{events:g.searchParams.get("events")==="1"});return i?a(o,200,{ok:!0,run:i}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!s&&n.method==="DELETE")return Z.stop(r),a(o,200,{ok:!0,removed:Z.remove(r)});if(s==="/stop"&&n.method==="POST"){const i=Z.stop(r);return i?a(o,200,{ok:!0,run:i}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(s==="/checkpoint"&&n.method==="GET")try{return a(o,200,{ok:!0,checkpoint:Z.checkpoint(r)})}catch(i){return a(o,404,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((s==="/handoff"||s==="/claim")&&n.method==="POST")try{const i=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},d=s==="/handoff"?Z.handoff(r,{taskId:i.taskId,model:i.model,by:i.by,reason:i.reason}):Z.claim(r,{client:i.client});return a(o,200,{ok:!0,run:d})}catch(i){return a(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(s.startsWith("/threads/")&&n.method==="DELETE")try{return a(o,200,{ok:!0,run:Z.removeThread(r,{threadId:s.slice(9),by:"person"})})}catch(i){return a(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((s==="/answer"||s==="/decide"||s==="/post")&&n.method==="POST")try{const i=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},d=String(i.by||"person").slice(0,40),p=s==="/answer"?Z.answer(r,{threadId:i.threadId,text:i.text,by:d}):s==="/decide"?Z.decide(r,{postId:i.postId,status:i.status,by:d}):Z.post(r,{threadId:i.threadId,text:i.text,by:d,kind:i.kind,replyTo:i.replyTo});return a(o,200,{ok:!0,run:p})}catch(i){return a(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="POST")try{const i=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:Z.append(r,i.events||[])})}catch(i){return a(o,i.message.startsWith("no run")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="GET"){if(!Z.get(r))return a(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 i=w=>o.write(`data: ${JSON.stringify(w)}
|
|
38
38
|
|
|
39
|
-
`),
|
|
39
|
+
`),d=g.searchParams.has("after")?Number(g.searchParams.get("after")):NaN;let p=Number.isFinite(d)?d:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:Z.get(r),after:p}});const h=Z.watch(r,w=>{w.seq==null?i(w):w.seq>p&&(p=w.seq,i(w))});for(const w of Z.eventsSince(r,p))p=w.seq,i(w);const S=setInterval(()=>{try{o.write(`: keep-alive
|
|
40
40
|
|
|
41
|
-
`)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(S)});return}}}if(l==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:ye.size,memories:ye.list()});if(l==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=ye.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 a(o,200,{ok:!0,size:ye.size,...r})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(l==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=ye.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 a(o,200,{ok:!0,action:r.action,record:r.record,replaced:r.replaces||null,size:ye.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(l==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=ye.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:ye.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(l==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=ye.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:ye.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(l==="/v1/memory/clear"&&n.method==="POST")return a(o,200,{ok:!0,dropped:ye.clear(),size:ye.size});if(l==="/v1/history/clear"&&n.method==="POST"){const e=j.clear();return a(o,200,{ok:!0,dropped:e,size:j.size})}if(l==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=j.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 a(o,200,{ok:!0,size:j.size,newest:j.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(l==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),s=
|
|
42
|
-
data: ${JSON.stringify({cursor:
|
|
41
|
+
`)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(S)});return}}}if(l==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:ye.size,memories:ye.list()});if(l==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=ye.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 a(o,200,{ok:!0,size:ye.size,...r})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(l==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=ye.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 a(o,200,{ok:!0,action:r.action,record:r.record,replaced:r.replaces||null,size:ye.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(l==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=ye.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:ye.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(l==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=ye.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:ye.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(l==="/v1/memory/clear"&&n.method==="POST")return a(o,200,{ok:!0,dropped:ye.clear(),size:ye.size});if(l==="/v1/history/clear"&&n.method==="POST"){const e=j.clear();return a(o,200,{ok:!0,dropped:e,size:j.size})}if(l==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=j.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 a(o,200,{ok:!0,size:j.size,newest:j.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(l==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),s=Va(r,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),i={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),p=await Fa(s,S=>j.search(S,{limit:d,...i}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=i.type?p:[...p.filter(S=>S.type==="brief"),...p.filter(S=>S.type!=="brief")];return a(o,200,{ok:!0,size:j.size,newest:j.newest,queries:s,results:h})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(l==="/v1/research"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const r=String(e.question||"").trim();if(!r)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!V(n))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const i=`http://127.0.0.1:${n.socket.localPort}`,d=s?async(w,{maxTokens:b=220}={})=>{const N=new AbortController,x=setTimeout(()=>N.abort(),3e4);try{const L=De()||Oe(),ue=await fetch(`${i}/v1/chat/completions`,{method:"POST",signal:N.signal,headers:{"content-type":"application/json",...L?{Authorization:`Bearer ${L}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:w}],stream:!1,max_tokens:b,temperature:.2})}),be=await ue.json().catch(()=>({}));return ue.ok?String(be?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(x)}}:null,p=le.get("identity")?.identity?.value||{},h=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,S=await Kr(r,{store:j,memories:ye.list(),complete:d,previous:h,self:String(p.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,Qr(r,S,{size:j.size,newest:j.newest}))}if(l==="/v1/history/related"&&n.method==="GET"){const e=String(g.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(g.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:j.related(e,{limit:r})})}if(l==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:j.size,newest:j.newest,bytes:j.bytes,lossless:j.lossless?{records:j.lossless.size,newest:j.lossless.newest}:null});if(l==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(g.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:j.size,bytes:j.bytes,newest:j.newest}},access:_t.snapshot(e)})}if(l==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=_t.push(Oo({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:r})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(l==="/v1/history/records"&&n.method==="PUT"){const e=j.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await T(n,Math.max(t.maxBodyBytes||0,ss))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),i=Number(r.at)||Date.now(),d=[];let p=0,h={},S=[],w=[];const b={upserts:[],removes:[]},N=x=>{if(!x||x.deletedAt){x?.id&&b.removes.push(x.id);return}try{const L=so(x);L&&b.upserts.push(L)}catch{}};if(Array.isArray(r.records)){const x=e.write(r.records,{host:s,at:i,merge:r.merge===!0});d.push(...x.written),h=x.revs,S=x.conflicts,w=x.merged;for(const L of x.written)N(e.get(L))}if(Array.isArray(r.entries)){const x=mt(),L=x?On((q,Se)=>xn(x,{salt:q,iterations:Se})):null,ue=async q=>{if(!L||!q.blob)return null;const Se=await L(q.blob),G=q.blob.compression&&q.blob.compression!=="none"?En($n,q.blob.compression):null;return _n(q.blob,Se,{codec:G})},be=await e.upsertEntries(r.entries,{open:ue});d.push(...be.written),p+=be.sealed;for(const q of be.written)N(e.get(q))}return(b.upserts.length||b.removes.length)&&j.bulk(b),d.length&&ze({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:h,conflicts:S,merged:w,sealed:p,size:e.size,rev:e.rev})}catch(r){return a(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(l==="/v1/events"&&n.method==="POST"){if(!Y)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=Array.isArray(e)?e:e.events;if(!Array.isArray(r))return a(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(r.length>2e3)return a(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const s=p=>(typeof p?.host=="string"&&p.host?p.host:vn(p?.source))===no,i=r.filter(s).map(p=>({id:p?.id??null,code:"RESERVED_HOST",message:`host "${no}" is this gateway's own log`})),d=wn(Y,i.length?r.filter(p=>!s(p)):r);return a(o,200,{ok:!0,appended:d.appended,duplicates:d.duplicates,rejected:[...i,...d.rejected],cursor:Y.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(l==="/v1/events/cursor"&&n.method==="GET")return Y?a(o,200,{ok:!0,cursor:Y.cursor(),count:Y.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(l==="/v1/events/stats"&&n.method==="GET"){if(!Y)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=bn(Y.all());return a(o,200,{ok:!0,stats:e,year:kn(e)})}if(l==="/v1/events"&&n.method==="GET"){if(!Y)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=ao(JSON.parse(g.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=Y.since(e,{limit:Number(g.searchParams.get("limit"))||void 0,host:g.searchParams.get("host")||null});return a(o,200,{ok:!0,events:r.events.map(s=>ft(s)),cursor:r.cursor,more:r.more})}if(l==="/v1/events/stream"&&n.method==="GET"){if(!Y)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(g.searchParams.has("cursor"))try{e=ao(JSON.parse(g.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
|
|
42
|
+
data: ${JSON.stringify({cursor:Y.cursor(),count:Y.count(),version:ie})}
|
|
43
43
|
|
|
44
|
-
`),
|
|
45
|
-
data: ${JSON.stringify(
|
|
44
|
+
`),Ee.add(o),n.on("close",()=>Ee.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=Y.since(r.cursor);for(const s of r.events)o.write(`event: cloudevent
|
|
45
|
+
data: ${JSON.stringify(ft(s))}
|
|
46
46
|
|
|
47
|
-
`)}}return}if(l==="/v1/link"&&n.method==="GET")return a(o,200,{...y?{enabled:!0,...y.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(l==="/v1/link/settings"&&n.method==="POST"){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change what it may reach",type:"forbidden"}});let e={};try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(typeof e.agentSessions!="boolean")return a(o,400,{error:{message:"link settings: { agentSessions: true|false }",type:"invalid_request"}});t.link={...t.link||{},agentSessions:e.agentSessions};try{ke(t,
|
|
48
|
-
data: ${JSON.stringify({pending:
|
|
47
|
+
`)}}return}if(l==="/v1/link"&&n.method==="GET")return a(o,200,{...y?{enabled:!0,...y.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(l==="/v1/link/settings"&&n.method==="POST"){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change what it may reach",type:"forbidden"}});let e={};try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(typeof e.agentSessions!="boolean")return a(o,400,{error:{message:"link settings: { agentSessions: true|false }",type:"invalid_request"}});t.link={...t.link||{},agentSessions:e.agentSessions};try{ke(t,se())}catch(r){console.warn(`[link] could not persist the settings: ${r.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(l==="/v1/link/pair"&&n.method==="POST"){if(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(e?.kind==="partner"){const r={partner:e.partner?.name,scopes:e.scopes,route:e.route||null,relay:String(e.relay||""),folder:typeof e.folder=="string"?e.folder:""};let s;try{s=y.previewPartner(r)}catch(i){return a(o,400,{error:{message:i?.message||String(i),type:"invalid_request",code:i?.code||"bad_partner"}})}if(e.confirm!==!0)return a(o,200,{confirmed:!1,preview:s});try{return a(o,200,{confirmed:!0,...await y.pairPartner(r)})}catch(i){return a(o,i?.code==="bad_partner"?400:502,{error:{message:i?.message||String(i),type:i?.code==="bad_partner"?"invalid_request":"relay"}})}}if(e?.kind&&e.kind!=="phone")return a(o,400,{error:{message:"link pair: kind is phone or partner",type:"invalid_request"}});try{return a(o,200,await y.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(r){return a(o,502,{error:{message:r?.message||String(r),type:"relay"}})}}if(l==="/v1/link/route"&&n.method==="POST"){if(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});let e={};try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let r;try{r=Vn({id:String(e.route||"link"),url:String(e.url||"")})}catch(i){return a(o,400,{error:{message:i.message,type:"bad_route"}})}const s={...t.link||{},route:r.id,fallback:e.fallback!==!1};r.id==="relay"?s.relayUrl=r.url:r.id==="link"&&delete s.relayUrl,(r.id==="tailscale"||r.id==="cloudflare")&&(s.tunnelUrl=r.url),t.link=s;try{ke(t,se())}catch(i){console.warn(`[link] could not persist the route: ${i.message}`)}return a(o,200,{enabled:!0,...await y.applySettings(s)})}if(l.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!y)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(l.slice(17));return await y.remove(e)?(f.cancelDevice(e),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(l==="/v1/link/files"||l.startsWith("/v1/link/files/")){const e=io(n.headers);if(e?.kind!=="partner"||!e.scopes.includes("files"))return a(o,403,{error:{message:"link files: a partner’s own folder, for a partner granted files",type:"forbidden",code:"link_scope"}});const r=y?.partnerFolderOf(e.device);if(!r)return a(o,403,{error:{message:"link files: this partner has no folder on this computer — pair it again with agents and files",type:"forbidden",code:"link_scope"}});const s=l.slice(14).replace(/^\//,"");let i=s;try{i=decodeURIComponent(s)}catch{}const d=n.method==="GET"&&(!s||/^(data|\.claude\/skills|\.claude\/agents|\.agents\/skills)\/?$/.test(i));let p;try{p=Zn(s,{listing:d})}catch(h){return a(o,400,{error:{message:h.message,type:"invalid_request",code:"bad_path"}})}try{if(n.method==="GET"&&d)return a(o,200,{folder:"its own",files:Xn(r,p.replace(/\/$/,""))});if(n.method==="GET"){const h=qn(r,p);o.writeHead(200,{"content-type":"application/octet-stream","content-length":String(h.size)}),h.stream.pipe(o);return}return n.method==="PUT"?a(o,200,ea(r,p,await T(n,t.maxBodyBytes))):n.method==="DELETE"?ta(r,p)?a(o,200,{ok:!0}):a(o,404,{error:{message:`${p}: no such file`,type:"not_found"}}):a(o,405,{error:{message:"link files: GET, PUT or DELETE",type:"invalid_request"}})}catch(h){const S=h?.status||(h?.code===413?413:h?.code==="bad_partner"?400:500);return a(o,S,{error:{message:h?.message||String(h),type:S===404?"not_found":S===413?"too_large":"invalid_request"}})}}if(l==="/v1/link/approvals"||l.startsWith("/v1/link/approvals/")){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"an agent’s approval is the owner’s to give, on this computer",type:"forbidden"}});if(l==="/v1/link/approvals"&&n.method==="GET")return a(o,200,{pending:f.list()});if(l==="/v1/link/approvals/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const r=d=>o.write(`event: approvals
|
|
48
|
+
data: ${JSON.stringify({pending:d})}
|
|
49
49
|
|
|
50
50
|
`);r(f.list());const s=f.subscribe(r),i=setInterval(()=>o.write(`:
|
|
51
51
|
|
|
52
|
-
`),25e3);i.unref?.(),o.on("close",()=>{s(),clearInterval(i)});return}const e=/^\/v1\/link\/approvals\/([A-Za-z0-9_-]{1,40})$/.exec(l);if(e&&n.method==="POST"){let r={};try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{r={}}return
|
|
53
|
-
data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:
|
|
52
|
+
`),25e3);i.unref?.(),o.on("close",()=>{s(),clearInterval(i)});return}const e=/^\/v1\/link\/approvals\/([A-Za-z0-9_-]{1,40})$/.exec(l);if(e&&n.method==="POST"){let r={};try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{r={}}return lo.some(s=>s.id===r.decision)?f.answer(e[1],r.decision)?a(o,200,{ok:!0}):a(o,404,{error:{message:"nothing is waiting under that id — answered, withdrawn or expired",type:"not_found"}}):a(o,400,{error:{message:`link approvals: { decision: ${lo.map(s=>s.id).join(" | ")} }`,type:"invalid_request"}})}}if(l==="/v1/browser"&&n.method==="GET")return a(o,200,m.status());if(l==="/v1/browser/stream"&&n.method==="GET"){m.stream(n,o);return}if((l==="/v1/browser/call"||l==="/v1/browser/announce"||l==="/v1/browser/result")&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const r=l==="/v1/browser/call"?await m.call(e,n):l==="/v1/browser/announce"?m.announce(e):m.result(e);return a(o,r.status,r.body)}if(l==="/v1/history/stream"&&n.method==="GET"){const e=j.lossless;if(!e)return a(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
|
|
53
|
+
data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:ie,prefsRevision:le.revision})}
|
|
54
54
|
|
|
55
|
-
`),Te.add(o),n.on("close",()=>Te.delete(o));return}if(l==="/v1/history/records"&&n.method==="GET"){const e=j.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(g.searchParams.get("since"))||0,cursor:g.searchParams.get("cursor")||"",limit:Number(g.searchParams.get("limit"))||200,kind:g.searchParams.get("kind")||null,bytes:Number(g.searchParams.get("bytes"))||0,afterRev:g.searchParams.has("after_rev")?Number(g.searchParams.get("after_rev"))||0:null});return a(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(g.searchParams.get("limit"))||50)),r=Math.max(0,Number(g.searchParams.get("offset"))||0),s=g.searchParams.get("type")||null;return a(o,200,{ok:!0,...j.list({limit:e,offset:r,type:s})})}if(l==="/v1/history/get"&&n.method==="GET"){const e=g.searchParams.get("maxChars")!=null?Math.max(1,Number(g.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(g.searchParams.get("offset"))||0),s=j.get(String(g.searchParams.get("id")||""),{maxChars:e,offset:r});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(l==="/v1/history/key"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:Zt()});if(l==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Br(String(e.passphrase)):Dr();const r=e.passphrase?await yt(j,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&ze(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return a(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 yt(j,ut());return e.ok&&e.whole&&ze(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(l==="/ner"){if(n.method==="GET"){const e=await Do(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await qe(t),R.state()!=="off"){if(!R.isReady()){const r=R.health();return a(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 s="",i=!1;try{const p=JSON.parse(r.toString("utf8"));s=p?.text||"",i=p?.strict===!0}catch{}const c=await R.detect(s,{strict:i});return a(o,200,{entities:c})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=Bo(t);if(!e){const r=R.modelOnDisk(t.ner?.model||void 0);return a(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:R.state(),model:t.ner?.model||null})}try{const r=await T(n,t.maxBodyBytes),s=await Ye(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),i=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(i)}catch(r){return a(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 a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:_t(t)});try{let r=e;const s=await Se(t.pro?.entitlementToken);await qe(t);const i=await Ke([dt(()=>r,c=>{r=c})],t.redaction,{isPro:s});return a(o,200,{text:r,count:i.count||0,sanitized:i.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Ao(i.vault,"types")||[],detector:_t(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(l==="/ner/models"){if(n.method==="GET"){const e=R.health().model||t.ner?.model||null,r=Math.round(ft.totalmem()/1048576),s=ca(co,{totalRamMB:r}).map(i=>({...i,installed:R.modelOnDisk(i.id)}));for(const i of[e,...R.modelsOnDisk()])!i||s.some(c=>c.id===i)||s.push({id:i,label:i,lang:"—",custom:!0,installed:R.modelOnDisk(i),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:R.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Ar(),recommendation:Yt(s,{totalRamMB:r},[]),state:R.state(),progress:R.progress(),available:s})}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 s=Math.round(ft.totalmem()/1048576),i=Yt(co.map(c=>({...c,installed:R.modelOnDisk(c.id)})),{totalRamMB:s},[]);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 s=[...new Set(e.union.map(c=>String(c||"").trim()).filter(Boolean))];for(const c of s)if(!(uo(c)||mo(c)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${c}`,type:"bad_model"}});const i=r||t.ner?.model||R.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(c=>c!==i),r&&ko(t,r);try{ke(t,ie())}catch{}return(async()=>{r&&await R.setModel(r,{onLog:p=>console.log(p)});const c=Pr(t.ner,{log:p=>console.log(p)});for(const p of R.companions())c.includes(p.model)||await R.removeCompanion(p.model);for(const p of c)await R.addCompanion(p,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});R.setUnionOrder(c)})().catch(c=>console.log(`[ner] union update failed: ${c.message}`)),a(o,202,{accepted:!0,active:i,union:t.ner.union,companions:R.companions(),state:R.state()})}if(!r||!(uo(r)||mo(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});ko(t,r);try{ke(t,ie())}catch{}return R.setModel(r,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:r,state:R.state(),progress:R.progress()})}}if(l==="/stt/models"){if(n.method==="GET"){const e=B.health().model||t.stt?.model||et,r=ua.map(s=>({...s,installed:B.modelOnDisk(s.id)}));return e&&!r.some(s=>s.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:B.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:B.state(),progress:B.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:B.health().dtype,runtime:B.health().runtime,dtypes:ha})}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||!(ma(r)||pa(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=typeof e.dtype=="string"&&ya(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},s&&(t.stt.dtype=s==="auto"?null:s);try{ke(t,ie())}catch{}return B.setModel(r,{onLog:i=>console.log(i),dtype:s||t.stt.dtype||"auto",warmMs:t.stt.warmMs,speaker:$t(t,{installing:!0})}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:B.state(),progress:B.progress(),speaker:{id:D.activeModel(),state:D.state(),installed:D.modelOnDisk()}})}}if(l==="/diarize/model"){if(n.method==="GET"){const e=D.activeModel(),r=sa.map(s=>({...s,installed:D.modelOnDisk(s.id)})).sort((s,i)=>(i.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:D.state(),threshold:D.activeThreshold(),progress:D.progress(),available: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){if(!io(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await D.setModel(r,{log:s=>console.log(s)}))return a(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{ke(t,ie())}catch{}return D.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:D.activeModel(),state:D.state(),threshold:D.activeThreshold(),progress:D.progress()})}return D.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:D.activeModel(),state:D.state(),threshold:D.activeThreshold(),progress:D.progress()})}}if(l==="/tts/models"){if(n.method==="GET"){const e=M.health().model||t.tts?.model||wo(wt()),r=wt(),s=po.find(c=>c.id===e)||null,i=po.map(c=>({...c,installed:M.modelOnDisk(c.id),unavailable:c.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!i.some(c=>c.id===e)&&i.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:M.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:M.state(),progress:M.progress(),available:i,voice:t.tts?.voice||(rt(e)==="pocket-tts"?tt:xe),arch:M.arch(),supportsVoices:M.arch()?M.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:M.arch()?M.supportsCustomVoices():!!s?.customVoices,sampleRate:M.sampleRate(),voices:M.isPocket()||!M.arch()&&rt(e)==="pocket-tts"?(M.builtinVoices().length?M.builtinVoices():Sa).map(c=>({id:c,label:c[0].toUpperCase()+c.slice(1),lang:"en",installed:M.builtinVoices().includes(c)})):M.arch()&&M.arch()!=="style-tts2"?[]:fa.map(c=>({...c,installed:M.voiceOnDisk(c.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:M.health().dtype,runtime:M.health().runtime,dtypes:ba})}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&&!(ga(r)||wa(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const c=me.parseCustomVoice(s);if(!(c?!!me.getVoice(c):ot(s)||ho(s)&&yo(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&ka(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:fo,voice:xe,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const c=va(r),p=me.parseCustomVoice(t.tts.voice||""),h=!!(p&&me.getVoice(p));if(c&&!h)if(rt(r)==="pocket-tts")t.tts.voice=tt;else{const w=me.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!c&&h&&(t.tts.voice=xe);const S=rt(r)==="pocket-tts";S&&!me.parseCustomVoice(t.tts.voice||"")&&!ot(t.tts.voice)&&(t.tts.voice=tt),!S&&ot(t.tts.voice)&&(t.tts.voice=xe)}i&&(t.tts.dtype=i==="auto"?null:i);try{ke(t,ie())}catch{}return r&&M.setModel(r,{onLog:c=>console.log(c),dtype:i||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:M.state(),progress:M.progress()})}}if(l==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:me.listVoices(),usable:M.supportsCustomVoices(),embedder:D.activeModel(),embedderReady:D.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():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,i=e&&typeof e.id=="string"?e.id.trim():"";if(i){if(!me.getVoice(i))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...me.renameVoice(i,r),usable:M.supportsCustomVoices()})}catch(c){return a(o,400,{error:{message:c.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!D.isReady()){const b=D.download({onLog:L=>console.log(L)}),A=Symbol("timeout"),_=await Promise.race([b.then(()=>null).catch(L=>L),new Promise(L=>setTimeout(()=>L(A),is))]);if(_===A||!D.isReady())return a(o,503,{error:{message:_===A?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${D.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:D.progress()})}const c=Float32Array.from(s),p=await D.embed(c);let h=null;try{const b=await M.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:A=>console.log(A)});b&&(h=await b.encodeVoice(ls(c,16e3,24e3)))}catch(b){console.log(`[tts] pocket conditioning unavailable for this voice (${b.message})`)}const S=i?me.replaceVoice(i,{vec:p,pocket:h}):me.saveVoice({name:r,vec:p,pocket:h}),w=i&&r&&r!==S.name?me.renameVoice(i,r):S;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${w.name}" (${(S.kinds||[]).join(" + ")}, sample discarded)`),a(o,i?200:201,{...S,...w,usable:M.supportsCustomVoices()})}catch(c){return a(o,400,{error:{message:c.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=g.searchParams.get("id")||"",r=me.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=me.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:xe;try{ke(t,ie())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((l==="/tts"||l==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return a(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 a(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>go)return a(o,413,{error:{message:`text too long (max ${go} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=Ta(t),c=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,p=c||(i?i.voice:t.tts?.voice||xe);if(i&&!_a(p))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(i){const{audio:Y,contentType:V,redacted:De}=await xa({dest:i,text:r,voice:p,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await Se(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":V,"Content-Length":String(Y.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(De)}),o.end(Y)}if(!await M.ready({onLog:Y=>console.log(Y),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||wo(wt()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:M.health().error||"tts model not ready",type:"tts_unavailable"}});const w=Oa({requested:c,configured:p,engine:M,voices:me,isPocketVoice:ot,isKnownVoice:ho,isValidVoiceId:yo,defaultVoice:xe,defaultPocketVoice:tt});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:b,customId:A,speakerEmbedding:_}=w,L=await M.synth(r,{voice:b,speed:s,speakerEmbedding:_}),se=M.sampleRate(),be=h==="pcm"?Buffer.from(new Float32Array(L).buffer):M.toWav(L,se);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(be.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(se),...A||M.isPocket()||M.supportsVoices()?{"X-Tts-Voice":b}:{}}),o.end(be)}catch(S){return a(o,500,{error:{message:S.message,type:"tts_failed"}})}}if(l==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=la(await T(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(b){return a(o,b.code===413?413:415,{error:{message:b.message,type:"bad_request"}})}const r=b=>e.find(A=>A.name===b&&!A.filename)?.data.toString("utf8").trim()||"",s=e.find(b=>b.name==="file"&&b.filename)||e.find(b=>b.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let i;try{i=await da(s.data)}catch(b){return a(o,b.code===415?415:500,{error:{message:b.message,type:"unsupported_media"}})}const c=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",p=gt(t,"stt");let h=null;if(p.kind==="remote"||p.kind==="container")try{h=lo(p,{fetchImpl:Ye})}catch(b){return a(o,500,{error:{message:`stt provider: ${b.message}`,type:"bad_provider"}})}!h&&!B.isReady()&&B.init({model:t.stt?.model||et,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:$t(t),onLog:b=>console.log(b)});const S=r("diarize")==="true"&&t.stt?.diarize!==!1;S&&!D.isReady()&&D.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:b=>console.log(b)});const w=Date.now();try{const{id:b}=B.createSession({lang:r("language")||void 0,diarize:S,interims:!1,remote:h}),A=[];let _=null;B.subscribe(b,V=>{V.type==="final"&&V.text?A.push(V):V.type==="language"&&(_=V.lang)});const L=16e3*5;for(let V=0;V<i.pcm.length;V+=L)B.pushAudio(b,i.pcm.subarray(V,Math.min(i.pcm.length,V+L)));await B.endSession(b);let se=0;const be=A.map((V,De)=>{const Jo=se,zo=(V.durationMs||0)/1e3;return se+=zo,{id:De,start:Math.round(Jo*100)/100,end:Math.round(se*100)/100,text:V.text,...V.speaker?{speaker:V.speaker}:{}}}),Y=be.map(V=>V.text).join(" ").replace(/\s+/g," ").trim();return c==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Y)):c==="verbose_json"?a(o,200,{task:"transcribe",language:_||r("language")||null,duration:Math.round(i.seconds*100)/100,text:Y,segments:be,provider:p.kind,took_ms:Date.now()-w}):a(o,200,{text:Y})}catch(b){return a(o,b.code==="too_many_sessions"?429:500,{error:{message:b.message,type:b.code||"stt_error"}})}}if(l==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(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=gt(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=lo(r,{fetchImpl:Ye})}catch(c){return a(o,500,{error:{message:`stt provider: ${c.message}`,type:"bad_provider"}})}!s&&!B.isReady()&&B.init({model:t.stt?.model||et,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:$t(t),onLog:c=>console.log(c)});const i=e?.diarize===!0&&t.stt?.diarize!==!1;i&&!D.isReady()&&D.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:c=>console.log(c)});try{const c=e?.poll===!0,{id:p}=B.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:i,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:c});return a(o,201,{id:p,state:B.state(),...c?{poll:!0}:{}})}catch(c){return a(o,c.code==="too_many_sessions"?429:500,{error:{message:c.message,type:c.code||"stt_error"}})}}{const e=l.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(c,p,h)=>{if(p.type!=="final"||!c.redact)return p;try{let S=p.text;return await Ke([dt(()=>S,w=>{S=w})],t.redaction,{isPro:h}),{...p,text:S}}catch{return p}},i=async c=>{const p=B.drainEvents(r);if(!p)return null;const h=[];if(c&&!c.closed){const w=c.remote?"ready":B.state();w==="downloading"||w==="loading"?h.push({type:"progress",state:w,...B.progress()||{}}):w==="error"?h.push({type:"error",code:"model_failed",message:B.health().error||"model failed to load",fatal:!0}):c.diarize&&["downloading","loading"].includes(D.state())?h.push({type:"diarize-progress",state:D.state(),...D.progress()||{}}):Co.get(c)!==w&&(Co.set(c,w),h.push({type:"state",state:w}))}const S=c?.redact?await Se(t.pro?.entitlementToken):!0;for(const w of p)c?h.push(await s(c,w,S)):w.type!=="final"&&w.type!=="interim"&&h.push(w);return h};if(e[2]==="/audio"&&n.method==="POST"){const c=B.getSession(r)||B.endedSession(r);try{const p=await T(n,t.maxBodyBytes);B.pushAudio(r,B.toFloat32(p));const h=await i(c);return a(o,200,{ok:!0,state:B.state(),...h?{events:h}:{}})}catch(p){const h=p.code==="no_session"?await i(c).catch(()=>null):null;return a(o,p.code==="no_session"?404:400,{error:{message:p.message,type:p.code||"stt_error"},...h?{events:h}:{}})}}if(e[2]==="/events"&&n.method==="GET"){const c=B.getSession(r);if(!c)return a(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 p=_=>o.write(`data: ${JSON.stringify(_)}
|
|
55
|
+
`),xe.add(o),n.on("close",()=>xe.delete(o));return}if(l==="/v1/history/records"&&n.method==="GET"){const e=j.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(g.searchParams.get("since"))||0,cursor:g.searchParams.get("cursor")||"",limit:Number(g.searchParams.get("limit"))||200,kind:g.searchParams.get("kind")||null,bytes:Number(g.searchParams.get("bytes"))||0,afterRev:g.searchParams.has("after_rev")?Number(g.searchParams.get("after_rev"))||0:null});return a(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(g.searchParams.get("limit"))||50)),r=Math.max(0,Number(g.searchParams.get("offset"))||0),s=g.searchParams.get("type")||null;return a(o,200,{ok:!0,...j.list({limit:e,offset:r,type:s})})}if(l==="/v1/history/get"&&n.method==="GET"){const e=g.searchParams.get("maxChars")!=null?Math.max(1,Number(g.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(g.searchParams.get("offset"))||0),s=j.get(String(g.searchParams.get("id")||""),{maxChars:e,offset:r});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(l==="/v1/history/key"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:eo()});if(l==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Ir(String(e.passphrase)):Rr();const r=e.passphrase?await gt(j,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&ze(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return a(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 gt(j,mt());return e.ok&&e.whole&&ze(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(l==="/ner"){if(n.method==="GET"){const e=await Ro(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await et(t),R.state()!=="off"){if(!R.isReady()){const r=R.health();return a(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 s="",i=!1;try{const p=JSON.parse(r.toString("utf8"));s=p?.text||"",i=p?.strict===!0}catch{}const d=await R.detect(s,{strict:i});return a(o,200,{entities:d})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=Io(t);if(!e){const r=R.modelOnDisk(t.ner?.model||void 0);return a(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:R.state(),model:t.ner?.model||null})}try{const r=await T(n,t.maxBodyBytes),s=await Ze(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),i=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(i)}catch(r){return a(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 a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Et(t)});try{let r=e;const s=await Te(t.pro?.entitlementToken);await et(t);const i=await Qe([ct(()=>r,d=>{r=d})],t.redaction,{isPro:s});return a(o,200,{text:r,count:i.count||0,sanitized:i.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Do(i.vault,"types")||[],detector:Et(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(l==="/ner/models"){if(n.method==="GET"){const e=R.health().model||t.ner?.model||null,r=Math.round(wt.totalmem()/1048576),s=ha(po,{totalRamMB:r}).map(i=>({...i,installed:R.modelOnDisk(i.id)}));for(const i of[e,...R.modelsOnDisk()])!i||s.some(d=>d.id===i)||s.push({id:i,label:i,lang:"—",custom:!0,installed:R.modelOnDisk(i),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:R.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Dr(),recommendation:qt(s,{totalRamMB:r},[]),state:R.state(),progress:R.progress(),available:s})}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 s=Math.round(wt.totalmem()/1048576),i=qt(po.map(d=>({...d,installed:R.modelOnDisk(d.id)})),{totalRamMB:s},[]);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 s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!(ho(d)||yo(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const i=r||t.ner?.model||R.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==i),r&&xo(t,r);try{ke(t,se())}catch{}return(async()=>{r&&await R.setModel(r,{onLog:p=>console.log(p)});const d=Mr(t.ner,{log:p=>console.log(p)});for(const p of R.companions())d.includes(p.model)||await R.removeCompanion(p.model);for(const p of d)await R.addCompanion(p,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});R.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:i,union:t.ner.union,companions:R.companions(),state:R.state()})}if(!r||!(ho(r)||yo(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});xo(t,r);try{ke(t,se())}catch{}return R.setModel(r,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:r,state:R.state(),progress:R.progress()})}}if(l==="/stt/models"){if(n.method==="GET"){const e=P.health().model||t.stt?.model||tt,r={platform:process.platform,arch:process.arch,helper:!!yt()},s=ya.map(i=>{const d=fo(i,r);return{...i,installed:P.modelOnDisk(i.id),...d?{unavailable:d}:{}}});return e&&!s.some(i=>i.id===e)&&s.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:P.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:P.state(),progress:P.progress(),available:s,dtype:t.stt?.dtype||"auto",loadedDtype:P.health().dtype,runtime:P.health().runtime,dtypes:wa})}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||!(fa(r)||ga(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=fo(ka(r),{platform:process.platform,arch:process.arch,helper:!!yt()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const i=typeof e.dtype=="string"&&ba(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},i&&(t.stt.dtype=i==="auto"?null:i);try{ke(t,se())}catch{}return P.setModel(r,{onLog:d=>console.log(d),dtype:i||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:At(t,{installing:!0})}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:P.state(),progress:P.progress(),speaker:{id:M.activeModel(),state:M.state(),installed:M.modelOnDisk()}})}}if(l==="/diarize/model"){if(n.method==="GET"){const e=M.activeModel(),r=ca.map(s=>({...s,installed:M.modelOnDisk(s.id)})).sort((s,i)=>(i.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:M.state(),threshold:M.activeThreshold(),segment:da.health(),progress:M.progress(),available: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){if(!uo(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await M.setModel(r,{log:s=>console.log(s)}))return a(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{ke(t,se())}catch{}return M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:M.activeModel(),state:M.state(),threshold:M.activeThreshold(),progress:M.progress()})}return M.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:M.activeModel(),state:M.state(),threshold:M.activeThreshold(),progress:M.progress()})}}if(l==="/tts/models"){if(n.method==="GET"){const e=D.health().model||t.tts?.model||So(kt()),r=kt(),s=go.find(d=>d.id===e)||null,i=go.map(d=>({...d,installed:D.modelOnDisk(d.id),unavailable:d.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!i.some(d=>d.id===e)&&i.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:D.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:D.state(),progress:D.progress(),available:i,voice:t.tts?.voice||(nt(e)==="pocket-tts"?ot:_e),arch:D.arch(),supportsVoices:D.arch()?D.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:D.arch()?D.supportsCustomVoices():!!s?.customVoices,sampleRate:D.sampleRate(),voices:D.isPocket()||!D.arch()&&nt(e)==="pocket-tts"?(D.builtinVoices().length?D.builtinVoices():Ea).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:D.builtinVoices().includes(d)})):D.arch()&&D.arch()!=="style-tts2"?[]:va.map(d=>({...d,installed:D.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:D.health().dtype,runtime:D.health().runtime,dtypes:xa})}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&&!(Sa(r)||Ta(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const d=me.parseCustomVoice(s);if(!(d?!!me.getVoice(d):rt(s)||wo(s)&&bo(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&_a(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:ko,voice:_e,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const d=Oa(r),p=me.parseCustomVoice(t.tts.voice||""),h=!!(p&&me.getVoice(p));if(d&&!h)if(nt(r)==="pocket-tts")t.tts.voice=ot;else{const w=me.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!d&&h&&(t.tts.voice=_e);const S=nt(r)==="pocket-tts";S&&!me.parseCustomVoice(t.tts.voice||"")&&!rt(t.tts.voice)&&(t.tts.voice=ot),!S&&rt(t.tts.voice)&&(t.tts.voice=_e)}i&&(t.tts.dtype=i==="auto"?null:i);try{ke(t,se())}catch{}return r&&D.setModel(r,{onLog:d=>console.log(d),dtype:i||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:D.state(),progress:D.progress()})}}if(l==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:me.listVoices(),usable:D.supportsCustomVoices(),embedder:M.activeModel(),embedderReady:M.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():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,i=e&&typeof e.id=="string"?e.id.trim():"";if(i){if(!me.getVoice(i))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...me.renameVoice(i,r),usable:D.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!M.isReady()){const b=M.download({onLog:L=>console.log(L)}),N=Symbol("timeout"),x=await Promise.race([b.then(()=>null).catch(L=>L),new Promise(L=>setTimeout(()=>L(N),ms))]);if(x===N||!M.isReady())return a(o,503,{error:{message:x===N?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${M.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:M.progress()})}const d=Float32Array.from(s),p=await M.embed(d);let h=null;try{const b=await D.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:N=>console.log(N)});b&&(h=await b.encodeVoice(ps(d,16e3,24e3)))}catch(b){console.log(`[tts] pocket conditioning unavailable for this voice (${b.message})`)}const S=i?me.replaceVoice(i,{vec:p,pocket:h}):me.saveVoice({name:r,vec:p,pocket:h}),w=i&&r&&r!==S.name?me.renameVoice(i,r):S;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${w.name}" (${(S.kinds||[]).join(" + ")}, sample discarded)`),a(o,i?200:201,{...S,...w,usable:D.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=g.searchParams.get("id")||"",r=me.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=me.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:_e;try{ke(t,se())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((l==="/tts"||l==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return a(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 a(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>vo)return a(o,413,{error:{message:`text too long (max ${vo} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=$a(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,p=d||(i?i.voice:t.tts?.voice||_e);if(i&&!Aa(p))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(i){const{audio:q,contentType:Se,redacted:G}=await Pa({dest:i,text:r,voice:p,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await Te(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":Se,"Content-Length":String(q.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(G)}),o.end(q)}if(!await D.ready({onLog:q=>console.log(q),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||So(kt()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:D.health().error||"tts model not ready",type:"tts_unavailable"}});const w=Na({requested:d,configured:p,engine:D,voices:me,isPocketVoice:rt,isKnownVoice:wo,isValidVoiceId:bo,defaultVoice:_e,defaultPocketVoice:ot});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:b,customId:N,speakerEmbedding:x}=w,L=await D.synth(r,{voice:b,speed:s,speakerEmbedding:x}),ue=D.sampleRate(),be=h==="pcm"?Buffer.from(new Float32Array(L).buffer):D.toWav(L,ue);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(be.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(ue),...N||D.isPocket()||D.supportsVoices()?{"X-Tts-Voice":b}:{}}),o.end(be)}catch(S){return a(o,500,{error:{message:S.message,type:"tts_failed"}})}}if(l==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=ma(await T(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(b){return a(o,b.code===413?413:415,{error:{message:b.message,type:"bad_request"}})}const r=b=>e.find(N=>N.name===b&&!N.filename)?.data.toString("utf8").trim()||"",s=e.find(b=>b.name==="file"&&b.filename)||e.find(b=>b.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let i;try{i=await pa(s.data)}catch(b){return a(o,b.code===415?415:500,{error:{message:b.message,type:"unsupported_media"}})}const d=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",p=bt(t,"stt");let h=null;if(p.kind==="remote"||p.kind==="container")try{h=mo(p,{fetchImpl:Ze})}catch(b){return a(o,500,{error:{message:`stt provider: ${b.message}`,type:"bad_provider"}})}if(!h&&!P.isReady()&&await P.init({model:t.stt?.model||tt,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:At(t),onLog:b=>console.log(b)}),!h&&!P.isReady())return a(o,503,{error:{message:`speech model not ready: ${P.health().error||P.state()}`,type:"stt_not_ready"}});const S=r("diarize")==="true"&&t.stt?.diarize!==!1;S&&!M.isReady()&&await M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:b=>console.log(b)});const w=Date.now();try{const{id:b}=P.createSession({lang:r("language")||void 0,diarize:S,interims:!1,remote:h}),N=[],x=[];let L=null;P.subscribe(b,G=>{G.type==="final"&&G.text?N.push(G):G.type==="language"?L=G.lang:G.type==="error"&&x.push(G.message||G.code)});const ue=16e3*5;for(let G=0;G<i.pcm.length;G+=ue)P.pushAudio(b,i.pcm.subarray(G,Math.min(i.pcm.length,G+ue))),await P.decodeNow(b);if(await P.endSession(b),!N.length&&x.length)return a(o,500,{error:{message:x[0],type:"decode_failed"}});let be=0;const q=N.map((G,Uo)=>{const Lt=typeof G.startMs=="number"?G.startMs/1e3:be,Vo=(G.durationMs||0)/1e3;return be=Lt+Vo,{id:Uo,start:Math.round(Lt*100)/100,end:Math.round(be*100)/100,text:G.text,...G.speaker?{speaker:G.speaker}:{},...G.turns?{turns:G.turns.map(Ke=>({start:Math.round(Ke.startMs/10)/100,end:Math.round((Ke.startMs+Ke.durationMs)/10)/100,speaker:Ke.speaker}))}:{}}}),Se=q.map(G=>G.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Se)):d==="verbose_json"?a(o,200,{task:"transcribe",language:L||r("language")||null,duration:Math.round(i.seconds*100)/100,text:Se,segments:q,provider:p.kind,took_ms:Date.now()-w}):a(o,200,{text:Se})}catch(b){return a(o,b.code==="too_many_sessions"?429:500,{error:{message:b.message,type:b.code||"stt_error"}})}}if(l==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(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=bt(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=mo(r,{fetchImpl:Ze})}catch(d){return a(o,500,{error:{message:`stt provider: ${d.message}`,type:"bad_provider"}})}!s&&!P.isReady()&&P.init({model:t.stt?.model||tt,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:At(t),onLog:d=>console.log(d)});const i=e?.diarize===!0&&t.stt?.diarize!==!1;i&&!M.isReady()&&M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:d=>console.log(d)});try{const d=e?.poll===!0,{id:p}=P.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:i,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:d});return a(o,201,{id:p,state:P.state(),...d?{poll:!0}:{}})}catch(d){return a(o,d.code==="too_many_sessions"?429:500,{error:{message:d.message,type:d.code||"stt_error"}})}}{const e=l.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(d,p,h)=>{if(p.type!=="final"||!d.redact)return p;try{let S=p.text;return await Qe([ct(()=>S,w=>{S=w})],t.redaction,{isPro:h}),{...p,text:S}}catch{return p}},i=async d=>{const p=P.drainEvents(r);if(!p)return null;const h=[];if(d&&!d.closed){const w=d.remote?"ready":P.state();w==="downloading"||w==="loading"?h.push({type:"progress",state:w,...P.progress()||{}}):w==="error"?h.push({type:"error",code:"model_failed",message:P.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes(M.state())?h.push({type:"diarize-progress",state:M.state(),...M.progress()||{}}):Lo.get(d)!==w&&(Lo.set(d,w),h.push({type:"state",state:w}))}const S=d?.redact?await Te(t.pro?.entitlementToken):!0;for(const w of p)d?h.push(await s(d,w,S)):w.type!=="final"&&w.type!=="interim"&&h.push(w);return h};if(e[2]==="/audio"&&n.method==="POST"){const d=P.getSession(r)||P.endedSession(r);try{const p=await T(n,t.maxBodyBytes);P.pushAudio(r,P.toFloat32(p));const h=await i(d);return a(o,200,{ok:!0,state:P.state(),...h?{events:h}:{}})}catch(p){const h=p.code==="no_session"?await i(d).catch(()=>null):null;return a(o,p.code==="no_session"?404:400,{error:{message:p.message,type:p.code||"stt_error"},...h?{events:h}:{}})}}if(e[2]==="/events"&&n.method==="GET"){const d=P.getSession(r);if(!d)return a(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 p=x=>o.write(`data: ${JSON.stringify(x)}
|
|
56
56
|
|
|
57
|
-
`),h=
|
|
58
|
-
data: ${JSON.stringify(
|
|
57
|
+
`),h=d.redact?await Te(t.pro?.entitlementToken):!0,S=x=>s(d,x,h);p({type:"state",state:d.remote?"ready":P.state()});const w=setInterval(()=>{const x=d.remote?"ready":P.state();if(x==="downloading"||x==="loading"){p({type:"progress",state:x,...P.progress()||{}});return}if(x==="error"){p({type:"error",code:"model_failed",message:P.health().error||"model failed to load",fatal:!0}),clearInterval(w);return}if(d.diarize){const L=M.state();if(L==="downloading"||L==="loading"){p({type:"diarize-progress",state:L,...M.progress()||{}});return}}p({type:"state",state:x}),clearInterval(w)},500);w.unref?.();let b=Promise.resolve();const N=P.subscribe(r,x=>{b=b.then(async()=>{p(await S(x)),x.type==="end"&&(clearInterval(w),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(w),N?.()});return}if(!e[2]&&n.method==="DELETE"){const d=P.getSession(r);await P.endSession(r);const p=d?.poll?await i(d).catch(()=>null):null;return a(o,200,{ok:!0,...p?{events:p}:{}})}}}if(l==="/logs"&&n.method==="GET")return a(o,200,{entries:[...Q].reverse()});if(l==="/config"&&n.method==="GET"){const e=await Te(t.pro?.entitlementToken);return a(o,200,To(t,{proUnlocked:e,policy:Ye()}))}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 a(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{Ca(t,e)}catch(h){if(h?.code==="SHAPE")return a(o,400,{error:h.message});throw h}Vt(t),JSON.stringify(t.sandbox||null)!==r&&Ge?.restart("sandbox settings changed");try{ke(t,se())}catch(h){return a(o,500,{error:`could not persist config: ${h.message}`})}const s=t.redaction?.detection,i=!s||!s.backend||s.backend==="off",d=R.state();t.ner?.autostart&&i&&d!=="ready"&&d!=="loading"&&d!=="downloading"&&R.setModel(t.ner.model,{onLog:h=>console.log(h)}).then(h=>{h&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const p=await Te(t.pro?.entitlementToken);return a(o,200,To(t,{proUnlocked:p,policy:Ye()}))}if(n.method==="GET"&&l==="/skills")return ve(n,o,t,`/skills${Me(g,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="POST"&&l==="/v1/threads/send"){if(!V(n))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"asking another chat is not available from a linked phone yet",type:"forbidden"}});const e=j.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let r={};try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"threads/send: body must be JSON",type:"invalid_request"}})}const s=String(r.to||""),i=String(r.message||"").trim();if(!i||i.length>ro)return a(o,400,{error:{message:`threads/send: a message of 1–${ro} characters`,type:"invalid_request"}});const d=r.from&&typeof r.from=="object"?{id:String(r.from.id||"").slice(0,200),title:String(r.from.title||"").slice(0,200)}:null,p=e.get(s);if(!p||p.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const h=Ur(p,{cards:le.get("agentTools").agentTools?.value?.agents||[]});if(h.error)return a(o,409,{error:{message:h.error,type:"no_model"}});if(r.dryRun===!0)return a(o,200,{ok:!0,title:p.title,model:h.model});const S=Vr({fromTitle:d?.title,message:i}),w={thread:{id:h.thread,...p.title?{title:p.title}:{}},...h.workingDir?{workingDir:h.workingDir}:{}};let b="";try{const x=await fetch(`http://127.0.0.1:${n.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":De()||Oe(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(w))},body:JSON.stringify({model:h.model,messages:[...Fr(p),{role:"user",content:S}],stream:!1}),signal:AbortSignal.timeout(6e5)}),L=await x.json().catch(()=>null);if(!x.ok)return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${L?.error?.message||`HTTP ${x.status}`}`,type:"upstream"}});b=String(L?.choices?.[0]?.message?.content||"")}catch(x){return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${x?.message||x}`,type:"upstream"}})}const N=Wr(e.get(s)||p,{question:S,reply:b,model:h.model,from:d});e.write([N],{host:"gateway",at:Date.now()});try{const x=so(e.get(s));x&&j.bulk({upserts:[x],removes:[]})}catch{}return ze({ids:[s]}),a(o,200,{ok:!0,title:p.title,model:h.model,reply:b})}const fe=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(l)?.[1];if(n.method==="POST"&&fe)return V(n)?n.headers["x-chatpanel-link-device"]&&t.link?.agentSessions===!1?a(o,403,{error:{message:"this computer does not share its coding agents' sessions with a linked phone — Settings › Link › Phones",type:"forbidden"}}):ve(n,o,t,fe,{method:"POST",timeoutMs:3e4}):a(o,403,{error:{message:"the agents' own sessions: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&l==="/skills-quarantined")return ve(n,o,t,`/skills-quarantined${Me(g,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(l==="/skills"&&n.method==="POST")return V(n)?ve(n,o,t,"/skills",{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(l)&&n.method==="DELETE"){const e=decodeURIComponent(l.slice(8));return Nt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):V(n)?ve(n,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):a(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(l)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(l),r=decodeURIComponent(e[1]);return Nt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):V(n)?ve(n,o,t,`/skills/${encodeURIComponent(r)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(n.method==="GET"&&l==="/agent-defs")return ve(n,o,t,`/agent-defs${Me(g,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(l)){const e=decodeURIComponent(l.slice(12));return Nt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):ve(n,o,t,`/agent-defs/${encodeURIComponent(e)}${Me(g,t)}`)}if(l.startsWith("/a2a/")){if(!V(n))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&l==="/a2a/agents")return a(o,200,{agents:Or()});if(n.method==="POST"&&l==="/a2a/card"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&vr(e.url||"");const r=await Xe(e.url,{force:!!e.force,auth:String(e.auth||"")});return a(o,200,{ok:!0,card:r.card,fingerprint:r.fingerprint,fresh:r.fresh,changed:!!r.changed,url:r.url})}if(n.method==="POST"&&l==="/a2a/message"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Xe(e.url,{auth:String(e.auth||"")})).card,s=await Sr({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),returnImmediately:!!e.returnImmediately,contextId:String(e.contextId||""),taskId:String(e.taskId||"")});return a(o,200,{ok:!0,...s})}if(n.method==="POST"&&l==="/a2a/message/stream"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Xe(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const s=(i,d)=>o.write(`event: ${i}
|
|
58
|
+
data: ${JSON.stringify(d)}
|
|
59
59
|
|
|
60
|
-
`);try{const i=await br({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:c=>s(c.kind,{kind:c.kind,task:c.task,message:c.message})});s("done",i)}catch(i){s("error",{code:i.code||"ERROR",message:i.message})}return o.end()}if(n.method==="POST"&&l==="/a2a/task"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Ze(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await vr({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await kr({card:r,id:String(e.id||""),auth:String(e.auth||"")});return a(o,200,{ok:!0,...s})}return a(o,404,{error:{message:`no such a2a route: ${l}`,type:"invalid_request"}})}catch(e){const r=e instanceof Ut||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof Ut&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(l==="/agent-defs/export"||l==="/agent-defs/export-plan"))return U(n)?ve(n,o,t,l,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(l)){const e=decodeURIComponent(l.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):ve(n,o,t,`/skills/${encodeURIComponent(e)}${Be(g,t)}`,{pick:r=>({skill:r?.skill||null})})}if(l==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(l)){if(!U(n))return a(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 a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await Re(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=je(t.bridge?.token);try{const s=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:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),c=await i.json().catch(()=>({}));return a(o,i.status,c)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(l)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(l),r=decodeURIComponent(e[1]),s=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):ve(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${Be(g,t)}`)}if(n.method==="GET"&&/\/models$/.test(l)){const e=await J(),r=e.sig!==void 0&&e.sig!==C;return C=e.sig,a(o,200,await Ca(t,{serviceHealth:async()=>e,fresh:r,engineAt:d.engineAt}))}if(ds.some(e=>l===e||l.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${le}) has no ${l} — update it to use this feature`,type:"unknown_endpoint"}});const W=Xa(l,n.headers,t);let ge;try{ge=await T(n,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let ue=null,k=null,re=ge,ne=0,he=0,He=0,we=!1,Ee=!1,Nt="",$e=!0;const ee=t.logRequests&&W.redactable&&n.method==="POST"?Za(F):null,Io=Date.now();if(W.redactable&&n.method==="POST"&&ge.length){try{k=JSON.parse(ge.toString("utf8"))}catch{k=null}if(k&&qa(k,W.kind))re=ge;else if(k){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(k.tools)&&k.tools.length){const w=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Ha,b=e.narrowAll?null:_=>!Ua.test(Oo(_)),A=k.tools.length;k.tools=Yo(k.tools,Fa(k,W.kind),{cap:w,keep:b,name:Oo,description:Va}),He=A-k.tools.length}$e=await Se(t.pro?.entitlementToken);const r=Ea(t,$e);if(!r.allowed)return a(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"}});if(we=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&U(n),!we){const w=nt(k?.model,t,W.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:()=>!1}),b=w?.type==="api"?await d.decide(w,k?.model).catch(()=>null):null;Ee=b?.redact===!1,Nt=Ee?b.engine||"declared":""}!we&&!Ee&&await qe(t);const s=we?[]:W.adapter.collectSegments(k,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const c=ee?ee.clock():0,{vault:p,count:h,sanitized:S}=we?{vault:null,count:0,sanitized:0}:await Ke(s,t.redaction,{signal:i.signal,isPro:$e,sanitizeOnly:Ee,onEgress:w=>Tt.push(So({ts:Date.now(),client:"redaction",tool:`detect:${w.backend}@${w.host||"local"}`,ok:w.ok,ms:w.ms,error:w.error}))});if(ee&&ee.lap("redact",c),ue=p,ne=h,he=S||0,h>0&&o.setHeader("x-chatpanel-redacted",String(h)),!$e&&h>0){$a(t,$e);try{ke(t,ie())}catch{}}if(!we&&!Ee&&Array.isArray(k.tools)&&k.tools.length&&typeof W.adapter.injectSystemNote=="function"){const w=nt(k?.model,t,W.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:A=>!!A.service&&x.fn(A.id)==="down"}),b=!(w&&w.type==="api");W.adapter.injectSystemNote(k,Xo({toolData:t.tools?.toolData,ownTools:b}))}else!we&&h>0&&typeof W.adapter.injectSystemNote=="function"&&W.adapter.injectSystemNote(k,qo());re=Buffer.from(JSON.stringify(k),"utf8")}}const Bt=Zo({vault:ue,toolData:t.tools?.toolData}),Ue=k&&typeof k.chatpanel=="object"&&k.chatpanel||null;if(Ue&&(delete k.chatpanel,re=Buffer.from(JSON.stringify(k),"utf8")),typeof k?.model=="string"&&k.model.startsWith("fusion:")){const e=kn(k.model,t,await J());if(e?.error)return ee?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(k.model=e.model,re=Buffer.from(JSON.stringify(k),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const te={destination:String(n.headers["x-chatpanel-destination"]||Ue?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Ue?.reach||"").trim(),run:At(n.headers["x-chatpanel-run"],Ue?.run)},Ve=await J(),Dt=e=>!!e.service&&Ve(e.id)==="down";let P=nt(k?.model,t,W.kind,{destination:te.destination,down:Dt});P?.type==="agent"&&k?.model&&!te.destination&&!ja(P,k.model)&&(await Ra(t,{serviceHealth:async()=>Ve,engineAt:d.engineAt}),P=nt(k?.model,t,W.kind,{destination:te.destination,down:Dt}));const Mt=P?.service&&Ve(P.id)==="down"?await E().revive(P.service).catch(()=>null):null;if(Mt?.ok&&(x.at=0),P?.service&&Ve(P.id)==="down"&&!Mt?.ok)return ee?.commit(),a(o,503,{error:{message:`${P.id} is not running — the model ${JSON.stringify(k?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:P.service}});if(te.destination&&(!P||P.id!==te.destination))return ee?.commit(),a(o,404,{error:{message:`no destination "${te.destination}" is configured on this gateway`,type:"unknown_destination",known:Ia(t).map(e=>e.id)}});const ae=no(n.headers);if(ae&&!Vn(ae,P?.type==="api"?"api":"agent"))return ee?.commit(),a(o,403,{error:{message:`link: partner "${ae.partner}" may not use ${P?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${ae.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const Fe=ae&&W.redactable&&n.method==="POST"&&k?{caller:ae,surface:mn(ae,ae.kind==="partner"?"":y?.deviceNameOf(ae.device)),model:k.model||null,startedAt:Io}:null;ee&&(ee.meta={t:Date.now(),model:k?.model||null,dest:P?P.id:null,type:P?P.type:null,redacted:ne,sanitized:he,narrowed:He,detail:Ao(ue,t.logDetail),redaction:we?"off":Ee?`on-device (${Nt})`:t.redaction.tier||"basic",...ae?.kind==="partner"?{via:Fn(ae)}:{}});const We=Qe();if(We&&P){const e=P.type==="api"?Ht(We,{model:k?.model||"",endpoint:P.baseUrl||""}):yr(We,P.agent||P.id)?Ht(We,{model:k?.model||""}):{ok:!1,reason:`agent "${P.agent||P.id}" is not allowed by your organisation’s policy`};if(!e.ok)return ee?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(P&&P.type==="api")return P.baseUrl?es(P.baseUrl,t)?(ee?.commit(),a(o,508,{error:{message:`destination "${P.id}" points back at the gateway (${P.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):cs(n,o,{...W,pathname:l,search:g.search,base:P.baseUrl,destKey:P.apiKey,destProtocol:P.protocol,harness:Bt,trace:ee,link:Fe&&{...Fe,agentId:P.id,dest:{type:"api",id:P.id}}},re,ue):(ee?.commit(),a(o,502,{error:`destination "${P.id}" has no baseUrl`}));const it=Ce(n),Ct=it==="local"&&t.bridge?.openAgentLane?"token":it;if(Ct==="local")return ee?.commit(),a(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)),Ro=new Set(["thread","ephemeral","workingDir"]),lt=ae?.kind==="partner";if(it==="token"&&n.headers["x-chatpanel-link-device"]&&!lt&&!(te.run&&Object.keys(te.run).some(e=>!Ro.has(e)))){const e=At(null,qt(Xt(de.get("agentTools").agentTools?.value,P?.agent||k?.model)));e&&(te.run={...e,...te.run||{}})}if(lt){const e=At(null,qt(Xt(de.get("agentTools").agentTools?.value,P?.agent||k?.model)));te.run={...e||{},...Wn(te.run,ae.device)};const r=y?.partnerFolderOf(ae.device);if(!r)return ee?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});te.run.workingDir=r,te.reach="",Array.isArray(k?.tools)&&(k.tools=k.tools.filter(s=>!so(s?.function?.name??s?.name)))}const Pe=tr({...te.run||{},...te.reach?{reach:te.reach}:{},...It?{askDepth:It}:{}},Ct);Pe.reach&&o.setHeader("x-chatpanel-reach-used",Pe.reach);const jo=lt?{inbox:f,partner:ae.partner,device:ae.device,conversation:Pe.thread?.id||null}:null,Lo=Fe&&{...Fe,dest:{type:"agent",id:P?.id||"bridge"},threadId:Pe.thread?.id||null};return as(n,o,{...W,pathname:l,agentOverride:P?.agent,harness:Bt,trace:ee,run:Object.keys(Pe).length?Pe:null,owner:jo,link:Lo},k,ue,t,$e)});return I.on("close",()=>{O?.stop("closed"),An(),m.close(),y?.stop(),f.stop()}),I.on("upgrade",(n,o,g)=>{o.on("error",()=>{});const l=String(n.url||"").split("?")[0];if(y&&l.startsWith(Un)){y.acceptTunnel(n,o,g).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
|
|
60
|
+
`);try{const i=await Tr({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:d=>s(d.kind,{kind:d.kind,task:d.task,message:d.message})});s("done",i)}catch(i){s("error",{code:i.code||"ERROR",message:i.message})}return o.end()}if(n.method==="POST"&&l==="/a2a/task"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Xe(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await _r({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await xr({card:r,id:String(e.id||""),auth:String(e.auth||"")});return a(o,200,{ok:!0,...s})}return a(o,404,{error:{message:`no such a2a route: ${l}`,type:"invalid_request"}})}catch(e){const r=e instanceof Wt||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof Wt&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(l==="/agent-defs/export"||l==="/agent-defs/export-plan"))return V(n)?ve(n,o,t,l,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(l)){const e=decodeURIComponent(l.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):ve(n,o,t,`/skills/${encodeURIComponent(e)}${Me(g,t)}`,{pick:r=>({skill:r?.skill||null})})}if(l==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(l)){if(!V(n))return a(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 a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await Re(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=je(t.bridge?.token);try{const s=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:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),d=await i.json().catch(()=>({}));return a(o,i.status,d)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(l)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(l),r=decodeURIComponent(e[1]),s=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):ve(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${Me(g,t)}`)}if(n.method==="GET"&&/\/models$/.test(l)){const e=await J(),r=e.sig!==void 0&&e.sig!==C;return C=e.sig,a(o,200,await Ja(t,{serviceHealth:async()=>e,fresh:r,engineAt:c.engineAt}))}if(hs.some(e=>l===e||l.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${ie}) has no ${l} — update it to use this feature`,type:"unknown_endpoint"}});const W=rs(l,n.headers,t);let ge;try{ge=await T(n,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let ce=null,k=null,re=ge,ne=0,he=0,He=0,we=!1,$e=!1,Mt="",Pe=!0;const ee=t.logRequests&&W.redactable&&n.method==="POST"?os(F):null,Jo=Date.now();if(W.redactable&&n.method==="POST"&&ge.length){try{k=JSON.parse(ge.toString("utf8"))}catch{k=null}if(k&&ns(k,W.kind))re=ge;else if(k){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(k.tools)&&k.tools.length){const w=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Ka,b=e.narrowAll?null:x=>!Qa.test(Ao(x)),N=k.tools.length;k.tools=er(k.tools,Za(k,W.kind),{cap:w,keep:b,name:Ao,description:Ya}),He=N-k.tools.length}Pe=await Te(t.pro?.entitlementToken);const r=Ba(t,Pe);if(!r.allowed)return a(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"}});if(we=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&V(n),!we){const w=at(k?.model,t,W.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:()=>!1}),b=w?.type==="api"?await c.decide(w,k?.model).catch(()=>null):null;$e=b?.redact===!1,Mt=$e?b.engine||"declared":""}!we&&!$e&&await et(t);const s=we?[]:W.adapter.collectSegments(k,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const d=ee?ee.clock():0,{vault:p,count:h,sanitized:S}=we?{vault:null,count:0,sanitized:0}:await Qe(s,t.redaction,{signal:i.signal,isPro:Pe,sanitizeOnly:$e,onEgress:w=>_t.push(Oo({ts:Date.now(),client:"redaction",tool:`detect:${w.backend}@${w.host||"local"}`,ok:w.ok,ms:w.ms,error:w.error}))});if(ee&&ee.lap("redact",d),ce=p,ne=h,he=S||0,h>0&&o.setHeader("x-chatpanel-redacted",String(h)),!Pe&&h>0){Ma(t,Pe);try{ke(t,se())}catch{}}if(!we&&!$e&&Array.isArray(k.tools)&&k.tools.length&&typeof W.adapter.injectSystemNote=="function"){const w=at(k?.model,t,W.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:N=>!!N.service&&_.fn(N.id)==="down"}),b=!(w&&w.type==="api");W.adapter.injectSystemNote(k,or({toolData:t.tools?.toolData,ownTools:b}))}else!we&&h>0&&typeof W.adapter.injectSystemNote=="function"&&W.adapter.injectSystemNote(k,rr());re=Buffer.from(JSON.stringify(k),"utf8")}}const Dt=tr({vault:ce,toolData:t.tools?.toolData}),Ue=k&&typeof k.chatpanel=="object"&&k.chatpanel||null;if(Ue&&(delete k.chatpanel,re=Buffer.from(JSON.stringify(k),"utf8")),typeof k?.model=="string"&&k.model.startsWith("fusion:")){const e=Tn(k.model,t,await J());if(e?.error)return ee?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(k.model=e.model,re=Buffer.from(JSON.stringify(k),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const te={destination:String(n.headers["x-chatpanel-destination"]||Ue?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Ue?.reach||"").trim(),run:Bt(n.headers["x-chatpanel-run"],Ue?.run)},Ve=await J(),Ct=e=>!!e.service&&Ve(e.id)==="down";let A=at(k?.model,t,W.kind,{destination:te.destination,down:Ct});A?.type==="agent"&&k?.model&&!te.destination&&!Ha(A,k.model)&&(await Ga(t,{serviceHealth:async()=>Ve,engineAt:c.engineAt}),A=at(k?.model,t,W.kind,{destination:te.destination,down:Ct}));const It=A?.service&&Ve(A.id)==="down"?await E().revive(A.service).catch(()=>null):null;if(It?.ok&&(_.at=0),A?.service&&Ve(A.id)==="down"&&!It?.ok)return ee?.commit(),a(o,503,{error:{message:`${A.id} is not running — the model ${JSON.stringify(k?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:A.service}});if(te.destination&&(!A||A.id!==te.destination))return ee?.commit(),a(o,404,{error:{message:`no destination "${te.destination}" is configured on this gateway`,type:"unknown_destination",known:za(t).map(e=>e.id)}});const ae=io(n.headers);if(ae&&!Kn(ae,A?.type==="api"?"api":"agent"))return ee?.commit(),a(o,403,{error:{message:`link: partner "${ae.partner}" may not use ${A?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${ae.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const Fe=ae&&W.redactable&&n.method==="POST"&&k?{caller:ae,surface:yn(ae,ae.kind==="partner"?"":y?.deviceNameOf(ae.device)),model:k.model||null,startedAt:Jo}:null;ee&&(ee.meta={t:Date.now(),model:k?.model||null,dest:A?A.id:null,type:A?A.type:null,redacted:ne,sanitized:he,narrowed:He,detail:Do(ce,t.logDetail),redaction:we?"off":$e?`on-device (${Mt})`:t.redaction.tier||"basic",...ae?.kind==="partner"?{via:Qn(ae)}:{}});const We=Ye();if(We&&A){const e=A.type==="api"?Ft(We,{model:k?.model||"",endpoint:A.baseUrl||""}):br(We,A.agent||A.id)?Ft(We,{model:k?.model||""}):{ok:!1,reason:`agent "${A.agent||A.id}" is not allowed by your organisation’s policy`};if(!e.ok)return ee?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(A&&A.type==="api")return A.baseUrl?as(A.baseUrl,t)?(ee?.commit(),a(o,508,{error:{message:`destination "${A.id}" points back at the gateway (${A.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):ys(n,o,{...W,pathname:l,search:g.search,base:A.baseUrl,destKey:A.apiKey,destProtocol:A.protocol,harness:Dt,trace:ee,link:Fe&&{...Fe,agentId:A.id,dest:{type:"api",id:A.id}}},re,ce):(ee?.commit(),a(o,502,{error:`destination "${A.id}" has no baseUrl`}));const lt=Ce(n),Rt=lt==="local"&&t.bridge?.openAgentLane?"token":lt;if(Rt==="local")return ee?.commit(),a(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 jt=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),zo=new Set(["thread","ephemeral","workingDir"]),dt=ae?.kind==="partner";if(lt==="token"&&n.headers["x-chatpanel-link-device"]&&!dt&&!(te.run&&Object.keys(te.run).some(e=>!zo.has(e)))){const e=Bt(null,oo(to(le.get("agentTools").agentTools?.value,A?.agent||k?.model)));e&&(te.run={...e,...te.run||{}})}if(dt){const e=Bt(null,oo(to(le.get("agentTools").agentTools?.value,A?.agent||k?.model)));te.run={...e||{},...Yn(te.run,ae.device)};const r=y?.partnerFolderOf(ae.device);if(!r)return ee?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});te.run.workingDir=r,te.reach="",Array.isArray(k?.tools)&&(k.tools=k.tools.filter(s=>!co(s?.function?.name??s?.name)))}const Ae=ar({...te.run||{},...te.reach?{reach:te.reach}:{},...jt?{askDepth:jt}:{}},Rt);Ae.reach&&o.setHeader("x-chatpanel-reach-used",Ae.reach);const Go=dt?{inbox:f,partner:ae.partner,device:ae.device,conversation:Ae.thread?.id||null}:null,Ho=Fe&&{...Fe,dest:{type:"agent",id:A?.id||"bridge"},threadId:Ae.thread?.id||null};return cs(n,o,{...W,pathname:l,agentOverride:A?.agent,harness:Dt,trace:ee,run:Object.keys(Ae).length?Ae:null,owner:Go,link:Ho},k,ce,t,Pe)});return I.on("close",()=>{O?.stop("closed"),Mn(),m.close(),y?.stop(),f.stop()}),I.on("upgrade",(n,o,g)=>{o.on("error",()=>{});const l=String(n.url||"").split("?")[0];if(y&&l.startsWith(Wn)){y.acceptTunnel(n,o,g).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
|
|
61
61
|
connection: close\r
|
|
62
62
|
content-length: 0\r
|
|
63
63
|
\r
|
|
64
|
-
`)}catch{}}),I.once("listening",()=>{E()}),I.linkHost=y,I.runtimeDefaults=()=>E().ensureDefaults(),I}function
|
|
64
|
+
`)}catch{}}),I.once("listening",()=>{E()}),I.linkHost=y,I.runtimeDefaults=()=>E().ensureDefaults(),I}function Bt(t,c){let u=c&&typeof c=="object"?c:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const m={};if(Array.isArray(u.grants)&&(m.grants=u.grants.map(y=>String(y).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const y=u.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(u.connectionId&&(m.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(m.workingDir=u.workingDir.trim().slice(0,1024)),Ra.includes(u.permissionMode)&&u.permissionMode!=="default"&&(m.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const y=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(v=>String(v).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),$=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(v=>String(v).slice(0,1024)).filter(Boolean).slice(0,32),B=u.sandbox.outside===!0,O=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(v=>String(v).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(y.length||$.length||B||O.length)&&(m.sandbox={...y.length?{hosts:y}:{},...$.length?{write:$}:{},...B?{outside:!0}:{},...O.length?{signIn:O}:{}})}const f=Jr(u.thread);return f&&(m.thread=f),u.ephemeral===!0&&(m.ephemeral=!0),Object.keys(m).length?m:null}let Ge=null,it=null;async function ol(t=Jt()){Cr();let c=null;try{c=await gr()}catch(v){throw v instanceof wr&&(console.error(`[chatpanel-gateway] org policy: ${v.message}`),process.exit(78)),v}const u=c?.policy||null;u&&(Vt(t,u),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`));const m=yr({enabled:Ut(t)});console.log(`[chatpanel-gateway] certificates: ${m.on?`this computer's list is trusted too (${m.added} added to the runtime's own)`:`the runtime's own list only — ${m.why}`}`),pr(globalThis,{allow:u?.egress?(v,{local:_})=>kr(u,v,{local:_}):null}),Oe();const f=fs(t),y=Br(t),$=Wo(t);let B=!1;f.on("error",v=>{if(v&&v.code==="EADDRINUSE"){const _=st(t.host)?"127.0.0.1":t.host;fetch(`http://${_}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(C=>C.ok?C.json():null).catch(()=>null).then(C=>{const J=!!(C?.version&&typeof C.tier=="string"),U=zr({name:"gateway",self:ie,holder:J?{ours:J,version:C.version}:null,managedBy:Gr(process.env),port:t.port});if(U.action==="standby"||B&&!C){if(!B)for(const E of U.lines)console.error(E);B=!0,setTimeout(()=>f.listen(t.port,t.host),Hr);return}if(J){const E=C.managedBy?` (run by ${C.managedBy})`:"";for(const[H,z]of U.lines.entries())console.error(H===0?z.replace(` on ${t.port}`,` at http://${_}:${t.port}${E}`):z)}else{const E=rn(t.port);console.error(`Port ${t.port} is held by ${E||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${se()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${v?.message||v}`),process.exit(1)}),f.listen(t.port,t.host,()=>{B&&console.log(" standby : the other gateway is gone — this copy has the port now"),B=!1,console.log(`ChatPanel Privacy Gateway v${ie} on http://${t.host}:${t.port}`),f.linkHost?.start().catch(v=>console.log(` link : not started (${v?.message||v})`)),f.runtimeDefaults?.().then(v=>{for(const _ of v||[])console.log(` ${_.label.toLowerCase().padEnd(9).slice(0,9)}: ${_.ok?_.already?"running":_.adopted?"already running — adopted":"started":`not started (${_.skipped})`}`)}).catch(v=>console.log(` runtime : defaults not started (${v?.message||v})`)),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");for(const v of La(t))console.log(` ⚠ sandbox : ${v}`);console.log(` confined : ${cn(ht({stateDir:Je.dirname(se())}))}`),it={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},on(t,{childEnv:()=>({...ja(t,process.env,Ye()),...Ia(t)})}).then(v=>{Ge=v}).catch(v=>{it={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${v?.message||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…)":"")),st(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),eo()&>(j,mt()).then(v=>{v?.ok&&(console.log(` warm : seeded ${v.ingested} records from ${v.file}`),v.whole&&ze())}).catch(()=>{});const O=()=>{y?.stop(),$.stop(),Ge?.stop(),Wa(f)};return process.on("SIGINT",O),process.on("SIGTERM",O),f}export{ss as RECORDS_MAX_BYTES,al as VERSION,fs as createGateway,us as joinUpstream,Ot as parseAgentModel,ol as start};
|
package/src/stt-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join as I}from"node:path";import{existsSync as ee,readdirSync as te}from"node:fs";import{randomUUID as ne}from"node:crypto";import{ensureLib as B,modelRoot as Y}from"./ner-engine.js";import{runtimeDtype as v,runtimeName as j,DTYPE_SUFFIX as re}from"./model-runtime.js";import{verifyModelWeights as oe}from"./model-integrity.js";import{DEFAULT_STT_MODEL as W,isEnglishOnly as G,sttModelDtype as z,isKnownSttModel as ie,sttModelEngine as H}from"./stt-models.js";import*as k from"./parakeet-engine.js";import*as E from"./diarize-engine.js";import{diarizeApproxMB as le}from"./diarize-models.js";import{makeWarmTimer as C}from"./warm-timer.js";const m=16e3,ae=m,se=3*m,ce=2,ue=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 fe(e,t){if(t>ce*m)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?ue.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}let c="off",p=null,f=null,M=null,A=null,g=null,D=null,_=null;function de(e=p||W,t=z(e)||v()){if(H(e)==="parakeet-tdt")return k.parakeetOnDisk(e,k.parakeetDtype(t));const n=I(Y(),...e.split("/"),"onnx");if(!ee(n))return!1;const r=re[t]??"";try{const o=te(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(l=>l===`decoder_model_merged${r}.onnx`||l===`decoder_model${r}.onnx`)}catch{return!1}}function Ue(){return c}function P(){return c==="ready"&&!!f}function Ke(){return g}function Oe(){return{configured:c!=="off",ok:P(),state:c,model:p,dtype:D,runtime:j(),error:M,warmMs:_?.warmMs??null}}function Xe(){return!!_?.pending()}function b(){return T.size>0||c==="loading"||c==="downloading"}async function U({log:e=()=>{}}={}){if(b())return!1;_?.disarm();const t=f;if(f=null,A=null,D=null,g=null,M=null,c="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 q(e){return e.then(t=>(t&&!b()&&_?.arm(),t))}async function Q(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(H(e)==="parakeet-tdt")return me(e,{log:t,allowDownload:n,dtype:r});const o=f,l=p;let a;try{a=await B()}catch(d){return c="error",M=`engine load failed: ${d.message}`,t(`[stt] transformers.js not available (${d.message}) — dictation falls back to the browser engine`),!1}const i=(r&&r!=="auto"?r:null)||z(e)||v(),s=de(e,i);if(a.env.allowRemoteModels=s?!1:!!n,!s&&!n)return c="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const y=a.env.remoteHost,w=!ie(e);if(!s&&w)try{a.env.remoteHost="https://huggingface.co/"}catch{}c=s?"loading":"downloading",s||(g={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${w?", from Hugging Face":""})…`));try{const d=u=>{if(!u)return;const R=typeof u.progress=="number"?Math.round(u.progress):g?.pct??0;u.status==="progress"||u.status==="download"||u.status==="initiate"?g={model:e,file:u.file||g?.file||null,pct:R}:u.status==="done"&&u.file&&t(`[stt] fetched ${u.file}`)};let S;try{S=await a.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:d})}catch(u){if(s||w||!n)throw u;t(`[stt] mirror fetch failed (${String(u.message).slice(0,80)}) — retrying from Hugging Face…`),a.env.remoteHost="https://huggingface.co/",a.env.allowRemoteModels=!0,S=await a.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:d})}if(!s)try{oe(e,{modelsDir:Y(),log:t})}catch(u){try{await S.dispose?.()}catch{}throw u}if(f=S,p=e,c="ready",M=null,g=null,D=i,o&&o!==S)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (in-process, offline) — local dictation active`),!0}catch(d){return M=d.message,g=null,o?(f=o,p=l,c="ready"):c="error",t(`[stt] model load failed (${d.message})${o?" — keeping previous model":""}`),!1}finally{try{a.env.remoteHost=y}catch{}}}async function me(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=f,l=p,a=k.parakeetDtype(r&&r!=="auto"?r:pe()),h=k.parakeetOnDisk(e,a);if(!h&&!n)return c="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;c=h?"loading":"downloading",h||(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:a,allowDownload:n,log:t,onProgress:y=>{g={model:e,file:y.file||null,pct:typeof y.pct=="number"?y.pct:g?.pct??0}}}),s=async y=>({text:await i.transcribe(y)});if(s.__parakeet=!0,s.dispose=()=>i.dispose(),f=s,p=e,c="ready",M=null,g=null,D=a,o&&o!==s)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${a} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return M=i.message,g=null,o?(f=o,p=l,c="ready"):c="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}function pe(){return k.PARAKEET_DEFAULT_DTYPE}const ge=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<=ge||e==="download"?{allowDownload:!0}:null}function K(e,{log:t=()=>{},warmMs:n}={}){const r=he({mode:e,onDisk:E.modelOnDisk(),ready:E.isReady(),approxMB:le(E.activeModel())});r&&E.init({...r,warmMs:n,onLog:t})}function Be(e={}){if(A)return A;const t=typeof e.onLog=="function"?e.onLog:()=>{};return p=e.model||W,c="loading",_=C({warmMs:e.warmMs,busy:b,log:t,unload:()=>U({log:t})}),A=q(Q(p,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})).then(n=>(n&&K(e.speaker,{log:t,warmMs:e.warmMs}),n)),A}async function Ye(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;const r=H(e)==="parakeet-tdt"?k.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:k.PARAKEET_DEFAULT_DTYPE):t.dtype&&t.dtype!=="auto"?t.dtype:z(e)||v();if(e===p&&P()&&D===r)return K(t.speaker,{log:n,warmMs:t.warmMs}),!0;_??=C({warmMs:t.warmMs,busy:b,log:n,unload:()=>U({log:n})});const o=await q(Q(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype}));return o&&K(t.speaker,{log:n,warmMs:t.warmMs}),o}const ye=8,_e=12e4,we=6e4,Me=1200,V=12,O=700,$=.008,Te=30,T=new Map,x=new Map;let N=Promise.resolve();function je(){return T.size}const ke=300,Ee=3e3;function Se(e){const t=Number(e);return Number.isFinite(t)?Math.min(Ee,Math.max(ke,Math.round(t))):O}function We({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=O,interims:l=!0,remote:a=null,poll:h=!1}={}){if(T.size>=ye){const s=new Error("too many concurrent dictation sessions");throw s.code="too_many_sessions",s}const i={id:ne(),endSilenceMs:Se(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:a||null,interims:l!==!1&&!a,chunks:[],samples:0,listeners:new Set,poll:h?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return T.set(i.id,i),_?.disarm(),i.diarizer&&E.retain(),J(i),{id:i.id}}function X(e){return T.get(String(e||""))||null}function Ge(e,t){const n=X(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function L(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function qe(e){const t=String(e||""),n=T.get(t);if(n)return n.poll?n.poll.splice(0):null;const r=x.get(t);return r?(clearTimeout(r.timer),x.delete(t),r.session.poll.splice(0)):null}function Qe(e){return x.get(String(e||""))?.session||null}function J(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>Le(e.id).catch(()=>{}),we),e.idleTimer.unref?.()}function Ve(e,t){const n=X(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,J(n),xe(n))}function Je(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 xe(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+Me-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,N=N.then(()=>Z(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function Ae(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 F(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let l=t;l<n;l++)r+=e[l]*e[l];return Math.sqrt(r/o)}function De(e){const t=Math.round(.02*m);let n=0,r=e.length;for(let o=0;o+t<=e.length;o+=t)if(F(e,o,o+t)>=$){n=o;break}for(let o=e.length-t;o>=0;o-=t)if(F(e,o,o+t)>=$){r=o+t;break}return r>n?e.subarray(n,r):e}async function be(e){try{const t=await B(),n=f?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>m*8?e.subarray(0,m*8):e,o=await f.processor(r),l=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),a=await f.model({...o,decoder_input_ids:l});let h=null,i=-1/0;for(const[s,y]of Object.entries(n.lang_to_id)){const w=Number(a.logits.data[y]);w>i&&(i=w,h=s)}return h?h.slice(2,-2):null}catch{return null}}async function Z(e,{flush:t=!1}={}){if(e.closed&&!t||!e.remote&&!P()||!e.samples)return;e.lastDecodeAt=Date.now();const n=Ae(e),r=Math.round((e.endSilenceMs||O)/1e3*m),o=n.length>r&&F(n,n.length-r)<$;if(F(n)<$){n.length>m*5&&(e.chunks=[n.subarray(n.length-m)],e.samples=m);return}if(!e.interims&&!t&&!o&&n.length<V*m)return;if(!e.remote&&!e.lang&&!e.langTried&&!G(p)&&!f?.__parakeet&&n.length>=m){e.langTried=!0;const i=await be(n);i&&(e.lang=i,L(e,{type:"language",lang:i}))}let l="";try{if(e.remote)l=(await e.remote.transcribe(n,{lang:e.lang})).text;else{const i=G(p)?{}:{language:e.lang||void 0,task:"transcribe"},s=await f(n,i);l=String(s?.text||"").trim()}}catch(i){L(e,{type:"error",code:"decode_failed",message:i.message,fatal:!1});return}if(!l)return;const a=n.length>=V*m,h=n.length>=Te*m;if(t||o||a||h){const i=t?"flush":o?"silence":h?"overflow":"length",s=i==="flush"||i==="silence";e.chunks=[],e.samples=0,e.lastInterim="";const y=De(n);if(fe(l,y?y.length:0))return;let w=null;if(e.diarizer)try{const d=e.speakerLabel?null:y,S=d?await E.embed(d):null,u=!!d&&d.length<ae,R=!!d&&d.length<se;w=e.diarizer.assign(S,{pinnedLabel:e.speakerLabel,weak:u,thin:R})}catch{}L(e,{type:"final",text:l,reason:i,endOfTurn:s,durationMs:Math.round(n.length/m*1e3),...w?{speaker:w}:{}})}else l!==e.lastInterim&&(e.lastInterim=l,L(e,{type:"interim",text:l}))}async function Le(e){const t=X(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(()=>Z(t,{flush:!0}).catch(()=>{})))}finally{if(L(t,{type:"end"}),t.listeners.clear(),T.delete(t.id),t.poll){const n=setTimeout(()=>x.delete(t.id),_e);n.unref?.(),x.set(t.id,{session:t,timer:n})}t.diarizer&&E.release(),T.size===0&&P()&&_?.arm()}return!0}function Ze(){for(const e of T.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);T.clear();for(const e of x.values())clearTimeout(e.timer);x.clear(),_?.disarm(),_=null,c="off",p=null,f=null,M=null,A=null,g=null}function Ie(e,t="test/fake",{warmMs:n=null,dtype:r=null}={}){f=e,p=t,c=e?"ready":"off",D=r,n!==null&&(_=C({warmMs:n,busy:b,unload:()=>U()}),e&&_.arm())}export{ge as AUTO_FETCH_MAX_MB,m as SAMPLE_RATE,se as THIN_SPEAKER_SAMPLES,ae as WEAK_SPEAKER_SAMPLES,Ze as _reset,Ie as _setPipeForTest,Se as clampEndSilence,We as createSession,qe as drainEvents,Le as endSession,Qe as endedSession,X as getSession,Oe as health,Be as init,P as isReady,fe as looksHallucinated,de as modelOnDisk,Ke as progress,Ve as pushAudio,v as runtimeDtype,j as runtimeName,je as sessionCount,Ye as setModel,he as speakerPlan,Ue as state,Ge as subscribe,Je as toFloat32,U as unload,Xe as warmPending};
|
|
1
|
+
import{join as Ee}from"node:path";import{existsSync as Te,readdirSync as ke}from"node:fs";import{randomUUID as xe}from"node:crypto";import{ensureLib as oe,modelRoot as ie}from"./ner-engine.js";import{runtimeDtype as B,runtimeName as le,DTYPE_SUFFIX as Se}from"./model-runtime.js";import{verifyModelWeights as be}from"./model-integrity.js";import{DEFAULT_STT_MODEL as ae,isEnglishOnly as se,sttModelDtype as q,isKnownSttModel as De,sttModelEngine as P}from"./stt-models.js";import*as D from"./parakeet-engine.js";import*as Q from"./coreml-stt-engine.js";import*as b from"./diarize-engine.js";import*as L from"./segment-engine.js";import{turnsFromSpans as Le,mainLocal as Ae,timeByLocal as ve,audioOfLocal as $e}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as Fe}from"./diarize-models.js";import{makeWarmTimer as V}from"./warm-timer.js";const h=16e3,ce=h,ue=3*h,Pe=2,Ne=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 Re(e,t){if(t>Pe*h)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?Ne.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}let s="off",w=null,g=null,M=null,A=null,y=null,v=null,E=null;function Oe(e=w||ae,t=q(e)||B()){if(P(e)==="parakeet-tdt")return D.parakeetOnDisk(e,D.parakeetDtype(t));if(P(e)==="coreml-tdt")return Q.coremlOnDisk(e);const n=Ee(ie(),...e.split("/"),"onnx");if(!Te(n))return!1;const r=Se[t]??"";try{const o=ke(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(i=>i===`decoder_model_merged${r}.onnx`||i===`decoder_model${r}.onnx`)}catch{return!1}}function mt(){return s}function K(){return s==="ready"&&!!g}function pt(){return y}function ht(){return{configured:s!=="off",ok:K(),state:s,model:w,dtype:v,runtime:le(),error:M,warmMs:E?.warmMs??null}}function gt(){return!!E?.pending()}function O(){return k.size>0||s==="loading"||s==="downloading"}async function J({log:e=()=>{}}={}){if(O())return!1;E?.disarm();const t=g;if(g=null,A=null,v=null,y=null,M=null,s="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((E?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function fe(e){return e.then(t=>(t&&!O()&&E?.arm(),t))}async function de(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(P(e)==="parakeet-tdt")return ze(e,{log:t,allowDownload:n,dtype:r});if(P(e)==="coreml-tdt")return He(e,{log:t,allowDownload:n});const o=g,i=w;let l;try{l=await oe()}catch(_){return s="error",M=`engine load failed: ${_.message}`,t(`[stt] transformers.js not available (${_.message}) — dictation falls back to the browser engine`),!1}const a=(r&&r!=="auto"?r:null)||q(e)||B(),f=Oe(e,a);if(l.env.allowRemoteModels=f?!1:!!n,!f&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const p=l.env.remoteHost,d=!De(e);if(!f&&d)try{l.env.remoteHost="https://huggingface.co/"}catch{}s=f?"loading":"downloading",f||(y={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${d?", from Hugging Face":""})…`));try{const _=m=>{if(!m)return;const j=typeof m.progress=="number"?Math.round(m.progress):y?.pct??0;m.status==="progress"||m.status==="download"||m.status==="initiate"?y={model:e,file:m.file||y?.file||null,pct:j}:m.status==="done"&&m.file&&t(`[stt] fetched ${m.file}`)};let c;try{c=await l.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:_})}catch(m){if(f||d||!n)throw m;t(`[stt] mirror fetch failed (${String(m.message).slice(0,80)}) — retrying from Hugging Face…`),l.env.remoteHost="https://huggingface.co/",l.env.allowRemoteModels=!0,c=await l.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:_})}if(!f)try{be(e,{modelsDir:ie(),log:t})}catch(m){try{await c.dispose?.()}catch{}throw m}if(g=c,w=e,s="ready",M=null,y=null,v=a,o&&o!==c)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${a} (in-process, offline) — local dictation active`),!0}catch(_){return M=_.message,y=null,o?(g=o,w=i,s="ready"):s="error",t(`[stt] model load failed (${_.message})${o?" — keeping previous model":""}`),!1}finally{try{l.env.remoteHost=p}catch{}}}async function ze(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=g,i=w,l=D.parakeetDtype(r&&r!=="auto"?r:Ce()),u=D.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||(y={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const a=await D.loadRecognizer({modelId:e,dtype:l,allowDownload:n,log:t,onProgress:p=>{y={model:e,file:p.file||null,pct:typeof p.pct=="number"?p.pct:y?.pct??0}}}),f=async p=>({text:await a.transcribe(p)});if(f.__transducer=!0,f.dispose=()=>a.dispose(),g=f,w=e,s="ready",M=null,y=null,v=l,o&&o!==f)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${l} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(a){return M=a.message,y=null,o?(g=o,w=i,s="ready"):s="error",t(`[stt] model load failed (${a.message})${o?" — keeping previous model":""}`),!1}}function Ce(){return D.PARAKEET_DEFAULT_DTYPE}const me="fp16";async function He(e,{log:t=()=>{},allowDownload:n=!0}={}){const r=g,o=w,i=Q.coremlOnDisk(e);if(!i&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;s=i?"loading":"downloading",i||(y={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let l=null;const u=await Q.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:a=>{y={model:e,file:a.file||null,pct:typeof a.pct=="number"?a.pct:y?.pct??0}},onExit:a=>{g===l&&(g=null,A=null,s="error",M=a,E?.disarm(),t(`[stt] ${a} — reloads on the next dictation`))}});if(l=async a=>({text:await u.transcribe(a)}),l.__transducer=!0,l.dispose=()=>u.dispose(),g=l,w=e,s="ready",M=null,y=null,v=me,r&&r!==l)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${u.version}, windows ${u.windows.join("/")} s, offline) — local dictation active`),!0}catch(l){return M=l.message,y=null,r?(g=r,w=o,s="ready"):s="error",t(`[stt] model load failed (${l.message})${r?" — keeping previous model":""}`),!1}}const Ue=30;function pe({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:r=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof r=="number"&&r<=Ue||e==="download"?{allowDownload:!0}:null}function Z(e,{log:t=()=>{},warmMs:n,allowDownload:r=!0}={}){const o=pe({mode:e,onDisk:b.modelOnDisk(),ready:b.isReady(),approxMB:Fe(b.activeModel())});if(o&&b.init({allowDownload:o.allowDownload&&r!==!1,warmMs:n,onLog:t}),e==="off"||I)return;const i=pe({mode:e,onDisk:L.modelOnDisk(),ready:L.isReady(),approxMB:L.SEGMENT_MODEL_APPROX_MB});i&&L.init({allowDownload:i.allowDownload&&r!==!1,warmMs:n,onLog:t})}let I=!1;function yt(e={}){if(A)return A;const t=typeof e.onLog=="function"?e.onLog:()=>{};return w=e.model||ae,I=e.segment===!1,s="loading",E=V({warmMs:e.warmMs,busy:O,log:t,unload:()=>J({log:t})}),A=fe(de(w,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})).then(n=>(n&&Z(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),n)),A}async function wt(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(I=t.segment===!1);const r=P(e)==="parakeet-tdt"?D.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:D.PARAKEET_DEFAULT_DTYPE):P(e)==="coreml-tdt"?me:t.dtype&&t.dtype!=="auto"?t.dtype:q(e)||B();if(e===w&&K()&&v===r)return Z(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;E??=V({warmMs:t.warmMs,busy:O,log:n,unload:()=>J({log:n})});const o=await fe(de(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype}));return o&&Z(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),o}const Be=8,Ke=12e4,Xe=6e4,je=1200,ee=12,te=700,ne=.008,Ye=.002,Ge=4;function We(e){return e>0?Math.min(ne,Math.max(Ye,e*Ge)):ne}function qe(e){const t=Math.round(.1*h),n=Math.floor(e.length/t);if(n<5)return null;const r=new Float32Array(n);for(let o=0;o<n;o++)r[o]=C(e,o*t,(o+1)*t);return r.sort(),r[Math.floor(n*.1)]}const he=30,k=new Map,$=new Map;let F=Promise.resolve();function _t(){return k.size}const Qe=300,Ve=3e3;function Je(e){const t=Number(e);return Number.isFinite(t)?Math.min(Ve,Math.max(Qe,Math.round(t))):te}function Mt({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=te,interims:i=!0,remote:l=null,poll:u=!1}={}){if(k.size>=Be){const f=new Error("too many concurrent dictation sessions");throw f.code="too_many_sessions",f}const a={id:xe(),endSilenceMs:Je(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new b.Diarizer:null,remote:l||null,interims:i!==!1&&!l,chunks:[],samples:0,listeners:new Set,poll:u?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return k.set(a.id,a),E?.disarm(),a.diarizer&&(b.retain(),L.retain()),ge(a),{id:a.id}}function X(e){return k.get(String(e||""))||null}function Et(e,t){const n=X(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function z(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Tt(e){const t=String(e||""),n=k.get(t);if(n)return n.poll?n.poll.splice(0):null;const r=$.get(t);return r?(clearTimeout(r.timer),$.delete(t),r.session.poll.splice(0)):null}function kt(e){return $.get(String(e||""))?.session||null}function ge(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>nt(e.id).catch(()=>{}),Xe),e.idleTimer.unref?.()}function xt(e,t){const n=X(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,n.pushed+=t.length,ge(n),Ze(n))}function St(e){const t=X(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),F=F.then(()=>re(t).catch(()=>{})),F)}function bt(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 Ze(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+je-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,F=F.then(()=>re(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function ye(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 Ie(e,t,n){const r=h/100,o=Math.max(0,e.length-t),i=Math.floor((e.length-o)/r),l=Math.max(1,Math.round(n/r));if(i<=l)return 0;const u=new Float32Array(i);for(let d=0;d<i;d++){let _=0;const c=o+d*r;for(let m=0;m<r;m++)_+=e[c+m]*e[c+m];u[d]=_/r}let a=-1,f=1/0,p=0;for(let d=0;d<l;d++)p+=u[d];for(let d=0;d+l<=i;d++)d>0&&(p+=u[d+l-1]-u[d-1]),p<f&&(f=p,a=d);return a<0?0:o+Math.round((a+l/2)*r)}function C(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let i=t;i<n;i++)r+=e[i]*e[i];return Math.sqrt(r/o)}function et(e,t=ne){const n=Math.round(.02*h);let r=0,o=e.length;for(let i=0;i+n<=e.length;i+=n)if(C(e,i,i+n)>=t){r=i;break}for(let i=e.length-n;i>=0;i-=n)if(C(e,i,i+n)>=t){o=i+n;break}return o>r?e.subarray(r,o):e}async function tt(e){try{const t=await oe(),n=g?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>h*8?e.subarray(0,h*8):e,o=await g.processor(r),i=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),l=await g.model({...o,decoder_input_ids:i});let u=null,a=-1/0;for(const[f,p]of Object.entries(n.lang_to_id)){const d=Number(l.logits.data[p]);d>a&&(a=d,u=f)}return u?u.slice(2,-2):null}catch{return null}}async function re(e,{flush:t=!1}={}){if(e.closed&&!t||!e.remote&&!K()||!e.samples)return;e.lastDecodeAt=Date.now();let n=ye(e);const r=n.length,o=Math.max(0,(e.pushed||0)-e.samples),i=Math.round((e.endSilenceMs||te)/1e3*h),l=qe(n);l!==null&&(e.noiseFloor==null||l<e.noiseFloor)&&(e.noiseFloor=l);const u=We(e.noiseFloor),a=n.length>i&&C(n,n.length-i)<u;if(C(n)<u){n.length>h*5&&(e.chunks=[n.subarray(n.length-h)],e.samples=h);return}if(!e.interims&&!t&&!a&&n.length<ee*h)return;let f=null;if(!t&&!a&&r>=ee*h&&r<he*h){const c=Ie(n,3*h,Math.round(.2*h));c>0&&c<n.length&&(f=n.subarray(c),n=n.subarray(0,c))}if(!e.remote&&!e.lang&&!e.langTried&&!se(w)&&!g?.__transducer&&n.length>=h){e.langTried=!0;const c=await tt(n);c&&(e.lang=c,z(e,{type:"language",lang:c}))}let p="";try{if(e.remote)p=(await e.remote.transcribe(n,{lang:e.lang})).text;else{const c=se(w)?{}:{language:e.lang||void 0,task:"transcribe"},m=await g(n,c);p=String(m?.text||"").trim()}}catch(c){z(e,{type:"error",code:"decode_failed",message:c.message,fatal:!1});return}if(!p)return;const d=r>=ee*h,_=r>=he*h;if(t||a||d||_){const c=t?"flush":a?"silence":_?"overflow":"length",m=c==="flush"||c==="silence",j=e.samples-r,H=[];f&&H.push(f),j>0&&H.push(ye(e).subarray(r)),e.chunks=H,e.samples=H.reduce((T,x)=>T+x.length,0),e.lastInterim="";const Y=et(n,u);if(Re(p,Y?Y.length:0))return;let N=null,G=null;if(e.diarizer)try{const T=e.speakerLabel?null:await L.spans(n),x=T?Le(T):[];if(x.length){const R=new Map;for(const{local:S}of ve(x)){const U=$e(n,x,S),we=U.length?await b.embed(U):null,_e=U.length<ce,Me=U.length<ue;R.set(S,e.diarizer.assign(we,{pinnedLabel:null,weak:_e,thin:Me}))}const W=Math.round(o/h*1e3);G=x.map(S=>({startMs:W+Math.round(S.start*1e3),durationMs:Math.round((S.end-S.start)*1e3),speaker:R.get(S.local)})).filter(S=>S.speaker),N=R.get(Ae(x))||null}}catch{}if(e.diarizer&&!N)try{const T=Y,x=T?await b.embed(T):null,R=!!T&&T.length<ce,W=!!T&&T.length<ue;N=e.diarizer.assign(x,{pinnedLabel:e.speakerLabel,weak:R,thin:W})}catch{}z(e,{type:"final",text:p,reason:c,endOfTurn:m,durationMs:Math.round(n.length/h*1e3),startMs:Math.round(o/h*1e3),...N?{speaker:N}:{},...G?.length?{turns:G}:{}})}else p!==e.lastInterim&&(e.lastInterim=p,z(e,{type:"interim",text:p}))}async function nt(e){const t=X(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(F=F.then(()=>re(t,{flush:!0}).catch(()=>{})))}finally{if(z(t,{type:"end"}),t.listeners.clear(),k.delete(t.id),t.poll){const n=setTimeout(()=>$.delete(t.id),Ke);n.unref?.(),$.set(t.id,{session:t,timer:n})}t.diarizer&&(b.release(),L.release()),k.size===0&&K()&&E?.arm()}return!0}function Dt(){for(const e of k.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);k.clear();for(const e of $.values())clearTimeout(e.timer);$.clear(),E?.disarm(),E=null,s="off",w=null,g=null,M=null,A=null,y=null}function Lt(e,t="test/fake",{warmMs:n=null,dtype:r=null}={}){g=e,w=t,s=e?"ready":"off",v=r,n!==null&&(E=V({warmMs:n,busy:O,unload:()=>J()}),e&&E.arm())}export{Ue as AUTO_FETCH_MAX_MB,h as SAMPLE_RATE,ue as THIN_SPEAKER_SAMPLES,ce as WEAK_SPEAKER_SAMPLES,Dt as _reset,Lt as _setPipeForTest,Je as clampEndSilence,Mt as createSession,St as decodeNow,Tt as drainEvents,nt as endSession,kt as endedSession,X as getSession,ht as health,yt as init,K as isReady,Re as looksHallucinated,Oe as modelOnDisk,qe as noiseFloorOf,pt as progress,xt as pushAudio,Ie as quietestCut,B as runtimeDtype,le as runtimeName,_t as sessionCount,wt as setModel,We as silenceGate,pe as speakerPlan,mt as state,Et as subscribe,bt as toFloat32,J as unload,gt as warmPending};
|
package/src/stt-models.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const i="istupakov/parakeet-tdt-0.6b-v3-onnx",a=[{id:"onnx-community/whisper-tiny.en",label:"Tiny (English)",lang:"English",tier:"light",approxMB:150,ramMB:400,note:"Fastest, lightest. English only — great for quick dictation on any machine."},{id:"onnx-community/whisper-base",label:"Base (multilingual)",lang:"99 languages (auto-detected)",tier:"balanced",approxMB:300,ramMB:700,note:"Small and quick to install. Detects the spoken language automatically; good accuracy at real-time speed."},{id:"onnx-community/whisper-small",label:"Small (multilingual)",lang:"99 languages (auto-detected)",tier:"accurate",approxMB:950,ramMB:1600,note:"Noticeably more accurate; needs a faster CPU to keep up in real time."},{id:"onnx-community/whisper-large-v3-turbo",label:"Large v3 Turbo (multilingual)",lang:"99 languages (auto-detected)",tier:"max",approxMB:1600,ramMB:3200,note:"Best accuracy. For powerful machines; use the native (npm) gateway for speed."},{id:"istupakov/parakeet-tdt-0.6b-v3-onnx",label:"Parakeet TDT 0.6B v3 (multilingual, fast)",lang:"25 European languages (auto-detected)",tier:"accurate",engine:"parakeet-tdt",recommended:!0,approxMB:690,ramMB:1600,note:"Recommended — NVIDIA Parakeet transducer. Several× faster than Whisper at similar or better accuracy, English + 24 EU languages. One-time download; best on the native (npm) gateway."}],
|
|
1
|
+
const i="istupakov/parakeet-tdt-0.6b-v3-onnx",a=[{id:"onnx-community/whisper-tiny.en",label:"Tiny (English)",lang:"English",tier:"light",approxMB:150,ramMB:400,note:"Fastest, lightest. English only — great for quick dictation on any machine."},{id:"onnx-community/whisper-base",label:"Base (multilingual)",lang:"99 languages (auto-detected)",tier:"balanced",approxMB:300,ramMB:700,note:"Small and quick to install. Detects the spoken language automatically; good accuracy at real-time speed."},{id:"onnx-community/whisper-small",label:"Small (multilingual)",lang:"99 languages (auto-detected)",tier:"accurate",approxMB:950,ramMB:1600,note:"Noticeably more accurate; needs a faster CPU to keep up in real time."},{id:"onnx-community/whisper-large-v3-turbo",label:"Large v3 Turbo (multilingual)",lang:"99 languages (auto-detected)",tier:"max",approxMB:1600,ramMB:3200,note:"Best accuracy. For powerful machines; use the native (npm) gateway for speed."},{id:"istupakov/parakeet-tdt-0.6b-v3-onnx",label:"Parakeet TDT 0.6B v3 (multilingual, fast)",lang:"25 European languages (auto-detected)",tier:"accurate",engine:"parakeet-tdt",recommended:!0,approxMB:690,ramMB:1600,note:"Recommended — NVIDIA Parakeet transducer. Several× faster than Whisper at similar or better accuracy, English + 24 EU languages. One-time download; best on the native (npm) gateway."},{id:"ConwayResearch/Underdog-Bark-3.0",label:"Parakeet TDT 0.6B v3 for the Neural Engine (English)",lang:"English",tier:"light",engine:"coreml-tdt",platforms:["darwin-arm64"],approxMB:200,ramMB:500,note:"The same Parakeet model, repacked for the Apple Neural Engine: a 200 MB download and the fastest dictation on a Mac. English only. Needs the Apple helper."}],s="istupakov/parakeet-tdt-0.6b-v3-onnx";function p(e){return n(e)?.engine||"whisper"}function u(e,{platform:t=process.platform,arch:r=process.arch,helper:l=!1}={}){return Array.isArray(e?.platforms)&&!e.platforms.includes(`${t}-${r}`)?"Needs a Mac with Apple Silicon.":e?.engine==="coreml-tdt"&&!l?"Needs the Apple helper — Install it on the Apple on-device row (Runtime).":null}function d(e){return a.some(t=>t.id===e)}function n(e){return a.find(t=>t.id===e)||null}function c(e){return/\.en$/.test(String(e||""))}function m(e){return n(e)?.dtype||null}function g(e){const t=String(e||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(t)&&!t.includes("..")}const o=[{id:"auto",label:"Auto (recommended)",note:"q8 on the native gateway, fp32 on the WASM binary."},{id:"q8",label:"q8 — fast, balanced",note:"Int8. Best speed/quality trade-off (native default)."},{id:"q4",label:"q4 — smallest & fastest",note:"4-bit. Least memory; slightly lower accuracy."},{id:"int8",label:"int8",note:"Alternative int8 export."},{id:"fp16",label:"fp16 — more accurate",note:"Half precision. Larger, a bit slower."},{id:"fp32",label:"fp32 — most accurate (slow)",note:"Full precision. Largest + slowest; the only one that loads on the WASM binary."}];function h(e){return o.some(t=>t.id===e)}export{i as DEFAULT_STT_MODEL,s as RECOMMENDED_STT_MODEL,o as STT_DTYPES,a as STT_MODEL_CATALOG,c as isEnglishOnly,d as isKnownSttModel,g as isValidCustomSttId,h as isValidDtype,n as sttModel,m as sttModelDtype,p as sttModelEngine,u as sttModelUnavailable};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.100.0";export{o as VERSION};
|