@chatpanel/bridge 0.11.24 → 0.11.25
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 +7 -7
- package/package.json +1 -13
- package/scripts/sync-channels.mjs +8 -90
- package/scripts/sync-events.mjs +7 -78
- package/scripts/sync-pii.mjs +7 -68
- package/src/api-compat.js +5 -294
- package/src/channels/adapters/telegram.js +3 -298
- package/src/channels/bridge.js +1 -59
- package/src/channels/eventlog.js +3 -57
- package/src/channels/gateway.js +1 -114
- package/src/channels/invoke.js +1 -172
- package/src/channels/normalize.js +1 -58
- package/src/channels/pairing.js +1 -95
- package/src/channels/service.js +1 -329
- package/src/channels/stream.js +5 -104
- package/src/cli-errors.js +3 -136
- package/src/connections.js +1 -160
- package/src/connectors.js +1 -100
- package/src/engines/antigravity.js +5 -235
- package/src/engines/args.js +1 -47
- package/src/engines/claude.js +6 -586
- package/src/engines/cli-agents.js +7 -312
- package/src/engines/codex.js +6 -481
- package/src/engines/custom.js +17 -577
- package/src/engines/prompt.js +6 -32
- package/src/engines/stream-formats.js +2 -222
- package/src/entitlement.js +1 -77
- package/src/env.js +3 -628
- package/src/events/capability.js +1 -134
- package/src/events/event.js +1 -183
- package/src/events/reach.js +1 -31
- package/src/events/ref.js +1 -63
- package/src/events/scm-connection.js +1 -188
- package/src/events/scopes.js +1 -20
- package/src/events/skill-manifest.js +1 -338
- package/src/events/skill-scan.js +3 -217
- package/src/events/view.js +1 -96
- package/src/mcp-capabilities.js +2 -139
- package/src/mcp-local.js +0 -0
- package/src/mcp-quarantine.js +1 -110
- package/src/net.js +1 -107
- package/src/pii/index.js +1 -29
- package/src/pii/net.js +1 -111
- package/src/pii/pii-detect.js +2 -296
- package/src/pii/pii-redact.js +1 -470
- package/src/pii/pipeline.js +1 -137
- package/src/pii/sanitize.js +2 -179
- package/src/pii/tool-harness.js +1 -184
- package/src/pii/tool-rank.js +1 -110
- package/src/proc.js +2 -91
- package/src/relay-timeout.js +1 -21
- package/src/runs.js +1 -49
- package/src/sanitize.js +1 -7
- package/src/scm.js +1 -76
- package/src/server.js +10 -1492
- package/src/service.js +11 -176
- package/src/sign-in.js +1 -91
- package/src/skills.js +1 -399
- package/src/ssrf.js +1 -70
- package/src/update.js +1 -216
- package/src/workdir.js +1 -108
- package/src/worktree.js +3 -125
package/src/server.js
CHANGED
|
@@ -1,1504 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
// running on this machine (Claude Code, Codex and Antigravity, each via its CLI) to
|
|
4
|
-
// the ChatPanel Chrome extension. Zero runtime dependencies.
|
|
5
|
-
//
|
|
6
|
-
// GET /health → { ok, version, agents: [{id,label,available,reason,connectors}], update }
|
|
7
|
-
// POST /update → self-update to the latest release (compiled binary installs)
|
|
8
|
-
// POST /chat → Server-Sent Events stream of { type, ... }:
|
|
9
|
-
// {type:'delta', text} incremental assistant text
|
|
10
|
-
// {type:'tool', name, summary}
|
|
11
|
-
// {type:'status'|'reasoning', text?}
|
|
12
|
-
// {type:'workdir', path, isDefault} where this run writes
|
|
13
|
-
// {type:'scm', phase:'before'|'after', repo, remote?, branch, head, commits?}
|
|
14
|
-
// the checkout it worked in, when it is one
|
|
15
|
-
// {type:'workspace', path, branch, base, created, connection?}
|
|
16
|
-
// the worktree the run was given (options.workspace)
|
|
17
|
-
// {type:'done', text?} (text only if not streamed)
|
|
18
|
-
// {type:'error', error}
|
|
19
|
-
// POST /v1/chat/completions, /v1/completions, /v1/responses
|
|
20
|
-
// → OpenAI-compatible text adapters for the local agents
|
|
21
|
-
// POST /v1/messages → Anthropic-compatible text adapter for the local agents
|
|
22
|
-
// GET /connections → SCM connections on this machine (records; never a token)
|
|
23
|
-
// POST /connections → { connection, token? } save one; the token goes to the keychain
|
|
24
|
-
// POST /connections/<id>/test { remote? } · POST /connections/<id>/delete
|
|
25
|
-
// GET /worktrees → the job worktrees the bridge made · POST /worktrees/remove
|
|
26
|
-
// GET /skills → skill packages on disk (name + description + files)
|
|
27
|
-
// GET /skills/<name> → one skill, SKILL.md body included
|
|
28
|
-
// GET /skills/<name>/file/<path> → one reference/template/asset from that package
|
|
29
|
-
//
|
|
30
|
-
// Binds to 127.0.0.1 only. A request guard (see `guard()`) enforces a loopback
|
|
31
|
-
// Host (anti DNS-rebinding) and an allowlisted Origin; the command-spawning
|
|
32
|
-
// endpoints (/chat, /mcp-local, /update, …) additionally require the extension
|
|
33
|
-
// origin or the per-install bridge token, so a malicious web page can't drive
|
|
34
|
-
// local execution. The CLI-facing /mcp endpoints stay open to no-Origin clients.
|
|
2
|
+
import{createServer as de}from"node:http";import P from"node:os";import{randomUUID as ue,randomBytes as pe,timingSafeEqual as he}from"node:crypto";import{mkdirSync as me,writeFileSync as fe,readFileSync as ge,existsSync as ye}from"node:fs";import{join as N}from"node:path";import*as we from"./engines/claude.js";import*as be from"./engines/codex.js";import*as Se from"./engines/antigravity.js";import{pi as ke,opencode as Te,kiro as ve,copilot as Ce,deepseek as Ee,hermes as xe}from"./engines/cli-agents.js";import{connectorsFor as Oe}from"./connectors.js";import*as Ae from"./engines/custom.js";import{installService as Pe,uninstallService as $e,serviceStatus as Ie,restartService as J}from"./service.js";import{skillIndex as U,listRecords as Ne,readRecord as Re,readPackageFile as He,skillsHealth as _e,quarantinedSkills as Me}from"./skills.js";import{capabilityToolSpecs as Be,runCapabilityTool as Ge}from"./mcp-capabilities.js";import{relayTimeoutFor as Ue}from"./relay-timeout.js";import{DEFAULT_WORKSPACE as De,isDefaultWorkdir as Le,resolveWorkdir as je,writeScopeNote as We}from"./workdir.js";import{gitState as Fe,gitDelta as Je}from"./scm.js";import{listConnections as Ke,putConnection as ze,removeConnection as Ve,runEnvFor as Ye,testConnection as Xe,secretBackend as K}from"./connections.js";import{worktreeFor as z,listWorktrees as Qe,removeWorktree as Ze,withHook as qe,WORKTREE_ROOT as V}from"./worktree.js";import{AGENT_CLIS as et,enrichPath as tt,enrichAgentEnv as nt,findAgentBin as Y,resolveCommand as ot}from"./env.js";import{stripHidden as X}from"./sanitize.js";import{checkForUpdate as rt,selfUpdate as Q,isEmbedded as at}from"./update.js";import{callLocalMcp as it}from"./mcp-local.js";import{assertPublicHttpUrl as Z,assertPublicWebUrl as q}from"./ssrf.js";import{startRun as ee,endRun as D,cancelRun as st,cancelAll as ct}from"./runs.js";import{CompatError as R,anthropicError as L,anthropicStream as lt,chatCompletionStream as dt,completionStream as ut,createAnthropicMessage as pt,createChatCompletion as ht,createCompletion as mt,createResponse as ft,openAIError as w,parseAnthropicMessage as gt,parseChatCompletion as yt,parseCompletion as wt,parseResponse as bt,responseStream as St}from"./api-compat.js";const g="0.11.25",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",O=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,T={claude:{engine:we,label:"Claude Code"},codex:{engine:be,label:"Codex"},antigravity:{engine:Se,label:"Antigravity"},pi:{engine:ke,label:"Pi"},opencode:{engine:Te,label:"OpenCode"},hermes:{engine:xe,label:"Hermes"},kiro:{engine:ve,label:"Kiro"},copilot:{engine:Ce,label:"GitHub Copilot"},deepseek:{engine:Ee,label:"DeepSeek Harness"},custom:{engine:Ae,label:"Custom",hidden:!0}},v=new Map;let $=null;function kt(t,e){const n=ue(),r={id:n,emit:t,specs:e,pending:new Map,nextId:0};return v.set(n,r),$=n,r}function te(t){const e=v.get(t);if(e){for(const n of e.pending.values())n.reject(new Error("chat ended"));if(v.delete(t),$===t){const n=[...v.keys()];$=n.length?n[n.length-1]:null}}}function Tt(){return $&&v.get($)||null}function vt(t,e,n){return new Promise((r,o)=>{const i=`t${++t.nextId}`,s=setTimeout(()=>{t.pending.delete(i),o(new Error("tool call timed out"))},Ue(t.specs,e));t.pending.set(i,{resolve:d=>{clearTimeout(s),r(Ct(d))},reject:d=>{clearTimeout(s),o(d)}}),t.emit({type:"tool_request",session:t.id,id:i,name:e,input:n})})}function Ct(t){if(t==null)return{content:[{type:"text",text:"ok"}]};if(typeof t=="string")return{content:[{type:"text",text:X(t)}]};const e=[];if(t.text&&e.push({type:"text",text:X(String(t.text))}),typeof t.image=="string"){const n=/^data:([^;]+);base64,(.+)$/s.exec(t.image);n&&e.push({type:"image",data:n[2],mimeType:n[1]})}return e.length||e.push({type:"text",text:"ok"}),{content:e}}function ne(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]")}function Et(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 xt(t,e){const n=t.headers.origin||"",r=ne(n);e.setHeader("Access-Control-Allow-Origin",r?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 j=new Set(["127.0.0.1","localhost","::1"]);function Ot(t){if(!j.has(k))return!0;const e=String(t.headers.host||"");if(!e)return!1;const n=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return j.has(n)}const W=N(P.homedir(),".chatpanel","bridge-token");let C="";function At(){try{ye(W)&&(C=ge(W,"utf8").trim()),C||(C=pe(32).toString("hex"),me(N(P.homedir(),".chatpanel"),{recursive:!0}),fe(W,C,{mode:384}))}catch(t){u("error",`could not initialise bridge token: ${t?.message||t}`)}}let H=null;async function oe(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:N(P.homedir(),".chatpanel"),dataDir:N(P.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${O}`,token:C},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function re(t,e,n){try{const r=await oe(),o=t.method==="POST"?await f(t):{};if(n==="status")return a(e,200,await r.status());if(n==="connect"){const i=await r.connect(o);return a(e,200,{ok:!0,...i})}return n==="pair"?a(e,200,await r.pair()):n==="unpair"?a(e,200,await r.unpair(String(o.actorId||""))):n==="settings"?a(e,200,await r.update(o)):n==="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 Pt(t){if(!C)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 r=Buffer.from(n),o=Buffer.from(C);return r.length===o.length&&he(r,o)}const $t=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"]),It=new Set(["/debug"]),Nt=t=>It.has(t);function Rt(t,e){if(!Ot(t))return"forbidden host";const n=t.headers.origin||"";return n&&!ne(n)?"forbidden origin":(t.method==="POST"&&$t.has(e)||t.method==="GET"&&Nt(e))&&!(Et(n)||Pt(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":null}function a(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function f(t){return new Promise((e,n)=>{let r="";t.on("data",o=>{r+=o,r.length>50*1024*1024&&n(new Error("Body too large"))}),t.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){n(o)}}),t.on("error",n)})}async function Ht(t){const e=await Promise.all(Object.entries(T).filter(([,o])=>!o.hidden).map(async([o,{engine:i,label:s}])=>{const d=await i.available().catch(c=>({ok:!1,reason:String(c?.message||c)})),l=await Oe(o).catch(()=>[]);return{id:o,label:s,available:d.ok,reason:d.reason,connectors:l}})),n=at()?{current:g,updateAvailable:!1,embedded:"gateway"}:await rt(g).catch(()=>({current:g,updateAvailable:!1})),r=await _e().catch(()=>null);a(t,200,{ok:!0,version:g,agents:e,update:n,workspace:De,worktrees:V,secretBackend:K(),...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function _t(t,e){const{index:n,problems:r}=await U({extraDirs:e});a(t,200,{ok:!0,skills:Ne(n),problems:r})}async function Mt(t,e){a(t,200,{ok:!0,quarantined:await Me(e)})}async function Bt(t,e,n){const{index:r}=await U({extraDirs:n}),o=Re(r,e);if(!o)return a(t,404,{ok:!1,error:"unknown skill"});a(t,200,{ok:!0,skill:o})}async function Gt(t,e,n,r){const{index:o}=await U({extraDirs:r}),i=await He(o,e,n);if(i.error)return a(t,i.error==="unknown skill"?404:400,{ok:!1,error:i.error});a(t,200,{ok:!0,...i})}async function Ut(){return(await Promise.all(Object.entries(T).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 ae(t,e=""){const n=await Ut();if(e){const r=n.find(o=>o.id===e);return r?a(t,200,r):a(t,404,w(new R(`Model "${e}" not found`,404,"model")))}return a(t,200,{object:"list",data:n})}async function Dt(t){try{const e=await Q(g);a(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>J(),400))}catch(e){a(t,400,{ok:!1,error:String(e?.message||e)})}}async function Lt(t,e){let n;try{n=await f(t)}catch(h){return a(e,400,{error:"Bad JSON: "+h.message})}const r=T[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});Array.isArray(n.images)&&n.images.length&&u("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 o=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
|
|
35
3
|
|
|
36
|
-
|
|
37
|
-
import os from 'node:os';
|
|
38
|
-
import { randomUUID, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
39
|
-
import { mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
|
|
40
|
-
import { join } from 'node:path';
|
|
41
|
-
import * as claude from './engines/claude.js';
|
|
42
|
-
import * as codex from './engines/codex.js';
|
|
43
|
-
import * as antigravity from './engines/antigravity.js';
|
|
44
|
-
import { pi, opencode, kiro, copilot, deepseek , hermes } from './engines/cli-agents.js';
|
|
45
|
-
import { connectorsFor } from './connectors.js';
|
|
46
|
-
import * as custom from './engines/custom.js';
|
|
47
|
-
import { installService, uninstallService, serviceStatus, restartService } from './service.js';
|
|
48
|
-
import { skillIndex, listRecords, readRecord, readPackageFile, skillsHealth, quarantinedSkills } from './skills.js';
|
|
49
|
-
import { capabilityToolSpecs, runCapabilityTool } from './mcp-capabilities.js';
|
|
50
|
-
import { relayTimeoutFor } from './relay-timeout.js';
|
|
51
|
-
import { DEFAULT_WORKSPACE, isDefaultWorkdir, resolveWorkdir, writeScopeNote } from './workdir.js';
|
|
52
|
-
import { gitState, gitDelta } from './scm.js';
|
|
53
|
-
import { listConnections, putConnection, removeConnection, runEnvFor, testConnection, secretBackend } from './connections.js';
|
|
54
|
-
import { worktreeFor, listWorktrees, removeWorktree, withHook, WORKTREE_ROOT } from './worktree.js';
|
|
55
|
-
import { AGENT_CLIS, enrichPath, enrichAgentEnv, findAgentBin, resolveCommand } from './env.js';
|
|
56
|
-
import { stripHidden } from './sanitize.js';
|
|
57
|
-
import { checkForUpdate, selfUpdate, isEmbedded } from './update.js';
|
|
58
|
-
import { callLocalMcp } from './mcp-local.js';
|
|
59
|
-
import { assertPublicHttpUrl, assertPublicWebUrl } from './ssrf.js';
|
|
60
|
-
import { startRun, endRun, cancelRun, cancelAll, activeRuns } from './runs.js';
|
|
61
|
-
import {
|
|
62
|
-
CompatError,
|
|
63
|
-
anthropicError,
|
|
64
|
-
anthropicStream,
|
|
65
|
-
chatCompletionStream,
|
|
66
|
-
completionStream,
|
|
67
|
-
createAnthropicMessage,
|
|
68
|
-
createChatCompletion,
|
|
69
|
-
createCompletion,
|
|
70
|
-
createResponse,
|
|
71
|
-
openAIError,
|
|
72
|
-
parseAnthropicMessage,
|
|
73
|
-
parseChatCompletion,
|
|
74
|
-
parseCompletion,
|
|
75
|
-
parseResponse,
|
|
76
|
-
responseStream,
|
|
77
|
-
} from './api-compat.js';
|
|
4
|
+
`)};let i=!1;const s=`run_${Math.random().toString(36).slice(2,10)}`,d=ee(s),l={signal:d.signal,abort:()=>d.cancel("client")},c=()=>{i=!0,d.cancel("disconnected")};t.on("close",c),e.on("close",c),e.on("error",c);const p=h=>{i||o(h)};o({type:"run",id:s});let m=null;if(n.options?.workspace&&typeof n.options.workspace=="object"){const h=n.options.workspace;if(m=await z({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),m.error){o({type:"error",error:`workspace: ${m.error}`}),D(s),e.writableEnded||e.end();return}}const b=m?m.path:je(n.options?.workingDir);let E=null;{const h=b,x=!!m||!Le(n.options?.workingDir),y=We(n.agent,n.options?.permissionMode,h);o({type:"workdir",path:h,isDefault:!x,writeScope:y||void 0}),o({type:"status",text:`Working in ${h}${x?"":" (default)"}`}),y&&o({type:"status",text:y}),E=await Fe(h),E&&o({type:"scm",phase:"before",...E})}let G=null;if(E||m){const h=Array.isArray(n.options?.grants)?n.options.grants:[],{env:x,connection:y}=Ye({remote:E?.remote||null,grants:h,branch:m?.branch||null,connectionId:n.options?.connectionId||null});G=qe(x),m&&o({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&o({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${x.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:x.CHATPANEL_SCM_PUSH}`})}const F={...n.options||{},...m?{workingDir:m.path}:{},...G?{runEnv:G}:{}};let I=null;n.pageTools?.specs?.length&&(I=kt(p,n.pageTools.specs),F.mcp={url:`http://${k}:${O}/mcp/${I.id}`,serverName:"chatpanel_browser",specs:n.pageTools.specs});try{await r.engine.chat({messages:Array.isArray(n.messages)?n.messages:[],system:n.system||"",options:F,images:Array.isArray(n.images)?n.images:[]},p,{signal:l.signal})}catch(h){u("error",`${n.agent} chat failed: ${h?.message||h}`),o({type:"error",error:h?.message||String(h)})}finally{if(!i){const h=await Je(b,E).catch(()=>null);h&&p({type:"scm",phase:"after",...h})}D(s),I&&te(I.id),e.writableEnded||e.end()}}async function jt(t,e,n){if(t.method==="GET"&&n==="/connections")return a(e,200,{ok:!0,connections:Ke(),secretBackend:K()});if(t.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await f(t);if(n==="/connections")try{return a(e,200,{ok:!0,connection:ze(r.connection||r,{token:r.token||null})})}catch(i){return a(e,400,{error:String(i?.message||i)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(n);return o?o[2]==="delete"?a(e,200,{ok:Ve(o[1])}):a(e,200,Xe(o[1],r.remote||"")):a(e,404,{error:"Not found"})}async function Wt(t,e,n){if(t.method==="GET"&&n==="/worktrees")return a(e,200,{ok:!0,root:V,worktrees:await Qe()});if(t.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await f(t);if(n==="/worktrees"){const o=await z({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return a(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(n==="/worktrees/remove"){const o=await Ze({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return a(e,o.ok?200:400,o)}return a(e,404,{error:"Not found"})}async function S(t,e,n){const r=T[t.agent];if(!r||r.hidden)throw new R(`Unknown ChatPanel agent "${t.agent}"`,400,"model");const o=await r.engine.available().catch(c=>({ok:!1,reason:c?.message||String(c)}));if(!o.ok)throw new R(o.reason||`${t.agent} is unavailable`,503,"model");const i=`run_${Math.random().toString(36).slice(2,10)}`,s=ee(i),d=()=>s.cancel("disconnected");n.on("close",d);let l="";try{return await r.engine.chat({messages:t.messages,system:t.system,options:t.options,images:[]},c=>{c?.type==="delta"&&c.text?(l+=c.text,e(c.text)):c?.type==="done"&&c.text&&!l&&(l=c.text,e(c.text))},{signal:s.signal}),l}finally{n.off("close",d),D(i)}}function _(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)}
|
|
78
5
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
// this drifts from package.json, so the two can't silently diverge.
|
|
82
|
-
const VERSION = '0.11.24';
|
|
83
|
-
const HOST = process.env.CHATPANEL_BRIDGE_HOST || '127.0.0.1';
|
|
84
|
-
const PORT = Number(process.env.CHATPANEL_BRIDGE_PORT) || 4319;
|
|
6
|
+
`)}function M(t,e,n){t.writableEnded||t.write(`event: ${e}
|
|
7
|
+
data: ${JSON.stringify(n)}
|
|
85
8
|
|
|
86
|
-
const ENGINES = {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
pi: { engine: pi, label: 'Pi' },
|
|
91
|
-
opencode: { engine: opencode, label: 'OpenCode' },
|
|
92
|
-
hermes: { engine: hermes, label: 'Hermes' },
|
|
93
|
-
kiro: { engine: kiro, label: 'Kiro' },
|
|
94
|
-
copilot: { engine: copilot, label: 'GitHub Copilot' },
|
|
95
|
-
deepseek: { engine: deepseek, label: 'DeepSeek Harness' },
|
|
96
|
-
// "Bring your own" — one engine drives any user-onboarded CLI (Pro). Hidden
|
|
97
|
-
// from /health (it's not a single installable agent; the extension manages the
|
|
98
|
-
// list and validates commands via /agent-check).
|
|
99
|
-
custom: { engine: custom, label: 'Custom', hidden: true },
|
|
100
|
-
};
|
|
101
|
-
|
|
102
|
-
// --------------------------------------------------------------------------
|
|
103
|
-
// Browser-tools relay. When the extension arms "Act on page" for a CLI agent, it
|
|
104
|
-
// sends the tool specs in /chat. We host an HTTP MCP server (/mcp/<session>) the
|
|
105
|
-
// CLI connects to; each tools/call is RELAYED to the extension over the chat SSE
|
|
106
|
-
// stream (a `tool_request` event), executed there (it owns the browser), and the
|
|
107
|
-
// result POSTed back to /tool-result. The bridge itself never touches the page.
|
|
108
|
-
// --------------------------------------------------------------------------
|
|
109
|
-
const sessions = new Map(); // sessionId -> { id, emit, specs, pending: Map, nextId }
|
|
110
|
-
let latestSessionId = null; // for the stable /mcp endpoint (CLIs configured once)
|
|
111
|
-
|
|
112
|
-
function createSession(emit, specs) {
|
|
113
|
-
const id = randomUUID();
|
|
114
|
-
const s = { id, emit, specs, pending: new Map(), nextId: 0 };
|
|
115
|
-
sessions.set(id, s);
|
|
116
|
-
latestSessionId = id;
|
|
117
|
-
return s;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
function deleteSession(id) {
|
|
121
|
-
const s = sessions.get(id);
|
|
122
|
-
if (!s) return;
|
|
123
|
-
for (const p of s.pending.values()) p.reject(new Error('chat ended'));
|
|
124
|
-
sessions.delete(id);
|
|
125
|
-
if (latestSessionId === id) {
|
|
126
|
-
// fall back to the most-recently-created surviving session, if any
|
|
127
|
-
const ids = [...sessions.keys()];
|
|
128
|
-
latestSessionId = ids.length ? ids[ids.length - 1] : null;
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
// The session a sessionless /mcp request maps to (CLIs configured once with a
|
|
133
|
-
// stable URL — e.g. `opencode mcp add chatpanel --url …/mcp`). The active chat.
|
|
134
|
-
function activeSession() {
|
|
135
|
-
return (latestSessionId && sessions.get(latestSessionId)) || null;
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
// Ask the extension to run a tool and await its result. Resolves to MCP content.
|
|
139
|
-
function relayToolCall(session, name, input) {
|
|
140
|
-
return new Promise((resolve, reject) => {
|
|
141
|
-
const id = `t${++session.nextId}`;
|
|
142
|
-
const timer = setTimeout(() => {
|
|
143
|
-
session.pending.delete(id);
|
|
144
|
-
reject(new Error('tool call timed out'));
|
|
145
|
-
}, relayTimeoutFor(session.specs, name)); // a team run declares its budget; see relay-timeout.js
|
|
146
|
-
session.pending.set(id, {
|
|
147
|
-
resolve: (result) => { clearTimeout(timer); resolve(toMcpContent(result)); },
|
|
148
|
-
reject: (e) => { clearTimeout(timer); reject(e); },
|
|
149
|
-
});
|
|
150
|
-
session.emit({ type: 'tool_request', session: session.id, id, name, input });
|
|
151
|
-
});
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
// The extension returns a string OR { text, image(dataURL) }; map to MCP content.
|
|
155
|
-
function toMcpContent(result) {
|
|
156
|
-
// L5: de-steganographize tool-result TEXT before it flows back to the CLI/model —
|
|
157
|
-
// the bridge is a public localhost endpoint, so (like the prompt path) it must strip
|
|
158
|
-
// ASCII-smuggled / bidi Unicode from relayed results, not assume the caller did.
|
|
159
|
-
if (result == null) return { content: [{ type: 'text', text: 'ok' }] };
|
|
160
|
-
if (typeof result === 'string') return { content: [{ type: 'text', text: stripHidden(result) }] };
|
|
161
|
-
const content = [];
|
|
162
|
-
if (result.text) content.push({ type: 'text', text: stripHidden(String(result.text)) });
|
|
163
|
-
if (typeof result.image === 'string') {
|
|
164
|
-
const m = /^data:([^;]+);base64,(.+)$/s.exec(result.image);
|
|
165
|
-
if (m) content.push({ type: 'image', data: m[2], mimeType: m[1] });
|
|
166
|
-
}
|
|
167
|
-
if (!content.length) content.push({ type: 'text', text: 'ok' });
|
|
168
|
-
return { content };
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
// --------------------------------------------------------------------------
|
|
172
|
-
// CORS — allow the extension (chrome-extension://…) and localhost dev origins.
|
|
173
|
-
// NOTE: CORS only controls whether a *page* may READ the response; it does NOT
|
|
174
|
-
// stop a cross-origin request from running. The hard allow/deny gating that
|
|
175
|
-
// actually protects the command-spawning endpoints lives in `guard()` below.
|
|
176
|
-
// --------------------------------------------------------------------------
|
|
177
|
-
function originAllowed(origin) {
|
|
178
|
-
return (
|
|
179
|
-
!origin ||
|
|
180
|
-
origin.startsWith('chrome-extension://') ||
|
|
181
|
-
origin.startsWith('moz-extension://') ||
|
|
182
|
-
origin.startsWith('http://localhost') ||
|
|
183
|
-
origin.startsWith('http://127.0.0.1') ||
|
|
184
|
-
origin.startsWith('http://[::1]')
|
|
185
|
-
);
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
// An origin that identifies the ChatPanel extension (or a local dev build).
|
|
189
|
-
// Distinct from originAllowed(): this REQUIRES the header to be present, so a
|
|
190
|
-
// no-Origin local process cannot pose as the extension on privileged routes.
|
|
191
|
-
function isExtensionOrigin(origin) {
|
|
192
|
-
return (
|
|
193
|
-
origin.startsWith('chrome-extension://') ||
|
|
194
|
-
origin.startsWith('moz-extension://') ||
|
|
195
|
-
origin.startsWith('http://localhost') ||
|
|
196
|
-
origin.startsWith('http://127.0.0.1') ||
|
|
197
|
-
origin.startsWith('http://[::1]')
|
|
198
|
-
);
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
function cors(req, res) {
|
|
202
|
-
const origin = req.headers.origin || '';
|
|
203
|
-
const allow = originAllowed(origin);
|
|
204
|
-
res.setHeader('Access-Control-Allow-Origin', allow ? origin || '*' : 'null');
|
|
205
|
-
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
|
206
|
-
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token');
|
|
207
|
-
res.setHeader('Vary', 'Origin');
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
// --------------------------------------------------------------------------
|
|
211
|
-
// Security gates — defend the localhost server against a malicious web page.
|
|
212
|
-
//
|
|
213
|
-
// Two browser attack classes are in scope even though we bind to 127.0.0.1:
|
|
214
|
-
// 1. DNS rebinding — a page on http://evil.example rebinds that name to
|
|
215
|
-
// 127.0.0.1 and fetches http://evil.example:PORT/…; the request arrives
|
|
216
|
-
// with Host: evil.example, which a naïve server happily serves.
|
|
217
|
-
// 2. Cross-origin CSRF — a page POSTs a CORS "simple" request (text/plain)
|
|
218
|
-
// to http://127.0.0.1:PORT/…; no preflight fires and the side effect runs.
|
|
219
|
-
//
|
|
220
|
-
// hostAllowed() closes (1) by rejecting any non-loopback Host. The Origin
|
|
221
|
-
// checks close (2). Privileged endpoints additionally require the extension
|
|
222
|
-
// origin or the per-install token, so a no-Origin local process can't drive
|
|
223
|
-
// command execution either.
|
|
224
|
-
// --------------------------------------------------------------------------
|
|
225
|
-
const LOOPBACK_HOSTNAMES = new Set(['127.0.0.1', 'localhost', '::1']);
|
|
226
|
-
|
|
227
|
-
function hostAllowed(req) {
|
|
228
|
-
// If the operator deliberately bound to a non-loopback/all interface
|
|
229
|
-
// (CHATPANEL_BRIDGE_HOST=0.0.0.0 / a LAN IP), don't second-guess their Host.
|
|
230
|
-
if (!LOOPBACK_HOSTNAMES.has(HOST)) return true;
|
|
231
|
-
const raw = String(req.headers.host || '');
|
|
232
|
-
if (!raw) return false; // HTTP/1.1 requires Host; absent → reject
|
|
233
|
-
const hostname = raw
|
|
234
|
-
.replace(/:\d+$/, '') // strip :port
|
|
235
|
-
.replace(/^\[|\]$/g, '') // strip IPv6 brackets
|
|
236
|
-
.toLowerCase();
|
|
237
|
-
return LOOPBACK_HOSTNAMES.has(hostname);
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
// Per-install bearer token — defense-in-depth so a non-browser local client can
|
|
241
|
-
// authenticate to privileged routes without relying on an Origin header. Written
|
|
242
|
-
// 0600 to ~/.chatpanel/bridge-token; the extension is allowed by origin and need
|
|
243
|
-
// not send it, so adding this never breaks the existing wire contract.
|
|
244
|
-
const TOKEN_PATH = join(os.homedir(), '.chatpanel', 'bridge-token');
|
|
245
|
-
let AUTH_TOKEN = '';
|
|
246
|
-
function ensureToken() {
|
|
247
|
-
try {
|
|
248
|
-
if (existsSync(TOKEN_PATH)) AUTH_TOKEN = readFileSync(TOKEN_PATH, 'utf8').trim();
|
|
249
|
-
if (!AUTH_TOKEN) {
|
|
250
|
-
AUTH_TOKEN = randomBytes(32).toString('hex');
|
|
251
|
-
mkdirSync(join(os.homedir(), '.chatpanel'), { recursive: true });
|
|
252
|
-
writeFileSync(TOKEN_PATH, AUTH_TOKEN, { mode: 0o600 });
|
|
253
|
-
}
|
|
254
|
-
} catch (e) {
|
|
255
|
-
// Token is optional hardening — never fail startup over it.
|
|
256
|
-
log('error', `could not initialise bridge token: ${e?.message || e}`);
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
// ---------------------------------------------------------------------------
|
|
260
|
-
// CHANNELS — a messaging surface (Telegram today) driving a local agent.
|
|
261
|
-
//
|
|
262
|
-
// Hosted HERE because a channel has to be running when nobody is looking: the point is to
|
|
263
|
-
// reach your machine from a phone with the browser closed, and the bridge is the only
|
|
264
|
-
// always-on local process a ChatPanel user already has. The alternative — a second daemon, or
|
|
265
|
-
// an npm install, or a service worker Chrome suspends — is another thing a non-technical
|
|
266
|
-
// person has to install and keep alive, which is the same as not shipping it.
|
|
267
|
-
//
|
|
268
|
-
// The bridge owns transport and auth; @chatpanel/channels (vendored to src/channels) owns the
|
|
269
|
-
// contract: verify a bot, hold its token 0600, enroll a phone by one-time code, cap it with
|
|
270
|
-
// `reach`, redact both ways. Loaded lazily so the redaction engine never touches a boot where
|
|
271
|
-
// no channel is configured.
|
|
272
|
-
let channelsSvc = null;
|
|
273
|
-
async function channelService() {
|
|
274
|
-
if (channelsSvc) return channelsSvc;
|
|
275
|
-
const { createChannelService } = await import('./channels/service.js');
|
|
276
|
-
channelsSvc = createChannelService({
|
|
277
|
-
home: join(os.homedir(), '.chatpanel'),
|
|
278
|
-
dataDir: join(os.homedir(), '.chatpanel', 'channels'),
|
|
279
|
-
// It talks to THIS bridge as a privileged local client — same port, same token it just
|
|
280
|
-
// read. No second address to configure and get wrong.
|
|
281
|
-
bridge: { baseUrl: `http://127.0.0.1:${PORT}`, token: AUTH_TOKEN },
|
|
282
|
-
logger: { log: (m) => log('info', m), warn: (m) => log('info', m), error: (m) => log('error', m) },
|
|
283
|
-
});
|
|
284
|
-
return channelsSvc;
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
async function handleChannels(req, res, action) {
|
|
288
|
-
try {
|
|
289
|
-
const svc = await channelService();
|
|
290
|
-
const body = req.method === 'POST' ? await readBody(req) : {};
|
|
291
|
-
if (action === 'status') return json(res, 200, await svc.status());
|
|
292
|
-
if (action === 'connect') {
|
|
293
|
-
// The token is verified with Telegram before it is written, so a typo fails HERE, in the
|
|
294
|
-
// settings screen, with a reason — not later as a silent poll loop nobody reads the logs of.
|
|
295
|
-
const r = await svc.connect(body);
|
|
296
|
-
return json(res, 200, { ok: true, ...r });
|
|
297
|
-
}
|
|
298
|
-
if (action === 'pair') return json(res, 200, await svc.pair());
|
|
299
|
-
if (action === 'unpair') return json(res, 200, await svc.unpair(String(body.actorId || '')));
|
|
300
|
-
if (action === 'settings') return json(res, 200, await svc.update(body));
|
|
301
|
-
if (action === 'disconnect') return json(res, 200, await svc.stop({ forget: !!body.forget }));
|
|
302
|
-
return json(res, 404, { error: 'unknown channel action' });
|
|
303
|
-
} catch (e) {
|
|
304
|
-
// A readable reason, because every one of these is something a person can fix: a bad token,
|
|
305
|
-
// a bot not created yet, no network.
|
|
306
|
-
return json(res, 400, { error: e?.message || String(e) });
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
function tokenOk(req) {
|
|
311
|
-
if (!AUTH_TOKEN) return false;
|
|
312
|
-
const h = String(req.headers['authorization'] || '');
|
|
313
|
-
const provided = (h.startsWith('Bearer ')
|
|
314
|
-
? h.slice(7)
|
|
315
|
-
: String(req.headers['x-api-key'] || req.headers['x-chatpanel-token'] || '')).trim();
|
|
316
|
-
if (!provided) return false;
|
|
317
|
-
const a = Buffer.from(provided);
|
|
318
|
-
const b = Buffer.from(AUTH_TOKEN);
|
|
319
|
-
return a.length === b.length && timingSafeEqual(a, b);
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
// POST sinks that spawn local agents/commands or self-update, plus GET /debug
|
|
323
|
-
// (leaks PATH/home). Only the extension (allowlisted origin) or a token-bearing
|
|
324
|
-
// client may reach these. The CLI-facing /mcp and /mcp/<id> routes are NOT here:
|
|
325
|
-
// local coding-agent CLIs connect to them with no Origin header by design.
|
|
326
|
-
const PRIVILEGED_POST = new Set([
|
|
327
|
-
'/chat',
|
|
328
|
-
'/v1/chat/completions',
|
|
329
|
-
'/v1/completions',
|
|
330
|
-
'/v1/responses',
|
|
331
|
-
'/v1/messages',
|
|
332
|
-
'/mcp-local',
|
|
333
|
-
'/mcp-remote',
|
|
334
|
-
'/fetch-title',
|
|
335
|
-
'/complete',
|
|
336
|
-
'/list-models',
|
|
337
|
-
'/agent-check',
|
|
338
|
-
'/update',
|
|
339
|
-
'/tool-result',
|
|
340
|
-
// Cancelling someone else's run is a denial of service, small but real — and every other
|
|
341
|
-
// endpoint that touches a run is already guarded. An unauthenticated hole next to nine
|
|
342
|
-
// guarded neighbours is a hole regardless of how little it grants.
|
|
343
|
-
'/cancel',
|
|
344
|
-
// A channel is a way into this machine from the internet. Everything that configures one —
|
|
345
|
-
// and the code that enrolls a phone — is as privileged as /chat itself.
|
|
346
|
-
'/channels/connect',
|
|
347
|
-
'/channels/pair',
|
|
348
|
-
'/channels/unpair',
|
|
349
|
-
'/channels/settings',
|
|
350
|
-
'/channels/disconnect',
|
|
351
|
-
// An SCM connection holds a token for this machine's git; a worktree is a checkout the
|
|
352
|
-
// bridge makes. Both are as privileged as /chat.
|
|
353
|
-
'/connections',
|
|
354
|
-
'/worktrees',
|
|
355
|
-
]);
|
|
356
|
-
// /channels is NOT here, for the same reason /skills is not, and it was a regression to add
|
|
357
|
-
// it: a privileged GET is unreachable from the extension. The panel holds `<all_urls>`, so
|
|
358
|
-
// its fetches bypass CORS altogether — no preflight fires — and the Fetch spec attaches
|
|
359
|
-
// `Origin` only to requests whose method is not GET or HEAD. That is the whole asymmetry:
|
|
360
|
-
// every privileged POST here works, and a privileged GET can only ever answer the settings
|
|
361
|
-
// page with "forbidden: this endpoint requires the ChatPanel extension or a valid bridge
|
|
362
|
-
// token", which is what shipped in 0.11.0.
|
|
363
|
-
//
|
|
364
|
-
// Nothing is opened up by removing it. `originAllowed` still refuses any web page (it is the
|
|
365
|
-
// check doing the work), so the only caller admitted is a local no-Origin process — which can
|
|
366
|
-
// already read ~/.chatpanel/channels/ off the disk. /debug stays privileged: it exposes
|
|
367
|
-
// configuration a local process cannot otherwise see.
|
|
368
|
-
const PRIVILEGED_GET = new Set(['/debug']);
|
|
369
|
-
|
|
370
|
-
// /skills* is NOT privileged, and that is a considered position rather than a
|
|
371
|
-
// convenience. `privileged` adds exactly one thing over the origin allowlist: it requires
|
|
372
|
-
// the Origin header to be PRESENT, so a no-Origin local process cannot pose as the
|
|
373
|
-
// extension. Work through who that actually excludes for a read-only listing of files:
|
|
374
|
-
//
|
|
375
|
-
// • a web page — always sends Origin, and a non-allowed one is already refused above;
|
|
376
|
-
// • a page on http://localhost — sends Origin, which `isExtensionOrigin` already
|
|
377
|
-
// accepts, so the privileged check never stopped it either way;
|
|
378
|
-
// • a page using <img>/<script> to force a no-Origin GET — cannot read the response,
|
|
379
|
-
// because it is JSON with no CORS grant to that origin;
|
|
380
|
-
// • remote SSRF into 127.0.0.1 — arrives with a non-loopback Host and dies at
|
|
381
|
-
// `hostAllowed` long before this;
|
|
382
|
-
// • a local process — the only caller left, and it can read the very same SKILL.md
|
|
383
|
-
// files straight off the disk.
|
|
384
|
-
//
|
|
385
|
-
// So the requirement excluded nothing that could not already read the bytes, while
|
|
386
|
-
// breaking the one client that should have them: Chrome omits Origin on a simple GET from
|
|
387
|
-
// an extension page (the POST routes get it only because a JSON body forces a preflight).
|
|
388
|
-
// The origin allowlist stays and is what keeps web pages out. /debug remains privileged —
|
|
389
|
-
// it exposes configuration a local process cannot otherwise see.
|
|
390
|
-
const isPrivilegedGetPath = (p) => PRIVILEGED_GET.has(p);
|
|
391
|
-
|
|
392
|
-
// SSRF guard for /mcp-remote lives in ./ssrf.js (assertPublicHttpUrl). Loopback
|
|
393
|
-
// is allowed (the user's own localhost MCP server — the common "via bridge"
|
|
394
|
-
// case; the extension can reach it directly anyway), cloud metadata is always
|
|
395
|
-
// blocked, and other private/LAN ranges are blocked unless the operator sets
|
|
396
|
-
// CHATPANEL_BRIDGE_ALLOW_PRIVATE_HOSTS=1. Checked on the initial URL AND after
|
|
397
|
-
// any redirect.
|
|
398
|
-
|
|
399
|
-
// Returns an error code if the request must be blocked, else null.
|
|
400
|
-
function guard(req, pathname) {
|
|
401
|
-
if (!hostAllowed(req)) return 'forbidden host';
|
|
402
|
-
const origin = req.headers.origin || '';
|
|
403
|
-
if (origin && !originAllowed(origin)) return 'forbidden origin';
|
|
404
|
-
const privileged =
|
|
405
|
-
(req.method === 'POST' && PRIVILEGED_POST.has(pathname)) ||
|
|
406
|
-
(req.method === 'GET' && isPrivilegedGetPath(pathname));
|
|
407
|
-
if (privileged && !(isExtensionOrigin(origin) || tokenOk(req))) {
|
|
408
|
-
return 'forbidden: this endpoint requires the ChatPanel extension or a valid bridge token';
|
|
409
|
-
}
|
|
410
|
-
return null;
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
function json(res, code, obj) {
|
|
414
|
-
res.writeHead(code, { 'Content-Type': 'application/json' });
|
|
415
|
-
res.end(JSON.stringify(obj));
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
function readBody(req) {
|
|
419
|
-
return new Promise((resolve, reject) => {
|
|
420
|
-
let data = '';
|
|
421
|
-
req.on('data', (c) => {
|
|
422
|
-
data += c;
|
|
423
|
-
if (data.length > 50 * 1024 * 1024) reject(new Error('Body too large'));
|
|
424
|
-
});
|
|
425
|
-
req.on('end', () => {
|
|
426
|
-
try {
|
|
427
|
-
resolve(data ? JSON.parse(data) : {});
|
|
428
|
-
} catch (e) {
|
|
429
|
-
reject(e);
|
|
430
|
-
}
|
|
431
|
-
});
|
|
432
|
-
req.on('error', reject);
|
|
433
|
-
});
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
// --------------------------------------------------------------------------
|
|
437
|
-
// Routes
|
|
438
|
-
// --------------------------------------------------------------------------
|
|
439
|
-
async function handleHealth(res) {
|
|
440
|
-
const agents = await Promise.all(
|
|
441
|
-
Object.entries(ENGINES)
|
|
442
|
-
.filter(([, e]) => !e.hidden)
|
|
443
|
-
.map(async ([id, { engine, label }]) => {
|
|
444
|
-
const a = await engine.available().catch((e) => ({ ok: false, reason: String(e?.message || e) }));
|
|
445
|
-
// WHAT THIS AGENT CAN ALREADY REACH, so the client stops guessing. A CLI agent brings
|
|
446
|
-
// its own connectors — a Slack MCP, a Jira MCP — that the extension cannot see, and
|
|
447
|
-
// an agent that was never told it may use them answers "go and look it up yourself".
|
|
448
|
-
// NAMES ONLY: a server's name is what a prompt needs; its URL, argv and env are what
|
|
449
|
-
// a leak would be made of. Additive, so an older extension ignores it.
|
|
450
|
-
const connectors = await connectorsFor(id).catch(() => []);
|
|
451
|
-
return { id, label, available: a.ok, reason: a.reason, connectors };
|
|
452
|
-
}),
|
|
453
|
-
);
|
|
454
|
-
// A bridge embedded in the gateway is whatever version the gateway shipped: the gateway's
|
|
455
|
-
// update is its update, so the check is not made and no client offers to update it here.
|
|
456
|
-
const update = isEmbedded() ? { current: VERSION, updateAvailable: false, embedded: 'gateway' }
|
|
457
|
-
: await checkForUpdate(VERSION).catch(() => ({ current: VERSION, updateAvailable: false }));
|
|
458
|
-
// ADDITIVE, and the client's only way to know this bridge can host skill packages —
|
|
459
|
-
// an older bridge simply omits it, which is what stops a newer extension assuming the
|
|
460
|
-
// endpoints exist. Never let a scan failure cost the caller its health check.
|
|
461
|
-
const skills = await skillsHealth().catch(() => null);
|
|
462
|
-
// So Settings can show what a blank "Working directory" actually resolves to, instead
|
|
463
|
-
// of leaving the user to discover it from where their files did not appear.
|
|
464
|
-
json(res, 200, {
|
|
465
|
-
ok: true, version: VERSION, agents, update,
|
|
466
|
-
workspace: DEFAULT_WORKSPACE,
|
|
467
|
-
// Where job worktrees go and where a connection's token is kept — additive.
|
|
468
|
-
worktrees: WORKTREE_ROOT, secretBackend: secretBackend(),
|
|
469
|
-
// WHO STARTED THIS PROCESS — additive. ChatPanel Desktop sets CHATPANEL_MANAGED_BY=desktop on
|
|
470
|
-
// the login service it registers; a client can then say so instead of offering install.sh.
|
|
471
|
-
...(process.env.CHATPANEL_MANAGED_BY ? { managedBy: String(process.env.CHATPANEL_MANAGED_BY).slice(0, 32) } : {}),
|
|
472
|
-
...(skills ? { skills } : {}),
|
|
473
|
-
});
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
// --------------------------------------------------------------------------
|
|
477
|
-
// Skill packages (F6 S2). Read-only: the store serves what is already on disk.
|
|
478
|
-
// Installing FROM a hub waits for the scanner — a write endpoint that lands before
|
|
479
|
-
// the gate is a window in which unscanned packages can be written, and windows like
|
|
480
|
-
// that do not close on schedule.
|
|
481
|
-
//
|
|
482
|
-
// The three routes are the progressive-disclosure ladder, so a client pays for a
|
|
483
|
-
// skill's body only when it picks one, and for a reference file only when it needs it.
|
|
484
|
-
// --------------------------------------------------------------------------
|
|
485
|
-
async function handleSkillsList(res, extraDirs) {
|
|
486
|
-
const { index, problems } = await skillIndex({ extraDirs });
|
|
487
|
-
json(res, 200, { ok: true, skills: listRecords(index), problems });
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
async function handleSkillsQuarantined(res, extraDirs) {
|
|
491
|
-
json(res, 200, { ok: true, quarantined: await quarantinedSkills(extraDirs) });
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
async function handleSkillRead(res, name, extraDirs) {
|
|
495
|
-
const { index } = await skillIndex({ extraDirs });
|
|
496
|
-
const skill = readRecord(index, name);
|
|
497
|
-
if (!skill) return json(res, 404, { ok: false, error: 'unknown skill' });
|
|
498
|
-
json(res, 200, { ok: true, skill });
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
async function handleSkillFile(res, name, relPath, extraDirs) {
|
|
502
|
-
const { index } = await skillIndex({ extraDirs });
|
|
503
|
-
const out = await readPackageFile(index, name, relPath);
|
|
504
|
-
// One shape for every refusal: a caller learns that it may not have the file, not
|
|
505
|
-
// whether the path exists, which is the difference between an error and an oracle.
|
|
506
|
-
if (out.error) return json(res, out.error === 'unknown skill' ? 404 : 400, { ok: false, error: out.error });
|
|
507
|
-
json(res, 200, { ok: true, ...out });
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
async function compatibleModels() {
|
|
511
|
-
const rows = await Promise.all(
|
|
512
|
-
Object.entries(ENGINES)
|
|
513
|
-
.filter(([, entry]) => !entry.hidden)
|
|
514
|
-
.map(async ([id, entry]) => ({
|
|
515
|
-
id,
|
|
516
|
-
object: 'model',
|
|
517
|
-
created: 0,
|
|
518
|
-
owned_by: 'chatpanel',
|
|
519
|
-
available: !!(await entry.engine.available().catch(() => ({ ok: false }))).ok,
|
|
520
|
-
})),
|
|
521
|
-
);
|
|
522
|
-
return rows.filter((row) => row.available).map(({ available, ...row }) => row);
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
async function handleCompatibleModels(res, modelId = '') {
|
|
526
|
-
const models = await compatibleModels();
|
|
527
|
-
if (modelId) {
|
|
528
|
-
const model = models.find((row) => row.id === modelId);
|
|
529
|
-
return model ? json(res, 200, model) : json(res, 404, openAIError(new CompatError(`Model "${modelId}" not found`, 404, 'model')));
|
|
530
|
-
}
|
|
531
|
-
return json(res, 200, { object: 'list', data: models });
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
// POST /update — self-update (compiled-binary installs). Swaps the binary, replies,
|
|
535
|
-
// then restarts the service into the new version. npm installs get instructions.
|
|
536
|
-
async function handleUpdate(res) {
|
|
537
|
-
try {
|
|
538
|
-
const result = await selfUpdate(VERSION); // throws on npm install / no update / failure
|
|
539
|
-
json(res, 200, { ok: true, updated: true, from: result.from, to: result.to });
|
|
540
|
-
res.on('finish', () => setTimeout(() => restartService(), 400));
|
|
541
|
-
} catch (e) {
|
|
542
|
-
json(res, 400, { ok: false, error: String(e?.message || e) });
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
|
|
546
|
-
async function handleChat(req, res) {
|
|
547
|
-
let body;
|
|
548
|
-
try {
|
|
549
|
-
body = await readBody(req);
|
|
550
|
-
} catch (e) {
|
|
551
|
-
return json(res, 400, { error: 'Bad JSON: ' + e.message });
|
|
552
|
-
}
|
|
553
|
-
const target = ENGINES[body.agent];
|
|
554
|
-
if (!target) return json(res, 404, { error: `Unknown agent "${body.agent}"` });
|
|
555
|
-
if (Array.isArray(body.images) && body.images.length) {
|
|
556
|
-
log('info', `chat: ${body.agent} received ${body.images.length} image(s)`);
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
// Open the SSE stream.
|
|
560
|
-
res.writeHead(200, {
|
|
561
|
-
'Content-Type': 'text/event-stream',
|
|
562
|
-
'Cache-Control': 'no-cache',
|
|
563
|
-
Connection: 'keep-alive',
|
|
564
|
-
});
|
|
565
|
-
const emit = (obj) => {
|
|
566
|
-
if (!res.writableEnded) res.write(`data: ${JSON.stringify(obj)}\n\n`);
|
|
567
|
-
};
|
|
568
|
-
|
|
569
|
-
// If the client disconnects (Stop, or the panel closes), stop caring about late
|
|
570
|
-
// writes AND abort the run so the engine kills its CLI child instead of letting it
|
|
571
|
-
// finish in the background. Older engines ignore the signal (harmless); the spawn
|
|
572
|
-
// engines honor it via killOnAbort.
|
|
573
|
-
let closed = false;
|
|
574
|
-
// A run id the client can cancel BY NAME. Emitted first, before anything else, so Stop
|
|
575
|
-
// works from the first millisecond rather than from whenever the engine gets going.
|
|
576
|
-
const runId = `run_${Math.random().toString(36).slice(2, 10)}`;
|
|
577
|
-
const run = startRun(runId);
|
|
578
|
-
const ac = { signal: run.signal, abort: () => run.cancel('client') };
|
|
579
|
-
// BOTH close events. On a request whose body was already consumed, req 'close' does not
|
|
580
|
-
// reliably signal a client disconnect — res 'close' does. Keeping both means a panel that
|
|
581
|
-
// crashes or is closed still tears the CLI down, while the Stop button no longer depends
|
|
582
|
-
// on either of them.
|
|
583
|
-
const onGone = () => { closed = true; run.cancel('disconnected'); };
|
|
584
|
-
req.on('close', onGone);
|
|
585
|
-
res.on('close', onGone);
|
|
586
|
-
res.on('error', onGone);
|
|
587
|
-
|
|
588
|
-
const safeEmit = (obj) => { if (!closed) emit(obj); };
|
|
589
|
-
emit({ type: 'run', id: runId });
|
|
590
|
-
|
|
591
|
-
// WHERE THIS RUN WILL WRITE, said before it starts. "The agent created a file and I
|
|
592
|
-
// cannot find it" was the single most confusing thing about a CLI agent, and the answer
|
|
593
|
-
// used to depend on which engine answered — the filesystem root, the home directory, or
|
|
594
|
-
// a temp folder the OS clears on its own schedule. Now there is one answer and it is
|
|
595
|
-
// announced. Additive: a client that does not know `workdir` ignores it, and the same
|
|
596
|
-
// information is repeated as a `status` line, which every client already renders.
|
|
597
|
-
// AND WHICH CHECKOUT, when the directory is one (scm.js): the repo, branch and HEAD before
|
|
598
|
-
// the agent starts, and after it ends what moved — so the team runner can put "worked on
|
|
599
|
-
// cp/p/j, 2 commits" on the task and the agent's record, not "it said it committed".
|
|
600
|
-
// A JOB'S WORKTREE, when the run names one (architecture-pillars.md §14.2):
|
|
601
|
-
// options.workspace = { repo, projectId, jobId, base? } → a checkout of its own on
|
|
602
|
-
// cp/<project>/<job>, which becomes the working directory. A worktree that cannot be
|
|
603
|
-
// made ends the run here — an Implementer must not fall back to the main checkout.
|
|
604
|
-
let workspace = null;
|
|
605
|
-
if (body.options?.workspace && typeof body.options.workspace === 'object') {
|
|
606
|
-
const w = body.options.workspace;
|
|
607
|
-
workspace = await worktreeFor({ repo: w.repo, projectId: w.projectId, jobId: w.jobId, base: w.base || null });
|
|
608
|
-
if (workspace.error) { emit({ type: 'error', error: `workspace: ${workspace.error}` }); endRun(runId); if (!res.writableEnded) res.end(); return; }
|
|
609
|
-
}
|
|
610
|
-
const workdir = workspace ? workspace.path : resolveWorkdir(body.options?.workingDir);
|
|
611
|
-
let scmBefore = null;
|
|
612
|
-
{
|
|
613
|
-
const dir = workdir;
|
|
614
|
-
const chosen = !!workspace || !isDefaultWorkdir(body.options?.workingDir);
|
|
615
|
-
const scope = writeScopeNote(body.agent, body.options?.permissionMode, dir);
|
|
616
|
-
emit({ type: 'workdir', path: dir, isDefault: !chosen, writeScope: scope || undefined });
|
|
617
|
-
emit({ type: 'status', text: `Working in ${dir}${chosen ? '' : ' (default)'}` });
|
|
618
|
-
if (scope) emit({ type: 'status', text: scope });
|
|
619
|
-
scmBefore = await gitState(dir);
|
|
620
|
-
if (scmBefore) emit({ type: 'scm', phase: 'before', ...scmBefore });
|
|
621
|
-
}
|
|
622
|
-
// THE CREDENTIAL AND THE LEASH, for this process only (connections.js, worktree.js): the
|
|
623
|
-
// token of the connection that matches the checkout's remote, scoped to its host in the
|
|
624
|
-
// spawned process's environment; the pre-push hook that keeps a push on the job's own
|
|
625
|
-
// branch, or refuses every push when the role has no scm:push. Nothing is written to the
|
|
626
|
-
// repository or the user's git config. Said on the stream, minus the secret.
|
|
627
|
-
let runEnv = null;
|
|
628
|
-
if (scmBefore || workspace) {
|
|
629
|
-
const grants = Array.isArray(body.options?.grants) ? body.options.grants : [];
|
|
630
|
-
const { env, connection } = runEnvFor({ remote: scmBefore?.remote || null, grants, branch: workspace?.branch || null, connectionId: body.options?.connectionId || null });
|
|
631
|
-
runEnv = withHook(env);
|
|
632
|
-
if (workspace) emit({ type: 'workspace', path: workspace.path, branch: workspace.branch, base: workspace.base, created: workspace.created, repo: workspace.repo, ...(connection ? { connection } : {}) });
|
|
633
|
-
if (connection) emit({ type: 'status', text: `Git credential: ${connection.kind} · ${connection.host}${connection.hasSecret ? '' : ' (no token stored)'} · push: ${env.CHATPANEL_SCM_PUSH === 'own' ? `${workspace?.branch} only` : env.CHATPANEL_SCM_PUSH}` });
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
// Browser-tools relay: when the extension sends page-tool specs, host an MCP
|
|
637
|
-
// server for this turn and tell the engine to point the CLI at it.
|
|
638
|
-
const options = { ...(body.options || {}), ...(workspace ? { workingDir: workspace.path } : {}), ...(runEnv ? { runEnv } : {}) };
|
|
639
|
-
let session = null;
|
|
640
|
-
if (body.pageTools?.specs?.length) {
|
|
641
|
-
session = createSession(safeEmit, body.pageTools.specs);
|
|
642
|
-
options.mcp = {
|
|
643
|
-
url: `http://${HOST}:${PORT}/mcp/${session.id}`,
|
|
644
|
-
serverName: 'chatpanel_browser',
|
|
645
|
-
specs: body.pageTools.specs,
|
|
646
|
-
};
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
try {
|
|
650
|
-
await target.engine.chat(
|
|
651
|
-
{
|
|
652
|
-
messages: Array.isArray(body.messages) ? body.messages : [],
|
|
653
|
-
system: body.system || '',
|
|
654
|
-
options,
|
|
655
|
-
images: Array.isArray(body.images) ? body.images : [],
|
|
656
|
-
},
|
|
657
|
-
safeEmit,
|
|
658
|
-
{ signal: ac.signal },
|
|
659
|
-
);
|
|
660
|
-
} catch (e) {
|
|
661
|
-
log('error', `${body.agent} chat failed: ${e?.message || e}`);
|
|
662
|
-
emit({ type: 'error', error: e?.message || String(e) });
|
|
663
|
-
} finally {
|
|
664
|
-
// What the run left in the checkout — said before the stream closes, so a client that
|
|
665
|
-
// already has the answer still gets the commits. A run that was cancelled is looked at
|
|
666
|
-
// too: the commits it made before Stop are real.
|
|
667
|
-
if (!closed) {
|
|
668
|
-
const after = await gitDelta(workdir, scmBefore).catch(() => null);
|
|
669
|
-
if (after) safeEmit({ type: 'scm', phase: 'after', ...after });
|
|
670
|
-
}
|
|
671
|
-
endRun(runId);
|
|
672
|
-
if (session) deleteSession(session.id);
|
|
673
|
-
if (!res.writableEnded) res.end();
|
|
674
|
-
}
|
|
675
|
-
}
|
|
676
|
-
|
|
677
|
-
// --- SCM connections and job worktrees (architecture-pillars.md §14) ---------------------
|
|
678
|
-
// GET is open like /skills (the panel's GET carries no Origin); every write is a POST and
|
|
679
|
-
// privileged. A token arrives in a POST body once, goes to the keychain, and is never
|
|
680
|
-
// returned — a client learns only `hasSecret`.
|
|
681
|
-
async function handleConnections(req, res, pathname) {
|
|
682
|
-
if (req.method === 'GET' && pathname === '/connections') return json(res, 200, { ok: true, connections: listConnections(), secretBackend: secretBackend() });
|
|
683
|
-
if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' });
|
|
684
|
-
const body = await readBody(req);
|
|
685
|
-
if (pathname === '/connections') {
|
|
686
|
-
try { return json(res, 200, { ok: true, connection: putConnection(body.connection || body, { token: body.token || null }) }); }
|
|
687
|
-
catch (e) { return json(res, 400, { error: String(e?.message || e) }); }
|
|
688
|
-
}
|
|
689
|
-
const m = /^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(pathname);
|
|
690
|
-
if (!m) return json(res, 404, { error: 'Not found' });
|
|
691
|
-
if (m[2] === 'delete') return json(res, 200, { ok: removeConnection(m[1]) });
|
|
692
|
-
return json(res, 200, testConnection(m[1], body.remote || ''));
|
|
693
|
-
}
|
|
694
|
-
async function handleWorktrees(req, res, pathname) {
|
|
695
|
-
if (req.method === 'GET' && pathname === '/worktrees') return json(res, 200, { ok: true, root: WORKTREE_ROOT, worktrees: await listWorktrees() });
|
|
696
|
-
if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' });
|
|
697
|
-
const body = await readBody(req);
|
|
698
|
-
if (pathname === '/worktrees') {
|
|
699
|
-
const r = await worktreeFor({ repo: body.repo, projectId: body.projectId, jobId: body.jobId, base: body.base || null });
|
|
700
|
-
return json(res, r.error ? 400 : 200, r.error ? { error: r.error } : { ok: true, ...r });
|
|
701
|
-
}
|
|
702
|
-
if (pathname === '/worktrees/remove') {
|
|
703
|
-
const r = await removeWorktree({ projectId: body.projectId, jobId: body.jobId, force: !!body.force });
|
|
704
|
-
return json(res, r.ok ? 200 : 400, r);
|
|
705
|
-
}
|
|
706
|
-
return json(res, 404, { error: 'Not found' });
|
|
707
|
-
}
|
|
708
|
-
|
|
709
|
-
async function runCompatibleAgent(config, onDelta, res) {
|
|
710
|
-
const target = ENGINES[config.agent];
|
|
711
|
-
if (!target || target.hidden) throw new CompatError(`Unknown ChatPanel agent "${config.agent}"`, 400, 'model');
|
|
712
|
-
const availability = await target.engine.available().catch((e) => ({ ok: false, reason: e?.message || String(e) }));
|
|
713
|
-
if (!availability.ok) throw new CompatError(availability.reason || `${config.agent} is unavailable`, 503, 'model');
|
|
714
|
-
|
|
715
|
-
const runId = `run_${Math.random().toString(36).slice(2, 10)}`;
|
|
716
|
-
const run = startRun(runId);
|
|
717
|
-
const onGone = () => run.cancel('disconnected');
|
|
718
|
-
res.on('close', onGone);
|
|
719
|
-
let output = '';
|
|
720
|
-
try {
|
|
721
|
-
await target.engine.chat(
|
|
722
|
-
{ messages: config.messages, system: config.system, options: config.options, images: [] },
|
|
723
|
-
(event) => {
|
|
724
|
-
if (event?.type === 'delta' && event.text) {
|
|
725
|
-
output += event.text;
|
|
726
|
-
onDelta(event.text);
|
|
727
|
-
} else if (event?.type === 'done' && event.text && !output) {
|
|
728
|
-
output = event.text;
|
|
729
|
-
onDelta(event.text);
|
|
730
|
-
}
|
|
731
|
-
},
|
|
732
|
-
{ signal: run.signal },
|
|
733
|
-
);
|
|
734
|
-
return output;
|
|
735
|
-
} finally {
|
|
736
|
-
res.off('close', onGone);
|
|
737
|
-
endRun(runId);
|
|
738
|
-
}
|
|
739
|
-
}
|
|
740
|
-
|
|
741
|
-
function beginSse(res) {
|
|
742
|
-
res.writeHead(200, {
|
|
743
|
-
'Content-Type': 'text/event-stream',
|
|
744
|
-
'Cache-Control': 'no-cache',
|
|
745
|
-
Connection: 'keep-alive',
|
|
746
|
-
});
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
function writeData(res, value) {
|
|
750
|
-
if (!res.writableEnded) res.write(`data: ${typeof value === 'string' ? value : JSON.stringify(value)}\n\n`);
|
|
751
|
-
}
|
|
752
|
-
|
|
753
|
-
function writeNamedEvent(res, name, value) {
|
|
754
|
-
if (!res.writableEnded) res.write(`event: ${name}\ndata: ${JSON.stringify(value)}\n\n`);
|
|
755
|
-
}
|
|
756
|
-
|
|
757
|
-
async function compatibleBody(req, res, parser, errorShape) {
|
|
758
|
-
try {
|
|
759
|
-
return parser(await readBody(req));
|
|
760
|
-
} catch (error) {
|
|
761
|
-
json(res, error?.status || 400, errorShape(error?.message?.startsWith('Unexpected') ? new CompatError(`Bad JSON: ${error.message}`) : error));
|
|
762
|
-
return null;
|
|
763
|
-
}
|
|
764
|
-
}
|
|
765
|
-
|
|
766
|
-
async function handleOpenAIChatCompletions(req, res) {
|
|
767
|
-
const config = await compatibleBody(req, res, parseChatCompletion, openAIError);
|
|
768
|
-
if (!config) return;
|
|
769
|
-
if (!config.stream) {
|
|
770
|
-
try {
|
|
771
|
-
const text = await runCompatibleAgent(config, () => {}, res);
|
|
772
|
-
return json(res, 200, createChatCompletion(config.requestedModel, text));
|
|
773
|
-
} catch (error) {
|
|
774
|
-
if (!res.writableEnded) return json(res, error?.status || 500, openAIError(error));
|
|
775
|
-
return;
|
|
776
|
-
}
|
|
777
|
-
}
|
|
778
|
-
|
|
779
|
-
beginSse(res);
|
|
780
|
-
const stream = chatCompletionStream(config.requestedModel, (event) => writeData(res, event));
|
|
781
|
-
try {
|
|
782
|
-
await runCompatibleAgent(config, (text) => stream.delta(text), res);
|
|
783
|
-
stream.done();
|
|
784
|
-
} catch (error) {
|
|
785
|
-
writeData(res, openAIError(error));
|
|
786
|
-
}
|
|
787
|
-
writeData(res, '[DONE]');
|
|
788
|
-
res.end();
|
|
789
|
-
}
|
|
790
|
-
|
|
791
|
-
async function handleOpenAICompletions(req, res) {
|
|
792
|
-
const config = await compatibleBody(req, res, parseCompletion, openAIError);
|
|
793
|
-
if (!config) return;
|
|
794
|
-
if (!config.stream) {
|
|
795
|
-
try {
|
|
796
|
-
const text = await runCompatibleAgent(config, () => {}, res);
|
|
797
|
-
return json(res, 200, createCompletion(config.requestedModel, text));
|
|
798
|
-
} catch (error) {
|
|
799
|
-
if (!res.writableEnded) return json(res, error?.status || 500, openAIError(error));
|
|
800
|
-
return;
|
|
801
|
-
}
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
beginSse(res);
|
|
805
|
-
const stream = completionStream(config.requestedModel, (event) => writeData(res, event));
|
|
806
|
-
try {
|
|
807
|
-
await runCompatibleAgent(config, (text) => stream.delta(text), res);
|
|
808
|
-
stream.done();
|
|
809
|
-
} catch (error) {
|
|
810
|
-
writeData(res, openAIError(error));
|
|
811
|
-
}
|
|
812
|
-
writeData(res, '[DONE]');
|
|
813
|
-
res.end();
|
|
814
|
-
}
|
|
815
|
-
|
|
816
|
-
async function handleOpenAIResponses(req, res) {
|
|
817
|
-
const config = await compatibleBody(req, res, parseResponse, openAIError);
|
|
818
|
-
if (!config) return;
|
|
819
|
-
if (!config.stream) {
|
|
820
|
-
try {
|
|
821
|
-
const text = await runCompatibleAgent(config, () => {}, res);
|
|
822
|
-
return json(res, 200, createResponse(config.requestedModel, text));
|
|
823
|
-
} catch (error) {
|
|
824
|
-
if (!res.writableEnded) return json(res, error?.status || 500, openAIError(error));
|
|
825
|
-
return;
|
|
826
|
-
}
|
|
827
|
-
}
|
|
828
|
-
|
|
829
|
-
beginSse(res);
|
|
830
|
-
const stream = responseStream(config.requestedModel, (event) => writeNamedEvent(res, event.type, event));
|
|
831
|
-
try {
|
|
832
|
-
await runCompatibleAgent(config, (text) => stream.delta(text), res);
|
|
833
|
-
stream.done();
|
|
834
|
-
} catch (error) {
|
|
835
|
-
const event = { type: 'error', sequence_number: 0, ...openAIError(error) };
|
|
836
|
-
writeNamedEvent(res, 'error', event);
|
|
837
|
-
}
|
|
838
|
-
res.end();
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
async function handleAnthropicMessages(req, res) {
|
|
842
|
-
const config = await compatibleBody(req, res, parseAnthropicMessage, anthropicError);
|
|
843
|
-
if (!config) return;
|
|
844
|
-
if (!config.stream) {
|
|
845
|
-
try {
|
|
846
|
-
const text = await runCompatibleAgent(config, () => {}, res);
|
|
847
|
-
return json(res, 200, createAnthropicMessage(config.requestedModel, text));
|
|
848
|
-
} catch (error) {
|
|
849
|
-
if (!res.writableEnded) return json(res, error?.status || 500, anthropicError(error));
|
|
850
|
-
return;
|
|
851
|
-
}
|
|
852
|
-
}
|
|
853
|
-
|
|
854
|
-
beginSse(res);
|
|
855
|
-
const stream = anthropicStream(config.requestedModel, (name, event) => writeNamedEvent(res, name, event));
|
|
856
|
-
try {
|
|
857
|
-
await runCompatibleAgent(config, (text) => stream.delta(text), res);
|
|
858
|
-
stream.done();
|
|
859
|
-
} catch (error) {
|
|
860
|
-
writeNamedEvent(res, 'error', anthropicError(error));
|
|
861
|
-
}
|
|
862
|
-
res.end();
|
|
863
|
-
}
|
|
864
|
-
|
|
865
|
-
/**
|
|
866
|
-
* POST /cancel { id } — stop a run by name.
|
|
867
|
-
*
|
|
868
|
-
* Stop is now an instruction, not something inferred from a socket. Answers 200 whether or
|
|
869
|
-
* not the run was still live: 'already finished' and 'cancelled' are the same outcome to the
|
|
870
|
-
* caller, and returning 404 would make a harmless race look like a failure.
|
|
871
|
-
*/
|
|
872
|
-
async function handleCancel(req, res) {
|
|
873
|
-
// readBody already PARSES. Wrapping it in JSON.parse threw on every call, so the id was
|
|
874
|
-
// always empty and Stop silently cancelled nothing — the unit tests covered the registry
|
|
875
|
-
// and not the handler that feeds it, which is exactly where this hid.
|
|
876
|
-
let body = {};
|
|
877
|
-
try { body = (await readBody(req)) || {}; } catch { /* an empty body cancels nothing */ }
|
|
878
|
-
const id = String(body.id || '').trim();
|
|
879
|
-
const cancelled = id ? cancelRun(id, 'stopped') : false;
|
|
880
|
-
if (cancelled) log('info', `cancel: ${id} stopped by client`);
|
|
881
|
-
return json(res, 200, { ok: true, cancelled });
|
|
882
|
-
}
|
|
883
|
-
|
|
884
|
-
// POST /mcp/<session> (per-run, bridge-injected) OR POST /mcp (stable: routes to
|
|
885
|
-
// the active chat — for CLIs configured once, e.g. `opencode mcp add … …/mcp`).
|
|
886
|
-
// JSON-RPC; tools/call relays to the extension and waits for /tool-result.
|
|
887
|
-
async function handleMcp(req, res, sessionId) {
|
|
888
|
-
let msg;
|
|
889
|
-
try {
|
|
890
|
-
msg = await readBody(req);
|
|
891
|
-
} catch {
|
|
892
|
-
return json(res, 200, { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
|
|
893
|
-
}
|
|
894
|
-
// Explicit session id (per-run URL) or the active chat (stable /mcp).
|
|
895
|
-
const session = sessionId ? sessions.get(sessionId) : activeSession();
|
|
896
|
-
const reply = (result) => {
|
|
897
|
-
if (session) res.setHeader('Mcp-Session-Id', session.id);
|
|
898
|
-
json(res, 200, { jsonrpc: '2.0', id: msg.id ?? null, result });
|
|
899
|
-
};
|
|
900
|
-
const fail = (code, message) => json(res, 200, { jsonrpc: '2.0', id: msg.id ?? null, error: { code, message } });
|
|
901
|
-
|
|
902
|
-
// Notifications (no id) — ack and ignore.
|
|
903
|
-
if (msg.id == null) { res.writeHead(202); return res.end(); }
|
|
904
|
-
|
|
905
|
-
if (msg.method === 'initialize') {
|
|
906
|
-
return reply({
|
|
907
|
-
protocolVersion: msg.params?.protocolVersion || '2025-06-18',
|
|
908
|
-
capabilities: { tools: { listChanged: false } },
|
|
909
|
-
serverInfo: { name: 'chatpanel-browser', version: VERSION },
|
|
910
|
-
});
|
|
911
|
-
}
|
|
912
|
-
// ChatPanel's own bridge-native capabilities (skills today; redaction and more later) are
|
|
913
|
-
// ALWAYS advertised — a CLI that added this server once gets them whether or not a browser
|
|
914
|
-
// chat is open. The active session's page tools are added ON TOP when a chat is driving.
|
|
915
|
-
const capTools = capabilityToolSpecs();
|
|
916
|
-
|
|
917
|
-
if (msg.method === 'tools/list') {
|
|
918
|
-
const pageTools = session
|
|
919
|
-
? session.specs.map((s) => ({
|
|
920
|
-
name: s.name,
|
|
921
|
-
description: s.description,
|
|
922
|
-
inputSchema: s.parameters || { type: 'object', properties: {} },
|
|
923
|
-
}))
|
|
924
|
-
: [];
|
|
925
|
-
return reply({ tools: [...capTools, ...pageTools] });
|
|
926
|
-
}
|
|
927
|
-
if (msg.method === 'tools/call') {
|
|
928
|
-
// A capability tool runs in the bridge and needs no browser; a page tool relays to the
|
|
929
|
-
// active chat. Capability tools win a name clash — they are ours and namespaced.
|
|
930
|
-
const cap = await runCapabilityTool(msg.params?.name, msg.params?.arguments || {});
|
|
931
|
-
if (cap) return reply(cap);
|
|
932
|
-
if (!session) return fail(-32001, 'That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel\'s own tools (chatpanel_*) work without one.');
|
|
933
|
-
try {
|
|
934
|
-
return reply(await relayToolCall(session, msg.params?.name, msg.params?.arguments || {}));
|
|
935
|
-
} catch (e) {
|
|
936
|
-
return reply({ content: [{ type: 'text', text: `error: ${e?.message || e}` }], isError: true });
|
|
937
|
-
}
|
|
938
|
-
}
|
|
939
|
-
return fail(-32601, `Method not found: ${msg.method}`);
|
|
940
|
-
}
|
|
941
|
-
|
|
942
|
-
// POST /mcp-local — proxy one JSON-RPC message to a user-configured STDIO MCP
|
|
943
|
-
// server that the bridge spawns and keeps alive. Body: { server:{id,command,args,
|
|
944
|
-
// env?,cwd?}, message }. Returns the full JSON-RPC response (or 202 for a
|
|
945
|
-
// notification). Lets the extension use local MCP servers it can't spawn itself.
|
|
946
|
-
async function handleMcpLocal(req, res) {
|
|
947
|
-
let body;
|
|
948
|
-
try {
|
|
949
|
-
body = await readBody(req);
|
|
950
|
-
} catch (e) {
|
|
951
|
-
return json(res, 400, { error: 'Bad JSON: ' + e.message });
|
|
952
|
-
}
|
|
953
|
-
const server = body.server || {};
|
|
954
|
-
const message = body.message;
|
|
955
|
-
if (!server.command || !message) return json(res, 400, { error: 'need server.command and message' });
|
|
956
|
-
try {
|
|
957
|
-
const result = await callLocalMcp(
|
|
958
|
-
{ key: server.id, command: server.command, args: server.args, env: server.env, cwd: server.cwd },
|
|
959
|
-
message,
|
|
960
|
-
);
|
|
961
|
-
if (message.id == null) { res.writeHead(202); return res.end(); }
|
|
962
|
-
return json(res, 200, result); // the full JSON-RPC response message
|
|
963
|
-
} catch (e) {
|
|
964
|
-
return json(res, 200, {
|
|
965
|
-
jsonrpc: '2.0',
|
|
966
|
-
id: message.id ?? null,
|
|
967
|
-
error: { code: -32000, message: String(e?.message || e) },
|
|
968
|
-
});
|
|
969
|
-
}
|
|
970
|
-
}
|
|
971
|
-
|
|
972
|
-
// POST /mcp-remote — proxy ONE JSON-RPC message to a remote Streamable-HTTP MCP
|
|
973
|
-
// server FROM the bridge (server-side, no browser Origin header), so the extension
|
|
974
|
-
// can reach servers that reject browser origins (their own DNS-rebinding/CORS
|
|
975
|
-
// protection). Body: { url, headers?, message }. Returns the upstream
|
|
976
|
-
// { status, sessionId, contentType, body } for the extension to parse. Privileged
|
|
977
|
-
// route + SSRF guard, so it can't be driven by a page or relay into the LAN.
|
|
978
|
-
async function handleMcpRemote(req, res) {
|
|
979
|
-
let body;
|
|
980
|
-
try {
|
|
981
|
-
body = await readBody(req);
|
|
982
|
-
} catch (e) {
|
|
983
|
-
return json(res, 400, { error: 'Bad JSON: ' + e.message });
|
|
984
|
-
}
|
|
985
|
-
const { url, headers: hdrs, message } = body || {};
|
|
986
|
-
if (!url || !message) return json(res, 400, { error: 'need url and message' });
|
|
987
|
-
let target;
|
|
988
|
-
try {
|
|
989
|
-
target = assertPublicHttpUrl(url);
|
|
990
|
-
} catch (e) {
|
|
991
|
-
return json(res, 400, { error: String(e?.message || e) });
|
|
992
|
-
}
|
|
993
|
-
// Forward only safe, MCP-relevant client headers (auth, session, protocol, x-*);
|
|
994
|
-
// never the Host/hop-by-hop headers. Content-Type/Accept are set by us.
|
|
995
|
-
const fwd = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' };
|
|
996
|
-
if (hdrs && typeof hdrs === 'object') {
|
|
997
|
-
for (const [k, v] of Object.entries(hdrs)) {
|
|
998
|
-
const lk = k.toLowerCase();
|
|
999
|
-
if (['authorization', 'mcp-session-id', 'mcp-protocol-version', 'x-api-key'].includes(lk) || lk.startsWith('x-')) {
|
|
1000
|
-
fwd[k] = String(v);
|
|
1001
|
-
}
|
|
1002
|
-
}
|
|
1003
|
-
}
|
|
1004
|
-
const ac = new AbortController();
|
|
1005
|
-
const t = setTimeout(() => ac.abort(), 30_000);
|
|
1006
|
-
try {
|
|
1007
|
-
const up = await fetch(target.href, { method: 'POST', headers: fwd, body: JSON.stringify(message), redirect: 'follow', signal: ac.signal });
|
|
1008
|
-
// A redirect may have landed on an internal host — re-check the final URL.
|
|
1009
|
-
try { if (up.url) assertPublicHttpUrl(up.url); } catch (e) { return json(res, 400, { error: String(e?.message || e) }); }
|
|
1010
|
-
const text = await up.text().catch(() => '');
|
|
1011
|
-
return json(res, 200, {
|
|
1012
|
-
status: up.status,
|
|
1013
|
-
sessionId: up.headers.get('Mcp-Session-Id') || null,
|
|
1014
|
-
contentType: up.headers.get('Content-Type') || '',
|
|
1015
|
-
body: text,
|
|
1016
|
-
});
|
|
1017
|
-
} catch (e) {
|
|
1018
|
-
const why = e?.name === 'AbortError' ? 'timed out' : String(e?.message || e);
|
|
1019
|
-
return json(res, 502, { error: `couldn't reach MCP server ${target.host}: ${why}` });
|
|
1020
|
-
} finally {
|
|
1021
|
-
clearTimeout(t);
|
|
1022
|
-
}
|
|
1023
|
-
}
|
|
1024
|
-
|
|
1025
|
-
// POST /fetch-title — fetch a PUBLIC web page and return ONLY its <title>, so a client can turn
|
|
1026
|
-
// a bare URL into a readable [Title](url) link without the browser's Origin/CORS limits and
|
|
1027
|
-
// without any third-party title service. This is the canonical "secure web fetch" the bridge
|
|
1028
|
-
// offers on behalf of clients:
|
|
1029
|
-
// • Privileged route (extension origin or bridge token only) — a random page can't drive it.
|
|
1030
|
-
// • STRICTER SSRF guard than /mcp-remote (assertPublicWebUrl): loopback / LAN / metadata are
|
|
1031
|
-
// blocked unconditionally — a page fetch has no business touching internal hosts.
|
|
1032
|
-
// • Redirects are followed MANUALLY, re-validating EVERY hop, so it can never be bounced onto
|
|
1033
|
-
// an internal address (stronger than an after-the-fact final-URL check).
|
|
1034
|
-
// • Response is read with a hard byte cap and stops at </title> — we only need the <head>.
|
|
1035
|
-
// • No cookies / auth / referer are ever sent; only the title string is returned.
|
|
1036
|
-
const FT_MAX_BYTES = 256 * 1024;
|
|
1037
|
-
const FT_MAX_REDIRECTS = 5;
|
|
1038
|
-
const FT_TIMEOUT_MS = 8000;
|
|
1039
|
-
|
|
1040
|
-
async function fetchTitleSafely(rawUrl) {
|
|
1041
|
-
let current = assertPublicWebUrl(rawUrl); // throws on non-http(s) / private / loopback / metadata
|
|
1042
|
-
const ac = new AbortController();
|
|
1043
|
-
const timer = setTimeout(() => ac.abort(), FT_TIMEOUT_MS);
|
|
1044
|
-
try {
|
|
1045
|
-
for (let hop = 0; hop <= FT_MAX_REDIRECTS; hop++) {
|
|
1046
|
-
const res = await fetch(current.href, {
|
|
1047
|
-
method: 'GET',
|
|
1048
|
-
redirect: 'manual', // follow hops ourselves so each target is re-validated before we call it
|
|
1049
|
-
signal: ac.signal,
|
|
1050
|
-
headers: { Accept: 'text/html,application/xhtml+xml', 'Accept-Language': 'en', 'User-Agent': `chatpanel-bridge/${VERSION} (+link-title)` },
|
|
1051
|
-
});
|
|
1052
|
-
if (res.status >= 300 && res.status < 400 && res.headers.get('location')) {
|
|
1053
|
-
current = assertPublicWebUrl(new URL(res.headers.get('location'), current).href); // re-guard the redirect
|
|
1054
|
-
if (res.body) { try { await res.body.cancel(); } catch { /* ignore */ } }
|
|
1055
|
-
continue;
|
|
1056
|
-
}
|
|
1057
|
-
if (!res.ok) { if (res.body) { try { await res.body.cancel(); } catch { /* ignore */ } } return { title: null }; }
|
|
1058
|
-
const ct = res.headers.get('content-type') || '';
|
|
1059
|
-
if (!/text\/html|application\/xhtml/i.test(ct)) { if (res.body) { try { await res.body.cancel(); } catch { /* ignore */ } } return { title: null }; }
|
|
1060
|
-
return { title: extractTitle(await readCapped(res)), url: current.href };
|
|
1061
|
-
}
|
|
1062
|
-
throw new Error('too many redirects');
|
|
1063
|
-
} finally {
|
|
1064
|
-
clearTimeout(timer);
|
|
1065
|
-
}
|
|
1066
|
-
}
|
|
1067
|
-
|
|
1068
|
-
// Read the response body up to FT_MAX_BYTES, stopping as soon as we've seen the closing </title>.
|
|
1069
|
-
async function readCapped(res) {
|
|
1070
|
-
if (!res.body?.getReader) return (await res.text().catch(() => '')).slice(0, FT_MAX_BYTES);
|
|
1071
|
-
const reader = res.body.getReader();
|
|
1072
|
-
const decoder = new TextDecoder('utf-8', { fatal: false });
|
|
1073
|
-
let out = '';
|
|
1074
|
-
let total = 0;
|
|
1075
|
-
try {
|
|
1076
|
-
for (;;) {
|
|
1077
|
-
const { done, value } = await reader.read();
|
|
1078
|
-
if (done) break;
|
|
1079
|
-
total += value.byteLength;
|
|
1080
|
-
out += decoder.decode(value, { stream: true });
|
|
1081
|
-
if (/<\/title\s*>/i.test(out) || total >= FT_MAX_BYTES) break;
|
|
1082
|
-
}
|
|
1083
|
-
} finally {
|
|
1084
|
-
try { await reader.cancel(); } catch { /* ignore */ }
|
|
1085
|
-
}
|
|
1086
|
-
return out;
|
|
1087
|
-
}
|
|
1088
|
-
|
|
1089
|
-
function decodeEntities(s) {
|
|
1090
|
-
return String(s)
|
|
1091
|
-
.replace(/&/g, '&')
|
|
1092
|
-
.replace(/</g, '<')
|
|
1093
|
-
.replace(/>/g, '>')
|
|
1094
|
-
.replace(/"/g, '"')
|
|
1095
|
-
.replace(/&(?:apos|#0*39|#x0*27);/gi, "'")
|
|
1096
|
-
.replace(/ /g, ' ')
|
|
1097
|
-
.replace(/&#(\d+);/g, (_, d) => { try { return String.fromCodePoint(+d); } catch { return ''; } })
|
|
1098
|
-
.replace(/&#x([0-9a-f]+);/gi, (_, h) => { try { return String.fromCodePoint(parseInt(h, 16)); } catch { return ''; } });
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
function extractTitle(html) {
|
|
1102
|
-
const m = /<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(html);
|
|
1103
|
-
return m ? decodeEntities(m[1]).replace(/\s+/g, ' ').trim().slice(0, 200) : '';
|
|
1104
|
-
}
|
|
1105
|
-
|
|
1106
|
-
async function handleFetchTitle(req, res) {
|
|
1107
|
-
let body;
|
|
1108
|
-
try { body = await readBody(req); } catch (e) { return json(res, 400, { error: 'Bad JSON: ' + e.message }); }
|
|
1109
|
-
const url = body && body.url;
|
|
1110
|
-
if (!url || typeof url !== 'string') return json(res, 400, { error: 'need url' });
|
|
1111
|
-
try {
|
|
1112
|
-
const out = await fetchTitleSafely(url);
|
|
1113
|
-
return json(res, 200, { title: out.title || null, url: out.url || url });
|
|
1114
|
-
} catch (e) {
|
|
1115
|
-
const why = e?.name === 'AbortError' ? 'timed out' : String(e?.message || e);
|
|
1116
|
-
return json(res, 400, { error: `couldn't fetch title: ${why}` });
|
|
1117
|
-
}
|
|
1118
|
-
}
|
|
1119
|
-
|
|
1120
|
-
// POST /tool-result — the extension returns a relayed tool's result.
|
|
1121
|
-
async function handleToolResult(req, res) {
|
|
1122
|
-
let body;
|
|
1123
|
-
try {
|
|
1124
|
-
body = await readBody(req);
|
|
1125
|
-
} catch (e) {
|
|
1126
|
-
return json(res, 400, { error: 'Bad JSON: ' + e.message });
|
|
1127
|
-
}
|
|
1128
|
-
const session = sessions.get(body.session);
|
|
1129
|
-
if (!session) return json(res, 404, { error: 'no such session' });
|
|
1130
|
-
const pending = session.pending.get(body.id);
|
|
1131
|
-
if (!pending) return json(res, 404, { error: 'no such pending call' });
|
|
1132
|
-
session.pending.delete(body.id);
|
|
1133
|
-
pending.resolve(body.result);
|
|
1134
|
-
return json(res, 200, { ok: true });
|
|
1135
|
-
}
|
|
1136
|
-
|
|
1137
|
-
// POST /complete → { agent, prompt, model? } → { text } — a fast, single-shot
|
|
1138
|
-
// completion for prompt autocomplete. Uses the engine's complete() if it has one
|
|
1139
|
-
// (Claude: Haiku, no tools), else a one-shot chat collected into text.
|
|
1140
|
-
async function handleComplete(req, res) {
|
|
1141
|
-
let body;
|
|
1142
|
-
try {
|
|
1143
|
-
body = await readBody(req);
|
|
1144
|
-
} catch (e) {
|
|
1145
|
-
return json(res, 400, { error: 'Bad JSON: ' + e.message });
|
|
1146
|
-
}
|
|
1147
|
-
const target = ENGINES[body.agent];
|
|
1148
|
-
if (!target) return json(res, 404, { error: `Unknown agent "${body.agent}"` });
|
|
1149
|
-
const prompt = String(body.prompt || '').slice(0, 6000);
|
|
1150
|
-
if (!prompt) return json(res, 400, { error: 'Empty prompt' });
|
|
1151
|
-
const model = body.model || '';
|
|
1152
|
-
// The extension sends a strict "continue, don't answer" system prompt (with any
|
|
1153
|
-
// page context already in `prompt`); fall back to a sensible default.
|
|
1154
|
-
const system =
|
|
1155
|
-
String(body.system || '').slice(0, 2000) ||
|
|
1156
|
-
'You autocomplete an unfinished message the user is typing. Output ONLY the ' +
|
|
1157
|
-
'few words that come next. Do not answer it. No quotes, no repetition.';
|
|
1158
|
-
try {
|
|
1159
|
-
let text = '';
|
|
1160
|
-
if (typeof target.engine.complete === 'function') {
|
|
1161
|
-
text = await target.engine.complete({ prompt, system, model });
|
|
1162
|
-
} else {
|
|
1163
|
-
await target.engine.chat(
|
|
1164
|
-
{ messages: [{ role: 'user', content: prompt }], system, options: { model } },
|
|
1165
|
-
(obj) => {
|
|
1166
|
-
if (obj.type === 'delta') text += obj.text || '';
|
|
1167
|
-
else if (obj.type === 'done' && obj.text) text += obj.text;
|
|
1168
|
-
},
|
|
1169
|
-
);
|
|
1170
|
-
}
|
|
1171
|
-
return json(res, 200, { text: (text || '').trim() });
|
|
1172
|
-
} catch (e) {
|
|
1173
|
-
return json(res, 502, { error: e?.message || String(e) });
|
|
1174
|
-
}
|
|
1175
|
-
}
|
|
1176
|
-
|
|
1177
|
-
// POST /list-models → { agent, options } → { models } — the unified model-list
|
|
1178
|
-
// interface. Each engine decides HOW to enumerate (claude → known aliases; custom
|
|
1179
|
-
// → runs the agent's configured `listModelsArgs`, e.g. pi `--list-models` /
|
|
1180
|
-
// opencode `models`, and parses stdout). Engines without a lister return [].
|
|
1181
|
-
async function handleListModels(req, res) {
|
|
1182
|
-
let body;
|
|
1183
|
-
try {
|
|
1184
|
-
body = await readBody(req);
|
|
1185
|
-
} catch (e) {
|
|
1186
|
-
return json(res, 400, { error: 'Bad JSON: ' + e.message });
|
|
1187
|
-
}
|
|
1188
|
-
const target = ENGINES[body.agent];
|
|
1189
|
-
if (!target) return json(res, 404, { error: `Unknown agent "${body.agent}"` });
|
|
1190
|
-
if (typeof target.engine.listModels !== 'function') return json(res, 200, { models: [] });
|
|
1191
|
-
try {
|
|
1192
|
-
const models = await target.engine.listModels(body.options || {});
|
|
1193
|
-
return json(res, 200, { models: Array.isArray(models) ? models : [] });
|
|
1194
|
-
} catch (e) {
|
|
1195
|
-
return json(res, 502, { error: e?.message || String(e) });
|
|
1196
|
-
}
|
|
1197
|
-
}
|
|
1198
|
-
|
|
1199
|
-
// POST /agent-check → { command } → { ok, via } — does this command resolve on
|
|
1200
|
-
// this machine? Powers the "✓ found" indicator when onboarding a custom agent.
|
|
1201
|
-
// `via` tells the user HOW it resolved (native / script / cmd / wsl) so a Windows
|
|
1202
|
-
// user sees e.g. "found in WSL". No execution, no entitlement needed (read-only).
|
|
1203
|
-
async function handleAgentCheck(req, res) {
|
|
1204
|
-
let body;
|
|
1205
|
-
try {
|
|
1206
|
-
body = await readBody(req);
|
|
1207
|
-
} catch (e) {
|
|
1208
|
-
return json(res, 400, { error: 'Bad JSON: ' + e.message });
|
|
1209
|
-
}
|
|
1210
|
-
const command = String(body.command || '').trim();
|
|
1211
|
-
if (!command) return json(res, 400, { error: 'No command' });
|
|
1212
|
-
let spec = null;
|
|
1213
|
-
try {
|
|
1214
|
-
spec = resolveCommand(command);
|
|
1215
|
-
} catch {
|
|
1216
|
-
spec = null;
|
|
1217
|
-
}
|
|
1218
|
-
return json(res, 200, { ok: !!spec, via: spec ? spec.kind : null });
|
|
1219
|
-
}
|
|
1220
|
-
|
|
1221
|
-
const server = createServer(async (req, res) => {
|
|
1222
|
-
cors(req, res);
|
|
1223
|
-
if (req.method === 'OPTIONS') {
|
|
1224
|
-
res.writeHead(204);
|
|
1225
|
-
return res.end();
|
|
1226
|
-
}
|
|
1227
|
-
let url;
|
|
1228
|
-
try {
|
|
1229
|
-
url = new URL(req.url, `http://${req.headers.host || '127.0.0.1'}`);
|
|
1230
|
-
} catch {
|
|
1231
|
-
return json(res, 400, { error: 'bad request' });
|
|
1232
|
-
}
|
|
1233
|
-
// Block DNS-rebinding / cross-origin CSRF before any route runs.
|
|
1234
|
-
const blocked = guard(req, url.pathname);
|
|
1235
|
-
if (blocked) return json(res, 403, { error: blocked });
|
|
1236
|
-
try {
|
|
1237
|
-
if (req.method === 'GET' && url.pathname === '/health') return handleHealth(res);
|
|
1238
|
-
// Custom skill folders the user configured in the extension, passed per request. They
|
|
1239
|
-
// are the user's own absolute paths on their own machine; the bridge validates and
|
|
1240
|
-
// scans them, and the same traversal/symlink guards apply to any file read from them.
|
|
1241
|
-
const extraDirs = url.searchParams.getAll('dir');
|
|
1242
|
-
if (req.method === 'GET' && url.pathname === '/skills') return handleSkillsList(res, extraDirs);
|
|
1243
|
-
if (req.method === 'GET' && url.pathname === '/skills-quarantined') return handleSkillsQuarantined(res, extraDirs);
|
|
1244
|
-
if (req.method === 'GET' && url.pathname.startsWith('/skills/')) {
|
|
1245
|
-
const rest = url.pathname.slice('/skills/'.length);
|
|
1246
|
-
const cut = rest.indexOf('/file/');
|
|
1247
|
-
if (cut === -1) return handleSkillRead(res, decodeURIComponent(rest), extraDirs);
|
|
1248
|
-
return handleSkillFile(
|
|
1249
|
-
res,
|
|
1250
|
-
decodeURIComponent(rest.slice(0, cut)),
|
|
1251
|
-
decodeURIComponent(rest.slice(cut + '/file/'.length)),
|
|
1252
|
-
extraDirs,
|
|
1253
|
-
);
|
|
1254
|
-
}
|
|
1255
|
-
if (url.pathname === '/connections' || url.pathname.startsWith('/connections/')) return handleConnections(req, res, url.pathname);
|
|
1256
|
-
if (url.pathname === '/worktrees' || url.pathname.startsWith('/worktrees/')) return handleWorktrees(req, res, url.pathname);
|
|
1257
|
-
if (req.method === 'GET' && url.pathname === '/v1/models') return handleCompatibleModels(res);
|
|
1258
|
-
if (req.method === 'GET' && url.pathname.startsWith('/v1/models/')) {
|
|
1259
|
-
return handleCompatibleModels(res, decodeURIComponent(url.pathname.slice('/v1/models/'.length)));
|
|
1260
|
-
}
|
|
1261
|
-
if (req.method === 'GET' && url.pathname === '/debug') {
|
|
1262
|
-
// L6: by default expose only version + agent AVAILABILITY (a boolean) — enough
|
|
1263
|
-
// to diagnose "is codex installed?". The full home dir, $PATH, and resolved
|
|
1264
|
-
// binary paths (which embed the username / home) leak environment detail, so
|
|
1265
|
-
// they're opt-in behind CHATPANEL_BRIDGE_DEBUG=1. The extension doesn't read
|
|
1266
|
-
// this route, so trimming it by default breaks nothing.
|
|
1267
|
-
const verbose = /^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG || '');
|
|
1268
|
-
return json(res, 200, {
|
|
1269
|
-
version: VERSION,
|
|
1270
|
-
agents: Object.fromEntries(AGENT_CLIS.map((name) => [name, verbose ? (findAgentBin(name) || null) : !!findAgentBin(name)])),
|
|
1271
|
-
...(verbose ? { home: os.homedir(), path: process.env.PATH } : {}),
|
|
1272
|
-
});
|
|
1273
|
-
}
|
|
1274
|
-
if (req.method === 'POST' && url.pathname === '/chat') return handleChat(req, res);
|
|
1275
|
-
if (req.method === 'POST' && url.pathname === '/v1/chat/completions') return handleOpenAIChatCompletions(req, res);
|
|
1276
|
-
if (req.method === 'POST' && url.pathname === '/v1/completions') return handleOpenAICompletions(req, res);
|
|
1277
|
-
if (req.method === 'POST' && url.pathname === '/v1/responses') return handleOpenAIResponses(req, res);
|
|
1278
|
-
if (req.method === 'POST' && url.pathname === '/v1/messages') return handleAnthropicMessages(req, res);
|
|
1279
|
-
// Stable endpoint: routes to the active chat. For CLIs configured once with a
|
|
1280
|
-
// fixed URL (e.g. `opencode mcp add chatpanel --url http://127.0.0.1:4319/mcp`).
|
|
1281
|
-
if (url.pathname === '/mcp') {
|
|
1282
|
-
if (req.method === 'POST') return handleMcp(req, res, null);
|
|
1283
|
-
if (req.method === 'GET') { res.writeHead(405); return res.end(); }
|
|
1284
|
-
}
|
|
1285
|
-
if (url.pathname.startsWith('/mcp/')) {
|
|
1286
|
-
const sid = decodeURIComponent(url.pathname.slice(5));
|
|
1287
|
-
if (req.method === 'POST') return handleMcp(req, res, sid);
|
|
1288
|
-
if (req.method === 'GET') { res.writeHead(405); return res.end(); } // no server-initiated stream
|
|
1289
|
-
if (req.method === 'DELETE') { deleteSession(sid); res.writeHead(204); return res.end(); }
|
|
1290
|
-
}
|
|
1291
|
-
if (req.method === 'GET' && url.pathname === '/channels') return handleChannels(req, res, 'status');
|
|
1292
|
-
if (req.method === 'POST' && url.pathname.startsWith('/channels/')) {
|
|
1293
|
-
return handleChannels(req, res, url.pathname.slice('/channels/'.length));
|
|
1294
|
-
}
|
|
1295
|
-
if (req.method === 'POST' && url.pathname === '/cancel') return handleCancel(req, res);
|
|
1296
|
-
if (req.method === 'POST' && url.pathname === '/tool-result') return handleToolResult(req, res);
|
|
1297
|
-
if (req.method === 'POST' && url.pathname === '/mcp-local') return handleMcpLocal(req, res);
|
|
1298
|
-
if (req.method === 'POST' && url.pathname === '/mcp-remote') return handleMcpRemote(req, res);
|
|
1299
|
-
if (req.method === 'POST' && url.pathname === '/fetch-title') return handleFetchTitle(req, res);
|
|
1300
|
-
if (req.method === 'POST' && url.pathname === '/complete') return handleComplete(req, res);
|
|
1301
|
-
if (req.method === 'POST' && url.pathname === '/list-models') return handleListModels(req, res);
|
|
1302
|
-
if (req.method === 'POST' && url.pathname === '/agent-check') return handleAgentCheck(req, res);
|
|
1303
|
-
if (req.method === 'POST' && url.pathname === '/update') return handleUpdate(res);
|
|
1304
|
-
json(res, 404, { error: 'Not found' });
|
|
1305
|
-
} catch (e) {
|
|
1306
|
-
json(res, 500, { error: e?.message || String(e) });
|
|
1307
|
-
}
|
|
1308
|
-
});
|
|
1309
|
-
|
|
1310
|
-
function log(level, msg) {
|
|
1311
|
-
const fn = level === 'error' ? console.error : console.log;
|
|
1312
|
-
fn(`[chatpanel-bridge] ${msg}`);
|
|
1313
|
-
}
|
|
1314
|
-
|
|
1315
|
-
// `--mcp-stdio <url>` — run as a stdio↔HTTP MCP proxy: read newline-delimited
|
|
1316
|
-
// JSON-RPC from stdin, forward each message to the bridge's HTTP MCP endpoint
|
|
1317
|
-
// (<url> = http://127.0.0.1:PORT/mcp/<session>), and write responses to stdout.
|
|
1318
|
-
// This lets ANY stdio-MCP CLI (Codex, a custom CLI) use the browser tools with
|
|
1319
|
-
// the bridge binary itself as the MCP server command — no extra runtime needed.
|
|
1320
|
-
function runMcpStdioProxy(url) {
|
|
1321
|
-
let buf = '';
|
|
1322
|
-
const queue = [];
|
|
1323
|
-
let draining = false;
|
|
1324
|
-
let ended = false;
|
|
1325
|
-
const maybeExit = () => { if (ended && !draining && !queue.length) process.exit(0); };
|
|
1326
|
-
const drain = async () => {
|
|
1327
|
-
if (draining) return;
|
|
1328
|
-
draining = true;
|
|
1329
|
-
while (queue.length) {
|
|
1330
|
-
const line = queue.shift();
|
|
1331
|
-
let msg;
|
|
1332
|
-
try { msg = JSON.parse(line); } catch { continue; }
|
|
1333
|
-
try {
|
|
1334
|
-
const res = await fetch(url, {
|
|
1335
|
-
method: 'POST',
|
|
1336
|
-
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
1337
|
-
body: line,
|
|
1338
|
-
});
|
|
1339
|
-
if (msg.id == null) continue; // notification — no response expected
|
|
1340
|
-
const text = (await res.text()).trim();
|
|
1341
|
-
if (text) process.stdout.write(text + '\n');
|
|
1342
|
-
} catch (e) {
|
|
1343
|
-
if (msg.id != null) {
|
|
1344
|
-
process.stdout.write(
|
|
1345
|
-
JSON.stringify({ jsonrpc: '2.0', id: msg.id, error: { code: -32000, message: String(e?.message || e) } }) + '\n',
|
|
1346
|
-
);
|
|
1347
|
-
}
|
|
1348
|
-
}
|
|
1349
|
-
}
|
|
1350
|
-
draining = false;
|
|
1351
|
-
maybeExit(); // stdin closed mid-flight → exit only after the queue is drained
|
|
1352
|
-
};
|
|
1353
|
-
process.stdin.setEncoding('utf8');
|
|
1354
|
-
process.stdin.on('data', (chunk) => {
|
|
1355
|
-
buf += chunk;
|
|
1356
|
-
let nl;
|
|
1357
|
-
while ((nl = buf.indexOf('\n')) >= 0) {
|
|
1358
|
-
const line = buf.slice(0, nl).trim();
|
|
1359
|
-
buf = buf.slice(nl + 1);
|
|
1360
|
-
if (line) queue.push(line);
|
|
1361
|
-
}
|
|
1362
|
-
drain();
|
|
1363
|
-
});
|
|
1364
|
-
process.stdin.on('end', () => { ended = true; maybeExit(); });
|
|
1365
|
-
process.stdin.resume();
|
|
1366
|
-
}
|
|
1367
|
-
|
|
1368
|
-
function startServer() {
|
|
1369
|
-
enrichPath(); // so codex/agy (Antigravity) are found even under a minimal service PATH
|
|
1370
|
-
enrichAgentEnv(); // and so env-authenticated CLIs (dsh) have their key under launchd
|
|
1371
|
-
ensureToken(); // per-install bearer token for privileged routes (defense-in-depth)
|
|
1372
|
-
// Fail LOUD on a port clash. The bridge binds a FIXED 4319 so the extension always
|
|
1373
|
-
// finds it; if it's taken, say how to recover instead of dying on a raw stack trace.
|
|
1374
|
-
server.on('error', (e) => {
|
|
1375
|
-
if (e && e.code === 'EADDRINUSE') {
|
|
1376
|
-
log('error', `Port ${PORT} is already in use — another app (or a second bridge) has it.`);
|
|
1377
|
-
log('error', `Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings.`);
|
|
1378
|
-
process.exit(1);
|
|
1379
|
-
}
|
|
1380
|
-
log('error', `bridge server error: ${e?.message || e}`);
|
|
1381
|
-
process.exit(1);
|
|
1382
|
-
});
|
|
1383
|
-
// Leaving a CLI running after the bridge exits is how orphans are made — and the user has
|
|
1384
|
-
// no way to find or stop them, because the thing that spawned them is gone.
|
|
1385
|
-
for (const sig of ['SIGINT', 'SIGTERM']) {
|
|
1386
|
-
process.on(sig, () => {
|
|
1387
|
-
const n = cancelAll('shutdown');
|
|
1388
|
-
if (n) log('info', `shutdown: stopped ${n} running agent${n === 1 ? '' : 's'}`);
|
|
1389
|
-
// Give SIGTERM a moment to land before the process goes; killTree escalates on its own.
|
|
1390
|
-
setTimeout(() => process.exit(0), n ? 300 : 0).unref?.();
|
|
1391
|
-
if (!n) process.exit(0);
|
|
1392
|
-
});
|
|
1393
|
-
}
|
|
1394
|
-
|
|
1395
|
-
server.listen(PORT, HOST, async () => {
|
|
1396
|
-
log('info', `listening on http://${HOST}:${PORT}`);
|
|
1397
|
-
// M7: a non-loopback bind disables the anti-DNS-rebinding Host check (hostAllowed
|
|
1398
|
-
// returns true for any Host), so the only inbound guard left is the per-install
|
|
1399
|
-
// token / extension Origin. Make that trade-off LOUD — it's rarely what you want.
|
|
1400
|
-
if (!LOOPBACK_HOSTNAMES.has(HOST)) {
|
|
1401
|
-
log('error', `⚠ SECURITY: bound to NON-LOOPBACK host ${HOST}. 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.`);
|
|
1402
|
-
}
|
|
1403
|
-
for (const [, { engine, label, hidden }] of Object.entries(ENGINES)) {
|
|
1404
|
-
if (hidden) continue;
|
|
1405
|
-
const a = await engine.available().catch(() => ({ ok: false }));
|
|
1406
|
-
log('info', ` ${a.ok ? '✓' : '✕'} ${label}${a.ok ? '' : ' — ' + (a.reason || 'unavailable')}`);
|
|
1407
|
-
}
|
|
1408
|
-
log('info', 'Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically.');
|
|
1409
|
-
// A channel someone connected last week must come back by itself after a reboot — nobody
|
|
1410
|
-
// is at the keyboard to press start, which is the entire premise of driving this from a
|
|
1411
|
-
// phone. Nothing loads and nothing runs until a bot has actually been connected.
|
|
1412
|
-
channelService()
|
|
1413
|
-
.then((svc) => svc.startIfConfigured())
|
|
1414
|
-
.then((r) => {
|
|
1415
|
-
if (r?.skipped) return;
|
|
1416
|
-
if (r?.ok) log('info', 'channels: telegram connected — polling for messages');
|
|
1417
|
-
else log('error', `channels: telegram not started — ${r?.error || 'unknown error'}`);
|
|
1418
|
-
})
|
|
1419
|
-
.catch((e) => log('error', `channels: ${e?.message || e}`));
|
|
1420
|
-
});
|
|
1421
|
-
}
|
|
1422
|
-
|
|
1423
|
-
function printHelp() {
|
|
1424
|
-
console.log(`ChatPanel Bridge v${VERSION}
|
|
9
|
+
`)}async function B(t,e,n,r){try{return n(await f(t))}catch(o){return a(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new R(`Bad JSON: ${o.message}`):o)),null}}async function Ft(t,e){const n=await B(t,e,yt,w);if(!n)return;if(!n.stream)try{const o=await S(n,()=>{},e);return a(e,200,ht(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,w(o))}_(e);const r=dt(n.requestedModel,o=>A(e,o));try{await S(n,o=>r.delta(o),e),r.done()}catch(o){A(e,w(o))}A(e,"[DONE]"),e.end()}async function Jt(t,e){const n=await B(t,e,wt,w);if(!n)return;if(!n.stream)try{const o=await S(n,()=>{},e);return a(e,200,mt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,w(o))}_(e);const r=ut(n.requestedModel,o=>A(e,o));try{await S(n,o=>r.delta(o),e),r.done()}catch(o){A(e,w(o))}A(e,"[DONE]"),e.end()}async function Kt(t,e){const n=await B(t,e,bt,w);if(!n)return;if(!n.stream)try{const o=await S(n,()=>{},e);return a(e,200,ft(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,w(o))}_(e);const r=St(n.requestedModel,o=>M(e,o.type,o));try{await S(n,o=>r.delta(o),e),r.done()}catch(o){const i={type:"error",sequence_number:0,...w(o)};M(e,"error",i)}e.end()}async function zt(t,e){const n=await B(t,e,gt,L);if(!n)return;if(!n.stream)try{const o=await S(n,()=>{},e);return a(e,200,pt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,L(o))}_(e);const r=lt(n.requestedModel,(o,i)=>M(e,o,i));try{await S(n,o=>r.delta(o),e),r.done()}catch(o){M(e,"error",L(o))}e.end()}async function Vt(t,e){let n={};try{n=await f(t)||{}}catch{}const r=String(n.id||"").trim(),o=r?st(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),a(e,200,{ok:!0,cancelled:o})}async function ie(t,e,n){let r;try{r=await f(t)}catch{return a(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=n?v.get(n):Tt(),i=l=>{o&&e.setHeader("Mcp-Session-Id",o.id),a(e,200,{jsonrpc:"2.0",id:r.id??null,result:l})},s=(l,c)=>a(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:l,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=Be();if(r.method==="tools/list"){const l=o?o.specs.map(c=>({name:c.name,description:c.description,inputSchema:c.parameters||{type:"object",properties:{}}})):[];return i({tools:[...d,...l]})}if(r.method==="tools/call"){const l=await Ge(r.params?.name,r.params?.arguments||{});if(l)return i(l);if(!o)return s(-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 vt(o,r.params?.name,r.params?.arguments||{}))}catch(c){return i({content:[{type:"text",text:`error: ${c?.message||c}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function Yt(t,e){let n;try{n=await f(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=n.server||{},o=n.message;if(!r.command||!o)return a(e,400,{error:"need server.command and message"});try{const i=await it({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 Xt(t,e){let n;try{n=await f(t)}catch(p){return a(e,400,{error:"Bad JSON: "+p.message})}const{url:r,headers:o,message:i}=n||{};if(!r||!i)return a(e,400,{error:"need url and message"});let s;try{s=Z(r)}catch(p){return a(e,400,{error:String(p?.message||p)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[p,m]of Object.entries(o)){const b=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(b)||b.startsWith("x-"))&&(d[p]=String(m))}const l=new AbortController,c=setTimeout(()=>l.abort(),3e4);try{const p=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(i),redirect:"follow",signal:l.signal});try{p.url&&Z(p.url)}catch(b){return a(e,400,{error:String(b?.message||b)})}const m=await p.text().catch(()=>"");return a(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",body:m})}catch(p){const m=p?.name==="AbortError"?"timed out":String(p?.message||p);return a(e,502,{error:`couldn't reach MCP server ${s.host}: ${m}`})}finally{clearTimeout(c)}}const se=256*1024,Qt=5,Zt=8e3;async function qt(t){let e=q(t);const n=new AbortController,r=setTimeout(()=>n.abort(),Zt);try{for(let o=0;o<=Qt;o++){const i=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(i.status>=300&&i.status<400&&i.headers.get("location")){if(e=q(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 s=i.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}return{title:nn(await en(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function en(t){if(!t.body?.getReader)return(await t.text().catch(()=>"")).slice(0,se);const e=t.body.getReader(),n=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:i,value:s}=await e.read();if(i||(o+=s.byteLength,r+=n.decode(s,{stream:!0}),/<\/title\s*>/i.test(r)||o>=se))break}}finally{try{await e.cancel()}catch{}}return r}function tn(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 nn(t){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(t);return e?tn(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function on(t,e){let n;try{n=await f(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=n&&n.url;if(!r||typeof r!="string")return a(e,400,{error:"need url"});try{const o=await qt(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 rn(t,e){let n;try{n=await f(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=v.get(n.session);if(!r)return a(e,404,{error:"no such session"});const o=r.pending.get(n.id);return o?(r.pending.delete(n.id),o.resolve(n.result),a(e,200,{ok:!0})):a(e,404,{error:"no such pending call"})}async function an(t,e){let n;try{n=await f(t)}catch(d){return a(e,400,{error:"Bad JSON: "+d.message})}const r=T[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});const o=String(n.prompt||"").slice(0,6e3);if(!o)return a(e,400,{error:"Empty prompt"});const i=n.model||"",s=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 d="";return typeof r.engine.complete=="function"?d=await r.engine.complete({prompt:o,system:s,model:i}):await r.engine.chat({messages:[{role:"user",content:o}],system:s,options:{model:i}},l=>{l.type==="delta"?d+=l.text||"":l.type==="done"&&l.text&&(d+=l.text)}),a(e,200,{text:(d||"").trim()})}catch(d){return a(e,502,{error:d?.message||String(d)})}}async function sn(t,e){let n;try{n=await f(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=T[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});if(typeof r.engine.listModels!="function")return a(e,200,{models:[]});try{const o=await r.engine.listModels(n.options||{});return a(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return a(e,502,{error:o?.message||String(o)})}}async function cn(t,e){let n;try{n=await f(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=String(n.command||"").trim();if(!r)return a(e,400,{error:"No command"});let o=null;try{o=ot(r)}catch{o=null}return a(e,200,{ok:!!o,via:o?o.kind:null})}const ce=de(async(t,e)=>{if(xt(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 a(e,400,{error:"bad request"})}const r=Rt(t,n.pathname);if(r)return a(e,403,{error:r});try{if(t.method==="GET"&&n.pathname==="/health")return Ht(e);const o=n.searchParams.getAll("dir");if(t.method==="GET"&&n.pathname==="/skills")return _t(e,o);if(t.method==="GET"&&n.pathname==="/skills-quarantined")return Mt(e,o);if(t.method==="GET"&&n.pathname.startsWith("/skills/")){const i=n.pathname.slice(8),s=i.indexOf("/file/");return s===-1?Bt(e,decodeURIComponent(i),o):Gt(e,decodeURIComponent(i.slice(0,s)),decodeURIComponent(i.slice(s+6)),o)}if(n.pathname==="/connections"||n.pathname.startsWith("/connections/"))return jt(t,e,n.pathname);if(n.pathname==="/worktrees"||n.pathname.startsWith("/worktrees/"))return Wt(t,e,n.pathname);if(t.method==="GET"&&n.pathname==="/v1/models")return ae(e);if(t.method==="GET"&&n.pathname.startsWith("/v1/models/"))return ae(e,decodeURIComponent(n.pathname.slice(11)));if(t.method==="GET"&&n.pathname==="/debug"){const i=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return a(e,200,{version:g,agents:Object.fromEntries(et.map(s=>[s,i?Y(s)||null:!!Y(s)])),...i?{home:P.homedir(),path:process.env.PATH}:{}})}if(t.method==="POST"&&n.pathname==="/chat")return Lt(t,e);if(t.method==="POST"&&n.pathname==="/v1/chat/completions")return Ft(t,e);if(t.method==="POST"&&n.pathname==="/v1/completions")return Jt(t,e);if(t.method==="POST"&&n.pathname==="/v1/responses")return Kt(t,e);if(t.method==="POST"&&n.pathname==="/v1/messages")return zt(t,e);if(n.pathname==="/mcp"){if(t.method==="POST")return ie(t,e,null);if(t.method==="GET")return e.writeHead(405),e.end()}if(n.pathname.startsWith("/mcp/")){const i=decodeURIComponent(n.pathname.slice(5));if(t.method==="POST")return ie(t,e,i);if(t.method==="GET")return e.writeHead(405),e.end();if(t.method==="DELETE")return te(i),e.writeHead(204),e.end()}if(t.method==="GET"&&n.pathname==="/channels")return re(t,e,"status");if(t.method==="POST"&&n.pathname.startsWith("/channels/"))return re(t,e,n.pathname.slice(10));if(t.method==="POST"&&n.pathname==="/cancel")return Vt(t,e);if(t.method==="POST"&&n.pathname==="/tool-result")return rn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-local")return Yt(t,e);if(t.method==="POST"&&n.pathname==="/mcp-remote")return Xt(t,e);if(t.method==="POST"&&n.pathname==="/fetch-title")return on(t,e);if(t.method==="POST"&&n.pathname==="/complete")return an(t,e);if(t.method==="POST"&&n.pathname==="/list-models")return sn(t,e);if(t.method==="POST"&&n.pathname==="/agent-check")return cn(t,e);if(t.method==="POST"&&n.pathname==="/update")return Dt(e);a(e,404,{error:"Not found"})}catch(o){a(e,500,{error:o?.message||String(o)})}});function u(t,e){(t==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function ln(t){let e="";const n=[];let r=!1,o=!1;const i=()=>{o&&!r&&!n.length&&process.exit(0)},s=async()=>{if(!r){for(r=!0;n.length;){const d=n.shift();let l;try{l=JSON.parse(d)}catch{continue}try{const c=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(l.id==null)continue;const p=(await c.text()).trim();p&&process.stdout.write(p+`
|
|
10
|
+
`)}catch(c){l.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:l.id,error:{code:-32e3,message:String(c?.message||c)}})+`
|
|
11
|
+
`)}}r=!1,i()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",d=>{e+=d;let l;for(;(l=e.indexOf(`
|
|
12
|
+
`))>=0;){const c=e.slice(0,l).trim();e=e.slice(l+1),c&&n.push(c)}s()}),process.stdin.on("end",()=>{o=!0,i()}),process.stdin.resume()}function dn(){tt(),nt(),At(),ce.on("error",t=>{t&&t.code==="EADDRINUSE"&&(u("error",`Port ${O} 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)),u("error",`bridge server error: ${t?.message||t}`),process.exit(1)});for(const t of["SIGINT","SIGTERM"])process.on(t,()=>{const e=ct("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`),setTimeout(()=>process.exit(0),e?300:0).unref?.(),e||process.exit(0)});ce.listen(O,k,async()=>{u("info",`listening on http://${k}:${O}`),j.has(k)||u("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(T)){if(n)continue;const r=await t.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${e}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),oe().then(t=>t.startIfConfigured()).then(t=>{t?.skipped||(t?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${t?.error||"unknown error"}`))}).catch(t=>u("error",`channels: ${t?.message||t}`))})}function un(){console.log(`ChatPanel Bridge v${g}
|
|
1425
13
|
|
|
1426
14
|
Usage:
|
|
1427
|
-
chatpanel-bridge start the bridge (foreground) on ${
|
|
15
|
+
chatpanel-bridge start the bridge (foreground) on ${k}:${O}
|
|
1428
16
|
chatpanel-bridge --install run automatically at login, in the background
|
|
1429
17
|
chatpanel-bridge --uninstall remove the login auto-start
|
|
1430
18
|
chatpanel-bridge --status show whether auto-start is set up
|
|
1431
19
|
chatpanel-bridge --update download & install the latest version, then restart
|
|
1432
20
|
chatpanel-bridge --version print the version
|
|
1433
21
|
|
|
1434
|
-
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT`);
|
|
1435
|
-
}
|
|
1436
|
-
|
|
1437
|
-
// Handle CLI commands before starting the server. Returns true if a command ran.
|
|
1438
|
-
function runCli() {
|
|
1439
|
-
const argv = process.argv;
|
|
1440
|
-
const has = (...flags) => flags.some((f) => argv.includes(f));
|
|
1441
|
-
|
|
1442
|
-
if (has('--help', '-h')) {
|
|
1443
|
-
printHelp();
|
|
1444
|
-
return true;
|
|
1445
|
-
}
|
|
1446
|
-
if (has('--version', '-v')) {
|
|
1447
|
-
console.log(VERSION);
|
|
1448
|
-
return true;
|
|
1449
|
-
}
|
|
1450
|
-
if (has('--install')) {
|
|
1451
|
-
try {
|
|
1452
|
-
installService();
|
|
1453
|
-
log('info', 'Installed. The bridge now starts automatically at login and is running in the background.');
|
|
1454
|
-
} catch (e) {
|
|
1455
|
-
log('error', 'Install failed: ' + (e?.message || e));
|
|
1456
|
-
process.exitCode = 1;
|
|
1457
|
-
}
|
|
1458
|
-
return true;
|
|
1459
|
-
}
|
|
1460
|
-
if (has('--uninstall')) {
|
|
1461
|
-
try {
|
|
1462
|
-
uninstallService();
|
|
1463
|
-
log('info', 'Removed the login auto-start.');
|
|
1464
|
-
} catch (e) {
|
|
1465
|
-
log('error', 'Uninstall failed: ' + (e?.message || e));
|
|
1466
|
-
process.exitCode = 1;
|
|
1467
|
-
}
|
|
1468
|
-
return true;
|
|
1469
|
-
}
|
|
1470
|
-
if (has('--status')) {
|
|
1471
|
-
let on = false;
|
|
1472
|
-
try {
|
|
1473
|
-
on = serviceStatus();
|
|
1474
|
-
} catch (e) {
|
|
1475
|
-
log('error', String(e?.message || e));
|
|
1476
|
-
}
|
|
1477
|
-
log('info', `auto-start: ${on ? 'installed' : 'not installed'}`);
|
|
1478
|
-
return true;
|
|
1479
|
-
}
|
|
1480
|
-
return false;
|
|
1481
|
-
}
|
|
1482
|
-
|
|
1483
|
-
const mcpStdioIdx = process.argv.indexOf('--mcp-stdio');
|
|
1484
|
-
if (mcpStdioIdx >= 0) {
|
|
1485
|
-
const url = process.argv[mcpStdioIdx + 1];
|
|
1486
|
-
if (!url) {
|
|
1487
|
-
console.error('--mcp-stdio requires a URL');
|
|
1488
|
-
process.exit(1);
|
|
1489
|
-
}
|
|
1490
|
-
runMcpStdioProxy(url);
|
|
1491
|
-
} else if (process.argv.includes('--update')) {
|
|
1492
|
-
(async () => {
|
|
1493
|
-
try {
|
|
1494
|
-
const r = await selfUpdate(VERSION);
|
|
1495
|
-
log('info', `Updated v${r.from} → v${r.to}. Restarting the background service…`);
|
|
1496
|
-
restartService();
|
|
1497
|
-
} catch (e) {
|
|
1498
|
-
log('error', 'Update failed: ' + (e?.message || e));
|
|
1499
|
-
process.exitCode = 1;
|
|
1500
|
-
}
|
|
1501
|
-
})();
|
|
1502
|
-
} else if (!runCli()) {
|
|
1503
|
-
startServer();
|
|
1504
|
-
}
|
|
22
|
+
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT`)}function pn(){const t=process.argv,e=(...n)=>n.some(r=>t.includes(r));if(e("--help","-h"))return un(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("--install")){try{Pe(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(n){u("error","Install failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--uninstall")){try{$e(),u("info","Removed the login auto-start.")}catch(n){u("error","Uninstall failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--status")){let n=!1;try{n=Ie()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${n?"installed":"not installed"}`),!0}return!1}const le=process.argv.indexOf("--mcp-stdio");if(le>=0){const t=process.argv[le+1];t||(console.error("--mcp-stdio requires a URL"),process.exit(1)),ln(t)}else process.argv.includes("--update")?(async()=>{try{const t=await Q(g);u("info",`Updated v${t.from} → v${t.to}. Restarting the background service…`),J()}catch(t){u("error","Update failed: "+(t?.message||t)),process.exitCode=1}})():pn()||dn();
|