@chatpanel/gateway 0.75.0 → 0.85.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/chatpanel-gateway.js +5 -5
- package/package.json +4 -4
- package/src/capabilities.js +1 -1
- package/src/capability-endpoints.js +1 -1
- package/src/configstore.js +1 -1
- package/src/egress.js +2 -2
- package/src/engine-pacer.js +1 -0
- package/src/local-engine-probe.js +1 -0
- package/src/ner-engine.js +1 -1
- package/src/pair-prompt.js +12 -0
- package/src/recruiting.js +1 -1
- package/src/redact.js +2 -2
- package/src/retrieval/search-apis.js +1 -0
- package/src/retrieval/search-serp.js +1 -1
- package/src/retrieval/search.js +1 -1
- package/src/router.js +1 -1
- package/src/runtime.js +6 -5
- package/src/search-api.js +1 -0
- package/src/search-outcome.js +1 -0
- package/src/server.js +33 -28
- package/src/service.js +17 -17
- package/src/stt-engine.js +1 -1
- package/src/version.js +1 -1
- package/src/web-search-tool.js +8 -8
- package/src/web-search.js +1 -1
package/bin/chatpanel-gateway.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const
|
|
3
|
-
`)}process.argv.includes("--json")?console.log(JSON.stringify(a,null,2)):console.log(o(a))}else if(
|
|
2
|
+
const n=process.argv[2],u={"--bridge":"chatpanel-bridge","--mcp-stdio":"chatpanel-bridge-mcp",mcp:"chatpanel-history-mcp","--extract-worker":"chatpanel-extract"},f=(t=process.argv)=>t.includes("--mcp-stdio")?u["--mcp-stdio"]:u[t[2]]||"chatpanel-gateway";try{process.title=f()}catch{}if(!process.versions.bun&&n!=="--version"&&n!=="-v"){const[t,o]=String(process.versions.node||"0.0").split(".").map(Number);(t<22||t===22&&o<13)&&(console.error(`ChatPanel Gateway needs Node.js 22.13 or newer — this is ${process.version}.`),console.error("Update Node (https://nodejs.org, or `nvm install 22`), then run this again — or use the standalone binary, which carries its own runtime:"),console.error(" curl -fsSL https://dl.chatpanel.net/install.sh | bash"),process.exit(1))}try{if(n==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:t}=await import("../src/extract/worker.js");t()}else if(n==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(n==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(n==="mcp"){const{runMcpServer:t}=await import("../src/mcp.js");await t()}else if(n==="tools"||n==="call"){const{runMcpCli:t}=await import("../src/mcp-cli.js");process.exit(await t(process.argv.slice(2)))}else if(n==="policy"){const{loadPolicy:t,formatPolicy:o,PolicyLoadError:l}=await import("../src/policy.js");try{const i=await t();process.argv.includes("--json")?console.log(JSON.stringify(i?{...i,label:void 0}:null,null,2)):console.log(o(i))}catch(i){throw i instanceof l&&(console.error(`org policy: ${i.message}`),process.exit(78)),i}}else if(n==="--audit"){const{egressAudit:t,formatAudit:o}=await import("../src/egress.js"),{loadConfig:l}=await import("../src/config.js"),{readFileSync:i}=await import("node:fs"),{join:w}=await import("node:path"),p=await import("node:os"),g=l(),e=`http://127.0.0.1:${g.port||4320}`;let a=null,r=`no gateway running at ${e}`;try{const h=i(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||w(p.homedir(),".chatpanel","gateway-token"),"utf8").trim(),s=await fetch(`${e}/audit`,{headers:{authorization:`Bearer ${h}`},signal:AbortSignal.timeout(2500)});if(s.ok)a=await s.json();else if(s.status===404){const c=await fetch(`${e}/health`,{signal:AbortSignal.timeout(2500)}).then(d=>d.json()).catch(()=>null);r=`the gateway running at ${e}${c?.version?` (${c.version})`:""} predates --audit (0.7.0) — restart it after updating`}else r=`the gateway at ${e} refused the audit (HTTP ${s.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!a){const{VERSION:h}=await import("../src/server.js");a={...t(g,{ledger:null,version:h}),observed:[]},console.log(`(${r}; showing what the current config allows)
|
|
3
|
+
`)}process.argv.includes("--json")?console.log(JSON.stringify(a,null,2)):console.log(o(a))}else if(n==="sandbox"){const{srtModuleUrl:t}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&t()&&(process.env.CHATPANEL_SRT_MODULE=t());const{runSandboxCli:o}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await o(process.argv.slice(3)))}else if(n==="pair"){const{loadConfig:t}=await import("../src/config.js"),{readFileSync:o}=await import("node:fs"),{join:l}=await import("node:path"),i=await import("node:os"),p=`http://127.0.0.1:${t().port||4320}`,g=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||l(i.homedir(),".chatpanel","gateway-token");try{const e=o(g,"utf8").trim(),a=await fetch(`${p}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${e}`},signal:AbortSignal.timeout(2500)}),r=await a.json().catch(()=>({}));if(a.status===404)throw new Error(`the gateway at ${p} predates pairing (0.9.0) — update and restart it`);if(!a.ok)throw new Error(r.error||`HTTP ${a.status}`);console.log(`Pairing code: ${r.display||r.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(e){console.error(`could not get a pairing code from the gateway at ${p}: ${e?.message||e}${/ENOENT/.test(String(e?.message))?` (no token at ${g} — has the gateway started once?)`:""}`),process.exit(1)}}else if(n==="local"){const{localStatus:t,formatLocalStatus:o}=await import("../src/local-status.js");process.stdout.write(o(await t()))}else if(n==="connect"){const{connectAgents:t,formatConnect:o}=await import("../src/connect-agents.js"),l=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(o(t({dryRun:l}),{dryRun:l}))}else{const{start:t,VERSION:o}=await import("../src/server.js"),{installService:l,uninstallService:i,serviceReport:w,stopService:p,pathWithDir:g}=await import("../src/service.js");switch(n){case"--stop":p(),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":{const e=await l({version:o,force:process.argv.includes("--force")}),a=e.health;if(e.newer){const r=a.managedBy&&a.managedBy!=="gateway"?` (run by the ${a.managedBy.replace(/-child$/,"")} app)`:"";console.log(`ChatPanel Privacy Gateway v${a.version} is already running at ${a.url}${r} — newer than this copy (v${o}). Nothing was changed.`),console.log(" To bring this copy up to date: npm i -g @chatpanel/gateway --ignore-scripts (or re-run install.sh), then chatpanel-gateway --install"),console.log(` To run this older v${o} instead anyway: chatpanel-gateway --install --force`);break}if(e.ok){const r=e.deferredTo?` — the ${e.deferredTo} app's gateway (v${a.version}) is the one answering right now; this install takes over at the next login`:"",h=e.replaced?`, replacing v${e.replaced}`:"";e.unchanged?console.log(`ChatPanel Privacy Gateway v${a.version}: already running at ${a.url} and registered to start at login — nothing was changed, nothing was restarted.`):console.log(`ChatPanel Privacy Gateway v${a.version}: running at ${a.url}${h}, starts at login${e.wsl?" (Windows login, through wsl.exe)":""}${r}.`);let s=null;for(let c=0;c<30;c++){try{s=(await(await fetch(`${a.url}/health`,{signal:AbortSignal.timeout(1500)})).json())?.bridge||null}catch{s=null}if(s&&s.mode!=="starting")break;await new Promise(d=>setTimeout(d,500))}if(s?["embedded","standalone","adopted"].includes(s.mode)?console.log(` bridge: ${s.mode}${s.version?` v${s.version}`:""} — local agents are available.`):console.error(` ⚠ bridge: ${s.why||s.mode}`):console.log(" bridge: this gateway does not report one yet — `chatpanel-gateway --status` shows it once it is up."),s?.version){const{staleBridgeCommands:c,staleBridgeLines:d}=await import("../src/service.js");for(const y of d(c({embedded:s.version}),{embedded:s.version}))console.log(y)}}else a.ok?(console.error(`ChatPanel Privacy Gateway: v${o} is registered to start at login, but v${a.version} still answers at ${a.url} 40 s later.`),console.error(" Something starts it back faster than it can be replaced — `chatpanel-gateway --status` says what holds the port; `--stop`, then `--install`, separates the two steps.")):(console.error(`ChatPanel Privacy Gateway: login auto-start is registered, but nothing answered at ${a.url} after 40 s.`),e.errLog&&console.error(` last of the error log:
|
|
4
4
|
${e.errLog.split(`
|
|
5
|
-
`).map(
|
|
6
|
-
`)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself."));e.shadow&&(console.log(` ⚠ ${e.shadow}/chatpanel-gateway comes first on your PATH, so typing \`chatpanel-gateway\` still runs THAT copy, not this v${o}.`),console.log(` Remove it, or run this one by its full path. (The service just registered is this v${o} either way.)`));try{const{pruneForeignPrebuilds:
|
|
7
|
-
`));break;default:console.error(`unknown option: ${
|
|
5
|
+
`).map(r=>` ${r}`).join(`
|
|
6
|
+
`)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself."));e.shadow&&(console.log(` ⚠ ${e.shadow}/chatpanel-gateway comes first on your PATH, so typing \`chatpanel-gateway\` still runs THAT copy, not this v${o}.`),console.log(` Remove it, or run this one by its full path. (The service just registered is this v${o} either way.)`));try{const{pruneForeignPrebuilds:r,pruneLine:h}=await import("../src/prune-install.js"),s=h(r({log:c=>console.error(c)}));s&&console.log(s)}catch{}e.launcher==="powershell"&&console.log(" (VBScript is not installed here, so the login launcher is PowerShell — a console flashes for an instant at login.)"),e.path?.added?console.log(` Added ${e.path.dir} to your PATH — \`chatpanel-gateway\` works in a NEW terminal.`):e.path?.error?console.log(` Could not add ${e.path.dir} to your PATH (${e.path.error}) — add it yourself to run \`chatpanel-gateway\` by name.`):e.path?.dir&&e.wsl&&g(process.env.PATH||"",e.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${e.path.dir}:$PATH"`),a.ok||process.exit(1);break}case"--uninstall":i(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(await w());break;case void 0:await t();break;case"--help":case"-h":console.log([`ChatPanel Privacy Gateway v${o}`,""," chatpanel-gateway --install run after every install or upgrade: login auto-start, replace an older one, wait for it and its bridge"," chatpanel-gateway run in the foreground, in this terminal"," chatpanel-gateway --status what starts it, what answers on the port, which copy is on PATH"," chatpanel-gateway --stop stop it (on Windows, before `npm i -g`)"," chatpanel-gateway --uninstall remove login auto-start"," chatpanel-gateway local the bridge and the gateway, one view"," chatpanel-gateway pair a one-time code for a browser the gateway does not recognise"," chatpanel-gateway connect point your CLI agents (Codex, Claude Code, …) at it"," chatpanel-gateway --audit every host it has contacted, and every host its config allows"," chatpanel-gateway --version print the version"].join(`
|
|
7
|
+
`));break;default:console.error(`unknown option: ${n}
|
|
8
8
|
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.
|
|
3
|
+
"version": "0.85.3",
|
|
4
4
|
"description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -23,9 +23,9 @@
|
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
26
|
-
"@chatpanel/bridge": "^0.
|
|
27
|
-
"@chatpanel/events": "^0.
|
|
28
|
-
"@chatpanel/pii": "^0.
|
|
26
|
+
"@chatpanel/bridge": "^0.44.1",
|
|
27
|
+
"@chatpanel/events": "^0.353.0",
|
|
28
|
+
"@chatpanel/pii": "^0.14.0",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
|
31
31
|
"fflate": "^0.8.3",
|
package/src/capabilities.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as r from"./ner-engine.js";import*as A from"./stt-engine.js";import*as L from"./tts-engine.js";import{MODEL_CATALOG as M,DEFAULT_MODEL as S}from"./models.js";import{STT_MODEL_CATALOG as C,DEFAULT_STT_MODEL as E}from"./stt-models.js";import{TTS_MODEL_CATALOG as R,resolveDefaultModel as U}from"./tts-models.js";import{rawOrtAvailable as $}from"./ort.js";import{providerOf as B,providerTable as G}from"./providers.js";import{CAPABILITY_ROUTES as u,overBudget as j,validateDetectRequest as F}from"./capability-endpoints.js";import{extractCapabilityEntry as I}from"./extract/handler.js";const b=e=>[...new Set(e.filter(Boolean))];function x(e,c={}){return{state:e.state||"off",name:e.runtime||null,dtype:e.dtype||null,error:e.error||null,...c}}function Q(e,{version:c="",reader:n=null,searcher:s=null,extract:p=null,proxy:f=null}={}){const
|
|
1
|
+
import*as r from"./ner-engine.js";import*as A from"./stt-engine.js";import*as L from"./tts-engine.js";import{MODEL_CATALOG as M,DEFAULT_MODEL as S}from"./models.js";import{STT_MODEL_CATALOG as C,DEFAULT_STT_MODEL as E}from"./stt-models.js";import{TTS_MODEL_CATALOG as R,resolveDefaultModel as U}from"./tts-models.js";import{rawOrtAvailable as $}from"./ort.js";import{providerOf as B,providerTable as G}from"./providers.js";import{CAPABILITY_ROUTES as u,overBudget as j,validateDetectRequest as F}from"./capability-endpoints.js";import{extractCapabilityEntry as I}from"./extract/handler.js";const b=e=>[...new Set(e.filter(Boolean))];function x(e,c={}){return{state:e.state||"off",name:e.runtime||null,dtype:e.dtype||null,error:e.error||null,...c}}function Q(e,{version:c="",reader:n=null,searcher:s=null,extract:p=null,proxy:f=null}={}){const i=r.health(),a=e?.redaction?.detection,o=!!(a&&a.backend&&a.backend!=="off"),m=i.model||e?.ner?.model||S,g=A.health(),v=L.health(),O=v.model||e?.tts?.model||U($()),l=[{id:"detect",route:u.detect,models:b([m,...M.map(t=>t.id)]),default:m,union:i.companions?.filter(t=>t.state==="ready").map(t=>t.model)||[],labels:r.isReady()?r.labels():[],maxTokens:r.isReady()?r.maxTokens():null,requirements:{egress:"none",deterministic:!0},stats:i.stats||{calls:0},runtime:o?{state:"external",name:a.backend,url:a.url||null}:x(i,{installed:r.modelOnDisk(m)})},{id:"stt",route:u.stt,streaming:"/stt/sessions",models:b([g.model||e?.stt?.model||E,...C.map(t=>t.id)]),default:g.model||e?.stt?.model||E,requirements:{egress:"none"},runtime:x(g)},{id:"tts",route:u.tts,voices:"/tts/voices",models:b([O,...R.map(t=>t.id)]),default:O,requirements:{egress:"none"},runtime:x(v)}],T=e?.read||{},w=!!T.remote?.url;l.push({id:"read",route:u.read,providers:n?n.providers():["defuddle","text",...w?["remote"]:[]],default:T.provider||"defuddle",requirements:{egress:"web"},stats:n?n.stats():{calls:0},runtime:{state:"ready",cache:n?n.cache.size():0,remote:w?"configured":"off"}});const h=e?.search||{},y=!!h.searxng?.url,k=s?.searxng?s.searxng.state():y?"unknown":"off";if(l.push({id:"search",route:u.search,providers:s?s.providers():["serp",...y?["searxng"]:[]],default:h.provider==="searxng"||h.provider==="serp"?h.provider:y?"searxng":"serp",requirements:{egress:"web"},stats:s?s.stats()[y?"searxng":"serp"]||{calls:0}:{calls:0},runtime:{state:"ready",searxng:k,...y?{searxngUrl:h.searxng.url}:{}}}),p)try{l.push(I(p))}catch{}if(f)for(const t of f.capabilities){const d=f.entry(t);d&&l.push(d)}l.push({id:"chat",route:u.chat,models:[],dialects:["/v1/chat/completions","/v1/messages","/v1/responses"],listing:"/v1/models"});const _={sttModel:g.model,ttsModel:v.model,nerModel:m};for(const t of l){const d=B(e,t.id,_),{token:D,...q}=d;t.provider=q,d.kind==="remote"&&(t.requirements={...t.requirements||{},egress:d.egress})}return{capabilities:l,server:{name:"chatpanel-gateway",version:String(c),audit:"/audit"},providers:Object.fromEntries(Object.entries(G(e,_)).map(([t,{token:d,...D}])=>[t,D]))}}async function V(e,{ensure:c=async()=>r.state(),model:n=null}={}){let s;try{s=F(e)}catch(o){return{status:400,body:{error:{message:o.message,type:"invalid_request"}}}}if(s.model&&n&&s.model!==n)return{status:404,body:{error:{message:`model ${s.model} is not loaded here (serving ${n})`,type:"model_not_found"}}};if(await c(),!r.isReady()){const o=r.health();return{status:503,body:{error:{message:o.state==="error"?`detector failed to load: ${o.error||"unknown error"}`:`detector is ${o.state} — not ready yet`,type:o.state==="error"?"detector_error":"detector_unready"},state:o.state,model:o.model}}}const p=j(r.stats(),s.text.length,s.budgetMs);if(p)return{status:503,body:{...p,model:r.health().model}};const f=performance.now();let i=await r.detectSpans(s.text,{strict:!!s.strict});if(s.labels){const o=new Set(s.labels);i=i.filter(m=>o.has(m.type))}const a=r.health();return{status:200,body:{entities:i,model:a.model,ms:Math.round(performance.now()-f),runtime:{name:a.runtime||null,dtype:a.dtype||null}}}}export{Q as capabilitiesDocument,V as handleDetect};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as q}from"./event.js";const x=Object.freeze(["detect","decide","rerank","embed","stt","tts","search","read","extract","chat","s2s"]),p=Object.freeze(["embedded","container","remote","harness","router","none"]),f=Object.freeze(["none","loopback","lan","internet","configurable"]),b=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",chat:"/v1/chat/completions",s2s:"/v1/audio/conversations"}),g=Object.freeze(new Set(["search","read","extract"])),v=Object.freeze(["day","week","month","year"]),h=Object.freeze(["login","paywall","rate_limited","robots","tdm"]),c=Object.freeze(["markdown","text"]),I="/v1/capabilities",A="over_budget",a=e=>!!e&&typeof e=="object"&&!Array.isArray(e),n=e=>typeof e=="string"&&e.length>0,d=e=>typeof e=="number"&&Number.isFinite(e),t=(e,s)=>{if(!e)throw new q("SHAPE",s)};function k(e,s){if(!a(e)||!(e.calls>0))return null;const r=d(e.p50Ms)?e.p50Ms:0,i=d(e.charsPerSec)&&e.charsPerSec>0&&d(s)?s/e.charsPerSec*1e3:0;return Math.round(Math.max(r,i))}function _(e,s,r){if(!d(r)||r<=0)return null;const i=k(e,s);return i===null||i<=r?null:{error:{type:A,message:`predicted ${i} ms is over the ${r} ms budget`,predictedMs:i,budgetMs:r}}}function O(e){t(a(e),"detect: body must be an object"),t(typeof e.text=="string","detect: text (string) required");const s={text:e.text};return e.model!=null&&(t(n(e.model),"detect: model must be a non-empty string"),s.model=e.model),e.labels!=null&&(t(Array.isArray(e.labels)&&e.labels.every(n),"detect: labels must be string[]"),s.labels=e.labels),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"detect: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function w(e,s=null){t(a(e),"detect: response must be an object"),t(Array.isArray(e.entities),"detect: entities[] required"),t(n(e.model),"detect: model required"),t(d(e.ms)&&e.ms>=0,"detect: ms required");for(const r of e.entities)t(a(r)&&n(r.value)&&n(r.type),"detect: entity needs value and type"),t(Number.isInteger(r.start)&&Number.isInteger(r.end)&&r.start>=0&&r.end>r.start,`detect: entity ${JSON.stringify(r.value)} needs start < end`),t(d(r.score)&&r.score>=0&&r.score<=1,`detect: entity ${JSON.stringify(r.value)} needs a score in [0,1]`),typeof s=="string"&&t(s.slice(r.start,r.end)===r.value,`detect: entity ${JSON.stringify(r.value)} is not at ${r.start}–${r.end} of the text`);return e}const m=e=>{if(!n(e))return!1;try{const s=new URL(e);return s.protocol==="http:"||s.protocol==="https:"}catch{return!1}};function E(e){t(a(e),"search: body must be an object"),t(n(e.q)&&e.q.trim().length>0,"search: q (non-empty string) required");const s={q:e.q.trim()};return e.limit!=null&&(t(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&&(t(n(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&&(t(n(e.site)&&!/[\s/]/.test(e.site),"search: site must be a hostname"),s.site=e.site.toLowerCase()),e.freshness!=null&&(t(v.includes(e.freshness),`search: freshness must be one of ${v.join(", ")}`),s.freshness=e.freshness),e.read!=null&&(t(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&&(t(n(e.provider),"search: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"search: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function N(e){return t(a(e),"search: response must be an object"),t(Array.isArray(e.results),"search: results[] required"),t(n(e.provider),"search: provider required"),t(d(e.ms)&&e.ms>=0,"search: ms required"),e.results.forEach((s,r)=>{t(a(s)&&s.rank===r+1,`search: result ${r} must carry rank ${r+1}`),t(m(s.url),`search: result ${r+1} needs an absolute http(s) url`),t(n(s.title),`search: result ${r+1} needs a title`),t(typeof s.snippet=="string",`search: result ${r+1} needs a snippet (may be empty)`),s.read!=null&&S(s.read)}),e}function C(e){t(a(e),"read: body must be an object"),t(m(e.url),"read: url (absolute http(s)) required");const s={url:e.url,format:"markdown"};return e.format!=null&&(t(c.includes(e.format),`read: format must be one of ${c.join(", ")}`),s.format=e.format),e.maxChars!=null&&(t(Number.isInteger(e.maxChars)&&e.maxChars>=200,"read: maxChars must be an integer ≥ 200"),s.maxChars=e.maxChars),e.snippet!=null&&(t(typeof e.snippet=="string","read: snippet must be a string"),s.snippet=e.snippet),e.provider!=null&&(t(n(e.provider),"read: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"read: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function S(e){t(a(e),"read: response must be an object"),t(m(e.url),"read: url (absolute, where the page landed) required"),t(typeof e.title=="string","read: title (string, may be empty) required"),t(c.includes(e.format),"read: format required");const s=e[e.format];t(typeof s=="string",`read: ${e.format} (string) required`),t(Number.isInteger(e.chars)&&e.chars===s.length,"read: chars must equal the content length"),t(typeof e.truncated=="boolean","read: truncated (boolean) required"),t(n(e.provider),"read: provider required"),t(d(e.ms)&&e.ms>=0,"read: ms required"),t(Array.isArray(e.sections),"read: sections[] required");for(const r of e.sections)t(a(r)&&n(r.id)&&n(r.heading),"read: section needs id and heading"),t(Number.isInteger(r.level)&&r.level>=1&&r.level<=6,`read: section ${r.id} needs level 1–6`),t(Number.isInteger(r.offset)&&r.offset>=0&&r.offset<=s.length,`read: section ${r.id} offset must index the content`);return e.restricted!=null&&t(a(e.restricted)&&h.includes(e.restricted.reason),`read: restricted.reason must be one of ${h.join(", ")}`),e}const $=Object.freeze(["choice","score","noul"]),M=/^[A-Za-z_][A-Za-z0-9_]*$/;function D(e){t(a(e),"decide: body must be an object"),t(n(e.state),"decide: state (non-empty string) required"),t(a(e.questions)&&Object.keys(e.questions).length>0,"decide: questions {} required");const s={};for(const[i,u]of Object.entries(e.questions)){t(M.test(i),`decide: question key ${JSON.stringify(i)} must be an identifier`),t(a(u)&&$.includes(u.type),`decide: question ${i}.type must be one of ${$.join(", ")}`),t(n(u.instructions),`decide: question ${i} needs instructions`);const l={type:u.type,instructions:u.instructions};u.type==="noul"?t(u.options==null,`decide: question ${i}: a noul has no options`):(t(Array.isArray(u.options)&&u.options.length>=2&&u.options.length<=255,`decide: question ${i}.options needs 2–255 entries`),l.options=u.options.map(o=>n(o)?{value:o}:(t(a(o)&&n(o.value),`decide: question ${i}: an option is a string or { value, describe? }`),o.describe!=null?{value:o.value,describe:String(o.describe)}:{value:o.value})),t(new Set(l.options.map(o=>o.value)).size===l.options.length,`decide: question ${i}.options must be distinct`)),s[i]=l}const r={state:e.state,questions:s};return e.model!=null&&(t(n(e.model),"decide: model must be a non-empty string"),r.model=e.model),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"decide: budgetMs must be a number ≥ 0"),r.budgetMs=e.budgetMs),r}function z(e,s=null){t(a(e),"decide: response must be an object"),t(a(e.answers),"decide: answers {} required"),t(n(e.model),"decide: model required"),t(d(e.ms)&&e.ms>=0,"decide: ms required"),e.calibrated!=null&&t(typeof e.calibrated=="boolean","decide: calibrated must be a boolean");const r=i=>d(i)&&i>=0&&i<=1;for(const i of Object.keys(s?s.questions:e.answers)){const u=e.answers[i];t(a(u),`decide: answer ${i} missing`),t(r(u.p),`decide: answer ${i}.p must be in [0,1]`),t(Array.isArray(u.options)&&u.options.every(o=>a(o)&&o.value!==void 0&&r(o.p)),`decide: answer ${i}.options must be [{ value, p }]`),u.confidence!=null&&t(r(u.confidence),`decide: answer ${i}.confidence must be in [0,1]`);const l=s?.questions?.[i];l?.type==="choice"&&t(l.options.some(o=>o.value===u.value),`decide: answer ${i}.value must be one of the options`),l?.type==="noul"&&t(typeof u.value=="boolean",`decide: answer ${i}.value must be a boolean`),l?.type==="score"&&t(d(u.value),`decide: answer ${i}.value must be a number`)}return e}function P(e){t(a(e),"rerank: body must be an object"),t(n(e.query),"rerank: query (non-empty string) required"),t(Array.isArray(e.documents)&&e.documents.length>=1&&e.documents.length<=1e3&&e.documents.every(r=>typeof r=="string"),"rerank: documents must be 1–1000 strings");const s={query:e.query,documents:e.documents.slice()};return e.top_n!=null&&(t(Number.isInteger(e.top_n)&&e.top_n>=1,"rerank: top_n must be an integer ≥ 1"),s.top_n=e.top_n),e.model!=null&&(t(n(e.model),"rerank: model must be a non-empty string"),s.model=e.model),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"rerank: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function T(e,s=null){t(a(e),"rerank: response must be an object"),t(Array.isArray(e.results),"rerank: results[] required"),t(n(e.model),"rerank: model required"),t(d(e.ms)&&e.ms>=0,"rerank: ms required");const r=s?s.documents.length:1/0,i=new Set;let u=1/0;return e.results.forEach((l,o)=>{t(a(l)&&Number.isInteger(l.index)&&l.index>=0&&l.index<r,`rerank: result ${o} needs an index into the documents`),t(!i.has(l.index),`rerank: index ${l.index} listed twice`),i.add(l.index),t(d(l.relevance_score),`rerank: result ${o} needs relevance_score`),t(l.relevance_score<=u,"rerank: results must be ordered best first"),u=l.relevance_score}),s?.top_n!=null&&t(e.results.length<=s.top_n,`rerank: more than top_n (${s.top_n}) results`),e}function y(e){t(a(e),"capabilities: response must be an object"),t(Array.isArray(e.capabilities),"capabilities: capabilities[] required"),t(a(e.server)&&n(e.server.name)&&n(e.server.version),"capabilities: server {name, version} required");const s=new Set;for(const r of e.capabilities)t(a(r)&&x.includes(r.id),`capabilities: unknown capability id ${JSON.stringify(r?.id)}`),t(!s.has(r.id),`capabilities: ${r.id} listed twice`),s.add(r.id),t(r.route===b[r.id],`capabilities: ${r.id} must be served at ${b[r.id]}`),g.has(r.id)?(t(Array.isArray(r.providers)&&r.providers.length>0&&r.providers.every(n),`capabilities: ${r.id}.providers must be a non-empty string[]`),r.default!=null&&t(r.providers.includes(r.default),`capabilities: ${r.id}.default must be one of its providers`)):(t(Array.isArray(r.models)&&r.models.every(n),`capabilities: ${r.id}.models must be string[]`),r.default!=null&&t(r.models.includes(r.default),`capabilities: ${r.id}.default must be one of its models`)),r.labels!=null&&t(Array.isArray(r.labels)&&r.labels.every(n),`capabilities: ${r.id}.labels must be string[]`),r.stats!=null&&t(a(r.stats)&&(g.has(r.id)||d(r.stats.calls)),`capabilities: ${r.id}.stats needs calls`),r.runtime!=null&&t(a(r.runtime)&&n(r.runtime.state),`capabilities: ${r.id}.runtime needs state`),r.provider!=null&&j(r.provider,r.id);return e}function j(e,s="capability"){return t(a(e)&&p.includes(e.kind),`capabilities: ${s}.provider.kind must be one of ${p.join(", ")}`),e.egress!=null&&t(f.includes(e.egress),`capabilities: ${s}.provider.egress must be one of ${f.join(", ")}`),e.url!=null&&t(n(e.url)&&/^https?:\/\//.test(e.url),`capabilities: ${s}.provider.url must be http(s)`),e.adapter!=null&&t(n(e.adapter),`capabilities: ${s}.provider.adapter must be a string`),e.model!=null&&t(n(e.model),`capabilities: ${s}.provider.model must be a string`),e.label!=null&&t(n(e.label),`capabilities: ${s}.provider.label must be a string`),e}function B(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{x as CAPABILITIES,b as CAPABILITY_ROUTES,$ as DECIDE_QUESTION_TYPES,I as DISCOVERY_ROUTE,f as EGRESS_KINDS,A as OVER_BUDGET,g as PROVIDER_CAPABILITIES,p as PROVIDER_KINDS,c as READ_FORMATS,h as READ_RESTRICTIONS,v as SEARCH_FRESHNESS,B as offeredCapabilities,_ as overBudget,k as predictMs,y as validateCapabilitiesResponse,D as validateDecideRequest,z as validateDecideResponse,O as validateDetectRequest,w as validateDetectResponse,j as validateProvider,C as validateReadRequest,S as validateReadResponse,P as validateRerankRequest,T as validateRerankResponse,E as validateSearchRequest,N as validateSearchResponse};
|
|
1
|
+
import{EventError as A}from"./event.js";const k=Object.freeze(["detect","decide","rerank","embed","stt","tts","search","read","extract","chat","s2s"]),p=Object.freeze(["embedded","container","remote","harness","router","none"]),f=Object.freeze(["none","loopback","lan","internet","configurable"]),g=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",chat:"/v1/chat/completions",s2s:"/v1/audio/conversations"}),b=Object.freeze(new Set(["search","read","extract"])),v=Object.freeze(["day","week","month","year"]),h=Object.freeze(["login","paywall","rate_limited","robots","tdm"]),c=Object.freeze(["markdown","text"]),w="/v1/capabilities",S="over_budget",a=e=>!!e&&typeof e=="object"&&!Array.isArray(e),n=e=>typeof e=="string"&&e.length>0,o=e=>typeof e=="number"&&Number.isFinite(e),t=(e,s)=>{if(!e)throw new A("SHAPE",s)};function j(e,s){if(!a(e)||!(e.calls>0))return null;const r=o(e.p50Ms)?e.p50Ms:0,i=o(e.charsPerSec)&&e.charsPerSec>0&&o(s)?s/e.charsPerSec*1e3:0;return Math.round(Math.max(r,i))}function E(e,s,r){if(!o(r)||r<=0)return null;const i=j(e,s);return i===null||i<=r?null:{error:{type:S,message:`predicted ${i} ms is over the ${r} ms budget`,predictedMs:i,budgetMs:r}}}function O(e){t(a(e),"detect: body must be an object"),t(typeof e.text=="string","detect: text (string) required");const s={text:e.text};return e.model!=null&&(t(n(e.model),"detect: model must be a non-empty string"),s.model=e.model),e.labels!=null&&(t(Array.isArray(e.labels)&&e.labels.every(n),"detect: labels must be string[]"),s.labels=e.labels),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"detect: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),e.strict!=null&&(t(typeof e.strict=="boolean","detect: strict must be a boolean"),e.strict&&(s.strict=!0)),s}function N(e,s=null){t(a(e),"detect: response must be an object"),t(Array.isArray(e.entities),"detect: entities[] required"),t(n(e.model),"detect: model required"),t(o(e.ms)&&e.ms>=0,"detect: ms required");for(const r of e.entities)t(a(r)&&n(r.value)&&n(r.type),"detect: entity needs value and type"),t(Number.isInteger(r.start)&&Number.isInteger(r.end)&&r.start>=0&&r.end>r.start,`detect: entity ${JSON.stringify(r.value)} needs start < end`),t(o(r.score)&&r.score>=0&&r.score<=1,`detect: entity ${JSON.stringify(r.value)} needs a score in [0,1]`),typeof s=="string"&&t(s.slice(r.start,r.end)===r.value,`detect: entity ${JSON.stringify(r.value)} is not at ${r.start}–${r.end} of the text`);return e}const m=e=>{if(!n(e))return!1;try{const s=new URL(e);return s.protocol==="http:"||s.protocol==="https:"}catch{return!1}};function C(e){t(a(e),"search: body must be an object"),t(n(e.q)&&e.q.trim().length>0,"search: q (non-empty string) required");const s={q:e.q.trim()};return e.limit!=null&&(t(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&&(t(n(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&&(t(n(e.site)&&!/[\s/]/.test(e.site),"search: site must be a hostname"),s.site=e.site.toLowerCase()),e.freshness!=null&&(t(v.includes(e.freshness),`search: freshness must be one of ${v.join(", ")}`),s.freshness=e.freshness),e.read!=null&&(t(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&&(t(n(e.provider),"search: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"search: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function y(e){return t(a(e),"search: response must be an object"),t(Array.isArray(e.results),"search: results[] required"),t(n(e.provider),"search: provider required"),t(o(e.ms)&&e.ms>=0,"search: ms required"),e.results.forEach((s,r)=>{t(a(s)&&s.rank===r+1,`search: result ${r} must carry rank ${r+1}`),t(m(s.url),`search: result ${r+1} needs an absolute http(s) url`),t(n(s.title),`search: result ${r+1} needs a title`),t(typeof s.snippet=="string",`search: result ${r+1} needs a snippet (may be empty)`),s.read!=null&&R(s.read),s.engine!=null&&t(typeof s.engine=="string",`search: result ${r+1} engine must be a string`),s.via!=null&&t($.includes(s.via),`search: result ${r+1} via must be one of ${$.join(", ")}`)}),e.trail!=null&&(t(a(e.trail)&&x.includes(e.trail.status),`search: trail.status must be one of ${x.join(", ")}`),t(Array.isArray(e.trail.asked)&&e.trail.asked.every(s=>a(s)&&n(s.id)&&["answered","empty","refused"].includes(s.outcome)),"search: trail.asked[] needs { id, outcome }"),t(Array.isArray(e.trail.resting)&&e.trail.resting.every(s=>a(s)&&n(s.id)&&o(s.until)),"search: trail.resting[] needs { id, until }")),e}const $=Object.freeze(["gateway","searxng","api","page","browser"]),x=Object.freeze(["answered","nothing","blocked","resting","offline","no-engines"]);function z(e){t(a(e),"read: body must be an object"),t(m(e.url),"read: url (absolute http(s)) required");const s={url:e.url,format:"markdown"};return e.format!=null&&(t(c.includes(e.format),`read: format must be one of ${c.join(", ")}`),s.format=e.format),e.maxChars!=null&&(t(Number.isInteger(e.maxChars)&&e.maxChars>=200,"read: maxChars must be an integer ≥ 200"),s.maxChars=e.maxChars),e.snippet!=null&&(t(typeof e.snippet=="string","read: snippet must be a string"),s.snippet=e.snippet),e.provider!=null&&(t(n(e.provider),"read: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"read: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function R(e){t(a(e),"read: response must be an object"),t(m(e.url),"read: url (absolute, where the page landed) required"),t(typeof e.title=="string","read: title (string, may be empty) required"),t(c.includes(e.format),"read: format required");const s=e[e.format];t(typeof s=="string",`read: ${e.format} (string) required`),t(Number.isInteger(e.chars)&&e.chars===s.length,"read: chars must equal the content length"),t(typeof e.truncated=="boolean","read: truncated (boolean) required"),t(n(e.provider),"read: provider required"),t(o(e.ms)&&e.ms>=0,"read: ms required"),t(Array.isArray(e.sections),"read: sections[] required");for(const r of e.sections)t(a(r)&&n(r.id)&&n(r.heading),"read: section needs id and heading"),t(Number.isInteger(r.level)&&r.level>=1&&r.level<=6,`read: section ${r.id} needs level 1–6`),t(Number.isInteger(r.offset)&&r.offset>=0&&r.offset<=s.length,`read: section ${r.id} offset must index the content`);return e.restricted!=null&&t(a(e.restricted)&&h.includes(e.restricted.reason),`read: restricted.reason must be one of ${h.join(", ")}`),e}const q=Object.freeze(["choice","score","noul"]),M=/^[A-Za-z_][A-Za-z0-9_]*$/;function D(e){t(a(e),"decide: body must be an object"),t(n(e.state),"decide: state (non-empty string) required"),t(a(e.questions)&&Object.keys(e.questions).length>0,"decide: questions {} required");const s={};for(const[i,l]of Object.entries(e.questions)){t(M.test(i),`decide: question key ${JSON.stringify(i)} must be an identifier`),t(a(l)&&q.includes(l.type),`decide: question ${i}.type must be one of ${q.join(", ")}`),t(n(l.instructions),`decide: question ${i} needs instructions`);const u={type:l.type,instructions:l.instructions};l.type==="noul"?t(l.options==null,`decide: question ${i}: a noul has no options`):(t(Array.isArray(l.options)&&l.options.length>=2&&l.options.length<=255,`decide: question ${i}.options needs 2–255 entries`),u.options=l.options.map(d=>n(d)?{value:d}:(t(a(d)&&n(d.value),`decide: question ${i}: an option is a string or { value, describe? }`),d.describe!=null?{value:d.value,describe:String(d.describe)}:{value:d.value})),t(new Set(u.options.map(d=>d.value)).size===u.options.length,`decide: question ${i}.options must be distinct`)),s[i]=u}const r={state:e.state,questions:s};return e.model!=null&&(t(n(e.model),"decide: model must be a non-empty string"),r.model=e.model),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"decide: budgetMs must be a number ≥ 0"),r.budgetMs=e.budgetMs),r}function T(e,s=null){t(a(e),"decide: response must be an object"),t(a(e.answers),"decide: answers {} required"),t(n(e.model),"decide: model required"),t(o(e.ms)&&e.ms>=0,"decide: ms required"),e.calibrated!=null&&t(typeof e.calibrated=="boolean","decide: calibrated must be a boolean");const r=i=>o(i)&&i>=0&&i<=1;for(const i of Object.keys(s?s.questions:e.answers)){const l=e.answers[i];t(a(l),`decide: answer ${i} missing`),t(r(l.p),`decide: answer ${i}.p must be in [0,1]`),t(Array.isArray(l.options)&&l.options.every(d=>a(d)&&d.value!==void 0&&r(d.p)),`decide: answer ${i}.options must be [{ value, p }]`),l.confidence!=null&&t(r(l.confidence),`decide: answer ${i}.confidence must be in [0,1]`);const u=s?.questions?.[i];u?.type==="choice"&&t(u.options.some(d=>d.value===l.value),`decide: answer ${i}.value must be one of the options`),u?.type==="noul"&&t(typeof l.value=="boolean",`decide: answer ${i}.value must be a boolean`),u?.type==="score"&&t(o(l.value),`decide: answer ${i}.value must be a number`)}return e}function P(e){t(a(e),"rerank: body must be an object"),t(n(e.query),"rerank: query (non-empty string) required"),t(Array.isArray(e.documents)&&e.documents.length>=1&&e.documents.length<=1e3&&e.documents.every(r=>typeof r=="string"),"rerank: documents must be 1–1000 strings");const s={query:e.query,documents:e.documents.slice()};return e.top_n!=null&&(t(Number.isInteger(e.top_n)&&e.top_n>=1,"rerank: top_n must be an integer ≥ 1"),s.top_n=e.top_n),e.model!=null&&(t(n(e.model),"rerank: model must be a non-empty string"),s.model=e.model),e.budgetMs!=null&&(t(o(e.budgetMs)&&e.budgetMs>=0,"rerank: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function U(e,s=null){t(a(e),"rerank: response must be an object"),t(Array.isArray(e.results),"rerank: results[] required"),t(n(e.model),"rerank: model required"),t(o(e.ms)&&e.ms>=0,"rerank: ms required");const r=s?s.documents.length:1/0,i=new Set;let l=1/0;return e.results.forEach((u,d)=>{t(a(u)&&Number.isInteger(u.index)&&u.index>=0&&u.index<r,`rerank: result ${d} needs an index into the documents`),t(!i.has(u.index),`rerank: index ${u.index} listed twice`),i.add(u.index),t(o(u.relevance_score),`rerank: result ${d} needs relevance_score`),t(u.relevance_score<=l,"rerank: results must be ordered best first"),l=u.relevance_score}),s?.top_n!=null&&t(e.results.length<=s.top_n,`rerank: more than top_n (${s.top_n}) results`),e}function B(e){t(a(e),"capabilities: response must be an object"),t(Array.isArray(e.capabilities),"capabilities: capabilities[] required"),t(a(e.server)&&n(e.server.name)&&n(e.server.version),"capabilities: server {name, version} required");const s=new Set;for(const r of e.capabilities)t(a(r)&&k.includes(r.id),`capabilities: unknown capability id ${JSON.stringify(r?.id)}`),t(!s.has(r.id),`capabilities: ${r.id} listed twice`),s.add(r.id),t(r.route===g[r.id],`capabilities: ${r.id} must be served at ${g[r.id]}`),b.has(r.id)?(t(Array.isArray(r.providers)&&r.providers.length>0&&r.providers.every(n),`capabilities: ${r.id}.providers must be a non-empty string[]`),r.default!=null&&t(r.providers.includes(r.default),`capabilities: ${r.id}.default must be one of its providers`)):(t(Array.isArray(r.models)&&r.models.every(n),`capabilities: ${r.id}.models must be string[]`),r.default!=null&&t(r.models.includes(r.default),`capabilities: ${r.id}.default must be one of its models`)),r.labels!=null&&t(Array.isArray(r.labels)&&r.labels.every(n),`capabilities: ${r.id}.labels must be string[]`),r.stats!=null&&t(a(r.stats)&&(b.has(r.id)||o(r.stats.calls)),`capabilities: ${r.id}.stats needs calls`),r.runtime!=null&&t(a(r.runtime)&&n(r.runtime.state),`capabilities: ${r.id}.runtime needs state`),r.provider!=null&&I(r.provider,r.id);return e}function I(e,s="capability"){return t(a(e)&&p.includes(e.kind),`capabilities: ${s}.provider.kind must be one of ${p.join(", ")}`),e.egress!=null&&t(f.includes(e.egress),`capabilities: ${s}.provider.egress must be one of ${f.join(", ")}`),e.url!=null&&t(n(e.url)&&/^https?:\/\//.test(e.url),`capabilities: ${s}.provider.url must be http(s)`),e.adapter!=null&&t(n(e.adapter),`capabilities: ${s}.provider.adapter must be a string`),e.model!=null&&t(n(e.model),`capabilities: ${s}.provider.model must be a string`),e.label!=null&&t(n(e.label),`capabilities: ${s}.provider.label must be a string`),e}function H(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{k as CAPABILITIES,g as CAPABILITY_ROUTES,q as DECIDE_QUESTION_TYPES,w as DISCOVERY_ROUTE,f as EGRESS_KINDS,S as OVER_BUDGET,b as PROVIDER_CAPABILITIES,p as PROVIDER_KINDS,c as READ_FORMATS,h as READ_RESTRICTIONS,v as SEARCH_FRESHNESS,x as SEARCH_TRAIL_STATUSES,$ as SEARCH_VIAS,H as offeredCapabilities,E as overBudget,j as predictMs,B as validateCapabilitiesResponse,D as validateDecideRequest,T as validateDecideResponse,O as validateDetectRequest,N as validateDetectResponse,I as validateProvider,z as validateReadRequest,R as validateReadResponse,P as validateRerankRequest,U as validateRerankResponse,C as validateSearchRequest,y as validateSearchResponse};
|
package/src/configstore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{writeFileSync as A,mkdirSync as w,chmodSync as k}from"node:fs";import{join as x,dirname as f}from"node:path";import E from"node:os";import{usage as D}from"./freegate.js";import{applyFusionsPatch as S}from"./fusions.js";import{EMBEDDED_MODELS as c,EMBEDDED_IDS as m,isEmbeddedModel as T}from"./embedded-models.js";import{normalizeRegistries as v,REGISTRY_KINDS as N}from"@chatpanel/events/registries.js";import{assertEndpointUrl as d}from"@chatpanel/pii";import{normalizeGrant as _}from"@chatpanel/bridge/src/events/sandbox-policy.js";const O=["open","allowlist","off"],b=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function l(e={}){const r=e&&typeof e=="object"?e:{},o=O.includes(r.mode)?r.mode:"open",{hosts:i}=_({hosts:r.hosts??[]});return{mode:o,hosts:i,write:b(r.write),denyRead:b(r.denyRead)}}function B(e){const r=l(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function p(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||x(E.homedir(),".chatpanel","gateway.config.json")}function U(e){const r=e?.registries||{},o={};for(const[i,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[i]&&(o[t]=r[i]);return o}function K(e,r=p()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===p({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);w(f(r),{recursive:!0,mode:448});const o={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp,link:e.link};A(r,JSON.stringify(o,null,2),{mode:384});try{k(r,384)}catch{}}function Y(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:i,...t}=o;return{...t,hasKey:!!i}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:o,...i}=e.redaction?.detection||{backend:"off"};return i})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:l(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0}},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([o,i])=>{const{token:t,...n}=i||{};return[o,{...n,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:D(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function F(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function R(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),t=Number(o.port)||(o.protocol==="https:"?443:80);return i&&t===(Number(r.port)||4320)}const y=["default","acceptEdits","bypassPermissions"];function $(e,r={}){const o=e?.bridge||{};return{...y.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function q(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const o=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=r.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const t=R(i,e);return t&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!t}).map(i=>{const t={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(t.agent=i.agent||i.id),i.type==="api"){t.baseUrl=String(i.baseUrl||""),t.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;s&&(t.apiKey=s)}const n=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;return n&&(t.service=n),t})}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),y.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(o=>String(o).trim()).filter(o=>/^[a-p]{32}$/.test(o))),r.upstreams&&typeof r.upstreams=="object")for(const o of["openai","anthropic"]){const i=r.upstreams[o];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:i.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const o=r.redaction;(o.tier==="basic"||o.tier==="full")&&(e.redaction.tier=o.tier),"redactSystem"in o&&(e.redaction.redactSystem=!!o.redactSystem),Array.isArray(o.dictionary)&&(e.redaction.dictionary=o.dictionary),o.detection&&typeof o.detection=="object"&&(e.redaction.detection=o.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=l({...e.sandbox||{},...r.sandbox})),r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const o=String(r.read.remote.url||"").trim();o&&d(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.registries&&typeof r.registries=="object"){const o=v(r.registries),i={...e.registries||{}};for(const t of N)t in r.registries&&(o[t]?i[t]=o[t]:delete i[t]);e.registries=i}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&d(i),e.search.searxng.url=i}typeof o.token=="string"&&(e.search.searxng.token=o.token),typeof o.engines=="string"&&(e.search.searxng.engines=o.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(o.safesearch)&&(e.search.searxng.safesearch=o.safesearch)}["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const o=S(e,r.fusions);if(o){const i=new Error(o);throw i.code="SHAPE",i}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const o of["rerank","decide","stt","tts","detect","embed"]){if(!(o in r.capabilities))continue;const i=r.capabilities[o];if(i===null){delete e.capabilities[o],o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!i||typeof i!="object")continue;const t=e.capabilities[o]||{},n={...t};if(i.provider==="embedded"){if(m.includes(o)&&i.model!=null){if(!T(o,i.model)){const s=new Error(`capabilities.${o}.model must be one of ${c[o].map(a=>a.id).join(", ")}`);throw s.code="SHAPE",s}e.capabilities[o]={provider:"embedded",model:i.model};continue}e.capabilities[o]={provider:"embedded"},o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(i.provider==="none"&&m.includes(o)){e.capabilities[o]={provider:"none"};continue}if("url"in i){const s=String(i.url||"").trim();s&&d(s);const a=u=>{try{return new URL(u).origin}catch{return u}};t.url&&s&&a(t.url)!==a(s)&&typeof i.token!="string"&&delete n.token,n.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(n.adapter=i.adapter),typeof i.model=="string"&&(n.model=i.model.trim()),typeof i.token=="string"&&(n.token=i.token),typeof i.calibrated=="boolean"&&(n.calibrated=i.calibrated),typeof i.redact=="boolean"&&(n.redact=i.redact),!n.url){delete e.capabilities[o];continue}n.provider="remote",delete n.service,e.capabilities[o]=n,o==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}})}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const o=Number(r.tools.maxPerTurn);Number.isFinite(o)&&o>=1&&(e.tools.maxPerTurn=Math.floor(o))}return e}export{y as PERMISSION_MODES,q as applyConfigPatch,F as applyNerModelSelection,$ as bridgeAgentOptions,p as configPath,R as isSelfDestination,l as normalizeSandboxConfig,K as persistConfig,Y as publicConfig,U as registryChildEnv,B as sandboxEnvFor};
|
|
1
|
+
import{patchApis as A,viewApis as w}from"./retrieval/search-apis.js";import{writeFileSync as k,mkdirSync as x,chmodSync as f}from"node:fs";import{join as E,dirname as D}from"node:path";import S from"node:os";import{usage as c}from"./freegate.js";import{applyFusionsPatch as v}from"./fusions.js";import{EMBEDDED_MODELS as T,EMBEDDED_IDS as m,isEmbeddedModel as N}from"./embedded-models.js";import{normalizeRegistries as _,REGISTRY_KINDS as O}from"@chatpanel/events/registries.js";import{assertEndpointUrl as d}from"@chatpanel/pii";import{normalizeGrant as R}from"@chatpanel/bridge/src/events/sandbox-policy.js";const P=["open","allowlist","off"],p=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function l(e={}){const r=e&&typeof e=="object"?e:{},i=P.includes(r.mode)?r.mode:"open",{hosts:o}=R({hosts:r.hosts??[]});return{mode:i,hosts:o,write:p(r.write),denyRead:p(r.denyRead)}}function g(e){const r=l(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function b(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||E(S.homedir(),".chatpanel","gateway.config.json")}function F(e){const r=e?.registries||{},i={};for(const[o,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[o]&&(i[t]=r[o]);return i}function $(e,r=b()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===b({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);x(D(r),{recursive:!0,mode:448});const i={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp,link:e.link};k(r,JSON.stringify(i,null,2),{mode:384});try{f(r,384)}catch{}}function q(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(i=>{const{apiKey:o,...t}=i;return{...t,hasKey:!!o}}),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:i,...o}=e.redaction?.detection||{backend:"off"};return o})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:l(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0},apis:w(e)},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([i,o])=>{const{token:t,...n}=o||{};return[i,{...n,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:c(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 W(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function j(e,r={}){if(!e||e.type!=="api")return!1;let i;try{i=new URL(String(e.baseUrl||""))}catch{return!1}const o=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(i.hostname),t=Number(i.port)||(i.protocol==="https:"?443:80);return o&&t===(Number(r.port)||4320)}const y=["default","acceptEdits","bypassPermissions"];function X(e,r={}){const i=e?.bridge||{};return{...y.includes(i.permissionMode)&&i.permissionMode!=="default"?{permissionMode:i.permissionMode}:{},...typeof i.workingDir=="string"&&i.workingDir.trim()?{workingDir:i.workingDir.trim()}:{},...r}}function z(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const i=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(o=>[o.id,o]));e.destinations=r.destinations.filter(o=>o&&typeof o.id=="string"&&(o.type==="agent"||o.type==="api")).filter(o=>{const t=j(o,e);return t&&console.log(`[gateway] refusing destination "${o.id}": ${o.baseUrl} is this gateway — a loop`),!t}).map(o=>{const t={id:o.id,type:o.type,models:Array.isArray(o.models)?o.models.filter(s=>typeof s=="string"&&s):[]};if(o.type==="agent"&&(t.agent=o.agent||o.id),o.type==="api"){t.baseUrl=String(o.baseUrl||""),t.protocol=o.protocol==="anthropic"?"anthropic":"openai";const s=typeof o.apiKey=="string"&&o.apiKey?o.apiKey:i.get(o.id)?.apiKey;s&&(t.apiKey=s)}const n=typeof o.service=="string"&&o.service?o.service:i.get(o.id)?.service;return n&&(t.service=n),t})}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),y.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(i=>String(i).trim()).filter(i=>/^[a-p]{32}$/.test(i))),r.upstreams&&typeof r.upstreams=="object")for(const i of["openai","anthropic"]){const o=r.upstreams[i];o&&typeof o.baseUrl=="string"&&o.baseUrl.trim()&&(e.upstreams[i]={...e.upstreams[i],baseUrl:o.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const i=r.redaction;(i.tier==="basic"||i.tier==="full")&&(e.redaction.tier=i.tier),"redactSystem"in i&&(e.redaction.redactSystem=!!i.redactSystem),Array.isArray(i.dictionary)&&(e.redaction.dictionary=i.dictionary),i.detection&&typeof i.detection=="object"&&(e.redaction.detection=i.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=l({...e.sandbox||{},...r.sandbox})),r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const i=String(r.read.remote.url||"").trim();i&&d(i),e.read.remote.url=i}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.registries&&typeof r.registries=="object"){const i=_(r.registries),o={...e.registries||{}};for(const t of O)t in r.registries&&(i[t]?o[t]=i[t]:delete o[t]);e.registries=o}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 i=r.search.searxng;if(i&&typeof i=="object"){if("url"in i){const o=String(i.url||"").trim();o&&d(o),e.search.searxng.url=o}typeof i.token=="string"&&(e.search.searxng.token=i.token),typeof i.engines=="string"&&(e.search.searxng.engines=i.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(i.safesearch)&&(e.search.searxng.safesearch=i.safesearch)}"apis"in r.search&&(e.search.apis=A(e.search.apis,r.search.apis)),["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const i=v(e,r.fusions);if(i){const o=new Error(i);throw o.code="SHAPE",o}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const i of["rerank","decide","stt","tts","detect","embed"]){if(!(i in r.capabilities))continue;const o=r.capabilities[i];if(o===null){delete e.capabilities[i],i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!o||typeof o!="object")continue;const t=e.capabilities[i]||{},n={...t};if(o.provider==="embedded"){if(m.includes(i)&&o.model!=null){if(!N(i,o.model)){const s=new Error(`capabilities.${i}.model must be one of ${T[i].map(a=>a.id).join(", ")}`);throw s.code="SHAPE",s}e.capabilities[i]={provider:"embedded",model:o.model};continue}e.capabilities[i]={provider:"embedded"},i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(o.provider==="none"&&m.includes(i)){e.capabilities[i]={provider:"none"};continue}if("url"in o){const s=String(o.url||"").trim();s&&d(s);const a=u=>{try{return new URL(u).origin}catch{return u}};t.url&&s&&a(t.url)!==a(s)&&typeof o.token!="string"&&delete n.token,n.url=s}if(typeof o.adapter=="string"&&/^[a-z-]+$/.test(o.adapter)&&(n.adapter=o.adapter),typeof o.model=="string"&&(n.model=o.model.trim()),typeof o.token=="string"&&(n.token=o.token),typeof o.calibrated=="boolean"&&(n.calibrated=o.calibrated),typeof o.redact=="boolean"&&(n.redact=o.redact),!n.url){delete e.capabilities[i];continue}n.provider="remote",delete n.service,e.capabilities[i]=n,i==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}})}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const i=Number(r.tools.maxPerTurn);Number.isFinite(i)&&i>=1&&(e.tools.maxPerTurn=Math.floor(i))}return e}export{y as PERMISSION_MODES,z as applyConfigPatch,W as applyNerModelSelection,X as bridgeAgentOptions,b as configPath,j as isSelfDestination,l as normalizeSandboxConfig,$ as persistConfig,q as publicConfig,F as registryChildEnv,g as sandboxEnvFor};
|
package/src/egress.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{linkPaths as k}from"@chatpanel/events/link-routes.js";import{isBlockedHost as m}from"@chatpanel/pii";const $=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),a=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[a]||"",scheme:a}}catch{return null}}const w=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:m(t,{allowLoopback:!1,allowPrivate:!1})&&!m(t,{allowLoopback:!0,allowPrivate:!0})};function E({clock:e=$}={}){const t=new Map;return{record(a){const n=g(a);if(!n||!n.host)return;const r=`${n.scheme}://${n.host}:${n.port}`,i=e(),c=t.get(r);if(c){c.count+=1,c.lastAt=i;return}t.set(r,{host:n.host,port:n.port,scheme:n.scheme,local:w(n.host),count:1,firstAt:i,lastAt:i})},snapshot(){return[...t.values()].sort((a,n)=>a.local===n.local?n.count-a.count:a.local?1:-1)},reset(){t.clear()}}}let y=null;function R(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const a=E();let n=t;a.setGate=d=>{n=d},a.blocked=[];const r=d=>{let s=null;try{s=g(d),a.record(d)}catch{}if(!n||!s?.host)return null;let u=!0;try{u=n(`${s.scheme}://${s.host}:${s.port}`,{local:w(s.host)})}catch{u=!0}if(u)return null;const o=`${s.host}:${s.port}`;a.blocked.includes(o)||a.blocked.push(o);const l=new Error(`egress to ${s.host} is blocked by your organisation’s policy`);return l.code="EGRESS_POLICY",l},i=e.fetch;typeof i=="function"&&(e.fetch=function(s,u){const o=r(s);return o?Promise.reject(o):i.call(this,s,u)});const c=e.WebSocket;return typeof c=="function"&&(e.WebSocket=new Proxy(c,{construct(d,s,u){const o=r(s[0]);if(o)throw o;return Reflect.construct(d,s,u)}})),e.__chatpanelEgress=a,e===globalThis&&(y=a),a}function L(){return y||(globalThis.__chatpanelEgress??null)}function p(e){try{return new URL(e).host}catch{return String(e||"")}}function S(e={},t=process.env,a=process.platform){const n=[],r=(o,l,{when:h="always",off:f=null,local:b=!1,data:v=""}={})=>{o&&n.push({host:o,purpose:l,when:h,off:f,local:b,data:v})};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"}),t.CHATPANEL_ORT_DIR||r("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"});const i=e.link?.enabled===!1?null:k(e.link||{}).relay;if(i){const o=new URL(i).host;r(o,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone is paired (Settings › Link your phone), and while pairing",off:"link.enabled = false, or remove every paired phone",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}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 c=e.search?.searxng?.url||"";if(c){let o=c;try{o=new URL(c).host}catch{}r(o,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(o)})}if(e.search?.provider!=="searxng"&&(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 o=e.read.remote.url;try{o=new URL(e.read.remote.url).host}catch{}r(o,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(o)})}const d={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[o,l]of Object.entries(d)){const h=e.capabilities?.[o];if(!h?.url||h.provider==="embedded")continue;let f=h.url;try{f=new URL(h.url).host}catch{}r(f,`${l.what}${h.service?` (the ${h.service} container, started under Settings › Runtime)`:` (${h.adapter} at the address you configured)`}`,{when:`a client calls /v1/${o}`,off:h.service?`stop the ${h.service} service under Settings › Runtime`:`capabilities.${o} = null`,data:`${l.data}${h.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(f)})}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[o,l]of Object.entries(e.upstreams||{}))l?.baseUrl&&r(p(l.baseUrl),`model upstream "${o}" — chat requests (after redaction) go here`,{when:`a request addressed to ${o}`,off:`upstreams.${o}.baseUrl`,local:w(p(l.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const o of e.destinations||[])o?.baseUrl&&r(p(o.baseUrl),`destination "${o.id||o.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${o.id||"it"}`,off:"destinations[]",local:w(p(o.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(p(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:w(p(e.ner.url).split(":")[0]),data:"the text being redacted"});const s=e.tts||{};if(s.provider==="openai"||s.provider==="elevenlabs"){const o=s.remote?.baseUrl?p(s.remote.baseUrl):s.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";r(o,`remote read-aloud voice (${s.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:s.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}a==="darwin"&&e.runtime?.heatwatch!==!1&&r("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const u=e.bridge?.url||"http://127.0.0.1:4319";return r(p(u),"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"}),n}function A(e,{ledger:t=L(),version:a="",startedAt:n=null,env:r=process.env,managed:i=null}={}){return{ok:!0,version:a,since:n?new Date(n).toISOString():null,...i?{managed:i,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. 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:S(e,r)}}function U(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 a of e.observed||[])t.push(` ${a.local?"[local] ":""}${a.scheme}://${a.host}:${a.port} ×${a.count} last ${a.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const a of e.declared||[])t.push(` ${a.local?"[local] ":""}${a.host}`),t.push(` ${a.purpose}`),t.push(` when: ${a.when}${a.off?` · off: ${a.off}`:""}`),a.data&&t.push(` sends: ${a.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(([,a])=>a).map(([a,n])=>n===!0?a:`${a}=${n}`).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{
|
|
1
|
+
import{searchEngines as k}from"./retrieval/search-apis.js";import{linkPaths as $}from"@chatpanel/events/link-routes.js";import{isBlockedHost as m}from"@chatpanel/pii";const E=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),s=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[s]||"",scheme:s}}catch{return null}}const w=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:m(t,{allowLoopback:!1,allowPrivate:!1})&&!m(t,{allowLoopback:!0,allowPrivate:!0})};function L({clock:e=E}={}){const t=new Map;return{record(s){const r=g(s);if(!r||!r.host)return;const o=`${r.scheme}://${r.host}:${r.port}`,h=e(),c=t.get(o);if(c){c.count+=1,c.lastAt=h;return}t.set(o,{host:r.host,port:r.port,scheme:r.scheme,local:w(r.host),count:1,firstAt:h,lastAt:h})},snapshot(){return[...t.values()].sort((s,r)=>s.local===r.local?r.count-s.count:s.local?1:-1)},reset(){t.clear()}}}let y=null;function U(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const s=L();let r=t;s.setGate=d=>{r=d},s.blocked=[];const o=d=>{let n=null;try{n=g(d),s.record(d)}catch{}if(!r||!n?.host)return null;let u=!0;try{u=r(`${n.scheme}://${n.host}:${n.port}`,{local:w(n.host)})}catch{u=!0}if(u)return null;const a=`${n.host}:${n.port}`;s.blocked.includes(a)||s.blocked.push(a);const i=new Error(`egress to ${n.host} is blocked by your organisation’s policy`);return i.code="EGRESS_POLICY",i},h=e.fetch;typeof h=="function"&&(e.fetch=function(n,u){const a=o(n);return a?Promise.reject(a):h.call(this,n,u)});const c=e.WebSocket;return typeof c=="function"&&(e.WebSocket=new Proxy(c,{construct(d,n,u){const a=o(n[0]);if(a)throw a;return Reflect.construct(d,n,u)}})),e.__chatpanelEgress=s,e===globalThis&&(y=s),s}function P(){return y||(globalThis.__chatpanelEgress??null)}function p(e){try{return new URL(e).host}catch{return String(e||"")}}function S(e={},t=process.env,s=process.platform){const r=[],o=(a,i,{when:l="always",off:f=null,local:b=!1,data:v=""}={})=>{a&&r.push({host:a,purpose:i,when:l,off:f,local:b,data:v})};o("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"}),o("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"}),o("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),t.CHATPANEL_ORT_DIR||o("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"});const h=e.link?.enabled===!1?null:$(e.link||{}).relay;if(h){const a=new URL(h).host;o(a,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone is paired (Settings › Link your phone), and while pairing",off:"link.enabled = false, or remove every paired phone",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}o("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 c=e.search?.searxng?.url||"";if(c){let a=c;try{a=new URL(c).host}catch{}o(a,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(a)})}if(e.search?.provider!=="searxng"){o("www.startpage.com","web search: the built-in results-page search, one of three engines",{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"}),o("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),o("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const a of k(e).filter(i=>i.kind==="api"&&i.enabled!==!1))o(a.api.host,`web search: ${a.api.name} (search API${a.api.needsKey?", with the key you gave it":", no key"})`,{when:"the same as www.startpage.com — one engine per search, a keyed API asked first",off:`search.apis: [{ id: "${a.api.id}", enabled: false }]`,data:"the same query"})}if(e.read?.remote?.url){let a=e.read.remote.url;try{a=new URL(e.read.remote.url).host}catch{}o(a,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(a)})}const d={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[a,i]of Object.entries(d)){const l=e.capabilities?.[a];if(!l?.url||l.provider==="embedded")continue;let f=l.url;try{f=new URL(l.url).host}catch{}o(f,`${i.what}${l.service?` (the ${l.service} container, started under Settings › Runtime)`:` (${l.adapter} at the address you configured)`}`,{when:`a client calls /v1/${a}`,off:l.service?`stop the ${l.service} service under Settings › Runtime`:`capabilities.${a} = null`,data:`${i.data}${l.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(f)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(o("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"}),o("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[a,i]of Object.entries(e.upstreams||{}))i?.baseUrl&&o(p(i.baseUrl),`model upstream "${a}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a}`,off:`upstreams.${a}.baseUrl`,local:w(p(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const a of e.destinations||[])a?.baseUrl&&o(p(a.baseUrl),`destination "${a.id||a.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a.id||"it"}`,off:"destinations[]",local:w(p(a.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});o("(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&&o(p(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:w(p(e.ner.url).split(":")[0]),data:"the text being redacted"});const n=e.tts||{};if(n.provider==="openai"||n.provider==="elevenlabs"){const a=n.remote?.baseUrl?p(n.remote.baseUrl):n.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(a,`remote read-aloud voice (${n.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:n.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}s==="darwin"&&e.runtime?.heatwatch!==!1&&o("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const u=e.bridge?.url||"http://127.0.0.1:4319";return o(p(u),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),r}function q(e,{ledger:t=P(),version:s="",startedAt:r=null,env:o=process.env,managed:h=null}={}){return{ok:!0,version:s,since:r?new Date(r).toISOString():null,...h?{managed:h,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. 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:S(e,o)}}function T(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 s of e.observed||[])t.push(` ${s.local?"[local] ":""}${s.scheme}://${s.host}:${s.port} ×${s.count} last ${s.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const s of e.declared||[])t.push(` ${s.local?"[local] ":""}${s.host}`),t.push(` ${s.purpose}`),t.push(` when: ${s.when}${s.off?` · off: ${s.off}`:""}`),s.data&&t.push(` sends: ${s.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(([,s])=>s).map(([s,r])=>r===!0?s:`${s}=${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{L as createEgressLedger,S as declaredEgress,q as egressAudit,P as egressLedger,T as formatAudit,U as installEgressLedger};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{engineOrder as A,mergeEngineResults as M,offTopic as x,isSearchPage as U}from"./web-search.js";import{tagResults as E,searchStatus as R}from"./search-outcome.js";const S=Object.freeze({gapMs:2e4,firstRestMs:2*6e4,maxRestMs:60*6e4,emptyStrikes:3});function O({status:i=0,timedOut:d=!1,network:o=!1,results:f=[]}={}){return Array.isArray(f)&&f.length?"answered":d||o||i===429||i===403||i>=500||i===-1?"refused":"empty"}function N({now:i=()=>Date.now(),random:d=Math.random,...o}={}){const f={...S,...o},c=new Map,p=n=>c.get(n)||{askedAt:0,empties:0,refusals:0,restUntil:0};function y(n,r){n.refusals+=1,n.restUntil=i()+Math.min(f.maxRestMs,r||f.firstRestMs*2**(n.refusals-1))}return{order(n){const r=i(),u=A(n),a=u.filter(t=>t.kind==="gateway"&&t.enabled!==!1),k=t=>t.kind==="api"&&t.needsKey,s=[u.filter(t=>k(t)&&t.enabled!==!1),u.filter(t=>t.kind!=="gateway"&&!k(t)&&t.enabled!==!1),u.filter(t=>!a.includes(t)&&t.enabled===!1)],m=t=>t.filter(e=>e.kind==="gateway"||p(e.id).restUntil<=r).map(e=>{const l=p(e.id),g=1/(1+l.empties)*(r-l.askedAt<f.gapMs?.1:1);return{e,key:Math.pow(d()||Number.MIN_VALUE,1/g)}}).sort((e,l)=>l.key-e.key).map(({e})=>e);return[...a,...s.flatMap(m)]},record(n,r,{retryAfterMs:u=0}={}){const a={...p(n),askedAt:i()};r==="answered"?(a.empties=0,a.refusals=0,a.restUntil=0):r==="refused"?y(a,u):++a.empties>=f.emptyStrikes&&(a.empties=0,y(a)),c.set(n,a)},resting(){const n=i();return[...c].filter(([,r])=>r.restUntil>n).map(([r,u])=>({id:r,until:u.restUntil}))}}}async function P(i,d,{pacer:o,limit:f=8,signal:c,lastResort:p=null,query:y=""}={}){const n=[],r=[],u=o.order(i),a=async(s,m)=>{let t;try{t=await m(s)}catch{t={network:!0}}const e=Array.isArray(t)?{results:t}:t||{};let l=(Array.isArray(e.results)?e.results:[]).filter(h=>!U(h?.url));const g=s.kind!=="gateway"&&!(s.kind==="api"&&s.needsKey);if(y&&g&&x(l,y)&&(l=[]),c?.aborted)return null;const b=O({...e,results:l});s.kind!=="gateway"&&s.kind!=="tab"&&o.record(s.id,b,{retryAfterMs:e.retryAfterMs});const w={id:s.id,found:l.length,outcome:b};return e.status&&(w.status=e.status),e.timedOut&&(w.timedOut=!0),(e.network||!e.status&&!e.timedOut&&b==="refused")&&(w.network=!0),n.push(w),l.length?E(l,s):null};for(const s of u){if(c?.aborted)break;const m=await a(s,d);if(m){r.push(m);break}}if(!r.length&&typeof p=="function"&&!c?.aborted){const s=await a({id:"browser",kind:"tab"},()=>p(u));s&&r.push(s)}const k={results:M(r,f),asked:n,resting:o.resting()};return{...k,status:R(k)}}function j(i,d=Date.now()){const o=String(i??"").trim();if(!o)return 0;if(/^\d+$/.test(o))return Number(o)*1e3;const f=Date.parse(o);return Number.isFinite(f)?Math.max(0,f-d):0}export{S as PACER_DEFAULTS,O as classifyAnswer,N as createEnginePacer,j as retryAfterMs,P as searchPolitely};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{PROBE_PATHS as h,engineOf as d,localModelCard as g,redactionFor as u}from"@chatpanel/events/local-engine.js";const w=10*6e4,b=6e4,m=1500,O=new Set(["localhost","127.0.0.1","::1","[::1]"]);function S(o){try{const e=new URL(String(o||""));return!/^https?:$/.test(e.protocol)||!O.has(e.hostname)?"":`${e.protocol}//${e.host}`}catch{return""}}function M({fetchImpl:o=globalThis.fetch,now:e=()=>Date.now(),timeoutMs:p=m,first:s=null}={}){const c=new Map;async function f(n){const r={};return await Promise.all(h.map(async t=>{try{const a=await o(`${n}${t}`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(p)});r[t]={status:a.status,json:await a.json().catch(()=>null)}}catch{}})),d(r)}async function l(n){const r=s?await Promise.resolve(s(n)).catch(()=>null):null;if(r)return r;const t=c.get(n);if(t?.pending)return t.pending;if(t&&e()-t.at<(t.found?w:b))return t.found;const a=f(n).then(i=>(c.set(n,{at:e(),found:i}),i),()=>(c.set(n,{at:e(),found:null}),null));return c.set(n,{...t||{},pending:a}),a}return{async decide(n,r){const t=S(n?.baseUrl),a=u({dest:n,loopback:!!t,card:null});return!t||n?.redact===!0||n?.local===!0||n?.service?a:u({dest:n,loopback:!0,card:g(await l(t),r)})},engineAt:l,reset(){c.clear()}}}export{M as createEngineProbe,S as loopbackRoot};
|
package/src/ner-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import nt from"node:os";import{join as O}from"node:path";import{existsSync as Y,mkdirSync as rt,readdirSync as B,readFileSync as ot}from"node:fs";import{DEFAULT_MODEL as J,isMirroredModel as st}from"./models.js";import{isLoopbackHost as it,isPrivateHost as at,isMetadataHost as lt}from"@chatpanel/pii";import{recaseForDetection as ct}from"@chatpanel/pii/pii-detect.js";import{verifyModelWeights as ut}from"./model-integrity.js";import{runtimeName as ft}from"./model-runtime.js";import{nativeOrtFailure as pt}from"./ort.js";import{makeWarmTimer as G}from"./warm-timer.js";import{makeModelFileCache as dt}from"./model-file-cache.js";const E="https://dl.chatpanel.net/models/";function mt(t=process.env){const e=t.CHATPANEL_MODEL_BASE_URL?"CHATPANEL_MODEL_BASE_URL":"registries.models",r=t.CHATPANEL_MODEL_BASE_URL||t.CHATPANEL_REGISTRY_MODELS;if(!r)return E;const o=c=>(console.warn(`[models] ignoring ${e} (${r}): ${c} — using ${E}`),E);let n;try{n=new URL(r)}catch{return o("not a valid URL")}if(n.protocol!=="http:"&&n.protocol!=="https:")return o(`scheme ${n.protocol} not allowed`);if(lt(n.hostname))return o("points at cloud metadata");const s=it(n.hostname)||at(n.hostname);return n.protocol==="http:"&&!s?o("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${n.origin} (${e}), not ${E}`),r.replace(/\/*$/,"/"))}const ht=mt();let d="off",g=null,y=null,M=null,L=null,A=null,b=null,T=null,_=null,C=0,v=null;const m=new Map;function N(){return process.env.CHATPANEL_MODELS_DIR||O(nt.homedir(),".chatpanel","models")}function R(t=g||J){const e=O(N(),...t.split("/"));return Y(O(e,"onnx","model_quantized.onnx"))||Y(O(e,"onnx","model.onnx"))}function zt(){const t=N(),e=[];try{for(const r of B(t,{withFileTypes:!0}))if(r.isDirectory())for(const o of B(O(t,r.name),{withFileTypes:!0})){if(!o.isDirectory())continue;const n=`${r.name}/${o.name}`;R(n)&>(O(t,r.name,o.name))&&e.push(n)}}catch{}return e}function gt(t){try{return(JSON.parse(ot(O(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function Yt(){return d}function $(){return d==="ready"&&!!y}function Bt(){return{configured:d!=="off",ok:$(),state:d,model:g,error:M,runtime:ft(),dtype:y?"q8":null,stats:kt(),companions:bt(),warmMs:_?.warmMs??null}}async function yt(t,{signal:e}={}){if(!$())return[];if(e?.aborted)return[];const r=String(t||""),o=await Q(r,e);if(!o)return[];const n=[];for(const i of o||[]){let u=String(i.word??"");const a=i.entity_group??i.entity??"ENTITY";if(u.startsWith("##")&&n.length&&n[n.length-1].type===a){n[n.length-1].value+=u.slice(2);continue}u=u.replace(/##/g,"").trim(),u&&n.push({value:u,type:a})}const s=new Set,c=[];for(const i of n){const u=vt(r,At(r,i.value.trim()));if(u.length<=1)continue;const a=`${i.type}:${u.toLowerCase()}`;s.has(a)||(s.add(a),c.push({value:u,type:i.type}))}return c}async function Q(t,e){C++;try{return await wt(t,e)}finally{C--,k()||_?.arm()}}async function wt(t,e){const r=performance.now(),o=[],n=[{text:t,key:"orig"}];if(H){const s=ct(t);s.changed&&n.push({text:s.text,key:"recased"})}for(const{model:s,pipe:c}of V())for(const i of n){let u=0;for(const a of Ot(i.text,c.tokenizer)){if(e?.aborted)return null;const l=i.text.indexOf(a,u),f=await c(a,{aggregation_strategy:"simple"});for(const p of f||[])o.push({...p,_win:l<0?u:l,_winText:a,_model:s,_pass:i.key,_passText:i.text});l>=0&&(u=Math.max(u,l+1))}}return $t(performance.now()-r,t.length,o.length),o}let H=!0;function Jt(t){H=t!==!1}async function Gt(t,{signal:e}={}){if(!$())return[];const r=String(t||""),o=await Q(r,e);if(!o)return[];const n=[],s=new Set;let c=-1,i=-1,u=null,a=null;for(const f of o){const p=String(f.word??"").replace(/##/g,"").trim();if(!p)continue;(f._win!==i||f._model!==u||f._pass!==a)&&(i=f._win,u=f._model,a=f._pass,c=f._win);const x=f._passText||r;let h=x.indexOf(p,c);if(h<0&&(h=x.indexOf(p,f._win)),h<0)continue;let S=h+p.length;c=S;const W=z=>!!z&&/[\p{L}\p{N}'’-]/u.test(z);for(;h>0&&W(r[h-1]);)h--;for(;S<r.length&&W(r[S]);)S++;const U=String(f.entity_group??f.entity??"ENTITY"),j=`${h}:${S}:${U}`;if(s.has(j))continue;s.add(j);const q=Number(f.score);n.push({value:r.slice(h,S),type:U,start:h,end:S,score:Number.isFinite(q)?Math.max(0,Math.min(1,q)):1,model:f._model})}n.sort((f,p)=>f.start-p.start||f.end-p.end);const l=[];for(const f of n){const p=l[l.length-1];if(p&&p.type===f.type&&p.end===f.start){p.end=f.end,p.value=r.slice(p.start,p.end),p.score=Math.min(p.score,f.score);continue}l.push({...f})}return m.size||H?Mt(l):l}const K=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function _t(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function P(t){const e=K.indexOf(_t(t.type));return e<0?K.length:e}let D=[];function xt(t){D=Array.isArray(t)?t.slice():[]}function F(t){if(t.model===g)return-1;const e=D.indexOf(t.model);return e<0?D.length:e}function Mt(t){const e=[...t].sort((o,n)=>o.start-n.start||n.end-o.end),r=[];for(const o of e){const n=r[r.length-1];if(n&&o.start<n.end){const s=i=>i.end-i.start;(P(o)<P(n)||P(o)===P(n)&&(s(o)>s(n)||s(o)===s(n)&&(F(o)<F(n)||F(o)===F(n)&&o.score>n.score)))&&(r[r.length-1]=o);continue}r.push(o)}return r}function Qt(){const t=y?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const o=String(r).replace(/^[BIES]-/,"");o&&o!=="O"&&e.add(o)}return[...e]}function Kt(){const t=Number(y?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function bt(){return[...m].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function Lt(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===g)return!1;if(m.get(t)?.pipe)return!0;m.set(t,{pipe:null,state:R(t)?"loading":"downloading",error:null});try{const{pipe:n}=await I(t,{log:e,allowDownload:r});return m.set(t,{pipe:n,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(n){return m.set(t,{pipe:null,state:"error",error:n.message}),e(`[ner] companion ${t} failed to load (${n.message}) — the union runs without it`),!1}}async function Vt(t){const e=m.get(t);if(!e)return!1;m.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function V(){const t=y?[{model:g,pipe:y}]:[];for(const[e,r]of m)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const St=160,X=256;function Ot(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),n=Math.min(X,Number.isFinite(r)&&r>0?r:X)-8,s=a=>{try{return e(a).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=n)return[t];const c=[];let i=0,u=Math.max(64,Math.floor(n*3));for(;i<t.length;){let a=Math.min(t.length,i+u);if(a<t.length){const x=t.lastIndexOf(" ",a);x>i+u/2&&(a=x)}let l=t.slice(i,a);for(;s(l)>n&&l.length>32;){u=Math.max(32,Math.floor(l.length/2)),a=i+u;const x=t.lastIndexOf(" ",a);x>i+u/2&&(a=x),l=t.slice(i,a)}if(c.push(l),a>=t.length)break;const f=Math.max(i+1,a-St),p=t.indexOf(" ",f);i=p>0&&p<a?p+1:a}return c}const Tt=200,w=[];function $t(t,e,r){w.push({ms:t,chars:e,spans:r}),w.length>Tt&&w.shift()}function kt(){if(!w.length)return{calls:0};const t=w.map(n=>n.ms).sort((n,s)=>n-s),e=n=>t[Math.min(t.length-1,Math.floor(n*t.length))],r=w.reduce((n,s)=>n+s.chars,0),o=w.reduce((n,s)=>n+s.ms,0);return{calls:w.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(w[w.length-1].ms),charsPerSec:o>0?Math.round(r/(o/1e3)):null}}function At(t,e){if(!e||t.includes(e))return e;const r=t.toLowerCase().indexOf(e.toLowerCase());return r<0?e:t.slice(r,r+e.length)}function vt(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const o=c=>!!c&&/[\p{L}\p{N}'’-]/u.test(c);let n=r,s=r+e.length;for(;n>0&&o(t[n-1]);)n--;for(;s<t.length&&o(t[s]);)s++;return t.slice(n,s)}async function Xt(t,e={}){let r="";try{r=JSON.parse(e.body||"{}").text||""}catch{}const o=await yt(r,{signal:e.signal});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function Zt(){return b}async function Z(){if(A)return A;const t=N();try{rt(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}let r;try{r=await import("@huggingface/transformers")}catch(p){throw e?p:new Error(pt(p))}const{env:o,pipeline:n,Tensor:s,AutoModel:c,AutoProcessor:i,AutoTokenizer:u,AutoModelForSequenceClassification:a,LogLevel:l}=r;if(o.cacheDir=t,e&&l)try{o.logLevel=l.ERROR}catch{}o.localModelPath=t,e||(o.useCustomCache=!0,o.customCache=dt(t,{remoteHost:()=>o.remoteHost}));try{o.remoteHost=ht}catch{}try{o.backends.onnx.wasm.numThreads=1}catch{}if(e)try{o.backends.onnx.wasm.proxy=!1,o.backends.onnx.wasm.wasmPaths=e}catch{}return A={env:o,pipeline:(p,x,h={})=>n(p,x,h.progress_callback&&o.allowRemoteModels===!1?{...h,progress_callback:void 0}:h),Tensor:s,AutoModel:c,AutoProcessor:i,AutoTokenizer:u,AutoModelForSequenceClassification:a},A}async function I(t,{log:e=()=>{},allowDownload:r=!0,onProgress:o=()=>{}}={}){const n=await Z(),s=R(t);if(n.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const c=n.env.remoteHost,i=!st(t);if(!s&&i)try{n.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${i?", from Hugging Face":""})…`);try{const u=l=>{l&&(l.status==="progress"||l.status==="download"||l.status==="initiate"?o(l):l.status==="done"&&l.file&&e(`[ner] fetched ${l.file}`))};let a;try{a=await n.pipeline("token-classification",t,{dtype:"q8",progress_callback:u})}catch(l){if(s||i||!r)throw l;e(`[ner] mirror fetch failed (${String(l.message).slice(0,80)}) — retrying from Hugging Face…`),n.env.remoteHost="https://huggingface.co/",n.env.allowRemoteModels=!0,a=await n.pipeline("token-classification",t,{dtype:"q8",progress_callback:u})}if(!s)try{ut(t,{modelsDir:N(),log:e})}catch(l){try{await a.dispose?.()}catch{}throw l}return{pipe:a,haveLocal:s}}finally{try{n.env.remoteHost=c}catch{}}}async function tt(t,{log:e=()=>{},allowDownload:r=!0}={}){const o=y,n=g;try{await Z()}catch(c){return d="error",M=`engine load failed: ${c.message}`,e(`[ner] transformers.js not available (${c.message}) — deterministic-only`),!1}const s=R(t);if(!s&&!r)return d="error",M="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;d=s?"loading":"downloading",s||(b={model:t,file:null,pct:0});try{const{pipe:c}=await I(t,{log:e,allowDownload:r,onProgress:i=>{b={model:t,file:i.file||b?.file||null,pct:typeof i.progress=="number"?Math.round(i.progress):b?.pct??0}}});if(y=c,g=t,d="ready",M=null,b=null,T&&(T={...T,model:t}),o&&o!==c)try{await o.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),k()||_?.arm(),!0}catch(c){return M=c.message,b=null,o?(y=o,g=n,d="ready"):d="error",e(`[ner] model load failed (${c.message})${o?" — keeping previous model":" — deterministic-only"}`),!1}}function Et(t={}){if(L)return L;const e=typeof t.onLog=="function"?t.onLog:()=>{};T=t,g=t.model||J,d="loading";const r=t.allowDownload!==!1;return _=G({warmMs:t.warmMs,busy:k,log:e,unload:()=>et({log:e})}),L=tt(g,{log:e,allowDownload:r}).then(async o=>{const n=Array.isArray(t.union)?t.union:[];xt(n);for(const s of n)await Lt(s,{log:e,allowDownload:r});return $()&&!k()&&_?.arm(),o}),L}function k(){if(C>0||d==="loading"||d==="downloading")return!0;for(const t of m.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function et({log:t=()=>{}}={}){if(k())return!1;_?.disarm();const e=V().map(r=>r.pipe);y=null,L=null,b=null,M=null,m.clear(),d=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((_?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function It(){try{d==="idle"&&(v||T)?await(v?v():Et(T)):L&&await L}catch{}return $()}async function te(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},o=e.allowDownload!==!1;if(!t)return!1;if(t===g&&$())return!0;const n=m.get(t);if(n?.pipe){const s=y;if(y=n.pipe,g=t,d="ready",M=null,m.delete(t),s)try{await s.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),!0}return tt(t,{log:r,allowDownload:o})}function ee(){d="off",g=null,y=null,M=null,L=null,A=null,b=null,w.length=0,m.clear(),H=!0,D=[],_?.disarm(),_=null,T=null,C=0,v=null}function ne(t,e){m.set(t,{pipe:e,state:"ready",error:null})}function re(t,{model:e="test/model",warmMs:r=null,reload:o=null}={}){y=t,g=e,d="ready",M=null,w.length=0,o&&(v=o),r!==null&&(_=G({warmMs:r,busy:k,unload:()=>et()}),t&&_.arm())}export{ee as _reset,ne as _setCompanionForTest,re as _setForTest,Lt as addCompanion,bt as companions,yt as detect,Gt as detectSpans,It as ensure,Z as ensureLib,Xt as fetchAdapter,Bt as health,Et as init,$ as isReady,Qt as labels,Kt as maxTokens,R as modelOnDisk,N as modelRoot,zt as modelsOnDisk,Zt as progress,Vt as removeCompanion,mt as resolveModelHost,Jt as setCaseRecovery,te as setModel,xt as setUnionOrder,Yt as state,kt as stats,Mt as unionSpans,et as unload,Ot as windowsFor};
|
|
1
|
+
import lt from"node:os";import{join as O}from"node:path";import{existsSync as G,mkdirSync as ct,readdirSync as Q,readFileSync as ut}from"node:fs";import{DEFAULT_MODEL as K,isMirroredModel as ft}from"./models.js";import{isLoopbackHost as pt,isPrivateHost as dt,isMetadataHost as ht}from"@chatpanel/pii";import{recaseForDetection as mt}from"@chatpanel/pii/pii-detect.js";import{recasedSpanOk as gt}from"@chatpanel/pii/recased-spans.js";import{verifyModelWeights as yt}from"./model-integrity.js";import{runtimeName as wt}from"./model-runtime.js";import{nativeOrtFailure as _t}from"./ort.js";import{makeWarmTimer as V}from"./warm-timer.js";import{makeModelFileCache as xt}from"./model-file-cache.js";const N="https://dl.chatpanel.net/models/";function Mt(t=process.env){const e=t.CHATPANEL_MODEL_BASE_URL?"CHATPANEL_MODEL_BASE_URL":"registries.models",r=t.CHATPANEL_MODEL_BASE_URL||t.CHATPANEL_REGISTRY_MODELS;if(!r)return N;const n=u=>(console.warn(`[models] ignoring ${e} (${r}): ${u} — using ${N}`),N);let o;try{o=new URL(r)}catch{return n("not a valid URL")}if(o.protocol!=="http:"&&o.protocol!=="https:")return n(`scheme ${o.protocol} not allowed`);if(ht(o.hostname))return n("points at cloud metadata");const s=pt(o.hostname)||dt(o.hostname);return o.protocol==="http:"&&!s?n("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${o.origin} (${e}), not ${N}`),r.replace(/\/*$/,"/"))}const bt=Mt();let d="off",g=null,y=null,b=null,S=null,E=null,L=null,h=null,_=null,P=0,C=null;const m=new Map;function R(){return process.env.CHATPANEL_MODELS_DIR||O(lt.homedir(),".chatpanel","models")}function H(t=g||K){const e=O(R(),...t.split("/"));return G(O(e,"onnx","model_quantized.onnx"))||G(O(e,"onnx","model.onnx"))}function Xt(){const t=R(),e=[];try{for(const r of Q(t,{withFileTypes:!0}))if(r.isDirectory())for(const n of Q(O(t,r.name),{withFileTypes:!0})){if(!n.isDirectory())continue;const o=`${r.name}/${n.name}`;H(o)&&Lt(O(t,r.name,n.name))&&e.push(o)}}catch{}return e}function Lt(t){try{return(JSON.parse(ut(O(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function Zt(){return d}function k(){return d==="ready"&&!!y}function It(){return{configured:d!=="off",ok:k(),state:d,model:g,error:b,runtime:wt(),dtype:y?"q8":null,stats:Pt(),companions:At(),warmMs:_?.warmMs??null}}async function St(t,{signal:e,strict:r=!1}={}){if(!k())return[];if(e?.aborted)return[];const n=String(t||""),o=await X(n,e);if(!o)return[];const s=[];for(const f of o||[]){if(Z(f,r))continue;let i=String(f.word??"");const a=f.entity_group??f.entity??"ENTITY";if(i.startsWith("##")&&s.length&&s[s.length-1].type===a){s[s.length-1].value+=i.slice(2);continue}i=i.replace(/##/g,"").trim(),i&&s.push({value:i,type:a})}const u=new Set,c=[];for(const f of s){const i=Ht(n,Rt(n,f.value.trim()));if(i.length<=1)continue;const a=`${f.type}:${i.toLowerCase()}`;u.has(a)||(u.add(a),c.push({value:i,type:f.type}))}return c}async function X(t,e){P++;try{return await Tt(t,e)}finally{P--,v()||_?.arm()}}async function Tt(t,e){const r=performance.now(),n=[],o=[{text:t,key:"orig"}];if(D){const s=mt(t);s.changed&&o.push({text:s.text,key:"recased"})}for(const{model:s,pipe:u}of et())for(const c of o){let f=0;for(const i of Et(c.text,u.tokenizer)){if(e?.aborted)return null;const a=c.text.indexOf(i,f),x=await u(i,{aggregation_strategy:"simple"});for(const l of x||[])n.push({...l,_win:a<0?f:a,_winText:i,_model:s,_pass:c.key,_passText:c.text});a>=0&&(f=Math.max(f,a+1))}}return Nt(performance.now()-r,t.length,n.length),n}let D=!0;function te(t){D=t!==!1}const Z=(t,e)=>!e&&t._pass==="recased"&&!gt(String(t.word??"").replace(/##/g,""),t.entity_group??t.entity);async function ee(t,{signal:e,strict:r=!1}={}){if(!k())return[];const n=String(t||""),o=await X(n,e);if(!o)return[];const s=[],u=new Set;let c=-1,f=-1,i=null,a=null;for(const l of o){if(Z(l,r))continue;const p=String(l.word??"").replace(/##/g,"").trim();if(!p)continue;(l._win!==f||l._model!==i||l._pass!==a)&&(f=l._win,i=l._model,a=l._pass,c=l._win);const $=l._passText||n;let M=$.indexOf(p,c);if(M<0&&(M=$.indexOf(p,l._win)),M<0)continue;let T=M+p.length;c=T;const q=J=>!!J&&/[\p{L}\p{N}'’-]/u.test(J);for(;M>0&&q(n[M-1]);)M--;for(;T<n.length&&q(n[T]);)T++;const z=String(l.entity_group??l.entity??"ENTITY"),Y=`${M}:${T}:${z}`;if(u.has(Y))continue;u.add(Y);const B=Number(l.score);s.push({value:n.slice(M,T),type:z,start:M,end:T,score:Number.isFinite(B)?Math.max(0,Math.min(1,B)):1,model:l._model})}s.sort((l,p)=>l.start-p.start||l.end-p.end);const x=[];for(const l of s){const p=x[x.length-1];if(p&&p.type===l.type&&p.end===l.start){p.end=l.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,l.score);continue}x.push({...l})}return m.size||D?$t(x):x}const I=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function Ot(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function F(t){const e=I.indexOf(Ot(t.type));return e<0?I.length:e}let A=[];function kt(t){A=Array.isArray(t)?t.slice():[],h&&(h={...h,union:A.slice()})}function W(t){if(t.model===g)return-1;const e=A.indexOf(t.model);return e<0?A.length:e}function $t(t){const e=[...t].sort((n,o)=>n.start-o.start||o.end-n.end),r=[];for(const n of e){const o=r[r.length-1];if(o&&n.start<o.end){const s=c=>c.end-c.start;(F(n)<F(o)||F(n)===F(o)&&(s(n)>s(o)||s(n)===s(o)&&(W(n)<W(o)||W(n)===W(o)&&n.score>o.score)))&&(r[r.length-1]=n);continue}r.push(n)}return r}function ne(){const t=y?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const n=String(r).replace(/^[BIES]-/,"");n&&n!=="O"&&e.add(n)}return[...e]}function oe(){const t=Number(y?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function At(){return[...m].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function tt(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===g)return!1;if(m.get(t)?.pipe)return!0;m.set(t,{pipe:null,state:H(t)?"loading":"downloading",error:null});try{const{pipe:o}=await rt(t,{log:e,allowDownload:r});return m.set(t,{pipe:o,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(o){return m.set(t,{pipe:null,state:"error",error:o.message}),e(`[ner] companion ${t} failed to load (${o.message}) — the union runs without it`),!1}}async function re(t){const e=m.get(t);if(!e)return!1;m.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function et(){const t=y?[{model:g,pipe:y}]:[];for(const[e,r]of m)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const vt=160,nt=256;function Et(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),o=Math.min(nt,Number.isFinite(r)&&r>0?r:nt)-8,s=i=>{try{return e(i).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=o)return[t];const u=[];let c=0,f=Math.max(64,Math.floor(o*3));for(;c<t.length;){let i=Math.min(t.length,c+f);if(i<t.length){const p=t.lastIndexOf(" ",i);p>c+f/2&&(i=p)}let a=t.slice(c,i);for(;s(a)>o&&a.length>32;){f=Math.max(32,Math.floor(a.length/2)),i=c+f;const p=t.lastIndexOf(" ",i);p>c+f/2&&(i=p),a=t.slice(c,i)}if(u.push(a),i>=t.length)break;const x=Math.max(c+1,i-vt),l=t.indexOf(" ",x);c=l>0&&l<i?l+1:i}return u}const Ct=200,w=[];function Nt(t,e,r){w.push({ms:t,chars:e,spans:r}),w.length>Ct&&w.shift()}function Pt(){if(!w.length)return{calls:0};const t=w.map(o=>o.ms).sort((o,s)=>o-s),e=o=>t[Math.min(t.length-1,Math.floor(o*t.length))],r=w.reduce((o,s)=>o+s.chars,0),n=w.reduce((o,s)=>o+s.ms,0);return{calls:w.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(w[w.length-1].ms),charsPerSec:n>0?Math.round(r/(n/1e3)):null}}function Rt(t,e){if(!e||t.includes(e))return e;const r=t.toLowerCase().indexOf(e.toLowerCase());return r<0?e:t.slice(r,r+e.length)}function Ht(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const n=u=>!!u&&/[\p{L}\p{N}'’-]/u.test(u);let o=r,s=r+e.length;for(;o>0&&n(t[o-1]);)o--;for(;s<t.length&&n(t[s]);)s++;return t.slice(o,s)}async function se(t,e={}){let r="",n=!1;try{const s=JSON.parse(e.body||"{}");r=s.text||"",n=s.strict===!0}catch{}const o=await St(r,{signal:e.signal,strict:n});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function ie(){return L}async function ot(){if(E)return E;const t=R();try{ct(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}let r;try{r=await import("@huggingface/transformers")}catch(l){throw e?l:new Error(_t(l))}const{env:n,pipeline:o,Tensor:s,AutoModel:u,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:i,LogLevel:a}=r;if(n.cacheDir=t,e&&a)try{n.logLevel=a.ERROR}catch{}n.localModelPath=t,e||(n.useCustomCache=!0,n.customCache=xt(t,{remoteHost:()=>n.remoteHost}));try{n.remoteHost=bt}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(e)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=e}catch{}return E={env:n,pipeline:(l,p,$={})=>o(l,p,$.progress_callback&&n.allowRemoteModels===!1?{...$,progress_callback:void 0}:$),Tensor:s,AutoModel:u,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:i},E}async function rt(t,{log:e=()=>{},allowDownload:r=!0,onProgress:n=()=>{}}={}){const o=await ot(),s=H(t);if(o.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const u=o.env.remoteHost,c=!ft(t);if(!s&&c)try{o.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${c?", from Hugging Face":""})…`);try{const f=a=>{a&&(a.status==="progress"||a.status==="download"||a.status==="initiate"?n(a):a.status==="done"&&a.file&&e(`[ner] fetched ${a.file}`))};let i;try{i=await o.pipeline("token-classification",t,{dtype:"q8",progress_callback:f})}catch(a){if(s||c||!r)throw a;e(`[ner] mirror fetch failed (${String(a.message).slice(0,80)}) — retrying from Hugging Face…`),o.env.remoteHost="https://huggingface.co/",o.env.allowRemoteModels=!0,i=await o.pipeline("token-classification",t,{dtype:"q8",progress_callback:f})}if(!s)try{yt(t,{modelsDir:R(),log:e})}catch(a){try{await i.dispose?.()}catch{}throw a}return{pipe:i,haveLocal:s}}finally{try{o.env.remoteHost=u}catch{}}}async function st(t,{log:e=()=>{},allowDownload:r=!0}={}){const n=y,o=g;try{await ot()}catch(u){return d="error",b=`engine load failed: ${u.message}`,e(`[ner] transformers.js not available (${u.message}) — deterministic-only`),!1}const s=H(t);if(!s&&!r)return d="error",b="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;d=s?"loading":"downloading",s||(L={model:t,file:null,pct:0});try{const{pipe:u}=await rt(t,{log:e,allowDownload:r,onProgress:c=>{L={model:t,file:c.file||L?.file||null,pct:typeof c.progress=="number"?Math.round(c.progress):L?.pct??0}}});if(y=u,g=t,d="ready",b=null,L=null,h&&(h={...h,model:t}),n&&n!==u)try{await n.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),v()||_?.arm(),!0}catch(u){return b=u.message,L=null,n?(y=n,g=o,d="ready"):d="error",e(`[ner] model load failed (${u.message})${n?" — keeping previous model":" — deterministic-only"}`),!1}}function Dt(t={}){if(S)return S;const e=typeof t.onLog=="function"?t.onLog:()=>{};h=t,g=t.model||K,d="loading";const r=t.allowDownload!==!1;return _=V({warmMs:t.warmMs,busy:v,log:e,unload:()=>it({log:e})}),S=st(g,{log:e,allowDownload:r}).then(async n=>{const o=Array.isArray(t.union)?t.union:[];kt(o);for(const s of o)await tt(s,{log:e,allowDownload:r});return k()&&!v()&&_?.arm(),n}),S}function v(){if(P>0||d==="loading"||d==="downloading")return!0;for(const t of m.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function it({log:t=()=>{}}={}){if(v())return!1;_?.disarm();const e=et().map(r=>r.pipe);y=null,S=null,L=null,b=null,m.clear(),d=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((_?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function Ft(){try{d==="idle"&&(C||h)?await(C?C():Dt(h)):S&&await S,k()&&await at()}catch{}return k()}let U=null;function at(){const t=A.filter(e=>e&&e!==g&&!m.has(e));return t.length?(U||=(async()=>{const e=typeof h?.onLog=="function"?h.onLog:()=>{};for(const r of t)m.has(r)||(j?await j(r):await tt(r,{log:e,allowDownload:h?.allowDownload!==!1}))})().catch(()=>{}).finally(()=>{U=null}),U):Promise.resolve()}let j=null;function ae(t){j=t}async function le(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},n=e.allowDownload!==!1;if(!t)return!1;if(t===g&&k())return!0;if(t===g&&d==="idle")return Ft();const o=m.get(t);if(o?.pipe){const u=y;if(y=o.pipe,g=t,d="ready",b=null,m.delete(t),u)try{await u.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),h&&(h={...h,model:t}),!0}const s=await st(t,{log:r,allowDownload:n});return s&&(h&&(h={...h,model:t}),await at()),s}function ce(){d="off",g=null,y=null,b=null,S=null,E=null,L=null,w.length=0,m.clear(),D=!0,A=[],_?.disarm(),_=null,h=null,P=0,C=null,j=null,U=null}function ue(t,e){m.set(t,{pipe:e,state:"ready",error:null})}function fe(t,{model:e="test/model",warmMs:r=null,reload:n=null}={}){y=t,g=e,d="ready",b=null,w.length=0,n&&(C=n),r!==null&&(_=V({warmMs:r,busy:v,unload:()=>it()}),t&&_.arm())}export{ce as _reset,ue as _setCompanionForTest,ae as _setCompanionLoaderForTest,fe as _setForTest,tt as addCompanion,At as companions,St as detect,ee as detectSpans,Ft as ensure,ot as ensureLib,se as fetchAdapter,It as health,Dt as init,k as isReady,ne as labels,oe as maxTokens,H as modelOnDisk,R as modelRoot,Xt as modelsOnDisk,ie as progress,re as removeCompanion,Mt as resolveModelHost,te as setCaseRecovery,le as setModel,kt as setUnionOrder,Zt as state,Pt as stats,$t as unionSpans,it as unload,Et as windowsFor};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{spawn as g}from"node:child_process";const p=9e4,h=6e5,b=4,f=60,A={chrome:"Google Chrome",edge:"Microsoft Edge",firefox:"Firefox",brave:"Brave",opera:"Opera"},y=c=>A[String(c||"").toLowerCase()]||"a browser";function v({confirm:c,now:s=()=>Date.now(),random:a=Math.random,newId:r,ttlMs:n=p}={}){let e=null,t=[];const m=()=>{e&&e.status==="waiting"&&s()>e.expiresAt&&(e.status="expired")};function l({browser:u="",who:w=""}={}){if(m(),e?.status==="waiting")return{ok:!1,reason:"busy"};if(t=t.filter(d=>s()-d<h),t.length>=b)return{ok:!1,reason:"too_many"};t.push(s());const o={id:r(),who:String(w),number:String(Math.floor(a()*9e3)+1e3),expiresAt:s()+n,status:"waiting"};return e=o,Promise.resolve().then(()=>c({browser:y(u),number:o.number})).then(d=>{o.status==="waiting"&&(o.status=d==="allow"?"allowed":d==="unavailable"?"unavailable":"denied")}).catch(()=>{o.status==="waiting"&&(o.status="unavailable")}),{ok:!0,id:o.id,number:o.number,expiresAt:o.expiresAt}}function i(u,{who:w=""}={}){if(m(),!e||!u||String(u)!==e.id||String(w)!==e.who)return{status:"expired"};const{status:o}=e;return o!=="waiting"&&(e=null),{status:o}}return{ask:l,result:i}}function $({browser:c,number:s},{platform:a=process.platform,run:r=S,env:n=process.env,seconds:e=f}={}){if(String(n.CHATPANEL_PAIR_PROMPT||"").toLowerCase()==="off")return Promise.resolve("unavailable");const t="ChatPanel",m=`${c} on this computer is asking to connect to ChatPanel.
|
|
2
|
+
|
|
3
|
+
Number: ${s}
|
|
4
|
+
|
|
5
|
+
Allow only if you just pressed “Pair this browser” in Chap's settings and it shows the same number.`;if(a==="darwin"){const l=`on run argv
|
|
6
|
+
set r to display dialog (item 1 of argv) with title (item 2 of argv) buttons {"Don't Allow", "Allow"} default button "Don't Allow" cancel button "Don't Allow" with icon caution giving up after ${e}
|
|
7
|
+
if gave up of r then return "deny"
|
|
8
|
+
if button returned of r is "Allow" then return "allow"
|
|
9
|
+
return "deny"
|
|
10
|
+
end run`;return r("osascript",["-e",l,m,t]).then(i=>i.missing?"unavailable":/^allow\s*$/.test(i.out)?"allow":"deny")}if(a==="win32"){const l='$f = New-Object System.Windows.Forms.Form -Property @{ TopMost = $true }; $r = [System.Windows.Forms.MessageBox]::Show($f, $args[0], $args[1], "YesNo", "Warning", "Button2"); if ($r -eq "Yes") { "allow" } else { "deny" }',i=`${m}
|
|
11
|
+
|
|
12
|
+
Yes = Allow No = Don't allow`;return r("powershell.exe",["-NoProfile","-NonInteractive","-STA","-Command",`Add-Type -AssemblyName System.Windows.Forms; & { ${l} } @args`,i,t]).then(u=>u.missing||u.code!==0?"unavailable":/^allow\s*$/.test(u.out)?"allow":"deny")}return!n.DISPLAY&&!n.WAYLAND_DISPLAY?Promise.resolve("unavailable"):r("zenity",["--question",`--title=${t}`,`--text=${m}`,"--ok-label=Allow","--cancel-label=Don't Allow","--default-cancel",`--timeout=${e}`]).then(l=>l.missing?r("kdialog",["--title",t,"--warningyesno",m]).then(i=>i.missing?"unavailable":i.code===0?"allow":"deny"):l.code===0?"allow":"deny")}function S(c,s){return new Promise(a=>{let r="",n;try{n=g(c,s,{stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{a({code:-1,out:"",missing:!0});return}const e=setTimeout(()=>{try{n.kill()}catch{}},(f+15)*1e3);e.unref?.(),n.stdout.on("data",t=>{r+=t}),n.on("error",t=>{clearTimeout(e),a({code:-1,out:"",missing:t?.code==="ENOENT"})}),n.on("close",t=>{clearTimeout(e),a({code:t,out:r.trim(),missing:!1})})})}export{b as ASK_MAX_IN_WINDOW,p as ASK_TTL_MS,h as ASK_WINDOW_MS,y as browserName,v as createPairAsk,$ as nativeConfirm};
|
package/src/recruiting.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{summarize as
|
|
1
|
+
import{summarize as v}from"./scorecard.js";import{applications as k,evaluatorPrompt as M,parseEvaluation as b,decide as P,recruitEvents as S,engineRows as A,MIN_FIT as E}from"./recruit.js";import{aggregateModelsAsync as F,listDestinations as D}from"./router.js";import{reachOfGatewayModel as N}from"@chatpanel/events/model-candidates.js";const O=new Set(["device","trusted","any"]);async function R(o,n,{jobKind:s=null,minCalls:r,timeoutMs:i=2500,engineAt:p=null}={}){const d=await F(o,{timeoutMs:i,engineAt:p}).catch(()=>({data:[]})),u=new Map(D(o).map(e=>[e.id,e])),t=(d.data||[]).map(e=>{const f=e.owned_by==="chatpanel-bridge",c=u.get(e.provider);return{id:e.id,model:e.id,kind:f?"bridge":"api",label:e.model?`${e.provider} · ${e.model}`:e.id,reach:N(e,c),capabilities:["tools"],available:e.configured===!1?!1:e.available!==!1}}),l=Object.fromEntries((n?.list?.({minCalls:r})||[]).map(e=>[e.key,e]));return A(t,{cards:l,minCalls:r,jobKind:s})}function q(o){const n=o?.get?.("agents")?.agents?.value;return(Array.isArray(n)?n:[]).filter(s=>s&&s.id&&s.enabled!==!1)}function z(o,n){const s={};for(const r of n){const i=o?.chains?.get?.(r.id);i?.length&&(s[r.id]=v(i))}return s}async function G(o,{cfg:n,prefsStore:s,scorecards:r,engines:i,reach:p="any",chatModel:d=null,now:u=Date.now(),engineAt:t=null}={}){const l=q(s),e=await R(n,i,{engineAt:t}),f=z(r,l),c=O.has(p)?p:"any",y=k(o,l,{summaries:f,rows:e,reach:c,chatModel:d,now:u});return{applications:y,prompt:M(o,y,l,{rows:e}),rows:e.map(a=>({key:a.key,label:a.label,reach:a.reach,quality:a.quality,costPer1k:a.costPer1k,latencyMs:a.latencyMs,available:a.available,observed:a.observed})),poolSize:l.length}}async function J(o,{cfg:n,prefsStore:s,scorecards:r,engines:i,record:p=null,reach:d="any",chatModel:u=null,evaluation:t=null,text:l=null,by:e="evaluator",minFit:f=E,now:c=Date.now(),engineAt:y=null}={}){const{applications:a,prompt:w}=await G(o,{cfg:n,prefsStore:s,scorecards:r,engines:i,reach:d,chatModel:u,now:c,engineAt:y});let m=null;l!=null?m=b(String(l),a):t&&typeof t=="object"&&(m=b(JSON.stringify({pick:t.pick,why:t.why,confidence:t.confidence,proposalName:t.proposal?.name,proposalPurpose:t.proposal?.purpose,proposalSkills:t.proposal?.skills,proposalGrants:t.proposal?.grants}),a));const g=P(o,a,{evaluation:m,minFit:f}),h=S(o,a,g,{by:g.by==="evaluator"?e:"fit",at:c,record:p});return{applications:a,evaluation:m,decision:g,events:h,prompt:w}}export{G as applicationsFor,q as poolFrom,J as recruitPass,R as rosterRows,z as summariesFrom};
|
package/src/redact.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createVault as
|
|
1
|
+
import{createVault as v,redactText as T,detectEntities as w,gatedDictionary as z,sanitizeUnicode as A,strictnessOf as b}from"@chatpanel/pii";import{ENTITIES_SCHEMA as h,entitiesFormat as N}from"./extraction.js";import{describeSchema as j,coerce as D}from"./structured.js";import*as F from"./ner-engine.js";async function U(r,o,{signal:g,isPro:x=!0,onEgress:M=null,fetchImpl:k=null,sanitizeOnly:E=!1,nerEngine:c=F}={}){const i=v();let f=0;for(const t of r){const e=t.get();if(typeof e!="string"||!e)continue;const{clean:n,removed:y}=A(e);y&&(t.set(n),f+=y)}const m=r.map(t=>t.get()).filter(t=>typeof t=="string"&&t);if(m.length===0)return{vault:i,count:0,sanitized:f};if(E)return{vault:i,count:0,sanitized:f};const a=o.tier==="full"?"full":"basic",I=z(o,x),s=o.detection,l=!!(s&&s.backend&&s.backend!=="off");a==="full"&&!l&&typeof c.ensure=="function"&&await c.ensure();const u=!l&&c.isReady();let p=[];if(a==="full"&&(l||u)){const t=u?{backend:"endpoint",url:"inproc:ner",transport:"in-process",timeoutMs:3e4,maxChars:8e3,types:s?.types,strictness:b(o)}:{...s,timeoutMs:Math.max(Number(s.timeoutMs)||0,3e4),strictness:b(o)},e=u?c.fetchAdapter:k||void 0;try{p=await w(m.join(`
|
|
2
2
|
|
|
3
|
-
`),{detection:t},{signal:g,fetchImpl:e,onEgress:
|
|
3
|
+
`),{detection:t},{signal:g,fetchImpl:e,onEgress:u?null:M,structured:{block:j(h),format:n=>N(n),parse:n=>D(n,h)?.value??null}})}catch{p=[]}}const S={tier:a,entities:p,dictionary:I};let d=0;for(const t of r){const e=t.get();if(typeof e!="string"||!e)continue;const n=T(e,i,S);n!==e&&d++,t.set(n)}return{vault:i,count:d,sanitized:f}}function V(r,o){return{get:r,set:o}}export{U as redactSegments,V as segment};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SEARCH_ENGINES as i}from"../web-search.js";import{apiEnginesFrom as n,patchApiEntries as s,viewApiEntries as a}from"../search-api.js";function c(r){return[...i.filter(t=>t.kind!=="gateway"),...n(r?.search?.apis)]}function E(r=[],t=[]){try{return s(r,t)}catch(e){throw Object.assign(new Error(e.message),{status:400})}}function h(r){return a(r?.search?.apis)}export{E as patchApis,c as searchEngines,h as viewApis};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{secureFetch as
|
|
1
|
+
import{secureFetch as A}from"../secure-fetch.js";import{SEARCH_ENGINES as g,buildSearchUrl as k,pickResults as b}from"../web-search.js";import{extractAnchors as E}from"../serp-anchors.js";import{createEnginePacer as S,searchPolitely as w,retryAfterMs as p}from"../engine-pacer.js";import{buildApiRequest as R,readApiResponse as x}from"../search-api.js";import{VERSION as _}from"../version.js";const j="serp",m=Object.freeze({allowLoopback:!1,allowPrivate:!1}),M=3e6,f=5e3,d=e=>e?AbortSignal.any([e,AbortSignal.timeout(f)]):AbortSignal.timeout(f),P=Object.freeze({Accept:"text/html,application/xhtml+xml","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36","Accept-Language":"en-US,en;q=0.9"});async function I(e,a,{fetchFn:n,signal:i,perEngine:o}){let r;try{r=k(e.url,a)}catch{return{results:[]}}try{const t=await n(r,{policy:m,headers:P,signal:d(i)});if(!t.ok)return{results:[],status:t.status,retryAfterMs:p(t.headers.get("retry-after"))};const l=t.headers.get("content-type")||"";if(l&&!/html|text|xml/i.test(l))return{results:[],status:t.status};const c=(await t.text()).slice(0,M);return{status:t.status,results:b(E(c),{engineHost:new URL(r).hostname,limit:o,fallback:!0})}}catch(t){return h(t,i)}}function h(e,a){return a?.aborted?{results:[]}:/abort|timeout/i.test(`${e?.name} ${e?.message}`)?{results:[],timedOut:!0}:{results:[],network:!0}}async function L(e,a,{fetchFn:n,signal:i,perEngine:o}){let r;try{r=R(e.api,{q:a.q,site:a.site,limit:o,vars:e.vars||{}})}catch{return{results:[]}}try{const t=await n(r.url,{method:r.method,headers:{"User-Agent":`ChatPanel-Gateway/${_} (https://chatpanel.net)`,...r.headers},body:r.body??void 0,policy:m,maxRedirects:0,signal:d(i)});return t.ok?{status:t.status,results:x(e.api,await t.json(),{limit:o})}:{results:[],status:t.status,retryAfterMs:p(t.headers.get("retry-after"))}}catch(t){return h(t,i)}}const O=S();async function z(e,{fetchFn:a=A,signal:n=void 0,engines:i=g,pacer:o=O}={}){const r=e.site?`site:${e.site} ${e.q}`:e.q,t=e.limit||8,l=(typeof i=="function"?i():i).filter(s=>s.enabled!==!1&&s.kind!=="gateway"),u=await w(l,s=>s.kind==="api"?L(s,e,{fetchFn:a,signal:n,perEngine:t}):I(s,r,{fetchFn:a,signal:n,perEngine:t}),{pacer:o,limit:t,signal:n,query:e.q});return{results:u.results.map((s,y)=>({rank:y+1,url:s.url,title:s.title,snippet:s.snippet||"",engine:s.engine,via:s.via})),engines:u.asked.map(s=>s.id),answers:[],suggestions:[],asked:u.asked,resting:u.resting}}export{f as PER_ENGINE_MS,j as PROVIDER_ID,z as searchSerp};
|
package/src/retrieval/search.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{validateSearchRequest as
|
|
1
|
+
import{validateSearchRequest as N,validateSearchResponse as J,overBudget as V}from"../capability-endpoints.js";import{createReadStats as B}from"./read.js";import{searchSerp as I,PROVIDER_ID as T}from"./search-serp.js";import{searchStatus as Z}from"../search-outcome.js";import{PROVIDER_ID as c}from"./search-searxng.js";const A=Object.freeze({timeoutMs:15e3,readConcurrency:4,readBudgetMs:8e3,aliasRead:5}),z=/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g,h=(a,r,i)=>({status:a,body:{error:{type:r,message:i}}});function G(a){const r=String(a||"").replace(z," ").replace(/\s+/g," ").trim();return{q:r,stripped:r!==String(a||"").trim()}}async function H(a,r,i){const p=new Array(a.length);let w=0;const M=Array.from({length:Math.min(r,a.length)},async()=>{for(;;){const g=w++;if(g>=a.length)return;p[g]=await i(a[g],g)}});return await Promise.all(M),p}function Y({reader:a=null,redact:r=async m=>m,searxng:i=null,defaultProvider:p="auto",fetchFn:w=void 0,engines:M=void 0,pacer:g=void 0,now:d=()=>Date.now(),stats:E={serp:B(),searxng:B()},timeoutMs:_=A.timeoutMs,wakeSearxng:O=null}={}){const m=()=>[T,...i?.url?[c]:[]];async function L(f){if(f.provider)return f.provider;if(p===c||p===T)return p;if(i?.url){const e=await i.health();if(e.state==="ready"||e.state==="unknown")return c}return T}return{providers:m,stats:()=>Object.fromEntries(Object.entries(E).map(([f,e])=>[f,e.stats()])),searxng:i,async search(f){let e;try{e=N(f)}catch(t){return h(400,"invalid_request",t.message)}if(e.provider&&!m().includes(e.provider))return h(404,"provider_not_found",`no search provider ${JSON.stringify(e.provider)} here (have ${m().join(", ")})`);if(e.read&&!a)return h(400,"invalid_request","read: no reader is available here");const S=d();let x=!1;try{const t=await r(e.q),{q:s,stripped:v}=G(t);v&&(x=!0,e.q=s)}catch(t){return h(500,"redaction_failed",t.message)}if(!e.q)return h(400,"unsafe_query","the query was only private values (an email, a card, a key…) and nothing searchable remains");const l=await L(e),D=V(E[l]?.stats(),0,e.budgetMs);if(D)return{status:503,body:{...D,provider:l}};const q=new AbortController,C=setTimeout(()=>q.abort(),Math.min(_,e.budgetMs>0?e.budgetMs:_));let o;try{o=l===c?await i.search(e,{signal:q.signal}):await I(e,{fetchFn:w,signal:q.signal,engines:M,pacer:g})}catch(t){return clearTimeout(C),q.signal.aborted?h(504,"fetch_timeout",`${l} did not answer within the budget`):h(502,"provider_failed",`${l}: ${t.message}`)}clearTimeout(C);let y=l;const P=(t,s)=>t===c?[{id:"searxng",outcome:s?.results?.length?"answered":"empty",found:s?.results?.length||0}]:s?.asked||[],R=[...P(l,o)];let k=o.resting||[];if(!o.results.length&&!e.provider&&m().length>1){const t=l===c?T:c;if(t===c&&typeof O=="function"){const n=d()+Math.min(8e3,e.budgetMs>0?Math.max(0,e.budgetMs-(d()-S)):8e3);try{await Promise.race([O(),new Promise(u=>setTimeout(u,Math.max(0,n-d())))])}catch{}for(;d()<n&&(await i.health({force:!0}).catch(()=>({state:"down"}))).state==="down";)await new Promise(u=>setTimeout(u,400))}const s=new AbortController,v=setTimeout(()=>s.abort(),Math.min(_,e.budgetMs>0?Math.max(1e3,e.budgetMs-(d()-S)):_));try{const n=t===c?await i.search(e,{signal:s.signal}):await I(e,{fetchFn:w,signal:s.signal,engines:M,pacer:g});R.push(...P(t,n)),n?.resting&&(k=n.resting),n?.results?.length&&(o=n,y=t)}catch{R.push({id:t,outcome:"refused",found:0,network:!0})}clearTimeout(v)}const $=Math.round(d()-S);E[y]?.record($,e.q.length);let b=o.results.map(t=>({...t,engine:t.engine||y,via:t.via||(y===c?"searxng":"page")}));if(e.read>0&&b.length){const t=e.budgetMs>0?Math.max(1e3,e.budgetMs-$):A.readBudgetMs,s=b.slice(0,e.read),v=await H(s,A.readConcurrency,async n=>{const u=await a.read({url:n.url,snippet:n.snippet,budgetMs:Math.min(t,A.readBudgetMs)});return u.status===200?u.body:null});b=b.map((n,u)=>u<s.length&&v[u]?{...n,read:v[u]}:n)}const j={results:b,answers:o.answers||[],suggestions:o.suggestions||[],engines:o.engines||[],...o.unresponsive?.length?{unresponsive:o.unresponsive}:{},...x?{redacted:!0,query:e.q}:{},provider:y,ms:Math.round(d()-S),trail:{status:Z({results:b,asked:R,resting:k}),asked:R,resting:k}};try{J(j)}catch(t){return h(500,"bad_shape",t.message)}return{status:200,body:j}}}}function ee(a){return{code:200,status:2e4,data:(a.results||[]).map(r=>({url:r.url,title:r.title,description:r.snippet||"",content:r.read?.markdown||r.read?.text||r.snippet||"",...r.read?.published?{publishedTime:r.read.published}:{},...r.engine?{engine:r.engine}:{},...r.via?{via:r.via}:{}})),...a.trail?{trail:a.trail}:{}}}export{A as SEARCH_DEFAULTS,Y as createSearcher,G as queryWithoutTokens,ee as toJinaSearch};
|