@chatpanel/gateway 0.11.13 → 0.17.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.
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- const a=process.argv[2];try{if(a==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(a==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(a==="mcp"){const{runMcpServer:t}=await import("../src/mcp.js");await t()}else if(a==="tools"||a==="call"){const{runMcpCli:t}=await import("../src/mcp-cli.js");process.exit(await t(process.argv.slice(2)))}else if(a==="policy"){const{loadPolicy:t,formatPolicy:o,PolicyLoadError:i}=await import("../src/policy.js");try{const e=await t();process.argv.includes("--json")?console.log(JSON.stringify(e?{...e,label:void 0}:null,null,2)):console.log(o(e))}catch(e){throw e instanceof i&&(console.error(`org policy: ${e.message}`),process.exit(78)),e}}else if(a==="--audit"){const{egressAudit:t,formatAudit:o}=await import("../src/egress.js"),{loadConfig:i}=await import("../src/config.js"),{readFileSync:e}=await import("node:fs"),{join:g}=await import("node:path"),r=await import("node:os"),l=i(),s=`http://127.0.0.1:${l.port||4320}`;let n=null,c=`no gateway running at ${s}`;try{const u=e(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||g(r.homedir(),".chatpanel","gateway-token"),"utf8").trim(),p=await fetch(`${s}/audit`,{headers:{authorization:`Bearer ${u}`},signal:AbortSignal.timeout(2500)});if(p.ok)n=await p.json();else if(p.status===404){const d=await fetch(`${s}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);c=`the gateway running at ${s}${d?.version?` (${d.version})`:""} predates --audit (0.7.0) — restart it after updating`}else c=`the gateway at ${s} refused the audit (HTTP ${p.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!n){const{VERSION:u}=await import("../src/server.js");n={...t(l,{ledger:null,version:u}),observed:[]},console.log(`(${c}; showing what the current config allows)
3
- `)}process.argv.includes("--json")?console.log(JSON.stringify(n,null,2)):console.log(o(n))}else if(a==="pair"){const{loadConfig:t}=await import("../src/config.js"),{readFileSync:o}=await import("node:fs"),{join:i}=await import("node:path"),e=await import("node:os"),r=`http://127.0.0.1:${t().port||4320}`,l=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||i(e.homedir(),".chatpanel","gateway-token");try{const s=o(l,"utf8").trim(),n=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${s}`},signal:AbortSignal.timeout(2500)}),c=await n.json().catch(()=>({}));if(n.status===404)throw new Error(`the gateway at ${r} predates pairing (0.9.0) — update and restart it`);if(!n.ok)throw new Error(c.error||`HTTP ${n.status}`);console.log(`Pairing code: ${c.display||c.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(s){console.error(`could not get a pairing code from the gateway at ${r}: ${s?.message||s}${/ENOENT/.test(String(s?.message))?` (no token at ${l} — has the gateway started once?)`:""}`),process.exit(1)}}else if(a==="local"){const{localStatus:t,formatLocalStatus:o}=await import("../src/local-status.js");process.stdout.write(o(await t()))}else if(a==="connect"){const{connectAgents:t,formatConnect:o}=await import("../src/connect-agents.js"),i=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(o(t({dryRun:i}),{dryRun:i}))}else{const{start:t,VERSION:o}=await import("../src/server.js"),{installService:i,uninstallService:e,serviceStatus:g,stopService:r}=await import("../src/service.js");switch(a){case"--stop":r(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(o);break;case"--install":i(),console.log("ChatPanel Privacy Gateway: installed login auto-start and started it.");break;case"--uninstall":e(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(g()?"installed (auto-start registered)":"not installed");break;case void 0:await t();break;default:console.error(`unknown option: ${a}
2
+ const e=process.argv[2];try{process.title=e==="--bridge"?"chatpanel-bridge":e==="--mcp-stdio"?"chatpanel-gateway-mcp":"chatpanel-gateway"}catch{}try{if(e==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:t}=await import("../src/extract/worker.js");t()}else if(e==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(e==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(e==="mcp"){const{runMcpServer:t}=await import("../src/mcp.js");await t()}else if(e==="tools"||e==="call"){const{runMcpCli:t}=await import("../src/mcp-cli.js");process.exit(await t(process.argv.slice(2)))}else if(e==="policy"){const{loadPolicy:t,formatPolicy:o,PolicyLoadError:i}=await import("../src/policy.js");try{const a=await t();process.argv.includes("--json")?console.log(JSON.stringify(a?{...a,label:void 0}:null,null,2)):console.log(o(a))}catch(a){throw a instanceof i&&(console.error(`org policy: ${a.message}`),process.exit(78)),a}}else if(e==="--audit"){const{egressAudit:t,formatAudit:o}=await import("../src/egress.js"),{loadConfig:i}=await import("../src/config.js"),{readFileSync:a}=await import("node:fs"),{join:p}=await import("node:path"),n=await import("node:os"),l=i(),s=`http://127.0.0.1:${l.port||4320}`;let r=null,c=`no gateway running at ${s}`;try{const d=a(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||p(n.homedir(),".chatpanel","gateway-token"),"utf8").trim(),g=await fetch(`${s}/audit`,{headers:{authorization:`Bearer ${d}`},signal:AbortSignal.timeout(2500)});if(g.ok)r=await g.json();else if(g.status===404){const u=await fetch(`${s}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);c=`the gateway running at ${s}${u?.version?` (${u.version})`:""} predates --audit (0.7.0) — restart it after updating`}else c=`the gateway at ${s} refused the audit (HTTP ${g.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!r){const{VERSION:d}=await import("../src/server.js");r={...t(l,{ledger:null,version:d}),observed:[]},console.log(`(${c}; showing what the current config allows)
3
+ `)}process.argv.includes("--json")?console.log(JSON.stringify(r,null,2)):console.log(o(r))}else if(e==="pair"){const{loadConfig:t}=await import("../src/config.js"),{readFileSync:o}=await import("node:fs"),{join:i}=await import("node:path"),a=await import("node:os"),n=`http://127.0.0.1:${t().port||4320}`,l=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||i(a.homedir(),".chatpanel","gateway-token");try{const s=o(l,"utf8").trim(),r=await fetch(`${n}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${s}`},signal:AbortSignal.timeout(2500)}),c=await r.json().catch(()=>({}));if(r.status===404)throw new Error(`the gateway at ${n} predates pairing (0.9.0) — update and restart it`);if(!r.ok)throw new Error(c.error||`HTTP ${r.status}`);console.log(`Pairing code: ${c.display||c.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(s){console.error(`could not get a pairing code from the gateway at ${n}: ${s?.message||s}${/ENOENT/.test(String(s?.message))?` (no token at ${l} — has the gateway started once?)`:""}`),process.exit(1)}}else if(e==="local"){const{localStatus:t,formatLocalStatus:o}=await import("../src/local-status.js");process.stdout.write(o(await t()))}else if(e==="connect"){const{connectAgents:t,formatConnect:o}=await import("../src/connect-agents.js"),i=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(o(t({dryRun:i}),{dryRun:i}))}else{const{start:t,VERSION:o}=await import("../src/server.js"),{installService:i,uninstallService:a,serviceStatus:p,stopService:n}=await import("../src/service.js");switch(e){case"--stop":n(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(o);break;case"--install":i(),console.log("ChatPanel Privacy Gateway: installed login auto-start and started it.");break;case"--uninstall":a(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(p()?"installed (auto-start registered)":"not installed");break;case void 0:await t();break;default:console.error(`unknown option: ${e}
4
4
  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(t){console.error(`error: ${t.message}`),process.exit(1)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.11.13",
3
+ "version": "0.17.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": {
@@ -21,11 +21,17 @@
21
21
  "node": ">=18"
22
22
  },
23
23
  "dependencies": {
24
- "@chatpanel/bridge": "^0.13.9",
24
+ "@anthropic-ai/sandbox-runtime": "^0.0.77",
25
+ "@chatpanel/bridge": "^0.14.0",
25
26
  "@chatpanel/events": "^0.117.0",
26
- "@chatpanel/pii": "^0.8.0",
27
+ "@chatpanel/pii": "^0.10.0",
27
28
  "@huggingface/transformers": "^4.2.0",
29
+ "defuddle": "^0.19.4",
30
+ "fflate": "^0.8.3",
31
+ "linkedom": "^0.18.13",
32
+ "mammoth": "^1.12.3",
28
33
  "onnxruntime-web": "1.26.0-dev.20260416-b7804b056c",
34
+ "pdfjs-dist": "^6.3.289",
29
35
  "phonemizer": "^1.2.1"
30
36
  },
31
37
  "homepage": "https://chatpanel.net",
@@ -1,3 +1,3 @@
1
- import"node:path";import{existsSync as Y}from"node:fs";import{spawn as q,spawnSync as z}from"node:child_process";import{resolveLaunch as J,standaloneCandidates as G,retireStandaloneBridge as Q}from"./service.js";import{DEFAULT_BRIDGE_URL as C}from"./bridge.js";const I=/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:(\d+))?\/?$/i,M=[1e3,2e3,5e3,1e4,3e4],X=6e4,Z=1200;function H(d,i){const n=String(d||"").split(".").map(t=>parseInt(t,10)),o=String(i||"").split(".").map(t=>parseInt(t,10));if(n.some(Number.isNaN)||o.some(Number.isNaN)||n.length<3||o.length<3)return 0;for(let t=0;t<3;t+=1)if(n[t]!==o[t])return n[t]>o[t]?1:-1;return 0}function U({managed:d=!0,cfgUrl:i="",healthy:n=null,standalone:o=null,embeddedVersion:t=null}={}){if(d===!1||d==="off")return{action:"off",why:"bridge supervision is off (the host runs its own)"};const p=String(i||C);if(!I.test(p))return{action:"off",why:`bridge.url ${p} is not on this machine; nothing to start here`};if(n)return!n.managedBy&&t&&n.version&&H(n.version,t)<0?{action:"replace",why:`a standalone bridge (v${n.version}, run by nobody) answers at ${p} and is older than the embedded one (v${t}) — retiring it`}:{action:"adopt",why:`a bridge already answers at ${p}${n.version?` (v${n.version}${n.managedBy?`, run by ${n.managedBy}`:""})`:""}`};const u=o?.version||null;return o?.path&&t&&H(u,t)>0?{action:"spawn-standalone",why:`the installed bridge (v${u}) is newer than the embedded one (v${t})`,path:o.path}:t?{action:"spawn-embedded",why:`starting the embedded bridge (v${t})${o?.path?` — the installed one is v${u||"?"}`:""}`}:o?.path?{action:"spawn-standalone",why:`starting the installed bridge${u?` (v${u})`:""}`,path:o.path}:{action:"off",why:"no bridge to start (no embedded copy, no standalone install)"}}async function W(d,{timeoutMs:i=Z,fetchImpl:n=fetch}={}){const o=new AbortController,t=setTimeout(()=>o.abort(),i);try{const p=await n(`${String(d).replace(/\/$/,"")}/health`,{signal:o.signal});if(!p.ok)return null;const u=await p.json().catch(()=>null);return u&&u.ok!==!1?{version:u.version||null,managedBy:u.managedBy||null}:null}catch{return null}finally{clearTimeout(t)}}function V(d,i=[],{timeoutMs:n=8e3}={}){try{const o=z(d,[...i,"--version"],{encoding:"utf8",timeout:n,env:{...process.env,CHATPANEL_BRIDGE_EMBEDDED:"1"}}),t=String(o.stdout||"").trim().split(`
2
- `).pop();return/^\d+\.\d+\.\d+/.test(t)?t:null}catch{return null}}function tt(){const{program:d,args:i}=J();return{program:d,args:[...i,"--bridge"]}}const et=d=>I.exec(String(d||C))?.[3]||"4319";async function lt(d,{log:i=a=>console.log(a),probe:n=W,spawnImpl:o=q,version:t=V,candidates:p=G(),exists:u=Y,launch:j=tt,managed:b=process.env.CHATPANEL_BRIDGE_MANAGED==="off"?!1:d?.bridge?.managed,waitForSiblingMs:O=2500,retire:F=Q,retireWaitMs:K=6e3,now:w=Date.now,setTimer:S=setTimeout,setWatch:T=(a,e)=>{const h=setTimeout(a,e);return h.unref?.(),h},watchEveryMs:N=1e4}={}){const a=String(d?.bridge?.url||C).replace(/\/$/,""),e={mode:"off",version:null,pid:null,restarts:0,why:"",child:null,stopping:!1,backoff:0},h=(r,c,s={})=>{Object.assign(e,{mode:r,why:c},s),i(` bridge : ${c}`)};let v=await n(a);if(!v&&b!==!1&&b!=="off"&&I.test(a)&&O>0){const r=w()+O;for(;!v&&w()<r;)await new Promise(c=>S(c,500)),v=await n(a)}const B=j(),y=!(b!==!1&&b!=="off")||v&&v.managedBy?null:t(B.program,B.args),x=p.find(r=>u(r))||null,L=x&&!v?{path:x,version:t(x,[])}:null,f=U({managed:b,cfgUrl:a,healthy:v,standalone:L,embeddedVersion:y});if(f.action==="off")return h("off",f.why),E();const P=r=>r.action==="spawn-embedded"?{...B,env:{CHATPANEL_BRIDGE_EMBEDDED:"1"},mode:"embedded",version:r.version||y}:{program:r.path,args:[],env:{},mode:"standalone",version:L?.version||null};let l=f.action==="adopt"||f.action==="replace"?null:P(f),R=0,$=null,_=0;const k=(r,c)=>{h("adopted",r,{version:c||null}),_=0;const s=async()=>{if(e.stopping||e.mode!=="adopted")return;const A=await n(a);if(A){_=0,e.version=A.version||e.version,$=T(s,N);return}if(_+=1,_<2){$=T(s,Math.min(N,3e3));return}if(!l){const g=y||t(B.program,B.args),m=U({managed:b,cfgUrl:a,healthy:null,standalone:L,embeddedVersion:g});if(m.action==="off"){h("off",`the adopted bridge went away and ${m.why}`);return}l=P({...m,version:g})}i(` bridge : the adopted bridge at ${a} went away — ${l.mode==="embedded"?`starting the embedded bridge (v${l.version||"?"})`:`starting the installed bridge (v${l.version||"?"})`}`),h(l.mode,`the adopted bridge went away; ${l.mode} bridge started in its place`,{version:l.version}),D()};$=T(s,N)},D=()=>{if(e.stopping)return;const r=o(l.program,l.args,{stdio:["ignore","pipe","pipe"],env:{...process.env,...l.env,CHATPANEL_MANAGED_BY:"gateway",CHATPANEL_BRIDGE_PORT:et(a)}});R=w(),e.child=r,e.pid=r.pid||null;const c=(s,A)=>s?.on("data",g=>{for(const m of String(g).split(`
3
- `))m.trim()&&i(`[bridge] ${m}`)});c(r.stdout,"out"),c(r.stderr,"err"),r.on("error",s=>i(`[bridge] could not start ${l.program}: ${s?.message||s}`)),r.on("exit",async(s,A)=>{if(e.child=null,e.pid=null,e.stopping)return;const g=await n(a);if(g){k(`a bridge already answers at ${a} (v${g.version||"?"}${g.managedBy?`, run by ${g.managedBy}`:""}) — ours stepped aside`,g.version);return}w()-R>X&&(e.backoff=0);const m=M[Math.min(e.backoff,M.length-1)];e.backoff+=1,e.restarts+=1,i(`[bridge] exited (${A||s}); restarting in ${m/1e3}s`),S(D,m)})};if(f.action==="adopt")return k(f.why,v.version),E();if(f.action==="replace"){i(` bridge : ${f.why}`);try{F({paths:p})}catch(s){i(` bridge : could not retire the standalone bridge: ${s?.message||s}`)}const r=w()+K;let c=await n(a);for(;c&&w()<r;)await new Promise(s=>S(s,500)),c=await n(a);return c?(k(`the standalone bridge (v${c.version||"?"}) did not stop — adopted; update or uninstall it by hand (chatpanel-bridge --uninstall)`,c.version),E()):(l=P({action:"spawn-embedded",version:y}),h("embedded",`the standalone bridge was retired; starting the embedded bridge (v${y})`,{version:y}),D(),E())}return h(l.mode,f.why,{version:l.version}),D(),E();function E(){return{status:()=>({mode:e.mode,version:e.version,pid:e.pid,restarts:e.restarts,why:e.why}),stop:()=>{if(e.stopping=!0,$&&(clearTimeout($),$=null),e.child&&!e.child.killed)try{e.child.kill("SIGTERM")}catch{}}}}}export{H as compareVersions,tt as embeddedLaunch,lt as ensureBridge,U as planBridge,W as probeBridge,G as standaloneCandidates,V as versionOf};
1
+ import"node:path";import{existsSync as Y}from"node:fs";import{spawn as q,spawnSync as z}from"node:child_process";import{resolveLaunch as J,standaloneCandidates as I,retireStandaloneBridge as Q}from"./service.js";import{DEFAULT_BRIDGE_URL as M}from"./bridge.js";const O=/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:(\d+))?\/?$/i,G=[1e3,2e3,5e3,1e4,3e4],X=6e4,Z=1200;function W(){if(process.env.CHATPANEL_SRT_MODULE)return{};try{return{CHATPANEL_SRT_MODULE:import.meta.resolve("@anthropic-ai/sandbox-runtime")}}catch{return{}}}function H(d,i){const n=String(d||"").split(".").map(t=>parseInt(t,10)),o=String(i||"").split(".").map(t=>parseInt(t,10));if(n.some(Number.isNaN)||o.some(Number.isNaN)||n.length<3||o.length<3)return 0;for(let t=0;t<3;t+=1)if(n[t]!==o[t])return n[t]>o[t]?1:-1;return 0}function U({managed:d=!0,cfgUrl:i="",healthy:n=null,standalone:o=null,embeddedVersion:t=null}={}){if(d===!1||d==="off")return{action:"off",why:"bridge supervision is off (the host runs its own)"};const p=String(i||M);if(!O.test(p))return{action:"off",why:`bridge.url ${p} is not on this machine; nothing to start here`};if(n)return!n.managedBy&&t&&n.version&&H(n.version,t)<0?{action:"replace",why:`a standalone bridge (v${n.version}, run by nobody) answers at ${p} and is older than the embedded one (v${t}) — retiring it`}:{action:"adopt",why:`a bridge already answers at ${p}${n.version?` (v${n.version}${n.managedBy?`, run by ${n.managedBy}`:""})`:""}`};const u=o?.version||null;return o?.path&&t&&H(u,t)>0?{action:"spawn-standalone",why:`the installed bridge (v${u}) is newer than the embedded one (v${t})`,path:o.path}:t?{action:"spawn-embedded",why:`starting the embedded bridge (v${t})${o?.path?` — the installed one is v${u||"?"}`:""}`}:o?.path?{action:"spawn-standalone",why:`starting the installed bridge${u?` (v${u})`:""}`,path:o.path}:{action:"off",why:"no bridge to start (no embedded copy, no standalone install)"}}async function V(d,{timeoutMs:i=Z,fetchImpl:n=fetch}={}){const o=new AbortController,t=setTimeout(()=>o.abort(),i);try{const p=await n(`${String(d).replace(/\/$/,"")}/health`,{signal:o.signal});if(!p.ok)return null;const u=await p.json().catch(()=>null);return u&&u.ok!==!1?{version:u.version||null,managedBy:u.managedBy||null}:null}catch{return null}finally{clearTimeout(t)}}function tt(d,i=[],{timeoutMs:n=8e3}={}){try{const o=z(d,[...i,"--version"],{encoding:"utf8",timeout:n,env:{...process.env,CHATPANEL_BRIDGE_EMBEDDED:"1"}}),t=String(o.stdout||"").trim().split(`
2
+ `).pop();return/^\d+\.\d+\.\d+/.test(t)?t:null}catch{return null}}function et(){const{program:d,args:i}=J();return{program:d,args:[...i,"--bridge"]}}const nt=d=>O.exec(String(d||M))?.[3]||"4319";async function ct(d,{log:i=a=>console.log(a),probe:n=V,spawnImpl:o=q,version:t=tt,candidates:p=I(),exists:u=Y,launch:j=et,managed:b=process.env.CHATPANEL_BRIDGE_MANAGED==="off"?!1:d?.bridge?.managed,waitForSiblingMs:R=2500,retire:F=Q,retireWaitMs:K=6e3,now:w=Date.now,setTimer:D=setTimeout,setWatch:S=(a,e)=>{const h=setTimeout(a,e);return h.unref?.(),h},watchEveryMs:L=1e4}={}){const a=String(d?.bridge?.url||M).replace(/\/$/,""),e={mode:"off",version:null,pid:null,restarts:0,why:"",child:null,stopping:!1,backoff:0},h=(r,c,s={})=>{Object.assign(e,{mode:r,why:c},s),i(` bridge : ${c}`)};let v=await n(a);if(!v&&b!==!1&&b!=="off"&&O.test(a)&&R>0){const r=w()+R;for(;!v&&w()<r;)await new Promise(c=>D(c,500)),v=await n(a)}const E=j(),y=!(b!==!1&&b!=="off")||v&&v.managedBy?null:t(E.program,E.args),N=p.find(r=>u(r))||null,x=N&&!v?{path:N,version:t(N,[])}:null,f=U({managed:b,cfgUrl:a,healthy:v,standalone:x,embeddedVersion:y});if(f.action==="off")return h("off",f.why),A();const P=r=>r.action==="spawn-embedded"?{...E,env:{CHATPANEL_BRIDGE_EMBEDDED:"1"},mode:"embedded",version:r.version||y}:{program:r.path,args:[],env:{},mode:"standalone",version:x?.version||null};let l=f.action==="adopt"||f.action==="replace"?null:P(f),k=0,$=null,_=0;const C=(r,c)=>{h("adopted",r,{version:c||null}),_=0;const s=async()=>{if(e.stopping||e.mode!=="adopted")return;const B=await n(a);if(B){_=0,e.version=B.version||e.version,$=S(s,L);return}if(_+=1,_<2){$=S(s,Math.min(L,3e3));return}if(!l){const g=y||t(E.program,E.args),m=U({managed:b,cfgUrl:a,healthy:null,standalone:x,embeddedVersion:g});if(m.action==="off"){h("off",`the adopted bridge went away and ${m.why}`);return}l=P({...m,version:g})}i(` bridge : the adopted bridge at ${a} went away — ${l.mode==="embedded"?`starting the embedded bridge (v${l.version||"?"})`:`starting the installed bridge (v${l.version||"?"})`}`),h(l.mode,`the adopted bridge went away; ${l.mode} bridge started in its place`,{version:l.version}),T()};$=S(s,L)},T=()=>{if(e.stopping)return;const r=o(l.program,l.args,{stdio:["ignore","pipe","pipe"],env:{...process.env,...l.env,CHATPANEL_MANAGED_BY:"gateway",CHATPANEL_BRIDGE_PORT:nt(a),...W()}});k=w(),e.child=r,e.pid=r.pid||null;const c=(s,B)=>s?.on("data",g=>{for(const m of String(g).split(`
3
+ `))m.trim()&&i(`[bridge] ${m}`)});c(r.stdout,"out"),c(r.stderr,"err"),r.on("error",s=>i(`[bridge] could not start ${l.program}: ${s?.message||s}`)),r.on("exit",async(s,B)=>{if(e.child=null,e.pid=null,e.stopping)return;const g=await n(a);if(g){C(`a bridge already answers at ${a} (v${g.version||"?"}${g.managedBy?`, run by ${g.managedBy}`:""}) — ours stepped aside`,g.version);return}w()-k>X&&(e.backoff=0);const m=G[Math.min(e.backoff,G.length-1)];e.backoff+=1,e.restarts+=1,i(`[bridge] exited (${B||s}); restarting in ${m/1e3}s`),D(T,m)})};if(f.action==="adopt")return C(f.why,v.version),A();if(f.action==="replace"){i(` bridge : ${f.why}`);try{F({paths:p})}catch(s){i(` bridge : could not retire the standalone bridge: ${s?.message||s}`)}const r=w()+K;let c=await n(a);for(;c&&w()<r;)await new Promise(s=>D(s,500)),c=await n(a);return c?(C(`the standalone bridge (v${c.version||"?"}) did not stop — adopted; update or uninstall it by hand (chatpanel-bridge --uninstall)`,c.version),A()):(l=P({action:"spawn-embedded",version:y}),h("embedded",`the standalone bridge was retired; starting the embedded bridge (v${y})`,{version:y}),T(),A())}return h(l.mode,f.why,{version:l.version}),T(),A();function A(){return{status:()=>({mode:e.mode,version:e.version,pid:e.pid,restarts:e.restarts,why:e.why}),stop:()=>{if(e.stopping=!0,$&&(clearTimeout($),$=null),e.child&&!e.child.killed)try{e.child.kill("SIGTERM")}catch{}}}}}export{H as compareVersions,et as embeddedLaunch,ct as ensureBridge,U as planBridge,V as probeBridge,W as srtModuleEnv,I as standaloneCandidates,tt as versionOf};
@@ -0,0 +1 @@
1
+ import*as s from"./ner-engine.js";import*as w from"./stt-engine.js";import*as D from"./tts-engine.js";import{MODEL_CATALOG as E,DEFAULT_MODEL as A}from"./models.js";import{STT_MODEL_CATALOG as L,DEFAULT_STT_MODEL as O}from"./stt-models.js";import{TTS_MODEL_CATALOG as q,resolveDefaultModel as M}from"./tts-models.js";import{rawOrtAvailable as S}from"./ort.js";import{CAPABILITY_ROUTES as f,overBudget as k,validateDetectRequest as C}from"./capability-endpoints.js";import{extractCapabilityEntry as R}from"./extract/handler.js";const g=e=>[...new Set(e.filter(Boolean))];function h(e,d={}){return{state:e.state||"off",name:e.runtime||null,dtype:e.dtype||null,error:e.error||null,...d}}function z(e,{version:d="",reader:n=null,searcher:t=null,extract:i=null}={}){const l=s.health(),o=e?.redaction?.detection,m=!!(o&&o.backend&&o.backend!=="off"),r=l.model||e?.ner?.model||A,u=w.health(),x=D.health(),b=x.model||e?.tts?.model||M(S()),y=[{id:"detect",route:f.detect,models:g([r,...E.map(a=>a.id)]),default:r,union:l.companions?.filter(a=>a.state==="ready").map(a=>a.model)||[],labels:s.isReady()?s.labels():[],maxTokens:s.isReady()?s.maxTokens():null,requirements:{egress:"none",deterministic:!0},stats:l.stats||{calls:0},runtime:m?{state:"external",name:o.backend,url:o.url||null}:h(l,{installed:s.modelOnDisk(r)})},{id:"stt",route:f.stt,streaming:"/stt/sessions",models:g([u.model||e?.stt?.model||O,...L.map(a=>a.id)]),default:u.model||e?.stt?.model||O,requirements:{egress:"none"},runtime:h(u)},{id:"tts",route:f.tts,voices:"/tts/voices",models:g([b,...q.map(a=>a.id)]),default:b,requirements:{egress:"none"},runtime:h(x)}],v=e?.read||{},T=!!v.remote?.url;y.push({id:"read",route:f.read,providers:n?n.providers():["defuddle","text",...T?["remote"]:[]],default:v.provider||"defuddle",requirements:{egress:"web"},stats:n?n.stats():{calls:0},runtime:{state:"ready",cache:n?n.cache.size():0,remote:T?"configured":"off"}});const c=e?.search||{},p=!!c.searxng?.url,_=t?.searxng?t.searxng.state():p?"unknown":"off";if(y.push({id:"search",route:f.search,providers:t?t.providers():["serp",...p?["searxng"]:[]],default:c.provider==="searxng"||c.provider==="serp"?c.provider:p?"searxng":"serp",requirements:{egress:"web"},stats:t?t.stats()[p?"searxng":"serp"]||{calls:0}:{calls:0},runtime:{state:"ready",searxng:_,...p?{searxngUrl:c.searxng.url}:{}}}),i)try{y.push(R(i))}catch{}return{capabilities:y,server:{name:"chatpanel-gateway",version:String(d),audit:"/audit"}}}async function P(e,{ensure:d=async()=>s.state(),model:n=null}={}){let t;try{t=C(e)}catch(r){return{status:400,body:{error:{message:r.message,type:"invalid_request"}}}}if(t.model&&n&&t.model!==n)return{status:404,body:{error:{message:`model ${t.model} is not loaded here (serving ${n})`,type:"model_not_found"}}};if(await d(),!s.isReady()){const r=s.health();return{status:503,body:{error:{message:r.state==="error"?`detector failed to load: ${r.error||"unknown error"}`:`detector is ${r.state} — not ready yet`,type:r.state==="error"?"detector_error":"detector_unready"},state:r.state,model:r.model}}}const i=k(s.stats(),t.text.length,t.budgetMs);if(i)return{status:503,body:{...i,model:s.health().model}};const l=performance.now();let o=await s.detectSpans(t.text);if(t.labels){const r=new Set(t.labels);o=o.filter(u=>r.has(u.type))}const m=s.health();return{status:200,body:{entities:o,model:m.model,ms:Math.round(performance.now()-l),runtime:{name:m.runtime||null,dtype:m.dtype||null}}}}export{z as capabilitiesDocument,P as handleDetect};
@@ -0,0 +1 @@
1
+ const f=Object.freeze(["detect","decide","rerank","embed","stt","tts","search","read","extract"]),c=Object.freeze({detect:"/v1/detect",decide:"/v1/decide",rerank:"/v1/rerank",embed:"/v1/embeddings",stt:"/v1/audio/transcriptions",tts:"/v1/audio/speech",search:"/v1/search",read:"/v1/read",extract:"/v1/extract"}),m=Object.freeze(new Set(["search","read","extract"])),p=Object.freeze(["day","week","month","year"]),o=Object.freeze(["login","paywall","rate_limited","robots","tdm"]),u=Object.freeze(["markdown","text"]),b="/v1/capabilities",g="over_budget",a=e=>!!e&&typeof e=="object"&&!Array.isArray(e),i=e=>typeof e=="string"&&e.length>0,n=e=>typeof e=="number"&&Number.isFinite(e),r=(e,s)=>{if(!e)throw new EventError("SHAPE",s)};function h(e,s){if(!a(e)||!(e.calls>0))return null;const t=n(e.p50Ms)?e.p50Ms:0,l=n(e.charsPerSec)&&e.charsPerSec>0&&n(s)?s/e.charsPerSec*1e3:0;return Math.round(Math.max(t,l))}function x(e,s,t){if(!n(t)||t<=0)return null;const l=h(e,s);return l===null||l<=t?null:{error:{type:g,message:`predicted ${l} ms is over the ${t} ms budget`,predictedMs:l,budgetMs:t}}}function A(e){r(a(e),"detect: body must be an object"),r(typeof e.text=="string","detect: text (string) required");const s={text:e.text};return e.model!=null&&(r(i(e.model),"detect: model must be a non-empty string"),s.model=e.model),e.labels!=null&&(r(Array.isArray(e.labels)&&e.labels.every(i),"detect: labels must be string[]"),s.labels=e.labels),e.budgetMs!=null&&(r(n(e.budgetMs)&&e.budgetMs>=0,"detect: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function $(e,s=null){r(a(e),"detect: response must be an object"),r(Array.isArray(e.entities),"detect: entities[] required"),r(i(e.model),"detect: model required"),r(n(e.ms)&&e.ms>=0,"detect: ms required");for(const t of e.entities)r(a(t)&&i(t.value)&&i(t.type),"detect: entity needs value and type"),r(Number.isInteger(t.start)&&Number.isInteger(t.end)&&t.start>=0&&t.end>t.start,`detect: entity ${JSON.stringify(t.value)} needs start < end`),r(n(t.score)&&t.score>=0&&t.score<=1,`detect: entity ${JSON.stringify(t.value)} needs a score in [0,1]`),typeof s=="string"&&r(s.slice(t.start,t.end)===t.value,`detect: entity ${JSON.stringify(t.value)} is not at ${t.start}–${t.end} of the text`);return e}const d=e=>{if(!i(e))return!1;try{const s=new URL(e);return s.protocol==="http:"||s.protocol==="https:"}catch{return!1}};function q(e){r(a(e),"search: body must be an object"),r(i(e.q)&&e.q.trim().length>0,"search: q (non-empty string) required");const s={q:e.q.trim()};return e.limit!=null&&(r(Number.isInteger(e.limit)&&e.limit>=1&&e.limit<=50,"search: limit must be an integer 1–50"),s.limit=e.limit),e.lang!=null&&(r(i(e.lang)&&/^[a-z]{2}(-[A-Za-z]{2})?$/.test(e.lang),"search: lang must be a BCP-47 tag like en or en-US"),s.lang=e.lang),e.site!=null&&(r(i(e.site)&&!/[\s/]/.test(e.site),"search: site must be a hostname"),s.site=e.site.toLowerCase()),e.freshness!=null&&(r(p.includes(e.freshness),`search: freshness must be one of ${p.join(", ")}`),s.freshness=e.freshness),e.read!=null&&(r(Number.isInteger(e.read)&&e.read>=0&&e.read<=10,"search: read must be an integer 0–10"),s.read=e.read),e.provider!=null&&(r(i(e.provider),"search: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(r(n(e.budgetMs)&&e.budgetMs>=0,"search: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function S(e){return r(a(e),"search: response must be an object"),r(Array.isArray(e.results),"search: results[] required"),r(i(e.provider),"search: provider required"),r(n(e.ms)&&e.ms>=0,"search: ms required"),e.results.forEach((s,t)=>{r(a(s)&&s.rank===t+1,`search: result ${t} must carry rank ${t+1}`),r(d(s.url),`search: result ${t+1} needs an absolute http(s) url`),r(i(s.title),`search: result ${t+1} needs a title`),r(typeof s.snippet=="string",`search: result ${t+1} needs a snippet (may be empty)`),s.read!=null&&v(s.read)}),e}function R(e){r(a(e),"read: body must be an object"),r(d(e.url),"read: url (absolute http(s)) required");const s={url:e.url,format:"markdown"};return e.format!=null&&(r(u.includes(e.format),`read: format must be one of ${u.join(", ")}`),s.format=e.format),e.maxChars!=null&&(r(Number.isInteger(e.maxChars)&&e.maxChars>=200,"read: maxChars must be an integer ≥ 200"),s.maxChars=e.maxChars),e.snippet!=null&&(r(typeof e.snippet=="string","read: snippet must be a string"),s.snippet=e.snippet),e.provider!=null&&(r(i(e.provider),"read: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(r(n(e.budgetMs)&&e.budgetMs>=0,"read: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function v(e){r(a(e),"read: response must be an object"),r(d(e.url),"read: url (absolute, where the page landed) required"),r(typeof e.title=="string","read: title (string, may be empty) required"),r(u.includes(e.format),"read: format required");const s=e[e.format];r(typeof s=="string",`read: ${e.format} (string) required`),r(Number.isInteger(e.chars)&&e.chars===s.length,"read: chars must equal the content length"),r(typeof e.truncated=="boolean","read: truncated (boolean) required"),r(i(e.provider),"read: provider required"),r(n(e.ms)&&e.ms>=0,"read: ms required"),r(Array.isArray(e.sections),"read: sections[] required");for(const t of e.sections)r(a(t)&&i(t.id)&&i(t.heading),"read: section needs id and heading"),r(Number.isInteger(t.level)&&t.level>=1&&t.level<=6,`read: section ${t.id} needs level 1–6`),r(Number.isInteger(t.offset)&&t.offset>=0&&t.offset<=s.length,`read: section ${t.id} offset must index the content`);return e.restricted!=null&&r(a(e.restricted)&&o.includes(e.restricted.reason),`read: restricted.reason must be one of ${o.join(", ")}`),e}function M(e){r(a(e),"capabilities: response must be an object"),r(Array.isArray(e.capabilities),"capabilities: capabilities[] required"),r(a(e.server)&&i(e.server.name)&&i(e.server.version),"capabilities: server {name, version} required");const s=new Set;for(const t of e.capabilities)r(a(t)&&f.includes(t.id),`capabilities: unknown capability id ${JSON.stringify(t?.id)}`),r(!s.has(t.id),`capabilities: ${t.id} listed twice`),s.add(t.id),r(t.route===c[t.id],`capabilities: ${t.id} must be served at ${c[t.id]}`),m.has(t.id)?(r(Array.isArray(t.providers)&&t.providers.length>0&&t.providers.every(i),`capabilities: ${t.id}.providers must be a non-empty string[]`),t.default!=null&&r(t.providers.includes(t.default),`capabilities: ${t.id}.default must be one of its providers`)):(r(Array.isArray(t.models)&&t.models.every(i),`capabilities: ${t.id}.models must be string[]`),t.default!=null&&r(t.models.includes(t.default),`capabilities: ${t.id}.default must be one of its models`)),t.labels!=null&&r(Array.isArray(t.labels)&&t.labels.every(i),`capabilities: ${t.id}.labels must be string[]`),t.stats!=null&&r(a(t.stats)&&(m.has(t.id)||n(t.stats.calls)),`capabilities: ${t.id}.stats needs calls`),t.runtime!=null&&r(a(t.runtime)&&i(t.runtime.state),`capabilities: ${t.id}.runtime needs state`);return e}function I(e){return(e?.capabilities||[]).map(s=>({id:s.id,route:s.route,models:s.models||[],providers:s.providers||[],ready:!s.runtime||["ready","external","idle"].includes(s.runtime.state),stats:s.stats||null,labels:s.labels||null}))}export{f as CAPABILITIES,c as CAPABILITY_ROUTES,b as DISCOVERY_ROUTE,g as OVER_BUDGET,m as PROVIDER_CAPABILITIES,u as READ_FORMATS,o as READ_RESTRICTIONS,p as SEARCH_FRESHNESS,I as offeredCapabilities,x as overBudget,h as predictMs,M as validateCapabilitiesResponse,A as validateDetectRequest,$ as validateDetectResponse,R as validateReadRequest,v as validateReadResponse,q as validateSearchRequest,S as validateSearchResponse};
package/src/config.js CHANGED
@@ -1 +1 @@
1
- import{readFileSync as s,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 d}from"./stt-models.js";const a={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],maxBodyBytes:26214400,pro:{entitlementToken:"",free:{used:0}},bridge:{url:"http://127.0.0.1:4319",agent:"codex",token:"",permissionMode:"default",workingDir:"",openAgentLane:!1},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,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:d,allowDownload:!0,diarize:!0},tts:{enabled:!0,provider:"local",model:"",voice:"",allowDownload:!0,remote:{baseUrl:"",model:"",voice:"",redact:!0}},logRequests:!0,logDetail:"off"};function o(e,t){if(Array.isArray(t))return t;if(t&&typeof t=="object"&&e&&typeof e=="object"){const i={...e};for(const r of Object.keys(t))i[r]=o(e[r],t[r]);return i}return t===void 0?e:t}function _(e=process.env){let t=a;const i=e.CHATPANEL_GATEWAY_CONFIG||p(A.homedir(),".chatpanel","gateway.config.json");if(l(i))try{t=o(t,JSON.parse(s(i,"utf8")))}catch(n){throw new Error(`bad config file ${i}: ${n.message}`)}e.CHATPANEL_GATEWAY_HOST&&(t=o(t,{host:e.CHATPANEL_GATEWAY_HOST})),e.CHATPANEL_GATEWAY_PORT&&(t=o(t,{port:Number(e.CHATPANEL_GATEWAY_PORT)})),e.OPENAI_BASE_URL&&(t=o(t,{upstreams:{openai:{baseUrl:e.OPENAI_BASE_URL}}})),e.ANTHROPIC_BASE_URL&&(t=o(t,{upstreams:{anthropic:{baseUrl:e.ANTHROPIC_BASE_URL}}})),e.CHATPANEL_REDACTION_TIER&&(t=o(t,{redaction:{tier:e.CHATPANEL_REDACTION_TIER}}));const r=Number(t.port);return(!Number.isInteger(r)||r<1||r>65535)&&(t.port!==a.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(t.port)} — using ${a.port}`),t=o(t,{port:a.port})),t}export{a as DEFAULTS,_ as loadConfig};
1
+ import{readFileSync as s,existsSync as l}from"node:fs";import{join as p}from"node:path";import d from"node:os";import{DEFAULT_MODEL as c}from"./models.js";import{DEFAULT_STT_MODEL as A}from"./stt-models.js";const a={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],maxBodyBytes:26214400,pro:{entitlementToken:"",free:{used:0}},bridge:{url:"http://127.0.0.1:4319",agent:"codex",token:"",permissionMode:"default",workingDir:"",openAgentLane:!1},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:[],caseRecovery:!0,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:A,allowDownload:!0,diarize:!0,warmMs:15*6e4},read:{provider:"defuddle",remote:{url:"",key:""}},search:{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},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 _(t=process.env){let e=a;const i=t.CHATPANEL_GATEWAY_CONFIG||p(d.homedir(),".chatpanel","gateway.config.json");if(l(i))try{e=r(e,JSON.parse(s(i,"utf8")))}catch(n){throw new Error(`bad config file ${i}: ${n.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}}));const o=Number(e.port);return(!Number.isInteger(o)||o<1||o>65535)&&(e.port!==a.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(e.port)} — using ${a.port}`),e=r(e,{port:a.port})),e}export{a as DEFAULTS,_ as loadConfig};
@@ -1 +1 @@
1
- import{writeFileSync as l,mkdirSync as a,chmodSync as d}from"node:fs";import{join as u,dirname as y}from"node:path";import m from"node:os";import{usage as b}from"./freegate.js";function p(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||u(m.homedir(),".chatpanel","gateway.config.json")}function g(e,o=p()){a(y(o),{recursive:!0,mode:448});const t={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,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools};l(o,JSON.stringify(t,null,2),{mode:384});try{d(o,384)}catch{}}function S(e,{proUnlocked:o=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(t=>{const{apiKey:r,...i}=t;return{...i,hasKey:!!r}}),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:t,...r}=e.redaction?.detection||{backend:"off"};return r})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:o,hasToken:!!e.pro?.entitlementToken,free:b(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 N(e,o){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=o,e.ner.autostart=!0,e.ner}function w(e,o={}){if(!e||e.type!=="api")return!1;let t;try{t=new URL(String(e.baseUrl||""))}catch{return!1}const r=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(t.hostname),i=Number(t.port)||(t.protocol==="https:"?443:80);return r&&i===(Number(o.port)||4320)}const s=["default","acceptEdits","bypassPermissions"];function f(e,o={}){const t=e?.bridge||{};return{...s.includes(t.permissionMode)&&t.permissionMode!=="default"?{permissionMode:t.permissionMode}:{},...typeof t.workingDir=="string"&&t.workingDir.trim()?{workingDir:t.workingDir.trim()}:{},...o}}function M(e,o={}){if((o.backend==="bridge"||o.backend==="api")&&(e.backend=o.backend),Array.isArray(o.destinations)){const t=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(r=>[r.id,r]));e.destinations=o.destinations.filter(r=>r&&typeof r.id=="string"&&(r.type==="agent"||r.type==="api")).filter(r=>{const i=w(r,e);return i&&console.log(`[gateway] refusing destination "${r.id}": ${r.baseUrl} is this gateway — a loop`),!i}).map(r=>{const i={id:r.id,type:r.type,models:Array.isArray(r.models)?r.models.filter(n=>typeof n=="string"&&n):[]};if(r.type==="agent"&&(i.agent=r.agent||r.id),r.type==="api"){i.baseUrl=String(r.baseUrl||""),i.protocol=r.protocol==="anthropic"?"anthropic":"openai";const n=typeof r.apiKey=="string"&&r.apiKey?r.apiKey:t.get(r.id)?.apiKey;n&&(i.apiKey=n)}return i})}if(o.bridge&&typeof o.bridge=="object"&&(typeof o.bridge.url=="string"&&(e.bridge.url=o.bridge.url),typeof o.bridge.agent=="string"&&(e.bridge.agent=o.bridge.agent),s.includes(o.bridge.permissionMode)&&(e.bridge.permissionMode=o.bridge.permissionMode),typeof o.bridge.workingDir=="string"&&(e.bridge.workingDir=o.bridge.workingDir.trim().slice(0,1024)),typeof o.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=o.bridge.openAgentLane)),Array.isArray(o.allowedExtensionIds)&&(e.allowedExtensionIds=o.allowedExtensionIds.map(t=>String(t).trim()).filter(t=>/^[a-p]{32}$/.test(t))),o.upstreams&&typeof o.upstreams=="object")for(const t of["openai","anthropic"]){const r=o.upstreams[t];r&&typeof r.baseUrl=="string"&&r.baseUrl.trim()&&(e.upstreams[t]={...e.upstreams[t],baseUrl:r.baseUrl.trim()})}if(o.redaction&&typeof o.redaction=="object"){const t=o.redaction;(t.tier==="basic"||t.tier==="full")&&(e.redaction.tier=t.tier),"redactSystem"in t&&(e.redaction.redactSystem=!!t.redactSystem),Array.isArray(t.dictionary)&&(e.redaction.dictionary=t.dictionary),t.detection&&typeof t.detection=="object"&&(e.redaction.detection=t.detection)}if(Array.isArray(o.allowedOrigins)&&(e.allowedOrigins=o.allowedOrigins),o.pro&&typeof o.pro=="object"&&typeof o.pro.entitlementToken=="string"&&(e.pro.entitlementToken=o.pro.entitlementToken),o.stt&&typeof o.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in o.stt&&(e.stt.enabled=!!o.stt.enabled),"allowDownload"in o.stt&&(e.stt.allowDownload=!!o.stt.allowDownload)),typeof o.logRequests=="boolean"&&(e.logRequests=o.logRequests),["off","types","values"].includes(o.logDetail)&&(e.logDetail=o.logDetail),o.tools&&typeof o.tools=="object"){e.tools=e.tools||{},"autoNarrow"in o.tools&&(e.tools.autoNarrow=!!o.tools.autoNarrow),"narrowAll"in o.tools&&(e.tools.narrowAll=!!o.tools.narrowAll),(o.tools.toolData==="real"||o.tools.toolData==="redactRemote")&&(e.tools.toolData=o.tools.toolData);const t=Number(o.tools.maxPerTurn);Number.isFinite(t)&&t>=1&&(e.tools.maxPerTurn=Math.floor(t))}return e}export{s as PERMISSION_MODES,M as applyConfigPatch,N as applyNerModelSelection,f as bridgeAgentOptions,p as configPath,w as isSelfDestination,g as persistConfig,S as publicConfig};
1
+ import{writeFileSync as d,mkdirSync as u,chmodSync as y}from"node:fs";import{join as m,dirname as p}from"node:path";import b from"node:os";import{usage as w}from"./freegate.js";import{assertEndpointUrl as n}from"@chatpanel/pii";function a(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||m(b.homedir(),".chatpanel","gateway.config.json")}function f(e,r=a()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===a({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);u(p(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,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools};d(r,JSON.stringify(o,null,2),{mode:384});try{y(r,384)}catch{}}function E(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:t,...i}=o;return{...i,hasKey:!!t}}),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,...t}=e.redaction?.detection||{backend:"off"};return t})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,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}},allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:w(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 N(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function k(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const t=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),i=Number(o.port)||(o.protocol==="https:"?443:80);return t&&i===(Number(r.port)||4320)}const l=["default","acceptEdits","bypassPermissions"];function g(e,r={}){const o=e?.bridge||{};return{...l.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function S(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(t=>[t.id,t]));e.destinations=r.destinations.filter(t=>t&&typeof t.id=="string"&&(t.type==="agent"||t.type==="api")).filter(t=>{const i=k(t,e);return i&&console.log(`[gateway] refusing destination "${t.id}": ${t.baseUrl} is this gateway — a loop`),!i}).map(t=>{const i={id:t.id,type:t.type,models:Array.isArray(t.models)?t.models.filter(s=>typeof s=="string"&&s):[]};if(t.type==="agent"&&(i.agent=t.agent||t.id),t.type==="api"){i.baseUrl=String(t.baseUrl||""),i.protocol=t.protocol==="anthropic"?"anthropic":"openai";const s=typeof t.apiKey=="string"&&t.apiKey?t.apiKey:o.get(t.id)?.apiKey;s&&(i.apiKey=s)}return i})}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),l.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 t=r.upstreams[o];t&&typeof t.baseUrl=="string"&&t.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:t.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.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&&n(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 t=String(o.url||"").trim();t&&n(t),e.search.searxng.url=t}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(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{l as PERMISSION_MODES,S as applyConfigPatch,N as applyNerModelSelection,g as bridgeAgentOptions,a as configPath,k as isSelfDestination,f as persistConfig,E as publicConfig};
@@ -1 +1 @@
1
- import{ensureLib as k,modelRoot as S}from"./ner-engine.js";import{join as $}from"node:path";import{existsSync as z,readdirSync as D}from"node:fs";const c="Xenova/wavlm-base-plus-sv";let i="off",h=null,p=null,m=null,a=null,u=null;function y(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function T(){return i}function x(){return i==="ready"&&!!h&&!!p}function E(){return u}function L(){return{configured:i!=="off",ok:x(),state:i,model:h,error:m}}function q(e=c,t=y()){const r=$(S(),...e.split("/"),"onnx");if(!z(r))return!1;const n=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return D(r).some(s=>s===`model${n}.onnx`)}catch{return!1}}async function b({log:e=()=>{},allowDownload:t=!0}={}){let r;try{r=await k()}catch(o){return i="error",m=o.message,e(`[diarize] engine unavailable (${o.message})`),!1}const n=q();if(r.env.allowRemoteModels=n?!1:!!t,!n&&!t)return i="error",m="model not on disk and downloads disabled",!1;const s=r.env.remoteHost;if(!n)try{r.env.remoteHost="https://huggingface.co/"}catch{}i=n?"loading":"downloading",n||(u={model:c,file:null,pct:0},e(`[diarize] downloading ${c} (one-time)…`));try{const{AutoModel:o,AutoProcessor:l}=r,d=f=>{if(!f)return;const M=typeof f.progress=="number"?Math.round(f.progress):u?.pct??0;(f.status==="progress"||f.status==="download"||f.status==="initiate")&&(u={model:c,file:f.file||u?.file||null,pct:M})},g=await l.from_pretrained(c,{progress_callback:d}),A=await o.from_pretrained(c,{dtype:y(),progress_callback:d});return p=g,h=A,i="ready",m=null,u=null,e(`[diarize] ready — ${c} @ ${y()}`),!0}catch(o){return m=o.message,u=null,i="error",e(`[diarize] load failed (${o.message}) — diarization off`),!1}finally{try{r.env.remoteHost=s}catch{}}}function O(e={}){return a&&i!=="error"||(i="loading",a=b({log:e.onLog,allowDownload:e.allowDownload!==!1})),a}function I({onLog:e}={}){return a=null,i="loading",a=b({log:e,allowDownload:!0}),a}const v=16e3;function _(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 w(e){try{const t=await p(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 j(e){if(!x()||!(e instanceof Float32Array)||!e.length)return null;const t=2*v,r=Math.round(1.3*v);if(e.length<=Math.round(t*1.4)){const o=await w(e);return o?_(o):null}const n=[];for(let o=0;o+t<=e.length;o+=r){const l=await w(e.subarray(o,o+t));l&&n.push(_(l))}if(!n.length){const o=await w(e);return o?_(o):null}const s=new Float32Array(n[0].length);for(const o of n)for(let l=0;l<s.length;l++)s[l]+=o[l];return _(s)}function C(){i="off",h=null,p=null,m=null,a=null,u=null}function N(e,t){h=e,p=t,i=e?"ready":"off"}function F(e,t){let r=0,n=0,s=0;for(let l=0;l<e.length;l++)r+=e[l]*t[l],n+=e[l]*e[l],s+=t[l]*t[l];const o=Math.sqrt(n)*Math.sqrt(s);return o?r/o:0}class W{constructor({threshold:t=.75,maxSpeakers:r=12}={}){this.threshold=t,this.maxSpeakers=r,this.centroids=[]}assign(t,{pinnedLabel:r=null,weak:n=!1}={}){if(!t)return null;if(r)return this._merge(this._find(r)||this._create(r),t);let s=null,o=-1;const l={};for(const d of this.centroids){const g=F(t,d.vec);l[d.label]=Math.round(g*1e3)/1e3,g>o&&(o=g,s=d)}return n&&s?{...this._merge(s,t,{update:!1}),scores:l,weak:!0}:s&&o>=this.threshold?{...this._merge(s,t),scores:l}:this.centroids.length>=this.maxSpeakers&&s?{...this._merge(s,t),scores:l}:{...this._merge(this._create(`Speaker ${this.centroids.length+1}`),t),scores:l,...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 s=0;s<t.vec.length;s++)t.vec[s]=(t.vec[s]*t.n+r[s])/(t.n+1);t.n+=1}return{id:t.id,label:t.label}}}export{c as DIARIZE_MODEL,W as Diarizer,C as _reset,N as _setForTest,I as download,j as embed,L as health,O as init,x as isReady,q as modelOnDisk,E as progress,T as state};
1
+ import{ensureLib as H,modelRoot as P}from"./ner-engine.js";import{join as R}from"node:path";import{existsSync as T,readdirSync as E}from"node:fs";import{makeWarmTimer as M}from"./warm-timer.js";const m="Xenova/wavlm-base-plus-sv";let i="off",c=null,p=null,h=null,u=null,f=null,a=null,_=0,x=0;function v(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function X(){return i}function A(){return i==="ready"&&!!c&&!!p}function Z(){return f}function B(){return{configured:i!=="off",ok:A(),state:i,model:c,error:h,warmMs:a?.warmMs??null}}function G(){return!!a?.pending()}function J(){_++,a?.disarm()}function K(){_=Math.max(0,_-1),_===0&&x===0&&A()&&a?.arm()}function w(){return _>0||x>0||i==="loading"||i==="downloading"}async function k({log:e=()=>{}}={}){if(w())return!1;a?.disarm();const t=c;if(c=null,p=null,u=null,f=null,h=null,i="off",t){try{await t.dispose?.()}catch{}e("[diarize] idle — speaker model unloaded (reloads on the next diarizing session)")}return!0}function O(e=m,t=v()){const n=R(P(),...e.split("/"),"onnx");if(!T(n))return!1;const r=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return E(n).some(l=>l===`model${r}.onnx`)}catch{return!1}}async function S({log:e=()=>{},allowDownload:t=!0}={}){let n;try{n=await H()}catch(o){return i="error",h=o.message,e(`[diarize] engine unavailable (${o.message})`),!1}const r=O();if(n.env.allowRemoteModels=r?!1:!!t,!r&&!t)return i="error",h="model not on disk and downloads disabled",!1;const l=n.env.remoteHost;if(!r)try{n.env.remoteHost="https://huggingface.co/"}catch{}i=r?"loading":"downloading",r||(f={model:m,file:null,pct:0},e(`[diarize] downloading ${m} (one-time)…`));try{const{AutoModel:o,AutoProcessor:s}=n,g=d=>{if(!d)return;const F=typeof d.progress=="number"?Math.round(d.progress):f?.pct??0;(d.status==="progress"||d.status==="download"||d.status==="initiate")&&(f={model:m,file:d.file||f?.file||null,pct:F})},y=await s.from_pretrained(m,{progress_callback:g}),q=await o.from_pretrained(m,{dtype:v(),progress_callback:g});return p=y,c=q,i="ready",h=null,f=null,e(`[diarize] ready — ${m} @ ${v()}`),!0}catch(o){return h=o.message,f=null,i="error",e(`[diarize] load failed (${o.message}) — diarization off`),!1}finally{try{n.env.remoteHost=l}catch{}}}function Q(e={}){if(u&&i!=="error")return u;i="loading";const t=typeof e.onLog=="function"?e.onLog:()=>{};return a=M({warmMs:e.warmMs,busy:w,log:t,unload:()=>k({log:t})}),u=$(S({log:t,allowDownload:e.allowDownload!==!1})),u}function $(e){return e.then(t=>(t&&!w()&&a?.arm(),t))}function U({onLog:e}={}){return u=null,i="loading",a??=M({warmMs:void 0,busy:w,log:e||(()=>{}),unload:()=>k({log:e||(()=>{})})}),u=$(S({log:e,allowDownload:!0})),u}const D=16e3;function b(e){let t=0;for(const r of e)t+=r*r;t=Math.sqrt(t)||1;const n=new Float32Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]/t;return n}async function z(e){try{const t=await p(e),n=await c(t),r=n.embeddings??n.logits??n.last_hidden_state;return r?.data?Float32Array.from(r.data):null}catch{return null}}async function V(e){if(!A()||!(e instanceof Float32Array)||!e.length)return null;x++;try{return await I(e)}finally{x--,w()||a?.arm()}}async function I(e){const t=2*D,n=Math.round(1.3*D);if(e.length<=Math.round(t*1.4)){const o=await z(e);return o?b(o):null}const r=[];for(let o=0;o+t<=e.length;o+=n){const s=await z(e.subarray(o,o+t));s&&r.push(b(s))}if(!r.length){const o=await z(e);return o?b(o):null}const l=new Float32Array(r[0].length);for(const o of r)for(let s=0;s<l.length;s++)l[s]+=o[s];return b(l)}function Y(){a?.disarm(),a=null,_=0,x=0,i="off",c=null,p=null,h=null,u=null,f=null}function tt(e,t,{warmMs:n=null}={}){c=e,p=t,i=e?"ready":"off",n!==null&&(a=M({warmMs:n,busy:w,unload:()=>k()}),e&&a.arm())}function L(e,t){let n=0,r=0,l=0;for(let s=0;s<e.length;s++)n+=e[s]*t[s],r+=e[s]*e[s],l+=t[s]*t[s];const o=Math.sqrt(r)*Math.sqrt(l);return o?n/o:0}class et{constructor({threshold:t=.75,maxSpeakers:n=12}={}){this.threshold=t,this.maxSpeakers=n,this.centroids=[]}assign(t,{pinnedLabel:n=null,weak:r=!1}={}){if(!t)return null;if(n)return this._merge(this._find(n)||this._create(n),t);let l=null,o=-1;const s={};for(const g of this.centroids){const y=L(t,g.vec);s[g.label]=Math.round(y*1e3)/1e3,y>o&&(o=y,l=g)}return r&&l?{...this._merge(l,t,{update:!1}),scores:s,weak:!0}:l&&o>=this.threshold?{...this._merge(l,t),scores:s}:this.centroids.length>=this.maxSpeakers&&l?{...this._merge(l,t),scores:s}:{...this._merge(this._create(`Speaker ${this.centroids.length+1}`),t),scores:s,...r?{weak:!0}:{}}}_find(t){return this.centroids.find(n=>n.label===t)||null}_create(t){const n={id:this.centroids.length+1,label:t,vec:null,n:0};return this.centroids.push(n),n}_merge(t,n,{update:r=!0}={}){if(!t.vec)t.vec=Float32Array.from(n),t.n=1;else if(r){for(let l=0;l<t.vec.length;l++)t.vec[l]=(t.vec[l]*t.n+n[l])/(t.n+1);t.n+=1}return{id:t.id,label:t.label}}}export{m as DIARIZE_MODEL,et as Diarizer,Y as _reset,tt as _setForTest,U as download,V as embed,B as health,Q as init,A as isReady,O as modelOnDisk,Z as progress,K as release,J as retain,X as state,k as unload,G as warmPending};
package/src/egress.js CHANGED
@@ -1,2 +1,2 @@
1
- import{isBlockedHost as f}from"@chatpanel/pii";const w=()=>new Date().toISOString();function g(t){try{const e=typeof t=="string"?new URL(t):t instanceof URL?t:new URL(t?.url);return{host:e.hostname,port:e.port||(e.protocol==="https:"?"443":e.protocol==="http:"?"80":""),scheme:e.protocol.replace(":","")}}catch{return null}}const d=t=>{const e=String(t||"").toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e==="[::1]"?!0:f(e,{allowLoopback:!1,allowPrivate:!1})&&!f(e,{allowLoopback:!0,allowPrivate:!0})};function m({clock:t=w}={}){const e=new Map;return{record(o){const s=g(o);if(!s||!s.host)return;const r=`${s.scheme}://${s.host}:${s.port}`,a=t(),n=e.get(r);if(n){n.count+=1,n.lastAt=a;return}e.set(r,{host:s.host,port:s.port,scheme:s.scheme,local:d(s.host),count:1,firstAt:a,lastAt:a})},snapshot(){return[...e.values()].sort((o,s)=>o.local===s.local?s.count-o.count:o.local?1:-1)},reset(){e.clear()}}}let b=null;function E(t=globalThis,{allow:e=null}={}){if(t.__chatpanelEgress)return e&&t.__chatpanelEgress.setGate(e),t.__chatpanelEgress;const o=m();let s=e;o.setGate=a=>{s=a},o.blocked=[];const r=t.fetch;return typeof r=="function"&&(t.fetch=function(n,i){let l=null;try{l=g(n),o.record(n)}catch{}if(s&&l?.host){let h=!0;try{h=s(`${l.scheme}://${l.host}:${l.port}`,{local:d(l.host)})}catch{h=!0}if(!h){const p=`${l.host}:${l.port}`;o.blocked.includes(p)||o.blocked.push(p);const u=new Error(`egress to ${l.host} is blocked by your organisation’s policy`);return u.code="EGRESS_POLICY",Promise.reject(u)}}return r.call(this,n,i)}),t.__chatpanelEgress=o,t===globalThis&&(b=o),o}function y(){return b||(globalThis.__chatpanelEgress??null)}function c(t){try{return new URL(t).host}catch{return String(t||"")}}function $(t={},e=process.env){const o=[],s=(n,i,{when:l="always",off:h=null,local:p=!1,data:u=""}={})=>{n&&o.push({host:n,purpose:i,when:l,off:h,local:p,data:u})};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"}),e.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[n,i]of Object.entries(t.upstreams||{}))i?.baseUrl&&s(c(i.baseUrl),`model upstream "${n}" — chat requests (after redaction) go here`,{when:`a request addressed to ${n}`,off:`upstreams.${n}.baseUrl`,local:d(c(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const n of t.destinations||[])n?.baseUrl&&s(c(n.baseUrl),`destination "${n.id||n.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${n.id||"it"}`,off:"destinations[]",local:d(c(n.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"}),t.ner?.url&&s(c(t.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:d(c(t.ner.url).split(":")[0]),data:"the text being redacted"});const r=t.tts||{};if(r.provider==="openai"||r.provider==="elevenlabs"){const n=r.remote?.baseUrl?c(r.remote.baseUrl):r.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";s(n,`remote read-aloud voice (${r.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:r.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}const a=t.bridge?.url||"http://127.0.0.1:4319";return s(c(a),"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"}),o}function k(t,{ledger:e=y(),version:o="",startedAt:s=null,env:r=process.env,managed:a=null}={}){return{ok:!0,version:o,since:s?new Date(s).toISOString():null,...a?{managed:a,blocked:e?.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:e?e.snapshot():[],declared:$(t,r)}}function L(t){const e=[];e.push(`ChatPanel Gateway ${t.version||""} — egress audit`.trim()),t.since&&e.push(`observed since ${t.since}`),e.push(""),e.push("OBSERVED — hosts this process has actually contacted"),t.observed?.length||e.push(" (none yet)");for(const o of t.observed||[])e.push(` ${o.local?"[local] ":""}${o.scheme}://${o.host}:${o.port} ×${o.count} last ${o.lastAt}`);e.push(""),e.push("DECLARED — hosts this configuration allows, and why");for(const o of t.declared||[])e.push(` ${o.local?"[local] ":""}${o.host}`),e.push(` ${o.purpose}`),e.push(` when: ${o.when}${o.off?` · off: ${o.off}`:""}`),o.data&&e.push(` sends: ${o.data}`);return t.managed&&(e.push(""),e.push(`POLICY — ${t.managed.name||t.managed.org||"managed"} (${t.managed.signed?"signed":"unsigned file"}, hash ${String(t.managed.policyHash||"").slice(0,12)}…)`),e.push(` enforcing: ${Object.entries(t.managed.enforces||{}).filter(([,o])=>o).map(([o,s])=>s===!0?o:`${o}=${s}`).join(", ")||"nothing yet"}`),e.push(` refused this session: ${t.blocked?.length?t.blocked.join(", "):"none"}`)),e.push(""),e.push(`Scope: ${t.scope}`),e.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)."),e.join(`
2
- `)}export{m as createEgressLedger,$ as declaredEgress,k as egressAudit,y as egressLedger,L as formatAudit,E as installEgressLedger};
1
+ import{isBlockedHost as f}from"@chatpanel/pii";const b=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url);return{host:t.hostname,port:t.port||(t.protocol==="https:"?"443":t.protocol==="http:"?"80":""),scheme:t.protocol.replace(":","")}}catch{return null}}const d=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 y({clock:e=b}={}){const t=new Map;return{record(o){const r=g(o);if(!r||!r.host)return;const l=`${r.scheme}://${r.host}:${r.port}`,a=e(),c=t.get(l);if(c){c.count+=1,c.lastAt=a;return}t.set(l,{host:r.host,port:r.port,scheme:r.scheme,local:d(r.host),count:1,firstAt:a,lastAt:a})},snapshot(){return[...t.values()].sort((o,r)=>o.local===r.local?r.count-o.count:o.local?1:-1)},reset(){t.clear()}}}let w=null;function E(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const o=y();let r=t;o.setGate=a=>{r=a},o.blocked=[];const l=e.fetch;return typeof l=="function"&&(e.fetch=function(c,s){let n=null;try{n=g(c),o.record(c)}catch{}if(r&&n?.host){let i=!0;try{i=r(`${n.scheme}://${n.host}:${n.port}`,{local:d(n.host)})}catch{i=!0}if(!i){const u=`${n.host}:${n.port}`;o.blocked.includes(u)||o.blocked.push(u);const p=new Error(`egress to ${n.host} is blocked by your organisation’s policy`);return p.code="EGRESS_POLICY",Promise.reject(p)}}return l.call(this,c,s)}),e.__chatpanelEgress=o,e===globalThis&&(w=o),o}function v(){return w||(globalThis.__chatpanelEgress??null)}function h(e){try{return new URL(e).host}catch{return String(e||"")}}function $(e={},t=process.env){const o=[],r=(s,n,{when:i="always",off:u=null,local:p=!1,data:m=""}={})=>{s&&o.push({host:s,purpose:n,when:i,off:u,local:p,data:m})};r("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"}),r("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"}),r("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"}),r("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 l=e.search?.searxng?.url||"";if(l){let s=l;try{s=new URL(l).host}catch{}r(s,"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(s)})}if(e.search?.provider!=="searxng"&&(r("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"}),r("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 s=e.read.remote.url;try{s=new URL(e.read.remote.url).host}catch{}r(s,"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(s)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(r("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"}),r("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[s,n]of Object.entries(e.upstreams||{}))n?.baseUrl&&r(h(n.baseUrl),`model upstream "${s}" — chat requests (after redaction) go here`,{when:`a request addressed to ${s}`,off:`upstreams.${s}.baseUrl`,local:d(h(n.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const s of e.destinations||[])s?.baseUrl&&r(h(s.baseUrl),`destination "${s.id||s.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${s.id||"it"}`,off:"destinations[]",local:d(h(s.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});r("(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&&r(h(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:d(h(e.ner.url).split(":")[0]),data:"the text being redacted"});const a=e.tts||{};if(a.provider==="openai"||a.provider==="elevenlabs"){const s=a.remote?.baseUrl?h(a.remote.baseUrl):a.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";r(s,`remote read-aloud voice (${a.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:a.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}const c=e.bridge?.url||"http://127.0.0.1:4319";return r(h(c),"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"}),o}function L(e,{ledger:t=v(),version:o="",startedAt:r=null,env:l=process.env,managed:a=null}={}){return{ok:!0,version:o,since:r?new Date(r).toISOString():null,...a?{managed:a,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:$(e,l)}}function x(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 o of e.observed||[])t.push(` ${o.local?"[local] ":""}${o.scheme}://${o.host}:${o.port} ×${o.count} last ${o.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const o of e.declared||[])t.push(` ${o.local?"[local] ":""}${o.host}`),t.push(` ${o.purpose}`),t.push(` when: ${o.when}${o.off?` · off: ${o.off}`:""}`),o.data&&t.push(` sends: ${o.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(([,o])=>o).map(([o,r])=>r===!0?o:`${o}=${r}`).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{y as createEgressLedger,$ as declaredEgress,L as egressAudit,v as egressLedger,x as formatAudit,E as installEgressLedger};
@@ -0,0 +1,4 @@
1
+ import a from"mammoth";async function f(r){const e=Buffer.from(r.buffer,r.byteOffset,r.byteLength),n=await a.convertToMarkdown({buffer:e},{ignoreEmptyParagraphs:!0}),t=String(n?.value||"").replace(/\r\n?/g,`
2
+ `).replace(/\n{3,}/g,`
3
+
4
+ `).trim(),o=(/^#{1,3} (.+)$/m.exec(t)||[])[1]||"";return{markdown:t,title:o.trim()}}export{f as docxPages};
@@ -0,0 +1,5 @@
1
+ import{createHash as f}from"node:crypto";import{paginateText as c,EXTRACT_TYPES as m}from"../extract-capability.js";import{pdfPages as g}from"./pdf.js";import{docxPages as h}from"./docx.js";import{xlsxPages as w,pptxPages as y,odfPages as b}from"./office-xml.js";const C="chatpanel-extract",T=[["pdf",[37,80,68,70,45]],["zip",[80,75,3,4]]],i={docx:"docx",xlsx:"xlsx",pptx:"pptx",odt:"odt",ods:"ods",odp:"odp",epub:"epub"},d={md:"md",markdown:"md",txt:"txt",text:"txt",csv:"csv",html:"html",htm:"html",json:"txt",xml:"txt",log:"txt"};function x(r){const e=/\.([a-z0-9]{1,8})$/i.exec(String(r||""));return e?e[1].toLowerCase():""}function v(r,{name:e="",hint:a=""}={}){const n=r.subarray(0,8);for(const[t,u]of T)if(u.every((p,l)=>n[l]===p)){if(t!=="zip")return t;const p=x(e);return i[p]?i[p]:i[a]?a:E(r)||"zip"}const o=x(e);if(d[o])return d[o];if(m.includes(a)&&a!=="pdf")return a;const s=r.subarray(0,4096);for(let t=0;t<s.length;t+=1)if(s[t]===0)return"binary";return"txt"}function E(r){const e=Buffer.from(r.subarray(0,4096)).toString("latin1");return e.includes("word/")?"docx":e.includes("xl/")?"xlsx":e.includes("ppt/")?"pptx":e.includes("mimetypeapplication/vnd.oasis.opendocument.text")?"odt":e.includes("mimetypeapplication/vnd.oasis.opendocument.spreadsheet")?"ods":e.includes("mimetypeapplication/vnd.oasis.opendocument.presentation")?"odp":""}function P(r){return f("sha256").update(r).digest("hex")}async function I(r,{name:e="",hint:a=""}={}){const n=r instanceof Uint8Array?r:new Uint8Array(r),o=v(n,{name:e,hint:a}),s={hash:P(n),type:o,title:""};switch(o){case"pdf":{const t=await g(n);return{...s,title:t.title,pages:t.pages,scanned:t.scanned}}case"docx":{const t=await h(n);return{...s,title:t.title,pages:c(t.markdown)}}case"xlsx":return{...s,pages:await w(n)};case"pptx":return{...s,pages:await y(n)};case"odt":case"ods":case"odp":{const t=await b(n,o);return{...s,pages:o==="odt"?c(t.text):t.pages}}case"md":case"txt":case"csv":case"html":{let t=Buffer.from(n).toString("utf8");return o==="html"&&(t=S(t)),{...s,pages:c(t)}}default:{const t=new Error(`extract: no reader for ${o==="binary"?"this file type":o}${e?` (${e})`:""}`);throw t.code="unsupported",t}}}function S(r){return String(r).replace(/<(script|style|noscript)\b[\s\S]*?<\/\1>/gi," ").replace(/<(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\b[^>]*>/gi,`
2
+ `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/[ \t]+/g," ").replace(/\n[ \t]+/g,`
3
+ `).replace(/\n{3,}/g,`
4
+
5
+ `).trim()}export{C as PROVIDER_ID,P as hashOf,I as openDocument,v as typeOf};
@@ -0,0 +1 @@
1
+ import{validateExtractRequest as p,MAX_DOCUMENT_BYTES as u}from"../extract-capability.js";import{PROVIDER_ID as d}from"./engine.js";function m(i){const n=i.status();return{id:"extract",route:"/v1/extract",providers:[d],default:d,types:["pdf","docx","xlsx","pptx","odt","ods","odp","md","txt","csv","html"],maxBytes:u,requirements:{egress:"none",deterministic:!0},stats:{opens:n.stats.opens,pages:n.stats.pages,msPerMBp50:n.stats.msPerMBp50},runtime:{name:"worker",state:n.running?"ready":"idle",sandbox:n.sandbox}}}async function l(i,{service:n}={}){let e;try{e=p(i)}catch(t){return{status:400,body:{error:{message:t.message,type:"invalid_request"}}}}const a=(t,r,s,o={})=>({status:t,body:{error:{message:s,type:r},...o}});try{if(e.kind==="page"){const s=n.known(e.hash);if(!s)return a(404,"unknown_document","that document is not open here — send its bytes again");if(e.page>s.pages)return a(400,"invalid_request",`page must be 1–${s.pages}`);const o=await n.page(e.hash,e.page);return{status:200,body:{hash:e.hash,type:o.type,pages:o.pages,page:e.page,text:o.text,title:s.title||"",provider:d,ms:o.ms}}}const t=Buffer.from(e.data,"base64");if(!t.length)return a(400,"invalid_request","extract: data decoded to nothing");if(t.length>u)return a(413,"too_large",`extract: ${t.length} bytes is over the ${u}-byte limit`);if(e.budgetMs!=null){const s=n.predictMs(t.length);if(s!=null&&s>e.budgetMs)return{status:503,body:{error:{message:`predicted ${s} ms, over the ${e.budgetMs} ms budget`,type:"over_budget"},predictedMs:s}}}const r=await n.open(t,{name:e.name,hint:e.type||""});return{status:200,body:{hash:r.hash,type:r.type,pages:r.pages,title:r.title||"",scanned:!!r.scanned,provider:d,ms:r.ms}}}catch(t){const r=t?.code||"extract_error";return r==="unsupported"?a(415,"unsupported",t.message):r==="unknown_document"?a(404,"unknown_document",t.message):r==="timeout"?a(504,"extract_timeout","the document took too long to parse and the worker was restarted"):r==="invalid_request"?a(400,"invalid_request",t.message):a(500,"extract_error",t?.message||String(t))}}export{m as extractCapabilityEntry,l as handleExtract};
@@ -0,0 +1,13 @@
1
+ import{unzipSync as w,strFromU8 as $}from"fflate";const g=s=>String(s||"").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&#(\d+);/g,(t,o)=>String.fromCodePoint(Number(o))).replace(/&amp;/g,"&");function S(s){return w(s instanceof Uint8Array?s:new Uint8Array(s))}const b=(s,t)=>s[t]?$(s[t]):"";function j(s){const t=[];for(const o of s.matchAll(/<si>([\s\S]*?)<\/si>/g))t.push(g([...o[1].matchAll(/<t[^>]*>([\s\S]*?)<\/t>/g)].map(a=>a[1]).join("")));return t}function k(s){const t=/^([A-Z]+)/.exec(s);if(!t)return 0;let o=0;for(const a of t[1])o=o*26+(a.charCodeAt(0)-64);return o-1}function v(s,t){const o=[];for(const a of s.matchAll(/<row\b[^>]*>([\s\S]*?)<\/row>/g)){const n=[];for(const p of a[1].matchAll(/<c\b([^>]*)(?:\/>|>([\s\S]*?)<\/c>)/g)){const l=p[1]||"",r=(/\br="([A-Z]+\d+)"/.exec(l)||[])[1]||"",c=(/\bt="(\w+)"/.exec(l)||[])[1]||"",e=p[2]||"";let i="";if(c==="s"){const h=Number((/<v>(\d+)<\/v>/.exec(e)||[])[1]);i=t[h]??""}else c==="inlineStr"?i=g([...e.matchAll(/<t[^>]*>([\s\S]*?)<\/t>/g)].map(h=>h[1]).join("")):c==="b"?i=/<v>1<\/v>/.test(e)?"TRUE":"FALSE":i=g((/<v>([\s\S]*?)<\/v>/.exec(e)||[])[1]||"");const m=r?k(r):n.length;for(;n.length<m;)n.push("");n[m]=i}o.push(n)}return o}const f=5e3;async function E(s){const t=S(s),o=j(b(t,"xl/sharedStrings.xml")),a=b(t,"xl/workbook.xml"),n=b(t,"xl/_rels/workbook.xml.rels"),p=[...a.matchAll(/<sheet\b[^>]*\bname="([^"]*)"[^>]*\br:id="([^"]+)"/g)].map(e=>[g(e[1]),e[2]]),l=e=>(new RegExp(`<Relationship\\b[^>]*\\bId="${e}"[^>]*\\bTarget="([^"]+)"`).exec(n)||new RegExp(`<Relationship\\b[^>]*\\bTarget="([^"]+)"[^>]*\\bId="${e}"`).exec(n)||[])[1]||"",r=[],c=p.length?p:Object.keys(t).filter(e=>/^xl\/worksheets\/sheet\d+\.xml$/.test(e)).map((e,i)=>[`Sheet${i+1}`,e]);for(const[e,i]of c){let m=p.length?l(i):i;p.length&&(m=m.startsWith("/")?m.slice(1):`xl/${m}`);const h=b(t,m);if(!h)continue;const x=v(h,o),A=x.slice(0,f).filter(u=>u.some(d=>d!=="")).map(u=>u.map(d=>d.replace(/\s+/g," ").trim()).join(" | "));r.push(`# ${e}
2
+ ${A.join(`
3
+ `)}${x.length>f?`
4
+ … ${x.length-f} more rows not shown`:""}`)}return r}async function N(s){const t=S(s),o=Object.keys(t).filter(n=>/^ppt\/slides\/slide\d+\.xml$/.test(n)).sort((n,p)=>Number(/slide(\d+)/.exec(n)[1])-Number(/slide(\d+)/.exec(p)[1])),a=[];for(const n of o){const l=[...b(t,n).matchAll(/<a:p\b[^>]*>([\s\S]*?)<\/a:p>/g)].map(e=>g([...e[1].matchAll(/<a:t>([\s\S]*?)<\/a:t>/g)].map(i=>i[1]).join("")).trim()).filter(Boolean),r=n.replace("slides/slide","notesSlides/notesSlide"),c=t[r]?[...b(t,r).matchAll(/<a:t>([\s\S]*?)<\/a:t>/g)].map(e=>g(e[1])).join(" ").trim():"";a.push(`${l.join(`
5
+ `)}${c?`
6
+
7
+ Speaker notes: ${c}`:""}`.trim())}return a}async function P(s,t){const o=S(s),a=b(o,"content.xml"),n=l=>g(String(l).replace(/<text:tab\/>/g," ").replace(/<text:s\b[^>]*\/>/g," ").replace(/<text:line-break\/>/g,`
8
+ `).replace(/<[^>]+>/g,""));if(t==="ods"){const l=[];for(const r of a.matchAll(/<table:table\b[^>]*\btable:name="([^"]*)"[^>]*>([\s\S]*?)<\/table:table>/g)){const c=[...r[2].matchAll(/<table:table-row\b[^>]*>([\s\S]*?)<\/table:table-row>/g)].map(e=>[...e[1].matchAll(/<table:table-cell\b[^>]*(?:\/>|>([\s\S]*?)<\/table:table-cell>)/g)].map(i=>n(i[1]||"").trim()).join(" | ")).filter(e=>e.replace(/[ |]/g,""));l.push(`# ${g(r[1])}
9
+ ${c.slice(0,f).join(`
10
+ `)}`)}return{pages:l}}if(t==="odp")return{pages:[...a.matchAll(/<draw:page\b[^>]*>([\s\S]*?)<\/draw:page>/g)].map(r=>[...r[1].matchAll(/<text:p\b[^>]*>([\s\S]*?)<\/text:p>/g)].map(c=>n(c[1]).trim()).filter(Boolean).join(`
11
+ `))};const p=[];for(const l of a.matchAll(/<text:(h|p)\b([^>]*)>([\s\S]*?)<\/text:\1>/g)){const r=Number((/text:outline-level="(\d+)"/.exec(l[2])||[])[1])||1,c=n(l[3]).trim();c&&p.push(l[1]==="h"?`${"#".repeat(Math.min(6,r))} ${c}`:c)}return{text:p.join(`
12
+
13
+ `)}}export{P as odfPages,N as pptxPages,E as xlsxPages};
@@ -0,0 +1 @@
1
+ import{pageTextFromItems as f,looksScanned as d}from"@chatpanel/events/pdf-layout.js";let a=null;function m(){return a||(a=import("pdfjs-dist/legacy/build/pdf.mjs").catch(o=>{throw a=null,o})),a}const h=1500;async function P(o,{maxPages:r=h}={}){const c=(await m()).getDocument({data:new Uint8Array(o),isEvalSupported:!1,disableFontFace:!0,useSystemFonts:!1,useWorkerFetch:!1,verbosity:0}),s=await c.promise;try{const l=await s.getMetadata().catch(()=>null),i=s.numPages,t=[];for(let e=1;e<=Math.min(i,r);e+=1){const n=await s.getPage(e);try{const g=await n.getTextContent(),u=n.getViewport({scale:1});t.push(f(g.items,{pageWidth:u.width}))}finally{n.cleanup()}}const p=l?.info||{};return{title:String(p.Title||"").trim(),pages:t,truncatedPages:i>t.length?i-t.length:0,scanned:d(t.map((e,n)=>({page:n+1,text:e})))}}finally{await c.destroy().catch(()=>{})}}export{h as PDF_MAX_PAGES,P as pdfPages};
@@ -0,0 +1,2 @@
1
+ import{spawn as S}from"node:child_process";import{createInterface as E}from"node:readline";import{tmpdir as _}from"node:os";import P from"node:path";import{fileURLToPath as I}from"node:url";const k=600*1e3,D=12e4,v=1e4;function L(){const d=process.execPath,f=P.basename(d).toLowerCase(),g=f.startsWith("node")||f.startsWith("bun"),h=I(new URL("../../bin/chatpanel-gateway.js",import.meta.url));return{program:d,args:[...g?[h]:[],"--extract-worker"]}}function G({wrap:d=null,idleMs:f=k,cacheDir:g=P.join(_(),"chatpanel-extract"),launch:h=L,onLog:T=()=>{}}={}){let a=null,w={layer:"none",reason:"not started"},B=0;const l=new Map;let c=null;const m=new Map,i={opens:0,msPerMB:[],pages:0};function M(){c&&clearTimeout(c),c=setTimeout(()=>x("idle"),f),c.unref&&c.unref()}function y(t){for(const[,n]of l)clearTimeout(n.timer),n.reject(Object.assign(new Error(t),{code:"worker_gone"}));l.clear()}async function O(){if(a)return a;const{program:t,args:n}=h();let r={bin:t,argv:n,opts:{stdio:["pipe","pipe","pipe"],env:{...process.env,NODE_OPTIONS:""}},record:{layer:"none",reason:"no sandbox runner in this gateway"}};if(typeof d=="function")try{r=await d(r.bin,r.argv,r.opts,{engine:"extract",cwd:g})}catch(e){r.record={layer:"none",reason:`sandbox: ${e?.message||e}`}}w=r.record||w,a=S(r.bin,r.argv,{...r.opts,stdio:["pipe","pipe","pipe"]});const o=a;return E({input:o.stdout,crlfDelay:1/0}).on("line",e=>{let s;try{s=JSON.parse(e)}catch{return}const u=l.get(s?.id);u&&(l.delete(s.id),clearTimeout(u.timer),s.ok?u.resolve(s):u.reject(Object.assign(new Error(s.error||"extract failed"),{code:s.code||"extract_error"})))}),o.stderr.on("data",e=>T(String(e).trim())),o.on("exit",(e,s)=>{a===o&&(a=null),m.clear(),y(`extract worker exited (${s||e})`)}),M(),o}function x(t="stopped"){c&&(clearTimeout(c),c=null);const n=a;if(a=null,m.clear(),n){try{n.stdin.end()}catch{}setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},3e3).unref?.()}y(`extract worker ${t}`)}async function b(t,n){const r=await O(),o=++B;return M(),new Promise((p,e)=>{const s=setTimeout(()=>{l.delete(o),e(Object.assign(new Error("extract timed out"),{code:"timeout"})),x("timed out")},n);l.set(o,{resolve:p,reject:e,timer:s}),r.stdin.write(`${JSON.stringify({id:o,...t})}
2
+ `)})}return{async open(t,{name:n="",hint:r=""}={}){const o=Date.now(),p=Buffer.isBuffer(t)?t.toString("base64"):Buffer.from(t).toString("base64"),e=await b({op:"open",name:n,hint:r,data:p},D),s=Date.now()-o,u=Math.max(.05,p.length*.75/(1024*1024));return i.opens+=1,i.msPerMB.push(s/u),i.msPerMB.length>50&&i.msPerMB.shift(),m.set(e.hash,{type:e.type,title:e.title,pages:e.pages,scanned:e.scanned,at:Date.now()}),{hash:e.hash,type:e.type,title:e.title,pages:e.pages,scanned:e.scanned,ms:s}},async page(t,n){const r=Date.now(),o=await b({op:"page",hash:t,page:n},v);return i.pages+=1,{text:o.text,pages:o.pages,type:o.type,ms:Date.now()-r}},known:t=>m.get(t)||null,predictMs(t){if(!i.msPerMB.length)return null;const n=[...i.msPerMB].sort((o,p)=>o-p),r=n[Math.floor(n.length/2)];return Math.round(r*Math.max(.05,t/(1024*1024)))},status(){const t=[...i.msPerMB].sort((n,r)=>n-r);return{running:!!a,pid:a?.pid||null,sandbox:w,open:m.size,stats:{opens:i.opens,pages:i.pages,msPerMBp50:t.length?Math.round(t[Math.floor(t.length/2)]):null}}},stop:x}}export{k as IDLE_MS,G as createExtractService,L as workerLaunch};
@@ -0,0 +1,3 @@
1
+ import{createInterface as c}from"node:readline";import{openDocument as p}from"./engine.js";const u=24,l=64*1024*1024,s=new Map;function h(n){const o=n.pages.reduce((e,t)=>e+t.length,0);s.delete(n.hash),s.set(n.hash,{...n,chars:o});let r=[...s.values()].reduce((e,t)=>e+t.chars,0);for(;s.size>u||r>l&&s.size>1;){const[e,t]=s.entries().next().value;s.delete(e),r-=t.chars}}async function d(n){const o=n?.id??null,r=(e,t)=>({id:o,ok:!1,code:e,error:t});try{if(n.op==="open"){const e=Buffer.from(String(n.data||""),"base64");if(!e.length)return r("invalid_request","no bytes");const t=await p(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),{name:n.name,hint:n.hint});return h(t),{id:o,ok:!0,hash:t.hash,type:t.type,title:t.title||"",pages:t.pages.length,scanned:!!t.scanned}}if(n.op==="page"){const e=s.get(String(n.hash||""));if(!e)return r("unknown_document","not open here — send the bytes again");const t=Number(n.page);return!Number.isInteger(t)||t<1||t>e.pages.length?r("invalid_request",`page must be 1–${e.pages.length}`):(s.delete(e.hash),s.set(e.hash,e),{id:o,ok:!0,text:e.pages[t-1],pages:e.pages.length,type:e.type})}return n.op==="status"?{id:o,ok:!0,docs:s.size,pid:process.pid}:r("invalid_request",`unknown op ${n.op}`)}catch(e){return r(e?.code==="unsupported"?"unsupported":"extract_error",e?.message||String(e))}}function f({input:n=process.stdin,output:o=process.stdout}={}){try{process.title="chatpanel-extract"}catch{}const r=c({input:n,crlfDelay:1/0});let e=Promise.resolve();r.on("line",t=>{if(!t.trim())return;let a;try{a=JSON.parse(t)}catch{o.write(`${JSON.stringify({id:null,ok:!1,code:"invalid_request",error:"not JSON"})}
2
+ `);return}e=e.then(()=>d(a)).then(i=>{o.write(`${JSON.stringify(i)}
3
+ `)})}),r.on("close",()=>process.exit(0))}process.argv[1]&&/worker\.js$/.test(process.argv[1])&&!process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED&&f();export{f as runExtractWorker};
@@ -0,0 +1,5 @@
1
+ import{EventError as h}from"@chatpanel/events/event.js";const b="/v1/extract",q="chatpanel-extract",y=64*1024*1024,A=6e3,R=Object.freeze(["pdf","docx","xlsx","pptx","odt","ods","odp","epub","md","txt","html","csv","text"]),x=t=>!!t&&typeof t=="object"&&!Array.isArray(t),f=t=>typeof t=="string"&&t.length>0,m=t=>typeof t=="number"&&Number.isFinite(t),i=(t,e)=>{if(!t)throw new h("SHAPE",e)},w=/^[0-9a-f]{64}$/;function O(t){i(x(t),"extract: body must be an object");const e={};if(t.budgetMs!=null&&(i(m(t.budgetMs)&&t.budgetMs>=0,"extract: budgetMs must be a number ≥ 0"),e.budgetMs=t.budgetMs),t.hash!=null)return i(typeof t.hash=="string"&&w.test(t.hash),"extract: hash must be 64 hex characters"),i(Number.isInteger(t.page)&&t.page>=1,"extract: page (integer ≥ 1) required with hash"),{kind:"page",hash:t.hash,page:t.page,...e};i(f(t.name),"extract: name required"),i(f(t.data),"extract: data (base64) required"),i(t.data.length<=Math.ceil(y*4/3)+4,"extract: document too large");const r={kind:"open",name:t.name,data:t.data,...e};return t.type!=null&&(i(f(t.type),"extract: type must be a non-empty string"),r.type=t.type.toLowerCase()),r}function E(t){return i(x(t),"extract: response must be an object"),i(typeof t.hash=="string"&&w.test(t.hash),"extract: hash (sha-256 hex) required"),i(Number.isInteger(t.pages)&&t.pages>=0,"extract: pages (integer ≥ 0) required"),i(f(t.type),"extract: type required"),i(f(t.provider),"extract: provider required"),i(m(t.ms)&&t.ms>=0,"extract: ms required"),t.page!=null&&(i(Number.isInteger(t.page)&&t.page>=1&&t.page<=Math.max(1,t.pages),"extract: page out of range"),i(typeof t.text=="string","extract: text (string, may be empty) required with page")),t.title!=null&&i(typeof t.title=="string","extract: title must be a string"),t}function S(t,{pageChars:e=A}={}){const r=String(t||"").replace(/\r\n?/g,`
2
+ `);if(!r.trim())return[];const s=[];let u=0;for(;u<r.length;){if(r.length-u<=e){s.push(r.slice(u));break}const c=r.slice(u,u+e),a=Math.floor(e*.6);let n=-1;const o=[...c.matchAll(/\n(?=#{1,6} |[A-Z][^\n]{0,80}\n[=-]{3,}\n)/g)].map(p=>p.index).filter(p=>p>=a);if(o.length&&(n=o[o.length-1]+1),n<0){const p=c.lastIndexOf(`
3
+
4
+ `);p>=a&&(n=p+2)}if(n<0){const p=c.lastIndexOf(`
5
+ `);p>=a&&(n=p+1)}n<0&&(n=e),s.push(r.slice(u,u+n)),u+=n}return s.map(c=>c.replace(/^\n+/,"")).filter(c=>c.trim())}function _({call:t,toBase64:e=M}={}){if(typeof t!="function")throw new h("SHAPE","gatewayExtractor: call required");const r=new Map;return async(s,{type:u="",name:c="document"}={})=>{const a=e(s),n=`${c}:${a.length}:${a.slice(0,64)}${a.slice(-64)}`;if(r.has(n))return r.get(n);let o;try{o=E(await t({name:c,...u?{type:u}:{},data:a}))}catch{return null}const p={hash:o.hash,type:o.type,pages:o.pages,title:o.title||"",async page(g){let l;try{l=E(await t({hash:o.hash,page:g}))}catch(d){throw r.delete(n),d}return l.text||""}};return r.set(n,p),p}}function M(t){typeof t=="string"&&(t=new TextEncoder().encode(t));const e=t instanceof Uint8Array?t:new Uint8Array(t);if(typeof Buffer<"u"&&Buffer.from)return Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64");let r="";for(let s=0;s<e.length;s+=32768)r+=String.fromCharCode.apply(null,e.subarray(s,s+32768));return btoa(r)}function I(...t){const e=t.filter(s=>typeof s=="function"),r=async(s,u,c)=>{for(let a=s;a<e.length;a+=1)try{const n=await e[a](u,c);if(n)return{doc:n,i:a}}catch{}return null};return async(s,u)=>{const c=await r(0,s,u);if(!c)return null;let{doc:a,i:n}=c;return{...a,get pages(){return a.pages},async page(o){try{return await a.page(o)}catch(p){const g=await r(n+1,s,u);if(!g)throw p;return{doc:a,i:n}=g,a.page(o)}}}}}export{q as EXTRACT_PROVIDER_ID,b as EXTRACT_ROUTE,R as EXTRACT_TYPES,y as MAX_DOCUMENT_BYTES,A as PAGE_CHARS,I as extractorChain,_ as gatewayExtractor,S as paginateText,O as validateExtractRequest,E as validateExtractResponse};
package/src/models.js CHANGED
@@ -1 +1 @@
1
- const l="Xenova/bert-base-NER",a=[{id:"Xenova/bert-base-NER",label:"English — standard",lang:"English",approxMB:105,note:"Default. Best English accuracy for people, organizations, and locations."},{id:"Xenova/distilbert-base-multilingual-cased-ner-hrl",label:"Multilingual — compact",lang:"10 languages",approxMB:150,note:"Covers en, es, fr, de, it, pt, nl, ar, zh, ru. Use for non-English text."},{id:"Xenova/bert-base-multilingual-cased-ner-hrl",label:"Multilingual — large",lang:"10 languages",approxMB:180,note:"Higher multilingual accuracy; larger download."},{id:"onnx-community/multilang-pii-ner-ONNX",label:"PII-specialised — multilingual",lang:"Multilingual",approxMB:282,mirrored:!1,recommended:!0,note:"Most thorough. Trained for PII rather than general entities: also finds addresses, postcodes, account and ID numbers, usernames and passwords. Larger download, fetched from Hugging Face."}];function o(n){const e=a.find(r=>r.id===n);return!!e&&e.mirrored!==!1}function t(n){return a.some(e=>e.id===n)}function i(n){const e=String(n||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(e)&&!e.includes("..")}export{l as DEFAULT_MODEL,a as MODEL_CATALOG,t as isKnownModel,o as isMirroredModel,i as isValidCustomModelId};
1
+ const t="Xenova/bert-base-NER",i=[{id:"Xenova/bert-base-NER",label:"English — standard",lang:"English",approxMB:105,note:"Default. Best English accuracy for people, organizations, and locations."},{id:"Xenova/distilbert-base-multilingual-cased-ner-hrl",label:"Multilingual — compact",lang:"10 languages",approxMB:150,note:"Covers en, es, fr, de, it, pt, nl, ar, zh, ru. Use for non-English text."},{id:"Xenova/bert-base-multilingual-cased-ner-hrl",label:"Multilingual — large",lang:"10 languages",approxMB:180,note:"Higher multilingual accuracy; larger download."},{id:"onnx-community/multilang-pii-ner-ONNX",label:"PII-specialised — multilingual",lang:"Multilingual",approxMB:282,mirrored:!1,note:"Trained for PII rather than general entities: finds addresses, postcodes, account and ID numbers, usernames and passwords. Cased text only — misses lowercase names. Fetched from Hugging Face."},{id:"openai/privacy-filter",label:"Privacy Filter — private people, addresses, secrets",lang:"English (some multilingual)",approxMB:1620,mirrored:!1,minRamMB:16384,ramMB:1e3,note:"Best at what redaction is for: finds private people (lowercase too), addresses, emails, phones, account numbers and passwords by context; skips public figures and places. Pair with a NER model for places and organisations. Large download from Hugging Face; needs about 1 GB of RAM while loaded."}];function l(a,{totalRamMB:e=0}={}){const r=n=>`${Math.round(n/1024)} GB`;return a.map(n=>{const o=Number(n.minRamMB)>0&&e>0&&e<n.minRamMB,s=n.recommended===!0||Number(n.minRamMB)>0&&e>=n.minRamMB;return{...n,recommended:s&&!o,...o?{ramNote:`needs about ${r(n.ramMB||1024)} of RAM while loaded — this machine has ${r(e)}; expect it to slow things down`}:{}}})}function d(a){const e=i.find(r=>r.id===a);return!!e&&e.mirrored!==!1}function u(a){return i.some(e=>e.id===a)}function c(a){const e=String(a||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(e)&&!e.includes("..")}export{t as DEFAULT_MODEL,i as MODEL_CATALOG,u as isKnownModel,d as isMirroredModel,c as isValidCustomModelId,l as recommendFor};
package/src/ner-engine.js CHANGED
@@ -1 +1 @@
1
- import $ from"node:os";import{join as _}from"node:path";import{existsSync as b,mkdirSync as E}from"node:fs";import{DEFAULT_MODEL as A,isMirroredModel as S}from"./models.js";import{isLoopbackHost as T,isPrivateHost as k,isMetadataHost as D}from"@chatpanel/pii";import{verifyModelWeights as P}from"./model-integrity.js";const L="https://dl.chatpanel.net/models/";function O(){const e=process.env.CHATPANEL_MODEL_BASE_URL;if(!e)return L;const t=s=>(console.warn(`[models] ignoring CHATPANEL_MODEL_BASE_URL (${e}): ${s} — using ${L}`),L);let n;try{n=new URL(e)}catch{return t("not a valid URL")}if(n.protocol!=="http:"&&n.protocol!=="https:")return t(`scheme ${n.protocol} not allowed`);if(D(n.hostname))return t("points at cloud metadata");const o=T(n.hostname)||k(n.hostname);return n.protocol==="http:"&&!o?t("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 ${L}`),e.replace(/\/*$/,"/"))}const R=O();let u="off",p=null,h=null,m=null,y=null,w=null,d=null;function x(){return process.env.CHATPANEL_MODELS_DIR||_($.homedir(),".chatpanel","models")}function N(e=p||A){const t=_(x(),...e.split("/"));return b(_(t,"onnx","model_quantized.onnx"))||b(_(t,"onnx","model.onnx"))}function Y(){return u}function v(){return u==="ready"&&!!h}function G(){return{configured:u!=="off",ok:v(),state:u,model:p,error:m}}async function C(e,{signal:t}={}){if(!v())return[];if(t?.aborted)return[];const n=String(e||""),o=await h(n,{aggregation_strategy:"simple"}),s=[];for(const f of o||[]){let l=String(f.word??"");const c=f.entity_group??f.entity??"ENTITY";if(l.startsWith("##")&&s.length&&s[s.length-1].type===c){s[s.length-1].value+=l.slice(2);continue}l=l.replace(/##/g,"").trim(),l&&s.push({value:l,type:c})}const r=new Set,i=[];for(const f of s){const l=U(n,f.value.trim());if(l.length<=1)continue;const c=`${f.type}:${l.toLowerCase()}`;r.has(c)||(r.add(c),i.push({value:l,type:f.type}))}return i}function U(e,t){if(!t)return t;const n=e.indexOf(t);if(n<0)return t;const o=i=>!!i&&/[\p{L}\p{N}'’-]/u.test(i);let s=n,r=n+t.length;for(;s>0&&o(e[s-1]);)s--;for(;r<e.length&&o(e[r]);)r++;return e.slice(s,r)}async function K(e,t={}){let n="";try{n=JSON.parse(t.body||"{}").text||""}catch{}const o=await C(n,{signal:t.signal});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function Q(){return d}async function W(){if(w)return w;const e=x();try{E(e,{recursive:!0})}catch{}const t=globalThis.__CHATPANEL_WASM_PATHS__||null;if(t)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}const{env:n,pipeline:o,Tensor:s,AutoModel:r,AutoProcessor:i}=await import("@huggingface/transformers");n.cacheDir=e,n.localModelPath=e;try{n.remoteHost=R}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(t)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=t}catch{}return w={env:n,pipeline:o,Tensor:s,AutoModel:r,AutoProcessor:i},w}async function M(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=h,s=p;let r;try{r=await W()}catch(c){return u="error",m=`engine load failed: ${c.message}`,t(`[ner] transformers.js not available (${c.message}) — deterministic-only`),!1}const i=N(e);if(r.env.allowRemoteModels=i?!1:!!n,!i&&!n)return u="error",m="model not on disk and downloads disabled",t(`[ner] model ${e} not installed and downloads disabled — deterministic-only`),!1;const f=r.env.remoteHost,l=!S(e);if(!i&&l)try{r.env.remoteHost="https://huggingface.co/"}catch{}u=i?"loading":"downloading",i||(d={model:e,file:null,pct:0},t(`[ner] downloading model ${e} (one-time${l?", from Hugging Face":""})…`));try{const c=a=>{if(!a)return;const H=typeof a.progress=="number"?Math.round(a.progress):d?.pct??0;a.status==="progress"||a.status==="download"||a.status==="initiate"?d={model:e,file:a.file||d?.file||null,pct:H}:a.status==="done"&&a.file&&t(`[ner] fetched ${a.file}`)};let g;try{g=await r.pipeline("token-classification",e,{dtype:"q8",progress_callback:c})}catch(a){if(i||l||!n)throw a;t(`[ner] mirror fetch failed (${String(a.message).slice(0,80)}) — retrying from Hugging Face…`),r.env.remoteHost="https://huggingface.co/",r.env.allowRemoteModels=!0,g=await r.pipeline("token-classification",e,{dtype:"q8",progress_callback:c})}if(!i)try{P(e,{modelsDir:x(),log:t})}catch(a){try{await g.dispose?.()}catch{}throw a}if(h=g,p=e,u="ready",m=null,d=null,o&&o!==g)try{await o.dispose?.()}catch{}return t(`[ner] ready — model ${e} (in-process, no Python) — entity detection active`),!0}catch(c){return m=c.message,d=null,o?(h=o,p=s,u="ready"):u="error",t(`[ner] model load failed (${c.message})${o?" — keeping previous model":" — deterministic-only"}`),!1}finally{try{r.env.remoteHost=f}catch{}}}function V(e={}){if(y)return y;const t=typeof e.onLog=="function"?e.onLog:()=>{};return p=e.model||A,u="loading",y=M(p,{log:t,allowDownload:e.allowDownload!==!1}),y}async function X(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{},o=t.allowDownload!==!1;return e?e===p&&v()?!0:M(e,{log:n,allowDownload:o}):!1}function Z(){u="off",p=null,h=null,m=null,y=null,w=null,d=null}export{Z as _reset,C as detect,W as ensureLib,K as fetchAdapter,G as health,V as init,v as isReady,N as modelOnDisk,x as modelRoot,Q as progress,O as resolveModelHost,X as setModel,Y as state};
1
+ import G from"node:os";import{join as b}from"node:path";import{existsSync as W,mkdirSync as V,readdirSync as U,readFileSync as K}from"node:fs";import{DEFAULT_MODEL as j,isMirroredModel as Q}from"./models.js";import{isLoopbackHost as X,isPrivateHost as Z,isMetadataHost as I}from"@chatpanel/pii";import{recaseForDetection as tt}from"@chatpanel/pii/pii-detect.js";import{verifyModelWeights as et}from"./model-integrity.js";import{runtimeName as nt}from"./model-runtime.js";const O="https://dl.chatpanel.net/models/";function rt(){const t=process.env.CHATPANEL_MODEL_BASE_URL;if(!t)return O;const e=r=>(console.warn(`[models] ignoring CHATPANEL_MODEL_BASE_URL (${t}): ${r} — using ${O}`),O);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(I(n.hostname))return e("points at cloud metadata");const o=X(n.hostname)||Z(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 ${O}`),t.replace(/\/*$/,"/"))}const ot=rt();let d="off",h=null,m=null,_=null,L=null,S=null,x=null;const g=new Map;function T(){return process.env.CHATPANEL_MODELS_DIR||b(G.homedir(),".chatpanel","models")}function k(t=h||j){const e=b(T(),...t.split("/"));return W(b(e,"onnx","model_quantized.onnx"))||W(b(e,"onnx","model.onnx"))}function $t(){const t=T(),e=[];try{for(const n of U(t,{withFileTypes:!0}))if(n.isDirectory())for(const o of U(b(t,n.name),{withFileTypes:!0})){if(!o.isDirectory())continue;const r=`${n.name}/${o.name}`;k(r)&&st(b(t,n.name,o.name))&&e.push(r)}}catch{}return e}function st(t){try{return(JSON.parse(K(b(t,"config.json"),"utf8")).architectures||[]).some(n=>/ForTokenClassification$/.test(String(n)))}catch{return!1}}function At(){return d}function $(){return d==="ready"&&!!m}function vt(){return{configured:d!=="off",ok:$(),state:d,model:h,error:_,runtime:nt(),dtype:m?"q8":null,stats:yt(),companions:ut()}}async function it(t,{signal:e}={}){if(!$())return[];if(e?.aborted)return[];const n=String(t||""),o=await q(n,e);if(!o)return[];const r=[];for(const c of o||[]){let a=String(c.word??"");const p=c.entity_group??c.entity??"ENTITY";if(a.startsWith("##")&&r.length&&r[r.length-1].type===p){r[r.length-1].value+=a.slice(2);continue}a=a.replace(/##/g,"").trim(),a&&r.push({value:a,type:p})}const s=new Set,i=[];for(const c of r){const a=_t(n,wt(n,c.value.trim()));if(a.length<=1)continue;const p=`${c.type}:${a.toLowerCase()}`;s.has(p)||(s.add(p),i.push({value:a,type:c.type}))}return i}async function q(t,e){const n=performance.now(),o=[],r=[{text:t,key:"orig"}];if(A){const s=tt(t);s.changed&&r.push({text:s.text,key:"recased"})}for(const{model:s,pipe:i}of pt())for(const c of r){let a=0;for(const p of ht(c.text,i.tokenizer)){if(e?.aborted)return null;const u=c.text.indexOf(p,a),l=await i(p,{aggregation_strategy:"simple"});for(const f of l||[])o.push({...f,_win:u<0?a:u,_winText:p,_model:s,_pass:c.key,_passText:c.text});u>=0&&(a=Math.max(a,u+1))}}return gt(performance.now()-n,t.length,o.length),o}let A=!0;function Et(t){A=t!==!1}async function Nt(t,{signal:e}={}){if(!$())return[];const n=String(t||""),o=await q(n,e);if(!o)return[];const r=[],s=new Set;let i=-1,c=-1,a=null,p=null;for(const l of o){const f=String(l.word??"").replace(/##/g,"").trim();if(!f)continue;(l._win!==c||l._model!==a||l._pass!==p)&&(c=l._win,a=l._model,p=l._pass,i=l._win);const P=l._passText||n;let w=P.indexOf(f,i);if(w<0&&(w=P.indexOf(f,l._win)),w<0)continue;let M=w+f.length;i=M;const H=F=>!!F&&/[\p{L}\p{N}'’-]/u.test(F);for(;w>0&&H(n[w-1]);)w--;for(;M<n.length&&H(n[M]);)M++;const D=String(l.entity_group??l.entity??"ENTITY"),R=`${w}:${M}:${D}`;if(s.has(R))continue;s.add(R);const C=Number(l.score);r.push({value:n.slice(w,M),type:D,start:w,end:M,score:Number.isFinite(C)?Math.max(0,Math.min(1,C)):1,model:l._model})}r.sort((l,f)=>l.start-f.start||l.end-f.end);const u=[];for(const l of r){const f=u[u.length-1];if(f&&f.type===l.type&&f.end===l.start){f.end=l.end,f.value=n.slice(f.start,f.end),f.score=Math.min(f.score,l.score);continue}u.push({...l})}return g.size||A?lt(u):u}const z=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function at(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 v(t){const e=z.indexOf(at(t.type));return e<0?z.length:e}let E=[];function ct(t){E=Array.isArray(t)?t.slice():[]}function N(t){if(t.model===h)return-1;const e=E.indexOf(t.model);return e<0?E.length:e}function lt(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=c=>c.end-c.start;(v(o)<v(r)||v(o)===v(r)&&(s(o)>s(r)||s(o)===s(r)&&(N(o)<N(r)||N(o)===N(r)&&o.score>r.score)))&&(n[n.length-1]=o);continue}n.push(o)}return n}function Pt(){const t=m?.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 Ht(){const t=Number(m?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function ut(){return[...g].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function ft(t,{log:e=()=>{},allowDownload:n=!0}={}){if(!t||t===h)return!1;if(g.get(t)?.pipe)return!0;g.set(t,{pipe:null,state:k(t)?"loading":"downloading",error:null});try{const{pipe:r}=await Y(t,{log:e,allowDownload:n});return g.set(t,{pipe:r,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(r){return g.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 Dt(t){const e=g.get(t);if(!e)return!1;g.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function pt(){const t=m?[{model:h,pipe:m}]:[];for(const[e,n]of g)n.pipe&&t.push({model:e,pipe:n.pipe});return t}const dt=160;function ht(t,e){const n=Number(e?.model_max_length);if(!t||!Number.isFinite(n)||n<=0||n>65536)return[t];const o=n-8,r=a=>{try{return e(a).input_ids.dims[1]}catch{return 1/0}};if(r(t)<=o)return[t];const s=[];let i=0,c=Math.max(64,Math.floor(o*3));for(;i<t.length;){let a=Math.min(t.length,i+c);if(a<t.length){const f=t.lastIndexOf(" ",a);f>i+c/2&&(a=f)}let p=t.slice(i,a);for(;r(p)>o&&p.length>32;){c=Math.max(32,Math.floor(p.length/2)),a=i+c;const f=t.lastIndexOf(" ",a);f>i+c/2&&(a=f),p=t.slice(i,a)}if(s.push(p),a>=t.length)break;const u=Math.max(i+1,a-dt),l=t.indexOf(" ",u);i=l>0&&l<a?l+1:a}return s}const mt=200,y=[];function gt(t,e,n){y.push({ms:t,chars:e,spans:n}),y.length>mt&&y.shift()}function yt(){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 wt(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 _t(t,e){if(!e)return e;const n=t.indexOf(e);if(n<0)return e;const o=i=>!!i&&/[\p{L}\p{N}'’-]/u.test(i);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 Rt(t,e={}){let n="";try{n=JSON.parse(e.body||"{}").text||""}catch{}const o=await it(n,{signal:e.signal});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function Ct(){return x}async function B(){if(S)return S;const t=T();try{V(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{}const{env:n,pipeline:o,Tensor:r,AutoModel:s,AutoProcessor:i}=await import("@huggingface/transformers");n.cacheDir=t,n.localModelPath=t;try{n.remoteHost=ot}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 S={env:n,pipeline:o,Tensor:r,AutoModel:s,AutoProcessor:i},S}async function Y(t,{log:e=()=>{},allowDownload:n=!0,onProgress:o=()=>{}}={}){const r=await B(),s=k(t);if(r.env.allowRemoteModels=s?!1:!!n,!s&&!n)throw new Error("model not on disk and downloads disabled");const i=r.env.remoteHost,c=!Q(t);if(!s&&c)try{r.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${c?", from Hugging Face":""})…`);try{const a=u=>{u&&(u.status==="progress"||u.status==="download"||u.status==="initiate"?o(u):u.status==="done"&&u.file&&e(`[ner] fetched ${u.file}`))};let p;try{p=await r.pipeline("token-classification",t,{dtype:"q8",progress_callback:a})}catch(u){if(s||c||!n)throw u;e(`[ner] mirror fetch failed (${String(u.message).slice(0,80)}) — retrying from Hugging Face…`),r.env.remoteHost="https://huggingface.co/",r.env.allowRemoteModels=!0,p=await r.pipeline("token-classification",t,{dtype:"q8",progress_callback:a})}if(!s)try{et(t,{modelsDir:T(),log:e})}catch(u){try{await p.dispose?.()}catch{}throw u}return{pipe:p,haveLocal:s}}finally{try{r.env.remoteHost=i}catch{}}}async function J(t,{log:e=()=>{},allowDownload:n=!0}={}){const o=m,r=h;try{await B()}catch(i){return d="error",_=`engine load failed: ${i.message}`,e(`[ner] transformers.js not available (${i.message}) — deterministic-only`),!1}const s=k(t);if(!s&&!n)return d="error",_="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;d=s?"loading":"downloading",s||(x={model:t,file:null,pct:0});try{const{pipe:i}=await Y(t,{log:e,allowDownload:n,onProgress:c=>{x={model:t,file:c.file||x?.file||null,pct:typeof c.progress=="number"?Math.round(c.progress):x?.pct??0}}});if(m=i,h=t,d="ready",_=null,x=null,o&&o!==i)try{await o.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),!0}catch(i){return _=i.message,x=null,o?(m=o,h=r,d="ready"):d="error",e(`[ner] model load failed (${i.message})${o?" — keeping previous model":" — deterministic-only"}`),!1}}function Ft(t={}){if(L)return L;const e=typeof t.onLog=="function"?t.onLog:()=>{};h=t.model||j,d="loading";const n=t.allowDownload!==!1;return L=J(h,{log:e,allowDownload:n}).then(async o=>{const r=Array.isArray(t.union)?t.union:[];ct(r);for(const s of r)await ft(s,{log:e,allowDownload:n});return o}),L}async function Wt(t,e={}){const n=typeof e.onLog=="function"?e.onLog:()=>{},o=e.allowDownload!==!1;if(!t)return!1;if(t===h&&$())return!0;const r=g.get(t);if(r?.pipe){const s=m;if(m=r.pipe,h=t,d="ready",_=null,g.delete(t),s)try{await s.dispose?.()}catch{}return n(`[ner] ${t} promoted from the union to primary`),!0}return J(t,{log:n,allowDownload:o})}function Ut(){d="off",h=null,m=null,_=null,L=null,S=null,x=null,y.length=0,g.clear(),A=!0,E=[]}function jt(t,e){g.set(t,{pipe:e,state:"ready",error:null})}function qt(t,{model:e="test/model"}={}){m=t,h=e,d="ready",_=null,y.length=0}export{Ut as _reset,jt as _setCompanionForTest,qt as _setForTest,ft as addCompanion,ut as companions,it as detect,Nt as detectSpans,B as ensureLib,Rt as fetchAdapter,vt as health,Ft as init,$ as isReady,Pt as labels,Ht as maxTokens,k as modelOnDisk,T as modelRoot,$t as modelsOnDisk,Ct as progress,Dt as removeCompanion,rt as resolveModelHost,Et as setCaseRecovery,Wt as setModel,ct as setUnionOrder,At as state,yt as stats,lt as unionSpans,ht as windowsFor};
package/src/ner.js CHANGED
@@ -1 +1 @@
1
- import*as o from"./ner-engine.js";import{persistConfig as d,configPath as c}from"./configstore.js";function u(e){const n=e.ner;if(!n||!n.autostart)return null;const r=e.redaction?.detection;if(r&&r.url&&/127\.0\.0\.1:9009\/ner/.test(r.url)){e.redaction.detection={backend:"off"},e.ner&&delete e.ner.port;try{d(e,c())}catch{}console.log("[ner] migrated legacy spaCy detector config (:9009) → in-process engine")}const t=e.redaction?.detection;if(t&&t.backend&&t.backend!=="off")return n.enableFullTier&&e.redaction.tier!=="full"&&(e.redaction.tier="full"),console.log(`[ner] using configured detector (${t.backend} ${t.url||""}) — full tier ${e.redaction.tier==="full"?"on":"off"}`),null;let i=!1;return o.init({model:n.model,allowDownload:n.allowDownload!==!1,onLog:l=>{i||console.log(l)}}).then(()=>{i||o.isReady()&&n.enableFullTier&&e.redaction.tier!=="full"&&(e.redaction.tier="full",console.log("[ner] full tier on — name/org redaction active"))}).catch(l=>{i||console.log(`[ner] init error (${l.message}) — deterministic-only`)}),{stop(){i=!0}}}async function f(e,{log:n=r=>console.log(r)}={}){const r=e?.redaction?.detection;if(r&&r.backend&&r.backend!=="off")return"external";const t=o.state();if(t==="ready")return t;if(t==="loading"||t==="downloading"||t==="error"){try{await o.init()}catch{}return o.state()}const i=e?.ner||{},l=i.model||void 0;if(!o.modelOnDisk(l))return"not-downloaded";try{await o.init({model:l,allowDownload:!1,onLog:n})}catch(a){return n(`[ner] on-demand load failed (${a.message}) — deterministic-only`),o.state()}return o.isReady()&&(n(`[ner] started on demand — model ${o.health().model} — entity detection active`),i.enableFullTier!==!1&&e.redaction&&e.redaction.tier!=="full"&&(e.redaction.tier="full",n("[ner] full tier on — name/org redaction active"))),o.state()}export{f as ensureNer,u as startNer};
1
+ import c from"node:os";import*as i from"./ner-engine.js";import{persistConfig as u,configPath as f}from"./configstore.js";import{MODEL_CATALOG as m}from"./models.js";import{fitUnion as p}from"@chatpanel/pii/detector-router.js";function a(e,{totalRamMB:n=Math.round(c.totalmem()/1048576),log:l=()=>{}}={}){const t=Array.isArray(e?.union)?e.union.filter(o=>o&&o!==e.model):[],r=p(e?.model,t,m,{totalRamMB:n});for(const o of r.skipped)l(`[ner] not loading ${o.id} — ${o.why}`);return d=r.skipped,r.load}let d=[];function b(){return d.slice()}function $(e){const n=e.ner;if(!n||!n.autostart)return null;const l=e.redaction?.detection;if(l&&l.url&&/127\.0\.0\.1:9009\/ner/.test(l.url)){e.redaction.detection={backend:"off"},e.ner&&delete e.ner.port;try{u(e,f())}catch{}console.log("[ner] migrated legacy spaCy detector config (:9009) → in-process engine")}const t=e.redaction?.detection;if(t&&t.backend&&t.backend!=="off")return n.enableFullTier&&e.redaction.tier!=="full"&&(e.redaction.tier="full"),console.log(`[ner] using configured detector (${t.backend} ${t.url||""}) — full tier ${e.redaction.tier==="full"?"on":"off"}`),null;let r=!1;return i.setCaseRecovery(n.caseRecovery!==!1),i.init({model:n.model,union:a(n,{log:o=>console.log(o)}),allowDownload:n.allowDownload!==!1,onLog:o=>{r||console.log(o)}}).then(()=>{r||i.isReady()&&n.enableFullTier&&e.redaction.tier!=="full"&&(e.redaction.tier="full",console.log("[ner] full tier on — name/org redaction active"))}).catch(o=>{r||console.log(`[ner] init error (${o.message}) — deterministic-only`)}),{stop(){r=!0}}}async function g(e,{log:n=l=>console.log(l)}={}){const l=e?.redaction?.detection;if(l&&l.backend&&l.backend!=="off")return"external";const t=i.state();if(t==="ready")return t;if(t==="loading"||t==="downloading"||t==="error"){try{await i.init()}catch{}return i.state()}const r=e?.ner||{},o=r.model||void 0;if(!i.modelOnDisk(o))return"not-downloaded";try{await i.init({model:o,union:a({...r,model:o},{log:n}),allowDownload:!1,onLog:n})}catch(s){return n(`[ner] on-demand load failed (${s.message}) — deterministic-only`),i.state()}return i.isReady()&&(n(`[ner] started on demand — model ${i.health().model} — entity detection active`),r.enableFullTier!==!1&&e.redaction&&e.redaction.tier!=="full"&&(e.redaction.tier="full",n("[ner] full tier on — name/org redaction active"))),i.state()}export{g as ensureNer,b as skippedCompanions,$ as startNer,a as unionForThisMachine};
@@ -1 +1 @@
1
- import{join as u}from"node:path";import{existsSync as O,mkdirSync as Z,readFileSync as P,statSync as L,createWriteStream as rt,renameSync as at}from"node:fs";import{Readable as ct}from"node:stream";import{modelRoot as lt}from"./ner-engine.js";import{SentencePieceUnigram as ft}from"./sentencepiece.js";import{getOrt as ht,ortProviders as mt}from"./ort.js";const dt="KevinAHM/pocket-tts-onnx",ut="KevinAHM/pocket-tts-web",F="english_2026-04",G=24e3,pt=500,v=1,wt=.7,_t=-4,J=3,X=12,gt=!0,Q=(s="_int8")=>["bundle.json","tokenizer.model","bos_before_voice.npy",`text_conditioner${s}.onnx`,`mimi_encoder${s}.onnx`,`mimi_decoder${s}.onnx`,`flow_lm_main${s}.onnx`,`flow_lm_flow${s}.onnx`],I="voices.bin";function C(s=F){return u(lt(),"pocket-tts",s)}function Ut(s=F,n="_int8"){const t=C(s);try{return Q(n).every(e=>{const o=u(t,e);return O(o)&&L(o).size>0})}catch{return!1}}async function q(s,n,t,{onProgress:e,log:o}={}){const r=n===I?`https://huggingface.co/spaces/${ut}/resolve/main/onnx/${s}/${n}`:`https://huggingface.co/${dt}/resolve/main/onnx/${s}/${n}`,i=await fetch(r,{redirect:"follow"});if(!i.ok||!i.body)throw new Error(`fetch ${n} → HTTP ${i.status}`);const a=Number(i.headers.get("content-length"))||0,h=u(t,`${n}.part`),m=rt(h);let f=0,c=-1;const w=ct.fromWeb(i.body);w.on("data",d=>{if(f+=d.length,a){const l=Math.round(f/a*100);l!==c&&(c=l,e?.({file:n,pct:l}))}}),await new Promise((d,l)=>{w.pipe(m),m.on("finish",d),m.on("error",l),w.on("error",l)}),at(h,u(t,n)),o?.(`[pocket-tts] fetched ${n}`)}async function yt(s=F,n="_int8",{onProgress:t,log:e}={}){const o=C(s);Z(o,{recursive:!0});for(const r of Q(n)){const i=u(o,r);O(i)&&L(i).size>0||(e?.(`[pocket-tts] downloading ${r}…`),await q(s,r,o,{onProgress:t,log:e}))}return o}async function bt(s=F,{onProgress:n,log:t}={}){const e=C(s),o=u(e,I);return O(o)&&L(o).size>1024||(Z(e,{recursive:!0}),t?.(`[pocket-tts] downloading ${I} (built-in voices, ~52 MB)…`),await q(s,I,e,{onProgress:n,log:t})),o}function tt(s=F){try{const n=u(C(s),I);return O(n)&&L(n).size>1024}catch{return!1}}function At(s){const n=[147,78,85,77,80,89];for(let c=0;c<n.length;c++)if(s[c]!==n[c])throw new Error("not an NPY file");const t=new DataView(s.buffer,s.byteOffset,s.byteLength),e=t.getUint8(6),o=e===1?t.getUint16(8,!0):t.getUint32(8,!0),r=e===1?10:12,i=new TextDecoder().decode(s.subarray(r,r+o)),a=/\(\s*([0-9,\s]*)\)/.exec(i);if(!a)throw new Error("could not parse NPY shape");const h=a[1].split(",").map(c=>c.trim()).filter(Boolean).map(c=>parseInt(c,10)),m=r+o,f=new Float32Array((s.byteLength-m)/4);for(let c=0;c<f.length;c++)f[c]=t.getFloat32(m+c*4,!0);return{data:f,shape:h}}function et(s,n,t){const e=s.reduce((r,i)=>r*i,1);if(n==="int64")return new BigInt64Array(e);if(n==="bool")return new Uint8Array(e);const o=new Float32Array(e);return t==="nan"?o.fill(NaN):t==="ones"&&o.fill(1),o}function R(s,n){const t={};for(const e of n)t[e.input_name]=new s.Tensor(e.dtype,et(e.shape,e.dtype,e.fill),e.shape);return t}function z(s,n,t){for(const e of t)s[e.input_name]=n[e.output_name]}function xt(s){const n=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),t=new DataView(n);let e=0;const o=new TextDecoder().decode(new Uint8Array(n,0,5));if(e+=5,o!=="PTVB1")throw new Error("not a voices.bin (bad header)");const r={},i=t.getUint32(e,!0);e+=4;for(let a=0;a<i;a++){const h=t.getUint16(e,!0);e+=2;const m=new TextDecoder().decode(new Uint8Array(n,e,h));e+=h;const f=t.getUint16(e,!0);e+=2;const c={};for(let w=0;w<f;w++){const d=t.getUint16(e,!0);e+=2;const l=new TextDecoder().decode(new Uint8Array(n,e,d));e+=d;const p=t.getUint8(e);e+=1;const S=t.getUint8(e);e+=1;const D=[];for(let _=0;_<S;_++)D.push(t.getUint32(e,!0)),e+=4;const U=t.getUint32(e,!0);e+=4;const k=n.slice(e,e+U),M=p===0?new Float32Array(k):p===1?new BigInt64Array(k):p===2?new Uint8Array(k):(()=>{throw new Error(`unsupported voices.bin dtype ${p}`)})();e+=U,c[l]={data:M,shape:D,dtype:p===0?"float32":p===1?"int64":"bool"}}r[m]=c}return r}function kt(s){const n={};for(const[t,e]of Object.entries(s)){const o=t.indexOf("/");o!==-1&&((n[t.slice(0,o)]||={})[t.slice(o+1)]=e)}return n}function Et(s){return s.step?{data:BigInt64Array.from([BigInt(s.step.data[0])]),shape:[1],dtype:"int64"}:s.offset&&!s.end_offset?{data:BigInt64Array.from([BigInt(s.offset.data[0])]),shape:[1],dtype:"int64"}:s.current_end?{data:BigInt64Array.from([BigInt(s.current_end.shape[0])]),shape:[1],dtype:"int64"}:{data:BigInt64Array.from([0n]),shape:[1],dtype:"int64"}}function Tt(s,n){const t=et(n.shape,n.dtype,n.fill),e=n.shape.reduce((f,c)=>f*c,1),o=n.dtype==="int64"?BigInt64Array:n.dtype==="bool"?Uint8Array:Float32Array,r=s.shape.length===n.shape.length;if(r&&s.shape.every((f,c)=>f===n.shape[c])||s.data.length===e)return new o(s.data);if(!r)return t;const i=[];let a=1;for(let f=s.shape.length-1;f>=0;f--)i[f]=a,a*=s.shape[f];const h=new Array(s.shape.length).fill(0),m=s.shape.map((f,c)=>Math.min(f,n.shape[c]));if(m.some(f=>f===0))return t;for(;;){let f=0;for(let l=0;l<h.length;l++)f+=h[l]*i[l];let c=0,w=1;for(let l=n.shape.length-1;l>=0;l--)c+=h[l]*w,w*=n.shape[l];t[c]=s.data[f];let d=h.length-1;for(;d>=0&&!(++h[d]<m[d]);d--)if(h[d]=0,d===0)return t;if(d<0)return t}}class Mt{constructor(){this.ready=!1,this.bundle=null,this.meta=null,this.tok=null,this.bos=null,this.sessions=null,this.st=null,this.latentDim=32,this.condDim=1024,this.samplesPerFrame=1920,this.builtin=null}builtinVoices(){return this.builtin?Object.keys(this.builtin).sort():[]}async load(n=F,{quant:t="_int8",onProgress:e,log:o=()=>{}}={}){const r=await yt(n,t,{onProgress:e,log:o});if(!tt(n))try{await bt(n,{onProgress:e,log:o})}catch(l){o(`[pocket-tts] built-in voices not downloaded (${l.message}) — cloning still works`)}const i=await ht();this.meta=JSON.parse(P(u(r,"bundle.json"),"utf8")),this.tok=new ft(new Uint8Array(P(u(r,"tokenizer.model")))),this.bos=this.meta.insert_bos_before_voice?At(P(u(r,"bos_before_voice.npy"))):null,this.latentDim=Number(this.meta.latent_dim)||32,this.condDim=Number(this.meta.conditioning_dim)||1024,this.samplesPerFrame=Math.round(G/(Number(this.meta.frame_rate)||12.5));const a={executionProviders:mt(),graphOptimizationLevel:"all",logSeverityLevel:3},[h,m,f,c,w]=await Promise.all([i.InferenceSession.create(u(r,`text_conditioner${t}.onnx`),a),i.InferenceSession.create(u(r,`mimi_encoder${t}.onnx`),a),i.InferenceSession.create(u(r,`mimi_decoder${t}.onnx`),a),i.InferenceSession.create(u(r,`flow_lm_main${t}.onnx`),a),i.InferenceSession.create(u(r,`flow_lm_flow${t}.onnx`),a)]);this.sessions={ort:i,textConditioner:h,mimiEncoder:m,mimiDecoder:f,flowMain:c,flowFlow:w},this.st=[];const d=1/v;for(let l=0;l<v;l++){const p=l/v;this.st.push({s:new i.Tensor("float32",new Float32Array([p]),[1,1]),t:new i.Tensor("float32",new Float32Array([p+d]),[1,1])})}try{tt(n)&&(this.builtin=xt(P(u(r,"voices.bin"))))}catch(l){o(`[pocket-tts] built-in voices unavailable (${l.message})`)}return this.bundle=n,this.ready=!0,o(`[pocket-tts] ready — ${n} (${t.replace("_","")||"fp32"}, ${G} Hz)`),!0}async encodeVoice(n){if(!this.ready)throw new Error("pocket-tts not loaded");const{ort:t,mimiEncoder:e}=this.sessions,o=n instanceof Float32Array?n:Float32Array.from(n),i=(await e.run({audio:new t.Tensor("float32",o,[1,1,o.length])}))[e.outputNames[0]];let a=i.dims.slice();for(;a.length>3&&a[0]===1;)a=a.slice(1);return a.length<3&&(a=[1,a[0],a[1]]),{data:Float32Array.from(i.data),shape:a}}#t(n){const{ort:t}=this.sessions;let e=n.data instanceof Float32Array?n.data:Float32Array.from(n.data),o=n.shape.slice();if(this.meta.insert_bos_before_voice&&this.bos){const r=new Float32Array(this.bos.data.length+e.length);r.set(this.bos.data,0),r.set(e,this.bos.data.length),e=r,o=[1,o[1]+this.bos.shape[1],o[2]]}return new t.Tensor("float32",e,o)}#e(n){const t=this.builtin?.[n];if(!t)throw new Error(`unknown built-in voice: ${n}`);const{ort:e}=this.sessions,o=kt(t),r=R(e,this.meta.flow_lm_state_manifest);for(const i of this.meta.flow_lm_state_manifest){const a=o[i.module]||{},h=a[i.key]||(i.key==="step"?Et(a):null);h&&(r[i.input_name]=new e.Tensor(i.dtype,Tt(h,i),i.shape))}return r}async#n(n){const{ort:t,flowMain:e}=this.sessions,o=R(t,this.meta.flow_lm_state_manifest),r=await e.run({sequence:new t.Tensor("float32",new Float32Array(0),[1,0,this.latentDim]),text_embeddings:this.#t(n),...o});return z(o,r,this.meta.flow_lm_state_manifest),o}#o(n){let t=String(n).replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim();if(!t)return{text:"",framesAfterEos:1};this.meta.remove_semicolons&&(t=t.replace(/;/g,","));const e=t.split(/\s+/).filter(Boolean).length;let o=e<=4?3:1;return this.meta.model_recommended_frames_after_eos!=null&&(o=Number(this.meta.model_recommended_frames_after_eos)),/[A-ZÀ-Þ]/.test(t[0])||(t=t[0].toUpperCase()+t.slice(1)),/[0-9A-Za-zÀ-ÿ]/.test(t[t.length-1])&&(t+="."),this.meta.pad_with_spaces_for_short_inputs&&e<5&&(t=` ${t}`),{text:t,framesAfterEos:o}}#s(n){const t=Number(this.meta.max_token_per_chunk)||50,e=n.match(/[^.!?]+[.!?]+|[^.!?]+$/g)||[n],o=[];for(const r of e){const i=r.trim();if(!i)continue;const a=this.tok.encodeIds(i);if(a.length<=t){o.push(i);continue}for(let h=0;h<a.length;h+=t){const m=this.tok.decodeIds(a.slice(h,h+t)).trim();m&&o.push(m)}}return o.length?o:[n]}async synth(n,{voice:t,onAudio:e=null}={}){if(!this.ready)throw new Error("pocket-tts not loaded");if(typeof t=="string"){if(!this.builtin?.[t])throw new Error(`unknown built-in voice: ${t}`)}else if(!t?.data?.length)throw new Error("pocket-tts needs a voice — record one, or pick a built-in");const{ort:o,textConditioner:r,flowMain:i,flowFlow:a,mimiDecoder:h}=this.sessions,m=this.#o(n);if(!m.text)return new Float32Array(0);const f=this.#s(m.text),c=typeof t=="string"?this.#e(t):await this.#n(t),w=new o.Tensor("float32",new Float32Array(0),[1,0,this.latentDim]),d=new o.Tensor("float32",new Float32Array(0),[1,0,this.condDim]);let l=R(o,this.meta.mimi_state_manifest),p={...c};const S=[];let D=!0;for(let _=0;_<f.length;_++){gt&&_>0&&(p={...c},l=R(o,this.meta.mimi_state_manifest));const B=this.tok.encodeIds(f[_]),nt=new o.Tensor("int64",BigInt64Array.from(B,T=>BigInt(T)),[1,B.length]);let E=(await r.run({token_ids:nt}))[r.outputNames[0]];E.dims.length===2&&(E=new o.Tensor("float32",Float32Array.from(E.data),[1,E.dims[0],E.dims[1]])),z(p,await i.run({sequence:w,text_embeddings:E,...p}),this.meta.flow_lm_state_manifest);const H=[];let V=0,W=new o.Tensor("float32",new Float32Array(this.latentDim).fill(NaN),[1,1,this.latentDim]),N=null;for(let T=0;T<pt;T++){const K=await i.run({sequence:W,text_embeddings:d,...p}),ot=K.conditioning;K.eos_logit.data[0]>_t&&N==null&&(N=T);const Y=N!=null&&T>=N+m.framesAfterEos,st=Math.sqrt(wt),$=new Float32Array(this.latentDim);for(let g=0;g<this.latentDim;g++){let x=0,A=0;for(;x===0;)x=Math.random();for(;A===0;)A=Math.random();$[g]=Math.sqrt(-2*Math.log(x))*Math.cos(2*Math.PI*A)*st}const it=1/v;for(let g=0;g<v;g++){const A=(await a.run({c:ot,s:this.st[g].s,t:this.st[g].t,x:new o.Tensor("float32",$,[1,this.latentDim])})).flow_dir.data;for(let y=0;y<this.latentDim;y++)$[y]+=A[y]*it}H.push(Float32Array.from($)),W=new o.Tensor("float32",$,[1,1,this.latentDim]),z(p,K,this.meta.flow_lm_state_manifest);const j=H.length-V;let b=0;if(Y?b=j:D&&j>=J?b=J:j>=X&&(b=X),b>0){const g=new Float32Array(b*this.latentDim);for(let y=0;y<b;y++)g.set(H[V+y],y*this.latentDim);const x=await h.run({latent:new o.Tensor("float32",g,[1,b,this.latentDim]),...l});z(l,x,this.meta.mimi_state_manifest),V+=b,D=!1;const A=Float32Array.from(x[h.outputNames[0]].data);S.push(A),e?.(A)}if(Y)break}}const U=S.reduce((_,B)=>_+B.length,0),k=new Float32Array(U);let M=0;for(const _ of S)k.set(_,M),M+=_.length;return k}}export{F as DEFAULT_BUNDLE,dt as POCKET_REPO,ut as POCKET_VOICES_SPACE,Mt as PocketTTS,G as SAMPLE_RATE,C as bundleDir,Ut as bundleOnDisk,yt as ensureBundle,bt as ensureVoicesBin,At as parseNpyFloat32,xt as parseVoicesBin,tt as voicesBinOnDisk};
1
+ import{join as u}from"node:path";import{existsSync as O,mkdirSync as Z,readFileSync as P,statSync as L,createWriteStream as rt,renameSync as at}from"node:fs";import{Readable as ct}from"node:stream";import{modelRoot as lt}from"./ner-engine.js";import{SentencePieceUnigram as ft}from"./sentencepiece.js";import{getOrt as ht,ortProviders as mt}from"./ort.js";const dt="KevinAHM/pocket-tts-onnx",ut="KevinAHM/pocket-tts-web",F="english_2026-04",G=24e3,pt=500,$=1,wt=.7,_t=-4,J=3,X=12,gt=!0,Q=(o="_int8")=>["bundle.json","tokenizer.model","bos_before_voice.npy",`text_conditioner${o}.onnx`,`mimi_encoder${o}.onnx`,`mimi_decoder${o}.onnx`,`flow_lm_main${o}.onnx`,`flow_lm_flow${o}.onnx`],I="voices.bin";function C(o=F){return u(lt(),"pocket-tts",o)}function Ut(o=F,n="_int8"){const t=C(o);try{return Q(n).every(e=>{const s=u(t,e);return O(s)&&L(s).size>0})}catch{return!1}}async function q(o,n,t,{onProgress:e,log:s}={}){const r=n===I?`https://huggingface.co/spaces/${ut}/resolve/main/onnx/${o}/${n}`:`https://huggingface.co/${dt}/resolve/main/onnx/${o}/${n}`,i=await fetch(r,{redirect:"follow"});if(!i.ok||!i.body)throw new Error(`fetch ${n} → HTTP ${i.status}`);const a=Number(i.headers.get("content-length"))||0,h=u(t,`${n}.part`),m=rt(h);let f=0,c=-1;const w=ct.fromWeb(i.body);w.on("data",d=>{if(f+=d.length,a){const l=Math.round(f/a*100);l!==c&&(c=l,e?.({file:n,pct:l}))}}),await new Promise((d,l)=>{w.pipe(m),m.on("finish",d),m.on("error",l),w.on("error",l)}),at(h,u(t,n)),s?.(`[pocket-tts] fetched ${n}`)}async function yt(o=F,n="_int8",{onProgress:t,log:e}={}){const s=C(o);Z(s,{recursive:!0});for(const r of Q(n)){const i=u(s,r);O(i)&&L(i).size>0||(e?.(`[pocket-tts] downloading ${r}…`),await q(o,r,s,{onProgress:t,log:e}))}return s}async function bt(o=F,{onProgress:n,log:t}={}){const e=C(o),s=u(e,I);return O(s)&&L(s).size>1024||(Z(e,{recursive:!0}),t?.(`[pocket-tts] downloading ${I} (built-in voices, ~52 MB)…`),await q(o,I,e,{onProgress:n,log:t})),s}function tt(o=F){try{const n=u(C(o),I);return O(n)&&L(n).size>1024}catch{return!1}}function At(o){const n=[147,78,85,77,80,89];for(let c=0;c<n.length;c++)if(o[c]!==n[c])throw new Error("not an NPY file");const t=new DataView(o.buffer,o.byteOffset,o.byteLength),e=t.getUint8(6),s=e===1?t.getUint16(8,!0):t.getUint32(8,!0),r=e===1?10:12,i=new TextDecoder().decode(o.subarray(r,r+s)),a=/\(\s*([0-9,\s]*)\)/.exec(i);if(!a)throw new Error("could not parse NPY shape");const h=a[1].split(",").map(c=>c.trim()).filter(Boolean).map(c=>parseInt(c,10)),m=r+s,f=new Float32Array((o.byteLength-m)/4);for(let c=0;c<f.length;c++)f[c]=t.getFloat32(m+c*4,!0);return{data:f,shape:h}}function et(o,n,t){const e=o.reduce((r,i)=>r*i,1);if(n==="int64")return new BigInt64Array(e);if(n==="bool")return new Uint8Array(e);const s=new Float32Array(e);return t==="nan"?s.fill(NaN):t==="ones"&&s.fill(1),s}function R(o,n){const t={};for(const e of n)t[e.input_name]=new o.Tensor(e.dtype,et(e.shape,e.dtype,e.fill),e.shape);return t}function z(o,n,t){for(const e of t)o[e.input_name]=n[e.output_name]}function xt(o){const n=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength),t=new DataView(n);let e=0;const s=new TextDecoder().decode(new Uint8Array(n,0,5));if(e+=5,s!=="PTVB1")throw new Error("not a voices.bin (bad header)");const r={},i=t.getUint32(e,!0);e+=4;for(let a=0;a<i;a++){const h=t.getUint16(e,!0);e+=2;const m=new TextDecoder().decode(new Uint8Array(n,e,h));e+=h;const f=t.getUint16(e,!0);e+=2;const c={};for(let w=0;w<f;w++){const d=t.getUint16(e,!0);e+=2;const l=new TextDecoder().decode(new Uint8Array(n,e,d));e+=d;const p=t.getUint8(e);e+=1;const S=t.getUint8(e);e+=1;const v=[];for(let _=0;_<S;_++)v.push(t.getUint32(e,!0)),e+=4;const U=t.getUint32(e,!0);e+=4;const k=n.slice(e,e+U),M=p===0?new Float32Array(k):p===1?new BigInt64Array(k):p===2?new Uint8Array(k):(()=>{throw new Error(`unsupported voices.bin dtype ${p}`)})();e+=U,c[l]={data:M,shape:v,dtype:p===0?"float32":p===1?"int64":"bool"}}r[m]=c}return r}function kt(o){const n={};for(const[t,e]of Object.entries(o)){const s=t.indexOf("/");s!==-1&&((n[t.slice(0,s)]||={})[t.slice(s+1)]=e)}return n}function Et(o){return o.step?{data:BigInt64Array.from([BigInt(o.step.data[0])]),shape:[1],dtype:"int64"}:o.offset&&!o.end_offset?{data:BigInt64Array.from([BigInt(o.offset.data[0])]),shape:[1],dtype:"int64"}:o.current_end?{data:BigInt64Array.from([BigInt(o.current_end.shape[0])]),shape:[1],dtype:"int64"}:{data:BigInt64Array.from([0n]),shape:[1],dtype:"int64"}}function Tt(o,n){const t=et(n.shape,n.dtype,n.fill),e=n.shape.reduce((f,c)=>f*c,1),s=n.dtype==="int64"?BigInt64Array:n.dtype==="bool"?Uint8Array:Float32Array,r=o.shape.length===n.shape.length;if(r&&o.shape.every((f,c)=>f===n.shape[c])||o.data.length===e)return new s(o.data);if(!r)return t;const i=[];let a=1;for(let f=o.shape.length-1;f>=0;f--)i[f]=a,a*=o.shape[f];const h=new Array(o.shape.length).fill(0),m=o.shape.map((f,c)=>Math.min(f,n.shape[c]));if(m.some(f=>f===0))return t;for(;;){let f=0;for(let l=0;l<h.length;l++)f+=h[l]*i[l];let c=0,w=1;for(let l=n.shape.length-1;l>=0;l--)c+=h[l]*w,w*=n.shape[l];t[c]=o.data[f];let d=h.length-1;for(;d>=0&&!(++h[d]<m[d]);d--)if(h[d]=0,d===0)return t;if(d<0)return t}}class Mt{constructor(){this.ready=!1,this.bundle=null,this.meta=null,this.tok=null,this.bos=null,this.sessions=null,this.st=null,this.latentDim=32,this.condDim=1024,this.samplesPerFrame=1920,this.builtin=null}builtinVoices(){return this.builtin?Object.keys(this.builtin).sort():[]}dispose(){const n=this.sessions;if(this.sessions=null,this.ready=!1,this.st=null,this.builtin=null,!!n){for(const[t,e]of Object.entries(n))if(t!=="ort")try{e?.release?.()}catch{}}}async load(n=F,{quant:t="_int8",onProgress:e,log:s=()=>{}}={}){const r=await yt(n,t,{onProgress:e,log:s});if(!tt(n))try{await bt(n,{onProgress:e,log:s})}catch(l){s(`[pocket-tts] built-in voices not downloaded (${l.message}) — cloning still works`)}const i=await ht();this.meta=JSON.parse(P(u(r,"bundle.json"),"utf8")),this.tok=new ft(new Uint8Array(P(u(r,"tokenizer.model")))),this.bos=this.meta.insert_bos_before_voice?At(P(u(r,"bos_before_voice.npy"))):null,this.latentDim=Number(this.meta.latent_dim)||32,this.condDim=Number(this.meta.conditioning_dim)||1024,this.samplesPerFrame=Math.round(G/(Number(this.meta.frame_rate)||12.5));const a={executionProviders:mt(),graphOptimizationLevel:"all",logSeverityLevel:3},[h,m,f,c,w]=await Promise.all([i.InferenceSession.create(u(r,`text_conditioner${t}.onnx`),a),i.InferenceSession.create(u(r,`mimi_encoder${t}.onnx`),a),i.InferenceSession.create(u(r,`mimi_decoder${t}.onnx`),a),i.InferenceSession.create(u(r,`flow_lm_main${t}.onnx`),a),i.InferenceSession.create(u(r,`flow_lm_flow${t}.onnx`),a)]);this.sessions={ort:i,textConditioner:h,mimiEncoder:m,mimiDecoder:f,flowMain:c,flowFlow:w},this.st=[];const d=1/$;for(let l=0;l<$;l++){const p=l/$;this.st.push({s:new i.Tensor("float32",new Float32Array([p]),[1,1]),t:new i.Tensor("float32",new Float32Array([p+d]),[1,1])})}try{tt(n)&&(this.builtin=xt(P(u(r,"voices.bin"))))}catch(l){s(`[pocket-tts] built-in voices unavailable (${l.message})`)}return this.bundle=n,this.ready=!0,s(`[pocket-tts] ready — ${n} (${t.replace("_","")||"fp32"}, ${G} Hz)`),!0}async encodeVoice(n){if(!this.ready)throw new Error("pocket-tts not loaded");const{ort:t,mimiEncoder:e}=this.sessions,s=n instanceof Float32Array?n:Float32Array.from(n),i=(await e.run({audio:new t.Tensor("float32",s,[1,1,s.length])}))[e.outputNames[0]];let a=i.dims.slice();for(;a.length>3&&a[0]===1;)a=a.slice(1);return a.length<3&&(a=[1,a[0],a[1]]),{data:Float32Array.from(i.data),shape:a}}#t(n){const{ort:t}=this.sessions;let e=n.data instanceof Float32Array?n.data:Float32Array.from(n.data),s=n.shape.slice();if(this.meta.insert_bos_before_voice&&this.bos){const r=new Float32Array(this.bos.data.length+e.length);r.set(this.bos.data,0),r.set(e,this.bos.data.length),e=r,s=[1,s[1]+this.bos.shape[1],s[2]]}return new t.Tensor("float32",e,s)}#e(n){const t=this.builtin?.[n];if(!t)throw new Error(`unknown built-in voice: ${n}`);const{ort:e}=this.sessions,s=kt(t),r=R(e,this.meta.flow_lm_state_manifest);for(const i of this.meta.flow_lm_state_manifest){const a=s[i.module]||{},h=a[i.key]||(i.key==="step"?Et(a):null);h&&(r[i.input_name]=new e.Tensor(i.dtype,Tt(h,i),i.shape))}return r}async#n(n){const{ort:t,flowMain:e}=this.sessions,s=R(t,this.meta.flow_lm_state_manifest),r=await e.run({sequence:new t.Tensor("float32",new Float32Array(0),[1,0,this.latentDim]),text_embeddings:this.#t(n),...s});return z(s,r,this.meta.flow_lm_state_manifest),s}#s(n){let t=String(n).replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim();if(!t)return{text:"",framesAfterEos:1};this.meta.remove_semicolons&&(t=t.replace(/;/g,","));const e=t.split(/\s+/).filter(Boolean).length;let s=e<=4?3:1;return this.meta.model_recommended_frames_after_eos!=null&&(s=Number(this.meta.model_recommended_frames_after_eos)),/[A-ZÀ-Þ]/.test(t[0])||(t=t[0].toUpperCase()+t.slice(1)),/[0-9A-Za-zÀ-ÿ]/.test(t[t.length-1])&&(t+="."),this.meta.pad_with_spaces_for_short_inputs&&e<5&&(t=` ${t}`),{text:t,framesAfterEos:s}}#o(n){const t=Number(this.meta.max_token_per_chunk)||50,e=n.match(/[^.!?]+[.!?]+|[^.!?]+$/g)||[n],s=[];for(const r of e){const i=r.trim();if(!i)continue;const a=this.tok.encodeIds(i);if(a.length<=t){s.push(i);continue}for(let h=0;h<a.length;h+=t){const m=this.tok.decodeIds(a.slice(h,h+t)).trim();m&&s.push(m)}}return s.length?s:[n]}async synth(n,{voice:t,onAudio:e=null}={}){if(!this.ready)throw new Error("pocket-tts not loaded");if(typeof t=="string"){if(!this.builtin?.[t])throw new Error(`unknown built-in voice: ${t}`)}else if(!t?.data?.length)throw new Error("pocket-tts needs a voice — record one, or pick a built-in");const{ort:s,textConditioner:r,flowMain:i,flowFlow:a,mimiDecoder:h}=this.sessions,m=this.#s(n);if(!m.text)return new Float32Array(0);const f=this.#o(m.text),c=typeof t=="string"?this.#e(t):await this.#n(t),w=new s.Tensor("float32",new Float32Array(0),[1,0,this.latentDim]),d=new s.Tensor("float32",new Float32Array(0),[1,0,this.condDim]);let l=R(s,this.meta.mimi_state_manifest),p={...c};const S=[];let v=!0;for(let _=0;_<f.length;_++){gt&&_>0&&(p={...c},l=R(s,this.meta.mimi_state_manifest));const B=this.tok.encodeIds(f[_]),nt=new s.Tensor("int64",BigInt64Array.from(B,T=>BigInt(T)),[1,B.length]);let E=(await r.run({token_ids:nt}))[r.outputNames[0]];E.dims.length===2&&(E=new s.Tensor("float32",Float32Array.from(E.data),[1,E.dims[0],E.dims[1]])),z(p,await i.run({sequence:w,text_embeddings:E,...p}),this.meta.flow_lm_state_manifest);const H=[];let V=0,W=new s.Tensor("float32",new Float32Array(this.latentDim).fill(NaN),[1,1,this.latentDim]),N=null;for(let T=0;T<pt;T++){const K=await i.run({sequence:W,text_embeddings:d,...p}),st=K.conditioning;K.eos_logit.data[0]>_t&&N==null&&(N=T);const Y=N!=null&&T>=N+m.framesAfterEos,ot=Math.sqrt(wt),D=new Float32Array(this.latentDim);for(let g=0;g<this.latentDim;g++){let x=0,A=0;for(;x===0;)x=Math.random();for(;A===0;)A=Math.random();D[g]=Math.sqrt(-2*Math.log(x))*Math.cos(2*Math.PI*A)*ot}const it=1/$;for(let g=0;g<$;g++){const A=(await a.run({c:st,s:this.st[g].s,t:this.st[g].t,x:new s.Tensor("float32",D,[1,this.latentDim])})).flow_dir.data;for(let y=0;y<this.latentDim;y++)D[y]+=A[y]*it}H.push(Float32Array.from(D)),W=new s.Tensor("float32",D,[1,1,this.latentDim]),z(p,K,this.meta.flow_lm_state_manifest);const j=H.length-V;let b=0;if(Y?b=j:v&&j>=J?b=J:j>=X&&(b=X),b>0){const g=new Float32Array(b*this.latentDim);for(let y=0;y<b;y++)g.set(H[V+y],y*this.latentDim);const x=await h.run({latent:new s.Tensor("float32",g,[1,b,this.latentDim]),...l});z(l,x,this.meta.mimi_state_manifest),V+=b,v=!1;const A=Float32Array.from(x[h.outputNames[0]].data);S.push(A),e?.(A)}if(Y)break}}const U=S.reduce((_,B)=>_+B.length,0),k=new Float32Array(U);let M=0;for(const _ of S)k.set(_,M),M+=_.length;return k}}export{F as DEFAULT_BUNDLE,dt as POCKET_REPO,ut as POCKET_VOICES_SPACE,Mt as PocketTTS,G as SAMPLE_RATE,C as bundleDir,Ut as bundleOnDisk,yt as ensureBundle,bt as ensureVoicesBin,At as parseNpyFloat32,xt as parseVoicesBin,tt as voicesBinOnDisk};
@@ -0,0 +1,10 @@
1
+ function x(t,e=""){let i;try{i=new URL(t)}catch{return String(t||"")}i.hash="";const s=/<link\b[^>]*\brel=["']canonical["'][^>]*\bhref=["']([^"']+)["'][^>]*>/i.exec(e)||/<link\b[^>]*\bhref=["']([^"']+)["'][^>]*\brel=["']canonical["'][^>]*>/i.exec(e);if(s)try{const n=new URL(s[1],i);if(n.origin===i.origin&&(n.protocol==="http:"||n.protocol==="https:"))return n.hash="",n.toString()}catch{}return i.toString()}function h(t){return String(t||"").toLowerCase().replace(/<[^>]+>/g,"").replace(/[^\p{L}\p{N}\s-]/gu,"").trim().replace(/\s+/g,"-").slice(0,80)||"section"}const b=t=>String(t).replace(/&(amp|lt|gt|quot|#39|nbsp);/g,(e,i)=>({amp:"&",lt:"<",gt:">",quot:'"',"#39":"'",nbsp:" "})[i]);function d(t=""){const e=new Map,i=String(t||""),s=/<h([1-6])\b([^>]*)>([\s\S]*?)<\/h\1\s*>/gi;for(const n of i.matchAll(s)){let r=/\bid=["']([^"']+)["']/i.exec(n[2])?.[1]||/<a\b[^>]*\bhref=["']#([^"']+)["']/i.exec(n[3])?.[1]||null;if(!r){const l=i.slice(Math.max(0,n.index-300),n.index),u=/<(?:section|div)\b[^>]*\bid=["']([^"']+)["'][^>]*>\s*$/i.exec(l);u&&(r=u[1])}const o=n[3].replace(/<a\b[^>]*\bhref=["']#[^"']*["'][^>]*>[\s\S]*?<\/a\s*>/gi,""),c=b(o.replace(/<[^>]+>/g,"")).replace(/\s+/g," ").trim();r&&c&&!e.has(c)&&e.set(c,r)}return e}function S(t,e=new Map){const i=String(t||""),s=[],n=new Map,r=/^(#{1,6})[ \t]+(.+?)[ \t]*#*[ \t]*$/gm;let o=!1,c=0;for(const l of i.split(`
2
+ `)){const u=c;if(c+=l.length+1,/^\s*(```|~~~)/.test(l)){o=!o;continue}if(o)continue;r.lastIndex=0;const a=r.exec(l);if(!a)continue;const p=a[2].trim();let f=e.get(p)||h(p);const g=(n.get(f)||0)+1;n.set(f,g),g>1&&(f=`${f}-${g}`),s.push({id:f,heading:p,level:a[1].length,offset:u})}return s}function $(t,e,i=[]){const s=String(t||"");if(!(e>0)||s.length<=e)return{text:s,truncated:!1};const n=Math.floor(e*.8);let r=-1;for(const o of i)o.offset>=n&&o.offset<=e&&(r=o.offset);if(r<0){const o=s.lastIndexOf(`
3
+
4
+ `,e);o>=n&&(r=o)}if(r<0){const o=s.lastIndexOf(`
5
+ `,e);r=o>=n?o:e}return{text:s.slice(0,r).trimEnd(),truncated:!0}}function m(t){const e=[];t.title&&e.push(`Title: ${t.title}`),e.push(`URL Source: ${t.url}`),t.published&&e.push(`Published Time: ${t.published}`),t.author&&e.push(`Author: ${t.author}`);const i=t[t.format||"markdown"]||t.markdown||t.text||"";return`${e.join(`
6
+ `)}
7
+
8
+ ${t.format==="text"?"Text Content:":"Markdown Content:"}
9
+ ${i}
10
+ `}export{x as canonicalUrl,d as headingIds,S as sectionsOf,h as slugify,m as toJinaText,$ as truncateAtSection};
@@ -0,0 +1 @@
1
+ const u=Object.freeze({maxEntries:200,ttlMs:864e5});function p(s){const o={noStore:!1,maxAge:null};for(const a of String(s||"").split(",")){const[e,n]=a.trim().toLowerCase().split("=");e==="no-store"&&(o.noStore=!0),e==="max-age"&&/^\d+$/.test(n||"")&&(o.maxAge=Number(n))}return o}function m({now:s=()=>Date.now(),maxEntries:o=u.maxEntries,ttlMs:a=u.ttlMs}={}){const e=new Map,n=(r,t)=>{e.delete(r),e.set(r,t)};return{get(r){const t=e.get(r);return t?(n(r,t),{...t,stale:s()>=t.expiresAt}):null},set(r,{doc:t,etag:l=null,lastModified:f=null,cacheControl:x=null}){const c=p(x);if(c.noStore)return!1;const A=c.maxAge!=null?Math.min(a,c.maxAge*1e3):a,i=s();for(n(r,{doc:t,etag:l,lastModified:f,fetchedAt:i,expiresAt:i+A});e.size>o;)e.delete(e.keys().next().value);return!0},revalidated(r){const t=e.get(r);if(!t)return!1;const l=s();return n(r,{...t,fetchedAt:l,expiresAt:l+(t.expiresAt-t.fetchedAt)}),!0},delete(r){return e.delete(r)},clear(){e.clear()},size(){return e.size}}}export{u as PAGE_CACHE_DEFAULTS,m as createPageCache};
@@ -0,0 +1 @@
1
+ let o=null,r=null;async function a(){if(!o){const[{Defuddle:e},{parseHTML:n}]=await Promise.all([import("defuddle/node"),import("linkedom")]);o=e,r=n}}async function d(e,n){await a();const{document:i}=r(String(e||"")),t=await o(i,n,{markdown:!0});return{title:t.title||"",author:t.author||"",published:t.published||"",description:t.description||"",lang:t.language||"",markdown:String(t.content||"").trim(),wordCount:t.wordCount||0}}const l="defuddle";export{l as PROVIDER_ID,d as extractWithDefuddle};