@chatpanel/bridge 0.12.6 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -1
- package/package.json +1 -1
- package/scripts/sync-pii.mjs +2 -2
- package/src/channels/adapters/telegram.js +3 -3
- package/src/channels/gateway.js +1 -1
- package/src/channels/service.js +1 -1
- package/src/pii/index.js +1 -1
- package/src/pii/trust.js +1 -0
- package/src/server.js +10 -9
package/README.md
CHANGED
|
@@ -175,7 +175,21 @@ available; unsupported tool requests return HTTP 400, and usage counts are zero.
|
|
|
175
175
|
|
|
176
176
|
## Safety
|
|
177
177
|
|
|
178
|
-
- Binds to `127.0.0.1` only
|
|
178
|
+
- Binds to `127.0.0.1` only. Every request must carry a loopback `Host` (no DNS
|
|
179
|
+
rebinding) and, if it has an `Origin`, an allowed one (no web page).
|
|
180
|
+
- **Who may run an agent.** The routes that start a local process need a *paired*
|
|
181
|
+
caller: ChatPanel's published Chrome/Edge extension (recognised by its extension
|
|
182
|
+
id — a browser never lets one extension send another's origin) or the per-install
|
|
183
|
+
token in `~/.chatpanel/bridge-token` (0600; the desktop app and CLIs read it). An
|
|
184
|
+
extension the bridge does not recognise — including ChatPanel's own Firefox build,
|
|
185
|
+
whose origin is a per-profile UUID — may still chat, but the run is capped to the
|
|
186
|
+
conversational tier: no files, no shell, no web, and no working directory,
|
|
187
|
+
workspace, credential or permission-mode option from the request body. The reply
|
|
188
|
+
tells the user why.
|
|
189
|
+
- **Pairing.** `chatpanel-bridge pair` prints a one-time code (5 minutes, 5 attempts).
|
|
190
|
+
Enter it in ChatPanel → Settings → Bridge and that browser holds the token from then
|
|
191
|
+
on. A dev build can instead be pinned by id: `CHATPANEL_BRIDGE_EXTENSION_IDS=<id>`.
|
|
192
|
+
Ask the bridge what it thinks of you with `POST /whoami` → `{ trust, paired }`.
|
|
179
193
|
- Claude tools are **read-only by default** (Read/Grep/Glob/WebFetch). Writes and
|
|
180
194
|
shell only run when an agent's permission mode is `acceptEdits` or
|
|
181
195
|
`bypassPermissions`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
|
|
6
6
|
"keywords": [
|
package/scripts/sync-pii.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFileSync as c,writeFileSync as d,existsSync as r,mkdirSync as h}from"node:fs";import{fileURLToPath as
|
|
2
|
+
import{readFileSync as c,writeFileSync as d,existsSync as r,mkdirSync as h}from"node:fs";import{fileURLToPath as u}from"node:url";import{dirname as f,join as n}from"node:path";const s=n(f(u(import.meta.url)),".."),m=["index.js","pii-redact.js","pii-detect.js","pipeline.js","tool-rank.js","tool-harness.js","sanitize.js","net.js","trust.js"];function y(){return[n(s,"node_modules","@chatpanel","pii"),n(s,"..","chatpanel-pii")].find(i=>r(n(i,"pii-redact.js")))}const e=process.argv.includes("--check"),p=y();if(!p){const i="chatpanel-pii not found (check out ../chatpanel-pii).";e&&(console.error(`sync-pii --check: ${i}`),process.exit(1)),console.warn(`sync-pii: ${i} Leaving src/pii as-is.`),process.exit(0)}const a=n(s,"src","pii");e||h(a,{recursive:!0});const j=i=>`// GENERATED — do not edit.
|
|
3
3
|
// Source of truth: chatpanel-pii/${i} (npm @chatpanel/pii).
|
|
4
4
|
// Edit there, then run: npm run sync:pii
|
|
5
5
|
//
|
|
@@ -7,4 +7,4 @@ import{readFileSync as c,writeFileSync as d,existsSync as r,mkdirSync as h}from"
|
|
|
7
7
|
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
8
8
|
// single-file binary has nothing to resolve.
|
|
9
9
|
|
|
10
|
-
`;let l=0;for(const i of m){const t=
|
|
10
|
+
`;let l=0;for(const i of m){const t=j(i)+c(n(p,i),"utf8"),o=n(a,i);if((r(o)?c(o,"utf8"):null)!==t){if(e){console.error(`sync-pii --check: src/pii/${i} differs from chatpanel-pii`),l+=1;continue}d(o,t),console.log(`sync-pii: updated src/pii/${i}`)}}e&&(l&&(console.error("Run `npm run sync:pii` and commit the result."),process.exit(1)),console.log("sync-pii --check: src/pii matches chatpanel-pii ✓"));
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{normalizeTelegram as
|
|
2
|
-
`);function
|
|
1
|
+
import{normalizeTelegram as ee,actorId as O}from"../normalize.js";import{buildInvocation as te,redactInbound as ae,outboundText as A,appendTurn as ne,appendInvoked as oe,appendRedacted as se,appendEgress as re}from"../invoke.js";import*as ie from"../bridge.js";import{splitForTelegram as F,createGate as ce}from"../stream.js";import{createVault as de}from"../../pii/index.js";const _="api.telegram.org",he=["ChatPanel — drive your local agent from here.","","Send a message and I run it on your machine.","/pair <code> — enroll this chat (ChatPanel → Settings → Channels)","/new — start fresh (forget this conversation + new privacy vault)","/stop — stop the current run","/help — this message"].join(`
|
|
2
|
+
`);function le(g,l){return[!l||l==="any"?"":["You are answering a message sent from the user's PHONE, relayed to this machine.",l==="device"?"You cannot read files, run commands, browse the web, or change anything.":"You can READ files and search the user's ChatPanel history. You cannot write or edit files, run shell commands, or browse the web — those are switched off for messages from a phone, and no tool will grant them.","If a request needs something you cannot do, say so plainly in your FIRST reply and offer what you can do instead. Never begin work you cannot finish.","Answers are read on a phone: be brief, and put the answer first."].join(" "),g].filter(Boolean).join(`
|
|
3
3
|
|
|
4
|
-
`)}function
|
|
4
|
+
`)}function we({botToken:g,baseUrl:l,token:$,pairing:P,savePairing:R=async()=>{},appender:x,agent:Y="claude",transport:C=ie,model:G="",provider:H="",system:L="",route:w=null,redact:N={tier:"basic"},privacy:k="standard",logger:u=console,signal:c}){const q=`https://${_}/bot${g}`,z=`https://${_}/file/bot${g}`,y=new Map,E=()=>({vault:de(),runId:null,history:[]}),U=e=>(y.has(e)||y.set(e,E()),y.get(e));async function p(e,n){return(await fetch(`${q}/${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n),signal:c})).json()}const r=(e,n)=>p("sendMessage",{chat_id:e,text:n}),S=(e,n,t)=>p("editMessageText",{chat_id:e,message_id:n,text:t});async function D(e){const n=[];for(const t of e||[])try{const o=(await p("getFile",{file_id:t.fileId}))?.result?.file_path;if(!o)continue;const s=await fetch(`${z}/${o}`,{signal:c}),d=Buffer.from(await s.arrayBuffer()),m=/\.png$/i.test(o)?"image/png":/\.webp$/i.test(o)?"image/webp":"image/jpeg";n.push({dataUrl:`data:${m};base64,${d.toString("base64")}`})}catch(a){u.warn?.(`[telegram] image fetch failed: ${a?.message||a}`)}return n}async function J(e){const n=O("telegram",e.chatId),{name:t,args:a}=e.command,o=t==="pair"||t==="start"&&a?a:"";if(o){const s=P.redeem(n,o,{label:e.from?.name||""});return await R(),void r(e.chatId,s.ok?`✅ paired (reach: ${s.reach}). Send me anything — I'll run it on your machine.`:`⛔ ${s.reason}`)}if(t==="help"||t==="start")return void r(e.chatId,he);if(t==="pair")return void r(e.chatId,"send /pair <code> — get the code in ChatPanel → Settings → Channels");if(t==="new")return y.set(e.chatId,E()),void r(e.chatId,"🧹 fresh conversation.");if(t==="stop"){const s=U(e.chatId),d=w&&w()||{},m=await(d.transport||C).cancel(s.runId,{baseUrl:d.baseUrl||l,token:d.token||$});return s.runId=null,void r(e.chatId,m?"⏹ stopped.":"nothing running.")}r(e.chatId,`unknown command /${t} — try /help`)}async function V(e){const n=O("telegram",e.chatId),t=P.reachOf(n);if(!t)return void r(e.chatId,"🔒 not paired. Get a code in the ChatPanel extension, then send: /pair <code>");if(!e.text&&!e.photos.length)return;const a=U(e.chatId);let o;try{o=te(e)}catch(i){return void r(e.chatId,`⚠️ ${i.message}`)}const{redacted:s,counts:d}=ae(e.text,a.vault,N);await oe(x,o),await se(x,d);const m=await D(e.photos),f=(await p("sendMessage",{chat_id:e.chatId,text:"…"}))?.result?.message_id,Q=ce(1200);let B="";const W=[...a.history,{role:"user",content:s}],h=w&&w()||{},X=h.transport||C;try{const i=await X.chat({agent:h.agent??Y,model:h.model??G,provider:h.provider??H,system:le(h.system??L,t),messages:W,images:m,options:{reach:t}},{baseUrl:h.baseUrl||l,token:h.token||$,signal:c,onEvent:(M,b)=>{if(b.runId&&(a.runId=b.runId),f&&(b.done||Q.ready())){const Z=A(b.text,a.vault,{privacy:k}),v=F(Z||"…")[0];v&&v!==B&&(B=v,S(e.chatId,f,v).catch(()=>{}))}}});a.runId=null;const I=A(i.text,a.vault,{privacy:k}),T=F(i.error?`⚠️ ${i.error}`:I||"(no output)");f?await S(e.chatId,f,T[0]):await r(e.chatId,T[0]);for(const M of T.slice(1))await r(e.chatId,M);!i.error&&i.text&&(a.history=ne(a.history,s,i.text)),await re(x,{host:_,redacted:k==="strict",controlled:!1})}catch(i){a.runId=null;const I=`⚠️ ${i?.message||i}`;f?await S(e.chatId,f,I).catch(()=>{}):await r(e.chatId,I).catch(()=>{})}}const j=e=>new Promise(n=>{if(c?.aborted)return n();let t;const a=()=>{clearTimeout(t),c?.removeEventListener?.("abort",a),n()};t=setTimeout(a,e),c?.addEventListener?.("abort",a,{once:!0})});async function K(){let e=0;for(u.log?.("[telegram] long-poll started (outbound-only; no inbound port).");!c?.aborted;){let n;try{const t=await p("getUpdates",{offset:e,timeout:30,allowed_updates:["message"]});if(t&&t.ok===!1){const a=t.error_code,o=a===401?" — check the bot token (@BotFather → /mybots → API token)":a===409?" — another chatpanel-channels (or another poller) is already reading this bot":"";u.error?.(`[telegram] getUpdates refused: ${t.description||`error_code ${a}`}${o}`),await j(5e3);continue}n=t?.result||[]}catch(t){if(c?.aborted)break;u.warn?.(`[telegram] getUpdates failed: ${t?.message||t}; retrying in 2s`),await j(2e3);continue}for(const t of n){e=t.update_id+1;const a=ee(t);if(!a)continue;const o=a.command?J(a):V(a);Promise.resolve(o).catch(s=>u.error?.(`[telegram] handler error: ${s?.message||s}`))}}u.log?.("[telegram] stopped.")}return K()}export{le as channelSystem,we as startTelegram};
|
package/src/channels/gateway.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseSse as
|
|
1
|
+
import{parseSse as x,foldOpenAiEvent as v,initialState as E}from"./stream.js";const c=new Map;async function A({model:r="",provider:o="",system:l="",messages:p=[],options:d={}},{baseUrl:y,token:f="",signal:u,onEvent:m=()=>{}}={}){const s=`gw_${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`,a=new AbortController;c.set(s,a);const h=()=>a.abort();u?.addEventListener?.("abort",h,{once:!0});let e=E();const g=t=>{e=v(e,t),m(t,e)};g({type:"run",id:s});try{const t=await fetch(`${String(y).replace(/\/$/,"")}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json",...f?{authorization:`Bearer ${f}`}:{},...d?.reach?{"x-chatpanel-reach":d.reach}:{},...o?{"x-chatpanel-destination":o}:{}},body:JSON.stringify({model:r,stream:!0,messages:[...l?[{role:"system",content:l}]:[],...p.map(n=>({role:n.role,content:String(n.content??"")}))]}),signal:a.signal});if(!t.ok||!t.body){const n=await t.text().catch(()=>"");throw new Error(`gateway ${t.status}${n?`: ${n.slice(0,300)}`:""}`)}let i="";const w=new TextDecoder;for await(const n of t.body){i+=typeof n=="string"?n:w.decode(n,{stream:!0});const{events:b,rest:S}=x(i);i=S;for(const $ of b)g($)}return e.done||(e={...e,done:!0}),e}catch(t){return a.signal.aborted?{...e,done:!0}:{...e,done:!0,error:t?.message||String(t)}}finally{c.delete(s),u?.removeEventListener?.("abort",h)}}async function D(r){const o=r&&c.get(r);return o?(o.abort(),c.delete(r),!0):!1}export{D as cancel,A as chat};
|
package/src/channels/service.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import v from"node:path";import{readFile as L,writeFile as J,mkdir as R,rm as z,stat as B}from"node:fs/promises";import{readFileSync as I}from"node:fs";import{createPairingStore as Y}from"./pairing.js";import*as q from"./bridge.js";import*as H from"./gateway.js";const j="http://127.0.0.1:4320";import{createEventLog as W}from"./eventlog.js";import{startTelegram as D}from"./adapters/telegram.js";const K="https://api.telegram.org",P=Object.freeze({agent:"claude",model:"",provider:"",gatewayUrl:j,privacy:"standard",tier:"basic"}),C=[2e3,5e3,15e3,6e4],G=async(s,n)=>{try{return JSON.parse(await L(s,"utf8"))}catch{return n}},M=(s,n)=>J(s,JSON.stringify(n,null,2),{mode:384});async function N(s,{fetchImpl:n=fetch,signal:m}={}){const f=await n(`${K}/bot${String(s||"").trim()}/getMe`,{signal:m}),c=await f.json().catch(()=>null);if(!c?.ok){const w=c?.description||`HTTP ${f.status}`;throw new Error(/unauthorized/i.test(w)?"Telegram rejected that token — copy it again from @BotFather":w)}return{id:c.result.id,username:c.result.username,name:c.result.first_name||""}}const Q=(s,n)=>`https://t.me/${s}?start=${n}`;function at({home:s,dataDir:n,bridge:m,logger:f=console,fetchImpl:c=void 0,now:w=()=>Date.now(),startAdapter:O=D}={}){const p=v.join(s,"telegram-token"),_=v.join(n,"config.json"),F=v.join(n,"pairing.json");let i=null,e={...P},S=null,u=null,k=null,g=!1,d="",A=0,h=!0;const y=()=>M(F,i?i.toJSON():{}),T=()=>M(_,e);async function E(){try{const t=(await L(p,"utf8")).trim();if(!t)return"";try{const{mode:r}=await B(p);r&63&&f.warn?.(`[channels] ${p} is group/world-readable — chmod 600 it (it holds your bot token).`)}catch{}return t}catch{return""}}async function l(){await R(n,{recursive:!0}),i||(i=Y(await G(F,{}),{now:w})),e={...P,...await G(_,{})},S||(S=await W({file:v.join(n,"events.jsonl"),host:"channel"}))}function $(t){k=new AbortController,g=!0;const r=()=>{try{return I(v.join(s,"gateway-token"),"utf8").trim()}catch{return""}},o=()=>{const a=!!e.model;return{transport:a?H:q,token:a?r():m.token,agent:a?"":e.agent,model:a?e.model:"",provider:a&&e.provider||"",baseUrl:a?e.gatewayUrl||j:m.baseUrl,system:e.system||"",privacy:e.privacy}},b=O({botToken:t,route:o,transport:o().transport,model:o().model,provider:o().provider,baseUrl:o().baseUrl,token:m.token,pairing:i,savePairing:y,appender:S,agent:e.agent,system:e.system||"",redact:{tier:e.tier},privacy:e.privacy,logger:f,signal:k.signal});Promise.resolve(b).catch(a=>{d=a?.message||String(a),f.warn?.(`[channels] telegram loop failed: ${d}`)}).finally(()=>{if(g=!1,h)return;const a=C[Math.min(A++,C.length-1)];f.warn?.(`[channels] telegram stopped unexpectedly — retrying in ${Math.round(a/1e3)}s`),setTimeout(()=>{h||$(t)},a).unref?.()})}async function U(){if(g)return{ok:!0,already:!0};await l();const t=await E();if(!t)return{ok:!1,error:"no bot token configured"};if(e.enabled===!1)return{ok:!1,error:"channel is turned off"};try{u=await N(t,{fetchImpl:c})}catch(r){return d=r?.message||String(r),{ok:!1,error:d}}return d="",A=0,h=!1,$(t),{ok:!0,bot:u}}return{async startIfConfigured(){return await l(),!await E()||e.enabled===!1?{ok:!1,skipped:!0}:U().catch(t=>({ok:!1,error:t?.message||String(t)}))},start:U,async connect({token:t,agent:r,privacy:o,tier:b}={}){await l();const a=await N(t,{fetchImpl:c});await J(p,String(t).trim(),{mode:384}),e={...e,...r?{agent:r}:{},...o?{privacy:o}:{},...b?{tier:b}:{},enabled:!0},await T(),await this.stop();const x=await U();if(!x.ok)throw new Error(x.error);return{bot:a,settings:{...e}}},async pair({ttlMs:t=10*6e4}={}){if(await l(),!u)throw new Error("connect a bot first");const r=i.requestCode({ttlMs:t});return await y(),{code:r,link:Q(u.username,r),expiresAt:w()+t,bot:{...u}}},async allow(t,{reach:r="trusted"}={}){return await l(),i.allow(t,{reach:r}),await y(),{actorId:t,reach:r}},async unpair(t){await l();const r=i.revoke(t);return await y(),{removed:r}},async update(t={}){await l();const r={...e};for(const o of["agent","model","provider","gatewayUrl","privacy","tier","system"])t[o]!=null&&(r[o]=t[o]);return t.agent!=null&&t.model==null&&(r.model="",r.provider=""),t.model&&(r.agent=""),e=r,await T(),{settings:{...e}}},async stop({forget:t=!1}={}){if(h=!0,k?.abort(),k=null,g=!1,t){await l(),e={...e,enabled:!1},await T(),await z(p,{force:!0});for(const r of i.list())i.revoke(r.actorId);await y(),u=null}return{ok:!0}},async status(){return await l(),{channel:"telegram",configured:!!await E(),enabled:e.enabled!==!1,running:g,bot:u?{...u}:null,error:d,paired:i.list(),settings:{agent:e.agent,model:e.model||"",provider:e.provider||"",gatewayUrl:e.gatewayUrl||j,privacy:e.privacy,tier:e.tier},via:e.model?"gateway":"bridge"}}}}export{P as DEFAULT_SETTINGS,at as createChannelService,Q as pairLink,N as verifyBot};
|
package/src/pii/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./pii-redact.js";export*from"./pii-detect.js";export*from"./pipeline.js";export*from"./tool-rank.js";export*from"./tool-harness.js";export*from"./sanitize.js";export*from"./net.js";
|
|
1
|
+
export*from"./pii-redact.js";export*from"./pii-detect.js";export*from"./pipeline.js";export*from"./tool-rank.js";export*from"./tool-harness.js";export*from"./sanitize.js";export*from"./net.js";export*from"./trust.js";
|
package/src/pii/trust.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const f=Object.freeze(["icemacffhbgnfoofclgdbcdmnlkkklem","jkmmbleapaognlonbnllpaoeibmfkjmp"]),p=/^[a-p]{32}$/;function E(n){return String(n||"").split(/[\s,]+/).map(t=>t.trim().toLowerCase().replace(/^chrome-extension:\/\//,"").replace(/\/+$/,"")).filter(t=>p.test(t))}function d(n,{extensionIds:t=[]}={}){const o=String(n||"").trim();if(!o)return"none";const r=/^chrome-extension:\/\/([a-p]{32})\/?$/i.exec(o);if(r){const e=r[1].toLowerCase();return f.includes(e)||(t||[]).includes(e)?"pinned":"extension"}return/^(chrome|moz)-extension:\/\//i.test(o)?"extension":/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?\/?$/i.test(o)?"localhost":"web"}function I({origin:n,hasToken:t=!1,extensionIds:o=[]}={}){if(t)return"token";const r=d(n,{extensionIds:o});return r==="pinned"?"pinned":r==="extension"||r==="localhost"?"unpaired":r==="none"?"local":"web"}function x(n){return n==="token"||n==="pinned"}const a=Object.freeze({device:0,trusted:1,any:2});function g(n,t){const o=a[n]??0,r=a[t]??0,e=o<=r?n:t;return a[e]===void 0?"device":e}function m(n){return x(n)?null:"device"}const k=Object.freeze(["workingDir","workspace","grants","connectionId","permissionMode","extraArgs","env","runEnv","reach"]);function N(n,t){const o=m(t),r=n&&typeof n=="object"?n:{};if(!o)return{...r};const e={};for(const[c,s]of Object.entries(r))k.includes(c)||(e[c]=s);return e.reach=g(r.reach||o,o),e}const h=Object.freeze(["claude"]);function R(n,t){return!t||t==="any"?!0:h.includes(String(n||""))}const A=300*1e3,S=5;function b(n){const t=String(n||"").replace(/\D/g,"");return t.length===6?`${t.slice(0,3)}-${t.slice(3)}`:t}function _({now:n=()=>Date.now(),random:t=Math.random,ttlMs:o=A,maxAttempts:r=S}={}){let e=null;function c(){const i=String(Math.floor(t()*1e6)).padStart(6,"0");return e={code:i,expiresAt:n()+o,attempts:0},{code:i,display:b(i),expiresAt:e.expiresAt}}function s(i){if(!e)return{ok:!1,reason:"no pairing code is active — ask the server for one"};if(n()>e.expiresAt)return e=null,{ok:!1,reason:"pairing code expired — ask for a new one"};e.attempts+=1;const u=String(i||"").replace(/\D/g,"");return u.length===6&&u===e.code?(e=null,{ok:!0}):e.attempts>=r?(e=null,{ok:!1,reason:"too many wrong codes — ask for a new one"}):{ok:!1,reason:"wrong pairing code"}}function l(){return e&&n()>e.expiresAt&&(e=null),e?{expiresAt:e.expiresAt,attemptsLeft:r-e.attempts}:null}return{issue:c,claim:s,active:l}}export{f as CHATPANEL_EXTENSION_IDS,S as PAIRING_MAX_ATTEMPTS,A as PAIRING_TTL_MS,h as REACH_ENFORCING_ENGINES,I as callerTrust,N as capRunOptions,d as classifyOrigin,_ as createPairingStore,R as engineHonoursReach,b as formatPairingCode,x as isPaired,g as minReach,E as parseExtensionIds,m as reachCeiling};
|
package/src/server.js
CHANGED
|
@@ -1,22 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createServer as ce}from"node:http";import x from"node:os";import{randomBytes as le,timingSafeEqual as de}from"node:crypto";import{mkdirSync as ue,writeFileSync as he,readFileSync as pe,existsSync as me}from"node:fs";import{join as $}from"node:path";import*as fe from"./engines/claude.js";import*as ge from"./engines/codex.js";import*as ye from"./engines/antigravity.js";import{pi as we,opencode as be,kiro as Se,copilot as ke,deepseek as Te,hermes as ve}from"./engines/cli-agents.js";import{connectorsFor as Ce}from"./connectors.js";import*as Ee from"./engines/custom.js";import{installService as Oe,uninstallService as Ae,serviceStatus as xe,restartService as j}from"./service.js";import{skillIndex as B,listRecords as Pe,readRecord as $e,readPackageFile as Ie,skillsHealth as Ne,quarantinedSkills as Re}from"./skills.js";import{capabilityToolSpecs as He,runCapabilityTool as _e}from"./mcp-capabilities.js";import{createSession as Me,deleteSession as J,getSession as F,activeSession as Be,relayToolCall as Ge}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ue,isDefaultWorkdir as De,resolveWorkdir as Le,writeScopeNote as We}from"./workdir.js";import{gitState as je,gitDelta as Je}from"./scm.js";import{listConnections as Fe,putConnection as Ke,removeConnection as ze,runEnvFor as Ve,testConnection as Ye,secretBackend as K}from"./connections.js";import{worktreeFor as z,listWorktrees as Xe,removeWorktree as Qe,withHook as Ze,WORKTREE_ROOT as V}from"./worktree.js";import{AGENT_CLIS as qe,enrichPath as et,enrichAgentEnv as tt,findAgentBin as Y,resolveCommand as nt}from"./env.js";import"./sanitize.js";import{checkForUpdate as ot,selfUpdate as X,isEmbedded as rt}from"./update.js";import{callLocalMcp as at}from"./mcp-local.js";import{assertPublicHttpUrl as Q,assertPublicWebUrl as Z}from"./ssrf.js";import{startRun as q,endRun as G,cancelRun as it,cancelAll as st}from"./runs.js";import{closeWarmPools as ct,warmStatus as lt}from"./warm.js";import{CompatError as I,anthropicError as U,anthropicStream as dt,chatCompletionStream as ut,completionStream as ht,createAnthropicMessage as pt,createChatCompletion as mt,createCompletion as ft,createResponse as gt,openAIError as w,parseAnthropicMessage as yt,parseChatCompletion as wt,parseCompletion as bt,parseResponse as St,responseStream as kt}from"./api-compat.js";const g="0.12.6",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",O=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,T={claude:{engine:fe,label:"Claude Code"},codex:{engine:ge,label:"Codex"},antigravity:{engine:ye,label:"Antigravity",tools:!1},pi:{engine:we,label:"Pi"},opencode:{engine:be,label:"OpenCode"},hermes:{engine:ve,label:"Hermes"},kiro:{engine:Se,label:"Kiro"},copilot:{engine:ke,label:"GitHub Copilot"},deepseek:{engine:Te,label:"DeepSeek Harness"},custom:{engine:Ee,label:"Custom",hidden:!0}};function ee(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Tt(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function vt(n,e){const t=n.headers.origin||"",r=ee(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 D=new Set(["127.0.0.1","localhost","::1"]);function Ct(n){if(!D.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return D.has(t)}const L=$(x.homedir(),".chatpanel","bridge-token");let v="";function Et(){try{me(L)&&(v=pe(L,"utf8").trim()),v||(v=le(32).toString("hex"),ue($(x.homedir(),".chatpanel"),{recursive:!0}),he(L,v,{mode:384}))}catch(n){h("error",`could not initialise bridge token: ${n?.message||n}`)}}let N=null;async function te(){if(N)return N;const{createChannelService:n}=await import("./channels/service.js");return N=n({home:$(x.homedir(),".chatpanel"),dataDir:$(x.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${O}`,token:v},logger:{log:e=>h("info",e),warn:e=>h("info",e),error:e=>h("error",e)}}),N}async function ne(n,e,t){try{const r=await te(),o=n.method==="POST"?await f(n):{};if(t==="status")return a(e,200,await r.status());if(t==="connect"){const i=await r.connect(o);return a(e,200,{ok:!0,...i})}return t==="pair"?a(e,200,await r.pair()):t==="unpair"?a(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?a(e,200,await r.update(o)):t==="disconnect"?a(e,200,await r.stop({forget:!!o.forget})):a(e,404,{error:"unknown channel action"})}catch(r){return a(e,400,{error:r?.message||String(r)})}}function Ot(n){if(!v)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(v);return r.length===o.length&&de(r,o)}const At=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/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"]),xt=new Set(["/debug"]),Pt=n=>xt.has(n);function $t(n,e){if(!Ct(n))return"forbidden host";const t=n.headers.origin||"";return t&&!ee(t)?"forbidden origin":(n.method==="POST"&&At.has(e)||n.method==="GET"&&Pt(e))&&!(Tt(t)||Ot(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":null}function a(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(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)})}async function It(n){const e=await Promise.all(Object.entries(T).filter(([,o])=>!o.hidden).map(async([o,{engine:i,label:l,tools:d}])=>{const s=await i.available().catch(u=>({ok:!1,reason:String(u?.message||u)})),c=await Ce(o).catch(()=>[]);return{id:o,label:l,available:s.ok,reason:s.reason,connectors:c,...d===!1?{tools:!1}:{}}})),t=rt()?{current:g,updateAvailable:!1,embedded:"gateway"}:await ot(g).catch(()=>({current:g,updateAvailable:!1})),r=await Ne().catch(()=>null);a(n,200,{ok:!0,version:g,agents:e,update:t,workspace:Ue,worktrees:V,secretBackend:K(),warm:lt(),...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function Nt(n,e){const{index:t,problems:r}=await B({extraDirs:e});a(n,200,{ok:!0,skills:Pe(t),problems:r})}async function Rt(n,e){a(n,200,{ok:!0,quarantined:await Re(e)})}async function Ht(n,e,t){const{index:r}=await B({extraDirs:t}),o=$e(r,e);if(!o)return a(n,404,{ok:!1,error:"unknown skill"});a(n,200,{ok:!0,skill:o})}async function _t(n,e,t,r){const{index:o}=await B({extraDirs:r}),i=await Ie(o,e,t);if(i.error)return a(n,i.error==="unknown skill"?404:400,{ok:!1,error:i.error});a(n,200,{ok:!0,...i})}async function Mt(){return(await Promise.all(Object.entries(T).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 oe(n,e=""){const t=await Mt();if(e){const r=t.find(o=>o.id===e);return r?a(n,200,r):a(n,404,w(new I(`Model "${e}" not found`,404,"model")))}return a(n,200,{object:"list",data:t})}async function Bt(n){try{const e=await X(g);a(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>j(),400))}catch(e){a(n,400,{ok:!1,error:String(e?.message||e)})}}async function Gt(n,e){let t;try{t=await f(n)}catch(p){return a(e,400,{error:"Bad JSON: "+p.message})}const r=T[t.agent];if(!r)return a(e,404,{error:`Unknown agent "${t.agent}"`});Array.isArray(t.images)&&t.images.length&&h("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 o=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
|
|
2
|
+
import{createServer as fe}from"node:http";import P from"node:os";import{randomBytes as ge,randomInt as ye,timingSafeEqual as we}from"node:crypto";import{mkdirSync as be,writeFileSync as Se,readFileSync as K,existsSync as ke}from"node:fs";import{join as _}from"node:path";import*as Te from"./engines/claude.js";import*as ve from"./engines/codex.js";import*as Ee from"./engines/antigravity.js";import{pi as Ce,opencode as Oe,kiro as Ae,copilot as Pe,deepseek as xe,hermes as $e}from"./engines/cli-agents.js";import{connectorsFor as Ie}from"./connectors.js";import*as Ne from"./engines/custom.js";import{installService as Re,uninstallService as _e,serviceStatus as He,restartService as V}from"./service.js";import{skillIndex as D,listRecords as Me,readRecord as Be,readPackageFile as Ge,skillsHealth as Ue,quarantinedSkills as De}from"./skills.js";import{capabilityToolSpecs as Le,runCapabilityTool as je}from"./mcp-capabilities.js";import{createSession as We,deleteSession as X,getSession as Y,activeSession as Fe,relayToolCall as Je}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ze,isDefaultWorkdir as Ke,resolveWorkdir as Ve,writeScopeNote as Xe}from"./workdir.js";import{gitState as Ye,gitDelta as Qe}from"./scm.js";import{listConnections as Ze,putConnection as qe,removeConnection as et,runEnvFor as tt,testConnection as nt,secretBackend as Q}from"./connections.js";import{worktreeFor as Z,listWorktrees as rt,removeWorktree as ot,withHook as at,WORKTREE_ROOT as q}from"./worktree.js";import{AGENT_CLIS as it,enrichPath as st,enrichAgentEnv as ct,findAgentBin as ee,resolveCommand as lt}from"./env.js";import"./sanitize.js";import{checkForUpdate as dt,selfUpdate as te,isEmbedded as ut}from"./update.js";import{callLocalMcp as ht}from"./mcp-local.js";import{assertPublicHttpUrl as ne,assertPublicWebUrl as re}from"./ssrf.js";import{startRun as oe,endRun as L,cancelRun as pt,cancelAll as mt}from"./runs.js";import{closeWarmPools as ft,warmStatus as gt}from"./warm.js";import{CompatError as x,anthropicError as j,anthropicStream as yt,chatCompletionStream as wt,completionStream as bt,createAnthropicMessage as St,createChatCompletion as kt,createCompletion as Tt,createResponse as vt,openAIError as w,parseAnthropicMessage as Et,parseChatCompletion as Ct,parseCompletion as Ot,parseResponse as At,responseStream as Pt}from"./api-compat.js";import{callerTrust as xt,isPaired as $,parseExtensionIds as $t,capRunOptions as It,engineHonoursReach as Nt,createPairingStore as Rt,formatPairingCode as _t}from"./pii/trust.js";const g="0.13.0",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,E={claude:{engine:Te,label:"Claude Code"},codex:{engine:ve,label:"Codex"},antigravity:{engine:Ee,label:"Antigravity",tools:!1},pi:{engine:Ce,label:"Pi"},opencode:{engine:Oe,label:"OpenCode"},hermes:{engine:$e,label:"Hermes"},kiro:{engine:Ae,label:"Kiro"},copilot:{engine:Pe,label:"GitHub Copilot"},deepseek:{engine:xe,label:"DeepSeek Harness"},custom:{engine:Ne,label:"Custom",hidden:!0}};function ae(t){return!t||t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}const Ht=$t(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function I(t){return t.chatpanelTrust||(t.chatpanelTrust=xt({origin:t.headers.origin||"",hasToken:le(t),extensionIds:Ht})),t.chatpanelTrust}function Mt(t){return t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}function Bt(t,e){const n=t.headers.origin||"",o=ae(n);e.setHeader("Access-Control-Allow-Origin",o?n||"*":"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 W=new Set(["127.0.0.1","localhost","::1"]);function Gt(t){if(!W.has(k))return!0;const e=String(t.headers.host||"");if(!e)return!1;const n=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return W.has(n)}const N=_(P.homedir(),".chatpanel","bridge-token");let S="";function Ut(){try{ke(N)&&(S=K(N,"utf8").trim()),S||(S=ge(32).toString("hex"),be(_(P.homedir(),".chatpanel"),{recursive:!0}),Se(N,S,{mode:384}))}catch(t){d("error",`could not initialise bridge token: ${t?.message||t}`)}}const ie=Rt({random:()=>ye(0,1e6)/1e6});function Dt(t){if(!S)return i(t,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ie.issue();return d("info","pairing code issued — valid for 5 minutes, one use"),i(t,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Lt(t,e){let n;try{n=await f(t)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=ie.claim(n?.code);return o.ok?(d("info",`paired a ${I(t)} client${t.headers.origin?` (${t.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(d("info",`pairing refused (${o.reason}) from ${I(t)} caller`),i(e,403,{error:o.reason}))}function jt(t,e){const n=I(t);return i(e,200,{ok:!0,trust:n,paired:$(n),version:g})}let H=null;async function se(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:_(P.homedir(),".chatpanel"),dataDir:_(P.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>d("info",e),warn:e=>d("info",e),error:e=>d("error",e)}}),H}async function ce(t,e,n){try{const o=await se(),r=t.method==="POST"?await f(t):{};if(n==="status")return i(e,200,await o.status());if(n==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return n==="pair"?i(e,200,await o.pair()):n==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):n==="settings"?i(e,200,await o.update(r)):n==="disconnect"?i(e,200,await o.stop({forget:!!r.forget})):i(e,404,{error:"unknown channel action"})}catch(o){return i(e,400,{error:o?.message||String(o)})}}function le(t){if(!S)return!1;const e=String(t.headers.authorization||""),n=(e.startsWith("Bearer ")?e.slice(7):String(t.headers["x-api-key"]||t.headers["x-chatpanel-token"]||"")).trim();if(!n)return!1;const o=Buffer.from(n),r=Buffer.from(S);return o.length===r.length&&we(o,r)}const Wt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/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"]),Ft=new Set(["/debug"]),Jt=t=>Ft.has(t);function zt(t,e){if(!Gt(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!ae(n))return"forbidden origin";const o=t.method==="POST"&&Wt.has(e)||t.method==="GET"&&Jt(e);return o&&!(Mt(n)||le(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!$(I(t))&&!Vt.has(e)?Kt:null}const Kt="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",Vt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(t,e,n){const o=I(t),r=It(n,o);if(!Nt(e,r.reach))return{error:`${$(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${$(o)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=$(o)?"":"Unpaired client: the agent runs without file, shell or web tools. Pair this client in ChatPanel Settings to unlock them.";return{options:r,note:a}}function i(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function f(t){return new Promise((e,n)=>{let o="";t.on("data",r=>{o+=r,o.length>50*1024*1024&&n(new Error("Body too large"))}),t.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){n(r)}}),t.on("error",n)})}async function Xt(t){const e=await Promise.all(Object.entries(E).filter(([,r])=>!r.hidden).map(async([r,{engine:a,label:l,tools:m}])=>{const s=await a.available().catch(u=>({ok:!1,reason:String(u?.message||u)})),c=await Ie(r).catch(()=>[]);return{id:r,label:l,available:s.ok,reason:s.reason,connectors:c,...m===!1?{tools:!1}:{}}})),n=ut()?{current:g,updateAvailable:!1,embedded:"gateway"}:await dt(g).catch(()=>({current:g,updateAvailable:!1})),o=await Ue().catch(()=>null);i(t,200,{ok:!0,version:g,agents:e,update:n,workspace:ze,worktrees:q,secretBackend:Q(),warm:gt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...o?{skills:o}:{}})}async function Yt(t,e){const{index:n,problems:o}=await D({extraDirs:e});i(t,200,{ok:!0,skills:Me(n),problems:o})}async function Qt(t,e){i(t,200,{ok:!0,quarantined:await De(e)})}async function Zt(t,e,n){const{index:o}=await D({extraDirs:n}),r=Be(o,e);if(!r)return i(t,404,{ok:!1,error:"unknown skill"});i(t,200,{ok:!0,skill:r})}async function qt(t,e,n,o){const{index:r}=await D({extraDirs:o}),a=await Ge(r,e,n);if(a.error)return i(t,a.error==="unknown skill"?404:400,{ok:!1,error:a.error});i(t,200,{ok:!0,...a})}async function en(){return(await Promise.all(Object.entries(E).filter(([,e])=>!e.hidden).map(async([e,n])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await n.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...n})=>n)}async function de(t,e=""){const n=await en();if(e){const o=n.find(r=>r.id===e);return o?i(t,200,o):i(t,404,w(new x(`Model "${e}" not found`,404,"model")))}return i(t,200,{object:"list",data:n})}async function tn(t){try{const e=await te(g);i(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>V(),400))}catch(e){i(t,400,{ok:!1,error:String(e?.message||e)})}}async function nn(t,e){let n;try{n=await f(t)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const o=E[n.agent];if(!o)return i(e,404,{error:`Unknown agent "${n.agent}"`});const r=F(t,n.agent,n.options||{});if(r.error)return i(e,403,{error:r.error});n.options=r.options,Array.isArray(n.images)&&n.images.length&&d("info",`chat: ${n.agent} received ${n.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)}
|
|
3
3
|
|
|
4
|
-
`)};let
|
|
4
|
+
`)};let l=!1;const m=`run_${Math.random().toString(36).slice(2,10)}`,s=oe(m),c={signal:s.signal,abort:()=>s.cancel("client")},u=()=>{l=!0,s.cancel("disconnected")};t.on("close",u),e.on("close",u),e.on("error",u);const b=h=>{l||a(h)};a({type:"run",id:m}),r.note&&a({type:"status",text:r.note});let p=null;if(n.options?.workspace&&typeof n.options.workspace=="object"){const h=n.options.workspace;if(p=await Z({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),p.error){a({type:"error",error:`workspace: ${p.error}`}),L(m),e.writableEnded||e.end();return}}const J=p?p.path:Ve(n.options?.workingDir);let C=null;{const h=J,O=!!p||!Ke(n.options?.workingDir),y=Xe(n.agent,n.options?.permissionMode,h);a({type:"workdir",path:h,isDefault:!O,writeScope:y||void 0}),a({type:"status",text:`Working in ${h}${O?"":" (default)"}`}),y&&a({type:"status",text:y}),C=await Ye(h),C&&a({type:"scm",phase:"before",...C})}let U=null;if(C||p){const h=Array.isArray(n.options?.grants)?n.options.grants:[],{env:O,connection:y}=tt({remote:C?.remote||null,grants:h,branch:p?.branch||null,connectionId:n.options?.connectionId||null});U=at(O),p&&a({type:"workspace",path:p.path,branch:p.branch,base:p.base,created:p.created,repo:p.repo,...y?{connection:y}:{}}),y&&a({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${p?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const z={...n.options||{},...p?{workingDir:p.path}:{},...U?{runEnv:U}:{}};let R=null;n.pageTools?.specs?.length&&(R=We(b,n.pageTools.specs),z.mcp={url:`http://${k}:${v}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:n.pageTools.specs});try{await o.engine.chat({messages:Array.isArray(n.messages)?n.messages:[],system:n.system||"",options:z,images:Array.isArray(n.images)?n.images:[]},b,{signal:c.signal})}catch(h){d("error",`${n.agent} chat failed: ${h?.message||h}`),a({type:"error",error:h?.message||String(h)})}finally{if(!l){const h=await Qe(J,C).catch(()=>null);h&&b({type:"scm",phase:"after",...h})}L(m),R&&X(R.id),e.writableEnded||e.end()}}async function rn(t,e,n){if(t.method==="GET"&&n==="/connections")return i(e,200,{ok:!0,connections:Ze(),secretBackend:Q()});if(t.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await f(t);if(n==="/connections")try{return i(e,200,{ok:!0,connection:qe(o.connection||o,{token:o.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const r=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(n);return r?r[2]==="delete"?i(e,200,{ok:et(r[1])}):i(e,200,nt(r[1],o.remote||"")):i(e,404,{error:"Not found"})}async function on(t,e,n){if(t.method==="GET"&&n==="/worktrees")return i(e,200,{ok:!0,root:q,worktrees:await rt()});if(t.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await f(t);if(n==="/worktrees"){const r=await Z({repo:o.repo,projectId:o.projectId,jobId:o.jobId,base:o.base||null});return i(e,r.error?400:200,r.error?{error:r.error}:{ok:!0,...r})}if(n==="/worktrees/remove"){const r=await ot({projectId:o.projectId,jobId:o.jobId,force:!!o.force});return i(e,r.ok?200:400,r)}return i(e,404,{error:"Not found"})}async function T(t,e,n){const o=E[t.agent];if(!o||o.hidden)throw new x(`Unknown ChatPanel agent "${t.agent}"`,400,"model");const r=await o.engine.available().catch(c=>({ok:!1,reason:c?.message||String(c)}));if(!r.ok)throw new x(r.reason||`${t.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,l=oe(a),m=()=>l.cancel("disconnected");n.on("close",m);let s="";try{return await o.engine.chat({messages:t.messages,system:t.system,options:t.options,images:[]},c=>{c?.type==="delta"&&c.text?(s+=c.text,e(c.text)):c?.type==="done"&&c.text&&!s&&(s=c.text,e(c.text))},{signal:l.signal}),s}finally{n.off("close",m),L(a)}}function M(t){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function A(t,e){t.writableEnded||t.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
|
|
5
5
|
|
|
6
|
-
`)}function
|
|
7
|
-
data: ${JSON.stringify(
|
|
6
|
+
`)}function B(t,e,n){t.writableEnded||t.write(`event: ${e}
|
|
7
|
+
data: ${JSON.stringify(n)}
|
|
8
8
|
|
|
9
|
-
`)}async function _(n,e,t,r){try{return t(await f(n))}catch(o){return a(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new I(`Bad JSON: ${o.message}`):o)),null}}async function Lt(n,e){const t=await _(n,e,wt,w);if(!t)return;if(!t.stream)try{const o=await S(t,()=>{},e);return a(e,200,mt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,w(o))}R(e);const r=ut(t.requestedModel,o=>A(e,o));try{await S(t,o=>r.delta(o),e),r.done()}catch(o){A(e,w(o))}A(e,"[DONE]"),e.end()}async function Wt(n,e){const t=await _(n,e,bt,w);if(!t)return;if(!t.stream)try{const o=await S(t,()=>{},e);return a(e,200,ft(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,w(o))}R(e);const r=ht(t.requestedModel,o=>A(e,o));try{await S(t,o=>r.delta(o),e),r.done()}catch(o){A(e,w(o))}A(e,"[DONE]"),e.end()}async function jt(n,e){const t=await _(n,e,St,w);if(!t)return;if(!t.stream)try{const o=await S(t,()=>{},e);return a(e,200,gt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,w(o))}R(e);const r=kt(t.requestedModel,o=>H(e,o.type,o));try{await S(t,o=>r.delta(o),e),r.done()}catch(o){const i={type:"error",sequence_number:0,...w(o)};H(e,"error",i)}e.end()}async function Jt(n,e){const t=await _(n,e,yt,U);if(!t)return;if(!t.stream)try{const o=await S(t,()=>{},e);return a(e,200,pt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,U(o))}R(e);const r=dt(t.requestedModel,(o,i)=>H(e,o,i));try{await S(t,o=>r.delta(o),e),r.done()}catch(o){H(e,"error",U(o))}e.end()}async function Ft(n,e){let t={};try{t=await f(n)||{}}catch{}const r=String(t.id||"").trim(),o=r?it(r,"stopped"):!1;return o&&h("info",`cancel: ${r} stopped by client`),a(e,200,{ok:!0,cancelled:o})}async function re(n,e,t){let r;try{r=await f(n)}catch{return a(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=t?F(t):Be(),i=s=>{o&&e.setHeader("Mcp-Session-Id",o.id),a(e,200,{jsonrpc:"2.0",id:r.id??null,result:s})},l=(s,c)=>a(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:s,message:c}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return i({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const d=He();if(r.method==="tools/list"){const s=o?o.specs.map(c=>({name:c.name,description:c.description,inputSchema:c.parameters||{type:"object",properties:{}}})):[];return i({tools:[...d,...s]})}if(r.method==="tools/call"){const s=await _e(r.params?.name,r.params?.arguments||{});if(s)return i(s);if(!o)return l(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return i(await Ge(o,r.params?.name,r.params?.arguments||{}))}catch(c){return i({content:[{type:"text",text:`error: ${c?.message||c}`}],isError:!0})}}return l(-32601,`Method not found: ${r.method}`)}async function Kt(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=t.server||{},o=t.message;if(!r.command||!o)return a(e,400,{error:"need server.command and message"});try{const i=await at({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd},o);return o.id==null?(e.writeHead(202),e.end()):a(e,200,i)}catch(i){return a(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(i?.message||i)}})}}async function zt(n,e){let t;try{t=await f(n)}catch(u){return a(e,400,{error:"Bad JSON: "+u.message})}const{url:r,headers:o,message:i}=t||{};if(!r||!i)return a(e,400,{error:"need url and message"});let l;try{l=Q(r)}catch(u){return a(e,400,{error:String(u?.message||u)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[u,m]of Object.entries(o)){const b=u.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(b)||b.startsWith("x-"))&&(d[u]=String(m))}const s=new AbortController,c=setTimeout(()=>s.abort(),3e4);try{const u=await fetch(l.href,{method:"POST",headers:d,body:JSON.stringify(i),redirect:"follow",signal:s.signal});try{u.url&&Q(u.url)}catch(b){return a(e,400,{error:String(b?.message||b)})}const m=await u.text().catch(()=>"");return a(e,200,{status:u.status,sessionId:u.headers.get("Mcp-Session-Id")||null,contentType:u.headers.get("Content-Type")||"",body:m})}catch(u){const m=u?.name==="AbortError"?"timed out":String(u?.message||u);return a(e,502,{error:`couldn't reach MCP server ${l.host}: ${m}`})}finally{clearTimeout(c)}}const ae=256*1024,Vt=5,Yt=8e3;async function Xt(n){let e=Z(n);const t=new AbortController,r=setTimeout(()=>t.abort(),Yt);try{for(let o=0;o<=Vt;o++){const i=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/${g} (+link-title)`}});if(i.status>=300&&i.status<400&&i.headers.get("location")){if(e=Z(new URL(i.headers.get("location"),e).href),i.body)try{await i.body.cancel()}catch{}continue}if(!i.ok){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}const l=i.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(l)){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}return{title:qt(await Qt(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function Qt(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,ae);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:i,value:l}=await e.read();if(i||(o+=l.byteLength,r+=t.decode(l,{stream:!0}),/<\/title\s*>/i.test(r)||o>=ae))break}}finally{try{await e.cancel()}catch{}}return r}function Zt(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 qt(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Zt(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function en(n,e){let t;try{t=await f(n)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=t&&t.url;if(!r||typeof r!="string")return a(e,400,{error:"need url"});try{const o=await Xt(r);return a(e,200,{title:o.title||null,url:o.url||r})}catch(o){const i=o?.name==="AbortError"?"timed out":String(o?.message||o);return a(e,400,{error:`couldn't fetch title: ${i}`})}}async function tn(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=F(t.session);if(!r)return a(e,404,{error:"no such session"});const o=r.pending.get(t.id);return o?(r.pending.delete(t.id),o.resolve(t.result),a(e,200,{ok:!0})):a(e,404,{error:"no such pending call"})}async function nn(n,e){let t;try{t=await f(n)}catch(d){return a(e,400,{error:"Bad JSON: "+d.message})}const r=T[t.agent];if(!r)return a(e,404,{error:`Unknown agent "${t.agent}"`});const o=String(t.prompt||"").slice(0,6e3);if(!o)return a(e,400,{error:"Empty prompt"});const i=t.model||"",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 d="";return typeof r.engine.complete=="function"?d=await r.engine.complete({prompt:o,system:l,model:i}):await r.engine.chat({messages:[{role:"user",content:o}],system:l,options:{model:i}},s=>{s.type==="delta"?d+=s.text||"":s.type==="done"&&s.text&&(d+=s.text)}),a(e,200,{text:(d||"").trim()})}catch(d){return a(e,502,{error:d?.message||String(d)})}}async function on(n,e){let t;try{t=await f(n)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=T[t.agent];if(!r)return a(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof r.engine.listModels!="function")return a(e,200,{models:[]});try{const o=await r.engine.listModels(t.options||{});return a(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return a(e,502,{error:o?.message||String(o)})}}async function rn(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=String(t.command||"").trim();if(!r)return a(e,400,{error:"No command"});let o=null;try{o=nt(r)}catch{o=null}return a(e,200,{ok:!!o,via:o?o.kind:null})}const ie=ce(async(n,e)=>{if(vt(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 a(e,400,{error:"bad request"})}const r=$t(n,t.pathname);if(r)return a(e,403,{error:r});try{if(n.method==="GET"&&t.pathname==="/health")return It(e);const o=t.searchParams.getAll("dir");if(n.method==="GET"&&t.pathname==="/skills")return Nt(e,o);if(n.method==="GET"&&t.pathname==="/skills-quarantined")return Rt(e,o);if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const i=t.pathname.slice(8),l=i.indexOf("/file/");return l===-1?Ht(e,decodeURIComponent(i),o):_t(e,decodeURIComponent(i.slice(0,l)),decodeURIComponent(i.slice(l+6)),o)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return Ut(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Dt(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return oe(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return oe(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const i=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return a(e,200,{version:g,agents:Object.fromEntries(qe.map(l=>[l,i?Y(l)||null:!!Y(l)])),...i?{home:x.homedir(),path:process.env.PATH}:{}})}if(n.method==="POST"&&t.pathname==="/chat")return Gt(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return Lt(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Wt(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return jt(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return Jt(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return re(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const i=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return re(n,e,i);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return J(i),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ne(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ne(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Ft(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return tn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local")return Kt(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return zt(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return en(n,e);if(n.method==="POST"&&t.pathname==="/complete")return nn(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return on(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return rn(n,e);if(n.method==="POST"&&t.pathname==="/update")return Bt(e);a(e,404,{error:"Not found"})}catch(o){a(e,500,{error:o?.message||String(o)})}});function h(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function an(n){let e="";const t=[];let r=!1,o=!1;const i=()=>{o&&!r&&!t.length&&process.exit(0)},l=async()=>{if(!r){for(r=!0;t.length;){const d=t.shift();let s;try{s=JSON.parse(d)}catch{continue}try{const c=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(s.id==null)continue;const u=(await c.text()).trim();u&&process.stdout.write(u+`
|
|
9
|
+
`)}async function G(t,e,n,o){try{const r=n(await f(t)),a=F(t,r.agent,r.options||{});if(a.error)throw new x(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new x(`Bad JSON: ${r.message}`):r)),null}}async function an(t,e){const n=await G(t,e,Ct,w);if(!n)return;if(!n.stream)try{const r=await T(n,()=>{},e);return i(e,200,kt(n.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,w(r))}M(e);const o=wt(n.requestedModel,r=>A(e,r));try{await T(n,r=>o.delta(r),e),o.done()}catch(r){A(e,w(r))}A(e,"[DONE]"),e.end()}async function sn(t,e){const n=await G(t,e,Ot,w);if(!n)return;if(!n.stream)try{const r=await T(n,()=>{},e);return i(e,200,Tt(n.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,w(r))}M(e);const o=bt(n.requestedModel,r=>A(e,r));try{await T(n,r=>o.delta(r),e),o.done()}catch(r){A(e,w(r))}A(e,"[DONE]"),e.end()}async function cn(t,e){const n=await G(t,e,At,w);if(!n)return;if(!n.stream)try{const r=await T(n,()=>{},e);return i(e,200,vt(n.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,w(r))}M(e);const o=Pt(n.requestedModel,r=>B(e,r.type,r));try{await T(n,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...w(r)};B(e,"error",a)}e.end()}async function ln(t,e){const n=await G(t,e,Et,j);if(!n)return;if(!n.stream)try{const r=await T(n,()=>{},e);return i(e,200,St(n.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,j(r))}M(e);const o=yt(n.requestedModel,(r,a)=>B(e,r,a));try{await T(n,r=>o.delta(r),e),o.done()}catch(r){B(e,"error",j(r))}e.end()}async function dn(t,e){let n={};try{n=await f(t)||{}}catch{}const o=String(n.id||"").trim(),r=o?pt(o,"stopped"):!1;return r&&d("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function ue(t,e,n){let o;try{o=await f(t)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=n?Y(n):Fe(),a=s=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:s})},l=(s,c)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:s,message:c}});if(o.id==null)return e.writeHead(202),e.end();if(o.method==="initialize")return a({protocolVersion:o.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const m=Le();if(o.method==="tools/list"){const s=r?r.specs.map(c=>({name:c.name,description:c.description,inputSchema:c.parameters||{type:"object",properties:{}}})):[];return a({tools:[...m,...s]})}if(o.method==="tools/call"){const s=await je(o.params?.name,o.params?.arguments||{});if(s)return a(s);if(!r)return l(-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 Je(r,o.params?.name,o.params?.arguments||{}))}catch(c){return a({content:[{type:"text",text:`error: ${c?.message||c}`}],isError:!0})}}return l(-32601,`Method not found: ${o.method}`)}async function un(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=n.server||{},r=n.message;if(!o.command||!r)return i(e,400,{error:"need server.command and message"});try{const a=await ht({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd},r);return r.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function hn(t,e){let n;try{n=await f(t)}catch(u){return i(e,400,{error:"Bad JSON: "+u.message})}const{url:o,headers:r,message:a}=n||{};if(!o||!a)return i(e,400,{error:"need url and message"});let l;try{l=ne(o)}catch(u){return i(e,400,{error:String(u?.message||u)})}const m={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[u,b]of Object.entries(r)){const p=u.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(p)||p.startsWith("x-"))&&(m[u]=String(b))}const s=new AbortController,c=setTimeout(()=>s.abort(),3e4);try{const u=await fetch(l.href,{method:"POST",headers:m,body:JSON.stringify(a),redirect:"follow",signal:s.signal});try{u.url&&ne(u.url)}catch(p){return i(e,400,{error:String(p?.message||p)})}const b=await u.text().catch(()=>"");return i(e,200,{status:u.status,sessionId:u.headers.get("Mcp-Session-Id")||null,contentType:u.headers.get("Content-Type")||"",body:b})}catch(u){const b=u?.name==="AbortError"?"timed out":String(u?.message||u);return i(e,502,{error:`couldn't reach MCP server ${l.host}: ${b}`})}finally{clearTimeout(c)}}const he=256*1024,pn=5,mn=8e3;async function fn(t){let e=re(t);const n=new AbortController,o=setTimeout(()=>n.abort(),mn);try{for(let r=0;r<=pn;r++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:n.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${g} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=re(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 l=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(l)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:wn(await gn(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function gn(t){if(!t.body?.getReader)return(await t.text().catch(()=>"")).slice(0,he);const e=t.body.getReader(),n=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:a,value:l}=await e.read();if(a||(r+=l.byteLength,o+=n.decode(l,{stream:!0}),/<\/title\s*>/i.test(o)||r>=he))break}}finally{try{await e.cancel()}catch{}}return o}function yn(t){return String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,n)=>{try{return String.fromCodePoint(+n)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,n)=>{try{return String.fromCodePoint(parseInt(n,16))}catch{return""}})}function wn(t){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(t);return e?yn(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function bn(t,e){let n;try{n=await f(t)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=n&&n.url;if(!o||typeof o!="string")return i(e,400,{error:"need url"});try{const r=await fn(o);return i(e,200,{title:r.title||null,url:r.url||o})}catch(r){const a=r?.name==="AbortError"?"timed out":String(r?.message||r);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function Sn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=Y(n.session);if(!o)return i(e,404,{error:"no such session"});const r=o.pending.get(n.id);return r?(o.pending.delete(n.id),r.resolve(n.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function kn(t,e){let n;try{n=await f(t)}catch(s){return i(e,400,{error:"Bad JSON: "+s.message})}const o=E[n.agent];if(!o)return i(e,404,{error:`Unknown agent "${n.agent}"`});const r=String(n.prompt||"").slice(0,6e3);if(!r)return i(e,400,{error:"Empty prompt"});const a=n.model||"",l=F(t,n.agent,{model:a});if(l.error)return i(e,403,{error:l.error});const m=String(n.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 o.engine.complete=="function"?s=await o.engine.complete({prompt:r,system:m,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:m,options:l.options},c=>{c.type==="delta"?s+=c.text||"":c.type==="done"&&c.text&&(s+=c.text)}),i(e,200,{text:(s||"").trim()})}catch(s){return i(e,502,{error:s?.message||String(s)})}}async function Tn(t,e){let n;try{n=await f(t)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=E[n.agent];if(!o)return i(e,404,{error:`Unknown agent "${n.agent}"`});if(typeof o.engine.listModels!="function")return i(e,200,{models:[]});try{const r=await o.engine.listModels(n.options||{});return i(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return i(e,502,{error:r?.message||String(r)})}}async function vn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(n.command||"").trim();if(!o)return i(e,400,{error:"No command"});let r=null;try{r=lt(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}const pe=fe(async(t,e)=>{if(Bt(t,e),t.method==="OPTIONS")return e.writeHead(204),e.end();let n;try{n=new URL(t.url,`http://${t.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const o=zt(t,n.pathname);if(o)return i(e,403,{error:o});try{if(t.method==="GET"&&n.pathname==="/health")return Xt(e);const r=n.searchParams.getAll("dir");if(t.method==="GET"&&n.pathname==="/skills")return Yt(e,r);if(t.method==="GET"&&n.pathname==="/skills-quarantined")return Qt(e,r);if(t.method==="GET"&&n.pathname.startsWith("/skills/")){const a=n.pathname.slice(8),l=a.indexOf("/file/");return l===-1?Zt(e,decodeURIComponent(a),r):qt(e,decodeURIComponent(a.slice(0,l)),decodeURIComponent(a.slice(l+6)),r)}if(n.pathname==="/connections"||n.pathname.startsWith("/connections/"))return rn(t,e,n.pathname);if(n.pathname==="/worktrees"||n.pathname.startsWith("/worktrees/"))return on(t,e,n.pathname);if(t.method==="GET"&&n.pathname==="/v1/models")return de(e);if(t.method==="GET"&&n.pathname.startsWith("/v1/models/"))return de(e,decodeURIComponent(n.pathname.slice(11)));if(t.method==="GET"&&n.pathname==="/debug"){const a=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:g,agents:Object.fromEntries(it.map(l=>[l,a?ee(l)||null:!!ee(l)])),...a?{home:P.homedir(),path:process.env.PATH}:{}})}if(t.method==="POST"&&n.pathname==="/chat")return nn(t,e);if(t.method==="POST"&&n.pathname==="/pair")return Lt(t,e);if(t.method==="POST"&&n.pathname==="/pair/code")return Dt(e);if(t.method==="POST"&&n.pathname==="/whoami")return jt(t,e);if(t.method==="POST"&&n.pathname==="/v1/chat/completions")return an(t,e);if(t.method==="POST"&&n.pathname==="/v1/completions")return sn(t,e);if(t.method==="POST"&&n.pathname==="/v1/responses")return cn(t,e);if(t.method==="POST"&&n.pathname==="/v1/messages")return ln(t,e);if(n.pathname==="/mcp"){if(t.method==="POST")return ue(t,e,null);if(t.method==="GET")return e.writeHead(405),e.end()}if(n.pathname.startsWith("/mcp/")){const a=decodeURIComponent(n.pathname.slice(5));if(t.method==="POST")return ue(t,e,a);if(t.method==="GET")return e.writeHead(405),e.end();if(t.method==="DELETE")return X(a),e.writeHead(204),e.end()}if(t.method==="GET"&&n.pathname==="/channels")return ce(t,e,"status");if(t.method==="POST"&&n.pathname.startsWith("/channels/"))return ce(t,e,n.pathname.slice(10));if(t.method==="POST"&&n.pathname==="/cancel")return dn(t,e);if(t.method==="POST"&&n.pathname==="/tool-result")return Sn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-local")return un(t,e);if(t.method==="POST"&&n.pathname==="/mcp-remote")return hn(t,e);if(t.method==="POST"&&n.pathname==="/fetch-title")return bn(t,e);if(t.method==="POST"&&n.pathname==="/complete")return kn(t,e);if(t.method==="POST"&&n.pathname==="/list-models")return Tn(t,e);if(t.method==="POST"&&n.pathname==="/agent-check")return vn(t,e);if(t.method==="POST"&&n.pathname==="/update")return tn(e);i(e,404,{error:"Not found"})}catch(r){i(e,500,{error:r?.message||String(r)})}});function d(t,e){(t==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function En(t){let e="";const n=[];let o=!1,r=!1;const a=()=>{r&&!o&&!n.length&&process.exit(0)},l=async()=>{if(!o){for(o=!0;n.length;){const m=n.shift();let s;try{s=JSON.parse(m)}catch{continue}try{const c=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:m});if(s.id==null)continue;const u=(await c.text()).trim();u&&process.stdout.write(u+`
|
|
10
10
|
`)}catch(c){s.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:s.id,error:{code:-32e3,message:String(c?.message||c)}})+`
|
|
11
|
-
`)}}
|
|
12
|
-
`))>=0;){const c=e.slice(0,s).trim();e=e.slice(s+1),c&&
|
|
11
|
+
`)}}o=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",m=>{e+=m;let s;for(;(s=e.indexOf(`
|
|
12
|
+
`))>=0;){const c=e.slice(0,s).trim();e=e.slice(s+1),c&&n.push(c)}l()}),process.stdin.on("end",()=>{r=!0,a()}),process.stdin.resume()}function Cn(){st(),ct(),Ut(),pe.on("error",t=>{t&&t.code==="EADDRINUSE"&&(d("error",`Port ${v} is already in use — another app (or a second bridge) has it.`),d("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)),d("error",`bridge server error: ${t?.message||t}`),process.exit(1)});for(const t of["SIGINT","SIGTERM"])process.on(t,()=>{const e=mt("shutdown");e&&d("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const n=ft("shutdown");n&&d("info",`shutdown: closed ${n} warm agent process${n===1?"":"es"}`),setTimeout(()=>process.exit(0),e||n?300:0).unref?.(),!e&&!n&&process.exit(0)});pe.listen(v,k,async()=>{d("info",`listening on http://${k}:${v}`),W.has(k)||d("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. 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:t,label:e,hidden:n}]of Object.entries(E)){if(n)continue;const o=await t.available().catch(()=>({ok:!1}));d("info",` ${o.ok?"✓":"✕"} ${e}${o.ok?"":" — "+(o.reason||"unavailable")}`)}d("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),se().then(t=>t.startIfConfigured()).then(t=>{t?.skipped||(t?.ok?d("info","channels: telegram connected — polling for messages"):d("error",`channels: telegram not started — ${t?.error||"unknown error"}`))}).catch(t=>d("error",`channels: ${t?.message||t}`))})}function On(){console.log(`ChatPanel Bridge v${g}
|
|
13
13
|
|
|
14
14
|
Usage:
|
|
15
|
-
chatpanel-bridge start the bridge (foreground) on ${k}:${
|
|
15
|
+
chatpanel-bridge start the bridge (foreground) on ${k}:${v}
|
|
16
16
|
chatpanel-bridge --install run automatically at login, in the background
|
|
17
17
|
chatpanel-bridge --uninstall remove the login auto-start
|
|
18
18
|
chatpanel-bridge --status show whether auto-start is set up
|
|
19
19
|
chatpanel-bridge --update download & install the latest version, then restart
|
|
20
20
|
chatpanel-bridge --version print the version
|
|
21
|
+
chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
|
|
21
22
|
|
|
22
|
-
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT`)}function
|
|
23
|
+
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT`)}function An(){const t=process.argv,e=(...n)=>n.some(o=>t.includes(o));if(e("--help","-h"))return On(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("pair","--pair"))return(async()=>{let n="";try{n=K(N,"utf8").trim()}catch{}const o=`http://${k}:${v}`;try{if(!n)throw new Error(`no token at ${N} — is the bridge running?`);const r=await fetch(`${o}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(2500)}),a=await r.json().catch(()=>({}));if(!r.ok)throw new Error(a.error||`HTTP ${r.status}`);console.log(`Pairing code: ${_t(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Bridge → "Pair this browser".')}catch(r){d("error",`could not get a pairing code from the bridge at ${o}: ${r?.message||r}`),process.exitCode=1}})(),!0;if(e("--install")){try{Re(),d("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(n){d("error","Install failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--uninstall")){try{_e(),d("info","Removed the login auto-start.")}catch(n){d("error","Uninstall failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--status")){let n=!1;try{n=He()}catch(o){d("error",String(o?.message||o))}return d("info",`auto-start: ${n?"installed":"not installed"}`),!0}return!1}const me=process.argv.indexOf("--mcp-stdio");if(me>=0){const t=process.argv[me+1];t||(console.error("--mcp-stdio requires a URL"),process.exit(1)),En(t)}else process.argv.includes("--update")?(async()=>{try{const t=await te(g);d("info",`Updated v${t.from} → v${t.to}. Restarting the background service…`),V()}catch(t){d("error","Update failed: "+(t?.message||t)),process.exitCode=1}})():An()||Cn();
|