@chatpanel/bridge 0.51.1 → 0.53.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.51.1",
3
+ "version": "0.53.0",
4
4
  "type": "module",
5
5
  "description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{readFileSync as h,writeFileSync as y,existsSync as p,mkdirSync as g}from"node:fs";import{fileURLToPath as j}from"node:url";import{dirname as d,join as s}from"node:path";const o=s(d(j(import.meta.url)),".."),$=["normalize.js","pairing.js","invoke.js","stream.js","bridge.js","gateway.js","eventlog.js","service.js","adapters/telegram.js"],w={"@chatpanel/pii":"../pii/index.js","@chatpanel/events/event.js":"../events/event.js","@chatpanel/events/capability.js":"../events/capability.js","@chatpanel/events/reach.js":"../events/reach.js"};function E(){return[s(o,"node_modules","@chatpanel","channels","src"),s(o,"..","chatpanel-channels","src")].find(n=>p(s(n,"service.js")))}const t=process.argv.includes("--check"),u=E();if(!u){const n="chatpanel-channels not found (check out ../chatpanel-channels).";t&&(console.error(`sync-channels --check: ${n}`),process.exit(1)),console.warn(`sync-channels: ${n} Leaving src/channels as-is.`),process.exit(0)}const k=n=>`// GENERATED — do not edit.
