@chatpanel/gateway 0.64.0 → 0.75.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.64.0",
3
+ "version": "0.75.0",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -15,15 +15,16 @@
15
15
  "bin",
16
16
  "gateway.config.example.json",
17
17
  "LICENSE",
18
- "README.md"
18
+ "README.md",
19
+ "native/darwin-arm64"
19
20
  ],
20
21
  "engines": {
21
22
  "node": ">=22.13"
22
23
  },
23
24
  "dependencies": {
24
25
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
25
- "@chatpanel/bridge": "^0.32.2",
26
- "@chatpanel/events": "^0.295.0",
26
+ "@chatpanel/bridge": "^0.42.0",
27
+ "@chatpanel/events": "^0.329.0",
27
28
  "@chatpanel/pii": "^0.12.0",
28
29
  "@huggingface/transformers": "^4.2.0",
29
30
  "defuddle": "^0.19.4",
@@ -0,0 +1 @@
1
+ import{readdirSync as s}from"node:fs";import n from"node:path";import{fileURLToPath as l}from"node:url";const c="chatpanel-apple-model",A="apple-on-device",w=25,m="arm64-apple-macos26.0",p=n.dirname(l(import.meta.url));function x(t){const e=Number.parseInt(String(t||""),10);return Number.isFinite(e)?e:0}function P({home:t,execPath:e=process.execPath,moduleDir:o=p}={}){const i=[n.join(o,"..","native","darwin-arm64")];return/^node(\.exe)?$/i.test(n.basename(e||""))||i.push(n.dirname(e)),t&&i.push(n.join(t,".chatpanel","bin")),i}function d(t=p){const e=n.join(t,"..","native","apple-model");try{return s(e).filter(o=>o.endsWith(".swift")).sort().map(o=>n.join(e,o))}catch{return[]}}function a(t,e){return["-O","-target",m,"-o",t,...e]}function S({home:t,sources:e=d()}={}){const o="https://developer.apple.com/documentation/foundationmodels";if(!e.length||!t)return{command:"comes with the gateway from npm and the desktop app on Apple Silicon",steps:[],url:o,note:"Needs macOS 26 on Apple Silicon with Apple Intelligence turned on (System Settings › Apple Intelligence & Siri)."};const i=n.join(t,".chatpanel","bin"),r=n.join(i,c);return{command:`swiftc ${a(r,["native/apple-model/*.swift"]).join(" ")}`,steps:[["mkdir","-p",i],["swiftc",...a(r,e)]],url:o,note:"A source checkout: builds the helper with the Command Line Tools. Needs Apple Intelligence turned on."}}export{c as APPLE_HELPER,w as APPLE_MIN_DARWIN,A as APPLE_MODEL_ID,m as APPLE_SWIFT_TARGET,a as appleBuildArgs,P as appleHelperDirs,S as appleInstallDoor,d as appleSources,x as darwinMajor};
@@ -1 +1 @@
1
- import{writeFileSync as A,mkdirSync as w,chmodSync as k}from"node:fs";import{join as f,dirname as x}from"node:path";import E from"node:os";import{usage as D}from"./freegate.js";import{applyFusionsPatch as c}from"./fusions.js";import{EMBEDDED_MODELS as S,EMBEDDED_IDS as m,isEmbeddedModel as T}from"./embedded-models.js";import{normalizeRegistries as v,REGISTRY_KINDS as N}from"@chatpanel/events/registries.js";import{assertEndpointUrl as d}from"@chatpanel/pii";import{normalizeGrant as _}from"@chatpanel/bridge/src/events/sandbox-policy.js";const O=["open","allowlist","off"],b=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function l(e={}){const r=e&&typeof e=="object"?e:{},o=O.includes(r.mode)?r.mode:"open",{hosts:i}=_({hosts:r.hosts??[]});return{mode:o,hosts:i,write:b(r.write),denyRead:b(r.denyRead)}}function B(e){const r=l(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function p(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||f(E.homedir(),".chatpanel","gateway.config.json")}function U(e){const r=e?.registries||{},o={};for(const[i,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[i]&&(o[t]=r[i]);return o}function K(e,r=p()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===p({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);w(x(r),{recursive:!0,mode:448});const o={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp};A(r,JSON.stringify(o,null,2),{mode:384});try{k(r,384)}catch{}}function Y(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:i,...t}=o;return{...t,hasKey:!!i}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:o,...i}=e.redaction?.detection||{backend:"off"};return i})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:l(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0}},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([o,i])=>{const{token:t,...n}=i||{};return[o,{...n,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:D(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function F(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function R(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),t=Number(o.port)||(o.protocol==="https:"?443:80);return i&&t===(Number(r.port)||4320)}const y=["default","acceptEdits","bypassPermissions"];function $(e,r={}){const o=e?.bridge||{};return{...y.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function q(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const o=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=r.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const t=R(i,e);return t&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!t}).map(i=>{const t={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(t.agent=i.agent||i.id),i.type==="api"){t.baseUrl=String(i.baseUrl||""),t.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;s&&(t.apiKey=s)}const n=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;return n&&(t.service=n),t})}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),y.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(o=>String(o).trim()).filter(o=>/^[a-p]{32}$/.test(o))),r.upstreams&&typeof r.upstreams=="object")for(const o of["openai","anthropic"]){const i=r.upstreams[o];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:i.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const o=r.redaction;(o.tier==="basic"||o.tier==="full")&&(e.redaction.tier=o.tier),"redactSystem"in o&&(e.redaction.redactSystem=!!o.redactSystem),Array.isArray(o.dictionary)&&(e.redaction.dictionary=o.dictionary),o.detection&&typeof o.detection=="object"&&(e.redaction.detection=o.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=l({...e.sandbox||{},...r.sandbox})),r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const o=String(r.read.remote.url||"").trim();o&&d(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.registries&&typeof r.registries=="object"){const o=v(r.registries),i={...e.registries||{}};for(const t of N)t in r.registries&&(o[t]?i[t]=o[t]:delete i[t]);e.registries=i}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&d(i),e.search.searxng.url=i}typeof o.token=="string"&&(e.search.searxng.token=o.token),typeof o.engines=="string"&&(e.search.searxng.engines=o.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(o.safesearch)&&(e.search.searxng.safesearch=o.safesearch)}["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const o=c(e,r.fusions);if(o){const i=new Error(o);throw i.code="SHAPE",i}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const o of["rerank","decide","stt","tts","detect","embed"]){if(!(o in r.capabilities))continue;const i=r.capabilities[o];if(i===null){delete e.capabilities[o],o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!i||typeof i!="object")continue;const t=e.capabilities[o]||{},n={...t};if(i.provider==="embedded"){if(m.includes(o)&&i.model!=null){if(!T(o,i.model)){const s=new Error(`capabilities.${o}.model must be one of ${S[o].map(a=>a.id).join(", ")}`);throw s.code="SHAPE",s}e.capabilities[o]={provider:"embedded",model:i.model};continue}e.capabilities[o]={provider:"embedded"},o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(i.provider==="none"&&m.includes(o)){e.capabilities[o]={provider:"none"};continue}if("url"in i){const s=String(i.url||"").trim();s&&d(s);const a=u=>{try{return new URL(u).origin}catch{return u}};t.url&&s&&a(t.url)!==a(s)&&typeof i.token!="string"&&delete n.token,n.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(n.adapter=i.adapter),typeof i.model=="string"&&(n.model=i.model.trim()),typeof i.token=="string"&&(n.token=i.token),typeof i.calibrated=="boolean"&&(n.calibrated=i.calibrated),typeof i.redact=="boolean"&&(n.redact=i.redact),!n.url){delete e.capabilities[o];continue}n.provider="remote",delete n.service,e.capabilities[o]=n,o==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}})}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const o=Number(r.tools.maxPerTurn);Number.isFinite(o)&&o>=1&&(e.tools.maxPerTurn=Math.floor(o))}return e}export{y as PERMISSION_MODES,q as applyConfigPatch,F as applyNerModelSelection,$ as bridgeAgentOptions,p as configPath,R as isSelfDestination,l as normalizeSandboxConfig,K as persistConfig,Y as publicConfig,U as registryChildEnv,B as sandboxEnvFor};
1
+ import{writeFileSync as A,mkdirSync as w,chmodSync as k}from"node:fs";import{join as x,dirname as f}from"node:path";import E from"node:os";import{usage as D}from"./freegate.js";import{applyFusionsPatch as S}from"./fusions.js";import{EMBEDDED_MODELS as c,EMBEDDED_IDS as m,isEmbeddedModel as T}from"./embedded-models.js";import{normalizeRegistries as v,REGISTRY_KINDS as N}from"@chatpanel/events/registries.js";import{assertEndpointUrl as d}from"@chatpanel/pii";import{normalizeGrant as _}from"@chatpanel/bridge/src/events/sandbox-policy.js";const O=["open","allowlist","off"],b=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function l(e={}){const r=e&&typeof e=="object"?e:{},o=O.includes(r.mode)?r.mode:"open",{hosts:i}=_({hosts:r.hosts??[]});return{mode:o,hosts:i,write:b(r.write),denyRead:b(r.denyRead)}}function B(e){const r=l(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function p(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||x(E.homedir(),".chatpanel","gateway.config.json")}function U(e){const r=e?.registries||{},o={};for(const[i,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[i]&&(o[t]=r[i]);return o}function K(e,r=p()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===p({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);w(f(r),{recursive:!0,mode:448});const o={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp,link:e.link};A(r,JSON.stringify(o,null,2),{mode:384});try{k(r,384)}catch{}}function Y(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:i,...t}=o;return{...t,hasKey:!!i}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:o,...i}=e.redaction?.detection||{backend:"off"};return i})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:l(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0}},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([o,i])=>{const{token:t,...n}=i||{};return[o,{...n,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:D(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function F(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function R(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),t=Number(o.port)||(o.protocol==="https:"?443:80);return i&&t===(Number(r.port)||4320)}const y=["default","acceptEdits","bypassPermissions"];function $(e,r={}){const o=e?.bridge||{};return{...y.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function q(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const o=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=r.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const t=R(i,e);return t&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!t}).map(i=>{const t={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(t.agent=i.agent||i.id),i.type==="api"){t.baseUrl=String(i.baseUrl||""),t.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;s&&(t.apiKey=s)}const n=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;return n&&(t.service=n),t})}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),y.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(o=>String(o).trim()).filter(o=>/^[a-p]{32}$/.test(o))),r.upstreams&&typeof r.upstreams=="object")for(const o of["openai","anthropic"]){const i=r.upstreams[o];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:i.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const o=r.redaction;(o.tier==="basic"||o.tier==="full")&&(e.redaction.tier=o.tier),"redactSystem"in o&&(e.redaction.redactSystem=!!o.redactSystem),Array.isArray(o.dictionary)&&(e.redaction.dictionary=o.dictionary),o.detection&&typeof o.detection=="object"&&(e.redaction.detection=o.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=l({...e.sandbox||{},...r.sandbox})),r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const o=String(r.read.remote.url||"").trim();o&&d(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.registries&&typeof r.registries=="object"){const o=v(r.registries),i={...e.registries||{}};for(const t of N)t in r.registries&&(o[t]?i[t]=o[t]:delete i[t]);e.registries=i}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&d(i),e.search.searxng.url=i}typeof o.token=="string"&&(e.search.searxng.token=o.token),typeof o.engines=="string"&&(e.search.searxng.engines=o.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(o.safesearch)&&(e.search.searxng.safesearch=o.safesearch)}["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const o=S(e,r.fusions);if(o){const i=new Error(o);throw i.code="SHAPE",i}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const o of["rerank","decide","stt","tts","detect","embed"]){if(!(o in r.capabilities))continue;const i=r.capabilities[o];if(i===null){delete e.capabilities[o],o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!i||typeof i!="object")continue;const t=e.capabilities[o]||{},n={...t};if(i.provider==="embedded"){if(m.includes(o)&&i.model!=null){if(!T(o,i.model)){const s=new Error(`capabilities.${o}.model must be one of ${c[o].map(a=>a.id).join(", ")}`);throw s.code="SHAPE",s}e.capabilities[o]={provider:"embedded",model:i.model};continue}e.capabilities[o]={provider:"embedded"},o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(i.provider==="none"&&m.includes(o)){e.capabilities[o]={provider:"none"};continue}if("url"in i){const s=String(i.url||"").trim();s&&d(s);const a=u=>{try{return new URL(u).origin}catch{return u}};t.url&&s&&a(t.url)!==a(s)&&typeof i.token!="string"&&delete n.token,n.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(n.adapter=i.adapter),typeof i.model=="string"&&(n.model=i.model.trim()),typeof i.token=="string"&&(n.token=i.token),typeof i.calibrated=="boolean"&&(n.calibrated=i.calibrated),typeof i.redact=="boolean"&&(n.redact=i.redact),!n.url){delete e.capabilities[o];continue}n.provider="remote",delete n.service,e.capabilities[o]=n,o==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}})}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const o=Number(r.tools.maxPerTurn);Number.isFinite(o)&&o>=1&&(e.tools.maxPerTurn=Math.floor(o))}return e}export{y as PERMISSION_MODES,q as applyConfigPatch,F as applyNerModelSelection,$ as bridgeAgentOptions,p as configPath,R as isSelfDestination,l as normalizeSandboxConfig,K as persistConfig,Y as publicConfig,U as registryChildEnv,B as sandboxEnvFor};
package/src/egress.js CHANGED
@@ -1,2 +1,2 @@
1
- import{isBlockedHost as f}from"@chatpanel/pii";const b=()=>new Date().toISOString();function w(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),r=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[r]||"",scheme:r}}catch{return null}}const p=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:f(t,{allowLoopback:!1,allowPrivate:!1})&&!f(t,{allowLoopback:!0,allowPrivate:!0})};function v({clock:e=b}={}){const t=new Map;return{record(r){const o=w(r);if(!o||!o.host)return;const h=`${o.scheme}://${o.host}:${o.port}`,l=e(),i=t.get(h);if(i){i.count+=1,i.lastAt=l;return}t.set(h,{host:o.host,port:o.port,scheme:o.scheme,local:p(o.host),count:1,firstAt:l,lastAt:l})},snapshot(){return[...t.values()].sort((r,o)=>r.local===o.local?o.count-r.count:r.local?1:-1)},reset(){t.clear()}}}let g=null;function E(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const r=v();let o=t;r.setGate=c=>{o=c},r.blocked=[];const h=c=>{let a=null;try{a=w(c),r.record(c)}catch{}if(!o||!a?.host)return null;let s=!0;try{s=o(`${a.scheme}://${a.host}:${a.port}`,{local:p(a.host)})}catch{s=!0}if(s)return null;const n=`${a.host}:${a.port}`;r.blocked.includes(n)||r.blocked.push(n);const d=new Error(`egress to ${a.host} is blocked by your organisation’s policy`);return d.code="EGRESS_POLICY",d},l=e.fetch;typeof l=="function"&&(e.fetch=function(a,s){const n=h(a);return n?Promise.reject(n):l.call(this,a,s)});const i=e.WebSocket;return typeof i=="function"&&(e.WebSocket=new Proxy(i,{construct(c,a,s){const n=h(a[0]);if(n)throw n;return Reflect.construct(c,a,s)}})),e.__chatpanelEgress=r,e===globalThis&&(g=r),r}function k(){return g||(globalThis.__chatpanelEgress??null)}function u(e){try{return new URL(e).host}catch{return String(e||"")}}function $(e={},t=process.env){const r=[],o=(a,s,{when:n="always",off:d=null,local:y=!1,data:m=""}={})=>{a&&r.push({host:a,purpose:s,when:n,off:d,local:y,data:m})};if(o("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),o("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),o("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),t.CHATPANEL_ORT_DIR||o("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),e.link?.enabled!==!1){let a="link.chatpanel.net";try{e.link?.relayUrl&&(a=new URL(e.link.relayUrl).host)}catch{}o(a,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone is paired (Settings › Link your phone), and while pairing",off:"link.enabled = false, or remove every paired phone",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}o("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const h=e.search?.searxng?.url||"";if(h){let a=h;try{a=new URL(h).host}catch{}o(a,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(a)})}if(e.search?.provider!=="searxng"&&(o("www.startpage.com","web search: the built-in results-page search, first engine",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),o("html.duckduckgo.com","web search: the built-in results-page search, fallback engine",{when:"Startpage returned nothing",off:"the same switch as www.startpage.com",data:"the same query"})),e.read?.remote?.url){let a=e.read.remote.url;try{a=new URL(e.read.remote.url).host}catch{}o(a,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(a)})}const l={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[a,s]of Object.entries(l)){const n=e.capabilities?.[a];if(!n?.url||n.provider==="embedded")continue;let d=n.url;try{d=new URL(n.url).host}catch{}o(d,`${s.what}${n.service?` (the ${n.service} container, started under Settings › Runtime)`:` (${n.adapter} at the address you configured)`}`,{when:`a client calls /v1/${a}`,off:n.service?`stop the ${n.service} service under Settings › Runtime`:`capabilities.${a} = null`,data:`${s.data}${n.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(d)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(o("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),o("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[a,s]of Object.entries(e.upstreams||{}))s?.baseUrl&&o(u(s.baseUrl),`model upstream "${a}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a}`,off:`upstreams.${a}.baseUrl`,local:p(u(s.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const a of e.destinations||[])a?.baseUrl&&o(u(a.baseUrl),`destination "${a.id||a.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a.id||"it"}`,off:"destinations[]",local:p(u(a.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});o("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&o(u(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:p(u(e.ner.url).split(":")[0]),data:"the text being redacted"});const i=e.tts||{};if(i.provider==="openai"||i.provider==="elevenlabs"){const a=i.remote?.baseUrl?u(i.remote.baseUrl):i.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(a,`remote read-aloud voice (${i.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:i.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}const c=e.bridge?.url||"http://127.0.0.1:4319";return o(u(c),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),r}function S(e,{ledger:t=k(),version:r="",startedAt:o=null,env:h=process.env,managed:l=null}={}){return{ok:!0,version:r,since:o?new Date(o).toISOString():null,...l?{managed:l,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:$(e,h)}}function x(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const r of e.observed||[])t.push(` ${r.local?"[local] ":""}${r.scheme}://${r.host}:${r.port} ×${r.count} last ${r.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const r of e.declared||[])t.push(` ${r.local?"[local] ":""}${r.host}`),t.push(` ${r.purpose}`),t.push(` when: ${r.when}${r.off?` · off: ${r.off}`:""}`),r.data&&t.push(` sends: ${r.data}`);return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,r])=>r).map(([r,o])=>o===!0?r:`${r}=${o}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
2
- `)}export{v as createEgressLedger,$ as declaredEgress,S as egressAudit,k as egressLedger,x as formatAudit,E as installEgressLedger};
1
+ import{linkPaths as k}from"@chatpanel/events/link-routes.js";import{isBlockedHost as m}from"@chatpanel/pii";const $=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),a=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[a]||"",scheme:a}}catch{return null}}const w=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:m(t,{allowLoopback:!1,allowPrivate:!1})&&!m(t,{allowLoopback:!0,allowPrivate:!0})};function E({clock:e=$}={}){const t=new Map;return{record(a){const n=g(a);if(!n||!n.host)return;const r=`${n.scheme}://${n.host}:${n.port}`,i=e(),c=t.get(r);if(c){c.count+=1,c.lastAt=i;return}t.set(r,{host:n.host,port:n.port,scheme:n.scheme,local:w(n.host),count:1,firstAt:i,lastAt:i})},snapshot(){return[...t.values()].sort((a,n)=>a.local===n.local?n.count-a.count:a.local?1:-1)},reset(){t.clear()}}}let y=null;function R(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const a=E();let n=t;a.setGate=d=>{n=d},a.blocked=[];const r=d=>{let s=null;try{s=g(d),a.record(d)}catch{}if(!n||!s?.host)return null;let u=!0;try{u=n(`${s.scheme}://${s.host}:${s.port}`,{local:w(s.host)})}catch{u=!0}if(u)return null;const o=`${s.host}:${s.port}`;a.blocked.includes(o)||a.blocked.push(o);const l=new Error(`egress to ${s.host} is blocked by your organisation’s policy`);return l.code="EGRESS_POLICY",l},i=e.fetch;typeof i=="function"&&(e.fetch=function(s,u){const o=r(s);return o?Promise.reject(o):i.call(this,s,u)});const c=e.WebSocket;return typeof c=="function"&&(e.WebSocket=new Proxy(c,{construct(d,s,u){const o=r(s[0]);if(o)throw o;return Reflect.construct(d,s,u)}})),e.__chatpanelEgress=a,e===globalThis&&(y=a),a}function L(){return y||(globalThis.__chatpanelEgress??null)}function p(e){try{return new URL(e).host}catch{return String(e||"")}}function S(e={},t=process.env,a=process.platform){const n=[],r=(o,l,{when:h="always",off:f=null,local:b=!1,data:v=""}={})=>{o&&n.push({host:o,purpose:l,when:h,off:f,local:b,data:v})};r("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),r("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),r("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),t.CHATPANEL_ORT_DIR||r("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"});const i=e.link?.enabled===!1?null:k(e.link||{}).relay;if(i){const o=new URL(i).host;r(o,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone is paired (Settings › Link your phone), and while pairing",off:"link.enabled = false, or remove every paired phone",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}r("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const c=e.search?.searxng?.url||"";if(c){let o=c;try{o=new URL(c).host}catch{}r(o,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(o)})}if(e.search?.provider!=="searxng"&&(r("www.startpage.com","web search: the built-in results-page search, first engine",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),r("html.duckduckgo.com","web search: the built-in results-page search, fallback engine",{when:"Startpage returned nothing",off:"the same switch as www.startpage.com",data:"the same query"})),e.read?.remote?.url){let o=e.read.remote.url;try{o=new URL(e.read.remote.url).host}catch{}r(o,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(o)})}const d={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[o,l]of Object.entries(d)){const h=e.capabilities?.[o];if(!h?.url||h.provider==="embedded")continue;let f=h.url;try{f=new URL(h.url).host}catch{}r(f,`${l.what}${h.service?` (the ${h.service} container, started under Settings › Runtime)`:` (${h.adapter} at the address you configured)`}`,{when:`a client calls /v1/${o}`,off:h.service?`stop the ${h.service} service under Settings › Runtime`:`capabilities.${o} = null`,data:`${l.data}${h.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(f)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(r("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),r("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[o,l]of Object.entries(e.upstreams||{}))l?.baseUrl&&r(p(l.baseUrl),`model upstream "${o}" — chat requests (after redaction) go here`,{when:`a request addressed to ${o}`,off:`upstreams.${o}.baseUrl`,local:w(p(l.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const o of e.destinations||[])o?.baseUrl&&r(p(o.baseUrl),`destination "${o.id||o.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${o.id||"it"}`,off:"destinations[]",local:w(p(o.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});r("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&r(p(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:w(p(e.ner.url).split(":")[0]),data:"the text being redacted"});const s=e.tts||{};if(s.provider==="openai"||s.provider==="elevenlabs"){const o=s.remote?.baseUrl?p(s.remote.baseUrl):s.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";r(o,`remote read-aloud voice (${s.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:s.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}a==="darwin"&&e.runtime?.heatwatch!==!1&&r("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const u=e.bridge?.url||"http://127.0.0.1:4319";return r(p(u),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),n}function A(e,{ledger:t=L(),version:a="",startedAt:n=null,env:r=process.env,managed:i=null}={}){return{ok:!0,version:a,since:n?new Date(n).toISOString():null,...i?{managed:i,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:S(e,r)}}function U(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const a of e.observed||[])t.push(` ${a.local?"[local] ":""}${a.scheme}://${a.host}:${a.port} ×${a.count} last ${a.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const a of e.declared||[])t.push(` ${a.local?"[local] ":""}${a.host}`),t.push(` ${a.purpose}`),t.push(` when: ${a.when}${a.off?` · off: ${a.off}`:""}`),a.data&&t.push(` sends: ${a.data}`);return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,a])=>a).map(([a,n])=>n===!0?a:`${a}=${n}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
2
+ `)}export{E as createEgressLedger,S as declaredEgress,A as egressAudit,L as egressLedger,U as formatAudit,R as installEgressLedger};
@@ -1 +1 @@
1
- function p(e){const a=String(e||"").trim();if(!a)return[];const t=[];let l="",n=null;for(const o of a)n?o===n?n=null:l+=o:o==='"'||o==="'"?n=o:/\s/.test(o)?l&&(t.push(l),l=""):l+=o;return l&&t.push(l),t}const f=Object.freeze([{id:"maxModelLen",label:"Context ceiling",kind:"number",what:"The longest prompt + answer the engine holds. Bounds the KV cache — without it the cache grows until the machine is full.",engines:["vllm","vllm-metal","llama"],default:({task:e})=>e==="chat"?8192:2048,min:512,max:262144,args:e=>["--max-model-len",String(e)],by:{llama:{default:({ramGB:e})=>e>0&&e<24?8192:16384,args:e=>["-c",String(e)]}}},{id:"prefixCache",label:"Prefix caching",kind:"bool",what:"Reuse the computed cache of a shared prompt prefix — the system prompt and tool list an agent resends every turn cost once.",engines:["vllm","vllm-metal","llama"],default:!0,args:e=>e?["--enable-prefix-caching"]:["--no-enable-prefix-caching"],by:{llama:{args:(e,{values:a})=>e?["--cache-reuse",String(a.maxModelLen>=32768?512:256)]:["--cache-reuse","0"]}}},{id:"kvCacheDtype",label:"KV cache precision",kind:"choice",options:["auto","fp8"],what:"fp8 halves the cache, so twice the context fits — on CUDA and ROCm; elsewhere leave auto.",engines:["vllm","llama"],default:"auto",backends:["cuda","rocm","metal","vulkan","cpu"],args:e=>e&&e!=="auto"?["--kv-cache-dtype",e]:[],by:{llama:{options:["auto","f16","q8_0"],what:"q8_0 halves the cache with little quality lost; auto takes q8_0 once the context is 32k or more.",args:(e,{values:a})=>e==="q8_0"||e==="auto"&&a.maxModelLen>=32768?["-ctk","q8_0","-ctv","q8_0"]:[]}}},{id:"gpuMemory",label:"GPU memory share",kind:"number",what:"The fraction of the accelerator’s memory the engine may take for weights and cache. Lower it when something else needs the GPU.",engines:["vllm"],default:.9,min:.1,max:.99,backends:["cuda","rocm","xpu"],args:e=>["--gpu-memory-utilization",String(e)]},{id:"gpuOffload",label:"GPU offload",kind:"bool",what:"Put every layer on the GPU (Metal, CUDA, Vulkan). Off runs the model on the CPU — only for a build without a GPU.",engines:["llama"],default:({backend:e})=>e!=="cpu",args:e=>["-ngl",e?"all":"0"]},{id:"flashAttention",label:"Flash attention",kind:"bool",what:"The fused attention kernel — less memory and faster on Metal and CUDA. Leave it on.",engines:["llama"],default:!0,args:e=>["-fa",e?"on":"off"]},{id:"threads",label:"Generation threads",kind:"number",what:"CPU threads for decoding. The performance cores — more only contends.",engines:["llama"],default:({perfCores:e})=>e||8,min:1,max:128,args:e=>["-t",String(e)]},{id:"batchThreads",label:"Prompt threads",kind:"number",what:"CPU threads for reading the prompt. All the physical cores.",engines:["llama"],default:({cores:e})=>e||8,min:1,max:128,args:e=>["-tb",String(e)]},{id:"speculative",label:"Speculative decoding",kind:"choice",options:["off","ngram"],what:"Draft tokens by n-gram lookup in the prompt and verify them in one pass — faster on code and edits, where the answer repeats the input.",engines:["vllm","vllm-metal","llama"],default:"off",tasks:["chat"],args:e=>e==="ngram"?["--speculative-config",JSON.stringify({method:"ngram",num_speculative_tokens:5,prompt_lookup_max:4})]:[],by:{llama:{options:["off","ngram","draft-mtp","draft"],default:({values:e})=>e?.draftModel?"draft-mtp":"off",what:"Draft tokens and verify them in one pass. ngram needs nothing; draft-mtp is the model’s own MTP head (name the draft file below — the `lm` recipe, ~0.75 accepted); draft is a small sibling model.",args:(e,{values:a,backend:t})=>e==="off"?[]:e==="ngram"?["--spec-type","ngram-simple","--spec-draft-n-max","3"]:a.draftModel?["--model-draft",a.draftModel,"--spec-type",e,"--spec-draft-n-max","3","--spec-draft-ngl",t==="cpu"?"0":"all",...a.maxModelLen>=32768?["--spec-draft-type-k","q8_0","--spec-draft-type-v","q8_0"]:[]]:[]}}},{id:"draftModel",label:"Draft model",kind:"text",what:"The GGUF the draft-mtp / draft modes draft with — the model’s MTP file (…-MTP.gguf) or a small sibling. A path, or a Hugging Face id.",engines:["llama"],default:"",tasks:["chat"],args:()=>[]},{id:"toolCalls",label:"Tool calling",kind:"choice",options:["off","hermes","llama3_json","mistral","pythonic","qwen3_coder"],what:"Parse the model’s tool calls into OpenAI tool_calls, so a harness sees tools and not text. Qwen3 and SmolLM3 speak hermes; Llama 3 llama3_json.",engines:["vllm","vllm-metal"],default:({model:e})=>/^(Qwen\/Qwen3|mlx-community\/Qwen3|HuggingFaceTB\/SmolLM3)/i.test(e||"")?"hermes":/Llama-3/i.test(e||"")?"llama3_json":"off",tasks:["chat"],args:e=>e&&e!=="off"?["--enable-auto-tool-choice","--tool-call-parser",e]:[]},{id:"reasoning",label:"Reasoning parser",kind:"choice",options:["off","qwen3","deepseek_r1"],what:"Split a thinking model’s reasoning from its answer, so the answer arrives clean and the thinking is a separate field.",engines:["vllm","vllm-metal","llama"],default:({model:e})=>/Qwen3/i.test(e||"")?"qwen3":"off",tasks:["chat"],args:e=>e&&e!=="off"?["--reasoning-parser",e]:[],by:{llama:{options:["auto","on","off"],default:"auto",label:"Thinking",what:"Whether the model thinks before answering (a template that supports it): on with a 1024-token budget returned as a separate field, off for direct answers, auto as the model decides.",args:e=>e==="on"?["--reasoning","on","--reasoning-budget","1024","--reasoning-format","deepseek"]:e==="off"?["--reasoning","off","--reasoning-budget","0"]:[]}}},{id:"chatTemplate",label:"Chat template",kind:"text",what:"A Jinja template file that overrides the model’s own — the fix when a fresh release ships a broken prompt template.",engines:["vllm","vllm-metal","llama","mlx"],default:"",tasks:["chat"],args:e=>e?["--chat-template",e]:[],by:{llama:{args:e=>e?["--chat-template-file",e]:[]}}},{id:"vision",label:"Vision projector",kind:"text",what:"The model’s multimodal projector (mmproj-*.gguf) — with it the server takes images; without it, more memory for text. A path.",engines:["llama"],default:"",tasks:["chat"],args:e=>e?["--mmproj",e,"--mmproj-offload"]:[]},{id:"maxSeqs",label:"Concurrent requests",kind:"number",what:"How many requests the engine batches at once. One user needs few; a team behind the gateway more — each costs cache.",engines:["vllm","vllm-metal","llama"],default:8,min:1,max:256,args:e=>["--max-num-seqs",String(e)],by:{llama:{default:1,what:"Server slots. One for a big model and a long context; more only when several people share this machine — each slot holds its own context.",args:e=>["-np",String(e)]}}},{id:"extraArgs",label:"Extra flags",kind:"args",what:"Anything else the engine takes, as you would type it after the command — the engine’s own documentation is the list. Appended last, so it wins over the rows above.",engines:["vllm","vllm-metal","llama","mlx"],default:"",args:e=>p(e)}]),x=e=>f.find(a=>a.id===e)||null;function b(e,a){const t=e.by?.[a];return t?{...e,...t,by:void 0}:e}function d(e,{task:a="chat",backend:t=null}={}){return f.filter(l=>l.engines.includes(e)&&(!l.tasks||l.tasks.includes(a))&&(!l.backends||!t||l.backends.includes(t))).map(l=>b(l,e))}function u(e,a){return typeof e.default=="function"?e.default(a):e.default}function w(e,a){if(!e)return null;if(e.kind==="bool")return typeof a=="boolean"?a:a==="true"?!0:a==="false"?!1:null;if(e.kind==="number"){const t=Number(a);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}if(e.kind==="choice")return e.options.includes(a)?a:null;if(e.kind==="text"){const t=String(a??"").trim();return t.length<=512&&!t.startsWith("-")&&!/[\s"'`$;|&<>]/.test(t)?t:null}if(e.kind==="args"){const t=String(a??"").trim();return t.length<=2e3&&!/[`$;|&<>\n]/.test(t)?t:null}return null}function y(e,a,t,l={}){const n={...a||{}},o=d(e,l);for(const[s,i]of Object.entries(t||{})){const r=o.find(h=>h.id===s);if(!r)return{error:`no tuning ${JSON.stringify(s)} for ${e}`};if(i==null){delete n[s];continue}const m=w(r,i);if(m===null)return{error:`${r.label}: ${r.kind==="choice"?`one of ${r.options.join(", ")}`:r.kind==="number"?`a number between ${r.min} and ${r.max}`:r.kind==="bool"?"on or off":r.kind==="args"?"flags as you would type them — no shell characters":"a plain path or id"}`};n[s]=m}return n}function c(e,a,t={}){const l={};for(const n of d(e,t))l[n.id]=a&&a[n.id]!==void 0?a[n.id]:u(n,{...t,values:{...a||{},...l}});return l}function v(e,a,t={}){const l=c(e,a,t),n=[];for(const o of d(e,t))n.push(...o.args(l[o.id],{...t,values:l}));return n}function S(e,a,t={}){const l=c(e,a,t);return d(e,t).map(n=>({id:n.id,label:n.label,what:n.what,kind:n.kind,...n.options?{options:n.options}:{},...n.kind==="number"?{min:n.min,max:n.max}:{},default:a&&a[n.id]!==void 0?u(n,{...t,values:l}):l[n.id],...a&&a[n.id]!==void 0?{value:a[n.id]}:{}}))}const M=Object.freeze({vllm:{label:"vLLM engine arguments",url:"https://docs.vllm.ai/en/latest/configuration/engine_args/"},"vllm-metal":{label:"vLLM engine arguments (vLLM-Metal takes the same)",url:"https://docs.vllm.ai/en/latest/configuration/engine_args/"},llama:{label:"llama-server flags",url:"https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md"},mlx:{label:"mlx_lm.server flags",url:"https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/SERVER.md"}}),k=Object.freeze([{id:"speed",label:"Fast chat",what:"Short questions, quick answers — the smallest context, the least memory.",ctx:({ramGB:e})=>e>0&&e<24?4096:8192,needGB:0},{id:"coding",label:"Coding",what:"A coding assistant’s room for a file and a conversation. The default.",ctx:({ramGB:e})=>e>0&&e<24?8192:16384,needGB:0},{id:"long",label:"Long context",what:"Several files or a long page at once — slower, the cache quantised to fit.",ctx:({ramGB:e})=>e>=36?32768:e>=24?16384:8192,needGB:24},{id:"xl",label:"Extra long",what:"A whole repository’s worth. An experiment under 64 GB: close other apps and watch memory.",ctx:({ramGB:e})=>e>=48?65536:32768,needGB:48}]);function _(e,a,t={}){const l=d(e,t);if((t.task||"chat")!=="chat"||!l.some(s=>s.id==="maxModelLen"))return[];const n=c(e,a,t);let o=!1;return k.map(s=>{const i=s.ctx(t),r={maxModelLen:i,...l.some(g=>g.id==="kvCacheDtype")?{kvCacheDtype:i>=32768?e==="llama"?"q8_0":t.backend==="cuda"||t.backend==="rocm"?"fp8":"auto":"auto"}:{}},m=!t.ramGB||t.ramGB>=s.needGB,h=!o&&n.maxModelLen===i;return h&&(o=!0),{id:s.id,label:s.label,what:s.what,patch:r,fits:m,...m?{}:{why:`needs ${s.needGB} GB of memory; this machine has ${t.ramGB}`},active:h}})}export{M as ENGINE_DOCS,k as PROFILES,f as TUNINGS,w as coerceTuning,b as forEngine,y as patchTunings,_ as profilesFor,c as resolveTunings,p as splitArgs,v as tuningArgs,u as tuningDefault,S as tuningRows,d as tuningsFor};
1
+ function p(e){const a=String(e||"").trim();if(!a)return[];const t=[];let l="",n=null;for(const o of a)n?o===n?n=null:l+=o:o==='"'||o==="'"?n=o:/\s/.test(o)?l&&(t.push(l),l=""):l+=o;return l&&t.push(l),t}const c=Object.freeze([{id:"maxModelLen",label:"Context ceiling",kind:"number",what:"The longest prompt + answer the engine holds. Bounds the KV cache — without it the cache grows until the machine is full.",engines:["vllm","vllm-metal","llama"],default:({task:e})=>e==="chat"?8192:2048,min:512,max:262144,args:e=>["--max-model-len",String(e)],by:{llama:{default:({ramGB:e})=>e>0&&e<24?8192:16384,args:e=>["-c",String(e)]}}},{id:"prefixCache",label:"Prefix caching",kind:"bool",what:"Reuse the computed cache of a shared prompt prefix — the system prompt and tool list an agent resends every turn cost once.",engines:["vllm","vllm-metal","llama"],default:!0,args:e=>e?["--enable-prefix-caching"]:["--no-enable-prefix-caching"],by:{llama:{args:(e,{values:a})=>e?["--cache-reuse",String(a.maxModelLen>=32768?512:256)]:["--cache-reuse","0"]}}},{id:"kvCacheDtype",label:"KV cache precision",kind:"choice",options:["auto","fp8"],what:"fp8 halves the cache, so twice the context fits — on CUDA and ROCm; elsewhere leave auto.",engines:["vllm","llama"],default:"auto",backends:["cuda","rocm","metal","vulkan","cpu"],args:e=>e&&e!=="auto"?["--kv-cache-dtype",e]:[],by:{llama:{options:["auto","f16","q8_0"],what:"q8_0 halves the cache with little quality lost; auto takes q8_0 once the context is 32k or more.",args:(e,{values:a})=>e==="q8_0"||e==="auto"&&a.maxModelLen>=32768?["-ctk","q8_0","-ctv","q8_0"]:[]}}},{id:"gpuMemory",label:"GPU memory share",kind:"number",what:"The fraction of the accelerator’s memory the engine may take for weights and cache. Lower it when something else needs the GPU.",engines:["vllm"],default:.9,min:.1,max:.99,backends:["cuda","rocm","xpu"],args:e=>["--gpu-memory-utilization",String(e)]},{id:"gpuOffload",label:"GPU offload",kind:"bool",what:"Put every layer on the GPU (Metal, CUDA, Vulkan). Off runs the model on the CPU — only for a build without a GPU.",engines:["llama"],default:({backend:e})=>e!=="cpu",args:e=>["-ngl",e?"all":"0"]},{id:"flashAttention",label:"Flash attention",kind:"bool",what:"The fused attention kernel — less memory and faster on Metal and CUDA. Leave it on.",engines:["llama"],default:!0,args:e=>["-fa",e?"on":"off"]},{id:"threads",label:"Generation threads",kind:"number",what:"CPU threads for decoding. The performance cores — more only contends.",engines:["llama"],default:({perfCores:e})=>e||8,min:1,max:128,args:e=>["-t",String(e)]},{id:"batchThreads",label:"Prompt threads",kind:"number",what:"CPU threads for reading the prompt. All the physical cores.",engines:["llama"],default:({cores:e})=>e||8,min:1,max:128,args:e=>["-tb",String(e)]},{id:"speculative",label:"Speculative decoding",kind:"choice",options:["off","ngram"],what:"Draft tokens by n-gram lookup in the prompt and verify them in one pass — faster on code and edits, where the answer repeats the input.",engines:["vllm","vllm-metal","llama"],default:"off",tasks:["chat"],args:e=>e==="ngram"?["--speculative-config",JSON.stringify({method:"ngram",num_speculative_tokens:5,prompt_lookup_max:4})]:[],by:{llama:{options:["off","ngram","draft-mtp","draft"],default:({values:e})=>e?.draftModel?"draft-mtp":"off",what:"Draft tokens and verify them in one pass. ngram needs nothing; draft-mtp is the model’s own MTP head (name the draft file below — the `lm` recipe, ~0.75 accepted); draft is a small sibling model.",args:(e,{values:a,backend:t})=>e==="off"?[]:e==="ngram"?["--spec-type","ngram-simple","--spec-draft-n-max","3"]:a.draftModel?["--model-draft",a.draftModel,"--spec-type",e,"--spec-draft-n-max","3","--spec-draft-ngl",t==="cpu"?"0":"all",...a.maxModelLen>=32768?["--spec-draft-type-k","q8_0","--spec-draft-type-v","q8_0"]:[]]:[]}}},{id:"draftModel",label:"Draft model",kind:"text",what:"The GGUF the draft-mtp / draft modes draft with — the model’s MTP file (…-MTP.gguf) or a small sibling. A path, or a Hugging Face id.",engines:["llama"],default:"",tasks:["chat"],args:()=>[]},{id:"toolCalls",label:"Tool calling",kind:"choice",options:["off","hermes","llama3_json","mistral","pythonic","qwen3_coder"],what:"Parse the model’s tool calls into OpenAI tool_calls, so a harness sees tools and not text. Qwen3 and SmolLM3 speak hermes; Llama 3 llama3_json.",engines:["vllm","vllm-metal"],default:({model:e})=>/^(Qwen\/Qwen3|mlx-community\/Qwen3|HuggingFaceTB\/SmolLM3)/i.test(e||"")?"hermes":/Llama-3/i.test(e||"")?"llama3_json":"off",tasks:["chat"],args:e=>e&&e!=="off"?["--enable-auto-tool-choice","--tool-call-parser",e]:[]},{id:"reasoning",label:"Reasoning parser",kind:"choice",options:["off","qwen3","deepseek_r1"],what:"Split a thinking model’s reasoning from its answer, so the answer arrives clean and the thinking is a separate field.",engines:["vllm","vllm-metal","llama","mlx"],default:({model:e})=>/Qwen3/i.test(e||"")?"qwen3":"off",tasks:["chat"],args:e=>e&&e!=="off"?["--reasoning-parser",e]:[],by:{mlx:{options:["off","on"],default:"off",label:"Thinking",what:"Whether a thinking model (Qwen3) reasons before answering. Off answers directly — faster, cooler, and enough for titles, topics and short replies.",args:e=>e==="on"?[]:["--chat-template-args",'{"enable_thinking":false}']},llama:{options:["auto","on","off"],default:"auto",label:"Thinking",what:"Whether the model thinks before answering (a template that supports it): on with a 1024-token budget returned as a separate field, off for direct answers, auto as the model decides.",args:e=>e==="on"?["--reasoning","on","--reasoning-budget","1024","--reasoning-format","deepseek"]:e==="off"?["--reasoning","off","--reasoning-budget","0"]:[]}}},{id:"chatTemplate",label:"Chat template",kind:"text",what:"A Jinja template file that overrides the model’s own — the fix when a fresh release ships a broken prompt template.",engines:["vllm","vllm-metal","llama","mlx"],default:"",tasks:["chat"],args:e=>e?["--chat-template",e]:[],by:{llama:{args:e=>e?["--chat-template-file",e]:[]}}},{id:"vision",label:"Vision projector",kind:"text",what:"The model’s multimodal projector (mmproj-*.gguf) — with it the server takes images; without it, more memory for text. A path.",engines:["llama"],default:"",tasks:["chat"],args:e=>e?["--mmproj",e,"--mmproj-offload"]:[]},{id:"maxSeqs",label:"Concurrent requests",kind:"number",what:"How many requests the engine batches at once. One user needs few; a team behind the gateway more — each costs cache.",engines:["vllm","vllm-metal","llama"],default:8,min:1,max:256,args:e=>["--max-num-seqs",String(e)],by:{llama:{default:1,what:"Server slots. One for a big model and a long context; more only when several people share this machine — each slot holds its own context.",args:e=>["-np",String(e)]}}},{id:"extraArgs",label:"Extra flags",kind:"args",what:"Anything else the engine takes, as you would type it after the command — the engine’s own documentation is the list. Appended last, so it wins over the rows above.",engines:["vllm","vllm-metal","llama","mlx"],default:"",args:e=>p(e)}]),x=e=>c.find(a=>a.id===e)||null;function b(e,a){const t=e.by?.[a];return t?{...e,...t,by:void 0}:e}function m(e,{task:a="chat",backend:t=null}={}){return c.filter(l=>l.engines.includes(e)&&(!l.tasks||l.tasks.includes(a))&&(!l.backends||!t||l.backends.includes(t))).map(l=>b(l,e))}function u(e,a){return typeof e.default=="function"?e.default(a):e.default}function w(e,a){if(!e)return null;if(e.kind==="bool")return typeof a=="boolean"?a:a==="true"?!0:a==="false"?!1:null;if(e.kind==="number"){const t=Number(a);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}if(e.kind==="choice")return e.options.includes(a)?a:null;if(e.kind==="text"){const t=String(a??"").trim();return t.length<=512&&!t.startsWith("-")&&!/[\s"'`$;|&<>]/.test(t)?t:null}if(e.kind==="args"){const t=String(a??"").trim();return t.length<=2e3&&!/[`$;|&<>\n]/.test(t)?t:null}return null}function y(e,a,t,l={}){const n={...a||{}},o=m(e,l);for(const[s,i]of Object.entries(t||{})){const r=o.find(h=>h.id===s);if(!r)return{error:`no tuning ${JSON.stringify(s)} for ${e}`};if(i==null){delete n[s];continue}const d=w(r,i);if(d===null)return{error:`${r.label}: ${r.kind==="choice"?`one of ${r.options.join(", ")}`:r.kind==="number"?`a number between ${r.min} and ${r.max}`:r.kind==="bool"?"on or off":r.kind==="args"?"flags as you would type them — no shell characters":"a plain path or id"}`};n[s]=d}return n}function f(e,a,t={}){const l={};for(const n of m(e,t))l[n.id]=a&&a[n.id]!==void 0?a[n.id]:u(n,{...t,values:{...a||{},...l}});return l}function v(e,a,t={}){const l=f(e,a,t),n=[];for(const o of m(e,t))n.push(...o.args(l[o.id],{...t,values:l}));return n}function S(e,a,t={}){const l=f(e,a,t);return m(e,t).map(n=>({id:n.id,label:n.label,what:n.what,kind:n.kind,...n.options?{options:n.options}:{},...n.kind==="number"?{min:n.min,max:n.max}:{},default:a&&a[n.id]!==void 0?u(n,{...t,values:l}):l[n.id],...a&&a[n.id]!==void 0?{value:a[n.id]}:{}}))}const _=Object.freeze({vllm:{label:"vLLM engine arguments",url:"https://docs.vllm.ai/en/latest/configuration/engine_args/"},"vllm-metal":{label:"vLLM engine arguments (vLLM-Metal takes the same)",url:"https://docs.vllm.ai/en/latest/configuration/engine_args/"},llama:{label:"llama-server flags",url:"https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md"},mlx:{label:"mlx_lm.server flags",url:"https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/SERVER.md"}}),k=Object.freeze([{id:"speed",label:"Fast chat",what:"Short questions, quick answers — the smallest context, the least memory.",ctx:({ramGB:e})=>e>0&&e<24?4096:8192,needGB:0},{id:"coding",label:"Coding",what:"A coding assistant’s room for a file and a conversation. The default.",ctx:({ramGB:e})=>e>0&&e<24?8192:16384,needGB:0},{id:"long",label:"Long context",what:"Several files or a long page at once — slower, the cache quantised to fit.",ctx:({ramGB:e})=>e>=36?32768:e>=24?16384:8192,needGB:24},{id:"xl",label:"Extra long",what:"A whole repository’s worth. An experiment under 64 GB: close other apps and watch memory.",ctx:({ramGB:e})=>e>=48?65536:32768,needGB:48}]);function M(e,a,t={}){const l=m(e,t);if((t.task||"chat")!=="chat"||!l.some(s=>s.id==="maxModelLen"))return[];const n=f(e,a,t);let o=!1;return k.map(s=>{const i=s.ctx(t),r={maxModelLen:i,...l.some(g=>g.id==="kvCacheDtype")?{kvCacheDtype:i>=32768?e==="llama"?"q8_0":t.backend==="cuda"||t.backend==="rocm"?"fp8":"auto":"auto"}:{}},d=!t.ramGB||t.ramGB>=s.needGB,h=!o&&n.maxModelLen===i;return h&&(o=!0),{id:s.id,label:s.label,what:s.what,patch:r,fits:d,...d?{}:{why:`needs ${s.needGB} GB of memory; this machine has ${t.ramGB}`},active:h}})}export{_ as ENGINE_DOCS,k as PROFILES,c as TUNINGS,w as coerceTuning,b as forEngine,y as patchTunings,M as profilesFor,f as resolveTunings,p as splitArgs,v as tuningArgs,u as tuningDefault,S as tuningRows,m as tuningsFor};
@@ -0,0 +1 @@
1
+ import{readFileSync as u}from"node:fs";import s from"node:path";const f="http://127.0.0.1:7878",c=1024*1024;async function m(n,{url:i=f,fetchImpl:t=globalThis.fetch,timeoutMs:r=1500}={}){if(!(n>0)||!t)return null;try{const o=await t(`${i}/v1/fit?need_gb=${(n/1024).toFixed(2)}`,{signal:AbortSignal.timeout(r)});if(!o.ok)return null;const e=await o.json();if(typeof e?.fits!="boolean")return null;const l=a=>Number.isFinite(a)?Math.round(a/c):null;return{fits:e.fits,needMB:l(e.neededBytes),availableMB:l(e.availableBytes),shortfallMB:l(e.shortfallBytes)||0,fitsGPULimit:e.fitsGPULimit??null,gpuWiredLimitMB:l(e.gpuWiredLimitBytes),close:Array.isArray(e.closeToFit)?e.closeToFit:[]}}catch{return null}}function _(n,i){if(!(i>0))return 0;let t;try{t=JSON.parse(u(n,"utf8"))}catch{return null}t=t.text_config||t;const r=t.num_hidden_layers,o=t.num_attention_heads,e=t.num_key_value_heads||o,l=t.head_dim||(t.hidden_size&&o?t.hidden_size/o:0);if(!(r>0&&e>0&&l>0))return null;const a=Number.isInteger(t.full_attention_interval)&&t.full_attention_interval>0?Math.ceil(r/t.full_attention_interval):r;return Math.ceil(2*a*e*l*2*i/c)}function y(n,i){try{const t=s.join(n,"hub",`models--${String(i).replace("/","--")}`),r=u(s.join(t,"refs","main"),"utf8").trim();return r?s.join(t,"snapshots",r,"config.json"):null}catch{return null}}function p({ramMB:n,kvMB:i=0}){return Math.ceil(((n||0)+(i||0))*1.1)}export{f as HEATWATCH_URL,y as cachedConfigPath,_ as kvCacheMB,m as liveFit,p as needMB};
@@ -1 +1 @@
1
- const s="0.29.0",o=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}`,o.cpu]:[o.cpu]}const L=Object.freeze({command:"brew tap vllm-project/vllm-metal https://github.com/vllm-project/vllm-metal && brew install vllm-project/vllm-metal/vllm-metal",steps:[["brew","tap","vllm-project/vllm-metal","https://github.com/vllm-project/vllm-metal"],["brew","install","vllm-project/vllm-metal/vllm-metal"]],note:"vLLM on the Apple Silicon GPU through MLX (vLLM-Metal, community maintained, v0.2). macOS Sonoma or later. Then `vllm serve` is on PATH; the Runtime starts it here, under the sandbox."});function m(e,t){return e==="cuda"?t==="podman"?["--device","nvidia.com/gpu=all","--security-opt=label=disable"]:["--runtime","nvidia","--gpus","all","--ipc=host"]:e==="rocm"?["--device","/dev/kfd","--device","/dev/dri","--group-add","video","--security-opt","seccomp=unconfined"]:e==="xpu"?["--device","/dev/dri"]:[]}async function x({exec:e,platform:t=process.platform,arch:n=process.arch}={}){const l=async(a,i)=>{try{const r=await e(a,i,{timeout:8e3});return r&&!/error|not found|no devices/i.test(String(r.stdout||"")+String(r.stderr||""))}catch{return!1}};return t==="darwin"&&n==="arm64"?"apple":await l("nvidia-smi",["-L"])?"cuda":t==="linux"&&await l("rocm-smi",["--showid"])?"rocm":t==="linux"&&await l("sycl-ls",[])?"xpu":null}function M({platform:e=process.platform,arch:t=process.arch,accelerator:n=null,engine:l=null,vllmOnPath:a=!1,containerOnly:i=!1}={}){return e==="darwin"&&(t==="arm64"||n==="apple")&&i?{backend:"cpu",kind:"container",image:o.cpu,sources:h(t),recipe:"vllm-cpu",devices:[],for:"an embedding model, or a whisper transcriber — the jobs the Metal engines cannot serve",speed:"slow: CPU only, no GPU from the VM; a 90-minute build first",notFor:"chat — use llama.cpp, MLX or vLLM-Metal for that",why:"A container on a Mac is CPU-only (the GPU is not reachable from the VM).",warn:"On Apple Silicon, vLLM-Metal is the engine that uses the GPU — run that service instead; this one is for trying the CPU build itself."}:e==="darwin"&&(t==="arm64"||n==="apple")?{backend:"metal",kind:"native",runner:"vllm serve",install:L,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.",...a?{}:{warn:"`vllm` is not on PATH — install vLLM-Metal (the command beside this), then Run."}}:l?n==="cuda"?{backend:"cuda",kind:"container",image:o.cuda,devices:m("cuda",l),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":""}.`,...l==="podman"&&e==="linux"?{warn:"Podman needs the NVIDIA Container Toolkit CDI spec (nvidia-ctk cdi generate) for --device nvidia.com/gpu=all."}:{}}:n==="rocm"&&e==="linux"?{backend:"rocm",kind:"container",image:o.rocm,devices:m("rocm",l),for:"chat, embeddings, transcription",speed:"fast: the GPU, batched",why:"AMD GPU found (rocm-smi): vLLM ROCm image."}:n==="xpu"&&e==="linux"?{backend:"xpu",kind:"container",image:o.xpu,devices:m("xpu",l),for:"chat, embeddings, transcription",speed:"fast: the GPU",why:"Intel GPU found (sycl-ls): vLLM XPU image."}:{backend:"cpu",kind:"container",image:o.cpu,sources:h(t),recipe:"vllm-cpu",devices:[],for:"an embedding model or a whisper transcriber; a small chat model to try",speed:`slow: CPU only${t==="x64"?"":"; a 90-minute build first"}`,why:`No accelerator found: vLLM’s CPU build (${t}). Small models only; slow.`,warn:"CPU inference — a 0.6B chat model is usable, anything larger wants a GPU."}:{backend:n==="cuda"?"cuda":n==="rocm"?"rocm":n==="xpu"?"xpu":"cpu",kind:"container",image:null,devices:[],why:"No container engine yet — Settings › Runtime has the install door.",warn:"no container engine"}}const f=Object.freeze({darwin:{command:"brew install llama.cpp",steps:[["brew","install","llama.cpp"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Homebrew’s build has Metal on."},win32:{command:"winget install --id ggml.llamacpp -e",steps:[["winget","install","--id","ggml.llamacpp","-e","--accept-source-agreements","--accept-package-agreements"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Or a release zip from GitHub (the CUDA build for an NVIDIA GPU)."},linux:{command:'curl -fsSL https://github.com/ggml-org/llama.cpp/releases/latest -o /dev/null && echo "download the release for your GPU"',url:"https://github.com/ggml-org/llama.cpp/releases",note:"A release build for the GPU (CUDA, Vulkan) or the CPU build; or build from source."}});function y({platform:e=process.platform,arch:t=process.arch,accelerator:n=null,llamaOnPath:l=!1}={}){const a=e==="darwin"&&t==="arm64"?"metal":n==="cuda"?"cuda":n==="rocm"?"rocm":n==="xpu"?"vulkan":"cpu",i=a==="metal"?"Apple Silicon: llama.cpp on the Metal GPU, all layers offloaded":a==="cpu"?"no accelerator found: llama.cpp on the CPU — a small quantised model runs at a usable pace":`llama.cpp with the ${a.toUpperCase()} build, all layers offloaded`,r=f[e]||f.linux;return{backend:a,kind:"native",runner:"llama-server",install:r,why:i,for:"chat and vision — the largest choice of models (GGUF), your own .gguf files, the MTP draft that makes a big model fast",speed:a==="cpu"?"usable: the CPU with a 4-bit model":`fast: the ${a==="metal"?"Apple":a.toUpperCase()} GPU`,...l?{}:{warn:"`llama-server` is not on PATH — install llama.cpp (the command beside this), then Run."}}}async function P({exec:e,platform:t=process.platform,totalmem:n=()=>0,cpus:l=()=>[]}={}){const a=Math.round(n()/1073741824),i=l().length||0;let r=Math.max(1,Math.floor(i/2))||1,c=r;if(t==="darwin"&&e){const p=async b=>{try{const w=await e("sysctl",["-n",b]),d=Number(String(w?.stdout||"").trim());return d>0?d:0}catch{return 0}},[u,g]=await Promise.all([p("hw.physicalcpu"),p("hw.perflevel0.physicalcpu")]);u&&(r=u),c=g||r}else i&&(r=i,c=Math.min(i,8));return{ramGB:a,cores:r,perfCores:c}}const v=Object.freeze({command:"uv tool install mlx-lm # or: pip3 install --user mlx-lm",steps:[["uv","tool","install","mlx-lm"]],fallback:[["pip3","install","--user","mlx-lm"]],url:"https://github.com/ml-explore/mlx-lm",note:"Needs uv or Python 3.10+; puts mlx_lm.server on PATH."});function U({platform:e=process.platform,arch:t=process.arch,mlxOnPath:n=!1}={}){return e==="darwin"&&t==="arm64"?{backend:"metal",kind:"native",runner:"mlx_lm.server",install:v,for:"chat — Apple’s own framework, the smallest install",speed:"fast: the Apple GPU",notFor:"vision, embeddings, transcription",why:"Apple Silicon: MLX on the GPU with unified memory — the lightest engine for a Mac.",...n?{}:{warn:"`mlx_lm.server` is not on PATH — install mlx-lm (the command beside this), then Run."}}:{backend:"none",kind:"native",runner:"mlx_lm.server",why:"MLX runs on Apple Silicon only.",install:v}}function A({platform:e=process.platform,arch:t=process.arch,accelerator:n=null}={}){return e==="darwin"&&t==="arm64"?{engine:"mlx",why:"Apple Silicon: MLX — Apple’s own framework on the GPU with unified memory, the smallest install and the lightest engine for a Mac. llama.cpp on Metal is the alternative when you need vision, embeddings or a GGUF model."}:n==="cuda"||n==="rocm"||n==="xpu"?{engine:"vllm",why:`${n.toUpperCase()} GPU: vLLM in a container serves a full-precision model at speed, with batching for several users.`}:{engine:"llama",why:"No GPU found: llama.cpp with a 4-bit model is what runs well on a CPU."}}export{f as LLAMA_INSTALL,v as MLX_INSTALL,o as VLLM_IMAGES,L as VLLM_METAL_INSTALL,s as VLLM_VERSION,x as detectAccelerator,m as deviceArgs,P as hostShape,M as pickInferenceEngine,y as pickLlamaEngine,U as pickMlxEngine,A as recommendEngine,h as vllmCpuSources};
1
+ const s="0.29.0",i=Object.freeze({cuda:`docker.io/vllm/vllm-openai:v${s}`,rocm:`docker.io/vllm/vllm-openai-rocm:v${s}`,xpu:`docker.io/vllm/vllm-openai-xpu:v${s}`,cpu:"ghcr.io/chatpanel/vllm-cpu:latest"});function h(e){return e==="x64"||e==="amd64"?[`public.ecr.aws/q9t5s3a7/vllm-cpu-release-repo:v${s}`,i.cpu]:[i.cpu]}const y=Object.freeze({command:"brew tap vllm-project/vllm-metal https://github.com/vllm-project/vllm-metal && brew install vllm-project/vllm-metal/vllm-metal",steps:[["brew","tap","vllm-project/vllm-metal","https://github.com/vllm-project/vllm-metal"],["brew","install","vllm-project/vllm-metal/vllm-metal"]],note:"vLLM on the Apple Silicon GPU through MLX (vLLM-Metal, community maintained, v0.2). macOS Sonoma or later. Then `vllm serve` is on PATH; the Runtime starts it here, under the sandbox."});function m(e,t){return e==="cuda"?t==="podman"?["--device","nvidia.com/gpu=all","--security-opt=label=disable"]:["--runtime","nvidia","--gpus","all","--ipc=host"]:e==="rocm"?["--device","/dev/kfd","--device","/dev/dri","--group-add","video","--security-opt","seccomp=unconfined"]:e==="xpu"?["--device","/dev/dri"]:[]}async function L({exec:e,platform:t=process.platform,arch:n=process.arch}={}){const a=async(l,o)=>{try{const r=await e(l,o,{timeout:8e3});return r&&!/error|not found|no devices/i.test(String(r.stdout||"")+String(r.stderr||""))}catch{return!1}};return t==="darwin"&&n==="arm64"?"apple":await a("nvidia-smi",["-L"])?"cuda":t==="linux"&&await a("rocm-smi",["--showid"])?"rocm":t==="linux"&&await a("sycl-ls",[])?"xpu":null}function x({platform:e=process.platform,arch:t=process.arch,accelerator:n=null,engine:a=null,vllmOnPath:l=!1,containerOnly:o=!1}={}){return e==="darwin"&&(t==="arm64"||n==="apple")&&o?{backend:"cpu",kind:"container",image:i.cpu,sources:h(t),recipe:"vllm-cpu",devices:[],for:"an embedding model, or a whisper transcriber — the jobs the Metal engines cannot serve",speed:"slow: CPU only, no GPU from the VM; a 90-minute build first",notFor:"chat — use llama.cpp, MLX or vLLM-Metal for that",why:"A container on a Mac is CPU-only (the GPU is not reachable from the VM).",warn:"On Apple Silicon, vLLM-Metal is the engine that uses the GPU — run that service instead; this one is for trying the CPU build itself."}:e==="darwin"&&(t==="arm64"||n==="apple")?{backend:"metal",kind:"native",runner:"vllm serve",install:y,for:"chat, with vLLM’s server and API (tool-call and reasoning parsers)",speed:"fast: the Apple GPU through MLX",notFor:"embeddings or transcription — the container for those",why:"Apple Silicon: vLLM-Metal on the host GPU (MLX underneath) — a container here is CPU-only.",...l?{}:{warn:"`vllm` is not on PATH — install vLLM-Metal (the command beside this), then Run."}}:a?n==="cuda"?{backend:"cuda",kind:"container",image:i.cuda,devices:m("cuda",a),for:"chat, embeddings, transcription — full precision, batched for several users",speed:"fast: the GPU, batched",why:`NVIDIA GPU found (nvidia-smi): vLLM ${s} CUDA image${e==="win32"?", through WSL2’s GPU passthrough":""}.`,...a==="podman"&&e==="linux"?{warn:"Podman needs the NVIDIA Container Toolkit CDI spec (nvidia-ctk cdi generate) for --device nvidia.com/gpu=all."}:{}}:n==="rocm"&&e==="linux"?{backend:"rocm",kind:"container",image:i.rocm,devices:m("rocm",a),for:"chat, embeddings, transcription",speed:"fast: the GPU, batched",why:"AMD GPU found (rocm-smi): vLLM ROCm image."}:n==="xpu"&&e==="linux"?{backend:"xpu",kind:"container",image:i.xpu,devices:m("xpu",a),for:"chat, embeddings, transcription",speed:"fast: the GPU",why:"Intel GPU found (sycl-ls): vLLM XPU image."}:{backend:"cpu",kind:"container",image:i.cpu,sources:h(t),recipe:"vllm-cpu",devices:[],for:"an embedding model or a whisper transcriber; a small chat model to try",speed:`slow: CPU only${t==="x64"?"":"; a 90-minute build first"}`,why:`No accelerator found: vLLM’s CPU build (${t}). Small models only; slow.`,warn:"CPU inference — a 0.6B chat model is usable, anything larger wants a GPU."}:{backend:n==="cuda"?"cuda":n==="rocm"?"rocm":n==="xpu"?"xpu":"cpu",kind:"container",image:null,devices:[],why:"No container engine yet — Settings › Runtime has the install door.",warn:"no container engine"}}const f=Object.freeze({darwin:{command:"brew install llama.cpp",steps:[["brew","install","llama.cpp"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Homebrew’s build has Metal on."},win32:{command:"winget install --id ggml.llamacpp -e",steps:[["winget","install","--id","ggml.llamacpp","-e","--accept-source-agreements","--accept-package-agreements"]],url:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md",note:"Or a release zip from GitHub (the CUDA build for an NVIDIA GPU)."},linux:{command:'curl -fsSL https://github.com/ggml-org/llama.cpp/releases/latest -o /dev/null && echo "download the release for your GPU"',url:"https://github.com/ggml-org/llama.cpp/releases",note:"A release build for the GPU (CUDA, Vulkan) or the CPU build; or build from source."}});function M({platform:e=process.platform,arch:t=process.arch,accelerator:n=null,llamaOnPath:a=!1}={}){const l=e==="darwin"&&t==="arm64"?"metal":n==="cuda"?"cuda":n==="rocm"?"rocm":n==="xpu"?"vulkan":"cpu",o=l==="metal"?"Apple Silicon: llama.cpp on the Metal GPU, all layers offloaded":l==="cpu"?"no accelerator found: llama.cpp on the CPU — a small quantised model runs at a usable pace":`llama.cpp with the ${l.toUpperCase()} build, all layers offloaded`,r=f[e]||f.linux;return{backend:l,kind:"native",runner:"llama-server",install:r,why:o,for:"chat and vision — the largest choice of models (GGUF), your own .gguf files, the MTP draft that makes a big model fast",speed:l==="cpu"?"usable: the CPU with a 4-bit model":`fast: the ${l==="metal"?"Apple":l.toUpperCase()} GPU`,...a?{}:{warn:"`llama-server` is not on PATH — install llama.cpp (the command beside this), then Run."}}}async function k({exec:e,platform:t=process.platform,totalmem:n=()=>0,cpus:a=()=>[]}={}){const l=Math.round(n()/1073741824),o=a().length||0;let r=Math.max(1,Math.floor(o/2))||1,c=r;if(t==="darwin"&&e){const p=async w=>{try{const b=await e("sysctl",["-n",w]),u=Number(String(b?.stdout||"").trim());return u>0?u:0}catch{return 0}},[d,g]=await Promise.all([p("hw.physicalcpu"),p("hw.perflevel0.physicalcpu")]);d&&(r=d),c=g||r}else o&&(r=o,c=Math.min(o,8));return{ramGB:l,cores:r,perfCores:c}}const v=Object.freeze({command:"uv tool install mlx-lm # or: pip3 install --user mlx-lm",steps:[["uv","tool","install","mlx-lm"]],fallback:[["pip3","install","--user","mlx-lm"]],url:"https://github.com/ml-explore/mlx-lm",note:"Needs uv or Python 3.10+; puts mlx_lm.server on PATH."});function P({platform:e=process.platform,arch:t=process.arch,mlxOnPath:n=!1}={}){return e==="darwin"&&t==="arm64"?{backend:"metal",kind:"native",runner:"mlx_lm.server",install:v,for:"chat — Apple’s own framework, the smallest install",speed:"fast: the Apple GPU",notFor:"vision, embeddings, transcription",why:"Apple Silicon: MLX on the GPU with unified memory — the lightest engine for a Mac.",...n?{}:{warn:"`mlx_lm.server` is not on PATH — install mlx-lm (the command beside this), then Run."}}:{backend:"none",kind:"native",runner:"mlx_lm.server",why:"MLX runs on Apple Silicon only.",install:v}}function U({platform:e=process.platform,arch:t=process.arch,osMajor:n=0,appleOnPath:a=!1,appleInstall:l=null}={}){const o={kind:"native",runner:"chatpanel-apple-model",...l?{install:l}:{}};return e==="darwin"&&t==="arm64"?n<25?{...o,backend:"none",why:"Apple’s on-device model needs macOS 26 or later."}:{...o,backend:"apple",for:"titles, topics, short answers — the system keeps the model, nothing stays loaded",speed:"quick for short text; the Mac decides when the model is in memory",notFor:"long chats (a 4,096-token window), images, tools",why:"Apple Silicon on macOS 26: Apple’s own model, which the system loads when asked and frees when not — the lightest way to run a model on a Mac.",...a?{}:{warn:l?.steps?.length?"The helper is not built in this checkout yet — Install builds it.":"The helper is not in this install — it comes with the gateway from npm and the desktop app."}}:{...o,backend:"none",why:"Apple’s on-device model runs on Apple Silicon Macs only."}}function A({platform:e=process.platform,arch:t=process.arch,accelerator:n=null}={}){return e==="darwin"&&t==="arm64"?{engine:"mlx",why:"Apple Silicon: MLX — Apple’s own framework on the GPU with unified memory, the smallest install and the lightest engine for a Mac. llama.cpp on Metal is the alternative when you need vision, embeddings or a GGUF model."}:n==="cuda"||n==="rocm"||n==="xpu"?{engine:"vllm",why:`${n.toUpperCase()} GPU: vLLM in a container serves a full-precision model at speed, with batching for several users.`}:{engine:"llama",why:"No GPU found: llama.cpp with a 4-bit model is what runs well on a CPU."}}export{f as LLAMA_INSTALL,v as MLX_INSTALL,i as VLLM_IMAGES,y as VLLM_METAL_INSTALL,s as VLLM_VERSION,L as detectAccelerator,m as deviceArgs,k as hostShape,U as pickAppleEngine,x as pickInferenceEngine,M as pickLlamaEngine,P as pickMlxEngine,A as recommendEngine,h as vllmCpuSources};
package/src/link-host.js CHANGED
@@ -1 +1 @@
1
- import{readFileSync as q,writeFileSync as ee,renameSync as te,mkdirSync as ne,chmodSync as oe}from"node:fs";import{dirname as re,join as ae}from"node:path";import B from"node:os";import{createLinkEndpoint as se}from"@chatpanel/events/link-connect.js";import{noiseCrypto as ie}from"@chatpanel/events/link-noise.js";import{pairingUri as ce,admissionToken as j,admissionVerifier as J,toB64url as $,fromB64url as I}from"@chatpanel/events/link-protocol.js";import{qrSvg as le}from"@chatpanel/events/qr.js";import{verifyEntitlement as pe,licenseFromPayload as de,can as me,FEATURE_TIER as V}from"@chatpanel/events/entitlement.js";const ue="https://link.chatpanel.net",G=10*6e4,fe=3e4,R=[1e3,2e3,5e3,1e4,3e4,6e4],he=40,ye=16e3,ke=/(^|\n): ?ping\n\n/g,ge=4,we=[/^\/v1\/models(?:\/|$|\?)/,/^\/v1\/chat\/completions$/,/^\/v1\/messages$/,/^\/v1\/audio\/(?:transcriptions|speech)$/,/^\/v1\/history\/(?:search|smart-search|get|list|related|status)(?:$|\?)/,/^\/v1\/history\/(?:records|stream)(?:$|\?)/,/^\/v1\/memory\/(?:recall|list|remember)(?:$|\?)/,/^\/v1\/(?:research|search|read|rerank|decide|capabilities|fusions)(?:$|\?)/,/^\/v1\/status$/],Ee=l=>we.some(i=>i.test(String(l||""))),H="x-chatpanel-entitlement",z="x-chatpanel-install",Y=(l,i)=>{for(const[m,y]of Object.entries(l||{}))if(m.toLowerCase()===i)return String(y||"");return""};async function Se(l,{now:i=Date.now()}={}){if(!V.link||V.link==="free")return!1;const m=Y(l,H),y=Y(l,z);if(!m||!y)return!1;const A=await pe(m,y,{now:i});return!!A&&me(de(A,{at:i}),"link",0,i)}function Te(){return ae(B.homedir(),".chatpanel","link.json")}function ve(l){try{const i=JSON.parse(q(l,"utf8"));return{v:1,key:i.key||null,rooms:Array.isArray(i.rooms)?i.rooms:[]}}catch{return{v:1,key:null,rooms:[]}}}function W(l,i){ne(re(l),{recursive:!0});const m=`${l}.tmp`;ee(m,JSON.stringify(i,null,2),{mode:384});try{oe(m,384)}catch{}te(m,l)}function Ne({relay:l=ue,name:i=B.hostname(),dispatch:m,path:y=Te(),fetch:A=globalThis.fetch,WebSocket:Q=globalThis.WebSocket,now:u=()=>Date.now(),random:U=f=>globalThis.crypto.getRandomValues(new Uint8Array(f)),crypto:_=ie(),log:x=()=>{},mayLink:X=Se}={}){const f=new URL(l).origin;if(!/^https:/.test(f)&&!/^http:\/\/127\.0\.0\.1(?::\d+)?$/.test(f))throw new Error("link: the relay must be https");let p=ve(y);const h=new Map;let g=null;async function b(){return g||(p.key?g=await _.keyPairFromPrivate(I(p.key)):(g=await _.generateKeyPair(),p.key=$(g.raw),W(y,p)),g)}const L=e=>p.rooms.find(t=>t.room===e)||null,P=()=>W(y,p),K=async(e,t,n,a)=>{try{return await A(`${f}/v1/room/${e}`,{method:t,headers:{authorization:`Bearer ${n}`,...a?{"content-type":"application/json"}:{}},body:a?JSON.stringify(a):void 0})}catch(c){const r=c?.cause?.code||"",o=r==="ENOTFOUND"?"this computer cannot look up its name (a VPN or DNS that does not know it yet)":r?`${r}`:c?.message||"no answer";throw new Error(`cannot reach the Link relay at ${new URL(f).host}: ${o}`)}};async function Z(e,t,n){if(!Ee(t.path))return await n.head(403,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:"link: a paired phone may not call this",type:"forbidden"}})),n.end();if(!await X(t.headers,{now:u()}))return await n.head(402,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:"ChatPanel Link needs Pro on this phone — upgrade on the phone, or restore its Pro under Settings › Plan",type:"pro_required"}})),n.end();const a={};for(const[s,d]of Object.entries(t.headers||{}))s.toLowerCase()!==H&&s.toLowerCase()!==z&&(a[s]=d);const c=t.method==="GET"?void 0:await t.body.bytes(),r=await m({method:t.method,path:t.path,headers:a,body:c,device:e.room}),o={};if(r.headers?.forEach?.((s,d)=>{o[d]=s}),await n.head(r.status,o),r.body){let s=[],d=0,S=u();const T=async()=>{if(!d)return;const k=new Uint8Array(d);let w=0;for(const v of s)k.set(v,w),w+=v.length;s=[],d=0,S=u(),await n.write(k)},E=/event-stream/.test(String(r.headers?.get?.("content-type")||""));for await(const k of r.body){if(n.cancelled)break;let w=k instanceof Uint8Array?k:new TextEncoder().encode(String(k));if(E){const v=new TextDecoder().decode(w);if(v.includes(": ping")){const F=v.replace(ke,"$1");if(!F)continue;w=new TextEncoder().encode(F)}}s.push(w),d+=w.length,(d>=ye||u()-S>=he)&&await T()}await T()}return n.end()}async function N(e){const t=h.get(e.room)||{attempts:0,stopped:!1,online:!1};if(h.set(e.room,t),t.stopped)return;const n=await b(),a=e.pending&&e.pending.expiresAt>u()?e.pending:null;if(!e.phoneKey&&!a){O(e.room,"the pairing code expired");return}const c=`${f.replace(/^http/,"ws")}/v1/room/${e.room}`;let r;try{r=new Q(c,["chatpanel-link.v1",e.token])}catch(o){D(e,o?.message);return}r.binaryType="arraybuffer",t.ws=r,t.endpoint=se({side:"laptop",keyPair:n,crypto:_,psk:e.phoneKey?null:I(a.psk),peerKey:e.phoneKey?I(e.phoneKey):null,sendBytes:o=>{try{r.send(o)}catch{}},onRequest:(o,s)=>Z(e,o,s),onSession:(o,s)=>{t.online=!0,t.attempts=0,e.lastSeen=u(),s.paired&&(e.phoneKey=$(s.peerKey),e.name=s.name||e.name||"Phone",e.pairedAt=u(),e.pending=null,x(`link: paired ${e.name}`)),P()},onEnd:()=>{t.online=!1}}),r.onopen=()=>{if(t.stopped||h.get(e.room)!==t){try{r.close(1e3,"stopped")}catch{}return}clearInterval(t.keepalive),t.keepalive=setInterval(()=>{try{r.send("ping")}catch{}},fe),t.keepalive.unref?.()},r.onmessage=o=>typeof o.data=="string"?t.endpoint.onText(o.data):t.endpoint.onBinary(new Uint8Array(o.data)),r.onclose=o=>{if(clearInterval(t.keepalive),t.online=!1,t.endpoint?.close("socket closed"),!t.stopped){if(o?.code===4003||o?.code===4004){C(e.room,"the relay removed the room");return}D(e,o?.code===4001?"replaced":o?.code===4008?"over the relay's budget":`closed ${o?.code||""}`,o?.code===4001?5:o?.code===4008?ge:null)}},r.onerror=()=>{}}function D(e,t,n=null){const a=h.get(e.room);if(!a||a.stopped)return;const c=n??Math.min(a.attempts,R.length-1);a.attempts++,clearTimeout(a.timer),a.timer=setTimeout(()=>N(e),R[c]),a.timer.unref?.(),x(`link: ${t}; again in ${R[c]/1e3}s`)}function M(e){const t=h.get(e);if(t){t.stopped=!0,clearTimeout(t.timer),clearInterval(t.keepalive),t.endpoint?.close("stopped");try{t.ws?.close(1e3,"stopped")}catch{}h.delete(e)}}function O(e,t){const n=L(e);n&&!n.phoneKey&&K(e,"DELETE",n.token).catch(()=>{}),C(e,t)}function C(e,t){M(e),p.rooms=p.rooms.filter(n=>n.room!==e),P(),x(`link: ${t}`)}return{async pair({name:e=i}={}){const t=await b(),n=U(16),a=U(32),c=$(n),r=await j(a,n,"laptop"),o=await j(a,n,"phone"),s=await K(c,"PUT",r,{laptop:await J(r),phone:await J(o)});if(s.status!==200&&s.status!==201)throw new Error(`link: the relay refused the room (${s.status})`);for(const E of p.rooms.filter(k=>!k.phoneKey))O(E.room,"a new pairing code replaced this one");const d=u()+G,S={room:c,token:r,phoneKey:null,name:"",pairedAt:null,lastSeen:null,pending:{psk:$(a),expiresAt:d}};p.rooms.push(S),P();const T=ce({relay:f,room:n,key:t.publicKey,secret:a,name:String(e||"").slice(0,60)});return N(S),setTimeout(()=>{const E=L(c);E&&!E.phoneKey&&O(c,"the pairing code expired")},G+1e3).unref?.(),{uri:T,svg:le(T,{ecc:"M"}),expiresAt:d,room:c}},status(){return{relay:f,devices:p.rooms.filter(e=>e.phoneKey).map(e=>({id:e.room,name:e.name||"Phone",pairedAt:e.pairedAt,lastSeen:e.lastSeen,online:!!h.get(e.room)?.online})),pairing:p.rooms.filter(e=>!e.phoneKey&&e.pending?.expiresAt>u()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,connected:!!h.get(e.room)?.online}))[0]||null}},async remove(e){const t=L(e);if(!t)return!1;try{await K(e,"DELETE",t.token)}catch{}return C(e,"removed"),!0},async start(){if(p.rooms.length){await b();for(const e of p.rooms)N(e)}},stop(){for(const e of[...h.keys()])M(e)},get publicKey(){return g?.publicKey||null}}}export{we as COMPANION_PATHS,ue as DEFAULT_RELAY,H as ENTITLEMENT_HEADER,z as INSTALL_HEADER,G as PAIRING_TTL_MS,Ee as companionMay,Ne as createLinkHost,Te as defaultLinkPath,Se as phoneMayLink};
1
+ import{readFileSync as fe,writeFileSync as me,renameSync as ye,mkdirSync as he,chmodSync as ge}from"node:fs";import{dirname as ke,join as we}from"node:path";import X from"node:os";import{createLinkEndpoint as Se}from"@chatpanel/events/link-connect.js";import{noiseCrypto as Ee}from"@chatpanel/events/link-noise.js";import{pairingUri as Te,admissionToken as q,admissionVerifier as j,toB64url as O,fromB64url as J,coalesceChunks as ve}from"@chatpanel/events/link-protocol.js";import{linkPaths as ee,LINK_ROUTES as _e,LINK_TUNNEL_ROOM_PATH as be,tunnelSetup as $e}from"@chatpanel/events/link-routes.js";import{timingSafeEqual as Ae}from"node:crypto";import{acceptWebSocket as Ne,refuseUpgrade as H}from"./ws-accept.js";import{qrSvg as Le}from"@chatpanel/events/qr.js";import{verifyEntitlement as Pe,licenseFromPayload as xe,can as Ke,FEATURE_TIER as te}from"@chatpanel/events/entitlement.js";const qe="https://link.chatpanel.net",ne=10*6e4,Oe=3e4,G=[1e3,2e3,5e3,1e4,3e4,6e4],Re=30,R="chatpanel-link.v1",Ue=/(^|\n): ?ping\n\n/g,Ie=4,Ce=[/^\/v1\/models(?:\/|$|\?)/,/^\/v1\/chat\/completions$/,/^\/v1\/messages$/,/^\/v1\/audio\/(?:transcriptions|speech)$/,/^\/v1\/history\/(?:search|smart-search|get|list|related|status)(?:$|\?)/,/^\/v1\/history\/(?:records|stream)(?:$|\?)/,/^\/v1\/memory\/(?:recall|list|remember)(?:$|\?)/,/^\/v1\/(?:research|search|read|rerank|decide|capabilities|fusions)(?:$|\?)/,/^\/v1\/status$/,/^\/v1\/link\/routes$/,/^\/v1\/agent-sessions(?:\/read|\/adopt|\/catchup)?$/],Me=u=>Ce.some(p=>p.test(String(u||""))),oe="x-chatpanel-entitlement",re="x-chatpanel-install",ae=(u,p)=>{for(const[h,v]of Object.entries(u||{}))if(h.toLowerCase()===p)return String(v||"");return""};async function Be(u,{now:p=Date.now()}={}){if(!te.link||te.link==="free")return!1;const h=ae(u,oe),v=ae(u,re);if(!h||!v)return!1;const N=await Pe(h,v,{now:p});return!!N&&Ke(xe(N,{at:p}),"link",0,p)}function De(){return we(X.homedir(),".chatpanel","link.json")}function Fe(u){try{const p=JSON.parse(fe(u,"utf8"));return{v:1,key:p.key||null,rooms:Array.isArray(p.rooms)?p.rooms:[]}}catch{return{v:1,key:null,rooms:[]}}}function se(u,p){he(ke(u),{recursive:!0});const h=`${u}.tmp`;me(h,JSON.stringify(p,null,2),{mode:384});try{ge(h,384)}catch{}ye(h,u)}function et({settings:u={},relay:p=null,port:h=4320,name:v=X.hostname(),dispatch:N,path:U=De(),fetch:ie=globalThis.fetch,WebSocket:ce=globalThis.WebSocket,now:g=()=>Date.now(),random:z=w=>globalThis.crypto.getRandomValues(new Uint8Array(w)),crypto:I=Ee(),log:L=()=>{},mayLink:le=Be}={}){const w=p?new URL(p).origin:null;if(w&&!/^https:/.test(w)&&!/^http:\/\/127\.0\.0\.1(?::\d+)?$/.test(w))throw new Error("link: the relay must be https");const W=t=>{const e=ee(t);return w&&e.relay?{...e,relay:w}:e};let c=W(u);c.problem&&L(`link: ${c.problem} — using ChatPanel Link`);let l=Fe(U);const pe=w||ee({relayUrl:u?.relayUrl}).relay;for(const t of l.rooms)t.relay===void 0&&(t.relay=pe);const y=new Map,S=new Map;let E=null;async function b(){return E||(l.key?E=await I.keyPairFromPrivate(J(l.key)):(E=await I.generateKeyPair(),l.key=O(E.raw),se(U,l)),E)}const $=t=>l.rooms.find(e=>e.room===t)||null,C=()=>se(U,l),A=t=>!!t.relay&&t.relay===c.relay,M=async(t,e,n,o,s)=>{try{return await ie(`${s}/v1/room/${t}`,{method:e,headers:{authorization:`Bearer ${n}`,...o?{"content-type":"application/json"}:{}},body:o?JSON.stringify(o):void 0})}catch(r){const a=r?.cause?.code||"",f=a==="ENOTFOUND"?"this computer cannot look up its name (a VPN or DNS that does not know it yet)":a?`${a}`:r?.message||"no answer";throw new Error(`cannot reach the Link relay at ${new URL(s).host}: ${f}`)}};async function ue(t,e,n){if(t.lastSeen=g(),!Me(e.path))return await n.head(403,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:"link: a paired phone may not call this",type:"forbidden"}})),n.end();if(!await le(e.headers,{now:g()}))return await n.head(402,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:"ChatPanel Link needs Pro on this phone — upgrade on the phone, or restore its Pro under Settings › Plan",type:"pro_required"}})),n.end();if(e.path==="/v1/link/routes")return await n.head(200,{"content-type":"application/json"}),await n.write(JSON.stringify({route:c.route,relay:A(t)?t.relay:null,gw:c.tunnel})),n.end();const o={};for(const[d,m]of Object.entries(e.headers||{}))d.toLowerCase()!==oe&&d.toLowerCase()!==re&&(o[d]=m);const s=e.method==="GET"?void 0:await e.body.bytes(),r=await N({method:e.method,path:e.path,headers:o,body:s,device:t.room}),a={};r.headers?.forEach?.((d,m)=>{a[m]=d});let f=!1;try{await n.head(r.status,a)}catch{f=!0}if(r.body){const d=/event-stream/.test(String(r.headers?.get?.("content-type")||""));for await(const m of ve(de(r.body,d))){if(n.cancelled)break;if(!f)try{await n.write(m)}catch{f=!0}}}if(!f)return n.end()}async function*de(t,e){for await(const n of t){let o=n instanceof Uint8Array?n:new TextEncoder().encode(String(n));if(e){const s=new TextDecoder().decode(o);if(s.includes(": ping")){const r=s.replace(Ue,"$1");if(!r)continue;o=new TextEncoder().encode(r)}}yield o}}function Y(t,e,n,o,s){return Se({side:"laptop",keyPair:e,crypto:I,psk:t.phoneKey?null:J(n.psk),peerKey:t.phoneKey?J(t.phoneKey):null,sendBytes:s,onRequest:(r,a)=>ue(t,r,a),onSession:(r,a)=>{o.online=!0,o.attempts=0,t.lastSeen=g(),a.paired&&(t.phoneKey=O(a.peerKey),t.name=a.name||t.name||"Phone",t.pairedAt=g(),t.pending=null,L(`link: paired ${t.name}`)),C()},onEnd:()=>{o.online=!1}})}async function P(t){if(!A(t))return;const e=y.get(t.room)||{attempts:0,stopped:!1,online:!1};if(y.set(t.room,e),e.stopped)return;const n=await b(),o=t.pending&&t.pending.expiresAt>g()?t.pending:null;if(!t.phoneKey&&!o){D(t.room,"the pairing code expired");return}const s=`${t.relay.replace(/^http/,"ws")}/v1/room/${t.room}`;let r;try{r=new ce(s,[R,t.token])}catch(a){Z(t,a?.message);return}r.binaryType="arraybuffer",e.ws=r,e.endpoint=Y(t,n,o,e,a=>{try{r.send(a)}catch{}}),r.onopen=()=>{if(e.stopped||y.get(t.room)!==e){try{r.close(1e3,"stopped")}catch{}return}clearInterval(e.keepalive),e.keepalive=setInterval(()=>{try{r.send("ping")}catch{}},Oe),e.keepalive.unref?.()},r.onmessage=a=>typeof a.data=="string"?e.endpoint.onText(a.data):e.endpoint.onBinary(new Uint8Array(a.data)),r.onclose=a=>{if(clearInterval(e.keepalive),e.online=!1,e.endpoint?.close("socket closed"),!e.stopped){if(a?.code===4003||a?.code===4004){F(t.room,"the relay removed the room");return}Z(t,a?.code===4001?"replaced":a?.code===4008?"over the relay's budget":`closed ${a?.code||""}`,a?.code===4001?5:a?.code===4008?Ie:null)}},r.onerror=()=>{}}function Z(t,e,n=null){const o=y.get(t.room);if(!o||o.stopped)return;const s=n??Math.min(o.attempts,G.length-1);o.attempts++,clearTimeout(o.timer),o.timer=setTimeout(()=>P(t),G[s]),o.timer.unref?.(),L(`link: ${e}; again in ${G[s]/1e3}s`)}function B(t){const e=y.get(t);if(e){e.stopped=!0,clearTimeout(e.timer),clearInterval(e.keepalive),e.endpoint?.close("stopped");try{e.ws?.close(1e3,"stopped")}catch{}y.delete(t)}}function x(t,e=1e3,n="stopped"){const o=S.get(t);if(o?.ws){o.endpoint?.close(n);try{o.ws.close(e,n)}catch{}o.ws=null,o.endpoint=null,o.online=!1}}function D(t,e){const n=$(t);n&&!n.phoneKey&&n.relay&&M(t,"DELETE",n.token,null,n.relay).catch(()=>{}),F(t,e)}function F(t,e){B(t),x(t,4004,"room removed"),S.delete(t),l.rooms=l.rooms.filter(n=>n.room!==t),C(),L(`link: ${e}`)}return{async pair({name:t=v}={}){const e=await b(),n=z(16),o=z(32),s=O(n),r=await q(o,n,"laptop"),a=await q(o,n,"phone"),f=await j(a);if(c.relay){const i=await M(s,"PUT",r,{laptop:await j(r),phone:f},c.relay);if(i.status!==200&&i.status!==201)throw new Error(`link: the relay refused the room (${i.status})`)}for(const i of l.rooms.filter(V=>!V.phoneKey))D(i.room,"a new pairing code replaced this one");const d=g()+ne,m={room:s,token:r,relay:c.relay,phoneVerifier:f,phoneKey:null,name:"",pairedAt:null,lastSeen:null,pending:{psk:O(o),expiresAt:d}};l.rooms.push(m),C();const _=Te({relay:c.relay,gw:c.tunnel,room:n,key:e.publicKey,secret:o,name:String(t||"").slice(0,60)});return P(m),setTimeout(()=>{const i=$(s);i&&!i.phoneKey&&D(s,"the pairing code expired")},ne+1e3).unref?.(),{uri:_,svg:Le(_,{ecc:"M"}),expiresAt:d,room:s}},status(){const t=e=>!!y.get(e.room)?.online||!!S.get(e.room)?.online;return{route:c.route,relay:c.relay,tunnel:c.tunnel,...c.problem?{problem:c.problem}:{},routes:_e,setup:$e(c.route,{port:h,url:c.tunnel||""}),devices:l.rooms.filter(e=>e.phoneKey).map(e=>({id:e.room,name:e.name||"Phone",pairedAt:e.pairedAt,lastSeen:e.lastSeen,online:t(e),via:S.get(e.room)?.online?"tunnel":y.get(e.room)?.online?"relay":null,...e.relay&&!A(e)?{staleRelay:e.relay}:{},...c.tunnel&&!e.phoneVerifier?{tunnelNeedsRelink:!0}:{}})),pairing:l.rooms.filter(e=>!e.phoneKey&&e.pending?.expiresAt>g()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,connected:t(e)}))[0]||null}},async applySettings(t={}){c=W(t);for(const e of[...y.keys()]){const n=$(e);(!n||!A(n))&&B(e)}if(!c.tunnel)for(const e of[...S.keys()])x(e,1001,"the tunnel was switched off");l.rooms.length&&await b();for(const e of l.rooms)A(e)&&!y.has(e.room)&&P(e);return this.status()},async acceptTunnel(t,e,n){const o=decodeURIComponent(String(t.url||"").split("?")[0].slice(be.length));if(!c.tunnel)return H(e,404,"not found");const s=$(o),r=String(t.headers["sec-websocket-protocol"]||"").split(",").map(k=>k.trim()).filter(Boolean),f=/^Bearer ([A-Za-z0-9_-]+)$/.exec(String(t.headers.authorization||""))?.[1]||(r.length===2&&r.includes(R)?r.find(k=>k!==R):null),d=s&&!s.phoneKey&&s.pending?.expiresAt>g()?s.pending:null,m=f?Buffer.from(await j(f)):null,_=s?.phoneVerifier?Buffer.from(s.phoneVerifier):null;if(!s||!s.phoneKey&&!d||!m||!_||m.length!==_.length||!Ae(m,_))return H(e,403,"not admitted");const i=S.get(o)||{connects:[]};if(S.set(o,i),i.connects=i.connects.filter(k=>g()-k<6e4),i.connects.length>=Re)return H(e,429,"too many connects");i.connects.push(g());const V=await b(),T=Ne(t,e,n,{protocol:R});if(!T)return;x(o,4001,"replaced"),i.ws=T,i.online=!1;const K=Y(s,V,d,i,k=>{try{T.send(k)}catch{}});i.endpoint=K,T.onmessage=k=>{typeof k.data!="string"&&K.onBinary(new Uint8Array(k.data))},T.onclose=()=>{K.close("socket closed"),i.ws===T&&(i.ws=null,i.endpoint=null,i.online=!1)};const Q=JSON.stringify({t:"peer",up:!0});K.onText(Q),T.send(Q)},async remove(t){const e=$(t);if(!e)return!1;if(e.relay)try{await M(t,"DELETE",e.token,null,e.relay)}catch{}return F(t,"removed"),!0},async start(){if(l.rooms.length){await b();for(const t of l.rooms)P(t)}},stop(){for(const t of[...y.keys()])B(t);for(const t of[...S.keys()])x(t,1001,"going away")},get publicKey(){return E?.publicKey||null}}}export{Ce as COMPANION_PATHS,qe as DEFAULT_RELAY,oe as ENTITLEMENT_HEADER,re as INSTALL_HEADER,ne as PAIRING_TTL_MS,Me as companionMay,et as createLinkHost,De as defaultLinkPath,Be as phoneMayLink};
@@ -1 +1 @@
1
- const M=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/,B=Object.freeze([{id:"BAAI/bge-reranker-base",label:"bge-reranker base",lang:"100+ languages",tier:"balanced",approxMB:1110,ramMB:1300,minRamMB:2048,licence:"MIT",recommended:!0,note:"Half the size of v2 m3, most of the quality, the same 100+ languages; the ship default."},{id:"BAAI/bge-reranker-v2-m3",label:"bge-reranker v2 m3",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:2600,minRamMB:4096,licence:"Apache-2.0",note:"The one the decision servers themselves rank with. Multilingual, strong on long passages; twice the memory."},{id:"BAAI/bge-reranker-large",label:"bge-reranker large",lang:"100+ languages",tier:"max",approxMB:2240,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The first-generation large model; v2 m3 is newer and usually better at the same cost."},{id:"mixedbread-ai/mxbai-rerank-base-v1",label:"mxbai-rerank base v1",lang:"English",tier:"balanced",approxMB:740,ramMB:900,minRamMB:2048,licence:"Apache-2.0",note:"English-only, small and quick — a good fit for notes and search on a modest machine."},{id:"cross-encoder/ms-marco-MiniLM-L-6-v2",label:"MiniLM-L6 (MS MARCO)",lang:"English",tier:"light",approxMB:90,ramMB:300,minRamMB:1024,licence:"Apache-2.0",note:"Tiny and fast; the classic web-search reranker. English only, short passages."}]),u=Object.freeze([{id:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",label:"ModernBERT base zero-shot v2",lang:"English",tier:"balanced",approxMB:600,ramMB:1e3,minRamMB:2048,licence:"Apache-2.0",recommended:!0,note:"A third of the size of large, close on most typed decisions; the ship default. Uncalibrated like every zero-shot NLI head — the p is an ordering, not a probability."},{id:"MoritzLaurer/ModernBERT-large-zeroshot-v2.0",label:"ModernBERT large zero-shot v2",lang:"English",tier:"accurate",approxMB:1600,ramMB:2400,minRamMB:4096,licence:"Apache-2.0",note:"What OpenDecision was built around; 8k context, a little sharper, three times the memory."},{id:"MoritzLaurer/deberta-v3-large-zeroshot-v2.0",label:"DeBERTa v3 large zero-shot v2",lang:"English",tier:"max",approxMB:1740,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The strongest English zero-shot classifier of the family; slower than ModernBERT, 512 tokens."},{id:"MoritzLaurer/mDeBERTa-v3-base-mnli-xnli",label:"mDeBERTa v3 base (XNLI)",lang:"100 languages",tier:"balanced",approxMB:1120,ramMB:1400,minRamMB:2048,licence:"MIT",note:"The multilingual one: sentiment, routing and triage in Hindi, Telugu, Spanish, German… on the same questions."},{id:"MoritzLaurer/deberta-v3-xsmall-zeroshot-v1.1-all-33",label:"DeBERTa v3 xsmall zero-shot",lang:"English",tier:"light",approxMB:280,ramMB:500,minRamMB:1024,licence:"MIT",note:"Tiny and quick — decisions in tens of milliseconds on any machine, at some accuracy."}]),d=Object.freeze([{id:"Qwen/Qwen3-0.6B",label:"Qwen3 0.6B",task:"chat",lang:"100+ languages",tier:"light",approxMB:1200,ramMB:3e3,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"The smallest Qwen3 — a chat model that runs on CPU at a usable pace. The ship default for trying vLLM here."},{id:"Qwen/Qwen3-1.7B",label:"Qwen3 1.7B",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:3400,ramMB:6e3,minRamMB:8192,licence:"Apache-2.0",note:"Noticeably stronger; wants 8 GB for the engine and patience on CPU."},{id:"Qwen/Qwen3-4B",label:"Qwen3 4B",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:8e3,ramMB:12e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant; a GPU, or a big machine and patience."},{id:"HuggingFaceTB/SmolLM3-3B",label:"SmolLM3 3B",task:"chat",lang:"6 languages",tier:"balanced",approxMB:6200,ramMB:9e3,minRamMB:12288,licence:"Apache-2.0",note:"A small model built for tool use and long context; English-first."},{id:"Qwen/Qwen3-Embedding-0.6B",label:"Qwen3 Embedding 0.6B",task:"embed",lang:"100+ languages",tier:"balanced",approxMB:1200,ramMB:2500,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"Embeddings for semantic search (1024 dims); the first provider /v1/embeddings has had."},{id:"BAAI/bge-m3",label:"bge-m3",task:"embed",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:3500,minRamMB:4096,licence:"MIT",note:"The multilingual retrieval standard; dense 1024-dim vectors, long passages."},{id:"openai/whisper-large-v3-turbo",label:"Whisper large v3 turbo",task:"transcription",lang:"99 languages",tier:"accurate",approxMB:1600,ramMB:4e3,minRamMB:6144,licence:"MIT",note:"Speech to text through vLLM’s /v1/audio/transcriptions — a container the whole machine’s ears share; heavy on CPU."},{id:"openai/whisper-small",label:"Whisper small",task:"transcription",lang:"99 languages",tier:"light",approxMB:970,ramMB:2500,minRamMB:4096,licence:"MIT",note:"The light transcriber for a container on CPU."},{id:"Qwen/Qwen3-ASR-0.6B",label:"Qwen3-ASR 0.6B (experimental)",task:"transcription",lang:"52 languages",tier:"balanced",approxMB:1400,ramMB:4e3,minRamMB:6144,licence:"Apache-2.0",note:"The strongest small multilingual transcriber (5–6% WER on the open leaderboard). EXPERIMENTAL here: vLLM’s transcription route served whisper-family models only when this entry was written — if the container comes up without /v1/audio/transcriptions, the Runtime says so and the row stays empty."}]);function w(n){return d.find(e=>e.id===n)?.task||"chat"}const p=Object.freeze([{id:"mlx-community/Qwen3-1.7B-4bit",label:"Qwen3 1.7B (4-bit)",task:"chat",lang:"100+ languages",tier:"light",approxMB:1100,ramMB:2500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac; the ship default for trying vLLM-Metal here."},{id:"mlx-community/Qwen3-4B-4bit",label:"Qwen3 4B (4-bit)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:5e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant on a 16 GB Mac."},{id:"mlx-community/Qwen3-8B-4bit",label:"Qwen3 8B (4-bit)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:4700,ramMB:9e3,minRamMB:24576,licence:"Apache-2.0",note:"Strong; wants 24 GB of unified memory."},{id:"mlx-community/gemma-3-4b-it-4bit",label:"Gemma 3 4B (4-bit)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2700,ramMB:5500,minRamMB:16384,licence:"Gemma",note:"Google’s small model, vision-capable; a strong multilingual choice."},{id:"mlx-community/Llama-3.2-3B-Instruct-4bit",label:"Llama 3.2 3B (4-bit)",task:"chat",lang:"8 languages",tier:"balanced",approxMB:1800,ramMB:4e3,minRamMB:8192,licence:"Llama 3.2",note:"The familiar one; English-first."}]),b=Object.freeze([{id:"unsloth/Qwen3-4B-GGUF:Q4_K_M",label:"Qwen3 4B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac or a laptop CPU; thinks when asked. The ship default for trying llama.cpp here."},{id:"unsloth/Qwen3-8B-GGUF:Q4_K_M",label:"Qwen3 8B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:5e3,ramMB:8e3,minRamMB:16384,licence:"Apache-2.0",note:"Strong general assistant; comfortable on 16 GB with a 16k context."},{id:"unsloth/Qwen2.5-Coder-7B-Instruct-GGUF:Q4_K_M",label:"Qwen2.5 Coder 7B (Q4_K_M)",task:"chat",lang:"code, English, Chinese",tier:"accurate",approxMB:4700,ramMB:7500,minRamMB:16384,licence:"Apache-2.0",note:"The coding model at this size; a local coding agent’s first pick."},{id:"ggml-org/gemma-3-4b-it-GGUF:Q4_K_M",label:"Gemma 3 4B (Q4_K_M)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Gemma",note:"Google’s small model; takes images once its mmproj is named under Vision projector."},{id:"unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL",label:"Gemma 4 26B-A4B (UD-Q4_K_XL)",task:"chat",lang:"140 languages",tier:"max",approxMB:16500,ramMB:22e3,minRamMB:36864,licence:"Gemma",note:"The mixture model the `lm` recipe runs — 26B of weights, 4B active per token, so it answers like a big model at a small one’s speed. Wants 36 GB+; its MTP draft file under Draft model makes it faster still."}]),x=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}(:[A-Za-z0-9._-]{1,32})?$/;function A(n){const e=String(n||"").trim();return x.test(e)||/^(\/|[A-Za-z]:\\)/.test(e)&&/\.gguf$/i.test(e)&&!/[\s"'`$;|&<>]/.test(e)}const f={reranker:B,opendecision:u,vllm:d,"vllm-metal":p,mlx:p,llama:b};function s(n){return f[n]||[]}function k(n,e){if(typeof e!="string"||!e.trim())return!1;const t=e.trim();return n==="llama"?s(n).some(r=>r.id===t)||A(t):s(n).some(r=>r.id===t)||M.test(t)}function L(n){return`models--${String(n).replace(/\//g,"--")}`}function R(n,{active:e=null,engineRamMB:t=0,engine:r=null,platform:m=process.platform,installed:c=()=>!1}={}){const i=a=>`${Math.round(a/1024*10)/10} GB`,g=a=>r==="podman"&&m!=="linux"?`podman machine stop && podman machine set --memory ${Math.max(4096,Math.ceil((a.ramMB+2048)/2048)*2048)} && podman machine start`:r==="docker"&&m!=="linux"?"raise the memory in Docker Desktop › Settings › Resources":null,l=s(n).map(a=>{const o=t>0&&a.ramMB>t,h=!o&&Number(a.minRamMB)>0&&t>0&&t<a.minRamMB;return{...a,installed:c(a.id),recommended:!!a.recommended&&!o&&!h,...o?{unavailable:`needs about ${i(a.ramMB)} of memory while loaded — the container engine has ${i(t)}${g(a)?`; raise it: ${g(a)}`:""}`}:{},...h?{ramNote:`needs about ${i(a.ramMB)} while loaded — the engine has ${i(t)}; expect it to slow things down`}:{}}});return e&&!l.some(a=>a.id===e)&&l.push({id:e,label:/\.gguf$/i.test(e)?e.split(/[\\/]/).pop():e,lang:"—",tier:"custom",custom:!0,installed:c(e),note:/\.gguf$/i.test(e)?"A GGUF on this machine.":"Custom model (from Hugging Face)."}),l}export{u as DECIDE_MODEL_CATALOG,M as HF_ID,b as LLAMA_MODEL_CATALOG,B as RERANK_MODEL_CATALOG,p as VLLM_METAL_MODEL_CATALOG,d as VLLM_MODEL_CATALOG,L as cacheDirName,s as catalogFor,A as isLlamaModelId,k as isValidModelId,R as modelsFor,w as vllmTaskOf};
1
+ const M=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/,B=Object.freeze([{id:"BAAI/bge-reranker-base",label:"bge-reranker base",lang:"100+ languages",tier:"balanced",approxMB:1110,ramMB:1300,minRamMB:2048,licence:"MIT",recommended:!0,note:"Half the size of v2 m3, most of the quality, the same 100+ languages; the ship default."},{id:"BAAI/bge-reranker-v2-m3",label:"bge-reranker v2 m3",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:2600,minRamMB:4096,licence:"Apache-2.0",note:"The one the decision servers themselves rank with. Multilingual, strong on long passages; twice the memory."},{id:"BAAI/bge-reranker-large",label:"bge-reranker large",lang:"100+ languages",tier:"max",approxMB:2240,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The first-generation large model; v2 m3 is newer and usually better at the same cost."},{id:"mixedbread-ai/mxbai-rerank-base-v1",label:"mxbai-rerank base v1",lang:"English",tier:"balanced",approxMB:740,ramMB:900,minRamMB:2048,licence:"Apache-2.0",note:"English-only, small and quick — a good fit for notes and search on a modest machine."},{id:"cross-encoder/ms-marco-MiniLM-L-6-v2",label:"MiniLM-L6 (MS MARCO)",lang:"English",tier:"light",approxMB:90,ramMB:300,minRamMB:1024,licence:"Apache-2.0",note:"Tiny and fast; the classic web-search reranker. English only, short passages."}]),u=Object.freeze([{id:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",label:"ModernBERT base zero-shot v2",lang:"English",tier:"balanced",approxMB:600,ramMB:1e3,minRamMB:2048,licence:"Apache-2.0",recommended:!0,note:"A third of the size of large, close on most typed decisions; the ship default. Uncalibrated like every zero-shot NLI head — the p is an ordering, not a probability."},{id:"MoritzLaurer/ModernBERT-large-zeroshot-v2.0",label:"ModernBERT large zero-shot v2",lang:"English",tier:"accurate",approxMB:1600,ramMB:2400,minRamMB:4096,licence:"Apache-2.0",note:"What OpenDecision was built around; 8k context, a little sharper, three times the memory."},{id:"MoritzLaurer/deberta-v3-large-zeroshot-v2.0",label:"DeBERTa v3 large zero-shot v2",lang:"English",tier:"max",approxMB:1740,ramMB:2600,minRamMB:4096,licence:"MIT",note:"The strongest English zero-shot classifier of the family; slower than ModernBERT, 512 tokens."},{id:"MoritzLaurer/mDeBERTa-v3-base-mnli-xnli",label:"mDeBERTa v3 base (XNLI)",lang:"100 languages",tier:"balanced",approxMB:1120,ramMB:1400,minRamMB:2048,licence:"MIT",note:"The multilingual one: sentiment, routing and triage in Hindi, Telugu, Spanish, German… on the same questions."},{id:"MoritzLaurer/deberta-v3-xsmall-zeroshot-v1.1-all-33",label:"DeBERTa v3 xsmall zero-shot",lang:"English",tier:"light",approxMB:280,ramMB:500,minRamMB:1024,licence:"MIT",note:"Tiny and quick — decisions in tens of milliseconds on any machine, at some accuracy."}]),d=Object.freeze([{id:"Qwen/Qwen3-0.6B",label:"Qwen3 0.6B",task:"chat",lang:"100+ languages",tier:"light",approxMB:1200,ramMB:3e3,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"The smallest Qwen3 — a chat model that runs on CPU at a usable pace. The ship default for trying vLLM here."},{id:"Qwen/Qwen3-1.7B",label:"Qwen3 1.7B",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:3400,ramMB:6e3,minRamMB:8192,licence:"Apache-2.0",note:"Noticeably stronger; wants 8 GB for the engine and patience on CPU."},{id:"Qwen/Qwen3-4B",label:"Qwen3 4B",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:8e3,ramMB:12e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant; a GPU, or a big machine and patience."},{id:"HuggingFaceTB/SmolLM3-3B",label:"SmolLM3 3B",task:"chat",lang:"6 languages",tier:"balanced",approxMB:6200,ramMB:9e3,minRamMB:12288,licence:"Apache-2.0",note:"A small model built for tool use and long context; English-first."},{id:"Qwen/Qwen3-Embedding-0.6B",label:"Qwen3 Embedding 0.6B",task:"embed",lang:"100+ languages",tier:"balanced",approxMB:1200,ramMB:2500,minRamMB:4096,licence:"Apache-2.0",recommended:!0,note:"Embeddings for semantic search (1024 dims); the first provider /v1/embeddings has had."},{id:"BAAI/bge-m3",label:"bge-m3",task:"embed",lang:"100+ languages",tier:"accurate",approxMB:2270,ramMB:3500,minRamMB:4096,licence:"MIT",note:"The multilingual retrieval standard; dense 1024-dim vectors, long passages."},{id:"openai/whisper-large-v3-turbo",label:"Whisper large v3 turbo",task:"transcription",lang:"99 languages",tier:"accurate",approxMB:1600,ramMB:4e3,minRamMB:6144,licence:"MIT",note:"Speech to text through vLLM’s /v1/audio/transcriptions — a container the whole machine’s ears share; heavy on CPU."},{id:"openai/whisper-small",label:"Whisper small",task:"transcription",lang:"99 languages",tier:"light",approxMB:970,ramMB:2500,minRamMB:4096,licence:"MIT",note:"The light transcriber for a container on CPU."},{id:"Qwen/Qwen3-ASR-0.6B",label:"Qwen3-ASR 0.6B (experimental)",task:"transcription",lang:"52 languages",tier:"balanced",approxMB:1400,ramMB:4e3,minRamMB:6144,licence:"Apache-2.0",note:"The strongest small multilingual transcriber (5–6% WER on the open leaderboard). EXPERIMENTAL here: vLLM’s transcription route served whisper-family models only when this entry was written — if the container comes up without /v1/audio/transcriptions, the Runtime says so and the row stays empty."}]);function w(n){return d.find(e=>e.id===n)?.task||"chat"}const p=Object.freeze([{id:"mlx-community/Qwen3-0.6B-4bit",label:"Qwen3 0.6B (4-bit)",task:"chat",lang:"100+ languages",tier:"light",approxMB:400,ramMB:1200,minRamMB:4096,licence:"Apache-2.0",note:"The smallest: titles and topic lists at almost no cost. Copies examples and skips optional steps — not for real conversations."},{id:"mlx-community/Qwen3-1.7B-4bit",label:"Qwen3 1.7B (4-bit)",task:"chat",lang:"100+ languages",tier:"light",approxMB:1100,ramMB:2500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac; the ship default for vLLM-Metal and MLX."},{id:"mlx-community/Qwen3-4B-4bit",label:"Qwen3 4B (4-bit)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:5e3,minRamMB:16384,licence:"Apache-2.0",note:"A capable local assistant on a 16 GB Mac."},{id:"mlx-community/Qwen3-8B-4bit",label:"Qwen3 8B (4-bit)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:4700,ramMB:9e3,minRamMB:24576,licence:"Apache-2.0",note:"Strong; wants 24 GB of unified memory."},{id:"mlx-community/gemma-3-4b-it-4bit",label:"Gemma 3 4B (4-bit)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2700,ramMB:5500,minRamMB:16384,licence:"Gemma",note:"Google’s small model, vision-capable; a strong multilingual choice."},{id:"mlx-community/Llama-3.2-3B-Instruct-4bit",label:"Llama 3.2 3B (4-bit)",task:"chat",lang:"8 languages",tier:"balanced",approxMB:1800,ramMB:4e3,minRamMB:8192,licence:"Llama 3.2",note:"The familiar one; English-first."}]),b=Object.freeze([{id:"unsloth/Qwen3-4B-GGUF:Q4_K_M",label:"Qwen3 4B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Apache-2.0",recommended:!0,note:"Quick on any Apple Silicon Mac or a laptop CPU; thinks when asked. The ship default for trying llama.cpp here."},{id:"unsloth/Qwen3-8B-GGUF:Q4_K_M",label:"Qwen3 8B (Q4_K_M)",task:"chat",lang:"100+ languages",tier:"accurate",approxMB:5e3,ramMB:8e3,minRamMB:16384,licence:"Apache-2.0",note:"Strong general assistant; comfortable on 16 GB with a 16k context."},{id:"unsloth/Qwen2.5-Coder-7B-Instruct-GGUF:Q4_K_M",label:"Qwen2.5 Coder 7B (Q4_K_M)",task:"chat",lang:"code, English, Chinese",tier:"accurate",approxMB:4700,ramMB:7500,minRamMB:16384,licence:"Apache-2.0",note:"The coding model at this size; a local coding agent’s first pick."},{id:"ggml-org/gemma-3-4b-it-GGUF:Q4_K_M",label:"Gemma 3 4B (Q4_K_M)",task:"chat",lang:"140 languages",tier:"balanced",approxMB:2500,ramMB:4500,minRamMB:8192,licence:"Gemma",note:"Google’s small model; takes images once its mmproj is named under Vision projector."},{id:"unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL",label:"Gemma 4 26B-A4B (UD-Q4_K_XL)",task:"chat",lang:"140 languages",tier:"max",approxMB:16500,ramMB:22e3,minRamMB:36864,licence:"Gemma",note:"The mixture model the `lm` recipe runs — 26B of weights, 4B active per token, so it answers like a big model at a small one’s speed. Wants 36 GB+; its MTP draft file under Draft model makes it faster still."}]),x=/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}(:[A-Za-z0-9._-]{1,32})?$/;function A(n){const e=String(n||"").trim();return x.test(e)||/^(\/|[A-Za-z]:\\)/.test(e)&&/\.gguf$/i.test(e)&&!/[\s"'`$;|&<>]/.test(e)}const f={reranker:B,opendecision:u,vllm:d,"vllm-metal":p,mlx:p,llama:b};function s(n){return f[n]||[]}function k(n,e){if(typeof e!="string"||!e.trim())return!1;const t=e.trim();return n==="llama"?s(n).some(i=>i.id===t)||A(t):s(n).some(i=>i.id===t)||M.test(t)}function L(n){return`models--${String(n).replace(/\//g,"--")}`}function R(n,{active:e=null,engineRamMB:t=0,engine:i=null,platform:m=process.platform,installed:c=()=>!1}={}){const r=a=>`${Math.round(a/1024*10)/10} GB`,g=a=>i==="podman"&&m!=="linux"?`podman machine stop && podman machine set --memory ${Math.max(4096,Math.ceil((a.ramMB+2048)/2048)*2048)} && podman machine start`:i==="docker"&&m!=="linux"?"raise the memory in Docker Desktop › Settings › Resources":null,l=s(n).map(a=>{const o=t>0&&a.ramMB>t,h=!o&&Number(a.minRamMB)>0&&t>0&&t<a.minRamMB;return{...a,installed:c(a.id),recommended:!!a.recommended&&!o&&!h,...o?{unavailable:`needs about ${r(a.ramMB)} of memory while loaded — the container engine has ${r(t)}${g(a)?`; raise it: ${g(a)}`:""}`}:{},...h?{ramNote:`needs about ${r(a.ramMB)} while loaded — the engine has ${r(t)}; expect it to slow things down`}:{}}});return e&&!l.some(a=>a.id===e)&&l.push({id:e,label:/\.gguf$/i.test(e)?e.split(/[\\/]/).pop():e,lang:"—",tier:"custom",custom:!0,installed:c(e),note:/\.gguf$/i.test(e)?"A GGUF on this machine.":"Custom model (from Hugging Face)."}),l}export{u as DECIDE_MODEL_CATALOG,M as HF_ID,b as LLAMA_MODEL_CATALOG,B as RERANK_MODEL_CATALOG,p as VLLM_METAL_MODEL_CATALOG,d as VLLM_MODEL_CATALOG,L as cacheDirName,s as catalogFor,A as isLlamaModelId,k as isValidModelId,R as modelsFor,w as vllmTaskOf};