@chatpanel/gateway 0.57.4 → 0.61.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.57.4",
3
+ "version": "0.61.2",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -23,7 +23,7 @@
23
23
  "dependencies": {
24
24
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
25
25
  "@chatpanel/bridge": "^0.32.2",
26
- "@chatpanel/events": "^0.226.0",
26
+ "@chatpanel/events": "^0.290.0",
27
27
  "@chatpanel/pii": "^0.12.0",
28
28
  "@huggingface/transformers": "^4.2.0",
29
29
  "defuddle": "^0.19.4",
@@ -0,0 +1,6 @@
1
+ import{randomUUID as m}from"node:crypto";import{BROWSER_RELAY as y,createBrowserRelay as b,validateBrowserCall as h,validateBrowserAnnounce as v,validateBrowserResult as p}from"@chatpanel/events/browser-relay.js";const k=25e3,_={not_connected:409,busy:409,disconnected:409,reconnected:409,timeout:504},i=(l,n=400,r="invalid_request")=>({status:n,body:{error:{message:`browser: ${l}`,type:r}}});function B({version:l=""}={}){const n=b({newId:m}),r=new Map,d=(o,e,t)=>o.write(`event: ${e}
2
+ data: ${JSON.stringify(t)}
3
+
4
+ `),f=setInterval(()=>{for(const[o,e]of r)try{e.write(`: ping
5
+
6
+ `)}catch{r.delete(o),n.disconnect(o)}},k);return f.unref?.(),{stream(o,e){e.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-accel-buffering":"no"});const t=n.connect((s,c)=>d(e,s,c));for(const[s,c]of r)if(s!==t){r.delete(s);try{c.end()}catch{}}r.set(t,e),d(e,"hello",{session:t,version:l}),o.on("close",()=>{r.get(t)===e&&r.delete(t),n.disconnect(t)})},announce(o){const e=v(o);return e.ok?n.announce(e.announce)?{status:200,body:{ok:!0}}:i("that session is not the connected browser",409,"conflict"):i(e.error)},result(o){const e=p(o);return e.ok?n.answer(e.answer)?{status:200,body:{ok:!0}}:i("no such call waiting for this session",404,"not_found"):i(e.error)},status:()=>n.status(),async call(o,e){const t=h(o);if(!t.ok)return i(t.error);const{id:s,done:c}=n.call(t.call);let u=null;const w=()=>{s&&n.expire(s,t.call.timeoutMs)};s&&(u=setTimeout(()=>n.expire(s,t.call.timeoutMs),t.call.timeoutMs),u.unref?.(),e?.on?.("close",w));const a=await c;return clearTimeout(u),e?.off?.("close",w),a.ok?{status:200,body:{ok:!0,result:a.result}}:{status:_[a.code]||502,body:{error:{message:a.error,type:a.code||"browser_error"}}}},health:()=>({relay:!0,connected:n.status().connected}),close(){clearInterval(f);for(const[o,e]of r){try{e.end()}catch{}n.disconnect(o)}r.clear()}}}export{y as BROWSER_RELAY,B as createBrowserRelayHost};
@@ -1 +1 @@
1
- import{writeFileSync as y,mkdirSync as A,chmodSync as w}from"node:fs";import{join as x,dirname as k}from"node:path";import f from"node:os";import{usage as E}from"./freegate.js";import{applyFusionsPatch as D}from"./fusions.js";import{EMBEDDED_MODELS as S,EMBEDDED_IDS as l,isEmbeddedModel as c}from"./embedded-models.js";import{normalizeRegistries as T,REGISTRY_KINDS as v}from"@chatpanel/events/registries.js";import{assertEndpointUrl as a}from"@chatpanel/pii";import{normalizeGrant as N}from"@chatpanel/bridge/src/events/sandbox-policy.js";const _=["open","allowlist","off"],u=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function d(e={}){const r=e&&typeof e=="object"?e:{},o=_.includes(r.mode)?r.mode:"open",{hosts:i}=N({hosts:r.hosts??[]});return{mode:o,hosts:i,write:u(r.write),denyRead:u(r.denyRead)}}function B(e){const r=d(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function m(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||x(f.homedir(),".chatpanel","gateway.config.json")}function K(e){const r=e?.registries||{},o={};for(const[i,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[i]&&(o[t]=r[i]);return o}function U(e,r=m()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===m({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);A(k(r),{recursive:!0,mode:448});const o={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp};y(r,JSON.stringify(o,null,2),{mode:384});try{w(r,384)}catch{}}function g(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:i,...t}=o;return{...t,hasKey:!!i}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:o,...i}=e.redaction?.detection||{backend:"off"};return i})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:d(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0}},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([o,i])=>{const{token:t,...n}=i||{};return[o,{...n,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:E(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function Y(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function O(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),t=Number(o.port)||(o.protocol==="https:"?443:80);return i&&t===(Number(r.port)||4320)}const b=["default","acceptEdits","bypassPermissions"];function F(e,r={}){const o=e?.bridge||{};return{...b.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function $(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const o=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=r.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const t=O(i,e);return t&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!t}).map(i=>{const t={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(t.agent=i.agent||i.id),i.type==="api"){t.baseUrl=String(i.baseUrl||""),t.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;s&&(t.apiKey=s)}const n=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;return n&&(t.service=n),t})}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),b.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(o=>String(o).trim()).filter(o=>/^[a-p]{32}$/.test(o))),r.upstreams&&typeof r.upstreams=="object")for(const o of["openai","anthropic"]){const i=r.upstreams[o];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:i.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const o=r.redaction;(o.tier==="basic"||o.tier==="full")&&(e.redaction.tier=o.tier),"redactSystem"in o&&(e.redaction.redactSystem=!!o.redactSystem),Array.isArray(o.dictionary)&&(e.redaction.dictionary=o.dictionary),o.detection&&typeof o.detection=="object"&&(e.redaction.detection=o.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=d({...e.sandbox||{},...r.sandbox})),r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const o=String(r.read.remote.url||"").trim();o&&a(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.registries&&typeof r.registries=="object"){const o=T(r.registries),i={...e.registries||{}};for(const t of v)t in r.registries&&(o[t]?i[t]=o[t]:delete i[t]);e.registries=i}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&a(i),e.search.searxng.url=i}typeof o.token=="string"&&(e.search.searxng.token=o.token),typeof o.engines=="string"&&(e.search.searxng.engines=o.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(o.safesearch)&&(e.search.searxng.safesearch=o.safesearch)}["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const o=D(e,r.fusions);if(o){const i=new Error(o);throw i.code="SHAPE",i}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const o of["rerank","decide","stt","tts","detect","embed"]){if(!(o in r.capabilities))continue;const i=r.capabilities[o];if(i===null){delete e.capabilities[o],o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!i||typeof i!="object")continue;const n={...e.capabilities[o]||{}};if(i.provider==="embedded"){if(l.includes(o)&&i.model!=null){if(!c(o,i.model)){const s=new Error(`capabilities.${o}.model must be one of ${S[o].map(p=>p.id).join(", ")}`);throw s.code="SHAPE",s}e.capabilities[o]={provider:"embedded",model:i.model};continue}e.capabilities[o]={provider:"embedded"},o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(i.provider==="none"&&l.includes(o)){e.capabilities[o]={provider:"none"};continue}if("url"in i){const s=String(i.url||"").trim();s&&a(s),n.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(n.adapter=i.adapter),typeof i.model=="string"&&(n.model=i.model.trim()),typeof i.token=="string"&&(n.token=i.token),typeof i.calibrated=="boolean"&&(n.calibrated=i.calibrated),typeof i.redact=="boolean"&&(n.redact=i.redact),!n.url){delete e.capabilities[o];continue}n.provider="remote",delete n.service,e.capabilities[o]=n,o==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}})}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const o=Number(r.tools.maxPerTurn);Number.isFinite(o)&&o>=1&&(e.tools.maxPerTurn=Math.floor(o))}return e}export{b as PERMISSION_MODES,$ as applyConfigPatch,Y as applyNerModelSelection,F as bridgeAgentOptions,m as configPath,O as isSelfDestination,d as normalizeSandboxConfig,U as persistConfig,g as publicConfig,K as registryChildEnv,B as sandboxEnvFor};
1
+ import{writeFileSync as A,mkdirSync as w,chmodSync as k}from"node:fs";import{join as f,dirname as x}from"node:path";import E from"node:os";import{usage as D}from"./freegate.js";import{applyFusionsPatch as c}from"./fusions.js";import{EMBEDDED_MODELS as S,EMBEDDED_IDS as m,isEmbeddedModel as T}from"./embedded-models.js";import{normalizeRegistries as v,REGISTRY_KINDS as N}from"@chatpanel/events/registries.js";import{assertEndpointUrl as d}from"@chatpanel/pii";import{normalizeGrant as _}from"@chatpanel/bridge/src/events/sandbox-policy.js";const O=["open","allowlist","off"],b=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function l(e={}){const r=e&&typeof e=="object"?e:{},o=O.includes(r.mode)?r.mode:"open",{hosts:i}=_({hosts:r.hosts??[]});return{mode:o,hosts:i,write:b(r.write),denyRead:b(r.denyRead)}}function B(e){const r=l(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function p(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||f(E.homedir(),".chatpanel","gateway.config.json")}function U(e){const r=e?.registries||{},o={};for(const[i,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[i]&&(o[t]=r[i]);return o}function K(e,r=p()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===p({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);w(x(r),{recursive:!0,mode:448});const o={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp};A(r,JSON.stringify(o,null,2),{mode:384});try{k(r,384)}catch{}}function Y(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:i,...t}=o;return{...t,hasKey:!!i}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:o,...i}=e.redaction?.detection||{backend:"off"};return i})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:l(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0}},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([o,i])=>{const{token:t,...n}=i||{};return[o,{...n,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:D(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function F(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function R(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),t=Number(o.port)||(o.protocol==="https:"?443:80);return i&&t===(Number(r.port)||4320)}const y=["default","acceptEdits","bypassPermissions"];function $(e,r={}){const o=e?.bridge||{};return{...y.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function q(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const o=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=r.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const t=R(i,e);return t&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!t}).map(i=>{const t={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(t.agent=i.agent||i.id),i.type==="api"){t.baseUrl=String(i.baseUrl||""),t.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;s&&(t.apiKey=s)}const n=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;return n&&(t.service=n),t})}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),y.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(o=>String(o).trim()).filter(o=>/^[a-p]{32}$/.test(o))),r.upstreams&&typeof r.upstreams=="object")for(const o of["openai","anthropic"]){const i=r.upstreams[o];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:i.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const o=r.redaction;(o.tier==="basic"||o.tier==="full")&&(e.redaction.tier=o.tier),"redactSystem"in o&&(e.redaction.redactSystem=!!o.redactSystem),Array.isArray(o.dictionary)&&(e.redaction.dictionary=o.dictionary),o.detection&&typeof o.detection=="object"&&(e.redaction.detection=o.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=l({...e.sandbox||{},...r.sandbox})),r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const o=String(r.read.remote.url||"").trim();o&&d(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.registries&&typeof r.registries=="object"){const o=v(r.registries),i={...e.registries||{}};for(const t of N)t in r.registries&&(o[t]?i[t]=o[t]:delete i[t]);e.registries=i}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&d(i),e.search.searxng.url=i}typeof o.token=="string"&&(e.search.searxng.token=o.token),typeof o.engines=="string"&&(e.search.searxng.engines=o.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(o.safesearch)&&(e.search.searxng.safesearch=o.safesearch)}["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const o=c(e,r.fusions);if(o){const i=new Error(o);throw i.code="SHAPE",i}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const o of["rerank","decide","stt","tts","detect","embed"]){if(!(o in r.capabilities))continue;const i=r.capabilities[o];if(i===null){delete e.capabilities[o],o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!i||typeof i!="object")continue;const t=e.capabilities[o]||{},n={...t};if(i.provider==="embedded"){if(m.includes(o)&&i.model!=null){if(!T(o,i.model)){const s=new Error(`capabilities.${o}.model must be one of ${S[o].map(a=>a.id).join(", ")}`);throw s.code="SHAPE",s}e.capabilities[o]={provider:"embedded",model:i.model};continue}e.capabilities[o]={provider:"embedded"},o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(i.provider==="none"&&m.includes(o)){e.capabilities[o]={provider:"none"};continue}if("url"in i){const s=String(i.url||"").trim();s&&d(s);const a=u=>{try{return new URL(u).origin}catch{return u}};t.url&&s&&a(t.url)!==a(s)&&typeof i.token!="string"&&delete n.token,n.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(n.adapter=i.adapter),typeof i.model=="string"&&(n.model=i.model.trim()),typeof i.token=="string"&&(n.token=i.token),typeof i.calibrated=="boolean"&&(n.calibrated=i.calibrated),typeof i.redact=="boolean"&&(n.redact=i.redact),!n.url){delete e.capabilities[o];continue}n.provider="remote",delete n.service,e.capabilities[o]=n,o==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}})}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const o=Number(r.tools.maxPerTurn);Number.isFinite(o)&&o>=1&&(e.tools.maxPerTurn=Math.floor(o))}return e}export{y as PERMISSION_MODES,q as applyConfigPatch,F as applyNerModelSelection,$ as bridgeAgentOptions,p as configPath,R as isSelfDestination,l as normalizeSandboxConfig,K as persistConfig,Y as publicConfig,U as registryChildEnv,B as sandboxEnvFor};
@@ -1 +1 @@
1
- import{ensureLib as R,modelRoot as P}from"./ner-engine.js";import{join as L}from"node:path";import{existsSync as O,readdirSync as I}from"node:fs";import{makeWarmTimer as z}from"./warm-timer.js";import{DEFAULT_DIARIZE_MODEL as k,diarizeThreshold as W,isKnownDiarizeModel as Z}from"./diarize-models.js";const Q=k;let s="off",c=k,h=null,w=null,g=null,u=null,f=null,a=null,y=0,M=0;function V(){return c}function v(){return W(c)}function D(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function X(){return s}function $(){return s==="ready"&&!!h&&!!w}function Y(){return f}function tt(){return{configured:s!=="off",ok:$(),state:s,model:c,loaded:!!h,threshold:v(),error:g,warmMs:a?.warmMs??null}}function et(){return!!a?.pending()}function rt(){y++,a?.disarm()}function nt(){y=Math.max(0,y-1),y===0&&M===0&&$()&&a?.arm()}function p(){return y>0||M>0||s==="loading"||s==="downloading"}async function b({log:e=()=>{}}={}){if(p())return!1;a?.disarm();const t=h;if(h=null,w=null,u=null,f=null,g=null,s="off",t){try{await t.dispose?.()}catch{}e("[diarize] idle — speaker model unloaded (reloads on the next diarizing session)")}return!0}function j(e=c,t=D()){const r=L(P(),...e.split("/"),"onnx");if(!O(r))return!1;const n=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return I(r).some(i=>i===`model${n}.onnx`)}catch{return!1}}async function T({log:e=()=>{},allowDownload:t=!0}={}){let r;try{r=await R()}catch(o){return s="error",g=o.message,e(`[diarize] engine unavailable (${o.message})`),!1}const n=c,i=j(n);if(r.env.allowRemoteModels=i?!1:!!t,!i&&!t)return s="error",g="model not on disk and downloads disabled",!1;const l=r.env.remoteHost;if(!i)try{r.env.remoteHost="https://huggingface.co/"}catch{}s=i?"loading":"downloading",i||(f={model:n,file:null,pct:0},e(`[diarize] downloading ${n} (one-time)…`));try{const{AutoModel:o,AutoProcessor:d}=r,_=m=>{if(!m)return;const H=typeof m.progress=="number"?Math.round(m.progress):f?.pct??0;(m.status==="progress"||m.status==="download"||m.status==="initiate")&&(f={model:n,file:m.file||f?.file||null,pct:H})},x=await d.from_pretrained(n,{progress_callback:_}),E=await o.from_pretrained(n,{dtype:D(),progress_callback:_});return w=x,h=E,s="ready",g=null,f=null,e(`[diarize] ready — ${n} @ ${D()} (speakers split at cosine ${v()})`),!0}catch(o){return g=o.message,f=null,s="error",e(`[diarize] load failed (${o.message}) — diarization off`),!1}finally{try{r.env.remoteHost=l}catch{}}}function ot(e={}){if(u&&s!=="error")return u;s="loading";const t=typeof e.onLog=="function"?e.onLog:()=>{};return a=z({warmMs:e.warmMs,busy:p,log:t,unload:()=>b({log:t})}),u=F(T({log:t,allowDownload:e.allowDownload!==!1})),u}function F(e){return e.then(t=>(t&&!p()&&a?.arm(),t))}async function lt(e,{log:t=()=>{}}={}){return Z(e)?e===c?!0:p()?!1:(await b({log:()=>{}}),c=e,t(`[diarize] speaker model set to ${e} (loads on the next diarizing session)`),!0):!1}function it({onLog:e}={}){return u=null,s="loading",a??=z({warmMs:void 0,busy:p,log:e||(()=>{}),unload:()=>b({log:e||(()=>{})})}),u=F(T({log:e,allowDownload:!0})),u}const q=16e3;function A(e){let t=0;for(const n of e)t+=n*n;t=Math.sqrt(t)||1;const r=new Float32Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]/t;return r}async function S(e){try{const t=await w(e),r=await h(t),n=r.embeddings??r.logits??r.last_hidden_state;return n?.data?Float32Array.from(n.data):null}catch{return null}}async function st(e){if(!$()||!(e instanceof Float32Array)||!e.length)return null;M++;try{return await C(e)}finally{M--,p()||a?.arm()}}async function C(e){const t=2*q,r=Math.round(1.3*q);if(e.length<=Math.round(t*1.4)){const l=await S(e);return l?A(l):null}const n=[];for(let l=0;l+t<=e.length;l+=r){const o=await S(e.subarray(l,l+t));o&&n.push(A(o))}if(!n.length){const l=await S(e);return l?A(l):null}const i=new Float32Array(n[0].length);for(const l of n)for(let o=0;o<i.length;o++)i[o]+=l[o];return A(i)}function at(){a?.disarm(),a=null,y=0,M=0,s="off",c=k,h=null,w=null,g=null,u=null,f=null}function ut(e,t,{warmMs:r=null}={}){h=e,w=t,s=e?"ready":"off",r!==null&&(a=z({warmMs:r,busy:p,unload:()=>b()}),e&&a.arm())}function K(e,t){let r=0,n=0,i=0;for(let o=0;o<e.length;o++)r+=e[o]*t[o],n+=e[o]*e[o],i+=t[o]*t[o];const l=Math.sqrt(n)*Math.sqrt(i);return l?r/l:0}class ft{constructor({threshold:t=v(),maxSpeakers:r=12}={}){this.threshold=t,this.maxSpeakers=r,this.centroids=[]}assign(t,{pinnedLabel:r=null,weak:n=!1,thin:i=!1}={}){if(!t)return null;if(r)return this._merge(this._find(r)||this._create(r),t);let l=null,o=-1;const d={};for(const _ of this.centroids){const x=K(t,_.vec);d[_.label]=Math.round(x*1e3)/1e3,x>o&&(o=x,l=_)}return n&&l?{...this._merge(l,t,{update:!1}),scores:d,weak:!0}:l&&o>=this.threshold?{...this._merge(l,t),scores:d}:this.centroids.length>=this.maxSpeakers&&l?{...this._merge(l,t),scores:d}:i&&l?{...this._merge(l,t,{update:!1}),scores:d,thin:!0}:{...this._merge(this._create(`Speaker ${this.centroids.length+1}`),t),scores:d,...n?{weak:!0}:{}}}_find(t){return this.centroids.find(r=>r.label===t)||null}_create(t){const r={id:this.centroids.length+1,label:t,vec:null,n:0};return this.centroids.push(r),r}_merge(t,r,{update:n=!0}={}){if(!t.vec)t.vec=Float32Array.from(r),t.n=1;else if(n){for(let i=0;i<t.vec.length;i++)t.vec[i]=(t.vec[i]*t.n+r[i])/(t.n+1);t.n+=1}return{id:t.id,label:t.label}}}export{Q as DIARIZE_MODEL,ft as Diarizer,at as _reset,ut as _setForTest,V as activeModel,v as activeThreshold,it as download,st as embed,tt as health,ot as init,$ as isReady,j as modelOnDisk,Y as progress,nt as release,rt as retain,lt as setModel,X as state,b as unload,et as warmPending};
1
+ import{ensureLib as R,modelRoot as O}from"./ner-engine.js";import{join as P}from"node:path";import{existsSync as q,readdirSync as I}from"node:fs";import{makeWarmTimer as M}from"./warm-timer.js";import{createSpeakerClusterer as C}from"@chatpanel/events/speaker-cluster.js";import{DEFAULT_DIARIZE_MODEL as b,diarizeThreshold as N,isKnownDiarizeModel as W}from"./diarize-models.js";const V=b;let o="off",f=b,d=null,g=null,p=null,u=null,c=null,a=null,w=0,_=0;function X(){return f}function v(){return N(f)}function A(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function Y(){return o}function z(){return o==="ready"&&!!d&&!!g}function tt(){return c}function et(){return{configured:o!=="off",ok:z(),state:o,model:f,loaded:!!d,threshold:v(),error:p,warmMs:a?.warmMs??null}}function nt(){return!!a?.pending()}function rt(){w++,a?.disarm()}function ot(){w=Math.max(0,w-1),w===0&&_===0&&z()&&a?.arm()}function h(){return w>0||_>0||o==="loading"||o==="downloading"}async function y({log:t=()=>{}}={}){if(h())return!1;a?.disarm();const e=d;if(d=null,g=null,u=null,c=null,p=null,o="off",e){try{await e.dispose?.()}catch{}t("[diarize] idle — speaker model unloaded (reloads on the next diarizing session)")}return!0}function Z(t=f,e=A()){const n=P(O(),...t.split("/"),"onnx");if(!q(n))return!1;const r=e==="fp32"?"":e==="q8"?"_quantized":`_${e}`;try{return I(n).some(s=>s===`model${r}.onnx`)}catch{return!1}}async function $({log:t=()=>{},allowDownload:e=!0}={}){let n;try{n=await R()}catch(l){return o="error",p=l.message,t(`[diarize] engine unavailable (${l.message})`),!1}const r=f,s=Z(r);if(n.env.allowRemoteModels=s?!1:!!e,!s&&!e)return o="error",p="model not on disk and downloads disabled",!1;const i=n.env.remoteHost;if(!s)try{n.env.remoteHost="https://huggingface.co/"}catch{}o=s?"loading":"downloading",s||(c={model:r,file:null,pct:0},t(`[diarize] downloading ${r} (one-time)…`));try{const{AutoModel:l,AutoProcessor:E}=n,k=m=>{if(!m)return;const L=typeof m.progress=="number"?Math.round(m.progress):c?.pct??0;(m.status==="progress"||m.status==="download"||m.status==="initiate")&&(c={model:r,file:m.file||c?.file||null,pct:L})},F=await E.from_pretrained(r,{progress_callback:k}),H=await l.from_pretrained(r,{dtype:A(),progress_callback:k});return g=F,d=H,o="ready",p=null,c=null,t(`[diarize] ready — ${r} @ ${A()} (speakers split at cosine ${v()})`),!0}catch(l){return p=l.message,c=null,o="error",t(`[diarize] load failed (${l.message}) — diarization off`),!1}finally{try{n.env.remoteHost=i}catch{}}}function lt(t={}){if(u&&o!=="error")return u;o="loading";const e=typeof t.onLog=="function"?t.onLog:()=>{};return a=M({warmMs:t.warmMs,busy:h,log:e,unload:()=>y({log:e})}),u=T($({log:e,allowDownload:t.allowDownload!==!1})),u}function T(t){return t.then(e=>(e&&!h()&&a?.arm(),e))}async function it(t,{log:e=()=>{}}={}){return W(t)?t===f?!0:h()?!1:(await y({log:()=>{}}),f=t,e(`[diarize] speaker model set to ${t} (loads on the next diarizing session)`),!0):!1}function at({onLog:t}={}){return u=null,o="loading",a??=M({warmMs:void 0,busy:h,log:t||(()=>{}),unload:()=>y({log:t||(()=>{})})}),u=T($({log:t,allowDownload:!0})),u}const S=16e3;function x(t){let e=0;for(const r of t)e+=r*r;e=Math.sqrt(e)||1;const n=new Float32Array(t.length);for(let r=0;r<t.length;r++)n[r]=t[r]/e;return n}async function D(t){try{const e=await g(t),n=await d(e),r=n.embeddings??n.logits??n.last_hidden_state;return r?.data?Float32Array.from(r.data):null}catch{return null}}async function st(t){if(!z()||!(t instanceof Float32Array)||!t.length)return null;_++;try{return await j(t)}finally{_--,h()||a?.arm()}}async function j(t){const e=2*S,n=Math.round(1.3*S);if(t.length<=Math.round(e*1.4)){const i=await D(t);return i?x(i):null}const r=[];for(let i=0;i+e<=t.length;i+=n){const l=await D(t.subarray(i,i+e));l&&r.push(x(l))}if(!r.length){const i=await D(t);return i?x(i):null}const s=new Float32Array(r[0].length);for(const i of r)for(let l=0;l<s.length;l++)s[l]+=i[l];return x(s)}function ut(){a?.disarm(),a=null,w=0,_=0,o="off",f=b,d=null,g=null,p=null,u=null,c=null}function ct(t,e,{warmMs:n=null}={}){d=t,g=e,o=t?"ready":"off",n!==null&&(a=M({warmMs:n,busy:h,unload:()=>y()}),t&&a.arm())}class ft{constructor({threshold:e=v(),maxSpeakers:n=12}={}){this.threshold=e,this.maxSpeakers=n,this._voices=C({threshold:e,maxSpeakers:n})}assign(e,n){return this._voices.assign(e,n)}get centroids(){return this._voices.toJSON().centroids}}export{V as DIARIZE_MODEL,ft as Diarizer,ut as _reset,ct as _setForTest,X as activeModel,v as activeThreshold,at as download,st as embed,et as health,lt as init,z as isReady,Z as modelOnDisk,tt as progress,ot as release,rt as retain,it as setModel,Y as state,y as unload,nt as warmPending};
@@ -1 +1 @@
1
- const o="onnx-community/wespeaker-voxceleb-resnet34-LM",t=[{id:"onnx-community/wespeaker-voxceleb-resnet34-LM",label:"WeSpeaker ResNet34 (recommended)",lang:"any",recommended:!0,approxMB:7,dim:256,threshold:.4,note:"Tells voices apart for meeting transcription (who said what). Small, fast, and the most accurate of the two."},{id:"Xenova/wavlm-base-plus-sv",label:"WavLM Base+ SV (previous default)",lang:"any",approxMB:102,dim:512,threshold:.75,note:"The earlier speaker model. Larger and slower, and it merges similar voices far more often — kept so an existing install can switch back."}];function r(e){return t.find(n=>n.id===e)||null}function a(e){return!!r(e)}function i(e){return(r(e)||r(o)).threshold}function s(e){return r(e)?.approxMB??null}export{o as DEFAULT_DIARIZE_MODEL,t as DIARIZE_MODEL_CATALOG,s as diarizeApproxMB,r as diarizeModelEntry,i as diarizeThreshold,a as isKnownDiarizeModel};
1
+ import{SPEAKER_MODELS as t,DEFAULT_SPEAKER_MODEL as e}from"@chatpanel/events/speaker-cluster.js";const i=e,E=t;function o(r){return E.find(n=>n.id===r)||null}function u(r){return!!o(r)}function d(r){return(o(r)||o(i)).threshold}function A(r){return o(r)?.approxMB??null}export{i as DEFAULT_DIARIZE_MODEL,E as DIARIZE_MODEL_CATALOG,A as diarizeApproxMB,o as diarizeModelEntry,d as diarizeThreshold,u as isKnownDiarizeModel};
package/src/egress.js CHANGED
@@ -1,2 +1,2 @@
1
- import{isBlockedHost as f}from"@chatpanel/pii";const y=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url);return{host:t.hostname,port:t.port||(t.protocol==="https:"?"443":t.protocol==="http:"?"80":""),scheme:t.protocol.replace(":","")}}catch{return null}}const u=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:f(t,{allowLoopback:!1,allowPrivate:!1})&&!f(t,{allowLoopback:!0,allowPrivate:!0})};function v({clock:e=y}={}){const t=new Map;return{record(r){const a=g(r);if(!a||!a.host)return;const h=`${a.scheme}://${a.host}:${a.port}`,c=e(),s=t.get(h);if(s){s.count+=1,s.lastAt=c;return}t.set(h,{host:a.host,port:a.port,scheme:a.scheme,local:u(a.host),count:1,firstAt:c,lastAt:c})},snapshot(){return[...t.values()].sort((r,a)=>r.local===a.local?a.count-r.count:r.local?1:-1)},reset(){t.clear()}}}let w=null;function L(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const r=v();let a=t;r.setGate=c=>{a=c},r.blocked=[];const h=e.fetch;return typeof h=="function"&&(e.fetch=function(s,p){let o=null;try{o=g(s),r.record(s)}catch{}if(a&&o?.host){let i=!0;try{i=a(`${o.scheme}://${o.host}:${o.port}`,{local:u(o.host)})}catch{i=!0}if(!i){const n=`${o.host}:${o.port}`;r.blocked.includes(n)||r.blocked.push(n);const l=new Error(`egress to ${o.host} is blocked by your organisation’s policy`);return l.code="EGRESS_POLICY",Promise.reject(l)}}return h.call(this,s,p)}),e.__chatpanelEgress=r,e===globalThis&&(w=r),r}function $(){return w||(globalThis.__chatpanelEgress??null)}function d(e){try{return new URL(e).host}catch{return String(e||"")}}function k(e={},t=process.env){const r=[],a=(o,i,{when:n="always",off:l=null,local:m=!1,data:b=""}={})=>{o&&r.push({host:o,purpose:i,when:n,off:l,local:m,data:b})};a("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),a("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),a("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),t.CHATPANEL_ORT_DIR||a("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),a("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const h=e.search?.searxng?.url||"";if(h){let o=h;try{o=new URL(h).host}catch{}a(o,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(o)})}if(e.search?.provider!=="searxng"&&(a("www.startpage.com","web search: the built-in results-page search, first engine",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),a("html.duckduckgo.com","web search: the built-in results-page search, fallback engine",{when:"Startpage returned nothing",off:"the same switch as www.startpage.com",data:"the same query"})),e.read?.remote?.url){let o=e.read.remote.url;try{o=new URL(e.read.remote.url).host}catch{}a(o,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(o)})}const c={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[o,i]of Object.entries(c)){const n=e.capabilities?.[o];if(!n?.url||n.provider==="embedded")continue;let l=n.url;try{l=new URL(n.url).host}catch{}a(l,`${i.what}${n.service?` (the ${n.service} container, started under Settings › Runtime)`:` (${n.adapter} at the address you configured)`}`,{when:`a client calls /v1/${o}`,off:n.service?`stop the ${n.service} service under Settings › Runtime`:`capabilities.${o} = null`,data:`${i.data}${n.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(l)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(a("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),a("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[o,i]of Object.entries(e.upstreams||{}))i?.baseUrl&&a(d(i.baseUrl),`model upstream "${o}" — chat requests (after redaction) go here`,{when:`a request addressed to ${o}`,off:`upstreams.${o}.baseUrl`,local:u(d(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const o of e.destinations||[])o?.baseUrl&&a(d(o.baseUrl),`destination "${o.id||o.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${o.id||"it"}`,off:"destinations[]",local:u(d(o.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});a("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&a(d(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:u(d(e.ner.url).split(":")[0]),data:"the text being redacted"});const s=e.tts||{};if(s.provider==="openai"||s.provider==="elevenlabs"){const o=s.remote?.baseUrl?d(s.remote.baseUrl):s.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";a(o,`remote read-aloud voice (${s.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:s.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}const p=e.bridge?.url||"http://127.0.0.1:4319";return a(d(p),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),r}function x(e,{ledger:t=$(),version:r="",startedAt:a=null,env:h=process.env,managed:c=null}={}){return{ok:!0,version:r,since:a?new Date(a).toISOString():null,...c?{managed:c,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:k(e,h)}}function S(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const r of e.observed||[])t.push(` ${r.local?"[local] ":""}${r.scheme}://${r.host}:${r.port} ×${r.count} last ${r.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const r of e.declared||[])t.push(` ${r.local?"[local] ":""}${r.host}`),t.push(` ${r.purpose}`),t.push(` when: ${r.when}${r.off?` · off: ${r.off}`:""}`),r.data&&t.push(` sends: ${r.data}`);return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,r])=>r).map(([r,a])=>a===!0?r:`${r}=${a}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
2
- `)}export{v as createEgressLedger,k as declaredEgress,x as egressAudit,$ as egressLedger,S as formatAudit,L as installEgressLedger};
1
+ import{isBlockedHost as f}from"@chatpanel/pii";const b=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url);return{host:t.hostname,port:t.port||(t.protocol==="https:"?"443":t.protocol==="http:"?"80":""),scheme:t.protocol.replace(":","")}}catch{return null}}const u=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:f(t,{allowLoopback:!1,allowPrivate:!1})&&!f(t,{allowLoopback:!0,allowPrivate:!0})};function v({clock:e=b}={}){const t=new Map;return{record(r){const a=g(r);if(!a||!a.host)return;const h=`${a.scheme}://${a.host}:${a.port}`,l=e(),s=t.get(h);if(s){s.count+=1,s.lastAt=l;return}t.set(h,{host:a.host,port:a.port,scheme:a.scheme,local:u(a.host),count:1,firstAt:l,lastAt:l})},snapshot(){return[...t.values()].sort((r,a)=>r.local===a.local?a.count-r.count:r.local?1:-1)},reset(){t.clear()}}}let w=null;function E(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const r=v();let a=t;r.setGate=l=>{a=l},r.blocked=[];const h=e.fetch;return typeof h=="function"&&(e.fetch=function(s,p){let o=null;try{o=g(s),r.record(s)}catch{}if(a&&o?.host){let i=!0;try{i=a(`${o.scheme}://${o.host}:${o.port}`,{local:u(o.host)})}catch{i=!0}if(!i){const n=`${o.host}:${o.port}`;r.blocked.includes(n)||r.blocked.push(n);const c=new Error(`egress to ${o.host} is blocked by your organisation’s policy`);return c.code="EGRESS_POLICY",Promise.reject(c)}}return h.call(this,s,p)}),e.__chatpanelEgress=r,e===globalThis&&(w=r),r}function k(){return w||(globalThis.__chatpanelEgress??null)}function d(e){try{return new URL(e).host}catch{return String(e||"")}}function $(e={},t=process.env){const r=[],a=(o,i,{when:n="always",off:c=null,local:m=!1,data:y=""}={})=>{o&&r.push({host:o,purpose:i,when:n,off:c,local:m,data:y})};if(a("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),a("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),a("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),t.CHATPANEL_ORT_DIR||a("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),e.link?.enabled!==!1){let o="link.chatpanel.net";try{e.link?.relayUrl&&(o=new URL(e.link.relayUrl).host)}catch{}a(o,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone is paired (Settings › Link your phone), and while pairing",off:"link.enabled = false, or remove every paired phone",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}a("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const h=e.search?.searxng?.url||"";if(h){let o=h;try{o=new URL(h).host}catch{}a(o,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(o)})}if(e.search?.provider!=="searxng"&&(a("www.startpage.com","web search: the built-in results-page search, first engine",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),a("html.duckduckgo.com","web search: the built-in results-page search, fallback engine",{when:"Startpage returned nothing",off:"the same switch as www.startpage.com",data:"the same query"})),e.read?.remote?.url){let o=e.read.remote.url;try{o=new URL(e.read.remote.url).host}catch{}a(o,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(o)})}const l={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[o,i]of Object.entries(l)){const n=e.capabilities?.[o];if(!n?.url||n.provider==="embedded")continue;let c=n.url;try{c=new URL(n.url).host}catch{}a(c,`${i.what}${n.service?` (the ${n.service} container, started under Settings › Runtime)`:` (${n.adapter} at the address you configured)`}`,{when:`a client calls /v1/${o}`,off:n.service?`stop the ${n.service} service under Settings › Runtime`:`capabilities.${o} = null`,data:`${i.data}${n.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(c)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(a("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),a("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[o,i]of Object.entries(e.upstreams||{}))i?.baseUrl&&a(d(i.baseUrl),`model upstream "${o}" — chat requests (after redaction) go here`,{when:`a request addressed to ${o}`,off:`upstreams.${o}.baseUrl`,local:u(d(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const o of e.destinations||[])o?.baseUrl&&a(d(o.baseUrl),`destination "${o.id||o.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${o.id||"it"}`,off:"destinations[]",local:u(d(o.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});a("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&a(d(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:u(d(e.ner.url).split(":")[0]),data:"the text being redacted"});const s=e.tts||{};if(s.provider==="openai"||s.provider==="elevenlabs"){const o=s.remote?.baseUrl?d(s.remote.baseUrl):s.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";a(o,`remote read-aloud voice (${s.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:s.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}const p=e.bridge?.url||"http://127.0.0.1:4319";return a(d(p),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),r}function x(e,{ledger:t=k(),version:r="",startedAt:a=null,env:h=process.env,managed:l=null}={}){return{ok:!0,version:r,since:a?new Date(a).toISOString():null,...l?{managed:l,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:$(e,h)}}function S(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const r of e.observed||[])t.push(` ${r.local?"[local] ":""}${r.scheme}://${r.host}:${r.port} ×${r.count} last ${r.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const r of e.declared||[])t.push(` ${r.local?"[local] ":""}${r.host}`),t.push(` ${r.purpose}`),t.push(` when: ${r.when}${r.off?` · off: ${r.off}`:""}`),r.data&&t.push(` sends: ${r.data}`);return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,r])=>r).map(([r,a])=>a===!0?r:`${r}=${a}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
2
+ `)}export{v as createEgressLedger,$ as declaredEgress,x as egressAudit,k as egressLedger,S as formatAudit,E as installEgressLedger};
@@ -0,0 +1 @@
1
+ import{readFileSync as z,writeFileSync as G,renameSync as H,mkdirSync as Y,chmodSync as W}from"node:fs";import{dirname as Q,join as X}from"node:path";import I from"node:os";import{createLinkEndpoint as Z}from"@chatpanel/events/link-connect.js";import{noiseCrypto as q}from"@chatpanel/events/link-noise.js";import{pairingUri as ee,admissionToken as B,admissionVerifier as F,toB64url as v,fromB64url as O}from"@chatpanel/events/link-protocol.js";import{qrSvg as te}from"@chatpanel/events/qr.js";const ne="https://link.chatpanel.net",R=10*6e4,oe=3e4,N=[1e3,2e3,5e3,1e4,3e4,6e4],re=40,ae=16e3,se=[/^\/v1\/models(?:\/|$|\?)/,/^\/v1\/chat\/completions$/,/^\/v1\/messages$/,/^\/v1\/audio\/(?:transcriptions|speech)$/,/^\/v1\/history\/(?:search|smart-search|get|list|related|status)(?:$|\?)/,/^\/v1\/memory\/(?:recall|list|remember)(?:$|\?)/,/^\/v1\/(?:research|search|read|rerank|decide|capabilities|fusions)(?:$|\?)/,/^\/v1\/status$/],ie=p=>se.some(m=>m.test(String(p||"")));function ce(){return X(I.homedir(),".chatpanel","link.json")}function le(p){try{const m=JSON.parse(z(p,"utf8"));return{v:1,key:m.key||null,rooms:Array.isArray(m.rooms)?m.rooms:[]}}catch{return{v:1,key:null,rooms:[]}}}function D(p,m){Y(Q(p),{recursive:!0});const k=`${p}.tmp`;G(k,JSON.stringify(m,null,2),{mode:384});try{W(k,384)}catch{}H(k,p)}function ke({relay:p=ne,name:m=I.hostname(),dispatch:k,path:E=ce(),fetch:j=globalThis.fetch,WebSocket:J=globalThis.WebSocket,now:y=()=>Date.now(),random:U=d=>globalThis.crypto.getRandomValues(new Uint8Array(d)),crypto:A=q(),log:$=()=>{}}={}){const d=new URL(p).origin;if(!/^https:/.test(d)&&!/^http:\/\/127\.0\.0\.1(?::\d+)?$/.test(d))throw new Error("link: the relay must be https");let c=le(E);const u=new Map;let f=null;async function T(){return f||(c.key?f=await A.keyPairFromPrivate(O(c.key)):(f=await A.generateKeyPair(),c.key=v(f.raw),D(E,c)),f)}const b=e=>c.rooms.find(t=>t.room===e)||null,K=()=>D(E,c),_=async(e,t,o,r)=>{try{return await j(`${d}/v1/room/${e}`,{method:t,headers:{authorization:`Bearer ${o}`,...r?{"content-type":"application/json"}:{}},body:r?JSON.stringify(r):void 0})}catch(s){const a=s?.cause?.code||"",n=a==="ENOTFOUND"?"this computer cannot look up its name (a VPN or DNS that does not know it yet)":a?`${a}`:s?.message||"no answer";throw new Error(`cannot reach the Link relay at ${new URL(d).host}: ${n}`)}};async function V(e,t,o){if(!ie(t.path))return await o.head(403,{"content-type":"application/json"}),await o.write(JSON.stringify({error:{message:"link: a paired phone may not call this",type:"forbidden"}})),o.end();const r=t.method==="GET"?void 0:await t.body.bytes(),s=await k({method:t.method,path:t.path,headers:t.headers,body:r,device:e.room}),a={};if(s.headers?.forEach?.((n,i)=>{a[i]=n}),await o.head(s.status,a),s.body){let n=[],i=0,g=y();const w=async()=>{if(!i)return;const h=new Uint8Array(i);let l=0;for(const S of n)h.set(S,l),l+=S.length;n=[],i=0,g=y(),await o.write(h)};for await(const h of s.body){if(o.cancelled)break;const l=h instanceof Uint8Array?h:new TextEncoder().encode(String(h));n.push(l),i+=l.length,(i>=ae||y()-g>=re)&&await w()}await w()}return o.end()}async function x(e){const t=u.get(e.room)||{attempts:0,stopped:!1,online:!1};if(u.set(e.room,t),t.stopped)return;const o=await T(),r=e.pending&&e.pending.expiresAt>y()?e.pending:null;if(!e.phoneKey&&!r){L(e.room,"the pairing code expired");return}const s=`${d.replace(/^http/,"ws")}/v1/room/${e.room}`;let a;try{a=new J(s,["chatpanel-link.v1",e.token])}catch(n){M(e,n?.message);return}a.binaryType="arraybuffer",t.ws=a,t.endpoint=Z({side:"laptop",keyPair:o,crypto:A,psk:e.phoneKey?null:O(r.psk),peerKey:e.phoneKey?O(e.phoneKey):null,sendBytes:n=>{try{a.send(n)}catch{}},onRequest:(n,i)=>V(e,n,i),onSession:(n,i)=>{t.online=!0,t.attempts=0,e.lastSeen=y(),i.paired&&(e.phoneKey=v(i.peerKey),e.name=i.name||e.name||"Phone",e.pairedAt=y(),e.pending=null,$(`link: paired ${e.name}`)),K()},onEnd:()=>{t.online=!1}}),a.onopen=()=>{if(t.stopped||u.get(e.room)!==t){try{a.close(1e3,"stopped")}catch{}return}clearInterval(t.keepalive),t.keepalive=setInterval(()=>{try{a.send("ping")}catch{}},oe),t.keepalive.unref?.()},a.onmessage=n=>typeof n.data=="string"?t.endpoint.onText(n.data):t.endpoint.onBinary(new Uint8Array(n.data)),a.onclose=n=>{if(clearInterval(t.keepalive),t.online=!1,t.endpoint?.close("socket closed"),!t.stopped){if(n?.code===4003||n?.code===4004){P(e.room,"the relay removed the room");return}M(e,n?.code===4001?"replaced":`closed ${n?.code||""}`,n?.code===4001?5:null)}},a.onerror=()=>{}}function M(e,t,o=null){const r=u.get(e.room);if(!r||r.stopped)return;const s=o??Math.min(r.attempts,N.length-1);r.attempts++,clearTimeout(r.timer),r.timer=setTimeout(()=>x(e),N[s]),r.timer.unref?.(),$(`link: ${t}; again in ${N[s]/1e3}s`)}function C(e){const t=u.get(e);if(t){t.stopped=!0,clearTimeout(t.timer),clearInterval(t.keepalive),t.endpoint?.close("stopped");try{t.ws?.close(1e3,"stopped")}catch{}u.delete(e)}}function L(e,t){const o=b(e);o&&!o.phoneKey&&_(e,"DELETE",o.token).catch(()=>{}),P(e,t)}function P(e,t){C(e),c.rooms=c.rooms.filter(o=>o.room!==e),K(),$(`link: ${t}`)}return{async pair({name:e=m}={}){const t=await T(),o=U(16),r=U(32),s=v(o),a=await B(r,o,"laptop"),n=await B(r,o,"phone"),i=await _(s,"PUT",a,{laptop:await F(a),phone:await F(n)});if(i.status!==200&&i.status!==201)throw new Error(`link: the relay refused the room (${i.status})`);for(const l of c.rooms.filter(S=>!S.phoneKey))L(l.room,"a new pairing code replaced this one");const g=y()+R,w={room:s,token:a,phoneKey:null,name:"",pairedAt:null,lastSeen:null,pending:{psk:v(r),expiresAt:g}};c.rooms.push(w),K();const h=ee({relay:d,room:o,key:t.publicKey,secret:r,name:String(e||"").slice(0,60)});return x(w),setTimeout(()=>{const l=b(s);l&&!l.phoneKey&&L(s,"the pairing code expired")},R+1e3).unref?.(),{uri:h,svg:te(h,{ecc:"M"}),expiresAt:g,room:s}},status(){return{relay:d,devices:c.rooms.filter(e=>e.phoneKey).map(e=>({id:e.room,name:e.name||"Phone",pairedAt:e.pairedAt,lastSeen:e.lastSeen,online:!!u.get(e.room)?.online})),pairing:c.rooms.filter(e=>!e.phoneKey&&e.pending?.expiresAt>y()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,connected:!!u.get(e.room)?.online}))[0]||null}},async remove(e){const t=b(e);if(!t)return!1;try{await _(e,"DELETE",t.token)}catch{}return P(e,"removed"),!0},async start(){if(c.rooms.length){await T();for(const e of c.rooms)x(e)}},stop(){for(const e of[...u.keys()])C(e)},get publicKey(){return f?.publicKey||null}}}export{se as COMPANION_PATHS,ne as DEFAULT_RELAY,R as PAIRING_TTL_MS,ie as companionMay,ke as createLinkHost,ce as defaultLinkPath};
package/src/mcp.js CHANGED
@@ -1,42 +1,46 @@
1
- import{loadConfig as y}from"./config.js";import{VERSION as g}from"./version.js";import{readBridgeToken as x}from"./bridge.js";import{ensureGatewayToken as b}from"./gateway-token.js";import{MEMORY_KINDS as j,MEMORY_KIND_NAMES as _}from"./memory.js";import{parseBriefText as A}from"./knowledge.js";import{capabilityToolsProvider as q,DECIDE_TOOL_NAME as I,RERANK_TOOL_NAME as L}from"./capability-tools.js";import{webSearchToolProvider as M}from"./web-search-tool.js";import{SEARCH_DEFAULTS as D}from"./retrieval/search.js";import{askToolsFor as T,callAsk as U}from"./mcp-ask.js";import{CAPABILITY_TOOLS as B,callCapability as H}from"./mcp-capabilities.js";const Y="2024-11-05",F={name:"chatpanel-history",version:g},W=["ChatPanel holds the USER'S OWN meetings, notes and past chats — transcripts, decisions,","action items, summaries — which usually are NOT in the working directory.","","Keep using all your normal tools. ADDITIONALLY, whenever the user's question touches a",'meeting, call, demo, note, or past conversation ("outcome of the meeting", "what did we','decide", "action items", "notes from yesterday", a person/day/topic in their history),',"ALSO consult ChatPanel — it is the source of truth for that personal history:"," • smart_search — START HERE: give it the question plus 2-4 of your own keyword"," phrasings; it runs them all and fuses the rankings, finding what one query misses."," • search_history — one exact keyword query, when you already know the terms. Search by"," CONTENT (not the generic meeting title). Supports filters:",' type (chat|meeting|note), since/before (dates or relative like "7d", "yesterday"),'," and limit/offset paging. Returns compact snippets, not full bodies."," • get_record — the full text of one result id; use maxChars/offset to page a long"," transcript instead of pulling it all into context."," • find_related — follow the graph: given a record id, the records most connected to it.","","ChatPanel also holds the user's MEMORY — a short list of durable facts about them (their","name, how they want answers written, what they are working on) that applies to EVERY task,","not just ones about their history:"," • recall — call it EARLY in a session, and whenever the user states a preference, to see"," what is already known. Then simply follow it; do not tell them you looked.",' • remember — save a new durable fact when they state one ("call me Alex", "always use',' pnpm"). One short sentence. Not for task details or anything true only today.'," • forget — remove one when they say it no longer holds.","Prefer these for the user's history and combine them with your other tools as you see fit.","Every result states how fresh the local copy is; if something recent is missing it may not","have synced yet — say so rather than concluding it does not exist.","","ChatPanel also runs SMALL LOCAL MODELS and a private web search on this machine:"," • decide — a sentiment, tone, urgency, spam/complaint, yes/no or pick-one judgement over"," text you already hold, answered with a probability per option in milliseconds. Call it"," instead of judging the text yourself."," • rerank — order many candidates (search hits, comments, sections) by relevance to a"," question, best first with a score, instead of reading them all."," • web_search — the user's own search (their SearXNG when one runs here), results with"," the top pages already read. Nothing leaves this machine but the query."," • redact_check — what is personal or secret in a piece of text, found by the detector on"," THIS machine. Call it before you put someone else's data into your own context, a"," commit message, an issue or a message to a third party — and whenever the user asks"," what is sensitive in something. It tells you what it could not see, so read that line."," • read_document — a URL as clean markdown through the user's own reader and cache,"," for a fraction of the context raw HTML would cost.","","ChatPanel can also hand a question to ANOTHER MODEL on this machine and give you its answer:"," • list_models — what can answer, and WHERE each one runs (on this device / a cloud)."," • ask_model — ask one. Use it for a second opinion on your own reasoning, for a model",' stronger in some domain, when the user names a model ("ask Claude what it thinks"), or'," when they want a question kept on-device — pick a `device` model and nothing leaves the"," machine. The model you ask sees your prompt and NOTHING else: no files, no shell, no web."," So paste in the code or context it needs. A slow answer returns a job id for ask_status."].join(`
2
- `);async function z(){try{const t=await fetch(`${f()}/health`,{signal:AbortSignal.timeout(600)}),e=String((await t.json())?.version||"");return!e||e===g?"":["",`IMPORTANT — VERSION MISMATCH. This MCP server is ChatPanel ${g}, but the gateway`,`running on this machine is ${e}. They are different installs: your client launched`,"whichever `chatpanel-gateway` is on its PATH, and it is not the one the user is running.","The practical effect is that TOOLS MAY BE MISSING here — a newer gateway has tools this","server does not advertise. If a ChatPanel tool the user expects is not in your list, this","is why. Tell them, and tell them the fix: point the MCP config at the newer executable","(or update the older install so both are the same version)."].join(`
3
- `)}catch{return""}}function k(){try{return y().mcp?.ask||{}}catch{return{}}}let m="unknown";function C(t){try{const e=b();fetch(`${f()}/v1/observability/access`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(t)}).catch(()=>{})}catch{}}function f(){const t=process.env.CHATPANEL_GATEWAY_URL;if(t)return t.replace(/\/+$/,"");let e=4320;try{e=y().port||4320}catch{}return`http://127.0.0.1:${e}`}function O(){try{return String(y().bridge?.url||"http://127.0.0.1:4319").replace(/\/+$/,"")}catch{return"http://127.0.0.1:4319"}}function J(){try{return x(y().bridge?.token||"")}catch{return x("")}}async function S(t){const e=J(),i=await fetch(O()+t,{headers:{Accept:"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}),a=await i.json().catch(()=>({}));if(!i.ok||a.ok===!1)throw new Error(a?.error||`bridge ${i.status}`);return a}const G=[{name:"smart_search",description:'BEST first choice for a question about the user\'s ChatPanel history (meetings, notes, past chats). Ask it a natural-language QUESTION and it expands that into several complementary keyword queries, runs them all, and fuses the rankings — which finds things a single query misses, in one round trip instead of several probes. You know the domain, so pass 2-4 of your own phrasings in `queries` too (e.g. for "what did we decide in the Ben demo": ["Ben demo decisions", "tooling demo action items", "demo outcome next steps"]). Supports the same filters as search_history (type, since, before) and returns snippets with each result\'s id; follow up with get_record for the full text or find_related to expand around a hit. BRIEFS come first when they match: a brief is a maintained page about one person, project or topic, derived from ALL the records that mention it, with every claim citing its record — so for "what do we know about X" read the brief, then open only the records it cites.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in natural language."},queries:{type:"array",items:{type:"string"},description:"Your own 2-4 keyword formulations of it — these lead the search."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a window like "7d"/"yesterday".'},before:{type:"string",description:"Latest date: a date or window like `since`."},limit:{type:"number",description:"Max fused results (default 10)."}},required:["question"]}},{name:"search_history",description:'Search the user\'s ChatPanel history — their past chats, meeting/call transcripts, and notes — by keyword relevance. Consult this (in ADDITION to your other tools) whenever the question touches a meeting, call, demo, note, or past conversation: "outcome of the meeting", "what did we decide", "action items", "what did <person> say", "notes from yesterday". Filters: `type` (chat|meeting|note), `since`/`before` (a date like 2026-08-01 or a relative window like "7d"/"yesterday"), and `limit`/`offset` for paging. Returns compact SNIPPETS (the matching excerpt) with each record\'s id/title/type/date — token-friendly; call get_record for the full text and find_related to follow connections. This is a LOCAL WARM COPY that syncs from ChatPanel; very recent items may not be here yet — results report how current the index is, so if something is missing it likely has not synced. Meeting titles are often generic ("Zoom Meeting"), so search by CONTENT, not the title.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Content keywords (topics, names, decisions) — not the meeting title."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a relative window like "7d", "2 weeks", "yesterday".'},before:{type:"string",description:"Latest date: a date or relative window like `since`."},limit:{type:"number",description:"Max results (default 10)."},offset:{type:"number",description:"Skip N results for paging (default 0)."}},required:["query"]}},{name:"get_record",description:"Fetch one history record's full text by id (chat:<id>, meeting:<id>, note:<id> from search_history). For a long transcript, page it with maxChars + offset instead of pulling it all into context — the result says how many chars remain.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Record id such as chat:abc, meeting:imp_123, or note:xyz."},maxChars:{type:"number",description:"Return at most this many characters (token management for long transcripts)."},offset:{type:"number",description:"Start at this character offset — page through with the offset the previous call reports."}},required:["id"]}},{name:"find_related",description:"Graph navigation: given a record id (from search_history), return the records most connected to it by shared content — the meetings/notes/chats about the same topic, people or thread. Use it to expand from one hit to the surrounding context instead of re-searching.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The record id to find neighbours of."},limit:{type:"number",description:"Max related records (default 5)."}},required:["id"]}},{name:"list_history",description:"List history records (newest first) with their id, title, type and date — no bodies. Reports how current this warm copy is (its newest record). Use to see the index horizon and browse/page the corpus.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max items (default 50)."},offset:{type:"number",description:"Skip N items for paging (default 0)."}}}},{name:"list_briefs",description:`The BRIEFS ChatPanel maintains — one page per person, project or topic that appears across enough records, each claim citing the record it came from. This is the index of what the user's corpus KNOWS, as opposed to what it merely contains: read it before asking "what do we know about X", then get_brief for the one you need. Briefs are rebuilt from the records, so they are as current as the last rebuild (dates shown).`,inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max briefs (default 50)."},offset:{type:"number",description:"Skip N for paging (default 0)."}}}},{name:"get_brief",description:"One brief as STRUCTURE: the subject, its other spellings, and each claim with the record ids it cites — so you can cite the record rather than the synthesis, and open only what you need with get_record. Prefer this over get_record for a brief:… id; get_record returns the same text as prose.",inputSchema:{type:"object",properties:{id:{type:"string",description:"A brief id (brief:…) from list_briefs or search results."}},required:["id"]}},{name:"recall",description:"What ChatPanel already knows about the USER — their name, how they want answers written, their ongoing work and environment. Short and cheap; call it at the START of a session and whenever the user states a preference, then just FOLLOW what it returns without announcing that you checked. Pass the current task in `text` and it also returns the facts relevant to that task, not only the always-on ones. This is memory, not history: for what was said in a meeting or a past chat use smart_search instead.",inputSchema:{type:"object",properties:{text:{type:"string",description:"What the user is asking about right now, so task-relevant facts come back too. Omit for just the always-on ones."}}}},{name:"remember",description:`Save a durable fact about the USER to ChatPanel, carried into every future session on every model and agent — the side panel, other CLIs, everything. Use it the moment they state a standing preference ("always use pnpm"), an identity fact ("call me Alex") or a constraint that will still be true next week. Do NOT use it for task details, anything obvious from the current work, or notes about a codebase — those belong in the repo. One short self-contained sentence, written in the third person. Saving is a change to the user's own data, so say in a short clause what you saved.`,inputSchema:{type:"object",properties:{text:{type:"string",description:'The fact, one short sentence in the third person ("Prefers pnpm over npm"). Max 280 characters.'},kind:{type:"string",enum:_,description:_.map(t=>`${t}: ${j[t].hint}`).join(" ")},tags:{type:"array",items:{type:"string"},description:"Optional short tags for grouping."}},required:["text"]}},{name:"forget",description:'Remove a memory from ChatPanel when the user says it no longer holds. Name it however they did ("the Frankfurt thing") or pass the id from recall — it matches on meaning, and tells you exactly what it removed.',inputSchema:{type:"object",properties:{query:{type:"string",description:"The memory to remove: its text, roughly how the user named it, or its id."}},required:["query"]}},{name:"list_skills",description:"List the reusable skills installed on this machine (via the ChatPanel bridge) — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes) and any configured folder. Returns each skill's name and one-line description. Call open_skill to load the one that fits the task.",inputSchema:{type:"object",properties:{}}},{name:"open_skill",description:"Load one skill's full instructions by name (from list_skills), then follow them. If the instructions point at reference files, read one with read_skill_file.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name from list_skills."}},required:["name"]}},{name:"read_skill_file",description:"Read one reference file a skill's instructions point at (any path inside the skill's own folder). Use only when the task needs it.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name."},path:{type:"string",description:"The reference path as written in the instructions, e.g. references/auth.md."}},required:["name","path"]}}],N={[I]:" The gateway decides in-process unless it was turned off: ChatPanel › Settings › Runtime › Decide (or the OpenDecision container, or a server that provides `decide` under Models).",[L]:" The gateway reranks in-process unless it was turned off: ChatPanel › Settings › Runtime › Rerank (or the Reranker container, or a server that provides `rerank` under Models)."};function R(){const t=f(),e=c=>[{id:"gateway",name:"the gateway",url:`${t}${c}`,where:"this device"}],i=q({providers:{decide:e("/v1/decide"),rerank:e("/v1/rerank")},fetch:(c,o)=>fetch(c,o)}),a=M({search:async c=>{const o=await l("/v1/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({q:c,limit:8,read:D.aliasRead})});return{query:c,engines:o.engines||[],results:(o.results||[]).map((n,r)=>({rank:r+1,title:n.title||n.url,url:n.url,engine:n.engine||"",text:n.read?.markdown||n.read?.text||n.snippet||""}))}}});return[i,a]}const V=R().flatMap(t=>t.specs.map(e=>({name:e.name,description:e.description,inputSchema:e.parameters})));async function K(t,e){const i=R().find(o=>o.specs.some(n=>n.name===t));if(!i)return null;const a=await i.execute(t,e);let c=typeof a=="string"?a:String(a?.text??a);return N[t]&&/^No (decision model|reranker) answered/.test(c)&&(c+=N[t]),c}function $(t,e){if(!t)return`Index: ${e} records (warm copy synced from ChatPanel).`;const i=new Date(t),a=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(i.getDate()).padStart(2,"0")} ${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}`;return`Index: ${e} records, current through ${a} (local warm copy — items newer than this may not have synced from ChatPanel yet).`}function E(){try{const t=b();return t?{Authorization:`Bearer ${t}`}:{}}catch{return{}}}async function l(t,e){let i;try{i=await fetch(f()+t,e)}catch(c){throw new Error(`the ChatPanel gateway is not running at ${f()} — start it with "chatpanel-gateway --install" (or run "chatpanel-gateway"), then retry. [${c.message}]`)}const a=await i.json().catch(()=>({}));if(!i.ok)throw new Error(a?.error?.message||`the gateway returned HTTP ${i.status} for ${t}`);return a}function w(t){if(t==null||t==="")return null;if(typeof t=="number")return t;const e=String(t).trim().toLowerCase(),i=864e5;if(e==="today")return Date.now()-i;if(e==="yesterday")return Date.now()-2*i;const a=/^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(e);if(a){const o=Number(a[1]),n=a[2][0],r=n==="d"?i:n==="w"?7*i:n==="m"?30*i:365*i;return Date.now()-o*r}const c=Date.parse(e);return Number.isNaN(c)?null:c}const v=(t,e)=>`${e+1}. [${t.id}] ${t.title||"(untitled)"} · ${t.type}${t.date?" · "+new Date(t.date).toISOString().slice(0,10):""}${t.snippet?`
4
- ${t.snippet}`:""}`;async function X(t,e={}){const i=await K(t,e);if(i!=null)return i;const a=await H(t,e,{gatewayJson:l});if(a!=null)return a;const c=await U(t,e,{baseUrl:f,gatewayJson:l,token:()=>{try{return b()}catch{return""}},client:()=>m,askConfig:k});if(c!=null)return c;if(t==="smart_search"){const o={question:String(e.question||""),queries:Array.isArray(e.queries)?e.queries.map(String):[],limit:Number(e.limit)||10};e.type&&(o.type=String(e.type));const n=w(e.since);n!=null&&(o.since=n);const r=w(e.before);r!=null&&(o.before=r);const s=await l("/v1/history/smart-search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),h=s.results||[],d=$(s.newest,s.size),u=(s.queries||[]).map(p=>`"${p}"`).join(", ");return h.length?[d,"",`${h.length} result(s) for "${e.question}" — searched ${s.queries.length} way(s): ${u}`,...h.map((p,P)=>`${v(p,P)}${p.foundBy?.length>1?`
1
+ import{loadConfig as y}from"./config.js";import{VERSION as b}from"./version.js";import{readBridgeToken as x}from"./bridge.js";import{ensureGatewayToken as k}from"./gateway-token.js";import{MEMORY_KINDS as R,MEMORY_KIND_NAMES as _}from"./memory.js";import{parseBriefText as P}from"./knowledge.js";import{capabilityToolsProvider as A,DECIDE_TOOL_NAME as I,RERANK_TOOL_NAME as L}from"./capability-tools.js";import{webSearchToolProvider as M}from"./web-search-tool.js";import{SEARCH_DEFAULTS as D}from"./retrieval/search.js";import{askToolsFor as T,callAsk as U}from"./mcp-ask.js";import{CAPABILITY_TOOLS as B,callCapability as H}from"./mcp-capabilities.js";const W="2024-11-05",F={name:"chatpanel-history",version:b},Y=["ChatPanel holds the USER'S OWN meetings, notes and past chats — transcripts, decisions,","action items, summaries — which usually are NOT in the working directory.","","Keep using all your normal tools. ADDITIONALLY, whenever the user's question touches a",'meeting, call, demo, note, or past conversation ("outcome of the meeting", "what did we','decide", "action items", "notes from yesterday", a person/day/topic in their history),',"ALSO consult ChatPanel — it is the source of truth for that personal history:",' • research — for "when was my last…", "how many…", "who do I meet with most", "what was',' that meeting about": it searches the WHOLE store as the question frames it (dates, counts,'," people), reads the top records in full and returns the evidence with ids to cite."," • smart_search — START HERE: give it the question plus 2-4 of your own keyword"," phrasings; it runs them all and fuses the rankings, finding what one query misses."," • search_history — one exact keyword query, when you already know the terms. Search by"," CONTENT (not the generic meeting title). Supports filters:",' type (chat|meeting|note), since/before (dates or relative like "7d", "yesterday"),'," and limit/offset paging. Returns compact snippets, not full bodies."," • get_record — the full text of one result id; use maxChars/offset to page a long"," transcript instead of pulling it all into context."," • find_related — follow the graph: given a record id, the records most connected to it.","","ChatPanel also holds the user's MEMORY — a short list of durable facts about them (their","name, how they want answers written, what they are working on) that applies to EVERY task,","not just ones about their history:"," • recall — call it EARLY in a session, and whenever the user states a preference, to see"," what is already known. Then simply follow it; do not tell them you looked.",' • remember — save a new durable fact when they state one ("call me Alex", "always use',' pnpm"). One short sentence. Not for task details or anything true only today.'," • forget — remove one when they say it no longer holds.","Prefer these for the user's history and combine them with your other tools as you see fit.","Every result states how fresh the local copy is; if something recent is missing it may not","have synced yet — say so rather than concluding it does not exist.","","ChatPanel also runs SMALL LOCAL MODELS and a private web search on this machine:"," • decide — a sentiment, tone, urgency, spam/complaint, yes/no or pick-one judgement over"," text you already hold, answered with a probability per option in milliseconds. Call it"," instead of judging the text yourself."," • rerank — order many candidates (search hits, comments, sections) by relevance to a"," question, best first with a score, instead of reading them all."," • web_search — the user's own search (their SearXNG when one runs here), results with"," the top pages already read. Nothing leaves this machine but the query."," • redact_check — what is personal or secret in a piece of text, found by the detector on"," THIS machine. Call it before you put someone else's data into your own context, a"," commit message, an issue or a message to a third party — and whenever the user asks"," what is sensitive in something. It tells you what it could not see, so read that line."," • read_document — a URL as clean markdown through the user's own reader and cache,"," for a fraction of the context raw HTML would cost.","","ChatPanel can also hand a question to ANOTHER MODEL on this machine and give you its answer:"," • list_models — what can answer, and WHERE each one runs (on this device / a cloud)."," • ask_model — ask one. Use it for a second opinion on your own reasoning, for a model",' stronger in some domain, when the user names a model ("ask Claude what it thinks"), or'," when they want a question kept on-device — pick a `device` model and nothing leaves the"," machine. The model you ask sees your prompt and NOTHING else: no files, no shell, no web."," So paste in the code or context it needs. A slow answer returns a job id for ask_status."].join(`
2
+ `);async function z(){try{const t=await fetch(`${f()}/health`,{signal:AbortSignal.timeout(600)}),e=String((await t.json())?.version||"");return!e||e===b?"":["",`IMPORTANT — VERSION MISMATCH. This MCP server is ChatPanel ${b}, but the gateway`,`running on this machine is ${e}. They are different installs: your client launched`,"whichever `chatpanel-gateway` is on its PATH, and it is not the one the user is running.","The practical effect is that TOOLS MAY BE MISSING here — a newer gateway has tools this","server does not advertise. If a ChatPanel tool the user expects is not in your list, this","is why. Tell them, and tell them the fix: point the MCP config at the newer executable","(or update the older install so both are the same version)."].join(`
3
+ `)}catch{return""}}function S(){try{return y().mcp?.ask||{}}catch{return{}}}let m="unknown";function O(t){try{const e=k();fetch(`${f()}/v1/observability/access`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(t)}).catch(()=>{})}catch{}}function f(){const t=process.env.CHATPANEL_GATEWAY_URL;if(t)return t.replace(/\/+$/,"");let e=4320;try{e=y().port||4320}catch{}return`http://127.0.0.1:${e}`}function C(){try{return String(y().bridge?.url||"http://127.0.0.1:4319").replace(/\/+$/,"")}catch{return"http://127.0.0.1:4319"}}function J(){try{return x(y().bridge?.token||"")}catch{return x("")}}async function $(t){const e=J(),i=await fetch(C()+t,{headers:{Accept:"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}),a=await i.json().catch(()=>({}));if(!i.ok||a.ok===!1)throw new Error(a?.error||`bridge ${i.status}`);return a}const G=[{name:"smart_search",description:'BEST first choice for a question about the user\'s ChatPanel history (meetings, notes, past chats). Ask it a natural-language QUESTION and it expands that into several complementary keyword queries, runs them all, and fuses the rankings — which finds things a single query misses, in one round trip instead of several probes. You know the domain, so pass 2-4 of your own phrasings in `queries` too (e.g. for "what did we decide in the Ben demo": ["Ben demo decisions", "tooling demo action items", "demo outcome next steps"]). Supports the same filters as search_history (type, since, before) and returns snippets with each result\'s id; follow up with get_record for the full text or find_related to expand around a hit. BRIEFS come first when they match: a brief is a maintained page about one person, project or topic, derived from ALL the records that mention it, with every claim citing its record — so for "what do we know about X" read the brief, then open only the records it cites.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in natural language."},queries:{type:"array",items:{type:"string"},description:"Your own 2-4 keyword formulations of it — these lead the search."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a window like "7d"/"yesterday".'},before:{type:"string",description:"Latest date: a date or window like `since`."},limit:{type:"number",description:"Max fused results (default 10)."}},required:["question"]}},{name:"research",description:'Research a question about the user\'s OWN meetings, notes and past chats from the WHOLE ChatPanel store, not a few snippets: it frames the question (which kind of record, which people, which dates, the latest or the first, a count, counts per person or per month), queries every record that matches — sorted by date when the question asks for the last one, counted when it asks how many — reads the top records in full, and returns what it searched, what it found (with record ids and dates) and what those records say. Use it for "when was my last meeting with Alex", "how many calls did I have in August", "who do I meet with most", "what did we decide about pricing". For a follow-up ("no, even later", "what was it about") pass back the `previous` it returned. Cite the [id]s it gives; follow up with get_record for more of one record.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in their words."},previous:{type:"object",description:"The `previous` value the last research call returned, to continue that question (a follow-up)."}},required:["question"]}},{name:"search_history",description:'Search the user\'s ChatPanel history — their past chats, meeting/call transcripts, and notes — by keyword relevance. Consult this (in ADDITION to your other tools) whenever the question touches a meeting, call, demo, note, or past conversation: "outcome of the meeting", "what did we decide", "action items", "what did <person> say", "notes from yesterday". Filters: `type` (chat|meeting|note), `since`/`before` (a date like 2026-08-01 or a relative window like "7d"/"yesterday"), and `limit`/`offset` for paging. Returns compact SNIPPETS (the matching excerpt) with each record\'s id/title/type/date — token-friendly; call get_record for the full text and find_related to follow connections. This is a LOCAL WARM COPY that syncs from ChatPanel; very recent items may not be here yet — results report how current the index is, so if something is missing it likely has not synced. Meeting titles are often generic ("Zoom Meeting"), so search by CONTENT, not the title.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Content keywords (topics, names, decisions) — not the meeting title."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a relative window like "7d", "2 weeks", "yesterday".'},before:{type:"string",description:"Latest date: a date or relative window like `since`."},limit:{type:"number",description:"Max results (default 10)."},offset:{type:"number",description:"Skip N results for paging (default 0)."}},required:["query"]}},{name:"get_record",description:"Fetch one history record's full text by id (chat:<id>, meeting:<id>, note:<id> from search_history). For a long transcript, page it with maxChars + offset instead of pulling it all into context — the result says how many chars remain.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Record id such as chat:abc, meeting:imp_123, or note:xyz."},maxChars:{type:"number",description:"Return at most this many characters (token management for long transcripts)."},offset:{type:"number",description:"Start at this character offset — page through with the offset the previous call reports."}},required:["id"]}},{name:"find_related",description:"Graph navigation: given a record id (from search_history), return the records most connected to it by shared content — the meetings/notes/chats about the same topic, people or thread. Use it to expand from one hit to the surrounding context instead of re-searching.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The record id to find neighbours of."},limit:{type:"number",description:"Max related records (default 5)."}},required:["id"]}},{name:"list_history",description:"List history records (newest first) with their id, title, type and date — no bodies. Reports how current this warm copy is (its newest record). Use to see the index horizon and browse/page the corpus.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max items (default 50)."},offset:{type:"number",description:"Skip N items for paging (default 0)."}}}},{name:"list_briefs",description:`The BRIEFS ChatPanel maintains — one page per person, project or topic that appears across enough records, each claim citing the record it came from. This is the index of what the user's corpus KNOWS, as opposed to what it merely contains: read it before asking "what do we know about X", then get_brief for the one you need. Briefs are rebuilt from the records, so they are as current as the last rebuild (dates shown).`,inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max briefs (default 50)."},offset:{type:"number",description:"Skip N for paging (default 0)."}}}},{name:"get_brief",description:"One brief as STRUCTURE: the subject, its other spellings, and each claim with the record ids it cites — so you can cite the record rather than the synthesis, and open only what you need with get_record. Prefer this over get_record for a brief:… id; get_record returns the same text as prose.",inputSchema:{type:"object",properties:{id:{type:"string",description:"A brief id (brief:…) from list_briefs or search results."}},required:["id"]}},{name:"recall",description:"What ChatPanel already knows about the USER — their name, how they want answers written, their ongoing work and environment. Short and cheap; call it at the START of a session and whenever the user states a preference, then just FOLLOW what it returns without announcing that you checked. Pass the current task in `text` and it also returns the facts relevant to that task, not only the always-on ones. This is memory, not history: for what was said in a meeting or a past chat use smart_search instead.",inputSchema:{type:"object",properties:{text:{type:"string",description:"What the user is asking about right now, so task-relevant facts come back too. Omit for just the always-on ones."}}}},{name:"remember",description:`Save a durable fact about the USER to ChatPanel, carried into every future session on every model and agent — the side panel, other CLIs, everything. Use it the moment they state a standing preference ("always use pnpm"), an identity fact ("call me Alex") or a constraint that will still be true next week. Do NOT use it for task details, anything obvious from the current work, or notes about a codebase — those belong in the repo. One short self-contained sentence, written in the third person. Saving is a change to the user's own data, so say in a short clause what you saved.`,inputSchema:{type:"object",properties:{text:{type:"string",description:'The fact, one short sentence in the third person ("Prefers pnpm over npm"). Max 280 characters.'},kind:{type:"string",enum:_,description:_.map(t=>`${t}: ${R[t].hint}`).join(" ")},tags:{type:"array",items:{type:"string"},description:"Optional short tags for grouping."}},required:["text"]}},{name:"forget",description:'Remove a memory from ChatPanel when the user says it no longer holds. Name it however they did ("the Frankfurt thing") or pass the id from recall — it matches on meaning, and tells you exactly what it removed.',inputSchema:{type:"object",properties:{query:{type:"string",description:"The memory to remove: its text, roughly how the user named it, or its id."}},required:["query"]}},{name:"list_skills",description:"List the reusable skills installed on this machine (via the ChatPanel bridge) — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes) and any configured folder. Returns each skill's name and one-line description. Call open_skill to load the one that fits the task.",inputSchema:{type:"object",properties:{}}},{name:"open_skill",description:"Load one skill's full instructions by name (from list_skills), then follow them. If the instructions point at reference files, read one with read_skill_file.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name from list_skills."}},required:["name"]}},{name:"read_skill_file",description:"Read one reference file a skill's instructions point at (any path inside the skill's own folder). Use only when the task needs it.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name."},path:{type:"string",description:"The reference path as written in the instructions, e.g. references/auth.md."}},required:["name","path"]}}],N={[I]:" The gateway decides in-process unless it was turned off: ChatPanel › Settings › Runtime › Decide (or the OpenDecision container, or a server that provides `decide` under Models).",[L]:" The gateway reranks in-process unless it was turned off: ChatPanel › Settings › Runtime › Rerank (or the Reranker container, or a server that provides `rerank` under Models)."};function q(){const t=f(),e=c=>[{id:"gateway",name:"the gateway",url:`${t}${c}`,where:"this device"}],i=A({providers:{decide:e("/v1/decide"),rerank:e("/v1/rerank")},fetch:(c,r)=>fetch(c,r)}),a=M({search:async c=>{const r=await l("/v1/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({q:c,limit:8,read:D.aliasRead})});return{query:c,engines:r.engines||[],results:(r.results||[]).map((n,o)=>({rank:o+1,title:n.title||n.url,url:n.url,engine:n.engine||"",text:n.read?.markdown||n.read?.text||n.snippet||""}))}}});return[i,a]}const V=q().flatMap(t=>t.specs.map(e=>({name:e.name,description:e.description,inputSchema:e.parameters})));async function K(t,e){const i=q().find(r=>r.specs.some(n=>n.name===t));if(!i)return null;const a=await i.execute(t,e);let c=typeof a=="string"?a:String(a?.text??a);return N[t]&&/^No (decision model|reranker) answered/.test(c)&&(c+=N[t]),c}function w(t,e){if(!t)return`Index: ${e} records (warm copy synced from ChatPanel).`;const i=new Date(t),a=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(i.getDate()).padStart(2,"0")} ${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}`;return`Index: ${e} records, current through ${a} (local warm copy — items newer than this may not have synced from ChatPanel yet).`}function j(){try{const t=k();return t?{Authorization:`Bearer ${t}`}:{}}catch{return{}}}async function l(t,e){let i;try{i=await fetch(f()+t,e)}catch(c){throw new Error(`the ChatPanel gateway is not running at ${f()} — start it with "chatpanel-gateway --install" (or run "chatpanel-gateway"), then retry. [${c.message}]`)}const a=await i.json().catch(()=>({}));if(!i.ok)throw new Error(a?.error?.message||`the gateway returned HTTP ${i.status} for ${t}`);return a}function g(t){if(t==null||t==="")return null;if(typeof t=="number")return t;const e=String(t).trim().toLowerCase(),i=864e5;if(e==="today")return Date.now()-i;if(e==="yesterday")return Date.now()-2*i;const a=/^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(e);if(a){const r=Number(a[1]),n=a[2][0],o=n==="d"?i:n==="w"?7*i:n==="m"?30*i:365*i;return Date.now()-r*o}const c=Date.parse(e);return Number.isNaN(c)?null:c}const v=(t,e)=>`${e+1}. [${t.id}] ${t.title||"(untitled)"} · ${t.type}${t.date?" · "+new Date(t.date).toISOString().slice(0,10):""}${t.snippet?`
4
+ ${t.snippet}`:""}`;async function X(t,e={}){const i=await K(t,e);if(i!=null)return i;const a=await H(t,e,{gatewayJson:l});if(a!=null)return a;const c=await U(t,e,{baseUrl:f,gatewayJson:l,token:()=>{try{return k()}catch{return""}},client:()=>m,askConfig:S});if(c!=null)return c;if(t==="research"){const r={question:String(e.question||"")};e.previous&&typeof e.previous=="object"&&(r.previous=e.previous);const n=await l("/v1/research",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)}),o=w(n.newest,n.size),s=n.attachment?.text||`Searched ${n.how||"the store"} — nothing found in the user's data.`;return`${o}
5
+
6
+ ${s}
7
+
8
+ previous (pass back for a follow-up): ${JSON.stringify(n.next||null)}`}if(t==="smart_search"){const r={question:String(e.question||""),queries:Array.isArray(e.queries)?e.queries.map(String):[],limit:Number(e.limit)||10};e.type&&(r.type=String(e.type));const n=g(e.since);n!=null&&(r.since=n);const o=g(e.before);o!=null&&(r.before=o);const s=await l("/v1/history/smart-search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)}),h=s.results||[],d=w(s.newest,s.size),u=(s.queries||[]).map(p=>`"${p}"`).join(", ");return h.length?[d,"",`${h.length} result(s) for "${e.question}" — searched ${s.queries.length} way(s): ${u}`,...h.map((p,E)=>`${v(p,E)}${p.foundBy?.length>1?`
5
9
  (matched ${p.foundBy.length} of the queries)`:""}`)].join(`
