@chatpanel/gateway 0.19.2 → 0.23.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/capabilities.js +1 -1
- package/src/capability-adapters.js +1 -0
- package/src/capability-endpoints.js +1 -1
- package/src/capability-providers.js +3 -0
- package/src/capability-proxy.js +1 -0
- package/src/capability-tools.js +3 -0
- package/src/config.js +1 -1
- package/src/configstore.js +1 -1
- package/src/egress.js +2 -2
- package/src/mcp.js +20 -20
- package/src/model-file-cache.js +1 -0
- package/src/ner-engine.js +1 -1
- package/src/ner.js +1 -1
- package/src/redact.js +2 -2
- package/src/runtime-models.js +1 -0
- package/src/runtime.js +3 -3
- package/src/server.js +14 -14
- package/src/service.js +16 -11
- package/src/shutdown.js +1 -0
- package/src/web-search-tool.js +19 -0
package/src/redact.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createVault as I,redactText as S,detectEntities as v,gatedDictionary as T,sanitizeUnicode as
|
|
1
|
+
import{createVault as I,redactText as S,detectEntities as v,gatedDictionary as T,sanitizeUnicode as w}from"@chatpanel/pii";import{ENTITIES_SCHEMA as b,entitiesFormat as z}from"./extraction.js";import{describeSchema as A,coerce as N}from"./structured.js";import*as j from"./ner-engine.js";async function R(s,r,{signal:g,isPro:h=!0,onEgress:x=null,fetchImpl:M=null,nerEngine:c=j}={}){const a=I();let f=0;for(const t of s){const e=t.get();if(typeof e!="string"||!e)continue;const{clean:n,removed:y}=w(e);y&&(t.set(n),f+=y)}const m=s.map(t=>t.get()).filter(t=>typeof t=="string"&&t);if(m.length===0)return{vault:a,count:0,sanitized:f};const u=r.tier==="full"?"full":"basic",k=T(r,h),o=r.detection,l=!!(o&&o.backend&&o.backend!=="off");u==="full"&&!l&&typeof c.ensure=="function"&&await c.ensure();const i=!l&&c.isReady();let p=[];if(u==="full"&&(l||i)){const t=i?{backend:"endpoint",url:"inproc:ner",transport:"in-process",timeoutMs:3e4,maxChars:8e3,types:o?.types}:{...o,timeoutMs:Math.max(Number(o.timeoutMs)||0,3e4)},e=i?c.fetchAdapter:M||void 0;try{p=await v(m.join(`
|
|
2
2
|
|
|
3
|
-
`),{detection:t},{signal:
|
|
3
|
+
`),{detection:t},{signal:g,fetchImpl:e,onEgress:i?null:x,structured:{block:A(b),format:n=>z(n),parse:n=>N(n,b)?.value??null}})}catch{p=[]}}const E={tier:u,entities:p,dictionary:k};let d=0;for(const t of s){const e=t.get();if(typeof e!="string"||!e)continue;const n=S(e,a,E);n!==e&&d++,t.set(n)}return{vault:a,count:d,sanitized:f}}function U(s,r){return{get:s,set:r}}export{R as redactSegments,U as segment};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const g=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/,M=Object.freeze([{id:"BAAI/bge-reranker-v2-m3",label:"bge-reranker v2 m3",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:2600,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"The one the decision servers themselves rank with. Multilingual, strong on long passages; the ship default."},{id:"BAAI/bge-reranker-base",label:"bge-reranker base",lang:"100+ languages",tier:"balanced",approxMB:1110,ramMB:1300,minRamMB:2048,licence:"MIT",note:"Half the size, most of the quality. The pick when the engine has 2 GB."},{id:"BAAI/bge-reranker-large",label:"bge-reranker large",lang:"100+ languages",tier:"max",approxMB:2240,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The first-generation large model; v2 m3 is newer and usually better at the same cost."},{id:"mixedbread-ai/mxbai-rerank-base-v1",label:"mxbai-rerank base v1",lang:"English",tier:"balanced",approxMB:740,ramMB:900,minRamMB:2048,licence:"Apache-2.0",note:"English-only, small and quick — a good fit for notes and search on a modest machine."},{id:"cross-encoder/ms-marco-MiniLM-L-6-v2",label:"MiniLM-L6 (MS MARCO)",lang:"English",tier:"light",approxMB:90,ramMB:300,minRamMB:1024,licence:"Apache-2.0",note:"Tiny and fast; the classic web-search reranker. English only, short passages."}]),p=Object.freeze([{id:"MoritzLaurer/ModernBERT-large-zeroshot-v2.0",label:"ModernBERT large zero-shot v2",lang:"English",tier:"accurate",approxMB:1600,ramMB:2400,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"What OpenDecision ships with; 8k context. Uncalibrated like every zero-shot NLI head — the p is an ordering, not a probability."},{id:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",label:"ModernBERT base zero-shot v2",lang:"English",tier:"balanced",approxMB:600,ramMB:1e3,minRamMB:2048,licence:"Apache-2.0",note:"A third of the size, close on most typed decisions. The pick when the engine has 2 GB."},{id:"MoritzLaurer/deberta-v3-large-zeroshot-v2.0",label:"DeBERTa v3 large zero-shot v2",lang:"English",tier:"max",approxMB:1740,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The strongest English zero-shot classifier of the family; slower than ModernBERT, 512 tokens."},{id:"MoritzLaurer/mDeBERTa-v3-base-mnli-xnli",label:"mDeBERTa v3 base (XNLI)",lang:"100 languages",tier:"balanced",approxMB:1120,ramMB:1400,minRamMB:2048,licence:"MIT",note:"The multilingual one: sentiment, routing and triage in Hindi, Telugu, Spanish, German… on the same questions."},{id:"MoritzLaurer/deberta-v3-xsmall-zeroshot-v1.1-all-33",label:"DeBERTa v3 xsmall zero-shot",lang:"English",tier:"light",approxMB:280,ramMB:500,minRamMB:1024,licence:"MIT",note:"Tiny and quick — decisions in tens of milliseconds on any machine, at some accuracy."}]),u={reranker:M,opendecision:p};function d(r){return u[r]||[]}function b(r,a){if(typeof a!="string"||!a.trim())return!1;const n=a.trim();return d(r).some(o=>o.id===n)||g.test(n)}function B(r){return`models--${String(r).replace(/\//g,"--")}`}function x(r,{active:a=null,engineRamMB:n=0,engine:o=null,platform:l=process.platform,installed:c=()=>!1}={}){const t=e=>`${Math.round(e/1024*10)/10} GB`,m=e=>o==="podman"&&l!=="linux"?`podman machine stop && podman machine set --memory ${Math.max(4096,Math.ceil((e.ramMB+2048)/2048)*2048)} && podman machine start`:o==="docker"&&l!=="linux"?"raise the memory in Docker Desktop › Settings › Resources":null,i=d(r).map(e=>{const s=n>0&&e.ramMB>n,h=!s&&Number(e.minRamMB)>0&&n>0&&n<e.minRamMB;return{...e,installed:c(e.id),recommended:!!e.recommended&&!s&&!h,...s?{unavailable:`needs about ${t(e.ramMB)} of memory while loaded — the container engine has ${t(n)}${m(e)?`; raise it: ${m(e)}`:""}`}:{},...h?{ramNote:`needs about ${t(e.ramMB)} while loaded — the engine has ${t(n)}; expect it to slow things down`}:{}}});return a&&!i.some(e=>e.id===a)&&i.push({id:a,label:a,lang:"—",tier:"custom",custom:!0,installed:c(a),note:"Custom model (from Hugging Face)."}),i}export{p as DECIDE_MODEL_CATALOG,g as HF_ID,M as RERANK_MODEL_CATALOG,B as cacheDirName,d as catalogFor,b as isValidModelId,x as modelsFor};
|
package/src/runtime.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{promisify as
|
|
2
|
-
`)}function
|
|
3
|
-
`).filter(Boolean).map(
|
|
1
|
+
import{promisify as U}from"node:util";import{execFile as K}from"node:child_process";import{existsSync as Q,mkdirSync as L,writeFileSync as Y}from"node:fs";import{randomBytes as Z}from"node:crypto";import C from"node:os";import S from"node:path";import{modelsFor as F,isValidModelId as ee,cacheDirName as ne,catalogFor as te}from"./runtime-models.js";const re=U(K),_=["podman","docker"],A="hf-cache",D=Object.freeze([{id:"searxng",label:"SearXNG",image:"docker.io/searxng/searxng:latest",container:"chatpanel-searxng",port:8888,containerPort:8080,provides:["search"],blurb:"A metasearch engine of your own: the gateway’s web search fans out through it instead of scraping result pages. Loopback only.",caps:["CHOWN","SETGID","SETUID"],answers:async(e,i)=>{try{return(await i(`${e}/search?q=chatpanel&format=json`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:e=>String(e.search?.searxng?.url||""),configure:(e,i)=>{e.search=e.search||{},e.search.searxng={...e.search.searxng||{},url:i}},unconfigure:(e,i)=>{e.search?.searxng?.url===i&&(e.search.searxng.url="")}},{id:"reranker",label:"Reranker",image:"ghcr.io/chatpanel/reranker:latest",container:"chatpanel-reranker",port:8889,containerPort:8e3,provides:["rerank"],adapter:"tei",model:"BAAI/bge-reranker-v2-m3",blurb:"Orders sources by relevance — research in plan notes, search results, tool results. A cross-encoder (bge-reranker-v2-m3, multilingual) behind the Text Embeddings Inference wire. Loopback only.",caps:[],volumes:e=>[`${S.join(e,A)}:/data`],env:e=>["HF_HOME=/data",`MODEL_ID=${e.model}`],answers:async(e,i)=>{try{return(await i(`${e}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:e=>String(e.capabilities?.rerank?.url||""),configure:(e,i,l)=>{e.capabilities=e.capabilities||{},e.capabilities.rerank={url:i,adapter:l.adapter,model:l.model,service:l.id}},unconfigure:(e,i)=>{e.capabilities?.rerank?.url===i&&delete e.capabilities.rerank}},{id:"opendecision",label:"OpenDecision",image:"ghcr.io/chatpanel/opendecision:latest",container:"chatpanel-opendecision",port:8890,containerPort:8e3,provides:["decide"],adapter:"systemone",model:"MoritzLaurer/ModernBERT-large-zeroshot-v2.0",calibrated:!1,blurb:"Typed decisions — sentiment, routing, triage — answered by a zero-shot classifier in one pass, no language model. TypeSafe-shaped (/v1/systemone), Apache-2.0. Loopback only.",caps:[],volumes:e=>[`${S.join(e,A)}:/data`],env:e=>["HF_HOME=/data",`MODEL_ID=${e.model}`],answers:async(e,i)=>{try{return(await i(`${e}/health`,{signal:AbortSignal.timeout(4e3)})).ok}catch{return!1}},configured:e=>String(e.capabilities?.decide?.url||""),configure:(e,i,l)=>{e.capabilities=e.capabilities||{},e.capabilities.decide={url:i,adapter:l.adapter,model:l.model,service:l.id,calibrated:l.calibrated}},unconfigure:(e,i)=>{e.capabilities?.decide?.url===i&&delete e.capabilities.decide}}]),N=e=>D.find(i=>i.id===e)||null,oe=({answers:e,configured:i,configure:l,unconfigure:w,volumes:$,args:d,env:E,caps:b,...M})=>M;function ae(e=[]){return["# Written by chatpanel-gateway (Settings › Runtime). JSON on, the limiter off — the port is","# bound to 127.0.0.1, which is what makes that safe. Do not publish it on 0.0.0.0.","use_default_settings: true","general:",' instance_name: "ChatPanel search"'," debug: false"," enable_metrics: false","server:",' secret_key: "${SEARXNG_SECRET}"'," limiter: false"," public_instance: false"," image_proxy: false",' method: "GET"',"search:"," safe_search: 0",' autocomplete: ""'," formats:"," - html"," - json","ui:"," static_use_hash: true","engines:",...(e.length?e:["duckduckgo","brave","startpage","bing","wikipedia","qwant"]).flatMap(l=>[` - name: ${l}`," disabled: false"])," - name: google"," disabled: true",""].join(`
|
|
2
|
+
`)}function B(e=process.platform){return e==="darwin"?{command:"brew install podman",url:"https://podman.io/docs/installation#macos",note:"Homebrew; then Start the engine below (it creates and starts the Podman machine)."}:e==="win32"?{command:"winget install RedHat.Podman",url:"https://podman.io/docs/installation#windows",note:"Then Start the engine below (it creates and starts the Podman machine under WSL)."}:{command:"sudo apt install podman # or: sudo dnf install podman",url:"https://podman.io/docs/installation#installing-on-linux",note:"Rootless; no daemon to start."}}function G(e,i){const l=i==="podman"?Array.isArray(e.Names)?e.Names[0]:String(e.Names||""):String(e.Names||e.Name||""),w=i==="podman"?Array.isArray(e.Ports)?e.Ports.map(d=>`${d.host_ip||""}:${d.host_port}->${d.container_port}/${d.protocol||"tcp"}`):[]:String(e.Ports||"").split(",").map(d=>d.trim()).filter(Boolean),$=String(e.State||"").toLowerCase()||(/^up/i.test(String(e.Status||""))?"running":"exited");return{name:l,image:String(e.Image||""),state:$,status:String(e.Status||""),ports:w,ours:l.startsWith("chatpanel-"),engine:i}}function fe({cfg:e,bridgeHealth:i,workers:l=()=>[],persist:w=()=>{},exec:$=(u,h,v={})=>re(u,h,{timeout:6e4,...v}),platform:d=process.platform,fetchImpl:E=globalThis.fetch,stateDir:b=S.join(C.homedir(),".chatpanel","runtime"),log:M=()=>{},sleep:J=u=>new Promise(h=>setTimeout(h,u)),totalMem:W=()=>C.totalmem()}={}){const u=async(t,o,r)=>{try{const n=await $(t,o,r);return{ok:!0,out:String(n.stdout||"").trim(),err:String(n.stderr||"").trim()}}catch(n){return{ok:!1,out:String(n?.stdout||"").trim(),err:String(n?.stderr||n?.message||n).trim(),code:n?.code}}},h=t=>String(e.runtime?.services?.[t.id]?.model||t.model||""),v=t=>t.model?{...t,model:h(t)}:t,P=t=>Q(S.join(b,A,"hub",ne(t)));async function j(t,o){if(!t||!o?.[t]?.running)return 0;if(t==="podman"&&d!=="linux"){const r=await u("podman",["machine","inspect","--format","{{.Resources.Memory}}"],{timeout:8e3}),n=parseInt(r.out,10);return r.ok&&n>0?n:0}if(t==="docker"&&d!=="linux"){const r=await u("docker",["info","--format","{{.MemTotal}}"],{timeout:8e3}),n=parseInt(r.out,10);return r.ok&&n>0?Math.round(n/1048576):0}return Math.round(W()/1048576)}async function k(){const t={};for(const r of _){const n=await u(r,["--version"],{timeout:5e3});if(!n.ok){t[r]={installed:!1};continue}const a=(n.out.match(/(\d+\.\d+(\.\d+)?)/)||[])[1]||n.out;let s=!1,m=null;if(r==="podman")if(d==="linux")s=(await u("podman",["info","--format","{{.Host.Arch}}"],{timeout:8e3})).ok;else{const c=await u("podman",["machine","list","--format","json"],{timeout:8e3});try{const f=JSON.parse(c.out||"[]")[0]||null;m=f?{name:f.Name,running:!!f.Running}:null,s=!!f?.Running}catch{m=null}}else s=(await u("docker",["info","--format","{{.ServerVersion}}"],{timeout:8e3})).ok;t[r]={installed:!0,version:a,running:s,...r==="podman"&&d!=="linux"?{machine:m}:{}}}const o=_.find(r=>t[r]?.installed&&t[r].running)||_.find(r=>t[r]?.installed)||null;return{...t,preferred:o,...o?{}:{install:B(d)}}}async function O(t="podman"){if(!_.includes(t))return{ok:!1,error:`unknown engine ${t}`};const o=(await k())[t];if(!o?.installed)return{ok:!1,error:`${t} is not installed`,install:B(d)};if(o.running)return{ok:!0,already:!0};if(t==="docker")return{ok:!1,error:"start Docker Desktop (or the docker daemon) yourself — the gateway does not manage it"};if(d!=="linux"){if(!o.machine){const n=await u("podman",["machine","init"],{timeout:6e5});if(!n.ok)return{ok:!1,error:`podman machine init: ${n.err||n.out}`}}const r=await u("podman",["machine","start"],{timeout:3e5});if(!r.ok&&!/already running/i.test(r.err))return{ok:!1,error:`podman machine start: ${r.err||r.out}`}}return{ok:!0}}async function X(){const t=await k(),o=t.preferred;if(!o||!t[o].running)return[];if(o==="podman"){const n=await u("podman",["ps","-a","--format","json"],{timeout:1e4});if(!n.ok)return[];try{return JSON.parse(n.out||"[]").map(a=>G(a,"podman"))}catch{return[]}}const r=await u("docker",["ps","-a","--format","{{json .}}"],{timeout:1e4});return r.ok?r.out.split(`
|
|
3
|
+
`).filter(Boolean).map(n=>{try{return G(JSON.parse(n),"docker")}catch{return null}}).filter(Boolean):[]}async function R(t,o){const r=await u(t,["inspect","--format","{{.State.Status}}",o],{timeout:8e3});return r.ok?/running/i.test(r.out)?"running":"stopped":"absent"}const x=t=>`http://127.0.0.1:${t.port}`;async function T(){const t=await k(),o=t.preferred,r=await j(o,t),n={};for(const a of D){const s=x(a);let m="no-engine";o&&t[o].running?m=await R(o,a.container):o&&(m="engine-stopped");const c=a.model?h(a):null;n[a.id]={...oe(a),engine:o,state:m,url:s,configured:a.configured(e),answering:m==="running"?await a.answers(s,E):!1,...a.model?{model:c,default:a.model,models:F(a.id,{active:c,engineRamMB:r,engine:o,platform:d,installed:P}),machine:{engineRamMB:r}}:{}}}return n}function z(t,{settingsFile:o=null,secret:r=null}={}){const n=v(t),a=["run","-d","--name",n.container,"--restart","unless-stopped","-p",`127.0.0.1:${n.port}:${n.containerPort}`];for(const s of n.volumes?n.volumes(b):[])a.push("-v",s);o&&a.push("-v",`${o}:/etc/searxng/settings.yml:ro`);for(const s of n.env?n.env(n):[])a.push("-e",s);r&&a.push("-e",`SEARXNG_SECRET=${r}`,"-e",`SEARXNG_BASE_URL=http://127.0.0.1:${n.port}/`),a.push("--cap-drop","ALL");for(const s of n.caps||[])a.push("--cap-add",s);return a.push(n.image,...n.args?n.args(n):[]),a}async function I(t){const o=N(t);if(!o)return{ok:!1,error:`unknown service ${t}`};const r=await k(),n=r.preferred;if(!n)return{ok:!1,error:"no container engine — install Podman first",install:B(d)};if(!r[n].running){const c=await O(n);if(!c.ok)return c}const a=await R(n,o.container);if(a!=="running")if(a==="stopped"){const c=await u(n,["start",o.container],{timeout:6e4});if(!c.ok)return{ok:!1,error:`${n} start: ${c.err||c.out}`}}else{L(b,{recursive:!0,mode:448});let c=null,y=null;o.id==="searxng"&&(c=S.join(b,"searxng-settings.yml"),Y(c,ae(String(e.search?.searxng?.engines||"").split(",").map(g=>g.trim()).filter(Boolean)),{mode:384}),y=Z(32).toString("hex")),o.volumes&&L(S.join(b,A),{recursive:!0,mode:448});const f=z(o,{settingsFile:c,secret:y});M(`[runtime] ${n} ${f.filter(g=>!g.startsWith("SEARXNG_SECRET")).join(" ")}`);const p=await u(n,f,{timeout:6e5});if(!p.ok)return{ok:!1,error:`${n} run: ${p.err||p.out}`}}const s=x(o);let m=!1;for(let c=0;c<30&&!m;c++)m=await o.answers(s,E),m||await J(1e3);return o.configure(e,s,v(o)),w(),{ok:!0,url:s,answering:m,...o.provides.length?{provides:o.provides}:{},...o.model?{model:h(o)}:{}}}async function V(t){const o=N(t);if(!o)return{ok:!1,error:`unknown service ${t}`};const r=await k(),n=r.preferred;if(n&&r[n].running){const a=await u(n,["stop",o.container],{timeout:6e4});if(!a.ok&&!/no such container/i.test(a.err))return{ok:!1,error:`${n} stop: ${a.err||a.out}`}}return o.unconfigure(e,x(o)),w(),{ok:!0}}async function q(t,o){const r=N(t);if(!r)return{ok:!1,error:`unknown service ${t}`};if(!r.model)return{ok:!1,error:`${r.label} takes no model`};const n=String(o||"").trim();if(!ee(t,n))return{ok:!1,error:`not a model id: ${JSON.stringify(o)} — pick one from the list, or a Hugging Face id like owner/name`};const a=await k(),s=a.preferred,m=await j(s,a),c=F(t,{active:n,engineRamMB:m,engine:s,platform:d,installed:P}).find(p=>p.id===n);if(c?.unavailable)return{ok:!1,error:`${n} ${c.unavailable}`};e.runtime=e.runtime||{services:{}},e.runtime.services=e.runtime.services||{},e.runtime.services[t]={...e.runtime.services[t]||{},model:n};const y=x(r);r.configured(e)===y&&r.configure(e,y,v(r)),w();let f=!1;if(s&&a[s].running){const p=await R(s,r.container);if(p!=="absent"){const g=await u(s,["rm","-f",r.container],{timeout:6e4});if(!g.ok&&!/no such container/i.test(g.err))return{ok:!1,error:`${s} rm: ${g.err||g.out}`};if(p==="running"){const H=await I(t);if(!H.ok)return H;f=!0}}}return{ok:!0,model:n,restarted:f,...c?.ramNote?{note:c.ramNote}:{}}}return{async status(){const[t,o,r,n]=await Promise.all([i().catch(()=>null),k(),T(),X()]);return{sandbox:t?.sandbox||null,processes:{all:[...Array.isArray(t?.processes)?t.processes:[],...l()],localMcp:Array.isArray(t?.localMcp)?t.localMcp:[],warm:t?.warm||null},containers:n,refused:Array.isArray(t?.sandbox?.refused)?t.sandbox.refused:[],bridge:t?{ok:!0,version:t.version||""}:{ok:!1},engines:o,services:r}},startEngine:O,startService:I,stopService:V,setModel:q,services:T,catalogFor:te}}export{D as SERVICES,G as containerRow,fe as createRuntime,B as installDoor,ae as searxngSettings};
|
package/src/server.js
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
import{createServer as
|
|
1
|
+
import{createServer as Dt}from"node:http";import{loadConfig as We}from"./config.js";import{startEntitlementRefresh as Ct,maybeRevalidate as Mt}from"./entitlement-refresh.js";import{redactSegments as ke,segment as Ae}from"./redact.js";import{pipeRestoredStream as jt,pipeRestoredOpenAIStream as It,makeTokenRestorer as Ke,restoreDeep as Rt}from"./stream.js";import{restoreText as Lt,gatedDictionary as zt,narrowSpecs as Jt,makeToolHarness as Gt,placeholderToolNote as Vt,placeholderNote as Ut,assertEndpointUrl as Ht,capRunOptions as Ft,isPaired as Wt}from"@chatpanel/pii";import{ensureGatewayToken as Pe,currentGatewayToken as Kt,isAdminAuthorized as F,callerTrustOf as Se,setPinnedExtensionIds as Zt,issuePairingCode as Yt,claimPairingCode as Qt}from"./gateway-token.js";import{installEgressLedger as Xt,egressAudit as qt}from"./egress.js";import{initPolicy as eo,activePolicy as to,applyPolicyToConfig as Ze,managedSummary as ye,PolicyLoadError as oo}from"./policy.js";import{routeAllowed as Ye,agentAllowed as ro,egressAllowed as no}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as de}from"./bridge.js";import{secureFetch as Qe}from"./secure-fetch.js";import{streamBridgeChat as Xe,readBridgeToken as ae,openBridgeChat as so}from"./bridge.js";import{createRelaySession as ao,getRelaySession as qe,endRelaySession as ve,pumpBridgeStream as io,deliverToolResult as lo,toolsToSpecs as co,parseToolCallId as et,touchRelaySession as Ee}from"./toolrelay.js";import{shaperFor as Ne}from"./shape.js";import{startNer as uo,ensureNer as Te,unionForThisMachine as mo,skippedCompanions as po}from"./ner.js";import{recommendDetector as tt}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as ho}from"./log.js";import{saveBackupSecret as yo,clearBackupSecret as fo,loadBackupSecret as Be,hasBackupSecret as ot}from"./history-store.js";import{createMemoryStore as go}from"./memory-store.js";import{createPrefsStore as bo}from"./prefs-store.js";import{createTeamStore as wo,loadOrCreateKey as De}from"./team-store.js";import{createScorecardStore as ko}from"./scorecard-store.js";import{createEngineLedgerStore as So}from"./engine-ledger-store.js";import{createProjectStore as vo}from"./project-store.js";import{applicationsFor as To,recruitPass as xo}from"./recruiting.js";import{ensureBridge as Oo}from"./bridge-supervisor.js";import{checkForUpdate as _o,updateStatus as $o,startUpdate as Ao,updateJob as Po}from"./update.js";import{createHistoryStore as Eo}from"./sqlite-store.js";import{ingestBackups as Ce}from"./backup-ingest.js";import{toSearchRecord as No}from"@chatpanel/events/library.js";import{deriveBackupKey as Bo,openRecord as Do,keyCache as Co,nodeCodec as Mo}from"@chatpanel/events/backup-envelope.js";import jo from"node:zlib";import*as A from"./ner-engine.js";import rt from"node:os";import{capabilitiesDocument as Io,handleDetect as Ro}from"./capabilities.js";import{createExtractService as Lo}from"./extract/service.js";import{workerSandbox as zo,disposeWorkerSandbox as Jo}from"./worker-sandbox.js";import{createRuntime as Go}from"./runtime.js";import{createCapabilityProxy as Vo}from"./capability-proxy.js";import{handleExtract as Uo}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as Ho}from"./extract-capability.js";import{createReader as Fo}from"./retrieval/read.js";import{createSearcher as Wo,toJinaSearch as Ko,SEARCH_DEFAULTS as Zo}from"./retrieval/search.js";import{createSearxng as Yo}from"./retrieval/search-searxng.js";import{toJinaText as Qo}from"./read-document.js";import*as B from"./stt-engine.js";import*as L from"./diarize-engine.js";import{MODEL_CATALOG as nt,isKnownModel as st,isValidCustomModelId as at,recommendFor as Xo}from"./models.js";import{STT_MODEL_CATALOG as qo,isKnownSttModel as er,isValidCustomSttId as tr,DEFAULT_STT_MODEL as Me,STT_DTYPES as or,isValidDtype as rr}from"./stt-models.js";import*as _ from"./tts-engine.js";import{TTS_MODEL_CATALOG as it,TTS_VOICES as nr,isKnownTtsModel as sr,isValidCustomTtsId as ar,isKnownVoice as lt,isValidVoiceId as ct,DEFAULT_TTS_MODEL as dt,DEFAULT_TTS_VOICE as ie,TTS_DTYPES as ir,isValidTtsDtype as lr,MAX_TTS_CHARS as ut,ttsModelHasCustomVoices as cr,resolveDefaultModel as mt,POCKET_VOICES as dr,DEFAULT_POCKET_VOICE as xe,isPocketVoice as Oe,ttsModelEngine as _e}from"./tts-models.js";import{ttsDestination as ur,synthesizeRemote as mr,isValidRemoteVoice as pr}from"./tts-remote.js";import{rawOrtAvailable as je}from"./ort.js";import*as U from"./tts-voices.js";import{resolveTtsVoice as hr}from"./tts-voice-resolve.js";import{resolvePro as ue,checkQuota as yr,consume as fr,usage as gr}from"./freegate.js";import{publicConfig as pt,applyConfigPatch as br,applyNerModelSelection as ht,persistConfig as le,configPath as re,bridgeAgentOptions as yt,PERMISSION_MODES as wr,sandboxEnvFor as kr}from"./configstore.js";import{resolveDestination as ft,aggregateModelsAsync as Sr,listDestinations as vr}from"./router.js";import{makeAccessEvent as gt}from"./observability.js";import{createPersistentAccessLog as Tr}from"./access-log-store.js";import{planQueries as xr,multiSearch as Or}from"./rrf.js";import*as Ie from"./openai.js";import*as bt from"./responses.js";import*as Re from"./anthropic.js";import{closeAndExit as _r}from"./shutdown.js";const Z="0.23.1",N=await Eo(),ne=new Set;function $e({ids:t=[]}={}){const l=N.lossless;if(!l||!ne.size)return;const c=JSON.stringify({newest:l.newest,size:l.size,ids:t.slice(0,50),at:Date.now()});for(const m of ne)try{m.write(`event: records
|
|
2
2
|
data: ${c}
|
|
3
3
|
|
|
4
4
|
`)}catch{ne.delete(m)}}setInterval(()=>{for(const t of ne)try{t.write(`: ping
|
|
5
5
|
|
|
6
|
-
`)}catch{ne.delete(t)}},25e3).unref?.();const
|
|
6
|
+
`)}catch{ne.delete(t)}},25e3).unref?.();const Y=await go(),Q=bo(),me=ko({key:De()}),pe=So({key:De()}),H=vo({key:De()}),G=wo({scorecards:me,engines:pe}),Le=new Set,wt=(t,l)=>{for(const m of Le)try{m({applied:t,by:l,revision:Q.revision})}catch{}const c=JSON.stringify({revision:Q.revision,applied:(t||[]).slice(0,50),by:l||"",at:Date.now()});for(const m of ne)try{m.write(`event: prefs
|
|
7
7
|
data: ${c}
|
|
8
8
|
|
|
9
|
-
`)}catch{ne.delete(m)}},
|
|
9
|
+
`)}catch{ne.delete(m)}},ze=Tr(),kt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),$r=16,Ar=/^mcp[_-]/i,St=t=>t&&t.function&&t.function.name||t&&t.name||"",Pr=t=>t&&t.function&&t.function.description||t&&t.description||"";function vt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(l=>typeof l=="string"?l:l&&(l.text||l.content)||"").join(" "):""}function Er(t,l){if(!t)return"";if(l==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(p=>vt(p&&(p.content??p))).join(" "):""}const c=Array.isArray(t.messages)?t.messages:[];for(let m=c.length-1;m>=0;m--)if(c[m]&&c[m].role==="user")return vt(c[m].content);return""}const Tt=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function xt(t){if(!t)return!1;const l=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return l==="localhost"||l==="127.0.0.1"||l==="::1"}function Nr(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 Br(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 Ot=Date.now();function Dr(t){if(!t)return"";const l={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(c=>`${l[c]||c} ${t[c]}ms`).join(" · ")}function Cr(t){const l=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return l?{kind:l[1],id:l[2],...l[3]?{model:l[3]}:{}}:null}function Mr(t){const l=performance.now(),c={};let m=!1;const p=(y,O)=>{c[y]=Math.round(O*10)/10};return{meta:{},timings:c,mark:p,lap(y,O){p(y,performance.now()-O)},clock(){return performance.now()},commit(){if(m)return;m=!0,p("total",performance.now()-l);const y={...this.meta,timings:c};setImmediate(()=>{t(y),console.log(`[gateway] model=${y.model||"-"} → ${y.dest?`${y.dest}(${y.type})`:"none"} · ${y.redaction==="off"?"redaction OFF (client request)":`redacted ${y.redacted||0}`}${y.sanitized?` · scrubbed ${y.sanitized} hidden`:""}${y.narrowed?` · narrowed -${y.narrowed}`:""} · ${Dr(c)}`)})}}}function _t(t,l){if(!t||!t.byToken||l!=="types"&&l!=="values")return;const c=[];for(const[m,p]of t.byToken){const y=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),O=y?y[1]:"PII",T=m.replace(/^\[\[|\]\]$/g,"");c.push(l==="values"?{token:T,type:O,value:p}:{token:T,type:O})}return c}function jr(t,l,c){return Re.matches(t)||"anthropic-version"in l?{kind:"anthropic",adapter:Re,redactable:Re.matches(t),base:c.upstreams?.anthropic?.baseUrl}:bt.matches(t)?{kind:"responses",adapter:bt,redactable:!0,base:c.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Ie,redactable:Ie.matches(t),base:c.upstreams?.openai?.baseUrl}}function Je(t,l){const c=String(t||"");if(kt.has(c))return{agent:c,agentModel:""};const m=c.indexOf("/");if(m>0){const p=c.slice(0,m);if(kt.has(p))return{agent:p,agentModel:c.slice(m+1)}}return{agent:l.bridge.agent,agentModel:""}}function $t(t,l){return Je(t,l).agent}function Ir(t,l){if(l!=="openai"||!t)return!1;const c=Ie.extractLatestToolResult(t);if(!c)return!1;const m=et(c.tool_call_id);return!!(m&&qe(m.gwId))}function Rr(t,l){try{const c=new URL(t),m=c.hostname.replace(/^\[|\]$/g,""),p=m==="127.0.0.1"||m==="localhost"||m==="::1",y=c.port||(c.protocol==="https:"?"443":"80");return p&&String(y)===String(l.port)}catch{return!1}}async function x(t,l){const c=[];let m=0;for await(const p of t){if(m+=p.length,l&&m>l){const y=new Error("payload too large");throw y.code=413,y}c.push(p)}return Buffer.concat(c)}function s(t,l,c){t.writeHead(l,{"content-type":"application/json"}),t.end(JSON.stringify(c))}function At(t){const l=t.redaction?.detection?.url;return!l||t.redaction?.detection?.backend==="off"?null:l}function Ge(t){const l=t?.redaction?.detection,c=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:c,coverage:c==="full"?"names":"patterns"};const m=A.health(),p=m.ok&&c==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:A.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:p,tier:c,coverage:p?"names":"patterns"}}async function Pt(t){if(A.state()!=="off"){const c=A.health();return{configured:c.configured,ok:c.ok,state:c.state,model:c.model,error:c.error||null,url:c.configured?`http://${t.host}:${t.port}/ner`:null,stats:c.stats,companions:c.companions}}const l=At(t);if(!l)return{configured:!1,ok:!1,url:null,model:null};try{const c=await Qe(l.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!c.ok)return{configured:!0,ok:!1,url:l,model:null};const m=await c.json().catch(()=>({}));return{configured:!0,ok:!0,url:l,model:m.model||null}}catch{return{configured:!0,ok:!1,url:l,model:null}}}function Lr(t,l){const c={};for(const[m,p]of Object.entries(t)){const y=m.toLowerCase();y.startsWith("x-chatpanel-")||Tt.has(y)||(c[m]=p)}c["accept-encoding"]="identity";try{c.host=new URL(l).host}catch{}return c}async function Et(t,l,c,m){const p=Ke(l.vault),y=m?m.clock():0;let O=y,T=!0;const k=()=>{m&&T&&(m.lap("upstream",y),O=m.clock(),T=!1)};await io(l,{onText:j=>{k(),Ee(l.id);const S=p.push(j);S&&t.write(c.sseDelta(S))},onToolRequest:({name:j,restoredArgs:S,toolId:W})=>{k(),Ee(l.id);const I=p.flush();I&&t.write(c.sseDelta(I)),t.write(c.sseToolCalls([{id:W,name:j,arguments:JSON.stringify(S)}])),t.write(c.sseToolFinish()),m&&m.lap("stream",O),t.end(),m?.commit()},onDone:()=>{const j=p.flush();j&&t.write(c.sseDelta(j)),t.write(c.sseTail()),m&&m.lap("stream",O),t.end(),ve(l.id),m?.commit()},onError:j=>{t.write(`data: ${JSON.stringify({error:{message:j.message,type:"bridge_error"}})}
|
|
10
10
|
|
|
11
|
-
`),t.end(),
|
|
11
|
+
`),t.end(),ve(l.id),m?.commit()}})}async function zr(t,l,{kind:c,adapter:m,agent:p,run:y=null},O,T,k,j,S,W=null,I=null){const{messages:n,system:o}=m.toTurn(O),{agentModel:f}=Je(O?.model,k),d=yt(k,{...f?{model:f}:{},...y||{}}),C=ae(k.bridge.token),E=Ne(c,O?.model||p),J={tier:k.redaction.tier==="full"?"full":"basic",dictionary:zt(k.redaction,j),entities:[]},$=await de(k),X=ao({vault:T,redactOpts:J,bridgeUrl:$,token:C,harness:W});let se;try{se=await so({bridgeUrl:$,agent:p,token:C,messages:n,system:o,specs:co(S),options:d,signal:void 0})}catch(ce){return ve(X.id),I?.commit(),s(l,502,{error:{message:`bridge: ${ce.message}`,type:"bridge_error"}})}return X.reader=se.body.getReader(),l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write(E.sseHead()),Et(l,X,E,I)}async function Jr(t,l,c,m,p=null){Ee(l.id),l.rounds=(l.rounds||0)+1;try{const O=p?p.clock():0;await lo(l,c),p&&p.lap("redact",O)}catch(O){return ve(l.id),p?.commit(),s(t,502,{error:{message:`tool-result: ${O.message}`,type:"bridge_error"}})}const y=Ne("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(y.sseHead()),Et(t,l,y,p)}async function Gr(t,l,{kind:c,adapter:m,redactable:p,pathname:y,agentOverride:O,harness:T,trace:k,run:j=null},S,W,I,n){if(!p)return k?.commit(),s(l,404,{error:`endpoint ${y} not supported by the bridge backend`});if(c==="openai"){const z=m.extractLatestToolResult(S);if(z){const q=et(z.tool_call_id),K=q&&qe(q.gwId);if(K)return Jr(l,K,z.content,S?.model,k)}const R=m.extractTools(S);if(R.length&&S?.stream===!0)return zr(t,l,{kind:c,adapter:m,agent:O||$t(S?.model,I),run:j},S,W,I,n,R,T,k)}const{messages:o,system:f}=m.toTurn(S),d=O||$t(S?.model,I),C=S?.stream===!0,E=Ne(c,S?.model||d),J=ae(I.bridge.token),$=new AbortController;l.on("close",()=>{l.writableFinished||$.abort()});const{agentModel:X}=Je(S?.model,I),se={bridgeUrl:await de(I),agent:d,token:J,messages:o,system:f,signal:$.signal,options:yt(I,{...X?{model:X}:{},...j||{}})};if(!C)try{let z="";const R=k?k.clock():0;await Xe(se,oe=>{z+=oe}),k&&k.lap("upstream",R);const q=k?k.clock():0,K=E.full(Lt(z,W));return k&&k.lap("restore",q),l.writeHead(200,{"content-type":E.contentType}),l.end(K),k?.commit()}catch(z){return k?.commit(),s(l,502,{error:{message:`bridge backend failed: ${z.message}`,type:"bridge_error"}})}l.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),l.write(E.sseHead());const ce=Ke(W),he=k?k.clock():0;let te=he;try{let z=!0;await Xe(se,q=>{k&&z&&(k.lap("upstream",he),te=k.clock(),z=!1);const K=ce.push(q);K&&l.write(E.sseDelta(K))},E.sseActivity?q=>{try{l.write(E.sseActivity(Rt(q,W)))}catch{}}:null);const R=ce.flush();R&&l.write(E.sseDelta(R)),l.write(E.sseTail())}catch(z){l.write(`data: ${JSON.stringify({error:{message:z.message,type:"bridge_error"}})}
|
|
12
12
|
|
|
13
|
-
`)}
|
|
13
|
+
`)}k&&k.lap("stream",te),l.end(),k?.commit()}function Vr(t,l,c=""){const m=String(t||"").replace(/\/+$/,""),p=String(l||"").split("/")[1];return p&&m.endsWith(`/${p}`)?m.slice(0,-(p.length+1))+l+c:m+l+c}const Ur=9e4;function Hr(t,l,c){if(l===c)return t;const m=l/c,p=new Float32Array(Math.floor(t.length/m));for(let y=0;y<p.length;y++){const O=y*m,T=Math.floor(O),k=Math.min(t.length-1,T+1),j=O-T;p[y]=t[T]*(1-j)+t[k]*j}return p}const Fr=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];function Ve(t,l){const c=new URLSearchParams;for(const y of t.searchParams.getAll("dir"))y&&c.append("dir",y);const m=t.searchParams.get("workdir")||String(l?.bridge?.workingDir||"").trim();m&&c.set("workdir",m);const p=c.toString();return p?`?${p}`:""}async function Wr(t,l,{adapter:c,kind:m,pathname:p,search:y,base:O,destKey:T,destProtocol:k,harness:j,trace:S},W,I){let n;const o=S?S.clock():0;try{const E=Lr(t.headers,O);T&&(k==="anthropic"?(E["x-api-key"]=T,delete E.authorization):E.authorization=`Bearer ${T}`);const J=Ht(Vr(O,p,y)).toString();n=await fetch(J,{method:t.method,headers:E,body:["GET","HEAD"].includes(t.method)?void 0:W})}catch(E){return S?.commit(),s(l,502,{error:`upstream fetch failed: ${E.message}`})}const f=n.headers.get("content-type")||"",d={};if(n.headers.forEach((E,J)=>{Tt.has(J.toLowerCase())||(d[J]=E)}),f.includes("text/event-stream")&&n.body){S&&S.lap("upstream",o);const E=S?S.clock():0;l.writeHead(n.status,d);const J=m==="openai"?It(n.body,l,I,j):jt(n.body,l,I);return Promise.resolve(J).finally(()=>{S&&S.lap("stream",E),S?.commit()})}const C=Buffer.from(await n.arrayBuffer());if(S&&S.lap("upstream",o),I&&f.includes("application/json"))try{const E=S?S.clock():0,J=c.restoreResponse(JSON.parse(C.toString("utf8")),I,j);return S&&S.lap("restore",E),l.writeHead(n.status,{...d,"content-type":"application/json"}),l.end(Buffer.from(JSON.stringify(J),"utf8")),S?.commit()}catch{}l.writeHead(n.status,d),l.end(C),S?.commit()}function Kr(t=We()){let l=null;const c=()=>{if(!l){const n=t.read||{};l=Fo({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=Lo({wrap:(n,o,f,d)=>zo().wrap(n,o,f,d),onLog:n=>console.warn(`[extract worker] ${n}`)})),m);let y=null;const O=()=>(y||(y=Go({cfg:t,bridgeHealth:async()=>{const n=await de(t);if(!n)return null;const o=ae(t.bridge?.token),f=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return f.ok?f.json():null},persist:()=>{try{le(t,re())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},workers:()=>{const n=m?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),y),T=Vo({cfg:t});let k=null;const j=()=>{if(!k){const n=t.search||{},o=n.searxng?.url?Yo({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;k=Wo({reader:c(),searxng:o,defaultProvider:n.provider||"auto",redact:async f=>{let d=f;return await ke([Ae(()=>d,C=>{d=C})],{...t.redaction,tier:"basic"},{isPro:!0}),d}})}return k};Zt(t.allowedExtensionIds||[]);const S=[],W=n=>{S.push(n),S.length>50&&S.shift()},I=Dt(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),d=f.pathname;if(!xt(n.headers.host))return s(o,403,{error:"loopback only"});if(!Nr(n.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(n.headers.origin&&Br(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(d==="/admin/token"&&n.method==="POST")return F(n)?s(o,200,{token:Pe()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(d==="/pair/code"&&n.method==="POST"){if(!F(n))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Yt();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(d==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=Qt(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Se(n)} caller`),s(o,403,{error:r.reason});console.log(`[gateway] paired a ${Se(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const a=ae(t.bridge?.token);return s(o,200,{ok:!0,token:Kt()||Pe(),...a?{bridgeToken:a}:{}})}if(d==="/whoami"&&n.method==="POST"){const e=Se(n);return s(o,200,{ok:!0,trust:e,paired:Wt(e),version:Z})}if(d==="/audit"&&n.method==="GET")return F(n)?s(o,200,qt(t,{version:Z,startedAt:Ot,managed:ye()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((d==="/config"||d==="/logs"||d==="/update"&&n.method!=="GET")&&!F(n))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(d==="/update"&&n.method==="GET"){const e=await _o(Z,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:Z,updateAvailable:!1,error:String(r?.message||r)}));return s(o,200,{ok:!0,update:e,job:Po()})}if(d==="/update"&&n.method==="POST"){const e=Ao(Z);return s(o,e.already?409:202,{ok:!0,job:e})}if((d==="/v1/history/key"||d==="/v1/history/ingest-backup")&&n.method==="POST"&&!F(n))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(d==="/v1/history/records"&&n.method==="PUT"&&!F(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((d==="/v1/history/ingest"||d==="/v1/history/clear")&&n.method==="POST"&&!F(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((d==="/v1/memory/remember"||d==="/v1/memory/forget"||d==="/v1/memory/sync"||d==="/v1/memory/clear")&&n.method==="POST"&&!F(n))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((d==="/v1/prefs"||d.startsWith("/v1/prefs/")||d.startsWith("/v1/teams")||d.startsWith("/v1/agents")||d.startsWith("/v1/projects"))&&!F(n))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if(d.startsWith("/v1/observability")&&!F(n))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&d==="/health"){const e=B.health(),r=_.health();return s(o,200,{ok:!0,version:Z,backend:t.backend,tier:t.redaction.tier,pairing:!0,...ye()?{managed:ye()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...fe?{bridge:fe.status()}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Me,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||dt,voice:t.tts?.voice||ie,runtime:r.runtime,dtype:r.dtype}})}if(d==="/status"&&n.method==="GET"){Mt(t);const e=await ue(t.pro?.entitlementToken),r=await Pt(t);return s(o,200,{ok:!0,version:Z,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...ye()?{managed:ye()}:{},...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:Ge(t),pro:{unlocked:e},usage:gr(t),uptimeSeconds:Math.floor((Date.now()-Ot)/1e3),update:$o(Z)})}if(d==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await x(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(d==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?s(o,200,{ok:!0,revision:Q.revision,stamps:Q.stamps()}):s(o,200,{ok:!0,revision:Q.revision,sections:Q.get(e)})}if(d==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))||{},r=Q.put(e.sections||{},{by:e.by||""});return r.applied.length&&wt(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(d==="/v1/prefs"&&n.method==="DELETE"){const e=String(f.searchParams.get("section")||""),r=e?Q.remove(e):!1;return r&&wt([e],""),s(o,200,{ok:!0,removed:r})}if(d==="/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:
|
|
15
|
+
`);e({type:"hello",revision:Q.revision,stamps:Q.stamps()});const r=i=>e({type:"changed",...i});Le.add(r);const a=setInterval(()=>{try{o.write(`: keep-alive
|
|
16
16
|
|
|
17
|
-
`)}catch{}},25e3);o.on("close",()=>{
|
|
17
|
+
`)}catch{}},25e3);o.on("close",()=>{Le.delete(r),clearInterval(a)});return}if(d==="/v1/projects"&&n.method==="GET")return s(o,200,{ok:!0,projects:H.list({limit:f.searchParams.get("limit")||50,status:f.searchParams.get("status")||""})});if(d==="/v1/projects/jobs"&&n.method==="GET")return s(o,200,{ok:!0,jobs:H.openJobs()});if(d==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:H.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(d);if(e){const r=e[1],a=e[2]||"",i=e[3]||"",u=e[4]||"",w=()=>s(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(u){const h=H.get(r);if(!h)return w();const v=h.jobs.find(b=>b.id===i);if(!v)return s(o,404,{error:{message:`no job ${i}`,type:"not_found"}});const g={cfg:t,prefsStore:Q,scorecards:me,engines:pe};if(u==="/applications"&&n.method==="GET"){const b=await To(v,{...g,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:v,...b})}if(u==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(v.status))return s(o,400,{error:{message:`job ${i} is ${v.status}; only an open job is recruited`,type:"project_error"}});try{const b=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))||{},P=String(b.by||"evaluator").slice(0,80),V=await xo(v,{...g,record:h,reach:b.reach||"any",chatModel:b.chatModel||null,evaluation:b.evaluation||null,text:b.text??null,by:P});let M=null;for(const ee of V.events)ee.type==="job.updated"?M=H.updateJob(r,i,ee.job,{by:ee.by||P}):M=H.append(r,[ee]);return s(o,200,{ok:!0,project:M,decision:V.decision,applications:V.applications,evaluation:V.evaluation})}catch(b){return s(o,400,{error:{message:`recruit: ${b.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&n.method==="GET"){const h=H.get(r,{events:f.searchParams.get("events")==="1"});return h?s(o,200,{ok:!0,project:h}):w()}if(!a&&n.method==="DELETE")return s(o,200,{ok:!0,removed:H.remove(r)});if(n.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const h=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))||{},v=String(h.by||"person").slice(0,80),g=a==="/events"?H.append(r,h.events||[]):i?H.updateJob(r,i,h.patch||h,{by:v}):H.postJob(r,h.job||h,{by:v});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(!H.get(r))return w();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=P=>o.write(`data: ${JSON.stringify(P)}
|
|
18
18
|
|
|
19
|
-
`);let v=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:
|
|
19
|
+
`);let v=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:H.get(r),after:v}});const g=H.watch(r,P=>{P.seq>v&&(v=P.seq,h(P))});for(const P of H.eventsSince(r,v))v=P.seq,h(P);const b=setInterval(()=>{try{o.write(`: keep
|
|
20
20
|
|
|
21
|
-
`)}catch{}},25e3);n.on("close",()=>{clearInterval(b),g()});return}}}if(d==="/v1/agents/scorecards"&&n.method==="GET")return s(o,200,{ok:!0,agents:me.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(d);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return s(o,200,{ok:!0,...await me.get(r)});if(n.method==="POST")try{const a=JSON.parse((await
|
|
21
|
+
`)}catch{}},25e3);n.on("close",()=>{clearInterval(b),g()});return}}}if(d==="/v1/agents/scorecards"&&n.method==="GET")return s(o,200,{ok:!0,agents:me.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(d);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return s(o,200,{ok:!0,...await me.get(r)});if(n.method==="POST")try{const a=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))||{},i=await me.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 pe.fromRating(me.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(d==="/v1/capabilities"&&n.method==="GET")return s(o,200,Io(t,{version:Z,reader:l,searcher:k,extract:p(),proxy:T}));if(d==="/v1/runtime"&&n.method==="GET")return s(o,200,await O().status());{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(d);if(e&&n.method==="POST"){if(!F(n))return s(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const a=String(r.action||"start"),i=O(),u=e[1]==="engines"?a==="start"?await i.startEngine(e[2]):{ok:!1,error:`unknown action ${a}`}:a==="start"?await i.startService(e[2]):a==="stop"?await i.stopService(e[2]):a==="model"?await i.setModel(e[2],r.model):{ok:!1,error:`unknown action ${a}`};return s(o,u.ok?200:400,u)}}if((d==="/v1/rerank"||d==="/v1/decide")&&n.method==="POST"){const e=d.slice(4);let r;try{r=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const a=await T.call(e,r);return s(o,a.status,a.body)}if(d==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await Ro(e,{ensure:()=>Te(t),model:A.health().model});return s(o,r.status,r.body)}catch(r){return s(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(d==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await x(n,Math.max(t.maxBodyBytes,Math.ceil(Ho*4/3)+1024))).toString("utf8"))}catch{return s(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Uo(e,{service:p()});return s(o,r.status,r.body)}if(d==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await c().read(e);return s(o,r.status,r.body)}if(d==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}const r=await j().search(e);return s(o,r.status,r.body)}if(/^\/v1\/search\/./.test(d)&&n.method==="GET"){let e;try{e=decodeURIComponent(d.slice(11))}catch{e=d.slice(11)}const r=f.searchParams.has("read")?Math.max(0,Math.min(10,Number(f.searchParams.get("read"))||0)):Zo.aliasRead,a=await j().search({q:e,read:r,limit:Math.max(r,5)});return s(o,a.status,a.status===200?Ko(a.body):a.body)}if(/^\/v1\/read\/./.test(d)&&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 c().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(Qo(u.body)))}if(d==="/v1/engines"&&n.method==="GET"){const e=Number(f.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:pe.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(d);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 pe.get(r,{entries:f.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&n.method==="POST")try{const a=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))||{},i=a.engine||Cr(r);if(!i)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const u=await pe.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(d==="/v1/teams/runs"&&n.method==="GET")return s(o,200,{ok:!0,runs:G.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(d==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:G.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(d);if(e){const r=e[1],a=e[2]||"";if(!a&&n.method==="GET"){const i=G.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 G.stop(r),s(o,200,{ok:!0,removed:G.remove(r)});if(a==="/stop"&&n.method==="POST"){const i=G.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:G.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 x(n,t.maxBodyBytes)).toString("utf8"))||{},u=a==="/handoff"?G.handoff(r,{taskId:i.taskId,model:i.model,by:i.by,reason:i.reason}):G.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:G.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 x(n,t.maxBodyBytes)).toString("utf8"))||{},u=String(i.by||"person").slice(0,40),w=a==="/answer"?G.answer(r,{threadId:i.threadId,text:i.text,by:u}):a==="/decide"?G.decide(r,{postId:i.postId,status:i.status,by:u}):G.post(r,{threadId:i.threadId,text:i.text,by:u,kind:i.kind,replyTo:i.replyTo});return s(o,200,{ok:!0,run:w})}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 x(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:G.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(!G.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
|
-
`),u=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let w=Number.isFinite(u)?u:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:
|
|
23
|
+
`),u=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let w=Number.isFinite(u)?u:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:G.get(r),after:w}});const h=G.watch(r,g=>{g.seq==null?i(g):g.seq>w&&(w=g.seq,i(g))});for(const g of G.eventsSince(r,w))w=g.seq,i(g);const v=setInterval(()=>{try{o.write(`: keep-alive
|
|
24
24
|
|
|
25
|
-
`)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(v)});return}}}if(d==="/v1/memory/list"&&n.method==="GET")return s(o,200,{ok:!0,size:
|
|
26
|
-
data: ${JSON.stringify({newest:e.newest,size:e.size,version:
|
|
25
|
+
`)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(v)});return}}}if(d==="/v1/memory/list"&&n.method==="GET")return s(o,200,{ok:!0,size:Y.size,memories:Y.list()});if(d==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))||{},r=Y.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:Y.size,...r})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(d==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))||{},r=Y.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:Y.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(d==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=Y.forget(String(e.query||""));return s(o,200,{ok:!0,removed:r,size:Y.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(d==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))||{},r=Y.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...r,memories:Y.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(d==="/v1/memory/clear"&&n.method==="POST")return s(o,200,{ok:!0,dropped:Y.clear(),size:Y.size});if(d==="/v1/history/clear"&&n.method==="POST"){const e=N.clear();return s(o,200,{ok:!0,dropped:e,size:N.size})}if(d==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await x(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(d==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),a=xr(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),w=await Or(a,v=>N.search(v,{limit:u,...i}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=i.type?w:[...w.filter(v=>v.type==="brief"),...w.filter(v=>v.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(d==="/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(d==="/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(d==="/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:ze.snapshot(e)})}if(d==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))||{},r=ze.push(gt({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(d==="/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 x(n,t.maxBodyBytes)).toString("utf8"))||{},a=String(r.host||"").slice(0,80),i=Number(r.at)||Date.now(),u=[];let w=0;const h={upserts:[],removes:[]},v=g=>{if(!g||g.deletedAt){g?.id&&h.removes.push(g.id);return}try{const b=No(g);b&&h.upserts.push(b)}catch{}};if(Array.isArray(r.records)){const g=e.upsert(r.records,{host:a,at:i});u.push(...g);for(const b of r.records)g.includes(b?.id)&&v(b)}if(Array.isArray(r.entries)){const g=Be(),b=g?Co((M,ee)=>Bo(g,{salt:M,iterations:ee})):null,P=async M=>{if(!b||!M.blob)return null;const ee=await b(M.blob),be=M.blob.compression&&M.blob.compression!=="none"?Mo(jo,M.blob.compression):null;return Do(M.blob,ee,{codec:be})},V=await e.upsertEntries(r.entries,{open:P});u.push(...V.written),w+=V.sealed;for(const M of V.written)v(e.get(M))}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:w,size:e.size})}catch(r){return s(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(d==="/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:Z,prefsRevision:Q.revision})}
|
|
27
27
|
|
|
28
|
-
`),ne.add(o),n.on("close",()=>ne.delete(o));return}if(d==="/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(d==="/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(d==="/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(d==="/v1/history/key"&&n.method==="GET")return s(o,200,{ok:!0,hasKey:tt()});if(d==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?ho(String(e.passphrase)):yo();const r=e.passphrase?await De(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(d==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await De(N,Ne());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(d==="/ner"){if(n.method==="GET"){const e=await At(t);return s(o,e.ok?200:503,e)}if(n.method==="POST"){if(await ve(t),A.state()!=="off"){if(!A.isReady()){const r=A.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 O(n,t.maxBodyBytes);let a="";try{a=JSON.parse(r.toString("utf8"))?.text||""}catch{}const i=await A.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=A.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:A.state(),model:t.ner?.model||null})}try{const r=await O(n,t.maxBodyBytes),a=await Ye(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(d==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ge(t)});try{let r=e;const a=await ue(t.pro?.entitlementToken);await ve(t);const i=await we([$e(()=>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:Ot(i.vault,"types")||[],detector:Ge(t)})}catch(r){return s(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(d==="/ner/models"){if(n.method==="GET"){const e=A.health().model||t.ner?.model||null,r=Math.round(ot.totalmem()/1048576),a=Yo(rt,{totalRamMB:r}).map(i=>({...i,installed:A.modelOnDisk(i.id)}));for(const i of[e,...A.modelsOnDisk()])!i||a.some(u=>u.id===i)||a.push({id:i,label:i,lang:"—",custom:!0,installed:A.modelOnDisk(i),note:"Custom model (from Hugging Face)."});return s(o,200,{active:e,companions:A.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:mo(),recommendation:et(a,{totalRamMB:r},[]),state:A.state(),progress:A.progress(),available:a})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const a=Math.round(ot.totalmem()/1048576),i=et(rt.map(u=>({...u,installed:A.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(!(nt(u)||st(u)))return s(o,400,{error:{message:`unknown or invalid model id in union: ${u}`,type:"bad_model"}});const i=r||t.ner?.model||A.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=a.filter(u=>u!==i),r&&pt(t,r);try{le(t,re())}catch{}return(async()=>{r&&await A.setModel(r,{onLog:w=>console.log(w)});const u=uo(t.ner,{log:w=>console.log(w)});for(const w of A.companions())u.includes(w.model)||await A.removeCompanion(w.model);for(const w of u)await A.addCompanion(w,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});A.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),s(o,202,{accepted:!0,active:i,union:t.ner.union,companions:A.companions(),state:A.state()})}if(!r||!(nt(r)||st(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});pt(t,r);try{le(t,re())}catch{}return A.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:A.state(),progress:A.progress()})}}if(d==="/stt/models"){if(n.method==="GET"){const e=M.health().model||t.stt?.model||Ce,r=Qo.map(a=>({...a,installed:M.modelOnDisk(a.id)}));return e&&!r.some(a=>a.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:M.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:M.state(),progress:M.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:M.health().dtype,runtime:M.health().runtime,dtypes:er})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(Xo(r)||qo(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&tr(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,re())}catch{}return M.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:M.state(),progress:M.progress()})}}if(d==="/diarize/model"){if(n.method==="GET"){const e=R.health();return s(o,200,{active:R.DIARIZE_MODEL,state:e.state,progress:R.progress(),available:[{id:R.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:R.modelOnDisk()}]})}if(n.method==="POST")return R.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:R.DIARIZE_MODEL,state:R.state(),progress:R.progress()})}if(d==="/tts/models"){if(n.method==="GET"){const e=$.health().model||t.tts?.model||ut(Me()),r=Me(),a=at.find(u=>u.id===e)||null,i=at.map(u=>({...u,installed:$.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:$.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:$.state(),progress:$.progress(),available:i,voice:t.tts?.voice||(Oe(e)==="pocket-tts"?Te:ie),arch:$.arch(),supportsVoices:$.arch()?$.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:$.arch()?$.supportsCustomVoices():!!a?.customVoices,sampleRate:$.sampleRate(),voices:$.isPocket()||!$.arch()&&Oe(e)==="pocket-tts"?($.builtinVoices().length?$.builtinVoices():lr).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:$.builtinVoices().includes(u)})):$.arch()&&$.arch()!=="style-tts2"?[]:or.map(u=>({...u,installed:$.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:$.health().dtype,runtime:$.health().runtime,dtypes:sr})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(rr(r)||nr(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=J.parseCustomVoice(a);if(!(u?!!J.getVoice(u):xe(a)||it(a)&<(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&ar(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:ct,voice:ie,allowDownload:!0}),r&&(t.tts.model=r),a&&(t.tts.voice=a),r&&!a){const u=ir(r),w=J.parseCustomVoice(t.tts.voice||""),h=!!(w&&J.getVoice(w));if(u&&!h)if(Oe(r)==="pocket-tts")t.tts.voice=Te;else{const g=J.listVoices();t.tts.voice=g.length?`custom:${g[0].id}`:""}else!u&&h&&(t.tts.voice=ie);const v=Oe(r)==="pocket-tts";v&&!J.parseCustomVoice(t.tts.voice||"")&&!xe(t.tts.voice)&&(t.tts.voice=Te),!v&&xe(t.tts.voice)&&(t.tts.voice=ie)}i&&(t.tts.dtype=i==="auto"?null:i);try{le(t,re())}catch{}return r&&$.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:$.state(),progress:$.progress()})}}if(d==="/tts/voices"){if(n.method==="GET")return s(o,200,{voices:J.listVoices(),usable:$.supportsCustomVoices(),embedder:R.DIARIZE_MODEL,embedderReady:R.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await O(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(!J.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,{...J.renameVoice(i,r),usable:$.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(!R.isReady()){const b=R.download({onLog:I=>console.log(I)}),E=Symbol("timeout"),z=await Promise.race([b.then(()=>null).catch(I=>I),new Promise(I=>setTimeout(()=>I(E),Gr))]);if(z===E||!R.isReady())return s(o,503,{error:{message:z===E?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${R.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:R.progress()})}const u=Float32Array.from(a),w=await R.embed(u);let h=null;try{const b=await $.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:E=>console.log(E)});b&&(h=await b.encodeVoice(Jr(u,16e3,24e3)))}catch(b){console.log(`[tts] pocket conditioning unavailable for this voice (${b.message})`)}const v=i?J.replaceVoice(i,{vec:w,pocket:h}):J.saveVoice({name:r,vec:w,pocket:h}),g=i&&r&&r!==v.name?J.renameVoice(i,r):v;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${g.name}" (${(v.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...v,...g,usable:$.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=J.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const a=J.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:ie;try{le(t,re())}catch{}}return s(o,200,{deleted:r,voice:t.tts?.voice})}}if((d==="/tts"||d==="/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 O(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>dt)return s(o,413,{error:{message:`text too long (max ${dt} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=cr(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,w=u||(i?i.voice:t.tts?.voice||ie);if(i&&!ur(w))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:be,contentType:Pt,redacted:Nt}=await dr({dest:i,text:r,voice:w,speed:a,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ue(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":Pt,"Content-Length":String(be.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(Nt)}),o.end(be)}if(!await $.ready({onLog:be=>console.log(be),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||ut(Me()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:$.health().error||"tts model not ready",type:"tts_unavailable"}});const g=mr({requested:u,configured:w,engine:$,voices:J,isPocketVoice:xe,isKnownVoice:it,isValidVoiceId:lt,defaultVoice:ie,defaultPocketVoice:Te});if(!g.ok)return s(o,g.status,{error:{message:g.message,type:g.type}});const{voice:b,customId:E,speakerEmbedding:z}=g,I=await $.synth(r,{voice:b,speed:a,speakerEmbedding:z}),Q=$.sampleRate(),ge=h==="pcm"?Buffer.from(new Float32Array(I).buffer):$.toWav(I,Q);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(ge.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Q),...E||$.isPocket()||$.supportsVoices()?{"X-Tts-Voice":b}:{}}),o.end(ge)}catch(v){return s(o,500,{error:{message:v.message,type:"tts_failed"}})}}if(d==="/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 O(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}M.isReady()||M.init({model:t.stt?.model||Ce,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&&!R.isReady()&&R.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:a=>console.log(a)});try{const{id:a}=M.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:r,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs});return s(o,201,{id:a,state:M.state()})}catch(a){return s(o,a.code==="too_many_sessions"?429:500,{error:{message:a.message,type:a.code||"stt_error"}})}}{const e=d.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 O(n,t.maxBodyBytes);return M.pushAudio(r,M.toFloat32(a)),s(o,200,{ok:!0,state:M.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=M.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=b=>o.write(`data: ${JSON.stringify(b)}
|
|
28
|
+
`),ne.add(o),n.on("close",()=>ne.delete(o));return}if(d==="/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(d==="/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(d==="/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(d==="/v1/history/key"&&n.method==="GET")return s(o,200,{ok:!0,hasKey:ot()});if(d==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?yo(String(e.passphrase)):fo();const r=e.passphrase?await Ce(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(d==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await Ce(N,Be());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(d==="/ner"){if(n.method==="GET"){const e=await Pt(t);return s(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Te(t),A.state()!=="off"){if(!A.isReady()){const r=A.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 x(n,t.maxBodyBytes);let a="";try{a=JSON.parse(r.toString("utf8"))?.text||""}catch{}const i=await A.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=At(t);if(!e){const r=A.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:A.state(),model:t.ner?.model||null})}try{const r=await x(n,t.maxBodyBytes),a=await Qe(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(d==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ge(t)});try{let r=e;const a=await ue(t.pro?.entitlementToken);await Te(t);const i=await ke([Ae(()=>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:_t(i.vault,"types")||[],detector:Ge(t)})}catch(r){return s(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(d==="/ner/models"){if(n.method==="GET"){const e=A.health().model||t.ner?.model||null,r=Math.round(rt.totalmem()/1048576),a=Xo(nt,{totalRamMB:r}).map(i=>({...i,installed:A.modelOnDisk(i.id)}));for(const i of[e,...A.modelsOnDisk()])!i||a.some(u=>u.id===i)||a.push({id:i,label:i,lang:"—",custom:!0,installed:A.modelOnDisk(i),note:"Custom model (from Hugging Face)."});return s(o,200,{active:e,companions:A.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:po(),recommendation:tt(a,{totalRamMB:r},[]),state:A.state(),progress:A.progress(),available:a})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const a=Math.round(rt.totalmem()/1048576),i=tt(nt.map(u=>({...u,installed:A.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(!(st(u)||at(u)))return s(o,400,{error:{message:`unknown or invalid model id in union: ${u}`,type:"bad_model"}});const i=r||t.ner?.model||A.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=a.filter(u=>u!==i),r&&ht(t,r);try{le(t,re())}catch{}return(async()=>{r&&await A.setModel(r,{onLog:w=>console.log(w)});const u=mo(t.ner,{log:w=>console.log(w)});for(const w of A.companions())u.includes(w.model)||await A.removeCompanion(w.model);for(const w of u)await A.addCompanion(w,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});A.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),s(o,202,{accepted:!0,active:i,union:t.ner.union,companions:A.companions(),state:A.state()})}if(!r||!(st(r)||at(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});ht(t,r);try{le(t,re())}catch{}return A.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:A.state(),progress:A.progress()})}}if(d==="/stt/models"){if(n.method==="GET"){const e=B.health().model||t.stt?.model||Me,r=qo.map(a=>({...a,installed:B.modelOnDisk(a.id)}));return e&&!r.some(a=>a.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:B.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:B.state(),progress:B.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:B.health().dtype,runtime:B.health().runtime,dtypes:or})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(er(r)||tr(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&rr(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,re())}catch{}return B.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:B.state(),progress:B.progress()})}}if(d==="/diarize/model"){if(n.method==="GET"){const e=L.health();return s(o,200,{active:L.DIARIZE_MODEL,state:e.state,progress:L.progress(),available:[{id:L.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:L.modelOnDisk()}]})}if(n.method==="POST")return L.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:L.DIARIZE_MODEL,state:L.state(),progress:L.progress()})}if(d==="/tts/models"){if(n.method==="GET"){const e=_.health().model||t.tts?.model||mt(je()),r=je(),a=it.find(u=>u.id===e)||null,i=it.map(u=>({...u,installed:_.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:_.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:_.state(),progress:_.progress(),available:i,voice:t.tts?.voice||(_e(e)==="pocket-tts"?xe:ie),arch:_.arch(),supportsVoices:_.arch()?_.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:_.arch()?_.supportsCustomVoices():!!a?.customVoices,sampleRate:_.sampleRate(),voices:_.isPocket()||!_.arch()&&_e(e)==="pocket-tts"?(_.builtinVoices().length?_.builtinVoices():dr).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:_.builtinVoices().includes(u)})):_.arch()&&_.arch()!=="style-tts2"?[]:nr.map(u=>({...u,installed:_.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:_.health().dtype,runtime:_.health().runtime,dtypes:ir})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(sr(r)||ar(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=U.parseCustomVoice(a);if(!(u?!!U.getVoice(u):Oe(a)||lt(a)&&ct(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&lr(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:dt,voice:ie,allowDownload:!0}),r&&(t.tts.model=r),a&&(t.tts.voice=a),r&&!a){const u=cr(r),w=U.parseCustomVoice(t.tts.voice||""),h=!!(w&&U.getVoice(w));if(u&&!h)if(_e(r)==="pocket-tts")t.tts.voice=xe;else{const g=U.listVoices();t.tts.voice=g.length?`custom:${g[0].id}`:""}else!u&&h&&(t.tts.voice=ie);const v=_e(r)==="pocket-tts";v&&!U.parseCustomVoice(t.tts.voice||"")&&!Oe(t.tts.voice)&&(t.tts.voice=xe),!v&&Oe(t.tts.voice)&&(t.tts.voice=ie)}i&&(t.tts.dtype=i==="auto"?null:i);try{le(t,re())}catch{}return r&&_.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:_.state(),progress:_.progress()})}}if(d==="/tts/voices"){if(n.method==="GET")return s(o,200,{voices:U.listVoices(),usable:_.supportsCustomVoices(),embedder:L.DIARIZE_MODEL,embedderReady:L.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await x(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(!U.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,{...U.renameVoice(i,r),usable:_.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(!L.isReady()){const b=L.download({onLog:M=>console.log(M)}),P=Symbol("timeout"),V=await Promise.race([b.then(()=>null).catch(M=>M),new Promise(M=>setTimeout(()=>M(P),Ur))]);if(V===P||!L.isReady())return s(o,503,{error:{message:V===P?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${L.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:L.progress()})}const u=Float32Array.from(a),w=await L.embed(u);let h=null;try{const b=await _.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:P=>console.log(P)});b&&(h=await b.encodeVoice(Hr(u,16e3,24e3)))}catch(b){console.log(`[tts] pocket conditioning unavailable for this voice (${b.message})`)}const v=i?U.replaceVoice(i,{vec:w,pocket:h}):U.saveVoice({name:r,vec:w,pocket:h}),g=i&&r&&r!==v.name?U.renameVoice(i,r):v;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${g.name}" (${(v.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...v,...g,usable:_.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=U.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const a=U.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:ie;try{le(t,re())}catch{}}return s(o,200,{deleted:r,voice:t.tts?.voice})}}if((d==="/tts"||d==="/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 x(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>ut)return s(o,413,{error:{message:`text too long (max ${ut} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=ur(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,w=u||(i?i.voice:t.tts?.voice||ie);if(i&&!pr(w))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:we,contentType:Nt,redacted:Bt}=await mr({dest:i,text:r,voice:w,speed:a,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ue(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":Nt,"Content-Length":String(we.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(Bt)}),o.end(we)}if(!await _.ready({onLog:we=>console.log(we),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||mt(je()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:_.health().error||"tts model not ready",type:"tts_unavailable"}});const g=hr({requested:u,configured:w,engine:_,voices:U,isPocketVoice:Oe,isKnownVoice:lt,isValidVoiceId:ct,defaultVoice:ie,defaultPocketVoice:xe});if(!g.ok)return s(o,g.status,{error:{message:g.message,type:g.type}});const{voice:b,customId:P,speakerEmbedding:V}=g,M=await _.synth(r,{voice:b,speed:a,speakerEmbedding:V}),ee=_.sampleRate(),be=h==="pcm"?Buffer.from(new Float32Array(M).buffer):_.toWav(M,ee);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(be.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(ee),...P||_.isPocket()||_.supportsVoices()?{"X-Tts-Voice":b}:{}}),o.end(be)}catch(v){return s(o,500,{error:{message:v.message,type:"tts_failed"}})}}if(d==="/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 x(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}B.isReady()||B.init({model:t.stt?.model||Me,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&&!L.isReady()&&L.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:a=>console.log(a)});try{const{id:a}=B.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:r,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs});return s(o,201,{id:a,state:B.state()})}catch(a){return s(o,a.code==="too_many_sessions"?429:500,{error:{message:a.message,type:a.code||"stt_error"}})}}{const e=d.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 x(n,t.maxBodyBytes);return B.pushAudio(r,B.toFloat32(a)),s(o,200,{ok:!0,state:B.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=B.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=b=>o.write(`data: ${JSON.stringify(b)}
|
|
29
29
|
|
|
30
|
-
`),u=a.redact?await ue(t.pro?.entitlementToken):!0,w=async b=>{if(b.type!=="final"||!a.redact)return b;try{let E=b.text;return await we([$e(()=>E,z=>{E=z})],t.redaction,{isPro:u}),{...b,text:E}}catch{return b}};i({type:"state",state:M.state()});const h=setInterval(()=>{const b=M.state();if(b==="downloading"||b==="loading"){i({type:"progress",state:b,...M.progress()||{}});return}if(b==="error"){i({type:"error",code:"model_failed",message:M.health().error||"model failed to load",fatal:!0}),clearInterval(h);return}if(a.diarize){const E=R.state();if(E==="downloading"||E==="loading"){i({type:"diarize-progress",state:E,...R.progress()||{}});return}}i({type:"state",state:b}),clearInterval(h)},500);h.unref?.();let v=Promise.resolve();const g=M.subscribe(r,b=>{v=v.then(async()=>{i(await w(b)),b.type==="end"&&(clearInterval(h),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(h),g?.()});return}if(!e[2]&&n.method==="DELETE")return await M.endSession(r),s(o,200,{ok:!0})}}if(d==="/logs"&&n.method==="GET")return s(o,200,{entries:[...j].reverse()});if(d==="/config"&&n.method==="GET"){const e=await ue(t.pro?.entitlementToken);return s(o,200,mt(t,{proUnlocked:e}))}if(d==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await O(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{fr(t,e)}catch(h){if(h?.code==="SHAPE")return s(o,400,{error:h.message});throw h}Ke(t),JSON.stringify(t.sandbox||null)!==r&&ye?.restart("sandbox settings changed");try{le(t,re())}catch(h){return s(o,500,{error:`could not persist config: ${h.message}`})}const a=t.redaction?.detection,i=!a||!a.backend||a.backend==="off",u=A.state();t.ner?.autostart&&i&&u!=="ready"&&u!=="loading"&&u!=="downloading"&&A.setModel(t.ner.model,{onLog:h=>console.log(h)}).then(h=>{h&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const w=await ue(t.pro?.entitlementToken);return s(o,200,mt(t,{proUnlocked:w}))}if(n.method==="GET"&&d==="/skills"){const e=await de(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${Je(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(d)){const e=decodeURIComponent(d.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 de(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)}${Je(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(d==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(d)){if(!W(n))return s(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(d==="/channels"&&n.method==="GET"||d!=="/channels"&&n.method==="POST"))return s(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await de(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 O(n,t.maxBodyBytes)).toString("utf8"):"",i=await fetch(`${e}${d}`,{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(d)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(d),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 de(t);if(!i)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const u=ae(t.bridge?.token);try{const w=await fetch(`${i}/skills/${encodeURIComponent(r)}/file/${a}${Je(f,t)}`,{headers:{Accept:"application/json",...u?{Authorization:`Bearer ${u}`}:{}},signal:AbortSignal.timeout(8e3)}),h=await w.json().catch(()=>({}));return w.ok?s(o,200,h):s(o,w.status,{error:{message:h?.error||`bridge ${w.status}`,type:"bridge_error"}})}catch(w){return s(o,502,{error:{message:`bridge unreachable: ${w.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/\/models$/.test(d))return s(o,200,await wr(t));if(Vr.some(e=>d===e||d.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${K}) has no ${d} — update it to use this feature`,type:"unknown_endpoint"}});const C=Dr(d,n.headers,t);let H;try{H=await O(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 P=null,S=null,X=H,te=0,se=0,ce=0,q=!1,oe=!0;const B=t.logRequests&&C.redactable&&n.method==="POST"?Br(x):null;if(C.redactable&&n.method==="POST"&&H.length){try{S=JSON.parse(H.toString("utf8"))}catch{S=null}if(S&&Cr(S,C.kind))X=H;else if(S){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(S.tools)&&S.tools.length){const g=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):xr,b=e.narrowAll?null:z=>!Or.test(kt(z)),E=S.tools.length;S.tools=zt(S.tools,$r(S,C.kind),{cap:g,keep:b,name:kt,description:_r}),ce=E-S.tools.length}oe=await ue(t.pro?.entitlementToken);const r=pr(t,oe);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"}});q=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&W(n),q||await ve(t);const a=q?[]:C.adapter.collectSegments(S,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const u=B?B.clock():0,{vault:w,count:h,sanitized:v}=q?{vault:null,count:0,sanitized:0}:await we(a,t.redaction,{signal:i.signal,isPro:oe,onEgress:g=>Le.push(ft({ts:Date.now(),client:"redaction",tool:`detect:${g.backend}@${g.host||"local"}`,ok:g.ok,ms:g.ms,error:g.error}))});if(B&&B.lap("redact",u),P=w,te=h,se=v||0,!oe&&h>0){hr(t,oe);try{le(t,re())}catch{}}if(!q&&Array.isArray(S.tools)&&S.tools.length&&typeof C.adapter.injectSystemNote=="function"){const g=yt(S?.model,t,C.kind,{destination:String(n.headers["x-chatpanel-destination"]||S?.chatpanel?.destination||"").trim()}),b=!(g&&g.type==="api");C.adapter.injectSystemNote(S,Jt({toolData:t.tools?.toolData,ownTools:b}))}else!q&&h>0&&typeof C.adapter.injectSystemNote=="function"&&C.adapter.injectSystemNote(S,Vt());X=Buffer.from(JSON.stringify(S),"utf8")}}const ee=Gt({vault:P,toolData:t.tools?.toolData}),F=S&&typeof S.chatpanel=="object"&&S.chatpanel||null;F&&(delete S.chatpanel,X=Buffer.from(JSON.stringify(S),"utf8"));const G={destination:String(n.headers["x-chatpanel-destination"]||F?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||F?.reach||"").trim(),run:Fr(n.headers["x-chatpanel-run"],F?.run)},D=yt(S?.model,t,C.kind,{destination:G.destination});if(G.destination&&(!D||D.id!==G.destination))return B?.commit(),s(o,404,{error:{message:`no destination "${G.destination}" is configured on this gateway`,type:"unknown_destination",known:kr(t).map(e=>e.id)}});B&&(B.meta={t:Date.now(),model:S?.model||null,dest:D?D.id:null,type:D?D.type:null,redacted:te,sanitized:se,narrowed:ce,detail:Ot(P,t.logDetail),redaction:q?"off":t.redaction.tier||"basic"});const fe=eo();if(fe&&D){const e=D.type==="api"?Ze(fe,{model:S?.model||"",endpoint:D.baseUrl||""}):oo(fe,D.agent||D.id)?Ze(fe,{model:S?.model||""}):{ok:!1,reason:`agent "${D.agent||D.id}" is not allowed by your organisation’s policy`};if(!e.ok)return B?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(D&&D.type==="api")return D.baseUrl?Mr(D.baseUrl,t)?(B?.commit(),s(o,508,{error:{message:`destination "${D.id}" points back at the gateway (${D.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Ur(n,o,{...C,pathname:d,search:f.search,base:D.baseUrl,destKey:D.apiKey,destProtocol:D.protocol,harness:ee,trace:B},X,P):(B?.commit(),s(o,502,{error:`destination "${D.id}" has no baseUrl`}));const Ve=ke(n),Ue=Ve==="local"&&t.bridge?.openAgentLane?"token":Ve;if(Ue==="local")return B?.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 He=Ht({...G.run||{},...G.reach?{reach:G.reach}:{}},Ue);return Lr(n,o,{...C,pathname:d,agentOverride:D?.agent,harness:ee,trace:B,run:Object.keys(He).length?He:null},S,P,t,oe)});return U.on("close",()=>{m?.stop("closed"),zo()}),U}function Fr(t,l){let c=l&&typeof l=="object"?l:null;if(!c&&t)try{c=JSON.parse(decodeURIComponent(String(t)))}catch{c=null}if(!c||typeof c!="object")return null;const m={};if(Array.isArray(c.grants)&&(m.grants=c.grants.map(p=>String(p).slice(0,80)).slice(0,32)),c.workspace&&typeof c.workspace=="object"&&c.workspace.repo){const p=c.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)}:{}}}if(c.connectionId&&(m.connectionId=String(c.connectionId).slice(0,64)),typeof c.workingDir=="string"&&c.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(c.workingDir.trim())&&(m.workingDir=c.workingDir.trim().slice(0,1024)),gr.includes(c.permissionMode)&&c.permissionMode!=="default"&&(m.permissionMode=c.permissionMode),c.sandbox&&typeof c.sandbox=="object"){const p=(Array.isArray(c.sandbox.hosts)?c.sandbox.hosts:String(c.sandbox.hosts||"").split(/[\s,;]+/)).map(_=>String(_).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),y=(Array.isArray(c.sandbox.write)?c.sandbox.write:[]).map(_=>String(_).slice(0,1024)).filter(Boolean).slice(0,32);(p.length||y.length)&&(m.sandbox={...p.length?{hosts:p}:{},...y.length?{write:y}:{}})}return Object.keys(m).length?m:null}let ye=null;async function Qn(t=Fe()){po();let l=null;try{l=await qt()}catch(k){throw k instanceof to&&(console.error(`[chatpanel-gateway] org policy: ${k.message}`),process.exit(78)),k}const c=l?.policy||null;c&&(Ke(t,c),console.log(`[chatpanel-gateway] ${l.label} — ${l.signed?"signed":"unsigned"} policy from ${l.source}`)),Qt(globalThis,{allow:c?.egress?(k,{local:T})=>ro(c,k,{local:T}):null}),Ae();const m=Hr(t),p=co(t),y=Dt(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 ${re()} (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${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"),xo(t,{childEnv:()=>br(t)}).then(k=>{ye=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…)":"")),Tt(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.`)}),tt()&&De(N,Ne()).then(k=>{k?.ok&&(console.log(` warm : seeded ${k.ingested} records from ${k.file}`),k.whole&&_e())}).catch(()=>{});const _=()=>{p?.stop(),y.stop(),ye?.stop(),m.close(()=>process.exit(0))};return process.on("SIGINT",_),process.on("SIGTERM",_),m}export{K as VERSION,Hr as createGateway,zr as joinUpstream,ze as parseAgentModel,Qn as start};
|
|
30
|
+
`),u=a.redact?await ue(t.pro?.entitlementToken):!0,w=async b=>{if(b.type!=="final"||!a.redact)return b;try{let P=b.text;return await ke([Ae(()=>P,V=>{P=V})],t.redaction,{isPro:u}),{...b,text:P}}catch{return b}};i({type:"state",state:B.state()});const h=setInterval(()=>{const b=B.state();if(b==="downloading"||b==="loading"){i({type:"progress",state:b,...B.progress()||{}});return}if(b==="error"){i({type:"error",code:"model_failed",message:B.health().error||"model failed to load",fatal:!0}),clearInterval(h);return}if(a.diarize){const P=L.state();if(P==="downloading"||P==="loading"){i({type:"diarize-progress",state:P,...L.progress()||{}});return}}i({type:"state",state:b}),clearInterval(h)},500);h.unref?.();let v=Promise.resolve();const g=B.subscribe(r,b=>{v=v.then(async()=>{i(await w(b)),b.type==="end"&&(clearInterval(h),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(h),g?.()});return}if(!e[2]&&n.method==="DELETE")return await B.endSession(r),s(o,200,{ok:!0})}}if(d==="/logs"&&n.method==="GET")return s(o,200,{entries:[...S].reverse()});if(d==="/config"&&n.method==="GET"){const e=await ue(t.pro?.entitlementToken);return s(o,200,pt(t,{proUnlocked:e}))}if(d==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await x(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{br(t,e)}catch(h){if(h?.code==="SHAPE")return s(o,400,{error:h.message});throw h}Ze(t),JSON.stringify(t.sandbox||null)!==r&&fe?.restart("sandbox settings changed");try{le(t,re())}catch(h){return s(o,500,{error:`could not persist config: ${h.message}`})}const a=t.redaction?.detection,i=!a||!a.backend||a.backend==="off",u=A.state();t.ner?.autostart&&i&&u!=="ready"&&u!=="loading"&&u!=="downloading"&&A.setModel(t.ner.model,{onLog:h=>console.log(h)}).then(h=>{h&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const w=await ue(t.pro?.entitlementToken);return s(o,200,pt(t,{proUnlocked:w}))}if(n.method==="GET"&&d==="/skills"){const e=await de(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${Ve(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(d)){const e=decodeURIComponent(d.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 de(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)}${Ve(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(d==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(d)){if(!F(n))return s(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(d==="/channels"&&n.method==="GET"||d!=="/channels"&&n.method==="POST"))return s(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await de(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 x(n,t.maxBodyBytes)).toString("utf8"):"",i=await fetch(`${e}${d}`,{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(d)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(d),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 de(t);if(!i)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const u=ae(t.bridge?.token);try{const w=await fetch(`${i}/skills/${encodeURIComponent(r)}/file/${a}${Ve(f,t)}`,{headers:{Accept:"application/json",...u?{Authorization:`Bearer ${u}`}:{}},signal:AbortSignal.timeout(8e3)}),h=await w.json().catch(()=>({}));return w.ok?s(o,200,h):s(o,w.status,{error:{message:h?.error||`bridge ${w.status}`,type:"bridge_error"}})}catch(w){return s(o,502,{error:{message:`bridge unreachable: ${w.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/\/models$/.test(d))return s(o,200,await Sr(t));if(Fr.some(e=>d===e||d.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${Z}) has no ${d} — update it to use this feature`,type:"unknown_endpoint"}});const C=jr(d,n.headers,t);let E;try{E=await x(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 J=null,$=null,X=E,se=0,ce=0,he=0,te=!1,z=!0;const R=t.logRequests&&C.redactable&&n.method==="POST"?Mr(W):null;if(C.redactable&&n.method==="POST"&&E.length){try{$=JSON.parse(E.toString("utf8"))}catch{$=null}if($&&Ir($,C.kind))X=E;else if($){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray($.tools)&&$.tools.length){const g=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):$r,b=e.narrowAll?null:V=>!Ar.test(St(V)),P=$.tools.length;$.tools=Jt($.tools,Er($,C.kind),{cap:g,keep:b,name:St,description:Pr}),he=P-$.tools.length}z=await ue(t.pro?.entitlementToken);const r=yr(t,z);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"}});te=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&F(n),te||await Te(t);const a=te?[]:C.adapter.collectSegments($,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const u=R?R.clock():0,{vault:w,count:h,sanitized:v}=te?{vault:null,count:0,sanitized:0}:await ke(a,t.redaction,{signal:i.signal,isPro:z,onEgress:g=>ze.push(gt({ts:Date.now(),client:"redaction",tool:`detect:${g.backend}@${g.host||"local"}`,ok:g.ok,ms:g.ms,error:g.error}))});if(R&&R.lap("redact",u),J=w,se=h,ce=v||0,!z&&h>0){fr(t,z);try{le(t,re())}catch{}}if(!te&&Array.isArray($.tools)&&$.tools.length&&typeof C.adapter.injectSystemNote=="function"){const g=ft($?.model,t,C.kind,{destination:String(n.headers["x-chatpanel-destination"]||$?.chatpanel?.destination||"").trim()}),b=!(g&&g.type==="api");C.adapter.injectSystemNote($,Vt({toolData:t.tools?.toolData,ownTools:b}))}else!te&&h>0&&typeof C.adapter.injectSystemNote=="function"&&C.adapter.injectSystemNote($,Ut());X=Buffer.from(JSON.stringify($),"utf8")}}const q=Gt({vault:J,toolData:t.tools?.toolData}),K=$&&typeof $.chatpanel=="object"&&$.chatpanel||null;K&&(delete $.chatpanel,X=Buffer.from(JSON.stringify($),"utf8"));const oe={destination:String(n.headers["x-chatpanel-destination"]||K?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||K?.reach||"").trim(),run:Zr(n.headers["x-chatpanel-run"],K?.run)},D=ft($?.model,t,C.kind,{destination:oe.destination});if(oe.destination&&(!D||D.id!==oe.destination))return R?.commit(),s(o,404,{error:{message:`no destination "${oe.destination}" is configured on this gateway`,type:"unknown_destination",known:vr(t).map(e=>e.id)}});R&&(R.meta={t:Date.now(),model:$?.model||null,dest:D?D.id:null,type:D?D.type:null,redacted:se,sanitized:ce,narrowed:he,detail:_t(J,t.logDetail),redaction:te?"off":t.redaction.tier||"basic"});const ge=to();if(ge&&D){const e=D.type==="api"?Ye(ge,{model:$?.model||"",endpoint:D.baseUrl||""}):ro(ge,D.agent||D.id)?Ye(ge,{model:$?.model||""}):{ok:!1,reason:`agent "${D.agent||D.id}" is not allowed by your organisation’s policy`};if(!e.ok)return R?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(D&&D.type==="api")return D.baseUrl?Rr(D.baseUrl,t)?(R?.commit(),s(o,508,{error:{message:`destination "${D.id}" points back at the gateway (${D.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Wr(n,o,{...C,pathname:d,search:f.search,base:D.baseUrl,destKey:D.apiKey,destProtocol:D.protocol,harness:q,trace:R},X,J):(R?.commit(),s(o,502,{error:`destination "${D.id}" has no baseUrl`}));const Ue=Se(n),He=Ue==="local"&&t.bridge?.openAgentLane?"token":Ue;if(He==="local")return R?.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 Fe=Ft({...oe.run||{},...oe.reach?{reach:oe.reach}:{}},He);return Gr(n,o,{...C,pathname:d,agentOverride:D?.agent,harness:q,trace:R,run:Object.keys(Fe).length?Fe:null},$,J,t,z)});return I.on("close",()=>{m?.stop("closed"),Jo()}),I}function Zr(t,l){let c=l&&typeof l=="object"?l:null;if(!c&&t)try{c=JSON.parse(decodeURIComponent(String(t)))}catch{c=null}if(!c||typeof c!="object")return null;const m={};if(Array.isArray(c.grants)&&(m.grants=c.grants.map(p=>String(p).slice(0,80)).slice(0,32)),c.workspace&&typeof c.workspace=="object"&&c.workspace.repo){const p=c.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)}:{}}}if(c.connectionId&&(m.connectionId=String(c.connectionId).slice(0,64)),typeof c.workingDir=="string"&&c.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(c.workingDir.trim())&&(m.workingDir=c.workingDir.trim().slice(0,1024)),wr.includes(c.permissionMode)&&c.permissionMode!=="default"&&(m.permissionMode=c.permissionMode),c.sandbox&&typeof c.sandbox=="object"){const p=(Array.isArray(c.sandbox.hosts)?c.sandbox.hosts:String(c.sandbox.hosts||"").split(/[\s,;]+/)).map(O=>String(O).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),y=(Array.isArray(c.sandbox.write)?c.sandbox.write:[]).map(O=>String(O).slice(0,1024)).filter(Boolean).slice(0,32);(p.length||y.length)&&(m.sandbox={...p.length?{hosts:p}:{},...y.length?{write:y}:{}})}return Object.keys(m).length?m:null}let fe=null;async function os(t=We()){ho();let l=null;try{l=await eo()}catch(T){throw T instanceof oo&&(console.error(`[chatpanel-gateway] org policy: ${T.message}`),process.exit(78)),T}const c=l?.policy||null;c&&(Ze(t,c),console.log(`[chatpanel-gateway] ${l.label} — ${l.signed?"signed":"unsigned"} policy from ${l.source}`)),Xt(globalThis,{allow:c?.egress?(T,{local:k})=>no(c,T,{local:k}):null}),Pe();const m=Kr(t),p=uo(t),y=Ct(t);m.on("error",T=>{T&&T.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 ${re()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${T?.message||T}`),process.exit(1)}),m.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${Z} 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"),Oo(t,{childEnv:()=>kr(t)}).then(T=>{fe=T}).catch(T=>console.log(` bridge : not supervised (${T?.message||T})`)),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),xt(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.`)}),ot()&&Ce(N,Be()).then(T=>{T?.ok&&(console.log(` warm : seeded ${T.ingested} records from ${T.file}`),T.whole&&$e())}).catch(()=>{});const O=()=>{p?.stop(),y.stop(),fe?.stop(),_r(m)};return process.on("SIGINT",O),process.on("SIGTERM",O),m}export{Z as VERSION,Kr as createGateway,Vr as joinUpstream,Je as parseAgentModel,os as start};
|