@chatpanel/gateway 0.98.3 → 0.100.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -65,9 +65,13 @@ running process), and waits until the new version — and its bridge — answer.
65
65
  `chatpanel-gateway` runs it in the foreground instead, for a terminal; if another gateway already
66
66
  holds 4320 it says which one and exits.
67
67
 
68
- **Upgrading from the standalone binary to npm:** `install.sh` put `~/.local/bin` first on your
69
- PATH, so `chatpanel-gateway` still means the old binary there. Run the npm copy by path once —
70
- `"$(npm prefix -g)/bin/chatpanel-gateway" --install` — and it takes over the login service.
68
+ **Two copies on one machine (the standalone binary and npm): the newest wins.** `install.sh` put
69
+ `~/.local/bin` first on your PATH, so `chatpanel-gateway` may still mean the old binary there — but
70
+ `chatpanel-gateway --install` from any copy hands off to the newest one on PATH, which takes over
71
+ the login service, turns `~/.local/bin/chatpanel-gateway` into a link to itself (so the name means
72
+ the active install from every PATH entry) and names any other older copy with the command that
73
+ removes it. `chatpanel-gateway --status` lists every copy, its version, which one PATH runs and
74
+ which one answers the port. `--install --force` keeps an older copy on purpose.
71
75
 
72
76
  On Windows, if `chatpanel-gateway` is "not recognized" right after `npm i -g`, npm's global bin
