@chatpanel/gateway 0.64.0 → 0.85.2
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/native/darwin-arm64/chatpanel-apple-model +0 -0
- package/package.json +6 -5
- package/src/apple-model.js +1 -0
- 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/engine-tunings.js +1 -1
- package/src/host-memory.js +1 -0
- package/src/inference-engines.js +1 -1
- package/src/link-host.js +1 -1
- 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-models.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 +37 -28
- package/src/service.js +11 -10
- 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/src/ws-accept.js +7 -0
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)}
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.85.2",
|
|
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": {
|
|
@@ -15,16 +15,17 @@
|
|
|
15
15
|
"bin",
|
|
16
16
|
"gateway.config.example.json",
|
|
17
17
|
"LICENSE",
|
|
18
|
-
"README.md"
|
|
18
|
+
"README.md",
|
|
19
|
+
"native/darwin-arm64"
|
|
19
20
|
],
|
|
20
21
|
"engines": {
|
|
21
22
|
"node": ">=22.13"
|
|
22
23
|
},
|
|
23
24
|
"dependencies": {
|
|
24
25
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
25
|
-
"@chatpanel/bridge": "^0.
|
|
26
|
-
"@chatpanel/events": "^0.
|
|
27
|
-
"@chatpanel/pii": "^0.
|
|
26
|
+
"@chatpanel/bridge": "^0.44.0",
|
|
27
|
+
"@chatpanel/events": "^0.353.0",
|
|
28
|
+
"@chatpanel/pii": "^0.14.0",
|
|
28
29
|
"@huggingface/transformers": "^4.2.0",
|
|
29
30
|
"defuddle": "^0.19.4",
|
|
30
31
|
"fflate": "^0.8.3",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readdirSync as s}from"node:fs";import n from"node:path";import{fileURLToPath as l}from"node:url";const c="chatpanel-apple-model",A="apple-on-device",w=25,m="arm64-apple-macos26.0",p=n.dirname(l(import.meta.url));function x(t){const e=Number.parseInt(String(t||""),10);return Number.isFinite(e)?e:0}function P({home:t,execPath:e=process.execPath,moduleDir:o=p}={}){const i=[n.join(o,"..","native","darwin-arm64")];return/^node(\.exe)?$/i.test(n.basename(e||""))||i.push(n.dirname(e)),t&&i.push(n.join(t,".chatpanel","bin")),i}function d(t=p){const e=n.join(t,"..","native","apple-model");try{return s(e).filter(o=>o.endsWith(".swift")).sort().map(o=>n.join(e,o))}catch{return[]}}function a(t,e){return["-O","-target",m,"-o",t,...e]}function S({home:t,sources:e=d()}={}){const o="https://developer.apple.com/documentation/foundationmodels";if(!e.length||!t)return{command:"comes with the gateway from npm and the desktop app on Apple Silicon",steps:[],url:o,note:"Needs macOS 26 on Apple Silicon with Apple Intelligence turned on (System Settings › Apple Intelligence & Siri)."};const i=n.join(t,".chatpanel","bin"),r=n.join(i,c);return{command:`swiftc ${a(r,["native/apple-model/*.swift"]).join(" ")}`,steps:[["mkdir","-p",i],["swiftc",...a(r,e)]],url:o,note:"A source checkout: builds the helper with the Command Line Tools. Needs Apple Intelligence turned on."}}export{c as APPLE_HELPER,w as APPLE_MIN_DARWIN,A as APPLE_MODEL_ID,m as APPLE_SWIFT_TARGET,a as appleBuildArgs,P as appleHelperDirs,S as appleInstallDoor,d as appleSources,x as darwinMajor};
|
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 f,dirname as x}from"node:path";import E from"node:os";import{usage as D}from"./freegate.js";import{applyFusionsPatch as c}from"./fusions.js";import{EMBEDDED_MODELS as S,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||f(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(x(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};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=c(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 ${S[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{isBlockedHost as f}from"@chatpanel/pii";const b=()=>new Date().toISOString();function w(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),r=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[r]||"",scheme:r}}catch{return null}}const p=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:f(t,{allowLoopback:!1,allowPrivate:!1})&&!f(t,{allowLoopback:!0,allowPrivate:!0})};function v({clock:e=b}={}){const t=new Map;return{record(r){const o=w(r);if(!o||!o.host)return;const h=`${o.scheme}://${o.host}:${o.port}`,l=e(),i=t.get(h);if(i){i.count+=1,i.lastAt=l;return}t.set(h,{host:o.host,port:o.port,scheme:o.scheme,local:p(o.host),count:1,firstAt:l,lastAt:l})},snapshot(){return[...t.values()].sort((r,o)=>r.local===o.local?o.count-r.count:r.local?1:-1)},reset(){t.clear()}}}let g=null;function E(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const r=v();let o=t;r.setGate=c=>{o=c},r.blocked=[];const h=c=>{let a=null;try{a=w(c),r.record(c)}catch{}if(!o||!a?.host)return null;let s=!0;try{s=o(`${a.scheme}://${a.host}:${a.port}`,{local:p(a.host)})}catch{s=!0}if(s)return null;const n=`${a.host}:${a.port}`;r.blocked.includes(n)||r.blocked.push(n);const d=new Error(`egress to ${a.host} is blocked by your organisation’s policy`);return d.code="EGRESS_POLICY",d},l=e.fetch;typeof l=="function"&&(e.fetch=function(a,s){const n=h(a);return n?Promise.reject(n):l.call(this,a,s)});const i=e.WebSocket;return typeof i=="function"&&(e.WebSocket=new Proxy(i,{construct(c,a,s){const n=h(a[0]);if(n)throw n;return Reflect.construct(c,a,s)}})),e.__chatpanelEgress=r,e===globalThis&&(g=r),r}function k(){return g||(globalThis.__chatpanelEgress??null)}function u(e){try{return new URL(e).host}catch{return String(e||"")}}function $(e={},t=process.env){const r=[],o=(a,s,{when:n="always",off:d=null,local:y=!1,data:m=""}={})=>{a&&r.push({host:a,purpose:s,when:n,off:d,local:y,data:m})};if(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"}),e.link?.enabled!==!1){let a="link.chatpanel.net";try{e.link?.relayUrl&&(a=new URL(e.link.relayUrl).host)}catch{}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 h=e.search?.searxng?.url||"";if(h){let a=h;try{a=new URL(h).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, 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"}),o("html.duckduckgo.com","web search: the built-in results-page search, fallback engine",{when:"Startpage returned nothing",off:"the same switch as www.startpage.com",data:"the same query"})),e.read?.remote?.url){let a=e.read.remote.url;try{a=new URL(e.read.remote.url).host}catch{}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 l={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,s]of Object.entries(l)){const n=e.capabilities?.[a];if(!n?.url||n.provider==="embedded")continue;let d=n.url;try{d=new URL(n.url).host}catch{}o(d,`${s.what}${n.service?` (the ${n.service} container, started under Settings › Runtime)`:` (${n.adapter} at the address you configured)`}`,{when:`a client calls /v1/${a}`,off:n.service?`stop the ${n.service} service under Settings › Runtime`:`capabilities.${a} = null`,data:`${s.data}${n.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(d)})}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,s]of Object.entries(e.upstreams||{}))s?.baseUrl&&o(u(s.baseUrl),`model upstream "${a}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a}`,off:`upstreams.${a}.baseUrl`,local:p(u(s.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const a of e.destinations||[])a?.baseUrl&&o(u(a.baseUrl),`destination "${a.id||a.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a.id||"it"}`,off:"destinations[]",local:p(u(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(u(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:p(u(e.ner.url).split(":")[0]),data:"the text being redacted"});const i=e.tts||{};if(i.provider==="openai"||i.provider==="elevenlabs"){const a=i.remote?.baseUrl?u(i.remote.baseUrl):i.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(a,`remote read-aloud voice (${i.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:i.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}const c=e.bridge?.url||"http://127.0.0.1:4319";return o(u(c),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),r}function S(e,{ledger:t=k(),version:r="",startedAt:o=null,env:h=process.env,managed:l=null}={}){return{ok:!0,version:r,since:o?new Date(o).toISOString():null,...l?{managed:l,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:$(e,h)}}function x(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const r of e.observed||[])t.push(` ${r.local?"[local] ":""}${r.scheme}://${r.host}:${r.port} ×${r.count} last ${r.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const r of e.declared||[])t.push(` ${r.local?"[local] ":""}${r.host}`),t.push(` ${r.purpose}`),t.push(` when: ${r.when}${r.off?` · off: ${r.off}`:""}`),r.data&&t.push(` sends: ${r.data}`);return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,r])=>r).map(([r,o])=>o===!0?r:`${r}=${o}`).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};
|
package/src/engine-tunings.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function p(e){const a=String(e||"").trim();if(!a)return[];const t=[];let l="",n=null;for(const o of a)n?o===n?n=null:l+=o:o==='"'||o==="'"?n=o:/\s/.test(o)?l&&(t.push(l),l=""):l+=o;return l&&t.push(l),t}const f=Object.freeze([{id:"maxModelLen",label:"Context ceiling",kind:"number",what:"The longest prompt + answer the engine holds. Bounds the KV cache — without it the cache grows until the machine is full.",engines:["vllm","vllm-metal","llama"],default:({task:e})=>e==="chat"?8192:2048,min:512,max:262144,args:e=>["--max-model-len",String(e)],by:{llama:{default:({ramGB:e})=>e>0&&e<24?8192:16384,args:e=>["-c",String(e)]}}},{id:"prefixCache",label:"Prefix caching",kind:"bool",what:"Reuse the computed cache of a shared prompt prefix — the system prompt and tool list an agent resends every turn cost once.",engines:["vllm","vllm-metal","llama"],default:!0,args:e=>e?["--enable-prefix-caching"]:["--no-enable-prefix-caching"],by:{llama:{args:(e,{values:a})=>e?["--cache-reuse",String(a.maxModelLen>=32768?512:256)]:["--cache-reuse","0"]}}},{id:"kvCacheDtype",label:"KV cache precision",kind:"choice",options:["auto","fp8"],what:"fp8 halves the cache, so twice the context fits — on CUDA and ROCm; elsewhere leave auto.",engines:["vllm","llama"],default:"auto",backends:["cuda","rocm","metal","vulkan","cpu"],args:e=>e&&e!=="auto"?["--kv-cache-dtype",e]:[],by:{llama:{options:["auto","f16","q8_0"],what:"q8_0 halves the cache with little quality lost; auto takes q8_0 once the context is 32k or more.",args:(e,{values:a})=>e==="q8_0"||e==="auto"&&a.maxModelLen>=32768?["-ctk","q8_0","-ctv","q8_0"]:[]}}},{id:"gpuMemory",label:"GPU memory share",kind:"number",what:"The fraction of the accelerator’s memory the engine may take for weights and cache. Lower it when something else needs the GPU.",engines:["vllm"],default:.9,min:.1,max:.99,backends:["cuda","rocm","xpu"],args:e=>["--gpu-memory-utilization",String(e)]},{id:"gpuOffload",label:"GPU offload",kind:"bool",what:"Put every layer on the GPU (Metal, CUDA, Vulkan). Off runs the model on the CPU — only for a build without a GPU.",engines:["llama"],default:({backend:e})=>e!=="cpu",args:e=>["-ngl",e?"all":"0"]},{id:"flashAttention",label:"Flash attention",kind:"bool",what:"The fused attention kernel — less memory and faster on Metal and CUDA. Leave it on.",engines:["llama"],default:!0,args:e=>["-fa",e?"on":"off"]},{id:"threads",label:"Generation threads",kind:"number",what:"CPU threads for decoding. The performance cores — more only contends.",engines:["llama"],default:({perfCores:e})=>e||8,min:1,max:128,args:e=>["-t",String(e)]},{id:"batchThreads",label:"Prompt threads",kind:"number",what:"CPU threads for reading the prompt. All the physical cores.",engines:["llama"],default:({cores:e})=>e||8,min:1,max:128,args:e=>["-tb",String(e)]},{id:"speculative",label:"Speculative decoding",kind:"choice",options:["off","ngram"],what:"Draft tokens by n-gram lookup in the prompt and verify them in one pass — faster on code and edits, where the answer repeats the input.",engines:["vllm","vllm-metal","llama"],default:"off",tasks:["chat"],args:e=>e==="ngram"?["--speculative-config",JSON.stringify({method:"ngram",num_speculative_tokens:5,prompt_lookup_max:4})]:[],by:{llama:{options:["off","ngram","draft-mtp","draft"],default:({values:e})=>e?.draftModel?"draft-mtp":"off",what:"Draft tokens and verify them in one pass. ngram needs nothing; draft-mtp is the model’s own MTP head (name the draft file below — the `lm` recipe, ~0.75 accepted); draft is a small sibling model.",args:(e,{values:a,backend:t})=>e==="off"?[]:e==="ngram"?["--spec-type","ngram-simple","--spec-draft-n-max","3"]:a.draftModel?["--model-draft",a.draftModel,"--spec-type",e,"--spec-draft-n-max","3","--spec-draft-ngl",t==="cpu"?"0":"all",...a.maxModelLen>=32768?["--spec-draft-type-k","q8_0","--spec-draft-type-v","q8_0"]:[]]:[]}}},{id:"draftModel",label:"Draft model",kind:"text",what:"The GGUF the draft-mtp / draft modes draft with — the model’s MTP file (…-MTP.gguf) or a small sibling. A path, or a Hugging Face id.",engines:["llama"],default:"",tasks:["chat"],args:()=>[]},{id:"toolCalls",label:"Tool calling",kind:"choice",options:["off","hermes","llama3_json","mistral","pythonic","qwen3_coder"],what:"Parse the model’s tool calls into OpenAI tool_calls, so a harness sees tools and not text. Qwen3 and SmolLM3 speak hermes; Llama 3 llama3_json.",engines:["vllm","vllm-metal"],default:({model:e})=>/^(Qwen\/Qwen3|mlx-community\/Qwen3|HuggingFaceTB\/SmolLM3)/i.test(e||"")?"hermes":/Llama-3/i.test(e||"")?"llama3_json":"off",tasks:["chat"],args:e=>e&&e!=="off"?["--enable-auto-tool-choice","--tool-call-parser",e]:[]},{id:"reasoning",label:"Reasoning parser",kind:"choice",options:["off","qwen3","deepseek_r1"],what:"Split a thinking model’s reasoning from its answer, so the answer arrives clean and the thinking is a separate field.",engines:["vllm","vllm-metal","llama"],default:({model:e})=>/Qwen3/i.test(e||"")?"qwen3":"off",tasks:["chat"],args:e=>e&&e!=="off"?["--reasoning-parser",e]:[],by:{llama:{options:["auto","on","off"],default:"auto",label:"Thinking",what:"Whether the model thinks before answering (a template that supports it): on with a 1024-token budget returned as a separate field, off for direct answers, auto as the model decides.",args:e=>e==="on"?["--reasoning","on","--reasoning-budget","1024","--reasoning-format","deepseek"]:e==="off"?["--reasoning","off","--reasoning-budget","0"]:[]}}},{id:"chatTemplate",label:"Chat template",kind:"text",what:"A Jinja template file that overrides the model’s own — the fix when a fresh release ships a broken prompt template.",engines:["vllm","vllm-metal","llama","mlx"],default:"",tasks:["chat"],args:e=>e?["--chat-template",e]:[],by:{llama:{args:e=>e?["--chat-template-file",e]:[]}}},{id:"vision",label:"Vision projector",kind:"text",what:"The model’s multimodal projector (mmproj-*.gguf) — with it the server takes images; without it, more memory for text. A path.",engines:["llama"],default:"",tasks:["chat"],args:e=>e?["--mmproj",e,"--mmproj-offload"]:[]},{id:"maxSeqs",label:"Concurrent requests",kind:"number",what:"How many requests the engine batches at once. One user needs few; a team behind the gateway more — each costs cache.",engines:["vllm","vllm-metal","llama"],default:8,min:1,max:256,args:e=>["--max-num-seqs",String(e)],by:{llama:{default:1,what:"Server slots. One for a big model and a long context; more only when several people share this machine — each slot holds its own context.",args:e=>["-np",String(e)]}}},{id:"extraArgs",label:"Extra flags",kind:"args",what:"Anything else the engine takes, as you would type it after the command — the engine’s own documentation is the list. Appended last, so it wins over the rows above.",engines:["vllm","vllm-metal","llama","mlx"],default:"",args:e=>p(e)}]),x=e=>f.find(a=>a.id===e)||null;function b(e,a){const t=e.by?.[a];return t?{...e,...t,by:void 0}:e}function d(e,{task:a="chat",backend:t=null}={}){return f.filter(l=>l.engines.includes(e)&&(!l.tasks||l.tasks.includes(a))&&(!l.backends||!t||l.backends.includes(t))).map(l=>b(l,e))}function u(e,a){return typeof e.default=="function"?e.default(a):e.default}function w(e,a){if(!e)return null;if(e.kind==="bool")return typeof a=="boolean"?a:a==="true"?!0:a==="false"?!1:null;if(e.kind==="number"){const t=Number(a);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}if(e.kind==="choice")return e.options.includes(a)?a:null;if(e.kind==="text"){const t=String(a??"").trim();return t.length<=512&&!t.startsWith("-")&&!/[\s"'`$;|&<>]/.test(t)?t:null}if(e.kind==="args"){const t=String(a??"").trim();return t.length<=2e3&&!/[`$;|&<>\n]/.test(t)?t:null}return null}function y(e,a,t,l={}){const n={...a||{}},o=d(e,l);for(const[s,i]of Object.entries(t||{})){const r=o.find(h=>h.id===s);if(!r)return{error:`no tuning ${JSON.stringify(s)} for ${e}`};if(i==null){delete n[s];continue}const m=w(r,i);if(m===null)return{error:`${r.label}: ${r.kind==="choice"?`one of ${r.options.join(", ")}`:r.kind==="number"?`a number between ${r.min} and ${r.max}`:r.kind==="bool"?"on or off":r.kind==="args"?"flags as you would type them — no shell characters":"a plain path or id"}`};n[s]=m}return n}function c(e,a,t={}){const l={};for(const n of d(e,t))l[n.id]=a&&a[n.id]!==void 0?a[n.id]:u(n,{...t,values:{...a||{},...l}});return l}function v(e,a,t={}){const l=c(e,a,t),n=[];for(const o of d(e,t))n.push(...o.args(l[o.id],{...t,values:l}));return n}function S(e,a,t={}){const l=c(e,a,t);return d(e,t).map(n=>({id:n.id,label:n.label,what:n.what,kind:n.kind,...n.options?{options:n.options}:{},...n.kind==="number"?{min:n.min,max:n.max}:{},default:a&&a[n.id]!==void 0?u(n,{...t,values:l}):l[n.id],...a&&a[n.id]!==void 0?{value:a[n.id]}:{}}))}const M=Object.freeze({vllm:{label:"vLLM engine arguments",url:"https://docs.vllm.ai/en/latest/configuration/engine_args/"},"vllm-metal":{label:"vLLM engine arguments (vLLM-Metal takes the same)",url:"https://docs.vllm.ai/en/latest/configuration/engine_args/"},llama:{label:"llama-server flags",url:"https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md"},mlx:{label:"mlx_lm.server flags",url:"https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/SERVER.md"}}),k=Object.freeze([{id:"speed",label:"Fast chat",what:"Short questions, quick answers — the smallest context, the least memory.",ctx:({ramGB:e})=>e>0&&e<24?4096:8192,needGB:0},{id:"coding",label:"Coding",what:"A coding assistant’s room for a file and a conversation. The default.",ctx:({ramGB:e})=>e>0&&e<24?8192:16384,needGB:0},{id:"long",label:"Long context",what:"Several files or a long page at once — slower, the cache quantised to fit.",ctx:({ramGB:e})=>e>=36?32768:e>=24?16384:8192,needGB:24},{id:"xl",label:"Extra long",what:"A whole repository’s worth. An experiment under 64 GB: close other apps and watch memory.",ctx:({ramGB:e})=>e>=48?65536:32768,needGB:48}]);function _(e,a,t={}){const l=d(e,t);if((t.task||"chat")!=="chat"||!l.some(s=>s.id==="maxModelLen"))return[];const n=c(e,a,t);let o=!1;return k.map(s=>{const i=s.ctx(t),r={maxModelLen:i,...l.some(g=>g.id==="kvCacheDtype")?{kvCacheDtype:i>=32768?e==="llama"?"q8_0":t.backend==="cuda"||t.backend==="rocm"?"fp8":"auto":"auto"}:{}},m=!t.ramGB||t.ramGB>=s.needGB,h=!o&&n.maxModelLen===i;return h&&(o=!0),{id:s.id,label:s.label,what:s.what,patch:r,fits:m,...m?{}:{why:`needs ${s.needGB} GB of memory; this machine has ${t.ramGB}`},active:h}})}export{M as ENGINE_DOCS,k as PROFILES,f as TUNINGS,w as coerceTuning,b as forEngine,y as patchTunings,_ as profilesFor,c as resolveTunings,p as splitArgs,v as tuningArgs,u as tuningDefault,S as tuningRows,d as tuningsFor};
|
|
1
|
+
function p(e){const a=String(e||"").trim();if(!a)return[];const t=[];let l="",n=null;for(const o of a)n?o===n?n=null:l+=o:o==='"'||o==="'"?n=o:/\s/.test(o)?l&&(t.push(l),l=""):l+=o;return l&&t.push(l),t}const c=Object.freeze([{id:"maxModelLen",label:"Context ceiling",kind:"number",what:"The longest prompt + answer the engine holds. Bounds the KV cache — without it the cache grows until the machine is full.",engines:["vllm","vllm-metal","llama"],default:({task:e})=>e==="chat"?8192:2048,min:512,max:262144,args:e=>["--max-model-len",String(e)],by:{llama:{default:({ramGB:e})=>e>0&&e<24?8192:16384,args:e=>["-c",String(e)]}}},{id:"prefixCache",label:"Prefix caching",kind:"bool",what:"Reuse the computed cache of a shared prompt prefix — the system prompt and tool list an agent resends every turn cost once.",engines:["vllm","vllm-metal","llama"],default:!0,args:e=>e?["--enable-prefix-caching"]:["--no-enable-prefix-caching"],by:{llama:{args:(e,{values:a})=>e?["--cache-reuse",String(a.maxModelLen>=32768?512:256)]:["--cache-reuse","0"]}}},{id:"kvCacheDtype",label:"KV cache precision",kind:"choice",options:["auto","fp8"],what:"fp8 halves the cache, so twice the context fits — on CUDA and ROCm; elsewhere leave auto.",engines:["vllm","llama"],default:"auto",backends:["cuda","rocm","metal","vulkan","cpu"],args:e=>e&&e!=="auto"?["--kv-cache-dtype",e]:[],by:{llama:{options:["auto","f16","q8_0"],what:"q8_0 halves the cache with little quality lost; auto takes q8_0 once the context is 32k or more.",args:(e,{values:a})=>e==="q8_0"||e==="auto"&&a.maxModelLen>=32768?["-ctk","q8_0","-ctv","q8_0"]:[]}}},{id:"gpuMemory",label:"GPU memory share",kind:"number",what:"The fraction of the accelerator’s memory the engine may take for weights and cache. Lower it when something else needs the GPU.",engines:["vllm"],default:.9,min:.1,max:.99,backends:["cuda","rocm","xpu"],args:e=>["--gpu-memory-utilization",String(e)]},{id:"gpuOffload",label:"GPU offload",kind:"bool",what:"Put every layer on the GPU (Metal, CUDA, Vulkan). Off runs the model on the CPU — only for a build without a GPU.",engines:["llama"],default:({backend:e})=>e!=="cpu",args:e=>["-ngl",e?"all":"0"]},{id:"flashAttention",label:"Flash attention",kind:"bool",what:"The fused attention kernel — less memory and faster on Metal and CUDA. Leave it on.",engines:["llama"],default:!0,args:e=>["-fa",e?"on":"off"]},{id:"threads",label:"Generation threads",kind:"number",what:"CPU threads for decoding. The performance cores — more only contends.",engines:["llama"],default:({perfCores:e})=>e||8,min:1,max:128,args:e=>["-t",String(e)]},{id:"batchThreads",label:"Prompt threads",kind:"number",what:"CPU threads for reading the prompt. All the physical cores.",engines:["llama"],default:({cores:e})=>e||8,min:1,max:128,args:e=>["-tb",String(e)]},{id:"speculative",label:"Speculative decoding",kind:"choice",options:["off","ngram"],what:"Draft tokens by n-gram lookup in the prompt and verify them in one pass — faster on code and edits, where the answer repeats the input.",engines:["vllm","vllm-metal","llama"],default:"off",tasks:["chat"],args:e=>e==="ngram"?["--speculative-config",JSON.stringify({method:"ngram",num_speculative_tokens:5,prompt_lookup_max:4})]:[],by:{llama:{options:["off","ngram","draft-mtp","draft"],default:({values:e})=>e?.draftModel?"draft-mtp":"off",what:"Draft tokens and verify them in one pass. ngram needs nothing; draft-mtp is the model’s own MTP head (name the draft file below — the `lm` recipe, ~0.75 accepted); draft is a small sibling model.",args:(e,{values:a,backend:t})=>e==="off"?[]:e==="ngram"?["--spec-type","ngram-simple","--spec-draft-n-max","3"]:a.draftModel?["--model-draft",a.draftModel,"--spec-type",e,"--spec-draft-n-max","3","--spec-draft-ngl",t==="cpu"?"0":"all",...a.maxModelLen>=32768?["--spec-draft-type-k","q8_0","--spec-draft-type-v","q8_0"]:[]]:[]}}},{id:"draftModel",label:"Draft model",kind:"text",what:"The GGUF the draft-mtp / draft modes draft with — the model’s MTP file (…-MTP.gguf) or a small sibling. A path, or a Hugging Face id.",engines:["llama"],default:"",tasks:["chat"],args:()=>[]},{id:"toolCalls",label:"Tool calling",kind:"choice",options:["off","hermes","llama3_json","mistral","pythonic","qwen3_coder"],what:"Parse the model’s tool calls into OpenAI tool_calls, so a harness sees tools and not text. Qwen3 and SmolLM3 speak hermes; Llama 3 llama3_json.",engines:["vllm","vllm-metal"],default:({model:e})=>/^(Qwen\/Qwen3|mlx-community\/Qwen3|HuggingFaceTB\/SmolLM3)/i.test(e||"")?"hermes":/Llama-3/i.test(e||"")?"llama3_json":"off",tasks:["chat"],args:e=>e&&e!=="off"?["--enable-auto-tool-choice","--tool-call-parser",e]:[]},{id:"reasoning",label:"Reasoning parser",kind:"choice",options:["off","qwen3","deepseek_r1"],what:"Split a thinking model’s reasoning from its answer, so the answer arrives clean and the thinking is a separate field.",engines:["vllm","vllm-metal","llama","mlx"],default:({model:e})=>/Qwen3/i.test(e||"")?"qwen3":"off",tasks:["chat"],args:e=>e&&e!=="off"?["--reasoning-parser",e]:[],by:{mlx:{options:["off","on"],default:"off",label:"Thinking",what:"Whether a thinking model (Qwen3) reasons before answering. Off answers directly — faster, cooler, and enough for titles, topics and short replies.",args:e=>e==="on"?[]:["--chat-template-args",'{"enable_thinking":false}']},llama:{options:["auto","on","off"],default:"auto",label:"Thinking",what:"Whether the model thinks before answering (a template that supports it): on with a 1024-token budget returned as a separate field, off for direct answers, auto as the model decides.",args:e=>e==="on"?["--reasoning","on","--reasoning-budget","1024","--reasoning-format","deepseek"]:e==="off"?["--reasoning","off","--reasoning-budget","0"]:[]}}},{id:"chatTemplate",label:"Chat template",kind:"text",what:"A Jinja template file that overrides the model’s own — the fix when a fresh release ships a broken prompt template.",engines:["vllm","vllm-metal","llama","mlx"],default:"",tasks:["chat"],args:e=>e?["--chat-template",e]:[],by:{llama:{args:e=>e?["--chat-template-file",e]:[]}}},{id:"vision",label:"Vision projector",kind:"text",what:"The model’s multimodal projector (mmproj-*.gguf) — with it the server takes images; without it, more memory for text. A path.",engines:["llama"],default:"",tasks:["chat"],args:e=>e?["--mmproj",e,"--mmproj-offload"]:[]},{id:"maxSeqs",label:"Concurrent requests",kind:"number",what:"How many requests the engine batches at once. One user needs few; a team behind the gateway more — each costs cache.",engines:["vllm","vllm-metal","llama"],default:8,min:1,max:256,args:e=>["--max-num-seqs",String(e)],by:{llama:{default:1,what:"Server slots. One for a big model and a long context; more only when several people share this machine — each slot holds its own context.",args:e=>["-np",String(e)]}}},{id:"extraArgs",label:"Extra flags",kind:"args",what:"Anything else the engine takes, as you would type it after the command — the engine’s own documentation is the list. Appended last, so it wins over the rows above.",engines:["vllm","vllm-metal","llama","mlx"],default:"",args:e=>p(e)}]),x=e=>c.find(a=>a.id===e)||null;function b(e,a){const t=e.by?.[a];return t?{...e,...t,by:void 0}:e}function m(e,{task:a="chat",backend:t=null}={}){return c.filter(l=>l.engines.includes(e)&&(!l.tasks||l.tasks.includes(a))&&(!l.backends||!t||l.backends.includes(t))).map(l=>b(l,e))}function u(e,a){return typeof e.default=="function"?e.default(a):e.default}function w(e,a){if(!e)return null;if(e.kind==="bool")return typeof a=="boolean"?a:a==="true"?!0:a==="false"?!1:null;if(e.kind==="number"){const t=Number(a);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}if(e.kind==="choice")return e.options.includes(a)?a:null;if(e.kind==="text"){const t=String(a??"").trim();return t.length<=512&&!t.startsWith("-")&&!/[\s"'`$;|&<>]/.test(t)?t:null}if(e.kind==="args"){const t=String(a??"").trim();return t.length<=2e3&&!/[`$;|&<>\n]/.test(t)?t:null}return null}function y(e,a,t,l={}){const n={...a||{}},o=m(e,l);for(const[s,i]of Object.entries(t||{})){const r=o.find(h=>h.id===s);if(!r)return{error:`no tuning ${JSON.stringify(s)} for ${e}`};if(i==null){delete n[s];continue}const d=w(r,i);if(d===null)return{error:`${r.label}: ${r.kind==="choice"?`one of ${r.options.join(", ")}`:r.kind==="number"?`a number between ${r.min} and ${r.max}`:r.kind==="bool"?"on or off":r.kind==="args"?"flags as you would type them — no shell characters":"a plain path or id"}`};n[s]=d}return n}function f(e,a,t={}){const l={};for(const n of m(e,t))l[n.id]=a&&a[n.id]!==void 0?a[n.id]:u(n,{...t,values:{...a||{},...l}});return l}function v(e,a,t={}){const l=f(e,a,t),n=[];for(const o of m(e,t))n.push(...o.args(l[o.id],{...t,values:l}));return n}function S(e,a,t={}){const l=f(e,a,t);return m(e,t).map(n=>({id:n.id,label:n.label,what:n.what,kind:n.kind,...n.options?{options:n.options}:{},...n.kind==="number"?{min:n.min,max:n.max}:{},default:a&&a[n.id]!==void 0?u(n,{...t,values:l}):l[n.id],...a&&a[n.id]!==void 0?{value:a[n.id]}:{}}))}const _=Object.freeze({vllm:{label:"vLLM engine arguments",url:"https://docs.vllm.ai/en/latest/configuration/engine_args/"},"vllm-metal":{label:"vLLM engine arguments (vLLM-Metal takes the same)",url:"https://docs.vllm.ai/en/latest/configuration/engine_args/"},llama:{label:"llama-server flags",url:"https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md"},mlx:{label:"mlx_lm.server flags",url:"https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/SERVER.md"}}),k=Object.freeze([{id:"speed",label:"Fast chat",what:"Short questions, quick answers — the smallest context, the least memory.",ctx:({ramGB:e})=>e>0&&e<24?4096:8192,needGB:0},{id:"coding",label:"Coding",what:"A coding assistant’s room for a file and a conversation. The default.",ctx:({ramGB:e})=>e>0&&e<24?8192:16384,needGB:0},{id:"long",label:"Long context",what:"Several files or a long page at once — slower, the cache quantised to fit.",ctx:({ramGB:e})=>e>=36?32768:e>=24?16384:8192,needGB:24},{id:"xl",label:"Extra long",what:"A whole repository’s worth. An experiment under 64 GB: close other apps and watch memory.",ctx:({ramGB:e})=>e>=48?65536:32768,needGB:48}]);function M(e,a,t={}){const l=m(e,t);if((t.task||"chat")!=="chat"||!l.some(s=>s.id==="maxModelLen"))return[];const n=f(e,a,t);let o=!1;return k.map(s=>{const i=s.ctx(t),r={maxModelLen:i,...l.some(g=>g.id==="kvCacheDtype")?{kvCacheDtype:i>=32768?e==="llama"?"q8_0":t.backend==="cuda"||t.backend==="rocm"?"fp8":"auto":"auto"}:{}},d=!t.ramGB||t.ramGB>=s.needGB,h=!o&&n.maxModelLen===i;return h&&(o=!0),{id:s.id,label:s.label,what:s.what,patch:r,fits:d,...d?{}:{why:`needs ${s.needGB} GB of memory; this machine has ${t.ramGB}`},active:h}})}export{_ as ENGINE_DOCS,k as PROFILES,c as TUNINGS,w as coerceTuning,b as forEngine,y as patchTunings,M as profilesFor,f as resolveTunings,p as splitArgs,v as tuningArgs,u as tuningDefault,S as tuningRows,m as tuningsFor};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readFileSync as u}from"node:fs";import s from"node:path";const f="http://127.0.0.1:7878",c=1024*1024;async function m(n,{url:i=f,fetchImpl:t=globalThis.fetch,timeoutMs:r=1500}={}){if(!(n>0)||!t)return null;try{const o=await t(`${i}/v1/fit?need_gb=${(n/1024).toFixed(2)}`,{signal:AbortSignal.timeout(r)});if(!o.ok)return null;const e=await o.json();if(typeof e?.fits!="boolean")return null;const l=a=>Number.isFinite(a)?Math.round(a/c):null;return{fits:e.fits,needMB:l(e.neededBytes),availableMB:l(e.availableBytes),shortfallMB:l(e.shortfallBytes)||0,fitsGPULimit:e.fitsGPULimit??null,gpuWiredLimitMB:l(e.gpuWiredLimitBytes),close:Array.isArray(e.closeToFit)?e.closeToFit:[]}}catch{return null}}function _(n,i){if(!(i>0))return 0;let t;try{t=JSON.parse(u(n,"utf8"))}catch{return null}t=t.text_config||t;const r=t.num_hidden_layers,o=t.num_attention_heads,e=t.num_key_value_heads||o,l=t.head_dim||(t.hidden_size&&o?t.hidden_size/o:0);if(!(r>0&&e>0&&l>0))return null;const a=Number.isInteger(t.full_attention_interval)&&t.full_attention_interval>0?Math.ceil(r/t.full_attention_interval):r;return Math.ceil(2*a*e*l*2*i/c)}function y(n,i){try{const t=s.join(n,"hub",`models--${String(i).replace("/","--")}`),r=u(s.join(t,"refs","main"),"utf8").trim();return r?s.join(t,"snapshots",r,"config.json"):null}catch{return null}}function p({ramMB:n,kvMB:i=0}){return Math.ceil(((n||0)+(i||0))*1.1)}export{f as HEATWATCH_URL,y as cachedConfigPath,_ as kvCacheMB,m as liveFit,p as needMB};
|
package/src/inference-engines.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const s="0.29.0",
|
|
1
|
+
const s="0.29.0",i=Object.freeze({cuda:`docker.io/vllm/vllm-openai:v${s}`,rocm:`docker.io/vllm/vllm-openai-rocm:v${s}`,xpu:`docker.io/vllm/vllm-openai-xpu:v${s}`,cpu:"ghcr.io/chatpanel/vllm-cpu:latest"});function h(e){return e==="x64"||e==="amd64"?[`public.ecr.aws/q9t5s3a7/vllm-cpu-release-repo:v${s}`,i.cpu]:[i.cpu]}const y=Object.freeze({command:"brew tap vllm-project/vllm-metal https://github.com/vllm-project/vllm-metal && brew install vllm-project/vllm-metal/vllm-metal",steps:[["brew","tap","vllm-project/vllm-metal","https://github.com/vllm-project/vllm-metal"],["brew","install","vllm-project/vllm-metal/vllm-metal"]],note:"vLLM on the Apple Silicon GPU through MLX (vLLM-Metal, community maintained, v0.2). macOS Sonoma or later. Then `vllm serve` is on PATH; the Runtime starts it here, under the sandbox."});function m(e,t){return e==="cuda"?t==="podman"?["--device","nvidia.com/gpu=all","--security-opt=label=disable"]:["--runtime","nvidia","--gpus","all","--ipc=host"]:e==="rocm"?["--device","/dev/kfd","--device","/dev/dri","--group-add","video","--security-opt","seccomp=unconfined"]:e==="xpu"?["--device","/dev/dri"]:[]}async function L({exec:e,platform:t=process.platform,arch:n=process.arch}={}){const a=async(l,o)=>{try{const r=await e(l,o,{timeout:8e3});return r&&!/error|not found|no devices/i.test(String(r.stdout||"")+String(r.stderr||""))}catch{return!1}};return t==="darwin"&&n==="arm64"?"apple":await a("nvidia-smi",["-L"])?"cuda":t==="linux"&&await a("rocm-smi",["--showid"])?"rocm":t==="linux"&&await a("sycl-ls",[])?"xpu":null}function x({platform:e=process.platform,arch:t=process.arch,accelerator:n=null,engine:a=null,vllmOnPath:l=!1,containerOnly:o=!1}={}){return e==="darwin"&&(t==="arm64"||n==="apple")&&o?{backend:"cpu",kind:"container",image:i.cpu,sources:h(t),recipe:"vllm-cpu",devices:[],for:"an embedding model, or a whisper transcriber — the jobs the Metal engines cannot serve",speed:"slow: CPU only, no GPU from the VM; a 90-minute build first",notFor:"chat — use llama.cpp, MLX or vLLM-Metal for that",why:"A container on a Mac is CPU-only (the GPU is not reachable from the VM).",warn:"On Apple Silicon, vLLM-Metal is the engine that uses the GPU — run that service instead; this one is for trying the CPU build itself."}:e==="darwin"&&(t==="arm64"||n==="apple")?{backend:"metal",kind:"native",runner:"vllm serve",install:y,for:"chat, with vLLM’s server and API (tool-call and reasoning parsers)",speed:"fast: the Apple GPU through MLX",notFor:"embeddings or transcription — the container for those",why:"Apple Silicon: vLLM-Metal on the host GPU (MLX underneath) — a container here is CPU-only.",...l?{}:{warn:"`vllm` is not on PATH — install vLLM-Metal (the command beside this), then Run."}}:a?n==="cuda"?{backend:"cuda",kind:"container",image:i.cuda,devices:m("cuda",a),for:"chat, embeddings, transcription — full precision, batched for several users",speed:"fast: the GPU, batched",why:`NVIDIA GPU found (nvidia-smi): vLLM ${s} CUDA image${e==="win32"?", through WSL2’s GPU passthrough":""}.`,...a==="podman"&&e==="linux"?{warn:"Podman needs the NVIDIA Container Toolkit CDI spec (nvidia-ctk cdi generate) for --device nvidia.com/gpu=all."}:{}}:n==="rocm"&&e==="linux"?{backend:"rocm",kind:"container",image:i.rocm,devices:m("rocm",a),for:"chat, embeddings, transcription",speed:"fast: the GPU, batched",why:"AMD GPU found (rocm-smi): vLLM ROCm image."}:n==="xpu"&&e==="linux"?{backend:"xpu",kind:"container",image:i.xpu,devices:m("xpu",a),for:"chat, embeddings, transcription",speed:"fast: the GPU",why:"Intel GPU found (sycl-ls): vLLM XPU image."}:{backend:"cpu",kind:"container",image:i.cpu,sources:h(t),recipe:"vllm-cpu",devices:[],for:"an embedding model or a whisper transcriber; a small chat model to try",speed:`slow: CPU only${t==="x64"?"":"; a 90-minute build first"}`,why:`No accelerator found: vLLM’s CPU build (${t}). Small models only; slow.`,warn:"CPU inference — a 0.6B chat model is usable, anything larger wants a GPU."}:{backend:n==="cuda"?"cuda":n==="rocm"?"rocm":n==="xpu"?"xpu":"cpu",kind:"container",image:null,devices:[],why:"No container engine yet — Settings › Runtime has the install door.",warn:"no container engine"}}const f=Object.freeze({darwin:{command:"brew install llama.cpp",steps:[["brew","install","llama.cpp"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Homebrew’s build has Metal on."},win32:{command:"winget install --id ggml.llamacpp -e",steps:[["winget","install","--id","ggml.llamacpp","-e","--accept-source-agreements","--accept-package-agreements"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Or a release zip from GitHub (the CUDA build for an NVIDIA GPU)."},linux:{command:'curl -fsSL https://github.com/ggml-org/llama.cpp/releases/latest -o /dev/null && echo "download the release for your GPU"',url:"https://github.com/ggml-org/llama.cpp/releases",note:"A release build for the GPU (CUDA, Vulkan) or the CPU build; or build from source."}});function M({platform:e=process.platform,arch:t=process.arch,accelerator:n=null,llamaOnPath:a=!1}={}){const l=e==="darwin"&&t==="arm64"?"metal":n==="cuda"?"cuda":n==="rocm"?"rocm":n==="xpu"?"vulkan":"cpu",o=l==="metal"?"Apple Silicon: llama.cpp on the Metal GPU, all layers offloaded":l==="cpu"?"no accelerator found: llama.cpp on the CPU — a small quantised model runs at a usable pace":`llama.cpp with the ${l.toUpperCase()} build, all layers offloaded`,r=f[e]||f.linux;return{backend:l,kind:"native",runner:"llama-server",install:r,why:o,for:"chat and vision — the largest choice of models (GGUF), your own .gguf files, the MTP draft that makes a big model fast",speed:l==="cpu"?"usable: the CPU with a 4-bit model":`fast: the ${l==="metal"?"Apple":l.toUpperCase()} GPU`,...a?{}:{warn:"`llama-server` is not on PATH — install llama.cpp (the command beside this), then Run."}}}async function k({exec:e,platform:t=process.platform,totalmem:n=()=>0,cpus:a=()=>[]}={}){const l=Math.round(n()/1073741824),o=a().length||0;let r=Math.max(1,Math.floor(o/2))||1,c=r;if(t==="darwin"&&e){const p=async w=>{try{const b=await e("sysctl",["-n",w]),u=Number(String(b?.stdout||"").trim());return u>0?u:0}catch{return 0}},[d,g]=await Promise.all([p("hw.physicalcpu"),p("hw.perflevel0.physicalcpu")]);d&&(r=d),c=g||r}else o&&(r=o,c=Math.min(o,8));return{ramGB:l,cores:r,perfCores:c}}const v=Object.freeze({command:"uv tool install mlx-lm # or: pip3 install --user mlx-lm",steps:[["uv","tool","install","mlx-lm"]],fallback:[["pip3","install","--user","mlx-lm"]],url:"https://github.com/ml-explore/mlx-lm",note:"Needs uv or Python 3.10+; puts mlx_lm.server on PATH."});function P({platform:e=process.platform,arch:t=process.arch,mlxOnPath:n=!1}={}){return e==="darwin"&&t==="arm64"?{backend:"metal",kind:"native",runner:"mlx_lm.server",install:v,for:"chat — Apple’s own framework, the smallest install",speed:"fast: the Apple GPU",notFor:"vision, embeddings, transcription",why:"Apple Silicon: MLX on the GPU with unified memory — the lightest engine for a Mac.",...n?{}:{warn:"`mlx_lm.server` is not on PATH — install mlx-lm (the command beside this), then Run."}}:{backend:"none",kind:"native",runner:"mlx_lm.server",why:"MLX runs on Apple Silicon only.",install:v}}function U({platform:e=process.platform,arch:t=process.arch,osMajor:n=0,appleOnPath:a=!1,appleInstall:l=null}={}){const o={kind:"native",runner:"chatpanel-apple-model",...l?{install:l}:{}};return e==="darwin"&&t==="arm64"?n<25?{...o,backend:"none",why:"Apple’s on-device model needs macOS 26 or later."}:{...o,backend:"apple",for:"titles, topics, short answers — the system keeps the model, nothing stays loaded",speed:"quick for short text; the Mac decides when the model is in memory",notFor:"long chats (a 4,096-token window), images, tools",why:"Apple Silicon on macOS 26: Apple’s own model, which the system loads when asked and frees when not — the lightest way to run a model on a Mac.",...a?{}:{warn:l?.steps?.length?"The helper is not built in this checkout yet — Install builds it.":"The helper is not in this install — it comes with the gateway from npm and the desktop app."}}:{...o,backend:"none",why:"Apple’s on-device model runs on Apple Silicon Macs only."}}function A({platform:e=process.platform,arch:t=process.arch,accelerator:n=null}={}){return e==="darwin"&&t==="arm64"?{engine:"mlx",why:"Apple Silicon: MLX — Apple’s own framework on the GPU with unified memory, the smallest install and the lightest engine for a Mac. llama.cpp on Metal is the alternative when you need vision, embeddings or a GGUF model."}:n==="cuda"||n==="rocm"||n==="xpu"?{engine:"vllm",why:`${n.toUpperCase()} GPU: vLLM in a container serves a full-precision model at speed, with batching for several users.`}:{engine:"llama",why:"No GPU found: llama.cpp with a 4-bit model is what runs well on a CPU."}}export{f as LLAMA_INSTALL,v as MLX_INSTALL,i as VLLM_IMAGES,y as VLLM_METAL_INSTALL,s as VLLM_VERSION,L as detectAccelerator,m as deviceArgs,k as hostShape,U as pickAppleEngine,x as pickInferenceEngine,M as pickLlamaEngine,P as pickMlxEngine,A as recommendEngine,h as vllmCpuSources};
|
package/src/link-host.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as q,writeFileSync as ee,renameSync as te,mkdirSync as ne,chmodSync as oe}from"node:fs";import{dirname as re,join as ae}from"node:path";import B from"node:os";import{createLinkEndpoint as se}from"@chatpanel/events/link-connect.js";import{noiseCrypto as ie}from"@chatpanel/events/link-noise.js";import{pairingUri as ce,admissionToken as j,admissionVerifier as J,toB64url as $,fromB64url as I}from"@chatpanel/events/link-protocol.js";import{qrSvg as le}from"@chatpanel/events/qr.js";import{verifyEntitlement as pe,licenseFromPayload as de,can as me,FEATURE_TIER as V}from"@chatpanel/events/entitlement.js";const ue="https://link.chatpanel.net",G=10*6e4,fe=3e4,R=[1e3,2e3,5e3,1e4,3e4,6e4],he=40,ye=16e3,ke=/(^|\n): ?ping\n\n/g,ge=4,we=[/^\/v1\/models(?:\/|$|\?)/,/^\/v1\/chat\/completions$/,/^\/v1\/messages$/,/^\/v1\/audio\/(?:transcriptions|speech)$/,/^\/v1\/history\/(?:search|smart-search|get|list|related|status)(?:$|\?)/,/^\/v1\/history\/(?:records|stream)(?:$|\?)/,/^\/v1\/memory\/(?:recall|list|remember)(?:$|\?)/,/^\/v1\/(?:research|search|read|rerank|decide|capabilities|fusions)(?:$|\?)/,/^\/v1\/status$/],Ee=l=>we.some(i=>i.test(String(l||""))),H="x-chatpanel-entitlement",z="x-chatpanel-install",Y=(l,i)=>{for(const[m,y]of Object.entries(l||{}))if(m.toLowerCase()===i)return String(y||"");return""};async function Se(l,{now:i=Date.now()}={}){if(!V.link||V.link==="free")return!1;const m=Y(l,H),y=Y(l,z);if(!m||!y)return!1;const A=await pe(m,y,{now:i});return!!A&&me(de(A,{at:i}),"link",0,i)}function Te(){return ae(B.homedir(),".chatpanel","link.json")}function ve(l){try{const i=JSON.parse(q(l,"utf8"));return{v:1,key:i.key||null,rooms:Array.isArray(i.rooms)?i.rooms:[]}}catch{return{v:1,key:null,rooms:[]}}}function W(l,i){ne(re(l),{recursive:!0});const m=`${l}.tmp`;ee(m,JSON.stringify(i,null,2),{mode:384});try{oe(m,384)}catch{}te(m,l)}function Ne({relay:l=ue,name:i=B.hostname(),dispatch:m,path:y=Te(),fetch:A=globalThis.fetch,WebSocket:Q=globalThis.WebSocket,now:u=()=>Date.now(),random:U=f=>globalThis.crypto.getRandomValues(new Uint8Array(f)),crypto:_=ie(),log:x=()=>{},mayLink:X=Se}={}){const f=new URL(l).origin;if(!/^https:/.test(f)&&!/^http:\/\/127\.0\.0\.1(?::\d+)?$/.test(f))throw new Error("link: the relay must be https");let p=ve(y);const h=new Map;let g=null;async function b(){return g||(p.key?g=await _.keyPairFromPrivate(I(p.key)):(g=await _.generateKeyPair(),p.key=$(g.raw),W(y,p)),g)}const L=e=>p.rooms.find(t=>t.room===e)||null,P=()=>W(y,p),K=async(e,t,n,a)=>{try{return await A(`${f}/v1/room/${e}`,{method:t,headers:{authorization:`Bearer ${n}`,...a?{"content-type":"application/json"}:{}},body:a?JSON.stringify(a):void 0})}catch(c){const r=c?.cause?.code||"",o=r==="ENOTFOUND"?"this computer cannot look up its name (a VPN or DNS that does not know it yet)":r?`${r}`:c?.message||"no answer";throw new Error(`cannot reach the Link relay at ${new URL(f).host}: ${o}`)}};async function Z(e,t,n){if(!Ee(t.path))return await n.head(403,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:"link: a paired phone may not call this",type:"forbidden"}})),n.end();if(!await X(t.headers,{now:u()}))return await n.head(402,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:"ChatPanel Link needs Pro on this phone — upgrade on the phone, or restore its Pro under Settings › Plan",type:"pro_required"}})),n.end();const a={};for(const[s,d]of Object.entries(t.headers||{}))s.toLowerCase()!==H&&s.toLowerCase()!==z&&(a[s]=d);const c=t.method==="GET"?void 0:await t.body.bytes(),r=await m({method:t.method,path:t.path,headers:a,body:c,device:e.room}),o={};if(r.headers?.forEach?.((s,d)=>{o[d]=s}),await n.head(r.status,o),r.body){let s=[],d=0,S=u();const T=async()=>{if(!d)return;const k=new Uint8Array(d);let w=0;for(const v of s)k.set(v,w),w+=v.length;s=[],d=0,S=u(),await n.write(k)},E=/event-stream/.test(String(r.headers?.get?.("content-type")||""));for await(const k of r.body){if(n.cancelled)break;let w=k instanceof Uint8Array?k:new TextEncoder().encode(String(k));if(E){const v=new TextDecoder().decode(w);if(v.includes(": ping")){const F=v.replace(ke,"$1");if(!F)continue;w=new TextEncoder().encode(F)}}s.push(w),d+=w.length,(d>=ye||u()-S>=he)&&await T()}await T()}return n.end()}async function N(e){const t=h.get(e.room)||{attempts:0,stopped:!1,online:!1};if(h.set(e.room,t),t.stopped)return;const n=await b(),a=e.pending&&e.pending.expiresAt>u()?e.pending:null;if(!e.phoneKey&&!a){O(e.room,"the pairing code expired");return}const c=`${f.replace(/^http/,"ws")}/v1/room/${e.room}`;let r;try{r=new Q(c,["chatpanel-link.v1",e.token])}catch(o){D(e,o?.message);return}r.binaryType="arraybuffer",t.ws=r,t.endpoint=se({side:"laptop",keyPair:n,crypto:_,psk:e.phoneKey?null:I(a.psk),peerKey:e.phoneKey?I(e.phoneKey):null,sendBytes:o=>{try{r.send(o)}catch{}},onRequest:(o,s)=>Z(e,o,s),onSession:(o,s)=>{t.online=!0,t.attempts=0,e.lastSeen=u(),s.paired&&(e.phoneKey=$(s.peerKey),e.name=s.name||e.name||"Phone",e.pairedAt=u(),e.pending=null,x(`link: paired ${e.name}`)),P()},onEnd:()=>{t.online=!1}}),r.onopen=()=>{if(t.stopped||h.get(e.room)!==t){try{r.close(1e3,"stopped")}catch{}return}clearInterval(t.keepalive),t.keepalive=setInterval(()=>{try{r.send("ping")}catch{}},fe),t.keepalive.unref?.()},r.onmessage=o=>typeof o.data=="string"?t.endpoint.onText(o.data):t.endpoint.onBinary(new Uint8Array(o.data)),r.onclose=o=>{if(clearInterval(t.keepalive),t.online=!1,t.endpoint?.close("socket closed"),!t.stopped){if(o?.code===4003||o?.code===4004){C(e.room,"the relay removed the room");return}D(e,o?.code===4001?"replaced":o?.code===4008?"over the relay's budget":`closed ${o?.code||""}`,o?.code===4001?5:o?.code===4008?ge:null)}},r.onerror=()=>{}}function D(e,t,n=null){const a=h.get(e.room);if(!a||a.stopped)return;const c=n??Math.min(a.attempts,R.length-1);a.attempts++,clearTimeout(a.timer),a.timer=setTimeout(()=>N(e),R[c]),a.timer.unref?.(),x(`link: ${t}; again in ${R[c]/1e3}s`)}function M(e){const t=h.get(e);if(t){t.stopped=!0,clearTimeout(t.timer),clearInterval(t.keepalive),t.endpoint?.close("stopped");try{t.ws?.close(1e3,"stopped")}catch{}h.delete(e)}}function O(e,t){const n=L(e);n&&!n.phoneKey&&K(e,"DELETE",n.token).catch(()=>{}),C(e,t)}function C(e,t){M(e),p.rooms=p.rooms.filter(n=>n.room!==e),P(),x(`link: ${t}`)}return{async pair({name:e=i}={}){const t=await b(),n=U(16),a=U(32),c=$(n),r=await j(a,n,"laptop"),o=await j(a,n,"phone"),s=await K(c,"PUT",r,{laptop:await J(r),phone:await J(o)});if(s.status!==200&&s.status!==201)throw new Error(`link: the relay refused the room (${s.status})`);for(const E of p.rooms.filter(k=>!k.phoneKey))O(E.room,"a new pairing code replaced this one");const d=u()+G,S={room:c,token:r,phoneKey:null,name:"",pairedAt:null,lastSeen:null,pending:{psk:$(a),expiresAt:d}};p.rooms.push(S),P();const T=ce({relay:f,room:n,key:t.publicKey,secret:a,name:String(e||"").slice(0,60)});return N(S),setTimeout(()=>{const E=L(c);E&&!E.phoneKey&&O(c,"the pairing code expired")},G+1e3).unref?.(),{uri:T,svg:le(T,{ecc:"M"}),expiresAt:d,room:c}},status(){return{relay:f,devices:p.rooms.filter(e=>e.phoneKey).map(e=>({id:e.room,name:e.name||"Phone",pairedAt:e.pairedAt,lastSeen:e.lastSeen,online:!!h.get(e.room)?.online})),pairing:p.rooms.filter(e=>!e.phoneKey&&e.pending?.expiresAt>u()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,connected:!!h.get(e.room)?.online}))[0]||null}},async remove(e){const t=L(e);if(!t)return!1;try{await K(e,"DELETE",t.token)}catch{}return C(e,"removed"),!0},async start(){if(p.rooms.length){await b();for(const e of p.rooms)N(e)}},stop(){for(const e of[...h.keys()])M(e)},get publicKey(){return g?.publicKey||null}}}export{we as COMPANION_PATHS,ue as DEFAULT_RELAY,H as ENTITLEMENT_HEADER,z as INSTALL_HEADER,G as PAIRING_TTL_MS,Ee as companionMay,Ne as createLinkHost,Te as defaultLinkPath,Se as phoneMayLink};
|
|
1
|
+
import{readFileSync as fe,writeFileSync as me,renameSync as ye,mkdirSync as he,chmodSync as ge}from"node:fs";import{dirname as ke,join as we}from"node:path";import X from"node:os";import{createLinkEndpoint as Se}from"@chatpanel/events/link-connect.js";import{noiseCrypto as Ee}from"@chatpanel/events/link-noise.js";import{pairingUri as Te,admissionToken as q,admissionVerifier as j,toB64url as O,fromB64url as J,coalesceChunks as ve}from"@chatpanel/events/link-protocol.js";import{linkPaths as ee,LINK_ROUTES as _e,LINK_TUNNEL_ROOM_PATH as be,tunnelSetup as $e}from"@chatpanel/events/link-routes.js";import{timingSafeEqual as Ae}from"node:crypto";import{acceptWebSocket as Ne,refuseUpgrade as H}from"./ws-accept.js";import{qrSvg as Le}from"@chatpanel/events/qr.js";import{verifyEntitlement as Pe,licenseFromPayload as xe,can as Ke,FEATURE_TIER as te}from"@chatpanel/events/entitlement.js";const qe="https://link.chatpanel.net",ne=10*6e4,Oe=3e4,G=[1e3,2e3,5e3,1e4,3e4,6e4],Re=30,R="chatpanel-link.v1",Ue=/(^|\n): ?ping\n\n/g,Ie=4,Ce=[/^\/v1\/models(?:\/|$|\?)/,/^\/v1\/chat\/completions$/,/^\/v1\/messages$/,/^\/v1\/audio\/(?:transcriptions|speech)$/,/^\/v1\/history\/(?:search|smart-search|get|list|related|status)(?:$|\?)/,/^\/v1\/history\/(?:records|stream)(?:$|\?)/,/^\/v1\/memory\/(?:recall|list|remember)(?:$|\?)/,/^\/v1\/(?:research|search|read|rerank|decide|capabilities|fusions)(?:$|\?)/,/^\/v1\/status$/,/^\/v1\/link\/routes$/,/^\/v1\/agent-sessions(?:\/read|\/adopt|\/catchup)?$/],Me=u=>Ce.some(p=>p.test(String(u||""))),oe="x-chatpanel-entitlement",re="x-chatpanel-install",ae=(u,p)=>{for(const[h,v]of Object.entries(u||{}))if(h.toLowerCase()===p)return String(v||"");return""};async function Be(u,{now:p=Date.now()}={}){if(!te.link||te.link==="free")return!1;const h=ae(u,oe),v=ae(u,re);if(!h||!v)return!1;const N=await Pe(h,v,{now:p});return!!N&&Ke(xe(N,{at:p}),"link",0,p)}function De(){return we(X.homedir(),".chatpanel","link.json")}function Fe(u){try{const p=JSON.parse(fe(u,"utf8"));return{v:1,key:p.key||null,rooms:Array.isArray(p.rooms)?p.rooms:[]}}catch{return{v:1,key:null,rooms:[]}}}function se(u,p){he(ke(u),{recursive:!0});const h=`${u}.tmp`;me(h,JSON.stringify(p,null,2),{mode:384});try{ge(h,384)}catch{}ye(h,u)}function et({settings:u={},relay:p=null,port:h=4320,name:v=X.hostname(),dispatch:N,path:U=De(),fetch:ie=globalThis.fetch,WebSocket:ce=globalThis.WebSocket,now:g=()=>Date.now(),random:z=w=>globalThis.crypto.getRandomValues(new Uint8Array(w)),crypto:I=Ee(),log:L=()=>{},mayLink:le=Be}={}){const w=p?new URL(p).origin:null;if(w&&!/^https:/.test(w)&&!/^http:\/\/127\.0\.0\.1(?::\d+)?$/.test(w))throw new Error("link: the relay must be https");const W=t=>{const e=ee(t);return w&&e.relay?{...e,relay:w}:e};let c=W(u);c.problem&&L(`link: ${c.problem} — using ChatPanel Link`);let l=Fe(U);const pe=w||ee({relayUrl:u?.relayUrl}).relay;for(const t of l.rooms)t.relay===void 0&&(t.relay=pe);const y=new Map,S=new Map;let E=null;async function b(){return E||(l.key?E=await I.keyPairFromPrivate(J(l.key)):(E=await I.generateKeyPair(),l.key=O(E.raw),se(U,l)),E)}const $=t=>l.rooms.find(e=>e.room===t)||null,C=()=>se(U,l),A=t=>!!t.relay&&t.relay===c.relay,M=async(t,e,n,o,s)=>{try{return await ie(`${s}/v1/room/${t}`,{method:e,headers:{authorization:`Bearer ${n}`,...o?{"content-type":"application/json"}:{}},body:o?JSON.stringify(o):void 0})}catch(r){const a=r?.cause?.code||"",f=a==="ENOTFOUND"?"this computer cannot look up its name (a VPN or DNS that does not know it yet)":a?`${a}`:r?.message||"no answer";throw new Error(`cannot reach the Link relay at ${new URL(s).host}: ${f}`)}};async function ue(t,e,n){if(t.lastSeen=g(),!Me(e.path))return await n.head(403,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:"link: a paired phone may not call this",type:"forbidden"}})),n.end();if(!await le(e.headers,{now:g()}))return await n.head(402,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:"ChatPanel Link needs Pro on this phone — upgrade on the phone, or restore its Pro under Settings › Plan",type:"pro_required"}})),n.end();if(e.path==="/v1/link/routes")return await n.head(200,{"content-type":"application/json"}),await n.write(JSON.stringify({route:c.route,relay:A(t)?t.relay:null,gw:c.tunnel})),n.end();const o={};for(const[d,m]of Object.entries(e.headers||{}))d.toLowerCase()!==oe&&d.toLowerCase()!==re&&(o[d]=m);const s=e.method==="GET"?void 0:await e.body.bytes(),r=await N({method:e.method,path:e.path,headers:o,body:s,device:t.room}),a={};r.headers?.forEach?.((d,m)=>{a[m]=d});let f=!1;try{await n.head(r.status,a)}catch{f=!0}if(r.body){const d=/event-stream/.test(String(r.headers?.get?.("content-type")||""));for await(const m of ve(de(r.body,d))){if(n.cancelled)break;if(!f)try{await n.write(m)}catch{f=!0}}}if(!f)return n.end()}async function*de(t,e){for await(const n of t){let o=n instanceof Uint8Array?n:new TextEncoder().encode(String(n));if(e){const s=new TextDecoder().decode(o);if(s.includes(": ping")){const r=s.replace(Ue,"$1");if(!r)continue;o=new TextEncoder().encode(r)}}yield o}}function Y(t,e,n,o,s){return Se({side:"laptop",keyPair:e,crypto:I,psk:t.phoneKey?null:J(n.psk),peerKey:t.phoneKey?J(t.phoneKey):null,sendBytes:s,onRequest:(r,a)=>ue(t,r,a),onSession:(r,a)=>{o.online=!0,o.attempts=0,t.lastSeen=g(),a.paired&&(t.phoneKey=O(a.peerKey),t.name=a.name||t.name||"Phone",t.pairedAt=g(),t.pending=null,L(`link: paired ${t.name}`)),C()},onEnd:()=>{o.online=!1}})}async function P(t){if(!A(t))return;const e=y.get(t.room)||{attempts:0,stopped:!1,online:!1};if(y.set(t.room,e),e.stopped)return;const n=await b(),o=t.pending&&t.pending.expiresAt>g()?t.pending:null;if(!t.phoneKey&&!o){D(t.room,"the pairing code expired");return}const s=`${t.relay.replace(/^http/,"ws")}/v1/room/${t.room}`;let r;try{r=new ce(s,[R,t.token])}catch(a){Z(t,a?.message);return}r.binaryType="arraybuffer",e.ws=r,e.endpoint=Y(t,n,o,e,a=>{try{r.send(a)}catch{}}),r.onopen=()=>{if(e.stopped||y.get(t.room)!==e){try{r.close(1e3,"stopped")}catch{}return}clearInterval(e.keepalive),e.keepalive=setInterval(()=>{try{r.send("ping")}catch{}},Oe),e.keepalive.unref?.()},r.onmessage=a=>typeof a.data=="string"?e.endpoint.onText(a.data):e.endpoint.onBinary(new Uint8Array(a.data)),r.onclose=a=>{if(clearInterval(e.keepalive),e.online=!1,e.endpoint?.close("socket closed"),!e.stopped){if(a?.code===4003||a?.code===4004){F(t.room,"the relay removed the room");return}Z(t,a?.code===4001?"replaced":a?.code===4008?"over the relay's budget":`closed ${a?.code||""}`,a?.code===4001?5:a?.code===4008?Ie:null)}},r.onerror=()=>{}}function Z(t,e,n=null){const o=y.get(t.room);if(!o||o.stopped)return;const s=n??Math.min(o.attempts,G.length-1);o.attempts++,clearTimeout(o.timer),o.timer=setTimeout(()=>P(t),G[s]),o.timer.unref?.(),L(`link: ${e}; again in ${G[s]/1e3}s`)}function B(t){const e=y.get(t);if(e){e.stopped=!0,clearTimeout(e.timer),clearInterval(e.keepalive),e.endpoint?.close("stopped");try{e.ws?.close(1e3,"stopped")}catch{}y.delete(t)}}function x(t,e=1e3,n="stopped"){const o=S.get(t);if(o?.ws){o.endpoint?.close(n);try{o.ws.close(e,n)}catch{}o.ws=null,o.endpoint=null,o.online=!1}}function D(t,e){const n=$(t);n&&!n.phoneKey&&n.relay&&M(t,"DELETE",n.token,null,n.relay).catch(()=>{}),F(t,e)}function F(t,e){B(t),x(t,4004,"room removed"),S.delete(t),l.rooms=l.rooms.filter(n=>n.room!==t),C(),L(`link: ${e}`)}return{async pair({name:t=v}={}){const e=await b(),n=z(16),o=z(32),s=O(n),r=await q(o,n,"laptop"),a=await q(o,n,"phone"),f=await j(a);if(c.relay){const i=await M(s,"PUT",r,{laptop:await j(r),phone:f},c.relay);if(i.status!==200&&i.status!==201)throw new Error(`link: the relay refused the room (${i.status})`)}for(const i of l.rooms.filter(V=>!V.phoneKey))D(i.room,"a new pairing code replaced this one");const d=g()+ne,m={room:s,token:r,relay:c.relay,phoneVerifier:f,phoneKey:null,name:"",pairedAt:null,lastSeen:null,pending:{psk:O(o),expiresAt:d}};l.rooms.push(m),C();const _=Te({relay:c.relay,gw:c.tunnel,room:n,key:e.publicKey,secret:o,name:String(t||"").slice(0,60)});return P(m),setTimeout(()=>{const i=$(s);i&&!i.phoneKey&&D(s,"the pairing code expired")},ne+1e3).unref?.(),{uri:_,svg:Le(_,{ecc:"M"}),expiresAt:d,room:s}},status(){const t=e=>!!y.get(e.room)?.online||!!S.get(e.room)?.online;return{route:c.route,relay:c.relay,tunnel:c.tunnel,...c.problem?{problem:c.problem}:{},routes:_e,setup:$e(c.route,{port:h,url:c.tunnel||""}),devices:l.rooms.filter(e=>e.phoneKey).map(e=>({id:e.room,name:e.name||"Phone",pairedAt:e.pairedAt,lastSeen:e.lastSeen,online:t(e),via:S.get(e.room)?.online?"tunnel":y.get(e.room)?.online?"relay":null,...e.relay&&!A(e)?{staleRelay:e.relay}:{},...c.tunnel&&!e.phoneVerifier?{tunnelNeedsRelink:!0}:{}})),pairing:l.rooms.filter(e=>!e.phoneKey&&e.pending?.expiresAt>g()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,connected:t(e)}))[0]||null}},async applySettings(t={}){c=W(t);for(const e of[...y.keys()]){const n=$(e);(!n||!A(n))&&B(e)}if(!c.tunnel)for(const e of[...S.keys()])x(e,1001,"the tunnel was switched off");l.rooms.length&&await b();for(const e of l.rooms)A(e)&&!y.has(e.room)&&P(e);return this.status()},async acceptTunnel(t,e,n){const o=decodeURIComponent(String(t.url||"").split("?")[0].slice(be.length));if(!c.tunnel)return H(e,404,"not found");const s=$(o),r=String(t.headers["sec-websocket-protocol"]||"").split(",").map(k=>k.trim()).filter(Boolean),f=/^Bearer ([A-Za-z0-9_-]+)$/.exec(String(t.headers.authorization||""))?.[1]||(r.length===2&&r.includes(R)?r.find(k=>k!==R):null),d=s&&!s.phoneKey&&s.pending?.expiresAt>g()?s.pending:null,m=f?Buffer.from(await j(f)):null,_=s?.phoneVerifier?Buffer.from(s.phoneVerifier):null;if(!s||!s.phoneKey&&!d||!m||!_||m.length!==_.length||!Ae(m,_))return H(e,403,"not admitted");const i=S.get(o)||{connects:[]};if(S.set(o,i),i.connects=i.connects.filter(k=>g()-k<6e4),i.connects.length>=Re)return H(e,429,"too many connects");i.connects.push(g());const V=await b(),T=Ne(t,e,n,{protocol:R});if(!T)return;x(o,4001,"replaced"),i.ws=T,i.online=!1;const K=Y(s,V,d,i,k=>{try{T.send(k)}catch{}});i.endpoint=K,T.onmessage=k=>{typeof k.data!="string"&&K.onBinary(new Uint8Array(k.data))},T.onclose=()=>{K.close("socket closed"),i.ws===T&&(i.ws=null,i.endpoint=null,i.online=!1)};const Q=JSON.stringify({t:"peer",up:!0});K.onText(Q),T.send(Q)},async remove(t){const e=$(t);if(!e)return!1;if(e.relay)try{await M(t,"DELETE",e.token,null,e.relay)}catch{}return F(t,"removed"),!0},async start(){if(l.rooms.length){await b();for(const t of l.rooms)P(t)}},stop(){for(const t of[...y.keys()])B(t);for(const t of[...S.keys()])x(t,1001,"going away")},get publicKey(){return E?.publicKey||null}}}export{Ce as COMPANION_PATHS,qe as DEFAULT_RELAY,oe as ENTITLEMENT_HEADER,re as INSTALL_HEADER,ne as PAIRING_TTL_MS,Me as companionMay,et as createLinkHost,De as defaultLinkPath,Be as phoneMayLink};
|
|
@@ -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};
|