@chatpanel/gateway 0.97.2 → 0.98.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.97.2",
3
+ "version": "0.98.0",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -15,7 +15,8 @@
15
15
  "bin",
16
16
  "gateway.config.example.json",
17
17
  "LICENSE",
18
- "README.md"
18
+ "README.md",
19
+ "native/darwin-arm64"
19
20
  ],
20
21
  "engines": {
21
22
  "node": ">=22.13"
@@ -23,7 +24,7 @@
23
24
  "dependencies": {
24
25
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
25
26
  "@chatpanel/bridge": "^0.46.0",
26
- "@chatpanel/events": "^0.358.1",
27
+ "@chatpanel/events": "^0.359.0",
27
28
  "@chatpanel/pii": "^0.15.0",
28
29
  "@huggingface/transformers": "^4.2.0",
29
30
  "defuddle": "^0.19.4",
@@ -0,0 +1,2 @@
1
+ import{randomUUID as N}from"node:crypto";import{createAppender as v}from"./event.js";const b="gateway",k=e=>Math.max(0,Number(e)||0),u=(e,t)=>String(e??"").replace(/[\r\n\t]+/g," ").trim().slice(0,t);function w(e,t=""){if(!e)return null;if(e.kind==="partner")return`partner:${u(e.partner,40)||"partner"}`;const o=u(t,40);return o?`phone:${o}`:"phone"}function O(e){if(!e||typeof e!="object")return null;const t=k(e.prompt_tokens_details?.cached_tokens??e.input_tokens_details?.cached_tokens??e.cache_read_input_tokens),o=e.prompt_tokens!=null||e.input_tokens_details!=null,a=k(e.prompt_tokens??e.input_tokens),s={inputTokens:o?Math.max(0,a-t):a,outputTokens:k(e.completion_tokens??e.output_tokens),cacheReadTokens:t,cacheWriteTokens:k(e.cache_creation_input_tokens)};return s.inputTokens||s.outputTokens||s.cacheReadTokens||s.cacheWriteTokens?s:null}const S=e=>[e?.usage,e?.message?.usage,e?.response?.usage].filter(t=>t&&typeof t=="object");function D(e){try{const t=S(JSON.parse(String(e)))[0];return t?O(t):null}catch{return null}}function I(){const e=new TextDecoder;let t="",o=null;const a=l=>{const c=l.trim();if(!c.startsWith("data:"))return;const n=c.slice(5).trim();if(!n||n==="[DONE]"||!n.includes("usage"))return;let r;try{r=JSON.parse(n)}catch{return}for(const T of S(r)){o={...o||{}};for(const[f,m]of Object.entries(T))m!=null&&(o[f]=m)}};return{stream:new TransformStream({transform(l,c){t+=e.decode(l,{stream:!0});let n;for(;(n=t.indexOf(`
2
+ `))!==-1;)a(t.slice(0,n)),t=t.slice(n+1);c.enqueue(l)},flush(){t+=e.decode(),t&&a(t),t=""}}),usage:()=>O(o)}}function U({store:e=null,now:t=()=>Date.now(),newId:o=()=>N(),log:a=s=>{}}={}){let s=null;const l=c=>{for(let n=0;n<2;n++)try{if(!s){const r=e.cursor()[b];s=v({host:b,seq:Number.isInteger(r)?r+1:0,now:t,newId:o})}return e.append(s.append("turn.ended",c)),!0}catch(r){if(s=null,r?.code!=="SEQ")return a(`[link-activity] not recorded: ${r?.code||r?.message||r}`),!1}return!1};return{begin({caller:c,surface:n,agentId:r=null,model:T=null,dest:f=null,threadId:m=null,startedAt:g}={}){if(!e||!c||!n)return null;const W=Number.isFinite(g)?g:t(),y=`link-${o()}`,p={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};let x=!1,_=!1;return{turnId:y,get ended(){return _},add(i){if(!i)return;const h=Object.keys(p);if(h.some(d=>k(i[d]))){x=!0;for(const d of h)p[d]+=k(i[d])}},end(i="ok",{code:h=""}={}){if(_)return!1;_=!0;const d={turnId:y,reason:i,stepped:i==="ok",ms:Math.max(0,t()-W),kind:"chat",relayed:!0,surface:n,...r?{agentId:u(r,120)}:{},...T?{model:u(T,200)}:{},...f?.type?{dest:{type:f.type,id:u(f.id,120)}}:{},...m?{threadId:u(m,160)}:{},...x?{tokensIn:p.inputTokens,tokensOut:p.outputTokens,cacheReadTokens:p.cacheReadTokens,cacheWriteTokens:p.cacheWriteTokens}:{},...i==="error"&&h?{error:{code:u(h,60)}}:{}};return l(d)}}}}}export{b as GATEWAY_HOST,U as createLinkActivity,w as linkSurface,O as providerUsage,I as sseUsageTap,D as usageOfBody};
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\/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 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 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=Ee,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 ve(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=Ee,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 E=new Map,P=new Map;let A=null;async function x(){return A||(u.key?A=await Z.keyPairFromPrivate(ne(u.key)):(A=await Z.generateKeyPair(),u.key=O(A.raw),ve(T,u)),A)}const _=t=>u.rooms.find(e=>e.room===t)||null,B=()=>ve(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(xe(a.body,m))){if(n.cancelled)break;if(!f)try{await n.write(y)}catch{f=!0}}}if(!f)return n.end()}async function*xe(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=E.get(t.room)||{attempts:0,stopped:!1,online:!1};if(E.set(t.room,e),e.stopped)return;const n=await x(),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||E.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=E.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=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 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=_(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 Ke({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=Ke({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},partnerFolderOf(t){const e=_(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 x(),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 K=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=_(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:K,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 x(),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(K=>!K.phoneKey&&!$(K)))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=_(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=>!!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: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":E.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[...E.keys()]){const n=_(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 x();for(const e of u.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 oe(e,404,"not found");const r=_(o),s=String(t.headers["sec-websocket-protocol"]||"").split(",").map(v=>v.trim()).filter(Boolean),d=/^Bearer ([A-Za-z0-9_-]+)$/.exec(String(t.headers.authorization||""))?.[1]||(s.length===2&&s.includes(Y)?s.find(v=>v!==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(v=>w()-v<6e4),p.connects.length>=lt)return oe(e,429,"too many connects");p.connects.push(w());const K=await x(),h=nt(t,e,n,{protocol:Y});if(!h)return;H(o,4001,"replaced"),p.ws=h,p.online=!1;const b=ie(r,K,f,p,v=>{try{h.send(v)}catch{}});p.endpoint=b,h.onmessage=v=>{typeof v.data!="string"&&b.onBinary(new Uint8Array(v.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=_(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 x();for(const t of u.rooms)I(t)}},stop(){for(const t of[...E.keys()])X(t);for(const t of[...P.keys()])H(t,1001,"going away")},get publicKey(){return A?.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,Ee 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 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\/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 Se(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=Se,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 ve(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 ve(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=v=>globalThis.crypto.getRandomValues(new Uint8Array(v)),crypto:Z=Fe(),log:U=v=>{},mayLink:Pe=Se,ownerIsPro:Ae=async()=>!1,home:_e=te.homedir(),confined:be=process.env.CHATPANEL_CONFINED==="1"}={}){const v=i?new URL(i).origin:null;if(v&&!/^https:/.test(v)&&!/^http:\/\/127\.0\.0\.1(?::\d+)?$/.test(v))throw new Error("link: the relay must be https");const se=t=>{const e=me(t);return v&&e.relay?{...e,relay:v}:e};let l=se(c);l.problem&&U(`link: ${l.problem} — using ChatPanel Link`);let u=ve(T);const Le=v||me({relayUrl:c?.relayUrl}).relay;for(const t of u.rooms)t.relay===void 0&&(t.relay=Le);const S=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=S.get(t.room)||{attempts:0,stopped:!1,online:!1};if(S.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||S.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=S.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=S.get(t);if(e){e.stopped=!0,clearTimeout(e.timer),clearInterval(e.keepalive),e.endpoint?.close("stopped");try{e.ws?.close(1e3,"stopped")}catch{}S.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=v||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=>!!S.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":S.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[...S.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)&&!S.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[...S.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,Se as phoneMayLink};
package/src/server.js CHANGED
@@ -1,64 +1,64 @@
1
- import{createServer as Ro}from"node:http";import{loadConfig as Ct}from"./config.js";import{startEntitlementRefresh as jo,maybeRevalidate as Lo}from"./entitlement-refresh.js";import{redactSegments as Ve,segment as st,rememberAnswer as It}from"./redact.js";import{pipeRestoredStream as Jo,pipeRestoredOpenAIStream as zo,makeTokenRestorer as Rt,restoreDeep as Go}from"./stream.js";import{restoreText as Uo,gatedDictionary as Ho,narrowSpecs as Vo,makeToolHarness as Fo,placeholderToolNote as Wo,placeholderNote as Ko,assertEndpointUrl as Qo,capRunOptions as Yo,isPaired as jt}from"@chatpanel/pii";import{ensureGatewayToken as Te,currentGatewayToken as Me,isAdminAuthorized as H,callerTrustOf as De,setPinnedExtensionIds as Zo,issuePairingCode as Xo,claimPairingCode as qo}from"./gateway-token.js";import{createPairAsk as er,nativeConfirm as tr}from"./pair-prompt.js";import{createEngineProbe as or}from"./local-engine-probe.js";import{randomUUID as rr}from"node:crypto";import{installEgressLedger as nr,egressAudit as ar}from"./egress.js";import{trustSystemCertificates as sr,systemCaWanted as Lt,systemCaState as ir}from"./system-ca.js";import{initPolicy as lr,activePolicy as Fe,applyPolicyToConfig as Jt,managedSummary as Ce,PolicyLoadError as dr}from"./policy.js";import{routeAllowed as zt,agentAllowed as cr,egressAllowed as ur}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as Ie}from"./bridge.js";import{secureFetch as We}from"./secure-fetch.js";import{fetchCard as Ke,forgetCard as mr,sendMessage as pr,streamMessage as hr,getTask as yr,cancelTask as fr,knownAgents as gr,A2AError as Gt}from"./a2a.js";import{streamBridgeChat as Ut,readBridgeToken as Re,openBridgeChat as wr,acceptedBridgeToken as Ht}from"./bridge.js";import{createRelaySession as br,getRelaySession as Vt,endRelaySession as je,pumpBridgeStream as kr,deliverToolResult as Ft,toolsToSpecs as vr,wantsApprovals as Sr,parseToolCallId as Wt,touchRelaySession as Qe}from"./toolrelay.js";import{shaperFor as it}from"./shape.js";import{startNer as Tr,ensureNer as Ye,unionForThisMachine as xr,skippedCompanions as _r}from"./ner.js";import{recommendDetector as Kt}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Or}from"./log.js";import{saveBackupSecret as Er,clearBackupSecret as $r,loadBackupSecret as lt,hasBackupSecret as Qt}from"./history-store.js";import{createMemoryStore as Pr}from"./memory-store.js";import{createPrefsStore as Ar}from"./prefs-store.js";import{agentCardFor as Yt,runHintFor as Zt}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as Nr}from"@chatpanel/events/agent-thread.js";import{portClashPlan as Br,serviceManagerOf as Mr,STANDBY_POLL_MS as Dr}from"@chatpanel/events/service-standby.js";import{threadTarget as Cr,frameQuestion as Ir,wireMessages as Rr,appendExchange as jr,MAX_MESSAGE as Xt}from"@chatpanel/events/thread-send.js";import{researchStore as Lr,researchResponse as Jr}from"./research.js";import{createTeamStore as zr,loadOrCreateKey as dt}from"./team-store.js";import{createScorecardStore as Gr}from"./scorecard-store.js";import{createEngineLedgerStore as Ur}from"./engine-ledger-store.js";import{createProjectStore as Hr}from"./project-store.js";import{applicationsFor as Vr,recruitPass as Fr}from"./recruiting.js";import{ensureBridge as Wr,holderOf as Kr}from"./bridge-supervisor.js";import{checkForUpdate as Qr,updateStatus as Yr,startUpdate as Zr,updateJob as Xr,installKind as qr}from"./update.js";import{confinedStatus as ct,confinedLine as en}from"./confine.js";import{appleHelperWanted as tn,findAppleHelper as on}from"./apple-helper-fetch.js";import{createHistoryStore as rn}from"./sqlite-store.js";import{createEventStore as nn}from"./event-store.js";import{ingestCloudEvents as an,cursorOf as qt}from"./event-sync.js";import{eventStats as sn,projectYear as ln}from"./event-stats.js";import{toCloudEvent as ut}from"./cloudevents.js";import{fusionsDocument as dn,resolveFusionModel as cn}from"./fusions.js";import{ingestBackups as mt}from"./backup-ingest.js";import{toSearchRecord as eo}from"@chatpanel/events/library.js";import{deriveBackupKey as un,openRecord as mn,keyCache as pn,nodeCodec as hn}from"@chatpanel/events/backup-envelope.js";import yn from"node:zlib";import*as I from"./ner-engine.js";import pt from"node:os";import{capabilitiesDocument as fn,handleDetect as gn}from"./capabilities.js";import{createExtractService as wn}from"./extract/service.js";import{workerSandbox as bn,disposeWorkerSandbox as kn}from"./worker-sandbox.js";import{createRuntime as vn,SERVICES as Sn}from"./runtime.js";import{createCapabilityProxy as Tn}from"./capability-proxy.js";import{createEmbeddedCapabilities as xn}from"./capability-embedded.js";import{EMBEDDED_MODELS as _n,EMBEDDED_IDS as On}from"./embedded-models.js";import{handleExtract as En}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as $n}from"./extract-capability.js";import{createReader as Pn}from"./retrieval/read.js";import{createBrowserRelayHost as An}from"./browser-relay.js";import{createLinkHost as Nn}from"./link-host.js";import{checkLinkRoute as Bn,tunnelHeader as Mn,LINK_TUNNEL_ROOM_PATH as Dn}from"@chatpanel/events/link-routes.js";import{linkCallerOf as to,linkDestinationAllowed as Cn,linkVia as In,partnerRunHint as Rn,PARTNER_APPROVAL_DECISIONS as oo,partnerFilePath as jn}from"@chatpanel/events/link-scopes.js";import{listPartnerFiles as Ln,readPartnerFile as Jn,writePartnerFile as zn,removePartnerFile as Gn}from"./link-files.js";import{isPermissionTool as ro}from"@chatpanel/events/agent-permission.js";import{createApprovalInbox as Un}from"./link-approvals.js";import{createSearcher as Hn,toJinaSearch as Vn,SEARCH_DEFAULTS as Fn}from"./retrieval/search.js";import{createSearxng as Wn}from"./retrieval/search-searxng.js";import{searchEngines as Kn}from"./retrieval/search-apis.js";import{toJinaText as Qn}from"./read-document.js";import*as B from"./stt-engine.js";import*as M from"./diarize-engine.js";import{DIARIZE_MODEL_CATALOG as Yn,DEFAULT_DIARIZE_MODEL as Zn,isKnownDiarizeModel as no}from"./diarize-models.js";import{providerOf as ht}from"./providers.js";import{createRemoteTranscriber as ao}from"./stt-remote.js";import{parseMultipart as Xn,decodeAudioFile as qn}from"./audio-file.js";import{MODEL_CATALOG as so,isKnownModel as io,isValidCustomModelId as lo,recommendFor as ea}from"./models.js";import{STT_MODEL_CATALOG as ta,isKnownSttModel as oa,isValidCustomSttId as ra,DEFAULT_STT_MODEL as Ze,STT_DTYPES as na,isValidDtype as aa}from"./stt-models.js";import*as C from"./tts-engine.js";import{TTS_MODEL_CATALOG as co,TTS_VOICES as sa,isKnownTtsModel as ia,isValidCustomTtsId as la,isKnownVoice as uo,isValidVoiceId as mo,DEFAULT_TTS_MODEL as po,DEFAULT_TTS_VOICE as ve,TTS_DTYPES as da,isValidTtsDtype as ca,MAX_TTS_CHARS as ho,ttsModelHasCustomVoices as ua,resolveDefaultModel as yo,POCKET_VOICES as ma,DEFAULT_POCKET_VOICE as Xe,isPocketVoice as qe,ttsModelEngine as et}from"./tts-models.js";import{ttsDestination as pa,synthesizeRemote as ha,isValidRemoteVoice as ya}from"./tts-remote.js";import{rawOrtAvailable as yt}from"./ort.js";import*as se from"./tts-voices.js";import{resolveTtsVoice as fa}from"./tts-voice-resolve.js";import{resolvePro as ge,checkQuota as ga,consume as wa,usage as ba}from"./freegate.js";import{publicConfig as fo,applyConfigPatch as ka,registryChildEnv as va,applyNerModelSelection as go,persistConfig as he,configPath as re,bridgeAgentOptions as wo,PERMISSION_MODES as Sa,sandboxEnvFor as Ta,sandboxProblems as xa}from"./configstore.js";import Le from"node:path";import{resolveDestination as tt,aggregateModelsAsync as _a,listDestinations as Oa,ensureModelCatalog as Ea,agentOwnsModel as $a}from"./router.js";import{makeAccessEvent as bo}from"./observability.js";import{createPersistentAccessLog as Pa}from"./access-log-store.js";import{planQueries as Aa,multiSearch as Na}from"./rrf.js";import*as ft from"./openai.js";import*as ko from"./responses.js";import*as gt from"./anthropic.js";import{closeAndExit as Ba}from"./shutdown.js";import{VERSION as ne}from"./version.js";import{VERSION as Ui}from"./version.js";const R=await rn(),we=new Set;function Je({ids:t=[]}={}){const d=R.lossless;if(!d||!we.size)return;const u=JSON.stringify({newest:d.newest,rev:d.rev,size:d.size,ids:t.slice(0,50),at:Date.now()});for(const m of we)try{m.write(`event: records
1
+ import{createServer as Go}from"node:http";import{loadConfig as Rt}from"./config.js";import{startEntitlementRefresh as Ho,maybeRevalidate as Uo}from"./entitlement-refresh.js";import{redactSegments as Ke,segment as dt,rememberAnswer as jt}from"./redact.js";import{pipeRestoredStream as Vo,pipeRestoredOpenAIStream as Fo,makeTokenRestorer as Lt,restoreDeep as Wo}from"./stream.js";import{restoreText as Ko,gatedDictionary as Qo,narrowSpecs as Yo,makeToolHarness as Zo,placeholderToolNote as Xo,placeholderNote as qo,assertEndpointUrl as er,capRunOptions as tr,isPaired as Jt}from"@chatpanel/pii";import{ensureGatewayToken as _e,currentGatewayToken as Me,isAdminAuthorized as U,callerTrustOf as Ce,setPinnedExtensionIds as or,issuePairingCode as rr,claimPairingCode as nr}from"./gateway-token.js";import{createPairAsk as ar,nativeConfirm as sr}from"./pair-prompt.js";import{createEngineProbe as ir}from"./local-engine-probe.js";import{randomUUID as lr}from"node:crypto";import{installEgressLedger as dr,egressAudit as cr}from"./egress.js";import{trustSystemCertificates as ur,systemCaWanted as zt,systemCaState as mr}from"./system-ca.js";import{initPolicy as pr,activePolicy as Qe,applyPolicyToConfig as Gt,managedSummary as Ie,PolicyLoadError as hr}from"./policy.js";import{routeAllowed as Ht,agentAllowed as yr,egressAllowed as fr}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as Re}from"./bridge.js";import{secureFetch as Ye}from"./secure-fetch.js";import{fetchCard as Ze,forgetCard as gr,sendMessage as wr,streamMessage as br,getTask as kr,cancelTask as vr,knownAgents as Sr,A2AError as Ut}from"./a2a.js";import{streamBridgeChat as Vt,readBridgeToken as je,openBridgeChat as Tr,acceptedBridgeToken as Ft}from"./bridge.js";import{createRelaySession as xr,getRelaySession as Wt,endRelaySession as Le,pumpBridgeStream as _r,deliverToolResult as Kt,toolsToSpecs as Or,wantsApprovals as Er,parseToolCallId as Qt,touchRelaySession as Xe}from"./toolrelay.js";import{shaperFor as ct}from"./shape.js";import{startNer as $r,ensureNer as qe,unionForThisMachine as Pr,skippedCompanions as Ar}from"./ner.js";import{recommendDetector as Yt}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Nr}from"./log.js";import{saveBackupSecret as Br,clearBackupSecret as Dr,loadBackupSecret as ut,hasBackupSecret as Zt}from"./history-store.js";import{createMemoryStore as Mr}from"./memory-store.js";import{createPrefsStore as Cr}from"./prefs-store.js";import{agentCardFor as Xt,runHintFor as qt}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as Ir}from"@chatpanel/events/agent-thread.js";import{portClashPlan as Rr,serviceManagerOf as jr,STANDBY_POLL_MS as Lr}from"@chatpanel/events/service-standby.js";import{threadTarget as Jr,frameQuestion as zr,wireMessages as Gr,appendExchange as Hr,MAX_MESSAGE as eo}from"@chatpanel/events/thread-send.js";import{researchStore as Ur,researchResponse as Vr}from"./research.js";import{createTeamStore as Fr,loadOrCreateKey as mt}from"./team-store.js";import{createScorecardStore as Wr}from"./scorecard-store.js";import{createEngineLedgerStore as Kr}from"./engine-ledger-store.js";import{createProjectStore as Qr}from"./project-store.js";import{applicationsFor as Yr,recruitPass as Zr}from"./recruiting.js";import{ensureBridge as Xr,holderOf as qr}from"./bridge-supervisor.js";import{checkForUpdate as en,updateStatus as tn,startUpdate as on,updateJob as rn,installKind as nn}from"./update.js";import{confinedStatus as pt,confinedLine as an}from"./confine.js";import{appleHelperWanted as sn,findAppleHelper as ln}from"./apple-helper-fetch.js";import{createHistoryStore as dn}from"./sqlite-store.js";import{createEventStore as cn}from"./event-store.js";import{createLinkActivity as un,linkSurface as mn,sseUsageTap as pn,usageOfBody as hn,GATEWAY_HOST as to}from"./link-activity.js";import{ingestCloudEvents as yn,cursorOf as oo}from"./event-sync.js";import{eventStats as fn,projectYear as gn}from"./event-stats.js";import{toCloudEvent as ht,ceHostOf as wn}from"./cloudevents.js";import{fusionsDocument as bn,resolveFusionModel as kn}from"./fusions.js";import{ingestBackups as yt}from"./backup-ingest.js";import{toSearchRecord as ro}from"@chatpanel/events/library.js";import{deriveBackupKey as vn,openRecord as Sn,keyCache as Tn,nodeCodec as xn}from"@chatpanel/events/backup-envelope.js";import _n from"node:zlib";import*as R from"./ner-engine.js";import ft from"node:os";import{capabilitiesDocument as On,handleDetect as En}from"./capabilities.js";import{createExtractService as $n}from"./extract/service.js";import{workerSandbox as Pn,disposeWorkerSandbox as An}from"./worker-sandbox.js";import{createRuntime as Nn,SERVICES as Bn}from"./runtime.js";import{createCapabilityProxy as Dn}from"./capability-proxy.js";import{createEmbeddedCapabilities as Mn}from"./capability-embedded.js";import{EMBEDDED_MODELS as Cn,EMBEDDED_IDS as In}from"./embedded-models.js";import{handleExtract as Rn}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as jn}from"./extract-capability.js";import{createReader as Ln}from"./retrieval/read.js";import{createBrowserRelayHost as Jn}from"./browser-relay.js";import{createLinkHost as zn}from"./link-host.js";import{checkLinkRoute as Gn,tunnelHeader as Hn,LINK_TUNNEL_ROOM_PATH as Un}from"@chatpanel/events/link-routes.js";import{linkCallerOf as no,linkDestinationAllowed as Vn,linkVia as Fn,partnerRunHint as Wn,PARTNER_APPROVAL_DECISIONS as ao,partnerFilePath as Kn}from"@chatpanel/events/link-scopes.js";import{listPartnerFiles as Qn,readPartnerFile as Yn,writePartnerFile as Zn,removePartnerFile as Xn}from"./link-files.js";import{isPermissionTool as so}from"@chatpanel/events/agent-permission.js";import{createApprovalInbox as qn}from"./link-approvals.js";import{createSearcher as ea,toJinaSearch as ta,SEARCH_DEFAULTS as oa}from"./retrieval/search.js";import{createSearxng as ra}from"./retrieval/search-searxng.js";import{searchEngines as na}from"./retrieval/search-apis.js";import{toJinaText as aa}from"./read-document.js";import*as B from"./stt-engine.js";import*as D from"./diarize-engine.js";import{DIARIZE_MODEL_CATALOG as sa,DEFAULT_DIARIZE_MODEL as ia,isKnownDiarizeModel as io}from"./diarize-models.js";import{providerOf as gt}from"./providers.js";import{createRemoteTranscriber as lo}from"./stt-remote.js";import{parseMultipart as la,decodeAudioFile as da}from"./audio-file.js";import{MODEL_CATALOG as co,isKnownModel as uo,isValidCustomModelId as mo,recommendFor as ca}from"./models.js";import{STT_MODEL_CATALOG as ua,isKnownSttModel as ma,isValidCustomSttId as pa,DEFAULT_STT_MODEL as et,STT_DTYPES as ha,isValidDtype as ya}from"./stt-models.js";import*as M from"./tts-engine.js";import{TTS_MODEL_CATALOG as po,TTS_VOICES as fa,isKnownTtsModel as ga,isValidCustomTtsId as wa,isKnownVoice as ho,isValidVoiceId as yo,DEFAULT_TTS_MODEL as fo,DEFAULT_TTS_VOICE as xe,TTS_DTYPES as ba,isValidTtsDtype as ka,MAX_TTS_CHARS as go,ttsModelHasCustomVoices as va,resolveDefaultModel as wo,POCKET_VOICES as Sa,DEFAULT_POCKET_VOICE as tt,isPocketVoice as ot,ttsModelEngine as rt}from"./tts-models.js";import{ttsDestination as Ta,synthesizeRemote as xa,isValidRemoteVoice as _a}from"./tts-remote.js";import{rawOrtAvailable as wt}from"./ort.js";import*as me from"./tts-voices.js";import{resolveTtsVoice as Oa}from"./tts-voice-resolve.js";import{resolvePro as Se,checkQuota as Ea,consume as $a,usage as Pa}from"./freegate.js";import{publicConfig as bo,applyConfigPatch as Aa,registryChildEnv as Na,applyNerModelSelection as ko,persistConfig as ke,configPath as ie,bridgeAgentOptions as vo,PERMISSION_MODES as Ba,sandboxEnvFor as Da,sandboxProblems as Ma}from"./configstore.js";import Je from"node:path";import{resolveDestination as nt,aggregateModelsAsync as Ca,listDestinations as Ia,ensureModelCatalog as Ra,agentOwnsModel as ja}from"./router.js";import{makeAccessEvent as So}from"./observability.js";import{createPersistentAccessLog as La}from"./access-log-store.js";import{planQueries as Ja,multiSearch as za}from"./rrf.js";import*as bt from"./openai.js";import*as To from"./responses.js";import*as kt from"./anthropic.js";import{closeAndExit as Ga}from"./shutdown.js";import{VERSION as le}from"./version.js";import{VERSION as el}from"./version.js";const j=await dn(),Te=new Set;function ze({ids:t=[]}={}){const d=j.lossless;if(!d||!Te.size)return;const u=JSON.stringify({newest:d.newest,rev:d.rev,size:d.size,ids:t.slice(0,50),at:Date.now()});for(const m of Te)try{m.write(`event: records
2
2
  data: ${u}
3
3
 
4
- `)}catch{we.delete(m)}}setInterval(()=>{for(const t of we)try{t.write(`: ping
4
+ `)}catch{Te.delete(m)}}setInterval(()=>{for(const t of Te)try{t.write(`: ping
5
5
 
6
- `)}catch{we.delete(t)}},25e3).unref?.();const Z=await nn(),xe=new Set;Z?.watch(t=>{if(!xe.size)return;const d=`event: cloudevent
7
- data: ${JSON.stringify(ut(t))}
6
+ `)}catch{Te.delete(t)}},25e3).unref?.();const Z=await cn(),vt=un({store:Z,log:t=>console.log(t)}),Oe=new Set;Z?.watch(t=>{if(!Oe.size)return;const d=`event: cloudevent
7
+ data: ${JSON.stringify(ht(t))}
8
8
 
9
- `;for(const u of xe)try{u.write(d)}catch{xe.delete(u)}}),setInterval(()=>{for(const t of xe)try{t.write(`: ping
9
+ `;for(const u of Oe)try{u.write(d)}catch{Oe.delete(u)}}),setInterval(()=>{for(const t of Oe)try{t.write(`: ping
10
10
 
11
- `)}catch{xe.delete(t)}},25e3).unref?.();const ce=await Pr(),ae=Ar(),$e=Gr({key:dt()}),Pe=Ur({key:dt()}),ie=Hr({key:dt()}),Y=zr({scorecards:$e,engines:Pe}),wt=new Set,vo=(t,d)=>{for(const m of wt)try{m({applied:t,by:d,revision:ae.revision})}catch{}const u=JSON.stringify({revision:ae.revision,applied:(t||[]).slice(0,50),by:d||"",at:Date.now()});for(const m of we)try{m.write(`event: prefs
11
+ `)}catch{Oe.delete(t)}},25e3).unref?.();const ye=await Mr(),de=Cr(),Ae=Wr({key:mt()}),Ne=Kr({key:mt()}),pe=Qr({key:mt()}),X=Fr({scorecards:Ae,engines:Ne}),St=new Set,xo=(t,d)=>{for(const m of St)try{m({applied:t,by:d,revision:de.revision})}catch{}const u=JSON.stringify({revision:de.revision,applied:(t||[]).slice(0,50),by:d||"",at:Date.now()});for(const m of Te)try{m.write(`event: prefs
12
12
  data: ${u}
13
13
 
14
- `)}catch{we.delete(m)}},bt=Pa(),So=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Ma=16,Da=/^mcp[_-]/i,To=t=>t&&t.function&&t.function.name||t&&t.name||"",Ca=t=>t&&t.function&&t.function.description||t&&t.description||"";function xo(t){return typeof t=="string"?t:Array.isArray(t)?t.map(d=>typeof d=="string"?d:d&&(d.text||d.content)||"").join(" "):""}function Ia(t,d){if(!t)return"";if(d==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(f=>xo(f&&(f.content??f))).join(" "):""}const u=Array.isArray(t.messages)?t.messages:[];for(let m=u.length-1;m>=0;m--)if(u[m]&&u[m].role==="user")return xo(u[m].content);return""}const _o=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function ot(t){if(!t)return!1;const d=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return d==="localhost"||d==="127.0.0.1"||d==="::1"}function Ra(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 ja(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 Oo=Date.now();function La(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 Ja(t){const d=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return d?{kind:d[1],id:d[2],...d[3]?{model:d[3]}:{}}:null}function za(t){const d=performance.now(),u={};let m=!1;const f=(y,E)=>{u[y]=Math.round(E*10)/10};return{meta:{},timings:u,mark:f,lap(y,E){f(y,performance.now()-E)},clock(){return performance.now()},commit(){if(m)return;m=!0,f("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}`:""} · ${La(u)}`)})}}}function Eo(t,d){if(!t||!t.byToken||d!=="types"&&d!=="values")return;const u=[];for(const[m,f]of t.byToken){const y=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),E=y?y[1]:"PII",A=m.replace(/^\[\[|\]\]$/g,"");u.push(d==="values"?{token:A,type:E,value:f}:{token:A,type:E})}return u}function Ga(t,d,u){return gt.matches(t)||"anthropic-version"in d?{kind:"anthropic",adapter:gt,redactable:gt.matches(t),base:u.upstreams?.anthropic?.baseUrl}:ko.matches(t)?{kind:"responses",adapter:ko,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:ft,redactable:ft.matches(t),base:u.upstreams?.openai?.baseUrl}}function kt(t,d){const u=String(t||"");if(So.has(u))return{agent:u,agentModel:""};const m=u.indexOf("/");if(m>0){const f=u.slice(0,m);if(So.has(f))return{agent:f,agentModel:u.slice(m+1)}}return{agent:d.bridge.agent,agentModel:""}}function $o(t,d){return kt(t,d).agent}function Ua(t,d){if(d!=="openai"||!t)return!1;const u=ft.extractLatestToolResult(t);if(!u)return!1;const m=Wt(u.tool_call_id);return!!(m&&Vt(m.gwId))}function Ha(t,d){try{const u=new URL(t),m=u.hostname.replace(/^\[|\]$/g,""),f=m==="127.0.0.1"||m==="localhost"||m==="::1",y=u.port||(u.protocol==="https:"?"443":"80");return f&&String(y)===String(d.port)}catch{return!1}}const Va=25*1024*1024;async function S(t,d){const u=[];let m=0;for await(const f of t){if(m+=f.length,d&&m>d){const y=new Error("payload too large");throw y.code=413,y}u.push(f)}return Buffer.concat(u)}function a(t,d,u){t.writeHead(d,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function Po(t){const d=t.redaction?.detection?.url;return!d||t.redaction?.detection?.backend==="off"?null:d}function vt(t){const d=t?.redaction?.detection,u=t?.redaction?.tier==="full"?"full":"basic";if(d&&d.backend&&d.backend!=="off")return{source:"external",backend:d.backend,state:"external",model:d.model||null,ready:!0,tier:u,coverage:u==="full"?"names":"patterns"};const m=I.health(),f=m.ok&&u==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:I.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:f,tier:u,coverage:f?"names":"patterns"}}async function Ao(t){if(I.state()!=="off"){const u=I.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=Po(t);if(!d)return{configured:!1,ok:!1,url:null,model:null};try{const u=await We(d.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:d,model:null};const m=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:d,model:m.model||null}}catch{return{configured:!0,ok:!1,url:d,model:null}}}function Fa(t,d){const u={};for(const[m,f]of Object.entries(t)){const y=m.toLowerCase();y.startsWith("x-chatpanel-")||_o.has(y)||(u[m]=f)}u["accept-encoding"]="identity";try{u.host=new URL(d).host}catch{}return u}async function No(t,d,u,m){const f=Rt(d.vault),y=Tt();t.on("close",()=>{t.writableFinished||je(d.id)});const E=m?m.clock():0;let A=E,O=!0;const k=()=>{m&&O&&(m.lap("upstream",E),A=m.clock(),O=!1)};let _="";const D=()=>{d.redaction&&_&&It(_,d.redaction),_=""};let z=null;const j={onText:$=>{k(),Qe(d.id);const U=f.push($);U&&(_+=U,t.write(u.sseDelta(U)))},onToolRequest:({name:$,restoredArgs:U,toolId:K})=>{if(k(),Qe(d.id),d.ownerApprovals&&ro($)){z=U;return}const X=f.flush();X&&(_+=X,t.write(u.sseDelta(X))),t.write(u.sseToolCalls([{id:K,name:$,arguments:JSON.stringify(U)}])),t.write(u.sseToolFinish(y.value)),m&&m.lap("stream",A),t.end(),m?.commit(),D()},onDone:()=>{const $=f.flush();$&&(_+=$,t.write(u.sseDelta($))),t.write(u.sseTail(y.value)),m&&m.lap("stream",A),t.end(),je(d.id),m?.commit(),D(),St(d)},onError:$=>{t.write(`data: ${JSON.stringify({error:{message:$.message,type:"bridge_error"}})}
14
+ `)}catch{Te.delete(m)}},Tt=La(),_o=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Ha=16,Ua=/^mcp[_-]/i,Oo=t=>t&&t.function&&t.function.name||t&&t.name||"",Va=t=>t&&t.function&&t.function.description||t&&t.description||"";function Eo(t){return typeof t=="string"?t:Array.isArray(t)?t.map(d=>typeof d=="string"?d:d&&(d.text||d.content)||"").join(" "):""}function Fa(t,d){if(!t)return"";if(d==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(f=>Eo(f&&(f.content??f))).join(" "):""}const u=Array.isArray(t.messages)?t.messages:[];for(let m=u.length-1;m>=0;m--)if(u[m]&&u[m].role==="user")return Eo(u[m].content);return""}const $o=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function at(t){if(!t)return!1;const d=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return d==="localhost"||d==="127.0.0.1"||d==="::1"}function Wa(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 Ka(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 Po=Date.now();function Qa(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 Ya(t){const d=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return d?{kind:d[1],id:d[2],...d[3]?{model:d[3]}:{}}:null}function Za(t){const d=performance.now(),u={};let m=!1;const f=(y,$)=>{u[y]=Math.round($*10)/10};return{meta:{},timings:u,mark:f,lap(y,$){f(y,performance.now()-$)},clock(){return performance.now()},commit(){if(m)return;m=!0,f("total",performance.now()-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}`:""} · ${Qa(u)}`)})}}}function Ao(t,d){if(!t||!t.byToken||d!=="types"&&d!=="values")return;const u=[];for(const[m,f]of t.byToken){const y=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),$=y?y[1]:"PII",N=m.replace(/^\[\[|\]\]$/g,"");u.push(d==="values"?{token:N,type:$,value:f}:{token:N,type:$})}return u}function Xa(t,d,u){return kt.matches(t)||"anthropic-version"in d?{kind:"anthropic",adapter:kt,redactable:kt.matches(t),base:u.upstreams?.anthropic?.baseUrl}:To.matches(t)?{kind:"responses",adapter:To,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:bt,redactable:bt.matches(t),base:u.upstreams?.openai?.baseUrl}}function xt(t,d){const u=String(t||"");if(_o.has(u))return{agent:u,agentModel:""};const m=u.indexOf("/");if(m>0){const f=u.slice(0,m);if(_o.has(f))return{agent:f,agentModel:u.slice(m+1)}}return{agent:d.bridge.agent,agentModel:""}}function No(t,d){return xt(t,d).agent}function qa(t,d){if(d!=="openai"||!t)return!1;const u=bt.extractLatestToolResult(t);if(!u)return!1;const m=Qt(u.tool_call_id);return!!(m&&Wt(m.gwId))}function es(t,d){try{const u=new URL(t),m=u.hostname.replace(/^\[|\]$/g,""),f=m==="127.0.0.1"||m==="localhost"||m==="::1",y=u.port||(u.protocol==="https:"?"443":"80");return f&&String(y)===String(d.port)}catch{return!1}}const ts=25*1024*1024;async function T(t,d){const u=[];let m=0;for await(const f of t){if(m+=f.length,d&&m>d){const y=new Error("payload too large");throw y.code=413,y}u.push(f)}return Buffer.concat(u)}function a(t,d,u){t.writeHead(d,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function Bo(t){const d=t.redaction?.detection?.url;return!d||t.redaction?.detection?.backend==="off"?null:d}function _t(t){const d=t?.redaction?.detection,u=t?.redaction?.tier==="full"?"full":"basic";if(d&&d.backend&&d.backend!=="off")return{source:"external",backend:d.backend,state:"external",model:d.model||null,ready:!0,tier:u,coverage:u==="full"?"names":"patterns"};const m=R.health(),f=m.ok&&u==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:R.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:f,tier:u,coverage:f?"names":"patterns"}}async function Do(t){if(R.state()!=="off"){const u=R.health();return{configured:u.configured,ok:u.ok,state:u.state,model:u.model,error:u.error||null,url:u.configured?`http://${t.host}:${t.port}/ner`:null,stats:u.stats,companions:u.companions}}const d=Bo(t);if(!d)return{configured:!1,ok:!1,url:null,model:null};try{const u=await Ye(d.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:d,model:null};const m=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:d,model:m.model||null}}catch{return{configured:!0,ok:!1,url:d,model:null}}}function os(t,d){const u={};for(const[m,f]of Object.entries(t)){const y=m.toLowerCase();y.startsWith("x-chatpanel-")||$o.has(y)||(u[m]=f)}u["accept-encoding"]="identity";try{u.host=new URL(d).host}catch{}return u}async function Mo(t,d,u,m){const f=Lt(d.vault),y=Et();t.on("close",()=>{t.writableFinished||Le(d.id)});const $=d.linkTurn||null,N=m?m.clock():0;let O=N,v=!0;const x=()=>{m&&v&&(m.lap("upstream",N),O=m.clock(),v=!1)};let C="";const J=()=>{d.redaction&&C&&jt(C,d.redaction),C=""};let H=null;const E={onText:G=>{x(),Xe(d.id);const z=f.push(G);z&&(C+=z,t.write(u.sseDelta(z)))},onToolRequest:({name:G,restoredArgs:z,toolId:oe})=>{if(x(),Xe(d.id),d.ownerApprovals&&so(G)){H=z;return}const q=f.flush();q&&(C+=q,t.write(u.sseDelta(q))),t.write(u.sseToolCalls([{id:oe,name:G,arguments:JSON.stringify(z)}])),t.write(u.sseToolFinish(y.value)),m&&m.lap("stream",O),t.end(),m?.commit(),J()},onDone:()=>{const G=f.flush();G&&(C+=G,t.write(u.sseDelta(G))),t.write(u.sseTail(y.value)),m&&m.lap("stream",O),t.end(),$?.end("ok"),Le(d.id),m?.commit(),J(),Ot(d)},onError:G=>{t.write(`data: ${JSON.stringify({error:{message:G.message,type:"bridge_error"}})}
15
15
 
16
- `),t.end(),je(d.id),m?.commit(),St(d)},onUsage:$=>y.add($)};for(;;){if(z=null,await kr(d,j)!=="parked"||!z)return;const U=d.ownerApprovals,K=new AbortController,X=()=>K.abort();t.once("close",X);const V=setInterval(()=>{Qe(d.id),t.writableEnded||t.write(`: waiting for the owner’s approval
16
+ `),t.end(),$?.end("error",{code:"bridge_error"}),Le(d.id),m?.commit(),Ot(d)},onUsage:G=>{y.add(G),$?.add(G)}};for(;;){if(H=null,await _r(d,E)!=="parked"||!H)return;const z=d.ownerApprovals,oe=new AbortController,q=()=>oe.abort();t.once("close",q);const K=setInterval(()=>{Xe(d.id),t.writableEnded||t.write(`: waiting for the owner’s approval
17
17
 
18
- `)},15e3);V.unref?.();let G;try{G=await U.inbox.ask(z,{partner:U.partner,device:U.device,conversation:U.conversation,signal:K.signal})}finally{clearInterval(V),t.off("close",X)}if(K.signal.aborted||t.writableEnded){St(d);return}try{await Ft(d,JSON.stringify(G))}catch(be){j.onError(be);return}}}function St(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function Wa(t,d,{kind:u,adapter:m,agent:f,run:y=null,owner:E=null},A,O,k,_,D,z=null,j=null){const{messages:$,system:U}=m.toTurn(A),{agentModel:K}=kt(A?.model,k),X=wo(k,{...K?{model:K}:{},...y||{}}),V=Re(k.bridge.token),G=it(u,A?.model||f),be={tier:k.redaction.tier==="full"?"full":"basic",dictionary:Ho(k.redaction,_),entities:[]},fe=await Ie(k),ue=br({vault:O,redactOpts:be,bridgeUrl:fe,token:V,harness:z});E&&(ue.ownerApprovals={...E,conversation:E.conversation||`partner.${E.device}.turn-${ue.id}`,turnScoped:!E.conversation}),O&&(ue.redaction=k.redaction);let de;try{de=await wr({bridgeUrl:fe,agent:f,token:V,messages:$,system:U,specs:vr(D),options:X,signal:void 0,approvals:!!E||Sr(D)})}catch(n){return je(ue.id),j?.commit(),a(d,502,{error:{message:`bridge: ${n.message}`,type:"bridge_error"}})}return ue.reader=de.body.getReader(),d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(G.sseHead()),No(d,ue,G,j)}async function Ka(t,d,u,m,f=null){Qe(d.id),d.rounds=(d.rounds||0)+1;try{const E=f?f.clock():0;await Ft(d,u),f&&f.lap("redact",E)}catch(E){return je(d.id),f?.commit(),a(t,502,{error:{message:`tool-result: ${E.message}`,type:"bridge_error"}})}const y=it("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(y.sseHead()),No(t,d,y,f)}function Tt(){let t=!1;const d={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const m of Object.keys(d))d[m]+=Math.max(0,Number(u?.[m])||0)},get value(){return t?d:null}}}async function Qa(t,d,{kind:u,adapter:m,redactable:f,pathname:y,agentOverride:E,harness:A,trace:O,run:k=null,owner:_=null},D,z,j,$){if(!f)return O?.commit(),a(d,404,{error:`endpoint ${y} not supported by the bridge backend`});if(u==="openai"){const J=m.extractLatestToolResult(D);if(J){const F=Wt(J.tool_call_id),T=F&&Vt(F.gwId);if(T)return Ka(d,T,J.content,D?.model,O)}const q=m.extractTools(D);if((q.length||_)&&D?.stream===!0)return Wa(t,d,{kind:u,adapter:m,agent:E||$o(D?.model,j),run:k,owner:_},D,z,j,$,q,A,O)}const{messages:U,system:K}=m.toTurn(D),X=E||$o(D?.model,j),V=D?.stream===!0,G=it(u,D?.model||X),be=Re(j.bridge.token),fe=new AbortController;d.on("close",()=>{d.writableFinished||fe.abort()});const{agentModel:ue}=kt(D?.model,j),de={bridgeUrl:await Ie(j),agent:X,token:be,messages:U,system:K,signal:fe.signal,options:wo(j,{...ue?{model:ue}:{},...k||{}})};if(!V)try{let J="";const q=Tt(),F=O?O.clock():0;await Ut(de,_e=>{J+=_e},null,_e=>q.add(_e)),O&&O.lap("upstream",F);const T=O?O.clock():0,Se=G.full(Uo(J,z),q.value);return O&&O.lap("restore",T),d.writeHead(200,{"content-type":G.contentType}),d.end(Se),O?.commit()}catch(J){return O?.commit(),a(d,502,{error:{message:`bridge backend failed: ${J.message}`,type:"bridge_error"}})}d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(G.sseHead());const n=Rt(z),o=O?O.clock():0;let g=o;const i=Tt();let le="";try{let J=!0;await Ut(de,F=>{O&&J&&(O.lap("upstream",o),g=O.clock(),J=!1);const T=n.push(F);T&&(le+=T,d.write(G.sseDelta(T)))},G.sseActivity?F=>{try{d.write(G.sseActivity(Go(F,z)))}catch{}}:null,F=>i.add(F));const q=n.flush();q&&(le+=q,d.write(G.sseDelta(q))),d.write(G.sseTail(i.value))}catch(J){d.write(`data: ${JSON.stringify({error:{message:J.message,type:"bridge_error"}})}
18
+ `)},15e3);K.unref?.();let ce;try{ce=await z.inbox.ask(H,{partner:z.partner,device:z.device,conversation:z.conversation,signal:oe.signal})}finally{clearInterval(K),t.off("close",q)}if(oe.signal.aborted||t.writableEnded){Ot(d);return}try{await Kt(d,JSON.stringify(ce))}catch(Q){E.onError(Q);return}}}function Ot(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function rs(t,d,{kind:u,adapter:m,agent:f,run:y=null,owner:$=null,linkTurn:N=null},O,v,x,C,J,H=null,E=null){const{messages:G,system:z}=m.toTurn(O),{agentModel:oe}=xt(O?.model,x),q=vo(x,{...oe?{model:oe}:{},...y||{}}),K=je(x.bridge.token),ce=ct(u,O?.model||f),Q={tier:x.redaction.tier==="full"?"full":"basic",dictionary:Qo(x.redaction,C),entities:[]},F=await Re(x),I=xr({vault:v,redactOpts:Q,bridgeUrl:F,token:K,harness:H});$&&(I.ownerApprovals={...$,conversation:$.conversation||`partner.${$.device}.turn-${I.id}`,turnScoped:!$.conversation}),N&&(I.linkTurn=N,I.onEnd=()=>N.end("aborted")),v&&(I.redaction=x.redaction);let n;try{n=await Tr({bridgeUrl:F,agent:f,token:K,messages:G,system:z,specs:Or(J),options:q,signal:void 0,approvals:!!$||Er(J)})}catch(o){return N?.end("error",{code:"bridge_error"}),Le(I.id),E?.commit(),a(d,502,{error:{message:`bridge: ${o.message}`,type:"bridge_error"}})}return I.reader=n.body.getReader(),d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(ce.sseHead()),Mo(d,I,ce,E)}async function ns(t,d,u,m,f=null){Xe(d.id),d.rounds=(d.rounds||0)+1;try{const $=f?f.clock():0;await Kt(d,u),f&&f.lap("redact",$)}catch($){return d.linkTurn?.end("error",{code:"tool_result"}),Le(d.id),f?.commit(),a(t,502,{error:{message:`tool-result: ${$.message}`,type:"bridge_error"}})}const y=ct("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(y.sseHead()),Mo(t,d,y,f)}function Et(){let t=!1;const d={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const m of Object.keys(d))d[m]+=Math.max(0,Number(u?.[m])||0)},get value(){return t?d:null}}}async function as(t,d,{kind:u,adapter:m,redactable:f,pathname:y,agentOverride:$,harness:N,trace:O,run:v=null,owner:x=null,link:C=null},J,H,E,G){if(!f)return O?.commit(),a(d,404,{error:`endpoint ${y} not supported by the bridge backend`});if(u==="openai"){const k=m.extractLatestToolResult(J);if(k){const ne=Qt(k.tool_call_id),he=ne&&Wt(ne.gwId);if(he)return ns(d,he,k.content,J?.model,O)}const re=m.extractTools(J);if((re.length||x)&&J?.stream===!0){const ne=$||No(J?.model,E),he=C?vt.begin({...C,agentId:ne}):null;return rs(t,d,{kind:u,adapter:m,agent:ne,run:v,owner:x,linkTurn:he},J,H,E,G,re,N,O)}}const{messages:z,system:oe}=m.toTurn(J),q=$||No(J?.model,E),K=C?vt.begin({...C,agentId:q}):null,ce=J?.stream===!0,Q=ct(u,J?.model||q),F=je(E.bridge.token),I=new AbortController;d.on("close",()=>{d.writableFinished||I.abort()});const{agentModel:n}=xt(J?.model,E),o={bridgeUrl:await Re(E),agent:q,token:F,messages:z,system:oe,signal:I.signal,options:vo(E,{...n?{model:n}:{},...v||{}})};if(!ce)try{let k="";const re=Et(),ne=O?O.clock():0;await Vt(o,we=>{k+=we},null,we=>re.add(we)),O&&O.lap("upstream",ne);const he=O?O.clock():0,He=Q.full(Ko(k,H),re.value);return O&&O.lap("restore",he),d.writeHead(200,{"content-type":Q.contentType}),d.end(He),K?.add(re.value),K?.end("ok"),O?.commit()}catch(k){return K?.end(I.signal.aborted?"aborted":"error",{code:"bridge_error"}),O?.commit(),a(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(Q.sseHead());const g=Lt(H),l=O?O.clock():0;let fe=l;const W=Et();let ge="",ue=!1;try{let k=!0;await Vt(o,ne=>{O&&k&&(O.lap("upstream",l),fe=O.clock(),k=!1);const he=g.push(ne);he&&(ge+=he,d.write(Q.sseDelta(he)))},Q.sseActivity?ne=>{try{d.write(Q.sseActivity(Wo(ne,H)))}catch{}}:null,ne=>W.add(ne));const re=g.flush();re&&(ge+=re,d.write(Q.sseDelta(re))),d.write(Q.sseTail(W.value))}catch(k){ue=!0,d.write(`data: ${JSON.stringify({error:{message:k.message,type:"bridge_error"}})}
19
19
 
20
- `)}O&&O.lap("stream",g),d.end(),O?.commit(),z&&le&&It(le,j.redaction)}function Ya(t,d,u=""){const m=String(t||"").replace(/\/+$/,""),f=String(d||"").split("/")[1];return f&&m.endsWith(`/${f}`)?m.slice(0,-(f.length+1))+d+u:m+d+u}const Za=9e4;function Xa(t,d,u){if(d===u)return t;const m=d/u,f=new Float32Array(Math.floor(t.length/m));for(let y=0;y<f.length;y++){const E=y*m,A=Math.floor(E),O=Math.min(t.length-1,A+1),k=E-A;f[y]=t[A]*(1-k)+t[O]*k}return f}const Bo=new WeakMap,qa=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function xt(t,{installing:d=!1}={}){return t.stt?.diarize===!1?"off":d&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ye(t,d,u,m,{method:f="GET",timeoutMs:y=8e3,pick:E=A=>A}={}){const A=await Ie(u);if(!A)return a(d,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const O=Re(u.bridge?.token),k=f!=="GET"&&f!=="DELETE";try{const _=k?(await S(t,u.maxBodyBytes)).toString("utf8"):"",D=await fetch(`${A}${m}`,{method:f,headers:{Accept:"application/json",...k?{"content-type":"application/json"}:{},...O?{Authorization:`Bearer ${O}`}:{}},...k?{body:_||"{}"}:{},signal:AbortSignal.timeout(y)}),z=await D.json().catch(()=>({}));return D.ok?a(d,200,E(z)):a(d,D.status,{error:{message:z?.error||`bridge ${D.status}`,type:"bridge_error"}})}catch(_){return a(d,502,{error:{message:`bridge unreachable: ${_.message}`,type:"bridge_unreachable"}})}}function _t(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Ae(t,d){const u=new URLSearchParams;for(const y of t.searchParams.getAll("dir"))y&&u.append("dir",y);const m=t.searchParams.get("workdir")||String(d?.bridge?.workingDir||"").trim();m&&u.set("workdir",m);const f=u.toString();return f?`?${f}`:""}async function es(t,d,{adapter:u,kind:m,pathname:f,search:y,base:E,destKey:A,destProtocol:O,harness:k,trace:_},D,z){let j;const $=_?_.clock():0;try{const V=Fa(t.headers,E);A&&(O==="anthropic"?(V["x-api-key"]=A,delete V.authorization):V.authorization=`Bearer ${A}`);const G=Qo(Ya(E,f,y)).toString();j=await fetch(G,{method:t.method,headers:V,body:["GET","HEAD"].includes(t.method)?void 0:D})}catch(V){return _?.commit(),a(d,502,{error:`upstream fetch failed: ${V.message}`})}const U=j.headers.get("content-type")||"",K={};if(j.headers.forEach((V,G)=>{_o.has(G.toLowerCase())||(K[G]=V)}),U.includes("text/event-stream")&&j.body){_&&_.lap("upstream",$);const V=_?_.clock():0;d.writeHead(j.status,K);const G=m==="openai"?zo(j.body,d,z,k):Jo(j.body,d,z);return Promise.resolve(G).finally(()=>{_&&_.lap("stream",V),_?.commit()})}const X=Buffer.from(await j.arrayBuffer());if(_&&_.lap("upstream",$),z&&U.includes("application/json"))try{const V=_?_.clock():0,G=u.restoreResponse(JSON.parse(X.toString("utf8")),z,k);return _&&_.lap("restore",V),d.writeHead(j.status,{...K,"content-type":"application/json"}),d.end(Buffer.from(JSON.stringify(G),"utf8")),_?.commit()}catch{}d.writeHead(j.status,K),d.end(X),_?.commit()}function ts(t=Ct()){const d=or({first:async n=>{const o=Number(new URL(n).port),g=Sn.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return g&&(await z())(g.id)==="up"?{engine:g.id,label:g.label,models:null}:null}}),u=er({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):tr(n),newId:()=>rr()}),m=An({version:ne}),f=Un({log:n=>console.log(` ${n}`)}),y=t.link?.enabled===!1?null:Nn({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:g,body:i,device:le})=>fetch(`http://127.0.0.1:${de.address()?.port||t.port}${o}`,{method:n,body:i,headers:{...g,"x-chatpanel-token":Me()||Te(),"x-chatpanel-link-device":String(le||"")}}),ownerIsPro:()=>ge(t.pro?.entitlementToken),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==M.activeModel()&&(no(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 ${Zn}`));let E=null;const A=()=>{if(!E){const n=t.read||{};E=Pn({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return E};let O=null;const k=()=>(O||(O=wn({wrap:(n,o,g,i)=>bn().wrap(n,o,g,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),O);let _={at:0,fn:()=>"unknown"},D=null;async function z(){if(Date.now()-_.at<1e4)return _.fn;let n=new Map;try{const i=await $().health();for(const[le,J]of Object.entries(i)){const q=(t.destinations||[]).filter(F=>F?.service===le).flatMap(F=>[F.id,...F.models||[]]);for(const F of[le,...q])n.set(F,J)}}catch{n=new Map}const o=i=>n.get(i)||"unknown",g=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return $().contextWindow(g.get(i)||i)}catch{return null}},o.card=i=>{try{return $().modelCard(g.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),_={at:Date.now(),fn:o},_.fn}let j=null;const $=()=>(j||(j=vn({cfg:t,bridgeHealth:async()=>{const n=await Ie(t);if(!n)return null;const o=Re(t.bridge?.token),g=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return g.ok?g.json():null},persist:()=>{try{he(t,re())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Le.join(Le.dirname(re()),"runtime"),workers:()=>{const n=O?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),j),U=Number(t.runtime?.idleMinutes),K=xn({warmMs:(Number.isFinite(U)&&U>=0?U:10)*6e4,log:n=>console.log(n)}),X=Tn({cfg:t,wake:(n,o)=>$().wake(n,o),embedded:K}),V=()=>{t.search?.searxng?.url&&$().wake("searxng").catch(()=>{})};let G=null;const be=()=>{if(!G){const n=t.search||{},o=n.searxng?.url?Wn({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;G=Hn({reader:A(),searxng:o,engines:()=>Kn(t),wakeSearxng:()=>$().wake("searxng"),defaultProvider:n.provider||"auto",redact:async g=>{let i=g;return await Ve([st(()=>i,le=>{i=le})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return G};Zo(t.allowedExtensionIds||[]);const fe=[],ue=n=>{fe.push(n),fe.length>50&&fe.shift()},de=Ro(async(n,o)=>{const g=new URL(n.url,"http://127.0.0.1"),i=g.pathname;if(!ot(n.headers.host))return a(o,403,{error:"loopback only"});if(!Ra(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(ot(t.host)&&Mn(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&&ja(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return H(n)?a(o,200,{token:Te()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!H(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Xo();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=qo(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${De(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${De(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:l}=await Ht(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()||Te(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&n.method==="POST"){const e=De(n);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(jt(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let r=null;try{r=JSON.parse((await 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 Ht(t);return a(o,200,{ok:!0,status:r,token:Me()||Te(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=De(n);return a(o,200,{ok:!0,trust:e,paired:jt(e),version:ne})}if(i==="/audit"&&n.method==="GET")return H(n)?a(o,200,ar(t,{version:ne,startedAt:Oo,managed:Ce(),certificates:{...ir(),wanted:Lt(t)},linkPartners:y?y.status().devices.filter(e=>e.kind==="partner"):[],confined:ct({stateDir:Le.dirname(re())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!H(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await Qr(ne,{force:g.searchParams.get("force")==="1"}).catch(r=>({current:ne,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:Xr()})}if(i==="/update"&&n.method==="POST"){const e=Zr(ne);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!H(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!H(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!H(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!H(n))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!H(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!H(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!H(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!H(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!H(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${ne} is running.
20
+ `)}O&&O.lap("stream",fe),d.end(),K&&(K.add(W.value),K.end(I.signal.aborted?"aborted":ue?"error":"ok",{code:"bridge_error"})),O?.commit(),H&&ge&&jt(ge,E.redaction)}function ss(t,d,u=""){const m=String(t||"").replace(/\/+$/,""),f=String(d||"").split("/")[1];return f&&m.endsWith(`/${f}`)?m.slice(0,-(f.length+1))+d+u:m+d+u}const is=9e4;function ls(t,d,u){if(d===u)return t;const m=d/u,f=new Float32Array(Math.floor(t.length/m));for(let y=0;y<f.length;y++){const $=y*m,N=Math.floor($),O=Math.min(t.length-1,N+1),v=$-N;f[y]=t[N]*(1-v)+t[O]*v}return f}const Co=new WeakMap,ds=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function $t(t,{installing:d=!1}={}){return t.stt?.diarize===!1?"off":d&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ve(t,d,u,m,{method:f="GET",timeoutMs:y=8e3,pick:$=N=>N}={}){const N=await Re(u);if(!N)return a(d,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const O=je(u.bridge?.token),v=f!=="GET"&&f!=="DELETE";try{const x=v?(await T(t,u.maxBodyBytes)).toString("utf8"):"",C=await fetch(`${N}${m}`,{method:f,headers:{Accept:"application/json",...v?{"content-type":"application/json"}:{},...O?{Authorization:`Bearer ${O}`}:{}},...v?{body:x||"{}"}:{},signal:AbortSignal.timeout(y)}),J=await C.json().catch(()=>({}));return C.ok?a(d,200,$(J)):a(d,C.status,{error:{message:J?.error||`bridge ${C.status}`,type:"bridge_error"}})}catch(x){return a(d,502,{error:{message:`bridge unreachable: ${x.message}`,type:"bridge_unreachable"}})}}function Pt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Be(t,d){const u=new URLSearchParams;for(const y of t.searchParams.getAll("dir"))y&&u.append("dir",y);const m=t.searchParams.get("workdir")||String(d?.bridge?.workingDir||"").trim();m&&u.set("workdir",m);const f=u.toString();return f?`?${f}`:""}async function cs(t,d,{adapter:u,kind:m,pathname:f,search:y,base:$,destKey:N,destProtocol:O,harness:v,trace:x,link:C=null},J,H){let E;const G=x?x.clock():0,z=C?vt.begin(C):null;let oe=!1;z&&d.on("close",()=>{d.writableFinished||(oe=!0)});const q=(F,I)=>{z&&(z.add(I),z.end(oe?"aborted":F>=400?"error":"ok",{code:`http_${F}`}))};try{const F=os(t.headers,$);N&&(O==="anthropic"?(F["x-api-key"]=N,delete F.authorization):F.authorization=`Bearer ${N}`);const I=er(ss($,f,y)).toString();E=await fetch(I,{method:t.method,headers:F,body:["GET","HEAD"].includes(t.method)?void 0:J})}catch(F){return z?.end("error",{code:"upstream_unreachable"}),x?.commit(),a(d,502,{error:`upstream fetch failed: ${F.message}`})}const K=E.headers.get("content-type")||"",ce={};if(E.headers.forEach((F,I)=>{$o.has(I.toLowerCase())||(ce[I]=F)}),K.includes("text/event-stream")&&E.body){x&&x.lap("upstream",G);const F=x?x.clock():0;d.writeHead(E.status,ce);const I=z?pn():null,n=I?E.body.pipeThrough(I.stream):E.body,o=m==="openai"?Fo(n,d,H,v):Vo(n,d,H);return Promise.resolve(o).finally(()=>{x&&x.lap("stream",F),q(E.status,I?.usage()),x?.commit()})}const Q=Buffer.from(await E.arrayBuffer());if(x&&x.lap("upstream",G),z&&q(E.status,K.includes("json")?hn(Q.toString("utf8")):null),H&&K.includes("application/json"))try{const F=x?x.clock():0,I=u.restoreResponse(JSON.parse(Q.toString("utf8")),H,v);return x&&x.lap("restore",F),d.writeHead(E.status,{...ce,"content-type":"application/json"}),d.end(Buffer.from(JSON.stringify(I),"utf8")),x?.commit()}catch{}d.writeHead(E.status,ce),d.end(Q),x?.commit()}function us(t=Rt()){const d=ir({first:async n=>{const o=Number(new URL(n).port),g=Bn.find(l=>l.port===o&&(l.provides||[]).includes("chat"));return g&&(await J())(g.id)==="up"?{engine:g.id,label:g.label,models:null}:null}}),u=ar({confirm:n=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(n):sr(n),newId:()=>lr()}),m=Jn({version:le}),f=qn({log:n=>console.log(` ${n}`)}),y=t.link?.enabled===!1?null:zn({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:g,body:l,device:fe})=>fetch(`http://127.0.0.1:${I.address()?.port||t.port}${o}`,{method:n,body:l,headers:{...g,"x-chatpanel-token":Me()||_e(),"x-chatpanel-link-device":String(fe||"")}}),ownerIsPro:()=>Se(t.pro?.entitlementToken),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==D.activeModel()&&(io(t.stt.diarizeModel)?D.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${ia}`));let $=null;const N=()=>{if(!$){const n=t.read||{};$=Ln({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return $};let O=null;const v=()=>(O||(O=$n({wrap:(n,o,g,l)=>Pn().wrap(n,o,g,l),onLog:n=>console.warn(`[extract worker] ${n}`)})),O);let x={at:0,fn:()=>"unknown"},C=null;async function J(){if(Date.now()-x.at<1e4)return x.fn;let n=new Map;try{const l=await E().health();for(const[fe,W]of Object.entries(l)){const ge=(t.destinations||[]).filter(ue=>ue?.service===fe).flatMap(ue=>[ue.id,...ue.models||[]]);for(const ue of[fe,...ge])n.set(ue,W)}}catch{n=new Map}const o=l=>n.get(l)||"unknown",g=new Map((t.destinations||[]).filter(l=>l?.service).map(l=>[l.id,l.service]));return o.window=l=>{try{return E().contextWindow(g.get(l)||l)}catch{return null}},o.card=l=>{try{return E().modelCard(g.get(l)||l)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),x={at:Date.now(),fn:o},x.fn}let H=null;const E=()=>(H||(H=Nn({cfg:t,bridgeHealth:async()=>{const n=await Re(t);if(!n)return null;const o=je(t.bridge?.token),g=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return g.ok?g.json():null},persist:()=>{try{ke(t,ie())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Je.join(Je.dirname(ie()),"runtime"),workers:()=>{const n=O?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),H),G=Number(t.runtime?.idleMinutes),z=Mn({warmMs:(Number.isFinite(G)&&G>=0?G:10)*6e4,log:n=>console.log(n)}),oe=Dn({cfg:t,wake:(n,o)=>E().wake(n,o),embedded:z}),q=()=>{t.search?.searxng?.url&&E().wake("searxng").catch(()=>{})};let K=null;const ce=()=>{if(!K){const n=t.search||{},o=n.searxng?.url?ra({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;K=ea({reader:N(),searxng:o,engines:()=>na(t),wakeSearxng:()=>E().wake("searxng"),defaultProvider:n.provider||"auto",redact:async g=>{let l=g;return await Ke([dt(()=>l,fe=>{l=fe})],{...t.redaction,tier:"basic"},{isPro:!0}),l}})}return K};or(t.allowedExtensionIds||[]);const Q=[],F=n=>{Q.push(n),Q.length>50&&Q.shift()},I=Go(async(n,o)=>{const g=new URL(n.url,"http://127.0.0.1"),l=g.pathname;if(!at(n.headers.host))return a(o,403,{error:"loopback only"});if(!Wa(n.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(at(t.host)&&Hn(n.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(n.headers.origin&&Ka(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(l==="/admin/token"&&n.method==="POST")return U(n)?a(o,200,{token:_e()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(l==="/pair/code"&&n.method==="POST"){if(!U(n))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=rr();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(l==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=nr(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Ce(n)} caller`),a(o,403,{error:r.reason});console.log(`[gateway] paired a ${Ce(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:s,refused:i}=await Ft(t);return i&&console.log(`[gateway] pairing: the bridge at ${i.url}${i.version?` (v${i.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Me()||_e(),...s?{bridgeToken:s}:{},...i?{bridgeRefused:i}:{}})}if(l==="/pair/ask"&&n.method==="POST"){const e=Ce(n);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(Jt(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let r=null;try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r=null}const s=u.ask({browser:r?.browser,who:n.headers.origin||""});if(!s.ok){const i=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:i,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${n.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(l==="/pair/ask/result"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:r}=u.result(e?.id,{who:n.headers.origin||""});if(r!=="allowed")return a(o,200,{ok:!0,status:r});console.log(`[gateway] paired ${n.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:i}=await Ft(t);return a(o,200,{ok:!0,status:r,token:Me()||_e(),...s?{bridgeToken:s}:{},...i?{bridgeRefused:i}:{}})}if(l==="/whoami"&&n.method==="POST"){const e=Ce(n);return a(o,200,{ok:!0,trust:e,paired:Jt(e),version:le})}if(l==="/audit"&&n.method==="GET")return U(n)?a(o,200,cr(t,{version:le,startedAt:Po,managed:Ie(),certificates:{...mr(),wanted:zt(t)},linkPartners:y?y.status().devices.filter(e=>e.kind==="partner"):[],confined:pt({stateDir:Je.dirname(ie())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((l==="/config"||l==="/logs"||l==="/update"&&n.method!=="GET")&&!U(n))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(l==="/update"&&n.method==="GET"){const e=await en(le,{force:g.searchParams.get("force")==="1"}).catch(r=>({current:le,updateAvailable:!1,error:String(r?.message||r)}));return a(o,200,{ok:!0,update:e,job:rn()})}if(l==="/update"&&n.method==="POST"){const e=on(le);return a(o,e.already?409:202,{ok:!0,job:e})}if((l==="/v1/history/key"||l==="/v1/history/ingest-backup")&&n.method==="POST"&&!U(n))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(l==="/v1/history/records"&&n.method==="PUT"&&!U(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/history/ingest"||l==="/v1/history/clear")&&n.method==="POST"&&!U(n))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/memory/remember"||l==="/v1/memory/forget"||l==="/v1/memory/sync"||l==="/v1/memory/clear")&&n.method==="POST"&&!U(n))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/prefs"||l.startsWith("/v1/prefs/")||l.startsWith("/v1/teams")||l.startsWith("/v1/agents")||l.startsWith("/v1/projects"))&&!U(n))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/browser"||l.startsWith("/v1/browser/"))&&!U(n))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/link"||l.startsWith("/v1/link/"))&&!U(n))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/events"||l.startsWith("/v1/events/"))&&!U(n))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(l.startsWith("/v1/observability")&&!U(n))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&l==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${le} is running.
21
21
 
22
22
  This address is for ChatPanel's apps, not a web page — there is nothing to open here.
23
23
  Use ChatPanel itself (the browser extension's Settings, or the desktop app).
24
24
  In a terminal, \`chatpanel-gateway --status\` shows what is running.
25
- `);if(n.method==="GET"&&i==="/health"){const e=B.health(),r=C.health();return a(o,200,{ok:!0,version:ne,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...Ce()?{managed:Ce()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},install:qr(),confined:ct({stateDir:Le.dirname(re())}),...tn({release:pt.release()})?{appleHelper:!!on()}:{},...ze?{bridge:ze.status()}:rt?{bridge:rt}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Ze,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||po,voice:t.tts?.voice||ve,runtime:r.runtime,dtype:r.dtype},events:Z?{count:Z.count(),hosts:Z.hosts().length}:null,browser:m.health()})}if(i==="/status"&&n.method==="GET"){Lo(t);const e=await ge(t.pro?.entitlementToken),r=await Ao(t);return a(o,200,{ok:!0,version:ne,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Ce()?{managed:Ce()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:r.configured,ready:r.ok,model:r.model,url:r.url},detector:vt(t),pro:{unlocked:e},usage:ba(t),uptimeSeconds:Math.floor((Date.now()-Oo)/1e3),update:Yr(ne)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=R.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:r})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&n.method==="GET"){const e=String(g.searchParams.get("section")||"");return g.searchParams.get("stamps")?a(o,200,{ok:!0,revision:ae.revision,stamps:ae.stamps()}):a(o,200,{ok:!0,revision:ae.revision,sections:ae.get(e)})}if(i==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=ae.put(e.sections||{},{by:e.by||""});return r.applied.length&&vo(r.applied,e.by||""),a(o,200,{ok:!0,...r})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(i==="/v1/prefs"&&n.method==="DELETE"){const e=String(g.searchParams.get("section")||""),r=e?ae.remove(e):!1;return r&&vo([e],""),a(o,200,{ok:!0,removed:r})}if(i==="/v1/prefs/events"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
25
+ `);if(n.method==="GET"&&l==="/health"){const e=B.health(),r=M.health();return a(o,200,{ok:!0,version:le,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...Ie()?{managed:Ie()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},install:nn(),confined:pt({stateDir:Je.dirname(ie())}),...sn({release:ft.release()})?{appleHelper:!!ln()}:{},...Ge?{bridge:Ge.status()}:st?{bridge:st}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||et,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||fo,voice:t.tts?.voice||xe,runtime:r.runtime,dtype:r.dtype},events:Z?{count:Z.count(),hosts:Z.hosts().length}:null,browser:m.health()})}if(l==="/status"&&n.method==="GET"){Uo(t);const e=await Se(t.pro?.entitlementToken),r=await Do(t);return a(o,200,{ok:!0,version:le,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Ie()?{managed:Ie()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:r.configured,ready:r.ok,model:r.model,url:r.url},detector:_t(t),pro:{unlocked:e},usage:Pa(t),uptimeSeconds:Math.floor((Date.now()-Po)/1e3),update:tn(le)})}if(l==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=j.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:r})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(l==="/v1/prefs"&&n.method==="GET"){const e=String(g.searchParams.get("section")||"");return g.searchParams.get("stamps")?a(o,200,{ok:!0,revision:de.revision,stamps:de.stamps()}):a(o,200,{ok:!0,revision:de.revision,sections:de.get(e)})}if(l==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=de.put(e.sections||{},{by:e.by||""});return r.applied.length&&xo(r.applied,e.by||""),a(o,200,{ok:!0,...r})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(l==="/v1/prefs"&&n.method==="DELETE"){const e=String(g.searchParams.get("section")||""),r=e?de.remove(e):!1;return r&&xo([e],""),a(o,200,{ok:!0,removed:r})}if(l==="/v1/prefs/events"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=i=>o.write(`data: ${JSON.stringify(i)}
26
26
 
27
- `);e({type:"hello",revision:ae.revision,stamps:ae.stamps()});const r=l=>e({type:"changed",...l});wt.add(r);const s=setInterval(()=>{try{o.write(`: keep-alive
27
+ `);e({type:"hello",revision:de.revision,stamps:de.stamps()});const r=i=>e({type:"changed",...i});St.add(r);const s=setInterval(()=>{try{o.write(`: keep-alive
28
28
 
29
- `)}catch{}},25e3);o.on("close",()=>{wt.delete(r),clearInterval(s)});return}if(i==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:ie.list({limit:g.searchParams.get("limit")||50,status:g.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&n.method==="GET")return a(o,200,{ok:!0,jobs:ie.openJobs()});if(i==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:ie.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return a(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(i);if(e){const r=e[1],s=e[2]||"",l=e[3]||"",c=e[4]||"",h=()=>a(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(c){const p=ie.get(r);if(!p)return h();const v=p.jobs.find(b=>b.id===l);if(!v)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const w={cfg:t,prefsStore:ae,scorecards:$e,engines:Pe,engineAt:d.engineAt};if(c==="/applications"&&n.method==="GET"){const b=await Vr(v,{...w,reach:g.searchParams.get("reach")||"any",chatModel:g.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:v,...b})}if(c==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(v.status))return a(o,400,{error:{message:`job ${l} is ${v.status}; only an open job is recruited`,type:"project_error"}});try{const b=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},P=String(b.by||"evaluator").slice(0,80),x=await Fr(v,{...w,record:p,reach:b.reach||"any",chatModel:b.chatModel||null,evaluation:b.evaluation||null,text:b.text??null,by:P});let L=null;for(const oe of x.events)oe.type==="job.updated"?L=ie.updateJob(r,l,oe.job,{by:oe.by||P}):L=ie.append(r,[oe]);return a(o,200,{ok:!0,project:L,decision:x.decision,applications:x.applications,evaluation:x.evaluation})}catch(b){return a(o,400,{error:{message:`recruit: ${b.message}`,type:"project_error"}})}}return a(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!s&&n.method==="GET"){const p=ie.get(r,{events:g.searchParams.get("events")==="1"});return p?a(o,200,{ok:!0,project:p}):h()}if(!s&&n.method==="DELETE")return a(o,200,{ok:!0,removed:ie.remove(r)});if(n.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const p=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},v=String(p.by||"person").slice(0,80),w=s==="/events"?ie.append(r,p.events||[]):l?ie.updateJob(r,l,p.patch||p,{by:v}):ie.postJob(r,p.job||p,{by:v});return a(o,200,{ok:!0,project:w})}catch(p){return a(o,p.message.startsWith("no ")?404:400,{error:{message:`project: ${p.message}`,type:"project_error"}})}if(s==="/events"&&n.method==="GET"){if(!ie.get(r))return h();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const p=P=>o.write(`data: ${JSON.stringify(P)}
29
+ `)}catch{}},25e3);o.on("close",()=>{St.delete(r),clearInterval(s)});return}if(l==="/v1/projects"&&n.method==="GET")return a(o,200,{ok:!0,projects:pe.list({limit:g.searchParams.get("limit")||50,status:g.searchParams.get("status")||""})});if(l==="/v1/projects/jobs"&&n.method==="GET")return a(o,200,{ok:!0,jobs:pe.openJobs()});if(l==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:pe.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return a(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(l);if(e){const r=e[1],s=e[2]||"",i=e[3]||"",c=e[4]||"",p=()=>a(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(c){const h=pe.get(r);if(!h)return p();const S=h.jobs.find(b=>b.id===i);if(!S)return a(o,404,{error:{message:`no job ${i}`,type:"not_found"}});const w={cfg:t,prefsStore:de,scorecards:Ae,engines:Ne,engineAt:d.engineAt};if(c==="/applications"&&n.method==="GET"){const b=await Yr(S,{...w,reach:g.searchParams.get("reach")||"any",chatModel:g.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:S,...b})}if(c==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(S.status))return a(o,400,{error:{message:`job ${i} is ${S.status}; only an open job is recruited`,type:"project_error"}});try{const b=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},A=String(b.by||"evaluator").slice(0,80),_=await Zr(S,{...w,record:h,reach:b.reach||"any",chatModel:b.chatModel||null,evaluation:b.evaluation||null,text:b.text??null,by:A});let L=null;for(const se of _.events)se.type==="job.updated"?L=pe.updateJob(r,i,se.job,{by:se.by||A}):L=pe.append(r,[se]);return a(o,200,{ok:!0,project:L,decision:_.decision,applications:_.applications,evaluation:_.evaluation})}catch(b){return a(o,400,{error:{message:`recruit: ${b.message}`,type:"project_error"}})}}return a(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!s&&n.method==="GET"){const h=pe.get(r,{events:g.searchParams.get("events")==="1"});return h?a(o,200,{ok:!0,project:h}):p()}if(!s&&n.method==="DELETE")return a(o,200,{ok:!0,removed:pe.remove(r)});if(n.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const h=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},S=String(h.by||"person").slice(0,80),w=s==="/events"?pe.append(r,h.events||[]):i?pe.updateJob(r,i,h.patch||h,{by:S}):pe.postJob(r,h.job||h,{by:S});return a(o,200,{ok:!0,project:w})}catch(h){return a(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(s==="/events"&&n.method==="GET"){if(!pe.get(r))return p();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=A=>o.write(`data: ${JSON.stringify(A)}
30
30
 
31
- `);let v=g.searchParams.has("after")?Number(g.searchParams.get("after")):-1;p({seq:-1,type:"hello",at:Date.now(),payload:{project:ie.get(r),after:v}});const w=ie.watch(r,P=>{P.seq>v&&(v=P.seq,p(P))});for(const P of ie.eventsSince(r,v))v=P.seq,p(P);const b=setInterval(()=>{try{o.write(`: keep
31
+ `);let S=g.searchParams.has("after")?Number(g.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:pe.get(r),after:S}});const w=pe.watch(r,A=>{A.seq>S&&(S=A.seq,h(A))});for(const A of pe.eventsSince(r,S))S=A.seq,h(A);const b=setInterval(()=>{try{o.write(`: keep
32
32
 
33
- `)}catch{}},25e3);n.on("close",()=>{clearInterval(b),w()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:$e.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return a(o,200,{ok:!0,...await $e.get(r)});if(n.method==="POST")try{const s=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},l=await $e.append({agentId:r,kind:"rating",runId:s.runId,taskId:s.taskId,jobId:s.jobId,rating:{by:String(s.by||"person").slice(0,40),score:s.score,note:s.note,about:s.about},refs:s.refs});return Pe.fromRating($e.chains.get(r)||[],{...l,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:l})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&n.method==="GET")return a(o,200,fn(t,{version:ne,reader:E,searcher:G,extract:k(),proxy:X}));if(i==="/v1/fusions"&&n.method==="GET"){const e={active:I.health().model||t.ner?.model||null,companions:I.companions()};let r=null;try{r=await $().status()}catch{r=null}return a(o,200,dn({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(On.map(r=>{const s=ht(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:_n[r],threads:K.threads,...s.kind==="embedded"?K.health(r,s.model):{}}]}));return a(o,200,{...await $().status(),inProcess:e})}if(i==="/v1/runtime/plan"&&n.method==="GET"){const e=new URL(n.url,"http://x").searchParams,r=await $().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,r.ok?200:400,r)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&n.method==="POST"){if(!H(n))return a(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const s=String(r.action||"start"),l=$(),c=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:r.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],r.model):s==="tune"?await l.setTunings(e[2],r.tunings):s==="profile"?await l.setProfile(e[2],r.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="cancel"?l.cancelJob(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,c.ok?200:400,c)}}if((i==="/v1/rerank"||i==="/v1/decide")&&n.method==="POST"){const e=i.slice(4);let r;try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await X.call(e,r);return a(o,s.status,s.body)}if(i==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await gn(e,{ensure:()=>Ye(t),model:I.health().model});return a(o,r.status,r.body)}catch(r){return a(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,Math.max(t.maxBodyBytes,Math.ceil($n*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await En(e,{service:k()});return a(o,r.status,r.body)}if(i==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await A().read(e);return a(o,r.status,r.body)}if(i==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}V();const r=await be().search(e);return a(o,r.status,r.body)}if(/^\/v1\/search\/./.test(i)&&n.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const r=g.searchParams.has("read")?Math.max(0,Math.min(10,Number(g.searchParams.get("read"))||0)):Fn.aliasRead;V();const s=await be().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?Vn(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(n.headers.accept||""),l=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",c=await A().read({url:r,format:l});return c.status!==200||s?a(o,c.status,c.status===200?{code:200,status:2e4,data:c.body}:c.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":c.body.provider}),o.end(Qn(c.body)))}if(i==="/v1/engines"&&n.method==="GET"){const e=Number(g.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:Pe.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const s=Number(g.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await Pe.get(r,{entries:g.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&n.method==="POST")try{const s=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||Ja(r);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const c=await Pe.append({...s,engine:l,kind:s.kind||"call"});return c.key!==r?a(o,400,{error:{message:`model-ledger: entry is for ${c.key}, not ${r}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:c})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
33
+ `)}catch{}},25e3);n.on("close",()=>{clearInterval(b),w()});return}}}if(l==="/v1/agents/scorecards"&&n.method==="GET")return a(o,200,{ok:!0,agents:Ae.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(l);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return a(o,200,{ok:!0,...await Ae.get(r)});if(n.method==="POST")try{const s=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},i=await Ae.append({agentId:r,kind:"rating",runId:s.runId,taskId:s.taskId,jobId:s.jobId,rating:{by:String(s.by||"person").slice(0,40),score:s.score,note:s.note,about:s.about},refs:s.refs});return Ne.fromRating(Ae.chains.get(r)||[],{...i,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:i})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(l==="/v1/capabilities"&&n.method==="GET")return a(o,200,On(t,{version:le,reader:$,searcher:K,extract:v(),proxy:oe}));if(l==="/v1/fusions"&&n.method==="GET"){const e={active:R.health().model||t.ner?.model||null,companions:R.companions()};let r=null;try{r=await E().status()}catch{r=null}return a(o,200,bn({cfg:t,ner:e,runtimeDoc:r}))}if(l==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(In.map(r=>{const s=gt(t,r);return[r,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:Cn[r],threads:z.threads,...s.kind==="embedded"?z.health(r,s.model):{}}]}));return a(o,200,{...await E().status(),inProcess:e})}if(l==="/v1/runtime/plan"&&n.method==="GET"){const e=new URL(n.url,"http://x").searchParams,r=await E().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,r.ok?200:400,r)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(l);if(e&&n.method==="POST"){if(!U(n))return a(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const s=String(r.action||"start"),i=E(),c=e[1]==="engines"?s==="start"?await i.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await i.startService(e[2],{force:r.force===!0}):s==="stop"?await i.stopService(e[2]):s==="model"?await i.setModel(e[2],r.model):s==="tune"?await i.setTunings(e[2],r.tunings):s==="profile"?await i.setProfile(e[2],r.profile):s==="pull"?await i.pullModel(e[2]):s==="install"?await i.installRunner(e[2]):s==="cancel"?i.cancelJob(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,c.ok?200:400,c)}}if((l==="/v1/rerank"||l==="/v1/decide")&&n.method==="POST"){const e=l.slice(4);let r;try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await oe.call(e,r);return a(o,s.status,s.body)}if(l==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await En(e,{ensure:()=>qe(t),model:R.health().model});return a(o,r.status,r.body)}catch(r){return a(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(l==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,Math.max(t.maxBodyBytes,Math.ceil(jn*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Rn(e,{service:v()});return a(o,r.status,r.body)}if(l==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await N().read(e);return a(o,r.status,r.body)}if(l==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}q();const r=await ce().search(e);return a(o,r.status,r.body)}if(/^\/v1\/search\/./.test(l)&&n.method==="GET"){let e;try{e=decodeURIComponent(l.slice(11))}catch{e=l.slice(11)}const r=g.searchParams.has("read")?Math.max(0,Math.min(10,Number(g.searchParams.get("read"))||0)):oa.aliasRead;q();const s=await ce().search({q:e,read:r,limit:Math.max(r,5)});return a(o,s.status,s.status===200?ta(s.body):s.body)}if(/^\/v1\/read\/./.test(l)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(n.headers.accept||""),i=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",c=await N().read({url:r,format:i});return c.status!==200||s?a(o,c.status,c.status===200?{code:200,status:2e4,data:c.body}:c.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":c.body.provider}),o.end(aa(c.body)))}if(l==="/v1/engines"&&n.method==="GET"){const e=Number(g.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:Ne.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(l);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const s=Number(g.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await Ne.get(r,{entries:g.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&n.method==="POST")try{const s=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},i=s.engine||Ya(r);if(!i)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const c=await Ne.append({...s,engine:i,kind:s.kind||"call"});return c.key!==r?a(o,400,{error:{message:`model-ledger: entry is for ${c.key}, not ${r}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:c})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(l==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=i=>{try{o.write(`data: ${JSON.stringify(i)}
34
34
 
35
- `)}catch{}};e({type:"hello",at:Date.now()});const r=Y.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
35
+ `)}catch{}};e({type:"hello",at:Date.now()});const r=X.watchAll(i=>e({type:"run",id:i.id,removed:!!i.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
36
36
 
37
- `)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(i==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:Y.list({limit:g.searchParams.get("limit")||50,team:g.searchParams.get("team")||""})});if(i==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:Y.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return a(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(i);if(e){const r=e[1],s=e[2]||"";if(!s&&n.method==="GET"){const l=Y.get(r,{events:g.searchParams.get("events")==="1"});return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!s&&n.method==="DELETE")return Y.stop(r),a(o,200,{ok:!0,removed:Y.remove(r)});if(s==="/stop"&&n.method==="POST"){const l=Y.stop(r);return l?a(o,200,{ok:!0,run:l}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(s==="/checkpoint"&&n.method==="GET")try{return a(o,200,{ok:!0,checkpoint:Y.checkpoint(r)})}catch(l){return a(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/handoff"||s==="/claim")&&n.method==="POST")try{const l=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},c=s==="/handoff"?Y.handoff(r,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):Y.claim(r,{client:l.client});return a(o,200,{ok:!0,run:c})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s.startsWith("/threads/")&&n.method==="DELETE")try{return a(o,200,{ok:!0,run:Y.removeThread(r,{threadId:s.slice(9),by:"person"})})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((s==="/answer"||s==="/decide"||s==="/post")&&n.method==="POST")try{const l=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},c=String(l.by||"person").slice(0,40),h=s==="/answer"?Y.answer(r,{threadId:l.threadId,text:l.text,by:c}):s==="/decide"?Y.decide(r,{postId:l.postId,status:l.status,by:c}):Y.post(r,{threadId:l.threadId,text:l.text,by:c,kind:l.kind,replyTo:l.replyTo});return a(o,200,{ok:!0,run:h})}catch(l){return a(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="POST")try{const l=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:Y.append(r,l.events||[])})}catch(l){return a(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="GET"){if(!Y.get(r))return a(o,404,{error:{message:`no run ${r}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=w=>o.write(`data: ${JSON.stringify(w)}
37
+ `)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(s)});return}if(l==="/v1/teams/runs"&&n.method==="GET")return a(o,200,{ok:!0,runs:X.list({limit:g.searchParams.get("limit")||50,team:g.searchParams.get("team")||""})});if(l==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:X.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return a(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(l);if(e){const r=e[1],s=e[2]||"";if(!s&&n.method==="GET"){const i=X.get(r,{events:g.searchParams.get("events")==="1"});return i?a(o,200,{ok:!0,run:i}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!s&&n.method==="DELETE")return X.stop(r),a(o,200,{ok:!0,removed:X.remove(r)});if(s==="/stop"&&n.method==="POST"){const i=X.stop(r);return i?a(o,200,{ok:!0,run:i}):a(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(s==="/checkpoint"&&n.method==="GET")try{return a(o,200,{ok:!0,checkpoint:X.checkpoint(r)})}catch(i){return a(o,404,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((s==="/handoff"||s==="/claim")&&n.method==="POST")try{const i=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},c=s==="/handoff"?X.handoff(r,{taskId:i.taskId,model:i.model,by:i.by,reason:i.reason}):X.claim(r,{client:i.client});return a(o,200,{ok:!0,run:c})}catch(i){return a(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(s.startsWith("/threads/")&&n.method==="DELETE")try{return a(o,200,{ok:!0,run:X.removeThread(r,{threadId:s.slice(9),by:"person"})})}catch(i){return a(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((s==="/answer"||s==="/decide"||s==="/post")&&n.method==="POST")try{const i=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},c=String(i.by||"person").slice(0,40),p=s==="/answer"?X.answer(r,{threadId:i.threadId,text:i.text,by:c}):s==="/decide"?X.decide(r,{postId:i.postId,status:i.status,by:c}):X.post(r,{threadId:i.threadId,text:i.text,by:c,kind:i.kind,replyTo:i.replyTo});return a(o,200,{ok:!0,run:p})}catch(i){return a(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="POST")try{const i=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,run:X.append(r,i.events||[])})}catch(i){return a(o,i.message.startsWith("no run")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(s==="/events"&&n.method==="GET"){if(!X.get(r))return a(o,404,{error:{message:`no run ${r}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const i=w=>o.write(`data: ${JSON.stringify(w)}
38
38
 
39
- `),c=g.searchParams.has("after")?Number(g.searchParams.get("after")):NaN;let h=Number.isFinite(c)?c:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:Y.get(r),after:h}});const p=Y.watch(r,w=>{w.seq==null?l(w):w.seq>h&&(h=w.seq,l(w))});for(const w of Y.eventsSince(r,h))h=w.seq,l(w);const v=setInterval(()=>{try{o.write(`: keep-alive
39
+ `),c=g.searchParams.has("after")?Number(g.searchParams.get("after")):NaN;let p=Number.isFinite(c)?c:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:X.get(r),after:p}});const h=X.watch(r,w=>{w.seq==null?i(w):w.seq>p&&(p=w.seq,i(w))});for(const w of X.eventsSince(r,p))p=w.seq,i(w);const S=setInterval(()=>{try{o.write(`: keep-alive
40
40
 
41
- `)}catch{}},25e3);o.on("close",()=>{p(),clearInterval(v)});return}}}if(i==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:ce.size,memories:ce.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=ce.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:ce.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=ce.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:ce.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}=ce.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:ce.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=ce.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:ce.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:ce.clear(),size:ce.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=R.clear();return a(o,200,{ok:!0,dropped:e,size:R.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=R.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:R.size,newest:R.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),s=Aa(r,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},c=Math.min(30,Math.max(5,Number(e.limit)||10)*2),h=await Na(s,v=>R.search(v,{limit:c,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),p=l.type?h:[...h.filter(v=>v.type==="brief"),...h.filter(v=>v.type!=="brief")];return a(o,200,{ok:!0,size:R.size,newest:R.newest,queries:s,results:p})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const r=String(e.question||"").trim();if(!r)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!H(n))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${n.socket.localPort}`,c=s?async(w,{maxTokens:b=220}={})=>{const P=new AbortController,x=setTimeout(()=>P.abort(),3e4);try{const L=Me()||Te(),oe=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:P.signal,headers:{"content-type":"application/json",...L?{Authorization:`Bearer ${L}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:w}],stream:!1,max_tokens:b,temperature:.2})}),pe=await oe.json().catch(()=>({}));return oe.ok?String(pe?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(x)}}:null,h=ae.get("identity")?.identity?.value||{},p=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,v=await Lr(r,{store:R,memories:ce.list(),complete:c,previous:p,self:String(h.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,Jr(r,v,{size:R.size,newest:R.newest}))}if(i==="/v1/history/related"&&n.method==="GET"){const e=String(g.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(g.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:R.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:R.size,newest:R.newest,bytes:R.bytes,lossless:R.lossless?{records:R.lossless.size,newest:R.lossless.newest}:null});if(i==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(g.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:R.size,bytes:R.bytes,newest:R.newest}},access:bt.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{},r=bt.push(bo({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:r})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&n.method==="PUT"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await S(n,Math.max(t.maxBodyBytes||0,Va))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),c=[];let h=0,p={},v=[],w=[];const b={upserts:[],removes:[]},P=x=>{if(!x||x.deletedAt){x?.id&&b.removes.push(x.id);return}try{const L=eo(x);L&&b.upserts.push(L)}catch{}};if(Array.isArray(r.records)){const x=e.write(r.records,{host:s,at:l,merge:r.merge===!0});c.push(...x.written),p=x.revs,v=x.conflicts,w=x.merged;for(const L of x.written)P(e.get(L))}if(Array.isArray(r.entries)){const x=lt(),L=x?pn((Q,W)=>un(x,{salt:Q,iterations:W})):null,oe=async Q=>{if(!L||!Q.blob)return null;const W=await L(Q.blob),Be=Q.blob.compression&&Q.blob.compression!=="none"?hn(yn,Q.blob.compression):null;return mn(Q.blob,W,{codec:Be})},pe=await e.upsertEntries(r.entries,{open:oe});c.push(...pe.written),h+=pe.sealed;for(const Q of pe.written)P(e.get(Q))}return(b.upserts.length||b.removes.length)&&R.bulk(b),c.length&&Je({ids:c}),a(o,200,{ok:!0,written:c.length,ids:c,revs:p,conflicts:v,merged:w,sealed:h,size:e.size,rev:e.rev})}catch(r){return a(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&n.method==="POST"){if(!Z)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=an(Z,r);return a(o,200,{ok:!0,appended:s.appended,duplicates:s.duplicates,rejected:s.rejected,cursor:Z.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 Z?a(o,200,{ok:!0,cursor:Z.cursor(),count:Z.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&n.method==="GET"){if(!Z)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=sn(Z.all());return a(o,200,{ok:!0,stats:e,year:ln(e)})}if(i==="/v1/events"&&n.method==="GET"){if(!Z)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=qt(JSON.parse(g.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=Z.since(e,{limit:Number(g.searchParams.get("limit"))||void 0,host:g.searchParams.get("host")||null});return a(o,200,{ok:!0,events:r.events.map(s=>ut(s)),cursor:r.cursor,more:r.more})}if(i==="/v1/events/stream"&&n.method==="GET"){if(!Z)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(g.searchParams.has("cursor"))try{e=qt(JSON.parse(g.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
42
- data: ${JSON.stringify({cursor:Z.cursor(),count:Z.count(),version:ne})}
41
+ `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(S)});return}}}if(l==="/v1/memory/list"&&n.method==="GET")return a(o,200,{ok:!0,size:ye.size,memories:ye.list()});if(l==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=ye.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:ye.size,...r})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(l==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=ye.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:r.action,record:r.record,replaced:r.replaces||null,size:ye.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(l==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=ye.forget(String(e.query||""));return a(o,200,{ok:!0,removed:r,size:ye.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(l==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=ye.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...r,memories:ye.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(l==="/v1/memory/clear"&&n.method==="POST")return a(o,200,{ok:!0,dropped:ye.clear(),size:ye.size});if(l==="/v1/history/clear"&&n.method==="POST"){const e=j.clear();return a(o,200,{ok:!0,dropped:e,size:j.size})}if(l==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=j.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:j.size,newest:j.newest,results:r})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(l==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),s=Ja(r,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),i={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},c=Math.min(30,Math.max(5,Number(e.limit)||10)*2),p=await za(s,S=>j.search(S,{limit:c,...i}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=i.type?p:[...p.filter(S=>S.type==="brief"),...p.filter(S=>S.type!=="brief")];return a(o,200,{ok:!0,size:j.size,newest:j.newest,queries:s,results:h})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(l==="/v1/research"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const r=String(e.question||"").trim();if(!r)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!U(n))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const i=`http://127.0.0.1:${n.socket.localPort}`,c=s?async(w,{maxTokens:b=220}={})=>{const A=new AbortController,_=setTimeout(()=>A.abort(),3e4);try{const L=Me()||_e(),se=await fetch(`${i}/v1/chat/completions`,{method:"POST",signal:A.signal,headers:{"content-type":"application/json",...L?{Authorization:`Bearer ${L}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:w}],stream:!1,max_tokens:b,temperature:.2})}),be=await se.json().catch(()=>({}));return se.ok?String(be?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(_)}}:null,p=de.get("identity")?.identity?.value||{},h=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,S=await Ur(r,{store:j,memories:ye.list(),complete:c,previous:h,self:String(p.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,Vr(r,S,{size:j.size,newest:j.newest}))}if(l==="/v1/history/related"&&n.method==="GET"){const e=String(g.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(g.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:j.related(e,{limit:r})})}if(l==="/v1/history/status"&&n.method==="GET")return a(o,200,{ok:!0,size:j.size,newest:j.newest,bytes:j.bytes,lossless:j.lossless?{records:j.lossless.size,newest:j.lossless.newest}:null});if(l==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(g.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:j.size,bytes:j.bytes,newest:j.newest}},access:Tt.snapshot(e)})}if(l==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=Tt.push(So({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:r})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(l==="/v1/history/records"&&n.method==="PUT"){const e=j.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await T(n,Math.max(t.maxBodyBytes||0,ts))).toString("utf8"))||{},s=String(r.host||"").slice(0,80),i=Number(r.at)||Date.now(),c=[];let p=0,h={},S=[],w=[];const b={upserts:[],removes:[]},A=_=>{if(!_||_.deletedAt){_?.id&&b.removes.push(_.id);return}try{const L=ro(_);L&&b.upserts.push(L)}catch{}};if(Array.isArray(r.records)){const _=e.write(r.records,{host:s,at:i,merge:r.merge===!0});c.push(..._.written),h=_.revs,S=_.conflicts,w=_.merged;for(const L of _.written)A(e.get(L))}if(Array.isArray(r.entries)){const _=ut(),L=_?Tn((Y,V)=>vn(_,{salt:Y,iterations:V})):null,se=async Y=>{if(!L||!Y.blob)return null;const V=await L(Y.blob),De=Y.blob.compression&&Y.blob.compression!=="none"?xn(_n,Y.blob.compression):null;return Sn(Y.blob,V,{codec:De})},be=await e.upsertEntries(r.entries,{open:se});c.push(...be.written),p+=be.sealed;for(const Y of be.written)A(e.get(Y))}return(b.upserts.length||b.removes.length)&&j.bulk(b),c.length&&ze({ids:c}),a(o,200,{ok:!0,written:c.length,ids:c,revs:h,conflicts:S,merged:w,sealed:p,size:e.size,rev:e.rev})}catch(r){return a(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(l==="/v1/events"&&n.method==="POST"){if(!Z)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=Array.isArray(e)?e:e.events;if(!Array.isArray(r))return a(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(r.length>2e3)return a(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const s=p=>(typeof p?.host=="string"&&p.host?p.host:wn(p?.source))===to,i=r.filter(s).map(p=>({id:p?.id??null,code:"RESERVED_HOST",message:`host "${to}" is this gateway's own log`})),c=yn(Z,i.length?r.filter(p=>!s(p)):r);return a(o,200,{ok:!0,appended:c.appended,duplicates:c.duplicates,rejected:[...i,...c.rejected],cursor:Z.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(l==="/v1/events/cursor"&&n.method==="GET")return Z?a(o,200,{ok:!0,cursor:Z.cursor(),count:Z.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(l==="/v1/events/stats"&&n.method==="GET"){if(!Z)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=fn(Z.all());return a(o,200,{ok:!0,stats:e,year:gn(e)})}if(l==="/v1/events"&&n.method==="GET"){if(!Z)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=oo(JSON.parse(g.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=Z.since(e,{limit:Number(g.searchParams.get("limit"))||void 0,host:g.searchParams.get("host")||null});return a(o,200,{ok:!0,events:r.events.map(s=>ht(s)),cursor:r.cursor,more:r.more})}if(l==="/v1/events/stream"&&n.method==="GET"){if(!Z)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(g.searchParams.has("cursor"))try{e=oo(JSON.parse(g.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
42
+ data: ${JSON.stringify({cursor:Z.cursor(),count:Z.count(),version:le})}
43
43
 
44
- `),xe.add(o),n.on("close",()=>xe.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=Z.since(r.cursor);for(const s of r.events)o.write(`event: cloudevent
45
- data: ${JSON.stringify(ut(s))}
44
+ `),Oe.add(o),n.on("close",()=>Oe.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=Z.since(r.cursor);for(const s of r.events)o.write(`event: cloudevent
45
+ data: ${JSON.stringify(ht(s))}
46
46
 
47
- `)}}return}if(i==="/v1/link"&&n.method==="GET")return a(o,200,{...y?{enabled:!0,...y.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(i==="/v1/link/settings"&&n.method==="POST"){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change what it may reach",type:"forbidden"}});let e={};try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(typeof e.agentSessions!="boolean")return a(o,400,{error:{message:"link settings: { agentSessions: true|false }",type:"invalid_request"}});t.link={...t.link||{},agentSessions:e.agentSessions};try{he(t,re())}catch(r){console.warn(`[link] could not persist the settings: ${r.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(i==="/v1/link/pair"&&n.method==="POST"){if(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(e?.kind==="partner"){const r={partner:e.partner?.name,scopes:e.scopes,route:e.route||null,relay:String(e.relay||""),folder:typeof e.folder=="string"?e.folder:""};let s;try{s=y.previewPartner(r)}catch(l){return a(o,400,{error:{message:l?.message||String(l),type:"invalid_request",code:l?.code||"bad_partner"}})}if(e.confirm!==!0)return a(o,200,{confirmed:!1,preview:s});try{return a(o,200,{confirmed:!0,...await y.pairPartner(r)})}catch(l){return a(o,l?.code==="bad_partner"?400:502,{error:{message:l?.message||String(l),type:l?.code==="bad_partner"?"invalid_request":"relay"}})}}if(e?.kind&&e.kind!=="phone")return a(o,400,{error:{message:"link pair: kind is phone or partner",type:"invalid_request"}});try{return a(o,200,await y.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(r){return a(o,502,{error:{message:r?.message||String(r),type:"relay"}})}}if(i==="/v1/link/route"&&n.method==="POST"){if(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});let e={};try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let r;try{r=Bn({id:String(e.route||"link"),url:String(e.url||"")})}catch(l){return a(o,400,{error:{message:l.message,type:"bad_route"}})}const s={...t.link||{},route:r.id,fallback:e.fallback!==!1};r.id==="relay"?s.relayUrl=r.url:r.id==="link"&&delete s.relayUrl,(r.id==="tailscale"||r.id==="cloudflare")&&(s.tunnelUrl=r.url),t.link=s;try{he(t,re())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await y.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!y)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await y.remove(e)?(f.cancelDevice(e),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/link/files"||i.startsWith("/v1/link/files/")){const e=to(n.headers);if(e?.kind!=="partner"||!e.scopes.includes("files"))return a(o,403,{error:{message:"link files: a partner’s own folder, for a partner granted files",type:"forbidden",code:"link_scope"}});const r=y?.partnerFolderOf(e.device);if(!r)return a(o,403,{error:{message:"link files: this partner has no folder on this computer — pair it again with agents and files",type:"forbidden",code:"link_scope"}});const s=i.slice(14).replace(/^\//,"");let l=s;try{l=decodeURIComponent(s)}catch{}const c=n.method==="GET"&&(!s||/^(data|\.claude\/skills|\.claude\/agents|\.agents\/skills)\/?$/.test(l));let h;try{h=jn(s,{listing:c})}catch(p){return a(o,400,{error:{message:p.message,type:"invalid_request",code:"bad_path"}})}try{if(n.method==="GET"&&c)return a(o,200,{folder:"its own",files:Ln(r,h.replace(/\/$/,""))});if(n.method==="GET"){const p=Jn(r,h);o.writeHead(200,{"content-type":"application/octet-stream","content-length":String(p.size)}),p.stream.pipe(o);return}return n.method==="PUT"?a(o,200,zn(r,h,await S(n,t.maxBodyBytes))):n.method==="DELETE"?Gn(r,h)?a(o,200,{ok:!0}):a(o,404,{error:{message:`${h}: no such file`,type:"not_found"}}):a(o,405,{error:{message:"link files: GET, PUT or DELETE",type:"invalid_request"}})}catch(p){const v=p?.status||(p?.code===413?413:p?.code==="bad_partner"?400:500);return a(o,v,{error:{message:p?.message||String(p),type:v===404?"not_found":v===413?"too_large":"invalid_request"}})}}if(i==="/v1/link/approvals"||i.startsWith("/v1/link/approvals/")){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"an agent’s approval is the owner’s to give, on this computer",type:"forbidden"}});if(i==="/v1/link/approvals"&&n.method==="GET")return a(o,200,{pending:f.list()});if(i==="/v1/link/approvals/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const r=c=>o.write(`event: approvals
47
+ `)}}return}if(l==="/v1/link"&&n.method==="GET")return a(o,200,{...y?{enabled:!0,...y.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(l==="/v1/link/settings"&&n.method==="POST"){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change what it may reach",type:"forbidden"}});let e={};try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(typeof e.agentSessions!="boolean")return a(o,400,{error:{message:"link settings: { agentSessions: true|false }",type:"invalid_request"}});t.link={...t.link||{},agentSessions:e.agentSessions};try{ke(t,ie())}catch(r){console.warn(`[link] could not persist the settings: ${r.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(l==="/v1/link/pair"&&n.method==="POST"){if(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(e?.kind==="partner"){const r={partner:e.partner?.name,scopes:e.scopes,route:e.route||null,relay:String(e.relay||""),folder:typeof e.folder=="string"?e.folder:""};let s;try{s=y.previewPartner(r)}catch(i){return a(o,400,{error:{message:i?.message||String(i),type:"invalid_request",code:i?.code||"bad_partner"}})}if(e.confirm!==!0)return a(o,200,{confirmed:!1,preview:s});try{return a(o,200,{confirmed:!0,...await y.pairPartner(r)})}catch(i){return a(o,i?.code==="bad_partner"?400:502,{error:{message:i?.message||String(i),type:i?.code==="bad_partner"?"invalid_request":"relay"}})}}if(e?.kind&&e.kind!=="phone")return a(o,400,{error:{message:"link pair: kind is phone or partner",type:"invalid_request"}});try{return a(o,200,await y.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(r){return a(o,502,{error:{message:r?.message||String(r),type:"relay"}})}}if(l==="/v1/link/route"&&n.method==="POST"){if(!y)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});let e={};try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let r;try{r=Gn({id:String(e.route||"link"),url:String(e.url||"")})}catch(i){return a(o,400,{error:{message:i.message,type:"bad_route"}})}const s={...t.link||{},route:r.id,fallback:e.fallback!==!1};r.id==="relay"?s.relayUrl=r.url:r.id==="link"&&delete s.relayUrl,(r.id==="tailscale"||r.id==="cloudflare")&&(s.tunnelUrl=r.url),t.link=s;try{ke(t,ie())}catch(i){console.warn(`[link] could not persist the route: ${i.message}`)}return a(o,200,{enabled:!0,...await y.applySettings(s)})}if(l.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!y)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(l.slice(17));return await y.remove(e)?(f.cancelDevice(e),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(l==="/v1/link/files"||l.startsWith("/v1/link/files/")){const e=no(n.headers);if(e?.kind!=="partner"||!e.scopes.includes("files"))return a(o,403,{error:{message:"link files: a partner’s own folder, for a partner granted files",type:"forbidden",code:"link_scope"}});const r=y?.partnerFolderOf(e.device);if(!r)return a(o,403,{error:{message:"link files: this partner has no folder on this computer — pair it again with agents and files",type:"forbidden",code:"link_scope"}});const s=l.slice(14).replace(/^\//,"");let i=s;try{i=decodeURIComponent(s)}catch{}const c=n.method==="GET"&&(!s||/^(data|\.claude\/skills|\.claude\/agents|\.agents\/skills)\/?$/.test(i));let p;try{p=Kn(s,{listing:c})}catch(h){return a(o,400,{error:{message:h.message,type:"invalid_request",code:"bad_path"}})}try{if(n.method==="GET"&&c)return a(o,200,{folder:"its own",files:Qn(r,p.replace(/\/$/,""))});if(n.method==="GET"){const h=Yn(r,p);o.writeHead(200,{"content-type":"application/octet-stream","content-length":String(h.size)}),h.stream.pipe(o);return}return n.method==="PUT"?a(o,200,Zn(r,p,await T(n,t.maxBodyBytes))):n.method==="DELETE"?Xn(r,p)?a(o,200,{ok:!0}):a(o,404,{error:{message:`${p}: no such file`,type:"not_found"}}):a(o,405,{error:{message:"link files: GET, PUT or DELETE",type:"invalid_request"}})}catch(h){const S=h?.status||(h?.code===413?413:h?.code==="bad_partner"?400:500);return a(o,S,{error:{message:h?.message||String(h),type:S===404?"not_found":S===413?"too_large":"invalid_request"}})}}if(l==="/v1/link/approvals"||l.startsWith("/v1/link/approvals/")){if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"an agent’s approval is the owner’s to give, on this computer",type:"forbidden"}});if(l==="/v1/link/approvals"&&n.method==="GET")return a(o,200,{pending:f.list()});if(l==="/v1/link/approvals/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const r=c=>o.write(`event: approvals
48
48
  data: ${JSON.stringify({pending:c})}
49
49
 
50
- `);r(f.list());const s=f.subscribe(r),l=setInterval(()=>o.write(`:
50
+ `);r(f.list());const s=f.subscribe(r),i=setInterval(()=>o.write(`:
51
51
 
52
- `),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 oo.some(s=>s.id===r.decision)?f.answer(e[1],r.decision)?a(o,200,{ok:!0}):a(o,404,{error:{message:"nothing is waiting under that id — answered, withdrawn or expired",type:"not_found"}}):a(o,400,{error:{message:`link approvals: { decision: ${oo.map(s=>s.id).join(" | ")} }`,type:"invalid_request"}})}}if(i==="/v1/browser"&&n.method==="GET")return a(o,200,m.status());if(i==="/v1/browser/stream"&&n.method==="GET"){m.stream(n,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&n.method==="POST"){let e;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const r=i==="/v1/browser/call"?await m.call(e,n):i==="/v1/browser/announce"?m.announce(e):m.result(e);return a(o,r.status,r.body)}if(i==="/v1/history/stream"&&n.method==="GET"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
53
- data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:ne,prefsRevision:ae.revision})}
52
+ `),25e3);i.unref?.(),o.on("close",()=>{s(),clearInterval(i)});return}const e=/^\/v1\/link\/approvals\/([A-Za-z0-9_-]{1,40})$/.exec(l);if(e&&n.method==="POST"){let r={};try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{r={}}return ao.some(s=>s.id===r.decision)?f.answer(e[1],r.decision)?a(o,200,{ok:!0}):a(o,404,{error:{message:"nothing is waiting under that id — answered, withdrawn or expired",type:"not_found"}}):a(o,400,{error:{message:`link approvals: { decision: ${ao.map(s=>s.id).join(" | ")} }`,type:"invalid_request"}})}}if(l==="/v1/browser"&&n.method==="GET")return a(o,200,m.status());if(l==="/v1/browser/stream"&&n.method==="GET"){m.stream(n,o);return}if((l==="/v1/browser/call"||l==="/v1/browser/announce"||l==="/v1/browser/result")&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const r=l==="/v1/browser/call"?await m.call(e,n):l==="/v1/browser/announce"?m.announce(e):m.result(e);return a(o,r.status,r.body)}if(l==="/v1/history/stream"&&n.method==="GET"){const e=j.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
53
+ data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:le,prefsRevision:de.revision})}
54
54
 
55
- `),we.add(o),n.on("close",()=>we.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(g.searchParams.get("since"))||0,cursor:g.searchParams.get("cursor")||"",limit:Number(g.searchParams.get("limit"))||200,kind:g.searchParams.get("kind")||null,bytes:Number(g.searchParams.get("bytes"))||0,afterRev:g.searchParams.has("after_rev")?Number(g.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(g.searchParams.get("limit"))||50)),r=Math.max(0,Number(g.searchParams.get("offset"))||0),s=g.searchParams.get("type")||null;return a(o,200,{ok:!0,...R.list({limit:e,offset:r,type:s})})}if(i==="/v1/history/get"&&n.method==="GET"){const e=g.searchParams.get("maxChars")!=null?Math.max(1,Number(g.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(g.searchParams.get("offset"))||0),s=R.get(String(g.searchParams.get("id")||""),{maxChars:e,offset:r});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:Qt()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Er(String(e.passphrase)):$r();const r=e.passphrase?await mt(R,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Je(),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 mt(R,lt());return e.ok&&e.whole&&Je(),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 Ao(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Ye(t),I.state()!=="off"){if(!I.isReady()){const r=I.health();return a(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await S(n,t.maxBodyBytes);let s="",l=!1;try{const h=JSON.parse(r.toString("utf8"));s=h?.text||"",l=h?.strict===!0}catch{}const c=await I.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=Po(t);if(!e){const r=I.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:I.state(),model:t.ner?.model||null})}try{const r=await S(n,t.maxBodyBytes),s=await We(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:vt(t)});try{let r=e;const s=await ge(t.pro?.entitlementToken);await Ye(t);const l=await Ve([st(()=>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:Eo(l.vault,"types")||[],detector:vt(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=I.health().model||t.ner?.model||null,r=Math.round(pt.totalmem()/1048576),s=ea(so,{totalRamMB:r}).map(l=>({...l,installed:I.modelOnDisk(l.id)}));for(const l of[e,...I.modelsOnDisk()])!l||s.some(c=>c.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:I.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:I.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:_r(),recommendation:Kt(s,{totalRamMB:r},[]),state:I.state(),progress:I.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(pt.totalmem()/1048576),l=Kt(so.map(c=>({...c,installed:I.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(!(io(c)||lo(c)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${c}`,type:"bad_model"}});const l=r||t.ner?.model||I.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(c=>c!==l),r&&go(t,r);try{he(t,re())}catch{}return(async()=>{r&&await I.setModel(r,{onLog:h=>console.log(h)});const c=xr(t.ner,{log:h=>console.log(h)});for(const h of I.companions())c.includes(h.model)||await I.removeCompanion(h.model);for(const h of c)await I.addCompanion(h,{onLog:p=>console.log(p),allowDownload:t.ner.allowDownload!==!1});I.setUnionOrder(c)})().catch(c=>console.log(`[ner] union update failed: ${c.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:I.companions(),state:I.state()})}if(!r||!(io(r)||lo(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});go(t,r);try{he(t,re())}catch{}return I.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:I.state(),progress:I.progress()})}}if(i==="/stt/models"){if(n.method==="GET"){const e=B.health().model||t.stt?.model||Ze,r=ta.map(s=>({...s,installed:B.modelOnDisk(s.id)}));return e&&!r.some(s=>s.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:B.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:B.state(),progress:B.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:B.health().dtype,runtime:B.health().runtime,dtypes:na})}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||!(oa(r)||ra(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=typeof e.dtype=="string"&&aa(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},s&&(t.stt.dtype=s==="auto"?null:s);try{he(t,re())}catch{}return B.setModel(r,{onLog:l=>console.log(l),dtype:s||t.stt.dtype||"auto",warmMs:t.stt.warmMs,speaker:xt(t,{installing:!0})}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:B.state(),progress:B.progress(),speaker:{id:M.activeModel(),state:M.state(),installed:M.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=M.activeModel(),r=Yn.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(),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(!no(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{he(t,re())}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=C.health().model||t.tts?.model||yo(yt()),r=yt(),s=co.find(c=>c.id===e)||null,l=co.map(c=>({...c,installed:C.modelOnDisk(c.id),unavailable:c.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(c=>c.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:C.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:C.state(),progress:C.progress(),available:l,voice:t.tts?.voice||(et(e)==="pocket-tts"?Xe:ve),arch:C.arch(),supportsVoices:C.arch()?C.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:C.arch()?C.supportsCustomVoices():!!s?.customVoices,sampleRate:C.sampleRate(),voices:C.isPocket()||!C.arch()&&et(e)==="pocket-tts"?(C.builtinVoices().length?C.builtinVoices():ma).map(c=>({id:c,label:c[0].toUpperCase()+c.slice(1),lang:"en",installed:C.builtinVoices().includes(c)})):C.arch()&&C.arch()!=="style-tts2"?[]:sa.map(c=>({...c,installed:C.voiceOnDisk(c.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:C.health().dtype,runtime:C.health().runtime,dtypes:da})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(ia(r)||la(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const c=se.parseCustomVoice(s);if(!(c?!!se.getVoice(c):qe(s)||uo(s)&&mo(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&ca(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:po,voice:ve,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const c=ua(r),h=se.parseCustomVoice(t.tts.voice||""),p=!!(h&&se.getVoice(h));if(c&&!p)if(et(r)==="pocket-tts")t.tts.voice=Xe;else{const w=se.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!c&&p&&(t.tts.voice=ve);const v=et(r)==="pocket-tts";v&&!se.parseCustomVoice(t.tts.voice||"")&&!qe(t.tts.voice)&&(t.tts.voice=Xe),!v&&qe(t.tts.voice)&&(t.tts.voice=ve)}l&&(t.tts.dtype=l==="auto"?null:l);try{he(t,re())}catch{}return r&&C.setModel(r,{onLog:c=>console.log(c),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:C.state(),progress:C.progress()})}}if(i==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:se.listVoices(),usable:C.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(!se.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,{...se.renameVoice(l,r),usable:C.supportsCustomVoices()})}catch(c){return a(o,400,{error:{message:c.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!M.isReady()){const b=M.download({onLog:L=>console.log(L)}),P=Symbol("timeout"),x=await Promise.race([b.then(()=>null).catch(L=>L),new Promise(L=>setTimeout(()=>L(P),Za))]);if(x===P||!M.isReady())return a(o,503,{error:{message:x===P?"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 c=Float32Array.from(s),h=await M.embed(c);let p=null;try{const b=await C.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:P=>console.log(P)});b&&(p=await b.encodeVoice(Xa(c,16e3,24e3)))}catch(b){console.log(`[tts] pocket conditioning unavailable for this voice (${b.message})`)}const v=l?se.replaceVoice(l,{vec:h,pocket:p}):se.saveVoice({name:r,vec:h,pocket:p}),w=l&&r&&r!==v.name?se.renameVoice(l,r):v;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${w.name}" (${(v.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...v,...w,usable:C.supportsCustomVoices()})}catch(c){return a(o,400,{error:{message:c.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=g.searchParams.get("id")||"",r=se.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=se.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:ve;try{he(t,re())}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>ho)return a(o,413,{error:{message:`text too long (max ${ho} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=pa(t),c=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,h=c||(l?l.voice:t.tts?.voice||ve);if(l&&!ya(h))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const p=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(p!=="wav"&&p!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${p}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:Q,contentType:W,redacted:Be}=await ha({dest:l,text:r,voice:h,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ge(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":W,"Content-Length":String(Q.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(Be)}),o.end(Q)}if(!await C.ready({onLog:Q=>console.log(Q),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||yo(yt()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:C.health().error||"tts model not ready",type:"tts_unavailable"}});const w=fa({requested:c,configured:h,engine:C,voices:se,isPocketVoice:qe,isKnownVoice:uo,isValidVoiceId:mo,defaultVoice:ve,defaultPocketVoice:Xe});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:b,customId:P,speakerEmbedding:x}=w,L=await C.synth(r,{voice:b,speed:s,speakerEmbedding:x}),oe=C.sampleRate(),pe=p==="pcm"?Buffer.from(new Float32Array(L).buffer):C.toWav(L,oe);return o.writeHead(200,{"Content-Type":p==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(pe.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(oe),...P||C.isPocket()||C.supportsVoices()?{"X-Tts-Voice":b}:{}}),o.end(pe)}catch(v){return a(o,500,{error:{message:v.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=Xn(await S(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(b){return a(o,b.code===413?413:415,{error:{message:b.message,type:"bad_request"}})}const r=b=>e.find(P=>P.name===b&&!P.filename)?.data.toString("utf8").trim()||"",s=e.find(b=>b.name==="file"&&b.filename)||e.find(b=>b.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await qn(s.data)}catch(b){return a(o,b.code===415?415:500,{error:{message:b.message,type:"unsupported_media"}})}const c=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",h=ht(t,"stt");let p=null;if(h.kind==="remote"||h.kind==="container")try{p=ao(h,{fetchImpl:We})}catch(b){return a(o,500,{error:{message:`stt provider: ${b.message}`,type:"bad_provider"}})}!p&&!B.isReady()&&B.init({model:t.stt?.model||Ze,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:xt(t),onLog:b=>console.log(b)});const v=r("diarize")==="true"&&t.stt?.diarize!==!1;v&&!M.isReady()&&M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:b=>console.log(b)});const w=Date.now();try{const{id:b}=B.createSession({lang:r("language")||void 0,diarize:v,interims:!1,remote:p}),P=[];let x=null;B.subscribe(b,W=>{W.type==="final"&&W.text?P.push(W):W.type==="language"&&(x=W.lang)});const L=16e3*5;for(let W=0;W<l.pcm.length;W+=L)B.pushAudio(b,l.pcm.subarray(W,Math.min(l.pcm.length,W+L)));await B.endSession(b);let oe=0;const pe=P.map((W,Be)=>{const Co=oe,Io=(W.durationMs||0)/1e3;return oe+=Io,{id:Be,start:Math.round(Co*100)/100,end:Math.round(oe*100)/100,text:W.text,...W.speaker?{speaker:W.speaker}:{}}}),Q=pe.map(W=>W.text).join(" ").replace(/\s+/g," ").trim();return c==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Q)):c==="verbose_json"?a(o,200,{task:"transcribe",language:x||r("language")||null,duration:Math.round(l.seconds*100)/100,text:Q,segments:pe,provider:h.kind,took_ms:Date.now()-w}):a(o,200,{text:Q})}catch(b){return a(o,b.code==="too_many_sessions"?429:500,{error:{message:b.message,type:b.code||"stt_error"}})}}if(i==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=ht(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=ao(r,{fetchImpl:We})}catch(c){return a(o,500,{error:{message:`stt provider: ${c.message}`,type:"bad_provider"}})}!s&&!B.isReady()&&B.init({model:t.stt?.model||Ze,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:xt(t),onLog:c=>console.log(c)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!M.isReady()&&M.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:c=>console.log(c)});try{const c=e?.poll===!0,{id:h}=B.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:c});return a(o,201,{id:h,state:B.state(),...c?{poll:!0}:{}})}catch(c){return a(o,c.code==="too_many_sessions"?429:500,{error:{message:c.message,type:c.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(c,h,p)=>{if(h.type!=="final"||!c.redact)return h;try{let v=h.text;return await Ve([st(()=>v,w=>{v=w})],t.redaction,{isPro:p}),{...h,text:v}}catch{return h}},l=async c=>{const h=B.drainEvents(r);if(!h)return null;const p=[];if(c&&!c.closed){const w=c.remote?"ready":B.state();w==="downloading"||w==="loading"?p.push({type:"progress",state:w,...B.progress()||{}}):w==="error"?p.push({type:"error",code:"model_failed",message:B.health().error||"model failed to load",fatal:!0}):c.diarize&&["downloading","loading"].includes(M.state())?p.push({type:"diarize-progress",state:M.state(),...M.progress()||{}}):Bo.get(c)!==w&&(Bo.set(c,w),p.push({type:"state",state:w}))}const v=c?.redact?await ge(t.pro?.entitlementToken):!0;for(const w of h)c?p.push(await s(c,w,v)):w.type!=="final"&&w.type!=="interim"&&p.push(w);return p};if(e[2]==="/audio"&&n.method==="POST"){const c=B.getSession(r)||B.endedSession(r);try{const h=await S(n,t.maxBodyBytes);B.pushAudio(r,B.toFloat32(h));const p=await l(c);return a(o,200,{ok:!0,state:B.state(),...p?{events:p}:{}})}catch(h){const p=h.code==="no_session"?await l(c).catch(()=>null):null;return a(o,h.code==="no_session"?404:400,{error:{message:h.message,type:h.code||"stt_error"},...p?{events:p}:{}})}}if(e[2]==="/events"&&n.method==="GET"){const c=B.getSession(r);if(!c)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=x=>o.write(`data: ${JSON.stringify(x)}
55
+ `),Te.add(o),n.on("close",()=>Te.delete(o));return}if(l==="/v1/history/records"&&n.method==="GET"){const e=j.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(g.searchParams.get("since"))||0,cursor:g.searchParams.get("cursor")||"",limit:Number(g.searchParams.get("limit"))||200,kind:g.searchParams.get("kind")||null,bytes:Number(g.searchParams.get("bytes"))||0,afterRev:g.searchParams.has("after_rev")?Number(g.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(l==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(g.searchParams.get("limit"))||50)),r=Math.max(0,Number(g.searchParams.get("offset"))||0),s=g.searchParams.get("type")||null;return a(o,200,{ok:!0,...j.list({limit:e,offset:r,type:s})})}if(l==="/v1/history/get"&&n.method==="GET"){const e=g.searchParams.get("maxChars")!=null?Math.max(1,Number(g.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(g.searchParams.get("offset"))||0),s=j.get(String(g.searchParams.get("id")||""),{maxChars:e,offset:r});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(l==="/v1/history/key"&&n.method==="GET")return a(o,200,{ok:!0,hasKey:Zt()});if(l==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Br(String(e.passphrase)):Dr();const r=e.passphrase?await yt(j,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&ze(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(l==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await yt(j,ut());return e.ok&&e.whole&&ze(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(l==="/ner"){if(n.method==="GET"){const e=await Do(t);return a(o,e.ok?200:503,e)}if(n.method==="POST"){if(await qe(t),R.state()!=="off"){if(!R.isReady()){const r=R.health();return a(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await T(n,t.maxBodyBytes);let s="",i=!1;try{const p=JSON.parse(r.toString("utf8"));s=p?.text||"",i=p?.strict===!0}catch{}const c=await R.detect(s,{strict:i});return a(o,200,{entities:c})}catch(r){return a(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=Bo(t);if(!e){const r=R.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:R.state(),model:t.ner?.model||null})}try{const r=await T(n,t.maxBodyBytes),s=await Ye(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),i=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(i)}catch(r){return a(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(l==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:_t(t)});try{let r=e;const s=await Se(t.pro?.entitlementToken);await qe(t);const i=await Ke([dt(()=>r,c=>{r=c})],t.redaction,{isPro:s});return a(o,200,{text:r,count:i.count||0,sanitized:i.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Ao(i.vault,"types")||[],detector:_t(t)})}catch(r){return a(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(l==="/ner/models"){if(n.method==="GET"){const e=R.health().model||t.ner?.model||null,r=Math.round(ft.totalmem()/1048576),s=ca(co,{totalRamMB:r}).map(i=>({...i,installed:R.modelOnDisk(i.id)}));for(const i of[e,...R.modelsOnDisk()])!i||s.some(c=>c.id===i)||s.push({id:i,label:i,lang:"—",custom:!0,installed:R.modelOnDisk(i),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:R.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Ar(),recommendation:Yt(s,{totalRamMB:r},[]),state:R.state(),progress:R.progress(),available:s})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(ft.totalmem()/1048576),i=Yt(co.map(c=>({...c,installed:R.modelOnDisk(c.id)})),{totalRamMB:s},[]);e={id:i.primary,union:i.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(c=>String(c||"").trim()).filter(Boolean))];for(const c of s)if(!(uo(c)||mo(c)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${c}`,type:"bad_model"}});const i=r||t.ner?.model||R.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(c=>c!==i),r&&ko(t,r);try{ke(t,ie())}catch{}return(async()=>{r&&await R.setModel(r,{onLog:p=>console.log(p)});const c=Pr(t.ner,{log:p=>console.log(p)});for(const p of R.companions())c.includes(p.model)||await R.removeCompanion(p.model);for(const p of c)await R.addCompanion(p,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});R.setUnionOrder(c)})().catch(c=>console.log(`[ner] union update failed: ${c.message}`)),a(o,202,{accepted:!0,active:i,union:t.ner.union,companions:R.companions(),state:R.state()})}if(!r||!(uo(r)||mo(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});ko(t,r);try{ke(t,ie())}catch{}return R.setModel(r,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:r,state:R.state(),progress:R.progress()})}}if(l==="/stt/models"){if(n.method==="GET"){const e=B.health().model||t.stt?.model||et,r=ua.map(s=>({...s,installed:B.modelOnDisk(s.id)}));return e&&!r.some(s=>s.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:B.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:B.state(),progress:B.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:B.health().dtype,runtime:B.health().runtime,dtypes:ha})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(ma(r)||pa(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=typeof e.dtype=="string"&&ya(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},s&&(t.stt.dtype=s==="auto"?null:s);try{ke(t,ie())}catch{}return B.setModel(r,{onLog:i=>console.log(i),dtype:s||t.stt.dtype||"auto",warmMs:t.stt.warmMs,speaker:$t(t,{installing:!0})}),a(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:B.state(),progress:B.progress(),speaker:{id:D.activeModel(),state:D.state(),installed:D.modelOnDisk()}})}}if(l==="/diarize/model"){if(n.method==="GET"){const e=D.activeModel(),r=sa.map(s=>({...s,installed:D.modelOnDisk(s.id)})).sort((s,i)=>(i.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:D.state(),threshold:D.activeThreshold(),progress:D.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!io(r))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await D.setModel(r,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{ke(t,ie())}catch{}return D.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:D.activeModel(),state:D.state(),threshold:D.activeThreshold(),progress:D.progress()})}return D.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:D.activeModel(),state:D.state(),threshold:D.activeThreshold(),progress:D.progress()})}}if(l==="/tts/models"){if(n.method==="GET"){const e=M.health().model||t.tts?.model||wo(wt()),r=wt(),s=po.find(c=>c.id===e)||null,i=po.map(c=>({...c,installed:M.modelOnDisk(c.id),unavailable:c.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!i.some(c=>c.id===e)&&i.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:M.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:M.state(),progress:M.progress(),available:i,voice:t.tts?.voice||(rt(e)==="pocket-tts"?tt:xe),arch:M.arch(),supportsVoices:M.arch()?M.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:M.arch()?M.supportsCustomVoices():!!s?.customVoices,sampleRate:M.sampleRate(),voices:M.isPocket()||!M.arch()&&rt(e)==="pocket-tts"?(M.builtinVoices().length?M.builtinVoices():Sa).map(c=>({id:c,label:c[0].toUpperCase()+c.slice(1),lang:"en",installed:M.builtinVoices().includes(c)})):M.arch()&&M.arch()!=="style-tts2"?[]:fa.map(c=>({...c,installed:M.voiceOnDisk(c.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:M.health().dtype,runtime:M.health().runtime,dtypes:ba})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(ga(r)||wa(r)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const c=me.parseCustomVoice(s);if(!(c?!!me.getVoice(c):ot(s)||ho(s)&&yo(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&ka(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:fo,voice:xe,allowDownload:!0}),r&&(t.tts.model=r),s&&(t.tts.voice=s),r&&!s){const c=va(r),p=me.parseCustomVoice(t.tts.voice||""),h=!!(p&&me.getVoice(p));if(c&&!h)if(rt(r)==="pocket-tts")t.tts.voice=tt;else{const w=me.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!c&&h&&(t.tts.voice=xe);const S=rt(r)==="pocket-tts";S&&!me.parseCustomVoice(t.tts.voice||"")&&!ot(t.tts.voice)&&(t.tts.voice=tt),!S&&ot(t.tts.voice)&&(t.tts.voice=xe)}i&&(t.tts.dtype=i==="auto"?null:i);try{ke(t,ie())}catch{}return r&&M.setModel(r,{onLog:c=>console.log(c),dtype:i||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:M.state(),progress:M.progress()})}}if(l==="/tts/voices"){if(n.method==="GET")return a(o,200,{voices:me.listVoices(),usable:M.supportsCustomVoices(),embedder:D.activeModel(),embedderReady:D.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,i=e&&typeof e.id=="string"?e.id.trim():"";if(i){if(!me.getVoice(i))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...me.renameVoice(i,r),usable:M.supportsCustomVoices()})}catch(c){return a(o,400,{error:{message:c.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!D.isReady()){const b=D.download({onLog:L=>console.log(L)}),A=Symbol("timeout"),_=await Promise.race([b.then(()=>null).catch(L=>L),new Promise(L=>setTimeout(()=>L(A),is))]);if(_===A||!D.isReady())return a(o,503,{error:{message:_===A?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${D.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:D.progress()})}const c=Float32Array.from(s),p=await D.embed(c);let h=null;try{const b=await M.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:A=>console.log(A)});b&&(h=await b.encodeVoice(ls(c,16e3,24e3)))}catch(b){console.log(`[tts] pocket conditioning unavailable for this voice (${b.message})`)}const S=i?me.replaceVoice(i,{vec:p,pocket:h}):me.saveVoice({name:r,vec:p,pocket:h}),w=i&&r&&r!==S.name?me.renameVoice(i,r):S;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${w.name}" (${(S.kinds||[]).join(" + ")}, sample discarded)`),a(o,i?200:201,{...S,...w,usable:M.supportsCustomVoices()})}catch(c){return a(o,400,{error:{message:c.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=g.searchParams.get("id")||"",r=me.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const s=me.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:xe;try{ke(t,ie())}catch{}}return a(o,200,{deleted:r,voice:t.tts?.voice})}}if((l==="/tts"||l==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>go)return a(o,413,{error:{message:`text too long (max ${go} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=Ta(t),c=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,p=c||(i?i.voice:t.tts?.voice||xe);if(i&&!_a(p))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(i){const{audio:Y,contentType:V,redacted:De}=await xa({dest:i,text:r,voice:p,speed:s,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await Se(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":V,"Content-Length":String(Y.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(De)}),o.end(Y)}if(!await M.ready({onLog:Y=>console.log(Y),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||wo(wt()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:M.health().error||"tts model not ready",type:"tts_unavailable"}});const w=Oa({requested:c,configured:p,engine:M,voices:me,isPocketVoice:ot,isKnownVoice:ho,isValidVoiceId:yo,defaultVoice:xe,defaultPocketVoice:tt});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:b,customId:A,speakerEmbedding:_}=w,L=await M.synth(r,{voice:b,speed:s,speakerEmbedding:_}),se=M.sampleRate(),be=h==="pcm"?Buffer.from(new Float32Array(L).buffer):M.toWav(L,se);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(be.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(se),...A||M.isPocket()||M.supportsVoices()?{"X-Tts-Voice":b}:{}}),o.end(be)}catch(S){return a(o,500,{error:{message:S.message,type:"tts_failed"}})}}if(l==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=la(await T(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(b){return a(o,b.code===413?413:415,{error:{message:b.message,type:"bad_request"}})}const r=b=>e.find(A=>A.name===b&&!A.filename)?.data.toString("utf8").trim()||"",s=e.find(b=>b.name==="file"&&b.filename)||e.find(b=>b.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let i;try{i=await da(s.data)}catch(b){return a(o,b.code===415?415:500,{error:{message:b.message,type:"unsupported_media"}})}const c=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",p=gt(t,"stt");let h=null;if(p.kind==="remote"||p.kind==="container")try{h=lo(p,{fetchImpl:Ye})}catch(b){return a(o,500,{error:{message:`stt provider: ${b.message}`,type:"bad_provider"}})}!h&&!B.isReady()&&B.init({model:t.stt?.model||et,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:$t(t),onLog:b=>console.log(b)});const S=r("diarize")==="true"&&t.stt?.diarize!==!1;S&&!D.isReady()&&D.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:b=>console.log(b)});const w=Date.now();try{const{id:b}=B.createSession({lang:r("language")||void 0,diarize:S,interims:!1,remote:h}),A=[];let _=null;B.subscribe(b,V=>{V.type==="final"&&V.text?A.push(V):V.type==="language"&&(_=V.lang)});const L=16e3*5;for(let V=0;V<i.pcm.length;V+=L)B.pushAudio(b,i.pcm.subarray(V,Math.min(i.pcm.length,V+L)));await B.endSession(b);let se=0;const be=A.map((V,De)=>{const Jo=se,zo=(V.durationMs||0)/1e3;return se+=zo,{id:De,start:Math.round(Jo*100)/100,end:Math.round(se*100)/100,text:V.text,...V.speaker?{speaker:V.speaker}:{}}}),Y=be.map(V=>V.text).join(" ").replace(/\s+/g," ").trim();return c==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(Y)):c==="verbose_json"?a(o,200,{task:"transcribe",language:_||r("language")||null,duration:Math.round(i.seconds*100)/100,text:Y,segments:be,provider:p.kind,took_ms:Date.now()-w}):a(o,200,{text:Y})}catch(b){return a(o,b.code==="too_many_sessions"?429:500,{error:{message:b.message,type:b.code||"stt_error"}})}}if(l==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=gt(t,"stt");let s=null;if(r.kind==="remote"||r.kind==="container")try{s=lo(r,{fetchImpl:Ye})}catch(c){return a(o,500,{error:{message:`stt provider: ${c.message}`,type:"bad_provider"}})}!s&&!B.isReady()&&B.init({model:t.stt?.model||et,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:$t(t),onLog:c=>console.log(c)});const i=e?.diarize===!0&&t.stt?.diarize!==!1;i&&!D.isReady()&&D.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:c=>console.log(c)});try{const c=e?.poll===!0,{id:p}=B.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:i,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:c});return a(o,201,{id:p,state:B.state(),...c?{poll:!0}:{}})}catch(c){return a(o,c.code==="too_many_sessions"?429:500,{error:{message:c.message,type:c.code||"stt_error"}})}}{const e=l.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1],s=async(c,p,h)=>{if(p.type!=="final"||!c.redact)return p;try{let S=p.text;return await Ke([dt(()=>S,w=>{S=w})],t.redaction,{isPro:h}),{...p,text:S}}catch{return p}},i=async c=>{const p=B.drainEvents(r);if(!p)return null;const h=[];if(c&&!c.closed){const w=c.remote?"ready":B.state();w==="downloading"||w==="loading"?h.push({type:"progress",state:w,...B.progress()||{}}):w==="error"?h.push({type:"error",code:"model_failed",message:B.health().error||"model failed to load",fatal:!0}):c.diarize&&["downloading","loading"].includes(D.state())?h.push({type:"diarize-progress",state:D.state(),...D.progress()||{}}):Co.get(c)!==w&&(Co.set(c,w),h.push({type:"state",state:w}))}const S=c?.redact?await Se(t.pro?.entitlementToken):!0;for(const w of p)c?h.push(await s(c,w,S)):w.type!=="final"&&w.type!=="interim"&&h.push(w);return h};if(e[2]==="/audio"&&n.method==="POST"){const c=B.getSession(r)||B.endedSession(r);try{const p=await T(n,t.maxBodyBytes);B.pushAudio(r,B.toFloat32(p));const h=await i(c);return a(o,200,{ok:!0,state:B.state(),...h?{events:h}:{}})}catch(p){const h=p.code==="no_session"?await i(c).catch(()=>null):null;return a(o,p.code==="no_session"?404:400,{error:{message:p.message,type:p.code||"stt_error"},...h?{events:h}:{}})}}if(e[2]==="/events"&&n.method==="GET"){const c=B.getSession(r);if(!c)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const p=_=>o.write(`data: ${JSON.stringify(_)}
56
56
 
57
- `),p=c.redact?await ge(t.pro?.entitlementToken):!0,v=x=>s(c,x,p);h({type:"state",state:c.remote?"ready":B.state()});const w=setInterval(()=>{const x=c.remote?"ready":B.state();if(x==="downloading"||x==="loading"){h({type:"progress",state:x,...B.progress()||{}});return}if(x==="error"){h({type:"error",code:"model_failed",message:B.health().error||"model failed to load",fatal:!0}),clearInterval(w);return}if(c.diarize){const L=M.state();if(L==="downloading"||L==="loading"){h({type:"diarize-progress",state:L,...M.progress()||{}});return}}h({type:"state",state:x}),clearInterval(w)},500);w.unref?.();let b=Promise.resolve();const P=B.subscribe(r,x=>{b=b.then(async()=>{h(await v(x)),x.type==="end"&&(clearInterval(w),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(w),P?.()});return}if(!e[2]&&n.method==="DELETE"){const c=B.getSession(r);await B.endSession(r);const h=c?.poll?await l(c).catch(()=>null):null;return a(o,200,{ok:!0,...h?{events:h}:{}})}}}if(i==="/logs"&&n.method==="GET")return a(o,200,{entries:[...fe].reverse()});if(i==="/config"&&n.method==="GET"){const e=await ge(t.pro?.entitlementToken);return a(o,200,fo(t,{proUnlocked:e,policy:Fe()}))}if(i==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return a(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{ka(t,e)}catch(p){if(p?.code==="SHAPE")return a(o,400,{error:p.message});throw p}Jt(t),JSON.stringify(t.sandbox||null)!==r&&ze?.restart("sandbox settings changed");try{he(t,re())}catch(p){return a(o,500,{error:`could not persist config: ${p.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",c=I.state();t.ner?.autostart&&l&&c!=="ready"&&c!=="loading"&&c!=="downloading"&&I.setModel(t.ner.model,{onLog:p=>console.log(p)}).then(p=>{p&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const h=await ge(t.pro?.entitlementToken);return a(o,200,fo(t,{proUnlocked:h,policy:Fe()}))}if(n.method==="GET"&&i==="/skills")return ye(n,o,t,`/skills${Ae(g,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="POST"&&i==="/v1/threads/send"){if(!H(n))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"asking another chat is not available from a linked phone yet",type:"forbidden"}});const e=R.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let r={};try{r=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"threads/send: body must be JSON",type:"invalid_request"}})}const s=String(r.to||""),l=String(r.message||"").trim();if(!l||l.length>Xt)return a(o,400,{error:{message:`threads/send: a message of 1–${Xt} characters`,type:"invalid_request"}});const c=r.from&&typeof r.from=="object"?{id:String(r.from.id||"").slice(0,200),title:String(r.from.title||"").slice(0,200)}:null,h=e.get(s);if(!h||h.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const p=Cr(h,{cards:ae.get("agentTools").agentTools?.value?.agents||[]});if(p.error)return a(o,409,{error:{message:p.error,type:"no_model"}});if(r.dryRun===!0)return a(o,200,{ok:!0,title:h.title,model:p.model});const v=Ir({fromTitle:c?.title,message:l}),w={thread:{id:p.thread,...h.title?{title:h.title}:{}},...p.workingDir?{workingDir:p.workingDir}:{}};let b="";try{const x=await fetch(`http://127.0.0.1:${n.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":Me()||Te(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(w))},body:JSON.stringify({model:p.model,messages:[...Rr(h),{role:"user",content:v}],stream:!1}),signal:AbortSignal.timeout(6e5)}),L=await x.json().catch(()=>null);if(!x.ok)return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${L?.error?.message||`HTTP ${x.status}`}`,type:"upstream"}});b=String(L?.choices?.[0]?.message?.content||"")}catch(x){return a(o,502,{error:{message:`that chat's ${p.model} did not answer: ${x?.message||x}`,type:"upstream"}})}const P=jr(e.get(s)||h,{question:v,reply:b,model:p.model,from:c});e.write([P],{host:"gateway",at:Date.now()});try{const x=eo(e.get(s));x&&R.bulk({upserts:[x],removes:[]})}catch{}return Je({ids:[s]}),a(o,200,{ok:!0,title:h.title,model:p.model,reply:b})}const le=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(n.method==="POST"&&le)return H(n)?n.headers["x-chatpanel-link-device"]&&t.link?.agentSessions===!1?a(o,403,{error:{message:"this computer does not share its coding agents' sessions with a linked phone — Settings › Link › Phones",type:"forbidden"}}):ye(n,o,t,le,{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 ye(n,o,t,`/skills-quarantined${Ae(g,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&n.method==="POST")return H(n)?ye(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 _t(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):H(n)?ye(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 _t(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):H(n)?ye(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 ye(n,o,t,`/agent-defs${Ae(g,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return _t(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):ye(n,o,t,`/agent-defs/${encodeURIComponent(e)}${Ae(g,t)}`)}if(i.startsWith("/a2a/")){if(!H(n))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:gr()});if(n.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await S(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&mr(e.url||"");const r=await Ke(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 Ke(e.url,{auth:String(e.auth||"")})).card,s=await pr({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 Ke(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}
57
+ `),h=c.redact?await Se(t.pro?.entitlementToken):!0,S=_=>s(c,_,h);p({type:"state",state:c.remote?"ready":B.state()});const w=setInterval(()=>{const _=c.remote?"ready":B.state();if(_==="downloading"||_==="loading"){p({type:"progress",state:_,...B.progress()||{}});return}if(_==="error"){p({type:"error",code:"model_failed",message:B.health().error||"model failed to load",fatal:!0}),clearInterval(w);return}if(c.diarize){const L=D.state();if(L==="downloading"||L==="loading"){p({type:"diarize-progress",state:L,...D.progress()||{}});return}}p({type:"state",state:_}),clearInterval(w)},500);w.unref?.();let b=Promise.resolve();const A=B.subscribe(r,_=>{b=b.then(async()=>{p(await S(_)),_.type==="end"&&(clearInterval(w),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(w),A?.()});return}if(!e[2]&&n.method==="DELETE"){const c=B.getSession(r);await B.endSession(r);const p=c?.poll?await i(c).catch(()=>null):null;return a(o,200,{ok:!0,...p?{events:p}:{}})}}}if(l==="/logs"&&n.method==="GET")return a(o,200,{entries:[...Q].reverse()});if(l==="/config"&&n.method==="GET"){const e=await Se(t.pro?.entitlementToken);return a(o,200,bo(t,{proUnlocked:e,policy:Qe()}))}if(l==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return a(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{Aa(t,e)}catch(h){if(h?.code==="SHAPE")return a(o,400,{error:h.message});throw h}Gt(t),JSON.stringify(t.sandbox||null)!==r&&Ge?.restart("sandbox settings changed");try{ke(t,ie())}catch(h){return a(o,500,{error:`could not persist config: ${h.message}`})}const s=t.redaction?.detection,i=!s||!s.backend||s.backend==="off",c=R.state();t.ner?.autostart&&i&&c!=="ready"&&c!=="loading"&&c!=="downloading"&&R.setModel(t.ner.model,{onLog:h=>console.log(h)}).then(h=>{h&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const p=await Se(t.pro?.entitlementToken);return a(o,200,bo(t,{proUnlocked:p,policy:Qe()}))}if(n.method==="GET"&&l==="/skills")return ve(n,o,t,`/skills${Be(g,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="POST"&&l==="/v1/threads/send"){if(!U(n))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(n.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"asking another chat is not available from a linked phone yet",type:"forbidden"}});const e=j.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let r={};try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"threads/send: body must be JSON",type:"invalid_request"}})}const s=String(r.to||""),i=String(r.message||"").trim();if(!i||i.length>eo)return a(o,400,{error:{message:`threads/send: a message of 1–${eo} 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,p=e.get(s);if(!p||p.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const h=Jr(p,{cards:de.get("agentTools").agentTools?.value?.agents||[]});if(h.error)return a(o,409,{error:{message:h.error,type:"no_model"}});if(r.dryRun===!0)return a(o,200,{ok:!0,title:p.title,model:h.model});const S=zr({fromTitle:c?.title,message:i}),w={thread:{id:h.thread,...p.title?{title:p.title}:{}},...h.workingDir?{workingDir:h.workingDir}:{}};let b="";try{const _=await fetch(`http://127.0.0.1:${n.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":Me()||_e(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(w))},body:JSON.stringify({model:h.model,messages:[...Gr(p),{role:"user",content:S}],stream:!1}),signal:AbortSignal.timeout(6e5)}),L=await _.json().catch(()=>null);if(!_.ok)return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${L?.error?.message||`HTTP ${_.status}`}`,type:"upstream"}});b=String(L?.choices?.[0]?.message?.content||"")}catch(_){return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${_?.message||_}`,type:"upstream"}})}const A=Hr(e.get(s)||p,{question:S,reply:b,model:h.model,from:c});e.write([A],{host:"gateway",at:Date.now()});try{const _=ro(e.get(s));_&&j.bulk({upserts:[_],removes:[]})}catch{}return ze({ids:[s]}),a(o,200,{ok:!0,title:p.title,model:h.model,reply:b})}const fe=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(l)?.[1];if(n.method==="POST"&&fe)return U(n)?n.headers["x-chatpanel-link-device"]&&t.link?.agentSessions===!1?a(o,403,{error:{message:"this computer does not share its coding agents' sessions with a linked phone — Settings › Link › Phones",type:"forbidden"}}):ve(n,o,t,fe,{method:"POST",timeoutMs:3e4}):a(o,403,{error:{message:"the agents' own sessions: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&l==="/skills-quarantined")return ve(n,o,t,`/skills-quarantined${Be(g,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(l==="/skills"&&n.method==="POST")return U(n)?ve(n,o,t,"/skills",{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(l)&&n.method==="DELETE"){const e=decodeURIComponent(l.slice(8));return Pt(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):U(n)?ve(n,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):a(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(l)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(l),r=decodeURIComponent(e[1]);return Pt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):U(n)?ve(n,o,t,`/skills/${encodeURIComponent(r)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(n.method==="GET"&&l==="/agent-defs")return ve(n,o,t,`/agent-defs${Be(g,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(l)){const e=decodeURIComponent(l.slice(12));return Pt(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):ve(n,o,t,`/agent-defs/${encodeURIComponent(e)}${Be(g,t)}`)}if(l.startsWith("/a2a/")){if(!U(n))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&l==="/a2a/agents")return a(o,200,{agents:Sr()});if(n.method==="POST"&&l==="/a2a/card"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&gr(e.url||"");const r=await Ze(e.url,{force:!!e.force,auth:String(e.auth||"")});return a(o,200,{ok:!0,card:r.card,fingerprint:r.fingerprint,fresh:r.fresh,changed:!!r.changed,url:r.url})}if(n.method==="POST"&&l==="/a2a/message"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Ze(e.url,{auth:String(e.auth||"")})).card,s=await wr({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),returnImmediately:!!e.returnImmediately,contextId:String(e.contextId||""),taskId:String(e.taskId||"")});return a(o,200,{ok:!0,...s})}if(n.method==="POST"&&l==="/a2a/message/stream"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Ze(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const s=(i,c)=>o.write(`event: ${i}
58
58
  data: ${JSON.stringify(c)}
59
59
 
60
- `);try{const l=await hr({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 Ke(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await fr({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await yr({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 Gt||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof Gt&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return H(n)?ye(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"}}):ye(n,o,t,`/skills/${encodeURIComponent(e)}${Ae(g,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!H(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await Ie(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=Re(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"}}):ye(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${Ae(g,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await z(),r=e.sig!==void 0&&e.sig!==D;return D=e.sig,a(o,200,await _a(t,{serviceHealth:async()=>e,fresh:r,engineAt:d.engineAt}))}if(qa.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${ne}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const J=Ga(i,n.headers,t);let q;try{q=await S(n,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let F=null,T=null,Se=q,_e=0,Et=0,$t=0,ke=!1,Oe=!1,Pt="",Ee=!0;const ee=t.logRequests&&J.redactable&&n.method==="POST"?za(ue):null;if(J.redactable&&n.method==="POST"&&q.length){try{T=JSON.parse(q.toString("utf8"))}catch{T=null}if(T&&Ua(T,J.kind))Se=q;else if(T){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(T.tools)&&T.tools.length){const w=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Ma,b=e.narrowAll?null:x=>!Da.test(To(x)),P=T.tools.length;T.tools=Vo(T.tools,Ia(T,J.kind),{cap:w,keep:b,name:To,description:Ca}),$t=P-T.tools.length}Ee=await ge(t.pro?.entitlementToken);const r=ga(t,Ee);if(!r.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${r.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});if(ke=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&H(n),!ke){const w=tt(T?.model,t,J.kind,{destination:String(n.headers["x-chatpanel-destination"]||T?.chatpanel?.destination||"").trim(),down:()=>!1}),b=w?.type==="api"?await d.decide(w,T?.model).catch(()=>null):null;Oe=b?.redact===!1,Pt=Oe?b.engine||"declared":""}!ke&&!Oe&&await Ye(t);const s=ke?[]:J.adapter.collectSegments(T,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const c=ee?ee.clock():0,{vault:h,count:p,sanitized:v}=ke?{vault:null,count:0,sanitized:0}:await Ve(s,t.redaction,{signal:l.signal,isPro:Ee,sanitizeOnly:Oe,onEgress:w=>bt.push(bo({ts:Date.now(),client:"redaction",tool:`detect:${w.backend}@${w.host||"local"}`,ok:w.ok,ms:w.ms,error:w.error}))});if(ee&&ee.lap("redact",c),F=h,_e=p,Et=v||0,p>0&&o.setHeader("x-chatpanel-redacted",String(p)),!Ee&&p>0){wa(t,Ee);try{he(t,re())}catch{}}if(!ke&&!Oe&&Array.isArray(T.tools)&&T.tools.length&&typeof J.adapter.injectSystemNote=="function"){const w=tt(T?.model,t,J.kind,{destination:String(n.headers["x-chatpanel-destination"]||T?.chatpanel?.destination||"").trim(),down:P=>!!P.service&&_.fn(P.id)==="down"}),b=!(w&&w.type==="api");J.adapter.injectSystemNote(T,Wo({toolData:t.tools?.toolData,ownTools:b}))}else!ke&&p>0&&typeof J.adapter.injectSystemNote=="function"&&J.adapter.injectSystemNote(T,Ko());Se=Buffer.from(JSON.stringify(T),"utf8")}}const At=Fo({vault:F,toolData:t.tools?.toolData}),Ge=T&&typeof T.chatpanel=="object"&&T.chatpanel||null;if(Ge&&(delete T.chatpanel,Se=Buffer.from(JSON.stringify(T),"utf8")),typeof T?.model=="string"&&T.model.startsWith("fusion:")){const e=cn(T.model,t,await z());if(e?.error)return ee?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(T.model=e.model,Se=Buffer.from(JSON.stringify(T),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const te={destination:String(n.headers["x-chatpanel-destination"]||Ge?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Ge?.reach||"").trim(),run:Ot(n.headers["x-chatpanel-run"],Ge?.run)},Ue=await z(),Nt=e=>!!e.service&&Ue(e.id)==="down";let N=tt(T?.model,t,J.kind,{destination:te.destination,down:Nt});N?.type==="agent"&&T?.model&&!te.destination&&!$a(N,T.model)&&(await Ea(t,{serviceHealth:async()=>Ue,engineAt:d.engineAt}),N=tt(T?.model,t,J.kind,{destination:te.destination,down:Nt}));const Bt=N?.service&&Ue(N.id)==="down"?await $().revive(N.service).catch(()=>null):null;if(Bt?.ok&&(_.at=0),N?.service&&Ue(N.id)==="down"&&!Bt?.ok)return ee?.commit(),a(o,503,{error:{message:`${N.id} is not running — the model ${JSON.stringify(T?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:N.service}});if(te.destination&&(!N||N.id!==te.destination))return ee?.commit(),a(o,404,{error:{message:`no destination "${te.destination}" is configured on this gateway`,type:"unknown_destination",known:Oa(t).map(e=>e.id)}});const me=to(n.headers);if(me&&!Cn(me,N?.type==="api"?"api":"agent"))return ee?.commit(),a(o,403,{error:{message:`link: partner "${me.partner}" may not use ${N?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${me.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});ee&&(ee.meta={t:Date.now(),model:T?.model||null,dest:N?N.id:null,type:N?N.type:null,redacted:_e,sanitized:Et,narrowed:$t,detail:Eo(F,t.logDetail),redaction:ke?"off":Oe?`on-device (${Pt})`:t.redaction.tier||"basic",...me?.kind==="partner"?{via:In(me)}:{}});const He=Fe();if(He&&N){const e=N.type==="api"?zt(He,{model:T?.model||"",endpoint:N.baseUrl||""}):cr(He,N.agent||N.id)?zt(He,{model:T?.model||""}):{ok:!1,reason:`agent "${N.agent||N.id}" is not allowed by your organisation’s policy`};if(!e.ok)return ee?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(N&&N.type==="api")return N.baseUrl?Ha(N.baseUrl,t)?(ee?.commit(),a(o,508,{error:{message:`destination "${N.id}" points back at the gateway (${N.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):es(n,o,{...J,pathname:i,search:g.search,base:N.baseUrl,destKey:N.apiKey,destProtocol:N.protocol,harness:At,trace:ee},Se,F):(ee?.commit(),a(o,502,{error:`destination "${N.id}" has no baseUrl`}));const nt=De(n),Mt=nt==="local"&&t.bridge?.openAgentLane?"token":nt;if(Mt==="local")return ee?.commit(),a(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const Dt=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),Mo=new Set(["thread","ephemeral","workingDir"]),at=me?.kind==="partner";if(nt==="token"&&n.headers["x-chatpanel-link-device"]&&!at&&!(te.run&&Object.keys(te.run).some(e=>!Mo.has(e)))){const e=Ot(null,Zt(Yt(ae.get("agentTools").agentTools?.value,N?.agent||T?.model)));e&&(te.run={...e,...te.run||{}})}if(at){const e=Ot(null,Zt(Yt(ae.get("agentTools").agentTools?.value,N?.agent||T?.model)));te.run={...e||{},...Rn(te.run,me.device)};const r=y?.partnerFolderOf(me.device);if(!r)return ee?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});te.run.workingDir=r,te.reach="",Array.isArray(T?.tools)&&(T.tools=T.tools.filter(s=>!ro(s?.function?.name??s?.name)))}const Ne=Yo({...te.run||{},...te.reach?{reach:te.reach}:{},...Dt?{askDepth:Dt}:{}},Mt);Ne.reach&&o.setHeader("x-chatpanel-reach-used",Ne.reach);const Do=at?{inbox:f,partner:me.partner,device:me.device,conversation:Ne.thread?.id||null}:null;return Qa(n,o,{...J,pathname:i,agentOverride:N?.agent,harness:At,trace:ee,run:Object.keys(Ne).length?Ne:null,owner:Do},T,F,t,Ee)});return de.on("close",()=>{O?.stop("closed"),kn(),m.close(),y?.stop(),f.stop()}),de.on("upgrade",(n,o,g)=>{o.on("error",()=>{});const i=String(n.url||"").split("?")[0];if(y&&i.startsWith(Dn)){y.acceptTunnel(n,o,g).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
60
+ `);try{const i=await br({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:c=>s(c.kind,{kind:c.kind,task:c.task,message:c.message})});s("done",i)}catch(i){s("error",{code:i.code||"ERROR",message:i.message})}return o.end()}if(n.method==="POST"&&l==="/a2a/task"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Ze(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await vr({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await kr({card:r,id:String(e.id||""),auth:String(e.auth||"")});return a(o,200,{ok:!0,...s})}return a(o,404,{error:{message:`no such a2a route: ${l}`,type:"invalid_request"}})}catch(e){const r=e instanceof Ut||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof Ut&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(l==="/agent-defs/export"||l==="/agent-defs/export-plan"))return U(n)?ve(n,o,t,l,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(l)){const e=decodeURIComponent(l.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):ve(n,o,t,`/skills/${encodeURIComponent(e)}${Be(g,t)}`,{pick:r=>({skill:r?.skill||null})})}if(l==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(l)){if(!U(n))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(l==="/channels"&&n.method==="GET"||l!=="/channels"&&n.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await Re(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=je(t.bridge?.token);try{const s=n.method==="POST"?(await T(n,t.maxBodyBytes)).toString("utf8"):"",i=await fetch(`${e}${l}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),c=await i.json().catch(()=>({}));return a(o,i.status,c)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(l)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(l),r=decodeURIComponent(e[1]),s=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):ve(n,o,t,`/skills/${encodeURIComponent(r)}/file/${s}${Be(g,t)}`)}if(n.method==="GET"&&/\/models$/.test(l)){const e=await J(),r=e.sig!==void 0&&e.sig!==C;return C=e.sig,a(o,200,await Ca(t,{serviceHealth:async()=>e,fresh:r,engineAt:d.engineAt}))}if(ds.some(e=>l===e||l.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${le}) has no ${l} — update it to use this feature`,type:"unknown_endpoint"}});const W=Xa(l,n.headers,t);let ge;try{ge=await T(n,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let ue=null,k=null,re=ge,ne=0,he=0,He=0,we=!1,Ee=!1,Nt="",$e=!0;const ee=t.logRequests&&W.redactable&&n.method==="POST"?Za(F):null,Io=Date.now();if(W.redactable&&n.method==="POST"&&ge.length){try{k=JSON.parse(ge.toString("utf8"))}catch{k=null}if(k&&qa(k,W.kind))re=ge;else if(k){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(k.tools)&&k.tools.length){const w=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Ha,b=e.narrowAll?null:_=>!Ua.test(Oo(_)),A=k.tools.length;k.tools=Yo(k.tools,Fa(k,W.kind),{cap:w,keep:b,name:Oo,description:Va}),He=A-k.tools.length}$e=await Se(t.pro?.entitlementToken);const r=Ea(t,$e);if(!r.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${r.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});if(we=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&U(n),!we){const w=nt(k?.model,t,W.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:()=>!1}),b=w?.type==="api"?await d.decide(w,k?.model).catch(()=>null):null;Ee=b?.redact===!1,Nt=Ee?b.engine||"declared":""}!we&&!Ee&&await qe(t);const s=we?[]:W.adapter.collectSegments(k,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const c=ee?ee.clock():0,{vault:p,count:h,sanitized:S}=we?{vault:null,count:0,sanitized:0}:await Ke(s,t.redaction,{signal:i.signal,isPro:$e,sanitizeOnly:Ee,onEgress:w=>Tt.push(So({ts:Date.now(),client:"redaction",tool:`detect:${w.backend}@${w.host||"local"}`,ok:w.ok,ms:w.ms,error:w.error}))});if(ee&&ee.lap("redact",c),ue=p,ne=h,he=S||0,h>0&&o.setHeader("x-chatpanel-redacted",String(h)),!$e&&h>0){$a(t,$e);try{ke(t,ie())}catch{}}if(!we&&!Ee&&Array.isArray(k.tools)&&k.tools.length&&typeof W.adapter.injectSystemNote=="function"){const w=nt(k?.model,t,W.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:A=>!!A.service&&x.fn(A.id)==="down"}),b=!(w&&w.type==="api");W.adapter.injectSystemNote(k,Xo({toolData:t.tools?.toolData,ownTools:b}))}else!we&&h>0&&typeof W.adapter.injectSystemNote=="function"&&W.adapter.injectSystemNote(k,qo());re=Buffer.from(JSON.stringify(k),"utf8")}}const Bt=Zo({vault:ue,toolData:t.tools?.toolData}),Ue=k&&typeof k.chatpanel=="object"&&k.chatpanel||null;if(Ue&&(delete k.chatpanel,re=Buffer.from(JSON.stringify(k),"utf8")),typeof k?.model=="string"&&k.model.startsWith("fusion:")){const e=kn(k.model,t,await J());if(e?.error)return ee?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(k.model=e.model,re=Buffer.from(JSON.stringify(k),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const te={destination:String(n.headers["x-chatpanel-destination"]||Ue?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Ue?.reach||"").trim(),run:At(n.headers["x-chatpanel-run"],Ue?.run)},Ve=await J(),Dt=e=>!!e.service&&Ve(e.id)==="down";let P=nt(k?.model,t,W.kind,{destination:te.destination,down:Dt});P?.type==="agent"&&k?.model&&!te.destination&&!ja(P,k.model)&&(await Ra(t,{serviceHealth:async()=>Ve,engineAt:d.engineAt}),P=nt(k?.model,t,W.kind,{destination:te.destination,down:Dt}));const Mt=P?.service&&Ve(P.id)==="down"?await E().revive(P.service).catch(()=>null):null;if(Mt?.ok&&(x.at=0),P?.service&&Ve(P.id)==="down"&&!Mt?.ok)return ee?.commit(),a(o,503,{error:{message:`${P.id} is not running — the model ${JSON.stringify(k?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:P.service}});if(te.destination&&(!P||P.id!==te.destination))return ee?.commit(),a(o,404,{error:{message:`no destination "${te.destination}" is configured on this gateway`,type:"unknown_destination",known:Ia(t).map(e=>e.id)}});const ae=no(n.headers);if(ae&&!Vn(ae,P?.type==="api"?"api":"agent"))return ee?.commit(),a(o,403,{error:{message:`link: partner "${ae.partner}" may not use ${P?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${ae.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const Fe=ae&&W.redactable&&n.method==="POST"&&k?{caller:ae,surface:mn(ae,ae.kind==="partner"?"":y?.deviceNameOf(ae.device)),model:k.model||null,startedAt:Io}:null;ee&&(ee.meta={t:Date.now(),model:k?.model||null,dest:P?P.id:null,type:P?P.type:null,redacted:ne,sanitized:he,narrowed:He,detail:Ao(ue,t.logDetail),redaction:we?"off":Ee?`on-device (${Nt})`:t.redaction.tier||"basic",...ae?.kind==="partner"?{via:Fn(ae)}:{}});const We=Qe();if(We&&P){const e=P.type==="api"?Ht(We,{model:k?.model||"",endpoint:P.baseUrl||""}):yr(We,P.agent||P.id)?Ht(We,{model:k?.model||""}):{ok:!1,reason:`agent "${P.agent||P.id}" is not allowed by your organisation’s policy`};if(!e.ok)return ee?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(P&&P.type==="api")return P.baseUrl?es(P.baseUrl,t)?(ee?.commit(),a(o,508,{error:{message:`destination "${P.id}" points back at the gateway (${P.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):cs(n,o,{...W,pathname:l,search:g.search,base:P.baseUrl,destKey:P.apiKey,destProtocol:P.protocol,harness:Bt,trace:ee,link:Fe&&{...Fe,agentId:P.id,dest:{type:"api",id:P.id}}},re,ue):(ee?.commit(),a(o,502,{error:`destination "${P.id}" has no baseUrl`}));const it=Ce(n),Ct=it==="local"&&t.bridge?.openAgentLane?"token":it;if(Ct==="local")return ee?.commit(),a(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const It=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),Ro=new Set(["thread","ephemeral","workingDir"]),lt=ae?.kind==="partner";if(it==="token"&&n.headers["x-chatpanel-link-device"]&&!lt&&!(te.run&&Object.keys(te.run).some(e=>!Ro.has(e)))){const e=At(null,qt(Xt(de.get("agentTools").agentTools?.value,P?.agent||k?.model)));e&&(te.run={...e,...te.run||{}})}if(lt){const e=At(null,qt(Xt(de.get("agentTools").agentTools?.value,P?.agent||k?.model)));te.run={...e||{},...Wn(te.run,ae.device)};const r=y?.partnerFolderOf(ae.device);if(!r)return ee?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});te.run.workingDir=r,te.reach="",Array.isArray(k?.tools)&&(k.tools=k.tools.filter(s=>!so(s?.function?.name??s?.name)))}const Pe=tr({...te.run||{},...te.reach?{reach:te.reach}:{},...It?{askDepth:It}:{}},Ct);Pe.reach&&o.setHeader("x-chatpanel-reach-used",Pe.reach);const jo=lt?{inbox:f,partner:ae.partner,device:ae.device,conversation:Pe.thread?.id||null}:null,Lo=Fe&&{...Fe,dest:{type:"agent",id:P?.id||"bridge"},threadId:Pe.thread?.id||null};return as(n,o,{...W,pathname:l,agentOverride:P?.agent,harness:Bt,trace:ee,run:Object.keys(Pe).length?Pe:null,owner:jo,link:Lo},k,ue,t,$e)});return I.on("close",()=>{O?.stop("closed"),An(),m.close(),y?.stop(),f.stop()}),I.on("upgrade",(n,o,g)=>{o.on("error",()=>{});const l=String(n.url||"").split("?")[0];if(y&&l.startsWith(Un)){y.acceptTunnel(n,o,g).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
61
61
  connection: close\r
62
62
  content-length: 0\r
63
63
  \r
64
- `)}catch{}}),de.once("listening",()=>{$()}),de.linkHost=y,de.runtimeDefaults=()=>$().ensureDefaults(),de}function Ot(t,d){let u=d&&typeof d=="object"?d:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const m={};if(Array.isArray(u.grants)&&(m.grants=u.grants.map(y=>String(y).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const y=u.workspace;m.workspace={repo:String(y.repo).slice(0,400),projectId:String(y.projectId||"").slice(0,120),jobId:String(y.jobId||"").slice(0,120),...y.base?{base:String(y.base).slice(0,120)}:{}}}if(u.connectionId&&(m.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(m.workingDir=u.workingDir.trim().slice(0,1024)),Sa.includes(u.permissionMode)&&u.permissionMode!=="default"&&(m.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const y=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(k=>String(k).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),E=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(k=>String(k).slice(0,1024)).filter(Boolean).slice(0,32),A=u.sandbox.outside===!0,O=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(k=>String(k).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(y.length||E.length||A||O.length)&&(m.sandbox={...y.length?{hosts:y}:{},...E.length?{write:E}:{},...A?{outside:!0}:{},...O.length?{signIn:O}:{}})}const f=Nr(u.thread);return f&&(m.thread=f),u.ephemeral===!0&&(m.ephemeral=!0),Object.keys(m).length?m:null}let ze=null,rt=null;async function Ji(t=Ct()){Or();let d=null;try{d=await lr()}catch(k){throw k instanceof dr&&(console.error(`[chatpanel-gateway] org policy: ${k.message}`),process.exit(78)),k}const u=d?.policy||null;u&&(Jt(t,u),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`));const m=sr({enabled:Lt(t)});console.log(`[chatpanel-gateway] certificates: ${m.on?`this computer's list is trusted too (${m.added} added to the runtime's own)`:`the runtime's own list only — ${m.why}`}`),nr(globalThis,{allow:u?.egress?(k,{local:_})=>ur(u,k,{local:_}):null}),Te();const f=ts(t),y=Tr(t),E=jo(t);let A=!1;f.on("error",k=>{if(k&&k.code==="EADDRINUSE"){const _=ot(t.host)?"127.0.0.1":t.host;fetch(`http://${_}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(D=>D.ok?D.json():null).catch(()=>null).then(D=>{const z=!!(D?.version&&typeof D.tier=="string"),j=Br({name:"gateway",self:ne,holder:z?{ours:z,version:D.version}:null,managedBy:Mr(process.env),port:t.port});if(j.action==="standby"||A&&!D){if(!A)for(const $ of j.lines)console.error($);A=!0,setTimeout(()=>f.listen(t.port,t.host),Dr);return}if(z){const $=D.managedBy?` (run by ${D.managedBy})`:"";for(const[U,K]of j.lines.entries())console.error(U===0?K.replace(` on ${t.port}`,` at http://${_}:${t.port}${$}`):K)}else{const $=Kr(t.port);console.error(`Port ${t.port} is held by ${$||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${re()} (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: ${k?.message||k}`),process.exit(1)}),f.listen(t.port,t.host,()=>{A&&console.log(" standby : the other gateway is gone — this copy has the port now"),A=!1,console.log(`ChatPanel Privacy Gateway v${ne} on http://${t.host}:${t.port}`),f.linkHost?.start().catch(k=>console.log(` link : not started (${k?.message||k})`)),f.runtimeDefaults?.().then(k=>{for(const _ of k||[])console.log(` ${_.label.toLowerCase().padEnd(9).slice(0,9)}: ${_.ok?_.already?"running":_.adopted?"already running — adopted":"started":`not started (${_.skipped})`}`)}).catch(k=>console.log(` runtime : defaults not started (${k?.message||k})`)),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 k of xa(t))console.log(` ⚠ sandbox : ${k}`);console.log(` confined : ${en(ct({stateDir:Le.dirname(re())}))}`),rt={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},Wr(t,{childEnv:()=>({...Ta(t,process.env,Fe()),...va(t)})}).then(k=>{ze=k}).catch(k=>{rt={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${k?.message||k})`},console.log(` bridge : not supervised (${k?.message||k})`)}),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…)":"")),ot(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.`)}),Qt()&&mt(R,lt()).then(k=>{k?.ok&&(console.log(` warm : seeded ${k.ingested} records from ${k.file}`),k.whole&&Je())}).catch(()=>{});const O=()=>{y?.stop(),E.stop(),ze?.stop(),Ba(f)};return process.on("SIGINT",O),process.on("SIGTERM",O),f}export{Va as RECORDS_MAX_BYTES,Ui as VERSION,ts as createGateway,Ya as joinUpstream,kt as parseAgentModel,Ji as start};
64
+ `)}catch{}}),I.once("listening",()=>{E()}),I.linkHost=y,I.runtimeDefaults=()=>E().ensureDefaults(),I}function At(t,d){let u=d&&typeof d=="object"?d:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const m={};if(Array.isArray(u.grants)&&(m.grants=u.grants.map(y=>String(y).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const y=u.workspace;m.workspace={repo:String(y.repo).slice(0,400),projectId:String(y.projectId||"").slice(0,120),jobId:String(y.jobId||"").slice(0,120),...y.base?{base:String(y.base).slice(0,120)}:{}}}if(u.connectionId&&(m.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(m.workingDir=u.workingDir.trim().slice(0,1024)),Ba.includes(u.permissionMode)&&u.permissionMode!=="default"&&(m.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const y=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(v=>String(v).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),$=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(v=>String(v).slice(0,1024)).filter(Boolean).slice(0,32),N=u.sandbox.outside===!0,O=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(v=>String(v).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(y.length||$.length||N||O.length)&&(m.sandbox={...y.length?{hosts:y}:{},...$.length?{write:$}:{},...N?{outside:!0}:{},...O.length?{signIn:O}:{}})}const f=Ir(u.thread);return f&&(m.thread=f),u.ephemeral===!0&&(m.ephemeral=!0),Object.keys(m).length?m:null}let Ge=null,st=null;async function Zi(t=Rt()){Nr();let d=null;try{d=await pr()}catch(v){throw v instanceof hr&&(console.error(`[chatpanel-gateway] org policy: ${v.message}`),process.exit(78)),v}const u=d?.policy||null;u&&(Gt(t,u),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`));const m=ur({enabled:zt(t)});console.log(`[chatpanel-gateway] certificates: ${m.on?`this computer's list is trusted too (${m.added} added to the runtime's own)`:`the runtime's own list only — ${m.why}`}`),dr(globalThis,{allow:u?.egress?(v,{local:x})=>fr(u,v,{local:x}):null}),_e();const f=us(t),y=$r(t),$=Ho(t);let N=!1;f.on("error",v=>{if(v&&v.code==="EADDRINUSE"){const x=at(t.host)?"127.0.0.1":t.host;fetch(`http://${x}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(C=>C.ok?C.json():null).catch(()=>null).then(C=>{const J=!!(C?.version&&typeof C.tier=="string"),H=Rr({name:"gateway",self:le,holder:J?{ours:J,version:C.version}:null,managedBy:jr(process.env),port:t.port});if(H.action==="standby"||N&&!C){if(!N)for(const E of H.lines)console.error(E);N=!0,setTimeout(()=>f.listen(t.port,t.host),Lr);return}if(J){const E=C.managedBy?` (run by ${C.managedBy})`:"";for(const[G,z]of H.lines.entries())console.error(G===0?z.replace(` on ${t.port}`,` at http://${x}:${t.port}${E}`):z)}else{const E=qr(t.port);console.error(`Port ${t.port} is held by ${E||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${ie()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${v?.message||v}`),process.exit(1)}),f.listen(t.port,t.host,()=>{N&&console.log(" standby : the other gateway is gone — this copy has the port now"),N=!1,console.log(`ChatPanel Privacy Gateway v${le} on http://${t.host}:${t.port}`),f.linkHost?.start().catch(v=>console.log(` link : not started (${v?.message||v})`)),f.runtimeDefaults?.().then(v=>{for(const x of v||[])console.log(` ${x.label.toLowerCase().padEnd(9).slice(0,9)}: ${x.ok?x.already?"running":x.adopted?"already running — adopted":"started":`not started (${x.skipped})`}`)}).catch(v=>console.log(` runtime : defaults not started (${v?.message||v})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token");for(const v of Ma(t))console.log(` ⚠ sandbox : ${v}`);console.log(` confined : ${an(pt({stateDir:Je.dirname(ie())}))}`),st={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},Xr(t,{childEnv:()=>({...Da(t,process.env,Qe()),...Na(t)})}).then(v=>{Ge=v}).catch(v=>{st={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${v?.message||v})`},console.log(` bridge : not supervised (${v?.message||v})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),at(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.`)}),Zt()&&yt(j,ut()).then(v=>{v?.ok&&(console.log(` warm : seeded ${v.ingested} records from ${v.file}`),v.whole&&ze())}).catch(()=>{});const O=()=>{y?.stop(),$.stop(),Ge?.stop(),Ga(f)};return process.on("SIGINT",O),process.on("SIGTERM",O),f}export{ts as RECORDS_MAX_BYTES,el as VERSION,us as createGateway,ss as joinUpstream,xt as parseAgentModel,Zi as start};
package/src/toolrelay.js CHANGED
@@ -1,4 +1,4 @@
1
- import{randomUUID as x}from"node:crypto";import{restoreDeep as f,redactText as m,createVault as I}from"@chatpanel/pii";import{PERMISSION_TOOL_NAME as T,isPermissionTool as y,permissionAllowed as w}from"@chatpanel/events/agent-permission.js";const a=new Map,g=(e,t)=>`gwtr_${e}_${t}`;function P(e){const t=/^gwtr_([^_]+)_(.+)$/.exec(String(e||""));return t?{gwId:t[1],toolId:t[2]}:null}function N(e){return(Array.isArray(e)?e:[]).filter(t=>t&&t.type==="function"&&t.function?.name&&!y(t.function.name)).map(t=>({name:t.function.name,description:t.function.description||"",parameters:t.function.parameters||{type:"object",properties:{}}}))}function $(e){return(Array.isArray(e)?e:[]).some(t=>t?.type==="function"&&y(t.function?.name))}const O=2e5;function k({vault:e,redactOpts:t,bridgeUrl:n,token:r,harness:l=null,idleMs:c=O}){const i=x().slice(0,8),s={id:i,reader:null,decoder:new TextDecoder,buf:"",bridgeSessionId:null,toolId:null,vault:e||I(),redactOpts:t||{tier:"basic"},bridgeUrl:n,token:r,harness:l,done:!1,idleMs:c,ttl:null,startedAt:Date.now(),rounds:0};return a.set(i,s),b(i),s}const q=e=>a.get(e);function b(e){const t=a.get(e);t&&(t.ttl&&clearTimeout(t.ttl),t.ttl=setTimeout(()=>_(e),t.idleMs),typeof t.ttl.unref=="function"&&t.ttl.unref())}function _(e){const t=a.get(e);if(t?.ttl&&clearTimeout(t.ttl),t?.reader)try{t.reader.cancel()}catch{}a.delete(e)}async function M(e,t){for(;;){let n;for(;(n=e.buf.indexOf(`
1
+ import{randomUUID as x}from"node:crypto";import{restoreDeep as f,redactText as m,createVault as I}from"@chatpanel/pii";import{PERMISSION_TOOL_NAME as T,isPermissionTool as y,permissionAllowed as w}from"@chatpanel/events/agent-permission.js";const a=new Map,g=(e,t)=>`gwtr_${e}_${t}`;function P(e){const t=/^gwtr_([^_]+)_(.+)$/.exec(String(e||""));return t?{gwId:t[1],toolId:t[2]}:null}function N(e){return(Array.isArray(e)?e:[]).filter(t=>t&&t.type==="function"&&t.function?.name&&!y(t.function.name)).map(t=>({name:t.function.name,description:t.function.description||"",parameters:t.function.parameters||{type:"object",properties:{}}}))}function $(e){return(Array.isArray(e)?e:[]).some(t=>t?.type==="function"&&y(t.function?.name))}const O=2e5;function k({vault:e,redactOpts:t,bridgeUrl:n,token:r,harness:l=null,idleMs:c=O}){const i=x().slice(0,8),s={id:i,reader:null,decoder:new TextDecoder,buf:"",bridgeSessionId:null,toolId:null,vault:e||I(),redactOpts:t||{tier:"basic"},bridgeUrl:n,token:r,harness:l,done:!1,idleMs:c,ttl:null,startedAt:Date.now(),rounds:0};return a.set(i,s),b(i),s}const q=e=>a.get(e);function b(e){const t=a.get(e);t&&(t.ttl&&clearTimeout(t.ttl),t.ttl=setTimeout(()=>h(e),t.idleMs),typeof t.ttl.unref=="function"&&t.ttl.unref())}function h(e){const t=a.get(e);if(t?.ttl&&clearTimeout(t.ttl),t?.reader)try{t.reader.cancel()}catch{}if(a.delete(e),t?.onEnd)try{t.onEnd()}catch{}}async function M(e,t){for(;;){let n;for(;(n=e.buf.indexOf(`
2
2
 
3
3
  `))!==-1;){const c=e.buf.slice(0,n);e.buf=e.buf.slice(n+2);for(const i of c.split(`
4
- `)){const s=i.trim();if(!s.startsWith("data:"))continue;const u=s.slice(5).trim();if(!u||u==="[DONE]")continue;let o;try{o=JSON.parse(u)}catch{continue}if(b(e.id),o.type==="delta"&&typeof o.text=="string")t.onText(o.text);else if(o.type==="permission_request"){e.bridgeSessionId=o.session,e.toolId=o.id,e.pendingPermission=!0;const{type:d,session:v,id:A,...p}=o,S={...p,input:f(p.input??{},e.vault)};return t.onToolRequest({name:T,restoredArgs:S,toolId:g(e.id,o.id)}),"parked"}else if(o.type==="tool_request"){e.bridgeSessionId=o.session,e.toolId=o.id,e.pendingPermission=!1;const d=e.harness?e.harness.toTool(o.name,o.input??{}):f(o.input??{},e.vault);return t.onToolRequest({name:o.name,restoredArgs:d,toolId:g(e.id,o.id)}),"parked"}else{if(o.type==="done")return e.done=!0,t.onDone?.(),"done";if(o.type==="error")return t.onError?.(new Error(o.error||"bridge error")),"done";o.type==="usage"&&t.onUsage?.(o)}}}const{done:r,value:l}=await e.reader.read();if(r)return e.done=!0,t.onDone?.(),"done";e.buf+=e.decoder.decode(l,{stream:!0})}}async function J(e,t){const n=e.pendingPermission?h(t,e):m(typeof t=="string"?t:JSON.stringify(t),e.vault,e.redactOpts);e.pendingPermission=!1;const r=await fetch(`${e.bridgeUrl.replace(/\/$/,"")}/tool-result`,{method:"POST",headers:{"content-type":"application/json",...e.token?{authorization:`Bearer ${e.token}`}:{}},body:JSON.stringify({session:e.bridgeSessionId,id:e.toolId,result:n})});if(!r.ok)throw new Error(`bridge /tool-result HTTP ${r.status}`)}function h(e,t){let n=e;if(typeof n=="string")try{n=JSON.parse(n)}catch{n=null}if(!w(n)){const r=n&&typeof n=="object"&&typeof n.message=="string"&&n.message?m(n.message,t.vault,t.redactOpts):"";return{behavior:"deny",scope:"once",...r?{message:r}:{}}}return{behavior:"allow",scope:n.scope==="chat"?"chat":"once"}}export{O as RELAY_IDLE_MS,k as createRelaySession,J as deliverToolResult,_ as endRelaySession,q as getRelaySession,P as parseToolCallId,h as permissionResultOf,M as pumpBridgeStream,N as toolsToSpecs,b as touchRelaySession,$ as wantsApprovals};
4
+ `)){const s=i.trim();if(!s.startsWith("data:"))continue;const u=s.slice(5).trim();if(!u||u==="[DONE]")continue;let o;try{o=JSON.parse(u)}catch{continue}if(b(e.id),o.type==="delta"&&typeof o.text=="string")t.onText(o.text);else if(o.type==="permission_request"){e.bridgeSessionId=o.session,e.toolId=o.id,e.pendingPermission=!0;const{type:d,session:v,id:A,...p}=o,S={...p,input:f(p.input??{},e.vault)};return t.onToolRequest({name:T,restoredArgs:S,toolId:g(e.id,o.id)}),"parked"}else if(o.type==="tool_request"){e.bridgeSessionId=o.session,e.toolId=o.id,e.pendingPermission=!1;const d=e.harness?e.harness.toTool(o.name,o.input??{}):f(o.input??{},e.vault);return t.onToolRequest({name:o.name,restoredArgs:d,toolId:g(e.id,o.id)}),"parked"}else{if(o.type==="done")return e.done=!0,t.onDone?.(),"done";if(o.type==="error")return t.onError?.(new Error(o.error||"bridge error")),"done";o.type==="usage"&&t.onUsage?.(o)}}}const{done:r,value:l}=await e.reader.read();if(r)return e.done=!0,t.onDone?.(),"done";e.buf+=e.decoder.decode(l,{stream:!0})}}async function J(e,t){const n=e.pendingPermission?_(t,e):m(typeof t=="string"?t:JSON.stringify(t),e.vault,e.redactOpts);e.pendingPermission=!1;const r=await fetch(`${e.bridgeUrl.replace(/\/$/,"")}/tool-result`,{method:"POST",headers:{"content-type":"application/json",...e.token?{authorization:`Bearer ${e.token}`}:{}},body:JSON.stringify({session:e.bridgeSessionId,id:e.toolId,result:n})});if(!r.ok)throw new Error(`bridge /tool-result HTTP ${r.status}`)}function _(e,t){let n=e;if(typeof n=="string")try{n=JSON.parse(n)}catch{n=null}if(!w(n)){const r=n&&typeof n=="object"&&typeof n.message=="string"&&n.message?m(n.message,t.vault,t.redactOpts):"";return{behavior:"deny",scope:"once",...r?{message:r}:{}}}return{behavior:"allow",scope:n.scope==="chat"?"chat":"once"}}export{O as RELAY_IDLE_MS,k as createRelaySession,J as deliverToolResult,h as endRelaySession,q as getRelaySession,P as parseToolCallId,_ as permissionResultOf,M as pumpBridgeStream,N as toolsToSpecs,b as touchRelaySession,$ as wantsApprovals};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.97.2";export{o as VERSION};
1
+ const o="0.98.0";export{o as VERSION};