6
10
  `)+`
7
11
 
8
12
  get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.question}".
9
13
  Searched ${s.queries?.length||0} way(s): ${u}.
10
14
  ${d}
11
- If you expected a recent item it may not have synced yet — check ChatPanel directly, or try different keywords (meeting titles are often generic).`}if(t==="search_history"){const o={query:String(e.query||""),limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0)};e.type&&(o.type=String(e.type));const n=w(e.since);n!=null&&(o.since=n);const r=w(e.before);r!=null&&(o.before=r);const s=await l("/v1/history/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),h=s.results||[],d=$(s.newest,s.size),u=[e.type&&`type=${e.type}`,e.since&&`since=${e.since}`,e.before&&`before=${e.before}`].filter(Boolean).join(", "),p=u?` (${u})`:"";return h.length?[d,"",`${h.length} result(s) for "${e.query}"${p}:`,...h.map(v)].join(`
15
+ If you expected a recent item it may not have synced yet — check ChatPanel directly, or try different keywords (meeting titles are often generic).`}if(t==="search_history"){const r={query:String(e.query||""),limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0)};e.type&&(r.type=String(e.type));const n=g(e.since);n!=null&&(r.since=n);const o=g(e.before);o!=null&&(r.before=o);const s=await l("/v1/history/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)}),h=s.results||[],d=w(s.newest,s.size),u=[e.type&&`type=${e.type}`,e.since&&`since=${e.since}`,e.before&&`before=${e.before}`].filter(Boolean).join(", "),p=u?` (${u})`:"";return h.length?[d,"",`${h.length} result(s) for "${e.query}"${p}:`,...h.map(v)].join(`
12
16
  `)+`
