@chatpanel/gateway 0.19.2 → 0.23.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/chatpanel-gateway.js +6 -3
- package/package.json +1 -1
- package/src/capabilities.js +1 -1
- package/src/capability-adapters.js +1 -0
- package/src/capability-endpoints.js +1 -1
- package/src/capability-providers.js +3 -0
- package/src/capability-proxy.js +1 -0
- package/src/capability-tools.js +3 -0
- package/src/config.js +1 -1
- package/src/configstore.js +1 -1
- package/src/egress.js +2 -2
- package/src/mcp.js +20 -20
- package/src/model-file-cache.js +1 -0
- package/src/ner-engine.js +1 -1
- package/src/ner.js +1 -1
- package/src/redact.js +2 -2
- package/src/runtime-models.js +1 -0
- package/src/runtime.js +3 -3
- package/src/server.js +14 -14
- package/src/service.js +23 -10
- package/src/shutdown.js +1 -0
- package/src/web-search-tool.js +19 -0
package/bin/chatpanel-gateway.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const
|
|
3
|
-
`)}process.argv.includes("--json")?console.log(JSON.stringify(
|
|
4
|
-
|
|
2
|
+
const o=process.argv[2];try{process.title=o==="--bridge"?"chatpanel-bridge":o==="--mcp-stdio"?"chatpanel-gateway-mcp":"chatpanel-gateway"}catch{}try{if(o==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:e}=await import("../src/extract/worker.js");e()}else if(o==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(o==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(o==="mcp"){const{runMcpServer:e}=await import("../src/mcp.js");await e()}else if(o==="tools"||o==="call"){const{runMcpCli:e}=await import("../src/mcp-cli.js");process.exit(await e(process.argv.slice(2)))}else if(o==="policy"){const{loadPolicy:e,formatPolicy:s,PolicyLoadError:n}=await import("../src/policy.js");try{const r=await e();process.argv.includes("--json")?console.log(JSON.stringify(r?{...r,label:void 0}:null,null,2)):console.log(s(r))}catch(r){throw r instanceof n&&(console.error(`org policy: ${r.message}`),process.exit(78)),r}}else if(o==="--audit"){const{egressAudit:e,formatAudit:s}=await import("../src/egress.js"),{loadConfig:n}=await import("../src/config.js"),{readFileSync:r}=await import("node:fs"),{join:p}=await import("node:path"),l=await import("node:os"),c=n(),t=`http://127.0.0.1:${c.port||4320}`;let a=null,i=`no gateway running at ${t}`;try{const h=r(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||p(l.homedir(),".chatpanel","gateway-token"),"utf8").trim(),g=await fetch(`${t}/audit`,{headers:{authorization:`Bearer ${h}`},signal:AbortSignal.timeout(2500)});if(g.ok)a=await g.json();else if(g.status===404){const d=await fetch(`${t}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);i=`the gateway running at ${t}${d?.version?` (${d.version})`:""} predates --audit (0.7.0) — restart it after updating`}else i=`the gateway at ${t} refused the audit (HTTP ${g.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!a){const{VERSION:h}=await import("../src/server.js");a={...e(c,{ledger:null,version:h}),observed:[]},console.log(`(${i}; showing what the current config allows)
|
|
3
|
+
`)}process.argv.includes("--json")?console.log(JSON.stringify(a,null,2)):console.log(s(a))}else if(o==="sandbox"){const{srtModuleUrl:e}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&e()&&(process.env.CHATPANEL_SRT_MODULE=e());const{runSandboxCli:s}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await s(process.argv.slice(3)))}else if(o==="pair"){const{loadConfig:e}=await import("../src/config.js"),{readFileSync:s}=await import("node:fs"),{join:n}=await import("node:path"),r=await import("node:os"),l=`http://127.0.0.1:${e().port||4320}`,c=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||n(r.homedir(),".chatpanel","gateway-token");try{const t=s(c,"utf8").trim(),a=await fetch(`${l}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),i=await a.json().catch(()=>({}));if(a.status===404)throw new Error(`the gateway at ${l} predates pairing (0.9.0) — update and restart it`);if(!a.ok)throw new Error(i.error||`HTTP ${a.status}`);console.log(`Pairing code: ${i.display||i.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(t){console.error(`could not get a pairing code from the gateway at ${l}: ${t?.message||t}${/ENOENT/.test(String(t?.message))?` (no token at ${c} — has the gateway started once?)`:""}`),process.exit(1)}}else if(o==="local"){const{localStatus:e,formatLocalStatus:s}=await import("../src/local-status.js");process.stdout.write(s(await e()))}else if(o==="connect"){const{connectAgents:e,formatConnect:s}=await import("../src/connect-agents.js"),n=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(s(e({dryRun:n}),{dryRun:n}))}else{const{start:e,VERSION:s}=await import("../src/server.js"),{installService:n,uninstallService:r,serviceReport:p,stopService:l,pathWithDir:c}=await import("../src/service.js");switch(o){case"--stop":l(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(s);break;case"--install":{const t=await n(),a=t.health;if(a.ok){const i=a.managedBy&&a.managedBy!=="gateway"?` — the ${a.managedBy} app's gateway is the one answering right now; this install takes over at the next login`:"";console.log(`ChatPanel Privacy Gateway v${a.version}: running at ${a.url}, starts at login${t.wsl?" (Windows login, through wsl.exe)":""}${i}.`)}else console.error(`ChatPanel Privacy Gateway: login auto-start is registered, but nothing answered at ${a.url} after 40 s.`),t.errLog&&console.error(` last of the error log:
|
|
4
|
+
${t.errLog.split(`
|
|
5
|
+
`).map(i=>` ${i}`).join(`
|
|
6
|
+
`)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself.");t.launcher==="powershell"&&console.log(" (VBScript is not installed here, so the login launcher is PowerShell — a console flashes for an instant at login.)"),t.path?.added?console.log(` Added ${t.path.dir} to your PATH — \`chatpanel-gateway\` works in a NEW terminal.`):t.path?.error?console.log(` Could not add ${t.path.dir} to your PATH (${t.path.error}) — add it yourself to run \`chatpanel-gateway\` by name.`):t.path?.dir&&t.wsl&&c(process.env.PATH||"",t.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${t.path.dir}:$PATH"`),a.ok||process.exit(1);break}case"--uninstall":r(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(await p());break;case void 0:await e();break;default:console.error(`unknown option: ${o}
|
|
7
|
+
Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|pair|policy|--audit|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(e){console.error(`error: ${e.message}`),process.exit(1)}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.23.2",
|
|
4
4
|
"description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/capabilities.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as s from"./ner-engine.js";import*as
|
|
1
|
+
import*as s from"./ner-engine.js";import*as E from"./stt-engine.js";import*as A from"./tts-engine.js";import{MODEL_CATALOG as L,DEFAULT_MODEL as q}from"./models.js";import{STT_MODEL_CATALOG as M,DEFAULT_STT_MODEL as w}from"./stt-models.js";import{TTS_MODEL_CATALOG as S,resolveDefaultModel as k}from"./tts-models.js";import{rawOrtAvailable as C}from"./ort.js";import{CAPABILITY_ROUTES as y,overBudget as R,validateDetectRequest as U}from"./capability-endpoints.js";import{extractCapabilityEntry as $}from"./extract/handler.js";const h=e=>[...new Set(e.filter(Boolean))];function b(e,i={}){return{state:e.state||"off",name:e.runtime||null,dtype:e.dtype||null,error:e.error||null,...i}}function Y(e,{version:i="",reader:o=null,searcher:t=null,extract:d=null,proxy:u=null}={}){const l=s.health(),a=e?.redaction?.detection,r=!!(a&&a.backend&&a.backend!=="off"),m=l.model||e?.ner?.model||q,g=E.health(),x=A.health(),v=x.model||e?.tts?.model||k(C()),c=[{id:"detect",route:y.detect,models:h([m,...L.map(n=>n.id)]),default:m,union:l.companions?.filter(n=>n.state==="ready").map(n=>n.model)||[],labels:s.isReady()?s.labels():[],maxTokens:s.isReady()?s.maxTokens():null,requirements:{egress:"none",deterministic:!0},stats:l.stats||{calls:0},runtime:r?{state:"external",name:a.backend,url:a.url||null}:b(l,{installed:s.modelOnDisk(m)})},{id:"stt",route:y.stt,streaming:"/stt/sessions",models:h([g.model||e?.stt?.model||w,...M.map(n=>n.id)]),default:g.model||e?.stt?.model||w,requirements:{egress:"none"},runtime:b(g)},{id:"tts",route:y.tts,voices:"/tts/voices",models:h([v,...S.map(n=>n.id)]),default:v,requirements:{egress:"none"},runtime:b(x)}],T=e?.read||{},O=!!T.remote?.url;c.push({id:"read",route:y.read,providers:o?o.providers():["defuddle","text",...O?["remote"]:[]],default:T.provider||"defuddle",requirements:{egress:"web"},stats:o?o.stats():{calls:0},runtime:{state:"ready",cache:o?o.cache.size():0,remote:O?"configured":"off"}});const p=e?.search||{},f=!!p.searxng?.url,D=t?.searxng?t.searxng.state():f?"unknown":"off";if(c.push({id:"search",route:y.search,providers:t?t.providers():["serp",...f?["searxng"]:[]],default:p.provider==="searxng"||p.provider==="serp"?p.provider:f?"searxng":"serp",requirements:{egress:"web"},stats:t?t.stats()[f?"searxng":"serp"]||{calls:0}:{calls:0},runtime:{state:"ready",searxng:D,...f?{searxngUrl:p.searxng.url}:{}}}),d)try{c.push($(d))}catch{}if(u)for(const n of u.capabilities){const _=u.entry(n);_&&c.push(_)}return{capabilities:c,server:{name:"chatpanel-gateway",version:String(i),audit:"/audit"}}}async function j(e,{ensure:i=async()=>s.state(),model:o=null}={}){let t;try{t=U(e)}catch(r){return{status:400,body:{error:{message:r.message,type:"invalid_request"}}}}if(t.model&&o&&t.model!==o)return{status:404,body:{error:{message:`model ${t.model} is not loaded here (serving ${o})`,type:"model_not_found"}}};if(await i(),!s.isReady()){const r=s.health();return{status:503,body:{error:{message:r.state==="error"?`detector failed to load: ${r.error||"unknown error"}`:`detector is ${r.state} — not ready yet`,type:r.state==="error"?"detector_error":"detector_unready"},state:r.state,model:r.model}}}const d=R(s.stats(),t.text.length,t.budgetMs);if(d)return{status:503,body:{...d,model:s.health().model}};const u=performance.now();let l=await s.detectSpans(t.text);if(t.labels){const r=new Set(t.labels);l=l.filter(m=>r.has(m.type))}const a=s.health();return{status:200,body:{entities:l,model:a.model,ms:Math.round(performance.now()-u),runtime:{name:a.runtime||null,dtype:a.dtype||null}}}}export{Y as capabilitiesDocument,j as handleDetect};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{EventError as b}from"@chatpanel/events/event.js";const d=e=>!!e&&typeof e=="object"&&!Array.isArray(e),l=e=>typeof e=="number"&&Number.isFinite(e),a=e=>{throw new b("SHAPE",e)},y=e=>Math.min(1,Math.max(0,e));function x(e){const t={};for(const[o,n]of Object.entries(e.questions)){const r={type:n.type,instructions:n.instructions};n.type==="choice"?r.criteria=Object.fromEntries(n.options.map(s=>[s.value,s.describe||s.value])):n.type==="score"&&(r.criteria=n.options.map(s=>s.describe?`${s.value}: ${s.describe}`:s.value)),t[o]=r}return{state:e.state,...e.model?{model:e.model}:{},questions:t}}function k(e,t){d(e)&&d(e.answers)||a("systemone: answers {} missing");const o={};for(const[n,r]of Object.entries(t.questions)){const s=e.answers[n];d(s)||a(`systemone: no answer for ${n}`);const p=d(s.probabilities)?s.probabilities:{},f=l(s.confidence)?y(s.confidence):void 0;if(r.type==="choice"){const i=typeof s.choice=="string"?s.choice:a(`systemone: ${n}.choice missing`),m=r.options.map(c=>({value:c.value,p:y(l(p[c.value])?p[c.value]:0)}));o[n]={value:i,p:m.find(c=>c.value===i)?.p??0,options:m,...f!=null?{confidence:f}:{}}}else if(r.type==="score"){l(s.score)||a(`systemone: ${n}.score missing`);const i=r.options.map((c,u)=>({value:c.value,p:y(l(p[String(u)])?p[String(u)]:0)})),m=i.reduce((c,u)=>u.p>c.p?u:c,i[0]);o[n]={value:s.score,p:m.p,options:i,...f!=null?{confidence:f}:{}}}else{l(s.noul)||a(`systemone: ${n}.noul missing`);const i=y(s.noul);o[n]={value:i>=.5,p:i>=.5?i:1-i,options:[{value:!0,p:i},{value:!1,p:1-i}]}}}return{answers:o,...typeof e.model=="string"&&e.model?{model:e.model}:{}}}function O(e){return{query:e.query,texts:e.documents,raw_scores:!1,return_text:!1}}function _(e,t){Array.isArray(e)||a("tei: an array of { index, score } expected");const o=e.map(n=>d(n)&&Number.isInteger(n.index)&&l(n.score)?{index:n.index,relevance_score:n.score}:a("tei: a result needs index and score")).sort((n,r)=>r.relevance_score-n.relevance_score);return{results:t.top_n!=null?o.slice(0,t.top_n):o}}function j(e,t){d(e)&&Array.isArray(e.results)||a("rerank: results[] missing");const o=e.results.map(n=>d(n)&&Number.isInteger(n.index)&&l(n.relevance_score)?{index:n.index,relevance_score:n.relevance_score}:a("rerank: a result needs index and relevance_score")).sort((n,r)=>r.relevance_score-n.relevance_score);return{results:t.top_n!=null?o.slice(0,t.top_n):o,...typeof e.model=="string"&&e.model?{model:e.model}:{}}}function S(e){return d(e)&&d(e.answers)||a("decide: answers {} missing"),{answers:e.answers,...typeof e.model=="string"&&e.model?{model:e.model}:{},...typeof e.calibrated=="boolean"?{calibrated:e.calibrated}:{}}}const v=Object.freeze({systemone:Object.freeze({id:"systemone",capability:"decide",route:"/v1/systemone",label:"TypeSafe System One (Jev · OpenDecision · Laya)",request:x,response:k}),tei:Object.freeze({id:"tei",capability:"rerank",route:"/rerank",label:"Text Embeddings Inference",request:O,response:_}),"rerank-standard":Object.freeze({id:"rerank-standard",capability:"rerank",route:"/v1/rerank",label:"Cohere / Jina rerank",request:e=>({...e,budgetMs:void 0}),response:j}),"decide-standard":Object.freeze({id:"decide-standard",capability:"decide",route:"/v1/decide",label:"ChatPanel decide",request:e=>({...e,budgetMs:void 0}),response:S})});function g(e){const t=v[e];if(!t)throw new b("SHAPE",`capability adapter ${JSON.stringify(e)} unknown (${Object.keys(v).join(", ")})`);return t}function A(e,t){const o=g(e),n=o.request(t);for(const r of Object.keys(n))n[r]===void 0&&delete n[r];return{route:o.route,body:n}}function $(e,t,o){return g(e).response(t,o)}export{v as ADAPTERS,A as adaptRequest,$ as adaptResponse,g as adapterFor};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const f=Object.freeze(["detect","decide","rerank","embed","stt","tts","search","read","extract"]),c=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"}),m=Object.freeze(new Set(["search","read","extract"])),p=Object.freeze(["day","week","month","year"]),o=Object.freeze(["login","paywall","rate_limited","robots","tdm"]),u=Object.freeze(["markdown","text"]),b="/v1/capabilities",g="over_budget",a=e=>!!e&&typeof e=="object"&&!Array.isArray(e),i=e=>typeof e=="string"&&e.length>0,n=e=>typeof e=="number"&&Number.isFinite(e),r=(e,s)=>{if(!e)throw new EventError("SHAPE",s)};function h(e,s){if(!a(e)||!(e.calls>0))return null;const t=n(e.p50Ms)?e.p50Ms:0,l=n(e.charsPerSec)&&e.charsPerSec>0&&n(s)?s/e.charsPerSec*1e3:0;return Math.round(Math.max(t,l))}function x(e,s,t){if(!n(t)||t<=0)return null;const l=h(e,s);return l===null||l<=t?null:{error:{type:g,message:`predicted ${l} ms is over the ${t} ms budget`,predictedMs:l,budgetMs:t}}}function A(e){r(a(e),"detect: body must be an object"),r(typeof e.text=="string","detect: text (string) required");const s={text:e.text};return e.model!=null&&(r(i(e.model),"detect: model must be a non-empty string"),s.model=e.model),e.labels!=null&&(r(Array.isArray(e.labels)&&e.labels.every(i),"detect: labels must be string[]"),s.labels=e.labels),e.budgetMs!=null&&(r(n(e.budgetMs)&&e.budgetMs>=0,"detect: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function $(e,s=null){r(a(e),"detect: response must be an object"),r(Array.isArray(e.entities),"detect: entities[] required"),r(i(e.model),"detect: model required"),r(n(e.ms)&&e.ms>=0,"detect: ms required");for(const t of e.entities)r(a(t)&&i(t.value)&&i(t.type),"detect: entity needs value and type"),r(Number.isInteger(t.start)&&Number.isInteger(t.end)&&t.start>=0&&t.end>t.start,`detect: entity ${JSON.stringify(t.value)} needs start < end`),r(n(t.score)&&t.score>=0&&t.score<=1,`detect: entity ${JSON.stringify(t.value)} needs a score in [0,1]`),typeof s=="string"&&r(s.slice(t.start,t.end)===t.value,`detect: entity ${JSON.stringify(t.value)} is not at ${t.start}–${t.end} of the text`);return e}const d=e=>{if(!i(e))return!1;try{const s=new URL(e);return s.protocol==="http:"||s.protocol==="https:"}catch{return!1}};function q(e){r(a(e),"search: body must be an object"),r(i(e.q)&&e.q.trim().length>0,"search: q (non-empty string) required");const s={q:e.q.trim()};return e.limit!=null&&(r(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&&(r(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&&(r(i(e.site)&&!/[\s/]/.test(e.site),"search: site must be a hostname"),s.site=e.site.toLowerCase()),e.freshness!=null&&(r(p.includes(e.freshness),`search: freshness must be one of ${p.join(", ")}`),s.freshness=e.freshness),e.read!=null&&(r(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&&(r(i(e.provider),"search: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(r(n(e.budgetMs)&&e.budgetMs>=0,"search: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function S(e){return r(a(e),"search: response must be an object"),r(Array.isArray(e.results),"search: results[] required"),r(i(e.provider),"search: provider required"),r(n(e.ms)&&e.ms>=0,"search: ms required"),e.results.forEach((s,t)=>{r(a(s)&&s.rank===t+1,`search: result ${t} must carry rank ${t+1}`),r(d(s.url),`search: result ${t+1} needs an absolute http(s) url`),r(i(s.title),`search: result ${t+1} needs a title`),r(typeof s.snippet=="string",`search: result ${t+1} needs a snippet (may be empty)`),s.read!=null&&v(s.read)}),e}function R(e){r(a(e),"read: body must be an object"),r(d(e.url),"read: url (absolute http(s)) required");const s={url:e.url,format:"markdown"};return e.format!=null&&(r(u.includes(e.format),`read: format must be one of ${u.join(", ")}`),s.format=e.format),e.maxChars!=null&&(r(Number.isInteger(e.maxChars)&&e.maxChars>=200,"read: maxChars must be an integer ≥ 200"),s.maxChars=e.maxChars),e.snippet!=null&&(r(typeof e.snippet=="string","read: snippet must be a string"),s.snippet=e.snippet),e.provider!=null&&(r(i(e.provider),"read: provider must be a non-empty string"),s.provider=e.provider),e.budgetMs!=null&&(r(n(e.budgetMs)&&e.budgetMs>=0,"read: budgetMs must be a number ≥ 0"),s.budgetMs=e.budgetMs),s}function v(e){r(a(e),"read: response must be an object"),r(d(e.url),"read: url (absolute, where the page landed) required"),r(typeof e.title=="string","read: title (string, may be empty) required"),r(u.includes(e.format),"read: format required");const s=e[e.format];r(typeof s=="string",`read: ${e.format} (string) required`),r(Number.isInteger(e.chars)&&e.chars===s.length,"read: chars must equal the content length"),r(typeof e.truncated=="boolean","read: truncated (boolean) required"),r(i(e.provider),"read: provider required"),r(n(e.ms)&&e.ms>=0,"read: ms required"),r(Array.isArray(e.sections),"read: sections[] required");for(const t of e.sections)r(a(t)&&i(t.id)&&i(t.heading),"read: section needs id and heading"),r(Number.isInteger(t.level)&&t.level>=1&&t.level<=6,`read: section ${t.id} needs level 1–6`),r(Number.isInteger(t.offset)&&t.offset>=0&&t.offset<=s.length,`read: section ${t.id} offset must index the content`);return e.restricted!=null&&r(a(e.restricted)&&o.includes(e.restricted.reason),`read: restricted.reason must be one of ${o.join(", ")}`),e}function M(e){r(a(e),"capabilities: response must be an object"),r(Array.isArray(e.capabilities),"capabilities: capabilities[] required"),r(a(e.server)&&i(e.server.name)&&i(e.server.version),"capabilities: server {name, version} required");const s=new Set;for(const t of e.capabilities)r(a(t)&&f.includes(t.id),`capabilities: unknown capability id ${JSON.stringify(t?.id)}`),r(!s.has(t.id),`capabilities: ${t.id} listed twice`),s.add(t.id),r(t.route===c[t.id],`capabilities: ${t.id} must be served at ${c[t.id]}`),m.has(t.id)?(r(Array.isArray(t.providers)&&t.providers.length>0&&t.providers.every(i),`capabilities: ${t.id}.providers must be a non-empty string[]`),t.default!=null&&r(t.providers.includes(t.default),`capabilities: ${t.id}.default must be one of its providers`)):(r(Array.isArray(t.models)&&t.models.every(i),`capabilities: ${t.id}.models must be string[]`),t.default!=null&&r(t.models.includes(t.default),`capabilities: ${t.id}.default must be one of its models`)),t.labels!=null&&r(Array.isArray(t.labels)&&t.labels.every(i),`capabilities: ${t.id}.labels must be string[]`),t.stats!=null&&r(a(t.stats)&&(m.has(t.id)||n(t.stats.calls)),`capabilities: ${t.id}.stats needs calls`),t.runtime!=null&&r(a(t.runtime)&&i(t.runtime.state),`capabilities: ${t.id}.runtime needs state`);return e}function I(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{f as CAPABILITIES,c as CAPABILITY_ROUTES,b as DISCOVERY_ROUTE,g as OVER_BUDGET,m as PROVIDER_CAPABILITIES,u as READ_FORMATS,o as READ_RESTRICTIONS,p as SEARCH_FRESHNESS,I as offeredCapabilities,x as overBudget,h as predictMs,M as validateCapabilitiesResponse,A as validateDetectRequest,$ as validateDetectResponse,R as validateReadRequest,v as validateReadResponse,q as validateSearchRequest,S as validateSearchResponse};
|
|
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};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{validateDetectResponse as A,validateDecideResponse as q,validateRerankResponse as k,CAPABILITY_ROUTES as E}from"./capability-endpoints.js";const b=6e4,$=i=>String(i||"").replace(/\/+$/,"");function x(i,{gatewayUrl:y="http://127.0.0.1:4320",discovery:o=null,endpoints:d=[],detection:l=null}={}){const f=E[i];if(!f)return[];const c=[];i==="detect"&&l?.backend==="endpoint"&&l.url&&!l.bundled&&c.push({id:l.serverId||"custom",name:l.serverId?"your detector server":"your custom detector",url:l.url,apiKey:l.apiKey||"",where:"your detector server"});const e=$(y)||"http://127.0.0.1:4320",r=(o?.capabilities||[]).find(t=>t.id===i),a=!!r&&(!r.runtime||["ready","external","idle"].includes(r.runtime.state));(i==="detect"||a)&&c.push({id:"gateway",name:"the gateway",url:`${e}${f}`,where:r?.runtime?.name==="container"||r?.requirements?.egress==="none"||!r?"this device":"your server",...r?.default||r?.models?.[0]?{model:r.default||r.models[0]}:{},...typeof r?.calibrated=="boolean"?{calibrated:r.calibrated}:{}});for(const t of d||[]){if(!t||t.enabled===!1||!t.baseUrl||!Array.isArray(t.provides)||!t.provides.includes(i))continue;const n=t.providesInfo?.[i];c.push({id:t.id,name:t.name||t.baseUrl,url:`${$(t.baseUrl)}${f}`,apiKey:t.apiKey||"",where:t.name||"a server",...n?.models?.[0]?{model:n.models[0]}:{},...typeof n?.calibrated=="boolean"?{calibrated:n.calibrated}:{}})}return c}function T(i){return y=>{const o=i[y.kind];return!Array.isArray(o)||!o.length?null:{provider:o[0].id,providers:o,reason:`${o.length} ${y.kind} provider${o.length===1?"":"s"} at hand`}}}const R={detect:A,decide:q,rerank:k};async function I(i,y,o,{fetch:d,timeoutMs:l=8e3,validateAgainst:f=null}={}){if(typeof d!="function")throw new Error("capability: fetch is required");const c=await d(i.url,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",...i.apiKey?{authorization:`Bearer ${i.apiKey}`}:{}},body:JSON.stringify(o),signal:AbortSignal.timeout(l)});let e=null;try{e=await c.json()}catch{e=null}if(!c.ok)throw new Error(`${i.id}: ${c.status}${e?.error?.type?` ${e.error.type}`:""}${e?.error?.message?` — ${e.error.message}`:""}`);return R[y](e,f)}async function K(i,y,o,{fetch:d,onTry:l=()=>{},...f}={}){let c="no provider";for(const e of i||[])try{return l(e),{doc:await I(e,y,o,{fetch:d,...f}),provider:e}}catch(r){const a=r?.message||String(r);c=a.startsWith(`${e.id}:`)?a:`${e.id}: ${a}`}throw new Error(c)}function O({fetch:i,normalizeEntities:y=d=>d.entities||[],budgetMs:o=5e3}={}){const d=async(e,r,a,t,n,u={})=>{const{doc:m,provider:p}=await K(e.assigned?.providers,a,t,{fetch:i,onTry:g=>r.partial?.({trying:g.id}),...u});return n(m,p)};async function l(e,r,a){const t=String(r.primary||"").slice(0,b);return d(e,a,"detect",{text:t,budgetMs:o},(n,u)=>{const m=y(n,{person:!0,org:!0,location:!0,number:!0}),p=[...new Set((n.entities||[]).map(g=>g.model).filter(Boolean))];return!p.length&&n.model&&p.push(n.model),{entities:m,models:p,provider:u.id,where:u.where}},{validateAgainst:t})}async function f(e,r,a){const t=String(r.primary||"").slice(0,b),n=e.questions||e.question||a.questions;if(!n||!Object.keys(n).length)throw new Error("decide: no questions on the step");return d(e,a,"decide",{state:t,questions:n,budgetMs:o},(m,p)=>({answers:m.answers,models:[m.model],calibrated:m.calibrated===!0,provider:p.id,where:p.where,ms:m.ms}),{timeoutMs:2e4})}async function c(e,r,a){const t=String(e.query||a.goal||"").trim(),n=r.primary;let u,m=s=>String(s),p;if(Array.isArray(n))u=n,m=s=>typeof s=="string"?s:String(s?.text??s?.snippet??s?.title??""),p=s=>s;else if(typeof n=="string"){const s=n.split(`
|
|
2
|
+
`);u=s.filter(h=>/^\s*[-*•]\s+/.test(h));const v=s.filter(h=>!/^\s*[-*•]\s+/.test(h));p=h=>[...h,...v].join(`
|
|
3
|
+
`)}else return n;if(!t||u.length<2)return n;const g=u.map(s=>m(s).replace(/\s+/g," ").trim().slice(0,2e3));return d(e,a,"rerank",{query:t,documents:g,budgetMs:o},s=>{const v=new Set(s.results.map(w=>w.index)),h=[...s.results.map(w=>u[w.index]),...u.filter((w,S)=>!v.has(S))];return p(h)},{validateAgainst:{documents:g}})}return{detect:l,decide:f,rerank:c}}export{I as callCapability,K as callFirstProvider,x as capabilityProviders,O as capabilityRunners,T as capabilitySource};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{secureFetch as k}from"./secure-fetch.js";import{createReadStats as O}from"./retrieval/read.js";import{CAPABILITY_ROUTES as A,overBudget as M,validateRerankRequest as T,validateRerankResponse as L,validateDecideRequest as j,validateDecideResponse as D}from"./capability-endpoints.js";import{adaptRequest as I,adaptResponse as P}from"./capability-adapters.js";const g=Object.freeze(["rerank","decide"]),w={rerank:{request:T,response:L,chars:c=>c.query.length+c.documents.reduce((u,l)=>u+l.length,0)},decide:{request:j,response:D,chars:c=>c.state.length}},x=18e4,C=6e4,d=(c,u,l,p={})=>({status:c,body:{error:{type:u,message:l,...p}}});function J({cfg:c,fetchImpl:u=k,now:l=()=>Date.now()}={}){const p=Object.fromEntries(g.map(e=>[e,{stats:O(),last:null,error:null}])),v=e=>{const r=c.capabilities?.[e];return r&&typeof r.url=="string"&&/^https?:\/\//.test(r.url)&&typeof r.adapter=="string"?r:null};async function _(e,r){if(!g.includes(e))return d(404,"unknown_capability",`no such capability ${e}`);const t=v(e);if(!t)return d(404,"no_provider",`no ${e} provider — run one under Settings › Runtime, or point capabilities.${e}.url at a server that provides it`);const i=w[e];let a;try{a=i.request(r)}catch(s){return d(400,"invalid_request",s.message)}if(a.model&&t.model&&a.model!==t.model)return d(404,"model_not_found",`${e}: model ${a.model} is not served here (${t.model} is)`);const o=p[e],y=i.chars(a),b=M(o.stats.stats(),y,a.budgetMs);if(b)return{status:503,body:b};let h;try{h=I(t.adapter,{...a,model:a.model||t.model||void 0})}catch(s){return d(500,"bad_adapter",s.message)}const S=`${t.url.replace(/\/+$/,"")}${h.route}`,q=l();let m;try{m=await u(S,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",...t.token?{authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify(h.body),signal:AbortSignal.timeout(a.budgetMs?Math.max(a.budgetMs*2,5e3):o.stats.stats().calls?C:x)})}catch(s){return o.error=s.message,o.last=l(),d(503,"provider_unavailable",`${e}: ${t.service?`the ${t.service} container`:t.url} did not answer — ${s.message}`)}let n;try{n=await m.json()}catch{n=null}if(!m.ok)return o.error=`HTTP ${m.status}`,o.last=l(),d(502,"provider_error",`${e}: the provider answered ${m.status}${n?.detail?` — ${typeof n.detail=="string"?n.detail:JSON.stringify(n.detail)}`:n?.error?` — ${typeof n.error=="string"?n.error:n.error.message||""}`:""}`);const $=l()-q;let f;try{const s=P(t.adapter,n,a);f={...s,model:t.model||s.model||t.adapter,...s.model&&t.model&&s.model!==t.model?{providerModel:s.model}:{},ms:$,...e==="decide"?{calibrated:t.calibrated===!0}:{}},i.response(f,a)}catch(s){return o.error=s.message,o.last=l(),d(502,"bad_shape",`${e}: the provider's answer did not fit the contract — ${s.message}`)}return o.stats.record($,y),o.error=null,o.last=l(),{status:200,body:f}}function R(e){const r=v(e);if(!r)return null;const t=p[e],i=t.stats.stats();return{id:e,route:A[e],models:r.model?[r.model]:[],...r.model?{default:r.model}:{},requirements:{egress:/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:|\/|$)/.test(r.url)?"none":"trusted"},...e==="decide"?{calibrated:r.calibrated===!0}:{},stats:i,runtime:{state:t.error?"down":i.calls?"ready":"idle",name:r.service?"container":"external",adapter:r.adapter,...r.service?{service:r.service}:{},url:r.url,...t.error?{error:t.error}:{}}}}return{call:_,entry:R,stats:e=>p[e]?.stats.stats()||{calls:0},capabilities:g}}export{J as createCapabilityProxy};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{callFirstProvider as h}from"./capability-providers.js";import{DECIDE_QUESTION_TYPES as k,validateDecideRequest as A,validateRerankRequest as x}from"./capability-endpoints.js";const m="decide",g="rerank",v=6e4,E=200,O=2e3,f=160,q="A small DECISION MODEL and/or a RERANKER run on this device. For a sentiment, tone, urgency, spam/complaint, yes/no or pick-one judgement over text you already hold, call `decide` instead of judging it yourself — it answers in milliseconds with a probability per option. To order many candidates (search hits, comments, sections, options) by relevance to a question, call `rerank` instead of reading them all. Report its answer as the model's, with the probability, and say when it is marked uncalibrated.",_=Object.freeze({name:m,annotations:{readOnlyHint:!0,idempotentHint:!0},description:"Ask a small local decision model one or more typed questions about a text: a choice among options (sentiment, category, urgency), a score on an ordered rubric, or a yes/no. Returns the answer per question with its probability and the runner-up. Use it for any classification of text you already have — the whole thread, a comment, an email — rather than judging it yourself. Not a language model: it cannot explain, only decide.",parameters:{type:"object",properties:{text:{type:"string",description:"The text to judge, as-is. Up to ~60k characters."},questions:{type:"array",minItems:1,description:"One or more questions, each answered independently over the same text.",items:{type:"object",properties:{key:{type:"string",description:'A short identifier for the answer (e.g. "sentiment"). Optional.'},type:{type:"string",enum:[...k],description:'"choice" picks one option; "score" places the text on options read as an ordered rubric (worst first); "noul" is yes/no and takes no options.'},instructions:{type:"string",description:'What to decide, in one sentence — e.g. "The overall sentiment of the comments toward the company."'},options:{type:"array",items:{type:"string"},description:"For choice and score: 2–255 distinct options. Omit for noul."}},required:["type","instructions"],additionalProperties:!1}}},required:["text","questions"],additionalProperties:!1}}),S=Object.freeze({name:g,annotations:{readOnlyHint:!0,idempotentHint:!0},description:"Order candidate texts by relevance to a query with a local reranker (a cross-encoder). Give it the query and the candidates — search results, comments, paragraphs, options — and it returns them best first with a relevance score each. Use it to pick what to read or cite from many candidates instead of reading them all.",parameters:{type:"object",properties:{query:{type:"string",description:"What relevance is measured against — the question or the need."},documents:{type:"array",items:{type:"string"},minItems:2,description:"The candidates, 2–200 strings. Each is read up to ~2000 characters."},top_n:{type:"integer",minimum:1,description:"Return only the best N. Default: all, ordered."}},required:["query","documents"],additionalProperties:!1}}),N=/^[A-Za-z_][A-Za-z0-9_]*$/;function R(e){const o={};return(Array.isArray(e)?e:[]).forEach((t,s)=>{if(!t||typeof t!="object")return;let n=String(t.key||"").trim();(!N.test(n)||o[n])&&(n=`q${s+1}`);const r={type:String(t.type||""),instructions:String(t.instructions||"")};r.type!=="noul"&&Array.isArray(t.options)&&(r.options=t.options.map(p=>String(p))),o[n]=r}),o}const b=e=>`${Math.round(Number(e)*100)}%`,y=e=>String(e).replace(/\s+/g," ").trim();function w(e,o,t){const s=o.where?` on ${o.where}`:"",n=Number.isFinite(e.ms)?` in ${Math.round(e.ms)} ms`:"";return`Answered by ${e.model||o.id}${s}${n} — ${t}, not a language model.`}function T(e,o,t){const s=[];for(const[n,r]of Object.entries(e.answers||{})){const p=t[n],i=typeof r.value=="boolean"?r.value?"yes":"no":String(r.value),a=(r.options||[]).filter(d=>d.value!==r.value).sort((d,l)=>l.p-d.p),u=a.length?`; then ${typeof a[0].value=="boolean"?a[0].value?"yes":"no":a[0].value} ${b(a[0].p)}`:"";s.push(`${n}${p?.instructions?` (${y(p.instructions)})`:""}: ${i} — ${b(r.p)}${u}`)}return s.push("",w(e,o,"a decision model")),e.calibrated===!1&&s.push("Uncalibrated: the probabilities rank the options but are not confidence — say so if you quote them."),s.join(`
|
|
2
|
+
`)}function j(e,o,t,{query:s="",topN:n=null}={}){const r=e.results.map((i,a)=>`${a+1}. [doc ${i.index+1}] score ${Number(i.relevance_score).toFixed(3)} — ${y(t[i.index]).slice(0,f)}${t[i.index].length>f?"…":""}`);return[`${e.results.length} of ${t.length} candidate(s) for "${y(s).slice(0,120)}", best first${n?` (top ${n})`:""}. [doc N] is the 1-based position in the list you sent.`,...r,"",w(e,o,"a reranker")].join(`
|
|
3
|
+
`)}function I({providers:e={},fetch:o,budgetMs:t=8e3}={}){if(typeof o!="function")throw new Error("capabilityToolsProvider: fetch required");const s=Array.isArray(e.decide)?e.decide:[],n=Array.isArray(e.rerank)?e.rerank:[];if(!s.length&&!n.length)return null;const r=[];return s.length&&r.push(_),n.length&&r.push(S),{specs:r,system:q,async execute(p,i){if(p===m&&s.length){const a=String(i?.text||"").trim().slice(0,v),u=R(i?.questions);if(!a)return"decide needs `text` — the passage to judge.";if(!Object.keys(u).length)return"decide needs at least one question: { type, instructions, options? }.";let d;try{d=A({state:a,questions:u,budgetMs:t})}catch(l){return`decide could not take the questions (${l.message}). Fix them and call again: a choice or score needs 2–255 distinct options, a noul none.`}try{const{doc:l,provider:c}=await h(s,"decide",d,{fetch:o,timeoutMs:2e4,validateAgainst:d});return T(l,c,d.questions)}catch(l){return`No decision model answered (${l?.message||l}). Judge the text yourself now and say the answer is your own reading, not a model's probability.`}}if(p===g&&n.length){const a=String(i?.query||"").trim(),u=(Array.isArray(i?.documents)?i.documents:[]).map(c=>String(c??"")).filter(c=>c.trim()).slice(0,E);if(!a)return"rerank needs `query` — what relevance is measured against.";if(u.length<2)return u.length===1?"One candidate needs no ordering — it is the answer.":"rerank needs `documents` — two or more candidates.";const d=Number.isInteger(i?.top_n)&&i.top_n>=1?Math.min(i.top_n,u.length):null;let l;try{l=x({query:a,documents:u.map(c=>y(c).slice(0,O)),budgetMs:t,...d?{top_n:d}:{}})}catch(c){return`rerank could not take the candidates (${c.message}).`}try{const{doc:c,provider:$}=await h(n,"rerank",l,{fetch:o,validateAgainst:l});return j(c,$,u,{query:a,topN:d})}catch(c){return`No reranker answered (${c?.message||c}). Order the candidates yourself by reading them, and say the ordering is your own.`}}return JSON.stringify({error:`Unknown tool: ${p}`})}}}export{q as CAPABILITY_TOOLS_SYSTEM,m as DECIDE_TOOL_NAME,g as RERANK_TOOL_NAME,I as capabilityToolsProvider,R as questionsToWire,T as renderDecideResult,j as renderRerankResult};
|
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 A}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:[],caseRecovery:!0,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:A,allowDownload:!0,diarize:!0,warmMs:15*6e4},read:{provider:"defuddle",remote:{url:"",key:""}},search:{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},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};
|
|
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 A}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:A,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:{}},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
|
|
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};
|
package/src/egress.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isBlockedHost as f}from"@chatpanel/pii";const b=()=>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
|
|
2
|
-
`)}export{
|
|
1
|
+
import{isBlockedHost as f}from"@chatpanel/pii";const b=()=>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=b}={}){const t=new Map;return{record(r){const o=g(r);if(!o||!o.host)return;const i=`${o.scheme}://${o.host}:${o.port}`,c=e(),a=t.get(i);if(a){a.count+=1,a.lastAt=c;return}t.set(i,{host:o.host,port:o.port,scheme:o.scheme,local:u(o.host),count:1,firstAt:c,lastAt:c})},snapshot(){return[...t.values()].sort((r,o)=>r.local===o.local?o.count-r.count:r.local?1:-1)},reset(){t.clear()}}}let w=null;function L(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const r=v();let o=t;r.setGate=c=>{o=c},r.blocked=[];const i=e.fetch;return typeof i=="function"&&(e.fetch=function(a,p){let s=null;try{s=g(a),r.record(a)}catch{}if(o&&s?.host){let l=!0;try{l=o(`${s.scheme}://${s.host}:${s.port}`,{local:u(s.host)})}catch{l=!0}if(!l){const n=`${s.host}:${s.port}`;r.blocked.includes(n)||r.blocked.push(n);const h=new Error(`egress to ${s.host} is blocked by your organisation’s policy`);return h.code="EGRESS_POLICY",Promise.reject(h)}}return i.call(this,a,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=[],o=(s,l,{when:n="always",off:h=null,local:m=!1,data:y=""}={})=>{s&&r.push({host:s,purpose:l,when:n,off:h,local:m,data:y})};o("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),o("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),o("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),o("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const i=e.search?.searxng?.url||"";if(i){let s=i;try{s=new URL(i).host}catch{}o(s,"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(s)})}if(e.search?.provider!=="searxng"&&(o("www.startpage.com","web search: the built-in results-page search, first engine",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),o("html.duckduckgo.com","web search: the built-in results-page search, fallback engine",{when:"Startpage returned nothing",off:"the same switch as www.startpage.com",data:"the same query"})),e.read?.remote?.url){let s=e.read.remote.url;try{s=new URL(e.read.remote.url).host}catch{}o(s,"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(s)})}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"}};for(const[s,l]of Object.entries(c)){const n=e.capabilities?.[s];if(!n?.url)continue;let h=n.url;try{h=new URL(n.url).host}catch{}o(h,`${l.what}${n.service?` (the ${n.service} container, started under Settings › Runtime)`:` (${n.adapter} at the address you configured)`}`,{when:`a client calls /v1/${s}`,off:n.service?`stop the ${n.service} service under Settings › Runtime`:`capabilities.${s} = null`,data:`${l.data}${n.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(h)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(o("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),o("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[s,l]of Object.entries(e.upstreams||{}))l?.baseUrl&&o(d(l.baseUrl),`model upstream "${s}" — chat requests (after redaction) go here`,{when:`a request addressed to ${s}`,off:`upstreams.${s}.baseUrl`,local:u(d(l.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const s of e.destinations||[])s?.baseUrl&&o(d(s.baseUrl),`destination "${s.id||s.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${s.id||"it"}`,off:"destinations[]",local:u(d(s.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});o("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&o(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 a=e.tts||{};if(a.provider==="openai"||a.provider==="elevenlabs"){const s=a.remote?.baseUrl?d(a.remote.baseUrl):a.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(s,`remote read-aloud voice (${a.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:a.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 o(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 S(e,{ledger:t=$(),version:r="",startedAt:o=null,env:i=process.env,managed:c=null}={}){return{ok:!0,version:r,since:o?new Date(o).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,i)}}function x(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const r of e.observed||[])t.push(` ${r.local?"[local] ":""}${r.scheme}://${r.host}:${r.port} ×${r.count} last ${r.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const r of e.declared||[])t.push(` ${r.local?"[local] ":""}${r.host}`),t.push(` ${r.purpose}`),t.push(` when: ${r.when}${r.off?` · off: ${r.off}`:""}`),r.data&&t.push(` sends: ${r.data}`);return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,r])=>r).map(([r,o])=>o===!0?r:`${r}=${o}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
|
|
2
|
+
`)}export{v as createEgressLedger,k as declaredEgress,S as egressAudit,$ as egressLedger,x as formatAudit,L as installEgressLedger};
|
package/src/mcp.js
CHANGED
|
@@ -1,34 +1,34 @@
|
|
|
1
|
-
import{loadConfig as
|
|
2
|
-
`);let d="unknown";function k(i){try{const e=b();fetch(`${m()}/v1/observability/access`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(i)}).catch(()=>{})}catch{}}function m(){const i=process.env.CHATPANEL_GATEWAY_URL;if(i)return i.replace(/\/+$/,"");let e=4320;try{e=p().port||4320}catch{}return`http://127.0.0.1:${e}`}function S(){try{return String(p().bridge?.url||"http://127.0.0.1:4319").replace(/\/+$/,"")}catch{return"http://127.0.0.1:4319"}}function T(){try{return w(p().bridge?.token||"")}catch{return w("")}}async function f(i){const e=T(),t=await fetch(S()+i,{headers:{Accept:"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}),n=await t.json().catch(()=>({}));if(!t.ok||n.ok===!1)throw new Error(n?.error||`bridge ${t.status}`);return n}const q=[{name:"smart_search",description:'BEST first choice for a question about the user\'s ChatPanel history (meetings, notes, past chats). Ask it a natural-language QUESTION and it expands that into several complementary keyword queries, runs them all, and fuses the rankings — which finds things a single query misses, in one round trip instead of several probes. You know the domain, so pass 2-4 of your own phrasings in `queries` too (e.g. for "what did we decide in the Ben demo": ["Ben demo decisions", "tooling demo action items", "demo outcome next steps"]). Supports the same filters as search_history (type, since, before) and returns snippets with each result\'s id; follow up with get_record for the full text or find_related to expand around a hit. BRIEFS come first when they match: a brief is a maintained page about one person, project or topic, derived from ALL the records that mention it, with every claim citing its record — so for "what do we know about X" read the brief, then open only the records it cites.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in natural language."},queries:{type:"array",items:{type:"string"},description:"Your own 2-4 keyword formulations of it — these lead the search."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a window like "7d"/"yesterday".'},before:{type:"string",description:"Latest date: a date or window like `since`."},limit:{type:"number",description:"Max fused results (default 10)."}},required:["question"]}},{name:"search_history",description:'Search the user\'s ChatPanel history — their past chats, meeting/call transcripts, and notes — by keyword relevance. Consult this (in ADDITION to your other tools) whenever the question touches a meeting, call, demo, note, or past conversation: "outcome of the meeting", "what did we decide", "action items", "what did <person> say", "notes from yesterday". Filters: `type` (chat|meeting|note), `since`/`before` (a date like 2026-08-01 or a relative window like "7d"/"yesterday"), and `limit`/`offset` for paging. Returns compact SNIPPETS (the matching excerpt) with each record\'s id/title/type/date — token-friendly; call get_record for the full text and find_related to follow connections. This is a LOCAL WARM COPY that syncs from ChatPanel; very recent items may not be here yet — results report how current the index is, so if something is missing it likely has not synced. Meeting titles are often generic ("Zoom Meeting"), so search by CONTENT, not the title.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Content keywords (topics, names, decisions) — not the meeting title."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a relative window like "7d", "2 weeks", "yesterday".'},before:{type:"string",description:"Latest date: a date or relative window like `since`."},limit:{type:"number",description:"Max results (default 10)."},offset:{type:"number",description:"Skip N results for paging (default 0)."}},required:["query"]}},{name:"get_record",description:"Fetch one history record's full text by id (chat:<id>, meeting:<id>, note:<id> from search_history). For a long transcript, page it with maxChars + offset instead of pulling it all into context — the result says how many chars remain.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Record id such as chat:abc, meeting:imp_123, or note:xyz."},maxChars:{type:"number",description:"Return at most this many characters (token management for long transcripts)."},offset:{type:"number",description:"Start at this character offset — page through with the offset the previous call reports."}},required:["id"]}},{name:"find_related",description:"Graph navigation: given a record id (from search_history), return the records most connected to it by shared content — the meetings/notes/chats about the same topic, people or thread. Use it to expand from one hit to the surrounding context instead of re-searching.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The record id to find neighbours of."},limit:{type:"number",description:"Max related records (default 5)."}},required:["id"]}},{name:"list_history",description:"List history records (newest first) with their id, title, type and date — no bodies. Reports how current this warm copy is (its newest record). Use to see the index horizon and browse/page the corpus.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max items (default 50)."},offset:{type:"number",description:"Skip N items for paging (default 0)."}}}},{name:"list_briefs",description:`The BRIEFS ChatPanel maintains — one page per person, project or topic that appears across enough records, each claim citing the record it came from. This is the index of what the user's corpus KNOWS, as opposed to what it merely contains: read it before asking "what do we know about X", then get_brief for the one you need. Briefs are rebuilt from the records, so they are as current as the last rebuild (dates shown).`,inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max briefs (default 50)."},offset:{type:"number",description:"Skip N for paging (default 0)."}}}},{name:"get_brief",description:"One brief as STRUCTURE: the subject, its other spellings, and each claim with the record ids it cites — so you can cite the record rather than the synthesis, and open only what you need with get_record. Prefer this over get_record for a brief:… id; get_record returns the same text as prose.",inputSchema:{type:"object",properties:{id:{type:"string",description:"A brief id (brief:…) from list_briefs or search results."}},required:["id"]}},{name:"recall",description:"What ChatPanel already knows about the USER — their name, how they want answers written, their ongoing work and environment. Short and cheap; call it at the START of a session and whenever the user states a preference, then just FOLLOW what it returns without announcing that you checked. Pass the current task in `text` and it also returns the facts relevant to that task, not only the always-on ones. This is memory, not history: for what was said in a meeting or a past chat use smart_search instead.",inputSchema:{type:"object",properties:{text:{type:"string",description:"What the user is asking about right now, so task-relevant facts come back too. Omit for just the always-on ones."}}}},{name:"remember",description:`Save a durable fact about the USER to ChatPanel, carried into every future session on every model and agent — the side panel, other CLIs, everything. Use it the moment they state a standing preference ("always use pnpm"), an identity fact ("call me Alex") or a constraint that will still be true next week. Do NOT use it for task details, anything obvious from the current work, or notes about a codebase — those belong in the repo. One short self-contained sentence, written in the third person. Saving is a change to the user's own data, so say in a short clause what you saved.`,inputSchema:{type:"object",properties:{text:{type:"string",description:'The fact, one short sentence in the third person ("Prefers pnpm over npm"). Max 280 characters.'},kind:{type:"string",enum:$,description:$.map(i=>`${i}: ${_[i].hint}`).join(" ")},tags:{type:"array",items:{type:"string"},description:"Optional short tags for grouping."}},required:["text"]}},{name:"forget",description:'Remove a memory from ChatPanel when the user says it no longer holds. Name it however they did ("the Frankfurt thing") or pass the id from recall — it matches on meaning, and tells you exactly what it removed.',inputSchema:{type:"object",properties:{query:{type:"string",description:"The memory to remove: its text, roughly how the user named it, or its id."}},required:["query"]}},{name:"list_skills",description:"List the reusable skills installed on this machine (via the ChatPanel bridge) — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes) and any configured folder. Returns each skill's name and one-line description. Call open_skill to load the one that fits the task.",inputSchema:{type:"object",properties:{}}},{name:"open_skill",description:"Load one skill's full instructions by name (from list_skills), then follow them. If the instructions point at reference files, read one with read_skill_file.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name from list_skills."}},required:["name"]}},{name:"read_skill_file",description:"Read one reference file a skill's instructions point at (any path inside the skill's own folder). Use only when the task needs it.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name."},path:{type:"string",description:"The reference path as written in the instructions, e.g. references/auth.md."}},required:["name","path"]}}];function y(i,e){if(!i)return`Index: ${e} records (warm copy synced from ChatPanel).`;const t=new Date(i),n=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`;return`Index: ${e} records, current through ${n} (local warm copy — items newer than this may not have synced from ChatPanel yet).`}function x(){try{const i=b();return i?{Authorization:`Bearer ${i}`}:{}}catch{return{}}}async function c(i,e){let t;try{t=await fetch(m()+i,e)}catch(r){throw new Error(`the ChatPanel gateway is not running at ${m()} — start it with "chatpanel-gateway --install" (or run "chatpanel-gateway"), then retry. [${r.message}]`)}const n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n?.error?.message||`the gateway returned HTTP ${t.status} for ${i}`);return n}function u(i){if(i==null||i==="")return null;if(typeof i=="number")return i;const e=String(i).trim().toLowerCase(),t=864e5;if(e==="today")return Date.now()-t;if(e==="yesterday")return Date.now()-2*t;const n=/^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(e);if(n){const o=Number(n[1]),s=n[2][0],a=s==="d"?t:s==="w"?7*t:s==="m"?30*t:365*t;return Date.now()-o*a}const r=Date.parse(e);return Number.isNaN(r)?null:r}const g=(i,e)=>`${e+1}. [${i.id}] ${i.title||"(untitled)"} · ${i.type}${i.date?" · "+new Date(i.date).toISOString().slice(0,10):""}${i.snippet?`
|
|
3
|
-
${
|
|
4
|
-
(matched ${
|
|
1
|
+
import{loadConfig as f}from"./config.js";import{readBridgeToken as b}from"./bridge.js";import{ensureGatewayToken as S}from"./gateway-token.js";import{MEMORY_KINDS as N,MEMORY_KIND_NAMES as k}from"./memory.js";import{parseBriefText as T}from"./knowledge.js";import{capabilityToolsProvider as j,DECIDE_TOOL_NAME as R,RERANK_TOOL_NAME as q}from"./capability-tools.js";import{webSearchToolProvider as P}from"./web-search-tool.js";import{SEARCH_DEFAULTS as E}from"./retrieval/search.js";const A="2024-11-05",L={name:"chatpanel-history",version:"1.0.0"},I=["ChatPanel holds the USER'S OWN meetings, notes and past chats — transcripts, decisions,","action items, summaries — which usually are NOT in the working directory.","","Keep using all your normal tools. ADDITIONALLY, whenever the user's question touches a",'meeting, call, demo, note, or past conversation ("outcome of the meeting", "what did we','decide", "action items", "notes from yesterday", a person/day/topic in their history),',"ALSO consult ChatPanel — it is the source of truth for that personal history:"," • smart_search — START HERE: give it the question plus 2-4 of your own keyword"," phrasings; it runs them all and fuses the rankings, finding what one query misses."," • search_history — one exact keyword query, when you already know the terms. Search by"," CONTENT (not the generic meeting title). Supports filters:",' type (chat|meeting|note), since/before (dates or relative like "7d", "yesterday"),'," and limit/offset paging. Returns compact snippets, not full bodies."," • get_record — the full text of one result id; use maxChars/offset to page a long"," transcript instead of pulling it all into context."," • find_related — follow the graph: given a record id, the records most connected to it.","","ChatPanel also holds the user's MEMORY — a short list of durable facts about them (their","name, how they want answers written, what they are working on) that applies to EVERY task,","not just ones about their history:"," • recall — call it EARLY in a session, and whenever the user states a preference, to see"," what is already known. Then simply follow it; do not tell them you looked.",' • remember — save a new durable fact when they state one ("call me Alex", "always use',' pnpm"). One short sentence. Not for task details or anything true only today.'," • forget — remove one when they say it no longer holds.","Prefer these for the user's history and combine them with your other tools as you see fit.","Every result states how fresh the local copy is; if something recent is missing it may not","have synced yet — say so rather than concluding it does not exist.","","ChatPanel also runs SMALL LOCAL MODELS and a private web search on this machine:"," • decide — a sentiment, tone, urgency, spam/complaint, yes/no or pick-one judgement over"," text you already hold, answered with a probability per option in milliseconds. Call it"," instead of judging the text yourself."," • rerank — order many candidates (search hits, comments, sections) by relevance to a"," question, best first with a score, instead of reading them all."," • web_search — the user's own search (their SearXNG when one runs here), results with"," the top pages already read. Nothing leaves this machine but the query."].join(`
|
|
2
|
+
`);let u="unknown";function $(n){try{const e=S();fetch(`${p()}/v1/observability/access`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(n)}).catch(()=>{})}catch{}}function p(){const n=process.env.CHATPANEL_GATEWAY_URL;if(n)return n.replace(/\/+$/,"");let e=4320;try{e=f().port||4320}catch{}return`http://127.0.0.1:${e}`}function v(){try{return String(f().bridge?.url||"http://127.0.0.1:4319").replace(/\/+$/,"")}catch{return"http://127.0.0.1:4319"}}function M(){try{return b(f().bridge?.token||"")}catch{return b("")}}async function y(n){const e=M(),s=await fetch(v()+n,{headers:{Accept:"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}),t=await s.json().catch(()=>({}));if(!s.ok||t.ok===!1)throw new Error(t?.error||`bridge ${s.status}`);return t}const D=[{name:"smart_search",description:'BEST first choice for a question about the user\'s ChatPanel history (meetings, notes, past chats). Ask it a natural-language QUESTION and it expands that into several complementary keyword queries, runs them all, and fuses the rankings — which finds things a single query misses, in one round trip instead of several probes. You know the domain, so pass 2-4 of your own phrasings in `queries` too (e.g. for "what did we decide in the Ben demo": ["Ben demo decisions", "tooling demo action items", "demo outcome next steps"]). Supports the same filters as search_history (type, since, before) and returns snippets with each result\'s id; follow up with get_record for the full text or find_related to expand around a hit. BRIEFS come first when they match: a brief is a maintained page about one person, project or topic, derived from ALL the records that mention it, with every claim citing its record — so for "what do we know about X" read the brief, then open only the records it cites.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in natural language."},queries:{type:"array",items:{type:"string"},description:"Your own 2-4 keyword formulations of it — these lead the search."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a window like "7d"/"yesterday".'},before:{type:"string",description:"Latest date: a date or window like `since`."},limit:{type:"number",description:"Max fused results (default 10)."}},required:["question"]}},{name:"search_history",description:'Search the user\'s ChatPanel history — their past chats, meeting/call transcripts, and notes — by keyword relevance. Consult this (in ADDITION to your other tools) whenever the question touches a meeting, call, demo, note, or past conversation: "outcome of the meeting", "what did we decide", "action items", "what did <person> say", "notes from yesterday". Filters: `type` (chat|meeting|note), `since`/`before` (a date like 2026-08-01 or a relative window like "7d"/"yesterday"), and `limit`/`offset` for paging. Returns compact SNIPPETS (the matching excerpt) with each record\'s id/title/type/date — token-friendly; call get_record for the full text and find_related to follow connections. This is a LOCAL WARM COPY that syncs from ChatPanel; very recent items may not be here yet — results report how current the index is, so if something is missing it likely has not synced. Meeting titles are often generic ("Zoom Meeting"), so search by CONTENT, not the title.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Content keywords (topics, names, decisions) — not the meeting title."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a relative window like "7d", "2 weeks", "yesterday".'},before:{type:"string",description:"Latest date: a date or relative window like `since`."},limit:{type:"number",description:"Max results (default 10)."},offset:{type:"number",description:"Skip N results for paging (default 0)."}},required:["query"]}},{name:"get_record",description:"Fetch one history record's full text by id (chat:<id>, meeting:<id>, note:<id> from search_history). For a long transcript, page it with maxChars + offset instead of pulling it all into context — the result says how many chars remain.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Record id such as chat:abc, meeting:imp_123, or note:xyz."},maxChars:{type:"number",description:"Return at most this many characters (token management for long transcripts)."},offset:{type:"number",description:"Start at this character offset — page through with the offset the previous call reports."}},required:["id"]}},{name:"find_related",description:"Graph navigation: given a record id (from search_history), return the records most connected to it by shared content — the meetings/notes/chats about the same topic, people or thread. Use it to expand from one hit to the surrounding context instead of re-searching.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The record id to find neighbours of."},limit:{type:"number",description:"Max related records (default 5)."}},required:["id"]}},{name:"list_history",description:"List history records (newest first) with their id, title, type and date — no bodies. Reports how current this warm copy is (its newest record). Use to see the index horizon and browse/page the corpus.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max items (default 50)."},offset:{type:"number",description:"Skip N items for paging (default 0)."}}}},{name:"list_briefs",description:`The BRIEFS ChatPanel maintains — one page per person, project or topic that appears across enough records, each claim citing the record it came from. This is the index of what the user's corpus KNOWS, as opposed to what it merely contains: read it before asking "what do we know about X", then get_brief for the one you need. Briefs are rebuilt from the records, so they are as current as the last rebuild (dates shown).`,inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max briefs (default 50)."},offset:{type:"number",description:"Skip N for paging (default 0)."}}}},{name:"get_brief",description:"One brief as STRUCTURE: the subject, its other spellings, and each claim with the record ids it cites — so you can cite the record rather than the synthesis, and open only what you need with get_record. Prefer this over get_record for a brief:… id; get_record returns the same text as prose.",inputSchema:{type:"object",properties:{id:{type:"string",description:"A brief id (brief:…) from list_briefs or search results."}},required:["id"]}},{name:"recall",description:"What ChatPanel already knows about the USER — their name, how they want answers written, their ongoing work and environment. Short and cheap; call it at the START of a session and whenever the user states a preference, then just FOLLOW what it returns without announcing that you checked. Pass the current task in `text` and it also returns the facts relevant to that task, not only the always-on ones. This is memory, not history: for what was said in a meeting or a past chat use smart_search instead.",inputSchema:{type:"object",properties:{text:{type:"string",description:"What the user is asking about right now, so task-relevant facts come back too. Omit for just the always-on ones."}}}},{name:"remember",description:`Save a durable fact about the USER to ChatPanel, carried into every future session on every model and agent — the side panel, other CLIs, everything. Use it the moment they state a standing preference ("always use pnpm"), an identity fact ("call me Alex") or a constraint that will still be true next week. Do NOT use it for task details, anything obvious from the current work, or notes about a codebase — those belong in the repo. One short self-contained sentence, written in the third person. Saving is a change to the user's own data, so say in a short clause what you saved.`,inputSchema:{type:"object",properties:{text:{type:"string",description:'The fact, one short sentence in the third person ("Prefers pnpm over npm"). Max 280 characters.'},kind:{type:"string",enum:k,description:k.map(n=>`${n}: ${N[n].hint}`).join(" ")},tags:{type:"array",items:{type:"string"},description:"Optional short tags for grouping."}},required:["text"]}},{name:"forget",description:'Remove a memory from ChatPanel when the user says it no longer holds. Name it however they did ("the Frankfurt thing") or pass the id from recall — it matches on meaning, and tells you exactly what it removed.',inputSchema:{type:"object",properties:{query:{type:"string",description:"The memory to remove: its text, roughly how the user named it, or its id."}},required:["query"]}},{name:"list_skills",description:"List the reusable skills installed on this machine (via the ChatPanel bridge) — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes) and any configured folder. Returns each skill's name and one-line description. Call open_skill to load the one that fits the task.",inputSchema:{type:"object",properties:{}}},{name:"open_skill",description:"Load one skill's full instructions by name (from list_skills), then follow them. If the instructions point at reference files, read one with read_skill_file.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name from list_skills."}},required:["name"]}},{name:"read_skill_file",description:"Read one reference file a skill's instructions point at (any path inside the skill's own folder). Use only when the task needs it.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name."},path:{type:"string",description:"The reference path as written in the instructions, e.g. references/auth.md."}},required:["name","path"]}}],x={[R]:" To have one: ChatPanel › Settings › Runtime › OpenDecision › Start (or a server that provides `decide` under Models).",[q]:" To have one: ChatPanel › Settings › Runtime › Reranker › Start (or a server that provides `rerank` under Models)."};function _(){const n=p(),e=r=>[{id:"gateway",name:"the gateway",url:`${n}${r}`,where:"this device"}],s=j({providers:{decide:e("/v1/decide"),rerank:e("/v1/rerank")},fetch:(r,o)=>fetch(r,o)}),t=P({search:async r=>{const o=await h("/v1/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({q:r,limit:8,read:E.aliasRead})});return{query:r,engines:o.engines||[],results:(o.results||[]).map((i,a)=>({rank:a+1,title:i.title||i.url,url:i.url,engine:i.engine||"",text:i.read?.markdown||i.read?.text||i.snippet||""}))}}});return[s,t]}const U=_().flatMap(n=>n.specs.map(e=>({name:e.name,description:e.description,inputSchema:e.parameters})));async function B(n,e){const s=_().find(o=>o.specs.some(i=>i.name===n));if(!s)return null;const t=await s.execute(n,e);let r=typeof t=="string"?t:String(t?.text??t);return x[n]&&/^No (decision model|reranker) answered/.test(r)&&(r+=x[n]),r}function g(n,e){if(!n)return`Index: ${e} records (warm copy synced from ChatPanel).`;const s=new Date(n),t=`${s.getFullYear()}-${String(s.getMonth()+1).padStart(2,"0")}-${String(s.getDate()).padStart(2,"0")} ${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`;return`Index: ${e} records, current through ${t} (local warm copy — items newer than this may not have synced from ChatPanel yet).`}function O(){try{const n=S();return n?{Authorization:`Bearer ${n}`}:{}}catch{return{}}}async function h(n,e){let s;try{s=await fetch(p()+n,e)}catch(r){throw new Error(`the ChatPanel gateway is not running at ${p()} — start it with "chatpanel-gateway --install" (or run "chatpanel-gateway"), then retry. [${r.message}]`)}const t=await s.json().catch(()=>({}));if(!s.ok)throw new Error(t?.error?.message||`the gateway returned HTTP ${s.status} for ${n}`);return t}function m(n){if(n==null||n==="")return null;if(typeof n=="number")return n;const e=String(n).trim().toLowerCase(),s=864e5;if(e==="today")return Date.now()-s;if(e==="yesterday")return Date.now()-2*s;const t=/^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(e);if(t){const o=Number(t[1]),i=t[2][0],a=i==="d"?s:i==="w"?7*s:i==="m"?30*s:365*s;return Date.now()-o*a}const r=Date.parse(e);return Number.isNaN(r)?null:r}const w=(n,e)=>`${e+1}. [${n.id}] ${n.title||"(untitled)"} · ${n.type}${n.date?" · "+new Date(n.date).toISOString().slice(0,10):""}${n.snippet?`
|
|
3
|
+
${n.snippet}`:""}`;async function F(n,e={}){const s=await B(n,e);if(s!=null)return s;if(n==="smart_search"){const t={question:String(e.question||""),queries:Array.isArray(e.queries)?e.queries.map(String):[],limit:Number(e.limit)||10};e.type&&(t.type=String(e.type));const r=m(e.since);r!=null&&(t.since=r);const o=m(e.before);o!=null&&(t.before=o);const i=await h("/v1/history/smart-search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),a=i.results||[],c=g(i.newest,i.size),l=(i.queries||[]).map(d=>`"${d}"`).join(", ");return a.length?[c,"",`${a.length} result(s) for "${e.question}" — searched ${i.queries.length} way(s): ${l}`,...a.map((d,C)=>`${w(d,C)}${d.foundBy?.length>1?`
|
|
4
|
+
(matched ${d.foundBy.length} of the queries)`:""}`)].join(`
|
|
5
5
|
`)+`
|
|
6
6
|
|
|
7
7
|
get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.question}".
|
|
8
|
-
Searched ${
|
|
9
|
-
${
|
|
10
|
-
If you expected a recent item it may not have synced yet — check ChatPanel directly, or try different keywords (meeting titles are often generic).`}if(
|
|
8
|
+
Searched ${i.queries?.length||0} way(s): ${l}.
|
|
9
|
+
${c}
|
|
10
|
+
If you expected a recent item it may not have synced yet — check ChatPanel directly, or try different keywords (meeting titles are often generic).`}if(n==="search_history"){const t={query:String(e.query||""),limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0)};e.type&&(t.type=String(e.type));const r=m(e.since);r!=null&&(t.since=r);const o=m(e.before);o!=null&&(t.before=o);const i=await h("/v1/history/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),a=i.results||[],c=g(i.newest,i.size),l=[e.type&&`type=${e.type}`,e.since&&`since=${e.since}`,e.before&&`before=${e.before}`].filter(Boolean).join(", "),d=l?` (${l})`:"";return a.length?[c,"",`${a.length} result(s) for "${e.query}"${d}:`,...a.map(w)].join(`
|
|
11
11
|
`)+`
|
|
12
12
|
|
|
13
|
-
get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.query}"${
|
|
14
|
-
${
|
|
15
|
-
If you expected a recent item, it may not have synced yet — check ChatPanel directly, or broaden the query (titles are often generic; try content keywords, or drop a filter).`}if(
|
|
13
|
+
get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.query}"${d}.
|
|
14
|
+
${c}
|
|
15
|
+
If you expected a recent item, it may not have synced yet — check ChatPanel directly, or broaden the query (titles are often generic; try content keywords, or drop a filter).`}if(n==="get_record"){const t=new URLSearchParams({id:String(e.id||"")});e.maxChars!=null&&t.set("maxChars",String(Math.max(1,Number(e.maxChars)||0))),e.offset!=null&&t.set("offset",String(Math.max(0,Number(e.offset)||0)));const o=(await h(`/v1/history/get?${t}`)).record,i=`[${o.id}] ${o.title||"(untitled)"} · ${o.type}${o.date?" · "+new Date(o.date).toISOString().slice(0,10):""}`,a=o.truncated?`
|
|
16
16
|
|
|
17
|
-
[showing ${
|
|
17
|
+
[showing ${o.text.length} of ${o.totalChars} chars (from offset ${o.offset}). For the next part call get_record again with offset=${o.offset+o.text.length}.]`:"";return`${i}
|
|
18
18
|
|
|
19
|
-
${
|
|
19
|
+
${o.text||"(empty)"}${a}`}if(n==="find_related"){const r=(await h(`/v1/history/related?id=${encodeURIComponent(String(e.id||""))}&limit=${Number(e.limit)||5}`)).results||[];return r.length?[`Records related to ${e.id}:`,...r.map(w)].join(`
|
|
20
20
|
`)+`
|
|
21
21
|
|
|
22
|
-
get_record <id> for full text.`:`Nothing related to ${e.id} found (or that id isn't in the warm index — run search_history first to get a valid id).`}if(
|
|
23
|
-
`)}if(
|
|
22
|
+
get_record <id> for full text.`:`Nothing related to ${e.id} found (or that id isn't in the warm index — run search_history first to get a valid id).`}if(n==="list_history"){const t=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0)}),r=await h(`/v1/history/list?${t}`),o=r.items||[];if(!o.length)return"History is empty (or the gateway has not been seeded yet — open ChatPanel with warm sync enabled).";const i=o[0]?.date||null;return[g(i,r.total),"",`${o.length} of ${r.total} records:`,...o.map(a=>`[${a.id}] ${a.title||"(untitled)"} · ${a.type}${a.date?" · "+new Date(a.date).toISOString().slice(0,10):""} · ${a.chars} chars`)].join(`
|
|
23
|
+
`)}if(n==="list_briefs"){const t=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0),type:"brief"}),r=await h(`/v1/history/list?${t}`),o=r.items||[];return o.length?[`${o.length} of ${r.total} briefs (each is a page about one subject, with every claim cited):`,...o.map(i=>`[${i.id}] ${i.title||"(untitled)"}${i.date?" · rebuilt "+new Date(i.date).toISOString().slice(0,10):""}`)].join(`
|
|
24
24
|
`)+`
|
|
25
25
|
|
|
26
|
-
get_brief <id> for its claims and the records they cite.`:`No briefs yet. ChatPanel builds them from the user's records on the Briefs page; if that has run, the user may have "share briefs with local agents" switched off.`}if(
|
|
27
|
-
`)}if(
|
|
26
|
+
get_brief <id> for its claims and the records they cite.`:`No briefs yet. ChatPanel builds them from the user's records on the Briefs page; if that has run, the user may have "share briefs with local agents" switched off.`}if(n==="get_brief"){const t=String(e.id||""),o=(await h(`/v1/history/get?${new URLSearchParams({id:t})}`)).record,i=T(o?.text);if(!i)return`${t} is not a brief (type ${o?.type||"unknown"}). Use get_record for it, or list_briefs for the brief ids.`;const a=[`BRIEF ${t} — ${i.name} (${i.kind})${i.aliases.length?` · also known as ${i.aliases.join(", ")}`:""}`,""];a.push(`${i.claims.length} claim(s), each with the records it cites:`);for(const c of i.claims)a.push(`• ${c.text}`),c.refs.length&&a.push(` cites: ${c.refs.map(l=>`${l.kind}:${l.id}`).join(", ")}`);return i.records.length&&a.push("",`Built from ${i.records.length} record(s) (most recent first): ${i.records.slice(0,12).map(c=>c.title).join(" · ")}${i.records.length>12?" …":""}`),a.push("","get_record <kind:id> opens a cited record; find_related <id> follows its connections."),a.join(`
|
|
27
|
+
`)}if(n==="recall"){const t=await h("/v1/memory/recall",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:String(e.text||"")})});return t.memories?.length?t.block:t.size?"Nothing in ChatPanel memory applies here.":"ChatPanel memory is empty — nothing is known about this user yet. Use `remember` when they state something durable about themselves or how they want to work."}if(n==="remember"){const t=String(e.text||"").trim();if(!t)return"remember needs `text` — one short sentence about the user.";const r=await h("/v1/memory/remember",{method:"POST",headers:{"content-type":"application/json",...O()},body:JSON.stringify({text:t,kind:e.kind?String(e.kind):"fact",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:"mcp",surface:"mcp",agent:u}})});return r.action==="duplicate"?`Already known: "${r.record.text}" — nothing changed.`:r.action==="update"?`Updated memory to "${r.record.text}" (was "${r.replaced?.text}"). It applies to every future session.`:`Remembered: "${r.record.text}". It applies to every future ChatPanel session, on every model.`}if(n==="forget"){const t=String(e.query||"").trim();if(!t)return"forget needs `query` — the memory to remove.";const r=await h("/v1/memory/forget",{method:"POST",headers:{"content-type":"application/json",...O()},body:JSON.stringify({query:t})});return r.removed?.length?`Forgot: ${r.removed.map(o=>`"${o.text}"`).join(", ")}.`:`No memory matches "${t}". Call recall to see what is stored.`}if(n==="list_skills"){let t;try{t=await y("/skills")}catch(o){return`Installed skills are unavailable because the ChatPanel bridge is not running at ${v()}. Install/start it with:
|
|
28
28
|
curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash
|
|
29
|
-
Then retry. History tools work without the bridge. [${
|
|
29
|
+
Then retry. History tools work without the bridge. [${o.message}]`}const r=t.skills||[];return r.length?[`${r.length} skill(s) installed:`,...r.map(o=>`- ${o.command||o.id}: ${o.description||o.name}${o.origin?.source?` (from ${o.origin.source})`:""}`)].join(`
|
|
30
30
|
`)+`
|
|
31
31
|
|
|
32
|
-
Use open_skill with a name to load its instructions.`:"No skills installed on this machine yet."}if(
|
|
33
|
-
`);for await(const
|
|
34
|
-
`))>=0;){const r=
|
|
32
|
+
Use open_skill with a name to load its instructions.`:"No skills installed on this machine yet."}if(n==="open_skill"){let t;try{t=await y(`/skills/${encodeURIComponent(String(e.name||"").trim())}`)}catch(r){return`Could not open "${e.name}": ${r.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return t.skill?.prompt||"(this skill has no extra instructions — just apply it.)"}if(n==="read_skill_file"){const t=encodeURIComponent(String(e.name||"").trim()),r=String(e.path||"").trim().split("/").map(encodeURIComponent).join("/");let o;try{o=await y(`/skills/${t}/file/${r}`)}catch(i){return`Could not read ${e.path}: ${i.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return o.text||"(empty)"}throw new Error(`unknown tool: ${n}`)}async function Y(n){const{id:e,method:s,params:t}=n||{},r=i=>({jsonrpc:"2.0",id:e,result:i}),o=(i,a)=>({jsonrpc:"2.0",id:e,error:{code:i,message:a}});try{switch(s){case"initialize":return u=t?.clientInfo?.name||u,r({protocolVersion:A,capabilities:{tools:{}},serverInfo:L,instructions:I});case"tools/list":return r({tools:[...D,...U]});case"tools/call":{const i=Date.now();try{const a=await F(t?.name,t?.arguments||{});return $({client:u,tool:t?.name,ok:!0,ms:Date.now()-i,args:t?.arguments||{}}),r({content:[{type:"text",text:a}]})}catch(a){throw $({client:u,tool:t?.name,ok:!1,ms:Date.now()-i,args:t?.arguments||{},error:a.message}),a}}case"ping":return r({});default:return typeof s=="string"&&s.startsWith("notifications/")||e===void 0?null:o(-32601,`method not found: ${s}`)}}catch(i){return s==="tools/call"?r({content:[{type:"text",text:`Error: ${i.message}`}],isError:!0}):o(-32603,i.message)}}async function Z(){let n="";process.stdin.setEncoding("utf8");const e=s=>process.stdout.write(JSON.stringify(s)+`
|
|
33
|
+
`);for await(const s of process.stdin){n+=s;let t;for(;(t=n.indexOf(`
|
|
34
|
+
`))>=0;){const r=n.slice(0,t).trim();if(n=n.slice(t+1),!r)continue;let o;try{o=JSON.parse(r)}catch{continue}const i=await Y(o);i&&e(i)}}}export{Y as handleRpc,Z as runMcpServer};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as x,readFileSync as $,createWriteStream as b}from"node:fs";import{mkdir as k,rename as v,unlink as P}from"node:fs/promises";import{dirname as W,join as f,resolve as g,sep as w}from"node:path";const R=/\.(onnx|onnx_data|onnx\.data|ort)$/i;function y(e,i,s=""){const t=String(i||"");if(!t)return null;if(/^https?:\/\//i.test(t)){const r=String(s||"").replace(/\/*$/,"/");if(!r||!t.startsWith(r))return null;let a;try{a=decodeURIComponent(t.slice(r.length)).replace(/\/resolve\/[^/]+\//,"/")}catch{return null}return a.split("/").includes("..")?null:f(e,a)}const n=g(t.startsWith(w)||/^[A-Za-z]:[\\/]/.test(t)?t:f(e,t));return n===e||n.startsWith(e+w)?n:null}function M(e,{remoteHost:i=()=>""}={}){return e=g(e),{async match(s){const t=y(e,s,i());if(!t||!x(t))return;if(R.test(t))return t;const n=$(t);return new Response(n,{status:200,headers:{"content-length":String(n.length),"content-type":"application/octet-stream"}})},async put(s,t,n){const r=y(e,s,i());if(!r)throw new Error(`refusing to cache outside the model dir: ${s}`);const a=`${r}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;await k(W(r),{recursive:!0});const l=Number(t.headers?.get?.("content-length"))||0;let u=0;const d=b(a);try{const h=t.body.getReader();for(;;){const{done:p,value:o}=await h.read();if(p)break;await new Promise((c,S)=>d.write(o,m=>m?S(m):c())),u+=o.length,l&&n&&n({status:"progress",progress:u/l*100,loaded:u,total:l})}await new Promise((p,o)=>d.end(c=>c?o(c):p())),await v(a,r)}catch(h){throw d.destroy(),await P(a).catch(()=>{}),h}}}}export{y as keyToPath,M as makeModelFileCache};
|