@chatpanel/gateway 0.121.5 → 0.133.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/native/darwin-arm64/chatpanel-apple-model +0 -0
- package/package.json +2 -2
- package/src/capabilities.js +1 -1
- package/src/capability-config.js +1 -0
- package/src/capability-proxy.js +1 -1
- package/src/configstore.js +1 -1
- package/src/egress.js +2 -2
- package/src/engine-tunings.js +1 -1
- package/src/gguf-meta.js +1 -0
- package/src/inference-engines.js +1 -1
- package/src/kb.js +2 -2
- package/src/llama-arch.js +1 -0
- package/src/llama-builds.js +1 -0
- package/src/model-pull.js +1 -1
- package/src/providers.js +1 -1
- package/src/router.js +1 -1
- package/src/runtime.js +6 -6
- package/src/server.js +22 -22
- package/src/transfer-rate.js +1 -0
- package/src/tts-remote.js +1 -1
- package/src/version.js +1 -1
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.133.3",
|
|
4
4
|
"description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
26
26
|
"@chatpanel/bridge": "^0.49.0",
|
|
27
|
-
"@chatpanel/events": "^0.
|
|
27
|
+
"@chatpanel/events": "^0.425.2",
|
|
28
28
|
"@chatpanel/pii": "^0.15.6",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
package/src/capabilities.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as r from"./ner-engine.js";import*as
|
|
1
|
+
import*as r from"./ner-engine.js";import*as k from"./stt-engine.js";import*as q 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 D}from"./stt-models.js";import{TTS_MODEL_CATALOG as I,resolveDefaultModel as R}from"./tts-models.js";import{rawOrtAvailable as B}from"./ort.js";import{providerOf as U,providerTable as $,providersOf as j}from"./providers.js";import{CAPABILITIES as G,CAPABILITY_ROUTES as u,overBudget as F,validateDetectRequest as P}from"./capability-endpoints.js";import{extractCapabilityEntry as z}from"./extract/handler.js";const T=t=>[...new Set(t.filter(Boolean))];function E(t,c={}){return{state:t.state||"off",name:t.runtime||null,dtype:t.dtype||null,error:t.error||null,...c}}function W(t,{version:c="",reader:n=null,searcher:s=null,extract:p=null,proxy:f=null}={}){const l=r.health(),i=t?.redaction?.detection,o=!!(i&&i.backend&&i.backend!=="off"),m=l.model||t?.ner?.model||S,y=k.health(),b=q.health(),w=b.model||t?.tts?.model||R(B()),d=[{id:"detect",route:u.detect,models:T([m,...M.map(e=>e.id)]),default:m,union:l.companions?.filter(e=>e.state==="ready").map(e=>e.model)||[],labels:r.isReady()?r.labels():[],maxTokens:r.isReady()?r.maxTokens():null,requirements:{egress:"none",deterministic:!0},stats:l.stats||{calls:0},runtime:o?{state:"external",name:i.backend,url:i.url||null}:E(l,{installed:r.modelOnDisk(m)})},{id:"stt",route:u.stt,streaming:"/stt/sessions",models:T([y.model||t?.stt?.model||D,...C.map(e=>e.id)]),default:y.model||t?.stt?.model||D,requirements:{egress:"none"},runtime:E(y)},{id:"tts",route:u.tts,voices:"/tts/voices",models:T([w,...I.map(e=>e.id)]),default:w,requirements:{egress:"none"},runtime:E(b)}],_=t?.read||{},A=!!_.remote?.url;d.push({id:"read",route:u.read,providers:n?n.providers():["defuddle","text",...A?["remote"]:[]],default:_.provider||"defuddle",requirements:{egress:"web"},stats:n?n.stats():{calls:0},runtime:{state:"ready",cache:n?n.cache.size():0,remote:A?"configured":"off"}});const v=t?.search||{},h=!!v.searxng?.url,L=s?.searxng?s.searxng.state():h?"unknown":"off";if(d.push({id:"search",route:u.search,providers:s?s.providers():["serp",...h?["searxng"]:[]],default:v.provider==="searxng"||v.provider==="serp"?v.provider:h?"searxng":"serp",requirements:{egress:"web"},stats:s?s.stats()[h?"searxng":"serp"]||{calls:0}:{calls:0},runtime:{state:"ready",searxng:L,...h?{searxngUrl:v.searxng.url}:{}}}),p)try{d.push(z(p))}catch{}if(f)for(const e of f.capabilities){const a=f.entry(e);a&&d.push(a)}d.push({id:"chat",route:u.chat,models:[],dialects:["/v1/chat/completions","/v1/messages","/v1/responses"],listing:"/v1/models"});const x={sttModel:y.model,ttsModel:b.model,nerModel:m};for(const e of d){const a=U(t,e.id,x),{token:g,...O}=a;e.provider=O,a.kind==="remote"&&(e.requirements={...e.requirements||{},egress:a.egress})}return{capabilities:d,server:{name:"chatpanel-gateway",version:String(c),audit:"/audit"},providers:Object.fromEntries(Object.entries($(t,x)).map(([e,{token:a,...g}])=>[e,g])),providerLists:Object.fromEntries(G.map(e=>{const a=j(t,e,x);return[e,{mode:a.mode,providers:a.providers.map(({token:g,...O})=>({...O,hasToken:!!g}))}]}))}}async function X(t,{ensure:c=async()=>r.state(),model:n=null}={}){let s;try{s=P(t)}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=F(r.stats(),s.text.length,s.budgetMs);if(p)return{status:503,body:{...p,model:r.health().model}};const f=performance.now();let l=await r.detectSpans(s.text,{strict:!!s.strict});if(s.labels){const o=new Set(s.labels);l=l.filter(m=>o.has(m.type))}const i=r.health();return{status:200,body:{entities:l,model:i.model,ms:Math.round(performance.now()-f),runtime:{name:i.runtime||null,dtype:i.dtype||null}}}}export{W as capabilitiesDocument,X as handleDetect};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export*from"@chatpanel/events/capability-config.js";
|
package/src/capability-proxy.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{secureFetch as
|
|
1
|
+
import{secureFetch as N}from"./secure-fetch.js";import{primaryProvider as z,capabilityList as J}from"./capability-config.js";import{createReadStats as G}from"./retrieval/read.js";import{CAPABILITY_ROUTES as j,overBudget as D,validateRerankRequest as H,validateRerankResponse as U,validateDecideRequest as V,validateDecideResponse as W,validateEmbedRequest as X,validateEmbedResponse as Y}from"./capability-endpoints.js";import{adaptRequest as K,adaptResponse as Q}from"./capability-adapters.js";import{defaultEmbeddedModel as S}from"./embedded-models.js";const M=Object.freeze(["rerank","decide","embed"]),x={rerank:{request:H,response:U,chars:m=>m.query.length+m.documents.reduce((h,c)=>h+c.length,0)},decide:{request:V,response:W,chars:m=>m.state.length},embed:{request:X,response:Y,chars:m=>m.input.reduce((h,c)=>h+c.length,0)}},Z=18e4,ee=6e4,i=(m,h,c,y={})=>({status:m,body:{error:{type:h,message:c,...y}}});function le({cfg:m,fetchImpl:h=N,now:c=()=>Date.now(),wake:y=null,embedded:g=null,asleep:A=null}={}){const q=Object.fromEntries(M.map(e=>[e,{stats:G(),last:null,error:null}])),R=e=>z(m.capabilities?.[e],e),w=e=>{const t=R(e);return t&&t.provider!=="embedded"&&t.provider!=="none"&&typeof t.url=="string"&&/^https?:\/\//.test(t.url)&&typeof t.adapter=="string"?t:null},E=e=>{if(!g||w(e))return null;const t=R(e);if(t?.provider==="none")return null;const n=t?.provider==="embedded"&&typeof t.model=="string"&&t.model?t.model:S(e);return n?{model:n}:null},L=e=>{if(!g||R(e)?.provider==="none")return null;const t=S(e);return t?{model:t}:null};async function $(e,t,n){const d=x[e];let s;try{s=d.request(n)}catch(u){return i(400,"invalid_request",u.message)}if(s.model&&s.model!==t.model)return i(404,"model_not_found",`${e}: model ${s.model} is not served here (${t.model} is)`);const a=q[e],v=d.chars(s),r=D(a.stats.stats(),v,s.budgetMs);if(r)return{status:503,body:r};const o=c();let f;try{f={...await g.call(e,s,t.model),model:t.model}}catch(u){return u.code==="WARMING"?i(503,"provider_warming",u.message,u.progress?{progress:u.progress}:{}):i(503,"provider_unavailable",`${e}: the in-process model ${t.model} could not answer — ${u.message}`)}const _=c()-o;f={...f,ms:_,...e==="decide"?{calibrated:!1}:{}};try{d.response(f,s)}catch(u){return i(502,"bad_shape",`${e}: the in-process answer did not fit the contract — ${u.message}`)}return a.stats.record(_,v),a.error=null,a.last=c(),{status:200,body:f}}async function B(e,t){if(!M.includes(e))return i(404,"unknown_capability",`no such capability ${e}`);let n=J(m.capabilities?.[e],e).providers;if(!n.length||n[0]?.provider==="none"||!w(e)&&n[0]?.provider!=="embedded"){const r=w(e);if(r)return T(e,r,t);const o=E(e);return o?$(e,o,t):i(404,"no_provider",`no ${e} provider — it is turned off (capabilities.${e}.provider = none): turn it on under Settings › Runtime, or point capabilities.${e}.url at a server that provides it`)}let d;try{d=x[e].request(t)}catch(r){return i(400,"invalid_request",r.message)}const s=r=>r.provider==="embedded"?typeof r.model=="string"&&r.model?r.model:S(e):r.model||null;if(d.model){const r=n.filter(o=>!s(o)||s(o)===d.model);r.length?n=r:n=n.slice(0,1)}if(e==="embed"){const r=s(n[0]);n=n.filter(o=>s(o)===r)}if(d.wake===!1){const r=g?n.find(f=>f.provider==="embedded"):null;if(r)return $(e,{model:s(r)},t);const o=L(e);if(o)return $(e,o,t)}const a=[];let v=null;for(const r of n){if(r.provider==="none")break;let o;if(r.provider==="embedded"){if(!g)continue;o=await $(e,{model:s(r)},t)}else{if(!(typeof r.url=="string"&&/^https?:\/\//.test(r.url)&&typeof r.adapter=="string"))continue;o=await T(e,r,t)}if(o.status===200)return a.length?{status:200,body:{...o.body,fellBackFrom:a}}:o;if(o.status===400||o.status===404)return o;a.push(r.service||r.id||(r.provider==="embedded"?"in-process":r.url)),v=o}return v||i(404,"no_provider",`no ${e} provider answers here`)}async function T(e,t,n){const d=x[e];let s;try{s=d.request(n)}catch(l){return i(400,"invalid_request",l.message)}if(s.model&&t.model&&s.model!==t.model)return i(404,"model_not_found",`${e}: model ${s.model} is not served here (${t.model} is)`);const a=q[e],v=d.chars(s),r=D(a.stats.stats(),v,s.budgetMs);if(r)return{status:503,body:r};let o;try{o=K(t.adapter,{...s,model:s.model||t.model||void 0})}catch(l){return i(500,"bad_adapter",l.message)}const f=`${t.url.replace(/\/+$/,"")}${o.route}`,_=()=>h(f,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",...t.token?{authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify(o.body),signal:AbortSignal.timeout(s.budgetMs?Math.max(s.budgetMs*2,5e3):a.stats.stats().calls?ee:Z)});if(s.wake===!1){const l=L(e);if(l)return $(e,l,n);if(t.service&&typeof A=="function"&&A(t.service))return i(503,"provider_asleep",`${e}: the ${t.service} container is asleep and this call does not wake it — carry on without it`)}const u=!!(t.service&&typeof y=="function");if(u){const l=await y(t.service).catch(O=>({ok:!1,error:O.message}));if(!l?.ok)return a.error=l?.error||"could not start",a.last=c(),i(503,"provider_unavailable",`${e}: the ${t.service} container could not be started — ${a.error}`)}const F=c();let b;try{b=await _()}catch(l){const O=u?await y(t.service,{force:!0}).catch(()=>null):null;try{if(!O?.ok)throw l;b=await _()}catch(P){return a.error=P.message,a.last=c(),i(503,"provider_unavailable",`${e}: ${t.service?`the ${t.service} container`:t.url} did not answer — ${P.message}`)}}let p;try{p=await b.json()}catch{p=null}if(!b.ok)return a.error=`HTTP ${b.status}`,a.last=c(),i(502,"provider_error",`${e}: the provider answered ${b.status}${p?.detail?` — ${typeof p.detail=="string"?p.detail:JSON.stringify(p.detail)}`:p?.error?` — ${typeof p.error=="string"?p.error:p.error.message||""}`:""}`);const I=c()-F;let k;try{const l=Q(t.adapter,p,s);k={...l,model:t.model||l.model||t.adapter,...l.model&&t.model&&l.model!==t.model?{providerModel:l.model}:{},ms:I,...e==="decide"?{calibrated:t.calibrated===!0}:{}},d.response(k,s)}catch(l){return a.error=l.message,a.last=c(),i(502,"bad_shape",`${e}: the provider's answer did not fit the contract — ${l.message}`)}return a.stats.record(I,v),a.error=null,a.last=c(),{status:200,body:k}}function C(e){const t=w(e),n=q[e],d=n.stats.stats();if(!t){const s=E(e);if(!s)return null;const a=g.health(e,s.model);return{id:e,route:j[e],models:[s.model],default:s.model,requirements:{egress:"none"},...e==="decide"?{calibrated:!1}:{},stats:d,runtime:{...a,name:"embedded",model:s.model,threads:g.threads}}}return{id:e,route:j[e],models:t.model?[t.model]:[],...t.model?{default:t.model}:{},requirements:{egress:/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:|\/|$)/.test(t.url)?"none":"trusted"},...e==="decide"?{calibrated:t.calibrated===!0}:{},stats:d,runtime:{state:n.error?"down":d.calls?"ready":"idle",name:t.service?"container":"external",adapter:t.adapter,...t.service?{service:t.service}:{},url:t.url,...n.error?{error:n.error}:{}}}}return{call:B,entry:C,stats:e=>q[e]?.stats.stats()||{calls:0},capabilities:M}}export{le as createCapabilityProxy};
|
package/src/configstore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{patchApis as R,viewApis as L}from"./retrieval/search-apis.js";import{writeFileSync as P,mkdirSync as h,chmodSync as j}from"node:fs";import{join as C,dirname as H}from"node:path";import B from"node:os";import{usage as I}from"./freegate.js";import{applyFusionsPatch as $}from"./fusions.js";import{EMBEDDED_MODELS as M,EMBEDDED_IDS as g,isEmbeddedModel as X}from"./embedded-models.js";import{normalizeRegistries as G,REGISTRY_KINDS as q}from"@chatpanel/events/registries.js";import{assertEndpointUrl as c}from"@chatpanel/pii";import{normalizeGrant as w}from"@chatpanel/bridge/src/events/sandbox-policy.js";import{SANDBOX_READ_MODES as b,SANDBOX_RUNTIMES as E,parseWrapperTemplate as U}from"@chatpanel/events/sandbox-choice.js";import{sandboxUnderPolicy as D}from"@chatpanel/events/policy.js";const m=["open","allowlist","off"],O=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(o=>String(o).trim()).filter(o=>o&&o.length<1024&&!o.includes("\0")),l=e=>Object.assign(new Error(e),{code:"SHAPE"}),_=/^[A-Za-z0-9][\w.-]{0,63}$/,F=e=>!e.hosts.length&&!e.write.length&&!e.outside&&!e.signIn;function J(e,{strict:o=!1}={}){const r={};if(!e||typeof e!="object"||Array.isArray(e))return r;for(const[i,n]of Object.entries(e))if(n!=null)try{if(!_.test(i))throw l(`not an agent id: ${JSON.stringify(i)}`);const t=w(n);F(t)||(r[i]=t)}catch(t){if(o)throw l(`sandbox.agents.${i}: ${t.message}`)}return r}function u(e={},{strict:o=!1}={}){const r=e&&typeof e=="object"?e:{};if(o&&r.mode!==void 0&&!m.includes(r.mode))throw l(`sandbox.mode must be one of ${m.join(", ")} — got ${JSON.stringify(r.mode)}`);const i=m.includes(r.mode)?r.mode:"open";if(o&&r.reads!==void 0&&!b.includes(r.reads))throw l(`sandbox.reads must be one of ${b.join(", ")} — got ${JSON.stringify(r.reads)}`);const n=b.includes(r.reads)?r.reads:b[0];if(o&&r.required!==void 0&&typeof r.required!="boolean")throw l(`sandbox.required must be true or false — got ${JSON.stringify(r.required)}`);if(o&&r.required===!0&&r.mode==="off")throw l("the sandbox cannot be required while it is off — choose open or allowlist first");const t=r.required===!0&&i!=="off";if(o&&r.runtime!==void 0&&!E.includes(r.runtime))throw l(`sandbox.runtime must be one of ${E.join(", ")} — got ${JSON.stringify(r.runtime)}`);const s=E.includes(r.runtime)?r.runtime:"srt";let a="";if(r.command!==void 0&&String(Array.isArray(r.command)?r.command.join(""):r.command).trim())try{U(r.command),a=Array.isArray(r.command)?JSON.stringify(r.command):String(r.command).trim()}catch(v){if(o)throw l(`sandbox.command: ${v.message.replace(/^sandbox command: /,"")}`);a=""}const d=typeof r.image=="string"&&/^[A-Za-z0-9][A-Za-z0-9._/:@-]{0,254}$/.test(r.image.trim())?r.image.trim():"";if(o&&r.image!==void 0&&String(r.image).trim()&&!d)throw l("sandbox.image must be an image reference (registry/name:tag)");const A=["podman","docker"].includes(r.engine)?r.engine:"";if(o&&s==="command"&&!a)throw l("the sandbox command is empty — name your sandbox tool, with {cmd} where the command goes");if(o&&s==="container"&&!d)throw l("a container needs an image — name the image the agents run in");const{hosts:f}=w({hosts:r.hosts??[]}),x=J(r.agents,{strict:o});return{mode:i,reads:n,required:t,runtime:s,command:a,image:d,engine:A,hosts:f,write:O(r.write),denyRead:O(r.denyRead),...Object.keys(x).length?{agents:x}:{}}}const K=["off","0","false"],N=e=>String(e||"").split(",").map(o=>o.trim()).filter(Boolean),S=(...e)=>[...new Set(e.flat())];function p(e=process.env){const o=String(e.CHATPANEL_SANDBOX_READS??"").trim().toLowerCase();return b.includes(o)?o:""}function y(e=process.env){const o=String(e.CHATPANEL_SANDBOX??"").trim().toLowerCase();return o?K.includes(o)?{mode:"off"}:m.includes(o)?{mode:o}:{unknown:o}:{}}function ae(e,o=process.env){const r=[],i=e?.sandbox&&typeof e.sandbox=="object"?e.sandbox:{};i.mode!==void 0&&!m.includes(i.mode)&&r.push(`sandbox.mode ${JSON.stringify(i.mode)} in the config is not one of ${m.join(", ")} — the sandbox stays ON, in "open" mode`);for(const[d,A]of Object.entries(i.agents&&typeof i.agents=="object"?i.agents:{}))try{if(!_.test(d))throw new Error("not an agent id");w(A)}catch(f){r.push(`sandbox.agents.${d} in the config is not valid and is ignored — ${f.message}`)}const n=y(o),t=u(i).mode;n.unknown&&r.push(`CHATPANEL_SANDBOX="${n.unknown}" in this process's environment is not one of ${m.join(", ")} — ignored; the config's "${t}" applies`),n.mode&&n.mode!==t&&r.push(`the sandbox mode is "${n.mode}" — from CHATPANEL_SANDBOX in this process's environment, which wins over the config's "${t}"; Settings › Runtime cannot change it while that variable is set`);const s=p(o),a=u(i).reads;return s&&s!==a&&r.push(`what agents may read is "${s}" — from CHATPANEL_SANDBOX_READS in this process's environment, which wins over the config's "${a}"; Settings › Runtime cannot change it while that variable is set`),r}function de(e,o=process.env,r=null){const i=u(e?.sandbox),{sandbox:n}=D(i,r);Array.isArray(n.command)&&(n.command=JSON.stringify(n.command));const t=y(o);let s={};try{const d=JSON.parse(o.CHATPANEL_SANDBOX_AGENTS||"{}");d&&typeof d=="object"&&!Array.isArray(d)&&(s=d)}catch{}const a={...s,...n.agents||{}};return{CHATPANEL_SANDBOX:r?.sandbox?.mode||t.mode||n.mode,CHATPANEL_SANDBOX_RUNTIME:n.runtime,CHATPANEL_SANDBOX_COMMAND:n.command||"",CHATPANEL_SANDBOX_IMAGE:n.image||"",CHATPANEL_SANDBOX_ENGINE:n.engine||"",CHATPANEL_SANDBOX_READS:r?.sandbox?.reads||p(o)||n.reads,CHATPANEL_SANDBOX_REQUIRED:n.required==="policy"?"policy":String(o.CHATPANEL_SANDBOX_REQUIRED||"")||(n.required?"on":""),CHATPANEL_SANDBOX_ALLOW_HOSTS:S(n.hosts,N(o.CHATPANEL_SANDBOX_ALLOW_HOSTS)).join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:S(n.write,N(o.CHATPANEL_SANDBOX_ALLOW_WRITE)).join(","),CHATPANEL_SANDBOX_DENY_READ:S(n.denyRead,N(o.CHATPANEL_SANDBOX_DENY_READ)).join(","),...Object.keys(a).length?{CHATPANEL_SANDBOX_AGENTS:JSON.stringify(a)}:{}}}function k(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||C(B.homedir(),".chatpanel","gateway.config.json")}function le(e){const o=e?.registries||{},r={};for(const[i,n]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])o[i]&&(r[n]=o[i]);return r}function me(e,o=k()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&o===k({}))throw new Error(`refusing to persist the real gateway config (${o}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);h(H(o),{recursive:!0,mode:448});const r={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,tls:e.tls};P(o,JSON.stringify(r,null,2),{mode:384});try{j(o,384)}catch{}}function ue(e,{proUnlocked:o=!1,policy:r=null}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(i=>{const{apiKey:n,...t}=i;return{...t,hasKey:!!n}}),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,...n}=e.redaction?.detection||{backend:"off"};return n})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:(()=>{const{sandbox:i,locked:n}=D(u(e.sandbox),r);return Array.isArray(i.command)&&(i.command=JSON.stringify(i.command)),{...i,...y().mode?{envMode:y().mode}:{},...p()?{envReads:p()}:{},...n.length?{locked:n,lockedBy:r?.org?.name||"your organisation"}:{}}})(),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:L(e)},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([i,n])=>{const{token:t,...s}=n||{};return[i,{...s,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:o,hasToken:!!e.pro?.entitlementToken,free:I(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 be(e,o){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=o,e.ner.autostart=!0,e.ner}function W(e,o={}){if(!e||e.type!=="api")return!1;let r;try{r=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(r.hostname),n=Number(r.port)||(r.protocol==="https:"?443:80);return i&&n===(Number(o.port)||4320)}const T=["default","acceptEdits","bypassPermissions"];function pe(e,o={}){const r=e?.bridge||{};return{...T.includes(r.permissionMode)&&r.permissionMode!=="default"?{permissionMode:r.permissionMode}:{},...typeof r.workingDir=="string"&&r.workingDir.trim()?{workingDir:r.workingDir.trim()}:{},...o}}function ye(e,o={}){if((o.backend==="bridge"||o.backend==="api")&&(e.backend=o.backend),Array.isArray(o.destinations)){const r=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=o.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const n=W(i,e);return n&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!n}).map(i=>{const n={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(n.agent=i.agent||i.id),i.type==="api"){n.baseUrl=String(i.baseUrl||""),n.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:r.get(i.id)?.apiKey;s&&(n.apiKey=s)}const t=typeof i.service=="string"&&i.service?i.service:r.get(i.id)?.service;return t&&(n.service=t),n})}if(o.bridge&&typeof o.bridge=="object"&&(typeof o.bridge.url=="string"&&(e.bridge.url=o.bridge.url),typeof o.bridge.agent=="string"&&(e.bridge.agent=o.bridge.agent),T.includes(o.bridge.permissionMode)&&(e.bridge.permissionMode=o.bridge.permissionMode),typeof o.bridge.workingDir=="string"&&(e.bridge.workingDir=o.bridge.workingDir.trim().slice(0,1024)),typeof o.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=o.bridge.openAgentLane)),Array.isArray(o.allowedExtensionIds)&&(e.allowedExtensionIds=o.allowedExtensionIds.map(r=>String(r).trim()).filter(r=>/^[a-p]{32}$/.test(r))),o.upstreams&&typeof o.upstreams=="object")for(const r of["openai","anthropic"]){const i=o.upstreams[r];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[r]={...e.upstreams[r],baseUrl:i.baseUrl.trim()})}if(o.redaction&&typeof o.redaction=="object"){const r=o.redaction;(r.tier==="basic"||r.tier==="full")&&(e.redaction.tier=r.tier),"redactSystem"in r&&(e.redaction.redactSystem=!!r.redactSystem),Array.isArray(r.dictionary)&&(e.redaction.dictionary=r.dictionary),r.detection&&typeof r.detection=="object"&&(e.redaction.detection=r.detection)}if(Array.isArray(o.allowedOrigins)&&(e.allowedOrigins=o.allowedOrigins),o.sandbox&&typeof o.sandbox=="object"){const r=u(e.sandbox),i={...r,...o.sandbox};o.sandbox.agents&&typeof o.sandbox.agents=="object"&&!Array.isArray(o.sandbox.agents)&&(i.agents={...r.agents||{},...o.sandbox.agents}),e.sandbox=u(i,{strict:!0})}if(o.pro&&typeof o.pro=="object"&&typeof o.pro.entitlementToken=="string"&&(e.pro.entitlementToken=o.pro.entitlementToken),o.stt&&typeof o.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in o.stt&&(e.stt.enabled=!!o.stt.enabled),"allowDownload"in o.stt&&(e.stt.allowDownload=!!o.stt.allowDownload)),o.read&&typeof o.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},o.read.remote&&typeof o.read.remote=="object"){if("url"in o.read.remote){const r=String(o.read.remote.url||"").trim();r&&c(r),e.read.remote.url=r}typeof o.read.remote.key=="string"&&(e.read.remote.key=o.read.remote.key)}["defuddle","text","remote"].includes(o.read.provider)&&(e.read.provider=o.read.provider==="remote"&&!e.read.remote.url?e.read.provider:o.read.provider)}if(o.registries&&typeof o.registries=="object"){const r=G(o.registries),i={...e.registries||{}};for(const n of q)n in o.registries&&(r[n]?i[n]=r[n]:delete i[n]);e.registries=i}if(o.search&&typeof o.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 r=o.search.searxng;if(r&&typeof r=="object"){if("url"in r){const i=String(r.url||"").trim();i&&c(i),e.search.searxng.url=i}typeof r.token=="string"&&(e.search.searxng.token=r.token),typeof r.engines=="string"&&(e.search.searxng.engines=r.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(r.safesearch)&&(e.search.searxng.safesearch=r.safesearch)}"apis"in o.search&&(e.search.apis=R(e.search.apis,o.search.apis)),["auto","serp","searxng"].includes(o.search.provider)&&(e.search.provider=o.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:o.search.provider)}if("fusions"in o){const r=$(e,o.fusions);if(r){const i=new Error(r);throw i.code="SHAPE",i}}if(o.capabilities&&typeof o.capabilities=="object"){e.capabilities=e.capabilities||{};for(const r of["rerank","decide","stt","tts","detect","embed"]){if(!(r in o.capabilities))continue;const i=o.capabilities[r];if(i===null){delete e.capabilities[r],r==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!i||typeof i!="object")continue;const n=e.capabilities[r]||{},t={...n};if(i.provider==="embedded"){if(g.includes(r)&&i.model!=null){if(!X(r,i.model)){const s=new Error(`capabilities.${r}.model must be one of ${M[r].map(a=>a.id).join(", ")}`);throw s.code="SHAPE",s}e.capabilities[r]={provider:"embedded",model:i.model};continue}e.capabilities[r]={provider:"embedded"},r==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(i.provider==="none"&&g.includes(r)){e.capabilities[r]={provider:"none"};continue}if("url"in i){const s=String(i.url||"").trim();s&&c(s);const a=d=>{try{return new URL(d).origin}catch{return d}};n.url&&s&&a(n.url)!==a(s)&&typeof i.token!="string"&&delete t.token,t.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(t.adapter=i.adapter),typeof i.model=="string"&&(t.model=i.model.trim()),typeof i.token=="string"&&(t.token=i.token),typeof i.calibrated=="boolean"&&(t.calibrated=i.calibrated),typeof i.redact=="boolean"&&(t.redact=i.redact),!t.url){delete e.capabilities[r];continue}t.provider="remote",delete t.service,e.capabilities[r]=t,r==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:t.url,...t.token?{apiKey:t.token}:{}})}}if(typeof o.logRequests=="boolean"&&(e.logRequests=o.logRequests),["off","types","values"].includes(o.logDetail)&&(e.logDetail=o.logDetail),o.tools&&typeof o.tools=="object"){e.tools=e.tools||{},"autoNarrow"in o.tools&&(e.tools.autoNarrow=!!o.tools.autoNarrow),"narrowAll"in o.tools&&(e.tools.narrowAll=!!o.tools.narrowAll),(o.tools.toolData==="real"||o.tools.toolData==="redactRemote")&&(e.tools.toolData=o.tools.toolData);const r=Number(o.tools.maxPerTurn);Number.isFinite(r)&&r>=1&&(e.tools.maxPerTurn=Math.floor(r))}return e}export{T as PERMISSION_MODES,m as SANDBOX_MODES,ye as applyConfigPatch,be as applyNerModelSelection,pe as bridgeAgentOptions,k as configPath,W as isSelfDestination,u as normalizeSandboxConfig,me as persistConfig,ue as publicConfig,le as registryChildEnv,de as sandboxEnvFor,y as sandboxModeFromEnv,ae as sandboxProblems,p as sandboxReadsFromEnv};
|
|
1
|
+
import{patchApis as B,viewApis as I}from"./retrieval/search-apis.js";import{writeFileSync as $,mkdirSync as M,chmodSync as X}from"node:fs";import{join as G,dirname as U}from"node:path";import q from"node:os";import{usage as F}from"./freegate.js";import{applyFusionsPatch as J}from"./fusions.js";import{EMBEDDED_MODELS as K,EMBEDDED_IDS as O,isEmbeddedModel as W}from"./embedded-models.js";import{capabilityList as w,isProviderList as _,listProblems as Y,primaryProvider as z,storedShape as v}from"./capability-config.js";import{normalizeRegistries as Z,REGISTRY_KINDS as Q}from"@chatpanel/events/registries.js";import{assertEndpointUrl as x}from"@chatpanel/pii";import{normalizeGrant as N}from"@chatpanel/bridge/src/events/sandbox-policy.js";import{SANDBOX_READ_MODES as A,SANDBOX_RUNTIMES as S,parseWrapperTemplate as V}from"@chatpanel/events/sandbox-choice.js";import{sandboxUnderPolicy as k}from"@chatpanel/events/policy.js";const p=["open","allowlist","off"],T=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(o=>String(o).trim()).filter(o=>o&&o.length<1024&&!o.includes("\0")),m=e=>Object.assign(new Error(e),{code:"SHAPE"}),h=/^[A-Za-z0-9][\w.-]{0,63}$/,ee=e=>!e.hosts.length&&!e.write.length&&!e.outside&&!e.signIn;function re(e,{strict:o=!1}={}){const r={};if(!e||typeof e!="object"||Array.isArray(e))return r;for(const[i,n]of Object.entries(e))if(n!=null)try{if(!h.test(i))throw m(`not an agent id: ${JSON.stringify(i)}`);const t=N(n);ee(t)||(r[i]=t)}catch(t){if(o)throw m(`sandbox.agents.${i}: ${t.message}`)}return r}function y(e={},{strict:o=!1}={}){const r=e&&typeof e=="object"?e:{};if(o&&r.mode!==void 0&&!p.includes(r.mode))throw m(`sandbox.mode must be one of ${p.join(", ")} — got ${JSON.stringify(r.mode)}`);const i=p.includes(r.mode)?r.mode:"open";if(o&&r.reads!==void 0&&!A.includes(r.reads))throw m(`sandbox.reads must be one of ${A.join(", ")} — got ${JSON.stringify(r.reads)}`);const n=A.includes(r.reads)?r.reads:A[0];if(o&&r.required!==void 0&&typeof r.required!="boolean")throw m(`sandbox.required must be true or false — got ${JSON.stringify(r.required)}`);if(o&&r.required===!0&&r.mode==="off")throw m("the sandbox cannot be required while it is off — choose open or allowlist first");const t=r.required===!0&&i!=="off";if(o&&r.runtime!==void 0&&!S.includes(r.runtime))throw m(`sandbox.runtime must be one of ${S.join(", ")} — got ${JSON.stringify(r.runtime)}`);const s=S.includes(r.runtime)?r.runtime:"srt";let d="";if(r.command!==void 0&&String(Array.isArray(r.command)?r.command.join(""):r.command).trim())try{V(r.command),d=Array.isArray(r.command)?JSON.stringify(r.command):String(r.command).trim()}catch(l){if(o)throw m(`sandbox.command: ${l.message.replace(/^sandbox command: /,"")}`);d=""}const a=typeof r.image=="string"&&/^[A-Za-z0-9][A-Za-z0-9._/:@-]{0,254}$/.test(r.image.trim())?r.image.trim():"";if(o&&r.image!==void 0&&String(r.image).trim()&&!a)throw m("sandbox.image must be an image reference (registry/name:tag)");const u=["podman","docker"].includes(r.engine)?r.engine:"";if(o&&s==="command"&&!d)throw m("the sandbox command is empty — name your sandbox tool, with {cmd} where the command goes");if(o&&s==="container"&&!a)throw m("a container needs an image — name the image the agents run in");const{hosts:f}=N({hosts:r.hosts??[]}),b=re(r.agents,{strict:o});return{mode:i,reads:n,required:t,runtime:s,command:d,image:a,engine:u,hosts:f,write:T(r.write),denyRead:T(r.denyRead),...Object.keys(b).length?{agents:b}:{}}}const oe=["off","0","false"],g=e=>String(e||"").split(",").map(o=>o.trim()).filter(Boolean),D=(...e)=>[...new Set(e.flat())];function c(e=process.env){const o=String(e.CHATPANEL_SANDBOX_READS??"").trim().toLowerCase();return A.includes(o)?o:""}function E(e=process.env){const o=String(e.CHATPANEL_SANDBOX??"").trim().toLowerCase();return o?oe.includes(o)?{mode:"off"}:p.includes(o)?{mode:o}:{unknown:o}:{}}function ce(e,o=process.env){const r=[],i=e?.sandbox&&typeof e.sandbox=="object"?e.sandbox:{};i.mode!==void 0&&!p.includes(i.mode)&&r.push(`sandbox.mode ${JSON.stringify(i.mode)} in the config is not one of ${p.join(", ")} — the sandbox stays ON, in "open" mode`);for(const[a,u]of Object.entries(i.agents&&typeof i.agents=="object"?i.agents:{}))try{if(!h.test(a))throw new Error("not an agent id");N(u)}catch(f){r.push(`sandbox.agents.${a} in the config is not valid and is ignored — ${f.message}`)}const n=E(o),t=y(i).mode;n.unknown&&r.push(`CHATPANEL_SANDBOX="${n.unknown}" in this process's environment is not one of ${p.join(", ")} — ignored; the config's "${t}" applies`),n.mode&&n.mode!==t&&r.push(`the sandbox mode is "${n.mode}" — from CHATPANEL_SANDBOX in this process's environment, which wins over the config's "${t}"; Settings › Runtime cannot change it while that variable is set`);const s=c(o),d=y(i).reads;return s&&s!==d&&r.push(`what agents may read is "${s}" — from CHATPANEL_SANDBOX_READS in this process's environment, which wins over the config's "${d}"; Settings › Runtime cannot change it while that variable is set`),r}function Ee(e,o=process.env,r=null){const i=y(e?.sandbox),{sandbox:n}=k(i,r);Array.isArray(n.command)&&(n.command=JSON.stringify(n.command));const t=E(o);let s={};try{const a=JSON.parse(o.CHATPANEL_SANDBOX_AGENTS||"{}");a&&typeof a=="object"&&!Array.isArray(a)&&(s=a)}catch{}const d={...s,...n.agents||{}};return{CHATPANEL_SANDBOX:r?.sandbox?.mode||t.mode||n.mode,CHATPANEL_SANDBOX_RUNTIME:n.runtime,CHATPANEL_SANDBOX_COMMAND:n.command||"",CHATPANEL_SANDBOX_IMAGE:n.image||"",CHATPANEL_SANDBOX_ENGINE:n.engine||"",CHATPANEL_SANDBOX_READS:r?.sandbox?.reads||c(o)||n.reads,CHATPANEL_SANDBOX_REQUIRED:n.required==="policy"?"policy":String(o.CHATPANEL_SANDBOX_REQUIRED||"")||(n.required?"on":""),CHATPANEL_SANDBOX_ALLOW_HOSTS:D(n.hosts,g(o.CHATPANEL_SANDBOX_ALLOW_HOSTS)).join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:D(n.write,g(o.CHATPANEL_SANDBOX_ALLOW_WRITE)).join(","),CHATPANEL_SANDBOX_DENY_READ:D(n.denyRead,g(o.CHATPANEL_SANDBOX_DENY_READ)).join(","),...Object.keys(d).length?{CHATPANEL_SANDBOX_AGENTS:JSON.stringify(d)}:{}}}function L(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||G(q.homedir(),".chatpanel","gateway.config.json")}function we(e){const o=e?.registries||{},r={};for(const[i,n]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])o[i]&&(r[n]=o[i]);return r}function P(e,o,r){r?e.capabilities[o]=r:delete e.capabilities[o]}function R(e,o,r,i){if(r.provider==="embedded")return O.includes(e)&&r.model!=null?(W(e,r.model)||i(`capabilities.${e}.model must be one of ${K[e].map(t=>t.id).join(", ")}`),{provider:"embedded",model:r.model}):{provider:"embedded"};if(r.provider==="none"&&O.includes(e))return{provider:"none"};const n={...o};if("url"in r){const t=String(r.url||"").trim();t&&x(t);const s=d=>{try{return new URL(d).origin}catch{return d}};o.url&&t&&s(o.url)!==s(t)&&typeof r.token!="string"&&delete n.token,n.url=t}return typeof r.adapter=="string"&&/^[a-z-]+$/.test(r.adapter)&&(n.adapter=r.adapter),typeof r.model=="string"&&(n.model=r.model.trim()),typeof r.token=="string"&&(n.token=r.token),typeof r.calibrated=="boolean"&&(n.calibrated=r.calibrated),typeof r.redact=="boolean"&&(n.redact=r.redact),n.url?(n.provider="remote",delete n.service,delete n.hasToken,n):null}const j=e=>{const{token:o,...r}=e||{};return{...r,hasToken:!!o}};function xe(e,o=L()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&o===L({}))throw new Error(`refusing to persist the real gateway config (${o}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);M(U(o),{recursive:!0,mode:448});const r={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,tls:e.tls};$(o,JSON.stringify(r,null,2),{mode:384});try{X(o,384)}catch{}}function Ne(e,{proUnlocked:o=!1,policy:r=null}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(i=>{const{apiKey:n,...t}=i;return{...t,hasKey:!!n}}),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,...n}=e.redaction?.detection||{backend:"off"};return n})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:(()=>{const{sandbox:i,locked:n}=k(y(e.sandbox),r);return Array.isArray(i.command)&&(i.command=JSON.stringify(i.command)),{...i,...E().mode?{envMode:E().mode}:{},...c()?{envReads:c()}:{},...n.length?{locked:n,lockedBy:r?.org?.name||"your organisation"}:{}}})(),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:I(e)},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([i,n])=>[i,_(n)?{...n,providers:n.providers.map(j)}:j(n)])),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:o,hasToken:!!e.pro?.entitlementToken,free:F(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 Se(e,o){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=o,e.ner.autostart=!0,e.ner}function ie(e,o={}){if(!e||e.type!=="api")return!1;let r;try{r=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(r.hostname),n=Number(r.port)||(r.protocol==="https:"?443:80);return i&&n===(Number(o.port)||4320)}const C=["default","acceptEdits","bypassPermissions"];function ge(e,o={}){const r=e?.bridge||{};return{...C.includes(r.permissionMode)&&r.permissionMode!=="default"?{permissionMode:r.permissionMode}:{},...typeof r.workingDir=="string"&&r.workingDir.trim()?{workingDir:r.workingDir.trim()}:{},...o}}function De(e,o={}){if((o.backend==="bridge"||o.backend==="api")&&(e.backend=o.backend),Array.isArray(o.destinations)){const r=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=o.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const n=ie(i,e);return n&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!n}).map(i=>{const n={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(n.agent=i.agent||i.id),i.type==="api"){n.baseUrl=String(i.baseUrl||""),n.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:r.get(i.id)?.apiKey;s&&(n.apiKey=s)}const t=typeof i.service=="string"&&i.service?i.service:r.get(i.id)?.service;return t&&(n.service=t),(i.fromEndpoint===!0||i.fromEndpoint===void 0&&r.get(i.id)?.fromEndpoint===!0)&&(n.fromEndpoint=!0),n})}if(o.bridge&&typeof o.bridge=="object"&&(typeof o.bridge.url=="string"&&(e.bridge.url=o.bridge.url),typeof o.bridge.agent=="string"&&(e.bridge.agent=o.bridge.agent),C.includes(o.bridge.permissionMode)&&(e.bridge.permissionMode=o.bridge.permissionMode),typeof o.bridge.workingDir=="string"&&(e.bridge.workingDir=o.bridge.workingDir.trim().slice(0,1024)),typeof o.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=o.bridge.openAgentLane)),Array.isArray(o.allowedExtensionIds)&&(e.allowedExtensionIds=o.allowedExtensionIds.map(r=>String(r).trim()).filter(r=>/^[a-p]{32}$/.test(r))),o.upstreams&&typeof o.upstreams=="object")for(const r of["openai","anthropic"]){const i=o.upstreams[r];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[r]={...e.upstreams[r],baseUrl:i.baseUrl.trim()})}if(o.redaction&&typeof o.redaction=="object"){const r=o.redaction;(r.tier==="basic"||r.tier==="full")&&(e.redaction.tier=r.tier),"redactSystem"in r&&(e.redaction.redactSystem=!!r.redactSystem),Array.isArray(r.dictionary)&&(e.redaction.dictionary=r.dictionary),r.detection&&typeof r.detection=="object"&&(e.redaction.detection=r.detection)}if(Array.isArray(o.allowedOrigins)&&(e.allowedOrigins=o.allowedOrigins),o.sandbox&&typeof o.sandbox=="object"){const r=y(e.sandbox),i={...r,...o.sandbox};o.sandbox.agents&&typeof o.sandbox.agents=="object"&&!Array.isArray(o.sandbox.agents)&&(i.agents={...r.agents||{},...o.sandbox.agents}),e.sandbox=y(i,{strict:!0})}if(o.pro&&typeof o.pro=="object"&&typeof o.pro.entitlementToken=="string"&&(e.pro.entitlementToken=o.pro.entitlementToken),o.stt&&typeof o.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in o.stt&&(e.stt.enabled=!!o.stt.enabled),"allowDownload"in o.stt&&(e.stt.allowDownload=!!o.stt.allowDownload)),o.read&&typeof o.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},o.read.remote&&typeof o.read.remote=="object"){if("url"in o.read.remote){const r=String(o.read.remote.url||"").trim();r&&x(r),e.read.remote.url=r}typeof o.read.remote.key=="string"&&(e.read.remote.key=o.read.remote.key)}["defuddle","text","remote"].includes(o.read.provider)&&(e.read.provider=o.read.provider==="remote"&&!e.read.remote.url?e.read.provider:o.read.provider)}if(o.registries&&typeof o.registries=="object"){const r=Z(o.registries),i={...e.registries||{}};for(const n of Q)n in o.registries&&(r[n]?i[n]=r[n]:delete i[n]);e.registries=i}if(o.search&&typeof o.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 r=o.search.searxng;if(r&&typeof r=="object"){if("url"in r){const i=String(r.url||"").trim();i&&x(i),e.search.searxng.url=i}typeof r.token=="string"&&(e.search.searxng.token=r.token),typeof r.engines=="string"&&(e.search.searxng.engines=r.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(r.safesearch)&&(e.search.searxng.safesearch=r.safesearch)}"apis"in o.search&&(e.search.apis=B(e.search.apis,o.search.apis)),["auto","serp","searxng"].includes(o.search.provider)&&(e.search.provider=o.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:o.search.provider)}if("fusions"in o){const r=J(e,o.fusions);if(r){const i=new Error(r);throw i.code="SHAPE",i}}if(o.capabilities&&typeof o.capabilities=="object"){e.capabilities=e.capabilities||{};const r=i=>{const n=new Error(i);throw n.code="SHAPE",n};for(const i of["rerank","decide","stt","tts","detect","embed"]){if(!(i in o.capabilities))continue;const n=o.capabilities[i];if(n===null){delete e.capabilities[i],i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!(!n||typeof n!="object")){if(_(n)){const t=Y(i,n);t.length&&r(t[0]);const s=w(e.capabilities[i],i).providers,d=[];for(const a of n.providers){if(!a||typeof a!="object")continue;if(typeof a.service=="string"&&a.service){const l=s.find(H=>H.service===a.service);l&&d.push(l);continue}const u=l=>{try{return new URL(l).origin}catch{return null}},f=(typeof a.id=="string"?s.find(l=>l.id===a.id):null)||(typeof a.url=="string"&&u(a.url)?s.find(l=>!l.id&&!l.service&&u(l.url)===u(a.url)):null)||{},b=R(i,f,a,r);b&&d.push(typeof a.id=="string"?{...b,id:a.id}:b)}P(e,i,v({mode:n.mode??w(e.capabilities[i],i).mode,providers:d},i))}else{const t=w(e.capabilities[i],i),s=R(i,t.providers[0]||{},n,r);P(e,i,v({mode:t.mode,providers:s?[s,...t.providers.slice(1)]:t.providers.slice(1)},i))}if(i==="detect"){const t=z(e.capabilities[i],i);t?.url&&t.provider==="remote"?(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:t.url,...t.token?{apiKey:t.token}:{}}):e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"})}}}}if(typeof o.logRequests=="boolean"&&(e.logRequests=o.logRequests),["off","types","values"].includes(o.logDetail)&&(e.logDetail=o.logDetail),o.tools&&typeof o.tools=="object"){e.tools=e.tools||{},"autoNarrow"in o.tools&&(e.tools.autoNarrow=!!o.tools.autoNarrow),"narrowAll"in o.tools&&(e.tools.narrowAll=!!o.tools.narrowAll),(o.tools.toolData==="real"||o.tools.toolData==="redactRemote")&&(e.tools.toolData=o.tools.toolData);const r=Number(o.tools.maxPerTurn);Number.isFinite(r)&&r>=1&&(e.tools.maxPerTurn=Math.floor(r))}return e}export{C as PERMISSION_MODES,p as SANDBOX_MODES,De as applyConfigPatch,Se as applyNerModelSelection,ge as bridgeAgentOptions,L as configPath,ie as isSelfDestination,y as normalizeSandboxConfig,xe as persistConfig,Ne as publicConfig,we as registryChildEnv,Ee as sandboxEnvFor,E as sandboxModeFromEnv,ce as sandboxProblems,c as sandboxReadsFromEnv};
|
package/src/egress.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{confinedLine as $}from"./confine.js";import{searchEngines as E}from"./retrieval/search-apis.js";import{linkPaths as S}from"@chatpanel/events/link-routes.js";import{isBlockedHost as m}from"@chatpanel/pii";const L=()=>new Date().toISOString();function y(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),n=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[n]||"",scheme:n}}catch{return null}}const g=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 P({clock:e=L}={}){const t=new Map;return{record(n){const r=y(n);if(!r||!r.host)return;const u=`${r.scheme}://${r.host}:${r.port}`,s=e(),c=t.get(u);if(c){c.count+=1,c.lastAt=s;return}t.set(u,{host:r.host,port:r.port,scheme:r.scheme,local:g(r.host),count:1,firstAt:s,lastAt:s})},snapshot(){return[...t.values()].sort((n,r)=>n.local===r.local?r.count-n.count:n.local?1:-1)},reset(){t.clear()}}}let b=null;function N(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const n=P();let r=t;n.setGate=l=>{r=l},n.blocked=[];const u=l=>{let i=null;try{i=y(l),n.record(l)}catch{}if(!r||!i?.host)return null;let h=!0;try{h=r(`${i.scheme}://${i.host}:${i.port}`,{local:g(i.host)})}catch{h=!0}if(h)return null;const o=`${i.host}:${i.port}`;n.blocked.includes(o)||n.blocked.push(o);const a=new Error(`egress to ${i.host} is blocked by your organisation’s policy`);return a.code="EGRESS_POLICY",a},s=e.fetch;typeof s=="function"&&(e.fetch=function(i,h){const o=u(i);return o?Promise.reject(o):s.call(this,i,h)});const c=e.WebSocket;return typeof c=="function"&&(e.WebSocket=new Proxy(c,{construct(l,i,h){const o=u(i[0]);if(o)throw o;return Reflect.construct(l,i,h)}})),e.__chatpanelEgress=n,e===globalThis&&(b=n),n}function A(){return b||(globalThis.__chatpanelEgress??null)}function f(e){try{return new URL(e).host}catch{return String(e||"")}}function x(e={},t=process.env,n=process.platform,r=process.arch){const u=[],s=(a,p,{when:d="always",off:w=null,local:v=!1,data:k=""}={})=>{a&&u.push({host:a,purpose:p,when:d,off:w,local:v,data:k})};s("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),s("huggingface.co","model weights (NER, dictation, read-aloud, translation, meetings) — ChatPanel’s pinned copies in huggingface.co/ChatPanel, or the upstream repo",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id and file being downloaded"}),s("dl.chatpanel.net","model weights only when Hugging Face is failing (an outage or a network that blocks it), and the installer",{when:"a model download Hugging Face could not serve",off:"the same switches as huggingface.co",data:"the model id being downloaded"}),s("raw.githubusercontent.com","the meeting echo canceller's weights (DTLN-aec, ~7 MB, pinned commit and hashes) — only when ChatPanel’s copy on Hugging Face cannot be reached",{when:"the first meeting captured with both the microphone and what is playing",off:"stt.aec = false, or the same switches as dl.chatpanel.net",data:"the file path being downloaded"}),t.CHATPANEL_ORT_DIR||s("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"}),n==="darwin"&&r==="arm64"&&s("registry.npmjs.org","the Apple on-device helper, for an install that came without it (the standalone binary)",{when:"Install on the Apple on-device row, `--install` or `--fetch-apple-helper` — never when the helper is already here",off:"do not run them; the npm package and the desktop app carry the helper and never fetch it",data:"nothing — this gateway version's package and its checksum"});const c=e.link?.enabled===!1?null:S(e.link||{}).relay;if(c){const a=new URL(c).host;s(a,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone or a partner server is paired (Settings › Link your phone, `chatpanel-gateway link pair`), and while pairing",off:"link.enabled = false, or remove every paired device",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}s("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const l=e.search?.searxng?.url||"";if(l){let a=l;try{a=new URL(l).host}catch{}s(a,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(a)})}if(e.search?.provider!=="searxng"){s("www.startpage.com","web search: the built-in results-page search, 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"}),s("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"}),s("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 E(e).filter(p=>p.kind==="api"&&p.enabled!==!1))s(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{}s(a,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(a)})}const i={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 (ElevenLabs: /speech-to-text)",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,p]of Object.entries(i)){const d=e.capabilities?.[a];if(!d?.url||d.provider==="embedded")continue;let w=d.url;try{w=new URL(d.url).host}catch{}s(w,`${p.what}${d.service?` (the ${d.service} container, started under Settings › Runtime)`:` (${d.adapter} at the address you configured)`}`,{when:`a client calls /v1/${a}`,off:d.service?`stop the ${d.service} service under Settings › Runtime`:`capabilities.${a} = null`,data:`${p.data}${d.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(w)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(s("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),s("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[a,p]of Object.entries(e.upstreams||{}))p?.baseUrl&&s(f(p.baseUrl),`model upstream "${a}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a}`,off:`upstreams.${a}.baseUrl`,local:g(f(p.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const a of e.destinations||[])a?.baseUrl&&s(f(a.baseUrl),`destination "${a.id||a.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a.id||"it"}`,off:"destinations[]",local:g(f(a.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});s("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&s(f(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:g(f(e.ner.url).split(":")[0]),data:"the text being redacted"});const h=e.tts||{};if(h.provider==="openai"||h.provider==="elevenlabs"){const a=h.remote?.baseUrl?f(h.remote.baseUrl):h.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";s(a,`remote read-aloud voice (${h.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:h.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}n==="darwin"&&e.runtime?.heatwatch!==!1&&s("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 o=e.bridge?.url||"http://127.0.0.1:4319";return s(f(o),"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"}),u}function O(e,{ledger:t=A(),version:n="",startedAt:r=null,env:u=process.env,managed:s=null,certificates:c=null,linkPartners:l=null,confined:i=null}={}){const h=x(e,u);for(const o of l||[])!o.host||o.route!=="link"&&o.route!=="relay"||h.some(a=>a.host===o.host)||h.push({host:o.host,purpose:`ChatPanel Link: the relay partner "${o.partner?.name||o.name}" reaches this gateway through`,when:"while that partner device is paired",off:`remove it: chatpanel-gateway link revoke ${o.id}`,data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"});return{ok:!0,version:n,since:r?new Date(r).toISOString():null,...c?{certificates:c}:{},...i?{confined:i}:{},...s?{managed:s,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:h,...l?{link:{partners:l.map(o=>({id:o.id,partner:o.partner?.name||o.name,scopes:o.scopes||[],route:o.route||null,host:o.host||null,...o.folder?{folder:o.folder}:{},pairedAt:o.pairedAt||null,lastSeen:o.lastSeen||null,online:!!o.online}))}}:{}}}function _(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 n of e.observed||[])t.push(` ${n.local?"[local] ":""}${n.scheme}://${n.host}:${n.port} ×${n.count} last ${n.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const n of e.declared||[])t.push(` ${n.local?"[local] ":""}${n.host}`),t.push(` ${n.purpose}`),t.push(` when: ${n.when}${n.off?` · off: ${n.off}`:""}`),n.data&&t.push(` sends: ${n.data}`);if(e.certificates){const n=e.certificates;t.push(""),t.push("CERTIFICATES — whose word is taken that a server is who it says"),t.push(n.on?` the runtime's own list, and this computer's (${n.added} added) — what a company proxy that re-signs HTTPS needs; checks stay on`:` the runtime's own list only${n.why?` — ${n.why}`:""}`),t.push(" off: tls.systemCa: false in the config, or CHATPANEL_SYSTEM_CA=off, then restart")}if(e.confined&&(t.push(""),t.push("CONFINEMENT — what this process itself can reach on this computer"),t.push(` ${$(e.confined)}`),e.confined.on&&t.push(" checked at start: home folder listed "+(e.confined.homeListed?"YES":"no")+" · home folder written "+(e.confined.homeWritten?"YES":"no")+" · sandbox runtime written "+(e.confined.fenceWritten?"YES":"no")+" · own folder written "+(e.confined.stateWritten?"yes":"NO"))),e.link){t.push(""),t.push("LINK PARTNERS — servers the owner paired to reach this gateway over ChatPanel Link"),e.link.partners?.length||t.push(" (none — no partner can reach this gateway until you pair one)");for(const n of e.link.partners||[]){const r=n.lastSeen?new Date(n.lastSeen).toISOString():"never";t.push(` partner:${n.partner} scopes: ${n.scopes.join(", ")||"none"} agents: ${n.scopes.includes("agents")?"yes":"no"}`),t.push(` route: ${n.route||"?"}${n.host?` via ${n.host}`:""} · last seen ${r}${n.online?" (online)":""}`),n.scopes.includes("agents")&&t.push(` agents run as yours do (your Coding Agents settings and sandbox), in ${n.folder||"its folder"}; it never answers their approval prompts`),t.push(` revoke: chatpanel-gateway link revoke ${n.id}`)}}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(([,n])=>n).map(([n,r])=>r===!0?n:`${n}=${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{
|
|
1
|
+
import{confinedLine as $}from"./confine.js";import{capabilityList as S}from"./capability-config.js";import{searchEngines as E}from"./retrieval/search-apis.js";import{linkPaths as L}from"@chatpanel/events/link-routes.js";import{isBlockedHost as g}from"@chatpanel/pii";const P=()=>new Date().toISOString();function y(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),a=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[a]||"",scheme:a}}catch{return null}}const w=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:g(t,{allowLoopback:!1,allowPrivate:!1})&&!g(t,{allowLoopback:!0,allowPrivate:!0})};function A({clock:e=P}={}){const t=new Map;return{record(a){const r=y(a);if(!r||!r.host)return;const u=`${r.scheme}://${r.host}:${r.port}`,s=e(),c=t.get(u);if(c){c.count+=1,c.lastAt=s;return}t.set(u,{host:r.host,port:r.port,scheme:r.scheme,local:w(r.host),count:1,firstAt:s,lastAt:s})},snapshot(){return[...t.values()].sort((a,r)=>a.local===r.local?r.count-a.count:a.local?1:-1)},reset(){t.clear()}}}let b=null;function O(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const a=A();let r=t;a.setGate=l=>{r=l},a.blocked=[];const u=l=>{let i=null;try{i=y(l),a.record(l)}catch{}if(!r||!i?.host)return null;let h=!0;try{h=r(`${i.scheme}://${i.host}:${i.port}`,{local:w(i.host)})}catch{h=!0}if(h)return null;const o=`${i.host}:${i.port}`;a.blocked.includes(o)||a.blocked.push(o);const n=new Error(`egress to ${i.host} is blocked by your organisation’s policy`);return n.code="EGRESS_POLICY",n},s=e.fetch;typeof s=="function"&&(e.fetch=function(i,h){const o=u(i);return o?Promise.reject(o):s.call(this,i,h)});const c=e.WebSocket;return typeof c=="function"&&(e.WebSocket=new Proxy(c,{construct(l,i,h){const o=u(i[0]);if(o)throw o;return Reflect.construct(l,i,h)}})),e.__chatpanelEgress=a,e===globalThis&&(b=a),a}function x(){return b||(globalThis.__chatpanelEgress??null)}function f(e){try{return new URL(e).host}catch{return String(e||"")}}function T(e={},t=process.env,a=process.platform,r=process.arch){const u=[],s=(n,p,{when:d="always",off:m=null,local:v=!1,data:k=""}={})=>{n&&u.push({host:n,purpose:p,when:d,off:m,local:v,data:k})};s("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),s("huggingface.co","model weights (NER, dictation, read-aloud, translation, meetings) — ChatPanel’s pinned copies in huggingface.co/ChatPanel, or the upstream repo",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id and file being downloaded"}),s("dl.chatpanel.net","model weights only when Hugging Face is failing (an outage or a network that blocks it), and the installer",{when:"a model download Hugging Face could not serve",off:"the same switches as huggingface.co",data:"the model id being downloaded"}),e.runtime?.services?.llama?.build!=="system"&&(s("api.github.com","llama.cpp for the Runtime: which files Unsloth’s release has, and their SHA-256",{when:"Start, Install or Update of llama.cpp when its build is not here yet",off:'runtime.services.llama.build = "system" — the llama-server on PATH (Homebrew’s, or your own)',data:"nothing — a read of the release (github.com/unslothai/llama.cpp)"}),s("github.com","llama.cpp for the Runtime: Unsloth’s prebuilt llama-server for this machine (~13 MB on a Mac)",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"}),s("release-assets.githubusercontent.com","where github.com redirects that download — GitHub’s own file host",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"})),s("raw.githubusercontent.com","the meeting echo canceller's weights (DTLN-aec, ~7 MB, pinned commit and hashes) — only when ChatPanel’s copy on Hugging Face cannot be reached",{when:"the first meeting captured with both the microphone and what is playing",off:"stt.aec = false, or the same switches as dl.chatpanel.net",data:"the file path being downloaded"}),t.CHATPANEL_ORT_DIR||s("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),a==="darwin"&&r==="arm64"&&s("registry.npmjs.org","the Apple on-device helper, for an install that came without it (the standalone binary)",{when:"Install on the Apple on-device row, `--install` or `--fetch-apple-helper` — never when the helper is already here",off:"do not run them; the npm package and the desktop app carry the helper and never fetch it",data:"nothing — this gateway version's package and its checksum"});const c=e.link?.enabled===!1?null:L(e.link||{}).relay;if(c){const n=new URL(c).host;s(n,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone or a partner server is paired (Settings › Link your phone, `chatpanel-gateway link pair`), and while pairing",off:"link.enabled = false, or remove every paired device",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}s("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const l=e.search?.searxng?.url||"";if(l){let n=l;try{n=new URL(l).host}catch{}s(n,"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(n)})}if(e.search?.provider!=="searxng"){s("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"}),s("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"}),s("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 n of E(e).filter(p=>p.kind==="api"&&p.enabled!==!1))s(n.api.host,`web search: ${n.api.name} (search API${n.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: "${n.api.id}", enabled: false }]`,data:"the same query"})}if(e.read?.remote?.url){let n=e.read.remote.url;try{n=new URL(e.read.remote.url).host}catch{}s(n,"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(n)})}const i={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 (ElevenLabs: /speech-to-text)",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[n,p]of Object.entries(i))for(const d of S(e.capabilities?.[n],n).providers){if(!d?.url||d.provider==="embedded")continue;let m=d.url;try{m=new URL(d.url).host}catch{}s(m,`${p.what}${d.service?` (the ${d.service} container, started under Settings › Runtime)`:` (${d.adapter} at the address you configured)`}`,{when:`a client calls /v1/${n}`,off:d.service?`stop the ${d.service} service under Settings › Runtime`:`capabilities.${n} = null`,data:`${p.data}${d.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(m)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(s("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),s("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[n,p]of Object.entries(e.upstreams||{}))p?.baseUrl&&s(f(p.baseUrl),`model upstream "${n}" — chat requests (after redaction) go here`,{when:`a request addressed to ${n}`,off:`upstreams.${n}.baseUrl`,local:w(f(p.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const n of e.destinations||[])n?.baseUrl&&s(f(n.baseUrl),`destination "${n.id||n.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${n.id||"it"}`,off:"destinations[]",local:w(f(n.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});s("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&s(f(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:w(f(e.ner.url).split(":")[0]),data:"the text being redacted"});const h=e.tts||{};if(h.provider==="openai"||h.provider==="elevenlabs"){const n=h.remote?.baseUrl?f(h.remote.baseUrl):h.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";s(n,`remote read-aloud voice (${h.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:h.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}a==="darwin"&&e.runtime?.heatwatch!==!1&&s("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 o=e.bridge?.url||"http://127.0.0.1:4319";return s(f(o),"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"}),u}function _(e,{ledger:t=x(),version:a="",startedAt:r=null,env:u=process.env,managed:s=null,certificates:c=null,linkPartners:l=null,confined:i=null}={}){const h=T(e,u);for(const o of l||[])!o.host||o.route!=="link"&&o.route!=="relay"||h.some(n=>n.host===o.host)||h.push({host:o.host,purpose:`ChatPanel Link: the relay partner "${o.partner?.name||o.name}" reaches this gateway through`,when:"while that partner device is paired",off:`remove it: chatpanel-gateway link revoke ${o.id}`,data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"});return{ok:!0,version:a,since:r?new Date(r).toISOString():null,...c?{certificates:c}:{},...i?{confined:i}:{},...s?{managed:s,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:h,...l?{link:{partners:l.map(o=>({id:o.id,partner:o.partner?.name||o.name,scopes:o.scopes||[],route:o.route||null,host:o.host||null,...o.folder?{folder:o.folder}:{},pairedAt:o.pairedAt||null,lastSeen:o.lastSeen||null,online:!!o.online}))}}:{}}}function q(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const a of e.observed||[])t.push(` ${a.local?"[local] ":""}${a.scheme}://${a.host}:${a.port} ×${a.count} last ${a.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const a of e.declared||[])t.push(` ${a.local?"[local] ":""}${a.host}`),t.push(` ${a.purpose}`),t.push(` when: ${a.when}${a.off?` · off: ${a.off}`:""}`),a.data&&t.push(` sends: ${a.data}`);if(e.certificates){const a=e.certificates;t.push(""),t.push("CERTIFICATES — whose word is taken that a server is who it says"),t.push(a.on?` the runtime's own list, and this computer's (${a.added} added) — what a company proxy that re-signs HTTPS needs; checks stay on`:` the runtime's own list only${a.why?` — ${a.why}`:""}`),t.push(" off: tls.systemCa: false in the config, or CHATPANEL_SYSTEM_CA=off, then restart")}if(e.confined&&(t.push(""),t.push("CONFINEMENT — what this process itself can reach on this computer"),t.push(` ${$(e.confined)}`),e.confined.on&&t.push(" checked at start: home folder listed "+(e.confined.homeListed?"YES":"no")+" · home folder written "+(e.confined.homeWritten?"YES":"no")+" · sandbox runtime written "+(e.confined.fenceWritten?"YES":"no")+" · own folder written "+(e.confined.stateWritten?"yes":"NO"))),e.link){t.push(""),t.push("LINK PARTNERS — servers the owner paired to reach this gateway over ChatPanel Link"),e.link.partners?.length||t.push(" (none — no partner can reach this gateway until you pair one)");for(const a of e.link.partners||[]){const r=a.lastSeen?new Date(a.lastSeen).toISOString():"never";t.push(` partner:${a.partner} scopes: ${a.scopes.join(", ")||"none"} agents: ${a.scopes.includes("agents")?"yes":"no"}`),t.push(` route: ${a.route||"?"}${a.host?` via ${a.host}`:""} · last seen ${r}${a.online?" (online)":""}`),a.scopes.includes("agents")&&t.push(` agents run as yours do (your Coding Agents settings and sandbox), in ${a.folder||"its folder"}; it never answers their approval prompts`),t.push(` revoke: chatpanel-gateway link revoke ${a.id}`)}}return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,a])=>a).map(([a,r])=>r===!0?a:`${a}=${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{A as createEgressLedger,T as declaredEgress,_ as egressAudit,x as egressLedger,q as formatAudit,O as installEgressLedger};
|
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 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};
|
|
1
|
+
function b(e){const t=String(e||"").trim();if(!t)return[];const n=[];let o="",a=null;for(const l of t)a?l===a?a=null:o+=l:l==='"'||l==="'"?a=l:/\s/.test(l)?o&&(n.push(o),o=""):o+=l;return o&&n.push(o),n}const g=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:e=>x(e),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:t})=>e?["--cache-reuse",String(t.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:t})=>e==="q8_0"||e==="auto"&&t.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-dspark","draft-dflash","draft-eagle3","draft-simple"],default:({values:e,recipe:t})=>{const n=e?.draftModel??t?.draft?.path??"";return!n||n==="off"?"off":t?.draft&&n===t.draft.path?t.draft.spec:"draft-mtp"},what:"Draft tokens and verify them in one pass. ngram needs nothing; the draft-… modes draft with the Draft model below — set for you when the model came with one (dspark, MTP, EAGLE3); draft-simple is a small sibling model.",args:(e,{values:t,backend:n})=>e==="off"?[]:e==="ngram"?["--spec-type","ngram-simple","--spec-draft-n-max","3"]:t.draftModel&&t.draftModel!=="off"?["--model-draft",t.draftModel,"--spec-type",e==="draft"?"draft-simple":e,"--spec-draft-n-max","3","--spec-draft-ngl",n==="cpu"?"0":"all",...t.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 modes draft with — the one the model came with when its repo ships one, else its MTP file (…-MTP.gguf) or a small sibling. A path; off for none.",engines:["llama"],default:({recipe:e})=>e?.draft?.path||"",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 returns its thinking as a separate field, off answers directly, auto lets the model decide. Thinking counts against the context window — the Thinking budget below caps it.",group:"reasoning",args:e=>e==="on"?["--reasoning","on","--reasoning-format","deepseek"]:e==="off"?["--reasoning","off","--reasoning-budget","0"]:[]}}},{id:"reasoningEffort",label:"Thinking effort",kind:"choice",options:["default","minimal","low","medium","high","xhigh"],what:"How hard a model whose template takes an effort (Inkling, gpt-oss) thinks before it answers. Low is quicker and leaves more of the window for the answer; default keeps the model’s own.",engines:["llama"],default:"default",tasks:["chat"],group:"reasoning",when:e=>e.recipe?.recommended?.reasoning?.effort!==!1&&d(e,"--reasoning-effort"),args:(e,t)=>e&&e!=="default"&&d(t,"--reasoning-effort")?["--reasoning-effort",e]:[]},{id:"reasoningBudget",label:"Thinking budget",kind:"number",min:-1,max:131072,what:"The most tokens the model may think before it must answer: -1 for no limit, 0 to answer at once. A budget keeps a thinking model from filling the context window before it writes a word.",engines:["llama"],tasks:["chat"],group:"reasoning",default:({values:e})=>e?.reasoning==="on"?1024:-1,when:e=>d(e,"--reasoning-budget"),args:(e,t)=>Number(e)>=0&&t.values?.reasoning!=="off"&&d(t,"--reasoning-budget")?["--reasoning-budget",String(e)]:[]},{id:"reasoningPreserve",label:"Keep earlier thinking",kind:"bool",what:"Send the model its earlier turns’ thinking back with the conversation. It reads its own reasoning again — and every turn costs that many tokens more. Off below a 32k context, where the room is better spent on the answer.",engines:["llama"],tasks:["chat"],group:"reasoning",default:({values:e})=>(Number(e?.maxModelLen)||0)>=32768,when:e=>d(e,"--no-reasoning-preserve"),args:(e,t)=>e||!d(t,"--no-reasoning-preserve")?[]:["--no-reasoning-preserve"]},...[["temperature","Temperature","temp","--temp",0,5,"How varied each word is: lower is steadier and more literal, higher is more varied."],["topP","Top-p","topP","--top-p",0,1,"Draw only from the most likely words whose chances add up to this share; 1.0 turns it off."],["topK","Top-k","topK","--top-k",0,1e3,"Draw only from this many of the most likely words; 0 turns it off."],["minP","Min-p","minP","--min-p",0,1,"Drop words less likely than this share of the most likely one; 0 turns it off."]].map(([e,t,n,o,a,l,r])=>({id:e,label:t,kind:"number",min:a,max:l,group:"sampling",what:`${r} The model’s publisher sets this in the file when they recommend one, and that is the default here; blank is llama.cpp’s own.`,engines:["llama"],tasks:["chat"],default:({recipe:s})=>typeof s?.recommended?.sampling?.[n]=="number"?s.recommended.sampling[n]:null,when:s=>d(s,o),args:(s,i)=>s==null||s===""||!d(i,o)?[]:[o,String(s)]})),{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. Set for you when the model came with one; a path, or off for none.",engines:["llama"],default:({recipe:e})=>e?.projector||"",tasks:["chat"],args:e=>e&&e!=="off"?["--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=>b(e)}]),T=e=>g.find(t=>t.id===e)||null,k=Object.freeze(["maxModelLen","kvCacheDtype","reasoning","reasoningEffort","reasoningBudget","reasoningPreserve","temperature","topP","topK","minP","speculative","draftModel","toolCalls","chatTemplate","vision","extraArgs"]);function S(e={}){const t={},n={};for(const[o,a]of Object.entries(e||{}))(k.includes(o)?n:t)[o]=a;return{engine:t,model:n}}function x({ramGB:e=0,recipe:t=null}={}){const n=!!(t?.recommended?.reasoning?.effort||t?.recommended?.reasoning?.toggle),o=e>0&&e<24?8192:n&&e>=36?32768:16384,a=Number(t?.recommended?.contextLength)||0;return a>0?Math.min(o,Math.max(2048,a)):o}function y(e,t){const n=e.by?.[t];return n?{...e,...n,by:void 0}:e}function m(e,t={}){const{task:n="chat",backend:o=null}=t;return g.filter(a=>a.engines.includes(e)&&(!a.tasks||a.tasks.includes(n))&&(!a.backends||!o||a.backends.includes(o))).map(a=>y(a,e)).filter(a=>!a.when||a.when(t))}function d(e,t){return(typeof e?.flags=="function"?e.flags(t):null)!==!1}function p(e,t){return typeof e.default=="function"?e.default(t):e.default}function v(e,t){if(!e)return null;if(e.kind==="bool")return typeof t=="boolean"?t:t==="true"?!0:t==="false"?!1:null;if(e.kind==="number"){const n=Number(t);return Number.isFinite(n)&&n>=e.min&&n<=e.max?n:null}if(e.kind==="choice")return e.options.includes(t)?t:null;if(e.kind==="text"){const n=String(t??"").trim();return n.length<=512&&!n.startsWith("-")&&!/[\s"'`$;|&<>]/.test(n)?n:null}if(e.kind==="args"){const n=String(t??"").trim();return n.length<=2e3&&!/[`$;|&<>\n]/.test(n)?n:null}return null}function L(e,t,n,o={}){const a={...t||{}},l=m(e,o);for(const[r,s]of Object.entries(n||{})){const i=l.find(h=>h.id===r);if(!i)return{error:`no tuning ${JSON.stringify(r)} for ${e}`};if(s==null){delete a[r];continue}const f=v(i,s);if(f===null)return{error:`${i.label}: ${i.kind==="choice"?`one of ${i.options.join(", ")}`:i.kind==="number"?`a number between ${i.min} and ${i.max}`:i.kind==="bool"?"on or off":i.kind==="args"?"flags as you would type them — no shell characters":"a plain path or id"}`};a[r]=f}return a}function c(e,t,n={}){const o={};for(const a of m(e,n))o[a.id]=t&&t[a.id]!==void 0?t[a.id]:p(a,{...n,values:{...t||{},...o}});return o}function _(e,t,n={}){const o=c(e,t,n),a=[];for(const l of m(e,n))a.push(...l.args(o[l.id],{...n,values:o}));return a}function P(e,t,n={}){const o=c(e,t,n);return m(e,n).map(a=>({id:a.id,label:a.label,what:a.what,kind:a.kind,...a.group?{group:a.group}:{},...a.options?{options:a.options}:{},...a.kind==="number"?{min:a.min,max:a.max}:{},default:t&&t[a.id]!==void 0?p(a,{...n,values:o}):o[a.id],...t&&t[a.id]!==void 0?{value:t[a.id]}:{}}))}const q=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"}}),M=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 O(e,t,n={}){const o=m(e,n);if((n.task||"chat")!=="chat"||!o.some(r=>r.id==="maxModelLen"))return[];const a=c(e,t,n);let l=!1;return M.map(r=>{const s=Number(n.recipe?.recommended?.contextLength)||0,i=s>0?Math.min(r.ctx(n),Math.max(2048,s)):r.ctx(n),f={maxModelLen:i,...o.some(w=>w.id==="kvCacheDtype")?{kvCacheDtype:i>=32768?e==="llama"?"q8_0":n.backend==="cuda"||n.backend==="rocm"?"fp8":"auto":"auto"}:{}},h=!n.ramGB||n.ramGB>=r.needGB,u=!l&&a.maxModelLen===i;return u&&(l=!0),{id:r.id,label:r.label,what:r.what,patch:f,fits:h,...h?{}:{why:`needs ${r.needGB} GB of memory; this machine has ${n.ramGB}`},active:u}})}export{q as ENGINE_DOCS,k as MODEL_ROWS,M as PROFILES,g as TUNINGS,v as coerceTuning,x as contextDefault,y as forEngine,L as patchTunings,O as profilesFor,c as resolveTunings,b as splitArgs,S as splitTunings,_ as tuningArgs,p as tuningDefault,P as tuningRows,m as tuningsFor};
|
package/src/gguf-meta.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{openSync as d,readSync as m,closeSync as h,fstatSync as y}from"node:fs";const g={0:1,1:1,2:2,3:2,4:4,5:4,6:4,7:1,10:8,11:8,12:8},b=1<<20;function k(s,n){let i=Buffer.alloc(0),o=0,r=0;const c=t=>{if(r>=o&&r+t<=o+i.length)return;const u=Math.max(t,1048576),l=Buffer.alloc(Math.min(u,Math.max(0,n-r))),f=m(s,l,0,l.length,r);if(f<t)throw new Error("truncated GGUF header");i=l.subarray(0,f),o=r},a=t=>{c(t);const u=r-o;return r+=t,i.subarray(u,u+t)};return{u32:()=>a(4).readUInt32LE(0),u64:()=>Number(a(8).readBigUInt64LE(0)),bytes:a,skip:t=>{if(r+=t,r>n)throw new Error("truncated GGUF header")}}}function E(s){const n=d(s,"r");try{const e=k(n,y(n).size);if(e.bytes(4).toString("latin1")!=="GGUF")return null;e.u32(),e.u64();const i=e.u64(),o=(a=!0)=>{const t=e.u64();return!a||t>b?(e.skip(t),null):e.bytes(t).toString("utf8")},r=a=>{const t=e.bytes(g[a]);switch(a){case 0:return t.readUInt8(0);case 1:return t.readInt8(0);case 2:return t.readUInt16LE(0);case 3:return t.readInt16LE(0);case 4:return t.readUInt32LE(0);case 5:return t.readInt32LE(0);case 6:return t.readFloatLE(0);case 7:return t.readUInt8(0)!==0;case 10:return Number(t.readBigUInt64LE(0));case 11:return Number(t.readBigInt64LE(0));case 12:return t.readDoubleLE(0);default:return null}},c={};for(let a=0;a<i;a++){const t=o(),u=e.u32();if(u===8){c[t]=o();continue}if(u===9){const l=e.u32(),f=e.u64();if(g[l]){e.skip(g[l]*f),c[t]={array:f};continue}if(l===8){for(let p=0;p<f;p++)o(!1);c[t]={array:f};continue}throw new Error(`nested array in ${t}`)}if(!(u in g))throw new Error(`unknown type ${u} at ${t}`);c[t]=r(u)}return c}finally{h(n)}}const I=s=>typeof s=="number"?Math.round(s*1e3)/1e3:s;function _(s){let n;try{n=E(s)}catch{return null}if(!n)return null;const e=n["general.architecture"],i={temp:"temp",top_p:"topP",top_k:"topK",min_p:"minP",repeat_penalty:"repeatPenalty"},o={};for(const[c,a]of Object.entries(i))typeof n[`general.sampling.${c}`]=="number"&&(o[a]=I(n[`general.sampling.${c}`]));const r=typeof n["tokenizer.chat_template"]=="string"?n["tokenizer.chat_template"]:"";return{...Object.keys(o).length?{sampling:o}:{},...e&&Number(n[`${e}.context_length`])>0?{contextLength:Number(n[`${e}.context_length`])}:{},reasoning:{effort:/reasoning_effort|thinking_effort/.test(r),toggle:/enable_thinking|\bthinking\b/.test(r)}}}export{E as ggufMetadata,_ as ggufRecommended};
|
package/src/inference-engines.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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 p(e,
|
|
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"]],update:{command:"brew upgrade vllm-project/vllm-metal/vllm-metal",steps:[["brew","upgrade","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 p(e,l){return e==="cuda"?l==="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 x({exec:e,platform:l=process.platform,arch:t=process.arch}={}){const a=async(n,r)=>{try{const o=await e(n,r,{timeout:8e3});return o&&!/error|not found|no devices/i.test(String(o.stdout||"")+String(o.stderr||""))}catch{return!1}};return l==="darwin"&&t==="arm64"?"apple":await a("nvidia-smi",["-L"])?"cuda":l==="linux"&&await a("rocm-smi",["--showid"])?"rocm":l==="linux"&&await a("sycl-ls",[])?"xpu":null}function L({platform:e=process.platform,arch:l=process.arch,accelerator:t=null,engine:a=null,vllmOnPath:n=!1,containerOnly:r=!1}={}){return e==="darwin"&&(l==="arm64"||t==="apple")&&r?{backend:"cpu",kind:"container",image:i.cpu,sources:h(l),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"&&(l==="arm64"||t==="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.",...n?{}:{warn:"`vllm` is not on PATH — install vLLM-Metal (the command beside this), then Run."}}:a?t==="cuda"?{backend:"cuda",kind:"container",image:i.cuda,devices:p("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."}:{}}:t==="rocm"&&e==="linux"?{backend:"rocm",kind:"container",image:i.rocm,devices:p("rocm",a),for:"chat, embeddings, transcription",speed:"fast: the GPU, batched",why:"AMD GPU found (rocm-smi): vLLM ROCm image."}:t==="xpu"&&e==="linux"?{backend:"xpu",kind:"container",image:i.xpu,devices:p("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(l),recipe:"vllm-cpu",devices:[],for:"an embedding model or a whisper transcriber; a small chat model to try",speed:`slow: CPU only${l==="x64"?"":"; a 90-minute build first"}`,why:`No accelerator found: vLLM’s CPU build (${l}). Small models only; slow.`,warn:"CPU inference — a 0.6B chat model is usable, anything larger wants a GPU."}:{backend:t==="cuda"?"cuda":t==="rocm"?"rocm":t==="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"]],update:{command:"brew upgrade llama.cpp",steps:[["brew","upgrade","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"]],update:{command:"winget upgrade --id ggml.llamacpp -e",steps:[["winget","upgrade","--id","ggml.llamacpp","-e","--accept-source-agreements","--accept-package-agreements"]],upToDate:"No (?:available|applicable) upgrade"},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:l=process.arch,accelerator:t=null,llamaOnPath:a=!1}={}){const n=e==="darwin"&&l==="arm64"?"metal":t==="cuda"?"cuda":t==="rocm"?"rocm":t==="xpu"?"vulkan":"cpu",r=n==="metal"?"Apple Silicon: llama.cpp on the Metal GPU, all layers offloaded":n==="cpu"?"no accelerator found: llama.cpp on the CPU — a small quantised model runs at a usable pace":`llama.cpp with the ${n.toUpperCase()} build, all layers offloaded`,o=f[e]||f.linux;return{backend:n,kind:"native",runner:"llama-server",install:o,why:r,for:"chat and vision — the largest choice of models (GGUF), your own .gguf files, the MTP draft that makes a big model fast",speed:n==="cpu"?"usable: the CPU with a 4-bit model":`fast: the ${n==="metal"?"Apple":n.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:l=process.platform,totalmem:t=()=>0,cpus:a=()=>[]}={}){const n=Math.round(t()/1073741824),r=a().length||0;let o=Math.max(1,Math.floor(r/2))||1,c=o;if(l==="darwin"&&e){const m=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,v]=await Promise.all([m("hw.physicalcpu"),m("hw.perflevel0.physicalcpu")]);d&&(o=d),c=v||o}else r&&(o=r,c=Math.min(r,8));return{ramGB:n,cores:o,perfCores:c}}const g=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"]],update:{command:"uv tool upgrade mlx-lm # or: pip3 install --user --upgrade mlx-lm",steps:[["uv","tool","upgrade","mlx-lm"]],fallback:[["pip3","install","--user","--upgrade","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:l=process.arch,mlxOnPath:t=!1}={}){return e==="darwin"&&l==="arm64"?{backend:"metal",kind:"native",runner:"mlx_lm.server",install:g,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.",...t?{}:{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:g}}function U({platform:e=process.platform,arch:l=process.arch,osMajor:t=0,appleOnPath:a=!1,appleInstall:n=null}={}){const r={kind:"native",runner:"chatpanel-apple-model",...n?{install:n}:{}};return e==="darwin"&&l==="arm64"?t<25?{...r,backend:"none",why:"Apple’s on-device model needs macOS 26 or later."}:{...r,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:n?.steps?.length?n.steps[0][0]==="mkdir"?"The helper is not built in this checkout yet — Install builds it.":"The helper is not in this install — Install fetches it.":"The helper is not in this install — run `chatpanel-gateway --fetch-apple-helper` to fetch it."}}:{...r,backend:"none",why:"Apple’s on-device model runs on Apple Silicon Macs only."}}function A({platform:e=process.platform,arch:l=process.arch,accelerator:t=null}={}){return e==="darwin"&&l==="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."}:t==="cuda"||t==="rocm"||t==="xpu"?{engine:"vllm",why:`${t.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,g as MLX_INSTALL,i as VLLM_IMAGES,y as VLLM_METAL_INSTALL,s as VLLM_VERSION,x as detectAccelerator,p as deviceArgs,k as hostShape,U as pickAppleEngine,L as pickInferenceEngine,M as pickLlamaEngine,P as pickMlxEngine,A as recommendEngine,h as vllmCpuSources};
|
package/src/kb.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as
|
|
2
|
-
`).find(r=>r.trim())||"");return{type:o.label||"text",pages:M(i).map((r,n)=>({page:n+1,text:r})),title:u?u[1].trim():""}}if(o.group!=="document")throw Object.assign(new Error(`${o.label||"binary"} is not a document`),{code:"unsupported"});if(!_)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const c=_(),d=await c.open(e,{name:t,hint:a}),s=[];for(let i=1;i<=d.pages;i+=1){let u="";try{u=String((await c.page(d.hash,i)).text||"")}catch(r){R(`[kb] ${t} p.${i}: ${r.message}`)}s.push({page:i,text:u})}return{type:d.type,pages:s,title:d.title||"",hash:d.hash,scanned:!!d.scanned}}async function U(e,t,{name:a,hint:o="",title:c="",source:d={},reach:s=""}){const i=await se(t,a,o),u=j(e,{title:c||i.title||L(a),pages:i.pages,source:{kind:d.kind||"bytes",name:a,...d},hash:i.hash||"",type:i.type,reach:s,now:g});return{id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced,...i.scanned?{scanned:!0}:{}}}function re(e,t){const a=Q(e).toLowerCase();return!te.has(a)&&!We.has(a)?!1:t?.length?t.some(o=>{const c=String(o).toLowerCase().replace(/^\*/,"");return a===(c.startsWith(".")?c:`.${c}`)||e.toLowerCase().endsWith(c)}):!0}async function ae(e,{path:t,recursive:a=!0,include:o=null,title:c=""}){const d=Fe(t,{home:W,cwd:process.cwd()});if(!d.ok)throw Object.assign(new Error(d.reason||"that path cannot be attached"),{code:"refused"});const s=J(ge(t.replace(/^~(?=$|\/)/,W))),i=[],u=[];let r=0,n=0;const l=async(y,m)=>{if(r>=T.files)return u.push({path:m,why:`stopped at ${T.files} files`}),!1;if(ee(y))return u.push({path:m,why:"withheld (a credential store)"}),!0;let x;try{x=H(y)}catch{return!0}const w=Q(y).toLowerCase(),k=te.has(w)?N:T.textBytes;if(x.size>k)return u.push({path:m,why:`too large (${Math.round(x.size/1048576)} MB)`}),!0;if(n+x.size>T.bytes)return u.push({path:m,why:"stopped: the folder is past the size limit"}),!1;r+=1,n+=x.size;try{const $=await U(e,fe(y),{name:L(y),title:i.length===0&&!m.includes("/")?c:"",source:{kind:"file",path:y},reach:"internal"});i.push({...$,path:m})}catch($){u.push({path:m,why:$.message})}return!0};if(!H(s).isDirectory())return await l(s,L(s)),{added:i,skipped:u};const O=async(y,m,G)=>{if(G>T.depth)return!0;let x=[];try{x=pe(y,{withFileTypes:!0}).sort((w,k)=>w.name.localeCompare(k.name))}catch{return!0}for(const w of x){const k=w.name;if(k.startsWith(".")&&w.isDirectory())continue;const $=he(y,k),K=m?`${m}/${k}`:k;if(w.isDirectory()){if(Ce.has(k)||!a)continue;try{if(!J($).startsWith(s)){u.push({path:K,why:"links outside the folder"});continue}}catch{continue}if(!await O($,K,G+1))return!1;continue}if(!(!w.isFile()&&!w.isSymbolicLink())){if(ee($)){u.push({path:K,why:"withheld (a credential store)"});continue}if(re(k,o)&&!await l($,K))return!1}}return!0};return await O(s,"",0),{added:i,skipped:u}}async function oe(e,{url:t,title:a=""}){if(!z)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const o=await z().read({url:t,format:"markdown"});if(o.status!==200)throw Object.assign(new Error(o.body?.error?.message||`read failed (${o.status})`),{code:"read_failed"});const c=String(o.body.markdown||o.body.text||"");if(!c.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const d=M(c).map((i,u)=>({page:u+1,text:i})),s=j(e,{title:a||o.body.title||t,pages:d,source:{kind:"url",url:o.body.url||t,name:o.body.title||""},type:"html",reach:"web",now:g});return{id:s.doc.id,title:s.doc.title,pages:s.doc.pages,chunks:s.doc.chunks,replaced:s.replaced}}async function ie(e,t,{admin:a=!1}={}){const o=g();let c=[],d=[];if(t.kind==="bytes"){const i=Buffer.from(t.data,"base64");if(!i.length)return f(400,"invalid_request","kb: data decoded to nothing");if(i.length>N)return f(413,"too_large",`kb: ${i.length} bytes is over the ${N}-byte limit`);try{c.push(await U(e,i,{name:t.name,hint:t.type||"",title:t.title,reach:t.reach}))}catch(u){return B(u)}}else if(t.kind==="path"){if(!a)return f(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:c,skipped:d}=await ae(e,t))}catch(i){return B(i)}}else if(t.kind==="url")try{c.push(await oe(e,t))}catch(i){return B(i)}else if(t.kind==="text"){const i=M(t.text).map((r,n)=>({page:n+1,text:r})),u=j(e,{title:t.title||t.name,pages:i,source:{kind:"text",name:t.name},type:"text",reach:t.reach,now:g});c.push({id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced})}const s=c.length?await D(e):0;return p.save(e),h({added:c,skipped:d,embedded:s,kb:S(e),ms:g()-o})}function B(e){const t=e?.code||"";return t==="refused"?f(403,"refused",`kb: ${e.message}`):t==="unsupported"?f(415,"unsupported",`kb: ${e.message}`):t==="too_large"?f(413,"too_large",`kb: ${e.message}`):t==="read_failed"||t==="empty"?f(502,"read_failed",`kb: ${e.message}`):t==="timeout"?f(504,"extract_timeout","kb: the document took too long to parse"):f(500,"kb_error",`kb: ${e?.message||e}`)}const X=(e,t)=>ve(e,t.query,{limit:t.limit,hops:t.hops,docs:t.docs||null,queries:t.queries||[],embed:I("query"),rerank:t.rerank===!1?null:ne,now:g}),ce=(e,t)=>e.docs.find(a=>a.id===t)?.title||t,Y=(e,t)=>{const a=Se(e,t);if(!a)return null;const o=a.kind==="note"?"Note":ce(e,a.doc);return{...a,title:o,cite:a.kind==="note"?`[note ${a.id.slice(5)}]`:`[${o.replace(/[[\]]/g,"")} p.${a.page}]`}};function ue(e,t){A(e);const a=Z(e.graph,t.node);if(!a)return h({node:null,neighbours:[],message:`no node named "${t.node}"`});const o=d=>{const s=e.graph.nodes.find(i=>i.id===d);return{id:d,label:s?.label||d.replace(/^chunk:/,"passage "),kind:s?.kind||"chunk"}},c={node:{id:a.id,kind:a.kind,label:a.label},neighbours:Ee(e.graph,a.id,{hops:t.hops,kinds:t.kinds||null,limit:t.limit})};if(t.to){const d=Z(e.graph,t.to);c.to=t.to,c.path=d?(Oe(e.graph,a.id,d.id)||[]).map(o):null,d&&!c.path.length&&(c.path=null)}return h(c)}async function de(e,t,{admin:a=!1}={}){if(t.model&&!a)return f(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const o=t.model&&typeof F=="function"?F(t.model):null,c=S(e),d=await _e(t.question,{search:(s,i)=>X(e,{query:s,limit:i.limit||10,hops:i.hops??1,docs:i.docs||t.docs||null}),outline:async s=>s?q(e.chunks,{doc:s}):e.outline,read:async s=>Y(e,s),complete:o,kbName:e.name,docs:c.documents,previous:t.previous||null,answer:t.answer||"",ask:t.ask!==!1,now:g});return h({attachment:d.attachment,read:d.read,hits:d.hits.map(s=>({id:s.id,doc:s.doc,title:s.title,page:s.page,section:s.section,cite:s.cite,lanes:s.lanes,via:s.via})),queries:d.queries,verdict:d.verdict,rounds:d.rounds,ask:d.ask,how:d.how,frame:{whole:d.frame.whole,docs:d.frame.docs},ms:d.ms})}async function le({method:e="GET",pathname:t="",query:a=new URLSearchParams,body:o=null,admin:c=!1,agent:d=""}={}){const s=Pe(t);if(!s)return f(404,"not_found",`no route ${t}`);if(s.bad)return f(400,"invalid_request",`kb: "${s.bad}" is not a valid id or route`);const i={admin:c,agent:String(d||a.get("agent")||"").trim().toLowerCase()},u=n=>{try{return{value:n()}}catch(l){return{res:f(400,"invalid_request",l.message)}}};if(!s.id){if(e==="GET")return h({kbs:p.list().filter(({manifest:n})=>V({access:n.access},i)).map(({manifest:n})=>({id:n.id,name:n.name,docs:(n.docs||[]).length,updatedAt:n.updatedAt,vectors:n.vectors?.count||0,model:n.vectors?.model||"",access:n.access||{agents:"all"}}))});if(e==="POST"){const n=u(()=>De(o||{}));if(n.res)return n.res;const l=n.value;if(l.id&&p.load(l.id))return h({kb:S(p.load(l.id)),existed:!0});const b=me({id:l.id,name:l.name,embed:l.embed,now:g});return p.save(b),{status:201,body:{kb:S(b)}}}return f(405,"method_not_allowed",`kb: ${e} is not allowed here`)}const r=p.load(s.id);if(!r)return f(404,"not_found",`kb: no knowledge base ${s.id} — POST /v1/kb to create one`);if(!V(r,i))return f(404,"not_found",`kb: no knowledge base ${s.id} for ${i.agent||"this caller"} — the owner can grant it (POST /v1/kb/${s.id}/access)`);if(!s.sub)return e==="GET"?h({kb:{...S(r),bytes:p.sizeOf(r.id),dir:c?p.dirOf(r.id):void 0}}):e==="DELETE"?c?(p.remove(r.id),h({ok:!0})):f(403,"forbidden","kb: deleting needs the gateway token or the extension origin"):f(405,"method_not_allowed",`kb: ${e} is not allowed here`);switch(s.sub){case"documents":{if(e==="POST"&&!s.rest){const n=u(()=>Be(o||{}));return n.res?n.res:ie(r,n.value,{admin:c})}if(e==="DELETE"&&s.rest)return c?ke(r,s.rest,{now:g})?(p.save(r),h({ok:!0,kb:S(r)})):f(404,"not_found",`kb: no document ${s.rest}`):f(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&s.rest){const n=Number(a.get("page"))||1,l=$e(r,s.rest,n);return l?h(l):f(404,"not_found",`kb: no document ${s.rest}`)}if(e==="GET")return h({documents:S(r).documents});break}case"passages":{if(e==="GET"&&s.rest){const n=Y(r,s.rest);return n?h(n):f(404,"not_found",`kb: no passage ${s.rest}`)}break}case"outline":{if(e==="GET"){A(r);const n=a.get("doc");return h({outline:n?q(r.chunks,{doc:n}):r.outline})}break}case"search":{if(e==="POST"){const n=u(()=>Ge(o||{}));return n.res?n.res:h(await X(r,n.value))}break}case"research":{if(e==="POST"){const n=u(()=>Le(o||{}));return n.res?n.res:de(r,n.value,{admin:c})}break}case"graph":{if(e==="POST"){const n=u(()=>je(o||{}));return n.res?n.res:ue(r,n.value)}break}case"report":{if(e==="GET")return A(r),{status:200,text:Ke(r),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return h({notes:r.notes});if(e==="POST"&&!s.rest){const n=u(()=>Ae(o||{}));if(n.res)return n.res;const l=n.value,b=l.status==="accepted"&&c?"accepted":"proposed",O=ye(r,{text:l.text,cites:l.cites||[],by:l.by||(c?"user":"agent"),status:b,now:g});return await D(r),p.save(r),{status:201,body:{note:O}}}if(e==="POST"&&s.rest){if(!c)return f(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const n=u(()=>Me(o||{}));if(n.res)return n.res;const l=n.value,b=we(r,s.rest,l.status,{now:g});return b?(p.save(r),h({note:b,removed:l.status==="removed"})):f(404,"not_found",`kb: no note ${s.rest}`)}break}case"access":{if(e==="GET")return h({access:r.access});if(e==="POST"){if(!c)return f(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const n=u(()=>Ne(o||{}));if(n.res)return n.res;const l=Te(r,n.value,{now:g});return p.save(r),h({access:l})}break}case"embed":{if(e==="POST"){const n=E(),l=v&&n?v.health("embed",n):{state:"off"},b=await D(r);return b&&p.save(r),h({embedded:b,vectors:r.vectors.by.size,model:r.vectors.model||n,dims:r.vectors.dims,state:l.state,...l.progress?{progress:l.progress}:{}})}break}default:break}return f(405,"method_not_allowed",`kb: ${e} ${t} is not a route`)}return{handle:le,store:p,embedModel:E}}export{T as KB_WALK_LIMITS,tt as createKbService};
|
|
1
|
+
import{readFileSync as pe,statSync as H,readdirSync as fe,realpathSync as J}from"node:fs";import{join as he,basename as L,extname as Q,resolve as ge}from"node:path";import me from"node:os";import{createKb as be,addDocument as j,removeDocument as ke,addNote as ye,setNoteStatus as we,searchKb as ve,embedMissing as xe,kbStatus as S,readPage as $e,chunkById as Se,refreshKb as A,setKbAccess as Te,kbMayUse as V}from"@chatpanel/events/kb-index.js";import{kbResearch as _e}from"@chatpanel/events/kb-research.js";import{neighbours as Ee,pathBetween as Oe,resolveNode as Z,graphReport as Ke}from"@chatpanel/events/kb-graph.js";import{outlineOf as q}from"@chatpanel/events/kb-chunk.js";import{routeKb as Pe,validateKbCreate as De,validateKbAdd as Be,validateKbSearch as Ge,validateKbResearch as Le,validateKbGraph as je,validateKbNote as Ae,validateKbNoteStatus as Me,validateKbAccess as Ne}from"@chatpanel/events/kb-capability.js";import{secretReason as ee,SKIP_DIR_NAMES as Ce,sniffType as ze,checkAttachablePath as Fe}from"@chatpanel/events/attached-paths.js";import{paginateText as M,MAX_DOCUMENT_BYTES as N}from"./extract-capability.js";import{defaultEmbeddedModel as Re}from"./embedded-models.js";import{primaryProvider as We}from"./capability-config.js";const T=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),te=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),Ie=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),p=(f,_,v,P={})=>({status:f,body:{error:{type:_,message:v},...P}}),h=f=>({status:200,body:f});function st({store:f,extract:_=null,embedded:v=null,cfg:P={},rerank:C=null,read:z=null,completer:F=null,log:R=()=>{},now:g=()=>Date.now(),home:W=me.homedir()}={}){const E=()=>{const e=We(P.capabilities?.embed,"embed");return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||Re("embed")||""},I=(e="passage")=>{const t=E();if(!v||!t)return null;const a=v.health("embed",t);return a.state!=="ready"&&!a.installed?(v.embed(t,["warm"],{kind:e}).catch(()=>{}),null):async o=>(await v.embed(t,o,{kind:e})).vectors},ne=typeof C=="function"?C:null;async function D(e,{late:t=()=>!1}={}){const a=I("passage");if(!a)return 0;try{return await xe(e,a,{model:E(),late:t})}catch(o){return R(`[kb] ${e.id}: embedding failed — ${o.message}`),0}}async function se(e,t,a=""){const o=ze(e,t);if(o.group==="key")throw Object.assign(new Error("its contents look like a credential — withheld"),{code:"refused"});if(o.text){const i=Buffer.from(e).toString("utf8"),u=/^\s*#\s+(.+?)\s*#*\s*$/m.exec(i.split(`
|
|
2
|
+
`).find(r=>r.trim())||"");return{type:o.label||"text",pages:M(i).map((r,n)=>({page:n+1,text:r})),title:u?u[1].trim():""}}if(o.group!=="document")throw Object.assign(new Error(`${o.label||"binary"} is not a document`),{code:"unsupported"});if(!_)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const c=_(),d=await c.open(e,{name:t,hint:a}),s=[];for(let i=1;i<=d.pages;i+=1){let u="";try{u=String((await c.page(d.hash,i)).text||"")}catch(r){R(`[kb] ${t} p.${i}: ${r.message}`)}s.push({page:i,text:u})}return{type:d.type,pages:s,title:d.title||"",hash:d.hash,scanned:!!d.scanned}}async function U(e,t,{name:a,hint:o="",title:c="",source:d={},reach:s=""}){const i=await se(t,a,o),u=j(e,{title:c||i.title||L(a),pages:i.pages,source:{kind:d.kind||"bytes",name:a,...d},hash:i.hash||"",type:i.type,reach:s,now:g});return{id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced,...i.scanned?{scanned:!0}:{}}}function re(e,t){const a=Q(e).toLowerCase();return!te.has(a)&&!Ie.has(a)?!1:t?.length?t.some(o=>{const c=String(o).toLowerCase().replace(/^\*/,"");return a===(c.startsWith(".")?c:`.${c}`)||e.toLowerCase().endsWith(c)}):!0}async function ae(e,{path:t,recursive:a=!0,include:o=null,title:c=""}){const d=Fe(t,{home:W,cwd:process.cwd()});if(!d.ok)throw Object.assign(new Error(d.reason||"that path cannot be attached"),{code:"refused"});const s=J(ge(t.replace(/^~(?=$|\/)/,W))),i=[],u=[];let r=0,n=0;const l=async(y,b)=>{if(r>=T.files)return u.push({path:b,why:`stopped at ${T.files} files`}),!1;if(ee(y))return u.push({path:b,why:"withheld (a credential store)"}),!0;let x;try{x=H(y)}catch{return!0}const w=Q(y).toLowerCase(),k=te.has(w)?N:T.textBytes;if(x.size>k)return u.push({path:b,why:`too large (${Math.round(x.size/1048576)} MB)`}),!0;if(n+x.size>T.bytes)return u.push({path:b,why:"stopped: the folder is past the size limit"}),!1;r+=1,n+=x.size;try{const $=await U(e,pe(y),{name:L(y),title:i.length===0&&!b.includes("/")?c:"",source:{kind:"file",path:y},reach:"internal"});i.push({...$,path:b})}catch($){u.push({path:b,why:$.message})}return!0};if(!H(s).isDirectory())return await l(s,L(s)),{added:i,skipped:u};const O=async(y,b,G)=>{if(G>T.depth)return!0;let x=[];try{x=fe(y,{withFileTypes:!0}).sort((w,k)=>w.name.localeCompare(k.name))}catch{return!0}for(const w of x){const k=w.name;if(k.startsWith(".")&&w.isDirectory())continue;const $=he(y,k),K=b?`${b}/${k}`:k;if(w.isDirectory()){if(Ce.has(k)||!a)continue;try{if(!J($).startsWith(s)){u.push({path:K,why:"links outside the folder"});continue}}catch{continue}if(!await O($,K,G+1))return!1;continue}if(!(!w.isFile()&&!w.isSymbolicLink())){if(ee($)){u.push({path:K,why:"withheld (a credential store)"});continue}if(re(k,o)&&!await l($,K))return!1}}return!0};return await O(s,"",0),{added:i,skipped:u}}async function oe(e,{url:t,title:a=""}){if(!z)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const o=await z().read({url:t,format:"markdown"});if(o.status!==200)throw Object.assign(new Error(o.body?.error?.message||`read failed (${o.status})`),{code:"read_failed"});const c=String(o.body.markdown||o.body.text||"");if(!c.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const d=M(c).map((i,u)=>({page:u+1,text:i})),s=j(e,{title:a||o.body.title||t,pages:d,source:{kind:"url",url:o.body.url||t,name:o.body.title||""},type:"html",reach:"web",now:g});return{id:s.doc.id,title:s.doc.title,pages:s.doc.pages,chunks:s.doc.chunks,replaced:s.replaced}}async function ie(e,t,{admin:a=!1}={}){const o=g();let c=[],d=[];if(t.kind==="bytes"){const i=Buffer.from(t.data,"base64");if(!i.length)return p(400,"invalid_request","kb: data decoded to nothing");if(i.length>N)return p(413,"too_large",`kb: ${i.length} bytes is over the ${N}-byte limit`);try{c.push(await U(e,i,{name:t.name,hint:t.type||"",title:t.title,reach:t.reach}))}catch(u){return B(u)}}else if(t.kind==="path"){if(!a)return p(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:c,skipped:d}=await ae(e,t))}catch(i){return B(i)}}else if(t.kind==="url")try{c.push(await oe(e,t))}catch(i){return B(i)}else if(t.kind==="text"){const i=M(t.text).map((r,n)=>({page:n+1,text:r})),u=j(e,{title:t.title||t.name,pages:i,source:{kind:"text",name:t.name},type:"text",reach:t.reach,now:g});c.push({id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced})}const s=c.length?await D(e):0;return f.save(e),h({added:c,skipped:d,embedded:s,kb:S(e),ms:g()-o})}function B(e){const t=e?.code||"";return t==="refused"?p(403,"refused",`kb: ${e.message}`):t==="unsupported"?p(415,"unsupported",`kb: ${e.message}`):t==="too_large"?p(413,"too_large",`kb: ${e.message}`):t==="read_failed"||t==="empty"?p(502,"read_failed",`kb: ${e.message}`):t==="timeout"?p(504,"extract_timeout","kb: the document took too long to parse"):p(500,"kb_error",`kb: ${e?.message||e}`)}const X=(e,t)=>ve(e,t.query,{limit:t.limit,hops:t.hops,docs:t.docs||null,queries:t.queries||[],embed:I("query"),rerank:t.rerank===!1?null:ne,now:g}),ce=(e,t)=>e.docs.find(a=>a.id===t)?.title||t,Y=(e,t)=>{const a=Se(e,t);if(!a)return null;const o=a.kind==="note"?"Note":ce(e,a.doc);return{...a,title:o,cite:a.kind==="note"?`[note ${a.id.slice(5)}]`:`[${o.replace(/[[\]]/g,"")} p.${a.page}]`}};function ue(e,t){A(e);const a=Z(e.graph,t.node);if(!a)return h({node:null,neighbours:[],message:`no node named "${t.node}"`});const o=d=>{const s=e.graph.nodes.find(i=>i.id===d);return{id:d,label:s?.label||d.replace(/^chunk:/,"passage "),kind:s?.kind||"chunk"}},c={node:{id:a.id,kind:a.kind,label:a.label},neighbours:Ee(e.graph,a.id,{hops:t.hops,kinds:t.kinds||null,limit:t.limit})};if(t.to){const d=Z(e.graph,t.to);c.to=t.to,c.path=d?(Oe(e.graph,a.id,d.id)||[]).map(o):null,d&&!c.path.length&&(c.path=null)}return h(c)}async function de(e,t,{admin:a=!1}={}){if(t.model&&!a)return p(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const o=t.model&&typeof F=="function"?F(t.model):null,c=S(e),d=await _e(t.question,{search:(s,i)=>X(e,{query:s,limit:i.limit||10,hops:i.hops??1,docs:i.docs||t.docs||null}),outline:async s=>s?q(e.chunks,{doc:s}):e.outline,read:async s=>Y(e,s),complete:o,kbName:e.name,docs:c.documents,previous:t.previous||null,answer:t.answer||"",ask:t.ask!==!1,now:g});return h({attachment:d.attachment,read:d.read,hits:d.hits.map(s=>({id:s.id,doc:s.doc,title:s.title,page:s.page,section:s.section,cite:s.cite,lanes:s.lanes,via:s.via})),queries:d.queries,verdict:d.verdict,rounds:d.rounds,ask:d.ask,how:d.how,frame:{whole:d.frame.whole,docs:d.frame.docs},ms:d.ms})}async function le({method:e="GET",pathname:t="",query:a=new URLSearchParams,body:o=null,admin:c=!1,agent:d=""}={}){const s=Pe(t);if(!s)return p(404,"not_found",`no route ${t}`);if(s.bad)return p(400,"invalid_request",`kb: "${s.bad}" is not a valid id or route`);const i={admin:c,agent:String(d||a.get("agent")||"").trim().toLowerCase()},u=n=>{try{return{value:n()}}catch(l){return{res:p(400,"invalid_request",l.message)}}};if(!s.id){if(e==="GET")return h({kbs:f.list().filter(({manifest:n})=>V({access:n.access},i)).map(({manifest:n})=>({id:n.id,name:n.name,docs:(n.docs||[]).length,updatedAt:n.updatedAt,vectors:n.vectors?.count||0,model:n.vectors?.model||"",access:n.access||{agents:"all"}}))});if(e==="POST"){const n=u(()=>De(o||{}));if(n.res)return n.res;const l=n.value;if(l.id&&f.load(l.id))return h({kb:S(f.load(l.id)),existed:!0});const m=be({id:l.id,name:l.name,embed:l.embed,now:g});return f.save(m),{status:201,body:{kb:S(m)}}}return p(405,"method_not_allowed",`kb: ${e} is not allowed here`)}const r=f.load(s.id);if(!r)return p(404,"not_found",`kb: no knowledge base ${s.id} — POST /v1/kb to create one`);if(!V(r,i))return p(404,"not_found",`kb: no knowledge base ${s.id} for ${i.agent||"this caller"} — the owner can grant it (POST /v1/kb/${s.id}/access)`);if(!s.sub)return e==="GET"?h({kb:{...S(r),bytes:f.sizeOf(r.id),dir:c?f.dirOf(r.id):void 0}}):e==="DELETE"?c?(f.remove(r.id),h({ok:!0})):p(403,"forbidden","kb: deleting needs the gateway token or the extension origin"):p(405,"method_not_allowed",`kb: ${e} is not allowed here`);switch(s.sub){case"documents":{if(e==="POST"&&!s.rest){const n=u(()=>Be(o||{}));return n.res?n.res:ie(r,n.value,{admin:c})}if(e==="DELETE"&&s.rest)return c?ke(r,s.rest,{now:g})?(f.save(r),h({ok:!0,kb:S(r)})):p(404,"not_found",`kb: no document ${s.rest}`):p(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&s.rest){const n=Number(a.get("page"))||1,l=$e(r,s.rest,n);return l?h(l):p(404,"not_found",`kb: no document ${s.rest}`)}if(e==="GET")return h({documents:S(r).documents});break}case"passages":{if(e==="GET"&&s.rest){const n=Y(r,s.rest);return n?h(n):p(404,"not_found",`kb: no passage ${s.rest}`)}break}case"outline":{if(e==="GET"){A(r);const n=a.get("doc");return h({outline:n?q(r.chunks,{doc:n}):r.outline})}break}case"search":{if(e==="POST"){const n=u(()=>Ge(o||{}));return n.res?n.res:h(await X(r,n.value))}break}case"research":{if(e==="POST"){const n=u(()=>Le(o||{}));return n.res?n.res:de(r,n.value,{admin:c})}break}case"graph":{if(e==="POST"){const n=u(()=>je(o||{}));return n.res?n.res:ue(r,n.value)}break}case"report":{if(e==="GET")return A(r),{status:200,text:Ke(r),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return h({notes:r.notes});if(e==="POST"&&!s.rest){const n=u(()=>Ae(o||{}));if(n.res)return n.res;const l=n.value,m=l.status==="accepted"&&c?"accepted":"proposed",O=ye(r,{text:l.text,cites:l.cites||[],by:l.by||(c?"user":"agent"),status:m,now:g});return await D(r),f.save(r),{status:201,body:{note:O}}}if(e==="POST"&&s.rest){if(!c)return p(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const n=u(()=>Me(o||{}));if(n.res)return n.res;const l=n.value,m=we(r,s.rest,l.status,{now:g});return m?(f.save(r),h({note:m,removed:l.status==="removed"})):p(404,"not_found",`kb: no note ${s.rest}`)}break}case"access":{if(e==="GET")return h({access:r.access});if(e==="POST"){if(!c)return p(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const n=u(()=>Ne(o||{}));if(n.res)return n.res;const l=Te(r,n.value,{now:g});return f.save(r),h({access:l})}break}case"embed":{if(e==="POST"){const n=E(),l=v&&n?v.health("embed",n):{state:"off"},m=await D(r);return m&&f.save(r),h({embedded:m,vectors:r.vectors.by.size,model:r.vectors.model||n,dims:r.vectors.dims,state:l.state,...l.progress?{progress:l.progress}:{}})}break}default:break}return p(405,"method_not_allowed",`kb: ${e} ${t} is not a route`)}return{handle:le,store:f,embedModel:E}}export{T as KB_WALK_LIMITS,st as createKbService};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readFileSync as p,readdirSync as l,realpathSync as a,statSync as u}from"node:fs";import i from"node:path";const g=256*2**20,f=new Map;function S(n){let t;try{t=a(n)}catch{return[]}const e=i.dirname(t),o=[];for(const r of[i.join(e,"..","lib"),e]){let c=[];try{c=l(r)}catch{continue}for(const s of c.sort())/^(lib)?llama(\.\d+)*\.(dylib|so|dll)(\.\d+)*$/i.test(s)&&o.push(i.join(r,s))}return o.push(t),o}function m(n){try{const t=u(n);if(!t.isFile()||t.size>g)return null;const e=f.get(n);if(e&&e.mtimeMs===t.mtimeMs)return e.buf;const o=p(n);return f.set(n,{mtimeMs:t.mtimeMs,buf:o}),o}catch{return null}}const d=(n,t)=>n.includes(Buffer.from(`\0${t}\0`,"latin1"));function j(n){const t=n?S(n).map(m).find(e=>e&&d(e,"llama")):null;return e=>t&&/^[a-z0-9_.-]{1,64}$/i.test(String(e||""))?d(t,String(e)):null}const h=new Map;function b(n){let t;try{t=a(n)}catch{return[]}const e=i.dirname(t),o=[];for(const r of[i.join(e,"..","lib"),e]){let c=[];try{c=l(r)}catch{continue}for(const s of c.sort())if(/^(lib)?llama-common(\.\d+)*\.(dylib|so|dll)(\.\d+)*$/i.test(s)){o.push(i.join(r,s));break}if(o.length)break}return o.push(t),o}function z(n){const t=n?b(n):[],e=t.map(r=>{try{return`${r}:${u(r).mtimeMs}`}catch{return r}}).join("|");let o=h.get(n);if(!o||o.key!==e){const r=new Set;for(const c of t){const s=m(c);if(s)for(const y of s.toString("latin1").matchAll(/--[a-z][a-z0-9-]{1,48}/g))r.add(y[0])}o={key:e,set:r.has("--ctx-size")?r:null},h.set(n,o)}return r=>o.set?o.set.has(r):null}export{z as llamaFlags,j as llamaKnows};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createWriteStream as H,existsSync as A,mkdirSync as v,readFileSync as B,writeFileSync as G,readdirSync as F,statSync as I,chmodSync as O,rmSync as c,renameSync as M}from"node:fs";import{createHash as N}from"node:crypto";import{Readable as R}from"node:stream";import{pipeline as W}from"node:stream/promises";import s from"node:path";const w=Object.freeze({id:"unsloth",label:"Unsloth’s llama.cpp",repo:"unslothai/llama.cpp",tag:"b12588-mix-c0c3de8",why:"upstream llama.cpp plus the newest models first — Unsloth’s looped-layer GGUFs (Inkling-2), DSpark and MTP drafting"}),Y=Object.freeze(["unsloth","system"]),ee="unsloth",C="https://api.github.com",b=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function D({platform:e,arch:r,accelerator:t=null},n=w.tag){if(e==="darwin")return`llama-${n}-bin-macos-${r==="arm64"?"arm64":"x64"}.tar.gz`;const o=t==="cuda"?"cuda":t==="rocm"||t==="xpu"?"vulkan":"cpu";return e==="linux"&&r==="x64"?`app-${n}-linux-x64-${o==="cuda"?"cuda12-portable":o}.tar.gz`:e==="linux"&&r==="arm64"?`app-${n}-linux-arm64-${o==="cuda"?"cuda13-portable":o}.tar.gz`:e==="win32"&&r==="x64"?`app-${n}-windows-x64-${o==="cuda"?"cuda12-portable":o}.zip`:e==="win32"&&r==="arm64"?`app-${n}-windows-arm64-cpu.zip`:null}async function P(e=w.tag,{fetchImpl:r=globalThis.fetch,repo:t=w.repo}={}){if(e!=="latest"&&!b.test(e))throw new Error(`not a release tag: ${JSON.stringify(e)}`);const n=await r(`${C}/repos/${t}/releases/${e==="latest"?"latest":`tags/${encodeURIComponent(e)}`}`,{headers:{accept:"application/vnd.github+json"},signal:AbortSignal.timeout(2e4)});if(!n.ok)throw new Error(`${t} release ${e}: GitHub answered ${n.status}`);const o=await n.json();if(!b.test(String(o.tag_name||"")))throw new Error(`${t}: a release without a usable tag`);return{tag:o.tag_name,assets:(o.assets||[]).map(i=>({name:String(i.name||""),url:String(i.browser_download_url||""),size:Number(i.size)||0,sha256:/^sha256:([0-9a-f]{64})$/.exec(String(i.digest||""))?.[1]||null}))}}const x=e=>s.join(e,"engines","llama-unsloth"),Z=e=>e==="win32"?"llama-server.exe":"llama-server";function E(e,r){const t=Z(r);if(A(s.join(e,t)))return s.join(e,t);for(const n of F(e)){const o=s.join(e,n,t);try{if(I(s.join(e,n)).isDirectory()&&A(o))return o}catch{}}return null}function L(e,r=process.platform){try{const t=B(s.join(x(e),"current"),"utf8").trim();if(!b.test(t))return null;const n=E(s.join(x(e),t),r);return n?{tag:t,bin:n}:null}catch{return null}}async function te({stateDir:e,platform:r,arch:t,accelerator:n=null,tag:o=w.tag,fetchImpl:i=globalThis.fetch,run:_,onProgress:U=()=>{}}){const u=await P(o,{fetchImpl:i}),g=L(e,r);if(g&&g.tag===u.tag)return{...g,already:!0};const m=D({platform:r,arch:t,accelerator:n},u.tag),a=m&&u.assets.find(d=>d.name===m);if(!a)throw new Error(`Unsloth’s llama.cpp ${u.tag} has no build for ${r}-${t}${m?` (${m})`:""} — pick the system llama.cpp instead`);if(!a.sha256)throw new Error(`${a.name}: the release publishes no SHA-256 for it — not installed`);if(!/^https:\/\/github\.com\/unslothai\/llama\.cpp\/releases\/download\//.test(a.url))throw new Error(`${a.name}: an unexpected download address — not installed`);const p=x(e);v(p,{recursive:!0,mode:448});const f=s.join(p,`${a.name}.part`),h=await i(a.url,{redirect:"follow"});if(!h.ok||!h.body)throw new Error(`${a.name}: GitHub answered ${h.status}`);const y=N("sha256");let S=0;const T=new TransformStream({transform(d,k){S+=d.byteLength,y.update(d),U({bytes:S,total:a.size,file:a.name}),k.enqueue(d)}});if(await W(R.fromWeb(h.body.pipeThrough(T)),H(f,{mode:384})),y.digest("hex")!==a.sha256)throw c(f,{force:!0}),new Error(`${a.name}: the download does not match its published SHA-256 — not installed`);const $=s.join(p,u.tag),l=`${$}.unpack`;c(l,{recursive:!0,force:!0}),v(l,{recursive:!0,mode:448});const j=await _("tar",[a.name.endsWith(".zip")?"-xf":"-xzf",f,"-C",l]);if(c(f,{force:!0}),!j.ok)throw c(l,{recursive:!0,force:!0}),new Error(`unpacking ${a.name}: ${j.err||"tar failed"}`);const z=E(l,r);if(!z)throw c(l,{recursive:!0,force:!0}),new Error(`${a.name}: no llama-server inside`);try{O(z,493)}catch{}return c($,{recursive:!0,force:!0}),M(l,$),G(s.join(p,"current"),u.tag,{mode:384}),L(e,r)}export{ee as DEFAULT_LLAMA_BUILD,Y as LLAMA_BUILDS,w as UNSLOTH_LLAMA,D as assetFor,x as buildRoot,te as installBuild,L as installedBuild,P as releaseOf};
|