2
+ import{readFileSync as h,writeFileSync as j,existsSync as p,mkdirSync as y}from"node:fs";import{fileURLToPath as g}from"node:url";import{dirname as d,join as s}from"node:path";const o=s(d(g(import.meta.url)),".."),$=["normalize.js","pairing.js","invoke.js","stream.js","bridge.js","gateway.js","eventlog.js","service.js","personal.js","adapters/telegram.js"],w={"@chatpanel/pii":"../pii/index.js","@chatpanel/events/event.js":"../events/event.js","@chatpanel/events/capability.js":"../events/capability.js","@chatpanel/events/reach.js":"../events/reach.js","@chatpanel/events/mentions.js":"../events/mentions.js"};function E(){return[s(o,"node_modules","@chatpanel","channels","src"),s(o,"..","chatpanel-channels","src")].find(n=>p(s(n,"service.js")))}const c=process.argv.includes("--check"),m=E();if(!m){const n="chatpanel-channels not found (check out ../chatpanel-channels).";c&&(console.error(`sync-channels --check: ${n}`),process.exit(1)),console.warn(`sync-channels: ${n} Leaving src/channels as-is.`),process.exit(0)}const k=n=>`// GENERATED — do not edit.
3
3
  // Source of truth: chatpanel-channels/src/${n} (npm @chatpanel/channels).
4
4
  // Edit there, then run: npm run sync:channels
5
5
  //
@@ -8,4 +8,4 @@ import{readFileSync as h,writeFileSync as y,existsSync as p,mkdirSync as g}from"
8
8
  // single-file binary has nothing to resolve. Package imports are rewritten to the
9
9
  // vendored engines (src/pii, src/events) by the sync script.
10
10
 
11
- `;function b(n,c){const e="../".repeat(n.split("/").length-1);let r=c.replace(/(from\s+['"])(@chatpanel\/[^'"]+)(['"])/g,(R,m,i,v)=>{const l=w[i];if(!l)throw new Error(`sync-channels: no rewrite for '${i}' (imported by ${n}) — add it to REWRITE`);return`${m}${e}${l}${v}`});const a=r.match(/from\s+['"]@chatpanel\/[^'"]+['"]/);if(a)throw new Error(`sync-channels: unrewritten import in ${n}: ${a[0]}`);return k(n)+r}let f=0;for(const n of $){const c=b(n,h(s(u,n),"utf8")),e=s(o,"src","channels",n);if(t||g(d(e),{recursive:!0}),(p(e)?h(e,"utf8"):null)!==c){if(t){console.error(`sync-channels --check: src/channels/${n} differs from chatpanel-channels`),f+=1;continue}y(e,c),console.log(`sync-channels: updated src/channels/${n}`)}}t&&(f&&(console.error("Run `npm run sync:channels` and commit the result."),process.exit(1)),console.log("sync-channels --check: src/channels matches chatpanel-channels ✓"));
11
+ `;function b(n,t){const e="../".repeat(n.split("/").length-1);let r=t.replace(/(from\s+['"])(@chatpanel\/[^'"]+)(['"])/g,(R,f,i,v)=>{const l=w[i];if(!l)throw new Error(`sync-channels: no rewrite for '${i}' (imported by ${n}) — add it to REWRITE`);return`${f}${e}${l}${v}`});const a=r.match(/from\s+['"]@chatpanel\/[^'"]+['"]/);if(a)throw new Error(`sync-channels: unrewritten import in ${n}: ${a[0]}`);return k(n)+r}let u=0;for(const n of $){const t=b(n,h(s(m,n),"utf8")),e=s(o,"src","channels",n);if(c||y(d(e),{recursive:!0}),(p(e)?h(e,"utf8"):null)!==t){if(c){console.error(`sync-channels --check: src/channels/${n} differs from chatpanel-channels`),u+=1;continue}j(e,t),console.log(`sync-channels: updated src/channels/${n}`)}}c&&(u&&(console.error("Run `npm run sync:channels` and commit the result."),process.exit(1)),console.log("sync-channels --check: src/channels matches chatpanel-channels ✓"));
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{readFileSync as r,writeFileSync as d,existsSync as i,mkdirSync as p}from"node:fs";import{fileURLToPath as m}from"node:url";import{dirname as h,join as s}from"node:path";const c=s(h(m(import.meta.url)),".."),f=["scopes.js","skill-manifest.js","skill-scan.js","ref.js","event.js","view.js","capability.js","reach.js","scm-connection.js","sandbox-policy.js","secret-names.js","sandbox-grant.js","runtime-host.js","sandbox-choice.js","harness-cards.js","agent-thread.js","compaction.js","context-window.js","mcp-errors.js","registries.js","mcp-signin.js","context-breakdown.js","mcp-config-import.js","agent-mcp.js","agent-mcp-host.js","file-write.js","toml-lite.js","frontmatter.js","skill-package.js","agent-portability.js","agent-dialects.js","agent-card.js","dialect-claude.js","dialect-codex.js","dialect-a2a.js","dialect-chatpanel.js","agent.js","team.js","engine.js","budget.js","mcp-args-env.js","mcp-launcher.js","agent-permission.js","access-request.js","policy.js","service-standby.js"];function u(){return[s(c,"node_modules","@chatpanel","events"),s(c,"..","chatpanel-events")].find(e=>i(s(e,"skill-manifest.js")))}const n=process.argv.includes("--check"),a=u();if(!a){const e="chatpanel-events not found (check out ../chatpanel-events).";n&&(console.error(`sync-events --check: ${e}`),process.exit(1)),console.warn(`sync-events: ${e} Leaving src/events as-is.`),process.exit(0)}const l=s(c,"src","events");n||p(l,{recursive:!0});const v=e=>`// GENERATED — do not edit.
2
+ import{readFileSync as r,writeFileSync as d,existsSync as i,mkdirSync as p}from"node:fs";import{fileURLToPath as m}from"node:url";import{dirname as h,join as s}from"node:path";const c=s(h(m(import.meta.url)),".."),f=["scopes.js","skill-manifest.js","skill-scan.js","ref.js","event.js","view.js","capability.js","reach.js","scm-connection.js","sandbox-policy.js","secret-names.js","sandbox-grant.js","runtime-host.js","sandbox-choice.js","harness-cards.js","agent-thread.js","compaction.js","context-window.js","mcp-errors.js","registries.js","mcp-signin.js","context-breakdown.js","mcp-config-import.js","agent-mcp.js","agent-mcp-host.js","file-write.js","toml-lite.js","frontmatter.js","skill-package.js","agent-portability.js","agent-dialects.js","agent-card.js","dialect-claude.js","dialect-codex.js","dialect-a2a.js","dialect-chatpanel.js","agent.js","team.js","engine.js","budget.js","mcp-args-env.js","mcp-launcher.js","agent-permission.js","access-request.js","policy.js","service-standby.js","mentions.js","kb-capability.js","extract-capability.js","context-api.js","rrf.js","sources-retrieval.js"];function u(){return[s(c,"node_modules","@chatpanel","events"),s(c,"..","chatpanel-events")].find(e=>i(s(e,"skill-manifest.js")))}const n=process.argv.includes("--check"),a=u();if(!a){const e="chatpanel-events not found (check out ../chatpanel-events).";n&&(console.error(`sync-events --check: ${e}`),process.exit(1)),console.warn(`sync-events: ${e} Leaving src/events as-is.`),process.exit(0)}const l=s(c,"src","events");n||p(l,{recursive:!0});const v=e=>`// GENERATED — do not edit.
3
3
  // Source of truth: chatpanel-events/${e} (npm @chatpanel/events).
4
4
  // Edit there, then run: npm run sync:events
5
5
  //
@@ -1,4 +1,6 @@
1
- import{normalizeTelegram as ee,actorId as O}from"../normalize.js";import{buildInvocation as te,redactInbound as ae,outboundText as A,appendTurn as ne,appendInvoked as oe,appendRedacted as se,appendEgress as re}from"../invoke.js";import*as ie from"../bridge.js";import{splitForTelegram as F,createGate as ce}from"../stream.js";import{createVault as de}from"../../pii/index.js";const _="api.telegram.org",he=["Chap — drive your local agent from here.","","Send a message and I run it on your machine.","/pair <code> — enroll this chat (Chap → Settings → Channels)","/new — start fresh (forget this conversation + new privacy vault)","/stop — stop the current run","/help — this message"].join(`
2
- `);function le(g,l){return[!l||l==="any"?"":["You are answering a message sent from the user's PHONE, relayed to this machine.",l==="device"?"You cannot read files, run commands, browse the web, or change anything.":"You can READ files and search the user's Chap history. You cannot write or edit files, run shell commands, or browse the web — those are switched off for messages from a phone, and no tool will grant them.","If a request needs something you cannot do, say so plainly in your FIRST reply and offer what you can do instead. Never begin work you cannot finish.","Answers are read on a phone: be brief, and put the answer first."].join(" "),g].filter(Boolean).join(`
1
+ import{normalizeTelegram as ie,actorId as F}from"../normalize.js";import{buildInvocation as ce,redactInbound as R,outboundText as G,appendTurn as de,appendInvoked as he,appendRedacted as le,appendEgress as ue}from"../invoke.js";import*as fe from"../bridge.js";import{splitForTelegram as H,createGate as pe}from"../stream.js";import{createVault as ge}from"../../pii/index.js";import{reachSatisfies as L}from"../../events/reach.js";import{withPersonal as me}from"../personal.js";const B="api.telegram.org",be=["Chap — drive your local agent from here.","","Send a message and I run it on your machine.","/pair <code> — enroll this chat (Chap → Settings → Channels)","@<binder> — work inside one of your binders (its notes, knowledge bases, instructions)","/binders — list your binders · /out — leave the one you are in","/new — start fresh (forget this conversation + new privacy vault)","/stop — stop the current run","/help — this message"].join(`
2
+ `);function we(b,u){return[!u||u==="any"?"":["You are answering a message sent from the user's PHONE, relayed to this machine.",u==="device"?"You cannot read files, run commands, browse the web, or change anything.":"You can READ files and search the user's Chap history. You cannot write or edit files, run shell commands, or browse the web — those are switched off for messages from a phone, and no tool will grant them.","If a request needs something you cannot do, say so plainly in your FIRST reply and offer what you can do instead. Never begin work you cannot finish.","Answers are read on a phone: be brief, and put the answer first."].join(" "),b].filter(Boolean).join(`
3
3
 
4
- `)}function we({botToken:g,baseUrl:l,token:$,pairing:C,savePairing:R=async()=>{},appender:k,agent:Y="claude",transport:E=ie,model:G="",provider:H="",system:L="",route:w=null,redact:N={tier:"basic"},privacy:x="standard",logger:u=console,signal:c}){const q=`https://${_}/bot${g}`,z=`https://${_}/file/bot${g}`,y=new Map,U=()=>({vault:de(),runId:null,history:[]}),j=e=>(y.has(e)||y.set(e,U()),y.get(e));async function p(e,n){return(await fetch(`${q}/${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n),signal:c})).json()}const r=(e,n)=>p("sendMessage",{chat_id:e,text:n}),S=(e,n,t)=>p("editMessageText",{chat_id:e,message_id:n,text:t});async function D(e){const n=[];for(const t of e||[])try{const o=(await p("getFile",{file_id:t.fileId}))?.result?.file_path;if(!o)continue;const s=await fetch(`${z}/${o}`,{signal:c}),d=Buffer.from(await s.arrayBuffer()),m=/\.png$/i.test(o)?"image/png":/\.webp$/i.test(o)?"image/webp":"image/jpeg";n.push({dataUrl:`data:${m};base64,${d.toString("base64")}`})}catch(a){u.warn?.(`[telegram] image fetch failed: ${a?.message||a}`)}return n}async function J(e){const n=O("telegram",e.chatId),{name:t,args:a}=e.command,o=t==="pair"||t==="start"&&a?a:"";if(o){const s=C.redeem(n,o,{label:e.from?.name||""});return await R(),void r(e.chatId,s.ok?`✅ paired (reach: ${s.reach}). Send me anything — I'll run it on your machine.`:`⛔ ${s.reason}`)}if(t==="help"||t==="start")return void r(e.chatId,he);if(t==="pair")return void r(e.chatId,"send /pair <code> — get the code in Chap → Settings → Channels");if(t==="new")return y.set(e.chatId,U()),void r(e.chatId,"🧹 fresh conversation.");if(t==="stop"){const s=j(e.chatId),d=w&&w()||{},m=await(d.transport||E).cancel(s.runId,{baseUrl:d.baseUrl||l,token:d.token||$});return s.runId=null,void r(e.chatId,m?"⏹ stopped.":"nothing running.")}r(e.chatId,`unknown command /${t} — try /help`)}async function V(e){const n=O("telegram",e.chatId),t=C.reachOf(n);if(!t)return void r(e.chatId,"🔒 not paired. Get a code in Chap (Settings → Channels), then send: /pair <code>");if(!e.text&&!e.photos.length)return;const a=j(e.chatId);let o;try{o=te(e)}catch(i){return void r(e.chatId,`⚠️ ${i.message}`)}const{redacted:s,counts:d}=ae(e.text,a.vault,N);await oe(k,o),await se(k,d);const m=await D(e.photos),f=(await p("sendMessage",{chat_id:e.chatId,text:"…"}))?.result?.message_id,Q=ce(1200);let B="";const W=[...a.history,{role:"user",content:s}],h=w&&w()||{},X=h.transport||E;try{const i=await X.chat({agent:h.agent??Y,model:h.model??G,provider:h.provider??H,system:le(h.system??L,t),messages:W,images:m,options:{reach:t}},{baseUrl:h.baseUrl||l,token:h.token||$,signal:c,onEvent:(M,b)=>{if(b.runId&&(a.runId=b.runId),f&&(b.done||Q.ready())){const Z=A(b.text,a.vault,{privacy:x}),v=F(Z||"…")[0];v&&v!==B&&(B=v,S(e.chatId,f,v).catch(()=>{}))}}});a.runId=null;const I=A(i.text,a.vault,{privacy:x}),T=F(i.error?`⚠️ ${i.error}`:I||"(no output)");f?await S(e.chatId,f,T[0]):await r(e.chatId,T[0]);for(const M of T.slice(1))await r(e.chatId,M);!i.error&&i.text&&(a.history=ne(a.history,s,i.text)),await re(k,{host:_,redacted:x==="strict",controlled:!1})}catch(i){a.runId=null;const I=`⚠️ ${i?.message||i}`;f?await S(e.chatId,f,I).catch(()=>{}):await r(e.chatId,I).catch(()=>{})}}const P=e=>new Promise(n=>{if(c?.aborted)return n();let t;const a=()=>{clearTimeout(t),c?.removeEventListener?.("abort",a),n()};t=setTimeout(a,e),c?.addEventListener?.("abort",a,{once:!0})});async function K(){let e=0;for(u.log?.("[telegram] long-poll started (outbound-only; no inbound port).");!c?.aborted;){let n;try{const t=await p("getUpdates",{offset:e,timeout:30,allowed_updates:["message"]});if(t&&t.ok===!1){const a=t.error_code,o=a===401?" — check the bot token (@BotFather → /mybots → API token)":a===409?" — another chatpanel-channels (or another poller) is already reading this bot":"";u.error?.(`[telegram] getUpdates refused: ${t.description||`error_code ${a}`}${o}`),await P(5e3);continue}n=t?.result||[]}catch(t){if(c?.aborted)break;u.warn?.(`[telegram] getUpdates failed: ${t?.message||t}; retrying in 2s`),await P(2e3);continue}for(const t of n){e=t.update_id+1;const a=ee(t);if(!a)continue;const o=a.command?J(a):V(a);Promise.resolve(o).catch(s=>u.error?.(`[telegram] handler error: ${s?.message||s}`))}}u.log?.("[telegram] stopped.")}return K()}export{le as channelSystem,we as startTelegram};
4
+ `)}function Ce({botToken:b,baseUrl:u,token:x,pairing:S,savePairing:N=async()=>{},appender:C,agent:q="claude",transport:E=fe,model:z="",provider:D="",system:J="",route:w=null,redact:P={tier:"basic"},privacy:T="standard",logger:f=console,personal:g=null,signal:h}){const V=`https://${B}/bot${b}`,K=`https://${B}/file/bot${b}`,y=new Map,U=()=>({vault:ge(),runId:null,history:[],binders:[]}),I=e=>(y.has(e)||y.set(e,U()),y.get(e));async function m(e,o){return(await fetch(`${V}/${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o),signal:h})).json()}const r=(e,o)=>m("sendMessage",{chat_id:e,text:o}),_=(e,o,t)=>m("editMessageText",{chat_id:e,message_id:o,text:t});async function Q(e){const o=[];for(const t of e||[])try{const i=(await m("getFile",{file_id:t.fileId}))?.result?.file_path;if(!i)continue;const a=await fetch(`${K}/${i}`,{signal:h}),c=Buffer.from(await a.arrayBuffer()),d=/\.png$/i.test(i)?"image/png":/\.webp$/i.test(i)?"image/webp":"image/jpeg";o.push({dataUrl:`data:${d};base64,${c.toString("base64")}`})}catch(n){f.warn?.(`[telegram] image fetch failed: ${n?.message||n}`)}return o}async function W(e){const o=F("telegram",e.chatId),{name:t,args:n}=e.command,i=t==="pair"||t==="start"&&n?n:"";if(i){const a=S.redeem(o,i,{label:e.from?.name||""});return await N(),void r(e.chatId,a.ok?`✅ paired (reach: ${a.reach}). Send me anything — I'll run it on your machine.`:`⛔ ${a.reason}`)}if(t==="help"||t==="start")return void r(e.chatId,be);if(t==="pair")return void r(e.chatId,"send /pair <code> — get the code in Chap → Settings → Channels");if(t==="new")return y.set(e.chatId,U()),void r(e.chatId,"🧹 fresh conversation.");if(t==="binders"){if(!g||!L(S.reachOf(o),"trusted"))return void r(e.chatId,"binders are not reachable from this phone.");const a=await g.binders(),c=new Set(I(e.chatId).binders);return void r(e.chatId,a.length?`Your binders — send @name to work inside one:
5
+ ${a.map(d=>`${c.has(d.id)?"● ":"○ "}${d.title}`).join(`
6
+ `)}`:"no binders yet — make one in Chap (Binders).")}if(t==="out"){const a=I(e.chatId),c=a.binders.length;return a.binders=[],void r(e.chatId,c?"🗂 out of the binder — answering from everything again.":"not inside a binder.")}if(t==="stop"){const a=I(e.chatId),c=w&&w()||{},d=await(c.transport||E).cancel(a.runId,{baseUrl:c.baseUrl||u,token:c.token||x});return a.runId=null,void r(e.chatId,d?"⏹ stopped.":"nothing running.")}r(e.chatId,`unknown command /${t} — try /help`)}async function X(e){const o=F("telegram",e.chatId),t=S.reachOf(o);if(!t)return void r(e.chatId,"🔒 not paired. Get a code in Chap (Settings → Channels), then send: /pair <code>");if(!e.text&&!e.photos.length)return;const n=I(e.chatId);let i;try{i=ce(e)}catch(s){return void r(e.chatId,`⚠️ ${s.message}`)}let a="",c=[];if(g&&e.text&&L(t,"trusted")){const s=await g.pickBinders(e.text,n.binders).catch(()=>null);s&&(n.binders=s.ids,c=s.named),a=await g.prepare(e.text,{binders:n.binders}).catch(()=>"")}const d=R(e.text,n.vault,P),M=a?R(me(e.text,a),n.vault,P):d,{redacted:ee}=d,{counts:te}=M;await he(C,i),await le(C,te);const ne=await Q(e.photos),p=(await m("sendMessage",{chat_id:e.chatId,text:c.length?`🗂 inside ${c.join(", ")} …`:"…"}))?.result?.message_id,ae=pe(1200);let Y="";const oe=[...n.history,{role:"user",content:M.redacted}],l=w&&w()||{},se=l.transport||E;try{const s=await se.chat({agent:l.agent??q,model:l.model??z,provider:l.provider??D,system:we(l.system??J,t),messages:oe,images:ne,options:{reach:t}},{baseUrl:l.baseUrl||u,token:l.token||x,signal:h,onEvent:(A,$)=>{if($.runId&&(n.runId=$.runId),p&&($.done||ae.ready())){const re=G($.text,n.vault,{privacy:T}),k=H(re||"…")[0];k&&k!==Y&&(Y=k,_(e.chatId,p,k).catch(()=>{}))}}});n.runId=null;const v=G(s.text,n.vault,{privacy:T}),j=H(s.error?`⚠️ ${s.error}`:v||"(no output)");p?await _(e.chatId,p,j[0]):await r(e.chatId,j[0]);for(const A of j.slice(1))await r(e.chatId,A);!s.error&&s.text&&(n.history=de(n.history,ee,s.text)),await ue(C,{host:B,redacted:T==="strict",controlled:!1})}catch(s){n.runId=null;const v=`⚠️ ${s?.message||s}`;p?await _(e.chatId,p,v).catch(()=>{}):await r(e.chatId,v).catch(()=>{})}}const O=e=>new Promise(o=>{if(h?.aborted)return o();let t;const n=()=>{clearTimeout(t),h?.removeEventListener?.("abort",n),o()};t=setTimeout(n,e),h?.addEventListener?.("abort",n,{once:!0})});async function Z(){let e=0;for(f.log?.("[telegram] long-poll started (outbound-only; no inbound port).");!h?.aborted;){let o;try{const t=await m("getUpdates",{offset:e,timeout:30,allowed_updates:["message"]});if(t&&t.ok===!1){const n=t.error_code,i=n===401?" — check the bot token (@BotFather → /mybots → API token)":n===409?" — another chatpanel-channels (or another poller) is already reading this bot":"";f.error?.(`[telegram] getUpdates refused: ${t.description||`error_code ${n}`}${i}`),await O(5e3);continue}o=t?.result||[]}catch(t){if(h?.aborted)break;f.warn?.(`[telegram] getUpdates failed: ${t?.message||t}; retrying in 2s`),await O(2e3);continue}for(const t of o){e=t.update_id+1;const n=ie(t);if(!n)continue;const i=n.command?W(n):X(n);Promise.resolve(i).catch(a=>f.error?.(`[telegram] handler error: ${a?.message||a}`))}}f.log?.("[telegram] stopped.")}return Z()}export{we as channelSystem,Ce as startTelegram};
@@ -0,0 +1,8 @@
1
+ import{mentionCatalog as $,parseMentions as S,mentionedBinders as T,keepBinders as d}from"../events/mentions.js";const m=9e3,w=3,A=12e3;function C({baseUrl:u="http://127.0.0.1:4320",token:c=()=>"",fetchImpl:y=fetch}={}){const g=String(u).replace(/\/$/,"");async function h(s,i,t){const n=new AbortController,l=setTimeout(()=>n.abort(),A);try{const r=typeof c=="function"?c():c,e=await y(`${g}${i}`,{method:s,signal:n.signal,headers:{"content-type":"application/json","x-chatpanel-client":"channels",...r?{authorization:`Bearer ${r}`}:{}},...t?{body:JSON.stringify(t)}:{}});return e.ok?await e.json().catch(()=>null):null}catch{return null}finally{clearTimeout(l)}}async function p(){const s=await h("GET","/v1/contexts");return Array.isArray(s?.contexts)?s.contexts:[]}async function b(s,i=[]){if(!/(^|\s)@[a-z0-9]/i.test(String(s||"")))return{ids:d(i,[]),named:[],all:null};const t=await p(),n=S(s,$({binders:t})).filter(e=>e.type==="binder"),l=d(i,n),r=T(n).filter(e=>!i.includes(e));return{ids:l,named:r.map(e=>t.find(o=>o.id===e)?.title).filter(Boolean),all:t}}async function x(s,{binders:i=[]}={}){const t=String(s||"").trim();if(!t)return"";const n=i.length&&(await h("GET",`/v1/contexts/turn?named=${encodeURIComponent(i.join(","))}`))?.turn||null,l=(n?.bases||[]).slice(0,w),[r,...e]=await Promise.all([h("POST","/v1/research",{question:t,...n?.ids?.length?{ids:n.ids}:{}}),...l.map(a=>h("POST",`/v1/kb/${encodeURIComponent(a.id)}/research`,{question:t}))]),o=[];n?.line&&o.push(`[Chap] ${n.line}`),n?.instructions&&o.push(n.instructions);for(const a of e)a?.attachment?.text&&(Array.isArray(a.hits)?a.hits.length:Number(a.hits)||0)>0&&o.push(a.attachment.text);r?.attachment?.text&&(r.count>0||r.memory?.length)&&o.push(r.attachment.text);const f=o.join(`
2
+
3
+ `);return f.length>m?`${f.slice(0,m)}
4
+ …(cut to fit a phone's turn)`:f}return{binders:p,pickBinders:b,prepare:x}}function M(u,c){return c?`${c}
5
+
6
+ ---
7
+ The person's message:
8
+ ${u}`:u}export{C as createPersonalContext,M as withPersonal};
@@ -1 +1 @@
1
- import v from"node:path";import{readFile as L,writeFile as J,mkdir as R,rm as z,stat as B}from"node:fs/promises";import{readFileSync as I}from"node:fs";import{createPairingStore as Y}from"./pairing.js";import*as q from"./bridge.js";import*as H from"./gateway.js";const j="http://127.0.0.1:4320";import{createEventLog as W}from"./eventlog.js";import{startTelegram as D}from"./adapters/telegram.js";const K="https://api.telegram.org",P=Object.freeze({agent:"claude",model:"",provider:"",gatewayUrl:j,privacy:"standard",tier:"basic"}),C=[2e3,5e3,15e3,6e4],G=async(s,n)=>{try{return JSON.parse(await L(s,"utf8"))}catch{return n}},M=(s,n)=>J(s,JSON.stringify(n,null,2),{mode:384});async function N(s,{fetchImpl:n=fetch,signal:m}={}){const f=await n(`${K}/bot${String(s||"").trim()}/getMe`,{signal:m}),c=await f.json().catch(()=>null);if(!c?.ok){const w=c?.description||`HTTP ${f.status}`;throw new Error(/unauthorized/i.test(w)?"Telegram rejected that token — copy it again from @BotFather":w)}return{id:c.result.id,username:c.result.username,name:c.result.first_name||""}}const Q=(s,n)=>`https://t.me/${s}?start=${n}`;function at({home:s,dataDir:n,bridge:m,logger:f=console,fetchImpl:c=void 0,now:w=()=>Date.now(),startAdapter:O=D}={}){const p=v.join(s,"telegram-token"),_=v.join(n,"config.json"),F=v.join(n,"pairing.json");let i=null,e={...P},S=null,u=null,k=null,g=!1,d="",A=0,h=!0;const y=()=>M(F,i?i.toJSON():{}),T=()=>M(_,e);async function E(){try{const t=(await L(p,"utf8")).trim();if(!t)return"";try{const{mode:r}=await B(p);r&63&&f.warn?.(`[channels] ${p} is group/world-readable — chmod 600 it (it holds your bot token).`)}catch{}return t}catch{return""}}async function l(){await R(n,{recursive:!0}),i||(i=Y(await G(F,{}),{now:w})),e={...P,...await G(_,{})},S||(S=await W({file:v.join(n,"events.jsonl"),host:"channel"}))}function $(t){k=new AbortController,g=!0;const r=()=>{try{return I(v.join(s,"gateway-token"),"utf8").trim()}catch{return""}},o=()=>{const a=!!e.model;return{transport:a?H:q,token:a?r():m.token,agent:a?"":e.agent,model:a?e.model:"",provider:a&&e.provider||"",baseUrl:a?e.gatewayUrl||j:m.baseUrl,system:e.system||"",privacy:e.privacy}},b=O({botToken:t,route:o,transport:o().transport,model:o().model,provider:o().provider,baseUrl:o().baseUrl,token:m.token,pairing:i,savePairing:y,appender:S,agent:e.agent,system:e.system||"",redact:{tier:e.tier},privacy:e.privacy,logger:f,signal:k.signal});Promise.resolve(b).catch(a=>{d=a?.message||String(a),f.warn?.(`[channels] telegram loop failed: ${d}`)}).finally(()=>{if(g=!1,h)return;const a=C[Math.min(A++,C.length-1)];f.warn?.(`[channels] telegram stopped unexpectedly — retrying in ${Math.round(a/1e3)}s`),setTimeout(()=>{h||$(t)},a).unref?.()})}async function U(){if(g)return{ok:!0,already:!0};await l();const t=await E();if(!t)return{ok:!1,error:"no bot token configured"};if(e.enabled===!1)return{ok:!1,error:"channel is turned off"};try{u=await N(t,{fetchImpl:c})}catch(r){return d=r?.message||String(r),{ok:!1,error:d}}return d="",A=0,h=!1,$(t),{ok:!0,bot:u}}return{async startIfConfigured(){return await l(),!await E()||e.enabled===!1?{ok:!1,skipped:!0}:U().catch(t=>({ok:!1,error:t?.message||String(t)}))},start:U,async connect({token:t,agent:r,privacy:o,tier:b}={}){await l();const a=await N(t,{fetchImpl:c});await J(p,String(t).trim(),{mode:384}),e={...e,...r?{agent:r}:{},...o?{privacy:o}:{},...b?{tier:b}:{},enabled:!0},await T(),await this.stop();const x=await U();if(!x.ok)throw new Error(x.error);return{bot:a,settings:{...e}}},async pair({ttlMs:t=10*6e4}={}){if(await l(),!u)throw new Error("connect a bot first");const r=i.requestCode({ttlMs:t});return await y(),{code:r,link:Q(u.username,r),expiresAt:w()+t,bot:{...u}}},async allow(t,{reach:r="trusted"}={}){return await l(),i.allow(t,{reach:r}),await y(),{actorId:t,reach:r}},async unpair(t){await l();const r=i.revoke(t);return await y(),{removed:r}},async update(t={}){await l();const r={...e};for(const o of["agent","model","provider","gatewayUrl","privacy","tier","system"])t[o]!=null&&(r[o]=t[o]);return t.agent!=null&&t.model==null&&(r.model="",r.provider=""),t.model&&(r.agent=""),e=r,await T(),{settings:{...e}}},async stop({forget:t=!1}={}){if(h=!0,k?.abort(),k=null,g=!1,t){await l(),e={...e,enabled:!1},await T(),await z(p,{force:!0});for(const r of i.list())i.revoke(r.actorId);await y(),u=null}return{ok:!0}},async status(){return await l(),{channel:"telegram",configured:!!await E(),enabled:e.enabled!==!1,running:g,bot:u?{...u}:null,error:d,paired:i.list(),settings:{agent:e.agent,model:e.model||"",provider:e.provider||"",gatewayUrl:e.gatewayUrl||j,privacy:e.privacy,tier:e.tier},via:e.model?"gateway":"bridge"}}}}export{P as DEFAULT_SETTINGS,at as createChannelService,Q as pairLink,N as verifyBot};
1
+ import k from"node:path";import{readFile as L,writeFile as P,mkdir as R,rm as z,stat as B}from"node:fs/promises";import{readFileSync as Y}from"node:fs";import{createPairingStore as q}from"./pairing.js";import*as H from"./bridge.js";import*as I from"./gateway.js";const S="http://127.0.0.1:4320";import{createEventLog as W}from"./eventlog.js";import{startTelegram as D}from"./adapters/telegram.js";import{createPersonalContext as K}from"./personal.js";const Q="https://api.telegram.org",C=Object.freeze({agent:"claude",model:"",provider:"",gatewayUrl:S,privacy:"standard",tier:"basic"}),J=[2e3,5e3,15e3,6e4],G=async(s,n)=>{try{return JSON.parse(await L(s,"utf8"))}catch{return n}},M=(s,n)=>P(s,JSON.stringify(n,null,2),{mode:384});async function N(s,{fetchImpl:n=fetch,signal:m}={}){const f=await n(`${Q}/bot${String(s||"").trim()}/getMe`,{signal:m}),l=await f.json().catch(()=>null);if(!l?.ok){const p=l?.description||`HTTP ${f.status}`;throw new Error(/unauthorized/i.test(p)?"Telegram rejected that token — copy it again from @BotFather":p)}return{id:l.result.id,username:l.result.username,name:l.result.first_name||""}}const V=(s,n)=>`https://t.me/${s}?start=${n}`;function ot({home:s,dataDir:n,bridge:m,logger:f=console,fetchImpl:l=void 0,now:p=()=>Date.now(),startAdapter:O=D}={}){const w=k.join(s,"telegram-token"),_=k.join(n,"config.json"),F=k.join(n,"pairing.json");let i=null,t={...C},T=null,u=null,v=null,g=!1,d="",x=0,h=!0;const y=()=>M(F,i?i.toJSON():{}),U=()=>M(_,t);async function E(){try{const e=(await L(w,"utf8")).trim();if(!e)return"";try{const{mode:r}=await B(w);r&63&&f.warn?.(`[channels] ${w} is group/world-readable — chmod 600 it (it holds your bot token).`)}catch{}return e}catch{return""}}async function c(){await R(n,{recursive:!0}),i||(i=q(await G(F,{}),{now:p})),t={...C,...await G(_,{})},T||(T=await W({file:k.join(n,"events.jsonl"),host:"channel"}))}function A(e){v=new AbortController,g=!0;const r=()=>{try{return Y(k.join(s,"gateway-token"),"utf8").trim()}catch{return""}},o=()=>{const a=!!t.model;return{transport:a?I:H,token:a?r():m.token,agent:a?"":t.agent,model:a?t.model:"",provider:a&&t.provider||"",baseUrl:a?t.gatewayUrl||S:m.baseUrl,system:t.system||"",privacy:t.privacy}},b=O({botToken:e,personal:t.personal===!1?null:K({baseUrl:t.gatewayUrl||S,token:r,fetchImpl:l}),route:o,transport:o().transport,model:o().model,provider:o().provider,baseUrl:o().baseUrl,token:m.token,pairing:i,savePairing:y,appender:T,agent:t.agent,system:t.system||"",redact:{tier:t.tier},privacy:t.privacy,logger:f,signal:v.signal});Promise.resolve(b).catch(a=>{d=a?.message||String(a),f.warn?.(`[channels] telegram loop failed: ${d}`)}).finally(()=>{if(g=!1,h)return;const a=J[Math.min(x++,J.length-1)];f.warn?.(`[channels] telegram stopped unexpectedly — retrying in ${Math.round(a/1e3)}s`),setTimeout(()=>{h||A(e)},a).unref?.()})}async function j(){if(g)return{ok:!0,already:!0};await c();const e=await E();if(!e)return{ok:!1,error:"no bot token configured"};if(t.enabled===!1)return{ok:!1,error:"channel is turned off"};try{u=await N(e,{fetchImpl:l})}catch(r){return d=r?.message||String(r),{ok:!1,error:d}}return d="",x=0,h=!1,A(e),{ok:!0,bot:u}}return{async startIfConfigured(){return await c(),!await E()||t.enabled===!1?{ok:!1,skipped:!0}:j().catch(e=>({ok:!1,error:e?.message||String(e)}))},start:j,async connect({token:e,agent:r,privacy:o,tier:b}={}){await c();const a=await N(e,{fetchImpl:l});await P(w,String(e).trim(),{mode:384}),t={...t,...r?{agent:r}:{},...o?{privacy:o}:{},...b?{tier:b}:{},enabled:!0},await U(),await this.stop();const $=await j();if(!$.ok)throw new Error($.error);return{bot:a,settings:{...t}}},async pair({ttlMs:e=10*6e4}={}){if(await c(),!u)throw new Error("connect a bot first");const r=i.requestCode({ttlMs:e});return await y(),{code:r,link:V(u.username,r),expiresAt:p()+e,bot:{...u}}},async allow(e,{reach:r="trusted"}={}){return await c(),i.allow(e,{reach:r}),await y(),{actorId:e,reach:r}},async unpair(e){await c();const r=i.revoke(e);return await y(),{removed:r}},async update(e={}){await c();const r={...t};for(const o of["agent","model","provider","gatewayUrl","privacy","tier","system"])e[o]!=null&&(r[o]=e[o]);return e.agent!=null&&e.model==null&&(r.model="",r.provider=""),e.model&&(r.agent=""),t=r,await U(),{settings:{...t}}},async stop({forget:e=!1}={}){if(h=!0,v?.abort(),v=null,g=!1,e){await c(),t={...t,enabled:!1},await U(),await z(w,{force:!0});for(const r of i.list())i.revoke(r.actorId);await y(),u=null}return{ok:!0}},async status(){return await c(),{channel:"telegram",configured:!!await E(),enabled:t.enabled!==!1,running:g,bot:u?{...u}:null,error:d,paired:i.list(),settings:{agent:t.agent,model:t.model||"",provider:t.provider||"",gatewayUrl:t.gatewayUrl||S,privacy:t.privacy,tier:t.tier},via:t.model?"gateway":"bridge"}}}}export{C as DEFAULT_SETTINGS,ot as createChannelService,V as pairLink,N as verifyBot};
@@ -1,7 +1,7 @@
1
- import{runSpec as h,listSpecModels as A,runForStdout as d,CHATPANEL_STABLE_MCP_URL as m}from"./custom.js";import{agentAvailable as b,selfMcpStdio as u}from"../env.js";function i(e,o,a,t={}){let r=!1,s=0;const n={sandboxEngine:e,...o,command:e};return{spec:n,async available(){if(Date.now()-s>(r?3e4:4e3)){s=Date.now();try{r=b(e)}catch{r=!1}}return r?{ok:!0}:{ok:!1,reason:a}},listModels(l={}){return t.listModels?t.listModels(e,l):A(e,o.listModelsArgs,l.workingDir)},chat(l,c,p){return h(n,l,c,p)}}}const _=i("pi",{args:"-p",promptVia:"stdin",modelArg:"--model {model}",imageArg:"@{path}",toolAdapter:"pi-extension",listModelsArgs:"--list-models",label:"Pi"},"pi not found on PATH. Install Pi, then run `pi` once to sign in."),D=i("opencode",{args:"run --format json --dangerously-skip-permissions",promptVia:"stdin",modelArg:"-m {model}",imageArg:"-f {path}",format:"opencode-json",mcpViaEnv:{env:"OPENCODE_CONFIG_CONTENT",args:["--standalone"]},listModelsArgs:"models",label:"OpenCode"},"opencode not found on PATH. Install opencode, then sign in."),H=i("kiro-cli",{args:"chat --no-interactive --require-mcp-startup",promptVia:"stdin",modelArg:"--model {model}",trustAllToolsForMcp:!0,trustAllToolsArg:"--trust-all-tools",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"kiro",stableMcpSetupArgs:["mcp","add","--scope","global","--name","chatpanel_browser","--url","http://127.0.0.1:4319/mcp","--force"],stableMcpSetupCommand:"kiro-cli mcp add --scope global --name chatpanel_browser --url http://127.0.0.1:4319/mcp --force",listModelsArgs:"--list-models",label:"Kiro"},"kiro-cli not found on PATH. Install Kiro CLI, then sign in."),S=["--output-format","json","--no-color","--log-level","none","--no-ask-user","--no-auto-update","--no-remote","--no-remote-export"],P=i("copilot",{args:S,promptVia:"stdin",modelArg:"--model {model}",imageArg:"--attachment {path}",format:"copilot-json",mcpArg:"--additional-mcp-config @{file}",permissionArgs:{default:["--allow-all-tools"],acceptEdits:["--allow-all-tools","--allow-all-paths"],bypassPermissions:["--allow-all"]},forbidden:"copilot",label:"GitHub Copilot"},"copilot not found on PATH. Install GitHub Copilot CLI, then run `copilot login`.",{listModels:(e,o)=>M(e,o.workingDir)});async function M(e="copilot",o){const a=await d(e,["help","config"],o),t=[],r=new Set;let s=!1;for(const n of String(a||"").split(`
2
- `)){const l=/^\s*`([A-Za-z][\w.]*)`\s*:/.exec(n);if(l){s=l[1]==="model";continue}if(!s)continue;const c=/^\s*-\s*"([^"]+)"\s*$/.exec(n);if(!c)continue;const p=c[1];if(!r.has(p)&&(r.add(p),t.push(p),t.length>=200))break}return t.length?["auto",...t]:[]}const E=i("dsh",{args:["--profile","headless","{prompt}"],promptVia:"arg",format:"text",modelPatch:{arg:"--patch {file}",build:e=>`- id: ${g}
1
+ import{runSpec as h,listSpecModels as A,runForStdout as d,CHATPANEL_STABLE_MCP_URL as m}from"./custom.js";import{agentAvailable as S,selfMcpStdio as u}from"../env.js";function i(e,o,a,t={}){let r=!1,s=0;const n={sandboxEngine:e,...o,command:e};return{spec:n,async available(){if(Date.now()-s>(r?3e4:4e3)){s=Date.now();try{r=S(e)}catch{r=!1}}return r?{ok:!0}:{ok:!1,reason:a}},listModels(l={}){return t.listModels?t.listModels(e,l):A(e,o.listModelsArgs,l.workingDir)},chat(l,c,p){return h(n,l,c,p)}}}const D=i("pi",{args:"-p",promptVia:"stdin",modelArg:"--model {model}",imageArg:"@{path}",toolAdapter:"pi-extension",listModelsArgs:"--list-models",label:"Pi"},"pi not found on PATH. Install Pi, then run `pi` once to sign in."),E=i("opencode",{args:"run --format json --dangerously-skip-permissions",promptVia:"stdin",modelArg:"-m {model}",imageArg:"-f {path}",format:"opencode-json",mcpViaEnv:{env:"OPENCODE_CONFIG_CONTENT",args:["--standalone"]},live:{serve:["serve","--hostname","127.0.0.1","--port","0"],attach:["--server","{url}"],passwordEnv:"OPENCODE_SERVER_PASSWORD",user:"opencode",events:"/api/event"},listModelsArgs:"models",label:"OpenCode"},"opencode not found on PATH. Install opencode, then sign in."),P=i("kiro-cli",{args:"chat --no-interactive --require-mcp-startup",promptVia:"stdin",modelArg:"--model {model}",trustAllToolsForMcp:!0,trustAllToolsArg:"--trust-all-tools",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"kiro",stableMcpSetupArgs:["mcp","add","--scope","global","--name","chatpanel_browser","--url","http://127.0.0.1:4319/mcp","--force"],stableMcpSetupCommand:"kiro-cli mcp add --scope global --name chatpanel_browser --url http://127.0.0.1:4319/mcp --force",listModelsArgs:"--list-models",label:"Kiro"},"kiro-cli not found on PATH. Install Kiro CLI, then sign in."),b=["--output-format","json","--no-color","--log-level","none","--no-ask-user","--no-auto-update","--no-remote","--no-remote-export"],x=i("copilot",{args:b,promptVia:"stdin",modelArg:"--model {model}",imageArg:"--attachment {path}",format:"copilot-json",mcpArg:"--additional-mcp-config @{file}",permissionArgs:{default:["--allow-all-tools"],acceptEdits:["--allow-all-tools","--allow-all-paths"],bypassPermissions:["--allow-all"]},forbidden:"copilot",label:"GitHub Copilot"},"copilot not found on PATH. Install GitHub Copilot CLI, then run `copilot login`.",{listModels:(e,o)=>M(e,o.workingDir)});async function M(e="copilot",o){const a=await d(e,["help","config"],o),t=[],r=new Set;let s=!1;for(const n of String(a||"").split(`
2
+ `)){const l=/^\s*`([A-Za-z][\w.]*)`\s*:/.exec(n);if(l){s=l[1]==="model";continue}if(!s)continue;const c=/^\s*-\s*"([^"]+)"\s*$/.exec(n);if(!c)continue;const p=c[1];if(!r.has(p)&&(r.add(p),t.push(p),t.length>=200))break}return t.length?["auto",...t]:[]}const v=i("dsh",{args:["--profile","headless","{prompt}"],promptVia:"arg",format:"text",modelPatch:{arg:"--patch {file}",build:e=>`- id: ${g}
3
3
  config:
4
4
  provider: ${k}
5
5
  model: ${JSON.stringify(e)}
6
6
  `},label:"DeepSeek Harness"},'dsh not found on PATH. Install DeepSeek Harness, then run `dsh --profile headless "hi"` once to check the profile.',{listModels:(e,o)=>w(e,o.workingDir)}),g="agent-default-model",k="deepseek-official",f=["deepseek-v4-flash","deepseek-v4-pro"];async function w(e="dsh",o){const a=await d(e,["--profile","headless","--dump-config"],o,6e4),t=String(a||"").split(`
7
- `),r=new RegExp(`^-\\s*id:\\s*${g}\\s*$`);for(let s=0;s<t.length;s++)if(r.test(t[s]))for(let n=s+1;n<t.length&&!/^-\s*id:/.test(t[n]);n++){const l=/^\s*model:\s*['"]?([\w.:-]+)['"]?\s*$/.exec(t[n]);if(l)return[...new Set([l[1],...f])]}return[...f]}const O=i("hermes",{args:"-z {prompt}",promptVia:"arg",modelArg:"-m {model}",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"hermes",stableMcpSetupArgs:()=>{const{command:e,args:o}=u(m);return["mcp","add","chatpanel_browser","--command",e,"--args",...o]},stableMcpSetupCommand:(()=>{const{command:e,args:o}=u(m);return`hermes mcp add chatpanel_browser --command ${e} --args ${o.join(" ")}`})(),label:"Hermes"},"hermes not found on PATH. Install Hermes Agent, then run `hermes setup` to sign in.",{listModels:async(e,o={})=>{try{const a=await d(e,["config","get","model"],o.workingDir),t=/^\s*default:\s*(\S+)/m.exec(a||"");return t?[t[1]]:[]}catch{return[]}}});export{P as copilot,E as deepseek,O as hermes,H as kiro,M as listCopilotModels,w as listDshModels,D as opencode,_ as pi};
7
+ `),r=new RegExp(`^-\\s*id:\\s*${g}\\s*$`);for(let s=0;s<t.length;s++)if(r.test(t[s]))for(let n=s+1;n<t.length&&!/^-\s*id:/.test(t[n]);n++){const l=/^\s*model:\s*['"]?([\w.:-]+)['"]?\s*$/.exec(t[n]);if(l)return[...new Set([l[1],...f])]}return[...f]}const H=i("hermes",{args:"-z {prompt}",promptVia:"arg",modelArg:"-m {model}",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"hermes",stableMcpSetupArgs:()=>{const{command:e,args:o}=u(m);return["mcp","add","chatpanel_browser","--command",e,"--args",...o]},stableMcpSetupCommand:(()=>{const{command:e,args:o}=u(m);return`hermes mcp add chatpanel_browser --command ${e} --args ${o.join(" ")}`})(),label:"Hermes"},"hermes not found on PATH. Install Hermes Agent, then run `hermes setup` to sign in.",{listModels:async(e,o={})=>{try{const a=await d(e,["config","get","model"],o.workingDir),t=/^\s*default:\s*(\S+)/m.exec(a||"");return t?[t[1]]:[]}catch{return[]}}});export{x as copilot,v as deepseek,H as hermes,P as kiro,M as listCopilotModels,w as listDshModels,E as opencode,D as pi};
@@ -1,15 +1,15 @@
1
- import{spawn as L}from"node:child_process";import{readFile as et,writeFile as _,unlink as rt}from"node:fs/promises";import T from"node:os";import x from"node:path";import{resolveCommand as I,buildSpawnSpec as N,selfMcpStdio as H}from"../env.js";import{missingCommandMessage as J}from"../events/mcp-errors.js";import{sandbox as F,noteSandbox as nt,track as R,grantedWriteRoots as ot}from"../sandbox.js";import{harnessDirArgs as it,harnessOwnModel as st}from"../events/harness-cards.js";import{readFileSync as at}from"node:fs";import{isProEntitled as V}from"../entitlement.js";import{killOnAbort as lt}from"../proc.js";import{buildCliPrompt as ct,fitCliPrompt as mt,argvPromptBudget as ut}from"./prompt.js";import{pushExtraArgs as pt,FORBIDDEN as z}from"./args.js";import{createStreamParser as dt,STREAM_FORMATS as ft}from"./stream-formats.js";import{resolveWorkdir as gt}from"../workdir.js";import{cliError as ht}from"../cli-errors.js";async function wt(t,n){const e=[];for(let r=0;r<(t?.length||0);r++){const o=/^data:([^;]+);base64,(.+)$/s.exec(t[r]?.dataUrl||"");if(!o)continue;const s=(o[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",f=x.join(T.tmpdir(),`chatpanel-custom-img-${n}-${r}.${s}`);await _(f,Buffer.from(o[2],"base64")),e.push(f)}return e}function St(t,n){const e=String(t||"").trim();if(!e||!n.length)return[];const r=[];for(const o of n)r.push(...e.includes("{path}")?e.replaceAll("{path}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]);return r}const G=Number(process.env.CHATPANEL_CUSTOM_TIMEOUT_MS)||18e4,yt="http://127.0.0.1:4319/mcp",D="http://127.0.0.1:4319/mcp";async function ee(){return{ok:!0}}function bt(t){const n=[],e=new Set;for(const r of String(t||"").split(`
2
- `)){const o=r.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(o)&&!/^(name|model|models|id|provider|available|usage|options|commands)$/i.test(o)&&!e.has(o)&&(e.add(o),n.push(o),n.length>=200))break}return n}async function re(t={}){if(!await V(t.entitlement))throw new Error("Custom agents require ChatPanel Pro.");const n=t.custom||{};return Ct(n.command,n.listModelsArgs,t.workingDir)}async function Ct(t,n,e){const r=String(n||"").trim();if(!t||!r)return[];const o=await $t(t,r.split(/\s+/).filter(Boolean),e);return bt(o)}async function $t(t,n,e,r=2e4){if(!t)return"";const o=I(t);if(!o)throw new Error(J(t,{platform:process.platform}));const s=e?x.resolve(e):null,[f,h,w]=N(o,n,s);w.env={...w.env||process.env,NO_COLOR:"1",CLICOLOR:"0"};const y=await F().wrap(f,h,w,{engine:"custom",cwd:s}),{bin:m,argv:b,opts:d}=y;return new Promise((i,S)=>{let g;try{g=R(L(m,b,d),y,{kind:"probe"})}catch(A){return S(new Error(`Failed to start ${t}: ${A.message}`))}let u="";const v=setTimeout(()=>{g.kill("SIGKILL"),S(new Error(`${t} timed out.`))},r);g.stdout.on("data",A=>u+=A.toString()),g.on("error",A=>{clearTimeout(v),S(new Error(`Failed to start ${t}: ${A.message}`))}),g.on("close",()=>{clearTimeout(v),i(u)});try{g.stdin.end()}catch{}})}function K(t){return(t?.specs||[]).filter(n=>n?.name)}function Z(t,n){const e=String(t).replace(/[^A-Za-z0-9_$]/g,"_");return/^[A-Za-z_$]/.test(e)?e:`tool_${n}_${e}`}function At(t,n){return["--extension",t]}function xt(t,n){const e=String(t||"").trim(),r=K(n).map(s=>s.name).filter(Boolean);if(!e||!r.length)return[];const o=r.join(",");return e.includes("{tools}")?e.replaceAll("{tools}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]}function vt(t={},n){return t.trustAllToolsForMcp?[t.trustAllToolsArg||"--trust-all-tools"]:t.trustToolsArg?xt(t.trustToolsArg,n):[]}function Et(t={}){return t.stableMcpSetupCommand?t.stableMcpSetupCommand:`opencode mcp add chatpanel --url ${D}`}function Mt(t={}){const n=typeof t.stableMcpSetupArgs=="function"?t.stableMcpSetupArgs():t.stableMcpSetupArgs,e=Array.isArray(n)?n.filter(r=>r!=null).map(String):null;return e?.length?{command:t.stableMcpSetupCommandName||t.command,args:e}:null}function Tt(t){const n=K(t),e=n.map((o,s)=>{const f=Z(o.name,s),h=o.parameters||{type:"object",properties:{}};return`const ${f}Tool = {
1
+ import{spawn as I}from"node:child_process";import{readFile as it,writeFile as N,unlink as st}from"node:fs/promises";import O from"node:os";import A from"node:path";import{resolveCommand as F,buildSpawnSpec as R,selfMcpStdio as V}from"../env.js";import{missingCommandMessage as G}from"../events/mcp-errors.js";import{sandbox as B,noteSandbox as at,track as j,grantedWriteRoots as lt}from"../sandbox.js";import{harnessDirArgs as ct,harnessOwnModel as mt}from"../events/harness-cards.js";import{readFileSync as ut}from"node:fs";import{isProEntitled as K}from"../entitlement.js";import{killOnAbort as pt}from"../proc.js";import{buildCliPrompt as dt,fitCliPrompt as ft,argvPromptBudget as gt}from"./prompt.js";import{pushExtraArgs as ht,FORBIDDEN as Z}from"./args.js";import{createStreamParser as wt,STREAM_FORMATS as St}from"./stream-formats.js";import{resolveWorkdir as yt}from"../workdir.js";import{cliError as vt}from"../cli-errors.js";import{startLiveServer as bt}from"./opencode-live.js";async function Ct(t,n){const e=[];for(let r=0;r<(t?.length||0);r++){const o=/^data:([^;]+);base64,(.+)$/s.exec(t[r]?.dataUrl||"");if(!o)continue;const a=(o[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",f=A.join(O.tmpdir(),`chatpanel-custom-img-${n}-${r}.${a}`);await N(f,Buffer.from(o[2],"base64")),e.push(f)}return e}function $t(t,n){const e=String(t||"").trim();if(!e||!n.length)return[];const r=[];for(const o of n)r.push(...e.includes("{path}")?e.replaceAll("{path}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]);return r}const q=Number(process.env.CHATPANEL_CUSTOM_TIMEOUT_MS)||18e4,W=Object.freeze({NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"}),At="http://127.0.0.1:4319/mcp",H="http://127.0.0.1:4319/mcp";async function ae(){return{ok:!0}}function xt(t){const n=[],e=new Set;for(const r of String(t||"").split(`
2
+ `)){const o=r.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(o)&&!/^(name|model|models|id|provider|available|usage|options|commands)$/i.test(o)&&!e.has(o)&&(e.add(o),n.push(o),n.length>=200))break}return n}async function le(t={}){if(!await K(t.entitlement))throw new Error("Custom agents require ChatPanel Pro.");const n=t.custom||{};return Et(n.command,n.listModelsArgs,t.workingDir)}async function Et(t,n,e){const r=String(n||"").trim();if(!t||!r)return[];const o=await Mt(t,r.split(/\s+/).filter(Boolean),e);return xt(o)}async function Mt(t,n,e,r=2e4){if(!t)return"";const o=F(t);if(!o)throw new Error(G(t,{platform:process.platform}));const a=e?A.resolve(e):null,[f,g,w]=R(o,n,a);w.env={...w.env||process.env,NO_COLOR:"1",CLICOLOR:"0"};const S=await B().wrap(f,g,w,{engine:"custom",cwd:a}),{bin:m,argv:v,opts:d}=S;return new Promise((i,y)=>{let h;try{h=j(I(m,v,d),S,{kind:"probe"})}catch($){return y(new Error(`Failed to start ${t}: ${$.message}`))}let u="";const x=setTimeout(()=>{h.kill("SIGKILL"),y(new Error(`${t} timed out.`))},r);h.stdout.on("data",$=>u+=$.toString()),h.on("error",$=>{clearTimeout(x),y(new Error(`Failed to start ${t}: ${$.message}`))}),h.on("close",()=>{clearTimeout(x),i(u)});try{h.stdin.end()}catch{}})}function Q(t){return(t?.specs||[]).filter(n=>n?.name)}function X(t,n){const e=String(t).replace(/[^A-Za-z0-9_$]/g,"_");return/^[A-Za-z_$]/.test(e)?e:`tool_${n}_${e}`}function Tt(t,n){return["--extension",t]}function Ot(t,n){const e=String(t||"").trim(),r=Q(n).map(a=>a.name).filter(Boolean);if(!e||!r.length)return[];const o=r.join(",");return e.includes("{tools}")?e.replaceAll("{tools}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]}function Pt(t={},n){return t.trustAllToolsForMcp?[t.trustAllToolsArg||"--trust-all-tools"]:t.trustToolsArg?Ot(t.trustToolsArg,n):[]}function kt(t={}){return t.stableMcpSetupCommand?t.stableMcpSetupCommand:`opencode mcp add chatpanel --url ${H}`}function Lt(t={}){const n=typeof t.stableMcpSetupArgs=="function"?t.stableMcpSetupArgs():t.stableMcpSetupArgs,e=Array.isArray(n)?n.filter(r=>r!=null).map(String):null;return e?.length?{command:t.stableMcpSetupCommandName||t.command,args:e}:null}function _t(t){const n=Q(t),e=n.map((o,a)=>{const f=X(o.name,a),g=o.parameters||{type:"object",properties:{}};return`const ${f}Tool = {
3
3
  name: ${JSON.stringify(o.name)},
4
4
  label: ${JSON.stringify(o.name)},
5
5
  description: ${JSON.stringify(o.description||o.name)},
6
- parameters: ${JSON.stringify(h)},
6
+ parameters: ${JSON.stringify(g)},
7
7
  async execute(toolCallId, params, signal) {
8
8
  return callMcpTool(${JSON.stringify(o.name)}, toolCallId, params, signal);
9
9
  },
10
10
  };`}).join(`
11
11
 
12
- `),r=n.map((o,s)=>` pi.registerTool(${Z(o.name,s)}Tool);`).join(`
12
+ `),r=n.map((o,a)=>` pi.registerTool(${X(o.name,a)}Tool);`).join(`
13
13
  `);return`import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
14
14
 
15
15
  const MCP_URL = ${JSON.stringify(t.url)};
@@ -65,7 +65,7 @@ ${e}
65
65
  export default function (pi: ExtensionAPI) {
66
66
  ${r}
67
67
  }
68
- `}async function Ot(t,n){const e=x.join(T.tmpdir(),`chatpanel-pi-tools-${n}.ts`);return await _(e,Tt(t)),e}async function Pt(){const t=process.env.XDG_CONFIG_HOME||x.join(T.homedir(),".config"),n=[x.join(t,"opencode","opencode.jsonc"),x.join(T.homedir(),"Library","Application Support","opencode","opencode.jsonc")];for(const e of n)try{if((await et(e,"utf8")).includes(yt))return!0}catch{}return!1}async function q(t,n,e){const r=I(t);if(!r)return"";const[o,s,f]=N(r,n,e||null),h=await F().wrap(o,s,f,{engine:"custom",cwd:e||null}),{bin:w,argv:y,opts:m}=h;return new Promise(b=>{const d=R(L(w,y,m),h,{kind:"probe"});let i="",S="";const g=setTimeout(()=>{d.kill("SIGKILL"),b(i+S)},4e3);d.stdout.on("data",u=>i+=u.toString()),d.stderr.on("data",u=>S+=u.toString()),d.on("error",()=>{clearTimeout(g),b(i+S)}),d.on("close",()=>{clearTimeout(g),b(i+S)});try{d.stdin.end()}catch{}})}async function kt(t,n){for(const e of["workspace","global","default"]){const r=await q(t,["mcp","list",e],n);if(r.includes(D)||/chatpanel_browser/i.test(r))return!0}return!1}async function Lt(t,n){const e=await q(t,["mcp","list"],n);return e.includes(D)||/chatpanel_browser/i.test(e)}async function _t(t,n){return t.stableMcpConfigCheck==="kiro"?kt(t.command||"kiro-cli",n):t.stableMcpConfigCheck==="opencode"?Pt():t.stableMcpConfigCheck==="hermes"?Lt(t.command||"hermes",n):!1}async function It(t,n){const e=I(t.command);if(!e)throw new Error(`Couldn't find "${t.command}" to set up browser tools.`);const[r,o,s]=N(e,t.args,n||null);s.env={...s.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"};const f=await F().wrap(r,o,s,{engine:"custom",cwd:n||null}),{bin:h,argv:w,opts:y}=f;await new Promise((m,b)=>{let d;try{d=R(L(h,w,y),f,{kind:"probe"})}catch(u){return b(new Error(`Failed to start ${t.command}: ${u.message}`))}let i="",S="";const g=setTimeout(()=>{d.kill("SIGKILL"),b(new Error(`${t.command} MCP setup timed out.`))},2e4);d.stderr.on("data",u=>i+=u.toString()),d.stdout?.on("data",u=>S+=u.toString()),d.on("error",u=>{clearTimeout(g),b(new Error(`Failed to start ${t.command}: ${u.message}`))}),d.on("close",u=>{if(clearTimeout(g),u===0)return m(`${S}
69
- ${i}`.trim());b(new Error(`${t.command} MCP setup exited ${u}: ${i.trim().split(`
70
- `).pop()||"failed"}`))});try{d.stdin.end()}catch{}})}function Nt(t,n){const e=String(n?.message||n||"");return/mcp['" ]* Python SDK|No module named ['"]?mcp|MCP support/i.test(e)?`${t} has no MCP support installed. Run \`hermes setup\` (or install the \`mcp\` package in its environment), then retry.`:/streamable_http|HTTP transport/i.test(e)?`${t}'s MCP client has no HTTP transport; ChatPanel registers a stdio server instead. Upgrade its \`mcp\` package if this persists.`:e.slice(0,200)||"the CLI could not register the tools"}async function Ft(t,n,e,r,o={}){if(!t.requiresStableMcp)return!0;const s=o.hasConfig||_t,f=o.runSetup||It;if(await s(t,n))return!0;const h=Et(t);if(!t.autoSetupStableMcp){const m=`${e} needs one-time browser-tool setup: ${h}`;throw r({type:"status",text:m}),new Error(m)}const w=Mt(t);if(!w?.command){const m=`${e} needs one-time browser-tool setup: ${h}`;throw r({type:"status",text:m}),new Error(m)}r({type:"status",text:`${e} is setting up one-time browser tools...`});const y=String(await f(w,n)||"").trim();if(await s(t,n))return!0;throw new Error(`${e} browser-tool setup did not register the server.`+(y?` ${y.split(`
71
- `).filter(Boolean).slice(-3).join(" ")}`:"")+` Run: ${h}`)}async function ne({messages:t,system:n,options:e,images:r},o,{signal:s}={}){if(!await V(e.entitlement))throw new Error("Custom agents require ChatPanel Pro. Upgrade in Settings to bring your own CLI agent.");return Rt(e.custom||{},{messages:t,system:n,options:e,images:r},o,{signal:s})}async function Rt(t,{messages:n,system:e,options:r={},images:o},s,{signal:f}={}){if(!t.command)throw new Error("This agent has no command configured.");const h=I(t.command);if(!h)throw new Error(J(t.command,{platform:process.platform}));let w=ct(n,e),y=gt(r.workingDir);const m=t.label||t.command,b=Object.hasOwn(ft,t.format)?t.format:"text",d=t.promptVia==="arg"?"arg":"stdin";let i=Array.isArray(t.args)?t.args.slice():t.args?String(t.args).split(/\s+/).filter(Boolean):[];pt(i,r.extraArgs,z[t.forbidden]||z.custom,s);const S=r.model||(t.modelArg?st({harness:t.dirsHarness||t.command,env:process.env,home:T.homedir(),readFile:a=>{try{return at(a,"utf8")}catch{return null}}}):"");if(S&&t.modelArg){const a=String(t.modelArg),l=a.includes("{model}")?a.replaceAll("{model}",S).split(/\s+/).filter(Boolean):[...a.split(/\s+/).filter(Boolean),S];i=[...i,...l]}if(t.permissionArgs){const a=String(r.permissionMode||"default"),l=t.permissionArgs[a]||t.permissionArgs.default||[];i=[...i,...l.map(String)]}i=[...i,...it({harness:t.dirsHarness||t.command,roots:ot(y),dirs:t.dirs!==void 0?t.dirs:r.dirs})];const g=`${Date.now()}-${Math.random().toString(36).slice(2)}`,u=t.imageArg?await wt(o,g):[],v=[];let A=null;const P=()=>[...u,...v].forEach(a=>rt(a).catch(()=>{}));if(r.mcp?.url&&t.toolAdapter==="pi-extension"){const a=await Ot(r.mcp,g);v.push(a),i=[...At(a,r.mcp),...i]}else if(r.mcp?.url&&t.mcpArg){const a=r.mcp.serverName||"chatpanel_browser",{command:l,args:p}=H(r.mcp.url),c=x.join(T.tmpdir(),`chatpanel-mcp-${g}.json`);await _(c,JSON.stringify({mcpServers:{[a]:{command:l,args:p}}})),v.push(c);const C=String(t.mcpArg);i=[...C.includes("{file}")?C.replaceAll("{file}",c).split(/\s+/).filter(Boolean):[...C.split(/\s+/).filter(Boolean),c],...i]}else if(r.mcp?.url&&t.mcpViaEnv?.env){const a=r.mcp.serverName||"chatpanel_browser",{command:l,args:p}=H(r.mcp.url);let c={};try{c=JSON.parse(process.env[t.mcpViaEnv.env]||"{}")||{}}catch{c={}}const C={...c.mcp?.servers||{},[a]:{type:"local",command:[l,...p]}};A={[t.mcpViaEnv.env]:JSON.stringify({...c,mcp:{...c.mcp||{},servers:C}})},t.mcpViaEnv.args?.length&&(i=[i[0],...t.mcpViaEnv.args,...i.slice(1)].filter(M=>M!==void 0))}if(r.mcp?.url&&!t.mcpViaEnv?.env)try{await Ft(t,y,m,s)}catch(a){s({type:"status",text:`${m}: continuing without ChatPanel's browser tools — ${Nt(m,a)}`}),r={...r,mcp:null}}if(r.mcp?.url&&i.push(...vt(t,r.mcp)),r.model&&typeof t.modelPatch?.build=="function"){const a=/^[A-Za-z0-9][\w.:-]{0,79}$/.test(String(r.model))?String(r.model):"";if(a){const l=x.join(T.tmpdir(),`chatpanel-modelpatch-${g}.yml`);await _(l,t.modelPatch.build(a)),v.push(l);const p=String(t.modelPatch.arg||"--patch {file}");i=[...p.includes("{file}")?p.replaceAll("{file}",l).split(/\s+/).filter(Boolean):[...p.split(/\s+/).filter(Boolean),l],...i]}}const E=St(t.imageArg,u);let B=!1;if(E.length&&(i=i.flatMap(a=>a==="{images}"?(B=!0,E):[a])),d==="arg"){const a=i.reduce((c,C)=>c+String(C).length+3,0)+E.reduce((c,C)=>c+String(C).length+3,0),l=mt(n,e,ut({viaCmdExe:h.kind==="cmd",otherArgsChars:a}));(l.dropped||l.prompt!==w)&&(w=l.prompt,s({type:"status",text:`${m} takes the prompt as a command-line argument, which this system caps — the oldest ${l.dropped||"part of the"} turn${l.dropped===1?"":"s"} of this conversation ${l.dropped?"were":"was"} left out to fit.`}));let p=!1;i=i.map(c=>c.includes("{prompt}")?(p=!0,c.replaceAll("{prompt}",w)):c),p||(E.length&&!B&&i.push(...E),i.push(w))}else E.length&&!B&&i.push(...E);const[W,X,j]=N(h,i,y,r.runEnv||null);j.env={...j.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb",...A||{}};const O=await F().wrap(W,X,j,{engine:t.sandboxEngine||"custom",cwd:y});nt(s,O.record);const[Q,Y,tt]=[O.bin,O.argv,O.opts];await new Promise((a,l)=>{let p;try{p=R(L(Q,Y,tt),O,{kind:"agent"})}catch($){return P(),l(new Error(`Failed to start ${m}: ${$.message}`))}const c=lt(p,f);let C="";const M=dt(b,s);let k;const U=()=>{clearTimeout(k),k=setTimeout(()=>{p.kill("SIGKILL"),P(),l(new Error(`${m} timed out — no output for ${Math.round(G/1e3)}s.`))},G)};U(),p.stdout.on("data",$=>{U(),M.push($.toString())}),p.stderr.on("data",$=>{U(),C+=$.toString()}),p.on("error",$=>{clearTimeout(k),c(),P(),l(new Error(`Failed to start ${m}: ${$.message}`))}),p.on("close",$=>{if(clearTimeout(k),c(),P(),f?.aborted){a();return}$===0?(s({type:"done",text:M.streamed?"":M.finish()}),a()):l(ht(m,$,C,"",{reported:M.error||""}))}),d==="stdin"&&p.stdin.write(w),p.stdin.end()})}export{D as CHATPANEL_STABLE_MCP_URL,ee as available,Tt as buildPiExtensionSource,ne as chat,q as commandOutput,Ft as ensureStableMcpConfig,re as listModels,Ct as listSpecModels,Nt as mcpSetupHint,vt as mcpTrustArgs,At as piToolArgs,$t as runForStdout,Rt as runSpec,Et as stableMcpSetupCommand,Mt as stableMcpSetupPlan,xt as trustToolArgs};
68
+ `}async function It(t,n){const e=A.join(O.tmpdir(),`chatpanel-pi-tools-${n}.ts`);return await N(e,_t(t)),e}async function Nt(){const t=process.env.XDG_CONFIG_HOME||A.join(O.homedir(),".config"),n=[A.join(t,"opencode","opencode.jsonc"),A.join(O.homedir(),"Library","Application Support","opencode","opencode.jsonc")];for(const e of n)try{if((await it(e,"utf8")).includes(At))return!0}catch{}return!1}async function Y(t,n,e){const r=F(t);if(!r)return"";const[o,a,f]=R(r,n,e||null),g=await B().wrap(o,a,f,{engine:"custom",cwd:e||null}),{bin:w,argv:S,opts:m}=g;return new Promise(v=>{const d=j(I(w,S,m),g,{kind:"probe"});let i="",y="";const h=setTimeout(()=>{d.kill("SIGKILL"),v(i+y)},4e3);d.stdout.on("data",u=>i+=u.toString()),d.stderr.on("data",u=>y+=u.toString()),d.on("error",()=>{clearTimeout(h),v(i+y)}),d.on("close",()=>{clearTimeout(h),v(i+y)});try{d.stdin.end()}catch{}})}async function Ft(t,n){for(const e of["workspace","global","default"]){const r=await Y(t,["mcp","list",e],n);if(r.includes(H)||/chatpanel_browser/i.test(r))return!0}return!1}async function Rt(t,n){const e=await Y(t,["mcp","list"],n);return e.includes(H)||/chatpanel_browser/i.test(e)}async function Bt(t,n){return t.stableMcpConfigCheck==="kiro"?Ft(t.command||"kiro-cli",n):t.stableMcpConfigCheck==="opencode"?Nt():t.stableMcpConfigCheck==="hermes"?Rt(t.command||"hermes",n):!1}async function jt(t,n){const e=F(t.command);if(!e)throw new Error(`Couldn't find "${t.command}" to set up browser tools.`);const[r,o,a]=R(e,t.args,n||null);a.env={...a.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"};const f=await B().wrap(r,o,a,{engine:"custom",cwd:n||null}),{bin:g,argv:w,opts:S}=f;await new Promise((m,v)=>{let d;try{d=j(I(g,w,S),f,{kind:"probe"})}catch(u){return v(new Error(`Failed to start ${t.command}: ${u.message}`))}let i="",y="";const h=setTimeout(()=>{d.kill("SIGKILL"),v(new Error(`${t.command} MCP setup timed out.`))},2e4);d.stderr.on("data",u=>i+=u.toString()),d.stdout?.on("data",u=>y+=u.toString()),d.on("error",u=>{clearTimeout(h),v(new Error(`Failed to start ${t.command}: ${u.message}`))}),d.on("close",u=>{if(clearTimeout(h),u===0)return m(`${y}
69
+ ${i}`.trim());v(new Error(`${t.command} MCP setup exited ${u}: ${i.trim().split(`
70
+ `).pop()||"failed"}`))});try{d.stdin.end()}catch{}})}function Ut(t,n){const e=String(n?.message||n||"");return/mcp['" ]* Python SDK|No module named ['"]?mcp|MCP support/i.test(e)?`${t} has no MCP support installed. Run \`hermes setup\` (or install the \`mcp\` package in its environment), then retry.`:/streamable_http|HTTP transport/i.test(e)?`${t}'s MCP client has no HTTP transport; ChatPanel registers a stdio server instead. Upgrade its \`mcp\` package if this persists.`:e.slice(0,200)||"the CLI could not register the tools"}async function Dt(t,n,e,r,o={}){if(!t.requiresStableMcp)return!0;const a=o.hasConfig||Bt,f=o.runSetup||jt;if(await a(t,n))return!0;const g=kt(t);if(!t.autoSetupStableMcp){const m=`${e} needs one-time browser-tool setup: ${g}`;throw r({type:"status",text:m}),new Error(m)}const w=Lt(t);if(!w?.command){const m=`${e} needs one-time browser-tool setup: ${g}`;throw r({type:"status",text:m}),new Error(m)}r({type:"status",text:`${e} is setting up one-time browser tools...`});const S=String(await f(w,n)||"").trim();if(await a(t,n))return!0;throw new Error(`${e} browser-tool setup did not register the server.`+(S?` ${S.split(`
71
+ `).filter(Boolean).slice(-3).join(" ")}`:"")+` Run: ${g}`)}async function ce({messages:t,system:n,options:e,images:r},o,{signal:a}={}){if(!await K(e.entitlement))throw new Error("Custom agents require ChatPanel Pro. Upgrade in Settings to bring your own CLI agent.");return Ht(e.custom||{},{messages:t,system:n,options:e,images:r},o,{signal:a})}async function Ht(t,{messages:n,system:e,options:r={},images:o},a,{signal:f}={}){if(!t.command)throw new Error("This agent has no command configured.");const g=F(t.command);if(!g)throw new Error(G(t.command,{platform:process.platform}));let w=dt(n,e),S=yt(r.workingDir);const m=t.label||t.command,v=Object.hasOwn(St,t.format)?t.format:"text",d=t.promptVia==="arg"?"arg":"stdin";let i=Array.isArray(t.args)?t.args.slice():t.args?String(t.args).split(/\s+/).filter(Boolean):[];ht(i,r.extraArgs,Z[t.forbidden]||Z.custom,a);const y=r.model||(t.modelArg?mt({harness:t.dirsHarness||t.command,env:process.env,home:O.homedir(),readFile:s=>{try{return ut(s,"utf8")}catch{return null}}}):"");if(y&&t.modelArg){const s=String(t.modelArg),l=s.includes("{model}")?s.replaceAll("{model}",y).split(/\s+/).filter(Boolean):[...s.split(/\s+/).filter(Boolean),y];i=[...i,...l]}if(t.permissionArgs){const s=String(r.permissionMode||"default"),l=t.permissionArgs[s]||t.permissionArgs.default||[];i=[...i,...l.map(String)]}i=[...i,...ct({harness:t.dirsHarness||t.command,roots:lt(S),dirs:t.dirs!==void 0?t.dirs:r.dirs})];const h=`${Date.now()}-${Math.random().toString(36).slice(2)}`,u=t.imageArg?await Ct(o,h):[],x=[];let $=null,J=null,E=null;const P=()=>{E?.stop(),[...u,...x].forEach(s=>st(s).catch(()=>{}))};if(r.mcp?.url&&t.toolAdapter==="pi-extension"){const s=await It(r.mcp,h);x.push(s),i=[...Tt(s,r.mcp),...i]}else if(r.mcp?.url&&t.mcpArg){const s=r.mcp.serverName||"chatpanel_browser",{command:l,args:p}=V(r.mcp.url),c=A.join(O.tmpdir(),`chatpanel-mcp-${h}.json`);await N(c,JSON.stringify({mcpServers:{[s]:{command:l,args:p}}})),x.push(c);const b=String(t.mcpArg);i=[...b.includes("{file}")?b.replaceAll("{file}",c).split(/\s+/).filter(Boolean):[...b.split(/\s+/).filter(Boolean),c],...i]}else if(r.mcp?.url&&t.mcpViaEnv?.env){const s=r.mcp.serverName||"chatpanel_browser",{command:l,args:p}=V(r.mcp.url);let c={};try{c=JSON.parse(process.env[t.mcpViaEnv.env]||"{}")||{}}catch{c={}}const b={...c.mcp?.servers||{},[s]:{type:"local",command:[l,...p]}};$={[t.mcpViaEnv.env]:JSON.stringify({...c,mcp:{...c.mcp||{},servers:b}})},J=t.mcpViaEnv.args||null}t.live&&(E=await bt({live:t.live,resolved:g,cwd:S,runEnv:r.runEnv||null,engine:t.sandboxEngine||"custom",env:{...W,...$||{}}}));const z=E?E.attach:J;if(z?.length&&(i=[i[0],...z,...i.slice(1)].filter(s=>s!==void 0)),r.mcp?.url&&!t.mcpViaEnv?.env)try{await Dt(t,S,m,a)}catch(s){a({type:"status",text:`${m}: continuing without ChatPanel's browser tools — ${Ut(m,s)}`}),r={...r,mcp:null}}if(r.mcp?.url&&i.push(...Pt(t,r.mcp)),r.model&&typeof t.modelPatch?.build=="function"){const s=/^[A-Za-z0-9][\w.:-]{0,79}$/.test(String(r.model))?String(r.model):"";if(s){const l=A.join(O.tmpdir(),`chatpanel-modelpatch-${h}.yml`);await N(l,t.modelPatch.build(s)),x.push(l);const p=String(t.modelPatch.arg||"--patch {file}");i=[...p.includes("{file}")?p.replaceAll("{file}",l).split(/\s+/).filter(Boolean):[...p.split(/\s+/).filter(Boolean),l],...i]}}const M=$t(t.imageArg,u);let U=!1;if(M.length&&(i=i.flatMap(s=>s==="{images}"?(U=!0,M):[s])),d==="arg"){const s=i.reduce((c,b)=>c+String(b).length+3,0)+M.reduce((c,b)=>c+String(b).length+3,0),l=ft(n,e,gt({viaCmdExe:g.kind==="cmd",otherArgsChars:s}));(l.dropped||l.prompt!==w)&&(w=l.prompt,a({type:"status",text:`${m} takes the prompt as a command-line argument, which this system caps — the oldest ${l.dropped||"part of the"} turn${l.dropped===1?"":"s"} of this conversation ${l.dropped?"were":"was"} left out to fit.`}));let p=!1;i=i.map(c=>c.includes("{prompt}")?(p=!0,c.replaceAll("{prompt}",w)):c),p||(M.length&&!U&&i.push(...M),i.push(w))}else M.length&&!U&&i.push(...M);const[tt,et,D]=R(g,i,S,r.runEnv||null);D.env={...D.env||process.env,...W,...$||{},...E?.env||{}};const k=await B().wrap(tt,et,D,{engine:t.sandboxEngine||"custom",cwd:S}).catch(s=>{throw P(),s});at(a,k.record);const[rt,nt,ot]=[k.bin,k.argv,k.opts];await new Promise((s,l)=>{let p;try{p=j(I(rt,nt,ot),k,{kind:"agent"})}catch(C){return P(),l(new Error(`Failed to start ${m}: ${C.message}`))}const c=pt(p,f);let b="";const T=wt(v,a);let L;const _=()=>{clearTimeout(L),L=setTimeout(()=>{p.kill("SIGKILL"),P(),l(new Error(`${m} timed out — no output for ${Math.round(q/1e3)}s.`))},q)};_(),E&&T.live&&E.follow({live:T.live,emit:a,onActivity:_}),p.stdout.on("data",C=>{_(),T.push(C.toString())}),p.stderr.on("data",C=>{_(),b+=C.toString()}),p.on("error",C=>{clearTimeout(L),c(),P(),l(new Error(`Failed to start ${m}: ${C.message}`))}),p.on("close",C=>{if(clearTimeout(L),c(),P(),f?.aborted){s();return}C===0?(a({type:"done",text:T.streamed?"":T.finish()}),s()):l(vt(m,C,b,"",{reported:T.error||""}))}),d==="stdin"&&p.stdin.write(w),p.stdin.end()})}export{H as CHATPANEL_STABLE_MCP_URL,ae as available,_t as buildPiExtensionSource,ce as chat,Y as commandOutput,Dt as ensureStableMcpConfig,le as listModels,Et as listSpecModels,Ut as mcpSetupHint,Pt as mcpTrustArgs,Tt as piToolArgs,Mt as runForStdout,Ht as runSpec,kt as stableMcpSetupCommand,Lt as stableMcpSetupPlan,Ot as trustToolArgs};
@@ -0,0 +1,2 @@
1
+ import{spawn as B}from"node:child_process";import{randomBytes as I}from"node:crypto";import{buildSpawnSpec as M}from"../env.js";import{sandbox as $,track as L}from"../sandbox.js";import{terminateTree as O}from"../proc.js";function W(r){const i=new Map,l=new Map,d=new Map;let u=!1;const a=(n,t)=>{const e=i.get(n)||0;t.length<=e||(i.set(n,t.length),u=!0,r({type:"delta",text:t.slice(e)}))},o=(n,t,e)=>{const c=String(t||""),s=(n.get(c)||"")+String(e||"");n.set(c,s),a(c,s)};return{delta:(n,t)=>o(l,n,t),part:(n,t)=>o(d,n,t),get streamed(){return u}}}async function P(r,{live:i,emit:l,onActivity:d=()=>{}}){const u=new TextDecoder;let a="",o="";const n=t=>{const e=t?.data||{};if(t?.type==="session.created"){o=o||String(e.sessionID||"");return}!o||e.sessionID!==o||!e.delta||(t.type==="session.text.delta"?(d(),i.delta(e.assistantMessageID,e.delta)):t.type==="session.reasoning.delta"&&(d(),l({type:"reasoning",text:String(e.delta)})))};for await(const t of r){a+=u.decode(t,{stream:!0});let e;for(;(e=a.indexOf(`
2
+ `))>=0;){const c=a.slice(0,e).trim();if(a=a.slice(e+1),!!c.startsWith("data:"))try{n(JSON.parse(c.slice(5)))}catch{}}}}const R=/https?:\/\/127\.0\.0\.1:\d+/;async function _({live:r,resolved:i,cwd:l,runEnv:d=null,env:u={},engine:a="custom",timeoutMs:o=4e3,spawnImpl:n=B,fetchImpl:t=fetch}){if(!Array.isArray(r?.serve)||!Array.isArray(r?.attach)||!r.passwordEnv)return null;const e=I(24).toString("base64url"),c={[r.passwordEnv]:e};let s=null;const h=new AbortController;let v=!1;const f=()=>{v||(v=!0,h.abort(),s&&O(s))};try{const[k,A,y]=M(i,r.serve,l,d);y.env={...y.env||process.env,...u,...c};const m=await $().wrap(k,A,y,{engine:a,cwd:l});s=L(n(m.bin,m.argv,m.opts),m,{kind:"agent",label:"live events"}),s.stdin?.end();const g=await new Promise(p=>{let b="";const E=setTimeout(()=>p(""),o),S=x=>{clearTimeout(E),p(x)};s.stdout.on("data",x=>{b=(b+x).slice(-2e3);const T=R.exec(b);T&&S(T[0])}),s.stderr?.on("data",()=>{}),s.once("error",()=>S("")),s.once("exit",()=>S(""))});if(!g)return f(),null;const D=setTimeout(()=>h.abort(),o),w=await t(g+(r.events||"/api/event"),{headers:{authorization:`Basic ${Buffer.from(`${r.user||"opencode"}:${e}`).toString("base64")}`,accept:"text/event-stream"},signal:h.signal});return clearTimeout(D),!w.ok||!w.body||!/event-stream/.test(w.headers.get("content-type")||"")?(f(),null):{url:g,env:c,attach:r.attach.map(p=>String(p).replaceAll("{url}",g)),follow:p=>{P(w.body,p).catch(()=>{})},stop:f}}catch{return f(),null}}export{P as followEvents,W as liveText,_ as startLiveServer};
@@ -1,2 +1,2 @@
1
- import{handleMessage as d}from"./claude.js";const m=/\u001b\[[0-9;?]*[ -/]*[@-~]/g,f=t=>String(t).replace(m,"");function c(t){let r="";return n=>{r+=n;let i;for(;(i=r.indexOf(`
2
- `))>=0;){const o=r.slice(0,i).trim();if(r=r.slice(i+1),!o.startsWith("{"))continue;let s;try{s=JSON.parse(o)}catch{continue}t(s)}}}function g(t){let r=!1;return{push(n){r=!0,t({type:"delta",text:f(n)})},finish:()=>"",get streamed(){return r}}}function y(t){let r=!1,n="";return{push:c(o=>{const s=d(o,t,r);s.streamed&&(r=!0),s.result!=null&&(n=s.result)}),finish:()=>n,get streamed(){return r}}}function x(t){let r=!1,n="";return{push:c(o=>{if(o.type==="text"&&o.part?.text)r=!0,t({type:"delta",text:o.part.text});else if(o.type==="tool"||o.type==="tool_use"){const s=o.part||{},a=s.tool||s.name||s.type||"tool",u=s.callID||s.callId||s.id||void 0,e=s.state||{},l=String(e.status||"").toLowerCase();t(l==="completed"||l==="error"?{type:"tool",name:a,phase:"done",callId:u,status:l==="error"?"error":"ok",result:String(e.output||e.error||"").slice(0,4e3)}:{type:"tool",name:a,phase:"start",callId:u,input:e.input||s.input,summary:""})}else if(o.type==="error"){const s=String(o.error?.data?.message||o.error?.message||o.error?.name||"error");n=o.error?.type==="provider.quota"||o.error?.status===402||/insufficient balance|quota/i.test(s)?`${s} — or pick a model your plan or keys cover for OpenCode (the model menu in Chap; \`opencode models\` lists them).`:s,t({type:"status",text:s.slice(0,300)})}}),finish:()=>"",get streamed(){return r},get error(){return n}}}const h=/permission denied|could not request permission|not allowed|denied by|requires approval/i;function S(t){let r=!1,n="",i=!1;const o=a=>{i||!h.test(String(a||""))||(i=!0,t({type:"status",text:"Copilot was denied a tool/URL — raise this agent’s Permission mode in Settings."}))};return{push:c(a=>{const u=a?.type||"",e=a?.data||{};switch(u){case"assistant.message_delta":e.deltaContent&&(r=!0,t({type:"delta",text:e.deltaContent}));break;case"assistant.message":typeof e.content=="string"&&e.content&&(n=e.content);break;case"assistant.reasoning":e.content&&t({type:"reasoning",text:String(e.content)});break;case"tool.execution_start":t({type:"tool",name:e.toolName||"tool",summary:""});break;case"tool.execution_complete":if(e.success===!1){const l=typeof e.result=="string"?e.result:e.result?.error||e.result?.message||"";l&&t({type:"status",text:String(l).slice(0,300)}),o(l)}else o(typeof e.result=="string"?e.result:"");break;case"session.auto_mode_resolved":e.chosenModel&&t({type:"status",text:`model: ${e.chosenModel}`});break;case"session.mcp_server_status_changed":e.status==="failed"&&e.error&&t({type:"status",text:`MCP ${e.serverName}: ${String(e.error).slice(0,160)}`});break;case"result":a.exitCode&&t({type:"status",text:`copilot exited ${a.exitCode}`});break;default:break}}),finish:()=>n,get streamed(){return r}}}const p={text:g,"claude-stream-json":y,"opencode-json":x,"copilot-json":S};function b(t,r){return(p[t]||p.text)(r)}export{p as STREAM_FORMATS,b as createStreamParser,f as stripAnsi};
1
+ import{handleMessage as m}from"./claude.js";import{liveText as f}from"./opencode-live.js";const g=/\u001b\[[0-9;?]*[ -/]*[@-~]/g,y=t=>String(t).replace(g,"");function p(t){let o="";return n=>{o+=n;let a;for(;(a=o.indexOf(`
2
+ `))>=0;){const i=o.slice(0,a).trim();if(o=o.slice(a+1),!i.startsWith("{"))continue;let s;try{s=JSON.parse(i)}catch{continue}t(s)}}}function x(t){let o=!1;return{push(n){o=!0,t({type:"delta",text:y(n)})},finish:()=>"",get streamed(){return o}}}function h(t){let o=!1,n="";return{push:p(i=>{const s=m(i,t,o);s.streamed&&(o=!0),s.result!=null&&(n=s.result)}),finish:()=>n,get streamed(){return o}}}function S(t){let o=!1;const n=f(t);let a="";return{push:p(s=>{if(s.type==="text"&&s.part?.text)n.part(s.part.messageID,s.part.text);else if(s.type==="tool"||s.type==="tool_use"){const r=s.part||{},u=r.tool||r.name||r.type||"tool",e=r.callID||r.callId||r.id||void 0,l=r.state||{},c=String(l.status||"").toLowerCase();t(c==="completed"||c==="error"?{type:"tool",name:u,phase:"done",callId:e,status:c==="error"?"error":"ok",result:String(l.output||l.error||"").slice(0,4e3)}:{type:"tool",name:u,phase:"start",callId:e,input:l.input||r.input,summary:""})}else if(s.type==="error"){const r=String(s.error?.data?.message||s.error?.message||s.error?.name||"error");a=s.error?.type==="provider.quota"||s.error?.status===402||/insufficient balance|quota/i.test(r)?`${r} — or pick a model your plan or keys cover for OpenCode (the model menu in Chap; \`opencode models\` lists them).`:r,t({type:"status",text:r.slice(0,300)})}}),finish:()=>"",live:n,get streamed(){return o||n.streamed},get error(){return a}}}const k=/permission denied|could not request permission|not allowed|denied by|requires approval/i;function b(t){let o=!1,n="",a=!1;const i=r=>{a||!k.test(String(r||""))||(a=!0,t({type:"status",text:"Copilot was denied a tool/URL — raise this agent’s Permission mode in Settings."}))};return{push:p(r=>{const u=r?.type||"",e=r?.data||{};switch(u){case"assistant.message_delta":e.deltaContent&&(o=!0,t({type:"delta",text:e.deltaContent}));break;case"assistant.message":typeof e.content=="string"&&e.content&&(n=e.content);break;case"assistant.reasoning":e.content&&t({type:"reasoning",text:String(e.content)});break;case"tool.execution_start":t({type:"tool",name:e.toolName||"tool",summary:""});break;case"tool.execution_complete":if(e.success===!1){const l=typeof e.result=="string"?e.result:e.result?.error||e.result?.message||"";l&&t({type:"status",text:String(l).slice(0,300)}),i(l)}else i(typeof e.result=="string"?e.result:"");break;case"session.auto_mode_resolved":e.chosenModel&&t({type:"status",text:`model: ${e.chosenModel}`});break;case"session.mcp_server_status_changed":e.status==="failed"&&e.error&&t({type:"status",text:`MCP ${e.serverName}: ${String(e.error).slice(0,160)}`});break;case"result":r.exitCode&&t({type:"status",text:`copilot exited ${r.exitCode}`});break;default:break}}),finish:()=>n,get streamed(){return o}}}const d={text:x,"claude-stream-json":h,"opencode-json":S,"copilot-json":b};function I(t,o){return(d[t]||d.text)(o)}export{d as STREAM_FORMATS,I as createStreamParser,y as stripAnsi};
@@ -0,0 +1,6 @@
1
+ import{fuseRRF as ee}from"./rrf.js";import{approxTokens as te}from"./sources-retrieval.js";const le="/v1/context",ue=Object.freeze(["kb","web","bedrock","gw","mcp"]),g=Object.freeze({maxTokens:4e3,limit:8,deadlineMs:4e3,maxDeadlineMs:2e4,k:60,sources:["kb:*"]}),ce="x-chatpanel-federated",x=e=>!!e&&typeof e=="object"&&!Array.isArray(e),C=e=>typeof e=="string"&&e.length>0,p=(e,t)=>{if(!e)throw Object.assign(new Error(t),{code:"SHAPE"})},re=/^(kb|web|bedrock|gw|mcp)(?::([A-Za-z0-9*][\w.*-]{0,63}))?(?::(kb|web|bedrock)(?::([A-Za-z0-9*][\w.*-]{0,63}))?)?$/;function z(e){const t=re.exec(String(e||"").trim());if(!t)return null;const[,n,i="*",u="",l=""]=t;return u&&n!=="gw"?null:{type:n,id:i,...u?{inner:`${u}:${l||"*"}`}:{}}}const U=(e,t)=>!!e&&e.type===t.type&&(e.id==="*"||t.id==="*"||e.id===t.id),X=e=>{if(e==null)return null;p(x(e),"context: filters must be an object");const t={};if(e.pages!=null&&(p(Array.isArray(e.pages)&&e.pages.length>=1&&e.pages.length<=2&&e.pages.every(n=>Number.isInteger(Number(n))&&Number(n)>=1),"context: filters.pages must be [from, to] page numbers"),t.pages=[Number(e.pages[0]),Number(e.pages[1]??e.pages[0])]),e.label!=null&&(p(typeof e.label=="string"&&e.label.trim().length<=40,"context: filters.label must be a printed page label"),e.label.trim()&&(t.label=e.label.trim())),e.section!=null&&(p(typeof e.section=="string","context: filters.section must be a string"),e.section.trim()&&(t.section=e.section.trim().slice(0,200))),e.form!=null&&(p(["prose","list","table"].includes(e.form),"context: filters.form must be prose, list or table"),t.form=e.form),e.types!=null){p(Array.isArray(e.types)&&e.types.every(i=>typeof i=="string"),"context: filters.types must be strings");const n=e.types.map(i=>i.trim().toLowerCase()).filter(Boolean).slice(0,20);n.length&&(t.types=n)}return e.docs!=null&&(p(Array.isArray(e.docs)&&e.docs.every(C),"context: filters.docs must be document ids"),t.docs=e.docs.slice(0,100)),Object.keys(t).length?t:null},me=X;function pe(e={}){p(x(e),"context: body must be an object"),p(C(e.query)&&e.query.trim().length>0,"context: query required");const t={query:e.query.trim().slice(0,2e3)},n=e.sources==null?g.sources:e.sources;p(Array.isArray(n)&&n.length>0&&n.length<=32,"context: sources must be a list of 1–32 source names"),t.sources=[...new Set(n.map(l=>String(l).trim()))];for(const l of t.sources)p(z(l),`context: "${l}" is not a source (kb:*, kb:<id>, web, web:<api>, bedrock:<id>, gw:<id>, gw:<id>:kb:<id>)`);t.filters=X(e.filters);const i=e.max_tokens??e.maxTokens;i!=null?(p(Number.isInteger(Number(i))&&Number(i)>=50&&Number(i)<=2e5,"context: max_tokens must be 50–200000"),t.maxTokens=Number(i)):t.maxTokens=g.maxTokens,e.limit!=null?(p(Number.isInteger(Number(e.limit))&&Number(e.limit)>=1&&Number(e.limit)<=50,"context: limit must be 1–50"),t.limit=Number(e.limit)):t.limit=g.limit;const u=e.deadline_ms??e.deadlineMs;return u!=null?(p(Number.isFinite(Number(u))&&Number(u)>=100,"context: deadline_ms must be ≥ 100"),t.deadlineMs=Math.min(g.maxDeadlineMs,Number(u))):t.deadlineMs=g.deadlineMs,e.rerank!=null?(p(typeof e.rerank=="boolean","context: rerank must be a boolean"),t.rerank=e.rerank):t.rerank=!0,t}const K=e=>String(e??"").replace(/\r\n?/g,`
2
+ `).trim();function ne(e,t){const n=(Array.isArray(e)?e:[]).filter(s=>x(s)&&K(s.content??s.text)),i=n.map(s=>Number(s.rawScore??s.score)).filter(Number.isFinite),u=i.length?Math.min(...i):0,l=i.length?Math.max(...i):0;return n.map((s,f)=>{const w=K(s.content??s.text),h=Number.isFinite(Number(s.rawScore??s.score))?Number(s.rawScore??s.score):null,d=x(s.source)?s.source:{};return{id:`${t.key}|${C(s.id)?s.id:f}`,source:{type:d.type||t.type,provider:d.provider||t.key,uri:String(d.uri||s.uri||s.url||""),...d.gateway?{gateway:d.gateway}:{},...d.name?{name:String(d.name)}:{}},title:String(s.title||d.name||"").slice(0,300),content:w,rawScore:h,score:h==null?1-f/Math.max(1,n.length):l>u?(h-u)/(l-u):1,tokens:Number.isFinite(Number(s.tokens))&&Number(s.tokens)>0?Number(s.tokens):te(w),at:Number(s.at)||null,meta:x(s.meta)?s.meta:{}}})}function B(e){return String(e.content||"").toLowerCase().replace(/<[^>]+>/g," ").replace(/[^\p{L}\p{N}]+/gu," ").trim().slice(0,600)}function se(e,t){const n=[];let i=0;const u=[];for(const l of e)i+l.tokens<=t?(n.push(l),i+=l.tokens):u.push(l.id);return{chunks:n,tokens:i,dropped:u}}const oe=e=>e.id&&e.id!=="*"?`${e.type}:${e.id}`:e.type;async function de({query:e,providers:t=[],sources:n=g.sources,filters:i=null,maxTokens:u=g.maxTokens,limit:l=g.limit,deadlineMs:s=g.deadlineMs,signal:f=null,deadlines:w={},redact:h=null,rerank:d=null,now:N=()=>Date.now(),timers:v=null,k:O=g.k}={}){const H=N(),y=String(e||"").trim(),Z=v?.set||((r,a)=>setTimeout(r,a)),Y=v?.clear||(r=>clearTimeout(r)),_=(n||[]).map(r=>typeof r=="string"?z(r):r).filter(Boolean),S={},j=[];for(const r of t||[]){if(!r||typeof r.retrieve!="function")continue;const a=_.filter(b=>U(b,r));if(!a.length)continue;const c=oe(r),o=r.type==="gw"?[...new Set(a.map(b=>b.inner||"*"))]:[...new Set(a.map(b=>b.id))];j.push({p:{...r,key:c},scope:o.includes("*")?["*"]:o})}for(const r of _)(t||[]).some(a=>a&&U(r,a))||(S[`${r.type}:${r.id}`]={ms:0,count:0,error:"not configured"});const G=async({p:r,scope:a})=>{const c=N(),o={ms:0,count:0};S[r.key]=o;let b=y;if(r.remote&&!r.trusted){if(typeof h!="function")return o.error="refused: a remote provider is asked only through redaction, and none is available here",[];try{b=String(await h(y)||"").trim()}catch(m){return o.error=`refused: redaction failed (${m?.message||m})`,[]}if(!b)return o.error="refused: nothing searchable remains once private values are taken out",[];b!==y&&(o.redacted=!0)}const D=Math.max(50,Number(w?.[r.key]??r.deadlineMs??s)||s),E=typeof AbortController=="function"?new AbortController:null,I=()=>E?.abort();f?.addEventListener?.("abort",I);let L=null;const W=new Promise(m=>{L=Z(()=>{o.timedOut=!0,E?.abort(),m(null)},D)});try{const m=await Promise.race([Promise.resolve().then(()=>r.retrieve(b,{filters:i,maxTokens:u,limit:l,scope:a,signal:E?.signal||f})),W]);if(o.timedOut)return o.error=`no answer within ${D} ms`,[];const P=ne(Array.isArray(m)?m:m?.chunks,r).slice(0,Math.max(l,1)*4);return o.count=P.length,m&&!Array.isArray(m)&&m.error&&(o.error=String(m.error)),P}catch(m){return o.error=f?.aborted?"cancelled":String(m?.message||m).slice(0,300),[]}finally{Y(L),f?.removeEventListener?.("abort",I),o.ms=Math.round(N()-c)}},J=await Promise.all(j.map(G)),q=new Map,$=new Map,Q=J.map(r=>r.map(a=>{const c=a.source.uri&&!/^kb:\/\//.test(a.source.uri)?`u:${a.source.uri}|${B(a).slice(0,80)}`:`t:${B(a)}`,o=q.get(c);return o?(o.meta.alsoIn=[...new Set([...o.meta.alsoIn||[],a.source.provider])],o.id):(q.set(c,a),$.set(a.id,a),a.id)}));let A=ee(Q,{k:O,limit:0}),F=!1;const k=A.slice(0,Math.max(l*3,l));if(typeof d=="function"&&k.length>1&&y)try{const r=await d(y,k.map(a=>{const c=$.get(a.id);return`${c.title?`${c.title}
3
+ `:""}${c.content}`.slice(0,2e3)}));Array.isArray(r)&&r.length===k.length&&(A=k.map((c,o)=>({id:c.id,s:Number(r[o])||0,i:o})).sort((c,o)=>o.s-c.s||c.i-o.i).map((c,o)=>({id:c.id,score:1/(O+o)})),F=!0)}catch{}else A=k;const M=A.slice(0,l),R=M.length?M[0].score:1,V=M.map(r=>({...$.get(r.id),score:R>0?Math.round(r.score/R*1e3)/1e3:0})),T=se(V,u);return{chunks:T.chunks,tokens:T.tokens,dropped:T.dropped,providers:S,reranked:F,ms:Math.round(N()-H)}}function be(e){const t=e?.chunks||[];return t.length?t.map((n,i)=>`[${i+1}] ${n.meta?.cite||n.title||n.source.uri}${n.source.gateway?` (on ${n.source.gateway})`:""} — ${n.source.type}:${n.source.provider}
4
+ ${n.content}`).join(`
5
+
6
+ `):"Nothing in the sources asked matched."}export{g as CONTEXT_DEFAULTS,ce as CONTEXT_FEDERATED_HEADER,le as CONTEXT_ROUTE,ue as CONTEXT_SOURCE_TYPES,B as dedupeKey,ne as normalizeChunks,se as packChunks,z as parseSource,be as renderContext,de as searchContext,U as sourceMatches,me as validateContextFilters,pe as validateContextRequest};
@@ -1,5 +1,5 @@
1
- const u=t=>t==null?0:Math.round((typeof t=="string"?t:JSON.stringify(t)).length/4),k=t=>typeof t=="string"?t:Array.isArray(t)?t.map(o=>o?.type==="text"&&o.text||"").join(`
2
- `):"",L=t=>Array.isArray(t)?t.filter(o=>o&&o.type!=="text").length:0,K=/<context source="[^"]*">\n# \[([\w-]+)\][^\n]*\n[\s\S]*?\n<\/context>/g,W=/<presence>\n[\s\S]*?\n<\/presence>/g,j=/\n*\[Chap\] Likely useful for this message[^\n]*/g;function M(t){const o=String(t||""),c=[];let r=o.replace(K,(l,a)=>(c.push({kind:a==="prefetch"?"fetched":"attached",of:a,tokens:u(l)}),""));r=r.replace(W,l=>(c.push({kind:"presence",tokens:u(l)}),""));let d=0;return r=r.replace(j,l=>(d+=u(l),"")),{words:u(r.trim()),blocks:c,hint:d}}function B(t){const o=String(t||"");return o.trim()?o.split(/\n(?=## )/).map(r=>{const d=(r.match(/^## ([^\n]+)/)||[])[1];return{label:d?d.trim().slice(0,60):"Instructions",tokens:u(r)}}).filter(r=>r.tokens>0):[]}const v=Object.freeze({instructions:"The system prompt: who the assistant is, how to answer, what it may use. Sent on every turn so the model behaves the same way each time.",toolText:"The tools' rules and catalog: which actions exist and when to use them. Sent every turn; the provider caches it.",toolSchemas:"The tool definitions the model can call — kept to one tool (`tools`) so a turn carries one schema, not one per action.",history:'The earlier messages of this conversation, so a follow-up ("how many in south?") is read against what came before.',historyCarried:"Context that rode on earlier messages — fetched results, attachments, presence — kept with them so the model can refer back.",toolExchange:"Tool calls and their results from earlier rounds.",fetched:"Looked up before the model ran (the weather, a search, the page), so it answers instead of calling a tool.",attached:"What the person attached to this message, or the client added as context.",presence:"What exists around the turn (the open page, notes, what was fetched before) — names, not contents.",hint:"The actions likely useful for this message — appended to the message, not the system prompt, so the prompt cache holds.",words:"The person's own words.",agentOwn:"The agent's own context: its system prompt, its built-in tools, its skills and MCP servers, its session. Not sent by us; it reads it every turn.",cached:"Read from the provider's prompt cache — already there, billed at a fraction, and fast."});function H({messages:t=[],tools:o=null,usage:c=null,agent:r=!1,agentContext:d=null}={}){const l=Array.isArray(t)?t:[],a=[],i=(e,n,s,h={})=>{(s>0||h.always)&&a.push({id:e,label:n,tokens:s,why:v[e]||"",...h})},y=l.filter(e=>e?.role==="system").map(e=>k(e.content)).join(`
1
+ const u=t=>t==null?0:Math.round((typeof t=="string"?t:JSON.stringify(t)).length/4),w=t=>typeof t=="string"?t:Array.isArray(t)?t.map(n=>n?.type==="text"&&n.text||"").join(`
2
+ `):"",_=t=>Array.isArray(t)?t.filter(n=>n&&n.type!=="text").length:0,K=/<context source="[^"]*">\n# \[([\w-]+)\][^\n]*\n[\s\S]*?\n<\/context>|(?:^|\n)# \[((?!presence\])[\w-]+)\][^\n]*\n[\s\S]*?(?=\n\n---\n\n|$)/g,R=/<presence>\n[\s\S]*?\n<\/presence>|(?:^|\n)# \[presence\][^\n]*\n[\s\S]*?(?=\n\n---\n\n|$)/g,W=/^---$/gm,j=/\n*\[Chap\] Likely useful for this message[^\n]*/g;function M(t){const n=String(t||""),c=[];let i=0,a=n.replace(j,h=>(i+=u(h),""));return a=a.replace(K,(h,l,r)=>{const m=l||r;return c.push({kind:m==="prefetch"?"fetched":"attached",of:m,tokens:u(h)}),""}),a=a.replace(R,h=>(c.push({kind:"presence",tokens:u(h)}),"")),a=a.replace(W,""),{words:u(a.trim()),blocks:c,hint:i}}function B(t){const n=String(t||"");return n.trim()?n.split(/\n(?=## )/).map(i=>{const a=(i.match(/^## ([^\n]+)/)||[])[1];return{label:a?a.trim().slice(0,60):"Instructions",tokens:u(i)}}).filter(i=>i.tokens>0):[]}const E=Object.freeze({instructions:"The system prompt: who the assistant is, how to answer, what it may use. Sent on every turn so the model behaves the same way each time.",toolText:"The tools' rules and catalog: which actions exist and when to use them. Sent every turn; the provider caches it.",toolSchemas:"The tool definitions the model can call — kept to one tool (`tools`) so a turn carries one schema, not one per action.",history:'The earlier messages of this conversation, so a follow-up ("how many in south?") is read against what came before.',historyCarried:"Context that rode on earlier messages — fetched results, attachments, presence — kept with them so the model can refer back.",toolExchange:"Tool calls and their results from earlier rounds.",fetched:"Looked up before the model ran (the weather, a search, the page), so it answers instead of calling a tool.",attached:"What the person attached to this message, or the client added as context.",presence:"What exists around the turn (the open page, notes, what was fetched before) — names, not contents.",hint:"The actions likely useful for this message — appended to the message, not the system prompt, so the prompt cache holds.",words:"The person's own words.",agentOwn:"The agent's own context: its system prompt, its built-in tools, its skills and MCP servers, its session. Not sent by us; it reads it every turn.",cached:"Read from the provider's prompt cache — already there, billed at a fraction, and fast."});function H({messages:t=[],tools:n=null,usage:c=null,agent:i=!1,agentContext:a=null}={}){const h=Array.isArray(t)?t:[],l=[],r=(e,o,s,d={})=>{(s>0||d.always)&&l.push({id:e,label:o,tokens:s,why:E[e]||"",...d})},m=h.filter(e=>e?.role==="system").map(e=>w(e.content)).join(`
3
3
 
4
- `),b=String(o?.system||""),E=b&&y.includes(b)?y.replace(b,""):y,S=B(E);i("instructions","Instructions (system prompt)",S.reduce((e,n)=>e+n.tokens,0),S.length>1?{items:S}:{}),i("toolText","Tool rules & catalog",u(b));const C=Array.isArray(o?.specs)?o.specs:[];i("toolSchemas",`Tool definitions (${C.length})`,u(C),{count:C.length});const g=l.filter(e=>e&&e.role!=="system");let p=-1;for(let e=g.length-1;e>=0;e--)if(g[e].role==="user"){p=e;break}const q=p>=0?g.slice(0,p):g,I=p>=0?g.slice(p+1):[];let N=0,O=0,A=0,x=0;const T=new Map;for(const e of q){if((e.role==="tool"||e.tool_calls)&&(A+=u(k(e.content))+u(e.tool_calls),e.role==="tool")||e.role!=="user"&&e.role!=="assistant")continue;e.role==="user"&&(x+=1);const n=M(k(e.content));N+=n.words+n.hint;for(const s of n.blocks)O+=s.tokens,T.set(s.of||s.kind,(T.get(s.of||s.kind)||0)+s.tokens)}i("history",`Conversation history (${x} earlier ${x===1?"question":"questions"})`,N,{count:x}),i("historyCarried","Context carried in the history",O,T.size?{items:[...T].map(([e,n])=>({label:e,tokens:n}))}:{});for(const e of I)A+=u(k(e.content))+u(e.tool_calls);if(i("toolExchange","Tool calls & results",A),p>=0){const e=g[p],n=M(k(e.content)),s=m=>n.blocks.filter(f=>f.kind===m),h=m=>m.reduce((f,$)=>f+$.tokens,0);i("fetched","Fetched for this message",h(s("fetched")),{count:s("fetched").length}),i("attached","Attached to this message",h(s("attached")),{count:s("attached").length,...s("attached").length?{items:s("attached").map(m=>({label:m.of,tokens:m.tokens}))}:{}}),i("presence","Presence (what is around the turn)",h(s("presence"))),i("hint","Hint (likely actions)",n.hint),i("words","Your message",n.words,{always:!0,...L(e.content)?{images:L(e.content)}:{}})}const _=a.reduce((e,n)=>e+n.tokens,0),w={rows:a,ours:_};if(c){const e=h=>Math.max(0,Number(h)||0),n=e(c.cacheReadTokens),s=e(c.inputTokens)+n+e(c.cacheWriteTokens);if(s>0&&(w.reported=s,w.cached=n,w.requests=e(c.requests)||e(c.calls)||1,r)){const h=Math.max(0,s-_*w.requests),m=Array.isArray(d)?d.filter(f=>f&&Number(f.tokens)>0).map(f=>({label:String(f.label),tokens:Math.round(Number(f.tokens))})):null;w.agentOwn=h,a.push({id:"agentOwn",label:"The agent's own context",tokens:h,why:v.agentOwn,...m?.length?{items:m}:{}})}}return w}function P(t){const o=[],c=String(t||""),r=c.match(/\*\*Tokens:\*\*\s*([\d.]+)(k|m)?\s*\//i)||[];for(const l of c.split(`
5
- `)){const a=l.match(/^\|\s*([^|]+?)\s*\|\s*([\d.,]+)\s*(k|m)?\s*\|\s*[\d.]+%\s*\|$/i);if(!a)continue;const i=a[1].trim();if(/deferred|free space|autocompact|^category$/i.test(i))continue;const y=Number(a[2].replace(/,/g,""))*(a[3]?.toLowerCase()==="k"?1e3:a[3]?.toLowerCase()==="m"?1e6:1);y>0&&o.push({label:i,tokens:Math.round(y)})}if(!o.length)return null;const d=r[1]?Math.round(Number(r[1])*(r[2]?.toLowerCase()==="k"?1e3:r[2]?.toLowerCase()==="m"?1e6:1)):o.reduce((l,a)=>l+a.tokens,0);return{items:o,total:d}}export{H as contextBreakdown,P as parseAgentContext,M as splitMessage,B as systemSections};
4
+ `),b=String(n?.system||""),$=b&&m.includes(b)?m.replace(b,""):m,S=B($);r("instructions","Instructions (system prompt)",S.reduce((e,o)=>e+o.tokens,0),S.length>1?{items:S}:{}),r("toolText","Tool rules & catalog",u(b));const C=Array.isArray(n?.specs)?n.specs:[];r("toolSchemas",`Tool definitions (${C.length})`,u(C),{count:C.length});const g=h.filter(e=>e&&e.role!=="system");let y=-1;for(let e=g.length-1;e>=0;e--)if(g[e].role==="user"){y=e;break}const v=y>=0?g.slice(0,y):g,q=y>=0?g.slice(y+1):[];let N=0,L=0,A=0,x=0;const T=new Map;for(const e of v){if((e.role==="tool"||e.tool_calls)&&(A+=u(w(e.content))+u(e.tool_calls),e.role==="tool")||e.role!=="user"&&e.role!=="assistant")continue;e.role==="user"&&(x+=1);const o=M(w(e.content));N+=o.words+o.hint;for(const s of o.blocks)L+=s.tokens,T.set(s.of||s.kind,(T.get(s.of||s.kind)||0)+s.tokens)}r("history",`Conversation history (${x} earlier ${x===1?"question":"questions"})`,N,{count:x}),r("historyCarried","Context carried in the history",L,T.size?{items:[...T].map(([e,o])=>({label:e,tokens:o}))}:{});for(const e of q)A+=u(w(e.content))+u(e.tool_calls);if(r("toolExchange","Tool calls & results",A),y>=0){const e=g[y],o=M(w(e.content)),s=p=>o.blocks.filter(f=>f.kind===p),d=p=>p.reduce((f,I)=>f+I.tokens,0);r("fetched","Fetched for this message",d(s("fetched")),{count:s("fetched").length}),r("attached","Attached to this message",d(s("attached")),{count:s("attached").length,...s("attached").length?{items:s("attached").map(p=>({label:p.of,tokens:p.tokens}))}:{}}),r("presence","Presence (what is around the turn)",d(s("presence"))),r("hint","Hint (likely actions)",o.hint),r("words","Your message",o.words,{always:!0,..._(e.content)?{images:_(e.content)}:{}})}const O=l.reduce((e,o)=>e+o.tokens,0),k={rows:l,ours:O};if(c){const e=d=>Math.max(0,Number(d)||0),o=e(c.cacheReadTokens),s=e(c.inputTokens)+o+e(c.cacheWriteTokens);if(s>0&&(k.reported=s,k.cached=o,k.requests=e(c.requests)||e(c.calls)||1,i)){const d=Math.max(0,s-O*k.requests),p=Array.isArray(a)?a.filter(f=>f&&Number(f.tokens)>0).map(f=>({label:String(f.label),tokens:Math.round(Number(f.tokens))})):null;k.agentOwn=d,l.push({id:"agentOwn",label:"The agent's own context",tokens:d,why:E.agentOwn,...p?.length?{items:p}:{}})}}return k}function P(t){const n=[],c=String(t||""),i=c.match(/\*\*Tokens:\*\*\s*([\d.]+)(k|m)?\s*\//i)||[];for(const h of c.split(`
5
+ `)){const l=h.match(/^\|\s*([^|]+?)\s*\|\s*([\d.,]+)\s*(k|m)?\s*\|\s*[\d.]+%\s*\|$/i);if(!l)continue;const r=l[1].trim();if(/deferred|free space|autocompact|^category$/i.test(r))continue;const m=Number(l[2].replace(/,/g,""))*(l[3]?.toLowerCase()==="k"?1e3:l[3]?.toLowerCase()==="m"?1e6:1);m>0&&n.push({label:r,tokens:Math.round(m)})}if(!n.length)return null;const a=i[1]?Math.round(Number(i[1])*(i[2]?.toLowerCase()==="k"?1e3:i[2]?.toLowerCase()==="m"?1e6:1)):n.reduce((h,l)=>h+l.tokens,0);return{items:n,total:a}}export{H as contextBreakdown,P as parseAgentContext,M as splitMessage,B as systemSections};
@@ -1 +1 @@
1
- import{isRef as o}from"./ref.js";const c=1,v=Object.freeze({turn:["started","ended"],assistant:["prompted","message","reasoning"],context:["assembled","attached","expanded","retrieved"],capability:["offered","granted","denied","activated","revoked","invoked","resulted"],privacy:["redacted","egress"],policy:["changed","guard_denied"],data:["created","updated","deleted"],automation:["fired","suppressed"],shim:["fired"],judge:["decided"]}),E=Object.freeze(Object.entries(v).flatMap(([e,r])=>r.map(d=>`${e}.${d}`))),w=Object.freeze(["user","rule","schedule","model","agent","channel"]),x=Object.freeze(["global","site","tab","session","agent"]),l=Object.freeze(["R","M","L","C","A","X","H"]),S=Object.freeze(["pure","idempotent","replay-safe","non-replayable"]),I=Object.freeze(["none","redacted","delegated"]);class a extends Error{constructor(r,d,i=null){super(d),this.name="EventError",this.code=r,this.detail=i}}const t=e=>typeof e=="string"&&e.length>0,n=e=>typeof e=="number"&&Number.isFinite(e),u=e=>Array.isArray(e);function s(e){return!!e&&w.includes(e.kind)&&t(e.id)}function j(e){return!!e&&x.includes(e.kind)&&t(e.id)}const A={"turn.started":e=>t(e.turnId),"turn.ended":e=>t(e.turnId),"assistant.prompted":e=>t(e.turnId)&&o(e.ref),"assistant.message":e=>t(e.turnId)&&o(e.ref),"assistant.reasoning":e=>t(e.turnId)&&o(e.ref),"context.assembled":e=>n(e.budget)&&n(e.used)&&!!e.parts&&typeof e.parts=="object"&&u(e.resident)&&e.resident.every(o)&&n(e.reachableCount),"context.attached":e=>o(e.ref),"context.expanded":e=>o(e.ref)&&n(e.tokens),"context.retrieved":e=>t(e.tool)&&n(e.count)&&u(e.sources)&&e.sources.every(r=>r&&typeof r=="object"&&n(r.rank)),"capability.offered":e=>t(e.capability)&&t(e.reason),"capability.granted":e=>t(e.capability)&&s(e.actor),"capability.denied":e=>t(e.capability)&&s(e.actor),"capability.activated":e=>t(e.capability)&&l.includes(e.classUsed),"capability.revoked":e=>t(e.capability)&&t(e.cause),"capability.invoked":e=>t(e.capability)&&s(e.actor)&&j(e.scope)&&S.includes(e.effects)&&(e.effects==="pure"||t(e.idempotencyKey)),"capability.resulted":e=>t(e.capability)&&typeof e.ok=="boolean"&&l.includes(e.classUsed)&&!!e.cost&&n(e.cost.ms),"privacy.redacted":e=>!!e.counts&&typeof e.counts=="object"&&Object.values(e.counts).every(n),"privacy.egress":e=>t(e.host)&&typeof e.redacted=="boolean"&&typeof e.controlled=="boolean","policy.changed":e=>t(e.dial)&&s(e.actor)&&"from"in e&&"to"in e,"policy.guard_denied":e=>t(e.capability)&&t(e.reason),"data.created":e=>o(e.ref),"data.updated":e=>o(e.ref),"data.deleted":e=>o(e.ref)&&typeof e.shredded=="boolean","automation.fired":e=>t(e.ruleId)&&l.includes(e.classUsed),"automation.suppressed":e=>t(e.ruleId)&&t(e.reason),"shim.fired":e=>t(e.shimId)&&(e.engine==null||t(e.engine)),"judge.decided":e=>t(e.stage)&&t(e.choice)&&s(e.actor)&&(e.planned==null||t(e.planned))&&["read","of","chars"].every(r=>e[r]==null||n(e[r]))};function y(e){if(!e||typeof e!="object")throw new a("SHAPE","event must be an object");if(e.v!==c)throw new a("VERSION",`expected v=${c}, got ${e.v} — upcast first`,e.v);if(!t(e.id))throw new a("SHAPE","id required");if(!t(e.host))throw new a("SHAPE","host required");if(!Number.isInteger(e.seq)||e.seq<0)throw new a("SHAPE","seq must be a non-negative integer");if(!u(e.causes)||!e.causes.every(t))throw new a("SHAPE","causes must be string[]");if(!n(e.at))throw new a("SHAPE","at required (advisory wall clock)");if(!E.includes(e.type))throw new a("TYPE",`unknown type ${e.type}`,e.type);if(!e.payload||typeof e.payload!="object")throw new a("SHAPE","payload required");const r=A[e.type];if(r&&!r(e.payload))throw new a("PAYLOAD",`payload invalid for ${e.type}`,e.type);return e}function P(e){try{return y(e),!0}catch{return!1}}function k({host:e,seq:r=0,now:d=()=>Date.now(),newId:i}){if(!t(e))throw new a("SHAPE","host required");const b=i||(()=>globalThis.crypto.randomUUID());let f=r;return{get host(){return e},get seq(){return f},append(p,h,g=[]){const m=Object.freeze({v:c,id:b(),host:e,seq:f++,causes:Object.freeze([...g]),at:d(),type:p,payload:h});return y(m)}}}export{w as ACTOR_KINDS,E as ALL_TYPES,l as CLASSES,c as CURRENT_VERSION,S as EFFECTS,I as EGRESS,v as EVENT_TYPES,a as EventError,x as SCOPE_KINDS,k as createAppender,P as isValidEvent,y as validateEvent};
1
+ import{isRef as o}from"./ref.js";const l=1,m=Object.freeze({turn:["started","ended"],assistant:["prompted","message","reasoning"],context:["assembled","attached","expanded","retrieved"],capability:["offered","granted","denied","activated","revoked","invoked","resulted"],privacy:["redacted","egress"],policy:["changed","guard_denied"],data:["created","updated","deleted"],automation:["fired","suppressed"],shim:["fired"],judge:["decided"],access:["changed","denied"]}),E=Object.freeze(Object.entries(m).flatMap(([e,r])=>r.map(d=>`${e}.${d}`))),w=Object.freeze(["user","rule","schedule","model","agent","channel"]),x=Object.freeze(["global","site","tab","session","agent"]),u=Object.freeze(["R","M","L","C","A","X","H"]),S=Object.freeze(["pure","idempotent","replay-safe","non-replayable"]),I=Object.freeze(["none","redacted","delegated"]);class a extends Error{constructor(r,d,i=null){super(d),this.name="EventError",this.code=r,this.detail=i}}const t=e=>typeof e=="string"&&e.length>0,n=e=>typeof e=="number"&&Number.isFinite(e),c=e=>Array.isArray(e);function s(e){return!!e&&w.includes(e.kind)&&t(e.id)}function j(e){return!!e&&x.includes(e.kind)&&t(e.id)}const A={"turn.started":e=>t(e.turnId),"turn.ended":e=>t(e.turnId),"assistant.prompted":e=>t(e.turnId)&&o(e.ref),"assistant.message":e=>t(e.turnId)&&o(e.ref),"assistant.reasoning":e=>t(e.turnId)&&o(e.ref),"context.assembled":e=>n(e.budget)&&n(e.used)&&!!e.parts&&typeof e.parts=="object"&&c(e.resident)&&e.resident.every(o)&&n(e.reachableCount),"context.attached":e=>o(e.ref),"context.expanded":e=>o(e.ref)&&n(e.tokens),"context.retrieved":e=>t(e.tool)&&n(e.count)&&c(e.sources)&&e.sources.every(r=>r&&typeof r=="object"&&n(r.rank)),"capability.offered":e=>t(e.capability)&&t(e.reason),"capability.granted":e=>t(e.capability)&&s(e.actor),"capability.denied":e=>t(e.capability)&&s(e.actor),"capability.activated":e=>t(e.capability)&&u.includes(e.classUsed),"capability.revoked":e=>t(e.capability)&&t(e.cause),"capability.invoked":e=>t(e.capability)&&s(e.actor)&&j(e.scope)&&S.includes(e.effects)&&(e.effects==="pure"||t(e.idempotencyKey)),"capability.resulted":e=>t(e.capability)&&typeof e.ok=="boolean"&&u.includes(e.classUsed)&&!!e.cost&&n(e.cost.ms),"privacy.redacted":e=>!!e.counts&&typeof e.counts=="object"&&Object.values(e.counts).every(n),"privacy.egress":e=>t(e.host)&&typeof e.redacted=="boolean"&&typeof e.controlled=="boolean","policy.changed":e=>t(e.dial)&&s(e.actor)&&"from"in e&&"to"in e,"policy.guard_denied":e=>t(e.capability)&&t(e.reason),"data.created":e=>o(e.ref),"data.updated":e=>o(e.ref),"data.deleted":e=>o(e.ref)&&typeof e.shredded=="boolean","automation.fired":e=>t(e.ruleId)&&u.includes(e.classUsed),"automation.suppressed":e=>t(e.ruleId)&&t(e.reason),"shim.fired":e=>t(e.shimId)&&(e.engine==null||t(e.engine)),"access.changed":e=>t(e.resource)&&s(e.actor)&&c(e.fields)&&e.fields.length>0&&e.fields.every(t),"access.denied":e=>t(e.resource)&&t(e.action)&&s(e.actor),"judge.decided":e=>t(e.stage)&&t(e.choice)&&s(e.actor)&&(e.planned==null||t(e.planned))&&["read","of","chars"].every(r=>e[r]==null||n(e[r]))};function y(e){if(!e||typeof e!="object")throw new a("SHAPE","event must be an object");if(e.v!==l)throw new a("VERSION",`expected v=${l}, got ${e.v} — upcast first`,e.v);if(!t(e.id))throw new a("SHAPE","id required");if(!t(e.host))throw new a("SHAPE","host required");if(!Number.isInteger(e.seq)||e.seq<0)throw new a("SHAPE","seq must be a non-negative integer");if(!c(e.causes)||!e.causes.every(t))throw new a("SHAPE","causes must be string[]");if(!n(e.at))throw new a("SHAPE","at required (advisory wall clock)");if(!E.includes(e.type))throw new a("TYPE",`unknown type ${e.type}`,e.type);if(!e.payload||typeof e.payload!="object")throw new a("SHAPE","payload required");const r=A[e.type];if(r&&!r(e.payload))throw new a("PAYLOAD",`payload invalid for ${e.type}`,e.type);return e}function P(e){try{return y(e),!0}catch{return!1}}function k({host:e,seq:r=0,now:d=()=>Date.now(),newId:i}){if(!t(e))throw new a("SHAPE","host required");const b=i||(()=>globalThis.crypto.randomUUID());let f=r;return{get host(){return e},get seq(){return f},append(p,h,g=[]){const v=Object.freeze({v:l,id:b(),host:e,seq:f++,causes:Object.freeze([...g]),at:d(),type:p,payload:h});return y(v)}}}export{w as ACTOR_KINDS,E as ALL_TYPES,u as CLASSES,l as CURRENT_VERSION,S as EFFECTS,I as EGRESS,m as EVENT_TYPES,a as EventError,x as SCOPE_KINDS,k as createAppender,P as isValidEvent,y as validateEvent};
@@ -0,0 +1,5 @@
1
+ import{EventError as w}from"./event.js";const R="/v1/extract",M="chatpanel-extract",q=64*1024*1024,T=6e3,_=Object.freeze(["pdf","docx","xlsx","pptx","odt","ods","odp","epub","md","txt","html","csv","text"]),h=t=>!!t&&typeof t=="object"&&!Array.isArray(t),l=t=>typeof t=="string"&&t.length>0,g=t=>typeof t=="number"&&Number.isFinite(t),n=(t,a)=>{if(!t)throw new w("SHAPE",a)},f=/^[0-9a-f]{64}$/;function y(t){n(h(t),"extract: body must be an object");const a={};if(t.budgetMs!=null&&(n(g(t.budgetMs)&&t.budgetMs>=0,"extract: budgetMs must be a number ≥ 0"),a.budgetMs=t.budgetMs),t.hash!=null)return n(typeof t.hash=="string"&&f.test(t.hash),"extract: hash must be 64 hex characters"),n(Number.isInteger(t.page)&&t.page>=1,"extract: page (integer ≥ 1) required with hash"),{kind:"page",hash:t.hash,page:t.page,...a};n(l(t.name),"extract: name required"),n(l(t.data),"extract: data (base64) required"),n(t.data.length<=Math.ceil(q*4/3)+4,"extract: document too large");const r={kind:"open",name:t.name,data:t.data,...a};return t.type!=null&&(n(l(t.type),"extract: type must be a non-empty string"),r.type=t.type.toLowerCase()),r}const O="/v1/extract/context",d=8;function S(t){n(h(t),"extract/context: body must be an object"),n(l(t.question)&&t.question.length<=2e3,"extract/context: question (string, ≤ 2000 characters) required"),n(Array.isArray(t.documents)&&t.documents.length>=1&&t.documents.length<=d,`extract/context: documents (1–${d}) required`);const a=t.documents.map((e,c)=>{if(n(h(e),`extract/context: documents[${c}] must be an object`),e.hash!=null)return n(typeof e.hash=="string"&&f.test(e.hash),`extract/context: documents[${c}].hash must be 64 hex characters`),{hash:e.hash,...e.name!=null?{name:String(e.name)}:{}};const s=y({name:e.name,data:e.data,...e.type!=null?{type:e.type}:{}});return{name:s.name,data:s.data,...s.type?{type:s.type}:{}}}),r={question:t.question,documents:a};return t.window!=null&&(n(Number.isInteger(t.window)&&t.window>0,"extract/context: window must be a positive integer (tokens)"),r.window=t.window),t.budgetChars!=null&&(n(Number.isInteger(t.budgetChars)&&t.budgetChars>=800,"extract/context: budgetChars must be an integer ≥ 800"),r.budgetChars=t.budgetChars),r}function X(t){return n(h(t),"extract/context: response must be an object"),n(t.attachment===null||h(t.attachment)&&t.attachment.kind==="prefetch"&&typeof t.attachment.text=="string","extract/context: attachment must be null or a prefetch block"),n(Array.isArray(t.read)&&Array.isArray(t.skipped),"extract/context: read and skipped (arrays) required"),n(["whole","pages","none"].includes(t.how),"extract/context: how must be whole, pages or none"),n(g(t.ms)&&t.ms>=0,"extract/context: ms required"),t}function E(t){return n(h(t),"extract: response must be an object"),n(typeof t.hash=="string"&&f.test(t.hash),"extract: hash (sha-256 hex) required"),n(Number.isInteger(t.pages)&&t.pages>=0,"extract: pages (integer ≥ 0) required"),n(l(t.type),"extract: type required"),n(l(t.provider),"extract: provider required"),n(g(t.ms)&&t.ms>=0,"extract: ms required"),t.page!=null&&(n(Number.isInteger(t.page)&&t.page>=1&&t.page<=Math.max(1,t.pages),"extract: page out of range"),n(typeof t.text=="string","extract: text (string, may be empty) required with page")),t.title!=null&&n(typeof t.title=="string","extract: title must be a string"),t}function k(t,{pageChars:a=T}={}){const r=String(t||"").replace(/\r\n?/g,`
2
+ `);if(!r.trim())return[];const e=[];let c=0;for(;c<r.length;){if(r.length-c<=a){e.push(r.slice(c));break}const s=r.slice(c,c+a),u=Math.floor(a*.6);let i=-1;const p=[...s.matchAll(/\n(?=#{1,6} |[A-Z][^\n]{0,80}\n[=-]{3,}\n)/g)].map(o=>o.index).filter(o=>o>=u);if(p.length&&(i=p[p.length-1]+1),i<0){const o=s.lastIndexOf(`
3
+
4
+ `);o>=u&&(i=o+2)}if(i<0){const o=s.lastIndexOf(`
5
+ `);o>=u&&(i=o+1)}i<0&&(i=a),e.push(r.slice(c,c+i)),c+=i}return e.map(s=>s.replace(/^\n+/,"")).filter(s=>s.trim())}function I({call:t,toBase64:a=C}={}){if(typeof t!="function")throw new w("SHAPE","gatewayExtractor: call required");const r=new Map;return async(e,{type:c="",name:s="document"}={})=>{const u=a(e),i=`${s}:${u.length}:${u.slice(0,64)}${u.slice(-64)}`;if(r.has(i))return r.get(i);let p;try{p=E(await t({name:s,...c?{type:c}:{},data:u}))}catch{return null}const o={hash:p.hash,type:p.type,pages:p.pages,title:p.title||"",async page(x){let m;try{m=E(await t({hash:p.hash,page:x}))}catch(A){throw r.delete(i),A}return m.text||""}};return r.set(i,o),o}}function C(t){typeof t=="string"&&(t=new TextEncoder().encode(t));const a=t instanceof Uint8Array?t:new Uint8Array(t);if(typeof Buffer<"u"&&Buffer.from)return Buffer.from(a.buffer,a.byteOffset,a.byteLength).toString("base64");let r="";for(let e=0;e<a.length;e+=32768)r+=String.fromCharCode.apply(null,a.subarray(e,e+32768));return btoa(r)}function N(...t){const a=t.filter(e=>typeof e=="function"),r=async(e,c,s)=>{for(let u=e;u<a.length;u+=1)try{const i=await a[u](c,s);if(i)return{doc:i,i:u}}catch{}return null};return async(e,c)=>{const s=await r(0,e,c);if(!s)return null;let{doc:u,i}=s;return{...u,get pages(){return u.pages},async page(p){try{return await u.page(p)}catch(o){const x=await r(i+1,e,c);if(!x)throw o;return{doc:u,i}=x,u.page(p)}}}}}export{d as EXTRACT_CONTEXT_MAX_DOCS,O as EXTRACT_CONTEXT_ROUTE,M as EXTRACT_PROVIDER_ID,R as EXTRACT_ROUTE,_ as EXTRACT_TYPES,q as MAX_DOCUMENT_BYTES,T as PAGE_CHARS,N as extractorChain,I as gatewayExtractor,k as paginateText,S as validateExtractContextRequest,X as validateExtractContextResponse,y as validateExtractRequest,E as validateExtractResponse};
@@ -0,0 +1 @@
1
+ import{EventError as o}from"./event.js";import{MAX_DOCUMENT_BYTES as k}from"./extract-capability.js";import{validateContextFilters as h}from"./context-api.js";const l="/v1/kb",f=/^[a-z0-9][a-z0-9_-]{0,63}$/i,g=Object.freeze(["documents","passages","outline","search","research","graph","report","notes","embed","access","sync","pages","reveal","view","instructions"]),v=Object.freeze(["sync","reveal"]),_="x-chatpanel-agent",K=Object.freeze(["bytes","path","url","text"]),x=4e6,a=e=>!!e&&typeof e=="object"&&!Array.isArray(e),n=e=>typeof e=="string"&&e.length>0,r=(e,t)=>{if(!e)throw new o("SHAPE",t)},c=(e,t,s,i)=>{if(e==null)return i;const u=Number(e);return r(Number.isInteger(u)&&u>=t&&u<=s,`must be an integer ${t}–${s}`),u};function M(e){const t=String(e||"");if(t!==l&&!t.startsWith(`${l}/`))return null;const s=t.slice(l.length).split("/").filter(Boolean).map(m=>{try{return decodeURIComponent(m)}catch{return m}});if(!s.length)return{id:"",sub:"",rest:""};const[i,u="",...p]=s;return f.test(i)?u&&!g.includes(u)?{id:i,sub:"",rest:"",bad:u}:{id:i,sub:u,rest:p.join("/")}:{id:"",sub:"",rest:"",bad:i}}function d(e={}){r(a(e),"kb: body must be an object");const t={};return e.id!=null&&(r(n(e.id)&&f.test(e.id),"kb: id must be 1–64 letters, digits, - or _"),t.id=e.id),e.name!=null&&(r(typeof e.name=="string","kb: name must be a string"),t.name=e.name.trim().slice(0,120)),e.embed!=null&&(r(e.embed==="auto"||e.embed==="off",'kb: embed must be "auto" or "off"'),t.embed=e.embed),t}function j(e={}){r(a(e),"kb: body must be an object");const t=e.title!=null?String(e.title).trim().slice(0,200):"",s=e.reach!=null?String(e.reach):"";if(n(e.data))return r(n(e.name),"kb: name required with data"),r(e.data.length<=Math.ceil(k*4/3)+4,"kb: document too large"),{kind:"bytes",name:e.name,data:e.data,...n(e.type)?{type:e.type.toLowerCase()}:{},title:t,reach:s};if(n(e.path))return{kind:"path",path:e.path,recursive:e.recursive!==!1,title:t,reach:s,...Array.isArray(e.include)?{include:e.include.map(String).slice(0,20)}:{}};if(n(e.url))return r(/^https?:\/\//i.test(e.url),"kb: url must be http(s)"),{kind:"url",url:e.url,title:t,reach:s};if(typeof e.text=="string")return r(e.text.trim().length>0,"kb: text is empty"),r(e.text.length<=x,"kb: text too long"),{kind:"text",text:e.text,name:n(e.name)?e.name:t||"text",title:t,reach:s};throw new o("SHAPE","kb: one of data (with name), path, url or text is required")}function w(e={}){r(a(e),"kb: body must be an object"),r(n(e.query)&&e.query.trim().length>0,"kb: query required");const t={query:e.query.trim().slice(0,2e3)};if(t.limit=c(e.limit,1,50,10),t.hops=c(e.hops,0,2,1),e.docs!=null&&(r(Array.isArray(e.docs)&&e.docs.every(n),"kb: docs must be a list of document ids"),t.docs=e.docs.slice(0,100)),e.queries!=null&&(r(Array.isArray(e.queries)&&e.queries.every(s=>typeof s=="string"),"kb: queries must be strings"),t.queries=e.queries.map(s=>s.trim()).filter(Boolean).slice(0,6)),e.rerank!=null&&(r(typeof e.rerank=="boolean","kb: rerank must be a boolean"),t.rerank=e.rerank),e.budgetMs!=null&&(r(Number.isFinite(Number(e.budgetMs))&&e.budgetMs>=0,"kb: budgetMs must be ≥ 0"),t.budgetMs=Number(e.budgetMs)),e.filters!=null){const s=h(e.filters);if(s){const{docs:i,...u}=s;Object.keys(u).length&&(t.filters=u),i?.length&&!t.docs&&(t.docs=i)}}return t}function N(e={}){return r(a(e),"kb: body must be an object"),e.doc!=null?(r(n(e.doc)&&e.doc.length<=64,"kb: doc must be a document id"),{doc:e.doc}):e.source!=null?(r(Number.isInteger(e.source)&&e.source>=0&&e.source<100,"kb: source must be the index of a kept folder"),{source:e.source}):{index:!0}}const S=e=>{const t=Number(e);return Number.isInteger(t)?Math.max(12,Math.min(200,t)):60};function E(e={}){r(a(e),"kb: body must be an object"),r(n(e.question)&&e.question.trim().length>0,"kb: question required");const t={question:e.question.trim().slice(0,2e3)};return e.answer!=null&&(r(typeof e.answer=="string","kb: answer must be a string"),t.answer=e.answer.trim().slice(0,400)),e.ask!=null&&(r(typeof e.ask=="boolean","kb: ask must be a boolean"),t.ask=e.ask),e.model!=null&&(r(typeof e.model=="string","kb: model must be a string"),t.model=e.model.trim()),e.previous!=null&&(r(a(e.previous),"kb: previous must be an object"),t.previous=e.previous),e.docs!=null&&(r(Array.isArray(e.docs)&&e.docs.every(n),"kb: docs must be a list of document ids"),t.docs=e.docs.slice(0,100)),t}function B(e={}){r(a(e),"kb: body must be an object"),r(n(e.node)&&e.node.trim().length>0,"kb: node required");const t={node:e.node.trim().slice(0,200)};return t.hops=c(e.hops,1,3,1),t.limit=c(e.limit,1,100,20),e.kinds!=null&&(r(Array.isArray(e.kinds)&&e.kinds.every(n),"kb: kinds must be strings"),t.kinds=e.kinds),e.to!=null&&(r(n(e.to),"kb: to must be a node"),t.to=e.to.trim().slice(0,200)),e.query!=null&&(r(typeof e.query=="string","kb: query must be a string"),e.query.trim()&&(t.query=e.query.trim().slice(0,500))),t}function O(e={}){r(a(e),"kb: body must be an object"),r(typeof e.text=="string"&&e.text.trim().length>0,"kb: text required");const t={text:e.text.trim().slice(0,4e3)};return e.cites!=null&&(r(Array.isArray(e.cites)&&e.cites.every(n),"kb: cites must be passage ids"),t.cites=e.cites.slice(0,20)),e.status!=null&&(r(e.status==="proposed"||e.status==="accepted","kb: status must be proposed or accepted"),t.status=e.status),e.by!=null&&(r(typeof e.by=="string","kb: by must be a string"),t.by=e.by.trim().slice(0,40)),t}function C(e={}){return r(a(e),"kb: body must be an object"),e.agents==="all"?{agents:"all"}:(r(Array.isArray(e.agents)&&e.agents.every(t=>typeof t=="string"&&t.trim()),'kb: agents must be "all" or a list of agent names'),{agents:e.agents.map(t=>t.trim().toLowerCase()).slice(0,100)})}function I(e={}){return r(a(e),"kb: body must be an object"),r(["proposed","accepted","removed"].includes(e.status),"kb: status must be proposed, accepted or removed"),{status:e.status}}function R({id:e,name:t="",docs:s=0,url:i="",mention:u=!1}={}){return r(n(e),"kbAttachment: id required"),{kind:"kb",id:e,title:t||e,docs:Number(s)||0,...i?{url:i}:{},...u?{mention:!0}:{}}}function T({id:e,name:t=""}={}){return r(n(e),"kbDetachment: id required"),{kind:"kb",id:e,title:t||e,off:!0}}function D(e=[]){const t=new Map;for(const s of Array.isArray(e)?e:[])for(const i of s?.attachments||[])i?.kind!=="kb"||!n(i.id)||(i.off?t.delete(i.id):(t.delete(i.id),t.set(i.id,i)));return[...t.values()]}function z(e={}){return r(a(e),"kb: body must be an object"),r(n(e.path),"kb: path required — the folder to keep in this base"),{path:e.path,...Array.isArray(e.include)?{include:e.include.map(String).slice(0,20)}:{},...n(e.name)?{name:e.name.trim().slice(0,120)}:{},...Number.isFinite(Number(e.waitMs))?{waitMs:Math.max(0,Math.min(25e3,Math.round(Number(e.waitMs))))}:{},...e.rebuild===!0?{rebuild:!0}:{}}}export{_ as KB_AGENT_HEADER,f as KB_ID_RE,v as KB_LOCAL_ACTIONS,x as KB_MAX_TEXT_CHARS,l as KB_ROUTE,K as KB_SOURCE_KINDS,g as KB_SUBS,R as kbAttachment,D as kbAttachmentsOf,T as kbDetachment,S as kbGraphLimit,M as routeKb,C as validateKbAccess,j as validateKbAdd,d as validateKbCreate,B as validateKbGraph,O as validateKbNote,I as validateKbNoteStatus,E as validateKbResearch,N as validateKbReveal,w as validateKbSearch,z as validateKbSync};
@@ -0,0 +1,3 @@
1
+ import{agentServerRef as b}from"./agent-mcp.js";import{kbAttachment as h}from"./kb-capability.js";const g=Object.freeze([{name:"web",group:"data",action:"web_search",description:"Search the web"},{name:"weather",group:"data",action:"weather",description:"Weather and forecast"},{name:"history",group:"data",action:"history_search",description:"Your past chats, notes and meetings"},{name:"notes",group:"note",description:"Write or change your notes"},{name:"memory",group:"memory",description:"What Chap remembers about you"},{name:"page",group:"page",description:"The open tab — read it or act on it",surfaces:["panel"]},{name:"sideline",group:"sideline",action:"sideline",description:"Hand a task to a coding agent, a team or a model"},{name:"team",group:"team",action:"team",description:"Run a saved team"},{name:"recipe",group:"recipes",action:"recipe",description:"Run a saved recipe"},{name:"widget",group:"widgets",description:"Build a small app you can keep"}].map(Object.freeze)),y=/[^a-z0-9_.-]+/g,m=o=>String(o||"").toLowerCase().replace(y,"-").replace(/^-+|-+$/g,"").slice(0,40);function z(o){if(/^\s*\/(?:sideline|breakout)\b/i.test(String(o||"")))return null;const t=/(?:^|\s)@([a-z0-9_.-]*)$/i.exec(String(o||""));return t?t[1]:null}const f=Object.freeze([Object.freeze({type:"binder",label:"Binders"}),Object.freeze({type:"tool",label:"Tools"}),Object.freeze({type:"kb",label:"Knowledge bases"}),Object.freeze({type:"server",label:"MCP servers"}),Object.freeze({type:"skill",label:"Skills"})]),$=new Map(f.map((o,t)=>[o.type,t]));function C({tools:o=g,surface:t="",servers:n=[],skills:r=[],bases:i=[],binders:s=[]}={}){const p=[],c=new Set,l=e=>{e.name&&!c.has(e.name)&&(c.add(e.name),p.push(e))};for(const e of o||[])e?.surfaces&&t&&!e.surfaces.includes(t)||l({type:"tool",name:e.name,group:e.group,action:e.action||"",description:e.description||""});for(const e of n||[]){if(!e||e.enabled===!1)continue;const a=b(e);l({type:"server",name:m(a?a.server.replace(/^@builtin$/,`${a.agent}-files`):e.name||e.url||e.command),id:e.id||"",label:e.name||"",group:"mcp",description:e.name?`MCP · ${e.name}`:"MCP server"})}for(const e of r||[]){const a=e?.command||"";!a||e.enabled===!1||l({type:"skill",name:m(a),command:a,group:"skills",description:e.description||"Skill"})}for(const e of i||[]){if(!e?.id)continue;const a=m(e.name||e.id)||m(e.id),d=c.has(a)?m(`${a.slice(0,37)}-kb`):a,u=Number(e.docs)||0;l({type:"kb",name:d,id:String(e.id),label:String(e.name||e.id),docs:u,group:"",description:`${e.name||e.id} · ${u} document${u===1?"":"s"}`})}for(const e of s||[]){if(!e||!/^context:[^:\s]+$/.test(String(e.id||""))||Number(e.deletedAt)>0||e.kind&&e.kind!=="context")continue;const a=String(e.title||"").trim()||"Binder",d=m(a)||"binder",u=c.has(d)?m(`${d.slice(0,33)}-binder`):d;l({type:"binder",name:u,id:String(e.id),label:a,group:"",description:w(e)})}return p}const k=[["chat","chat","chats"],["note","note","notes"],["meeting","meeting","meetings"],["brief","brief","briefs"]];function w(o){const t=o.body?.members&&typeof o.body.members=="object"?Object.entries(o.body.members).filter(([,s])=>s?.on).map(([s])=>s):[],n=s=>o.counts&&Number.isFinite(Number(o.counts[s]))?Number(o.counts[s]):t.filter(p=>p.startsWith(`${s}:`)).length,r=Array.isArray(o.refs)?o.refs.length:o.body?.refs&&typeof o.body.refs=="object"?Object.values(o.body.refs).filter(s=>s?.on).length:0,i=k.map(([s,p,c])=>[n(s),p,c]).filter(([s])=>s>0).map(([s,p,c])=>`${s} ${s===1?p:c}`);return r&&i.push(`${r} ${r===1?"source":"sources"}`),i.length?`Binder · ${i.join(", ")}`:"Binder"}function A(o=[],t="",{cap:n=24,perType:r=6}={}){const i=String(t||"").toLowerCase(),s=o.filter(e=>e.name.startsWith(i)),p=i?o.filter(e=>!e.name.startsWith(i)&&e.name.includes(i)):[],c=[...s,...p],l=[];for(const e of[...f.map(a=>a.type),...new Set(c.map(a=>a.type).filter(a=>!$.has(a)))])l.push(...c.filter(a=>a.type===e).slice(0,r));return l.slice(0,n)}function _(o=[]){const t=[];for(const n of o||[]){const r=t[t.length-1];r&&r.type===n.type?r.items.push(n):t.push({type:n.type,label:f.find(i=>i.type===n.type)?.label||n.type,items:[n]})}return t}function M(o=[]){return(o||[]).filter(t=>t?.type==="kb"&&t.id).map(t=>h({id:t.id,name:t.label||t.name,docs:t.docs,mention:!0}))}function S(o=[]){return[...new Set((o||[]).filter(t=>t?.type==="binder"&&t.id).map(t=>String(t.id)))]}function T(o=[],t=[],{max:n=8}={}){const r=[...Array.isArray(o)?o:[],...S(t)].map(String).filter(i=>/^context:[^:\s]+$/.test(i));return[...new Set(r.reverse())].reverse().slice(-n)}function B(o=[],t=[],{off:n={}}={}){if(!(t||[]).some(s=>s?.type==="binder"))return[];const r=new Map;for(const s of Array.isArray(o)?o:[]){if(s?.role!=="user"||typeof s.content!="string"||!s.content.includes("@"))continue;const p=Number(s.at)||Number(s.createdAt)||0;for(const c of O(s.content,t))c.type==="binder"&&c.id&&(r.delete(c.id),r.set(c.id,p))}const i=n&&typeof n=="object"?n:{};return[...r.entries()].filter(([s,p])=>!(Number(i[s])>0&&Number(i[s])>=p)).map(([s])=>s)}function x(o){return`@${o?.name||""} `}function E(o,t,n){const r=String(o||""),i=r.slice(0,t).lastIndexOf("@");if(i<0)return{text:r,caret:t};const s=r.slice(0,i)+x(n);return{text:s+r.slice(t).replace(/^\S*\s?/,""),caret:s.length}}function O(o,t=[]){const n=new Map((t||[]).map(l=>[l.name,l])),r=[],i=new Set,s=l=>{const e=n.get(String(l||"").toLowerCase().replace(/[.]+$/,""));e&&!i.has(e.name)&&(i.add(e.name),r.push(e))},p=String(o||"");if(/^\s*\/(?:sideline|breakout)\b/i.test(p))return r;for(const l of p.matchAll(/(?<![\w@.])@([a-z0-9][a-z0-9_.-]*)/gi))s(l[1]);const c=/^\s*\/([a-z0-9][a-z0-9_.-]*)/i.exec(p);return c&&n.get(c[1].toLowerCase())?.type==="skill"&&s(c[1]),r}function L(o=[]){const t=new Set;for(const n of o||[])n?.group&&t.add(n.group),n?.type==="skill"&&t.add("sideline");return[...t]}function N(o=[]){const t=[];for(const n of o||[])n.type==="tool"?t.push(n.action?`\`${n.name}\`: call {"action":"${n.action}",…} through \`tools\` for this.`:`\`${n.name}\`: use Chap's ${n.description.toLowerCase()} tools — \`tools\` with {"action":"find","query":"${n.name}"} finds them.`):n.type==="server"?t.push(`\`${n.name}\`: the ${n.label||n.name} MCP server — {"action":"find","query":"${n.name}"} lists its tools.`):n.type==="kb"?t.push(`\`${n.name}\`: the knowledge base "${n.label||n.name}" — its best passages come with this message; search it further with {"action":"kb_search",…} through \`tools\`, and cite what you use.`):n.type==="skill"&&t.push(`\`${n.command}\` skill: open it first — {"action":"skill_open","args":{"name":"${n.command}"}} — and follow it.`);return t.length?`[Chap] The person picked for this message — use ${t.length===1?"it":"them"}:
2
+ ${t.map(n=>`- ${n}`).join(`
3
+ `)}`:""}function P(o=[]){const t=N(o);return t?{id:"mentions",quiet:!0,specs:[],execute:async()=>"",hint:()=>t}:null}export{g as MENTION_TOOLS,f as MENTION_TYPES,B as bindersNamedIn,T as keepBinders,E as mentionApply,C as mentionCatalog,N as mentionHint,x as mentionInsert,A as mentionItems,P as mentionProvider,_ as mentionSections,z as mentionTyping,M as mentionedBases,S as mentionedBinders,O as parseMentions,L as pinnedGroups};
@@ -0,0 +1 @@
1
+ function l(c,{k:u=60,limit:h=0,weights:a=null}={}){const r=new Map;(c||[]).forEach((e,o)=>{if(!Array.isArray(e))return;const s=Array.isArray(a)&&Number.isFinite(a[o])?a[o]:1;e.forEach((t,i)=>{t!=null&&r.set(t,(r.get(t)||0)+s/(u+i))})});const n=[...r.entries()].map(([e,o])=>({id:e,score:o})).sort((e,o)=>o.score-e.score);return h>0?n.slice(0,h):n}const w=new Set("a an and are as at be been but by can could did do does for from had has have how i if in into is it its me my of on or our ought shall should so than that the their them then there these they this those to um was we were what when where which who whom why will with would you your about tell show give find get please could-you was-there did-we".split(/\s+/));function d(c,{extra:u=[],max:h=4}={}){const a=String(c||"").trim(),r=[],n=new Set,e=t=>{const i=String(t||"").trim().replace(/\s+/g," "),f=i.toLowerCase();i&&!n.has(f)&&(n.add(f),r.push(i))};e(a);for(const t of u)e(t);const s=(a.toLowerCase().match(/[a-z0-9][a-z0-9'’_+-]*/g)||[]).filter(t=>!w.has(t)&&t.length>2);return s.length>=2&&e(s.join(" ")),s.length>3&&e([...s].sort((t,i)=>i.length-t.length).slice(0,3).join(" ")),r.slice(0,Math.max(1,h))}async function p(c,u,{limit:h=10,k:a=60}={}){const r=[],n=new Map,e=new Map;for(const o of c||[]){let s=[];try{s=await u(o)||[]}catch{s=[]}r.push(s.map(t=>t.id));for(const t of s)(!n.has(t.id)||!n.get(t.id).snippet&&t.snippet)&&n.set(t.id,t),e.has(t.id)||e.set(t.id,[]),e.get(t.id).push(o)}return l(r,{k:a,limit:h}).map(({id:o,score:s})=>({...n.get(o),id:o,score:s,foundBy:e.get(o)||[]}))}export{l as fuseRRF,p as multiSearch,d as planQueries};
@@ -0,0 +1,10 @@
1
+ const $=/\n{2,}/,d=n=>Math.ceil(String(n||"").length/4);function f(n,o=0){const r=String(n?.url||"");return/^(?:chat|note|meeting|brief):[A-Za-z0-9_-]+$/.test(r)?r:`${String(n?.kind||"src").toLowerCase().replace(/[^a-z0-9]+/g,"")||"src"}-${o+1}`}function y(n=[]){const o=(Array.isArray(n)?n:[n]).filter(e=>e&&(e.text||e.url)).map((e,t,s)=>({id:e.id||(s.findIndex(a=>f(a,0)===f(e,0))<t?f({kind:e.kind},t):f(e,t)),kind:e.kind||"context",title:e.title||e.url||"Untitled",url:e.url||"",text:String(e.text||""),tokens:d(e.text)})),r=new Map(o.map(e=>[e.id,e]));return{entries:o,get:e=>r.get(String(e||"").trim())||null,get tokens(){return o.reduce((e,t)=>e+t.tokens,0)}}}function x(n,o=120){const r=String(n||"");if(!r||r.length<=o)return r;try{const e=new URL(r),t=`${e.host}${e.pathname}`.replace(/\/$/,""),s=[...e.searchParams.entries()][0],a=s&&`${s[0]}=${s[1]}`,l=a&&`${t}?${a}`,u=l&&l.length<=o?l:t;return u.length<=o?`${u}…`:`${u.slice(0,o)}…`}catch{return`${r.slice(0,o)}…`}}function M(n){return n?.entries?.length?["Attached sources (NOT included below — read them with the `source` tool):",...n.entries.map(r=>`- ${r.id} — ${r.title}${r.url?` (${x(r.url)})`:""} · ~${r.tokens} tokens`)].join(`
2
+ `):""}const k=n=>n.length>6?n.slice(0,Math.max(5,Math.ceil(n.length/2))):n;function m(n,o){if(!o.length)return 0;const r=n.toLowerCase();let e=0;for(const t of o)r.includes(k(t))&&(e+=Math.min(3,t.length/4));return e}const w=new Set(["the","and","for","this","that","with","from","what","when","where","which","have","has","was","are","you","your","can","about","into","does","did","how","why","all","any","its"]);function S(n){return String(n||"").toLowerCase().split(/[^a-z0-9]+/).filter(o=>o.length>2&&!w.has(o))}function b(n,o=2e3){const r=Math.max(400,Math.floor(o*4/6)),e=[];for(const t of String(n||"").split($)){if(!t.trim())continue;if(t.length<=r){e.push(t);continue}let s="";for(const a of t.split(`
3
+ `))for(let l=0;l<Math.max(1,a.length);l+=r){const u=a.slice(l,l+r);s&&s.length+u.length+1>r&&(e.push(s),s=""),s=s?`${s}
4
+ ${u}`:u}s.trim()&&e.push(s)}return e}function N(n,{id:o,query:r="",maxTokens:e=2e3}={}){const t=n?.get?.(o);if(!t){const i=(n?.entries||[]).map(c=>c.id).join(", ");return{error:`No attached source '${o}'.${i?` Available: ${i}.`:" Nothing is attached."}`}}const s=Math.max(200,Number(e)||2e3);if(t.tokens<=s)return{id:t.id,title:t.title,url:t.url,text:t.text,truncated:!1,of:t.tokens};const a=S(r),l=b(t.text,s);if(!a.length){const i=t.text.slice(0,s*4);return{id:t.id,title:t.title,url:t.url,text:i,truncated:!0,of:t.tokens,note:`Showing the first ~${d(i)} of ${t.tokens} tokens. Pass a query to get the relevant parts instead.`}}const u=l.map((i,c)=>({c:i,i:c,s:m(i,a)})).filter(i=>i.s>0).sort((i,c)=>c.s-i.s),h=[];let g=0;for(const i of u){const c=d(i.c);g+c>s||(h.push(i),g+=c)}if(!h.length){const i=t.text.slice(0,s*4);return{id:t.id,title:t.title,url:t.url,text:i,truncated:!0,of:t.tokens,note:`Nothing in this source matched '${r}'. Showing the beginning instead.`}}h.sort((i,c)=>i.i-c.i);const p=h.some((i,c)=>c>0&&i.i!==h[c-1].i+1);return{id:t.id,title:t.title,url:t.url,text:h.map(i=>i.c).join(p?`
5
+
6
+ […]
7
+
8
+ `:`
9
+
10
+ `),truncated:!0,of:t.tokens,note:`${h.length} of ${l.length} sections, matched on '${r}'.`}}export{d as approxTokens,y as makeSourceStore,M as manifestText,S as queryTerms,N as readSource,b as sectionsOf,x as shortUrl,f as sourceId};
package/src/server.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as Le}from"node:http";import O from"node:os";import{randomBytes as We,randomInt as je,timingSafeEqual as Fe}from"node:crypto";import{mkdirSync as Je,writeFileSync as Xe,readFileSync as ae,existsSync as Ke}from"node:fs";import{join as M}from"node:path";import*as ze from"./engines/claude.js";import*as Ye from"./engines/codex.js";import*as Ve from"./engines/antigravity.js";import{pi as Qe,opencode as Ze,kiro as qe,copilot as et,deepseek as tt,hermes as nt}from"./engines/cli-agents.js";import{connectorsFor as ot}from"./connectors.js";import{agentServersFor as rt,resolveAgentServer as ie,builtinRefusal as at,narrowBuiltinList as it}from"./agent-mcp.js";import*as st from"./engines/custom.js";import{installService as ct,uninstallService as lt,serviceStatus as dt,restartService as se}from"./service.js";import{skillIndex as J,listRecords as ut,readRecord as ht,readPackageFile as pt,skillsHealth as ft,quarantinedSkills as mt,clearSkillCache as X,preferredIndex as K}from"./skills.js";import{writeSkillPackage as gt,writeSkillFile as wt,deleteSkillPackage as yt,SkillWriteError as bt}from"./skill-write.js";import{agentDefRoots as St,scanAgentDefs as kt,listAgentDefs as Tt,readAgentDef as vt,planAgentExport as xt,exportAgentDef as Et,agentDefsHealth as At,AgentDefError as Ot}from"./agent-defs.js";import{capabilityToolSpecs as Ct,runCapabilityTool as Pt}from"./mcp-capabilities.js";import{createSession as $t,deleteSession as ce,getSession as le,activeSession as Rt,relayToolCall as It}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Nt,isDefaultWorkdir as Dt,resolveWorkdir as _t,writeScopeNote as Ht}from"./workdir.js";import{sandbox as z,runSandboxCli as Mt,withGrant as de,withAgentGrant as Bt,withoutOutsideWhenCapped as Gt,grantedWriteRoots as ue,acceptRefusalReport as Ut,liveProcesses as Lt,sandboxConfigFromEnv as Wt}from"./sandbox.js";import{createAccessGate as jt,chatKeyOf as Ft,chatFolders as Jt}from"./access-gate.js";import{signInDenial as Xt}from"./events/sandbox-policy.js";import{gitState as Kt,gitDelta as zt}from"./scm.js";import{listConnections as Yt,putConnection as Vt,removeConnection as Qt,runEnvFor as Zt,testConnection as qt,secretBackend as he}from"./connections.js";import{worktreeFor as pe,listWorktrees as en,removeWorktree as tn,withHook as nn,WORKTREE_ROOT as fe}from"./worktree.js";import{AGENT_CLIS as on,agentAvailable as rn,agentInstallDirs as an,enrichPath as sn,enrichAgentEnv as cn,findAgentBin as ln,forgetMisses as dn,primeAgentLookups as un,resolveCommand as me,isCompiledBinary as hn}from"./env.js";import"./sanitize.js";import{checkForUpdate as pn,selfUpdate as ge,isEmbedded as we}from"./update.js";import{callLocalMcp as fn,localMcpStatus as mn,signInLocalMcp as gn,signInStatusLocalMcp as wn}from"./mcp-local.js";import{assertPublicHttpUrl as ye,assertPublicWebUrl as be}from"./ssrf.js";import{startRun as Se,endRun as Y,cancelRun as yn,cancelAll as bn}from"./runs.js";import{closeWarmPools as Sn,warmStatus as kn}from"./warm.js";import{SESSION_AGENTS as ke,listSessions as Tn,readSession as vn,adoptSession as xn,catchUp as En}from"./agent-sessions.js";import{agentContext as An}from"./agent-context.js";import{normalizeThread as Te}from"./events/agent-thread.js";import{portClashPlan as On,serviceManagerOf as Cn,STANDBY_POLL_MS as Pn}from"./events/service-standby.js";import{holdThread as ve}from"./threads.js";import{oneReply as $n}from"./one-reply.js";import{createSnapshot as Rn}from"./health-snapshot.js";import{CompatError as P,anthropicError as V,anthropicStream as In,chatCompletionStream as Nn,completionStream as Dn,createAnthropicMessage as _n,createChatCompletion as Hn,createCompletion as Mn,createResponse as Bn,openAIError as S,parseAnthropicMessage as Gn,parseChatCompletion as Un,parseCompletion as Ln,parseResponse as Wn,responseStream as jn}from"./api-compat.js";import{callerTrust as Fn,isPaired as I,parseExtensionIds as Jn,capRunOptions as Xn,engineHonoursReach as Kn,createPairingStore as zn,formatPairingCode as Yn}from"./pii/trust.js";const y="0.51.1",v=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",k=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,x={claude:{engine:ze,label:"Claude Code"},codex:{engine:Ye,label:"Codex"},antigravity:{engine:Ve,label:"Antigravity",tools:!1},pi:{engine:Qe,label:"Pi"},opencode:{engine:Ze,label:"OpenCode"},hermes:{engine:nt,label:"Hermes"},kiro:{engine:qe,label:"Kiro"},copilot:{engine:et,label:"GitHub Copilot"},deepseek:{engine:tt,label:"DeepSeek Harness"},custom:{engine:st,label:"Custom",hidden:!0}};function xe(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Vn=Jn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Fn({origin:n.headers.origin||"",hasToken:Ce(n),extensionIds:Vn})),n.chatpanelTrust}function Qn(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Zn(n,e){const t=n.headers.origin||"",r=xe(t);e.setHeader("Access-Control-Allow-Origin",r?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const Q=new Set(["127.0.0.1","localhost","::1"]);function qn(n){if(!Q.has(v))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return Q.has(t)}const D=M(O.homedir(),".chatpanel","bridge-token");let E="";function eo(){try{Ke(D)&&(E=ae(D,"utf8").trim()),E||(E=We(32).toString("hex"),Je(M(O.homedir(),".chatpanel"),{recursive:!0}),Xe(D,E,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const Ee=zn({random:()=>je(0,1e6)/1e6});function to(n){if(!E)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=Ee.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function no(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=Ee.claim(t?.code);return r.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:E})):(u("info",`pairing refused (${r.reason}) from ${N(n)} caller`),i(e,403,{error:r.reason}))}function oo(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:y})}let B=null;async function Ae(){if(B)return B;const{createChannelService:n}=await import("./channels/service.js");return B=n({home:M(O.homedir(),".chatpanel"),dataDir:M(O.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${k}`,token:E},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),B}async function Oe(n,e,t){try{const r=await Ae(),o=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await r.status());if(t==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await r.pair()):t==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?i(e,200,await r.update(o)):t==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function Ce(n){if(!E)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const r=Buffer.from(t),o=Buffer.from(E);return r.length===o.length&&Fe(r,o)}const ro=new Set(["/agent-context","/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),ao=new Set(["/debug"]),io=n=>ao.has(n),so=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function co(n,e){if(!qn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!xe(t))return"forbidden origin";const r=n.method==="POST"&&ro.has(e)||n.method==="GET"&&io(e)||so(n.method,e);return r&&!(Qn(t)||Ce(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I(N(n))&&!uo.has(e)?lo:null}const Pe=()=>we()?"chatpanel-gateway pair":"chatpanel-bridge pair",lo=`forbidden: this client is not paired with the bridge — run \`${Pe()}\` and enter the code in ChatPanel Settings`,uo=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function Z(n,e,t){const r=N(n),o=Bt(e,Gt(Xn(t,r)));if(!Kn(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":`pair this client (${Pe()})`} to use ${e}`};const a=o.reach,c=I(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:o,note:c}}async function $e(n,e,t){const r=e?.message||String(e);try{const o=await z().status(),a=!!(o.enabled&&o.runtime)&&t?.outside!==!0,c=Xt(`${r}
2
+ import{createServer as Le}from"node:http";import O from"node:os";import{randomBytes as We,randomInt as je,timingSafeEqual as Fe}from"node:crypto";import{mkdirSync as Je,writeFileSync as Xe,readFileSync as ae,existsSync as Ke}from"node:fs";import{join as M}from"node:path";import*as ze from"./engines/claude.js";import*as Ye from"./engines/codex.js";import*as Ve from"./engines/antigravity.js";import{pi as Qe,opencode as Ze,kiro as qe,copilot as et,deepseek as tt,hermes as nt}from"./engines/cli-agents.js";import{connectorsFor as ot}from"./connectors.js";import{agentServersFor as rt,resolveAgentServer as ie,builtinRefusal as at,narrowBuiltinList as it}from"./agent-mcp.js";import*as st from"./engines/custom.js";import{installService as ct,uninstallService as lt,serviceStatus as dt,restartService as se}from"./service.js";import{skillIndex as J,listRecords as ut,readRecord as ht,readPackageFile as pt,skillsHealth as ft,quarantinedSkills as mt,clearSkillCache as X,preferredIndex as K}from"./skills.js";import{writeSkillPackage as gt,writeSkillFile as wt,deleteSkillPackage as yt,SkillWriteError as bt}from"./skill-write.js";import{agentDefRoots as St,scanAgentDefs as kt,listAgentDefs as Tt,readAgentDef as vt,planAgentExport as xt,exportAgentDef as Et,agentDefsHealth as At,AgentDefError as Ot}from"./agent-defs.js";import{capabilityToolSpecs as Ct,runCapabilityTool as Pt}from"./mcp-capabilities.js";import{createSession as $t,deleteSession as ce,getSession as le,activeSession as Rt,relayToolCall as It}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Nt,isDefaultWorkdir as Dt,resolveWorkdir as _t,writeScopeNote as Ht}from"./workdir.js";import{sandbox as z,runSandboxCli as Mt,withGrant as de,withAgentGrant as Bt,withoutOutsideWhenCapped as Gt,grantedWriteRoots as ue,acceptRefusalReport as Ut,liveProcesses as Lt,sandboxConfigFromEnv as Wt}from"./sandbox.js";import{createAccessGate as jt,chatKeyOf as Ft,chatFolders as Jt}from"./access-gate.js";import{signInDenial as Xt}from"./events/sandbox-policy.js";import{gitState as Kt,gitDelta as zt}from"./scm.js";import{listConnections as Yt,putConnection as Vt,removeConnection as Qt,runEnvFor as Zt,testConnection as qt,secretBackend as he}from"./connections.js";import{worktreeFor as pe,listWorktrees as en,removeWorktree as tn,withHook as nn,WORKTREE_ROOT as fe}from"./worktree.js";import{AGENT_CLIS as on,agentAvailable as rn,agentInstallDirs as an,enrichPath as sn,enrichAgentEnv as cn,findAgentBin as ln,forgetMisses as dn,primeAgentLookups as un,resolveCommand as me,isCompiledBinary as hn}from"./env.js";import"./sanitize.js";import{checkForUpdate as pn,selfUpdate as ge,isEmbedded as we}from"./update.js";import{callLocalMcp as fn,localMcpStatus as mn,signInLocalMcp as gn,signInStatusLocalMcp as wn}from"./mcp-local.js";import{assertPublicHttpUrl as ye,assertPublicWebUrl as be}from"./ssrf.js";import{startRun as Se,endRun as Y,cancelRun as yn,cancelAll as bn}from"./runs.js";import{closeWarmPools as Sn,warmStatus as kn}from"./warm.js";import{SESSION_AGENTS as ke,listSessions as Tn,readSession as vn,adoptSession as xn,catchUp as En}from"./agent-sessions.js";import{agentContext as An}from"./agent-context.js";import{normalizeThread as Te}from"./events/agent-thread.js";import{portClashPlan as On,serviceManagerOf as Cn,STANDBY_POLL_MS as Pn}from"./events/service-standby.js";import{holdThread as ve}from"./threads.js";import{oneReply as $n}from"./one-reply.js";import{createSnapshot as Rn}from"./health-snapshot.js";import{CompatError as P,anthropicError as V,anthropicStream as In,chatCompletionStream as Nn,completionStream as Dn,createAnthropicMessage as _n,createChatCompletion as Hn,createCompletion as Mn,createResponse as Bn,openAIError as S,parseAnthropicMessage as Gn,parseChatCompletion as Un,parseCompletion as Ln,parseResponse as Wn,responseStream as jn}from"./api-compat.js";import{callerTrust as Fn,isPaired as I,parseExtensionIds as Jn,capRunOptions as Xn,engineHonoursReach as Kn,createPairingStore as zn,formatPairingCode as Yn}from"./pii/trust.js";const y="0.53.0",v=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",k=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,x={claude:{engine:ze,label:"Claude Code"},codex:{engine:Ye,label:"Codex"},antigravity:{engine:Ve,label:"Antigravity",tools:!1},pi:{engine:Qe,label:"Pi"},opencode:{engine:Ze,label:"OpenCode"},hermes:{engine:nt,label:"Hermes"},kiro:{engine:qe,label:"Kiro"},copilot:{engine:et,label:"GitHub Copilot"},deepseek:{engine:tt,label:"DeepSeek Harness"},custom:{engine:st,label:"Custom",hidden:!0}};function xe(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Vn=Jn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Fn({origin:n.headers.origin||"",hasToken:Ce(n),extensionIds:Vn})),n.chatpanelTrust}function Qn(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Zn(n,e){const t=n.headers.origin||"",r=xe(t);e.setHeader("Access-Control-Allow-Origin",r?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const Q=new Set(["127.0.0.1","localhost","::1"]);function qn(n){if(!Q.has(v))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return Q.has(t)}const D=M(O.homedir(),".chatpanel","bridge-token");let E="";function eo(){try{Ke(D)&&(E=ae(D,"utf8").trim()),E||(E=We(32).toString("hex"),Je(M(O.homedir(),".chatpanel"),{recursive:!0}),Xe(D,E,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const Ee=zn({random:()=>je(0,1e6)/1e6});function to(n){if(!E)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=Ee.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function no(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=Ee.claim(t?.code);return r.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:E})):(u("info",`pairing refused (${r.reason}) from ${N(n)} caller`),i(e,403,{error:r.reason}))}function oo(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:y})}let B=null;async function Ae(){if(B)return B;const{createChannelService:n}=await import("./channels/service.js");return B=n({home:M(O.homedir(),".chatpanel"),dataDir:M(O.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${k}`,token:E},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),B}async function Oe(n,e,t){try{const r=await Ae(),o=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await r.status());if(t==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await r.pair()):t==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?i(e,200,await r.update(o)):t==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function Ce(n){if(!E)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const r=Buffer.from(t),o=Buffer.from(E);return r.length===o.length&&Fe(r,o)}const ro=new Set(["/agent-context","/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),ao=new Set(["/debug"]),io=n=>ao.has(n),so=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function co(n,e){if(!qn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!xe(t))return"forbidden origin";const r=n.method==="POST"&&ro.has(e)||n.method==="GET"&&io(e)||so(n.method,e);return r&&!(Qn(t)||Ce(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I(N(n))&&!uo.has(e)?lo:null}const Pe=()=>we()?"chatpanel-gateway pair":"chatpanel-bridge pair",lo=`forbidden: this client is not paired with the bridge — run \`${Pe()}\` and enter the code in ChatPanel Settings`,uo=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function Z(n,e,t){const r=N(n),o=Bt(e,Gt(Xn(t,r)));if(!Kn(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":`pair this client (${Pe()})`} to use ${e}`};const a=o.reach,c=I(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:o,note:c}}async function $e(n,e,t){const r=e?.message||String(e);try{const o=await z().status(),a=!!(o.enabled&&o.runtime)&&t?.outside!==!0,c=Xt(`${r}
3
3
  ${e?.detail||""}`,{grant:t,sandboxed:a,agent:n,agentLabel:x[n]?.label||n||"This agent"});if(c)return c.line}catch{}return r}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function m(n){return new Promise((e,t)=>{let r="";n.on("data",o=>{r+=o,r.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){t(o)}}),n.on("error",t)})}const Re=Rn({compute:ho});async function ho(){await un();const n=await Promise.all(Object.entries(x).filter(([,a])=>!a.hidden).map(async([a,{engine:c,label:l,tools:s}])=>{const d=await c.available().catch(f=>({ok:!1,reason:String(f?.message||f)})),p=await ot(a).catch(()=>[]),w=await rt(a,{available:d.ok}).catch(()=>[]);return{id:a,label:l,available:d.ok,reason:d.reason,connectors:p,...w.length?{mcpServers:w}:{},...s===!1?{tools:!1}:{}}})),e=we()?{current:y,updateAvailable:!1,embedded:"gateway"}:await pn(y).catch(()=>({current:y,updateAvailable:!1})),t=await ft().catch(()=>null),r=await At().catch(()=>null),o=await z().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:r,sandboxStatus:o}}async function po(n,{fresh:e=!1}={}){e&&dn();const{at:t,value:{agents:r,update:o,skills:a,agentDefs:c,sandboxStatus:l}}=await Re.get({fresh:e});i(n,200,{ok:!0,version:y,agents:r,update:o,checkedAt:t,workspace:Nt,sandbox:l,localMcp:mn(),processes:Lt(),worktrees:fe,secretBackend:he(),warm:kn(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...a?{skills:a}:{},...c?{agentDefs:c}:{}})}async function fo(n,e,t,r={}){const o=await J({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:ut(K(o,r)),problems:o.problems})}async function mo(n,e,t){i(n,200,{ok:!0,quarantined:await mt(e,t)})}async function go(n,e,t,r,o={}){const a=ht(K(await J({extraDirs:t,workdir:r}),o),e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function wo(n,e,t,r,o,a={}){const c=await pt(K(await J({extraDirs:r,workdir:o}),a),e,t);if(c.error)return i(n,c.error==="unknown skill"?404:400,{ok:!1,error:c.error});i(n,200,{ok:!0,...c})}async function yo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}try{const r=await gt({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return X(),i(e,200,r)}catch(r){return i(e,q(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function bo(n,e,t,r){let o;try{o=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}try{const a=await wt({name:t,path:r,text:o?.text??""});return X(),i(e,200,a)}catch(a){return i(e,q(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function So(n,e){try{const t=await yt({name:e});return X(),i(n,200,t)}catch(t){return i(n,q(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function q(n){return n instanceof bt?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Ie(n,e){return kt({roots:St(process.env,O.homedir(),n,e)})}async function ko(n,e,t){const{index:r,quarantined:o,problems:a}=await Ie(e,t);i(n,200,{ok:!0,agents:Tt(r),...o.length?{quarantined:o.map(c=>({id:c.agent.id,path:c.relPath,source:c.source,verdict:c.scan.verdict}))}:{},...a.length?{problems:a}:{}})}async function To(n,e,t,r){const{index:o}=await Ie(t,r),a=vt(o,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function vo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}try{return i(e,200,{ok:!0,...await xt({agent:t?.agent,to:t?.to})})}catch(r){return i(e,Ne(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function xo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}try{return i(e,200,await Et({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(r){return i(e,Ne(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}function Ne(n){if(n instanceof Ot){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function Eo(){return(await Promise.all(Object.entries(x).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function De(n,e=""){const t=await Eo();if(e){const r=t.find(o=>o.id===e);return r?i(n,200,r):i(n,404,S(new P(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function Ao(n){try{const e=await ge(y);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>se(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function Oo(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const r=x[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=Z(n,t.agent,t.options||{});if(o.error)return i(e,403,{error:o.error});t.options=o.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
4
4
 
5
5
  `)};let c=!1;const l=`run_${Math.random().toString(36).slice(2,10)}`,s=Se(l),d={signal:s.signal,abort:()=>s.cancel("client")},p=()=>{c=!0,s.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const w=h=>{c||a(h)};a({type:"run",id:l}),o.note&&a({type:"status",text:o.note});let f=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(f=await pe({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),Y(l),e.writableEnded||e.end();return}}const _=f?f.path:_t(t.options?.workingDir),W=Ft(t.agent,t.options),te=W?Jt(W):[];te.length&&(t.options={...t.options,sandbox:{...t.options.sandbox||{},write:[...new Set([...Array.isArray(t.options.sandbox?.write)?t.options.sandbox.write:[],...te])]}});let C=null;{const h=_,T=!!f||!Dt(t.options?.workingDir),g=Ht(t.agent,t.options?.permissionMode,h,ue(h,{grant:t.options?.sandbox}));a({type:"workdir",path:h,isDefault:!T,writeScope:g||void 0}),a({type:"status",text:`Working in ${h}${T?"":" (default)"}`}),g&&a({type:"status",text:g}),C=await Kt(h),C&&a({type:"scm",phase:"before",...C})}let j=null;if(C||f){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:T,connection:g}=Zt({remote:C?.remote||null,grants:h,branch:f?.branch||null,connectionId:t.options?.connectionId||null});j=nn(T),f&&a({type:"workspace",path:f.path,branch:f.branch,base:f.base,created:f.created,repo:f.repo,...g?{connection:g}:{}}),g&&a({type:"status",text:`Git credential: ${g.kind} · ${g.host}${g.hasSecret?"":" (no token stored)"} · push: ${T.CHATPANEL_SCM_PUSH==="own"?`${f?.branch} only`:T.CHATPANEL_SCM_PUSH}`})}const F=t.approvals===!0,b={...t.options||{},...f?{workingDir:f.path}:{},...j?{runEnv:j}:{},approvals:F};let R=null;(t.pageTools?.specs?.length||F)&&(R=$t(w,t.pageTools?.specs||[]),b.permissionSession=R,t.pageTools?.specs?.length&&(b.mcp={url:`http://${v}:${k}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));const Ge=Wt();let ne=b.sandbox||null;F&&Ge.enabled&&(process.env.CHATPANEL_SANDBOX_RUNTIME||"srt")==="srt"&&b.sandbox?.outside!==!0&&(b.accessGate=jt({agent:t.agent,label:x[t.agent]?.label||t.agent,key:W,cwd:_,roots:()=>ue(_,{grant:ne})}));try{const h=$n(w),T=(g,H)=>de(g.sandbox,()=>r.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:H,options:g,images:Array.isArray(t.images)?t.images:[]},h.emit,{signal:d.signal}));await ve(t.agent,b,d.signal,async()=>{await T(b,t.system||"");let g=b;for(let H=0;H<2&&b.accessGate?.restart().length&&!d.signal.aborted;H++){const oe=b.accessGate.take();g={...g,sandbox:{...g.sandbox||{},write:[...new Set([...Array.isArray(g.sandbox?.write)?g.sandbox.write:[],...oe])]}},ne=g.sandbox;const re=oe.map(Ue=>b.accessGate.short(Ue)).join(", ");h.seam(),w({type:"status",text:`Restarted with write access to ${re} — carrying on`}),await T(g,`${t.system||""}