@chatpanel/bridge 0.13.7 → 0.13.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/engines/claude.js +5 -5
- package/src/server.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.8",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
|
|
6
6
|
"keywords": [
|
package/src/engines/claude.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{spawn as
|
|
2
|
-
`))>=0;){const
|
|
1
|
+
import{spawn as I}from"node:child_process";import{writeFile as O,unlink as R}from"node:fs/promises";import k from"node:os";import P from"node:path";import{resolveClaude as g,buildSpawnSpec as j,isCompiledBinary as Z,selfMcpStdio as ee}from"../env.js";import{signInStatus as te,signInMessage as F,loginRequired as re}from"../sign-in.js";import{buildCliPrompt as D}from"./prompt.js";import{summarizeCliError as oe}from"../cli-errors.js";import{killOnAbort as ne}from"../proc.js";import{pushExtraArgs as se,FORBIDDEN as ae}from"./args.js";import{relayTimeoutMax as ie}from"../relay-timeout.js";import{displayPath as le,resolveWorkdir as H}from"../workdir.js";import{connectorsFor as ce}from"../connectors.js";import{chatWarm as ue}from"./claude-warm.js";async function de(e,t){const n=[];for(let i=0;i<(e?.length||0);i++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[i]?.dataUrl||"");if(!s)continue;const o=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",r=P.join(k.tmpdir(),`chatpanel-claude-img-${t}-${i}.${o}`);await O(r,Buffer.from(s[2],"base64")),n.push(r)}return n}const z=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,U=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task"],B=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),pe=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task","ToolSearch"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch"])}),fe=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),me=Object.freeze(["remember","forget"]),G=Object.freeze({device:Object.freeze([]),trusted:fe});function he(e,t=[]){const n=G[e]||G.device,i=(t||[]).filter(r=>typeof r=="string"&&/^chatpanel/i.test(r)),s=[],o=[];for(const r of i){for(const a of n)s.push(`mcp__${r}__${a}`);for(const a of me)o.push(`mcp__${r}__${a}`)}return{allow:s,deny:o}}function ye(e){if(!e||e==="any")return null;const t=B[e]?e:"device";return{allow:[...B[t]],deny:[...pe[t]]}}let S="Claude Code not found.",q=0,b=!1;async function He(){if(Date.now()-q>(b?3e4:4e3)){q=Date.now();try{g()||!Z()&&await L()?b=!0:(b=!1,S=process.platform==="win32"?"Claude Code not found on Windows PATH or in WSL. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in — in Windows or in your WSL distro.":"Claude Code not found on PATH. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in.")}catch{b=!1}}return b?await te("claude",g()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:F("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:S}}async function ze(){return["opus","sonnet","haiku"]}function _e(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:n,args:i}=ee(e.url),s=[...new Set(e.specs.map(o=>o?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:n,args:i}}},allowedTools:s.map(o=>`mcp__${t}__${o}`)}}function Y({prompt:e,args:t,cwd:n,env:i=null,emit:s,signal:o}){const r=g();if(!r)return null;const[a,c,h]=j(r,t,n,i);return new Promise((y,p)=>{let u;try{u=I(a,c,h)}catch(m){return p(new Error(`Failed to start claude: ${m.message}`))}const l=ne(u,o);let d="",_="",w=!1,f=null;const T={sawText:!1,tail:"",boundary:!1};let A="",C;const v=()=>{clearTimeout(C),C=setTimeout(()=>{u.kill("SIGKILL"),p(new Error(`Claude Code timed out — no output for ${Math.round(z/1e3)}s.`))},z)};v(),u.stdout.on("data",m=>{v(),d+=m.toString();let M;for(;(M=d.indexOf(`
|
|
2
|
+
`))>=0;){const $=d.slice(0,M).trim();if(d=d.slice(M+1),!$.startsWith("{"))continue;let W;try{W=JSON.parse($)}catch{continue}const E=K(W,s,w,n,T);E.streamed&&(w=!0),E.result!=null&&(A=E.result),E.apiError&&(f=E.apiError)}}),u.stderr.on("data",m=>{v(),_+=m.toString()}),u.on("error",m=>{clearTimeout(C),l(),p(new Error(`Failed to start claude (${a}): ${m.message}`))}),u.on("close",m=>{if(clearTimeout(C),l(),o?.aborted){y({streamedAny:w,resultText:A});return}if(f&&re(f))return p(new Error(F("Claude Code","claude")));if(m===0&&f)return p(new Error(`Claude Code reported an error: ${f}`));m===0?y({streamedAny:w,resultText:A}):p(new Error(oe("Claude Code",m,_,f||"",{agentId:"claude"})))}),u.stdin.write(e),u.stdin.end()})}function we(e){let t="";return typeof e=="string"?t=e:Array.isArray(e)&&(t=e.map(n=>typeof n=="string"?n:n?.text||"").filter(Boolean).join(`
|
|
3
3
|
`)),t.length>4e3?`${t.slice(0,4e3)}…`:t}function J(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
|
|
4
4
|
|
|
5
|
-
`}),e.boundary=!1)}function X(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function K(e,t,
|
|
6
|
-
`)||String(e.error||"api error"),
|
|
5
|
+
`}),e.boundary=!1)}function X(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function K(e,t,n,i="",s=null){const o={streamed:!1,result:null};if(e.type==="stream_event"){const r=e.event;r?.type==="content_block_delta"&&(r.delta?.type==="text_delta"?(o.streamed=!0,J(s,t),t({type:"delta",text:r.delta.text}),X(s,r.delta.text)):r.delta?.type==="thinking_delta"&&t({type:"reasoning",text:r.delta.thinking||""}))}else if(e.type==="assistant"){if(e.is_api_error_message||e.error)return o.apiError=(e.message?.content||[]).filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
6
|
+
`)||String(e.error||"api error"),o;for(const r of e.message?.content||[])r.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:r.name,phase:"start",callId:r.id,input:r.input,summary:Ce(r,i)})):r.type==="text"&&!n&&(o.streamed=!0,J(s,t),t({type:"delta",text:r.text}),X(s,r.text))}else if(e.type==="user")for(const r of e.message?.content||[])r.type==="tool_result"&&t({type:"tool",phase:"done",callId:r.tool_use_id,status:r.is_error?"error":"ok",result:we(r.content)});else if(e.type==="result"){e.is_error?o.apiError=o.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?o.result=e.result||"":t({type:"status",text:`(${e.subtype})`});const r=e.usage||e.message?.usage;r&&t({type:"usage",provider:"bridge",inputTokens:r.input_tokens||0,outputTokens:r.output_tokens||0,cacheReadTokens:r.cache_read_input_tokens||0,cacheWriteTokens:r.cache_creation_input_tokens||0,costUsd:e.total_cost_usd!=null?e.total_cost_usd:null})}return o}const Q=process.env.CHATPANEL_CLAUDE_EFFORT??"low";let x=null;function V({probe:e=null}={}){return x||(x=(async()=>{try{return String(await(e?e():new Promise(t=>{const[n,i,s]=j(g(),["--help"],null),o=I(n,i,{...s,stdio:["ignore","pipe","pipe"]});let r="";o.stdout.on("data",a=>{r+=a}),o.on("error",()=>t("")),o.on("close",()=>t(r)),setTimeout(()=>{try{o.kill()}catch{}t(r)},8e3).unref?.()}))||"")}catch{return""}})(),x)}async function be(e={}){return/--effort\b/.test(await V(e))}async function Te(e={}){return/--append-system-prompt-file\b/.test(await V(e))}function Ue(){x=null}async function Ee({system:e,options:t,tag:n}){const i=t.permissionMode||"default",s=H(t.workingDir),o=["--print","--output-format","stream-json","--include-partial-messages","--verbose"];Q&&await be()&&o.push("--effort",Q);const r=[],a=[],c=_e(t.mcp);if(c){const l=P.join(k.tmpdir(),`chatpanel-mcp-${n}.json`);await O(l,JSON.stringify(c.config)),r.push(l),o.push("--mcp-config",l),a.push(...c.allowedTools)}const h=ye(t.reach);if(h){const l=he(t.reach,await ce("claude").catch(()=>[]));o.push("--allowedTools",...h.allow,...a,...l.allow),o.push("--disallowedTools",...h.deny,...l.deny)}else i==="bypassPermissions"?o.push("--permission-mode","bypassPermissions"):i==="acceptEdits"?(o.push("--permission-mode","acceptEdits"),a.length&&o.push("--allowedTools",...a)):o.push("--allowedTools",...U,...a);if(e)if(g()?.kind!=="wsl"&&await Te()){const d=P.join(k.tmpdir(),`chatpanel-system-${n}.md`);await O(d,e,{mode:384}),r.push(d),o.push("--append-system-prompt-file",d)}else o.push("--append-system-prompt",e);t.model&&o.push("--model",t.model),t.useLocalConfig===!1&&o.push("--setting-sources","");const y=c&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(ie(t.mcp?.specs))}:null,p=y||t.runEnv?{...t.runEnv||{},...y||{}}:null;return{args:o,cwd:s,runEnv:p,cleanup:()=>r.forEach(l=>R(l).catch(()=>{})),hasMcp:!!c}}function ge(e,t=[],n=""){let i=D(e,n);return t.length&&(i+=`
|
|
7
7
|
|
|
8
|
-
The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}async function
|
|
8
|
+
The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}async function Be({messages:e,system:t,options:n,images:i},s,{signal:o}={}){const r=await ue({messages:e,system:t,options:n,images:i},s,{signal:o}).catch(a=>({handled:!1,reason:a?.message||String(a),thrown:!0}));if(!r.handled&&!o?.aborted){if(r.thrown)throw new Error(r.reason);return xe({messages:e,system:t,options:n,images:i},s,{signal:o})}}async function xe({messages:e,system:t,options:n,images:i},s,{signal:o}={}){const r=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=await Ee({system:t,options:n,tag:r}),{args:c,cwd:h,runEnv:y}=a,p=await de(i,r),u=()=>{p.forEach(_=>R(_).catch(()=>{})),a.cleanup()},l=ge(e,p);se(c,n.extraArgs,ae.claude,s);const d=Y({prompt:l,args:c,cwd:h,env:y,emit:s,signal:o});if(d===null)return u(),ke({messages:e,system:t,options:n},s,{signal:o});try{const{streamedAny:_,resultText:w}=await d;s({type:"done",text:_?"":w})}finally{u()}}async function Ge({prompt:e,system:t,model:n}){const i=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",n||"haiku","--system-prompt",t||"Continue the user's text briefly. Reply with only the continuation."];let s="";const o=Y({prompt:e,args:i,cwd:null,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(o===null)return Se({prompt:e,system:t,model:n});const{resultText:r}=await o;return(s||r||"").trim()}function Ce(e,t=""){const n=e.input||{};return n.command?String(n.command).slice(0,60):n.file_path?le(n.file_path,t):n.pattern?n.pattern:n.url?n.url:n.description?String(n.description).slice(0,80):n.query?String(n.query).slice(0,80):n.prompt?String(n.prompt).slice(0,80):""}let N=null;function L(){return N||(N=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),N}async function ke({messages:e,system:t,options:n},i,{signal:s}={}){const o=await L();if(!o)throw new Error(S);const{query:r}=o,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const c=n.permissionMode||"default",h=H(n.workingDir),y=c==="acceptEdits"||c==="bypassPermissions",p=new Set(U),u=async f=>p.has(f)||y?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${f} blocked — set this agent's permission mode in ChatPanel to enable it.`};let l=!1;const d={sawText:!1,tail:"",boundary:!1};let _="";const w=r({prompt:D(e),options:{cwd:h,permissionMode:c,includePartialMessages:!0,canUseTool:u,abortController:a,settingSources:n.useLocalConfig===!1?[]:["user","project"],systemPrompt:t?{type:"preset",preset:"claude_code",append:t}:{type:"preset",preset:"claude_code"},...n.model?{model:n.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const f of w){const T=K(f,i,l,h,d);T.streamed&&(l=!0),T.result!=null&&(_=T.result)}}catch(f){if(s?.aborted||a.signal.aborted)return;throw f}i({type:"done",text:l?"":_})}async function Se({prompt:e,system:t,model:n}){const i=await L();if(!i)throw new Error(S);const{query:s}=i;let o="";const r=s({prompt:e,options:{cwd:k.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:t||"Continue the user's text briefly. Reply with only the continuation.",model:n||"haiku"}});for await(const a of r)if(a.type==="assistant")for(const c of a.message.content)c.type==="text"&&(o+=c.text);else a.type==="result"&&a.subtype==="success"&&!o&&(o=a.result||"");return o.trim()}export{Ue as _resetEffortProbe,He as available,Ee as buildClaudeLaunch,he as channelMcpTools,ye as channelToolPolicy,Be as chat,xe as chatCold,_e as claudeMcpConfig,ge as claudePrompt,be as claudeSupportsEffort,Te as claudeSupportsSystemPromptFile,Ge as complete,K as handleMessage,ze as listModels,de as writeImages};
|
package/src/server.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createServer as fe}from"node:http";import A from"node:os";import{randomBytes as ge,randomInt as ye,timingSafeEqual as we}from"node:crypto";import{mkdirSync as be,writeFileSync as Se,readFileSync as K,existsSync as ke}from"node:fs";import{join as _}from"node:path";import*as Te from"./engines/claude.js";import*as ve from"./engines/codex.js";import*as Ce from"./engines/antigravity.js";import{pi as Ee,opencode as Oe,kiro as Pe,copilot as Ae,deepseek as xe,hermes as $e}from"./engines/cli-agents.js";import{connectorsFor as Ie}from"./connectors.js";import*as Ne from"./engines/custom.js";import{installService as Re,uninstallService as _e,serviceStatus as He,restartService as V}from"./service.js";import{skillIndex as D,listRecords as Me,readRecord as Be,readPackageFile as Ge,skillsHealth as Ue,quarantinedSkills as De}from"./skills.js";import{capabilityToolSpecs as Le,runCapabilityTool as je}from"./mcp-capabilities.js";import{createSession as We,deleteSession as X,getSession as Y,activeSession as Fe,relayToolCall as Je}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ze,isDefaultWorkdir as Ke,resolveWorkdir as Ve,writeScopeNote as Xe}from"./workdir.js";import{gitState as Ye,gitDelta as Qe}from"./scm.js";import{listConnections as Ze,putConnection as qe,removeConnection as et,runEnvFor as tt,testConnection as nt,secretBackend as Q}from"./connections.js";import{worktreeFor as Z,listWorktrees as rt,removeWorktree as ot,withHook as at,WORKTREE_ROOT as q}from"./worktree.js";import{AGENT_CLIS as it,enrichPath as st,enrichAgentEnv as ct,findAgentBin as ee,resolveCommand as lt}from"./env.js";import"./sanitize.js";import{checkForUpdate as dt,selfUpdate as te,isEmbedded as ut}from"./update.js";import{callLocalMcp as ht}from"./mcp-local.js";import{assertPublicHttpUrl as ne,assertPublicWebUrl as re}from"./ssrf.js";import{startRun as oe,endRun as L,cancelRun as pt,cancelAll as mt}from"./runs.js";import{closeWarmPools as ft,warmStatus as gt}from"./warm.js";import{CompatError as x,anthropicError as j,anthropicStream as yt,chatCompletionStream as wt,completionStream as bt,createAnthropicMessage as St,createChatCompletion as kt,createCompletion as Tt,createResponse as vt,openAIError as w,parseAnthropicMessage as Ct,parseChatCompletion as Et,parseCompletion as Ot,parseResponse as Pt,responseStream as At}from"./api-compat.js";import{callerTrust as xt,isPaired as $,parseExtensionIds as $t,capRunOptions as It,engineHonoursReach as Nt,createPairingStore as Rt,formatPairingCode as _t}from"./pii/trust.js";const g="0.13.7",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Te,label:"Claude Code"},codex:{engine:ve,label:"Codex"},antigravity:{engine:Ce,label:"Antigravity",tools:!1},pi:{engine:Ee,label:"Pi"},opencode:{engine:Oe,label:"OpenCode"},hermes:{engine:$e,label:"Hermes"},kiro:{engine:Pe,label:"Kiro"},copilot:{engine:Ae,label:"GitHub Copilot"},deepseek:{engine:xe,label:"DeepSeek Harness"},custom:{engine:Ne,label:"Custom",hidden:!0}};function ae(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Ht=$t(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function I(n){return n.chatpanelTrust||(n.chatpanelTrust=xt({origin:n.headers.origin||"",hasToken:le(n),extensionIds:Ht})),n.chatpanelTrust}function Mt(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Bt(n,e){const t=n.headers.origin||"",o=ae(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const W=new Set(["127.0.0.1","localhost","::1"]);function Gt(n){if(!W.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return W.has(t)}const N=_(A.homedir(),".chatpanel","bridge-token");let S="";function Ut(){try{ke(N)&&(S=K(N,"utf8").trim()),S||(S=ge(32).toString("hex"),be(_(A.homedir(),".chatpanel"),{recursive:!0}),Se(N,S,{mode:384}))}catch(n){d("error",`could not initialise bridge token: ${n?.message||n}`)}}const ie=Rt({random:()=>ye(0,1e6)/1e6});function Dt(n){if(!S)return a(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ie.issue();return d("info","pairing code issued — valid for 5 minutes, one use"),a(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Lt(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=ie.claim(t?.code);return o.ok?(d("info",`paired a ${I(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),a(e,200,{ok:!0,token:S})):(d("info",`pairing refused (${o.reason}) from ${I(n)} caller`),a(e,403,{error:o.reason}))}function jt(n,e){const t=I(n);return a(e,200,{ok:!0,trust:t,paired:$(t),version:g})}let H=null;async function se(){if(H)return H;const{createChannelService:n}=await import("./channels/service.js");return H=n({home:_(A.homedir(),".chatpanel"),dataDir:_(A.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>d("info",e),warn:e=>d("info",e),error:e=>d("error",e)}}),H}async function ce(n,e,t){try{const o=await se(),r=n.method==="POST"?await f(n):{};if(t==="status")return a(e,200,await o.status());if(t==="connect"){const i=await o.connect(r);return a(e,200,{ok:!0,...i})}return t==="pair"?a(e,200,await o.pair()):t==="unpair"?a(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?a(e,200,await o.update(r)):t==="disconnect"?a(e,200,await o.stop({forget:!!r.forget})):a(e,404,{error:"unknown channel action"})}catch(o){return a(e,400,{error:o?.message||String(o)})}}function le(n){if(!S)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(S);return o.length===r.length&&we(o,r)}const Wt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),Ft=new Set(["/debug"]),Jt=n=>Ft.has(n);function zt(n,e){if(!Gt(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ae(t))return"forbidden origin";const o=n.method==="POST"&&Wt.has(e)||n.method==="GET"&&Jt(e);return o&&!(Mt(t)||le(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!$(I(n))&&!Vt.has(e)?Kt:null}const Kt="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",Vt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(n,e,t){const o=I(n),r=It(t,o);if(!Nt(e,r.reach))return{error:`${$(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${$(o)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const i=r.reach,s=$(o)?i==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":i==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:r,note:s}}function a(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}async function Xt(n){const e=await Promise.all(Object.entries(C).filter(([,r])=>!r.hidden).map(async([r,{engine:i,label:s,tools:u}])=>{const c=await i.available().catch(h=>({ok:!1,reason:String(h?.message||h)})),l=await Ie(r).catch(()=>[]);return{id:r,label:s,available:c.ok,reason:c.reason,connectors:l,...u===!1?{tools:!1}:{}}})),t=ut()?{current:g,updateAvailable:!1,embedded:"gateway"}:await dt(g).catch(()=>({current:g,updateAvailable:!1})),o=await Ue().catch(()=>null);a(n,200,{ok:!0,version:g,agents:e,update:t,workspace:ze,worktrees:q,secretBackend:Q(),warm:gt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...o?{skills:o}:{}})}async function Yt(n,e,t){const{index:o,problems:r}=await D({extraDirs:e,workdir:t});a(n,200,{ok:!0,skills:Me(o),problems:r})}async function Qt(n,e,t){a(n,200,{ok:!0,quarantined:await De(e,t)})}async function Zt(n,e,t,o){const{index:r}=await D({extraDirs:t,workdir:o}),i=Be(r,e);if(!i)return a(n,404,{ok:!1,error:"unknown skill"});a(n,200,{ok:!0,skill:i})}async function qt(n,e,t,o,r){const{index:i}=await D({extraDirs:o,workdir:r}),s=await Ge(i,e,t);if(s.error)return a(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});a(n,200,{ok:!0,...s})}async function en(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function de(n,e=""){const t=await en();if(e){const o=t.find(r=>r.id===e);return o?a(n,200,o):a(n,404,w(new x(`Model "${e}" not found`,404,"model")))}return a(n,200,{object:"list",data:t})}async function tn(n){try{const e=await te(g);a(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){a(n,400,{ok:!1,error:String(e?.message||e)})}}async function nn(n,e){let t;try{t=await f(n)}catch(p){return a(e,400,{error:"Bad JSON: "+p.message})}const o=C[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});const r=F(n,t.agent,t.options||{});if(r.error)return a(e,403,{error:r.error});t.options=r.options,Array.isArray(t.images)&&t.images.length&&d("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const i=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
|
|
2
|
+
import{createServer as fe}from"node:http";import A from"node:os";import{randomBytes as ge,randomInt as ye,timingSafeEqual as we}from"node:crypto";import{mkdirSync as be,writeFileSync as Se,readFileSync as K,existsSync as ke}from"node:fs";import{join as _}from"node:path";import*as Te from"./engines/claude.js";import*as ve from"./engines/codex.js";import*as Ce from"./engines/antigravity.js";import{pi as Ee,opencode as Oe,kiro as Pe,copilot as Ae,deepseek as xe,hermes as $e}from"./engines/cli-agents.js";import{connectorsFor as Ie}from"./connectors.js";import*as Ne from"./engines/custom.js";import{installService as Re,uninstallService as _e,serviceStatus as He,restartService as V}from"./service.js";import{skillIndex as D,listRecords as Me,readRecord as Be,readPackageFile as Ge,skillsHealth as Ue,quarantinedSkills as De}from"./skills.js";import{capabilityToolSpecs as Le,runCapabilityTool as je}from"./mcp-capabilities.js";import{createSession as We,deleteSession as X,getSession as Y,activeSession as Fe,relayToolCall as Je}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ze,isDefaultWorkdir as Ke,resolveWorkdir as Ve,writeScopeNote as Xe}from"./workdir.js";import{gitState as Ye,gitDelta as Qe}from"./scm.js";import{listConnections as Ze,putConnection as qe,removeConnection as et,runEnvFor as tt,testConnection as nt,secretBackend as Q}from"./connections.js";import{worktreeFor as Z,listWorktrees as rt,removeWorktree as ot,withHook as at,WORKTREE_ROOT as q}from"./worktree.js";import{AGENT_CLIS as it,enrichPath as st,enrichAgentEnv as ct,findAgentBin as ee,resolveCommand as lt}from"./env.js";import"./sanitize.js";import{checkForUpdate as dt,selfUpdate as te,isEmbedded as ut}from"./update.js";import{callLocalMcp as ht}from"./mcp-local.js";import{assertPublicHttpUrl as ne,assertPublicWebUrl as re}from"./ssrf.js";import{startRun as oe,endRun as L,cancelRun as pt,cancelAll as mt}from"./runs.js";import{closeWarmPools as ft,warmStatus as gt}from"./warm.js";import{CompatError as x,anthropicError as j,anthropicStream as yt,chatCompletionStream as wt,completionStream as bt,createAnthropicMessage as St,createChatCompletion as kt,createCompletion as Tt,createResponse as vt,openAIError as w,parseAnthropicMessage as Ct,parseChatCompletion as Et,parseCompletion as Ot,parseResponse as Pt,responseStream as At}from"./api-compat.js";import{callerTrust as xt,isPaired as $,parseExtensionIds as $t,capRunOptions as It,engineHonoursReach as Nt,createPairingStore as Rt,formatPairingCode as _t}from"./pii/trust.js";const g="0.13.8",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Te,label:"Claude Code"},codex:{engine:ve,label:"Codex"},antigravity:{engine:Ce,label:"Antigravity",tools:!1},pi:{engine:Ee,label:"Pi"},opencode:{engine:Oe,label:"OpenCode"},hermes:{engine:$e,label:"Hermes"},kiro:{engine:Pe,label:"Kiro"},copilot:{engine:Ae,label:"GitHub Copilot"},deepseek:{engine:xe,label:"DeepSeek Harness"},custom:{engine:Ne,label:"Custom",hidden:!0}};function ae(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Ht=$t(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function I(n){return n.chatpanelTrust||(n.chatpanelTrust=xt({origin:n.headers.origin||"",hasToken:le(n),extensionIds:Ht})),n.chatpanelTrust}function Mt(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Bt(n,e){const t=n.headers.origin||"",o=ae(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const W=new Set(["127.0.0.1","localhost","::1"]);function Gt(n){if(!W.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return W.has(t)}const N=_(A.homedir(),".chatpanel","bridge-token");let S="";function Ut(){try{ke(N)&&(S=K(N,"utf8").trim()),S||(S=ge(32).toString("hex"),be(_(A.homedir(),".chatpanel"),{recursive:!0}),Se(N,S,{mode:384}))}catch(n){d("error",`could not initialise bridge token: ${n?.message||n}`)}}const ie=Rt({random:()=>ye(0,1e6)/1e6});function Dt(n){if(!S)return a(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ie.issue();return d("info","pairing code issued — valid for 5 minutes, one use"),a(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Lt(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=ie.claim(t?.code);return o.ok?(d("info",`paired a ${I(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),a(e,200,{ok:!0,token:S})):(d("info",`pairing refused (${o.reason}) from ${I(n)} caller`),a(e,403,{error:o.reason}))}function jt(n,e){const t=I(n);return a(e,200,{ok:!0,trust:t,paired:$(t),version:g})}let H=null;async function se(){if(H)return H;const{createChannelService:n}=await import("./channels/service.js");return H=n({home:_(A.homedir(),".chatpanel"),dataDir:_(A.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>d("info",e),warn:e=>d("info",e),error:e=>d("error",e)}}),H}async function ce(n,e,t){try{const o=await se(),r=n.method==="POST"?await f(n):{};if(t==="status")return a(e,200,await o.status());if(t==="connect"){const i=await o.connect(r);return a(e,200,{ok:!0,...i})}return t==="pair"?a(e,200,await o.pair()):t==="unpair"?a(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?a(e,200,await o.update(r)):t==="disconnect"?a(e,200,await o.stop({forget:!!r.forget})):a(e,404,{error:"unknown channel action"})}catch(o){return a(e,400,{error:o?.message||String(o)})}}function le(n){if(!S)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(S);return o.length===r.length&&we(o,r)}const Wt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),Ft=new Set(["/debug"]),Jt=n=>Ft.has(n);function zt(n,e){if(!Gt(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ae(t))return"forbidden origin";const o=n.method==="POST"&&Wt.has(e)||n.method==="GET"&&Jt(e);return o&&!(Mt(t)||le(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!$(I(n))&&!Vt.has(e)?Kt:null}const Kt="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",Vt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(n,e,t){const o=I(n),r=It(t,o);if(!Nt(e,r.reach))return{error:`${$(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${$(o)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const i=r.reach,s=$(o)?i==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":i==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:r,note:s}}function a(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}async function Xt(n){const e=await Promise.all(Object.entries(C).filter(([,r])=>!r.hidden).map(async([r,{engine:i,label:s,tools:u}])=>{const c=await i.available().catch(h=>({ok:!1,reason:String(h?.message||h)})),l=await Ie(r).catch(()=>[]);return{id:r,label:s,available:c.ok,reason:c.reason,connectors:l,...u===!1?{tools:!1}:{}}})),t=ut()?{current:g,updateAvailable:!1,embedded:"gateway"}:await dt(g).catch(()=>({current:g,updateAvailable:!1})),o=await Ue().catch(()=>null);a(n,200,{ok:!0,version:g,agents:e,update:t,workspace:ze,worktrees:q,secretBackend:Q(),warm:gt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...o?{skills:o}:{}})}async function Yt(n,e,t){const{index:o,problems:r}=await D({extraDirs:e,workdir:t});a(n,200,{ok:!0,skills:Me(o),problems:r})}async function Qt(n,e,t){a(n,200,{ok:!0,quarantined:await De(e,t)})}async function Zt(n,e,t,o){const{index:r}=await D({extraDirs:t,workdir:o}),i=Be(r,e);if(!i)return a(n,404,{ok:!1,error:"unknown skill"});a(n,200,{ok:!0,skill:i})}async function qt(n,e,t,o,r){const{index:i}=await D({extraDirs:o,workdir:r}),s=await Ge(i,e,t);if(s.error)return a(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});a(n,200,{ok:!0,...s})}async function en(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function de(n,e=""){const t=await en();if(e){const o=t.find(r=>r.id===e);return o?a(n,200,o):a(n,404,w(new x(`Model "${e}" not found`,404,"model")))}return a(n,200,{object:"list",data:t})}async function tn(n){try{const e=await te(g);a(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){a(n,400,{ok:!1,error:String(e?.message||e)})}}async function nn(n,e){let t;try{t=await f(n)}catch(p){return a(e,400,{error:"Bad JSON: "+p.message})}const o=C[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});const r=F(n,t.agent,t.options||{});if(r.error)return a(e,403,{error:r.error});t.options=r.options,Array.isArray(t.images)&&t.images.length&&d("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const i=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
|
|
3
3
|
|
|
4
4
|
`)};let s=!1;const u=`run_${Math.random().toString(36).slice(2,10)}`,c=oe(u),l={signal:c.signal,abort:()=>c.cancel("client")},h=()=>{s=!0,c.cancel("disconnected")};n.on("close",h),e.on("close",h),e.on("error",h);const b=p=>{s||i(p)};i({type:"run",id:u}),r.note&&i({type:"status",text:r.note});let m=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const p=t.options.workspace;if(m=await Z({repo:p.repo,projectId:p.projectId,jobId:p.jobId,base:p.base||null}),m.error){i({type:"error",error:`workspace: ${m.error}`}),L(u),e.writableEnded||e.end();return}}const J=m?m.path:Ve(t.options?.workingDir);let E=null;{const p=J,O=!!m||!Ke(t.options?.workingDir),y=Xe(t.agent,t.options?.permissionMode,p);i({type:"workdir",path:p,isDefault:!O,writeScope:y||void 0}),i({type:"status",text:`Working in ${p}${O?"":" (default)"}`}),y&&i({type:"status",text:y}),E=await Ye(p),E&&i({type:"scm",phase:"before",...E})}let U=null;if(E||m){const p=Array.isArray(t.options?.grants)?t.options.grants:[],{env:O,connection:y}=tt({remote:E?.remote||null,grants:p,branch:m?.branch||null,connectionId:t.options?.connectionId||null});U=at(O),m&&i({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&i({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const z={...t.options||{},...m?{workingDir:m.path}:{},...U?{runEnv:U}:{}};let R=null;t.pageTools?.specs?.length&&(R=We(b,t.pageTools.specs),z.mcp={url:`http://${k}:${v}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs});try{await o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:z,images:Array.isArray(t.images)?t.images:[]},b,{signal:l.signal})}catch(p){d("error",`${t.agent} chat failed: ${p?.message||p}`),i({type:"error",error:p?.message||String(p)})}finally{if(!s){const p=await Qe(J,E).catch(()=>null);p&&b({type:"scm",phase:"after",...p})}L(u),R&&X(R.id),e.writableEnded||e.end()}}async function rn(n,e,t){if(n.method==="GET"&&t==="/connections")return a(e,200,{ok:!0,connections:Ze(),secretBackend:Q()});if(n.method!=="POST")return a(e,405,{error:"method not allowed"});const o=await f(n);if(t==="/connections")try{return a(e,200,{ok:!0,connection:qe(o.connection||o,{token:o.token||null})})}catch(i){return a(e,400,{error:String(i?.message||i)})}const r=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return r?r[2]==="delete"?a(e,200,{ok:et(r[1])}):a(e,200,nt(r[1],o.remote||"")):a(e,404,{error:"Not found"})}async function on(n,e,t){if(n.method==="GET"&&t==="/worktrees")return a(e,200,{ok:!0,root:q,worktrees:await rt()});if(n.method!=="POST")return a(e,405,{error:"method not allowed"});const o=await f(n);if(t==="/worktrees"){const r=await Z({repo:o.repo,projectId:o.projectId,jobId:o.jobId,base:o.base||null});return a(e,r.error?400:200,r.error?{error:r.error}:{ok:!0,...r})}if(t==="/worktrees/remove"){const r=await ot({projectId:o.projectId,jobId:o.jobId,force:!!o.force});return a(e,r.ok?200:400,r)}return a(e,404,{error:"Not found"})}async function T(n,e,t){const o=C[n.agent];if(!o||o.hidden)throw new x(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const r=await o.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!r.ok)throw new x(r.reason||`${n.agent} is unavailable`,503,"model");const i=`run_${Math.random().toString(36).slice(2,10)}`,s=oe(i),u=()=>s.cancel("disconnected");t.on("close",u);let c="";try{return await o.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal}),c}finally{t.off("close",u),L(i)}}function M(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function P(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
|
|
5
5
|
|