@chatpanel/gateway 0.23.2 → 0.39.4
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 +4 -4
- package/src/audio-file.js +4 -0
- package/src/bridge.js +4 -4
- package/src/capabilities.js +1 -1
- package/src/capability-endpoints.js +1 -1
- package/src/cloudevents.js +4 -0
- package/src/config.js +1 -1
- package/src/configstore.js +1 -1
- package/src/diarize-engine.js +1 -1
- package/src/egress.js +2 -2
- package/src/engine-tunings.js +1 -0
- package/src/event-stats.js +1 -0
- package/src/event-store.js +15 -0
- package/src/event-sync.js +1 -0
- package/src/event.js +1 -0
- package/src/fusions.js +1 -0
- package/src/images.js +34 -0
- package/src/inference-engines.js +1 -0
- package/src/model-pull.js +1 -0
- package/src/ner-engine.js +1 -1
- package/src/order.js +1 -0
- package/src/policy.js +2 -2
- package/src/providers.js +1 -0
- package/src/ref.js +1 -0
- package/src/router.js +1 -1
- package/src/runtime-models.js +1 -1
- package/src/runtime.js +5 -3
- package/src/server.js +28 -17
- package/src/service.js +9 -9
- package/src/sqlite-store.js +1 -1
- package/src/stt-engine.js +1 -1
- package/src/stt-remote.js +1 -0
- package/src/toolrelay.js +3 -3
- package/src/tts-remote.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.39.4",
|
|
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": {
|
|
@@ -22,9 +22,9 @@
|
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
25
|
-
"@chatpanel/bridge": "^0.
|
|
26
|
-
"@chatpanel/events": "^0.
|
|
27
|
-
"@chatpanel/pii": "^0.
|
|
25
|
+
"@chatpanel/bridge": "^0.20.1",
|
|
26
|
+
"@chatpanel/events": "^0.189.0",
|
|
27
|
+
"@chatpanel/pii": "^0.11.0",
|
|
28
28
|
"@huggingface/transformers": "^4.2.0",
|
|
29
29
|
"defuddle": "^0.19.4",
|
|
30
30
|
"fflate": "^0.8.3",
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{spawn as u}from"node:child_process";const g=16e3;function A(t,r){const i=/boundary=(?:"([^"]+)"|([^;]+))/i.exec(String(r||""));if(!i)throw Object.assign(new Error("multipart/form-data with a boundary expected"),{code:415});const e=Buffer.from(`--${i[1]||i[2]}`),d=[];let n=t.indexOf(e);for(;n!==-1&&(n+=e.length,!(t[n]===45&&t[n+1]===45));){t[n]===13?n+=2:t[n]===10&&(n+=1);const o=t.indexOf(`\r
|
|
2
|
+
\r
|
|
3
|
+
`,n);if(o===-1)break;const c=t.subarray(n,o).toString("utf8"),l=t.indexOf(e,o+4);if(l===-1)break;let a=l;t[a-1]===10&&a--,t[a-1]===13&&a--;const s=/name="([^"]*)"(?:;\s*filename="([^"]*)")?/i.exec(c)||[],f=(/content-type:\s*([^\r\n]+)/i.exec(c)||[])[1]||null;d.push({name:s[1]||"",filename:s[2]||null,type:f,data:t.subarray(o+4,a)}),n=l}return d}function E(t,r){const i=t[0].length,e=new Float32Array(i);for(let c=0;c<i;c++){let l=0;for(const a of t)l+=a[c];e[c]=l/t.length}if(r===g)return e;const d=Math.max(1,Math.round(i*g/r)),n=new Float32Array(d),o=r/g;for(let c=0;c<d;c++){const l=c*o,a=Math.floor(l),s=l-a;n[c]=(1-s)*(e[a]??0)+s*(e[a+1]??e[a]??0)}return n}function w(t){if(t.length<44||t.toString("ascii",0,4)!=="RIFF"||t.toString("ascii",8,12)!=="WAVE")return null;let r=12,i=null,e=null;for(;r+8<=t.length;){const f=t.toString("ascii",r,r+4),m=t.readUInt32LE(r+4);if(f==="fmt "&&(i={format:t.readUInt16LE(r+8),channels:t.readUInt16LE(r+10),rate:t.readUInt32LE(r+12),bits:t.readUInt16LE(r+22)}),f==="data"){e=t.subarray(r+8,Math.min(t.length,r+8+m));break}r+=8+m+m%2}if(!i||!e)throw Object.assign(new Error("WAV without fmt or data chunk"),{code:415});const{channels:d,rate:n,bits:o}=i,c=i.format===3||i.format===65534&&o===32,l=o/8,a=Math.floor(e.length/(l*d)),s=Array.from({length:d},()=>new Float32Array(a));for(let f=0;f<a;f++)for(let m=0;m<d;m++){const p=(f*d+m)*l;s[m][f]=c?e.readFloatLE(p):o===16?e.readInt16LE(p)/32768:o===8?(e[p]-128)/128:o===24?((e[p]|e[p+1]<<8|e[p+2]<<16)<<8>>8)/8388608:e.readInt32LE(p)/2147483648}return{pcm:E(s,n),rate:g,seconds:a/n}}function x(t,{spawn:r=u,bin:i="ffmpeg",timeoutMs:e=12e4}={}){return new Promise((d,n)=>{let o;try{o=r(i,["-nostdin","-loglevel","error","-i","pipe:0","-f","f32le","-ac","1","-ar",String(g),"pipe:1"],{stdio:["pipe","pipe","pipe"]})}catch(s){return n(Object.assign(new Error(`ffmpeg: ${s.message}`),{code:415}))}const c=[];let l="";const a=setTimeout(()=>{try{o.kill("SIGKILL")}catch{}n(Object.assign(new Error("ffmpeg: timed out"),{code:500}))},e);o.stdout.on("data",s=>c.push(s)),o.stderr.on("data",s=>{l+=s}),o.on("error",s=>{clearTimeout(a),n(Object.assign(new Error(s.code==="ENOENT"?"ffmpeg is not on PATH — send a WAV, or install ffmpeg for mp3/m4a/webm/ogg":`ffmpeg: ${s.message}`),{code:415}))}),o.on("close",s=>{if(clearTimeout(a),s!==0)return n(Object.assign(new Error(`ffmpeg could not read this file${l?`: ${l.trim().split(`
|
|
4
|
+
`).pop()}`:""}`),{code:415}));const f=Buffer.concat(c),m=f.length-f.length%4,p=new Float32Array(m/4);for(let h=0;h<p.length;h++)p[h]=f.readFloatLE(h*4);d({pcm:p,rate:g,seconds:p.length/g})}),o.stdin.on("error",()=>{}),o.stdin.end(t)})}async function L(t,r={}){const i=w(t);return i||x(t,r)}export{g as TARGET_RATE,L as decodeAudioFile,w as decodeWav,x as decodeWithFfmpeg,A as parseMultipart,E as toMono16k};
|
package/src/bridge.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{readFileSync as D,existsSync as j}from"node:fs";import{join as
|
|
2
|
-
`):""}function _(t){return(t||[]).filter(e=>e&&(e.role==="user"||e.role==="assistant"||e.role==="system")).map(e=>({role:e.role,content:G(e.content)}))}async function W({bridgeUrl:t,agent:e,token:r,messages:o,system:s,specs:n,options:l,signal:
|
|
3
|
-
`)){const g=m.trim();if(!g.startsWith("data:"))continue;const B=g.slice(5).trim();if(!B||B==="[DONE]")continue;let i;try{i=JSON.parse(B)}catch{continue}i.type==="delta"&&typeof i.text=="string"?(T=!0,h+=i.text,a(i.text)):i.type==="done"?!T&&typeof i.text=="string"&&i.text&&(h+=i.text,a(i.text)):i.type==="error"?w=new Error(i.error||"bridge error"):
|
|
1
|
+
import{readFileSync as D,existsSync as j}from"node:fs";import{join as v}from"node:path";import C from"node:os";const A=v(C.homedir(),".chatpanel","bridge-token"),L="http://127.0.0.1:4319",N=1e4;let u={at:0,cfgUrl:"",url:"",fell:!1};async function E(t,e){try{return(await fetch(`${t}/health`,{signal:AbortSignal.timeout(e)})).ok}catch{return!1}}async function k(t,{fallback:e,timeoutMs:r=1500,now:o=Date.now()}={}){e===void 0&&(e=process.env.CHATPANEL_BRIDGE_FALLBACK==="off"?"":L);const s=String(t?.bridge?.url||"").replace(/\/$/,"");if(u.url&&u.cfgUrl===s&&o-u.at<N)return u.url;let n=s||e,l=!1;return e&&n!==e&&!await E(n,r)&&await E(e,r)&&(n=e,l=!0,(!u.fell||u.cfgUrl!==s)&&console.log(`[gateway] bridge.url ${s} is not answering; the bridge on ${e} is — using it (fix the address in Settings to silence this)`)),u={at:o,cfgUrl:s,url:n,fell:l},n}function z(){u={at:0,cfgUrl:"",url:"",fell:!1}}let y=!1;function S(t){try{if(j(t))return D(t,"utf8").trim()}catch{}return""}function F(t,e=A){const r=S(e);return!t||y&&r&&r!==t?r:t}function J(t,e=A){const r=S(e);return!r||r===t?"":(y||(y=!0,console.warn("[gateway] the bridge rejected bridge.token from gateway.config.json; using ~/.chatpanel/bridge-token (the bridge wrote it). Clear the config value to silence this.")),r)}function M(){y=!1}const P=t=>t===401||t===403;async function R(t,e,r,o,s){const n=a=>fetch(`${t.replace(/\/$/,"")}/chat`,{method:"POST",headers:{"content-type":"application/json",...a?{authorization:`Bearer ${a}`}:{}},body:r,signal:o}),l=F(e,s);let c=await n(l);if(P(c.status)){const a=J(l,s);a&&(await c.text().catch(()=>{}),c=await n(a))}return c}function G(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:typeof e?.text=="string"?e.text:"").filter(Boolean).join(`
|
|
2
|
+
`):""}function _(t){return(t||[]).filter(e=>e&&(e.role==="user"||e.role==="assistant"||e.role==="system")).map(e=>({role:e.role,content:G(e.content)}))}async function W({bridgeUrl:t,agent:e,token:r,messages:o,system:s,specs:n,options:l,signal:c,tokenPath:a,approvals:p=!1}){const f=await R(t,r,JSON.stringify({agent:e,messages:_(o),system:s||"",options:l||{},...Array.isArray(n)&&n.length?{pageTools:{specs:n}}:{},...p?{approvals:!0}:{}}),c,a);if(!f.ok||!f.body)throw new Error(await $(f));return f}async function $(t){const e=await t.text().catch(()=>"");let r="";try{const o=JSON.parse(e);r=String(o?.error?.message||o?.error||o?.message||"").trim()}catch{}return r?r.slice(0,600):`bridge /chat HTTP ${t.status}${e?`: ${e.slice(0,200)}`:""}`}async function q({bridgeUrl:t,agent:e,token:r,messages:o,system:s,options:n,signal:l,tokenPath:c},a,p=null){const f=await R(t,r,JSON.stringify({agent:e,messages:_(o),system:s||"",options:n||{}}),l,c);if(!f.ok||!f.body)throw new Error(await $(f));const O=f.body.getReader(),U=new TextDecoder;let d="",h="",T=!1,w=null;const b=x=>{for(const m of x.split(`
|
|
3
|
+
`)){const g=m.trim();if(!g.startsWith("data:"))continue;const B=g.slice(5).trim();if(!B||B==="[DONE]")continue;let i;try{i=JSON.parse(B)}catch{continue}i.type==="delta"&&typeof i.text=="string"?(T=!0,h+=i.text,a(i.text)):i.type==="done"?!T&&typeof i.text=="string"&&i.text&&(h+=i.text,a(i.text)):i.type==="error"?w=new Error(i.error||"bridge error"):p&&p(i)}};for(;;){const{done:x,value:m}=await O.read();if(x)break;d+=U.decode(m,{stream:!0});let g;for(;(g=d.indexOf(`
|
|
4
4
|
|
|
5
|
-
`))!==-1;)b(d.slice(0,g)),d=d.slice(g+2)}if(d.trim()&&b(d),w)throw w;return h}export{
|
|
5
|
+
`))!==-1;)b(d.slice(0,g)),d=d.slice(g+2)}if(d.trim()&&b(d),w)throw w;return h}export{L as DEFAULT_BRIDGE_URL,$ as bridgeRefusal,J as bridgeTokenRejected,W as openBridgeChat,F as readBridgeToken,z as resetBridgeResolution,M as resetBridgeTokenPreference,k as resolveBridgeUrl,q as streamBridgeChat,_ as toBridgeMessages};
|
package/src/capabilities.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as r from"./ner-engine.js";import*as A from"./stt-engine.js";import*as L from"./tts-engine.js";import{MODEL_CATALOG as M,DEFAULT_MODEL as S}from"./models.js";import{STT_MODEL_CATALOG as C,DEFAULT_STT_MODEL as E}from"./stt-models.js";import{TTS_MODEL_CATALOG as R,resolveDefaultModel as U}from"./tts-models.js";import{rawOrtAvailable as $}from"./ort.js";import{providerOf as B,providerTable as G}from"./providers.js";import{CAPABILITY_ROUTES as u,overBudget as j,validateDetectRequest as F}from"./capability-endpoints.js";import{extractCapabilityEntry as I}from"./extract/handler.js";const b=e=>[...new Set(e.filter(Boolean))];function x(e,c={}){return{state:e.state||"off",name:e.runtime||null,dtype:e.dtype||null,error:e.error||null,...c}}function Q(e,{version:c="",reader:n=null,searcher:s=null,extract:p=null,proxy:f=null}={}){const l=r.health(),a=e?.redaction?.detection,o=!!(a&&a.backend&&a.backend!=="off"),m=l.model||e?.ner?.model||S,g=A.health(),v=L.health(),O=v.model||e?.tts?.model||U($()),i=[{id:"detect",route:u.detect,models:b([m,...M.map(t=>t.id)]),default:m,union:l.companions?.filter(t=>t.state==="ready").map(t=>t.model)||[],labels:r.isReady()?r.labels():[],maxTokens:r.isReady()?r.maxTokens():null,requirements:{egress:"none",deterministic:!0},stats:l.stats||{calls:0},runtime:o?{state:"external",name:a.backend,url:a.url||null}:x(l,{installed:r.modelOnDisk(m)})},{id:"stt",route:u.stt,streaming:"/stt/sessions",models:b([g.model||e?.stt?.model||E,...C.map(t=>t.id)]),default:g.model||e?.stt?.model||E,requirements:{egress:"none"},runtime:x(g)},{id:"tts",route:u.tts,voices:"/tts/voices",models:b([O,...R.map(t=>t.id)]),default:O,requirements:{egress:"none"},runtime:x(v)}],T=e?.read||{},w=!!T.remote?.url;i.push({id:"read",route:u.read,providers:n?n.providers():["defuddle","text",...w?["remote"]:[]],default:T.provider||"defuddle",requirements:{egress:"web"},stats:n?n.stats():{calls:0},runtime:{state:"ready",cache:n?n.cache.size():0,remote:w?"configured":"off"}});const h=e?.search||{},y=!!h.searxng?.url,k=s?.searxng?s.searxng.state():y?"unknown":"off";if(i.push({id:"search",route:u.search,providers:s?s.providers():["serp",...y?["searxng"]:[]],default:h.provider==="searxng"||h.provider==="serp"?h.provider:y?"searxng":"serp",requirements:{egress:"web"},stats:s?s.stats()[y?"searxng":"serp"]||{calls:0}:{calls:0},runtime:{state:"ready",searxng:k,...y?{searxngUrl:h.searxng.url}:{}}}),p)try{i.push(I(p))}catch{}if(f)for(const t of f.capabilities){const d=f.entry(t);d&&i.push(d)}i.push({id:"chat",route:u.chat,models:[],dialects:["/v1/chat/completions","/v1/messages","/v1/responses"],listing:"/v1/models"});const _={sttModel:g.model,ttsModel:v.model,nerModel:m};for(const t of i){const d=B(e,t.id,_),{token:D,...q}=d;t.provider=q,d.kind==="remote"&&(t.requirements={...t.requirements||{},egress:d.egress})}return{capabilities:i,server:{name:"chatpanel-gateway",version:String(c),audit:"/audit"},providers:Object.fromEntries(Object.entries(G(e,_)).map(([t,{token:d,...D}])=>[t,D]))}}async function V(e,{ensure:c=async()=>r.state(),model:n=null}={}){let s;try{s=F(e)}catch(o){return{status:400,body:{error:{message:o.message,type:"invalid_request"}}}}if(s.model&&n&&s.model!==n)return{status:404,body:{error:{message:`model ${s.model} is not loaded here (serving ${n})`,type:"model_not_found"}}};if(await c(),!r.isReady()){const o=r.health();return{status:503,body:{error:{message:o.state==="error"?`detector failed to load: ${o.error||"unknown error"}`:`detector is ${o.state} — not ready yet`,type:o.state==="error"?"detector_error":"detector_unready"},state:o.state,model:o.model}}}const p=j(r.stats(),s.text.length,s.budgetMs);if(p)return{status:503,body:{...p,model:r.health().model}};const f=performance.now();let l=await r.detectSpans(s.text);if(s.labels){const o=new Set(s.labels);l=l.filter(m=>o.has(m.type))}const a=r.health();return{status:200,body:{entities:l,model:a.model,ms:Math.round(performance.now()-f),runtime:{name:a.runtime||null,dtype:a.dtype||null}}}}export{Q as capabilitiesDocument,V as handleDetect};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as v}from"@chatpanel/events/event.js";const q=Object.freeze(["detect","decide","rerank","embed","stt","tts","search","read","extract"]),p=Object.freeze({detect:"/v1/detect",decide:"/v1/decide",rerank:"/v1/rerank",embed:"/v1/embeddings",stt:"/v1/audio/transcriptions",tts:"/v1/audio/speech",search:"/v1/search",read:"/v1/read",extract:"/v1/extract"}),f=Object.freeze(new Set(["search","read","extract"])),g=Object.freeze(["day","week","month","year"]),b=Object.freeze(["login","paywall","rate_limited","robots","tdm"]),c=Object.freeze(["markdown","text"]),S="/v1/capabilities",$="over_budget",a=e=>!!e&&typeof e=="object"&&!Array.isArray(e),i=e=>typeof e=="string"&&e.length>0,d=e=>typeof e=="number"&&Number.isFinite(e),t=(e,s)=>{if(!e)throw new v("SHAPE",s)};function x(e,s){if(!a(e)||!(e.calls>0))return null;const r=d(e.p50Ms)?e.p50Ms:0,n=d(e.charsPerSec)&&e.charsPerSec>0&&d(s)?s/e.charsPerSec*1e3:0;return Math.round(Math.max(r,n))}function R(e,s,r){if(!d(r)||r<=0)return null;const n=x(e,s);return n===null||n<=r?null:{error:{type:$,message:`predicted ${n} ms is over the ${r} ms budget`,predictedMs:n,budgetMs:r}}}function j(e){t(a(e),"detect: body must be an object"),t(typeof e.text=="string","detect: text (string) required");const s={text:e.text};return e.model!=null&&(t(i(e.model),"detect: model must be a non-empty string"),s.model=e.model),e.labels!=null&&(t(Array.isArray(e.labels)&&e.labels.every(i),"detect: labels must be string[]"),s.labels=e.labels),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"detect: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function w(e,s=null){t(a(e),"detect: response must be an object"),t(Array.isArray(e.entities),"detect: entities[] required"),t(i(e.model),"detect: model required"),t(d(e.ms)&&e.ms>=0,"detect: ms required");for(const r of e.entities)t(a(r)&&i(r.value)&&i(r.type),"detect: entity needs value and type"),t(Number.isInteger(r.start)&&Number.isInteger(r.end)&&r.start>=0&&r.end>r.start,`detect: entity ${JSON.stringify(r.value)} needs start < end`),t(d(r.score)&&r.score>=0&&r.score<=1,`detect: entity ${JSON.stringify(r.value)} needs a score in [0,1]`),typeof s=="string"&&t(s.slice(r.start,r.end)===r.value,`detect: entity ${JSON.stringify(r.value)} is not at ${r.start}–${r.end} of the text`);return e}const m=e=>{if(!i(e))return!1;try{const s=new URL(e);return s.protocol==="http:"||s.protocol==="https:"}catch{return!1}};function I(e){t(a(e),"search: body must be an object"),t(i(e.q)&&e.q.trim().length>0,"search: q (non-empty string) required");const s={q:e.q.trim()};return e.limit!=null&&(t(Number.isInteger(e.limit)&&e.limit>=1&&e.limit<=50,"search: limit must be an integer 1–50"),s.limit=e.limit),e.lang!=null&&(t(i(e.lang)&&/^[a-z]{2}(-[A-Za-z]{2})?$/.test(e.lang),"search: lang must be a BCP-47 tag like en or en-US"),s.lang=e.lang),e.site!=null&&(t(i(e.site)&&!/[\s/]/.test(e.site),"search: site must be a hostname"),s.site=e.site.toLowerCase()),e.freshness!=null&&(t(g.includes(e.freshness),`search: freshness must be one of ${g.join(", ")}`),s.freshness=e.freshness),e.read!=null&&(t(Number.isInteger(e.read)&&e.read>=0&&e.read<=10,"search: read must be an integer 0–10"),s.read=e.read),e.provider!=null&&(t(i(e.provider),"search: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"search: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function _(e){return t(a(e),"search: response must be an object"),t(Array.isArray(e.results),"search: results[] required"),t(i(e.provider),"search: provider required"),t(d(e.ms)&&e.ms>=0,"search: ms required"),e.results.forEach((s,r)=>{t(a(s)&&s.rank===r+1,`search: result ${r} must carry rank ${r+1}`),t(m(s.url),`search: result ${r+1} needs an absolute http(s) url`),t(i(s.title),`search: result ${r+1} needs a title`),t(typeof s.snippet=="string",`search: result ${r+1} needs a snippet (may be empty)`),s.read!=null&&A(s.read)}),e}function O(e){t(a(e),"read: body must be an object"),t(m(e.url),"read: url (absolute http(s)) required");const s={url:e.url,format:"markdown"};return e.format!=null&&(t(c.includes(e.format),`read: format must be one of ${c.join(", ")}`),s.format=e.format),e.maxChars!=null&&(t(Number.isInteger(e.maxChars)&&e.maxChars>=200,"read: maxChars must be an integer ≥ 200"),s.maxChars=e.maxChars),e.snippet!=null&&(t(typeof e.snippet=="string","read: snippet must be a string"),s.snippet=e.snippet),e.provider!=null&&(t(i(e.provider),"read: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"read: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function A(e){t(a(e),"read: response must be an object"),t(m(e.url),"read: url (absolute, where the page landed) required"),t(typeof e.title=="string","read: title (string, may be empty) required"),t(c.includes(e.format),"read: format required");const s=e[e.format];t(typeof s=="string",`read: ${e.format} (string) required`),t(Number.isInteger(e.chars)&&e.chars===s.length,"read: chars must equal the content length"),t(typeof e.truncated=="boolean","read: truncated (boolean) required"),t(i(e.provider),"read: provider required"),t(d(e.ms)&&e.ms>=0,"read: ms required"),t(Array.isArray(e.sections),"read: sections[] required");for(const r of e.sections)t(a(r)&&i(r.id)&&i(r.heading),"read: section needs id and heading"),t(Number.isInteger(r.level)&&r.level>=1&&r.level<=6,`read: section ${r.id} needs level 1–6`),t(Number.isInteger(r.offset)&&r.offset>=0&&r.offset<=s.length,`read: section ${r.id} offset must index the content`);return e.restricted!=null&&t(a(e.restricted)&&b.includes(e.restricted.reason),`read: restricted.reason must be one of ${b.join(", ")}`),e}const h=Object.freeze(["choice","score","noul"]),k=/^[A-Za-z_][A-Za-z0-9_]*$/;function E(e){t(a(e),"decide: body must be an object"),t(i(e.state),"decide: state (non-empty string) required"),t(a(e.questions)&&Object.keys(e.questions).length>0,"decide: questions {} required");const s={};for(const[n,u]of Object.entries(e.questions)){t(k.test(n),`decide: question key ${JSON.stringify(n)} must be an identifier`),t(a(u)&&h.includes(u.type),`decide: question ${n}.type must be one of ${h.join(", ")}`),t(i(u.instructions),`decide: question ${n} needs instructions`);const l={type:u.type,instructions:u.instructions};u.type==="noul"?t(u.options==null,`decide: question ${n}: a noul has no options`):(t(Array.isArray(u.options)&&u.options.length>=2&&u.options.length<=255,`decide: question ${n}.options needs 2–255 entries`),l.options=u.options.map(o=>i(o)?{value:o}:(t(a(o)&&i(o.value),`decide: question ${n}: an option is a string or { value, describe? }`),o.describe!=null?{value:o.value,describe:String(o.describe)}:{value:o.value})),t(new Set(l.options.map(o=>o.value)).size===l.options.length,`decide: question ${n}.options must be distinct`)),s[n]=l}const r={state:e.state,questions:s};return e.model!=null&&(t(i(e.model),"decide: model must be a non-empty string"),r.model=e.model),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"decide: budgetMs must be a number ≥ 0"),r.budgetMs=e.budgetMs),r}function N(e,s=null){t(a(e),"decide: response must be an object"),t(a(e.answers),"decide: answers {} required"),t(i(e.model),"decide: model required"),t(d(e.ms)&&e.ms>=0,"decide: ms required"),e.calibrated!=null&&t(typeof e.calibrated=="boolean","decide: calibrated must be a boolean");const r=n=>d(n)&&n>=0&&n<=1;for(const n of Object.keys(s?s.questions:e.answers)){const u=e.answers[n];t(a(u),`decide: answer ${n} missing`),t(r(u.p),`decide: answer ${n}.p must be in [0,1]`),t(Array.isArray(u.options)&&u.options.every(o=>a(o)&&o.value!==void 0&&r(o.p)),`decide: answer ${n}.options must be [{ value, p }]`),u.confidence!=null&&t(r(u.confidence),`decide: answer ${n}.confidence must be in [0,1]`);const l=s?.questions?.[n];l?.type==="choice"&&t(l.options.some(o=>o.value===u.value),`decide: answer ${n}.value must be one of the options`),l?.type==="noul"&&t(typeof u.value=="boolean",`decide: answer ${n}.value must be a boolean`),l?.type==="score"&&t(d(u.value),`decide: answer ${n}.value must be a number`)}return e}function C(e){t(a(e),"rerank: body must be an object"),t(i(e.query),"rerank: query (non-empty string) required"),t(Array.isArray(e.documents)&&e.documents.length>=1&&e.documents.length<=1e3&&e.documents.every(r=>typeof r=="string"),"rerank: documents must be 1–1000 strings");const s={query:e.query,documents:e.documents.slice()};return e.top_n!=null&&(t(Number.isInteger(e.top_n)&&e.top_n>=1,"rerank: top_n must be an integer ≥ 1"),s.top_n=e.top_n),e.model!=null&&(t(i(e.model),"rerank: model must be a non-empty string"),s.model=e.model),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"rerank: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function z(e,s=null){t(a(e),"rerank: response must be an object"),t(Array.isArray(e.results),"rerank: results[] required"),t(i(e.model),"rerank: model required"),t(d(e.ms)&&e.ms>=0,"rerank: ms required");const r=s?s.documents.length:1/0,n=new Set;let u=1/0;return e.results.forEach((l,o)=>{t(a(l)&&Number.isInteger(l.index)&&l.index>=0&&l.index<r,`rerank: result ${o} needs an index into the documents`),t(!n.has(l.index),`rerank: index ${l.index} listed twice`),n.add(l.index),t(d(l.relevance_score),`rerank: result ${o} needs relevance_score`),t(l.relevance_score<=u,"rerank: results must be ordered best first"),u=l.relevance_score}),s?.top_n!=null&&t(e.results.length<=s.top_n,`rerank: more than top_n (${s.top_n}) results`),e}function D(e){t(a(e),"capabilities: response must be an object"),t(Array.isArray(e.capabilities),"capabilities: capabilities[] required"),t(a(e.server)&&i(e.server.name)&&i(e.server.version),"capabilities: server {name, version} required");const s=new Set;for(const r of e.capabilities)t(a(r)&&q.includes(r.id),`capabilities: unknown capability id ${JSON.stringify(r?.id)}`),t(!s.has(r.id),`capabilities: ${r.id} listed twice`),s.add(r.id),t(r.route===p[r.id],`capabilities: ${r.id} must be served at ${p[r.id]}`),f.has(r.id)?(t(Array.isArray(r.providers)&&r.providers.length>0&&r.providers.every(i),`capabilities: ${r.id}.providers must be a non-empty string[]`),r.default!=null&&t(r.providers.includes(r.default),`capabilities: ${r.id}.default must be one of its providers`)):(t(Array.isArray(r.models)&&r.models.every(i),`capabilities: ${r.id}.models must be string[]`),r.default!=null&&t(r.models.includes(r.default),`capabilities: ${r.id}.default must be one of its models`)),r.labels!=null&&t(Array.isArray(r.labels)&&r.labels.every(i),`capabilities: ${r.id}.labels must be string[]`),r.stats!=null&&t(a(r.stats)&&(f.has(r.id)||d(r.stats.calls)),`capabilities: ${r.id}.stats needs calls`),r.runtime!=null&&t(a(r.runtime)&&i(r.runtime.state),`capabilities: ${r.id}.runtime needs state`);return e}function T(e){return(e?.capabilities||[]).map(s=>({id:s.id,route:s.route,models:s.models||[],providers:s.providers||[],ready:!s.runtime||["ready","external","idle"].includes(s.runtime.state),stats:s.stats||null,labels:s.labels||null}))}export{q as CAPABILITIES,p as CAPABILITY_ROUTES,h as DECIDE_QUESTION_TYPES,S as DISCOVERY_ROUTE,$ as OVER_BUDGET,f as PROVIDER_CAPABILITIES,c as READ_FORMATS,b as READ_RESTRICTIONS,g as SEARCH_FRESHNESS,T as offeredCapabilities,R as overBudget,x as predictMs,D as validateCapabilitiesResponse,E as validateDecideRequest,N as validateDecideResponse,j as validateDetectRequest,w as validateDetectResponse,O as validateReadRequest,A as validateReadResponse,C as validateRerankRequest,z as validateRerankResponse,I as validateSearchRequest,_ as validateSearchResponse};
|
|
1
|
+
import{EventError as q}from"./event.js";const x=Object.freeze(["detect","decide","rerank","embed","stt","tts","search","read","extract","chat","s2s"]),p=Object.freeze(["embedded","container","remote","harness","router","none"]),f=Object.freeze(["none","loopback","lan","internet","configurable"]),b=Object.freeze({detect:"/v1/detect",decide:"/v1/decide",rerank:"/v1/rerank",embed:"/v1/embeddings",stt:"/v1/audio/transcriptions",tts:"/v1/audio/speech",search:"/v1/search",read:"/v1/read",extract:"/v1/extract",chat:"/v1/chat/completions",s2s:"/v1/audio/conversations"}),g=Object.freeze(new Set(["search","read","extract"])),v=Object.freeze(["day","week","month","year"]),h=Object.freeze(["login","paywall","rate_limited","robots","tdm"]),c=Object.freeze(["markdown","text"]),I="/v1/capabilities",A="over_budget",a=e=>!!e&&typeof e=="object"&&!Array.isArray(e),n=e=>typeof e=="string"&&e.length>0,d=e=>typeof e=="number"&&Number.isFinite(e),t=(e,s)=>{if(!e)throw new q("SHAPE",s)};function k(e,s){if(!a(e)||!(e.calls>0))return null;const r=d(e.p50Ms)?e.p50Ms:0,i=d(e.charsPerSec)&&e.charsPerSec>0&&d(s)?s/e.charsPerSec*1e3:0;return Math.round(Math.max(r,i))}function _(e,s,r){if(!d(r)||r<=0)return null;const i=k(e,s);return i===null||i<=r?null:{error:{type:A,message:`predicted ${i} ms is over the ${r} ms budget`,predictedMs:i,budgetMs:r}}}function O(e){t(a(e),"detect: body must be an object"),t(typeof e.text=="string","detect: text (string) required");const s={text:e.text};return e.model!=null&&(t(n(e.model),"detect: model must be a non-empty string"),s.model=e.model),e.labels!=null&&(t(Array.isArray(e.labels)&&e.labels.every(n),"detect: labels must be string[]"),s.labels=e.labels),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"detect: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function w(e,s=null){t(a(e),"detect: response must be an object"),t(Array.isArray(e.entities),"detect: entities[] required"),t(n(e.model),"detect: model required"),t(d(e.ms)&&e.ms>=0,"detect: ms required");for(const r of e.entities)t(a(r)&&n(r.value)&&n(r.type),"detect: entity needs value and type"),t(Number.isInteger(r.start)&&Number.isInteger(r.end)&&r.start>=0&&r.end>r.start,`detect: entity ${JSON.stringify(r.value)} needs start < end`),t(d(r.score)&&r.score>=0&&r.score<=1,`detect: entity ${JSON.stringify(r.value)} needs a score in [0,1]`),typeof s=="string"&&t(s.slice(r.start,r.end)===r.value,`detect: entity ${JSON.stringify(r.value)} is not at ${r.start}–${r.end} of the text`);return e}const m=e=>{if(!n(e))return!1;try{const s=new URL(e);return s.protocol==="http:"||s.protocol==="https:"}catch{return!1}};function E(e){t(a(e),"search: body must be an object"),t(n(e.q)&&e.q.trim().length>0,"search: q (non-empty string) required");const s={q:e.q.trim()};return e.limit!=null&&(t(Number.isInteger(e.limit)&&e.limit>=1&&e.limit<=50,"search: limit must be an integer 1–50"),s.limit=e.limit),e.lang!=null&&(t(n(e.lang)&&/^[a-z]{2}(-[A-Za-z]{2})?$/.test(e.lang),"search: lang must be a BCP-47 tag like en or en-US"),s.lang=e.lang),e.site!=null&&(t(n(e.site)&&!/[\s/]/.test(e.site),"search: site must be a hostname"),s.site=e.site.toLowerCase()),e.freshness!=null&&(t(v.includes(e.freshness),`search: freshness must be one of ${v.join(", ")}`),s.freshness=e.freshness),e.read!=null&&(t(Number.isInteger(e.read)&&e.read>=0&&e.read<=10,"search: read must be an integer 0–10"),s.read=e.read),e.provider!=null&&(t(n(e.provider),"search: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"search: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function N(e){return t(a(e),"search: response must be an object"),t(Array.isArray(e.results),"search: results[] required"),t(n(e.provider),"search: provider required"),t(d(e.ms)&&e.ms>=0,"search: ms required"),e.results.forEach((s,r)=>{t(a(s)&&s.rank===r+1,`search: result ${r} must carry rank ${r+1}`),t(m(s.url),`search: result ${r+1} needs an absolute http(s) url`),t(n(s.title),`search: result ${r+1} needs a title`),t(typeof s.snippet=="string",`search: result ${r+1} needs a snippet (may be empty)`),s.read!=null&&S(s.read)}),e}function C(e){t(a(e),"read: body must be an object"),t(m(e.url),"read: url (absolute http(s)) required");const s={url:e.url,format:"markdown"};return e.format!=null&&(t(c.includes(e.format),`read: format must be one of ${c.join(", ")}`),s.format=e.format),e.maxChars!=null&&(t(Number.isInteger(e.maxChars)&&e.maxChars>=200,"read: maxChars must be an integer ≥ 200"),s.maxChars=e.maxChars),e.snippet!=null&&(t(typeof e.snippet=="string","read: snippet must be a string"),s.snippet=e.snippet),e.provider!=null&&(t(n(e.provider),"read: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"read: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function S(e){t(a(e),"read: response must be an object"),t(m(e.url),"read: url (absolute, where the page landed) required"),t(typeof e.title=="string","read: title (string, may be empty) required"),t(c.includes(e.format),"read: format required");const s=e[e.format];t(typeof s=="string",`read: ${e.format} (string) required`),t(Number.isInteger(e.chars)&&e.chars===s.length,"read: chars must equal the content length"),t(typeof e.truncated=="boolean","read: truncated (boolean) required"),t(n(e.provider),"read: provider required"),t(d(e.ms)&&e.ms>=0,"read: ms required"),t(Array.isArray(e.sections),"read: sections[] required");for(const r of e.sections)t(a(r)&&n(r.id)&&n(r.heading),"read: section needs id and heading"),t(Number.isInteger(r.level)&&r.level>=1&&r.level<=6,`read: section ${r.id} needs level 1–6`),t(Number.isInteger(r.offset)&&r.offset>=0&&r.offset<=s.length,`read: section ${r.id} offset must index the content`);return e.restricted!=null&&t(a(e.restricted)&&h.includes(e.restricted.reason),`read: restricted.reason must be one of ${h.join(", ")}`),e}const $=Object.freeze(["choice","score","noul"]),M=/^[A-Za-z_][A-Za-z0-9_]*$/;function D(e){t(a(e),"decide: body must be an object"),t(n(e.state),"decide: state (non-empty string) required"),t(a(e.questions)&&Object.keys(e.questions).length>0,"decide: questions {} required");const s={};for(const[i,u]of Object.entries(e.questions)){t(M.test(i),`decide: question key ${JSON.stringify(i)} must be an identifier`),t(a(u)&&$.includes(u.type),`decide: question ${i}.type must be one of ${$.join(", ")}`),t(n(u.instructions),`decide: question ${i} needs instructions`);const l={type:u.type,instructions:u.instructions};u.type==="noul"?t(u.options==null,`decide: question ${i}: a noul has no options`):(t(Array.isArray(u.options)&&u.options.length>=2&&u.options.length<=255,`decide: question ${i}.options needs 2–255 entries`),l.options=u.options.map(o=>n(o)?{value:o}:(t(a(o)&&n(o.value),`decide: question ${i}: an option is a string or { value, describe? }`),o.describe!=null?{value:o.value,describe:String(o.describe)}:{value:o.value})),t(new Set(l.options.map(o=>o.value)).size===l.options.length,`decide: question ${i}.options must be distinct`)),s[i]=l}const r={state:e.state,questions:s};return e.model!=null&&(t(n(e.model),"decide: model must be a non-empty string"),r.model=e.model),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"decide: budgetMs must be a number ≥ 0"),r.budgetMs=e.budgetMs),r}function z(e,s=null){t(a(e),"decide: response must be an object"),t(a(e.answers),"decide: answers {} required"),t(n(e.model),"decide: model required"),t(d(e.ms)&&e.ms>=0,"decide: ms required"),e.calibrated!=null&&t(typeof e.calibrated=="boolean","decide: calibrated must be a boolean");const r=i=>d(i)&&i>=0&&i<=1;for(const i of Object.keys(s?s.questions:e.answers)){const u=e.answers[i];t(a(u),`decide: answer ${i} missing`),t(r(u.p),`decide: answer ${i}.p must be in [0,1]`),t(Array.isArray(u.options)&&u.options.every(o=>a(o)&&o.value!==void 0&&r(o.p)),`decide: answer ${i}.options must be [{ value, p }]`),u.confidence!=null&&t(r(u.confidence),`decide: answer ${i}.confidence must be in [0,1]`);const l=s?.questions?.[i];l?.type==="choice"&&t(l.options.some(o=>o.value===u.value),`decide: answer ${i}.value must be one of the options`),l?.type==="noul"&&t(typeof u.value=="boolean",`decide: answer ${i}.value must be a boolean`),l?.type==="score"&&t(d(u.value),`decide: answer ${i}.value must be a number`)}return e}function P(e){t(a(e),"rerank: body must be an object"),t(n(e.query),"rerank: query (non-empty string) required"),t(Array.isArray(e.documents)&&e.documents.length>=1&&e.documents.length<=1e3&&e.documents.every(r=>typeof r=="string"),"rerank: documents must be 1–1000 strings");const s={query:e.query,documents:e.documents.slice()};return e.top_n!=null&&(t(Number.isInteger(e.top_n)&&e.top_n>=1,"rerank: top_n must be an integer ≥ 1"),s.top_n=e.top_n),e.model!=null&&(t(n(e.model),"rerank: model must be a non-empty string"),s.model=e.model),e.budgetMs!=null&&(t(d(e.budgetMs)&&e.budgetMs>=0,"rerank: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function T(e,s=null){t(a(e),"rerank: response must be an object"),t(Array.isArray(e.results),"rerank: results[] required"),t(n(e.model),"rerank: model required"),t(d(e.ms)&&e.ms>=0,"rerank: ms required");const r=s?s.documents.length:1/0,i=new Set;let u=1/0;return e.results.forEach((l,o)=>{t(a(l)&&Number.isInteger(l.index)&&l.index>=0&&l.index<r,`rerank: result ${o} needs an index into the documents`),t(!i.has(l.index),`rerank: index ${l.index} listed twice`),i.add(l.index),t(d(l.relevance_score),`rerank: result ${o} needs relevance_score`),t(l.relevance_score<=u,"rerank: results must be ordered best first"),u=l.relevance_score}),s?.top_n!=null&&t(e.results.length<=s.top_n,`rerank: more than top_n (${s.top_n}) results`),e}function y(e){t(a(e),"capabilities: response must be an object"),t(Array.isArray(e.capabilities),"capabilities: capabilities[] required"),t(a(e.server)&&n(e.server.name)&&n(e.server.version),"capabilities: server {name, version} required");const s=new Set;for(const r of e.capabilities)t(a(r)&&x.includes(r.id),`capabilities: unknown capability id ${JSON.stringify(r?.id)}`),t(!s.has(r.id),`capabilities: ${r.id} listed twice`),s.add(r.id),t(r.route===b[r.id],`capabilities: ${r.id} must be served at ${b[r.id]}`),g.has(r.id)?(t(Array.isArray(r.providers)&&r.providers.length>0&&r.providers.every(n),`capabilities: ${r.id}.providers must be a non-empty string[]`),r.default!=null&&t(r.providers.includes(r.default),`capabilities: ${r.id}.default must be one of its providers`)):(t(Array.isArray(r.models)&&r.models.every(n),`capabilities: ${r.id}.models must be string[]`),r.default!=null&&t(r.models.includes(r.default),`capabilities: ${r.id}.default must be one of its models`)),r.labels!=null&&t(Array.isArray(r.labels)&&r.labels.every(n),`capabilities: ${r.id}.labels must be string[]`),r.stats!=null&&t(a(r.stats)&&(g.has(r.id)||d(r.stats.calls)),`capabilities: ${r.id}.stats needs calls`),r.runtime!=null&&t(a(r.runtime)&&n(r.runtime.state),`capabilities: ${r.id}.runtime needs state`),r.provider!=null&&j(r.provider,r.id);return e}function j(e,s="capability"){return t(a(e)&&p.includes(e.kind),`capabilities: ${s}.provider.kind must be one of ${p.join(", ")}`),e.egress!=null&&t(f.includes(e.egress),`capabilities: ${s}.provider.egress must be one of ${f.join(", ")}`),e.url!=null&&t(n(e.url)&&/^https?:\/\//.test(e.url),`capabilities: ${s}.provider.url must be http(s)`),e.adapter!=null&&t(n(e.adapter),`capabilities: ${s}.provider.adapter must be a string`),e.model!=null&&t(n(e.model),`capabilities: ${s}.provider.model must be a string`),e.label!=null&&t(n(e.label),`capabilities: ${s}.provider.label must be a string`),e}function B(e){return(e?.capabilities||[]).map(s=>({id:s.id,route:s.route,models:s.models||[],providers:s.providers||[],ready:!s.runtime||["ready","external","idle"].includes(s.runtime.state),stats:s.stats||null,labels:s.labels||null}))}export{x as CAPABILITIES,b as CAPABILITY_ROUTES,$ as DECIDE_QUESTION_TYPES,I as DISCOVERY_ROUTE,f as EGRESS_KINDS,A as OVER_BUDGET,g as PROVIDER_CAPABILITIES,p as PROVIDER_KINDS,c as READ_FORMATS,h as READ_RESTRICTIONS,v as SEARCH_FRESHNESS,B as offeredCapabilities,_ as overBudget,k as predictMs,y as validateCapabilitiesResponse,D as validateDecideRequest,z as validateDecideResponse,O as validateDetectRequest,w as validateDetectResponse,j as validateProvider,C as validateReadRequest,S as validateReadResponse,P as validateRerankRequest,T as validateRerankResponse,E as validateSearchRequest,N as validateSearchResponse};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{validateEvent as E,EventError as o}from"./event.js";const u="1.0",i="net.chatpanel",p="urn:chatpanel:host:",a=t=>typeof t=="string"&&t.length>0;function f(t){const e=Number(t);if(!Number.isFinite(e))throw new o("SHAPE","time: a finite epoch-ms number is required");return new Date(e).toISOString()}function d(t){return`${p}${encodeURIComponent(String(t))}`}function C(t){const e=String(t||"");return e.startsWith(p)?decodeURIComponent(e.slice(p.length)):null}function l(t,{source:e=null}={}){const n=E(t);return{specversion:u,id:n.id,source:e||d(n.host),type:`${i}.${n.type}`,time:f(n.at),datacontenttype:"application/json",seq:n.seq,host:n.host,causes:n.causes.join(","),chatpanelv:n.v,data:n.payload}}function w(t){if(!t||typeof t!="object")throw new o("CLOUDEVENT","a CloudEvent must be an object");if(t.specversion!==u)throw new o("CLOUDEVENT",`specversion ${t.specversion} is not ${u}`,t.specversion);if(!a(t.id))throw new o("CLOUDEVENT","id required");if(!a(t.type)||!t.type.startsWith(`${i}.`))throw new o("CLOUDEVENT",`type must start with ${i}.`,t.type);if(!a(t.time))throw new o("CLOUDEVENT","time required (RFC 3339)");const e=Date.parse(t.time);if(!Number.isFinite(e))throw new o("CLOUDEVENT",`time is not RFC 3339: ${t.time}`,t.time);const n=a(t.host)?t.host:C(t.source);if(!n)throw new o("CLOUDEVENT","host required (the `host` extension or a urn:chatpanel:host: source)");const r=Number(t.seq);if(!Number.isInteger(r)||r<0)throw new o("CLOUDEVENT","seq extension required: a non-negative integer");const h=Number(t.chatpanelv);if(!Number.isInteger(h))throw new o("CLOUDEVENT","chatpanelv extension required: the log schema version");const c=t.causes==null||t.causes===""?[]:Array.isArray(t.causes)?t.causes.map(String):String(t.causes).split(",").map(m=>m.trim()).filter(Boolean);let s=t.data;if(typeof s=="string")try{s=JSON.parse(s)}catch{throw new o("CLOUDEVENT","data is a string that is not JSON")}return E({v:h,id:t.id,host:n,seq:r,causes:c,at:e,type:t.type.slice(i.length+1),payload:s})}function v(t,e){const n=(t||[]).map(r=>JSON.stringify(l(r,e)));return n.length?`${n.join(`
|
|
2
|
+
`)}
|
|
3
|
+
`:""}function g(t){return String(t||"").split(`
|
|
4
|
+
`).map(e=>e.trim()).filter(Boolean).map(e=>w(JSON.parse(e)))}function O(t,e){return(t||[]).map(n=>l(n,e))}export{p as CE_SOURCE_PREFIX,u as CE_SPECVERSION,i as CE_TYPE_PREFIX,C as ceHostOf,d as ceSourceOf,w as fromCloudEvent,g as fromCloudEventLines,f as rfc3339,l as toCloudEvent,O as toCloudEventBatch,v as toCloudEventLines};
|
package/src/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as s,existsSync as d}from"node:fs";import{join as l}from"node:path";import p from"node:os";import{DEFAULT_MODEL as c}from"./models.js";import{DEFAULT_STT_MODEL as
|
|
1
|
+
import{readFileSync as s,existsSync as d}from"node:fs";import{join as l}from"node:path";import p from"node:os";import{DEFAULT_MODEL as c}from"./models.js";import{DEFAULT_STT_MODEL as u}from"./stt-models.js";const a={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],maxBodyBytes:26214400,pro:{entitlementToken:"",free:{used:0}},sandbox:{mode:"open",hosts:[],write:[],denyRead:[]},bridge:{url:"http://127.0.0.1:4319",agent:"codex",token:"",permissionMode:"default",workingDir:"",openAgentLane:!1},upstreams:{openai:{baseUrl:"https://api.openai.com"},anthropic:{baseUrl:"https://api.anthropic.com"}},redaction:{tier:"basic",dictionary:[],detection:{backend:"off"},redactSystem:!0},ner:{autostart:!0,model:c,union:[],warmMs:15*6e4,caseRecovery:!0,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:u,allowDownload:!0,diarize:!0,warmMs:15*6e4},read:{provider:"defuddle",remote:{url:"",key:""}},search:{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},capabilities:{},runtime:{services:{}},fusions:[],tts:{enabled:!0,warmMs:15*6e4,provider:"local",model:"",voice:"",allowDownload:!0,remote:{baseUrl:"",model:"",voice:"",redact:!0}},logRequests:!0,logDetail:"off"};function r(t,e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&t&&typeof t=="object"){const i={...t};for(const o of Object.keys(e))i[o]=r(t[o],e[o]);return i}return e===void 0?t:e}function _(t=process.env){let e=a;const i=t.CHATPANEL_GATEWAY_CONFIG||l(p.homedir(),".chatpanel","gateway.config.json");if(d(i))try{e=r(e,JSON.parse(s(i,"utf8")))}catch(n){throw new Error(`bad config file ${i}: ${n.message}`)}t.CHATPANEL_GATEWAY_HOST&&(e=r(e,{host:t.CHATPANEL_GATEWAY_HOST})),t.CHATPANEL_GATEWAY_PORT&&(e=r(e,{port:Number(t.CHATPANEL_GATEWAY_PORT)})),t.OPENAI_BASE_URL&&(e=r(e,{upstreams:{openai:{baseUrl:t.OPENAI_BASE_URL}}})),t.ANTHROPIC_BASE_URL&&(e=r(e,{upstreams:{anthropic:{baseUrl:t.ANTHROPIC_BASE_URL}}})),t.CHATPANEL_REDACTION_TIER&&(e=r(e,{redaction:{tier:t.CHATPANEL_REDACTION_TIER}}));const o=Number(e.port);return(!Number.isInteger(o)||o<1||o>65535)&&(e.port!==a.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(e.port)} — using ${a.port}`),e=r(e,{port:a.port})),e}export{a as DEFAULTS,_ as loadConfig};
|
package/src/configstore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{writeFileSync as y,mkdirSync as b,chmodSync as p}from"node:fs";import{join as w,dirname as A}from"node:path";import x from"node:os";import{usage as k}from"./freegate.js";import{assertEndpointUrl as a}from"@chatpanel/pii";import{normalizeGrant as D}from"@chatpanel/bridge/src/events/sandbox-policy.js";const f=["open","allowlist","off"],d=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=f.includes(r.mode)?r.mode:"open",{hosts:i}=D({hosts:r.hosts??[]});return{mode:o,hosts:i,write:d(r.write),denyRead:d(r.denyRead)}}function _(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 u(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||w(x.homedir(),".chatpanel","gateway.config.json")}function R(e,r=u()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===u({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);b(A(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,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox};y(r,JSON.stringify(o,null,2),{mode:384});try{p(r,384)}catch{}}function L(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:i,...n}=o;return{...n,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}},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||{}},capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([o,i])=>{const{token:n,...t}=i||{};return[o,{...t,hasToken:!!n}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:k(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 P(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function E(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),n=Number(o.port)||(o.protocol==="https:"?443:80);return i&&n===(Number(r.port)||4320)}const m=["default","acceptEdits","bypassPermissions"];function C(e,r={}){const o=e?.bridge||{};return{...m.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function M(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 n=E(i,e);return n&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!n}).map(i=>{const n={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(t=>typeof t=="string"&&t):[]};if(i.type==="agent"&&(n.agent=i.agent||i.id),i.type==="api"){n.baseUrl=String(i.baseUrl||""),n.protocol=i.protocol==="anthropic"?"anthropic":"openai";const t=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;t&&(n.apiKey=t)}return n})}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),m.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&&a(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&a(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(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const o of["rerank","decide"]){if(!(o in r.capabilities))continue;const i=r.capabilities[o];if(i===null){delete e.capabilities[o];continue}if(!i||typeof i!="object")continue;const t={...e.capabilities[o]||{}};if("url"in i){const s=String(i.url||"").trim();s&&a(s),t.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(t.adapter=i.adapter),typeof i.model=="string"&&(t.model=i.model.trim()),typeof i.token=="string"&&(t.token=i.token),typeof i.calibrated=="boolean"&&(t.calibrated=i.calibrated),!t.url){delete e.capabilities[o];continue}delete t.service,e.capabilities[o]=t}}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{m as PERMISSION_MODES,M as applyConfigPatch,P as applyNerModelSelection,C as bridgeAgentOptions,u as configPath,E as isSelfDestination,l as normalizeSandboxConfig,R as persistConfig,L as publicConfig,_ as sandboxEnvFor};
|
|
1
|
+
import{writeFileSync as b,mkdirSync as y,chmodSync as p}from"node:fs";import{join as A,dirname as w}from"node:path";import x from"node:os";import{usage as k}from"./freegate.js";import{applyFusionsPatch as f}from"./fusions.js";import{assertEndpointUrl as a}from"@chatpanel/pii";import{normalizeGrant as D}from"@chatpanel/bridge/src/events/sandbox-policy.js";const v=["open","allowlist","off"],l=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function d(e={}){const r=e&&typeof e=="object"?e:{},o=v.includes(r.mode)?r.mode:"open",{hosts:i}=D({hosts:r.hosts??[]});return{mode:o,hosts:i,write:l(r.write),denyRead:l(r.denyRead)}}function P(e){const r=d(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 u(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||A(x.homedir(),".chatpanel","gateway.config.json")}function R(e,r=u()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===u({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);y(w(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};b(r,JSON.stringify(o,null,2),{mode:384});try{p(r,384)}catch{}}function L(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:i,...n}=o;return{...n,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:d(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0}},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([o,i])=>{const{token:n,...t}=i||{};return[o,{...t,hasToken:!!n}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:k(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 C(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function E(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),n=Number(o.port)||(o.protocol==="https:"?443:80);return i&&n===(Number(r.port)||4320)}const m=["default","acceptEdits","bypassPermissions"];function M(e,r={}){const o=e?.bridge||{};return{...m.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function I(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 n=E(i,e);return n&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!n}).map(i=>{const n={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(n.agent=i.agent||i.id),i.type==="api"){n.baseUrl=String(i.baseUrl||""),n.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;s&&(n.apiKey=s)}const t=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;return t&&(n.service=t),n})}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),m.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=d({...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&&a(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&a(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=f(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]||{}};if(i.provider==="embedded"){e.capabilities[o]={provider:"embedded"},o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if("url"in i){const s=String(i.url||"").trim();s&&a(s),t.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(t.adapter=i.adapter),typeof i.model=="string"&&(t.model=i.model.trim()),typeof i.token=="string"&&(t.token=i.token),typeof i.calibrated=="boolean"&&(t.calibrated=i.calibrated),typeof i.redact=="boolean"&&(t.redact=i.redact),!t.url){delete e.capabilities[o];continue}t.provider="remote",delete t.service,e.capabilities[o]=t,o==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:t.url,...t.token?{apiKey:t.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{m as PERMISSION_MODES,I as applyConfigPatch,C as applyNerModelSelection,M as bridgeAgentOptions,u as configPath,E as isSelfDestination,d as normalizeSandboxConfig,R as persistConfig,L as publicConfig,P as sandboxEnvFor};
|
package/src/diarize-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ensureLib as H,modelRoot as P}from"./ner-engine.js";import{join as R}from"node:path";import{existsSync as T,readdirSync as E}from"node:fs";import{makeWarmTimer as
|
|
1
|
+
import{ensureLib as H,modelRoot as P}from"./ner-engine.js";import{join as R}from"node:path";import{existsSync as T,readdirSync as E}from"node:fs";import{makeWarmTimer as A}from"./warm-timer.js";const h="Xenova/wavlm-base-plus-sv";let i="off",c=null,p=null,g=null,f=null,d=null,a=null,_=0,b=0;function v(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function X(){return i}function k(){return i==="ready"&&!!c&&!!p}function Z(){return d}function B(){return{configured:i!=="off",ok:k(),state:i,model:c,error:g,warmMs:a?.warmMs??null}}function G(){return!!a?.pending()}function J(){_++,a?.disarm()}function K(){_=Math.max(0,_-1),_===0&&b===0&&k()&&a?.arm()}function w(){return _>0||b>0||i==="loading"||i==="downloading"}async function z({log:e=()=>{}}={}){if(w())return!1;a?.disarm();const t=c;if(c=null,p=null,f=null,d=null,g=null,i="off",t){try{await t.dispose?.()}catch{}e("[diarize] idle — speaker model unloaded (reloads on the next diarizing session)")}return!0}function O(e=h,t=v()){const n=R(P(),...e.split("/"),"onnx");if(!T(n))return!1;const o=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return E(n).some(s=>s===`model${o}.onnx`)}catch{return!1}}async function $({log:e=()=>{},allowDownload:t=!0}={}){let n;try{n=await H()}catch(r){return i="error",g=r.message,e(`[diarize] engine unavailable (${r.message})`),!1}const o=O();if(n.env.allowRemoteModels=o?!1:!!t,!o&&!t)return i="error",g="model not on disk and downloads disabled",!1;const s=n.env.remoteHost;if(!o)try{n.env.remoteHost="https://huggingface.co/"}catch{}i=o?"loading":"downloading",o||(d={model:h,file:null,pct:0},e(`[diarize] downloading ${h} (one-time)…`));try{const{AutoModel:r,AutoProcessor:l}=n,u=m=>{if(!m)return;const F=typeof m.progress=="number"?Math.round(m.progress):d?.pct??0;(m.status==="progress"||m.status==="download"||m.status==="initiate")&&(d={model:h,file:m.file||d?.file||null,pct:F})},y=await l.from_pretrained(h,{progress_callback:u}),x=await r.from_pretrained(h,{dtype:v(),progress_callback:u});return p=y,c=x,i="ready",g=null,d=null,e(`[diarize] ready — ${h} @ ${v()}`),!0}catch(r){return g=r.message,d=null,i="error",e(`[diarize] load failed (${r.message}) — diarization off`),!1}finally{try{n.env.remoteHost=s}catch{}}}function Q(e={}){if(f&&i!=="error")return f;i="loading";const t=typeof e.onLog=="function"?e.onLog:()=>{};return a=A({warmMs:e.warmMs,busy:w,log:t,unload:()=>z({log:t})}),f=D($({log:t,allowDownload:e.allowDownload!==!1})),f}function D(e){return e.then(t=>(t&&!w()&&a?.arm(),t))}function U({onLog:e}={}){return f=null,i="loading",a??=A({warmMs:void 0,busy:w,log:e||(()=>{}),unload:()=>z({log:e||(()=>{})})}),f=D($({log:e,allowDownload:!0})),f}const q=16e3;function M(e){let t=0;for(const o of e)t+=o*o;t=Math.sqrt(t)||1;const n=new Float32Array(e.length);for(let o=0;o<e.length;o++)n[o]=e[o]/t;return n}async function S(e){try{const t=await p(e),n=await c(t),o=n.embeddings??n.logits??n.last_hidden_state;return o?.data?Float32Array.from(o.data):null}catch{return null}}async function V(e){if(!k()||!(e instanceof Float32Array)||!e.length)return null;b++;try{return await I(e)}finally{b--,w()||a?.arm()}}async function I(e){const t=2*q,n=Math.round(1.3*q);if(e.length<=Math.round(t*1.4)){const r=await S(e);return r?M(r):null}const o=[];for(let r=0;r+t<=e.length;r+=n){const l=await S(e.subarray(r,r+t));l&&o.push(M(l))}if(!o.length){const r=await S(e);return r?M(r):null}const s=new Float32Array(o[0].length);for(const r of o)for(let l=0;l<s.length;l++)s[l]+=r[l];return M(s)}function Y(){a?.disarm(),a=null,_=0,b=0,i="off",c=null,p=null,g=null,f=null,d=null}function tt(e,t,{warmMs:n=null}={}){c=e,p=t,i=e?"ready":"off",n!==null&&(a=A({warmMs:n,busy:w,unload:()=>z()}),e&&a.arm())}function L(e,t){let n=0,o=0,s=0;for(let l=0;l<e.length;l++)n+=e[l]*t[l],o+=e[l]*e[l],s+=t[l]*t[l];const r=Math.sqrt(o)*Math.sqrt(s);return r?n/r:0}class et{constructor({threshold:t=.75,maxSpeakers:n=12}={}){this.threshold=t,this.maxSpeakers=n,this.centroids=[]}assign(t,{pinnedLabel:n=null,weak:o=!1,thin:s=!1}={}){if(!t)return null;if(n)return this._merge(this._find(n)||this._create(n),t);let r=null,l=-1;const u={};for(const y of this.centroids){const x=L(t,y.vec);u[y.label]=Math.round(x*1e3)/1e3,x>l&&(l=x,r=y)}return o&&r?{...this._merge(r,t,{update:!1}),scores:u,weak:!0}:r&&l>=this.threshold?{...this._merge(r,t),scores:u}:this.centroids.length>=this.maxSpeakers&&r?{...this._merge(r,t),scores:u}:s&&r?{...this._merge(r,t,{update:!1}),scores:u,thin:!0}:{...this._merge(this._create(`Speaker ${this.centroids.length+1}`),t),scores:u,...o?{weak:!0}:{}}}_find(t){return this.centroids.find(n=>n.label===t)||null}_create(t){const n={id:this.centroids.length+1,label:t,vec:null,n:0};return this.centroids.push(n),n}_merge(t,n,{update:o=!0}={}){if(!t.vec)t.vec=Float32Array.from(n),t.n=1;else if(o){for(let s=0;s<t.vec.length;s++)t.vec[s]=(t.vec[s]*t.n+n[s])/(t.n+1);t.n+=1}return{id:t.id,label:t.label}}}export{h as DIARIZE_MODEL,et as Diarizer,Y as _reset,tt as _setForTest,U as download,V as embed,B as health,Q as init,k as isReady,O as modelOnDisk,Z as progress,K as release,J as retain,X as state,z as unload,G as warmPending};
|
package/src/egress.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isBlockedHost as f}from"@chatpanel/pii";const
|
|
2
|
-
`)}export{v as createEgressLedger,k as declaredEgress,
|
|
1
|
+
import{isBlockedHost as f}from"@chatpanel/pii";const y=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url);return{host:t.hostname,port:t.port||(t.protocol==="https:"?"443":t.protocol==="http:"?"80":""),scheme:t.protocol.replace(":","")}}catch{return null}}const u=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=y}={}){const t=new Map;return{record(r){const s=g(r);if(!s||!s.host)return;const h=`${s.scheme}://${s.host}:${s.port}`,c=e(),o=t.get(h);if(o){o.count+=1,o.lastAt=c;return}t.set(h,{host:s.host,port:s.port,scheme:s.scheme,local:u(s.host),count:1,firstAt:c,lastAt:c})},snapshot(){return[...t.values()].sort((r,s)=>r.local===s.local?s.count-r.count:r.local?1:-1)},reset(){t.clear()}}}let w=null;function x(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const r=v();let s=t;r.setGate=c=>{s=c},r.blocked=[];const h=e.fetch;return typeof h=="function"&&(e.fetch=function(o,p){let a=null;try{a=g(o),r.record(o)}catch{}if(s&&a?.host){let i=!0;try{i=s(`${a.scheme}://${a.host}:${a.port}`,{local:u(a.host)})}catch{i=!0}if(!i){const n=`${a.host}:${a.port}`;r.blocked.includes(n)||r.blocked.push(n);const l=new Error(`egress to ${a.host} is blocked by your organisation’s policy`);return l.code="EGRESS_POLICY",Promise.reject(l)}}return h.call(this,o,p)}),e.__chatpanelEgress=r,e===globalThis&&(w=r),r}function $(){return w||(globalThis.__chatpanelEgress??null)}function d(e){try{return new URL(e).host}catch{return String(e||"")}}function k(e={},t=process.env){const r=[],s=(a,i,{when:n="always",off:l=null,local:m=!1,data:b=""}={})=>{a&&r.push({host:a,purpose:i,when:n,off:l,local:m,data:b})};s("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),s("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),s("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),s("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const h=e.search?.searxng?.url||"";if(h){let a=h;try{a=new URL(h).host}catch{}s(a,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(a)})}if(e.search?.provider!=="searxng"&&(s("www.startpage.com","web search: the built-in results-page search, 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"}),s("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{}s(a,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(a)})}const c={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[a,i]of Object.entries(c)){const n=e.capabilities?.[a];if(!n?.url||n.provider==="embedded")continue;let l=n.url;try{l=new URL(n.url).host}catch{}s(l,`${i.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:`${i.data}${n.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(l)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(s("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),s("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[a,i]of Object.entries(e.upstreams||{}))i?.baseUrl&&s(d(i.baseUrl),`model upstream "${a}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a}`,off:`upstreams.${a}.baseUrl`,local:u(d(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const a of e.destinations||[])a?.baseUrl&&s(d(a.baseUrl),`destination "${a.id||a.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a.id||"it"}`,off:"destinations[]",local:u(d(a.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});s("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&s(d(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:u(d(e.ner.url).split(":")[0]),data:"the text being redacted"});const o=e.tts||{};if(o.provider==="openai"||o.provider==="elevenlabs"){const a=o.remote?.baseUrl?d(o.remote.baseUrl):o.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";s(a,`remote read-aloud voice (${o.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:o.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}const p=e.bridge?.url||"http://127.0.0.1:4319";return s(d(p),"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 L(e,{ledger:t=$(),version:r="",startedAt:s=null,env:h=process.env,managed:c=null}={}){return{ok:!0,version:r,since:s?new Date(s).toISOString():null,...c?{managed:c,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:k(e,h)}}function S(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,s])=>s===!0?r:`${r}=${s}`).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,k as declaredEgress,L as egressAudit,$ as egressLedger,S as formatAudit,x as installEgressLedger};
|
|
@@ -0,0 +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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const j=864e5,m=n=>{try{return JSON.stringify(n).length}catch{return 0}},D=n=>{const s=[],a=(e,l)=>{if(!(!e||typeof e!="object"||l>3)){if(typeof e.hash=="string"&&typeof e.kind=="string"){s.push(e.hash);return}for(const y of Array.isArray(e)?e:Object.values(e))a(y,l+1)}};return a(n,0),s},k=n=>Math.round(n*1e3)/10;function I(n=[]){const s=Array.isArray(n)?n.filter(t=>t&&typeof t=="object"):[];let a=0,e=1/0,l=-1/0;const y={},g={},b=new Map,c=[];let v=0,M=0;for(const t of s){const r=m(t);a+=r,Number.isFinite(t.at)&&(t.at<e&&(e=t.at),t.at>l&&(l=t.at));const u=y[t.host]||(y[t.host]={events:0,bytes:0});u.events+=1,u.bytes+=r,g[t.type]=(g[t.type]||0)+1;const d=t.payload?.turnId;if(typeof d=="string"&&d){const p=b.get(d)||{events:0,bytes:0,surface:null};p.events+=1,p.bytes+=r,t.type==="turn.started"&&typeof t.payload.surface=="string"&&(p.surface=t.payload.surface),b.set(d,p)}c.push(...D(t.payload)),t.type==="capability.invoked"&&(v+=1),t.type==="capability.resulted"&&t.payload?.ok===!1&&(M+=1)}const i=s.length&&l>e?Math.max(1,(l-e)/864e5):s.length?1:0,o=[...b.values()],h=o.map(t=>t.events).sort((t,r)=>t-r),f={};for(const t of o){const r=t.surface||"unknown",u=f[r]||(f[r]={turns:0,events:0,bytes:0});u.turns+=1,u.events+=t.events,u.bytes+=t.bytes}for(const t of Object.values(f))t.avgEvents=Math.round(t.events/t.turns),t.avgBytes=Math.round(t.bytes/t.turns),delete t.events,delete t.bytes;const A=new Set(c).size;return{events:s.length,bytes:a,avgBytes:s.length?Math.round(a/s.length):0,span:{fromAt:Number.isFinite(e)?e:null,toAt:Number.isFinite(l)?l:null,days:Math.round(i*10)/10},perDay:{events:i?Math.round(s.length/i):0,bytes:i?Math.round(a/i):0},hosts:y,types:g,turns:{count:o.length,avgEvents:o.length?Math.round(o.reduce((t,r)=>t+r.events,0)/o.length):0,avgBytes:o.length?Math.round(o.reduce((t,r)=>t+r.bytes,0)/o.length):0,p95Events:h.length?h[Math.min(h.length-1,Math.floor(h.length*.95))]:0,bySurface:f},refs:{total:c.length,distinct:A,dedupHitRate:c.length?k(1-A/c.length):0},toolCalls:{total:v,perTurn:o.length?Math.round(v/o.length*10)/10:0,failed:M}}}function Y(n,{capEvents:s=2e4}={}){if(!n||!n.span?.days)return null;const a=Math.round(n.perDay.events*365),e=Math.round(n.perDay.bytes*365);return{eventsPerYear:a,bytesPerYear:e,daysToCap:n.perDay.events?Math.round(s/n.perDay.events):null}}export{I as eventStats,Y as projectYear};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{join as T}from"node:path";import{mkdirSync as O,chmodSync as A,existsSync as L}from"node:fs";import f from"node:os";import{openDb as S}from"./sqlite-store.js";import{validateEvent as C,EventError as M}from"./event.js";const p=T(f.homedir(),".chatpanel"),m=process.env.CHATPANEL_EVENTS_DB||T(p,"events.db"),I=25e3,d=2e4,y=250,b=16e3,a=1e3,D=`
|
|
2
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
3
|
+
id TEXT PRIMARY KEY,
|
|
4
|
+
host TEXT NOT NULL,
|
|
5
|
+
seq INTEGER NOT NULL,
|
|
6
|
+
at INTEGER NOT NULL,
|
|
7
|
+
type TEXT NOT NULL,
|
|
8
|
+
causes TEXT NOT NULL DEFAULT '[]',
|
|
9
|
+
payload TEXT NOT NULL,
|
|
10
|
+
v INTEGER NOT NULL DEFAULT 1,
|
|
11
|
+
UNIQUE (host, seq)
|
|
12
|
+
);
|
|
13
|
+
CREATE INDEX IF NOT EXISTS events_at ON events (at, host, seq);
|
|
14
|
+
CREATE INDEX IF NOT EXISTS events_type ON events (type, at);
|
|
15
|
+
`;class _{constructor({path:t=m,now:s=()=>Date.now()}={}){this.path=t,this.now=s,this.db=null,this._sinceCheck=0,this._watchers=new Set}async init(){if(this.path!==":memory:"){O(p,{recursive:!0,mode:448});const t=!L(this.path);if(this.db=await S(this.path),t)try{A(this.path,384)}catch{}}else this.db=await S(this.path);return this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec(D),this}append(t){if(C(t),this.db.get("SELECT 1 AS x FROM events WHERE id = ?",[t.id]))return{appended:!1,event:t};const s=this.db.get("SELECT MAX(seq) AS seq FROM events WHERE host = ?",[t.host])?.seq;if(Number.isFinite(s)&&s!==null&&t.seq<=s)throw new M("SEQ",`seq ${t.seq} <= ${s} already seen for host ${t.host}`,t.host);let e=JSON.stringify(t.payload);e.length>b&&(e=JSON.stringify({_clipped:!0,_chars:e.length,...q(t.payload)})),this.db.run("INSERT INTO events (id, host, seq, at, type, causes, payload, v) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[t.id,t.host,t.seq,t.at,t.type,JSON.stringify(t.causes),e,t.v]),this._sinceCheck+=1,this._sinceCheck>=y&&(this._sinceCheck=0,this.prune());for(const h of this._watchers)try{h(t)}catch{}return{appended:!0,event:t}}cursor(){const t={};for(const s of this.db.all("SELECT host, MAX(seq) AS seq FROM events GROUP BY host ORDER BY host"))t[s.host]=s.seq;return t}since(t={},{limit:s=a,host:e=null}={}){const h=Math.max(1,Math.min(a,Number(s)||a)),u=e?[e]:this.db.all("SELECT DISTINCT host FROM events ORDER BY host").map(n=>n.host),r=[];let i=!1;for(const n of u){if(r.length>=h){i=!0;break}const R=Number.isInteger(t?.[n])?t[n]:-1,c=this.db.all("SELECT * FROM events WHERE host = ? AND seq > ? ORDER BY seq ASC LIMIT ?",[n,R,h-r.length+1]);c.length>h-r.length&&(i=!0,c.length=h-r.length);for(const N of c)r.push(l(N))}const E={...t};for(const n of r)E[n.host]=Math.max(E[n.host]??-1,n.seq);return{events:r,cursor:E,more:i}}recent({limit:t=200,type:s=null}={}){const e=Math.max(1,Math.min(a,Number(t)||200));return(s?this.db.all("SELECT * FROM events WHERE type = ? ORDER BY at DESC, seq DESC LIMIT ?",[s,e]):this.db.all("SELECT * FROM events ORDER BY at DESC, host DESC, seq DESC LIMIT ?",[e])).map(l)}all(){return this.db.all("SELECT * FROM events ORDER BY at ASC, host ASC, seq ASC").map(l)}count(){return this.db.get("SELECT COUNT(*) AS n FROM events")?.n||0}hosts(){return this.db.all("SELECT host, COUNT(*) AS n, MAX(seq) AS seq, MAX(at) AS at FROM events GROUP BY host ORDER BY host")}prune(){const t=this.count();return t<=I?0:(this.db.run("DELETE FROM events WHERE id IN (SELECT id FROM events ORDER BY at ASC, host ASC, seq ASC LIMIT ?)",[t-d]),t-d)}watch(t){return this._watchers.add(t),()=>this._watchers.delete(t)}clear(){this.db.exec("DELETE FROM events")}}function l(o){return{v:o.v??1,id:o.id,host:o.host,seq:o.seq,at:o.at,type:o.type,causes:JSON.parse(o.causes||"[]"),payload:JSON.parse(o.payload)}}function q(o){const t={};for(const[s,e]of Object.entries(o||{}))t[s]=typeof e=="string"&&e.length>2e3?`${e.slice(0,2e3)}…`:e;return t}async function X(o={}){try{return await new _(o).init()}catch(t){return console.log(`[events] SQLite unavailable (${t.message}); the event log is off`),null}}export{_ as EventStore,I as MAX_EVENTS,a as PAGE_LIMIT,d as PRUNE_TO,X as createEventStore};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toCloudEvent as g,fromCloudEvent as m}from"./cloudevents.js";const d=Object.freeze({maxEvents:500,maxBytes:512*1024});function h({events:o=[],cursor:t={},host:e,maxEvents:r=d.maxEvents,maxBytes:n=d.maxBytes}={}){const c=Number.isInteger(t?.[e])?t[e]:-1,u=o.filter(s=>s&&s.host===e&&s.seq>c).sort((s,p)=>s.seq-p.seq),i=[];let f=0,a=null;for(const s of u){const p=g(s),l=JSON.stringify(p).length;if(i.length&&(i.length>=r||f+l>n))break;i.push(p),f+=l,a=s.seq}return{batch:i,seq:a,remaining:u.length-i.length}}function v(o,t){const e={appended:0,duplicates:0,rejected:[],events:[]};for(const r of Array.isArray(t)?t:[]){let n;try{n=m(r),o.append(n).appended?(e.appended+=1,e.events.push(n)):e.duplicates+=1}catch(c){e.rejected.push({id:typeof r?.id=="string"?r.id:null,code:c?.code||"INGEST",message:String(c?.message||c)})}}return e}function x(o){const t=o?.cursor??o;if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[r,n]of Object.entries(t))typeof r=="string"&&Number.isInteger(n)&&n>=0&&(e[r]=n);return e}export{d as PUSH_LIMITS,x as cursorOf,v as ingestCloudEvents,h as planEventPush};
|
package/src/event.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isRef as n}from"./ref.js";const i=1,v=Object.freeze({turn:["started","ended"],assistant:["prompted","message","reasoning"],context:["assembled","attached","expanded","retrieved"],capability:["offered","granted","denied","activated","revoked","invoked","resulted"],privacy:["redacted","egress"],policy:["changed","guard_denied"],data:["created","updated","deleted"],automation:["fired","suppressed"]}),m=Object.freeze(Object.entries(v).flatMap(([e,r])=>r.map(s=>`${e}.${s}`))),w=Object.freeze(["user","rule","schedule","model","agent","channel"]),x=Object.freeze(["global","site","tab","session","agent"]),u=Object.freeze(["R","M","L","C","A","X","H"]),S=Object.freeze(["pure","idempotent","replay-safe","non-replayable"]),k=Object.freeze(["none","redacted","delegated"]);class a extends Error{constructor(r,s,c=null){super(s),this.name="EventError",this.code=r,this.detail=c}}const t=e=>typeof e=="string"&&e.length>0,o=e=>typeof e=="number"&&Number.isFinite(e),l=e=>Array.isArray(e);function d(e){return!!e&&w.includes(e.kind)&&t(e.id)}function A(e){return!!e&&x.includes(e.kind)&&t(e.id)}const O={"turn.started":e=>t(e.turnId),"turn.ended":e=>t(e.turnId),"assistant.prompted":e=>t(e.turnId)&&n(e.ref),"assistant.message":e=>t(e.turnId)&&n(e.ref),"assistant.reasoning":e=>t(e.turnId)&&n(e.ref),"context.assembled":e=>o(e.budget)&&o(e.used)&&!!e.parts&&typeof e.parts=="object"&&l(e.resident)&&e.resident.every(n)&&o(e.reachableCount),"context.attached":e=>n(e.ref),"context.expanded":e=>n(e.ref)&&o(e.tokens),"context.retrieved":e=>t(e.tool)&&o(e.count)&&l(e.sources)&&e.sources.every(r=>r&&typeof r=="object"&&o(r.rank)),"capability.offered":e=>t(e.capability)&&t(e.reason),"capability.granted":e=>t(e.capability)&&d(e.actor),"capability.denied":e=>t(e.capability)&&d(e.actor),"capability.activated":e=>t(e.capability)&&u.includes(e.classUsed),"capability.revoked":e=>t(e.capability)&&t(e.cause),"capability.invoked":e=>t(e.capability)&&d(e.actor)&&A(e.scope)&&S.includes(e.effects)&&(e.effects==="pure"||t(e.idempotencyKey)),"capability.resulted":e=>t(e.capability)&&typeof e.ok=="boolean"&&u.includes(e.classUsed)&&!!e.cost&&o(e.cost.ms),"privacy.redacted":e=>!!e.counts&&typeof e.counts=="object"&&Object.values(e.counts).every(o),"privacy.egress":e=>t(e.host)&&typeof e.redacted=="boolean"&&typeof e.controlled=="boolean","policy.changed":e=>t(e.dial)&&d(e.actor)&&"from"in e&&"to"in e,"policy.guard_denied":e=>t(e.capability)&&t(e.reason),"data.created":e=>n(e.ref),"data.updated":e=>n(e.ref),"data.deleted":e=>n(e.ref)&&typeof e.shredded=="boolean","automation.fired":e=>t(e.ruleId)&&u.includes(e.classUsed),"automation.suppressed":e=>t(e.ruleId)&&t(e.reason)};function y(e){if(!e||typeof e!="object")throw new a("SHAPE","event must be an object");if(e.v!==i)throw new a("VERSION",`expected v=${i}, got ${e.v} — upcast first`,e.v);if(!t(e.id))throw new a("SHAPE","id required");if(!t(e.host))throw new a("SHAPE","host required");if(!Number.isInteger(e.seq)||e.seq<0)throw new a("SHAPE","seq must be a non-negative integer");if(!l(e.causes)||!e.causes.every(t))throw new a("SHAPE","causes must be string[]");if(!o(e.at))throw new a("SHAPE","at required (advisory wall clock)");if(!m.includes(e.type))throw new a("TYPE",`unknown type ${e.type}`,e.type);if(!e.payload||typeof e.payload!="object")throw new a("SHAPE","payload required");const r=O[e.type];if(r&&!r(e.payload))throw new a("PAYLOAD",`payload invalid for ${e.type}`,e.type);return e}function I(e){try{return y(e),!0}catch{return!1}}function P({host:e,seq:r=0,now:s=()=>Date.now(),newId:c}){if(!t(e))throw new a("SHAPE","host required");const p=c||(()=>globalThis.crypto.randomUUID());let f=r;return{get host(){return e},get seq(){return f},append(b,h,E=[]){const g=Object.freeze({v:i,id:p(),host:e,seq:f++,causes:Object.freeze([...E]),at:s(),type:b,payload:h});return y(g)}}}export{w as ACTOR_KINDS,m as ALL_TYPES,u as CLASSES,i as CURRENT_VERSION,S as EFFECTS,k as EGRESS,v as EVENT_TYPES,a as EventError,x as SCOPE_KINDS,P as createAppender,I as isValidEvent,y as validateEvent};
|
package/src/fusions.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{FUSION_KINDS as l,validateFusion as c,pickMember as p,describeFusion as m,fusionIdOf as b,normalizeMember as y}from"@chatpanel/events/model-fusion.js";function k(r){const e=r?.active||r?.model||null,t=(r?.companions||[]).filter(i=>i.state==="ready"||i.state==="loaded").map(i=>i.model);return!e||!t.length?null:{id:"ner-union",kind:"union",capability:"detect",members:[e,...t],source:"ner",derived:!0}}function v(r){const e=[];for(const[t,i]of Object.entries(r?.services||{})){if(!i||typeof i!="object"||!Array.isArray(i.tunings)||!i.model)continue;const n=a=>{const u=i.tunings.find(f=>f.id===a);return u?u.value!==void 0?u.value:u.default:void 0},o=n("speculative"),s=n("draftModel");(o==="draft-mtp"||o==="draft")&&s&&e.push({id:`${t}-draft`,kind:"draft",capability:"chat",members:[{id:i.model,role:"target"},{id:s,role:"draft"}],source:t,derived:!0,running:i.state==="running"})}return e}function d(r){return(Array.isArray(r.fusions)?r.fusions:[]).filter(e=>e&&typeof e=="object")}function g(r,e){if(e===null)return r.fusions=[],null;if(!Array.isArray(e))return"fusions: a list";const t=[];for(const i of e){const n=c(i);if(n)return`fusions ${JSON.stringify(i?.id??"?")}: ${n}`;if(t.some(o=>o.id===i.id))return`fusions: id ${JSON.stringify(i.id)} twice`;if(i.id==="ner-union"||/-draft$/.test(i.id))return`fusions: ${JSON.stringify(i.id)} is a derived id`;t.push({id:i.id,kind:i.kind,capability:i.capability,members:i.members.map(y),...i.label?{label:String(i.label).slice(0,80)}:{}})}return r.fusions=t,null}function x({cfg:r,ner:e=null,runtimeDoc:t=null,nameOf:i=n=>n}){const n=[k(e),...v(t),...d(r)].filter(Boolean);return{kinds:l,fusions:n.map(o=>({...o,describe:m(o,i)}))}}function F(r,e,t=()=>"unknown"){const i=b(r);if(!i)return null;const n=d(e).find(s=>s.id===i);if(!n)return{error:`no fusion "${i}" on this gateway`};if(n.kind!=="fallback"||n.capability!=="chat")return{error:`fusion "${i}" is a ${n.kind} for ${n.capability} — only a chat fallback can be sent a turn`};const o=p(n,t);return o.member?{model:o.member.id,fusion:n,next:o.next.map(s=>s.id),skipped:o.skipped.map(s=>s.id)}:{error:`fusion "${i}": every member is down (${o.skipped.map(s=>s.id).join(", ")})`}}export{g as applyFusionsPatch,d as composedFusions,v as draftFusions,x as fusionsDocument,k as nerUnionFusion,F as resolveFusionModel};
|
package/src/images.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
const e=Object.freeze({"vllm-cpu":{tag:"ghcr.io/chatpanel/vllm:latest",what:"vLLM’s CPU build (arm64 and amd64) with the audio extras — a chat, embedding or whisper model on a machine without a GPU",minutes:90,dockerfile:`ARG VLLM_VERSION=v0.29.0
|
|
2
|
+
FROM python:3.12-slim AS build
|
|
3
|
+
ARG VLLM_VERSION
|
|
4
|
+
RUN apt-get update && apt-get install -y --no-install-recommends git build-essential cmake ninja-build libnuma-dev curl ca-certificates \\
|
|
5
|
+
&& rm -rf /var/lib/apt/lists/*
|
|
6
|
+
# Since 0.29 vLLM carries a Rust crate (vllm-rs) that setuptools-rust builds inside
|
|
7
|
+
# \`pip install .\`, so the build stage needs cargo — rustup pinned by the tree's own
|
|
8
|
+
# rust-toolchain.toml. The runtime image below carries none of this.
|
|
9
|
+
RUN curl -sSf https://sh.rustup.rs | sh -s -- -y --no-modify-path --profile minimal
|
|
10
|
+
ENV PATH=/root/.cargo/bin:$PATH CARGO_BUILD_JOBS=4
|
|
11
|
+
WORKDIR /src
|
|
12
|
+
RUN git clone --depth 1 --branch \${VLLM_VERSION} https://github.com/vllm-project/vllm.git .
|
|
13
|
+
# vLLM's own CPU recipe (docker/Dockerfile.cpu): the build requirements with CPU-only torch
|
|
14
|
+
# from PyTorch's CPU wheel index, the CPU runtime requirements, then vLLM for the CPU target.
|
|
15
|
+
RUN pip install --no-cache-dir --upgrade pip \\
|
|
16
|
+
&& pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cpu -r requirements/build/cpu.txt \\
|
|
17
|
+
&& pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cpu -r requirements/cpu.txt \\
|
|
18
|
+
&& VLLM_TARGET_DEVICE=cpu pip install --no-cache-dir --no-build-isolation .
|
|
19
|
+
|
|
20
|
+
FROM python:3.12-slim
|
|
21
|
+
RUN apt-get update && apt-get install -y --no-install-recommends libnuma1 libgomp1 curl ffmpeg \\
|
|
22
|
+
&& rm -rf /var/lib/apt/lists/* \\
|
|
23
|
+
&& useradd --create-home --uid 10001 vllm
|
|
24
|
+
COPY --from=build /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages
|
|
25
|
+
COPY --from=build /usr/local/bin/vllm /usr/local/bin/vllm
|
|
26
|
+
# The audio route needs the audio extras (librosa, soundfile); small, and only used by a whisper.
|
|
27
|
+
RUN pip install --no-cache-dir librosa soundfile
|
|
28
|
+
USER vllm
|
|
29
|
+
ENV HF_HOME=/data VLLM_CPU_KVCACHE_SPACE=4 VLLM_LOGGING_LEVEL=INFO
|
|
30
|
+
EXPOSE 8000
|
|
31
|
+
HEALTHCHECK --interval=30s --timeout=5s --start-period=600s CMD curl -fsS http://127.0.0.1:8000/health || exit 1
|
|
32
|
+
ENTRYPOINT ["vllm", "serve"]
|
|
33
|
+
CMD ["Qwen/Qwen3-0.6B", "--host", "0.0.0.0", "--port", "8000"]
|
|
34
|
+
`}});export{e as IMAGE_RECIPES};
|
|
@@ -0,0 +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: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,n){return e==="cuda"?n==="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:n=process.platform,arch:t=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 n==="darwin"&&t==="arm64"?"apple":await l("nvidia-smi",["-L"])?"cuda":n==="linux"&&await l("rocm-smi",["--showid"])?"rocm":n==="linux"&&await l("sycl-ls",[])?"xpu":null}function M({platform:e=process.platform,arch:n=process.arch,accelerator:t=null,engine:l=null,vllmOnPath:a=!1,containerOnly:i=!1}={}){return e==="darwin"&&(n==="arm64"||t==="apple")&&i?{backend:"cpu",kind:"container",image:o.cpu,sources:h(n),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"&&(n==="arm64"||t==="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?t==="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."}:{}}:t==="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."}:t==="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(n),recipe:"vllm-cpu",devices:[],for:"an embedding model or a whisper transcriber; a small chat model to try",speed:`slow: CPU only${n==="x64"?"":"; a 90-minute build first"}`,why:`No accelerator found: vLLM’s CPU build (${n}). Small models only; slow.`,warn:"CPU inference — a 0.6B chat model is usable, anything larger wants a GPU."}:{backend:t==="cuda"?"cuda":t==="rocm"?"rocm":t==="xpu"?"xpu":"cpu",kind:"container",image:null,devices:[],why:"No container engine yet — Settings › Runtime has the install door.",warn:"no container engine"}}const f=Object.freeze({darwin:{command:"brew install llama.cpp",steps:[["brew","install","llama.cpp"]],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 P({platform:e=process.platform,arch:n=process.arch,accelerator:t=null,llamaOnPath:l=!1}={}){const a=e==="darwin"&&n==="arm64"?"metal":t==="cuda"?"cuda":t==="rocm"?"rocm":t==="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 y({exec:e,platform:n=process.platform,totalmem:t=()=>0,cpus:l=()=>[]}={}){const a=Math.round(t()/1073741824),i=l().length||0;let r=Math.max(1,Math.floor(i/2))||1,c=r;if(n==="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:n=process.arch,mlxOnPath:t=!1}={}){return e==="darwin"&&n==="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.",...t?{}:{warn:"`mlx_lm.server` is not on PATH — install mlx-lm (the command beside this), then Run."}}:{backend:"none",kind:"native",runner:"mlx_lm.server",why:"MLX runs on Apple Silicon only.",install:v}}function k({platform:e=process.platform,arch:n=process.arch,accelerator:t=null}={}){return e==="darwin"&&n==="arm64"?{engine:"llama",why:"Apple Silicon: llama.cpp on Metal is the mature path — the largest choice of models (GGUF), vision, and the MTP draft that makes a big model fast. MLX is the lighter alternative."}:t==="cuda"||t==="rocm"||t==="xpu"?{engine:"vllm",why:`${t.toUpperCase()} GPU: vLLM in a container serves a full-precision model at speed, with batching for several users.`}:{engine:"llama",why:"No GPU found: llama.cpp with a 4-bit model is what runs well on a CPU."}}export{f as LLAMA_INSTALL,v as MLX_INSTALL,o as VLLM_IMAGES,L as VLLM_METAL_INSTALL,s as VLLM_VERSION,x as detectAccelerator,m as deviceArgs,y as hostShape,M as pickInferenceEngine,P as pickLlamaEngine,U as pickMlxEngine,k as recommendEngine,h as vllmCpuSources};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createWriteStream as F,mkdirSync as $,renameSync as L,existsSync as g,writeFileSync as E,statSync as A,readFileSync as T,readdirSync as R}from"node:fs";import{Readable as G}from"node:stream";import{pipeline as H}from"node:stream/promises";import c from"node:path";const b="https://huggingface.co",I=/\.(bin|pt|pth|ckpt|h5|msgpack|onnx|gguf|tflite)$/i,M=/(^|\/)(\.gitattributes|README\.md|LICENSE.*|.*\.md|original\/.*|coreml\/.*|onnx\/.*|images?\/.*|assets\/.*)$/i;function y(t){const r=/^([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}))?$/.exec(String(t||"").trim());return r?{repo:r[1],quant:r[2]||null}:null}const x=(t,r)=>c.join(t,"hub",`models--${r.replace("/","--")}`);async function z(t,{fetchImpl:r=globalThis.fetch,token:n=null}={}){const o=await r(`${b}/api/models/${t}?blobs=true`,{headers:n?{authorization:`Bearer ${n}`}:{},signal:AbortSignal.timeout(2e4)});if(o.status===401||o.status===403)throw new Error(`${t}: gated or private on Hugging Face — accept its licence there and add a token`);if(o.status===404)throw new Error(`${t}: no such model on Hugging Face`);if(!o.ok)throw new Error(`${t}: Hugging Face answered ${o.status}`);const l=await o.json(),i=(l.siblings||[]).map(e=>({path:e.rfilename,size:Number(e.lfs?.size??e.size??0)})).filter(e=>e.path);return{commit:String(l.sha||"main"),siblings:i}}function Q(t){const r=t.some(o=>/\.safetensors$/i.test(o.path)),n=t.filter(o=>!(M.test(o.path)||r&&I.test(o.path)||!r&&/\.(gguf|onnx|tflite|msgpack|h5|ckpt)$/i.test(o.path)));return{files:n,total:n.reduce((o,l)=>o+l.size,0)}}function Z(t,r=null){const n=t.filter(e=>/\.gguf$/i.test(e.path)&&!/mmproj/i.test(e.path));if(!n.length)throw new Error("no GGUF file in this repo");const o=(r||"Q4_K_M").toLowerCase();let i=(e=>n.filter(s=>s.path.toLowerCase().includes(`-${e}.`)||s.path.toLowerCase().includes(`-${e}-0`)||s.path.toLowerCase().includes(`.${e}.`)||s.path.toLowerCase().includes(`/${e}/`)||s.path.toLowerCase().includes(`_${e}.`)))(o);if(!i.length&&!r&&(i=n.length===1?n:[]),!i.length)throw new Error(`no ${r||"Q4_K_M"} GGUF here — the repo has: ${[...new Set(n.map(e=>B(e.path)))].slice(0,12).join(", ")}`);return i=i.slice().sort((e,s)=>e.path.localeCompare(s.path)),{files:i,total:i.reduce((e,s)=>e+s.size,0),main:i[0].path}}function B(t){const r=c.basename(t).replace(/\.gguf$/i,"").replace(/-\d{5}-of-\d{5}$/,""),n=/-((?:UD-)?(?:I?Q\d[A-Z0-9_]*|BF16|F16|F32|MTP))$/i.exec(r);return n?n[1]:r}const m=(t,r,n)=>c.join(t,"gguf",r.replace("/","--"),c.basename(n));async function S({repo:t,commit:r,files:n,destOf:o,fetchImpl:l=globalThis.fetch,token:i=null,onProgress:e=()=>{},total:s=0}){let u=0;for(const a of n){const p=o(a.path);if(g(p)&&a.size&&A(p).size===a.size){u+=a.size,e({file:a.path,bytes:u,total:s,fileBytes:a.size,fileTotal:a.size,skipped:!0});continue}$(c.dirname(p),{recursive:!0,mode:448});const h=await l(`${b}/${t}/resolve/${encodeURIComponent(r)}/${a.path.split("/").map(encodeURIComponent).join("/")}`,{headers:i?{authorization:`Bearer ${i}`}:{},redirect:"follow"});if(!h.ok||!h.body)throw new Error(`${a.path}: Hugging Face answered ${h.status}`);let f=0;const C=new TransformStream({transform(d,_){f+=d.byteLength,u+=d.byteLength,e({file:a.path,bytes:u,total:s,fileBytes:f,fileTotal:a.size}),_.enqueue(d)}}),w=`${p}.part`;await H(G.fromWeb(h.body.pipeThrough(C)),F(w,{mode:384})),L(w,p)}return u}async function O(t,{root:r,fetchImpl:n=globalThis.fetch,token:o=null,onProgress:l=()=>{}}={}){const{commit:i,siblings:e}=await z(t,{fetchImpl:n,token:o}),{files:s,total:u}=Q(e);if(!s.length)throw new Error(`${t}: nothing to download (no weights or config listed)`);const a=x(r,t),p=c.join(a,"snapshots",i),h=await S({repo:t,commit:i,files:s,total:u,destOf:f=>c.join(p,f),fetchImpl:n,token:o,onProgress:l});return $(c.join(a,"refs"),{recursive:!0,mode:448}),E(c.join(a,"refs","main"),i,{mode:384}),{dir:p,commit:i,files:s.map(f=>f.path),bytes:h,total:u}}async function k(t,{root:r,fetchImpl:n=globalThis.fetch,token:o=null,onProgress:l=()=>{}}={}){const i=y(t);if(!i)throw new Error(`not a model id: ${t}`);const{commit:e,siblings:s}=await z(i.repo,{fetchImpl:n,token:o}),{files:u,total:a,main:p}=Z(s,i.quant),h=await S({repo:i.repo,commit:e,files:u,total:a,destOf:f=>m(r,i.repo,f),fetchImpl:n,token:o,onProgress:l});return{main:m(r,i.repo,p),files:u.map(f=>m(r,i.repo,f.path)),bytes:h,total:a}}function D(t,r){const n=x(t,r);try{const o=T(c.join(n,"refs","main"),"utf8").trim();return!!o&&g(c.join(n,"snapshots",o))&&g(c.join(n,"snapshots",o,"config.json"))}catch{return!1}}function P(t,r){const n=y(r);if(!n)return null;const o=c.join(t,"gguf",n.repo.replace("/","--"));if(!g(o))return null;const l=(n.quant||"Q4_K_M").toLowerCase(),i=j(o).filter(e=>/\.gguf$/i.test(e)&&!e.endsWith(".part")&&(e.toLowerCase().includes(`-${l}.`)||e.toLowerCase().includes(`-${l}-0`)||e.toLowerCase().includes(`.${l}.`)||e.toLowerCase().includes(`_${l}.`)||!n.quant&&j(o).filter(s=>/\.gguf$/i.test(s)).length===1)).sort();return i.length?c.join(o,i[0]):null}function j(t){try{return R(t)}catch{return[]}}export{b as HF_API,z as describeRepo,S as downloadFiles,P as ggufInstalled,m as ggufPath,y as parseModelRef,Z as planGgufFiles,Q as planRepoFiles,k as pullGguf,O as pullRepo,B as quantOf,x as repoCacheDir,D as repoInstalled};
|