@chatpanel/gateway 0.155.0 → 0.158.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/contexts-api.js +1 -1
- package/src/egress.js +2 -2
- package/src/gateway-events.js +1 -0
- package/src/link-activity.js +2 -2
- package/src/mcp.js +19 -19
- package/src/principals.js +3 -0
- package/src/server.js +32 -32
- 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.158.0",
|
|
4
4
|
"description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
26
26
|
"@chatpanel/bridge": "^0.52.0",
|
|
27
|
-
"@chatpanel/events": "^0.
|
|
27
|
+
"@chatpanel/events": "^0.509.0",
|
|
28
28
|
"@chatpanel/pii": "^0.15.6",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
package/src/contexts-api.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{makeContext as
|
|
1
|
+
import{makeContext as F,editContext as P,addToContext as W,removeFromContext as Z,contextIndex as D,contextMembers as _,suggestContexts as H,contextScope as K,addRefs as Q,removeRefs as V,setPeople as Y,parseRef as X,CONTEXT_COLORS as p,CONTEXT_NO_ACCESS as U,CONTEXT_ROLES as z,MAX_CONTEXT_INSTRUCTIONS as G}from"@chatpanel/events/contexts.js";import{contextAllows as J,contextFor as q}from"@chatpanel/events/context-access.js";import{toSearchRecord as tt}from"@chatpanel/events/library.js";import{randomUUID as et}from"node:crypto";const nt=/^context:[A-Za-z0-9_-]{1,80}$/,L=/^(chat|note|meeting|brief):[^\s]{1,200}$/,x=Object.freeze({kind:"owner"});class N extends Error{constructor(c,h){super(h),this.status=c}}function it({store:s,notify:c=()=>{},host:h="gateway",now:i=()=>Date.now(),newId:E=()=>et().replace(/-/g,"").slice(0,20),upstreamOk:k=()=>!1,audit:l=()=>{}}={}){const y=()=>s.ofKind("context").filter(t=>!t.deletedAt),S=t=>s.heads(t),u=(t,e=null,n=x)=>{const o=q(n,t,{upstreamOk:r=>k(r,n)});return o?{id:t.id,title:t.title,color:t.body?.color||p[0],about:t.body?.about||"",keywords:t.body?.keywords||[],...e?{counts:e.counts,last:e.last}:{},updatedAt:t.updatedAt,instructions:o.instructions,refs:o.refs,mcp_servers:o.mcp_servers,skills:o.skills,...o.access?{access:o.access}:{}}:null},d=(t,e,n)=>J(t,e,n),f=t=>{const e=s.write([t],{host:h,at:i()});return e.written.length&&c({ids:e.written}),s.get(t.id)||t},m=t=>{if(!nt.test(String(t||"")))return null;const e=s.get(t);return e&&!e.deletedAt?e:null},$=t=>t?.kind==="agent"?{kind:"agent",id:String(t.name||"unknown")}:{kind:"user",id:t?.kind==="person"?String(t.id):t?.kind==="owner"?"owner":"unknown"},C=(t,e,n,o,r)=>(l("access.denied",{resource:String(e||"context:?").slice(0,120),action:n,actor:$(t)}),new N(o,r)),j=(t,e,n)=>l("access.changed",{resource:e.id,actor:$(t),fields:n}),O=(t,e,n)=>{const o=m(e);if(!o)throw new N(404,"no such context");if(!d(t,o,"list"))throw C(t,e,n,404,"no such context");if(!d(t,o,n))throw C(t,e,n,403,`contexts: ${n} needs a role this caller does not have`);return o},R=t=>L.test(t),M=t=>(Array.isArray(t)?t:[]).slice(0,500);return{list(t=x){const e=y().filter(o=>d(t,o,"list")),n=[...new Set(e.flatMap(o=>_(o)))];return D(e,S(n)).map(o=>u(o.context,o,t)).filter(Boolean)},create(t={},e=x){if(e?.kind!=="owner")throw C(e,"context:new","create",403,"contexts: only the owner makes one here");B(t);const n=P(F({name:t.name,color:t.color,about:t.about,keywords:t.keywords,newId:E,now:i()}),ot(t),{now:i()});return u(f(n),null,e)},get(t,e=x){const n=O(e,t,"list");if(!d(e,n,"read"))return{context:u(n,null,e),items:[]};const[o]=D([n],S(_(n)));return{context:u(n,o,e),items:(o?.items||[]).map(r=>({id:r.id,kind:r.kind,title:r.title,updatedAt:r.updatedAt}))}},edit(t,e={},n=x){B(e);const o=e.agents!==void 0||e.noAccess!==void 0,r=O(n,t,o?"manage":"edit"),a=u(f(P(r,e,{now:i()})),null,n);return o&&j(n,r,["agents","noAccess"].filter(A=>e[A]!==void 0)),a},remove(t,e=x){const n=O(e,t,"manage"),o=i();return f({id:n.id,kind:"context",title:n.title,updatedAt:Math.max(o,Number(n.updatedAt)||0),deletedAt:Math.max(o,(Number(n.updatedAt)||0)+1)}),!0},items(t,{add:e=[],remove:n=[]}={},o=x){return this.resources(t,{add:M(e).map(String).filter(R),remove:M(n).map(String).filter(R)},o)},resources(t,{add:e=[],remove:n=[]}={},o=x){let r=O(o,t,"edit");const a=i(),A=w=>{const T=[],I=[];for(const b of M(w))typeof b=="string"&&R(b)?T.push(b):(typeof b=="string"?X(b):b&&X(`${b.type}:${b.id}`))&&I.push(b);return{members:T,refs:I}},g=A(e),v=A(n);return g.members.length&&(r=W(r,g.members,{now:a})),v.members.length&&(r=Z(r,v.members,{now:a})),g.refs.length&&(r=Q(r,g.refs,{now:a})),v.refs.length&&(r=V(r,v.refs,{now:a})),u(f(r),null,o)},people(t,e={},n=x){const o=O(n,t,"manage"),r={};for(const[A,g]of Object.entries(e&&typeof e=="object"?e:{})){if(g!==null&&!z.includes(g))throw new Error(`a role is ${z.join(", ")} or null`);r[A]=g}const a=u(f(Y(o,r,{now:i()})),null,n);return Object.keys(r).length&&j(n,o,["people"]),a},suggest({id:t="",title:e="",text:n="",limit:o=3}={},r=x){let a=String(e||""),A=String(n||"");if(t&&L.test(String(t))){const w=s.get(t),T=w?tt(w):null;a=a||w?.title||"",A=A||T?.text||""}const g=y().filter(w=>d(r,w,"edit")),v=S([...new Set(g.flatMap(w=>_(w)))]);return H({title:a,text:A,contexts:g,records:v,limit:Math.min(8,Math.max(1,Number(o)||3))}).filter(w=>!(t&&g.find(T=>T.id===w.id)?.body?.members?.[t]?.on))},scope(t,e=x){const n=O(e,t,"use");return K(n,S(_(n)))}}}function B(s={}){if(s.instructions!==void 0&&(typeof s.instructions!="string"||s.instructions.length>G))throw new Error(`instructions are a string of at most ${G} characters`);for(const c of["mcp_servers","skills","agents"])if(s[c]!==void 0&&s[c]!==null&&!(Array.isArray(s[c])&&s[c].every(h=>typeof h=="string")))throw new Error(`${c} is a list of names, or null for every one`);if(s.noAccess!==void 0&&!U.includes(s.noAccess))throw new Error(`noAccess is ${U.join(" or ")}`)}const ot=s=>Object.fromEntries(["instructions","mcp_servers","skills","noAccess","agents"].filter(c=>s[c]!==void 0).map(c=>[c,s[c]]));async function dt(s,c,{pathname:h,api:i,readJson:E,sendJson:k,principal:l=x}){if(!h.startsWith("/v1/contexts"))return!1;const y=(u,d,f="invalid_request_error")=>k(c,u,{error:{message:d,type:f}}),S=u=>{const d=u();return d?k(c,200,{ok:!0,context:d}):y(404,"no such context","not_found")};try{if(h==="/v1/contexts"&&s.method==="GET")return k(c,200,{ok:!0,contexts:i.list(l)}),!0;if(h==="/v1/contexts"&&s.method==="POST"){const m=await E(s);return String(m?.name||"").trim()?(k(c,200,{ok:!0,context:i.create(m,l)}),!0):(y(400,"a context needs a name"),!0)}if(h==="/v1/contexts/suggest"&&s.method==="POST")return k(c,200,{ok:!0,suggestions:i.suggest(await E(s),l)}),!0;const u=/^\/v1\/contexts\/(context:[A-Za-z0-9_-]{1,80})(\/items|\/scope|\/resources|\/people)?$/.exec(decodeURIComponent(h));if(!u)return y(404,"no such contexts route","not_found"),!0;const[,d,f]=u;if(!f&&s.method==="GET")return k(c,200,{ok:!0,...i.get(d,l)}),!0;if(!f&&s.method==="PATCH"){const m=await E(s);return S(()=>i.edit(d,m,l)),!0}if(!f&&s.method==="DELETE")return i.remove(d,l),k(c,200,{ok:!0}),!0;if(f==="/items"&&s.method==="POST"){const m=await E(s);return S(()=>i.items(d,m,l)),!0}if(f==="/resources"&&s.method==="POST"){const m=await E(s);return S(()=>i.resources(d,m,l)),!0}if(f==="/people"&&s.method==="POST"){const m=await E(s);return S(()=>i.people(d,m,l)),!0}return f==="/scope"&&s.method==="GET"?(k(c,200,{ok:!0,...i.scope(d,l)}),!0):(y(405,"method not allowed","method_not_allowed"),!0)}catch(u){return u instanceof N?(y(u.status,u.message,u.status===404?"not_found":"forbidden"),!0):(y(400,`contexts: ${u.message}`),!0)}}export{N as ContextDenied,it as createContextsApi,dt as handleContexts};
|
package/src/egress.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{confinedLine as $}from"./confine.js";import{capabilityList as S}from"./capability-config.js";import{searchEngines as E}from"./retrieval/search-apis.js";import{linkPaths as L}from"@chatpanel/events/link-routes.js";import{isBlockedHost as g}from"@chatpanel/pii";const x=()=>new Date().toISOString();function y(t){try{const a=typeof t=="string"?new URL(t):t instanceof URL?t:new URL(t?.url),n=a.protocol.replace(":","");return{host:a.hostname,port:a.port||{https:"443",wss:"443",http:"80",ws:"80"}[n]||"",scheme:n}}catch{return null}}const w=t=>{const a=String(t||"").toLowerCase();return a==="localhost"||a.endsWith(".localhost")||a==="::1"||a==="[::1]"?!0:g(a,{allowLoopback:!1,allowPrivate:!1})&&!g(a,{allowLoopback:!0,allowPrivate:!0})};function A({clock:t=x}={}){const a=new Map;return{record(n){const r=y(n);if(!r||!r.host)return;const p=`${r.scheme}://${r.host}:${r.port}`,o=t(),u=a.get(p);if(u){u.count+=1,u.lastAt=o;return}a.set(p,{host:r.host,port:r.port,scheme:r.scheme,local:w(r.host),count:1,firstAt:o,lastAt:o})},snapshot(){return[...a.values()].sort((n,r)=>n.local===r.local?r.count-n.count:n.local?1:-1)},reset(){a.clear()}}}let b=null;function N(t=globalThis,{allow:a=null}={}){if(t.__chatpanelEgress)return a&&t.__chatpanelEgress.setGate(a),t.__chatpanelEgress;const n=A();let r=a;n.setGate=c=>{r=c},n.blocked=[];const p=c=>{let i=null;try{i=y(c),n.record(c)}catch{}if(!r||!i?.host)return null;let l=!0;try{l=r(`${i.scheme}://${i.host}:${i.port}`,{local:w(i.host)})}catch{l=!0}if(l)return null;const s=`${i.host}:${i.port}`;n.blocked.includes(s)||n.blocked.push(s);const e=new Error(`egress to ${i.host} is blocked by your organisation’s policy`);return e.code="EGRESS_POLICY",e},o=t.fetch;typeof o=="function"&&(t.fetch=function(i,l){const s=p(i);return s?Promise.reject(s):o.call(this,i,l)});const u=t.WebSocket;return typeof u=="function"&&(t.WebSocket=new Proxy(u,{construct(c,i,l){const s=p(i[0]);if(s)throw s;return Reflect.construct(c,i,l)}})),t.__chatpanelEgress=n,t===globalThis&&(b=n),n}function P(){return b||(globalThis.__chatpanelEgress??null)}function m(t){try{return new URL(t).host}catch{return String(t||"")}}function R(t={},a=process.env,n=process.platform,r=process.arch){const p=[],o=(e,d,{when:h="always",off:f=null,local:v=!1,data:k=""}={})=>{e&&p.push({host:e,purpose:d,when:h,off:f,local:v,data:k})};o("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),o("huggingface.co","model weights (NER, dictation, read-aloud, translation, meetings) — ChatPanel’s pinned copies in huggingface.co/ChatPanel, or the upstream repo",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id and file being downloaded"}),o("dl.chatpanel.net","model weights only when Hugging Face is failing (an outage or a network that blocks it), and the installer",{when:"a model download Hugging Face could not serve",off:"the same switches as huggingface.co",data:"the model id being downloaded"}),t.runtime?.services?.llama?.build!=="system"&&(o("api.github.com","llama.cpp for the Runtime: which files Unsloth’s release has, and their SHA-256",{when:"Start, Install or Update of llama.cpp when its build is not here yet",off:'runtime.services.llama.build = "system" — the llama-server on PATH (Homebrew’s, or your own)',data:"nothing — a read of the release (github.com/unslothai/llama.cpp)"}),o("github.com","llama.cpp for the Runtime: Unsloth’s prebuilt llama-server for this machine (~13 MB on a Mac)",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"}),o("release-assets.githubusercontent.com","where github.com redirects that download — GitHub’s own file host",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"})),o("raw.githubusercontent.com","the meeting echo canceller's weights (DTLN-aec, ~7 MB, pinned commit and hashes) — only when ChatPanel’s copy on Hugging Face cannot be reached",{when:"the first meeting captured with both the microphone and what is playing",off:"stt.aec = false, or the same switches as dl.chatpanel.net",data:"the file path being downloaded"}),a.CHATPANEL_ORT_DIR||o("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),n==="darwin"&&r==="arm64"&&o("registry.npmjs.org","the Apple on-device helper, for an install that came without it (the standalone binary)",{when:"Install on the Apple on-device row, `--install` or `--fetch-apple-helper` — never when the helper is already here",off:"do not run them; the npm package and the desktop app carry the helper and never fetch it",data:"nothing — this gateway version's package and its checksum"});const u=t.link?.enabled===!1?null:L(t.link||{}).relay;if(u){const e=new URL(u).host;o(e,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone or a partner server is paired (Settings › Link your phone, `chatpanel-gateway link pair`), and while pairing",off:"link.enabled = false, or remove every paired device",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}o("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const c=t.search?.searxng?.url||"";if(c){let e=c;try{e=new URL(c).host}catch{}o(e,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(e)})}if(t.search?.provider!=="searxng"){o("www.startpage.com","web search: the built-in results-page search, one of three engines",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),o("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),o("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const e of E(t).filter(d=>d.kind==="api"&&d.enabled!==!1))o(e.api.host,`web search: ${e.api.name} (search API${e.api.needsKey?", with the key you gave it":", no key"})`,{when:"the same as www.startpage.com — one engine per search, a keyed API asked first",off:`search.apis: [{ id: "${e.api.id}", enabled: false }]`,data:"the same query"})}for(const e of Array.isArray(t.context?.providers)?t.context.providers:[]){if(!e||e.enabled===!1)continue;const d=`context.providers: [{ id: "${e.id}", enabled: false }] (Settings › Knowledge › Sources)`;if(e.kind==="bedrock"&&e.region)o(`bedrock-agent-runtime.${e.region}.amazonaws.com`,`knowledge: your AWS Bedrock knowledge base "${e.name||e.id}" (Retrieve)`,{when:"a context search names it (bedrock:"+e.id+") — from a client holding the gateway token",off:d,data:"the search query with emails, cards, keys and dictionary terms removed; signed with the AWS keys you gave it"});else if(e.kind==="gateway"&&e.url){let h=e.url;try{h=new URL(e.url).host}catch{}o(h,`knowledge: the ChatPanel gateway "${e.name||e.id}" you configured (its /v1/context and /v1/kb)`,{when:"a context search names it (gw:"+e.id+"), and the knowledge library lists its bases",off:d,data:e.trusted?"the search query AS TYPED — you marked this gateway as your own (trusted)":"the search query with emails, cards, keys and dictionary terms removed; the token you gave it",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(h)})}else if(e.kind==="bucket"&&e.endpoint){let h=e.endpoint;try{const f=new URL(e.endpoint);h=e.addressing==="virtual"?`${e.bucket}.${f.host}`:f.host}catch{}o(h,`knowledge: the team base "${e.name||e.id}" kept in your ${e.provider||"S3-compatible"} bucket ${e.bucket}/${e.prefix||""}`,{when:e.role==="builder"?`every ${e.pollMinutes||5} min: list the documents, read the new and changed ones, publish the index`:`every ${e.pollMinutes||5} min: is a newer index published? then fetch only what changed`,off:d,data:`${e.role==="builder"?"the index of the documents in that bucket (passages, vectors, the report), written back beside them":"nothing of yours — reads of the published index"}; ${e.credentials?.profile?`signed with your ${e.credentials.from==="oci"?"OCI config":"shared credentials"} profile "${e.credentials.profile}" (read from the file at each call)`:"the keys you gave it"}`,local:/^(localhost|127\.|\[::1\])/.test(h)})}}if(t.read?.remote?.url){let e=t.read.remote.url;try{e=new URL(t.read.remote.url).host}catch{}o(e,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(e)})}const i={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions (ElevenLabs: /speech-to-text)",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[e,d]of Object.entries(i))for(const h of S(t.capabilities?.[e],e,{destinations:t.destinations||[]}).providers){if(!h?.url||h.provider==="embedded")continue;let f=h.url;try{f=new URL(h.url).host}catch{}o(f,`${d.what}${h.service?` (the ${h.service} container, started under Settings › Runtime)`:` (${h.adapter} at the address you configured)`}`,{when:`a client calls /v1/${e}`,off:h.service?`stop the ${h.service} service under Settings › Runtime`:`capabilities.${e} = null`,data:`${d.data}${h.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(f)})}a.CHATPANEL_SELF_UPDATE!=="off"&&(o("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),o("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[e,d]of Object.entries(t.upstreams||{}))d?.baseUrl&&o(m(d.baseUrl),`model upstream "${e}" — chat requests (after redaction) go here`,{when:`a request addressed to ${e}`,off:`upstreams.${e}.baseUrl`,local:w(m(d.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const e of t.destinations||[])e?.baseUrl&&o(m(e.baseUrl),`destination "${e.id||e.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${e.id||"it"}`,off:"destinations[]",local:w(m(e.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});o("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),t.ner?.url&&o(m(t.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:w(m(t.ner.url).split(":")[0]),data:"the text being redacted"});const l=t.tts||{};if(l.provider==="openai"||l.provider==="elevenlabs"){const e=l.remote?.baseUrl?m(l.remote.baseUrl):l.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(e,`remote read-aloud voice (${l.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:l.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}n==="darwin"&&t.runtime?.heatwatch!==!1&&o("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const s=t.bridge?.url||"http://127.0.0.1:4319";return o(m(s),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),p}function O(t,{ledger:a=P(),version:n="",startedAt:r=null,env:p=process.env,managed:o=null,certificates:u=null,linkPartners:c=null,confined:i=null}={}){const l=R(t,p);for(const s of c||[])!s.host||s.route!=="link"&&s.route!=="relay"||l.some(e=>e.host===s.host)||l.push({host:s.host,purpose:`ChatPanel Link: the relay partner "${s.partner?.name||s.name}" reaches this gateway through`,when:"while that partner device is paired",off:`remove it: chatpanel-gateway link revoke ${s.id}`,data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"});return{ok:!0,version:n,since:r?new Date(r).toISOString():null,...u?{certificates:u}:{},...i?{confined:i}:{},...o?{managed:o,blocked:a?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:a?a.snapshot():[],declared:l,...c?{link:{partners:c.map(s=>({id:s.id,partner:s.partner?.name||s.name,scopes:s.scopes||[],route:s.route||null,host:s.host||null,...s.folder?{folder:s.folder}:{},pairedAt:s.pairedAt||null,lastSeen:s.lastSeen||null,online:!!s.online}))}}:{}}}function _(t){const a=[];a.push(`ChatPanel Gateway ${t.version||""} — egress audit`.trim()),t.since&&a.push(`observed since ${t.since}`),a.push(""),a.push("OBSERVED — hosts this process has actually contacted"),t.observed?.length||a.push(" (none yet)");for(const n of t.observed||[])a.push(` ${n.local?"[local] ":""}${n.scheme}://${n.host}:${n.port} ×${n.count} last ${n.lastAt}`);a.push(""),a.push("DECLARED — hosts this configuration allows, and why");for(const n of t.declared||[])a.push(` ${n.local?"[local] ":""}${n.host}`),a.push(` ${n.purpose}`),a.push(` when: ${n.when}${n.off?` · off: ${n.off}`:""}`),n.data&&a.push(` sends: ${n.data}`);if(t.certificates){const n=t.certificates;a.push(""),a.push("CERTIFICATES — whose word is taken that a server is who it says"),a.push(n.on?` the runtime's own list, and this computer's (${n.added} added) — what a company proxy that re-signs HTTPS needs; checks stay on`:` the runtime's own list only${n.why?` — ${n.why}`:""}`),a.push(" off: tls.systemCa: false in the config, or CHATPANEL_SYSTEM_CA=off, then restart")}if(t.confined&&(a.push(""),a.push("CONFINEMENT — what this process itself can reach on this computer"),a.push(` ${$(t.confined)}`),t.confined.on&&a.push(" checked at start: home folder listed "+(t.confined.homeListed?"YES":"no")+" · home folder written "+(t.confined.homeWritten?"YES":"no")+" · sandbox runtime written "+(t.confined.fenceWritten?"YES":"no")+" · own folder written "+(t.confined.stateWritten?"yes":"NO"))),t.link){a.push(""),a.push("LINK PARTNERS — servers the owner paired to reach this gateway over ChatPanel Link"),t.link.partners?.length||a.push(" (none — no partner can reach this gateway until you pair one)");for(const n of t.link.partners||[]){const r=n.lastSeen?new Date(n.lastSeen).toISOString():"never";a.push(` partner:${n.partner} scopes: ${n.scopes.join(", ")||"none"} agents: ${n.scopes.includes("agents")?"yes":"no"}`),a.push(` route: ${n.route||"?"}${n.host?` via ${n.host}`:""} · last seen ${r}${n.online?" (online)":""}`),n.scopes.includes("agents")&&a.push(` agents run as yours do (your Coding Agents settings and sandbox), in ${n.folder||"its folder"}; it never answers their approval prompts`),a.push(` revoke: chatpanel-gateway link revoke ${n.id}`)}}return t.managed&&(a.push(""),a.push(`POLICY — ${t.managed.name||t.managed.org||"managed"} (${t.managed.signed?"signed":"unsigned file"}, hash ${String(t.managed.policyHash||"").slice(0,12)}…)`),a.push(` enforcing: ${Object.entries(t.managed.enforces||{}).filter(([,n])=>n).map(([n,r])=>r===!0?n:`${n}=${r}`).join(", ")||"nothing yet"}`),a.push(` refused this session: ${t.blocked?.length?t.blocked.join(", "):"none"}`)),a.push(""),a.push(`Scope: ${t.scope}`),a.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),a.join(`
|
|
2
|
-
`)}export{
|
|
1
|
+
import{confinedLine as $}from"./confine.js";import{capabilityList as S}from"./capability-config.js";import{searchEngines as E}from"./retrieval/search-apis.js";import{linkPaths as x}from"@chatpanel/events/link-routes.js";import{isBlockedHost as g}from"@chatpanel/pii";const A=()=>new Date().toISOString();function y(t){try{const a=typeof t=="string"?new URL(t):t instanceof URL?t:new URL(t?.url),n=a.protocol.replace(":","");return{host:a.hostname,port:a.port||{https:"443",wss:"443",http:"80",ws:"80"}[n]||"",scheme:n}}catch{return null}}const m=t=>{const a=String(t||"").toLowerCase();return a==="localhost"||a.endsWith(".localhost")||a==="::1"||a==="[::1]"?!0:g(a,{allowLoopback:!1,allowPrivate:!1})&&!g(a,{allowLoopback:!0,allowPrivate:!0})};function L({clock:t=A}={}){const a=new Map;return{record(n){const s=y(n);if(!s||!s.host)return;const p=`${s.scheme}://${s.host}:${s.port}`,o=t(),u=a.get(p);if(u){u.count+=1,u.lastAt=o;return}a.set(p,{host:s.host,port:s.port,scheme:s.scheme,local:m(s.host),count:1,firstAt:o,lastAt:o})},snapshot(){return[...a.values()].sort((n,s)=>n.local===s.local?s.count-n.count:n.local?1:-1)},reset(){a.clear()}}}let b=null;function q(t=globalThis,{allow:a=null}={}){if(t.__chatpanelEgress)return a&&t.__chatpanelEgress.setGate(a),t.__chatpanelEgress;const n=L();let s=a;n.setGate=c=>{s=c},n.blocked=[];const p=c=>{let r=null;try{r=y(c),n.record(c)}catch{}if(!s||!r?.host)return null;let h=!0;try{h=s(`${r.scheme}://${r.host}:${r.port}`,{local:m(r.host)})}catch{h=!0}if(h)return null;const d=`${r.host}:${r.port}`;n.blocked.includes(d)||n.blocked.push(d);const e=new Error(`egress to ${r.host} is blocked by your organisation’s policy`);return e.code="EGRESS_POLICY",e},o=t.fetch;typeof o=="function"&&(t.fetch=function(r,h){const d=p(r);return d?Promise.reject(d):o.call(this,r,h)});const u=t.WebSocket;return typeof u=="function"&&(t.WebSocket=new Proxy(u,{construct(c,r,h){const d=p(r[0]);if(d)throw d;return Reflect.construct(c,r,h)}})),t.__chatpanelEgress=n,t===globalThis&&(b=n),n}function P(){return b||(globalThis.__chatpanelEgress??null)}function w(t){try{return new URL(t).host}catch{return String(t||"")}}function R(t={},a=process.env,n=process.platform,s=process.arch){const p=[],o=(e,l,{when:i="always",off:f=null,local:k=!1,data:v=""}={})=>{e&&p.push({host:e,purpose:l,when:i,off:f,local:k,data:v})};o("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),o("huggingface.co","model weights (NER, dictation, read-aloud, translation, meetings) — ChatPanel’s pinned copies in huggingface.co/ChatPanel, or the upstream repo",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id and file being downloaded"}),o("dl.chatpanel.net","model weights only when Hugging Face is failing (an outage or a network that blocks it), and the installer",{when:"a model download Hugging Face could not serve",off:"the same switches as huggingface.co",data:"the model id being downloaded"}),t.runtime?.services?.llama?.build!=="system"&&(o("api.github.com","llama.cpp for the Runtime: which files Unsloth’s release has, and their SHA-256",{when:"Start, Install or Update of llama.cpp when its build is not here yet",off:'runtime.services.llama.build = "system" — the llama-server on PATH (Homebrew’s, or your own)',data:"nothing — a read of the release (github.com/unslothai/llama.cpp)"}),o("github.com","llama.cpp for the Runtime: Unsloth’s prebuilt llama-server for this machine (~13 MB on a Mac)",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"}),o("release-assets.githubusercontent.com","where github.com redirects that download — GitHub’s own file host",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"})),o("raw.githubusercontent.com","the meeting echo canceller's weights (DTLN-aec, ~7 MB, pinned commit and hashes) — only when ChatPanel’s copy on Hugging Face cannot be reached",{when:"the first meeting captured with both the microphone and what is playing",off:"stt.aec = false, or the same switches as dl.chatpanel.net",data:"the file path being downloaded"}),a.CHATPANEL_ORT_DIR||o("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),n==="darwin"&&s==="arm64"&&o("registry.npmjs.org","the Apple on-device helper, for an install that came without it (the standalone binary)",{when:"Install on the Apple on-device row, `--install` or `--fetch-apple-helper` — never when the helper is already here",off:"do not run them; the npm package and the desktop app carry the helper and never fetch it",data:"nothing — this gateway version's package and its checksum"});const u=t.link?.enabled===!1?null:x(t.link||{}).relay;if(u){const e=new URL(u).host;o(e,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone or a partner server is paired (Settings › Link your phone, `chatpanel-gateway link pair`), and while pairing",off:"link.enabled = false, or remove every paired device",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}o("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const c=t.search?.searxng?.url||"";if(c){let e=c;try{e=new URL(c).host}catch{}o(e,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(e)})}if(t.search?.provider!=="searxng"){o("www.startpage.com","web search: the built-in results-page search, one of three engines",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),o("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),o("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const e of E(t).filter(l=>l.kind==="api"&&l.enabled!==!1))o(e.api.host,`web search: ${e.api.name} (search API${e.api.needsKey?", with the key you gave it":", no key"})`,{when:"the same as www.startpage.com — one engine per search, a keyed API asked first",off:`search.apis: [{ id: "${e.api.id}", enabled: false }]`,data:"the same query"})}for(const e of Array.isArray(t.context?.providers)?t.context.providers:[]){if(!e||e.enabled===!1)continue;const l=`context.providers: [{ id: "${e.id}", enabled: false }] (Settings › Knowledge › Sources)`;if(e.kind==="bedrock"&&e.region)o(`bedrock-agent-runtime.${e.region}.amazonaws.com`,`knowledge: your AWS Bedrock knowledge base "${e.name||e.id}" (Retrieve)`,{when:"a context search names it (bedrock:"+e.id+") — from a client holding the gateway token",off:l,data:"the search query with emails, cards, keys and dictionary terms removed; signed with the AWS keys you gave it"});else if(e.kind==="gateway"&&e.url){let i=e.url;try{i=new URL(e.url).host}catch{}o(i,`knowledge: the ChatPanel gateway "${e.name||e.id}" you configured (its /v1/context and /v1/kb)`,{when:"a context search names it (gw:"+e.id+"), and the knowledge library lists its bases",off:l,data:e.trusted?"the search query AS TYPED — you marked this gateway as your own (trusted)":"the search query with emails, cards, keys and dictionary terms removed; the token you gave it",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(i)})}else if(e.kind==="bucket"&&e.endpoint){let i=e.endpoint;try{const f=new URL(e.endpoint);i=e.addressing==="virtual"?`${e.bucket}.${f.host}`:f.host}catch{}o(i,`knowledge: the team base "${e.name||e.id}" kept in your ${e.provider||"S3-compatible"} bucket ${e.bucket}/${e.prefix||""}`,{when:e.role==="builder"?`every ${e.pollMinutes||5} min: list the documents, read the new and changed ones, publish the index`:`every ${e.pollMinutes||5} min: is a newer index published? then fetch only what changed`,off:l,data:`${e.role==="builder"?"the index of the documents in that bucket (passages, vectors, the report), written back beside them":"nothing of yours — reads of the published index"}; ${e.credentials?.profile?`signed with your ${e.credentials.from==="oci"?"OCI config":"shared credentials"} profile "${e.credentials.profile}" (read from the file at each call)`:"the keys you gave it"}`,local:/^(localhost|127\.|\[::1\])/.test(i)})}}if(t.read?.remote?.url){let e=t.read.remote.url;try{e=new URL(t.read.remote.url).host}catch{}o(e,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(e)})}const r={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions (ElevenLabs: /speech-to-text)",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[e,l]of Object.entries(r))for(const i of S(t.capabilities?.[e],e,{destinations:t.destinations||[]}).providers){if(!i?.url||i.provider==="embedded")continue;let f=i.url;try{f=new URL(i.url).host}catch{}o(f,`${l.what}${i.service?` (the ${i.service} container, started under Settings › Runtime)`:` (${i.adapter} at the address you configured)`}`,{when:`a client calls /v1/${e}`,off:i.service?`stop the ${i.service} service under Settings › Runtime`:`capabilities.${e} = null`,data:`${l.data}${i.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(f)})}a.CHATPANEL_SELF_UPDATE!=="off"&&(o("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),o("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[e,l]of Object.entries(t.upstreams||{}))l?.baseUrl&&o(w(l.baseUrl),`model upstream "${e}" — chat requests (after redaction) go here`,{when:`a request addressed to ${e}`,off:`upstreams.${e}.baseUrl`,local:m(w(l.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const e of t.destinations||[])e?.baseUrl&&o(w(e.baseUrl),`destination "${e.id||e.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${e.id||"it"}`,off:"destinations[]",local:m(w(e.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});o("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),t.ner?.url&&o(w(t.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:m(w(t.ner.url).split(":")[0]),data:"the text being redacted"});const h=t.tts||{};if(h.provider==="openai"||h.provider==="elevenlabs"){const e=h.remote?.baseUrl?w(h.remote.baseUrl):h.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";o(e,`remote read-aloud voice (${h.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:h.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}n==="darwin"&&t.runtime?.heatwatch!==!1&&o("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const d=t.bridge?.url||"http://127.0.0.1:4319";return o(w(d),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),p}function N(t,{ledger:a=P(),version:n="",startedAt:s=null,env:p=process.env,managed:o=null,certificates:u=null,linkPartners:c=null,confined:r=null,readers:h=null}={}){const d=R(t,p);for(const e of c||[])!e.host||e.route!=="link"&&e.route!=="relay"||d.some(l=>l.host===e.host)||d.push({host:e.host,purpose:`ChatPanel Link: the relay partner "${e.partner?.name||e.name}" reaches this gateway through`,when:"while that partner device is paired",off:`remove it: chatpanel-gateway link revoke ${e.id}`,data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"});return{ok:!0,version:n,since:s?new Date(s).toISOString():null,...u?{certificates:u}:{},...r?{confined:r}:{},...h?{readers:h}:{},...o?{managed:o,blocked:a?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:a?a.snapshot():[],declared:d,...c?{link:{partners:c.map(e=>({id:e.id,partner:e.partner?.name||e.name,scopes:e.scopes||[],route:e.route||null,host:e.host||null,...e.folder?{folder:e.folder}:{},pairedAt:e.pairedAt||null,lastSeen:e.lastSeen||null,online:!!e.online}))}}:{}}}function _(t){const a=[];a.push(`ChatPanel Gateway ${t.version||""} — egress audit`.trim()),t.since&&a.push(`observed since ${t.since}`),a.push(""),a.push("OBSERVED — hosts this process has actually contacted"),t.observed?.length||a.push(" (none yet)");for(const n of t.observed||[])a.push(` ${n.local?"[local] ":""}${n.scheme}://${n.host}:${n.port} ×${n.count} last ${n.lastAt}`);a.push(""),a.push("DECLARED — hosts this configuration allows, and why");for(const n of t.declared||[])a.push(` ${n.local?"[local] ":""}${n.host}`),a.push(` ${n.purpose}`),a.push(` when: ${n.when}${n.off?` · off: ${n.off}`:""}`),n.data&&a.push(` sends: ${n.data}`);if(t.certificates){const n=t.certificates;a.push(""),a.push("CERTIFICATES — whose word is taken that a server is who it says"),a.push(n.on?` the runtime's own list, and this computer's (${n.added} added) — what a company proxy that re-signs HTTPS needs; checks stay on`:` the runtime's own list only${n.why?` — ${n.why}`:""}`),a.push(" off: tls.systemCa: false in the config, or CHATPANEL_SYSTEM_CA=off, then restart")}if(t.confined&&(a.push(""),a.push("CONFINEMENT — what this process itself can reach on this computer"),a.push(` ${$(t.confined)}`),t.confined.on&&a.push(" checked at start: home folder listed "+(t.confined.homeListed?"YES":"no")+" · home folder written "+(t.confined.homeWritten?"YES":"no")+" · sandbox runtime written "+(t.confined.fenceWritten?"YES":"no")+" · own folder written "+(t.confined.stateWritten?"yes":"NO"))),t.readers){const n=t.readers;a.push(""),a.push("READERS — who may read your history, memory and knowledge bases here"),a.push(n.personalReads==="credential"?" a credential is required: the gateway token, the ChatPanel extension, an agent connected with `chatpanel-gateway connect`, or one issued below. Websites and other browser extensions are refused.":' OPEN to any program on this computer (and a browser extension holding no token can also read). Require a credential: security.personalReads: "credential" in the config, then restart.'),a.push(" not covered: a program running as your user can read ~/.chatpanel directly — the operating-system account is that boundary.");for(const s of n.principals||[])a.push(` ${s.kind}:${s.name} …${s.hint||""}${s.revokedAt?" REVOKED":""}${s.expiresAt?` expires ${new Date(s.expiresAt).toISOString().slice(0,10)}`:""}`)}if(t.link){a.push(""),a.push("LINK PARTNERS — servers the owner paired to reach this gateway over ChatPanel Link"),t.link.partners?.length||a.push(" (none — no partner can reach this gateway until you pair one)");for(const n of t.link.partners||[]){const s=n.lastSeen?new Date(n.lastSeen).toISOString():"never";a.push(` partner:${n.partner} scopes: ${n.scopes.join(", ")||"none"} agents: ${n.scopes.includes("agents")?"yes":"no"}`),a.push(` route: ${n.route||"?"}${n.host?` via ${n.host}`:""} · last seen ${s}${n.online?" (online)":""}`),n.scopes.includes("agents")&&a.push(` agents run as yours do (your Coding Agents settings and sandbox), in ${n.folder||"its folder"}; it never answers their approval prompts`),a.push(` revoke: chatpanel-gateway link revoke ${n.id}`)}}return t.managed&&(a.push(""),a.push(`POLICY — ${t.managed.name||t.managed.org||"managed"} (${t.managed.signed?"signed":"unsigned file"}, hash ${String(t.managed.policyHash||"").slice(0,12)}…)`),a.push(` enforcing: ${Object.entries(t.managed.enforces||{}).filter(([,n])=>n).map(([n,s])=>s===!0?n:`${n}=${s}`).join(", ")||"nothing yet"}`),a.push(` refused this session: ${t.blocked?.length?t.blocked.join(", "):"none"}`)),a.push(""),a.push(`Scope: ${t.scope}`),a.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),a.join(`
|
|
2
|
+
`)}export{L as createEgressLedger,R as declaredEgress,N as egressAudit,P as egressLedger,_ as formatAudit,q as installEgressLedger};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUID as l}from"node:crypto";import{createAppender as s}from"./event.js";const o="gateway";function w({store:r=null,now:p=()=>Date.now(),newId:u=()=>l(),log:c=t=>{}}={}){let t=null;return function(n,f){if(!r)return!1;for(let a=0;a<2;a++)try{if(!t){const e=r.cursor()[o];t=s({host:o,seq:Number.isInteger(e)?e+1:0,now:p,newId:u})}return r.append(t.append(n,f)),!0}catch(e){if(t=null,e?.code!=="SEQ")return c(`[gateway-events] ${n} not recorded: ${e?.code||e?.message||e}`),!1}return!1}}export{o as GATEWAY_HOST,w as createGatewayEvents};
|
package/src/link-activity.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{randomUUID as
|
|
2
|
-
`))!==-1;)
|
|
1
|
+
import{randomUUID as v}from"node:crypto";import{createGatewayEvents as N,GATEWAY_HOST as R}from"./gateway-events.js";const d=e=>Math.max(0,Number(e)||0),i=(e,t)=>String(e??"").replace(/[\r\n\t]+/g," ").trim().slice(0,t);function D(e,t=""){if(!e)return null;if(e.kind==="partner")return`partner:${i(e.partner,40)||"partner"}`;const n=i(t,40);return n?`phone:${n}`:"phone"}function b(e){if(!e||typeof e!="object")return null;const t=d(e.prompt_tokens_details?.cached_tokens??e.input_tokens_details?.cached_tokens??e.cache_read_input_tokens),n=e.prompt_tokens!=null||e.input_tokens_details!=null,s=d(e.prompt_tokens??e.input_tokens),o={inputTokens:n?Math.max(0,s-t):s,outputTokens:d(e.completion_tokens??e.output_tokens),cacheReadTokens:t,cacheWriteTokens:d(e.cache_creation_input_tokens)};return o.inputTokens||o.outputTokens||o.cacheReadTokens||o.cacheWriteTokens?o:null}const S=e=>[e?.usage,e?.message?.usage,e?.response?.usage].filter(t=>t&&typeof t=="object");function U(e){try{const t=S(JSON.parse(String(e)))[0];return t?b(t):null}catch{return null}}function E(){const e=new TextDecoder;let t="",n=null;const s=c=>{const u=c.trim();if(!u.startsWith("data:"))return;const r=u.slice(5).trim();if(!r||r==="[DONE]"||!r.includes("usage"))return;let f;try{f=JSON.parse(r)}catch{return}for(const h of S(f)){n={...n||{}};for(const[T,l]of Object.entries(h))l!=null&&(n[T]=l)}};return{stream:new TransformStream({transform(c,u){t+=e.decode(c,{stream:!0});let r;for(;(r=t.indexOf(`
|
|
2
|
+
`))!==-1;)s(t.slice(0,r)),t=t.slice(r+1);u.enqueue(c)},flush(){t+=e.decode(),t&&s(t),t=""}}),usage:()=>b(n)}}function I({store:e=null,now:t=()=>Date.now(),newId:n=()=>v(),log:s=c=>{},events:o=null}={}){const c=o||N({store:e,now:t,newId:n,log:s}),u=r=>c("turn.ended",r);return{begin({caller:r,surface:f,agentId:h=null,model:T=null,dest:l=null,threadId:g=null,startedAt:y}={}){if(!e||!r||!f)return null;const W=Number.isFinite(y)?y:t(),x=`link-${n()}`,p={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};let O=!1,_=!1;return{turnId:x,get ended(){return _},add(a){if(!a)return;const m=Object.keys(p);if(m.some(k=>d(a[k]))){O=!0;for(const k of m)p[k]+=d(a[k])}},end(a="ok",{code:m=""}={}){if(_)return!1;_=!0;const k={turnId:x,reason:a,stepped:a==="ok",ms:Math.max(0,t()-W),kind:"chat",relayed:!0,surface:f,...h?{agentId:i(h,120)}:{},...T?{model:i(T,200)}:{},...l?.type?{dest:{type:l.type,id:i(l.id,120)}}:{},...g?{threadId:i(g,160)}:{},...O?{tokensIn:p.inputTokens,tokensOut:p.outputTokens,cacheReadTokens:p.cacheReadTokens,cacheWriteTokens:p.cacheWriteTokens}:{},...a==="error"&&m?{error:{code:i(m,60)}}:{}};return u(k)}}}}}export{R as GATEWAY_HOST,I as createLinkActivity,D as linkSurface,b as providerUsage,E as sseUsageTap,U as usageOfBody};
|
package/src/mcp.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import{loadConfig as
|
|
2
|
-
`);async function
|
|
3
|
-
`)}catch{return""}}function S(){try{return y().mcp?.ask||{}}catch{return{}}}let m="unknown";function q(n){try{const e=k();fetch(`${f()}/v1/observability/access`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(n)}).catch(()=>{})}catch{}}function f(){const n=process.env.CHATPANEL_GATEWAY_URL;if(n)return n.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 Q(){try{return x(y().bridge?.token||"")}catch{return x("")}}async function $(n){const e=Q(),s=await fetch(O()+n,{headers:{Accept:"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}),i=await s.json().catch(()=>({}));if(!s.ok||i.ok===!1)throw new Error(i?.error||`bridge ${s.status}`);return i}const Z=[{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:"research",description:'Research a question about the user\'s OWN meetings, notes and past chats from the WHOLE ChatPanel store, not a few snippets: it frames the question (which kind of record, which people, which dates, the latest or the first, a count, counts per person or per month), queries every record that matches — sorted by date when the question asks for the last one, counted when it asks how many — reads the top records in full, and returns what it searched, what it found (with record ids and dates) and what those records say. Use it for "when was my last meeting with Alex", "how many calls did I have in August", "who do I meet with most", "what did we decide about pricing". For a follow-up ("no, even later", "what was it about") pass back the `previous` it returned. Cite the [id]s it gives; follow up with get_record for more of one record.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in their words."},previous:{type:"object",description:"The `previous` value the last research call returned, to continue that question (a follow-up)."}},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(n=>`${n}: ${E[n].hint}`).join(" ")},tags:{type:"array",items:{type:"string"},description:"Optional short tags for grouping."}},required:["text"]}},{name:"forget",description:'Remove a memory from ChatPanel when the user says it no longer holds. Name it however they did ("the Frankfurt thing") or pass the id from recall — it matches on meaning, and tells you exactly what it removed.',inputSchema:{type:"object",properties:{query:{type:"string",description:"The memory to remove: its text, roughly how the user named it, or its id."}},required:["query"]}},{name:"list_skills",description:"List the reusable skills installed on this machine (via the ChatPanel bridge) — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes) and any configured folder. Returns each skill's name and one-line description. Call open_skill to load the one that fits the task.",inputSchema:{type:"object",properties:{}}},{name:"open_skill",description:"Load one skill's full instructions by name (from list_skills), then follow them. If the instructions point at reference files, read one with read_skill_file.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name from list_skills."}},required:["name"]}},{name:"read_skill_file",description:"Read one reference file a skill's instructions point at (any path inside the skill's own folder). Use only when the task needs it.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name."},path:{type:"string",description:"The reference path as written in the instructions, e.g. references/auth.md."}},required:["name","path"]}},{name:"kb_list",description:"The knowledge bases on this machine — the user's indexed documents (PDFs, office files, folders, web pages), each with its id, name and size. START HERE for any question about a document the user has, then kb_search that base. Read a base's REPORT with kb_report before reading pages: it is the map (documents, outlines, the names that bind them).",inputSchema:{type:"object",properties:{}}},{name:"kb_search",description:"Search one knowledge base for the passages that answer a question — the words (several query shapes), the meaning (vectors) and the graph (passages sharing a name with a hit) fused, a reranker on top, best first, each with its citation like [report.pdf p.12] and its passage id. Search BEFORE paging a document; pass 1–3 of your own phrasings in `queries` when you know the domain.",inputSchema:{type:"object",properties:{kb:{type:"string",description:"The base id (from kb_list)."},query:{type:"string",description:"The question, or key words."},queries:{type:"array",items:{type:"string"},description:"Your own phrasings, searched too and fused."},limit:{type:"integer",minimum:1,maximum:30,description:"How many passages (default 8)."},doc:{type:"string",description:"Only this document id."}},required:["kb","query"]}},{name:"kb_read",description:"Read one passage by its id (from kb_search), or one page of a document by document id and page number. A page call says which page is next.",inputSchema:{type:"object",properties:{kb:{type:"string",description:"The base id."},id:{type:"string",description:'A passage id like "d3f2a1b4c5d6#12".'},doc:{type:"string",description:"A document id (with page)."},page:{type:"integer",minimum:1,description:"The page (with doc)."}},required:["kb"]}},{name:"kb_outline",description:"The table of contents of a document in a base (its sections, with the page each starts on and the first passage id), or of every document when none is named.",inputSchema:{type:"object",properties:{kb:{type:"string"},doc:{type:"string",description:"A document id; omit for all."}},required:["kb"]}},{name:"kb_graph",description:'Walk the base\'s graph one step from a name, a defined term, a section or a passage id: the passages that step reaches — where a term is DEFINED, what REFERS to a section ("see Note 7"), where a name is mentioned, what a passage cites — each with its citation and why, then the names to step to next. Use it after kb_search when a hit names something you need (a defined term, "as described in …", a party), instead of searching again. With `to`, the path between two nodes.',inputSchema:{type:"object",properties:{kb:{type:"string"},node:{type:"string",description:'A name, a defined term, a section, or a passage id from kb_search (e.g. "d3f2a1b4c5d6#12").'},query:{type:"string",description:"The question you are answering: the step ranks its passages and the next names toward it."},to:{type:"string",description:"A second node: the path from node to it."},hops:{type:"integer",minimum:1,maximum:3}},required:["kb","node"]}},{name:"kb_status",description:"What one base holds: its documents (ids, titles, pages, passages), notes, entities, connections, and whether it has vectors.",inputSchema:{type:"object",properties:{kb:{type:"string"}},required:["kb"]}},{name:"kb_report",description:"The base's graph report as Markdown: every document with its outline, the most-mentioned entities, the communities of names that keep appearing together, the notes filed so far. Read it once before searching a base you have not seen.",inputSchema:{type:"object",properties:{kb:{type:"string"}},required:["kb"]}},{name:"kb_note",description:"File a note into a base — a fact you established, a summary, a correction — citing the passage ids it rests on. It is PROPOSED until the user accepts it in ChatPanel; proposed notes are searched and shown as proposed. Use it when the user asks to remember or record something about these documents, or when you resolved something that took work to find.",inputSchema:{type:"object",properties:{kb:{type:"string"},text:{type:"string",description:"One to three sentences."},cites:{type:"array",items:{type:"string"},description:"Passage ids the note stands on."}},required:["kb","text"]}},{name:"search_context",description:"Search the user's knowledge across every knowledge base at once (and, when you name it, the web) — passages ranked across sources and packed to a token budget, each with its citation and where it came from. Use it when you do not know which base holds the answer; kb_search one base when you do.",inputSchema:{type:"object",properties:{query:{type:"string",description:"The question, or key words."},sources:{type:"array",items:{type:"string"},description:'Where to look: "kb:*" (every base, the default), "kb:<id>", "web".'},max_tokens:{type:"integer",minimum:200,maximum:2e4,description:"The budget for the passages returned (default 4000)."},pages:{type:"array",items:{type:"integer"},description:"Only pages [from, to]."},section:{type:"string",description:"Only passages whose section path contains this."},form:{type:"string",enum:["prose","list","table"],description:"Only passages of this form."}},required:["query"]}}],C={[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 N(){const n=f(),e=c=>[{id:"gateway",name:"the gateway",url:`${n}${c}`,where:"this device"}],s=A({providers:{decide:e("/v1/decide"),rerank:e("/v1/rerank")},fetch:(c,o)=>fetch(c,o)}),i=W({search:async c=>{const o=await d("/v1/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({q:c,limit:8,read:F.aliasRead})});return{query:c,engines:o.engines||[],results:(o.results||[]).map((t,r)=>({rank:r+1,title:t.title||t.url,url:t.url,engine:t.engine||"",text:t.read?.markdown||t.read?.text||t.snippet||""}))}}});return[s,i]}const ee=N().flatMap(n=>n.specs.map(e=>({name:e.name,description:e.description,inputSchema:e.parameters})));async function te(n,e){const s=N().find(o=>o.specs.some(t=>t.name===n));if(!s)return null;const i=await s.execute(n,e);let c=typeof i=="string"?i:String(i?.text??i);return C[n]&&/^No (decision model|reranker) answered/.test(c)&&(c+=C[n]),c}function w(n,e){if(!n)return`Index: ${e} records (warm copy synced from ChatPanel).`;const s=new Date(n),i=`${s.getFullYear()}-${String(s.getMonth()+1).padStart(2,"0")}-${String(s.getDate()).padStart(2,"0")} ${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`;return`Index: ${e} records, current through ${i} (local warm copy — items newer than this may not have synced from ChatPanel yet).`}function j(){try{const n=k();return n?{Authorization:`Bearer ${n}`}:{}}catch{return{}}}async function d(n,e){let s;try{s=await fetch(f()+n,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 i=await s.json().catch(()=>({}));if(!s.ok)throw new Error(i?.error?.message||`the gateway returned HTTP ${s.status} for ${n}`);return i}function g(n){if(n==null||n==="")return null;if(typeof n=="number")return n;const e=String(n).trim().toLowerCase(),s=864e5;if(e==="today")return Date.now()-s;if(e==="yesterday")return Date.now()-2*s;const i=/^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(e);if(i){const o=Number(i[1]),t=i[2][0],r=t==="d"?s:t==="w"?7*s:t==="m"?30*s:365*s;return Date.now()-o*r}const c=Date.parse(e);return Number.isNaN(c)?null:c}const v=(n,e)=>`${e+1}. [${n.id}] ${n.title||"(untitled)"} · ${n.type}${n.date?" · "+new Date(n.date).toISOString().slice(0,10):""}${n.snippet?`
|
|
4
|
-
${n.snippet}`:""}`;async function
|
|
1
|
+
import{readFileSync as M,statSync as U}from"node:fs";import{loadConfig as w}from"./config.js";import{AGENT_TOKEN_PATH as _}from"./principals.js";import{VERSION as k}from"./version.js";import{readBridgeToken as T}from"./bridge.js";import{ensureGatewayToken as S}from"./gateway-token.js";import{MEMORY_KINDS as D,MEMORY_KIND_NAMES as O}from"./memory.js";import{parseBriefText as H}from"./knowledge.js";import{capabilityToolsProvider as B,DECIDE_TOOL_NAME as W,RERANK_TOOL_NAME as F}from"./capability-tools.js";import{renderSearch as z,renderOutline as J,renderGraph as Y,renderStatus as G}from"@chatpanel/events/kb-tool.js";import{renderContext as K}from"@chatpanel/events/context-api.js";import{webSearchToolProvider as V}from"./web-search-tool.js";import{SEARCH_DEFAULTS as X}from"./retrieval/search.js";import{askToolsFor as q,callAsk as Q}from"./mcp-ask.js";import{CAPABILITY_TOOLS as Z,callCapability as ee}from"./mcp-capabilities.js";const te="2024-11-05",ne={name:"chatpanel-history",version:k},re=["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:",' • research — for "when was my last…", "how many…", "who do I meet with most", "what was',' that meeting about": it searches the WHOLE store as the question frames it (dates, counts,'," people), reads the top records in full and returns the evidence with ids to cite."," • 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 oe(){try{const n=await fetch(`${f()}/health`,{signal:AbortSignal.timeout(600)}),e=String((await n.json())?.version||"");return!e||e===k?"":["",`IMPORTANT — VERSION MISMATCH. This MCP server is ChatPanel ${k}, 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 $(){try{return w().mcp?.ask||{}}catch{return{}}}let m="unknown";function C(n){try{const e=S();fetch(`${f()}/v1/observability/access`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(n)}).catch(()=>{})}catch{}}function f(){const n=process.env.CHATPANEL_GATEWAY_URL;if(n)return n.replace(/\/+$/,"");let e=4320;try{e=w().port||4320}catch{}return`http://127.0.0.1:${e}`}function N(){try{return String(w().bridge?.url||"http://127.0.0.1:4319").replace(/\/+$/,"")}catch{return"http://127.0.0.1:4319"}}function ie(){try{return T(w().bridge?.token||"")}catch{return T("")}}async function v(n){const e=ie(),i=await fetch(N()+n,{headers:{Accept:"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}),s=await i.json().catch(()=>({}));if(!i.ok||s.ok===!1)throw new Error(s?.error||`bridge ${i.status}`);return s}const se=[{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:"research",description:'Research a question about the user\'s OWN meetings, notes and past chats from the WHOLE ChatPanel store, not a few snippets: it frames the question (which kind of record, which people, which dates, the latest or the first, a count, counts per person or per month), queries every record that matches — sorted by date when the question asks for the last one, counted when it asks how many — reads the top records in full, and returns what it searched, what it found (with record ids and dates) and what those records say. Use it for "when was my last meeting with Alex", "how many calls did I have in August", "who do I meet with most", "what did we decide about pricing". For a follow-up ("no, even later", "what was it about") pass back the `previous` it returned. Cite the [id]s it gives; follow up with get_record for more of one record.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in their words."},previous:{type:"object",description:"The `previous` value the last research call returned, to continue that question (a follow-up)."}},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:O,description:O.map(n=>`${n}: ${D[n].hint}`).join(" ")},tags:{type:"array",items:{type:"string"},description:"Optional short tags for grouping."}},required:["text"]}},{name:"forget",description:'Remove a memory from ChatPanel when the user says it no longer holds. Name it however they did ("the Frankfurt thing") or pass the id from recall — it matches on meaning, and tells you exactly what it removed.',inputSchema:{type:"object",properties:{query:{type:"string",description:"The memory to remove: its text, roughly how the user named it, or its id."}},required:["query"]}},{name:"list_skills",description:"List the reusable skills installed on this machine (via the ChatPanel bridge) — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes) and any configured folder. Returns each skill's name and one-line description. Call open_skill to load the one that fits the task.",inputSchema:{type:"object",properties:{}}},{name:"open_skill",description:"Load one skill's full instructions by name (from list_skills), then follow them. If the instructions point at reference files, read one with read_skill_file.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name from list_skills."}},required:["name"]}},{name:"read_skill_file",description:"Read one reference file a skill's instructions point at (any path inside the skill's own folder). Use only when the task needs it.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name."},path:{type:"string",description:"The reference path as written in the instructions, e.g. references/auth.md."}},required:["name","path"]}},{name:"kb_list",description:"The knowledge bases on this machine — the user's indexed documents (PDFs, office files, folders, web pages), each with its id, name and size. START HERE for any question about a document the user has, then kb_search that base. Read a base's REPORT with kb_report before reading pages: it is the map (documents, outlines, the names that bind them).",inputSchema:{type:"object",properties:{}}},{name:"kb_search",description:"Search one knowledge base for the passages that answer a question — the words (several query shapes), the meaning (vectors) and the graph (passages sharing a name with a hit) fused, a reranker on top, best first, each with its citation like [report.pdf p.12] and its passage id. Search BEFORE paging a document; pass 1–3 of your own phrasings in `queries` when you know the domain.",inputSchema:{type:"object",properties:{kb:{type:"string",description:"The base id (from kb_list)."},query:{type:"string",description:"The question, or key words."},queries:{type:"array",items:{type:"string"},description:"Your own phrasings, searched too and fused."},limit:{type:"integer",minimum:1,maximum:30,description:"How many passages (default 8)."},doc:{type:"string",description:"Only this document id."}},required:["kb","query"]}},{name:"kb_read",description:"Read one passage by its id (from kb_search), or one page of a document by document id and page number. A page call says which page is next.",inputSchema:{type:"object",properties:{kb:{type:"string",description:"The base id."},id:{type:"string",description:'A passage id like "d3f2a1b4c5d6#12".'},doc:{type:"string",description:"A document id (with page)."},page:{type:"integer",minimum:1,description:"The page (with doc)."}},required:["kb"]}},{name:"kb_outline",description:"The table of contents of a document in a base (its sections, with the page each starts on and the first passage id), or of every document when none is named.",inputSchema:{type:"object",properties:{kb:{type:"string"},doc:{type:"string",description:"A document id; omit for all."}},required:["kb"]}},{name:"kb_graph",description:'Walk the base\'s graph one step from a name, a defined term, a section or a passage id: the passages that step reaches — where a term is DEFINED, what REFERS to a section ("see Note 7"), where a name is mentioned, what a passage cites — each with its citation and why, then the names to step to next. Use it after kb_search when a hit names something you need (a defined term, "as described in …", a party), instead of searching again. With `to`, the path between two nodes.',inputSchema:{type:"object",properties:{kb:{type:"string"},node:{type:"string",description:'A name, a defined term, a section, or a passage id from kb_search (e.g. "d3f2a1b4c5d6#12").'},query:{type:"string",description:"The question you are answering: the step ranks its passages and the next names toward it."},to:{type:"string",description:"A second node: the path from node to it."},hops:{type:"integer",minimum:1,maximum:3}},required:["kb","node"]}},{name:"kb_status",description:"What one base holds: its documents (ids, titles, pages, passages), notes, entities, connections, and whether it has vectors.",inputSchema:{type:"object",properties:{kb:{type:"string"}},required:["kb"]}},{name:"kb_report",description:"The base's graph report as Markdown: every document with its outline, the most-mentioned entities, the communities of names that keep appearing together, the notes filed so far. Read it once before searching a base you have not seen.",inputSchema:{type:"object",properties:{kb:{type:"string"}},required:["kb"]}},{name:"kb_note",description:"File a note into a base — a fact you established, a summary, a correction — citing the passage ids it rests on. It is PROPOSED until the user accepts it in ChatPanel; proposed notes are searched and shown as proposed. Use it when the user asks to remember or record something about these documents, or when you resolved something that took work to find.",inputSchema:{type:"object",properties:{kb:{type:"string"},text:{type:"string",description:"One to three sentences."},cites:{type:"array",items:{type:"string"},description:"Passage ids the note stands on."}},required:["kb","text"]}},{name:"search_context",description:"Search the user's knowledge across every knowledge base at once (and, when you name it, the web) — passages ranked across sources and packed to a token budget, each with its citation and where it came from. Use it when you do not know which base holds the answer; kb_search one base when you do.",inputSchema:{type:"object",properties:{query:{type:"string",description:"The question, or key words."},sources:{type:"array",items:{type:"string"},description:'Where to look: "kb:*" (every base, the default), "kb:<id>", "web".'},max_tokens:{type:"integer",minimum:200,maximum:2e4,description:"The budget for the passages returned (default 4000)."},pages:{type:"array",items:{type:"integer"},description:"Only pages [from, to]."},section:{type:"string",description:"Only passages whose section path contains this."},form:{type:"string",enum:["prose","list","table"],description:"Only passages of this form."}},required:["query"]}}],j={[W]:" 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).",[F]:" 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 A(){const n=f(),e=c=>[{id:"gateway",name:"the gateway",url:`${n}${c}`,where:"this device"}],i=B({providers:{decide:e("/v1/decide"),rerank:e("/v1/rerank")},fetch:(c,o)=>fetch(c,o)}),s=V({search:async c=>{const o=await d("/v1/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({q:c,limit:8,read:X.aliasRead})});return{query:c,engines:o.engines||[],results:(o.results||[]).map((t,r)=>({rank:r+1,title:t.title||t.url,url:t.url,engine:t.engine||"",text:t.read?.markdown||t.read?.text||t.snippet||""}))}}});return[i,s]}const ae=A().flatMap(n=>n.specs.map(e=>({name:e.name,description:e.description,inputSchema:e.parameters})));async function ce(n,e){const i=A().find(o=>o.specs.some(t=>t.name===n));if(!i)return null;const s=await i.execute(n,e);let c=typeof s=="string"?s:String(s?.text??s);return j[n]&&/^No (decision model|reranker) answered/.test(c)&&(c+=j[n]),c}function g(n,e){if(!n)return`Index: ${e} records (warm copy synced from ChatPanel).`;const i=new Date(n),s=`${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 ${s} (local warm copy — items newer than this may not have synced from ChatPanel yet).`}function R(){try{const n=S();return n?{Authorization:`Bearer ${n}`}:{}}catch{return{}}}let y="",E=-1;const P=()=>{try{return M(_,"utf8").trim()}catch{return""}},I=(n={})=>{let e=-1;try{e=U(_).mtimeMs}catch{e=-1}(!y||e!==E)&&(y=P(),E=e);const i={...n.headers||{}};return y&&!i.authorization&&!i.Authorization&&(i.authorization=`Bearer ${y}`),{...n,headers:i}};async function d(n,e){let i;try{if(i=await fetch(f()+n,I(e)),i.status===403||i.status===401){const c=P();c&&c!==y&&(y=c,i=await fetch(f()+n,I(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 s=await i.json().catch(()=>({}));if(!i.ok)throw new Error(s?.error?.message||`the gateway returned HTTP ${i.status} for ${n}`);return s}function b(n){if(n==null||n==="")return null;if(typeof n=="number")return n;const e=String(n).trim().toLowerCase(),i=864e5;if(e==="today")return Date.now()-i;if(e==="yesterday")return Date.now()-2*i;const s=/^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(e);if(s){const o=Number(s[1]),t=s[2][0],r=t==="d"?i:t==="w"?7*i:t==="m"?30*i:365*i;return Date.now()-o*r}const c=Date.parse(e);return Number.isNaN(c)?null:c}const x=(n,e)=>`${e+1}. [${n.id}] ${n.title||"(untitled)"} · ${n.type}${n.date?" · "+new Date(n.date).toISOString().slice(0,10):""}${n.snippet?`
|
|
4
|
+
${n.snippet}`:""}`;async function he(n,e={}){const i=await ce(n,e);if(i!=null)return i;const s=await ee(n,e,{gatewayJson:d});if(s!=null)return s;const c=await Q(n,e,{baseUrl:f,gatewayJson:d,token:()=>{try{return S()}catch{return""}},client:()=>m,askConfig:$});if(c!=null)return c;if(n==="research"){const o={question:String(e.question||"")};e.previous&&typeof e.previous=="object"&&(o.previous=e.previous);const t=await d("/v1/research",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),r=g(t.newest,t.size),a=t.attachment?.text||`Searched ${t.how||"the store"} — nothing found in the user's data.`;return`${r}
|
|
5
5
|
|
|
6
6
|
${a}
|
|
7
7
|
|
|
8
|
-
previous (pass back for a follow-up): ${JSON.stringify(t.next||null)}`}if(n==="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 t=
|
|
8
|
+
previous (pass back for a follow-up): ${JSON.stringify(t.next||null)}`}if(n==="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 t=b(e.since);t!=null&&(o.since=t);const r=b(e.before);r!=null&&(o.before=r);const a=await d("/v1/history/smart-search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),h=a.results||[],l=g(a.newest,a.size),p=(a.queries||[]).map(u=>`"${u}"`).join(", ");return h.length?[l,"",`${h.length} result(s) for "${e.question}" — searched ${a.queries.length} way(s): ${p}`,...h.map((u,L)=>`${x(u,L)}${u.foundBy?.length>1?`
|
|
9
9
|
(matched ${u.foundBy.length} of the queries)`:""}`)].join(`
|
|
10
10
|
`)+`
|
|
11
11
|
|
|
12
12
|
get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.question}".
|
|
13
13
|
Searched ${a.queries?.length||0} way(s): ${p}.
|
|
14
14
|
${l}
|
|
15
|
-
If you expected a recent item it may not have synced yet — check ChatPanel directly, or try different keywords (meeting titles are often generic).`}if(n==="search_history"){const 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 t=
|
|
15
|
+
If you expected a recent item it may not have synced yet — check ChatPanel directly, or try different keywords (meeting titles are often generic).`}if(n==="search_history"){const 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 t=b(e.since);t!=null&&(o.since=t);const r=b(e.before);r!=null&&(o.before=r);const a=await d("/v1/history/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),h=a.results||[],l=g(a.newest,a.size),p=[e.type&&`type=${e.type}`,e.since&&`since=${e.since}`,e.before&&`before=${e.before}`].filter(Boolean).join(", "),u=p?` (${p})`:"";return h.length?[l,"",`${h.length} result(s) for "${e.query}"${u}:`,...h.map(x)].join(`
|
|
16
16
|
`)+`
|
|
17
17
|
|
|
18
18
|
get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.query}"${u}.
|
|
@@ -21,33 +21,33 @@ If you expected a recent item, it may not have synced yet — check ChatPanel di
|
|
|
21
21
|
|
|
22
22
|
[showing ${r.text.length} of ${r.totalChars} chars (from offset ${r.offset}). For the next part call get_record again with offset=${r.offset+r.text.length}.]`:"";return`${a}
|
|
23
23
|
|
|
24
|
-
${r.text||"(empty)"}${h}`}if(n==="find_related"){const t=(await d(`/v1/history/related?id=${encodeURIComponent(String(e.id||""))}&limit=${Number(e.limit)||5}`)).results||[];return t.length?[`Records related to ${e.id}:`,...t.map(
|
|
24
|
+
${r.text||"(empty)"}${h}`}if(n==="find_related"){const t=(await d(`/v1/history/related?id=${encodeURIComponent(String(e.id||""))}&limit=${Number(e.limit)||5}`)).results||[];return t.length?[`Records related to ${e.id}:`,...t.map(x)].join(`
|
|
25
25
|
`)+`
|
|
26
26
|
|
|
27
|
-
get_record <id> for full text.`:`Nothing related to ${e.id} found (or that id isn't in the warm index — run search_history first to get a valid id).`}if(n==="list_history"){const o=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0)}),t=await d(`/v1/history/list?${o}`),r=t.items||[];if(!r.length)return"History is empty (or the gateway has not been seeded yet — open ChatPanel with warm sync enabled).";const a=r[0]?.date||null;return[
|
|
27
|
+
get_record <id> for full text.`:`Nothing related to ${e.id} found (or that id isn't in the warm index — run search_history first to get a valid id).`}if(n==="list_history"){const o=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0)}),t=await d(`/v1/history/list?${o}`),r=t.items||[];if(!r.length)return"History is empty (or the gateway has not been seeded yet — open ChatPanel with warm sync enabled).";const a=r[0]?.date||null;return[g(a,t.total),"",`${r.length} of ${t.total} records:`,...r.map(h=>`[${h.id}] ${h.title||"(untitled)"} · ${h.type}${h.date?" · "+new Date(h.date).toISOString().slice(0,10):""} · ${h.chars} chars`)].join(`
|
|
28
28
|
`)}if(n==="list_briefs"){const o=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0),type:"brief"}),t=await d(`/v1/history/list?${o}`),r=t.items||[];return r.length?[`${r.length} of ${t.total} briefs (each is a page about one subject, with every claim cited):`,...r.map(a=>`[${a.id}] ${a.title||"(untitled)"}${a.date?" · rebuilt "+new Date(a.date).toISOString().slice(0,10):""}`)].join(`
|
|
29
29
|
`)+`
|
|
30
30
|
|
|
31
|
-
get_brief <id> for its claims and the records they cite.`:`No briefs yet. ChatPanel builds them from the user's records on the Briefs page; if that has run, the user may have "share briefs with local agents" switched off.`}if(n==="get_brief"){const o=String(e.id||""),r=(await d(`/v1/history/get?${new URLSearchParams({id:o})}`)).record,a=
|
|
32
|
-
`)}if(n==="recall"){const o=await d("/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(n==="remember"){const o=String(e.text||"").trim();if(!o)return"remember needs `text` — one short sentence about the user.";const t=await d("/v1/memory/remember",{method:"POST",headers:{"content-type":"application/json",...
|
|
31
|
+
get_brief <id> for its claims and the records they cite.`:`No briefs yet. ChatPanel builds them from the user's records on the Briefs page; if that has run, the user may have "share briefs with local agents" switched off.`}if(n==="get_brief"){const o=String(e.id||""),r=(await d(`/v1/history/get?${new URLSearchParams({id:o})}`)).record,a=H(r?.text);if(!a)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} — ${a.name} (${a.kind})${a.aliases.length?` · also known as ${a.aliases.join(", ")}`:""}`,""];h.push(`${a.claims.length} claim(s), each with the records it cites:`);for(const l of a.claims)h.push(`• ${l.text}`),l.refs.length&&h.push(` cites: ${l.refs.map(p=>`${p.kind}:${p.id}`).join(", ")}`);return a.records.length&&h.push("",`Built from ${a.records.length} record(s) (most recent first): ${a.records.slice(0,12).map(l=>l.title).join(" · ")}${a.records.length>12?" …":""}`),h.push("","get_record <kind:id> opens a cited record; find_related <id> follows its connections."),h.join(`
|
|
32
|
+
`)}if(n==="recall"){const o=await d("/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(n==="remember"){const o=String(e.text||"").trim();if(!o)return"remember needs `text` — one short sentence about the user.";const t=await d("/v1/memory/remember",{method:"POST",headers:{"content-type":"application/json",...R()},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 t.action==="duplicate"?`Already known: "${t.record.text}" — nothing changed.`:t.action==="update"?`Updated memory to "${t.record.text}" (was "${t.replaced?.text}"). It applies to every future session.`:`Remembered: "${t.record.text}". It applies to every future ChatPanel session, on every model.`}if(n==="forget"){const o=String(e.query||"").trim();if(!o)return"forget needs `query` — the memory to remove.";const t=await d("/v1/memory/forget",{method:"POST",headers:{"content-type":"application/json",...R()},body:JSON.stringify({query:o})});return t.removed?.length?`Forgot: ${t.removed.map(r=>`"${r.text}"`).join(", ")}.`:`No memory matches "${o}". Call recall to see what is stored.`}if(n==="list_skills"){let o;try{o=await v("/skills")}catch(r){return`Installed skills are unavailable because the ChatPanel bridge is not running at ${N()}. Install/start it with:
|
|
33
33
|
curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash
|
|
34
34
|
Then retry. History tools work without the bridge. [${r.message}]`}const t=o.skills||[];return t.length?[`${t.length} skill(s) installed:`,...t.map(r=>`- ${r.command||r.id}: ${r.description||r.name}${r.origin?.source?` (from ${r.origin.source})`:""}`)].join(`
|
|
35
35
|
`)+`
|
|
36
36
|
|
|
37
|
-
Use open_skill with a name to load its instructions.`:"No skills installed on this machine yet."}if(n==="open_skill"){let o;try{o=await
|
|
38
|
-
`):"No knowledge bases on this machine yet. The user builds one in ChatPanel (attach a folder or a document) or with `chatpanel kb build <path>`."}if(!
|
|
37
|
+
Use open_skill with a name to load its instructions.`:"No skills installed on this machine yet."}if(n==="open_skill"){let o;try{o=await v(`/skills/${encodeURIComponent(String(e.name||"").trim())}`)}catch(t){return`Could not open "${e.name}": ${t.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return o.skill?.prompt||"(this skill has no extra instructions — just apply it.)"}if(n==="read_skill_file"){const o=encodeURIComponent(String(e.name||"").trim()),t=String(e.path||"").trim().split("/").map(encodeURIComponent).join("/");let r;try{r=await v(`/skills/${o}/file/${t}`)}catch(a){return`Could not read ${e.path}: ${a.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return r.text||"(empty)"}if(n.startsWith("kb_"))return de(n,e);if(n==="search_context")return le(e);throw new Error(`unknown tool: ${n}`)}async function de(n,e={}){const i=String(e.kb||"").trim(),s=i?`/v1/kb/${encodeURIComponent(i)}`:"",c={"x-chatpanel-agent":String(m||"unknown").toLowerCase()},o=(t,r)=>d(t,{method:"POST",headers:{"content-type":"application/json",...c},body:JSON.stringify(r)});if(n==="kb_list"){const r=(await d("/v1/kb",{headers:c})).kbs||[];return r.length?[`${r.length} knowledge base${r.length===1?"":"s"}:`,...r.map(a=>`- ${a.id}: ${a.name} — ${a.docs} document${a.docs===1?"":"s"}${a.vectors?`, ${a.vectors} vectors`:""}`),"","kb_report <id> for the map, kb_search <id> for a question."].join(`
|
|
38
|
+
`):"No knowledge bases on this machine yet. The user builds one in ChatPanel (attach a folder or a document) or with `chatpanel kb build <path>`."}if(!i)return"Which knowledge base? kb_list gives the ids.";if(n==="kb_search"){const t=await o(`${s}/search`,{query:String(e.query||""),limit:Math.max(1,Math.min(30,Number(e.limit)||8)),...e.doc?{docs:[String(e.doc)]}:{},...Array.isArray(e.queries)?{queries:e.queries.map(String)}:{}});return`${t.instructions?.text?`Instructions from the administrator of this base — follow them when answering from it:
|
|
39
39
|
${t.instructions.text}
|
|
40
40
|
|
|
41
|
-
`:""}${
|
|
42
|
-
${t.text}`}catch(t){return`No passage ${e.id}: ${t.message}. Search first; passage ids look like "d3f2a1b4c5d6#12".`}if(e.doc)try{const t=await d(`${
|
|
43
|
-
${t.text||"(no text on this page — an image or a scan)"}`}catch(t){return`No document ${e.doc}: ${t.message}. kb_status lists the ids.`}return"kb_read needs a passage id, or a document id with a page."}if(n==="kb_outline"){const[t,r]=await Promise.all([d(`${
|
|
44
|
-
`)}async function
|
|
41
|
+
`:""}${z(t)}`}if(n==="kb_read"){if(e.id)try{const t=await d(`${s}/passages/${encodeURIComponent(String(e.id))}`,{headers:c});return`${t.cite||t.id}${t.section?` §${t.section}`:""}
|
|
42
|
+
${t.text}`}catch(t){return`No passage ${e.id}: ${t.message}. Search first; passage ids look like "d3f2a1b4c5d6#12".`}if(e.doc)try{const t=await d(`${s}/documents/${encodeURIComponent(String(e.doc))}?page=${Number(e.page)||1}`,{headers:c});return`${t.title} — page ${t.page} of ${t.pages}${t.page<t.pages?` (next: ${t.page+1})`:" (last page)"}
|
|
43
|
+
${t.text||"(no text on this page — an image or a scan)"}`}catch(t){return`No document ${e.doc}: ${t.message}. kb_status lists the ids.`}return"kb_read needs a passage id, or a document id with a page."}if(n==="kb_outline"){const[t,r]=await Promise.all([d(`${s}/outline${e.doc?`?doc=${encodeURIComponent(String(e.doc))}`:""}`,{headers:c}),d(s,{headers:c})]);return J(t.outline||[],r.kb)}if(n==="kb_graph")return Y(await o(`${s}/graph`,{node:String(e.node||""),hops:Math.max(1,Math.min(3,Number(e.hops)||1)),...e.to?{to:String(e.to)}:{},...typeof e.query=="string"&&e.query.trim()?{query:e.query}:{}}));if(n==="kb_status")return G((await d(s,{headers:c})).kb);if(n==="kb_report"){const t=await fetch(`${f()}${s}/report`,{headers:c});if(!t.ok)throw new Error(`the gateway returned HTTP ${t.status} for the report`);return t.text()}if(n==="kb_note"){const r=(await o(`${s}/notes`,{text:String(e.text||""),cites:Array.isArray(e.cites)?e.cites.map(String):[]})).note||{};return`Noted (${r.status||"proposed"} — the user can accept it in ChatPanel): ${r.text}${r.cites?.length?` — cites ${r.cites.join(", ")}`:""}`}throw new Error(`unknown tool: ${n}`)}async function le(n={}){const e={"x-chatpanel-agent":String(m||"unknown").toLowerCase()},i={...Array.isArray(n.pages)&&n.pages.length?{pages:n.pages.slice(0,2).map(Number)}:{},...n.section?{section:String(n.section)}:{},...n.form?{form:String(n.form)}:{}},s=await d("/v1/context",{method:"POST",headers:{"content-type":"application/json",...e},body:JSON.stringify({query:String(n.query||""),sources:Array.isArray(n.sources)&&n.sources.length?n.sources.map(String):["kb:*"],...Object.keys(i).length?{filters:i}:{},max_tokens:Math.max(200,Math.min(2e4,Number(n.max_tokens)||4e3))})}),c=Object.entries(s.providers||{}).filter(([,o])=>o.error).map(([o,t])=>`${o}: ${t.error}`);return[K(s),...c.length?["",`Not searched — ${c.join("; ")}`]:[]].join(`
|
|
44
|
+
`)}async function pe(n){const{id:e,method:i,params:s}=n||{},c=t=>({jsonrpc:"2.0",id:e,result:t}),o=(t,r)=>({jsonrpc:"2.0",id:e,error:{code:t,message:r}});try{switch(i){case"initialize":{m=s?.clientInfo?.name||m;const t=await oe(),r=q($()).some(a=>a.name==="delegate_task")?`
|
|
45
45
|
|
|
46
46
|
ChatPanel can also DELEGATE a whole piece of work to one of the user's coding agents,
|
|
47
47
|
running here with its own tools in a directory they have allowed:
|
|
48
48
|
• delegate_task — a refactor across many files, a test suite to run and fix, a build to
|
|
49
49
|
diagnose. Unlike ask_model it reads and EDITS files and runs commands, so use it for work
|
|
50
50
|
that belongs on this machine, tell the user what you delegated and where, and expect
|
|
51
|
-
minutes — it returns a job id for ask_status.`:"";return c({protocolVersion:
|
|
52
|
-
`);for await(const
|
|
53
|
-
`))>=0;){const c=n.slice(0,
|
|
51
|
+
minutes — it returns a job id for ask_status.`:"";return c({protocolVersion:te,capabilities:{tools:{}},serverInfo:ne,instructions:re+r+t})}case"tools/list":return c({tools:[...se,...ae,...Z,...q($())]});case"tools/call":{const t=Date.now();try{const r=await he(s?.name,s?.arguments||{});return C({client:m,tool:s?.name,ok:!0,ms:Date.now()-t,args:s?.arguments||{}}),c({content:[{type:"text",text:r}]})}catch(r){throw C({client:m,tool:s?.name,ok:!1,ms:Date.now()-t,args:s?.arguments||{},error:r.message}),r}}case"ping":return c({});default:return typeof i=="string"&&i.startsWith("notifications/")||e===void 0?null:o(-32601,`method not found: ${i}`)}}catch(t){return i==="tools/call"?c({content:[{type:"text",text:`Error: ${t.message}`}],isError:!0}):o(-32603,t.message)}}async function Ce(){let n="";process.stdin.setEncoding("utf8");const e=i=>process.stdout.write(JSON.stringify(i)+`
|
|
52
|
+
`);for await(const i of process.stdin){n+=i;let s;for(;(s=n.indexOf(`
|
|
53
|
+
`))>=0;){const c=n.slice(0,s).trim();if(n=n.slice(s+1),!c)continue;let o;try{o=JSON.parse(c)}catch{continue}const t=await pe(o);t&&e(t)}}}export{pe as handleRpc,Ce as runMcpServer};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{createHash as w,randomBytes as I,timingSafeEqual as b}from"node:crypto";import{readFileSync as S,writeFileSync as L,renameSync as H,mkdirSync as O,chmodSync as C,existsSync as j}from"node:fs";import{dirname as B,join as _}from"node:path";import N from"node:os";const v=Object.freeze(["agent","person"]),x="agent:local",R={agent:"chp_a_",person:"chp_p_"},K=/^chp_[ap]_[A-Za-z0-9_-]{40,60}$/,z=process.env.CHATPANEL_PRINCIPALS_PATH||_(N.homedir(),".chatpanel","principals.json"),D=process.env.CHATPANEL_AGENT_TOKEN_PATH||_(N.homedir(),".chatpanel","agent-token"),y=t=>w("sha256").update(String(t)).digest("hex"),k=(t,n)=>String(t??"").replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,n);function P(t,n){O(B(t),{recursive:!0});const c=`${t}.${process.pid}.tmp`;L(c,n,{mode:384});try{C(c,384)}catch{}H(c,t)}function q({path:t=z,now:n=()=>Date.now(),random:c=o=>I(o)}={}){let o=[];try{const e=JSON.parse(S(t,"utf8"));o=Array.isArray(e?.principals)?e.principals:[]}catch{o=[]}const l=new Map,m=()=>P(t,`${JSON.stringify({v:1,principals:o},null,2)}
|
|
2
|
+
`),T=e=>e&&!e.revokedAt&&!(Number(e.expiresAt)>0&&Number(e.expiresAt)<=n()),A=e=>({id:e.id,kind:e.kind,name:e.name,groups:e.groups||[],hint:e.hint,createdAt:e.createdAt,...e.expiresAt?{expiresAt:e.expiresAt}:{},...e.revokedAt?{revokedAt:e.revokedAt}:{},...l.has(e.id)?{lastUsedAt:l.get(e.id)}:{}});function h({kind:e,name:s,groups:r=[],expiresAt:i=0,id:p=""}={}){if(!v.includes(e))throw new Error(`a principal is ${v.join(" or ")}`);const a=k(s,80);if(!a)throw new Error("a principal needs a name");const u=`${R[e]}${c(32).toString("base64url")}`,d={id:p||`${e}:${c(9).toString("base64url")}`,kind:e,name:a,groups:(Array.isArray(r)?r:[]).map(f=>k(f,80)).filter(Boolean).slice(0,50),hash:y(u),hint:u.slice(-4),createdAt:n(),...Number(i)>0?{expiresAt:Number(i)}:{}};return o=[...o.filter(f=>f.id!==d.id),d],m(),{principal:A(d),token:u}}function g(e){const s=String(e||"").trim();if(!K.test(s))return null;const r=Buffer.from(y(s),"hex");let i=null;for(const p of o){const a=Buffer.from(String(p.hash||""),"hex");a.length===r.length&&b(a,r)&&!i&&(i=p)}return T(i)?(l.set(i.id,n()),{id:i.id,kind:i.kind,name:i.name,groups:i.groups||[]}):null}function E(e){const s=o.find(r=>r.id===e&&!r.revokedAt);return s?(s.revokedAt=n(),m(),!0):!1}function $(e=D){try{const r=S(e,"utf8").trim();if(g(r)?.id===x)return r}catch{}const{token:s}=h({kind:"agent",name:"Agents on this computer",id:x});return P(e,`${s}
|
|
3
|
+
`),s}return{issue:h,verify:g,revoke:E,ensureLocalAgentToken:$,list:()=>o.map(A),has:()=>j(t)}}function M(t={}){const n=String(t.authorization||"");return(n.startsWith("Bearer ")?n.slice(7):String(t["x-chatpanel-token"]||"")).trim()}export{D as AGENT_TOKEN_PATH,x as LOCAL_AGENT_ID,z as PRINCIPALS_PATH,v as PRINCIPAL_KINDS,q as createPrincipals,M as presentedToken,P as writePrivate};
|