@chatpanel/gateway 0.11.14 → 0.17.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.
@@ -0,0 +1,3 @@
1
+ const w="remote";function p(s){const r=String(s||""),a=r.split(/\n\n/,1)[0],n={};for(const l of a.split(`
2
+ `)){const o=/^([A-Za-z ]+):\s*(.*)$/.exec(l);o&&(n[o[1].trim().toLowerCase()]=o[2].trim())}const c=r.search(/\n(Markdown|Text) Content:\n/),d=c>=0?r.slice(r.indexOf(`
3
+ `,c+1)+1):r.slice(a.length).trim();return{title:n.title||"",url:n["url source"]||"",published:n["published time"]||"",author:n.author||"",markdown:d.trim()}}async function x({url:s,base:r,key:a="",fetchFn:n,signal:c,format:d="markdown"}){const l=String(r).replace(/\/?$/,"/")+s,o={Accept:"application/json, text/plain;q=0.9","X-Return-Format":d==="text"?"text":"markdown"};a&&(o.Authorization=`Bearer ${a}`);const i=await n(l,{headers:o,signal:c});if(!i.ok){const t=new Error(`remote reader answered HTTP ${i.status}`);throw t.status=i.status,t}const h=i.headers.get("content-type")||"",u=await i.text();if(/json/i.test(h)){let t;try{t=JSON.parse(u)}catch{throw new Error("remote reader: JSON promised, not delivered")}const e=t?.data||t;if(t?.code&&!e?.content)throw new Error(`remote reader: ${t.message||t.code}`);return{title:e.title||"",url:e.url||s,published:e.publishedTime||e.published||"",author:e.author||"",markdown:String(e.content||e.text||"").trim()}}const m=p(u);return{...m,url:m.url||s}}export{w as PROVIDER_ID,x as readRemote};
@@ -0,0 +1,5 @@
1
+ const f=2e6,m=200,a={amp:"&",lt:"<",gt:">",quot:'"',"#39":"'",apos:"'",nbsp:" ",middot:"·",hellip:"…",mdash:"—",ndash:"–",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",copy:"©",reg:"®",trade:"™",bull:"•",laquo:"«",raquo:"»",times:"×",deg:"°"};function u(r){return String(r).replace(/&(#x?[0-9a-f]+|[a-z]+);/gi,(n,t)=>{const e=t.toLowerCase();return a[e]?a[e]:e.startsWith("#x")?String.fromCodePoint(parseInt(e.slice(2),16)||32):e.startsWith("#")?String.fromCodePoint(parseInt(e.slice(1),10)||32):n})}const c=["script","style","noscript","svg","template","header","footer","nav","aside","form","button","dialog","iframe","select"],d=/<(p|div|li|ul|ol|h[1-6]|br|hr|tr|td|th|table|section|article|blockquote|pre|dd|dt|dl|figcaption)\b[^>]*>/gi;function l(r,n){let t=r;for(const e of n)t=t.replace(new RegExp(`<${e}\\b[^>]*>[\\s\\S]*?<\\/${e}\\s*>`,"gi")," ");return t}const s=r=>r.replace(/<!--[\s\S]*?-->/g," ").replace(d,`
2
+ `).replace(/<[^>]+>/g," "),i=r=>u(r).replace(/[ \t\r\f\v]+/g," ").replace(/ *\n */g,`
3
+ `).replace(/\n{3,}/g,`
4
+
5
+ `).trim();function g(r){for(const t of["main","article"]){const e=new RegExp(`<${t}\\b[^>]*>([\\s\\S]*?)<\\/${t}\\s*>`,"i").exec(r);if(!e)continue;const o=i(s(l(e[1],c)));if(o.length>200)return o}const n=/<[a-z][^>]*\brole=["']main["'][^>]*>([\s\S]*?)<\/(?:div|section)\s*>/i.exec(r);if(n){const t=i(s(l(n[1],c)));if(t.length>200)return t}return null}function x(r){const n=String(r||"").slice(0,2e6),t=/<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n),e=t?i(s(t[1])).replace(/\s+/g," ").trim():"",o=l(n,c),p=g(o)||i(s(o));return{title:e,text:p}}const S="text";export{m as MIN_READABLE_CHARS,S as PROVIDER_ID,u as decodeEntities,x as readableFromHtml};
@@ -0,0 +1 @@
1
+ import{secureFetch as J}from"../secure-fetch.js";import{validateReadRequest as Y,validateReadResponse as F,overBudget as Q}from"../capability-endpoints.js";import{createHostBudget as Z,restrictionOf as V}from"../site-policy.js";import{canonicalUrl as E,headingIds as q,sectionsOf as I,truncateAtSection as tt}from"../read-document.js";import{createPageCache as et}from"./page-cache.js";import{extractWithDefuddle as rt,PROVIDER_ID as L}from"./read-defuddle.js";import{readableFromHtml as at,MIN_READABLE_CHARS as st,PROVIDER_ID as T}from"./read-text.js";import{readRemote as ot,PROVIDER_ID as O}from"./read-remote.js";const H=Object.freeze({timeoutMs:12e3,maxHtmlBytes:2e6,maxChars:4e4}),nt=Object.freeze({allowLoopback:!1,allowPrivate:!1}),it=Object.freeze({Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.5","Accept-Language":"en-US,en;q=0.9","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36"});function ct({keep:l=50}={}){const e=[];return{record(o,f){e.push({ms:o,chars:f}),e.length>l&&e.shift()},stats(){if(!e.length)return{calls:0};const o=e.map(u=>u.ms).sort((u,i)=>u-i),f=e.reduce((u,i)=>u+i.chars,0),h=e.reduce((u,i)=>u+i.ms,0);return{calls:e.length,p50Ms:o[Math.floor(o.length/2)],p95Ms:o[Math.min(o.length-1,Math.floor(o.length*.95))],charsPerSec:h?Math.round(f/h*1e3):0}}}}const $=l=>(String(l||"").match(/\S+/g)||[]).length,B=l=>{try{return new URL(l).hostname.toLowerCase()}catch{return""}},p=(l,e,o)=>({status:l,body:{error:{type:e,message:o}}});async function dt(l,e){const o=l.body?.getReader?.();if(!o){const i=await l.text();return{text:i.slice(0,e),capped:i.length>e}}const f=[];let h=0;for(;;){const{done:i,value:_}=await o.read();if(i)break;if(h+=_.byteLength,f.push(_),h>=e){try{await o.cancel()}catch{}break}}return{text:Buffer.concat(f.map(i=>Buffer.from(i.buffer,i.byteOffset,i.byteLength))).subarray(0,e).toString("utf8"),capped:h>e}}function yt({fetchFn:l=J,now:e=()=>Date.now(),cache:o=et({now:e}),budget:f=Z({now:e}),stats:h=ct(),remote:u=null,defaultProvider:i=L,extract:_=rt,timeoutMs:k=H.timeoutMs,maxHtmlBytes:N=H.maxHtmlBytes}={}){const A=()=>[L,T,...u?.url?[O]:[]];function v(t,r,{cached:n,ms:c,restricted:a=null}){const d=r.format==="text"?t.text:t.markdown,m=r.format==="text"?[]:t.sections,{text:b,truncated:s}=tt(d,r.maxChars||H.maxChars,m),M={url:t.url,requested:r.url,title:t.title,author:t.author||void 0,published:t.published||void 0,site:B(t.url),lang:t.lang||void 0,format:r.format,[r.format]:b,chars:b.length,truncated:s,sections:m.filter(S=>S.offset<=b.length),fetched:new Date(t.fetchedAt).toISOString(),cached:n,provider:t.provider,ms:c,restricted:a};return{status:200,body:F(M)}}function R(t,r,{provider:n,ms:c}){const a=String(t.snippet||""),d={url:t.url,requested:t.url,title:"",site:B(t.url),format:t.format,[t.format]:a,chars:a.length,truncated:!1,sections:[],fetched:new Date(e()).toISOString(),cached:!1,provider:n,ms:c,restricted:r};return{status:200,body:F(d)}}async function W(t,r,n){const c={...it};return r?.etag&&(c["If-None-Match"]=r.etag),r?.lastModified&&(c["If-Modified-Since"]=r.lastModified),l(t.url,{policy:nt,headers:c,signal:n})}async function K(t,r){const n=B(t.url),c=f.holdFor(n);if(c>0)return R(t,{reason:"rate_limited",detail:`${n} asked us to wait ${Math.ceil(c/1e3)} s more`},{provider:i,ms:Math.round(e()-r)});const a=o.get(t.url);if(a&&!a.stale)return v(a.doc,t,{cached:!0,ms:Math.round(e()-r)});const d=await f.acquire(n),m=new AbortController,b=setTimeout(()=>m.abort(),Math.min(k,t.budgetMs>0?t.budgetMs:k));let s;try{s=await W(t,a?.stale?a:null,m.signal)}catch(M){return clearTimeout(b),d(),m.signal.aborted?p(504,"fetch_timeout",`${n} did not answer within the budget`):p(502,/blocked|refusing|private|loopback/i.test(M.message)?"blocked_host":"fetch_failed",M.message)}try{if(s.status===304&&a)return o.revalidated(t.url),v(a.doc,t,{cached:!0,ms:Math.round(e()-r)});const M=s.url||t.url;(s.status===429||s.status===503)&&f.noteRetryAfter(n,s.headers.get("retry-after"));const S=V({status:s.status,headers:s.headers});if(S)return R(t,S,{provider:i,ms:Math.round(e()-r)});if(!s.ok)return p(502,"fetch_failed",`${n} answered HTTP ${s.status}`);const D=(s.headers.get("content-type")||"").toLowerCase();if(D&&!/html|xml|text\/plain|markdown/.test(D))return p(415,"unsupported_content",`${n} served ${D.split(";")[0]} — only HTML and text are read`);const{text:x}=await dt(s,N),P=e();let g;if(/text\/plain|markdown/.test(D)){const w=x.trim();g={url:E(M),title:"",markdown:w,text:w,sections:I(w),provider:T,fetchedAt:P}}else{const w=at(x);let y=null;try{y=await _(x,M)}catch{y=null}const C=y&&$(y.markdown)>=Math.min(st/5,$(w.text)*.5),z=C?y.markdown:w.text;g={url:E(M,x),title:C&&y.title||w.title||"",author:y?.author||"",published:y?.published||"",lang:y?.lang||"",markdown:z,text:w.text,sections:I(z,q(x)),provider:C?L:T,fetchedAt:P};const G=$(g.markdown),j=V({status:s.status,headers:s.headers,html:x,words:G});if(j)return R(t,j,{provider:g.provider,ms:Math.round(e()-r)})}const U=Math.round(e()-r);return h.record(U,g.markdown.length),o.set(t.url,{doc:g,etag:s.headers.get("etag"),lastModified:s.headers.get("last-modified"),cacheControl:s.headers.get("cache-control")}),g.url!==t.url&&o.set(g.url,{doc:g,etag:s.headers.get("etag"),lastModified:s.headers.get("last-modified"),cacheControl:s.headers.get("cache-control")}),v(g,t,{cached:!1,ms:U})}finally{clearTimeout(b),d()}}async function X(t,r){if(!u?.url)return p(404,"provider_not_found","no remote reader is configured (read.remote.url)");const n=new AbortController,c=setTimeout(()=>n.abort(),Math.min(k*3,t.budgetMs>0?t.budgetMs:k*3));try{const a=await ot({url:t.url,base:u.url,key:u.key,fetchFn:l,signal:n.signal,format:t.format}),d=e(),m={url:E(a.url||t.url),title:a.title,author:a.author,published:a.published,markdown:a.markdown,text:a.markdown,sections:I(a.markdown),provider:O,fetchedAt:d},b=Math.round(e()-r);return h.record(b,m.markdown.length),o.set(t.url,{doc:m}),v(m,t,{cached:!1,ms:b})}catch(a){return n.signal.aborted?p(504,"fetch_timeout","the remote reader did not answer within the budget"):a.status===401||a.status===402||a.status===403?R(t,{reason:"login",detail:`remote reader: HTTP ${a.status}`},{provider:O,ms:Math.round(e()-r)}):p(502,"fetch_failed",a.message)}finally{clearTimeout(c)}}return{providers:A,stats:()=>h.stats(),cache:o,async read(t){let r;try{r=Y(t)}catch(d){return p(400,"invalid_request",d.message)}const n=r.provider||i;if(!A().includes(n))return p(404,"provider_not_found",`no read provider ${JSON.stringify(n)} here (have ${A().join(", ")})`);const c=e(),a=o.get(r.url);if(!(a&&!a.stale)){const d=Q(h.stats(),0,r.budgetMs);if(d)return{status:503,body:d}}try{return n===O?await X(r,c):await K(r,c)}catch(d){return p(500,"read_failed",d.message)}}}}export{H as READ_DEFAULTS,ct as createReadStats,yt as createReader};
@@ -0,0 +1 @@
1
+ import{secureFetch as p}from"../secure-fetch.js";import{buildSearxngUrl as S,searxngResults as y}from"../search-searxng.js";const x="searxng",T=6e4;function A({url:d,token:i="",engines:f="",safesearch:g=null,fetchFn:l=p,now:o=()=>Date.now()}={}){const a=String(d||"").trim().replace(/\/?$/,"/");let e={state:"unknown",at:0,error:null};const h=()=>{const t={Accept:"application/json"};return i&&(t.Authorization=`Bearer ${i}`),t};return{id:x,url:a,async health({force:t=!1}={}){if(!a)return{state:"off"};if(!t&&o()-e.at<T)return e;try{const r=await l(new URL("healthz",a).toString(),{headers:{Accept:"text/plain"},signal:AbortSignal.timeout(3e3)});e={state:r.ok?"ready":"down",at:o(),error:r.ok?null:`HTTP ${r.status}`}}catch(r){e={state:"down",at:o(),error:r.message}}return e},state(){return a?e.state:"off"},async search(t,{signal:r}={}){const m=S(a,t,{engines:f,safesearch:g}),s=await l(m,{headers:h(),signal:r});if(!s.ok){const n=new Error(s.status===403?"SearXNG answered 403 — its settings.yml must list json under search.formats":s.status===429?"SearXNG answered 429 — set limiter: false in its settings.yml for an API client":`SearXNG answered HTTP ${s.status}`);throw n.status=s.status,n}let c;try{c=await s.json()}catch{throw new Error("SearXNG did not answer JSON — is format=json enabled?")}e={state:"ready",at:o(),error:null};const u=y(c,{limit:t.limit||8,site:t.site||""}),w=[...new Set(u.results.flatMap(n=>n.engines||[n.engine]))];return{...u,engines:w}}}}export{x as PROVIDER_ID,A as createSearxng};
@@ -0,0 +1 @@
1
+ import{secureFetch as m}from"../secure-fetch.js";import{SEARCH_ENGINES as h,buildSearchUrl as d,pickResults as b,mergeEngineResults as f,engineOrder as k}from"../web-search.js";import{extractAnchors as E}from"../serp-anchors.js";const I="serp",x=Object.freeze({allowLoopback:!1,allowPrivate:!1}),S=3e6,w=Object.freeze({Accept:"text/html,application/xhtml+xml","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36","Accept-Language":"en-US,en;q=0.9"});async function A(i,l,{fetchFn:s,signal:p,perEngine:r}){let o;try{o=d(i.url,l)}catch{return[]}try{const n=await s(o,{policy:x,headers:w,signal:p});if(!n.ok)return[];const a=n.headers.get("content-type")||"";if(a&&!/html|text|xml/i.test(a))return[];const c=(await n.text()).slice(0,S);return b(E(c),{engineHost:new URL(o).hostname,limit:r,fallback:!0})}catch{return[]}}const _=new Map;async function O(i,{fetchFn:l=m,signal:s=void 0,engines:p=h,streaks:r=_}={}){const o=i.site?`site:${i.site} ${i.q}`:i.q,n=i.limit||8,a=k(p).filter(e=>e.enabled!==!1).map((e,t)=>({e,i:t})).sort((e,t)=>(r.get(e.e.id)||0)-(r.get(t.e.id)||0)||e.i-t.i).map(({e})=>e),c=[],u=[];for(const e of a){if(s?.aborted)break;const t=await A(e,o,{fetchFn:l,signal:s,perEngine:n});if(u.push(e.id),s?.aborted||r.set(e.id,t.length?0:(r.get(e.id)||0)+1),t.length&&c.push(t.map(g=>({...g,engine:e.id}))),f(c,n).length>=n||t.length)break}return{results:f(c,n).map((e,t)=>({rank:t+1,url:e.url,title:e.title,snippet:e.snippet||"",engine:e.engine})),engines:u,answers:[],suggestions:[]}}export{I as PROVIDER_ID,O as searchSerp};
@@ -0,0 +1 @@
1
+ import{validateSearchRequest as $,validateSearchResponse as j,overBudget as B}from"../capability-endpoints.js";import{createReadStats as D}from"./read.js";import{searchSerp as C,PROVIDER_ID as S}from"./search-serp.js";import{PROVIDER_ID as b}from"./search-searxng.js";const v=Object.freeze({timeoutMs:15e3,readConcurrency:4,readBudgetMs:8e3,aliasRead:5}),I=/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g,i=(r,t,a)=>({status:r,body:{error:{type:t,message:a}}});function L(r){const t=String(r||"").replace(I," ").replace(/\s+/g," ").trim();return{q:t,stripped:t!==String(r||"").trim()}}async function N(r,t,a){const d=new Array(r.length);let w=0;const M=Array.from({length:Math.min(t,r.length)},async()=>{for(;;){const s=w++;if(s>=r.length)return;d[s]=await a(r[s],s)}});return await Promise.all(M),d}function F({reader:r=null,redact:t=async p=>p,searxng:a=null,defaultProvider:d="auto",fetchFn:w=void 0,engines:M=void 0,now:s=()=>Date.now(),stats:_={serp:D(),searxng:D()},timeoutMs:q=v.timeoutMs}={}){const p=()=>[S,...a?.url?[b]:[]];async function x(c){if(c.provider)return c.provider;if(d===b||d===S)return d;if(a?.url){const e=await a.health();if(e.state==="ready"||e.state==="unknown")return b}return S}return{providers:p,stats:()=>Object.fromEntries(Object.entries(_).map(([c,e])=>[c,e.stats()])),searxng:a,async search(c){let e;try{e=$(c)}catch(n){return i(400,"invalid_request",n.message)}if(e.provider&&!p().includes(e.provider))return i(404,"provider_not_found",`no search provider ${JSON.stringify(e.provider)} here (have ${p().join(", ")})`);if(e.read&&!r)return i(400,"invalid_request","read: no reader is available here");const R=s();let E=!1;try{const n=await t(e.q),{q:m,stripped:y}=L(n);y&&(E=!0,e.q=m)}catch(n){return i(500,"redaction_failed",n.message)}if(!e.q)return i(400,"unsafe_query","the query was only private values (an email, a card, a key…) and nothing searchable remains");const o=await x(e),A=B(_[o]?.stats(),0,e.budgetMs);if(A)return{status:503,body:{...A,provider:o}};const f=new AbortController,O=setTimeout(()=>f.abort(),Math.min(q,e.budgetMs>0?e.budgetMs:q));let u;try{u=o===b?await a.search(e,{signal:f.signal}):await C(e,{fetchFn:w,signal:f.signal,engines:M})}catch(n){return clearTimeout(O),f.signal.aborted?i(504,"fetch_timeout",`${o} did not answer within the budget`):i(502,"provider_failed",`${o}: ${n.message}`)}clearTimeout(O);const T=Math.round(s()-R);_[o]?.record(T,e.q.length);let h=u.results;if(e.read>0&&h.length){const n=e.budgetMs>0?Math.max(1e3,e.budgetMs-T):v.readBudgetMs,m=h.slice(0,e.read),y=await N(m,v.readConcurrency,async g=>{const l=await r.read({url:g.url,snippet:g.snippet,budgetMs:Math.min(n,v.readBudgetMs)});return l.status===200?l.body:null});h=h.map((g,l)=>l<m.length&&y[l]?{...g,read:y[l]}:g)}const k={results:h,answers:u.answers||[],suggestions:u.suggestions||[],engines:u.engines||[],...u.unresponsive?.length?{unresponsive:u.unresponsive}:{},...E?{redacted:!0,query:e.q}:{},provider:o,ms:Math.round(s()-R)};try{j(k)}catch(n){return i(500,"bad_shape",n.message)}return{status:200,body:k}}}}function G(r){return{code:200,status:2e4,data:(r.results||[]).map(t=>({url:t.url,title:t.title,description:t.snippet||"",content:t.read?.markdown||t.read?.text||t.snippet||"",...t.read?.published?{publishedTime:t.read.published}:{}}))}}export{v as SEARCH_DEFAULTS,F as createSearcher,L as queryWithoutTokens,G as toJinaSearch};
@@ -0,0 +1 @@
1
+ const p=Object.freeze({day:"day",week:"month",month:"month",year:"year"});function f(t,r,{engines:g="",safesearch:c=null,pageno:a=1}={}){const o=String(t||"").trim();if(!/^https?:\/\//i.test(o))throw new Error("searxng: url must start with http:// or https://");const s=new URL("search",o.replace(/\/?$/,"/")),e=r.site?`site:${r.site} ${r.q}`:r.q;return s.searchParams.set("q",e),s.searchParams.set("format","json"),r.lang&&s.searchParams.set("language",r.lang),r.freshness&&s.searchParams.set("time_range",p[r.freshness]),a>1&&s.searchParams.set("pageno",String(a)),g&&s.searchParams.set("engines",g),c!=null&&s.searchParams.set("safesearch",String(c)),s.toString()}const i=t=>typeof t=="string"?t:"";function y(t,{limit:r=8,site:g=""}={}){const c=Array.isArray(t?.results)?t.results:[],a=[],o=new Set,s=String(g||"").toLowerCase();for(const e of c){let n;try{n=new URL(i(e?.url))}catch{continue}if(n.protocol!=="https:"&&n.protocol!=="http:"||s&&n.hostname.toLowerCase()!==s&&!n.hostname.toLowerCase().endsWith(`.${s}`))continue;const u=n.origin+n.pathname;if(o.has(u))continue;o.add(u);const l=Array.isArray(e.engines)?e.engines.filter(h=>typeof h=="string"):[];if(a.push({rank:a.length+1,url:n.toString(),title:i(e.title).replace(/\s+/g," ").trim()||n.toString(),snippet:i(e.content).replace(/\s+/g," ").trim(),engine:i(e.engine)||l[0]||"searxng",...l.length?{engines:l}:{},...typeof e.score=="number"?{score:e.score}:{},...i(e.publishedDate)?{publishedDate:e.publishedDate}:{}}),a.length>=r)break}return{results:a,answers:(Array.isArray(t?.answers)?t.answers:[]).map(e=>typeof e=="string"?e:i(e?.answer)).filter(Boolean),suggestions:(Array.isArray(t?.suggestions)?t.suggestions:[]).filter(e=>typeof e=="string"),unresponsive:(Array.isArray(t?.unresponsive_engines)?t.unresponsive_engines:[]).map(e=>Array.isArray(e)?e[0]:i(e)).filter(Boolean)}}export{p as FRESHNESS_TO_TIME_RANGE,f as buildSearxngUrl,y as searxngResults};
@@ -0,0 +1 @@
1
+ const m={amp:"&",lt:"<",gt:">",quot:'"',"#39":"'",apos:"'",nbsp:" "},S=i=>String(i).replace(/&(#x?[0-9a-f]+|[a-z]+);/gi,(s,p)=>{const e=p.toLowerCase();return m[e]?m[e]:e.startsWith("#x")?String.fromCodePoint(parseInt(e.slice(2),16)||32):e.startsWith("#")?String.fromCodePoint(parseInt(e.slice(1),10)||32):s}),h=i=>S(i).replace(/\s+/g," ").trim(),C=/^(header|footer|nav|aside|form|button|dialog)$/i;function w(i){const s=[],e=String(i||"").replace(/<script[\s\S]*?<\/script>/gi," ").replace(/<style[\s\S]*?<\/style>/gi," ").replace(/<!--[\s\S]*?-->/g," ");let a=0;const x=/<(\/?)([a-zA-Z][a-zA-Z0-9]*)\b([^>]*)>/g;let o,c=null,u=!1,l=0;for(;o=x.exec(e);){const[n,t,g,f]=o,d=g.toLowerCase();if(C.test(d)){t?a=Math.max(0,a-1):/\/>$/.test(n)||(a+=1);continue}if(d==="a"&&!t){const r=f.match(/\bhref\s*=\s*("([^"]*)"|'([^']*)'|([^\s"'>]+))/i);c=r?h(r[2]??r[3]??r[4]??""):null,u=a>0,l=o.index+n.length;continue}if(d==="a"&&t&&c!=null){const r=h(e.slice(l,o.index).replace(/<[^>]*>/g," "));s.push({href:c,text:r,chrome:u,at:l,end:o.index+n.length}),c=null}}for(let n=0;n<s.length;n++){const t=s[n],g=Math.min(s[n+1]?.at??e.length,t.end+1400),f=e.slice(t.end,Math.max(t.end,g)).replace(/<[^>]*>/g," ");t.snippet=h(f).slice(0,220).trim(),delete t.at,delete t.end}return s}export{w as extractAnchors};
package/src/server.js CHANGED
@@ -1,30 +1,30 @@
1
- import{createServer as gt}from"node:http";import{loadConfig as je}from"./config.js";import{startEntitlementRefresh as bt,maybeRevalidate as wt}from"./entitlement-refresh.js";import{redactSegments as we,segment as Me}from"./redact.js";import{pipeRestoredStream as kt,pipeRestoredOpenAIStream as St,makeTokenRestorer as Re,restoreDeep as vt}from"./stream.js";import{restoreText as Tt,gatedDictionary as _t,narrowSpecs as Ot,makeToolHarness as $t,placeholderToolNote as Pt,placeholderNote as At,assertEndpointUrl as Et,capRunOptions as xt,isPaired as Nt}from"@chatpanel/pii";import{ensureGatewayToken as ke,currentGatewayToken as Bt,isAdminAuthorized as H,callerTrustOf as me,setPinnedExtensionIds as Dt,issuePairingCode as Ct,claimPairingCode as It}from"./gateway-token.js";import{installEgressLedger as jt,egressAudit as Mt}from"./egress.js";import{initPolicy as Rt,activePolicy as zt,applyPolicyToConfig as ze,managedSummary as ce,PolicyLoadError as Lt}from"./policy.js";import{routeAllowed as Le,agentAllowed as Gt,egressAllowed as Vt}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as re}from"./bridge.js";import{secureFetch as Ge}from"./secure-fetch.js";import{streamBridgeChat as Ve,readBridgeToken as ee,openBridgeChat as Jt}from"./bridge.js";import{createRelaySession as Ht,getRelaySession as Je,endRelaySession as pe,pumpBridgeStream as Ut,deliverToolResult as Ft,toolsToSpecs as Wt,parseToolCallId as He,touchRelaySession as Se}from"./toolrelay.js";import{shaperFor as ve}from"./shape.js";import{startNer as Kt,ensureNer as Te}from"./ner.js";import{installTimestampedConsole as Zt}from"./log.js";import{saveBackupSecret as Yt,clearBackupSecret as Qt,loadBackupSecret as _e,hasBackupSecret as Ue}from"./history-store.js";import{createMemoryStore as Xt}from"./memory-store.js";import{createPrefsStore as qt}from"./prefs-store.js";import{createTeamStore as eo,loadOrCreateKey as Oe}from"./team-store.js";import{createScorecardStore as to}from"./scorecard-store.js";import{createEngineLedgerStore as oo}from"./engine-ledger-store.js";import{createProjectStore as ro}from"./project-store.js";import{applicationsFor as no,recruitPass as so}from"./recruiting.js";import{ensureBridge as ao}from"./bridge-supervisor.js";import{checkForUpdate as io,updateStatus as lo,startUpdate as co,updateJob as uo}from"./update.js";import{createHistoryStore as mo}from"./sqlite-store.js";import{ingestBackups as $e}from"./backup-ingest.js";import{toSearchRecord as po}from"@chatpanel/events/library.js";import{deriveBackupKey as ho,openRecord as yo,keyCache as fo,nodeCodec as go}from"@chatpanel/events/backup-envelope.js";import bo from"node:zlib";import*as D from"./ner-engine.js";import*as A from"./stt-engine.js";import*as B from"./diarize-engine.js";import{MODEL_CATALOG as wo,isKnownModel as ko,isValidCustomModelId as So}from"./models.js";import{STT_MODEL_CATALOG as vo,isKnownSttModel as To,isValidCustomSttId as _o,DEFAULT_STT_MODEL as Pe,STT_DTYPES as Oo,isValidDtype as $o}from"./stt-models.js";import*as S from"./tts-engine.js";import{TTS_MODEL_CATALOG as Fe,TTS_VOICES as Po,isKnownTtsModel as Ao,isValidCustomTtsId as Eo,isKnownVoice as We,isValidVoiceId as Ke,DEFAULT_TTS_MODEL as Ze,DEFAULT_TTS_VOICE as X,TTS_DTYPES as xo,isValidTtsDtype as No,MAX_TTS_CHARS as Ye,ttsModelHasCustomVoices as Bo,resolveDefaultModel as Qe,POCKET_VOICES as Do,DEFAULT_POCKET_VOICE as he,isPocketVoice as ye,ttsModelEngine as fe}from"./tts-models.js";import{ttsDestination as Co,synthesizeRemote as Io,isValidRemoteVoice as jo}from"./tts-remote.js";import{rawOrtAvailable as Ae}from"./ort.js";import*as G from"./tts-voices.js";import{resolveTtsVoice as Mo}from"./tts-voice-resolve.js";import{resolvePro as te,checkQuota as Ro,consume as zo,usage as Lo}from"./freegate.js";import{publicConfig as Xe,applyConfigPatch as Go,applyNerModelSelection as Vo,persistConfig as ne,configPath as oe,bridgeAgentOptions as qe,PERMISSION_MODES as Jo}from"./configstore.js";import{resolveDestination as et,aggregateModelsAsync as Ho,listDestinations as Uo}from"./router.js";import{makeAccessEvent as tt}from"./observability.js";import{createPersistentAccessLog as Fo}from"./access-log-store.js";import{planQueries as Wo,multiSearch as Ko}from"./rrf.js";import*as Ee from"./openai.js";import*as ot from"./responses.js";import*as xe from"./anthropic.js";const K="0.11.14",O=await mo(),Q=new Set;function ge({ids:t=[]}={}){const l=O.lossless;if(!l||!Q.size)return;const d=JSON.stringify({newest:l.newest,size:l.size,ids:t.slice(0,50),at:Date.now()});for(const r of Q)try{r.write(`event: records
1
+ import{createServer as Et}from"node:http";import{loadConfig as Ve}from"./config.js";import{startEntitlementRefresh as At,maybeRevalidate as Nt}from"./entitlement-refresh.js";import{redactSegments as ge,segment as xe}from"./redact.js";import{pipeRestoredStream as Bt,pipeRestoredOpenAIStream as Dt,makeTokenRestorer as Ue,restoreDeep as Ct}from"./stream.js";import{restoreText as Mt,gatedDictionary as It,narrowSpecs as jt,makeToolHarness as Rt,placeholderToolNote as Lt,placeholderNote as zt,assertEndpointUrl as Gt,capRunOptions as Jt,isPaired as Vt}from"@chatpanel/pii";import{ensureGatewayToken as $e,currentGatewayToken as Ut,isAdminAuthorized as Z,callerTrustOf as be,setPinnedExtensionIds as Ht,issuePairingCode as Ft,claimPairingCode as Wt}from"./gateway-token.js";import{installEgressLedger as Kt,egressAudit as Zt}from"./egress.js";import{initPolicy as Yt,activePolicy as Qt,applyPolicyToConfig as He,managedSummary as pe,PolicyLoadError as Xt}from"./policy.js";import{routeAllowed as Fe,agentAllowed as qt,egressAllowed as eo}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as ce}from"./bridge.js";import{secureFetch as We}from"./secure-fetch.js";import{streamBridgeChat as Ke,readBridgeToken as ae,openBridgeChat as to}from"./bridge.js";import{createRelaySession as oo,getRelaySession as Ze,endRelaySession as we,pumpBridgeStream as ro,deliverToolResult as no,toolsToSpecs as so,parseToolCallId as Ye,touchRelaySession as Pe}from"./toolrelay.js";import{shaperFor as Ee}from"./shape.js";import{startNer as ao,ensureNer as ke,unionForThisMachine as io,skippedCompanions as lo}from"./ner.js";import{recommendDetector as Qe}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as co}from"./log.js";import{saveBackupSecret as uo,clearBackupSecret as mo,loadBackupSecret as Ae,hasBackupSecret as Xe}from"./history-store.js";import{createMemoryStore as po}from"./memory-store.js";import{createPrefsStore as ho}from"./prefs-store.js";import{createTeamStore as yo,loadOrCreateKey as Ne}from"./team-store.js";import{createScorecardStore as fo}from"./scorecard-store.js";import{createEngineLedgerStore as go}from"./engine-ledger-store.js";import{createProjectStore as bo}from"./project-store.js";import{applicationsFor as wo,recruitPass as ko}from"./recruiting.js";import{ensureBridge as So}from"./bridge-supervisor.js";import{checkForUpdate as vo,updateStatus as To,startUpdate as _o,updateJob as Oo}from"./update.js";import{createHistoryStore as xo}from"./sqlite-store.js";import{ingestBackups as Be}from"./backup-ingest.js";import{toSearchRecord as $o}from"@chatpanel/events/library.js";import{deriveBackupKey as Po,openRecord as Eo,keyCache as Ao,nodeCodec as No}from"@chatpanel/events/backup-envelope.js";import Bo from"node:zlib";import*as P from"./ner-engine.js";import qe from"node:os";import{capabilitiesDocument as Do,handleDetect as Co}from"./capabilities.js";import{createExtractService as Mo}from"./extract/service.js";import{handleExtract as Io}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as jo}from"./extract-capability.js";import{createReader as Ro}from"./retrieval/read.js";import{createSearcher as Lo,toJinaSearch as zo,SEARCH_DEFAULTS as Go}from"./retrieval/search.js";import{createSearxng as Jo}from"./retrieval/search-searxng.js";import{toJinaText as Vo}from"./read-document.js";import*as D from"./stt-engine.js";import*as I from"./diarize-engine.js";import{MODEL_CATALOG as et,isKnownModel as tt,isValidCustomModelId as ot,recommendFor as Uo}from"./models.js";import{STT_MODEL_CATALOG as Ho,isKnownSttModel as Fo,isValidCustomSttId as Wo,DEFAULT_STT_MODEL as De,STT_DTYPES as Ko,isValidDtype as Zo}from"./stt-models.js";import*as O from"./tts-engine.js";import{TTS_MODEL_CATALOG as rt,TTS_VOICES as Yo,isKnownTtsModel as Qo,isValidCustomTtsId as Xo,isKnownVoice as nt,isValidVoiceId as st,DEFAULT_TTS_MODEL as at,DEFAULT_TTS_VOICE as re,TTS_DTYPES as qo,isValidTtsDtype as er,MAX_TTS_CHARS as it,ttsModelHasCustomVoices as tr,resolveDefaultModel as lt,POCKET_VOICES as or,DEFAULT_POCKET_VOICE as Se,isPocketVoice as ve,ttsModelEngine as Te}from"./tts-models.js";import{ttsDestination as rr,synthesizeRemote as nr,isValidRemoteVoice as sr}from"./tts-remote.js";import{rawOrtAvailable as Ce}from"./ort.js";import*as G from"./tts-voices.js";import{resolveTtsVoice as ar}from"./tts-voice-resolve.js";import{resolvePro as ie,checkQuota as ir,consume as lr,usage as cr}from"./freegate.js";import{publicConfig as ct,applyConfigPatch as dr,applyNerModelSelection as dt,persistConfig as le,configPath as ne,bridgeAgentOptions as ut,PERMISSION_MODES as ur}from"./configstore.js";import{resolveDestination as mt,aggregateModelsAsync as mr,listDestinations as pr}from"./router.js";import{makeAccessEvent as pt}from"./observability.js";import{createPersistentAccessLog as hr}from"./access-log-store.js";import{planQueries as yr,multiSearch as fr}from"./rrf.js";import*as Me from"./openai.js";import*as ht from"./responses.js";import*as Ie from"./anthropic.js";const Y="0.17.0",N=await xo(),te=new Set;function _e({ids:t=[]}={}){const l=N.lossless;if(!l||!te.size)return;const d=JSON.stringify({newest:l.newest,size:l.size,ids:t.slice(0,50),at:Date.now()});for(const m of te)try{m.write(`event: records
2
2
  data: ${d}
3
3
 
4
- `)}catch{Q.delete(r)}}setInterval(()=>{for(const t of Q)try{t.write(`: ping
4
+ `)}catch{te.delete(m)}}setInterval(()=>{for(const t of te)try{t.write(`: ping
5
5
 
6
- `)}catch{Q.delete(t)}},25e3).unref?.();const U=await Xt(),F=qt(),se=to({key:Oe()}),ae=oo({key:Oe()}),V=ro({key:Oe()}),C=eo({scorecards:se,engines:ae}),Ne=new Set,rt=(t,l)=>{for(const r of Ne)try{r({applied:t,by:l,revision:F.revision})}catch{}const d=JSON.stringify({revision:F.revision,applied:(t||[]).slice(0,50),by:l||"",at:Date.now()});for(const r of Q)try{r.write(`event: prefs
6
+ `)}catch{te.delete(t)}},25e3).unref?.();const Q=await po(),X=ho(),de=fo({key:Ne()}),ue=go({key:Ne()}),J=bo({key:Ne()}),R=yo({scorecards:de,engines:ue}),je=new Set,yt=(t,l)=>{for(const m of je)try{m({applied:t,by:l,revision:X.revision})}catch{}const d=JSON.stringify({revision:X.revision,applied:(t||[]).slice(0,50),by:l||"",at:Date.now()});for(const m of te)try{m.write(`event: prefs
7
7
  data: ${d}
8
8
 
9
- `)}catch{Q.delete(r)}},Be=Fo(),nt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Zo=16,Yo=/^mcp[_-]/i,st=t=>t&&t.function&&t.function.name||t&&t.name||"",Qo=t=>t&&t.function&&t.function.description||t&&t.description||"";function at(t){return typeof t=="string"?t:Array.isArray(t)?t.map(l=>typeof l=="string"?l:l&&(l.text||l.content)||"").join(" "):""}function Xo(t,l){if(!t)return"";if(l==="responses"){const r=t.input;return typeof r=="string"?r:Array.isArray(r)?r.map(o=>at(o&&(o.content??o))).join(" "):""}const d=Array.isArray(t.messages)?t.messages:[];for(let r=d.length-1;r>=0;r--)if(d[r]&&d[r].role==="user")return at(d[r].content);return""}const it=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function lt(t){if(!t)return!1;const l=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return l==="localhost"||l==="127.0.0.1"||l==="::1"}function qo(t,l){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(l.allowedOrigins)&&l.allowedOrigins.includes(t)}function er(t,l){t.setHeader("Access-Control-Allow-Origin",l||"*"),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 ct=Date.now();function tr(t){if(!t)return"";const l={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(d=>`${l[d]||d} ${t[d]}ms`).join(" · ")}function or(t){const l=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return l?{kind:l[1],id:l[2],...l[3]?{model:l[3]}:{}}:null}function rr(t){const l=performance.now(),d={};let r=!1;const o=(u,c)=>{d[u]=Math.round(c*10)/10};return{meta:{},timings:d,mark:o,lap(u,c){o(u,performance.now()-c)},clock(){return performance.now()},commit(){if(r)return;r=!0,o("total",performance.now()-l);const u={...this.meta,timings:d};setImmediate(()=>{t(u),console.log(`[gateway] model=${u.model||"-"} → ${u.dest?`${u.dest}(${u.type})`:"none"} · ${u.redaction==="off"?"redaction OFF (client request)":`redacted ${u.redacted||0}`}${u.sanitized?` · scrubbed ${u.sanitized} hidden`:""}${u.narrowed?` · narrowed -${u.narrowed}`:""} · ${tr(d)}`)})}}}function dt(t,l){if(!t||!t.byToken||l!=="types"&&l!=="values")return;const d=[];for(const[r,o]of t.byToken){const u=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(r),c=u?u[1]:"PII",g=r.replace(/^\[\[|\]\]$/g,"");d.push(l==="values"?{token:g,type:c,value:o}:{token:g,type:c})}return d}function nr(t,l,d){return xe.matches(t)||"anthropic-version"in l?{kind:"anthropic",adapter:xe,redactable:xe.matches(t),base:d.upstreams?.anthropic?.baseUrl}:ot.matches(t)?{kind:"responses",adapter:ot,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Ee,redactable:Ee.matches(t),base:d.upstreams?.openai?.baseUrl}}function De(t,l){const d=String(t||"");if(nt.has(d))return{agent:d,agentModel:""};const r=d.indexOf("/");if(r>0){const o=d.slice(0,r);if(nt.has(o))return{agent:o,agentModel:d.slice(r+1)}}return{agent:l.bridge.agent,agentModel:""}}function ut(t,l){return De(t,l).agent}function sr(t,l){if(l!=="openai"||!t)return!1;const d=Ee.extractLatestToolResult(t);if(!d)return!1;const r=He(d.tool_call_id);return!!(r&&Je(r.gwId))}function ar(t,l){try{const d=new URL(t),r=d.hostname.replace(/^\[|\]$/g,""),o=r==="127.0.0.1"||r==="localhost"||r==="::1",u=d.port||(d.protocol==="https:"?"443":"80");return o&&String(u)===String(l.port)}catch{return!1}}async function v(t,l){const d=[];let r=0;for await(const o of t){if(r+=o.length,l&&r>l){const u=new Error("payload too large");throw u.code=413,u}d.push(o)}return Buffer.concat(d)}function s(t,l,d){t.writeHead(l,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function mt(t){const l=t.redaction?.detection?.url;return!l||t.redaction?.detection?.backend==="off"?null:l}function Ce(t){const l=t?.redaction?.detection,d=t?.redaction?.tier==="full"?"full":"basic";if(l&&l.backend&&l.backend!=="off")return{source:"external",backend:l.backend,state:"external",model:l.model||null,ready:!0,tier:d,coverage:d==="full"?"names":"patterns"};const r=D.health(),o=r.ok&&d==="full";return{source:"bundled",state:r.state,model:r.model||t?.ner?.model||null,installed:D.modelOnDisk(t?.ner?.model||void 0),error:r.error||null,ready:o,tier:d,coverage:o?"names":"patterns"}}async function pt(t){if(D.state()!=="off"){const d=D.health();return{configured:d.configured,ok:d.ok,state:d.state,model:d.model,error:d.error||null,url:d.configured?`http://${t.host}:${t.port}/ner`:null}}const l=mt(t);if(!l)return{configured:!1,ok:!1,url:null,model:null};try{const d=await Ge(l.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:l,model:null};const r=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:l,model:r.model||null}}catch{return{configured:!0,ok:!1,url:l,model:null}}}function ir(t,l){const d={};for(const[r,o]of Object.entries(t)){const u=r.toLowerCase();u.startsWith("x-chatpanel-")||it.has(u)||(d[r]=o)}d["accept-encoding"]="identity";try{d.host=new URL(l).host}catch{}return d}async function ht(t,l,d,r){const o=Re(l.vault),u=r?r.clock():0;let c=u,g=!0;const w=()=>{r&&g&&(r.lap("upstream",u),c=r.clock(),g=!1)};await Ut(l,{onText:P=>{w(),Se(l.id);const p=o.push(P);p&&t.write(d.sseDelta(p))},onToolRequest:({name:P,restoredArgs:p,toolId:z})=>{w(),Se(l.id);const x=o.flush();x&&t.write(d.sseDelta(x)),t.write(d.sseToolCalls([{id:z,name:P,arguments:JSON.stringify(p)}])),t.write(d.sseToolFinish()),r&&r.lap("stream",c),t.end(),r?.commit()},onDone:()=>{const P=o.flush();P&&t.write(d.sseDelta(P)),t.write(d.sseTail()),r&&r.lap("stream",c),t.end(),pe(l.id),r?.commit()},onError:P=>{t.write(`data: ${JSON.stringify({error:{message:P.message,type:"bridge_error"}})}
9
+ `)}catch{te.delete(m)}},Re=hr(),ft=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),gr=16,br=/^mcp[_-]/i,gt=t=>t&&t.function&&t.function.name||t&&t.name||"",wr=t=>t&&t.function&&t.function.description||t&&t.description||"";function bt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(l=>typeof l=="string"?l:l&&(l.text||l.content)||"").join(" "):""}function kr(t,l){if(!t)return"";if(l==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(p=>bt(p&&(p.content??p))).join(" "):""}const d=Array.isArray(t.messages)?t.messages:[];for(let m=d.length-1;m>=0;m--)if(d[m]&&d[m].role==="user")return bt(d[m].content);return""}const wt=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function kt(t){if(!t)return!1;const l=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return l==="localhost"||l==="127.0.0.1"||l==="::1"}function Sr(t,l){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(l.allowedOrigins)&&l.allowedOrigins.includes(t)}function vr(t,l){t.setHeader("Access-Control-Allow-Origin",l||"*"),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 St=Date.now();function Tr(t){if(!t)return"";const l={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(d=>`${l[d]||d} ${t[d]}ms`).join(" · ")}function _r(t){const l=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return l?{kind:l[1],id:l[2],...l[3]?{model:l[3]}:{}}:null}function Or(t){const l=performance.now(),d={};let m=!1;const p=(b,x)=>{d[b]=Math.round(x*10)/10};return{meta:{},timings:d,mark:p,lap(b,x){p(b,performance.now()-x)},clock(){return performance.now()},commit(){if(m)return;m=!0,p("total",performance.now()-l);const b={...this.meta,timings:d};setImmediate(()=>{t(b),console.log(`[gateway] model=${b.model||"-"} → ${b.dest?`${b.dest}(${b.type})`:"none"} · ${b.redaction==="off"?"redaction OFF (client request)":`redacted ${b.redacted||0}`}${b.sanitized?` · scrubbed ${b.sanitized} hidden`:""}${b.narrowed?` · narrowed -${b.narrowed}`:""} · ${Tr(d)}`)})}}}function vt(t,l){if(!t||!t.byToken||l!=="types"&&l!=="values")return;const d=[];for(const[m,p]of t.byToken){const b=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),x=b?b[1]:"PII",k=m.replace(/^\[\[|\]\]$/g,"");d.push(l==="values"?{token:k,type:x,value:p}:{token:k,type:x})}return d}function xr(t,l,d){return Ie.matches(t)||"anthropic-version"in l?{kind:"anthropic",adapter:Ie,redactable:Ie.matches(t),base:d.upstreams?.anthropic?.baseUrl}:ht.matches(t)?{kind:"responses",adapter:ht,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Me,redactable:Me.matches(t),base:d.upstreams?.openai?.baseUrl}}function Le(t,l){const d=String(t||"");if(ft.has(d))return{agent:d,agentModel:""};const m=d.indexOf("/");if(m>0){const p=d.slice(0,m);if(ft.has(p))return{agent:p,agentModel:d.slice(m+1)}}return{agent:l.bridge.agent,agentModel:""}}function Tt(t,l){return Le(t,l).agent}function $r(t,l){if(l!=="openai"||!t)return!1;const d=Me.extractLatestToolResult(t);if(!d)return!1;const m=Ye(d.tool_call_id);return!!(m&&Ze(m.gwId))}function Pr(t,l){try{const d=new URL(t),m=d.hostname.replace(/^\[|\]$/g,""),p=m==="127.0.0.1"||m==="localhost"||m==="::1",b=d.port||(d.protocol==="https:"?"443":"80");return p&&String(b)===String(l.port)}catch{return!1}}async function _(t,l){const d=[];let m=0;for await(const p of t){if(m+=p.length,l&&m>l){const b=new Error("payload too large");throw b.code=413,b}d.push(p)}return Buffer.concat(d)}function s(t,l,d){t.writeHead(l,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function _t(t){const l=t.redaction?.detection?.url;return!l||t.redaction?.detection?.backend==="off"?null:l}function ze(t){const l=t?.redaction?.detection,d=t?.redaction?.tier==="full"?"full":"basic";if(l&&l.backend&&l.backend!=="off")return{source:"external",backend:l.backend,state:"external",model:l.model||null,ready:!0,tier:d,coverage:d==="full"?"names":"patterns"};const m=P.health(),p=m.ok&&d==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:P.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:p,tier:d,coverage:p?"names":"patterns"}}async function Ot(t){if(P.state()!=="off"){const d=P.health();return{configured:d.configured,ok:d.ok,state:d.state,model:d.model,error:d.error||null,url:d.configured?`http://${t.host}:${t.port}/ner`:null,stats:d.stats,companions:d.companions}}const l=_t(t);if(!l)return{configured:!1,ok:!1,url:null,model:null};try{const d=await We(l.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:l,model:null};const m=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:l,model:m.model||null}}catch{return{configured:!0,ok:!1,url:l,model:null}}}function Er(t,l){const d={};for(const[m,p]of Object.entries(t)){const b=m.toLowerCase();b.startsWith("x-chatpanel-")||wt.has(b)||(d[m]=p)}d["accept-encoding"]="identity";try{d.host=new URL(l).host}catch{}return d}async function xt(t,l,d,m){const p=Ue(l.vault),b=m?m.clock():0;let x=b,k=!0;const T=()=>{m&&k&&(m.lap("upstream",b),x=m.clock(),k=!1)};await ro(l,{onText:n=>{T(),Pe(l.id);const o=p.push(n);o&&t.write(d.sseDelta(o))},onToolRequest:({name:n,restoredArgs:o,toolId:f})=>{T(),Pe(l.id);const c=p.flush();c&&t.write(d.sseDelta(c)),t.write(d.sseToolCalls([{id:f,name:n,arguments:JSON.stringify(o)}])),t.write(d.sseToolFinish()),m&&m.lap("stream",x),t.end(),m?.commit()},onDone:()=>{const n=p.flush();n&&t.write(d.sseDelta(n)),t.write(d.sseTail()),m&&m.lap("stream",x),t.end(),we(l.id),m?.commit()},onError:n=>{t.write(`data: ${JSON.stringify({error:{message:n.message,type:"bridge_error"}})}
10
10
 
11
- `),t.end(),pe(l.id),r?.commit()}})}async function lr(t,l,{kind:d,adapter:r,agent:o,run:u=null},c,g,w,P,p,z=null,x=null){const{messages:I,system:Y}=r.toTurn(c),{agentModel:L}=De(c?.model,w),R=qe(w,{...L?{model:L}:{},...u||{}}),N=ee(w.bridge.token),$=ve(d,c?.model||o),j={tier:w.redaction.tier==="full"?"full":"basic",dictionary:_t(w.redaction,P),entities:[]},J=await re(w),T=Ht({vault:g,redactOpts:j,bridgeUrl:J,token:N,harness:z});let Z;try{Z=await Jt({bridgeUrl:J,agent:o,token:N,messages:I,system:Y,specs:Wt(p),options:R,signal:void 0})}catch(q){return pe(T.id),x?.commit(),s(l,502,{error:{message:`bridge: ${q.message}`,type:"bridge_error"}})}return T.reader=Z.body.getReader(),l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write($.sseHead()),ht(l,T,$,x)}async function cr(t,l,d,r,o=null){Se(l.id),l.rounds=(l.rounds||0)+1;try{const c=o?o.clock():0;await Ft(l,d),o&&o.lap("redact",c)}catch(c){return pe(l.id),o?.commit(),s(t,502,{error:{message:`tool-result: ${c.message}`,type:"bridge_error"}})}const u=ve("openai",r||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(u.sseHead()),ht(t,l,u,o)}async function dr(t,l,{kind:d,adapter:r,redactable:o,pathname:u,agentOverride:c,harness:g,trace:w,run:P=null},p,z,x,I){if(!o)return w?.commit(),s(l,404,{error:`endpoint ${u} not supported by the bridge backend`});if(d==="openai"){const e=r.extractLatestToolResult(p);if(e){const a=He(e.tool_call_id),i=a&&Je(a.gwId);if(i)return cr(l,i,e.content,p?.model,w)}const n=r.extractTools(p);if(n.length&&p?.stream===!0)return lr(t,l,{kind:d,adapter:r,agent:c||ut(p?.model,x),run:P},p,z,x,I,n,g,w)}const{messages:Y,system:L}=r.toTurn(p),R=c||ut(p?.model,x),N=p?.stream===!0,$=ve(d,p?.model||R),j=ee(x.bridge.token),J=new AbortController;l.on("close",()=>{l.writableFinished||J.abort()});const{agentModel:T}=De(p?.model,x),Z={bridgeUrl:await re(x),agent:R,token:j,messages:Y,system:L,signal:J.signal,options:qe(x,{...T?{model:T}:{},...P||{}})};if(!N)try{let e="";const n=w?w.clock():0;await Ve(Z,m=>{e+=m}),w&&w.lap("upstream",n);const a=w?w.clock():0,i=$.full(Tt(e,z));return w&&w.lap("restore",a),l.writeHead(200,{"content-type":$.contentType}),l.end(i),w?.commit()}catch(e){return w?.commit(),s(l,502,{error:{message:`bridge backend failed: ${e.message}`,type:"bridge_error"}})}l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write($.sseHead());const q=Re(z),ie=w?w.clock():0;let le=ie;try{let e=!0;await Ve(Z,a=>{w&&e&&(w.lap("upstream",ie),le=w.clock(),e=!1);const i=q.push(a);i&&l.write($.sseDelta(i))},$.sseActivity?a=>{try{l.write($.sseActivity(vt(a,z)))}catch{}}:null);const n=q.flush();n&&l.write($.sseDelta(n)),l.write($.sseTail())}catch(e){l.write(`data: ${JSON.stringify({error:{message:e.message,type:"bridge_error"}})}
11
+ `),t.end(),we(l.id),m?.commit()}})}async function Ar(t,l,{kind:d,adapter:m,agent:p,run:b=null},x,k,T,n,o,f=null,c=null){const{messages:A,system:F}=m.toTurn(x),{agentModel:U}=Le(x?.model,T),v=ut(T,{...U?{model:U}:{},...b||{}}),W=ae(T.bridge.token),B=Ee(d,x?.model||p),z={tier:T.redaction.tier==="full"?"full":"basic",dictionary:It(T.redaction,n),entities:[]},oe=await ce(T),V=oo({vault:k,redactOpts:z,bridgeUrl:oe,token:W,harness:f});let K;try{K=await to({bridgeUrl:oe,agent:p,token:W,messages:A,system:F,specs:so(o),options:v,signal:void 0})}catch(j){return we(V.id),c?.commit(),s(l,502,{error:{message:`bridge: ${j.message}`,type:"bridge_error"}})}return V.reader=K.body.getReader(),l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write(B.sseHead()),xt(l,V,B,c)}async function Nr(t,l,d,m,p=null){Pe(l.id),l.rounds=(l.rounds||0)+1;try{const x=p?p.clock():0;await no(l,d),p&&p.lap("redact",x)}catch(x){return we(l.id),p?.commit(),s(t,502,{error:{message:`tool-result: ${x.message}`,type:"bridge_error"}})}const b=Ee("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(b.sseHead()),xt(t,l,b,p)}async function Br(t,l,{kind:d,adapter:m,redactable:p,pathname:b,agentOverride:x,harness:k,trace:T,run:n=null},o,f,c,A){if(!p)return T?.commit(),s(l,404,{error:`endpoint ${b} not supported by the bridge backend`});if(d==="openai"){const M=m.extractLatestToolResult(o);if(M){const H=Ye(M.tool_call_id),ee=H&&Ze(H.gwId);if(ee)return Nr(l,ee,M.content,o?.model,T)}const $=m.extractTools(o);if($.length&&o?.stream===!0)return Ar(t,l,{kind:d,adapter:m,agent:x||Tt(o?.model,c),run:n},o,f,c,A,$,k,T)}const{messages:F,system:U}=m.toTurn(o),v=x||Tt(o?.model,c),W=o?.stream===!0,B=Ee(d,o?.model||v),z=ae(c.bridge.token),oe=new AbortController;l.on("close",()=>{l.writableFinished||oe.abort()});const{agentModel:V}=Le(o?.model,c),K={bridgeUrl:await ce(c),agent:v,token:z,messages:F,system:U,signal:oe.signal,options:ut(c,{...V?{model:V}:{},...n||{}})};if(!W)try{let M="";const $=T?T.clock():0;await Ke(K,he=>{M+=he}),T&&T.lap("upstream",$);const H=T?T.clock():0,ee=B.full(Mt(M,f));return T&&T.lap("restore",H),l.writeHead(200,{"content-type":B.contentType}),l.end(ee),T?.commit()}catch(M){return T?.commit(),s(l,502,{error:{message:`bridge backend failed: ${M.message}`,type:"bridge_error"}})}l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write(B.sseHead());const j=Ue(f),me=T?T.clock():0;let se=me;try{let M=!0;await Ke(K,H=>{T&&M&&(T.lap("upstream",me),se=T.clock(),M=!1);const ee=j.push(H);ee&&l.write(B.sseDelta(ee))},B.sseActivity?H=>{try{l.write(B.sseActivity(Ct(H,f)))}catch{}}:null);const $=j.flush();$&&l.write(B.sseDelta($)),l.write(B.sseTail())}catch(M){l.write(`data: ${JSON.stringify({error:{message:M.message,type:"bridge_error"}})}
12
12
 
13
- `)}w&&w.lap("stream",le),l.end(),w?.commit()}function ur(t,l,d=""){const r=String(t||"").replace(/\/+$/,""),o=String(l||"").split("/")[1];return o&&r.endsWith(`/${o}`)?r.slice(0,-(o.length+1))+l+d:r+l+d}const mr=9e4;function pr(t,l,d){if(l===d)return t;const r=l/d,o=new Float32Array(Math.floor(t.length/r));for(let u=0;u<o.length;u++){const c=u*r,g=Math.floor(c),w=Math.min(t.length-1,g+1),P=c-g;o[u]=t[g]*(1-P)+t[w]*P}return o}const hr=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];function Ie(t,l){const d=new URLSearchParams;for(const u of t.searchParams.getAll("dir"))u&&d.append("dir",u);const r=t.searchParams.get("workdir")||String(l?.bridge?.workingDir||"").trim();r&&d.set("workdir",r);const o=d.toString();return o?`?${o}`:""}async function yr(t,l,{adapter:d,kind:r,pathname:o,search:u,base:c,destKey:g,destProtocol:w,harness:P,trace:p},z,x){let I;const Y=p?p.clock():0;try{const $=ir(t.headers,c);g&&(w==="anthropic"?($["x-api-key"]=g,delete $.authorization):$.authorization=`Bearer ${g}`);const j=Et(ur(c,o,u)).toString();I=await fetch(j,{method:t.method,headers:$,body:["GET","HEAD"].includes(t.method)?void 0:z})}catch($){return p?.commit(),s(l,502,{error:`upstream fetch failed: ${$.message}`})}const L=I.headers.get("content-type")||"",R={};if(I.headers.forEach(($,j)=>{it.has(j.toLowerCase())||(R[j]=$)}),L.includes("text/event-stream")&&I.body){p&&p.lap("upstream",Y);const $=p?p.clock():0;l.writeHead(I.status,R);const j=r==="openai"?St(I.body,l,x,P):kt(I.body,l,x);return Promise.resolve(j).finally(()=>{p&&p.lap("stream",$),p?.commit()})}const N=Buffer.from(await I.arrayBuffer());if(p&&p.lap("upstream",Y),x&&L.includes("application/json"))try{const $=p?p.clock():0,j=d.restoreResponse(JSON.parse(N.toString("utf8")),x,P);return p&&p.lap("restore",$),l.writeHead(I.status,{...R,"content-type":"application/json"}),l.end(Buffer.from(JSON.stringify(j),"utf8")),p?.commit()}catch{}l.writeHead(I.status,R),l.end(N),p?.commit()}function fr(t=je()){Dt(t.allowedExtensionIds||[]);const l=[],d=r=>{l.push(r),l.length>50&&l.shift()};return gt(async(r,o)=>{const u=new URL(r.url,"http://127.0.0.1"),c=u.pathname;if(!lt(r.headers.host))return s(o,403,{error:"loopback only"});if(!qo(r.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(r.headers.origin&&er(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(c==="/admin/token"&&r.method==="POST")return H(r)?s(o,200,{token:ke()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(c==="/pair/code"&&r.method==="POST"){if(!H(r))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Ct();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(c==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=It(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${me(r)} caller`),s(o,403,{error:n.reason});console.log(`[gateway] paired a ${me(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const a=ee(t.bridge?.token);return s(o,200,{ok:!0,token:Bt()||ke(),...a?{bridgeToken:a}:{}})}if(c==="/whoami"&&r.method==="POST"){const e=me(r);return s(o,200,{ok:!0,trust:e,paired:Nt(e),version:K})}if(c==="/audit"&&r.method==="GET")return H(r)?s(o,200,Mt(t,{version:K,startedAt:ct,managed:ce()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((c==="/config"||c==="/logs"||c==="/update"&&r.method!=="GET")&&!H(r))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(c==="/update"&&r.method==="GET"){const e=await io(K,{force:u.searchParams.get("force")==="1"}).catch(n=>({current:K,updateAvailable:!1,error:String(n?.message||n)}));return s(o,200,{ok:!0,update:e,job:uo()})}if(c==="/update"&&r.method==="POST"){const e=co(K);return s(o,e.already?409:202,{ok:!0,job:e})}if((c==="/v1/history/key"||c==="/v1/history/ingest-backup")&&r.method==="POST"&&!H(r))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(c==="/v1/history/records"&&r.method==="PUT"&&!H(r))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/history/ingest"||c==="/v1/history/clear")&&r.method==="POST"&&!H(r))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/memory/remember"||c==="/v1/memory/forget"||c==="/v1/memory/sync"||c==="/v1/memory/clear")&&r.method==="POST"&&!H(r))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/prefs"||c.startsWith("/v1/prefs/")||c.startsWith("/v1/teams")||c.startsWith("/v1/agents")||c.startsWith("/v1/projects"))&&!H(r))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(c.startsWith("/v1/observability")&&!H(r))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&c==="/health"){const e=A.health(),n=S.health();return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,pairing:!0,...ce()?{managed:ce()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...be?{bridge:be.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Pe,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Ze,voice:t.tts?.voice||X,runtime:n.runtime,dtype:n.dtype}})}if(c==="/status"&&r.method==="GET"){wt(t);const e=await te(t.pro?.entitlementToken),n=await pt(t);return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,...ce()?{managed:ce()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:n.configured,ready:n.ok,model:n.model,url:n.url},detector:Ce(t),pro:{unlocked:e},usage:Lo(t),uptimeSeconds:Math.floor((Date.now()-ct)/1e3),update:lo(K)})}if(c==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=O.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:n})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/v1/prefs"&&r.method==="GET"){const e=String(u.searchParams.get("section")||"");return u.searchParams.get("stamps")?s(o,200,{ok:!0,revision:F.revision,stamps:F.stamps()}):s(o,200,{ok:!0,revision:F.revision,sections:F.get(e)})}if(c==="/v1/prefs"&&(r.method==="POST"||r.method==="PUT"))try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=F.put(e.sections||{},{by:e.by||""});return n.applied.length&&rt(n.applied,e.by||""),s(o,200,{ok:!0,...n})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(c==="/v1/prefs"&&r.method==="DELETE"){const e=String(u.searchParams.get("section")||""),n=e?F.remove(e):!1;return n&&rt([e],""),s(o,200,{ok:!0,removed:n})}if(c==="/v1/prefs/events"&&r.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)}
13
+ `)}T&&T.lap("stream",se),l.end(),T?.commit()}function Dr(t,l,d=""){const m=String(t||"").replace(/\/+$/,""),p=String(l||"").split("/")[1];return p&&m.endsWith(`/${p}`)?m.slice(0,-(p.length+1))+l+d:m+l+d}const Cr=9e4;function Mr(t,l,d){if(l===d)return t;const m=l/d,p=new Float32Array(Math.floor(t.length/m));for(let b=0;b<p.length;b++){const x=b*m,k=Math.floor(x),T=Math.min(t.length-1,k+1),n=x-k;p[b]=t[k]*(1-n)+t[T]*n}return p}const Ir=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];function Ge(t,l){const d=new URLSearchParams;for(const b of t.searchParams.getAll("dir"))b&&d.append("dir",b);const m=t.searchParams.get("workdir")||String(l?.bridge?.workingDir||"").trim();m&&d.set("workdir",m);const p=d.toString();return p?`?${p}`:""}async function jr(t,l,{adapter:d,kind:m,pathname:p,search:b,base:x,destKey:k,destProtocol:T,harness:n,trace:o},f,c){let A;const F=o?o.clock():0;try{const B=Er(t.headers,x);k&&(T==="anthropic"?(B["x-api-key"]=k,delete B.authorization):B.authorization=`Bearer ${k}`);const z=Gt(Dr(x,p,b)).toString();A=await fetch(z,{method:t.method,headers:B,body:["GET","HEAD"].includes(t.method)?void 0:f})}catch(B){return o?.commit(),s(l,502,{error:`upstream fetch failed: ${B.message}`})}const U=A.headers.get("content-type")||"",v={};if(A.headers.forEach((B,z)=>{wt.has(z.toLowerCase())||(v[z]=B)}),U.includes("text/event-stream")&&A.body){o&&o.lap("upstream",F);const B=o?o.clock():0;l.writeHead(A.status,v);const z=m==="openai"?Dt(A.body,l,c,n):Bt(A.body,l,c);return Promise.resolve(z).finally(()=>{o&&o.lap("stream",B),o?.commit()})}const W=Buffer.from(await A.arrayBuffer());if(o&&o.lap("upstream",F),c&&U.includes("application/json"))try{const B=o?o.clock():0,z=d.restoreResponse(JSON.parse(W.toString("utf8")),c,n);return o&&o.lap("restore",B),l.writeHead(A.status,{...v,"content-type":"application/json"}),l.end(Buffer.from(JSON.stringify(z),"utf8")),o?.commit()}catch{}l.writeHead(A.status,v),l.end(W),o?.commit()}function Rr(t=Ve()){let l=null;const d=()=>{if(!l){const n=t.read||{};l=Ro({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return l};let m=null;const p=()=>(m||(m=Mo({onLog:n=>console.warn(`[extract worker] ${n}`)})),m);let b=null;const x=()=>{if(!b){const n=t.search||{},o=n.searxng?.url?Jo({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;b=Lo({reader:d(),searxng:o,defaultProvider:n.provider||"auto",redact:async f=>{let c=f;return await ge([xe(()=>c,A=>{c=A})],{...t.redaction,tier:"basic"},{isPro:!0}),c}})}return b};Ht(t.allowedExtensionIds||[]);const k=[],T=n=>{k.push(n),k.length>50&&k.shift()};return Et(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),c=f.pathname;if(!kt(n.headers.host))return s(o,403,{error:"loopback only"});if(!Sr(n.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(n.headers.origin&&vr(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(c==="/admin/token"&&n.method==="POST")return Z(n)?s(o,200,{token:$e()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(c==="/pair/code"&&n.method==="POST"){if(!Z(n))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Ft();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(c==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=Wt(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${be(n)} caller`),s(o,403,{error:r.reason});console.log(`[gateway] paired a ${be(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const a=ae(t.bridge?.token);return s(o,200,{ok:!0,token:Ut()||$e(),...a?{bridgeToken:a}:{}})}if(c==="/whoami"&&n.method==="POST"){const e=be(n);return s(o,200,{ok:!0,trust:e,paired:Vt(e),version:Y})}if(c==="/audit"&&n.method==="GET")return Z(n)?s(o,200,Zt(t,{version:Y,startedAt:St,managed:pe()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((c==="/config"||c==="/logs"||c==="/update"&&n.method!=="GET")&&!Z(n))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(c==="/update"&&n.method==="GET"){const e=await vo(Y,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:Y,updateAvailable:!1,error:String(r?.message||r)}));return s(o,200,{ok:!0,update:e,job:Oo()})}if(c==="/update"&&n.method==="POST"){const e=_o(Y);return s(o,e.already?409:202,{ok:!0,job:e})}if((c==="/v1/history/key"||c==="/v1/history/ingest-backup")&&n.method==="POST"&&!Z(n))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(c==="/v1/history/records"&&n.method==="PUT"&&!Z(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/history/ingest"||c==="/v1/history/clear")&&n.method==="POST"&&!Z(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/memory/remember"||c==="/v1/memory/forget"||c==="/v1/memory/sync"||c==="/v1/memory/clear")&&n.method==="POST"&&!Z(n))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((c==="/v1/prefs"||c.startsWith("/v1/prefs/")||c.startsWith("/v1/teams")||c.startsWith("/v1/agents")||c.startsWith("/v1/projects"))&&!Z(n))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(c.startsWith("/v1/observability")&&!Z(n))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&c==="/health"){const e=D.health(),r=O.health();return s(o,200,{ok:!0,version:Y,backend:t.backend,tier:t.redaction.tier,pairing:!0,...pe()?{managed:pe()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...Oe?{bridge:Oe.status()}:{},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||De,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||at,voice:t.tts?.voice||re,runtime:r.runtime,dtype:r.dtype}})}if(c==="/status"&&n.method==="GET"){Nt(t);const e=await ie(t.pro?.entitlementToken),r=await Ot(t);return s(o,200,{ok:!0,version:Y,backend:t.backend,tier:t.redaction.tier,...pe()?{managed:pe()}:{},...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:ze(t),pro:{unlocked:e},usage:cr(t),uptimeSeconds:Math.floor((Date.now()-St)/1e3),update:To(Y)})}if(c==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=N.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:r})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?s(o,200,{ok:!0,revision:X.revision,stamps:X.stamps()}):s(o,200,{ok:!0,revision:X.revision,sections:X.get(e)})}if(c==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=X.put(e.sections||{},{by:e.by||""});return r.applied.length&&yt(r.applied,e.by||""),s(o,200,{ok:!0,...r})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(c==="/v1/prefs"&&n.method==="DELETE"){const e=String(f.searchParams.get("section")||""),r=e?X.remove(e):!1;return r&&yt([e],""),s(o,200,{ok:!0,removed:r})}if(c==="/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)}
14
14
 
15
- `);e({type:"hello",revision:F.revision,stamps:F.stamps()});const n=i=>e({type:"changed",...i});Ne.add(n);const a=setInterval(()=>{try{o.write(`: keep-alive
15
+ `);e({type:"hello",revision:X.revision,stamps:X.stamps()});const r=i=>e({type:"changed",...i});je.add(r);const a=setInterval(()=>{try{o.write(`: keep-alive
16
16
 
17
- `)}catch{}},25e3);o.on("close",()=>{Ne.delete(n),clearInterval(a)});return}if(c==="/v1/projects"&&r.method==="GET")return s(o,200,{ok:!0,projects:V.list({limit:u.searchParams.get("limit")||50,status:u.searchParams.get("status")||""})});if(c==="/v1/projects/jobs"&&r.method==="GET")return s(o,200,{ok:!0,jobs:V.openJobs()});if(c==="/v1/projects"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:V.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return s(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(c);if(e){const n=e[1],a=e[2]||"",i=e[3]||"",m=e[4]||"",b=()=>s(o,404,{error:{message:`no project ${n}`,type:"not_found"}});if(m){const h=V.get(n);if(!h)return b();const k=h.jobs.find(f=>f.id===i);if(!k)return s(o,404,{error:{message:`no job ${i}`,type:"not_found"}});const y={cfg:t,prefsStore:F,scorecards:se,engines:ae};if(m==="/applications"&&r.method==="GET"){const f=await no(k,{...y,reach:u.searchParams.get("reach")||"any",chatModel:u.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:k,...f})}if(m==="/recruit"&&r.method==="POST"){if(!["open","evaluating"].includes(k.status))return s(o,400,{error:{message:`job ${i} is ${k.status}; only an open job is recruited`,type:"project_error"}});try{const f=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},_=String(f.by||"evaluator").slice(0,80),M=await so(k,{...y,record:h,reach:f.reach||"any",chatModel:f.chatModel||null,evaluation:f.evaluation||null,text:f.text??null,by:_});let E=null;for(const W of M.events)W.type==="job.updated"?E=V.updateJob(n,i,W.job,{by:W.by||_}):E=V.append(n,[W]);return s(o,200,{ok:!0,project:E,decision:M.decision,applications:M.applications,evaluation:M.evaluation})}catch(f){return s(o,400,{error:{message:`recruit: ${f.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&r.method==="GET"){const h=V.get(n,{events:u.searchParams.get("events")==="1"});return h?s(o,200,{ok:!0,project:h}):b()}if(!a&&r.method==="DELETE")return s(o,200,{ok:!0,removed:V.remove(n)});if(r.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const h=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},k=String(h.by||"person").slice(0,80),y=a==="/events"?V.append(n,h.events||[]):i?V.updateJob(n,i,h.patch||h,{by:k}):V.postJob(n,h.job||h,{by:k});return s(o,200,{ok:!0,project:y})}catch(h){return s(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(a==="/events"&&r.method==="GET"){if(!V.get(n))return b();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=_=>o.write(`data: ${JSON.stringify(_)}
17
+ `)}catch{}},25e3);o.on("close",()=>{je.delete(r),clearInterval(a)});return}if(c==="/v1/projects"&&n.method==="GET")return s(o,200,{ok:!0,projects:J.list({limit:f.searchParams.get("limit")||50,status:f.searchParams.get("status")||""})});if(c==="/v1/projects/jobs"&&n.method==="GET")return s(o,200,{ok:!0,jobs:J.openJobs()});if(c==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:J.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return s(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(c);if(e){const r=e[1],a=e[2]||"",i=e[3]||"",u=e[4]||"",y=()=>s(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(u){const h=J.get(r);if(!h)return y();const S=h.jobs.find(w=>w.id===i);if(!S)return s(o,404,{error:{message:`no job ${i}`,type:"not_found"}});const g={cfg:t,prefsStore:X,scorecards:de,engines:ue};if(u==="/applications"&&n.method==="GET"){const w=await wo(S,{...g,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:S,...w})}if(u==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(S.status))return s(o,400,{error:{message:`job ${i} is ${S.status}; only an open job is recruited`,type:"project_error"}});try{const w=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},E=String(w.by||"evaluator").slice(0,80),L=await ko(S,{...g,record:h,reach:w.reach||"any",chatModel:w.chatModel||null,evaluation:w.evaluation||null,text:w.text??null,by:E});let C=null;for(const q of L.events)q.type==="job.updated"?C=J.updateJob(r,i,q.job,{by:q.by||E}):C=J.append(r,[q]);return s(o,200,{ok:!0,project:C,decision:L.decision,applications:L.applications,evaluation:L.evaluation})}catch(w){return s(o,400,{error:{message:`recruit: ${w.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&n.method==="GET"){const h=J.get(r,{events:f.searchParams.get("events")==="1"});return h?s(o,200,{ok:!0,project:h}):y()}if(!a&&n.method==="DELETE")return s(o,200,{ok:!0,removed:J.remove(r)});if(n.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const h=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},S=String(h.by||"person").slice(0,80),g=a==="/events"?J.append(r,h.events||[]):i?J.updateJob(r,i,h.patch||h,{by:S}):J.postJob(r,h.job||h,{by:S});return s(o,200,{ok:!0,project:g})}catch(h){return s(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(a==="/events"&&n.method==="GET"){if(!J.get(r))return y();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=E=>o.write(`data: ${JSON.stringify(E)}
18
18
 
19
- `);let k=u.searchParams.has("after")?Number(u.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:V.get(n),after:k}});const y=V.watch(n,_=>{_.seq>k&&(k=_.seq,h(_))});for(const _ of V.eventsSince(n,k))k=_.seq,h(_);const f=setInterval(()=>{try{o.write(`: keep
19
+ `);let S=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:J.get(r),after:S}});const g=J.watch(r,E=>{E.seq>S&&(S=E.seq,h(E))});for(const E of J.eventsSince(r,S))S=E.seq,h(E);const w=setInterval(()=>{try{o.write(`: keep
20
20
 
21
- `)}catch{}},25e3);r.on("close",()=>{clearInterval(f),y()});return}}}if(c==="/v1/agents/scorecards"&&r.method==="GET")return s(o,200,{ok:!0,agents:se.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(c);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return s(o,200,{ok:!0,...await se.get(n)});if(r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},i=await se.append({agentId:n,kind:"rating",runId:a.runId,taskId:a.taskId,jobId:a.jobId,rating:{by:String(a.by||"person").slice(0,40),score:a.score,note:a.note,about:a.about},refs:a.refs});return ae.fromRating(se.chains.get(n)||[],{...i,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:i})}catch(a){return s(o,400,{error:{message:`scorecard: ${a.message}`,type:"scorecard_error"}})}}}if(c==="/v1/engines"&&r.method==="GET"){const e=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:ae.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(c);if(e){const n=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&r.method==="GET"){const a=Number(u.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await ae.get(n,{entries:u.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&r.method==="POST")try{const a=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},i=a.engine||or(n);if(!i)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const m=await ae.append({...a,engine:i,kind:a.kind||"call"});return m.key!==n?s(o,400,{error:{message:`model-ledger: entry is for ${m.key}, not ${n}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:m})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(c==="/v1/teams/runs"&&r.method==="GET")return s(o,200,{ok:!0,runs:C.list({limit:u.searchParams.get("limit")||50,team:u.searchParams.get("team")||""})});if(c==="/v1/teams/runs"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return s(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(c);if(e){const n=e[1],a=e[2]||"";if(!a&&r.method==="GET"){const i=C.get(n,{events:u.searchParams.get("events")==="1"});return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(!a&&r.method==="DELETE")return C.stop(n),s(o,200,{ok:!0,removed:C.remove(n)});if(a==="/stop"&&r.method==="POST"){const i=C.stop(n);return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${n}`,type:"not_found"}})}if(a==="/checkpoint"&&r.method==="GET")try{return s(o,200,{ok:!0,checkpoint:C.checkpoint(n)})}catch(i){return s(o,404,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&r.method==="POST")try{const i=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=a==="/handoff"?C.handoff(n,{taskId:i.taskId,model:i.model,by:i.by,reason:i.reason}):C.claim(n,{client:i.client});return s(o,200,{ok:!0,run:m})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&r.method==="DELETE")try{return s(o,200,{ok:!0,run:C.removeThread(n,{threadId:a.slice(9),by:"person"})})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&r.method==="POST")try{const i=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},m=String(i.by||"person").slice(0,40),b=a==="/answer"?C.answer(n,{threadId:i.threadId,text:i.text,by:m}):a==="/decide"?C.decide(n,{postId:i.postId,status:i.status,by:m}):C.post(n,{threadId:i.threadId,text:i.text,by:m,kind:i.kind,replyTo:i.replyTo});return s(o,200,{ok:!0,run:b})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="POST")try{const i=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:C.append(n,i.events||[])})}catch(i){return s(o,i.message.startsWith("no run")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&r.method==="GET"){if(!C.get(n))return s(o,404,{error:{message:`no run ${n}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const i=y=>o.write(`data: ${JSON.stringify(y)}
21
+ `)}catch{}},25e3);n.on("close",()=>{clearInterval(w),g()});return}}}if(c==="/v1/agents/scorecards"&&n.method==="GET")return s(o,200,{ok:!0,agents:de.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(c);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return s(o,200,{ok:!0,...await de.get(r)});if(n.method==="POST")try{const a=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},i=await de.append({agentId:r,kind:"rating",runId:a.runId,taskId:a.taskId,jobId:a.jobId,rating:{by:String(a.by||"person").slice(0,40),score:a.score,note:a.note,about:a.about},refs:a.refs});return ue.fromRating(de.chains.get(r)||[],{...i,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:i})}catch(a){return s(o,400,{error:{message:`scorecard: ${a.message}`,type:"scorecard_error"}})}}}if(c==="/v1/capabilities"&&n.method==="GET")return s(o,200,Do(t,{version:Y,reader:l,searcher:b,extract:p()}));if(c==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await Co(e,{ensure:()=>ke(t),model:P.health().model});return s(o,r.status,r.body)}catch(r){return s(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(c==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await _(n,Math.max(t.maxBodyBytes,Math.ceil(jo*4/3)+1024))).toString("utf8"))}catch{return s(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Io(e,{service:p()});return s(o,r.status,r.body)}if(c==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await d().read(e);return s(o,r.status,r.body)}if(c==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}const r=await x().search(e);return s(o,r.status,r.body)}if(/^\/v1\/search\/./.test(c)&&n.method==="GET"){let e;try{e=decodeURIComponent(c.slice(11))}catch{e=c.slice(11)}const r=f.searchParams.has("read")?Math.max(0,Math.min(10,Number(f.searchParams.get("read"))||0)):Go.aliasRead,a=await x().search({q:e,read:r,limit:Math.max(r,5)});return s(o,a.status,a.status===200?zo(a.body):a.body)}if(/^\/v1\/read\/./.test(c)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),a=/application\/json/i.test(n.headers.accept||""),i=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",u=await d().read({url:r,format:i});return u.status!==200||a?s(o,u.status,u.status===200?{code:200,status:2e4,data:u.body}:u.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":u.body.provider}),o.end(Vo(u.body)))}if(c==="/v1/engines"&&n.method==="GET"){const e=Number(f.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:ue.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(c);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const a=Number(f.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await ue.get(r,{entries:f.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&n.method==="POST")try{const a=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},i=a.engine||_r(r);if(!i)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const u=await ue.append({...a,engine:i,kind:a.kind||"call"});return u.key!==r?s(o,400,{error:{message:`model-ledger: entry is for ${u.key}, not ${r}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:u})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(c==="/v1/teams/runs"&&n.method==="GET")return s(o,200,{ok:!0,runs:R.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(c==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:R.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return s(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(c);if(e){const r=e[1],a=e[2]||"";if(!a&&n.method==="GET"){const i=R.get(r,{events:f.searchParams.get("events")==="1"});return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!a&&n.method==="DELETE")return R.stop(r),s(o,200,{ok:!0,removed:R.remove(r)});if(a==="/stop"&&n.method==="POST"){const i=R.stop(r);return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(a==="/checkpoint"&&n.method==="GET")try{return s(o,200,{ok:!0,checkpoint:R.checkpoint(r)})}catch(i){return s(o,404,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&n.method==="POST")try{const i=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},u=a==="/handoff"?R.handoff(r,{taskId:i.taskId,model:i.model,by:i.by,reason:i.reason}):R.claim(r,{client:i.client});return s(o,200,{ok:!0,run:u})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&n.method==="DELETE")try{return s(o,200,{ok:!0,run:R.removeThread(r,{threadId:a.slice(9),by:"person"})})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&n.method==="POST")try{const i=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},u=String(i.by||"person").slice(0,40),y=a==="/answer"?R.answer(r,{threadId:i.threadId,text:i.text,by:u}):a==="/decide"?R.decide(r,{postId:i.postId,status:i.status,by:u}):R.post(r,{threadId:i.threadId,text:i.text,by:u,kind:i.kind,replyTo:i.replyTo});return s(o,200,{ok:!0,run:y})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&n.method==="POST")try{const i=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:R.append(r,i.events||[])})}catch(i){return s(o,i.message.startsWith("no run")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&n.method==="GET"){if(!R.get(r))return s(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=g=>o.write(`data: ${JSON.stringify(g)}
22
22
 
23
- `),m=u.searchParams.has("after")?Number(u.searchParams.get("after")):NaN;let b=Number.isFinite(m)?m:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:C.get(n),after:b}});const h=C.watch(n,y=>{y.seq==null?i(y):y.seq>b&&(b=y.seq,i(y))});for(const y of C.eventsSince(n,b))b=y.seq,i(y);const k=setInterval(()=>{try{o.write(`: keep-alive
23
+ `),u=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let y=Number.isFinite(u)?u:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:R.get(r),after:y}});const h=R.watch(r,g=>{g.seq==null?i(g):g.seq>y&&(y=g.seq,i(g))});for(const g of R.eventsSince(r,y))y=g.seq,i(g);const S=setInterval(()=>{try{o.write(`: keep-alive
24
24
 
25
- `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(k)});return}}}if(c==="/v1/memory/list"&&r.method==="GET")return s(o,200,{ok:!0,size:U.size,memories:U.list()});if(c==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=U.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 s(o,200,{ok:!0,size:U.size,...n})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=U.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 s(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:U.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=U.forget(String(e.query||""));return s(o,200,{ok:!0,removed:n,size:U.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=U.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...n,memories:U.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/clear"&&r.method==="POST")return s(o,200,{ok:!0,dropped:U.clear(),size:U.size});if(c==="/v1/history/clear"&&r.method==="POST"){const e=O.clear();return s(o,200,{ok:!0,dropped:e,size:O.size})}if(c==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=O.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 s(o,200,{ok:!0,size:O.size,newest:O.newest,results:n})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),a=Wo(n,{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},m=Math.min(30,Math.max(5,Number(e.limit)||10)*2),b=await Ko(a,k=>O.search(k,{limit:m,...i}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=i.type?b:[...b.filter(k=>k.type==="brief"),...b.filter(k=>k.type!=="brief")];return s(o,200,{ok:!0,size:O.size,newest:O.newest,queries:a,results:h})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/related"&&r.method==="GET"){const e=String(u.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(u.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:O.related(e,{limit:n})})}if(c==="/v1/history/status"&&r.method==="GET")return s(o,200,{ok:!0,size:O.size,newest:O.newest,bytes:O.bytes,lossless:O.lossless?{records:O.lossless.size,newest:O.lossless.newest}:null});if(c==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:O.size,bytes:O.bytes,newest:O.newest}},access:Be.snapshot(e)})}if(c==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},n=Be.push(tt({ts:Date.now(),...e}));return s(o,200,{ok:!0,event:n})}catch(e){return s(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(c==="/v1/history/records"&&r.method==="PUT"){const e=O.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{},a=String(n.host||"").slice(0,80),i=Number(n.at)||Date.now(),m=[];let b=0;const h={upserts:[],removes:[]},k=y=>{if(!y||y.deletedAt){y?.id&&h.removes.push(y.id);return}try{const f=po(y);f&&h.upserts.push(f)}catch{}};if(Array.isArray(n.records)){const y=e.upsert(n.records,{host:a,at:i});m.push(...y);for(const f of n.records)y.includes(f?.id)&&k(f)}if(Array.isArray(n.entries)){const y=_e(),f=y?fo((E,W)=>ho(y,{salt:E,iterations:W})):null,_=async E=>{if(!f||!E.blob)return null;const W=await f(E.blob),de=E.blob.compression&&E.blob.compression!=="none"?go(bo,E.blob.compression):null;return yo(E.blob,W,{codec:de})},M=await e.upsertEntries(n.entries,{open:_});m.push(...M.written),b+=M.sealed;for(const E of M.written)k(e.get(E))}return(h.upserts.length||h.removes.length)&&O.bulk(h),m.length&&ge({ids:m}),s(o,200,{ok:!0,written:m.length,ids:m,sealed:b,size:e.size})}catch(n){return s(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(c==="/v1/history/stream"&&r.method==="GET"){const e=O.lossless;if(!e)return s(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
26
- data: ${JSON.stringify({newest:e.newest,size:e.size,version:K,prefsRevision:F.revision})}
25
+ `)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(S)});return}}}if(c==="/v1/memory/list"&&n.method==="GET")return s(o,200,{ok:!0,size:Q.size,memories:Q.list()});if(c==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=Q.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 s(o,200,{ok:!0,size:Q.size,...r})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=Q.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 s(o,200,{ok:!0,action:r.action,record:r.record,replaced:r.replaces||null,size:Q.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=Q.forget(String(e.query||""));return s(o,200,{ok:!0,removed:r,size:Q.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(c==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=Q.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...r,memories:Q.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(c==="/v1/memory/clear"&&n.method==="POST")return s(o,200,{ok:!0,dropped:Q.clear(),size:Q.size});if(c==="/v1/history/clear"&&n.method==="POST"){const e=N.clear();return s(o,200,{ok:!0,dropped:e,size:N.size})}if(c==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=N.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 s(o,200,{ok:!0,size:N.size,newest:N.newest,results:r})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),a=yr(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},u=Math.min(30,Math.max(5,Number(e.limit)||10)*2),y=await fr(a,S=>N.search(S,{limit:u,...i}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=i.type?y:[...y.filter(S=>S.type==="brief"),...y.filter(S=>S.type!=="brief")];return s(o,200,{ok:!0,size:N.size,newest:N.newest,queries:a,results:h})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(c==="/v1/history/related"&&n.method==="GET"){const e=String(f.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(f.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:N.related(e,{limit:r})})}if(c==="/v1/history/status"&&n.method==="GET")return s(o,200,{ok:!0,size:N.size,newest:N.newest,bytes:N.bytes,lossless:N.lossless?{records:N.lossless.size,newest:N.lossless.newest}:null});if(c==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:N.size,bytes:N.bytes,newest:N.newest}},access:Re.snapshot(e)})}if(c==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},r=Re.push(pt({ts:Date.now(),...e}));return s(o,200,{ok:!0,event:r})}catch(e){return s(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(c==="/v1/history/records"&&n.method==="PUT"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{},a=String(r.host||"").slice(0,80),i=Number(r.at)||Date.now(),u=[];let y=0;const h={upserts:[],removes:[]},S=g=>{if(!g||g.deletedAt){g?.id&&h.removes.push(g.id);return}try{const w=$o(g);w&&h.upserts.push(w)}catch{}};if(Array.isArray(r.records)){const g=e.upsert(r.records,{host:a,at:i});u.push(...g);for(const w of r.records)g.includes(w?.id)&&S(w)}if(Array.isArray(r.entries)){const g=Ae(),w=g?Ao((C,q)=>Po(g,{salt:C,iterations:q})):null,E=async C=>{if(!w||!C.blob)return null;const q=await w(C.blob),ye=C.blob.compression&&C.blob.compression!=="none"?No(Bo,C.blob.compression):null;return Eo(C.blob,q,{codec:ye})},L=await e.upsertEntries(r.entries,{open:E});u.push(...L.written),y+=L.sealed;for(const C of L.written)S(e.get(C))}return(h.upserts.length||h.removes.length)&&N.bulk(h),u.length&&_e({ids:u}),s(o,200,{ok:!0,written:u.length,ids:u,sealed:y,size:e.size})}catch(r){return s(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(c==="/v1/history/stream"&&n.method==="GET"){const e=N.lossless;if(!e)return s(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
26
+ data: ${JSON.stringify({newest:e.newest,size:e.size,version:Y,prefsRevision:X.revision})}
27
27
 
28
- `),Q.add(o),r.on("close",()=>Q.delete(o));return}if(c==="/v1/history/records"&&r.method==="GET"){const e=O.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const n=e.since({since:Number(u.searchParams.get("since"))||0,cursor:u.searchParams.get("cursor")||"",limit:Number(u.searchParams.get("limit"))||200,kind:u.searchParams.get("kind")||null});return s(o,200,{ok:!0,...n,size:e.size,newest:e.newest})}if(c==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(u.searchParams.get("limit"))||50)),n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=u.searchParams.get("type")||null;return s(o,200,{ok:!0,...O.list({limit:e,offset:n,type:a})})}if(c==="/v1/history/get"&&r.method==="GET"){const e=u.searchParams.get("maxChars")!=null?Math.max(1,Number(u.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(u.searchParams.get("offset"))||0),a=O.get(String(u.searchParams.get("id")||""),{maxChars:e,offset:n});return a?s(o,200,{ok:!0,record:a}):s(o,404,{error:{message:"no such record",type:"not_found"}})}if(c==="/v1/history/key"&&r.method==="GET")return s(o,200,{ok:!0,hasKey:Ue()});if(c==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Yt(String(e.passphrase)):Qt();const n=e.passphrase?await $e(O,String(e.passphrase)):{ok:!0,ingested:0};return n.ok&&n.whole&&ge(),s(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(c==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await $e(O,_e());return e.ok&&e.whole&&ge(),s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/ner"){if(r.method==="GET"){const e=await pt(t);return s(o,e.ok?200:503,e)}if(r.method==="POST"){if(await Te(t),D.state()!=="off"){if(!D.isReady()){const n=D.health();return s(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await v(r,t.maxBodyBytes);let a="";try{a=JSON.parse(n.toString("utf8"))?.text||""}catch{}const i=await D.detect(a);return s(o,200,{entities:i})}catch(n){return s(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=mt(t);if(!e){const n=D.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:D.state(),model:t.ner?.model||null})}try{const n=await v(r,t.maxBodyBytes),a=await Ge(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),i=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(i)}catch(n){return s(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(c==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ce(t)});try{let n=e;const a=await te(t.pro?.entitlementToken);await Te(t);const i=await we([Me(()=>n,m=>{n=m})],t.redaction,{isPro:a});return s(o,200,{text:n,count:i.count||0,sanitized:i.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:dt(i.vault,"types")||[],detector:Ce(t)})}catch(n){return s(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(c==="/ner/models"){if(r.method==="GET"){const e=D.health().model||t.ner?.model||null,n=wo.map(a=>({...a,installed:D.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",custom:!0,installed:D.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:D.state(),progress:D.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(ko(n)||So(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Vo(t,n);try{ne(t,oe())}catch{}return D.setModel(n,{onLog:a=>console.log(a)}).then(a=>{a&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),s(o,202,{accepted:!0,active:n,state:D.state(),progress:D.progress()})}}if(c==="/stt/models"){if(r.method==="GET"){const e=A.health().model||t.stt?.model||Pe,n=vo.map(a=>({...a,installed:A.modelOnDisk(a.id)}));return e&&!n.some(a=>a.id===e)&&n.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:A.state(),progress:A.progress(),available:n,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:Oo})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(To(n)||_o(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&$o(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{ne(t,oe())}catch{}return A.setModel(n,{onLog:i=>console.log(i),dtype:a||t.stt.dtype||"auto"}),s(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress()})}}if(c==="/diarize/model"){if(r.method==="GET"){const e=B.health();return s(o,200,{active:B.DIARIZE_MODEL,state:e.state,progress:B.progress(),available:[{id:B.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:B.modelOnDisk()}]})}if(r.method==="POST")return B.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:B.DIARIZE_MODEL,state:B.state(),progress:B.progress()})}if(c==="/tts/models"){if(r.method==="GET"){const e=S.health().model||t.tts?.model||Qe(Ae()),n=Ae(),a=Fe.find(m=>m.id===e)||null,i=Fe.map(m=>({...m,installed:S.modelOnDisk(m.id),unavailable:m.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!i.some(m=>m.id===e)&&i.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:S.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:S.state(),progress:S.progress(),available:i,voice:t.tts?.voice||(fe(e)==="pocket-tts"?he:X),arch:S.arch(),supportsVoices:S.arch()?S.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:S.arch()?S.supportsCustomVoices():!!a?.customVoices,sampleRate:S.sampleRate(),voices:S.isPocket()||!S.arch()&&fe(e)==="pocket-tts"?(S.builtinVoices().length?S.builtinVoices():Do).map(m=>({id:m,label:m[0].toUpperCase()+m.slice(1),lang:"en",installed:S.builtinVoices().includes(m)})):S.arch()&&S.arch()!=="style-tts2"?[]:Po.map(m=>({...m,installed:S.voiceOnDisk(m.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:S.health().dtype,runtime:S.health().runtime,dtypes:xo})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(Ao(n)||Eo(n)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=e&&typeof e.voice=="string"?e.voice.trim():null;if(a){const m=G.parseCustomVoice(a);if(!(m?!!G.getVoice(m):ye(a)||We(a)&&Ke(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&No(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Ze,voice:X,allowDownload:!0}),n&&(t.tts.model=n),a&&(t.tts.voice=a),n&&!a){const m=Bo(n),b=G.parseCustomVoice(t.tts.voice||""),h=!!(b&&G.getVoice(b));if(m&&!h)if(fe(n)==="pocket-tts")t.tts.voice=he;else{const y=G.listVoices();t.tts.voice=y.length?`custom:${y[0].id}`:""}else!m&&h&&(t.tts.voice=X);const k=fe(n)==="pocket-tts";k&&!G.parseCustomVoice(t.tts.voice||"")&&!ye(t.tts.voice)&&(t.tts.voice=he),!k&&ye(t.tts.voice)&&(t.tts.voice=X)}i&&(t.tts.dtype=i==="auto"?null:i);try{ne(t,oe())}catch{}return n&&S.setModel(n,{onLog:m=>console.log(m),dtype:i||t.tts.dtype||"auto"}),s(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:S.state(),progress:S.progress()})}}if(c==="/tts/voices"){if(r.method==="GET")return s(o,200,{voices:G.listVoices(),usable:S.supportsCustomVoices(),embedder:B.DIARIZE_MODEL,embedderReady:B.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,i=e&&typeof e.id=="string"?e.id.trim():"";if(i){if(!G.getVoice(i))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...G.renameVoice(i,n),usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.message,type:"rename_failed"}})}}if(a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!n)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!a||a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!B.isReady()){const f=B.download({onLog:E=>console.log(E)}),_=Symbol("timeout"),M=await Promise.race([f.then(()=>null).catch(E=>E),new Promise(E=>setTimeout(()=>E(_),mr))]);if(M===_||!B.isReady())return s(o,503,{error:{message:M===_?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${B.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:B.progress()})}const m=Float32Array.from(a),b=await B.embed(m);let h=null;try{const f=await S.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:_=>console.log(_)});f&&(h=await f.encodeVoice(pr(m,16e3,24e3)))}catch(f){console.log(`[tts] pocket conditioning unavailable for this voice (${f.message})`)}const k=i?G.replaceVoice(i,{vec:b,pocket:h}):G.saveVoice({name:n,vec:b,pocket:h}),y=i&&n&&n!==k.name?G.renameVoice(i,n):k;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${y.name}" (${(k.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...k,...y,usable:S.supportsCustomVoices()})}catch(m){return s(o,400,{error:{message:m.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=u.searchParams.get("id")||"",n=G.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const a=G.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:X;try{ne(t,oe())}catch{}}return s(o,200,{deleted:n,voice:t.tts?.voice})}}if((c==="/tts"||c==="/v1/audio/speech")&&r.method==="POST"){if(t.tts?.enabled===!1)return s(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Ye)return s(o,413,{error:{message:`text too long (max ${Ye} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=Co(t),m=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,b=m||(i?i.voice:t.tts?.voice||X);if(i&&!jo(b))return s(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 s(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(i){const{audio:ue,contentType:yt,redacted:ft}=await Io({dest:i,text:n,voice:b,speed:a,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await te(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":yt,"Content-Length":String(ue.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(ft)}),o.end(ue)}if(!await S.ready({onLog:ue=>console.log(ue),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Qe(Ae()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:S.health().error||"tts model not ready",type:"tts_unavailable"}});const y=Mo({requested:m,configured:b,engine:S,voices:G,isPocketVoice:ye,isKnownVoice:We,isValidVoiceId:Ke,defaultVoice:X,defaultPocketVoice:he});if(!y.ok)return s(o,y.status,{error:{message:y.message,type:y.type}});const{voice:f,customId:_,speakerEmbedding:M}=y,E=await S.synth(n,{voice:f,speed:a,speakerEmbedding:M}),W=S.sampleRate(),de=h==="pcm"?Buffer.from(new Float32Array(E).buffer):S.toWav(E,W);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(de.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(W),..._||S.isPocket()||S.supportsVoices()?{"X-Tts-Voice":f}:{}}),o.end(de)}catch(k){return s(o,500,{error:{message:k.message,type:"tts_failed"}})}}if(c==="/stt/sessions"&&r.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}A.isReady()||A.init({model:t.stt?.model||Pe,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,onLog:a=>console.log(a)});const n=e?.diarize===!0&&t.stt?.diarize!==!1;n&&!B.isReady()&&B.init({allowDownload:t.stt?.allowDownload!==!1,onLog:a=>console.log(a)});try{const{id:a}=A.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:n,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs});return s(o,201,{id:a,state:A.state()})}catch(a){return s(o,a.code==="too_many_sessions"?429:500,{error:{message:a.message,type:a.code||"stt_error"}})}}{const e=c.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1];if(e[2]==="/audio"&&r.method==="POST")try{const a=await v(r,t.maxBodyBytes);return A.pushAudio(n,A.toFloat32(a)),s(o,200,{ok:!0,state:A.state()})}catch(a){return s(o,a.code==="no_session"?404:400,{error:{message:a.message,type:a.code||"stt_error"}})}if(e[2]==="/events"&&r.method==="GET"){const a=A.getSession(n);if(!a)return s(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 i=f=>o.write(`data: ${JSON.stringify(f)}
28
+ `),te.add(o),n.on("close",()=>te.delete(o));return}if(c==="/v1/history/records"&&n.method==="GET"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(f.searchParams.get("since"))||0,cursor:f.searchParams.get("cursor")||"",limit:Number(f.searchParams.get("limit"))||200,kind:f.searchParams.get("kind")||null});return s(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(c==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||50)),r=Math.max(0,Number(f.searchParams.get("offset"))||0),a=f.searchParams.get("type")||null;return s(o,200,{ok:!0,...N.list({limit:e,offset:r,type:a})})}if(c==="/v1/history/get"&&n.method==="GET"){const e=f.searchParams.get("maxChars")!=null?Math.max(1,Number(f.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(f.searchParams.get("offset"))||0),a=N.get(String(f.searchParams.get("id")||""),{maxChars:e,offset:r});return a?s(o,200,{ok:!0,record:a}):s(o,404,{error:{message:"no such record",type:"not_found"}})}if(c==="/v1/history/key"&&n.method==="GET")return s(o,200,{ok:!0,hasKey:Xe()});if(c==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?uo(String(e.passphrase)):mo();const r=e.passphrase?await Be(N,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&_e(),s(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(c==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await Be(N,Ae());return e.ok&&e.whole&&_e(),s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(c==="/ner"){if(n.method==="GET"){const e=await Ot(t);return s(o,e.ok?200:503,e)}if(n.method==="POST"){if(await ke(t),P.state()!=="off"){if(!P.isReady()){const r=P.health();return s(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 _(n,t.maxBodyBytes);let a="";try{a=JSON.parse(r.toString("utf8"))?.text||""}catch{}const i=await P.detect(a);return s(o,200,{entities:i})}catch(r){return s(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=_t(t);if(!e){const r=P.modelOnDisk(t.ner?.model||void 0);return s(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:P.state(),model:t.ner?.model||null})}try{const r=await _(n,t.maxBodyBytes),a=await We(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),i=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(i)}catch(r){return s(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(c==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:ze(t)});try{let r=e;const a=await ie(t.pro?.entitlementToken);await ke(t);const i=await ge([xe(()=>r,u=>{r=u})],t.redaction,{isPro:a});return s(o,200,{text:r,count:i.count||0,sanitized:i.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:vt(i.vault,"types")||[],detector:ze(t)})}catch(r){return s(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(c==="/ner/models"){if(n.method==="GET"){const e=P.health().model||t.ner?.model||null,r=Math.round(qe.totalmem()/1048576),a=Uo(et,{totalRamMB:r}).map(i=>({...i,installed:P.modelOnDisk(i.id)}));for(const i of[e,...P.modelsOnDisk()])!i||a.some(u=>u.id===i)||a.push({id:i,label:i,lang:"—",custom:!0,installed:P.modelOnDisk(i),note:"Custom model (from Hugging Face)."});return s(o,200,{active:e,companions:P.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:lo(),recommendation:Qe(a,{totalRamMB:r},[]),state:P.state(),progress:P.progress(),available:a})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const a=Math.round(qe.totalmem()/1048576),i=Qe(et.map(u=>({...u,installed:P.modelOnDisk(u.id)})),{totalRamMB:a},[]);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 a=[...new Set(e.union.map(u=>String(u||"").trim()).filter(Boolean))];for(const u of a)if(!(tt(u)||ot(u)))return s(o,400,{error:{message:`unknown or invalid model id in union: ${u}`,type:"bad_model"}});const i=r||t.ner?.model||P.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=a.filter(u=>u!==i),r&&dt(t,r);try{le(t,ne())}catch{}return(async()=>{r&&await P.setModel(r,{onLog:y=>console.log(y)});const u=io(t.ner,{log:y=>console.log(y)});for(const y of P.companions())u.includes(y.model)||await P.removeCompanion(y.model);for(const y of u)await P.addCompanion(y,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});P.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),s(o,202,{accepted:!0,active:i,union:t.ner.union,companions:P.companions(),state:P.state()})}if(!r||!(tt(r)||ot(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});dt(t,r);try{le(t,ne())}catch{}return P.setModel(r,{onLog:a=>console.log(a)}).then(a=>{a&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),s(o,202,{accepted:!0,active:r,state:P.state(),progress:P.progress()})}}if(c==="/stt/models"){if(n.method==="GET"){const e=D.health().model||t.stt?.model||De,r=Ho.map(a=>({...a,installed:D.modelOnDisk(a.id)}));return e&&!r.some(a=>a.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:D.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:D.state(),progress:D.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:D.health().dtype,runtime:D.health().runtime,dtypes:Ko})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(Fo(r)||Wo(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&Zo(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{le(t,ne())}catch{}return D.setModel(r,{onLog:i=>console.log(i),dtype:a||t.stt.dtype||"auto",warmMs:t.stt.warmMs}),s(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:D.state(),progress:D.progress()})}}if(c==="/diarize/model"){if(n.method==="GET"){const e=I.health();return s(o,200,{active:I.DIARIZE_MODEL,state:e.state,progress:I.progress(),available:[{id:I.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:I.modelOnDisk()}]})}if(n.method==="POST")return I.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:I.DIARIZE_MODEL,state:I.state(),progress:I.progress()})}if(c==="/tts/models"){if(n.method==="GET"){const e=O.health().model||t.tts?.model||lt(Ce()),r=Ce(),a=rt.find(u=>u.id===e)||null,i=rt.map(u=>({...u,installed:O.modelOnDisk(u.id),unavailable:u.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!i.some(u=>u.id===e)&&i.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:O.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:O.state(),progress:O.progress(),available:i,voice:t.tts?.voice||(Te(e)==="pocket-tts"?Se:re),arch:O.arch(),supportsVoices:O.arch()?O.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:O.arch()?O.supportsCustomVoices():!!a?.customVoices,sampleRate:O.sampleRate(),voices:O.isPocket()||!O.arch()&&Te(e)==="pocket-tts"?(O.builtinVoices().length?O.builtinVoices():or).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:O.builtinVoices().includes(u)})):O.arch()&&O.arch()!=="style-tts2"?[]:Yo.map(u=>({...u,installed:O.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:O.health().dtype,runtime:O.health().runtime,dtypes:qo})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(Qo(r)||Xo(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=e&&typeof e.voice=="string"?e.voice.trim():null;if(a){const u=G.parseCustomVoice(a);if(!(u?!!G.getVoice(u):ve(a)||nt(a)&&st(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&er(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:at,voice:re,allowDownload:!0}),r&&(t.tts.model=r),a&&(t.tts.voice=a),r&&!a){const u=tr(r),y=G.parseCustomVoice(t.tts.voice||""),h=!!(y&&G.getVoice(y));if(u&&!h)if(Te(r)==="pocket-tts")t.tts.voice=Se;else{const g=G.listVoices();t.tts.voice=g.length?`custom:${g[0].id}`:""}else!u&&h&&(t.tts.voice=re);const S=Te(r)==="pocket-tts";S&&!G.parseCustomVoice(t.tts.voice||"")&&!ve(t.tts.voice)&&(t.tts.voice=Se),!S&&ve(t.tts.voice)&&(t.tts.voice=re)}i&&(t.tts.dtype=i==="auto"?null:i);try{le(t,ne())}catch{}return r&&O.setModel(r,{onLog:u=>console.log(u),dtype:i||t.tts.dtype||"auto"}),s(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:O.state(),progress:O.progress()})}}if(c==="/tts/voices"){if(n.method==="GET")return s(o,200,{voices:G.listVoices(),usable:O.supportsCustomVoices(),embedder:I.DIARIZE_MODEL,embedderReady:I.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,i=e&&typeof e.id=="string"?e.id.trim():"";if(i){if(!G.getVoice(i))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!r)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...G.renameVoice(i,r),usable:O.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.message,type:"rename_failed"}})}}if(a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!a||a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!I.isReady()){const w=I.download({onLog:C=>console.log(C)}),E=Symbol("timeout"),L=await Promise.race([w.then(()=>null).catch(C=>C),new Promise(C=>setTimeout(()=>C(E),Cr))]);if(L===E||!I.isReady())return s(o,503,{error:{message:L===E?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${I.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:I.progress()})}const u=Float32Array.from(a),y=await I.embed(u);let h=null;try{const w=await O.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:E=>console.log(E)});w&&(h=await w.encodeVoice(Mr(u,16e3,24e3)))}catch(w){console.log(`[tts] pocket conditioning unavailable for this voice (${w.message})`)}const S=i?G.replaceVoice(i,{vec:y,pocket:h}):G.saveVoice({name:r,vec:y,pocket:h}),g=i&&r&&r!==S.name?G.renameVoice(i,r):S;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${g.name}" (${(S.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...S,...g,usable:O.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=f.searchParams.get("id")||"",r=G.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const a=G.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:re;try{le(t,ne())}catch{}}return s(o,200,{deleted:r,voice:t.tts?.voice})}}if((c==="/tts"||c==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return s(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await _(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 s(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>it)return s(o,413,{error:{message:`text too long (max ${it} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=rr(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,y=u||(i?i.voice:t.tts?.voice||re);if(i&&!sr(y))return s(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 s(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(i){const{audio:fe,contentType:$t,redacted:Pt}=await nr({dest:i,text:r,voice:y,speed:a,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ie(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":$t,"Content-Length":String(fe.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(Pt)}),o.end(fe)}if(!await O.ready({onLog:fe=>console.log(fe),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||lt(Ce()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:O.health().error||"tts model not ready",type:"tts_unavailable"}});const g=ar({requested:u,configured:y,engine:O,voices:G,isPocketVoice:ve,isKnownVoice:nt,isValidVoiceId:st,defaultVoice:re,defaultPocketVoice:Se});if(!g.ok)return s(o,g.status,{error:{message:g.message,type:g.type}});const{voice:w,customId:E,speakerEmbedding:L}=g,C=await O.synth(r,{voice:w,speed:a,speakerEmbedding:L}),q=O.sampleRate(),ye=h==="pcm"?Buffer.from(new Float32Array(C).buffer):O.toWav(C,q);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ye.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(q),...E||O.isPocket()||O.supportsVoices()?{"X-Tts-Voice":w}:{}}),o.end(ye)}catch(S){return s(o,500,{error:{message:S.message,type:"tts_failed"}})}}if(c==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}D.isReady()||D.init({model:t.stt?.model||De,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,onLog:a=>console.log(a)});const r=e?.diarize===!0&&t.stt?.diarize!==!1;r&&!I.isReady()&&I.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:a=>console.log(a)});try{const{id:a}=D.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:r,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs});return s(o,201,{id:a,state:D.state()})}catch(a){return s(o,a.code==="too_many_sessions"?429:500,{error:{message:a.message,type:a.code||"stt_error"}})}}{const e=c.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1];if(e[2]==="/audio"&&n.method==="POST")try{const a=await _(n,t.maxBodyBytes);return D.pushAudio(r,D.toFloat32(a)),s(o,200,{ok:!0,state:D.state()})}catch(a){return s(o,a.code==="no_session"?404:400,{error:{message:a.message,type:a.code||"stt_error"}})}if(e[2]==="/events"&&n.method==="GET"){const a=D.getSession(r);if(!a)return s(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 i=w=>o.write(`data: ${JSON.stringify(w)}
29
29
 
30
- `),m=a.redact?await te(t.pro?.entitlementToken):!0,b=async f=>{if(f.type!=="final"||!a.redact)return f;try{let _=f.text;return await we([Me(()=>_,M=>{_=M})],t.redaction,{isPro:m}),{...f,text:_}}catch{return f}};i({type:"state",state:A.state()});const h=setInterval(()=>{const f=A.state();if(f==="downloading"||f==="loading"){i({type:"progress",state:f,...A.progress()||{}});return}if(f==="error"){i({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(h);return}if(a.diarize){const _=B.state();if(_==="downloading"||_==="loading"){i({type:"diarize-progress",state:_,...B.progress()||{}});return}}i({type:"state",state:f}),clearInterval(h)},500);h.unref?.();let k=Promise.resolve();const y=A.subscribe(n,f=>{k=k.then(async()=>{i(await b(f)),f.type==="end"&&(clearInterval(h),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(h),y?.()});return}if(!e[2]&&r.method==="DELETE")return await A.endSession(n),s(o,200,{ok:!0})}}if(c==="/logs"&&r.method==="GET")return s(o,200,{entries:[...l].reverse()});if(c==="/config"&&r.method==="GET"){const e=await te(t.pro?.entitlementToken);return s(o,200,Xe(t,{proUnlocked:e}))}if(c==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await v(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});Go(t,e),ze(t);try{ne(t,oe())}catch(b){return s(o,500,{error:`could not persist config: ${b.message}`})}const n=t.redaction?.detection,a=!n||!n.backend||n.backend==="off",i=D.state();t.ner?.autostart&&a&&i!=="ready"&&i!=="loading"&&i!=="downloading"&&D.setModel(t.ner.model,{onLog:b=>console.log(b)}).then(b=>{b&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await te(t.pro?.entitlementToken);return s(o,200,Xe(t,{proUnlocked:m}))}if(r.method==="GET"&&c==="/skills"){const e=await re(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=ee(t.bridge?.token);try{const a=await fetch(`${e}/skills${Ie(u,t)}`,{headers:{Accept:"application/json",...n?{Authorization:`Bearer ${n}`}:{}},signal:AbortSignal.timeout(8e3)}),i=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(i?.skills)?i.skills:[]}):s(o,a.status,{error:{message:i?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+$/.test(c)){const e=decodeURIComponent(c.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const n=await re(t);if(!n)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=ee(t.bridge?.token);try{const i=await fetch(`${n}/skills/${encodeURIComponent(e)}${Ie(u,t)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),m=await i.json().catch(()=>({}));return i.ok?s(o,200,{skill:m?.skill||null}):s(o,i.status,{error:{message:m?.error||`bridge ${i.status}`,type:"bridge_error"}})}catch(i){return s(o,502,{error:{message:`bridge unreachable: ${i.message}`,type:"bridge_unreachable"}})}}if(c==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(c)){if(!H(r))return s(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(c==="/channels"&&r.method==="GET"||c!=="/channels"&&r.method==="POST"))return s(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await re(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=ee(t.bridge?.token);try{const a=r.method==="POST"?(await v(r,t.maxBodyBytes)).toString("utf8"):"",i=await fetch(`${e}${c}`,{method:r.method,headers:{Accept:"application/json",...r.method==="POST"?{"content-type":"application/json"}:{},...n?{Authorization:`Bearer ${n}`}:{}},...r.method==="POST"?{body:a||"{}"}:{},signal:AbortSignal.timeout(15e3)}),m=await i.json().catch(()=>({}));return s(o,i.status,m)}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(c)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(c),n=decodeURIComponent(e[1]),a=e[2];if(!n||n==="."||n===".."||n.includes("/")||n.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a)))return s(o,400,{error:{message:"not a skill file",type:"invalid_request"}});const i=await re(t);if(!i)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const m=ee(t.bridge?.token);try{const b=await fetch(`${i}/skills/${encodeURIComponent(n)}/file/${a}${Ie(u,t)}`,{headers:{Accept:"application/json",...m?{Authorization:`Bearer ${m}`}:{}},signal:AbortSignal.timeout(8e3)}),h=await b.json().catch(()=>({}));return b.ok?s(o,200,h):s(o,b.status,{error:{message:h?.error||`bridge ${b.status}`,type:"bridge_error"}})}catch(b){return s(o,502,{error:{message:`bridge unreachable: ${b.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/\/models$/.test(c))return s(o,200,await Ho(t));if(hr.some(e=>c===e||c.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${K}) has no ${c} — update it to use this feature`,type:"unknown_endpoint"}});const g=nr(c,r.headers,t);let w;try{w=await v(r,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let P=null,p=null,z=w,x=0,I=0,Y=0,L=!1,R=!0;const N=t.logRequests&&g.redactable&&r.method==="POST"?rr(d):null;if(g.redactable&&r.method==="POST"&&w.length){try{p=JSON.parse(w.toString("utf8"))}catch{p=null}if(p&&sr(p,g.kind))z=w;else if(p){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(p.tools)&&p.tools.length){const y=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Zo,f=e.narrowAll?null:M=>!Yo.test(st(M)),_=p.tools.length;p.tools=Ot(p.tools,Xo(p,g.kind),{cap:y,keep:f,name:st,description:Qo}),Y=_-p.tools.length}R=await te(t.pro?.entitlementToken);const n=Ro(t,R);if(!n.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${n.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});L=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&H(r),L||await Te(t);const a=L?[]:g.adapter.collectSegments(p,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const m=N?N.clock():0,{vault:b,count:h,sanitized:k}=L?{vault:null,count:0,sanitized:0}:await we(a,t.redaction,{signal:i.signal,isPro:R,onEgress:y=>Be.push(tt({ts:Date.now(),client:"redaction",tool:`detect:${y.backend}@${y.host||"local"}`,ok:y.ok,ms:y.ms,error:y.error}))});if(N&&N.lap("redact",m),P=b,x=h,I=k||0,!R&&h>0){zo(t,R);try{ne(t,oe())}catch{}}if(!L&&Array.isArray(p.tools)&&p.tools.length&&typeof g.adapter.injectSystemNote=="function"){const y=et(p?.model,t,g.kind,{destination:String(r.headers["x-chatpanel-destination"]||p?.chatpanel?.destination||"").trim()}),f=!(y&&y.type==="api");g.adapter.injectSystemNote(p,Pt({toolData:t.tools?.toolData,ownTools:f}))}else!L&&h>0&&typeof g.adapter.injectSystemNote=="function"&&g.adapter.injectSystemNote(p,At());z=Buffer.from(JSON.stringify(p),"utf8")}}const $=$t({vault:P,toolData:t.tools?.toolData}),j=p&&typeof p.chatpanel=="object"&&p.chatpanel||null;j&&(delete p.chatpanel,z=Buffer.from(JSON.stringify(p),"utf8"));const J={destination:String(r.headers["x-chatpanel-destination"]||j?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||j?.reach||"").trim(),run:gr(r.headers["x-chatpanel-run"],j?.run)},T=et(p?.model,t,g.kind,{destination:J.destination});if(J.destination&&(!T||T.id!==J.destination))return N?.commit(),s(o,404,{error:{message:`no destination "${J.destination}" is configured on this gateway`,type:"unknown_destination",known:Uo(t).map(e=>e.id)}});N&&(N.meta={t:Date.now(),model:p?.model||null,dest:T?T.id:null,type:T?T.type:null,redacted:x,sanitized:I,narrowed:Y,detail:dt(P,t.logDetail),redaction:L?"off":t.redaction.tier||"basic"});const Z=zt();if(Z&&T){const e=T.type==="api"?Le(Z,{model:p?.model||"",endpoint:T.baseUrl||""}):Gt(Z,T.agent||T.id)?Le(Z,{model:p?.model||""}):{ok:!1,reason:`agent "${T.agent||T.id}" is not allowed by your organisation’s policy`};if(!e.ok)return N?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(T&&T.type==="api")return T.baseUrl?ar(T.baseUrl,t)?(N?.commit(),s(o,508,{error:{message:`destination "${T.id}" points back at the gateway (${T.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):yr(r,o,{...g,pathname:c,search:u.search,base:T.baseUrl,destKey:T.apiKey,destProtocol:T.protocol,harness:$,trace:N},z,P):(N?.commit(),s(o,502,{error:`destination "${T.id}" has no baseUrl`}));const q=me(r),ie=q==="local"&&t.bridge?.openAgentLane?"token":q;if(ie==="local")return N?.commit(),s(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 le=xt({...J.run||{},...J.reach?{reach:J.reach}:{}},ie);return dr(r,o,{...g,pathname:c,agentOverride:T?.agent,harness:$,trace:N,run:Object.keys(le).length?le:null},p,P,t,R)})}function gr(t,l){let d=l&&typeof l=="object"?l:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const r={};if(Array.isArray(d.grants)&&(r.grants=d.grants.map(o=>String(o).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const o=d.workspace;r.workspace={repo:String(o.repo).slice(0,400),projectId:String(o.projectId||"").slice(0,120),jobId:String(o.jobId||"").slice(0,120),...o.base?{base:String(o.base).slice(0,120)}:{}}}return d.connectionId&&(r.connectionId=String(d.connectionId).slice(0,64)),typeof d.workingDir=="string"&&d.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(d.workingDir.trim())&&(r.workingDir=d.workingDir.trim().slice(0,1024)),Jo.includes(d.permissionMode)&&d.permissionMode!=="default"&&(r.permissionMode=d.permissionMode),Object.keys(r).length?r:null}let be=null;async function dn(t=je()){Zt();let l=null;try{l=await Rt()}catch(g){throw g instanceof Lt&&(console.error(`[chatpanel-gateway] org policy: ${g.message}`),process.exit(78)),g}const d=l?.policy||null;d&&(ze(t,d),console.log(`[chatpanel-gateway] ${l.label} — ${l.signed?"signed":"unsigned"} policy from ${l.source}`)),jt(globalThis,{allow:d?.egress?(g,{local:w})=>Vt(d,g,{local:w}):null}),ke();const r=fr(t),o=Kt(t),u=bt(t);r.on("error",g=>{g&&g.code==="EADDRINUSE"&&(console.error(`Port ${t.port} is already in use — another app (or a second gateway) has it.`),console.error(`Fix: free the port, or set a different one — edit "port" in ${oe()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${g?.message||g}`),process.exit(1)}),r.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${K} on http://${t.host}:${t.port}`),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"),ao(t).then(g=>{be=g}).catch(g=>console.log(` bridge : not supervised (${g?.message||g})`)),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…)":"")),lt(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.`)}),Ue()&&$e(O,_e()).then(g=>{g?.ok&&(console.log(` warm : seeded ${g.ingested} records from ${g.file}`),g.whole&&ge())}).catch(()=>{});const c=()=>{o?.stop(),u.stop(),be?.stop(),r.close(()=>process.exit(0))};return process.on("SIGINT",c),process.on("SIGTERM",c),r}export{K as VERSION,fr as createGateway,ur as joinUpstream,De as parseAgentModel,dn as start};
30
+ `),u=a.redact?await ie(t.pro?.entitlementToken):!0,y=async w=>{if(w.type!=="final"||!a.redact)return w;try{let E=w.text;return await ge([xe(()=>E,L=>{E=L})],t.redaction,{isPro:u}),{...w,text:E}}catch{return w}};i({type:"state",state:D.state()});const h=setInterval(()=>{const w=D.state();if(w==="downloading"||w==="loading"){i({type:"progress",state:w,...D.progress()||{}});return}if(w==="error"){i({type:"error",code:"model_failed",message:D.health().error||"model failed to load",fatal:!0}),clearInterval(h);return}if(a.diarize){const E=I.state();if(E==="downloading"||E==="loading"){i({type:"diarize-progress",state:E,...I.progress()||{}});return}}i({type:"state",state:w}),clearInterval(h)},500);h.unref?.();let S=Promise.resolve();const g=D.subscribe(r,w=>{S=S.then(async()=>{i(await y(w)),w.type==="end"&&(clearInterval(h),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(h),g?.()});return}if(!e[2]&&n.method==="DELETE")return await D.endSession(r),s(o,200,{ok:!0})}}if(c==="/logs"&&n.method==="GET")return s(o,200,{entries:[...k].reverse()});if(c==="/config"&&n.method==="GET"){const e=await ie(t.pro?.entitlementToken);return s(o,200,ct(t,{proUnlocked:e}))}if(c==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await _(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});dr(t,e),He(t);try{le(t,ne())}catch(y){return s(o,500,{error:`could not persist config: ${y.message}`})}const r=t.redaction?.detection,a=!r||!r.backend||r.backend==="off",i=P.state();t.ner?.autostart&&a&&i!=="ready"&&i!=="loading"&&i!=="downloading"&&P.setModel(t.ner.model,{onLog:y=>console.log(y)}).then(y=>{y&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const u=await ie(t.pro?.entitlementToken);return s(o,200,ct(t,{proUnlocked:u}))}if(n.method==="GET"&&c==="/skills"){const e=await ce(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=ae(t.bridge?.token);try{const a=await fetch(`${e}/skills${Ge(f,t)}`,{headers:{Accept:"application/json",...r?{Authorization:`Bearer ${r}`}:{}},signal:AbortSignal.timeout(8e3)}),i=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(i?.skills)?i.skills:[]}):s(o,a.status,{error:{message:i?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(c)){const e=decodeURIComponent(c.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const r=await ce(t);if(!r)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=ae(t.bridge?.token);try{const i=await fetch(`${r}/skills/${encodeURIComponent(e)}${Ge(f,t)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),u=await i.json().catch(()=>({}));return i.ok?s(o,200,{skill:u?.skill||null}):s(o,i.status,{error:{message:u?.error||`bridge ${i.status}`,type:"bridge_error"}})}catch(i){return s(o,502,{error:{message:`bridge unreachable: ${i.message}`,type:"bridge_unreachable"}})}}if(c==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(c)){if(!Z(n))return s(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(c==="/channels"&&n.method==="GET"||c!=="/channels"&&n.method==="POST"))return s(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await ce(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=ae(t.bridge?.token);try{const a=n.method==="POST"?(await _(n,t.maxBodyBytes)).toString("utf8"):"",i=await fetch(`${e}${c}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:a||"{}"}:{},signal:AbortSignal.timeout(15e3)}),u=await i.json().catch(()=>({}));return s(o,i.status,u)}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(c)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(c),r=decodeURIComponent(e[1]),a=e[2];if(!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a)))return s(o,400,{error:{message:"not a skill file",type:"invalid_request"}});const i=await ce(t);if(!i)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const u=ae(t.bridge?.token);try{const y=await fetch(`${i}/skills/${encodeURIComponent(r)}/file/${a}${Ge(f,t)}`,{headers:{Accept:"application/json",...u?{Authorization:`Bearer ${u}`}:{}},signal:AbortSignal.timeout(8e3)}),h=await y.json().catch(()=>({}));return y.ok?s(o,200,h):s(o,y.status,{error:{message:h?.error||`bridge ${y.status}`,type:"bridge_error"}})}catch(y){return s(o,502,{error:{message:`bridge unreachable: ${y.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/\/models$/.test(c))return s(o,200,await mr(t));if(Ir.some(e=>c===e||c.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${Y}) has no ${c} — update it to use this feature`,type:"unknown_endpoint"}});const A=xr(c,n.headers,t);let F;try{F=await _(n,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let U=null,v=null,W=F,B=0,z=0,oe=0,V=!1,K=!0;const j=t.logRequests&&A.redactable&&n.method==="POST"?Or(T):null;if(A.redactable&&n.method==="POST"&&F.length){try{v=JSON.parse(F.toString("utf8"))}catch{v=null}if(v&&$r(v,A.kind))W=F;else if(v){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(v.tools)&&v.tools.length){const g=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):gr,w=e.narrowAll?null:L=>!br.test(gt(L)),E=v.tools.length;v.tools=jt(v.tools,kr(v,A.kind),{cap:g,keep:w,name:gt,description:wr}),oe=E-v.tools.length}K=await ie(t.pro?.entitlementToken);const r=ir(t,K);if(!r.allowed)return s(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"}});V=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&Z(n),V||await ke(t);const a=V?[]:A.adapter.collectSegments(v,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const u=j?j.clock():0,{vault:y,count:h,sanitized:S}=V?{vault:null,count:0,sanitized:0}:await ge(a,t.redaction,{signal:i.signal,isPro:K,onEgress:g=>Re.push(pt({ts:Date.now(),client:"redaction",tool:`detect:${g.backend}@${g.host||"local"}`,ok:g.ok,ms:g.ms,error:g.error}))});if(j&&j.lap("redact",u),U=y,B=h,z=S||0,!K&&h>0){lr(t,K);try{le(t,ne())}catch{}}if(!V&&Array.isArray(v.tools)&&v.tools.length&&typeof A.adapter.injectSystemNote=="function"){const g=mt(v?.model,t,A.kind,{destination:String(n.headers["x-chatpanel-destination"]||v?.chatpanel?.destination||"").trim()}),w=!(g&&g.type==="api");A.adapter.injectSystemNote(v,Lt({toolData:t.tools?.toolData,ownTools:w}))}else!V&&h>0&&typeof A.adapter.injectSystemNote=="function"&&A.adapter.injectSystemNote(v,zt());W=Buffer.from(JSON.stringify(v),"utf8")}}const me=Rt({vault:U,toolData:t.tools?.toolData}),se=v&&typeof v.chatpanel=="object"&&v.chatpanel||null;se&&(delete v.chatpanel,W=Buffer.from(JSON.stringify(v),"utf8"));const M={destination:String(n.headers["x-chatpanel-destination"]||se?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||se?.reach||"").trim(),run:Lr(n.headers["x-chatpanel-run"],se?.run)},$=mt(v?.model,t,A.kind,{destination:M.destination});if(M.destination&&(!$||$.id!==M.destination))return j?.commit(),s(o,404,{error:{message:`no destination "${M.destination}" is configured on this gateway`,type:"unknown_destination",known:pr(t).map(e=>e.id)}});j&&(j.meta={t:Date.now(),model:v?.model||null,dest:$?$.id:null,type:$?$.type:null,redacted:B,sanitized:z,narrowed:oe,detail:vt(U,t.logDetail),redaction:V?"off":t.redaction.tier||"basic"});const H=Qt();if(H&&$){const e=$.type==="api"?Fe(H,{model:v?.model||"",endpoint:$.baseUrl||""}):qt(H,$.agent||$.id)?Fe(H,{model:v?.model||""}):{ok:!1,reason:`agent "${$.agent||$.id}" is not allowed by your organisation’s policy`};if(!e.ok)return j?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if($&&$.type==="api")return $.baseUrl?Pr($.baseUrl,t)?(j?.commit(),s(o,508,{error:{message:`destination "${$.id}" points back at the gateway (${$.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):jr(n,o,{...A,pathname:c,search:f.search,base:$.baseUrl,destKey:$.apiKey,destProtocol:$.protocol,harness:me,trace:j},W,U):(j?.commit(),s(o,502,{error:`destination "${$.id}" has no baseUrl`}));const ee=be(n),he=ee==="local"&&t.bridge?.openAgentLane?"token":ee;if(he==="local")return j?.commit(),s(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 Je=Jt({...M.run||{},...M.reach?{reach:M.reach}:{}},he);return Br(n,o,{...A,pathname:c,agentOverride:$?.agent,harness:me,trace:j,run:Object.keys(Je).length?Je:null},v,U,t,K)})}function Lr(t,l){let d=l&&typeof l=="object"?l:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const m={};if(Array.isArray(d.grants)&&(m.grants=d.grants.map(p=>String(p).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const p=d.workspace;m.workspace={repo:String(p.repo).slice(0,400),projectId:String(p.projectId||"").slice(0,120),jobId:String(p.jobId||"").slice(0,120),...p.base?{base:String(p.base).slice(0,120)}:{}}}return d.connectionId&&(m.connectionId=String(d.connectionId).slice(0,64)),typeof d.workingDir=="string"&&d.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(d.workingDir.trim())&&(m.workingDir=d.workingDir.trim().slice(0,1024)),ur.includes(d.permissionMode)&&d.permissionMode!=="default"&&(m.permissionMode=d.permissionMode),Object.keys(m).length?m:null}let Oe=null;async function Jn(t=Ve()){co();let l=null;try{l=await Yt()}catch(k){throw k instanceof Xt&&(console.error(`[chatpanel-gateway] org policy: ${k.message}`),process.exit(78)),k}const d=l?.policy||null;d&&(He(t,d),console.log(`[chatpanel-gateway] ${l.label} — ${l.signed?"signed":"unsigned"} policy from ${l.source}`)),Kt(globalThis,{allow:d?.egress?(k,{local:T})=>eo(d,k,{local:T}):null}),$e();const m=Rr(t),p=ao(t),b=At(t);m.on("error",k=>{k&&k.code==="EADDRINUSE"&&(console.error(`Port ${t.port} is already in use — another app (or a second gateway) has it.`),console.error(`Fix: free the port, or set a different one — edit "port" in ${ne()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${k?.message||k}`),process.exit(1)}),m.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${Y} on http://${t.host}:${t.port}`),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"),So(t).then(k=>{Oe=k}).catch(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…)":"")),kt(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.`)}),Xe()&&Be(N,Ae()).then(k=>{k?.ok&&(console.log(` warm : seeded ${k.ingested} records from ${k.file}`),k.whole&&_e())}).catch(()=>{});const x=()=>{p?.stop(),b.stop(),Oe?.stop(),_extract?.stop("shutdown"),m.close(()=>process.exit(0))};return process.on("SIGINT",x),process.on("SIGTERM",x),m.on("close",()=>_extract?.stop("closed")),m}export{Y as VERSION,Rr as createGateway,Dr as joinUpstream,Le as parseAgentModel,Jn as start};
@@ -0,0 +1 @@
1
+ const g=Object.freeze({perHost:2,total:4});function p(t,s){if(t==null)return null;const l=String(t).trim();if(!l)return null;if(/^\d+$/.test(l))return Number(l)*1e3;const n=Date.parse(l);return Number.isNaN(n)?null:Math.max(0,n-s)}function y({now:t=()=>Date.now(),perHost:s=g.perHost,total:l=g.total}={}){const n=new Map;let a=0;const r=[],u=new Map,c=e=>a<l&&(n.get(e)||0)<s,d=e=>{n.set(e,(n.get(e)||0)+1),a+=1;let i=!1;return()=>{i||(i=!0,n.set(e,n.get(e)-1),n.get(e)===0&&n.delete(e),a-=1,b())}},b=()=>{for(let e=0;e<r.length;e++)if(c(r[e].host)){const{host:i,resolve:o}=r.splice(e,1)[0];if(o(d(i)),e-=1,a>=l)break}};return{acquire(e){const i=String(e||"").toLowerCase();return c(i)?Promise.resolve(d(i)):new Promise(o=>r.push({host:i,resolve:o}))},noteRetryAfter(e,i){const o=p(i,t());if(o==null||o<=0)return 0;const f=Math.min(o,15*6e4);return u.set(String(e||"").toLowerCase(),t()+f),f},holdFor(e){const i=u.get(String(e||"").toLowerCase());if(!i)return 0;const o=i-t();return o<=0?(u.delete(String(e||"").toLowerCase()),0):o},snapshot(){return{inFlight:Object.fromEntries(n),total:a,waiting:r.length,holds:u.size}}}}const w=200,m=/\b(paywall|subscribe to (continue|read)|subscription required|subscribers? only|become a (member|subscriber)|to continue reading|unlock this (article|story)|premium (article|content))\b/i,h=/(type=["']password["']|\b(sign in|log in|login) to (continue|view|read)\b|\bplease (sign|log) in\b|\byou must be logged in\b)/i;function T({status:t=200,headers:s={},html:l="",words:n=0}={}){const a=r=>{if(!s)return null;if(typeof s.get=="function")return s.get(r);const u=Object.keys(s).find(c=>c.toLowerCase()===r.toLowerCase());return u?s[u]:null};if(t===429||t===503){const r=a("retry-after");return{reason:"rate_limited",detail:r?`HTTP ${t}, Retry-After ${r}`:`HTTP ${t}`}}if(t===401||t===402||t===403)return{reason:t===402?"paywall":"login",detail:`HTTP ${t}`};if(n<w){const r=String(l||"");if(m.test(r))return{reason:"paywall",detail:"a subscription wall with little readable text"};if(h.test(r))return{reason:"login",detail:"a login form with little readable text"}}return null}function x(t){if(!t)return"";switch(t.reason){case"login":return"could not be read: the page is behind a login";case"paywall":return"could not be read: the page is behind a paywall";case"rate_limited":return"could not be read: the site asked us to slow down";case"robots":return"was not read: the site's robots.txt disallows it";case"tdm":return"was not read: the site reserves its content from automated mining";default:return"could not be read"}}export{g as HOST_BUDGET_DEFAULTS,w as THIN_PAGE_WORDS,y as createHostBudget,x as describeRestriction,p as parseRetryAfter,T as restrictionOf};