@chatpanel/gateway 0.39.11 → 0.44.3

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/src/mcp.js CHANGED
@@ -1,34 +1,42 @@
1
- import{loadConfig as f}from"./config.js";import{readBridgeToken as b}from"./bridge.js";import{ensureGatewayToken as S}from"./gateway-token.js";import{MEMORY_KINDS as N,MEMORY_KIND_NAMES as k}from"./memory.js";import{parseBriefText as T}from"./knowledge.js";import{capabilityToolsProvider as j,DECIDE_TOOL_NAME as R,RERANK_TOOL_NAME as q}from"./capability-tools.js";import{webSearchToolProvider as P}from"./web-search-tool.js";import{SEARCH_DEFAULTS as E}from"./retrieval/search.js";const A="2024-11-05",L={name:"chatpanel-history",version:"1.0.0"},I=["ChatPanel holds the USER'S OWN meetings, notes and past chats — transcripts, decisions,","action items, summaries — which usually are NOT in the working directory.","","Keep using all your normal tools. ADDITIONALLY, whenever the user's question touches a",'meeting, call, demo, note, or past conversation ("outcome of the meeting", "what did we','decide", "action items", "notes from yesterday", a person/day/topic in their history),',"ALSO consult ChatPanel — it is the source of truth for that personal history:"," • smart_search — START HERE: give it the question plus 2-4 of your own keyword"," phrasings; it runs them all and fuses the rankings, finding what one query misses."," • search_history — one exact keyword query, when you already know the terms. Search by"," CONTENT (not the generic meeting title). Supports filters:",' type (chat|meeting|note), since/before (dates or relative like "7d", "yesterday"),'," and limit/offset paging. Returns compact snippets, not full bodies."," • get_record — the full text of one result id; use maxChars/offset to page a long"," transcript instead of pulling it all into context."," • find_related — follow the graph: given a record id, the records most connected to it.","","ChatPanel also holds the user's MEMORY — a short list of durable facts about them (their","name, how they want answers written, what they are working on) that applies to EVERY task,","not just ones about their history:"," • recall — call it EARLY in a session, and whenever the user states a preference, to see"," what is already known. Then simply follow it; do not tell them you looked.",' • remember — save a new durable fact when they state one ("call me Alex", "always use',' pnpm"). One short sentence. Not for task details or anything true only today.'," • forget — remove one when they say it no longer holds.","Prefer these for the user's history and combine them with your other tools as you see fit.","Every result states how fresh the local copy is; if something recent is missing it may not","have synced yet — say so rather than concluding it does not exist.","","ChatPanel also runs SMALL LOCAL MODELS and a private web search on this machine:"," • decide — a sentiment, tone, urgency, spam/complaint, yes/no or pick-one judgement over"," text you already hold, answered with a probability per option in milliseconds. Call it"," instead of judging the text yourself."," • rerank — order many candidates (search hits, comments, sections) by relevance to a"," question, best first with a score, instead of reading them all."," • web_search — the user's own search (their SearXNG when one runs here), results with"," the top pages already read. Nothing leaves this machine but the query."].join(`
2
- `);let u="unknown";function $(n){try{const e=S();fetch(`${p()}/v1/observability/access`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(n)}).catch(()=>{})}catch{}}function p(){const n=process.env.CHATPANEL_GATEWAY_URL;if(n)return n.replace(/\/+$/,"");let e=4320;try{e=f().port||4320}catch{}return`http://127.0.0.1:${e}`}function v(){try{return String(f().bridge?.url||"http://127.0.0.1:4319").replace(/\/+$/,"")}catch{return"http://127.0.0.1:4319"}}function M(){try{return b(f().bridge?.token||"")}catch{return b("")}}async function y(n){const e=M(),s=await fetch(v()+n,{headers:{Accept:"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}),t=await s.json().catch(()=>({}));if(!s.ok||t.ok===!1)throw new Error(t?.error||`bridge ${s.status}`);return t}const D=[{name:"smart_search",description:'BEST first choice for a question about the user\'s ChatPanel history (meetings, notes, past chats). Ask it a natural-language QUESTION and it expands that into several complementary keyword queries, runs them all, and fuses the rankings — which finds things a single query misses, in one round trip instead of several probes. You know the domain, so pass 2-4 of your own phrasings in `queries` too (e.g. for "what did we decide in the Ben demo": ["Ben demo decisions", "tooling demo action items", "demo outcome next steps"]). Supports the same filters as search_history (type, since, before) and returns snippets with each result\'s id; follow up with get_record for the full text or find_related to expand around a hit. BRIEFS come first when they match: a brief is a maintained page about one person, project or topic, derived from ALL the records that mention it, with every claim citing its record — so for "what do we know about X" read the brief, then open only the records it cites.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in natural language."},queries:{type:"array",items:{type:"string"},description:"Your own 2-4 keyword formulations of it — these lead the search."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a window like "7d"/"yesterday".'},before:{type:"string",description:"Latest date: a date or window like `since`."},limit:{type:"number",description:"Max fused results (default 10)."}},required:["question"]}},{name:"search_history",description:'Search the user\'s ChatPanel history — their past chats, meeting/call transcripts, and notes — by keyword relevance. Consult this (in ADDITION to your other tools) whenever the question touches a meeting, call, demo, note, or past conversation: "outcome of the meeting", "what did we decide", "action items", "what did <person> say", "notes from yesterday". Filters: `type` (chat|meeting|note), `since`/`before` (a date like 2026-08-01 or a relative window like "7d"/"yesterday"), and `limit`/`offset` for paging. Returns compact SNIPPETS (the matching excerpt) with each record\'s id/title/type/date — token-friendly; call get_record for the full text and find_related to follow connections. This is a LOCAL WARM COPY that syncs from ChatPanel; very recent items may not be here yet — results report how current the index is, so if something is missing it likely has not synced. Meeting titles are often generic ("Zoom Meeting"), so search by CONTENT, not the title.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Content keywords (topics, names, decisions) — not the meeting title."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a relative window like "7d", "2 weeks", "yesterday".'},before:{type:"string",description:"Latest date: a date or relative window like `since`."},limit:{type:"number",description:"Max results (default 10)."},offset:{type:"number",description:"Skip N results for paging (default 0)."}},required:["query"]}},{name:"get_record",description:"Fetch one history record's full text by id (chat:<id>, meeting:<id>, note:<id> from search_history). For a long transcript, page it with maxChars + offset instead of pulling it all into context — the result says how many chars remain.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Record id such as chat:abc, meeting:imp_123, or note:xyz."},maxChars:{type:"number",description:"Return at most this many characters (token management for long transcripts)."},offset:{type:"number",description:"Start at this character offset — page through with the offset the previous call reports."}},required:["id"]}},{name:"find_related",description:"Graph navigation: given a record id (from search_history), return the records most connected to it by shared content — the meetings/notes/chats about the same topic, people or thread. Use it to expand from one hit to the surrounding context instead of re-searching.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The record id to find neighbours of."},limit:{type:"number",description:"Max related records (default 5)."}},required:["id"]}},{name:"list_history",description:"List history records (newest first) with their id, title, type and date — no bodies. Reports how current this warm copy is (its newest record). Use to see the index horizon and browse/page the corpus.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max items (default 50)."},offset:{type:"number",description:"Skip N items for paging (default 0)."}}}},{name:"list_briefs",description:`The BRIEFS ChatPanel maintains — one page per person, project or topic that appears across enough records, each claim citing the record it came from. This is the index of what the user's corpus KNOWS, as opposed to what it merely contains: read it before asking "what do we know about X", then get_brief for the one you need. Briefs are rebuilt from the records, so they are as current as the last rebuild (dates shown).`,inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max briefs (default 50)."},offset:{type:"number",description:"Skip N for paging (default 0)."}}}},{name:"get_brief",description:"One brief as STRUCTURE: the subject, its other spellings, and each claim with the record ids it cites — so you can cite the record rather than the synthesis, and open only what you need with get_record. Prefer this over get_record for a brief:… id; get_record returns the same text as prose.",inputSchema:{type:"object",properties:{id:{type:"string",description:"A brief id (brief:…) from list_briefs or search results."}},required:["id"]}},{name:"recall",description:"What ChatPanel already knows about the USER — their name, how they want answers written, their ongoing work and environment. Short and cheap; call it at the START of a session and whenever the user states a preference, then just FOLLOW what it returns without announcing that you checked. Pass the current task in `text` and it also returns the facts relevant to that task, not only the always-on ones. This is memory, not history: for what was said in a meeting or a past chat use smart_search instead.",inputSchema:{type:"object",properties:{text:{type:"string",description:"What the user is asking about right now, so task-relevant facts come back too. Omit for just the always-on ones."}}}},{name:"remember",description:`Save a durable fact about the USER to ChatPanel, carried into every future session on every model and agent — the side panel, other CLIs, everything. Use it the moment they state a standing preference ("always use pnpm"), an identity fact ("call me Alex") or a constraint that will still be true next week. Do NOT use it for task details, anything obvious from the current work, or notes about a codebase — those belong in the repo. One short self-contained sentence, written in the third person. Saving is a change to the user's own data, so say in a short clause what you saved.`,inputSchema:{type:"object",properties:{text:{type:"string",description:'The fact, one short sentence in the third person ("Prefers pnpm over npm"). Max 280 characters.'},kind:{type:"string",enum:k,description:k.map(n=>`${n}: ${N[n].hint}`).join(" ")},tags:{type:"array",items:{type:"string"},description:"Optional short tags for grouping."}},required:["text"]}},{name:"forget",description:'Remove a memory from ChatPanel when the user says it no longer holds. Name it however they did ("the Frankfurt thing") or pass the id from recall — it matches on meaning, and tells you exactly what it removed.',inputSchema:{type:"object",properties:{query:{type:"string",description:"The memory to remove: its text, roughly how the user named it, or its id."}},required:["query"]}},{name:"list_skills",description:"List the reusable skills installed on this machine (via the ChatPanel bridge) — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes) and any configured folder. Returns each skill's name and one-line description. Call open_skill to load the one that fits the task.",inputSchema:{type:"object",properties:{}}},{name:"open_skill",description:"Load one skill's full instructions by name (from list_skills), then follow them. If the instructions point at reference files, read one with read_skill_file.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name from list_skills."}},required:["name"]}},{name:"read_skill_file",description:"Read one reference file a skill's instructions point at (any path inside the skill's own folder). Use only when the task needs it.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name."},path:{type:"string",description:"The reference path as written in the instructions, e.g. references/auth.md."}},required:["name","path"]}}],x={[R]:" To have one: ChatPanel › Settings › Runtime › OpenDecision › Start (or a server that provides `decide` under Models).",[q]:" To have one: ChatPanel › Settings › Runtime › Reranker › Start (or a server that provides `rerank` under Models)."};function _(){const n=p(),e=r=>[{id:"gateway",name:"the gateway",url:`${n}${r}`,where:"this device"}],s=j({providers:{decide:e("/v1/decide"),rerank:e("/v1/rerank")},fetch:(r,o)=>fetch(r,o)}),t=P({search:async r=>{const o=await h("/v1/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({q:r,limit:8,read:E.aliasRead})});return{query:r,engines:o.engines||[],results:(o.results||[]).map((i,a)=>({rank:a+1,title:i.title||i.url,url:i.url,engine:i.engine||"",text:i.read?.markdown||i.read?.text||i.snippet||""}))}}});return[s,t]}const U=_().flatMap(n=>n.specs.map(e=>({name:e.name,description:e.description,inputSchema:e.parameters})));async function B(n,e){const s=_().find(o=>o.specs.some(i=>i.name===n));if(!s)return null;const t=await s.execute(n,e);let r=typeof t=="string"?t:String(t?.text??t);return x[n]&&/^No (decision model|reranker) answered/.test(r)&&(r+=x[n]),r}function g(n,e){if(!n)return`Index: ${e} records (warm copy synced from ChatPanel).`;const s=new Date(n),t=`${s.getFullYear()}-${String(s.getMonth()+1).padStart(2,"0")}-${String(s.getDate()).padStart(2,"0")} ${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`;return`Index: ${e} records, current through ${t} (local warm copy — items newer than this may not have synced from ChatPanel yet).`}function O(){try{const n=S();return n?{Authorization:`Bearer ${n}`}:{}}catch{return{}}}async function h(n,e){let s;try{s=await fetch(p()+n,e)}catch(r){throw new Error(`the ChatPanel gateway is not running at ${p()} — start it with "chatpanel-gateway --install" (or run "chatpanel-gateway"), then retry. [${r.message}]`)}const t=await s.json().catch(()=>({}));if(!s.ok)throw new Error(t?.error?.message||`the gateway returned HTTP ${s.status} for ${n}`);return t}function m(n){if(n==null||n==="")return null;if(typeof n=="number")return n;const e=String(n).trim().toLowerCase(),s=864e5;if(e==="today")return Date.now()-s;if(e==="yesterday")return Date.now()-2*s;const t=/^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(e);if(t){const o=Number(t[1]),i=t[2][0],a=i==="d"?s:i==="w"?7*s:i==="m"?30*s:365*s;return Date.now()-o*a}const r=Date.parse(e);return Number.isNaN(r)?null:r}const w=(n,e)=>`${e+1}. [${n.id}] ${n.title||"(untitled)"} · ${n.type}${n.date?" · "+new Date(n.date).toISOString().slice(0,10):""}${n.snippet?`
3
- ${n.snippet}`:""}`;async function F(n,e={}){const s=await B(n,e);if(s!=null)return s;if(n==="smart_search"){const t={question:String(e.question||""),queries:Array.isArray(e.queries)?e.queries.map(String):[],limit:Number(e.limit)||10};e.type&&(t.type=String(e.type));const r=m(e.since);r!=null&&(t.since=r);const o=m(e.before);o!=null&&(t.before=o);const i=await h("/v1/history/smart-search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),a=i.results||[],c=g(i.newest,i.size),l=(i.queries||[]).map(d=>`"${d}"`).join(", ");return a.length?[c,"",`${a.length} result(s) for "${e.question}" — searched ${i.queries.length} way(s): ${l}`,...a.map((d,C)=>`${w(d,C)}${d.foundBy?.length>1?`
4
- (matched ${d.foundBy.length} of the queries)`:""}`)].join(`
1
+ import{loadConfig as y}from"./config.js";import{VERSION as w}from"./version.js";import{readBridgeToken as x}from"./bridge.js";import{ensureGatewayToken as b}from"./gateway-token.js";import{MEMORY_KINDS as j,MEMORY_KIND_NAMES as _}from"./memory.js";import{parseBriefText as A}from"./knowledge.js";import{capabilityToolsProvider as q,DECIDE_TOOL_NAME as I,RERANK_TOOL_NAME as L}from"./capability-tools.js";import{webSearchToolProvider as M}from"./web-search-tool.js";import{SEARCH_DEFAULTS as D}from"./retrieval/search.js";import{askToolsFor as T,callAsk as U}from"./mcp-ask.js";import{CAPABILITY_TOOLS as B,callCapability as H}from"./mcp-capabilities.js";const Y="2024-11-05",F={name:"chatpanel-history",version:w},W=["ChatPanel holds the USER'S OWN meetings, notes and past chats — transcripts, decisions,","action items, summaries — which usually are NOT in the working directory.","","Keep using all your normal tools. ADDITIONALLY, whenever the user's question touches a",'meeting, call, demo, note, or past conversation ("outcome of the meeting", "what did we','decide", "action items", "notes from yesterday", a person/day/topic in their history),',"ALSO consult ChatPanel — it is the source of truth for that personal history:"," • smart_search — START HERE: give it the question plus 2-4 of your own keyword"," phrasings; it runs them all and fuses the rankings, finding what one query misses."," • search_history — one exact keyword query, when you already know the terms. Search by"," CONTENT (not the generic meeting title). Supports filters:",' type (chat|meeting|note), since/before (dates or relative like "7d", "yesterday"),'," and limit/offset paging. Returns compact snippets, not full bodies."," • get_record — the full text of one result id; use maxChars/offset to page a long"," transcript instead of pulling it all into context."," • find_related — follow the graph: given a record id, the records most connected to it.","","ChatPanel also holds the user's MEMORY — a short list of durable facts about them (their","name, how they want answers written, what they are working on) that applies to EVERY task,","not just ones about their history:"," • recall — call it EARLY in a session, and whenever the user states a preference, to see"," what is already known. Then simply follow it; do not tell them you looked.",' • remember — save a new durable fact when they state one ("call me Alex", "always use',' pnpm"). One short sentence. Not for task details or anything true only today.'," • forget — remove one when they say it no longer holds.","Prefer these for the user's history and combine them with your other tools as you see fit.","Every result states how fresh the local copy is; if something recent is missing it may not","have synced yet — say so rather than concluding it does not exist.","","ChatPanel also runs SMALL LOCAL MODELS and a private web search on this machine:"," • decide — a sentiment, tone, urgency, spam/complaint, yes/no or pick-one judgement over"," text you already hold, answered with a probability per option in milliseconds. Call it"," instead of judging the text yourself."," • rerank — order many candidates (search hits, comments, sections) by relevance to a"," question, best first with a score, instead of reading them all."," • web_search — the user's own search (their SearXNG when one runs here), results with"," the top pages already read. Nothing leaves this machine but the query."," • redact_check — what is personal or secret in a piece of text, found by the detector on"," THIS machine. Call it before you put someone else's data into your own context, a"," commit message, an issue or a message to a third party — and whenever the user asks"," what is sensitive in something. It tells you what it could not see, so read that line."," • read_document — a URL as clean markdown through the user's own reader and cache,"," for a fraction of the context raw HTML would cost.","","ChatPanel can also hand a question to ANOTHER MODEL on this machine and give you its answer:"," • list_models — what can answer, and WHERE each one runs (on this device / a cloud)."," • ask_model — ask one. Use it for a second opinion on your own reasoning, for a model",' stronger in some domain, when the user names a model ("ask Claude what it thinks"), or'," when they want a question kept on-device — pick a `device` model and nothing leaves the"," machine. The model you ask sees your prompt and NOTHING else: no files, no shell, no web."," So paste in the code or context it needs. A slow answer returns a job id for ask_status."].join(`
2
+ `);async function z(){try{const t=await fetch(`${f()}/health`,{signal:AbortSignal.timeout(600)}),e=String((await t.json())?.version||"");return!e||e===w?"":["",`IMPORTANT — VERSION MISMATCH. This MCP server is ChatPanel ${w}, but the gateway`,`running on this machine is ${e}. They are different installs: your client launched`,"whichever `chatpanel-gateway` is on its PATH, and it is not the one the user is running.","The practical effect is that TOOLS MAY BE MISSING here — a newer gateway has tools this","server does not advertise. If a ChatPanel tool the user expects is not in your list, this","is why. Tell them, and tell them the fix: point the MCP config at the newer executable","(or update the older install so both are the same version)."].join(`
3
+ `)}catch{return""}}function k(){try{return y().mcp?.ask||{}}catch{return{}}}let m="unknown";function C(t){try{const e=b();fetch(`${f()}/v1/observability/access`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(t)}).catch(()=>{})}catch{}}function f(){const t=process.env.CHATPANEL_GATEWAY_URL;if(t)return t.replace(/\/+$/,"");let e=4320;try{e=y().port||4320}catch{}return`http://127.0.0.1:${e}`}function O(){try{return String(y().bridge?.url||"http://127.0.0.1:4319").replace(/\/+$/,"")}catch{return"http://127.0.0.1:4319"}}function J(){try{return x(y().bridge?.token||"")}catch{return x("")}}async function S(t){const e=J(),i=await fetch(O()+t,{headers:{Accept:"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}),a=await i.json().catch(()=>({}));if(!i.ok||a.ok===!1)throw new Error(a?.error||`bridge ${i.status}`);return a}const G=[{name:"smart_search",description:'BEST first choice for a question about the user\'s ChatPanel history (meetings, notes, past chats). Ask it a natural-language QUESTION and it expands that into several complementary keyword queries, runs them all, and fuses the rankings — which finds things a single query misses, in one round trip instead of several probes. You know the domain, so pass 2-4 of your own phrasings in `queries` too (e.g. for "what did we decide in the Ben demo": ["Ben demo decisions", "tooling demo action items", "demo outcome next steps"]). Supports the same filters as search_history (type, since, before) and returns snippets with each result\'s id; follow up with get_record for the full text or find_related to expand around a hit. BRIEFS come first when they match: a brief is a maintained page about one person, project or topic, derived from ALL the records that mention it, with every claim citing its record — so for "what do we know about X" read the brief, then open only the records it cites.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in natural language."},queries:{type:"array",items:{type:"string"},description:"Your own 2-4 keyword formulations of it — these lead the search."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a window like "7d"/"yesterday".'},before:{type:"string",description:"Latest date: a date or window like `since`."},limit:{type:"number",description:"Max fused results (default 10)."}},required:["question"]}},{name:"search_history",description:'Search the user\'s ChatPanel history — their past chats, meeting/call transcripts, and notes — by keyword relevance. Consult this (in ADDITION to your other tools) whenever the question touches a meeting, call, demo, note, or past conversation: "outcome of the meeting", "what did we decide", "action items", "what did <person> say", "notes from yesterday". Filters: `type` (chat|meeting|note), `since`/`before` (a date like 2026-08-01 or a relative window like "7d"/"yesterday"), and `limit`/`offset` for paging. Returns compact SNIPPETS (the matching excerpt) with each record\'s id/title/type/date — token-friendly; call get_record for the full text and find_related to follow connections. This is a LOCAL WARM COPY that syncs from ChatPanel; very recent items may not be here yet — results report how current the index is, so if something is missing it likely has not synced. Meeting titles are often generic ("Zoom Meeting"), so search by CONTENT, not the title.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Content keywords (topics, names, decisions) — not the meeting title."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a relative window like "7d", "2 weeks", "yesterday".'},before:{type:"string",description:"Latest date: a date or relative window like `since`."},limit:{type:"number",description:"Max results (default 10)."},offset:{type:"number",description:"Skip N results for paging (default 0)."}},required:["query"]}},{name:"get_record",description:"Fetch one history record's full text by id (chat:<id>, meeting:<id>, note:<id> from search_history). For a long transcript, page it with maxChars + offset instead of pulling it all into context — the result says how many chars remain.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Record id such as chat:abc, meeting:imp_123, or note:xyz."},maxChars:{type:"number",description:"Return at most this many characters (token management for long transcripts)."},offset:{type:"number",description:"Start at this character offset — page through with the offset the previous call reports."}},required:["id"]}},{name:"find_related",description:"Graph navigation: given a record id (from search_history), return the records most connected to it by shared content — the meetings/notes/chats about the same topic, people or thread. Use it to expand from one hit to the surrounding context instead of re-searching.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The record id to find neighbours of."},limit:{type:"number",description:"Max related records (default 5)."}},required:["id"]}},{name:"list_history",description:"List history records (newest first) with their id, title, type and date — no bodies. Reports how current this warm copy is (its newest record). Use to see the index horizon and browse/page the corpus.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max items (default 50)."},offset:{type:"number",description:"Skip N items for paging (default 0)."}}}},{name:"list_briefs",description:`The BRIEFS ChatPanel maintains — one page per person, project or topic that appears across enough records, each claim citing the record it came from. This is the index of what the user's corpus KNOWS, as opposed to what it merely contains: read it before asking "what do we know about X", then get_brief for the one you need. Briefs are rebuilt from the records, so they are as current as the last rebuild (dates shown).`,inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max briefs (default 50)."},offset:{type:"number",description:"Skip N for paging (default 0)."}}}},{name:"get_brief",description:"One brief as STRUCTURE: the subject, its other spellings, and each claim with the record ids it cites — so you can cite the record rather than the synthesis, and open only what you need with get_record. Prefer this over get_record for a brief:… id; get_record returns the same text as prose.",inputSchema:{type:"object",properties:{id:{type:"string",description:"A brief id (brief:…) from list_briefs or search results."}},required:["id"]}},{name:"recall",description:"What ChatPanel already knows about the USER — their name, how they want answers written, their ongoing work and environment. Short and cheap; call it at the START of a session and whenever the user states a preference, then just FOLLOW what it returns without announcing that you checked. Pass the current task in `text` and it also returns the facts relevant to that task, not only the always-on ones. This is memory, not history: for what was said in a meeting or a past chat use smart_search instead.",inputSchema:{type:"object",properties:{text:{type:"string",description:"What the user is asking about right now, so task-relevant facts come back too. Omit for just the always-on ones."}}}},{name:"remember",description:`Save a durable fact about the USER to ChatPanel, carried into every future session on every model and agent — the side panel, other CLIs, everything. Use it the moment they state a standing preference ("always use pnpm"), an identity fact ("call me Alex") or a constraint that will still be true next week. Do NOT use it for task details, anything obvious from the current work, or notes about a codebase — those belong in the repo. One short self-contained sentence, written in the third person. Saving is a change to the user's own data, so say in a short clause what you saved.`,inputSchema:{type:"object",properties:{text:{type:"string",description:'The fact, one short sentence in the third person ("Prefers pnpm over npm"). Max 280 characters.'},kind:{type:"string",enum:_,description:_.map(t=>`${t}: ${j[t].hint}`).join(" ")},tags:{type:"array",items:{type:"string"},description:"Optional short tags for grouping."}},required:["text"]}},{name:"forget",description:'Remove a memory from ChatPanel when the user says it no longer holds. Name it however they did ("the Frankfurt thing") or pass the id from recall — it matches on meaning, and tells you exactly what it removed.',inputSchema:{type:"object",properties:{query:{type:"string",description:"The memory to remove: its text, roughly how the user named it, or its id."}},required:["query"]}},{name:"list_skills",description:"List the reusable skills installed on this machine (via the ChatPanel bridge) — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes) and any configured folder. Returns each skill's name and one-line description. Call open_skill to load the one that fits the task.",inputSchema:{type:"object",properties:{}}},{name:"open_skill",description:"Load one skill's full instructions by name (from list_skills), then follow them. If the instructions point at reference files, read one with read_skill_file.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name from list_skills."}},required:["name"]}},{name:"read_skill_file",description:"Read one reference file a skill's instructions point at (any path inside the skill's own folder). Use only when the task needs it.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name."},path:{type:"string",description:"The reference path as written in the instructions, e.g. references/auth.md."}},required:["name","path"]}}],N={[I]:" To have one: ChatPanel › Settings › Runtime › OpenDecision › Start (or a server that provides `decide` under Models).",[L]:" To have one: ChatPanel › Settings › Runtime › Reranker › Start (or a server that provides `rerank` under Models)."};function E(){const t=f(),e=c=>[{id:"gateway",name:"the gateway",url:`${t}${c}`,where:"this device"}],i=q({providers:{decide:e("/v1/decide"),rerank:e("/v1/rerank")},fetch:(c,o)=>fetch(c,o)}),a=M({search:async c=>{const o=await l("/v1/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({q:c,limit:8,read:D.aliasRead})});return{query:c,engines:o.engines||[],results:(o.results||[]).map((n,r)=>({rank:r+1,title:n.title||n.url,url:n.url,engine:n.engine||"",text:n.read?.markdown||n.read?.text||n.snippet||""}))}}});return[i,a]}const V=E().flatMap(t=>t.specs.map(e=>({name:e.name,description:e.description,inputSchema:e.parameters})));async function K(t,e){const i=E().find(o=>o.specs.some(n=>n.name===t));if(!i)return null;const a=await i.execute(t,e);let c=typeof a=="string"?a:String(a?.text??a);return N[t]&&/^No (decision model|reranker) answered/.test(c)&&(c+=N[t]),c}function $(t,e){if(!t)return`Index: ${e} records (warm copy synced from ChatPanel).`;const i=new Date(t),a=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(i.getDate()).padStart(2,"0")} ${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}`;return`Index: ${e} records, current through ${a} (local warm copy — items newer than this may not have synced from ChatPanel yet).`}function R(){try{const t=b();return t?{Authorization:`Bearer ${t}`}:{}}catch{return{}}}async function l(t,e){let i;try{i=await fetch(f()+t,e)}catch(c){throw new Error(`the ChatPanel gateway is not running at ${f()} — start it with "chatpanel-gateway --install" (or run "chatpanel-gateway"), then retry. [${c.message}]`)}const a=await i.json().catch(()=>({}));if(!i.ok)throw new Error(a?.error?.message||`the gateway returned HTTP ${i.status} for ${t}`);return a}function g(t){if(t==null||t==="")return null;if(typeof t=="number")return t;const e=String(t).trim().toLowerCase(),i=864e5;if(e==="today")return Date.now()-i;if(e==="yesterday")return Date.now()-2*i;const a=/^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(e);if(a){const o=Number(a[1]),n=a[2][0],r=n==="d"?i:n==="w"?7*i:n==="m"?30*i:365*i;return Date.now()-o*r}const c=Date.parse(e);return Number.isNaN(c)?null:c}const v=(t,e)=>`${e+1}. [${t.id}] ${t.title||"(untitled)"} · ${t.type}${t.date?" · "+new Date(t.date).toISOString().slice(0,10):""}${t.snippet?`
4
+ ${t.snippet}`:""}`;async function X(t,e={}){const i=await K(t,e);if(i!=null)return i;const a=await H(t,e,{gatewayJson:l});if(a!=null)return a;const c=await U(t,e,{baseUrl:f,gatewayJson:l,token:()=>{try{return b()}catch{return""}},client:()=>m,askConfig:k});if(c!=null)return c;if(t==="smart_search"){const o={question:String(e.question||""),queries:Array.isArray(e.queries)?e.queries.map(String):[],limit:Number(e.limit)||10};e.type&&(o.type=String(e.type));const n=g(e.since);n!=null&&(o.since=n);const r=g(e.before);r!=null&&(o.before=r);const s=await l("/v1/history/smart-search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),h=s.results||[],d=$(s.newest,s.size),u=(s.queries||[]).map(p=>`"${p}"`).join(", ");return h.length?[d,"",`${h.length} result(s) for "${e.question}" — searched ${s.queries.length} way(s): ${u}`,...h.map((p,P)=>`${v(p,P)}${p.foundBy?.length>1?`
5
+ (matched ${p.foundBy.length} of the queries)`:""}`)].join(`
5
6
  `)+`
6
7
 
7
8
  get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.question}".
8
- Searched ${i.queries?.length||0} way(s): ${l}.
9
- ${c}
10
- If you expected a recent item it may not have synced yet — check ChatPanel directly, or try different keywords (meeting titles are often generic).`}if(n==="search_history"){const t={query:String(e.query||""),limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0)};e.type&&(t.type=String(e.type));const r=m(e.since);r!=null&&(t.since=r);const o=m(e.before);o!=null&&(t.before=o);const i=await h("/v1/history/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),a=i.results||[],c=g(i.newest,i.size),l=[e.type&&`type=${e.type}`,e.since&&`since=${e.since}`,e.before&&`before=${e.before}`].filter(Boolean).join(", "),d=l?` (${l})`:"";return a.length?[c,"",`${a.length} result(s) for "${e.query}"${d}:`,...a.map(w)].join(`
9
+ Searched ${s.queries?.length||0} way(s): ${u}.
10
+ ${d}
11
+ If you expected a recent item it may not have synced yet — check ChatPanel directly, or try different keywords (meeting titles are often generic).`}if(t==="search_history"){const o={query:String(e.query||""),limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0)};e.type&&(o.type=String(e.type));const n=g(e.since);n!=null&&(o.since=n);const r=g(e.before);r!=null&&(o.before=r);const s=await l("/v1/history/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),h=s.results||[],d=$(s.newest,s.size),u=[e.type&&`type=${e.type}`,e.since&&`since=${e.since}`,e.before&&`before=${e.before}`].filter(Boolean).join(", "),p=u?` (${u})`:"";return h.length?[d,"",`${h.length} result(s) for "${e.query}"${p}:`,...h.map(v)].join(`
11
12
  `)+`
12
13
 
13
- get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.query}"${d}.
14
- ${c}
15
- If you expected a recent item, it may not have synced yet — check ChatPanel directly, or broaden the query (titles are often generic; try content keywords, or drop a filter).`}if(n==="get_record"){const t=new URLSearchParams({id:String(e.id||"")});e.maxChars!=null&&t.set("maxChars",String(Math.max(1,Number(e.maxChars)||0))),e.offset!=null&&t.set("offset",String(Math.max(0,Number(e.offset)||0)));const o=(await h(`/v1/history/get?${t}`)).record,i=`[${o.id}] ${o.title||"(untitled)"} · ${o.type}${o.date?" · "+new Date(o.date).toISOString().slice(0,10):""}`,a=o.truncated?`
14
+ get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.query}"${p}.
15
+ ${d}
16
+ If you expected a recent item, it may not have synced yet — check ChatPanel directly, or broaden the query (titles are often generic; try content keywords, or drop a filter).`}if(t==="get_record"){const o=new URLSearchParams({id:String(e.id||"")});e.maxChars!=null&&o.set("maxChars",String(Math.max(1,Number(e.maxChars)||0))),e.offset!=null&&o.set("offset",String(Math.max(0,Number(e.offset)||0)));const r=(await l(`/v1/history/get?${o}`)).record,s=`[${r.id}] ${r.title||"(untitled)"} · ${r.type}${r.date?" · "+new Date(r.date).toISOString().slice(0,10):""}`,h=r.truncated?`
16
17
 
17
- [showing ${o.text.length} of ${o.totalChars} chars (from offset ${o.offset}). For the next part call get_record again with offset=${o.offset+o.text.length}.]`:"";return`${i}
18
+ [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`${s}
18
19
 
19
- ${o.text||"(empty)"}${a}`}if(n==="find_related"){const r=(await h(`/v1/history/related?id=${encodeURIComponent(String(e.id||""))}&limit=${Number(e.limit)||5}`)).results||[];return r.length?[`Records related to ${e.id}:`,...r.map(w)].join(`
20
+ ${r.text||"(empty)"}${h}`}if(t==="find_related"){const n=(await l(`/v1/history/related?id=${encodeURIComponent(String(e.id||""))}&limit=${Number(e.limit)||5}`)).results||[];return n.length?[`Records related to ${e.id}:`,...n.map(v)].join(`
20
21
  `)+`
21
22
 
22
- get_record <id> for full text.`:`Nothing related to ${e.id} found (or that id isn't in the warm index — run search_history first to get a valid id).`}if(n==="list_history"){const t=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0)}),r=await h(`/v1/history/list?${t}`),o=r.items||[];if(!o.length)return"History is empty (or the gateway has not been seeded yet — open ChatPanel with warm sync enabled).";const i=o[0]?.date||null;return[g(i,r.total),"",`${o.length} of ${r.total} records:`,...o.map(a=>`[${a.id}] ${a.title||"(untitled)"} · ${a.type}${a.date?" · "+new Date(a.date).toISOString().slice(0,10):""} · ${a.chars} chars`)].join(`
23
- `)}if(n==="list_briefs"){const t=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0),type:"brief"}),r=await h(`/v1/history/list?${t}`),o=r.items||[];return o.length?[`${o.length} of ${r.total} briefs (each is a page about one subject, with every claim cited):`,...o.map(i=>`[${i.id}] ${i.title||"(untitled)"}${i.date?" · rebuilt "+new Date(i.date).toISOString().slice(0,10):""}`)].join(`
23
+ 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(t==="list_history"){const o=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0)}),n=await l(`/v1/history/list?${o}`),r=n.items||[];if(!r.length)return"History is empty (or the gateway has not been seeded yet — open ChatPanel with warm sync enabled).";const s=r[0]?.date||null;return[$(s,n.total),"",`${r.length} of ${n.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(`
24
+ `)}if(t==="list_briefs"){const o=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0),type:"brief"}),n=await l(`/v1/history/list?${o}`),r=n.items||[];return r.length?[`${r.length} of ${n.total} briefs (each is a page about one subject, with every claim cited):`,...r.map(s=>`[${s.id}] ${s.title||"(untitled)"}${s.date?" · rebuilt "+new Date(s.date).toISOString().slice(0,10):""}`)].join(`
24
25
  `)+`
25
26
 
26
- get_brief <id> for its claims and the records they cite.`:`No briefs yet. ChatPanel builds them from the user's records on the Briefs page; if that has run, the user may have "share briefs with local agents" switched off.`}if(n==="get_brief"){const t=String(e.id||""),o=(await h(`/v1/history/get?${new URLSearchParams({id:t})}`)).record,i=T(o?.text);if(!i)return`${t} is not a brief (type ${o?.type||"unknown"}). Use get_record for it, or list_briefs for the brief ids.`;const a=[`BRIEF ${t} — ${i.name} (${i.kind})${i.aliases.length?` · also known as ${i.aliases.join(", ")}`:""}`,""];a.push(`${i.claims.length} claim(s), each with the records it cites:`);for(const c of i.claims)a.push(`• ${c.text}`),c.refs.length&&a.push(` cites: ${c.refs.map(l=>`${l.kind}:${l.id}`).join(", ")}`);return i.records.length&&a.push("",`Built from ${i.records.length} record(s) (most recent first): ${i.records.slice(0,12).map(c=>c.title).join(" · ")}${i.records.length>12?" …":""}`),a.push("","get_record <kind:id> opens a cited record; find_related <id> follows its connections."),a.join(`
27
- `)}if(n==="recall"){const t=await h("/v1/memory/recall",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:String(e.text||"")})});return t.memories?.length?t.block:t.size?"Nothing in ChatPanel memory applies here.":"ChatPanel memory is empty — nothing is known about this user yet. Use `remember` when they state something durable about themselves or how they want to work."}if(n==="remember"){const t=String(e.text||"").trim();if(!t)return"remember needs `text` — one short sentence about the user.";const r=await h("/v1/memory/remember",{method:"POST",headers:{"content-type":"application/json",...O()},body:JSON.stringify({text:t,kind:e.kind?String(e.kind):"fact",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:"mcp",surface:"mcp",agent:u}})});return r.action==="duplicate"?`Already known: "${r.record.text}" — nothing changed.`:r.action==="update"?`Updated memory to "${r.record.text}" (was "${r.replaced?.text}"). It applies to every future session.`:`Remembered: "${r.record.text}". It applies to every future ChatPanel session, on every model.`}if(n==="forget"){const t=String(e.query||"").trim();if(!t)return"forget needs `query` — the memory to remove.";const r=await h("/v1/memory/forget",{method:"POST",headers:{"content-type":"application/json",...O()},body:JSON.stringify({query:t})});return r.removed?.length?`Forgot: ${r.removed.map(o=>`"${o.text}"`).join(", ")}.`:`No memory matches "${t}". Call recall to see what is stored.`}if(n==="list_skills"){let t;try{t=await y("/skills")}catch(o){return`Installed skills are unavailable because the ChatPanel bridge is not running at ${v()}. Install/start it with:
27
+ get_brief <id> for its claims and the records they cite.`:`No briefs yet. ChatPanel builds them from the user's records on the Briefs page; if that has run, the user may have "share briefs with local agents" switched off.`}if(t==="get_brief"){const o=String(e.id||""),r=(await l(`/v1/history/get?${new URLSearchParams({id:o})}`)).record,s=A(r?.text);if(!s)return`${o} is not a brief (type ${r?.type||"unknown"}). Use get_record for it, or list_briefs for the brief ids.`;const h=[`BRIEF ${o} — ${s.name} (${s.kind})${s.aliases.length?` · also known as ${s.aliases.join(", ")}`:""}`,""];h.push(`${s.claims.length} claim(s), each with the records it cites:`);for(const d of s.claims)h.push(`• ${d.text}`),d.refs.length&&h.push(` cites: ${d.refs.map(u=>`${u.kind}:${u.id}`).join(", ")}`);return s.records.length&&h.push("",`Built from ${s.records.length} record(s) (most recent first): ${s.records.slice(0,12).map(d=>d.title).join(" · ")}${s.records.length>12?" …":""}`),h.push("","get_record <kind:id> opens a cited record; find_related <id> follows its connections."),h.join(`
28
+ `)}if(t==="recall"){const o=await l("/v1/memory/recall",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:String(e.text||"")})});return o.memories?.length?o.block:o.size?"Nothing in ChatPanel memory applies here.":"ChatPanel memory is empty — nothing is known about this user yet. Use `remember` when they state something durable about themselves or how they want to work."}if(t==="remember"){const o=String(e.text||"").trim();if(!o)return"remember needs `text` — one short sentence about the user.";const n=await l("/v1/memory/remember",{method:"POST",headers:{"content-type":"application/json",...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 n.action==="duplicate"?`Already known: "${n.record.text}" — nothing changed.`:n.action==="update"?`Updated memory to "${n.record.text}" (was "${n.replaced?.text}"). It applies to every future session.`:`Remembered: "${n.record.text}". It applies to every future ChatPanel session, on every model.`}if(t==="forget"){const o=String(e.query||"").trim();if(!o)return"forget needs `query` — the memory to remove.";const n=await l("/v1/memory/forget",{method:"POST",headers:{"content-type":"application/json",...R()},body:JSON.stringify({query:o})});return n.removed?.length?`Forgot: ${n.removed.map(r=>`"${r.text}"`).join(", ")}.`:`No memory matches "${o}". Call recall to see what is stored.`}if(t==="list_skills"){let o;try{o=await S("/skills")}catch(r){return`Installed skills are unavailable because the ChatPanel bridge is not running at ${O()}. Install/start it with:
28
29
  curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash
29
- Then retry. History tools work without the bridge. [${o.message}]`}const r=t.skills||[];return r.length?[`${r.length} skill(s) installed:`,...r.map(o=>`- ${o.command||o.id}: ${o.description||o.name}${o.origin?.source?` (from ${o.origin.source})`:""}`)].join(`
30
+ Then retry. History tools work without the bridge. [${r.message}]`}const n=o.skills||[];return n.length?[`${n.length} skill(s) installed:`,...n.map(r=>`- ${r.command||r.id}: ${r.description||r.name}${r.origin?.source?` (from ${r.origin.source})`:""}`)].join(`
30
31
  `)+`
31
32
 
32
- Use open_skill with a name to load its instructions.`:"No skills installed on this machine yet."}if(n==="open_skill"){let t;try{t=await y(`/skills/${encodeURIComponent(String(e.name||"").trim())}`)}catch(r){return`Could not open "${e.name}": ${r.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return t.skill?.prompt||"(this skill has no extra instructions — just apply it.)"}if(n==="read_skill_file"){const t=encodeURIComponent(String(e.name||"").trim()),r=String(e.path||"").trim().split("/").map(encodeURIComponent).join("/");let o;try{o=await y(`/skills/${t}/file/${r}`)}catch(i){return`Could not read ${e.path}: ${i.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return o.text||"(empty)"}throw new Error(`unknown tool: ${n}`)}async function Y(n){const{id:e,method:s,params:t}=n||{},r=i=>({jsonrpc:"2.0",id:e,result:i}),o=(i,a)=>({jsonrpc:"2.0",id:e,error:{code:i,message:a}});try{switch(s){case"initialize":return u=t?.clientInfo?.name||u,r({protocolVersion:A,capabilities:{tools:{}},serverInfo:L,instructions:I});case"tools/list":return r({tools:[...D,...U]});case"tools/call":{const i=Date.now();try{const a=await F(t?.name,t?.arguments||{});return $({client:u,tool:t?.name,ok:!0,ms:Date.now()-i,args:t?.arguments||{}}),r({content:[{type:"text",text:a}]})}catch(a){throw $({client:u,tool:t?.name,ok:!1,ms:Date.now()-i,args:t?.arguments||{},error:a.message}),a}}case"ping":return r({});default:return typeof s=="string"&&s.startsWith("notifications/")||e===void 0?null:o(-32601,`method not found: ${s}`)}}catch(i){return s==="tools/call"?r({content:[{type:"text",text:`Error: ${i.message}`}],isError:!0}):o(-32603,i.message)}}async function Z(){let n="";process.stdin.setEncoding("utf8");const e=s=>process.stdout.write(JSON.stringify(s)+`
33
- `);for await(const s of process.stdin){n+=s;let t;for(;(t=n.indexOf(`
34
- `))>=0;){const r=n.slice(0,t).trim();if(n=n.slice(t+1),!r)continue;let o;try{o=JSON.parse(r)}catch{continue}const i=await Y(o);i&&e(i)}}}export{Y as handleRpc,Z as runMcpServer};
33
+ Use open_skill with a name to load its instructions.`:"No skills installed on this machine yet."}if(t==="open_skill"){let o;try{o=await S(`/skills/${encodeURIComponent(String(e.name||"").trim())}`)}catch(n){return`Could not open "${e.name}": ${n.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(t==="read_skill_file"){const o=encodeURIComponent(String(e.name||"").trim()),n=String(e.path||"").trim().split("/").map(encodeURIComponent).join("/");let r;try{r=await S(`/skills/${o}/file/${n}`)}catch(s){return`Could not read ${e.path}: ${s.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return r.text||"(empty)"}throw new Error(`unknown tool: ${t}`)}async function Q(t){const{id:e,method:i,params:a}=t||{},c=n=>({jsonrpc:"2.0",id:e,result:n}),o=(n,r)=>({jsonrpc:"2.0",id:e,error:{code:n,message:r}});try{switch(i){case"initialize":{m=a?.clientInfo?.name||m;const n=await z(),r=T(k()).some(s=>s.name==="delegate_task")?`
34
+
35
+ ChatPanel can also DELEGATE a whole piece of work to one of the user's coding agents,
36
+ running here with its own tools in a directory they have allowed:
37
+ • delegate_task — a refactor across many files, a test suite to run and fix, a build to
38
+ diagnose. Unlike ask_model it reads and EDITS files and runs commands, so use it for work
39
+ that belongs on this machine, tell the user what you delegated and where, and expect
40
+ minutes — it returns a job id for ask_status.`:"";return c({protocolVersion:Y,capabilities:{tools:{}},serverInfo:F,instructions:W+r+n})}case"tools/list":return c({tools:[...G,...V,...B,...T(k())]});case"tools/call":{const n=Date.now();try{const r=await X(a?.name,a?.arguments||{});return C({client:m,tool:a?.name,ok:!0,ms:Date.now()-n,args:a?.arguments||{}}),c({content:[{type:"text",text:r}]})}catch(r){throw C({client:m,tool:a?.name,ok:!1,ms:Date.now()-n,args:a?.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(n){return i==="tools/call"?c({content:[{type:"text",text:`Error: ${n.message}`}],isError:!0}):o(-32603,n.message)}}async function de(){let t="";process.stdin.setEncoding("utf8");const e=i=>process.stdout.write(JSON.stringify(i)+`
41
+ `);for await(const i of process.stdin){t+=i;let a;for(;(a=t.indexOf(`
42
+ `))>=0;){const c=t.slice(0,a).trim();if(t=t.slice(a+1),!c)continue;let o;try{o=JSON.parse(c)}catch{continue}const n=await Q(o);n&&e(n)}}}export{Q as handleRpc,de as runMcpServer};
package/src/recruiting.js CHANGED
@@ -1 +1 @@
1
- import{summarize as v}from"./scorecard.js";import{applications as w,evaluatorPrompt as k,parseEvaluation as m,decide as S,recruitEvents as M,engineRows as P,MIN_FIT as A}from"./recruit.js";import{aggregateModelsAsync as D,listDestinations as E}from"./router.js";const F=new Set(["device","trusted","any"]);function $(e){if(!e||e.type==="agent")return"trusted";const s=String(e.baseUrl||"");return/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(:|\/|$)/i.test(s)?"device":/^https?:\/\/(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|[^/]+\.local(:|\/|$))/i.test(s)?"trusted":"any"}async function N(e,s,{jobKind:r=null,minCalls:n,timeoutMs:i=2500}={}){const l=await D(e,{timeoutMs:i}).catch(()=>({data:[]})),p=new Map(E(e).map(t=>[t.id,t])),d=(l.data||[]).map(t=>{const c=t.owned_by==="chatpanel-bridge",u=p.get(t.provider);return{id:t.id,model:t.id,kind:c?"bridge":"api",label:t.model?`${t.provider} · ${t.model}`:t.id,reach:c?"trusted":$(u),capabilities:["tools"],available:t.configured===!1?!1:t.available!==!1}}),a=Object.fromEntries((s?.list?.({minCalls:n})||[]).map(t=>[t.key,t]));return P(d,{cards:a,minCalls:n,jobKind:r})}function O(e){const s=e?.get?.("agents")?.agents?.value;return(Array.isArray(s)?s:[]).filter(r=>r&&r.id&&r.enabled!==!1)}function R(e,s){const r={};for(const n of s){const i=e?.chains?.get?.(n.id);i?.length&&(r[n.id]=v(i))}return r}async function q(e,{cfg:s,prefsStore:r,scorecards:n,engines:i,reach:l="any",chatModel:p=null,now:d=Date.now()}={}){const a=O(r),t=await N(s,i),c=R(n,a),u=F.has(l)?l:"any",f=w(e,a,{summaries:c,rows:t,reach:u,chatModel:p,now:d});return{applications:f,prompt:k(e,f,a,{rows:t}),rows:t.map(o=>({key:o.key,label:o.label,reach:o.reach,quality:o.quality,costPer1k:o.costPer1k,latencyMs:o.latencyMs,available:o.available,observed:o.observed})),poolSize:a.length}}async function G(e,{cfg:s,prefsStore:r,scorecards:n,engines:i,record:l=null,reach:p="any",chatModel:d=null,evaluation:a=null,text:t=null,by:c="evaluator",minFit:u=A,now:f=Date.now()}={}){const{applications:o,prompt:b}=await q(e,{cfg:s,prefsStore:r,scorecards:n,engines:i,reach:p,chatModel:d,now:f});let y=null;t!=null?y=m(String(t),o):a&&typeof a=="object"&&(y=m(JSON.stringify({pick:a.pick,why:a.why,confidence:a.confidence,proposalName:a.proposal?.name,proposalPurpose:a.proposal?.purpose,proposalSkills:a.proposal?.skills,proposalGrants:a.proposal?.grants}),o));const g=S(e,o,{evaluation:y,minFit:u}),h=M(e,o,g,{by:g.by==="evaluator"?c:"fit",at:f,record:l});return{applications:o,evaluation:y,decision:g,events:h,prompt:b}}export{q as applicationsFor,O as poolFrom,G as recruitPass,N as rosterRows,R as summariesFrom};
1
+ import{summarize as h}from"./scorecard.js";import{applications as v,evaluatorPrompt as k,parseEvaluation as g,decide as M,recruitEvents as P,engineRows as S,MIN_FIT as A}from"./recruit.js";import{aggregateModelsAsync as E,listDestinations as F}from"./router.js";import{reachOfGatewayModel as D}from"@chatpanel/events/model-candidates.js";const N=new Set(["device","trusted","any"]);async function O(t,r,{jobKind:s=null,minCalls:n,timeoutMs:i=2500}={}){const l=await E(t,{timeoutMs:i}).catch(()=>({data:[]})),p=new Map(F(t).map(e=>[e.id,e])),c=(l.data||[]).map(e=>{const d=e.owned_by==="chatpanel-bridge",u=p.get(e.provider);return{id:e.id,model:e.id,kind:d?"bridge":"api",label:e.model?`${e.provider} · ${e.model}`:e.id,reach:D(e,u),capabilities:["tools"],available:e.configured===!1?!1:e.available!==!1}}),a=Object.fromEntries((r?.list?.({minCalls:n})||[]).map(e=>[e.key,e]));return S(c,{cards:a,minCalls:n,jobKind:s})}function R(t){const r=t?.get?.("agents")?.agents?.value;return(Array.isArray(r)?r:[]).filter(s=>s&&s.id&&s.enabled!==!1)}function q(t,r){const s={};for(const n of r){const i=t?.chains?.get?.(n.id);i?.length&&(s[n.id]=h(i))}return s}async function z(t,{cfg:r,prefsStore:s,scorecards:n,engines:i,reach:l="any",chatModel:p=null,now:c=Date.now()}={}){const a=R(s),e=await O(r,i),d=q(n,a),u=N.has(l)?l:"any",f=v(t,a,{summaries:d,rows:e,reach:u,chatModel:p,now:c});return{applications:f,prompt:k(t,f,a,{rows:e}),rows:e.map(o=>({key:o.key,label:o.label,reach:o.reach,quality:o.quality,costPer1k:o.costPer1k,latencyMs:o.latencyMs,available:o.available,observed:o.observed})),poolSize:a.length}}async function H(t,{cfg:r,prefsStore:s,scorecards:n,engines:i,record:l=null,reach:p="any",chatModel:c=null,evaluation:a=null,text:e=null,by:d="evaluator",minFit:u=A,now:f=Date.now()}={}){const{applications:o,prompt:b}=await z(t,{cfg:r,prefsStore:s,scorecards:n,engines:i,reach:p,chatModel:c,now:f});let y=null;e!=null?y=g(String(e),o):a&&typeof a=="object"&&(y=g(JSON.stringify({pick:a.pick,why:a.why,confidence:a.confidence,proposalName:a.proposal?.name,proposalPurpose:a.proposal?.purpose,proposalSkills:a.proposal?.skills,proposalGrants:a.proposal?.grants}),o));const m=M(t,o,{evaluation:y,minFit:u}),w=P(t,o,m,{by:m.by==="evaluator"?d:"fit",at:f,record:l});return{applications:o,evaluation:y,decision:m,events:w,prompt:b}}export{z as applicationsFor,R as poolFrom,H as recruitPass,O as rosterRows,q as summariesFrom};
@@ -1 +1 @@
1
- import{validateSearchRequest as $,validateSearchResponse as j,overBudget as B}from"../capability-endpoints.js";import{createReadStats as D}from"./read.js";import{searchSerp as C,PROVIDER_ID as S}from"./search-serp.js";import{PROVIDER_ID as b}from"./search-searxng.js";const v=Object.freeze({timeoutMs:15e3,readConcurrency:4,readBudgetMs:8e3,aliasRead:5}),I=/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g,i=(r,t,a)=>({status:r,body:{error:{type:t,message:a}}});function L(r){const t=String(r||"").replace(I," ").replace(/\s+/g," ").trim();return{q:t,stripped:t!==String(r||"").trim()}}async function N(r,t,a){const d=new Array(r.length);let w=0;const M=Array.from({length:Math.min(t,r.length)},async()=>{for(;;){const s=w++;if(s>=r.length)return;d[s]=await a(r[s],s)}});return await Promise.all(M),d}function F({reader:r=null,redact:t=async p=>p,searxng:a=null,defaultProvider:d="auto",fetchFn:w=void 0,engines:M=void 0,now:s=()=>Date.now(),stats:_={serp:D(),searxng:D()},timeoutMs:q=v.timeoutMs}={}){const p=()=>[S,...a?.url?[b]:[]];async function x(c){if(c.provider)return c.provider;if(d===b||d===S)return d;if(a?.url){const e=await a.health();if(e.state==="ready"||e.state==="unknown")return b}return S}return{providers:p,stats:()=>Object.fromEntries(Object.entries(_).map(([c,e])=>[c,e.stats()])),searxng:a,async search(c){let e;try{e=$(c)}catch(n){return i(400,"invalid_request",n.message)}if(e.provider&&!p().includes(e.provider))return i(404,"provider_not_found",`no search provider ${JSON.stringify(e.provider)} here (have ${p().join(", ")})`);if(e.read&&!r)return i(400,"invalid_request","read: no reader is available here");const R=s();let E=!1;try{const n=await t(e.q),{q:m,stripped:y}=L(n);y&&(E=!0,e.q=m)}catch(n){return i(500,"redaction_failed",n.message)}if(!e.q)return i(400,"unsafe_query","the query was only private values (an email, a card, a key…) and nothing searchable remains");const o=await x(e),A=B(_[o]?.stats(),0,e.budgetMs);if(A)return{status:503,body:{...A,provider:o}};const f=new AbortController,O=setTimeout(()=>f.abort(),Math.min(q,e.budgetMs>0?e.budgetMs:q));let u;try{u=o===b?await a.search(e,{signal:f.signal}):await C(e,{fetchFn:w,signal:f.signal,engines:M})}catch(n){return clearTimeout(O),f.signal.aborted?i(504,"fetch_timeout",`${o} did not answer within the budget`):i(502,"provider_failed",`${o}: ${n.message}`)}clearTimeout(O);const T=Math.round(s()-R);_[o]?.record(T,e.q.length);let h=u.results;if(e.read>0&&h.length){const n=e.budgetMs>0?Math.max(1e3,e.budgetMs-T):v.readBudgetMs,m=h.slice(0,e.read),y=await N(m,v.readConcurrency,async g=>{const l=await r.read({url:g.url,snippet:g.snippet,budgetMs:Math.min(n,v.readBudgetMs)});return l.status===200?l.body:null});h=h.map((g,l)=>l<m.length&&y[l]?{...g,read:y[l]}:g)}const k={results:h,answers:u.answers||[],suggestions:u.suggestions||[],engines:u.engines||[],...u.unresponsive?.length?{unresponsive:u.unresponsive}:{},...E?{redacted:!0,query:e.q}:{},provider:o,ms:Math.round(s()-R)};try{j(k)}catch(n){return i(500,"bad_shape",n.message)}return{status:200,body:k}}}}function G(r){return{code:200,status:2e4,data:(r.results||[]).map(t=>({url:t.url,title:t.title,description:t.snippet||"",content:t.read?.markdown||t.read?.text||t.snippet||"",...t.read?.published?{publishedTime:t.read.published}:{}}))}}export{v as SEARCH_DEFAULTS,F as createSearcher,L as queryWithoutTokens,G as toJinaSearch};
1
+ import{validateSearchRequest as j,validateSearchResponse as B,overBudget as I}from"../capability-endpoints.js";import{createReadStats as x}from"./read.js";import{searchSerp as C,PROVIDER_ID as _}from"./search-serp.js";import{PROVIDER_ID as l}from"./search-searxng.js";const S=Object.freeze({timeoutMs:15e3,readConcurrency:4,readBudgetMs:8e3,aliasRead:5}),L=/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g,c=(r,t,n)=>({status:r,body:{error:{type:t,message:n}}});function N(r){const t=String(r||"").replace(L," ").replace(/\s+/g," ").trim();return{q:t,stripped:t!==String(r||"").trim()}}async function J(r,t,n){const p=new Array(r.length);let y=0;const v=Array.from({length:Math.min(t,r.length)},async()=>{for(;;){const s=y++;if(s>=r.length)return;p[s]=await n(r[s],s)}});return await Promise.all(v),p}function H({reader:r=null,redact:t=async h=>h,searxng:n=null,defaultProvider:p="auto",fetchFn:y=void 0,engines:v=void 0,now:s=()=>Date.now(),stats:q={serp:x(),searxng:x()},timeoutMs:w=S.timeoutMs}={}){const h=()=>[_,...n?.url?[l]:[]];async function $(g){if(g.provider)return g.provider;if(p===l||p===_)return p;if(n?.url){const e=await n.health();if(e.state==="ready"||e.state==="unknown")return l}return _}return{providers:h,stats:()=>Object.fromEntries(Object.entries(q).map(([g,e])=>[g,e.stats()])),searxng:n,async search(g){let e;try{e=j(g)}catch(a){return c(400,"invalid_request",a.message)}if(e.provider&&!h().includes(e.provider))return c(404,"provider_not_found",`no search provider ${JSON.stringify(e.provider)} here (have ${h().join(", ")})`);if(e.read&&!r)return c(400,"invalid_request","read: no reader is available here");const R=s();let E=!1;try{const a=await t(e.q),{q:o,stripped:m}=N(a);m&&(E=!0,e.q=o)}catch(a){return c(500,"redaction_failed",a.message)}if(!e.q)return c(400,"unsafe_query","the query was only private values (an email, a card, a key…) and nothing searchable remains");const d=await $(e),T=I(q[d]?.stats(),0,e.budgetMs);if(T)return{status:503,body:{...T,provider:d}};const M=new AbortController,O=setTimeout(()=>M.abort(),Math.min(w,e.budgetMs>0?e.budgetMs:w));let i;try{i=d===l?await n.search(e,{signal:M.signal}):await C(e,{fetchFn:y,signal:M.signal,engines:v})}catch(a){return clearTimeout(O),M.signal.aborted?c(504,"fetch_timeout",`${d} did not answer within the budget`):c(502,"provider_failed",`${d}: ${a.message}`)}clearTimeout(O);let A=d;if(!i.results.length&&!e.provider&&h().length>1){const a=d===l?_:l,o=new AbortController,m=setTimeout(()=>o.abort(),Math.min(w,e.budgetMs>0?Math.max(1e3,e.budgetMs-(s()-R)):w));try{const u=a===l?await n.search(e,{signal:o.signal}):await C(e,{fetchFn:y,signal:o.signal,engines:v});u?.results?.length&&(i=u,A=a)}catch{}clearTimeout(m)}const k=Math.round(s()-R);q[A]?.record(k,e.q.length);let b=i.results;if(e.read>0&&b.length){const a=e.budgetMs>0?Math.max(1e3,e.budgetMs-k):S.readBudgetMs,o=b.slice(0,e.read),m=await J(o,S.readConcurrency,async u=>{const f=await r.read({url:u.url,snippet:u.snippet,budgetMs:Math.min(a,S.readBudgetMs)});return f.status===200?f.body:null});b=b.map((u,f)=>f<o.length&&m[f]?{...u,read:m[f]}:u)}const D={results:b,answers:i.answers||[],suggestions:i.suggestions||[],engines:i.engines||[],...i.unresponsive?.length?{unresponsive:i.unresponsive}:{},...E?{redacted:!0,query:e.q}:{},provider:A,ms:Math.round(s()-R)};try{B(D)}catch(a){return c(500,"bad_shape",a.message)}return{status:200,body:D}}}}function K(r){return{code:200,status:2e4,data:(r.results||[]).map(t=>({url:t.url,title:t.title,description:t.snippet||"",content:t.read?.markdown||t.read?.text||t.snippet||"",...t.read?.published?{publishedTime:t.read.published}:{}}))}}export{S as SEARCH_DEFAULTS,H as createSearcher,N as queryWithoutTokens,K as toJinaSearch};
package/src/router.js CHANGED
@@ -1 +1 @@
1
- import{secureFetch as j}from"./secure-fetch.js";import{readBridgeToken as S,resolveBridgeUrl as _}from"./bridge.js";const x=["codex","claude","opencode","pi","kiro","antigravity"];function g(e){const a=(Array.isArray(e.destinations)?e.destinations:[]).filter(Boolean),c=new Set(a.map(n=>n.id)),r=[...a.filter(n=>n.type==="agent"),...x.filter(n=>!c.has(n)).map(n=>({id:n,type:"agent",agent:n,models:[n]})),...a.filter(n=>n.type!=="agent")];return e.backend==="api"&&!a.some(n=>n.type==="api")&&(r.push({id:"openai",type:"api",protocol:"openai",baseUrl:e.upstreams?.openai?.baseUrl,models:[]}),r.push({id:"anthropic",type:"api",protocol:"anthropic",baseUrl:e.upstreams?.anthropic?.baseUrl,models:[]})),r}function P(e,a,c,{destination:r="",down:n=()=>!1}={}){const i=g(a),l=c==="anthropic",s=o=>(l?o.protocol==="anthropic":o.protocol!=="anthropic")&&!n(o);return r?i.find(o=>o.id===r)||null:e&&i.find(o=>Array.isArray(o.models)&&o.models.includes(e))||e&&i.find(o=>o.id===e||o.agent===e)||e&&e.includes("/")&&i.find(o=>o.type==="agent"&&(o.agent===e.slice(0,e.indexOf("/"))||o.id===e.slice(0,e.indexOf("/"))))||i.find(o=>a.backend==="bridge"?o.type==="agent":o.type==="api"&&s(o))||i.find(o=>(a.backend==="bridge"?o.type==="agent":o.type==="api")&&!n(o))||i.find(o=>!n(o))||null}function O(e){return e.type==="agent"?{api:"agent",endpoints:["/v1/chat/completions"]}:e.protocol==="anthropic"?{api:"anthropic",endpoints:["/v1/messages"]}:{api:"openai",endpoints:["/v1/chat/completions","/v1/responses"]}}const U=/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0|[^/]*\.local)(:|\/|$)/i;function M(e){if(!e||e.type==="agent")return"";const a=String(e.baseUrl||"");return a?U.test(a)||e.apiKey||e.hasKey?"":`no API key is saved for ${e.id}`:"no endpoint URL is set for this provider"}function T(e){const a=[],c=new Set,r=(n,i,l)=>{if(!n||c.has(n))return;c.add(n);const s=O(l),o=M(l);a.push({id:n,object:"model",owned_by:i,...o?{configured:!1,reason:o}:{},provider:l.id,provider_type:l.type==="agent"?"agent":l.protocol==="anthropic"?"anthropic":"openai",api:s.api,endpoints:s.endpoints})};for(const n of g(e))if(n.type==="agent")for(const i of n.models?.length?n.models:[n.id])r(i,"chatpanel-bridge",n);else for(const i of n.models||[])r(i,n.id,n);return{object:"list",data:a}}async function C(e,a,c){const r=await _(e);if(!r||!a)return new Map;const n=S(e.bridge?.token),i=[...a.entries()].filter(([,s])=>s).map(([s])=>s),l=new Map;return await Promise.all(i.map(async s=>{try{const o=await fetch(`${r}/list-models`,{method:"POST",headers:{"content-type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({agent:s}),signal:AbortSignal.timeout(c)});if(!o.ok)return;const f=await o.json(),b=(Array.isArray(f?.models)?f.models:[]).map(t=>typeof t=="string"?t:t?.id||t?.name||"").map(t=>String(t).trim()).filter(Boolean);b.length&&l.set(s,b.slice(0,40))}catch{}})),l}async function B(e,a){const c=await _(e);if(!c)return null;try{const r=S(e.bridge?.token),n=await fetch(`${c}/health`,{headers:{Accept:"application/json",...r?{Authorization:`Bearer ${r}`}:{}},signal:AbortSignal.timeout(a)});if(!n.ok)return null;const i=await n.json();if(!Array.isArray(i?.agents))return null;const l=new Map(i.agents.map(s=>[s.id,!!s.available]));return l.noTools=new Set(i.agents.filter(s=>s.tools===!1).map(s=>s.id)),l}catch{return null}}const K=Number(process.env.CHATPANEL_MODELS_CACHE_MS)||6e4;let d={at:0,key:"",value:null,inflight:null};function N(e){try{return JSON.stringify([g(e).map(a=>[a.id,a.type,a.baseUrl,a.models]),e.bridge?.url||""])}catch{return String(Date.now())}}function z(){d={at:0,key:"",value:null,inflight:null}}async function H(e,{timeoutMs:a=4e3,fresh:c=!1,now:r=Date.now,serviceHealth:n=null}={}){const i=N(e),l=d.value&&d.key===i,s=!l||r()-d.at>K;if(l&&!c&&!s)return d.value;const o=()=>(d.inflight||(d.inflight=D(e,{timeoutMs:a,serviceHealth:n}).then(f=>(d={at:r(),key:i,value:f,inflight:null},f)).catch(f=>{throw d.inflight=null,f})),d.inflight);return l&&!c?(o().catch(()=>{}),d.value):o()}async function D(e,{timeoutMs:a=4e3,serviceHealth:c=null}={}){const r=T(e),n=new Set(r.data.map(t=>t.id)),i=c?await c():null,l=new Map(g(e).filter(t=>t.service).map(t=>[t.id,t.service])),s=t=>{if(l.get(t.owned_by)&&i){const y=i(t.owned_by);y!=="unknown"&&(t.available=y==="up");const p=typeof i.window=="function"?i.window(t.owned_by):null;p&&(t.context_window=p);const u=typeof i.card=="function"?i.card(t.owned_by):null;u&&(t.card=u)}return t};for(const t of r.data)s(t);const o=await B(e,a);if(o){r.data=r.data.filter(t=>t.owned_by!=="chatpanel-bridge"||o.get(t.id)!==!1);for(const t of r.data)t.owned_by==="chatpanel-bridge"&&(t.available=o.get(t.id)??!1,o.noTools?.has(t.id)&&(t.tools=!1))}const f=await C(e,o,a);for(const[t,h]of f){const y=r.data.find(p=>p.id===t);if(y)for(const p of h){const u=`${t}/${p}`;n.has(u)||(n.add(u),r.data.push({...y,id:u,model:p,available:!0}))}}const b=g(e).filter(t=>t.type==="api"&&t.baseUrl);return await Promise.all(b.map(async t=>{const h=new AbortController,y=setTimeout(()=>h.abort(),a);try{const p={"content-type":"application/json"};t.apiKey&&(t.protocol==="anthropic"?(p["x-api-key"]=t.apiKey,p["anthropic-version"]="2023-06-01"):p.authorization=`Bearer ${t.apiKey}`);const u=await j(`${t.baseUrl.replace(/\/$/,"")}/models`,{headers:p,signal:h.signal});if(!u.ok)return;const w=await u.json(),$=Array.isArray(w?.data)?w.data:Array.isArray(w?.models)?w.models:[];for(const v of $){const m=typeof v=="string"?v:v?.id;if(m&&!n.has(m)){n.add(m);const A=O(t),k=M(t);r.data.push(s({id:m,object:"model",owned_by:t.id,provider:t.id,provider_type:t.protocol==="anthropic"?"anthropic":"openai",api:A.api,endpoints:A.endpoints,...k?{configured:!1,reason:k}:{}}))}}}catch{}finally{clearTimeout(y)}})),r}export{T as aggregateModels,H as aggregateModelsAsync,g as listDestinations,z as resetModelsCache,P as resolveDestination};
1
+ import{secureFetch as x}from"./secure-fetch.js";import{readBridgeToken as _,resolveBridgeUrl as S}from"./bridge.js";import{reachOfGatewayModel as M,agentModelReach as U}from"@chatpanel/events/model-candidates.js";const T=["codex","claude","opencode","pi","kiro","antigravity"];function b(t){const a=(Array.isArray(t.destinations)?t.destinations:[]).filter(Boolean),c=new Set(a.map(n=>n.id)),r=[...a.filter(n=>n.type==="agent"),...T.filter(n=>!c.has(n)).map(n=>({id:n,type:"agent",agent:n,models:[n]})),...a.filter(n=>n.type!=="agent")];return t.backend==="api"&&!a.some(n=>n.type==="api")&&(r.push({id:"openai",type:"api",protocol:"openai",baseUrl:t.upstreams?.openai?.baseUrl,models:[]}),r.push({id:"anthropic",type:"api",protocol:"anthropic",baseUrl:t.upstreams?.anthropic?.baseUrl,models:[]})),r}function H(t,a,c,{destination:r="",down:n=()=>!1}={}){const i=b(a),l=c==="anthropic",s=o=>(l?o.protocol==="anthropic":o.protocol!=="anthropic")&&!n(o);return r?i.find(o=>o.id===r)||null:t&&i.find(o=>Array.isArray(o.models)&&o.models.includes(t))||t&&i.find(o=>o.id===t||o.agent===t)||t&&t.includes("/")&&i.find(o=>o.type==="agent"&&(o.agent===t.slice(0,t.indexOf("/"))||o.id===t.slice(0,t.indexOf("/"))))||i.find(o=>a.backend==="bridge"?o.type==="agent":o.type==="api"&&s(o))||i.find(o=>(a.backend==="bridge"?o.type==="agent":o.type==="api")&&!n(o))||i.find(o=>!n(o))||null}function O(t){return t.type==="agent"?{api:"agent",endpoints:["/v1/chat/completions"]}:t.protocol==="anthropic"?{api:"anthropic",endpoints:["/v1/messages"]}:{api:"openai",endpoints:["/v1/chat/completions","/v1/responses"]}}const C=/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0|[^/]*\.local)(:|\/|$)/i;function $(t){if(!t||t.type==="agent")return"";const a=String(t.baseUrl||"");return a?C.test(a)||t.apiKey||t.hasKey?"":`no API key is saved for ${t.id}`:"no endpoint URL is set for this provider"}function B(t){const a=[],c=new Set,r=(n,i,l)=>{if(!n||c.has(n))return;c.add(n);const s=O(l),o=$(l);a.push({id:n,object:"model",owned_by:i,...o?{configured:!1,reason:o}:{},provider:l.id,provider_type:l.type==="agent"?"agent":l.protocol==="anthropic"?"anthropic":"openai",api:s.api,endpoints:s.endpoints,reach:M({id:n,owned_by:i,provider_type:l.type==="agent"?"agent":"openai"},l)})};for(const n of b(t))if(n.type==="agent")for(const i of n.models?.length?n.models:[n.id])r(i,"chatpanel-bridge",n);else for(const i of n.models||[])r(i,n.id,n);return{object:"list",data:a}}async function K(t,a,c){const r=await S(t);if(!r||!a)return new Map;const n=_(t.bridge?.token),i=[...a.entries()].filter(([,s])=>s).map(([s])=>s),l=new Map;return await Promise.all(i.map(async s=>{try{const o=await fetch(`${r}/list-models`,{method:"POST",headers:{"content-type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({agent:s}),signal:AbortSignal.timeout(c)});if(!o.ok)return;const d=await o.json(),w=(Array.isArray(d?.models)?d.models:[]).map(e=>typeof e=="string"?e:e?.id||e?.name||"").map(e=>String(e).trim()).filter(Boolean);w.length&&l.set(s,w.slice(0,40))}catch{}})),l}async function N(t,a){const c=await S(t);if(!c)return null;try{const r=_(t.bridge?.token),n=await fetch(`${c}/health`,{headers:{Accept:"application/json",...r?{Authorization:`Bearer ${r}`}:{}},signal:AbortSignal.timeout(a)});if(!n.ok)return null;const i=await n.json();if(!Array.isArray(i?.agents))return null;const l=new Map(i.agents.map(s=>[s.id,!!s.available]));return l.noTools=new Set(i.agents.filter(s=>s.tools===!1).map(s=>s.id)),l}catch{return null}}const D=Number(process.env.CHATPANEL_MODELS_CACHE_MS)||6e4;let f={at:0,key:"",value:null,inflight:null};function E(t){try{return JSON.stringify([b(t).map(a=>[a.id,a.type,a.baseUrl,a.models]),t.bridge?.url||""])}catch{return String(Date.now())}}function F(){f={at:0,key:"",value:null,inflight:null}}async function G(t,{timeoutMs:a=4e3,fresh:c=!1,now:r=Date.now,serviceHealth:n=null}={}){const i=E(t),l=f.value&&f.key===i,s=!l||r()-f.at>D;if(l&&!c&&!s)return f.value;const o=()=>(f.inflight||(f.inflight=L(t,{timeoutMs:a,serviceHealth:n}).then(d=>(f={at:r(),key:i,value:d,inflight:null},d)).catch(d=>{throw f.inflight=null,d})),f.inflight);return l&&!c?(o().catch(()=>{}),f.value):o()}async function L(t,{timeoutMs:a=4e3,serviceHealth:c=null}={}){const r=B(t),n=new Set(r.data.map(e=>e.id)),i=c?await c():null,l=new Map(b(t).filter(e=>e.service).map(e=>[e.id,e.service])),s=e=>{if(l.get(e.owned_by)&&i){const y=i(e.owned_by);y!=="unknown"&&(e.available=y==="up");const p=typeof i.window=="function"?i.window(e.owned_by):null;p&&(e.context_window=p);const u=typeof i.card=="function"?i.card(e.owned_by):null;u&&(e.card=u)}return e};for(const e of r.data)s(e);const o=await N(t,a);if(o){r.data=r.data.filter(e=>e.owned_by!=="chatpanel-bridge"||o.get(e.id)!==!1);for(const e of r.data)e.owned_by==="chatpanel-bridge"&&(e.available=o.get(e.id)??!1,o.noTools?.has(e.id)&&(e.tools=!1))}const d=await K(t,o,a);for(const[e,h]of d){const y=r.data.find(p=>p.id===e);if(y)for(const p of h){const u=`${e}/${p}`;n.has(u)||(n.add(u),r.data.push({...y,id:u,model:p,available:!0,reach:U(p)}))}}const w=b(t).filter(e=>e.type==="api"&&e.baseUrl);return await Promise.all(w.map(async e=>{const h=new AbortController,y=setTimeout(()=>h.abort(),a);try{const p={"content-type":"application/json"};e.apiKey&&(e.protocol==="anthropic"?(p["x-api-key"]=e.apiKey,p["anthropic-version"]="2023-06-01"):p.authorization=`Bearer ${e.apiKey}`);const u=await x(`${e.baseUrl.replace(/\/$/,"")}/models`,{headers:p,signal:h.signal});if(!u.ok)return;const m=await u.json(),j=Array.isArray(m?.data)?m.data:Array.isArray(m?.models)?m.models:[];for(const v of j){const g=typeof v=="string"?v:v?.id;if(g&&!n.has(g)){n.add(g);const A=O(e),k=$(e);r.data.push(s({id:g,object:"model",owned_by:e.id,provider:e.id,provider_type:e.protocol==="anthropic"?"anthropic":"openai",api:A.api,endpoints:A.endpoints,...k?{configured:!1,reason:k}:{},reach:M({id:g,owned_by:e.id},e)}))}}}catch{}finally{clearTimeout(y)}})),r}export{B as aggregateModels,G as aggregateModelsAsync,b as listDestinations,F as resetModelsCache,H as resolveDestination};