@chatpanel/gateway 0.120.1 → 0.121.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.120.1",
3
+ "version": "0.121.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,8 +23,8 @@
23
23
  },
24
24
  "dependencies": {
25
25
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
26
- "@chatpanel/bridge": "^0.48.0",
27
- "@chatpanel/events": "^0.396.3",
26
+ "@chatpanel/bridge": "^0.49.0",
27
+ "@chatpanel/events": "^0.405.0",
28
28
  "@chatpanel/pii": "^0.15.6",
29
29
  "@huggingface/transformers": "^4.2.0",
30
30
  "defuddle": "^0.19.4",
@@ -1 +1 @@
1
- import{modelFetch as Q}from"./model-sources.js";import{existsSync as z,readFileSync as Z,mkdirSync as V,createWriteStream as ee,createReadStream as te,renameSync as ne,rmSync as U}from"node:fs";import{createHash as re}from"node:crypto";import{join as A}from"node:path";import{modelRoot as oe}from"./ner-engine.js";import{getOrt as ce,ortProviders as ae,rawOrtAvailable as se}from"./ort.js";import{fft as ie}from"./aec-engine.js";import{INDIC_LICENSE as M,licenseAcceptance as fe}from"./stt-models.js";const $e="bodhan-ai/indic-transcribe-core",de=fe(M);function $(){return A(oe(),"bodhan-ai","indic-transcribe-core-int8")}const le="https://huggingface.co/ChatPanel/indic-transcribe-core-int8/resolve/main",D=Object.freeze({"encoder.onnx":"fa49d702bf83d52327105736ded11aea2e6afcfcb1667182e6db36e5cc27f097","encoder.onnx.data":"66c3442b950a3ff5e18fc33db1d15069b7888235776bdc86824d6f99d728f9a5","cross_kv.onnx":"0aed59ffef5e77e2b957d42f742ea2645fed3ac49954b6a91dc8e629d7196c26","cross_kv.onnx.data":"022d88763437e56ac1156b3953c68a01c205b52627094a086d243b822f6e810b","decoder.onnx":"f858a610f1d3498a993d5eb0424ef888d96edc853be3b7aa32846b237d2c4a97","decoder.onnx.data":"c557a469b426ad424b0ed04c7422df44fc12131df2ae300b3f4bc92bdf50d05b","mel_fb_128x257.f32":"586bbdf62da6485f02faecb278f781277fab9537558a57d611bf2fc35e12452b","window_400.f32":"cb9f40f78ef078b89ba969960015aa5e5a833e0c549e9dcdb532d9defbb418d2","vocab.json":"894a3b8761a73dec92577e7ef1664d1357fdee6008a598add2c9006423d3c79d","LICENSE.md":"b39f2a9cb2d5ace3a03f4425cbc6db38ebd9a53ab7a7648d67dc1e0998ad75c2"});function q(){return Object.keys(D).every(a=>z(A($(),a)))}const G=a=>new Promise((o,s)=>{const i=re("sha256");te(a).on("data",b=>i.update(b)).on("error",s).on("end",()=>o(i.digest("hex")))});async function De({licenseAccepted:a=null,onProgress:o=()=>{},log:s=()=>{},fetchImpl:i=Q()}={}){if(q())return $();if(a!==de){const x=new Error(`Indic-Transcribe is downloaded only after its licence (${M.name}) is accepted`);throw x.code="license_required",x}const b=$();V(b,{recursive:!0});const d=Object.keys(D);for(const[x,u]of d.entries()){const y=A(b,u);if(z(y))continue;const g=await i(`${le}/${u}`);if(!g.ok||!g.body)throw new Error(`${u}: HTTP ${g.status}`);const f=Number(g.headers.get("content-length"))||0,v=`${y}.part`;if(await new Promise((w,r)=>{const h=ee(v),n=g.body.getReader();let e=0;const c=()=>n.read().then(({done:t,value:p})=>{if(t){h.end(w);return}e+=p.length,f&&o({file:u,pct:Math.round((x+e/f)/d.length*100)}),h.write(Buffer.from(p)),c()},r);h.on("error",r),c()}),await G(v)!==D[u])throw U(v,{force:!0}),new Error(`${u} does not match its pinned hash — not used`);ne(v,y),s(`[indic] fetched ${u}`)}return b}const P=16e3,C=512,W=160,J=400,L=128,T=C/2+1,be=.97,pe=2**-24,me=1e-5,we=24,he=8,ue=128,K=new Set,X=3;function ge(a,{fb:o,window:s}){const i=a.length,b=new Float32Array(i);b[0]=a[0]||0;for(let r=1;r<i;r++)b[r]=a[r]-be*a[r-1];const d=Math.floor(i/W)+1,x=C/2,u=r=>(r<0&&(r=-r),r>=i&&(r=2*(i-1)-r),b[Math.max(0,Math.min(i-1,r))]),y=(C-J)/2,g=new Float64Array(C),f=new Float64Array(C),v=new Float64Array(T),w=new Float32Array(L*d);for(let r=0;r<d;r++){const h=r*W-x;for(let n=0;n<C;n++){const e=n>=y&&n<y+J?s[n-y]:0;g[n]=e?u(h+n)*e:0,f[n]=0}ie(g,f);for(let n=0;n<T;n++)v[n]=g[n]*g[n]+f[n]*f[n];for(let n=0;n<L;n++){let e=0;const c=n*T;for(let t=0;t<T;t++)e+=o[c+t]*v[t];w[n*d+r]=Math.log(e+pe)}}for(let r=0;r<L;r++){const h=r*d;let n=0;for(let t=0;t<d;t++)n+=w[h+t];n/=d;let e=0;for(let t=0;t<d;t++)e+=(w[h+t]-n)**2;const c=Math.sqrt(e/Math.max(1,d-1))+me;for(let t=0;t<d;t++)w[h+t]=(w[h+t]-n)/c}return{data:w,frames:d}}function _e(a){return String(a||"").replace(/\b[A-Z][A-Z']*(?:[\s,.!?;:-]+[A-Z][A-Z']*){2,}\b/g,o=>o.toLowerCase().replace(/\bi\b/g,"I").replace(/\bi'(m|ll|ve|d)\b/g,(i,b)=>`I'${b}`).replace(/(^|[.!?]\s+)([a-z])/g,(i,b,d)=>b+d.toUpperCase())).replace(/(^|[.!?]\s+)([a-z])/,(o,s,i)=>/[A-Z]{3}/.test(a)?s+i.toUpperCase():o)}const ye=/\b(do|does|did|is|are|was|were|ca|could|would|should|wo|have|has|had|ai|must|need)n t\b/gi,Ie=[[ye,(a,o)=>`${o}n't`],[/\b(can) t\b/gi,(a,o)=>`${o}'t`],[/\b(it|that|what|there|here|let|he|she|who|where|how|everyone|nobody) s\b/gi,(a,o)=>`${o}'s`],[/\b(I) (m)\b/g,()=>"I'm"],[/\b(I|you|we|they) (ll|ve|d)\b/gi,(a,o,s)=>`${o}'${s}`],[/\b(you|we|they) re\b/gi,(a,o)=>`${o}'re`]];function xe(a){let o=String(a||"");for(const[s,i]of Ie)o=o.replace(s,i);return o}function ve(a,o){return a.map(s=>o[s]??"").join("").replace(/▁/g," ").trim()}async function Le({sessionOptions:a=null,log:o=()=>{}}={}){if(!se())throw new Error("Indic-Transcribe needs the npm gateway (the standalone binary cannot run it)");if(!q())throw new Error("Indic-Transcribe is not downloaded");const s=$();for(const[e,c]of Object.entries(D))if(!K.has(e)){if(await G(A(s,e))!==c)throw U(A(s,e),{force:!0}),new Error(`${e} changed on disk — removed`);K.add(e)}const i=await ce(),b={executionProviders:ae(),graphOptimizationLevel:"all",logSeverityLevel:3,...a||{}},[d,x,u]=await Promise.all(["encoder","cross_kv","decoder"].map(e=>i.InferenceSession.create(A(s,`${e}.onnx`),b))),y=e=>{const c=Z(A(s,e));return new Float32Array(c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength))},g={fb:y("mel_fb_128x257.f32"),window:y("window_400.f32")},f=JSON.parse(Z(A(s,"vocab.json"),"utf8")),v=new Set(f.eos),w=i.Tensor;o("[indic] ready — Indic-Transcribe-core (int8, in-process, offline)");async function r(e,c,t){const p=await u.run({ids:new w("int64",BigInt64Array.from([BigInt(c)]),[1,1]),pos:new w("int64",BigInt64Array.from([BigInt(t)]),[1]),self_k:e.k,self_v:e.v,cross_k:e.ck,cross_v:e.cv});return e.k=p.new_self_k,e.v=p.new_self_v,p.logits.data}async function h(e){const{data:c,frames:t}=ge(e,g),p=(await d.run({features:new w("float32",c,[1,L,t])})).states,S=await x.run({states:p}),E=new w("float32",new Float32Array(0),[we,1,he,0,ue]),l={k:E,v:E,ck:S.cross_k,cv:S.cross_v},_=f.prompt_te.slice();let F=null;for(let I=0;I<X;I++)F=await r(l,_[I],I);return{st:l,prompt:_,logits:F}}function n(e,c){const t=(c&&c.length?c:Object.keys(f.lang_ids)).filter(l=>f.lang_ids[l]!=null);let p=-1/0;for(const l of t)p=Math.max(p,e[f.lang_ids[l]]);let S=0;const E={};for(const l of t)E[l]=Math.exp(e[f.lang_ids[l]]-p),S+=E[l];return t.map(l=>[l,E[l]/S]).sort((l,_)=>_[1]-l[1])}return{vocab:f,async identify(e,{langs:c=[]}={}){if(!(e instanceof Float32Array)||e.length<P/4)return{lang:null,confidence:0,scores:{}};const t=n((await h(e)).logits,c);return t.length?{lang:t[0][0],confidence:t[0][1],scores:Object.fromEntries(t)}:{lang:null,confidence:0,scores:{}}},async transcribe(e,{lang:c=null,langs:t=[],last:p=null,maxNew:S=256,choose:E=null}={}){if(!(e instanceof Float32Array)||e.length<P/4)return{text:"",lang:c,confidence:0};const{st:l,prompt:_,logits:F}=await h(e);let I=null,O=c,R=1;if(!O){const m=n(F,t),k=Object.fromEntries(m);O=(E&&m.length?E(k,e.length/P):null)||m[0]?.[0]||p||"en",R=k[O]??0}const Y=f.lang_ids[O]??f.lang_ids.en;_[3]=_[4]=Y;for(let m=X;m<_.length;m++)I=await r(l,_[m],m);const j=[];for(let m=_.length;m<_.length+S;m++){let k=0,H=-1/0;for(let N=0;N<I.length;N++)I[N]>H&&(H=I[N],k=N);if(v.has(k))break;j.push(k),I=await r(l,k,m)}const B=_e(ve(j.filter(m=>!f.timestamp_ids.includes(m)),f.pieces));return{text:O==="en"?xe(B):B,lang:O,confidence:R}},async dispose(){for(const e of[d,x,u])try{await e.release?.()}catch{}}}}export{D as INDIC_FILES,M as INDIC_LICENSE,de as INDIC_LICENSE_ACCEPTANCE,$e as INDIC_MODEL_ID,le as INDIC_SOURCE,P as SAMPLE_RATE,ve as decodeIds,De as ensureIndicFiles,$ as indicDir,q as indicOnDisk,Le as loadRecognizer,ge as melFeatures,xe as restoreApostrophes,_e as restoreCase};
1
+ import{modelFetch as ee}from"./model-sources.js";import{existsSync as U,readFileSync as q,mkdirSync as te,createWriteStream as ne,createReadStream as re,renameSync as oe,rmSync as G}from"node:fs";import{createHash as ce}from"node:crypto";import{join as C}from"node:path";import{modelRoot as se}from"./ner-engine.js";import{getOrt as ae,ortProviders as ie,rawOrtAvailable as fe}from"./ort.js";import{fft as de}from"./aec-engine.js";import{INDIC_LICENSE as z,licenseAcceptance as le}from"./stt-models.js";const Le="bodhan-ai/indic-transcribe-core",be=le(z);function L(){return C(se(),"bodhan-ai","indic-transcribe-core-int8")}const pe="https://huggingface.co/ChatPanel/indic-transcribe-core-int8/resolve/main",P=Object.freeze({"encoder.onnx":"fa49d702bf83d52327105736ded11aea2e6afcfcb1667182e6db36e5cc27f097","encoder.onnx.data":"66c3442b950a3ff5e18fc33db1d15069b7888235776bdc86824d6f99d728f9a5","cross_kv.onnx":"0aed59ffef5e77e2b957d42f742ea2645fed3ac49954b6a91dc8e629d7196c26","cross_kv.onnx.data":"022d88763437e56ac1156b3953c68a01c205b52627094a086d243b822f6e810b","decoder.onnx":"f858a610f1d3498a993d5eb0424ef888d96edc853be3b7aa32846b237d2c4a97","decoder.onnx.data":"c557a469b426ad424b0ed04c7422df44fc12131df2ae300b3f4bc92bdf50d05b","mel_fb_128x257.f32":"586bbdf62da6485f02faecb278f781277fab9537558a57d611bf2fc35e12452b","window_400.f32":"cb9f40f78ef078b89ba969960015aa5e5a833e0c549e9dcdb532d9defbb418d2","vocab.json":"894a3b8761a73dec92577e7ef1664d1357fdee6008a598add2c9006423d3c79d","LICENSE.md":"b39f2a9cb2d5ace3a03f4425cbc6db38ebd9a53ab7a7648d67dc1e0998ad75c2"});function W(){return Object.keys(P).every(r=>U(C(L(),r)))}const X=r=>new Promise((o,i)=>{const s=ce("sha256");re(r).on("data",l=>s.update(l)).on("error",i).on("end",()=>o(s.digest("hex")))});async function Pe({licenseAccepted:r=null,onProgress:o=()=>{},log:i=()=>{},fetchImpl:s=ee()}={}){if(W())return L();if(r!==be){const A=new Error(`Indic-Transcribe is downloaded only after its licence (${z.name}) is accepted`);throw A.code="license_required",A}const l=L();te(l,{recursive:!0});const a=Object.keys(P);for(const[A,g]of a.entries()){const I=C(l,g);if(U(I))continue;const _=await s(`${pe}/${g}`);if(!_.ok||!_.body)throw new Error(`${g}: HTTP ${_.status}`);const f=Number(_.headers.get("content-length"))||0,S=`${I}.part`;if(await new Promise((u,c)=>{const w=ne(S),n=_.body.getReader();let h=0;const e=()=>n.read().then(({done:t,value:b})=>{if(t){w.end(u);return}h+=b.length,f&&o({file:g,pct:Math.round((A+h/f)/a.length*100)}),w.write(Buffer.from(b)),e()},c);w.on("error",c),e()}),await X(S)!==P[g])throw G(S,{force:!0}),new Error(`${g} does not match its pinned hash — not used`);oe(S,I),i(`[indic] fetched ${g}`)}return l}const M=16e3,F=512,J=160,K=400,T=128,j=F/2+1,he=.97,me=2**-24,ue=1e-5,we=24,ge=8,_e=128,Y=new Set,Q=3,R=80;function ye(r,o=R*M){const i=Math.max(1,Math.ceil(r/o)),s=Math.ceil(r/i),l=[];for(let a=0;a<r;a+=s)l.push([a,Math.min(r,a+s)]);return l}function xe(r,{fb:o,window:i}){const s=r.length,l=new Float32Array(s);l[0]=r[0]||0;for(let c=1;c<s;c++)l[c]=r[c]-he*r[c-1];const a=Math.floor(s/J)+1,A=F/2,g=c=>(c<0&&(c=-c),c>=s&&(c=2*(s-1)-c),l[Math.max(0,Math.min(s-1,c))]),I=(F-K)/2,_=new Float64Array(F),f=new Float64Array(F),S=new Float64Array(j),u=new Float32Array(T*a);for(let c=0;c<a;c++){const w=c*J-A;for(let n=0;n<F;n++){const h=n>=I&&n<I+K?i[n-I]:0;_[n]=h?g(w+n)*h:0,f[n]=0}de(_,f);for(let n=0;n<j;n++)S[n]=_[n]*_[n]+f[n]*f[n];for(let n=0;n<T;n++){let h=0;const e=n*j;for(let t=0;t<j;t++)h+=o[e+t]*S[t];u[n*a+c]=Math.log(h+me)}}for(let c=0;c<T;c++){const w=c*a;let n=0;for(let t=0;t<a;t++)n+=u[w+t];n/=a;let h=0;for(let t=0;t<a;t++)h+=(u[w+t]-n)**2;const e=Math.sqrt(h/Math.max(1,a-1))+ue;for(let t=0;t<a;t++)u[w+t]=(u[w+t]-n)/e}return{data:u,frames:a}}function Ie(r){return String(r||"").replace(/\b[A-Z][A-Z']*(?:[\s,.!?;:-]+[A-Z][A-Z']*){2,}\b/g,o=>o.toLowerCase().replace(/\bi\b/g,"I").replace(/\bi'(m|ll|ve|d)\b/g,(s,l)=>`I'${l}`).replace(/(^|[.!?]\s+)([a-z])/g,(s,l,a)=>l+a.toUpperCase())).replace(/(^|[.!?]\s+)([a-z])/,(o,i,s)=>/[A-Z]{3}/.test(r)?i+s.toUpperCase():o)}const ve=/\b(do|does|did|is|are|was|were|ca|could|would|should|wo|have|has|had|ai|must|need)n t\b/gi,Ee=[[ve,(r,o)=>`${o}n't`],[/\b(can) t\b/gi,(r,o)=>`${o}'t`],[/\b(it|that|what|there|here|let|he|she|who|where|how|everyone|nobody) s\b/gi,(r,o)=>`${o}'s`],[/\b(I) (m)\b/g,()=>"I'm"],[/\b(I|you|we|they) (ll|ve|d)\b/gi,(r,o,i)=>`${o}'${i}`],[/\b(you|we|they) re\b/gi,(r,o)=>`${o}'re`]];function Ae(r){let o=String(r||"");for(const[i,s]of Ee)o=o.replace(i,s);return o}function Se(r,o){return r.map(i=>o[i]??"").join("").replace(/▁/g," ").trim()}async function Te({sessionOptions:r=null,log:o=()=>{}}={}){if(!fe())throw new Error("Indic-Transcribe needs the npm gateway (the standalone binary cannot run it)");if(!W())throw new Error("Indic-Transcribe is not downloaded");const i=L();for(const[e,t]of Object.entries(P))if(!Y.has(e)){if(await X(C(i,e))!==t)throw G(C(i,e),{force:!0}),new Error(`${e} changed on disk — removed`);Y.add(e)}const s=await ae(),l={executionProviders:ie(),graphOptimizationLevel:"all",logSeverityLevel:3,...r||{}},[a,A,g]=await Promise.all(["encoder","cross_kv","decoder"].map(e=>s.InferenceSession.create(C(i,`${e}.onnx`),l))),I=e=>{const t=q(C(i,e));return new Float32Array(t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength))},_={fb:I("mel_fb_128x257.f32"),window:I("window_400.f32")},f=JSON.parse(q(C(i,"vocab.json"),"utf8")),S=new Set(f.eos),u=s.Tensor;o("[indic] ready — Indic-Transcribe-core (int8, in-process, offline)");async function c(e,t,b){const m=await g.run({ids:new u("int64",BigInt64Array.from([BigInt(t)]),[1,1]),pos:new u("int64",BigInt64Array.from([BigInt(b)]),[1]),self_k:e.k,self_v:e.v,cross_k:e.ck,cross_v:e.cv});return e.k=m.new_self_k,e.v=m.new_self_v,m.logits.data}async function w(e){const{data:t,frames:b}=xe(e.length>R*M?e.subarray(0,R*M):e,_),m=(await a.run({features:new u("float32",t,[1,T,b])})).states,O=await A.run({states:m}),v=new u("float32",new Float32Array(0),[we,1,ge,0,_e]),p={k:v,v,ck:O.cross_k,cv:O.cross_v},y=f.prompt_te.slice();let $=null;for(let E=0;E<Q;E++)$=await c(p,y[E],E);return{st:p,prompt:y,logits:$}}function n(e,t){const b=(t&&t.length?t:Object.keys(f.lang_ids)).filter(p=>f.lang_ids[p]!=null);let m=-1/0;for(const p of b)m=Math.max(m,e[f.lang_ids[p]]);let O=0;const v={};for(const p of b)v[p]=Math.exp(e[f.lang_ids[p]]-m),O+=v[p];return b.map(p=>[p,v[p]/O]).sort((p,y)=>y[1]-p[1])}return{vocab:f,async identify(e,{langs:t=[]}={}){if(!(e instanceof Float32Array)||e.length<M/4)return{lang:null,confidence:0,scores:{}};const b=n((await w(e)).logits,t);return b.length?{lang:b[0][0],confidence:b[0][1],scores:Object.fromEntries(b)}:{lang:null,confidence:0,scores:{}}},transcribe:h,async dispose(){for(const e of[a,A,g])try{await e.release?.()}catch{}}};async function h(e,{lang:t=null,langs:b=[],last:m=null,maxNew:O=256,choose:v=null}={}){if(!(e instanceof Float32Array)||e.length<M/4)return{text:"",lang:t,confidence:0};if(e.length>R*M){const d=[];for(const[x,D]of ye(e.length)){const k=await h(e.subarray(x,D),{lang:t,langs:b,last:m,maxNew:O,choose:v});k.text&&d.push(k),m=k.lang||m}return{text:d.map(x=>x.text).join(" "),lang:d[0]?.lang??t,confidence:d[0]?.confidence??0}}const{st:p,prompt:y,logits:$}=await w(e);let E=null,N=t,B=1;if(!N){const d=n($,b),x=Object.fromEntries(d);N=(v&&d.length?v(x,e.length/M):null)||d[0]?.[0]||m||"en",B=x[N]??0}const V=f.lang_ids[N]??f.lang_ids.en;y[3]=y[4]=V;for(let d=Q;d<y.length;d++)E=await c(p,y[d],d);const H=[];for(let d=y.length;d<y.length+O;d++){let x=0,D=-1/0;for(let k=0;k<E.length;k++)E[k]>D&&(D=E[k],x=k);if(S.has(x))break;H.push(x),E=await c(p,x,d)}const Z=Ie(Se(H.filter(d=>!f.timestamp_ids.includes(d)),f.pieces));return{text:N==="en"?Ae(Z):Z,lang:N,confidence:B}}}export{P as INDIC_FILES,z as INDIC_LICENSE,be as INDIC_LICENSE_ACCEPTANCE,Le as INDIC_MODEL_ID,pe as INDIC_SOURCE,R as MAX_SECONDS,M as SAMPLE_RATE,Se as decodeIds,Pe as ensureIndicFiles,L as indicDir,W as indicOnDisk,Te as loadRecognizer,xe as melFeatures,Ae as restoreApostrophes,Ie as restoreCase,ye as windowPieces};
package/src/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import{createServer as er}from"node:http";import{loadConfig as Wt}from"./config.js";import{startEntitlementRefresh as tr,maybeRevalidate as or}from"./entitlement-refresh.js";import{redactSegments as Ze,segment as ht,rememberAnswer as Kt}from"./redact.js";import{pipeRestoredStream as rr,pipeRestoredOpenAIStream as nr,makeTokenRestorer as Qt,restoreDeep as ar}from"./stream.js";import{restoreText as sr,gatedDictionary as ir,narrowSpecs as lr,makeToolHarness as dr,placeholderToolNote as cr,placeholderNote as ur,assertEndpointUrl as mr,capRunOptions as pr,isPaired as Yt}from"@chatpanel/pii";import{ensureGatewayToken as _e,currentGatewayToken as Me,isAdminAuthorized as H,callerTrustOf as Le,setPinnedExtensionIds as hr,issuePairingCode as yr,claimPairingCode as fr}from"./gateway-token.js";import{createPairAsk as gr,nativeConfirm as wr}from"./pair-prompt.js";import{createEngineProbe as br}from"./local-engine-probe.js";import{randomUUID as vr}from"node:crypto";import{installEgressLedger as kr,egressAudit as Sr}from"./egress.js";import{trustSystemCertificates as Tr,systemCaWanted as Xt,systemCaState as xr}from"./system-ca.js";import{initPolicy as _r,activePolicy as qe,applyPolicyToConfig as Zt,managedSummary as Je,PolicyLoadError as Or}from"./policy.js";import{routeAllowed as qt,agentAllowed as Er,egressAllowed as Pr}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as je}from"./bridge.js";import{secureFetch as et}from"./secure-fetch.js";import{fetchCard as tt,forgetCard as $r,sendMessage as Ar,streamMessage as Nr,getTask as Br,cancelTask as Mr,knownAgents as Dr,A2AError as eo}from"./a2a.js";import{streamBridgeChat as to,readBridgeToken as ze,openBridgeChat as Cr,acceptedBridgeToken as oo}from"./bridge.js";import{createRelaySession as Ir,getRelaySession as ro,endRelaySession as Ge,pumpBridgeStream as Rr,deliverToolResult as no,toolsToSpecs as Lr,wantsApprovals as Jr,parseToolCallId as ao,touchRelaySession as ot}from"./toolrelay.js";import{shaperFor as yt}from"./shape.js";import{startNer as jr,ensureNer as rt,unionForThisMachine as zr,skippedCompanions as Gr}from"./ner.js";import{recommendDetector as so}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Hr}from"./log.js";import{saveBackupSecret as Ur,clearBackupSecret as Vr,loadBackupSecret as ft,hasBackupSecret as io}from"./history-store.js";import{createMemoryStore as Fr}from"./memory-store.js";import{createPrefsStore as Wr}from"./prefs-store.js";import{agentCardFor as lo,runHintFor as co}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as Kr}from"@chatpanel/events/agent-thread.js";import{portClashPlan as Qr,serviceManagerOf as Yr,STANDBY_POLL_MS as Xr}from"@chatpanel/events/service-standby.js";import{threadTarget as Zr,frameQuestion as qr,wireMessages as en,appendExchange as tn,MAX_MESSAGE as uo}from"@chatpanel/events/thread-send.js";import{researchStore as on,researchResponse as rn}from"./research.js";import{createTeamStore as nn,loadOrCreateKey as gt}from"./team-store.js";import{createScorecardStore as an}from"./scorecard-store.js";import{createEngineLedgerStore as sn}from"./engine-ledger-store.js";import{createProjectStore as ln}from"./project-store.js";import{applicationsFor as dn,recruitPass as cn}from"./recruiting.js";import{ensureBridge as un,holderOf as mn}from"./bridge-supervisor.js";import{checkForUpdate as pn,updateStatus as hn,startUpdate as yn,updateJob as fn,installKind as gn}from"./update.js";import{confinedStatus as wt,confinedLine as wn}from"./confine.js";import{appleHelperWanted as bn,findAppleHelper as bt}from"./apple-helper-fetch.js";import{createHistoryStore as vn}from"./sqlite-store.js";import{createEventStore as kn}from"./event-store.js";import{createLinkActivity as Sn,linkSurface as Tn,sseUsageTap as xn,usageOfBody as _n,GATEWAY_HOST as mo}from"./link-activity.js";import{ingestCloudEvents as On,cursorOf as po}from"./event-sync.js";import{eventStats as En,projectYear as Pn}from"./event-stats.js";import{toCloudEvent as vt,ceHostOf as $n}from"./cloudevents.js";import{fusionsDocument as An,resolveFusionModel as Nn}from"./fusions.js";import{ingestBackups as kt}from"./backup-ingest.js";import{toSearchRecord as ho}from"@chatpanel/events/library.js";import{deriveBackupKey as Bn,openRecord as Mn,keyCache as Dn,nodeCodec as Cn}from"@chatpanel/events/backup-envelope.js";import In from"node:zlib";import*as L from"./ner-engine.js";import St from"node:os";import{capabilitiesDocument as Rn,handleDetect as Ln}from"./capabilities.js";import{createExtractService as Jn}from"./extract/service.js";import{workerSandbox as jn,disposeWorkerSandbox as zn}from"./worker-sandbox.js";import{createRuntime as Gn,SERVICES as Hn}from"./runtime.js";import{createCapabilityProxy as Un}from"./capability-proxy.js";import{createEmbeddedCapabilities as Vn}from"./capability-embedded.js";import{EMBEDDED_MODELS as Fn,EMBEDDED_IDS as Wn}from"./embedded-models.js";import{handleExtract as Kn,handleExtractContext as Qn}from"./extract/handler.js";import{createKbStore as Yn}from"./kb-store.js";import{createKbService as Xn}from"./kb.js";import{MAX_DOCUMENT_BYTES as Tt}from"./extract-capability.js";import{createReader as Zn}from"./retrieval/read.js";import{createBrowserRelayHost as qn}from"./browser-relay.js";import{createLinkHost as ea}from"./link-host.js";import{checkLinkRoute as ta,tunnelHeader as oa,LINK_TUNNEL_ROOM_PATH as ra}from"@chatpanel/events/link-routes.js";import{linkCallerOf as nt,linkDestinationAllowed as na,linkVia as aa,partnerRunHint as sa,PARTNER_APPROVAL_DECISIONS as yo,partnerFilePath as ia}from"@chatpanel/events/link-scopes.js";import{listPartnerFiles as la,readPartnerFile as da,writePartnerFile as ca,removePartnerFile as ua}from"./link-files.js";import{handleFileWrite as ma}from"./file-write.js";import{handleAppleNotes as pa}from"./apple-notes.js";import{WRITE_MAX_BYTES as ha}from"@chatpanel/events/file-write.js";import{isPermissionTool as fo}from"@chatpanel/events/agent-permission.js";import{createApprovalInbox as ya}from"./link-approvals.js";import{createSearcher as fa,toJinaSearch as ga,SEARCH_DEFAULTS as wa}from"./retrieval/search.js";import{createSearxng as ba}from"./retrieval/search-searxng.js";import{searchEngines as va}from"./retrieval/search-apis.js";import{toJinaText as ka}from"./read-document.js";import*as A from"./stt-engine.js";import*as D from"./diarize-engine.js";import*as $e from"./translate-engine.js";import*as Sa from"./indictrans-engine.js";import*as xt from"./aec-engine.js";import{speechCoverage as Ta}from"@chatpanel/events/speech-language.js";import*as xa from"./segment-engine.js";import{DIARIZE_MODEL_CATALOG as _a,DEFAULT_DIARIZE_MODEL as Oa,isKnownDiarizeModel as go}from"./diarize-models.js";import{providerOf as _t}from"./providers.js";import{createRemoteTranscriber as wo}from"./stt-remote.js";import{parseMultipart as Ea,decodeAudioFile as Pa}from"./audio-file.js";import{MODEL_CATALOG as bo,isKnownModel as vo,isValidCustomModelId as ko,recommendFor as $a}from"./models.js";import{STT_MODEL_CATALOG as Aa,isKnownSttModel as Na,isValidCustomSttId as Ba,DEFAULT_STT_MODEL as De,STT_DTYPES as Ma,isValidDtype as Da,sttModel as at,sttModelUnavailable as So,licenseAcceptance as To}from"./stt-models.js";import*as C from"./tts-engine.js";import{TTS_MODEL_CATALOG as xo,TTS_VOICES as Ca,isKnownTtsModel as Ia,isValidCustomTtsId as Ra,isKnownVoice as _o,isValidVoiceId as Oo,DEFAULT_TTS_MODEL as Eo,DEFAULT_TTS_VOICE as Oe,TTS_DTYPES as La,isValidTtsDtype as Ja,MAX_TTS_CHARS as Po,ttsModelHasCustomVoices as ja,resolveDefaultModel as $o,POCKET_VOICES as za,DEFAULT_POCKET_VOICE as st,isPocketVoice as it,ttsModelEngine as lt}from"./tts-models.js";import{ttsDestination as Ga,synthesizeRemote as Ha,isValidRemoteVoice as Ua}from"./tts-remote.js";import{rawOrtAvailable as Ot}from"./ort.js";import*as pe from"./tts-voices.js";import{resolveTtsVoice as Va}from"./tts-voice-resolve.js";import{resolvePro as Te,checkQuota as Fa,consume as Wa,usage as Ka}from"./freegate.js";import{publicConfig as Ao,applyConfigPatch as Qa,registryChildEnv as Ya,applyNerModelSelection as No,persistConfig as be,configPath as le,bridgeAgentOptions as Bo,PERMISSION_MODES as Xa,sandboxEnvFor as Za,sandboxProblems as qa}from"./configstore.js";import He from"node:path";import{resolveDestination as dt,aggregateModelsAsync as es,listDestinations as ts,ensureModelCatalog as os,agentOwnsModel as rs}from"./router.js";import{makeAccessEvent as Mo}from"./observability.js";import{createPersistentAccessLog as ns}from"./access-log-store.js";import{planQueries as as,multiSearch as ss}from"./rrf.js";import*as Et from"./openai.js";import*as Do from"./responses.js";import*as Pt from"./anthropic.js";import{closeAndExit as is}from"./shutdown.js";import{VERSION as de}from"./version.js";import{VERSION as _l}from"./version.js";const J=await vn(),xe=new Set;function Ue({ids:t=[]}={}){const d=J.lossless;if(!d||!xe.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 p of xe)try{p.write(`event: records
1
+ import{createServer as er}from"node:http";import{loadConfig as Wt}from"./config.js";import{startEntitlementRefresh as tr,maybeRevalidate as or}from"./entitlement-refresh.js";import{redactSegments as Ze,segment as ht,rememberAnswer as Kt}from"./redact.js";import{pipeRestoredStream as rr,pipeRestoredOpenAIStream as nr,makeTokenRestorer as Qt,restoreDeep as ar}from"./stream.js";import{restoreText as sr,gatedDictionary as ir,narrowSpecs as lr,makeToolHarness as dr,placeholderToolNote as cr,placeholderNote as ur,assertEndpointUrl as mr,capRunOptions as pr,isPaired as Yt}from"@chatpanel/pii";import{ensureGatewayToken as _e,currentGatewayToken as Me,isAdminAuthorized as H,callerTrustOf as Le,setPinnedExtensionIds as hr,issuePairingCode as yr,claimPairingCode as fr}from"./gateway-token.js";import{createPairAsk as gr,nativeConfirm as wr}from"./pair-prompt.js";import{createEngineProbe as br}from"./local-engine-probe.js";import{randomUUID as vr}from"node:crypto";import{installEgressLedger as kr,egressAudit as Sr}from"./egress.js";import{trustSystemCertificates as Tr,systemCaWanted as Xt,systemCaState as xr}from"./system-ca.js";import{initPolicy as _r,activePolicy as qe,applyPolicyToConfig as Zt,managedSummary as Je,PolicyLoadError as Or}from"./policy.js";import{routeAllowed as qt,agentAllowed as Er,egressAllowed as Pr}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as je}from"./bridge.js";import{secureFetch as et}from"./secure-fetch.js";import{fetchCard as tt,forgetCard as $r,sendMessage as Ar,streamMessage as Nr,getTask as Br,cancelTask as Mr,knownAgents as Dr,A2AError as eo}from"./a2a.js";import{streamBridgeChat as to,readBridgeToken as ze,openBridgeChat as Cr,acceptedBridgeToken as oo}from"./bridge.js";import{createRelaySession as Ir,getRelaySession as ro,endRelaySession as Ge,pumpBridgeStream as Rr,deliverToolResult as no,toolsToSpecs as Lr,wantsApprovals as Jr,parseToolCallId as ao,touchRelaySession as ot}from"./toolrelay.js";import{shaperFor as yt}from"./shape.js";import{startNer as jr,ensureNer as rt,unionForThisMachine as zr,skippedCompanions as Gr}from"./ner.js";import{recommendDetector as so}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Hr}from"./log.js";import{saveBackupSecret as Ur,clearBackupSecret as Vr,loadBackupSecret as ft,hasBackupSecret as io}from"./history-store.js";import{createMemoryStore as Fr}from"./memory-store.js";import{createPrefsStore as Wr}from"./prefs-store.js";import{agentCardFor as lo,runHintFor as co}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as Kr}from"@chatpanel/events/agent-thread.js";import{portClashPlan as Qr,serviceManagerOf as Yr,STANDBY_POLL_MS as Xr}from"@chatpanel/events/service-standby.js";import{threadTarget as Zr,frameQuestion as qr,wireMessages as en,appendExchange as tn,MAX_MESSAGE as uo}from"@chatpanel/events/thread-send.js";import{researchStore as on,researchResponse as rn}from"./research.js";import{createTeamStore as nn,loadOrCreateKey as gt}from"./team-store.js";import{createScorecardStore as an}from"./scorecard-store.js";import{createEngineLedgerStore as sn}from"./engine-ledger-store.js";import{createProjectStore as ln}from"./project-store.js";import{applicationsFor as dn,recruitPass as cn}from"./recruiting.js";import{ensureBridge as un,holderOf as mn}from"./bridge-supervisor.js";import{checkForUpdate as pn,updateStatus as hn,startUpdate as yn,updateJob as fn,installKind as gn}from"./update.js";import{confinedStatus as wt,confinedLine as wn}from"./confine.js";import{appleHelperWanted as bn,findAppleHelper as bt}from"./apple-helper-fetch.js";import{createHistoryStore as vn}from"./sqlite-store.js";import{createEventStore as kn}from"./event-store.js";import{createLinkActivity as Sn,linkSurface as Tn,sseUsageTap as xn,usageOfBody as _n,GATEWAY_HOST as mo}from"./link-activity.js";import{ingestCloudEvents as On,cursorOf as po}from"./event-sync.js";import{eventStats as En,projectYear as Pn}from"./event-stats.js";import{toCloudEvent as vt,ceHostOf as $n}from"./cloudevents.js";import{fusionsDocument as An,resolveFusionModel as Nn}from"./fusions.js";import{ingestBackups as kt}from"./backup-ingest.js";import{toSearchRecord as ho}from"@chatpanel/events/library.js";import{deriveBackupKey as Bn,openRecord as Mn,keyCache as Dn,nodeCodec as Cn}from"@chatpanel/events/backup-envelope.js";import In from"node:zlib";import*as L from"./ner-engine.js";import St from"node:os";import{capabilitiesDocument as Rn,handleDetect as Ln}from"./capabilities.js";import{createExtractService as Jn}from"./extract/service.js";import{workerSandbox as jn,disposeWorkerSandbox as zn}from"./worker-sandbox.js";import{createRuntime as Gn,SERVICES as Hn}from"./runtime.js";import{createCapabilityProxy as Un}from"./capability-proxy.js";import{createEmbeddedCapabilities as Vn}from"./capability-embedded.js";import{EMBEDDED_MODELS as Fn,EMBEDDED_IDS as Wn}from"./embedded-models.js";import{handleExtract as Kn,handleExtractContext as Qn}from"./extract/handler.js";import{createKbStore as Yn}from"./kb-store.js";import{createKbService as Xn}from"./kb.js";import{MAX_DOCUMENT_BYTES as Tt}from"./extract-capability.js";import{createReader as Zn}from"./retrieval/read.js";import{createBrowserRelayHost as qn}from"./browser-relay.js";import{createLinkHost as ea}from"./link-host.js";import{checkLinkRoute as ta,tunnelHeader as oa,LINK_TUNNEL_ROOM_PATH as ra}from"@chatpanel/events/link-routes.js";import{linkCallerOf as nt,linkDestinationAllowed as na,linkVia as aa,partnerRunHint as sa,PARTNER_APPROVAL_DECISIONS as yo,partnerFilePath as ia}from"@chatpanel/events/link-scopes.js";import{listPartnerFiles as la,readPartnerFile as da,writePartnerFile as ca,removePartnerFile as ua}from"./link-files.js";import{handleFileWrite as ma}from"./file-write.js";import{handleAppleNotes as pa}from"./apple-notes.js";import{WRITE_MAX_BYTES as ha}from"@chatpanel/events/file-write.js";import{isPermissionTool as fo}from"@chatpanel/events/agent-permission.js";import{createApprovalInbox as ya}from"./link-approvals.js";import{createSearcher as fa,toJinaSearch as ga,SEARCH_DEFAULTS as wa}from"./retrieval/search.js";import{createSearxng as ba}from"./retrieval/search-searxng.js";import{searchEngines as va}from"./retrieval/search-apis.js";import{toJinaText as ka}from"./read-document.js";import*as A from"./stt-engine.js";import*as M from"./diarize-engine.js";import*as $e from"./translate-engine.js";import*as Sa from"./indictrans-engine.js";import*as xt from"./aec-engine.js";import{speechCoverage as Ta}from"@chatpanel/events/speech-language.js";import*as xa from"./segment-engine.js";import{DIARIZE_MODEL_CATALOG as _a,DEFAULT_DIARIZE_MODEL as Oa,isKnownDiarizeModel as go,diarizeModelEntry as Ea}from"./diarize-models.js";import{providerOf as _t}from"./providers.js";import{createRemoteTranscriber as wo}from"./stt-remote.js";import{parseMultipart as Pa,decodeAudioFile as $a}from"./audio-file.js";import{MODEL_CATALOG as bo,isKnownModel as vo,isValidCustomModelId as ko,recommendFor as Aa}from"./models.js";import{STT_MODEL_CATALOG as Na,isKnownSttModel as Ba,isValidCustomSttId as Ma,DEFAULT_STT_MODEL as De,STT_DTYPES as Da,isValidDtype as Ca,sttModel as at,sttModelUnavailable as So,licenseAcceptance as To}from"./stt-models.js";import*as D from"./tts-engine.js";import{TTS_MODEL_CATALOG as xo,TTS_VOICES as Ia,isKnownTtsModel as Ra,isValidCustomTtsId as La,isKnownVoice as _o,isValidVoiceId as Oo,DEFAULT_TTS_MODEL as Eo,DEFAULT_TTS_VOICE as Oe,TTS_DTYPES as Ja,isValidTtsDtype as ja,MAX_TTS_CHARS as Po,ttsModelHasCustomVoices as za,resolveDefaultModel as $o,POCKET_VOICES as Ga,DEFAULT_POCKET_VOICE as st,isPocketVoice as it,ttsModelEngine as lt}from"./tts-models.js";import{ttsDestination as Ha,synthesizeRemote as Ua,isValidRemoteVoice as Va}from"./tts-remote.js";import{rawOrtAvailable as Ot}from"./ort.js";import*as de from"./tts-voices.js";import{resolveTtsVoice as Fa}from"./tts-voice-resolve.js";import{resolvePro as Te,checkQuota as Wa,consume as Ka,usage as Qa}from"./freegate.js";import{publicConfig as Ao,applyConfigPatch as Ya,registryChildEnv as Xa,applyNerModelSelection as No,persistConfig as be,configPath as ce,bridgeAgentOptions as Bo,PERMISSION_MODES as Za,sandboxEnvFor as qa,sandboxProblems as es}from"./configstore.js";import He from"node:path";import{resolveDestination as dt,aggregateModelsAsync as ts,listDestinations as os,ensureModelCatalog as rs,agentOwnsModel as ns}from"./router.js";import{makeAccessEvent as Mo}from"./observability.js";import{createPersistentAccessLog as as}from"./access-log-store.js";import{planQueries as ss,multiSearch as is}from"./rrf.js";import*as Et from"./openai.js";import*as Do from"./responses.js";import*as Pt from"./anthropic.js";import{closeAndExit as ls}from"./shutdown.js";import{VERSION as ue}from"./version.js";import{VERSION as Ol}from"./version.js";const J=await vn(),xe=new Set;function Ue({ids:t=[]}={}){const d=J.lossless;if(!d||!xe.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 p of xe)try{p.write(`event: records
2
2
  data: ${u}
3
3
 
4
4
  `)}catch{xe.delete(p)}}setInterval(()=>{for(const t of xe)try{t.write(`: ping
@@ -8,60 +8,60 @@ data: ${JSON.stringify(vt(t))}
8
8
 
9
9
  `;for(const u of Ee)try{u.write(d)}catch{Ee.delete(u)}}),setInterval(()=>{for(const t of Ee)try{t.write(`: ping
10
10
 
11
- `)}catch{Ee.delete(t)}},25e3).unref?.();const fe=await Fr(),ce=Wr(),Ce=an({key:gt()}),Ie=sn({key:gt()}),he=ln({key:gt()}),oe=nn({scorecards:Ce,engines:Ie}),At=new Set,Co=(t,d)=>{for(const p of At)try{p({applied:t,by:d,revision:ce.revision})}catch{}const u=JSON.stringify({revision:ce.revision,applied:(t||[]).slice(0,50),by:d||"",at:Date.now()});for(const p of xe)try{p.write(`event: prefs
11
+ `)}catch{Ee.delete(t)}},25e3).unref?.();const fe=await Fr(),me=Wr(),Ce=an({key:gt()}),Ie=sn({key:gt()}),he=ln({key:gt()}),re=nn({scorecards:Ce,engines:Ie}),At=new Set,Co=(t,d)=>{for(const p of At)try{p({applied:t,by:d,revision:me.revision})}catch{}const u=JSON.stringify({revision:me.revision,applied:(t||[]).slice(0,50),by:d||"",at:Date.now()});for(const p of xe)try{p.write(`event: prefs
12
12
  data: ${u}
13
13
 
14
- `)}catch{xe.delete(p)}},Nt=ns(),Io=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),ls=16,ds=/^mcp[_-]/i,Ro=t=>t&&t.function&&t.function.name||t&&t.name||"",cs=t=>t&&t.function&&t.function.description||t&&t.description||"";function Lo(t){return typeof t=="string"?t:Array.isArray(t)?t.map(d=>typeof d=="string"?d:d&&(d.text||d.content)||"").join(" "):""}function us(t,d){if(!t)return"";if(d==="responses"){const p=t.input;return typeof p=="string"?p:Array.isArray(p)?p.map(w=>Lo(w&&(w.content??w))).join(" "):""}const u=Array.isArray(t.messages)?t.messages:[];for(let p=u.length-1;p>=0;p--)if(u[p]&&u[p].role==="user")return Lo(u[p].content);return""}const Jo=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function ct(t){if(!t)return!1;const d=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return d==="localhost"||d==="127.0.0.1"||d==="::1"}function ms(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 ps(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 jo=Date.now();function hs(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 ys(t){const d=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return d?{kind:d[1],id:d[2],...d[3]?{model:d[3]}:{}}:null}function fs(t){const d=performance.now(),u={};let p=!1;const w=(y,$)=>{u[y]=Math.round($*10)/10};return{meta:{},timings:u,mark:w,lap(y,$){w(y,performance.now()-$)},clock(){return performance.now()},commit(){if(p)return;p=!0,w("total",performance.now()-d);const y={...this.meta,timings:u};setImmediate(()=>{t(y),console.log(`[gateway] model=${y.model||"-"} → ${y.dest?`${y.dest}(${y.type})`:"none"} · ${y.redaction==="off"?"redaction OFF (client request)":`redacted ${y.redacted||0}`}${y.sanitized?` · scrubbed ${y.sanitized} hidden`:""}${y.narrowed?` · narrowed -${y.narrowed}`:""} · ${hs(u)}`)})}}}function zo(t,d){if(!t||!t.byToken||d!=="types"&&d!=="values")return;const u=[];for(const[p,w]of t.byToken){const y=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(p),$=y?y[1]:"PII",B=p.replace(/^\[\[|\]\]$/g,"");u.push(d==="values"?{token:B,type:$,value:w}:{token:B,type:$})}return u}function gs(t,d,u){return Pt.matches(t)||"anthropic-version"in d?{kind:"anthropic",adapter:Pt,redactable:Pt.matches(t),base:u.upstreams?.anthropic?.baseUrl}:Do.matches(t)?{kind:"responses",adapter:Do,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Et,redactable:Et.matches(t),base:u.upstreams?.openai?.baseUrl}}function Bt(t,d){const u=String(t||"");if(Io.has(u))return{agent:u,agentModel:""};const p=u.indexOf("/");if(p>0){const w=u.slice(0,p);if(Io.has(w))return{agent:w,agentModel:u.slice(p+1)}}return{agent:d.bridge.agent,agentModel:""}}function Go(t,d){return Bt(t,d).agent}function ws(t,d){if(d!=="openai"||!t)return!1;const u=Et.extractLatestToolResult(t);if(!u)return!1;const p=ao(u.tool_call_id);return!!(p&&ro(p.gwId))}function bs(t,d){try{const u=new URL(t),p=u.hostname.replace(/^\[|\]$/g,""),w=p==="127.0.0.1"||p==="localhost"||p==="::1",y=u.port||(u.protocol==="https:"?"443":"80");return w&&String(y)===String(d.port)}catch{return!1}}const vs=25*1024*1024;async function S(t,d){const u=[];let p=0;for await(const w of t){if(p+=w.length,d&&p>d){const y=new Error("payload too large");throw y.code=413,y}u.push(w)}return Buffer.concat(u)}function a(t,d,u){t.writeHead(d,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function Ho(t){const d=t.redaction?.detection?.url;return!d||t.redaction?.detection?.backend==="off"?null:d}function Mt(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 p=L.health(),w=p.ok&&u==="full";return{source:"bundled",state:p.state,model:p.model||t?.ner?.model||null,installed:L.modelOnDisk(t?.ner?.model||void 0),error:p.error||null,ready:w,tier:u,coverage:w?"names":"patterns"}}async function Uo(t){if(L.state()!=="off"){const u=L.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=Ho(t);if(!d)return{configured:!1,ok:!1,url:null,model:null};try{const u=await et(d.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:d,model:null};const p=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:d,model:p.model||null}}catch{return{configured:!0,ok:!1,url:d,model:null}}}function ks(t,d){const u={};for(const[p,w]of Object.entries(t)){const y=p.toLowerCase();y.startsWith("x-chatpanel-")||Jo.has(y)||(u[p]=w)}u["accept-encoding"]="identity";try{u.host=new URL(d).host}catch{}return u}async function Vo(t,d,u,p){const w=Qt(d.vault),y=Ct();t.on("close",()=>{t.writableFinished||Ge(d.id)});const $=d.linkTurn||null,B=p?p.clock():0;let E=B,T=!0;const x=()=>{p&&T&&(p.lap("upstream",B),E=p.clock(),T=!1)};let R="";const j=()=>{d.redaction&&R&&Kt(R,d.redaction),R=""};let V=null;const P={onText:U=>{x(),ot(d.id);const z=w.push(U);z&&(R+=z,t.write(u.sseDelta(z)))},onToolRequest:({name:U,restoredArgs:z,toolId:X})=>{if(x(),ot(d.id),d.ownerApprovals&&fo(U)){V=z;return}const ee=w.flush();ee&&(R+=ee,t.write(u.sseDelta(ee))),t.write(u.sseToolCalls([{id:X,name:U,arguments:JSON.stringify(z)}])),t.write(u.sseToolFinish(y.value)),p&&p.lap("stream",E),t.end(),p?.commit(),j()},onDone:()=>{const U=w.flush();U&&(R+=U,t.write(u.sseDelta(U))),t.write(u.sseTail(y.value)),p&&p.lap("stream",E),t.end(),$?.end("ok"),Ge(d.id),p?.commit(),j(),Dt(d)},onError:U=>{t.write(`data: ${JSON.stringify({error:{message:U.message,type:"bridge_error"}})}
14
+ `)}catch{xe.delete(p)}},Nt=as(),Io=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),ds=16,cs=/^mcp[_-]/i,Ro=t=>t&&t.function&&t.function.name||t&&t.name||"",us=t=>t&&t.function&&t.function.description||t&&t.description||"";function Lo(t){return typeof t=="string"?t:Array.isArray(t)?t.map(d=>typeof d=="string"?d:d&&(d.text||d.content)||"").join(" "):""}function ms(t,d){if(!t)return"";if(d==="responses"){const p=t.input;return typeof p=="string"?p:Array.isArray(p)?p.map(w=>Lo(w&&(w.content??w))).join(" "):""}const u=Array.isArray(t.messages)?t.messages:[];for(let p=u.length-1;p>=0;p--)if(u[p]&&u[p].role==="user")return Lo(u[p].content);return""}const Jo=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function ct(t){if(!t)return!1;const d=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return d==="localhost"||d==="127.0.0.1"||d==="::1"}function ps(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 hs(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 jo=Date.now();function ys(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 fs(t){const d=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return d?{kind:d[1],id:d[2],...d[3]?{model:d[3]}:{}}:null}function gs(t){const d=performance.now(),u={};let p=!1;const w=(y,$)=>{u[y]=Math.round($*10)/10};return{meta:{},timings:u,mark:w,lap(y,$){w(y,performance.now()-$)},clock(){return performance.now()},commit(){if(p)return;p=!0,w("total",performance.now()-d);const y={...this.meta,timings:u};setImmediate(()=>{t(y),console.log(`[gateway] model=${y.model||"-"} → ${y.dest?`${y.dest}(${y.type})`:"none"} · ${y.redaction==="off"?"redaction OFF (client request)":`redacted ${y.redacted||0}`}${y.sanitized?` · scrubbed ${y.sanitized} hidden`:""}${y.narrowed?` · narrowed -${y.narrowed}`:""} · ${ys(u)}`)})}}}function zo(t,d){if(!t||!t.byToken||d!=="types"&&d!=="values")return;const u=[];for(const[p,w]of t.byToken){const y=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(p),$=y?y[1]:"PII",B=p.replace(/^\[\[|\]\]$/g,"");u.push(d==="values"?{token:B,type:$,value:w}:{token:B,type:$})}return u}function ws(t,d,u){return Pt.matches(t)||"anthropic-version"in d?{kind:"anthropic",adapter:Pt,redactable:Pt.matches(t),base:u.upstreams?.anthropic?.baseUrl}:Do.matches(t)?{kind:"responses",adapter:Do,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Et,redactable:Et.matches(t),base:u.upstreams?.openai?.baseUrl}}function Bt(t,d){const u=String(t||"");if(Io.has(u))return{agent:u,agentModel:""};const p=u.indexOf("/");if(p>0){const w=u.slice(0,p);if(Io.has(w))return{agent:w,agentModel:u.slice(p+1)}}return{agent:d.bridge.agent,agentModel:""}}function Go(t,d){return Bt(t,d).agent}function bs(t,d){if(d!=="openai"||!t)return!1;const u=Et.extractLatestToolResult(t);if(!u)return!1;const p=ao(u.tool_call_id);return!!(p&&ro(p.gwId))}function vs(t,d){try{const u=new URL(t),p=u.hostname.replace(/^\[|\]$/g,""),w=p==="127.0.0.1"||p==="localhost"||p==="::1",y=u.port||(u.protocol==="https:"?"443":"80");return w&&String(y)===String(d.port)}catch{return!1}}const ks=25*1024*1024;async function S(t,d){const u=[];let p=0;for await(const w of t){if(p+=w.length,d&&p>d){const y=new Error("payload too large");throw y.code=413,y}u.push(w)}return Buffer.concat(u)}function a(t,d,u){t.writeHead(d,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function Ho(t){const d=t.redaction?.detection?.url;return!d||t.redaction?.detection?.backend==="off"?null:d}function Mt(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 p=L.health(),w=p.ok&&u==="full";return{source:"bundled",state:p.state,model:p.model||t?.ner?.model||null,installed:L.modelOnDisk(t?.ner?.model||void 0),error:p.error||null,ready:w,tier:u,coverage:w?"names":"patterns"}}async function Uo(t){if(L.state()!=="off"){const u=L.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=Ho(t);if(!d)return{configured:!1,ok:!1,url:null,model:null};try{const u=await et(d.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:d,model:null};const p=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:d,model:p.model||null}}catch{return{configured:!0,ok:!1,url:d,model:null}}}function Ss(t,d){const u={};for(const[p,w]of Object.entries(t)){const y=p.toLowerCase();y.startsWith("x-chatpanel-")||Jo.has(y)||(u[p]=w)}u["accept-encoding"]="identity";try{u.host=new URL(d).host}catch{}return u}async function Vo(t,d,u,p){const w=Qt(d.vault),y=Ct();t.on("close",()=>{t.writableFinished||Ge(d.id)});const $=d.linkTurn||null,B=p?p.clock():0;let E=B,T=!0;const _=()=>{p&&T&&(p.lap("upstream",B),E=p.clock(),T=!1)};let R="";const j=()=>{d.redaction&&R&&Kt(R,d.redaction),R=""};let V=null;const P={onText:U=>{_(),ot(d.id);const z=w.push(U);z&&(R+=z,t.write(u.sseDelta(z)))},onToolRequest:({name:U,restoredArgs:z,toolId:X})=>{if(_(),ot(d.id),d.ownerApprovals&&fo(U)){V=z;return}const te=w.flush();te&&(R+=te,t.write(u.sseDelta(te))),t.write(u.sseToolCalls([{id:X,name:U,arguments:JSON.stringify(z)}])),t.write(u.sseToolFinish(y.value)),p&&p.lap("stream",E),t.end(),p?.commit(),j()},onDone:()=>{const U=w.flush();U&&(R+=U,t.write(u.sseDelta(U))),t.write(u.sseTail(y.value)),p&&p.lap("stream",E),t.end(),$?.end("ok"),Ge(d.id),p?.commit(),j(),Dt(d)},onError:U=>{t.write(`data: ${JSON.stringify({error:{message:U.message,type:"bridge_error"}})}
15
15
 
16
- `),t.end(),$?.end("error",{code:"bridge_error"}),Ge(d.id),p?.commit(),Dt(d)},onUsage:U=>{y.add(U),$?.add(U)}};for(;;){if(V=null,await Rr(d,P)!=="parked"||!V)return;const z=d.ownerApprovals,X=new AbortController,ee=()=>X.abort();t.once("close",ee);const te=setInterval(()=>{ot(d.id),t.writableEnded||t.write(`: waiting for the owner’s approval
16
+ `),t.end(),$?.end("error",{code:"bridge_error"}),Ge(d.id),p?.commit(),Dt(d)},onUsage:U=>{y.add(U),$?.add(U)}};for(;;){if(V=null,await Rr(d,P)!=="parked"||!V)return;const z=d.ownerApprovals,X=new AbortController,te=()=>X.abort();t.once("close",te);const oe=setInterval(()=>{ot(d.id),t.writableEnded||t.write(`: waiting for the owner’s approval
17
17
 
18
- `)},15e3);te.unref?.();let ye;try{ye=await z.inbox.ask(V,{partner:z.partner,device:z.device,conversation:z.conversation,signal:X.signal})}finally{clearInterval(te),t.off("close",ee)}if(X.signal.aborted||t.writableEnded){Dt(d);return}try{await no(d,JSON.stringify(ye))}catch(Y){P.onError(Y);return}}}function Dt(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function Ss(t,d,{kind:u,adapter:p,agent:w,run:y=null,owner:$=null,linkTurn:B=null},E,T,x,R,j,V=null,P=null){const{messages:U,system:z}=p.toTurn(E),{agentModel:X}=Bt(E?.model,x),ee=Bo(x,{...X?{model:X}:{},...y||{}}),te=ze(x.bridge.token),ye=yt(u,E?.model||w),Y={tier:x.redaction.tier==="full"?"full":"basic",dictionary:ir(x.redaction,R),entities:[]},ge=await je(x),I=Ir({vault:T,redactOpts:Y,bridgeUrl:ge,token:te,harness:V});$&&(I.ownerApprovals={...$,conversation:$.conversation||`partner.${$.device}.turn-${I.id}`,turnScoped:!$.conversation}),B&&(I.linkTurn=B,I.onEnd=()=>B.end("aborted")),T&&(I.redaction=x.redaction);let q;try{q=await Cr({bridgeUrl:ge,agent:w,token:te,messages:U,system:z,specs:Lr(j),options:ee,signal:void 0,approvals:!!$||Jr(j)})}catch(ue){return B?.end("error",{code:"bridge_error"}),Ge(I.id),P?.commit(),a(d,502,{error:{message:`bridge: ${ue.message}`,type:"bridge_error"}})}return I.reader=q.body.getReader(),d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(ye.sseHead()),Vo(d,I,ye,P)}async function Ts(t,d,u,p,w=null){ot(d.id),d.rounds=(d.rounds||0)+1;try{const $=w?w.clock():0;await no(d,u),w&&w.lap("redact",$)}catch($){return d.linkTurn?.end("error",{code:"tool_result"}),Ge(d.id),w?.commit(),a(t,502,{error:{message:`tool-result: ${$.message}`,type:"bridge_error"}})}const y=yt("openai",p||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(y.sseHead()),Vo(t,d,y,w)}function Ct(){let t=!1;const d={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const p of Object.keys(d))d[p]+=Math.max(0,Number(u?.[p])||0)},get value(){return t?d:null}}}async function xs(t,d,{kind:u,adapter:p,redactable:w,pathname:y,agentOverride:$,harness:B,trace:E,run:T=null,owner:x=null,link:R=null},j,V,P,U){if(!w)return E?.commit(),a(d,404,{error:`endpoint ${y} not supported by the bridge backend`});if(u==="openai"){const K=p.extractLatestToolResult(j);if(K){const k=ao(K.tool_call_id),se=k&&ro(k.gwId);if(se)return Ts(d,se,K.content,j?.model,E)}const W=p.extractTools(j);if((W.length||x)&&j?.stream===!0){const k=$||Go(j?.model,P),se=R?$t.begin({...R,agentId:k}):null;return Ss(t,d,{kind:u,adapter:p,agent:k,run:T,owner:x,linkTurn:se},j,V,P,U,W,B,E)}}const{messages:z,system:X}=p.toTurn(j),ee=$||Go(j?.model,P),te=R?$t.begin({...R,agentId:ee}):null,ye=j?.stream===!0,Y=yt(u,j?.model||ee),ge=ze(P.bridge.token),I=new AbortController;d.on("close",()=>{d.writableFinished||I.abort()});const{agentModel:q}=Bt(j?.model,P),ue={bridgeUrl:await je(P),agent:ee,token:ge,messages:z,system:X,signal:I.signal,options:Bo(P,{...q?{model:q}:{},...T||{}})};if(!ye)try{let K="";const W=Ct(),k=E?E.clock():0;await to(ue,Ae=>{K+=Ae},null,Ae=>W.add(Ae)),E&&E.lap("upstream",k);const se=E?E.clock():0,Fe=Y.full(sr(K,V),W.value);return E&&E.lap("restore",se),d.writeHead(200,{"content-type":Y.contentType}),d.end(Fe),te?.add(W.value),te?.end("ok"),E?.commit()}catch(K){return te?.end(I.signal.aborted?"aborted":"error",{code:"bridge_error"}),E?.commit(),a(d,502,{error:{message:`bridge backend failed: ${K.message}`,type:"bridge_error"}})}d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(Y.sseHead());const n=Qt(V),o=E?E.clock():0;let f=o;const i=Ct();let Z="",F=!1;try{let K=!0;await to(ue,k=>{E&&K&&(E.lap("upstream",o),f=E.clock(),K=!1);const se=n.push(k);se&&(Z+=se,d.write(Y.sseDelta(se)))},Y.sseActivity?k=>{try{d.write(Y.sseActivity(ar(k,V)))}catch{}}:null,k=>i.add(k));const W=n.flush();W&&(Z+=W,d.write(Y.sseDelta(W))),d.write(Y.sseTail(i.value))}catch(K){F=!0,d.write(`data: ${JSON.stringify({error:{message:K.message,type:"bridge_error"}})}
18
+ `)},15e3);oe.unref?.();let ye;try{ye=await z.inbox.ask(V,{partner:z.partner,device:z.device,conversation:z.conversation,signal:X.signal})}finally{clearInterval(oe),t.off("close",te)}if(X.signal.aborted||t.writableEnded){Dt(d);return}try{await no(d,JSON.stringify(ye))}catch(Y){P.onError(Y);return}}}function Dt(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function Ts(t,d,{kind:u,adapter:p,agent:w,run:y=null,owner:$=null,linkTurn:B=null},E,T,_,R,j,V=null,P=null){const{messages:U,system:z}=p.toTurn(E),{agentModel:X}=Bt(E?.model,_),te=Bo(_,{...X?{model:X}:{},...y||{}}),oe=ze(_.bridge.token),ye=yt(u,E?.model||w),Y={tier:_.redaction.tier==="full"?"full":"basic",dictionary:ir(_.redaction,R),entities:[]},ge=await je(_),C=Ir({vault:T,redactOpts:Y,bridgeUrl:ge,token:oe,harness:V});$&&(C.ownerApprovals={...$,conversation:$.conversation||`partner.${$.device}.turn-${C.id}`,turnScoped:!$.conversation}),B&&(C.linkTurn=B,C.onEnd=()=>B.end("aborted")),T&&(C.redaction=_.redaction);let ee;try{ee=await Cr({bridgeUrl:ge,agent:w,token:oe,messages:U,system:z,specs:Lr(j),options:te,signal:void 0,approvals:!!$||Jr(j)})}catch(pe){return B?.end("error",{code:"bridge_error"}),Ge(C.id),P?.commit(),a(d,502,{error:{message:`bridge: ${pe.message}`,type:"bridge_error"}})}return C.reader=ee.body.getReader(),d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(ye.sseHead()),Vo(d,C,ye,P)}async function xs(t,d,u,p,w=null){ot(d.id),d.rounds=(d.rounds||0)+1;try{const $=w?w.clock():0;await no(d,u),w&&w.lap("redact",$)}catch($){return d.linkTurn?.end("error",{code:"tool_result"}),Ge(d.id),w?.commit(),a(t,502,{error:{message:`tool-result: ${$.message}`,type:"bridge_error"}})}const y=yt("openai",p||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(y.sseHead()),Vo(t,d,y,w)}function Ct(){let t=!1;const d={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const p of Object.keys(d))d[p]+=Math.max(0,Number(u?.[p])||0)},get value(){return t?d:null}}}async function _s(t,d,{kind:u,adapter:p,redactable:w,pathname:y,agentOverride:$,harness:B,trace:E,run:T=null,owner:_=null,link:R=null},j,V,P,U){if(!w)return E?.commit(),a(d,404,{error:`endpoint ${y} not supported by the bridge backend`});if(u==="openai"){const K=p.extractLatestToolResult(j);if(K){const k=ao(K.tool_call_id),ie=k&&ro(k.gwId);if(ie)return xs(d,ie,K.content,j?.model,E)}const W=p.extractTools(j);if((W.length||_)&&j?.stream===!0){const k=$||Go(j?.model,P),ie=R?$t.begin({...R,agentId:k}):null;return Ts(t,d,{kind:u,adapter:p,agent:k,run:T,owner:_,linkTurn:ie},j,V,P,U,W,B,E)}}const{messages:z,system:X}=p.toTurn(j),te=$||Go(j?.model,P),oe=R?$t.begin({...R,agentId:te}):null,ye=j?.stream===!0,Y=yt(u,j?.model||te),ge=ze(P.bridge.token),C=new AbortController;d.on("close",()=>{d.writableFinished||C.abort()});const{agentModel:ee}=Bt(j?.model,P),pe={bridgeUrl:await je(P),agent:te,token:ge,messages:z,system:X,signal:C.signal,options:Bo(P,{...ee?{model:ee}:{},...T||{}})};if(!ye)try{let K="";const W=Ct(),k=E?E.clock():0;await to(pe,Ae=>{K+=Ae},null,Ae=>W.add(Ae)),E&&E.lap("upstream",k);const ie=E?E.clock():0,Fe=Y.full(sr(K,V),W.value);return E&&E.lap("restore",ie),d.writeHead(200,{"content-type":Y.contentType}),d.end(Fe),oe?.add(W.value),oe?.end("ok"),E?.commit()}catch(K){return oe?.end(C.signal.aborted?"aborted":"error",{code:"bridge_error"}),E?.commit(),a(d,502,{error:{message:`bridge backend failed: ${K.message}`,type:"bridge_error"}})}d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(Y.sseHead());const n=Qt(V),o=E?E.clock():0;let f=o;const i=Ct();let Z="",F=!1;try{let K=!0;await to(pe,k=>{E&&K&&(E.lap("upstream",o),f=E.clock(),K=!1);const ie=n.push(k);ie&&(Z+=ie,d.write(Y.sseDelta(ie)))},Y.sseActivity?k=>{try{d.write(Y.sseActivity(ar(k,V)))}catch{}}:null,k=>i.add(k));const W=n.flush();W&&(Z+=W,d.write(Y.sseDelta(W))),d.write(Y.sseTail(i.value))}catch(K){F=!0,d.write(`data: ${JSON.stringify({error:{message:K.message,type:"bridge_error"}})}
19
19
 
20
- `)}E&&E.lap("stream",f),d.end(),te&&(te.add(i.value),te.end(I.signal.aborted?"aborted":F?"error":"ok",{code:"bridge_error"})),E?.commit(),V&&Z&&Kt(Z,P.redaction)}function _s(t,d,u=""){const p=String(t||"").replace(/\/+$/,""),w=String(d||"").split("/")[1];return w&&p.endsWith(`/${w}`)?p.slice(0,-(w.length+1))+d+u:p+d+u}const Os=9e4;function Es(t,d,u){if(d===u)return t;const p=d/u,w=new Float32Array(Math.floor(t.length/p));for(let y=0;y<w.length;y++){const $=y*p,B=Math.floor($),E=Math.min(t.length-1,B+1),T=$-B;w[y]=t[B]*(1-T)+t[E]*T}return w}const Fo=new WeakMap,Ps=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function Wo(t,d){const u=at(d)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?To(u):null}function It(t,{installing:d=!1}={}){return t.stt?.diarize===!1?"off":d&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ve(t,d,u,p,{method:w="GET",timeoutMs:y=8e3,pick:$=B=>B}={}){const B=await je(u);if(!B)return a(d,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const E=ze(u.bridge?.token),T=w!=="GET"&&w!=="DELETE";try{const x=T?(await S(t,u.maxBodyBytes)).toString("utf8"):"",R=await fetch(`${B}${p}`,{method:w,headers:{Accept:"application/json",...T?{"content-type":"application/json"}:{},...E?{Authorization:`Bearer ${E}`}:{}},...T?{body:x||"{}"}:{},signal:AbortSignal.timeout(y)}),j=await R.json().catch(()=>({}));return R.ok?a(d,200,$(j)):a(d,R.status,{error:{message:j?.error||`bridge ${R.status}`,type:"bridge_error"}})}catch(x){return a(d,502,{error:{message:`bridge unreachable: ${x.message}`,type:"bridge_unreachable"}})}}function Rt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Re(t,d){const u=new URLSearchParams;for(const y of t.searchParams.getAll("dir"))y&&u.append("dir",y);const p=t.searchParams.get("workdir")||String(d?.bridge?.workingDir||"").trim();p&&u.set("workdir",p);const w=u.toString();return w?`?${w}`:""}async function $s(t,d,{adapter:u,kind:p,pathname:w,search:y,base:$,destKey:B,destProtocol:E,harness:T,trace:x,link:R=null},j,V){let P;const U=x?x.clock():0,z=R?$t.begin(R):null;let X=!1;const ee=new AbortController;d.on("close",()=>{d.writableFinished||(X=!0,ee.abort())});const te=(I,q)=>{z&&(z.add(q),z.end(X?"aborted":I>=400?"error":"ok",{code:`http_${I}`}))};try{const I=ks(t.headers,$);B&&(E==="anthropic"?(I["x-api-key"]=B,delete I.authorization):I.authorization=`Bearer ${B}`);const q=mr(_s($,w,y)).toString();P=await fetch(q,{method:t.method,headers:I,body:["GET","HEAD"].includes(t.method)?void 0:j,signal:ee.signal})}catch(I){return X?(te(499),x?.commit()):(z?.end("error",{code:"upstream_unreachable"}),x?.commit(),a(d,502,{error:`upstream fetch failed: ${I.message}`}))}const ye=P.headers.get("content-type")||"",Y={};if(P.headers.forEach((I,q)=>{Jo.has(q.toLowerCase())||(Y[q]=I)}),ye.includes("text/event-stream")&&P.body){x&&x.lap("upstream",U);const I=x?x.clock():0;d.writeHead(P.status,Y);const q=z?xn():null,ue=q?P.body.pipeThrough(q.stream):P.body,n=p==="openai"?nr(ue,d,V,T):rr(ue,d,V);return Promise.resolve(n).catch(o=>{if(!X)throw o}).finally(()=>{x&&x.lap("stream",I),te(P.status,q?.usage()),x?.commit()})}let ge;try{ge=Buffer.from(await P.arrayBuffer())}catch(I){if(X)return te(499),x?.commit();throw I}if(x&&x.lap("upstream",U),z&&te(P.status,ye.includes("json")?_n(ge.toString("utf8")):null),V&&ye.includes("application/json"))try{const I=x?x.clock():0,q=u.restoreResponse(JSON.parse(ge.toString("utf8")),V,T);return x&&x.lap("restore",I),d.writeHead(P.status,{...Y,"content-type":"application/json"}),d.end(Buffer.from(JSON.stringify(q),"utf8")),x?.commit()}catch{}d.writeHead(P.status,Y),d.end(ge),x?.commit()}function As(t=Wt()){const d=br({first:async n=>{const o=Number(new URL(n).port),f=Hn.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=gr({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):wr(n),newId:()=>vr()}),p=qn({version:de}),w=ya({log:n=>console.log(` ${n}`)}),y=t.link?.enabled===!1?null:ea({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:f,body:i,device:Z})=>fetch(`http://127.0.0.1:${ue.address()?.port||t.port}${o}`,{method:n,body:i,headers:{...f,"x-chatpanel-token":Me()||_e(),"x-chatpanel-link-device":String(Z||"")}}),ownerIsPro:()=>Te(t.pro?.entitlementToken),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==D.activeModel()&&(go(t.stt.diarizeModel)?D.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${Oa}`));let $=null;const B=()=>{if(!$){const n=t.read||{};$=Zn({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return $};let E=null;const T=()=>(E||(E=Jn({wrap:(n,o,f,i)=>jn().wrap(n,o,f,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),E);let x={at:0,fn:()=>"unknown"},R=null;async function j(){if(Date.now()-x.at<1e4)return x.fn;let n=new Map;try{const i=await P().health();for(const[Z,F]of Object.entries(i)){const K=(t.destinations||[]).filter(W=>W?.service===Z).flatMap(W=>[W.id,...W.models||[]]);for(const W of[Z,...K])n.set(W,F)}}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 P().contextWindow(f.get(i)||i)}catch{return null}},o.card=i=>{try{return P().modelCard(f.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),x={at:Date.now(),fn:o},x.fn}let V=null;const P=()=>(V||(V=Gn({cfg:t,bridgeHealth:async()=>{const n=await je(t);if(!n)return null;const o=ze(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{be(t,le())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:He.join(He.dirname(le()),"runtime"),workers:()=>{const n=E?.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)})),V),U=Number(t.runtime?.idleMinutes),z=Vn({warmMs:(Number.isFinite(U)&&U>=0?U:10)*6e4,log:n=>console.log(n)}),X=Un({cfg:t,wake:(n,o)=>P().wake(n,o),embedded:z});let ee=null;const te=()=>(ee||(ee=Xn({store:Yn({log:n=>console.warn(`[kb] ${n}`)}),extract:T,embedded:z,cfg:t,rerank:async(n,o)=>{const f=await X.call("rerank",{query:n,documents:o.map(Z=>String(Z).slice(0,2e3))});if(f.status!==200)return null;const i=new Array(o.length).fill(0);for(const Z of f.body.results||[])i[Z.index]=Z.relevance_score;return i},read:()=>B(),completer:n=>async(o,{maxTokens:f=160}={})=>{const i=new AbortController,Z=setTimeout(()=>i.abort(),3e4);try{const F=Me()||_e(),K=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...F?{Authorization:`Bearer ${F}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:n,messages:[{role:"user",content:o}],stream:!1,max_tokens:f,temperature:0})}),W=await K.json().catch(()=>({}));return K.ok?String(W?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(Z)}},log:n=>console.warn(n)})),ee),ye=()=>{t.search?.searxng?.url&&P().wake("searxng").catch(()=>{})};let Y=null;const ge=()=>{if(!Y){const n=t.search||{},o=n.searxng?.url?ba({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;Y=fa({reader:B(),searxng:o,engines:()=>va(t),wakeSearxng:()=>P().wake("searxng"),defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await Ze([ht(()=>i,Z=>{i=Z})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return Y};hr(t.allowedExtensionIds||[]);const I=[],q=n=>{I.push(n),I.length>50&&I.shift()},ue=er(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1");let i=f.pathname;if(!ct(n.headers.host))return a(o,403,{error:"loopback only"});if(!ms(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(ct(t.host)&&oa(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&&ps(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return H(n)?a(o,200,{token:_e()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!H(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=yr();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=fr(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Le(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Le(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:l}=await oo(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:Me()||_e(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&n.method==="POST"){const e=Le(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(Yt(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 oo(t);return a(o,200,{ok:!0,status:r,token:Me()||_e(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Le(n);return a(o,200,{ok:!0,trust:e,paired:Yt(e),version:de})}if(i==="/audit"&&n.method==="GET")return H(n)?a(o,200,Sr(t,{version:de,startedAt:jo,managed:Je(),certificates:{...xr(),wanted:Xt(t)},linkPartners:y?y.status().devices.filter(e=>e.kind==="partner"):[],confined:wt({stateDir:He.dirname(le())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!H(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await pn(de,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:de,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:fn()})}if(i==="/update"&&n.method==="POST"){const e=yn(de);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!H(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"&&!H(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"&&!H(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"&&!H(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"))&&!H(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!H(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!H(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!H(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!H(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${de} is running.
20
+ `)}E&&E.lap("stream",f),d.end(),oe&&(oe.add(i.value),oe.end(C.signal.aborted?"aborted":F?"error":"ok",{code:"bridge_error"})),E?.commit(),V&&Z&&Kt(Z,P.redaction)}function Os(t,d,u=""){const p=String(t||"").replace(/\/+$/,""),w=String(d||"").split("/")[1];return w&&p.endsWith(`/${w}`)?p.slice(0,-(w.length+1))+d+u:p+d+u}const Es=9e4;function Ps(t,d,u){if(d===u)return t;const p=d/u,w=new Float32Array(Math.floor(t.length/p));for(let y=0;y<w.length;y++){const $=y*p,B=Math.floor($),E=Math.min(t.length-1,B+1),T=$-B;w[y]=t[B]*(1-T)+t[E]*T}return w}const Fo=new WeakMap,$s=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function Wo(t,d){const u=at(d)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?To(u):null}function It(t,{installing:d=!1}={}){return t.stt?.diarize===!1?"off":d&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ve(t,d,u,p,{method:w="GET",timeoutMs:y=8e3,pick:$=B=>B}={}){const B=await je(u);if(!B)return a(d,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const E=ze(u.bridge?.token),T=w!=="GET"&&w!=="DELETE";try{const _=T?(await S(t,u.maxBodyBytes)).toString("utf8"):"",R=await fetch(`${B}${p}`,{method:w,headers:{Accept:"application/json",...T?{"content-type":"application/json"}:{},...E?{Authorization:`Bearer ${E}`}:{}},...T?{body:_||"{}"}:{},signal:AbortSignal.timeout(y)}),j=await R.json().catch(()=>({}));return R.ok?a(d,200,$(j)):a(d,R.status,{error:{message:j?.error||`bridge ${R.status}`,type:"bridge_error"}})}catch(_){return a(d,502,{error:{message:`bridge unreachable: ${_.message}`,type:"bridge_unreachable"}})}}function Rt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Re(t,d){const u=new URLSearchParams;for(const y of t.searchParams.getAll("dir"))y&&u.append("dir",y);const p=t.searchParams.get("workdir")||String(d?.bridge?.workingDir||"").trim();p&&u.set("workdir",p);const w=u.toString();return w?`?${w}`:""}async function As(t,d,{adapter:u,kind:p,pathname:w,search:y,base:$,destKey:B,destProtocol:E,harness:T,trace:_,link:R=null},j,V){let P;const U=_?_.clock():0,z=R?$t.begin(R):null;let X=!1;const te=new AbortController;d.on("close",()=>{d.writableFinished||(X=!0,te.abort())});const oe=(C,ee)=>{z&&(z.add(ee),z.end(X?"aborted":C>=400?"error":"ok",{code:`http_${C}`}))};try{const C=Ss(t.headers,$);B&&(E==="anthropic"?(C["x-api-key"]=B,delete C.authorization):C.authorization=`Bearer ${B}`);const ee=mr(Os($,w,y)).toString();P=await fetch(ee,{method:t.method,headers:C,body:["GET","HEAD"].includes(t.method)?void 0:j,signal:te.signal})}catch(C){return X?(oe(499),_?.commit()):(z?.end("error",{code:"upstream_unreachable"}),_?.commit(),a(d,502,{error:`upstream fetch failed: ${C.message}`}))}const ye=P.headers.get("content-type")||"",Y={};if(P.headers.forEach((C,ee)=>{Jo.has(ee.toLowerCase())||(Y[ee]=C)}),ye.includes("text/event-stream")&&P.body){_&&_.lap("upstream",U);const C=_?_.clock():0;d.writeHead(P.status,Y);const ee=z?xn():null,pe=ee?P.body.pipeThrough(ee.stream):P.body,n=p==="openai"?nr(pe,d,V,T):rr(pe,d,V);return Promise.resolve(n).catch(o=>{if(!X)throw o}).finally(()=>{_&&_.lap("stream",C),oe(P.status,ee?.usage()),_?.commit()})}let ge;try{ge=Buffer.from(await P.arrayBuffer())}catch(C){if(X)return oe(499),_?.commit();throw C}if(_&&_.lap("upstream",U),z&&oe(P.status,ye.includes("json")?_n(ge.toString("utf8")):null),V&&ye.includes("application/json"))try{const C=_?_.clock():0,ee=u.restoreResponse(JSON.parse(ge.toString("utf8")),V,T);return _&&_.lap("restore",C),d.writeHead(P.status,{...Y,"content-type":"application/json"}),d.end(Buffer.from(JSON.stringify(ee),"utf8")),_?.commit()}catch{}d.writeHead(P.status,Y),d.end(ge),_?.commit()}function Ns(t=Wt()){const d=br({first:async n=>{const o=Number(new URL(n).port),f=Hn.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=gr({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):wr(n),newId:()=>vr()}),p=qn({version:ue}),w=ya({log:n=>console.log(` ${n}`)}),y=t.link?.enabled===!1?null:ea({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:f,body:i,device:Z})=>fetch(`http://127.0.0.1:${pe.address()?.port||t.port}${o}`,{method:n,body:i,headers:{...f,"x-chatpanel-token":Me()||_e(),"x-chatpanel-link-device":String(Z||"")}}),ownerIsPro:()=>Te(t.pro?.entitlementToken),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==M.activeModel()&&(go(t.stt.diarizeModel)?M.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${Oa}`));let $=null;const B=()=>{if(!$){const n=t.read||{};$=Zn({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return $};let E=null;const T=()=>(E||(E=Jn({wrap:(n,o,f,i)=>jn().wrap(n,o,f,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),E);let _={at:0,fn:()=>"unknown"},R=null;async function j(){if(Date.now()-_.at<1e4)return _.fn;let n=new Map;try{const i=await P().health();for(const[Z,F]of Object.entries(i)){const K=(t.destinations||[]).filter(W=>W?.service===Z).flatMap(W=>[W.id,...W.models||[]]);for(const W of[Z,...K])n.set(W,F)}}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 P().contextWindow(f.get(i)||i)}catch{return null}},o.card=i=>{try{return P().modelCard(f.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),_={at:Date.now(),fn:o},_.fn}let V=null;const P=()=>(V||(V=Gn({cfg:t,bridgeHealth:async()=>{const n=await je(t);if(!n)return null;const o=ze(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{be(t,ce())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:He.join(He.dirname(ce()),"runtime"),workers:()=>{const n=E?.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)})),V),U=Number(t.runtime?.idleMinutes),z=Vn({warmMs:(Number.isFinite(U)&&U>=0?U:10)*6e4,log:n=>console.log(n)}),X=Un({cfg:t,wake:(n,o)=>P().wake(n,o),embedded:z});let te=null;const oe=()=>(te||(te=Xn({store:Yn({log:n=>console.warn(`[kb] ${n}`)}),extract:T,embedded:z,cfg:t,rerank:async(n,o)=>{const f=await X.call("rerank",{query:n,documents:o.map(Z=>String(Z).slice(0,2e3))});if(f.status!==200)return null;const i=new Array(o.length).fill(0);for(const Z of f.body.results||[])i[Z.index]=Z.relevance_score;return i},read:()=>B(),completer:n=>async(o,{maxTokens:f=160}={})=>{const i=new AbortController,Z=setTimeout(()=>i.abort(),3e4);try{const F=Me()||_e(),K=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...F?{Authorization:`Bearer ${F}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:n,messages:[{role:"user",content:o}],stream:!1,max_tokens:f,temperature:0})}),W=await K.json().catch(()=>({}));return K.ok?String(W?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(Z)}},log:n=>console.warn(n)})),te),ye=()=>{t.search?.searxng?.url&&P().wake("searxng").catch(()=>{})};let Y=null;const ge=()=>{if(!Y){const n=t.search||{},o=n.searxng?.url?ba({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;Y=fa({reader:B(),searxng:o,engines:()=>va(t),wakeSearxng:()=>P().wake("searxng"),defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await Ze([ht(()=>i,Z=>{i=Z})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return Y};hr(t.allowedExtensionIds||[]);const C=[],ee=n=>{C.push(n),C.length>50&&C.shift()},pe=er(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1");let i=f.pathname;if(!ct(n.headers.host))return a(o,403,{error:"loopback only"});if(!ps(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(ct(t.host)&&oa(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&&hs(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return H(n)?a(o,200,{token:_e()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!H(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=yr();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=fr(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Le(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Le(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:l}=await oo(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:Me()||_e(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&n.method==="POST"){const e=Le(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(Yt(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 oo(t);return a(o,200,{ok:!0,status:r,token:Me()||_e(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Le(n);return a(o,200,{ok:!0,trust:e,paired:Yt(e),version:ue})}if(i==="/audit"&&n.method==="GET")return H(n)?a(o,200,Sr(t,{version:ue,startedAt:jo,managed:Je(),certificates:{...xr(),wanted:Xt(t)},linkPartners:y?y.status().devices.filter(e=>e.kind==="partner"):[],confined:wt({stateDir:He.dirname(ce())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!H(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await pn(ue,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:ue,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:fn()})}if(i==="/update"&&n.method==="POST"){const e=yn(ue);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!H(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"&&!H(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"&&!H(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"&&!H(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"))&&!H(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!H(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!H(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!H(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!H(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${ue} is running.
21
21
 
22
22
  This address is for ChatPanel's apps, not a web page — there is nothing to open here.
23
23
  Use ChatPanel itself (the browser extension's Settings, or the desktop app).
24
24
  In a terminal, \`chatpanel-gateway --status\` shows what is running.
25
- `);if(n.method==="GET"&&i==="/health"){const e=A.health(),r=C.health();return a(o,200,{ok:!0,version:de,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...Je()?{managed:Je()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},install:gn(),confined:wt({stateDir:He.dirname(le())}),...bn({release:St.release()})?{appleHelper:!!bt()}:{},...Ve?{bridge:Ve.status()}:ut?{bridge:ut}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||De,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||Eo,voice:t.tts?.voice||Oe,runtime:r.runtime,dtype:r.dtype},events:Q?{count:Q.count(),hosts:Q.hosts().length}:null,browser:p.health()})}if(i==="/status"&&n.method==="GET"){or(t);const e=await Te(t.pro?.entitlementToken),r=await Uo(t);return a(o,200,{ok:!0,version:de,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Je()?{managed:Je()}:{},...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:Mt(t),pro:{unlocked:e},usage:Ka(t),uptimeSeconds:Math.floor((Date.now()-jo)/1e3),update:hn(de)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=J.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:r})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?a(o,200,{ok:!0,revision:ce.revision,stamps:ce.stamps()}):a(o,200,{ok:!0,revision:ce.revision,sections:ce.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=ce.put(e.sections||{},{by:e.by||""});return r.applied.length&&Co(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?ce.remove(e):!1;return r&&Co([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)}
25
+ `);if(n.method==="GET"&&i==="/health"){const e=A.health(),r=D.health();return a(o,200,{ok:!0,version:ue,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...Je()?{managed:Je()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},install:gn(),confined:wt({stateDir:He.dirname(ce())}),...bn({release:St.release()})?{appleHelper:!!bt()}:{},...Ve?{bridge:Ve.status()}:ut?{bridge:ut}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||De,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||Eo,voice:t.tts?.voice||Oe,runtime:r.runtime,dtype:r.dtype},events:Q?{count:Q.count(),hosts:Q.hosts().length}:null,browser:p.health()})}if(i==="/status"&&n.method==="GET"){or(t);const e=await Te(t.pro?.entitlementToken),r=await Uo(t);return a(o,200,{ok:!0,version:ue,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Je()?{managed:Je()}:{},...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:Mt(t),pro:{unlocked:e},usage:Qa(t),uptimeSeconds:Math.floor((Date.now()-jo)/1e3),update:hn(ue)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=J.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:r})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?a(o,200,{ok:!0,revision:me.revision,stamps:me.stamps()}):a(o,200,{ok:!0,revision:me.revision,sections:me.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=me.put(e.sections||{},{by:e.by||""});return r.applied.length&&Co(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?me.remove(e):!1;return r&&Co([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)}
26
26
 
27
- `);e({type:"hello",revision:ce.revision,stamps:ce.stamps()});const r=l=>e({type:"changed",...l});At.add(r);const s=setInterval(()=>{try{o.write(`: keep-alive
27
+ `);e({type:"hello",revision:me.revision,stamps:me.stamps()});const r=l=>e({type:"changed",...l});At.add(r);const s=setInterval(()=>{try{o.write(`: keep-alive
28
28
 
29
- `)}catch{}},25e3);o.on("close",()=>{At.delete(r),clearInterval(s)});return}if(i==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:he.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:he.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:he.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]||"",m=()=>a(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(c){const h=he.get(r);if(!h)return m();const g=h.jobs.find(b=>b.id===l);if(!g)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const v={cfg:t,prefsStore:ce,scorecards:Ce,engines:Ie,engineAt:d.engineAt};if(c==="/applications"&&n.method==="GET"){const b=await dn(g,{...v,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:g,...b})}if(c==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(g.status))return a(o,400,{error:{message:`job ${l} is ${g.status}; only an open job is recruited`,type:"project_error"}});try{const b=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},O=String(b.by||"evaluator").slice(0,80),_=await cn(g,{...v,record:h,reach:b.reach||"any",chatModel:b.chatModel||null,evaluation:b.evaluation||null,text:b.text??null,by:O});let M=null;for(const me of _.events)me.type==="job.updated"?M=he.updateJob(r,l,me.job,{by:me.by||O}):M=he.append(r,[me]);return a(o,200,{ok:!0,project:M,decision:_.decision,applications:_.applications,evaluation:_.evaluation})}catch(b){return a(o,400,{error:{message:`recruit: ${b.message}`,type:"project_error"}})}}return a(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!s&&n.method==="GET"){const h=he.get(r,{events:f.searchParams.get("events")==="1"});return h?a(o,200,{ok:!0,project:h}):m()}if(!s&&n.method==="DELETE")return a(o,200,{ok:!0,removed:he.remove(r)});if(n.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const h=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},g=String(h.by||"person").slice(0,80),v=s==="/events"?he.append(r,h.events||[]):l?he.updateJob(r,l,h.patch||h,{by:g}):he.postJob(r,h.job||h,{by:g});return a(o,200,{ok:!0,project:v})}catch(h){return a(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(s==="/events"&&n.method==="GET"){if(!he.get(r))return m();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=O=>o.write(`data: ${JSON.stringify(O)}
29
+ `)}catch{}},25e3);o.on("close",()=>{At.delete(r),clearInterval(s)});return}if(i==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:he.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:he.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:he.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]||"",m=()=>a(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(c){const h=he.get(r);if(!h)return m();const g=h.jobs.find(v=>v.id===l);if(!g)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const b={cfg:t,prefsStore:me,scorecards:Ce,engines:Ie,engineAt:d.engineAt};if(c==="/applications"&&n.method==="GET"){const v=await dn(g,{...b,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:g,...v})}if(c==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(g.status))return a(o,400,{error:{message:`job ${l} is ${g.status}; only an open job is recruited`,type:"project_error"}});try{const v=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},O=String(v.by||"evaluator").slice(0,80),x=await cn(g,{...b,record:h,reach:v.reach||"any",chatModel:v.chatModel||null,evaluation:v.evaluation||null,text:v.text??null,by:O});let I=null;for(const q of x.events)q.type==="job.updated"?I=he.updateJob(r,l,q.job,{by:q.by||O}):I=he.append(r,[q]);return a(o,200,{ok:!0,project:I,decision:x.decision,applications:x.applications,evaluation:x.evaluation})}catch(v){return a(o,400,{error:{message:`recruit: ${v.message}`,type:"project_error"}})}}return a(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!s&&n.method==="GET"){const h=he.get(r,{events:f.searchParams.get("events")==="1"});return h?a(o,200,{ok:!0,project:h}):m()}if(!s&&n.method==="DELETE")return a(o,200,{ok:!0,removed:he.remove(r)});if(n.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const h=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},g=String(h.by||"person").slice(0,80),b=s==="/events"?he.append(r,h.events||[]):l?he.updateJob(r,l,h.patch||h,{by:g}):he.postJob(r,h.job||h,{by:g});return a(o,200,{ok:!0,project:b})}catch(h){return a(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(s==="/events"&&n.method==="GET"){if(!he.get(r))return m();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=O=>o.write(`data: ${JSON.stringify(O)}
30
30
 
31
- `);let g=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:he.get(r),after:g}});const v=he.watch(r,O=>{O.seq>g&&(g=O.seq,h(O))});for(const O of he.eventsSince(r,g))g=O.seq,h(O);const b=setInterval(()=>{try{o.write(`: keep
31
+ `);let g=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:he.get(r),after:g}});const b=he.watch(r,O=>{O.seq>g&&(g=O.seq,h(O))});for(const O of he.eventsSince(r,g))g=O.seq,h(O);const v=setInterval(()=>{try{o.write(`: keep
32
32
 
33
- `)}catch{}},25e3);n.on("close",()=>{clearInterval(b),v()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:Ce.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 Ce.get(r)});if(n.method==="POST")try{const s=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},l=await Ce.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 Ie.fromRating(Ce.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,Rn(t,{version:de,reader:$,searcher:Y,extract:T(),proxy:X}));if(i==="/v1/fusions"&&n.method==="GET"){const e={active:L.health().model||t.ner?.model||null,companions:L.companions()};let r=null;try{r=await P().status()}catch{r=null}return a(o,200,An({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(Wn.map(r=>{const s=_t(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:Fn[r],threads:z.threads,...s.kind==="embedded"?z.health(r,s.model):{}}]}));return a(o,200,{...await P().status(),inProcess:e})}if(i==="/v1/runtime/plan"&&n.method==="GET"){const e=new URL(n.url,"http://x").searchParams,r=await P().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(!H(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=P(),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/embeddings"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"embed: body must be JSON",type:"invalid_request"}})}const r=await X.call("embed",e);return a(o,r.status,r.body)}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 X.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 Ln(e,{ensure:()=>rt(t),model:L.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/context"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,Math.max(t.maxBodyBytes,Math.ceil(Tt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract/context: body must be JSON",type:"invalid_request"}})}const r=await Qn(e,{service:T()});return a(o,r.status,r.body)}if((i==="/v1/files/write"||i==="/v1/files/exists")&&n.method==="POST"){if(!H(n)||nt(n.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await S(n,Math.max(t.maxBodyBytes,ha*6+4096))).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const r=await ma(i.slice(10),e);return a(o,r.status,r.body)}if(i==="/v1/import/apple-notes"&&n.method==="POST"){if(!H(n)||nt(n.headers))return a(o,403,{error:{message:"apple-notes: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"apple-notes: body must be JSON",type:"invalid_request"}})}const r=await pa(e);return a(o,r.status,r.body)}if(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,Math.max(t.maxBodyBytes,Math.ceil(Tt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Kn(e,{service:T()});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 B().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"}})}ye();const r=await ge().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)):wa.aliasRead;ye();const s=await ge().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?ga(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 B().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(ka(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:Ie.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 Ie.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||ys(r);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const c=await Ie.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)}
33
+ `)}catch{}},25e3);n.on("close",()=>{clearInterval(v),b()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:Ce.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 Ce.get(r)});if(n.method==="POST")try{const s=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},l=await Ce.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 Ie.fromRating(Ce.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,Rn(t,{version:ue,reader:$,searcher:Y,extract:T(),proxy:X}));if(i==="/v1/fusions"&&n.method==="GET"){const e={active:L.health().model||t.ner?.model||null,companions:L.companions()};let r=null;try{r=await P().status()}catch{r=null}return a(o,200,An({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(Wn.map(r=>{const s=_t(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:Fn[r],threads:z.threads,...s.kind==="embedded"?z.health(r,s.model):{}}]}));return a(o,200,{...await P().status(),inProcess:e})}if(i==="/v1/runtime/plan"&&n.method==="GET"){const e=new URL(n.url,"http://x").searchParams,r=await P().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(!H(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=P(),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/embeddings"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"embed: body must be JSON",type:"invalid_request"}})}const r=await X.call("embed",e);return a(o,r.status,r.body)}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 X.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 Ln(e,{ensure:()=>rt(t),model:L.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/context"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,Math.max(t.maxBodyBytes,Math.ceil(Tt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract/context: body must be JSON",type:"invalid_request"}})}const r=await Qn(e,{service:T()});return a(o,r.status,r.body)}if((i==="/v1/files/write"||i==="/v1/files/exists")&&n.method==="POST"){if(!H(n)||nt(n.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await S(n,Math.max(t.maxBodyBytes,ha*6+4096))).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const r=await ma(i.slice(10),e);return a(o,r.status,r.body)}if(i==="/v1/import/apple-notes"&&n.method==="POST"){if(!H(n)||nt(n.headers))return a(o,403,{error:{message:"apple-notes: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"apple-notes: body must be JSON",type:"invalid_request"}})}const r=await pa(e);return a(o,r.status,r.body)}if(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,Math.max(t.maxBodyBytes,Math.ceil(Tt*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Kn(e,{service:T()});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 B().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"}})}ye();const r=await ge().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)):wa.aliasRead;ye();const s=await ge().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?ga(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 B().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(ka(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:Ie.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 Ie.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||fs(r);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const c=await Ie.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)}
34
34
 
35
- `)}catch{}};e({type:"hello",at:Date.now()});const r=oe.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
35
+ `)}catch{}};e({type:"hello",at:Date.now()});const r=re.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
36
36
 
37
- `)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(i==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:oe.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:oe.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=oe.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 oe.stop(r),a(o,200,{ok:!0,removed:oe.remove(r)});if(s==="/stop"&&n.method==="POST"){const l=oe.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:oe.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"?oe.handoff(r,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):oe.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:oe.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),m=s==="/answer"?oe.answer(r,{threadId:l.threadId,text:l.text,by:c}):s==="/decide"?oe.decide(r,{postId:l.postId,status:l.status,by:c}):oe.post(r,{threadId:l.threadId,text:l.text,by:c,kind:l.kind,replyTo:l.replyTo});return a(o,200,{ok:!0,run:m})}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:oe.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(!oe.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=v=>o.write(`data: ${JSON.stringify(v)}
37
+ `)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(i==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:re.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:re.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=re.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 re.stop(r),a(o,200,{ok:!0,removed:re.remove(r)});if(s==="/stop"&&n.method==="POST"){const l=re.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:re.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"?re.handoff(r,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):re.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:re.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),m=s==="/answer"?re.answer(r,{threadId:l.threadId,text:l.text,by:c}):s==="/decide"?re.decide(r,{postId:l.postId,status:l.status,by:c}):re.post(r,{threadId:l.threadId,text:l.text,by:c,kind:l.kind,replyTo:l.replyTo});return a(o,200,{ok:!0,run:m})}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:re.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(!re.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=b=>o.write(`data: ${JSON.stringify(b)}
38
38
 
39
- `),c=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let m=Number.isFinite(c)?c:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:oe.get(r),after:m}});const h=oe.watch(r,v=>{v.seq==null?l(v):v.seq>m&&(m=v.seq,l(v))});for(const v of oe.eventsSince(r,m))m=v.seq,l(v);const g=setInterval(()=>{try{o.write(`: keep-alive
39
+ `),c=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let m=Number.isFinite(c)?c:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:re.get(r),after:m}});const h=re.watch(r,b=>{b.seq==null?l(b):b.seq>m&&(m=b.seq,l(b))});for(const b of re.eventsSince(r,m))m=b.seq,l(b);const g=setInterval(()=>{try{o.write(`: keep-alive
40
40
 
41
- `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(g)});return}}}if(i==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:fe.size,memories:fe.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=fe.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:fe.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=fe.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:fe.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}=fe.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:fe.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=fe.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:fe.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:fe.clear(),size:fe.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=J.clear();return a(o,200,{ok:!0,dropped:e,size:J.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=J.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:J.size,newest:J.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(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=as(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),m=await ss(s,g=>J.search(g,{limit:c,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?m:[...m.filter(g=>g.type==="brief"),...m.filter(g=>g.type!=="brief")];return a(o,200,{ok:!0,size:J.size,newest:J.newest,queries:s,results:h})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(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&&!H(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(v,{maxTokens:b=220}={})=>{const O=new AbortController,_=setTimeout(()=>O.abort(),3e4);try{const M=Me()||_e(),me=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:O.signal,headers:{"content-type":"application/json",...M?{Authorization:`Bearer ${M}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:v}],stream:!1,max_tokens:b,temperature:.2})}),we=await me.json().catch(()=>({}));return me.ok?String(we?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(_)}}:null,m=ce.get("identity")?.identity?.value||{},h=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,g=await on(r,{store:J,memories:fe.list(),complete:c,previous:h,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,rn(r,g,{size:J.size,newest:J.newest}))}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(n.method==="POST"||n.method==="PUT")try{const s=(await S(n,Math.max(t.maxBodyBytes,Math.ceil(Tt*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const r=await te().handle({method:n.method,pathname:i,query:f.searchParams,body:e,admin:H(n),agent:String(n.headers["x-chatpanel-agent"]||"")});return r.text!=null?(o.writeHead(r.status,{"content-type":r.contentType||"text/plain; charset=utf-8"}),o.end(r.text)):a(o,r.status,r.body)}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:J.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:J.size,newest:J.newest,bytes:J.bytes,lossless:J.lossless?{records:J.lossless.size,newest:J.lossless.newest}:null});if(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:J.size,bytes:J.bytes,newest:J.newest}},access:Nt.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=Nt.push(Mo({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=J.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await S(n,Math.max(t.maxBodyBytes||0,vs))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),c=[];let m=0,h={},g=[],v=[];const b={upserts:[],removes:[]},O=_=>{if(!_||_.deletedAt){_?.id&&b.removes.push(_.id);return}try{const M=ho(_);M&&b.upserts.push(M)}catch{}};if(Array.isArray(r.records)){const _=e.write(r.records,{host:s,at:l,merge:r.merge===!0});c.push(..._.written),h=_.revs,g=_.conflicts,v=_.merged;for(const M of _.written)O(e.get(M))}if(Array.isArray(r.entries)){const _=ft(),M=_?Dn((re,Se)=>Bn(_,{salt:re,iterations:Se})):null,me=async re=>{if(!M||!re.blob)return null;const Se=await M(re.blob),G=re.blob.compression&&re.blob.compression!=="none"?Cn(In,re.blob.compression):null;return Mn(re.blob,Se,{codec:G})},we=await e.upsertEntries(r.entries,{open:me});c.push(...we.written),m+=we.sealed;for(const re of we.written)O(e.get(re))}return(b.upserts.length||b.removes.length)&&J.bulk(b),c.length&&Ue({ids:c}),a(o,200,{ok:!0,written:c.length,ids:c,revs:h,conflicts:g,merged:v,sealed:m,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==="DELETE"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(f.searchParams.get(m)||""),r=f.searchParams.get("host"),s=e("all");if((r===null||r==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(r!==null&&r.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:r;if(!e("force")){const m=Q.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:r},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${r}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const c=Q.deleteOf(l);for(const m of Ee)try{m.write(`event: deleted
41
+ `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(g)});return}}}if(i==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:fe.size,memories:fe.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=fe.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:fe.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=fe.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:fe.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}=fe.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:fe.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=fe.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:fe.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:fe.clear(),size:fe.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=J.clear();return a(o,200,{ok:!0,dropped:e,size:J.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=J.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:J.size,newest:J.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(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=ss(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),m=await is(s,g=>J.search(g,{limit:c,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?m:[...m.filter(g=>g.type==="brief"),...m.filter(g=>g.type!=="brief")];return a(o,200,{ok:!0,size:J.size,newest:J.newest,queries:s,results:h})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(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&&!H(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(b,{maxTokens:v=220}={})=>{const O=new AbortController,x=setTimeout(()=>O.abort(),3e4);try{const I=Me()||_e(),q=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:O.signal,headers:{"content-type":"application/json",...I?{Authorization:`Bearer ${I}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:b}],stream:!1,max_tokens:v,temperature:.2})}),we=await q.json().catch(()=>({}));return q.ok?String(we?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(x)}}:null,m=me.get("identity")?.identity?.value||{},h=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,g=await on(r,{store:J,memories:fe.list(),complete:c,previous:h,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,rn(r,g,{size:J.size,newest:J.newest}))}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(n.method==="POST"||n.method==="PUT")try{const s=(await S(n,Math.max(t.maxBodyBytes,Math.ceil(Tt*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const r=await oe().handle({method:n.method,pathname:i,query:f.searchParams,body:e,admin:H(n),agent:String(n.headers["x-chatpanel-agent"]||"")});return r.text!=null?(o.writeHead(r.status,{"content-type":r.contentType||"text/plain; charset=utf-8"}),o.end(r.text)):a(o,r.status,r.body)}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:J.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:J.size,newest:J.newest,bytes:J.bytes,lossless:J.lossless?{records:J.lossless.size,newest:J.lossless.newest}:null});if(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:J.size,bytes:J.bytes,newest:J.newest}},access:Nt.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=Nt.push(Mo({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=J.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await S(n,Math.max(t.maxBodyBytes||0,ks))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),c=[];let m=0,h={},g=[],b=[];const v={upserts:[],removes:[]},O=x=>{if(!x||x.deletedAt){x?.id&&v.removes.push(x.id);return}try{const I=ho(x);I&&v.upserts.push(I)}catch{}};if(Array.isArray(r.records)){const x=e.write(r.records,{host:s,at:l,merge:r.merge===!0});c.push(...x.written),h=x.revs,g=x.conflicts,b=x.merged;for(const I of x.written)O(e.get(I))}if(Array.isArray(r.entries)){const x=ft(),I=x?Dn((ne,Se)=>Bn(x,{salt:ne,iterations:Se})):null,q=async ne=>{if(!I||!ne.blob)return null;const Se=await I(ne.blob),G=ne.blob.compression&&ne.blob.compression!=="none"?Cn(In,ne.blob.compression):null;return Mn(ne.blob,Se,{codec:G})},we=await e.upsertEntries(r.entries,{open:q});c.push(...we.written),m+=we.sealed;for(const ne of we.written)O(e.get(ne))}return(v.upserts.length||v.removes.length)&&J.bulk(v),c.length&&Ue({ids:c}),a(o,200,{ok:!0,written:c.length,ids:c,revs:h,conflicts:g,merged:b,sealed:m,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==="DELETE"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(f.searchParams.get(m)||""),r=f.searchParams.get("host"),s=e("all");if((r===null||r==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(r!==null&&r.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:r;if(!e("force")){const m=Q.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:r},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${r}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const c=Q.deleteOf(l);for(const m of Ee)try{m.write(`event: deleted
42
42
  data: ${JSON.stringify({...s?{all:!0}:{host:r},deleted:c})}
43
43
 
44
44
  `)}catch{}return a(o,200,{ok:!0,deleted:c,...s?{all:!0}:{host:r},cursor:Q.cursor()})}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=m=>(typeof m?.host=="string"&&m.host?m.host:$n(m?.source))===mo,l=r.filter(s).map(m=>({id:m?.id??null,code:"RESERVED_HOST",message:`host "${mo}" is this gateway's own log`})),c=On(Q,l.length?r.filter(m=>!s(m)):r);return a(o,200,{ok:!0,appended:c.appended,duplicates:c.duplicates,rejected:[...l,...c.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=En(Q.all());return a(o,200,{ok:!0,stats:e,year:Pn(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=po(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=>vt(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=po(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
45
- data: ${JSON.stringify({cursor:Q.cursor(),count:Q.count(),version:de})}
45
+ data: ${JSON.stringify({cursor:Q.cursor(),count:Q.count(),version:ue})}
46
46
 
47
47
  `),Ee.add(o),n.on("close",()=>Ee.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
48
48
  data: ${JSON.stringify(vt(s))}
49
49
 
50
- `)}}return}if(i==="/v1/link"&&n.method==="GET")return a(o,200,{...y?{enabled:!0,...y.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(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{be(t,le())}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(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(e?.kind==="partner"){const r={partner:e.partner?.name,scopes:e.scopes,route:e.route||null,relay:String(e.relay||""),folder:typeof e.folder=="string"?e.folder:""};let s;try{s=y.previewPartner(r)}catch(l){return a(o,400,{error:{message:l?.message||String(l),type:"invalid_request",code:l?.code||"bad_partner"}})}if(e.confirm!==!0)return a(o,200,{confirmed:!1,preview:s});try{return a(o,200,{confirmed:!0,...await y.pairPartner(r)})}catch(l){return a(o,l?.code==="bad_partner"?400:502,{error:{message:l?.message||String(l),type:l?.code==="bad_partner"?"invalid_request":"relay"}})}}if(e?.kind&&e.kind!=="phone")return a(o,400,{error:{message:"link pair: kind is phone or partner",type:"invalid_request"}});try{return a(o,200,await y.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(r){return a(o,502,{error:{message:r?.message||String(r),type:"relay"}})}}if(i==="/v1/link/route"&&n.method==="POST"){if(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});let e={};try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let r;try{r=ta({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{be(t,le())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await y.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!y)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await y.remove(e)?(w.cancelDevice(e),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/link/files"||i.startsWith("/v1/link/files/")){const e=nt(n.headers);if(e?.kind!=="partner"||!e.scopes.includes("files"))return a(o,403,{error:{message:"link files: a partner’s own folder, for a partner granted files",type:"forbidden",code:"link_scope"}});const r=y?.partnerFolderOf(e.device);if(!r)return a(o,403,{error:{message:"link files: this partner has no folder on this computer — pair it again with agents and files",type:"forbidden",code:"link_scope"}});const s=i.slice(14).replace(/^\//,"");let l=s;try{l=decodeURIComponent(s)}catch{}const c=n.method==="GET"&&(!s||/^(data|\.claude\/skills|\.claude\/agents|\.agents\/skills)\/?$/.test(l));let m;try{m=ia(s,{listing:c})}catch(h){return a(o,400,{error:{message:h.message,type:"invalid_request",code:"bad_path"}})}try{if(n.method==="GET"&&c)return a(o,200,{folder:"its own",files:la(r,m.replace(/\/$/,""))});if(n.method==="GET"){const h=da(r,m);o.writeHead(200,{"content-type":"application/octet-stream","content-length":String(h.size)}),h.stream.pipe(o);return}return n.method==="PUT"?a(o,200,ca(r,m,await S(n,t.maxBodyBytes))):n.method==="DELETE"?ua(r,m)?a(o,200,{ok:!0}):a(o,404,{error:{message:`${m}: no such file`,type:"not_found"}}):a(o,405,{error:{message:"link files: GET, PUT or DELETE",type:"invalid_request"}})}catch(h){const g=h?.status||(h?.code===413?413:h?.code==="bad_partner"?400:500);return a(o,g,{error:{message:h?.message||String(h),type:g===404?"not_found":g===413?"too_large":"invalid_request"}})}}if(i==="/v1/link/approvals"||i.startsWith("/v1/link/approvals/")){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"an agent’s approval is the owner’s to give, on this computer",type:"forbidden"}});if(i==="/v1/link/approvals"&&n.method==="GET")return a(o,200,{pending:w.list()});if(i==="/v1/link/approvals/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const r=c=>o.write(`event: approvals
50
+ `)}}return}if(i==="/v1/link"&&n.method==="GET")return a(o,200,{...y?{enabled:!0,...y.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(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{be(t,ce())}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(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(e?.kind==="partner"){const r={partner:e.partner?.name,scopes:e.scopes,route:e.route||null,relay:String(e.relay||""),folder:typeof e.folder=="string"?e.folder:""};let s;try{s=y.previewPartner(r)}catch(l){return a(o,400,{error:{message:l?.message||String(l),type:"invalid_request",code:l?.code||"bad_partner"}})}if(e.confirm!==!0)return a(o,200,{confirmed:!1,preview:s});try{return a(o,200,{confirmed:!0,...await y.pairPartner(r)})}catch(l){return a(o,l?.code==="bad_partner"?400:502,{error:{message:l?.message||String(l),type:l?.code==="bad_partner"?"invalid_request":"relay"}})}}if(e?.kind&&e.kind!=="phone")return a(o,400,{error:{message:"link pair: kind is phone or partner",type:"invalid_request"}});try{return a(o,200,await y.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(r){return a(o,502,{error:{message:r?.message||String(r),type:"relay"}})}}if(i==="/v1/link/route"&&n.method==="POST"){if(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});let e={};try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let r;try{r=ta({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{be(t,ce())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await y.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!y)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await y.remove(e)?(w.cancelDevice(e),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/link/files"||i.startsWith("/v1/link/files/")){const e=nt(n.headers);if(e?.kind!=="partner"||!e.scopes.includes("files"))return a(o,403,{error:{message:"link files: a partner’s own folder, for a partner granted files",type:"forbidden",code:"link_scope"}});const r=y?.partnerFolderOf(e.device);if(!r)return a(o,403,{error:{message:"link files: this partner has no folder on this computer — pair it again with agents and files",type:"forbidden",code:"link_scope"}});const s=i.slice(14).replace(/^\//,"");let l=s;try{l=decodeURIComponent(s)}catch{}const c=n.method==="GET"&&(!s||/^(data|\.claude\/skills|\.claude\/agents|\.agents\/skills)\/?$/.test(l));let m;try{m=ia(s,{listing:c})}catch(h){return a(o,400,{error:{message:h.message,type:"invalid_request",code:"bad_path"}})}try{if(n.method==="GET"&&c)return a(o,200,{folder:"its own",files:la(r,m.replace(/\/$/,""))});if(n.method==="GET"){const h=da(r,m);o.writeHead(200,{"content-type":"application/octet-stream","content-length":String(h.size)}),h.stream.pipe(o);return}return n.method==="PUT"?a(o,200,ca(r,m,await S(n,t.maxBodyBytes))):n.method==="DELETE"?ua(r,m)?a(o,200,{ok:!0}):a(o,404,{error:{message:`${m}: no such file`,type:"not_found"}}):a(o,405,{error:{message:"link files: GET, PUT or DELETE",type:"invalid_request"}})}catch(h){const g=h?.status||(h?.code===413?413:h?.code==="bad_partner"?400:500);return a(o,g,{error:{message:h?.message||String(h),type:g===404?"not_found":g===413?"too_large":"invalid_request"}})}}if(i==="/v1/link/approvals"||i.startsWith("/v1/link/approvals/")){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"an agent’s approval is the owner’s to give, on this computer",type:"forbidden"}});if(i==="/v1/link/approvals"&&n.method==="GET")return a(o,200,{pending:w.list()});if(i==="/v1/link/approvals/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const r=c=>o.write(`event: approvals
51
51
  data: ${JSON.stringify({pending:c})}
52
52
 
53
53
  `);r(w.list());const s=w.subscribe(r),l=setInterval(()=>o.write(`:
54
54
 
55
55
  `),25e3);l.unref?.(),o.on("close",()=>{s(),clearInterval(l)});return}const e=/^\/v1\/link\/approvals\/([A-Za-z0-9_-]{1,40})$/.exec(i);if(e&&n.method==="POST"){let r={};try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{r={}}return yo.some(s=>s.id===r.decision)?w.answer(e[1],r.decision)?a(o,200,{ok:!0}):a(o,404,{error:{message:"nothing is waiting under that id — answered, withdrawn or expired",type:"not_found"}}):a(o,400,{error:{message:`link approvals: { decision: ${yo.map(s=>s.id).join(" | ")} }`,type:"invalid_request"}})}}if(i==="/v1/browser"&&n.method==="GET")return a(o,200,p.status());if(i==="/v1/browser/stream"&&n.method==="GET"){p.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 p.call(e,n):i==="/v1/browser/announce"?p.announce(e):p.result(e);return a(o,r.status,r.body)}if(i==="/v1/history/stream"&&n.method==="GET"){const e=J.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
56
- data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:de,prefsRevision:ce.revision})}
56
+ data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:ue,prefsRevision:me.revision})}
57
57
 
58
- `),xe.add(o),n.on("close",()=>xe.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=J.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(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,...J.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=J.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:io()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Ur(String(e.passphrase)):Vr();const r=e.passphrase?await kt(J,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ue(),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 kt(J,ft());return e.ok&&e.whole&&Ue(),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 Uo(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await rt(t),L.state()!=="off"){if(!L.isReady()){const r=L.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 m=JSON.parse(r.toString("utf8"));s=m?.text||"",l=m?.strict===!0}catch{}const c=await L.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=Ho(t);if(!e){const r=L.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:L.state(),model:t.ner?.model||null})}try{const r=await S(n,t.maxBodyBytes),s=await et(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:Mt(t)});try{let r=e;const s=await Te(t.pro?.entitlementToken);await rt(t);const l=await Ze([ht(()=>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:zo(l.vault,"types")||[],detector:Mt(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=L.health().model||t.ner?.model||null,r=Math.round(St.totalmem()/1048576),s=$a(bo,{totalRamMB:r}).map(l=>({...l,installed:L.modelOnDisk(l.id)}));for(const l of[e,...L.modelsOnDisk()])!l||s.some(c=>c.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:L.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:L.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Gr(),recommendation:so(s,{totalRamMB:r},[]),state:L.state(),progress:L.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(St.totalmem()/1048576),l=so(bo.map(c=>({...c,installed:L.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(!(vo(c)||ko(c)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${c}`,type:"bad_model"}});const l=r||t.ner?.model||L.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(c=>c!==l),r&&No(t,r);try{be(t,le())}catch{}return(async()=>{r&&await L.setModel(r,{onLog:m=>console.log(m)});const c=zr(t.ner,{log:m=>console.log(m)});for(const m of L.companions())c.includes(m.model)||await L.removeCompanion(m.model);for(const m of c)await L.addCompanion(m,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});L.setUnionOrder(c)})().catch(c=>console.log(`[ner] union update failed: ${c.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:L.companions(),state:L.state()})}if(!r||!(vo(r)||ko(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});No(t,r);try{be(t,le())}catch{}return L.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:L.state(),progress:L.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=A.health().model||t.stt?.model||De,r={platform:process.platform,arch:process.arch,helper:!!bt()},s=Aa.map(l=>{const c=So(l,r);return{...l,installed:A.modelOnDisk(l.id),...c?{unavailable:c}:{}}});return e&&!s.some(l=>l.id===e)&&s.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:s,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:Ma,licenses:t.stt?.licenses||{}})}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||!(Na(r)||Ba(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=So(at(r),{platform:process.platform,arch:process.arch,helper:!!bt()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const l=at(r)?.license||null;if(l){const m=To(l),h=t.stt?.licenses?.[l.id]?.version===l.version;if(!h&&e.acceptLicense!==m)return a(o,409,{error:{message:`Accept the ${l.name} to use this model`,type:"license_required"},license:{...l,accept:m}});h||(t.stt||={enabled:!0,allowDownload:!0},t.stt.licenses={...t.stt.licenses||{},[l.id]:{version:l.version,acceptedAt:new Date().toISOString()}})}const c=typeof e.dtype=="string"&&Da(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},c&&(t.stt.dtype=c==="auto"?null:c);try{be(t,le())}catch{}return A.setModel(r,{onLog:m=>console.log(m),dtype:c||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:It(t,{installing:!0}),licenseAccepted:Wo(t,r)}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress(),speaker:{id:D.activeModel(),state:D.state(),installed:D.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=D.activeModel(),r=_a.map(s=>({...s,installed:D.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:D.state(),threshold:D.activeThreshold(),segment:xa.health(),translate:$e.health(),indictrans:Sa.health(),aec:xt.health(),progress:D.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(!go(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await D.setModel(r,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{be(t,le())}catch{}return D.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:D.activeModel(),state:D.state(),threshold:D.activeThreshold(),progress:D.progress()})}return D.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:D.activeModel(),state:D.state(),threshold:D.activeThreshold(),progress:D.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=C.health().model||t.tts?.model||$o(Ot()),r=Ot(),s=xo.find(c=>c.id===e)||null,l=xo.map(c=>({...c,installed:C.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:C.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:C.state(),progress:C.progress(),available:l,voice:t.tts?.voice||(lt(e)==="pocket-tts"?st:Oe),arch:C.arch(),supportsVoices:C.arch()?C.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:C.arch()?C.supportsCustomVoices():!!s?.customVoices,sampleRate:C.sampleRate(),voices:C.isPocket()||!C.arch()&&lt(e)==="pocket-tts"?(C.builtinVoices().length?C.builtinVoices():za).map(c=>({id:c,label:c[0].toUpperCase()+c.slice(1),lang:"en",installed:C.builtinVoices().includes(c)})):C.arch()&&C.arch()!=="style-tts2"?[]:Ca.map(c=>({...c,installed:C.voiceOnDisk(c.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:C.health().dtype,runtime:C.health().runtime,dtypes:La})}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&&!(Ia(r)||Ra(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=pe.parseCustomVoice(s);if(!(c?!!pe.getVoice(c):it(s)||_o(s)&&Oo(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&Ja(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Eo,voice:Oe,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const c=ja(r),m=pe.parseCustomVoice(t.tts.voice||""),h=!!(m&&pe.getVoice(m));if(c&&!h)if(lt(r)==="pocket-tts")t.tts.voice=st;else{const v=pe.listVoices();t.tts.voice=v.length?`custom:${v[0].id}`:""}else!c&&h&&(t.tts.voice=Oe);const g=lt(r)==="pocket-tts";g&&!pe.parseCustomVoice(t.tts.voice||"")&&!it(t.tts.voice)&&(t.tts.voice=st),!g&&it(t.tts.voice)&&(t.tts.voice=Oe)}l&&(t.tts.dtype=l==="auto"?null:l);try{be(t,le())}catch{}return r&&C.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:C.state(),progress:C.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:pe.listVoices(),usable:C.supportsCustomVoices(),embedder:D.activeModel(),embedderReady:D.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(!pe.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,{...pe.renameVoice(l,r),usable:C.supportsCustomVoices()})}catch(c){return a(o,400,{error:{message:c.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!D.isReady()){const b=D.download({onLog:M=>console.log(M)}),O=Symbol("timeout"),_=await Promise.race([b.then(()=>null).catch(M=>M),new Promise(M=>setTimeout(()=>M(O),Os))]);if(_===O||!D.isReady())return a(o,503,{error:{message:_===O?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${D.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:D.progress()})}const c=Float32Array.from(s),m=await D.embed(c);let h=null;try{const b=await C.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:O=>console.log(O)});b&&(h=await b.encodeVoice(Es(c,16e3,24e3)))}catch(b){console.log(`[tts] pocket conditioning unavailable for this voice (${b.message})`)}const g=l?pe.replaceVoice(l,{vec:m,pocket:h}):pe.saveVoice({name:r,vec:m,pocket:h}),v=l&&r&&r!==g.name?pe.renameVoice(l,r):g;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${v.name}" (${(g.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...g,...v,usable:C.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=pe.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=pe.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:Oe;try{be(t,le())}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>Po)return a(o,413,{error:{message:`text too long (max ${Po} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Ga(t),c=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,m=c||(l?l.voice:t.tts?.voice||Oe);if(l&&!Ua(m))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:re,contentType:Se,redacted:G}=await Ha({dest:l,text:r,voice:m,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await Te(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":Se,"Content-Length":String(re.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(G)}),o.end(re)}if(!await C.ready({onLog:re=>console.log(re),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||$o(Ot()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:C.health().error||"tts model not ready",type:"tts_unavailable"}});const v=Va({requested:c,configured:m,engine:C,voices:pe,isPocketVoice:it,isKnownVoice:_o,isValidVoiceId:Oo,defaultVoice:Oe,defaultPocketVoice:st});if(!v.ok)return a(o,v.status,{error:{message:v.message,type:v.type}});const{voice:b,customId:O,speakerEmbedding:_}=v,M=await C.synth(r,{voice:b,speed:s,speakerEmbedding:_}),me=C.sampleRate(),we=h==="pcm"?Buffer.from(new Float32Array(M).buffer):C.toWav(M,me);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(we.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(me),...O||C.isPocket()||C.supportsVoices()?{"X-Tts-Voice":b}:{}}),o.end(we)}catch(g){return a(o,500,{error:{message:g.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=Ea(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(O=>O.name===b&&!O.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 Pa(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",m=_t(t,"stt");let h=null;if(m.kind==="remote"||m.kind==="container")try{h=wo(m,{fetchImpl:et})}catch(b){return a(o,500,{error:{message:`stt provider: ${b.message}`,type:"bad_provider"}})}if(!h&&!A.isReady()&&await A.init({model:t.stt?.model||De,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:It(t),onLog:b=>console.log(b)}),!h&&!A.isReady())return a(o,503,{error:{message:`speech model not ready: ${A.health().error||A.state()}`,type:"stt_not_ready"}});const g=r("diarize")==="true"&&t.stt?.diarize!==!1;g&&!D.isReady()&&await D.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:b=>console.log(b)});const v=Date.now();try{const{id:b}=A.createSession({lang:r("language")||void 0,diarize:g,interims:!1,remote:h}),O=[],_=[];let M=null;A.subscribe(b,G=>{G.type==="final"&&G.text?O.push(G):G.type==="language"?M=G.lang:G.type==="error"&&_.push(G.message||G.code)});const me=16e3*5;for(let G=0;G<l.pcm.length;G+=me)A.pushAudio(b,l.pcm.subarray(G,Math.min(l.pcm.length,G+me))),await A.decodeNow(b);if(await A.endSession(b),!O.length&&_.length)return a(o,500,{error:{message:_[0],type:"decode_failed"}});let we=0;const re=O.map((G,Zo)=>{const Ft=typeof G.startMs=="number"?G.startMs/1e3:we,qo=(G.durationMs||0)/1e3;return we=Ft+qo,{id:Zo,start:Math.round(Ft*100)/100,end:Math.round(we*100)/100,text:G.text,...G.speaker?{speaker:G.speaker}:{},...G.turns?{turns:G.turns.map(Xe=>({start:Math.round(Xe.startMs/10)/100,end:Math.round((Xe.startMs+Xe.durationMs)/10)/100,speaker:Xe.speaker}))}:{}}}),Se=re.map(G=>G.text).join(" ").replace(/\s+/g," ").trim();return c==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Se)):c==="verbose_json"?a(o,200,{task:"transcribe",language:M||r("language")||null,duration:Math.round(l.seconds*100)/100,text:Se,segments:re,provider:m.kind,took_ms:Date.now()-v}):a(o,200,{text:Se})}catch(b){return a(o,b.code==="too_many_sessions"?429:500,{error:{message:b.message,type:b.code||"stt_error"}})}}if(i.startsWith("/v1/stt/sessions")&&(i=i.slice(3)),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=_t(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=wo(r,{fetchImpl:et})}catch(O){return a(o,500,{error:{message:`stt provider: ${O.message}`,type:"bad_provider"}})}!s&&!A.isReady()&&A.init({model:t.stt?.model||De,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:It(t),licenseAccepted:Wo(t,t.stt?.model||De),onLog:O=>console.log(O)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!D.isReady()&&D.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)});const c=typeof e?.translateTo=="string"&&t.stt?.translate!==!1?e.translateTo:null,m=c?{allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)}:null,h=e?.echo&&typeof e.echo=="object"&&typeof e.echo.group=="string"&&["mic","reference"].includes(e.echo.role)&&t.stt?.aec!==!1&&!s?{group:e.echo.group,role:e.echo.role}:null;h&&xt.state()==="off"&&xt.init({allowDownload:t.stt?.allowDownload!==!1,onLog:O=>console.log(O)});const g=Array.isArray(e?.langs)?e.langs.slice(0,12):null,v=t.stt?.model||De,b=g&&!s?Ta(g,{engine:at(v)?.engine||"",englishOnly:/\.en$/.test(v)}).missing:[];try{const O=e?.poll===!0,_=e?.format==="pcm16"?"pcm16":"f32",{id:M}=A.createSession({lang:e?.lang,langs:g,translateTo:c,translateLoad:m,echo:h,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:O,format:_});return a(o,201,{id:M,state:A.state(),format:_,...O?{poll:!0}:{},...b.length?{languagesMissing:b}:{},...c?{translate:$e.state()}:{}})}catch(O){return a(o,O.code==="too_many_sessions"?429:500,{error:{message:O.message,type:O.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(c,m,h)=>{if(m.type!=="final"&&m.type!=="translation"||!c.redact||!m.text)return m;try{let g=m.text;return await Ze([ht(()=>g,v=>{g=v})],t.redaction,{isPro:h}),{...m,text:g}}catch{return m}},l=async c=>{const m=A.drainEvents(r);if(!m)return null;const h=[];if(c&&!c.closed){const v=c.remote?"ready":A.state();v==="downloading"||v==="loading"?h.push({type:"progress",state:v,...A.progress()||{}}):v==="error"?h.push({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}):c.diarize&&["downloading","loading"].includes(D.state())?h.push({type:"diarize-progress",state:D.state(),...D.progress()||{}}):c.translateTo&&["downloading","loading"].includes($e.state())?h.push({type:"translate-progress",state:$e.state(),...$e.progress()||{}}):Fo.get(c)!==v&&(Fo.set(c,v),h.push({type:"state",state:v}))}const g=c?.redact?await Te(t.pro?.entitlementToken):!0;for(const v of m)c?h.push(await s(c,v,g)):v.type!=="final"&&v.type!=="interim"&&v.type!=="translation"&&h.push(v);return h};if(e[2]==="/audio"&&n.method==="POST"){const c=A.getSession(r)||A.endedSession(r);try{const m=await S(n,t.maxBodyBytes);A.pushAudio(r,A.toFloat32(m,c?.format));const h=await l(c);return a(o,200,{ok:!0,state:A.state(),...h?{events:h}:{}})}catch(m){const h=m.code==="no_session"?await l(c).catch(()=>null):null;return a(o,m.code==="no_session"?404:400,{error:{message:m.message,type:m.code||"stt_error"},...h?{events:h}:{}})}}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 m=_=>o.write(`data: ${JSON.stringify(_)}
58
+ `),xe.add(o),n.on("close",()=>xe.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=J.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(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,...J.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=J.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:io()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Ur(String(e.passphrase)):Vr();const r=e.passphrase?await kt(J,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ue(),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 kt(J,ft());return e.ok&&e.whole&&Ue(),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 Uo(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await rt(t),L.state()!=="off"){if(!L.isReady()){const r=L.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 m=JSON.parse(r.toString("utf8"));s=m?.text||"",l=m?.strict===!0}catch{}const c=await L.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=Ho(t);if(!e){const r=L.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:L.state(),model:t.ner?.model||null})}try{const r=await S(n,t.maxBodyBytes),s=await et(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:Mt(t)});try{let r=e;const s=await Te(t.pro?.entitlementToken);await rt(t);const l=await Ze([ht(()=>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:zo(l.vault,"types")||[],detector:Mt(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=L.health().model||t.ner?.model||null,r=Math.round(St.totalmem()/1048576),s=Aa(bo,{totalRamMB:r}).map(l=>({...l,installed:L.modelOnDisk(l.id)}));for(const l of[e,...L.modelsOnDisk()])!l||s.some(c=>c.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:L.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:L.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Gr(),recommendation:so(s,{totalRamMB:r},[]),state:L.state(),progress:L.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(St.totalmem()/1048576),l=so(bo.map(c=>({...c,installed:L.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(!(vo(c)||ko(c)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${c}`,type:"bad_model"}});const l=r||t.ner?.model||L.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(c=>c!==l),r&&No(t,r);try{be(t,ce())}catch{}return(async()=>{r&&await L.setModel(r,{onLog:m=>console.log(m)});const c=zr(t.ner,{log:m=>console.log(m)});for(const m of L.companions())c.includes(m.model)||await L.removeCompanion(m.model);for(const m of c)await L.addCompanion(m,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});L.setUnionOrder(c)})().catch(c=>console.log(`[ner] union update failed: ${c.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:L.companions(),state:L.state()})}if(!r||!(vo(r)||ko(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});No(t,r);try{be(t,ce())}catch{}return L.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:L.state(),progress:L.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=A.health().model||t.stt?.model||De,r={platform:process.platform,arch:process.arch,helper:!!bt()},s=Na.map(l=>{const c=So(l,r);return{...l,installed:A.modelOnDisk(l.id),...c?{unavailable:c}:{}}});return e&&!s.some(l=>l.id===e)&&s.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:s,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:Da,licenses:t.stt?.licenses||{}})}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||!(Ba(r)||Ma(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=So(at(r),{platform:process.platform,arch:process.arch,helper:!!bt()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const l=at(r)?.license||null;if(l){const m=To(l),h=t.stt?.licenses?.[l.id]?.version===l.version;if(!h&&e.acceptLicense!==m)return a(o,409,{error:{message:`Accept the ${l.name} to use this model`,type:"license_required"},license:{...l,accept:m}});h||(t.stt||={enabled:!0,allowDownload:!0},t.stt.licenses={...t.stt.licenses||{},[l.id]:{version:l.version,acceptedAt:new Date().toISOString()}})}const c=typeof e.dtype=="string"&&Ca(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},c&&(t.stt.dtype=c==="auto"?null:c);try{be(t,ce())}catch{}return A.setModel(r,{onLog:m=>console.log(m),dtype:c||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:It(t,{installing:!0}),licenseAccepted:Wo(t,r)}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress(),speaker:{id:M.activeModel(),state:M.state(),installed:M.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=M.activeModel(),r=_a.map(s=>({...s,installed:M.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:M.state(),threshold:M.activeThreshold(),segment:xa.health(),translate:$e.health(),indictrans:Sa.health(),aec:xt.health(),progress:M.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(!go(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await M.setModel(r,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{be(t,ce())}catch{}return M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:M.activeModel(),state:M.state(),threshold:M.activeThreshold(),progress:M.progress()})}return M.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:M.activeModel(),state:M.state(),threshold:M.activeThreshold(),progress:M.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=D.health().model||t.tts?.model||$o(Ot()),r=Ot(),s=xo.find(c=>c.id===e)||null,l=xo.map(c=>({...c,installed:D.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:D.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:D.state(),progress:D.progress(),available:l,voice:t.tts?.voice||(lt(e)==="pocket-tts"?st:Oe),arch:D.arch(),supportsVoices:D.arch()?D.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:D.arch()?D.supportsCustomVoices():!!s?.customVoices,sampleRate:D.sampleRate(),voices:D.isPocket()||!D.arch()&&lt(e)==="pocket-tts"?(D.builtinVoices().length?D.builtinVoices():Ga).map(c=>({id:c,label:c[0].toUpperCase()+c.slice(1),lang:"en",installed:D.builtinVoices().includes(c)})):D.arch()&&D.arch()!=="style-tts2"?[]:Ia.map(c=>({...c,installed:D.voiceOnDisk(c.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:D.health().dtype,runtime:D.health().runtime,dtypes:Ja})}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&&!(Ra(r)||La(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=de.parseCustomVoice(s);if(!(c?!!de.getVoice(c):it(s)||_o(s)&&Oo(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&ja(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Eo,voice:Oe,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const c=za(r),m=de.parseCustomVoice(t.tts.voice||""),h=!!(m&&de.getVoice(m));if(c&&!h)if(lt(r)==="pocket-tts")t.tts.voice=st;else{const b=de.listVoices();t.tts.voice=b.length?`custom:${b[0].id}`:""}else!c&&h&&(t.tts.voice=Oe);const g=lt(r)==="pocket-tts";g&&!de.parseCustomVoice(t.tts.voice||"")&&!it(t.tts.voice)&&(t.tts.voice=st),!g&&it(t.tts.voice)&&(t.tts.voice=Oe)}l&&(t.tts.dtype=l==="auto"?null:l);try{be(t,ce())}catch{}return r&&D.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:D.state(),progress:D.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:de.listVoices(),usable:D.supportsCustomVoices(),embedder:M.activeModel(),embedderReady:M.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(!de.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,{...de.renameVoice(l,r),usable:D.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{const c=Ea(M.activeModel())?.dim===de.EMBED_DIM;if(c&&!M.isReady()){const O=M.download({onLog:q=>console.log(q)}),x=Symbol("timeout"),I=await Promise.race([O.then(()=>null).catch(q=>q),new Promise(q=>setTimeout(()=>q(x),Es))]);if(I===x||!M.isReady())return a(o,503,{error:{message:I===x?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${M.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:M.progress()})}const m=Float32Array.from(s),h=c?await M.embed(m):null;let g=null;try{const O=await D.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:x=>console.log(x)});O&&(g=await O.encodeVoice(Ps(m,16e3,24e3)))}catch(O){console.log(`[tts] pocket conditioning unavailable for this voice (${O.message})`)}const b=l?de.replaceVoice(l,{vec:h,pocket:g}):de.saveVoice({name:r,vec:h,pocket:g}),v=l&&r&&r!==b.name?de.renameVoice(l,r):b;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${v.name}" (${(b.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...b,...v,usable:D.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=de.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=de.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:Oe;try{be(t,ce())}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>Po)return a(o,413,{error:{message:`text too long (max ${Po} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=Ha(t),c=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,m=c||(l?l.voice:t.tts?.voice||Oe);if(l&&!Va(m))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:ne,contentType:Se,redacted:G}=await Ua({dest:l,text:r,voice:m,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await Te(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":Se,"Content-Length":String(ne.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(G)}),o.end(ne)}if(!await D.ready({onLog:ne=>console.log(ne),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||$o(Ot()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:D.health().error||"tts model not ready",type:"tts_unavailable"}});const b=Fa({requested:c,configured:m,engine:D,voices:de,isPocketVoice:it,isKnownVoice:_o,isValidVoiceId:Oo,defaultVoice:Oe,defaultPocketVoice:st});if(!b.ok)return a(o,b.status,{error:{message:b.message,type:b.type}});const{voice:v,customId:O,speakerEmbedding:x}=b,I=await D.synth(r,{voice:v,speed:s,speakerEmbedding:x}),q=D.sampleRate(),we=h==="pcm"?Buffer.from(new Float32Array(I).buffer):D.toWav(I,q);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(we.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(q),...O||D.isPocket()||D.supportsVoices()?{"X-Tts-Voice":v}:{}}),o.end(we)}catch(g){return a(o,500,{error:{message:g.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=Pa(await S(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(v){return a(o,v.code===413?413:415,{error:{message:v.message,type:"bad_request"}})}const r=v=>e.find(O=>O.name===v&&!O.filename)?.data.toString("utf8").trim()||"",s=e.find(v=>v.name==="file"&&v.filename)||e.find(v=>v.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await $a(s.data)}catch(v){return a(o,v.code===415?415:500,{error:{message:v.message,type:"unsupported_media"}})}const c=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",m=_t(t,"stt");let h=null;if(m.kind==="remote"||m.kind==="container")try{h=wo(m,{fetchImpl:et})}catch(v){return a(o,500,{error:{message:`stt provider: ${v.message}`,type:"bad_provider"}})}if(!h&&!A.isReady()&&await A.init({model:t.stt?.model||De,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:It(t),onLog:v=>console.log(v)}),!h&&!A.isReady())return a(o,503,{error:{message:`speech model not ready: ${A.health().error||A.state()}`,type:"stt_not_ready"}});const g=r("diarize")==="true"&&t.stt?.diarize!==!1;g&&!M.isReady()&&await M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:v=>console.log(v)});const b=Date.now();try{const{id:v}=A.createSession({lang:r("language")||void 0,diarize:g,interims:!1,remote:h}),O=[],x=[];let I=null;A.subscribe(v,G=>{G.type==="final"&&G.text?O.push(G):G.type==="language"?I=G.lang:G.type==="error"&&x.push(G.message||G.code)});const q=16e3*5;for(let G=0;G<l.pcm.length;G+=q)A.pushAudio(v,l.pcm.subarray(G,Math.min(l.pcm.length,G+q))),await A.decodeNow(v);if(await A.endSession(v),!O.length&&x.length)return a(o,500,{error:{message:x[0],type:"decode_failed"}});let we=0;const ne=O.map((G,Zo)=>{const Ft=typeof G.startMs=="number"?G.startMs/1e3:we,qo=(G.durationMs||0)/1e3;return we=Ft+qo,{id:Zo,start:Math.round(Ft*100)/100,end:Math.round(we*100)/100,text:G.text,...G.speaker?{speaker:G.speaker}:{},...G.turns?{turns:G.turns.map(Xe=>({start:Math.round(Xe.startMs/10)/100,end:Math.round((Xe.startMs+Xe.durationMs)/10)/100,speaker:Xe.speaker}))}:{}}}),Se=ne.map(G=>G.text).join(" ").replace(/\s+/g," ").trim();return c==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Se)):c==="verbose_json"?a(o,200,{task:"transcribe",language:I||r("language")||null,duration:Math.round(l.seconds*100)/100,text:Se,segments:ne,provider:m.kind,took_ms:Date.now()-b}):a(o,200,{text:Se})}catch(v){return a(o,v.code==="too_many_sessions"?429:500,{error:{message:v.message,type:v.code||"stt_error"}})}}if(i.startsWith("/v1/stt/sessions")&&(i=i.slice(3)),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=_t(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=wo(r,{fetchImpl:et})}catch(O){return a(o,500,{error:{message:`stt provider: ${O.message}`,type:"bad_provider"}})}!s&&!A.isReady()&&A.init({model:t.stt?.model||De,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:It(t),licenseAccepted:Wo(t,t.stt?.model||De),onLog:O=>console.log(O)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!M.isReady()&&M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)});const c=typeof e?.translateTo=="string"&&t.stt?.translate!==!1?e.translateTo:null,m=c?{allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)}:null,h=e?.echo&&typeof e.echo=="object"&&typeof e.echo.group=="string"&&["mic","reference"].includes(e.echo.role)&&t.stt?.aec!==!1&&!s?{group:e.echo.group,role:e.echo.role}:null;h&&xt.state()==="off"&&xt.init({allowDownload:t.stt?.allowDownload!==!1,onLog:O=>console.log(O)});const g=Array.isArray(e?.langs)?e.langs.slice(0,12):null,b=t.stt?.model||De,v=g&&!s?Ta(g,{engine:at(b)?.engine||"",englishOnly:/\.en$/.test(b)}).missing:[];try{const O=e?.poll===!0,x=e?.format==="pcm16"?"pcm16":"f32",{id:I}=A.createSession({lang:e?.lang,langs:g,translateTo:c,translateLoad:m,echo:h,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:O,format:x});return a(o,201,{id:I,state:A.state(),format:x,...O?{poll:!0}:{},...v.length?{languagesMissing:v}:{},...c?{translate:$e.state()}:{}})}catch(O){return a(o,O.code==="too_many_sessions"?429:500,{error:{message:O.message,type:O.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(c,m,h)=>{if(m.type!=="final"&&m.type!=="translation"||!c.redact||!m.text)return m;try{let g=m.text;return await Ze([ht(()=>g,b=>{g=b})],t.redaction,{isPro:h}),{...m,text:g}}catch{return m}},l=async c=>{const m=A.drainEvents(r);if(!m)return null;const h=[];if(c&&!c.closed){const b=c.remote?"ready":A.state();b==="downloading"||b==="loading"?h.push({type:"progress",state:b,...A.progress()||{}}):b==="error"?h.push({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}):c.diarize&&["downloading","loading"].includes(M.state())?h.push({type:"diarize-progress",state:M.state(),...M.progress()||{}}):c.translateTo&&["downloading","loading"].includes($e.state())?h.push({type:"translate-progress",state:$e.state(),...$e.progress()||{}}):Fo.get(c)!==b&&(Fo.set(c,b),h.push({type:"state",state:b}))}const g=c?.redact?await Te(t.pro?.entitlementToken):!0;for(const b of m)c?h.push(await s(c,b,g)):b.type!=="final"&&b.type!=="interim"&&b.type!=="translation"&&h.push(b);return h};if(e[2]==="/audio"&&n.method==="POST"){const c=A.getSession(r)||A.endedSession(r);try{const m=await S(n,t.maxBodyBytes);A.pushAudio(r,A.toFloat32(m,c?.format));const h=await l(c);return a(o,200,{ok:!0,state:A.state(),...h?{events:h}:{}})}catch(m){const h=m.code==="no_session"?await l(c).catch(()=>null):null;return a(o,m.code==="no_session"?404:400,{error:{message:m.message,type:m.code||"stt_error"},...h?{events:h}:{}})}}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 m=x=>o.write(`data: ${JSON.stringify(x)}
59
59
 
60
- `),h=c.redact?await Te(t.pro?.entitlementToken):!0,g=_=>s(c,_,h);m({type:"state",state:c.remote?"ready":A.state()});const v=setInterval(()=>{const _=c.remote?"ready":A.state();if(_==="downloading"||_==="loading"){m({type:"progress",state:_,...A.progress()||{}});return}if(_==="error"){m({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(v);return}if(c.diarize){const M=D.state();if(M==="downloading"||M==="loading"){m({type:"diarize-progress",state:M,...D.progress()||{}});return}}if(c.translateTo){const M=$e.state();if(M==="downloading"||M==="loading"){m({type:"translate-progress",state:M,...$e.progress()||{}});return}}m({type:"state",state:_}),clearInterval(v)},500);v.unref?.();let b=Promise.resolve();const O=A.subscribe(r,_=>{b=b.then(async()=>{m(await g(_)),_.type==="end"&&(clearInterval(v),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(v),O?.()});return}if(!e[2]&&n.method==="DELETE"){const c=A.getSession(r);await A.endSession(r);const m=c?.poll?await l(c).catch(()=>null):null;return a(o,200,{ok:!0,...m?{events:m}:{}})}}}if(i==="/logs"&&n.method==="GET")return a(o,200,{entries:[...I].reverse()});if(i==="/config"&&n.method==="GET"){const e=await Te(t.pro?.entitlementToken);return a(o,200,Ao(t,{proUnlocked:e,policy:qe()}))}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{Qa(t,e)}catch(h){if(h?.code==="SHAPE")return a(o,400,{error:h.message});throw h}Zt(t),JSON.stringify(t.sandbox||null)!==r&&Ve?.restart("sandbox settings changed");try{be(t,le())}catch(h){return a(o,500,{error:`could not persist config: ${h.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",c=L.state();t.ner?.autostart&&l&&c!=="ready"&&c!=="loading"&&c!=="downloading"&&L.setModel(t.ner.model,{onLog:h=>console.log(h)}).then(h=>{h&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await Te(t.pro?.entitlementToken);return a(o,200,Ao(t,{proUnlocked:m,policy:qe()}))}if(n.method==="GET"&&i==="/skills")return ve(n,o,t,`/skills${Re(f,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="POST"&&i==="/v1/threads/send"){if(!H(n))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"asking another chat is not available from a linked phone yet",type:"forbidden"}});const e=J.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let r={};try{r=JSON.parse((await 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>uo)return a(o,400,{error:{message:`threads/send: a message of 1–${uo} 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,m=e.get(s);if(!m||m.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const h=Zr(m,{cards:ce.get("agentTools").agentTools?.value?.agents||[]});if(h.error)return a(o,409,{error:{message:h.error,type:"no_model"}});if(r.dryRun===!0)return a(o,200,{ok:!0,title:m.title,model:h.model});const g=qr({fromTitle:c?.title,message:l}),v={thread:{id:h.thread,...m.title?{title:m.title}:{}},...h.workingDir?{workingDir:h.workingDir}:{}};let b="";try{const _=await fetch(`http://127.0.0.1:${n.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":Me()||_e(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(v))},body:JSON.stringify({model:h.model,messages:[...en(m),{role:"user",content:g}],stream:!1}),signal:AbortSignal.timeout(6e5)}),M=await _.json().catch(()=>null);if(!_.ok)return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${M?.error?.message||`HTTP ${_.status}`}`,type:"upstream"}});b=String(M?.choices?.[0]?.message?.content||"")}catch(_){return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${_?.message||_}`,type:"upstream"}})}const O=tn(e.get(s)||m,{question:g,reply:b,model:h.model,from:c});e.write([O],{host:"gateway",at:Date.now()});try{const _=ho(e.get(s));_&&J.bulk({upserts:[_],removes:[]})}catch{}return Ue({ids:[s]}),a(o,200,{ok:!0,title:m.title,model:h.model,reply:b})}const Z=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(n.method==="POST"&&Z)return H(n)?n.headers["x-chatpanel-link-device"]&&t.link?.agentSessions===!1?a(o,403,{error:{message:"this computer does not share its coding agents' sessions with a linked phone — Settings › Link › Phones",type:"forbidden"}}):ve(n,o,t,Z,{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 ve(n,o,t,`/skills-quarantined${Re(f,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&n.method==="POST")return H(n)?ve(n,o,t,"/skills",{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(i)&&n.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return Rt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):H(n)?ve(n,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):a(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(i)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]);return Rt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):H(n)?ve(n,o,t,`/skills/${encodeURIComponent(r)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(n.method==="GET"&&i==="/agent-defs")return ve(n,o,t,`/agent-defs${Re(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 Rt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):ve(n,o,t,`/agent-defs/${encodeURIComponent(e)}${Re(f,t)}`)}if(i.startsWith("/a2a/")){if(!H(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:Dr()});if(n.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&$r(e.url||"");const r=await tt(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 tt(e.url,{auth:String(e.auth||"")})).card,s=await Ar({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 tt(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}
60
+ `),h=c.redact?await Te(t.pro?.entitlementToken):!0,g=x=>s(c,x,h);m({type:"state",state:c.remote?"ready":A.state()});const b=setInterval(()=>{const x=c.remote?"ready":A.state();if(x==="downloading"||x==="loading"){m({type:"progress",state:x,...A.progress()||{}});return}if(x==="error"){m({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(b);return}if(c.diarize){const I=M.state();if(I==="downloading"||I==="loading"){m({type:"diarize-progress",state:I,...M.progress()||{}});return}}if(c.translateTo){const I=$e.state();if(I==="downloading"||I==="loading"){m({type:"translate-progress",state:I,...$e.progress()||{}});return}}m({type:"state",state:x}),clearInterval(b)},500);b.unref?.();let v=Promise.resolve();const O=A.subscribe(r,x=>{v=v.then(async()=>{m(await g(x)),x.type==="end"&&(clearInterval(b),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(b),O?.()});return}if(!e[2]&&n.method==="DELETE"){const c=A.getSession(r);await A.endSession(r);const m=c?.poll?await l(c).catch(()=>null):null;return a(o,200,{ok:!0,...m?{events:m}:{}})}}}if(i==="/logs"&&n.method==="GET")return a(o,200,{entries:[...C].reverse()});if(i==="/config"&&n.method==="GET"){const e=await Te(t.pro?.entitlementToken);return a(o,200,Ao(t,{proUnlocked:e,policy:qe()}))}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{Ya(t,e)}catch(h){if(h?.code==="SHAPE")return a(o,400,{error:h.message});throw h}Zt(t),JSON.stringify(t.sandbox||null)!==r&&Ve?.restart("sandbox settings changed");try{be(t,ce())}catch(h){return a(o,500,{error:`could not persist config: ${h.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",c=L.state();t.ner?.autostart&&l&&c!=="ready"&&c!=="loading"&&c!=="downloading"&&L.setModel(t.ner.model,{onLog:h=>console.log(h)}).then(h=>{h&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await Te(t.pro?.entitlementToken);return a(o,200,Ao(t,{proUnlocked:m,policy:qe()}))}if(n.method==="GET"&&i==="/skills")return ve(n,o,t,`/skills${Re(f,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="POST"&&i==="/v1/threads/send"){if(!H(n))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"asking another chat is not available from a linked phone yet",type:"forbidden"}});const e=J.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let r={};try{r=JSON.parse((await 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>uo)return a(o,400,{error:{message:`threads/send: a message of 1–${uo} 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,m=e.get(s);if(!m||m.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const h=Zr(m,{cards:me.get("agentTools").agentTools?.value?.agents||[]});if(h.error)return a(o,409,{error:{message:h.error,type:"no_model"}});if(r.dryRun===!0)return a(o,200,{ok:!0,title:m.title,model:h.model});const g=qr({fromTitle:c?.title,message:l}),b={thread:{id:h.thread,...m.title?{title:m.title}:{}},...h.workingDir?{workingDir:h.workingDir}:{}};let v="";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":Me()||_e(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(b))},body:JSON.stringify({model:h.model,messages:[...en(m),{role:"user",content:g}],stream:!1}),signal:AbortSignal.timeout(6e5)}),I=await x.json().catch(()=>null);if(!x.ok)return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${I?.error?.message||`HTTP ${x.status}`}`,type:"upstream"}});v=String(I?.choices?.[0]?.message?.content||"")}catch(x){return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${x?.message||x}`,type:"upstream"}})}const O=tn(e.get(s)||m,{question:g,reply:v,model:h.model,from:c});e.write([O],{host:"gateway",at:Date.now()});try{const x=ho(e.get(s));x&&J.bulk({upserts:[x],removes:[]})}catch{}return Ue({ids:[s]}),a(o,200,{ok:!0,title:m.title,model:h.model,reply:v})}const Z=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(n.method==="POST"&&Z)return H(n)?n.headers["x-chatpanel-link-device"]&&t.link?.agentSessions===!1?a(o,403,{error:{message:"this computer does not share its coding agents' sessions with a linked phone — Settings › Link › Phones",type:"forbidden"}}):ve(n,o,t,Z,{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 ve(n,o,t,`/skills-quarantined${Re(f,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&n.method==="POST")return H(n)?ve(n,o,t,"/skills",{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(i)&&n.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return Rt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):H(n)?ve(n,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):a(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(i)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]);return Rt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):H(n)?ve(n,o,t,`/skills/${encodeURIComponent(r)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(n.method==="GET"&&i==="/agent-defs")return ve(n,o,t,`/agent-defs${Re(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 Rt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):ve(n,o,t,`/agent-defs/${encodeURIComponent(e)}${Re(f,t)}`)}if(i.startsWith("/a2a/")){if(!H(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:Dr()});if(n.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&$r(e.url||"");const r=await tt(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 tt(e.url,{auth:String(e.auth||"")})).card,s=await Ar({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 tt(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}
61
61
  data: ${JSON.stringify(c)}
62
62
 
63
- `);try{const l=await Nr({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 tt(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await Mr({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await Br({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 eo||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof eo&&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 H(n)?ve(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"}}):ve(n,o,t,`/skills/${encodeURIComponent(e)}${Re(f,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!H(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 je(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=ze(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"}}):ve(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${Re(f,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await j(),r=e.sig!==void 0&&e.sig!==R;return R=e.sig,a(o,200,await es(t,{serviceHealth:async()=>e,fresh:r,engineAt:d.engineAt}))}if(Ps.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${de}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const F=gs(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 W=null,k=null,se=K,Fe=0,Ae=0,Jt=0,ke=!1,Pe=!1,jt="",Ne=!0;const ne=t.logRequests&&F.redactable&&n.method==="POST"?fs(q):null,Ko=Date.now();if(F.redactable&&n.method==="POST"&&K.length){try{k=JSON.parse(K.toString("utf8"))}catch{k=null}if(k&&ws(k,F.kind))se=K;else if(k){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(k.tools)&&k.tools.length){const g=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):ls,v=e.narrowAll?null:O=>!ds.test(Ro(O)),b=k.tools.length;k.tools=lr(k.tools,us(k,F.kind),{cap:g,keep:v,name:Ro,description:cs}),Jt=b-k.tools.length}if(Ne=await Te(t.pro?.entitlementToken),ke=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&H(n),!ke){const g=dt(k?.model,t,F.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:()=>!1}),v=g?.type==="api"?await d.decide(g,k?.model).catch(()=>null):null;Pe=v?.redact===!1,jt=Pe?v.engine||"declared":""}if(!ke&&!Pe){const g=Fa(t,Ne);if(!g.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${g.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}})}!ke&&!Pe&&await rt(t);const r=ke?[]:F.adapter.collectSegments(k,t.redaction,{skipPublic:H(n)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=ne?ne.clock():0,{vault:c,count:m,sanitized:h}=ke?{vault:null,count:0,sanitized:0}:await Ze(r,t.redaction,{signal:s.signal,isPro:Ne,sanitizeOnly:Pe,onEgress:g=>Nt.push(Mo({ts:Date.now(),client:"redaction",tool:`detect:${g.backend}@${g.host||"local"}`,ok:g.ok,ms:g.ms,error:g.error}))});if(ne&&ne.lap("redact",l),F.adapter.joinTextParts?.(k),W=c,Fe=m,Ae=h||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!Ne&&m>0){Wa(t,Ne);try{be(t,le())}catch{}}if(!ke&&!Pe&&Array.isArray(k.tools)&&k.tools.length&&typeof F.adapter.injectSystemNote=="function"){const g=dt(k?.model,t,F.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:b=>!!b.service&&x.fn(b.id)==="down"}),v=!(g&&g.type==="api");F.adapter.injectSystemNote(k,cr({toolData:t.tools?.toolData,ownTools:v}))}else!ke&&m>0&&typeof F.adapter.injectSystemNote=="function"&&F.adapter.injectSystemNote(k,ur());se=Buffer.from(JSON.stringify(k),"utf8")}}const zt=dr({vault:W,toolData:t.tools?.toolData}),We=k&&typeof k.chatpanel=="object"&&k.chatpanel||null;if(We&&(delete k.chatpanel,se=Buffer.from(JSON.stringify(k),"utf8")),typeof k?.model=="string"&&k.model.startsWith("fusion:")){const e=Nn(k.model,t,await j());if(e?.error)return ne?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(k.model=e.model,se=Buffer.from(JSON.stringify(k),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const ae={destination:String(n.headers["x-chatpanel-destination"]||We?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||We?.reach||"").trim(),run:Lt(n.headers["x-chatpanel-run"],We?.run)},Ke=await j(),Gt=e=>!!e.service&&Ke(e.id)==="down";let N=dt(k?.model,t,F.kind,{destination:ae.destination,down:Gt});N?.type==="agent"&&k?.model&&!ae.destination&&!rs(N,k.model)&&(await os(t,{serviceHealth:async()=>Ke,engineAt:d.engineAt}),N=dt(k?.model,t,F.kind,{destination:ae.destination,down:Gt}));const Ht=N?.service&&Ke(N.id)==="down"?await P().revive(N.service).catch(()=>null):null;if(Ht?.ok&&(x.at=0),N?.service&&Ke(N.id)==="down"&&!Ht?.ok)return ne?.commit(),a(o,503,{error:{message:`${N.id} is not running — the model ${JSON.stringify(k?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:N.service}});if(ae.destination&&(!N||N.id!==ae.destination))return ne?.commit(),a(o,404,{error:{message:`no destination "${ae.destination}" is configured on this gateway`,type:"unknown_destination",known:ts(t).map(e=>e.id)}});const ie=nt(n.headers);if(ie&&!na(ie,N?.type==="api"?"api":"agent"))return ne?.commit(),a(o,403,{error:{message:`link: partner "${ie.partner}" may not use ${N?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${ie.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const Qe=ie&&F.redactable&&n.method==="POST"&&k?{caller:ie,surface:Tn(ie,ie.kind==="partner"?"":y?.deviceNameOf(ie.device)),model:k.model||null,startedAt:Ko}:null;ne&&(ne.meta={t:Date.now(),model:k?.model||null,dest:N?N.id:null,type:N?N.type:null,redacted:Fe,sanitized:Ae,narrowed:Jt,detail:zo(W,t.logDetail),redaction:ke?"off":Pe?`on-device (${jt})`:t.redaction.tier||"basic",...ie?.kind==="partner"?{via:aa(ie)}:{}});const Ye=qe();if(Ye&&N){const e=N.type==="api"?qt(Ye,{model:k?.model||"",endpoint:N.baseUrl||""}):Er(Ye,N.agent||N.id)?qt(Ye,{model:k?.model||""}):{ok:!1,reason:`agent "${N.agent||N.id}" is not allowed by your organisation’s policy`};if(!e.ok)return ne?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(N&&N.type==="api")return N.baseUrl?bs(N.baseUrl,t)?(ne?.commit(),a(o,508,{error:{message:`destination "${N.id}" points back at the gateway (${N.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):$s(n,o,{...F,pathname:i,search:f.search,base:N.baseUrl,destKey:N.apiKey,destProtocol:N.protocol,harness:zt,trace:ne,link:Qe&&{...Qe,agentId:N.id,dest:{type:"api",id:N.id}}},se,W):(ne?.commit(),a(o,502,{error:`destination "${N.id}" has no baseUrl`}));const mt=Le(n),Ut=mt==="local"&&t.bridge?.openAgentLane?"token":mt;if(Ut==="local")return ne?.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 Vt=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),Qo=new Set(["thread","ephemeral","workingDir","worker"]),pt=ie?.kind==="partner";if(mt==="token"&&n.headers["x-chatpanel-link-device"]&&!pt&&!(ae.run&&Object.keys(ae.run).some(e=>!Qo.has(e)))){const e=Lt(null,co(lo(ce.get("agentTools").agentTools?.value,N?.agent||k?.model)));e&&(ae.run={...e,...ae.run||{}})}if(pt){const e=Lt(null,co(lo(ce.get("agentTools").agentTools?.value,N?.agent||k?.model)));ae.run={...e||{},...sa(ae.run,ie.device)};const r=y?.partnerFolderOf(ie.device);if(!r)return ne?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});ae.run.workingDir=r,ae.reach="",Array.isArray(k?.tools)&&(k.tools=k.tools.filter(s=>!fo(s?.function?.name??s?.name)))}const Be=pr({...ae.run||{},...ae.reach?{reach:ae.reach}:{},...Vt?{askDepth:Vt}:{}},Ut);Be.reach&&o.setHeader("x-chatpanel-reach-used",Be.reach);const Yo=pt?{inbox:w,partner:ie.partner,device:ie.device,conversation:Be.thread?.id||null}:null,Xo=Qe&&{...Qe,dest:{type:"agent",id:N?.id||"bridge"},threadId:Be.thread?.id||null};return xs(n,o,{...F,pathname:i,agentOverride:N?.agent,harness:zt,trace:ne,run:Object.keys(Be).length?Be:null,owner:Yo,link:Xo},k,W,t,Ne)});return ue.on("close",()=>{E?.stop("closed"),zn(),p.close(),y?.stop(),w.stop()}),ue.on("upgrade",(n,o,f)=>{o.on("error",()=>{});const i=String(n.url||"").split("?")[0];if(y&&i.startsWith(ra)){y.acceptTunnel(n,o,f).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
63
+ `);try{const l=await Nr({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 tt(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await Mr({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await Br({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 eo||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof eo&&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 H(n)?ve(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"}}):ve(n,o,t,`/skills/${encodeURIComponent(e)}${Re(f,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!H(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 je(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=ze(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"}}):ve(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${Re(f,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await j(),r=e.sig!==void 0&&e.sig!==R;return R=e.sig,a(o,200,await ts(t,{serviceHealth:async()=>e,fresh:r,engineAt:d.engineAt}))}if($s.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${ue}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const F=ws(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 W=null,k=null,ie=K,Fe=0,Ae=0,Jt=0,ke=!1,Pe=!1,jt="",Ne=!0;const ae=t.logRequests&&F.redactable&&n.method==="POST"?gs(ee):null,Ko=Date.now();if(F.redactable&&n.method==="POST"&&K.length){try{k=JSON.parse(K.toString("utf8"))}catch{k=null}if(k&&bs(k,F.kind))ie=K;else if(k){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(k.tools)&&k.tools.length){const g=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):ds,b=e.narrowAll?null:O=>!cs.test(Ro(O)),v=k.tools.length;k.tools=lr(k.tools,ms(k,F.kind),{cap:g,keep:b,name:Ro,description:us}),Jt=v-k.tools.length}if(Ne=await Te(t.pro?.entitlementToken),ke=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&H(n),!ke){const g=dt(k?.model,t,F.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:()=>!1}),b=g?.type==="api"?await d.decide(g,k?.model).catch(()=>null):null;Pe=b?.redact===!1,jt=Pe?b.engine||"declared":""}if(!ke&&!Pe){const g=Wa(t,Ne);if(!g.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${g.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}})}!ke&&!Pe&&await rt(t);const r=ke?[]:F.adapter.collectSegments(k,t.redaction,{skipPublic:H(n)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=ae?ae.clock():0,{vault:c,count:m,sanitized:h}=ke?{vault:null,count:0,sanitized:0}:await Ze(r,t.redaction,{signal:s.signal,isPro:Ne,sanitizeOnly:Pe,onEgress:g=>Nt.push(Mo({ts:Date.now(),client:"redaction",tool:`detect:${g.backend}@${g.host||"local"}`,ok:g.ok,ms:g.ms,error:g.error}))});if(ae&&ae.lap("redact",l),F.adapter.joinTextParts?.(k),W=c,Fe=m,Ae=h||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!Ne&&m>0){Ka(t,Ne);try{be(t,ce())}catch{}}if(!ke&&!Pe&&Array.isArray(k.tools)&&k.tools.length&&typeof F.adapter.injectSystemNote=="function"){const g=dt(k?.model,t,F.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:v=>!!v.service&&_.fn(v.id)==="down"}),b=!(g&&g.type==="api");F.adapter.injectSystemNote(k,cr({toolData:t.tools?.toolData,ownTools:b}))}else!ke&&m>0&&typeof F.adapter.injectSystemNote=="function"&&F.adapter.injectSystemNote(k,ur());ie=Buffer.from(JSON.stringify(k),"utf8")}}const zt=dr({vault:W,toolData:t.tools?.toolData}),We=k&&typeof k.chatpanel=="object"&&k.chatpanel||null;if(We&&(delete k.chatpanel,ie=Buffer.from(JSON.stringify(k),"utf8")),typeof k?.model=="string"&&k.model.startsWith("fusion:")){const e=Nn(k.model,t,await j());if(e?.error)return ae?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(k.model=e.model,ie=Buffer.from(JSON.stringify(k),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const se={destination:String(n.headers["x-chatpanel-destination"]||We?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||We?.reach||"").trim(),run:Lt(n.headers["x-chatpanel-run"],We?.run)},Ke=await j(),Gt=e=>!!e.service&&Ke(e.id)==="down";let N=dt(k?.model,t,F.kind,{destination:se.destination,down:Gt});N?.type==="agent"&&k?.model&&!se.destination&&!ns(N,k.model)&&(await rs(t,{serviceHealth:async()=>Ke,engineAt:d.engineAt}),N=dt(k?.model,t,F.kind,{destination:se.destination,down:Gt}));const Ht=N?.service&&Ke(N.id)==="down"?await P().revive(N.service).catch(()=>null):null;if(Ht?.ok&&(_.at=0),N?.service&&Ke(N.id)==="down"&&!Ht?.ok)return ae?.commit(),a(o,503,{error:{message:`${N.id} is not running — the model ${JSON.stringify(k?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:N.service}});if(se.destination&&(!N||N.id!==se.destination))return ae?.commit(),a(o,404,{error:{message:`no destination "${se.destination}" is configured on this gateway`,type:"unknown_destination",known:os(t).map(e=>e.id)}});const le=nt(n.headers);if(le&&!na(le,N?.type==="api"?"api":"agent"))return ae?.commit(),a(o,403,{error:{message:`link: partner "${le.partner}" may not use ${N?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${le.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const Qe=le&&F.redactable&&n.method==="POST"&&k?{caller:le,surface:Tn(le,le.kind==="partner"?"":y?.deviceNameOf(le.device)),model:k.model||null,startedAt:Ko}:null;ae&&(ae.meta={t:Date.now(),model:k?.model||null,dest:N?N.id:null,type:N?N.type:null,redacted:Fe,sanitized:Ae,narrowed:Jt,detail:zo(W,t.logDetail),redaction:ke?"off":Pe?`on-device (${jt})`:t.redaction.tier||"basic",...le?.kind==="partner"?{via:aa(le)}:{}});const Ye=qe();if(Ye&&N){const e=N.type==="api"?qt(Ye,{model:k?.model||"",endpoint:N.baseUrl||""}):Er(Ye,N.agent||N.id)?qt(Ye,{model:k?.model||""}):{ok:!1,reason:`agent "${N.agent||N.id}" is not allowed by your organisation’s policy`};if(!e.ok)return ae?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(N&&N.type==="api")return N.baseUrl?vs(N.baseUrl,t)?(ae?.commit(),a(o,508,{error:{message:`destination "${N.id}" points back at the gateway (${N.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):As(n,o,{...F,pathname:i,search:f.search,base:N.baseUrl,destKey:N.apiKey,destProtocol:N.protocol,harness:zt,trace:ae,link:Qe&&{...Qe,agentId:N.id,dest:{type:"api",id:N.id}}},ie,W):(ae?.commit(),a(o,502,{error:`destination "${N.id}" has no baseUrl`}));const mt=Le(n),Ut=mt==="local"&&t.bridge?.openAgentLane?"token":mt;if(Ut==="local")return ae?.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 Vt=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),Qo=new Set(["thread","ephemeral","workingDir","worker"]),pt=le?.kind==="partner";if(mt==="token"&&n.headers["x-chatpanel-link-device"]&&!pt&&!(se.run&&Object.keys(se.run).some(e=>!Qo.has(e)))){const e=Lt(null,co(lo(me.get("agentTools").agentTools?.value,N?.agent||k?.model)));e&&(se.run={...e,...se.run||{}})}if(pt){const e=Lt(null,co(lo(me.get("agentTools").agentTools?.value,N?.agent||k?.model)));se.run={...e||{},...sa(se.run,le.device)};const r=y?.partnerFolderOf(le.device);if(!r)return ae?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});se.run.workingDir=r,se.reach="",Array.isArray(k?.tools)&&(k.tools=k.tools.filter(s=>!fo(s?.function?.name??s?.name)))}const Be=pr({...se.run||{},...se.reach?{reach:se.reach}:{},...Vt?{askDepth:Vt}:{}},Ut);Be.reach&&o.setHeader("x-chatpanel-reach-used",Be.reach);const Yo=pt?{inbox:w,partner:le.partner,device:le.device,conversation:Be.thread?.id||null}:null,Xo=Qe&&{...Qe,dest:{type:"agent",id:N?.id||"bridge"},threadId:Be.thread?.id||null};return _s(n,o,{...F,pathname:i,agentOverride:N?.agent,harness:zt,trace:ae,run:Object.keys(Be).length?Be:null,owner:Yo,link:Xo},k,W,t,Ne)});return pe.on("close",()=>{E?.stop("closed"),zn(),p.close(),y?.stop(),w.stop()}),pe.on("upgrade",(n,o,f)=>{o.on("error",()=>{});const i=String(n.url||"").split("?")[0];if(y&&i.startsWith(ra)){y.acceptTunnel(n,o,f).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
64
64
  connection: close\r
65
65
  content-length: 0\r
66
66
  \r
67
- `)}catch{}}),ue.once("listening",()=>{P()}),ue.linkHost=y,ue.runtimeDefaults=()=>P().ensureDefaults(),ue}function Lt(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 p={};if(Array.isArray(u.grants)&&(p.grants=u.grants.map(y=>String(y).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const y=u.workspace;p.workspace={repo:String(y.repo).slice(0,400),projectId:String(y.projectId||"").slice(0,120),jobId:String(y.jobId||"").slice(0,120),...y.base?{base:String(y.base).slice(0,120)}:{}}}if(u.connectionId&&(p.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(p.workingDir=u.workingDir.trim().slice(0,1024)),Xa.includes(u.permissionMode)&&u.permissionMode!=="default"&&(p.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const y=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(T=>String(T).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),$=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(T=>String(T).slice(0,1024)).filter(Boolean).slice(0,32),B=u.sandbox.outside===!0,E=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(T=>String(T).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(y.length||$.length||B||E.length)&&(p.sandbox={...y.length?{hosts:y}:{},...$.length?{write:$}:{},...B?{outside:!0}:{},...E.length?{signIn:E}:{}})}const w=Kr(u.thread);return w&&(p.thread=w),u.ephemeral===!0&&(p.ephemeral=!0),u.worker===!0&&(p.worker=!0,p.ephemeral=!0),u.lean===!0&&(p.lean=!0,p.ephemeral=!0),Object.keys(p).length?p:null}let Ve=null,ut=null;async function Sl(t=Wt()){Hr();let d=null;try{d=await _r()}catch(T){throw T instanceof Or&&(console.error(`[chatpanel-gateway] org policy: ${T.message}`),process.exit(78)),T}const u=d?.policy||null;u&&(Zt(t,u),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`));const p=Tr({enabled:Xt(t)});console.log(`[chatpanel-gateway] certificates: ${p.on?`this computer's list is trusted too (${p.added} added to the runtime's own)`:`the runtime's own list only — ${p.why}`}`),kr(globalThis,{allow:u?.egress?(T,{local:x})=>Pr(u,T,{local:x}):null}),_e();const w=As(t),y=jr(t),$=tr(t);let B=!1;w.on("error",T=>{if(T&&T.code==="EADDRINUSE"){const x=ct(t.host)?"127.0.0.1":t.host;fetch(`http://${x}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(R=>R.ok?R.json():null).catch(()=>null).then(R=>{const j=!!(R?.version&&typeof R.tier=="string"),V=Qr({name:"gateway",self:de,holder:j?{ours:j,version:R.version}:null,managedBy:Yr(process.env),port:t.port});if(V.action==="standby"||B&&!R){if(!B)for(const P of V.lines)console.error(P);B=!0,setTimeout(()=>w.listen(t.port,t.host),Xr);return}if(j){const P=R.managedBy?` (run by ${R.managedBy})`:"";for(const[U,z]of V.lines.entries())console.error(U===0?z.replace(` on ${t.port}`,` at http://${x}:${t.port}${P}`):z)}else{const P=mn(t.port);console.error(`Port ${t.port} is held by ${P||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${le()} (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: ${T?.message||T}`),process.exit(1)}),w.listen(t.port,t.host,()=>{B&&console.log(" standby : the other gateway is gone — this copy has the port now"),B=!1,console.log(`ChatPanel Privacy Gateway v${de} on http://${t.host}:${t.port}`),w.linkHost?.start().catch(T=>console.log(` link : not started (${T?.message||T})`)),w.runtimeDefaults?.().then(T=>{for(const x of T||[])console.log(` ${x.label.toLowerCase().padEnd(9).slice(0,9)}: ${x.ok?x.already?"running":x.adopted?"already running — adopted":"started":`not started (${x.skipped})`}`)}).catch(T=>console.log(` runtime : defaults not started (${T?.message||T})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token");for(const T of qa(t))console.log(` ⚠ sandbox : ${T}`);console.log(` confined : ${wn(wt({stateDir:He.dirname(le())}))}`),ut={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},un(t,{childEnv:()=>({...Za(t,process.env,qe()),...Ya(t)})}).then(T=>{Ve=T}).catch(T=>{ut={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${T?.message||T})`},console.log(` bridge : not supervised (${T?.message||T})`)}),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…)":"")),ct(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.`)}),io()&&kt(J,ft()).then(T=>{T?.ok&&(console.log(` warm : seeded ${T.ingested} records from ${T.file}`),T.whole&&Ue())}).catch(()=>{});const E=()=>{y?.stop(),$.stop(),Ve?.stop(),is(w)};return process.on("SIGINT",E),process.on("SIGTERM",E),w}export{vs as RECORDS_MAX_BYTES,_l as VERSION,As as createGateway,_s as joinUpstream,Bt as parseAgentModel,Sl as start};
67
+ `)}catch{}}),pe.once("listening",()=>{P()}),pe.linkHost=y,pe.runtimeDefaults=()=>P().ensureDefaults(),pe}function Lt(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 p={};if(Array.isArray(u.grants)&&(p.grants=u.grants.map(y=>String(y).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const y=u.workspace;p.workspace={repo:String(y.repo).slice(0,400),projectId:String(y.projectId||"").slice(0,120),jobId:String(y.jobId||"").slice(0,120),...y.base?{base:String(y.base).slice(0,120)}:{}}}if(u.connectionId&&(p.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(p.workingDir=u.workingDir.trim().slice(0,1024)),Za.includes(u.permissionMode)&&u.permissionMode!=="default"&&(p.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const y=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(T=>String(T).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),$=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(T=>String(T).slice(0,1024)).filter(Boolean).slice(0,32),B=u.sandbox.outside===!0,E=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(T=>String(T).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(y.length||$.length||B||E.length)&&(p.sandbox={...y.length?{hosts:y}:{},...$.length?{write:$}:{},...B?{outside:!0}:{},...E.length?{signIn:E}:{}})}const w=Kr(u.thread);return w&&(p.thread=w),u.ephemeral===!0&&(p.ephemeral=!0),u.worker===!0&&(p.worker=!0,p.ephemeral=!0),u.lean===!0&&(p.lean=!0,p.ephemeral=!0),Object.keys(p).length?p:null}let Ve=null,ut=null;async function Tl(t=Wt()){Hr();let d=null;try{d=await _r()}catch(T){throw T instanceof Or&&(console.error(`[chatpanel-gateway] org policy: ${T.message}`),process.exit(78)),T}const u=d?.policy||null;u&&(Zt(t,u),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`));const p=Tr({enabled:Xt(t)});console.log(`[chatpanel-gateway] certificates: ${p.on?`this computer's list is trusted too (${p.added} added to the runtime's own)`:`the runtime's own list only — ${p.why}`}`),kr(globalThis,{allow:u?.egress?(T,{local:_})=>Pr(u,T,{local:_}):null}),_e();const w=Ns(t),y=jr(t),$=tr(t);let B=!1;w.on("error",T=>{if(T&&T.code==="EADDRINUSE"){const _=ct(t.host)?"127.0.0.1":t.host;fetch(`http://${_}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(R=>R.ok?R.json():null).catch(()=>null).then(R=>{const j=!!(R?.version&&typeof R.tier=="string"),V=Qr({name:"gateway",self:ue,holder:j?{ours:j,version:R.version}:null,managedBy:Yr(process.env),port:t.port});if(V.action==="standby"||B&&!R){if(!B)for(const P of V.lines)console.error(P);B=!0,setTimeout(()=>w.listen(t.port,t.host),Xr);return}if(j){const P=R.managedBy?` (run by ${R.managedBy})`:"";for(const[U,z]of V.lines.entries())console.error(U===0?z.replace(` on ${t.port}`,` at http://${_}:${t.port}${P}`):z)}else{const P=mn(t.port);console.error(`Port ${t.port} is held by ${P||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${ce()} (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: ${T?.message||T}`),process.exit(1)}),w.listen(t.port,t.host,()=>{B&&console.log(" standby : the other gateway is gone — this copy has the port now"),B=!1,console.log(`ChatPanel Privacy Gateway v${ue} on http://${t.host}:${t.port}`),w.linkHost?.start().catch(T=>console.log(` link : not started (${T?.message||T})`)),w.runtimeDefaults?.().then(T=>{for(const _ of T||[])console.log(` ${_.label.toLowerCase().padEnd(9).slice(0,9)}: ${_.ok?_.already?"running":_.adopted?"already running — adopted":"started":`not started (${_.skipped})`}`)}).catch(T=>console.log(` runtime : defaults not started (${T?.message||T})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token");for(const T of es(t))console.log(` ⚠ sandbox : ${T}`);console.log(` confined : ${wn(wt({stateDir:He.dirname(ce())}))}`),ut={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},un(t,{childEnv:()=>({...qa(t,process.env,qe()),...Xa(t)})}).then(T=>{Ve=T}).catch(T=>{ut={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${T?.message||T})`},console.log(` bridge : not supervised (${T?.message||T})`)}),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…)":"")),ct(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.`)}),io()&&kt(J,ft()).then(T=>{T?.ok&&(console.log(` warm : seeded ${T.ingested} records from ${T.file}`),T.whole&&Ue())}).catch(()=>{});const E=()=>{y?.stop(),$.stop(),Ve?.stop(),ls(w)};return process.on("SIGINT",E),process.on("SIGTERM",E),w}export{ks as RECORDS_MAX_BYTES,Ol as VERSION,Ns as createGateway,Os as joinUpstream,Bt as parseAgentModel,Tl as start};
package/src/stt-engine.js CHANGED
@@ -1 +1 @@
1
- import{join as Qe}from"node:path";import{deflateSync as Je}from"node:zlib";import ve from"node:os";import{existsSync as Ze,readdirSync as et}from"node:fs";import{randomUUID as tt}from"node:crypto";import{ensureLib as Ne,modelRoot as Oe}from"./ner-engine.js";import{runtimeDtype as ie,runtimeName as Pe,DTYPE_SUFFIX as nt}from"./model-runtime.js";import{verifyModelWeights as ot}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Re,isEnglishOnly as me,sttModelDtype as he,isKnownSttModel as rt,sttModelEngine as G}from"./stt-models.js";import*as K from"./parakeet-engine.js";import*as _e from"./coreml-stt-engine.js";import*as ne from"./indic-engine.js";import*as j from"./diarize-engine.js";import*as Y from"./segment-engine.js";import{turnsFromSpans as lt,mainLocal as at,timeByLocal as st,audioOfLocal as it}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as ct}from"./diarize-models.js";import*as oe from"./translate-engine.js";import*as Z from"./indictrans-engine.js";import{rawOrtAvailable as ut}from"./ort.js";import*as R from"./vad-engine.js";import*as ee from"./echo-pair.js";import{mostlyEcho as ft}from"./aec-engine.js";import{pickSegmentLanguage as dt,detectTextLanguage as gt,needsTranslation as pt,localTranslatable as mt,normalizeLanguages as ht,normalizeLanguage as _t,decodeLanguages as wt,lineLanguage as yt,autoCandidates as Mt,AUTO_LEARN_CONFIDENCE as Tt,AUTO_LEARN_SECONDS as St,ANY_LANGUAGE_CONFIDENCE as Et,AUTO_LANGUAGES as Lt}from"@chatpanel/events/speech-language.js";import{makeWarmTimer as we}from"./warm-timer.js";const g=16e3,Fe=g,Ce=3*g,At=2,xt=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function kt(e,t){if(t>At*g)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?xt.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const bt=12,ye=3;function Dt(e){const t=String(e||"").split(/\s+/).filter(Boolean);if(t.length<ye)return{text:String(e||"").trim(),removed:0,total:t.length};const n=l=>l.toLowerCase().replace(/[^\p{L}\p{N}']/gu,""),o=[];let r=0;for(let l=0;l<t.length;){let i=0,s=0;for(let a=1;a<=bt&&l+a*ye<=t.length;a++){let c=1;for(;l+(c+1)*a<=t.length&&t.slice(l+c*a,l+(c+1)*a).every((u,p)=>n(u)===n(t[l+p]));)c++;c>=ye&&(c-1)*a>i&&(i=(c-1)*a,s=a)}i?(o.push(...t.slice(l,l+s)),r+=i,l+=s+i):(o.push(t[l]),l++)}return{text:o.join(" "),removed:r,total:t.length}}const vt=.6,$e=2.4;function He(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/Je(t).length}function Nt(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function Ot({cores:e=ve.availableParallelism?.()??ve.cpus().length,env:t=process.env}={}){const n=Number(t.CHATPANEL_STT_THREADS);return Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(e/2)))}function re(e){return{intraOpNumThreads:Ot(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Pt=.12,ze=.8,Rt=.15,Ft=.5,Ct=1.2,Ue=(e,t)=>e>=Ft||e>=Rt&&!(t<Ct),$t=.999,Ht=2.5;function ce(e={},t=1/0){return Ue(e.en??0,t)?"en":Object.entries(e).sort((n,o)=>o[1]-n[1])[0]?.[0]||null}function zt(e,t=[]){const n=[];return e.forEach((o,r)=>{const l=t[r]??o.lang,i=n[n.length-1];i&&i.lang===l?i.to=o.to:n.push({from:o.from,to:o.to,lang:l})}),n}function Ut(e,{base:t=null,rate:n=g}={}){const o=e||[],r=a=>{const[c,u]=Object.entries(a.scores||{}).sort((p,v)=>v[1]-p[1])[0]||[];return c&&c!=="en"&&u>=$t?c:null},l=new Array(o.length).fill(null);for(let a=0;a<o.length;){const c=r(o[a]);let u=a+1;if(c)for(;u<o.length&&r(o[u])===c;)u++;if(c&&(o[u-1].to-o[a].from)/n>=Ht)for(let p=a;p<u;p++)l[p]=c;a=u}const i=[];let s=t;return o.forEach((a,c)=>{l[c]?s=l[c]:s!=="en"&&Ue(a.scores?.en??0,(a.to-a.from)/n)&&(s="en");const u=i[i.length-1];u&&u.lang===s?u.to=a.to:i.push({from:a.from,to:a.to,lang:s})}),i}function Gt(e,t,{frame:n=Math.round(.03*g),minPause:o=Pt*g,minPiece:r=ze*g}={}){const l=[];let i=0,s=-1;for(let a=0;a+n<=e;a+=n){const c=t(a,a+n)===!1;if(c&&s<0&&(s=a),(!c||a+2*n>e)&&s>=0){const u=c?a+n:a,p=Math.round((s+u)/2);u-s>=o&&p-i>=r&&e-p>=r&&(l.push(p),i=p),s=-1}}return l}const jt=.12;function Bt(e,t=Math.round(.03*g)){const n=Math.floor(e.length/t);if(n<3)return 0;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=J(e,r*t,(r+1)*t);return o.sort(),Math.max(1e-4,o[Math.floor(n*.9)]*jt)}let m="off",L=null,h=null,b=null,q=null,M=null,W=null,N=null;function Kt(e=L||Re,t=he(e)||ie()){if(G(e)==="parakeet-tdt")return K.parakeetOnDisk(e,K.parakeetDtype(t));if(G(e)==="coreml-tdt")return _e.coremlOnDisk(e);if(G(e)==="indic-canary")return ne.indicOnDisk();const n=Qe(Oe(),...e.split("/"),"onnx");if(!Ze(n))return!1;const o=nt[t]??"";try{const r=et(n);return r.includes(`encoder_model${o}.onnx`)&&r.some(l=>l===`decoder_model_merged${o}.onnx`||l===`decoder_model${o}.onnx`)}catch{return!1}}function bn(){return m}function ue(){return m==="ready"&&!!h}function Dn(){return M}function vn(){return{configured:m!=="off",ok:ue(),state:m,model:L,dtype:W,runtime:Pe(),error:b,warmMs:N?.warmMs??null,vad:R.state()}}function Nn(){return!!N?.pending()}function le(){return $.size>0||m==="loading"||m==="downloading"}async function Me({log:e=()=>{}}={}){if(le())return!1;N?.disarm();const t=h;if(h=null,q=null,W=null,M=null,b=null,m="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((N?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function Ge(e){return e.then(t=>(t&&!le()&&N?.arm(),t))}async function je(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(G(e)==="parakeet-tdt")return Wt(e,{log:t,allowDownload:n,dtype:o});if(G(e)==="coreml-tdt")return It(e,{log:t,allowDownload:n});if(G(e)==="indic-canary")return Yt(e,{log:t,allowDownload:n,licenseAccepted:r});const l=h,i=L;let s;try{s=await Ne()}catch(T){return m="error",b=`engine load failed: ${T.message}`,t(`[stt] transformers.js not available (${T.message}) — dictation falls back to the browser engine`),!1}const c=(o&&o!=="auto"?o:null)||he(e)||ie(),u=Kt(e,c);if(s.env.allowRemoteModels=u?!1:!!n,!u&&!n)return m="error",b="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const p=s.env.remoteHost,v=!rt(e);if(!u&&v)try{s.env.remoteHost="https://huggingface.co/"}catch{}m=u?"loading":"downloading",u||(M={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${v?", from Hugging Face":""})…`));try{const T=f=>{if(!f)return;const H=typeof f.progress=="number"?Math.round(f.progress):M?.pct??0;f.status==="progress"||f.status==="download"||f.status==="initiate"?M={model:e,file:f.file||M?.file||null,pct:H}:f.status==="done"&&f.file&&t(`[stt] fetched ${f.file}`)};let S;try{S=await s.pipeline("automatic-speech-recognition",e,{dtype:c,progress_callback:T,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:re()}})}catch(f){if(u||v||!n)throw f;t(`[stt] mirror fetch failed (${String(f.message).slice(0,80)}) — retrying from Hugging Face…`),s.env.remoteHost="https://huggingface.co/",s.env.allowRemoteModels=!0,S=await s.pipeline("automatic-speech-recognition",e,{dtype:c,progress_callback:T,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:re()}})}if(!u)try{ot(e,{modelsDir:Oe(),log:t})}catch(f){try{await S.dispose?.()}catch{}throw f}if(h=S,L=e,m="ready",b=null,M=null,W=c,l&&l!==S)try{await l.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${c} (in-process, offline) — local dictation active`),!0}catch(T){return b=T.message,M=null,l?(h=l,L=i,m="ready"):m="error",t(`[stt] model load failed (${T.message})${l?" — keeping previous model":""}`),!1}finally{try{s.env.remoteHost=p}catch{}}}async function Wt(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=h,l=L,i=K.parakeetDtype(o&&o!=="auto"?o:Xt()),s=K.parakeetOnDisk(e,i);if(!s&&!n)return m="error",b="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;m=s?"loading":"downloading",s||(M={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const a=await K.loadRecognizer({modelId:e,dtype:i,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:re(),onProgress:u=>{M={model:e,file:u.file||null,pct:typeof u.pct=="number"?u.pct:M?.pct??0}}}),c=async u=>({text:await a.transcribe(u)});if(c.__transducer=!0,c.dispose=()=>a.dispose(),h=c,L=e,m="ready",b=null,M=null,W=i,r&&r!==c)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(a){return b=a.message,M=null,r?(h=r,L=l,m="ready"):m="error",t(`[stt] model load failed (${a.message})${r?" — keeping previous model":""}`),!1}}function Xt(){return K.PARAKEET_DEFAULT_DTYPE}const Be="fp16";async function It(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=h,r=L,l=_e.coremlOnDisk(e);if(!l&&!n)return m="error",b="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;m=l?"loading":"downloading",l||(M={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let i=null;const s=await _e.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:a=>{M={model:e,file:a.file||null,pct:typeof a.pct=="number"?a.pct:M?.pct??0}},onExit:a=>{h===i&&(h=null,q=null,m="error",b=a,N?.disarm(),t(`[stt] ${a} — reloads on the next dictation`))}});if(i=async a=>({text:await s.transcribe(a)}),i.__transducer=!0,i.dispose=()=>s.dispose(),h=i,L=e,m="ready",b=null,M=null,W=Be,o&&o!==i)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${s.version}, windows ${s.windows.join("/")} s, offline) — local dictation active`),!0}catch(i){return b=i.message,M=null,o?(h=o,L=r,m="ready"):m="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}async function Yt(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=h,l=L,i=ne.indicOnDisk();if(!i&&!n)return m="error",b="model not on disk and downloads disabled",!1;m=i?"loading":"downloading",i||(M={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from Hugging Face)…`));try{i||await ne.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:c=>{M={model:e,file:c.file,pct:c.pct}}});const s=await ne.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:re(),log:t}),a=async(c,u={})=>s.transcribe(c,u);if(a.identify=(c,u)=>s.identify(c,u),a.__transducer=!0,a.__indic=!0,a.dispose=()=>s.dispose(),h=a,L=e,m="ready",b=null,M=null,W="int8",r&&r!==a)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${ne.INDIC_LICENSE.attribution}`),!0}catch(s){return b=s.message,M=null,r?(h=r,L=l,m="ready"):m="error",t(`[stt] model load failed (${s.message})${r?" — keeping previous model":""}`),!1}}const qt=30;function Ke({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:o=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof o=="number"&&o<=qt||e==="download"?{allowDownload:!0}:null}function Te(e,{log:t=()=>{},warmMs:n,allowDownload:o=!0}={}){const r=Ke({mode:e,onDisk:j.modelOnDisk(),ready:j.isReady(),approxMB:ct(j.activeModel())});if(r&&j.init({allowDownload:r.allowDownload&&o!==!1,warmMs:n,onLog:t}),e==="off"||Se)return;const l=Ke({mode:e,onDisk:Y.modelOnDisk(),ready:Y.isReady(),approxMB:Y.SEGMENT_MODEL_APPROX_MB});l&&Y.init({allowDownload:l.allowDownload&&o!==!1,warmMs:n,onLog:t})}let Se=!1,Ee=null;function Le(e={},{log:t=()=>{}}={}){e.vad!==!1&&(Ee={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},(R.state()==="off"||R.state()==="error")&&R.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function On(e={}){if(q&&m!=="error")return q;const t=typeof e.onLog=="function"?e.onLog:()=>{};return L=e.model||Re,Se=e.segment===!1,m="loading",N=we({warmMs:e.warmMs,busy:le,log:t,unload:()=>Me({log:t})}),q=Ge(je(L,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Te(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),Le(e,{log:t})),n)),q}async function Pn(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(Se=t.segment===!1);const o=G(e)==="parakeet-tdt"?K.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:K.PARAKEET_DEFAULT_DTYPE):G(e)==="coreml-tdt"?Be:G(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:he(e)||ie();if(e===L&&ue()&&W===o)return Te(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;N??=we({warmMs:t.warmMs,busy:le,log:n,unload:()=>Me({log:n})});const r=await Ge(je(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Te(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),Le(t,{log:n})),r}const Vt=8,Qt=12e4,Jt=6e4,Zt=1200,fe=12,Ae=700,xe=.008,en=.002,tn=4;function nn(e){return e>0?Math.min(xe,Math.max(en,e*tn)):xe}function on(e){const t=Math.round(.1*g),n=Math.floor(e.length/t);if(n<5)return null;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=J(e,r*t,(r+1)*t);return o.sort(),o[Math.floor(n*.1)]}const We=30,rn=15e3,$=new Map,V=new Map;let Q=Promise.resolve();function Rn(){return $.size}const ln=300,an=3e3;function sn(e){const t=Number(e);return Number.isFinite(t)?Math.min(an,Math.max(ln,Math.round(t))):Ae}function Fn({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:l=!1,diarize:i=!1,speakerLabel:s=null,endSilenceMs:a=Ae,interims:c=!0,remote:u=null,poll:p=!1,format:v="f32"}={}){if($.size>=Vt){const H=new Error("too many concurrent dictation sessions");throw H.code="too_many_sessions",H}const T=Array.isArray(t)?ht(t):null,S=typeof e=="string"&&e?e.slice(0,12):null,f={id:tt(),format:v==="pcm16"?"pcm16":"f32",endSilenceMs:sn(a),lang:T?T.length===1?T[0]:T.length?null:S:S,langs:T,lastLang:null,lastDecoded:null,learned:new Set,translateTo:_t(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?ee.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!l,diarize:!!i,speakerLabel:typeof s=="string"&&s?s.slice(0,40):null,diarizer:i?new j.Diarizer:null,remote:u||null,interims:c!==!1&&!u,chunks:[],samples:0,listeners:new Set,poll:p?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return $.set(f.id,f),N?.disarm(),f.diarizer&&(j.retain(),Y.retain()),f.translateTo&&(oe.retain(),Z.retain()),R.retain(),Ee&&(R.state()==="off"||R.state()==="error")&&Le(Ee),Xe(f),{id:f.id}}function de(e){return $.get(String(e||""))||null}function Cn(e,t){const n=de(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function X(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function $n(e){const t=String(e||""),n=$.get(t);if(n)return n.poll?n.poll.splice(0):null;const o=V.get(t);return o?(clearTimeout(o.timer),V.delete(t),o.session.poll.splice(0)):null}function Hn(e){return V.get(String(e||""))?.session||null}function Xe(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>dn(e.id).catch(()=>{}),Jt),e.idleTimer.unref?.()}function zn(e,t){const n=de(e);if(!n||n.closed){const o=new Error("no such session");throw o.code="no_session",o}if(!(!(t instanceof Float32Array)||!t.length)){if(Xe(n),n.echo?.role==="mic"){ee.pushMic(n.echo,t),Ie(n);return}n.echo?.role==="reference"&&ee.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,Ie(n)}}function Un(e){const t=de(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),Q=Q.then(()=>ke(t).catch(()=>{})),Q)}function Gn(e,t="f32"){if(t==="pcm16"){const r=new Float32Array(Math.floor(e.length/2));for(let l=0;l<r.length;l++)r[l]=e.readInt16LE(l*2)/32768;return r}const n=e.length-e.length%4,o=new Float32Array(n/4);for(let r=0;r<o.length;r++)o[r]=e.readFloatLE(r*4);return o}function Ie(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+Zt-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,Q=Q.then(()=>ke(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function Ye(e){const t=new Float32Array(e.samples);let n=0;for(const o of e.chunks)t.set(o,n),n+=o.length;return t}function cn(e,t,n){const o=g/100,r=Math.max(0,e.length-t),l=Math.floor((e.length-r)/o),i=Math.max(1,Math.round(n/o));if(l<=i)return 0;const s=new Float32Array(l);for(let p=0;p<l;p++){let v=0;const T=r+p*o;for(let S=0;S<o;S++)v+=e[T+S]*e[T+S];s[p]=v/o}let a=-1,c=1/0,u=0;for(let p=0;p<i;p++)u+=s[p];for(let p=0;p+i<=l;p++)p>0&&(u+=s[p+i-1]-s[p-1]),u<c&&(c=u,a=p);return a<0?0:r+Math.round((a+i/2)*o)}function J(e,t=0,n=e.length){let o=0;const r=Math.max(1,n-t);for(let l=t;l<n;l++)o+=e[l]*e[l];return Math.sqrt(o/r)}function un(e,t=xe){const n=Math.round(.02*g);let o=0,r=e.length;for(let l=0;l+n<=e.length;l+=n)if(J(e,l,l+n)>=t){o=l;break}for(let l=e.length-n;l>=0;l-=n)if(J(e,l,l+n)>=t){r=l+n;break}return r>o?e.subarray(o,r):e}async function qe(e){try{const t=await Ne(),n=h?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const o=e.length>g*8?e.subarray(0,g*8):e,r=await h.processor(o),l=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),i=await h.model({...r,decoder_input_ids:l}),s={};for(const[a,c]of Object.entries(n.lang_to_id))s[a.slice(2,-2)]=Number(i.logits.data[c]);return s}catch{return null}}async function fn(e){const t=await qe(e);if(!t)return null;let n=null,o=-1/0;for(const[r,l]of Object.entries(t))l>o&&(o=l,n=r);return n}async function ke(e,{flush:t=!1}={}){if(e.closed&&!t)return;if(e.echo?.role==="mic"){const d=await ee.drain(e.echo,{force:t});d.length&&(e.chunks.push(d),e.samples+=d.length,e.pushed+=d.length)}if(!e.remote&&!ue()||!e.samples)return;e.lastDecodeAt=Date.now();let n=Ye(e);const o=n.length,r=Math.max(0,(e.pushed||0)-e.samples),l=Math.round((e.endSilenceMs||Ae)/1e3*g),i=on(n);i!==null&&(e.noiseFloor==null||i<e.noiseFloor)&&(e.noiseFloor=i);const s=nn(e.noiseFloor);let a=null,c=null;R.isReady()&&(e.vad||=R.createStream(),await e.vad.advance(n,r)&&(a=e.vad.speechIn(r,r+n.length,R.ONSET),n.length>l&&(c=e.vad.speechIn(r+n.length-l,r+n.length,R.OFFSET))));const u=n.length>l&&(c!==null?!c:J(n,n.length-l)<s);if(a===!1||a===null&&J(n)<s){n.length>g*5&&(e.chunks=[n.subarray(n.length-g)],e.samples=g);return}if(!e.interims&&!t&&!u&&n.length<fe*g)return;let p=null;if(!t&&!u&&o>=fe*g&&o<We*g){const d=cn(n,3*g,Math.round(.2*g));d>0&&d<n.length&&(p=n.subarray(d),n=n.subarray(0,d))}const v=!e.remote&&!me(L)&&!h?.__transducer;if(v&&!e.langs&&!e.lang&&!e.langTried&&n.length>=g){e.langTried=!0;const d=await fn(n);d&&(e.lang=d,X(e,{type:"language",lang:d}))}const T=t||u||o>=fe*g;let S=e.lang;if(v&&e.langs&&!e.lang){const d=e.langs.length>0,O=d?wt(e.langs):Mt([...e.learned]);if(O.length===1)S=O[0];else if(S=O.includes(e.lastDecoded)?e.lastDecoded:null,(T||!S)&&n.length>=g/2){const x=await qe(n);if(x){const y=dt({scores:x,allowed:O,seconds:n.length/g,last:e.lastDecoded});S=!d&&!y.inherited&&y.confidence<Et?e.lastDecoded||"en":y.lang,!d&&T&&!y.inherited&&y.confidence>=Tt&&n.length>=St*g&&e.learned.add(y.lang)}}T&&S&&(e.lastDecoded=S)}let f="",H=null,z=null,ge=null;try{if(e.remote){const d=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});f=d.text,ge=d.lang||null}else{const d=h.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:ce}:e.lang?{lang:e.lang}:{langs:[...Lt],last:e.lastLang,choose:ce}:me(L)?{}:{language:S||void 0,task:"transcribe"},O=h.__indic&&h.identify&&T&&d.langs&&n.length>=2*ze*g?Gt(n.length,(y=>(_,D)=>J(n,_,D)>=y)(Bt(n))):[];let x=null;if(O.length){const y=await h.identify(n,{langs:d.langs}),_=[0,...O,n.length],D=[];for(let k=0;k+1<_.length;k++){const E=await h.identify(n.subarray(_[k],_[k+1]),{langs:d.langs});D.push({from:_[k],to:_[k+1],scores:E?.scores||{}})}if(x=Ut(D,{base:y?.scores?ce(y.scores,n.length/g):null}),x.length>1){const k=[];for(let E=0;E<x.length;E++){const C=x[E],te=C.lang&&C.lang!=="en"&&(x[E-1]?.lang==="en"||x[E+1]?.lang==="en");k.push(te?ce((await h.identify(n.subarray(C.from,C.to),{langs:d.langs}))?.scores||{},(C.to-C.from)/g):C.lang)}x=zt(x,k)}x.length<2&&(x=null)}if(x){z=[];for(const _ of x){const D=await h(n.subarray(_.from,_.to),_.lang?{lang:_.lang}:{...d}),k=String(D?.text||"").trim(),E=D?.lang||_.lang||null;k&&z.push({text:k,lang:E,from:_.from,to:_.to}),E&&(d.last=E)}f=z.map(_=>_.text).join(" ");const y=new Map;for(const _ of z)_.lang&&y.set(_.lang,(y.get(_.lang)||0)+(_.to-_.from));H=[...y].sort((_,D)=>D[1]-_[1])[0]?.[0]||null,(z.length<2||y.size<2)&&(z=null)}else{const y=await h(n,d);f=String(y?.text||"").trim(),h.__indic&&(H=y?.lang||null)}}}catch(d){X(e,{type:"error",code:"decode_failed",message:d.message,fatal:!1});return}if(!f)return;{const d=Dt(f);if(d.removed&&d.removed/d.total>=vt&&d.total>=12?f="":f=d.text,f&&He(f)>$e){const O=Nt(f);f=O.replace(/[\s\p{P}]/gu,"").length<12||He(O)>$e?"":O}if(!f)return}const Ve=o>=fe*g,be=o>=We*g;if(t||u||Ve||be){const d=t?"flush":u?"silence":be?"overflow":"length",O=d==="flush"||d==="silence",x=e.samples-o,y=[];p&&y.push(p),x>0&&y.push(Ye(e).subarray(o)),e.chunks=y,e.samples=y.reduce((w,A)=>w+A.length,0),e.lastInterim="";const _=un(n,s);if(kt(f,_?_.length:0)||e.echo?.role==="mic"&&ft(ee.verdict(e.echo,r,r+n.length)))return;let D=null,k=null;if(e.diarizer)try{const w=e.speakerLabel?null:await Y.spans(n),A=w?lt(w):[];if(A.length){const P=new Map;for(const{local:F}of st(A)){const U=it(n,A,F),ae=U.length?await j.embed(U):null,se=U.length<Fe,I=U.length<Ce;P.set(F,e.diarizer.assign(ae,{pinnedLabel:null,weak:se,thin:I}))}const B=Math.round(r/g*1e3);k=A.map(F=>({startMs:B+Math.round(F.start*1e3),durationMs:Math.round((F.end-F.start)*1e3),speaker:P.get(F.local)})).filter(F=>F.speaker),D=P.get(at(A))||null}}catch{}if(e.diarizer&&!D)try{const w=_,A=w?await j.embed(w):null,P=!!w&&w.length<Fe,B=!!w&&w.length<Ce;D=e.diarizer.assign(A,{pinnedLabel:e.speakerLabel,weak:P,thin:B})}catch{}let E=null;(e.langs||e.translateTo)&&(H?E=H:ge?E=ge:me(L)&&!e.remote?E="en":v?E=yt(f,S||e.lang)||null:E=e.lang||gt(f,{allowed:e.langs||[],last:e.lastLang}).lang,E&&E!==e.lastLang&&(e.lastLang=E,X(e,{type:"language",lang:E})));const C=Math.round(r/g*1e3),te=z&&(e.langs||e.translateTo)?z.map((w,A)=>({text:w.text,lang:w.lang,startMs:C+Math.round(w.from/g*1e3),durationMs:Math.round((w.to-w.from)/g*1e3),last:A===z.length-1})):[{text:f,lang:E,startMs:C,durationMs:Math.round(n.length/g*1e3),last:!0}];for(const w of te){te.length>1&&w.lang&&w.lang!==e.lastLang&&(e.lastLang=w.lang,X(e,{type:"language",lang:w.lang}));const{text:A,lang:P,startMs:B}=w,F=(A.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(A.match(new RegExp("\\p{L}","gu"))||[]).length),U=Z.indictransLanguage(P)&&F<.5&&Z.state()!=="error"&&ut(),ae=!!e.translateTo&&pt(P,e.translateTo)&&(U||mt(A,P)&&oe.state()!=="error"),se=te.length>1&&k?k.filter(I=>I.startMs<B+w.durationMs&&I.startMs+I.durationMs>B):k;if(X(e,{type:"final",text:A,reason:d,endOfTurn:w.last?O:!1,durationMs:w.durationMs,startMs:B,...P?{lang:P}:{},...ae?{translating:!0}:{},...D?{speaker:D}:{},...se?.length?{turns:se}:{}}),ae){const I=e.translateTo,pe=U?Z:oe;pe.state()==="off"&&pe.init({...e.translateLoad,...U?{sessionOptions:re()}:{}}),e.translations=e.translations.then(async()=>{await pe.ready();const De=U?await Z.translate(A,P):await oe.translate(A);X(e,{type:"translation",startMs:B,lang:P,to:I,text:De||null,...De?{}:{failed:!0}})}).catch(()=>{})}}}else f!==e.lastInterim&&(e.lastInterim=f,X(e,{type:"interim",text:f}))}async function dn(e){const t=de(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(Q=Q.then(()=>ke(t,{flush:!0}).catch(()=>{}))),await Promise.race([t.translations,new Promise(n=>setTimeout(n,rn).unref?.())])}finally{if(X(t,{type:"end"}),t.listeners.clear(),$.delete(t.id),t.poll){const n=setTimeout(()=>V.delete(t.id),Qt);n.unref?.(),V.set(t.id,{session:t,timer:n})}t.diarizer&&(j.release(),Y.release()),t.translateTo&&(oe.release(),Z.release()),R.release(),ee.leave(t.echo),$.size===0&&ue()&&N?.arm()}return!0}function jn(){for(const e of $.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);$.clear();for(const e of V.values())clearTimeout(e.timer);V.clear(),N?.disarm(),N=null,m="off",L=null,h=null,b=null,q=null,M=null}function Bn(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){h=e,L=t,m=e?"ready":"off",W=o,n!==null&&(N=we({warmMs:n,busy:le,unload:()=>Me()}),e&&N.arm())}export{qt as AUTO_FETCH_MAX_MB,$e as COMPRESSION_LIMIT,$t as FROM_ENGLISH,Ht as FROM_ENGLISH_RUN_S,vt as LOOP_DROP,jt as PAUSE_SHARE,ze as PIECE_MIN_S,Pt as PIECE_PAUSE_S,g as SAMPLE_RATE,Ft as SURE_ENGLISH,Ce as THIN_SPEAKER_SAMPLES,Rt as TO_ENGLISH,Ct as WEAK_ENGLISH_MIN_S,Fe as WEAK_SPEAKER_SAMPLES,jn as _reset,Bn as _setPipeForTest,sn as clampEndSilence,Dt as collapseLoops,Nt as collapseRuns,He as compressionRatio,Fn as createSession,Un as decodeNow,$n as drainEvents,dn as endSession,Hn as endedSession,de as getSession,vn as health,On as init,ue as isReady,Ut as languageGroups,kt as looksHallucinated,Kt as modelOnDisk,on as noiseFloorOf,Gt as pauseCuts,Bt as pauseLevel,Dn as progress,zn as pushAudio,cn as quietestCut,zt as relabelGroups,ie as runtimeDtype,Pe as runtimeName,ce as segmentLanguage,Rn as sessionCount,Pn as setModel,nn as silenceGate,Ke as speakerPlan,bn as state,re as sttSessionOptions,Ot as sttThreads,Cn as subscribe,Gn as toFloat32,Me as unload,Nn as warmPending};
1
+ import{join as Ve}from"node:path";import{deflateSync as Qe}from"node:zlib";import ve from"node:os";import{existsSync as Je,readdirSync as Ze}from"node:fs";import{randomUUID as et}from"node:crypto";import{ensureLib as Ne,modelRoot as Pe}from"./ner-engine.js";import{runtimeDtype as se,runtimeName as Oe,DTYPE_SUFFIX as tt}from"./model-runtime.js";import{verifyModelWeights as nt}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Re,isEnglishOnly as me,sttModelDtype as he,isKnownSttModel as ot,sttModelEngine as G}from"./stt-models.js";import*as I from"./parakeet-engine.js";import*as _e from"./coreml-stt-engine.js";import*as te from"./indic-engine.js";import*as j from"./diarize-engine.js";import*as Y from"./segment-engine.js";import{turnsFromSpans as rt,mainLocal as lt,timeByLocal as at,audioOfLocal as st}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as it}from"./diarize-models.js";import*as ne from"./translate-engine.js";import*as Z from"./indictrans-engine.js";import{rawOrtAvailable as ct}from"./ort.js";import*as $ from"./vad-engine.js";import*as ee from"./echo-pair.js";import{mostlyEcho as ut}from"./aec-engine.js";import{pickSegmentLanguage as ft,detectTextLanguage as dt,needsTranslation as gt,localTranslatable as pt,normalizeLanguages as mt,normalizeLanguage as ht,decodeLanguages as _t,lineLanguage as wt,autoCandidates as yt,AUTO_LEARN_CONFIDENCE as Mt,AUTO_LEARN_SECONDS as Et,ANY_LANGUAGE_CONFIDENCE as St,AUTO_LANGUAGES as Tt}from"@chatpanel/events/speech-language.js";import*as Lt from"@chatpanel/events/speech-language.js";import{makeWarmTimer as we}from"./warm-timer.js";const p=16e3,Fe=p,$e=3*p,xt=2,At=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function kt(e,t){if(t>xt*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?At.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const bt=12,ye=3;function Dt(e){const t=String(e||"").split(/\s+/).filter(Boolean);if(t.length<ye)return{text:String(e||"").trim(),removed:0,total:t.length};const n=l=>l.toLowerCase().replace(/[^\p{L}\p{N}']/gu,""),o=[];let r=0;for(let l=0;l<t.length;){let f=0,c=0;for(let i=1;i<=bt&&l+i*ye<=t.length;i++){let s=1;for(;l+(s+1)*i<=t.length&&t.slice(l+s*i,l+(s+1)*i).every((u,d)=>n(u)===n(t[l+d]));)s++;s>=ye&&(s-1)*i>f&&(f=(s-1)*i,c=i)}f?(o.push(...t.slice(l,l+c)),r+=f,l+=c+f):(o.push(t[l]),l++)}return{text:o.join(" "),removed:r,total:t.length}}const vt=.6,Ce=2.4;function He(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/Qe(t).length}function Nt(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function Pt({cores:e=ve.availableParallelism?.()??ve.cpus().length,env:t=process.env}={}){const n=Number(t.CHATPANEL_STT_THREADS);return Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(e/2)))}function oe(e){return{intraOpNumThreads:Pt(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Ot=.12,ze=.8,Rt=.15,Ft=.5,$t=1.2,Ue=(e,t)=>e>=Ft||e>=Rt&&!(t<$t),Ct=.999,Ht=2.5;function ie(e={},t=1/0){return Ue(e.en??0,t)?"en":Object.entries(e).sort((n,o)=>o[1]-n[1])[0]?.[0]||null}function zt(e,t=[]){const n=[];return e.forEach((o,r)=>{const l=t[r]??o.lang,f=n[n.length-1];f&&f.lang===l?f.to=o.to:n.push({from:o.from,to:o.to,lang:l})}),n}function Ut(e,{base:t=null,rate:n=p}={}){const o=e||[],r=i=>{const[s,u]=Object.entries(i.scores||{}).sort((d,b)=>b[1]-d[1])[0]||[];return s&&s!=="en"&&u>=Ct?s:null},l=new Array(o.length).fill(null);for(let i=0;i<o.length;){const s=r(o[i]);let u=i+1;if(s)for(;u<o.length&&r(o[u])===s;)u++;if(s&&(o[u-1].to-o[i].from)/n>=Ht)for(let d=i;d<u;d++)l[d]=s;i=u}const f=[];let c=t;return o.forEach((i,s)=>{l[s]?c=l[s]:c!=="en"&&Ue(i.scores?.en??0,(i.to-i.from)/n)&&(c="en");const u=f[f.length-1];u&&u.lang===c?u.to=i.to:f.push({from:i.from,to:i.to,lang:c})}),f}async function Gt(e,t,n){const{spelledEnglish:o,isSpelledEnglish:r,SPELLED_ENGLISH_MIN:l,SPELLED_SHAPE_MIN:f}=Lt;if(typeof o!="function")return e;const c=[];let i=!1;for(const s of e){const u=o(s.text);if(!s.lang||s.lang==="en"||u.english<l&&!r(s.text)){c.push(s);continue}const d=u.words>=f&&u.shaped===u.words,b=[];for(let a=0;a+1<t.length;a++)t[a]>=s.from&&t[a+1]<=s.to&&b.push([t[a],t[a+1]]);if(b.length<2||d){const a=r(s.text)?await n(s.from,s.to,"en"):"";a?(c.push({...s,text:a,lang:"en"}),i=!0):c.push(s);continue}const h=[];for(const[a,S]of b){const A=await n(a,S,s.lang),z=o(A),ge=z.words>0&&z.words-z.shaped<=(z.english>=1&&z.words>=3?1:0);h.push({from:a,to:S,text:A,near:ge,lang:r(A)?"en":s.lang})}for(let a=!0;a;)a=!1,h.forEach((S,A)=>{S.lang!=="en"&&S.near&&(h[A-1]?.lang==="en"||h[A+1]?.lang==="en")&&(S.lang="en",a=!0)});if(!h.some(a=>a.lang==="en")){c.push(s);continue}const M=[];for(const a of h){const S=M[M.length-1];S&&S.lang===a.lang?(S.to=a.to,S.n++):M.push({from:a.from,to:a.to,lang:a.lang,n:1,text:a.text})}for(const a of M){const S=a.n===1&&a.lang===s.lang?a.text:await n(a.from,a.to,a.lang);S&&c.push({from:a.from,to:a.to,lang:a.lang,text:S})}i=!0}return i?c.reduce((s,u)=>{const d=s[s.length-1];return d&&d.lang===u.lang&&d.to===u.from?s[s.length-1]={...d,to:u.to,text:`${d.text} ${u.text}`}:s.push(u),s},[]):e}function jt(e,t,{frame:n=Math.round(.03*p),minPause:o=Ot*p,minPiece:r=ze*p}={}){const l=[];let f=0,c=-1;for(let i=0;i+n<=e;i+=n){const s=t(i,i+n)===!1;if(s&&c<0&&(c=i),(!s||i+2*n>e)&&c>=0){const u=s?i+n:i,d=Math.round((c+u)/2);u-c>=o&&d-f>=r&&e-d>=r&&(l.push(d),f=d),c=-1}}return l}const Bt=.12;function It(e,t=Math.round(.03*p)){const n=Math.floor(e.length/t);if(n<3)return 0;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=J(e,r*t,(r+1)*t);return o.sort(),Math.max(1e-4,o[Math.floor(n*.9)]*Bt)}let _="off",x=null,m=null,v=null,q=null,L=null,K=null,P=null;function Kt(e=x||Re,t=he(e)||se()){if(G(e)==="parakeet-tdt")return I.parakeetOnDisk(e,I.parakeetDtype(t));if(G(e)==="coreml-tdt")return _e.coremlOnDisk(e);if(G(e)==="indic-canary")return te.indicOnDisk();const n=Ve(Pe(),...e.split("/"),"onnx");if(!Je(n))return!1;const o=tt[t]??"";try{const r=Ze(n);return r.includes(`encoder_model${o}.onnx`)&&r.some(l=>l===`decoder_model_merged${o}.onnx`||l===`decoder_model${o}.onnx`)}catch{return!1}}function Dn(){return _}function ce(){return _==="ready"&&!!m}function vn(){return L}function Nn(){return{configured:_!=="off",ok:ce(),state:_,model:x,dtype:K,runtime:Oe(),error:v,warmMs:P?.warmMs??null,vad:$.state()}}function Pn(){return!!P?.pending()}function re(){return H.size>0||_==="loading"||_==="downloading"}async function Me({log:e=()=>{}}={}){if(re())return!1;P?.disarm();const t=m;if(m=null,q=null,K=null,L=null,v=null,_="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((P?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function Ge(e){return e.then(t=>(t&&!re()&&P?.arm(),t))}async function je(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(G(e)==="parakeet-tdt")return Wt(e,{log:t,allowDownload:n,dtype:o});if(G(e)==="coreml-tdt")return Yt(e,{log:t,allowDownload:n});if(G(e)==="indic-canary")return qt(e,{log:t,allowDownload:n,licenseAccepted:r});const l=m,f=x;let c;try{c=await Ne()}catch(h){return _="error",v=`engine load failed: ${h.message}`,t(`[stt] transformers.js not available (${h.message}) — dictation falls back to the browser engine`),!1}const s=(o&&o!=="auto"?o:null)||he(e)||se(),u=Kt(e,s);if(c.env.allowRemoteModels=u?!1:!!n,!u&&!n)return _="error",v="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const d=c.env.remoteHost,b=!ot(e);if(!u&&b)try{c.env.remoteHost="https://huggingface.co/"}catch{}_=u?"loading":"downloading",u||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${b?", from Hugging Face":""})…`));try{const h=a=>{if(!a)return;const S=typeof a.progress=="number"?Math.round(a.progress):L?.pct??0;a.status==="progress"||a.status==="download"||a.status==="initiate"?L={model:e,file:a.file||L?.file||null,pct:S}:a.status==="done"&&a.file&&t(`[stt] fetched ${a.file}`)};let M;try{M=await c.pipeline("automatic-speech-recognition",e,{dtype:s,progress_callback:h,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:oe()}})}catch(a){if(u||b||!n)throw a;t(`[stt] mirror fetch failed (${String(a.message).slice(0,80)}) — retrying from Hugging Face…`),c.env.remoteHost="https://huggingface.co/",c.env.allowRemoteModels=!0,M=await c.pipeline("automatic-speech-recognition",e,{dtype:s,progress_callback:h,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:oe()}})}if(!u)try{nt(e,{modelsDir:Pe(),log:t})}catch(a){try{await M.dispose?.()}catch{}throw a}if(m=M,x=e,_="ready",v=null,L=null,K=s,l&&l!==M)try{await l.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${s} (in-process, offline) — local dictation active`),!0}catch(h){return v=h.message,L=null,l?(m=l,x=f,_="ready"):_="error",t(`[stt] model load failed (${h.message})${l?" — keeping previous model":""}`),!1}finally{try{c.env.remoteHost=d}catch{}}}async function Wt(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=m,l=x,f=I.parakeetDtype(o&&o!=="auto"?o:Xt()),c=I.parakeetOnDisk(e,f);if(!c&&!n)return _="error",v="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;_=c?"loading":"downloading",c||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await I.loadRecognizer({modelId:e,dtype:f,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:oe(),onProgress:u=>{L={model:e,file:u.file||null,pct:typeof u.pct=="number"?u.pct:L?.pct??0}}}),s=async u=>({text:await i.transcribe(u)});if(s.__transducer=!0,s.dispose=()=>i.dispose(),m=s,x=e,_="ready",v=null,L=null,K=f,r&&r!==s)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${f} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return v=i.message,L=null,r?(m=r,x=l,_="ready"):_="error",t(`[stt] model load failed (${i.message})${r?" — keeping previous model":""}`),!1}}function Xt(){return I.PARAKEET_DEFAULT_DTYPE}const Be="fp16";async function Yt(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=m,r=x,l=_e.coremlOnDisk(e);if(!l&&!n)return _="error",v="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;_=l?"loading":"downloading",l||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let f=null;const c=await _e.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:i=>{L={model:e,file:i.file||null,pct:typeof i.pct=="number"?i.pct:L?.pct??0}},onExit:i=>{m===f&&(m=null,q=null,_="error",v=i,P?.disarm(),t(`[stt] ${i} — reloads on the next dictation`))}});if(f=async i=>({text:await c.transcribe(i)}),f.__transducer=!0,f.dispose=()=>c.dispose(),m=f,x=e,_="ready",v=null,L=null,K=Be,o&&o!==f)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${c.version}, windows ${c.windows.join("/")} s, offline) — local dictation active`),!0}catch(f){return v=f.message,L=null,o?(m=o,x=r,_="ready"):_="error",t(`[stt] model load failed (${f.message})${o?" — keeping previous model":""}`),!1}}async function qt(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=m,l=x,f=te.indicOnDisk();if(!f&&!n)return _="error",v="model not on disk and downloads disabled",!1;_=f?"loading":"downloading",f||(L={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from Hugging Face)…`));try{f||await te.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:s=>{L={model:e,file:s.file,pct:s.pct}}});const c=await te.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:oe(),log:t}),i=async(s,u={})=>c.transcribe(s,u);if(i.identify=(s,u)=>c.identify(s,u),i.__transducer=!0,i.__indic=!0,i.dispose=()=>c.dispose(),m=i,x=e,_="ready",v=null,L=null,K="int8",r&&r!==i)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${te.INDIC_LICENSE.attribution}`),!0}catch(c){return v=c.message,L=null,r?(m=r,x=l,_="ready"):_="error",t(`[stt] model load failed (${c.message})${r?" — keeping previous model":""}`),!1}}const Vt=30;function Ie({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:o=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof o=="number"&&o<=Vt||e==="download"?{allowDownload:!0}:null}function Ee(e,{log:t=()=>{},warmMs:n,allowDownload:o=!0}={}){const r=Ie({mode:e,onDisk:j.modelOnDisk(),ready:j.isReady(),approxMB:it(j.activeModel())});if(r&&j.init({allowDownload:r.allowDownload&&o!==!1,warmMs:n,onLog:t}),e==="off"||Se)return;const l=Ie({mode:e,onDisk:Y.modelOnDisk(),ready:Y.isReady(),approxMB:Y.SEGMENT_MODEL_APPROX_MB});l&&Y.init({allowDownload:l.allowDownload&&o!==!1,warmMs:n,onLog:t})}let Se=!1,Te=null;function Le(e={},{log:t=()=>{}}={}){e.vad!==!1&&(Te={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},($.state()==="off"||$.state()==="error")&&$.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function On(e={}){if(q&&_!=="error")return q;const t=typeof e.onLog=="function"?e.onLog:()=>{};return x=e.model||Re,Se=e.segment===!1,_="loading",P=we({warmMs:e.warmMs,busy:re,log:t,unload:()=>Me({log:t})}),q=Ge(je(x,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Ee(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),Le(e,{log:t})),n)),q}async function Rn(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(Se=t.segment===!1);const o=G(e)==="parakeet-tdt"?I.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:I.PARAKEET_DEFAULT_DTYPE):G(e)==="coreml-tdt"?Be:G(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:he(e)||se();if(e===x&&ce()&&K===o)return Ee(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;P??=we({warmMs:t.warmMs,busy:re,log:n,unload:()=>Me({log:n})});const r=await Ge(je(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Ee(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),Le(t,{log:n})),r}const Qt=8,Jt=12e4,Zt=6e4,en=1200,ue=12,xe=700,Ae=.008,tn=.002,nn=4;function on(e){return e>0?Math.min(Ae,Math.max(tn,e*nn)):Ae}function rn(e){const t=Math.round(.1*p),n=Math.floor(e.length/t);if(n<5)return null;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=J(e,r*t,(r+1)*t);return o.sort(),o[Math.floor(n*.1)]}const Ke=30,ln=15e3,H=new Map,V=new Map;let Q=Promise.resolve();function Fn(){return H.size}const an=300,sn=3e3;function cn(e){const t=Number(e);return Number.isFinite(t)?Math.min(sn,Math.max(an,Math.round(t))):xe}function $n({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:l=!1,diarize:f=!1,speakerLabel:c=null,endSilenceMs:i=xe,interims:s=!0,remote:u=null,poll:d=!1,format:b="f32"}={}){if(H.size>=Qt){const S=new Error("too many concurrent dictation sessions");throw S.code="too_many_sessions",S}const h=Array.isArray(t)?mt(t):null,M=typeof e=="string"&&e?e.slice(0,12):null,a={id:et(),format:b==="pcm16"?"pcm16":"f32",endSilenceMs:cn(i),lang:h?h.length===1?h[0]:h.length?null:M:M,langs:h,lastLang:null,lastDecoded:null,learned:new Set,translateTo:ht(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?ee.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!l,diarize:!!f,speakerLabel:typeof c=="string"&&c?c.slice(0,40):null,diarizer:f?new j.Diarizer:null,remote:u||null,interims:s!==!1&&!u,chunks:[],samples:0,listeners:new Set,poll:d?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return H.set(a.id,a),P?.disarm(),a.diarizer&&(j.retain(),Y.retain()),a.translateTo&&(ne.retain(),Z.retain()),$.retain(),Te&&($.state()==="off"||$.state()==="error")&&Le(Te),We(a),{id:a.id}}function fe(e){return H.get(String(e||""))||null}function Cn(e,t){const n=fe(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function W(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Hn(e){const t=String(e||""),n=H.get(t);if(n)return n.poll?n.poll.splice(0):null;const o=V.get(t);return o?(clearTimeout(o.timer),V.delete(t),o.session.poll.splice(0)):null}function zn(e){return V.get(String(e||""))?.session||null}function We(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>gn(e.id).catch(()=>{}),Zt),e.idleTimer.unref?.()}function Un(e,t){const n=fe(e);if(!n||n.closed){const o=new Error("no such session");throw o.code="no_session",o}if(!(!(t instanceof Float32Array)||!t.length)){if(We(n),n.echo?.role==="mic"){ee.pushMic(n.echo,t),Xe(n);return}n.echo?.role==="reference"&&ee.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,Xe(n)}}function Gn(e){const t=fe(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),Q=Q.then(()=>ke(t).catch(()=>{})),Q)}function jn(e,t="f32"){if(t==="pcm16"){const r=new Float32Array(Math.floor(e.length/2));for(let l=0;l<r.length;l++)r[l]=e.readInt16LE(l*2)/32768;return r}const n=e.length-e.length%4,o=new Float32Array(n/4);for(let r=0;r<o.length;r++)o[r]=e.readFloatLE(r*4);return o}function Xe(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+en-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,Q=Q.then(()=>ke(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function de(e,t,n){const o=e.samples-t,r=[];n&&r.push(n),o>0&&r.push(Ye(e).subarray(t)),e.chunks=r,e.samples=r.reduce((l,f)=>l+f.length,0),e.lastInterim=""}function Ye(e){const t=new Float32Array(e.samples);let n=0;for(const o of e.chunks)t.set(o,n),n+=o.length;return t}function un(e,t,n){const o=p/100,r=Math.max(0,e.length-t),l=Math.floor((e.length-r)/o),f=Math.max(1,Math.round(n/o));if(l<=f)return 0;const c=new Float32Array(l);for(let d=0;d<l;d++){let b=0;const h=r+d*o;for(let M=0;M<o;M++)b+=e[h+M]*e[h+M];c[d]=b/o}let i=-1,s=1/0,u=0;for(let d=0;d<f;d++)u+=c[d];for(let d=0;d+f<=l;d++)d>0&&(u+=c[d+f-1]-c[d-1]),u<s&&(s=u,i=d);return i<0?0:r+Math.round((i+f/2)*o)}function J(e,t=0,n=e.length){let o=0;const r=Math.max(1,n-t);for(let l=t;l<n;l++)o+=e[l]*e[l];return Math.sqrt(o/r)}function fn(e,t=Ae){const n=Math.round(.02*p);let o=0,r=e.length;for(let l=0;l+n<=e.length;l+=n)if(J(e,l,l+n)>=t){o=l;break}for(let l=e.length-n;l>=0;l-=n)if(J(e,l,l+n)>=t){r=l+n;break}return r>o?e.subarray(o,r):e}async function qe(e){try{const t=await Ne(),n=m?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const o=e.length>p*8?e.subarray(0,p*8):e,r=await m.processor(o),l=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),f=await m.model({...r,decoder_input_ids:l}),c={};for(const[i,s]of Object.entries(n.lang_to_id))c[i.slice(2,-2)]=Number(f.logits.data[s]);return c}catch{return null}}async function dn(e){const t=await qe(e);if(!t)return null;let n=null,o=-1/0;for(const[r,l]of Object.entries(t))l>o&&(o=l,n=r);return n}async function ke(e,{flush:t=!1}={}){if(e.closed&&!t)return;if(e.echo?.role==="mic"){const g=await ee.drain(e.echo,{force:t});g.length&&(e.chunks.push(g),e.samples+=g.length,e.pushed+=g.length)}if(!e.remote&&!ce()||!e.samples)return;e.lastDecodeAt=Date.now();let n=Ye(e);const o=n.length,r=Math.max(0,(e.pushed||0)-e.samples),l=Math.round((e.endSilenceMs||xe)/1e3*p),f=rn(n);f!==null&&(e.noiseFloor==null||f<e.noiseFloor)&&(e.noiseFloor=f);const c=on(e.noiseFloor);let i=null,s=null;$.isReady()&&(e.vad||=$.createStream(),await e.vad.advance(n,r)&&(i=e.vad.speechIn(r,r+n.length,$.ONSET),n.length>l&&(s=e.vad.speechIn(r+n.length-l,r+n.length,$.OFFSET))));const u=n.length>l&&(s!==null?!s:J(n,n.length-l)<c);if(i===!1||i===null&&J(n)<c){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(!e.interims&&!t&&!u&&n.length<ue*p)return;let d=null;if(!t&&!u&&o>=ue*p&&o<Ke*p){const g=un(n,3*p,Math.round(.2*p));g>0&&g<n.length&&(d=n.subarray(g),n=n.subarray(0,g))}const b=!e.remote&&!me(x)&&!m?.__transducer;if(b&&!e.langs&&!e.lang&&!e.langTried&&n.length>=p){e.langTried=!0;const g=await dn(n);g&&(e.lang=g,W(e,{type:"language",lang:g}))}const h=t||u||o>=ue*p;let M=e.lang;if(b&&e.langs&&!e.lang){const g=e.langs.length>0,O=g?_t(e.langs):yt([...e.learned]);if(O.length===1)M=O[0];else if(M=O.includes(e.lastDecoded)?e.lastDecoded:null,(h||!M)&&n.length>=p/2){const R=await qe(n);if(R){const T=ft({scores:R,allowed:O,seconds:n.length/p,last:e.lastDecoded});M=!g&&!T.inherited&&T.confidence<St?e.lastDecoded||"en":T.lang,!g&&h&&!T.inherited&&T.confidence>=Mt&&n.length>=Et*p&&e.learned.add(T.lang)}}h&&M&&(e.lastDecoded=M)}let a="",S=null,A=null,z=null;try{if(e.remote){const g=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});a=g.text,z=g.lang||null}else{const g=m.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:ie}:e.lang?{lang:e.lang}:{langs:[...Tt],last:e.lastLang,choose:ie}:me(x)?{}:{language:M||void 0,task:"transcribe"},O=m.__indic&&m.identify&&h&&g.langs&&n.length>=2*ze*p?jt(n.length,(E=>(y,k)=>J(n,y,k)>=E)(It(n))):[],R=[0,...O,n.length];let T=null;if(O.length){const E=await m.identify(n,{langs:g.langs}),y=[];for(let k=0;k+1<R.length;k++){const N=await m.identify(n.subarray(R[k],R[k+1]),{langs:g.langs});y.push({from:R[k],to:R[k+1],scores:N?.scores||{}})}if(T=Ut(y,{base:E?.scores?ie(E.scores,n.length/p):null}),T.length>1){const k=[];for(let N=0;N<T.length;N++){const w=T[N],D=w.lang&&w.lang!=="en"&&(T[N-1]?.lang==="en"||T[N+1]?.lang==="en");k.push(D?ie((await m.identify(n.subarray(w.from,w.to),{langs:g.langs}))?.scores||{},(w.to-w.from)/p):w.lang)}T=zt(T,k)}T.length<2&&(T=null)}if(T){A=[];for(const E of T){const y=await m(n.subarray(E.from,E.to),E.lang?{lang:E.lang}:{...g}),k=String(y?.text||"").trim(),N=y?.lang||E.lang||null;k&&A.push({text:k,lang:N,from:E.from,to:E.to}),N&&(g.last=N)}}else{const E=await m(n,g);a=String(E?.text||"").trim(),m.__indic&&(S=E?.lang||null),m.__indic&&a&&(A=[{text:a,lang:S,from:0,to:n.length}])}if(A&&h&&g.langs&&(A=await Gt(A,R,async(E,y,k)=>String((await m(n.subarray(E,y),{lang:k}))?.text||"").trim())),A){a=A.map(y=>y.text).join(" ");const E=new Map;for(const y of A)y.lang&&E.set(y.lang,(E.get(y.lang)||0)+(y.to-y.from));S=[...E].sort((y,k)=>k[1]-y[1])[0]?.[0]||null,(A.length<2||E.size<2)&&(A=null)}}}catch(g){W(e,{type:"error",code:"decode_failed",message:g.message,fatal:!1}),h&&de(e,o,d);return}if(!a){h&&de(e,o,d);return}{const g=Dt(a);if(g.removed&&g.removed/g.total>=vt&&g.total>=12?a="":a=g.text,a&&He(a)>Ce){const O=Nt(a);a=O.replace(/[\s\p{P}]/gu,"").length<12||He(O)>Ce?"":O}if(!a){h&&de(e,o,d);return}}const ge=o>=ue*p,be=o>=Ke*p;if(t||u||ge||be){const g=t?"flush":u?"silence":be?"overflow":"length",O=g==="flush"||g==="silence";de(e,o,d);const R=fn(n,c);if(kt(a,R?R.length:0)||e.echo?.role==="mic"&&ut(ee.verdict(e.echo,r,r+n.length)))return;let T=null,E=null;if(e.diarizer)try{const w=e.speakerLabel?null:await Y.spans(n),D=w?rt(w):[];if(D.length){const F=new Map;for(const{local:C}of at(D)){const U=st(n,D,C),le=U.length?await j.embed(U):null,ae=U.length<Fe,X=U.length<$e;F.set(C,e.diarizer.assign(le,{pinnedLabel:null,weak:ae,thin:X}))}const B=Math.round(r/p*1e3);E=D.map(C=>({startMs:B+Math.round(C.start*1e3),durationMs:Math.round((C.end-C.start)*1e3),speaker:F.get(C.local)})).filter(C=>C.speaker),T=F.get(lt(D))||null}}catch{}if(e.diarizer&&!T)try{const w=R,D=w?await j.embed(w):null,F=!!w&&w.length<Fe,B=!!w&&w.length<$e;T=e.diarizer.assign(D,{pinnedLabel:e.speakerLabel,weak:F,thin:B})}catch{}let y=null;(e.langs||e.translateTo)&&(S?y=S:z?y=z:me(x)&&!e.remote?y="en":b?y=wt(a,M||e.lang)||null:y=e.lang||dt(a,{allowed:e.langs||[],last:e.lastLang}).lang,y&&y!==e.lastLang&&(e.lastLang=y,W(e,{type:"language",lang:y})));const k=Math.round(r/p*1e3),N=A&&(e.langs||e.translateTo)?A.map((w,D)=>({text:w.text,lang:w.lang,startMs:k+Math.round(w.from/p*1e3),durationMs:Math.round((w.to-w.from)/p*1e3),last:D===A.length-1})):[{text:a,lang:y,startMs:k,durationMs:Math.round(n.length/p*1e3),last:!0}];for(const w of N){N.length>1&&w.lang&&w.lang!==e.lastLang&&(e.lastLang=w.lang,W(e,{type:"language",lang:w.lang}));const{text:D,lang:F,startMs:B}=w,C=(D.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(D.match(new RegExp("\\p{L}","gu"))||[]).length),U=Z.indictransLanguage(F)&&C<.5&&Z.state()!=="error"&&ct(),le=!!e.translateTo&&gt(F,e.translateTo)&&(U||pt(D,F)&&ne.state()!=="error"),ae=N.length>1&&E?E.filter(X=>X.startMs<B+w.durationMs&&X.startMs+X.durationMs>B):E;if(W(e,{type:"final",text:D,reason:g,endOfTurn:w.last?O:!1,durationMs:w.durationMs,startMs:B,...F?{lang:F}:{},...le?{translating:!0}:{},...T?{speaker:T}:{},...ae?.length?{turns:ae}:{}}),le){const X=e.translateTo,pe=U?Z:ne;pe.state()==="off"&&pe.init({...e.translateLoad,...U?{sessionOptions:oe()}:{}}),e.translations=e.translations.then(async()=>{await pe.ready();const De=U?await Z.translate(D,F):await ne.translate(D);W(e,{type:"translation",startMs:B,lang:F,to:X,text:De||null,...De?{}:{failed:!0}})}).catch(()=>{})}}}else a!==e.lastInterim&&(e.lastInterim=a,W(e,{type:"interim",text:a}))}async function gn(e){const t=fe(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(Q=Q.then(()=>ke(t,{flush:!0}).catch(()=>{}))),await Promise.race([t.translations,new Promise(n=>setTimeout(n,ln).unref?.())])}finally{if(W(t,{type:"end"}),t.listeners.clear(),H.delete(t.id),t.poll){const n=setTimeout(()=>V.delete(t.id),Jt);n.unref?.(),V.set(t.id,{session:t,timer:n})}t.diarizer&&(j.release(),Y.release()),t.translateTo&&(ne.release(),Z.release()),$.release(),ee.leave(t.echo),H.size===0&&ce()&&P?.arm()}return!0}function Bn(){for(const e of H.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);H.clear();for(const e of V.values())clearTimeout(e.timer);V.clear(),P?.disarm(),P=null,_="off",x=null,m=null,v=null,q=null,L=null}function In(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){m=e,x=t,_=e?"ready":"off",K=o,n!==null&&(P=we({warmMs:n,busy:re,unload:()=>Me()}),e&&P.arm())}export{Vt as AUTO_FETCH_MAX_MB,Ce as COMPRESSION_LIMIT,Ct as FROM_ENGLISH,Ht as FROM_ENGLISH_RUN_S,vt as LOOP_DROP,Bt as PAUSE_SHARE,ze as PIECE_MIN_S,Ot as PIECE_PAUSE_S,p as SAMPLE_RATE,Ft as SURE_ENGLISH,$e as THIN_SPEAKER_SAMPLES,Rt as TO_ENGLISH,$t as WEAK_ENGLISH_MIN_S,Fe as WEAK_SPEAKER_SAMPLES,Bn as _reset,In as _setPipeForTest,cn as clampEndSilence,Dt as collapseLoops,Nt as collapseRuns,He as compressionRatio,$n as createSession,Gn as decodeNow,Hn as drainEvents,gn as endSession,zn as endedSession,fe as getSession,Nn as health,On as init,ce as isReady,Ut as languageGroups,kt as looksHallucinated,Kt as modelOnDisk,rn as noiseFloorOf,jt as pauseCuts,It as pauseLevel,vn as progress,Un as pushAudio,un as quietestCut,zt as relabelGroups,Gt as respellEnglish,se as runtimeDtype,Oe as runtimeName,ie as segmentLanguage,Fn as sessionCount,Rn as setModel,on as silenceGate,Ie as speakerPlan,Dn as state,oe as sttSessionOptions,Pt as sttThreads,Cn as subscribe,jn as toFloat32,Me as unload,Pn as warmPending};
@@ -1 +1 @@
1
- function v({requested:c=null,configured:d,engine:i,voices:s,isPocketVoice:r,isKnownVoice:k,isValidVoiceId:m,defaultVoice:p,defaultPocketVoice:a}){const t=c||d,o=i.isPocket();let e=s.parseCustomVoice(t);if(o&&r(t))return{ok:!0,voice:t,customId:null,speakerEmbedding:null};if(i.supportsCustomVoices()){let u=e?s.getVoice(e):null;if(!u&&!c){if(o)return{ok:!0,voice:a,customId:null,speakerEmbedding:null};const l=s.listVoices();l.length&&(e=l[0].id,u=s.getVoice(e))}if(!u)return e?{ok:!1,status:404,type:"bad_voice",message:"no such saved voice"}:{ok:!1,status:400,type:"bad_voice",message:"this model speaks in a voice you record — add one in Settings → Text-to-speech"};let n;if(o){if(n=s.getPocketVoice(e),!n)return{ok:!1,status:409,type:"voice_kind_missing",message:"this voice was saved without a Pocket TTS conditioning — record it again with Pocket TTS selected"}}else n=u.vec;return{ok:!0,voice:`custom:${e}`,customId:e,speakerEmbedding:n}}return e?c?{ok:!1,status:409,type:"voice_unsupported",message:`the active model (${i.arch()}) cannot use a recorded voice — switch to SpeechT5`}:{ok:!0,voice:p,customId:null,speakerEmbedding:null}:o&&!r(t)?{ok:!0,voice:a,customId:null,speakerEmbedding:null}:i.supportsVoices()&&!o&&!(k(t)&&m(t))?{ok:!1,status:400,type:"bad_voice",message:"unknown or invalid voice"}:{ok:!0,voice:t,customId:null,speakerEmbedding:null}}export{v as resolveTtsVoice};
1
+ function v({requested:c=null,configured:d,engine:n,voices:s,isPocketVoice:r,isKnownVoice:k,isValidVoiceId:m,defaultVoice:p,defaultPocketVoice:a}){const t=c||d,o=n.isPocket();let e=s.parseCustomVoice(t);if(o&&r(t))return{ok:!0,voice:t,customId:null,speakerEmbedding:null};if(n.supportsCustomVoices()){let u=e?s.getVoice(e):null;if(!u&&!c){if(o)return{ok:!0,voice:a,customId:null,speakerEmbedding:null};const l=s.listVoices();l.length&&(e=l[0].id,u=s.getVoice(e))}if(!u)return e?{ok:!1,status:404,type:"bad_voice",message:"no such saved voice"}:{ok:!1,status:400,type:"bad_voice",message:"this model speaks in a voice you record — add one in Settings → Text-to-speech"};let i;if(o){if(i=s.getPocketVoice(e),!i)return{ok:!1,status:409,type:"voice_kind_missing",message:"this voice was saved without a Pocket TTS conditioning — record it again with Pocket TTS selected"}}else if(i=u.vec,!i?.length)return{ok:!1,status:409,type:"voice_kind_missing",message:"this voice was saved for Pocket TTS only — select Pocket TTS to speak in it"};return{ok:!0,voice:`custom:${e}`,customId:e,speakerEmbedding:i}}return e?c?{ok:!1,status:409,type:"voice_unsupported",message:`the active model (${n.arch()}) cannot use a recorded voice — switch to SpeechT5`}:{ok:!0,voice:p,customId:null,speakerEmbedding:null}:o&&!r(t)?{ok:!0,voice:a,customId:null,speakerEmbedding:null}:n.supportsVoices()&&!o&&!(k(t)&&m(t))?{ok:!1,status:400,type:"bad_voice",message:"unknown or invalid voice"}:{ok:!0,voice:t,customId:null,speakerEmbedding:null}}export{v as resolveTtsVoice};
package/src/tts-voices.js CHANGED
@@ -1 +1 @@
1
- import{existsSync as g,mkdirSync as w,readFileSync as y,writeFileSync as u,readdirSync as b,rmSync as S}from"node:fs";import{join as l}from"node:path";import{randomUUID as E}from"node:crypto";import V from"node:os";const s=512,a="wavlm-512",p="pocket-mimi",x=20,v=60;function m(){return process.env.CHATPANEL_TTS_VOICES||l(V.homedir(),".chatpanel","tts-voices")}function h(e){return/^[A-Za-z0-9_-]{1,64}$/.test(String(e||""))}function _(e){const r=String(e||"");if(!r.startsWith("custom:"))return null;const t=r.slice(7);return h(t)?t:null}function f(e){return l(m(),`${e}.json`)}function N(){const e=m();if(!g(e))return[];const r=[];for(const t of b(e))if(t.endsWith(".json"))try{const n=JSON.parse(y(l(e,t),"utf8"));n?.id&&n?.name&&r.push({id:n.id,name:n.name,createdAt:n.createdAt||0,updatedAt:n.updatedAt||0,dim:n.vec?.length||0,kinds:n.pocketShape?[a,p]:[a]})}catch{}return r.sort((t,n)=>n.createdAt-t.createdAt)}function d(e){return l(m(),`${e}.pocket.bin`)}function A(e){if(!h(e))return null;try{const r=JSON.parse(y(f(e),"utf8"));return!Array.isArray(r?.vec)||r.vec.length!==s?null:r}catch{return null}}function $(e){if(!h(e))return null;const r=A(e);if(!r?.pocketShape)return null;try{const t=y(d(e));return{data:new Float32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),shape:r.pocketShape}}catch{return null}}function C(e){const r=A(e);return r?r.pocketShape?[a,p]:[a]:[]}function I({name:e,vec:r,pocket:t=null}){const n=String(e||"").trim().slice(0,v);if(!n)throw new Error("a name is required");if(!r||r.length!==s)throw new Error(`expected a ${s}-value embedding, got ${r?.length||0}`);if(N().length>=x)throw new Error(`at most ${x} saved voices — delete one first`);const i=m();w(i,{recursive:!0});const o={id:E(),name:n,createdAt:Date.now(),vec:Array.from(r,c=>Number(c)||0)};if(t?.data?.length&&Array.isArray(t.shape)){o.pocketShape=t.shape;const c=t.data instanceof Float32Array?t.data:Float32Array.from(t.data);u(d(o.id),Buffer.from(c.buffer,c.byteOffset,c.byteLength))}return u(f(o.id),JSON.stringify(o)),{id:o.id,name:o.name,createdAt:o.createdAt,dim:o.vec.length,kinds:o.pocketShape?[a,p]:[a]}}function M(e,r){const t=A(e);if(!t)return null;const n=String(r||"").trim().slice(0,v);if(!n)throw new Error("a name is required");return t.name=n,t.updatedAt=Date.now(),u(f(e),JSON.stringify(t)),{id:e,name:t.name,createdAt:t.createdAt||0,updatedAt:t.updatedAt,dim:t.vec?.length||0}}function J(e,{vec:r,pocket:t=null}){const n=A(e);if(!n)return null;if(!r||r.length!==s)throw new Error(`expected a ${s}-value embedding, got ${r?.length||0}`);if(n.vec=Array.from(r,i=>Number(i)||0),n.updatedAt=Date.now(),t?.data?.length&&Array.isArray(t.shape)){n.pocketShape=t.shape;const i=t.data instanceof Float32Array?t.data:Float32Array.from(t.data);u(d(e),Buffer.from(i.buffer,i.byteOffset,i.byteLength))}else n.pocketShape&&(delete n.pocketShape,S(d(e),{force:!0}));return u(f(e),JSON.stringify(n)),{id:e,name:n.name,createdAt:n.createdAt||0,updatedAt:n.updatedAt,dim:n.vec.length,kinds:n.pocketShape?[a,p]:[a]}}function T(e){if(!h(e))return!1;const r=f(e);return g(r)?(S(r,{force:!0}),S(d(e),{force:!0}),!0):!1}export{s as EMBED_DIM,p as KIND_POCKET,a as KIND_SPEECHT5,T as deleteVoice,$ as getPocketVoice,A as getVoice,h as isValidVoiceRef,N as listVoices,_ as parseCustomVoice,M as renameVoice,J as replaceVoice,I as saveVoice,C as voiceKinds,m as voicesDir};
1
+ import{existsSync as S,mkdirSync as O,readFileSync as A,writeFileSync as s,readdirSync as b,rmSync as y}from"node:fs";import{join as l}from"node:path";import{randomUUID as E}from"node:crypto";import N from"node:os";const T=512,V="wavlm-512",F="pocket-mimi",g=20,v=60;function d(){return process.env.CHATPANEL_TTS_VOICES||l(N.homedir(),".chatpanel","tts-voices")}function p(e){return/^[A-Za-z0-9_-]{1,64}$/.test(String(e||""))}function M(e){const n=String(e||"");if(!n.startsWith("custom:"))return null;const t=n.slice(7);return p(t)?t:null}function u(e){return l(d(),`${e}.json`)}function D(){const e=d();if(!S(e))return[];const n=[];for(const t of b(e))if(t.endsWith(".json"))try{const r=JSON.parse(A(l(e,t),"utf8"));r?.id&&r?.name&&n.push({id:r.id,name:r.name,createdAt:r.createdAt||0,updatedAt:r.updatedAt||0,dim:r.vec?.length||0,kinds:i(r)})}catch{}return n.sort((t,r)=>r.createdAt-t.createdAt)}function f(e){return l(d(),`${e}.pocket.bin`)}function m(e){if(!p(e))return null;try{const n=JSON.parse(A(u(e),"utf8"));return i(n).length?n:null}catch{return null}}function J(e){if(!p(e))return null;const n=m(e);if(!n?.pocketShape)return null;try{const t=A(f(e));return{data:new Float32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),shape:n.pocketShape}}catch{return null}}const x=e=>!!e&&e.length===T,i=e=>[...x(e?.vec)?[V]:[],...e?.pocketShape?[F]:[]];function K(e){const n=m(e);return n?i(n):[]}function w(e,n){const t=x(e),r=!!(n?.data?.length&&Array.isArray(n.shape));if(!t&&!r)throw new Error(P);return{t5:t,hasPocket:r}}const P="no voice engine here can use this recording — Pocket TTS is not installed, and SpeechT5 needs the wavlm speaker model (512 values); install Pocket TTS in Settings → Text-to-speech";function L({name:e,vec:n=null,pocket:t=null}){const r=String(e||"").trim().slice(0,v);if(!r)throw new Error("a name is required");const{t5:h}=w(n,t);if(D().length>=g)throw new Error(`at most ${g} saved voices — delete one first`);const a=d();O(a,{recursive:!0});const o={id:E(),name:r,createdAt:Date.now(),...h?{vec:Array.from(n,c=>Number(c)||0)}:{}};if(t?.data?.length&&Array.isArray(t.shape)){o.pocketShape=t.shape;const c=t.data instanceof Float32Array?t.data:Float32Array.from(t.data);s(f(o.id),Buffer.from(c.buffer,c.byteOffset,c.byteLength))}return s(u(o.id),JSON.stringify(o)),{id:o.id,name:o.name,createdAt:o.createdAt,dim:o.vec?.length||0,kinds:i(o)}}function $(e,n){const t=m(e);if(!t)return null;const r=String(n||"").trim().slice(0,v);if(!r)throw new Error("a name is required");return t.name=r,t.updatedAt=Date.now(),s(u(e),JSON.stringify(t)),{id:e,name:t.name,createdAt:t.createdAt||0,updatedAt:t.updatedAt,dim:t.vec?.length||0,kinds:i(t)}}function j(e,{vec:n=null,pocket:t=null}){const r=m(e);if(!r)return null;const{t5:h}=w(n,t);if(h?r.vec=Array.from(n,a=>Number(a)||0):delete r.vec,r.updatedAt=Date.now(),t?.data?.length&&Array.isArray(t.shape)){r.pocketShape=t.shape;const a=t.data instanceof Float32Array?t.data:Float32Array.from(t.data);s(f(e),Buffer.from(a.buffer,a.byteOffset,a.byteLength))}else r.pocketShape&&(delete r.pocketShape,y(f(e),{force:!0}));return s(u(e),JSON.stringify(r)),{id:e,name:r.name,createdAt:r.createdAt||0,updatedAt:r.updatedAt,dim:r.vec?.length||0,kinds:i(r)}}function B(e){if(!p(e))return!1;const n=u(e);return S(n)?(y(n,{force:!0}),y(f(e),{force:!0}),!0):!1}export{T as EMBED_DIM,F as KIND_POCKET,V as KIND_SPEECHT5,P as NO_PRINT,B as deleteVoice,J as getPocketVoice,m as getVoice,x as isSpeechT5Print,p as isValidVoiceRef,D as listVoices,M as parseCustomVoice,$ as renameVoice,j as replaceVoice,L as saveVoice,K as voiceKinds,d as voicesDir};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.120.1";export{o as VERSION};
1
+ const o="0.121.5";export{o as VERSION};