13
17
 
14
18
  get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.query}"${p}.
15
19
  ${d}
16
- If you expected a recent item, it may not have synced yet — check ChatPanel directly, or broaden the query (titles are often generic; try content keywords, or drop a filter).`}if(t==="get_record"){const o=new URLSearchParams({id:String(e.id||"")});e.maxChars!=null&&o.set("maxChars",String(Math.max(1,Number(e.maxChars)||0))),e.offset!=null&&o.set("offset",String(Math.max(0,Number(e.offset)||0)));const r=(await l(`/v1/history/get?${o}`)).record,s=`[${r.id}] ${r.title||"(untitled)"} · ${r.type}${r.date?" · "+new Date(r.date).toISOString().slice(0,10):""}`,h=r.truncated?`
20
+ If you expected a recent item, it may not have synced yet — check ChatPanel directly, or broaden the query (titles are often generic; try content keywords, or drop a filter).`}if(t==="get_record"){const r=new URLSearchParams({id:String(e.id||"")});e.maxChars!=null&&r.set("maxChars",String(Math.max(1,Number(e.maxChars)||0))),e.offset!=null&&r.set("offset",String(Math.max(0,Number(e.offset)||0)));const o=(await l(`/v1/history/get?${r}`)).record,s=`[${o.id}] ${o.title||"(untitled)"} · ${o.type}${o.date?" · "+new Date(o.date).toISOString().slice(0,10):""}`,h=o.truncated?`
17
21
 
18
- [showing ${r.text.length} of ${r.totalChars} chars (from offset ${r.offset}). For the next part call get_record again with offset=${r.offset+r.text.length}.]`:"";return`${s}
22
+ [showing ${o.text.length} of ${o.totalChars} chars (from offset ${o.offset}). For the next part call get_record again with offset=${o.offset+o.text.length}.]`:"";return`${s}
19
23
 
20
- ${r.text||"(empty)"}${h}`}if(t==="find_related"){const n=(await l(`/v1/history/related?id=${encodeURIComponent(String(e.id||""))}&limit=${Number(e.limit)||5}`)).results||[];return n.length?[`Records related to ${e.id}:`,...n.map(v)].join(`
24
+ ${o.text||"(empty)"}${h}`}if(t==="find_related"){const n=(await l(`/v1/history/related?id=${encodeURIComponent(String(e.id||""))}&limit=${Number(e.limit)||5}`)).results||[];return n.length?[`Records related to ${e.id}:`,...n.map(v)].join(`
21
25
  `)+`
22
26
 
