@chatpanel/bridge 0.20.2 → 0.24.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/scripts/sync-events.mjs +1 -1
- package/src/engines/antigravity.js +5 -5
- package/src/engines/claude.js +6 -6
- package/src/engines/cli-agents.js +1 -1
- package/src/engines/codex.js +1 -1
- package/src/env.js +2 -3
- package/src/events/registries.js +1 -0
- package/src/mcp-local.js +4 -4
- package/src/server.js +6 -6
- package/src/warm-pool.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.24.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
|
|
6
6
|
"keywords": [
|
package/scripts/sync-events.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFileSync as r,writeFileSync as h,existsSync as i,mkdirSync as m}from"node:fs";import{fileURLToPath as d}from"node:url";import{dirname as f,join as n}from"node:path";const c=n(f(d(import.meta.url)),".."),v=["scopes.js","skill-manifest.js","skill-scan.js","ref.js","event.js","view.js","capability.js","reach.js","scm-connection.js","sandbox-policy.js","sandbox-grant.js","mcp-errors.js","mcp-signin.js","mcp-config-import.js","mcp-launcher.js","agent-permission.js"];function u(){return[n(c,"node_modules","@chatpanel","events"),n(c,"..","chatpanel-events")].find(e=>i(n(e,"skill-manifest.js")))}const s=process.argv.includes("--check"),a=u();if(!a){const e="chatpanel-events not found (check out ../chatpanel-events).";s&&(console.error(`sync-events --check: ${e}`),process.exit(1)),console.warn(`sync-events: ${e} Leaving src/events as-is.`),process.exit(0)}const l=n(c,"src","events");s||m(l,{recursive:!0});const j=e=>`// GENERATED — do not edit.
|
|
2
|
+
import{readFileSync as r,writeFileSync as h,existsSync as i,mkdirSync as m}from"node:fs";import{fileURLToPath as d}from"node:url";import{dirname as f,join as n}from"node:path";const c=n(f(d(import.meta.url)),".."),v=["scopes.js","skill-manifest.js","skill-scan.js","ref.js","event.js","view.js","capability.js","reach.js","scm-connection.js","sandbox-policy.js","sandbox-grant.js","mcp-errors.js","registries.js","mcp-signin.js","mcp-config-import.js","mcp-launcher.js","agent-permission.js"];function u(){return[n(c,"node_modules","@chatpanel","events"),n(c,"..","chatpanel-events")].find(e=>i(n(e,"skill-manifest.js")))}const s=process.argv.includes("--check"),a=u();if(!a){const e="chatpanel-events not found (check out ../chatpanel-events).";s&&(console.error(`sync-events --check: ${e}`),process.exit(1)),console.warn(`sync-events: ${e} Leaving src/events as-is.`),process.exit(0)}const l=n(c,"src","events");s||m(l,{recursive:!0});const j=e=>`// GENERATED — do not edit.
|
|
3
3
|
// Source of truth: chatpanel-events/${e} (npm @chatpanel/events).
|
|
4
4
|
// Edit there, then run: npm run sync:events
|
|
5
5
|
//
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{spawn as
|
|
2
|
-
`)){const
|
|
3
|
-
`}),{streamed:!0}}const
|
|
1
|
+
import{spawn as N,spawnSync as F}from"node:child_process";import{writeFileSync as z,unlinkSync as R}from"node:fs";import"node:os";import O from"node:path";import{agentAvailable as U,resolveCommand as j,buildSpawnSpec as B}from"../env.js";import{fitCliPrompt as G,argvPromptBudget as H}from"./prompt.js";import{summarizeCliError as J}from"../cli-errors.js";import{killOnAbort as K,spawnGroupOpts as W}from"../proc.js";import{track as Y,sandbox as Z,noteSandbox as q}from"../sandbox.js";import{pushExtraArgs as Q,FORBIDDEN as V}from"./args.js";import{resolveWorkdir as X}from"../workdir.js";const D=Number(process.env.CHATPANEL_AGY_TIMEOUT_MS)||18e4;async function yt(){try{const u=j("agy");if(!u)return[];const[a,n,i]=B(u,["models"],null),r=F(a,n,{...i,encoding:"utf8",timeout:15e3}),l=[],t=new Set;for(const s of String(r.stdout||"").split(`
|
|
2
|
+
`)){const o=s.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(o)&&!/^(name|model|models|id|provider|available)$/i.test(o)&&!t.has(o)&&(t.add(o),l.push(o),l.length>=100))break}return l}catch{return[]}}const P=()=>({started:new Set,finalText:""});function tt(u,a,n=P()){const i=String(u||"").trim();if(!i)return{streamed:!1};let r;try{r=JSON.parse(i)}catch{return a({type:"delta",text:`${i}
|
|
3
|
+
`}),{streamed:!0}}const l=r.event||r.type||"";if(l==="init")return a({type:"status",text:"Antigravity working"}),{streamed:!1};if(l==="result"){const s=r.result||{};return n.finalText=typeof s.response=="string"?s.response:"",s.status&&s.status!=="SUCCESS"&&a({type:"status",text:`Antigravity: ${s.status}`}),{streamed:!1}}if(l!=="step_update")return{streamed:!1};const t=r.step_update||{};if(t.step_type==="tool"){const s=`agy_${t.step_index??n.started.size}`,o=t.tool_info&&typeof t.tool_info=="object"?t.tool_info:{},d=t.tool_name||o.name||"tool";if(n.started.has(s)||(n.started.add(s),a({type:"tool",name:d,phase:"start",callId:s,input:o.parameters&&typeof o.parameters=="object"?o.parameters:{}})),t.state==="DONE"){const g=!!o.error||t.state==="ERROR",c=o.output==null?"":typeof o.output=="string"?o.output:JSON.stringify(o.output);a({type:"tool",name:d,phase:"done",callId:s,status:g?`error: ${String(o.error||"failed").slice(0,80)}`:"ok",result:String(g?o.error||"":c).slice(0,4e3)})}return{streamed:!1}}return t.step_type==="agent_response"&&typeof t.text_delta=="string"&&t.text_delta?(a({type:"delta",text:t.text_delta}),{streamed:!0}):{streamed:!1}}let x=!1,L=0;async function ht(){if(Date.now()-L>(x?3e4:4e3)){L=Date.now();try{x=U("agy")}catch{x=!1}}return x?{ok:!0}:{ok:!1,reason:"agy not found on PATH. Install Antigravity, then run `agy` once to sign in."}}function et(u,a){const n=[];for(let i=0;i<(u?.length||0);i++){const r=/^data:([^;]+);base64,(.+)$/s.exec(u[i]?.dataUrl||"");if(!r)continue;const l=(r[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",t=O.join(a,`chatpanel-img-${Date.now()}-${i}.${l}`);try{z(t,Buffer.from(r[2],"base64")),n.push(t)}catch{}}return n}async function wt({messages:u,system:a,options:n,images:i},r,{signal:l}={}){const t=X(n.workingDir),s=et(i,t),o=()=>s.forEach(e=>{try{R(e)}catch{}}),d=G(u,a,H({otherArgsChars:400}));let g=d.prompt;d.dropped&&r({type:"status",text:`Antigravity takes the prompt as a command-line argument, which this system caps — the oldest ${d.dropped} turn${d.dropped===1?"":"s"} of this conversation were left out to fit.`}),s.length&&(g+=`
|
|
4
4
|
|
|
5
|
-
The user attached image(s): ${s.map(
|
|
6
|
-
`))>=0;)
|
|
5
|
+
The user attached image(s): ${s.map(e=>"@"+O.basename(e)).join(" ")}`);const c=["-p",g];n.model&&c.push("--model",n.model),n.permissionMode==="bypassPermissions"&&c.push("--dangerously-skip-permissions"),Q(c,n.extraArgs,V.antigravity,r);const _=async e=>{const M=e?[...c,"--output-format","stream-json"]:c,y=await Z().wrap("agy",M,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,...n.runEnv||{}},...W},{engine:"antigravity",cwd:t});return q(r,y.record),new Promise((k,b)=>{let f;try{f=Y(N(y.bin,y.argv,y.opts),y,{kind:"agent"})}catch(p){return b(new Error(`Failed to start agy: ${p.message}`))}const $=K(f,l);let E="",T="",m="",v=!1;const I=P();let h;const S=()=>{clearTimeout(h),h=setTimeout(()=>{f.kill("SIGKILL"),b(new Error(`Antigravity timed out — no output for ${Math.round(D/1e3)}s.`))},D)};S();const C=p=>{tt(p,r,I).streamed&&(v=!0)};f.stdout.on("data",p=>{S();const w=p.toString();if(E+=w,!e){v=!0,r({type:"delta",text:w});return}m+=w;let A;for(;(A=m.indexOf(`
|
|
6
|
+
`))>=0;)C(m.slice(0,A)),m=m.slice(A+1)}),f.stderr.on("data",p=>{S(),T+=p.toString()}),f.on("error",p=>{clearTimeout(h),$(),b(new Error(`Failed to start agy: ${p.message}`))}),f.on("close",p=>{if(clearTimeout(h),$(),l?.aborted){k({code:0,aborted:!0});return}e&&m.trim()&&C(m),k({code:p,out:E,err:T,streamed:v,state:I})})})};try{let e=await _(!0);if(e.aborted||e.code!==0&&!e.streamed&&/output-format|unknown flag|flag provided but not defined/i.test(e.err)&&(r({type:"status",text:"This Antigravity CLI has no structured output; showing its text only. Update it with `agy update` to see tool activity."}),e=await _(!1),e.aborted))return;if(e.code!==0)throw new Error(J("Antigravity",e.code,e.err,e.out));e.streamed||r({type:"delta",text:(e.state?.finalText||e.out).trim()||"(no output)"}),r({type:"done",text:""})}finally{o()}}export{ht as available,wt as chat,tt as forwardAgyLine,yt as listModels,P as newAgyState};
|
package/src/engines/claude.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{spawn as
|
|
2
|
-
`)}catch{}};
|
|
3
|
-
`))>=0;){const
|
|
4
|
-
`):(
|
|
1
|
+
import{spawn as F}from"node:child_process";import{writeFile as W,unlink as H}from"node:fs/promises";import P from"node:os";import R from"node:path";import{resolveClaude as S,buildSpawnSpec as q,isCompiledBinary as ae,selfMcpStdio as ie}from"../env.js";import{signInStatus as le,signInMessage as z,loginRequired as ce}from"../sign-in.js";import{buildCliPrompt as U}from"./prompt.js";import{summarizeCliError as ue}from"../cli-errors.js";import{killOnAbort as pe}from"../proc.js";import{sandbox as de,noteSandbox as fe,track as he}from"../sandbox.js";import{pushExtraArgs as me,FORBIDDEN as ye}from"./args.js";import{relayTimeoutMax as _e}from"../relay-timeout.js";import{displayPath as be,resolveWorkdir as B}from"../workdir.js";import{connectorsFor as we}from"../connectors.js";import{chatWarm as Te}from"./claude-warm.js";import{claudePermissionResponse as ge,permissionAnswer as xe}from"../events/agent-permission.js";import{relayPermission as Ee}from"../mcp-sessions.js";async function Ce(e,t){const r=[];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",n=R.join(P.tmpdir(),`chatpanel-claude-img-${t}-${i}.${o}`);await W(n,Buffer.from(s[2],"base64")),r.push(n)}return r}const G=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,J=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task"],K=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),ke=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"])}),Se=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),Ae=Object.freeze(["remember","forget"]),ve=Object.freeze(["ask_model","ask_status"]),Y=Object.freeze({device:Object.freeze([]),trusted:Se});function Ne(e,t=[]){const r=Y[e]||Y.device,i=(t||[]).filter(n=>typeof n=="string"&&/^chatpanel/i.test(n)),s=[],o=[];for(const n of i){for(const a of r)s.push(`mcp__${n}__${a}`);for(const a of[...Ae,...ve])o.push(`mcp__${n}__${a}`)}return{allow:s,deny:o}}function Pe(e){if(!e||e==="any")return null;const t=K[e]?e:"device";return{allow:[...K[t]],deny:[...ke[t]]}}let M="Claude Code not found.",X=0,E=!1;async function st(){if(Date.now()-X>(E?3e4:4e3)){X=Date.now();try{S()||!ae()&&await j()?E=!0:(E=!1,M=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{E=!1}}return E?await le("claude",S()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:z("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:M}}async function at(){return["opus","sonnet","haiku"]}function Me(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:r,args:i}=ie(e.url),s=[...new Set(e.specs.map(o=>o?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:r,args:i}}},allowedTools:s.map(o=>`mcp__${t}__${o}`)}}async function Oe(e,t,r){const i=e?.request_id,s=e?.request?.subtype;if(s==="can_use_tool"){const o=t?await t(e.request):xe("deny","This run has no approval surface.");return r(ge(i,o,e.request)),!0}return r({type:"control_response",response:{subtype:"error",request_id:i,error:`unsupported control request: ${s||"unknown"}`}}),!1}function Q({prompt:e,args:t,cwd:r,env:i=null,emit:s,signal:o,harness:n=null,host:a=!1,ask:u=null}){const f=S();if(!f)return null;const[y,_,b]=q(f,a?[...t,"--input-format","stream-json"]:t,r,i);return new Promise((m,p)=>{de().wrap(y,_,b,{engine:"claude",cwd:r}).then(c=>{fe(s,c.record);let l;try{l=he(F(c.bin,c.argv,c.opts),c,{kind:"agent"})}catch(d){return p(new Error(`Failed to start claude: ${d.message}`))}const w=pe(l,o);let h="",T="",v=!1,g=null;const oe={sawText:!1,tail:"",boundary:!1,harnessChars:n};let O="",C,L=0;const N=()=>{clearTimeout(C),!L&&(C=setTimeout(()=>{l.kill("SIGKILL"),p(new Error(`Claude Code timed out — no output for ${Math.round(G/1e3)}s.`))},G))};N();const se=d=>{try{l.stdin.write(`${JSON.stringify(d)}
|
|
2
|
+
`)}catch{}};l.stdout.on("data",d=>{N(),h+=d.toString();let $;for(;($=h.indexOf(`
|
|
3
|
+
`))>=0;){const D=h.slice(0,$).trim();if(h=h.slice($+1),!D.startsWith("{"))continue;let x;try{x=JSON.parse(D)}catch{continue}if(x.type==="control_request"){L++,clearTimeout(C),Oe(x,u,se).catch(()=>{}).finally(()=>{L--,N()});continue}if(x.type==="control_response")continue;const k=ee(x,s,v,r,oe);k.streamed&&(v=!0),k.result!=null&&(O=k.result),k.apiError&&(g=k.apiError),a&&x.type==="result"&&l.stdin.end()}}),l.stderr.on("data",d=>{N(),T+=d.toString()}),l.on("error",d=>{clearTimeout(C),w(),p(new Error(`Failed to start claude (${y}): ${d.message}`))}),l.on("close",d=>{if(clearTimeout(C),w(),o?.aborted){m({streamedAny:v,resultText:O});return}if(g&&ce(g))return p(new Error(z("Claude Code","claude")));if(d===0&&g)return p(new Error(`Claude Code reported an error: ${g}`));d===0?m({streamedAny:v,resultText:O}):p(new Error(ue("Claude Code",d,T,g||"",{agentId:"claude"})))}),a?l.stdin.write(`${JSON.stringify({type:"user",message:{role:"user",content:e}})}
|
|
4
|
+
`):(l.stdin.write(e),l.stdin.end())}).catch(p)})}function Le(e){let t="";return typeof e=="string"?t=e:Array.isArray(e)&&(t=e.map(r=>typeof r=="string"?r:r?.text||"").filter(Boolean).join(`
|
|
5
5
|
`)),t.length>4e3?`${t.slice(0,4e3)}…`:t}function V(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
|
|
6
6
|
|
|
7
7
|
`}),e.boundary=!1)}function Z(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function ee(e,t,r,i="",s=null){const o={streamed:!1,result:null};if(e.type==="stream_event"){const n=e.event;n?.type==="content_block_delta"&&(n.delta?.type==="text_delta"?(o.streamed=!0,V(s,t),t({type:"delta",text:n.delta.text}),Z(s,n.delta.text)):n.delta?.type==="thinking_delta"&&t({type:"reasoning",text:n.delta.thinking||""}))}else if(e.type==="assistant"){if(e.is_api_error_message||e.error)return o.apiError=(e.message?.content||[]).filter(n=>n.type==="text").map(n=>n.text).join(`
|
|
8
|
-
`)||String(e.error||"api error"),o;for(const n of e.message?.content||[])n.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:n.name,phase:"start",callId:n.id,input:n.input,summary:
|
|
8
|
+
`)||String(e.error||"api error"),o;for(const n of e.message?.content||[])n.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:n.name,phase:"start",callId:n.id,input:n.input,summary:De(n,i)})):n.type==="text"&&!r&&(o.streamed=!0,V(s,t),t({type:"delta",text:n.text}),Z(s,n.text))}else if(e.type==="user")for(const n of e.message?.content||[])n.type==="tool_result"&&t({type:"tool",phase:"done",callId:n.tool_use_id,status:n.is_error?"error":"ok",result:Le(n.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 n=e.usage||e.message?.usage;if(n){const a=Number.isFinite(Number(e.total_cost_usd))?Number(e.total_cost_usd):null,u=Number(s?.costUsdBefore)||0;s&&a!=null&&(s.costUsdTotal=a),t({type:"usage",provider:"bridge",inputTokens:n.input_tokens||0,outputTokens:n.output_tokens||0,cacheReadTokens:n.cache_read_input_tokens||0,cacheWriteTokens:n.cache_creation_input_tokens||0,costUsd:a!=null?Math.max(0,a-u):null,costBasis:"list",...s?.harnessChars!=null?{harnessChars:s.harnessChars}:{}})}}return o}const te=process.env.CHATPANEL_CLAUDE_EFFORT??"low";let A=null;function re({probe:e=null}={}){return A||(A=(async()=>{try{return String(await(e?e():new Promise(t=>{const[r,i,s]=q(S(),["--help"],null),o=F(r,i,{...s,stdio:["ignore","pipe","pipe"]});let n="";o.stdout.on("data",a=>{n+=a}),o.on("error",()=>t("")),o.on("close",()=>t(n)),setTimeout(()=>{try{o.kill()}catch{}t(n)},8e3).unref?.()}))||"")}catch{return""}})(),A)}async function $e(e={}){return/--effort\b/.test(await re(e))}async function We(e={}){return/--append-system-prompt(?:-file\b|\[-file\])/.test(await re(e))}function it(){A=null}async function Re({system:e,options:t,tag:r}){const i=t.permissionMode||"default",s=B(t.workingDir),o=["--print","--output-format","stream-json","--include-partial-messages","--verbose"];te&&await $e()&&o.push("--effort",te);const n=[],a=[],u=Me(t.mcp);if(u){const c=R.join(P.tmpdir(),`chatpanel-mcp-${r}.json`);await W(c,JSON.stringify(u.config)),n.push(c),o.push("--mcp-config",c),a.push(...u.allowedTools)}const f=Pe(t.reach);if(f){const c=Ne(t.reach,await we("claude").catch(()=>[]));o.push("--allowedTools",...f.allow,...a,...c.allow),o.push("--disallowedTools",...f.deny,...c.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",...J,...a);const y=!f&&t.approvals===!0;if(y&&o.push("--permission-prompt-tool","stdio"),e)if(S()?.kind!=="wsl"&&await We()){const l=R.join(P.tmpdir(),`chatpanel-system-${r}.md`);await W(l,e,{mode:384}),n.push(l),o.push("--append-system-prompt-file",l)}else o.push("--append-system-prompt",e);t.model&&o.push("--model",t.model),t.useLocalConfig===!1&&o.push("--setting-sources","");const _=u&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(_e(t.mcp?.specs))}:null,b=t.askDepth?{CHATPANEL_ASK_DEPTH:String(Math.max(0,Math.min(8,Number(t.askDepth)||0)))}:null,m=_||b||t.runEnv?{...t.runEnv||{},..._||{},...b||{}}:null;return{args:o,cwd:s,runEnv:m,cleanup:()=>n.forEach(c=>H(c).catch(()=>{})),hasMcp:!!u,approvals:y}}function ne({prompt:e="",system:t="",specs:r=null}={}){const i=Array.isArray(r)&&r.length?JSON.stringify(r).length:0;return String(e).length+String(t).length+i}function Ie(e,t=[],r=""){let i=U(e,r);return t.length&&(i+=`
|
|
9
9
|
|
|
10
|
-
The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}async function
|
|
10
|
+
The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}async function lt({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=await Te({messages:e,system:t,options:r,images:i},s,{signal:o}).catch(a=>({handled:!1,reason:a?.message||String(a),thrown:!0}));if(!n.handled&&!o?.aborted){if(n.thrown)throw new Error(n.reason);return je({messages:e,system:t,options:r,images:i},s,{signal:o})}}async function je({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=await Re({system:t,options:r,tag:n}),{args:u,cwd:f,runEnv:y}=a,_=await Ce(i,n),b=()=>{_.forEach(l=>H(l).catch(()=>{})),a.cleanup()},m=Ie(e,_);me(u,r.extraArgs,ye.claude,s);const p=a.approvals&&r.permissionSession?l=>Ee(r.permissionSession,l):null,c=Q({prompt:m,args:u,cwd:f,env:y,emit:s,signal:o,harness:ne({prompt:m,system:t,specs:r.mcp?.specs}),host:a.approvals,ask:p});if(c===null)return b(),Fe({messages:e,system:t,options:r},s,{signal:o});try{const{streamedAny:l,resultText:w}=await c;s({type:"done",text:l?"":w})}finally{b()}}async function ct({prompt:e,system:t,model:r}){const i=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",r||"haiku","--system-prompt",t||"Continue the user's text briefly. Reply with only the continuation."];let s="";const o=Q({prompt:e,args:i,cwd:null,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(o===null)return He({prompt:e,system:t,model:r});const{resultText:n}=await o;return(s||n||"").trim()}function De(e,t=""){const r=e.input||{};return r.command?String(r.command).slice(0,60):r.file_path?be(r.file_path,t):r.pattern?r.pattern:r.url?r.url:r.description?String(r.description).slice(0,80):r.query?String(r.query).slice(0,80):r.prompt?String(r.prompt).slice(0,80):""}let I=null;function j(){return I||(I=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),I}async function Fe({messages:e,system:t,options:r},i,{signal:s}={}){const o=await j();if(!o)throw new Error(M);const{query:n}=o,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const u=r.permissionMode||"default",f=B(r.workingDir),y=u==="acceptEdits"||u==="bypassPermissions",_=new Set(J),b=async h=>_.has(h)||y?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${h} blocked — set this agent's permission mode in ChatPanel to enable it.`};let m=!1;const p=U(e),c={sawText:!1,tail:"",boundary:!1,harnessChars:ne({prompt:p,system:t})};let l="";const w=n({prompt:p,options:{cwd:f,permissionMode:u,includePartialMessages:!0,canUseTool:b,abortController:a,settingSources:r.useLocalConfig===!1?[]:["user","project"],systemPrompt:t?{type:"preset",preset:"claude_code",append:t}:{type:"preset",preset:"claude_code"},...r.model?{model:r.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const h of w){const T=ee(h,i,m,f,c);T.streamed&&(m=!0),T.result!=null&&(l=T.result)}}catch(h){if(s?.aborted||a.signal.aborted)return;throw h}i({type:"done",text:m?"":l})}async function He({prompt:e,system:t,model:r}){const i=await j();if(!i)throw new Error(M);const{query:s}=i;let o="";const n=s({prompt:e,options:{cwd:P.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:t||"Continue the user's text briefly. Reply with only the continuation.",model:r||"haiku"}});for await(const a of n)if(a.type==="assistant")for(const u of a.message.content)u.type==="text"&&(o+=u.text);else a.type==="result"&&a.subtype==="success"&&!o&&(o=a.result||"");return o.trim()}export{it as _resetEffortProbe,Oe as answerControlRequest,st as available,Re as buildClaudeLaunch,Ne as channelMcpTools,Pe as channelToolPolicy,lt as chat,je as chatCold,Me as claudeMcpConfig,Ie as claudePrompt,$e as claudeSupportsEffort,We as claudeSupportsSystemPromptFile,ct as complete,ee as handleMessage,ne as harnessChars,at as listModels,Ce as writeImages};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{runSpec as h,listSpecModels as A,runForStdout as d,CHATPANEL_STABLE_MCP_URL as m}from"./custom.js";import{
|
|
1
|
+
import{runSpec as h,listSpecModels as A,runForStdout as d,CHATPANEL_STABLE_MCP_URL as m}from"./custom.js";import{agentAvailable as b,selfMcpStdio as u}from"../env.js";function a(e,o,i,t={}){let r=!1,s=0;const n={...o,command:e};return{spec:n,async available(){if(Date.now()-s>(r?3e4:4e3)){s=Date.now();try{r=b(e)}catch{r=!1}}return r?{ok:!0}:{ok:!1,reason:i}},listModels(l={}){return t.listModels?t.listModels(e,l):A(e,o.listModelsArgs,l.workingDir)},chat(l,c,p){return h(n,l,c,p)}}}const H=a("pi",{args:"-p",promptVia:"stdin",modelArg:"--model {model}",imageArg:"@{path}",toolAdapter:"pi-extension",listModelsArgs:"--list-models",label:"Pi"},"pi not found on PATH. Install Pi, then run `pi` once to sign in."),D=a("opencode",{args:"run --format json --dangerously-skip-permissions",promptVia:"stdin",modelArg:"-m {model}",imageArg:"-f {path}",format:"opencode-json",requiresStableMcp:!0,stableMcpConfigCheck:"opencode",listModelsArgs:"models",label:"OpenCode"},"opencode not found on PATH. Install opencode, then sign in."),P=a("kiro-cli",{args:"chat --no-interactive --require-mcp-startup",promptVia:"stdin",modelArg:"--model {model}",trustAllToolsForMcp:!0,trustAllToolsArg:"--trust-all-tools",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"kiro",stableMcpSetupArgs:["mcp","add","--scope","global","--name","chatpanel_browser","--url","http://127.0.0.1:4319/mcp","--force"],stableMcpSetupCommand:"kiro-cli mcp add --scope global --name chatpanel_browser --url http://127.0.0.1:4319/mcp --force",listModelsArgs:"--list-models",label:"Kiro"},"kiro-cli not found on PATH. Install Kiro CLI, then sign in."),S=["--output-format","json","--no-color","--log-level","none","--no-ask-user","--no-auto-update","--no-remote","--no-remote-export"],_=a("copilot",{args:S,promptVia:"stdin",modelArg:"--model {model}",imageArg:"--attachment {path}",format:"copilot-json",mcpArg:"--additional-mcp-config @{file}",permissionArgs:{default:["--allow-all-tools"],acceptEdits:["--allow-all-tools","--allow-all-paths"],bypassPermissions:["--allow-all"]},forbidden:"copilot",label:"GitHub Copilot"},"copilot not found on PATH. Install GitHub Copilot CLI, then run `copilot login`.",{listModels:(e,o)=>M(e,o.workingDir)});async function M(e="copilot",o){const i=await d(e,["help","config"],o),t=[],r=new Set;let s=!1;for(const n of String(i||"").split(`
|
|
2
2
|
`)){const l=/^\s*`([A-Za-z][\w.]*)`\s*:/.exec(n);if(l){s=l[1]==="model";continue}if(!s)continue;const c=/^\s*-\s*"([^"]+)"\s*$/.exec(n);if(!c)continue;const p=c[1];if(!r.has(p)&&(r.add(p),t.push(p),t.length>=200))break}return t.length?["auto",...t]:[]}const T=a("dsh",{args:["--profile","headless","{prompt}"],promptVia:"arg",format:"text",modelPatch:{arg:"--patch {file}",build:e=>`- id: ${g}
|
|
3
3
|
config:
|
|
4
4
|
provider: ${k}
|
package/src/engines/codex.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{spawn as B}from"node:child_process";import{killOnAbort as H,spawnGroupOpts as F}from"../proc.js";import{track as L,sandbox as X,noteSandbox as J}from"../sandbox.js";import{readFile as R,unlink as M,writeFile as q}from"node:fs/promises";import{existsSync as N,mkdirSync as z,symlinkSync as W,readFileSync as O}from"node:fs";import S from"node:os";import m from"node:path";import{
|
|
1
|
+
import{spawn as B}from"node:child_process";import{killOnAbort as H,spawnGroupOpts as F}from"../proc.js";import{track as L,sandbox as X,noteSandbox as J}from"../sandbox.js";import{readFile as R,unlink as M,writeFile as q}from"node:fs/promises";import{existsSync as N,mkdirSync as z,symlinkSync as W,readFileSync as O}from"node:fs";import S from"node:os";import m from"node:path";import{agentAvailable as G,selfMcpStdio as K,resolveCommand as U}from"../env.js";import{relayTimeoutMax as Z}from"../relay-timeout.js";import{buildCliPrompt as Q}from"./prompt.js";import{pushExtraArgs as V,FORBIDDEN as Y}from"./args.js";import{resolveWorkdir as ee}from"../workdir.js";import{summarizeCliError as te}from"../cli-errors.js";import{signInStatus as oe,signInMessage as re}from"../sign-in.js";import{disabledMcpServers as ne,planMcpRetry as se,quarantine as ae}from"../mcp-quarantine.js";import{chatWarm as ce}from"./codex-appserver.js";const j=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,D=process.env.CHATPANEL_CODEX_EFFORT??"low",ie=["gpt-5-codex","gpt-5","o3","o4-mini"];let C=!1;function Te(){C=!1}async function Pe(){const n=new Set;try{const r=process.env.CODEX_HOME||m.join(S.homedir(),".codex"),t=O(m.join(r,"config.toml"),"utf8");for(const a of t.matchAll(/(?:^|\n)\s*model\s*=\s*["']([^"'\n]+)["']/g))n.add(a[1].trim())}catch{}for(const r of ie)n.add(r);return[...n]}const I=m.join(S.homedir(),".chatpanel","codex-home");let T=!1;function le(){if(!T)try{z(I,{recursive:!0});const n=m.join(S.homedir(),".codex","auth.json"),r=m.join(I,"auth.json");if(N(n)&&!N(r))try{W(n,r)}catch{}T=!0}catch{return null}return I}let A=!1,P=0;async function Be(){if(Date.now()-P>(A?3e4:4e3)){P=Date.now();try{A=G("codex")}catch{A=!1}}return A?await oe("codex",U("codex")).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:re("Codex","codex")}:{ok:!0}:{ok:!1,reason:"codex not found on PATH. Install it and run `codex login`."}}function de(n){if(!n?.url)return[];const r=n.serverName||"chatpanel_browser",{command:t,args:a}=K(n.url),e=["-c",`mcp_servers.${r}.command=${JSON.stringify(t)}`,"-c",`mcp_servers.${r}.args=${JSON.stringify(a)}`,"-c",`mcp_servers.${r}.default_tools_approval_mode="approve"`,"-c",`mcp_servers.${r}.startup_timeout_sec=30`,"-c",`mcp_servers.${r}.tool_timeout_sec=${Math.ceil(Z(n.specs)/1e3)}`],s=[...new Set((n.specs||[]).map(i=>i?.name).filter(Boolean))];return s.length&&e.push("-c",`mcp_servers.${r}.enabled_tools=${JSON.stringify(s)}`),e}function pe(n){try{const r=O(m.join(n,"config.toml"),"utf8"),t=new Set;for(const a of r.matchAll(/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*[.\]]/gm))t.add(a[1]);return t}catch{return new Set}}function ue(n){const r=new Set;try{const t=O(m.join(n,"config.toml"),"utf8"),a=/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*\]\s*$([\s\S]*?)(?=^\s*\[|$(?![\r\n]))/gm;for(const e of t.matchAll(a)){const s=e[2]||"",i=/^\s*command\s*=\s*"([^"]*)"/m.exec(s)?.[1]||"",o=/^\s*url\s*=\s*"([^"]*)"/m.exec(s)?.[1]||"";(/chatpanel-(gateway|bridge)(\.js|\.cmd|\.exe)?$/.test(i)||/^https?:\/\/(127\.0\.0\.1|localhost):43(19|20)\//.test(o))&&r.add(e[1])}}catch{}return r}function fe(n=[]){return n.flatMap(r=>["-c",`mcp_servers.${r}.enabled=false`])}async function me(n,r){const t=[];for(let a=0;a<(n?.length||0);a++){const e=/^data:([^;]+);base64,(.+)$/s.exec(n[a]?.dataUrl||"");if(!e)continue;const s=(e[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",i=m.join(S.tmpdir(),`chatpanel-codex-img-${r}-${a}.${s}`);await q(i,Buffer.from(e[2],"base64")),t.push(i)}return t}async function he({args:n,cwd:r,env:t,prompt:a,outFile:e,emit:s,signal:i}){const o=await X().wrap("codex",n,{cwd:r,stdio:["pipe","pipe","pipe"],env:t,...F},{engine:"codex",cwd:r});return J(s,o.record),new Promise((c,f)=>{let l;try{l=L(B(o.bin,o.argv,o.opts),o,{kind:"agent"})}catch(u){return f(new Error(`Failed to start codex: ${u.message}`))}const g=H(l,i);let y="",b="",w=!1;const k=u=>{u?.type!=="status"&&(w=!0),s(u)},_={started:new Set,reasoned:new Set,n:0};let x;const $=()=>{clearTimeout(x),x=setTimeout(()=>{l.kill("SIGKILL"),f(new Error(`Codex timed out — no output for ${Math.round(j/1e3)}s.`))},j)};$(),l.stdout.on("data",u=>{$(),y+=u.toString();let h;for(;(h=y.indexOf(`
|
|
2
2
|
`))>=0;){const v=y.slice(0,h).trim();if(y=y.slice(h+1),!!v.startsWith("{"))try{ye(JSON.parse(v),k,_)}catch{}}}),l.stderr.on("data",u=>{$(),b+=u.toString()}),l.on("error",u=>{clearTimeout(x),g(),f(u)}),l.on("close",async u=>{clearTimeout(x),g();let h="";try{h=(await R(e,"utf8")).trim()}catch{}M(e).catch(()=>{}),c({code:u,stderr:b,text:h,streamed:w,said:!!_.saidAny,policyBlocked:!!_.policyBlocked})}),l.stdin.write(a),l.stdin.end()})}async function He({messages:n,system:r,options:t,images:a},e,{signal:s}={}){const i=await ce({messages:n,system:r,options:t,images:a},e,{signal:s}).catch(o=>({handled:!1,reason:o?.message||String(o),thrown:!0}));if(!i.handled&&!s?.aborted){if(i.thrown)throw new Error(i.reason);return ge({messages:n,system:r,options:t,images:a},e,{signal:s})}}async function ge({messages:n,system:r,options:t,images:a},e,{signal:s}={}){const i=`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=m.join(S.tmpdir(),`chatpanel-codex-${i}.txt`),c=await me(a,i),f=()=>c.forEach(d=>M(d).catch(()=>{})),l=ee(t.workingDir),g=[];V(g,t.extraArgs,Y.codex,e);const y=d=>{const p=["exec","--json","--skip-git-repo-check","-o",o];if(t.permissionMode==="bypassPermissions")p.push("--dangerously-bypass-approvals-and-sandbox");else{const E=t.permissionMode==="acceptEdits"?"workspace-write":"read-only";p.push("-s",E),C||p.push("-c","approval_policy=never")}D&&p.push("-c",`model_reasoning_effort=${D}`),p.push("-c","model_reasoning_summary=auto"),p.push(...de(t.mcp)),p.push(...fe(d)),t.model&&p.push("-m",t.model),p.push(...g);for(const E of c)p.push("-i",E);return p.push("-"),p},b=t.useLocalConfig!==!1,w={...process.env,...t.runEnv||{}};if(!b){const d=le();d&&(w.CODEX_HOME=d)}const k=t.mcp?.serverName||"chatpanel_browser",_=w.CODEX_HOME||process.env.CODEX_HOME||m.join(S.homedir(),".codex"),x=pe(_),$=(t.mcp?.specs||[]).length>0;let u=[...new Set([...ne("codex",t,[k]),...$?ue(_):[]])].filter(d=>x.has(d));const h=Q(n,r),v=()=>he({args:y(u),cwd:l,env:w,prompt:h,outFile:o,emit:e,signal:s});try{let d=await v();if(d.policyBlocked&&(C=!0),!s?.aborted&&d.code!==0&&!d.streamed){const p=se({agent:"codex",text:d.stderr,protect:[k],already:u});p&&x.has(p.server)&&(ae("codex",p.server),e({type:"status",text:`MCP server "${p.server}" failed to load — ${p.short}. Skipping it and retrying.`}),u=[...u,p.server],d=await v())}if(s?.aborted)return;if(d.code!==0)throw new Error(te("Codex",d.code,d.stderr,"",{agentId:"codex"}));d.said||e({type:"delta",text:d.text||"(no output)"}),e({type:"done",text:""})}finally{f()}}function ye(n,r,t={started:new Set,reasoned:new Set,n:0}){const a=n.type||"",e=n.item||{},s=e.type||"",i=a==="item.completed"||e.status==="completed"||e.status==="failed";if(s==="agent_message"&&i){const o=e.id||`msg_${t.n++}`,c=String(e.text||"");c&&!t.said?.has(o)&&((t.said||=new Set).add(o),r({type:"delta",text:`${t.saidAny?`
|
|
3
3
|
|
|
4
4
|
`:""}${c}`}),t.saidAny=!0);return}if(s==="command_execution"||!s&&a.includes("command")){const o=e.id||`cmd_${t.n++}`;if(t.started.has(o)||(t.started.add(o),r({type:"tool",name:"shell",phase:"start",callId:o,input:{command:e.command||""}})),i){const c=e.exit_code===0||e.exit_code==null;r({type:"tool",name:"shell",phase:"done",callId:o,status:c?"ok":`exit ${e.exit_code}`,result:String(e.aggregated_output||"").slice(0,4e3)})}return}if(s==="file_change"||!s&&a.includes("patch")){const o=e.id||`edit_${t.n++}`,c=Array.isArray(e.changes)?e.changes.map(f=>f.path||f.file).filter(Boolean):[];t.started.has(o)||(t.started.add(o),r({type:"tool",name:"edit",phase:"start",callId:o,input:{files:c}})),i&&r({type:"tool",name:"edit",phase:"done",callId:o,status:"ok"});return}if(s==="web_search"){const o=e.id||`ws_${t.n++}`,c=e.action&&typeof e.action=="object"?e.action:{},f=e.query||c.query||"",l=c.url||"";t.started.has(o)||(t.started.add(o),r({type:"tool",name:"web_search",phase:"start",callId:o,input:{query:f,...l?{url:l}:{}}})),(i||a==="item.completed")&&r({type:"tool",name:"web_search",phase:"done",callId:o,status:"ok",result:l?`Opened ${l}`:f?`Searched the web for ${f}`:"Searched the web"});return}if(s==="mcp_tool_call"){const o=e.id||`mcp_${t.n++}`,c=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(t.started.has(o)||(t.started.add(o),r({type:"tool",name:c,phase:"start",callId:o,input:e.arguments&&typeof e.arguments=="object"?e.arguments:{}})),i){const f=e.status==="failed"||e.error!=null,l=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error,g=e.result==null?"":typeof e.result=="string"?e.result:JSON.stringify(e.result);r({type:"tool",name:c,phase:"done",callId:o,status:f?`error: ${String(l||"failed").slice(0,80)}`:"ok",result:String(f?l||"":g).slice(0,4e3)})}return}if(s==="todo_list"&&Array.isArray(e.items)&&e.items.length){const o=e.items.map(c=>`${c.completed?"☑":"☐"} ${c.text||""}`).join(`
|
package/src/env.js
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
import d from"node:os";import{spawnGroupOpts as C}from"./proc.js";import c from"node:path";import{spawnSync as f}from"node:child_process";import{readdirSync as m,readFileSync as A,existsSync as u}from"node:fs";let g=!1,x=!1;const k=["codex","claude","agy","pi","opencode","kiro-cli","copilot","dsh"];function O(n){return j(process.env.PATH||"",process.platform).some(o=>o&&(u(c.join(o,n))||u(c.join(o,n+".exe"))))}function K(n){for(const e of $(n))if(u(e))return e;return E(n)||null}function P(){const n=c.basename(process.execPath).toLowerCase();return!(n.startsWith("node")||n.startsWith("bun"))}function pn(n){const e=["--mcp-stdio",n];if(P())return{command:process.execPath,args:e};const o=process.argv[1]||c.join(process.cwd(),"src","server.js"),t=process.env.CHATPANEL_BRIDGE_EMBEDDED==="1"?["--bridge"]:[];return{command:process.execPath,args:[o,...t,...e]}}function E(n){if(process.platform==="win32")return"";try{const e=process.env.SHELL||"/bin/zsh",t=(f(e,["-lc",`command -v ${n} 2>/dev/null`],{encoding:"utf8",timeout:4e3}).stdout||"").trim().split(`
|
|
2
|
-
`)
|
|
3
|
-
`)){const r=i.indexOf(" ");if(r<=0)continue;const s=i.slice(0,r).trim(),a=i.slice(r+1);R.includes(s)&&!process.env[s]&&a&&(process.env[s]=a)}}catch{}}function bn(){if(g)return;g=!0;const n=d.homedir();if(process.platform==="win32"){L({force:!0,home:n});return}const e=tn(n),o=[...e?[e]:[],"/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",c.join(n,".local","bin"),c.join(n,"bin"),c.join(n,".npm-global","bin"),c.join(n,".cargo","bin"),c.join(n,".deno","bin"),c.join(n,".bun","bin"),...h(n),...on(n)];let t="";try{const s=process.env.SHELL||"/bin/zsh",a=f(s,["-lc",'command -p echo "$PATH"'],{encoding:"utf8",timeout:4e3});a.status===0&&(t=(a.stdout||"").trim())}catch{}const i=new Set,r=[...e?[e]:[],...t?t.split(":"):[],...process.env.PATH?process.env.PATH.split(c.delimiter):[],...o].filter(s=>s&&!i.has(s)&&(i.add(s),!0));process.env.PATH=r.join(c.delimiter);for(const s of k){if(O(s))continue;const a=E(s);a&&(process.env.PATH=c.dirname(a)+c.delimiter+process.env.PATH)}}export{k as AGENT_CLIS,rn as agentCandidateBins,h as agentInstallDirs,fn as buildSpawnSpec,$ as commandCandidateFiles,jn as enrichAgentEnv,bn as enrichPath,S as expandWindowsEnv,K as findAgentBin,P as isCompiledBinary,D as isWindowsExecutable,X as nodeRuntimeWindows,tn as nvmCurrentBin,V as parseRegValue,L as refreshWindowsPath,U as registryPathWindows,dn as resolveClaude,_ as resolveCommand,pn as selfMcpStdio,nn as toWslPath};
|
|
1
|
+
import f from"node:os";import{spawnGroupOpts as O}from"./proc.js";import s from"node:path";import{spawnSync as b}from"node:child_process";import{readdirSync as h,readFileSync as _,existsSync as u}from"node:fs";let N=!1,y=!1;const D=["codex","claude","agy","pi","opencode","kiro-cli","copilot","dsh"];function J(n){return d(process.env.PATH||"",process.platform).some(o=>o&&(u(s.join(o,n))||u(s.join(o,n+".exe"))))}function Z(n){const t=R(n);if(t)return t;if(k()){const o=R(n);if(o)return o}return sn(n)||null}function Hn(n){return!!v(n)}function R(n){for(const t of q(n))if(u(t))return t;return null}function g(){const n=s.basename(process.execPath).toLowerCase();return!(n.startsWith("node")||n.startsWith("bun"))}function On(n){const t=["--mcp-stdio",n];if(g())return{command:process.execPath,args:t};const o=process.argv[1]||s.join(process.cwd(),"src","server.js"),i=process.env.CHATPANEL_BRIDGE_EMBEDDED==="1"?["--bridge"]:[];return{command:process.execPath,args:[o,...i,...t]}}const m="CHATPANEL_ENV",$=6e3;function x(n){for(const t of String(n||"").split(/\r?\n/)){const o=t.indexOf(" ");if(o>0&&t.slice(0,o).trim().endsWith(m))return t.slice(o+1).trim()}return""}function nn(n){return/^[\w.+-]+$/.test(String(n||""))}function E(){if(process.env.SHELL)return process.env.SHELL;try{const{shell:n}=f.userInfo();if(n&&n!=="/usr/bin/false"&&n!=="/sbin/nologin")return n}catch{}return"/bin/sh"}function W(n,{interactive:t}={}){if(process.platform==="win32")return"";try{const o=t?["-l","-i","-c"]:["-l","-c"];return b(E(),[...o,n],{encoding:"utf8",timeout:$,stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}}).stdout||""}catch{return""}}function tn(n){let t="";for(const o of String(n||"").split(/\r?\n/))o.startsWith("PATH=")&&(t=o.slice(5).trim());return t}function on({interactive:n=!0,ask:t=W}={}){const o=x(t(`command -p printf '%s\\t%s\\n' ${m} "$PATH"`,{interactive:n}));return d(o||tn(t("/usr/bin/env",{interactive:n})),process.platform)}const C=1e4,en=3e5;let S=0,P=C;function k({force:n=!1,now:t=Date.now(),read:o=on,env:i=process.env}={}){if(process.platform==="win32"||!n&&t-S<P)return!1;S=t;const e=d(i.PATH||"",process.platform),r=L(j([...o({interactive:!0}),...e])),c=r.length>e.length;return P=c?C:Math.min(P*2,en),c?(i.PATH=r.join(s.delimiter),!0):!1}function Nn(){S=0,P=C,T.clear()}const T=new Map,rn=15e3;function sn(n){if(process.platform==="win32"||!nn(n))return"";const t=T.get(n);if(t&&(t.bin||Date.now()-t.at<rn))return t.bin;const o=[`command -p printf '%s\\t%s\\n' ${m} "$(command -v ${n} 2>/dev/null)"`,`type -p ${n}`];let i="";for(const e of[!1,!0]){for(const r of o){const c=W(r,{interactive:e}),l=x(c)||String(c||"").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.startsWith("/")).pop()||"";if(l.startsWith("/")&&u(l)){i=l;break}}if(i)break}return T.set(n,{bin:i,at:Date.now()}),i}function yn(){return process.env.CHATPANEL_CLAUDE_PATH?v(process.env.CHATPANEL_CLAUDE_PATH):v("claude")}function v(n){if(!n)return null;if(n.includes("/")||n.includes("\\")||/\.[a-z0-9]+$/i.test(n)){if(!u(n))return null;const i=s.extname(n).toLowerCase();return!g()&&/^\.(c?js|mjs)$/.test(i)?{kind:"script",script:n}:process.platform==="win32"&&(i===".cmd"||i===".bat")?{kind:"cmd",bin:n}:process.platform==="win32"&&i===""&&!Q(n)?null:{kind:"native",bin:n}}if(process.platform==="win32"){const i=bn(n);return i||(/^[\w.-]+$/.test(n)&&Pn(n)?{kind:"wsl",command:n}:null)}const o=Z(n);return o?{kind:"native",bin:o}:null}const cn="HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",ln="HKCU\\Environment",an=4e3;let V=0;function un(n,t="Path"){const o=String(t).toLowerCase();for(const i of String(n||"").split(/\r?\n/)){const e=/^\s*(\S+)\s+REG_(?:EXPAND_)?SZ\s+(.*?)\s*$/.exec(i);if(e&&e[1].toLowerCase()===o)return e[2]}return""}function B(n,t=process.env){const o=new Map(Object.keys(t||{}).map(i=>[i.toLowerCase(),t[i]]));return String(n||"").replace(/%([^%]+)%/g,(i,e)=>{const r=o.get(String(e).toLowerCase());return r==null?i:String(r)})}function pn(n,t){try{const o=s.win32.join(process.env.SystemRoot||"C:\\Windows","System32","reg.exe"),i=b(u(o)?o:"reg",["query",n,"/v",t],{encoding:"utf8",timeout:3e3,windowsHide:!0});return i.status===0?un(i.stdout,t):""}catch{return""}}function dn({query:n=pn,env:t=process.env}={}){const o=B(n(cn,"Path"),t),i=B(n(ln,"Path"),t);return j([...d(o,"win32"),...d(i,"win32")])}function fn({run:n=jn}={}){const t=n(`[Console]::Out.Write("${m}\`t" + $env:PATH + "\`n")`);return d(x(t),"win32")}function jn(n){for(const t of["pwsh.exe","powershell.exe"])try{const o=b(t,["-NoLogo","-NonInteractive","-ExecutionPolicy","Bypass","-Command",n],{encoding:"utf8",timeout:$,stdio:["ignore","pipe","ignore"],windowsHide:!0}),i=M(o.stdout||"");if(i)return i}catch{}return""}function F({force:n=!1,now:t=Date.now(),registry:o=dn,profile:i=fn,env:e=process.env,home:r=f.homedir()}={}){if(process.platform!=="win32"&&!n||!n&&t-V<an)return!1;V=t;const c=d(e.PATH||"","win32"),l=j([...c,...o({env:e}),...H(r,"win32",e)]);D.some(p=>!l.some(A=>u(s.win32.join(A,`${p}.cmd`))||u(s.win32.join(A,`${p}.exe`))))&&l.push(...i());const a=L(j(l),"win32");return a.length===c.length?!1:(e.PATH=a.join(I("win32")),!0)}function bn(n){return K(n)||(F()?K(n):null)}function K(n){const t=w("win32");for(const o of q(n,f.homedir(),"win32",process.env)){if(!u(o))continue;const i=t.dirname(o),e=t.extname(o).toLowerCase(),r=n==="claude"&&An(i)||hn(i,n)||(/^\.(c?js|mjs)$/.test(e)?o:null);if(r){if(!g())return{kind:"script",script:r};const c=wn(i);if(c)return{kind:"script",script:r,runtime:c}}if(e===".exe")return{kind:"native",bin:o};if(e===".cmd"||e===".bat")return{kind:"cmd",bin:o};if(e===""&&Q(o))return{kind:"native",bin:o}}return null}function wn(n,{env:t=process.env,exists:o=u}={}){const i=s.win32,e=j([n,...d(t.PATH||"","win32"),...t.NVM_SYMLINK?[t.NVM_SYMLINK]:[],i.join(t.ProgramFiles||"C:\\Program Files","nodejs")]);for(const r of e){const c=i.join(r,"node.exe");if(o(c))return c}return null}function An(n){const t=[["node_modules","@anthropic-ai","claude-code","cli.js"],["..","node_modules","@anthropic-ai","claude-code","cli.js"],["..","lib","node_modules","@anthropic-ai","claude-code","cli.js"]];for(const o of t){const i=s.join(n,...o);if(u(i))return i}return null}function hn(n,t){for(const o of[`${t}.cmd`,t,`${t}.ps1`]){let i;try{i=_(s.join(n,o),"utf8")}catch{continue}const e=i.match(/(?:%~?dp0%|\$basedir|\$\{basedir\})[\\/]+([^"'\s]+\.[cm]?js)/i);if(e){const r=s.join(n,e[1].replace(/[\\/]+/g,s.sep));if(u(r))return r}}return null}const Y=new Map,mn=15e3;function Pn(n){const t=Y.get(n);if(t&&(t.ok||Date.now()-t.at<mn))return t.ok;let o=!1;try{const i=b("wsl.exe",["-e","bash","-lic",`command -v ${n}`],{encoding:"utf8",timeout:8e3,windowsHide:!0});o=i.status===0&&/\S/.test(M(i.stdout||""))}catch{o=!1}return Y.set(n,{ok:o,at:Date.now()}),o}function Dn(n,t,o,i=null){const e=i&&typeof i=="object"&&Object.keys(i).length?{...process.env,...i}:process.env;if(n.kind==="wsl"){const c=[];if(o){const a=_n(o);a&&c.push("--cd",a)}return["wsl.exe",[...c,"-e","bash","-lic",`exec ${n.command} "$@"`,"chatpanel",...t],{stdio:["pipe","pipe","pipe"],env:e,windowsHide:!0,...O}]}const r={cwd:o||f.homedir(),stdio:["pipe","pipe","pipe"],env:e,windowsHide:!0,...O};return n.kind==="script"?[n.runtime||process.execPath,[n.script,...t],r]:n.kind==="cmd"?["cmd.exe",["/d","/s","/c",n.bin,...t],r]:[n.bin,t,r]}function _n(n){try{const t=b("wsl.exe",["-e","wslpath","-a",n],{encoding:"utf8",timeout:5e3,windowsHide:!0}),o=M(t.stdout||"").trim();return o.startsWith("/")?o:null}catch{return null}}function M(n){return n.replace(/^/,"").trim()}function gn(n=f.homedir(),t=process.env){const o=s.join(t.NVM_DIR||s.join(n,".nvm"),"versions","node");let i;try{i=h(o).filter(r=>/^v\d+\./.test(r))}catch{return null}if(!i.length)return null;const e=(r,c)=>{const l=r.slice(1).split(".").map(Number),a=c.slice(1).split(".").map(Number);for(let p=0;p<3;p+=1)if((l[p]||0)!==(a[p]||0))return(a[p]||0)-(l[p]||0);return 0};try{const r=_(s.join(t.NVM_DIR||s.join(n,".nvm"),"alias","default"),"utf8").trim(),c=r.startsWith("v")?r:`v${r}`;if(i.includes(c))return s.join(o,c,"bin")}catch{}return s.join(o,i.sort(e)[0],"bin")}function xn(n,t=process.env){return[s.join(t.MISE_DATA_DIR||s.join(n,".local","share","mise"),"shims"),s.join(n,".local","share","rtx","shims"),s.join(t.ASDF_DATA_DIR||s.join(n,".asdf"),"shims"),s.join(t.PYENV_ROOT||s.join(n,".pyenv"),"shims"),s.join(t.RBENV_ROOT||s.join(n,".rbenv"),"shims"),s.join(t.NODENV_ROOT||s.join(n,".nodenv"),"shims"),s.join(t.PROTO_HOME||s.join(n,".proto"),"shims"),s.join(t.PROTO_HOME||s.join(n,".proto"),"bin"),s.join(t.VOLTA_HOME||s.join(n,".volta"),"bin")]}function En(n,t=process.env){const o=[],i=(e,r)=>{try{for(const c of h(e))o.push(s.join(e,c,r))}catch{}};return i(s.join(t.NVM_DIR||s.join(n,".nvm"),"versions","node"),"bin"),i(s.join(n,".local","share","fnm","node-versions"),s.join("installation","bin")),i(s.join(n,"Library","Application Support","fnm","node-versions"),s.join("installation","bin")),i(s.join(t.MISE_DATA_DIR||s.join(n,".local","share","mise"),"installs","node"),"bin"),o}function w(n){return n==="win32"?s.win32:s}function I(n){return n==="win32"?";":s.delimiter}function d(n,t){return(n||"").split(I(t)).filter(Boolean)}function j(n){return[...new Set(n.filter(Boolean))]}const G={win32:3e4,other:65536};function L(n,t=process.platform){const o=t==="win32"?G.win32:G.other,i=I(t),e=[];let r=0;for(const c of n){const l=c.length+(e.length?i.length:0);if(r+l>o)break;e.push(c),r+=l}return e}function H(n,t=process.platform,o=process.env){const i=w(t);if(t==="win32"){const e=o.APPDATA||i.join(n,"AppData","Roaming"),r=o.LOCALAPPDATA||i.join(n,"AppData","Local"),c=o.ProgramFiles||"C:\\Program Files",l=o["ProgramFiles(x86)"]||"C:\\Program Files (x86)",a=o.ProgramData||"C:\\ProgramData";return[i.join(n,".local","bin"),i.join(n,".codex","bin"),i.join(n,".claude","bin"),i.join(n,".claude","local"),i.join(n,".claude","local","bin"),i.join(e,"npm"),...o.NVM_SYMLINK?[o.NVM_SYMLINK]:[],i.join(c,"nodejs"),...Cn(e,r),i.join(r,"pnpm"),i.join(r,"Yarn","bin"),i.join(r,"Volta","bin"),i.join(n,".yarn","bin"),i.join(n,".bun","bin"),i.join(n,".deno","bin"),i.join(o.SCOOP||i.join(n,"scoop"),"shims"),i.join(a,"chocolatey","bin"),i.join(r,"Microsoft","WindowsApps"),i.join(r,"Microsoft","WinGet","Links"),i.join(o.MISE_DATA_DIR||i.join(r,"mise"),"shims"),i.join(o.PROTO_HOME||i.join(n,".proto"),"shims"),i.join(o.PROTO_HOME||i.join(n,".proto"),"bin"),i.join(r,"Programs","Claude Code"),i.join(r,"Anthropic","Claude Code"),i.join(c,"Claude Code"),i.join(c,"Anthropic","Claude Code"),i.join(l,"Claude Code"),i.join(l,"Anthropic","Claude Code")]}return[s.join(n,".local","bin"),s.join(n,".opencode","bin"),s.join(n,".codex","bin"),s.join(n,".claude","bin"),s.join(n,".claude","local"),s.join(n,".claude","local","bin"),o.PNPM_HOME||s.join(n,"Library","pnpm"),s.join(n,".local","share","pnpm"),s.join(n,".nix-profile","bin"),"/nix/var/nix/profiles/default/bin",s.join(n,".guix-profile","bin"),"/home/linuxbrew/.linuxbrew/bin","/snap/bin",...xn(n,o)]}function Cn(n,t){const o=s.win32,i=[];for(const e of[o.join(t,"fnm"),o.join(n,"fnm")]){let r=[];try{r=h(o.join(e,"node-versions")).filter(c=>/^v?\d+\.\d+\.\d+/.test(c)).sort((c,l)=>l.localeCompare(c,void 0,{numeric:!0}))}catch{}for(const c of r)i.push(o.join(e,"node-versions",c,"installation"))}return i}function U(n,t=process.platform){const o=w(t),i=o.join(n,".local","share","claude","versions");let e=[];try{e=h(i).filter(r=>/^\d+\.\d+\.\d+/.test(r)).sort((r,c)=>c.localeCompare(r,void 0,{numeric:!0}))}catch{}return e.map(r=>o.join(i,r))}function X(n,t){return t!=="win32"?[n]:/\.(cmd|exe|bat|ps1)$/i.test(n)?[n]:[`${n}.exe`,`${n}.cmd`,`${n}.bat`,n,`${n}.ps1`]}function Q(n,t=_){try{const o=t(n).subarray(0,2);return o.length===2&&o[0]===77&&o[1]===90}catch{return!1}}function Sn(n,t=f.homedir(),o=process.platform,i=process.env){const e=w(o),r=e.join(t,".local","bin",n),c=o==="win32"?i.LOCALAPPDATA||e.join(t,"AppData","Local"):null,l=o==="win32"?i.ProgramFiles||"C:\\Program Files":null,a=o==="win32"?i["ProgramFiles(x86)"]||"C:\\Program Files (x86)":null,p={claude:[r,e.join(t,".claude","bin","claude"),e.join(t,".claude","local","claude"),e.join(t,".claude","local","bin","claude"),...o==="win32"?[e.join(c,"Microsoft","WindowsApps","claude.exe"),e.join(c,"Programs","Claude Code","claude.exe"),e.join(c,"Anthropic","Claude Code","claude.exe"),e.join(l,"Claude Code","claude.exe"),e.join(l,"Anthropic","Claude Code","claude.exe"),e.join(a,"Claude Code","claude.exe"),e.join(a,"Anthropic","Claude Code","claude.exe"),...U(t,o)]:U(t,o)],codex:[r,e.join(t,".codex","bin","codex")],agy:[r,"/Applications/Antigravity.app/Contents/MacOS/agy","/Applications/Antigravity IDE.app/Contents/MacOS/agy"],pi:[r],opencode:[e.join(t,".opencode","bin","opencode"),r],"kiro-cli":[r,"/Applications/Kiro CLI.app/Contents/MacOS/kiro-cli"]};return j((p[n]||[r]).flatMap(A=>X(A,o)))}function q(n,t=f.homedir(),o=process.platform,i=process.env){const e=w(o),r=j([...d(i.PATH||"",o),...H(t,o,i)]).flatMap(c=>X(e.join(c,n),o));return j([...r,...Sn(n,t,o,i)])}const z=["DEEPSEEK_API_KEY","DSH_HOME","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","GEMINI_API_KEY","GOOGLE_API_KEY","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"];function Rn(){if(y||(y=!0,process.platform==="win32"))return;const n=z.filter(t=>!process.env[t]);if(n.length)try{const t=E(),o=`${n.map(e=>`[ -n "\${${e}:-}" ] && printf '%s\\t%s\\n' ${e} "$${e}"`).join("; ")}; true`,i=b(t,["-l","-i","-c",o],{encoding:"utf8",timeout:6e3,env:{...process.env,TERM:"dumb"}});for(const e of String(i.stdout||"").split(`
|
|
2
|
+
`)){const r=e.indexOf(" ");if(r<=0)continue;const c=e.slice(0,r).trim(),l=e.slice(r+1);z.includes(c)&&!process.env[c]&&l&&(process.env[c]=l)}}catch{}}function $n(){if(N)return;N=!0;const n=f.homedir();if(process.platform==="win32"){F({force:!0,home:n});return}const t=gn(n),o=[...t?[t]:[],"/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",s.join(n,".local","bin"),s.join(n,"bin"),s.join(n,".npm-global","bin"),s.join(n,".cargo","bin"),s.join(n,".deno","bin"),s.join(n,".bun","bin"),...H(n),...En(n)];let i="";try{const c=E(),l=b(c,["-l","-c",'command -p echo "$PATH"'],{encoding:"utf8",timeout:4e3});l.status===0&&(i=(l.stdout||"").trim())}catch{}const e=new Set,r=[...t?[t]:[],...i?i.split(":"):[],...process.env.PATH?process.env.PATH.split(s.delimiter):[],...o].filter(c=>c&&!e.has(c)&&(e.add(c),!0));process.env.PATH=L(r).join(s.delimiter),D.some(c=>!J(c))&&k({force:!0})}export{D as AGENT_CLIS,Hn as agentAvailable,Sn as agentCandidateBins,H as agentInstallDirs,Dn as buildSpawnSpec,L as capPathList,q as commandCandidateFiles,Rn as enrichAgentEnv,$n as enrichPath,B as expandWindowsEnv,Z as findAgentBin,g as isCompiledBinary,Q as isWindowsExecutable,wn as nodeRuntimeWindows,gn as nvmCurrentBin,tn as parseEnvPath,un as parseRegValue,x as parseSentinel,fn as profilePathWindows,k as refreshShellPath,F as refreshWindowsPath,dn as registryPathWindows,Nn as resetShellProbes,yn as resolveClaude,v as resolveCommand,On as selfMcpStdio,on as shellPath,_n as toWslPath};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const p=Object.freeze({npm:"https://registry.npmjs.org",pypi:"https://pypi.org/simple",models:"https://huggingface.co",github:"https://api.github.com"}),a=Object.freeze(Object.keys(p));function h(r){const t=String(r??"").trim();if(!t)return"";let n;try{n=new URL(t)}catch{throw new Error(`registry: ${JSON.stringify(t)} is not a URL`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error(`registry: ${n.protocol} is not http(s)`);if(n.username||n.password)throw new Error("registry: put credentials in your package manager's own config, not here");return`${n.origin}${n.pathname.replace(/\/+$/,"")}`}function u(r={}){const t={};for(const n of a){if(!(n in(r||{})))continue;const e=h(r[n]);e&&(t[n]=e)}return t}function f(r,t={}){if(!a.includes(r))throw new Error(`registry: unknown kind ${JSON.stringify(r)}`);return t&&t[r]||p[r]}function m(r={}){return a.some(t=>r?.[t]&&r[t]!==p[t])}function y(r,t,n={}){const e=f(r,n),i=p[r];if(e===i)return String(t);let o;try{o=new URL(String(t))}catch{return String(t)}const s=new URL(i);if(o.origin!==s.origin)return String(t);const c=o.pathname.startsWith(s.pathname)?o.pathname.slice(s.pathname.length):o.pathname;return`${e}${c.startsWith("/")?"":"/"}${c}${o.search}`}function l(r={},t={}){const n={...t},e=(c,g)=>{g&&(n[c]=g)},i=r?.npm,o=r?.pypi,s=r?.models;return e("npm_config_registry",i),e("NPM_CONFIG_REGISTRY",i),e("UV_INDEX_URL",o),e("PIP_INDEX_URL",o),e("HF_ENDPOINT",s),n}export{p as DEFAULT_REGISTRIES,a as REGISTRY_KINDS,m as hasOverrides,y as mirrorUrl,u as normalizeRegistries,l as registryEnv,f as registryFor,h as validRegistry};
|
package/src/mcp-local.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{spawn as
|
|
1
|
+
import{spawn as B}from"node:child_process";import{registryEnv as G,normalizeRegistries as H}from"./events/registries.js";function F(n){try{return H({npm:n.CHATPANEL_REGISTRY_NPM,pypi:n.CHATPANEL_REGISTRY_PYPI,models:n.CHATPANEL_REGISTRY_MODELS,github:n.CHATPANEL_REGISTRY_GITHUB})}catch{return{}}}import Y from"node:os";import k from"node:path";import{resolveCommand as U,buildSpawnSpec as J}from"./env.js";import{sandbox as q,refusalsFor as K,track as V}from"./sandbox.js";import{missingCommandMessage as W}from"./events/mcp-errors.js";import{parseSignInPrompt as Q,signInError as x,signInFromError as X}from"./events/mcp-signin.js";import{pickProbeTool as Z}from"./events/mcp-launcher.js";import{envLikeArgs as nn}from"./events/mcp-config-import.js";const d=new Map,b=new Map,C=10*6e4,en=6e4,tn=5*6e4,$=Object.freeze({protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"ChatPanel",version:"1.0"}}),rn=150,on=8*6e4,sn=16*6e4,S=4e3;function L(n){const e=Y.homedir(),t={};for(const[i,s]of Object.entries(n||{})){const o=String(s);t[i]=o==="~"?e:o.startsWith("~/")?k.join(e,o.slice(2)):o}return t}const A=n=>n.key||`${n.command}\0${(Array.isArray(n.args)?n.args.join(" "):n.args)||""}`,O=n=>JSON.stringify([n.command,Array.isArray(n.args)?n.args:String(n.args||""),n.env||{},n.cwd||null,n.sandbox||null]);function T(n,e){clearTimeout(n.idleTimer);for(const{reject:t,timer:i}of n.pending.values())clearTimeout(i),t(e);n.pending.clear(),d.get(n.key)===n&&d.delete(n.key);try{n.child.kill()}catch{}}function f(n){clearTimeout(n.idleTimer);const e=n.pendingSignIn?Math.max(C,sn):C;n.idleTimer=setTimeout(()=>{try{n.child.kill()}catch{}d.delete(n.key)},e)}function an(n){const e=String(n||"").replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\r/g,`
|
|
2
2
|
`).split(`
|
|
3
3
|
`).map(t=>t.trimEnd()).filter(Boolean).join(`
|
|
4
|
-
`).trim();return e?e.length>S?`…${e.slice(-S)}`:e:""}function
|
|
5
|
-
`))>=0;){const
|
|
6
|
-
`);return e.id==null?(t(),Promise.resolve(null)):new Promise((
|
|
4
|
+
`).trim();return e?e.length>S?`…${e.slice(-S)}`:e:""}function y(n,e){const t=an(e?.stderr);return t?`${n}: ${t}`:n}const M=new Map,j=new Set;function Mn(){const n=[];for(const e of d.values())e.child.exitCode!=null||e.child.killed||n.push({id:e.key,command:k.basename(String(e.command||"")),pid:e.child.pid??null,sandbox:e.sandbox,commandId:e.commandId,since:e.startedAt,refused:K(e.commandId)});return n}async function z(n){const e=A(n),t=O(n);if(M.has(e)){const o=await M.get(e);if(o.sig===t)return o}const i=d.get(e);if(i&&i.child.exitCode==null&&!i.child.killed){if(i.sig===t)return f(i),i;T(i,new Error("local MCP server restarted: its configuration changed"))}const s=ln(n,e,t).finally(()=>M.delete(e));return M.set(e,s),s}async function ln(n,e,t=O(n)){const i=U(n.command);if(!i)throw new Error(W(n.command,{platform:process.platform}));const s=Array.isArray(n.args)?n.args:String(n.args||"").split(/\s+/).filter(Boolean),o={};for(const a of nn(s)){const l=a.indexOf("=");o[a.slice(0,l).trim()]=a.slice(l+1).trim()}const[p,h,u]=J(i,s,n.cwd||null);u.env={...u.env||process.env,...G(F(u.env||process.env)),...L(o),...L(n.env||{})},Object.keys(o).length&&console.error(`[bridge] local MCP "${n.command}": ${Object.keys(o).join(", ")} looked like environment variables in Arguments, so they were applied as env too`),u.stdio=["pipe","pipe","pipe"];const c=await q().wrap(p,h,u,{engine:"mcp",cwd:n.cwd||null,commandId:`mcp:${String(e).slice(0,48)}`,...n.sandbox?{grant:n.sandbox}:{}}),[N,R,D]=[c.bin,c.argv,c.opts];c.record.layer==="none"&&!j.has(c.record.reason)&&(j.add(c.record.reason),console.error(`[bridge] local MCP "${n.command}" runs outside a sandbox — ${c.record.reason}`));const g=V(B(N,R,D),c,{kind:"mcp",label:e}),r={key:e,sig:t,child:g,command:n.command,sandbox:c.record,commandId:c.commandId,startedAt:Date.now(),pending:new Map,buf:"",stderr:"",idleTimer:null,initialized:!1,handshake:null,pendingSignIn:null,pendingSignInAt:0,signInIds:null},v=a=>T(r,a);return g.stdout.setEncoding("utf8"),g.stdout.on("data",a=>{r.buf+=a;let l;for(;(l=r.buf.indexOf(`
|
|
5
|
+
`))>=0;){const I=r.buf.slice(0,l).trim();if(r.buf=r.buf.slice(l+1),I[0]!=="{"&&I[0]!=="[")continue;let w;try{w=JSON.parse(I)}catch{continue}for(const m of Array.isArray(w)?w:[w]){m&&m.id!=null&&r.signInIds?.has(m.id)&&(r.signInIds.delete(m.id),r.signInIds.size||(r.pendingSignIn=null,r.signedInAt=Date.now(),f(r)));const P=m&&m.id!=null?r.pending.get(m.id):null;P&&(clearTimeout(P.timer),r.pending.delete(m.id),P.resolve(m))}}}),g.stderr.setEncoding("utf8"),g.stderr.on("data",a=>{r.stderr+=a,r.stderr.length>S*2&&(r.stderr=r.stderr.slice(-S*2)),r.pending.size&&(r.promptBuf=((r.promptBuf||"")+a).slice(-2e3),clearTimeout(r.promptTimer),r.promptTimer=setTimeout(()=>{const l=Q(r.promptBuf);l&&(r.promptBuf="",dn(r,l))},rn))}),g.on("error",a=>v(new Error(y(`local MCP "${n.command}" failed to start: ${a.message}`,r)))),g.on("close",(a,l)=>{const I=l?`exited with signal ${l}`:a==null?"exited":`exited with code ${a}`;v(new Error(y(`local MCP "${n.command}" ${I}`,r)))}),d.set(e,r),f(r),r}function dn(n,e){if(f(n),e.code&&(n.pendingSignIn=e,n.pendingSignInAt=Date.now(),n.signInIds=new Set(n.pending.keys()),f(n)),e.browser){for(const i of n.pending.values())clearTimeout(i.timer),i.timer=setTimeout(()=>{i.reject(new Error(y("local MCP call timed out waiting for the sign-in",n)))},tn);return}const t=x(e);for(const[i,s]of n.pending)clearTimeout(s.timer),n.pending.delete(i),s.resolve({jsonrpc:"2.0",id:i,error:t})}function _(n,e){const t=()=>n.child.stdin.write(JSON.stringify(e)+`
|
|
6
|
+
`);return e.id==null?(t(),Promise.resolve(null)):new Promise((i,s)=>{const o=setTimeout(()=>{n.pending.delete(e.id),s(new Error(y("local MCP call timed out",n)))},en);n.pending.set(e.id,{resolve:i,reject:s,timer:o}),t()})}function cn(n,e){return n.initialized?Promise.resolve():(n.handshake||(n.handshake=(async()=>{const t=await _(n,{jsonrpc:"2.0",id:`cp-init-${Date.now()}`,method:"initialize",params:e});if(t?.error)throw new Error(`local MCP re-initialize failed: ${t.error.message||t.error.code}`);await _(n,{jsonrpc:"2.0",method:"notifications/initialized"}),n.initialized=!0})().finally(()=>{n.handshake=null})),n.handshake)}async function En(n,{initializeParams:e=$}={}){const t=await z(n);if(t.pendingSignIn)return{state:"prompt",signIn:t.pendingSignIn,since:t.pendingSignInAt};await E(n,{jsonrpc:"2.0",id:`cp-si-init-${Date.now()}`,method:"initialize",params:e}).catch(()=>{});const s=(await E(n,{jsonrpc:"2.0",id:`cp-si-list-${Date.now()}`,method:"tools/list",params:{}}).catch(()=>null))?.result?.tools||[],o=Z(s);if(!o)return{state:"unsupported",error:"This server declares no read-only tool that takes no arguments, so there is nothing safe to call to make it sign in."};const p=await E(n,{jsonrpc:"2.0",id:`cp-si-${Date.now()}`,method:"tools/call",params:{name:o,arguments:{}}}).catch(u=>({error:{message:String(u?.message||u)}})),h=X(p?.error);return h?{state:"prompt",signIn:h,since:d.get(A(n))?.pendingSignInAt||Date.now(),probe:o}:p?.error?{state:"failed",error:p.error.message||"the server refused",probe:o}:{state:"signed-in",probe:o}}function Pn(n){const e=d.get(A(n));return!e||e.child.exitCode!=null?{state:"gone"}:e.pendingSignIn?{state:"prompt",signIn:e.pendingSignIn,since:e.pendingSignInAt}:{state:e.signedInAt?"signed-in":"idle"}}function mn(n){const e=d.get(n);return e?(T(e,new Error("local MCP server stopped")),!0):!1}function bn(){let n=0;for(const e of[...d.keys()])mn(e)&&(n+=1);return n}function An(n){return d.get(n)||null}function _n(n){return b.has(n)}async function E(n,e){if(!n?.command)throw new Error("no command for local MCP server");const t=await z(n);if(f(t),e.method==="initialize")b.set(t.key,e.params||{}),t.initialized=!0;else if(e.method!=="notifications/initialized"){if(e.id!=null&&t.pendingSignIn&&Date.now()-t.pendingSignInAt<on)return{jsonrpc:"2.0",id:e.id,error:x(t.pendingSignIn)};if(e.id!=null&&t.pendingSignIn)return T(t,new Error("local MCP sign-in expired: starting a new one")),E(n,e);t.initialized||await cn(t,b.get(t.key)||$)}return _(t,e)}export{An as _procForTest,E as callLocalMcp,_n as hasInitParams,Mn as localMcpStatus,En as signInLocalMcp,Pn as signInStatusLocalMcp,bn as stopAllLocalMcp,mn as stopLocalMcp};
|
package/src/server.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createServer as ye}from"node:http";import P from"node:os";import{randomBytes as be,randomInt as Se,timingSafeEqual as ke}from"node:crypto";import{mkdirSync as Te,writeFileSync as ve,readFileSync as K,existsSync as Ce}from"node:fs";import{join as H}from"node:path";import*as Ee from"./engines/claude.js";import*as Oe from"./engines/codex.js";import*as xe from"./engines/antigravity.js";import{pi as Ae,opencode as Pe,kiro as $e,copilot as Ie,deepseek as Ne,hermes as Re}from"./engines/cli-agents.js";import{connectorsFor as _e}from"./connectors.js";import*as He from"./engines/custom.js";import{installService as Me,uninstallService as Be,serviceStatus as Ge,restartService as V}from"./service.js";import{skillIndex as W,listRecords as De,readRecord as Ue,readPackageFile as We,skillsHealth as Le,quarantinedSkills as je}from"./skills.js";import{capabilityToolSpecs as Je,runCapabilityTool as Fe}from"./mcp-capabilities.js";import{createSession as Xe,deleteSession as Y,getSession as Q,activeSession as ze,relayToolCall as Ke}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ve,isDefaultWorkdir as Ye,resolveWorkdir as Qe,writeScopeNote as Ze}from"./workdir.js";import{sandbox as Z,runSandboxCli as qe,withGrant as q,acceptRefusalReport as et,liveProcesses as tt}from"./sandbox.js";import{gitState as nt,gitDelta as ot}from"./scm.js";import{listConnections as rt,putConnection as at,removeConnection as it,runEnvFor as st,testConnection as ct,secretBackend as ee}from"./connections.js";import{worktreeFor as te,listWorktrees as lt,removeWorktree as dt,withHook as ut,WORKTREE_ROOT as ne}from"./worktree.js";import{AGENT_CLIS as pt,enrichPath as ht,enrichAgentEnv as mt,findAgentBin as oe,resolveCommand as ft}from"./env.js";import"./sanitize.js";import{checkForUpdate as gt,selfUpdate as re,isEmbedded as wt}from"./update.js";import{callLocalMcp as yt,localMcpStatus as bt,signInLocalMcp as St,signInStatusLocalMcp as kt}from"./mcp-local.js";import{assertPublicHttpUrl as ae,assertPublicWebUrl as ie}from"./ssrf.js";import{startRun as se,endRun as L,cancelRun as Tt,cancelAll as vt}from"./runs.js";import{closeWarmPools as Ct,warmStatus as Et}from"./warm.js";import{CompatError as $,anthropicError as j,anthropicStream as Ot,chatCompletionStream as xt,completionStream as At,createAnthropicMessage as Pt,createChatCompletion as $t,createCompletion as It,createResponse as Nt,openAIError as b,parseAnthropicMessage as Rt,parseChatCompletion as _t,parseCompletion as Ht,parseResponse as Mt,responseStream as Bt}from"./api-compat.js";import{callerTrust as Gt,isPaired as I,parseExtensionIds as Dt,capRunOptions as Ut,engineHonoursReach as Wt,createPairingStore as Lt,formatPairingCode as jt}from"./pii/trust.js";const w="0.20.2",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Ee,label:"Claude Code"},codex:{engine:Oe,label:"Codex"},antigravity:{engine:xe,label:"Antigravity",tools:!1},pi:{engine:Ae,label:"Pi"},opencode:{engine:Pe,label:"OpenCode"},hermes:{engine:Re,label:"Hermes"},kiro:{engine:$e,label:"Kiro"},copilot:{engine:Ie,label:"GitHub Copilot"},deepseek:{engine:Ne,label:"DeepSeek Harness"},custom:{engine:He,label:"Custom",hidden:!0}};function ce(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 Jt=Dt(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Gt({origin:n.headers.origin||"",hasToken:pe(n),extensionIds:Jt})),n.chatpanelTrust}function Ft(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 Xt(n,e){const t=n.headers.origin||"",r=ce(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 J=new Set(["127.0.0.1","localhost","::1"]);function zt(n){if(!J.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(t)}const R=H(P.homedir(),".chatpanel","bridge-token");let S="";function Kt(){try{Ce(R)&&(S=K(R,"utf8").trim()),S||(S=be(32).toString("hex"),Te(H(P.homedir(),".chatpanel"),{recursive:!0}),ve(R,S,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const le=Lt({random:()=>Se(0,1e6)/1e6});function Vt(n){if(!S)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=le.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Yt(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=le.claim(t?.code);return r.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${N(n)} caller`),i(e,403,{error:r.reason}))}function Qt(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:w})}let M=null;async function de(){if(M)return M;const{createChannelService:n}=await import("./channels/service.js");return M=n({home:H(P.homedir(),".chatpanel"),dataDir:H(P.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),M}async function ue(n,e,t){try{const r=await de(),o=n.method==="POST"?await f(n):{};if(t==="status")return i(e,200,await r.status());if(t==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await r.pair()):t==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?i(e,200,await r.update(o)):t==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function pe(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 r=Buffer.from(t),o=Buffer.from(S);return r.length===o.length&&ke(r,o)}const Zt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),qt=new Set(["/debug"]),en=n=>qt.has(n);function tn(n,e){if(!zt(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ce(t))return"forbidden origin";const r=n.method==="POST"&&Zt.has(e)||n.method==="GET"&&en(e);return r&&!(Ft(t)||pe(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I(N(n))&&!on.has(e)?nn:null}const nn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",on=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 r=N(n),o=Ut(t,r);if(!Wt(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=o.reach,s=I(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:o,note:s}}function i(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 rn(n){const e=await Promise.all(Object.entries(C).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:d,tools:c}])=>{const l=await s.available().catch(g=>({ok:!1,reason:String(g?.message||g)})),p=await _e(a).catch(()=>[]);return{id:a,label:d,available:l.ok,reason:l.reason,connectors:p,...c===!1?{tools:!1}:{}}})),t=wt()?{current:w,updateAvailable:!1,embedded:"gateway"}:await gt(w).catch(()=>({current:w,updateAvailable:!1})),r=await Le().catch(()=>null),o=await Z().status().catch(a=>({enabled:!1,reason:a.message}));i(n,200,{ok:!0,version:w,agents:e,update:t,workspace:Ve,sandbox:o,localMcp:bt(),processes:tt(),worktrees:ne,secretBackend:ee(),warm:Et(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function an(n,e,t){const{index:r,problems:o}=await W({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:De(r),problems:o})}async function sn(n,e,t){i(n,200,{ok:!0,quarantined:await je(e,t)})}async function cn(n,e,t,r){const{index:o}=await W({extraDirs:t,workdir:r}),a=Ue(o,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function ln(n,e,t,r,o){const{index:a}=await W({extraDirs:r,workdir:o}),s=await We(a,e,t);if(s.error)return i(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(n,200,{ok:!0,...s})}async function dn(){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 he(n,e=""){const t=await dn();if(e){const r=t.find(o=>o.id===e);return r?i(n,200,r):i(n,404,b(new $(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function un(n){try{const e=await re(w);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function pn(n,e){let t;try{t=await f(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=F(n,t.agent,t.options||{});if(o.error)return i(e,403,{error:o.error});t.options=o.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
|
|
2
|
+
import{createServer as ye}from"node:http";import A from"node:os";import{randomBytes as be,randomInt as Se,timingSafeEqual as ke}from"node:crypto";import{mkdirSync as Te,writeFileSync as ve,readFileSync as K,existsSync as Ce}from"node:fs";import{join as H}from"node:path";import*as Ee from"./engines/claude.js";import*as Oe from"./engines/codex.js";import*as Ae from"./engines/antigravity.js";import{pi as xe,opencode as Pe,kiro as $e,copilot as Ie,deepseek as Ne,hermes as Re}from"./engines/cli-agents.js";import{connectorsFor as _e}from"./connectors.js";import*as He from"./engines/custom.js";import{installService as Me,uninstallService as Be,serviceStatus as De,restartService as V}from"./service.js";import{skillIndex as W,listRecords as Ge,readRecord as Ue,readPackageFile as We,skillsHealth as Le,quarantinedSkills as je}from"./skills.js";import{capabilityToolSpecs as Je,runCapabilityTool as Fe}from"./mcp-capabilities.js";import{createSession as Xe,deleteSession as Y,getSession as Q,activeSession as ze,relayToolCall as Ke}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ve,isDefaultWorkdir as Ye,resolveWorkdir as Qe,writeScopeNote as Ze}from"./workdir.js";import{sandbox as Z,runSandboxCli as qe,withGrant as q,acceptRefusalReport as et,liveProcesses as tt}from"./sandbox.js";import{gitState as nt,gitDelta as ot}from"./scm.js";import{listConnections as rt,putConnection as at,removeConnection as it,runEnvFor as st,testConnection as ct,secretBackend as ee}from"./connections.js";import{worktreeFor as te,listWorktrees as lt,removeWorktree as dt,withHook as ut,WORKTREE_ROOT as ne}from"./worktree.js";import{AGENT_CLIS as pt,agentAvailable as ht,agentInstallDirs as mt,enrichPath as ft,enrichAgentEnv as gt,findAgentBin as wt,resolveCommand as oe}from"./env.js";import"./sanitize.js";import{checkForUpdate as yt,selfUpdate as re,isEmbedded as bt}from"./update.js";import{callLocalMcp as St,localMcpStatus as kt,signInLocalMcp as Tt,signInStatusLocalMcp as vt}from"./mcp-local.js";import{assertPublicHttpUrl as ae,assertPublicWebUrl as ie}from"./ssrf.js";import{startRun as se,endRun as L,cancelRun as Ct,cancelAll as Et}from"./runs.js";import{closeWarmPools as Ot,warmStatus as At}from"./warm.js";import{CompatError as $,anthropicError as j,anthropicStream as xt,chatCompletionStream as Pt,completionStream as $t,createAnthropicMessage as It,createChatCompletion as Nt,createCompletion as Rt,createResponse as _t,openAIError as b,parseAnthropicMessage as Ht,parseChatCompletion as Mt,parseCompletion as Bt,parseResponse as Dt,responseStream as Gt}from"./api-compat.js";import{callerTrust as Ut,isPaired as I,parseExtensionIds as Wt,capRunOptions as Lt,engineHonoursReach as jt,createPairingStore as Jt,formatPairingCode as Ft}from"./pii/trust.js";const w="0.24.1",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Ee,label:"Claude Code"},codex:{engine:Oe,label:"Codex"},antigravity:{engine:Ae,label:"Antigravity",tools:!1},pi:{engine:xe,label:"Pi"},opencode:{engine:Pe,label:"OpenCode"},hermes:{engine:Re,label:"Hermes"},kiro:{engine:$e,label:"Kiro"},copilot:{engine:Ie,label:"GitHub Copilot"},deepseek:{engine:Ne,label:"DeepSeek Harness"},custom:{engine:He,label:"Custom",hidden:!0}};function ce(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 Xt=Wt(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Ut({origin:n.headers.origin||"",hasToken:pe(n),extensionIds:Xt})),n.chatpanelTrust}function zt(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 Kt(n,e){const t=n.headers.origin||"",r=ce(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 J=new Set(["127.0.0.1","localhost","::1"]);function Vt(n){if(!J.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(t)}const R=H(A.homedir(),".chatpanel","bridge-token");let S="";function Yt(){try{Ce(R)&&(S=K(R,"utf8").trim()),S||(S=be(32).toString("hex"),Te(H(A.homedir(),".chatpanel"),{recursive:!0}),ve(R,S,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const le=Jt({random:()=>Se(0,1e6)/1e6});function Qt(n){if(!S)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=le.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Zt(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=le.claim(t?.code);return r.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${N(n)} caller`),i(e,403,{error:r.reason}))}function qt(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:w})}let M=null;async function de(){if(M)return M;const{createChannelService:n}=await import("./channels/service.js");return M=n({home:H(A.homedir(),".chatpanel"),dataDir:H(A.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),M}async function ue(n,e,t){try{const r=await de(),o=n.method==="POST"?await f(n):{};if(t==="status")return i(e,200,await r.status());if(t==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await r.pair()):t==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?i(e,200,await r.update(o)):t==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function pe(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 r=Buffer.from(t),o=Buffer.from(S);return r.length===o.length&&ke(r,o)}const en=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),tn=new Set(["/debug"]),nn=n=>tn.has(n);function on(n,e){if(!Vt(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ce(t))return"forbidden origin";const r=n.method==="POST"&&en.has(e)||n.method==="GET"&&nn(e);return r&&!(zt(t)||pe(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I(N(n))&&!an.has(e)?rn:null}const rn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",an=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 r=N(n),o=Lt(t,r);if(!jt(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=o.reach,s=I(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:o,note:s}}function i(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 sn(n){const e=await Promise.all(Object.entries(C).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:d,tools:c}])=>{const l=await s.available().catch(g=>({ok:!1,reason:String(g?.message||g)})),p=await _e(a).catch(()=>[]);return{id:a,label:d,available:l.ok,reason:l.reason,connectors:p,...c===!1?{tools:!1}:{}}})),t=bt()?{current:w,updateAvailable:!1,embedded:"gateway"}:await yt(w).catch(()=>({current:w,updateAvailable:!1})),r=await Le().catch(()=>null),o=await Z().status().catch(a=>({enabled:!1,reason:a.message}));i(n,200,{ok:!0,version:w,agents:e,update:t,workspace:Ve,sandbox:o,localMcp:kt(),processes:tt(),worktrees:ne,secretBackend:ee(),warm:At(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function cn(n,e,t){const{index:r,problems:o}=await W({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:Ge(r),problems:o})}async function ln(n,e,t){i(n,200,{ok:!0,quarantined:await je(e,t)})}async function dn(n,e,t,r){const{index:o}=await W({extraDirs:t,workdir:r}),a=Ue(o,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function un(n,e,t,r,o){const{index:a}=await W({extraDirs:r,workdir:o}),s=await We(a,e,t);if(s.error)return i(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(n,200,{ok:!0,...s})}async function pn(){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 he(n,e=""){const t=await pn();if(e){const r=t.find(o=>o.id===e);return r?i(n,200,r):i(n,404,b(new $(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function hn(n){try{const e=await re(w);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function mn(n,e){let t;try{t=await f(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=F(n,t.agent,t.options||{});if(o.error)return i(e,403,{error:o.error});t.options=o.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
|
|
3
3
|
|
|
4
|
-
`)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=se(d),l={signal:c.signal,abort:()=>c.cancel("client")},p=()=>{s=!0,c.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const g=h=>{s||a(h)};a({type:"run",id:d}),o.note&&a({type:"status",text:o.note});let m=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(m=await te({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),m.error){a({type:"error",error:`workspace: ${m.error}`}),L(d),e.writableEnded||e.end();return}}const X=m?m.path:Qe(t.options?.workingDir);let E=null;{const h=X,O=!!m||!Ye(t.options?.workingDir),y=Ze(t.agent,t.options?.permissionMode,h);a({type:"workdir",path:h,isDefault:!O,writeScope:y||void 0}),a({type:"status",text:`Working in ${h}${O?"":" (default)"}`}),y&&a({type:"status",text:y}),E=await nt(h),E&&a({type:"scm",phase:"before",...E})}let U=null;if(E||m){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:O,connection:y}=st({remote:E?.remote||null,grants:h,branch:m?.branch||null,connectionId:t.options?.connectionId||null});U=ut(O),m&&a({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&a({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const z=t.approvals===!0,_={...t.options||{},...m?{workingDir:m.path}:{},...U?{runEnv:U}:{},approvals:z};let
|
|
4
|
+
`)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=se(d),l={signal:c.signal,abort:()=>c.cancel("client")},p=()=>{s=!0,c.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const g=h=>{s||a(h)};a({type:"run",id:d}),o.note&&a({type:"status",text:o.note});let m=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(m=await te({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),m.error){a({type:"error",error:`workspace: ${m.error}`}),L(d),e.writableEnded||e.end();return}}const X=m?m.path:Qe(t.options?.workingDir);let E=null;{const h=X,O=!!m||!Ye(t.options?.workingDir),y=Ze(t.agent,t.options?.permissionMode,h);a({type:"workdir",path:h,isDefault:!O,writeScope:y||void 0}),a({type:"status",text:`Working in ${h}${O?"":" (default)"}`}),y&&a({type:"status",text:y}),E=await nt(h),E&&a({type:"scm",phase:"before",...E})}let U=null;if(E||m){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:O,connection:y}=st({remote:E?.remote||null,grants:h,branch:m?.branch||null,connectionId:t.options?.connectionId||null});U=ut(O),m&&a({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&a({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const z=t.approvals===!0,_={...t.options||{},...m?{workingDir:m.path}:{},...U?{runEnv:U}:{},approvals:z};let P=null;(t.pageTools?.specs?.length||z)&&(P=Xe(g,t.pageTools?.specs||[]),_.permissionSession=P,t.pageTools?.specs?.length&&(_.mcp={url:`http://${k}:${v}/mcp/${P.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));try{await q(_.sandbox,()=>r.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:_,images:Array.isArray(t.images)?t.images:[]},g,{signal:l.signal}))}catch(h){u("error",`${t.agent} chat failed: ${h?.message||h}`),a({type:"error",error:h?.message||String(h)})}finally{if(!s){const h=await ot(X,E).catch(()=>null);h&&g({type:"scm",phase:"after",...h})}L(d),P&&Y(P.id),e.writableEnded||e.end()}}async function fn(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:rt(),secretBackend:ee()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:at(r.connection||r,{token:r.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return o?o[2]==="delete"?i(e,200,{ok:it(o[1])}):i(e,200,ct(o[1],r.remote||"")):i(e,404,{error:"Not found"})}async function gn(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:ne,worktrees:await lt()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/worktrees"){const o=await te({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return i(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(t==="/worktrees/remove"){const o=await dt({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return i(e,o.ok?200:400,o)}return i(e,404,{error:"Not found"})}async function T(n,e,t){const r=C[n.agent];if(!r||r.hidden)throw new $(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const o=await r.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!o.ok)throw new $(o.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=se(a),d=()=>s.cancel("disconnected");t.on("close",d);let c="";try{return await q(n.options?.sandbox,()=>r.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",d),L(a)}}function B(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
|
|
5
5
|
|
|
6
|
-
`)}function
|
|
6
|
+
`)}function D(n,e,t){n.writableEnded||n.write(`event: ${e}
|
|
7
7
|
data: ${JSON.stringify(t)}
|
|
8
8
|
|
|
9
|
-
`)}async function D(n,e,t,r){try{const o=t(await f(n)),a=F(n,o.agent,o.options||{});if(a.error)throw new $(a.error,403,"permission");return o.options=a.options,o}catch(o){return i(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new $(`Bad JSON: ${o.message}`):o)),null}}async function fn(n,e){const t=await D(n,e,_t,b);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,$t(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}B(e);const r=xt(t.requestedModel,o=>x(e,o));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function gn(n,e){const t=await D(n,e,Ht,b);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,It(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}B(e);const r=At(t.requestedModel,o=>x(e,o));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function wn(n,e){const t=await D(n,e,Mt,b);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,Nt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}B(e);const r=Bt(t.requestedModel,o=>G(e,o.type,o));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...b(o)};G(e,"error",a)}e.end()}async function yn(n,e){const t=await D(n,e,Rt,j);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,Pt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,j(o))}B(e);const r=Ot(t.requestedModel,(o,a)=>G(e,o,a));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){G(e,"error",j(o))}e.end()}async function bn(n,e){let t={};try{t=await f(n)||{}}catch{}const r=String(t.id||"").trim(),o=r?Tt(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function me(n,e,t){let r;try{r=await f(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=t?Q(t):ze(),a=c=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:c})},s=(c,l)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:c,message:l}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return a({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:w}});const d=Je();if(r.method==="tools/list"){const c=o?o.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...d,...c]})}if(r.method==="tools/call"){const c=await Fe(r.params?.name,r.params?.arguments||{});if(c)return a(c);if(!o)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await Ke(o,r.params?.name,r.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function Sn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=t.server||{},o=t.message;if(!r.command||!o)return i(e,400,{error:"need server.command and message"});try{const a=await yt({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox},o);return o.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function kn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=t.server||{};if(!r.command)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const o={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};try{return i(e,200,t.status?kt(o):await St(o))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function Tn(n,e){let t;try{t=await f(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const{url:r,headers:o,message:a}=t||{};if(!r||!a)return i(e,400,{error:"need url and message"});let s;try{s=ae(r)}catch(p){return i(e,400,{error:String(p?.message||p)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[p,g]of Object.entries(o)){const m=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(m)||m.startsWith("x-"))&&(d[p]=String(g))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const p=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(a),redirect:"follow",signal:c.signal});try{p.url&&ae(p.url)}catch(m){return i(e,400,{error:String(m?.message||m)})}const g=await p.text().catch(()=>"");return i(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",authenticate:p.headers.get("WWW-Authenticate")||"",body:g})}catch(p){const g=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${g}`})}finally{clearTimeout(l)}}const fe=256*1024,vn=5,Cn=8e3;async function En(n){let e=ie(n);const t=new AbortController,r=setTimeout(()=>t.abort(),Cn);try{for(let o=0;o<=vn;o++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${w} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=ie(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const s=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:An(await On(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function On(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,fe);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(o+=s.byteLength,r+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(r)||o>=fe))break}}finally{try{await e.cancel()}catch{}}return r}function xn(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function An(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?xn(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Pn(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t&&t.url;if(!r||typeof r!="string")return i(e,400,{error:"need url"});try{const o=await En(r);return i(e,200,{title:o.title||null,url:o.url||r})}catch(o){const a=o?.name==="AbortError"?"timed out":String(o?.message||o);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function $n(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=Q(t.session);if(!r)return i(e,404,{error:"no such session"});const o=r.pending.get(t.id);return o?(r.pending.delete(t.id),o.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function In(n,e){let t;try{t=await f(n)}catch(c){return i(e,400,{error:"Bad JSON: "+c.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=String(t.prompt||"").slice(0,6e3);if(!o)return i(e,400,{error:"Empty prompt"});const a=t.model||"",s=F(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const d=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 c="";return typeof r.engine.complete=="function"?c=await r.engine.complete({prompt:o,system:d,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:d,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),i(e,200,{text:(c||"").trim()})}catch(c){return i(e,502,{error:c?.message||String(c)})}}async function Nn(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof r.engine.listModels!="function")return i(e,200,{models:[]});try{const o=await r.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return i(e,502,{error:o?.message||String(o)})}}async function Rn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(t.command||"").trim();if(!r)return i(e,400,{error:"No command"});let o=null;try{o=ft(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}const ge=ye(async(n,e)=>{if(Xt(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const r=tn(n,t.pathname);if(r)return i(e,403,{error:r});try{if(n.method==="GET"&&t.pathname==="/health")return rn(e);const o=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return an(e,o,a);if(n.method==="GET"&&t.pathname==="/skills-quarantined")return sn(e,o,a);if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),d=s.indexOf("/file/");return d===-1?cn(e,decodeURIComponent(s),o,a):ln(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return hn(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return mn(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return he(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return he(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:w,agents:Object.fromEntries(pt.map(d=>[d,s?oe(d)||null:!!oe(d)])),...s?{home:P.homedir(),path:process.env.PATH}:{}})}if(n.method==="POST"&&t.pathname==="/chat")return pn(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Yt(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return Vt(e);if(n.method==="POST"&&t.pathname==="/whoami")return Qt(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return fn(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return gn(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return wn(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return yn(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return me(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const s=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return me(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return Y(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ue(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ue(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return bn(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return $n(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await f(n)}catch{s=null}const d=et(s||{});return e.writeHead(d?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return Sn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return kn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return Tn(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Pn(n,e);if(n.method==="POST"&&t.pathname==="/complete")return In(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Nn(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Rn(n,e);if(n.method==="POST"&&t.pathname==="/update")return un(e);i(e,404,{error:"Not found"})}catch(o){i(e,500,{error:o?.message||String(o)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function _n(n){let e="";const t=[];let r=!1,o=!1;const a=()=>{o&&!r&&!t.length&&process.exit(0)},s=async()=>{if(!r){for(r=!0;t.length;){const d=t.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const p=(await l.text()).trim();p&&process.stdout.write(p+`
|
|
9
|
+
`)}async function G(n,e,t,r){try{const o=t(await f(n)),a=F(n,o.agent,o.options||{});if(a.error)throw new $(a.error,403,"permission");return o.options=a.options,o}catch(o){return i(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new $(`Bad JSON: ${o.message}`):o)),null}}async function wn(n,e){const t=await G(n,e,Mt,b);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,Nt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}B(e);const r=Pt(t.requestedModel,o=>x(e,o));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function yn(n,e){const t=await G(n,e,Bt,b);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,Rt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}B(e);const r=$t(t.requestedModel,o=>x(e,o));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function bn(n,e){const t=await G(n,e,Dt,b);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,_t(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}B(e);const r=Gt(t.requestedModel,o=>D(e,o.type,o));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...b(o)};D(e,"error",a)}e.end()}async function Sn(n,e){const t=await G(n,e,Ht,j);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,It(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,j(o))}B(e);const r=xt(t.requestedModel,(o,a)=>D(e,o,a));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){D(e,"error",j(o))}e.end()}async function kn(n,e){let t={};try{t=await f(n)||{}}catch{}const r=String(t.id||"").trim(),o=r?Ct(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function me(n,e,t){let r;try{r=await f(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=t?Q(t):ze(),a=c=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:c})},s=(c,l)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:c,message:l}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return a({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:w}});const d=Je();if(r.method==="tools/list"){const c=o?o.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...d,...c]})}if(r.method==="tools/call"){const c=await Fe(r.params?.name,r.params?.arguments||{});if(c)return a(c);if(!o)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await Ke(o,r.params?.name,r.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function Tn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=t.server||{},o=t.message;if(!r.command||!o)return i(e,400,{error:"need server.command and message"});try{const a=await St({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox},o);return o.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function vn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=t.server||{};if(!r.command)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const o={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};try{return i(e,200,t.status?vt(o):await Tt(o))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function Cn(n,e){let t;try{t=await f(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const{url:r,headers:o,message:a}=t||{};if(!r||!a)return i(e,400,{error:"need url and message"});let s;try{s=ae(r)}catch(p){return i(e,400,{error:String(p?.message||p)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[p,g]of Object.entries(o)){const m=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(m)||m.startsWith("x-"))&&(d[p]=String(g))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const p=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(a),redirect:"follow",signal:c.signal});try{p.url&&ae(p.url)}catch(m){return i(e,400,{error:String(m?.message||m)})}const g=await p.text().catch(()=>"");return i(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",authenticate:p.headers.get("WWW-Authenticate")||"",body:g})}catch(p){const g=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${g}`})}finally{clearTimeout(l)}}const fe=256*1024,En=5,On=8e3;async function An(n){let e=ie(n);const t=new AbortController,r=setTimeout(()=>t.abort(),On);try{for(let o=0;o<=En;o++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${w} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=ie(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const s=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:$n(await xn(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function xn(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,fe);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(o+=s.byteLength,r+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(r)||o>=fe))break}}finally{try{await e.cancel()}catch{}}return r}function Pn(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function $n(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Pn(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function In(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t&&t.url;if(!r||typeof r!="string")return i(e,400,{error:"need url"});try{const o=await An(r);return i(e,200,{title:o.title||null,url:o.url||r})}catch(o){const a=o?.name==="AbortError"?"timed out":String(o?.message||o);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function Nn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=Q(t.session);if(!r)return i(e,404,{error:"no such session"});const o=r.pending.get(t.id);return o?(r.pending.delete(t.id),o.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function Rn(n,e){let t;try{t=await f(n)}catch(c){return i(e,400,{error:"Bad JSON: "+c.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=String(t.prompt||"").slice(0,6e3);if(!o)return i(e,400,{error:"Empty prompt"});const a=t.model||"",s=F(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const d=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 c="";return typeof r.engine.complete=="function"?c=await r.engine.complete({prompt:o,system:d,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:d,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),i(e,200,{text:(c||"").trim()})}catch(c){return i(e,502,{error:c?.message||String(c)})}}async function _n(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof r.engine.listModels!="function")return i(e,200,{models:[]});try{const o=await r.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return i(e,502,{error:o?.message||String(o)})}}async function Hn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(t.command||"").trim();if(!r)return i(e,400,{error:"No command"});let o=null;try{o=oe(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}const ge=ye(async(n,e)=>{if(Kt(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const r=on(n,t.pathname);if(r)return i(e,403,{error:r});try{if(n.method==="GET"&&t.pathname==="/health")return sn(e);const o=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return cn(e,o,a);if(n.method==="GET"&&t.pathname==="/skills-quarantined")return ln(e,o,a);if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),d=s.indexOf("/file/");return d===-1?dn(e,decodeURIComponent(s),o,a):un(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return fn(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return gn(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return he(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return he(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:w,agents:Object.fromEntries(pt.map(d=>[d,s?wt(d)||oe(d)?.kind||null:ht(d)])),...s?{home:A.homedir(),path:process.env.PATH,installDirs:mt(A.homedir())}:{}})}if(n.method==="POST"&&t.pathname==="/chat")return mn(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Zt(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return Qt(e);if(n.method==="POST"&&t.pathname==="/whoami")return qt(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return wn(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return yn(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return bn(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return Sn(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return me(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const s=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return me(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return Y(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ue(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ue(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return kn(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Nn(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await f(n)}catch{s=null}const d=et(s||{});return e.writeHead(d?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return Tn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return vn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return Cn(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return In(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Rn(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return _n(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Hn(n,e);if(n.method==="POST"&&t.pathname==="/update")return hn(e);i(e,404,{error:"Not found"})}catch(o){i(e,500,{error:o?.message||String(o)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Mn(n){let e="";const t=[];let r=!1,o=!1;const a=()=>{o&&!r&&!t.length&&process.exit(0)},s=async()=>{if(!r){for(r=!0;t.length;){const d=t.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const p=(await l.text()).trim();p&&process.stdout.write(p+`
|
|
10
10
|
`)}catch(l){c.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:c.id,error:{code:-32e3,message:String(l?.message||l)}})+`
|
|
11
11
|
`)}}r=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",d=>{e+=d;let c;for(;(c=e.indexOf(`
|
|
12
|
-
`))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&t.push(l)}s()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function
|
|
12
|
+
`))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&t.push(l)}s()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function Bn(){ft(),gt(),Yt(),ge.on("error",n=>{n&&n.code==="EADDRINUSE"&&(u("error",`Port ${v} 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=Et("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const t=Ot("shutdown");t&&u("info",`shutdown: closed ${t} warm agent process${t===1?"":"es"}`),Z().close(),setTimeout(()=>process.exit(0),e||t?300:0).unref?.(),!e&&!t&&process.exit(0)});ge.listen(v,k,async()=>{u("info",`listening on http://${k}:${v}`),J.has(k)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:n,label:e,hidden:t}]of Object.entries(C)){if(t)continue;const r=await n.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${e}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),de().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 Dn(){console.log(`ChatPanel Bridge v${w}
|
|
13
13
|
|
|
14
14
|
Usage:
|
|
15
15
|
chatpanel-bridge start the bridge (foreground) on ${k}:${v}
|
|
@@ -21,4 +21,4 @@ Usage:
|
|
|
21
21
|
chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
|
|
22
22
|
chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
|
|
23
23
|
|
|
24
|
-
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function
|
|
24
|
+
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function Gn(){const n=process.argv,e=(...t)=>t.some(r=>n.includes(r));if(e("--help","-h"))return Dn(),!0;if(e("--version","-v"))return console.log(w),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=K(R,"utf8").trim()}catch{}const r=`http://${k}:${v}`;try{if(!t)throw new Error(`no token at ${R} — is the bridge running?`);const o=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),a=await o.json().catch(()=>({}));if(!o.ok)throw new Error(a.error||`HTTP ${o.status}`);console.log(`Pairing code: ${Ft(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(o){u("error",`could not get a pairing code from the bridge at ${r}: ${o?.message||o}`),process.exitCode=1}})(),!0;if(n.includes("sandbox"))return qe(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{Me(),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{Be(),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=De()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const we=process.argv.indexOf("--mcp-stdio");if(we>=0){const n=process.argv[we+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Mn(n)}else process.argv.includes("--update")?(async()=>{try{const n=await re(w);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),V()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():Gn()||Bn();
|
package/src/warm-pool.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{treeRssBytes as
|
|
1
|
+
import{treeRssBytes as R,totalMemoryBytes as B}from"./proc.js";const v=1024**3,A=B(),D=Number(process.env.CHATPANEL_WARM_IDLE_MS)||(A>=16*v?10*6e4:5*6e4),S=Number(process.env.CHATPANEL_WARM_BUDGET_MB)*1024**2||Math.min(Math.floor(A*.2),3*v),U=400*1024**2;function N(n,a,o=U){const p=Math.floor(a/o),l=n>=48*v?4:n>=24*v?3:n>=12*v?2:1;return Math.max(1,Math.min(p,l))}const k=Number(process.env.CHATPANEL_WARM_MAX)||N(A,S),z=new Set;function x(n=[]){const o=(Array.isArray(n)?n:[]).slice(0,-1),p=o.filter(c=>c?.role==="user").map(c=>String(c.content||"").trim()),l=o.filter(c=>c?.role==="assistant").length;return{users:p,answers:l}}function y(n,a){if(n.answers!==a.answers||n.users.length!==a.users.length)return!1;for(let o=0;o<n.users.length;o++)if(n.users[o]!==a.users[o])return!1;return!0}function W({max:n=k,idleMs:a=D,budgetBytes:o=S,group:p=z,now:l=Date.now,measure:c=r=>R(r?.pid),log:h=()=>{}}={}){const r=new Set;let m=null;const $=()=>{let e=0;for(const s of p)e+=s.bytes;return e};let M=0;const f=e=>`${Math.round(e/1024**2)} MB`;function d(e,s="dropped"){if(r.has(e)){r.delete(e),e.alive=!1;try{e.session?.close?.(s)}catch{}h(`warm ${e.label}: ${s} (${r.size} live)`),!r.size&&m&&(clearInterval(m),m=null)}}function _(){const e=l();for(const s of[...r])!s.busy&&e-s.lastUsed>a&&d(s,"idle")}function L(){m||!Number.isFinite(a)||a<=0||(m=setInterval(_,Math.min(a,6e4)),m.unref?.())}const E={get size(){return r.size},get bytes(){let e=0;for(const s of r)e+=s.bytes||0;return e},peek({key:e,messages:s}){const i=x(s);for(const t of r)if(!t.busy&&t.alive&&t.key===e&&y(t.shape,i))return!0;return!1},acquire({key:e,messages:s}){const i=x(s);for(const t of r)if(!(t.busy||!t.alive||t.key!==e)){if(!y(t.shape,i)){h(`warm ${t.label}: shape differs (have ${t.shape.users.length}u/${t.shape.answers}a, asked ${i.users.length}u/${i.answers}a)`);continue}return t.busy=!0,t.lastUsed=l(),h(`warm ${t.label}: reused`),t}return null},reserve({key:e,label:s=e,evict:i=!0}){const t=()=>{let u=null;for(const b of r)!b.busy&&(!u||b.lastUsed<u.lastUsed)&&(u=b);return u};if(r.size>=n){const u=i?t():null;if(!u)return null;d(u,"evicted")}const w=M||U;for(;$()+w>o;){const u=i?t():null;if(!u)return h(`warm ${s}: not kept — ${f($())} warm + ~${f(w)} would pass the ${f(o)} budget`),null;d(u,`evicted for memory (${f($())} warm)`)}const T={key:e,label:s,session:null,shape:{users:[],answers:0},busy:!0,alive:!0,lastUsed:l(),bytes:w};return r.add(T),h(`warm ${s}: starting (${r.size} live, ~${f($())} of ${f(o)})`),L(),T},attach(e,s){return e.session=s,s.onExit?.(()=>{e.alive&&d(e,"process exited")}),e},release(e,{user:s,answered:i}){e.alive&&(typeof s=="string"&&(e.shape={users:[...e.shape.users,s.trim()],answers:e.shape.answers+(i?1:0)}),e.busy=!1,e.lastUsed=l(),setImmediate(()=>{if(!e.alive)return;const t=c(e.session);t>0&&(e.bytes=t,M=t,h(`warm ${e.label}: ${f(t)} resident`))}))},drop:d,closeAll(e="shutdown"){for(const s of[...r])d(s,e)},keys(){return[...r].map(e=>e.key)},reap:_};return p.add(E),E}export{S as WARM_BUDGET_BYTES,W as createWarmPool,x as historyShape,N as warmMaxFor};
|