@chatpanel/gateway 0.44.3 → 0.46.4
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/bin/chatpanel-gateway-bin.mjs +2 -1
- package/package.json +3 -3
- package/src/config.js +1 -1
- package/src/configstore.js +1 -1
- package/src/egress.js +2 -2
- package/src/ner-engine.js +1 -1
- package/src/ort-native.js +1 -0
- package/src/server.js +8 -8
- package/src/version.js +1 -1
|
@@ -1 +1,2 @@
|
|
|
1
|
-
import{pathToFileURL as
|
|
1
|
+
import{pathToFileURL as s}from"node:url";import{createRequire as m}from"node:module";import{existsSync as l,readFileSync as c}from"node:fs";import{join as f}from"node:path";import{homedir as p}from"node:os";import{normalizeRegistries as u}from"@chatpanel/events/registries.js";import d from"../assets/ort-wasm-simd-threaded.wasm";import g from"../assets/ort-wasm-simd-threaded.mjs";import{findNativeBinding as _,ensureNativeOrt as h}from"../src/ort-native.js";function A(){try{const e=process.env.CHATPANEL_GATEWAY_CONFIG||f(p(),".chatpanel","gateway.config.json"),i=l(e)?JSON.parse(c(e,"utf8")):{},r={npm:process.env.CHATPANEL_REGISTRY_NPM,models:process.env.CHATPANEL_REGISTRY_MODELS};return u({...i.registries||{},...r.npm?{npm:r.npm}:{},...r.models?{models:r.models}:{}})}catch{return{}}}const t=e=>{try{process.stderr.write(`[ort] ${e}
|
|
2
|
+
`)}catch{}};let n=null,a=!1;function N(e){if(a)return n;a=!0;try{n=m(import.meta.url)(e),t(`native runtime loaded — ${e}`)}catch(i){t(`native runtime would not load (${String(i?.message||i).slice(0,120)}) — falling back to WASM`),n=null}return n}let o=_();o||h({registries:A(),onProgress:e=>{e.phase==="download"&&t(`fetching the native runtime once (~108 MB) from ${new URL(e.url).host} — WASM answers until it lands`)}}).then(e=>t(`native runtime ready — ${e} (restart to use it)`)).catch(e=>t(`no native runtime (${String(e?.message||e).slice(0,120)}) — staying on WASM`)),o?globalThis.__CHATPANEL_ORT_BINDING__=()=>N(o):globalThis.__CHATPANEL_WASM_PATHS__={wasm:s(d).href,mjs:s(g).href},await import("./chatpanel-gateway.js");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.46.4",
|
|
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": {
|
|
@@ -22,8 +22,8 @@
|
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
25
|
-
"@chatpanel/bridge": "^0.
|
|
26
|
-
"@chatpanel/events": "^0.
|
|
25
|
+
"@chatpanel/bridge": "^0.24.0",
|
|
26
|
+
"@chatpanel/events": "^0.193.0",
|
|
27
27
|
"@chatpanel/pii": "^0.11.0",
|
|
28
28
|
"@huggingface/transformers": "^4.2.0",
|
|
29
29
|
"defuddle": "^0.19.4",
|
package/src/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as
|
|
1
|
+
import{readFileSync as d,existsSync as p}from"node:fs";import{join as c}from"node:path";import l from"node:os";import{DEFAULT_MODEL as A}from"./models.js";import{DEFAULT_STT_MODEL as E}from"./stt-models.js";const s={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],maxBodyBytes:26214400,pro:{entitlementToken:"",free:{used:0}},sandbox:{mode:"open",hosts:[],write:[],denyRead:[]},bridge:{url:"http://127.0.0.1:4319",agent:"codex",token:"",permissionMode:"default",workingDir:"",openAgentLane:!1},mcp:{ask:{maxReach:"device",defaultModel:"",delegate:{roots:[],permissionMode:"acceptEdits"}}},upstreams:{openai:{baseUrl:"https://api.openai.com"},anthropic:{baseUrl:"https://api.anthropic.com"}},redaction:{tier:"basic",dictionary:[],detection:{backend:"off"},redactSystem:!0},ner:{autostart:!0,model:A,union:[],warmMs:15*6e4,caseRecovery:!0,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:E,allowDownload:!0,diarize:!0,warmMs:15*6e4},read:{provider:"defuddle",remote:{url:"",key:""}},search:{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},capabilities:{},runtime:{services:{}},registries:{},fusions:[],tts:{enabled:!0,warmMs:15*6e4,provider:"local",model:"",voice:"",allowDownload:!0,remote:{baseUrl:"",model:"",voice:"",redact:!0}},logRequests:!0,logDetail:"off"};function r(t,e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&t&&typeof t=="object"){const i={...t};for(const o of Object.keys(e))i[o]=r(t[o],e[o]);return i}return e===void 0?t:e}function g(t=process.env){let e=s;const i=t.CHATPANEL_GATEWAY_CONFIG||c(l.homedir(),".chatpanel","gateway.config.json");if(p(i))try{e=r(e,JSON.parse(d(i,"utf8")))}catch(a){throw new Error(`bad config file ${i}: ${a.message}`)}t.CHATPANEL_GATEWAY_HOST&&(e=r(e,{host:t.CHATPANEL_GATEWAY_HOST})),t.CHATPANEL_GATEWAY_PORT&&(e=r(e,{port:Number(t.CHATPANEL_GATEWAY_PORT)})),t.OPENAI_BASE_URL&&(e=r(e,{upstreams:{openai:{baseUrl:t.OPENAI_BASE_URL}}})),t.ANTHROPIC_BASE_URL&&(e=r(e,{upstreams:{anthropic:{baseUrl:t.ANTHROPIC_BASE_URL}}})),t.CHATPANEL_REDACTION_TIER&&(e=r(e,{redaction:{tier:t.CHATPANEL_REDACTION_TIER}}));for(const[a,n]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])t[n]&&(e=r(e,{registries:{[a]:t[n]}}));if(e.registries?.models&&!t.CHATPANEL_REGISTRY_MODELS)try{process.env.CHATPANEL_REGISTRY_MODELS=e.registries.models}catch{}const o=Number(e.port);return(!Number.isInteger(o)||o<1||o>65535)&&(e.port!==s.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(e.port)} — using ${s.port}`),e=r(e,{port:s.port})),e}export{s as DEFAULTS,g as loadConfig};
|
package/src/configstore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{writeFileSync as b,mkdirSync as y,chmodSync as p}from"node:fs";import{join as A,dirname as w}from"node:path";import x from"node:os";import{usage as k}from"./freegate.js";import{applyFusionsPatch as f}from"./fusions.js";import{assertEndpointUrl as a}from"@chatpanel/pii";import{normalizeGrant as D}from"@chatpanel/bridge/src/events/sandbox-policy.js";const v=["open","allowlist","off"],l=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=v.includes(r.mode)?r.mode:"open",{hosts:i}=D({hosts:r.hosts??[]});return{mode:o,hosts:i,write:l(r.write),denyRead:l(r.denyRead)}}function P(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 u(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||A(x.homedir(),".chatpanel","gateway.config.json")}function R(e,r=u()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===u({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);y(w(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,mcp:e.mcp};b(r,JSON.stringify(o,null,2),{mode:384});try{p(r,384)}catch{}}function L(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:i,...n}=o;return{...n,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}},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:n,...t}=i||{};return[o,{...t,hasToken:!!n}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:k(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 C(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function E(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),n=Number(o.port)||(o.protocol==="https:"?443:80);return i&&n===(Number(r.port)||4320)}const m=["default","acceptEdits","bypassPermissions"];function M(e,r={}){const o=e?.bridge||{};return{...m.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function I(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 n=E(i,e);return n&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!n}).map(i=>{const n={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(n.agent=i.agent||i.id),i.type==="api"){n.baseUrl=String(i.baseUrl||""),n.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;s&&(n.apiKey=s)}const t=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;return t&&(n.service=t),n})}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),m.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.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=f(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]||{}};if(i.provider==="embedded"){e.capabilities[o]={provider:"embedded"},o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if("url"in i){const s=String(i.url||"").trim();s&&a(s),t.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(t.adapter=i.adapter),typeof i.model=="string"&&(t.model=i.model.trim()),typeof i.token=="string"&&(t.token=i.token),typeof i.calibrated=="boolean"&&(t.calibrated=i.calibrated),typeof i.redact=="boolean"&&(t.redact=i.redact),!t.url){delete e.capabilities[o];continue}t.provider="remote",delete t.service,e.capabilities[o]=t,o==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:t.url,...t.token?{apiKey:t.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{m as PERMISSION_MODES,I as applyConfigPatch,C as applyNerModelSelection,M as bridgeAgentOptions,u as configPath,E as isSelfDestination,d as normalizeSandboxConfig,R as persistConfig,L as publicConfig,P as sandboxEnvFor};
|
|
1
|
+
import{writeFileSync as b,mkdirSync as y,chmodSync as p}from"node:fs";import{join as A,dirname as w}from"node:path";import x from"node:os";import{usage as k}from"./freegate.js";import{applyFusionsPatch as f}from"./fusions.js";import{normalizeRegistries as E,REGISTRY_KINDS as D}from"@chatpanel/events/registries.js";import{assertEndpointUrl as a}from"@chatpanel/pii";import{normalizeGrant as S}from"@chatpanel/bridge/src/events/sandbox-policy.js";const T=["open","allowlist","off"],l=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=T.includes(r.mode)?r.mode:"open",{hosts:i}=S({hosts:r.hosts??[]});return{mode:o,hosts:i,write:l(r.write),denyRead:l(r.denyRead)}}function L(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 u(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||A(x.homedir(),".chatpanel","gateway.config.json")}function C(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 M(e,r=u()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===u({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);y(w(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};b(r,JSON.stringify(o,null,2),{mode:384});try{p(r,384)}catch{}}function H(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:k(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 G(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function N(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 m=["default","acceptEdits","bypassPermissions"];function g(e,r={}){const o=e?.bridge||{};return{...m.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function K(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=N(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),m.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=E(r.registries),i={...e.registries||{}};for(const t of D)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=f(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"){e.capabilities[o]={provider:"embedded"},o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});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{m as PERMISSION_MODES,K as applyConfigPatch,G as applyNerModelSelection,g as bridgeAgentOptions,u as configPath,N as isSelfDestination,d as normalizeSandboxConfig,M as persistConfig,H as publicConfig,C as registryChildEnv,L as sandboxEnvFor};
|
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 s=g(r);if(!s||!s.host)return;const h=`${s.scheme}://${s.host}:${s.port}`,c=e(),o=t.get(h);if(o){o.count+=1,o.lastAt=c;return}t.set(h,{host:s.host,port:s.port,scheme:s.scheme,local:u(s.host),count:1,firstAt:c,lastAt:c})},snapshot(){return[...t.values()].sort((r,s)=>r.local===s.local?s.count-r.count:r.local?1:-1)},reset(){t.clear()}}}let w=null;function x(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const r=v();let s=t;r.setGate=c=>{s=c},r.blocked=[];const h=e.fetch;return typeof h=="function"&&(e.fetch=function(o,p){let a=null;try{a=g(o),r.record(o)}catch{}if(s&&a?.host){let i=!0;try{i=s(`${a.scheme}://${a.host}:${a.port}`,{local:u(a.host)})}catch{i=!0}if(!i){const n=`${a.host}:${a.port}`;r.blocked.includes(n)||r.blocked.push(n);const l=new Error(`egress to ${a.host} is blocked by your organisation’s policy`);return l.code="EGRESS_POLICY",Promise.reject(l)}}return h.call(this,o,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=[],s=(a,i,{when:n="always",off:l=null,local:m=!1,data:b=""}={})=>{a&&r.push({host:a,purpose:i,when:n,off:l,local:m,data:b})};s("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"}),s("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"}),s("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"}),s("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 a=h;try{a=new URL(h).host}catch{}s(a,"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(a)})}if(e.search?.provider!=="searxng"&&(s("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"}),s("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 a=e.read.remote.url;try{a=new URL(e.read.remote.url).host}catch{}s(a,"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(a)})}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[a,i]of Object.entries(c)){const n=e.capabilities?.[a];if(!n?.url||n.provider==="embedded")continue;let l=n.url;try{l=new URL(n.url).host}catch{}s(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/${a}`,off:n.service?`stop the ${n.service} service under Settings › Runtime`:`capabilities.${a} = null`,data:`${i.data}${n.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(l)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(s("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"}),s("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[a,i]of Object.entries(e.upstreams||{}))i?.baseUrl&&s(d(i.baseUrl),`model upstream "${a}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a}`,off:`upstreams.${a}.baseUrl`,local:u(d(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const a of e.destinations||[])a?.baseUrl&&s(d(a.baseUrl),`destination "${a.id||a.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a.id||"it"}`,off:"destinations[]",local:u(d(a.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});s("(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&&s(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 o=e.tts||{};if(o.provider==="openai"||o.provider==="elevenlabs"){const a=o.remote?.baseUrl?d(o.remote.baseUrl):o.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";s(a,`remote read-aloud voice (${o.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:o.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 s(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 L(e,{ledger:t=$(),version:r="",startedAt:s=null,env:h=process.env,managed:c=null}={}){return{ok:!0,version:r,since:s?new Date(s).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,s])=>s===!0?r:`${r}=${s}`).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,
|
|
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};
|
package/src/ner-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import nt from"node:os";import{join as S}from"node:path";import{existsSync as B,mkdirSync as rt,readdirSync as Y,readFileSync as ot}from"node:fs";import{DEFAULT_MODEL as J,isMirroredModel as st}from"./models.js";import{isLoopbackHost as it,isPrivateHost as at,isMetadataHost as lt}from"@chatpanel/pii";import{recaseForDetection as ct}from"@chatpanel/pii/pii-detect.js";import{verifyModelWeights as ut}from"./model-integrity.js";import{runtimeName as ft}from"./model-runtime.js";import{nativeOrtFailure as pt}from"./ort.js";import{makeWarmTimer as Q}from"./warm-timer.js";import{makeModelFileCache as dt}from"./model-file-cache.js";const E="https://dl.chatpanel.net/models/";function mt(){const t=process.env.CHATPANEL_MODEL_BASE_URL;if(!t)return E;const e=r=>(console.warn(`[models] ignoring CHATPANEL_MODEL_BASE_URL (${t}): ${r} — using ${E}`),E);let n;try{n=new URL(t)}catch{return e("not a valid URL")}if(n.protocol!=="http:"&&n.protocol!=="https:")return e(`scheme ${n.protocol} not allowed`);if(lt(n.hostname))return e("points at cloud metadata");const o=it(n.hostname)||at(n.hostname);return n.protocol==="http:"&&!o?e("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${n.origin} (CHATPANEL_MODEL_BASE_URL override), not ${E}`),t.replace(/\/*$/,"/"))}const ht=mt();let d="off",h=null,g=null,x=null,L=null,v=null,M=null,T=null,w=null,N=0,A=null;const m=new Map;function C(){return process.env.CHATPANEL_MODELS_DIR||S(nt.homedir(),".chatpanel","models")}function H(t=h||J){const e=S(C(),...t.split("/"));return B(S(e,"onnx","model_quantized.onnx"))||B(S(e,"onnx","model.onnx"))}function zt(){const t=C(),e=[];try{for(const n of Y(t,{withFileTypes:!0}))if(n.isDirectory())for(const o of Y(S(t,n.name),{withFileTypes:!0})){if(!o.isDirectory())continue;const r=`${n.name}/${o.name}`;H(r)&>(S(t,n.name,o.name))&&e.push(r)}}catch{}return e}function gt(t){try{return(JSON.parse(ot(S(t,"config.json"),"utf8")).architectures||[]).some(n=>/ForTokenClassification$/.test(String(n)))}catch{return!1}}function Bt(){return d}function k(){return d==="ready"&&!!g}function Yt(){return{configured:d!=="off",ok:k(),state:d,model:h,error:x,runtime:ft(),dtype:g?"q8":null,stats:$t(),companions:bt(),warmMs:w?.warmMs??null}}async function yt(t,{signal:e}={}){if(!k())return[];if(e?.aborted)return[];const n=String(t||""),o=await G(n,e);if(!o)return[];const r=[];for(const i of o||[]){let c=String(i.word??"");const l=i.entity_group??i.entity??"ENTITY";if(c.startsWith("##")&&r.length&&r[r.length-1].type===l){r[r.length-1].value+=c.slice(2);continue}c=c.replace(/##/g,"").trim(),c&&r.push({value:c,type:l})}const s=new Set,u=[];for(const i of r){const c=At(n,vt(n,i.value.trim()));if(c.length<=1)continue;const l=`${i.type}:${c.toLowerCase()}`;s.has(l)||(s.add(l),u.push({value:c,type:i.type}))}return u}async function G(t,e){N++;try{return await wt(t,e)}finally{N--,$()||w?.arm()}}async function wt(t,e){const n=performance.now(),o=[],r=[{text:t,key:"orig"}];if(P){const s=ct(t);s.changed&&r.push({text:s.text,key:"recased"})}for(const{model:s,pipe:u}of V())for(const i of r){let c=0;for(const l of St(i.text,u.tokenizer)){if(e?.aborted)return null;const a=i.text.indexOf(l,c),f=await u(l,{aggregation_strategy:"simple"});for(const p of f||[])o.push({...p,_win:a<0?c:a,_winText:l,_model:s,_pass:i.key,_passText:i.text});a>=0&&(c=Math.max(c,a+1))}}return kt(performance.now()-n,t.length,o.length),o}let P=!0;function Jt(t){P=t!==!1}async function Qt(t,{signal:e}={}){if(!k())return[];const n=String(t||""),o=await G(n,e);if(!o)return[];const r=[],s=new Set;let u=-1,i=-1,c=null,l=null;for(const f of o){const p=String(f.word??"").replace(/##/g,"").trim();if(!p)continue;(f._win!==i||f._model!==c||f._pass!==l)&&(i=f._win,c=f._model,l=f._pass,u=f._win);const b=f._passText||n;let _=b.indexOf(p,u);if(_<0&&(_=b.indexOf(p,f._win)),_<0)continue;let O=_+p.length;u=O;const W=z=>!!z&&/[\p{L}\p{N}'’-]/u.test(z);for(;_>0&&W(n[_-1]);)_--;for(;O<n.length&&W(n[O]);)O++;const U=String(f.entity_group??f.entity??"ENTITY"),j=`${_}:${O}:${U}`;if(s.has(j))continue;s.add(j);const q=Number(f.score);r.push({value:n.slice(_,O),type:U,start:_,end:O,score:Number.isFinite(q)?Math.max(0,Math.min(1,q)):1,model:f._model})}r.sort((f,p)=>f.start-p.start||f.end-p.end);const a=[];for(const f of r){const p=a[a.length-1];if(p&&p.type===f.type&&p.end===f.start){p.end=f.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,f.score);continue}a.push({...f})}return m.size||P?Mt(a):a}const K=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function _t(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function R(t){const e=K.indexOf(_t(t.type));return e<0?K.length:e}let D=[];function xt(t){D=Array.isArray(t)?t.slice():[]}function F(t){if(t.model===h)return-1;const e=D.indexOf(t.model);return e<0?D.length:e}function Mt(t){const e=[...t].sort((o,r)=>o.start-r.start||r.end-o.end),n=[];for(const o of e){const r=n[n.length-1];if(r&&o.start<r.end){const s=i=>i.end-i.start;(R(o)<R(r)||R(o)===R(r)&&(s(o)>s(r)||s(o)===s(r)&&(F(o)<F(r)||F(o)===F(r)&&o.score>r.score)))&&(n[n.length-1]=o);continue}n.push(o)}return n}function Gt(){const t=g?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const n of Object.values(t)){const o=String(n).replace(/^[BIES]-/,"");o&&o!=="O"&&e.add(o)}return[...e]}function Kt(){const t=Number(g?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function bt(){return[...m].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function Lt(t,{log:e=()=>{},allowDownload:n=!0}={}){if(!t||t===h)return!1;if(m.get(t)?.pipe)return!0;m.set(t,{pipe:null,state:H(t)?"loading":"downloading",error:null});try{const{pipe:r}=await I(t,{log:e,allowDownload:n});return m.set(t,{pipe:r,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(r){return m.set(t,{pipe:null,state:"error",error:r.message}),e(`[ner] companion ${t} failed to load (${r.message}) — the union runs without it`),!1}}async function Vt(t){const e=m.get(t);if(!e)return!1;m.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function V(){const t=g?[{model:h,pipe:g}]:[];for(const[e,n]of m)n.pipe&&t.push({model:e,pipe:n.pipe});return t}const Ot=160,X=256;function St(t,e){if(!t||typeof e!="function")return[t];const n=Number(e.model_max_length),r=Math.min(X,Number.isFinite(n)&&n>0?n:X)-8,s=l=>{try{return e(l).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=r)return[t];const u=[];let i=0,c=Math.max(64,Math.floor(r*3));for(;i<t.length;){let l=Math.min(t.length,i+c);if(l<t.length){const b=t.lastIndexOf(" ",l);b>i+c/2&&(l=b)}let a=t.slice(i,l);for(;s(a)>r&&a.length>32;){c=Math.max(32,Math.floor(a.length/2)),l=i+c;const b=t.lastIndexOf(" ",l);b>i+c/2&&(l=b),a=t.slice(i,l)}if(u.push(a),l>=t.length)break;const f=Math.max(i+1,l-Ot),p=t.indexOf(" ",f);i=p>0&&p<l?p+1:l}return u}const Tt=200,y=[];function kt(t,e,n){y.push({ms:t,chars:e,spans:n}),y.length>Tt&&y.shift()}function $t(){if(!y.length)return{calls:0};const t=y.map(r=>r.ms).sort((r,s)=>r-s),e=r=>t[Math.min(t.length-1,Math.floor(r*t.length))],n=y.reduce((r,s)=>r+s.chars,0),o=y.reduce((r,s)=>r+s.ms,0);return{calls:y.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(y[y.length-1].ms),charsPerSec:o>0?Math.round(n/(o/1e3)):null}}function vt(t,e){if(!e||t.includes(e))return e;const n=t.toLowerCase().indexOf(e.toLowerCase());return n<0?e:t.slice(n,n+e.length)}function At(t,e){if(!e)return e;const n=t.indexOf(e);if(n<0)return e;const o=u=>!!u&&/[\p{L}\p{N}'’-]/u.test(u);let r=n,s=n+e.length;for(;r>0&&o(t[r-1]);)r--;for(;s<t.length&&o(t[s]);)s++;return t.slice(r,s)}async function Xt(t,e={}){let n="";try{n=JSON.parse(e.body||"{}").text||""}catch{}const o=await yt(n,{signal:e.signal});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function Zt(){return M}async function Z(){if(v)return v;const t=C();try{rt(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}let n;try{n=await import("@huggingface/transformers")}catch(a){throw e?a:new Error(pt(a))}const{env:o,pipeline:r,Tensor:s,AutoModel:u,AutoProcessor:i,LogLevel:c}=n;if(o.cacheDir=t,e&&c)try{o.logLevel=c.ERROR}catch{}o.localModelPath=t,e||(o.useCustomCache=!0,o.customCache=dt(t,{remoteHost:()=>o.remoteHost}));try{o.remoteHost=ht}catch{}try{o.backends.onnx.wasm.numThreads=1}catch{}if(e)try{o.backends.onnx.wasm.proxy=!1,o.backends.onnx.wasm.wasmPaths=e}catch{}return v={env:o,pipeline:(a,f,p={})=>r(a,f,p.progress_callback&&o.allowRemoteModels===!1?{...p,progress_callback:void 0}:p),Tensor:s,AutoModel:u,AutoProcessor:i},v}async function I(t,{log:e=()=>{},allowDownload:n=!0,onProgress:o=()=>{}}={}){const r=await Z(),s=H(t);if(r.env.allowRemoteModels=s?!1:!!n,!s&&!n)throw new Error("model not on disk and downloads disabled");const u=r.env.remoteHost,i=!st(t);if(!s&&i)try{r.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${i?", from Hugging Face":""})…`);try{const c=a=>{a&&(a.status==="progress"||a.status==="download"||a.status==="initiate"?o(a):a.status==="done"&&a.file&&e(`[ner] fetched ${a.file}`))};let l;try{l=await r.pipeline("token-classification",t,{dtype:"q8",progress_callback:c})}catch(a){if(s||i||!n)throw a;e(`[ner] mirror fetch failed (${String(a.message).slice(0,80)}) — retrying from Hugging Face…`),r.env.remoteHost="https://huggingface.co/",r.env.allowRemoteModels=!0,l=await r.pipeline("token-classification",t,{dtype:"q8",progress_callback:c})}if(!s)try{ut(t,{modelsDir:C(),log:e})}catch(a){try{await l.dispose?.()}catch{}throw a}return{pipe:l,haveLocal:s}}finally{try{r.env.remoteHost=u}catch{}}}async function tt(t,{log:e=()=>{},allowDownload:n=!0}={}){const o=g,r=h;try{await Z()}catch(u){return d="error",x=`engine load failed: ${u.message}`,e(`[ner] transformers.js not available (${u.message}) — deterministic-only`),!1}const s=H(t);if(!s&&!n)return d="error",x="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;d=s?"loading":"downloading",s||(M={model:t,file:null,pct:0});try{const{pipe:u}=await I(t,{log:e,allowDownload:n,onProgress:i=>{M={model:t,file:i.file||M?.file||null,pct:typeof i.progress=="number"?Math.round(i.progress):M?.pct??0}}});if(g=u,h=t,d="ready",x=null,M=null,T&&(T={...T,model:t}),o&&o!==u)try{await o.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),$()||w?.arm(),!0}catch(u){return x=u.message,M=null,o?(g=o,h=r,d="ready"):d="error",e(`[ner] model load failed (${u.message})${o?" — keeping previous model":" — deterministic-only"}`),!1}}function Et(t={}){if(L)return L;const e=typeof t.onLog=="function"?t.onLog:()=>{};T=t,h=t.model||J,d="loading";const n=t.allowDownload!==!1;return w=Q({warmMs:t.warmMs,busy:$,log:e,unload:()=>et({log:e})}),L=tt(h,{log:e,allowDownload:n}).then(async o=>{const r=Array.isArray(t.union)?t.union:[];xt(r);for(const s of r)await Lt(s,{log:e,allowDownload:n});return k()&&!$()&&w?.arm(),o}),L}function $(){if(N>0||d==="loading"||d==="downloading")return!0;for(const t of m.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function et({log:t=()=>{}}={}){if($())return!1;w?.disarm();const e=V().map(n=>n.pipe);g=null,L=null,M=null,x=null,m.clear(),d=e.length?"idle":"off";for(const n of e)try{await n.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((w?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function It(){try{d==="idle"&&(A||T)?await(A?A():Et(T)):L&&await L}catch{}return k()}async function te(t,e={}){const n=typeof e.onLog=="function"?e.onLog:()=>{},o=e.allowDownload!==!1;if(!t)return!1;if(t===h&&k())return!0;const r=m.get(t);if(r?.pipe){const s=g;if(g=r.pipe,h=t,d="ready",x=null,m.delete(t),s)try{await s.dispose?.()}catch{}return n(`[ner] ${t} promoted from the union to primary`),!0}return tt(t,{log:n,allowDownload:o})}function ee(){d="off",h=null,g=null,x=null,L=null,v=null,M=null,y.length=0,m.clear(),P=!0,D=[],w?.disarm(),w=null,T=null,N=0,A=null}function ne(t,e){m.set(t,{pipe:e,state:"ready",error:null})}function re(t,{model:e="test/model",warmMs:n=null,reload:o=null}={}){g=t,h=e,d="ready",x=null,y.length=0,o&&(A=o),n!==null&&(w=Q({warmMs:n,busy:$,unload:()=>et()}),t&&w.arm())}export{ee as _reset,ne as _setCompanionForTest,re as _setForTest,Lt as addCompanion,bt as companions,yt as detect,Qt as detectSpans,It as ensure,Z as ensureLib,Xt as fetchAdapter,Yt as health,Et as init,k as isReady,Gt as labels,Kt as maxTokens,H as modelOnDisk,C as modelRoot,zt as modelsOnDisk,Zt as progress,Vt as removeCompanion,mt as resolveModelHost,Jt as setCaseRecovery,te as setModel,xt as setUnionOrder,Bt as state,$t as stats,Mt as unionSpans,et as unload,St as windowsFor};
|
|
1
|
+
import nt from"node:os";import{join as S}from"node:path";import{existsSync as z,mkdirSync as rt,readdirSync as B,readFileSync as ot}from"node:fs";import{DEFAULT_MODEL as J,isMirroredModel as st}from"./models.js";import{isLoopbackHost as it,isPrivateHost as at,isMetadataHost as lt}from"@chatpanel/pii";import{recaseForDetection as ct}from"@chatpanel/pii/pii-detect.js";import{verifyModelWeights as ut}from"./model-integrity.js";import{runtimeName as ft}from"./model-runtime.js";import{nativeOrtFailure as pt}from"./ort.js";import{makeWarmTimer as G}from"./warm-timer.js";import{makeModelFileCache as dt}from"./model-file-cache.js";const E="https://dl.chatpanel.net/models/";function mt(t=process.env){const e=t.CHATPANEL_MODEL_BASE_URL?"CHATPANEL_MODEL_BASE_URL":"registries.models",r=t.CHATPANEL_MODEL_BASE_URL||t.CHATPANEL_REGISTRY_MODELS;if(!r)return E;const o=c=>(console.warn(`[models] ignoring ${e} (${r}): ${c} — using ${E}`),E);let n;try{n=new URL(r)}catch{return o("not a valid URL")}if(n.protocol!=="http:"&&n.protocol!=="https:")return o(`scheme ${n.protocol} not allowed`);if(lt(n.hostname))return o("points at cloud metadata");const s=it(n.hostname)||at(n.hostname);return n.protocol==="http:"&&!s?o("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${n.origin} (${e}), not ${E}`),r.replace(/\/*$/,"/"))}const ht=mt();let d="off",h=null,g=null,x=null,L=null,A=null,M=null,T=null,w=null,N=0,v=null;const m=new Map;function R(){return process.env.CHATPANEL_MODELS_DIR||S(nt.homedir(),".chatpanel","models")}function C(t=h||J){const e=S(R(),...t.split("/"));return z(S(e,"onnx","model_quantized.onnx"))||z(S(e,"onnx","model.onnx"))}function Yt(){const t=R(),e=[];try{for(const r of B(t,{withFileTypes:!0}))if(r.isDirectory())for(const o of B(S(t,r.name),{withFileTypes:!0})){if(!o.isDirectory())continue;const n=`${r.name}/${o.name}`;C(n)&>(S(t,r.name,o.name))&&e.push(n)}}catch{}return e}function gt(t){try{return(JSON.parse(ot(S(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function zt(){return d}function $(){return d==="ready"&&!!g}function Bt(){return{configured:d!=="off",ok:$(),state:d,model:h,error:x,runtime:ft(),dtype:g?"q8":null,stats:kt(),companions:bt(),warmMs:w?.warmMs??null}}async function yt(t,{signal:e}={}){if(!$())return[];if(e?.aborted)return[];const r=String(t||""),o=await Q(r,e);if(!o)return[];const n=[];for(const i of o||[]){let u=String(i.word??"");const l=i.entity_group??i.entity??"ENTITY";if(u.startsWith("##")&&n.length&&n[n.length-1].type===l){n[n.length-1].value+=u.slice(2);continue}u=u.replace(/##/g,"").trim(),u&&n.push({value:u,type:l})}const s=new Set,c=[];for(const i of n){const u=vt(r,At(r,i.value.trim()));if(u.length<=1)continue;const l=`${i.type}:${u.toLowerCase()}`;s.has(l)||(s.add(l),c.push({value:u,type:i.type}))}return c}async function Q(t,e){N++;try{return await wt(t,e)}finally{N--,k()||w?.arm()}}async function wt(t,e){const r=performance.now(),o=[],n=[{text:t,key:"orig"}];if(H){const s=ct(t);s.changed&&n.push({text:s.text,key:"recased"})}for(const{model:s,pipe:c}of V())for(const i of n){let u=0;for(const l of St(i.text,c.tokenizer)){if(e?.aborted)return null;const a=i.text.indexOf(l,u),f=await c(l,{aggregation_strategy:"simple"});for(const p of f||[])o.push({...p,_win:a<0?u:a,_winText:l,_model:s,_pass:i.key,_passText:i.text});a>=0&&(u=Math.max(u,a+1))}}return $t(performance.now()-r,t.length,o.length),o}let H=!0;function Jt(t){H=t!==!1}async function Gt(t,{signal:e}={}){if(!$())return[];const r=String(t||""),o=await Q(r,e);if(!o)return[];const n=[],s=new Set;let c=-1,i=-1,u=null,l=null;for(const f of o){const p=String(f.word??"").replace(/##/g,"").trim();if(!p)continue;(f._win!==i||f._model!==u||f._pass!==l)&&(i=f._win,u=f._model,l=f._pass,c=f._win);const b=f._passText||r;let _=b.indexOf(p,c);if(_<0&&(_=b.indexOf(p,f._win)),_<0)continue;let O=_+p.length;c=O;const W=Y=>!!Y&&/[\p{L}\p{N}'’-]/u.test(Y);for(;_>0&&W(r[_-1]);)_--;for(;O<r.length&&W(r[O]);)O++;const U=String(f.entity_group??f.entity??"ENTITY"),j=`${_}:${O}:${U}`;if(s.has(j))continue;s.add(j);const q=Number(f.score);n.push({value:r.slice(_,O),type:U,start:_,end:O,score:Number.isFinite(q)?Math.max(0,Math.min(1,q)):1,model:f._model})}n.sort((f,p)=>f.start-p.start||f.end-p.end);const a=[];for(const f of n){const p=a[a.length-1];if(p&&p.type===f.type&&p.end===f.start){p.end=f.end,p.value=r.slice(p.start,p.end),p.score=Math.min(p.score,f.score);continue}a.push({...f})}return m.size||H?Mt(a):a}const K=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function _t(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function P(t){const e=K.indexOf(_t(t.type));return e<0?K.length:e}let D=[];function xt(t){D=Array.isArray(t)?t.slice():[]}function F(t){if(t.model===h)return-1;const e=D.indexOf(t.model);return e<0?D.length:e}function Mt(t){const e=[...t].sort((o,n)=>o.start-n.start||n.end-o.end),r=[];for(const o of e){const n=r[r.length-1];if(n&&o.start<n.end){const s=i=>i.end-i.start;(P(o)<P(n)||P(o)===P(n)&&(s(o)>s(n)||s(o)===s(n)&&(F(o)<F(n)||F(o)===F(n)&&o.score>n.score)))&&(r[r.length-1]=o);continue}r.push(o)}return r}function Qt(){const t=g?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const o=String(r).replace(/^[BIES]-/,"");o&&o!=="O"&&e.add(o)}return[...e]}function Kt(){const t=Number(g?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function bt(){return[...m].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function Lt(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===h)return!1;if(m.get(t)?.pipe)return!0;m.set(t,{pipe:null,state:C(t)?"loading":"downloading",error:null});try{const{pipe:n}=await I(t,{log:e,allowDownload:r});return m.set(t,{pipe:n,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(n){return m.set(t,{pipe:null,state:"error",error:n.message}),e(`[ner] companion ${t} failed to load (${n.message}) — the union runs without it`),!1}}async function Vt(t){const e=m.get(t);if(!e)return!1;m.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function V(){const t=g?[{model:h,pipe:g}]:[];for(const[e,r]of m)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const Ot=160,X=256;function St(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),n=Math.min(X,Number.isFinite(r)&&r>0?r:X)-8,s=l=>{try{return e(l).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=n)return[t];const c=[];let i=0,u=Math.max(64,Math.floor(n*3));for(;i<t.length;){let l=Math.min(t.length,i+u);if(l<t.length){const b=t.lastIndexOf(" ",l);b>i+u/2&&(l=b)}let a=t.slice(i,l);for(;s(a)>n&&a.length>32;){u=Math.max(32,Math.floor(a.length/2)),l=i+u;const b=t.lastIndexOf(" ",l);b>i+u/2&&(l=b),a=t.slice(i,l)}if(c.push(a),l>=t.length)break;const f=Math.max(i+1,l-Ot),p=t.indexOf(" ",f);i=p>0&&p<l?p+1:l}return c}const Tt=200,y=[];function $t(t,e,r){y.push({ms:t,chars:e,spans:r}),y.length>Tt&&y.shift()}function kt(){if(!y.length)return{calls:0};const t=y.map(n=>n.ms).sort((n,s)=>n-s),e=n=>t[Math.min(t.length-1,Math.floor(n*t.length))],r=y.reduce((n,s)=>n+s.chars,0),o=y.reduce((n,s)=>n+s.ms,0);return{calls:y.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(y[y.length-1].ms),charsPerSec:o>0?Math.round(r/(o/1e3)):null}}function At(t,e){if(!e||t.includes(e))return e;const r=t.toLowerCase().indexOf(e.toLowerCase());return r<0?e:t.slice(r,r+e.length)}function vt(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const o=c=>!!c&&/[\p{L}\p{N}'’-]/u.test(c);let n=r,s=r+e.length;for(;n>0&&o(t[n-1]);)n--;for(;s<t.length&&o(t[s]);)s++;return t.slice(n,s)}async function Xt(t,e={}){let r="";try{r=JSON.parse(e.body||"{}").text||""}catch{}const o=await yt(r,{signal:e.signal});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function Zt(){return M}async function Z(){if(A)return A;const t=R();try{rt(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}let r;try{r=await import("@huggingface/transformers")}catch(a){throw e?a:new Error(pt(a))}const{env:o,pipeline:n,Tensor:s,AutoModel:c,AutoProcessor:i,LogLevel:u}=r;if(o.cacheDir=t,e&&u)try{o.logLevel=u.ERROR}catch{}o.localModelPath=t,e||(o.useCustomCache=!0,o.customCache=dt(t,{remoteHost:()=>o.remoteHost}));try{o.remoteHost=ht}catch{}try{o.backends.onnx.wasm.numThreads=1}catch{}if(e)try{o.backends.onnx.wasm.proxy=!1,o.backends.onnx.wasm.wasmPaths=e}catch{}return A={env:o,pipeline:(a,f,p={})=>n(a,f,p.progress_callback&&o.allowRemoteModels===!1?{...p,progress_callback:void 0}:p),Tensor:s,AutoModel:c,AutoProcessor:i},A}async function I(t,{log:e=()=>{},allowDownload:r=!0,onProgress:o=()=>{}}={}){const n=await Z(),s=C(t);if(n.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const c=n.env.remoteHost,i=!st(t);if(!s&&i)try{n.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${i?", from Hugging Face":""})…`);try{const u=a=>{a&&(a.status==="progress"||a.status==="download"||a.status==="initiate"?o(a):a.status==="done"&&a.file&&e(`[ner] fetched ${a.file}`))};let l;try{l=await n.pipeline("token-classification",t,{dtype:"q8",progress_callback:u})}catch(a){if(s||i||!r)throw a;e(`[ner] mirror fetch failed (${String(a.message).slice(0,80)}) — retrying from Hugging Face…`),n.env.remoteHost="https://huggingface.co/",n.env.allowRemoteModels=!0,l=await n.pipeline("token-classification",t,{dtype:"q8",progress_callback:u})}if(!s)try{ut(t,{modelsDir:R(),log:e})}catch(a){try{await l.dispose?.()}catch{}throw a}return{pipe:l,haveLocal:s}}finally{try{n.env.remoteHost=c}catch{}}}async function tt(t,{log:e=()=>{},allowDownload:r=!0}={}){const o=g,n=h;try{await Z()}catch(c){return d="error",x=`engine load failed: ${c.message}`,e(`[ner] transformers.js not available (${c.message}) — deterministic-only`),!1}const s=C(t);if(!s&&!r)return d="error",x="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;d=s?"loading":"downloading",s||(M={model:t,file:null,pct:0});try{const{pipe:c}=await I(t,{log:e,allowDownload:r,onProgress:i=>{M={model:t,file:i.file||M?.file||null,pct:typeof i.progress=="number"?Math.round(i.progress):M?.pct??0}}});if(g=c,h=t,d="ready",x=null,M=null,T&&(T={...T,model:t}),o&&o!==c)try{await o.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),k()||w?.arm(),!0}catch(c){return x=c.message,M=null,o?(g=o,h=n,d="ready"):d="error",e(`[ner] model load failed (${c.message})${o?" — keeping previous model":" — deterministic-only"}`),!1}}function Et(t={}){if(L)return L;const e=typeof t.onLog=="function"?t.onLog:()=>{};T=t,h=t.model||J,d="loading";const r=t.allowDownload!==!1;return w=G({warmMs:t.warmMs,busy:k,log:e,unload:()=>et({log:e})}),L=tt(h,{log:e,allowDownload:r}).then(async o=>{const n=Array.isArray(t.union)?t.union:[];xt(n);for(const s of n)await Lt(s,{log:e,allowDownload:r});return $()&&!k()&&w?.arm(),o}),L}function k(){if(N>0||d==="loading"||d==="downloading")return!0;for(const t of m.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function et({log:t=()=>{}}={}){if(k())return!1;w?.disarm();const e=V().map(r=>r.pipe);g=null,L=null,M=null,x=null,m.clear(),d=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((w?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function It(){try{d==="idle"&&(v||T)?await(v?v():Et(T)):L&&await L}catch{}return $()}async function te(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},o=e.allowDownload!==!1;if(!t)return!1;if(t===h&&$())return!0;const n=m.get(t);if(n?.pipe){const s=g;if(g=n.pipe,h=t,d="ready",x=null,m.delete(t),s)try{await s.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),!0}return tt(t,{log:r,allowDownload:o})}function ee(){d="off",h=null,g=null,x=null,L=null,A=null,M=null,y.length=0,m.clear(),H=!0,D=[],w?.disarm(),w=null,T=null,N=0,v=null}function ne(t,e){m.set(t,{pipe:e,state:"ready",error:null})}function re(t,{model:e="test/model",warmMs:r=null,reload:o=null}={}){g=t,h=e,d="ready",x=null,y.length=0,o&&(v=o),r!==null&&(w=G({warmMs:r,busy:k,unload:()=>et()}),t&&w.arm())}export{ee as _reset,ne as _setCompanionForTest,re as _setForTest,Lt as addCompanion,bt as companions,yt as detect,Gt as detectSpans,It as ensure,Z as ensureLib,Xt as fetchAdapter,Bt as health,Et as init,$ as isReady,Qt as labels,Kt as maxTokens,C as modelOnDisk,R as modelRoot,Yt as modelsOnDisk,Zt as progress,Vt as removeCompanion,mt as resolveModelHost,Jt as setCaseRecovery,te as setModel,xt as setUnionOrder,zt as state,kt as stats,Mt as unionSpans,et as unload,St as windowsFor};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{mirrorUrl as E}from"@chatpanel/events/registries.js";import{createRequire as R}from"node:module";import{gunzipSync as k}from"node:zlib";import{mkdirSync as x,writeFileSync as I,existsSync as d,renameSync as A,rmSync as $,chmodSync as O}from"node:fs";import{join as i,dirname as w}from"node:path";import{homedir as _}from"node:os";const b=globalThis.__CHATPANEL_ORT_VERSION__||"1.30.0",N="napi-v6";function g(e=process.platform,t=process.arch){return({darwin:["arm64","x64"],linux:["arm64","x64"],win32:["x64","arm64"]}[e]||[]).includes(t)?{platform:e,arch:t}:null}function T(e=i(_(),".chatpanel"),t=b,r=g()){return r?i(e,"runtime","ort",t,`${r.platform}-${r.arch}`):null}const u="onnxruntime_binding.node";function q({env:e=process.env,stateDir:t=i(_(),".chatpanel"),require:r=null}={}){const c=e.CHATPANEL_ORT_DIR?i(e.CHATPANEL_ORT_DIR,u):null;if(c&&d(c))return c;const n=T(t);if(n&&d(i(n,u)))return i(n,u);try{const o=(r||R(import.meta.url)).resolve("onnxruntime-node/package.json"),a=g(),s=a?i(w(o),"bin",N,a.platform,a.arch,u):null;if(s&&d(s))return s}catch{}return null}function*B(e,t=()=>!0){let r=0;for(;r+512<=e.length;){const c=e.subarray(r,r+512);if(c[0]===0)break;const n=(h,y)=>c.subarray(h,h+y).toString("utf8").replace(/\0.*$/,"").trim(),m=n(0,100),o=n(345,155),a=parseInt(n(124,12)||"0",8)||0,s=String.fromCharCode(c[156]||48),p=o?`${o}/${m}`:m;r+=512,(s==="0"||s==="\0"||s==="48")&&t(p)&&(yield{name:p,data:e.subarray(r,r+a)}),r+=Math.ceil(a/512)*512}}async function P({stateDir:e=i(_(),".chatpanel"),version:t=b,fetchImpl:r=fetch,onProgress:c=()=>{},target:n=g(),registries:m={}}={}){if(!n)throw new Error(`no native onnxruntime build for ${process.platform}/${process.arch}`);const o=T(e,t,n);if(d(i(o,u)))return i(o,u);const a=E("npm",`https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-${t}.tgz`,m);c({phase:"download",url:a});const s=await r(a);if(!s.ok)throw new Error(`onnxruntime-node ${t}: registry answered ${s.status}`);const p=Buffer.from(await s.arrayBuffer());c({phase:"extract",bytes:p.length});const h=Buffer.from(k(p)),y=`package/bin/${N}/${n.platform}/${n.arch}/`,f=`${o}.incoming-${process.pid}`;$(f,{recursive:!0,force:!0}),x(f,{recursive:!0});let v=0;for(const S of B(h,l=>l.startsWith(y))){const l=i(f,S.name.slice(y.length));if(x(w(l),{recursive:!0}),I(l,S.data),/\.(node|dylib|so|so\.\d+|dll)$/.test(l))try{O(l,493)}catch{}v+=1}if(!d(i(f,u)))throw $(f,{recursive:!0,force:!0}),new Error(`onnxruntime-node ${t} carries no ${n.platform}/${n.arch} binding`);return x(w(o),{recursive:!0}),$(o,{recursive:!0,force:!0}),A(f,o),c({phase:"ready",dir:o,files:v}),i(o,u)}export{b as ORT_VERSION,P as ensureNativeOrt,q as findNativeBinding,T as ortDir,g as ortTarget,B as readTar};
|
package/src/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createServer as Wt}from"node:http";import{loadConfig as nt}from"./config.js";import{startEntitlementRefresh as Kt,maybeRevalidate as Qt}from"./entitlement-refresh.js";import{redactSegments as $e,segment as Re}from"./redact.js";import{pipeRestoredStream as Zt,pipeRestoredOpenAIStream as Yt,makeTokenRestorer as st,restoreDeep as Xt}from"./stream.js";import{restoreText as qt,gatedDictionary as eo,narrowSpecs as to,makeToolHarness as oo,placeholderToolNote as ro,placeholderNote as no,assertEndpointUrl as so,capRunOptions as ao,isPaired as io}from"@chatpanel/pii";import{ensureGatewayToken as Ie,currentGatewayToken as lo,isAdminAuthorized as X,callerTrustOf as Pe,setPinnedExtensionIds as co,issuePairingCode as uo,claimPairingCode as mo}from"./gateway-token.js";import{installEgressLedger as po,egressAudit as ho}from"./egress.js";import{initPolicy as yo,activePolicy as fo,applyPolicyToConfig as at,managedSummary as ke,PolicyLoadError as go}from"./policy.js";import{routeAllowed as it,agentAllowed as wo,egressAllowed as bo}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as ye}from"./bridge.js";import{secureFetch as Ee}from"./secure-fetch.js";import{streamBridgeChat as lt,readBridgeToken as de,openBridgeChat as vo}from"./bridge.js";import{createRelaySession as ko,getRelaySession as ct,endRelaySession as Se,pumpBridgeStream as So,deliverToolResult as To,toolsToSpecs as xo,wantsApprovals as _o,parseToolCallId as dt,touchRelaySession as Le}from"./toolrelay.js";import{shaperFor as Je}from"./shape.js";import{startNer as Oo,ensureNer as Ae,unionForThisMachine as $o,skippedCompanions as Po}from"./ner.js";import{recommendDetector as ut}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Eo}from"./log.js";import{saveBackupSecret as Ao,clearBackupSecret as No,loadBackupSecret as ze,hasBackupSecret as mt}from"./history-store.js";import{createMemoryStore as Bo}from"./memory-store.js";import{createPrefsStore as Do}from"./prefs-store.js";import{createTeamStore as Mo,loadOrCreateKey as Ge}from"./team-store.js";import{createScorecardStore as Co}from"./scorecard-store.js";import{createEngineLedgerStore as jo}from"./engine-ledger-store.js";import{createProjectStore as Ro}from"./project-store.js";import{applicationsFor as Io,recruitPass as Lo}from"./recruiting.js";import{ensureBridge as Jo}from"./bridge-supervisor.js";import{checkForUpdate as zo,updateStatus as Go,startUpdate as Ho,updateJob as Vo}from"./update.js";import{createHistoryStore as Uo}from"./sqlite-store.js";import{createEventStore as Fo}from"./event-store.js";import{ingestCloudEvents as Wo,cursorOf as pt}from"./event-sync.js";import{eventStats as Ko,projectYear as Qo}from"./event-stats.js";import{toCloudEvent as He}from"./cloudevents.js";import{fusionsDocument as Zo,resolveFusionModel as Yo}from"./fusions.js";import{ingestBackups as Ve}from"./backup-ingest.js";import{toSearchRecord as Xo}from"@chatpanel/events/library.js";import{deriveBackupKey as qo,openRecord as er,keyCache as tr,nodeCodec as or}from"@chatpanel/events/backup-envelope.js";import rr from"node:zlib";import*as E from"./ner-engine.js";import ht from"node:os";import{capabilitiesDocument as nr,handleDetect as sr}from"./capabilities.js";import{createExtractService as ar}from"./extract/service.js";import{workerSandbox as ir,disposeWorkerSandbox as lr}from"./worker-sandbox.js";import{createRuntime as cr}from"./runtime.js";import{createCapabilityProxy as dr}from"./capability-proxy.js";import{handleExtract as ur}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as mr}from"./extract-capability.js";import{createReader as pr}from"./retrieval/read.js";import{createSearcher as hr,toJinaSearch as yr,SEARCH_DEFAULTS as fr}from"./retrieval/search.js";import{createSearxng as gr}from"./retrieval/search-searxng.js";import{toJinaText as wr}from"./read-document.js";import*as A from"./stt-engine.js";import*as j from"./diarize-engine.js";import{providerOf as yt}from"./providers.js";import{createRemoteTranscriber as ft}from"./stt-remote.js";import{parseMultipart as br,decodeAudioFile as vr}from"./audio-file.js";import{MODEL_CATALOG as gt,isKnownModel as wt,isValidCustomModelId as bt,recommendFor as kr}from"./models.js";import{STT_MODEL_CATALOG as Sr,isKnownSttModel as Tr,isValidCustomSttId as xr,DEFAULT_STT_MODEL as Ne,STT_DTYPES as _r,isValidDtype as Or}from"./stt-models.js";import*as P from"./tts-engine.js";import{TTS_MODEL_CATALOG as vt,TTS_VOICES as $r,isKnownTtsModel as Pr,isValidCustomTtsId as Er,isKnownVoice as kt,isValidVoiceId as St,DEFAULT_TTS_MODEL as Tt,DEFAULT_TTS_VOICE as ue,TTS_DTYPES as Ar,isValidTtsDtype as Nr,MAX_TTS_CHARS as xt,ttsModelHasCustomVoices as Br,resolveDefaultModel as _t,POCKET_VOICES as Dr,DEFAULT_POCKET_VOICE as Be,isPocketVoice as De,ttsModelEngine as Me}from"./tts-models.js";import{ttsDestination as Mr,synthesizeRemote as Cr,isValidRemoteVoice as jr}from"./tts-remote.js";import{rawOrtAvailable as Ue}from"./ort.js";import*as K from"./tts-voices.js";import{resolveTtsVoice as Rr}from"./tts-voice-resolve.js";import{resolvePro as fe,checkQuota as Ir,consume as Lr,usage as Jr}from"./freegate.js";import{publicConfig as Ot,applyConfigPatch as zr,applyNerModelSelection as $t,persistConfig as me,configPath as se,bridgeAgentOptions as Pt,PERMISSION_MODES as
|
|
1
|
+
import{createServer as Wt}from"node:http";import{loadConfig as nt}from"./config.js";import{startEntitlementRefresh as Kt,maybeRevalidate as Qt}from"./entitlement-refresh.js";import{redactSegments as $e,segment as Re}from"./redact.js";import{pipeRestoredStream as Zt,pipeRestoredOpenAIStream as Yt,makeTokenRestorer as st,restoreDeep as Xt}from"./stream.js";import{restoreText as qt,gatedDictionary as eo,narrowSpecs as to,makeToolHarness as oo,placeholderToolNote as ro,placeholderNote as no,assertEndpointUrl as so,capRunOptions as ao,isPaired as io}from"@chatpanel/pii";import{ensureGatewayToken as Ie,currentGatewayToken as lo,isAdminAuthorized as X,callerTrustOf as Pe,setPinnedExtensionIds as co,issuePairingCode as uo,claimPairingCode as mo}from"./gateway-token.js";import{installEgressLedger as po,egressAudit as ho}from"./egress.js";import{initPolicy as yo,activePolicy as fo,applyPolicyToConfig as at,managedSummary as ke,PolicyLoadError as go}from"./policy.js";import{routeAllowed as it,agentAllowed as wo,egressAllowed as bo}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as ye}from"./bridge.js";import{secureFetch as Ee}from"./secure-fetch.js";import{streamBridgeChat as lt,readBridgeToken as de,openBridgeChat as vo}from"./bridge.js";import{createRelaySession as ko,getRelaySession as ct,endRelaySession as Se,pumpBridgeStream as So,deliverToolResult as To,toolsToSpecs as xo,wantsApprovals as _o,parseToolCallId as dt,touchRelaySession as Le}from"./toolrelay.js";import{shaperFor as Je}from"./shape.js";import{startNer as Oo,ensureNer as Ae,unionForThisMachine as $o,skippedCompanions as Po}from"./ner.js";import{recommendDetector as ut}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Eo}from"./log.js";import{saveBackupSecret as Ao,clearBackupSecret as No,loadBackupSecret as ze,hasBackupSecret as mt}from"./history-store.js";import{createMemoryStore as Bo}from"./memory-store.js";import{createPrefsStore as Do}from"./prefs-store.js";import{createTeamStore as Mo,loadOrCreateKey as Ge}from"./team-store.js";import{createScorecardStore as Co}from"./scorecard-store.js";import{createEngineLedgerStore as jo}from"./engine-ledger-store.js";import{createProjectStore as Ro}from"./project-store.js";import{applicationsFor as Io,recruitPass as Lo}from"./recruiting.js";import{ensureBridge as Jo}from"./bridge-supervisor.js";import{checkForUpdate as zo,updateStatus as Go,startUpdate as Ho,updateJob as Vo}from"./update.js";import{createHistoryStore as Uo}from"./sqlite-store.js";import{createEventStore as Fo}from"./event-store.js";import{ingestCloudEvents as Wo,cursorOf as pt}from"./event-sync.js";import{eventStats as Ko,projectYear as Qo}from"./event-stats.js";import{toCloudEvent as He}from"./cloudevents.js";import{fusionsDocument as Zo,resolveFusionModel as Yo}from"./fusions.js";import{ingestBackups as Ve}from"./backup-ingest.js";import{toSearchRecord as Xo}from"@chatpanel/events/library.js";import{deriveBackupKey as qo,openRecord as er,keyCache as tr,nodeCodec as or}from"@chatpanel/events/backup-envelope.js";import rr from"node:zlib";import*as E from"./ner-engine.js";import ht from"node:os";import{capabilitiesDocument as nr,handleDetect as sr}from"./capabilities.js";import{createExtractService as ar}from"./extract/service.js";import{workerSandbox as ir,disposeWorkerSandbox as lr}from"./worker-sandbox.js";import{createRuntime as cr}from"./runtime.js";import{createCapabilityProxy as dr}from"./capability-proxy.js";import{handleExtract as ur}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as mr}from"./extract-capability.js";import{createReader as pr}from"./retrieval/read.js";import{createSearcher as hr,toJinaSearch as yr,SEARCH_DEFAULTS as fr}from"./retrieval/search.js";import{createSearxng as gr}from"./retrieval/search-searxng.js";import{toJinaText as wr}from"./read-document.js";import*as A from"./stt-engine.js";import*as j from"./diarize-engine.js";import{providerOf as yt}from"./providers.js";import{createRemoteTranscriber as ft}from"./stt-remote.js";import{parseMultipart as br,decodeAudioFile as vr}from"./audio-file.js";import{MODEL_CATALOG as gt,isKnownModel as wt,isValidCustomModelId as bt,recommendFor as kr}from"./models.js";import{STT_MODEL_CATALOG as Sr,isKnownSttModel as Tr,isValidCustomSttId as xr,DEFAULT_STT_MODEL as Ne,STT_DTYPES as _r,isValidDtype as Or}from"./stt-models.js";import*as P from"./tts-engine.js";import{TTS_MODEL_CATALOG as vt,TTS_VOICES as $r,isKnownTtsModel as Pr,isValidCustomTtsId as Er,isKnownVoice as kt,isValidVoiceId as St,DEFAULT_TTS_MODEL as Tt,DEFAULT_TTS_VOICE as ue,TTS_DTYPES as Ar,isValidTtsDtype as Nr,MAX_TTS_CHARS as xt,ttsModelHasCustomVoices as Br,resolveDefaultModel as _t,POCKET_VOICES as Dr,DEFAULT_POCKET_VOICE as Be,isPocketVoice as De,ttsModelEngine as Me}from"./tts-models.js";import{ttsDestination as Mr,synthesizeRemote as Cr,isValidRemoteVoice as jr}from"./tts-remote.js";import{rawOrtAvailable as Ue}from"./ort.js";import*as K from"./tts-voices.js";import{resolveTtsVoice as Rr}from"./tts-voice-resolve.js";import{resolvePro as fe,checkQuota as Ir,consume as Lr,usage as Jr}from"./freegate.js";import{publicConfig as Ot,applyConfigPatch as zr,registryChildEnv as Gr,applyNerModelSelection as $t,persistConfig as me,configPath as se,bridgeAgentOptions as Pt,PERMISSION_MODES as Hr,sandboxEnvFor as Vr}from"./configstore.js";import Et from"node:path";import{resolveDestination as At,aggregateModelsAsync as Ur,listDestinations as Fr}from"./router.js";import{makeAccessEvent as Nt}from"./observability.js";import{createPersistentAccessLog as Wr}from"./access-log-store.js";import{planQueries as Kr,multiSearch as Qr}from"./rrf.js";import*as Fe from"./openai.js";import*as Bt from"./responses.js";import*as We from"./anthropic.js";import{closeAndExit as Zr}from"./shutdown.js";import{VERSION as ee}from"./version.js";import{VERSION as Ls}from"./version.js";const N=await Uo(),ae=new Set;function Ce({ids:t=[]}={}){const c=N.lossless;if(!c||!ae.size)return;const d=JSON.stringify({newest:c.newest,size:c.size,ids:t.slice(0,50),at:Date.now()});for(const m of ae)try{m.write(`event: records
|
|
2
2
|
data: ${d}
|
|
3
3
|
|
|
4
4
|
`)}catch{ae.delete(m)}}setInterval(()=>{for(const t of ae)try{t.write(`: ping
|
|
@@ -11,11 +11,11 @@ data: ${JSON.stringify(He(t))}
|
|
|
11
11
|
`)}catch{ge.delete(t)}},25e3).unref?.();const te=await Bo(),oe=Do(),we=Co({key:Ge()}),be=jo({key:Ge()}),Q=Ro({key:Ge()}),G=Mo({scorecards:we,engines:be}),Ke=new Set,Dt=(t,c)=>{for(const m of Ke)try{m({applied:t,by:c,revision:oe.revision})}catch{}const d=JSON.stringify({revision:oe.revision,applied:(t||[]).slice(0,50),by:c||"",at:Date.now()});for(const m of ae)try{m.write(`event: prefs
|
|
12
12
|
data: ${d}
|
|
13
13
|
|
|
14
|
-
`)}catch{ae.delete(m)}},Qe=
|
|
14
|
+
`)}catch{ae.delete(m)}},Qe=Wr(),Mt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Yr=16,Xr=/^mcp[_-]/i,Ct=t=>t&&t.function&&t.function.name||t&&t.name||"",qr=t=>t&&t.function&&t.function.description||t&&t.description||"";function jt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(c=>typeof c=="string"?c:c&&(c.text||c.content)||"").join(" "):""}function en(t,c){if(!t)return"";if(c==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(f=>jt(f&&(f.content??f))).join(" "):""}const d=Array.isArray(t.messages)?t.messages:[];for(let m=d.length-1;m>=0;m--)if(d[m]&&d[m].role==="user")return jt(d[m].content);return""}const Rt=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function It(t){if(!t)return!1;const c=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return c==="localhost"||c==="127.0.0.1"||c==="::1"}function tn(t,c){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(c.allowedOrigins)&&c.allowedOrigins.includes(t)}function on(t,c){t.setHeader("Access-Control-Allow-Origin",c||"*"),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 Lt=Date.now();function rn(t){if(!t)return"";const c={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(d=>`${c[d]||d} ${t[d]}ms`).join(" · ")}function nn(t){const c=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return c?{kind:c[1],id:c[2],...c[3]?{model:c[3]}:{}}:null}function sn(t){const c=performance.now(),d={};let m=!1;const f=(g,$)=>{d[g]=Math.round($*10)/10};return{meta:{},timings:d,mark:f,lap(g,$){f(g,performance.now()-$)},clock(){return performance.now()},commit(){if(m)return;m=!0,f("total",performance.now()-c);const g={...this.meta,timings:d};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}`:""} · ${rn(d)}`)})}}}function Jt(t,c){if(!t||!t.byToken||c!=="types"&&c!=="values")return;const d=[];for(const[m,f]of t.byToken){const g=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),$=g?g[1]:"PII",S=m.replace(/^\[\[|\]\]$/g,"");d.push(c==="values"?{token:S,type:$,value:f}:{token:S,type:$})}return d}function an(t,c,d){return We.matches(t)||"anthropic-version"in c?{kind:"anthropic",adapter:We,redactable:We.matches(t),base:d.upstreams?.anthropic?.baseUrl}:Bt.matches(t)?{kind:"responses",adapter:Bt,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Fe,redactable:Fe.matches(t),base:d.upstreams?.openai?.baseUrl}}function Ze(t,c){const d=String(t||"");if(Mt.has(d))return{agent:d,agentModel:""};const m=d.indexOf("/");if(m>0){const f=d.slice(0,m);if(Mt.has(f))return{agent:f,agentModel:d.slice(m+1)}}return{agent:c.bridge.agent,agentModel:""}}function zt(t,c){return Ze(t,c).agent}function ln(t,c){if(c!=="openai"||!t)return!1;const d=Fe.extractLatestToolResult(t);if(!d)return!1;const m=dt(d.tool_call_id);return!!(m&&ct(m.gwId))}function cn(t,c){try{const d=new URL(t),m=d.hostname.replace(/^\[|\]$/g,""),f=m==="127.0.0.1"||m==="localhost"||m==="::1",g=d.port||(d.protocol==="https:"?"443":"80");return f&&String(g)===String(c.port)}catch{return!1}}async function T(t,c){const d=[];let m=0;for await(const f of t){if(m+=f.length,c&&m>c){const g=new Error("payload too large");throw g.code=413,g}d.push(f)}return Buffer.concat(d)}function s(t,c,d){t.writeHead(c,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function Gt(t){const c=t.redaction?.detection?.url;return!c||t.redaction?.detection?.backend==="off"?null:c}function Ye(t){const c=t?.redaction?.detection,d=t?.redaction?.tier==="full"?"full":"basic";if(c&&c.backend&&c.backend!=="off")return{source:"external",backend:c.backend,state:"external",model:c.model||null,ready:!0,tier:d,coverage:d==="full"?"names":"patterns"};const m=E.health(),f=m.ok&&d==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:E.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:f,tier:d,coverage:f?"names":"patterns"}}async function Ht(t){if(E.state()!=="off"){const d=E.health();return{configured:d.configured,ok:d.ok,state:d.state,model:d.model,error:d.error||null,url:d.configured?`http://${t.host}:${t.port}/ner`:null,stats:d.stats,companions:d.companions}}const c=Gt(t);if(!c)return{configured:!1,ok:!1,url:null,model:null};try{const d=await Ee(c.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:c,model:null};const m=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:c,model:m.model||null}}catch{return{configured:!0,ok:!1,url:c,model:null}}}function dn(t,c){const d={};for(const[m,f]of Object.entries(t)){const g=m.toLowerCase();g.startsWith("x-chatpanel-")||Rt.has(g)||(d[m]=f)}d["accept-encoding"]="identity";try{d.host=new URL(c).host}catch{}return d}async function Vt(t,c,d,m){const f=st(c.vault);t.on("close",()=>{t.writableFinished||Se(c.id)});const g=m?m.clock():0;let $=g,S=!0;const x=()=>{m&&S&&(m.lap("upstream",g),$=m.clock(),S=!1)};await So(c,{onText:D=>{x(),Le(c.id);const _=f.push(D);_&&t.write(d.sseDelta(_))},onToolRequest:({name:D,restoredArgs:_,toolId:F})=>{x(),Le(c.id);const R=f.flush();R&&t.write(d.sseDelta(R)),t.write(d.sseToolCalls([{id:F,name:D,arguments:JSON.stringify(_)}])),t.write(d.sseToolFinish()),m&&m.lap("stream",$),t.end(),m?.commit()},onDone:()=>{const D=f.flush();D&&t.write(d.sseDelta(D)),t.write(d.sseTail()),m&&m.lap("stream",$),t.end(),Se(c.id),m?.commit()},onError:D=>{t.write(`data: ${JSON.stringify({error:{message:D.message,type:"bridge_error"}})}
|
|
15
15
|
|
|
16
|
-
`),t.end(),Se(c.id),m?.commit()}})}async function
|
|
16
|
+
`),t.end(),Se(c.id),m?.commit()}})}async function un(t,c,{kind:d,adapter:m,agent:f,run:g=null},$,S,x,D,_,F=null,R=null){const{messages:L,system:ie}=m.toTurn($),{agentModel:re}=Ze($?.model,x),n=Pt(x,{...re?{model:re}:{},...g||{}}),o=de(x.bridge.token),p=Je(d,$?.model||f),l={tier:x.redaction.tier==="full"?"full":"basic",dictionary:eo(x.redaction,D),entities:[]},C=await ye(x),Z=ko({vault:S,redactOpts:l,bridgeUrl:C,token:o,harness:F});let q;try{q=await vo({bridgeUrl:C,agent:f,token:o,messages:L,system:ie,specs:xo(_),options:n,signal:void 0,approvals:_o(_)})}catch(v){return Se(Z.id),R?.commit(),s(c,502,{error:{message:`bridge: ${v.message}`,type:"bridge_error"}})}return Z.reader=q.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(p.sseHead()),Vt(c,Z,p,R)}async function mn(t,c,d,m,f=null){Le(c.id),c.rounds=(c.rounds||0)+1;try{const $=f?f.clock():0;await To(c,d),f&&f.lap("redact",$)}catch($){return Se(c.id),f?.commit(),s(t,502,{error:{message:`tool-result: ${$.message}`,type:"bridge_error"}})}const g=Je("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(g.sseHead()),Vt(t,c,g,f)}async function pn(t,c,{kind:d,adapter:m,redactable:f,pathname:g,agentOverride:$,harness:S,trace:x,run:D=null},_,F,R,L){if(!f)return x?.commit(),s(c,404,{error:`endpoint ${g} not supported by the bridge backend`});if(d==="openai"){const V=m.extractLatestToolResult(_);if(V){const U=dt(V.tool_call_id),Y=U&&ct(U.gwId);if(Y)return mn(c,Y,V.content,_?.model,x)}const ne=m.extractTools(_);if(ne.length&&_?.stream===!0)return un(t,c,{kind:d,adapter:m,agent:$||zt(_?.model,R),run:D},_,F,R,L,ne,S,x)}const{messages:ie,system:re}=m.toTurn(_),n=$||zt(_?.model,R),o=_?.stream===!0,p=Je(d,_?.model||n),l=de(R.bridge.token),C=new AbortController;c.on("close",()=>{c.writableFinished||C.abort()});const{agentModel:Z}=Ze(_?.model,R),q={bridgeUrl:await ye(R),agent:n,token:l,messages:ie,system:re,signal:C.signal,options:Pt(R,{...Z?{model:Z}:{},...D||{}})};if(!o)try{let V="";const ne=x?x.clock():0;await lt(q,H=>{V+=H}),x&&x.lap("upstream",ne);const U=x?x.clock():0,Y=p.full(qt(V,F));return x&&x.lap("restore",U),c.writeHead(200,{"content-type":p.contentType}),c.end(Y),x?.commit()}catch(V){return x?.commit(),s(c,502,{error:{message:`bridge backend failed: ${V.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(p.sseHead());const v=st(F),le=x?x.clock():0;let ve=le;try{let V=!0;await lt(q,U=>{x&&V&&(x.lap("upstream",le),ve=x.clock(),V=!1);const Y=v.push(U);Y&&c.write(p.sseDelta(Y))},p.sseActivity?U=>{try{c.write(p.sseActivity(Xt(U,F)))}catch{}}:null);const ne=v.flush();ne&&c.write(p.sseDelta(ne)),c.write(p.sseTail())}catch(V){c.write(`data: ${JSON.stringify({error:{message:V.message,type:"bridge_error"}})}
|
|
17
17
|
|
|
18
|
-
`)}x&&x.lap("stream",ve),c.end(),x?.commit()}function
|
|
18
|
+
`)}x&&x.lap("stream",ve),c.end(),x?.commit()}function hn(t,c,d=""){const m=String(t||"").replace(/\/+$/,""),f=String(c||"").split("/")[1];return f&&m.endsWith(`/${f}`)?m.slice(0,-(f.length+1))+c+d:m+c+d}const yn=9e4;function fn(t,c,d){if(c===d)return t;const m=c/d,f=new Float32Array(Math.floor(t.length/m));for(let g=0;g<f.length;g++){const $=g*m,S=Math.floor($),x=Math.min(t.length-1,S+1),D=$-S;f[g]=t[S]*(1-D)+t[x]*D}return f}const gn=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];function Xe(t,c){const d=new URLSearchParams;for(const g of t.searchParams.getAll("dir"))g&&d.append("dir",g);const m=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();m&&d.set("workdir",m);const f=d.toString();return f?`?${f}`:""}async function wn(t,c,{adapter:d,kind:m,pathname:f,search:g,base:$,destKey:S,destProtocol:x,harness:D,trace:_},F,R){let L;const ie=_?_.clock():0;try{const p=dn(t.headers,$);S&&(x==="anthropic"?(p["x-api-key"]=S,delete p.authorization):p.authorization=`Bearer ${S}`);const l=so(hn($,f,g)).toString();L=await fetch(l,{method:t.method,headers:p,body:["GET","HEAD"].includes(t.method)?void 0:F})}catch(p){return _?.commit(),s(c,502,{error:`upstream fetch failed: ${p.message}`})}const re=L.headers.get("content-type")||"",n={};if(L.headers.forEach((p,l)=>{Rt.has(l.toLowerCase())||(n[l]=p)}),re.includes("text/event-stream")&&L.body){_&&_.lap("upstream",ie);const p=_?_.clock():0;c.writeHead(L.status,n);const l=m==="openai"?Yt(L.body,c,R,D):Zt(L.body,c,R);return Promise.resolve(l).finally(()=>{_&&_.lap("stream",p),_?.commit()})}const o=Buffer.from(await L.arrayBuffer());if(_&&_.lap("upstream",ie),R&&re.includes("application/json"))try{const p=_?_.clock():0,l=d.restoreResponse(JSON.parse(o.toString("utf8")),R,D);return _&&_.lap("restore",p),c.writeHead(L.status,{...n,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(l),"utf8")),_?.commit()}catch{}c.writeHead(L.status,n),c.end(o),_?.commit()}function bn(t=nt()){let c=null;const d=()=>{if(!c){const n=t.read||{};c=pr({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return c};let m=null;const f=()=>(m||(m=ar({wrap:(n,o,p,l)=>ir().wrap(n,o,p,l),onLog:n=>console.warn(`[extract worker] ${n}`)})),m);let g={at:0,fn:()=>"unknown"},$=null;async function S(){if(Date.now()-g.at<1e4)return g.fn;let n=new Map;try{const l=await D().health();for(const[C,Z]of Object.entries(l)){const q=(t.destinations||[]).filter(v=>v?.service===C).flatMap(v=>[v.id,...v.models||[]]);for(const v of[C,...q])n.set(v,Z)}}catch{n=new Map}const o=l=>n.get(l)||"unknown",p=new Map((t.destinations||[]).filter(l=>l?.service).map(l=>[l.id,l.service]));return o.window=l=>{try{return D().contextWindow(p.get(l)||l)}catch{return null}},o.card=l=>{try{return D().modelCard(p.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 D=()=>(x||(x=cr({cfg:t,bridgeHealth:async()=>{const n=await ye(t);if(!n)return null;const o=de(t.bridge?.token),p=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return p.ok?p.json():null},persist:()=>{try{me(t,se())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Et.join(Et.dirname(se()),"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),_=dr({cfg:t});let F=null;const R=()=>{if(!F){const n=t.search||{},o=n.searxng?.url?gr({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;F=hr({reader:d(),searxng:o,defaultProvider:n.provider||"auto",redact:async p=>{let l=p;return await $e([Re(()=>l,C=>{l=C})],{...t.redaction,tier:"basic"},{isPro:!0}),l}})}return F};co(t.allowedExtensionIds||[]);const L=[],ie=n=>{L.push(n),L.length>50&&L.shift()},re=Wt(async(n,o)=>{const p=new URL(n.url,"http://127.0.0.1"),l=p.pathname;if(!It(n.headers.host))return s(o,403,{error:"loopback only"});if(!tn(n.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(n.headers.origin&&on(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(l==="/admin/token"&&n.method==="POST")return X(n)?s(o,200,{token:Ie()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(l==="/pair/code"&&n.method==="POST"){if(!X(n))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=uo();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=mo(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Pe(n)} caller`),s(o,403,{error:r.reason});console.log(`[gateway] paired a ${Pe(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const a=de(t.bridge?.token);return s(o,200,{ok:!0,token:lo()||Ie(),...a?{bridgeToken:a}:{}})}if(l==="/whoami"&&n.method==="POST"){const e=Pe(n);return s(o,200,{ok:!0,trust:e,paired:io(e),version:ee})}if(l==="/audit"&&n.method==="GET")return X(n)?s(o,200,ho(t,{version:ee,startedAt:Lt,managed:ke()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((l==="/config"||l==="/logs"||l==="/update"&&n.method!=="GET")&&!X(n))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(l==="/update"&&n.method==="GET"){const e=await zo(ee,{force:p.searchParams.get("force")==="1"}).catch(r=>({current:ee,updateAvailable:!1,error:String(r?.message||r)}));return s(o,200,{ok:!0,update:e,job:Vo()})}if(l==="/update"&&n.method==="POST"){const e=Ho(ee);return s(o,e.already?409:202,{ok:!0,job:e})}if((l==="/v1/history/key"||l==="/v1/history/ingest-backup")&&n.method==="POST"&&!X(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"&&!X(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"&&!X(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"&&!X(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"))&&!X(n))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/events"||l.startsWith("/v1/events/"))&&!X(n))return s(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(l.startsWith("/v1/observability")&&!X(n))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&l==="/health"){const e=A.health(),r=P.health();return s(o,200,{ok:!0,version:ee,backend:t.backend,tier:t.redaction.tier,pairing:!0,...ke()?{managed:ke()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...Te?{bridge:Te.status()}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Ne,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||Tt,voice:t.tts?.voice||ue,runtime:r.runtime,dtype:r.dtype},events:z?{count:z.count(),hosts:z.hosts().length}:null})}if(l==="/status"&&n.method==="GET"){Qt(t);const e=await fe(t.pro?.entitlementToken),r=await Ht(t);return s(o,200,{ok:!0,version:ee,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...ke()?{managed:ke()}:{},...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:Ye(t),pro:{unlocked:e},usage:Jr(t),uptimeSeconds:Math.floor((Date.now()-Lt)/1e3),update:Go(ee)})}if(l==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=N.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:r})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(l==="/v1/prefs"&&n.method==="GET"){const e=String(p.searchParams.get("section")||"");return p.searchParams.get("stamps")?s(o,200,{ok:!0,revision:oe.revision,stamps:oe.stamps()}):s(o,200,{ok:!0,revision:oe.revision,sections:oe.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=oe.put(e.sections||{},{by:e.by||""});return r.applied.length&&Dt(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(p.searchParams.get("section")||""),r=e?oe.remove(e):!1;return r&&Dt([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)}
|
|
19
19
|
|
|
20
20
|
`);e({type:"hello",revision:oe.revision,stamps:oe.stamps()});const r=i=>e({type:"changed",...i});Ke.add(r);const a=setInterval(()=>{try{o.write(`: keep-alive
|
|
21
21
|
|
|
@@ -23,11 +23,11 @@ data: ${d}
|
|
|
23
23
|
|
|
24
24
|
`);let k=p.searchParams.has("after")?Number(p.searchParams.get("after")):-1;y({seq:-1,type:"hello",at:Date.now(),payload:{project:Q.get(r),after:k}});const b=Q.watch(r,O=>{O.seq>k&&(k=O.seq,y(O))});for(const O of Q.eventsSince(r,k))k=O.seq,y(O);const h=setInterval(()=>{try{o.write(`: keep
|
|
25
25
|
|
|
26
|
-
`)}catch{}},25e3);n.on("close",()=>{clearInterval(h),b()});return}}}if(l==="/v1/agents/scorecards"&&n.method==="GET")return s(o,200,{ok:!0,agents:we.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 we.get(r)});if(n.method==="POST")try{const a=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},i=await we.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 be.fromRating(we.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,nr(t,{version:ee,reader:c,searcher:F,extract:f(),proxy:_}));if(l==="/v1/fusions"&&n.method==="GET"){const e={active:E.health().model||t.ner?.model||null,companions:E.companions()};let r=null;try{r=await D().status()}catch{r=null}return s(o,200,Zo({cfg:t,ner:e,runtimeDoc:r}))}if(l==="/v1/runtime"&&n.method==="GET")return s(o,200,await D().status());{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(l);if(e&&n.method==="POST"){if(!X(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=D(),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 _.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 sr(e,{ensure:()=>Ae(t),model:E.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(mr*4/3)+1024))).toString("utf8"))}catch{return s(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await ur(e,{service:f()});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 d().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"}})}const r=await R().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=p.searchParams.has("read")?Math.max(0,Math.min(10,Number(p.searchParams.get("read"))||0)):fr.aliasRead,a=await R().search({q:e,read:r,limit:Math.max(r,5)});return s(o,a.status,a.status===200?yr(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 d().read({url:r,format:i});return u.status!==200||a?s(o,u.status,u.status===200?{code:200,status:2e4,data:u.body}:u.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":u.body.provider}),o.end(wr(u.body)))}if(l==="/v1/engines"&&n.method==="GET"){const e=Number(p.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:be.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(p.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await be.get(r,{entries:p.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||
|
|
26
|
+
`)}catch{}},25e3);n.on("close",()=>{clearInterval(h),b()});return}}}if(l==="/v1/agents/scorecards"&&n.method==="GET")return s(o,200,{ok:!0,agents:we.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 we.get(r)});if(n.method==="POST")try{const a=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},i=await we.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 be.fromRating(we.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,nr(t,{version:ee,reader:c,searcher:F,extract:f(),proxy:_}));if(l==="/v1/fusions"&&n.method==="GET"){const e={active:E.health().model||t.ner?.model||null,companions:E.companions()};let r=null;try{r=await D().status()}catch{r=null}return s(o,200,Zo({cfg:t,ner:e,runtimeDoc:r}))}if(l==="/v1/runtime"&&n.method==="GET")return s(o,200,await D().status());{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(l);if(e&&n.method==="POST"){if(!X(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=D(),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 _.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 sr(e,{ensure:()=>Ae(t),model:E.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(mr*4/3)+1024))).toString("utf8"))}catch{return s(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await ur(e,{service:f()});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 d().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"}})}const r=await R().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=p.searchParams.has("read")?Math.max(0,Math.min(10,Number(p.searchParams.get("read"))||0)):fr.aliasRead,a=await R().search({q:e,read:r,limit:Math.max(r,5)});return s(o,a.status,a.status===200?yr(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 d().read({url:r,format:i});return u.status!==200||a?s(o,u.status,u.status===200?{code:200,status:2e4,data:u.body}:u.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":u.body.provider}),o.end(wr(u.body)))}if(l==="/v1/engines"&&n.method==="GET"){const e=Number(p.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:be.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(p.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await be.get(r,{entries:p.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||nn(r);if(!i)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const u=await be.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/runs"&&n.method==="GET")return s(o,200,{ok:!0,runs:G.list({limit:p.searchParams.get("limit")||50,team:p.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:G.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return s(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(l);if(e){const r=e[1],a=e[2]||"";if(!a&&n.method==="GET"){const i=G.get(r,{events:p.searchParams.get("events")==="1"});return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!a&&n.method==="DELETE")return G.stop(r),s(o,200,{ok:!0,removed:G.remove(r)});if(a==="/stop"&&n.method==="POST"){const i=G.stop(r);return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(a==="/checkpoint"&&n.method==="GET")try{return s(o,200,{ok:!0,checkpoint:G.checkpoint(r)})}catch(i){return s(o,404,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&n.method==="POST")try{const i=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},u=a==="/handoff"?G.handoff(r,{taskId:i.taskId,model:i.model,by:i.by,reason:i.reason}):G.claim(r,{client:i.client});return s(o,200,{ok:!0,run:u})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&n.method==="DELETE")try{return s(o,200,{ok:!0,run:G.removeThread(r,{threadId:a.slice(9),by:"person"})})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&n.method==="POST")try{const i=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},u=String(i.by||"person").slice(0,40),w=a==="/answer"?G.answer(r,{threadId:i.threadId,text:i.text,by:u}):a==="/decide"?G.decide(r,{postId:i.postId,status:i.status,by:u}):G.post(r,{threadId:i.threadId,text:i.text,by:u,kind:i.kind,replyTo:i.replyTo});return s(o,200,{ok:!0,run:w})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&n.method==="POST")try{const i=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:G.append(r,i.events||[])})}catch(i){return s(o,i.message.startsWith("no run")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&n.method==="GET"){if(!G.get(r))return s(o,404,{error:{message:`no run ${r}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const i=b=>o.write(`data: ${JSON.stringify(b)}
|
|
27
27
|
|
|
28
28
|
`),u=p.searchParams.has("after")?Number(p.searchParams.get("after")):NaN;let w=Number.isFinite(u)?u:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:G.get(r),after:w}});const y=G.watch(r,b=>{b.seq==null?i(b):b.seq>w&&(w=b.seq,i(b))});for(const b of G.eventsSince(r,w))w=b.seq,i(b);const k=setInterval(()=>{try{o.write(`: keep-alive
|
|
29
29
|
|
|
30
|
-
`)}catch{}},25e3);o.on("close",()=>{y(),clearInterval(k)});return}}}if(l==="/v1/memory/list"&&n.method==="GET")return s(o,200,{ok:!0,size:te.size,memories:te.list()});if(l==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.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:te.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=te.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:te.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}=te.forget(String(e.query||""));return s(o,200,{ok:!0,removed:r,size:te.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=te.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...r,memories:te.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:te.clear(),size:te.size});if(l==="/v1/history/clear"&&n.method==="POST"){const e=N.clear();return s(o,200,{ok:!0,dropped:e,size:N.size})}if(l==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=N.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return s(o,200,{ok:!0,size:N.size,newest:N.newest,results:r})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(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=
|
|
30
|
+
`)}catch{}},25e3);o.on("close",()=>{y(),clearInterval(k)});return}}}if(l==="/v1/memory/list"&&n.method==="GET")return s(o,200,{ok:!0,size:te.size,memories:te.list()});if(l==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.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:te.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=te.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:te.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}=te.forget(String(e.query||""));return s(o,200,{ok:!0,removed:r,size:te.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=te.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...r,memories:te.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:te.clear(),size:te.size});if(l==="/v1/history/clear"&&n.method==="POST"){const e=N.clear();return s(o,200,{ok:!0,dropped:e,size:N.size})}if(l==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=N.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return s(o,200,{ok:!0,size:N.size,newest:N.newest,results:r})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(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=Kr(r,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),i={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},u=Math.min(30,Math.max(5,Number(e.limit)||10)*2),w=await Qr(a,k=>N.search(k,{limit:u,...i}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),y=i.type?w:[...w.filter(k=>k.type==="brief"),...w.filter(k=>k.type!=="brief")];return s(o,200,{ok:!0,size:N.size,newest:N.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(p.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(p.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:N.related(e,{limit:r})})}if(l==="/v1/history/status"&&n.method==="GET")return s(o,200,{ok:!0,size:N.size,newest:N.newest,bytes:N.bytes,lossless:N.lossless?{records:N.lossless.size,newest:N.lossless.newest}:null});if(l==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(p.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:N.size,bytes:N.bytes,newest:N.newest}},access:Qe.snapshot(e)})}if(l==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=Qe.push(Nt({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=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},a=String(r.host||"").slice(0,80),i=Number(r.at)||Date.now(),u=[];let w=0;const y={upserts:[],removes:[]},k=b=>{if(!b||b.deletedAt){b?.id&&y.removes.push(b.id);return}try{const h=Xo(b);h&&y.upserts.push(h)}catch{}};if(Array.isArray(r.records)){const b=e.upsert(r.records,{host:a,at:i});u.push(...b);for(const h of r.records)b.includes(h?.id)&&k(h)}if(Array.isArray(r.entries)){const b=ze(),h=b?tr((M,W)=>qo(b,{salt:M,iterations:W})):null,O=async M=>{if(!h||!M.blob)return null;const W=await h(M.blob),he=M.blob.compression&&M.blob.compression!=="none"?or(rr,M.blob.compression):null;return er(M.blob,W,{codec:he})},I=await e.upsertEntries(r.entries,{open:O});u.push(...I.written),w+=I.sealed;for(const M of I.written)k(e.get(M))}return(y.upserts.length||y.removes.length)&&N.bulk(y),u.length&&Ce({ids:u}),s(o,200,{ok:!0,written:u.length,ids:u,sealed:w,size:e.size})}catch(r){return s(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(l==="/v1/events"&&n.method==="POST"){if(!z)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=Wo(z,r);return s(o,200,{ok:!0,appended:a.appended,duplicates:a.duplicates,rejected:a.rejected,cursor:z.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 z?s(o,200,{ok:!0,cursor:z.cursor(),count:z.count()}):s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(l==="/v1/events/stats"&&n.method==="GET"){if(!z)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=Ko(z.all());return s(o,200,{ok:!0,stats:e,year:Qo(e)})}if(l==="/v1/events"&&n.method==="GET"){if(!z)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=pt(JSON.parse(p.searchParams.get("cursor")||"{}"))}catch{return s(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=z.since(e,{limit:Number(p.searchParams.get("limit"))||void 0,host:p.searchParams.get("host")||null});return s(o,200,{ok:!0,events:r.events.map(a=>He(a)),cursor:r.cursor,more:r.more})}if(l==="/v1/events/stream"&&n.method==="GET"){if(!z)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(p.searchParams.has("cursor"))try{e=pt(JSON.parse(p.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
|
|
31
31
|
data: ${JSON.stringify({cursor:z.cursor(),count:z.count(),version:ee})}
|
|
32
32
|
|
|
33
33
|
`),ge.add(o),n.on("close",()=>ge.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=z.since(r.cursor);for(const a of r.events)o.write(`event: cloudevent
|
|
@@ -36,6 +36,6 @@ data: ${JSON.stringify(He(a))}
|
|
|
36
36
|
`)}}return}if(l==="/v1/history/stream"&&n.method==="GET"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
|
|
37
37
|
data: ${JSON.stringify({newest:e.newest,size:e.size,version:ee,prefsRevision:oe.revision})}
|
|
38
38
|
|
|
39
|
-
`),ae.add(o),n.on("close",()=>ae.delete(o));return}if(l==="/v1/history/records"&&n.method==="GET"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(p.searchParams.get("since"))||0,cursor:p.searchParams.get("cursor")||"",limit:Number(p.searchParams.get("limit"))||200,kind:p.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(p.searchParams.get("limit"))||50)),r=Math.max(0,Number(p.searchParams.get("offset"))||0),a=p.searchParams.get("type")||null;return s(o,200,{ok:!0,...N.list({limit:e,offset:r,type:a})})}if(l==="/v1/history/get"&&n.method==="GET"){const e=p.searchParams.get("maxChars")!=null?Math.max(1,Number(p.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(p.searchParams.get("offset"))||0),a=N.get(String(p.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:mt()});if(l==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Ao(String(e.passphrase)):No();const r=e.passphrase?await Ve(N,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ce(),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 Ve(N,ze());return e.ok&&e.whole&&Ce(),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 Ht(t);return s(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Ae(t),E.state()!=="off"){if(!E.isReady()){const r=E.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 E.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=Gt(t);if(!e){const r=E.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:E.state(),model:t.ner?.model||null})}try{const r=await T(n,t.maxBodyBytes),a=await Ee(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:Ye(t)});try{let r=e;const a=await fe(t.pro?.entitlementToken);await Ae(t);const i=await $e([Re(()=>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:Jt(i.vault,"types")||[],detector:Ye(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=E.health().model||t.ner?.model||null,r=Math.round(ht.totalmem()/1048576),a=kr(gt,{totalRamMB:r}).map(i=>({...i,installed:E.modelOnDisk(i.id)}));for(const i of[e,...E.modelsOnDisk()])!i||a.some(u=>u.id===i)||a.push({id:i,label:i,lang:"—",custom:!0,installed:E.modelOnDisk(i),note:"Custom model (from Hugging Face)."});return s(o,200,{active:e,companions:E.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Po(),recommendation:ut(a,{totalRamMB:r},[]),state:E.state(),progress:E.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(ht.totalmem()/1048576),i=ut(gt.map(u=>({...u,installed:E.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(!(wt(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||E.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=a.filter(u=>u!==i),r&&$t(t,r);try{me(t,se())}catch{}return(async()=>{r&&await E.setModel(r,{onLog:w=>console.log(w)});const u=$o(t.ner,{log:w=>console.log(w)});for(const w of E.companions())u.includes(w.model)||await E.removeCompanion(w.model);for(const w of u)await E.addCompanion(w,{onLog:y=>console.log(y),allowDownload:t.ner.allowDownload!==!1});E.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),s(o,202,{accepted:!0,active:i,union:t.ner.union,companions:E.companions(),state:E.state()})}if(!r||!(wt(r)||bt(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});$t(t,r);try{me(t,se())}catch{}return E.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:E.state(),progress:E.progress()})}}if(l==="/stt/models"){if(n.method==="GET"){const e=A.health().model||t.stt?.model||Ne,r=Sr.map(a=>({...a,installed:A.modelOnDisk(a.id)}));return e&&!r.some(a=>a.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:A.state(),progress:A.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:_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||!(Tr(r)||xr(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&Or(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{me(t,se())}catch{}return A.setModel(r,{onLog:i=>console.log(i),dtype:a||t.stt.dtype||"auto",warmMs:t.stt.warmMs}),s(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress()})}}if(l==="/diarize/model"){if(n.method==="GET"){const e=j.health();return s(o,200,{active:j.DIARIZE_MODEL,state:e.state,progress:j.progress(),available:[{id:j.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:j.modelOnDisk()}]})}if(n.method==="POST")return j.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:j.DIARIZE_MODEL,state:j.state(),progress:j.progress()})}if(l==="/tts/models"){if(n.method==="GET"){const e=P.health().model||t.tts?.model||_t(Ue()),r=Ue(),a=vt.find(u=>u.id===e)||null,i=vt.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||(Me(e)==="pocket-tts"?Be:ue),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()&&Me(e)==="pocket-tts"?(P.builtinVoices().length?P.builtinVoices():Dr).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:P.builtinVoices().includes(u)})):P.arch()&&P.arch()!=="style-tts2"?[]:$r.map(u=>({...u,installed:P.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:P.health().dtype,runtime:P.health().runtime,dtypes:Ar})}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&&!(Pr(r)||Er(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=K.parseCustomVoice(a);if(!(u?!!K.getVoice(u):De(a)||kt(a)&&St(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&Nr(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Tt,voice:ue,allowDownload:!0}),r&&(t.tts.model=r),a&&(t.tts.voice=a),r&&!a){const u=Br(r),w=K.parseCustomVoice(t.tts.voice||""),y=!!(w&&K.getVoice(w));if(u&&!y)if(Me(r)==="pocket-tts")t.tts.voice=Be;else{const b=K.listVoices();t.tts.voice=b.length?`custom:${b[0].id}`:""}else!u&&y&&(t.tts.voice=ue);const k=Me(r)==="pocket-tts";k&&!K.parseCustomVoice(t.tts.voice||"")&&!De(t.tts.voice)&&(t.tts.voice=Be),!k&&De(t.tts.voice)&&(t.tts.voice=ue)}i&&(t.tts.dtype=i==="auto"?null:i);try{me(t,se())}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:K.listVoices(),usable:P.supportsCustomVoices(),embedder:j.DIARIZE_MODEL,embedderReady:j.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(!K.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,{...K.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(!j.isReady()){const h=j.download({onLog:M=>console.log(M)}),O=Symbol("timeout"),I=await Promise.race([h.then(()=>null).catch(M=>M),new Promise(M=>setTimeout(()=>M(O),hn))]);if(I===O||!j.isReady())return s(o,503,{error:{message:I===O?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${j.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:j.progress()})}const u=Float32Array.from(a),w=await j.embed(u);let y=null;try{const h=await P.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:O=>console.log(O)});h&&(y=await h.encodeVoice(yn(u,16e3,24e3)))}catch(h){console.log(`[tts] pocket conditioning unavailable for this voice (${h.message})`)}const k=i?K.replaceVoice(i,{vec:w,pocket:y}):K.saveVoice({name:r,vec:w,pocket:y}),b=i&&r&&r!==k.name?K.renameVoice(i,r):k;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${b.name}" (${(k.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...k,...b,usable:P.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=p.searchParams.get("id")||"",r=K.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const a=K.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:ue;try{me(t,se())}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>xt)return s(o,413,{error:{message:`text too long (max ${xt} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=Mr(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,w=u||(i?i.voice:t.tts?.voice||ue);if(i&&!jr(w))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:ce,contentType:J,redacted:je}=await Cr({dest:i,text:r,voice:w,speed:a,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await fe(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":J,"Content-Length":String(ce.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(je)}),o.end(ce)}if(!await P.ready({onLog:ce=>console.log(ce),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||_t(Ue()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:P.health().error||"tts model not ready",type:"tts_unavailable"}});const b=Rr({requested:u,configured:w,engine:P,voices:K,isPocketVoice:De,isKnownVoice:kt,isValidVoiceId:St,defaultVoice:ue,defaultPocketVoice:Be});if(!b.ok)return s(o,b.status,{error:{message:b.message,type:b.type}});const{voice:h,customId:O,speakerEmbedding:I}=b,M=await P.synth(r,{voice:h,speed:a,speakerEmbedding:I}),W=P.sampleRate(),he=y==="pcm"?Buffer.from(new Float32Array(M).buffer):P.toWav(M,W);return o.writeHead(200,{"Content-Type":y==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(he.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(W),...O||P.isPocket()||P.supportsVoices()?{"X-Tts-Voice":h}:{}}),o.end(he)}catch(k){return s(o,500,{error:{message:k.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=br(await T(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(h){return s(o,h.code===413?413:415,{error:{message:h.message,type:"bad_request"}})}const r=h=>e.find(O=>O.name===h&&!O.filename)?.data.toString("utf8").trim()||"",a=e.find(h=>h.name==="file"&&h.filename)||e.find(h=>h.filename);if(!a?.data?.length)return s(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let i;try{i=await vr(a.data)}catch(h){return s(o,h.code===415?415:500,{error:{message:h.message,type:"unsupported_media"}})}const u=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",w=yt(t,"stt");let y=null;if(w.kind==="remote"||w.kind==="container")try{y=ft(w,{fetchImpl:Ee})}catch(h){return s(o,500,{error:{message:`stt provider: ${h.message}`,type:"bad_provider"}})}!y&&!A.isReady()&&A.init({model:t.stt?.model||Ne,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,onLog:h=>console.log(h)});const k=r("diarize")==="true"&&t.stt?.diarize!==!1;k&&!j.isReady()&&j.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:h=>console.log(h)});const b=Date.now();try{const{id:h}=A.createSession({lang:r("language")||void 0,diarize:k,interims:!1,remote:y}),O=[];let I=null;A.subscribe(h,J=>{J.type==="final"&&J.text?O.push(J):J.type==="language"&&(I=J.lang)});const M=16e3*5;for(let J=0;J<i.pcm.length;J+=M)A.pushAudio(h,i.pcm.subarray(J,Math.min(i.pcm.length,J+M)));await A.endSession(h);let W=0;const he=O.map((J,je)=>{const Ut=W,Ft=(J.durationMs||0)/1e3;return W+=Ft,{id:je,start:Math.round(Ut*100)/100,end:Math.round(W*100)/100,text:J.text,...J.speaker?{speaker:J.speaker}:{}}}),ce=he.map(J=>J.text).join(" ").replace(/\s+/g," ").trim();return u==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(ce)):u==="verbose_json"?s(o,200,{task:"transcribe",language:I||r("language")||null,duration:Math.round(i.seconds*100)/100,text:ce,segments:he,provider:w.kind,took_ms:Date.now()-b}):s(o,200,{text:ce})}catch(h){return s(o,h.code==="too_many_sessions"?429:500,{error:{message:h.message,type:h.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=yt(t,"stt");let a=null;if(r.kind==="remote"||r.kind==="container")try{a=ft(r,{fetchImpl:Ee})}catch(u){return s(o,500,{error:{message:`stt provider: ${u.message}`,type:"bad_provider"}})}!a&&!A.isReady()&&A.init({model:t.stt?.model||Ne,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});const i=e?.diarize===!0&&t.stt?.diarize!==!1;i&&!j.isReady()&&j.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});try{const{id:u}=A.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:A.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 A.pushAudio(r,A.toFloat32(a)),s(o,200,{ok:!0,state:A.state()})}catch(a){return s(o,a.code==="no_session"?404:400,{error:{message:a.message,type:a.code||"stt_error"}})}if(e[2]==="/events"&&n.method==="GET"){const a=A.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=h=>o.write(`data: ${JSON.stringify(h)}
|
|
39
|
+
`),ae.add(o),n.on("close",()=>ae.delete(o));return}if(l==="/v1/history/records"&&n.method==="GET"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(p.searchParams.get("since"))||0,cursor:p.searchParams.get("cursor")||"",limit:Number(p.searchParams.get("limit"))||200,kind:p.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(p.searchParams.get("limit"))||50)),r=Math.max(0,Number(p.searchParams.get("offset"))||0),a=p.searchParams.get("type")||null;return s(o,200,{ok:!0,...N.list({limit:e,offset:r,type:a})})}if(l==="/v1/history/get"&&n.method==="GET"){const e=p.searchParams.get("maxChars")!=null?Math.max(1,Number(p.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(p.searchParams.get("offset"))||0),a=N.get(String(p.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:mt()});if(l==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Ao(String(e.passphrase)):No();const r=e.passphrase?await Ve(N,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ce(),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 Ve(N,ze());return e.ok&&e.whole&&Ce(),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 Ht(t);return s(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Ae(t),E.state()!=="off"){if(!E.isReady()){const r=E.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 E.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=Gt(t);if(!e){const r=E.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:E.state(),model:t.ner?.model||null})}try{const r=await T(n,t.maxBodyBytes),a=await Ee(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:Ye(t)});try{let r=e;const a=await fe(t.pro?.entitlementToken);await Ae(t);const i=await $e([Re(()=>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:Jt(i.vault,"types")||[],detector:Ye(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=E.health().model||t.ner?.model||null,r=Math.round(ht.totalmem()/1048576),a=kr(gt,{totalRamMB:r}).map(i=>({...i,installed:E.modelOnDisk(i.id)}));for(const i of[e,...E.modelsOnDisk()])!i||a.some(u=>u.id===i)||a.push({id:i,label:i,lang:"—",custom:!0,installed:E.modelOnDisk(i),note:"Custom model (from Hugging Face)."});return s(o,200,{active:e,companions:E.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Po(),recommendation:ut(a,{totalRamMB:r},[]),state:E.state(),progress:E.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(ht.totalmem()/1048576),i=ut(gt.map(u=>({...u,installed:E.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(!(wt(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||E.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=a.filter(u=>u!==i),r&&$t(t,r);try{me(t,se())}catch{}return(async()=>{r&&await E.setModel(r,{onLog:w=>console.log(w)});const u=$o(t.ner,{log:w=>console.log(w)});for(const w of E.companions())u.includes(w.model)||await E.removeCompanion(w.model);for(const w of u)await E.addCompanion(w,{onLog:y=>console.log(y),allowDownload:t.ner.allowDownload!==!1});E.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),s(o,202,{accepted:!0,active:i,union:t.ner.union,companions:E.companions(),state:E.state()})}if(!r||!(wt(r)||bt(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});$t(t,r);try{me(t,se())}catch{}return E.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:E.state(),progress:E.progress()})}}if(l==="/stt/models"){if(n.method==="GET"){const e=A.health().model||t.stt?.model||Ne,r=Sr.map(a=>({...a,installed:A.modelOnDisk(a.id)}));return e&&!r.some(a=>a.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:A.state(),progress:A.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:_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||!(Tr(r)||xr(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&Or(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{me(t,se())}catch{}return A.setModel(r,{onLog:i=>console.log(i),dtype:a||t.stt.dtype||"auto",warmMs:t.stt.warmMs}),s(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress()})}}if(l==="/diarize/model"){if(n.method==="GET"){const e=j.health();return s(o,200,{active:j.DIARIZE_MODEL,state:e.state,progress:j.progress(),available:[{id:j.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:j.modelOnDisk()}]})}if(n.method==="POST")return j.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:j.DIARIZE_MODEL,state:j.state(),progress:j.progress()})}if(l==="/tts/models"){if(n.method==="GET"){const e=P.health().model||t.tts?.model||_t(Ue()),r=Ue(),a=vt.find(u=>u.id===e)||null,i=vt.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||(Me(e)==="pocket-tts"?Be:ue),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()&&Me(e)==="pocket-tts"?(P.builtinVoices().length?P.builtinVoices():Dr).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:P.builtinVoices().includes(u)})):P.arch()&&P.arch()!=="style-tts2"?[]:$r.map(u=>({...u,installed:P.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:P.health().dtype,runtime:P.health().runtime,dtypes:Ar})}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&&!(Pr(r)||Er(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=K.parseCustomVoice(a);if(!(u?!!K.getVoice(u):De(a)||kt(a)&&St(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&Nr(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Tt,voice:ue,allowDownload:!0}),r&&(t.tts.model=r),a&&(t.tts.voice=a),r&&!a){const u=Br(r),w=K.parseCustomVoice(t.tts.voice||""),y=!!(w&&K.getVoice(w));if(u&&!y)if(Me(r)==="pocket-tts")t.tts.voice=Be;else{const b=K.listVoices();t.tts.voice=b.length?`custom:${b[0].id}`:""}else!u&&y&&(t.tts.voice=ue);const k=Me(r)==="pocket-tts";k&&!K.parseCustomVoice(t.tts.voice||"")&&!De(t.tts.voice)&&(t.tts.voice=Be),!k&&De(t.tts.voice)&&(t.tts.voice=ue)}i&&(t.tts.dtype=i==="auto"?null:i);try{me(t,se())}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:K.listVoices(),usable:P.supportsCustomVoices(),embedder:j.DIARIZE_MODEL,embedderReady:j.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(!K.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,{...K.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(!j.isReady()){const h=j.download({onLog:M=>console.log(M)}),O=Symbol("timeout"),I=await Promise.race([h.then(()=>null).catch(M=>M),new Promise(M=>setTimeout(()=>M(O),yn))]);if(I===O||!j.isReady())return s(o,503,{error:{message:I===O?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${j.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:j.progress()})}const u=Float32Array.from(a),w=await j.embed(u);let y=null;try{const h=await P.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:O=>console.log(O)});h&&(y=await h.encodeVoice(fn(u,16e3,24e3)))}catch(h){console.log(`[tts] pocket conditioning unavailable for this voice (${h.message})`)}const k=i?K.replaceVoice(i,{vec:w,pocket:y}):K.saveVoice({name:r,vec:w,pocket:y}),b=i&&r&&r!==k.name?K.renameVoice(i,r):k;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${b.name}" (${(k.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...k,...b,usable:P.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=p.searchParams.get("id")||"",r=K.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const a=K.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:ue;try{me(t,se())}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>xt)return s(o,413,{error:{message:`text too long (max ${xt} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=Mr(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,w=u||(i?i.voice:t.tts?.voice||ue);if(i&&!jr(w))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:ce,contentType:J,redacted:je}=await Cr({dest:i,text:r,voice:w,speed:a,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await fe(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":J,"Content-Length":String(ce.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(je)}),o.end(ce)}if(!await P.ready({onLog:ce=>console.log(ce),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||_t(Ue()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:P.health().error||"tts model not ready",type:"tts_unavailable"}});const b=Rr({requested:u,configured:w,engine:P,voices:K,isPocketVoice:De,isKnownVoice:kt,isValidVoiceId:St,defaultVoice:ue,defaultPocketVoice:Be});if(!b.ok)return s(o,b.status,{error:{message:b.message,type:b.type}});const{voice:h,customId:O,speakerEmbedding:I}=b,M=await P.synth(r,{voice:h,speed:a,speakerEmbedding:I}),W=P.sampleRate(),he=y==="pcm"?Buffer.from(new Float32Array(M).buffer):P.toWav(M,W);return o.writeHead(200,{"Content-Type":y==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(he.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(W),...O||P.isPocket()||P.supportsVoices()?{"X-Tts-Voice":h}:{}}),o.end(he)}catch(k){return s(o,500,{error:{message:k.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=br(await T(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(h){return s(o,h.code===413?413:415,{error:{message:h.message,type:"bad_request"}})}const r=h=>e.find(O=>O.name===h&&!O.filename)?.data.toString("utf8").trim()||"",a=e.find(h=>h.name==="file"&&h.filename)||e.find(h=>h.filename);if(!a?.data?.length)return s(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let i;try{i=await vr(a.data)}catch(h){return s(o,h.code===415?415:500,{error:{message:h.message,type:"unsupported_media"}})}const u=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",w=yt(t,"stt");let y=null;if(w.kind==="remote"||w.kind==="container")try{y=ft(w,{fetchImpl:Ee})}catch(h){return s(o,500,{error:{message:`stt provider: ${h.message}`,type:"bad_provider"}})}!y&&!A.isReady()&&A.init({model:t.stt?.model||Ne,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,onLog:h=>console.log(h)});const k=r("diarize")==="true"&&t.stt?.diarize!==!1;k&&!j.isReady()&&j.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:h=>console.log(h)});const b=Date.now();try{const{id:h}=A.createSession({lang:r("language")||void 0,diarize:k,interims:!1,remote:y}),O=[];let I=null;A.subscribe(h,J=>{J.type==="final"&&J.text?O.push(J):J.type==="language"&&(I=J.lang)});const M=16e3*5;for(let J=0;J<i.pcm.length;J+=M)A.pushAudio(h,i.pcm.subarray(J,Math.min(i.pcm.length,J+M)));await A.endSession(h);let W=0;const he=O.map((J,je)=>{const Ut=W,Ft=(J.durationMs||0)/1e3;return W+=Ft,{id:je,start:Math.round(Ut*100)/100,end:Math.round(W*100)/100,text:J.text,...J.speaker?{speaker:J.speaker}:{}}}),ce=he.map(J=>J.text).join(" ").replace(/\s+/g," ").trim();return u==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(ce)):u==="verbose_json"?s(o,200,{task:"transcribe",language:I||r("language")||null,duration:Math.round(i.seconds*100)/100,text:ce,segments:he,provider:w.kind,took_ms:Date.now()-b}):s(o,200,{text:ce})}catch(h){return s(o,h.code==="too_many_sessions"?429:500,{error:{message:h.message,type:h.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=yt(t,"stt");let a=null;if(r.kind==="remote"||r.kind==="container")try{a=ft(r,{fetchImpl:Ee})}catch(u){return s(o,500,{error:{message:`stt provider: ${u.message}`,type:"bad_provider"}})}!a&&!A.isReady()&&A.init({model:t.stt?.model||Ne,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});const i=e?.diarize===!0&&t.stt?.diarize!==!1;i&&!j.isReady()&&j.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});try{const{id:u}=A.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:A.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 A.pushAudio(r,A.toFloat32(a)),s(o,200,{ok:!0,state:A.state()})}catch(a){return s(o,a.code==="no_session"?404:400,{error:{message:a.message,type:a.code||"stt_error"}})}if(e[2]==="/events"&&n.method==="GET"){const a=A.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=h=>o.write(`data: ${JSON.stringify(h)}
|
|
40
40
|
|
|
41
|
-
`),u=a.redact?await fe(t.pro?.entitlementToken):!0,w=async h=>{if(h.type!=="final"||!a.redact)return h;try{let O=h.text;return await $e([Re(()=>O,I=>{O=I})],t.redaction,{isPro:u}),{...h,text:O}}catch{return h}};i({type:"state",state:a.remote?"ready":A.state()});const y=setInterval(()=>{const h=a.remote?"ready":A.state();if(h==="downloading"||h==="loading"){i({type:"progress",state:h,...A.progress()||{}});return}if(h==="error"){i({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(y);return}if(a.diarize){const O=j.state();if(O==="downloading"||O==="loading"){i({type:"diarize-progress",state:O,...j.progress()||{}});return}}i({type:"state",state:h}),clearInterval(y)},500);y.unref?.();let k=Promise.resolve();const b=A.subscribe(r,h=>{k=k.then(async()=>{i(await w(h)),h.type==="end"&&(clearInterval(y),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(y),b?.()});return}if(!e[2]&&n.method==="DELETE")return await A.endSession(r),s(o,200,{ok:!0})}}if(l==="/logs"&&n.method==="GET")return s(o,200,{entries:[...L].reverse()});if(l==="/config"&&n.method==="GET"){const e=await fe(t.pro?.entitlementToken);return s(o,200,Ot(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{zr(t,e)}catch(y){if(y?.code==="SHAPE")return s(o,400,{error:y.message});throw y}at(t),JSON.stringify(t.sandbox||null)!==r&&Te?.restart("sandbox settings changed");try{me(t,se())}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=E.state();t.ner?.autostart&&i&&u!=="ready"&&u!=="loading"&&u!=="downloading"&&E.setModel(t.ner.model,{onLog:y=>console.log(y)}).then(y=>{y&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const w=await fe(t.pro?.entitlementToken);return s(o,200,Ot(t,{proUnlocked:w}))}if(n.method==="GET"&&l==="/skills"){const e=await ye(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=de(t.bridge?.token);try{const a=await fetch(`${e}/skills${Xe(p,t)}`,{headers:{Accept:"application/json",...r?{Authorization:`Bearer ${r}`}:{}},signal:AbortSignal.timeout(8e3)}),i=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(i?.skills)?i.skills:[]}):s(o,a.status,{error:{message:i?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(l)){const e=decodeURIComponent(l.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const r=await ye(t);if(!r)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=de(t.bridge?.token);try{const i=await fetch(`${r}/skills/${encodeURIComponent(e)}${Xe(p,t)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),u=await i.json().catch(()=>({}));return i.ok?s(o,200,{skill:u?.skill||null}):s(o,i.status,{error:{message:u?.error||`bridge ${i.status}`,type:"bridge_error"}})}catch(i){return s(o,502,{error:{message:`bridge unreachable: ${i.message}`,type:"bridge_unreachable"}})}}if(l==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(l)){if(!X(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 ye(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=de(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];if(!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a)))return s(o,400,{error:{message:"not a skill file",type:"invalid_request"}});const i=await ye(t);if(!i)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const u=de(t.bridge?.token);try{const w=await fetch(`${i}/skills/${encodeURIComponent(r)}/file/${a}${Xe(p,t)}`,{headers:{Accept:"application/json",...u?{Authorization:`Bearer ${u}`}:{}},signal:AbortSignal.timeout(8e3)}),y=await w.json().catch(()=>({}));return w.ok?s(o,200,y):s(o,w.status,{error:{message:y?.error||`bridge ${w.status}`,type:"bridge_error"}})}catch(w){return s(o,502,{error:{message:`bridge unreachable: ${w.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/\/models$/.test(l)){const e=await S(),r=e.sig!==void 0&&e.sig!==$;return $=e.sig,s(o,200,await Vr(t,{serviceHealth:async()=>e,fresh:r}))}if(fn.some(e=>l===e||l.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${ee}) has no ${l} — update it to use this feature`,type:"unknown_endpoint"}});const C=sn(l,n.headers,t);let Z;try{Z=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 q=null,v=null,le=Z,ve=0,V=0,ne=0,U=!1,Y=!0;const H=t.logRequests&&C.redactable&&n.method==="POST"?nn(ie):null;if(C.redactable&&n.method==="POST"&&Z.length){try{v=JSON.parse(Z.toString("utf8"))}catch{v=null}if(v&&an(v,C.kind))le=Z;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):Zr,h=e.narrowAll?null:I=>!Yr.test(Ct(I)),O=v.tools.length;v.tools=to(v.tools,qr(v,C.kind),{cap:b,keep:h,name:Ct,description:Xr}),ne=O-v.tools.length}Y=await fe(t.pro?.entitlementToken);const r=Ir(t,Y);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"}});U=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&X(n),U||await Ae(t);const a=U?[]:C.adapter.collectSegments(v,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const u=H?H.clock():0,{vault:w,count:y,sanitized:k}=U?{vault:null,count:0,sanitized:0}:await $e(a,t.redaction,{signal:i.signal,isPro:Y,onEgress:b=>Qe.push(Nt({ts:Date.now(),client:"redaction",tool:`detect:${b.backend}@${b.host||"local"}`,ok:b.ok,ms:b.ms,error:b.error}))});if(H&&H.lap("redact",u),q=w,ve=y,V=k||0,y>0&&o.setHeader("x-chatpanel-redacted",String(y)),!Y&&y>0){Lr(t,Y);try{me(t,se())}catch{}}if(!U&&Array.isArray(v.tools)&&v.tools.length&&typeof C.adapter.injectSystemNote=="function"){const b=At(v?.model,t,C.kind,{destination:String(n.headers["x-chatpanel-destination"]||v?.chatpanel?.destination||"").trim(),down:O=>!!O.service&&g.fn(O.id)==="down"}),h=!(b&&b.type==="api");C.adapter.injectSystemNote(v,ro({toolData:t.tools?.toolData,ownTools:h}))}else!U&&y>0&&typeof C.adapter.injectSystemNote=="function"&&C.adapter.injectSystemNote(v,no());le=Buffer.from(JSON.stringify(v),"utf8")}}const qe=oo({vault:q,toolData:t.tools?.toolData}),xe=v&&typeof v.chatpanel=="object"&&v.chatpanel||null;if(xe&&(delete v.chatpanel,le=Buffer.from(JSON.stringify(v),"utf8")),typeof v?.model=="string"&&v.model.startsWith("fusion:")){const e=Yo(v.model,t,await S());if(e?.error)return H?.commit(),s(o,400,{error:{message:e.error,type:"fusion"}});e&&(v.model=e.model,le=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"]||xe?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||xe?.reach||"").trim(),run:bn(n.headers["x-chatpanel-run"],xe?.run)},et=await S(),B=At(v?.model,t,C.kind,{destination:pe.destination,down:e=>!!e.service&&et(e.id)==="down"});if(B?.service&&et(B.id)==="down")return H?.commit(),s(o,503,{error:{message:`${B.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:B.service}});if(pe.destination&&(!B||B.id!==pe.destination))return H?.commit(),s(o,404,{error:{message:`no destination "${pe.destination}" is configured on this gateway`,type:"unknown_destination",known:Ur(t).map(e=>e.id)}});H&&(H.meta={t:Date.now(),model:v?.model||null,dest:B?B.id:null,type:B?B.type:null,redacted:ve,sanitized:V,narrowed:ne,detail:Jt(q,t.logDetail),redaction:U?"off":t.redaction.tier||"basic"});const _e=fo();if(_e&&B){const e=B.type==="api"?it(_e,{model:v?.model||"",endpoint:B.baseUrl||""}):wo(_e,B.agent||B.id)?it(_e,{model:v?.model||""}):{ok:!1,reason:`agent "${B.agent||B.id}" is not allowed by your organisation’s policy`};if(!e.ok)return H?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(B&&B.type==="api")return B.baseUrl?ln(B.baseUrl,t)?(H?.commit(),s(o,508,{error:{message:`destination "${B.id}" points back at the gateway (${B.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):gn(n,o,{...C,pathname:l,search:p.search,base:B.baseUrl,destKey:B.apiKey,destProtocol:B.protocol,harness:qe,trace:H},le,q):(H?.commit(),s(o,502,{error:`destination "${B.id}" has no baseUrl`}));const tt=Pe(n),ot=tt==="local"&&t.bridge?.openAgentLane?"token":tt;if(ot==="local")return H?.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 rt=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),Oe=ao({...pe.run||{},...pe.reach?{reach:pe.reach}:{},...rt?{askDepth:rt}:{}},ot);return Oe.reach&&o.setHeader("x-chatpanel-reach-used",Oe.reach),mn(n,o,{...C,pathname:l,agentOverride:B?.agent,harness:qe,trace:H,run:Object.keys(Oe).length?Oe:null},v,q,t,Y)});return re.on("close",()=>{m?.stop("closed"),lr()}),re}function bn(t,c){let d=c&&typeof c=="object"?c:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const m={};if(Array.isArray(d.grants)&&(m.grants=d.grants.map(f=>String(f).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const f=d.workspace;m.workspace={repo:String(f.repo).slice(0,400),projectId:String(f.projectId||"").slice(0,120),jobId:String(f.jobId||"").slice(0,120),...f.base?{base:String(f.base).slice(0,120)}:{}}}if(d.connectionId&&(m.connectionId=String(d.connectionId).slice(0,64)),typeof d.workingDir=="string"&&d.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(d.workingDir.trim())&&(m.workingDir=d.workingDir.trim().slice(0,1024)),Gr.includes(d.permissionMode)&&d.permissionMode!=="default"&&(m.permissionMode=d.permissionMode),d.sandbox&&typeof d.sandbox=="object"){const f=(Array.isArray(d.sandbox.hosts)?d.sandbox.hosts:String(d.sandbox.hosts||"").split(/[\s,;]+/)).map($=>String($).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),g=(Array.isArray(d.sandbox.write)?d.sandbox.write:[]).map($=>String($).slice(0,1024)).filter(Boolean).slice(0,32);(f.length||g.length)&&(m.sandbox={...f.length?{hosts:f}:{},...g.length?{write:g}:{}})}return Object.keys(m).length?m:null}let Te=null;async function Cs(t=nt()){Eo();let c=null;try{c=await yo()}catch(S){throw S instanceof go&&(console.error(`[chatpanel-gateway] org policy: ${S.message}`),process.exit(78)),S}const d=c?.policy||null;d&&(at(t,d),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`)),po(globalThis,{allow:d?.egress?(S,{local:x})=>bo(d,S,{local:x}):null}),Ie();const m=wn(t),f=Oo(t),g=Kt(t);m.on("error",S=>{S&&S.code==="EADDRINUSE"&&(console.error(`Port ${t.port} is already in use — another app (or a second gateway) has it.`),console.error(`Fix: free the port, or set a different one — edit "port" in ${se()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${S?.message||S}`),process.exit(1)}),m.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${ee} 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"),Jo(t,{childEnv:()=>Hr(t)}).then(S=>{Te=S}).catch(S=>console.log(` bridge : not supervised (${S?.message||S})`)),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…)":"")),It(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.`)}),mt()&&Ve(N,ze()).then(S=>{S?.ok&&(console.log(` warm : seeded ${S.ingested} records from ${S.file}`),S.whole&&Ce())}).catch(()=>{});const $=()=>{f?.stop(),g.stop(),Te?.stop(),Qr(m)};return process.on("SIGINT",$),process.on("SIGTERM",$),m}export{Is as VERSION,wn as createGateway,pn as joinUpstream,Ze as parseAgentModel,Cs as start};
|
|
41
|
+
`),u=a.redact?await fe(t.pro?.entitlementToken):!0,w=async h=>{if(h.type!=="final"||!a.redact)return h;try{let O=h.text;return await $e([Re(()=>O,I=>{O=I})],t.redaction,{isPro:u}),{...h,text:O}}catch{return h}};i({type:"state",state:a.remote?"ready":A.state()});const y=setInterval(()=>{const h=a.remote?"ready":A.state();if(h==="downloading"||h==="loading"){i({type:"progress",state:h,...A.progress()||{}});return}if(h==="error"){i({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(y);return}if(a.diarize){const O=j.state();if(O==="downloading"||O==="loading"){i({type:"diarize-progress",state:O,...j.progress()||{}});return}}i({type:"state",state:h}),clearInterval(y)},500);y.unref?.();let k=Promise.resolve();const b=A.subscribe(r,h=>{k=k.then(async()=>{i(await w(h)),h.type==="end"&&(clearInterval(y),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(y),b?.()});return}if(!e[2]&&n.method==="DELETE")return await A.endSession(r),s(o,200,{ok:!0})}}if(l==="/logs"&&n.method==="GET")return s(o,200,{entries:[...L].reverse()});if(l==="/config"&&n.method==="GET"){const e=await fe(t.pro?.entitlementToken);return s(o,200,Ot(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{zr(t,e)}catch(y){if(y?.code==="SHAPE")return s(o,400,{error:y.message});throw y}at(t),JSON.stringify(t.sandbox||null)!==r&&Te?.restart("sandbox settings changed");try{me(t,se())}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=E.state();t.ner?.autostart&&i&&u!=="ready"&&u!=="loading"&&u!=="downloading"&&E.setModel(t.ner.model,{onLog:y=>console.log(y)}).then(y=>{y&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const w=await fe(t.pro?.entitlementToken);return s(o,200,Ot(t,{proUnlocked:w}))}if(n.method==="GET"&&l==="/skills"){const e=await ye(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=de(t.bridge?.token);try{const a=await fetch(`${e}/skills${Xe(p,t)}`,{headers:{Accept:"application/json",...r?{Authorization:`Bearer ${r}`}:{}},signal:AbortSignal.timeout(8e3)}),i=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(i?.skills)?i.skills:[]}):s(o,a.status,{error:{message:i?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(l)){const e=decodeURIComponent(l.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const r=await ye(t);if(!r)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=de(t.bridge?.token);try{const i=await fetch(`${r}/skills/${encodeURIComponent(e)}${Xe(p,t)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),u=await i.json().catch(()=>({}));return i.ok?s(o,200,{skill:u?.skill||null}):s(o,i.status,{error:{message:u?.error||`bridge ${i.status}`,type:"bridge_error"}})}catch(i){return s(o,502,{error:{message:`bridge unreachable: ${i.message}`,type:"bridge_unreachable"}})}}if(l==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(l)){if(!X(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 ye(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=de(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];if(!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a)))return s(o,400,{error:{message:"not a skill file",type:"invalid_request"}});const i=await ye(t);if(!i)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const u=de(t.bridge?.token);try{const w=await fetch(`${i}/skills/${encodeURIComponent(r)}/file/${a}${Xe(p,t)}`,{headers:{Accept:"application/json",...u?{Authorization:`Bearer ${u}`}:{}},signal:AbortSignal.timeout(8e3)}),y=await w.json().catch(()=>({}));return w.ok?s(o,200,y):s(o,w.status,{error:{message:y?.error||`bridge ${w.status}`,type:"bridge_error"}})}catch(w){return s(o,502,{error:{message:`bridge unreachable: ${w.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/\/models$/.test(l)){const e=await S(),r=e.sig!==void 0&&e.sig!==$;return $=e.sig,s(o,200,await Ur(t,{serviceHealth:async()=>e,fresh:r}))}if(gn.some(e=>l===e||l.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${ee}) has no ${l} — update it to use this feature`,type:"unknown_endpoint"}});const C=an(l,n.headers,t);let Z;try{Z=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 q=null,v=null,le=Z,ve=0,V=0,ne=0,U=!1,Y=!0;const H=t.logRequests&&C.redactable&&n.method==="POST"?sn(ie):null;if(C.redactable&&n.method==="POST"&&Z.length){try{v=JSON.parse(Z.toString("utf8"))}catch{v=null}if(v&&ln(v,C.kind))le=Z;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):Yr,h=e.narrowAll?null:I=>!Xr.test(Ct(I)),O=v.tools.length;v.tools=to(v.tools,en(v,C.kind),{cap:b,keep:h,name:Ct,description:qr}),ne=O-v.tools.length}Y=await fe(t.pro?.entitlementToken);const r=Ir(t,Y);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"}});U=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&X(n),U||await Ae(t);const a=U?[]:C.adapter.collectSegments(v,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const u=H?H.clock():0,{vault:w,count:y,sanitized:k}=U?{vault:null,count:0,sanitized:0}:await $e(a,t.redaction,{signal:i.signal,isPro:Y,onEgress:b=>Qe.push(Nt({ts:Date.now(),client:"redaction",tool:`detect:${b.backend}@${b.host||"local"}`,ok:b.ok,ms:b.ms,error:b.error}))});if(H&&H.lap("redact",u),q=w,ve=y,V=k||0,y>0&&o.setHeader("x-chatpanel-redacted",String(y)),!Y&&y>0){Lr(t,Y);try{me(t,se())}catch{}}if(!U&&Array.isArray(v.tools)&&v.tools.length&&typeof C.adapter.injectSystemNote=="function"){const b=At(v?.model,t,C.kind,{destination:String(n.headers["x-chatpanel-destination"]||v?.chatpanel?.destination||"").trim(),down:O=>!!O.service&&g.fn(O.id)==="down"}),h=!(b&&b.type==="api");C.adapter.injectSystemNote(v,ro({toolData:t.tools?.toolData,ownTools:h}))}else!U&&y>0&&typeof C.adapter.injectSystemNote=="function"&&C.adapter.injectSystemNote(v,no());le=Buffer.from(JSON.stringify(v),"utf8")}}const qe=oo({vault:q,toolData:t.tools?.toolData}),xe=v&&typeof v.chatpanel=="object"&&v.chatpanel||null;if(xe&&(delete v.chatpanel,le=Buffer.from(JSON.stringify(v),"utf8")),typeof v?.model=="string"&&v.model.startsWith("fusion:")){const e=Yo(v.model,t,await S());if(e?.error)return H?.commit(),s(o,400,{error:{message:e.error,type:"fusion"}});e&&(v.model=e.model,le=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"]||xe?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||xe?.reach||"").trim(),run:vn(n.headers["x-chatpanel-run"],xe?.run)},et=await S(),B=At(v?.model,t,C.kind,{destination:pe.destination,down:e=>!!e.service&&et(e.id)==="down"});if(B?.service&&et(B.id)==="down")return H?.commit(),s(o,503,{error:{message:`${B.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:B.service}});if(pe.destination&&(!B||B.id!==pe.destination))return H?.commit(),s(o,404,{error:{message:`no destination "${pe.destination}" is configured on this gateway`,type:"unknown_destination",known:Fr(t).map(e=>e.id)}});H&&(H.meta={t:Date.now(),model:v?.model||null,dest:B?B.id:null,type:B?B.type:null,redacted:ve,sanitized:V,narrowed:ne,detail:Jt(q,t.logDetail),redaction:U?"off":t.redaction.tier||"basic"});const _e=fo();if(_e&&B){const e=B.type==="api"?it(_e,{model:v?.model||"",endpoint:B.baseUrl||""}):wo(_e,B.agent||B.id)?it(_e,{model:v?.model||""}):{ok:!1,reason:`agent "${B.agent||B.id}" is not allowed by your organisation’s policy`};if(!e.ok)return H?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(B&&B.type==="api")return B.baseUrl?cn(B.baseUrl,t)?(H?.commit(),s(o,508,{error:{message:`destination "${B.id}" points back at the gateway (${B.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):wn(n,o,{...C,pathname:l,search:p.search,base:B.baseUrl,destKey:B.apiKey,destProtocol:B.protocol,harness:qe,trace:H},le,q):(H?.commit(),s(o,502,{error:`destination "${B.id}" has no baseUrl`}));const tt=Pe(n),ot=tt==="local"&&t.bridge?.openAgentLane?"token":tt;if(ot==="local")return H?.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 rt=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),Oe=ao({...pe.run||{},...pe.reach?{reach:pe.reach}:{},...rt?{askDepth:rt}:{}},ot);return Oe.reach&&o.setHeader("x-chatpanel-reach-used",Oe.reach),pn(n,o,{...C,pathname:l,agentOverride:B?.agent,harness:qe,trace:H,run:Object.keys(Oe).length?Oe:null},v,q,t,Y)});return re.on("close",()=>{m?.stop("closed"),lr()}),re}function vn(t,c){let d=c&&typeof c=="object"?c:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const m={};if(Array.isArray(d.grants)&&(m.grants=d.grants.map(f=>String(f).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const f=d.workspace;m.workspace={repo:String(f.repo).slice(0,400),projectId:String(f.projectId||"").slice(0,120),jobId:String(f.jobId||"").slice(0,120),...f.base?{base:String(f.base).slice(0,120)}:{}}}if(d.connectionId&&(m.connectionId=String(d.connectionId).slice(0,64)),typeof d.workingDir=="string"&&d.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(d.workingDir.trim())&&(m.workingDir=d.workingDir.trim().slice(0,1024)),Hr.includes(d.permissionMode)&&d.permissionMode!=="default"&&(m.permissionMode=d.permissionMode),d.sandbox&&typeof d.sandbox=="object"){const f=(Array.isArray(d.sandbox.hosts)?d.sandbox.hosts:String(d.sandbox.hosts||"").split(/[\s,;]+/)).map($=>String($).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),g=(Array.isArray(d.sandbox.write)?d.sandbox.write:[]).map($=>String($).slice(0,1024)).filter(Boolean).slice(0,32);(f.length||g.length)&&(m.sandbox={...f.length?{hosts:f}:{},...g.length?{write:g}:{}})}return Object.keys(m).length?m:null}let Te=null;async function js(t=nt()){Eo();let c=null;try{c=await yo()}catch(S){throw S instanceof go&&(console.error(`[chatpanel-gateway] org policy: ${S.message}`),process.exit(78)),S}const d=c?.policy||null;d&&(at(t,d),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`)),po(globalThis,{allow:d?.egress?(S,{local:x})=>bo(d,S,{local:x}):null}),Ie();const m=bn(t),f=Oo(t),g=Kt(t);m.on("error",S=>{S&&S.code==="EADDRINUSE"&&(console.error(`Port ${t.port} is already in use — another app (or a second gateway) has it.`),console.error(`Fix: free the port, or set a different one — edit "port" in ${se()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${S?.message||S}`),process.exit(1)}),m.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${ee} 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"),Jo(t,{childEnv:()=>({...Vr(t),...Gr(t)})}).then(S=>{Te=S}).catch(S=>console.log(` bridge : not supervised (${S?.message||S})`)),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…)":"")),It(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.`)}),mt()&&Ve(N,ze()).then(S=>{S?.ok&&(console.log(` warm : seeded ${S.ingested} records from ${S.file}`),S.whole&&Ce())}).catch(()=>{});const $=()=>{f?.stop(),g.stop(),Te?.stop(),Zr(m)};return process.on("SIGINT",$),process.on("SIGTERM",$),m}export{Ls as VERSION,bn as createGateway,hn as joinUpstream,Ze as parseAgentModel,js as start};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.46.4";export{o as VERSION};
|