@chatpanel/gateway 0.85.4 → 0.85.5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.85.4",
3
+ "version": "0.85.5",
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": {
@@ -23,9 +23,9 @@
23
23
  },
24
24
  "dependencies": {
25
25
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
26
- "@chatpanel/bridge": "^0.44.1",
26
+ "@chatpanel/bridge": "^0.44.2",
27
27
  "@chatpanel/events": "^0.353.0",
28
- "@chatpanel/pii": "^0.14.0",
28
+ "@chatpanel/pii": "^0.15.0",
29
29
  "@huggingface/transformers": "^4.2.0",
30
30
  "defuddle": "^0.19.4",
31
31
  "fflate": "^0.8.3",
package/src/models.js CHANGED
@@ -1 +1 @@
1
- const t="Xenova/bert-base-NER",i=[{id:"Xenova/bert-base-NER",label:"English — standard",lang:"English",approxMB:105,note:"Default. Best English accuracy for people, organizations, and locations."},{id:"Xenova/distilbert-base-multilingual-cased-ner-hrl",label:"Multilingual — compact",lang:"10 languages",approxMB:150,note:"Covers en, es, fr, de, it, pt, nl, ar, zh, ru. Use for non-English text."},{id:"Xenova/bert-base-multilingual-cased-ner-hrl",label:"Multilingual — large",lang:"10 languages",approxMB:180,note:"Higher multilingual accuracy; larger download."},{id:"onnx-community/multilang-pii-ner-ONNX",label:"PII-specialised — multilingual",lang:"Multilingual",approxMB:282,mirrored:!1,note:"Trained for PII rather than general entities: finds addresses, postcodes, account and ID numbers, usernames and passwords. Cased text only — misses lowercase names. Fetched from Hugging Face."},{id:"openai/privacy-filter",label:"Privacy Filter — private people, addresses, secrets",lang:"English (some multilingual)",approxMB:1620,mirrored:!1,minRamMB:16384,ramMB:1e3,note:"Best at what redaction is for: finds private people (lowercase too), addresses, emails, phones, account numbers and passwords by context; skips public figures and places. Pair with a NER model for places and organisations. Large download from Hugging Face; needs about 1 GB of RAM while loaded."}];function l(a,{totalRamMB:e=0}={}){const r=n=>`${Math.round(n/1024)} GB`;return a.map(n=>{const o=Number(n.minRamMB)>0&&e>0&&e<n.minRamMB,s=n.recommended===!0||Number(n.minRamMB)>0&&e>=n.minRamMB;return{...n,recommended:s&&!o,...o?{ramNote:`needs about ${r(n.ramMB||1024)} of RAM while loaded — this machine has ${r(e)}; expect it to slow things down`}:{}}})}function d(a){const e=i.find(r=>r.id===a);return!!e&&e.mirrored!==!1}function u(a){return i.some(e=>e.id===a)}function c(a){const e=String(a||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(e)&&!e.includes("..")}export{t as DEFAULT_MODEL,i as MODEL_CATALOG,u as isKnownModel,d as isMirroredModel,c as isValidCustomModelId,l as recommendFor};
1
+ const t="Xenova/bert-base-NER",s=[{id:"Xenova/bert-base-NER",label:"English — standard",lang:"English",approxMB:105,note:"Default. Best English accuracy for people, organizations, and locations."},{id:"Xenova/distilbert-base-multilingual-cased-ner-hrl",label:"Multilingual — compact",lang:"10 languages",approxMB:150,note:"Covers en, es, fr, de, it, pt, nl, ar, zh, ru. Use for non-English text."},{id:"Xenova/bert-base-multilingual-cased-ner-hrl",label:"Multilingual — large",lang:"10 languages",approxMB:180,note:"Higher multilingual accuracy; larger download."},{id:"onnx-community/multilang-pii-ner-ONNX",label:"PII-specialised — multilingual",lang:"Multilingual",approxMB:282,mirrored:!1,note:"Trained for PII rather than general entities: finds addresses, postcodes, account and ID numbers, usernames and passwords. Cased text only — misses lowercase names. Fetched from Hugging Face."},{id:"openai/privacy-filter",label:"Privacy Filter — private people, addresses, secrets",lang:"English (some multilingual)",approxMB:1620,mirrored:!1,ramMB:1e3,note:"Best at what redaction is for: finds private people (lowercase too), addresses, emails, phones, account numbers and passwords by context; skips public figures and places. Pair with a NER model for places and organisations. Large download from Hugging Face; needs about 1 GB of RAM while loaded."}];function l(a,{totalRamMB:e=0}={}){const r=n=>`${Math.round(n/1024)} GB`;return a.map(n=>{const o=Number(n.minRamMB)>0&&e>0&&e<n.minRamMB,i=n.recommended===!0||Number(n.minRamMB)>0&&e>=n.minRamMB;return{...n,recommended:i&&!o,...o?{ramNote:`needs about ${r(n.ramMB||1024)} of RAM while loaded — this machine has ${r(e)}; expect it to slow things down`}:{}}})}function d(a){const e=s.find(r=>r.id===a);return!!e&&e.mirrored!==!1}function u(a){return s.some(e=>e.id===a)}function c(a){const e=String(a||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(e)&&!e.includes("..")}export{t as DEFAULT_MODEL,s as MODEL_CATALOG,u as isKnownModel,d as isMirroredModel,c as isValidCustomModelId,l as recommendFor};
package/src/ner-engine.js CHANGED
@@ -1 +1 @@
1
- import lt from"node:os";import{join as O}from"node:path";import{existsSync as G,mkdirSync as ct,readdirSync as Q,readFileSync as ut}from"node:fs";import{DEFAULT_MODEL as K,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 V}from"./warm-timer.js";import{makeModelFileCache as xt}from"./model-file-cache.js";const N="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 N;const n=u=>(console.warn(`[models] ignoring ${e} (${r}): ${u} — using ${N}`),N);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 ${N}`),r.replace(/\/*$/,"/"))}const bt=Mt();let d="off",g=null,y=null,b=null,S=null,E=null,L=null,h=null,_=null,P=0,C=null;const m=new Map;function R(){return process.env.CHATPANEL_MODELS_DIR||O(lt.homedir(),".chatpanel","models")}function H(t=g||K){const e=O(R(),...t.split("/"));return G(O(e,"onnx","model_quantized.onnx"))||G(O(e,"onnx","model.onnx"))}function Xt(){const t=R(),e=[];try{for(const r of Q(t,{withFileTypes:!0}))if(r.isDirectory())for(const n of Q(O(t,r.name),{withFileTypes:!0})){if(!n.isDirectory())continue;const o=`${r.name}/${n.name}`;H(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 Zt(){return d}function k(){return d==="ready"&&!!y}function It(){return{configured:d!=="off",ok:k(),state:d,model:g,error:b,runtime:wt(),dtype:y?"q8":null,stats:Pt(),companions:At(),warmMs:_?.warmMs??null}}async function St(t,{signal:e,strict:r=!1}={}){if(!k())return[];if(e?.aborted)return[];const n=String(t||""),o=await X(n,e);if(!o)return[];const s=[];for(const f of o||[]){if(Z(f,r))continue;let i=String(f.word??"");const a=f.entity_group??f.entity??"ENTITY";if(i.startsWith("##")&&s.length&&s[s.length-1].type===a){s[s.length-1].value+=i.slice(2);continue}i=i.replace(/##/g,"").trim(),i&&s.push({value:i,type:a})}const u=new Set,c=[];for(const f of s){const i=Ht(n,Rt(n,f.value.trim()));if(i.length<=1)continue;const a=`${f.type}:${i.toLowerCase()}`;u.has(a)||(u.add(a),c.push({value:i,type:f.type}))}return c}async function X(t,e){P++;try{return await Tt(t,e)}finally{P--,v()||_?.arm()}}async function Tt(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:u}of et())for(const c of o){let f=0;for(const i of Et(c.text,u.tokenizer)){if(e?.aborted)return null;const a=c.text.indexOf(i,f),x=await u(i,{aggregation_strategy:"simple"});for(const l of x||[])n.push({...l,_win:a<0?f:a,_winText:i,_model:s,_pass:c.key,_passText:c.text});a>=0&&(f=Math.max(f,a+1))}}return Nt(performance.now()-r,t.length,n.length),n}let D=!0;function te(t){D=t!==!1}const Z=(t,e)=>!e&&t._pass==="recased"&&!gt(String(t.word??"").replace(/##/g,""),t.entity_group??t.entity);async function ee(t,{signal:e,strict:r=!1}={}){if(!k())return[];const n=String(t||""),o=await X(n,e);if(!o)return[];const s=[],u=new Set;let c=-1,f=-1,i=null,a=null;for(const l of o){if(Z(l,r))continue;const p=String(l.word??"").replace(/##/g,"").trim();if(!p)continue;(l._win!==f||l._model!==i||l._pass!==a)&&(f=l._win,i=l._model,a=l._pass,c=l._win);const $=l._passText||n;let M=$.indexOf(p,c);if(M<0&&(M=$.indexOf(p,l._win)),M<0)continue;let T=M+p.length;c=T;const q=J=>!!J&&/[\p{L}\p{N}'’-]/u.test(J);for(;M>0&&q(n[M-1]);)M--;for(;T<n.length&&q(n[T]);)T++;const z=String(l.entity_group??l.entity??"ENTITY"),Y=`${M}:${T}:${z}`;if(u.has(Y))continue;u.add(Y);const B=Number(l.score);s.push({value:n.slice(M,T),type:z,start:M,end:T,score:Number.isFinite(B)?Math.max(0,Math.min(1,B)):1,model:l._model})}s.sort((l,p)=>l.start-p.start||l.end-p.end);const x=[];for(const l of s){const p=x[x.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}x.push({...l})}return m.size||D?$t(x):x}const I=["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=I.indexOf(Ot(t.type));return e<0?I.length:e}let A=[];function kt(t){A=Array.isArray(t)?t.slice():[],h&&(h={...h,union:A.slice()})}function W(t){if(t.model===g)return-1;const e=A.indexOf(t.model);return e<0?A.length:e}function $t(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;(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 ne(){const t=y?.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 oe(){const t=Number(y?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function At(){return[...m].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function tt(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===g)return!1;if(m.get(t)?.pipe)return!0;m.set(t,{pipe:null,state:H(t)?"loading":"downloading",error:null});try{const{pipe:o}=await rt(t,{log:e,allowDownload:r});return m.set(t,{pipe:o,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(o){return m.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 re(t){const e=m.get(t);if(!e)return!1;m.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function et(){const t=y?[{model:g,pipe:y}]:[];for(const[e,r]of m)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const vt=160,nt=256;function Et(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),o=Math.min(nt,Number.isFinite(r)&&r>0?r:nt)-8,s=i=>{try{return e(i).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=o)return[t];const u=[];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 a=t.slice(c,i);for(;s(a)>o&&a.length>32;){f=Math.max(32,Math.floor(a.length/2)),i=c+f;const p=t.lastIndexOf(" ",i);p>c+f/2&&(i=p),a=t.slice(c,i)}if(u.push(a),i>=t.length)break;const x=Math.max(c+1,i-vt),l=t.indexOf(" ",x);c=l>0&&l<i?l+1:i}return u}const Ct=200,w=[];function Nt(t,e,r){w.push({ms:t,chars:e,spans:r}),w.length>Ct&&w.shift()}function Pt(){if(!w.length)return{calls:0};const t=w.map(o=>o.ms).sort((o,s)=>o-s),e=o=>t[Math.min(t.length-1,Math.floor(o*t.length))],r=w.reduce((o,s)=>o+s.chars,0),n=w.reduce((o,s)=>o+s.ms,0);return{calls:w.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(w[w.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 Ht(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const n=u=>!!u&&/[\p{L}\p{N}'’-]/u.test(u);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 se(t,e={}){let r="",n=!1;try{const s=JSON.parse(e.body||"{}");r=s.text||"",n=s.strict===!0}catch{}const o=await St(r,{signal:e.signal,strict:n});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function ie(){return L}async function ot(){if(E)return E;const t=R();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(l){throw e?l:new Error(_t(l))}const{env:n,pipeline:o,Tensor:s,AutoModel:u,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:i,LogLevel:a}=r;if(n.cacheDir=t,e&&a)try{n.logLevel=a.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:(l,p,$={})=>o(l,p,$.progress_callback&&n.allowRemoteModels===!1?{...$,progress_callback:void 0}:$),Tensor:s,AutoModel:u,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:i},E}async function rt(t,{log:e=()=>{},allowDownload:r=!0,onProgress:n=()=>{}}={}){const o=await ot(),s=H(t);if(o.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const u=o.env.remoteHost,c=!ft(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 f=a=>{a&&(a.status==="progress"||a.status==="download"||a.status==="initiate"?n(a):a.status==="done"&&a.file&&e(`[ner] fetched ${a.file}`))};let i;try{i=await o.pipeline("token-classification",t,{dtype:"q8",progress_callback:f})}catch(a){if(s||c||!r)throw a;e(`[ner] mirror fetch failed (${String(a.message).slice(0,80)}) — retrying from Hugging Face…`),o.env.remoteHost="https://huggingface.co/",o.env.allowRemoteModels=!0,i=await o.pipeline("token-classification",t,{dtype:"q8",progress_callback:f})}if(!s)try{yt(t,{modelsDir:R(),log:e})}catch(a){try{await i.dispose?.()}catch{}throw a}return{pipe:i,haveLocal:s}}finally{try{o.env.remoteHost=u}catch{}}}async function st(t,{log:e=()=>{},allowDownload:r=!0}={}){const n=y,o=g;try{await ot()}catch(u){return d="error",b=`engine load failed: ${u.message}`,e(`[ner] transformers.js not available (${u.message}) — deterministic-only`),!1}const s=H(t);if(!s&&!r)return d="error",b="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;d=s?"loading":"downloading",s||(L={model:t,file:null,pct:0});try{const{pipe:u}=await rt(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(y=u,g=t,d="ready",b=null,L=null,h&&(h={...h,model:t}),n&&n!==u)try{await n.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),v()||_?.arm(),!0}catch(u){return b=u.message,L=null,n?(y=n,g=o,d="ready"):d="error",e(`[ner] model load failed (${u.message})${n?" — keeping previous model":" — deterministic-only"}`),!1}}function Dt(t={}){if(S)return S;const e=typeof t.onLog=="function"?t.onLog:()=>{};h=t,g=t.model||K,d="loading";const r=t.allowDownload!==!1;return _=V({warmMs:t.warmMs,busy:v,log:e,unload:()=>it({log:e})}),S=st(g,{log:e,allowDownload:r}).then(async n=>{const o=Array.isArray(t.union)?t.union:[];kt(o);for(const s of o)await tt(s,{log:e,allowDownload:r});return k()&&!v()&&_?.arm(),n}),S}function v(){if(P>0||d==="loading"||d==="downloading")return!0;for(const t of m.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function it({log:t=()=>{}}={}){if(v())return!1;_?.disarm();const e=et().map(r=>r.pipe);y=null,S=null,L=null,b=null,m.clear(),d=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((_?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function Ft(){try{d==="idle"&&(C||h)?await(C?C():Dt(h)):S&&await S,k()&&await at()}catch{}return k()}let U=null;function at(){const t=A.filter(e=>e&&e!==g&&!m.has(e));return t.length?(U||=(async()=>{const e=typeof h?.onLog=="function"?h.onLog:()=>{};for(const r of t)m.has(r)||(j?await j(r):await tt(r,{log:e,allowDownload:h?.allowDownload!==!1}))})().catch(()=>{}).finally(()=>{U=null}),U):Promise.resolve()}let j=null;function ae(t){j=t}async function le(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},n=e.allowDownload!==!1;if(!t)return!1;if(t===g&&k())return!0;if(t===g&&d==="idle")return Ft();const o=m.get(t);if(o?.pipe){const u=y;if(y=o.pipe,g=t,d="ready",b=null,m.delete(t),u)try{await u.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),h&&(h={...h,model:t}),!0}const s=await st(t,{log:r,allowDownload:n});return s&&(h&&(h={...h,model:t}),await at()),s}function ce(){d="off",g=null,y=null,b=null,S=null,E=null,L=null,w.length=0,m.clear(),D=!0,A=[],_?.disarm(),_=null,h=null,P=0,C=null,j=null,U=null}function ue(t,e){m.set(t,{pipe:e,state:"ready",error:null})}function fe(t,{model:e="test/model",warmMs:r=null,reload:n=null}={}){y=t,g=e,d="ready",b=null,w.length=0,n&&(C=n),r!==null&&(_=V({warmMs:r,busy:v,unload:()=>it()}),t&&_.arm())}export{ce as _reset,ue as _setCompanionForTest,ae as _setCompanionLoaderForTest,fe as _setForTest,tt as addCompanion,At as companions,St as detect,ee as detectSpans,Ft as ensure,ot as ensureLib,se as fetchAdapter,It as health,Dt as init,k as isReady,ne as labels,oe as maxTokens,H as modelOnDisk,R as modelRoot,Xt as modelsOnDisk,ie as progress,re as removeCompanion,Mt as resolveModelHost,te as setCaseRecovery,le as setModel,kt as setUnionOrder,Zt as state,Pt as stats,$t as unionSpans,it as unload,Et as windowsFor};
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};
package/src/redact.js CHANGED
@@ -1,3 +1 @@
1
- import{createVault as v,redactText as T,detectEntities as w,gatedDictionary as z,sanitizeUnicode as A,strictnessOf as b}from"@chatpanel/pii";import{ENTITIES_SCHEMA as h,entitiesFormat as N}from"./extraction.js";import{describeSchema as j,coerce as D}from"./structured.js";import*as F from"./ner-engine.js";async function U(r,o,{signal:g,isPro:x=!0,onEgress:M=null,fetchImpl:k=null,sanitizeOnly:E=!1,nerEngine:c=F}={}){const i=v();let f=0;for(const t of r){const e=t.get();if(typeof e!="string"||!e)continue;const{clean:n,removed:y}=A(e);y&&(t.set(n),f+=y)}const m=r.map(t=>t.get()).filter(t=>typeof t=="string"&&t);if(m.length===0)return{vault:i,count:0,sanitized:f};if(E)return{vault:i,count:0,sanitized:f};const a=o.tier==="full"?"full":"basic",I=z(o,x),s=o.detection,l=!!(s&&s.backend&&s.backend!=="off");a==="full"&&!l&&typeof c.ensure=="function"&&await c.ensure();const u=!l&&c.isReady();let p=[];if(a==="full"&&(l||u)){const t=u?{backend:"endpoint",url:"inproc:ner",transport:"in-process",timeoutMs:3e4,maxChars:8e3,types:s?.types,strictness:b(o)}:{...s,timeoutMs:Math.max(Number(s.timeoutMs)||0,3e4),strictness:b(o)},e=u?c.fetchAdapter:k||void 0;try{p=await w(m.join(`
2
-
3
- `),{detection:t},{signal:g,fetchImpl:e,onEgress:u?null:M,structured:{block:j(h),format:n=>N(n),parse:n=>D(n,h)?.value??null}})}catch{p=[]}}const S={tier:a,entities:p,dictionary:I};let d=0;for(const t of r){const e=t.get();if(typeof e!="string"||!e)continue;const n=T(e,i,S);n!==e&&d++,t.set(n)}return{vault:i,count:d,sanitized:f}}function V(r,o){return{get:r,set:o}}export{U as redactSegments,V as segment};
1
+ import{createHash as W}from"node:crypto";import{createVault as Y,redactText as Z,detectEntities as tt,gatedDictionary as et,sanitizeUnicode as nt,strictnessOf as z}from"@chatpanel/pii";import{ENTITIES_SCHEMA as P,entitiesFormat as ot}from"./extraction.js";import{describeSchema as st,coerce as rt}from"./structured.js";import*as q from"./ner-engine.js";const b=8e3,it=2e6,u=new Map;let k=0,_="";const F=t=>`${W("sha256").update(t).digest("base64")}:${t.length}`;function G(t,e,o){t!==_&&(u.clear(),k=0,_=t);const s=F(e);if(!u.has(s))for(u.set(s,{ents:o,len:e.length}),k+=e.length;k>it&&u.size;){const[n]=u.keys();k-=u.get(n).len,u.delete(n)}}function B(t,e){return t===_?u.get(F(e))?.ents:void 0}function gt(){u.clear(),k=0,_="",f.length=0,x=0}function K(t,e=b){const o=[];for(const s of String(t||"").split(/\n[ \t]*\n/)){let n=s.trim();for(;n.length>e;){let i=n.lastIndexOf(" ",e);i<e/2&&(i=e),o.push(n.slice(0,i).trim()),n=n.slice(i).trim()}n.length>=8&&o.push(n)}return o}function ct(t){if(t<=1)return t===1?[0]:[];const e=[t-1,0];for(let o=t-2;o>0;o--)e.push(o);return e}function L(t,{useEngine:e}){const o=t.detection,s=e?{backend:"endpoint",url:"inproc:ner",transport:"in-process",timeoutMs:3e4,maxChars:b,types:o?.types,strictness:z(t)}:{...o,timeoutMs:Math.max(Number(o.timeoutMs)||0,3e4),strictness:z(t)},n=JSON.stringify([s.backend,s.url||"",s.model||"",s.strictness||"",s.types||null]);return{detection:s,sig:n}}const lt=()=>({block:st(P),format:t=>ot(t),parse:t=>rt(t,P)?.value??null});async function U(t,{detection:e,fetchImpl:o,signal:s=void 0,onEgress:n=null}){let i=!1,g=null;try{g=await tt(t,{detection:e},{signal:s,fetchImpl:o,onError:()=>{i=!0},onEgress:n,structured:lt()})}catch{g=null}return i?null:g}const ut=64e3,f=[];let x=0,D=0,p=null;function X(t,{detection:e,fetchImpl:o,sig:s}){for(const n of t)B(s,n)||f.some(i=>i.text===n)||(f.push({text:n,detection:e,fetchImpl:o,sig:s}),x+=n.length);for(;x>ut&&f.length;)x-=f.shift().text.length}function ft(){return p||(f.length?(p=(async()=>{try{for(;f.length;){if(D>0)return;const t=f.shift();if(x-=t.text.length,B(t.sig,t.text))continue;const e=await U(t.text,t);e&&G(t.sig,t.text,e)}}finally{p=null}})(),p):Promise.resolve())}function j(){if(!f.length||p)return;setTimeout(()=>{ft().catch(()=>{})},50).unref?.()}function mt(t,e,{nerEngine:o=q}={}){if(!t||typeof t!="string"||e?.tier!=="full")return!1;const s=e.detection;if(s&&s.backend&&s.backend!=="off"||!o.isReady())return!1;const{detection:n,sig:i}=L(e,{useEngine:!0});return X(K(t,n.maxChars||b),{detection:n,fetchImpl:o.fetchAdapter,sig:i}),j(),!0}async function yt(t,e,{signal:o,isPro:s=!0,onEgress:n=null,fetchImpl:i=null,budgetChars:g=b,sanitizeOnly:J=!1,nerEngine:w=q}={}){const S=Y();let C=0;for(const r of t){const c=r.get();if(typeof c!="string"||!c)continue;const{clean:a,removed:y}=nt(c);y&&(r.set(a),C+=y)}const A=t.map(r=>r.get()).filter(r=>typeof r=="string"&&r);if(A.length===0)return{vault:S,count:0,sanitized:C};if(J)return{vault:S,count:0,sanitized:C};const E=e.tier==="full"?"full":"basic",V=et(e,s),M=e.detection,v=!!(M&&M.backend&&M.backend!=="off");E==="full"&&!v&&typeof w.ensure=="function"&&await w.ensure();const m=!v&&w.isReady();let H=[],O=0;if(E==="full"&&(v||m)){const{detection:r,sig:c}=L(e,{useEngine:m}),a=m?w.fetchAdapter:i||void 0,y=new Set,R=[],I=[];let $=g;D++;try{for(const h of ct(A.length))for(const l of K(A[h],r.maxChars||b)){if(o?.aborted)break;if(y.has(l))continue;y.add(l);let d=B(c,l);if(!d){if(l.length>$){O+=l.length,I.push(l);continue}$-=l.length,d=await U(l,{detection:r,fetchImpl:a,signal:o,onEgress:m?null:n}),d?G(c,l,d):d=[]}R.push(...d)}}finally{D--}m&&I.length&&X(I,{detection:r,fetchImpl:a,sig:c}),j();const T=new Map;for(const h of R){if(!h||!h.value)continue;const l=`${h.type}:${String(h.value).toLowerCase()}`;T.has(l)||T.set(l,h)}H=[...T.values()]}const Q={tier:E,entities:H,dictionary:V};let N=0;for(const r of t){const c=r.get();if(typeof c!="string"||!c)continue;const a=Z(c,S,Q);a!==c&&N++,r.set(a)}return{vault:S,count:N,sanitized:C,unscanned:O}}function bt(t,e){return{get:t,set:e}}export{gt as clearBlockCache,K as detectBlocks,ft as flushPendingDetection,yt as redactSegments,mt as rememberAnswer,ct as scanOrder,bt as segment};
package/src/server.js CHANGED
@@ -1,57 +1,57 @@
1
- import{createServer as So}from"node:http";import{loadConfig as _t}from"./config.js";import{startEntitlementRefresh as To,maybeRevalidate as xo}from"./entitlement-refresh.js";import{redactSegments as ze,segment as qe}from"./redact.js";import{pipeRestoredStream as Oo,pipeRestoredOpenAIStream as _o,makeTokenRestorer as Et,restoreDeep as Eo}from"./stream.js";import{restoreText as $o,gatedDictionary as Po,narrowSpecs as Ao,makeToolHarness as No,placeholderToolNote as Bo,placeholderNote as Mo,assertEndpointUrl as Do,capRunOptions as Co,isPaired as $t}from"@chatpanel/pii";import{ensureGatewayToken as ve,currentGatewayToken as Pe,isAdminAuthorized as G,callerTrustOf as Ae,setPinnedExtensionIds as Ro,issuePairingCode as Io,claimPairingCode as jo}from"./gateway-token.js";import{createPairAsk as Lo,nativeConfirm as Jo}from"./pair-prompt.js";import{createEngineProbe as zo}from"./local-engine-probe.js";import{randomUUID as Go}from"node:crypto";import{installEgressLedger as Uo,egressAudit as Ho}from"./egress.js";import{initPolicy as Vo,activePolicy as Fo,applyPolicyToConfig as Pt,managedSummary as Ne,PolicyLoadError as Wo}from"./policy.js";import{routeAllowed as At,agentAllowed as Ko,egressAllowed as Qo}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as Be}from"./bridge.js";import{secureFetch as Ge}from"./secure-fetch.js";import{fetchCard as Ue,forgetCard as Yo,sendMessage as Xo,streamMessage as Zo,getTask as qo,cancelTask as er,knownAgents as tr,A2AError as Nt}from"./a2a.js";import{streamBridgeChat as Bt,readBridgeToken as Me,openBridgeChat as or,acceptedBridgeToken as Mt}from"./bridge.js";import{createRelaySession as rr,getRelaySession as Dt,endRelaySession as De,pumpBridgeStream as nr,deliverToolResult as ar,toolsToSpecs as sr,wantsApprovals as ir,parseToolCallId as Ct,touchRelaySession as et}from"./toolrelay.js";import{shaperFor as tt}from"./shape.js";import{startNer as lr,ensureNer as He,unionForThisMachine as dr,skippedCompanions as cr}from"./ner.js";import{recommendDetector as Rt}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as ur}from"./log.js";import{saveBackupSecret as mr,clearBackupSecret as pr,loadBackupSecret as ot,hasBackupSecret as It}from"./history-store.js";import{createMemoryStore as hr}from"./memory-store.js";import{createPrefsStore as yr}from"./prefs-store.js";import{agentCardFor as fr,runHintFor as gr}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as wr}from"@chatpanel/events/agent-thread.js";import{portClashPlan as br,serviceManagerOf as kr,STANDBY_POLL_MS as vr}from"@chatpanel/events/service-standby.js";import{threadTarget as Sr,frameQuestion as Tr,wireMessages as xr,appendExchange as Or,MAX_MESSAGE as jt}from"@chatpanel/events/thread-send.js";import{researchStore as _r,researchResponse as Er}from"./research.js";import{createTeamStore as $r,loadOrCreateKey as rt}from"./team-store.js";import{createScorecardStore as Pr}from"./scorecard-store.js";import{createEngineLedgerStore as Ar}from"./engine-ledger-store.js";import{createProjectStore as Nr}from"./project-store.js";import{applicationsFor as Br,recruitPass as Mr}from"./recruiting.js";import{ensureBridge as Dr,holderOf as Cr}from"./bridge-supervisor.js";import{checkForUpdate as Rr,updateStatus as Ir,startUpdate as jr,updateJob as Lr}from"./update.js";import{createHistoryStore as Jr}from"./sqlite-store.js";import{createEventStore as zr}from"./event-store.js";import{ingestCloudEvents as Gr,cursorOf as Lt}from"./event-sync.js";import{eventStats as Ur,projectYear as Hr}from"./event-stats.js";import{toCloudEvent as nt}from"./cloudevents.js";import{fusionsDocument as Vr,resolveFusionModel as Fr}from"./fusions.js";import{ingestBackups as at}from"./backup-ingest.js";import{toSearchRecord as Jt}from"@chatpanel/events/library.js";import{deriveBackupKey as Wr,openRecord as Kr,keyCache as Qr,nodeCodec as Yr}from"@chatpanel/events/backup-envelope.js";import Xr from"node:zlib";import*as C from"./ner-engine.js";import zt from"node:os";import{capabilitiesDocument as Zr,handleDetect as qr}from"./capabilities.js";import{createExtractService as en}from"./extract/service.js";import{workerSandbox as tn,disposeWorkerSandbox as on}from"./worker-sandbox.js";import{createRuntime as rn,SERVICES as nn}from"./runtime.js";import{createCapabilityProxy as an}from"./capability-proxy.js";import{createEmbeddedCapabilities as sn}from"./capability-embedded.js";import{EMBEDDED_MODELS as ln,EMBEDDED_IDS as dn}from"./embedded-models.js";import{handleExtract as cn}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as un}from"./extract-capability.js";import{createReader as mn}from"./retrieval/read.js";import{createBrowserRelayHost as pn}from"./browser-relay.js";import{createLinkHost as hn}from"./link-host.js";import{checkLinkRoute as yn,tunnelHeader as fn,LINK_TUNNEL_ROOM_PATH as gn}from"@chatpanel/events/link-routes.js";import{createSearcher as wn,toJinaSearch as bn,SEARCH_DEFAULTS as kn}from"./retrieval/search.js";import{createSearxng as vn}from"./retrieval/search-searxng.js";import{searchEngines as Sn}from"./retrieval/search-apis.js";import{toJinaText as Tn}from"./read-document.js";import*as $ from"./stt-engine.js";import*as P from"./diarize-engine.js";import{DIARIZE_MODEL_CATALOG as xn,DEFAULT_DIARIZE_MODEL as On,isKnownDiarizeModel as Gt}from"./diarize-models.js";import{providerOf as st}from"./providers.js";import{createRemoteTranscriber as Ut}from"./stt-remote.js";import{parseMultipart as _n,decodeAudioFile as En}from"./audio-file.js";import{MODEL_CATALOG as Ht,isKnownModel as Vt,isValidCustomModelId as Ft,recommendFor as $n}from"./models.js";import{STT_MODEL_CATALOG as Pn,isKnownSttModel as An,isValidCustomSttId as Nn,DEFAULT_STT_MODEL as Ve,STT_DTYPES as Bn,isValidDtype as Mn}from"./stt-models.js";import*as N from"./tts-engine.js";import{TTS_MODEL_CATALOG as Wt,TTS_VOICES as Dn,isKnownTtsModel as Cn,isValidCustomTtsId as Rn,isKnownVoice as Kt,isValidVoiceId as Qt,DEFAULT_TTS_MODEL as Yt,DEFAULT_TTS_VOICE as be,TTS_DTYPES as In,isValidTtsDtype as jn,MAX_TTS_CHARS as Xt,ttsModelHasCustomVoices as Ln,resolveDefaultModel as Zt,POCKET_VOICES as Jn,DEFAULT_POCKET_VOICE as Fe,isPocketVoice as We,ttsModelEngine as Ke}from"./tts-models.js";import{ttsDestination as zn,synthesizeRemote as Gn,isValidRemoteVoice as Un}from"./tts-remote.js";import{rawOrtAvailable as it}from"./ort.js";import*as ee from"./tts-voices.js";import{resolveTtsVoice as Hn}from"./tts-voice-resolve.js";import{resolvePro as ke,checkQuota as Vn,consume as Fn,usage as Wn}from"./freegate.js";import{publicConfig as qt,applyConfigPatch as Kn,registryChildEnv as Qn,applyNerModelSelection as eo,persistConfig as ue,configPath as ae,bridgeAgentOptions as to,PERMISSION_MODES as Yn,sandboxEnvFor as Xn}from"./configstore.js";import oo from"node:path";import{resolveDestination as Qe,aggregateModelsAsync as Zn,listDestinations as qn,ensureModelCatalog as ea,agentOwnsModel as ta}from"./router.js";import{makeAccessEvent as ro}from"./observability.js";import{createPersistentAccessLog as oa}from"./access-log-store.js";import{planQueries as ra,multiSearch as na}from"./rrf.js";import*as lt from"./openai.js";import*as no from"./responses.js";import*as dt from"./anthropic.js";import{closeAndExit as aa}from"./shutdown.js";import{VERSION as X}from"./version.js";import{VERSION as di}from"./version.js";const R=await Jr(),fe=new Set;function Ce({ids:t=[]}={}){const c=R.lossless;if(!c||!fe.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 fe)try{m.write(`event: records
1
+ import{createServer as To}from"node:http";import{loadConfig as _t}from"./config.js";import{startEntitlementRefresh as xo,maybeRevalidate as Oo}from"./entitlement-refresh.js";import{redactSegments as Ge,segment as et,rememberAnswer as Et}from"./redact.js";import{pipeRestoredStream as _o,pipeRestoredOpenAIStream as Eo,makeTokenRestorer as $t,restoreDeep as $o}from"./stream.js";import{restoreText as Po,gatedDictionary as Ao,narrowSpecs as No,makeToolHarness as Bo,placeholderToolNote as Mo,placeholderNote as Do,assertEndpointUrl as Co,capRunOptions as Ro,isPaired as Pt}from"@chatpanel/pii";import{ensureGatewayToken as ve,currentGatewayToken as Ae,isAdminAuthorized as G,callerTrustOf as Ne,setPinnedExtensionIds as Io,issuePairingCode as jo,claimPairingCode as Lo}from"./gateway-token.js";import{createPairAsk as Jo,nativeConfirm as zo}from"./pair-prompt.js";import{createEngineProbe as Go}from"./local-engine-probe.js";import{randomUUID as Uo}from"node:crypto";import{installEgressLedger as Ho,egressAudit as Vo}from"./egress.js";import{initPolicy as Fo,activePolicy as Wo,applyPolicyToConfig as At,managedSummary as Be,PolicyLoadError as Ko}from"./policy.js";import{routeAllowed as Nt,agentAllowed as Qo,egressAllowed as Yo}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as Me}from"./bridge.js";import{secureFetch as Ue}from"./secure-fetch.js";import{fetchCard as He,forgetCard as Xo,sendMessage as Zo,streamMessage as qo,getTask as er,cancelTask as tr,knownAgents as or,A2AError as Bt}from"./a2a.js";import{streamBridgeChat as Mt,readBridgeToken as De,openBridgeChat as rr,acceptedBridgeToken as Dt}from"./bridge.js";import{createRelaySession as nr,getRelaySession as Ct,endRelaySession as Ce,pumpBridgeStream as ar,deliverToolResult as sr,toolsToSpecs as ir,wantsApprovals as lr,parseToolCallId as Rt,touchRelaySession as tt}from"./toolrelay.js";import{shaperFor as ot}from"./shape.js";import{startNer as dr,ensureNer as Ve,unionForThisMachine as cr,skippedCompanions as ur}from"./ner.js";import{recommendDetector as It}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as mr}from"./log.js";import{saveBackupSecret as pr,clearBackupSecret as hr,loadBackupSecret as rt,hasBackupSecret as jt}from"./history-store.js";import{createMemoryStore as yr}from"./memory-store.js";import{createPrefsStore as fr}from"./prefs-store.js";import{agentCardFor as gr,runHintFor as wr}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as br}from"@chatpanel/events/agent-thread.js";import{portClashPlan as kr,serviceManagerOf as vr,STANDBY_POLL_MS as Sr}from"@chatpanel/events/service-standby.js";import{threadTarget as Tr,frameQuestion as xr,wireMessages as Or,appendExchange as _r,MAX_MESSAGE as Lt}from"@chatpanel/events/thread-send.js";import{researchStore as Er,researchResponse as $r}from"./research.js";import{createTeamStore as Pr,loadOrCreateKey as nt}from"./team-store.js";import{createScorecardStore as Ar}from"./scorecard-store.js";import{createEngineLedgerStore as Nr}from"./engine-ledger-store.js";import{createProjectStore as Br}from"./project-store.js";import{applicationsFor as Mr,recruitPass as Dr}from"./recruiting.js";import{ensureBridge as Cr,holderOf as Rr}from"./bridge-supervisor.js";import{checkForUpdate as Ir,updateStatus as jr,startUpdate as Lr,updateJob as Jr}from"./update.js";import{createHistoryStore as zr}from"./sqlite-store.js";import{createEventStore as Gr}from"./event-store.js";import{ingestCloudEvents as Ur,cursorOf as Jt}from"./event-sync.js";import{eventStats as Hr,projectYear as Vr}from"./event-stats.js";import{toCloudEvent as at}from"./cloudevents.js";import{fusionsDocument as Fr,resolveFusionModel as Wr}from"./fusions.js";import{ingestBackups as st}from"./backup-ingest.js";import{toSearchRecord as zt}from"@chatpanel/events/library.js";import{deriveBackupKey as Kr,openRecord as Qr,keyCache as Yr,nodeCodec as Xr}from"@chatpanel/events/backup-envelope.js";import Zr from"node:zlib";import*as R from"./ner-engine.js";import Gt from"node:os";import{capabilitiesDocument as qr,handleDetect as en}from"./capabilities.js";import{createExtractService as tn}from"./extract/service.js";import{workerSandbox as on,disposeWorkerSandbox as rn}from"./worker-sandbox.js";import{createRuntime as nn,SERVICES as an}from"./runtime.js";import{createCapabilityProxy as sn}from"./capability-proxy.js";import{createEmbeddedCapabilities as ln}from"./capability-embedded.js";import{EMBEDDED_MODELS as dn,EMBEDDED_IDS as cn}from"./embedded-models.js";import{handleExtract as un}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as mn}from"./extract-capability.js";import{createReader as pn}from"./retrieval/read.js";import{createBrowserRelayHost as hn}from"./browser-relay.js";import{createLinkHost as yn}from"./link-host.js";import{checkLinkRoute as fn,tunnelHeader as gn,LINK_TUNNEL_ROOM_PATH as wn}from"@chatpanel/events/link-routes.js";import{createSearcher as bn,toJinaSearch as kn,SEARCH_DEFAULTS as vn}from"./retrieval/search.js";import{createSearxng as Sn}from"./retrieval/search-searxng.js";import{searchEngines as Tn}from"./retrieval/search-apis.js";import{toJinaText as xn}from"./read-document.js";import*as A from"./stt-engine.js";import*as N from"./diarize-engine.js";import{DIARIZE_MODEL_CATALOG as On,DEFAULT_DIARIZE_MODEL as _n,isKnownDiarizeModel as Ut}from"./diarize-models.js";import{providerOf as it}from"./providers.js";import{createRemoteTranscriber as Ht}from"./stt-remote.js";import{parseMultipart as En,decodeAudioFile as $n}from"./audio-file.js";import{MODEL_CATALOG as Vt,isKnownModel as Ft,isValidCustomModelId as Wt,recommendFor as Pn}from"./models.js";import{STT_MODEL_CATALOG as An,isKnownSttModel as Nn,isValidCustomSttId as Bn,DEFAULT_STT_MODEL as Fe,STT_DTYPES as Mn,isValidDtype as Dn}from"./stt-models.js";import*as B from"./tts-engine.js";import{TTS_MODEL_CATALOG as Kt,TTS_VOICES as Cn,isKnownTtsModel as Rn,isValidCustomTtsId as In,isKnownVoice as Qt,isValidVoiceId as Yt,DEFAULT_TTS_MODEL as Xt,DEFAULT_TTS_VOICE as we,TTS_DTYPES as jn,isValidTtsDtype as Ln,MAX_TTS_CHARS as Zt,ttsModelHasCustomVoices as Jn,resolveDefaultModel as qt,POCKET_VOICES as zn,DEFAULT_POCKET_VOICE as We,isPocketVoice as Ke,ttsModelEngine as Qe}from"./tts-models.js";import{ttsDestination as Gn,synthesizeRemote as Un,isValidRemoteVoice as Hn}from"./tts-remote.js";import{rawOrtAvailable as lt}from"./ort.js";import*as ee from"./tts-voices.js";import{resolveTtsVoice as Vn}from"./tts-voice-resolve.js";import{resolvePro as be,checkQuota as Fn,consume as Wn,usage as Kn}from"./freegate.js";import{publicConfig as eo,applyConfigPatch as Qn,registryChildEnv as Yn,applyNerModelSelection as to,persistConfig as ue,configPath as se,bridgeAgentOptions as oo,PERMISSION_MODES as Xn,sandboxEnvFor as Zn}from"./configstore.js";import ro from"node:path";import{resolveDestination as Ye,aggregateModelsAsync as qn,listDestinations as ea,ensureModelCatalog as ta,agentOwnsModel as oa}from"./router.js";import{makeAccessEvent as no}from"./observability.js";import{createPersistentAccessLog as ra}from"./access-log-store.js";import{planQueries as na,multiSearch as aa}from"./rrf.js";import*as dt from"./openai.js";import*as ao from"./responses.js";import*as ct from"./anthropic.js";import{closeAndExit as sa}from"./shutdown.js";import{VERSION as X}from"./version.js";import{VERSION as ci}from"./version.js";const I=await zr(),fe=new Set;function Re({ids:t=[]}={}){const d=I.lossless;if(!d||!fe.size)return;const u=JSON.stringify({newest:d.newest,rev:d.rev,size:d.size,ids:t.slice(0,50),at:Date.now()});for(const m of fe)try{m.write(`event: records
2
2
  data: ${u}
3
3
 
4
4
  `)}catch{fe.delete(m)}}setInterval(()=>{for(const t of fe)try{t.write(`: ping
5
5
 
6
- `)}catch{fe.delete(t)}},25e3).unref?.();const Q=await zr(),Se=new Set;Q?.watch(t=>{if(!Se.size)return;const c=`event: cloudevent
7
- data: ${JSON.stringify(nt(t))}
6
+ `)}catch{fe.delete(t)}},25e3).unref?.();const K=await Gr(),Se=new Set;K?.watch(t=>{if(!Se.size)return;const d=`event: cloudevent
7
+ data: ${JSON.stringify(at(t))}
8
8
 
9
- `;for(const u of Se)try{u.write(c)}catch{Se.delete(u)}}),setInterval(()=>{for(const t of Se)try{t.write(`: ping
9
+ `;for(const u of Se)try{u.write(d)}catch{Se.delete(u)}}),setInterval(()=>{for(const t of Se)try{t.write(`: ping
10
10
 
11
- `)}catch{Se.delete(t)}},25e3).unref?.();const se=await hr(),te=yr(),Oe=Pr({key:rt()}),_e=Ar({key:rt()}),oe=Nr({key:rt()}),W=$r({scorecards:Oe,engines:_e}),ct=new Set,ao=(t,c)=>{for(const m of ct)try{m({applied:t,by:c,revision:te.revision})}catch{}const u=JSON.stringify({revision:te.revision,applied:(t||[]).slice(0,50),by:c||"",at:Date.now()});for(const m of fe)try{m.write(`event: prefs
11
+ `)}catch{Se.delete(t)}},25e3).unref?.();const ie=await yr(),te=fr(),_e=Ar({key:nt()}),Ee=Nr({key:nt()}),oe=Br({key:nt()}),F=Pr({scorecards:_e,engines:Ee}),ut=new Set,so=(t,d)=>{for(const m of ut)try{m({applied:t,by:d,revision:te.revision})}catch{}const u=JSON.stringify({revision:te.revision,applied:(t||[]).slice(0,50),by:d||"",at:Date.now()});for(const m of fe)try{m.write(`event: prefs
12
12
  data: ${u}
13
13
 
14
- `)}catch{fe.delete(m)}},ut=oa(),so=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),sa=16,ia=/^mcp[_-]/i,io=t=>t&&t.function&&t.function.name||t&&t.name||"",la=t=>t&&t.function&&t.function.description||t&&t.description||"";function lo(t){return typeof t=="string"?t:Array.isArray(t)?t.map(c=>typeof c=="string"?c:c&&(c.text||c.content)||"").join(" "):""}function da(t,c){if(!t)return"";if(c==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(g=>lo(g&&(g.content??g))).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 lo(u[m].content);return""}const co=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function Ye(t){if(!t)return!1;const c=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return c==="localhost"||c==="127.0.0.1"||c==="::1"}function ca(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 ua(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 uo=Date.now();function ma(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 pa(t){const c=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return c?{kind:c[1],id:c[2],...c[3]?{model:c[3]}:{}}:null}function ha(t){const c=performance.now(),u={};let m=!1;const g=(k,_)=>{u[k]=Math.round(_*10)/10};return{meta:{},timings:u,mark:g,lap(k,_){g(k,performance.now()-_)},clock(){return performance.now()},commit(){if(m)return;m=!0,g("total",performance.now()-c);const k={...this.meta,timings:u};setImmediate(()=>{t(k),console.log(`[gateway] model=${k.model||"-"} → ${k.dest?`${k.dest}(${k.type})`:"none"} · ${k.redaction==="off"?"redaction OFF (client request)":`redacted ${k.redacted||0}`}${k.sanitized?` · scrubbed ${k.sanitized} hidden`:""}${k.narrowed?` · narrowed -${k.narrowed}`:""} · ${ma(u)}`)})}}}function mo(t,c){if(!t||!t.byToken||c!=="types"&&c!=="values")return;const u=[];for(const[m,g]of t.byToken){const k=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),_=k?k[1]:"PII",B=m.replace(/^\[\[|\]\]$/g,"");u.push(c==="values"?{token:B,type:_,value:g}:{token:B,type:_})}return u}function ya(t,c,u){return dt.matches(t)||"anthropic-version"in c?{kind:"anthropic",adapter:dt,redactable:dt.matches(t),base:u.upstreams?.anthropic?.baseUrl}:no.matches(t)?{kind:"responses",adapter:no,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:lt,redactable:lt.matches(t),base:u.upstreams?.openai?.baseUrl}}function mt(t,c){const u=String(t||"");if(so.has(u))return{agent:u,agentModel:""};const m=u.indexOf("/");if(m>0){const g=u.slice(0,m);if(so.has(g))return{agent:g,agentModel:u.slice(m+1)}}return{agent:c.bridge.agent,agentModel:""}}function po(t,c){return mt(t,c).agent}function fa(t,c){if(c!=="openai"||!t)return!1;const u=lt.extractLatestToolResult(t);if(!u)return!1;const m=Ct(u.tool_call_id);return!!(m&&Dt(m.gwId))}function ga(t,c){try{const u=new URL(t),m=u.hostname.replace(/^\[|\]$/g,""),g=m==="127.0.0.1"||m==="localhost"||m==="::1",k=u.port||(u.protocol==="https:"?"443":"80");return g&&String(k)===String(c.port)}catch{return!1}}const wa=25*1024*1024;async function S(t,c){const u=[];let m=0;for await(const g of t){if(m+=g.length,c&&m>c){const k=new Error("payload too large");throw k.code=413,k}u.push(g)}return Buffer.concat(u)}function a(t,c,u){t.writeHead(c,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function ho(t){const c=t.redaction?.detection?.url;return!c||t.redaction?.detection?.backend==="off"?null:c}function pt(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=C.health(),g=m.ok&&u==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:C.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:g,tier:u,coverage:g?"names":"patterns"}}async function yo(t){if(C.state()!=="off"){const u=C.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=ho(t);if(!c)return{configured:!1,ok:!1,url:null,model:null};try{const u=await Ge(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 ba(t,c){const u={};for(const[m,g]of Object.entries(t)){const k=m.toLowerCase();k.startsWith("x-chatpanel-")||co.has(k)||(u[m]=g)}u["accept-encoding"]="identity";try{u.host=new URL(c).host}catch{}return u}async function fo(t,c,u,m){const g=Et(c.vault),k=ht();t.on("close",()=>{t.writableFinished||De(c.id)});const _=m?m.clock():0;let B=_,y=!0;const M=()=>{m&&y&&(m.lap("upstream",_),B=m.clock(),y=!1)};await nr(c,{onText:v=>{M(),et(c.id);const J=g.push(v);J&&t.write(u.sseDelta(J))},onToolRequest:({name:v,restoredArgs:J,toolId:L})=>{M(),et(c.id);const A=g.flush();A&&t.write(u.sseDelta(A)),t.write(u.sseToolCalls([{id:L,name:v,arguments:JSON.stringify(J)}])),t.write(u.sseToolFinish(k.value)),m&&m.lap("stream",B),t.end(),m?.commit()},onDone:()=>{const v=g.flush();v&&t.write(u.sseDelta(v)),t.write(u.sseTail(k.value)),m&&m.lap("stream",B),t.end(),De(c.id),m?.commit()},onError:v=>{t.write(`data: ${JSON.stringify({error:{message:v.message,type:"bridge_error"}})}
14
+ `)}catch{fe.delete(m)}},mt=ra(),io=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),ia=16,la=/^mcp[_-]/i,lo=t=>t&&t.function&&t.function.name||t&&t.name||"",da=t=>t&&t.function&&t.function.description||t&&t.description||"";function co(t){return typeof t=="string"?t:Array.isArray(t)?t.map(d=>typeof d=="string"?d:d&&(d.text||d.content)||"").join(" "):""}function ca(t,d){if(!t)return"";if(d==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(g=>co(g&&(g.content??g))).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 co(u[m].content);return""}const uo=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function Xe(t){if(!t)return!1;const d=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return d==="localhost"||d==="127.0.0.1"||d==="::1"}function ua(t,d){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(d.allowedOrigins)&&d.allowedOrigins.includes(t)}function ma(t,d){t.setHeader("Access-Control-Allow-Origin",d||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const mo=Date.now();function pa(t){if(!t)return"";const d={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(u=>`${d[u]||u} ${t[u]}ms`).join(" · ")}function ha(t){const d=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return d?{kind:d[1],id:d[2],...d[3]?{model:d[3]}:{}}:null}function ya(t){const d=performance.now(),u={};let m=!1;const g=(k,_)=>{u[k]=Math.round(_*10)/10};return{meta:{},timings:u,mark:g,lap(k,_){g(k,performance.now()-_)},clock(){return performance.now()},commit(){if(m)return;m=!0,g("total",performance.now()-d);const k={...this.meta,timings:u};setImmediate(()=>{t(k),console.log(`[gateway] model=${k.model||"-"} → ${k.dest?`${k.dest}(${k.type})`:"none"} · ${k.redaction==="off"?"redaction OFF (client request)":`redacted ${k.redacted||0}`}${k.sanitized?` · scrubbed ${k.sanitized} hidden`:""}${k.narrowed?` · narrowed -${k.narrowed}`:""} · ${pa(u)}`)})}}}function po(t,d){if(!t||!t.byToken||d!=="types"&&d!=="values")return;const u=[];for(const[m,g]of t.byToken){const k=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),_=k?k[1]:"PII",M=m.replace(/^\[\[|\]\]$/g,"");u.push(d==="values"?{token:M,type:_,value:g}:{token:M,type:_})}return u}function fa(t,d,u){return ct.matches(t)||"anthropic-version"in d?{kind:"anthropic",adapter:ct,redactable:ct.matches(t),base:u.upstreams?.anthropic?.baseUrl}:ao.matches(t)?{kind:"responses",adapter:ao,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:dt,redactable:dt.matches(t),base:u.upstreams?.openai?.baseUrl}}function pt(t,d){const u=String(t||"");if(io.has(u))return{agent:u,agentModel:""};const m=u.indexOf("/");if(m>0){const g=u.slice(0,m);if(io.has(g))return{agent:g,agentModel:u.slice(m+1)}}return{agent:d.bridge.agent,agentModel:""}}function ho(t,d){return pt(t,d).agent}function ga(t,d){if(d!=="openai"||!t)return!1;const u=dt.extractLatestToolResult(t);if(!u)return!1;const m=Rt(u.tool_call_id);return!!(m&&Ct(m.gwId))}function wa(t,d){try{const u=new URL(t),m=u.hostname.replace(/^\[|\]$/g,""),g=m==="127.0.0.1"||m==="localhost"||m==="::1",k=u.port||(u.protocol==="https:"?"443":"80");return g&&String(k)===String(d.port)}catch{return!1}}const ba=25*1024*1024;async function S(t,d){const u=[];let m=0;for await(const g of t){if(m+=g.length,d&&m>d){const k=new Error("payload too large");throw k.code=413,k}u.push(g)}return Buffer.concat(u)}function a(t,d,u){t.writeHead(d,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function yo(t){const d=t.redaction?.detection?.url;return!d||t.redaction?.detection?.backend==="off"?null:d}function ht(t){const d=t?.redaction?.detection,u=t?.redaction?.tier==="full"?"full":"basic";if(d&&d.backend&&d.backend!=="off")return{source:"external",backend:d.backend,state:"external",model:d.model||null,ready:!0,tier:u,coverage:u==="full"?"names":"patterns"};const m=R.health(),g=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:g,tier:u,coverage:g?"names":"patterns"}}async function fo(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 d=yo(t);if(!d)return{configured:!1,ok:!1,url:null,model:null};try{const u=await Ue(d.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:d,model:null};const m=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:d,model:m.model||null}}catch{return{configured:!0,ok:!1,url:d,model:null}}}function ka(t,d){const u={};for(const[m,g]of Object.entries(t)){const k=m.toLowerCase();k.startsWith("x-chatpanel-")||uo.has(k)||(u[m]=g)}u["accept-encoding"]="identity";try{u.host=new URL(d).host}catch{}return u}async function go(t,d,u,m){const g=$t(d.vault),k=yt();t.on("close",()=>{t.writableFinished||Ce(d.id)});const _=m?m.clock():0;let M=_,y=!0;const D=()=>{m&&y&&(m.lap("upstream",_),M=m.clock(),y=!1)};let v="";const z=()=>{d.redaction&&v&&Et(v,d.redaction),v=""};await ar(d,{onText:P=>{D(),tt(d.id);const E=g.push(P);E&&(v+=E,t.write(u.sseDelta(E)))},onToolRequest:({name:P,restoredArgs:E,toolId:re})=>{D(),tt(d.id);const W=g.flush();W&&(v+=W,t.write(u.sseDelta(W))),t.write(u.sseToolCalls([{id:re,name:P,arguments:JSON.stringify(E)}])),t.write(u.sseToolFinish(k.value)),m&&m.lap("stream",M),t.end(),m?.commit(),z()},onDone:()=>{const P=g.flush();P&&(v+=P,t.write(u.sseDelta(P))),t.write(u.sseTail(k.value)),m&&m.lap("stream",M),t.end(),Ce(d.id),m?.commit(),z()},onError:P=>{t.write(`data: ${JSON.stringify({error:{message:P.message,type:"bridge_error"}})}
15
15
 
16
- `),t.end(),De(c.id),m?.commit()},onUsage:v=>k.add(v)})}async function ka(t,c,{kind:u,adapter:m,agent:g,run:k=null},_,B,y,M,v,J=null,L=null){const{messages:A,system:ie}=m.toTurn(_),{agentModel:re}=mt(_?.model,y),le=to(y,{...re?{model:re}:{},...k||{}}),pe=Me(y.bridge.token),j=tt(u,_?.model||g),Z={tier:y.redaction.tier==="full"?"full":"basic",dictionary:Po(y.redaction,M),entities:[]},he=await Be(y),ge=rr({vault:B,redactOpts:Z,bridgeUrl:he,token:pe,harness:J});let de;try{de=await or({bridgeUrl:he,agent:g,token:pe,messages:A,system:ie,specs:sr(v),options:le,signal:void 0,approvals:ir(v)})}catch(n){return De(ge.id),L?.commit(),a(c,502,{error:{message:`bridge: ${n.message}`,type:"bridge_error"}})}return ge.reader=de.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(j.sseHead()),fo(c,ge,j,L)}async function va(t,c,u,m,g=null){et(c.id),c.rounds=(c.rounds||0)+1;try{const _=g?g.clock():0;await ar(c,u),g&&g.lap("redact",_)}catch(_){return De(c.id),g?.commit(),a(t,502,{error:{message:`tool-result: ${_.message}`,type:"bridge_error"}})}const k=tt("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(k.sseHead()),fo(t,c,k,g)}function ht(){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 Sa(t,c,{kind:u,adapter:m,redactable:g,pathname:k,agentOverride:_,harness:B,trace:y,run:M=null},v,J,L,A){if(!g)return y?.commit(),a(c,404,{error:`endpoint ${k} not supported by the bridge backend`});if(u==="openai"){const U=m.extractLatestToolResult(v);if(U){const K=Ct(U.tool_call_id),V=K&&Dt(K.gwId);if(V)return va(c,V,U.content,v?.model,y)}const z=m.extractTools(v);if(z.length&&v?.stream===!0)return ka(t,c,{kind:u,adapter:m,agent:_||po(v?.model,L),run:M},v,J,L,A,z,B,y)}const{messages:ie,system:re}=m.toTurn(v),le=_||po(v?.model,L),pe=v?.stream===!0,j=tt(u,v?.model||le),Z=Me(L.bridge.token),he=new AbortController;c.on("close",()=>{c.writableFinished||he.abort()});const{agentModel:ge}=mt(v?.model,L),de={bridgeUrl:await Be(L),agent:le,token:Z,messages:ie,system:re,signal:he.signal,options:to(L,{...ge?{model:ge}:{},...M||{}})};if(!pe)try{let U="";const z=ht(),K=y?y.clock():0;await Bt(de,ye=>{U+=ye},null,ye=>z.add(ye)),y&&y.lap("upstream",K);const V=y?y.clock():0,O=j.full($o(U,J),z.value);return y&&y.lap("restore",V),c.writeHead(200,{"content-type":j.contentType}),c.end(O),y?.commit()}catch(U){return y?.commit(),a(c,502,{error:{message:`bridge backend failed: ${U.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(j.sseHead());const n=Et(J),o=y?y.clock():0;let f=o;const i=ht();try{let U=!0;await Bt(de,K=>{y&&U&&(y.lap("upstream",o),f=y.clock(),U=!1);const V=n.push(K);V&&c.write(j.sseDelta(V))},j.sseActivity?K=>{try{c.write(j.sseActivity(Eo(K,J)))}catch{}}:null,K=>i.add(K));const z=n.flush();z&&c.write(j.sseDelta(z)),c.write(j.sseTail(i.value))}catch(U){c.write(`data: ${JSON.stringify({error:{message:U.message,type:"bridge_error"}})}
16
+ `),t.end(),Ce(d.id),m?.commit()},onUsage:P=>k.add(P)})}async function va(t,d,{kind:u,adapter:m,agent:g,run:k=null},_,M,y,D,v,z=null,P=null){const{messages:E,system:re}=m.toTurn(_),{agentModel:W}=pt(_?.model,y),le=oo(y,{...W?{model:W}:{},...k||{}}),pe=De(y.bridge.token),J=ot(u,_?.model||g),Z={tier:y.redaction.tier==="full"?"full":"basic",dictionary:Ao(y.redaction,D),entities:[]},he=await Me(y),ye=nr({vault:M,redactOpts:Z,bridgeUrl:he,token:pe,harness:z});M&&(ye.redaction=y.redaction);let de;try{de=await rr({bridgeUrl:he,agent:g,token:pe,messages:E,system:re,specs:ir(v),options:le,signal:void 0,approvals:lr(v)})}catch(n){return Ce(ye.id),P?.commit(),a(d,502,{error:{message:`bridge: ${n.message}`,type:"bridge_error"}})}return ye.reader=de.body.getReader(),d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(J.sseHead()),go(d,ye,J,P)}async function Sa(t,d,u,m,g=null){tt(d.id),d.rounds=(d.rounds||0)+1;try{const _=g?g.clock():0;await sr(d,u),g&&g.lap("redact",_)}catch(_){return Ce(d.id),g?.commit(),a(t,502,{error:{message:`tool-result: ${_.message}`,type:"bridge_error"}})}const k=ot("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(k.sseHead()),go(t,d,k,g)}function yt(){let t=!1;const d={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const m of Object.keys(d))d[m]+=Math.max(0,Number(u?.[m])||0)},get value(){return t?d:null}}}async function Ta(t,d,{kind:u,adapter:m,redactable:g,pathname:k,agentOverride:_,harness:M,trace:y,run:D=null},v,z,P,E){if(!g)return y?.commit(),a(d,404,{error:`endpoint ${k} not supported by the bridge backend`});if(u==="openai"){const L=m.extractLatestToolResult(v);if(L){const U=Rt(L.tool_call_id),O=U&&Ct(U.gwId);if(O)return Sa(d,O,L.content,v?.model,y)}const Q=m.extractTools(v);if(Q.length&&v?.stream===!0)return va(t,d,{kind:u,adapter:m,agent:_||ho(v?.model,P),run:D},v,z,P,E,Q,M,y)}const{messages:re,system:W}=m.toTurn(v),le=_||ho(v?.model,P),pe=v?.stream===!0,J=ot(u,v?.model||le),Z=De(P.bridge.token),he=new AbortController;d.on("close",()=>{d.writableFinished||he.abort()});const{agentModel:ye}=pt(v?.model,P),de={bridgeUrl:await Me(P),agent:le,token:Z,messages:re,system:W,signal:he.signal,options:oo(P,{...ye?{model:ye}:{},...D||{}})};if(!pe)try{let L="";const Q=yt(),U=y?y.clock():0;await Mt(de,Te=>{L+=Te},null,Te=>Q.add(Te)),y&&y.lap("upstream",U);const O=y?y.clock():0,ke=J.full(Po(L,z),Q.value);return y&&y.lap("restore",O),d.writeHead(200,{"content-type":J.contentType}),d.end(ke),y?.commit()}catch(L){return y?.commit(),a(d,502,{error:{message:`bridge backend failed: ${L.message}`,type:"bridge_error"}})}d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(J.sseHead());const n=$t(z),o=y?y.clock():0;let f=o;const i=yt();let ne="";try{let L=!0;await Mt(de,U=>{y&&L&&(y.lap("upstream",o),f=y.clock(),L=!1);const O=n.push(U);O&&(ne+=O,d.write(J.sseDelta(O)))},J.sseActivity?U=>{try{d.write(J.sseActivity($o(U,z)))}catch{}}:null,U=>i.add(U));const Q=n.flush();Q&&(ne+=Q,d.write(J.sseDelta(Q))),d.write(J.sseTail(i.value))}catch(L){d.write(`data: ${JSON.stringify({error:{message:L.message,type:"bridge_error"}})}
17
17
 
18
- `)}y&&y.lap("stream",f),c.end(),y?.commit()}function Ta(t,c,u=""){const m=String(t||"").replace(/\/+$/,""),g=String(c||"").split("/")[1];return g&&m.endsWith(`/${g}`)?m.slice(0,-(g.length+1))+c+u:m+c+u}const xa=9e4;function Oa(t,c,u){if(c===u)return t;const m=c/u,g=new Float32Array(Math.floor(t.length/m));for(let k=0;k<g.length;k++){const _=k*m,B=Math.floor(_),y=Math.min(t.length-1,B+1),M=_-B;g[k]=t[B]*(1-M)+t[y]*M}return g}const go=new WeakMap,_a=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function yt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function me(t,c,u,m,{method:g="GET",timeoutMs:k=8e3,pick:_=B=>B}={}){const B=await Be(u);if(!B)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const y=Me(u.bridge?.token),M=g!=="GET"&&g!=="DELETE";try{const v=M?(await S(t,u.maxBodyBytes)).toString("utf8"):"",J=await fetch(`${B}${m}`,{method:g,headers:{Accept:"application/json",...M?{"content-type":"application/json"}:{},...y?{Authorization:`Bearer ${y}`}:{}},...M?{body:v||"{}"}:{},signal:AbortSignal.timeout(k)}),L=await J.json().catch(()=>({}));return J.ok?a(c,200,_(L)):a(c,J.status,{error:{message:L?.error||`bridge ${J.status}`,type:"bridge_error"}})}catch(v){return a(c,502,{error:{message:`bridge unreachable: ${v.message}`,type:"bridge_unreachable"}})}}function ft(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Ee(t,c){const u=new URLSearchParams;for(const k of t.searchParams.getAll("dir"))k&&u.append("dir",k);const m=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();m&&u.set("workdir",m);const g=u.toString();return g?`?${g}`:""}async function Ea(t,c,{adapter:u,kind:m,pathname:g,search:k,base:_,destKey:B,destProtocol:y,harness:M,trace:v},J,L){let A;const ie=v?v.clock():0;try{const j=ba(t.headers,_);B&&(y==="anthropic"?(j["x-api-key"]=B,delete j.authorization):j.authorization=`Bearer ${B}`);const Z=Do(Ta(_,g,k)).toString();A=await fetch(Z,{method:t.method,headers:j,body:["GET","HEAD"].includes(t.method)?void 0:J})}catch(j){return v?.commit(),a(c,502,{error:`upstream fetch failed: ${j.message}`})}const re=A.headers.get("content-type")||"",le={};if(A.headers.forEach((j,Z)=>{co.has(Z.toLowerCase())||(le[Z]=j)}),re.includes("text/event-stream")&&A.body){v&&v.lap("upstream",ie);const j=v?v.clock():0;c.writeHead(A.status,le);const Z=m==="openai"?_o(A.body,c,L,M):Oo(A.body,c,L);return Promise.resolve(Z).finally(()=>{v&&v.lap("stream",j),v?.commit()})}const pe=Buffer.from(await A.arrayBuffer());if(v&&v.lap("upstream",ie),L&&re.includes("application/json"))try{const j=v?v.clock():0,Z=u.restoreResponse(JSON.parse(pe.toString("utf8")),L,M);return v&&v.lap("restore",j),c.writeHead(A.status,{...le,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(Z),"utf8")),v?.commit()}catch{}c.writeHead(A.status,le),c.end(pe),v?.commit()}function $a(t=_t()){const c=zo({first:async n=>{const o=Number(new URL(n).port),f=nn.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return f&&(await J())(f.id)==="up"?{engine:f.id,label:f.label,models:null}:null}}),u=Lo({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):Jo(n),newId:()=>Go()}),m=pn({version:X}),g=t.link?.enabled===!1?null:hn({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:f,body:i,device:U})=>fetch(`http://127.0.0.1:${t.port}${o}`,{method:n,body:i,headers:{...f,"x-chatpanel-token":Pe()||ve(),"x-chatpanel-link-device":String(U||"")}}),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==P.activeModel()&&(Gt(t.stt.diarizeModel)?P.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${On}`));let k=null;const _=()=>{if(!k){const n=t.read||{};k=mn({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return k};let B=null;const y=()=>(B||(B=en({wrap:(n,o,f,i)=>tn().wrap(n,o,f,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),B);let M={at:0,fn:()=>"unknown"},v=null;async function J(){if(Date.now()-M.at<1e4)return M.fn;let n=new Map;try{const i=await A().health();for(const[U,z]of Object.entries(i)){const K=(t.destinations||[]).filter(V=>V?.service===U).flatMap(V=>[V.id,...V.models||[]]);for(const V of[U,...K])n.set(V,z)}}catch{n=new Map}const o=i=>n.get(i)||"unknown",f=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return A().contextWindow(f.get(i)||i)}catch{return null}},o.card=i=>{try{return A().modelCard(f.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),M={at:Date.now(),fn:o},M.fn}let L=null;const A=()=>(L||(L=rn({cfg:t,bridgeHealth:async()=>{const n=await Be(t);if(!n)return null;const o=Me(t.bridge?.token),f=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return f.ok?f.json():null},persist:()=>{try{ue(t,ae())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:oo.join(oo.dirname(ae()),"runtime"),workers:()=>{const n=B?.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)})),L),ie=Number(t.runtime?.idleMinutes),re=sn({warmMs:(Number.isFinite(ie)&&ie>=0?ie:10)*6e4,log:n=>console.log(n)}),le=an({cfg:t,wake:(n,o)=>A().wake(n,o),embedded:re}),pe=()=>{t.search?.searxng?.url&&A().wake("searxng").catch(()=>{})};let j=null;const Z=()=>{if(!j){const n=t.search||{},o=n.searxng?.url?vn({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;j=wn({reader:_(),searxng:o,engines:()=>Sn(t),wakeSearxng:()=>A().wake("searxng"),defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await ze([qe(()=>i,U=>{i=U})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return j};Ro(t.allowedExtensionIds||[]);const he=[],ge=n=>{he.push(n),he.length>50&&he.shift()},de=So(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),i=f.pathname;if(!Ye(n.headers.host))return a(o,403,{error:"loopback only"});if(!ca(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(Ye(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&&ua(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return G(n)?a(o,200,{token:ve()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!G(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Io();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=jo(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Ae(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Ae(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:l}=await Mt(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Pe()||ve(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&n.method==="POST"){const e=Ae(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($t(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 S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r=null}const s=u.ask({browser:r?.browser,who:n.headers.origin||""});if(!s.ok){const l=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:l,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(i==="/pair/ask/result"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(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:l}=await Mt(t);return a(o,200,{ok:!0,status:r,token:Pe()||ve(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Ae(n);return a(o,200,{ok:!0,trust:e,paired:$t(e),version:X})}if(i==="/audit"&&n.method==="GET")return G(n)?a(o,200,Ho(t,{version:X,startedAt:uo,managed:Ne()})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!G(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await Rr(X,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:X,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:Lr()})}if(i==="/update"&&n.method==="POST"){const e=jr(X);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!G(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!G(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!G(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!G(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!G(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${X} is running.
18
+ `)}y&&y.lap("stream",f),d.end(),y?.commit(),z&&ne&&Et(ne,P.redaction)}function xa(t,d,u=""){const m=String(t||"").replace(/\/+$/,""),g=String(d||"").split("/")[1];return g&&m.endsWith(`/${g}`)?m.slice(0,-(g.length+1))+d+u:m+d+u}const Oa=9e4;function _a(t,d,u){if(d===u)return t;const m=d/u,g=new Float32Array(Math.floor(t.length/m));for(let k=0;k<g.length;k++){const _=k*m,M=Math.floor(_),y=Math.min(t.length-1,M+1),D=_-M;g[k]=t[M]*(1-D)+t[y]*D}return g}const wo=new WeakMap,Ea=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function ft(t,{installing:d=!1}={}){return t.stt?.diarize===!1?"off":d&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function me(t,d,u,m,{method:g="GET",timeoutMs:k=8e3,pick:_=M=>M}={}){const M=await Me(u);if(!M)return a(d,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const y=De(u.bridge?.token),D=g!=="GET"&&g!=="DELETE";try{const v=D?(await S(t,u.maxBodyBytes)).toString("utf8"):"",z=await fetch(`${M}${m}`,{method:g,headers:{Accept:"application/json",...D?{"content-type":"application/json"}:{},...y?{Authorization:`Bearer ${y}`}:{}},...D?{body:v||"{}"}:{},signal:AbortSignal.timeout(k)}),P=await z.json().catch(()=>({}));return z.ok?a(d,200,_(P)):a(d,z.status,{error:{message:P?.error||`bridge ${z.status}`,type:"bridge_error"}})}catch(v){return a(d,502,{error:{message:`bridge unreachable: ${v.message}`,type:"bridge_unreachable"}})}}function gt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function $e(t,d){const u=new URLSearchParams;for(const k of t.searchParams.getAll("dir"))k&&u.append("dir",k);const m=t.searchParams.get("workdir")||String(d?.bridge?.workingDir||"").trim();m&&u.set("workdir",m);const g=u.toString();return g?`?${g}`:""}async function $a(t,d,{adapter:u,kind:m,pathname:g,search:k,base:_,destKey:M,destProtocol:y,harness:D,trace:v},z,P){let E;const re=v?v.clock():0;try{const J=ka(t.headers,_);M&&(y==="anthropic"?(J["x-api-key"]=M,delete J.authorization):J.authorization=`Bearer ${M}`);const Z=Co(xa(_,g,k)).toString();E=await fetch(Z,{method:t.method,headers:J,body:["GET","HEAD"].includes(t.method)?void 0:z})}catch(J){return v?.commit(),a(d,502,{error:`upstream fetch failed: ${J.message}`})}const W=E.headers.get("content-type")||"",le={};if(E.headers.forEach((J,Z)=>{uo.has(Z.toLowerCase())||(le[Z]=J)}),W.includes("text/event-stream")&&E.body){v&&v.lap("upstream",re);const J=v?v.clock():0;d.writeHead(E.status,le);const Z=m==="openai"?Eo(E.body,d,P,D):_o(E.body,d,P);return Promise.resolve(Z).finally(()=>{v&&v.lap("stream",J),v?.commit()})}const pe=Buffer.from(await E.arrayBuffer());if(v&&v.lap("upstream",re),P&&W.includes("application/json"))try{const J=v?v.clock():0,Z=u.restoreResponse(JSON.parse(pe.toString("utf8")),P,D);return v&&v.lap("restore",J),d.writeHead(E.status,{...le,"content-type":"application/json"}),d.end(Buffer.from(JSON.stringify(Z),"utf8")),v?.commit()}catch{}d.writeHead(E.status,le),d.end(pe),v?.commit()}function Pa(t=_t()){const d=Go({first:async n=>{const o=Number(new URL(n).port),f=an.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return f&&(await z())(f.id)==="up"?{engine:f.id,label:f.label,models:null}:null}}),u=Jo({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):zo(n),newId:()=>Uo()}),m=hn({version:X}),g=t.link?.enabled===!1?null:yn({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:f,body:i,device:ne})=>fetch(`http://127.0.0.1:${t.port}${o}`,{method:n,body:i,headers:{...f,"x-chatpanel-token":Ae()||ve(),"x-chatpanel-link-device":String(ne||"")}}),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==N.activeModel()&&(Ut(t.stt.diarizeModel)?N.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${_n}`));let k=null;const _=()=>{if(!k){const n=t.read||{};k=pn({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return k};let M=null;const y=()=>(M||(M=tn({wrap:(n,o,f,i)=>on().wrap(n,o,f,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),M);let D={at:0,fn:()=>"unknown"},v=null;async function z(){if(Date.now()-D.at<1e4)return D.fn;let n=new Map;try{const i=await E().health();for(const[ne,L]of Object.entries(i)){const Q=(t.destinations||[]).filter(U=>U?.service===ne).flatMap(U=>[U.id,...U.models||[]]);for(const U of[ne,...Q])n.set(U,L)}}catch{n=new Map}const o=i=>n.get(i)||"unknown",f=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return E().contextWindow(f.get(i)||i)}catch{return null}},o.card=i=>{try{return E().modelCard(f.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),D={at:Date.now(),fn:o},D.fn}let P=null;const E=()=>(P||(P=nn({cfg:t,bridgeHealth:async()=>{const n=await Me(t);if(!n)return null;const o=De(t.bridge?.token),f=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return f.ok?f.json():null},persist:()=>{try{ue(t,se())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:ro.join(ro.dirname(se()),"runtime"),workers:()=>{const n=M?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),P),re=Number(t.runtime?.idleMinutes),W=ln({warmMs:(Number.isFinite(re)&&re>=0?re:10)*6e4,log:n=>console.log(n)}),le=sn({cfg:t,wake:(n,o)=>E().wake(n,o),embedded:W}),pe=()=>{t.search?.searxng?.url&&E().wake("searxng").catch(()=>{})};let J=null;const Z=()=>{if(!J){const n=t.search||{},o=n.searxng?.url?Sn({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;J=bn({reader:_(),searxng:o,engines:()=>Tn(t),wakeSearxng:()=>E().wake("searxng"),defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await Ge([et(()=>i,ne=>{i=ne})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return J};Io(t.allowedExtensionIds||[]);const he=[],ye=n=>{he.push(n),he.length>50&&he.shift()},de=To(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),i=f.pathname;if(!Xe(n.headers.host))return a(o,403,{error:"loopback only"});if(!ua(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(Xe(t.host)&&gn(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&&ma(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return G(n)?a(o,200,{token:ve()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!G(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=jo();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=Lo(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Ne(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Ne(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:l}=await Dt(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Ae()||ve(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&n.method==="POST"){const e=Ne(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(Pt(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 S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r=null}const s=u.ask({browser:r?.browser,who:n.headers.origin||""});if(!s.ok){const l=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:l,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(i==="/pair/ask/result"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(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:l}=await Dt(t);return a(o,200,{ok:!0,status:r,token:Ae()||ve(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Ne(n);return a(o,200,{ok:!0,trust:e,paired:Pt(e),version:X})}if(i==="/audit"&&n.method==="GET")return G(n)?a(o,200,Vo(t,{version:X,startedAt:mo,managed:Be()})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!G(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await Ir(X,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:X,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:Jr()})}if(i==="/update"&&n.method==="POST"){const e=Lr(X);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!G(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!G(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!G(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!G(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!G(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${X} is running.
19
19
 
20
20
  This address is for ChatPanel's apps, not a web page — there is nothing to open here.
21
21
  Use ChatPanel itself (the browser extension's Settings, or the desktop app).
22
22
  In a terminal, \`chatpanel-gateway --status\` shows what is running.
23
- `);if(n.method==="GET"&&i==="/health"){const e=$.health(),r=N.health();return a(o,200,{ok:!0,version:X,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...Ne()?{managed:Ne()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...Re?{bridge:Re.status()}:Xe?{bridge:Xe}:{},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||Ve,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||Yt,voice:t.tts?.voice||be,runtime:r.runtime,dtype:r.dtype},events:Q?{count:Q.count(),hosts:Q.hosts().length}:null,browser:m.health()})}if(i==="/status"&&n.method==="GET"){xo(t);const e=await ke(t.pro?.entitlementToken),r=await yo(t);return a(o,200,{ok:!0,version:X,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Ne()?{managed:Ne()}:{},...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:pt(t),pro:{unlocked:e},usage:Wn(t),uptimeSeconds:Math.floor((Date.now()-uo)/1e3),update:Ir(X)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=R.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(i==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?a(o,200,{ok:!0,revision:te.revision,stamps:te.stamps()}):a(o,200,{ok:!0,revision:te.revision,sections:te.get(e)})}if(i==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.put(e.sections||{},{by:e.by||""});return r.applied.length&&ao(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(i==="/v1/prefs"&&n.method==="DELETE"){const e=String(f.searchParams.get("section")||""),r=e?te.remove(e):!1;return r&&ao([e],""),a(o,200,{ok:!0,removed:r})}if(i==="/v1/prefs/events"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
23
+ `);if(n.method==="GET"&&i==="/health"){const e=A.health(),r=B.health();return a(o,200,{ok:!0,version:X,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...Be()?{managed:Be()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...Ie?{bridge:Ie.status()}:Ze?{bridge:Ze}:{},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||Fe,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||Xt,voice:t.tts?.voice||we,runtime:r.runtime,dtype:r.dtype},events:K?{count:K.count(),hosts:K.hosts().length}:null,browser:m.health()})}if(i==="/status"&&n.method==="GET"){Oo(t);const e=await be(t.pro?.entitlementToken),r=await fo(t);return a(o,200,{ok:!0,version:X,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Be()?{managed:Be()}:{},...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:ht(t),pro:{unlocked:e},usage:Kn(t),uptimeSeconds:Math.floor((Date.now()-mo)/1e3),update:jr(X)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=I.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(i==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?a(o,200,{ok:!0,revision:te.revision,stamps:te.stamps()}):a(o,200,{ok:!0,revision:te.revision,sections:te.get(e)})}if(i==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.put(e.sections||{},{by:e.by||""});return r.applied.length&&so(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(i==="/v1/prefs"&&n.method==="DELETE"){const e=String(f.searchParams.get("section")||""),r=e?te.remove(e):!1;return r&&so([e],""),a(o,200,{ok:!0,removed:r})}if(i==="/v1/prefs/events"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
24
24
 
25
- `);e({type:"hello",revision:te.revision,stamps:te.stamps()});const r=l=>e({type:"changed",...l});ct.add(r);const s=setInterval(()=>{try{o.write(`: keep-alive
25
+ `);e({type:"hello",revision:te.revision,stamps:te.stamps()});const r=l=>e({type:"changed",...l});ut.add(r);const s=setInterval(()=>{try{o.write(`: keep-alive
26
26
 
27
- `)}catch{}},25e3);o.on("close",()=>{ct.delete(r),clearInterval(s)});return}if(i==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:oe.list({limit:f.searchParams.get("limit")||50,status:f.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&n.method==="GET")return a(o,200,{ok:!0,jobs:oe.openJobs()});if(i==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:oe.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(i);if(e){const r=e[1],s=e[2]||"",l=e[3]||"",d=e[4]||"",h=()=>a(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(d){const p=oe.get(r);if(!p)return h();const T=p.jobs.find(b=>b.id===l);if(!T)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const w={cfg:t,prefsStore:te,scorecards:Oe,engines:_e,engineAt:c.engineAt};if(d==="/applications"&&n.method==="GET"){const b=await Br(T,{...w,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:T,...b})}if(d==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(T.status))return a(o,400,{error:{message:`job ${l} is ${T.status}; only an open job is recruited`,type:"project_error"}});try{const b=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},E=String(b.by||"evaluator").slice(0,80),x=await Mr(T,{...w,record:p,reach:b.reach||"any",chatModel:b.chatModel||null,evaluation:b.evaluation||null,text:b.text??null,by:E});let I=null;for(const Y of x.events)Y.type==="job.updated"?I=oe.updateJob(r,l,Y.job,{by:Y.by||E}):I=oe.append(r,[Y]);return a(o,200,{ok:!0,project:I,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 p=oe.get(r,{events:f.searchParams.get("events")==="1"});return p?a(o,200,{ok:!0,project:p}):h()}if(!s&&n.method==="DELETE")return a(o,200,{ok:!0,removed:oe.remove(r)});if(n.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const p=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},T=String(p.by||"person").slice(0,80),w=s==="/events"?oe.append(r,p.events||[]):l?oe.updateJob(r,l,p.patch||p,{by:T}):oe.postJob(r,p.job||p,{by:T});return a(o,200,{ok:!0,project:w})}catch(p){return a(o,p.message.startsWith("no ")?404:400,{error:{message:`project: ${p.message}`,type:"project_error"}})}if(s==="/events"&&n.method==="GET"){if(!oe.get(r))return h();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const p=E=>o.write(`data: ${JSON.stringify(E)}
27
+ `)}catch{}},25e3);o.on("close",()=>{ut.delete(r),clearInterval(s)});return}if(i==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:oe.list({limit:f.searchParams.get("limit")||50,status:f.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&n.method==="GET")return a(o,200,{ok:!0,jobs:oe.openJobs()});if(i==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:oe.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(i);if(e){const r=e[1],s=e[2]||"",l=e[3]||"",c=e[4]||"",h=()=>a(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(c){const p=oe.get(r);if(!p)return h();const T=p.jobs.find(b=>b.id===l);if(!T)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const w={cfg:t,prefsStore:te,scorecards:_e,engines:Ee,engineAt:d.engineAt};if(c==="/applications"&&n.method==="GET"){const b=await Mr(T,{...w,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:T,...b})}if(c==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(T.status))return a(o,400,{error:{message:`job ${l} is ${T.status}; only an open job is recruited`,type:"project_error"}});try{const b=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},$=String(b.by||"evaluator").slice(0,80),x=await Dr(T,{...w,record:p,reach:b.reach||"any",chatModel:b.chatModel||null,evaluation:b.evaluation||null,text:b.text??null,by:$});let j=null;for(const Y of x.events)Y.type==="job.updated"?j=oe.updateJob(r,l,Y.job,{by:Y.by||$}):j=oe.append(r,[Y]);return a(o,200,{ok:!0,project:j,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 p=oe.get(r,{events:f.searchParams.get("events")==="1"});return p?a(o,200,{ok:!0,project:p}):h()}if(!s&&n.method==="DELETE")return a(o,200,{ok:!0,removed:oe.remove(r)});if(n.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const p=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},T=String(p.by||"person").slice(0,80),w=s==="/events"?oe.append(r,p.events||[]):l?oe.updateJob(r,l,p.patch||p,{by:T}):oe.postJob(r,p.job||p,{by:T});return a(o,200,{ok:!0,project:w})}catch(p){return a(o,p.message.startsWith("no ")?404:400,{error:{message:`project: ${p.message}`,type:"project_error"}})}if(s==="/events"&&n.method==="GET"){if(!oe.get(r))return h();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const p=$=>o.write(`data: ${JSON.stringify($)}
28
28
 
29
- `);let T=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;p({seq:-1,type:"hello",at:Date.now(),payload:{project:oe.get(r),after:T}});const w=oe.watch(r,E=>{E.seq>T&&(T=E.seq,p(E))});for(const E of oe.eventsSince(r,T))T=E.seq,p(E);const b=setInterval(()=>{try{o.write(`: keep
29
+ `);let T=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;p({seq:-1,type:"hello",at:Date.now(),payload:{project:oe.get(r),after:T}});const w=oe.watch(r,$=>{$.seq>T&&(T=$.seq,p($))});for(const $ of oe.eventsSince(r,T))T=$.seq,p($);const b=setInterval(()=>{try{o.write(`: keep
30
30
 
31
- `)}catch{}},25e3);n.on("close",()=>{clearInterval(b),w()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:Oe.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return a(o,200,{ok:!0,...await Oe.get(r)});if(n.method==="POST")try{const s=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},l=await Oe.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 _e.fromRating(Oe.chains.get(r)||[],{...l,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:l})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&n.method==="GET")return a(o,200,Zr(t,{version:X,reader:k,searcher:j,extract:y(),proxy:le}));if(i==="/v1/fusions"&&n.method==="GET"){const e={active:C.health().model||t.ner?.model||null,companions:C.companions()};let r=null;try{r=await A().status()}catch{r=null}return a(o,200,Vr({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(dn.map(r=>{const s=st(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:ln[r],threads:re.threads,...s.kind==="embedded"?re.health(r,s.model):{}}]}));return a(o,200,{...await A().status(),inProcess:e})}if(i==="/v1/runtime/plan"&&n.method==="GET"){const e=new URL(n.url,"http://x").searchParams,r=await A().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(i);if(e&&n.method==="POST"){if(!G(n))return a(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const s=String(r.action||"start"),l=A(),d=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:r.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],r.model):s==="tune"?await l.setTunings(e[2],r.tunings):s==="profile"?await l.setProfile(e[2],r.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="cancel"?l.cancelJob(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,d.ok?200:400,d)}}if((i==="/v1/rerank"||i==="/v1/decide")&&n.method==="POST"){const e=i.slice(4);let r;try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await le.call(e,r);return a(o,s.status,s.body)}if(i==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await qr(e,{ensure:()=>He(t),model:C.health().model});return a(o,r.status,r.body)}catch(r){return a(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,Math.max(t.maxBodyBytes,Math.ceil(un*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await cn(e,{service:y()});return a(o,r.status,r.body)}if(i==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await _().read(e);return a(o,r.status,r.body)}if(i==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}pe();const r=await Z().search(e);return a(o,r.status,r.body)}if(/^\/v1\/search\/./.test(i)&&n.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const r=f.searchParams.has("read")?Math.max(0,Math.min(10,Number(f.searchParams.get("read"))||0)):kn.aliasRead;pe();const s=await Z().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?bn(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&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||""),l=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",d=await _().read({url:r,format:l});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(Tn(d.body)))}if(i==="/v1/engines"&&n.method==="GET"){const e=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:_e.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const s=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await _e.get(r,{entries:f.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&n.method==="POST")try{const s=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||pa(r);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const d=await _e.append({...s,engine:l,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(i==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
31
+ `)}catch{}},25e3);n.on("close",()=>{clearInterval(b),w()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:_e.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return a(o,200,{ok:!0,...await _e.get(r)});if(n.method==="POST")try{const s=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},l=await _e.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 Ee.fromRating(_e.chains.get(r)||[],{...l,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:l})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&n.method==="GET")return a(o,200,qr(t,{version:X,reader:k,searcher:J,extract:y(),proxy:le}));if(i==="/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,Fr({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(cn.map(r=>{const s=it(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:dn[r],threads:W.threads,...s.kind==="embedded"?W.health(r,s.model):{}}]}));return a(o,200,{...await E().status(),inProcess:e})}if(i==="/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(i);if(e&&n.method==="POST"){if(!G(n))return a(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const s=String(r.action||"start"),l=E(),c=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:r.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],r.model):s==="tune"?await l.setTunings(e[2],r.tunings):s==="profile"?await l.setProfile(e[2],r.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="cancel"?l.cancelJob(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,c.ok?200:400,c)}}if((i==="/v1/rerank"||i==="/v1/decide")&&n.method==="POST"){const e=i.slice(4);let r;try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await le.call(e,r);return a(o,s.status,s.body)}if(i==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await en(e,{ensure:()=>Ve(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(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,Math.max(t.maxBodyBytes,Math.ceil(mn*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await un(e,{service:y()});return a(o,r.status,r.body)}if(i==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await _().read(e);return a(o,r.status,r.body)}if(i==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}pe();const r=await Z().search(e);return a(o,r.status,r.body)}if(/^\/v1\/search\/./.test(i)&&n.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const r=f.searchParams.has("read")?Math.max(0,Math.min(10,Number(f.searchParams.get("read"))||0)):vn.aliasRead;pe();const s=await Z().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?kn(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&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||""),l=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",c=await _().read({url:r,format:l});return c.status!==200||s?a(o,c.status,c.status===200?{code:200,status:2e4,data:c.body}:c.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":c.body.provider}),o.end(xn(c.body)))}if(i==="/v1/engines"&&n.method==="GET"){const e=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:Ee.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const s=Number(f.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await Ee.get(r,{entries:f.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&n.method==="POST")try{const s=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||ha(r);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const c=await Ee.append({...s,engine:l,kind:s.kind||"call"});return c.key!==r?a(o,400,{error:{message:`model-ledger: entry is for ${c.key}, not ${r}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:c})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
32
32
 
33
- `)}catch{}};e({type:"hello",at:Date.now()});const r=W.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
33
+ `)}catch{}};e({type:"hello",at:Date.now()});const r=F.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
34
34
 
35
- `)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(i==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:W.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(i==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:W.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(i);if(e){const r=e[1],s=e[2]||"";if(!s&&n.method==="GET"){const l=W.get(r,{events:f.searchParams.get("events")==="1"});return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!s&&n.method==="DELETE")return W.stop(r),a(o,200,{ok:!0,removed:W.remove(r)});if(s==="/stop"&&n.method==="POST"){const l=W.stop(r);return l?a(o,200,{ok:!0,run:l}):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:W.checkpoint(r)})}catch(l){return a(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/handoff"||s==="/claim")&&n.method==="POST")try{const l=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},d=s==="/handoff"?W.handoff(r,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):W.claim(r,{client:l.client});return a(o,200,{ok:!0,run:d})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s.startsWith("/threads/")&&n.method==="DELETE")try{return a(o,200,{ok:!0,run:W.removeThread(r,{threadId:s.slice(9),by:"person"})})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/answer"||s==="/decide"||s==="/post")&&n.method==="POST")try{const l=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},d=String(l.by||"person").slice(0,40),h=s==="/answer"?W.answer(r,{threadId:l.threadId,text:l.text,by:d}):s==="/decide"?W.decide(r,{postId:l.postId,status:l.status,by:d}):W.post(r,{threadId:l.threadId,text:l.text,by:d,kind:l.kind,replyTo:l.replyTo});return a(o,200,{ok:!0,run:h})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="POST")try{const l=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:W.append(r,l.events||[])})}catch(l){return a(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="GET"){if(!W.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 l=w=>o.write(`data: ${JSON.stringify(w)}
35
+ `)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(i==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:F.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(i==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:F.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(i);if(e){const r=e[1],s=e[2]||"";if(!s&&n.method==="GET"){const l=F.get(r,{events:f.searchParams.get("events")==="1"});return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!s&&n.method==="DELETE")return F.stop(r),a(o,200,{ok:!0,removed:F.remove(r)});if(s==="/stop"&&n.method==="POST"){const l=F.stop(r);return l?a(o,200,{ok:!0,run:l}):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:F.checkpoint(r)})}catch(l){return a(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/handoff"||s==="/claim")&&n.method==="POST")try{const l=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},c=s==="/handoff"?F.handoff(r,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):F.claim(r,{client:l.client});return a(o,200,{ok:!0,run:c})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s.startsWith("/threads/")&&n.method==="DELETE")try{return a(o,200,{ok:!0,run:F.removeThread(r,{threadId:s.slice(9),by:"person"})})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/answer"||s==="/decide"||s==="/post")&&n.method==="POST")try{const l=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},c=String(l.by||"person").slice(0,40),h=s==="/answer"?F.answer(r,{threadId:l.threadId,text:l.text,by:c}):s==="/decide"?F.decide(r,{postId:l.postId,status:l.status,by:c}):F.post(r,{threadId:l.threadId,text:l.text,by:c,kind:l.kind,replyTo:l.replyTo});return a(o,200,{ok:!0,run:h})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="POST")try{const l=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:F.append(r,l.events||[])})}catch(l){return a(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="GET"){if(!F.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 l=w=>o.write(`data: ${JSON.stringify(w)}
36
36
 
37
- `),d=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let h=Number.isFinite(d)?d:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:W.get(r),after:h}});const p=W.watch(r,w=>{w.seq==null?l(w):w.seq>h&&(h=w.seq,l(w))});for(const w of W.eventsSince(r,h))h=w.seq,l(w);const T=setInterval(()=>{try{o.write(`: keep-alive
37
+ `),c=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let h=Number.isFinite(c)?c:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:F.get(r),after:h}});const p=F.watch(r,w=>{w.seq==null?l(w):w.seq>h&&(h=w.seq,l(w))});for(const w of F.eventsSince(r,h))h=w.seq,l(w);const T=setInterval(()=>{try{o.write(`: keep-alive
38
38
 
39
- `)}catch{}},25e3);o.on("close",()=>{p(),clearInterval(T)});return}}}if(i==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:se.size,memories:se.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=se.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:se.size,...r})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=se.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:se.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=se.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:se.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=se.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:se.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&n.method==="POST")return a(o,200,{ok:!0,dropped:se.clear(),size:se.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=R.clear();return a(o,200,{ok:!0,dropped:e,size:R.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=R.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:R.size,newest:R.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),s=ra(r,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),h=await na(s,T=>R.search(T,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),p=l.type?h:[...h.filter(T=>T.type==="brief"),...h.filter(T=>T.type!=="brief")];return a(o,200,{ok:!0,size:R.size,newest:R.newest,queries:s,results:p})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&n.method==="POST"){let e;try{e=JSON.parse((await S(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&&!G(n))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${n.socket.localPort}`,d=s?async(w,{maxTokens:b=220}={})=>{const E=new AbortController,x=setTimeout(()=>E.abort(),3e4);try{const I=Pe()||ve(),Y=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:E.signal,headers:{"content-type":"application/json",...I?{Authorization:`Bearer ${I}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:w}],stream:!1,max_tokens:b,temperature:.2})}),ce=await Y.json().catch(()=>({}));return Y.ok?String(ce?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(x)}}:null,h=te.get("identity")?.identity?.value||{},p=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,T=await _r(r,{store:R,memories:se.list(),complete:d,previous:p,self:String(h.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,Er(r,T,{size:R.size,newest:R.newest}))}if(i==="/v1/history/related"&&n.method==="GET"){const e=String(f.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(f.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:R.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:R.size,newest:R.newest,bytes:R.bytes,lossless:R.lossless?{records:R.lossless.size,newest:R.lossless.newest}:null});if(i==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:R.size,bytes:R.bytes,newest:R.newest}},access:ut.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=ut.push(ro({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(i==="/v1/history/records"&&n.method==="PUT"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await S(n,Math.max(t.maxBodyBytes||0,wa))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),d=[];let h=0,p={},T=[],w=[];const b={upserts:[],removes:[]},E=x=>{if(!x||x.deletedAt){x?.id&&b.removes.push(x.id);return}try{const I=Jt(x);I&&b.upserts.push(I)}catch{}};if(Array.isArray(r.records)){const x=e.write(r.records,{host:s,at:l,merge:r.merge===!0});d.push(...x.written),p=x.revs,T=x.conflicts,w=x.merged;for(const I of x.written)E(e.get(I))}if(Array.isArray(r.entries)){const x=ot(),I=x?Qr((F,H)=>Wr(x,{salt:F,iterations:H})):null,Y=async F=>{if(!I||!F.blob)return null;const H=await I(F.blob),$e=F.blob.compression&&F.blob.compression!=="none"?Yr(Xr,F.blob.compression):null;return Kr(F.blob,H,{codec:$e})},ce=await e.upsertEntries(r.entries,{open:Y});d.push(...ce.written),h+=ce.sealed;for(const F of ce.written)E(e.get(F))}return(b.upserts.length||b.removes.length)&&R.bulk(b),d.length&&Ce({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:p,conflicts:T,merged:w,sealed:h,size:e.size,rev:e.rev})}catch(r){return a(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&n.method==="POST"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await S(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=Gr(Q,r);return a(o,200,{ok:!0,appended:s.appended,duplicates:s.duplicates,rejected:s.rejected,cursor:Q.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&n.method==="GET")return Q?a(o,200,{ok:!0,cursor:Q.cursor(),count:Q.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&n.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=Ur(Q.all());return a(o,200,{ok:!0,stats:e,year:Hr(e)})}if(i==="/v1/events"&&n.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=Lt(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=Q.since(e,{limit:Number(f.searchParams.get("limit"))||void 0,host:f.searchParams.get("host")||null});return a(o,200,{ok:!0,events:r.events.map(s=>nt(s)),cursor:r.cursor,more:r.more})}if(i==="/v1/events/stream"&&n.method==="GET"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(f.searchParams.has("cursor"))try{e=Lt(JSON.parse(f.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
40
- data: ${JSON.stringify({cursor:Q.cursor(),count:Q.count(),version:X})}
39
+ `)}catch{}},25e3);o.on("close",()=>{p(),clearInterval(T)});return}}}if(i==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:ie.size,memories:ie.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=ie.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:ie.size,...r})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=ie.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:ie.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=ie.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:ie.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=ie.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:ie.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&n.method==="POST")return a(o,200,{ok:!0,dropped:ie.clear(),size:ie.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=I.clear();return a(o,200,{ok:!0,dropped:e,size:I.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=I.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:I.size,newest:I.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),s=na(r,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},c=Math.min(30,Math.max(5,Number(e.limit)||10)*2),h=await aa(s,T=>I.search(T,{limit:c,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),p=l.type?h:[...h.filter(T=>T.type==="brief"),...h.filter(T=>T.type!=="brief")];return a(o,200,{ok:!0,size:I.size,newest:I.newest,queries:s,results:p})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&n.method==="POST"){let e;try{e=JSON.parse((await S(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&&!G(n))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${n.socket.localPort}`,c=s?async(w,{maxTokens:b=220}={})=>{const $=new AbortController,x=setTimeout(()=>$.abort(),3e4);try{const j=Ae()||ve(),Y=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:$.signal,headers:{"content-type":"application/json",...j?{Authorization:`Bearer ${j}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:w}],stream:!1,max_tokens:b,temperature:.2})}),ce=await Y.json().catch(()=>({}));return Y.ok?String(ce?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(x)}}:null,h=te.get("identity")?.identity?.value||{},p=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,T=await Er(r,{store:I,memories:ie.list(),complete:c,previous:p,self:String(h.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,$r(r,T,{size:I.size,newest:I.newest}))}if(i==="/v1/history/related"&&n.method==="GET"){const e=String(f.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(f.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:I.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:I.size,newest:I.newest,bytes:I.bytes,lossless:I.lossless?{records:I.lossless.size,newest:I.lossless.newest}:null});if(i==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:I.size,bytes:I.bytes,newest:I.newest}},access:mt.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=mt.push(no({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(i==="/v1/history/records"&&n.method==="PUT"){const e=I.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await S(n,Math.max(t.maxBodyBytes||0,ba))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),c=[];let h=0,p={},T=[],w=[];const b={upserts:[],removes:[]},$=x=>{if(!x||x.deletedAt){x?.id&&b.removes.push(x.id);return}try{const j=zt(x);j&&b.upserts.push(j)}catch{}};if(Array.isArray(r.records)){const x=e.write(r.records,{host:s,at:l,merge:r.merge===!0});c.push(...x.written),p=x.revs,T=x.conflicts,w=x.merged;for(const j of x.written)$(e.get(j))}if(Array.isArray(r.entries)){const x=rt(),j=x?Yr((V,H)=>Kr(x,{salt:V,iterations:H})):null,Y=async V=>{if(!j||!V.blob)return null;const H=await j(V.blob),Pe=V.blob.compression&&V.blob.compression!=="none"?Xr(Zr,V.blob.compression):null;return Qr(V.blob,H,{codec:Pe})},ce=await e.upsertEntries(r.entries,{open:Y});c.push(...ce.written),h+=ce.sealed;for(const V of ce.written)$(e.get(V))}return(b.upserts.length||b.removes.length)&&I.bulk(b),c.length&&Re({ids:c}),a(o,200,{ok:!0,written:c.length,ids:c,revs:p,conflicts:T,merged:w,sealed:h,size:e.size,rev:e.rev})}catch(r){return a(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&n.method==="POST"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await S(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=Ur(K,r);return a(o,200,{ok:!0,appended:s.appended,duplicates:s.duplicates,rejected:s.rejected,cursor:K.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&n.method==="GET")return K?a(o,200,{ok:!0,cursor:K.cursor(),count:K.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&n.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=Hr(K.all());return a(o,200,{ok:!0,stats:e,year:Vr(e)})}if(i==="/v1/events"&&n.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=Jt(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=K.since(e,{limit:Number(f.searchParams.get("limit"))||void 0,host:f.searchParams.get("host")||null});return a(o,200,{ok:!0,events:r.events.map(s=>at(s)),cursor:r.cursor,more:r.more})}if(i==="/v1/events/stream"&&n.method==="GET"){if(!K)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(f.searchParams.has("cursor"))try{e=Jt(JSON.parse(f.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
40
+ data: ${JSON.stringify({cursor:K.cursor(),count:K.count(),version:X})}
41
41
 
42
- `),Se.add(o),n.on("close",()=>Se.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=Q.since(r.cursor);for(const s of r.events)o.write(`event: cloudevent
43
- data: ${JSON.stringify(nt(s))}
42
+ `),Se.add(o),n.on("close",()=>Se.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=K.since(r.cursor);for(const s of r.events)o.write(`event: cloudevent
43
+ data: ${JSON.stringify(at(s))}
44
44
 
45
- `)}}return}if(i==="/v1/link"&&n.method==="GET")return a(o,200,{...g?{enabled:!0,...g.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(i==="/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 S(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{ue(t,ae())}catch(r){console.warn(`[link] could not persist the settings: ${r.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(i==="/v1/link/pair"&&n.method==="POST"){if(!g)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 S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}try{return a(o,200,await g.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(i==="/v1/link/route"&&n.method==="POST"){if(!g)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 S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let r;try{r=yn({id:String(e.route||"link"),url:String(e.url||"")})}catch(l){return a(o,400,{error:{message:l.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{ue(t,ae())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await g.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!g)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await g.remove(e)?a(o,200,{ok:!0}):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/browser"&&n.method==="GET")return a(o,200,m.status());if(i==="/v1/browser/stream"&&n.method==="GET"){m.stream(n,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const r=i==="/v1/browser/call"?await m.call(e,n):i==="/v1/browser/announce"?m.announce(e):m.result(e);return a(o,r.status,r.body)}if(i==="/v1/history/stream"&&n.method==="GET"){const e=R.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
45
+ `)}}return}if(i==="/v1/link"&&n.method==="GET")return a(o,200,{...g?{enabled:!0,...g.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(i==="/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 S(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{ue(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(i==="/v1/link/pair"&&n.method==="POST"){if(!g)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 S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}try{return a(o,200,await g.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(i==="/v1/link/route"&&n.method==="POST"){if(!g)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 S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let r;try{r=fn({id:String(e.route||"link"),url:String(e.url||"")})}catch(l){return a(o,400,{error:{message:l.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{ue(t,se())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await g.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!g)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await g.remove(e)?a(o,200,{ok:!0}):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/browser"&&n.method==="GET")return a(o,200,m.status());if(i==="/v1/browser/stream"&&n.method==="GET"){m.stream(n,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const r=i==="/v1/browser/call"?await m.call(e,n):i==="/v1/browser/announce"?m.announce(e):m.result(e);return a(o,r.status,r.body)}if(i==="/v1/history/stream"&&n.method==="GET"){const e=I.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
46
46
  data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:X,prefsRevision:te.revision})}
47
47
 
48
- `),fe.add(o),n.on("close",()=>fe.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(f.searchParams.get("since"))||0,cursor:f.searchParams.get("cursor")||"",limit:Number(f.searchParams.get("limit"))||200,kind:f.searchParams.get("kind")||null,bytes:Number(f.searchParams.get("bytes"))||0,afterRev:f.searchParams.has("after_rev")?Number(f.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||50)),r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=f.searchParams.get("type")||null;return a(o,200,{ok:!0,...R.list({limit:e,offset:r,type:s})})}if(i==="/v1/history/get"&&n.method==="GET"){const e=f.searchParams.get("maxChars")!=null?Math.max(1,Number(f.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=R.get(String(f.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(i==="/v1/history/key"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:It()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?mr(String(e.passphrase)):pr();const r=e.passphrase?await at(R,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ce(),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(i==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await at(R,ot());return e.ok&&e.whole&&Ce(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(n.method==="GET"){const e=await yo(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await He(t),C.state()!=="off"){if(!C.isReady()){const r=C.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 S(n,t.maxBodyBytes);let s="",l=!1;try{const h=JSON.parse(r.toString("utf8"));s=h?.text||"",l=h?.strict===!0}catch{}const d=await C.detect(s,{strict:l});return a(o,200,{entities:d})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=ho(t);if(!e){const r=C.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:C.state(),model:t.ner?.model||null})}try{const r=await S(n,t.maxBodyBytes),s=await Ge(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(r){return a(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:pt(t)});try{let r=e;const s=await ke(t.pro?.entitlementToken);await He(t);const l=await ze([qe(()=>r,d=>{r=d})],t.redaction,{isPro:s});return a(o,200,{text:r,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:mo(l.vault,"types")||[],detector:pt(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(n.method==="GET"){const e=C.health().model||t.ner?.model||null,r=Math.round(zt.totalmem()/1048576),s=$n(Ht,{totalRamMB:r}).map(l=>({...l,installed:C.modelOnDisk(l.id)}));for(const l of[e,...C.modelsOnDisk()])!l||s.some(d=>d.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:C.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:C.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:cr(),recommendation:Rt(s,{totalRamMB:r},[]),state:C.state(),progress:C.progress(),available:s})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(zt.totalmem()/1048576),l=Rt(Ht.map(d=>({...d,installed:C.modelOnDisk(d.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!(Vt(d)||Ft(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const l=r||t.ner?.model||C.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==l),r&&eo(t,r);try{ue(t,ae())}catch{}return(async()=>{r&&await C.setModel(r,{onLog:h=>console.log(h)});const d=dr(t.ner,{log:h=>console.log(h)});for(const h of C.companions())d.includes(h.model)||await C.removeCompanion(h.model);for(const h of d)await C.addCompanion(h,{onLog:p=>console.log(p),allowDownload:t.ner.allowDownload!==!1});C.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:C.companions(),state:C.state()})}if(!r||!(Vt(r)||Ft(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});eo(t,r);try{ue(t,ae())}catch{}return C.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:C.state(),progress:C.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=$.health().model||t.stt?.model||Ve,r=Pn.map(s=>({...s,installed:$.modelOnDisk(s.id)}));return e&&!r.some(s=>s.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:$.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:$.state(),progress:$.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:$.health().dtype,runtime:$.health().runtime,dtypes:Bn})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(An(r)||Nn(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=typeof e.dtype=="string"&&Mn(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{ue(t,ae())}catch{}return $.setModel(r,{onLog:l=>console.log(l),dtype:s||t.stt.dtype||"auto",warmMs:t.stt.warmMs,speaker:yt(t,{installing:!0})}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:$.state(),progress:$.progress(),speaker:{id:P.activeModel(),state:P.state(),installed:P.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=P.activeModel(),r=xn.map(s=>({...s,installed:P.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:P.state(),threshold:P.activeThreshold(),progress:P.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!Gt(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await P.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{ue(t,ae())}catch{}return P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}return P.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=N.health().model||t.tts?.model||Zt(it()),r=it(),s=Wt.find(d=>d.id===e)||null,l=Wt.map(d=>({...d,installed:N.modelOnDisk(d.id),unavailable:d.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(d=>d.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:N.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:N.state(),progress:N.progress(),available:l,voice:t.tts?.voice||(Ke(e)==="pocket-tts"?Fe:be),arch:N.arch(),supportsVoices:N.arch()?N.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:N.arch()?N.supportsCustomVoices():!!s?.customVoices,sampleRate:N.sampleRate(),voices:N.isPocket()||!N.arch()&&Ke(e)==="pocket-tts"?(N.builtinVoices().length?N.builtinVoices():Jn).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:N.builtinVoices().includes(d)})):N.arch()&&N.arch()!=="style-tts2"?[]:Dn.map(d=>({...d,installed:N.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:N.health().dtype,runtime:N.health().runtime,dtypes:In})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(Cn(r)||Rn(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=ee.parseCustomVoice(s);if(!(d?!!ee.getVoice(d):We(s)||Kt(s)&&Qt(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&jn(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Yt,voice:be,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const d=Ln(r),h=ee.parseCustomVoice(t.tts.voice||""),p=!!(h&&ee.getVoice(h));if(d&&!p)if(Ke(r)==="pocket-tts")t.tts.voice=Fe;else{const w=ee.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!d&&p&&(t.tts.voice=be);const T=Ke(r)==="pocket-tts";T&&!ee.parseCustomVoice(t.tts.voice||"")&&!We(t.tts.voice)&&(t.tts.voice=Fe),!T&&We(t.tts.voice)&&(t.tts.voice=be)}l&&(t.tts.dtype=l==="auto"?null:l);try{ue(t,ae())}catch{}return r&&N.setModel(r,{onLog:d=>console.log(d),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:N.state(),progress:N.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:ee.listVoices(),usable:N.supportsCustomVoices(),embedder:P.activeModel(),embedderReady:P.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(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,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!ee.getVoice(l))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,{...ee.renameVoice(l,r),usable:N.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(!P.isReady()){const b=P.download({onLog:I=>console.log(I)}),E=Symbol("timeout"),x=await Promise.race([b.then(()=>null).catch(I=>I),new Promise(I=>setTimeout(()=>I(E),xa))]);if(x===E||!P.isReady())return a(o,503,{error:{message:x===E?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${P.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:P.progress()})}const d=Float32Array.from(s),h=await P.embed(d);let p=null;try{const b=await N.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:E=>console.log(E)});b&&(p=await b.encodeVoice(Oa(d,16e3,24e3)))}catch(b){console.log(`[tts] pocket conditioning unavailable for this voice (${b.message})`)}const T=l?ee.replaceVoice(l,{vec:h,pocket:p}):ee.saveVoice({name:r,vec:h,pocket:p}),w=l&&r&&r!==T.name?ee.renameVoice(l,r):T;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${w.name}" (${(T.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...T,...w,usable:N.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=f.searchParams.get("id")||"",r=ee.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=ee.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:be;try{ue(t,ae())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((i==="/tts"||i==="/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 S(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>Xt)return a(o,413,{error:{message:`text too long (max ${Xt} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=zn(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,h=d||(l?l.voice:t.tts?.voice||be);if(l&&!Un(h))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const p=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(p!=="wav"&&p!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${p}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:F,contentType:H,redacted:$e}=await Gn({dest:l,text:r,voice:h,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ke(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":H,"Content-Length":String(F.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String($e)}),o.end(F)}if(!await N.ready({onLog:F=>console.log(F),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Zt(it()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:N.health().error||"tts model not ready",type:"tts_unavailable"}});const w=Hn({requested:d,configured:h,engine:N,voices:ee,isPocketVoice:We,isKnownVoice:Kt,isValidVoiceId:Qt,defaultVoice:be,defaultPocketVoice:Fe});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:b,customId:E,speakerEmbedding:x}=w,I=await N.synth(r,{voice:b,speed:s,speakerEmbedding:x}),Y=N.sampleRate(),ce=p==="pcm"?Buffer.from(new Float32Array(I).buffer):N.toWav(I,Y);return o.writeHead(200,{"Content-Type":p==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ce.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Y),...E||N.isPocket()||N.supportsVoices()?{"X-Tts-Voice":b}:{}}),o.end(ce)}catch(T){return a(o,500,{error:{message:T.message,type:"tts_failed"}})}}if(i==="/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=_n(await S(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(E=>E.name===b&&!E.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 l;try{l=await En(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",h=st(t,"stt");let p=null;if(h.kind==="remote"||h.kind==="container")try{p=Ut(h,{fetchImpl:Ge})}catch(b){return a(o,500,{error:{message:`stt provider: ${b.message}`,type:"bad_provider"}})}!p&&!$.isReady()&&$.init({model:t.stt?.model||Ve,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:yt(t),onLog:b=>console.log(b)});const T=r("diarize")==="true"&&t.stt?.diarize!==!1;T&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:b=>console.log(b)});const w=Date.now();try{const{id:b}=$.createSession({lang:r("language")||void 0,diarize:T,interims:!1,remote:p}),E=[];let x=null;$.subscribe(b,H=>{H.type==="final"&&H.text?E.push(H):H.type==="language"&&(x=H.lang)});const I=16e3*5;for(let H=0;H<l.pcm.length;H+=I)$.pushAudio(b,l.pcm.subarray(H,Math.min(l.pcm.length,H+I)));await $.endSession(b);let Y=0;const ce=E.map((H,$e)=>{const ko=Y,vo=(H.durationMs||0)/1e3;return Y+=vo,{id:$e,start:Math.round(ko*100)/100,end:Math.round(Y*100)/100,text:H.text,...H.speaker?{speaker:H.speaker}:{}}}),F=ce.map(H=>H.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(F)):d==="verbose_json"?a(o,200,{task:"transcribe",language:x||r("language")||null,duration:Math.round(l.seconds*100)/100,text:F,segments:ce,provider:h.kind,took_ms:Date.now()-w}):a(o,200,{text:F})}catch(b){return a(o,b.code==="too_many_sessions"?429:500,{error:{message:b.message,type:b.code||"stt_error"}})}}if(i==="/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 S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=st(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=Ut(r,{fetchImpl:Ge})}catch(d){return a(o,500,{error:{message:`stt provider: ${d.message}`,type:"bad_provider"}})}!s&&!$.isReady()&&$.init({model:t.stt?.model||Ve,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:yt(t),onLog:d=>console.log(d)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:d=>console.log(d)});try{const d=e?.poll===!0,{id:h}=$.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:d});return a(o,201,{id:h,state:$.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=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(d,h,p)=>{if(h.type!=="final"||!d.redact)return h;try{let T=h.text;return await ze([qe(()=>T,w=>{T=w})],t.redaction,{isPro:p}),{...h,text:T}}catch{return h}},l=async d=>{const h=$.drainEvents(r);if(!h)return null;const p=[];if(d&&!d.closed){const w=d.remote?"ready":$.state();w==="downloading"||w==="loading"?p.push({type:"progress",state:w,...$.progress()||{}}):w==="error"?p.push({type:"error",code:"model_failed",message:$.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes(P.state())?p.push({type:"diarize-progress",state:P.state(),...P.progress()||{}}):go.get(d)!==w&&(go.set(d,w),p.push({type:"state",state:w}))}const T=d?.redact?await ke(t.pro?.entitlementToken):!0;for(const w of h)d?p.push(await s(d,w,T)):w.type!=="final"&&w.type!=="interim"&&p.push(w);return p};if(e[2]==="/audio"&&n.method==="POST"){const d=$.getSession(r)||$.endedSession(r);try{const h=await S(n,t.maxBodyBytes);$.pushAudio(r,$.toFloat32(h));const p=await l(d);return a(o,200,{ok:!0,state:$.state(),...p?{events:p}:{}})}catch(h){const p=h.code==="no_session"?await l(d).catch(()=>null):null;return a(o,h.code==="no_session"?404:400,{error:{message:h.message,type:h.code||"stt_error"},...p?{events:p}:{}})}}if(e[2]==="/events"&&n.method==="GET"){const d=$.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 h=x=>o.write(`data: ${JSON.stringify(x)}
48
+ `),fe.add(o),n.on("close",()=>fe.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=I.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(f.searchParams.get("since"))||0,cursor:f.searchParams.get("cursor")||"",limit:Number(f.searchParams.get("limit"))||200,kind:f.searchParams.get("kind")||null,bytes:Number(f.searchParams.get("bytes"))||0,afterRev:f.searchParams.has("after_rev")?Number(f.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||50)),r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=f.searchParams.get("type")||null;return a(o,200,{ok:!0,...I.list({limit:e,offset:r,type:s})})}if(i==="/v1/history/get"&&n.method==="GET"){const e=f.searchParams.get("maxChars")!=null?Math.max(1,Number(f.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(f.searchParams.get("offset"))||0),s=I.get(String(f.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(i==="/v1/history/key"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:jt()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?pr(String(e.passphrase)):hr();const r=e.passphrase?await st(I,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Re(),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(i==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await st(I,rt());return e.ok&&e.whole&&Re(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(n.method==="GET"){const e=await fo(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Ve(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 S(n,t.maxBodyBytes);let s="",l=!1;try{const h=JSON.parse(r.toString("utf8"));s=h?.text||"",l=h?.strict===!0}catch{}const c=await R.detect(s,{strict:l});return a(o,200,{entities:c})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=yo(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 S(n,t.maxBodyBytes),s=await Ue(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(r){return a(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:ht(t)});try{let r=e;const s=await be(t.pro?.entitlementToken);await Ve(t);const l=await Ge([et(()=>r,c=>{r=c})],t.redaction,{isPro:s});return a(o,200,{text:r,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:po(l.vault,"types")||[],detector:ht(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(n.method==="GET"){const e=R.health().model||t.ner?.model||null,r=Math.round(Gt.totalmem()/1048576),s=Pn(Vt,{totalRamMB:r}).map(l=>({...l,installed:R.modelOnDisk(l.id)}));for(const l of[e,...R.modelsOnDisk()])!l||s.some(c=>c.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:R.modelOnDisk(l),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:ur(),recommendation:It(s,{totalRamMB:r},[]),state:R.state(),progress:R.progress(),available:s})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(Gt.totalmem()/1048576),l=It(Vt.map(c=>({...c,installed:R.modelOnDisk(c.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(c=>String(c||"").trim()).filter(Boolean))];for(const c of s)if(!(Ft(c)||Wt(c)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${c}`,type:"bad_model"}});const l=r||t.ner?.model||R.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(c=>c!==l),r&&to(t,r);try{ue(t,se())}catch{}return(async()=>{r&&await R.setModel(r,{onLog:h=>console.log(h)});const c=cr(t.ner,{log:h=>console.log(h)});for(const h of R.companions())c.includes(h.model)||await R.removeCompanion(h.model);for(const h of c)await R.addCompanion(h,{onLog:p=>console.log(p),allowDownload:t.ner.allowDownload!==!1});R.setUnionOrder(c)})().catch(c=>console.log(`[ner] union update failed: ${c.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:R.companions(),state:R.state()})}if(!r||!(Ft(r)||Wt(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});to(t,r);try{ue(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(i==="/stt/models"){if(n.method==="GET"){const e=A.health().model||t.stt?.model||Fe,r=An.map(s=>({...s,installed:A.modelOnDisk(s.id)}));return e&&!r.some(s=>s.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:A.state(),progress:A.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:Mn})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(Nn(r)||Bn(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=typeof e.dtype=="string"&&Dn(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{ue(t,se())}catch{}return A.setModel(r,{onLog:l=>console.log(l),dtype:s||t.stt.dtype||"auto",warmMs:t.stt.warmMs,speaker:ft(t,{installing:!0})}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress(),speaker:{id:N.activeModel(),state:N.state(),installed:N.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=N.activeModel(),r=On.map(s=>({...s,installed:N.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:N.state(),threshold:N.activeThreshold(),progress:N.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!Ut(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await N.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{ue(t,se())}catch{}return N.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:N.activeModel(),state:N.state(),threshold:N.activeThreshold(),progress:N.progress()})}return N.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:N.activeModel(),state:N.state(),threshold:N.activeThreshold(),progress:N.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=B.health().model||t.tts?.model||qt(lt()),r=lt(),s=Kt.find(c=>c.id===e)||null,l=Kt.map(c=>({...c,installed:B.modelOnDisk(c.id),unavailable:c.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(c=>c.id===e)&&l.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:l,voice:t.tts?.voice||(Qe(e)==="pocket-tts"?We:we),arch:B.arch(),supportsVoices:B.arch()?B.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:B.arch()?B.supportsCustomVoices():!!s?.customVoices,sampleRate:B.sampleRate(),voices:B.isPocket()||!B.arch()&&Qe(e)==="pocket-tts"?(B.builtinVoices().length?B.builtinVoices():zn).map(c=>({id:c,label:c[0].toUpperCase()+c.slice(1),lang:"en",installed:B.builtinVoices().includes(c)})):B.arch()&&B.arch()!=="style-tts2"?[]:Cn.map(c=>({...c,installed:B.voiceOnDisk(c.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:B.health().dtype,runtime:B.health().runtime,dtypes:jn})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(Rn(r)||In(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=ee.parseCustomVoice(s);if(!(c?!!ee.getVoice(c):Ke(s)||Qt(s)&&Yt(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&Ln(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Xt,voice:we,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const c=Jn(r),h=ee.parseCustomVoice(t.tts.voice||""),p=!!(h&&ee.getVoice(h));if(c&&!p)if(Qe(r)==="pocket-tts")t.tts.voice=We;else{const w=ee.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!c&&p&&(t.tts.voice=we);const T=Qe(r)==="pocket-tts";T&&!ee.parseCustomVoice(t.tts.voice||"")&&!Ke(t.tts.voice)&&(t.tts.voice=We),!T&&Ke(t.tts.voice)&&(t.tts.voice=we)}l&&(t.tts.dtype=l==="auto"?null:l);try{ue(t,se())}catch{}return r&&B.setModel(r,{onLog:c=>console.log(c),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:B.state(),progress:B.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:ee.listVoices(),usable:B.supportsCustomVoices(),embedder:N.activeModel(),embedderReady:N.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(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,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!ee.getVoice(l))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,{...ee.renameVoice(l,r),usable:B.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(!N.isReady()){const b=N.download({onLog:j=>console.log(j)}),$=Symbol("timeout"),x=await Promise.race([b.then(()=>null).catch(j=>j),new Promise(j=>setTimeout(()=>j($),Oa))]);if(x===$||!N.isReady())return a(o,503,{error:{message:x===$?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${N.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:N.progress()})}const c=Float32Array.from(s),h=await N.embed(c);let p=null;try{const b=await B.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:$=>console.log($)});b&&(p=await b.encodeVoice(_a(c,16e3,24e3)))}catch(b){console.log(`[tts] pocket conditioning unavailable for this voice (${b.message})`)}const T=l?ee.replaceVoice(l,{vec:h,pocket:p}):ee.saveVoice({name:r,vec:h,pocket:p}),w=l&&r&&r!==T.name?ee.renameVoice(l,r):T;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${w.name}" (${(T.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...T,...w,usable:B.supportsCustomVoices()})}catch(c){return a(o,400,{error:{message:c.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=f.searchParams.get("id")||"",r=ee.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=ee.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:we;try{ue(t,se())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((i==="/tts"||i==="/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 S(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>Zt)return a(o,413,{error:{message:`text too long (max ${Zt} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Gn(t),c=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,h=c||(l?l.voice:t.tts?.voice||we);if(l&&!Hn(h))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const p=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(p!=="wav"&&p!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${p}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:V,contentType:H,redacted:Pe}=await Un({dest:l,text:r,voice:h,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await be(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":H,"Content-Length":String(V.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(Pe)}),o.end(V)}if(!await B.ready({onLog:V=>console.log(V),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||qt(lt()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:B.health().error||"tts model not ready",type:"tts_unavailable"}});const w=Vn({requested:c,configured:h,engine:B,voices:ee,isPocketVoice:Ke,isKnownVoice:Qt,isValidVoiceId:Yt,defaultVoice:we,defaultPocketVoice:We});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:b,customId:$,speakerEmbedding:x}=w,j=await B.synth(r,{voice:b,speed:s,speakerEmbedding:x}),Y=B.sampleRate(),ce=p==="pcm"?Buffer.from(new Float32Array(j).buffer):B.toWav(j,Y);return o.writeHead(200,{"Content-Type":p==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ce.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Y),...$||B.isPocket()||B.supportsVoices()?{"X-Tts-Voice":b}:{}}),o.end(ce)}catch(T){return a(o,500,{error:{message:T.message,type:"tts_failed"}})}}if(i==="/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=En(await S(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($=>$.name===b&&!$.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 l;try{l=await $n(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",h=it(t,"stt");let p=null;if(h.kind==="remote"||h.kind==="container")try{p=Ht(h,{fetchImpl:Ue})}catch(b){return a(o,500,{error:{message:`stt provider: ${b.message}`,type:"bad_provider"}})}!p&&!A.isReady()&&A.init({model:t.stt?.model||Fe,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ft(t),onLog:b=>console.log(b)});const T=r("diarize")==="true"&&t.stt?.diarize!==!1;T&&!N.isReady()&&N.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:b=>console.log(b)});const w=Date.now();try{const{id:b}=A.createSession({lang:r("language")||void 0,diarize:T,interims:!1,remote:p}),$=[];let x=null;A.subscribe(b,H=>{H.type==="final"&&H.text?$.push(H):H.type==="language"&&(x=H.lang)});const j=16e3*5;for(let H=0;H<l.pcm.length;H+=j)A.pushAudio(b,l.pcm.subarray(H,Math.min(l.pcm.length,H+j)));await A.endSession(b);let Y=0;const ce=$.map((H,Pe)=>{const vo=Y,So=(H.durationMs||0)/1e3;return Y+=So,{id:Pe,start:Math.round(vo*100)/100,end:Math.round(Y*100)/100,text:H.text,...H.speaker?{speaker:H.speaker}:{}}}),V=ce.map(H=>H.text).join(" ").replace(/\s+/g," ").trim();return c==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(V)):c==="verbose_json"?a(o,200,{task:"transcribe",language:x||r("language")||null,duration:Math.round(l.seconds*100)/100,text:V,segments:ce,provider:h.kind,took_ms:Date.now()-w}):a(o,200,{text:V})}catch(b){return a(o,b.code==="too_many_sessions"?429:500,{error:{message:b.message,type:b.code||"stt_error"}})}}if(i==="/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 S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=it(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=Ht(r,{fetchImpl:Ue})}catch(c){return a(o,500,{error:{message:`stt provider: ${c.message}`,type:"bad_provider"}})}!s&&!A.isReady()&&A.init({model:t.stt?.model||Fe,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ft(t),onLog:c=>console.log(c)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!N.isReady()&&N.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:c=>console.log(c)});try{const c=e?.poll===!0,{id:h}=A.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:c});return a(o,201,{id:h,state:A.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=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(c,h,p)=>{if(h.type!=="final"||!c.redact)return h;try{let T=h.text;return await Ge([et(()=>T,w=>{T=w})],t.redaction,{isPro:p}),{...h,text:T}}catch{return h}},l=async c=>{const h=A.drainEvents(r);if(!h)return null;const p=[];if(c&&!c.closed){const w=c.remote?"ready":A.state();w==="downloading"||w==="loading"?p.push({type:"progress",state:w,...A.progress()||{}}):w==="error"?p.push({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}):c.diarize&&["downloading","loading"].includes(N.state())?p.push({type:"diarize-progress",state:N.state(),...N.progress()||{}}):wo.get(c)!==w&&(wo.set(c,w),p.push({type:"state",state:w}))}const T=c?.redact?await be(t.pro?.entitlementToken):!0;for(const w of h)c?p.push(await s(c,w,T)):w.type!=="final"&&w.type!=="interim"&&p.push(w);return p};if(e[2]==="/audio"&&n.method==="POST"){const c=A.getSession(r)||A.endedSession(r);try{const h=await S(n,t.maxBodyBytes);A.pushAudio(r,A.toFloat32(h));const p=await l(c);return a(o,200,{ok:!0,state:A.state(),...p?{events:p}:{}})}catch(h){const p=h.code==="no_session"?await l(c).catch(()=>null):null;return a(o,h.code==="no_session"?404:400,{error:{message:h.message,type:h.code||"stt_error"},...p?{events:p}:{}})}}if(e[2]==="/events"&&n.method==="GET"){const c=A.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 h=x=>o.write(`data: ${JSON.stringify(x)}
49
49
 
50
- `),p=d.redact?await ke(t.pro?.entitlementToken):!0,T=x=>s(d,x,p);h({type:"state",state:d.remote?"ready":$.state()});const w=setInterval(()=>{const x=d.remote?"ready":$.state();if(x==="downloading"||x==="loading"){h({type:"progress",state:x,...$.progress()||{}});return}if(x==="error"){h({type:"error",code:"model_failed",message:$.health().error||"model failed to load",fatal:!0}),clearInterval(w);return}if(d.diarize){const I=P.state();if(I==="downloading"||I==="loading"){h({type:"diarize-progress",state:I,...P.progress()||{}});return}}h({type:"state",state:x}),clearInterval(w)},500);w.unref?.();let b=Promise.resolve();const E=$.subscribe(r,x=>{b=b.then(async()=>{h(await T(x)),x.type==="end"&&(clearInterval(w),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(w),E?.()});return}if(!e[2]&&n.method==="DELETE"){const d=$.getSession(r);await $.endSession(r);const h=d?.poll?await l(d).catch(()=>null):null;return a(o,200,{ok:!0,...h?{events:h}:{}})}}}if(i==="/logs"&&n.method==="GET")return a(o,200,{entries:[...he].reverse()});if(i==="/config"&&n.method==="GET"){const e=await ke(t.pro?.entitlementToken);return a(o,200,qt(t,{proUnlocked:e}))}if(i==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(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{Kn(t,e)}catch(p){if(p?.code==="SHAPE")return a(o,400,{error:p.message});throw p}Pt(t),JSON.stringify(t.sandbox||null)!==r&&Re?.restart("sandbox settings changed");try{ue(t,ae())}catch(p){return a(o,500,{error:`could not persist config: ${p.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",d=C.state();t.ner?.autostart&&l&&d!=="ready"&&d!=="loading"&&d!=="downloading"&&C.setModel(t.ner.model,{onLog:p=>console.log(p)}).then(p=>{p&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const h=await ke(t.pro?.entitlementToken);return a(o,200,qt(t,{proUnlocked:h}))}if(n.method==="GET"&&i==="/skills")return me(n,o,t,`/skills${Ee(f,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="POST"&&i==="/v1/threads/send"){if(!G(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=R.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 S(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||""),l=String(r.message||"").trim();if(!l||l.length>jt)return a(o,400,{error:{message:`threads/send: a message of 1–${jt} 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,h=e.get(s);if(!h||h.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const p=Sr(h,{cards:te.get("agentTools").agentTools?.value?.agents||[]});if(p.error)return a(o,409,{error:{message:p.error,type:"no_model"}});if(r.dryRun===!0)return a(o,200,{ok:!0,title:h.title,model:p.model});const T=Tr({fromTitle:d?.title,message:l}),w={thread:{id:p.thread,...h.title?{title:h.title}:{}},...p.workingDir?{workingDir:p.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":Pe()||ve(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(w))},body:JSON.stringify({model:p.model,messages:[...xr(h),{role:"user",content:T}],stream:!1}),signal:AbortSignal.timeout(6e5)}),I=await x.json().catch(()=>null);if(!x.ok)return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${I?.error?.message||`HTTP ${x.status}`}`,type:"upstream"}});b=String(I?.choices?.[0]?.message?.content||"")}catch(x){return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${x?.message||x}`,type:"upstream"}})}const E=Or(e.get(s)||h,{question:T,reply:b,model:p.model,from:d});e.write([E],{host:"gateway",at:Date.now()});try{const x=Jt(e.get(s));x&&R.bulk({upserts:[x],removes:[]})}catch{}return Ce({ids:[s]}),a(o,200,{ok:!0,title:h.title,model:p.model,reply:b})}const U=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(n.method==="POST"&&U)return G(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 › Your phone",type:"forbidden"}}):me(n,o,t,U,{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"&&i==="/skills-quarantined")return me(n,o,t,`/skills-quarantined${Ee(f,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&n.method==="POST")return G(n)?me(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(i)&&n.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return ft(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):G(n)?me(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(i)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]);return ft(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):G(n)?me(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"&&i==="/agent-defs")return me(n,o,t,`/agent-defs${Ee(f,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return ft(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):me(n,o,t,`/agent-defs/${encodeURIComponent(e)}${Ee(f,t)}`)}if(i.startsWith("/a2a/")){if(!G(n))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:tr()});if(n.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&Yo(e.url||"");const r=await Ue(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"&&i==="/a2a/message"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Ue(e.url,{auth:String(e.auth||"")})).card,s=await Xo({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"&&i==="/a2a/message/stream"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Ue(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const s=(l,d)=>o.write(`event: ${l}
51
- data: ${JSON.stringify(d)}
50
+ `),p=c.redact?await be(t.pro?.entitlementToken):!0,T=x=>s(c,x,p);h({type:"state",state:c.remote?"ready":A.state()});const w=setInterval(()=>{const x=c.remote?"ready":A.state();if(x==="downloading"||x==="loading"){h({type:"progress",state:x,...A.progress()||{}});return}if(x==="error"){h({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(w);return}if(c.diarize){const j=N.state();if(j==="downloading"||j==="loading"){h({type:"diarize-progress",state:j,...N.progress()||{}});return}}h({type:"state",state:x}),clearInterval(w)},500);w.unref?.();let b=Promise.resolve();const $=A.subscribe(r,x=>{b=b.then(async()=>{h(await T(x)),x.type==="end"&&(clearInterval(w),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(w),$?.()});return}if(!e[2]&&n.method==="DELETE"){const c=A.getSession(r);await A.endSession(r);const h=c?.poll?await l(c).catch(()=>null):null;return a(o,200,{ok:!0,...h?{events:h}:{}})}}}if(i==="/logs"&&n.method==="GET")return a(o,200,{entries:[...he].reverse()});if(i==="/config"&&n.method==="GET"){const e=await be(t.pro?.entitlementToken);return a(o,200,eo(t,{proUnlocked:e}))}if(i==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(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{Qn(t,e)}catch(p){if(p?.code==="SHAPE")return a(o,400,{error:p.message});throw p}At(t),JSON.stringify(t.sandbox||null)!==r&&Ie?.restart("sandbox settings changed");try{ue(t,se())}catch(p){return a(o,500,{error:`could not persist config: ${p.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",c=R.state();t.ner?.autostart&&l&&c!=="ready"&&c!=="loading"&&c!=="downloading"&&R.setModel(t.ner.model,{onLog:p=>console.log(p)}).then(p=>{p&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const h=await be(t.pro?.entitlementToken);return a(o,200,eo(t,{proUnlocked:h}))}if(n.method==="GET"&&i==="/skills")return me(n,o,t,`/skills${$e(f,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="POST"&&i==="/v1/threads/send"){if(!G(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=I.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 S(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||""),l=String(r.message||"").trim();if(!l||l.length>Lt)return a(o,400,{error:{message:`threads/send: a message of 1–${Lt} characters`,type:"invalid_request"}});const c=r.from&&typeof r.from=="object"?{id:String(r.from.id||"").slice(0,200),title:String(r.from.title||"").slice(0,200)}:null,h=e.get(s);if(!h||h.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const p=Tr(h,{cards:te.get("agentTools").agentTools?.value?.agents||[]});if(p.error)return a(o,409,{error:{message:p.error,type:"no_model"}});if(r.dryRun===!0)return a(o,200,{ok:!0,title:h.title,model:p.model});const T=xr({fromTitle:c?.title,message:l}),w={thread:{id:p.thread,...h.title?{title:h.title}:{}},...p.workingDir?{workingDir:p.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":Ae()||ve(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(w))},body:JSON.stringify({model:p.model,messages:[...Or(h),{role:"user",content:T}],stream:!1}),signal:AbortSignal.timeout(6e5)}),j=await x.json().catch(()=>null);if(!x.ok)return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${j?.error?.message||`HTTP ${x.status}`}`,type:"upstream"}});b=String(j?.choices?.[0]?.message?.content||"")}catch(x){return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${x?.message||x}`,type:"upstream"}})}const $=_r(e.get(s)||h,{question:T,reply:b,model:p.model,from:c});e.write([$],{host:"gateway",at:Date.now()});try{const x=zt(e.get(s));x&&I.bulk({upserts:[x],removes:[]})}catch{}return Re({ids:[s]}),a(o,200,{ok:!0,title:h.title,model:p.model,reply:b})}const ne=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(n.method==="POST"&&ne)return G(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 › Your phone",type:"forbidden"}}):me(n,o,t,ne,{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"&&i==="/skills-quarantined")return me(n,o,t,`/skills-quarantined${$e(f,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&n.method==="POST")return G(n)?me(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(i)&&n.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return gt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):G(n)?me(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(i)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]);return gt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):G(n)?me(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"&&i==="/agent-defs")return me(n,o,t,`/agent-defs${$e(f,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return gt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):me(n,o,t,`/agent-defs/${encodeURIComponent(e)}${$e(f,t)}`)}if(i.startsWith("/a2a/")){if(!G(n))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:or()});if(n.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&Xo(e.url||"");const r=await He(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"&&i==="/a2a/message"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await He(e.url,{auth:String(e.auth||"")})).card,s=await Zo({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"&&i==="/a2a/message/stream"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await He(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const s=(l,c)=>o.write(`event: ${l}
51
+ data: ${JSON.stringify(c)}
52
52
 
53
- `);try{const l=await Zo({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",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(n.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Ue(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await er({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await qo({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: ${i}`,type:"invalid_request"}})}catch(e){const r=e instanceof Nt||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof Nt&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return G(n)?me(n,o,t,i,{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(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):me(n,o,t,`/skills/${encodeURIComponent(e)}${Ee(f,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!G(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await Be(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=Me(t.bridge?.token);try{const s=n.method==="POST"?(await S(n,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),d=await l.json().catch(()=>({}));return a(o,l.status,d)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),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"}}):me(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${Ee(f,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await J(),r=e.sig!==void 0&&e.sig!==v;return v=e.sig,a(o,200,await Zn(t,{serviceHealth:async()=>e,fresh:r,engineAt:c.engineAt}))}if(_a.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${X}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const z=ya(i,n.headers,t);let K;try{K=await S(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 V=null,O=null,ye=K,gt=0,wt=0,bt=0,we=!1,Te=!1,kt="",xe=!0;const q=t.logRequests&&z.redactable&&n.method==="POST"?ha(ge):null;if(z.redactable&&n.method==="POST"&&K.length){try{O=JSON.parse(K.toString("utf8"))}catch{O=null}if(O&&fa(O,z.kind))ye=K;else if(O){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(O.tools)&&O.tools.length){const w=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):sa,b=e.narrowAll?null:x=>!ia.test(io(x)),E=O.tools.length;O.tools=Ao(O.tools,da(O,z.kind),{cap:w,keep:b,name:io,description:la}),bt=E-O.tools.length}xe=await ke(t.pro?.entitlementToken);const r=Vn(t,xe);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"&&G(n),!we){const w=Qe(O?.model,t,z.kind,{destination:String(n.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:()=>!1}),b=w?.type==="api"?await c.decide(w,O?.model).catch(()=>null):null;Te=b?.redact===!1,kt=Te?b.engine||"declared":""}!we&&!Te&&await He(t);const s=we?[]:z.adapter.collectSegments(O,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const d=q?q.clock():0,{vault:h,count:p,sanitized:T}=we?{vault:null,count:0,sanitized:0}:await ze(s,t.redaction,{signal:l.signal,isPro:xe,sanitizeOnly:Te,onEgress:w=>ut.push(ro({ts:Date.now(),client:"redaction",tool:`detect:${w.backend}@${w.host||"local"}`,ok:w.ok,ms:w.ms,error:w.error}))});if(q&&q.lap("redact",d),V=h,gt=p,wt=T||0,p>0&&o.setHeader("x-chatpanel-redacted",String(p)),!xe&&p>0){Fn(t,xe);try{ue(t,ae())}catch{}}if(!we&&!Te&&Array.isArray(O.tools)&&O.tools.length&&typeof z.adapter.injectSystemNote=="function"){const w=Qe(O?.model,t,z.kind,{destination:String(n.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:E=>!!E.service&&M.fn(E.id)==="down"}),b=!(w&&w.type==="api");z.adapter.injectSystemNote(O,Bo({toolData:t.tools?.toolData,ownTools:b}))}else!we&&p>0&&typeof z.adapter.injectSystemNote=="function"&&z.adapter.injectSystemNote(O,Mo());ye=Buffer.from(JSON.stringify(O),"utf8")}}const vt=No({vault:V,toolData:t.tools?.toolData}),Ie=O&&typeof O.chatpanel=="object"&&O.chatpanel||null;if(Ie&&(delete O.chatpanel,ye=Buffer.from(JSON.stringify(O),"utf8")),typeof O?.model=="string"&&O.model.startsWith("fusion:")){const e=Fr(O.model,t,await J());if(e?.error)return q?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(O.model=e.model,ye=Buffer.from(JSON.stringify(O),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const ne={destination:String(n.headers["x-chatpanel-destination"]||Ie?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Ie?.reach||"").trim(),run:wo(n.headers["x-chatpanel-run"],Ie?.run)},je=await J(),St=e=>!!e.service&&je(e.id)==="down";let D=Qe(O?.model,t,z.kind,{destination:ne.destination,down:St});D?.type==="agent"&&O?.model&&!ne.destination&&!ta(D,O.model)&&(await ea(t,{serviceHealth:async()=>je,engineAt:c.engineAt}),D=Qe(O?.model,t,z.kind,{destination:ne.destination,down:St}));const Tt=D?.service&&je(D.id)==="down"?await A().revive(D.service).catch(()=>null):null;if(Tt?.ok&&(M.at=0),D?.service&&je(D.id)==="down"&&!Tt?.ok)return q?.commit(),a(o,503,{error:{message:`${D.id} is not running — the model ${JSON.stringify(O?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:D.service}});if(ne.destination&&(!D||D.id!==ne.destination))return q?.commit(),a(o,404,{error:{message:`no destination "${ne.destination}" is configured on this gateway`,type:"unknown_destination",known:qn(t).map(e=>e.id)}});q&&(q.meta={t:Date.now(),model:O?.model||null,dest:D?D.id:null,type:D?D.type:null,redacted:gt,sanitized:wt,narrowed:bt,detail:mo(V,t.logDetail),redaction:we?"off":Te?`on-device (${kt})`:t.redaction.tier||"basic"});const Le=Fo();if(Le&&D){const e=D.type==="api"?At(Le,{model:O?.model||"",endpoint:D.baseUrl||""}):Ko(Le,D.agent||D.id)?At(Le,{model:O?.model||""}):{ok:!1,reason:`agent "${D.agent||D.id}" is not allowed by your organisation’s policy`};if(!e.ok)return q?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(D&&D.type==="api")return D.baseUrl?ga(D.baseUrl,t)?(q?.commit(),a(o,508,{error:{message:`destination "${D.id}" points back at the gateway (${D.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Ea(n,o,{...z,pathname:i,search:f.search,base:D.baseUrl,destKey:D.apiKey,destProtocol:D.protocol,harness:vt,trace:q},ye,V):(q?.commit(),a(o,502,{error:`destination "${D.id}" has no baseUrl`}));const Ze=Ae(n),xt=Ze==="local"&&t.bridge?.openAgentLane?"token":Ze;if(xt==="local")return q?.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 Ot=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),bo=new Set(["thread","ephemeral","workingDir"]);if(Ze==="token"&&n.headers["x-chatpanel-link-device"]&&!(ne.run&&Object.keys(ne.run).some(e=>!bo.has(e)))){const e=wo(null,gr(fr(te.get("agentTools").agentTools?.value,D?.agent||O?.model)));e&&(ne.run={...e,...ne.run||{}})}const Je=Co({...ne.run||{},...ne.reach?{reach:ne.reach}:{},...Ot?{askDepth:Ot}:{}},xt);return Je.reach&&o.setHeader("x-chatpanel-reach-used",Je.reach),Sa(n,o,{...z,pathname:i,agentOverride:D?.agent,harness:vt,trace:q,run:Object.keys(Je).length?Je:null},O,V,t,xe)});return de.on("close",()=>{B?.stop("closed"),on(),m.close(),g?.stop()}),de.on("upgrade",(n,o,f)=>{o.on("error",()=>{});const i=String(n.url||"").split("?")[0];if(g&&i.startsWith(gn)){g.acceptTunnel(n,o,f).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
53
+ `);try{const l=await qo({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",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(n.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await He(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await tr({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await er({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: ${i}`,type:"invalid_request"}})}catch(e){const r=e instanceof Bt||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof Bt&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return G(n)?me(n,o,t,i,{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(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):me(n,o,t,`/skills/${encodeURIComponent(e)}${$e(f,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!G(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await Me(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=De(t.bridge?.token);try{const s=n.method==="POST"?(await S(n,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),c=await l.json().catch(()=>({}));return a(o,l.status,c)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),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"}}):me(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${$e(f,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await z(),r=e.sig!==void 0&&e.sig!==v;return v=e.sig,a(o,200,await qn(t,{serviceHealth:async()=>e,fresh:r,engineAt:d.engineAt}))}if(Ea.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${X}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const L=fa(i,n.headers,t);let Q;try{Q=await S(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 U=null,O=null,ke=Q,Te=0,wt=0,bt=0,ge=!1,xe=!1,kt="",Oe=!0;const q=t.logRequests&&L.redactable&&n.method==="POST"?ya(ye):null;if(L.redactable&&n.method==="POST"&&Q.length){try{O=JSON.parse(Q.toString("utf8"))}catch{O=null}if(O&&ga(O,L.kind))ke=Q;else if(O){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(O.tools)&&O.tools.length){const w=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):ia,b=e.narrowAll?null:x=>!la.test(lo(x)),$=O.tools.length;O.tools=No(O.tools,ca(O,L.kind),{cap:w,keep:b,name:lo,description:da}),bt=$-O.tools.length}Oe=await be(t.pro?.entitlementToken);const r=Fn(t,Oe);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(ge=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&G(n),!ge){const w=Ye(O?.model,t,L.kind,{destination:String(n.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:()=>!1}),b=w?.type==="api"?await d.decide(w,O?.model).catch(()=>null):null;xe=b?.redact===!1,kt=xe?b.engine||"declared":""}!ge&&!xe&&await Ve(t);const s=ge?[]:L.adapter.collectSegments(O,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const c=q?q.clock():0,{vault:h,count:p,sanitized:T}=ge?{vault:null,count:0,sanitized:0}:await Ge(s,t.redaction,{signal:l.signal,isPro:Oe,sanitizeOnly:xe,onEgress:w=>mt.push(no({ts:Date.now(),client:"redaction",tool:`detect:${w.backend}@${w.host||"local"}`,ok:w.ok,ms:w.ms,error:w.error}))});if(q&&q.lap("redact",c),U=h,Te=p,wt=T||0,p>0&&o.setHeader("x-chatpanel-redacted",String(p)),!Oe&&p>0){Wn(t,Oe);try{ue(t,se())}catch{}}if(!ge&&!xe&&Array.isArray(O.tools)&&O.tools.length&&typeof L.adapter.injectSystemNote=="function"){const w=Ye(O?.model,t,L.kind,{destination:String(n.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:$=>!!$.service&&D.fn($.id)==="down"}),b=!(w&&w.type==="api");L.adapter.injectSystemNote(O,Mo({toolData:t.tools?.toolData,ownTools:b}))}else!ge&&p>0&&typeof L.adapter.injectSystemNote=="function"&&L.adapter.injectSystemNote(O,Do());ke=Buffer.from(JSON.stringify(O),"utf8")}}const vt=Bo({vault:U,toolData:t.tools?.toolData}),je=O&&typeof O.chatpanel=="object"&&O.chatpanel||null;if(je&&(delete O.chatpanel,ke=Buffer.from(JSON.stringify(O),"utf8")),typeof O?.model=="string"&&O.model.startsWith("fusion:")){const e=Wr(O.model,t,await z());if(e?.error)return q?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(O.model=e.model,ke=Buffer.from(JSON.stringify(O),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const ae={destination:String(n.headers["x-chatpanel-destination"]||je?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||je?.reach||"").trim(),run:bo(n.headers["x-chatpanel-run"],je?.run)},Le=await z(),St=e=>!!e.service&&Le(e.id)==="down";let C=Ye(O?.model,t,L.kind,{destination:ae.destination,down:St});C?.type==="agent"&&O?.model&&!ae.destination&&!oa(C,O.model)&&(await ta(t,{serviceHealth:async()=>Le,engineAt:d.engineAt}),C=Ye(O?.model,t,L.kind,{destination:ae.destination,down:St}));const Tt=C?.service&&Le(C.id)==="down"?await E().revive(C.service).catch(()=>null):null;if(Tt?.ok&&(D.at=0),C?.service&&Le(C.id)==="down"&&!Tt?.ok)return q?.commit(),a(o,503,{error:{message:`${C.id} is not running — the model ${JSON.stringify(O?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:C.service}});if(ae.destination&&(!C||C.id!==ae.destination))return q?.commit(),a(o,404,{error:{message:`no destination "${ae.destination}" is configured on this gateway`,type:"unknown_destination",known:ea(t).map(e=>e.id)}});q&&(q.meta={t:Date.now(),model:O?.model||null,dest:C?C.id:null,type:C?C.type:null,redacted:Te,sanitized:wt,narrowed:bt,detail:po(U,t.logDetail),redaction:ge?"off":xe?`on-device (${kt})`:t.redaction.tier||"basic"});const Je=Wo();if(Je&&C){const e=C.type==="api"?Nt(Je,{model:O?.model||"",endpoint:C.baseUrl||""}):Qo(Je,C.agent||C.id)?Nt(Je,{model:O?.model||""}):{ok:!1,reason:`agent "${C.agent||C.id}" is not allowed by your organisation’s policy`};if(!e.ok)return q?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(C&&C.type==="api")return C.baseUrl?wa(C.baseUrl,t)?(q?.commit(),a(o,508,{error:{message:`destination "${C.id}" points back at the gateway (${C.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):$a(n,o,{...L,pathname:i,search:f.search,base:C.baseUrl,destKey:C.apiKey,destProtocol:C.protocol,harness:vt,trace:q},ke,U):(q?.commit(),a(o,502,{error:`destination "${C.id}" has no baseUrl`}));const qe=Ne(n),xt=qe==="local"&&t.bridge?.openAgentLane?"token":qe;if(xt==="local")return q?.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 Ot=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),ko=new Set(["thread","ephemeral","workingDir"]);if(qe==="token"&&n.headers["x-chatpanel-link-device"]&&!(ae.run&&Object.keys(ae.run).some(e=>!ko.has(e)))){const e=bo(null,wr(gr(te.get("agentTools").agentTools?.value,C?.agent||O?.model)));e&&(ae.run={...e,...ae.run||{}})}const ze=Ro({...ae.run||{},...ae.reach?{reach:ae.reach}:{},...Ot?{askDepth:Ot}:{}},xt);return ze.reach&&o.setHeader("x-chatpanel-reach-used",ze.reach),Ta(n,o,{...L,pathname:i,agentOverride:C?.agent,harness:vt,trace:q,run:Object.keys(ze).length?ze:null},O,U,t,Oe)});return de.on("close",()=>{M?.stop("closed"),rn(),m.close(),g?.stop()}),de.on("upgrade",(n,o,f)=>{o.on("error",()=>{});const i=String(n.url||"").split("?")[0];if(g&&i.startsWith(wn)){g.acceptTunnel(n,o,f).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
54
54
  connection: close\r
55
55
  content-length: 0\r
56
56
  \r
57
- `)}catch{}}),de.once("listening",()=>{A()}),de.linkHost=g,de.runtimeDefaults=()=>A().ensureDefaults(),de}function wo(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(k=>String(k).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const k=u.workspace;m.workspace={repo:String(k.repo).slice(0,400),projectId:String(k.projectId||"").slice(0,120),jobId:String(k.jobId||"").slice(0,120),...k.base?{base:String(k.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)),Yn.includes(u.permissionMode)&&u.permissionMode!=="default"&&(m.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const k=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(y=>String(y).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),_=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(y=>String(y).slice(0,1024)).filter(Boolean).slice(0,32),B=u.sandbox.outside===!0;(k.length||_.length||B)&&(m.sandbox={...k.length?{hosts:k}:{},..._.length?{write:_}:{},...B?{outside:!0}:{}})}const g=wr(u.thread);return g&&(m.thread=g),u.ephemeral===!0&&(m.ephemeral=!0),Object.keys(m).length?m:null}let Re=null,Xe=null;async function si(t=_t()){ur();let c=null;try{c=await Vo()}catch(y){throw y instanceof Wo&&(console.error(`[chatpanel-gateway] org policy: ${y.message}`),process.exit(78)),y}const u=c?.policy||null;u&&(Pt(t,u),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`)),Uo(globalThis,{allow:u?.egress?(y,{local:M})=>Qo(u,y,{local:M}):null}),ve();const m=$a(t),g=lr(t),k=To(t);let _=!1;m.on("error",y=>{if(y&&y.code==="EADDRINUSE"){const M=Ye(t.host)?"127.0.0.1":t.host;fetch(`http://${M}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(v=>v.ok?v.json():null).catch(()=>null).then(v=>{const J=!!(v?.version&&typeof v.tier=="string"),L=br({name:"gateway",self:X,holder:J?{ours:J,version:v.version}:null,managedBy:kr(process.env),port:t.port});if(L.action==="standby"||_&&!v){if(!_)for(const A of L.lines)console.error(A);_=!0,setTimeout(()=>m.listen(t.port,t.host),vr);return}if(J){const A=v.managedBy?` (run by ${v.managedBy})`:"";for(const[ie,re]of L.lines.entries())console.error(ie===0?re.replace(` on ${t.port}`,` at http://${M}:${t.port}${A}`):re)}else{const A=Cr(t.port);console.error(`Port ${t.port} is held by ${A||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${ae()} (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: ${y?.message||y}`),process.exit(1)}),m.listen(t.port,t.host,()=>{_&&console.log(" standby : the other gateway is gone — this copy has the port now"),_=!1,console.log(`ChatPanel Privacy Gateway v${X} on http://${t.host}:${t.port}`),m.linkHost?.start().catch(y=>console.log(` link : not started (${y?.message||y})`)),m.runtimeDefaults?.().then(y=>{for(const M of y||[])console.log(` ${M.label.toLowerCase().padEnd(9).slice(0,9)}: ${M.ok?M.already?"running":M.adopted?"already running — adopted":"started":`not started (${M.skipped})`}`)}).catch(y=>console.log(` runtime : defaults not started (${y?.message||y})`)),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"),Xe={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},Dr(t,{childEnv:()=>({...Xn(t),...Qn(t)})}).then(y=>{Re=y}).catch(y=>{Xe={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${y?.message||y})`},console.log(` bridge : not supervised (${y?.message||y})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),Ye(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.`)}),It()&&at(R,ot()).then(y=>{y?.ok&&(console.log(` warm : seeded ${y.ingested} records from ${y.file}`),y.whole&&Ce())}).catch(()=>{});const B=()=>{g?.stop(),k.stop(),Re?.stop(),aa(m)};return process.on("SIGINT",B),process.on("SIGTERM",B),m}export{wa as RECORDS_MAX_BYTES,di as VERSION,$a as createGateway,Ta as joinUpstream,mt as parseAgentModel,si as start};
57
+ `)}catch{}}),de.once("listening",()=>{E()}),de.linkHost=g,de.runtimeDefaults=()=>E().ensureDefaults(),de}function bo(t,d){let u=d&&typeof d=="object"?d: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(k=>String(k).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const k=u.workspace;m.workspace={repo:String(k.repo).slice(0,400),projectId:String(k.projectId||"").slice(0,120),jobId:String(k.jobId||"").slice(0,120),...k.base?{base:String(k.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)),Xn.includes(u.permissionMode)&&u.permissionMode!=="default"&&(m.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const k=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(y=>String(y).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),_=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(y=>String(y).slice(0,1024)).filter(Boolean).slice(0,32),M=u.sandbox.outside===!0;(k.length||_.length||M)&&(m.sandbox={...k.length?{hosts:k}:{},..._.length?{write:_}:{},...M?{outside:!0}:{}})}const g=br(u.thread);return g&&(m.thread=g),u.ephemeral===!0&&(m.ephemeral=!0),Object.keys(m).length?m:null}let Ie=null,Ze=null;async function ii(t=_t()){mr();let d=null;try{d=await Fo()}catch(y){throw y instanceof Ko&&(console.error(`[chatpanel-gateway] org policy: ${y.message}`),process.exit(78)),y}const u=d?.policy||null;u&&(At(t,u),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`)),Ho(globalThis,{allow:u?.egress?(y,{local:D})=>Yo(u,y,{local:D}):null}),ve();const m=Pa(t),g=dr(t),k=xo(t);let _=!1;m.on("error",y=>{if(y&&y.code==="EADDRINUSE"){const D=Xe(t.host)?"127.0.0.1":t.host;fetch(`http://${D}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(v=>v.ok?v.json():null).catch(()=>null).then(v=>{const z=!!(v?.version&&typeof v.tier=="string"),P=kr({name:"gateway",self:X,holder:z?{ours:z,version:v.version}:null,managedBy:vr(process.env),port:t.port});if(P.action==="standby"||_&&!v){if(!_)for(const E of P.lines)console.error(E);_=!0,setTimeout(()=>m.listen(t.port,t.host),Sr);return}if(z){const E=v.managedBy?` (run by ${v.managedBy})`:"";for(const[re,W]of P.lines.entries())console.error(re===0?W.replace(` on ${t.port}`,` at http://${D}:${t.port}${E}`):W)}else{const E=Rr(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: ${y?.message||y}`),process.exit(1)}),m.listen(t.port,t.host,()=>{_&&console.log(" standby : the other gateway is gone — this copy has the port now"),_=!1,console.log(`ChatPanel Privacy Gateway v${X} on http://${t.host}:${t.port}`),m.linkHost?.start().catch(y=>console.log(` link : not started (${y?.message||y})`)),m.runtimeDefaults?.().then(y=>{for(const D of y||[])console.log(` ${D.label.toLowerCase().padEnd(9).slice(0,9)}: ${D.ok?D.already?"running":D.adopted?"already running — adopted":"started":`not started (${D.skipped})`}`)}).catch(y=>console.log(` runtime : defaults not started (${y?.message||y})`)),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"),Ze={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},Cr(t,{childEnv:()=>({...Zn(t),...Yn(t)})}).then(y=>{Ie=y}).catch(y=>{Ze={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${y?.message||y})`},console.log(` bridge : not supervised (${y?.message||y})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),Xe(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.`)}),jt()&&st(I,rt()).then(y=>{y?.ok&&(console.log(` warm : seeded ${y.ingested} records from ${y.file}`),y.whole&&Re())}).catch(()=>{});const M=()=>{g?.stop(),k.stop(),Ie?.stop(),sa(m)};return process.on("SIGINT",M),process.on("SIGTERM",M),m}export{ba as RECORDS_MAX_BYTES,ci as VERSION,Pa as createGateway,xa as joinUpstream,pt as parseAgentModel,ii as start};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.85.4";export{o as VERSION};
1
+ const o="0.85.5";export{o as VERSION};