73
77
  folder is not on that shell's PATH yet: open a new PowerShell, or run it by path —
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- const i=process.argv[2],m={"--bridge":"chatpanel-bridge","--mcp-stdio":"chatpanel-bridge-mcp",mcp:"chatpanel-history-mcp","--extract-worker":"chatpanel-extract"},y=(a=process.argv)=>a.includes("--mcp-stdio")?m["--mcp-stdio"]:m[a[2]]||"chatpanel-gateway";try{process.title=y()}catch{}if(!process.versions.bun&&i!=="--version"&&i!=="-v"){const[a,s]=String(process.versions.node||"0.0").split(".").map(Number);(a<22||a===22&&s<13)&&(console.error(`ChatPanel Gateway needs Node.js 22.13 or newer — this is ${process.version}.`),console.error("Update Node (https://nodejs.org, or `nvm install 22`), then run this again — or use the standalone binary, which carries its own runtime:"),console.error(" curl -fsSL https://dl.chatpanel.net/install.sh | bash"),process.exit(1))}try{if(i==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:a}=await import("../src/extract/worker.js");a()}else if(i==="--bridge"){if(process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),!process.argv.includes("--mcp-stdio")&&!process.argv.includes("--version")){const{trustSystemCertificates:a,systemCaWantedOnDisk:s}=await import("../src/system-ca.js");a({enabled:s()})}await import("@chatpanel/bridge/src/server.js")}else if(i==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(i==="mcp"){const{runMcpServer:a}=await import("../src/mcp.js");await a()}else if(i==="tools"||i==="call"){const{runMcpCli:a}=await import("../src/mcp-cli.js");process.exit(await a(process.argv.slice(2)))}else if(i==="policy"){const{loadPolicy:a,formatPolicy:s,PolicyLoadError:h}=await import("../src/policy.js");try{const l=await a();process.argv.includes("--json")?console.log(JSON.stringify(l?{...l,label:void 0}:null,null,2)):console.log(s(l))}catch(l){throw l instanceof h&&(console.error(`org policy: ${l.message}`),process.exit(78)),l}}else if(i==="--audit"){const{egressAudit:a,formatAudit:s}=await import("../src/egress.js"),{loadConfig:h}=await import("../src/config.js"),{readFileSync:l}=await import("node:fs"),{join:u}=await import("node:path"),g=await import("node:os"),c=h(),e=`http://127.0.0.1:${c.port||4320}`;let t=null,n=`no gateway running at ${e}`;try{const p=l(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||u(g.homedir(),".chatpanel","gateway-token"),"utf8").trim(),o=await fetch(`${e}/audit`,{headers:{authorization:`Bearer ${p}`},signal:AbortSignal.timeout(2500)});if(o.ok)t=await o.json();else if(o.status===404){const r=await fetch(`${e}/health`,{signal:AbortSignal.timeout(2500)}).then(d=>d.json()).catch(()=>null);n=`the gateway running at ${e}${r?.version?` (${r.version})`:""} predates --audit (0.7.0) — restart it after updating`}else n=`the gateway at ${e} refused the audit (HTTP ${o.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!t){const{VERSION:p}=await import("../src/server.js"),{systemCaWanted:o}=await import("../src/system-ca.js"),r=o(c),{partnerDevicesOnDisk:d}=await import("../src/link-host.js"),w=c.link?.enabled===!1?[]:d(...c.link?.path?[c.link.path]:[]);t={...a(c,{ledger:null,version:p,linkPartners:w,certificates:{on:!1,added:0,wanted:r,why:r?"no gateway is running; when one starts it adds this computer's list":"switched off (tls.systemCa: false, or CHATPANEL_SYSTEM_CA=off)"}}),observed:[]},console.log(`(${n}; showing what the current config allows)
3
- `)}process.argv.includes("--json")?console.log(JSON.stringify(t,null,2)):console.log(s(t))}else if(i==="sandbox"){const{srtModuleUrl:a}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&a()&&(process.env.CHATPANEL_SRT_MODULE=a());const{runSandboxCli:s}=await import("@chatpanel/bridge/src/sandbox.js"),{sandboxCommand:h}=await import("../src/sandbox-cli.js"),{loadConfig:l}=await import("../src/config.js"),{readFileSync:u}=await import("node:fs"),{join:g}=await import("node:path"),c=await import("node:os");let e="";try{e=u(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||g(c.homedir(),".chatpanel","gateway-token"),"utf8").trim()}catch{}process.exit(await h(process.argv.slice(3),{cfg:l(),token:e,local:t=>s(t)}))}else if(i==="pair"){const{loadConfig:a}=await import("../src/config.js"),{readFileSync:s}=await import("node:fs"),{join:h}=await import("node:path"),l=await import("node:os"),g=`http://127.0.0.1:${a().port||4320}`,c=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||h(l.homedir(),".chatpanel","gateway-token");try{const e=s(c,"utf8").trim(),t=await fetch(`${g}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${e}`},signal:AbortSignal.timeout(2500)}),n=await t.json().catch(()=>({}));if(t.status===404)throw new Error(`the gateway at ${g} predates pairing (0.9.0) — update and restart it`);if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);console.log(`Pairing code: ${n.display||n.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(e){console.error(`could not get a pairing code from the gateway at ${g}: ${e?.message||e}${/ENOENT/.test(String(e?.message))?` (no token at ${c} — has the gateway started once?)`:""}`),process.exit(1)}}else if(i==="link"){const{linkCommand:a}=await import("../src/link-cli.js"),{loadConfig:s}=await import("../src/config.js"),{readFileSync:h}=await import("node:fs"),{join:l}=await import("node:path"),u=await import("node:os"),c=`http://127.0.0.1:${s().port||4320}`,e=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||l(u.homedir(),".chatpanel","gateway-token");let t="";try{t=h(e,"utf8").trim()}catch{console.error(`no gateway token at ${e} — has the gateway started once?`),process.exit(1)}const n=async(o,r,d)=>{try{const w=await fetch(`${c}${r}`,{method:o,headers:{authorization:`Bearer ${t}`,...d?{"content-type":"application/json"}:{}},body:d?JSON.stringify(d):void 0,signal:AbortSignal.timeout(2e4)});return{status:w.status,json:await w.json().catch(()=>null)}}catch(w){return{status:0,json:{error:{message:`no gateway answering at ${c} (${w?.message||w})`}}}}},p=process.stdin.isTTY?async o=>{const{createInterface:r}=await import("node:readline/promises"),d=r({input:process.stdin,output:process.stdout});try{return/^y(es)?$/i.test((await d.question(o)).trim())}finally{d.close()}}:null;process.exit(await a(process.argv.slice(3),{call:n,ask:p}))}else if(i==="local"){const{localStatus:a,formatLocalStatus:s}=await import("../src/local-status.js");process.stdout.write(s(await a()))}else if(i==="connect"){const{connectAgents:a,formatConnect:s}=await import("../src/connect-agents.js"),h=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(s(a({dryRun:h}),{dryRun:h}))}else if(i==="--confined"||i===void 0&&process.env.CHATPANEL_CONFINED!=="1"&&await(await import("../src/confine-start.js")).confinedByPolicy()){const{startConfined:a}=await import("../src/confine-start.js");await a({by:i==="--confined"?"flag":"policy"})}else{const{start:a,VERSION:s}=await import("../src/server.js"),{installService:h,uninstallService:l,serviceReport:u,stopService:g,pathWithDir:c}=await import("../src/service.js");switch(i){case"--stop":g(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(s);break;case"--fetch-apple-helper":{const{ensureAppleHelper:e,appleHelperWanted:t}=await import("../src/apple-helper-fetch.js"),n=await import("node:os");if(!t({release:n.release()})){console.log("Apple’s on-device model needs an Apple Silicon Mac on macOS 26 or later — nothing to fetch here.");break}try{const{loadConfig:p}=await import("../src/config.js"),o=await e({version:s,registries:p().registries||{},onProgress:r=>{r.phase==="download"&&console.log(`fetching the Apple on-device helper (v${r.version}) from ${new URL(r.url).host}…`)}});console.log(`Apple on-device helper: ${o}`)}catch(p){console.error(`could not fetch the Apple on-device helper: ${p?.message||p}`),process.exit(1)}break}case"--install":{try{const{ensureAppleHelper:n,appleHelperWanted:p,findAppleHelper:o}=await import("../src/apple-helper-fetch.js"),r=await import("node:os");if(p({release:r.release()})&&!o()){const{loadConfig:d}=await import("../src/config.js");await n({version:s,registries:d().registries||{}}),console.log("Apple on-device helper: fetched (this install came without it).")}}catch(n){console.log(`Apple on-device helper: not fetched (${String(n?.message||n).slice(0,160)}) — \`chatpanel-gateway --fetch-apple-helper\` tries again; everything else works without it.`)}const e=await h({version:s,force:process.argv.includes("--force")}),t=e.health;if(e.newer){const n=t.managedBy&&t.managedBy!=="gateway"?` (run by the ${t.managedBy.replace(/-child$/,"")} app)`:"";console.log(`ChatPanel Privacy Gateway v${t.version} is already running at ${t.url}${n} — newer than this copy (v${s}). Nothing was changed.`),console.log(" To bring this copy up to date: npm i -g @chatpanel/gateway --ignore-scripts (or re-run install.sh), then chatpanel-gateway --install"),console.log(` To run this older v${s} instead anyway: chatpanel-gateway --install --force`);break}if(e.ok){const n=e.deferredTo?` — the ${e.deferredTo} app's gateway (v${t.version}) is the one answering right now; this install takes over at the next login`:"",p=e.replaced?`, replacing v${e.replaced}`:"";e.unchanged?console.log(`ChatPanel Privacy Gateway v${t.version}: already running at ${t.url} and registered to start at login — nothing was changed, nothing was restarted.`):console.log(`ChatPanel Privacy Gateway v${t.version}: running at ${t.url}${p}, starts at login${e.wsl?" (Windows login, through wsl.exe)":""}${n}.`);let o=null;for(let r=0;r<30;r++){try{o=(await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(1500)})).json())?.bridge||null}catch{o=null}if(o&&o.mode!=="starting")break;await new Promise(d=>setTimeout(d,500))}if(o?["embedded","standalone","adopted"].includes(o.mode)?console.log(` bridge: ${o.mode}${o.version?` v${o.version}`:""} — local agents are available.`):console.error(` ⚠ bridge: ${o.why||o.mode}`):console.log(" bridge: this gateway does not report one yet — `chatpanel-gateway --status` shows it once it is up."),o?.version){const{staleBridgeCommands:r,staleBridgeLines:d}=await import("../src/service.js");for(const w of d(r({embedded:o.version}),{embedded:o.version}))console.log(w)}}else t.ok?(console.error(`ChatPanel Privacy Gateway: v${s} is registered to start at login, but v${t.version} still answers at ${t.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 ${t.url} after 40 s.`),e.errLog&&console.error(` last of the error log:
4
- ${e.errLog.split(`
5
- `).map(n=>` ${n}`).join(`
6
- `)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself."));e.shadow&&(console.log(` ⚠ ${e.shadow}/chatpanel-gateway comes first on your PATH, so typing \`chatpanel-gateway\` still runs THAT copy, not this v${s}.`),console.log(` Remove it, or run this one by its full path. (The service just registered is this v${s} either way.)`));try{const{pruneForeignPrebuilds:n,pruneLine:p}=await import("../src/prune-install.js"),o=p(n({log:r=>console.error(r)}));o&&console.log(o)}catch{}e.launcher==="powershell"&&console.log(" (VBScript is not installed here, so the login launcher is PowerShell — a console flashes for an instant at login.)"),e.path?.added?console.log(` Added ${e.path.dir} to your PATH — \`chatpanel-gateway\` works in a NEW terminal.`):e.path?.error?console.log(` Could not add ${e.path.dir} to your PATH (${e.path.error}) — add it yourself to run \`chatpanel-gateway\` by name.`):e.path?.dir&&e.wsl&&c(process.env.PATH||"",e.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${e.path.dir}:$PATH"`),t.ok||process.exit(1);break}case"--uninstall":l(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":{console.log(await u());try{const{loadConfig:e}=await import("../src/config.js"),{sandboxProblems:t}=await import("../src/configstore.js");for(const n of t(e()))console.log(` ⚠ ${n}`)}catch{}break}case void 0:await a();break;case"--help":case"-h":console.log([`ChatPanel Privacy Gateway v${s}`,""," chatpanel-gateway --install run after every install or upgrade: login auto-start, replace an older one, wait for it and its bridge"," chatpanel-gateway run in the foreground, in this terminal"," chatpanel-gateway --status what starts it, what answers on the port, which copy is on PATH, how agents are sandboxed"," chatpanel-gateway sandbox what the sandbox is doing; `sandbox allow <agent> aws` lets one agent use a sign-in"," chatpanel-gateway --stop stop it (on Windows, before `npm i -g`)"," chatpanel-gateway --uninstall remove login auto-start"," chatpanel-gateway local the bridge and the gateway, one view"," chatpanel-gateway pair a one-time code for a browser the gateway does not recognise"," chatpanel-gateway link ChatPanel Link: paired devices; `link pair --partner <name>` lets a partner server in (shown and confirmed first); `link revoke <id>`; `link route <mode>`"," chatpanel-gateway connect point your CLI agents (Codex, Claude Code, …) at it"," chatpanel-gateway --audit every host it has contacted, and every host its config allows"," chatpanel-gateway --version print the version"].join(`
7
- `));break;default:console.error(`unknown option: ${i}
8
- Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|pair|link|policy|--audit|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(a){console.error(`error: ${a.message}`),process.exit(1)}
2
+ const r=process.argv[2],P={"--bridge":"chatpanel-bridge","--mcp-stdio":"chatpanel-bridge-mcp",mcp:"chatpanel-history-mcp","--extract-worker":"chatpanel-extract"},k=(e=process.argv)=>e.includes("--mcp-stdio")?P["--mcp-stdio"]:P[e[2]]||"chatpanel-gateway";try{process.title=k()}catch{}if(!process.versions.bun&&r!=="--version"&&r!=="-v"){const[e,t]=String(process.versions.node||"0.0").split(".").map(Number);(e<22||e===22&&t<13)&&(console.error(`ChatPanel Gateway needs Node.js 22.13 or newer — this is ${process.version}.`),console.error("Update Node (https://nodejs.org, or `nvm install 22`), then run this again — or use the standalone binary, which carries its own runtime:"),console.error(" curl -fsSL https://dl.chatpanel.net/install.sh | bash"),process.exit(1))}try{if(r==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:e}=await import("../src/extract/worker.js");e()}else if(r==="--bridge"){if(process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),!process.argv.includes("--mcp-stdio")&&!process.argv.includes("--version")){const{trustSystemCertificates:e,systemCaWantedOnDisk:t}=await import("../src/system-ca.js");e({enabled:t()})}await import("@chatpanel/bridge/src/server.js")}else if(r==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(r==="mcp"){const{runMcpServer:e}=await import("../src/mcp.js");await e()}else if(r==="tools"||r==="call"){const{runMcpCli:e}=await import("../src/mcp-cli.js");process.exit(await e(process.argv.slice(2)))}else if(r==="policy"){const{loadPolicy:e,formatPolicy:t,PolicyLoadError:w}=await import("../src/policy.js");try{const i=await e();process.argv.includes("--json")?console.log(JSON.stringify(i?{...i,label:void 0}:null,null,2)):console.log(t(i))}catch(i){throw i instanceof w&&(console.error(`org policy: ${i.message}`),process.exit(78)),i}}else if(r==="--audit"){const{egressAudit:e,formatAudit:t}=await import("../src/egress.js"),{loadConfig:w}=await import("../src/config.js"),{readFileSync:i}=await import("node:fs"),{join:v}=await import("node:path"),y=await import("node:os"),c=w(),a=`http://127.0.0.1:${c.port||4320}`;let o=null,l=`no gateway running at ${a}`;try{const u=i(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||v(y.homedir(),".chatpanel","gateway-token"),"utf8").trim(),m=await fetch(`${a}/audit`,{headers:{authorization:`Bearer ${u}`},signal:AbortSignal.timeout(2500)});if(m.ok)o=await m.json();else if(m.status===404){const g=await fetch(`${a}/health`,{signal:AbortSignal.timeout(2500)}).then(f=>f.json()).catch(()=>null);l=`the gateway running at ${a}${g?.version?` (${g.version})`:""} predates --audit (0.7.0) — restart it after updating`}else l=`the gateway at ${a} refused the audit (HTTP ${m.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!o){const{VERSION:u}=await import("../src/server.js"),{systemCaWanted:m}=await import("../src/system-ca.js"),g=m(c),{partnerDevicesOnDisk:f}=await import("../src/link-host.js"),h=c.link?.enabled===!1?[]:f(...c.link?.path?[c.link.path]:[]);o={...e(c,{ledger:null,version:u,linkPartners:h,certificates:{on:!1,added:0,wanted:g,why:g?"no gateway is running; when one starts it adds this computer's list":"switched off (tls.systemCa: false, or CHATPANEL_SYSTEM_CA=off)"}}),observed:[]},console.log(`(${l}; showing what the current config allows)
3
+ `)}process.argv.includes("--json")?console.log(JSON.stringify(o,null,2)):console.log(t(o))}else if(r==="sandbox"){const{srtModuleUrl:e}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&e()&&(process.env.CHATPANEL_SRT_MODULE=e());const{runSandboxCli:t}=await import("@chatpanel/bridge/src/sandbox.js"),{sandboxCommand:w}=await import("../src/sandbox-cli.js"),{loadConfig:i}=await import("../src/config.js"),{readFileSync:v}=await import("node:fs"),{join:y}=await import("node:path"),c=await import("node:os");let a="";try{a=v(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||y(c.homedir(),".chatpanel","gateway-token"),"utf8").trim()}catch{}process.exit(await w(process.argv.slice(3),{cfg:i(),token:a,local:o=>t(o)}))}else if(r==="pair"){const{loadConfig:e}=await import("../src/config.js"),{readFileSync:t}=await import("node:fs"),{join:w}=await import("node:path"),i=await import("node:os"),y=`http://127.0.0.1:${e().port||4320}`,c=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||w(i.homedir(),".chatpanel","gateway-token");try{const a=t(c,"utf8").trim(),o=await fetch(`${y}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${a}`},signal:AbortSignal.timeout(2500)}),l=await o.json().catch(()=>({}));if(o.status===404)throw new Error(`the gateway at ${y} predates pairing (0.9.0) — update and restart it`);if(!o.ok)throw new Error(l.error||`HTTP ${o.status}`);console.log(`Pairing code: ${l.display||l.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(a){console.error(`could not get a pairing code from the gateway at ${y}: ${a?.message||a}${/ENOENT/.test(String(a?.message))?` (no token at ${c} — has the gateway started once?)`:""}`),process.exit(1)}}else if(r==="link"){const{linkCommand:e}=await import("../src/link-cli.js"),{loadConfig:t}=await import("../src/config.js"),{readFileSync:w}=await import("node:fs"),{join:i}=await import("node:path"),v=await import("node:os"),c=`http://127.0.0.1:${t().port||4320}`,a=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||i(v.homedir(),".chatpanel","gateway-token");let o="";try{o=w(a,"utf8").trim()}catch{console.error(`no gateway token at ${a} — has the gateway started once?`),process.exit(1)}const l=async(m,g,f)=>{try{const h=await fetch(`${c}${g}`,{method:m,headers:{authorization:`Bearer ${o}`,...f?{"content-type":"application/json"}:{}},body:f?JSON.stringify(f):void 0,signal:AbortSignal.timeout(2e4)});return{status:h.status,json:await h.json().catch(()=>null)}}catch(h){return{status:0,json:{error:{message:`no gateway answering at ${c} (${h?.message||h})`}}}}},u=process.stdin.isTTY?async m=>{const{createInterface:g}=await import("node:readline/promises"),f=g({input:process.stdin,output:process.stdout});try{return/^y(es)?$/i.test((await f.question(m)).trim())}finally{f.close()}}:null;process.exit(await e(process.argv.slice(3),{call:l,ask:u}))}else if(r==="local"){const{localStatus:e,formatLocalStatus:t}=await import("../src/local-status.js");process.stdout.write(t(await e()))}else if(r==="connect"){const{connectAgents:e,formatConnect:t}=await import("../src/connect-agents.js"),w=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(t(e({dryRun:w}),{dryRun:w}))}else if(r==="--confined"||r===void 0&&process.env.CHATPANEL_CONFINED!=="1"&&await(await import("../src/confine-start.js")).confinedByPolicy()){const{startConfined:e}=await import("../src/confine-start.js");await e({by:r==="--confined"?"flag":"policy"})}else{const{start:e,VERSION:t}=await import("../src/server.js"),{installService:w,uninstallService:i,serviceReport:v,stopService:y,pathWithDir:c}=await import("../src/service.js");switch(r){case"--stop":y(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(t);break;case"--fetch-apple-helper":{const{ensureAppleHelper:a,appleHelperWanted:o}=await import("../src/apple-helper-fetch.js"),l=await import("node:os");if(!o({release:l.release()})){console.log("Apple’s on-device model needs an Apple Silicon Mac on macOS 26 or later — nothing to fetch here.");break}try{const{loadConfig:u}=await import("../src/config.js"),m=await a({version:t,registries:u().registries||{},onProgress:g=>{g.phase==="download"&&console.log(`fetching the Apple on-device helper (v${g.version}) from ${new URL(g.url).host}…`)}});console.log(`Apple on-device helper: ${m}`)}catch(u){console.error(`could not fetch the Apple on-device helper: ${u?.message||u}`),process.exit(1)}break}case"--install":{try{const{ensureAppleHelper:d,appleHelperWanted:$,findAppleHelper:s}=await import("../src/apple-helper-fetch.js"),A=await import("node:os");if($({release:A.release()})&&!s()){const{loadConfig:b}=await import("../src/config.js");await d({version:t,registries:b().registries||{}}),console.log("Apple on-device helper: fetched (this install came without it).")}}catch(d){console.log(`Apple on-device helper: not fetched (${String(d?.message||d).slice(0,160)}) — \`chatpanel-gateway --fetch-apple-helper\` tries again; everything else works without it.`)}const a=process.argv.includes("--force"),{gatewayCommands:o,newerCopy:l,handoffLine:u,retireStandaloneGateway:m,installCopyLines:g}=await import("../src/install-copies.js"),f=o(),h=a||process.env.CHATPANEL_INSTALL_HANDOFF?null:l(f,t);if(h){console.log(u(h,t));const{spawnSync:d}=await import("node:child_process"),$=/\.cmd$/i.test(h.path),s=d($?`"${h.path}"`:h.path,process.argv.slice(2),{stdio:"inherit",shell:$,env:{...process.env,CHATPANEL_INSTALL_HANDOFF:"1"}});s.error&&(console.error(` could not run ${h.path}: ${s.error.message} — run it yourself: ${h.path} --install`),process.exit(1)),process.exit(s.status??1)}const n=await w({version:t,force:a}),p=n.health;if(n.newer){const d=p.managedBy&&p.managedBy!=="gateway"?` (run by the ${p.managedBy.replace(/-child$/,"")} app)`:"";console.log(`ChatPanel Privacy Gateway v${p.version} is already running at ${p.url}${d} — newer than this copy (v${t}). Nothing was changed.`),console.log(" To bring this copy up to date: npm i -g @chatpanel/gateway --ignore-scripts (or re-run install.sh), then chatpanel-gateway --install"),console.log(` To run this older v${t} instead anyway: chatpanel-gateway --install --force`);break}if(n.ok){const d=n.deferredTo?` — the ${n.deferredTo} app's gateway (v${p.version}) is the one answering right now; this install takes over at the next login`:"",$=n.replaced?`, replacing v${n.replaced}`:"";n.unchanged?console.log(`ChatPanel Privacy Gateway v${p.version}: already running at ${p.url} and registered to start at login — nothing was changed, nothing was restarted.`):console.log(`ChatPanel Privacy Gateway v${p.version}: running at ${p.url}${$}, starts at login${n.wsl?" (Windows login, through wsl.exe)":""}${d}.`);let s=null;for(let A=0;A<30;A++){try{s=(await(await fetch(`${p.url}/health`,{signal:AbortSignal.timeout(1500)})).json())?.bridge||null}catch{s=null}if(s&&s.mode!=="starting")break;await new Promise(b=>setTimeout(b,500))}if(s?["embedded","standalone","adopted"].includes(s.mode)?console.log(` bridge: ${s.mode}${s.version?` v${s.version}`:""} — local agents are available.`):console.error(` ⚠ bridge: ${s.why||s.mode}`):console.log(" bridge: this gateway does not report one yet — `chatpanel-gateway --status` shows it once it is up."),s?.version){const{staleBridgeCommands:A,staleBridgeLines:b}=await import("../src/service.js");for(const C of b(A({embedded:s.version}),{embedded:s.version}))console.log(C)}}else p.ok?(console.error(`ChatPanel Privacy Gateway: v${t} is registered to start at login, but v${p.version} still answers at ${p.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 ${p.url} after 40 s.`),n.errLog&&console.error(` last of the error log:
4
+ ${n.errLog.split(`
5
+ `).map(d=>` ${d}`).join(`
6
+ `)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself."));const T=n.ok?m({copies:f,version:t}):null;for(const d of g({copies:f,version:t,retired:T,force:a}))console.log(d);try{const{pruneForeignPrebuilds:d,pruneLine:$}=await import("../src/prune-install.js"),s=$(d({log:A=>console.error(A)}));s&&console.log(s)}catch{}n.launcher==="powershell"&&console.log(" (VBScript is not installed here, so the login launcher is PowerShell — a console flashes for an instant at login.)"),n.path?.added?console.log(` Added ${n.path.dir} to your PATH — \`chatpanel-gateway\` works in a NEW terminal.`):n.path?.error?console.log(` Could not add ${n.path.dir} to your PATH (${n.path.error}) — add it yourself to run \`chatpanel-gateway\` by name.`):n.path?.dir&&n.wsl&&c(process.env.PATH||"",n.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${n.path.dir}:$PATH"`),p.ok||process.exit(1);break}case"--uninstall":i(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":{console.log(await v());try{const{gatewayCommands:a,statusCopyLines:o}=await import("../src/install-copies.js"),{probeHealth:l}=await import("../src/service.js");for(const u of o({copies:a(),version:t,running:await l()}))console.log(u)}catch(a){console.log(` (could not list the installed copies: ${a?.message||a})`)}try{const{loadConfig:a}=await import("../src/config.js"),{sandboxProblems:o}=await import("../src/configstore.js");for(const l of o(a()))console.log(` ⚠ ${l}`)}catch{}break}case void 0:await e();break;case"--help":case"-h":console.log([`ChatPanel Privacy Gateway v${t}`,""," chatpanel-gateway --install run after every install or upgrade: login auto-start, replace an older one, wait for it and its bridge"," chatpanel-gateway run in the foreground, in this terminal"," chatpanel-gateway --status what starts it, what answers on the port, which copy is on PATH, how agents are sandboxed"," chatpanel-gateway sandbox what the sandbox is doing; `sandbox allow <agent> aws` lets one agent use a sign-in"," chatpanel-gateway --stop stop it (on Windows, before `npm i -g`)"," chatpanel-gateway --uninstall remove login auto-start"," chatpanel-gateway local the bridge and the gateway, one view"," chatpanel-gateway pair a one-time code for a browser the gateway does not recognise"," chatpanel-gateway link ChatPanel Link: paired devices; `link pair --partner <name>` lets a partner server in (shown and confirmed first); `link revoke <id>`; `link route <mode>`"," chatpanel-gateway connect point your CLI agents (Codex, Claude Code, …) at it"," chatpanel-gateway --audit every host it has contacted, and every host its config allows"," chatpanel-gateway --version print the version"].join(`
7
+ `));break;default:console.error(`unknown option: ${r}
8
+ Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|pair|link|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.98.3",
3
+ "version": "0.100.0",
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": {
@@ -24,7 +24,7 @@
24
24
  "dependencies": {
25
25
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
26
26
  "@chatpanel/bridge": "^0.46.1",
27
- "@chatpanel/events": "^0.361.0",
27
+ "@chatpanel/events": "^0.362.0",
28
28
  "@chatpanel/pii": "^0.15.0",
29
29
  "@huggingface/transformers": "^4.2.0",
30
30
  "defuddle": "^0.19.4",
package/src/config.js CHANGED
@@ -1 +1 @@
1
- import{readFileSync as d,existsSync as l}from"node:fs";import{join as p}from"node:path";import A 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 m}from"./diarize-models.js";const s={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],maxBodyBytes:26214400,tls:{systemCa:!0},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:m,warmMs:15*6e4},read:{provider:"defuddle",remote:{url:"",key:""}},search:{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},capabilities:{},runtime:{services:{}},registries:{},fusions:[],tts:{enabled:!0,warmMs:15*6e4,provider:"local",model:"",voice:"",allowDownload:!0,remote:{baseUrl:"",model:"",voice:"",redact:!0}},logRequests:!0,logDetail:"off"};function r(t,e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&t&&typeof t=="object"){const i={...t};for(const o of Object.keys(e))i[o]=r(t[o],e[o]);return i}return e===void 0?t:e}function g(t=process.env){let e=s;const i=t.CHATPANEL_GATEWAY_CONFIG||p(A.homedir(),".chatpanel","gateway.config.json");if(l(i))try{e=r(e,JSON.parse(d(i,"utf8")))}catch(a){throw new Error(`bad config file ${i}: ${a.message}`)}t.CHATPANEL_GATEWAY_HOST&&(e=r(e,{host:t.CHATPANEL_GATEWAY_HOST})),t.CHATPANEL_GATEWAY_PORT&&(e=r(e,{port:Number(t.CHATPANEL_GATEWAY_PORT)})),t.OPENAI_BASE_URL&&(e=r(e,{upstreams:{openai:{baseUrl:t.OPENAI_BASE_URL}}})),t.ANTHROPIC_BASE_URL&&(e=r(e,{upstreams:{anthropic:{baseUrl:t.ANTHROPIC_BASE_URL}}})),t.CHATPANEL_REDACTION_TIER&&(e=r(e,{redaction:{tier:t.CHATPANEL_REDACTION_TIER}}));for(const[a,n]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])t[n]&&(e=r(e,{registries:{[a]:t[n]}}));if(e.registries?.models&&!t.CHATPANEL_REGISTRY_MODELS)try{process.env.CHATPANEL_REGISTRY_MODELS=e.registries.models}catch{}const o=Number(e.port);return(!Number.isInteger(o)||o<1||o>65535)&&(e.port!==s.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(e.port)} — using ${s.port}`),e=r(e,{port:s.port})),e}export{s as DEFAULTS,g as loadConfig};
1
+ import{readFileSync as d,existsSync as l}from"node:fs";import{join as p}from"node:path";import A 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 m}from"./diarize-models.js";const s={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],maxBodyBytes:26214400,tls:{systemCa:!0},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:m,segment:!0,warmMs:15*6e4},read:{provider:"defuddle",remote:{url:"",key:""}},search:{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},capabilities:{},runtime:{services:{}},registries:{},fusions:[],tts:{enabled:!0,warmMs:15*6e4,provider:"local",model:"",voice:"",allowDownload:!0,remote:{baseUrl:"",model:"",voice:"",redact:!0}},logRequests:!0,logDetail:"off"};function r(t,e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&t&&typeof t=="object"){const i={...t};for(const o of Object.keys(e))i[o]=r(t[o],e[o]);return i}return e===void 0?t:e}function R(t=process.env){let e=s;const i=t.CHATPANEL_GATEWAY_CONFIG||p(A.homedir(),".chatpanel","gateway.config.json");if(l(i))try{e=r(e,JSON.parse(d(i,"utf8")))}catch(a){throw new Error(`bad config file ${i}: ${a.message}`)}t.CHATPANEL_GATEWAY_HOST&&(e=r(e,{host:t.CHATPANEL_GATEWAY_HOST})),t.CHATPANEL_GATEWAY_PORT&&(e=r(e,{port:Number(t.CHATPANEL_GATEWAY_PORT)})),t.OPENAI_BASE_URL&&(e=r(e,{upstreams:{openai:{baseUrl:t.OPENAI_BASE_URL}}})),t.ANTHROPIC_BASE_URL&&(e=r(e,{upstreams:{anthropic:{baseUrl:t.ANTHROPIC_BASE_URL}}})),t.CHATPANEL_REDACTION_TIER&&(e=r(e,{redaction:{tier:t.CHATPANEL_REDACTION_TIER}}));for(const[a,n]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])t[n]&&(e=r(e,{registries:{[a]:t[n]}}));if(e.registries?.models&&!t.CHATPANEL_REGISTRY_MODELS)try{process.env.CHATPANEL_REGISTRY_MODELS=e.registries.models}catch{}const o=Number(e.port);return(!Number.isInteger(o)||o<1||o>65535)&&(e.port!==s.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(e.port)} — using ${s.port}`),e=r(e,{port:s.port})),e}export{s as DEFAULTS,R as loadConfig};
@@ -0,0 +1,3 @@
1
+ import{existsSync as A,statSync as C,mkdirSync as B,createWriteStream as W,renameSync as U}from"node:fs";import{join as k,dirname as J}from"node:path";import{spawn as V,execFile as _}from"node:child_process";import{Readable as G}from"node:stream";import{modelRoot as K}from"./ner-engine.js";import{findAppleHelper as Q}from"./apple-helper-fetch.js";const x="coreml/ane",L=Object.freeze(["BarkEncoder.mlpackage/Manifest.json","BarkEncoder.mlpackage/Data/com.apple.CoreML/model.mlmodel","BarkEncoder.mlpackage/Data/com.apple.CoreML/weights/weight.bin","decoder.npz","vocab.json"]),Y=Object.freeze(["coreml/LICENSE","coreml/NOTICE"]),P="0.4.0",q=10*6e4,I=16e3;function N(e){return k(K(),...String(e).split("/"))}function T(e){return k(N(e),...x.split("/"))}function X(e){const n=T(e);try{return L.every(o=>{const t=k(n,o);return A(t)&&C(t).size>0})}catch{return!1}}function Z(e,n=P){const o=/(\d+)\.(\d+)\.(\d+)/.exec(String(e||""));if(!o)return!1;const t=o.slice(1,4).map(Number),a=n.split(".").map(Number);for(let i=0;i<3;i++)if(t[i]!==a[i])return t[i]>a[i];return!0}function z(e,n=""){return e?`the Apple helper here is ${n||"older than "+P} and speech needs ${P} — run \`chatpanel-gateway --fetch-apple-helper\` (a source checkout: Install on the Apple on-device row rebuilds it)`:"the Apple helper is not installed — Install it on the Apple on-device row (Settings › Runtime), or run `chatpanel-gateway --fetch-apple-helper`"}async function ee(e,{fetchImpl:n=fetch}={}){const o=`https://huggingface.co/api/models/${e}/tree/main/${x}?recursive=true`,t=await n(o);if(!t.ok)throw new Error(`list ${x} → HTTP ${t.status}`);const a=await t.json(),i=`${x}/`,r=(Array.isArray(a)?a:[]).filter(s=>s&&s.type==="file"&&typeof s.path=="string"&&s.path.startsWith(i)&&!s.path.endsWith(".py")).map(s=>({path:s.path.slice(i.length),size:Number(s.size)||0})),c=L.filter(s=>!r.some(d=>d.path===s));if(c.length)throw new Error(`the repo's ${x} lacks ${c.join(", ")}`);return r}async function D(e,n,{onProgress:o,log:t,fetchImpl:a=fetch,label:i=n}={}){const r=await a(e,{redirect:"follow"});if(!r.ok||!r.body)throw new Error(`fetch ${i} → HTTP ${r.status}`);B(J(n),{recursive:!0});const c=Number(r.headers.get("content-length"))||0,s=`${n}.part`,d=W(s);let b=0,w=-1;const g=G.fromWeb(r.body);g.on("data",E=>{if(b+=E.length,c){const p=Math.round(b/c*100);p!==w&&(w=p,o?.({file:i,pct:p}))}}),await new Promise((E,p)=>{g.pipe(d),d.on("finish",E),d.on("error",p),g.on("error",p)}),U(s,n),t?.(`[speech] fetched ${i}`)}async function te(e,{onProgress:n,log:o,fetchImpl:t=fetch}={}){const a=T(e),i=await ee(e,{fetchImpl:t});for(const{path:r}of i){const c=k(a,r);A(c)&&C(c).size>0||(o?.(`[speech] downloading ${r}…`),await D(`https://huggingface.co/${e}/resolve/main/${x}/${r}`,c,{onProgress:n,log:o,fetchImpl:t,label:r}))}for(const r of Y){const c=k(N(e),...r.split("/"));if(!A(c))try{await D(`https://huggingface.co/${e}/resolve/main/${r}`,c,{log:o,fetchImpl:t,label:r})}catch(s){o?.(`[speech] no ${r} in the repo (${s.message})`)}}return a}function re(e,{execFileImpl:n=_}={}){return new Promise(o=>{try{n(e,["--version"],{timeout:1e4},(t,a)=>o(t?"":String(a||"").trim()))}catch{o("")}})}async function pe({modelId:e,allowDownload:n=!0,onProgress:o,log:t=()=>{},helper:a=Q(),units:i="ane",onExit:r=()=>{},spawnImpl:c=V,execFileImpl:s=_,fetchImpl:d=fetch,readyTimeoutMs:b=q}){if(!a)throw new Error(z(!1));const w=await re(a,{execFileImpl:s});if(!Z(w))throw new Error(z(!0,w));const g=X(e);if(!g&&!n)throw new Error("model not on disk and downloads disabled");const E=g?T(e):await te(e,{onProgress:o,log:t,fetchImpl:d}),p=c(a,["speech","--model",E,"--port","0","--units",i],{stdio:["ignore","pipe","pipe"]});let y="",M=!0,O=!1,R=!1;p.stderr?.on("data",u=>{for(const l of String(u).split(`
2
+ `))l.trim()&&(y=l.trim(),t(`[speech] ${y}`))});const v=await new Promise((u,l)=>{let m="";const $=setTimeout(()=>{try{p.kill()}catch{}l(new Error(`the speech helper did not come up within ${Math.round(b/6e4)} min${y?` (${y})`:""}`))},b);p.stdout?.on("data",f=>{m+=f;const h=m.indexOf(`
3
+ `);if(!(h<0)){clearTimeout($);try{const S=JSON.parse(m.slice(0,h));if(S&&S.ready&&S.port)return O=!0,u(S);l(new Error(`unexpected helper reply: ${m.slice(0,h)}`))}catch{l(new Error(`unexpected helper reply: ${m.slice(0,h)}`))}}}),p.on("error",f=>{clearTimeout($),l(new Error(`cannot start the speech helper: ${f.message}`))}),p.on("exit",f=>{clearTimeout($),M=!1;const h=`the speech helper exited (${f})${y?`: ${y}`:""}`;if(!O)return l(new Error(h));R||r(h)})}),H=`http://127.0.0.1:${v.port}`;async function j(u){if(!(u instanceof Float32Array)||u.length<400)return"";if(!M)throw new Error("the speech helper is not running");const l=Buffer.allocUnsafe(u.length*2);for(let f=0;f<u.length;f++){const h=Math.max(-1,Math.min(1,u[f]));l.writeInt16LE(h<0?Math.round(h*32768):Math.round(h*32767),f*2)}const m=await d(`${H}/v1/audio/transcriptions`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({pcm16:l.toString("base64"),sampleRate:I})}),$=await m.json().catch(()=>({}));if(!m.ok)throw new Error($?.error?.message||`speech helper → HTTP ${m.status}`);return String($.text||"").replace(/\s+/g," ").trim()}function F(){R=!0,M=!1;try{p.kill()}catch{}}return{transcribe:j,dispose:F,dir:E,windows:v.windows||[],port:v.port,pid:p.pid,version:w}}export{Y as COREML_LICENCE,x as COREML_PACKAGE,L as COREML_REQUIRED,q as READY_TIMEOUT_MS,I as SAMPLE_RATE,P as SPEECH_HELPER_MIN,N as coremlDir,X as coremlOnDisk,T as coremlPackageDir,te as ensureFiles,z as helperAdvice,re as helperVersion,Z as helperVersionOk,ee as listPackageFiles,pe as loadRecognizer};
@@ -1 +1 @@
1
- import{ensureLib as R,modelRoot as O}from"./ner-engine.js";import{join as P}from"node:path";import{existsSync as q,readdirSync as I}from"node:fs";import{makeWarmTimer as M}from"./warm-timer.js";import{createSpeakerClusterer as C}from"@chatpanel/events/speaker-cluster.js";import{DEFAULT_DIARIZE_MODEL as b,diarizeThreshold as N,isKnownDiarizeModel as W}from"./diarize-models.js";const V=b;let o="off",f=b,d=null,g=null,p=null,u=null,c=null,a=null,w=0,_=0;function X(){return f}function v(){return N(f)}function A(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function Y(){return o}function z(){return o==="ready"&&!!d&&!!g}function tt(){return c}function et(){return{configured:o!=="off",ok:z(),state:o,model:f,loaded:!!d,threshold:v(),error:p,warmMs:a?.warmMs??null}}function nt(){return!!a?.pending()}function rt(){w++,a?.disarm()}function ot(){w=Math.max(0,w-1),w===0&&_===0&&z()&&a?.arm()}function h(){return w>0||_>0||o==="loading"||o==="downloading"}async function y({log:t=()=>{}}={}){if(h())return!1;a?.disarm();const e=d;if(d=null,g=null,u=null,c=null,p=null,o="off",e){try{await e.dispose?.()}catch{}t("[diarize] idle — speaker model unloaded (reloads on the next diarizing session)")}return!0}function Z(t=f,e=A()){const n=P(O(),...t.split("/"),"onnx");if(!q(n))return!1;const r=e==="fp32"?"":e==="q8"?"_quantized":`_${e}`;try{return I(n).some(s=>s===`model${r}.onnx`)}catch{return!1}}async function $({log:t=()=>{},allowDownload:e=!0}={}){let n;try{n=await R()}catch(l){return o="error",p=l.message,t(`[diarize] engine unavailable (${l.message})`),!1}const r=f,s=Z(r);if(n.env.allowRemoteModels=s?!1:!!e,!s&&!e)return o="error",p="model not on disk and downloads disabled",!1;const i=n.env.remoteHost;if(!s)try{n.env.remoteHost="https://huggingface.co/"}catch{}o=s?"loading":"downloading",s||(c={model:r,file:null,pct:0},t(`[diarize] downloading ${r} (one-time)…`));try{const{AutoModel:l,AutoProcessor:E}=n,k=m=>{if(!m)return;const L=typeof m.progress=="number"?Math.round(m.progress):c?.pct??0;(m.status==="progress"||m.status==="download"||m.status==="initiate")&&(c={model:r,file:m.file||c?.file||null,pct:L})},F=await E.from_pretrained(r,{progress_callback:k}),H=await l.from_pretrained(r,{dtype:A(),progress_callback:k});return g=F,d=H,o="ready",p=null,c=null,t(`[diarize] ready — ${r} @ ${A()} (speakers split at cosine ${v()})`),!0}catch(l){return p=l.message,c=null,o="error",t(`[diarize] load failed (${l.message}) — diarization off`),!1}finally{try{n.env.remoteHost=i}catch{}}}function lt(t={}){if(u&&o!=="error")return u;o="loading";const e=typeof t.onLog=="function"?t.onLog:()=>{};return a=M({warmMs:t.warmMs,busy:h,log:e,unload:()=>y({log:e})}),u=T($({log:e,allowDownload:t.allowDownload!==!1})),u}function T(t){return t.then(e=>(e&&!h()&&a?.arm(),e))}async function it(t,{log:e=()=>{}}={}){return W(t)?t===f?!0:h()?!1:(await y({log:()=>{}}),f=t,e(`[diarize] speaker model set to ${t} (loads on the next diarizing session)`),!0):!1}function at({onLog:t}={}){return u=null,o="loading",a??=M({warmMs:void 0,busy:h,log:t||(()=>{}),unload:()=>y({log:t||(()=>{})})}),u=T($({log:t,allowDownload:!0})),u}const S=16e3;function x(t){let e=0;for(const r of t)e+=r*r;e=Math.sqrt(e)||1;const n=new Float32Array(t.length);for(let r=0;r<t.length;r++)n[r]=t[r]/e;return n}async function D(t){try{const e=await g(t),n=await d(e),r=n.embeddings??n.logits??n.last_hidden_state;return r?.data?Float32Array.from(r.data):null}catch{return null}}async function st(t){if(!z()||!(t instanceof Float32Array)||!t.length)return null;_++;try{return await j(t)}finally{_--,h()||a?.arm()}}async function j(t){const e=2*S,n=Math.round(1.3*S);if(t.length<=Math.round(e*1.4)){const i=await D(t);return i?x(i):null}const r=[];for(let i=0;i+e<=t.length;i+=n){const l=await D(t.subarray(i,i+e));l&&r.push(x(l))}if(!r.length){const i=await D(t);return i?x(i):null}const s=new Float32Array(r[0].length);for(const i of r)for(let l=0;l<s.length;l++)s[l]+=i[l];return x(s)}function ut(){a?.disarm(),a=null,w=0,_=0,o="off",f=b,d=null,g=null,p=null,u=null,c=null}function ct(t,e,{warmMs:n=null}={}){d=t,g=e,o=t?"ready":"off",n!==null&&(a=M({warmMs:n,busy:h,unload:()=>y()}),t&&a.arm())}class ft{constructor({threshold:e=v(),maxSpeakers:n=12}={}){this.threshold=e,this.maxSpeakers=n,this._voices=C({threshold:e,maxSpeakers:n})}assign(e,n){return this._voices.assign(e,n)}get centroids(){return this._voices.toJSON().centroids}}export{V as DIARIZE_MODEL,ft as Diarizer,ut as _reset,ct as _setForTest,X as activeModel,v as activeThreshold,at as download,st as embed,et as health,lt as init,z as isReady,Z as modelOnDisk,tt as progress,ot as release,rt as retain,it as setModel,Y as state,y as unload,nt as warmPending};
1
+ import{ensureLib as R,modelRoot as O,withModelSource as P}from"./ner-engine.js";import{join as q}from"node:path";import{existsSync as I,readdirSync as C}from"node:fs";import{makeWarmTimer as M}from"./warm-timer.js";import{createSpeakerClusterer as H}from"@chatpanel/events/speaker-cluster.js";import{DEFAULT_DIARIZE_MODEL as b,diarizeThreshold as N,isKnownDiarizeModel as W}from"./diarize-models.js";const V=b;let l="off",f=b,d=null,g=null,p=null,u=null,c=null,a=null,w=0,_=0;function X(){return f}function A(){return N(f)}function z(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function Y(){return l}function D(){return l==="ready"&&!!d&&!!g}function ee(){return c}function te(){return{configured:l!=="off",ok:D(),state:l,model:f,loaded:!!d,threshold:A(),error:p,warmMs:a?.warmMs??null}}function ne(){return!!a?.pending()}function re(){w++,a?.disarm()}function oe(){w=Math.max(0,w-1),w===0&&_===0&&D()&&a?.arm()}function h(){return w>0||_>0||l==="loading"||l==="downloading"}async function y({log:e=()=>{}}={}){if(h())return!1;a?.disarm();const t=d;if(d=null,g=null,u=null,c=null,p=null,l="off",t){try{await t.dispose?.()}catch{}e("[diarize] idle — speaker model unloaded (reloads on the next diarizing session)")}return!0}function Z(e=f,t=z()){const r=q(O(),...e.split("/"),"onnx");if(!I(r))return!1;const n=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return C(r).some(i=>i===`model${n}.onnx`)}catch{return!1}}async function $({log:e=()=>{},allowDownload:t=!0}={}){let r;try{r=await R()}catch(o){return l="error",p=o.message,e(`[diarize] engine unavailable (${o.message})`),!1}const n=f,i=Z(n);if(!i&&!t)return l="error",p="model not on disk and downloads disabled",!1;l=i?"loading":"downloading",i||(c={model:n,file:null,pct:0},e(`[diarize] downloading ${n} (one-time)…`));try{const{AutoModel:o,AutoProcessor:s}=r,k=m=>{if(!m)return;const L=typeof m.progress=="number"?Math.round(m.progress):c?.pct??0;(m.status==="progress"||m.status==="download"||m.status==="initiate")&&(c={model:n,file:m.file||c?.file||null,pct:L})},{processor:E,model:F}=await P({host:i?null:"https://huggingface.co/",allowRemote:!i},async()=>({processor:await s.from_pretrained(n,{progress_callback:k}),model:await o.from_pretrained(n,{dtype:z(),progress_callback:k})}));return g=E,d=F,l="ready",p=null,c=null,e(`[diarize] ready — ${n} @ ${z()} (speakers split at cosine ${A()})`),!0}catch(o){return p=o.message,c=null,l="error",e(`[diarize] load failed (${o.message}) — diarization off`),!1}}function le(e={}){if(u&&l!=="error")return u;l="loading";const t=typeof e.onLog=="function"?e.onLog:()=>{};return a=M({warmMs:e.warmMs,busy:h,log:t,unload:()=>y({log:t})}),u=S($({log:t,allowDownload:e.allowDownload!==!1})),u}function S(e){return e.then(t=>(t&&!h()&&a?.arm(),t))}async function ae(e,{log:t=()=>{}}={}){return W(e)?e===f?!0:h()?!1:(await y({log:()=>{}}),f=e,t(`[diarize] speaker model set to ${e} (loads on the next diarizing session)`),!0):!1}function ie({onLog:e}={}){return u=null,l="loading",a??=M({warmMs:void 0,busy:h,log:e||(()=>{}),unload:()=>y({log:e||(()=>{})})}),u=S($({log:e,allowDownload:!0})),u}const T=16e3;function x(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 v(e){try{const t=await g(e),r=await d(t),n=r.embeddings??r.logits??r.last_hidden_state;return n?.data?Float32Array.from(n.data):null}catch{return null}}async function se(e){if(!D()||!(e instanceof Float32Array)||!e.length)return null;_++;try{return await j(e)}finally{_--,h()||a?.arm()}}async function j(e){const t=2*T,r=Math.round(1.3*T);if(e.length<=Math.round(t*1.4)){const o=await v(e);return o?x(o):null}const n=[];for(let o=0;o+t<=e.length;o+=r){const s=await v(e.subarray(o,o+t));s&&n.push(x(s))}if(!n.length){const o=await v(e);return o?x(o):null}const i=new Float32Array(n[0].length);for(const o of n)for(let s=0;s<i.length;s++)i[s]+=o[s];return x(i)}function ue(){a?.disarm(),a=null,w=0,_=0,l="off",f=b,d=null,g=null,p=null,u=null,c=null}function ce(e,t,{warmMs:r=null}={}){d=e,g=t,l=e?"ready":"off",r!==null&&(a=M({warmMs:r,busy:h,unload:()=>y()}),e&&a.arm())}class fe{constructor({threshold:t=A(),maxSpeakers:r=12}={}){this.threshold=t,this.maxSpeakers=r,this._voices=H({threshold:t,maxSpeakers:r})}assign(t,r){return this._voices.assign(t,r)}get centroids(){return this._voices.toJSON().centroids}}export{V as DIARIZE_MODEL,fe as Diarizer,ue as _reset,ce as _setForTest,X as activeModel,A as activeThreshold,ie as download,se as embed,te as health,le as init,D as isReady,Z as modelOnDisk,ee as progress,oe as release,re as retain,ae as setModel,Y as state,y as unload,ne as warmPending};
@@ -0,0 +1 @@
1
+ import G from"node:os";import y from"node:path";import{statSync as N,lstatSync as D,readFileSync as F,unlinkSync as I,symlinkSync as B}from"node:fs";import{spawnSync as V}from"node:child_process";import{isCompiledBinary as K,hostFacts as M}from"@chatpanel/events/runtime-host.js";import{compareVersions as A,realPath as j,commandDir as O}from"./service.js";const d="chatpanel-gateway",H="@chatpanel/gateway",$={npm:"the npm package",binary:"the standalone binary",checkout:"a source checkout"},R=t=>{try{return N(t).isFile()}catch{return!1}},h=(t,o)=>{const n=String(t||"").trim().replace(/[\\/]+$/,"");return o==="win32"?n.toLowerCase():n};function U({platform:t=process.platform,home:o=G.homedir(),env:n=process.env}={}){return t==="win32"?y.win32.join(n.LOCALAPPDATA||y.win32.join(o,"AppData","Local"),"ChatPanel",`${d}.exe`):y.posix.join(o,".local","bin",d)}function z(t,{run:o=V,env:n=process.env}={}){try{const s=o(t,["--version"],{encoding:"utf8",timeout:15e3,killSignal:"SIGKILL",windowsHide:!0,stdio:["ignore","pipe","ignore"],env:{...n,CHATPANEL_SELF_UPDATE:"off",CHATPANEL_RUNTIME_AUTO:"off"}}),r=/(\d+\.\d+\.\d+)/.exec(String(s?.stdout||""));return r?r[1]:""}catch{return""}}function g(t,o,n){try{const s=JSON.parse(o(n.join(t,"package.json")));return s?.name===H&&s.version?String(s.version):""}catch{return""}}function Z({pathEnv:t=process.env.PATH||"",platform:o=process.platform,isFile:n=R,real:s=j,read:r=i=>F(i,"utf8"),versionOf:p=z}={}){const i=o==="win32"?y.win32:y.posix,c=o==="win32",l=c?[`${d}.cmd`,`${d}.exe`]:[d],e=[],a=new Set;for(const u of String(t).split(c?";":":")){const f=h(u,o);if(!f)continue;const w=l.map(m=>i.join(f,m)).find(m=>n(m));if(!w)continue;let v=s(w),x="binary",k="",C="";const L=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(v),T=c?/\.cmd$/i.test(w)?[i.join(f,"node_modules","@chatpanel","gateway")].find(m=>g(m,r,i)):"":L&&g(L[1],r,i)?L[1]:"";if(T){x="npm",k=g(T,r,i),v=i.join(T,"bin",`${d}.js`);const m=i.join(f,c?"npm.cmd":"npm");C=`${n(m)?m:"npm"} rm -g ${H}`}else/[/\\]bin[/\\]chatpanel-gateway\.js$/.test(v)&&g(i.dirname(i.dirname(v)),r,i)?(x="checkout",k=g(i.dirname(i.dirname(v)),r,i)):(k=p(v),C=c?`del "${w}"`:`rm "${w}"`);const b=h(v,o);a.has(b)||(a.add(b),e.push({path:w,dir:f,target:v,kind:x,version:k,first:e.length===0,remove:C}))}return e}function P({execPath:t=process.execPath,argv1:o=process.argv[1]||"",real:n=j,compiled:s=K(M())}={}){return n(s?t:y.resolve(o))}const S=(t,o=P(),n=process.platform)=>!!o&&h(t.target,n)===h(o,n);function E(t,o){let n=null;for(const s of t||[])!s.version||A(s.version,o)<=0||(!n||A(s.version,n.version)>0)&&(n=s);return n}const _=(t,o)=>(t||[]).filter(n=>n.version&&A(n.version,o)<0);function nn({copies:t=[],version:o="",command:n=(()=>{const e=O();return e?y.join(e,d):""})(),standalone:s=U(),platform:r=process.platform,self:p=P(),lstat:i=D,unlink:c=I,symlink:l=B}={}){const e=_(t,o).find(a=>a.kind==="binary"&&h(a.path,r)===h(s,r)&&!S(a,p,r));if(!e)return null;if(r==="win32"||!n||h(n,r)===h(s,r))return{remove:e.remove,was:e.version,path:e.path};try{return i(s).isFile()?(c(s),l(n,s),{linked:s,to:n,was:e.version}):{remove:e.remove,was:e.version,path:e.path}}catch(a){return{remove:e.remove,was:e.version,path:e.path,error:a?.message||String(a)}}}function tn(t,o){return`ChatPanel Privacy Gateway: this copy is v${o}, but v${t.version} is installed at ${t.path} (${$[t.kind]}) — handing --install to the newer one.`}function en({copies:t=[],version:o="",retired:n=null,self:s=P(),platform:r=process.platform,force:p=!1}={}){const i=[];n?.linked&&i.push(` ✓ ${n.linked} (v${n.was}, the standalone binary) is now a link to this v${o} — \`chatpanel-gateway\` means this copy from every PATH entry.`);const c=n?.linked?h(n.linked,r):"";for(const e of _(t,o)){if(S(e,s,r)||h(e.path,r)===c)continue;const a=e.first?" — and it is first on your PATH, so typing `chatpanel-gateway` runs THAT copy":"";i.push(` ⚠ An older ChatPanel Gateway is still installed: ${e.path} (v${e.version}, ${$[e.kind]}). It is not the one that runs now${a}.`),e.remove&&i.push(` Remove it: ${e.remove}`),n?.error&&h(e.path,r)===h(n.path,r)&&i.push(` (could not replace it with a link: ${n.error})`)}const l=E(t,o);return l&&p&&i.push(` ⚠ A newer ChatPanel Gateway is installed at ${l.path} (v${l.version}, ${$[l.kind]}); this v${o} runs because of --force. \`${l.path} --install\` makes the newer one the service.`),i}function on({copies:t=[],version:o="",running:n=null,self:s=P(),platform:r=process.platform}={}){const p=[],i=n?.ok?String(n.version||""):"",c=t.find(a=>a.first),l=new Set(t.map(a=>a.version||"?"));if(t.length>1||c&&i&&c.version&&c.version!==i){p.push(`installs: ${t.length} ${t.length===1?"copy":"copies"} of chatpanel-gateway on PATH${l.size>1?", not the same version":""}`);const a=Math.max(...t.map(u=>u.path.length));for(const u of t){const f=[u.first?"first on PATH — what `chatpanel-gateway` runs":"",S(u,s,r)?"this command":""].filter(Boolean);p.push(` ${u.path.padEnd(a)} ${u.version?`v${u.version}`:"version unknown"} ${$[u.kind]}${f.length?` ← ${f.join("; ")}`:""}`)}c&&i&&c.version&&c.version!==i&&p.push(` ✕ \`chatpanel-gateway\` on your PATH is v${c.version} (${c.path}), but the gateway running is v${i} — the command you type is not the copy that runs.`)}const e=E(t,o);if(e&&!S(e,s,r)){const a=i&&A(e.version,i)>0?` and than the running v${i}`:"";p.push(` ✕ v${e.version} at ${e.path} (${$[e.kind]}) is newer than this command (v${o})${a} — \`${e.path} --install\` makes it the one that runs.`)}return p}export{$ as KIND_LABEL,z as binaryVersion,Z as gatewayCommands,tn as handoffLine,en as installCopyLines,S as isSelf,E as newerCopy,_ as olderCopies,nn as retireStandaloneGateway,P as selfTarget,U as standaloneGatewayPath,on as statusCopyLines};
package/src/ner-engine.js CHANGED
@@ -1 +1 @@
1
- import q from"node:os";import{join as O}from"node:path";import{existsSync as Q,mkdirSync as ct,readdirSync as K,readFileSync as ut}from"node:fs";import{DEFAULT_MODEL as V,isMirroredModel as ft}from"./models.js";import{isLoopbackHost as pt,isPrivateHost as dt,isMetadataHost as ht}from"@chatpanel/pii";import{recaseForDetection as mt}from"@chatpanel/pii/pii-detect.js";import{recasedSpanOk as gt}from"@chatpanel/pii/recased-spans.js";import{verifyModelWeights as yt}from"./model-integrity.js";import{runtimeName as wt}from"./model-runtime.js";import{nativeOrtFailure as _t}from"./ort.js";import{makeWarmTimer as X}from"./warm-timer.js";import{makeModelFileCache as xt}from"./model-file-cache.js";const C="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 C;const n=c=>(console.warn(`[models] ignoring ${e} (${r}): ${c} — using ${C}`),C);let o;try{o=new URL(r)}catch{return n("not a valid URL")}if(o.protocol!=="http:"&&o.protocol!=="https:")return n(`scheme ${o.protocol} not allowed`);if(ht(o.hostname))return n("points at cloud metadata");const s=pt(o.hostname)||dt(o.hostname);return o.protocol==="http:"&&!s?n("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${o.origin} (${e}), not ${C}`),r.replace(/\/*$/,"/"))}const bt=Mt();let h="off",y=null,w=null,b=null,T=null,E=null,L=null,m=null,x=null,P=0,N=null;const g=new Map;function H(){return process.env.CHATPANEL_MODELS_DIR||O(q.homedir(),".chatpanel","models")}function R(t=y||V){const e=O(H(),...t.split("/"));return Q(O(e,"onnx","model_quantized.onnx"))||Q(O(e,"onnx","model.onnx"))}function Zt(){const t=H(),e=[];try{for(const r of K(t,{withFileTypes:!0}))if(r.isDirectory())for(const n of K(O(t,r.name),{withFileTypes:!0})){if(!n.isDirectory())continue;const o=`${r.name}/${n.name}`;R(o)&&Lt(O(t,r.name,n.name))&&e.push(o)}}catch{}return e}function Lt(t){try{return(JSON.parse(ut(O(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function It(){return h}function A(){return h==="ready"&&!!w}function te(){return{configured:h!=="off",ok:A(),state:h,model:y,error:b,runtime:wt(),dtype:w?"q8":null,stats:Pt(),companions:$t(),warmMs:x?.warmMs??null}}async function Tt(t,{signal:e,strict:r=!1}={}){if(!A())return[];if(e?.aborted)return[];const n=String(t||""),o=await Z(n,e);if(!o)return[];const s=[];for(const f of o||[]){if(I(f,r))continue;let i=String(f.word??"");const u=f.entity_group??f.entity??"ENTITY";if(i.startsWith("##")&&s.length&&s[s.length-1].type===u){s[s.length-1].value+=i.slice(2);continue}i=i.replace(/##/g,"").trim(),i&&s.push({value:i,type:u})}const c=new Set,l=[];for(const f of s){const i=Rt(n,Ht(n,f.value.trim()));if(i.length<=1)continue;const u=`${f.type}:${i.toLowerCase()}`;c.has(u)||(c.add(u),l.push({value:i,type:f.type}))}return l}async function Z(t,e){P++;try{return await St(t,e)}finally{P--,v()||x?.arm()}}async function St(t,e){const r=performance.now(),n=[],o=[{text:t,key:"orig"}];if(D){const s=mt(t);s.changed&&o.push({text:s.text,key:"recased"})}for(const{model:s,pipe:c}of nt())for(const l of o){let f=0;for(const i of Et(l.text,c.tokenizer)){if(e?.aborted)return null;const u=l.text.indexOf(i,f),d=await c(i,{aggregation_strategy:"simple"});for(const a of d||[])n.push({...a,_win:u<0?f:u,_winText:i,_model:s,_pass:l.key,_passText:l.text});u>=0&&(f=Math.max(f,u+1))}}return Ct(performance.now()-r,t.length,n.length),n}let D=!0;function ee(t){D=t!==!1}const I=(t,e)=>!e&&t._pass==="recased"&&!gt(String(t.word??"").replace(/##/g,""),t.entity_group??t.entity);async function ne(t,{signal:e,strict:r=!1}={}){if(!A())return[];const n=String(t||""),o=await Z(n,e);if(!o)return[];const s=[],c=new Set;let l=-1,f=-1,i=null,u=null;for(const a of o){if(I(a,r))continue;const p=String(a.word??"").replace(/##/g,"").trim();if(!p)continue;(a._win!==f||a._model!==i||a._pass!==u)&&(f=a._win,i=a._model,u=a._pass,l=a._win);const k=a._passText||n;let M=k.indexOf(p,l);if(M<0&&(M=k.indexOf(p,a._win)),M<0)continue;let S=M+p.length;l=S;const z=G=>!!G&&/[\p{L}\p{N}'’-]/u.test(G);for(;M>0&&z(n[M-1]);)M--;for(;S<n.length&&z(n[S]);)S++;const Y=String(a.entity_group??a.entity??"ENTITY"),B=`${M}:${S}:${Y}`;if(c.has(B))continue;c.add(B);const J=Number(a.score);s.push({value:n.slice(M,S),type:Y,start:M,end:S,score:Number.isFinite(J)?Math.max(0,Math.min(1,J)):1,model:a._model})}s.sort((a,p)=>a.start-p.start||a.end-p.end);const d=[];for(const a of s){const p=d[d.length-1];if(p&&p.type===a.type&&p.end===a.start){p.end=a.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,a.score);continue}d.push({...a})}return g.size||D?kt(d):d}const tt=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function Ot(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 F(t){const e=tt.indexOf(Ot(t.type));return e<0?tt.length:e}let $=[];function At(t){$=Array.isArray(t)?t.slice():[],m&&(m={...m,union:$.slice()})}function W(t){if(t.model===y)return-1;const e=$.indexOf(t.model);return e<0?$.length:e}function kt(t){const e=[...t].sort((n,o)=>n.start-o.start||o.end-n.end),r=[];for(const n of e){const o=r[r.length-1];if(o&&n.start<o.end){const s=l=>l.end-l.start;(F(n)<F(o)||F(n)===F(o)&&(s(n)>s(o)||s(n)===s(o)&&(W(n)<W(o)||W(n)===W(o)&&n.score>o.score)))&&(r[r.length-1]=n);continue}r.push(n)}return r}function oe(){const t=w?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const n=String(r).replace(/^[BIES]-/,"");n&&n!=="O"&&e.add(n)}return[...e]}function re(){const t=Number(w?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function $t(){return[...g].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function et(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===y)return!1;if(g.get(t)?.pipe)return!0;g.set(t,{pipe:null,state:R(t)?"loading":"downloading",error:null});try{const{pipe:o}=await st(t,{log:e,allowDownload:r});return g.set(t,{pipe:o,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(o){return g.set(t,{pipe:null,state:"error",error:o.message}),e(`[ner] companion ${t} failed to load (${o.message}) — the union runs without it`),!1}}async function se(t){const e=g.get(t);if(!e)return!1;g.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function nt(){const t=w?[{model:y,pipe:w}]:[];for(const[e,r]of g)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const vt=160,ot=256;function Et(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),o=Math.min(ot,Number.isFinite(r)&&r>0?r:ot)-8,s=i=>{try{return e(i).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=o)return[t];const c=[];let l=0,f=Math.max(64,Math.floor(o*3));for(;l<t.length;){let i=Math.min(t.length,l+f);if(i<t.length){const p=t.lastIndexOf(" ",i);p>l+f/2&&(i=p)}let u=t.slice(l,i);for(;s(u)>o&&u.length>32;){f=Math.max(32,Math.floor(u.length/2)),i=l+f;const p=t.lastIndexOf(" ",i);p>l+f/2&&(i=p),u=t.slice(l,i)}if(c.push(u),i>=t.length)break;const d=Math.max(l+1,i-vt),a=t.indexOf(" ",d);l=a>0&&a<i?a+1:i}return c}const Nt=200,_=[];function Ct(t,e,r){_.push({ms:t,chars:e,spans:r}),_.length>Nt&&_.shift()}function Pt(){if(!_.length)return{calls:0};const t=_.map(o=>o.ms).sort((o,s)=>o-s),e=o=>t[Math.min(t.length-1,Math.floor(o*t.length))],r=_.reduce((o,s)=>o+s.chars,0),n=_.reduce((o,s)=>o+s.ms,0);return{calls:_.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(_[_.length-1].ms),charsPerSec:n>0?Math.round(r/(n/1e3)):null}}function Ht(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 Rt(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const n=c=>!!c&&/[\p{L}\p{N}'’-]/u.test(c);let o=r,s=r+e.length;for(;o>0&&n(t[o-1]);)o--;for(;s<t.length&&n(t[s]);)s++;return t.slice(o,s)}async function ie(t,e={}){let r="",n=!1;try{const s=JSON.parse(e.body||"{}");r=s.text||"",n=s.strict===!0}catch{}const o=await Tt(r,{signal:e.signal,strict:n});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function ae(){return L}async function rt(){if(E)return E;const t=H();try{ct(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(_t(a))}const{env:n,pipeline:o,Tensor:s,AutoModel:c,AutoProcessor:l,AutoTokenizer:f,AutoModelForSequenceClassification:i,LogLevel:u}=r;if(n.cacheDir=t,e&&u)try{n.logLevel=u.ERROR}catch{}n.localModelPath=t,e||(n.useCustomCache=!0,n.customCache=xt(t,{remoteHost:()=>n.remoteHost}));try{n.remoteHost=bt}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(e)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=e}catch{}return E={env:n,pipeline:(a,p,k={})=>o(a,p,k.progress_callback&&n.allowRemoteModels===!1?{...k,progress_callback:void 0}:k),Tensor:s,AutoModel:c,AutoProcessor:l,AutoTokenizer:f,AutoModelForSequenceClassification:i},E}function Dt({cores:t=q.availableParallelism?.()??q.cpus().length,wasm:e=!!globalThis.__CHATPANEL_WASM_PATHS__,env:r=process.env}={}){const n=Number(r.CHATPANEL_NER_THREADS);return{intraOpNumThreads:e?1:Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(8,t-1)),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}async function st(t,{log:e=()=>{},allowDownload:r=!0,onProgress:n=()=>{}}={}){const o=await rt(),s=R(t);if(o.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const c=o.env.remoteHost,l=!ft(t);if(!s&&l)try{o.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${l?", from Hugging Face":""})…`);try{const i={dtype:"q8",progress_callback:d=>{d&&(d.status==="progress"||d.status==="download"||d.status==="initiate"?n(d):d.status==="done"&&d.file&&e(`[ner] fetched ${d.file}`))},session_options:Dt()};let u;try{u=await o.pipeline("token-classification",t,i)}catch(d){if(s||l||!r)throw d;e(`[ner] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),o.env.remoteHost="https://huggingface.co/",o.env.allowRemoteModels=!0,u=await o.pipeline("token-classification",t,i)}if(!s)try{yt(t,{modelsDir:H(),log:e})}catch(d){try{await u.dispose?.()}catch{}throw d}return{pipe:u,haveLocal:s}}finally{try{o.env.remoteHost=c}catch{}}}async function it(t,{log:e=()=>{},allowDownload:r=!0}={}){const n=w,o=y;try{await rt()}catch(c){return h="error",b=`engine load failed: ${c.message}`,e(`[ner] transformers.js not available (${c.message}) — deterministic-only`),!1}const s=R(t);if(!s&&!r)return h="error",b="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;h=s?"loading":"downloading",s||(L={model:t,file:null,pct:0});try{const{pipe:c}=await st(t,{log:e,allowDownload:r,onProgress:l=>{L={model:t,file:l.file||L?.file||null,pct:typeof l.progress=="number"?Math.round(l.progress):L?.pct??0}}});if(w=c,y=t,h="ready",b=null,L=null,m&&(m={...m,model:t}),n&&n!==c)try{await n.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),v()||x?.arm(),!0}catch(c){return b=c.message,L=null,n?(w=n,y=o,h="ready"):h="error",e(`[ner] model load failed (${c.message})${n?" — keeping previous model":" — deterministic-only"}`),!1}}function Ft(t={}){if(T)return T;const e=typeof t.onLog=="function"?t.onLog:()=>{};m=t,y=t.model||V,h="loading";const r=t.allowDownload!==!1;return x=X({warmMs:t.warmMs,busy:v,log:e,unload:()=>at({log:e})}),T=it(y,{log:e,allowDownload:r}).then(async n=>{const o=Array.isArray(t.union)?t.union:[];At(o);for(const s of o)await et(s,{log:e,allowDownload:r});return A()&&!v()&&x?.arm(),n}),T}function v(){if(P>0||h==="loading"||h==="downloading")return!0;for(const t of g.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function at({log:t=()=>{}}={}){if(v())return!1;x?.disarm();const e=nt().map(r=>r.pipe);w=null,T=null,L=null,b=null,g.clear(),h=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((x?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function Wt(){try{h==="idle"&&(N||m)?await(N?N():Ft(m)):T&&await T,A()&&await lt()}catch{}return A()}let U=null;function lt(){const t=$.filter(e=>e&&e!==y&&!g.has(e));return t.length?(U||=(async()=>{const e=typeof m?.onLog=="function"?m.onLog:()=>{};for(const r of t)g.has(r)||(j?await j(r):await et(r,{log:e,allowDownload:m?.allowDownload!==!1}))})().catch(()=>{}).finally(()=>{U=null}),U):Promise.resolve()}let j=null;function le(t){j=t}async function ce(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},n=e.allowDownload!==!1;if(!t)return!1;if(t===y&&A())return!0;if(t===y&&h==="idle")return Wt();const o=g.get(t);if(o?.pipe){const c=w;if(w=o.pipe,y=t,h="ready",b=null,g.delete(t),c)try{await c.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),m&&(m={...m,model:t}),!0}const s=await it(t,{log:r,allowDownload:n});return s&&(m&&(m={...m,model:t}),await lt()),s}function ue(){h="off",y=null,w=null,b=null,T=null,E=null,L=null,_.length=0,g.clear(),D=!0,$=[],x?.disarm(),x=null,m=null,P=0,N=null,j=null,U=null}function fe(t,e){g.set(t,{pipe:e,state:"ready",error:null})}function pe(t,{model:e="test/model",warmMs:r=null,reload:n=null}={}){w=t,y=e,h="ready",b=null,_.length=0,n&&(N=n),r!==null&&(x=X({warmMs:r,busy:v,unload:()=>at()}),t&&x.arm())}export{ue as _reset,fe as _setCompanionForTest,le as _setCompanionLoaderForTest,pe as _setForTest,et as addCompanion,$t as companions,Tt as detect,ne as detectSpans,Wt as ensure,rt as ensureLib,ie as fetchAdapter,te as health,Ft as init,A as isReady,oe as labels,re as maxTokens,R as modelOnDisk,H as modelRoot,Zt as modelsOnDisk,ae as progress,se as removeCompanion,Mt as resolveModelHost,Dt as sessionOptionsFor,ee as setCaseRecovery,ce as setModel,At as setUnionOrder,It as state,Pt as stats,kt as unionSpans,at as unload,Et as windowsFor};
1
+ import q from"node:os";import{join as S}from"node:path";import{existsSync as K,mkdirSync as ut,readdirSync as V,readFileSync as ft}from"node:fs";import{DEFAULT_MODEL as X,isMirroredModel as pt}from"./models.js";import{isLoopbackHost as dt,isPrivateHost as mt,isMetadataHost as ht}from"@chatpanel/pii";import{recaseForDetection as gt}from"@chatpanel/pii/pii-detect.js";import{recasedSpanOk as yt}from"@chatpanel/pii/recased-spans.js";import{verifyModelWeights as wt}from"./model-integrity.js";import{runtimeName as _t}from"./model-runtime.js";import{nativeOrtFailure as Mt}from"./ort.js";import{makeWarmTimer as Z}from"./warm-timer.js";import{makeModelFileCache as xt}from"./model-file-cache.js";const H="https://dl.chatpanel.net/models/";function bt(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 H;const n=a=>(console.warn(`[models] ignoring ${e} (${r}): ${a} — using ${H}`),H);let o;try{o=new URL(r)}catch{return n("not a valid URL")}if(o.protocol!=="http:"&&o.protocol!=="https:")return n(`scheme ${o.protocol} not allowed`);if(ht(o.hostname))return n("points at cloud metadata");const s=dt(o.hostname)||mt(o.hostname);return o.protocol==="http:"&&!s?n("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${o.origin} (${e}), not ${H}`),r.replace(/\/*$/,"/"))}const Lt=bt();let m="off",y=null,w=null,b=null,T=null,C=null,L=null,h=null,M=null,N=0,E=null;const g=new Map;let I=Promise.resolve();function It({host:t=null,allowRemote:e=!1}={},r){const n=I.then(async()=>{const o=await z(),s=o.env.remoteHost,a=o.env.allowRemoteModels;try{o.env.allowRemoteModels=e,t&&(o.env.remoteHost=t)}catch{}try{return await r(o)}finally{try{o.env.remoteHost=s,o.env.allowRemoteModels=a}catch{}}});return I=n.catch(()=>{}),n}function P(){return process.env.CHATPANEL_MODELS_DIR||S(q.homedir(),".chatpanel","models")}function R(t=y||X){const e=S(P(),...t.split("/"));return K(S(e,"onnx","model_quantized.onnx"))||K(S(e,"onnx","model.onnx"))}function te(){const t=P(),e=[];try{for(const r of V(t,{withFileTypes:!0}))if(r.isDirectory())for(const n of V(S(t,r.name),{withFileTypes:!0})){if(!n.isDirectory())continue;const o=`${r.name}/${n.name}`;R(o)&&Tt(S(t,r.name,n.name))&&e.push(o)}}catch{}return e}function Tt(t){try{return(JSON.parse(ft(S(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function ee(){return m}function O(){return m==="ready"&&!!w}function ne(){return{configured:m!=="off",ok:O(),state:m,model:y,error:b,runtime:_t(),dtype:w?"q8":null,stats:Pt(),companions:$t(),warmMs:M?.warmMs??null}}async function At(t,{signal:e,strict:r=!1}={}){if(!O())return[];if(e?.aborted)return[];const n=String(t||""),o=await tt(n,e);if(!o)return[];const s=[];for(const f of o||[]){if(et(f,r))continue;let i=String(f.word??"");const u=f.entity_group??f.entity??"ENTITY";if(i.startsWith("##")&&s.length&&s[s.length-1].type===u){s[s.length-1].value+=i.slice(2);continue}i=i.replace(/##/g,"").trim(),i&&s.push({value:i,type:u})}const a=new Set,c=[];for(const f of s){const i=Ft(n,Rt(n,f.value.trim()));if(i.length<=1)continue;const u=`${f.type}:${i.toLowerCase()}`;a.has(u)||(a.add(u),c.push({value:i,type:f.type}))}return c}async function tt(t,e){N++;try{return await St(t,e)}finally{N--,$()||M?.arm()}}async function St(t,e){const r=performance.now(),n=[],o=[{text:t,key:"orig"}];if(F){const s=gt(t);s.changed&&o.push({text:s.text,key:"recased"})}for(const{model:s,pipe:a}of rt())for(const c of o){let f=0;for(const i of Et(c.text,a.tokenizer)){if(e?.aborted)return null;const u=c.text.indexOf(i,f),d=await a(i,{aggregation_strategy:"simple"});for(const l of d||[])n.push({...l,_win:u<0?f:u,_winText:i,_model:s,_pass:c.key,_passText:c.text});u>=0&&(f=Math.max(f,u+1))}}return Nt(performance.now()-r,t.length,n.length),n}let F=!0;function oe(t){F=t!==!1}const et=(t,e)=>!e&&t._pass==="recased"&&!yt(String(t.word??"").replace(/##/g,""),t.entity_group??t.entity);async function re(t,{signal:e,strict:r=!1}={}){if(!O())return[];const n=String(t||""),o=await tt(n,e);if(!o)return[];const s=[],a=new Set;let c=-1,f=-1,i=null,u=null;for(const l of o){if(et(l,r))continue;const p=String(l.word??"").replace(/##/g,"").trim();if(!p)continue;(l._win!==f||l._model!==i||l._pass!==u)&&(f=l._win,i=l._model,u=l._pass,c=l._win);const v=l._passText||n;let x=v.indexOf(p,c);if(x<0&&(x=v.indexOf(p,l._win)),x<0)continue;let A=x+p.length;c=A;const Y=Q=>!!Q&&/[\p{L}\p{N}'’-]/u.test(Q);for(;x>0&&Y(n[x-1]);)x--;for(;A<n.length&&Y(n[A]);)A++;const B=String(l.entity_group??l.entity??"ENTITY"),J=`${x}:${A}:${B}`;if(a.has(J))continue;a.add(J);const G=Number(l.score);s.push({value:n.slice(x,A),type:B,start:x,end:A,score:Number.isFinite(G)?Math.max(0,Math.min(1,G)):1,model:l._model})}s.sort((l,p)=>l.start-p.start||l.end-p.end);const d=[];for(const l of s){const p=d[d.length-1];if(p&&p.type===l.type&&p.end===l.start){p.end=l.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,l.score);continue}d.push({...l})}return g.size||F?kt(d):d}const nt=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function Ot(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 D(t){const e=nt.indexOf(Ot(t.type));return e<0?nt.length:e}let k=[];function vt(t){k=Array.isArray(t)?t.slice():[],h&&(h={...h,union:k.slice()})}function W(t){if(t.model===y)return-1;const e=k.indexOf(t.model);return e<0?k.length:e}function kt(t){const e=[...t].sort((n,o)=>n.start-o.start||o.end-n.end),r=[];for(const n of e){const o=r[r.length-1];if(o&&n.start<o.end){const s=c=>c.end-c.start;(D(n)<D(o)||D(n)===D(o)&&(s(n)>s(o)||s(n)===s(o)&&(W(n)<W(o)||W(n)===W(o)&&n.score>o.score)))&&(r[r.length-1]=n);continue}r.push(n)}return r}function se(){const t=w?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const n=String(r).replace(/^[BIES]-/,"");n&&n!=="O"&&e.add(n)}return[...e]}function ie(){const t=Number(w?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function $t(){return[...g].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function ot(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===y)return!1;if(g.get(t)?.pipe)return!0;g.set(t,{pipe:null,state:R(t)?"loading":"downloading",error:null});try{const{pipe:o}=await it(t,{log:e,allowDownload:r});return g.set(t,{pipe:o,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(o){return g.set(t,{pipe:null,state:"error",error:o.message}),e(`[ner] companion ${t} failed to load (${o.message}) — the union runs without it`),!1}}async function ae(t){const e=g.get(t);if(!e)return!1;g.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function rt(){const t=w?[{model:y,pipe:w}]:[];for(const[e,r]of g)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const Ct=160,st=256;function Et(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),o=Math.min(st,Number.isFinite(r)&&r>0?r:st)-8,s=i=>{try{return e(i).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=o)return[t];const a=[];let c=0,f=Math.max(64,Math.floor(o*3));for(;c<t.length;){let i=Math.min(t.length,c+f);if(i<t.length){const p=t.lastIndexOf(" ",i);p>c+f/2&&(i=p)}let u=t.slice(c,i);for(;s(u)>o&&u.length>32;){f=Math.max(32,Math.floor(u.length/2)),i=c+f;const p=t.lastIndexOf(" ",i);p>c+f/2&&(i=p),u=t.slice(c,i)}if(a.push(u),i>=t.length)break;const d=Math.max(c+1,i-Ct),l=t.indexOf(" ",d);c=l>0&&l<i?l+1:i}return a}const Ht=200,_=[];function Nt(t,e,r){_.push({ms:t,chars:e,spans:r}),_.length>Ht&&_.shift()}function Pt(){if(!_.length)return{calls:0};const t=_.map(o=>o.ms).sort((o,s)=>o-s),e=o=>t[Math.min(t.length-1,Math.floor(o*t.length))],r=_.reduce((o,s)=>o+s.chars,0),n=_.reduce((o,s)=>o+s.ms,0);return{calls:_.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(_[_.length-1].ms),charsPerSec:n>0?Math.round(r/(n/1e3)):null}}function Rt(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 Ft(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const n=a=>!!a&&/[\p{L}\p{N}'’-]/u.test(a);let o=r,s=r+e.length;for(;o>0&&n(t[o-1]);)o--;for(;s<t.length&&n(t[s]);)s++;return t.slice(o,s)}async function le(t,e={}){let r="",n=!1;try{const s=JSON.parse(e.body||"{}");r=s.text||"",n=s.strict===!0}catch{}const o=await At(r,{signal:e.signal,strict:n});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function ce(){return L}async function z(){if(C)return C;const t=P();try{ut(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(l){throw e?l:new Error(Mt(l))}const{env:n,pipeline:o,Tensor:s,AutoModel:a,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:i,LogLevel:u}=r;if(n.cacheDir=t,e&&u)try{n.logLevel=u.ERROR}catch{}n.localModelPath=t,e||(n.useCustomCache=!0,n.customCache=xt(t,{remoteHost:()=>n.remoteHost}));try{n.remoteHost=Lt}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(e)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=e}catch{}return C={env:n,pipeline:(l,p,v={})=>o(l,p,v.progress_callback&&n.allowRemoteModels===!1?{...v,progress_callback:void 0}:v),Tensor:s,AutoModel:a,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:i,AutoModelForAudioFrameClassification:r.AutoModelForAudioFrameClassification},C}function Dt({cores:t=q.availableParallelism?.()??q.cpus().length,wasm:e=!!globalThis.__CHATPANEL_WASM_PATHS__,env:r=process.env}={}){const n=Number(r.CHATPANEL_NER_THREADS);return{intraOpNumThreads:e?1:Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(8,t-1)),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}async function it(t,{log:e=()=>{},allowDownload:r=!0,onProgress:n=()=>{}}={}){const o=await z(),s=R(t);if(o.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const a=o.env.remoteHost,c=!pt(t);if(!s&&c)try{o.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${c?", from Hugging Face":""})…`);try{const i={dtype:"q8",progress_callback:d=>{d&&(d.status==="progress"||d.status==="download"||d.status==="initiate"?n(d):d.status==="done"&&d.file&&e(`[ner] fetched ${d.file}`))},session_options:Dt()};let u;try{u=await o.pipeline("token-classification",t,i)}catch(d){if(s||c||!r)throw d;e(`[ner] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),o.env.remoteHost="https://huggingface.co/",o.env.allowRemoteModels=!0,u=await o.pipeline("token-classification",t,i)}if(!s)try{wt(t,{modelsDir:P(),log:e})}catch(d){try{await u.dispose?.()}catch{}throw d}return{pipe:u,haveLocal:s}}finally{try{o.env.remoteHost=a}catch{}}}async function at(t,{log:e=()=>{},allowDownload:r=!0}={}){const n=w,o=y;try{await z()}catch(a){return m="error",b=`engine load failed: ${a.message}`,e(`[ner] transformers.js not available (${a.message}) — deterministic-only`),!1}const s=R(t);if(!s&&!r)return m="error",b="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;m=s?"loading":"downloading",s||(L={model:t,file:null,pct:0});try{const{pipe:a}=await it(t,{log:e,allowDownload:r,onProgress:c=>{L={model:t,file:c.file||L?.file||null,pct:typeof c.progress=="number"?Math.round(c.progress):L?.pct??0}}});if(w=a,y=t,m="ready",b=null,L=null,h&&(h={...h,model:t}),n&&n!==a)try{await n.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),$()||M?.arm(),!0}catch(a){return b=a.message,L=null,n?(w=n,y=o,m="ready"):m="error",e(`[ner] model load failed (${a.message})${n?" — keeping previous model":" — deterministic-only"}`),!1}}function Wt(t={}){if(T)return T;const e=typeof t.onLog=="function"?t.onLog:()=>{};h=t,y=t.model||X,m="loading";const r=t.allowDownload!==!1;return M=Z({warmMs:t.warmMs,busy:$,log:e,unload:()=>lt({log:e})}),T=at(y,{log:e,allowDownload:r}).then(async n=>{const o=Array.isArray(t.union)?t.union:[];vt(o);for(const s of o)await ot(s,{log:e,allowDownload:r});return O()&&!$()&&M?.arm(),n}),T}function $(){if(N>0||m==="loading"||m==="downloading")return!0;for(const t of g.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function lt({log:t=()=>{}}={}){if($())return!1;M?.disarm();const e=rt().map(r=>r.pipe);w=null,T=null,L=null,b=null,g.clear(),m=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((M?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function Ut(){try{m==="idle"&&(E||h)?await(E?E():Wt(h)):T&&await T,O()&&await ct()}catch{}return O()}let U=null;function ct(){const t=k.filter(e=>e&&e!==y&&!g.has(e));return t.length?(U||=(async()=>{const e=typeof h?.onLog=="function"?h.onLog:()=>{};for(const r of t)g.has(r)||(j?await j(r):await ot(r,{log:e,allowDownload:h?.allowDownload!==!1}))})().catch(()=>{}).finally(()=>{U=null}),U):Promise.resolve()}let j=null;function ue(t){j=t}async function fe(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},n=e.allowDownload!==!1;if(!t)return!1;if(t===y&&O())return!0;if(t===y&&m==="idle")return Ut();const o=g.get(t);if(o?.pipe){const a=w;if(w=o.pipe,y=t,m="ready",b=null,g.delete(t),a)try{await a.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),h&&(h={...h,model:t}),!0}const s=await at(t,{log:r,allowDownload:n});return s&&(h&&(h={...h,model:t}),await ct()),s}function pe(){m="off",y=null,w=null,b=null,T=null,C=null,L=null,_.length=0,g.clear(),F=!0,k=[],M?.disarm(),M=null,h=null,N=0,E=null,j=null,U=null}function de(t,e){g.set(t,{pipe:e,state:"ready",error:null})}function me(t,{model:e="test/model",warmMs:r=null,reload:n=null}={}){w=t,y=e,m="ready",b=null,_.length=0,n&&(E=n),r!==null&&(M=Z({warmMs:r,busy:$,unload:()=>lt()}),t&&M.arm())}export{pe as _reset,de as _setCompanionForTest,ue as _setCompanionLoaderForTest,me as _setForTest,ot as addCompanion,$t as companions,At as detect,re as detectSpans,Ut as ensure,z as ensureLib,le as fetchAdapter,ne as health,Wt as init,O as isReady,se as labels,ie as maxTokens,R as modelOnDisk,P as modelRoot,te as modelsOnDisk,ce as progress,ae as removeCompanion,bt as resolveModelHost,Dt as sessionOptionsFor,oe as setCaseRecovery,fe as setModel,vt as setUnionOrder,ee as state,Pt as stats,kt as unionSpans,lt as unload,Et as windowsFor,It as withModelSource};
@@ -0,0 +1 @@
1
+ import{existsSync as $,readdirSync as D}from"node:fs";import{join as S}from"node:path";import{ensureLib as T,modelRoot as P,withModelSource as R}from"./ner-engine.js";import{runtimeDtype as x}from"./model-runtime.js";import{makeWarmTimer as M}from"./warm-timer.js";const A="onnx-community/pyannote-segmentation-3.0",N=6,O=16e3;let r="off",g=A,u=null,d=null,a=null,m=null,s=null,o=null,_=0,p=0,w=null;function B(){return g}function U(){return r}function h(){return r==="ready"&&!!u&&!!d}function W(){return s}function X(){return{configured:r!=="off",ok:h(),state:r,model:g,loaded:!!u,error:a,warmMs:o?.warmMs??null}}function y(){return _>0||p>0||r==="loading"||r==="downloading"}function H(){p++,o?.disarm()}function J(){p=Math.max(0,p-1),p===0&&_===0&&h()&&o?.arm()}async function b({log:e=()=>{}}={}){if(y())return!1;o?.disarm();const n=u;if(u=null,d=null,w=null,m=null,s=null,a=null,r="off",n){try{await n.dispose?.()}catch{}e("[segment] idle — model unloaded (reloads on the next diarizing session)")}return!0}function v(e=g,n=x()){const l=S(P(),...e.split("/"),"onnx");if(!$(l))return!1;const t=n==="fp32"?"":n==="q8"?"_quantized":`_${n}`;try{return D(l).some(f=>f===`model${t}.onnx`)}catch{return!1}}async function z({log:e=()=>{},allowDownload:n=!0}={}){let l;try{l=await T()}catch(i){return r="error",a=i.message,e(`[segment] engine unavailable (${i.message})`),!1}if(!l.AutoModelForAudioFrameClassification)return r="error",a="this transformers.js has no audio frame classification",e(`[segment] ${a}`),!1;const t=g,f=v(t);if(!f&&!n)return r="error",a="model not on disk and downloads disabled",!1;r=f?"loading":"downloading",f||(s={model:t,file:null,pct:0},e(`[segment] downloading ${t} (one-time)…`));try{const i=c=>{if(!c)return;const L=typeof c.progress=="number"?Math.round(c.progress):s?.pct??0;(c.status==="progress"||c.status==="download"||c.status==="initiate")&&(s={model:t,file:c.file||s?.file||null,pct:L})},{processor:k,model:E}=await R({host:f?null:"https://huggingface.co/",allowRemote:!f},async()=>({processor:await l.AutoProcessor.from_pretrained(t,{progress_callback:i}),model:await l.AutoModelForAudioFrameClassification.from_pretrained(t,{dtype:x(),progress_callback:i})}));return d=k,u=E,r="ready",a=null,s=null,e(`[segment] ready — ${t} @ ${x()} (speaker turns inside a segment)`),!0}catch(i){return a=i.message,s=null,r="error",e(`[segment] load failed (${i.message}) — one speaker per segment, as before`),!1}}function F(e){return e.then(n=>(n&&!y()&&o?.arm(),n))}function K(e={}){if(m&&r!=="error")return m;r="loading";const n=typeof e.onLog=="function"?e.onLog:()=>{};return o=M({warmMs:e.warmMs,busy:y,log:n,unload:()=>b({log:n})}),m=F(z({log:n,allowDownload:e.allowDownload!==!1})),m}async function Q(e){if(!h()||!(e instanceof Float32Array)||e.length<O/2)return null;_++;try{if(w)return await w(e);const n=await d(e),{logits:l}=await u(n),t=d.post_process_speaker_diarization(l,e.length);return Array.isArray(t?.[0])?t[0]:null}catch{return null}finally{_--,y()||o?.arm()}}function V(){o?.disarm(),o=null,p=0,_=0,r="off",g=A,u=null,d=null,a=null,m=null,s=null}function Y(e,{warmMs:n=null}={}){w=e||null,u=e?{dispose:async()=>{}}:null,d=e?{}:null,r=e?"ready":"off",n!==null&&(o=M({warmMs:n,busy:y,unload:()=>b()}),e&&o.arm())}export{A as DEFAULT_SEGMENT_MODEL,O as SAMPLE_RATE,N as SEGMENT_MODEL_APPROX_MB,V as _reset,Y as _setForTest,B as activeModel,X as health,K as init,h as isReady,v as modelOnDisk,W as progress,J as release,H as retain,Q as spans,U as state,b as unload};