23
- get_record <id> for full text.`:`Nothing related to ${e.id} found (or that id isn't in the warm index — run search_history first to get a valid id).`}if(t==="list_history"){const o=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0)}),n=await l(`/v1/history/list?${o}`),r=n.items||[];if(!r.length)return"History is empty (or the gateway has not been seeded yet — open ChatPanel with warm sync enabled).";const s=r[0]?.date||null;return[$(s,n.total),"",`${r.length} of ${n.total} records:`,...r.map(h=>`[${h.id}] ${h.title||"(untitled)"} · ${h.type}${h.date?" · "+new Date(h.date).toISOString().slice(0,10):""} · ${h.chars} chars`)].join(`
24
- `)}if(t==="list_briefs"){const o=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0),type:"brief"}),n=await l(`/v1/history/list?${o}`),r=n.items||[];return r.length?[`${r.length} of ${n.total} briefs (each is a page about one subject, with every claim cited):`,...r.map(s=>`[${s.id}] ${s.title||"(untitled)"}${s.date?" · rebuilt "+new Date(s.date).toISOString().slice(0,10):""}`)].join(`
27
+ get_record <id> for full text.`:`Nothing related to ${e.id} found (or that id isn't in the warm index — run search_history first to get a valid id).`}if(t==="list_history"){const r=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0)}),n=await l(`/v1/history/list?${r}`),o=n.items||[];if(!o.length)return"History is empty (or the gateway has not been seeded yet — open ChatPanel with warm sync enabled).";const s=o[0]?.date||null;return[w(s,n.total),"",`${o.length} of ${n.total} records:`,...o.map(h=>`[${h.id}] ${h.title||"(untitled)"} · ${h.type}${h.date?" · "+new Date(h.date).toISOString().slice(0,10):""} · ${h.chars} chars`)].join(`
28
+ `)}if(t==="list_briefs"){const r=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0),type:"brief"}),n=await l(`/v1/history/list?${r}`),o=n.items||[];return o.length?[`${o.length} of ${n.total} briefs (each is a page about one subject, with every claim cited):`,...o.map(s=>`[${s.id}] ${s.title||"(untitled)"}${s.date?" · rebuilt "+new Date(s.date).toISOString().slice(0,10):""}`)].join(`
25
29
  `)+`
26
30
 
27
- get_brief <id> for its claims and the records they cite.`:`No briefs yet. ChatPanel builds them from the user's records on the Briefs page; if that has run, the user may have "share briefs with local agents" switched off.`}if(t==="get_brief"){const o=String(e.id||""),r=(await l(`/v1/history/get?${new URLSearchParams({id:o})}`)).record,s=A(r?.text);if(!s)return`${o} is not a brief (type ${r?.type||"unknown"}). Use get_record for it, or list_briefs for the brief ids.`;const h=[`BRIEF ${o} — ${s.name} (${s.kind})${s.aliases.length?` · also known as ${s.aliases.join(", ")}`:""}`,""];h.push(`${s.claims.length} claim(s), each with the records it cites:`);for(const d of s.claims)h.push(`• ${d.text}`),d.refs.length&&h.push(` cites: ${d.refs.map(u=>`${u.kind}:${u.id}`).join(", ")}`);return s.records.length&&h.push("",`Built from ${s.records.length} record(s) (most recent first): ${s.records.slice(0,12).map(d=>d.title).join(" · ")}${s.records.length>12?" …":""}`),h.push("","get_record <kind:id> opens a cited record; find_related <id> follows its connections."),h.join(`
28
- `)}if(t==="recall"){const o=await l("/v1/memory/recall",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:String(e.text||"")})});return o.memories?.length?o.block:o.size?"Nothing in ChatPanel memory applies here.":"ChatPanel memory is empty — nothing is known about this user yet. Use `remember` when they state something durable about themselves or how they want to work."}if(t==="remember"){const o=String(e.text||"").trim();if(!o)return"remember needs `text` — one short sentence about the user.";const n=await l("/v1/memory/remember",{method:"POST",headers:{"content-type":"application/json",...E()},body:JSON.stringify({text:o,kind:e.kind?String(e.kind):"fact",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:"mcp",surface:"mcp",agent:m}})});return n.action==="duplicate"?`Already known: "${n.record.text}" — nothing changed.`:n.action==="update"?`Updated memory to "${n.record.text}" (was "${n.replaced?.text}"). It applies to every future session.`:`Remembered: "${n.record.text}". It applies to every future ChatPanel session, on every model.`}if(t==="forget"){const o=String(e.query||"").trim();if(!o)return"forget needs `query` — the memory to remove.";const n=await l("/v1/memory/forget",{method:"POST",headers:{"content-type":"application/json",...E()},body:JSON.stringify({query:o})});return n.removed?.length?`Forgot: ${n.removed.map(r=>`"${r.text}"`).join(", ")}.`:`No memory matches "${o}". Call recall to see what is stored.`}if(t==="list_skills"){let o;try{o=await S("/skills")}catch(r){return`Installed skills are unavailable because the ChatPanel bridge is not running at ${O()}. Install/start it with:
31
+ get_brief <id> for its claims and the records they cite.`:`No briefs yet. ChatPanel builds them from the user's records on the Briefs page; if that has run, the user may have "share briefs with local agents" switched off.`}if(t==="get_brief"){const r=String(e.id||""),o=(await l(`/v1/history/get?${new URLSearchParams({id:r})}`)).record,s=P(o?.text);if(!s)return`${r} is not a brief (type ${o?.type||"unknown"}). Use get_record for it, or list_briefs for the brief ids.`;const h=[`BRIEF ${r} — ${s.name} (${s.kind})${s.aliases.length?` · also known as ${s.aliases.join(", ")}`:""}`,""];h.push(`${s.claims.length} claim(s), each with the records it cites:`);for(const d of s.claims)h.push(`• ${d.text}`),d.refs.length&&h.push(` cites: ${d.refs.map(u=>`${u.kind}:${u.id}`).join(", ")}`);return s.records.length&&h.push("",`Built from ${s.records.length} record(s) (most recent first): ${s.records.slice(0,12).map(d=>d.title).join(" · ")}${s.records.length>12?" …":""}`),h.push("","get_record <kind:id> opens a cited record; find_related <id> follows its connections."),h.join(`
32
+ `)}if(t==="recall"){const r=await l("/v1/memory/recall",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:String(e.text||"")})});return r.memories?.length?r.block:r.size?"Nothing in ChatPanel memory applies here.":"ChatPanel memory is empty — nothing is known about this user yet. Use `remember` when they state something durable about themselves or how they want to work."}if(t==="remember"){const r=String(e.text||"").trim();if(!r)return"remember needs `text` — one short sentence about the user.";const n=await l("/v1/memory/remember",{method:"POST",headers:{"content-type":"application/json",...j()},body:JSON.stringify({text:r,kind:e.kind?String(e.kind):"fact",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:"mcp",surface:"mcp",agent:m}})});return n.action==="duplicate"?`Already known: "${n.record.text}" — nothing changed.`:n.action==="update"?`Updated memory to "${n.record.text}" (was "${n.replaced?.text}"). It applies to every future session.`:`Remembered: "${n.record.text}". It applies to every future ChatPanel session, on every model.`}if(t==="forget"){const r=String(e.query||"").trim();if(!r)return"forget needs `query` — the memory to remove.";const n=await l("/v1/memory/forget",{method:"POST",headers:{"content-type":"application/json",...j()},body:JSON.stringify({query:r})});return n.removed?.length?`Forgot: ${n.removed.map(o=>`"${o.text}"`).join(", ")}.`:`No memory matches "${r}". Call recall to see what is stored.`}if(t==="list_skills"){let r;try{r=await $("/skills")}catch(o){return`Installed skills are unavailable because the ChatPanel bridge is not running at ${C()}. Install/start it with:
29
33
  curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash
30
- Then retry. History tools work without the bridge. [${r.message}]`}const n=o.skills||[];return n.length?[`${n.length} skill(s) installed:`,...n.map(r=>`- ${r.command||r.id}: ${r.description||r.name}${r.origin?.source?` (from ${r.origin.source})`:""}`)].join(`
34
+ Then retry. History tools work without the bridge. [${o.message}]`}const n=r.skills||[];return n.length?[`${n.length} skill(s) installed:`,...n.map(o=>`- ${o.command||o.id}: ${o.description||o.name}${o.origin?.source?` (from ${o.origin.source})`:""}`)].join(`
31
35
  `)+`
32
36
 
33
- Use open_skill with a name to load its instructions.`:"No skills installed on this machine yet."}if(t==="open_skill"){let o;try{o=await S(`/skills/${encodeURIComponent(String(e.name||"").trim())}`)}catch(n){return`Could not open "${e.name}": ${n.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return o.skill?.prompt||"(this skill has no extra instructions — just apply it.)"}if(t==="read_skill_file"){const o=encodeURIComponent(String(e.name||"").trim()),n=String(e.path||"").trim().split("/").map(encodeURIComponent).join("/");let r;try{r=await S(`/skills/${o}/file/${n}`)}catch(s){return`Could not read ${e.path}: ${s.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return r.text||"(empty)"}throw new Error(`unknown tool: ${t}`)}async function Q(t){const{id:e,method:i,params:a}=t||{},c=n=>({jsonrpc:"2.0",id:e,result:n}),o=(n,r)=>({jsonrpc:"2.0",id:e,error:{code:n,message:r}});try{switch(i){case"initialize":{m=a?.clientInfo?.name||m;const n=await z(),r=T(k()).some(s=>s.name==="delegate_task")?`
37
+ Use open_skill with a name to load its instructions.`:"No skills installed on this machine yet."}if(t==="open_skill"){let r;try{r=await $(`/skills/${encodeURIComponent(String(e.name||"").trim())}`)}catch(n){return`Could not open "${e.name}": ${n.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return r.skill?.prompt||"(this skill has no extra instructions — just apply it.)"}if(t==="read_skill_file"){const r=encodeURIComponent(String(e.name||"").trim()),n=String(e.path||"").trim().split("/").map(encodeURIComponent).join("/");let o;try{o=await $(`/skills/${r}/file/${n}`)}catch(s){return`Could not read ${e.path}: ${s.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return o.text||"(empty)"}throw new Error(`unknown tool: ${t}`)}async function Q(t){const{id:e,method:i,params:a}=t||{},c=n=>({jsonrpc:"2.0",id:e,result:n}),r=(n,o)=>({jsonrpc:"2.0",id:e,error:{code:n,message:o}});try{switch(i){case"initialize":{m=a?.clientInfo?.name||m;const n=await z(),o=T(S()).some(s=>s.name==="delegate_task")?`
34
38
 
35
39
  ChatPanel can also DELEGATE a whole piece of work to one of the user's coding agents,
36
40
  running here with its own tools in a directory they have allowed:
37
41
  • delegate_task — a refactor across many files, a test suite to run and fix, a build to
38
42
  diagnose. Unlike ask_model it reads and EDITS files and runs commands, so use it for work
39
43
  that belongs on this machine, tell the user what you delegated and where, and expect
40
- minutes — it returns a job id for ask_status.`:"";return c({protocolVersion:Y,capabilities:{tools:{}},serverInfo:F,instructions:W+r+n})}case"tools/list":return c({tools:[...G,...V,...B,...T(k())]});case"tools/call":{const n=Date.now();try{const r=await X(a?.name,a?.arguments||{});return C({client:m,tool:a?.name,ok:!0,ms:Date.now()-n,args:a?.arguments||{}}),c({content:[{type:"text",text:r}]})}catch(r){throw C({client:m,tool:a?.name,ok:!1,ms:Date.now()-n,args:a?.arguments||{},error:r.message}),r}}case"ping":return c({});default:return typeof i=="string"&&i.startsWith("notifications/")||e===void 0?null:o(-32601,`method not found: ${i}`)}}catch(n){return i==="tools/call"?c({content:[{type:"text",text:`Error: ${n.message}`}],isError:!0}):o(-32603,n.message)}}async function de(){let t="";process.stdin.setEncoding("utf8");const e=i=>process.stdout.write(JSON.stringify(i)+`
44
+ minutes — it returns a job id for ask_status.`:"";return c({protocolVersion:W,capabilities:{tools:{}},serverInfo:F,instructions:Y+o+n})}case"tools/list":return c({tools:[...G,...V,...B,...T(S())]});case"tools/call":{const n=Date.now();try{const o=await X(a?.name,a?.arguments||{});return O({client:m,tool:a?.name,ok:!0,ms:Date.now()-n,args:a?.arguments||{}}),c({content:[{type:"text",text:o}]})}catch(o){throw O({client:m,tool:a?.name,ok:!1,ms:Date.now()-n,args:a?.arguments||{},error:o.message}),o}}case"ping":return c({});default:return typeof i=="string"&&i.startsWith("notifications/")||e===void 0?null:r(-32601,`method not found: ${i}`)}}catch(n){return i==="tools/call"?c({content:[{type:"text",text:`Error: ${n.message}`}],isError:!0}):r(-32603,n.message)}}async function de(){let t="";process.stdin.setEncoding("utf8");const e=i=>process.stdout.write(JSON.stringify(i)+`
41
45
  `);for await(const i of process.stdin){t+=i;let a;for(;(a=t.indexOf(`
42
- `))>=0;){const c=t.slice(0,a).trim();if(t=t.slice(a+1),!c)continue;let o;try{o=JSON.parse(c)}catch{continue}const n=await Q(o);n&&e(n)}}}export{Q as handleRpc,de as runMcpServer};
46
+ `))>=0;){const c=t.slice(0,a).trim();if(t=t.slice(a+1),!c)continue;let r;try{r=JSON.parse(c)}catch{continue}const n=await Q(r);n&&e(n)}}}export{Q as handleRpc,de as runMcpServer};
@@ -0,0 +1 @@
1
+ import{research as $,speakersIn as x}from"@chatpanel/events/research.js";import{runSearchModes as M,namesIn as k}from"@chatpanel/events/search-modes.js";const y=r=>String(r||"").toLowerCase().replace(/[^\p{L}\p{N} ]/gu," ").replace(/\s+/g," ").trim(),N=(r,t,e)=>Math.max(t,Math.min(e,Number(r)||t));function O(r={}){const t=(r.names||[]).map(y).filter(Boolean).map(n=>`"${n}"`);return t.length?t.join(" AND "):[...new Set((r.terms||[]).flatMap(n=>y(n).split(" ")).filter(n=>n.length>=2))].map(n=>`${n}*`).join(" OR ")}function R(r,t){const e=[],n=[];t&&(e.push("fts MATCH ?"),n.push(t)),r.kind&&(e.push("r.type = ?"),n.push(String(r.kind)));const s=Math.max(Number(r.after)||0,Number(r.since)||0);return s>0&&(e.push("r.date >= ?"),n.push(s)),Number(r.before)>0&&(e.push("r.date < ?"),n.push(Number(r.before))),{where:e.length?`WHERE ${e.join(" AND ")}`:"",args:n}}const T={month:"%Y-%m",week:"%Y-W%W",day:"%Y-%m-%d"},C=/^(?:(?:MEETING|CHAT|NOTE|BRIEF|Date|Platform|Tags|Agent):[^\n]*|[A-Z][A-Z ]{2,30}:[ \t]*)$/gm,S=r=>String(r||"").replace(/^\[\d{1,2}:\d{2}(?::\d{2})?\s*(?:[AaPp]\.?\s?[Mm]\.?)?\]\s*/gm,"").replace(C,"");function D(r,t={},{excludeId:e=null}={}){const n=O(t),{where:s,args:a}=R(t,n),o=e?`${s?" AND":"WHERE"} r.id != ?`:"",u=e?[...a,String(e)]:a,c="fts JOIN records r ON r.id = fts.id",E=t.sort==="newest"?"r.date DESC":t.sort==="oldest"?"r.date ASC":n?"bm25(fts, 0.0, 4.0, 1.0)":"r.date DESC",d=n?"snippet(fts, 2, '', '', '…', 16)":"substr(fts.text, 1, 220)",h=r.all(`SELECT r.id id, r.type type, r.title title, r.date date, ${d} snip FROM ${c} ${s}${o} ORDER BY ${E} LIMIT ?`,[...u,N(t.limit||8,1,50)]).map(i=>({id:i.id,kind:i.type,title:i.title||"",date:Number(i.date)||0,snippet:String(i.snip||"").replace(/\s+/g," ").trim()})),g=Number(r.get(`SELECT COUNT(*) c FROM ${c} ${s}${o}`,u)?.c)||0,p={rows:h,count:g},m=T[t.group];if(m)p.groups=r.all(`SELECT strftime('${m}', r.date / 1000, 'unixepoch', 'localtime') k, COUNT(*) n FROM ${c} ${s}${o}${s||o?" AND":"WHERE"} r.date > 0 GROUP BY k ORDER BY k DESC LIMIT 36`,u).map(i=>({key:i.k,count:Number(i.n)||0}));else if(t.group==="person"){const i=new Map;for(const f of r.all(`SELECT fts.text text FROM ${c} ${s}${o} ORDER BY r.date DESC LIMIT 2000`,u))for(const l of new Set(x(S(f.text)).map(b=>b.name)))i.set(l,(i.get(l)||0)+1);p.groups=[...i].sort((f,l)=>l[1]-f[1]||f[0].localeCompare(l[0])).slice(0,36).map(([f,l])=>({key:f,count:l}))}return p}function w(r,{excludeId:t=null}={}){return r?.db?.all?async e=>D(r.db,e,{excludeId:t}):async e=>{const n=[...e.names||[],...e.terms||[]].join(" "),s=Math.max(Number(e.after)||0,Number(e.since)||0);let a=n?r.search(n,{limit:50,type:e.kind||null,since:s||null,before:e.before?e.before-1:null}):r.list({limit:50,type:e.kind||null}).items;return a=a.filter(o=>o.id!==t),e.sort==="newest"&&a.sort((o,u)=>(u.date||0)-(o.date||0)),e.sort==="oldest"&&a.sort((o,u)=>(o.date||0)-(u.date||0)),{rows:a.slice(0,N(e.limit||8,1,50)).map(o=>({id:o.id,kind:o.type,title:o.title||"",date:Number(o.date)||0,snippet:o.snippet||""})),count:a.length,approximate:!0}}}function A(r,{excludeId:t=null}={}){const e=w(r,{excludeId:t});return async({terms:n=[],phrase:s=!1,kind:a="",sinceAt:o=0,limit:u=20}={})=>{const c=(n||[]).map(String).filter(Boolean);return c.length?(await e({kind:a,names:s?[c.join(" ")]:[],terms:s?[]:c,since:o,sort:"relevance",limit:u})).rows:[]}}async function Y(r,{store:t,memories:e=[],complete:n=null,previous:s=null,self:a="",excludeId:o=null,mapWindow:u=0,answerWindow:c=0,parallel:E=1,corrections:d=null,limits:h,now:g}={}){const p=A(t,{excludeId:o});return $(String(r||"").slice(0,600),{previous:s,memories:e,knownNames:e.flatMap(m=>k(m?.text||"")),query:w(t,{excludeId:o}),readText:async m=>{const i=t.get(m);return i?{id:i.id,title:i.title,date:i.date,text:S(i.text)}:null},searchModes:m=>M(String(m).slice(0,500),{lexical:p,memories:e,self:a,excludeId:o,limit:8,modes:["memory","keyword","graph","hybrid"],corrections:d}),complete:n,mapWindow:u,answerWindow:c,parallel:E,corrections:d,self:a,...h?{limits:h}:{},...g?{now:g}:{}})}function L(r){const t=r.read?.[0]||r.rows?.find(n=>!String(n.id).startsWith("memory:"))||null,e=Number(t?.date)||0;return{plan:r.plan,top:t?.id||null,answer:e?new Date(e).toISOString().slice(0,10):""}}function H(r,t,{size:e=0,newest:n=null}={}){return{ok:!0,question:String(r||""),plan:t.plan,how:t.how,framedBy:t.framedBy||"rules",count:t.count,rows:t.rows||[],groups:t.groups||null,read:(t.read||[]).map(s=>({id:s.id,title:s.title||"",date:Number(s.date)||0,parts:s.chunks,of:s.of,speakers:s.speakers||[],notes:s.notes||[]})),memory:t.memory||[],rounds:t.rounds,verdict:t.verdict||null,ms:t.ms,next:L(t),attachment:t.attachment?{title:t.attachment.title,text:t.attachment.text}:null,size:e,newest:n}}export{O as matchOf,S as readable,H as researchResponse,Y as researchStore,D as sqliteQuery,A as storeLexical,w as storeQuery};
package/src/server.js CHANGED
@@ -1,48 +1,48 @@
1
- import{createServer as so}from"node:http";import{loadConfig as gt}from"./config.js";import{startEntitlementRefresh as ao,maybeRevalidate as io}from"./entitlement-refresh.js";import{redactSegments as Me,segment as Ve}from"./redact.js";import{pipeRestoredStream as lo,pipeRestoredOpenAIStream as co,makeTokenRestorer as wt,restoreDeep as uo}from"./stream.js";import{restoreText as mo,gatedDictionary as po,narrowSpecs as ho,makeToolHarness as yo,placeholderToolNote as fo,placeholderNote as go,assertEndpointUrl as wo,capRunOptions as bo,isPaired as ko}from"@chatpanel/pii";import{ensureGatewayToken as Fe,currentGatewayToken as vo,isAdminAuthorized as H,callerTrustOf as Be,setPinnedExtensionIds as So,issuePairingCode as To,claimPairingCode as xo}from"./gateway-token.js";import{installEgressLedger as Oo,egressAudit as _o}from"./egress.js";import{initPolicy as Eo,activePolicy as $o,applyPolicyToConfig as bt,managedSummary as xe,PolicyLoadError as Po}from"./policy.js";import{routeAllowed as kt,agentAllowed as Ao,egressAllowed as No}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as Oe}from"./bridge.js";import{secureFetch as De}from"./secure-fetch.js";import{fetchCard as Ce,forgetCard as Mo,sendMessage as Bo,streamMessage as Do,getTask as Co,cancelTask as Ro,knownAgents as Io,A2AError as vt}from"./a2a.js";import{streamBridgeChat as St,readBridgeToken as _e,openBridgeChat as jo,acceptedBridgeToken as Lo}from"./bridge.js";import{createRelaySession as zo,getRelaySession as Tt,endRelaySession as Ee,pumpBridgeStream as Jo,deliverToolResult as Go,toolsToSpecs as Uo,wantsApprovals as Ho,parseToolCallId as xt,touchRelaySession as We}from"./toolrelay.js";import{shaperFor as Ke}from"./shape.js";import{startNer as Vo,ensureNer as Re,unionForThisMachine as Fo,skippedCompanions as Wo}from"./ner.js";import{recommendDetector as Ot}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Ko}from"./log.js";import{saveBackupSecret as Qo,clearBackupSecret as Yo,loadBackupSecret as Qe,hasBackupSecret as _t}from"./history-store.js";import{createMemoryStore as Zo}from"./memory-store.js";import{createPrefsStore as Xo}from"./prefs-store.js";import{createTeamStore as qo,loadOrCreateKey as Ye}from"./team-store.js";import{createScorecardStore as er}from"./scorecard-store.js";import{createEngineLedgerStore as tr}from"./engine-ledger-store.js";import{createProjectStore as or}from"./project-store.js";import{applicationsFor as rr,recruitPass as nr}from"./recruiting.js";import{ensureBridge as sr,holderOf as ar,compareVersions as ir}from"./bridge-supervisor.js";import{checkForUpdate as lr,updateStatus as dr,startUpdate as cr,updateJob as ur}from"./update.js";import{createHistoryStore as mr}from"./sqlite-store.js";import{createEventStore as pr}from"./event-store.js";import{ingestCloudEvents as hr,cursorOf as Et}from"./event-sync.js";import{eventStats as yr,projectYear as fr}from"./event-stats.js";import{toCloudEvent as Ze}from"./cloudevents.js";import{fusionsDocument as gr,resolveFusionModel as wr}from"./fusions.js";import{ingestBackups as Xe}from"./backup-ingest.js";import{toSearchRecord as br}from"@chatpanel/events/library.js";import{deriveBackupKey as kr,openRecord as vr,keyCache as Sr,nodeCodec as Tr}from"@chatpanel/events/backup-envelope.js";import xr from"node:zlib";import*as N from"./ner-engine.js";import $t from"node:os";import{capabilitiesDocument as Or,handleDetect as _r}from"./capabilities.js";import{createExtractService as Er}from"./extract/service.js";import{workerSandbox as $r,disposeWorkerSandbox as Pr}from"./worker-sandbox.js";import{createRuntime as Ar}from"./runtime.js";import{createCapabilityProxy as Nr}from"./capability-proxy.js";import{createEmbeddedCapabilities as Mr}from"./capability-embedded.js";import{EMBEDDED_MODELS as Br,EMBEDDED_IDS as Dr}from"./embedded-models.js";import{handleExtract as Cr}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as Rr}from"./extract-capability.js";import{createReader as Ir}from"./retrieval/read.js";import{createSearcher as jr,toJinaSearch as Lr,SEARCH_DEFAULTS as zr}from"./retrieval/search.js";import{createSearxng as Jr}from"./retrieval/search-searxng.js";import{toJinaText as Gr}from"./read-document.js";import*as B from"./stt-engine.js";import*as A from"./diarize-engine.js";import{DIARIZE_MODEL_CATALOG as Ur,DEFAULT_DIARIZE_MODEL as Hr,isKnownDiarizeModel as Pt}from"./diarize-models.js";import{providerOf as qe}from"./providers.js";import{createRemoteTranscriber as At}from"./stt-remote.js";import{parseMultipart as Vr,decodeAudioFile as Fr}from"./audio-file.js";import{MODEL_CATALOG as Nt,isKnownModel as Mt,isValidCustomModelId as Bt,recommendFor as Wr}from"./models.js";import{STT_MODEL_CATALOG as Kr,isKnownSttModel as Qr,isValidCustomSttId as Yr,DEFAULT_STT_MODEL as Ie,STT_DTYPES as Zr,isValidDtype as Xr}from"./stt-models.js";import*as P from"./tts-engine.js";import{TTS_MODEL_CATALOG as Dt,TTS_VOICES as qr,isKnownTtsModel as en,isValidCustomTtsId as tn,isKnownVoice as Ct,isValidVoiceId as Rt,DEFAULT_TTS_MODEL as It,DEFAULT_TTS_VOICE as ge,TTS_DTYPES as on,isValidTtsDtype as rn,MAX_TTS_CHARS as jt,ttsModelHasCustomVoices as nn,resolveDefaultModel as Lt,POCKET_VOICES as sn,DEFAULT_POCKET_VOICE as je,isPocketVoice as Le,ttsModelEngine as ze}from"./tts-models.js";import{ttsDestination as an,synthesizeRemote as ln,isValidRemoteVoice as dn}from"./tts-remote.js";import{rawOrtAvailable as et}from"./ort.js";import*as Y from"./tts-voices.js";import{resolveTtsVoice as cn}from"./tts-voice-resolve.js";import{resolvePro as be,checkQuota as un,consume as mn,usage as pn}from"./freegate.js";import{publicConfig as zt,applyConfigPatch as hn,registryChildEnv as yn,applyNerModelSelection as Jt,persistConfig as he,configPath as ne,bridgeAgentOptions as Gt,PERMISSION_MODES as fn,sandboxEnvFor as gn}from"./configstore.js";import Ut from"node:path";import{resolveDestination as tt,aggregateModelsAsync as wn,listDestinations as bn,ensureModelCatalog as kn,agentOwnsModel as vn}from"./router.js";import{makeAccessEvent as Ht}from"./observability.js";import{createPersistentAccessLog as Sn}from"./access-log-store.js";import{planQueries as Tn,multiSearch as xn}from"./rrf.js";import*as ot from"./openai.js";import*as Vt from"./responses.js";import*as rt from"./anthropic.js";import{closeAndExit as On}from"./shutdown.js";import{VERSION as W}from"./version.js";import{VERSION as ga}from"./version.js";const D=await mr(),ye=new Set;function Je({ids:t=[]}={}){const d=D.lossless;if(!d||!ye.size)return;const c=JSON.stringify({newest:d.newest,size:d.size,ids:t.slice(0,50),at:Date.now()});for(const m of ye)try{m.write(`event: records
1
+ import{createServer as co}from"node:http";import{loadConfig as vt}from"./config.js";import{startEntitlementRefresh as uo,maybeRevalidate as mo}from"./entitlement-refresh.js";import{redactSegments as De,segment as Qe}from"./redact.js";import{pipeRestoredStream as po,pipeRestoredOpenAIStream as ho,makeTokenRestorer as kt,restoreDeep as yo}from"./stream.js";import{restoreText as fo,gatedDictionary as go,narrowSpecs as wo,makeToolHarness as bo,placeholderToolNote as vo,placeholderNote as ko,assertEndpointUrl as So,capRunOptions as To,isPaired as xo}from"@chatpanel/pii";import{ensureGatewayToken as Oe,currentGatewayToken as Ye,isAdminAuthorized as z,callerTrustOf as Re,setPinnedExtensionIds as Oo,issuePairingCode as _o,claimPairingCode as Eo}from"./gateway-token.js";import{installEgressLedger as $o,egressAudit as Po}from"./egress.js";import{initPolicy as Ao,activePolicy as No,applyPolicyToConfig as St,managedSummary as _e,PolicyLoadError as Bo}from"./policy.js";import{routeAllowed as Tt,agentAllowed as Mo,egressAllowed as Co}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as Ee}from"./bridge.js";import{secureFetch as Ie}from"./secure-fetch.js";import{fetchCard as je,forgetCard as Do,sendMessage as Ro,streamMessage as Io,getTask as jo,cancelTask as Lo,knownAgents as Jo,A2AError as xt}from"./a2a.js";import{streamBridgeChat as Ot,readBridgeToken as $e,openBridgeChat as zo,acceptedBridgeToken as Go}from"./bridge.js";import{createRelaySession as Ho,getRelaySession as _t,endRelaySession as Pe,pumpBridgeStream as Uo,deliverToolResult as Vo,toolsToSpecs as Fo,wantsApprovals as Wo,parseToolCallId as Et,touchRelaySession as Ze}from"./toolrelay.js";import{shaperFor as Xe}from"./shape.js";import{startNer as Ko,ensureNer as Le,unionForThisMachine as Qo,skippedCompanions as Yo}from"./ner.js";import{recommendDetector as $t}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Zo}from"./log.js";import{saveBackupSecret as Xo,clearBackupSecret as qo,loadBackupSecret as qe,hasBackupSecret as Pt}from"./history-store.js";import{createMemoryStore as er}from"./memory-store.js";import{createPrefsStore as tr}from"./prefs-store.js";import{agentCardFor as or,runHintFor as rr}from"@chatpanel/events/agent-run-hint.js";import{researchStore as nr,researchResponse as sr}from"./research.js";import{createTeamStore as ar,loadOrCreateKey as et}from"./team-store.js";import{createScorecardStore as ir}from"./scorecard-store.js";import{createEngineLedgerStore as lr}from"./engine-ledger-store.js";import{createProjectStore as dr}from"./project-store.js";import{applicationsFor as cr,recruitPass as ur}from"./recruiting.js";import{ensureBridge as mr,holderOf as pr,compareVersions as hr}from"./bridge-supervisor.js";import{checkForUpdate as yr,updateStatus as fr,startUpdate as gr,updateJob as wr}from"./update.js";import{createHistoryStore as br}from"./sqlite-store.js";import{createEventStore as vr}from"./event-store.js";import{ingestCloudEvents as kr,cursorOf as At}from"./event-sync.js";import{eventStats as Sr,projectYear as Tr}from"./event-stats.js";import{toCloudEvent as tt}from"./cloudevents.js";import{fusionsDocument as xr,resolveFusionModel as Or}from"./fusions.js";import{ingestBackups as ot}from"./backup-ingest.js";import{toSearchRecord as _r}from"@chatpanel/events/library.js";import{deriveBackupKey as Er,openRecord as $r,keyCache as Pr,nodeCodec as Ar}from"@chatpanel/events/backup-envelope.js";import Nr from"node:zlib";import*as A from"./ner-engine.js";import Nt from"node:os";import{capabilitiesDocument as Br,handleDetect as Mr}from"./capabilities.js";import{createExtractService as Cr}from"./extract/service.js";import{workerSandbox as Dr,disposeWorkerSandbox as Rr}from"./worker-sandbox.js";import{createRuntime as Ir}from"./runtime.js";import{createCapabilityProxy as jr}from"./capability-proxy.js";import{createEmbeddedCapabilities as Lr}from"./capability-embedded.js";import{EMBEDDED_MODELS as Jr,EMBEDDED_IDS as zr}from"./embedded-models.js";import{handleExtract as Gr}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as Hr}from"./extract-capability.js";import{createReader as Ur}from"./retrieval/read.js";import{createBrowserRelayHost as Vr}from"./browser-relay.js";import{createLinkHost as Fr,DEFAULT_RELAY as Wr}from"./link-host.js";import{createSearcher as Kr,toJinaSearch as Qr,SEARCH_DEFAULTS as Yr}from"./retrieval/search.js";import{createSearxng as Zr}from"./retrieval/search-searxng.js";import{toJinaText as Xr}from"./read-document.js";import*as D from"./stt-engine.js";import*as P from"./diarize-engine.js";import{DIARIZE_MODEL_CATALOG as qr,DEFAULT_DIARIZE_MODEL as en,isKnownDiarizeModel as Bt}from"./diarize-models.js";import{providerOf as rt}from"./providers.js";import{createRemoteTranscriber as Mt}from"./stt-remote.js";import{parseMultipart as tn,decodeAudioFile as on}from"./audio-file.js";import{MODEL_CATALOG as Ct,isKnownModel as Dt,isValidCustomModelId as Rt,recommendFor as rn}from"./models.js";import{STT_MODEL_CATALOG as nn,isKnownSttModel as sn,isValidCustomSttId as an,DEFAULT_STT_MODEL as Je,STT_DTYPES as ln,isValidDtype as dn}from"./stt-models.js";import*as $ from"./tts-engine.js";import{TTS_MODEL_CATALOG as It,TTS_VOICES as cn,isKnownTtsModel as un,isValidCustomTtsId as mn,isKnownVoice as jt,isValidVoiceId as Lt,DEFAULT_TTS_MODEL as Jt,DEFAULT_TTS_VOICE as fe,TTS_DTYPES as pn,isValidTtsDtype as hn,MAX_TTS_CHARS as zt,ttsModelHasCustomVoices as yn,resolveDefaultModel as Gt,POCKET_VOICES as fn,DEFAULT_POCKET_VOICE as ze,isPocketVoice as Ge,ttsModelEngine as He}from"./tts-models.js";import{ttsDestination as gn,synthesizeRemote as wn,isValidRemoteVoice as bn}from"./tts-remote.js";import{rawOrtAvailable as nt}from"./ort.js";import*as Z from"./tts-voices.js";import{resolveTtsVoice as vn}from"./tts-voice-resolve.js";import{resolvePro as we,checkQuota as kn,consume as Sn,usage as Tn}from"./freegate.js";import{publicConfig as Ht,applyConfigPatch as xn,registryChildEnv as On,applyNerModelSelection as Ut,persistConfig as pe,configPath as ne,bridgeAgentOptions as Vt,PERMISSION_MODES as _n,sandboxEnvFor as En}from"./configstore.js";import Ft from"node:path";import{resolveDestination as st,aggregateModelsAsync as $n,listDestinations as Pn,ensureModelCatalog as An,agentOwnsModel as Nn}from"./router.js";import{makeAccessEvent as Wt}from"./observability.js";import{createPersistentAccessLog as Bn}from"./access-log-store.js";import{planQueries as Mn,multiSearch as Cn}from"./rrf.js";import*as at from"./openai.js";import*as Kt from"./responses.js";import*as it from"./anthropic.js";import{closeAndExit as Dn}from"./shutdown.js";import{VERSION as K}from"./version.js";import{VERSION as Aa}from"./version.js";const B=await br(),he=new Set;function Ue({ids:t=[]}={}){const d=B.lossless;if(!d||!he.size)return;const c=JSON.stringify({newest:d.newest,size:d.size,ids:t.slice(0,50),at:Date.now()});for(const m of he)try{m.write(`event: records
2
2
  data: ${c}
3
3
 
4
- `)}catch{ye.delete(m)}}setInterval(()=>{for(const t of ye)try{t.write(`: ping
4
+ `)}catch{he.delete(m)}}setInterval(()=>{for(const t of he)try{t.write(`: ping
5
5
 
6
- `)}catch{ye.delete(t)}},25e3).unref?.();const F=await pr(),ke=new Set;F?.watch(t=>{if(!ke.size)return;const d=`event: cloudevent
7
- data: ${JSON.stringify(Ze(t))}
6
+ `)}catch{he.delete(t)}},25e3).unref?.();const W=await vr(),be=new Set;W?.watch(t=>{if(!be.size)return;const d=`event: cloudevent
7
+ data: ${JSON.stringify(tt(t))}
8
8
 
9
- `;for(const c of ke)try{c.write(d)}catch{ke.delete(c)}}),setInterval(()=>{for(const t of ke)try{t.write(`: ping
9
+ `;for(const c of be)try{c.write(d)}catch{be.delete(c)}}),setInterval(()=>{for(const t of be)try{t.write(`: ping
10
10
 
11
- `)}catch{ke.delete(t)}},25e3).unref?.();const ee=await Zo(),te=Xo(),ve=er({key:Ye()}),Se=tr({key:Ye()}),Z=or({key:Ye()}),V=qo({scorecards:ve,engines:Se}),nt=new Set,Ft=(t,d)=>{for(const m of nt)try{m({applied:t,by:d,revision:te.revision})}catch{}const c=JSON.stringify({revision:te.revision,applied:(t||[]).slice(0,50),by:d||"",at:Date.now()});for(const m of ye)try{m.write(`event: prefs
11
+ `)}catch{be.delete(t)}},25e3).unref?.();const oe=await er(),te=tr(),Se=ir({key:et()}),Te=lr({key:et()}),X=dr({key:et()}),V=ar({scorecards:Se,engines:Te}),lt=new Set,Qt=(t,d)=>{for(const m of lt)try{m({applied:t,by:d,revision:te.revision})}catch{}const c=JSON.stringify({revision:te.revision,applied:(t||[]).slice(0,50),by:d||"",at:Date.now()});for(const m of he)try{m.write(`event: prefs
12
12
  data: ${c}
13
13
 
14
- `)}catch{ye.delete(m)}},st=Sn(),Wt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),_n=16,En=/^mcp[_-]/i,Kt=t=>t&&t.function&&t.function.name||t&&t.name||"",$n=t=>t&&t.function&&t.function.description||t&&t.description||"";function Qt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(d=>typeof d=="string"?d:d&&(d.text||d.content)||"").join(" "):""}function Pn(t,d){if(!t)return"";if(d==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(h=>Qt(h&&(h.content??h))).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 Qt(c[m].content);return""}const Yt=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function at(t){if(!t)return!1;const d=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return d==="localhost"||d==="127.0.0.1"||d==="::1"}function An(t,d){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(d.allowedOrigins)&&d.allowedOrigins.includes(t)}function Nn(t,d){t.setHeader("Access-Control-Allow-Origin",d||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const Zt=Date.now();function Mn(t){if(!t)return"";const d={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(c=>`${d[c]||c} ${t[c]}ms`).join(" · ")}function Bn(t){const d=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return d?{kind:d[1],id:d[2],...d[3]?{model:d[3]}:{}}:null}function Dn(t){const d=performance.now(),c={};let m=!1;const h=(g,E)=>{c[g]=Math.round(E*10)/10};return{meta:{},timings:c,mark:h,lap(g,E){h(g,performance.now()-E)},clock(){return performance.now()},commit(){if(m)return;m=!0,h("total",performance.now()-d);const g={...this.meta,timings:c};setImmediate(()=>{t(g),console.log(`[gateway] model=${g.model||"-"} → ${g.dest?`${g.dest}(${g.type})`:"none"} · ${g.redaction==="off"?"redaction OFF (client request)":`redacted ${g.redacted||0}`}${g.sanitized?` · scrubbed ${g.sanitized} hidden`:""}${g.narrowed?` · narrowed -${g.narrowed}`:""} · ${Mn(c)}`)})}}}function Xt(t,d){if(!t||!t.byToken||d!=="types"&&d!=="values")return;const c=[];for(const[m,h]of t.byToken){const g=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),E=g?g[1]:"PII",k=m.replace(/^\[\[|\]\]$/g,"");c.push(d==="values"?{token:k,type:E,value:h}:{token:k,type:E})}return c}function Cn(t,d,c){return rt.matches(t)||"anthropic-version"in d?{kind:"anthropic",adapter:rt,redactable:rt.matches(t),base:c.upstreams?.anthropic?.baseUrl}:Vt.matches(t)?{kind:"responses",adapter:Vt,redactable:!0,base:c.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:ot,redactable:ot.matches(t),base:c.upstreams?.openai?.baseUrl}}function it(t,d){const c=String(t||"");if(Wt.has(c))return{agent:c,agentModel:""};const m=c.indexOf("/");if(m>0){const h=c.slice(0,m);if(Wt.has(h))return{agent:h,agentModel:c.slice(m+1)}}return{agent:d.bridge.agent,agentModel:""}}function qt(t,d){return it(t,d).agent}function Rn(t,d){if(d!=="openai"||!t)return!1;const c=ot.extractLatestToolResult(t);if(!c)return!1;const m=xt(c.tool_call_id);return!!(m&&Tt(m.gwId))}function In(t,d){try{const c=new URL(t),m=c.hostname.replace(/^\[|\]$/g,""),h=m==="127.0.0.1"||m==="localhost"||m==="::1",g=c.port||(c.protocol==="https:"?"443":"80");return h&&String(g)===String(d.port)}catch{return!1}}async function T(t,d){const c=[];let m=0;for await(const h of t){if(m+=h.length,d&&m>d){const g=new Error("payload too large");throw g.code=413,g}c.push(h)}return Buffer.concat(c)}function s(t,d,c){t.writeHead(d,{"content-type":"application/json"}),t.end(JSON.stringify(c))}function eo(t){const d=t.redaction?.detection?.url;return!d||t.redaction?.detection?.backend==="off"?null:d}function lt(t){const d=t?.redaction?.detection,c=t?.redaction?.tier==="full"?"full":"basic";if(d&&d.backend&&d.backend!=="off")return{source:"external",backend:d.backend,state:"external",model:d.model||null,ready:!0,tier:c,coverage:c==="full"?"names":"patterns"};const m=N.health(),h=m.ok&&c==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:N.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:h,tier:c,coverage:h?"names":"patterns"}}async function to(t){if(N.state()!=="off"){const c=N.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 d=eo(t);if(!d)return{configured:!1,ok:!1,url:null,model:null};try{const c=await De(d.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!c.ok)return{configured:!0,ok:!1,url:d,model:null};const m=await c.json().catch(()=>({}));return{configured:!0,ok:!0,url:d,model:m.model||null}}catch{return{configured:!0,ok:!1,url:d,model:null}}}function jn(t,d){const c={};for(const[m,h]of Object.entries(t)){const g=m.toLowerCase();g.startsWith("x-chatpanel-")||Yt.has(g)||(c[m]=h)}c["accept-encoding"]="identity";try{c.host=new URL(d).host}catch{}return c}async function oo(t,d,c,m){const h=wt(d.vault),g=dt();t.on("close",()=>{t.writableFinished||Ee(d.id)});const E=m?m.clock():0;let k=E,x=!0;const $=()=>{m&&x&&(m.lap("upstream",E),k=m.clock(),x=!1)};await Jo(d,{onText:w=>{$(),We(d.id);const I=h.push(w);I&&t.write(c.sseDelta(I))},onToolRequest:({name:w,restoredArgs:I,toolId:L})=>{$(),We(d.id);const z=h.flush();z&&t.write(c.sseDelta(z)),t.write(c.sseToolCalls([{id:L,name:w,arguments:JSON.stringify(I)}])),t.write(c.sseToolFinish(g.value)),m&&m.lap("stream",k),t.end(),m?.commit()},onDone:()=>{const w=h.flush();w&&t.write(c.sseDelta(w)),t.write(c.sseTail(g.value)),m&&m.lap("stream",k),t.end(),Ee(d.id),m?.commit()},onError:w=>{t.write(`data: ${JSON.stringify({error:{message:w.message,type:"bridge_error"}})}
14
+ `)}catch{he.delete(m)}},dt=Bn(),Yt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Rn=16,In=/^mcp[_-]/i,Zt=t=>t&&t.function&&t.function.name||t&&t.name||"",jn=t=>t&&t.function&&t.function.description||t&&t.description||"";function Xt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(d=>typeof d=="string"?d:d&&(d.text||d.content)||"").join(" "):""}function Ln(t,d){if(!t)return"";if(d==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(h=>Xt(h&&(h.content??h))).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 Xt(c[m].content);return""}const qt=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function ct(t){if(!t)return!1;const d=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return d==="localhost"||d==="127.0.0.1"||d==="::1"}function Jn(t,d){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(d.allowedOrigins)&&d.allowedOrigins.includes(t)}function zn(t,d){t.setHeader("Access-Control-Allow-Origin",d||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const eo=Date.now();function Gn(t){if(!t)return"";const d={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(c=>`${d[c]||c} ${t[c]}ms`).join(" · ")}function Hn(t){const d=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return d?{kind:d[1],id:d[2],...d[3]?{model:d[3]}:{}}:null}function Un(t){const d=performance.now(),c={};let m=!1;const h=(g,E)=>{c[g]=Math.round(E*10)/10};return{meta:{},timings:c,mark:h,lap(g,E){h(g,performance.now()-E)},clock(){return performance.now()},commit(){if(m)return;m=!0,h("total",performance.now()-d);const g={...this.meta,timings:c};setImmediate(()=>{t(g),console.log(`[gateway] model=${g.model||"-"} → ${g.dest?`${g.dest}(${g.type})`:"none"} · ${g.redaction==="off"?"redaction OFF (client request)":`redacted ${g.redacted||0}`}${g.sanitized?` · scrubbed ${g.sanitized} hidden`:""}${g.narrowed?` · narrowed -${g.narrowed}`:""} · ${Gn(c)}`)})}}}function to(t,d){if(!t||!t.byToken||d!=="types"&&d!=="values")return;const c=[];for(const[m,h]of t.byToken){const g=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),E=g?g[1]:"PII",w=m.replace(/^\[\[|\]\]$/g,"");c.push(d==="values"?{token:w,type:E,value:h}:{token:w,type:E})}return c}function Vn(t,d,c){return it.matches(t)||"anthropic-version"in d?{kind:"anthropic",adapter:it,redactable:it.matches(t),base:c.upstreams?.anthropic?.baseUrl}:Kt.matches(t)?{kind:"responses",adapter:Kt,redactable:!0,base:c.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:at,redactable:at.matches(t),base:c.upstreams?.openai?.baseUrl}}function ut(t,d){const c=String(t||"");if(Yt.has(c))return{agent:c,agentModel:""};const m=c.indexOf("/");if(m>0){const h=c.slice(0,m);if(Yt.has(h))return{agent:h,agentModel:c.slice(m+1)}}return{agent:d.bridge.agent,agentModel:""}}function oo(t,d){return ut(t,d).agent}function Fn(t,d){if(d!=="openai"||!t)return!1;const c=at.extractLatestToolResult(t);if(!c)return!1;const m=Et(c.tool_call_id);return!!(m&&_t(m.gwId))}function Wn(t,d){try{const c=new URL(t),m=c.hostname.replace(/^\[|\]$/g,""),h=m==="127.0.0.1"||m==="localhost"||m==="::1",g=c.port||(c.protocol==="https:"?"443":"80");return h&&String(g)===String(d.port)}catch{return!1}}async function T(t,d){const c=[];let m=0;for await(const h of t){if(m+=h.length,d&&m>d){const g=new Error("payload too large");throw g.code=413,g}c.push(h)}return Buffer.concat(c)}function s(t,d,c){t.writeHead(d,{"content-type":"application/json"}),t.end(JSON.stringify(c))}function ro(t){const d=t.redaction?.detection?.url;return!d||t.redaction?.detection?.backend==="off"?null:d}function mt(t){const d=t?.redaction?.detection,c=t?.redaction?.tier==="full"?"full":"basic";if(d&&d.backend&&d.backend!=="off")return{source:"external",backend:d.backend,state:"external",model:d.model||null,ready:!0,tier:c,coverage:c==="full"?"names":"patterns"};const m=A.health(),h=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:h,tier:c,coverage:h?"names":"patterns"}}async function no(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 d=ro(t);if(!d)return{configured:!1,ok:!1,url:null,model:null};try{const c=await Ie(d.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!c.ok)return{configured:!0,ok:!1,url:d,model:null};const m=await c.json().catch(()=>({}));return{configured:!0,ok:!0,url:d,model:m.model||null}}catch{return{configured:!0,ok:!1,url:d,model:null}}}function Kn(t,d){const c={};for(const[m,h]of Object.entries(t)){const g=m.toLowerCase();g.startsWith("x-chatpanel-")||qt.has(g)||(c[m]=h)}c["accept-encoding"]="identity";try{c.host=new URL(d).host}catch{}return c}async function so(t,d,c,m){const h=kt(d.vault),g=pt();t.on("close",()=>{t.writableFinished||Pe(d.id)});const E=m?m.clock():0;let w=E,O=!0;const M=()=>{m&&O&&(m.lap("upstream",E),w=m.clock(),O=!1)};await Uo(d,{onText:v=>{M(),Ze(d.id);const C=h.push(v);C&&t.write(c.sseDelta(C))},onToolRequest:({name:v,restoredArgs:C,toolId:j})=>{M(),Ze(d.id);const G=h.flush();G&&t.write(c.sseDelta(G)),t.write(c.sseToolCalls([{id:j,name:v,arguments:JSON.stringify(C)}])),t.write(c.sseToolFinish(g.value)),m&&m.lap("stream",w),t.end(),m?.commit()},onDone:()=>{const v=h.flush();v&&t.write(c.sseDelta(v)),t.write(c.sseTail(g.value)),m&&m.lap("stream",w),t.end(),Pe(d.id),m?.commit()},onError:v=>{t.write(`data: ${JSON.stringify({error:{message:v.message,type:"bridge_error"}})}
15
15
 
16
- `),t.end(),Ee(d.id),m?.commit()},onUsage:w=>g.add(w)})}async function Ln(t,d,{kind:c,adapter:m,agent:h,run:g=null},E,k,x,$,w,I=null,L=null){const{messages:z,system:oe}=m.toTurn(E),{agentModel:se}=it(E?.model,x),X=Gt(x,{...se?{model:se}:{},...g||{}}),ue=_e(x.bridge.token),C=Ke(c,E?.model||h),n={tier:x.redaction.tier==="full"?"full":"basic",dictionary:po(x.redaction,$),entities:[]},o=await Oe(x),f=zo({vault:k,redactOpts:n,bridgeUrl:o,token:ue,harness:I});let l;try{l=await jo({bridgeUrl:o,agent:h,token:ue,messages:z,system:oe,specs:Uo(w),options:X,signal:void 0,approvals:Ho(w)})}catch(j){return Ee(f.id),L?.commit(),s(d,502,{error:{message:`bridge: ${j.message}`,type:"bridge_error"}})}return f.reader=l.body.getReader(),d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(C.sseHead()),oo(d,f,C,L)}async function zn(t,d,c,m,h=null){We(d.id),d.rounds=(d.rounds||0)+1;try{const E=h?h.clock():0;await Go(d,c),h&&h.lap("redact",E)}catch(E){return Ee(d.id),h?.commit(),s(t,502,{error:{message:`tool-result: ${E.message}`,type:"bridge_error"}})}const g=Ke("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(g.sseHead()),oo(t,d,g,h)}function dt(){let t=!1;const d={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(c){t=!0;for(const m of Object.keys(d))d[m]+=Math.max(0,Number(c?.[m])||0)},get value(){return t?d:null}}}async function Jn(t,d,{kind:c,adapter:m,redactable:h,pathname:g,agentOverride:E,harness:k,trace:x,run:$=null},w,I,L,z){if(!h)return x?.commit(),s(d,404,{error:`endpoint ${g} not supported by the bridge backend`});if(c==="openai"){const G=m.extractLatestToolResult(w);if(G){const q=xt(G.tool_call_id),le=q&&Tt(q.gwId);if(le)return zn(d,le,G.content,w?.model,x)}const re=m.extractTools(w);if(re.length&&w?.stream===!0)return Ln(t,d,{kind:c,adapter:m,agent:E||qt(w?.model,L),run:$},w,I,L,z,re,k,x)}const{messages:oe,system:se}=m.toTurn(w),X=E||qt(w?.model,L),ue=w?.stream===!0,C=Ke(c,w?.model||X),n=_e(L.bridge.token),o=new AbortController;d.on("close",()=>{d.writableFinished||o.abort()});const{agentModel:f}=it(w?.model,L),l={bridgeUrl:await Oe(L),agent:X,token:n,messages:oe,system:se,signal:o.signal,options:Gt(L,{...f?{model:f}:{},...$||{}})};if(!ue)try{let G="";const re=dt(),q=x?x.clock():0;await St(l,de=>{G+=de},null,de=>re.add(de)),x&&x.lap("upstream",q);const le=x?x.clock():0,me=C.full(mo(G,I),re.value);return x&&x.lap("restore",le),d.writeHead(200,{"content-type":C.contentType}),d.end(me),x?.commit()}catch(G){return x?.commit(),s(d,502,{error:{message:`bridge backend failed: ${G.message}`,type:"bridge_error"}})}d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(C.sseHead());const j=wt(I),ae=x?x.clock():0;let ie=ae;const v=dt();try{let G=!0;await St(l,q=>{x&&G&&(x.lap("upstream",ae),ie=x.clock(),G=!1);const le=j.push(q);le&&d.write(C.sseDelta(le))},C.sseActivity?q=>{try{d.write(C.sseActivity(uo(q,I)))}catch{}}:null,q=>v.add(q));const re=j.flush();re&&d.write(C.sseDelta(re)),d.write(C.sseTail(v.value))}catch(G){d.write(`data: ${JSON.stringify({error:{message:G.message,type:"bridge_error"}})}
16
+ `),t.end(),Pe(d.id),m?.commit()},onUsage:v=>g.add(v)})}async function Qn(t,d,{kind:c,adapter:m,agent:h,run:g=null},E,w,O,M,v,C=null,j=null){const{messages:G,system:ue}=m.toTurn(E),{agentModel:se}=ut(E?.model,O),q=Vt(O,{...se?{model:se}:{},...g||{}}),ae=$e(O.bridge.token),R=Xe(c,E?.model||h),ee={tier:O.redaction.tier==="full"?"full":"basic",dictionary:go(O.redaction,M),entities:[]},ie=await Ee(O),n=Ho({vault:w,redactOpts:ee,bridgeUrl:ie,token:ae,harness:C});let o;try{o=await zo({bridgeUrl:ie,agent:h,token:ae,messages:G,system:ue,specs:Fo(v),options:q,signal:void 0,approvals:Wo(v)})}catch(f){return Pe(n.id),j?.commit(),s(d,502,{error:{message:`bridge: ${f.message}`,type:"bridge_error"}})}return n.reader=o.body.getReader(),d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(R.sseHead()),so(d,n,R,j)}async function Yn(t,d,c,m,h=null){Ze(d.id),d.rounds=(d.rounds||0)+1;try{const E=h?h.clock():0;await Vo(d,c),h&&h.lap("redact",E)}catch(E){return Pe(d.id),h?.commit(),s(t,502,{error:{message:`tool-result: ${E.message}`,type:"bridge_error"}})}const g=Xe("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(g.sseHead()),so(t,d,g,h)}function pt(){let t=!1;const d={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(c){t=!0;for(const m of Object.keys(d))d[m]+=Math.max(0,Number(c?.[m])||0)},get value(){return t?d:null}}}async function Zn(t,d,{kind:c,adapter:m,redactable:h,pathname:g,agentOverride:E,harness:w,trace:O,run:M=null},v,C,j,G){if(!h)return O?.commit(),s(d,404,{error:`endpoint ${g} not supported by the bridge backend`});if(c==="openai"){const H=m.extractLatestToolResult(v);if(H){const Q=Et(H.tool_call_id),de=Q&&_t(Q.gwId);if(de)return Yn(d,de,H.content,v?.model,O)}const k=m.extractTools(v);if(k.length&&v?.stream===!0)return Qn(t,d,{kind:c,adapter:m,agent:E||oo(v?.model,j),run:M},v,C,j,G,k,w,O)}const{messages:ue,system:se}=m.toTurn(v),q=E||oo(v?.model,j),ae=v?.stream===!0,R=Xe(c,v?.model||q),ee=$e(j.bridge.token),ie=new AbortController;d.on("close",()=>{d.writableFinished||ie.abort()});const{agentModel:n}=ut(v?.model,j),o={bridgeUrl:await Ee(j),agent:q,token:ee,messages:ue,system:se,signal:ie.signal,options:Vt(j,{...n?{model:n}:{},...M||{}})};if(!ae)try{let H="";const k=pt(),Q=O?O.clock():0;await Ot(o,ve=>{H+=ve},null,ve=>k.add(ve)),O&&O.lap("upstream",Q);const de=O?O.clock():0,Ne=R.full(fo(H,C),k.value);return O&&O.lap("restore",de),d.writeHead(200,{"content-type":R.contentType}),d.end(Ne),O?.commit()}catch(H){return O?.commit(),s(d,502,{error:{message:`bridge backend failed: ${H.message}`,type:"bridge_error"}})}d.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),d.write(R.sseHead());const f=kt(C),i=O?O.clock():0;let L=i;const le=pt();try{let H=!0;await Ot(o,Q=>{O&&H&&(O.lap("upstream",i),L=O.clock(),H=!1);const de=f.push(Q);de&&d.write(R.sseDelta(de))},R.sseActivity?Q=>{try{d.write(R.sseActivity(yo(Q,C)))}catch{}}:null,Q=>le.add(Q));const k=f.flush();k&&d.write(R.sseDelta(k)),d.write(R.sseTail(le.value))}catch(H){d.write(`data: ${JSON.stringify({error:{message:H.message,type:"bridge_error"}})}
17
17
 
18
- `)}x&&x.lap("stream",ie),d.end(),x?.commit()}function Gn(t,d,c=""){const m=String(t||"").replace(/\/+$/,""),h=String(d||"").split("/")[1];return h&&m.endsWith(`/${h}`)?m.slice(0,-(h.length+1))+d+c:m+d+c}const Un=9e4;function Hn(t,d,c){if(d===c)return t;const m=d/c,h=new Float32Array(Math.floor(t.length/m));for(let g=0;g<h.length;g++){const E=g*m,k=Math.floor(E),x=Math.min(t.length-1,k+1),$=E-k;h[g]=t[k]*(1-$)+t[x]*$}return h}const Vn=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/a2a","/redact","/config","/logs","/status","/admin"];function ct(t,{installing:d=!1}={}){return t.stt?.diarize===!1?"off":d&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ce(t,d,c,m,{method:h="GET",timeoutMs:g=8e3,pick:E=k=>k}={}){const k=await Oe(c);if(!k)return s(d,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const x=_e(c.bridge?.token),$=h!=="GET"&&h!=="DELETE";try{const w=$?(await T(t,c.maxBodyBytes)).toString("utf8"):"",I=await fetch(`${k}${m}`,{method:h,headers:{Accept:"application/json",...$?{"content-type":"application/json"}:{},...x?{Authorization:`Bearer ${x}`}:{}},...$?{body:w||"{}"}:{},signal:AbortSignal.timeout(g)}),L=await I.json().catch(()=>({}));return I.ok?s(d,200,E(L)):s(d,I.status,{error:{message:L?.error||`bridge ${I.status}`,type:"bridge_error"}})}catch(w){return s(d,502,{error:{message:`bridge unreachable: ${w.message}`,type:"bridge_unreachable"}})}}function ut(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Te(t,d){const c=new URLSearchParams;for(const g of t.searchParams.getAll("dir"))g&&c.append("dir",g);const m=t.searchParams.get("workdir")||String(d?.bridge?.workingDir||"").trim();m&&c.set("workdir",m);const h=c.toString();return h?`?${h}`:""}async function Fn(t,d,{adapter:c,kind:m,pathname:h,search:g,base:E,destKey:k,destProtocol:x,harness:$,trace:w},I,L){let z;const oe=w?w.clock():0;try{const C=jn(t.headers,E);k&&(x==="anthropic"?(C["x-api-key"]=k,delete C.authorization):C.authorization=`Bearer ${k}`);const n=wo(Gn(E,h,g)).toString();z=await fetch(n,{method:t.method,headers:C,body:["GET","HEAD"].includes(t.method)?void 0:I})}catch(C){return w?.commit(),s(d,502,{error:`upstream fetch failed: ${C.message}`})}const se=z.headers.get("content-type")||"",X={};if(z.headers.forEach((C,n)=>{Yt.has(n.toLowerCase())||(X[n]=C)}),se.includes("text/event-stream")&&z.body){w&&w.lap("upstream",oe);const C=w?w.clock():0;d.writeHead(z.status,X);const n=m==="openai"?co(z.body,d,L,$):lo(z.body,d,L);return Promise.resolve(n).finally(()=>{w&&w.lap("stream",C),w?.commit()})}const ue=Buffer.from(await z.arrayBuffer());if(w&&w.lap("upstream",oe),L&&se.includes("application/json"))try{const C=w?w.clock():0,n=c.restoreResponse(JSON.parse(ue.toString("utf8")),L,$);return w&&w.lap("restore",C),d.writeHead(z.status,{...X,"content-type":"application/json"}),d.end(Buffer.from(JSON.stringify(n),"utf8")),w?.commit()}catch{}d.writeHead(z.status,X),d.end(ue),w?.commit()}function Wn(t=gt()){t.stt?.diarizeModel&&t.stt.diarizeModel!==A.activeModel()&&(Pt(t.stt.diarizeModel)?A.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${Hr}`));let d=null;const c=()=>{if(!d){const n=t.read||{};d=Ir({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return d};let m=null;const h=()=>(m||(m=Er({wrap:(n,o,f,l)=>$r().wrap(n,o,f,l),onLog:n=>console.warn(`[extract worker] ${n}`)})),m);let g={at:0,fn:()=>"unknown"},E=null;async function k(){if(Date.now()-g.at<1e4)return g.fn;let n=new Map;try{const l=await $().health();for(const[j,ae]of Object.entries(l)){const ie=(t.destinations||[]).filter(v=>v?.service===j).flatMap(v=>[v.id,...v.models||[]]);for(const v of[j,...ie])n.set(v,ae)}}catch{n=new Map}const o=l=>n.get(l)||"unknown",f=new Map((t.destinations||[]).filter(l=>l?.service).map(l=>[l.id,l.service]));return o.window=l=>{try{return $().contextWindow(f.get(l)||l)}catch{return null}},o.card=l=>{try{return $().modelCard(f.get(l)||l)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),g={at:Date.now(),fn:o},g.fn}let x=null;const $=()=>(x||(x=Ar({cfg:t,bridgeHealth:async()=>{const n=await Oe(t);if(!n)return null;const o=_e(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{he(t,ne())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Ut.join(Ut.dirname(ne()),"runtime"),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)})),x),w=Number(t.runtime?.idleMinutes),I=Mr({warmMs:(Number.isFinite(w)&&w>=0?w:10)*6e4,log:n=>console.log(n)}),L=Nr({cfg:t,wake:(n,o)=>$().wake(n,o),embedded:I}),z=()=>{t.search?.searxng?.url&&$().wake("searxng").catch(()=>{})};let oe=null;const se=()=>{if(!oe){const n=t.search||{},o=n.searxng?.url?Jr({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;oe=jr({reader:c(),searxng:o,defaultProvider:n.provider||"auto",redact:async f=>{let l=f;return await Me([Ve(()=>l,j=>{l=j})],{...t.redaction,tier:"basic"},{isPro:!0}),l}})}return oe};So(t.allowedExtensionIds||[]);const X=[],ue=n=>{X.push(n),X.length>50&&X.shift()},C=so(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),l=f.pathname;if(!at(n.headers.host))return s(o,403,{error:"loopback only"});if(!An(n.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(n.headers.origin&&Nn(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(l==="/admin/token"&&n.method==="POST")return H(n)?s(o,200,{token:Fe()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(l==="/pair/code"&&n.method==="POST"){if(!H(n))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=To();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(l==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=xo(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Be(n)} caller`),s(o,403,{error:r.reason});console.log(`[gateway] paired a ${Be(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:a,refused:i}=await Lo(t);return i&&console.log(`[gateway] pairing: the bridge at ${i.url}${i.version?` (v${i.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),s(o,200,{ok:!0,token:vo()||Fe(),...a?{bridgeToken:a}:{},...i?{bridgeRefused:i}:{}})}if(l==="/whoami"&&n.method==="POST"){const e=Be(n);return s(o,200,{ok:!0,trust:e,paired:ko(e),version:W})}if(l==="/audit"&&n.method==="GET")return H(n)?s(o,200,_o(t,{version:W,startedAt:Zt,managed:xe()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((l==="/config"||l==="/logs"||l==="/update"&&n.method!=="GET")&&!H(n))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(l==="/update"&&n.method==="GET"){const e=await lr(W,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:W,updateAvailable:!1,error:String(r?.message||r)}));return s(o,200,{ok:!0,update:e,job:ur()})}if(l==="/update"&&n.method==="POST"){const e=cr(W);return s(o,e.already?409:202,{ok:!0,job:e})}if((l==="/v1/history/key"||l==="/v1/history/ingest-backup")&&n.method==="POST"&&!H(n))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(l==="/v1/history/records"&&n.method==="PUT"&&!H(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/history/ingest"||l==="/v1/history/clear")&&n.method==="POST"&&!H(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/memory/remember"||l==="/v1/memory/forget"||l==="/v1/memory/sync"||l==="/v1/memory/clear")&&n.method==="POST"&&!H(n))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/prefs"||l.startsWith("/v1/prefs/")||l.startsWith("/v1/teams")||l.startsWith("/v1/agents")||l.startsWith("/v1/projects"))&&!H(n))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/events"||l.startsWith("/v1/events/"))&&!H(n))return s(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(l.startsWith("/v1/observability")&&!H(n))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&l==="/health"){const e=B.health(),r=P.health();return s(o,200,{ok:!0,version:W,backend:t.backend,tier:t.redaction.tier,pairing:!0,...xe()?{managed:xe()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...$e?{bridge:$e.status()}:Ge?{bridge:Ge}:{},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||Ie,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||It,voice:t.tts?.voice||ge,runtime:r.runtime,dtype:r.dtype},events:F?{count:F.count(),hosts:F.hosts().length}:null})}if(l==="/status"&&n.method==="GET"){io(t);const e=await be(t.pro?.entitlementToken),r=await to(t);return s(o,200,{ok:!0,version:W,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...xe()?{managed:xe()}:{},...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:lt(t),pro:{unlocked:e},usage:pn(t),uptimeSeconds:Math.floor((Date.now()-Zt)/1e3),update:dr(W)})}if(l==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=D.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(l==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?s(o,200,{ok:!0,revision:te.revision,stamps:te.stamps()}):s(o,200,{ok:!0,revision:te.revision,sections:te.get(e)})}if(l==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.put(e.sections||{},{by:e.by||""});return r.applied.length&&Ft(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(l==="/v1/prefs"&&n.method==="DELETE"){const e=String(f.searchParams.get("section")||""),r=e?te.remove(e):!1;return r&&Ft([e],""),s(o,200,{ok:!0,removed:r})}if(l==="/v1/prefs/events"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=i=>o.write(`data: ${JSON.stringify(i)}
18
+ `)}O&&O.lap("stream",L),d.end(),O?.commit()}function Xn(t,d,c=""){const m=String(t||"").replace(/\/+$/,""),h=String(d||"").split("/")[1];return h&&m.endsWith(`/${h}`)?m.slice(0,-(h.length+1))+d+c:m+d+c}const qn=9e4;function es(t,d,c){if(d===c)return t;const m=d/c,h=new Float32Array(Math.floor(t.length/m));for(let g=0;g<h.length;g++){const E=g*m,w=Math.floor(E),O=Math.min(t.length-1,w+1),M=E-w;h[g]=t[w]*(1-M)+t[O]*M}return h}const ts=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link"];function ht(t,{installing:d=!1}={}){return t.stt?.diarize===!1?"off":d&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function ce(t,d,c,m,{method:h="GET",timeoutMs:g=8e3,pick:E=w=>w}={}){const w=await Ee(c);if(!w)return s(d,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const O=$e(c.bridge?.token),M=h!=="GET"&&h!=="DELETE";try{const v=M?(await T(t,c.maxBodyBytes)).toString("utf8"):"",C=await fetch(`${w}${m}`,{method:h,headers:{Accept:"application/json",...M?{"content-type":"application/json"}:{},...O?{Authorization:`Bearer ${O}`}:{}},...M?{body:v||"{}"}:{},signal:AbortSignal.timeout(g)}),j=await C.json().catch(()=>({}));return C.ok?s(d,200,E(j)):s(d,C.status,{error:{message:j?.error||`bridge ${C.status}`,type:"bridge_error"}})}catch(v){return s(d,502,{error:{message:`bridge unreachable: ${v.message}`,type:"bridge_unreachable"}})}}function yt(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function xe(t,d){const c=new URLSearchParams;for(const g of t.searchParams.getAll("dir"))g&&c.append("dir",g);const m=t.searchParams.get("workdir")||String(d?.bridge?.workingDir||"").trim();m&&c.set("workdir",m);const h=c.toString();return h?`?${h}`:""}async function os(t,d,{adapter:c,kind:m,pathname:h,search:g,base:E,destKey:w,destProtocol:O,harness:M,trace:v},C,j){let G;const ue=v?v.clock():0;try{const R=Kn(t.headers,E);w&&(O==="anthropic"?(R["x-api-key"]=w,delete R.authorization):R.authorization=`Bearer ${w}`);const ee=So(Xn(E,h,g)).toString();G=await fetch(ee,{method:t.method,headers:R,body:["GET","HEAD"].includes(t.method)?void 0:C})}catch(R){return v?.commit(),s(d,502,{error:`upstream fetch failed: ${R.message}`})}const se=G.headers.get("content-type")||"",q={};if(G.headers.forEach((R,ee)=>{qt.has(ee.toLowerCase())||(q[ee]=R)}),se.includes("text/event-stream")&&G.body){v&&v.lap("upstream",ue);const R=v?v.clock():0;d.writeHead(G.status,q);const ee=m==="openai"?ho(G.body,d,j,M):po(G.body,d,j);return Promise.resolve(ee).finally(()=>{v&&v.lap("stream",R),v?.commit()})}const ae=Buffer.from(await G.arrayBuffer());if(v&&v.lap("upstream",ue),j&&se.includes("application/json"))try{const R=v?v.clock():0,ee=c.restoreResponse(JSON.parse(ae.toString("utf8")),j,M);return v&&v.lap("restore",R),d.writeHead(G.status,{...q,"content-type":"application/json"}),d.end(Buffer.from(JSON.stringify(ee),"utf8")),v?.commit()}catch{}d.writeHead(G.status,q),d.end(ae),v?.commit()}function rs(t=vt()){const d=Vr({version:K}),c=t.link?.enabled===!1?null:Fr({relay:t.link?.relayUrl||Wr,...t.link?.path?{path:t.link.path}:{},dispatch:({method:n,path:o,headers:f,body:i,device:L})=>fetch(`http://127.0.0.1:${t.port}${o}`,{method:n,body:i,headers:{...f,"x-chatpanel-token":Ye()||Oe(),"x-chatpanel-link-device":String(L||"")}}),log:n=>console.log(` ${n}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==P.activeModel()&&(Bt(t.stt.diarizeModel)?P.setModel(t.stt.diarizeModel,{log:n=>console.log(n)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${en}`));let m=null;const h=()=>{if(!m){const n=t.read||{};m=Ur({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return m};let g=null;const E=()=>(g||(g=Cr({wrap:(n,o,f,i)=>Dr().wrap(n,o,f,i),onLog:n=>console.warn(`[extract worker] ${n}`)})),g);let w={at:0,fn:()=>"unknown"},O=null;async function M(){if(Date.now()-w.at<1e4)return w.fn;let n=new Map;try{const i=await C().health();for(const[L,le]of Object.entries(i)){const H=(t.destinations||[]).filter(k=>k?.service===L).flatMap(k=>[k.id,...k.models||[]]);for(const k of[L,...H])n.set(k,le)}}catch{n=new Map}const o=i=>n.get(i)||"unknown",f=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return C().contextWindow(f.get(i)||i)}catch{return null}},o.card=i=>{try{return C().modelCard(f.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),w={at:Date.now(),fn:o},w.fn}let v=null;const C=()=>(v||(v=Ir({cfg:t,bridgeHealth:async()=>{const n=await Ee(t);if(!n)return null;const o=$e(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{pe(t,ne())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Ft.join(Ft.dirname(ne()),"runtime"),workers:()=>{const n=g?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),v),j=Number(t.runtime?.idleMinutes),G=Lr({warmMs:(Number.isFinite(j)&&j>=0?j:10)*6e4,log:n=>console.log(n)}),ue=jr({cfg:t,wake:(n,o)=>C().wake(n,o),embedded:G}),se=()=>{t.search?.searxng?.url&&C().wake("searxng").catch(()=>{})};let q=null;const ae=()=>{if(!q){const n=t.search||{},o=n.searxng?.url?Zr({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;q=Kr({reader:h(),searxng:o,defaultProvider:n.provider||"auto",redact:async f=>{let i=f;return await De([Qe(()=>i,L=>{i=L})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return q};Oo(t.allowedExtensionIds||[]);const R=[],ee=n=>{R.push(n),R.length>50&&R.shift()},ie=co(async(n,o)=>{const f=new URL(n.url,"http://127.0.0.1"),i=f.pathname;if(!ct(n.headers.host))return s(o,403,{error:"loopback only"});if(!Jn(n.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(n.headers.origin&&zn(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&n.method==="POST")return z(n)?s(o,200,{token:Oe()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&n.method==="POST"){if(!z(n))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=_o();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(i==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=Eo(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Re(n)} caller`),s(o,403,{error:r.reason});console.log(`[gateway] paired a ${Re(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const{token:a,refused:l}=await Go(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),s(o,200,{ok:!0,token:Ye()||Oe(),...a?{bridgeToken:a}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&n.method==="POST"){const e=Re(n);return s(o,200,{ok:!0,trust:e,paired:xo(e),version:K})}if(i==="/audit"&&n.method==="GET")return z(n)?s(o,200,Po(t,{version:K,startedAt:eo,managed:_e()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&n.method!=="GET")&&!z(n))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&n.method==="GET"){const e=await yr(K,{force:f.searchParams.get("force")==="1"}).catch(r=>({current:K,updateAvailable:!1,error:String(r?.message||r)}));return s(o,200,{ok:!0,update:e,job:wr()})}if(i==="/update"&&n.method==="POST"){const e=gr(K);return s(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&n.method==="POST"&&!z(n))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&n.method==="PUT"&&!z(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&n.method==="POST"&&!z(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&n.method==="POST"&&!z(n))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!z(n))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!z(n))return s(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!z(n))return s(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!z(n))return s(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!z(n))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&i==="/health"){const e=D.health(),r=$.health();return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,pairing:!0,..._e()?{managed:_e()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...Ae?{bridge:Ae.status()}:Ve?{bridge:Ve}:{},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||Je,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||Jt,voice:t.tts?.voice||fe,runtime:r.runtime,dtype:r.dtype},events:W?{count:W.count(),hosts:W.hosts().length}:null,browser:d.health()})}if(i==="/status"&&n.method==="GET"){mo(t);const e=await we(t.pro?.entitlementToken),r=await no(t);return s(o,200,{ok:!0,version:K,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},..._e()?{managed:_e()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:r.configured,ready:r.ok,model:r.model,url:r.url},detector:mt(t),pro:{unlocked:e},usage:Tn(t),uptimeSeconds:Math.floor((Date.now()-eo)/1e3),update:fr(K)})}if(i==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=B.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(i==="/v1/prefs"&&n.method==="GET"){const e=String(f.searchParams.get("section")||"");return f.searchParams.get("stamps")?s(o,200,{ok:!0,revision:te.revision,stamps:te.stamps()}):s(o,200,{ok:!0,revision:te.revision,sections:te.get(e)})}if(i==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.put(e.sections||{},{by:e.by||""});return r.applied.length&&Qt(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(i==="/v1/prefs"&&n.method==="DELETE"){const e=String(f.searchParams.get("section")||""),r=e?te.remove(e):!1;return r&&Qt([e],""),s(o,200,{ok:!0,removed:r})}if(i==="/v1/prefs/events"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
19
19
 
20
- `);e({type:"hello",revision:te.revision,stamps:te.stamps()});const r=i=>e({type:"changed",...i});nt.add(r);const a=setInterval(()=>{try{o.write(`: keep-alive
20
+ `);e({type:"hello",revision:te.revision,stamps:te.stamps()});const r=l=>e({type:"changed",...l});lt.add(r);const a=setInterval(()=>{try{o.write(`: keep-alive
21
21
 
22
- `)}catch{}},25e3);o.on("close",()=>{nt.delete(r),clearInterval(a)});return}if(l==="/v1/projects"&&n.method==="GET")return s(o,200,{ok:!0,projects:Z.list({limit:f.searchParams.get("limit")||50,status:f.searchParams.get("status")||""})});if(l==="/v1/projects/jobs"&&n.method==="GET")return s(o,200,{ok:!0,jobs:Z.openJobs()});if(l==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:Z.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(l);if(e){const r=e[1],a=e[2]||"",i=e[3]||"",u=e[4]||"",S=()=>s(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(u){const y=Z.get(r);if(!y)return S();const O=y.jobs.find(p=>p.id===i);if(!O)return s(o,404,{error:{message:`no job ${i}`,type:"not_found"}});const b={cfg:t,prefsStore:te,scorecards:ve,engines:Se};if(u==="/applications"&&n.method==="GET"){const p=await rr(O,{...b,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:O,...p})}if(u==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(O.status))return s(o,400,{error:{message:`job ${i} is ${O.status}; only an open job is recruited`,type:"project_error"}});try{const p=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},_=String(p.by||"evaluator").slice(0,80),J=await nr(O,{...b,record:y,reach:p.reach||"any",chatModel:p.chatModel||null,evaluation:p.evaluation||null,text:p.text??null,by:_});let R=null;for(const Q of J.events)Q.type==="job.updated"?R=Z.updateJob(r,i,Q.job,{by:Q.by||_}):R=Z.append(r,[Q]);return s(o,200,{ok:!0,project:R,decision:J.decision,applications:J.applications,evaluation:J.evaluation})}catch(p){return s(o,400,{error:{message:`recruit: ${p.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&n.method==="GET"){const y=Z.get(r,{events:f.searchParams.get("events")==="1"});return y?s(o,200,{ok:!0,project:y}):S()}if(!a&&n.method==="DELETE")return s(o,200,{ok:!0,removed:Z.remove(r)});if(n.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const y=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},O=String(y.by||"person").slice(0,80),b=a==="/events"?Z.append(r,y.events||[]):i?Z.updateJob(r,i,y.patch||y,{by:O}):Z.postJob(r,y.job||y,{by:O});return s(o,200,{ok:!0,project:b})}catch(y){return s(o,y.message.startsWith("no ")?404:400,{error:{message:`project: ${y.message}`,type:"project_error"}})}if(a==="/events"&&n.method==="GET"){if(!Z.get(r))return S();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const y=_=>o.write(`data: ${JSON.stringify(_)}
22
+ `)}catch{}},25e3);o.on("close",()=>{lt.delete(r),clearInterval(a)});return}if(i==="/v1/projects"&&n.method==="GET")return s(o,200,{ok:!0,projects:X.list({limit:f.searchParams.get("limit")||50,status:f.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&n.method==="GET")return s(o,200,{ok:!0,jobs:X.openJobs()});if(i==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:X.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(i);if(e){const r=e[1],a=e[2]||"",l=e[3]||"",u=e[4]||"",S=()=>s(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(u){const y=X.get(r);if(!y)return S();const x=y.jobs.find(p=>p.id===l);if(!x)return s(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const b={cfg:t,prefsStore:te,scorecards:Se,engines:Te};if(u==="/applications"&&n.method==="GET"){const p=await cr(x,{...b,reach:f.searchParams.get("reach")||"any",chatModel:f.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:x,...p})}if(u==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(x.status))return s(o,400,{error:{message:`job ${l} is ${x.status}; only an open job is recruited`,type:"project_error"}});try{const p=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},_=String(p.by||"evaluator").slice(0,80),J=await ur(x,{...b,record:y,reach:p.reach||"any",chatModel:p.chatModel||null,evaluation:p.evaluation||null,text:p.text??null,by:_});let I=null;for(const F of J.events)F.type==="job.updated"?I=X.updateJob(r,l,F.job,{by:F.by||_}):I=X.append(r,[F]);return s(o,200,{ok:!0,project:I,decision:J.decision,applications:J.applications,evaluation:J.evaluation})}catch(p){return s(o,400,{error:{message:`recruit: ${p.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&n.method==="GET"){const y=X.get(r,{events:f.searchParams.get("events")==="1"});return y?s(o,200,{ok:!0,project:y}):S()}if(!a&&n.method==="DELETE")return s(o,200,{ok:!0,removed:X.remove(r)});if(n.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const y=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},x=String(y.by||"person").slice(0,80),b=a==="/events"?X.append(r,y.events||[]):l?X.updateJob(r,l,y.patch||y,{by:x}):X.postJob(r,y.job||y,{by:x});return s(o,200,{ok:!0,project:b})}catch(y){return s(o,y.message.startsWith("no ")?404:400,{error:{message:`project: ${y.message}`,type:"project_error"}})}if(a==="/events"&&n.method==="GET"){if(!X.get(r))return S();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const y=_=>o.write(`data: ${JSON.stringify(_)}
23
23
 
24
- `);let O=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;y({seq:-1,type:"hello",at:Date.now(),payload:{project:Z.get(r),after:O}});const b=Z.watch(r,_=>{_.seq>O&&(O=_.seq,y(_))});for(const _ of Z.eventsSince(r,O))O=_.seq,y(_);const p=setInterval(()=>{try{o.write(`: keep
24
+ `);let x=f.searchParams.has("after")?Number(f.searchParams.get("after")):-1;y({seq:-1,type:"hello",at:Date.now(),payload:{project:X.get(r),after:x}});const b=X.watch(r,_=>{_.seq>x&&(x=_.seq,y(_))});for(const _ of X.eventsSince(r,x))x=_.seq,y(_);const p=setInterval(()=>{try{o.write(`: keep
25
25
 
26
- `)}catch{}},25e3);n.on("close",()=>{clearInterval(p),b()});return}}}if(l==="/v1/agents/scorecards"&&n.method==="GET")return s(o,200,{ok:!0,agents:ve.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(l);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return s(o,200,{ok:!0,...await ve.get(r)});if(n.method==="POST")try{const a=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},i=await ve.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 Se.fromRating(ve.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(l==="/v1/capabilities"&&n.method==="GET")return s(o,200,Or(t,{version:W,reader:d,searcher:oe,extract:h(),proxy:L}));if(l==="/v1/fusions"&&n.method==="GET"){const e={active:N.health().model||t.ner?.model||null,companions:N.companions()};let r=null;try{r=await $().status()}catch{r=null}return s(o,200,gr({cfg:t,ner:e,runtimeDoc:r}))}if(l==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(Dr.map(r=>{const a=qe(t,r);return[r,{provider:a.kind,model:a.kind==="embedded"?a.model:null,models:Br[r],threads:I.threads,...a.kind==="embedded"?I.health(r,a.model):{}}]}));return s(o,200,{...await $().status(),inProcess:e})}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(l);if(e&&n.method==="POST"){if(!H(n))return s(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const a=String(r.action||"start"),i=$(),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):a==="tune"?await i.setTunings(e[2],r.tunings):a==="profile"?await i.setProfile(e[2],r.profile):a==="pull"?await i.pullModel(e[2]):a==="install"?await i.installRunner(e[2]):a==="cancel"?i.cancelJob(e[2]):{ok:!1,error:`unknown action ${a}`};return s(o,u.ok?200:400,u)}}if((l==="/v1/rerank"||l==="/v1/decide")&&n.method==="POST"){const e=l.slice(4);let r;try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const a=await L.call(e,r);return s(o,a.status,a.body)}if(l==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await _r(e,{ensure:()=>Re(t),model:N.health().model});return s(o,r.status,r.body)}catch(r){return s(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(l==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,Math.max(t.maxBodyBytes,Math.ceil(Rr*4/3)+1024))).toString("utf8"))}catch{return s(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Cr(e,{service:h()});return s(o,r.status,r.body)}if(l==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return 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(l==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}z();const r=await se().search(e);return s(o,r.status,r.body)}if(/^\/v1\/search\/./.test(l)&&n.method==="GET"){let e;try{e=decodeURIComponent(l.slice(11))}catch{e=l.slice(11)}const r=f.searchParams.has("read")?Math.max(0,Math.min(10,Number(f.searchParams.get("read"))||0)):zr.aliasRead;z();const a=await se().search({q:e,read:r,limit:Math.max(r,5)});return s(o,a.status,a.status===200?Lr(a.body):a.body)}if(/^\/v1\/read\/./.test(l)&&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(Gr(u.body)))}if(l==="/v1/engines"&&n.method==="GET"){const e=Number(f.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:Se.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(l);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const a=Number(f.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await Se.get(r,{entries:f.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&n.method==="POST")try{const a=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},i=a.engine||Bn(r);if(!i)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const u=await Se.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(l==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=i=>{try{o.write(`data: ${JSON.stringify(i)}
26
+ `)}catch{}},25e3);n.on("close",()=>{clearInterval(p),b()});return}}}if(i==="/v1/agents/scorecards"&&n.method==="GET")return s(o,200,{ok:!0,agents:Se.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return s(o,200,{ok:!0,...await Se.get(r)});if(n.method==="POST")try{const a=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},l=await Se.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 Te.fromRating(Se.chains.get(r)||[],{...l,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:l})}catch(a){return s(o,400,{error:{message:`scorecard: ${a.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&n.method==="GET")return s(o,200,Br(t,{version:K,reader:m,searcher:q,extract:E(),proxy:ue}));if(i==="/v1/fusions"&&n.method==="GET"){const e={active:A.health().model||t.ner?.model||null,companions:A.companions()};let r=null;try{r=await C().status()}catch{r=null}return s(o,200,xr({cfg:t,ner:e,runtimeDoc:r}))}if(i==="/v1/runtime"&&n.method==="GET"){const e=Object.fromEntries(zr.map(r=>{const a=rt(t,r);return[r,{provider:a.kind,model:a.kind==="embedded"?a.model:null,models:Jr[r],threads:G.threads,...a.kind==="embedded"?G.health(r,a.model):{}}]}));return s(o,200,{...await C().status(),inProcess:e})}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&n.method==="POST"){if(!z(n))return s(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const a=String(r.action||"start"),l=C(),u=e[1]==="engines"?a==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${a}`}:a==="start"?await l.startService(e[2]):a==="stop"?await l.stopService(e[2]):a==="model"?await l.setModel(e[2],r.model):a==="tune"?await l.setTunings(e[2],r.tunings):a==="profile"?await l.setProfile(e[2],r.profile):a==="pull"?await l.pullModel(e[2]):a==="install"?await l.installRunner(e[2]):a==="cancel"?l.cancelJob(e[2]):{ok:!1,error:`unknown action ${a}`};return s(o,u.ok?200:400,u)}}if((i==="/v1/rerank"||i==="/v1/decide")&&n.method==="POST"){const e=i.slice(4);let r;try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const a=await ue.call(e,r);return s(o,a.status,a.body)}if(i==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await Mr(e,{ensure:()=>Le(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(i==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,Math.max(t.maxBodyBytes,Math.ceil(Hr*4/3)+1024))).toString("utf8"))}catch{return s(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await Gr(e,{service:E()});return s(o,r.status,r.body)}if(i==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await h().read(e);return s(o,r.status,r.body)}if(i==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}se();const r=await ae().search(e);return s(o,r.status,r.body)}if(/^\/v1\/search\/./.test(i)&&n.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const r=f.searchParams.has("read")?Math.max(0,Math.min(10,Number(f.searchParams.get("read"))||0)):Yr.aliasRead;se();const a=await ae().search({q:e,read:r,limit:Math.max(r,5)});return s(o,a.status,a.status===200?Qr(a.body):a.body)}if(/^\/v1\/read\/./.test(i)&&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||""),l=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",u=await h().read({url:r,format:l});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(Xr(u.body)))}if(i==="/v1/engines"&&n.method==="GET"){const e=Number(f.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:Te.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const a=Number(f.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await Te.get(r,{entries:f.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&n.method==="POST")try{const a=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},l=a.engine||Hn(r);if(!l)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const u=await Te.append({...a,engine:l,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(i==="/v1/teams/stream"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
27
27
 
28
- `)}catch{}};e({type:"hello",at:Date.now()});const r=V.watchAll(i=>e({type:"run",id:i.id,removed:!!i.removed})),a=setInterval(()=>{try{o.write(`: keep-alive
28
+ `)}catch{}};e({type:"hello",at:Date.now()});const r=V.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),a=setInterval(()=>{try{o.write(`: keep-alive
29
29
 
30
- `)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(a)});return}if(l==="/v1/teams/runs"&&n.method==="GET")return s(o,200,{ok:!0,runs:V.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(l==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:V.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(l);if(e){const r=e[1],a=e[2]||"";if(!a&&n.method==="GET"){const i=V.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 V.stop(r),s(o,200,{ok:!0,removed:V.remove(r)});if(a==="/stop"&&n.method==="POST"){const i=V.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:V.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 T(n,t.maxBodyBytes)).toString("utf8"))||{},u=a==="/handoff"?V.handoff(r,{taskId:i.taskId,model:i.model,by:i.by,reason:i.reason}):V.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:V.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 T(n,t.maxBodyBytes)).toString("utf8"))||{},u=String(i.by||"person").slice(0,40),S=a==="/answer"?V.answer(r,{threadId:i.threadId,text:i.text,by:u}):a==="/decide"?V.decide(r,{postId:i.postId,status:i.status,by:u}):V.post(r,{threadId:i.threadId,text:i.text,by:u,kind:i.kind,replyTo:i.replyTo});return s(o,200,{ok:!0,run:S})}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 T(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:V.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(!V.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=b=>o.write(`data: ${JSON.stringify(b)}
30
+ `)}catch{}},25e3);o.on("close",()=>{r(),clearInterval(a)});return}if(i==="/v1/teams/runs"&&n.method==="GET")return s(o,200,{ok:!0,runs:V.list({limit:f.searchParams.get("limit")||50,team:f.searchParams.get("team")||""})});if(i==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:V.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(i);if(e){const r=e[1],a=e[2]||"";if(!a&&n.method==="GET"){const l=V.get(r,{events:f.searchParams.get("events")==="1"});return l?s(o,200,{ok:!0,run:l}):s(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!a&&n.method==="DELETE")return V.stop(r),s(o,200,{ok:!0,removed:V.remove(r)});if(a==="/stop"&&n.method==="POST"){const l=V.stop(r);return l?s(o,200,{ok:!0,run:l}):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:V.checkpoint(r)})}catch(l){return s(o,404,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&n.method==="POST")try{const l=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},u=a==="/handoff"?V.handoff(r,{taskId:l.taskId,model:l.model,by:l.by,reason:l.reason}):V.claim(r,{client:l.client});return s(o,200,{ok:!0,run:u})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&n.method==="DELETE")try{return s(o,200,{ok:!0,run:V.removeThread(r,{threadId:a.slice(9),by:"person"})})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&n.method==="POST")try{const l=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},u=String(l.by||"person").slice(0,40),S=a==="/answer"?V.answer(r,{threadId:l.threadId,text:l.text,by:u}):a==="/decide"?V.decide(r,{postId:l.postId,status:l.status,by:u}):V.post(r,{threadId:l.threadId,text:l.text,by:u,kind:l.kind,replyTo:l.replyTo});return s(o,200,{ok:!0,run:S})}catch(l){return s(o,l.message.startsWith("no ")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&n.method==="POST")try{const l=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:V.append(r,l.events||[])})}catch(l){return s(o,l.message.startsWith("no run")?404:400,{error:{message:`team run: ${l.message}`,type:"team_error"}})}if(a==="/events"&&n.method==="GET"){if(!V.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 l=b=>o.write(`data: ${JSON.stringify(b)}
31
31
 
32
- `),u=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let S=Number.isFinite(u)?u:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:V.get(r),after:S}});const y=V.watch(r,b=>{b.seq==null?i(b):b.seq>S&&(S=b.seq,i(b))});for(const b of V.eventsSince(r,S))S=b.seq,i(b);const O=setInterval(()=>{try{o.write(`: keep-alive
32
+ `),u=f.searchParams.has("after")?Number(f.searchParams.get("after")):NaN;let S=Number.isFinite(u)?u:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:V.get(r),after:S}});const y=V.watch(r,b=>{b.seq==null?l(b):b.seq>S&&(S=b.seq,l(b))});for(const b of V.eventsSince(r,S))S=b.seq,l(b);const x=setInterval(()=>{try{o.write(`: keep-alive
33
33
 
34
- `)}catch{}},25e3);o.on("close",()=>{y(),clearInterval(O)});return}}}if(l==="/v1/memory/list"&&n.method==="GET")return s(o,200,{ok:!0,size:ee.size,memories:ee.list()});if(l==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=ee.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:ee.size,...r})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(l==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=ee.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:ee.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(l==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=ee.forget(String(e.query||""));return s(o,200,{ok:!0,removed:r,size:ee.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(l==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=ee.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...r,memories:ee.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(l==="/v1/memory/clear"&&n.method==="POST")return s(o,200,{ok:!0,dropped:ee.clear(),size:ee.size});if(l==="/v1/history/clear"&&n.method==="POST"){const e=D.clear();return s(o,200,{ok:!0,dropped:e,size:D.size})}if(l==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=D.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:D.size,newest:D.newest,results:r})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(l==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),a=Tn(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),S=await xn(a,O=>D.search(O,{limit:u,...i}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),y=i.type?S:[...S.filter(O=>O.type==="brief"),...S.filter(O=>O.type!=="brief")];return s(o,200,{ok:!0,size:D.size,newest:D.newest,queries:a,results:y})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(l==="/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:D.related(e,{limit:r})})}if(l==="/v1/history/status"&&n.method==="GET")return s(o,200,{ok:!0,size:D.size,newest:D.newest,bytes:D.bytes,lossless:D.lossless?{records:D.lossless.size,newest:D.lossless.newest}:null});if(l==="/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:D.size,bytes:D.bytes,newest:D.newest}},access:st.snapshot(e)})}if(l==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=st.push(Ht({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(l==="/v1/history/records"&&n.method==="PUT"){const e=D.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},a=String(r.host||"").slice(0,80),i=Number(r.at)||Date.now(),u=[];let S=0;const y={upserts:[],removes:[]},O=b=>{if(!b||b.deletedAt){b?.id&&y.removes.push(b.id);return}try{const p=br(b);p&&y.upserts.push(p)}catch{}};if(Array.isArray(r.records)){const b=e.upsert(r.records,{host:a,at:i});u.push(...b);for(const p of r.records)b.includes(p?.id)&&O(p)}if(Array.isArray(r.entries)){const b=Qe(),p=b?Sr((R,Q)=>kr(b,{salt:R,iterations:Q})):null,_=async R=>{if(!p||!R.blob)return null;const Q=await p(R.blob),we=R.blob.compression&&R.blob.compression!=="none"?Tr(xr,R.blob.compression):null;return vr(R.blob,Q,{codec:we})},J=await e.upsertEntries(r.entries,{open:_});u.push(...J.written),S+=J.sealed;for(const R of J.written)O(e.get(R))}return(y.upserts.length||y.removes.length)&&D.bulk(y),u.length&&Je({ids:u}),s(o,200,{ok:!0,written:u.length,ids:u,sealed:S,size:e.size})}catch(r){return s(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(l==="/v1/events"&&n.method==="POST"){if(!F)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=Array.isArray(e)?e:e.events;if(!Array.isArray(r))return s(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(r.length>2e3)return s(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const a=hr(F,r);return s(o,200,{ok:!0,appended:a.appended,duplicates:a.duplicates,rejected:a.rejected,cursor:F.cursor()})}catch(e){return s(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(l==="/v1/events/cursor"&&n.method==="GET")return F?s(o,200,{ok:!0,cursor:F.cursor(),count:F.count()}):s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(l==="/v1/events/stats"&&n.method==="GET"){if(!F)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=yr(F.all());return s(o,200,{ok:!0,stats:e,year:fr(e)})}if(l==="/v1/events"&&n.method==="GET"){if(!F)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=Et(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{return s(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=F.since(e,{limit:Number(f.searchParams.get("limit"))||void 0,host:f.searchParams.get("host")||null});return s(o,200,{ok:!0,events:r.events.map(a=>Ze(a)),cursor:r.cursor,more:r.more})}if(l==="/v1/events/stream"&&n.method==="GET"){if(!F)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(f.searchParams.has("cursor"))try{e=Et(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
35
- data: ${JSON.stringify({cursor:F.cursor(),count:F.count(),version:W})}
34
+ `)}catch{}},25e3);o.on("close",()=>{y(),clearInterval(x)});return}}}if(i==="/v1/memory/list"&&n.method==="GET")return s(o,200,{ok:!0,size:oe.size,memories:oe.list()});if(i==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=oe.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:oe.size,...r})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=oe.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:oe.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=oe.forget(String(e.query||""));return s(o,200,{ok:!0,removed:r,size:oe.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=oe.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...r,memories:oe.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&n.method==="POST")return s(o,200,{ok:!0,dropped:oe.clear(),size:oe.size});if(i==="/v1/history/clear"&&n.method==="POST"){const e=B.clear();return s(o,200,{ok:!0,dropped:e,size:B.size})}if(i==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=B.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:B.size,newest:B.newest,results:r})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),a=Mn(r,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},u=Math.min(30,Math.max(5,Number(e.limit)||10)*2),S=await Cn(a,x=>B.search(x,{limit:u,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),y=l.type?S:[...S.filter(x=>x.type==="brief"),...S.filter(x=>x.type!=="brief")];return s(o,200,{ok:!0,size:B.size,newest:B.newest,queries:a,results:y})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return s(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const r=String(e.question||"").trim();if(!r)return s(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const a=typeof e.model=="string"?e.model.trim():"";if(a&&!z(n))return s(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${n.socket.localPort}`,u=a?async(b,{maxTokens:p=220}={})=>{const _=new AbortController,J=setTimeout(()=>_.abort(),3e4);try{const I=Ye()||Oe(),F=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.signal,headers:{"content-type":"application/json",...I?{Authorization:`Bearer ${I}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:a,messages:[{role:"user",content:b}],stream:!1,max_tokens:p,temperature:.2})}),me=await F.json().catch(()=>({}));return F.ok?String(me?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(J)}}:null,S=te.get("identity")?.identity?.value||{},y=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,x=await nr(r,{store:B,memories:oe.list(),complete:u,previous:y,self:String(S.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return s(o,200,sr(r,x,{size:B.size,newest:B.newest}))}if(i==="/v1/history/related"&&n.method==="GET"){const e=String(f.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(f.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:B.related(e,{limit:r})})}if(i==="/v1/history/status"&&n.method==="GET")return s(o,200,{ok:!0,size:B.size,newest:B.newest,bytes:B.bytes,lossless:B.lossless?{records:B.lossless.size,newest:B.lossless.newest}:null});if(i==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:B.size,bytes:B.bytes,newest:B.newest}},access:dt.snapshot(e)})}if(i==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=dt.push(Wt({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(i==="/v1/history/records"&&n.method==="PUT"){const e=B.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},a=String(r.host||"").slice(0,80),l=Number(r.at)||Date.now(),u=[];let S=0;const y={upserts:[],removes:[]},x=b=>{if(!b||b.deletedAt){b?.id&&y.removes.push(b.id);return}try{const p=_r(b);p&&y.upserts.push(p)}catch{}};if(Array.isArray(r.records)){const b=e.upsert(r.records,{host:a,at:l});u.push(...b);for(const p of r.records)b.includes(p?.id)&&x(p)}if(Array.isArray(r.entries)){const b=qe(),p=b?Pr((I,F)=>Er(b,{salt:I,iterations:F})):null,_=async I=>{if(!p||!I.blob)return null;const F=await p(I.blob),me=I.blob.compression&&I.blob.compression!=="none"?Ar(Nr,I.blob.compression):null;return $r(I.blob,F,{codec:me})},J=await e.upsertEntries(r.entries,{open:_});u.push(...J.written),S+=J.sealed;for(const I of J.written)x(e.get(I))}return(y.upserts.length||y.removes.length)&&B.bulk(y),u.length&&Ue({ids:u}),s(o,200,{ok:!0,written:u.length,ids:u,sealed:S,size:e.size})}catch(r){return s(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&n.method==="POST"){if(!W)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=Array.isArray(e)?e:e.events;if(!Array.isArray(r))return s(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(r.length>2e3)return s(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const a=kr(W,r);return s(o,200,{ok:!0,appended:a.appended,duplicates:a.duplicates,rejected:a.rejected,cursor:W.cursor()})}catch(e){return s(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&n.method==="GET")return W?s(o,200,{ok:!0,cursor:W.cursor(),count:W.count()}):s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&n.method==="GET"){if(!W)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=Sr(W.all());return s(o,200,{ok:!0,stats:e,year:Tr(e)})}if(i==="/v1/events"&&n.method==="GET"){if(!W)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=At(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{return s(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=W.since(e,{limit:Number(f.searchParams.get("limit"))||void 0,host:f.searchParams.get("host")||null});return s(o,200,{ok:!0,events:r.events.map(a=>tt(a)),cursor:r.cursor,more:r.more})}if(i==="/v1/events/stream"&&n.method==="GET"){if(!W)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(f.searchParams.has("cursor"))try{e=At(JSON.parse(f.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
35
+ data: ${JSON.stringify({cursor:W.cursor(),count:W.count(),version:K})}
36
36
 
37
- `),ke.add(o),n.on("close",()=>ke.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=F.since(r.cursor);for(const a of r.events)o.write(`event: cloudevent
38
- data: ${JSON.stringify(Ze(a))}
37
+ `),be.add(o),n.on("close",()=>be.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=W.since(r.cursor);for(const a of r.events)o.write(`event: cloudevent
38
+ data: ${JSON.stringify(tt(a))}
39
39
 
40
- `)}}return}if(l==="/v1/history/stream"&&n.method==="GET"){const e=D.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
41
- data: ${JSON.stringify({newest:e.newest,size:e.size,version:W,prefsRevision:te.revision})}
40
+ `)}}return}if(i==="/v1/link"&&n.method==="GET")return s(o,200,c?{enabled:!0,...c.status()}:{enabled:!1,devices:[],pairing:null});if(i==="/v1/link/pair"&&n.method==="POST"){if(!c)return s(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(n.headers["x-chatpanel-link-device"])return s(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}try{return s(o,200,await c.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(r){return s(o,502,{error:{message:r?.message||String(r),type:"relay"}})}}if(i.startsWith("/v1/link/devices/")&&n.method==="DELETE"){if(!c)return s(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await c.remove(e)?s(o,200,{ok:!0}):s(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/browser"&&n.method==="GET")return s(o,200,d.status());if(i==="/v1/browser/stream"&&n.method==="GET"){d.stream(n,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const r=i==="/v1/browser/call"?await d.call(e,n):i==="/v1/browser/announce"?d.announce(e):d.result(e);return s(o,r.status,r.body)}if(i==="/v1/history/stream"&&n.method==="GET"){const e=B.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
41
+ data: ${JSON.stringify({newest:e.newest,size:e.size,version:K,prefsRevision:te.revision})}
42
42
 
43
- `),ye.add(o),n.on("close",()=>ye.delete(o));return}if(l==="/v1/history/records"&&n.method==="GET"){const e=D.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(l==="/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,...D.list({limit:e,offset:r,type:a})})}if(l==="/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=D.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(l==="/v1/history/key"&&n.method==="GET")return s(o,200,{ok:!0,hasKey:_t()});if(l==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Qo(String(e.passphrase)):Yo();const r=e.passphrase?await Xe(D,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Je(),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(l==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await Xe(D,Qe());return e.ok&&e.whole&&Je(),s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(l==="/ner"){if(n.method==="GET"){const e=await to(t);return s(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Re(t),N.state()!=="off"){if(!N.isReady()){const r=N.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 T(n,t.maxBodyBytes);let a="";try{a=JSON.parse(r.toString("utf8"))?.text||""}catch{}const i=await N.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=eo(t);if(!e){const r=N.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:N.state(),model:t.ner?.model||null})}try{const r=await T(n,t.maxBodyBytes),a=await De(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(l==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:lt(t)});try{let r=e;const a=await be(t.pro?.entitlementToken);await Re(t);const i=await Me([Ve(()=>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:Xt(i.vault,"types")||[],detector:lt(t)})}catch(r){return s(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(l==="/ner/models"){if(n.method==="GET"){const e=N.health().model||t.ner?.model||null,r=Math.round($t.totalmem()/1048576),a=Wr(Nt,{totalRamMB:r}).map(i=>({...i,installed:N.modelOnDisk(i.id)}));for(const i of[e,...N.modelsOnDisk()])!i||a.some(u=>u.id===i)||a.push({id:i,label:i,lang:"—",custom:!0,installed:N.modelOnDisk(i),note:"Custom model (from Hugging Face)."});return s(o,200,{active:e,companions:N.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Wo(),recommendation:Ot(a,{totalRamMB:r},[]),state:N.state(),progress:N.progress(),available:a})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const a=Math.round($t.totalmem()/1048576),i=Ot(Nt.map(u=>({...u,installed:N.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(!(Mt(u)||Bt(u)))return s(o,400,{error:{message:`unknown or invalid model id in union: ${u}`,type:"bad_model"}});const i=r||t.ner?.model||N.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=a.filter(u=>u!==i),r&&Jt(t,r);try{he(t,ne())}catch{}return(async()=>{r&&await N.setModel(r,{onLog:S=>console.log(S)});const u=Fo(t.ner,{log:S=>console.log(S)});for(const S of N.companions())u.includes(S.model)||await N.removeCompanion(S.model);for(const S of u)await N.addCompanion(S,{onLog:y=>console.log(y),allowDownload:t.ner.allowDownload!==!1});N.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),s(o,202,{accepted:!0,active:i,union:t.ner.union,companions:N.companions(),state:N.state()})}if(!r||!(Mt(r)||Bt(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Jt(t,r);try{he(t,ne())}catch{}return N.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:N.state(),progress:N.progress()})}}if(l==="/stt/models"){if(n.method==="GET"){const e=B.health().model||t.stt?.model||Ie,r=Kr.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:Zr})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(Qr(r)||Yr(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&Xr(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{he(t,ne())}catch{}return B.setModel(r,{onLog:i=>console.log(i),dtype:a||t.stt.dtype||"auto",warmMs:t.stt.warmMs,speaker:ct(t,{installing:!0})}),s(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:B.state(),progress:B.progress(),speaker:{id:A.activeModel(),state:A.state(),installed:A.modelOnDisk()}})}}if(l==="/diarize/model"){if(n.method==="GET"){const e=A.activeModel(),r=Ur.map(a=>({...a,installed:A.modelOnDisk(a.id)})).sort((a,i)=>(i.id===e?1:0)-(a.id===e?1:0));return s(o,200,{active:e,state:A.state(),threshold:A.activeThreshold(),progress:A.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!Pt(r))return s(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await A.setModel(r,{log:a=>console.log(a)}))return s(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{he(t,ne())}catch{}return A.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:a=>console.log(a)}),s(o,202,{accepted:!0,active:A.activeModel(),state:A.state(),threshold:A.activeThreshold(),progress:A.progress()})}return A.download({onLog:a=>console.log(a)}),s(o,202,{accepted:!0,active:A.activeModel(),state:A.state(),threshold:A.activeThreshold(),progress:A.progress()})}}if(l==="/tts/models"){if(n.method==="GET"){const e=P.health().model||t.tts?.model||Lt(et()),r=et(),a=Dt.find(u=>u.id===e)||null,i=Dt.map(u=>({...u,installed:P.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:P.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:P.state(),progress:P.progress(),available:i,voice:t.tts?.voice||(ze(e)==="pocket-tts"?je:ge),arch:P.arch(),supportsVoices:P.arch()?P.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:P.arch()?P.supportsCustomVoices():!!a?.customVoices,sampleRate:P.sampleRate(),voices:P.isPocket()||!P.arch()&&ze(e)==="pocket-tts"?(P.builtinVoices().length?P.builtinVoices():sn).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:P.builtinVoices().includes(u)})):P.arch()&&P.arch()!=="style-tts2"?[]:qr.map(u=>({...u,installed:P.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:P.health().dtype,runtime:P.health().runtime,dtypes:on})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(en(r)||tn(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=Y.parseCustomVoice(a);if(!(u?!!Y.getVoice(u):Le(a)||Ct(a)&&Rt(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&rn(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:It,voice:ge,allowDownload:!0}),r&&(t.tts.model=r),a&&(t.tts.voice=a),r&&!a){const u=nn(r),S=Y.parseCustomVoice(t.tts.voice||""),y=!!(S&&Y.getVoice(S));if(u&&!y)if(ze(r)==="pocket-tts")t.tts.voice=je;else{const b=Y.listVoices();t.tts.voice=b.length?`custom:${b[0].id}`:""}else!u&&y&&(t.tts.voice=ge);const O=ze(r)==="pocket-tts";O&&!Y.parseCustomVoice(t.tts.voice||"")&&!Le(t.tts.voice)&&(t.tts.voice=je),!O&&Le(t.tts.voice)&&(t.tts.voice=ge)}i&&(t.tts.dtype=i==="auto"?null:i);try{he(t,ne())}catch{}return r&&P.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:P.state(),progress:P.progress()})}}if(l==="/tts/voices"){if(n.method==="GET")return s(o,200,{voices:Y.listVoices(),usable:P.supportsCustomVoices(),embedder:A.activeModel(),embedderReady:A.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,i=e&&typeof e.id=="string"?e.id.trim():"";if(i){if(!Y.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,{...Y.renameVoice(i,r),usable:P.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(!A.isReady()){const p=A.download({onLog:R=>console.log(R)}),_=Symbol("timeout"),J=await Promise.race([p.then(()=>null).catch(R=>R),new Promise(R=>setTimeout(()=>R(_),Un))]);if(J===_||!A.isReady())return s(o,503,{error:{message:J===_?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${A.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:A.progress()})}const u=Float32Array.from(a),S=await A.embed(u);let y=null;try{const p=await P.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:_=>console.log(_)});p&&(y=await p.encodeVoice(Hn(u,16e3,24e3)))}catch(p){console.log(`[tts] pocket conditioning unavailable for this voice (${p.message})`)}const O=i?Y.replaceVoice(i,{vec:S,pocket:y}):Y.saveVoice({name:r,vec:S,pocket:y}),b=i&&r&&r!==O.name?Y.renameVoice(i,r):O;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${b.name}" (${(O.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...O,...b,usable:P.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=Y.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const a=Y.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:ge;try{he(t,ne())}catch{}}return s(o,200,{deleted:r,voice:t.tts?.voice})}}if((l==="/tts"||l==="/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 T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>jt)return s(o,413,{error:{message:`text too long (max ${jt} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=an(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,S=u||(i?i.voice:t.tts?.voice||ge);if(i&&!dn(S))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const y=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(y!=="wav"&&y!=="pcm")return s(o,400,{error:{message:`unsupported response_format "${y}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(i){const{audio:fe,contentType:U,redacted:He}=await ln({dest:i,text:r,voice:S,speed:a,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await be(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":U,"Content-Length":String(fe.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(He)}),o.end(fe)}if(!await P.ready({onLog:fe=>console.log(fe),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Lt(et()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:P.health().error||"tts model not ready",type:"tts_unavailable"}});const b=cn({requested:u,configured:S,engine:P,voices:Y,isPocketVoice:Le,isKnownVoice:Ct,isValidVoiceId:Rt,defaultVoice:ge,defaultPocketVoice:je});if(!b.ok)return s(o,b.status,{error:{message:b.message,type:b.type}});const{voice:p,customId:_,speakerEmbedding:J}=b,R=await P.synth(r,{voice:p,speed:a,speakerEmbedding:J}),Q=P.sampleRate(),we=y==="pcm"?Buffer.from(new Float32Array(R).buffer):P.toWav(R,Q);return o.writeHead(200,{"Content-Type":y==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(we.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Q),..._||P.isPocket()||P.supportsVoices()?{"X-Tts-Voice":p}:{}}),o.end(we)}catch(O){return s(o,500,{error:{message:O.message,type:"tts_failed"}})}}if(l==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=Vr(await T(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(p){return s(o,p.code===413?413:415,{error:{message:p.message,type:"bad_request"}})}const r=p=>e.find(_=>_.name===p&&!_.filename)?.data.toString("utf8").trim()||"",a=e.find(p=>p.name==="file"&&p.filename)||e.find(p=>p.filename);if(!a?.data?.length)return s(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let i;try{i=await Fr(a.data)}catch(p){return s(o,p.code===415?415:500,{error:{message:p.message,type:"unsupported_media"}})}const u=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",S=qe(t,"stt");let y=null;if(S.kind==="remote"||S.kind==="container")try{y=At(S,{fetchImpl:De})}catch(p){return s(o,500,{error:{message:`stt provider: ${p.message}`,type:"bad_provider"}})}!y&&!B.isReady()&&B.init({model:t.stt?.model||Ie,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ct(t),onLog:p=>console.log(p)});const O=r("diarize")==="true"&&t.stt?.diarize!==!1;O&&!A.isReady()&&A.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:p=>console.log(p)});const b=Date.now();try{const{id:p}=B.createSession({lang:r("language")||void 0,diarize:O,interims:!1,remote:y}),_=[];let J=null;B.subscribe(p,U=>{U.type==="final"&&U.text?_.push(U):U.type==="language"&&(J=U.lang)});const R=16e3*5;for(let U=0;U<i.pcm.length;U+=R)B.pushAudio(p,i.pcm.subarray(U,Math.min(i.pcm.length,U+R)));await B.endSession(p);let Q=0;const we=_.map((U,He)=>{const ro=Q,no=(U.durationMs||0)/1e3;return Q+=no,{id:He,start:Math.round(ro*100)/100,end:Math.round(Q*100)/100,text:U.text,...U.speaker?{speaker:U.speaker}:{}}}),fe=we.map(U=>U.text).join(" ").replace(/\s+/g," ").trim();return u==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(fe)):u==="verbose_json"?s(o,200,{task:"transcribe",language:J||r("language")||null,duration:Math.round(i.seconds*100)/100,text:fe,segments:we,provider:S.kind,took_ms:Date.now()-b}):s(o,200,{text:fe})}catch(p){return s(o,p.code==="too_many_sessions"?429:500,{error:{message:p.message,type:p.code||"stt_error"}})}}if(l==="/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 T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=qe(t,"stt");let a=null;if(r.kind==="remote"||r.kind==="container")try{a=At(r,{fetchImpl:De})}catch(u){return s(o,500,{error:{message:`stt provider: ${u.message}`,type:"bad_provider"}})}!a&&!B.isReady()&&B.init({model:t.stt?.model||Ie,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ct(t),onLog:u=>console.log(u)});const i=e?.diarize===!0&&t.stt?.diarize!==!1;i&&!A.isReady()&&A.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});try{const{id:u}=B.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:i,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:a});return s(o,201,{id:u,state:B.state()})}catch(u){return s(o,u.code==="too_many_sessions"?429:500,{error:{message:u.message,type:u.code||"stt_error"}})}}{const e=l.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 T(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=p=>o.write(`data: ${JSON.stringify(p)}
43
+ `),he.add(o),n.on("close",()=>he.delete(o));return}if(i==="/v1/history/records"&&n.method==="GET"){const e=B.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(i==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(f.searchParams.get("limit"))||50)),r=Math.max(0,Number(f.searchParams.get("offset"))||0),a=f.searchParams.get("type")||null;return s(o,200,{ok:!0,...B.list({limit:e,offset:r,type:a})})}if(i==="/v1/history/get"&&n.method==="GET"){const e=f.searchParams.get("maxChars")!=null?Math.max(1,Number(f.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(f.searchParams.get("offset"))||0),a=B.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(i==="/v1/history/key"&&n.method==="GET")return s(o,200,{ok:!0,hasKey:Pt()});if(i==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Xo(String(e.passphrase)):qo();const r=e.passphrase?await ot(B,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ue(),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(i==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await ot(B,qe());return e.ok&&e.whole&&Ue(),s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(n.method==="GET"){const e=await no(t);return s(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Le(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 T(n,t.maxBodyBytes);let a="";try{a=JSON.parse(r.toString("utf8"))?.text||""}catch{}const l=await A.detect(a);return s(o,200,{entities:l})}catch(r){return s(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=ro(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 T(n,t.maxBodyBytes),a=await Ie(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),l=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(l)}catch(r){return s(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:mt(t)});try{let r=e;const a=await we(t.pro?.entitlementToken);await Le(t);const l=await De([Qe(()=>r,u=>{r=u})],t.redaction,{isPro:a});return s(o,200,{text:r,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:to(l.vault,"types")||[],detector:mt(t)})}catch(r){return s(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(n.method==="GET"){const e=A.health().model||t.ner?.model||null,r=Math.round(Nt.totalmem()/1048576),a=rn(Ct,{totalRamMB:r}).map(l=>({...l,installed:A.modelOnDisk(l.id)}));for(const l of[e,...A.modelsOnDisk()])!l||a.some(u=>u.id===l)||a.push({id:l,label:l,lang:"—",custom:!0,installed:A.modelOnDisk(l),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:Yo(),recommendation:$t(a,{totalRamMB:r},[]),state:A.state(),progress:A.progress(),available:a})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const a=Math.round(Nt.totalmem()/1048576),l=$t(Ct.map(u=>({...u,installed:A.modelOnDisk(u.id)})),{totalRamMB:a},[]);e={id:l.primary,union:l.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const a=[...new Set(e.union.map(u=>String(u||"").trim()).filter(Boolean))];for(const u of a)if(!(Dt(u)||Rt(u)))return s(o,400,{error:{message:`unknown or invalid model id in union: ${u}`,type:"bad_model"}});const l=r||t.ner?.model||A.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=a.filter(u=>u!==l),r&&Ut(t,r);try{pe(t,ne())}catch{}return(async()=>{r&&await A.setModel(r,{onLog:S=>console.log(S)});const u=Qo(t.ner,{log:S=>console.log(S)});for(const S of A.companions())u.includes(S.model)||await A.removeCompanion(S.model);for(const S of u)await A.addCompanion(S,{onLog:y=>console.log(y),allowDownload:t.ner.allowDownload!==!1});A.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),s(o,202,{accepted:!0,active:l,union:t.ner.union,companions:A.companions(),state:A.state()})}if(!r||!(Dt(r)||Rt(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Ut(t,r);try{pe(t,ne())}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(i==="/stt/models"){if(n.method==="GET"){const e=D.health().model||t.stt?.model||Je,r=nn.map(a=>({...a,installed:D.modelOnDisk(a.id)}));return e&&!r.some(a=>a.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:D.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:D.state(),progress:D.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:D.health().dtype,runtime:D.health().runtime,dtypes:ln})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(sn(r)||an(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&dn(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{pe(t,ne())}catch{}return D.setModel(r,{onLog:l=>console.log(l),dtype:a||t.stt.dtype||"auto",warmMs:t.stt.warmMs,speaker:ht(t,{installing:!0})}),s(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:D.state(),progress:D.progress(),speaker:{id:P.activeModel(),state:P.state(),installed:P.modelOnDisk()}})}}if(i==="/diarize/model"){if(n.method==="GET"){const e=P.activeModel(),r=qr.map(a=>({...a,installed:P.modelOnDisk(a.id)})).sort((a,l)=>(l.id===e?1:0)-(a.id===e?1:0));return s(o,200,{active:e,state:P.state(),threshold:P.activeThreshold(),progress:P.progress(),available:r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r){if(!Bt(r))return s(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await P.setModel(r,{log:a=>console.log(a)}))return s(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=r:t.stt={enabled:!0,diarize:!0,diarizeModel:r};try{pe(t,ne())}catch{}return P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:a=>console.log(a)}),s(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}return P.download({onLog:a=>console.log(a)}),s(o,202,{accepted:!0,active:P.activeModel(),state:P.state(),threshold:P.activeThreshold(),progress:P.progress()})}}if(i==="/tts/models"){if(n.method==="GET"){const e=$.health().model||t.tts?.model||Gt(nt()),r=nt(),a=It.find(u=>u.id===e)||null,l=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&&!l.some(u=>u.id===e)&&l.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:l,voice:t.tts?.voice||(He(e)==="pocket-tts"?ze:fe),arch:$.arch(),supportsVoices:$.arch()?$.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:$.arch()?$.supportsCustomVoices():!!a?.customVoices,sampleRate:$.sampleRate(),voices:$.isPocket()||!$.arch()&&He(e)==="pocket-tts"?($.builtinVoices().length?$.builtinVoices():fn).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:$.builtinVoices().includes(u)})):$.arch()&&$.arch()!=="style-tts2"?[]:cn.map(u=>({...u,installed:$.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:$.health().dtype,runtime:$.health().runtime,dtypes:pn})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(un(r)||mn(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=Z.parseCustomVoice(a);if(!(u?!!Z.getVoice(u):Ge(a)||jt(a)&&Lt(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&hn(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Jt,voice:fe,allowDownload:!0}),r&&(t.tts.model=r),a&&(t.tts.voice=a),r&&!a){const u=yn(r),S=Z.parseCustomVoice(t.tts.voice||""),y=!!(S&&Z.getVoice(S));if(u&&!y)if(He(r)==="pocket-tts")t.tts.voice=ze;else{const b=Z.listVoices();t.tts.voice=b.length?`custom:${b[0].id}`:""}else!u&&y&&(t.tts.voice=fe);const x=He(r)==="pocket-tts";x&&!Z.parseCustomVoice(t.tts.voice||"")&&!Ge(t.tts.voice)&&(t.tts.voice=ze),!x&&Ge(t.tts.voice)&&(t.tts.voice=fe)}l&&(t.tts.dtype=l==="auto"?null:l);try{pe(t,ne())}catch{}return r&&$.setModel(r,{onLog:u=>console.log(u),dtype:l||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(i==="/tts/voices"){if(n.method==="GET")return s(o,200,{voices:Z.listVoices(),usable:$.supportsCustomVoices(),embedder:P.activeModel(),embedderReady:P.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!Z.getVoice(l))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,{...Z.renameVoice(l,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(!P.isReady()){const p=P.download({onLog:I=>console.log(I)}),_=Symbol("timeout"),J=await Promise.race([p.then(()=>null).catch(I=>I),new Promise(I=>setTimeout(()=>I(_),qn))]);if(J===_||!P.isReady())return s(o,503,{error:{message:J===_?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${P.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:P.progress()})}const u=Float32Array.from(a),S=await P.embed(u);let y=null;try{const p=await $.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:_=>console.log(_)});p&&(y=await p.encodeVoice(es(u,16e3,24e3)))}catch(p){console.log(`[tts] pocket conditioning unavailable for this voice (${p.message})`)}const x=l?Z.replaceVoice(l,{vec:S,pocket:y}):Z.saveVoice({name:r,vec:S,pocket:y}),b=l&&r&&r!==x.name?Z.renameVoice(l,r):x;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${b.name}" (${(x.kinds||[]).join(" + ")}, sample discarded)`),s(o,l?200:201,{...x,...b,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=Z.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const a=Z.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:fe;try{pe(t,ne())}catch{}}return s(o,200,{deleted:r,voice:t.tts?.voice})}}if((i==="/tts"||i==="/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 T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>zt)return s(o,413,{error:{message:`text too long (max ${zt} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=gn(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,S=u||(l?l.voice:t.tts?.voice||fe);if(l&&!bn(S))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const y=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(y!=="wav"&&y!=="pcm")return s(o,400,{error:{message:`unsupported response_format "${y}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:ye,contentType:U,redacted:Ke}=await wn({dest:l,text:r,voice:S,speed:a,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await we(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":U,"Content-Length":String(ye.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(Ke)}),o.end(ye)}if(!await $.ready({onLog:ye=>console.log(ye),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Gt(nt()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:$.health().error||"tts model not ready",type:"tts_unavailable"}});const b=vn({requested:u,configured:S,engine:$,voices:Z,isPocketVoice:Ge,isKnownVoice:jt,isValidVoiceId:Lt,defaultVoice:fe,defaultPocketVoice:ze});if(!b.ok)return s(o,b.status,{error:{message:b.message,type:b.type}});const{voice:p,customId:_,speakerEmbedding:J}=b,I=await $.synth(r,{voice:p,speed:a,speakerEmbedding:J}),F=$.sampleRate(),me=y==="pcm"?Buffer.from(new Float32Array(I).buffer):$.toWav(I,F);return o.writeHead(200,{"Content-Type":y==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(me.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(F),..._||$.isPocket()||$.supportsVoices()?{"X-Tts-Voice":p}:{}}),o.end(me)}catch(x){return s(o,500,{error:{message:x.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=tn(await T(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(p){return s(o,p.code===413?413:415,{error:{message:p.message,type:"bad_request"}})}const r=p=>e.find(_=>_.name===p&&!_.filename)?.data.toString("utf8").trim()||"",a=e.find(p=>p.name==="file"&&p.filename)||e.find(p=>p.filename);if(!a?.data?.length)return s(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await on(a.data)}catch(p){return s(o,p.code===415?415:500,{error:{message:p.message,type:"unsupported_media"}})}const u=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",S=rt(t,"stt");let y=null;if(S.kind==="remote"||S.kind==="container")try{y=Mt(S,{fetchImpl:Ie})}catch(p){return s(o,500,{error:{message:`stt provider: ${p.message}`,type:"bad_provider"}})}!y&&!D.isReady()&&D.init({model:t.stt?.model||Je,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ht(t),onLog:p=>console.log(p)});const x=r("diarize")==="true"&&t.stt?.diarize!==!1;x&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:p=>console.log(p)});const b=Date.now();try{const{id:p}=D.createSession({lang:r("language")||void 0,diarize:x,interims:!1,remote:y}),_=[];let J=null;D.subscribe(p,U=>{U.type==="final"&&U.text?_.push(U):U.type==="language"&&(J=U.lang)});const I=16e3*5;for(let U=0;U<l.pcm.length;U+=I)D.pushAudio(p,l.pcm.subarray(U,Math.min(l.pcm.length,U+I)));await D.endSession(p);let F=0;const me=_.map((U,Ke)=>{const io=F,lo=(U.durationMs||0)/1e3;return F+=lo,{id:Ke,start:Math.round(io*100)/100,end:Math.round(F*100)/100,text:U.text,...U.speaker?{speaker:U.speaker}:{}}}),ye=me.map(U=>U.text).join(" ").replace(/\s+/g," ").trim();return u==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(ye)):u==="verbose_json"?s(o,200,{task:"transcribe",language:J||r("language")||null,duration:Math.round(l.seconds*100)/100,text:ye,segments:me,provider:S.kind,took_ms:Date.now()-b}):s(o,200,{text:ye})}catch(p){return s(o,p.code==="too_many_sessions"?429:500,{error:{message:p.message,type:p.code||"stt_error"}})}}if(i==="/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 T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=rt(t,"stt");let a=null;if(r.kind==="remote"||r.kind==="container")try{a=Mt(r,{fetchImpl:Ie})}catch(u){return s(o,500,{error:{message:`stt provider: ${u.message}`,type:"bad_provider"}})}!a&&!D.isReady()&&D.init({model:t.stt?.model||Je,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,speaker:ht(t),onLog:u=>console.log(u)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!P.isReady()&&P.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});try{const{id:u}=D.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:l,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:a});return s(o,201,{id:u,state:D.state()})}catch(u){return s(o,u.code==="too_many_sessions"?429:500,{error:{message:u.message,type:u.code||"stt_error"}})}}{const e=i.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 T(n,t.maxBodyBytes);return D.pushAudio(r,D.toFloat32(a)),s(o,200,{ok:!0,state:D.state()})}catch(a){return s(o,a.code==="no_session"?404:400,{error:{message:a.message,type:a.code||"stt_error"}})}if(e[2]==="/events"&&n.method==="GET"){const a=D.getSession(r);if(!a)return s(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const l=p=>o.write(`data: ${JSON.stringify(p)}
44
44
 
45
- `),u=a.redact?await be(t.pro?.entitlementToken):!0,S=async p=>{if(p.type!=="final"||!a.redact)return p;try{let _=p.text;return await Me([Ve(()=>_,J=>{_=J})],t.redaction,{isPro:u}),{...p,text:_}}catch{return p}};i({type:"state",state:a.remote?"ready":B.state()});const y=setInterval(()=>{const p=a.remote?"ready":B.state();if(p==="downloading"||p==="loading"){i({type:"progress",state:p,...B.progress()||{}});return}if(p==="error"){i({type:"error",code:"model_failed",message:B.health().error||"model failed to load",fatal:!0}),clearInterval(y);return}if(a.diarize){const _=A.state();if(_==="downloading"||_==="loading"){i({type:"diarize-progress",state:_,...A.progress()||{}});return}}i({type:"state",state:p}),clearInterval(y)},500);y.unref?.();let O=Promise.resolve();const b=B.subscribe(r,p=>{O=O.then(async()=>{i(await S(p)),p.type==="end"&&(clearInterval(y),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(y),b?.()});return}if(!e[2]&&n.method==="DELETE")return await B.endSession(r),s(o,200,{ok:!0})}}if(l==="/logs"&&n.method==="GET")return s(o,200,{entries:[...X].reverse()});if(l==="/config"&&n.method==="GET"){const e=await be(t.pro?.entitlementToken);return s(o,200,zt(t,{proUnlocked:e}))}if(l==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{hn(t,e)}catch(y){if(y?.code==="SHAPE")return s(o,400,{error:y.message});throw y}bt(t),JSON.stringify(t.sandbox||null)!==r&&$e?.restart("sandbox settings changed");try{he(t,ne())}catch(y){return s(o,500,{error:`could not persist config: ${y.message}`})}const a=t.redaction?.detection,i=!a||!a.backend||a.backend==="off",u=N.state();t.ner?.autostart&&i&&u!=="ready"&&u!=="loading"&&u!=="downloading"&&N.setModel(t.ner.model,{onLog:y=>console.log(y)}).then(y=>{y&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const S=await be(t.pro?.entitlementToken);return s(o,200,zt(t,{proUnlocked:S}))}if(n.method==="GET"&&l==="/skills")return ce(n,o,t,`/skills${Te(f,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="GET"&&l==="/skills-quarantined")return ce(n,o,t,`/skills-quarantined${Te(f,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(l==="/skills"&&n.method==="POST")return H(n)?ce(n,o,t,"/skills",{method:"POST",timeoutMs:15e3}):s(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(l)&&n.method==="DELETE"){const e=decodeURIComponent(l.slice(8));return ut(e)?s(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):H(n)?ce(n,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):s(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(l)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(l),r=decodeURIComponent(e[1]);return ut(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?s(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):H(n)?ce(n,o,t,`/skills/${encodeURIComponent(r)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):s(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(n.method==="GET"&&l==="/agent-defs")return ce(n,o,t,`/agent-defs${Te(f,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(l)){const e=decodeURIComponent(l.slice(12));return ut(e)?s(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):ce(n,o,t,`/agent-defs/${encodeURIComponent(e)}${Te(f,t)}`)}if(l.startsWith("/a2a/")){if(!H(n))return s(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&l==="/a2a/agents")return s(o,200,{agents:Io()});if(n.method==="POST"&&l==="/a2a/card"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&Mo(e.url||"");const r=await Ce(e.url,{force:!!e.force,auth:String(e.auth||"")});return s(o,200,{ok:!0,card:r.card,fingerprint:r.fingerprint,fresh:r.fresh,changed:!!r.changed,url:r.url})}if(n.method==="POST"&&l==="/a2a/message"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Ce(e.url,{auth:String(e.auth||"")})).card,a=await Bo({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),returnImmediately:!!e.returnImmediately,contextId:String(e.contextId||""),taskId:String(e.taskId||"")});return s(o,200,{ok:!0,...a})}if(n.method==="POST"&&l==="/a2a/message/stream"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Ce(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=(i,u)=>o.write(`event: ${i}
45
+ `),u=a.redact?await we(t.pro?.entitlementToken):!0,S=async p=>{if(p.type!=="final"||!a.redact)return p;try{let _=p.text;return await De([Qe(()=>_,J=>{_=J})],t.redaction,{isPro:u}),{...p,text:_}}catch{return p}};l({type:"state",state:a.remote?"ready":D.state()});const y=setInterval(()=>{const p=a.remote?"ready":D.state();if(p==="downloading"||p==="loading"){l({type:"progress",state:p,...D.progress()||{}});return}if(p==="error"){l({type:"error",code:"model_failed",message:D.health().error||"model failed to load",fatal:!0}),clearInterval(y);return}if(a.diarize){const _=P.state();if(_==="downloading"||_==="loading"){l({type:"diarize-progress",state:_,...P.progress()||{}});return}}l({type:"state",state:p}),clearInterval(y)},500);y.unref?.();let x=Promise.resolve();const b=D.subscribe(r,p=>{x=x.then(async()=>{l(await S(p)),p.type==="end"&&(clearInterval(y),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(y),b?.()});return}if(!e[2]&&n.method==="DELETE")return await D.endSession(r),s(o,200,{ok:!0})}}if(i==="/logs"&&n.method==="GET")return s(o,200,{entries:[...R].reverse()});if(i==="/config"&&n.method==="GET"){const e=await we(t.pro?.entitlementToken);return s(o,200,Ht(t,{proUnlocked:e}))}if(i==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{xn(t,e)}catch(y){if(y?.code==="SHAPE")return s(o,400,{error:y.message});throw y}St(t),JSON.stringify(t.sandbox||null)!==r&&Ae?.restart("sandbox settings changed");try{pe(t,ne())}catch(y){return s(o,500,{error:`could not persist config: ${y.message}`})}const a=t.redaction?.detection,l=!a||!a.backend||a.backend==="off",u=A.state();t.ner?.autostart&&l&&u!=="ready"&&u!=="loading"&&u!=="downloading"&&A.setModel(t.ner.model,{onLog:y=>console.log(y)}).then(y=>{y&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const S=await we(t.pro?.entitlementToken);return s(o,200,Ht(t,{proUnlocked:S}))}if(n.method==="GET"&&i==="/skills")return ce(n,o,t,`/skills${xe(f,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(n.method==="GET"&&i==="/skills-quarantined")return ce(n,o,t,`/skills-quarantined${xe(f,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&n.method==="POST")return z(n)?ce(n,o,t,"/skills",{method:"POST",timeoutMs:15e3}):s(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(i)&&n.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return yt(e)?s(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):z(n)?ce(n,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):s(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(i)&&n.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]);return yt(r)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?s(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):z(n)?ce(n,o,t,`/skills/${encodeURIComponent(r)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):s(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(n.method==="GET"&&i==="/agent-defs")return ce(n,o,t,`/agent-defs${xe(f,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(n.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return yt(e)?s(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):ce(n,o,t,`/agent-defs/${encodeURIComponent(e)}${xe(f,t)}`)}if(i.startsWith("/a2a/")){if(!z(n))return s(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(n.method==="GET"&&i==="/a2a/agents")return s(o,200,{agents:Jo()});if(n.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&Do(e.url||"");const r=await je(e.url,{force:!!e.force,auth:String(e.auth||"")});return s(o,200,{ok:!0,card:r.card,fingerprint:r.fingerprint,fresh:r.fresh,changed:!!r.changed,url:r.url})}if(n.method==="POST"&&i==="/a2a/message"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await je(e.url,{auth:String(e.auth||"")})).card,a=await Ro({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),returnImmediately:!!e.returnImmediately,contextId:String(e.contextId||""),taskId:String(e.taskId||"")});return s(o,200,{ok:!0,...a})}if(n.method==="POST"&&i==="/a2a/message/stream"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await je(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=(l,u)=>o.write(`event: ${l}
46
46
  data: ${JSON.stringify(u)}
47
47
 
48
- `);try{const i=await Do({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:u=>a(u.kind,{kind:u.kind,task:u.task,message:u.message})});a("done",i)}catch(i){a("error",{code:i.code||"ERROR",message:i.message})}return o.end()}if(n.method==="POST"&&l==="/a2a/task"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await Ce(e.url,{auth:String(e.auth||"")})).card,a=e.cancel?await Ro({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await Co({card:r,id:String(e.id||""),auth:String(e.auth||"")});return s(o,200,{ok:!0,...a})}return s(o,404,{error:{message:`no such a2a route: ${l}`,type:"invalid_request"}})}catch(e){const r=e instanceof vt||e?.name==="A2AClientError"?e.code:"ERROR";return s(o,e instanceof vt&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(l==="/agent-defs/export"||l==="/agent-defs/export-plan"))return H(n)?ce(n,o,t,l,{method:"POST",timeoutMs:15e3}):s(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(l)){const e=decodeURIComponent(l.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?s(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):ce(n,o,t,`/skills/${encodeURIComponent(e)}${Te(f,t)}`,{pick:r=>({skill:r?.skill||null})})}if(l==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(l)){if(!H(n))return s(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(l==="/channels"&&n.method==="GET"||l!=="/channels"&&n.method==="POST"))return s(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await Oe(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=_e(t.bridge?.token);try{const a=n.method==="POST"?(await T(n,t.maxBodyBytes)).toString("utf8"):"",i=await fetch(`${e}${l}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body: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(l)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(l),r=decodeURIComponent(e[1]),a=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a))?s(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):ce(n,o,t,`/skills/${encodeURIComponent(r)}/file/${a}${Te(f,t)}`)}if(n.method==="GET"&&/\/models$/.test(l)){const e=await k(),r=e.sig!==void 0&&e.sig!==E;return E=e.sig,s(o,200,await wn(t,{serviceHealth:async()=>e,fresh:r}))}if(Vn.some(e=>l===e||l.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${W}) has no ${l} — update it to use this feature`,type:"unknown_endpoint"}});const j=Cn(l,n.headers,t);let ae;try{ae=await T(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 ie=null,v=null,G=ae,re=0,q=0,le=0,me=!1,de=!0;const K=t.logRequests&&j.redactable&&n.method==="POST"?Dn(ue):null;if(j.redactable&&n.method==="POST"&&ae.length){try{v=JSON.parse(ae.toString("utf8"))}catch{v=null}if(v&&Rn(v,j.kind))G=ae;else if(v){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(v.tools)&&v.tools.length){const b=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):_n,p=e.narrowAll?null:J=>!En.test(Kt(J)),_=v.tools.length;v.tools=ho(v.tools,Pn(v,j.kind),{cap:b,keep:p,name:Kt,description:$n}),le=_-v.tools.length}de=await be(t.pro?.entitlementToken);const r=un(t,de);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"}});me=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&H(n),me||await Re(t);const a=me?[]:j.adapter.collectSegments(v,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const u=K?K.clock():0,{vault:S,count:y,sanitized:O}=me?{vault:null,count:0,sanitized:0}:await Me(a,t.redaction,{signal:i.signal,isPro:de,onEgress:b=>st.push(Ht({ts:Date.now(),client:"redaction",tool:`detect:${b.backend}@${b.host||"local"}`,ok:b.ok,ms:b.ms,error:b.error}))});if(K&&K.lap("redact",u),ie=S,re=y,q=O||0,y>0&&o.setHeader("x-chatpanel-redacted",String(y)),!de&&y>0){mn(t,de);try{he(t,ne())}catch{}}if(!me&&Array.isArray(v.tools)&&v.tools.length&&typeof j.adapter.injectSystemNote=="function"){const b=tt(v?.model,t,j.kind,{destination:String(n.headers["x-chatpanel-destination"]||v?.chatpanel?.destination||"").trim(),down:_=>!!_.service&&g.fn(_.id)==="down"}),p=!(b&&b.type==="api");j.adapter.injectSystemNote(v,fo({toolData:t.tools?.toolData,ownTools:p}))}else!me&&y>0&&typeof j.adapter.injectSystemNote=="function"&&j.adapter.injectSystemNote(v,go());G=Buffer.from(JSON.stringify(v),"utf8")}}const mt=yo({vault:ie,toolData:t.tools?.toolData}),Pe=v&&typeof v.chatpanel=="object"&&v.chatpanel||null;if(Pe&&(delete v.chatpanel,G=Buffer.from(JSON.stringify(v),"utf8")),typeof v?.model=="string"&&v.model.startsWith("fusion:")){const e=wr(v.model,t,await k());if(e?.error)return K?.commit(),s(o,400,{error:{message:e.error,type:"fusion"}});e&&(v.model=e.model,G=Buffer.from(JSON.stringify(v),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const pe={destination:String(n.headers["x-chatpanel-destination"]||Pe?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Pe?.reach||"").trim(),run:Kn(n.headers["x-chatpanel-run"],Pe?.run)},Ue=await k(),pt=e=>!!e.service&&Ue(e.id)==="down";let M=tt(v?.model,t,j.kind,{destination:pe.destination,down:pt});if(M?.type==="agent"&&v?.model&&!pe.destination&&!vn(M,v.model)&&(await kn(t,{serviceHealth:async()=>Ue}),M=tt(v?.model,t,j.kind,{destination:pe.destination,down:pt})),M?.service&&Ue(M.id)==="down")return K?.commit(),s(o,503,{error:{message:`${M.id} is not running — the model ${JSON.stringify(v?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:M.service}});if(pe.destination&&(!M||M.id!==pe.destination))return K?.commit(),s(o,404,{error:{message:`no destination "${pe.destination}" is configured on this gateway`,type:"unknown_destination",known:bn(t).map(e=>e.id)}});K&&(K.meta={t:Date.now(),model:v?.model||null,dest:M?M.id:null,type:M?M.type:null,redacted:re,sanitized:q,narrowed:le,detail:Xt(ie,t.logDetail),redaction:me?"off":t.redaction.tier||"basic"});const Ae=$o();if(Ae&&M){const e=M.type==="api"?kt(Ae,{model:v?.model||"",endpoint:M.baseUrl||""}):Ao(Ae,M.agent||M.id)?kt(Ae,{model:v?.model||""}):{ok:!1,reason:`agent "${M.agent||M.id}" is not allowed by your organisation’s policy`};if(!e.ok)return K?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(M&&M.type==="api")return M.baseUrl?In(M.baseUrl,t)?(K?.commit(),s(o,508,{error:{message:`destination "${M.id}" points back at the gateway (${M.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):Fn(n,o,{...j,pathname:l,search:f.search,base:M.baseUrl,destKey:M.apiKey,destProtocol:M.protocol,harness:mt,trace:K},G,ie):(K?.commit(),s(o,502,{error:`destination "${M.id}" has no baseUrl`}));const ht=Be(n),yt=ht==="local"&&t.bridge?.openAgentLane?"token":ht;if(yt==="local")return K?.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 ft=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),Ne=bo({...pe.run||{},...pe.reach?{reach:pe.reach}:{},...ft?{askDepth:ft}:{}},yt);return Ne.reach&&o.setHeader("x-chatpanel-reach-used",Ne.reach),Jn(n,o,{...j,pathname:l,agentOverride:M?.agent,harness:mt,trace:K,run:Object.keys(Ne).length?Ne:null},v,ie,t,de)});return C.on("close",()=>{m?.stop("closed"),Pr()}),C.once("listening",()=>{$()}),C}function Kn(t,d){let c=d&&typeof d=="object"?d: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(h=>String(h).slice(0,80)).slice(0,32)),c.workspace&&typeof c.workspace=="object"&&c.workspace.repo){const h=c.workspace;m.workspace={repo:String(h.repo).slice(0,400),projectId:String(h.projectId||"").slice(0,120),jobId:String(h.jobId||"").slice(0,120),...h.base?{base:String(h.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)),fn.includes(c.permissionMode)&&c.permissionMode!=="default"&&(m.permissionMode=c.permissionMode),c.sandbox&&typeof c.sandbox=="object"){const h=(Array.isArray(c.sandbox.hosts)?c.sandbox.hosts:String(c.sandbox.hosts||"").split(/[\s,;]+/)).map(k=>String(k).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),g=(Array.isArray(c.sandbox.write)?c.sandbox.write:[]).map(k=>String(k).slice(0,1024)).filter(Boolean).slice(0,32),E=c.sandbox.outside===!0;(h.length||g.length||E)&&(m.sandbox={...h.length?{hosts:h}:{},...g.length?{write:g}:{},...E?{outside:!0}:{}})}return Object.keys(m).length?m:null}let $e=null,Ge=null;async function ha(t=gt()){Ko();let d=null;try{d=await Eo()}catch(k){throw k instanceof Po&&(console.error(`[chatpanel-gateway] org policy: ${k.message}`),process.exit(78)),k}const c=d?.policy||null;c&&(bt(t,c),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`)),Oo(globalThis,{allow:c?.egress?(k,{local:x})=>No(c,k,{local:x}):null}),Fe();const m=Wn(t),h=Vo(t),g=ao(t);m.on("error",k=>{if(k&&k.code==="EADDRINUSE"){const x=at(t.host)?"127.0.0.1":t.host;fetch(`http://${x}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then($=>$.ok?$.json():null).catch(()=>null).then($=>{if($?.version&&typeof $.tier=="string"){const w=$.managedBy?` (run by ${$.managedBy})`:"",I=ir(W,$.version);console.error(`ChatPanel Gateway v${$.version} is already running at http://${x}:${t.port}${w} — this one (v${W}) did not start.`),I>0?console.error("To replace it with this version and keep it starting at login: chatpanel-gateway --install"):I<0?console.error(`The running one is NEWER. Nothing to do — this copy (v${W}) is the stale one; \`which -a chatpanel-gateway\` shows where it comes from.`):console.error("It is this same version: nothing to do. `chatpanel-gateway --status` shows how it is started.")}else{const w=ar(t.port);console.error(`Port ${t.port} is held by ${w||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${ne()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${k?.message||k}`),process.exit(1)}),m.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${W} 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"),Ge={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},sr(t,{childEnv:()=>({...gn(t),...yn(t)})}).then(k=>{$e=k}).catch(k=>{Ge={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${k?.message||k})`},console.log(` bridge : not supervised (${k?.message||k})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),at(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),_t()&&Xe(D,Qe()).then(k=>{k?.ok&&(console.log(` warm : seeded ${k.ingested} records from ${k.file}`),k.whole&&Je())}).catch(()=>{});const E=()=>{h?.stop(),g.stop(),$e?.stop(),On(m)};return process.on("SIGINT",E),process.on("SIGTERM",E),m}export{ga as VERSION,Wn as createGateway,Gn as joinUpstream,it as parseAgentModel,ha as start};
48
+ `);try{const l=await Io({card:r,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:u=>a(u.kind,{kind:u.kind,task:u.task,message:u.message})});a("done",l)}catch(l){a("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(n.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}"),r=e.card||(await je(e.url,{auth:String(e.auth||"")})).card,a=e.cancel?await Lo({card:r,id:String(e.id||""),auth:String(e.auth||"")}):await jo({card:r,id:String(e.id||""),auth:String(e.auth||"")});return s(o,200,{ok:!0,...a})}return s(o,404,{error:{message:`no such a2a route: ${i}`,type:"invalid_request"}})}catch(e){const r=e instanceof xt||e?.name==="A2AClientError"?e.code:"ERROR";return s(o,e instanceof xt&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:r}})}}if(n.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return z(n)?ce(n,o,t,i,{method:"POST",timeoutMs:15e3}):s(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?s(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):ce(n,o,t,`/skills/${encodeURIComponent(e)}${xe(f,t)}`,{pick:r=>({skill:r?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!z(n))return s(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&n.method==="GET"||i!=="/channels"&&n.method==="POST"))return s(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await Ee(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=$e(t.bridge?.token);try{const a=n.method==="POST"?(await T(n,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:a||"{}"}:{},signal:AbortSignal.timeout(15e3)}),u=await l.json().catch(()=>({}));return s(o,l.status,u)}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),r=decodeURIComponent(e[1]),a=e[2];return!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a))?s(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):ce(n,o,t,`/skills/${encodeURIComponent(r)}/file/${a}${xe(f,t)}`)}if(n.method==="GET"&&/\/models$/.test(i)){const e=await M(),r=e.sig!==void 0&&e.sig!==O;return O=e.sig,s(o,200,await $n(t,{serviceHealth:async()=>e,fresh:r}))}if(ts.some(e=>i===e||i.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${K}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const L=Vn(i,n.headers,t);let le;try{le=await T(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 H=null,k=null,Q=le,de=0,Ne=0,ve=0,ge=!1,ke=!0;const Y=t.logRequests&&L.redactable&&n.method==="POST"?Un(ee):null;if(L.redactable&&n.method==="POST"&&le.length){try{k=JSON.parse(le.toString("utf8"))}catch{k=null}if(k&&Fn(k,L.kind))Q=le;else if(k){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(k.tools)&&k.tools.length){const b=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Rn,p=e.narrowAll?null:J=>!In.test(Zt(J)),_=k.tools.length;k.tools=wo(k.tools,Ln(k,L.kind),{cap:b,keep:p,name:Zt,description:jn}),ve=_-k.tools.length}ke=await we(t.pro?.entitlementToken);const r=kn(t,ke);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"}});ge=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&z(n),ge||await Le(t);const a=ge?[]:L.adapter.collectSegments(k,t.redaction),l=new AbortController;o.on("close",()=>{o.writableFinished||l.abort()});const u=Y?Y.clock():0,{vault:S,count:y,sanitized:x}=ge?{vault:null,count:0,sanitized:0}:await De(a,t.redaction,{signal:l.signal,isPro:ke,onEgress:b=>dt.push(Wt({ts:Date.now(),client:"redaction",tool:`detect:${b.backend}@${b.host||"local"}`,ok:b.ok,ms:b.ms,error:b.error}))});if(Y&&Y.lap("redact",u),H=S,de=y,Ne=x||0,y>0&&o.setHeader("x-chatpanel-redacted",String(y)),!ke&&y>0){Sn(t,ke);try{pe(t,ne())}catch{}}if(!ge&&Array.isArray(k.tools)&&k.tools.length&&typeof L.adapter.injectSystemNote=="function"){const b=st(k?.model,t,L.kind,{destination:String(n.headers["x-chatpanel-destination"]||k?.chatpanel?.destination||"").trim(),down:_=>!!_.service&&w.fn(_.id)==="down"}),p=!(b&&b.type==="api");L.adapter.injectSystemNote(k,vo({toolData:t.tools?.toolData,ownTools:p}))}else!ge&&y>0&&typeof L.adapter.injectSystemNote=="function"&&L.adapter.injectSystemNote(k,ko());Q=Buffer.from(JSON.stringify(k),"utf8")}}const ft=bo({vault:H,toolData:t.tools?.toolData}),Be=k&&typeof k.chatpanel=="object"&&k.chatpanel||null;if(Be&&(delete k.chatpanel,Q=Buffer.from(JSON.stringify(k),"utf8")),typeof k?.model=="string"&&k.model.startsWith("fusion:")){const e=Or(k.model,t,await M());if(e?.error)return Y?.commit(),s(o,400,{error:{message:e.error,type:"fusion"}});e&&(k.model=e.model,Q=Buffer.from(JSON.stringify(k),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const re={destination:String(n.headers["x-chatpanel-destination"]||Be?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||Be?.reach||"").trim(),run:ao(n.headers["x-chatpanel-run"],Be?.run)},Fe=await M(),gt=e=>!!e.service&&Fe(e.id)==="down";let N=st(k?.model,t,L.kind,{destination:re.destination,down:gt});if(N?.type==="agent"&&k?.model&&!re.destination&&!Nn(N,k.model)&&(await An(t,{serviceHealth:async()=>Fe}),N=st(k?.model,t,L.kind,{destination:re.destination,down:gt})),N?.service&&Fe(N.id)==="down")return Y?.commit(),s(o,503,{error:{message:`${N.id} is not running — the model ${JSON.stringify(k?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:N.service}});if(re.destination&&(!N||N.id!==re.destination))return Y?.commit(),s(o,404,{error:{message:`no destination "${re.destination}" is configured on this gateway`,type:"unknown_destination",known:Pn(t).map(e=>e.id)}});Y&&(Y.meta={t:Date.now(),model:k?.model||null,dest:N?N.id:null,type:N?N.type:null,redacted:de,sanitized:Ne,narrowed:ve,detail:to(H,t.logDetail),redaction:ge?"off":t.redaction.tier||"basic"});const Me=No();if(Me&&N){const e=N.type==="api"?Tt(Me,{model:k?.model||"",endpoint:N.baseUrl||""}):Mo(Me,N.agent||N.id)?Tt(Me,{model:k?.model||""}):{ok:!1,reason:`agent "${N.agent||N.id}" is not allowed by your organisation’s policy`};if(!e.ok)return Y?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(N&&N.type==="api")return N.baseUrl?Wn(N.baseUrl,t)?(Y?.commit(),s(o,508,{error:{message:`destination "${N.id}" points back at the gateway (${N.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):os(n,o,{...L,pathname:i,search:f.search,base:N.baseUrl,destKey:N.apiKey,destProtocol:N.protocol,harness:ft,trace:Y},Q,H):(Y?.commit(),s(o,502,{error:`destination "${N.id}" has no baseUrl`}));const We=Re(n),wt=We==="local"&&t.bridge?.openAgentLane?"token":We;if(wt==="local")return Y?.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 bt=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0));!re.run&&We==="token"&&n.headers["x-chatpanel-link-device"]&&(re.run=ao(null,rr(or(te.get("agentTools").agentTools?.value,N?.agent||k?.model))));const Ce=To({...re.run||{},...re.reach?{reach:re.reach}:{},...bt?{askDepth:bt}:{}},wt);return Ce.reach&&o.setHeader("x-chatpanel-reach-used",Ce.reach),Zn(n,o,{...L,pathname:i,agentOverride:N?.agent,harness:ft,trace:Y,run:Object.keys(Ce).length?Ce:null},k,H,t,ke)});return ie.on("close",()=>{g?.stop("closed"),Rr(),d.close(),c?.stop()}),ie.once("listening",()=>{C()}),ie.linkHost=c,ie}function ao(t,d){let c=d&&typeof d=="object"?d: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(h=>String(h).slice(0,80)).slice(0,32)),c.workspace&&typeof c.workspace=="object"&&c.workspace.repo){const h=c.workspace;m.workspace={repo:String(h.repo).slice(0,400),projectId:String(h.projectId||"").slice(0,120),jobId:String(h.jobId||"").slice(0,120),...h.base?{base:String(h.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)),_n.includes(c.permissionMode)&&c.permissionMode!=="default"&&(m.permissionMode=c.permissionMode),c.sandbox&&typeof c.sandbox=="object"){const h=(Array.isArray(c.sandbox.hosts)?c.sandbox.hosts:String(c.sandbox.hosts||"").split(/[\s,;]+/)).map(w=>String(w).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),g=(Array.isArray(c.sandbox.write)?c.sandbox.write:[]).map(w=>String(w).slice(0,1024)).filter(Boolean).slice(0,32),E=c.sandbox.outside===!0;(h.length||g.length||E)&&(m.sandbox={...h.length?{hosts:h}:{},...g.length?{write:g}:{},...E?{outside:!0}:{}})}return Object.keys(m).length?m:null}let Ae=null,Ve=null;async function Ea(t=vt()){Zo();let d=null;try{d=await Ao()}catch(w){throw w instanceof Bo&&(console.error(`[chatpanel-gateway] org policy: ${w.message}`),process.exit(78)),w}const c=d?.policy||null;c&&(St(t,c),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`)),$o(globalThis,{allow:c?.egress?(w,{local:O})=>Co(c,w,{local:O}):null}),Oe();const m=rs(t),h=Ko(t),g=uo(t);m.on("error",w=>{if(w&&w.code==="EADDRINUSE"){const O=ct(t.host)?"127.0.0.1":t.host;fetch(`http://${O}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(M=>M.ok?M.json():null).catch(()=>null).then(M=>{if(M?.version&&typeof M.tier=="string"){const v=M.managedBy?` (run by ${M.managedBy})`:"",C=hr(K,M.version);console.error(`ChatPanel Gateway v${M.version} is already running at http://${O}:${t.port}${v} — this one (v${K}) did not start.`),C>0?console.error("To replace it with this version and keep it starting at login: chatpanel-gateway --install"):C<0?console.error(`The running one is NEWER. Nothing to do — this copy (v${K}) is the stale one; \`which -a chatpanel-gateway\` shows where it comes from.`):console.error("It is this same version: nothing to do. `chatpanel-gateway --status` shows how it is started.")}else{const v=pr(t.port);console.error(`Port ${t.port} is held by ${v||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${ne()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${w?.message||w}`),process.exit(1)}),m.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${K} on http://${t.host}:${t.port}`),m.linkHost?.start().catch(w=>console.log(` link : not started (${w?.message||w})`)),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"),Ve={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},mr(t,{childEnv:()=>({...En(t),...On(t)})}).then(w=>{Ae=w}).catch(w=>{Ve={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${w?.message||w})`},console.log(` bridge : not supervised (${w?.message||w})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),ct(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),Pt()&&ot(B,qe()).then(w=>{w?.ok&&(console.log(` warm : seeded ${w.ingested} records from ${w.file}`),w.whole&&Ue())}).catch(()=>{});const E=()=>{h?.stop(),g.stop(),Ae?.stop(),Dn(m)};return process.on("SIGINT",E),process.on("SIGTERM",E),m}export{Aa as VERSION,rs as createGateway,Xn as joinUpstream,ut as parseAgentModel,Ea as start};
package/src/update.js CHANGED
@@ -1 +1,3 @@
1
- import J from"node:os";import l from"node:path";import{execFile as b}from"node:child_process";import{chmod as G,rename as P,mkdir as K,readFile as V,writeFile as j,rm as Y}from"node:fs/promises";import{existsSync as W,readFileSync as q,realpathSync as z}from"node:fs";import{restartService as Q,serviceRegistered as y}from"./service.js";const g="@chatpanel/gateway",be="chatpanel/chatpanel-gateway",D="https://dl.chatpanel.net/version/gateway",E=(process.env.CHATPANEL_NPM_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/$/,""),X=`${E}/${g}/latest`,Z=e=>`https://dl.chatpanel.net/gateway/${e.replace(/^chatpanel-gateway-/,"")}`,L=360*60*1e3,N=600*1e3,ee=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),te=15*6e4,k=20*6e4,_=process.env.CHATPANEL_UPDATE_CACHE||l.join(J.homedir(),".chatpanel","gateway-update-check.json"),S=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",O={"User-Agent":"chatpanel-gateway-updater"},ne=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function ae(e){try{const t=new URL(e);return t.protocol==="https:"&&ne.has(t.hostname)}catch{return!1}}let m={at:0,error:""};function Ee(){m={at:0,error:""}}function T(){const e=l.basename(process.execPath).toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}function re(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function f(e=""){const t=/(\d+(?:\.\d+){0,3})/.exec(e||"");return t?t[1]:null}function R(e,t){const n=String(e).split(".").map(Number),a=String(t).split(".").map(Number);for(let r=0;r<Math.max(n.length,a.length);r+=1){const o=(n[r]||0)-(a[r]||0);if(o)return o>0?1:-1}return 0}async function oe(){try{return JSON.parse(await V(_,"utf8"))}catch{return null}}async function se(e){try{await K(l.dirname(_),{recursive:!0}),await j(_,JSON.stringify(e))}catch{}}async function v(e,t=ee){const n=new AbortController,a=setTimeout(()=>n.abort(),t);try{const r=await fetch(e,{headers:{Accept:"application/json, application/vnd.github+json",...O},signal:n.signal});if(!r.ok)throw new Error(r.status===403&&/github/.test(e)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${r.status}`);return await r.json()}catch(r){const o=r?.cause?.code||r?.cause?.message||r?.message||String(r);throw new Error(n.signal.aborted?`the update server did not answer within ${Math.round(t/1e3)}s`:`${new URL(e).hostname}: ${o}`)}finally{clearTimeout(a)}}function x(e=process.argv[1]){let t=e?l.resolve(e):"";try{t=z(t)}catch{}const n=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(t);return n?n[1]:""}function ie(){const e=x();if(!e)return"";try{return String(JSON.parse(q(l.join(e,"package.json"),"utf8")).version||"")}catch{return""}}function $(){const e=l.dirname(process.execPath);return[l.join(e,"..","lib","node_modules","npm","bin","npm-cli.js"),l.join(e,"node_modules","npm","bin","npm-cli.js")].find(n=>W(n))||""}function le(e=process.env,t=process.execPath){const n={...e,npm_config_registry:E,npm_config_fund:"false",npm_config_audit:"false"};delete n.ELECTRON_RUN_AS_NODE;const a=Object.keys(n).find(r=>r.toLowerCase()==="path")||"PATH";return n[a]=[l.dirname(t),...(n[a]||"").split(l.delimiter).filter(Boolean)].filter((r,o,c)=>c.indexOf(r)===o).join(l.delimiter),n}function ce(){import("./prune-install.js").then(({pruneForeignPrebuilds:e,pruneLine:t})=>{const n=t(e({log:a=>console.log(a)}));n&&console.log(`[update]${n}`)}).catch(()=>{})}function de(){return["install","-g",`${g}@latest`,"--ignore-scripts"]}function pe(){const e=$(),t=le(),n=de(),[a,r]=e?[process.execPath,[e,...n]]:["npm",n];return new Promise(o=>{b(a,r,{env:t,timeout:k,maxBuffer:8<<20,windowsHide:!0},(c,p,s)=>{const i=`${p||""}${s||""}`.trim();return c?c.killed&&!i?o({ok:!1,out:`npm was still running after ${Math.round(k/6e4)} minutes and was stopped`}):o({ok:!1,out:i||(e?c.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):(ce(),o({ok:!0,out:i}))})})}async function H(e,{force:t=!1}={}){const n=T()?"binary":"npm";if(S)return{current:e,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:n==="npm"?"npm":"release",service:!1,disabled:!0};const a=re();let r=null,o=null,c=!1,p="",s=0;const i=await oe(),w=i&&i.mode===n,C=()=>{r=w&&i.latest||null,o=w&&i.assetUrl||null,s=w&&i.checkedAt||0,c=!0};if(!t&&w&&Date.now()-i.checkedAt<L)r=i.latest,o=i.assetUrl,s=i.checkedAt;else if(!t&&m.at&&Date.now()-m.at<N)p=m.error,C();else try{if(n==="npm"){let u;try{u=await v(X),r=f(u.version)}catch(B){const U=await v(D);if(r=f(U?.npm?.version)||f(U?.version),!r)throw B}}else{const u=await v(D);r=f(u.version)||f(u.release?.tag),o=a&&(u.release?.assets||[]).includes(a)?Z(a):null}s=Date.now(),await se({checkedAt:s,mode:n,latest:r,assetUrl:o}),m={at:0,error:""}}catch(u){p=u.message,m={at:Date.now(),error:p},C()}const M=!!r&&R(r,e)>0,I=n==="binary"?!!o&&(process.platform!=="win32"||y()):!!x()&&(process.platform!=="win32"||y()&&!!$()),F=n==="npm"?process.platform==="win32"?`chatpanel-gateway --stop; npm i -g ${g}@latest --ignore-scripts; chatpanel-gateway --install`:`npm i -g ${g}@latest --ignore-scripts`:null;return{current:e,latest:r,updateAvailable:M,mode:n,canSelfUpdate:I,assetUrl:o,stale:c,error:p,npmCommand:F,channel:n==="npm"?"npm":"release",service:y(),checkedAt:s}}let h=null,A=null;function _e(e){const t=T()?"binary":"npm";return S?{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:!1,disabled:!0}:((!h||(h.stale?!(m.at&&Date.now()-m.at<N):Date.now()-h.seenAt>L))&&!A&&(A=H(e).then(a=>{h={...a,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{A=null})),h?{...h,seenAt:void 0,current:e}:{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:y()})}function Se(){h=null,A=null}async function ue(e){const t=process.execPath,n=l.dirname(t),a=l.join(n,`.chatpanel-gateway.new-${Date.now()}`),r=new AbortController,o=setTimeout(()=>r.abort(),te);let c;try{const s=await fetch(e.assetUrl,{headers:O,redirect:"follow",signal:r.signal});if(!s.ok)throw new Error(`download failed (HTTP ${s.status})`);if(!ae(s.url||e.assetUrl))throw new Error(`refused: the download was redirected to ${s.url}, which is not a ChatPanel release host`);c=Buffer.from(await s.arrayBuffer())}finally{clearTimeout(o)}if(c.length<5<<20)throw new Error(`the download was only ${(c.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await j(a,c),process.platform!=="win32"&&await G(a,493),process.platform==="darwin"&&await new Promise(s=>b("xattr",["-c",a],()=>s()));const p=await new Promise(s=>b(a,["--version"],{timeout:6e4,windowsHide:!0},(i,w)=>s(i?"":String(w||"").trim())));if(!f(p))throw await Y(a,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await P(t,l.join(n,`chatpanel-gateway.old-${Date.now()}.exe`)),await P(a,t),f(p)}async function me(e){if(S)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const t=await H(e,{force:!0});if(t.stale)throw new Error(`Could not reach the update server${t.error?` (${t.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!t.updateAvailable)throw new Error(`Already on the latest ${t.channel} version (v${e}).`);if(!t.canSelfUpdate)throw new Error(t.mode==="npm"?`This gateway cannot update itself here. Run: ${t.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(t.mode==="binary")return{from:e,to:await ue(t),mode:"binary"};if(process.platform==="win32")return{from:e,to:t.latest,mode:"npm",deferred:`"${process.execPath}" "${$()}" install -g ${g}@latest --registry=${E} --no-fund --no-audit`};const n=await pe();if(!n.ok)throw new Error(`npm install failed: ${n.out.slice(0,800)}`);const a=ie();if(!a||R(a,e)<=0)throw new Error(`npm ran, but the install at ${x()} is still ${a||"unreadable"} — the service launches a copy npm did not update. Run: ${t.npmCommand}`);return{from:e,to:a,mode:"npm"}}const d={state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0};function Te(){return{...d}}function ve(e,{restart:t=Q,apply:n=me}={}){return d.state==="installing"||d.state==="restarting"?{...d,already:!0}:(Object.assign(d,{state:"installing",mode:T()?"binary":"npm",from:e,to:"",detail:"",startedAt:Date.now(),endedAt:0}),n(e).then(a=>{Object.assign(d,{state:"restarting",to:a.to,mode:a.mode,detail:a.deferred?`stopping to install v${a.to}, then relaunching`:`v${a.to} is installed; restarting the gateway into it`}),setTimeout(()=>{t({winInstall:a.deferred||""})||Object.assign(d,{state:"done",endedAt:Date.now(),detail:`v${a.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.`})},400)}).catch(a=>{Object.assign(d,{state:"failed",endedAt:Date.now(),detail:String(a?.message||a).slice(0,1200)})}),{...d})}function xe(){Object.assign(d,{state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0})}export{xe as _resetUpdateJob,Se as _resetUpdateStatus,H as checkForUpdate,R as cmpVersions,ae as downloadHostAllowed,T as isCompiledBinary,de as npmInstallArgs,le as npmInstallEnv,x as npmPackageRoot,Ee as resetUpdateBackoff,me as selfUpdate,ve as startUpdate,Te as updateJob,_e as updateStatus};
1
+ import U from"node:os";import i from"node:path";import{execFile as A}from"node:child_process";import{chmod as G,rename as L,mkdir as K,readFile as V,writeFile as R,rm as W}from"node:fs/promises";import{existsSync as Y,readFileSync as q,realpathSync as z}from"node:fs";import{restartService as Q,serviceRegistered as y}from"./service.js";const g="@chatpanel/gateway",Et="chatpanel/chatpanel-gateway",j="https://dl.chatpanel.net/version/gateway",E=(process.env.CHATPANEL_NPM_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/$/,""),X=`${E}/${g}/latest`,Z=t=>`https://dl.chatpanel.net/gateway/${t.replace(/^chatpanel-gateway-/,"")}`,D=360*60*1e3,N=600*1e3,tt=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),et=15*6e4,k=20*6e4,_=process.env.CHATPANEL_UPDATE_CACHE||i.join(U.homedir(),".chatpanel","gateway-update-check.json"),S=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",O={"User-Agent":"chatpanel-gateway-updater"},nt=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function at(t){try{const e=new URL(t);return e.protocol==="https:"&&nt.has(e.hostname)}catch{return!1}}let m={at:0,error:""};function _t(){m={at:0,error:""}}function $(){const t=i.basename(process.execPath).toLowerCase();return!(t.startsWith("node")||t.startsWith("bun"))}function rt(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function f(t=""){const e=/(\d+(?:\.\d+){0,3})/.exec(t||"");return e?e[1]:null}function H(t,e){const n=String(t).split(".").map(Number),a=String(e).split(".").map(Number);for(let r=0;r<Math.max(n.length,a.length);r+=1){const o=(n[r]||0)-(a[r]||0);if(o)return o>0?1:-1}return 0}async function ot(){try{return JSON.parse(await V(_,"utf8"))}catch{return null}}async function st(t){try{await K(i.dirname(_),{recursive:!0}),await R(_,JSON.stringify(t))}catch{}}async function x(t,e=tt){const n=new AbortController,a=setTimeout(()=>n.abort(),e);try{const r=await fetch(t,{headers:{Accept:"application/json, application/vnd.github+json",...O},signal:n.signal});if(!r.ok)throw new Error(r.status===403&&/github/.test(t)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${r.status}`);return await r.json()}catch(r){const o=r?.cause?.code||r?.cause?.message||r?.message||String(r);throw new Error(n.signal.aborted?`the update server did not answer within ${Math.round(e/1e3)}s`:`${new URL(t).hostname}: ${o}`)}finally{clearTimeout(a)}}function T(t=process.argv[1]){let e=t?i.resolve(t):"";try{e=z(e)}catch{}const n=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(e);return n?n[1]:""}function it(){const t=T();if(!t)return"";try{return String(JSON.parse(q(i.join(t,"package.json"),"utf8")).version||"")}catch{return""}}function v(){const t=i.dirname(process.execPath);return[i.join(t,"..","lib","node_modules","npm","bin","npm-cli.js"),i.join(t,"node_modules","npm","bin","npm-cli.js")].find(n=>Y(n))||""}function lt(t=process.env,e=process.execPath){const n={...t,npm_config_registry:E,npm_config_fund:"false",npm_config_audit:"false"};delete n.ELECTRON_RUN_AS_NODE;const a=Object.keys(n).find(r=>r.toLowerCase()==="path")||"PATH";return n[a]=[i.dirname(e),...(n[a]||"").split(i.delimiter).filter(Boolean)].filter((r,o,c)=>c.indexOf(r)===o).join(i.delimiter),n}function ct(){import("./prune-install.js").then(({pruneForeignPrebuilds:t,pruneLine:e})=>{const n=e(t({log:a=>console.log(a)}));n&&console.log(`[update]${n}`)}).catch(()=>{})}function pt(){return["install","-g",`${g}@latest`,"--ignore-scripts"]}function dt(t,{home:e=U.homedir(),platform:n=process.platform}={}){if(n==="win32"||!/\b(EACCES|EPERM)\b/.test(t||""))return"";const a=(t.match(/^npm (?:error|ERR!) path (.+)$/m)||[])[1]?.trim()||"",r=a.indexOf(`${i.sep}lib${i.sep}node_modules`),o=r>0?a.slice(0,r):"";return o?o===e||o.startsWith(e+i.sep)?`npm cannot write ${o} — part of it belongs to another user, usually from an earlier \`sudo npm i -g\` (npm's hint about ~/.npm is a different folder). Fix: sudo chown -R "$(whoami)" "${o}" — then update again.`:`npm cannot write ${o}, which belongs to another user. Install the standalone build instead — it needs no npm: curl -fsSL https://dl.chatpanel.net/install.sh | bash`:""}function ut(){const t=v(),e=lt(),n=pt(),[a,r]=t?[process.execPath,[t,...n]]:["npm",n];return new Promise(o=>{A(a,r,{env:e,timeout:k,maxBuffer:8<<20,windowsHide:!0},(c,d,s)=>{const l=`${d||""}${s||""}`.trim();return c?c.killed&&!l?o({ok:!1,out:`npm was still running after ${Math.round(k/6e4)} minutes and was stopped`}):o({ok:!1,out:l||(t?c.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):(ct(),o({ok:!0,out:l}))})})}async function M(t,{force:e=!1}={}){const n=$()?"binary":"npm";if(S)return{current:t,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:n==="npm"?"npm":"release",service:!1,disabled:!0};const a=rt();let r=null,o=null,c=!1,d="",s=0;const l=await ot(),w=l&&l.mode===n,C=()=>{r=w&&l.latest||null,o=w&&l.assetUrl||null,s=w&&l.checkedAt||0,c=!0};if(!e&&w&&Date.now()-l.checkedAt<D)r=l.latest,o=l.assetUrl,s=l.checkedAt;else if(!e&&m.at&&Date.now()-m.at<N)d=m.error,C();else try{if(n==="npm"){let u;try{u=await x(X),r=f(u.version)}catch(J){const P=await x(j);if(r=f(P?.npm?.version)||f(P?.version),!r)throw J}}else{const u=await x(j);r=f(u.version)||f(u.release?.tag),o=a&&(u.release?.assets||[]).includes(a)?Z(a):null}s=Date.now(),await st({checkedAt:s,mode:n,latest:r,assetUrl:o}),m={at:0,error:""}}catch(u){d=u.message,m={at:Date.now(),error:d},C()}const I=!!r&&H(r,t)>0,F=n==="binary"?!!o&&(process.platform!=="win32"||y()):!!T()&&(process.platform!=="win32"||y()&&!!v()),B=n==="npm"?process.platform==="win32"?`chatpanel-gateway --stop; npm i -g ${g}@latest --ignore-scripts; chatpanel-gateway --install`:`npm i -g ${g}@latest --ignore-scripts`:null;return{current:t,latest:r,updateAvailable:I,mode:n,canSelfUpdate:F,assetUrl:o,stale:c,error:d,npmCommand:B,channel:n==="npm"?"npm":"release",service:y(),checkedAt:s}}let h=null,b=null;function St(t){const e=$()?"binary":"npm";return S?{current:t,latest:null,updateAvailable:!1,mode:e,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:e==="npm"?"npm":"release",service:!1,disabled:!0}:((!h||(h.stale?!(m.at&&Date.now()-m.at<N):Date.now()-h.seenAt>D))&&!b&&(b=M(t).then(a=>{h={...a,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{b=null})),h?{...h,seenAt:void 0,current:t}:{current:t,latest:null,updateAvailable:!1,mode:e,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:e==="npm"?"npm":"release",service:y()})}function $t(){h=null,b=null}async function mt(t){const e=process.execPath,n=i.dirname(e),a=i.join(n,`.chatpanel-gateway.new-${Date.now()}`),r=new AbortController,o=setTimeout(()=>r.abort(),et);let c;try{const s=await fetch(t.assetUrl,{headers:O,redirect:"follow",signal:r.signal});if(!s.ok)throw new Error(`download failed (HTTP ${s.status})`);if(!at(s.url||t.assetUrl))throw new Error(`refused: the download was redirected to ${s.url}, which is not a ChatPanel release host`);c=Buffer.from(await s.arrayBuffer())}finally{clearTimeout(o)}if(c.length<5<<20)throw new Error(`the download was only ${(c.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await R(a,c),process.platform!=="win32"&&await G(a,493),process.platform==="darwin"&&await new Promise(s=>A("xattr",["-c",a],()=>s()));const d=await new Promise(s=>A(a,["--version"],{timeout:6e4,windowsHide:!0},(l,w)=>s(l?"":String(w||"").trim())));if(!f(d))throw await W(a,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await L(e,i.join(n,`chatpanel-gateway.old-${Date.now()}.exe`)),await L(a,e),f(d)}async function ft(t){if(S)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const e=await M(t,{force:!0});if(e.stale)throw new Error(`Could not reach the update server${e.error?` (${e.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!e.updateAvailable)throw new Error(`Already on the latest ${e.channel} version (v${t}).`);if(!e.canSelfUpdate)throw new Error(e.mode==="npm"?`This gateway cannot update itself here. Run: ${e.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(e.mode==="binary")return{from:t,to:await mt(e),mode:"binary"};if(process.platform==="win32")return{from:t,to:e.latest,mode:"npm",deferred:`"${process.execPath}" "${v()}" install -g ${g}@latest --registry=${E} --no-fund --no-audit`};const n=await ut();if(!n.ok){const r=dt(n.out);throw new Error(r?`${r}
2
+
3
+ npm said: ${n.out.slice(0,600)}`:`npm install failed: ${n.out.slice(0,800)}`)}const a=it();if(!a||H(a,t)<=0)throw new Error(`npm ran, but the install at ${T()} is still ${a||"unreadable"} — the service launches a copy npm did not update. Run: ${e.npmCommand}`);return{from:t,to:a,mode:"npm"}}const p={state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0};function xt(){return{...p}}function Tt(t,{restart:e=Q,apply:n=ft}={}){return p.state==="installing"||p.state==="restarting"?{...p,already:!0}:(Object.assign(p,{state:"installing",mode:$()?"binary":"npm",from:t,to:"",detail:"",startedAt:Date.now(),endedAt:0}),n(t).then(a=>{Object.assign(p,{state:"restarting",to:a.to,mode:a.mode,detail:a.deferred?`stopping to install v${a.to}, then relaunching`:`v${a.to} is installed; restarting the gateway into it`}),setTimeout(()=>{e({winInstall:a.deferred||""})||Object.assign(p,{state:"done",endedAt:Date.now(),detail:`v${a.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.`})},400)}).catch(a=>{Object.assign(p,{state:"failed",endedAt:Date.now(),detail:String(a?.message||a).slice(0,1200)})}),{...p})}function vt(){Object.assign(p,{state:"idle",mode:"",from:"",to:"",detail:"",startedAt:0,endedAt:0})}export{vt as _resetUpdateJob,$t as _resetUpdateStatus,M as checkForUpdate,H as cmpVersions,at as downloadHostAllowed,$ as isCompiledBinary,pt as npmInstallArgs,lt as npmInstallEnv,T as npmPackageRoot,dt as npmPermissionHint,_t as resetUpdateBackoff,ft as selfUpdate,Tt as startUpdate,xt as updateJob,St as updateStatus};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.57.4";export{o as VERSION};
1
+ const o="0.61.2";export{o as VERSION};