@chatpanel/gateway 0.55.0 → 0.57.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -3
- package/src/capability-embedded.js +1 -0
- package/src/capability-proxy.js +1 -1
- package/src/configstore.js +1 -1
- package/src/cross-encoder.js +1 -0
- package/src/embedded-models.js +1 -0
- package/src/mcp.js +6 -6
- package/src/ner-engine.js +1 -1
- package/src/providers.js +1 -1
- package/src/router.js +1 -1
- package/src/runtime.js +4 -4
- package/src/server.js +25 -25
- package/src/version.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.57.1",
|
|
4
4
|
"description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -22,8 +22,8 @@
|
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
25
|
-
"@chatpanel/bridge": "^0.
|
|
26
|
-
"@chatpanel/events": "^0.
|
|
25
|
+
"@chatpanel/bridge": "^0.32.1",
|
|
26
|
+
"@chatpanel/events": "^0.221.0",
|
|
27
27
|
"@chatpanel/pii": "^0.11.3",
|
|
28
28
|
"@huggingface/transformers": "^4.2.0",
|
|
29
29
|
"defuddle": "^0.19.4",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{openDecision as h}from"@chatpanel/events/open-decision.js";import{adaptRequest as x,adaptResponse as w}from"./capability-adapters.js";import{createCrossEncoder as y}from"./cross-encoder.js";const _=e=>1/(1+Math.exp(-e)),v=e=>{const o=Math.max(...e),s=e.map(n=>Math.exp(n-o)),a=s.reduce((n,m)=>n+m,0);return s.map(n=>n/a)};function E(e){const o=e?.label2id&&Object.entries(e.label2id).find(([a])=>/^entail/i.test(a));if(o)return Number(o[1]);const s=e?.id2label&&Object.entries(e.id2label).find(([,a])=>/^entail/i.test(String(a)));if(s)return Number(s[0]);throw new Error("the decide model has no entailment class — it is not an NLI model")}function M(e){return e.length===1?_(e[0]):v(e)[e.length-1]}function N({encoderFor:e=null,warmMs:o,threads:s=2,log:a=()=>{}}={}){const n={},m=t=>n[t]||=e?e(t):y({name:t,warmMs:o,threads:s,log:a});async function b(t,r,p){const d=m(t);if(t==="rerank"){const{rows:u}=await d.pairs(p,r.query,r.documents),l=u.map((i,c)=>({index:c,relevance_score:M(i)})).sort((i,c)=>c.relevance_score-i.relevance_score||i.index-c.index);return{results:r.top_n?l.slice(0,r.top_n):l}}if(t==="decide"){const{config:u}=await d.prepare(p),l={entailment:E(u),nli:async(c,f)=>(await d.pairs(p,c,f,{maxLength:1024})).rows},i=await h(x("systemone",r).body,l);return w("systemone",i,r)}throw new Error(`no in-process ${t}`)}return{call:b,health:(t,r)=>n[t]?n[t].health(r):{state:"idle"},threads:s}}export{N as createEmbeddedCapabilities,E as entailmentIndex,M as relevanceOf};
|
package/src/capability-proxy.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{secureFetch as
|
|
1
|
+
import{secureFetch as D}from"./secure-fetch.js";import{createReadStats as P}from"./retrieval/read.js";import{CAPABILITY_ROUTES as A,overBudget as x,validateRerankRequest as C,validateRerankResponse as B,validateDecideRequest as N,validateDecideResponse as z}from"./capability-endpoints.js";import{adaptRequest as F,adaptResponse as J}from"./capability-adapters.js";import{defaultEmbeddedModel as G}from"./embedded-models.js";const M=Object.freeze(["rerank","decide"]),T={rerank:{request:C,response:B,chars:u=>u.query.length+u.documents.reduce((f,n)=>f+n.length,0)},decide:{request:N,response:z,chars:u=>u.state.length}},H=18e4,U=6e4,l=(u,f,n,h={})=>({status:u,body:{error:{type:f,message:n,...h}}});function Q({cfg:u,fetchImpl:f=D,now:n=()=>Date.now(),wake:h=null,embedded:y=null}={}){const _=Object.fromEntries(M.map(e=>[e,{stats:P(),last:null,error:null}])),R=e=>{const t=u.capabilities?.[e];return t&&t.provider!=="embedded"&&t.provider!=="none"&&typeof t.url=="string"&&/^https?:\/\//.test(t.url)&&typeof t.adapter=="string"?t:null},S=e=>{if(!y||R(e))return null;const t=u.capabilities?.[e];if(t?.provider==="none")return null;const r=t?.provider==="embedded"&&typeof t.model=="string"&&t.model?t.model:G(e);return r?{model:r}:null};async function E(e,t,r){const d=T[e];let s;try{s=d.request(r)}catch(c){return l(400,"invalid_request",c.message)}if(s.model&&s.model!==t.model)return l(404,"model_not_found",`${e}: model ${s.model} is not served here (${t.model} is)`);const o=_[e],v=d.chars(s),b=x(o.stats.stats(),v,s.budgetMs);if(b)return{status:503,body:b};const g=n();let m;try{m={...await y.call(e,s,t.model),model:t.model}}catch(c){return c.code==="WARMING"?l(503,"provider_warming",c.message,c.progress?{progress:c.progress}:{}):l(503,"provider_unavailable",`${e}: the in-process model ${t.model} could not answer — ${c.message}`)}const $=n()-g;m={...m,ms:$,...e==="decide"?{calibrated:!1}:{}};try{d.response(m,s)}catch(c){return l(502,"bad_shape",`${e}: the in-process answer did not fit the contract — ${c.message}`)}return o.stats.record($,v),o.error=null,o.last=n(),{status:200,body:m}}async function I(e,t){if(!M.includes(e))return l(404,"unknown_capability",`no such capability ${e}`);const r=R(e);if(!r){const a=S(e);return a?E(e,a,t):l(404,"no_provider",`no ${e} provider — it is turned off (capabilities.${e}.provider = none): turn it on under Settings › Runtime, or point capabilities.${e}.url at a server that provides it`)}const d=T[e];let s;try{s=d.request(t)}catch(a){return l(400,"invalid_request",a.message)}if(s.model&&r.model&&s.model!==r.model)return l(404,"model_not_found",`${e}: model ${s.model} is not served here (${r.model} is)`);const o=_[e],v=d.chars(s),b=x(o.stats.stats(),v,s.budgetMs);if(b)return{status:503,body:b};let g;try{g=F(r.adapter,{...s,model:s.model||r.model||void 0})}catch(a){return l(500,"bad_adapter",a.message)}const m=`${r.url.replace(/\/+$/,"")}${g.route}`,$=()=>f(m,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",...r.token?{authorization:`Bearer ${r.token}`}:{}},body:JSON.stringify(g.body),signal:AbortSignal.timeout(s.budgetMs?Math.max(s.budgetMs*2,5e3):o.stats.stats().calls?U:H)}),c=!!(r.service&&typeof h=="function");if(c){const a=await h(r.service).catch(k=>({ok:!1,error:k.message}));if(!a?.ok)return o.error=a?.error||"could not start",o.last=n(),l(503,"provider_unavailable",`${e}: the ${r.service} container could not be started — ${o.error}`)}const j=n();let p;try{p=await $()}catch(a){const k=c?await h(r.service,{force:!0}).catch(()=>null):null;try{if(!k?.ok)throw a;p=await $()}catch(O){return o.error=O.message,o.last=n(),l(503,"provider_unavailable",`${e}: ${r.service?`the ${r.service} container`:r.url} did not answer — ${O.message}`)}}let i;try{i=await p.json()}catch{i=null}if(!p.ok)return o.error=`HTTP ${p.status}`,o.last=n(),l(502,"provider_error",`${e}: the provider answered ${p.status}${i?.detail?` — ${typeof i.detail=="string"?i.detail:JSON.stringify(i.detail)}`:i?.error?` — ${typeof i.error=="string"?i.error:i.error.message||""}`:""}`);const w=n()-j;let q;try{const a=J(r.adapter,i,s);q={...a,model:r.model||a.model||r.adapter,...a.model&&r.model&&a.model!==r.model?{providerModel:a.model}:{},ms:w,...e==="decide"?{calibrated:r.calibrated===!0}:{}},d.response(q,s)}catch(a){return o.error=a.message,o.last=n(),l(502,"bad_shape",`${e}: the provider's answer did not fit the contract — ${a.message}`)}return o.stats.record(w,v),o.error=null,o.last=n(),{status:200,body:q}}function L(e){const t=R(e),r=_[e],d=r.stats.stats();if(!t){const s=S(e);if(!s)return null;const o=y.health(e,s.model);return{id:e,route:A[e],models:[s.model],default:s.model,requirements:{egress:"none"},...e==="decide"?{calibrated:!1}:{},stats:d,runtime:{...o,name:"embedded",model:s.model,threads:y.threads}}}return{id:e,route:A[e],models:t.model?[t.model]:[],...t.model?{default:t.model}:{},requirements:{egress:/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:|\/|$)/.test(t.url)?"none":"trusted"},...e==="decide"?{calibrated:t.calibrated===!0}:{},stats:d,runtime:{state:r.error?"down":d.calls?"ready":"idle",name:t.service?"container":"external",adapter:t.adapter,...t.service?{service:t.service}:{},url:t.url,...r.error?{error:r.error}:{}}}}return{call:I,entry:L,stats:e=>_[e]?.stats.stats()||{calls:0},capabilities:M}}export{Q as createCapabilityProxy};
|
package/src/configstore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{writeFileSync as b,mkdirSync as y,chmodSync as p}from"node:fs";import{join as A,dirname as w}from"node:path";import x from"node:os";import{usage as k}from"./freegate.js";import{applyFusionsPatch as f}from"./fusions.js";import{normalizeRegistries as E,REGISTRY_KINDS as D}from"@chatpanel/events/registries.js";import{assertEndpointUrl as a}from"@chatpanel/pii";import{normalizeGrant as S}from"@chatpanel/bridge/src/events/sandbox-policy.js";const T=["open","allowlist","off"],l=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function d(e={}){const r=e&&typeof e=="object"?e:{},o=T.includes(r.mode)?r.mode:"open",{hosts:i}=S({hosts:r.hosts??[]});return{mode:o,hosts:i,write:l(r.write),denyRead:l(r.denyRead)}}function L(e){const r=d(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function u(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||A(x.homedir(),".chatpanel","gateway.config.json")}function C(e){const r=e?.registries||{},o={};for(const[i,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[i]&&(o[t]=r[i]);return o}function M(e,r=u()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===u({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);y(w(r),{recursive:!0,mode:448});const o={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp};b(r,JSON.stringify(o,null,2),{mode:384});try{p(r,384)}catch{}}function H(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:i,...t}=o;return{...t,hasKey:!!i}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:o,...i}=e.redaction?.detection||{backend:"off"};return i})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:d(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0}},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([o,i])=>{const{token:t,...n}=i||{};return[o,{...n,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free: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 G(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function N(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),t=Number(o.port)||(o.protocol==="https:"?443:80);return i&&t===(Number(r.port)||4320)}const m=["default","acceptEdits","bypassPermissions"];function g(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 K(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const o=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=r.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const t=N(i,e);return t&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!t}).map(i=>{const t={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(t.agent=i.agent||i.id),i.type==="api"){t.baseUrl=String(i.baseUrl||""),t.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;s&&(t.apiKey=s)}const n=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;return n&&(t.service=n),t})}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),m.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(o=>String(o).trim()).filter(o=>/^[a-p]{32}$/.test(o))),r.upstreams&&typeof r.upstreams=="object")for(const o of["openai","anthropic"]){const i=r.upstreams[o];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:i.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const o=r.redaction;(o.tier==="basic"||o.tier==="full")&&(e.redaction.tier=o.tier),"redactSystem"in o&&(e.redaction.redactSystem=!!o.redactSystem),Array.isArray(o.dictionary)&&(e.redaction.dictionary=o.dictionary),o.detection&&typeof o.detection=="object"&&(e.redaction.detection=o.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=d({...e.sandbox||{},...r.sandbox})),r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const o=String(r.read.remote.url||"").trim();o&&a(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.registries&&typeof r.registries=="object"){const o=E(r.registries),i={...e.registries||{}};for(const t of D)t in r.registries&&(o[t]?i[t]=o[t]:delete i[t]);e.registries=i}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&a(i),e.search.searxng.url=i}typeof o.token=="string"&&(e.search.searxng.token=o.token),typeof o.engines=="string"&&(e.search.searxng.engines=o.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(o.safesearch)&&(e.search.searxng.safesearch=o.safesearch)}["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const o=f(e,r.fusions);if(o){const i=new Error(o);throw i.code="SHAPE",i}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const o of["rerank","decide","stt","tts","detect","embed"]){if(!(o in r.capabilities))continue;const i=r.capabilities[o];if(i===null){delete e.capabilities[o],o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!i||typeof i!="object")continue;const n={...e.capabilities[o]||{}};if(i.provider==="embedded"){e.capabilities[o]={provider:"embedded"},o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if("url"in i){const s=String(i.url||"").trim();s&&a(s),n.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(n.adapter=i.adapter),typeof i.model=="string"&&(n.model=i.model.trim()),typeof i.token=="string"&&(n.token=i.token),typeof i.calibrated=="boolean"&&(n.calibrated=i.calibrated),typeof i.redact=="boolean"&&(n.redact=i.redact),!n.url){delete e.capabilities[o];continue}n.provider="remote",delete n.service,e.capabilities[o]=n,o==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}})}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const o=Number(r.tools.maxPerTurn);Number.isFinite(o)&&o>=1&&(e.tools.maxPerTurn=Math.floor(o))}return e}export{m as PERMISSION_MODES,K as applyConfigPatch,G as applyNerModelSelection,g as bridgeAgentOptions,u as configPath,N as isSelfDestination,d as normalizeSandboxConfig,M as persistConfig,H as publicConfig,C as registryChildEnv,L as sandboxEnvFor};
|
|
1
|
+
import{writeFileSync as y,mkdirSync as A,chmodSync as w}from"node:fs";import{join as x,dirname as k}from"node:path";import f from"node:os";import{usage as E}from"./freegate.js";import{applyFusionsPatch as D}from"./fusions.js";import{EMBEDDED_MODELS as S,EMBEDDED_IDS as l,isEmbeddedModel as c}from"./embedded-models.js";import{normalizeRegistries as T,REGISTRY_KINDS as v}from"@chatpanel/events/registries.js";import{assertEndpointUrl as a}from"@chatpanel/pii";import{normalizeGrant as N}from"@chatpanel/bridge/src/events/sandbox-policy.js";const _=["open","allowlist","off"],u=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function d(e={}){const r=e&&typeof e=="object"?e:{},o=_.includes(r.mode)?r.mode:"open",{hosts:i}=N({hosts:r.hosts??[]});return{mode:o,hosts:i,write:u(r.write),denyRead:u(r.denyRead)}}function B(e){const r=d(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function m(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||x(f.homedir(),".chatpanel","gateway.config.json")}function K(e){const r=e?.registries||{},o={};for(const[i,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[i]&&(o[t]=r[i]);return o}function U(e,r=m()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===m({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);A(k(r),{recursive:!0,mode:448});const o={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp};y(r,JSON.stringify(o,null,2),{mode:384});try{w(r,384)}catch{}}function g(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:i,...t}=o;return{...t,hasKey:!!i}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:o,...i}=e.redaction?.detection||{backend:"off"};return i})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:d(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0}},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([o,i])=>{const{token:t,...n}=i||{};return[o,{...n,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:E(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 Y(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function O(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),t=Number(o.port)||(o.protocol==="https:"?443:80);return i&&t===(Number(r.port)||4320)}const b=["default","acceptEdits","bypassPermissions"];function F(e,r={}){const o=e?.bridge||{};return{...b.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function $(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const o=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=r.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const t=O(i,e);return t&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!t}).map(i=>{const t={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(t.agent=i.agent||i.id),i.type==="api"){t.baseUrl=String(i.baseUrl||""),t.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;s&&(t.apiKey=s)}const n=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;return n&&(t.service=n),t})}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),b.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(o=>String(o).trim()).filter(o=>/^[a-p]{32}$/.test(o))),r.upstreams&&typeof r.upstreams=="object")for(const o of["openai","anthropic"]){const i=r.upstreams[o];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:i.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const o=r.redaction;(o.tier==="basic"||o.tier==="full")&&(e.redaction.tier=o.tier),"redactSystem"in o&&(e.redaction.redactSystem=!!o.redactSystem),Array.isArray(o.dictionary)&&(e.redaction.dictionary=o.dictionary),o.detection&&typeof o.detection=="object"&&(e.redaction.detection=o.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=d({...e.sandbox||{},...r.sandbox})),r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const o=String(r.read.remote.url||"").trim();o&&a(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.registries&&typeof r.registries=="object"){const o=T(r.registries),i={...e.registries||{}};for(const t of v)t in r.registries&&(o[t]?i[t]=o[t]:delete i[t]);e.registries=i}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&a(i),e.search.searxng.url=i}typeof o.token=="string"&&(e.search.searxng.token=o.token),typeof o.engines=="string"&&(e.search.searxng.engines=o.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(o.safesearch)&&(e.search.searxng.safesearch=o.safesearch)}["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const o=D(e,r.fusions);if(o){const i=new Error(o);throw i.code="SHAPE",i}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const o of["rerank","decide","stt","tts","detect","embed"]){if(!(o in r.capabilities))continue;const i=r.capabilities[o];if(i===null){delete e.capabilities[o],o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!i||typeof i!="object")continue;const n={...e.capabilities[o]||{}};if(i.provider==="embedded"){if(l.includes(o)&&i.model!=null){if(!c(o,i.model)){const s=new Error(`capabilities.${o}.model must be one of ${S[o].map(p=>p.id).join(", ")}`);throw s.code="SHAPE",s}e.capabilities[o]={provider:"embedded",model:i.model};continue}e.capabilities[o]={provider:"embedded"},o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(i.provider==="none"&&l.includes(o)){e.capabilities[o]={provider:"none"};continue}if("url"in i){const s=String(i.url||"").trim();s&&a(s),n.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(n.adapter=i.adapter),typeof i.model=="string"&&(n.model=i.model.trim()),typeof i.token=="string"&&(n.token=i.token),typeof i.calibrated=="boolean"&&(n.calibrated=i.calibrated),typeof i.redact=="boolean"&&(n.redact=i.redact),!n.url){delete e.capabilities[o];continue}n.provider="remote",delete n.service,e.capabilities[o]=n,o==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}})}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const o=Number(r.tools.maxPerTurn);Number.isFinite(o)&&o>=1&&(e.tools.maxPerTurn=Math.floor(o))}return e}export{b as PERMISSION_MODES,$ as applyConfigPatch,Y as applyNerModelSelection,F as bridgeAgentOptions,m as configPath,O as isSelfDestination,d as normalizeSandboxConfig,U as persistConfig,g as publicConfig,K as registryChildEnv,B as sandboxEnvFor};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ensureLib as C,modelRoot as S,modelOnDisk as F}from"./ner-engine.js";import{isMirroredModel as G}from"./models.js";import{verifyModelWeights as I}from"./model-integrity.js";import{makeWarmTimer as L}from"./warm-timer.js";class T extends Error{constructor(d,$=null){super(d),this.code="WARMING",this.progress=$}}const k=6e4;function D({name:l,threads:d=2,warmMs:$,allowDownload:H=!0,log:f=()=>{},loadLib:W=C,onDisk:h=F,now:v=()=>Date.now()}={}){let a=null,o=null,n=null,m=0,g=Promise.resolve();const M=L({warmMs:$,busy:()=>m>0||!!o,log:f,unload:()=>x()});async function q(r){const e=await W(),t=h(r);if(!t&&!H)throw new Error(`${r} is not on disk and downloads are off`);e.env.allowRemoteModels=!t;const c=e.env.remoteHost;if(!t&&!G(r))try{e.env.remoteHost="https://huggingface.co/"}catch{}t||f(`[${l}] downloading ${r} (one-time)…`);try{const u=t?void 0:s=>{o&&s?.status==="progress"&&(o.progress={file:s.file||null,pct:Math.round(s.progress||0)})},p={dtype:"q8",session_options:{intraOpNumThreads:d,interOpNumThreads:1},...u?{progress_callback:u}:{}},w=await e.AutoTokenizer.from_pretrained(r,u?{progress_callback:u}:{}),i=await e.AutoModelForSequenceClassification.from_pretrained(r,p);if(!t)try{I(r,{modelsDir:S(),log:f})}catch(s){try{await i.dispose?.()}catch{}throw s}return f(`[${l}] ready — ${r} in-process (${d} threads)`),{id:r,tokenizer:w,model:i,config:i.config||{}}}finally{try{e.env.remoteHost=c}catch{}}}function E(r){if(o?.id===r)return o.promise;const e=q(r).then(async t=>{const c=a;if(a=t,n=null,c&&c!==t)try{await c.model.dispose?.()}catch{}return t},t=>{throw n={id:r,error:t.message,at:v()},f(`[${l}] could not load ${r}: ${t.message}`),t}).finally(()=>{o?.promise===e&&(o=null),M.arm()});return o={id:r,promise:e,progress:null},e}async function b(r){if(a?.id===r)return a;if(n?.id===r&&v()-n.at<k)throw new Error(n.error);if(o?.id!==r&&!h(r))throw E(r).catch(()=>{}),new T(`${l}: downloading ${r} — try again shortly`);if(o?.id===r&&!h(r))throw new T(`${l}: still downloading ${r}`,o.progress);return E(r)}function z(r,e,t,{maxLength:c=512}={}){m++,M.disarm();const u=g.then(async()=>{const p=await b(r),w=[];for(let i=0;i<t.length;i+=16){const s=t.slice(i,i+16),O=p.tokenizer(new Array(s.length).fill(e),{text_pair:s,padding:!0,truncation:!0,max_length:c}),{logits:A}=await p.model(O),R=A.dims[1];for(let y=0;y<s.length;y++)w.push(Array.from(A.data.slice(y*R,(y+1)*R)))}return{rows:w,config:p.config}});return g=u.catch(()=>{}),u.finally(()=>{m--,m||M.arm()})}function N(r){const e=g.then(async()=>({config:(await b(r)).config}));return g=e.catch(()=>{}),e}async function x(){const r=a;if(a=null,r){try{await r.model.dispose?.()}catch{}f(`[${l}] unloaded ${r.id} (idle)`)}}function _(r){return o?.id===r?h(r)?"loading":"downloading":a?.id===r?"ready":n?.id===r&&v()-n.at<k?"down":"idle"}return{pairs:z,prepare:N,state:_,health:r=>({state:_(r),...o?.id===r&&o.progress?{progress:o.progress}:{},...n?.id===r&&_(r)==="down"?{error:n.error}:{}}),loaded:()=>a?.id||null,unload:x,threads:d}}export{T as WarmingError,D as createCrossEncoder};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=Object.freeze({rerank:Object.freeze([Object.freeze({id:"Xenova/ms-marco-TinyBERT-L-2-v2",label:"TinyBERT L-2",mb:5,languages:"English",note:"lightest — the default"}),Object.freeze({id:"jinaai/jina-reranker-v1-tiny-en",label:"Jina reranker v1 tiny",mb:34,languages:"English",note:"a little sharper, still light"}),Object.freeze({id:"Xenova/bge-reranker-base",label:"BGE reranker base",mb:289,languages:"100+ languages",note:"multilingual; ~1 GB while loaded"})]),decide:Object.freeze([Object.freeze({id:"MoritzLaurer/ModernBERT-base-zeroshot-v2.0",label:"ModernBERT base zero-shot",mb:147,languages:"English",note:"the default"})])}),n=Object.freeze(Object.keys(a)),l=e=>a[e]?.[0]?.id||null,i=(e,t)=>!!a[e]?.some(r=>r.id===t);export{n as EMBEDDED_IDS,a as EMBEDDED_MODELS,l as defaultEmbeddedModel,i as isEmbeddedModel};
|
package/src/mcp.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import{loadConfig as y}from"./config.js";import{VERSION as
|
|
2
|
-
`);async function z(){try{const t=await fetch(`${f()}/health`,{signal:AbortSignal.timeout(600)}),e=String((await t.json())?.version||"");return!e||e===
|
|
3
|
-
`)}catch{return""}}function k(){try{return y().mcp?.ask||{}}catch{return{}}}let m="unknown";function C(t){try{const e=b();fetch(`${f()}/v1/observability/access`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(t)}).catch(()=>{})}catch{}}function f(){const t=process.env.CHATPANEL_GATEWAY_URL;if(t)return t.replace(/\/+$/,"");let e=4320;try{e=y().port||4320}catch{}return`http://127.0.0.1:${e}`}function O(){try{return String(y().bridge?.url||"http://127.0.0.1:4319").replace(/\/+$/,"")}catch{return"http://127.0.0.1:4319"}}function J(){try{return x(y().bridge?.token||"")}catch{return x("")}}async function S(t){const e=J(),i=await fetch(O()+t,{headers:{Accept:"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}),a=await i.json().catch(()=>({}));if(!i.ok||a.ok===!1)throw new Error(a?.error||`bridge ${i.status}`);return a}const G=[{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(t=>`${t}: ${j[t].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"]}}],N={[I]:" To have one: ChatPanel › Settings › Runtime › OpenDecision › Start (or a server that provides `decide` under Models).",[L]:" To have one: ChatPanel › Settings › Runtime › Reranker › Start (or a server that provides `rerank` under Models)."};function E(){const t=f(),e=c=>[{id:"gateway",name:"the gateway",url:`${t}${c}`,where:"this device"}],i=q({providers:{decide:e("/v1/decide"),rerank:e("/v1/rerank")},fetch:(c,o)=>fetch(c,o)}),a=M({search:async c=>{const o=await l("/v1/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({q:c,limit:8,read:D.aliasRead})});return{query:c,engines:o.engines||[],results:(o.results||[]).map((n,r)=>({rank:r+1,title:n.title||n.url,url:n.url,engine:n.engine||"",text:n.read?.markdown||n.read?.text||n.snippet||""}))}}});return[i,a]}const V=E().flatMap(t=>t.specs.map(e=>({name:e.name,description:e.description,inputSchema:e.parameters})));async function K(t,e){const i=E().find(o=>o.specs.some(n=>n.name===t));if(!i)return null;const a=await i.execute(t,e);let c=typeof a=="string"?a:String(a?.text??a);return N[t]&&/^No (decision model|reranker) answered/.test(c)&&(c+=N[t]),c}function $(t,e){if(!t)return`Index: ${e} records (warm copy synced from ChatPanel).`;const i=new Date(t),a=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(i.getDate()).padStart(2,"0")} ${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}`;return`Index: ${e} records, current through ${a} (local warm copy — items newer than this may not have synced from ChatPanel yet).`}function R(){try{const t=b();return t?{Authorization:`Bearer ${t}`}:{}}catch{return{}}}async function l(t,e){let i;try{i=await fetch(f()+t,e)}catch(c){throw new Error(`the ChatPanel gateway is not running at ${f()} — start it with "chatpanel-gateway --install" (or run "chatpanel-gateway"), then retry. [${c.message}]`)}const a=await i.json().catch(()=>({}));if(!i.ok)throw new Error(a?.error?.message||`the gateway returned HTTP ${i.status} for ${t}`);return a}function g(t){if(t==null||t==="")return null;if(typeof t=="number")return t;const e=String(t).trim().toLowerCase(),i=864e5;if(e==="today")return Date.now()-i;if(e==="yesterday")return Date.now()-2*i;const a=/^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(e);if(a){const o=Number(a[1]),n=a[2][0],r=n==="d"?i:n==="w"?7*i:n==="m"?30*i:365*i;return Date.now()-o*r}const c=Date.parse(e);return Number.isNaN(c)?null:c}const v=(t,e)=>`${e+1}. [${t.id}] ${t.title||"(untitled)"} · ${t.type}${t.date?" · "+new Date(t.date).toISOString().slice(0,10):""}${t.snippet?`
|
|
4
|
-
${t.snippet}`:""}`;async function X(t,e={}){const i=await K(t,e);if(i!=null)return i;const a=await H(t,e,{gatewayJson:l});if(a!=null)return a;const c=await U(t,e,{baseUrl:f,gatewayJson:l,token:()=>{try{return b()}catch{return""}},client:()=>m,askConfig:k});if(c!=null)return c;if(t==="smart_search"){const o={question:String(e.question||""),queries:Array.isArray(e.queries)?e.queries.map(String):[],limit:Number(e.limit)||10};e.type&&(o.type=String(e.type));const n=
|
|
1
|
+
import{loadConfig as y}from"./config.js";import{VERSION as g}from"./version.js";import{readBridgeToken as x}from"./bridge.js";import{ensureGatewayToken as b}from"./gateway-token.js";import{MEMORY_KINDS as j,MEMORY_KIND_NAMES as _}from"./memory.js";import{parseBriefText as A}from"./knowledge.js";import{capabilityToolsProvider as q,DECIDE_TOOL_NAME as I,RERANK_TOOL_NAME as L}from"./capability-tools.js";import{webSearchToolProvider as M}from"./web-search-tool.js";import{SEARCH_DEFAULTS as D}from"./retrieval/search.js";import{askToolsFor as T,callAsk as U}from"./mcp-ask.js";import{CAPABILITY_TOOLS as B,callCapability as H}from"./mcp-capabilities.js";const Y="2024-11-05",F={name:"chatpanel-history",version:g},W=["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."," • redact_check — what is personal or secret in a piece of text, found by the detector on"," THIS machine. Call it before you put someone else's data into your own context, a"," commit message, an issue or a message to a third party — and whenever the user asks"," what is sensitive in something. It tells you what it could not see, so read that line."," • read_document — a URL as clean markdown through the user's own reader and cache,"," for a fraction of the context raw HTML would cost.","","ChatPanel can also hand a question to ANOTHER MODEL on this machine and give you its answer:"," • list_models — what can answer, and WHERE each one runs (on this device / a cloud)."," • ask_model — ask one. Use it for a second opinion on your own reasoning, for a model",' stronger in some domain, when the user names a model ("ask Claude what it thinks"), or'," when they want a question kept on-device — pick a `device` model and nothing leaves the"," machine. The model you ask sees your prompt and NOTHING else: no files, no shell, no web."," So paste in the code or context it needs. A slow answer returns a job id for ask_status."].join(`
|
|
2
|
+
`);async function z(){try{const t=await fetch(`${f()}/health`,{signal:AbortSignal.timeout(600)}),e=String((await t.json())?.version||"");return!e||e===g?"":["",`IMPORTANT — VERSION MISMATCH. This MCP server is ChatPanel ${g}, but the gateway`,`running on this machine is ${e}. They are different installs: your client launched`,"whichever `chatpanel-gateway` is on its PATH, and it is not the one the user is running.","The practical effect is that TOOLS MAY BE MISSING here — a newer gateway has tools this","server does not advertise. If a ChatPanel tool the user expects is not in your list, this","is why. Tell them, and tell them the fix: point the MCP config at the newer executable","(or update the older install so both are the same version)."].join(`
|
|
3
|
+
`)}catch{return""}}function k(){try{return y().mcp?.ask||{}}catch{return{}}}let m="unknown";function C(t){try{const e=b();fetch(`${f()}/v1/observability/access`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(t)}).catch(()=>{})}catch{}}function f(){const t=process.env.CHATPANEL_GATEWAY_URL;if(t)return t.replace(/\/+$/,"");let e=4320;try{e=y().port||4320}catch{}return`http://127.0.0.1:${e}`}function O(){try{return String(y().bridge?.url||"http://127.0.0.1:4319").replace(/\/+$/,"")}catch{return"http://127.0.0.1:4319"}}function J(){try{return x(y().bridge?.token||"")}catch{return x("")}}async function S(t){const e=J(),i=await fetch(O()+t,{headers:{Accept:"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}),a=await i.json().catch(()=>({}));if(!i.ok||a.ok===!1)throw new Error(a?.error||`bridge ${i.status}`);return a}const G=[{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(t=>`${t}: ${j[t].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"]}}],N={[I]:" The gateway decides in-process unless it was turned off: ChatPanel › Settings › Runtime › Decide (or the OpenDecision container, or a server that provides `decide` under Models).",[L]:" The gateway reranks in-process unless it was turned off: ChatPanel › Settings › Runtime › Rerank (or the Reranker container, or a server that provides `rerank` under Models)."};function R(){const t=f(),e=c=>[{id:"gateway",name:"the gateway",url:`${t}${c}`,where:"this device"}],i=q({providers:{decide:e("/v1/decide"),rerank:e("/v1/rerank")},fetch:(c,o)=>fetch(c,o)}),a=M({search:async c=>{const o=await l("/v1/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({q:c,limit:8,read:D.aliasRead})});return{query:c,engines:o.engines||[],results:(o.results||[]).map((n,r)=>({rank:r+1,title:n.title||n.url,url:n.url,engine:n.engine||"",text:n.read?.markdown||n.read?.text||n.snippet||""}))}}});return[i,a]}const V=R().flatMap(t=>t.specs.map(e=>({name:e.name,description:e.description,inputSchema:e.parameters})));async function K(t,e){const i=R().find(o=>o.specs.some(n=>n.name===t));if(!i)return null;const a=await i.execute(t,e);let c=typeof a=="string"?a:String(a?.text??a);return N[t]&&/^No (decision model|reranker) answered/.test(c)&&(c+=N[t]),c}function $(t,e){if(!t)return`Index: ${e} records (warm copy synced from ChatPanel).`;const i=new Date(t),a=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(i.getDate()).padStart(2,"0")} ${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}`;return`Index: ${e} records, current through ${a} (local warm copy — items newer than this may not have synced from ChatPanel yet).`}function E(){try{const t=b();return t?{Authorization:`Bearer ${t}`}:{}}catch{return{}}}async function l(t,e){let i;try{i=await fetch(f()+t,e)}catch(c){throw new Error(`the ChatPanel gateway is not running at ${f()} — start it with "chatpanel-gateway --install" (or run "chatpanel-gateway"), then retry. [${c.message}]`)}const a=await i.json().catch(()=>({}));if(!i.ok)throw new Error(a?.error?.message||`the gateway returned HTTP ${i.status} for ${t}`);return a}function w(t){if(t==null||t==="")return null;if(typeof t=="number")return t;const e=String(t).trim().toLowerCase(),i=864e5;if(e==="today")return Date.now()-i;if(e==="yesterday")return Date.now()-2*i;const a=/^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(e);if(a){const o=Number(a[1]),n=a[2][0],r=n==="d"?i:n==="w"?7*i:n==="m"?30*i:365*i;return Date.now()-o*r}const c=Date.parse(e);return Number.isNaN(c)?null:c}const v=(t,e)=>`${e+1}. [${t.id}] ${t.title||"(untitled)"} · ${t.type}${t.date?" · "+new Date(t.date).toISOString().slice(0,10):""}${t.snippet?`
|
|
4
|
+
${t.snippet}`:""}`;async function X(t,e={}){const i=await K(t,e);if(i!=null)return i;const a=await H(t,e,{gatewayJson:l});if(a!=null)return a;const c=await U(t,e,{baseUrl:f,gatewayJson:l,token:()=>{try{return b()}catch{return""}},client:()=>m,askConfig:k});if(c!=null)return c;if(t==="smart_search"){const o={question:String(e.question||""),queries:Array.isArray(e.queries)?e.queries.map(String):[],limit:Number(e.limit)||10};e.type&&(o.type=String(e.type));const n=w(e.since);n!=null&&(o.since=n);const r=w(e.before);r!=null&&(o.before=r);const s=await l("/v1/history/smart-search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),h=s.results||[],d=$(s.newest,s.size),u=(s.queries||[]).map(p=>`"${p}"`).join(", ");return h.length?[d,"",`${h.length} result(s) for "${e.question}" — searched ${s.queries.length} way(s): ${u}`,...h.map((p,P)=>`${v(p,P)}${p.foundBy?.length>1?`
|
|
5
5
|
(matched ${p.foundBy.length} of the queries)`:""}`)].join(`
|
|
6
6
|
`)+`
|
|
7
7
|
|
|
8
8
|
get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.question}".
|
|
9
9
|
Searched ${s.queries?.length||0} way(s): ${u}.
|
|
10
10
|
${d}
|
|
11
|
-
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(t==="search_history"){const o={query:String(e.query||""),limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0)};e.type&&(o.type=String(e.type));const n=
|
|
11
|
+
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(t==="search_history"){const o={query:String(e.query||""),limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0)};e.type&&(o.type=String(e.type));const n=w(e.since);n!=null&&(o.since=n);const r=w(e.before);r!=null&&(o.before=r);const s=await l("/v1/history/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),h=s.results||[],d=$(s.newest,s.size),u=[e.type&&`type=${e.type}`,e.since&&`since=${e.since}`,e.before&&`before=${e.before}`].filter(Boolean).join(", "),p=u?` (${u})`:"";return h.length?[d,"",`${h.length} result(s) for "${e.query}"${p}:`,...h.map(v)].join(`
|
|
12
12
|
`)+`
|
|
13
13
|
|
|
14
14
|
get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.query}"${p}.
|
|
@@ -25,7 +25,7 @@ get_record <id> for full text.`:`Nothing related to ${e.id} found (or that id is
|
|
|
25
25
|
`)+`
|
|
26
26
|
|
|
27
27
|
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(t==="get_brief"){const o=String(e.id||""),r=(await l(`/v1/history/get?${new URLSearchParams({id:o})}`)).record,s=A(r?.text);if(!s)return`${o} is not a brief (type ${r?.type||"unknown"}). Use get_record for it, or list_briefs for the brief ids.`;const h=[`BRIEF ${o} — ${s.name} (${s.kind})${s.aliases.length?` · also known as ${s.aliases.join(", ")}`:""}`,""];h.push(`${s.claims.length} claim(s), each with the records it cites:`);for(const d of s.claims)h.push(`• ${d.text}`),d.refs.length&&h.push(` cites: ${d.refs.map(u=>`${u.kind}:${u.id}`).join(", ")}`);return s.records.length&&h.push("",`Built from ${s.records.length} record(s) (most recent first): ${s.records.slice(0,12).map(d=>d.title).join(" · ")}${s.records.length>12?" …":""}`),h.push("","get_record <kind:id> opens a cited record; find_related <id> follows its connections."),h.join(`
|
|
28
|
-
`)}if(t==="recall"){const o=await l("/v1/memory/recall",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:String(e.text||"")})});return o.memories?.length?o.block:o.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(t==="remember"){const o=String(e.text||"").trim();if(!o)return"remember needs `text` — one short sentence about the user.";const n=await l("/v1/memory/remember",{method:"POST",headers:{"content-type":"application/json",...
|
|
28
|
+
`)}if(t==="recall"){const o=await l("/v1/memory/recall",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:String(e.text||"")})});return o.memories?.length?o.block:o.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(t==="remember"){const o=String(e.text||"").trim();if(!o)return"remember needs `text` — one short sentence about the user.";const n=await l("/v1/memory/remember",{method:"POST",headers:{"content-type":"application/json",...E()},body:JSON.stringify({text:o,kind:e.kind?String(e.kind):"fact",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:"mcp",surface:"mcp",agent:m}})});return n.action==="duplicate"?`Already known: "${n.record.text}" — nothing changed.`:n.action==="update"?`Updated memory to "${n.record.text}" (was "${n.replaced?.text}"). It applies to every future session.`:`Remembered: "${n.record.text}". It applies to every future ChatPanel session, on every model.`}if(t==="forget"){const o=String(e.query||"").trim();if(!o)return"forget needs `query` — the memory to remove.";const n=await l("/v1/memory/forget",{method:"POST",headers:{"content-type":"application/json",...E()},body:JSON.stringify({query:o})});return n.removed?.length?`Forgot: ${n.removed.map(r=>`"${r.text}"`).join(", ")}.`:`No memory matches "${o}". Call recall to see what is stored.`}if(t==="list_skills"){let o;try{o=await S("/skills")}catch(r){return`Installed skills are unavailable because the ChatPanel bridge is not running at ${O()}. Install/start it with:
|
|
29
29
|
curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash
|
|
30
30
|
Then retry. History tools work without the bridge. [${r.message}]`}const n=o.skills||[];return n.length?[`${n.length} skill(s) installed:`,...n.map(r=>`- ${r.command||r.id}: ${r.description||r.name}${r.origin?.source?` (from ${r.origin.source})`:""}`)].join(`
|
|
31
31
|
`)+`
|
package/src/ner-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import nt from"node:os";import{join as S}from"node:path";import{existsSync as z,mkdirSync as rt,readdirSync as B,readFileSync as ot}from"node:fs";import{DEFAULT_MODEL as J,isMirroredModel as st}from"./models.js";import{isLoopbackHost as it,isPrivateHost as at,isMetadataHost as lt}from"@chatpanel/pii";import{recaseForDetection as ct}from"@chatpanel/pii/pii-detect.js";import{verifyModelWeights as ut}from"./model-integrity.js";import{runtimeName as ft}from"./model-runtime.js";import{nativeOrtFailure as pt}from"./ort.js";import{makeWarmTimer as G}from"./warm-timer.js";import{makeModelFileCache as dt}from"./model-file-cache.js";const E="https://dl.chatpanel.net/models/";function mt(t=process.env){const e=t.CHATPANEL_MODEL_BASE_URL?"CHATPANEL_MODEL_BASE_URL":"registries.models",r=t.CHATPANEL_MODEL_BASE_URL||t.CHATPANEL_REGISTRY_MODELS;if(!r)return E;const o=c=>(console.warn(`[models] ignoring ${e} (${r}): ${c} — using ${E}`),E);let n;try{n=new URL(r)}catch{return o("not a valid URL")}if(n.protocol!=="http:"&&n.protocol!=="https:")return o(`scheme ${n.protocol} not allowed`);if(lt(n.hostname))return o("points at cloud metadata");const s=it(n.hostname)||at(n.hostname);return n.protocol==="http:"&&!s?o("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${n.origin} (${e}), not ${E}`),r.replace(/\/*$/,"/"))}const ht=mt();let d="off",h=null,g=null,x=null,L=null,A=null,M=null,T=null,w=null,N=0,v=null;const m=new Map;function R(){return process.env.CHATPANEL_MODELS_DIR||S(nt.homedir(),".chatpanel","models")}function C(t=h||J){const e=S(R(),...t.split("/"));return z(S(e,"onnx","model_quantized.onnx"))||z(S(e,"onnx","model.onnx"))}function Yt(){const t=R(),e=[];try{for(const r of B(t,{withFileTypes:!0}))if(r.isDirectory())for(const o of B(S(t,r.name),{withFileTypes:!0})){if(!o.isDirectory())continue;const n=`${r.name}/${o.name}`;C(n)&>(S(t,r.name,o.name))&&e.push(n)}}catch{}return e}function gt(t){try{return(JSON.parse(ot(S(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function zt(){return d}function $(){return d==="ready"&&!!g}function Bt(){return{configured:d!=="off",ok:$(),state:d,model:h,error:x,runtime:ft(),dtype:g?"q8":null,stats:kt(),companions:bt(),warmMs:w?.warmMs??null}}async function yt(t,{signal:e}={}){if(!$())return[];if(e?.aborted)return[];const r=String(t||""),o=await Q(r,e);if(!o)return[];const n=[];for(const i of o||[]){let u=String(i.word??"");const l=i.entity_group??i.entity??"ENTITY";if(u.startsWith("##")&&n.length&&n[n.length-1].type===l){n[n.length-1].value+=u.slice(2);continue}u=u.replace(/##/g,"").trim(),u&&n.push({value:u,type:l})}const s=new Set,c=[];for(const i of n){const u=vt(r,At(r,i.value.trim()));if(u.length<=1)continue;const l=`${i.type}:${u.toLowerCase()}`;s.has(l)||(s.add(l),c.push({value:u,type:i.type}))}return c}async function Q(t,e){N++;try{return await wt(t,e)}finally{N--,k()||w?.arm()}}async function wt(t,e){const r=performance.now(),o=[],n=[{text:t,key:"orig"}];if(H){const s=ct(t);s.changed&&n.push({text:s.text,key:"recased"})}for(const{model:s,pipe:c}of V())for(const i of n){let u=0;for(const l of St(i.text,c.tokenizer)){if(e?.aborted)return null;const a=i.text.indexOf(l,u),f=await c(l,{aggregation_strategy:"simple"});for(const p of f||[])o.push({...p,_win:a<0?u:a,_winText:l,_model:s,_pass:i.key,_passText:i.text});a>=0&&(u=Math.max(u,a+1))}}return $t(performance.now()-r,t.length,o.length),o}let H=!0;function Jt(t){H=t!==!1}async function Gt(t,{signal:e}={}){if(!$())return[];const r=String(t||""),o=await Q(r,e);if(!o)return[];const n=[],s=new Set;let c=-1,i=-1,u=null,l=null;for(const f of o){const p=String(f.word??"").replace(/##/g,"").trim();if(!p)continue;(f._win!==i||f._model!==u||f._pass!==l)&&(i=f._win,u=f._model,l=f._pass,c=f._win);const b=f._passText||r;let _=b.indexOf(p,c);if(_<0&&(_=b.indexOf(p,f._win)),_<0)continue;let O=_+p.length;c=O;const W=Y=>!!Y&&/[\p{L}\p{N}'’-]/u.test(Y);for(;_>0&&W(r[_-1]);)_--;for(;O<r.length&&W(r[O]);)O++;const U=String(f.entity_group??f.entity??"ENTITY"),j=`${_}:${O}:${U}`;if(s.has(j))continue;s.add(j);const q=Number(f.score);n.push({value:r.slice(_,O),type:U,start:_,end:O,score:Number.isFinite(q)?Math.max(0,Math.min(1,q)):1,model:f._model})}n.sort((f,p)=>f.start-p.start||f.end-p.end);const a=[];for(const f of n){const p=a[a.length-1];if(p&&p.type===f.type&&p.end===f.start){p.end=f.end,p.value=r.slice(p.start,p.end),p.score=Math.min(p.score,f.score);continue}a.push({...f})}return m.size||H?Mt(a):a}const K=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function _t(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function P(t){const e=K.indexOf(_t(t.type));return e<0?K.length:e}let D=[];function xt(t){D=Array.isArray(t)?t.slice():[]}function F(t){if(t.model===h)return-1;const e=D.indexOf(t.model);return e<0?D.length:e}function Mt(t){const e=[...t].sort((o,n)=>o.start-n.start||n.end-o.end),r=[];for(const o of e){const n=r[r.length-1];if(n&&o.start<n.end){const s=i=>i.end-i.start;(P(o)<P(n)||P(o)===P(n)&&(s(o)>s(n)||s(o)===s(n)&&(F(o)<F(n)||F(o)===F(n)&&o.score>n.score)))&&(r[r.length-1]=o);continue}r.push(o)}return r}function Qt(){const t=g?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const o=String(r).replace(/^[BIES]-/,"");o&&o!=="O"&&e.add(o)}return[...e]}function Kt(){const t=Number(g?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function bt(){return[...m].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function Lt(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===h)return!1;if(m.get(t)?.pipe)return!0;m.set(t,{pipe:null,state:C(t)?"loading":"downloading",error:null});try{const{pipe:n}=await I(t,{log:e,allowDownload:r});return m.set(t,{pipe:n,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(n){return m.set(t,{pipe:null,state:"error",error:n.message}),e(`[ner] companion ${t} failed to load (${n.message}) — the union runs without it`),!1}}async function Vt(t){const e=m.get(t);if(!e)return!1;m.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function V(){const t=g?[{model:h,pipe:g}]:[];for(const[e,r]of m)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const Ot=160,X=256;function St(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),n=Math.min(X,Number.isFinite(r)&&r>0?r:X)-8,s=l=>{try{return e(l).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=n)return[t];const c=[];let i=0,u=Math.max(64,Math.floor(n*3));for(;i<t.length;){let l=Math.min(t.length,i+u);if(l<t.length){const b=t.lastIndexOf(" ",l);b>i+u/2&&(l=b)}let a=t.slice(i,l);for(;s(a)>n&&a.length>32;){u=Math.max(32,Math.floor(a.length/2)),l=i+u;const b=t.lastIndexOf(" ",l);b>i+u/2&&(l=b),a=t.slice(i,l)}if(c.push(a),l>=t.length)break;const f=Math.max(i+1,l-Ot),p=t.indexOf(" ",f);i=p>0&&p<l?p+1:l}return c}const Tt=200,y=[];function $t(t,e,r){y.push({ms:t,chars:e,spans:r}),y.length>Tt&&y.shift()}function kt(){if(!y.length)return{calls:0};const t=y.map(n=>n.ms).sort((n,s)=>n-s),e=n=>t[Math.min(t.length-1,Math.floor(n*t.length))],r=y.reduce((n,s)=>n+s.chars,0),o=y.reduce((n,s)=>n+s.ms,0);return{calls:y.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(y[y.length-1].ms),charsPerSec:o>0?Math.round(r/(o/1e3)):null}}function At(t,e){if(!e||t.includes(e))return e;const r=t.toLowerCase().indexOf(e.toLowerCase());return r<0?e:t.slice(r,r+e.length)}function vt(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const o=c=>!!c&&/[\p{L}\p{N}'’-]/u.test(c);let n=r,s=r+e.length;for(;n>0&&o(t[n-1]);)n--;for(;s<t.length&&o(t[s]);)s++;return t.slice(n,s)}async function Xt(t,e={}){let r="";try{r=JSON.parse(e.body||"{}").text||""}catch{}const o=await yt(r,{signal:e.signal});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function Zt(){return M}async function Z(){if(A)return A;const t=R();try{rt(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}let r;try{r=await import("@huggingface/transformers")}catch(a){throw e?a:new Error(pt(a))}const{env:o,pipeline:n,Tensor:s,AutoModel:c,AutoProcessor:i,LogLevel:u}=r;if(o.cacheDir=t,e&&u)try{o.logLevel=u.ERROR}catch{}o.localModelPath=t,e||(o.useCustomCache=!0,o.customCache=dt(t,{remoteHost:()=>o.remoteHost}));try{o.remoteHost=ht}catch{}try{o.backends.onnx.wasm.numThreads=1}catch{}if(e)try{o.backends.onnx.wasm.proxy=!1,o.backends.onnx.wasm.wasmPaths=e}catch{}return A={env:o,pipeline:(a,f,p={})=>n(a,f,p.progress_callback&&o.allowRemoteModels===!1?{...p,progress_callback:void 0}:p),Tensor:s,AutoModel:c,AutoProcessor:i},A}async function I(t,{log:e=()=>{},allowDownload:r=!0,onProgress:o=()=>{}}={}){const n=await Z(),s=C(t);if(n.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const c=n.env.remoteHost,i=!st(t);if(!s&&i)try{n.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${i?", from Hugging Face":""})…`);try{const u=a=>{a&&(a.status==="progress"||a.status==="download"||a.status==="initiate"?o(a):a.status==="done"&&a.file&&e(`[ner] fetched ${a.file}`))};let l;try{l=await n.pipeline("token-classification",t,{dtype:"q8",progress_callback:u})}catch(a){if(s||i||!r)throw a;e(`[ner] mirror fetch failed (${String(a.message).slice(0,80)}) — retrying from Hugging Face…`),n.env.remoteHost="https://huggingface.co/",n.env.allowRemoteModels=!0,l=await n.pipeline("token-classification",t,{dtype:"q8",progress_callback:u})}if(!s)try{ut(t,{modelsDir:R(),log:e})}catch(a){try{await l.dispose?.()}catch{}throw a}return{pipe:l,haveLocal:s}}finally{try{n.env.remoteHost=c}catch{}}}async function tt(t,{log:e=()=>{},allowDownload:r=!0}={}){const o=g,n=h;try{await Z()}catch(c){return d="error",x=`engine load failed: ${c.message}`,e(`[ner] transformers.js not available (${c.message}) — deterministic-only`),!1}const s=C(t);if(!s&&!r)return d="error",x="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;d=s?"loading":"downloading",s||(M={model:t,file:null,pct:0});try{const{pipe:c}=await I(t,{log:e,allowDownload:r,onProgress:i=>{M={model:t,file:i.file||M?.file||null,pct:typeof i.progress=="number"?Math.round(i.progress):M?.pct??0}}});if(g=c,h=t,d="ready",x=null,M=null,T&&(T={...T,model:t}),o&&o!==c)try{await o.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),k()||w?.arm(),!0}catch(c){return x=c.message,M=null,o?(g=o,h=n,d="ready"):d="error",e(`[ner] model load failed (${c.message})${o?" — keeping previous model":" — deterministic-only"}`),!1}}function Et(t={}){if(L)return L;const e=typeof t.onLog=="function"?t.onLog:()=>{};T=t,h=t.model||J,d="loading";const r=t.allowDownload!==!1;return w=G({warmMs:t.warmMs,busy:k,log:e,unload:()=>et({log:e})}),L=tt(h,{log:e,allowDownload:r}).then(async o=>{const n=Array.isArray(t.union)?t.union:[];xt(n);for(const s of n)await Lt(s,{log:e,allowDownload:r});return $()&&!k()&&w?.arm(),o}),L}function k(){if(N>0||d==="loading"||d==="downloading")return!0;for(const t of m.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function et({log:t=()=>{}}={}){if(k())return!1;w?.disarm();const e=V().map(r=>r.pipe);g=null,L=null,M=null,x=null,m.clear(),d=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((w?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function It(){try{d==="idle"&&(v||T)?await(v?v():Et(T)):L&&await L}catch{}return $()}async function te(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},o=e.allowDownload!==!1;if(!t)return!1;if(t===h&&$())return!0;const n=m.get(t);if(n?.pipe){const s=g;if(g=n.pipe,h=t,d="ready",x=null,m.delete(t),s)try{await s.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),!0}return tt(t,{log:r,allowDownload:o})}function ee(){d="off",h=null,g=null,x=null,L=null,A=null,M=null,y.length=0,m.clear(),H=!0,D=[],w?.disarm(),w=null,T=null,N=0,v=null}function ne(t,e){m.set(t,{pipe:e,state:"ready",error:null})}function re(t,{model:e="test/model",warmMs:r=null,reload:o=null}={}){g=t,h=e,d="ready",x=null,y.length=0,o&&(v=o),r!==null&&(w=G({warmMs:r,busy:k,unload:()=>et()}),t&&w.arm())}export{ee as _reset,ne as _setCompanionForTest,re as _setForTest,Lt as addCompanion,bt as companions,yt as detect,Gt as detectSpans,It as ensure,Z as ensureLib,Xt as fetchAdapter,Bt as health,Et as init,$ as isReady,Qt as labels,Kt as maxTokens,C as modelOnDisk,R as modelRoot,Yt as modelsOnDisk,Zt as progress,Vt as removeCompanion,mt as resolveModelHost,Jt as setCaseRecovery,te as setModel,xt as setUnionOrder,zt as state,kt as stats,Mt as unionSpans,et as unload,St as windowsFor};
|
|
1
|
+
import nt from"node:os";import{join as O}from"node:path";import{existsSync as Y,mkdirSync as rt,readdirSync as B,readFileSync as ot}from"node:fs";import{DEFAULT_MODEL as J,isMirroredModel as st}from"./models.js";import{isLoopbackHost as it,isPrivateHost as at,isMetadataHost as lt}from"@chatpanel/pii";import{recaseForDetection as ct}from"@chatpanel/pii/pii-detect.js";import{verifyModelWeights as ut}from"./model-integrity.js";import{runtimeName as ft}from"./model-runtime.js";import{nativeOrtFailure as pt}from"./ort.js";import{makeWarmTimer as G}from"./warm-timer.js";import{makeModelFileCache as dt}from"./model-file-cache.js";const E="https://dl.chatpanel.net/models/";function mt(t=process.env){const e=t.CHATPANEL_MODEL_BASE_URL?"CHATPANEL_MODEL_BASE_URL":"registries.models",r=t.CHATPANEL_MODEL_BASE_URL||t.CHATPANEL_REGISTRY_MODELS;if(!r)return E;const o=c=>(console.warn(`[models] ignoring ${e} (${r}): ${c} — using ${E}`),E);let n;try{n=new URL(r)}catch{return o("not a valid URL")}if(n.protocol!=="http:"&&n.protocol!=="https:")return o(`scheme ${n.protocol} not allowed`);if(lt(n.hostname))return o("points at cloud metadata");const s=it(n.hostname)||at(n.hostname);return n.protocol==="http:"&&!s?o("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${n.origin} (${e}), not ${E}`),r.replace(/\/*$/,"/"))}const ht=mt();let d="off",g=null,y=null,M=null,L=null,A=null,b=null,T=null,_=null,C=0,v=null;const m=new Map;function N(){return process.env.CHATPANEL_MODELS_DIR||O(nt.homedir(),".chatpanel","models")}function R(t=g||J){const e=O(N(),...t.split("/"));return Y(O(e,"onnx","model_quantized.onnx"))||Y(O(e,"onnx","model.onnx"))}function zt(){const t=N(),e=[];try{for(const r of B(t,{withFileTypes:!0}))if(r.isDirectory())for(const o of B(O(t,r.name),{withFileTypes:!0})){if(!o.isDirectory())continue;const n=`${r.name}/${o.name}`;R(n)&>(O(t,r.name,o.name))&&e.push(n)}}catch{}return e}function gt(t){try{return(JSON.parse(ot(O(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function Yt(){return d}function $(){return d==="ready"&&!!y}function Bt(){return{configured:d!=="off",ok:$(),state:d,model:g,error:M,runtime:ft(),dtype:y?"q8":null,stats:kt(),companions:bt(),warmMs:_?.warmMs??null}}async function yt(t,{signal:e}={}){if(!$())return[];if(e?.aborted)return[];const r=String(t||""),o=await Q(r,e);if(!o)return[];const n=[];for(const i of o||[]){let u=String(i.word??"");const a=i.entity_group??i.entity??"ENTITY";if(u.startsWith("##")&&n.length&&n[n.length-1].type===a){n[n.length-1].value+=u.slice(2);continue}u=u.replace(/##/g,"").trim(),u&&n.push({value:u,type:a})}const s=new Set,c=[];for(const i of n){const u=vt(r,At(r,i.value.trim()));if(u.length<=1)continue;const a=`${i.type}:${u.toLowerCase()}`;s.has(a)||(s.add(a),c.push({value:u,type:i.type}))}return c}async function Q(t,e){C++;try{return await wt(t,e)}finally{C--,k()||_?.arm()}}async function wt(t,e){const r=performance.now(),o=[],n=[{text:t,key:"orig"}];if(H){const s=ct(t);s.changed&&n.push({text:s.text,key:"recased"})}for(const{model:s,pipe:c}of V())for(const i of n){let u=0;for(const a of Ot(i.text,c.tokenizer)){if(e?.aborted)return null;const l=i.text.indexOf(a,u),f=await c(a,{aggregation_strategy:"simple"});for(const p of f||[])o.push({...p,_win:l<0?u:l,_winText:a,_model:s,_pass:i.key,_passText:i.text});l>=0&&(u=Math.max(u,l+1))}}return $t(performance.now()-r,t.length,o.length),o}let H=!0;function Jt(t){H=t!==!1}async function Gt(t,{signal:e}={}){if(!$())return[];const r=String(t||""),o=await Q(r,e);if(!o)return[];const n=[],s=new Set;let c=-1,i=-1,u=null,a=null;for(const f of o){const p=String(f.word??"").replace(/##/g,"").trim();if(!p)continue;(f._win!==i||f._model!==u||f._pass!==a)&&(i=f._win,u=f._model,a=f._pass,c=f._win);const x=f._passText||r;let h=x.indexOf(p,c);if(h<0&&(h=x.indexOf(p,f._win)),h<0)continue;let S=h+p.length;c=S;const W=z=>!!z&&/[\p{L}\p{N}'’-]/u.test(z);for(;h>0&&W(r[h-1]);)h--;for(;S<r.length&&W(r[S]);)S++;const U=String(f.entity_group??f.entity??"ENTITY"),j=`${h}:${S}:${U}`;if(s.has(j))continue;s.add(j);const q=Number(f.score);n.push({value:r.slice(h,S),type:U,start:h,end:S,score:Number.isFinite(q)?Math.max(0,Math.min(1,q)):1,model:f._model})}n.sort((f,p)=>f.start-p.start||f.end-p.end);const l=[];for(const f of n){const p=l[l.length-1];if(p&&p.type===f.type&&p.end===f.start){p.end=f.end,p.value=r.slice(p.start,p.end),p.score=Math.min(p.score,f.score);continue}l.push({...f})}return m.size||H?Mt(l):l}const K=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function _t(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function P(t){const e=K.indexOf(_t(t.type));return e<0?K.length:e}let D=[];function xt(t){D=Array.isArray(t)?t.slice():[]}function F(t){if(t.model===g)return-1;const e=D.indexOf(t.model);return e<0?D.length:e}function Mt(t){const e=[...t].sort((o,n)=>o.start-n.start||n.end-o.end),r=[];for(const o of e){const n=r[r.length-1];if(n&&o.start<n.end){const s=i=>i.end-i.start;(P(o)<P(n)||P(o)===P(n)&&(s(o)>s(n)||s(o)===s(n)&&(F(o)<F(n)||F(o)===F(n)&&o.score>n.score)))&&(r[r.length-1]=o);continue}r.push(o)}return r}function Qt(){const t=y?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const o=String(r).replace(/^[BIES]-/,"");o&&o!=="O"&&e.add(o)}return[...e]}function Kt(){const t=Number(y?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function bt(){return[...m].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function Lt(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===g)return!1;if(m.get(t)?.pipe)return!0;m.set(t,{pipe:null,state:R(t)?"loading":"downloading",error:null});try{const{pipe:n}=await I(t,{log:e,allowDownload:r});return m.set(t,{pipe:n,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(n){return m.set(t,{pipe:null,state:"error",error:n.message}),e(`[ner] companion ${t} failed to load (${n.message}) — the union runs without it`),!1}}async function Vt(t){const e=m.get(t);if(!e)return!1;m.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function V(){const t=y?[{model:g,pipe:y}]:[];for(const[e,r]of m)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const St=160,X=256;function Ot(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),n=Math.min(X,Number.isFinite(r)&&r>0?r:X)-8,s=a=>{try{return e(a).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=n)return[t];const c=[];let i=0,u=Math.max(64,Math.floor(n*3));for(;i<t.length;){let a=Math.min(t.length,i+u);if(a<t.length){const x=t.lastIndexOf(" ",a);x>i+u/2&&(a=x)}let l=t.slice(i,a);for(;s(l)>n&&l.length>32;){u=Math.max(32,Math.floor(l.length/2)),a=i+u;const x=t.lastIndexOf(" ",a);x>i+u/2&&(a=x),l=t.slice(i,a)}if(c.push(l),a>=t.length)break;const f=Math.max(i+1,a-St),p=t.indexOf(" ",f);i=p>0&&p<a?p+1:a}return c}const Tt=200,w=[];function $t(t,e,r){w.push({ms:t,chars:e,spans:r}),w.length>Tt&&w.shift()}function kt(){if(!w.length)return{calls:0};const t=w.map(n=>n.ms).sort((n,s)=>n-s),e=n=>t[Math.min(t.length-1,Math.floor(n*t.length))],r=w.reduce((n,s)=>n+s.chars,0),o=w.reduce((n,s)=>n+s.ms,0);return{calls:w.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(w[w.length-1].ms),charsPerSec:o>0?Math.round(r/(o/1e3)):null}}function At(t,e){if(!e||t.includes(e))return e;const r=t.toLowerCase().indexOf(e.toLowerCase());return r<0?e:t.slice(r,r+e.length)}function vt(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const o=c=>!!c&&/[\p{L}\p{N}'’-]/u.test(c);let n=r,s=r+e.length;for(;n>0&&o(t[n-1]);)n--;for(;s<t.length&&o(t[s]);)s++;return t.slice(n,s)}async function Xt(t,e={}){let r="";try{r=JSON.parse(e.body||"{}").text||""}catch{}const o=await yt(r,{signal:e.signal});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function Zt(){return b}async function Z(){if(A)return A;const t=N();try{rt(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}let r;try{r=await import("@huggingface/transformers")}catch(p){throw e?p:new Error(pt(p))}const{env:o,pipeline:n,Tensor:s,AutoModel:c,AutoProcessor:i,AutoTokenizer:u,AutoModelForSequenceClassification:a,LogLevel:l}=r;if(o.cacheDir=t,e&&l)try{o.logLevel=l.ERROR}catch{}o.localModelPath=t,e||(o.useCustomCache=!0,o.customCache=dt(t,{remoteHost:()=>o.remoteHost}));try{o.remoteHost=ht}catch{}try{o.backends.onnx.wasm.numThreads=1}catch{}if(e)try{o.backends.onnx.wasm.proxy=!1,o.backends.onnx.wasm.wasmPaths=e}catch{}return A={env:o,pipeline:(p,x,h={})=>n(p,x,h.progress_callback&&o.allowRemoteModels===!1?{...h,progress_callback:void 0}:h),Tensor:s,AutoModel:c,AutoProcessor:i,AutoTokenizer:u,AutoModelForSequenceClassification:a},A}async function I(t,{log:e=()=>{},allowDownload:r=!0,onProgress:o=()=>{}}={}){const n=await Z(),s=R(t);if(n.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const c=n.env.remoteHost,i=!st(t);if(!s&&i)try{n.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${i?", from Hugging Face":""})…`);try{const u=l=>{l&&(l.status==="progress"||l.status==="download"||l.status==="initiate"?o(l):l.status==="done"&&l.file&&e(`[ner] fetched ${l.file}`))};let a;try{a=await n.pipeline("token-classification",t,{dtype:"q8",progress_callback:u})}catch(l){if(s||i||!r)throw l;e(`[ner] mirror fetch failed (${String(l.message).slice(0,80)}) — retrying from Hugging Face…`),n.env.remoteHost="https://huggingface.co/",n.env.allowRemoteModels=!0,a=await n.pipeline("token-classification",t,{dtype:"q8",progress_callback:u})}if(!s)try{ut(t,{modelsDir:N(),log:e})}catch(l){try{await a.dispose?.()}catch{}throw l}return{pipe:a,haveLocal:s}}finally{try{n.env.remoteHost=c}catch{}}}async function tt(t,{log:e=()=>{},allowDownload:r=!0}={}){const o=y,n=g;try{await Z()}catch(c){return d="error",M=`engine load failed: ${c.message}`,e(`[ner] transformers.js not available (${c.message}) — deterministic-only`),!1}const s=R(t);if(!s&&!r)return d="error",M="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;d=s?"loading":"downloading",s||(b={model:t,file:null,pct:0});try{const{pipe:c}=await I(t,{log:e,allowDownload:r,onProgress:i=>{b={model:t,file:i.file||b?.file||null,pct:typeof i.progress=="number"?Math.round(i.progress):b?.pct??0}}});if(y=c,g=t,d="ready",M=null,b=null,T&&(T={...T,model:t}),o&&o!==c)try{await o.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),k()||_?.arm(),!0}catch(c){return M=c.message,b=null,o?(y=o,g=n,d="ready"):d="error",e(`[ner] model load failed (${c.message})${o?" — keeping previous model":" — deterministic-only"}`),!1}}function Et(t={}){if(L)return L;const e=typeof t.onLog=="function"?t.onLog:()=>{};T=t,g=t.model||J,d="loading";const r=t.allowDownload!==!1;return _=G({warmMs:t.warmMs,busy:k,log:e,unload:()=>et({log:e})}),L=tt(g,{log:e,allowDownload:r}).then(async o=>{const n=Array.isArray(t.union)?t.union:[];xt(n);for(const s of n)await Lt(s,{log:e,allowDownload:r});return $()&&!k()&&_?.arm(),o}),L}function k(){if(C>0||d==="loading"||d==="downloading")return!0;for(const t of m.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function et({log:t=()=>{}}={}){if(k())return!1;_?.disarm();const e=V().map(r=>r.pipe);y=null,L=null,b=null,M=null,m.clear(),d=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((_?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function It(){try{d==="idle"&&(v||T)?await(v?v():Et(T)):L&&await L}catch{}return $()}async function te(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},o=e.allowDownload!==!1;if(!t)return!1;if(t===g&&$())return!0;const n=m.get(t);if(n?.pipe){const s=y;if(y=n.pipe,g=t,d="ready",M=null,m.delete(t),s)try{await s.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),!0}return tt(t,{log:r,allowDownload:o})}function ee(){d="off",g=null,y=null,M=null,L=null,A=null,b=null,w.length=0,m.clear(),H=!0,D=[],_?.disarm(),_=null,T=null,C=0,v=null}function ne(t,e){m.set(t,{pipe:e,state:"ready",error:null})}function re(t,{model:e="test/model",warmMs:r=null,reload:o=null}={}){y=t,g=e,d="ready",M=null,w.length=0,o&&(v=o),r!==null&&(_=G({warmMs:r,busy:k,unload:()=>et()}),t&&_.arm())}export{ee as _reset,ne as _setCompanionForTest,re as _setForTest,Lt as addCompanion,bt as companions,yt as detect,Gt as detectSpans,It as ensure,Z as ensureLib,Xt as fetchAdapter,Bt as health,Et as init,$ as isReady,Qt as labels,Kt as maxTokens,R as modelOnDisk,N as modelRoot,zt as modelsOnDisk,Zt as progress,Vt as removeCompanion,mt as resolveModelHost,Jt as setCaseRecovery,te as setModel,xt as setUnionOrder,Yt as state,kt as stats,Mt as unionSpans,et as unload,Ot as windowsFor};
|
package/src/providers.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CAPABILITIES as
|
|
1
|
+
import{CAPABILITIES as m,CAPABILITY_ROUTES as b,PROVIDER_KINDS as k}from"./capability-endpoints.js";import{listDestinations as h}from"./router.js";import{defaultEmbeddedModel as c}from"./embedded-models.js";const g=/^(localhost|127\.|\[::1\]|0\.0\.0\.0)/,v=/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|\[?fe80:|.*\.local$)/i;function l(t){if(!t)return"none";let r="";try{r=new URL(t).hostname}catch{return"internet"}return g.test(r)?"loopback":v.test(r)?"lan":"internet"}const d=t=>typeof t=="string"&&t.trim()?t.trim():null;function f(t,r){const e=t?.capabilities?.[r];if(!e||typeof e!="object")return null;const a=d(e.url);let n=k.includes(e.provider)?e.provider:null;return n||(n=e.service?"container":a?"remote":"embedded"),n==="remote"&&!/^https?:\/\//.test(a||"")?null:{kind:n,...a?{url:a}:{},...d(e.adapter)?{adapter:d(e.adapter)}:{},...d(e.model)?{model:d(e.model)}:n==="embedded"&&c(r)?{model:c(r)}:{},...d(e.service)?{service:d(e.service)}:{},...d(e.token)?{token:d(e.token)}:{},...typeof e.calibrated=="boolean"?{calibrated:e.calibrated}:{},...typeof e.redact=="boolean"?{redact:e.redact}:{},egress:n==="embedded"?"none":n==="container"?"loopback":l(a)}}function y(t,r,e={}){if(!m.includes(r))throw new Error(`providerOf: unknown capability ${r}`);const a=f(t,r);if(a)return o(r,a,e);switch(r){case"chat":{const n=h(t),s=n.filter(u=>u.type==="agent").length,i=n.filter(u=>u.type!=="agent");if(!n.length)return o(r,{kind:"none",egress:"none"},e);if(!i.length)return o(r,{kind:"harness",egress:"internet",destinations:n.length,harnesses:s},e);const p=i.some(u=>l(u.baseUrl)==="internet")?"internet":i.some(u=>l(u.baseUrl)==="lan")?"lan":"loopback";return o(r,{kind:"router",egress:p,destinations:n.length,harnesses:s,apis:i.length},e)}case"detect":{const n=t?.redaction?.detection;return n?.backend==="endpoint"&&d(n.url)?o(r,{kind:"remote",url:n.url,adapter:"detect",egress:l(n.url)},e):n?.backend&&n.backend!=="off"&&n.backend!=="endpoint"?o(r,{kind:"embedded",egress:"none",model:e.nerModel||t?.ner?.model},e):o(r,{kind:"embedded",egress:"none",model:e.nerModel||t?.ner?.model},e)}case"stt":return t?.stt?.enabled===!1?o(r,{kind:"none",egress:"none"},e):o(r,{kind:"embedded",egress:"none",model:e.sttModel||t?.stt?.model},e);case"tts":{const n=t?.tts?.provider;if(t?.tts?.enabled===!1)return o(r,{kind:"none",egress:"none"},e);if(n&&n!=="local"){const s=t?.tts?.remote||{},i=d(s.baseUrl)||(n==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1");return o(r,{kind:"remote",url:i,adapter:n,model:d(s.model)||void 0,egress:l(i),redact:s.redact!==!1},e)}return o(r,{kind:"embedded",egress:"none",model:e.ttsModel||t?.tts?.model},e)}case"search":{const n=t?.search?.provider||"auto",s=d(t?.search?.searxng?.url);return n==="searxng"||n==="auto"&&s?o(r,{kind:l(s)==="loopback"?"container":"remote",url:s,adapter:"searxng",egress:l(s)},e):o(r,{kind:"embedded",adapter:"serp",egress:"internet"},e)}case"read":{const n=t?.read?.provider||"defuddle",s=d(t?.read?.remote?.url);return n==="remote"&&s?o(r,{kind:"remote",url:s,adapter:"remote",egress:l(s)},e):o(r,{kind:"embedded",adapter:n,egress:"internet"},e)}case"extract":return o(r,{kind:"embedded",egress:"none"},e);case"rerank":case"decide":return o(r,{kind:"embedded",model:c(r),egress:"none"},e);default:return o(r,{kind:"none",egress:"none"},e)}}const w={embedded:"this device",container:"a container on this device",remote:"a server",harness:"coding agents, each at its own vendor",router:"the model router",none:"nobody yet"};function o(t,r,e){const a=r.kind==="remote"?(()=>{try{return new URL(r.url).host}catch{return r.url}})():w[r.kind],n=r.model||r.adapter||r.service||"";return{...r,label:n?`${n} — ${a}`:a,route:b[t]}}function x(t,r={}){return Object.fromEntries(m.map(e=>[e,y(t,e,r)]))}function E(t,r={}){const e=[];for(const[a,n]of Object.entries(x(t,r))){if(n.kind!=="remote"||!n.url)continue;let s=n.url;try{s=new URL(n.url).host}catch{}e.push({id:a,host:s,adapter:n.adapter||"",token:!!n.token,egress:n.egress,route:n.route})}return e}export{E as declaredProviderHosts,l as egressOf,y as providerOf,x as providerTable};
|
package/src/router.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{secureFetch as
|
|
1
|
+
import{secureFetch as j}from"./secure-fetch.js";import{readBridgeToken as k,resolveBridgeUrl as S}from"./bridge.js";import{reachOfGatewayModel as M,agentModelReach as U}from"@chatpanel/events/model-candidates.js";const C=["codex","claude","opencode","pi","kiro","antigravity"];function b(e){const o=(Array.isArray(e.destinations)?e.destinations:[]).filter(Boolean),s=new Set(o.map(t=>t.id)),i=[...o.filter(t=>t.type==="agent"),...C.filter(t=>!s.has(t)).map(t=>({id:t,type:"agent",agent:t,models:[t]})),...o.filter(t=>t.type!=="agent")];return e.backend==="api"&&!o.some(t=>t.type==="api")&&(i.push({id:"openai",type:"api",protocol:"openai",baseUrl:e.upstreams?.openai?.baseUrl,models:[]}),i.push({id:"anthropic",type:"api",protocol:"anthropic",baseUrl:e.upstreams?.anthropic?.baseUrl,models:[]})),i}function G(e,o,s,{destination:i="",down:t=()=>!1}={}){const r=b(o),c=s==="anthropic",l=a=>(c?a.protocol==="anthropic":a.protocol!=="anthropic")&&!t(a);return i?r.find(a=>a.id===i)||null:e&&r.find(a=>Array.isArray(a.models)&&a.models.includes(e))||e&&r.find(a=>a.id===e||a.agent===e)||e&&e.includes("/")&&r.find(a=>a.type==="agent"&&(a.agent===e.slice(0,e.indexOf("/"))||a.id===e.slice(0,e.indexOf("/"))))||e&&L(e,r,l)||r.find(a=>o.backend==="bridge"?a.type==="agent":a.type==="api"&&l(a))||r.find(a=>(o.backend==="bridge"?a.type==="agent":a.type==="api")&&!t(a))||r.find(a=>!t(a))||null}function O(e){return e.type==="agent"?{api:"agent",endpoints:["/v1/chat/completions"]}:e.protocol==="anthropic"?{api:"anthropic",endpoints:["/v1/messages"]}:{api:"openai",endpoints:["/v1/chat/completions","/v1/responses"]}}const T=/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0|[^/]*\.local)(:|\/|$)/i;function x(e){if(!e||e.type==="agent")return"";const o=String(e.baseUrl||"");return o?T.test(o)||e.apiKey||e.hasKey?"":`no API key is saved for ${e.id}`:"no endpoint URL is set for this provider"}function B(e){const o=[],s=new Set,i=(t,r,c)=>{if(!t||s.has(t))return;s.add(t);const l=O(c),a=x(c);o.push({id:t,object:"model",owned_by:r,...a?{configured:!1,reason:a}:{},provider:c.id,provider_type:c.type==="agent"?"agent":c.protocol==="anthropic"?"anthropic":"openai",api:l.api,endpoints:l.endpoints,reach:M({id:t,owned_by:r,provider_type:c.type==="agent"?"agent":"openai"},c)})};for(const t of b(e))if(t.type==="agent")for(const r of t.models?.length?t.models:[t.id])i(r,"chatpanel-bridge",t);else for(const r of t.models||[])i(r,t.id,t);return{object:"list",data:o}}async function K(e,o,s){const i=await S(e);if(!i||!o)return new Map;const t=k(e.bridge?.token),r=[...o.entries()].filter(([,l])=>l).map(([l])=>l),c=new Map;return await Promise.all(r.map(async l=>{try{const a=await fetch(`${i}/list-models`,{method:"POST",headers:{"content-type":"application/json",...t?{Authorization:`Bearer ${t}`}:{}},body:JSON.stringify({agent:l}),signal:AbortSignal.timeout(s)});if(!a.ok)return;const d=await a.json(),w=(Array.isArray(d?.models)?d.models:[]).map(n=>typeof n=="string"?n:n?.id||n?.name||"").map(n=>String(n).trim()).filter(Boolean);w.length&&c.set(l,w.slice(0,40))}catch{}})),c}async function N(e,o){const s=await S(e);if(!s)return null;try{const i=k(e.bridge?.token),t=await fetch(`${s}/health`,{headers:{Accept:"application/json",...i?{Authorization:`Bearer ${i}`}:{}},signal:AbortSignal.timeout(o)});if(!t.ok)return null;const r=await t.json();if(!Array.isArray(r?.agents))return null;const c=new Map(r.agents.map(l=>[l.id,!!l.available]));return c.noTools=new Set(r.agents.filter(l=>l.tools===!1).map(l=>l.id)),c}catch{return null}}const D=Number(process.env.CHATPANEL_MODELS_CACHE_MS)||6e4;let p={at:0,key:"",value:null,inflight:null};function E(e){try{return JSON.stringify([b(e).map(o=>[o.id,o.type,o.baseUrl,o.models]),e.bridge?.url||""])}catch{return String(Date.now())}}function I(){p={at:0,key:"",value:null,inflight:null}}function J(e,o){const s=String(o||"");if(!e||e.type!=="agent"||!s)return!1;const i=s.includes("/")?s.slice(0,s.indexOf("/")):s;return Array.isArray(e.models)&&e.models.includes(s)||e.id===s||e.agent===s||e.id===i||e.agent===i}function L(e,o,s){const i=(p.value?.data||[]).find(t=>t?.id===e&&t.owned_by!=="chatpanel-bridge");return i&&o.find(t=>t.id===i.owned_by&&t.type==="api"&&s(t))||null}async function W(e,o){if(!p.value)try{await P(e,o)}catch{}}async function P(e,{timeoutMs:o=4e3,fresh:s=!1,now:i=Date.now,serviceHealth:t=null}={}){const r=E(e),c=p.value&&p.key===r,l=!c||i()-p.at>D;if(c&&!s&&!l)return p.value;const a=()=>(p.inflight||(p.inflight=R(e,{timeoutMs:o,serviceHealth:t}).then(d=>(p={at:i(),key:r,value:d,inflight:null},d)).catch(d=>{throw p.inflight=null,d})),p.inflight);return c&&!s?(a().catch(()=>{}),p.value):a()}async function R(e,{timeoutMs:o=4e3,serviceHealth:s=null}={}){const i=B(e),t=new Set(i.data.map(n=>n.id)),r=s?await s():null,c=new Map(b(e).filter(n=>n.service).map(n=>[n.id,n.service])),l=n=>{if(c.get(n.owned_by)&&r){const y=r(n.owned_by);y!=="unknown"&&(n.available=y==="up");const f=typeof r.window=="function"?r.window(n.owned_by):null;f&&(n.context_window=f);const u=typeof r.card=="function"?r.card(n.owned_by):null;u&&(n.card=u)}return n};for(const n of i.data)l(n);const a=await N(e,o);if(a){i.data=i.data.filter(n=>n.owned_by!=="chatpanel-bridge"||a.get(n.id)!==!1);for(const n of i.data)n.owned_by==="chatpanel-bridge"&&(n.available=a.get(n.id)??!1,a.noTools?.has(n.id)&&(n.tools=!1))}const d=await K(e,a,o);for(const[n,h]of d){const y=i.data.find(f=>f.id===n);if(y)for(const f of h){const u=`${n}/${f}`;t.has(u)||(t.add(u),i.data.push({...y,id:u,model:f,available:!0,reach:U(f)}))}}const w=b(e).filter(n=>n.type==="api"&&n.baseUrl);return await Promise.all(w.map(async n=>{const h=new AbortController,y=setTimeout(()=>h.abort(),o);try{const f={"content-type":"application/json"};n.apiKey&&(n.protocol==="anthropic"?(f["x-api-key"]=n.apiKey,f["anthropic-version"]="2023-06-01"):f.authorization=`Bearer ${n.apiKey}`);const u=await j(`${n.baseUrl.replace(/\/$/,"")}/models`,{headers:f,signal:h.signal});if(!u.ok)return;const m=await u.json(),$=Array.isArray(m?.data)?m.data:Array.isArray(m?.models)?m.models:[];for(const v of $){const g=typeof v=="string"?v:v?.id;if(g&&!t.has(g)){t.add(g);const A=O(n),_=x(n);i.data.push(l({id:g,object:"model",owned_by:n.id,provider:n.id,provider_type:n.protocol==="anthropic"?"anthropic":"openai",api:A.api,endpoints:A.endpoints,..._?{configured:!1,reason:_}:{},reach:M({id:g,owned_by:n.id},n)}))}}}catch{}finally{clearTimeout(y)}})),i}export{J as agentOwnsModel,B as aggregateModels,P as aggregateModelsAsync,W as ensureModelCatalog,b as listDestinations,I as resetModelsCache,G as resolveDestination};
|