@chatpanel/gateway 0.139.3 → 0.139.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.139.3",
3
+ "version": "0.139.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": {
@@ -24,7 +24,7 @@
24
24
  "dependencies": {
25
25
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
26
26
  "@chatpanel/bridge": "^0.52.0",
27
- "@chatpanel/events": "^0.447.1",
27
+ "@chatpanel/events": "^0.455.0",
28
28
  "@chatpanel/pii": "^0.15.6",
29
29
  "@huggingface/transformers": "^4.2.0",
30
30
  "defuddle": "^0.19.4",
package/src/link-host.js CHANGED
@@ -1 +1 @@
1
- import{readFileSync as Oe,writeFileSync as Re,renameSync as Ue,mkdirSync as ee,chmodSync as Ce}from"node:fs";import{dirname as J,join as ue,resolve as de,sep as Ie}from"node:path";import te from"node:os";import{createLinkEndpoint as De}from"@chatpanel/events/link-connect.js";import{noiseCrypto as Fe}from"@chatpanel/events/link-noise.js";import{pairingUri as fe,pairingCode as Me,admissionToken as G,admissionVerifier as F,toB64url as O,fromB64url as ne,coalesceChunks as je}from"@chatpanel/events/link-protocol.js";import{linkPaths as me,linkRoute as z,checkLinkRoute as Be,DEFAULT_LINK_RELAY as Ve,LINK_ROUTES as he,LINK_TUNNEL_ROOM_PATH as He,tunnelSetup as Je}from"@chatpanel/events/link-routes.js";import{linkDeviceKind as M,partnerMay as Ge,partnerHeaders as ze,withoutLinkMarks as We,linkMarkHeaders as Ye,checkPartnerName as Qe,checkPartnerScopes as Ze,describePartnerAccess as Xe,checkPartnerFolder as qe,partnerFolderSlug as et}from"@chatpanel/events/link-scopes.js";import{timingSafeEqual as tt}from"node:crypto";import{acceptWebSocket as nt,refuseUpgrade as oe}from"./ws-accept.js";import{qrSvg as ot}from"@chatpanel/events/qr.js";import{verifyEntitlement as rt,licenseFromPayload as at,can as st,FEATURE_TIER as ye}from"@chatpanel/events/entitlement.js";const bt="https://link.chatpanel.net",W=10*6e4,it=3e4,re=[1e3,2e3,5e3,1e4,3e4,6e4],lt=30,Y="chatpanel-link.v1",ct=/(^|\n): ?ping\n\n/g,pt=4,ut=[/^\/v1\/models(?:\/|$|\?)/,/^\/v1\/chat\/completions$/,/^\/v1\/messages$/,/^\/v1\/audio\/(?:transcriptions|speech)$/,/^\/v1\/history\/(?:search|smart-search|get|list|related|status)(?:$|\?)/,/^\/v1\/history\/(?:records|stream)(?:$|\?)/,/^\/v1\/memory\/(?:recall|list|remember)(?:$|\?)/,/^\/v1\/(?:research|search|read|rerank|decide|capabilities|fusions)(?:$|\?)/,/^\/v1\/status$/,/^\/v1\/stt\/sessions(?:\/[0-9a-f-]{36}(?:\/audio)?)?$/,/^\/v1\/link\/routes$/,/^\/v1\/agent-sessions(?:\/read|\/adopt|\/catchup)?$/],dt=c=>ut.some(i=>i.test(String(c||""))),ge="x-chatpanel-entitlement",we="x-chatpanel-install",ke=(c,i)=>{for(const[g,k]of Object.entries(c||{}))if(g.toLowerCase()===i)return String(k||"");return""};async function ve(c,{now:i=Date.now()}={}){if(!ye.link||ye.link==="free")return!1;const g=ke(c,ge),k=ke(c,we);if(!g||!k)return!1;const N=await rt(g,k,{now:i});return!!N&&st(at(N,{at:i}),"link",0,i)}const ft=!1;async function mt(c,i,{now:g=Date.now(),phoneCheck:k=ve,ownerIsPro:N=async()=>!1}={}){return M(c)==="partner"?ft?!!await N():!0:k(i?.headers||{},{now:g})}const L=c=>Object.assign(new Error(c),{code:"bad_partner"}),R=c=>{try{return new URL(c).host}catch{return""}};function Lt(c=ae()){return Se(c).rooms.filter(i=>M(i)==="partner"&&i.phoneKey).map(i=>({id:i.room,kind:"partner",name:i.name,partner:{name:i.partner?.name||i.name},scopes:i.scopes||[],route:i.route||null,host:R(i.relay||i.gw||""),pairedAt:i.pairedAt||null,lastSeen:i.lastSeen||null,...(i.scopes||[]).includes("agents")?{folder:Q(i,c)}:{}}))}function Q(c,i=ae()){return c?.folder||ue(J(i),"partners",et(c?.partner?.name||c?.name))}const ht=(c,i)=>{const g=de(c),k=de(i);return g===k||g.startsWith(`${k}${Ie}`)};function ae(){return ue(te.homedir(),".chatpanel","link.json")}function Se(c){try{const i=JSON.parse(Oe(c,"utf8"));return{v:1,key:i.key||null,rooms:Array.isArray(i.rooms)?i.rooms:[]}}catch{return{v:1,key:null,rooms:[]}}}function Ee(c,i){ee(J(c),{recursive:!0});const g=`${c}.tmp`;Re(g,JSON.stringify(i,null,2),{mode:384});try{Ce(g,384)}catch{}Ue(g,c)}function Nt({settings:c={},relay:i=null,port:g=4320,name:k=te.hostname(),dispatch:N,path:T=ae(),fetch:$e=globalThis.fetch,WebSocket:Te=globalThis.WebSocket,now:w=()=>Date.now(),random:j=S=>globalThis.crypto.getRandomValues(new Uint8Array(S)),crypto:Z=Fe(),log:U=S=>{},mayLink:Pe=ve,ownerIsPro:Ae=async()=>!1,home:_e=te.homedir(),confined:be=process.env.CHATPANEL_CONFINED==="1"}={}){const S=i?new URL(i).origin:null;if(S&&!/^https:/.test(S)&&!/^http:\/\/127\.0\.0\.1(?::\d+)?$/.test(S))throw new Error("link: the relay must be https");const se=t=>{const e=me(t);return S&&e.relay?{...e,relay:S}:e};let l=se(c);l.problem&&U(`link: ${l.problem} — using ChatPanel Link`);let u=Se(T);const Le=S||me({relayUrl:c?.relayUrl}).relay;for(const t of u.rooms)t.relay===void 0&&(t.relay=Le);const v=new Map,P=new Map;let _=null;async function K(){return _||(u.key?_=await Z.keyPairFromPrivate(ne(u.key)):(_=await Z.generateKeyPair(),u.key=O(_.raw),Ee(T,u)),_)}const A=t=>u.rooms.find(e=>e.room===t)||null,B=()=>Ee(T,u),C=t=>M(t)==="partner"?!!t.relay:!!t.relay&&t.relay===l.relay,$=t=>M(t)==="partner",V=async(t,e,n,o,r)=>{try{return await $e(`${r}/v1/room/${t}`,{method:e,headers:{authorization:`Bearer ${n}`,...o?{"content-type":"application/json"}:{}},body:o?JSON.stringify(o):void 0})}catch(s){const a=s?.cause?.code||"",d=a==="ENOTFOUND"?"this computer cannot look up its name (a VPN or DNS that does not know it yet)":a?`${a}`:s?.message||"no answer";throw new Error(`cannot reach the Link relay at ${new URL(r).host}: ${d}`)}};async function Ne(t,e,n){t.lastSeen=w();const o=$(t);if(o?!Ge(t.scopes,e):!dt(e.path))return await n.head(403,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:o?`link: partner "${t.name}" may not call ${e.method} ${e.path.split("?")[0]} — its scopes are ${(t.scopes||[]).join(", ")||"none"}`:"link: a paired phone may not call this",type:"forbidden",...o?{code:"link_scope"}:{}}})),n.end();if(!await mt(t,e,{now:w(),phoneCheck:Pe,ownerIsPro:Ae}))return await n.head(402,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:o?"ChatPanel Link partner devices need ChatPanel Pro on this computer":"ChatPanel Link needs Pro on this phone — upgrade on the phone, or restore its Pro under Settings › Plan",type:"pro_required"}})),n.end();if(e.path==="/v1/link/routes")return await n.head(200,{"content-type":"application/json"}),await n.write(JSON.stringify({route:l.route,relay:C(t)?t.relay:null,gw:l.tunnel})),n.end();let r={};if(o)r=ze(e.headers);else for(const[m,y]of Object.entries(e.headers||{}))m.toLowerCase()!==ge&&m.toLowerCase()!==we&&(r[m]=y);r={...We(r),...Ye(t)};const s=e.method==="GET"?void 0:await e.body.bytes(),a=await N({method:e.method,path:e.path,headers:r,body:s,device:t.room}),d={};a.headers?.forEach?.((m,y)=>{d[y]=m});let f=!1;try{await n.head(a.status,d)}catch{f=!0}if(a.body){const m=/event-stream/.test(String(a.headers?.get?.("content-type")||""));for await(const y of je(Ke(a.body,m))){if(n.cancelled)break;if(!f)try{await n.write(y)}catch{f=!0}}}if(!f)return n.end()}async function*Ke(t,e){for await(const n of t){let o=n instanceof Uint8Array?n:new TextEncoder().encode(String(n));if(e){const r=new TextDecoder().decode(o);if(r.includes(": ping")){const s=r.replace(ct,"$1");if(!s)continue;o=new TextEncoder().encode(s)}}yield o}}function ie(t,e,n,o,r){return De({side:"laptop",keyPair:e,crypto:Z,psk:t.phoneKey?null:ne(n.psk),peerKey:t.phoneKey?ne(t.phoneKey):null,sendBytes:r,onRequest:(s,a)=>Ne(t,s,a),onSession:(s,a)=>{o.online=!0,o.attempts=0,t.lastSeen=w(),a.paired&&(t.phoneKey=O(a.peerKey),$(t)||(t.name=a.name||t.name||"Phone"),t.pairedAt=w(),t.pending=null,U(`link: paired ${t.name}`)),B()},onEnd:()=>{o.online=!1}})}async function I(t){if(!C(t))return;const e=v.get(t.room)||{attempts:0,stopped:!1,online:!1};if(v.set(t.room,e),e.stopped)return;const n=await K(),o=t.pending&&t.pending.expiresAt>w()?t.pending:null;if(!t.phoneKey&&!o){D(t.room,"the pairing code expired");return}const r=`${t.relay.replace(/^http/,"ws")}/v1/room/${t.room}`;let s;try{s=new Te(r,[Y,t.token])}catch(a){le(t,a?.message);return}s.binaryType="arraybuffer",e.ws=s,e.endpoint=ie(t,n,o,e,a=>{try{s.send(a)}catch{}}),s.onopen=()=>{if(e.stopped||v.get(t.room)!==e){try{s.close(1e3,"stopped")}catch{}return}clearInterval(e.keepalive),e.keepalive=setInterval(()=>{try{s.send("ping")}catch{}},it),e.keepalive.unref?.()},s.onmessage=a=>typeof a.data=="string"?e.endpoint.onText(a.data):e.endpoint.onBinary(new Uint8Array(a.data)),s.onclose=a=>{if(clearInterval(e.keepalive),e.online=!1,e.endpoint?.close("socket closed"),!e.stopped){if(a?.code===4003||a?.code===4004){q(t.room,"the relay removed the room");return}le(t,a?.code===4001?"replaced":a?.code===4008?"over the relay's budget":`closed ${a?.code||""}`,a?.code===4001?5:a?.code===4008?pt:null)}},s.onerror=()=>{}}function le(t,e,n=null){const o=v.get(t.room);if(!o||o.stopped)return;const r=n??Math.min(o.attempts,re.length-1);o.attempts++,clearTimeout(o.timer),o.timer=setTimeout(()=>I(t),re[r]),o.timer.unref?.(),U(`link: ${e}; again in ${re[r]/1e3}s`)}function X(t){const e=v.get(t);if(e){e.stopped=!0,clearTimeout(e.timer),clearInterval(e.keepalive),e.endpoint?.close("stopped");try{e.ws?.close(1e3,"stopped")}catch{}v.delete(t)}}function H(t,e=1e3,n="stopped"){const o=P.get(t);if(o?.ws){o.endpoint?.close(n);try{o.ws.close(e,n)}catch{}o.ws=null,o.endpoint=null,o.online=!1}}function D(t,e){const n=A(t);n&&!n.phoneKey&&n.relay&&V(t,"DELETE",n.token,null,n.relay).catch(()=>{}),q(t,e)}function q(t,e){X(t),H(t,4004,"room removed"),P.delete(t),u.rooms=u.rooms.filter(n=>n.room!==t),B(),U(`link: ${e}`)}function xe({route:t=null,relay:e=""}={}){const n=t||(e?"relay":l.route);if(!z(n))throw L(`unknown route "${n}" — one of ${he.map(r=>r.id).join(", ")}`);if(z(n).kind==="tunnel"){if(l.route!==n||!l.tunnel)throw L(`this gateway's ${z(n).label} door is not open — set it as the route first (chatpanel-gateway link route ${n} --gw <https address>), then pair`);return{route:n,relay:null,gw:l.tunnel,host:R(l.tunnel)}}if(n==="relay"){const r=e||(l.route==="relay"?l.relay:"");if(!r)throw L('the relay route needs the relay’s https address (--relay <url>), or "Your own relay" set as the route');let s;try{s=Be({id:"relay",url:r})}catch(a){throw L(a.message)}return{route:s.id,relay:s.url,gw:null,host:R(s.url)}}const o=S||Ve;return{route:"link",relay:o,gw:null,host:R(o)}}function ce({partner:t,scopes:e,route:n=null,relay:o="",folder:r=""}={}){const s=Qe(t),a=Ze(e),d=xe({route:n,relay:o});let f="";if(a.includes("agents")){try{f=String(r||"").trim()?qe(r,{name:s,home:_e}):Q({partner:{name:s}},T)}catch(m){throw L(m.message)}if(be&&!ht(f,J(T)))throw L(`this gateway runs confined and writes only ${J(T)} — leave the folder empty (the default is inside it), or run the gateway unconfined to use ${f}`)}return{via:d,folder:f,preview:Xe({partner:s,scopes:a,route:d.route,host:d.host,folder:f})}}return{previewPartner(t={}){return ce(t).preview},deviceNameOf(t){const e=A(t);return e?.phoneKey?String(e.name||""):""},partnerFolderOf(t){const e=A(t);if(!e||!$(e)||!e.phoneKey||!(e.scopes||[]).includes("agents"))return null;const n=Q(e,T);try{ee(n,{recursive:!0,mode:448})}catch{return null}return n},async pairPartner(t={}){const{via:e,preview:n,folder:o}=ce(t);if(o)try{ee(o,{recursive:!0,mode:448})}catch(h){throw L(`could not create ${o}: ${h.message}`)}const r=await K(),s=j(16),a=j(32),d=O(s),f=await G(a,s,"laptop"),m=await F(await G(a,s,"phone"));if(e.relay){const h=await V(d,"PUT",f,{laptop:await F(f),phone:m},e.relay);if(h.status!==200&&h.status!==201)throw new Error(`link: the relay refused the room (${h.status})`)}for(const h of u.rooms.filter(b=>!b.phoneKey&&$(b)))D(h.room,"a new partner code replaced this one");const y=w()+W,p={room:d,token:f,relay:e.relay,phoneVerifier:m,phoneKey:null,name:n.partner,pairedAt:null,lastSeen:null,pending:{psk:O(a),expiresAt:y},kind:"partner",partner:{name:n.partner},scopes:n.scopes,route:e.route,...o?{folder:o}:{}};u.rooms.push(p),B();const x=Me({uri:fe({relay:e.relay,gw:e.gw,room:s,key:r.publicKey,secret:a,name:""}),expiresAt:y,route:e.route});return I(p),setTimeout(()=>{const h=A(d);h&&!h.phoneKey&&D(d,"the partner code expired")},W+1e3).unref?.(),U(`link: partner code issued for ${n.partner} (${n.scopes.join(", ")}; route ${e.route} via ${e.host})`),{code:x,expiresAt:y,room:d,kind:"partner",partner:{name:n.partner},scopes:n.scopes,route:e.route,host:e.host,...o?{folder:o}:{},preview:n}},async pair({name:t=k}={}){const e=await K(),n=j(16),o=j(32),r=O(n),s=await G(o,n,"laptop"),a=await G(o,n,"phone"),d=await F(a);if(l.relay){const p=await V(r,"PUT",s,{laptop:await F(s),phone:d},l.relay);if(p.status!==200&&p.status!==201)throw new Error(`link: the relay refused the room (${p.status})`)}for(const p of u.rooms.filter(x=>!x.phoneKey&&!$(x)))D(p.room,"a new pairing code replaced this one");const f=w()+W,m={room:r,token:s,relay:l.relay,phoneVerifier:d,phoneKey:null,name:"",pairedAt:null,lastSeen:null,pending:{psk:O(o),expiresAt:f}};u.rooms.push(m),B();const y=fe({relay:l.relay,gw:l.tunnel,room:n,key:e.publicKey,secret:o,name:String(t||"").slice(0,60)});return I(m),setTimeout(()=>{const p=A(r);p&&!p.phoneKey&&D(r,"the pairing code expired")},W+1e3).unref?.(),{uri:y,svg:ot(y,{ecc:"M"}),expiresAt:f,room:r}},status(){const t=e=>!!v.get(e.room)?.online||!!P.get(e.room)?.online;return{route:l.route,relay:l.relay,tunnel:l.tunnel,...l.problem?{problem:l.problem}:{},routes:he,setup:Je(l.route,{port:g,url:l.tunnel||""}),devices:u.rooms.filter(e=>e.phoneKey).map(e=>({id:e.room,kind:M(e),name:e.name||"Phone",pairedAt:e.pairedAt,lastSeen:e.lastSeen,online:t(e),...$(e)?{partner:{name:e.partner?.name||e.name},scopes:e.scopes||[],route:e.route||null,host:R(e.relay||"")||R(e.route===l.route&&l.tunnel||""),...(e.scopes||[]).includes("agents")?{folder:Q(e,T)}:{},...e.route&&z(e.route)?.kind==="tunnel"&&e.route!==l.route?{routeClosed:!0}:{}}:{},via:P.get(e.room)?.online?"tunnel":v.get(e.room)?.online?"relay":null,...e.relay&&!C(e)?{staleRelay:e.relay}:{},...!$(e)&&l.tunnel&&!e.phoneVerifier?{tunnelNeedsRelink:!0}:{}})),pairing:u.rooms.filter(e=>!e.phoneKey&&!$(e)&&e.pending?.expiresAt>w()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,connected:t(e)}))[0]||null,partnerPairing:u.rooms.filter(e=>!e.phoneKey&&$(e)&&e.pending?.expiresAt>w()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,partner:{name:e.name},scopes:e.scopes||[],route:e.route||null}))[0]||null}},async applySettings(t={}){l=se(t);for(const e of[...v.keys()]){const n=A(e);(!n||!C(n))&&X(e)}if(!l.tunnel)for(const e of[...P.keys()])H(e,1001,"the tunnel was switched off");u.rooms.length&&await K();for(const e of u.rooms)C(e)&&!v.has(e.room)&&I(e);return this.status()},async acceptTunnel(t,e,n){const o=decodeURIComponent(String(t.url||"").split("?")[0].slice(He.length));if(!l.tunnel)return oe(e,404,"not found");const r=A(o),s=String(t.headers["sec-websocket-protocol"]||"").split(",").map(E=>E.trim()).filter(Boolean),d=/^Bearer ([A-Za-z0-9_-]+)$/.exec(String(t.headers.authorization||""))?.[1]||(s.length===2&&s.includes(Y)?s.find(E=>E!==Y):null),f=r&&!r.phoneKey&&r.pending?.expiresAt>w()?r.pending:null,m=d?Buffer.from(await F(d)):null,y=r?.phoneVerifier?Buffer.from(r.phoneVerifier):null;if(!r||!r.phoneKey&&!f||!m||!y||m.length!==y.length||!tt(m,y))return oe(e,403,"not admitted");const p=P.get(o)||{connects:[]};if(P.set(o,p),p.connects=p.connects.filter(E=>w()-E<6e4),p.connects.length>=lt)return oe(e,429,"too many connects");p.connects.push(w());const x=await K(),h=nt(t,e,n,{protocol:Y});if(!h)return;H(o,4001,"replaced"),p.ws=h,p.online=!1;const b=ie(r,x,f,p,E=>{try{h.send(E)}catch{}});p.endpoint=b,h.onmessage=E=>{typeof E.data!="string"&&b.onBinary(new Uint8Array(E.data))},h.onclose=()=>{b.close("socket closed"),p.ws===h&&(p.ws=null,p.endpoint=null,p.online=!1)};const pe=JSON.stringify({t:"peer",up:!0});b.onText(pe),h.send(pe)},async remove(t){const e=A(t);if(!e)return!1;if(e.relay)try{await V(t,"DELETE",e.token,null,e.relay)}catch{}return q(t,"removed"),!0},async start(){if(u.rooms.length){await K();for(const t of u.rooms)I(t)}},stop(){for(const t of[...v.keys()])X(t);for(const t of[...P.keys()])H(t,1001,"going away")},get publicKey(){return _?.publicKey||null}}}export{ut as COMPANION_PATHS,bt as DEFAULT_RELAY,ge as ENTITLEMENT_HEADER,we as INSTALL_HEADER,W as PAIRING_TTL_MS,ft as PARTNER_DEVICES_REQUIRE_PRO,dt as companionMay,Nt as createLinkHost,ae as defaultLinkPath,mt as deviceMayLink,Lt as partnerDevicesOnDisk,Q as partnerFolderFor,ve as phoneMayLink};
1
+ import{readFileSync as Oe,writeFileSync as Re,renameSync as Ue,mkdirSync as ee,chmodSync as Ce}from"node:fs";import{dirname as F,join as pe,resolve as ue,sep as Ie}from"node:path";import de from"node:os";import{createLinkEndpoint as De}from"@chatpanel/events/link-connect.js";import{noiseCrypto as Fe}from"@chatpanel/events/link-noise.js";import{pairingUri as fe,pairingCode as Me,admissionToken as G,admissionVerifier as M,toB64url as O,fromB64url as te,coalesceChunks as je}from"@chatpanel/events/link-protocol.js";import{linkPaths as me,linkRoute as z,checkLinkRoute as Be,DEFAULT_LINK_RELAY as Ve,LINK_ROUTES as he,LINK_TUNNEL_ROOM_PATH as He,tunnelSetup as Je}from"@chatpanel/events/link-routes.js";import{linkDeviceKind as j,partnerMay as Ge,partnerHeaders as ze,withoutLinkMarks as We,linkMarkHeaders as Ye,checkPartnerName as Qe,checkPartnerScopes as Ze,describePartnerAccess as Xe,checkPartnerFolder as qe,partnerFolderSlug as et}from"@chatpanel/events/link-scopes.js";import{timingSafeEqual as tt}from"node:crypto";import{acceptWebSocket as nt,refuseUpgrade as ne}from"./ws-accept.js";import{configPath as ot}from"./configstore.js";import{qrSvg as rt}from"@chatpanel/events/qr.js";import{verifyEntitlement as at,licenseFromPayload as st,can as it,FEATURE_TIER as ye}from"@chatpanel/events/entitlement.js";const bt="https://link.chatpanel.net",W=10*6e4,ct=3e4,oe=[1e3,2e3,5e3,1e4,3e4,6e4],lt=30,Y="chatpanel-link.v1",pt=/(^|\n): ?ping\n\n/g,ut=4,dt=[/^\/v1\/models(?:\/|$|\?)/,/^\/v1\/chat\/completions$/,/^\/v1\/messages$/,/^\/v1\/audio\/(?:transcriptions|speech)$/,/^\/v1\/history\/(?:search|smart-search|get|list|related|status)(?:$|\?)/,/^\/v1\/history\/(?:records|stream)(?:$|\?)/,/^\/v1\/memory\/(?:recall|list|remember)(?:$|\?)/,/^\/v1\/(?:research|search|read|rerank|decide|capabilities|fusions)(?:$|\?)/,/^\/v1\/status$/,/^\/v1\/stt\/sessions(?:\/[0-9a-f-]{36}(?:\/audio)?)?$/,/^\/v1\/link\/routes$/,/^\/v1\/agent-sessions(?:\/read|\/adopt|\/catchup)?$/],ft=c=>dt.some(i=>i.test(String(c||""))),ge="x-chatpanel-entitlement",we="x-chatpanel-install",ke=(c,i)=>{for(const[g,k]of Object.entries(c||{}))if(g.toLowerCase()===i)return String(k||"");return""};async function Ee(c,{now:i=Date.now()}={}){if(!ye.link||ye.link==="free")return!1;const g=ke(c,ge),k=ke(c,we);if(!g||!k)return!1;const b=await at(g,k,{now:i});return!!b&&it(st(b,{at:i}),"link",0,i)}const mt=!1;async function ht(c,i,{now:g=Date.now(),phoneCheck:k=Ee,ownerIsPro:b=async()=>!1}={}){return j(c)==="partner"?mt?!!await b():!0:k(i?.headers||{},{now:g})}const N=c=>Object.assign(new Error(c),{code:"bad_partner"}),R=c=>{try{return new URL(c).host}catch{return""}};function Kt(c=re()){return Se(c).rooms.filter(i=>j(i)==="partner"&&i.phoneKey).map(i=>({id:i.room,kind:"partner",name:i.name,partner:{name:i.partner?.name||i.name},scopes:i.scopes||[],route:i.route||null,host:R(i.relay||i.gw||""),pairedAt:i.pairedAt||null,lastSeen:i.lastSeen||null,...(i.scopes||[]).includes("agents")?{folder:Q(i,c)}:{}}))}function Q(c,i=re()){return c?.folder||pe(F(i),"partners",et(c?.partner?.name||c?.name))}const yt=(c,i)=>{const g=ue(c),k=ue(i);return g===k||g.startsWith(`${k}${Ie}`)};function re(c=process.env){return c.CHATPANEL_LINK_STATE||pe(F(ot(c)),"link.json")}function Se(c){try{const i=JSON.parse(Oe(c,"utf8"));return{v:1,key:i.key||null,rooms:Array.isArray(i.rooms)?i.rooms:[]}}catch{return{v:1,key:null,rooms:[]}}}function ve(c,i){ee(F(c),{recursive:!0});const g=`${c}.tmp`;Re(g,JSON.stringify(i,null,2),{mode:384});try{Ce(g,384)}catch{}Ue(g,c)}function xt({settings:c={},relay:i=null,port:g=4320,name:k=de.hostname(),dispatch:b,path:$=re(),fetch:Te=globalThis.fetch,WebSocket:$e=globalThis.WebSocket,now:w=()=>Date.now(),random:B=S=>globalThis.crypto.getRandomValues(new Uint8Array(S)),crypto:Z=Fe(),log:U=S=>{},mayLink:Pe=Ee,ownerIsPro:Ae=async()=>!1,home:_e=de.homedir(),confined:Le=process.env.CHATPANEL_CONFINED==="1"}={}){const S=i?new URL(i).origin:null;if(S&&!/^https:/.test(S)&&!/^http:\/\/127\.0\.0\.1(?::\d+)?$/.test(S))throw new Error("link: the relay must be https");const ae=t=>{const e=me(t);return S&&e.relay?{...e,relay:S}:e};let l=ae(c);l.problem&&U(`link: ${l.problem} — using ChatPanel Link`);let d=Se($);const Ne=S||me({relayUrl:c?.relayUrl}).relay;for(const t of d.rooms)t.relay===void 0&&(t.relay=Ne);const E=new Map,P=new Map;let _=null;async function K(){return _||(d.key?_=await Z.keyPairFromPrivate(te(d.key)):(_=await Z.generateKeyPair(),d.key=O(_.raw),ve($,d)),_)}const A=t=>d.rooms.find(e=>e.room===t)||null,V=()=>ve($,d),C=t=>j(t)==="partner"?!!t.relay:!!t.relay&&t.relay===l.relay,T=t=>j(t)==="partner",H=async(t,e,n,o,a)=>{try{return await Te(`${a}/v1/room/${t}`,{method:e,headers:{authorization:`Bearer ${n}`,...o?{"content-type":"application/json"}:{}},body:o?JSON.stringify(o):void 0})}catch(s){const r=s?.cause?.code||"",f=r==="ENOTFOUND"?"this computer cannot look up its name (a VPN or DNS that does not know it yet)":r?`${r}`:s?.message||"no answer";throw new Error(`cannot reach the Link relay at ${new URL(a).host}: ${f}`)}};async function be(t,e,n){t.lastSeen=w();const o=T(t);if(o?!Ge(t.scopes,e):!ft(e.path))return await n.head(403,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:o?`link: partner "${t.name}" may not call ${e.method} ${e.path.split("?")[0]} — its scopes are ${(t.scopes||[]).join(", ")||"none"}`:"link: a paired phone may not call this",type:"forbidden",...o?{code:"link_scope"}:{}}})),n.end();if(!await ht(t,e,{now:w(),phoneCheck:Pe,ownerIsPro:Ae}))return await n.head(402,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:o?"ChatPanel Link partner devices need ChatPanel Pro on this computer":"ChatPanel Link needs Pro on this phone — upgrade on the phone, or restore its Pro under Settings › Plan",type:"pro_required"}})),n.end();if(e.path==="/v1/link/routes")return await n.head(200,{"content-type":"application/json"}),await n.write(JSON.stringify({route:l.route,relay:C(t)?t.relay:null,gw:l.tunnel})),n.end();let a={};if(o)a=ze(e.headers);else for(const[u,h]of Object.entries(e.headers||{}))u.toLowerCase()!==ge&&u.toLowerCase()!==we&&(a[u]=h);a={...We(a),...Ye(t)};const s=e.method==="GET"?void 0:await e.body.bytes();let r;try{r=await b({method:e.method,path:e.path,headers:a,body:s,device:t.room,signal:n.signal})}catch(u){if(n.cancelled)return;throw u}const f={};r.headers?.forEach?.((u,h)=>{f[h]=u});let m=!1;try{await n.head(r.status,f)}catch{m=!0}if(r.body){const u=/event-stream/.test(String(r.headers?.get?.("content-type")||""));try{for await(const h of je(Ke(r.body,u))){if(n.cancelled)break;if(!m)try{await n.write(h)}catch{m=!0}}}catch(h){if(!n.cancelled)throw h}}if(!(m||n.cancelled))return n.end()}async function*Ke(t,e){for await(const n of t){let o=n instanceof Uint8Array?n:new TextEncoder().encode(String(n));if(e){const a=new TextDecoder().decode(o);if(a.includes(": ping")){const s=a.replace(pt,"$1");if(!s)continue;o=new TextEncoder().encode(s)}}yield o}}function se(t,e,n,o,a){return De({side:"laptop",keyPair:e,crypto:Z,psk:t.phoneKey?null:te(n.psk),peerKey:t.phoneKey?te(t.phoneKey):null,sendBytes:a,onRequest:(s,r)=>be(t,s,r),onSession:(s,r)=>{o.online=!0,o.attempts=0,t.lastSeen=w(),r.paired&&(t.phoneKey=O(r.peerKey),T(t)||(t.name=r.name||t.name||"Phone"),t.pairedAt=w(),t.pending=null,U(`link: paired ${t.name}`)),V()},onEnd:()=>{o.online=!1}})}async function I(t){if(!C(t))return;const e=E.get(t.room)||{attempts:0,stopped:!1,online:!1};if(E.set(t.room,e),e.stopped)return;const n=await K(),o=t.pending&&t.pending.expiresAt>w()?t.pending:null;if(!t.phoneKey&&!o){D(t.room,"the pairing code expired");return}const a=`${t.relay.replace(/^http/,"ws")}/v1/room/${t.room}`;let s;try{s=new $e(a,[Y,t.token])}catch(r){ie(t,r?.message);return}s.binaryType="arraybuffer",e.ws=s,e.endpoint=se(t,n,o,e,r=>{try{s.send(r)}catch{}}),s.onopen=()=>{if(e.stopped||E.get(t.room)!==e){try{s.close(1e3,"stopped")}catch{}return}clearInterval(e.keepalive),e.keepalive=setInterval(()=>{try{s.send("ping")}catch{}},ct),e.keepalive.unref?.()},s.onmessage=r=>typeof r.data=="string"?e.endpoint.onText(r.data):e.endpoint.onBinary(new Uint8Array(r.data)),s.onclose=r=>{if(clearInterval(e.keepalive),e.online=!1,e.endpoint?.close("socket closed"),!e.stopped){if(r?.code===4003||r?.code===4004){q(t.room,"the relay removed the room");return}ie(t,r?.code===4001?"replaced":r?.code===4008?"over the relay's budget":`closed ${r?.code||""}`,r?.code===4001?5:r?.code===4008?ut:null)}},s.onerror=()=>{}}function ie(t,e,n=null){const o=E.get(t.room);if(!o||o.stopped)return;const a=n??Math.min(o.attempts,oe.length-1);o.attempts++,clearTimeout(o.timer),o.timer=setTimeout(()=>I(t),oe[a]),o.timer.unref?.(),U(`link: ${e}; again in ${oe[a]/1e3}s`)}function X(t){const e=E.get(t);if(e){e.stopped=!0,clearTimeout(e.timer),clearInterval(e.keepalive),e.endpoint?.close("stopped");try{e.ws?.close(1e3,"stopped")}catch{}E.delete(t)}}function J(t,e=1e3,n="stopped"){const o=P.get(t);if(o?.ws){o.endpoint?.close(n);try{o.ws.close(e,n)}catch{}o.ws=null,o.endpoint=null,o.online=!1}}function D(t,e){const n=A(t);n&&!n.phoneKey&&n.relay&&H(t,"DELETE",n.token,null,n.relay).catch(()=>{}),q(t,e)}function q(t,e){X(t),J(t,4004,"room removed"),P.delete(t),d.rooms=d.rooms.filter(n=>n.room!==t),V(),U(`link: ${e}`)}function xe({route:t=null,relay:e=""}={}){const n=t||(e?"relay":l.route);if(!z(n))throw N(`unknown route "${n}" — one of ${he.map(a=>a.id).join(", ")}`);if(z(n).kind==="tunnel"){if(l.route!==n||!l.tunnel)throw N(`this gateway's ${z(n).label} door is not open — set it as the route first (chatpanel-gateway link route ${n} --gw <https address>), then pair`);return{route:n,relay:null,gw:l.tunnel,host:R(l.tunnel)}}if(n==="relay"){const a=e||(l.route==="relay"?l.relay:"");if(!a)throw N('the relay route needs the relay’s https address (--relay <url>), or "Your own relay" set as the route');let s;try{s=Be({id:"relay",url:a})}catch(r){throw N(r.message)}return{route:s.id,relay:s.url,gw:null,host:R(s.url)}}const o=S||Ve;return{route:"link",relay:o,gw:null,host:R(o)}}function ce({partner:t,scopes:e,route:n=null,relay:o="",folder:a=""}={}){const s=Qe(t),r=Ze(e),f=xe({route:n,relay:o});let m="";if(r.includes("agents")){try{m=String(a||"").trim()?qe(a,{name:s,home:_e}):Q({partner:{name:s}},$)}catch(u){throw N(u.message)}if(Le&&!yt(m,F($)))throw N(`this gateway runs confined and writes only ${F($)} — leave the folder empty (the default is inside it), or run the gateway unconfined to use ${m}`)}return{via:f,folder:m,preview:Xe({partner:s,scopes:r,route:f.route,host:f.host,folder:m})}}return{previewPartner(t={}){return ce(t).preview},deviceNameOf(t){const e=A(t);return e?.phoneKey?String(e.name||""):""},partnerFolderOf(t){const e=A(t);if(!e||!T(e)||!e.phoneKey||!(e.scopes||[]).includes("agents"))return null;const n=Q(e,$);try{ee(n,{recursive:!0,mode:448})}catch{return null}return n},async pairPartner(t={}){const{via:e,preview:n,folder:o}=ce(t);if(o)try{ee(o,{recursive:!0,mode:448})}catch(y){throw N(`could not create ${o}: ${y.message}`)}const a=await K(),s=B(16),r=B(32),f=O(s),m=await G(r,s,"laptop"),u=await M(await G(r,s,"phone"));if(e.relay){const y=await H(f,"PUT",m,{laptop:await M(m),phone:u},e.relay);if(y.status!==200&&y.status!==201)throw new Error(`link: the relay refused the room (${y.status})`)}for(const y of d.rooms.filter(L=>!L.phoneKey&&T(L)))D(y.room,"a new partner code replaced this one");const h=w()+W,p={room:f,token:m,relay:e.relay,phoneVerifier:u,phoneKey:null,name:n.partner,pairedAt:null,lastSeen:null,pending:{psk:O(r),expiresAt:h},kind:"partner",partner:{name:n.partner},scopes:n.scopes,route:e.route,...o?{folder:o}:{}};d.rooms.push(p),V();const x=Me({uri:fe({relay:e.relay,gw:e.gw,room:s,key:a.publicKey,secret:r,name:""}),expiresAt:h,route:e.route});return I(p),setTimeout(()=>{const y=A(f);y&&!y.phoneKey&&D(f,"the partner code expired")},W+1e3).unref?.(),U(`link: partner code issued for ${n.partner} (${n.scopes.join(", ")}; route ${e.route} via ${e.host})`),{code:x,expiresAt:h,room:f,kind:"partner",partner:{name:n.partner},scopes:n.scopes,route:e.route,host:e.host,...o?{folder:o}:{},preview:n}},async pair({name:t=k}={}){const e=await K(),n=B(16),o=B(32),a=O(n),s=await G(o,n,"laptop"),r=await G(o,n,"phone"),f=await M(r);if(l.relay){const p=await H(a,"PUT",s,{laptop:await M(s),phone:f},l.relay);if(p.status!==200&&p.status!==201)throw new Error(`link: the relay refused the room (${p.status})`)}for(const p of d.rooms.filter(x=>!x.phoneKey&&!T(x)))D(p.room,"a new pairing code replaced this one");const m=w()+W,u={room:a,token:s,relay:l.relay,phoneVerifier:f,phoneKey:null,name:"",pairedAt:null,lastSeen:null,pending:{psk:O(o),expiresAt:m}};d.rooms.push(u),V();const h=fe({relay:l.relay,gw:l.tunnel,room:n,key:e.publicKey,secret:o,name:String(t||"").slice(0,60)});return I(u),setTimeout(()=>{const p=A(a);p&&!p.phoneKey&&D(a,"the pairing code expired")},W+1e3).unref?.(),{uri:h,svg:rt(h,{ecc:"M"}),expiresAt:m,room:a}},status(){const t=e=>!!E.get(e.room)?.online||!!P.get(e.room)?.online;return{route:l.route,relay:l.relay,tunnel:l.tunnel,...l.problem?{problem:l.problem}:{},routes:he,setup:Je(l.route,{port:g,url:l.tunnel||""}),devices:d.rooms.filter(e=>e.phoneKey).map(e=>({id:e.room,kind:j(e),name:e.name||"Phone",pairedAt:e.pairedAt,lastSeen:e.lastSeen,online:t(e),...T(e)?{partner:{name:e.partner?.name||e.name},scopes:e.scopes||[],route:e.route||null,host:R(e.relay||"")||R(e.route===l.route&&l.tunnel||""),...(e.scopes||[]).includes("agents")?{folder:Q(e,$)}:{},...e.route&&z(e.route)?.kind==="tunnel"&&e.route!==l.route?{routeClosed:!0}:{}}:{},via:P.get(e.room)?.online?"tunnel":E.get(e.room)?.online?"relay":null,...e.relay&&!C(e)?{staleRelay:e.relay}:{},...!T(e)&&l.tunnel&&!e.phoneVerifier?{tunnelNeedsRelink:!0}:{}})),pairing:d.rooms.filter(e=>!e.phoneKey&&!T(e)&&e.pending?.expiresAt>w()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,connected:t(e)}))[0]||null,partnerPairing:d.rooms.filter(e=>!e.phoneKey&&T(e)&&e.pending?.expiresAt>w()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,partner:{name:e.name},scopes:e.scopes||[],route:e.route||null}))[0]||null}},async applySettings(t={}){l=ae(t);for(const e of[...E.keys()]){const n=A(e);(!n||!C(n))&&X(e)}if(!l.tunnel)for(const e of[...P.keys()])J(e,1001,"the tunnel was switched off");d.rooms.length&&await K();for(const e of d.rooms)C(e)&&!E.has(e.room)&&I(e);return this.status()},async acceptTunnel(t,e,n){const o=decodeURIComponent(String(t.url||"").split("?")[0].slice(He.length));if(!l.tunnel)return ne(e,404,"not found");const a=A(o),s=String(t.headers["sec-websocket-protocol"]||"").split(",").map(v=>v.trim()).filter(Boolean),f=/^Bearer ([A-Za-z0-9_-]+)$/.exec(String(t.headers.authorization||""))?.[1]||(s.length===2&&s.includes(Y)?s.find(v=>v!==Y):null),m=a&&!a.phoneKey&&a.pending?.expiresAt>w()?a.pending:null,u=f?Buffer.from(await M(f)):null,h=a?.phoneVerifier?Buffer.from(a.phoneVerifier):null;if(!a||!a.phoneKey&&!m||!u||!h||u.length!==h.length||!tt(u,h))return ne(e,403,"not admitted");const p=P.get(o)||{connects:[]};if(P.set(o,p),p.connects=p.connects.filter(v=>w()-v<6e4),p.connects.length>=lt)return ne(e,429,"too many connects");p.connects.push(w());const x=await K(),y=nt(t,e,n,{protocol:Y});if(!y)return;J(o,4001,"replaced"),p.ws=y,p.online=!1;const L=se(a,x,m,p,v=>{try{y.send(v)}catch{}});p.endpoint=L,y.onmessage=v=>{typeof v.data!="string"&&L.onBinary(new Uint8Array(v.data))},y.onclose=()=>{L.close("socket closed"),p.ws===y&&(p.ws=null,p.endpoint=null,p.online=!1)};const le=JSON.stringify({t:"peer",up:!0});L.onText(le),y.send(le)},async remove(t){const e=A(t);if(!e)return!1;if(e.relay)try{await H(t,"DELETE",e.token,null,e.relay)}catch{}return q(t,"removed"),!0},async start(){if(d.rooms.length){await K();for(const t of d.rooms)I(t)}},stop(){for(const t of[...E.keys()])X(t);for(const t of[...P.keys()])J(t,1001,"going away")},get publicKey(){return _?.publicKey||null}}}export{dt as COMPANION_PATHS,bt as DEFAULT_RELAY,ge as ENTITLEMENT_HEADER,we as INSTALL_HEADER,W as PAIRING_TTL_MS,mt as PARTNER_DEVICES_REQUIRE_PRO,ft as companionMay,xt as createLinkHost,re as defaultLinkPath,ht as deviceMayLink,Kt as partnerDevicesOnDisk,Q as partnerFolderFor,Ee as phoneMayLink};
package/src/server.js CHANGED
@@ -11,13 +11,13 @@ data: ${JSON.stringify(vt(t))}
11
11
  `)}catch{Ee.delete(t)}},25e3).unref?.();const fe=await Wr(),me=Kr(),Ce=sn({key:gt()}),Ie=ln({key:gt()}),he=dn({key:gt()}),re=an({scorecards:Ce,engines:Ie}),At=new Set,Io=(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=is(),Ro=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),us=16,ms=/^mcp[_-]/i,Jo=t=>t&&t.function&&t.function.name||t&&t.name||"",ps=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 hs(t,d){if(!t)return"";if(d==="responses"){const p=t.input;return typeof p=="string"?p:Array.isArray(p)?p.map(b=>Lo(b&&(b.content??b))).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 ys(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 fs(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 zo=Date.now();function gs(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 ws(t){const d=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return d?{kind:d[1],id:d[2],...d[3]?{model:d[3]}:{}}:null}function bs(t){const d=performance.now(),u={};let p=!1;const b=(y,$)=>{u[y]=Math.round($*10)/10};return{meta:{},timings:u,mark:b,lap(y,$){b(y,performance.now()-$)},clock(){return performance.now()},commit(){if(p)return;p=!0,b("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}`:""} · ${gs(u)}`)})}}}function Go(t,d){if(!t||!t.byToken||d!=="types"&&d!=="values")return;const u=[];for(const[p,b]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:b}:{token:B,type:$})}return u}function vs(t,d,u){return Pt.matches(t)||"anthropic-version"in d?{kind:"anthropic",adapter:Pt,redactable:Pt.matches(t),base:u.upstreams?.anthropic?.baseUrl}:Co.matches(t)?{kind:"responses",adapter:Co,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(Ro.has(u))return{agent:u,agentModel:""};const p=u.indexOf("/");if(p>0){const b=u.slice(0,p);if(Ro.has(b))return{agent:b,agentModel:u.slice(p+1)}}return{agent:d.bridge.agent,agentModel:""}}function Ho(t,d){return Bt(t,d).agent}function ks(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 Ss(t,d){try{const u=new URL(t),p=u.hostname.replace(/^\[|\]$/g,""),b=p==="127.0.0.1"||p==="localhost"||p==="::1",y=u.port||(u.protocol==="https:"?"443":"80");return b&&String(y)===String(d.port)}catch{return!1}}const Ts=25*1024*1024;async function S(t,d){const u=[];let p=0;for await(const b of t){if(p+=b.length,d&&p>d){const y=new Error("payload too large");throw y.code=413,y}u.push(b)}return Buffer.concat(u)}function a(t,d,u){t.writeHead(d,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function Uo(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=J.health(),b=p.ok&&u==="full";return{source:"bundled",state:p.state,model:p.model||t?.ner?.model||null,installed:J.modelOnDisk(t?.ner?.model||void 0),error:p.error||null,ready:b,tier:u,coverage:b?"names":"patterns"}}async function Vo(t){if(J.state()!=="off"){const u=J.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=Uo(t);if(!d)return{configured:!1,ok:!1,url:null,model:null};try{const u=await tt(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 xs(t,d){const u={};for(const[p,b]of Object.entries(t)){const y=p.toLowerCase();y.startsWith("x-chatpanel-")||jo.has(y)||(u[p]=b)}u["accept-encoding"]="identity";try{u.host=new URL(d).host}catch{}return u}async function Fo(t,d,u,p){const b=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=>{_(),rt(d.id);const z=b.push(U);z&&(R+=z,t.write(u.sseDelta(z)))},onToolRequest:({name:U,restoredArgs:z,toolId:X})=>{if(_(),rt(d.id),d.ownerApprovals&&fo(U)){V=z;return}const te=b.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=b.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=is(),Ro=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),us=16,ms=/^mcp[_-]/i,Jo=t=>t&&t.function&&t.function.name||t&&t.name||"",ps=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 hs(t,d){if(!t)return"";if(d==="responses"){const p=t.input;return typeof p=="string"?p:Array.isArray(p)?p.map(b=>Lo(b&&(b.content??b))).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 ys(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 fs(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 zo=Date.now();function gs(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 ws(t){const d=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return d?{kind:d[1],id:d[2],...d[3]?{model:d[3]}:{}}:null}function bs(t){const d=performance.now(),u={};let p=!1;const b=(y,$)=>{u[y]=Math.round($*10)/10};return{meta:{},timings:u,mark:b,lap(y,$){b(y,performance.now()-$)},clock(){return performance.now()},commit(){if(p)return;p=!0,b("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}`:""} · ${gs(u)}`)})}}}function Go(t,d){if(!t||!t.byToken||d!=="types"&&d!=="values")return;const u=[];for(const[p,b]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:b}:{token:B,type:$})}return u}function vs(t,d,u){return Pt.matches(t)||"anthropic-version"in d?{kind:"anthropic",adapter:Pt,redactable:Pt.matches(t),base:u.upstreams?.anthropic?.baseUrl}:Co.matches(t)?{kind:"responses",adapter:Co,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(Ro.has(u))return{agent:u,agentModel:""};const p=u.indexOf("/");if(p>0){const b=u.slice(0,p);if(Ro.has(b))return{agent:b,agentModel:u.slice(p+1)}}return{agent:d.bridge.agent,agentModel:""}}function Ho(t,d){return Bt(t,d).agent}function ks(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 Ss(t,d){try{const u=new URL(t),p=u.hostname.replace(/^\[|\]$/g,""),b=p==="127.0.0.1"||p==="localhost"||p==="::1",y=u.port||(u.protocol==="https:"?"443":"80");return b&&String(y)===String(d.port)}catch{return!1}}const Ts=25*1024*1024;async function S(t,d){const u=[];let p=0;for await(const b of t){if(p+=b.length,d&&p>d){const y=new Error("payload too large");throw y.code=413,y}u.push(b)}return Buffer.concat(u)}function a(t,d,u){t.writeHead(d,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function Uo(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=J.health(),b=p.ok&&u==="full";return{source:"bundled",state:p.state,model:p.model||t?.ner?.model||null,installed:J.modelOnDisk(t?.ner?.model||void 0),error:p.error||null,ready:b,tier:u,coverage:b?"names":"patterns"}}async function Vo(t){if(J.state()!=="off"){const u=J.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=Uo(t);if(!d)return{configured:!1,ok:!1,url:null,model:null};try{const u=await tt(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 xs(t,d){const u={};for(const[p,b]of Object.entries(t)){const y=p.toLowerCase();y.startsWith("x-chatpanel-")||jo.has(y)||(u[p]=b)}u["accept-encoding"]="identity";try{u.host=new URL(d).host}catch{}return u}async function Fo(t,d,u,p){const b=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 F=null;const P={onText:V=>{_(),rt(d.id);const z=b.push(V);z&&(R+=z,t.write(u.sseDelta(z)))},onToolRequest:({name:V,restoredArgs:z,toolId:X})=>{if(_(),rt(d.id),d.ownerApprovals&&fo(V)){F=z;return}const te=b.flush();te&&(R+=te,t.write(u.sseDelta(te))),t.write(u.sseToolCalls([{id:X,name:V,arguments:JSON.stringify(z)}])),t.write(u.sseToolFinish(y.value)),p&&p.lap("stream",E),t.end(),p?.commit(),j()},onDone:()=>{const V=b.flush();V&&(R+=V,t.write(u.sseDelta(V))),t.write(u.sseTail(y.value)),p&&p.lap("stream",E),t.end(),$?.end("ok"),Ge(d.id),p?.commit(),j(),Dt(d)},onError:V=>{t.write(`data: ${JSON.stringify({error:{message:V.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 Jr(d,P)!=="parked"||!V)return;const z=d.ownerApprovals,X=new AbortController,te=()=>X.abort();t.once("close",te);const oe=setInterval(()=>{rt(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:V=>{y.add(V),$?.add(V)}};for(;;){if(F=null,await Jr(d,P)!=="parked"||!F)return;const z=d.ownerApprovals,X=new AbortController,te=()=>X.abort();t.once("close",te);const oe=setInterval(()=>{rt(d.id),t.writableEnded||t.write(`: waiting for the owner’s approval
17
17
 
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 _s(t,d,{kind:u,adapter:p,agent:b,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=Mo(_,{...X?{model:X}:{},...y||{}}),oe=ze(_.bridge.token),ye=yt(u,E?.model||b),Y={tier:_.redaction.tier==="full"?"full":"basic",dictionary:lr(_.redaction,R),entities:[]},ge=await je(_),C=Rr({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 Ir({bridgeUrl:ge,agent:b,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()),Fo(d,C,ye,P)}async function Os(t,d,u,p,b=null){rt(d.id),d.rounds=(d.rounds||0)+1;try{const $=b?b.clock():0;await no(d,u),b&&b.lap("redact",$)}catch($){return d.linkTurn?.end("error",{code:"tool_result"}),Ge(d.id),b?.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()),Fo(t,d,y,b)}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 Es(t,d,{kind:u,adapter:p,redactable:b,pathname:y,agentOverride:$,harness:B,trace:E,run:T=null,owner:_=null,link:R=null},j,V,P,U){if(!b)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 Os(d,ie,K.content,j?.model,E)}const W=p.extractTools(j);if((W.length||_)&&j?.stream===!0){const k=$||Ho(j?.model,P),ie=R?$t.begin({...R,agentId:k}):null;return _s(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=$||Ho(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:Mo(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,We=Y.full(ir(K,V),W.value);return E&&E.lap("restore",ie),d.writeHead(200,{"content-type":Y.contentType}),d.end(We),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(sr(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(F,{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 _s(t,d,{kind:u,adapter:p,agent:b,run:y=null,owner:$=null,linkTurn:B=null},E,T,_,R,j,F=null,P=null){const{messages:V,system:z}=p.toTurn(E),{agentModel:X}=Bt(E?.model,_),te=Mo(_,{...X?{model:X}:{},...y||{}}),oe=ze(_.bridge.token),ye=yt(u,E?.model||b),Y={tier:_.redaction.tier==="full"?"full":"basic",dictionary:lr(_.redaction,R),entities:[]},ge=await je(_),C=Rr({vault:T,redactOpts:Y,bridgeUrl:ge,token:oe,harness:F});$&&(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 Ir({bridgeUrl:ge,agent:b,token:oe,messages:V,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()),Fo(d,C,ye,P)}async function Os(t,d,u,p,b=null){rt(d.id),d.rounds=(d.rounds||0)+1;try{const $=b?b.clock():0;await no(d,u),b&&b.lap("redact",$)}catch($){return d.linkTurn?.end("error",{code:"tool_result"}),Ge(d.id),b?.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()),Fo(t,d,y,b)}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 Es(t,d,{kind:u,adapter:p,redactable:b,pathname:y,agentOverride:$,harness:B,trace:E,run:T=null,owner:_=null,link:R=null},j,F,P,V){if(!b)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 Os(d,ie,K.content,j?.model,E)}const W=p.extractTools(j);if((W.length||_)&&j?.stream===!0){const k=$||Ho(j?.model,P),ie=R?$t.begin({...R,agentId:k}):null;return _s(t,d,{kind:u,adapter:p,agent:k,run:T,owner:_,linkTurn:ie},j,F,P,V,W,B,E)}}const{messages:z,system:X}=p.toTurn(j),te=$||Ho(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:Mo(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,We=Y.full(ir(K,F),W.value);return E&&E.lap("restore",ie),d.writeHead(200,{"content-type":Y.contentType}),d.end(We),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(F),o=E?E.clock():0;let f=o;const i=Ct();let Z="",H=!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(sr(k,F)))}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){H=!0,d.write(`data: ${JSON.stringify({error:{message:K.message,type:"bridge_error"}})}
19
19
 
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 Ps(t,d,u=""){const p=String(t||"").replace(/\/+$/,""),b=String(d||"").split("/")[1];return b&&p.endsWith(`/${b}`)?p.slice(0,-(b.length+1))+d+u:p+d+u}const $s=9e4;function As(t,d,u){if(d===u)return t;const p=d/u,b=new Float32Array(Math.floor(t.length/p));for(let y=0;y<b.length;y++){const $=y*p,B=Math.floor($),E=Math.min(t.length-1,B+1),T=$-B;b[y]=t[B]*(1-T)+t[E]*T}return b}const Wo=new WeakMap,Ns=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function Ko(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:b="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=b!=="GET"&&b!=="DELETE";try{const _=T?(await S(t,u.maxBodyBytes)).toString("utf8"):"",R=await fetch(`${B}${p}`,{method:b,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 b=u.toString();return b?`?${b}`:""}async function Bs(t,d,{adapter:u,kind:p,pathname:b,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=xs(t.headers,$);B&&(E==="anthropic"?(C["x-api-key"]=B,delete C.authorization):C.authorization=`Bearer ${B}`);const ee=pr(Ps($,b,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?_n():null,pe=ee?P.body.pipeThrough(ee.stream):P.body,n=p==="openai"?ar(pe,d,V,T):nr(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")?On(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 Ms(t=Wt()){const d=vr({first:async n=>{const o=Number(new URL(n).port),f=Un.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=wr({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):br(n),newId:()=>kr()}),p=ea({version:ue}),b=ga({log:n=>console.log(` ${n}`)}),y=t.link?.enabled===!1?null:ta({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:()=>ke(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 ${Pa}`));let $=null;const B=()=>{if(!$){const n=t.read||{};$=qn({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)=>zn().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=Hn({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:Ue.join(Ue.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=Fn({warmMs:(Number.isFinite(U)&&U>=0?U:10)*6e4,log:n=>console.log(n)}),X=Vn({cfg:t,wake:(n,o)=>P().wake(n,o),embedded:z,asleep:n=>P().isAsleep(n)});let te=null;const oe=()=>(te||(te=Zn({store:Xn({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?ka({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;Y=wa({reader:B(),searxng:o,engines:()=>Sa(t),wakeSearxng:()=>P().wake("searxng"),defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await qe([ht(()=>i,Z=>{i=Z})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return Y};yr(t.allowedExtensionIds||[]);const C=[],ee=n=>{C.push(n),C.length>50&&C.shift()},pe=tr(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(!ys(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(ct(t.host)&&ra(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&&fs(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return G(n)?a(o,200,{token:_e()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!G(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=fr();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=gr(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Je(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Je(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=Je(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=Je(n);return a(o,200,{ok:!0,trust:e,paired:Yt(e),version:ue})}if(i==="/audit"&&n.method==="GET")return G(n)?a(o,200,Tr(t,{version:ue,startedAt:zo,managed:Le(),certificates:{..._r(),wanted:Xt(t)},linkPartners:y?y.status().devices.filter(e=>e.kind==="partner"):[],confined:wt({stateDir:Ue.dirname(ce())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!G(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await hn(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:gn()})}if(i==="/update"&&n.method==="POST"){const e=fn(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"&&!G(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!G(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!G(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!G(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!G(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!G(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${ue} is running.
20
+ `)}E&&E.lap("stream",f),d.end(),oe&&(oe.add(i.value),oe.end(C.signal.aborted?"aborted":H?"error":"ok",{code:"bridge_error"})),E?.commit(),F&&Z&&Kt(Z,P.redaction)}function Ps(t,d,u=""){const p=String(t||"").replace(/\/+$/,""),b=String(d||"").split("/")[1];return b&&p.endsWith(`/${b}`)?p.slice(0,-(b.length+1))+d+u:p+d+u}const $s=9e4;function As(t,d,u){if(d===u)return t;const p=d/u,b=new Float32Array(Math.floor(t.length/p));for(let y=0;y<b.length;y++){const $=y*p,B=Math.floor($),E=Math.min(t.length-1,B+1),T=$-B;b[y]=t[B]*(1-T)+t[E]*T}return b}const Wo=new WeakMap,Ns=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function Ko(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:b="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=b!=="GET"&&b!=="DELETE";try{const _=T?(await S(t,u.maxBodyBytes)).toString("utf8"):"",R=await fetch(`${B}${p}`,{method:b,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 b=u.toString();return b?`?${b}`:""}async function Bs(t,d,{adapter:u,kind:p,pathname:b,search:y,base:$,destKey:B,destProtocol:E,harness:T,trace:_,link:R=null},j,F){let P;const V=_?_.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=xs(t.headers,$);B&&(E==="anthropic"?(C["x-api-key"]=B,delete C.authorization):C.authorization=`Bearer ${B}`);const ee=pr(Ps($,b,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",V);const C=_?_.clock():0;d.writeHead(P.status,Y);const ee=z?_n():null,pe=ee?P.body.pipeThrough(ee.stream):P.body,n=p==="openai"?ar(pe,d,F,T):nr(pe,d,F);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",V),z&&oe(P.status,ye.includes("json")?On(ge.toString("utf8")):null),F&&ye.includes("application/json"))try{const C=_?_.clock():0,ee=u.restoreResponse(JSON.parse(ge.toString("utf8")),F,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 Ms(t=Wt()){const d=vr({first:async n=>{const o=Number(new URL(n).port),f=Un.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=wr({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):br(n),newId:()=>kr()}),p=ea({version:ue}),b=ga({log:n=>console.log(` ${n}`)}),y=t.link?.enabled===!1?null:ta({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:f,body:i,device:Z,signal:H})=>fetch(`http://127.0.0.1:${pe.address()?.port||t.port}${o}`,{method:n,body:i,...H?{signal:H}:{},headers:{...f,"x-chatpanel-token":Me()||_e(),"x-chatpanel-link-device":String(Z||"")}}),ownerIsPro:()=>ke(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 ${Pa}`));let $=null;const B=()=>{if(!$){const n=t.read||{};$=qn({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)=>zn().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,H]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,H)}}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 F=null;const P=()=>(F||(F=Hn({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:Ue.join(Ue.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)})),F),V=Number(t.runtime?.idleMinutes),z=Fn({warmMs:(Number.isFinite(V)&&V>=0?V:10)*6e4,log:n=>console.log(n)}),X=Vn({cfg:t,wake:(n,o)=>P().wake(n,o),embedded:z,asleep:n=>P().isAsleep(n)});let te=null;const oe=()=>(te||(te=Zn({store:Xn({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 H=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",...H?{Authorization:`Bearer ${H}`}:{},"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?ka({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;Y=wa({reader:B(),searxng:o,engines:()=>Sa(t),wakeSearxng:()=>P().wake("searxng"),defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await qe([ht(()=>i,Z=>{i=Z})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return Y};yr(t.allowedExtensionIds||[]);const C=[],ee=n=>{C.push(n),C.length>50&&C.shift()},pe=tr(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(!ys(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(ct(t.host)&&ra(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&&fs(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return G(n)?a(o,200,{token:_e()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!G(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=fr();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=gr(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Je(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Je(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=Je(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=Je(n);return a(o,200,{ok:!0,trust:e,paired:Yt(e),version:ue})}if(i==="/audit"&&n.method==="GET")return G(n)?a(o,200,Tr(t,{version:ue,startedAt:zo,managed:Le(),certificates:{..._r(),wanted:Xt(t)},linkPartners:y?y.status().devices.filter(e=>e.kind==="partner"):[],confined:wt({stateDir:Ue.dirname(ce())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!G(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await hn(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:gn()})}if(i==="/update"&&n.method==="POST"){const e=fn(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"&&!G(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!G(n))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!G(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!G(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!G(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!G(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!G(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${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).
@@ -38,7 +38,7 @@ In a terminal, \`chatpanel-gateway --status\` shows what is running.
38
38
 
39
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,w=>{w.seq==null?l(w):w.seq>m&&(m=w.seq,l(w))});for(const w of re.eventsSince(r,m))m=w.seq,l(w);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=L.clear();return a(o,200,{ok:!0,dropped:e,size:L.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=L.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:L.size,newest:L.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=ls(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 ds(s,g=>L.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:L.size,newest:L.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&&!G(n))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${n.socket.localPort}`,c=s?async(w,{maxTokens: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:w}],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 rn(r,{store:L,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,nn(r,g,{size:L.size,newest:L.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:G(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:L.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:L.size,newest:L.newest,bytes:L.bytes,lossless:L.lossless?{records:L.lossless.size,newest:L.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:L.size,bytes:L.bytes,newest:L.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(Do({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=L.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,Ts))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),c=[];let m=0,h={},g=[],w=[];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,w=x.merged;for(const I of x.written)O(e.get(I))}if(Array.isArray(r.entries)){const x=ft(),I=x?Cn((ne,Te)=>Mn(x,{salt:ne,iterations:Te})):null,q=async ne=>{if(!I||!ne.blob)return null;const Te=await I(ne.blob),H=ne.blob.compression&&ne.blob.compression!=="none"?In(Rn,ne.blob.compression):null;return Dn(ne.blob,Te,{codec:H})},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)&&L.bulk(v),c.length&&Ve({ids:c}),a(o,200,{ok:!0,written:c.length,ids:c,revs:h,conflicts:g,merged:w,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=L.clear();return a(o,200,{ok:!0,dropped:e,size:L.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=L.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:L.size,newest:L.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=ls(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 ds(s,g=>L.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:L.size,newest:L.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&&!G(n))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${n.socket.localPort}`,c=s?async(w,{maxTokens: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:w}],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 rn(r,{store:L,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,nn(r,g,{size:L.size,newest:L.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:G(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:L.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:L.size,newest:L.newest,bytes:L.bytes,lossless:L.lossless?{records:L.lossless.size,newest:L.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:L.size,bytes:L.bytes,newest:L.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(Do({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=L.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,Ts))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),c=[];let m=0,h={},g=[],w=[];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,w=x.merged;for(const I of x.written)O(e.get(I))}if(Array.isArray(r.entries)){const x=ft(),I=x?Cn((ne,Te)=>Mn(x,{salt:ne,iterations:Te})):null,q=async ne=>{if(!I||!ne.blob)return null;const Te=await I(ne.blob),U=ne.blob.compression&&ne.blob.compression!=="none"?In(Rn,ne.blob.compression):null;return Dn(ne.blob,Te,{codec:U})},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)&&L.bulk(v),c.length&&Ve({ids:c}),a(o,200,{ok:!0,written:c.length,ids:c,revs:h,conflicts:g,merged:w,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:An(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=En(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=Pn(Q.all());return a(o,200,{ok:!0,stats:e,year:$n(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
@@ -55,13 +55,13 @@ data: ${JSON.stringify({pending:c})}
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)?b.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=L.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
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=L.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,...L.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=L.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?Vr(String(e.passphrase)):Fr();const r=e.passphrase?await kt(L,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ve(),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(L,ft());return e.ok&&e.whole&&Ve(),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 Vo(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await nt(t),J.state()!=="off"){if(!J.isReady()){const r=J.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 J.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=Uo(t);if(!e){const r=J.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:J.state(),model:t.ner?.model||null})}try{const r=await S(n,t.maxBodyBytes),s=await tt(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 ke(t.pro?.entitlementToken);await nt(t);const l=await qe([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:Go(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=J.health().model||t.ner?.model||null,r=Math.round(St.totalmem()/1048576),s=Ba(bo,{totalRamMB:r}).map(l=>({...l,installed:J.modelOnDisk(l.id)}));for(const l of[e,...J.modelsOnDisk()])!l||s.some(c=>c.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:J.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:J.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Hr(),recommendation:so(s,{totalRamMB:r},[]),state:J.state(),progress:J.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:J.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||J.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(c=>c!==l),r&&Bo(t,r);try{be(t,ce())}catch{}return(async()=>{r&&await J.setModel(r,{onLog:m=>console.log(m)});const c=Gr(t.ner,{log:m=>console.log(m)});for(const m of J.companions())c.includes(m.model)||await J.removeCompanion(m.model);for(const m of c)await J.addCompanion(m,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});J.setUnionOrder(c)})().catch(c=>console.log(`[ner] union update failed: ${c.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:J.companions(),state:J.state()})}if(!r||!(vo(r)||ko(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Bo(t,r);try{be(t,ce())}catch{}return J.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:J.state(),progress:J.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=Ma.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:Ia,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||!(Da(r)||Ca(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"&&Ra(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:Ko(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=Ea.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:Oa.health(),translate:$e.health(),indictrans:xa.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():Ua).map(c=>({id:c,label:c[0].toUpperCase()+c.slice(1),lang:"en",installed:D.builtinVoices().includes(c)})):D.arch()&&D.arch()!=="style-tts2"?[]:Ja.map(c=>({...c,installed:D.voiceOnDisk(c.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:D.health().dtype,runtime:D.health().runtime,dtypes:za})}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&&!(La(r)||ja(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"&&Ga(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=Ha(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 w=de.listVoices();t.tts.voice=w.length?`custom:${w[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=$a(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),$s))]);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(As(m,16e3,24e3)))}catch(O){console.log(`[tts] pocket conditioning unavailable for this voice (${O.message})`)}const w=l?de.replaceVoice(l,{vec:h,pocket:g}):de.saveVoice({name:r,vec:h,pocket:g}),v=l&&r&&r!==w.name?de.renameVoice(l,r):w;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${v.name}" (${(w.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...w,...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=Va(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&&!Wa(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:Te,redacted:H}=await Fa({dest:l,text:r,voice:m,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ke(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":Te,"Content-Length":String(ne.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(H)}),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 w=Ka({requested:c,configured:m,engine:D,voices:de,isPocketVoice:it,isKnownVoice:_o,isValidVoiceId:Oo,defaultVoice:Oe,defaultPocketVoice:st});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:v,customId:O,speakerEmbedding:x}=w,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=Aa(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 Na(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:tt})}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 w=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,H=>{H.type==="final"&&H.text?O.push(H):H.type==="language"?I=H.lang:H.type==="error"&&x.push(H.message||H.code)});const q=16e3*5;for(let H=0;H<l.pcm.length;H+=q)A.pushAudio(v,l.pcm.subarray(H,Math.min(l.pcm.length,H+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((H,qo)=>{const Ft=typeof H.startMs=="number"?H.startMs/1e3:we,er=(H.durationMs||0)/1e3;return we=Ft+er,{id:qo,start:Math.round(Ft*100)/100,end:Math.round(we*100)/100,text:H.text,...H.speaker?{speaker:H.speaker}:{},...H.turns?{turns:H.turns.map(Ze=>({start:Math.round(Ze.startMs/10)/100,end:Math.round((Ze.startMs+Ze.durationMs)/10)/100,speaker:Ze.speaker}))}:{}}}),Te=ne.map(H=>H.text).join(" ").replace(/\s+/g," ").trim();return c==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Te)):c==="verbose_json"?a(o,200,{task:"transcribe",language:I||r("language")||null,duration:Math.round(l.seconds*100)/100,text:Te,segments:ne,provider:m.kind,took_ms:Date.now()-w}):a(o,200,{text:Te})}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:tt})}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:Ko(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,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)});const g=Array.isArray(e?.langs)?e.langs.slice(0,12):null,w=t.stt?.model||De,v=g&&!s?_a(g,{engine:at(w)?.engine||"",englishOnly:/\.en$/.test(w)}).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 qe([ht(()=>g,w=>{g=w})],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 w=c.remote?"ready":A.state();w==="downloading"||w==="loading"?h.push({type:"progress",state:w,...A.progress()||{}}):w==="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()||{}}):Wo.get(c)!==w&&(Wo.set(c,w),h.push({type:"state",state:w}))}const g=c?.redact?await ke(t.pro?.entitlementToken):!0;for(const w of m)c?h.push(await s(c,w,g)):w.type!=="final"&&w.type!=="interim"&&w.type!=="translation"&&h.push(w);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)}
58
+ `),xe.add(o),n.on("close",()=>xe.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=L.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,...L.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=L.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?Vr(String(e.passphrase)):Fr();const r=e.passphrase?await kt(L,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ve(),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(L,ft());return e.ok&&e.whole&&Ve(),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 Vo(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await nt(t),J.state()!=="off"){if(!J.isReady()){const r=J.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 J.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=Uo(t);if(!e){const r=J.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:J.state(),model:t.ner?.model||null})}try{const r=await S(n,t.maxBodyBytes),s=await tt(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 ke(t.pro?.entitlementToken);await nt(t);const l=await qe([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:Go(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=J.health().model||t.ner?.model||null,r=Math.round(St.totalmem()/1048576),s=Ba(bo,{totalRamMB:r}).map(l=>({...l,installed:J.modelOnDisk(l.id)}));for(const l of[e,...J.modelsOnDisk()])!l||s.some(c=>c.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:J.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:J.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Hr(),recommendation:so(s,{totalRamMB:r},[]),state:J.state(),progress:J.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:J.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||J.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(c=>c!==l),r&&Bo(t,r);try{be(t,ce())}catch{}return(async()=>{r&&await J.setModel(r,{onLog:m=>console.log(m)});const c=Gr(t.ner,{log:m=>console.log(m)});for(const m of J.companions())c.includes(m.model)||await J.removeCompanion(m.model);for(const m of c)await J.addCompanion(m,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});J.setUnionOrder(c)})().catch(c=>console.log(`[ner] union update failed: ${c.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:J.companions(),state:J.state()})}if(!r||!(vo(r)||ko(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Bo(t,r);try{be(t,ce())}catch{}return J.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:J.state(),progress:J.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=Ma.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:Ia,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||!(Da(r)||Ca(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"&&Ra(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:Ko(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=Ea.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:Oa.health(),translate:$e.health(),indictrans:xa.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():Ua).map(c=>({id:c,label:c[0].toUpperCase()+c.slice(1),lang:"en",installed:D.builtinVoices().includes(c)})):D.arch()&&D.arch()!=="style-tts2"?[]:Ja.map(c=>({...c,installed:D.voiceOnDisk(c.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:D.health().dtype,runtime:D.health().runtime,dtypes:za})}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&&!(La(r)||ja(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"&&Ga(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=Ha(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 w=de.listVoices();t.tts.voice=w.length?`custom:${w[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=$a(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),$s))]);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(As(m,16e3,24e3)))}catch(O){console.log(`[tts] pocket conditioning unavailable for this voice (${O.message})`)}const w=l?de.replaceVoice(l,{vec:h,pocket:g}):de.saveVoice({name:r,vec:h,pocket:g}),v=l&&r&&r!==w.name?de.renameVoice(l,r):w;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${v.name}" (${(w.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...w,...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=Va(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&&!Wa(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:Te,redacted:U}=await Fa({dest:l,text:r,voice:m,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ke(t.pro?.entitlementToken),format:h});return o.writeHead(200,{"Content-Type":Te,"Content-Length":String(ne.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(U)}),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 w=Ka({requested:c,configured:m,engine:D,voices:de,isPocketVoice:it,isKnownVoice:_o,isValidVoiceId:Oo,defaultVoice:Oe,defaultPocketVoice:st});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:v,customId:O,speakerEmbedding:x}=w,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=Aa(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 Na(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:tt})}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 w=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,U=>{U.type==="final"&&U.text?O.push(U):U.type==="language"?I=U.lang:U.type==="error"&&x.push(U.message||U.code)});const q=16e3*5;for(let U=0;U<l.pcm.length;U+=q)A.pushAudio(v,l.pcm.subarray(U,Math.min(l.pcm.length,U+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((U,qo)=>{const Ft=typeof U.startMs=="number"?U.startMs/1e3:we,er=(U.durationMs||0)/1e3;return we=Ft+er,{id:qo,start:Math.round(Ft*100)/100,end:Math.round(we*100)/100,text:U.text,...U.speaker?{speaker:U.speaker}:{},...U.turns?{turns:U.turns.map(Ze=>({start:Math.round(Ze.startMs/10)/100,end:Math.round((Ze.startMs+Ze.durationMs)/10)/100,speaker:Ze.speaker}))}:{}}}),Te=ne.map(U=>U.text).join(" ").replace(/\s+/g," ").trim();return c==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Te)):c==="verbose_json"?a(o,200,{task:"transcribe",language:I||r("language")||null,duration:Math.round(l.seconds*100)/100,text:Te,segments:ne,provider:m.kind,took_ms:Date.now()-w}):a(o,200,{text:Te})}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:tt})}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:Ko(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,warmMs:t.stt?.warmMs,onLog:O=>console.log(O)});const g=Array.isArray(e?.langs)?e.langs.slice(0,12):null,w=t.stt?.model||De,v=g&&!s?_a(g,{engine:at(w)?.engine||"",englishOnly:/\.en$/.test(w)}).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 qe([ht(()=>g,w=>{g=w})],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 w=c.remote?"ready":A.state();w==="downloading"||w==="loading"?h.push({type:"progress",state:w,...A.progress()||{}}):w==="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()||{}}):Wo.get(c)!==w&&(Wo.set(c,w),h.push({type:"state",state:w}))}const g=c?.redact?await ke(t.pro?.entitlementToken):!0;for(const w of m)c?h.push(await s(c,w,g)):w.type!=="final"&&w.type!=="interim"&&w.type!=="translation"&&h.push(w);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
60
  `),h=c.redact?await ke(t.pro?.entitlementToken):!0,g=x=>s(c,x,h);m({type:"state",state:c.remote?"ready":A.state()});const w=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(w);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(w)},500);w.unref?.();let v=Promise.resolve();const O=A.subscribe(r,x=>{v=v.then(async()=>{m(await g(x)),x.type==="end"&&(clearInterval(w),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(w),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 ke(t.pro?.entitlementToken);return a(o,200,Ao(t,{proUnlocked:e,policy:et()}))}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);if(e.capabilities&&typeof e.capabilities=="object"){const h=JSON.parse(JSON.stringify({capabilities:t.capabilities||{},redaction:t.redaction||{}}));try{No(h,{capabilities:e.capabilities})}catch(w){if(w?.code==="SHAPE")return a(o,400,{error:w.message});throw w}const g=Object.keys(e.capabilities).map(w=>os(w,t.capabilities?.[w],h.capabilities?.[w])).find(Boolean);if(g&&!await ke(t.pro?.entitlementToken))return a(o,403,{error:g,needs:"pro"})}try{No(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&&Fe?.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=J.state();t.ner?.autostart&&l&&c!=="ready"&&c!=="loading"&&c!=="downloading"&&J.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 ke(t.pro?.entitlementToken);return a(o,200,Ao(t,{proUnlocked:m,policy:et()}))}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(!G(n))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"asking another chat is not available from a linked phone yet",type:"forbidden"}});const e=L.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=qr(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=en({fromTitle:c?.title,message:l}),w={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(w))},body:JSON.stringify({model:h.model,messages:[...tn(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=on(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&&L.bulk({upserts:[x],removes:[]})}catch{}return Ve({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 G(n)?n.headers["x-chatpanel-link-device"]&&t.link?.agentSessions===!1?a(o,403,{error:{message:"this computer does not share its coding agents' sessions with a linked phone — Settings › 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 G(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"}}):G(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"}}):G(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(!G(n))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:Cr()});if(n.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&Ar(e.url||"");const r=await ot(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 ot(e.url,{auth:String(e.auth||"")})).card,s=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||""),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 ot(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 Br({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:c=>s(c.kind,{kind:c.kind,task:c.task,message:c.message})});s("done",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 ot(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await Dr({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await Mr({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 G(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(!G(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await 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 rs(t,{serviceHealth:async()=>e,fresh:r,engineAt:d.engineAt}))}if(Ns.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=vs(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,We=0,Ae=0,Lt=0,Se=!1,Pe=!1,jt="",Ne=!0;const ae=t.logRequests&&F.redactable&&n.method==="POST"?bs(ee):null,Qo=Date.now();if(F.redactable&&n.method==="POST"&&K.length){try{k=JSON.parse(K.toString("utf8"))}catch{k=null}if(k&&ks(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):us,w=e.narrowAll?null:O=>!ms.test(Jo(O)),v=k.tools.length;k.tools=dr(k.tools,hs(k,F.kind),{cap:g,keep:w,name:Jo,description:ps}),Lt=v-k.tools.length}if(Ne=await ke(t.pro?.entitlementToken),Se=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&G(n),!Se){const g=dt(k?.model,t,F.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:()=>!1}),w=g?.type==="api"?await d.decide(g,k?.model).catch(()=>null):null;Pe=w?.redact===!1,jt=Pe?w.engine||"declared":""}if(!Se&&!Pe){const g=Qa(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"}})}!Se&&!Pe&&await nt(t);const r=Se?[]:F.adapter.collectSegments(k,t.redaction,{skipPublic:G(n)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=ae?ae.clock():0,{vault:c,count:m,sanitized:h}=Se?{vault:null,count:0,sanitized:0}:await qe(r,t.redaction,{signal:s.signal,isPro:Ne,sanitizeOnly:Pe,onEgress:g=>Nt.push(Do({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,We=m,Ae=h||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!Ne&&m>0){Ya(t,Ne);try{be(t,ce())}catch{}}if(!Se&&!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"}),w=!(g&&g.type==="api");F.adapter.injectSystemNote(k,ur({toolData:t.tools?.toolData,ownTools:w}))}else!Se&&m>0&&typeof F.adapter.injectSystemNote=="function"&&F.adapter.injectSystemNote(k,mr());ie=Buffer.from(JSON.stringify(k),"utf8")}}const zt=cr({vault:W,toolData:t.tools?.toolData}),Ke=k&&typeof k.chatpanel=="object"&&k.chatpanel||null;if(Ke&&(delete k.chatpanel,ie=Buffer.from(JSON.stringify(k),"utf8")),typeof k?.model=="string"&&k.model.startsWith("fusion:")){const e=Bn(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"]||Ke?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Ke?.reach||"").trim(),run:Jt(n.headers["x-chatpanel-run"],Ke?.run)},Qe=await j(),Gt=e=>!!e.service&&Qe(e.id)==="down";let N=dt(k?.model,t,F.kind,{destination:se.destination,down:Gt});N?.type==="agent"&&k?.model&&!se.destination&&!ss(N,k.model)&&(await as(t,{serviceHealth:async()=>Qe,engineAt:d.engineAt}),N=dt(k?.model,t,F.kind,{destination:se.destination,down:Gt}));const Ht=N?.service&&Qe(N.id)==="down"?await P().revive(N.service).catch(()=>null):null;if(Ht?.ok&&(_.at=0),N?.service&&Qe(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:ns(t).map(e=>e.id)}});const le=He(n.headers);if(le&&!aa(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 Ye=le&&F.redactable&&n.method==="POST"&&k?{caller:le,surface:xn(le,le.kind==="partner"?"":y?.deviceNameOf(le.device)),model:k.model||null,startedAt:Qo}:null;ae&&(ae.meta={t:Date.now(),model:k?.model||null,dest:N?N.id:null,type:N?N.type:null,redacted:We,sanitized:Ae,narrowed:Lt,detail:Go(W,t.logDetail),redaction:Se?"off":Pe?`on-device (${jt})`:t.redaction.tier||"basic",...le?.kind==="partner"?{via:sa(le)}:{}});const Xe=et();if(Xe&&N){const e=N.type==="api"?qt(Xe,{model:k?.model||"",endpoint:N.baseUrl||""}):Pr(Xe,N.agent||N.id)?qt(Xe,{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?Ss(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"}})):Bs(n,o,{...F,pathname:i,search:f.search,base:N.baseUrl,destKey:N.apiKey,destProtocol:N.protocol,harness:zt,trace:ae,link:Ye&&{...Ye,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=Je(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)),Yo=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=>!Yo.has(e)))){const e=Jt(null,co(lo(me.get("agentTools").agentTools?.value,N?.agent||k?.model)));e&&(se.run={...e,...se.run||{}})}if(pt){const e=Jt(null,co(lo(me.get("agentTools").agentTools?.value,N?.agent||k?.model)));se.run={...e||{},...ia(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=hr({...se.run||{},...se.reach?{reach:se.reach}:{},...Vt?{askDepth:Vt}:{}},Ut);Be.reach&&o.setHeader("x-chatpanel-reach-used",Be.reach);const Xo=pt?{inbox:b,partner:le.partner,device:le.device,conversation:Be.thread?.id||null}:null,Zo=Ye&&{...Ye,dest:{type:"agent",id:N?.id||"bridge"},threadId:Be.thread?.id||null};return Es(n,o,{...F,pathname:i,agentOverride:N?.agent,harness:zt,trace:ae,run:Object.keys(Be).length?Be:null,owner:Xo,link:Zo},k,W,t,Ne)});return pe.on("close",()=>{E?.stop("closed"),Gn(),p.close(),y?.stop(),b.stop()}),pe.on("upgrade",(n,o,f)=>{o.on("error",()=>{});const i=String(n.url||"").split("?")[0];if(y&&i.startsWith(na)){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 Br({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:c=>s(c.kind,{kind:c.kind,task:c.task,message:c.message})});s("done",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 ot(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await Dr({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await Mr({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 G(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(!G(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await 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 rs(t,{serviceHealth:async()=>e,fresh:r,engineAt:d.engineAt}))}if(Ns.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 H=vs(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,We=0,Ae=0,Lt=0,Se=!1,Pe=!1,jt="",Ne=!0;const ae=t.logRequests&&H.redactable&&n.method==="POST"?bs(ee):null,Qo=Date.now();if(H.redactable&&n.method==="POST"&&K.length){try{k=JSON.parse(K.toString("utf8"))}catch{k=null}if(k&&ks(k,H.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):us,w=e.narrowAll?null:O=>!ms.test(Jo(O)),v=k.tools.length;k.tools=dr(k.tools,hs(k,H.kind),{cap:g,keep:w,name:Jo,description:ps}),Lt=v-k.tools.length}if(Ne=await ke(t.pro?.entitlementToken),Se=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&G(n),!Se){const g=dt(k?.model,t,H.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:()=>!1}),w=g?.type==="api"?await d.decide(g,k?.model).catch(()=>null):null;Pe=w?.redact===!1,jt=Pe?w.engine||"declared":""}if(!Se&&!Pe){const g=Qa(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"}})}!Se&&!Pe&&await nt(t);const r=Se?[]:H.adapter.collectSegments(k,t.redaction,{skipPublic:G(n)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=ae?ae.clock():0,{vault:c,count:m,sanitized:h}=Se?{vault:null,count:0,sanitized:0}:await qe(r,t.redaction,{signal:s.signal,isPro:Ne,sanitizeOnly:Pe,onEgress:g=>Nt.push(Do({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),H.adapter.joinTextParts?.(k),W=c,We=m,Ae=h||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!Ne&&m>0){Ya(t,Ne);try{be(t,ce())}catch{}}if(!Se&&!Pe&&Array.isArray(k.tools)&&k.tools.length&&typeof H.adapter.injectSystemNote=="function"){const g=dt(k?.model,t,H.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:v=>!!v.service&&_.fn(v.id)==="down"}),w=!(g&&g.type==="api");H.adapter.injectSystemNote(k,ur({toolData:t.tools?.toolData,ownTools:w}))}else!Se&&m>0&&typeof H.adapter.injectSystemNote=="function"&&H.adapter.injectSystemNote(k,mr());ie=Buffer.from(JSON.stringify(k),"utf8")}}const zt=cr({vault:W,toolData:t.tools?.toolData}),Ke=k&&typeof k.chatpanel=="object"&&k.chatpanel||null;if(Ke&&(delete k.chatpanel,ie=Buffer.from(JSON.stringify(k),"utf8")),typeof k?.model=="string"&&k.model.startsWith("fusion:")){const e=Bn(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"]||Ke?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Ke?.reach||"").trim(),run:Jt(n.headers["x-chatpanel-run"],Ke?.run)},Qe=await j(),Gt=e=>!!e.service&&Qe(e.id)==="down";let N=dt(k?.model,t,H.kind,{destination:se.destination,down:Gt});N?.type==="agent"&&k?.model&&!se.destination&&!ss(N,k.model)&&(await as(t,{serviceHealth:async()=>Qe,engineAt:d.engineAt}),N=dt(k?.model,t,H.kind,{destination:se.destination,down:Gt}));const Ht=N?.service&&Qe(N.id)==="down"?await P().revive(N.service).catch(()=>null):null;if(Ht?.ok&&(_.at=0),N?.service&&Qe(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:ns(t).map(e=>e.id)}});const le=He(n.headers);if(le&&!aa(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 Ye=le&&H.redactable&&n.method==="POST"&&k?{caller:le,surface:xn(le,le.kind==="partner"?"":y?.deviceNameOf(le.device)),model:k.model||null,startedAt:Qo}:null;ae&&(ae.meta={t:Date.now(),model:k?.model||null,dest:N?N.id:null,type:N?N.type:null,redacted:We,sanitized:Ae,narrowed:Lt,detail:Go(W,t.logDetail),redaction:Se?"off":Pe?`on-device (${jt})`:t.redaction.tier||"basic",...le?.kind==="partner"?{via:sa(le)}:{}});const Xe=et();if(Xe&&N){const e=N.type==="api"?qt(Xe,{model:k?.model||"",endpoint:N.baseUrl||""}):Pr(Xe,N.agent||N.id)?qt(Xe,{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?Ss(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"}})):Bs(n,o,{...H,pathname:i,search:f.search,base:N.baseUrl,destKey:N.apiKey,destProtocol:N.protocol,harness:zt,trace:ae,link:Ye&&{...Ye,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=Je(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)),Yo=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=>!Yo.has(e)))){const e=Jt(null,co(lo(me.get("agentTools").agentTools?.value,N?.agent||k?.model)));e&&(se.run={...e,...se.run||{}})}if(pt){const e=Jt(null,co(lo(me.get("agentTools").agentTools?.value,N?.agent||k?.model)));se.run={...e||{},...ia(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=hr({...se.run||{},...se.reach?{reach:se.reach}:{},...Vt?{askDepth:Vt}:{}},Ut);Be.reach&&o.setHeader("x-chatpanel-reach-used",Be.reach);const Xo=pt?{inbox:b,partner:le.partner,device:le.device,conversation:Be.thread?.id||null}:null,Zo=Ye&&{...Ye,dest:{type:"agent",id:N?.id||"bridge"},threadId:Be.thread?.id||null};return Es(n,o,{...H,pathname:i,agentOverride:N?.agent,harness:zt,trace:ae,run:Object.keys(Be).length?Be:null,owner:Xo,link:Zo},k,W,t,Ne)});return pe.on("close",()=>{E?.stop("closed"),Gn(),p.close(),y?.stop(),b.stop()}),pe.on("upgrade",(n,o,f)=>{o.on("error",()=>{});const i=String(n.url||"").split("?")[0];if(y&&i.startsWith(na)){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{}}),pe.once("listening",()=>{P()}),pe.linkHost=y,pe.runtimeDefaults=()=>P().ensureDefaults(),pe}function Jt(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)),qa.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 b=Qr(u.thread);return b&&(p.thread=b),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 Fe=null,ut=null;async function El(t=Wt()){Ur();let d=null;try{d=await Or()}catch(T){throw T instanceof Er&&(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=xr({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}`}`),Sr(globalThis,{allow:u?.egress?(T,{local:_})=>$r(u,T,{local:_}):null}),_e();const b=Ms(t),y=zr(t),$=or(t);let B=!1;b.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=Yr({name:"gateway",self:ue,holder:j?{ours:j,version:R.version}:null,managedBy:Xr(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(()=>b.listen(t.port,t.host),Zr);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=pn(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)}),b.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}`),b.linkHost?.start().catch(T=>console.log(` link : not started (${T?.message||T})`)),b.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 ts(t))console.log(` ⚠ sandbox : ${T}`);console.log(` confined : ${bn(wt({stateDir:Ue.dirname(ce())}))}`),ut={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},mn(t,{childEnv:()=>({...es(t,process.env,et()),...Za(t)})}).then(T=>{Fe=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(L,ft()).then(T=>{T?.ok&&(console.log(` warm : seeded ${T.ingested} records from ${T.file}`),T.whole&&Ve())}).catch(()=>{});const E=()=>{y?.stop(),$.stop(),Fe?.stop(),cs(b)};return process.on("SIGINT",E),process.on("SIGTERM",E),b}export{Ts as RECORDS_MAX_BYTES,Al as VERSION,Ms as createGateway,Ps as joinUpstream,Bt as parseAgentModel,El as start};
67
+ `)}catch{}}),pe.once("listening",()=>{P()}),pe.linkHost=y,pe.runtimeDefaults=()=>P().ensureDefaults(),pe}function Jt(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)),qa.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 b=Qr(u.thread);return b&&(p.thread=b),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 Fe=null,ut=null;async function El(t=Wt()){Ur();let d=null;try{d=await Or()}catch(T){throw T instanceof Er&&(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=xr({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}`}`),Sr(globalThis,{allow:u?.egress?(T,{local:_})=>$r(u,T,{local:_}):null}),_e();const b=Ms(t),y=zr(t),$=or(t);let B=!1;b.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"),F=Yr({name:"gateway",self:ue,holder:j?{ours:j,version:R.version}:null,managedBy:Xr(process.env),port:t.port});if(F.action==="standby"||B&&!R){if(!B)for(const P of F.lines)console.error(P);B=!0,setTimeout(()=>b.listen(t.port,t.host),Zr);return}if(j){const P=R.managedBy?` (run by ${R.managedBy})`:"";for(const[V,z]of F.lines.entries())console.error(V===0?z.replace(` on ${t.port}`,` at http://${_}:${t.port}${P}`):z)}else{const P=pn(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)}),b.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}`),b.linkHost?.start().catch(T=>console.log(` link : not started (${T?.message||T})`)),b.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 ts(t))console.log(` ⚠ sandbox : ${T}`);console.log(` confined : ${bn(wt({stateDir:Ue.dirname(ce())}))}`),ut={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},mn(t,{childEnv:()=>({...es(t,process.env,et()),...Za(t)})}).then(T=>{Fe=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(L,ft()).then(T=>{T?.ok&&(console.log(` warm : seeded ${T.ingested} records from ${T.file}`),T.whole&&Ve())}).catch(()=>{});const E=()=>{y?.stop(),$.stop(),Fe?.stop(),cs(b)};return process.on("SIGINT",E),process.on("SIGTERM",E),b}export{Ts as RECORDS_MAX_BYTES,Al as VERSION,Ms as createGateway,Ps as joinUpstream,Bt as parseAgentModel,El as start};
package/src/tts-remote.js CHANGED
@@ -1 +1 @@
1
- import{secureFetch as g}from"./secure-fetch.js";import{redactSegments as T,segment as w}from"./redact.js";import{primaryProvider as $}from"./capability-config.js";const _=["local","openai","elevenlabs"];function b(e){return _.includes(String(e||""))}function z(e={}){const o=e.tts||{},t=$(e.capabilities?.tts,"tts",{destinations:e.destinations||[]});if(t&&typeof t=="object"){if(t.provider==="embedded")return null;const i=t.adapter||"openai";if(t.url&&b(i)){const c=o.remote||{};return{kind:i,baseUrl:String(t.url).replace(/\/+$/,""),model:t.model||c.model||(i==="elevenlabs"?"eleven_multilingual_v2":"tts-1"),voice:t.voice||c.voice||(i==="elevenlabs"?"21m00Tcm4TlvDq8ikWAM":"alloy"),redact:t.redact!==!1,token:t.token||"",...t.endpoint?{endpoint:t.endpoint}:{}}}}const r=o.provider||"local";if(r==="local"||!b(r))return null;const a=o.remote||{};return{kind:r,baseUrl:String(a.baseUrl||(r==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1")).replace(/\/+$/,""),model:a.model||(r==="elevenlabs"?"eleven_multilingual_v2":"tts-1"),voice:a.voice||(r==="elevenlabs"?"21m00Tcm4TlvDq8ikWAM":"alloy"),redact:a.redact!==!1}}function A(e){return/^[A-Za-z0-9_-]{1,64}$/.test(String(e||""))}const E=new Set(["alloy","ash","ballad","coral","echo","fable","nova","onyx","sage","shimmer","verse"]);function P(e,o){const t=String(o||"");return t?e.endpoint?e.kind==="elevenlabs"?/^[A-Za-z0-9]{20}$/.test(t)?t:e.voice:E.has(t)?t:e.voice:t:e.voice}async function C({dest:e,text:o,voice:t,speed:r=1,auth:a,redaction:i,isPro:c=!0,onEgress:h=null,fetchImpl:y=null}={}){if(!e)throw new Error("no remote TTS destination configured");const l=e.endpoint&&e.token?e.token:a||e.token||"",u=P(e,t);if(!A(u))throw new Error(`invalid remote voice id: ${u}`);let m=String(o),f=0;if(e.redact&&i){const n={text:m},k=await T([w(()=>n.text,S=>{n.text=S})],i,{isPro:c,onEgress:h});m=n.text,f=k?.count||0}const x=y||g,p={"Content-Type":"application/json"};let d,v;if(e.kind==="elevenlabs"){d=`${e.baseUrl}/text-to-speech/${encodeURIComponent(u)}`,v={text:m,model_id:e.model};const n=U(l);n&&(p["xi-api-key"]=n)}else d=`${e.baseUrl}/audio/speech`,v={model:e.model,input:m,voice:u,response_format:"wav",speed:r},l&&(p.Authorization=l.startsWith("Bearer ")?l:`Bearer ${l}`);const s=await x(d,{method:"POST",headers:p,body:JSON.stringify(v)});if(!s.ok){let n=`HTTP ${s.status}`;try{n=(await s.text()).slice(0,300)||n}catch{}throw new Error(`remote tts failed: ${n}`)}return{audio:Buffer.from(await s.arrayBuffer()),contentType:s.headers.get("content-type")||"audio/mpeg",redacted:f}}function U(e){const o=String(e||"").trim();return o.toLowerCase().startsWith("bearer ")?o.slice(7).trim():o}export{_ as TTS_PROVIDERS,A as isValidRemoteVoice,b as isValidTtsProvider,P as remoteVoiceFor,C as synthesizeRemote,z as ttsDestination};
1
+ import{secureFetch as g}from"./secure-fetch.js";import{redactSegments as U,segment as I}from"./redact.js";import{primaryProvider as _}from"./capability-config.js";const L=["local","openai","elevenlabs"];function h(e){return L.includes(String(e||""))}function O(e={}){const r=e.tts||{},t=_(e.capabilities?.tts,"tts",{destinations:e.destinations||[]});if(t&&typeof t=="object"){if(t.provider==="embedded")return null;const i=t.adapter||"openai";if(t.url&&h(i)){const s=r.remote||{};return{kind:i,baseUrl:String(t.url).replace(/\/+$/,""),model:t.model||s.model||(i==="elevenlabs"?"eleven_multilingual_v2":"tts-1"),voice:t.voice||s.voice||(i==="elevenlabs"?"21m00Tcm4TlvDq8ikWAM":"alloy"),redact:t.redact!==!1,token:t.token||"",...t.endpoint?{endpoint:t.endpoint}:{}}}}const n=r.provider||"local";if(n==="local"||!h(n))return null;const a=r.remote||{};return{kind:n,baseUrl:String(a.baseUrl||(n==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1")).replace(/\/+$/,""),model:a.model||(n==="elevenlabs"?"eleven_multilingual_v2":"tts-1"),voice:a.voice||(n==="elevenlabs"?"21m00Tcm4TlvDq8ikWAM":"alloy"),redact:a.redact!==!1}}function $(e){return/^[A-Za-z0-9_-]{1,64}$/.test(String(e||""))}const A=new Set(["alloy","ash","ballad","coral","echo","fable","nova","onyx","sage","shimmer","verse"]);function B(e,r){const t=String(r||"");return t?e.endpoint?e.kind==="elevenlabs"?/^[A-Za-z0-9]{20}$/.test(t)?t:e.voice:A.has(t)?t:e.voice:t:e.voice}async function z({dest:e,text:r,voice:t,speed:n=1,auth:a,redaction:i,isPro:s=!0,onEgress:E=null,fetchImpl:T=null,format:u=null}={}){if(!e)throw new Error("no remote TTS destination configured");const l=e.endpoint&&e.token?e.token:a||e.token||"",p=B(e,t);if(!$(p))throw new Error(`invalid remote voice id: ${p}`);let d=String(r),m=0;if(e.redact&&i){const o={text:d},x=await U([I(()=>o.text,S=>{o.text=S})],i,{isPro:s,onEgress:E});d=o.text,m=x?.count||0}const k=T||g,v={"Content-Type":"application/json"};let f,w;if(e.kind==="elevenlabs"){f=`${e.baseUrl}/text-to-speech/${encodeURIComponent(p)}`,(u==="wav"||u==="pcm")&&(f+=`?output_format=pcm_${y}`),w={text:d,model_id:e.model};const o=P(l);o&&(v["xi-api-key"]=o)}else f=`${e.baseUrl}/audio/speech`,w={model:e.model,input:d,voice:p,response_format:"wav",speed:n},l&&(v.Authorization=l.startsWith("Bearer ")?l:`Bearer ${l}`);const c=await k(f,{method:"POST",headers:v,body:JSON.stringify(w)});if(!c.ok){let o=`HTTP ${c.status}`;try{o=(await c.text()).slice(0,300)||o}catch{}throw new Error(`remote tts failed: ${o}`)}const b=Buffer.from(await c.arrayBuffer());return e.kind==="elevenlabs"&&u==="pcm"?{audio:b,contentType:"audio/pcm",redacted:m}:e.kind==="elevenlabs"&&u==="wav"?{audio:V(b,y),contentType:"audio/wav",redacted:m}:{audio:b,contentType:c.headers.get("content-type")||"audio/mpeg",redacted:m}}const y=24e3;function V(e,r){const t=e.length&-2,n=Buffer.alloc(44);return n.write("RIFF",0),n.writeUInt32LE(36+t,4),n.write("WAVE",8),n.write("fmt ",12),n.writeUInt32LE(16,16),n.writeUInt16LE(1,20),n.writeUInt16LE(1,22),n.writeUInt32LE(r,24),n.writeUInt32LE(r*2,28),n.writeUInt16LE(2,32),n.writeUInt16LE(16,34),n.write("data",36),n.writeUInt32LE(t,40),Buffer.concat([n,e.subarray(0,t)])}function P(e){const r=String(e||"").trim();return r.toLowerCase().startsWith("bearer ")?r.slice(7).trim():r}export{L as TTS_PROVIDERS,$ as isValidRemoteVoice,h as isValidTtsProvider,V as pcm16ToWav,B as remoteVoiceFor,z as synthesizeRemote,O as ttsDestination};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.139.3";export{o as VERSION};
1
+ const o="0.139.5";export{o as VERSION};