@chatpanel/bridge 0.12.0 → 0.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.12.0",
3
+ "version": "0.12.2",
4
4
  "type": "module",
5
5
  "description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
@@ -1,3 +1,3 @@
1
- import{unlink as P}from"node:fs/promises";import{spawnRpcChild as N}from"../rpc-child.js";import{createWarmPool as O}from"../warm-pool.js";import{registerWarmPool as q}from"../warm.js";import{createSession as R,deleteSession as T,rebindSession as W,releaseSession as I}from"../mcp-sessions.js";import{resolveClaude as H,buildSpawnSpec as j}from"../env.js";import{loginRequired as _,signInMessage as M}from"../sign-in.js";import{pushExtraArgs as L,FORBIDDEN as k}from"./args.js";import{buildClaudeLaunch as U,claudePrompt as B,handleMessage as F,writeImages as G}from"./claude.js";const D=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,J=5e3,f=q("claude",O({log:u=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${u}`)}}));function z(u={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||u.warm===!1)}function K({spec:u,args:y,cwd:t,env:v,spawnImpl:p,log:w=()=>{}}){const $=[...y,"--input-format","stream-json"],[C,A,S]=j(u,$,t,v);let e=null;const m=new Set;let o="",x=0;const l=N(C,A,{spawnOpts:S,spawnImpl:p,jsonrpc:!1,onStderr:s=>{o=(o+s).slice(-2e3),e&&e.touch()},onExit:s=>{if(w(`claude exited: ${s.signal||s.code}${o?` — ${o.trim().split(`
2
- `).pop()}`:""}`),e){const i=e.apiError&&_(e.apiError)?M("Claude Code","claude"):e.apiError?`Claude Code reported an error: ${e.apiError}`:`Claude Code exited (${s.signal||s.code})${o?`: ${o.trim().split(`
3
- `).pop().slice(0,200)}`:""}`;e.finish({status:"died",error:i})}for(const i of m)try{i(s)}catch{}},onMessage:s=>{if(!e||(e.touch(),s.type==="control_response"))return;const i=F(s,e.emit,e.streamedAny,t,e.flow);i.streamed&&(e.streamedAny=!0),i.result!=null&&(e.resultText=i.result),i.apiError&&(e.apiError=i.apiError),s.type==="result"&&(e.apiError&&_(e.apiError)?e.finish({status:"failed",error:M("Claude Code","claude")}):e.apiError?e.finish({status:"failed",error:`Claude Code reported an error: ${e.apiError}`}):e.finish({status:"completed",error:null}))}});return{get pid(){return l.pid},get alive(){return!l.exited},onExit(s){m.add(s)},close(){l.close()},async turn({prompt:s,emit:i,signal:h}){if(l.exited)throw new Error("Claude Code process is gone");if(e)throw new Error("a turn is already running on this process");let n=null,a;const c=new Promise(g=>{a=g}),r={emit:i,flow:{sawText:!1,tail:"",boundary:!1},streamedAny:!1,resultText:"",apiError:null,touch(){clearTimeout(n),n=setTimeout(()=>r.finish({status:"timeout",error:`Claude Code timed out — no output for ${Math.round(D/1e3)}s.`}),D)},finish(g){e===r&&(clearTimeout(n),e=null,a(g))}};e=r,r.touch();const E=()=>{if(e===r){r.interrupted=!0;try{l.send({type:"control_request",request_id:`stop_${++x}`,request:{subtype:"interrupt"}})}catch{}setTimeout(()=>{e===r&&(r.finish({status:"killed",error:null}),l.kill())},J).unref?.()}};if(h?.aborted)return r.finish({status:"killed",error:null}),{streamedAny:!1,resultText:"",status:"killed"};h?.addEventListener("abort",E,{once:!0});try{l.send({type:"user",message:{role:"user",content:s}})}catch(g){r.finish({status:"failed",error:g.message})}const d=await c;h?.removeEventListener("abort",E),d.status==="timeout"&&l.kill();const b=d.status==="killed"?"killed":r.interrupted?"interrupted":d.status;return{streamedAny:r.streamedAny,resultText:r.resultText,status:b,error:d.error}}}}async function ne({messages:u,system:y,options:t,images:v},p,{signal:w,launch:$=K}={}){if(!z(t))return{handled:!1,reason:"not eligible"};const C=H();if(!C)return{handled:!1,reason:"claude not resolvable"};const A=`${Date.now()}-${Math.random().toString(36).slice(2)}`,S=(t.mcp?.specs||[]).map(a=>a?.name).filter(Boolean),e=[];L(e,t.extraArgs,k.claude,()=>{});const m=JSON.stringify({agent:"claude",cwd:t.workingDir||"",mode:t.permissionMode||"default",model:t.model||"",local:t.useLocalConfig!==!1,system:String(y||""),reach:t.reach||"",tools:[...S].sort(),extra:e,env:t.runEnv?Object.keys(t.runEnv).sort().map(a=>`${a}=${t.runEnv[a]}`):[]});let o=f.acquire({key:m,messages:u}),x=!1;if(!o){if(o=f.reserve({key:m,label:`claude ${t.workingDir||"home"}`}),!o)return{handled:!1,reason:"all warm slots busy"};x=!0;let a=null,c=null;try{let r=t.mcp;r?.url&&S.length&&(a=R(p,r.specs),r={...r,url:`${r.url.replace(/\/[^/]*$/,"")}/${a.id}`}),c=await U({system:y,options:{...t,mcp:r},tag:A});const E=[...c.args];L(E,t.extraArgs,k.claude,p);const d=$({spec:C,args:E,cwd:c.cwd,env:c.runEnv});d.mcpSession=a,f.attach(o,d);const b=c.cleanup;d.onExit(()=>{a&&T(a.id),b()})}catch(r){return a&&T(a.id),c?.cleanup(),f.drop(o,`launch failed: ${r.message}`),{handled:!1,reason:r.message}}}const l=o.session;l.mcpSession&&W(l.mcpSession,p,t.mcp?.specs);const s=u[u.length-1],i=await G(v,A),h=B(x?u:[s],i);let n;try{n=await l.turn({prompt:h,emit:p,signal:w})}finally{i.forEach(a=>P(a).catch(()=>{})),l.mcpSession&&I(l.mcpSession)}if(w?.aborted||n.status==="interrupted")return n.status==="interrupted"&&l.alive?f.release(o,{user:String(s?.content||""),answered:n.streamedAny}):f.drop(o,"stopped"),{handled:!0};if(n.status!=="completed"){if(f.drop(o,n.error||n.status),!n.streamedAny)return{handled:!1,reason:n.error||n.status};throw new Error(n.error||`Claude Code ${n.status}`)}return p({type:"done",text:n.streamedAny?"":n.resultText}),f.release(o,{user:String(s?.content||""),answered:!0}),{handled:!0}}export{ne as chatWarm,K as launchClaudeSession,f as pool,z as warmEligible};
1
+ import{unlink as P}from"node:fs/promises";import{spawnRpcChild as N}from"../rpc-child.js";import{createWarmPool as O}from"../warm-pool.js";import{registerWarmPool as q}from"../warm.js";import{createSession as R,deleteSession as T,rebindSession as W,releaseSession as I}from"../mcp-sessions.js";import{resolveClaude as H,buildSpawnSpec as j}from"../env.js";import{loginRequired as _,signInMessage as M}from"../sign-in.js";import{pushExtraArgs as L,FORBIDDEN as k}from"./args.js";import{buildClaudeLaunch as U,claudePrompt as B,handleMessage as F,writeImages as G}from"./claude.js";const D=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,J=5e3,d=q("claude",O({log:c=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${c}`)}}));function z(c={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||c.warm===!1)}function K({spec:c,args:g,cwd:t,env:$,spawnImpl:f,log:S=()=>{}}){const b=[...g,"--input-format","stream-json"],[A,x,v]=j(c,b,t,$);let e=null;const y=new Set;let n="",w=0;const o=N(A,x,{spawnOpts:v,spawnImpl:f,jsonrpc:!1,onStderr:s=>{n=(n+s).slice(-2e3),e&&e.touch()},onExit:s=>{if(S(`claude exited: ${s.signal||s.code}${n?` — ${n.trim().split(`
2
+ `).pop()}`:""}`),e){const i=e.apiError&&_(e.apiError)?M("Claude Code","claude"):e.apiError?`Claude Code reported an error: ${e.apiError}`:`Claude Code exited (${s.signal||s.code})${n?`: ${n.trim().split(`
3
+ `).pop().slice(0,200)}`:""}`;e.finish({status:"died",error:i})}for(const i of y)try{i(s)}catch{}},onMessage:s=>{if(!e||(e.touch(),s.type==="control_response"))return;const i=F(s,e.emit,e.streamedAny,t,e.flow);i.streamed&&(e.streamedAny=!0),i.result!=null&&(e.resultText=i.result),i.apiError&&(e.apiError=i.apiError),s.type==="result"&&(e.apiError&&_(e.apiError)?e.finish({status:"failed",error:M("Claude Code","claude")}):e.apiError?e.finish({status:"failed",error:`Claude Code reported an error: ${e.apiError}`}):e.finish({status:"completed",error:null}))}});return{get pid(){return o.pid},get alive(){return!o.exited},onExit(s){y.add(s)},close(){o.close()},async turn({prompt:s,emit:i,signal:p}){if(o.exited)throw new Error("Claude Code process is gone");if(e)throw new Error("a turn is already running on this process");let C=null,a;const l=new Promise(h=>{a=h}),r={emit:i,flow:{sawText:!1,tail:"",boundary:!1},streamedAny:!1,resultText:"",apiError:null,touch(){clearTimeout(C),C=setTimeout(()=>r.finish({status:"timeout",error:`Claude Code timed out — no output for ${Math.round(D/1e3)}s.`}),D)},finish(h){e===r&&(clearTimeout(C),e=null,a(h))}};e=r,r.touch();const u=()=>{if(e===r){r.interrupted=!0;try{o.send({type:"control_request",request_id:`stop_${++w}`,request:{subtype:"interrupt"}})}catch{}setTimeout(()=>{e===r&&(r.finish({status:"killed",error:null}),o.kill())},J).unref?.()}};if(p?.aborted)return r.finish({status:"killed",error:null}),{streamedAny:!1,resultText:"",status:"killed"};p?.addEventListener("abort",u,{once:!0});try{o.send({type:"user",message:{role:"user",content:s}})}catch(h){r.finish({status:"failed",error:h.message})}const m=await l;p?.removeEventListener("abort",u),m.status==="timeout"&&o.kill();const E=m.status==="killed"?"killed":r.interrupted?"interrupted":m.status;return{streamedAny:r.streamedAny,resultText:r.resultText,status:E,error:m.error}}}}async function ne({messages:c,system:g,options:t,images:$},f,{signal:S,launch:b=K}={}){if(!z(t))return{handled:!1,reason:"not eligible"};const A=H();if(!A)return{handled:!1,reason:"claude not resolvable"};const x=`${Date.now()}-${Math.random().toString(36).slice(2)}`,v=(t.mcp?.specs||[]).map(l=>l?.name).filter(Boolean),e=[];L(e,t.extraArgs,k.claude,()=>{});const y=JSON.stringify({agent:"claude",cwd:t.workingDir||"",mode:t.permissionMode||"default",model:t.model||"",local:t.useLocalConfig!==!1,reach:t.reach||"",tools:[...v].sort(),extra:e,env:t.runEnv?Object.keys(t.runEnv).sort().map(l=>`${l}=${t.runEnv[l]}`):[]});let n=d.acquire({key:y,messages:c}),w=!1;if(!n){if(n=d.reserve({key:y,label:`claude ${t.workingDir||"home"}`}),!n)return{handled:!1,reason:"all warm slots busy"};w=!0;let l=null,r=null;try{let u=t.mcp;u?.url&&v.length&&(l=R(f,u.specs),u={...u,url:`${u.url.replace(/\/[^/]*$/,"")}/${l.id}`}),r=await U({system:g,options:{...t,mcp:u},tag:x});const m=[...r.args];L(m,t.extraArgs,k.claude,f);const E=b({spec:A,args:m,cwd:r.cwd,env:r.runEnv});E.mcpSession=l,E.systemSent=String(g||""),d.attach(n,E);const h=r.cleanup;E.onExit(()=>{l&&T(l.id),h()})}catch(u){return l&&T(l.id),r?.cleanup(),d.drop(n,`launch failed: ${u.message}`),{handled:!1,reason:u.message}}}const o=n.session;o.mcpSession&&W(o.mcpSession,f,t.mcp?.specs);const s=c[c.length-1],i=await G($,x),p=String(g||""),C=B(w?c:[s],i,!w&&p!==o.systemSent?p:"");o.systemSent=p;let a;try{a=await o.turn({prompt:C,emit:f,signal:S})}finally{i.forEach(l=>P(l).catch(()=>{})),o.mcpSession&&I(o.mcpSession)}if(S?.aborted||a.status==="interrupted")return a.status==="interrupted"&&o.alive?d.release(n,{user:String(s?.content||""),answered:a.streamedAny}):d.drop(n,"stopped"),{handled:!0};if(a.status!=="completed"){if(d.drop(n,a.error||a.status),!a.streamedAny)return{handled:!1,reason:a.error||a.status};throw new Error(a.error||`Claude Code ${a.status}`)}return f({type:"done",text:a.streamedAny?"":a.resultText}),d.release(n,{user:String(s?.content||""),answered:!0}),{handled:!0}}export{ne as chatWarm,K as launchClaudeSession,d as pool,z as warmEligible};
@@ -3,6 +3,6 @@ import{spawn as J}from"node:child_process";import{writeFile as L,unlink as N}fro
3
3
  `)),t.length>4e3?`${t.slice(0,4e3)}…`:t}function G(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
4
4
 
5
5
  `}),e.boundary=!1)}function q(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function Y(e,t,o,l="",s=null){const n={streamed:!1,result:null};if(e.type==="stream_event"){const r=e.event;r?.type==="content_block_delta"&&(r.delta?.type==="text_delta"?(n.streamed=!0,G(s,t),t({type:"delta",text:r.delta.text}),q(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 n.apiError=(e.message?.content||[]).filter(r=>r.type==="text").map(r=>r.text).join(`
6
- `)||String(e.error||"api error"),n;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:be(r,l)})):r.type==="text"&&!o&&(n.streamed=!0,G(s,t),t({type:"delta",text:r.text}),q(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:he(r.content)});else if(e.type==="result"){e.is_error?n.apiError=n.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?n.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 n}async function ye({system:e,options:t,tag:o}){const l=t.permissionMode||"default",s=j(t.workingDir),n=["--print","--output-format","stream-json","--include-partial-messages","--verbose"],r=[],a=[],i=me(t.mcp);if(i){const c=W.join(A.tmpdir(),`chatpanel-mcp-${o}.json`);await L(c,JSON.stringify(i.config)),r.push(c),n.push("--mcp-config",c),a.push(...i.allowedTools)}const m=fe(t.reach);if(m){const c=pe(t.reach,await ae("claude").catch(()=>[]));n.push("--allowedTools",...m.allow,...a,...c.allow),n.push("--disallowedTools",...m.deny,...c.deny)}else l==="bypassPermissions"?n.push("--permission-mode","bypassPermissions"):l==="acceptEdits"?(n.push("--permission-mode","acceptEdits"),a.length&&n.push("--allowedTools",...a)):n.push("--allowedTools",...H,...a);e&&n.push("--append-system-prompt",e),t.model&&n.push("--model",t.model),t.useLocalConfig===!1&&n.push("--setting-sources","");const y=i&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(ne(t.mcp?.specs))}:null,d=y||t.runEnv?{...t.runEnv||{},...y||{}}:null;return{args:n,cwd:s,runEnv:d,cleanup:()=>r.forEach(c=>N(c).catch(()=>{})),hasMcp:!!i}}function _e(e,t=[]){let o=R(e);return t.length&&(o+=`
6
+ `)||String(e.error||"api error"),n;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:be(r,l)})):r.type==="text"&&!o&&(n.streamed=!0,G(s,t),t({type:"delta",text:r.text}),q(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:he(r.content)});else if(e.type==="result"){e.is_error?n.apiError=n.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?n.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 n}async function ye({system:e,options:t,tag:o}){const l=t.permissionMode||"default",s=j(t.workingDir),n=["--print","--output-format","stream-json","--include-partial-messages","--verbose"],r=[],a=[],i=me(t.mcp);if(i){const c=W.join(A.tmpdir(),`chatpanel-mcp-${o}.json`);await L(c,JSON.stringify(i.config)),r.push(c),n.push("--mcp-config",c),a.push(...i.allowedTools)}const m=fe(t.reach);if(m){const c=pe(t.reach,await ae("claude").catch(()=>[]));n.push("--allowedTools",...m.allow,...a,...c.allow),n.push("--disallowedTools",...m.deny,...c.deny)}else l==="bypassPermissions"?n.push("--permission-mode","bypassPermissions"):l==="acceptEdits"?(n.push("--permission-mode","acceptEdits"),a.length&&n.push("--allowedTools",...a)):n.push("--allowedTools",...H,...a);e&&n.push("--append-system-prompt",e),t.model&&n.push("--model",t.model),t.useLocalConfig===!1&&n.push("--setting-sources","");const y=i&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(ne(t.mcp?.specs))}:null,d=y||t.runEnv?{...t.runEnv||{},...y||{}}:null;return{args:n,cwd:s,runEnv:d,cleanup:()=>r.forEach(c=>N(c).catch(()=>{})),hasMcp:!!i}}function _e(e,t=[],o=""){let l=R(e,o);return t.length&&(l+=`
7
7
 
8
- The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),o}async function je({messages:e,system:t,options:o,images:l},s,{signal:n}={}){const r=await le({messages:e,system:t,options:o,images:l},s,{signal:n}).catch(a=>({handled:!1,reason:a?.message||String(a),thrown:!0}));if(!r.handled&&!n?.aborted){if(r.thrown)throw new Error(r.reason);return we({messages:e,system:t,options:o,images:l},s,{signal:n})}}async function we({messages:e,system:t,options:o,images:l},s,{signal:n}={}){const r=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=await ye({system:t,options:o,tag:r}),{args:i,cwd:m,runEnv:y}=a,d=await ie(l,r),u=()=>{d.forEach(_=>N(_).catch(()=>{})),a.cleanup()},c=_e(e,d);re(i,o.extraArgs,oe.claude,s);const h=F({prompt:c,args:i,cwd:m,env:y,emit:s,signal:n});if(h===null)return u(),Te({messages:e,system:t,options:o},s,{signal:n});try{const{streamedAny:_,resultText:w}=await h;s({type:"done",text:_?"":w})}finally{u()}}async function De({prompt:e,system:t,model:o}){const l=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",o||"haiku","--system-prompt",t||"Continue the user's text briefly. Reply with only the continuation."];let s="";const n=F({prompt:e,args:l,cwd:null,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(n===null)return ge({prompt:e,system:t,model:o});const{resultText:r}=await n;return(s||r||"").trim()}function be(e,t=""){const o=e.input||{};return o.command?String(o.command).slice(0,60):o.file_path?se(o.file_path,t):o.pattern?o.pattern:o.url?o.url:o.description?String(o.description).slice(0,80):o.query?String(o.query).slice(0,80):o.prompt?String(o.prompt).slice(0,80):""}let M=null;function O(){return M||(M=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),M}async function Te({messages:e,system:t,options:o},l,{signal:s}={}){const n=await O();if(!n)throw new Error(C);const{query:r}=n,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const i=o.permissionMode||"default",m=j(o.workingDir),y=i==="acceptEdits"||i==="bypassPermissions",d=new Set(H),u=async p=>d.has(p)||y?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${p} blocked — set this agent's permission mode in ChatPanel to enable it.`};let c=!1;const h={sawText:!1,tail:"",boundary:!1};let _="";const w=r({prompt:R(e),options:{cwd:m,permissionMode:i,includePartialMessages:!0,canUseTool:u,abortController:a,settingSources:o.useLocalConfig===!1?[]:["user","project"],systemPrompt:t?{type:"preset",preset:"claude_code",append:t}:{type:"preset",preset:"claude_code"},...o.model?{model:o.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const p of w){const T=Y(p,l,c,m,h);T.streamed&&(c=!0),T.result!=null&&(_=T.result)}}catch(p){if(s?.aborted||a.signal.aborted)return;throw p}l({type:"done",text:c?"":_})}async function ge({prompt:e,system:t,model:o}){const l=await O();if(!l)throw new Error(C);const{query:s}=l;let n="";const r=s({prompt:e,options:{cwd:A.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:t||"Continue the user's text briefly. Reply with only the continuation.",model:o||"haiku"}});for await(const a of r)if(a.type==="assistant")for(const i of a.message.content)i.type==="text"&&(n+=i.text);else a.type==="result"&&a.subtype==="success"&&!n&&(n=a.result||"");return n.trim()}export{Ie as available,ye as buildClaudeLaunch,pe as channelMcpTools,fe as channelToolPolicy,je as chat,we as chatCold,me as claudeMcpConfig,_e as claudePrompt,De as complete,Y as handleMessage,Re as listModels,ie as writeImages};
8
+ The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),l}async function je({messages:e,system:t,options:o,images:l},s,{signal:n}={}){const r=await le({messages:e,system:t,options:o,images:l},s,{signal:n}).catch(a=>({handled:!1,reason:a?.message||String(a),thrown:!0}));if(!r.handled&&!n?.aborted){if(r.thrown)throw new Error(r.reason);return we({messages:e,system:t,options:o,images:l},s,{signal:n})}}async function we({messages:e,system:t,options:o,images:l},s,{signal:n}={}){const r=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=await ye({system:t,options:o,tag:r}),{args:i,cwd:m,runEnv:y}=a,d=await ie(l,r),u=()=>{d.forEach(_=>N(_).catch(()=>{})),a.cleanup()},c=_e(e,d);re(i,o.extraArgs,oe.claude,s);const h=F({prompt:c,args:i,cwd:m,env:y,emit:s,signal:n});if(h===null)return u(),Te({messages:e,system:t,options:o},s,{signal:n});try{const{streamedAny:_,resultText:w}=await h;s({type:"done",text:_?"":w})}finally{u()}}async function De({prompt:e,system:t,model:o}){const l=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",o||"haiku","--system-prompt",t||"Continue the user's text briefly. Reply with only the continuation."];let s="";const n=F({prompt:e,args:l,cwd:null,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(n===null)return ge({prompt:e,system:t,model:o});const{resultText:r}=await n;return(s||r||"").trim()}function be(e,t=""){const o=e.input||{};return o.command?String(o.command).slice(0,60):o.file_path?se(o.file_path,t):o.pattern?o.pattern:o.url?o.url:o.description?String(o.description).slice(0,80):o.query?String(o.query).slice(0,80):o.prompt?String(o.prompt).slice(0,80):""}let M=null;function O(){return M||(M=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),M}async function Te({messages:e,system:t,options:o},l,{signal:s}={}){const n=await O();if(!n)throw new Error(C);const{query:r}=n,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const i=o.permissionMode||"default",m=j(o.workingDir),y=i==="acceptEdits"||i==="bypassPermissions",d=new Set(H),u=async p=>d.has(p)||y?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${p} blocked — set this agent's permission mode in ChatPanel to enable it.`};let c=!1;const h={sawText:!1,tail:"",boundary:!1};let _="";const w=r({prompt:R(e),options:{cwd:m,permissionMode:i,includePartialMessages:!0,canUseTool:u,abortController:a,settingSources:o.useLocalConfig===!1?[]:["user","project"],systemPrompt:t?{type:"preset",preset:"claude_code",append:t}:{type:"preset",preset:"claude_code"},...o.model?{model:o.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const p of w){const T=Y(p,l,c,m,h);T.streamed&&(c=!0),T.result!=null&&(_=T.result)}}catch(p){if(s?.aborted||a.signal.aborted)return;throw p}l({type:"done",text:c?"":_})}async function ge({prompt:e,system:t,model:o}){const l=await O();if(!l)throw new Error(C);const{query:s}=l;let n="";const r=s({prompt:e,options:{cwd:A.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:t||"Continue the user's text briefly. Reply with only the continuation.",model:o||"haiku"}});for await(const a of r)if(a.type==="assistant")for(const i of a.message.content)i.type==="text"&&(n+=i.text);else a.type==="result"&&a.subtype==="success"&&!n&&(n=a.result||"");return n.trim()}export{Ie as available,ye as buildClaudeLaunch,pe as channelMcpTools,fe as channelToolPolicy,je as chat,we as chatCold,me as claudeMcpConfig,_e as claudePrompt,De as complete,Y as handleMessage,Re as listModels,ie as writeImages};
package/src/server.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as ce}from"node:http";import x from"node:os";import{randomBytes as le,timingSafeEqual as de}from"node:crypto";import{mkdirSync as ue,writeFileSync as he,readFileSync as pe,existsSync as me}from"node:fs";import{join as $}from"node:path";import*as fe from"./engines/claude.js";import*as ge from"./engines/codex.js";import*as ye from"./engines/antigravity.js";import{pi as we,opencode as be,kiro as Se,copilot as ke,deepseek as Te,hermes as ve}from"./engines/cli-agents.js";import{connectorsFor as Ce}from"./connectors.js";import*as Ee from"./engines/custom.js";import{installService as Oe,uninstallService as Ae,serviceStatus as xe,restartService as j}from"./service.js";import{skillIndex as B,listRecords as Pe,readRecord as $e,readPackageFile as Ie,skillsHealth as Ne,quarantinedSkills as Re}from"./skills.js";import{capabilityToolSpecs as He,runCapabilityTool as _e}from"./mcp-capabilities.js";import{createSession as Me,deleteSession as J,getSession as F,activeSession as Be,relayToolCall as Ge}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ue,isDefaultWorkdir as De,resolveWorkdir as Le,writeScopeNote as We}from"./workdir.js";import{gitState as je,gitDelta as Je}from"./scm.js";import{listConnections as Fe,putConnection as Ke,removeConnection as ze,runEnvFor as Ve,testConnection as Ye,secretBackend as K}from"./connections.js";import{worktreeFor as z,listWorktrees as Xe,removeWorktree as Qe,withHook as Ze,WORKTREE_ROOT as V}from"./worktree.js";import{AGENT_CLIS as qe,enrichPath as et,enrichAgentEnv as tt,findAgentBin as Y,resolveCommand as nt}from"./env.js";import"./sanitize.js";import{checkForUpdate as rt,selfUpdate as X,isEmbedded as ot}from"./update.js";import{callLocalMcp as at}from"./mcp-local.js";import{assertPublicHttpUrl as Q,assertPublicWebUrl as Z}from"./ssrf.js";import{startRun as q,endRun as G,cancelRun as it,cancelAll as st}from"./runs.js";import{closeWarmPools as ct,warmStatus as lt}from"./warm.js";import{CompatError as I,anthropicError as U,anthropicStream as dt,chatCompletionStream as ut,completionStream as ht,createAnthropicMessage as pt,createChatCompletion as mt,createCompletion as ft,createResponse as gt,openAIError as w,parseAnthropicMessage as yt,parseChatCompletion as wt,parseCompletion as bt,parseResponse as St,responseStream as kt}from"./api-compat.js";const g="0.12.0",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",O=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,T={claude:{engine:fe,label:"Claude Code"},codex:{engine:ge,label:"Codex"},antigravity:{engine:ye,label:"Antigravity"},pi:{engine:we,label:"Pi"},opencode:{engine:be,label:"OpenCode"},hermes:{engine:ve,label:"Hermes"},kiro:{engine:Se,label:"Kiro"},copilot:{engine:ke,label:"GitHub Copilot"},deepseek:{engine:Te,label:"DeepSeek Harness"},custom:{engine:Ee,label:"Custom",hidden:!0}};function ee(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Tt(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function vt(n,e){const t=n.headers.origin||"",o=ee(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 D=new Set(["127.0.0.1","localhost","::1"]);function Ct(n){if(!D.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return D.has(t)}const L=$(x.homedir(),".chatpanel","bridge-token");let v="";function Et(){try{me(L)&&(v=pe(L,"utf8").trim()),v||(v=le(32).toString("hex"),ue($(x.homedir(),".chatpanel"),{recursive:!0}),he(L,v,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}let N=null;async function te(){if(N)return N;const{createChannelService:n}=await import("./channels/service.js");return N=n({home:$(x.homedir(),".chatpanel"),dataDir:$(x.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${O}`,token:v},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),N}async function ne(n,e,t){try{const o=await te(),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 Ot(n){if(!v)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(v);return o.length===r.length&&de(o,r)}const At=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees"]),xt=new Set(["/debug"]),Pt=n=>xt.has(n);function $t(n,e){if(!Ct(n))return"forbidden host";const t=n.headers.origin||"";return t&&!ee(t)?"forbidden origin":(n.method==="POST"&&At.has(e)||n.method==="GET"&&Pt(e))&&!(Tt(t)||Ot(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":null}function a(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let 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 It(n){const e=await Promise.all(Object.entries(T).filter(([,r])=>!r.hidden).map(async([r,{engine:i,label:l}])=>{const d=await i.available().catch(s=>({ok:!1,reason:String(s?.message||s)})),c=await Ce(r).catch(()=>[]);return{id:r,label:l,available:d.ok,reason:d.reason,connectors:c}})),t=ot()?{current:g,updateAvailable:!1,embedded:"gateway"}:await rt(g).catch(()=>({current:g,updateAvailable:!1})),o=await Ne().catch(()=>null);a(n,200,{ok:!0,version:g,agents:e,update:t,workspace:Ue,worktrees:V,secretBackend:K(),warm:lt(),...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...o?{skills:o}:{}})}async function Nt(n,e){const{index:t,problems:o}=await B({extraDirs:e});a(n,200,{ok:!0,skills:Pe(t),problems:o})}async function Rt(n,e){a(n,200,{ok:!0,quarantined:await Re(e)})}async function Ht(n,e,t){const{index:o}=await B({extraDirs:t}),r=$e(o,e);if(!r)return a(n,404,{ok:!1,error:"unknown skill"});a(n,200,{ok:!0,skill:r})}async function _t(n,e,t,o){const{index:r}=await B({extraDirs:o}),i=await Ie(r,e,t);if(i.error)return a(n,i.error==="unknown skill"?404:400,{ok:!1,error:i.error});a(n,200,{ok:!0,...i})}async function Mt(){return(await Promise.all(Object.entries(T).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function re(n,e=""){const t=await Mt();if(e){const o=t.find(r=>r.id===e);return o?a(n,200,o):a(n,404,w(new I(`Model "${e}" not found`,404,"model")))}return a(n,200,{object:"list",data:t})}async function Bt(n){try{const e=await X(g);a(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>j(),400))}catch(e){a(n,400,{ok:!1,error:String(e?.message||e)})}}async function Gt(n,e){let t;try{t=await f(n)}catch(p){return a(e,400,{error:"Bad JSON: "+p.message})}const o=T[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const r=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
2
+ import{createServer as ce}from"node:http";import x from"node:os";import{randomBytes as le,timingSafeEqual as de}from"node:crypto";import{mkdirSync as ue,writeFileSync as he,readFileSync as pe,existsSync as me}from"node:fs";import{join as $}from"node:path";import*as fe from"./engines/claude.js";import*as ge from"./engines/codex.js";import*as ye from"./engines/antigravity.js";import{pi as we,opencode as be,kiro as Se,copilot as ke,deepseek as Te,hermes as ve}from"./engines/cli-agents.js";import{connectorsFor as Ce}from"./connectors.js";import*as Ee from"./engines/custom.js";import{installService as Oe,uninstallService as Ae,serviceStatus as xe,restartService as j}from"./service.js";import{skillIndex as B,listRecords as Pe,readRecord as $e,readPackageFile as Ie,skillsHealth as Ne,quarantinedSkills as Re}from"./skills.js";import{capabilityToolSpecs as He,runCapabilityTool as _e}from"./mcp-capabilities.js";import{createSession as Me,deleteSession as J,getSession as F,activeSession as Be,relayToolCall as Ge}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ue,isDefaultWorkdir as De,resolveWorkdir as Le,writeScopeNote as We}from"./workdir.js";import{gitState as je,gitDelta as Je}from"./scm.js";import{listConnections as Fe,putConnection as Ke,removeConnection as ze,runEnvFor as Ve,testConnection as Ye,secretBackend as K}from"./connections.js";import{worktreeFor as z,listWorktrees as Xe,removeWorktree as Qe,withHook as Ze,WORKTREE_ROOT as V}from"./worktree.js";import{AGENT_CLIS as qe,enrichPath as et,enrichAgentEnv as tt,findAgentBin as Y,resolveCommand as nt}from"./env.js";import"./sanitize.js";import{checkForUpdate as ot,selfUpdate as X,isEmbedded as rt}from"./update.js";import{callLocalMcp as at}from"./mcp-local.js";import{assertPublicHttpUrl as Q,assertPublicWebUrl as Z}from"./ssrf.js";import{startRun as q,endRun as G,cancelRun as it,cancelAll as st}from"./runs.js";import{closeWarmPools as ct,warmStatus as lt}from"./warm.js";import{CompatError as I,anthropicError as U,anthropicStream as dt,chatCompletionStream as ut,completionStream as ht,createAnthropicMessage as pt,createChatCompletion as mt,createCompletion as ft,createResponse as gt,openAIError as w,parseAnthropicMessage as yt,parseChatCompletion as wt,parseCompletion as bt,parseResponse as St,responseStream as kt}from"./api-compat.js";const g="0.12.2",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",O=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,T={claude:{engine:fe,label:"Claude Code"},codex:{engine:ge,label:"Codex"},antigravity:{engine:ye,label:"Antigravity",tools:!1},pi:{engine:we,label:"Pi"},opencode:{engine:be,label:"OpenCode"},hermes:{engine:ve,label:"Hermes"},kiro:{engine:Se,label:"Kiro"},copilot:{engine:ke,label:"GitHub Copilot"},deepseek:{engine:Te,label:"DeepSeek Harness"},custom:{engine:Ee,label:"Custom",hidden:!0}};function ee(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Tt(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function vt(n,e){const t=n.headers.origin||"",r=ee(t);e.setHeader("Access-Control-Allow-Origin",r?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const D=new Set(["127.0.0.1","localhost","::1"]);function Ct(n){if(!D.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return D.has(t)}const L=$(x.homedir(),".chatpanel","bridge-token");let v="";function Et(){try{me(L)&&(v=pe(L,"utf8").trim()),v||(v=le(32).toString("hex"),ue($(x.homedir(),".chatpanel"),{recursive:!0}),he(L,v,{mode:384}))}catch(n){h("error",`could not initialise bridge token: ${n?.message||n}`)}}let N=null;async function te(){if(N)return N;const{createChannelService:n}=await import("./channels/service.js");return N=n({home:$(x.homedir(),".chatpanel"),dataDir:$(x.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${O}`,token:v},logger:{log:e=>h("info",e),warn:e=>h("info",e),error:e=>h("error",e)}}),N}async function ne(n,e,t){try{const r=await te(),o=n.method==="POST"?await f(n):{};if(t==="status")return a(e,200,await r.status());if(t==="connect"){const i=await r.connect(o);return a(e,200,{ok:!0,...i})}return t==="pair"?a(e,200,await r.pair()):t==="unpair"?a(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?a(e,200,await r.update(o)):t==="disconnect"?a(e,200,await r.stop({forget:!!o.forget})):a(e,404,{error:"unknown channel action"})}catch(r){return a(e,400,{error:r?.message||String(r)})}}function Ot(n){if(!v)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const r=Buffer.from(t),o=Buffer.from(v);return r.length===o.length&&de(r,o)}const At=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees"]),xt=new Set(["/debug"]),Pt=n=>xt.has(n);function $t(n,e){if(!Ct(n))return"forbidden host";const t=n.headers.origin||"";return t&&!ee(t)?"forbidden origin":(n.method==="POST"&&At.has(e)||n.method==="GET"&&Pt(e))&&!(Tt(t)||Ot(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":null}function a(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let r="";n.on("data",o=>{r+=o,r.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){t(o)}}),n.on("error",t)})}async function It(n){const e=await Promise.all(Object.entries(T).filter(([,o])=>!o.hidden).map(async([o,{engine:i,label:l,tools:d}])=>{const s=await i.available().catch(u=>({ok:!1,reason:String(u?.message||u)})),c=await Ce(o).catch(()=>[]);return{id:o,label:l,available:s.ok,reason:s.reason,connectors:c,...d===!1?{tools:!1}:{}}})),t=rt()?{current:g,updateAvailable:!1,embedded:"gateway"}:await ot(g).catch(()=>({current:g,updateAvailable:!1})),r=await Ne().catch(()=>null);a(n,200,{ok:!0,version:g,agents:e,update:t,workspace:Ue,worktrees:V,secretBackend:K(),warm:lt(),...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function Nt(n,e){const{index:t,problems:r}=await B({extraDirs:e});a(n,200,{ok:!0,skills:Pe(t),problems:r})}async function Rt(n,e){a(n,200,{ok:!0,quarantined:await Re(e)})}async function Ht(n,e,t){const{index:r}=await B({extraDirs:t}),o=$e(r,e);if(!o)return a(n,404,{ok:!1,error:"unknown skill"});a(n,200,{ok:!0,skill:o})}async function _t(n,e,t,r){const{index:o}=await B({extraDirs:r}),i=await Ie(o,e,t);if(i.error)return a(n,i.error==="unknown skill"?404:400,{ok:!1,error:i.error});a(n,200,{ok:!0,...i})}async function Mt(){return(await Promise.all(Object.entries(T).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function oe(n,e=""){const t=await Mt();if(e){const r=t.find(o=>o.id===e);return r?a(n,200,r):a(n,404,w(new I(`Model "${e}" not found`,404,"model")))}return a(n,200,{object:"list",data:t})}async function Bt(n){try{const e=await X(g);a(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>j(),400))}catch(e){a(n,400,{ok:!1,error:String(e?.message||e)})}}async function Gt(n,e){let t;try{t=await f(n)}catch(p){return a(e,400,{error:"Bad JSON: "+p.message})}const r=T[t.agent];if(!r)return a(e,404,{error:`Unknown agent "${t.agent}"`});Array.isArray(t.images)&&t.images.length&&h("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const o=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
3
3
 
4
- `)};let i=!1;const l=`run_${Math.random().toString(36).slice(2,10)}`,d=q(l),c={signal:d.signal,abort:()=>d.cancel("client")},s=()=>{i=!0,d.cancel("disconnected")};n.on("close",s),e.on("close",s),e.on("error",s);const h=p=>{i||r(p)};r({type:"run",id:l});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){r({type:"error",error:`workspace: ${m.error}`}),G(l),e.writableEnded||e.end();return}}const b=m?m.path:Le(t.options?.workingDir);let C=null;{const p=b,E=!!m||!De(t.options?.workingDir),y=We(t.agent,t.options?.permissionMode,p);r({type:"workdir",path:p,isDefault:!E,writeScope:y||void 0}),r({type:"status",text:`Working in ${p}${E?"":" (default)"}`}),y&&r({type:"status",text:y}),C=await je(p),C&&r({type:"scm",phase:"before",...C})}let M=null;if(C||m){const p=Array.isArray(t.options?.grants)?t.options.grants:[],{env:E,connection:y}=Ve({remote:C?.remote||null,grants:p,branch:m?.branch||null,connectionId:t.options?.connectionId||null});M=Ze(E),m&&r({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&r({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${E.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:E.CHATPANEL_SCM_PUSH}`})}const W={...t.options||{},...m?{workingDir:m.path}:{},...M?{runEnv:M}:{}};let P=null;t.pageTools?.specs?.length&&(P=Me(h,t.pageTools.specs),W.mcp={url:`http://${k}:${O}/mcp/${P.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs});try{await o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:W,images:Array.isArray(t.images)?t.images:[]},h,{signal:c.signal})}catch(p){u("error",`${t.agent} chat failed: ${p?.message||p}`),r({type:"error",error:p?.message||String(p)})}finally{if(!i){const p=await Je(b,C).catch(()=>null);p&&h({type:"scm",phase:"after",...p})}G(l),P&&J(P.id),e.writableEnded||e.end()}}async function Ut(n,e,t){if(n.method==="GET"&&t==="/connections")return a(e,200,{ok:!0,connections:Fe(),secretBackend:K()});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:Ke(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:ze(r[1])}):a(e,200,Ye(r[1],o.remote||"")):a(e,404,{error:"Not found"})}async function Dt(n,e,t){if(n.method==="GET"&&t==="/worktrees")return a(e,200,{ok:!0,root:V,worktrees:await Xe()});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 Qe({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 S(n,e,t){const o=T[n.agent];if(!o||o.hidden)throw new I(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const r=await o.engine.available().catch(s=>({ok:!1,reason:s?.message||String(s)}));if(!r.ok)throw new I(r.reason||`${n.agent} is unavailable`,503,"model");const i=`run_${Math.random().toString(36).slice(2,10)}`,l=q(i),d=()=>l.cancel("disconnected");t.on("close",d);let c="";try{return await o.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},s=>{s?.type==="delta"&&s.text?(c+=s.text,e(s.text)):s?.type==="done"&&s.text&&!c&&(c=s.text,e(s.text))},{signal:l.signal}),c}finally{t.off("close",d),G(i)}}function R(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function A(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
4
+ `)};let i=!1;const l=`run_${Math.random().toString(36).slice(2,10)}`,d=q(l),s={signal:d.signal,abort:()=>d.cancel("client")},c=()=>{i=!0,d.cancel("disconnected")};n.on("close",c),e.on("close",c),e.on("error",c);const u=p=>{i||o(p)};o({type:"run",id:l});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){o({type:"error",error:`workspace: ${m.error}`}),G(l),e.writableEnded||e.end();return}}const b=m?m.path:Le(t.options?.workingDir);let C=null;{const p=b,E=!!m||!De(t.options?.workingDir),y=We(t.agent,t.options?.permissionMode,p);o({type:"workdir",path:p,isDefault:!E,writeScope:y||void 0}),o({type:"status",text:`Working in ${p}${E?"":" (default)"}`}),y&&o({type:"status",text:y}),C=await je(p),C&&o({type:"scm",phase:"before",...C})}let M=null;if(C||m){const p=Array.isArray(t.options?.grants)?t.options.grants:[],{env:E,connection:y}=Ve({remote:C?.remote||null,grants:p,branch:m?.branch||null,connectionId:t.options?.connectionId||null});M=Ze(E),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: ${E.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:E.CHATPANEL_SCM_PUSH}`})}const W={...t.options||{},...m?{workingDir:m.path}:{},...M?{runEnv:M}:{}};let P=null;t.pageTools?.specs?.length&&(P=Me(u,t.pageTools.specs),W.mcp={url:`http://${k}:${O}/mcp/${P.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs});try{await r.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:W,images:Array.isArray(t.images)?t.images:[]},u,{signal:s.signal})}catch(p){h("error",`${t.agent} chat failed: ${p?.message||p}`),o({type:"error",error:p?.message||String(p)})}finally{if(!i){const p=await Je(b,C).catch(()=>null);p&&u({type:"scm",phase:"after",...p})}G(l),P&&J(P.id),e.writableEnded||e.end()}}async function Ut(n,e,t){if(n.method==="GET"&&t==="/connections")return a(e,200,{ok:!0,connections:Fe(),secretBackend:K()});if(n.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/connections")try{return a(e,200,{ok:!0,connection:Ke(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(t);return o?o[2]==="delete"?a(e,200,{ok:ze(o[1])}):a(e,200,Ye(o[1],r.remote||"")):a(e,404,{error:"Not found"})}async function Dt(n,e,t){if(n.method==="GET"&&t==="/worktrees")return a(e,200,{ok:!0,root:V,worktrees:await Xe()});if(n.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/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(t==="/worktrees/remove"){const o=await Qe({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(n,e,t){const r=T[n.agent];if(!r||r.hidden)throw new I(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const o=await r.engine.available().catch(c=>({ok:!1,reason:c?.message||String(c)}));if(!o.ok)throw new I(o.reason||`${n.agent} is unavailable`,503,"model");const i=`run_${Math.random().toString(36).slice(2,10)}`,l=q(i),d=()=>l.cancel("disconnected");t.on("close",d);let s="";try{return await r.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},c=>{c?.type==="delta"&&c.text?(s+=c.text,e(c.text)):c?.type==="done"&&c.text&&!s&&(s=c.text,e(c.text))},{signal:l.signal}),s}finally{t.off("close",d),G(i)}}function R(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function A(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
5
5
 
6
6
  `)}function H(n,e,t){n.writableEnded||n.write(`event: ${e}
7
7
  data: ${JSON.stringify(t)}
8
8
 
9
- `)}async function _(n,e,t,o){try{return t(await f(n))}catch(r){return a(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new I(`Bad JSON: ${r.message}`):r)),null}}async function Lt(n,e){const t=await _(n,e,wt,w);if(!t)return;if(!t.stream)try{const r=await S(t,()=>{},e);return a(e,200,mt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,w(r))}R(e);const o=ut(t.requestedModel,r=>A(e,r));try{await S(t,r=>o.delta(r),e),o.done()}catch(r){A(e,w(r))}A(e,"[DONE]"),e.end()}async function Wt(n,e){const t=await _(n,e,bt,w);if(!t)return;if(!t.stream)try{const r=await S(t,()=>{},e);return a(e,200,ft(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,w(r))}R(e);const o=ht(t.requestedModel,r=>A(e,r));try{await S(t,r=>o.delta(r),e),o.done()}catch(r){A(e,w(r))}A(e,"[DONE]"),e.end()}async function jt(n,e){const t=await _(n,e,St,w);if(!t)return;if(!t.stream)try{const r=await S(t,()=>{},e);return a(e,200,gt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,w(r))}R(e);const o=kt(t.requestedModel,r=>H(e,r.type,r));try{await S(t,r=>o.delta(r),e),o.done()}catch(r){const i={type:"error",sequence_number:0,...w(r)};H(e,"error",i)}e.end()}async function Jt(n,e){const t=await _(n,e,yt,U);if(!t)return;if(!t.stream)try{const r=await S(t,()=>{},e);return a(e,200,pt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,U(r))}R(e);const o=dt(t.requestedModel,(r,i)=>H(e,r,i));try{await S(t,r=>o.delta(r),e),o.done()}catch(r){H(e,"error",U(r))}e.end()}async function Ft(n,e){let t={};try{t=await f(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?it(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),a(e,200,{ok:!0,cancelled:r})}async function oe(n,e,t){let o;try{o=await f(n)}catch{return a(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=t?F(t):Be(),i=c=>{r&&e.setHeader("Mcp-Session-Id",r.id),a(e,200,{jsonrpc:"2.0",id:o.id??null,result:c})},l=(c,s)=>a(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:c,message:s}});if(o.id==null)return e.writeHead(202),e.end();if(o.method==="initialize")return i({protocolVersion:o.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const d=He();if(o.method==="tools/list"){const c=r?r.specs.map(s=>({name:s.name,description:s.description,inputSchema:s.parameters||{type:"object",properties:{}}})):[];return i({tools:[...d,...c]})}if(o.method==="tools/call"){const c=await _e(o.params?.name,o.params?.arguments||{});if(c)return i(c);if(!r)return l(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return i(await Ge(r,o.params?.name,o.params?.arguments||{}))}catch(s){return i({content:[{type:"text",text:`error: ${s?.message||s}`}],isError:!0})}}return l(-32601,`Method not found: ${o.method}`)}async function Kt(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const o=t.server||{},r=t.message;if(!o.command||!r)return a(e,400,{error:"need server.command and message"});try{const i=await at({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd},r);return r.id==null?(e.writeHead(202),e.end()):a(e,200,i)}catch(i){return a(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:-32e3,message:String(i?.message||i)}})}}async function zt(n,e){let t;try{t=await f(n)}catch(h){return a(e,400,{error:"Bad JSON: "+h.message})}const{url:o,headers:r,message:i}=t||{};if(!o||!i)return a(e,400,{error:"need url and message"});let l;try{l=Q(o)}catch(h){return a(e,400,{error:String(h?.message||h)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[h,m]of Object.entries(r)){const b=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(b)||b.startsWith("x-"))&&(d[h]=String(m))}const c=new AbortController,s=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(l.href,{method:"POST",headers:d,body:JSON.stringify(i),redirect:"follow",signal:c.signal});try{h.url&&Q(h.url)}catch(b){return a(e,400,{error:String(b?.message||b)})}const m=await h.text().catch(()=>"");return a(e,200,{status:h.status,sessionId:h.headers.get("Mcp-Session-Id")||null,contentType:h.headers.get("Content-Type")||"",body:m})}catch(h){const m=h?.name==="AbortError"?"timed out":String(h?.message||h);return a(e,502,{error:`couldn't reach MCP server ${l.host}: ${m}`})}finally{clearTimeout(s)}}const ae=256*1024,Vt=5,Yt=8e3;async function Xt(n){let e=Z(n);const t=new AbortController,o=setTimeout(()=>t.abort(),Yt);try{for(let r=0;r<=Vt;r++){const i=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${g} (+link-title)`}});if(i.status>=300&&i.status<400&&i.headers.get("location")){if(e=Z(new URL(i.headers.get("location"),e).href),i.body)try{await i.body.cancel()}catch{}continue}if(!i.ok){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}const l=i.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(l)){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}return{title:qt(await Qt(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function Qt(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,ae);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:i,value:l}=await e.read();if(i||(r+=l.byteLength,o+=t.decode(l,{stream:!0}),/<\/title\s*>/i.test(o)||r>=ae))break}}finally{try{await e.cancel()}catch{}}return o}function Zt(n){return String(n).replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function qt(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Zt(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function en(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=t&&t.url;if(!o||typeof o!="string")return a(e,400,{error:"need url"});try{const r=await Xt(o);return a(e,200,{title:r.title||null,url:r.url||o})}catch(r){const i=r?.name==="AbortError"?"timed out":String(r?.message||r);return a(e,400,{error:`couldn't fetch title: ${i}`})}}async function tn(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const o=F(t.session);if(!o)return a(e,404,{error:"no such session"});const r=o.pending.get(t.id);return r?(o.pending.delete(t.id),r.resolve(t.result),a(e,200,{ok:!0})):a(e,404,{error:"no such pending call"})}async function nn(n,e){let t;try{t=await f(n)}catch(d){return a(e,400,{error:"Bad JSON: "+d.message})}const o=T[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});const r=String(t.prompt||"").slice(0,6e3);if(!r)return a(e,400,{error:"Empty prompt"});const i=t.model||"",l=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let d="";return typeof o.engine.complete=="function"?d=await o.engine.complete({prompt:r,system:l,model:i}):await o.engine.chat({messages:[{role:"user",content:r}],system:l,options:{model:i}},c=>{c.type==="delta"?d+=c.text||"":c.type==="done"&&c.text&&(d+=c.text)}),a(e,200,{text:(d||"").trim()})}catch(d){return a(e,502,{error:d?.message||String(d)})}}async function rn(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=T[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof o.engine.listModels!="function")return a(e,200,{models:[]});try{const r=await o.engine.listModels(t.options||{});return a(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return a(e,502,{error:r?.message||String(r)})}}async function on(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const o=String(t.command||"").trim();if(!o)return a(e,400,{error:"No command"});let r=null;try{r=nt(o)}catch{r=null}return a(e,200,{ok:!!r,via:r?r.kind:null})}const ie=ce(async(n,e)=>{if(vt(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return a(e,400,{error:"bad request"})}const o=$t(n,t.pathname);if(o)return a(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return It(e);const r=t.searchParams.getAll("dir");if(n.method==="GET"&&t.pathname==="/skills")return Nt(e,r);if(n.method==="GET"&&t.pathname==="/skills-quarantined")return Rt(e,r);if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const i=t.pathname.slice(8),l=i.indexOf("/file/");return l===-1?Ht(e,decodeURIComponent(i),r):_t(e,decodeURIComponent(i.slice(0,l)),decodeURIComponent(i.slice(l+6)),r)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return Ut(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Dt(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return re(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return re(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const i=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return a(e,200,{version:g,agents:Object.fromEntries(qe.map(l=>[l,i?Y(l)||null:!!Y(l)])),...i?{home:x.homedir(),path:process.env.PATH}:{}})}if(n.method==="POST"&&t.pathname==="/chat")return Gt(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return Lt(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Wt(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return jt(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return Jt(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return oe(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const i=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return oe(n,e,i);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return J(i),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ne(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ne(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Ft(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return tn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local")return Kt(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return zt(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return en(n,e);if(n.method==="POST"&&t.pathname==="/complete")return nn(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return rn(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return on(n,e);if(n.method==="POST"&&t.pathname==="/update")return Bt(e);a(e,404,{error:"Not found"})}catch(r){a(e,500,{error:r?.message||String(r)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function an(n){let e="";const t=[];let o=!1,r=!1;const i=()=>{r&&!o&&!t.length&&process.exit(0)},l=async()=>{if(!o){for(o=!0;t.length;){const d=t.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const h=(await s.text()).trim();h&&process.stdout.write(h+`
10
- `)}catch(s){c.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:c.id,error:{code:-32e3,message:String(s?.message||s)}})+`
11
- `)}}o=!1,i()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",d=>{e+=d;let c;for(;(c=e.indexOf(`
12
- `))>=0;){const s=e.slice(0,c).trim();e=e.slice(c+1),s&&t.push(s)}l()}),process.stdin.on("end",()=>{r=!0,i()}),process.stdin.resume()}function sn(){et(),tt(),Et(),ie.on("error",n=>{n&&n.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: ${n?.message||n}`),process.exit(1)});for(const n of["SIGINT","SIGTERM"])process.on(n,()=>{const e=st("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const t=ct("shutdown");t&&u("info",`shutdown: closed ${t} warm agent process${t===1?"":"es"}`),setTimeout(()=>process.exit(0),e||t?300:0).unref?.(),!e&&!t&&process.exit(0)});ie.listen(O,k,async()=>{u("info",`listening on http://${k}:${O}`),D.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:n,label:e,hidden:t}]of Object.entries(T)){if(t)continue;const o=await n.available().catch(()=>({ok:!1}));u("info",` ${o.ok?"✓":"✕"} ${e}${o.ok?"":" — "+(o.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),te().then(n=>n.startIfConfigured()).then(n=>{n?.skipped||(n?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${n?.error||"unknown error"}`))}).catch(n=>u("error",`channels: ${n?.message||n}`))})}function cn(){console.log(`ChatPanel Bridge v${g}
9
+ `)}async function _(n,e,t,r){try{return t(await f(n))}catch(o){return a(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new I(`Bad JSON: ${o.message}`):o)),null}}async function Lt(n,e){const t=await _(n,e,wt,w);if(!t)return;if(!t.stream)try{const o=await S(t,()=>{},e);return a(e,200,mt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,w(o))}R(e);const r=ut(t.requestedModel,o=>A(e,o));try{await S(t,o=>r.delta(o),e),r.done()}catch(o){A(e,w(o))}A(e,"[DONE]"),e.end()}async function Wt(n,e){const t=await _(n,e,bt,w);if(!t)return;if(!t.stream)try{const o=await S(t,()=>{},e);return a(e,200,ft(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,w(o))}R(e);const r=ht(t.requestedModel,o=>A(e,o));try{await S(t,o=>r.delta(o),e),r.done()}catch(o){A(e,w(o))}A(e,"[DONE]"),e.end()}async function jt(n,e){const t=await _(n,e,St,w);if(!t)return;if(!t.stream)try{const o=await S(t,()=>{},e);return a(e,200,gt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,w(o))}R(e);const r=kt(t.requestedModel,o=>H(e,o.type,o));try{await S(t,o=>r.delta(o),e),r.done()}catch(o){const i={type:"error",sequence_number:0,...w(o)};H(e,"error",i)}e.end()}async function Jt(n,e){const t=await _(n,e,yt,U);if(!t)return;if(!t.stream)try{const o=await S(t,()=>{},e);return a(e,200,pt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,U(o))}R(e);const r=dt(t.requestedModel,(o,i)=>H(e,o,i));try{await S(t,o=>r.delta(o),e),r.done()}catch(o){H(e,"error",U(o))}e.end()}async function Ft(n,e){let t={};try{t=await f(n)||{}}catch{}const r=String(t.id||"").trim(),o=r?it(r,"stopped"):!1;return o&&h("info",`cancel: ${r} stopped by client`),a(e,200,{ok:!0,cancelled:o})}async function re(n,e,t){let r;try{r=await f(n)}catch{return a(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=t?F(t):Be(),i=s=>{o&&e.setHeader("Mcp-Session-Id",o.id),a(e,200,{jsonrpc:"2.0",id:r.id??null,result:s})},l=(s,c)=>a(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:s,message:c}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return i({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const d=He();if(r.method==="tools/list"){const s=o?o.specs.map(c=>({name:c.name,description:c.description,inputSchema:c.parameters||{type:"object",properties:{}}})):[];return i({tools:[...d,...s]})}if(r.method==="tools/call"){const s=await _e(r.params?.name,r.params?.arguments||{});if(s)return i(s);if(!o)return l(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return i(await Ge(o,r.params?.name,r.params?.arguments||{}))}catch(c){return i({content:[{type:"text",text:`error: ${c?.message||c}`}],isError:!0})}}return l(-32601,`Method not found: ${r.method}`)}async function Kt(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=t.server||{},o=t.message;if(!r.command||!o)return a(e,400,{error:"need server.command and message"});try{const i=await at({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd},o);return o.id==null?(e.writeHead(202),e.end()):a(e,200,i)}catch(i){return a(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(i?.message||i)}})}}async function zt(n,e){let t;try{t=await f(n)}catch(u){return a(e,400,{error:"Bad JSON: "+u.message})}const{url:r,headers:o,message:i}=t||{};if(!r||!i)return a(e,400,{error:"need url and message"});let l;try{l=Q(r)}catch(u){return a(e,400,{error:String(u?.message||u)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[u,m]of Object.entries(o)){const b=u.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(b)||b.startsWith("x-"))&&(d[u]=String(m))}const s=new AbortController,c=setTimeout(()=>s.abort(),3e4);try{const u=await fetch(l.href,{method:"POST",headers:d,body:JSON.stringify(i),redirect:"follow",signal:s.signal});try{u.url&&Q(u.url)}catch(b){return a(e,400,{error:String(b?.message||b)})}const m=await u.text().catch(()=>"");return a(e,200,{status:u.status,sessionId:u.headers.get("Mcp-Session-Id")||null,contentType:u.headers.get("Content-Type")||"",body:m})}catch(u){const m=u?.name==="AbortError"?"timed out":String(u?.message||u);return a(e,502,{error:`couldn't reach MCP server ${l.host}: ${m}`})}finally{clearTimeout(c)}}const ae=256*1024,Vt=5,Yt=8e3;async function Xt(n){let e=Z(n);const t=new AbortController,r=setTimeout(()=>t.abort(),Yt);try{for(let o=0;o<=Vt;o++){const i=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${g} (+link-title)`}});if(i.status>=300&&i.status<400&&i.headers.get("location")){if(e=Z(new URL(i.headers.get("location"),e).href),i.body)try{await i.body.cancel()}catch{}continue}if(!i.ok){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}const l=i.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(l)){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}return{title:qt(await Qt(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function Qt(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,ae);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:i,value:l}=await e.read();if(i||(o+=l.byteLength,r+=t.decode(l,{stream:!0}),/<\/title\s*>/i.test(r)||o>=ae))break}}finally{try{await e.cancel()}catch{}}return r}function Zt(n){return String(n).replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function qt(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Zt(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function en(n,e){let t;try{t=await f(n)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=t&&t.url;if(!r||typeof r!="string")return a(e,400,{error:"need url"});try{const o=await Xt(r);return a(e,200,{title:o.title||null,url:o.url||r})}catch(o){const i=o?.name==="AbortError"?"timed out":String(o?.message||o);return a(e,400,{error:`couldn't fetch title: ${i}`})}}async function tn(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=F(t.session);if(!r)return a(e,404,{error:"no such session"});const o=r.pending.get(t.id);return o?(r.pending.delete(t.id),o.resolve(t.result),a(e,200,{ok:!0})):a(e,404,{error:"no such pending call"})}async function nn(n,e){let t;try{t=await f(n)}catch(d){return a(e,400,{error:"Bad JSON: "+d.message})}const r=T[t.agent];if(!r)return a(e,404,{error:`Unknown agent "${t.agent}"`});const o=String(t.prompt||"").slice(0,6e3);if(!o)return a(e,400,{error:"Empty prompt"});const i=t.model||"",l=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let d="";return typeof r.engine.complete=="function"?d=await r.engine.complete({prompt:o,system:l,model:i}):await r.engine.chat({messages:[{role:"user",content:o}],system:l,options:{model:i}},s=>{s.type==="delta"?d+=s.text||"":s.type==="done"&&s.text&&(d+=s.text)}),a(e,200,{text:(d||"").trim()})}catch(d){return a(e,502,{error:d?.message||String(d)})}}async function on(n,e){let t;try{t=await f(n)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=T[t.agent];if(!r)return a(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof r.engine.listModels!="function")return a(e,200,{models:[]});try{const o=await r.engine.listModels(t.options||{});return a(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return a(e,502,{error:o?.message||String(o)})}}async function rn(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=String(t.command||"").trim();if(!r)return a(e,400,{error:"No command"});let o=null;try{o=nt(r)}catch{o=null}return a(e,200,{ok:!!o,via:o?o.kind:null})}const ie=ce(async(n,e)=>{if(vt(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return a(e,400,{error:"bad request"})}const r=$t(n,t.pathname);if(r)return a(e,403,{error:r});try{if(n.method==="GET"&&t.pathname==="/health")return It(e);const o=t.searchParams.getAll("dir");if(n.method==="GET"&&t.pathname==="/skills")return Nt(e,o);if(n.method==="GET"&&t.pathname==="/skills-quarantined")return Rt(e,o);if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const i=t.pathname.slice(8),l=i.indexOf("/file/");return l===-1?Ht(e,decodeURIComponent(i),o):_t(e,decodeURIComponent(i.slice(0,l)),decodeURIComponent(i.slice(l+6)),o)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return Ut(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Dt(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return oe(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return oe(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const i=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return a(e,200,{version:g,agents:Object.fromEntries(qe.map(l=>[l,i?Y(l)||null:!!Y(l)])),...i?{home:x.homedir(),path:process.env.PATH}:{}})}if(n.method==="POST"&&t.pathname==="/chat")return Gt(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return Lt(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Wt(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return jt(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return Jt(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return re(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const i=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return re(n,e,i);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return J(i),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ne(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ne(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Ft(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return tn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local")return Kt(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return zt(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return en(n,e);if(n.method==="POST"&&t.pathname==="/complete")return nn(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return on(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return rn(n,e);if(n.method==="POST"&&t.pathname==="/update")return Bt(e);a(e,404,{error:"Not found"})}catch(o){a(e,500,{error:o?.message||String(o)})}});function h(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function an(n){let e="";const t=[];let r=!1,o=!1;const i=()=>{o&&!r&&!t.length&&process.exit(0)},l=async()=>{if(!r){for(r=!0;t.length;){const d=t.shift();let s;try{s=JSON.parse(d)}catch{continue}try{const c=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(s.id==null)continue;const u=(await c.text()).trim();u&&process.stdout.write(u+`
10
+ `)}catch(c){s.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:s.id,error:{code:-32e3,message:String(c?.message||c)}})+`
11
+ `)}}r=!1,i()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",d=>{e+=d;let s;for(;(s=e.indexOf(`
12
+ `))>=0;){const c=e.slice(0,s).trim();e=e.slice(s+1),c&&t.push(c)}l()}),process.stdin.on("end",()=>{o=!0,i()}),process.stdin.resume()}function sn(){et(),tt(),Et(),ie.on("error",n=>{n&&n.code==="EADDRINUSE"&&(h("error",`Port ${O} is already in use — another app (or a second bridge) has it.`),h("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)),h("error",`bridge server error: ${n?.message||n}`),process.exit(1)});for(const n of["SIGINT","SIGTERM"])process.on(n,()=>{const e=st("shutdown");e&&h("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const t=ct("shutdown");t&&h("info",`shutdown: closed ${t} warm agent process${t===1?"":"es"}`),setTimeout(()=>process.exit(0),e||t?300:0).unref?.(),!e&&!t&&process.exit(0)});ie.listen(O,k,async()=>{h("info",`listening on http://${k}:${O}`),D.has(k)||h("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:n,label:e,hidden:t}]of Object.entries(T)){if(t)continue;const r=await n.available().catch(()=>({ok:!1}));h("info",` ${r.ok?"✓":"✕"} ${e}${r.ok?"":" — "+(r.reason||"unavailable")}`)}h("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),te().then(n=>n.startIfConfigured()).then(n=>{n?.skipped||(n?.ok?h("info","channels: telegram connected — polling for messages"):h("error",`channels: telegram not started — ${n?.error||"unknown error"}`))}).catch(n=>h("error",`channels: ${n?.message||n}`))})}function cn(){console.log(`ChatPanel Bridge v${g}
13
13
 
14
14
  Usage:
15
15
  chatpanel-bridge start the bridge (foreground) on ${k}:${O}
@@ -19,4 +19,4 @@ Usage:
19
19
  chatpanel-bridge --update download & install the latest version, then restart
20
20
  chatpanel-bridge --version print the version
21
21
 
22
- Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT`)}function ln(){const n=process.argv,e=(...t)=>t.some(o=>n.includes(o));if(e("--help","-h"))return cn(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("--install")){try{Oe(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(t){u("error","Install failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--uninstall")){try{Ae(),u("info","Removed the login auto-start.")}catch(t){u("error","Uninstall failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--status")){let t=!1;try{t=xe()}catch(o){u("error",String(o?.message||o))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const se=process.argv.indexOf("--mcp-stdio");if(se>=0){const n=process.argv[se+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),an(n)}else process.argv.includes("--update")?(async()=>{try{const n=await X(g);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),j()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():ln()||sn();
22
+ Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT`)}function ln(){const n=process.argv,e=(...t)=>t.some(r=>n.includes(r));if(e("--help","-h"))return cn(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("--install")){try{Oe(),h("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(t){h("error","Install failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--uninstall")){try{Ae(),h("info","Removed the login auto-start.")}catch(t){h("error","Uninstall failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--status")){let t=!1;try{t=xe()}catch(r){h("error",String(r?.message||r))}return h("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const se=process.argv.indexOf("--mcp-stdio");if(se>=0){const n=process.argv[se+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),an(n)}else process.argv.includes("--update")?(async()=>{try{const n=await X(g);h("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),j()}catch(n){h("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():ln()||sn();