@chatpanel/gateway 0.44.3 → 0.52.3
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/README.md +1 -1
- package/bin/chatpanel-gateway-bin.mjs +2 -1
- package/bin/chatpanel-gateway.js +4 -4
- package/package.json +4 -4
- package/src/bridge.js +4 -4
- package/src/config.js +1 -1
- package/src/configstore.js +1 -1
- package/src/diarize-engine.js +1 -1
- package/src/diarize-models.js +1 -0
- package/src/egress.js +2 -2
- package/src/ner-engine.js +1 -1
- package/src/ort-native.js +1 -0
- package/src/server.js +23 -23
- package/src/service.js +18 -17
- package/src/shape.js +5 -5
- package/src/stt-engine.js +1 -1
- package/src/toolrelay.js +2 -2
- package/src/version.js +1 -1
package/README.md
CHANGED
|
@@ -256,7 +256,7 @@ behaviour for a trusted machine — the startup log calls it out.
|
|
|
256
256
|
|
|
257
257
|
**Pairing** a browser the gateway does not recognise (ChatPanel's Firefox build, whose
|
|
258
258
|
origin is a per-profile UUID; a dev build): `chatpanel-gateway pair` prints a one-time
|
|
259
|
-
code (5 minutes, 5 attempts); enter it in ChatPanel → Settings →
|
|
259
|
+
code (5 minutes, 5 attempts); enter it in ChatPanel → Settings → Coding Agents. The exchange
|
|
260
260
|
(`POST /pair`) hands over the gateway token and, when this machine has one, the bridge
|
|
261
261
|
token — one code covers both. `POST /whoami` → `{ trust, paired }` tells a client where
|
|
262
262
|
it stands.
|
|
@@ -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/bin/chatpanel-gateway.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const
|
|
3
|
-
`)}process.argv.includes("--json")?console.log(JSON.stringify(
|
|
2
|
+
const s=process.argv[2],u={"--bridge":"chatpanel-bridge","--mcp-stdio":"chatpanel-bridge-mcp",mcp:"chatpanel-history-mcp","--extract-worker":"chatpanel-extract"};try{process.title=u[s]||"chatpanel-gateway"}catch{}try{if(s==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:e}=await import("../src/extract/worker.js");e()}else if(s==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(s==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(s==="mcp"){const{runMcpServer:e}=await import("../src/mcp.js");await e()}else if(s==="tools"||s==="call"){const{runMcpCli:e}=await import("../src/mcp-cli.js");process.exit(await e(process.argv.slice(2)))}else if(s==="policy"){const{loadPolicy:e,formatPolicy:a,PolicyLoadError:n}=await import("../src/policy.js");try{const r=await e();process.argv.includes("--json")?console.log(JSON.stringify(r?{...r,label:void 0}:null,null,2)):console.log(a(r))}catch(r){throw r instanceof n&&(console.error(`org policy: ${r.message}`),process.exit(78)),r}}else if(s==="--audit"){const{egressAudit:e,formatAudit:a}=await import("../src/egress.js"),{loadConfig:n}=await import("../src/config.js"),{readFileSync:r}=await import("node:fs"),{join:h}=await import("node:path"),l=await import("node:os"),c=n(),t=`http://127.0.0.1:${c.port||4320}`;let o=null,i=`no gateway running at ${t}`;try{const p=r(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||h(l.homedir(),".chatpanel","gateway-token"),"utf8").trim(),g=await fetch(`${t}/audit`,{headers:{authorization:`Bearer ${p}`},signal:AbortSignal.timeout(2500)});if(g.ok)o=await g.json();else if(g.status===404){const d=await fetch(`${t}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);i=`the gateway running at ${t}${d?.version?` (${d.version})`:""} predates --audit (0.7.0) — restart it after updating`}else i=`the gateway at ${t} refused the audit (HTTP ${g.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!o){const{VERSION:p}=await import("../src/server.js");o={...e(c,{ledger:null,version:p}),observed:[]},console.log(`(${i}; showing what the current config allows)
|
|
3
|
+
`)}process.argv.includes("--json")?console.log(JSON.stringify(o,null,2)):console.log(a(o))}else if(s==="sandbox"){const{srtModuleUrl:e}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&e()&&(process.env.CHATPANEL_SRT_MODULE=e());const{runSandboxCli:a}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await a(process.argv.slice(3)))}else if(s==="pair"){const{loadConfig:e}=await import("../src/config.js"),{readFileSync:a}=await import("node:fs"),{join:n}=await import("node:path"),r=await import("node:os"),l=`http://127.0.0.1:${e().port||4320}`,c=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||n(r.homedir(),".chatpanel","gateway-token");try{const t=a(c,"utf8").trim(),o=await fetch(`${l}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),i=await o.json().catch(()=>({}));if(o.status===404)throw new Error(`the gateway at ${l} predates pairing (0.9.0) — update and restart it`);if(!o.ok)throw new Error(i.error||`HTTP ${o.status}`);console.log(`Pairing code: ${i.display||i.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(t){console.error(`could not get a pairing code from the gateway at ${l}: ${t?.message||t}${/ENOENT/.test(String(t?.message))?` (no token at ${c} — has the gateway started once?)`:""}`),process.exit(1)}}else if(s==="local"){const{localStatus:e,formatLocalStatus:a}=await import("../src/local-status.js");process.stdout.write(a(await e()))}else if(s==="connect"){const{connectAgents:e,formatConnect:a}=await import("../src/connect-agents.js"),n=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(a(e({dryRun:n}),{dryRun:n}))}else{const{start:e,VERSION:a}=await import("../src/server.js"),{installService:n,uninstallService:r,serviceReport:h,stopService:l,pathWithDir:c}=await import("../src/service.js");switch(s){case"--stop":l(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(a);break;case"--install":{const t=await n({version:a}),o=t.health;if(t.ok){const i=t.deferredTo?` — the ${t.deferredTo} app's gateway (v${o.version}) is the one answering right now; this install takes over at the next login`:"",p=t.replaced?`, replacing v${t.replaced}`:"";console.log(`ChatPanel Privacy Gateway v${o.version}: running at ${o.url}${p}, starts at login${t.wsl?" (Windows login, through wsl.exe)":""}${i}.`)}else o.ok?(console.error(`ChatPanel Privacy Gateway: v${a} is registered to start at login, but v${o.version} still answers at ${o.url} 40 s later.`),console.error(" Something starts it back faster than it can be replaced — `chatpanel-gateway --status` says what holds the port; `--stop`, then `--install`, separates the two steps.")):(console.error(`ChatPanel Privacy Gateway: login auto-start is registered, but nothing answered at ${o.url} after 40 s.`),t.errLog&&console.error(` last of the error log:
|
|
4
4
|
${t.errLog.split(`
|
|
5
|
-
`).map(
|
|
6
|
-
`)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself.");try{const{pruneForeignPrebuilds:
|
|
5
|
+
`).map(i=>` ${i}`).join(`
|
|
6
|
+
`)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself."));t.shadow&&(console.log(` ⚠ ${t.shadow}/chatpanel-gateway comes first on your PATH, so typing \`chatpanel-gateway\` still runs THAT copy, not this v${a}.`),console.log(` Remove it, or run this one by its full path. (The service just registered is this v${a} either way.)`));try{const{pruneForeignPrebuilds:i,pruneLine:p}=await import("../src/prune-install.js"),g=p(i({log:d=>console.error(d)}));g&&console.log(g)}catch{}t.launcher==="powershell"&&console.log(" (VBScript is not installed here, so the login launcher is PowerShell — a console flashes for an instant at login.)"),t.path?.added?console.log(` Added ${t.path.dir} to your PATH — \`chatpanel-gateway\` works in a NEW terminal.`):t.path?.error?console.log(` Could not add ${t.path.dir} to your PATH (${t.path.error}) — add it yourself to run \`chatpanel-gateway\` by name.`):t.path?.dir&&t.wsl&&c(process.env.PATH||"",t.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${t.path.dir}:$PATH"`),o.ok||process.exit(1);break}case"--uninstall":r(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(await h());break;case void 0:await e();break;default:console.error(`unknown option: ${s}
|
|
7
7
|
Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|pair|policy|--audit|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(e){console.error(`error: ${e.message}`),process.exit(1)}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.52.3",
|
|
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,9 +22,9 @@
|
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
25
|
-
"@chatpanel/bridge": "^0.
|
|
26
|
-
"@chatpanel/events": "^0.
|
|
27
|
-
"@chatpanel/pii": "^0.11.
|
|
25
|
+
"@chatpanel/bridge": "^0.27.2",
|
|
26
|
+
"@chatpanel/events": "^0.200.1",
|
|
27
|
+
"@chatpanel/pii": "^0.11.1",
|
|
28
28
|
"@huggingface/transformers": "^4.2.0",
|
|
29
29
|
"defuddle": "^0.19.4",
|
|
30
30
|
"fflate": "^0.8.3",
|
package/src/bridge.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{readFileSync as
|
|
2
|
-
`):""}function
|
|
3
|
-
`)){const
|
|
1
|
+
import{readFileSync as j,existsSync as C}from"node:fs";import{join as L}from"node:path";import N from"node:os";const S=L(N.homedir(),".chatpanel","bridge-token"),F="http://127.0.0.1:4319",v=1e4;let c={at:0,cfgUrl:"",url:"",fell:!1};async function A(t,e){try{return(await fetch(`${t}/health`,{signal:AbortSignal.timeout(e)})).ok}catch{return!1}}async function z(t,{fallback:e,timeoutMs:r=1500,now:o=Date.now()}={}){e===void 0&&(e=process.env.CHATPANEL_BRIDGE_FALLBACK==="off"?"":F);const s=String(t?.bridge?.url||"").replace(/\/$/,"");if(c.url&&c.cfgUrl===s&&o-c.at<v)return c.url;let i=s||e,l=!1;return e&&i!==e&&!await A(i,r)&&await A(e,r)&&(i=e,l=!0,(!c.fell||c.cfgUrl!==s)&&console.log(`[gateway] bridge.url ${s} is not answering; the bridge on ${e} is — using it (fix the address in Settings to silence this)`)),c={at:o,cfgUrl:s,url:i,fell:l},i}function M(){c={at:0,cfgUrl:"",url:"",fell:!1}}let y=!1;function R(t){try{if(C(t))return j(t,"utf8").trim()}catch{}return""}function J(t,e=S){const r=R(e);return!t||y&&r&&r!==t?r:t}function P(t,e=S){const r=R(e);return!r||r===t?"":(y||(y=!0,console.warn("[gateway] the bridge rejected bridge.token from gateway.config.json; using ~/.chatpanel/bridge-token (the bridge wrote it). Clear the config value to silence this.")),r)}function W(){y=!1}const G=t=>t===401||t===403;async function _(t,e,r,o,s){const i=a=>fetch(`${t.replace(/\/$/,"")}/chat`,{method:"POST",headers:{"content-type":"application/json",...a?{authorization:`Bearer ${a}`}:{}},body:r,signal:o}),l=J(e,s);let f=await i(l);if(G(f.status)){const a=P(l,s);a&&(await f.text().catch(()=>{}),f=await i(a))}return f}function H(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:typeof e?.text=="string"?e.text:"").filter(Boolean).join(`
|
|
2
|
+
`):""}function $(t){return(t||[]).filter(e=>e&&(e.role==="user"||e.role==="assistant"||e.role==="system")).map(e=>({role:e.role,content:H(e.content)}))}async function q({bridgeUrl:t,agent:e,token:r,messages:o,system:s,specs:i,options:l,signal:f,tokenPath:a,approvals:g=!1}){const u=await _(t,r,JSON.stringify({agent:e,messages:$(o),system:s||"",options:l||{},...Array.isArray(i)&&i.length?{pageTools:{specs:i}}:{},...g?{approvals:!0}:{}}),f,a);if(!u.ok||!u.body)throw new Error(await O(u));return u}async function O(t){const e=await t.text().catch(()=>"");let r="";try{const o=JSON.parse(e);r=String(o?.error?.message||o?.error||o?.message||"").trim()}catch{}return r?r.slice(0,600):`bridge /chat HTTP ${t.status}${e?`: ${e.slice(0,200)}`:""}`}async function Q({bridgeUrl:t,agent:e,token:r,messages:o,system:s,options:i,signal:l,tokenPath:f},a,g=null,u=null){const h=await _(t,r,JSON.stringify({agent:e,messages:$(o),system:s||"",options:i||{}}),l,f);if(!h.ok||!h.body)throw new Error(await O(h));const D=h.body.getReader(),U=new TextDecoder;let d="",w="",b=!1,x=null;const E=m=>{for(const B of m.split(`
|
|
3
|
+
`)){const p=B.trim();if(!p.startsWith("data:"))continue;const T=p.slice(5).trim();if(!T||T==="[DONE]")continue;let n;try{n=JSON.parse(T)}catch{continue}n.type==="delta"&&typeof n.text=="string"?(b=!0,w+=n.text,a(n.text)):n.type==="done"?!b&&typeof n.text=="string"&&n.text&&(w+=n.text,a(n.text)):n.type==="error"?x=new Error(n.error||"bridge error"):(n.type==="usage"&&u&&u(n),g&&g(n))}};for(;;){const{done:m,value:B}=await D.read();if(m)break;d+=U.decode(B,{stream:!0});let p;for(;(p=d.indexOf(`
|
|
4
4
|
|
|
5
|
-
`))!==-1;)
|
|
5
|
+
`))!==-1;)E(d.slice(0,p)),d=d.slice(p+2)}if(d.trim()&&E(d),x)throw x;return w}export{F as DEFAULT_BRIDGE_URL,O as bridgeRefusal,P as bridgeTokenRejected,q as openBridgeChat,J as readBridgeToken,M as resetBridgeResolution,W as resetBridgeTokenPreference,z as resolveBridgeUrl,Q as streamBridgeChat,$ as toBridgeMessages};
|
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 A}from"node:path";import l from"node:os";import{DEFAULT_MODEL as c}from"./models.js";import{DEFAULT_STT_MODEL as E}from"./stt-models.js";import{DEFAULT_DIARIZE_MODEL as f}from"./diarize-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:c,union:[],warmMs:15*6e4,caseRecovery:!0,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:E,allowDownload:!0,diarize:!0,diarizeModel:f,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 t(r,e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&r&&typeof r=="object"){const i={...r};for(const o of Object.keys(e))i[o]=t(r[o],e[o]);return i}return e===void 0?r:e}function g(r=process.env){let e=s;const i=r.CHATPANEL_GATEWAY_CONFIG||A(l.homedir(),".chatpanel","gateway.config.json");if(p(i))try{e=t(e,JSON.parse(d(i,"utf8")))}catch(a){throw new Error(`bad config file ${i}: ${a.message}`)}r.CHATPANEL_GATEWAY_HOST&&(e=t(e,{host:r.CHATPANEL_GATEWAY_HOST})),r.CHATPANEL_GATEWAY_PORT&&(e=t(e,{port:Number(r.CHATPANEL_GATEWAY_PORT)})),r.OPENAI_BASE_URL&&(e=t(e,{upstreams:{openai:{baseUrl:r.OPENAI_BASE_URL}}})),r.ANTHROPIC_BASE_URL&&(e=t(e,{upstreams:{anthropic:{baseUrl:r.ANTHROPIC_BASE_URL}}})),r.CHATPANEL_REDACTION_TIER&&(e=t(e,{redaction:{tier:r.CHATPANEL_REDACTION_TIER}}));for(const[a,n]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[n]&&(e=t(e,{registries:{[a]:r[n]}}));if(e.registries?.models&&!r.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=t(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/diarize-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ensureLib as
|
|
1
|
+
import{ensureLib as R,modelRoot as P}from"./ner-engine.js";import{join as L}from"node:path";import{existsSync as O,readdirSync as I}from"node:fs";import{makeWarmTimer as z}from"./warm-timer.js";import{DEFAULT_DIARIZE_MODEL as k,diarizeThreshold as W,isKnownDiarizeModel as Z}from"./diarize-models.js";const Q=k;let s="off",c=k,h=null,w=null,g=null,u=null,f=null,a=null,y=0,M=0;function V(){return c}function v(){return W(c)}function D(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function X(){return s}function $(){return s==="ready"&&!!h&&!!w}function Y(){return f}function tt(){return{configured:s!=="off",ok:$(),state:s,model:c,loaded:!!h,threshold:v(),error:g,warmMs:a?.warmMs??null}}function et(){return!!a?.pending()}function rt(){y++,a?.disarm()}function nt(){y=Math.max(0,y-1),y===0&&M===0&&$()&&a?.arm()}function p(){return y>0||M>0||s==="loading"||s==="downloading"}async function b({log:e=()=>{}}={}){if(p())return!1;a?.disarm();const t=h;if(h=null,w=null,u=null,f=null,g=null,s="off",t){try{await t.dispose?.()}catch{}e("[diarize] idle — speaker model unloaded (reloads on the next diarizing session)")}return!0}function j(e=c,t=D()){const r=L(P(),...e.split("/"),"onnx");if(!O(r))return!1;const n=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return I(r).some(i=>i===`model${n}.onnx`)}catch{return!1}}async function T({log:e=()=>{},allowDownload:t=!0}={}){let r;try{r=await R()}catch(o){return s="error",g=o.message,e(`[diarize] engine unavailable (${o.message})`),!1}const n=c,i=j(n);if(r.env.allowRemoteModels=i?!1:!!t,!i&&!t)return s="error",g="model not on disk and downloads disabled",!1;const l=r.env.remoteHost;if(!i)try{r.env.remoteHost="https://huggingface.co/"}catch{}s=i?"loading":"downloading",i||(f={model:n,file:null,pct:0},e(`[diarize] downloading ${n} (one-time)…`));try{const{AutoModel:o,AutoProcessor:d}=r,_=m=>{if(!m)return;const H=typeof m.progress=="number"?Math.round(m.progress):f?.pct??0;(m.status==="progress"||m.status==="download"||m.status==="initiate")&&(f={model:n,file:m.file||f?.file||null,pct:H})},x=await d.from_pretrained(n,{progress_callback:_}),E=await o.from_pretrained(n,{dtype:D(),progress_callback:_});return w=x,h=E,s="ready",g=null,f=null,e(`[diarize] ready — ${n} @ ${D()} (speakers split at cosine ${v()})`),!0}catch(o){return g=o.message,f=null,s="error",e(`[diarize] load failed (${o.message}) — diarization off`),!1}finally{try{r.env.remoteHost=l}catch{}}}function ot(e={}){if(u&&s!=="error")return u;s="loading";const t=typeof e.onLog=="function"?e.onLog:()=>{};return a=z({warmMs:e.warmMs,busy:p,log:t,unload:()=>b({log:t})}),u=F(T({log:t,allowDownload:e.allowDownload!==!1})),u}function F(e){return e.then(t=>(t&&!p()&&a?.arm(),t))}async function lt(e,{log:t=()=>{}}={}){return Z(e)?e===c?!0:p()?!1:(await b({log:()=>{}}),c=e,t(`[diarize] speaker model set to ${e} (loads on the next diarizing session)`),!0):!1}function it({onLog:e}={}){return u=null,s="loading",a??=z({warmMs:void 0,busy:p,log:e||(()=>{}),unload:()=>b({log:e||(()=>{})})}),u=F(T({log:e,allowDownload:!0})),u}const q=16e3;function A(e){let t=0;for(const n of e)t+=n*n;t=Math.sqrt(t)||1;const r=new Float32Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]/t;return r}async function S(e){try{const t=await w(e),r=await h(t),n=r.embeddings??r.logits??r.last_hidden_state;return n?.data?Float32Array.from(n.data):null}catch{return null}}async function st(e){if(!$()||!(e instanceof Float32Array)||!e.length)return null;M++;try{return await C(e)}finally{M--,p()||a?.arm()}}async function C(e){const t=2*q,r=Math.round(1.3*q);if(e.length<=Math.round(t*1.4)){const l=await S(e);return l?A(l):null}const n=[];for(let l=0;l+t<=e.length;l+=r){const o=await S(e.subarray(l,l+t));o&&n.push(A(o))}if(!n.length){const l=await S(e);return l?A(l):null}const i=new Float32Array(n[0].length);for(const l of n)for(let o=0;o<i.length;o++)i[o]+=l[o];return A(i)}function at(){a?.disarm(),a=null,y=0,M=0,s="off",c=k,h=null,w=null,g=null,u=null,f=null}function ut(e,t,{warmMs:r=null}={}){h=e,w=t,s=e?"ready":"off",r!==null&&(a=z({warmMs:r,busy:p,unload:()=>b()}),e&&a.arm())}function K(e,t){let r=0,n=0,i=0;for(let o=0;o<e.length;o++)r+=e[o]*t[o],n+=e[o]*e[o],i+=t[o]*t[o];const l=Math.sqrt(n)*Math.sqrt(i);return l?r/l:0}class ft{constructor({threshold:t=v(),maxSpeakers:r=12}={}){this.threshold=t,this.maxSpeakers=r,this.centroids=[]}assign(t,{pinnedLabel:r=null,weak:n=!1,thin:i=!1}={}){if(!t)return null;if(r)return this._merge(this._find(r)||this._create(r),t);let l=null,o=-1;const d={};for(const _ of this.centroids){const x=K(t,_.vec);d[_.label]=Math.round(x*1e3)/1e3,x>o&&(o=x,l=_)}return n&&l?{...this._merge(l,t,{update:!1}),scores:d,weak:!0}:l&&o>=this.threshold?{...this._merge(l,t),scores:d}:this.centroids.length>=this.maxSpeakers&&l?{...this._merge(l,t),scores:d}:i&&l?{...this._merge(l,t,{update:!1}),scores:d,thin:!0}:{...this._merge(this._create(`Speaker ${this.centroids.length+1}`),t),scores:d,...n?{weak:!0}:{}}}_find(t){return this.centroids.find(r=>r.label===t)||null}_create(t){const r={id:this.centroids.length+1,label:t,vec:null,n:0};return this.centroids.push(r),r}_merge(t,r,{update:n=!0}={}){if(!t.vec)t.vec=Float32Array.from(r),t.n=1;else if(n){for(let i=0;i<t.vec.length;i++)t.vec[i]=(t.vec[i]*t.n+r[i])/(t.n+1);t.n+=1}return{id:t.id,label:t.label}}}export{Q as DIARIZE_MODEL,ft as Diarizer,at as _reset,ut as _setForTest,V as activeModel,v as activeThreshold,it as download,st as embed,tt as health,ot as init,$ as isReady,j as modelOnDisk,Y as progress,nt as release,rt as retain,lt as setModel,X as state,b as unload,et as warmPending};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o="onnx-community/wespeaker-voxceleb-resnet34-LM",t=[{id:"onnx-community/wespeaker-voxceleb-resnet34-LM",label:"WeSpeaker ResNet34 (recommended)",lang:"any",recommended:!0,approxMB:7,dim:256,threshold:.6,note:"Tells voices apart for meeting transcription (who said what). Small, fast, and the most accurate of the two."},{id:"Xenova/wavlm-base-plus-sv",label:"WavLM Base+ SV (previous default)",lang:"any",approxMB:102,dim:512,threshold:.75,note:"The earlier speaker model. Larger and slower, and it merges similar voices far more often — kept so an existing install can switch back."}];function r(e){return t.find(n=>n.id===e)||null}function a(e){return!!r(e)}function i(e){return(r(e)||r(o)).threshold}function s(e){return r(e)?.approxMB??null}export{o as DEFAULT_DIARIZE_MODEL,t as DIARIZE_MODEL_CATALOG,s as diarizeApproxMB,r as diarizeModelEntry,i as diarizeThreshold,a as isKnownDiarizeModel};
|
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};
|