@chatpanel/bridge 0.52.0 → 0.53.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/scripts/sync-channels.mjs +2 -2
- package/scripts/sync-events.mjs +1 -1
- package/src/channels/adapters/telegram.js +5 -3
- package/src/channels/personal.js +8 -0
- package/src/channels/service.js +1 -1
- package/src/events/agent-permission.js +2 -2
- package/src/events/context-api.js +6 -0
- package/src/events/context-breakdown.js +4 -4
- package/src/events/event.js +1 -1
- package/src/events/extract-capability.js +5 -0
- package/src/events/kb-capability.js +1 -0
- package/src/events/mentions.js +3 -0
- package/src/events/rrf.js +1 -0
- package/src/events/sources-retrieval.js +10 -0
- package/src/origins.js +1 -0
- package/src/server.js +7 -7
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.53.1",
|
|
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
|
|
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,
|
|
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 ✓"));
|
package/scripts/sync-events.mjs
CHANGED
|
@@ -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
|
|
2
|
-
`);function
|
|
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
|
|
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};
|
package/src/channels/service.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
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,2 +1,2 @@
|
|
|
1
|
-
const T="permission_request",
|
|
2
|
-
`);let
|
|
1
|
+
const T="permission_request",h=Object.freeze({ALLOW:"allow",ALLOW_CHAT:"allow_chat",DENY:"deny"}),k=600*1e3,L="permission_prompt";function N(){return{name:L,description:"Chap-internal: the person answers the agent's permission prompt. Not for the model.",parameters:{type:"object",properties:{tool:{type:"string"},input:{type:"object"},description:{type:"string"},path:{type:"string"},rules:{type:"array"}}}}}const C=t=>t===L,c=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),a=t=>typeof t=="string"?t:t==null?"":String(t);function P(t={}){const e=c(t)?t:{},o=a(e.tool_name||e.toolName||e.tool),n=[];for(const s of Array.isArray(e.permission_suggestions)?e.permission_suggestions:[])if(!(!c(s)||s.type!=="addRules"||s.behavior==="deny"))for(const r of Array.isArray(s.rules)?s.rules:[]){if(!c(r))continue;const p=a(r.toolName||o),l=a(r.ruleContent);p&&!n.some(u=>u.tool===p&&u.content===l)&&n.push({tool:p,content:l})}return{tool:o,displayName:a(e.display_name||e.displayName)||o,input:c(e.input)?e.input:{},description:a(e.description),path:a(e.blocked_path||e.path)||null,rules:n,toolUseId:a(e.tool_use_id||e.toolUseId)||null}}function A(t={}){const e=Array.isArray(t.rules)?t.rules.filter(o=>o&&o.tool):[];return e.length?e.map(o=>o.content?`${o.tool}(${o.content})`:o.tool):t.tool?[String(t.tool)]:[]}function S(t={}){const e=a(t.tool),o=c(t.input)?t.input:{},n=(i,m=240)=>i.length>m?`${i.slice(0,m-1)}…`:i;let s,r;if(e==="Bash")s="Run a command",r=n(a(o.command).trim()||a(t.description)||"a shell command");else if(e==="Edit"||e==="MultiEdit"||e==="NotebookEdit")s="Edit a file",r=a(o.file_path||o.notebook_path||t.path)||"a file";else if(e==="Write"){s="Write a file";const i=a(o.file_path||t.path)||"a file",m=a(o.content).length;r=m?`${i} (${m.toLocaleString()} chars)`:i}else if(/^mcp__/.test(e))s="Use a connected server",r=e.replace(/^mcp__/,"").replace(/__/," › ");else{s=`Use ${t.displayName||e||"a tool"}`;let i="";try{i=JSON.stringify(o)}catch{i=""}r=a(t.description)||(i&&i!=="{}"?n(i,200):e)}const p=A(t),l=Array.isArray(t.rules)?t.rules.filter(i=>i?.content):[],u=l.length&&l.some(i=>i.content!==r)?l.map(i=>i.content).join(", "):p.length&&!l.length?`every ${e} call`:null,f=c(t.access)?a(t.access.folder):"",d=f?`This works in ${f}, outside the folders it may change. Allowing it opens ${f} to it for the rest of this chat.`:null;return{title:s,detail:r,scope:u,description:a(t.description)||null,access:d}}function y(t,e=""){return t===h.ALLOW?{behavior:"allow",scope:"once"}:t===h.ALLOW_CHAT?{behavior:"allow",scope:"chat"}:{behavior:"deny",scope:"once",...e?{message:String(e)}:{}}}function _(t){return c(t)&&t.behavior==="allow"}function E(t,e){const o=new Set(Array.isArray(t)?t:[]);for(const n of A(e))o.add(n);return[...o].sort()}const b="*";function O(t,e){const o=new Set(Array.isArray(t)?t:[]);if(o.has(b))return y(h.ALLOW);const n=A(e);return n.length&&n.every(s=>o.has(s))?y(h.ALLOW):null}function R(t,e,o={}){const n=c(o)?o:{},s=_(e);let r;if(s){if(r={behavior:"allow",updatedInput:c(n.input)?n.input:{}},e.scope==="chat"){const p=(Array.isArray(n.permission_suggestions)?n.permission_suggestions:[]).filter(l=>c(l)&&l.type==="addRules"&&l.behavior!=="deny"&&Array.isArray(l.rules)&&l.rules.length).map(l=>({type:"addRules",rules:l.rules,behavior:"allow",destination:"session"}));p.length&&(r.updatedPermissions=p)}}else r={behavior:"deny",message:a(e?.message)||"The user declined this action in Chap. Continue without it, or explain what it was for and ask."};return{type:"control_response",response:{subtype:"success",request_id:String(t),response:r}}}function I(t,e){const{detail:o}=S(t),n=_(e),s=n&&e.scope==="chat"?" for this chat":"";return`${n?"Allowed":"Declined"}${s}: ${o}`}function $(t){return t==="Bash"?"code":/^(Edit|MultiEdit|NotebookEdit)$/.test(String(t))?"pencil":t==="Write"?"file":/^mcp__/.test(String(t))?"plug":"bot"}const W=4e5;function M(t={},e=null){if(!_(e)||!c(t))return null;const o=c(t.input)?t.input:{};if(!["Write","Create","write_file"].includes(String(t.tool||"")))return null;const n=String(o.file_path||o.path||""),s=typeof o.content=="string"?o.content:"";return!/\.svg$/i.test(n)||!/<svg[\s>]/i.test(s)||s.length>W?null:{kind:"svg",title:n.split(/[\\/]/).pop()||"picture.svg",text:s}}function v({memory:t=new Map}={}){const e=t;async function o(n,{convId:s=null,confirm:r,agentName:p="The agent"}={}){const l=c(n.access)?null:O(await e.get(s)||[],n);if(l)return l;const{title:u,detail:f,scope:d,description:i,access:m}=S(n),x=[m,f,i&&i!==f?i:"",d?`“Allow for this chat” also covers: ${d}`:""].filter(Boolean).join(`
|
|
2
|
+
`);let g;try{if(typeof r!="function")throw new Error("no card");g=await r(x,{title:`${p} asks — ${u.toLowerCase()}?`,iconName:$(n.tool),scopeLabel:"Allow for this chat",allLabel:"Allow all in this chat"})}catch(w){return y(h.DENY,`Chap could not show the permission card (${w?.message||w}).`)}return g==="all"?(await e.set(s,[b]),y(h.ALLOW_CHAT)):g==="site"||g==="always"?(await e.set(s,E(await e.get(s)||[],n)),y(h.ALLOW_CHAT)):y(g==="allow"?h.ALLOW:h.DENY)}return{ask:o,forget(n){e.delete(n)},standing(n){return e.get(n)||[]},provider({convId:n=null,confirm:s,agentName:r="The agent",onAnswered:p=null}={}){return{id:"permission",specs:[N()],execute:async(l,u)=>{const f=u&&typeof u=="object"?u:{},d=await o(f,{convId:n,confirm:s,agentName:r});try{p?.(f,d)}catch{}return JSON.stringify(d)}}}}}export{b as ALLOW_ALL,W as MAX_SHOWN_PICTURE,h as PERMISSION_ANSWERS,T as PERMISSION_EVENT,k as PERMISSION_TIMEOUT_MS,L as PERMISSION_TOOL_NAME,R as claudePermissionResponse,v as createPermissionDesk,S as describePermission,C as isPermissionTool,_ as permissionAllowed,y as permissionAnswer,$ as permissionIcon,A as permissionKeys,I as permissionLine,P as permissionRequestFromClaude,N as permissionToolSpec,M as pictureFromPermission,O as recallPermission,E as rememberPermission};
|
|
@@ -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),
|
|
2
|
-
`):"",
|
|
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(
|
|
5
|
-
`)){const
|
|
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};
|
package/src/events/event.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isRef as o}from"./ref.js";const
|
|
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/origins.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d{1,5})?$/,e=/^(chrome|moz)-extension:\/\/[A-Za-z0-9-]+$/;function r(t){const n=String(t||"");return e.test(n)||o.test(n)}function s(t){return!t||r(t)}export{r as isExtensionOrigin,s as originAllowed};
|
package/src/server.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
${e?.detail||""}`,{grant:t,sandboxed:a,agent:n,agentLabel:
|
|
2
|
+
import{originAllowed as ae,isExtensionOrigin as Le}from"./origins.js";import{createServer as We}from"node:http";import O from"node:os";import{randomBytes as je,randomInt as Fe,timingSafeEqual as Je}from"node:crypto";import{mkdirSync as Xe,writeFileSync as Ke,readFileSync as ie,existsSync as Ye}from"node:fs";import{join as M}from"node:path";import*as ze from"./engines/claude.js";import*as Ve from"./engines/codex.js";import*as Qe from"./engines/antigravity.js";import{pi as Ze,opencode as qe,kiro as et,copilot as tt,deepseek as nt,hermes as ot}from"./engines/cli-agents.js";import{connectorsFor as rt}from"./connectors.js";import{agentServersFor as at,resolveAgentServer as se,builtinRefusal as it,narrowBuiltinList as st}from"./agent-mcp.js";import*as ct from"./engines/custom.js";import{installService as lt,uninstallService as dt,serviceStatus as ut,restartService as ce}from"./service.js";import{skillIndex as J,listRecords as ht,readRecord as pt,readPackageFile as ft,skillsHealth as mt,quarantinedSkills as gt,clearSkillCache as X,preferredIndex as K}from"./skills.js";import{writeSkillPackage as wt,writeSkillFile as yt,deleteSkillPackage as bt,SkillWriteError as St}from"./skill-write.js";import{agentDefRoots as kt,scanAgentDefs as Tt,listAgentDefs as vt,readAgentDef as Et,planAgentExport as xt,exportAgentDef as At,agentDefsHealth as Ot,AgentDefError as Ct}from"./agent-defs.js";import{capabilityToolSpecs as Pt,runCapabilityTool as $t}from"./mcp-capabilities.js";import{createSession as Rt,deleteSession as le,getSession as de,activeSession as It,relayToolCall as Nt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Dt,isDefaultWorkdir as _t,resolveWorkdir as Ht,writeScopeNote as Mt}from"./workdir.js";import{sandbox as Y,runSandboxCli as Bt,withGrant as ue,withAgentGrant as Gt,withoutOutsideWhenCapped as Ut,grantedWriteRoots as he,acceptRefusalReport as Lt,liveProcesses as Wt,sandboxConfigFromEnv as jt}from"./sandbox.js";import{createAccessGate as Ft,chatKeyOf as Jt,chatFolders as Xt}from"./access-gate.js";import{signInDenial as Kt}from"./events/sandbox-policy.js";import{gitState as Yt,gitDelta as zt}from"./scm.js";import{listConnections as Vt,putConnection as Qt,removeConnection as Zt,runEnvFor as qt,testConnection as en,secretBackend as pe}from"./connections.js";import{worktreeFor as fe,listWorktrees as tn,removeWorktree as nn,withHook as on,WORKTREE_ROOT as me}from"./worktree.js";import{AGENT_CLIS as rn,agentAvailable as an,agentInstallDirs as sn,enrichPath as cn,enrichAgentEnv as ln,findAgentBin as dn,forgetMisses as un,primeAgentLookups as hn,resolveCommand as ge,isCompiledBinary as pn}from"./env.js";import"./sanitize.js";import{checkForUpdate as fn,selfUpdate as we,isEmbedded as ye}from"./update.js";import{callLocalMcp as mn,localMcpStatus as gn,signInLocalMcp as wn,signInStatusLocalMcp as yn}from"./mcp-local.js";import{assertPublicHttpUrl as be,assertPublicWebUrl as Se}from"./ssrf.js";import{startRun as ke,endRun as z,cancelRun as bn,cancelAll as Sn}from"./runs.js";import{closeWarmPools as kn,warmStatus as Tn}from"./warm.js";import{SESSION_AGENTS as Te,listSessions as vn,readSession as En,adoptSession as xn,catchUp as An}from"./agent-sessions.js";import{agentContext as On}from"./agent-context.js";import{normalizeThread as ve}from"./events/agent-thread.js";import{portClashPlan as Cn,serviceManagerOf as Pn,STANDBY_POLL_MS as $n}from"./events/service-standby.js";import{holdThread as Ee}from"./threads.js";import{oneReply as Rn}from"./one-reply.js";import{createSnapshot as In}from"./health-snapshot.js";import{CompatError as P,anthropicError as V,anthropicStream as Nn,chatCompletionStream as Dn,completionStream as _n,createAnthropicMessage as Hn,createChatCompletion as Mn,createCompletion as Bn,createResponse as Gn,openAIError as S,parseAnthropicMessage as Un,parseChatCompletion as Ln,parseCompletion as Wn,parseResponse as jn,responseStream as Fn}from"./api-compat.js";import{callerTrust as Jn,isPaired as I,parseExtensionIds as Xn,capRunOptions as Kn,engineHonoursReach as Yn,createPairingStore as zn,formatPairingCode as Vn}from"./pii/trust.js";const y="0.53.1",v=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",k=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,E={claude:{engine:ze,label:"Claude Code"},codex:{engine:Ve,label:"Codex"},antigravity:{engine:Qe,label:"Antigravity",tools:!1},pi:{engine:Ze,label:"Pi"},opencode:{engine:qe,label:"OpenCode"},hermes:{engine:ot,label:"Hermes"},kiro:{engine:et,label:"Kiro"},copilot:{engine:tt,label:"GitHub Copilot"},deepseek:{engine:nt,label:"DeepSeek Harness"},custom:{engine:ct,label:"Custom",hidden:!0}},Qn=Xn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Jn({origin:n.headers.origin||"",hasToken:Ce(n),extensionIds:Qn})),n.chatpanelTrust}function Zn(n,e){const t=n.headers.origin||"",r=ae(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 x="";function eo(){try{Ye(D)&&(x=ie(D,"utf8").trim()),x||(x=je(32).toString("hex"),Xe(M(O.homedir(),".chatpanel"),{recursive:!0}),Ke(D,x,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const xe=zn({random:()=>Fe(0,1e6)/1e6});function to(n){if(!x)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=xe.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=xe.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:x})):(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:x},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(!x)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(x);return r.length===o.length&&Je(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&&!ae(t))return"forbidden origin";const r=n.method==="POST"&&ro.has(e)||n.method==="GET"&&io(e)||so(n.method,e);return r&&!(Le(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=()=>ye()?"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=Gt(e,Ut(Kn(t,r)));if(!Yn(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 Y().status(),a=!!(o.enabled&&o.runtime)&&t?.outside!==!0,c=Kt(`${r}
|
|
3
|
+
${e?.detail||""}`,{grant:t,sandboxed:a,agent:n,agentLabel:E[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=In({compute:ho});async function ho(){await hn();const n=await Promise.all(Object.entries(E).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 rt(a).catch(()=>[]),w=await at(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=ye()?{current:y,updateAvailable:!1,embedded:"gateway"}:await fn(y).catch(()=>({current:y,updateAvailable:!1})),t=await mt().catch(()=>null),r=await Ot().catch(()=>null),o=await Y().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&&un();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:Dt,sandbox:l,localMcp:gn(),processes:Wt(),worktrees:me,secretBackend:pe(),warm:Tn(),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:ht(K(o,r)),problems:o.problems})}async function mo(n,e,t){i(n,200,{ok:!0,quarantined:await gt(e,t)})}async function go(n,e,t,r,o={}){const a=pt(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 ft(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 wt({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 yt({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 bt({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 St?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 Tt({roots:kt(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:vt(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=Et(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 Eo(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 At({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 Ct){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function xo(){return(await Promise.all(Object.entries(E).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 xo();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 we(y);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>ce(),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=E[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
|
-
`)};let c=!1;const l=`run_${Math.random().toString(36).slice(2,10)}`,s=
|
|
5
|
+
`)};let c=!1;const l=`run_${Math.random().toString(36).slice(2,10)}`,s=ke(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 fe({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),z(l),e.writableEnded||e.end();return}}const _=f?f.path:Ht(t.options?.workingDir),W=Jt(t.agent,t.options),te=W?Xt(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||!_t(t.options?.workingDir),g=Mt(t.agent,t.options?.permissionMode,h,he(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 Yt(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}=qt({remote:C?.remote||null,grants:h,branch:f?.branch||null,connectionId:t.options?.connectionId||null});j=on(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=Rt(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=jt();let ne=b.sandbox||null;F&&Ge.enabled&&(process.env.CHATPANEL_SANDBOX_RUNTIME||"srt")==="srt"&&b.sandbox?.outside!==!0&&(b.accessGate=Ft({agent:t.agent,label:E[t.agent]?.label||t.agent,key:W,cwd:_,roots:()=>he(_,{grant:ne})}));try{const h=Rn(w),T=(g,H)=>ue(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 Ee(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||""}
|
|
6
6
|
|
|
7
|
-
[ChatPanel] The person has just allowed writing in ${re}, and you were restarted with that access. Carry on with their request: do the step that was blocked. Do not ask again.`.trim())}h.finish()})}catch(h){u("error",`${t.agent} chat failed: ${h?.message||h}`),h?.detail&&u("error",`${t.agent} said: ${h.detail}`),a({type:"error",error:await $e(t.agent,h,b.sandbox)})}finally{if(!c){const h=await zt(_,C).catch(()=>null);h&&w({type:"scm",phase:"after",...h})}
|
|
7
|
+
[ChatPanel] The person has just allowed writing in ${re}, and you were restarted with that access. Carry on with their request: do the step that was blocked. Do not ask again.`.trim())}h.finish()})}catch(h){u("error",`${t.agent} chat failed: ${h?.message||h}`),h?.detail&&u("error",`${t.agent} said: ${h.detail}`),a({type:"error",error:await $e(t.agent,h,b.sandbox)})}finally{if(!c){const h=await zt(_,C).catch(()=>null);h&&w({type:"scm",phase:"after",...h})}z(l),R&&le(R.id),e.writableEnded||e.end()}}async function Co(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:Vt(),secretBackend:pe()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await m(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:Qt(r.connection||r,{token:r.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return o?o[2]==="delete"?i(e,200,{ok:Zt(o[1])}):i(e,200,en(o[1],r.remote||"")):i(e,404,{error:"Not found"})}async function Po(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:me,worktrees:await tn()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await m(n);if(t==="/worktrees"){const o=await fe({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return i(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(t==="/worktrees/remove"){const o=await nn({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return i(e,o.ok?200:400,o)}return i(e,404,{error:"Not found"})}async function A(n,e,t){const r=E[n.agent];if(!r||r.hidden)throw new P(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const o=await r.engine.available().catch(d=>({ok:!1,reason:d?.message||String(d)}));if(!o.ok)throw new P(o.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,c=ke(a),l=()=>c.cancel("disconnected");t.on("close",l);let s="";try{return await ue(n.options?.sandbox,()=>Ee(n.agent,n.options,c.signal,()=>r.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},d=>{d?.type==="delta"&&d.text?(s+=d.text,e(d.text)):d?.type==="done"&&d.text&&!s&&(s=d.text,e(d.text))},{signal:c.signal}))),s}catch(d){throw d instanceof Error&&!(d instanceof P)&&(d.message=await $e(n.agent,d,n.options?.sandbox)),d}finally{t.off("close",l),z(a)}}function G(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function $(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
|
|
8
8
|
|
|
9
9
|
`)}function U(n,e,t){n.writableEnded||n.write(`event: ${e}
|
|
10
10
|
data: ${JSON.stringify(t)}
|
|
11
11
|
|
|
12
|
-
`)}async function L(n,e,t,r){try{const o=t(await m(n)),a=Z(n,o.agent,o.options||{});if(a.error)throw new P(a.error,403,"permission");return o.options=a.options,o}catch(o){return i(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${o.message}`):o)),null}}async function $o(n,e){const t=await L(n,e,Un,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Hn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=Nn(t.requestedModel,o=>$(e,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){$(e,S(o))}$(e,"[DONE]"),e.end()}async function Ro(n,e){const t=await L(n,e,Ln,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Mn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=Dn(t.requestedModel,o=>$(e,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){$(e,S(o))}$(e,"[DONE]"),e.end()}async function Io(n,e){const t=await L(n,e,Wn,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Bn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=jn(t.requestedModel,o=>U(e,o.type,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...S(o)};U(e,"error",a)}e.end()}async function No(n,e){const t=await L(n,e,Gn,V);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,_n(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,V(o))}G(e);const r=In(t.requestedModel,(o,a)=>U(e,o,a));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){U(e,"error",V(o))}e.end()}async function Do(n,e){let t={};try{t=await m(n)||{}}catch{}const r=String(t.id||"").trim(),o=r?yn(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function _e(n,e,t){let r;try{r=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=t?le(t):Rt(),a=s=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:s})},c=(s,d)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:s,message:d}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return a({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:y}});const l=Ct();if(r.method==="tools/list"){const s=o?o.specs.map(d=>({name:d.name,description:d.description,inputSchema:d.parameters||{type:"object",properties:{}}})):[];return a({tools:[...l,...s]})}if(r.method==="tools/call"){const s=await Pt(r.params?.name,r.params?.arguments||{});if(s)return a(s);if(!o)return c(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await It(o,r.params?.name,r.params?.arguments||{}))}catch(d){return a({content:[{type:"text",text:`error: ${d?.message||d}`}],isError:!0})}}return c(-32601,`Method not found: ${r.method}`)}async function _o(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=t.server||{},o=t.message;if(!r.command&&!r.from||!o)return i(e,400,{error:"need server.command (or server.from) and message"});try{let a;if(r.from){if(a=await ie(r),a.builtin&&o.method==="tools/call"){const l=await at(a.builtin,o);if(l)return i(e,200,{jsonrpc:"2.0",id:o.id??null,result:{content:[{type:"text",text:`Refused: ${l}`}],isError:!0}})}}else a={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};let c=await fn(a,o);return a.builtin&&o.method==="tools/list"&&(c=it(a.builtin,c)),o.id==null?(e.writeHead(202),e.end()):i(e,200,c)}catch(a){return i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function Ho(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t.server||{};if(!r.command&&!r.from)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});try{const o=r.from?await ie(r):{key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};return i(e,200,t.status?wn(o):await gn(o))}catch(o){return i(e,200,{state:"failed",error:String(o?.message||o)})}}async function Mo(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const{url:r,headers:o,message:a}=t||{};if(!r||!a)return i(e,400,{error:"need url and message"});let c;try{c=ye(r)}catch(p){return i(e,400,{error:String(p?.message||p)})}const l={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[p,w]of Object.entries(o)){const f=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(l[p]=String(w))}const s=new AbortController,d=setTimeout(()=>s.abort(),3e4);try{const p=await fetch(c.href,{method:"POST",headers:l,body:JSON.stringify(a),redirect:"follow",signal:s.signal});try{p.url&&ye(p.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const w=await p.text().catch(()=>"");return i(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",authenticate:p.headers.get("WWW-Authenticate")||"",body:w})}catch(p){const w=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${c.host}: ${w}`})}finally{clearTimeout(d)}}const He=256*1024,Bo=5,Go=8e3;async function Uo(n){let e=be(n);const t=new AbortController,r=setTimeout(()=>t.abort(),Go);try{for(let o=0;o<=Bo;o++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${y} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=be(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const c=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(c)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:jo(await Lo(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function Lo(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,He);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:c}=await e.read();if(a||(o+=c.byteLength,r+=t.decode(c,{stream:!0}),/<\/title\s*>/i.test(r)||o>=He))break}}finally{try{await e.cancel()}catch{}}return r}function Wo(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function jo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Wo(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Fo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t&&t.url;if(!r||typeof r!="string")return i(e,400,{error:"need url"});try{const o=await Uo(r);return i(e,200,{title:o.title||null,url:o.url||r})}catch(o){const a=o?.name==="AbortError"?"timed out":String(o?.message||o);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function Jo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=le(t.session);if(!r)return i(e,404,{error:"no such session"});const o=r.pending.get(t.id);return o?(r.pending.delete(t.id),o.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function Xo(n,e){let t;try{t=await m(n)}catch(s){return i(e,400,{error:"Bad JSON: "+s.message})}const r=x[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=String(t.prompt||"").slice(0,6e3);if(!o)return i(e,400,{error:"Empty prompt"});const a=t.model||"",c=Z(n,t.agent,{model:a});if(c.error)return i(e,403,{error:c.error});const l=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let s="";return typeof r.engine.complete=="function"?s=await r.engine.complete({prompt:o,system:l,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:l,options:c.options},d=>{d.type==="delta"?s+=d.text||"":d.type==="done"&&d.text&&(s+=d.text)}),i(e,200,{text:(s||"").trim()})}catch(s){return i(e,502,{error:s?.message||String(s)})}}async function Ko(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=x[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof r.engine.listModels!="function")return i(e,200,{models:[]});try{const o=await r.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return i(e,502,{error:o?.message||String(o)})}}async function zo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(t.command||"").trim();if(!r)return i(e,400,{error:"No command"});let o=null;try{o=me(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}async function Yo(n,e,t){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(r?.agent||"");if(!ke.includes(o))return i(e,404,{error:`${o||"that agent"} keeps no sessions Chap can read (it can: ${ke.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await Tn(o,{limit:r.limit})});if(t==="/agent-sessions/read"){const a=await vn(o,String(r.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${o} session ${String(r.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=Te({id:r.thread?.id??r.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const c=await xn(o,String(r.id||""),a.id);return c?i(e,200,{session:c}):i(e,404,{error:`no ${o} session ${String(r.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=Te({id:r.thread?.id??r.thread});return a?i(e,200,await En(o,a.id,Array.isArray(r.messages)?r.messages:[])):i(e,400,{error:"catchup needs the Chap conversation: { thread: { id } }"})}return i(e,404,{error:"Not found"})}catch(a){return i(e,a?.status||500,{error:a?.message||String(a)})}}const ee=Le(async(n,e)=>{if(Zn(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const r=co(n,t.pathname);if(r)return i(e,403,{error:r});try{if(n.method==="GET"&&t.pathname==="/health")return po(e,{fresh:t.searchParams.get("fresh")==="1"});const o=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"",c={agent:t.searchParams.get("agent")||"",source:t.searchParams.get("source")||""};if(n.method==="GET"&&t.pathname==="/skills")return fo(e,o,a,c);if(n.method==="POST"&&t.pathname==="/agent-context"){const l=await m(n).catch(()=>({})),s=l?.options&&typeof l.options=="object"?l.options:{},d={...s.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof s.permissionMode=="string"?{permissionMode:s.permissionMode}:{},...typeof s.workingDir=="string"&&s.workingDir?{workingDir:s.workingDir}:{},...typeof s.model=="string"&&s.model?{model:s.model}:{}};return i(e,200,await An({agent:typeof l?.agent=="string"?l.agent:"claude",options:d}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return mo(e,o,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return ko(e,o,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return vo(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return xo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return To(e,decodeURIComponent(t.pathname.slice(12)),o,a);if(n.method==="POST"&&t.pathname==="/skills")return yo(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const l=t.pathname.slice(8),s=l.indexOf("/file/");return s===-1?n.method==="DELETE"?So(e,decodeURIComponent(l)):i(e,405,{ok:!1,error:"use POST /skills to save a skill"}):n.method==="DELETE"?i(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):bo(n,e,decodeURIComponent(l.slice(0,s)),decodeURIComponent(l.slice(s+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const l=t.pathname.slice(8),s=l.indexOf("/file/");return s===-1?go(e,decodeURIComponent(l),o,a,c):wo(e,decodeURIComponent(l.slice(0,s)),decodeURIComponent(l.slice(s+6)),o,a,c)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return Co(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Po(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return De(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return De(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const l=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:y,agents:Object.fromEntries(on.map(s=>[s,l?ln(s)||me(s)?.kind||null:rn(s)])),...l?{home:O.homedir(),path:process.env.PATH,installDirs:an(O.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Yo(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return Oo(n,e);if(n.method==="POST"&&t.pathname==="/pair")return no(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return to(e);if(n.method==="POST"&&t.pathname==="/whoami")return oo(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return $o(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Ro(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return Io(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return No(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return _e(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const l=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return _e(n,e,l);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return ce(l),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return Oe(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return Oe(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Do(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Jo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let l=null;try{l=await m(n)}catch{l=null}const s=Ut(l||{});return e.writeHead(s?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return _o(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return Ho(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return Mo(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Fo(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Xo(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Ko(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return zo(n,e);if(n.method==="POST"&&t.pathname==="/update")return Ao(e);i(e,404,{error:"Not found"})}catch(o){i(e,500,{error:o?.message||String(o)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Vo(n){let e="";const t=[];let r=!1,o=!1;const a=()=>{o&&!r&&!t.length&&process.exit(0)},c=async()=>{if(!r){for(r=!0;t.length;){const l=t.shift();let s;try{s=JSON.parse(l)}catch{continue}try{const d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:l});if(s.id==null)continue;const p=(await d.text()).trim();p&&process.stdout.write(p+`
|
|
12
|
+
`)}async function L(n,e,t,r){try{const o=t(await m(n)),a=Z(n,o.agent,o.options||{});if(a.error)throw new P(a.error,403,"permission");return o.options=a.options,o}catch(o){return i(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${o.message}`):o)),null}}async function $o(n,e){const t=await L(n,e,Ln,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Mn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=Dn(t.requestedModel,o=>$(e,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){$(e,S(o))}$(e,"[DONE]"),e.end()}async function Ro(n,e){const t=await L(n,e,Wn,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Bn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=_n(t.requestedModel,o=>$(e,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){$(e,S(o))}$(e,"[DONE]"),e.end()}async function Io(n,e){const t=await L(n,e,jn,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Gn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=Fn(t.requestedModel,o=>U(e,o.type,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...S(o)};U(e,"error",a)}e.end()}async function No(n,e){const t=await L(n,e,Un,V);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Hn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,V(o))}G(e);const r=Nn(t.requestedModel,(o,a)=>U(e,o,a));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){U(e,"error",V(o))}e.end()}async function Do(n,e){let t={};try{t=await m(n)||{}}catch{}const r=String(t.id||"").trim(),o=r?bn(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function _e(n,e,t){let r;try{r=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=t?de(t):It(),a=s=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:s})},c=(s,d)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:s,message:d}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return a({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:y}});const l=Pt();if(r.method==="tools/list"){const s=o?o.specs.map(d=>({name:d.name,description:d.description,inputSchema:d.parameters||{type:"object",properties:{}}})):[];return a({tools:[...l,...s]})}if(r.method==="tools/call"){const s=await $t(r.params?.name,r.params?.arguments||{});if(s)return a(s);if(!o)return c(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await Nt(o,r.params?.name,r.params?.arguments||{}))}catch(d){return a({content:[{type:"text",text:`error: ${d?.message||d}`}],isError:!0})}}return c(-32601,`Method not found: ${r.method}`)}async function _o(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=t.server||{},o=t.message;if(!r.command&&!r.from||!o)return i(e,400,{error:"need server.command (or server.from) and message"});try{let a;if(r.from){if(a=await se(r),a.builtin&&o.method==="tools/call"){const l=await it(a.builtin,o);if(l)return i(e,200,{jsonrpc:"2.0",id:o.id??null,result:{content:[{type:"text",text:`Refused: ${l}`}],isError:!0}})}}else a={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};let c=await mn(a,o);return a.builtin&&o.method==="tools/list"&&(c=st(a.builtin,c)),o.id==null?(e.writeHead(202),e.end()):i(e,200,c)}catch(a){return i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function Ho(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t.server||{};if(!r.command&&!r.from)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});try{const o=r.from?await se(r):{key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};return i(e,200,t.status?yn(o):await wn(o))}catch(o){return i(e,200,{state:"failed",error:String(o?.message||o)})}}async function Mo(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const{url:r,headers:o,message:a}=t||{};if(!r||!a)return i(e,400,{error:"need url and message"});let c;try{c=be(r)}catch(p){return i(e,400,{error:String(p?.message||p)})}const l={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[p,w]of Object.entries(o)){const f=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(l[p]=String(w))}const s=new AbortController,d=setTimeout(()=>s.abort(),3e4);try{const p=await fetch(c.href,{method:"POST",headers:l,body:JSON.stringify(a),redirect:"follow",signal:s.signal});try{p.url&&be(p.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const w=await p.text().catch(()=>"");return i(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",authenticate:p.headers.get("WWW-Authenticate")||"",body:w})}catch(p){const w=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${c.host}: ${w}`})}finally{clearTimeout(d)}}const He=256*1024,Bo=5,Go=8e3;async function Uo(n){let e=Se(n);const t=new AbortController,r=setTimeout(()=>t.abort(),Go);try{for(let o=0;o<=Bo;o++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${y} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=Se(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const c=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(c)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:jo(await Lo(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function Lo(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,He);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:c}=await e.read();if(a||(o+=c.byteLength,r+=t.decode(c,{stream:!0}),/<\/title\s*>/i.test(r)||o>=He))break}}finally{try{await e.cancel()}catch{}}return r}function Wo(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function jo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Wo(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Fo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t&&t.url;if(!r||typeof r!="string")return i(e,400,{error:"need url"});try{const o=await Uo(r);return i(e,200,{title:o.title||null,url:o.url||r})}catch(o){const a=o?.name==="AbortError"?"timed out":String(o?.message||o);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function Jo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=de(t.session);if(!r)return i(e,404,{error:"no such session"});const o=r.pending.get(t.id);return o?(r.pending.delete(t.id),o.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function Xo(n,e){let t;try{t=await m(n)}catch(s){return i(e,400,{error:"Bad JSON: "+s.message})}const r=E[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=String(t.prompt||"").slice(0,6e3);if(!o)return i(e,400,{error:"Empty prompt"});const a=t.model||"",c=Z(n,t.agent,{model:a});if(c.error)return i(e,403,{error:c.error});const l=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let s="";return typeof r.engine.complete=="function"?s=await r.engine.complete({prompt:o,system:l,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:l,options:c.options},d=>{d.type==="delta"?s+=d.text||"":d.type==="done"&&d.text&&(s+=d.text)}),i(e,200,{text:(s||"").trim()})}catch(s){return i(e,502,{error:s?.message||String(s)})}}async function Ko(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=E[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof r.engine.listModels!="function")return i(e,200,{models:[]});try{const o=await r.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return i(e,502,{error:o?.message||String(o)})}}async function Yo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(t.command||"").trim();if(!r)return i(e,400,{error:"No command"});let o=null;try{o=ge(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}async function zo(n,e,t){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(r?.agent||"");if(!Te.includes(o))return i(e,404,{error:`${o||"that agent"} keeps no sessions Chap can read (it can: ${Te.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await vn(o,{limit:r.limit})});if(t==="/agent-sessions/read"){const a=await En(o,String(r.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${o} session ${String(r.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=ve({id:r.thread?.id??r.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const c=await xn(o,String(r.id||""),a.id);return c?i(e,200,{session:c}):i(e,404,{error:`no ${o} session ${String(r.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=ve({id:r.thread?.id??r.thread});return a?i(e,200,await An(o,a.id,Array.isArray(r.messages)?r.messages:[])):i(e,400,{error:"catchup needs the Chap conversation: { thread: { id } }"})}return i(e,404,{error:"Not found"})}catch(a){return i(e,a?.status||500,{error:a?.message||String(a)})}}const ee=We(async(n,e)=>{if(Zn(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const r=co(n,t.pathname);if(r)return i(e,403,{error:r});try{if(n.method==="GET"&&t.pathname==="/health")return po(e,{fresh:t.searchParams.get("fresh")==="1"});const o=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"",c={agent:t.searchParams.get("agent")||"",source:t.searchParams.get("source")||""};if(n.method==="GET"&&t.pathname==="/skills")return fo(e,o,a,c);if(n.method==="POST"&&t.pathname==="/agent-context"){const l=await m(n).catch(()=>({})),s=l?.options&&typeof l.options=="object"?l.options:{},d={...s.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof s.permissionMode=="string"?{permissionMode:s.permissionMode}:{},...typeof s.workingDir=="string"&&s.workingDir?{workingDir:s.workingDir}:{},...typeof s.model=="string"&&s.model?{model:s.model}:{}};return i(e,200,await On({agent:typeof l?.agent=="string"?l.agent:"claude",options:d}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return mo(e,o,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return ko(e,o,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return vo(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return Eo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return To(e,decodeURIComponent(t.pathname.slice(12)),o,a);if(n.method==="POST"&&t.pathname==="/skills")return yo(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const l=t.pathname.slice(8),s=l.indexOf("/file/");return s===-1?n.method==="DELETE"?So(e,decodeURIComponent(l)):i(e,405,{ok:!1,error:"use POST /skills to save a skill"}):n.method==="DELETE"?i(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):bo(n,e,decodeURIComponent(l.slice(0,s)),decodeURIComponent(l.slice(s+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const l=t.pathname.slice(8),s=l.indexOf("/file/");return s===-1?go(e,decodeURIComponent(l),o,a,c):wo(e,decodeURIComponent(l.slice(0,s)),decodeURIComponent(l.slice(s+6)),o,a,c)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return Co(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Po(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return De(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return De(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const l=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:y,agents:Object.fromEntries(rn.map(s=>[s,l?dn(s)||ge(s)?.kind||null:an(s)])),...l?{home:O.homedir(),path:process.env.PATH,installDirs:sn(O.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return zo(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return Oo(n,e);if(n.method==="POST"&&t.pathname==="/pair")return no(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return to(e);if(n.method==="POST"&&t.pathname==="/whoami")return oo(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return $o(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Ro(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return Io(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return No(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return _e(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const l=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return _e(n,e,l);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return le(l),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return Oe(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return Oe(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Do(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Jo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let l=null;try{l=await m(n)}catch{l=null}const s=Lt(l||{});return e.writeHead(s?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return _o(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return Ho(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return Mo(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Fo(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Xo(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Ko(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Yo(n,e);if(n.method==="POST"&&t.pathname==="/update")return Ao(e);i(e,404,{error:"Not found"})}catch(o){i(e,500,{error:o?.message||String(o)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Vo(n){let e="";const t=[];let r=!1,o=!1;const a=()=>{o&&!r&&!t.length&&process.exit(0)},c=async()=>{if(!r){for(r=!0;t.length;){const l=t.shift();let s;try{s=JSON.parse(l)}catch{continue}try{const d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:l});if(s.id==null)continue;const p=(await d.text()).trim();p&&process.stdout.write(p+`
|
|
13
13
|
`)}catch(d){s.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:s.id,error:{code:-32e3,message:String(d?.message||d)}})+`
|
|
14
14
|
`)}}r=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",l=>{e+=l;let s;for(;(s=e.indexOf(`
|
|
15
|
-
`))>=0;){const d=e.slice(0,s).trim();e=e.slice(s+1),d&&t.push(d)}c()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function Qo(){
|
|
15
|
+
`))>=0;){const d=e.slice(0,s).trim();e=e.slice(s+1),d&&t.push(d)}c()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function Qo(){cn(),ln(),eo();let n=!1;ee.on("error",e=>{if(e&&e.code==="EADDRINUSE"){fetch(`http://127.0.0.1:${k}/health`,{signal:AbortSignal.timeout(1500)}).then(t=>t.ok?t.json():null).catch(()=>null).then(t=>{const r=!!(t?.version&&Array.isArray(t.agents)),o=Cn({name:"bridge",self:y,holder:r?{ours:r,version:t.version}:null,managedBy:Pn(process.env),port:k});if(o.action==="standby"||n&&!t){if(!n)for(const a of o.lines)u("info",a);n=!0,setTimeout(()=>ee.listen(k,v),$n);return}if(r)for(const a of o.lines)u("error",a);else u("error",`Port ${k} is already in use — another app (or a second bridge) has it.`),u("error","Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings.");process.exit(1)});return}u("error",`bridge server error: ${e?.message||e}`),process.exit(1)});for(const e of["SIGINT","SIGTERM"])process.on(e,()=>{const t=Sn("shutdown");t&&u("info",`shutdown: stopped ${t} running agent${t===1?"":"s"}`);const r=kn("shutdown");r&&u("info",`shutdown: closed ${r} warm agent process${r===1?"":"es"}`),Y().close(),setTimeout(()=>process.exit(0),t||r?300:0).unref?.(),!t&&!r&&process.exit(0)});ee.listen(k,v,async()=>{n&&u("info","standby: the other bridge is gone — this copy has the port now"),n=!1,u("info",`listening on http://${v}:${k}`),Re.warm(),Q.has(v)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${v}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:e,label:t,hidden:r}]of Object.entries(E)){if(r)continue;const o=await e.available().catch(()=>({ok:!1}));u("info",` ${o.ok?"✓":"✕"} ${t}${o.ok?"":" — "+(o.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),Ae().then(e=>e.startIfConfigured()).then(e=>{e?.skipped||(e?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${e?.error||"unknown error"}`))}).catch(e=>u("error",`channels: ${e?.message||e}`))})}function Zo(){console.log(`ChatPanel Bridge v${y}
|
|
16
16
|
|
|
17
17
|
Usage:
|
|
18
18
|
chatpanel-bridge start the bridge (foreground) on ${v}:${k}
|
|
@@ -24,4 +24,4 @@ Usage:
|
|
|
24
24
|
chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
|
|
25
25
|
chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
|
|
26
26
|
|
|
27
|
-
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function qo(){const n=process.argv,e=(...t)=>t.some(r=>n.includes(r));if(e("--help","-h"))return Zo(),!0;if(e("--version","-v"))return console.log(y),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=
|
|
27
|
+
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function qo(){const n=process.argv,e=(...t)=>t.some(r=>n.includes(r));if(e("--help","-h"))return Zo(),!0;if(e("--version","-v"))return console.log(y),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=ie(D,"utf8").trim()}catch{}const r=`http://${v}:${k}`;try{if(!t)throw new Error(`no token at ${D} — is the bridge running?`);const o=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),a=await o.json().catch(()=>({}));if(!o.ok)throw new Error(a.error||`HTTP ${o.status}`);console.log(`Pairing code: ${Vn(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(o){u("error",`could not get a pairing code from the bridge at ${r}: ${o?.message||o}`),process.exitCode=1}})(),!0;if(n.includes("sandbox"))return Bt(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{lt(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(t){u("error","Install failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--uninstall")){try{dt(),u("info","Removed the login auto-start.")}catch(t){u("error","Uninstall failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--status")){let t=!1;try{t=ut()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const Me=process.argv.indexOf("--mcp-stdio"),Be=process.argv.indexOf("--sandbox-host");if(Be>=0){const{runSandboxHost:n}=await import("./sandbox-host.js");await n(process.argv[Be+1],{compiled:pn()})}else if(Me>=0){const n=process.argv[Me+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Vo(n)}else process.argv.includes("--update")?(async()=>{try{const n=await we(y);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),ce()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():qo()||Qo();
|