@chatpanel/bridge 0.44.0 → 0.44.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/engines/claude-warm.js +2 -2
- package/src/engines/claude.js +1 -1
- package/src/env.js +2 -2
- package/src/health-snapshot.js +1 -1
- package/src/pii/pii-detect.js +2 -2
- package/src/server.js +5 -5
- package/src/sign-in.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.44.
|
|
3
|
+
"version": "0.44.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
|
|
6
6
|
"keywords": [
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{unlink as z}from"node:fs/promises";import{spawnRpcChild as K}from"../rpc-child.js";import{spawn as Q}from"node:child_process";import{track as V,sandbox as X}from"../sandbox.js";import{createWarmPool as Y}from"../warm-pool.js";import{registerWarmPool as Z}from"../warm.js";import{createSession as W,deleteSession as P,rebindSession as ee,releaseSession as re,relayPermission as U}from"../mcp-sessions.js";import{resolveClaude as se,buildSpawnSpec as te}from"../env.js";import{loginRequired as B,signInMessage as H}from"../sign-in.js";import{pushExtraArgs as R,FORBIDDEN as q}from"./args.js";import{buildClaudeLaunch as F,claudePrompt as ae,handleMessage as ne,harnessChars as le,writeImages as oe,answerControlRequest as ie}from"./claude.js";const j=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,ue=5e3,d=Z("claude",Y({log:n=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${n}`)}}));function ce(n={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||n.warm===!1)}async function G({spec:n,args:E,cwd:r,env:b,spawnImpl:S,log:g=()=>{},ask:$=null,peers:w=!0}){const u=[...E,"--input-format","stream-json"],[
|
|
1
|
+
import{unlink as z}from"node:fs/promises";import{spawnRpcChild as K}from"../rpc-child.js";import{spawn as Q}from"node:child_process";import{track as V,sandbox as X}from"../sandbox.js";import{createWarmPool as Y}from"../warm-pool.js";import{registerWarmPool as Z}from"../warm.js";import{createSession as W,deleteSession as P,rebindSession as ee,releaseSession as re,relayPermission as U}from"../mcp-sessions.js";import{resolveClaude as se,buildSpawnSpec as te}from"../env.js";import{loginRequired as B,signInMessage as H}from"../sign-in.js";import{pushExtraArgs as R,FORBIDDEN as q}from"./args.js";import{buildClaudeLaunch as F,claudePrompt as ae,handleMessage as ne,harnessChars as le,writeImages as oe,answerControlRequest as ie}from"./claude.js";const j=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,ue=5e3,d=Z("claude",Y({log:n=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${n}`)}}));function ce(n={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||n.warm===!1)}async function G({spec:n,args:E,cwd:r,env:b,spawnImpl:S,log:g=()=>{},ask:$=null,peers:w=!0}){const u=[...E,"--input-format","stream-json"],[f,c,v]=te(n,u,r,b),p=await X().wrap(f,c,v,{engine:"claude",cwd:r,peers:w});p.record.layer==="none"&&g(`sandbox: claude session runs outside a sandbox — ${p.record.reason}`);const[i,m,C]=[p.bin,p.argv,p.opts];let e=null;const x=new Set;let y="",T=0,I=0,l=null;const h=K(i,m,{spawnOpts:C,spawnImpl:(s,t,a)=>V((S||Q)(s,t,a),p,{kind:"warm"}),jsonrpc:!1,onStderr:s=>{y=(y+s).slice(-2e3),e&&e.touch()},onExit:s=>{if(g(`claude exited: ${s.signal||s.code}${y?` — ${y.trim().split(`
|
|
2
2
|
`).pop()}`:""}`),e){const t=e.apiError&&B(e.apiError)?H("Claude Code","claude"):e.apiError?`Claude Code reported an error: ${e.apiError}`:`Claude Code exited (${s.signal||s.code})${y?`: ${y.trim().split(`
|
|
3
|
-
`).pop().slice(0,200)}`:""}`;e.finish({status:"died",error:t})}for(const t of x)try{t(s)}catch{}},onMessage:s=>{if(!e||(e.touch(),s.type==="control_response"))return;if(s.type==="control_request"){const a=e;a.asking++,a.touch(),ie(s,$,_=>{try{h.send(_)}catch{}}).catch(()=>{}).finally(()=>{a.asking--,e===a&&a.touch()});return}const t=ne(s,e.emit,e.streamedAny,r,e.flow);t.sessionId&&(l=t.sessionId),t.streamed&&(e.streamedAny=!0),t.result!=null&&(e.resultText=t.result),t.apiError&&(e.apiError=t.apiError),s.type==="result"&&(e.apiError&&B(e.apiError)?e.finish({status:"failed",error:H("Claude Code","claude")}):e.apiError?e.finish({status:"failed",error:`Claude Code reported an error: ${e.apiError}`}):e.finish({status:"completed",error:null}))}});return{get pid(){return h.pid},get alive(){return!h.exited},get sessionId(){return l},onExit(s){x.add(s)},close(){h.close()},async turn({prompt:s,emit:t,signal:a,harness:_=null}){if(h.exited)throw new Error("Claude Code process is gone");if(e)throw new Error("a turn is already running on this process");let k=null,A;const N=new Promise(M=>{A=M}),o={emit:t,flow:{sawText:!1,tail:"",boundary:!1,costUsdBefore:I,harnessChars:_},streamedAny:!1,resultText:"",apiError:null,asking:0,touch(){clearTimeout(k),!o.asking&&(k=setTimeout(()=>o.finish({status:"timeout",error:`Claude Code timed out — no output for ${Math.round(j/1e3)}s.`}),j))},finish(M){e===o&&(clearTimeout(k),e=null,A(M))}};e=o,o.touch();const O=()=>{if(e===o){o.interrupted=!0;try{h.send({type:"control_request",request_id:`stop_${++T}`,request:{subtype:"interrupt"}})}catch{}setTimeout(()=>{e===o&&(o.finish({status:"killed",error:null}),h.kill())},ue).unref?.()}};if(a?.aborted)return o.finish({status:"killed",error:null}),{streamedAny:!1,resultText:"",status:"killed"};a?.addEventListener("abort",O,{once:!0});try{h.send({type:"user",message:{role:"user",content:s}})}catch(M){o.finish({status:"failed",error:M.message})}const L=await N;o.flow.costUsdTotal!=null&&(I=o.flow.costUsdTotal),a?.removeEventListener("abort",O),L.status==="timeout"&&h.kill();const J=L.status==="killed"?"killed":o.interrupted?"interrupted":L.status;return{streamedAny:o.streamedAny,resultText:o.resultText,status:J,error:L.error,sessionId:l}}}}const D=new Set;async function de({key:n,spec:E,options:r,label:b,launch:S=G,log:g=()=>{},force:$=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!$||!n||!E||D.has(n)||d.peek({key:n,messages:[{role:"user",content:""}]}))return!1;D.add(n);const w=d.reserve({key:n,label:`${b} (spare)`,evict:!1});if(!w)return D.delete(n),!1;let u=null,
|
|
3
|
+
`).pop().slice(0,200)}`:""}`;e.finish({status:"died",error:t})}for(const t of x)try{t(s)}catch{}},onMessage:s=>{if(!e||(e.touch(),s.type==="control_response"))return;if(s.type==="control_request"){const a=e;a.asking++,a.touch(),ie(s,$,_=>{try{h.send(_)}catch{}}).catch(()=>{}).finally(()=>{a.asking--,e===a&&a.touch()});return}const t=ne(s,e.emit,e.streamedAny,r,e.flow);t.sessionId&&(l=t.sessionId),t.streamed&&(e.streamedAny=!0),t.result!=null&&(e.resultText=t.result),t.apiError&&(e.apiError=t.apiError),s.type==="result"&&(e.apiError&&B(e.apiError)?e.finish({status:"failed",error:H("Claude Code","claude")}):e.apiError?e.finish({status:"failed",error:`Claude Code reported an error: ${e.apiError}`}):e.finish({status:"completed",error:null}))}});return{get pid(){return h.pid},get alive(){return!h.exited},get sessionId(){return l},onExit(s){x.add(s)},close(){h.close()},async turn({prompt:s,emit:t,signal:a,harness:_=null}){if(h.exited)throw new Error("Claude Code process is gone");if(e)throw new Error("a turn is already running on this process");let k=null,A;const N=new Promise(M=>{A=M}),o={emit:t,flow:{sawText:!1,tail:"",boundary:!1,costUsdBefore:I,harnessChars:_},streamedAny:!1,resultText:"",apiError:null,asking:0,touch(){clearTimeout(k),!o.asking&&(k=setTimeout(()=>o.finish({status:"timeout",error:`Claude Code timed out — no output for ${Math.round(j/1e3)}s.`}),j))},finish(M){e===o&&(clearTimeout(k),e=null,A(M))}};e=o,o.touch();const O=()=>{if(e===o){o.interrupted=!0;try{h.send({type:"control_request",request_id:`stop_${++T}`,request:{subtype:"interrupt"}})}catch{}setTimeout(()=>{e===o&&(o.finish({status:"killed",error:null}),h.kill())},ue).unref?.()}};if(a?.aborted)return o.finish({status:"killed",error:null}),{streamedAny:!1,resultText:"",status:"killed"};a?.addEventListener("abort",O,{once:!0});try{h.send({type:"user",message:{role:"user",content:s}})}catch(M){o.finish({status:"failed",error:M.message})}const L=await N;o.flow.costUsdTotal!=null&&(I=o.flow.costUsdTotal),a?.removeEventListener("abort",O),L.status==="timeout"&&h.kill();const J=L.status==="killed"?"killed":o.interrupted?"interrupted":L.status;return{streamedAny:o.streamedAny,resultText:o.resultText,status:J,error:L.error,sessionId:l}}}}const D=new Set;async function de({key:n,spec:E,options:r,label:b,launch:S=G,log:g=()=>{},force:$=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!$||!n||!E||r?.ephemeral===!0||D.has(n)||d.peek({key:n,messages:[{role:"user",content:""}]}))return!1;D.add(n);const w=d.reserve({key:n,label:`${b} (spare)`,evict:!1});if(!w)return D.delete(n),!1;let u=null,f=null;try{let c=r.mcp;const v=r.mcp?.specs||[];(c?.url&&v.length||r.approvals===!0)&&(u=W(()=>{},v),c?.url&&v.length&&(c={...c,url:`${c.url.replace(/\/[^/]*$/,"")}/${u.id}`})),f=await F({system:"",options:{...r,mcp:c},tag:`spare-${Date.now()}-${Math.random().toString(36).slice(2)}`});const p=[...f.args];R(p,r.extraArgs,q.claude,()=>{});const i=u,m=await S({spec:E,args:p,cwd:f.cwd,env:f.runEnv,ask:f.approvals&&i?e=>U(i,e):null,peers:f.peers});m.mcpSession=u,m.systemSent="",d.attach(w,m);const C=f.cleanup;return m.onExit(()=>{u&&P(u.id),C()}),d.release(w,{user:null,answered:!1}),g(`warm ${b}: spare ready`),!0}catch(c){return u&&P(u.id),f?.cleanup?.(),d.drop(w,`spare launch failed: ${c.message}`),!1}finally{D.delete(n)}}async function xe({messages:n,system:E,options:r,images:b,thread:S=null},g,{signal:$,launch:w=G}={}){if(!ce(r))return{handled:!1,reason:"not eligible"};const u=se();if(!u)return{handled:!1,reason:"claude not resolvable"};const f=`${Date.now()}-${Math.random().toString(36).slice(2)}`,c=(r.mcp?.specs||[]).map(s=>s?.name).filter(Boolean),v=[];R(v,r.extraArgs,q.claude,()=>{});const p=JSON.stringify({agent:"claude",cwd:r.workingDir||"",mode:r.permissionMode||"default",model:r.model||"",local:r.useLocalConfig!==!1,reach:r.reach||"",tools:[...c].sort(),extra:v,approvals:r.approvals===!0,env:r.runEnv?Object.keys(r.runEnv).sort().map(s=>`${s}=${r.runEnv[s]}`):[],hosts:r.sandbox?.hosts?(Array.isArray(r.sandbox.hosts)?r.sandbox.hosts:String(r.sandbox.hosts).split(/[\s,;]+/)).map(s=>String(s).trim().toLowerCase()).filter(Boolean).sort():[],outside:r.sandbox?.outside===!0,ephemeral:r.ephemeral===!0});let i=d.acquire({key:p,messages:n}),m=!1;const C=!i&&S?.plan.mode==="resume"?S.plan.sessionId:null;if(!i){if(i=d.reserve({key:p,label:`claude ${r.workingDir||"home"}`,evict:r.ephemeral!==!0}),!i)return{handled:!1,reason:"all warm slots busy"};m=!0;let s=null,t=null;try{let a=r.mcp;(a?.url&&c.length||r.approvals===!0)&&(s=W(g,a?.specs||[]),a?.url&&c.length&&(a={...a,url:`${a.url.replace(/\/[^/]*$/,"")}/${s.id}`})),t=await F({system:E,options:{...r,mcp:a},tag:f,resume:C,name:S?.thread.title||""});const _=[...t.args];R(_,r.extraArgs,q.claude,g);const k=s,A=await w({spec:u,args:_,cwd:t.cwd,env:t.runEnv,ask:t.approvals&&k?o=>U(k,o):null,peers:t.peers});A.mcpSession=s,A.systemSent=String(E||""),d.attach(i,A),C&&d.holds(i,n);const N=t.cleanup;A.onExit(()=>{s&&P(s.id),N()})}catch(a){return s&&P(s.id),t?.cleanup(),d.drop(i,`launch failed: ${a.message}`),{handled:!1,reason:a.message}}}const e=i.session;e.mcpSession&&ee(e.mcpSession,g,r.mcp?.specs);const x=n[n.length-1],y=await oe(b,f),T=String(E||""),I=ae(m&&!C?n:C?S.plan.tail||[x]:[x],y,!m&&T!==e.systemSent?T:"");e.systemSent=T;let l;try{l=await e.turn({prompt:I,emit:g,signal:$,harness:le({prompt:I,system:m?T:"",specs:m?r.mcp?.specs:null})})}finally{y.forEach(s=>z(s).catch(()=>{})),e.mcpSession&&re(e.mcpSession)}if($?.aborted||l.status==="interrupted")return l.status==="interrupted"&&e.alive?d.release(i,{user:String(x?.content||""),answered:l.streamedAny}):d.drop(i,"stopped"),{handled:!0};if(l.status!=="completed"){if(d.drop(i,l.error||l.status),!l.streamedAny)return{handled:!1,reason:l.error||l.status};throw new Error(l.error||`Claude Code ${l.status}`)}g({type:"done",text:l.streamedAny?"":l.resultText}),d.release(i,{user:String(x?.content||""),answered:!0});const h=l.sessionId||e.sessionId||null;return setTimeout(()=>{de({key:p,spec:u,options:r,label:`claude ${r.workingDir||"home"}`,launch:w}).catch(()=>{})},250).unref?.(),{handled:!0,completed:!0,sessionId:h}}export{xe as chatWarm,G as launchClaudeSession,d as pool,de as prewarmClaude,ce as warmEligible};
|
package/src/engines/claude.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{spawn as z}from"node:child_process";import{writeFile as R,unlink as G}from"node:fs/promises";import P from"node:os";import D from"node:path";import{resolveClaude as v,buildSpawnSpec as J,isCompiledBinary as ue,selfMcpStdio as de}from"../env.js";import{signInStatus as pe,signInMessage as Y,loginRequired as fe}from"../sign-in.js";import{buildCliPrompt as K}from"./prompt.js";import{cliError as he}from"../cli-errors.js";import{killOnAbort as me}from"../proc.js";import{sandbox as ye,noteSandbox as _e,track as be,grantedWriteRoots as we}from"../sandbox.js";import{harnessDirArgs as Te,harnessSessionArgs as j}from"../events/harness-cards.js";import{threadTurn as ge}from"../threads.js";import{liveClaudeSessions as Ee}from"../agent-sessions.js";import{pushExtraArgs as xe,FORBIDDEN as Ce}from"./args.js";import{relayTimeoutMax as Se}from"../relay-timeout.js";import{displayPath as ke,resolveWorkdir as F}from"../workdir.js";import{connectorsFor as Ae}from"../connectors.js";import{chatWarm as ve}from"./claude-warm.js";import{claudePermissionResponse as Ne,permissionAnswer as Me}from"../events/agent-permission.js";import{relayPermission as Pe}from"../mcp-sessions.js";async function Oe(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=D.join(P.tmpdir(),`chatpanel-claude-img-${t}-${i}.${o}`);await R(n,Buffer.from(s[2],"base64")),r.push(n)}return r}const X=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,V=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task","ListAgents"],Q=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),Ie=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task","ToolSearch","ListAgents","SendMessage"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch","SendMessage"])}),Le=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),$e=Object.freeze(["remember","forget"]),We=Object.freeze(["ask_model","ask_status"]),Z=Object.freeze({device:Object.freeze([]),trusted:Le});function Re(e,t=[]){const r=Z[e]||Z.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[...$e,...We])o.push(`mcp__${n}__${a}`)}return{allow:s,deny:o}}function De(e){if(!e||e==="any")return null;const t=Q[e]?e:"device";return{allow:[...Q[t]],deny:[...Ie[t]]}}let O="Claude Code not found.",ee=0,k=!1;async function yt(){if(Date.now()-ee>(k?3e4:4e3)){ee=Date.now();try{v()||!ue()&&await q()?k=!0:(k=!1,O=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{k=!1}}return k?await pe("claude",v()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:Y("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:O}}async function _t(){return["opus","sonnet","haiku"]}function je(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:r,args:i}=de(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 Fe(e,t,r){const i=e?.request_id,s=e?.request?.subtype;if(s==="can_use_tool"){const o=t?await t(e.request):Me("deny","This run has no approval surface.");return r(Ne(i,o,e.request)),!0}return r({type:"control_response",response:{subtype:"error",request_id:i,error:`unsupported control request: ${s||"unknown"}`}}),!1}function te({prompt:e,args:t,cwd:r,env:i=null,emit:s,signal:o,harness:n=null,host:a=!1,ask:c=null,peers:u=!0}){const d=v();if(!d)return null;const[y,g,w]=J(d,a?[...t,"--input-format","stream-json"]:t,r,i);return new Promise((_,p)=>{ye().wrap(y,g,w,{engine:"claude",cwd:r,peers:u}).then(T=>{_e(s,T.record);let l;try{l=be(z(T.bin,T.argv,T.opts),T,{kind:"agent"})}catch(m){return p(new Error(`Failed to start claude: ${m.message}`))}const f=me(l,o);let b="",E="",h=!1,C=null;const le={sawText:!1,tail:"",boundary:!1,harnessChars:n};let I="",L=null,A,$=0;const M=()=>{clearTimeout(A),!$&&(A=setTimeout(()=>{l.kill("SIGKILL"),p(new Error(`Claude Code timed out — no output for ${Math.round(X/1e3)}s.`))},X))};M();const ce=m=>{try{l.stdin.write(`${JSON.stringify(m)}
|
|
1
|
+
import{spawn as z}from"node:child_process";import{writeFile as R,unlink as G}from"node:fs/promises";import P from"node:os";import D from"node:path";import{resolveClaude as v,buildSpawnSpec as J,isCompiledBinary as ue,selfMcpStdio as de}from"../env.js";import{signInStatus as pe,signInMessage as Y,loginRequired as fe}from"../sign-in.js";import{buildCliPrompt as K}from"./prompt.js";import{cliError as he}from"../cli-errors.js";import{killOnAbort as me}from"../proc.js";import{sandbox as ye,noteSandbox as _e,track as be,grantedWriteRoots as we}from"../sandbox.js";import{harnessDirArgs as Te,harnessSessionArgs as j}from"../events/harness-cards.js";import{threadTurn as ge}from"../threads.js";import{liveClaudeSessions as Ee}from"../agent-sessions.js";import{pushExtraArgs as xe,FORBIDDEN as Ce}from"./args.js";import{relayTimeoutMax as Se}from"../relay-timeout.js";import{displayPath as ke,resolveWorkdir as F}from"../workdir.js";import{connectorsFor as Ae}from"../connectors.js";import{chatWarm as ve}from"./claude-warm.js";import{claudePermissionResponse as Ne,permissionAnswer as Me}from"../events/agent-permission.js";import{relayPermission as Pe}from"../mcp-sessions.js";async function Oe(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=D.join(P.tmpdir(),`chatpanel-claude-img-${t}-${i}.${o}`);await R(n,Buffer.from(s[2],"base64")),r.push(n)}return r}const X=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,V=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task","ListAgents"],Q=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),Ie=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task","ToolSearch","ListAgents","SendMessage"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch","SendMessage"])}),Le=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),$e=Object.freeze(["remember","forget"]),We=Object.freeze(["ask_model","ask_status"]),Z=Object.freeze({device:Object.freeze([]),trusted:Le});function Re(e,t=[]){const r=Z[e]||Z.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[...$e,...We])o.push(`mcp__${n}__${a}`)}return{allow:s,deny:o}}function De(e){if(!e||e==="any")return null;const t=Q[e]?e:"device";return{allow:[...Q[t]],deny:[...Ie[t]]}}let O="Claude Code not found.",ee=0,k=!1;async function yt(){if(Date.now()-ee>(k?3e4:4e3)){ee=Date.now();try{v({probe:"async"})||!ue()&&await q()?k=!0:(k=!1,O=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{k=!1}}return k?await pe("claude",v()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:Y("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:O}}async function _t(){return["opus","sonnet","haiku"]}function je(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:r,args:i}=de(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 Fe(e,t,r){const i=e?.request_id,s=e?.request?.subtype;if(s==="can_use_tool"){const o=t?await t(e.request):Me("deny","This run has no approval surface.");return r(Ne(i,o,e.request)),!0}return r({type:"control_response",response:{subtype:"error",request_id:i,error:`unsupported control request: ${s||"unknown"}`}}),!1}function te({prompt:e,args:t,cwd:r,env:i=null,emit:s,signal:o,harness:n=null,host:a=!1,ask:c=null,peers:u=!0}){const d=v();if(!d)return null;const[y,g,w]=J(d,a?[...t,"--input-format","stream-json"]:t,r,i);return new Promise((_,p)=>{ye().wrap(y,g,w,{engine:"claude",cwd:r,peers:u}).then(T=>{_e(s,T.record);let l;try{l=be(z(T.bin,T.argv,T.opts),T,{kind:"agent"})}catch(m){return p(new Error(`Failed to start claude: ${m.message}`))}const f=me(l,o);let b="",E="",h=!1,C=null;const le={sawText:!1,tail:"",boundary:!1,harnessChars:n};let I="",L=null,A,$=0;const M=()=>{clearTimeout(A),!$&&(A=setTimeout(()=>{l.kill("SIGKILL"),p(new Error(`Claude Code timed out — no output for ${Math.round(X/1e3)}s.`))},X))};M();const ce=m=>{try{l.stdin.write(`${JSON.stringify(m)}
|
|
2
2
|
`)}catch{}};l.stdout.on("data",m=>{M(),b+=m.toString();let W;for(;(W=b.indexOf(`
|
|
3
3
|
`))>=0;){const B=b.slice(0,W).trim();if(b=b.slice(W+1),!B.startsWith("{"))continue;let S;try{S=JSON.parse(B)}catch{continue}if(S.type==="control_request"){$++,clearTimeout(A),Fe(S,c,ce).catch(()=>{}).finally(()=>{$--,M()});continue}if(S.type==="control_response")continue;const x=oe(S,s,h,r,le);x.streamed&&(h=!0),x.result!=null&&(I=x.result),x.apiError&&(C=x.apiError),x.sessionId&&(L=x.sessionId),a&&S.type==="result"&&l.stdin.end()}}),l.stderr.on("data",m=>{M(),E+=m.toString()}),l.on("error",m=>{clearTimeout(A),f(),p(new Error(`Failed to start claude (${y}): ${m.message}`))}),l.on("close",m=>{if(clearTimeout(A),f(),o?.aborted){_({streamedAny:h,resultText:I,sessionId:L,stopped:!0});return}if(C&&fe(C))return p(new Error(Y("Claude Code","claude")));if(m===0&&C)return p(new Error(`Claude Code reported an error: ${C}`));m===0?_({streamedAny:h,resultText:I,sessionId:L}):p(he("Claude Code",m,E,C||"",{agentId:"claude"}))}),a?l.stdin.write(`${JSON.stringify({type:"user",message:{role:"user",content:e}})}
|
|
4
4
|
`):(l.stdin.write(e),l.stdin.end())}).catch(p)})}function He(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(`
|
package/src/env.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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=
|
|
1
|
+
import j from"node:os";import{spawnGroupOpts as U}from"./proc.js";import c from"node:path";import{spawn as X,spawnSync as w}from"node:child_process";import{readdirSync as M,readFileSync as D,existsSync as f}from"node:fs";let z=!1,Q=!1;const R=["codex","claude","agy","pi","opencode","kiro-cli","copilot","dsh"];function jn(n){return d(process.env.PATH||"",process.platform).some(o=>o&&(f(c.join(o,n))||f(c.join(o,n+".exe"))))}function hn(n){const t=I(n);if(t)return t;if(k()){const o=I(n);if(o)return o}return _n(n)||null}function Jn(n){return!!B(n,{probe:"async"})}function I(n){for(const t of dn(n))if(f(t))return t;return null}function $(){const n=c.basename(process.execPath).toLowerCase();return!(n.startsWith("node")||n.startsWith("bun"))}function Zn(n){const t=["--mcp-stdio",n];if($())return{command:process.execPath,args:t};const o=process.argv[1]||c.join(process.cwd(),"src","server.js"),e=process.env.CHATPANEL_BRIDGE_EMBEDDED==="1"?["--bridge"]:[];return{command:process.execPath,args:[o,...e,...t]}}const b="CHATPANEL_ENV",W=6e3;function T(n){for(const t of String(n||"").split(/\r?\n/)){const o=t.indexOf(" ");if(o>0&&t.slice(0,o).trim().endsWith(b))return t.slice(o+1).trim()}return""}function q(n){return/^[\w.+-]+$/.test(String(n||""))}function v(){if(process.env.SHELL)return process.env.SHELL;try{const{shell:n}=j.userInfo();if(n&&n!=="/usr/bin/false"&&n!=="/sbin/nologin")return n}catch{}return"/bin/sh"}function J(n,{interactive:t}={}){if(process.platform==="win32")return"";try{const o=t?["-l","-i","-c"]:["-l","-c"];return w(v(),[...o,n],{encoding:"utf8",timeout:W,stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}}).stdout||""}catch{return""}}function wn(n){let t="";for(const o of String(n||"").split(/\r?\n/))o.startsWith("PATH=")&&(t=o.slice(5).trim());return t}function bn({interactive:n=!0,ask:t=J}={}){const o=T(t(`command -p printf '%s\\t%s\\n' ${b} "$PATH"`,{interactive:n}));return d(o||wn(t("/usr/bin/env",{interactive:n})),process.platform)}const y=1e4,Pn=3e5;let L=0,x=y;function k({force:n=!1,now:t=Date.now(),read:o=bn,env:e=process.env}={}){if(process.platform==="win32"||!n&&(t-L<x||t<_))return!1;L=t;const i=d(e.PATH||"",process.platform),r=Y(m([...o({interactive:!0}),...i])),s=r.length>i.length;return x=s?y:Math.min(x*2,Pn),s?(e.PATH=r.join(c.delimiter),!0):!1}function nt(){L=0,x=y,h.clear(),_=0,A=H,O=!1}const h=new Map,gn=15e3;function _n(n){if(process.platform==="win32"||!q(n))return"";const t=h.get(n);if(t&&(t.bin||Date.now()-t.at<gn||Date.now()<_))return t.bin;const o=[`command -p printf '%s\\t%s\\n' ${b} "$(command -v ${n} 2>/dev/null)"`,`type -p ${n}`];let e="";for(const i of[!1,!0]){for(const r of o){const s=J(r,{interactive:i}),l=T(s)||String(s||"").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.startsWith("/")).pop()||"";if(l.startsWith("/")&&f(l)){e=l;break}}if(e)break}return h.set(n,{bin:e,at:Date.now()}),e}const H=15e3,An=3e5;let _=0,A=H,O=!1,E=null;function xn(n,{interactive:t}={}){return new Promise(o=>{let e="",i;try{i=X(v(),[...t?["-l","-i","-c"]:["-l","-c"],n],{stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}})}catch{o("");return}const r=setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},W);i.stdout.on("data",s=>{e+=s}),i.on("error",()=>{clearTimeout(r),o("")}),i.on("close",()=>{clearTimeout(r),o(e)})})}const En=new RegExp(`${b}=([\\w.+-]+)$`);function Z(n){const t=new Map;for(const o of String(n||"").split(/\r?\n/)){const e=o.indexOf(" ");if(e<=0)continue;const i=En.exec(o.slice(0,e).trim());i&&t.set(i[1],o.slice(e+1).trim())}return t}function tt({names:n=R,ask:t=xn,now:o=()=>Date.now()}={}){if(process.platform==="win32"||O)return Promise.resolve(!1);if(E)return E;if(o()<_)return Promise.resolve(!1);const e=m([...n,...h.keys()]).filter(r=>q(r)&&!I(r)&&!h.get(r)?.bin);if(!e.length)return Promise.resolve(!1);const i=[`command -p printf '%s\\t%s\\n' ${b} "$PATH"`,...e.map(r=>`command -p printf '%s\\t%s\\n' ${b}=${r} "$(command -v ${r} 2>/dev/null)"`)].join("; ");return E=(async()=>{let r=await t(i,{interactive:!0}),s=Z(r);if(s.size||(r=await t(i,{interactive:!1}),s=Z(r)),!s.size)return O=!0,!0;const l=o();let a=!1;const u=d(T(r),process.platform);u.length&&k({force:!0,now:l,read:()=>u})&&(a=!0);for(const p of e){if(!s.has(p))continue;const P=s.get(p),g=P.startsWith("/")&&f(P)?P:"";(g||I(p))&&(a=!0),h.set(p,{bin:g,at:l})}return a&&(A=H),_=l+A,a||(A=Math.min(A*2,An)),!0})().catch(()=>!0).finally(()=>{E=null}),E}function et(){_=0,A=H,O=!1,L=0,x=y,F=0;for(const[n,t]of h)t.bin||h.delete(n);for(const[n,t]of S)t.ok||S.delete(n)}function ot({probe:n="sync"}={}){return process.env.CHATPANEL_CLAUDE_PATH?B(process.env.CHATPANEL_CLAUDE_PATH,{probe:n}):B("claude",{probe:n})}function B(n,{probe:t="sync"}={}){if(!n)return null;if(n.includes("/")||n.includes("\\")||/\.[a-z0-9]+$/i.test(n)){if(!f(n))return null;const i=c.extname(n).toLowerCase();return!$()&&/^\.(c?js|mjs)$/.test(i)?{kind:"script",script:n}:process.platform==="win32"&&(i===".cmd"||i===".bat")?{kind:"cmd",bin:n}:process.platform==="win32"&&i===""&&!fn(n)?null:{kind:"native",bin:n}}if(process.platform==="win32"){const i=On(n);return i||(/^[\w.-]+$/.test(n)&&kn(n,{probe:t})?{kind:"wsl",command:n}:null)}const e=hn(n);return e?{kind:"native",bin:e}:null}const Sn="HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",Cn="HKCU\\Environment",Mn=4e3,In=3e5;let F=0,nn=0;function Tn(n,t="Path"){const o=String(t).toLowerCase();for(const e of String(n||"").split(/\r?\n/)){const i=/^\s*(\S+)\s+REG_(?:EXPAND_)?SZ\s+(.*?)\s*$/.exec(e);if(i&&i[1].toLowerCase()===o)return i[2]}return""}function tn(n,t=process.env){const o=new Map(Object.keys(t||{}).map(e=>[e.toLowerCase(),t[e]]));return String(n||"").replace(/%([^%]+)%/g,(e,i)=>{const r=o.get(String(i).toLowerCase());return r==null?e:String(r)})}function vn(n,t){try{const o=c.win32.join(process.env.SystemRoot||"C:\\Windows","System32","reg.exe"),e=w(f(o)?o:"reg",["query",n,"/v",t],{encoding:"utf8",timeout:3e3,windowsHide:!0});return e.status===0?Tn(e.stdout,t):""}catch{return""}}function yn({query:n=vn,env:t=process.env}={}){const o=tn(n(Sn,"Path"),t),e=tn(n(Cn,"Path"),t);return m([...d(o,"win32"),...d(e,"win32")])}function Ln({run:n=Hn}={}){const t=n(`[Console]::Out.Write("${b}\`t" + $env:PATH + "\`n")`);return d(T(t),"win32")}function Hn(n){for(const t of["pwsh.exe","powershell.exe"])try{const o=w(t,["-NoLogo","-NonInteractive","-ExecutionPolicy","Bypass","-Command",n],{encoding:"utf8",timeout:W,stdio:["ignore","pipe","ignore"],windowsHide:!0}),e=K(o.stdout||"");if(e)return e}catch{}return""}function en({force:n=!1,now:t=Date.now(),registry:o=yn,profile:e=Ln,env:i=process.env,home:r=j.homedir()}={}){if(process.platform!=="win32"&&!n||!n&&t-nn<Mn)return!1;nn=t;const s=d(i.PATH||"","win32"),l=m([...s,...o({env:i}),...G(r,"win32",i)]);t-F>=In&&R.some(u=>!l.some(p=>f(c.win32.join(p,`${u}.cmd`))||f(c.win32.join(p,`${u}.exe`))))&&(F=t,l.push(...e()));const a=Y(m(l),"win32");return a.length===s.length?!1:(i.PATH=a.join(V("win32")),!0)}function On(n){return on(n)||(en()?on(n):null)}function on(n){const t=C("win32");for(const o of dn(n,j.homedir(),"win32",process.env)){if(!f(o))continue;const e=t.dirname(o),i=t.extname(o).toLowerCase(),r=n==="claude"&&Dn(e)||Rn(e,n)||(/^\.(c?js|mjs)$/.test(i)?o:null);if(r){if(!$())return{kind:"script",script:r};const s=Nn(e);if(s)return{kind:"script",script:r,runtime:s}}if(i===".exe")return{kind:"native",bin:o};if(i===".cmd"||i===".bat")return{kind:"cmd",bin:o};if(i===""&&fn(o))return{kind:"native",bin:o}}return null}function Nn(n,{env:t=process.env,exists:o=f}={}){const e=c.win32,i=m([n,...d(t.PATH||"","win32"),...t.NVM_SYMLINK?[t.NVM_SYMLINK]:[],e.join(t.ProgramFiles||"C:\\Program Files","nodejs")]);for(const r of i){const s=e.join(r,"node.exe");if(o(s))return s}return null}function Dn(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 e=c.join(n,...o);if(f(e))return e}return null}function Rn(n,t){for(const o of[`${t}.cmd`,t,`${t}.ps1`]){let e;try{e=D(c.join(n,o),"utf8")}catch{continue}const i=e.match(/(?:%~?dp0%|\$basedir|\$\{basedir\})[\\/]+([^"'\s]+\.[cm]?js)/i);if(i){const r=c.join(n,i[1].replace(/[\\/]+/g,c.sep));if(f(r))return r}}return null}const S=new Map,N=new Map,$n=15e3,Wn=3e5,rn=8e3,sn=n=>["-e","bash","-lic",`command -v ${n}`];function cn(n,t){return n!==0?!1:(K(String(t||"")).replace(/\0/g,"").split(/\r?\n/).map(e=>e.trim()).filter(Boolean).pop()||"").startsWith("/")}function ln(n,t,o){const e=S.get(n),i=t?0:Math.min(e&&!e.ok&&e.ttl?e.ttl*2:$n,Wn);S.set(n,{ok:t,at:o,ttl:i})}function kn(n,{probe:t="sync",now:o=Date.now(),spawnSyncImpl:e=w,spawnImpl:i=X}={}){const r=S.get(n);if(r&&(r.ok||o-r.at<r.ttl))return r.ok;if(t==="async"){if(!N.has(n)){const l=new Promise(a=>{let u="",p;try{p=i("wsl.exe",sn(n),{windowsHide:!0,stdio:["ignore","pipe","ignore"]})}catch{a(!1);return}const P=setTimeout(()=>{try{p.kill()}catch{}},rn);p.stdout?.on("data",g=>{u+=g}),p.on("error",()=>{clearTimeout(P),a(!1)}),p.on("close",g=>{clearTimeout(P),a(cn(g,u))})}).then(a=>(ln(n,a,Date.now()),a)).finally(()=>N.delete(n));N.set(n,l)}return!1}let s=!1;try{const l=e("wsl.exe",sn(n),{encoding:"utf8",timeout:rn,windowsHide:!0});s=cn(l.status,l.stdout)}catch{s=!1}return ln(n,s,o),s}function it(n){return N.get(n)||null}function rt(n,t,o,e=null){const i=e&&typeof e=="object"&&Object.keys(e).length?{...process.env,...e}:process.env;if(n.kind==="wsl"){const s=[];if(o){const a=Bn(o);a&&s.push("--cd",a)}return["wsl.exe",[...s,"-e","bash","-lic",`exec ${n.command} "$@"`,"chatpanel",...t],{stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...U}]}const r={cwd:o||j.homedir(),stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...U};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 Bn(n){try{const t=w("wsl.exe",["-e","wslpath","-a",n],{encoding:"utf8",timeout:5e3,windowsHide:!0}),o=K(t.stdout||"").trim();return o.startsWith("/")?o:null}catch{return null}}function K(n){return n.replace(/^/,"").trim()}function Fn(n=j.homedir(),t=process.env){const o=c.join(t.NVM_DIR||c.join(n,".nvm"),"versions","node");let e;try{e=M(o).filter(r=>/^v\d+\./.test(r))}catch{return null}if(!e.length)return null;const i=(r,s)=>{const l=r.slice(1).split(".").map(Number),a=s.slice(1).split(".").map(Number);for(let u=0;u<3;u+=1)if((l[u]||0)!==(a[u]||0))return(a[u]||0)-(l[u]||0);return 0};try{const r=D(c.join(t.NVM_DIR||c.join(n,".nvm"),"alias","default"),"utf8").trim(),s=r.startsWith("v")?r:`v${r}`;if(e.includes(s))return c.join(o,s,"bin")}catch{}return c.join(o,e.sort(i)[0],"bin")}function Kn(n,t=process.env){return[c.join(t.MISE_DATA_DIR||c.join(n,".local","share","mise"),"shims"),c.join(n,".local","share","rtx","shims"),c.join(t.ASDF_DATA_DIR||c.join(n,".asdf"),"shims"),c.join(t.PYENV_ROOT||c.join(n,".pyenv"),"shims"),c.join(t.RBENV_ROOT||c.join(n,".rbenv"),"shims"),c.join(t.NODENV_ROOT||c.join(n,".nodenv"),"shims"),c.join(t.PROTO_HOME||c.join(n,".proto"),"shims"),c.join(t.PROTO_HOME||c.join(n,".proto"),"bin"),c.join(t.VOLTA_HOME||c.join(n,".volta"),"bin")]}function Vn(n,t=process.env){const o=[],e=(i,r)=>{try{for(const s of M(i))o.push(c.join(i,s,r))}catch{}};return e(c.join(t.NVM_DIR||c.join(n,".nvm"),"versions","node"),"bin"),e(c.join(n,".local","share","fnm","node-versions"),c.join("installation","bin")),e(c.join(n,"Library","Application Support","fnm","node-versions"),c.join("installation","bin")),e(c.join(t.MISE_DATA_DIR||c.join(n,".local","share","mise"),"installs","node"),"bin"),o}function C(n){return n==="win32"?c.win32:c}function V(n){return n==="win32"?";":c.delimiter}function d(n,t){return(n||"").split(V(t)).filter(Boolean)}function m(n){return[...new Set(n.filter(Boolean))]}const an={win32:3e4,other:65536};function Y(n,t=process.platform){const o=t==="win32"?an.win32:an.other,e=V(t),i=[];let r=0;for(const s of n){const l=s.length+(i.length?e.length:0);if(r+l>o)break;i.push(s),r+=l}return i}function G(n,t=process.platform,o=process.env){const e=C(t);if(t==="win32"){const i=o.APPDATA||e.join(n,"AppData","Roaming"),r=o.LOCALAPPDATA||e.join(n,"AppData","Local"),s=o.ProgramFiles||"C:\\Program Files",l=o["ProgramFiles(x86)"]||"C:\\Program Files (x86)",a=o.ProgramData||"C:\\ProgramData";return[e.join(n,".local","bin"),e.join(n,".codex","bin"),e.join(n,".claude","bin"),e.join(n,".claude","local"),e.join(n,".claude","local","bin"),e.join(i,"npm"),...o.NVM_SYMLINK?[o.NVM_SYMLINK]:[],e.join(s,"nodejs"),...Yn(i,r),e.join(r,"pnpm"),e.join(r,"Yarn","bin"),e.join(r,"Volta","bin"),e.join(n,".yarn","bin"),e.join(n,".bun","bin"),e.join(n,".deno","bin"),e.join(o.SCOOP||e.join(n,"scoop"),"shims"),e.join(a,"chocolatey","bin"),e.join(r,"Microsoft","WindowsApps"),e.join(r,"Microsoft","WinGet","Links"),e.join(o.MISE_DATA_DIR||e.join(r,"mise"),"shims"),e.join(o.PROTO_HOME||e.join(n,".proto"),"shims"),e.join(o.PROTO_HOME||e.join(n,".proto"),"bin"),e.join(r,"Programs","Claude Code"),e.join(r,"Anthropic","Claude Code"),e.join(s,"Claude Code"),e.join(s,"Anthropic","Claude Code"),e.join(l,"Claude Code"),e.join(l,"Anthropic","Claude Code")]}return[c.join(n,".local","bin"),c.join(n,".opencode","bin"),c.join(n,".codex","bin"),c.join(n,".claude","bin"),c.join(n,".claude","local"),c.join(n,".claude","local","bin"),o.PNPM_HOME||c.join(n,"Library","pnpm"),c.join(n,".local","share","pnpm"),c.join(n,".nix-profile","bin"),"/nix/var/nix/profiles/default/bin",c.join(n,".guix-profile","bin"),"/home/linuxbrew/.linuxbrew/bin","/snap/bin",...Kn(n,o)]}function Yn(n,t){const o=c.win32,e=[];for(const i of[o.join(t,"fnm"),o.join(n,"fnm")]){let r=[];try{r=M(o.join(i,"node-versions")).filter(s=>/^v?\d+\.\d+\.\d+/.test(s)).sort((s,l)=>l.localeCompare(s,void 0,{numeric:!0}))}catch{}for(const s of r)e.push(o.join(i,"node-versions",s,"installation"))}return e}function un(n,t=process.platform){const o=C(t),e=o.join(n,".local","share","claude","versions");let i=[];try{i=M(e).filter(r=>/^\d+\.\d+\.\d+/.test(r)).sort((r,s)=>s.localeCompare(r,void 0,{numeric:!0}))}catch{}return i.map(r=>o.join(e,r))}function pn(n,t){return t!=="win32"?[n]:/\.(cmd|exe|bat|ps1)$/i.test(n)?[n]:[`${n}.exe`,`${n}.cmd`,`${n}.bat`,n,`${n}.ps1`]}function fn(n,t=D){try{const o=t(n).subarray(0,2);return o.length===2&&o[0]===77&&o[1]===90}catch{return!1}}function Gn(n,t=j.homedir(),o=process.platform,e=process.env){const i=C(o),r=i.join(t,".local","bin",n),s=o==="win32"?e.LOCALAPPDATA||i.join(t,"AppData","Local"):null,l=o==="win32"?e.ProgramFiles||"C:\\Program Files":null,a=o==="win32"?e["ProgramFiles(x86)"]||"C:\\Program Files (x86)":null,u={claude:[r,i.join(t,".claude","bin","claude"),i.join(t,".claude","local","claude"),i.join(t,".claude","local","bin","claude"),...o==="win32"?[i.join(s,"Microsoft","WindowsApps","claude.exe"),i.join(s,"Programs","Claude Code","claude.exe"),i.join(s,"Anthropic","Claude Code","claude.exe"),i.join(l,"Claude Code","claude.exe"),i.join(l,"Anthropic","Claude Code","claude.exe"),i.join(a,"Claude Code","claude.exe"),i.join(a,"Anthropic","Claude Code","claude.exe"),...un(t,o)]:un(t,o)],codex:[r,i.join(t,".codex","bin","codex")],agy:[r,"/Applications/Antigravity.app/Contents/MacOS/agy","/Applications/Antigravity IDE.app/Contents/MacOS/agy"],pi:[r],opencode:[i.join(t,".opencode","bin","opencode"),r],"kiro-cli":[r,"/Applications/Kiro CLI.app/Contents/MacOS/kiro-cli"]};return m((u[n]||[r]).flatMap(p=>pn(p,o)))}function dn(n,t=j.homedir(),o=process.platform,e=process.env){const i=C(o),r=m([...d(e.PATH||"",o),...G(t,o,e)]).flatMap(s=>pn(i.join(s,n),o));return m([...r,...Gn(n,t,o,e)])}const mn=["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 st(){if(Q||(Q=!0,process.platform==="win32"))return;const n=mn.filter(t=>!process.env[t]);if(n.length)try{const t=v(),o=`${n.map(i=>`[ -n "\${${i}:-}" ] && printf '%s\\t%s\\n' ${i} "$${i}"`).join("; ")}; true`,e=w(t,["-l","-i","-c",o],{encoding:"utf8",timeout:6e3,env:{...process.env,TERM:"dumb"}});for(const i of String(e.stdout||"").split(`
|
|
2
|
+
`)){const r=i.indexOf(" ");if(r<=0)continue;const s=i.slice(0,r).trim(),l=i.slice(r+1);mn.includes(s)&&!process.env[s]&&l&&(process.env[s]=l)}}catch{}}function ct(){if(z)return;z=!0;const n=j.homedir();if(process.platform==="win32"){en({force:!0,home:n});return}const t=Fn(n),o=[...t?[t]:[],"/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"),...G(n),...Vn(n)];let e="";try{const s=v(),l=w(s,["-l","-c",'command -p echo "$PATH"'],{encoding:"utf8",timeout:4e3});l.status===0&&(e=(l.stdout||"").trim())}catch{}const i=new Set,r=[...t?[t]:[],...e?e.split(":"):[],...process.env.PATH?process.env.PATH.split(c.delimiter):[],...o].filter(s=>s&&!i.has(s)&&(i.add(s),!0));process.env.PATH=Y(r).join(c.delimiter),R.some(s=>!jn(s))&&k({force:!0})}export{R as AGENT_CLIS,Jn as agentAvailable,Gn as agentCandidateBins,G as agentInstallDirs,rt as buildSpawnSpec,Y as capPathList,dn as commandCandidateFiles,kn as commandInWsl,st as enrichAgentEnv,ct as enrichPath,tn as expandWindowsEnv,hn as findAgentBin,et as forgetMisses,$ as isCompiledBinary,fn as isWindowsExecutable,Nn as nodeRuntimeWindows,Fn as nvmCurrentBin,wn as parseEnvPath,Tn as parseRegValue,T as parseSentinel,Z as parseWhich,tt as primeAgentLookups,Ln as profilePathWindows,k as refreshShellPath,en as refreshWindowsPath,yn as registryPathWindows,nt as resetShellProbes,ot as resolveClaude,B as resolveCommand,Zn as selfMcpStdio,bn as shellPath,Bn as toWslPath,cn as wslAnswer,it as wslProbeInFlight};
|
package/src/health-snapshot.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function c({compute:
|
|
1
|
+
function c({compute:u,freshMs:s=1e4,now:l=()=>Date.now(),defer:f=e=>setImmediate(e)}={}){let e=null,t=null,n=!1;const r=()=>(t||=Promise.resolve().then(u).then(a=>(e={at:l(),value:a},e)).finally(()=>{t=null}),t);return{async get({fresh:a=!1}={}){return!e||a?r():(l()-e.at>s&&!t&&!n&&(n=!0,f(()=>{n=!1,r().catch(()=>{})})),e)},warm(){e||r().catch(()=>{})}}}export{c as createSnapshot};
|
package/src/pii/pii-detect.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{assertEndpointUrl as D}from"./net.js";const A=new Map,m=300;function G(){A.clear()}function T(e,t){let o=5381;const r=`${t?.backend}|${t?.url}|${t?.model}|${t?.strictness||""}|${JSON.stringify(t?.types||null)}|${e}`;for(let n=0;n<r.length;n++)o=(o<<5)+o+r.charCodeAt(n)|0;return`${r.length}:${o}`}function p(e,t,o){return new Promise((r,n)=>{const
|
|
1
|
+
import{assertEndpointUrl as D}from"./net.js";const A=new Map,m=300;function G(){A.clear()}function T(e,t){let o=5381;const r=`${t?.backend}|${t?.url}|${t?.model}|${t?.strictness||""}|${JSON.stringify(t?.types||null)}|${e}`;for(let n=0;n<r.length;n++)o=(o<<5)+o+r.charCodeAt(n)|0;return`${r.length}:${o}`}function p(e,t,o){return new Promise((r,n)=>{const i=setTimeout(()=>n(new Error("detect timeout")),Math.max(200,t||1500)),s=()=>{clearTimeout(i),n(new Error("aborted"))};o&&o.addEventListener?.("abort",s,{once:!0}),e.then(c=>{clearTimeout(i),r(c)},c=>{clearTimeout(i),n(c)})})}function y(e){const t=String(e||"ENTITY").toUpperCase().replace(/[^A-Z0-9]/g,"")||"ENTITY";return{PER:"PERSON",PERSON:"PERSON",PERSONNAME:"PERSON",PRIVATEPERSON:"PERSON",GIVENNAME:"PERSON",FIRSTNAME:"PERSON",MIDDLENAME:"PERSON",SURNAME:"PERSON",LASTNAME:"PERSON",FULLNAME:"PERSON",ORG:"ORG",ORGANIZATION:"ORG",COMPANYNAME:"ORG",COMPANY:"ORG",GPE:"LOCATION",LOC:"LOCATION",LOCATION:"LOCATION",CITY:"LOCATION",STATE:"LOCATION",COUNTY:"LOCATION",COUNTRY:"LOCATION",STREET:"ADDRESS",BUILDINGNUM:"ADDRESS",BUILDINGNUMBER:"ADDRESS",ZIPCODE:"ADDRESS",POSTCODE:"ADDRESS",SECADDRESS:"ADDRESS",ADDRESS:"ADDRESS",PRIVATEADDRESS:"ADDRESS",NORP:"GROUP",EMAIL:"EMAIL",EMAILADDRESS:"EMAIL",PRIVATEEMAIL:"EMAIL",PHONE:"PHONE",PHONENUMBER:"PHONE",TELEPHONENUM:"PHONE",PRIVATEPHONE:"PHONE",PHONEIMEI:"ID",SOCIALNUM:"SSN",USSSN:"SSN",SSN:"SSN",CREDITCARDNUMBER:"CREDITCARD",CREDITCARD:"CREDITCARD",IBAN:"IBAN",IBANCODE:"IBAN",ACCOUNTNUM:"ID",ACCOUNTNUMBER:"ID",TAXNUM:"ID",IDCARDNUM:"ID",DRIVERLICENSENUM:"ID",PASSPORTNUM:"ID",VEHICLEVRM:"ID",DATEOFBIRTH:"ID",DOB:"ID",PRIVATEDATE:"ID",PRIVATEURL:"ID",USERNAME:"ID",USERID:"ID",IP:"ID",IPADDRESS:"ID",MAC:"ID",PASSWORD:"SECRET",APIKEY:"SECRET",SECRET:"SECRET"}[t]||t}const w=new Set(["EMAIL","PHONE","SSN","CREDITCARD","IBAN","ID","SECRET"]),C=new Set(["LOCATION","FAC","ADDRESS","GROUP","NRP"]),d=/(?:^|[\s$€£])\$?\d+(?:[.,]\d+)?\s?(?:[kmb]n?|mm|million|billion|thousand|%)(?=[\s.,;:!?)]|$)/i,P=/(?:^|\s)\d{1,6}(?=\s|,|$)/;function g(e){const t=String(e||"").trim();return d.test(t)&&!P.test(t)}const Y=Object.freeze(["balanced","strict"]),L=e=>e?.strictness==="strict"||e?.detection?.strictness==="strict"?"strict":"balanced";function b(e,t,o,r="balanced"){const n=s=>!o||o[s]!==!1;return r!=="strict"&&t==="ADDRESS"&&g(e)?!1:w.has(t)?!0:t==="PERSON"?n("person"):t==="ORG"?n("org"):C.has(t)?n("location"):(String(e).match(/\d/g)||[]).length>=7?n("number"):!1}function R(e,t,{strictness:o="balanced"}={}){let r=[];Array.isArray(e)?r=e:e&&Array.isArray(e.entities)?r=e.entities:e&&Array.isArray(e.ents)?r=e.ents:e&&Array.isArray(e.results)&&(r=e.results);const n=[],i=new Set;for(const s of r){if(!s)continue;const c=String(s.value??s.text??s.entity??s.word??"").trim(),a=y(s.type??s.label??s.entity_group??s.entity_type??s.tag);if(!c||c.length>200||!b(c,a,t,o))continue;const l=`${a}:${c.toLowerCase()}`;i.has(l)||(i.add(l),n.push({value:c,type:a}))}return n}const M=new Set("a an the i am is are was were be been being to of in on at for and or but if so not no yes ok okay hi hello hey you your yours me my mine we us our ours they them their he him his she her it its this that these those what where when who whom why how which do does did done have has had having will would can could should may might must shall there here now then last next first time day days week month year today tomorrow yesterday see saw seen say said tell told go went gone come came get got give gave take took make made know knew think thought want need like just also very really with from into onto over under about after before between through during without within up down out off again still used use using live lived move moved work worked help please thanks thank sorry new old good bad more most some any all each because as than too so such only own same other another much many few both either neither every never always often".split(/\s+/));function V(e){const t=String(e||"");let o=!1;return{text:t.replace(new RegExp("(^|[^\\p{L}\\p{N}'’])(\\p{Ll})(\\p{L}*)","gu"),(n,i,s,c)=>{const a=s+c;if(M.has(a))return n;const l=s.toUpperCase();return l.length!==1||l===s?n:(o=!0,i+l+c)}),changed:o}}function U(e){if(!e)return null;const t=String(e).indexOf("{"),o=String(e).lastIndexOf("}");if(t<0||o<=t)return null;try{return JSON.parse(String(e).slice(t,o+1))}catch{return null}}const k="You extract sensitive entities from text for redaction. Copy each value exactly as it appears. Include people, organizations, locations, and account/ID numbers. No commentary, no code fences.",$='Return ONLY JSON: {"entities":[{"value":"<verbatim text>","type":"PERSON|ORG|LOCATION|ID|EMAIL|PHONE|OTHER"}]}. No commentary, no code fences.',f=Object.freeze({block:"",format:null,parse:null});async function x(e,t,o,r){const n=await r(t.url,{method:"POST",headers:{"Content-Type":"application/json",...t.apiKey?{Authorization:`Bearer ${t.apiKey}`}:{}},body:JSON.stringify({text:e,...t.strictness==="strict"?{strict:!0}:{}}),signal:o});if(!n.ok)throw new Error(`detect HTTP ${n.status}`);return R(await n.json(),t.types,{strictness:t.strictness})}async function v(e,t,o,r,n=f){const i=String(t.url||"").replace(/\/$/,""),s=/\/chat\/completions$/.test(i)?i:/\/v\d+$/.test(i)?`${i}/chat/completions`:`${i}/v1/chat/completions`,c=`${k}
|
|
2
2
|
|
|
3
|
-
${n.block||$}`,
|
|
3
|
+
${n.block||$}`,a=async S=>{const E=n.format?n.format(S):null,u=await r(s,{method:"POST",headers:{"Content-Type":"application/json",...t.apiKey?{Authorization:`Bearer ${t.apiKey}`}:{}},body:JSON.stringify({model:t.model||"local",temperature:0,max_tokens:t.maxTokens||256,messages:[{role:"system",content:c},{role:"user",content:e}],...E||{}}),signal:o});if(!u.ok){const O=new Error(`detect HTTP ${u.status}`);throw O.status=u.status,O}return u.json()};let l=null;if(n.format)for(const S of["schema","object","none"])try{l=await a(S);break}catch(E){if(S==="none"||E.status!==400&&E.status!==422)throw E}else l=await a("none");const h=l?.choices?.[0]?.message?.content??l?.content??"",N=n.parse?n.parse(h):U(h);return R(N,t.types,{strictness:t.strictness})}function I(e,t,o,r,n,i){if(typeof e=="function")try{e({backend:t.backend||"",host:H(t.url),chars:o.length,entities:n,ms:Date.now()-r,ok:!i,error:i?String(i.message||i).slice(0,200):""})}catch{}}const H=e=>{try{return new URL(String(e)).host}catch{return""}};async function _(e,t,{signal:o,fetchImpl:r=globalThis.fetch,strict:n=!1,structured:i=f,onEgress:s=null,onError:c=null}={}){const a=t?.detection?{...t.detection,strictness:L(t)}:null;if(!a||!a.backend||a.backend==="off"||!a.url||typeof r!="function")return[];const l=a.transport==="in-process";if(l&&r===globalThis.fetch)throw new Error("detection.transport 'in-process' needs an injected fetch; refusing to treat a network call as in-process");const h=String(e||"").slice(0,a.maxChars||8e3);if(h.trim().length<8)return[];const N=T(h,a);if(!n&&A.has(N))return A.get(N);const S=a.backend==="endpoint"?x:v;let E=[];try{l||D(a.url);const u=Date.now();try{E=await p(S(h,a,o,r,i),a.timeoutMs||1500,o),l||I(s,a,h,u,E.length,null)}catch(O){throw l||I(s,a,h,u,0,O),O}}catch(u){if(n)throw u;try{c?.(u)}catch{}return[]}return A.size>=m&&A.clear(),n||A.set(N,E),E}export{k as EXTRACT_SYS,Y as REDACTION_STRICTNESS,G as clearDetectCache,_ as detectEntities,y as normType,R as normalizeEntities,U as parseJsonLoose,g as quantityNotAddress,V as recaseForDetection,L as strictnessOf,p as withTimeout};
|
package/src/server.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createServer as xe}from"node:http";import v from"node:os";import{randomBytes as Pe,randomInt as $e,timingSafeEqual as Re}from"node:crypto";import{mkdirSync as Ie,writeFileSync as Ne,readFileSync as Q,existsSync as De}from"node:fs";import{join as _}from"node:path";import*as _e from"./engines/claude.js";import*as He from"./engines/codex.js";import*as Me from"./engines/antigravity.js";import{pi as Be,opencode as Ue,kiro as We,copilot as Le,deepseek as Ge,hermes as je}from"./engines/cli-agents.js";import{connectorsFor as Fe}from"./connectors.js";import*as Je from"./engines/custom.js";import{installService as Xe,uninstallService as ze,serviceStatus as Ke,restartService as Z}from"./service.js";import{skillIndex as L,listRecords as Ye,readRecord as Ve,readPackageFile as Qe,skillsHealth as Ze,quarantinedSkills as qe,clearSkillCache as G}from"./skills.js";import{writeSkillPackage as et,writeSkillFile as tt,deleteSkillPackage as nt,SkillWriteError as ot}from"./skill-write.js";import{agentDefRoots as rt,scanAgentDefs as at,listAgentDefs as it,readAgentDef as st,planAgentExport as ct,exportAgentDef as lt,agentDefsHealth as dt,AgentDefError as ut}from"./agent-defs.js";import{capabilityToolSpecs as ht,runCapabilityTool as pt}from"./mcp-capabilities.js";import{createSession as ft,deleteSession as q,getSession as ee,activeSession as mt,relayToolCall as gt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as yt,isDefaultWorkdir as wt,resolveWorkdir as St,writeScopeNote as bt}from"./workdir.js";import{sandbox as te,runSandboxCli as kt,withGrant as ne,withoutOutsideWhenCapped as Tt,grantedWriteRoots as Et,acceptRefusalReport as vt,liveProcesses as Ot}from"./sandbox.js";import{gitState as At,gitDelta as Ct}from"./scm.js";import{listConnections as xt,putConnection as Pt,removeConnection as $t,runEnvFor as Rt,testConnection as It,secretBackend as oe}from"./connections.js";import{worktreeFor as re,listWorktrees as Nt,removeWorktree as Dt,withHook as _t,WORKTREE_ROOT as ae}from"./worktree.js";import{AGENT_CLIS as Ht,agentAvailable as Mt,agentInstallDirs as Bt,enrichPath as Ut,enrichAgentEnv as Wt,findAgentBin as Lt,resolveCommand as ie}from"./env.js";import"./sanitize.js";import{checkForUpdate as Gt,selfUpdate as se,isEmbedded as ce}from"./update.js";import{callLocalMcp as jt,localMcpStatus as Ft,signInLocalMcp as Jt,signInStatusLocalMcp as Xt}from"./mcp-local.js";import{assertPublicHttpUrl as le,assertPublicWebUrl as de}from"./ssrf.js";import{startRun as ue,endRun as j,cancelRun as zt,cancelAll as Kt}from"./runs.js";import{closeWarmPools as Yt,warmStatus as Vt}from"./warm.js";import{SESSION_AGENTS as he,listSessions as Qt,readSession as Zt,adoptSession as qt,catchUp as en}from"./agent-sessions.js";import{agentContext as tn}from"./agent-context.js";import{normalizeThread as pe}from"./events/agent-thread.js";import{portClashPlan as nn,serviceManagerOf as on,STANDBY_POLL_MS as rn}from"./events/service-standby.js";import{holdThread as fe}from"./threads.js";import{createSnapshot as an}from"./health-snapshot.js";import{CompatError as R,anthropicError as F,anthropicStream as sn,chatCompletionStream as cn,completionStream as ln,createAnthropicMessage as dn,createChatCompletion as un,createCompletion as hn,createResponse as pn,openAIError as S,parseAnthropicMessage as fn,parseChatCompletion as mn,parseCompletion as gn,parseResponse as yn,responseStream as wn}from"./api-compat.js";import{callerTrust as Sn,isPaired as I,parseExtensionIds as bn,capRunOptions as kn,engineHonoursReach as Tn,createPairingStore as En,formatPairingCode as vn}from"./pii/trust.js";const g="0.44.0",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",b=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,O={claude:{engine:_e,label:"Claude Code"},codex:{engine:He,label:"Codex"},antigravity:{engine:Me,label:"Antigravity",tools:!1},pi:{engine:Be,label:"Pi"},opencode:{engine:Ue,label:"OpenCode"},hermes:{engine:je,label:"Hermes"},kiro:{engine:We,label:"Kiro"},copilot:{engine:Le,label:"GitHub Copilot"},deepseek:{engine:Ge,label:"DeepSeek Harness"},custom:{engine:Je,label:"Custom",hidden:!0}};function me(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 On=bn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Sn({origin:n.headers.origin||"",hasToken:Se(n),extensionIds:On})),n.chatpanelTrust}function An(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 Cn(n,e){const t=n.headers.origin||"",o=me(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function xn(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 D=_(v.homedir(),".chatpanel","bridge-token");let T="";function Pn(){try{De(D)&&(T=Q(D,"utf8").trim()),T||(T=Pe(32).toString("hex"),Ie(_(v.homedir(),".chatpanel"),{recursive:!0}),Ne(D,T,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const ge=En({random:()=>$e(0,1e6)/1e6});function $n(n){if(!T)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ge.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 Rn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=ge.claim(t?.code);return o.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:T})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function In(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:g})}let H=null;async function ye(){if(H)return H;const{createChannelService:n}=await import("./channels/service.js");return H=n({home:_(v.homedir(),".chatpanel"),dataDir:_(v.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${b}`,token:T},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function we(n,e,t){try{const o=await ye(),r=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await o.status());if(t==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await o.pair()):t==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?i(e,200,await o.update(r)):t==="disconnect"?i(e,200,await o.stop({forget:!!r.forget})):i(e,404,{error:"unknown channel action"})}catch(o){return i(e,400,{error:o?.message||String(o)})}}function Se(n){if(!T)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(T);return o.length===r.length&&Re(o,r)}const Nn=new Set(["/agent-context","/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/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"]),Dn=new Set(["/debug"]),_n=n=>Dn.has(n),Hn=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function Mn(n,e){if(!xn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!me(t))return"forbidden origin";const o=n.method==="POST"&&Nn.has(e)||n.method==="GET"&&_n(e)||Hn(n.method,e);return o&&!(An(t)||Se(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!Un.has(e)?Bn:null}const be=()=>ce()?"chatpanel-gateway pair":"chatpanel-bridge pair",Bn=`forbidden: this client is not paired with the bridge — run \`${be()}\` and enter the code in ChatPanel Settings`,Un=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function X(n,e,t){const o=N(n),r=Tt(kn(t,o));if(!Tn(e,r.reach))return{error:`${I(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(o)?"raise the tier":`pair this client (${be()})`} to use ${e}`};const a=r.reach,s=I(o)?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 → Coding Agents to unlock them.";return{options:r,note:s}}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function m(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}const ke=an({compute:Wn});async function Wn(){const n=await Promise.all(Object.entries(O).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:c,tools:l}])=>{const d=await s.available().catch(y=>({ok:!1,reason:String(y?.message||y)})),h=await Fe(a).catch(()=>[]);return{id:a,label:c,available:d.ok,reason:d.reason,connectors:h,...l===!1?{tools:!1}:{}}})),e=ce()?{current:g,updateAvailable:!1,embedded:"gateway"}:await Gt(g).catch(()=>({current:g,updateAvailable:!1})),t=await Ze().catch(()=>null),o=await dt().catch(()=>null),r=await te().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:o,sandboxStatus:r}}async function Ln(n,{fresh:e=!1}={}){const{at:t,value:{agents:o,update:r,skills:a,agentDefs:s,sandboxStatus:c}}=await ke.get({fresh:e});i(n,200,{ok:!0,version:g,agents:o,update:r,checkedAt:t,workspace:yt,sandbox:c,localMcp:Ft(),processes:Ot(),worktrees:ae,secretBackend:oe(),warm:Vt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...a?{skills:a}:{},...s?{agentDefs:s}:{}})}async function Gn(n,e,t){const{index:o,problems:r}=await L({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:Ye(o),problems:r})}async function jn(n,e,t){i(n,200,{ok:!0,quarantined:await qe(e,t)})}async function Fn(n,e,t,o){const{index:r}=await L({extraDirs:t,workdir:o}),a=Ve(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function Jn(n,e,t,o,r){const{index:a}=await L({extraDirs:o,workdir:r}),s=await Qe(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 Xn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{const o=await et({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return G(),i(e,200,o)}catch(o){return i(e,z(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function zn(n,e,t,o){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}try{const a=await tt({name:t,path:o,text:r?.text??""});return G(),i(e,200,a)}catch(a){return i(e,z(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function Kn(n,e){try{const t=await nt({name:e});return G(),i(n,200,t)}catch(t){return i(n,z(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function z(n){return n instanceof ot?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Te(n,e){return at({roots:rt(process.env,v.homedir(),n,e)})}async function Yn(n,e,t){const{index:o,quarantined:r,problems:a}=await Te(e,t);i(n,200,{ok:!0,agents:it(o),...r.length?{quarantined:r.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...a.length?{problems:a}:{}})}async function Vn(n,e,t,o){const{index:r}=await Te(t,o),a=st(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function Qn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,{ok:!0,...await ct({agent:t?.agent,to:t?.to})})}catch(o){return i(e,Ee(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function Zn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,await lt({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(o){return i(e,Ee(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}function Ee(n){if(n instanceof ut){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function qn(){return(await Promise.all(Object.entries(O).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 ve(n,e=""){const t=await qn();if(e){const o=t.find(r=>r.id===e);return o?i(n,200,o):i(n,404,S(new R(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function eo(n){try{const e=await se(g);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>Z(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function to(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=X(n,t.agent,t.options||{});if(r.error)return i(e,403,{error:r.error});t.options=r.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=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
|
|
2
|
+
import{createServer as xe}from"node:http";import v from"node:os";import{randomBytes as Pe,randomInt as $e,timingSafeEqual as Re}from"node:crypto";import{mkdirSync as Ie,writeFileSync as Ne,readFileSync as Q,existsSync as De}from"node:fs";import{join as _}from"node:path";import*as _e from"./engines/claude.js";import*as He from"./engines/codex.js";import*as Me from"./engines/antigravity.js";import{pi as Be,opencode as Ue,kiro as We,copilot as Le,deepseek as Ge,hermes as je}from"./engines/cli-agents.js";import{connectorsFor as Fe}from"./connectors.js";import*as Je from"./engines/custom.js";import{installService as Xe,uninstallService as ze,serviceStatus as Ke,restartService as Z}from"./service.js";import{skillIndex as L,listRecords as Ye,readRecord as Ve,readPackageFile as Qe,skillsHealth as Ze,quarantinedSkills as qe,clearSkillCache as G}from"./skills.js";import{writeSkillPackage as et,writeSkillFile as tt,deleteSkillPackage as nt,SkillWriteError as ot}from"./skill-write.js";import{agentDefRoots as rt,scanAgentDefs as at,listAgentDefs as it,readAgentDef as st,planAgentExport as ct,exportAgentDef as lt,agentDefsHealth as dt,AgentDefError as ut}from"./agent-defs.js";import{capabilityToolSpecs as ht,runCapabilityTool as pt}from"./mcp-capabilities.js";import{createSession as ft,deleteSession as q,getSession as ee,activeSession as mt,relayToolCall as gt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as yt,isDefaultWorkdir as wt,resolveWorkdir as St,writeScopeNote as bt}from"./workdir.js";import{sandbox as te,runSandboxCli as kt,withGrant as ne,withoutOutsideWhenCapped as Tt,grantedWriteRoots as Et,acceptRefusalReport as vt,liveProcesses as Ot}from"./sandbox.js";import{gitState as At,gitDelta as Ct}from"./scm.js";import{listConnections as xt,putConnection as Pt,removeConnection as $t,runEnvFor as Rt,testConnection as It,secretBackend as oe}from"./connections.js";import{worktreeFor as re,listWorktrees as Nt,removeWorktree as Dt,withHook as _t,WORKTREE_ROOT as ae}from"./worktree.js";import{AGENT_CLIS as Ht,agentAvailable as Mt,agentInstallDirs as Bt,enrichPath as Ut,enrichAgentEnv as Wt,findAgentBin as Lt,forgetMisses as Gt,primeAgentLookups as jt,resolveCommand as ie}from"./env.js";import"./sanitize.js";import{checkForUpdate as Ft,selfUpdate as se,isEmbedded as ce}from"./update.js";import{callLocalMcp as Jt,localMcpStatus as Xt,signInLocalMcp as zt,signInStatusLocalMcp as Kt}from"./mcp-local.js";import{assertPublicHttpUrl as le,assertPublicWebUrl as de}from"./ssrf.js";import{startRun as ue,endRun as j,cancelRun as Yt,cancelAll as Vt}from"./runs.js";import{closeWarmPools as Qt,warmStatus as Zt}from"./warm.js";import{SESSION_AGENTS as he,listSessions as qt,readSession as en,adoptSession as tn,catchUp as nn}from"./agent-sessions.js";import{agentContext as on}from"./agent-context.js";import{normalizeThread as pe}from"./events/agent-thread.js";import{portClashPlan as rn,serviceManagerOf as an,STANDBY_POLL_MS as sn}from"./events/service-standby.js";import{holdThread as fe}from"./threads.js";import{createSnapshot as cn}from"./health-snapshot.js";import{CompatError as R,anthropicError as F,anthropicStream as ln,chatCompletionStream as dn,completionStream as un,createAnthropicMessage as hn,createChatCompletion as pn,createCompletion as fn,createResponse as mn,openAIError as S,parseAnthropicMessage as gn,parseChatCompletion as yn,parseCompletion as wn,parseResponse as Sn,responseStream as bn}from"./api-compat.js";import{callerTrust as kn,isPaired as I,parseExtensionIds as Tn,capRunOptions as En,engineHonoursReach as vn,createPairingStore as On,formatPairingCode as An}from"./pii/trust.js";const g="0.44.2",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",b=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,O={claude:{engine:_e,label:"Claude Code"},codex:{engine:He,label:"Codex"},antigravity:{engine:Me,label:"Antigravity",tools:!1},pi:{engine:Be,label:"Pi"},opencode:{engine:Ue,label:"OpenCode"},hermes:{engine:je,label:"Hermes"},kiro:{engine:We,label:"Kiro"},copilot:{engine:Le,label:"GitHub Copilot"},deepseek:{engine:Ge,label:"DeepSeek Harness"},custom:{engine:Je,label:"Custom",hidden:!0}};function me(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 Cn=Tn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=kn({origin:n.headers.origin||"",hasToken:Se(n),extensionIds:Cn})),n.chatpanelTrust}function xn(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 Pn(n,e){const t=n.headers.origin||"",o=me(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function $n(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 D=_(v.homedir(),".chatpanel","bridge-token");let T="";function Rn(){try{De(D)&&(T=Q(D,"utf8").trim()),T||(T=Pe(32).toString("hex"),Ie(_(v.homedir(),".chatpanel"),{recursive:!0}),Ne(D,T,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const ge=On({random:()=>$e(0,1e6)/1e6});function In(n){if(!T)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ge.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 Nn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=ge.claim(t?.code);return o.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:T})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function Dn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:g})}let H=null;async function ye(){if(H)return H;const{createChannelService:n}=await import("./channels/service.js");return H=n({home:_(v.homedir(),".chatpanel"),dataDir:_(v.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${b}`,token:T},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function we(n,e,t){try{const o=await ye(),r=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await o.status());if(t==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await o.pair()):t==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?i(e,200,await o.update(r)):t==="disconnect"?i(e,200,await o.stop({forget:!!r.forget})):i(e,404,{error:"unknown channel action"})}catch(o){return i(e,400,{error:o?.message||String(o)})}}function Se(n){if(!T)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(T);return o.length===r.length&&Re(o,r)}const _n=new Set(["/agent-context","/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/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"]),Hn=new Set(["/debug"]),Mn=n=>Hn.has(n),Bn=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function Un(n,e){if(!$n(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!me(t))return"forbidden origin";const o=n.method==="POST"&&_n.has(e)||n.method==="GET"&&Mn(e)||Bn(n.method,e);return o&&!(xn(t)||Se(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!Ln.has(e)?Wn:null}const be=()=>ce()?"chatpanel-gateway pair":"chatpanel-bridge pair",Wn=`forbidden: this client is not paired with the bridge — run \`${be()}\` and enter the code in ChatPanel Settings`,Ln=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function X(n,e,t){const o=N(n),r=Tt(En(t,o));if(!vn(e,r.reach))return{error:`${I(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(o)?"raise the tier":`pair this client (${be()})`} to use ${e}`};const a=r.reach,s=I(o)?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 → Coding Agents to unlock them.";return{options:r,note:s}}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function m(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}const ke=cn({compute:Gn});async function Gn(){await jt();const n=await Promise.all(Object.entries(O).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:c,tools:l}])=>{const d=await s.available().catch(y=>({ok:!1,reason:String(y?.message||y)})),h=await Fe(a).catch(()=>[]);return{id:a,label:c,available:d.ok,reason:d.reason,connectors:h,...l===!1?{tools:!1}:{}}})),e=ce()?{current:g,updateAvailable:!1,embedded:"gateway"}:await Ft(g).catch(()=>({current:g,updateAvailable:!1})),t=await Ze().catch(()=>null),o=await dt().catch(()=>null),r=await te().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:o,sandboxStatus:r}}async function jn(n,{fresh:e=!1}={}){e&&Gt();const{at:t,value:{agents:o,update:r,skills:a,agentDefs:s,sandboxStatus:c}}=await ke.get({fresh:e});i(n,200,{ok:!0,version:g,agents:o,update:r,checkedAt:t,workspace:yt,sandbox:c,localMcp:Xt(),processes:Ot(),worktrees:ae,secretBackend:oe(),warm:Zt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...a?{skills:a}:{},...s?{agentDefs:s}:{}})}async function Fn(n,e,t){const{index:o,problems:r}=await L({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:Ye(o),problems:r})}async function Jn(n,e,t){i(n,200,{ok:!0,quarantined:await qe(e,t)})}async function Xn(n,e,t,o){const{index:r}=await L({extraDirs:t,workdir:o}),a=Ve(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function zn(n,e,t,o,r){const{index:a}=await L({extraDirs:o,workdir:r}),s=await Qe(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 Kn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{const o=await et({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return G(),i(e,200,o)}catch(o){return i(e,z(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function Yn(n,e,t,o){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}try{const a=await tt({name:t,path:o,text:r?.text??""});return G(),i(e,200,a)}catch(a){return i(e,z(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function Vn(n,e){try{const t=await nt({name:e});return G(),i(n,200,t)}catch(t){return i(n,z(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function z(n){return n instanceof ot?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Te(n,e){return at({roots:rt(process.env,v.homedir(),n,e)})}async function Qn(n,e,t){const{index:o,quarantined:r,problems:a}=await Te(e,t);i(n,200,{ok:!0,agents:it(o),...r.length?{quarantined:r.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...a.length?{problems:a}:{}})}async function Zn(n,e,t,o){const{index:r}=await Te(t,o),a=st(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function qn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,{ok:!0,...await ct({agent:t?.agent,to:t?.to})})}catch(o){return i(e,Ee(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function eo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,await lt({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(o){return i(e,Ee(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}function Ee(n){if(n instanceof ut){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function to(){return(await Promise.all(Object.entries(O).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 ve(n,e=""){const t=await to();if(e){const o=t.find(r=>r.id===e);return o?i(n,200,o):i(n,404,S(new R(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function no(n){try{const e=await se(g);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>Z(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function oo(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=X(n,t.agent,t.options||{});if(r.error)return i(e,403,{error:r.error});t.options=r.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=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
|
|
3
3
|
|
|
4
|
-
`)};let s=!1;const c=`run_${Math.random().toString(36).slice(2,10)}`,l=ue(c),d={signal:l.signal,abort:()=>l.cancel("client")},h=()=>{s=!0,l.cancel("disconnected")};n.on("close",h),e.on("close",h),e.on("error",h);const y=p=>{s||a(p)};a({type:"run",id:c}),r.note&&a({type:"status",text:r.note});let f=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const p=t.options.workspace;if(f=await re({repo:p.repo,projectId:p.projectId,jobId:p.jobId,base:p.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),j(c),e.writableEnded||e.end();return}}const Y=f?f.path:St(t.options?.workingDir);let A=null;{const p=Y,C=!!f||!wt(t.options?.workingDir),w=bt(t.agent,t.options?.permissionMode,p,Et(p,{grant:t.options?.sandbox}));a({type:"workdir",path:p,isDefault:!C,writeScope:w||void 0}),a({type:"status",text:`Working in ${p}${C?"":" (default)"}`}),w&&a({type:"status",text:w}),A=await At(p),A&&a({type:"scm",phase:"before",...A})}let W=null;if(A||f){const p=Array.isArray(t.options?.grants)?t.options.grants:[],{env:C,connection:w}=Rt({remote:A?.remote||null,grants:p,branch:f?.branch||null,connectionId:t.options?.connectionId||null});W=_t(C),f&&a({type:"workspace",path:f.path,branch:f.branch,base:f.base,created:f.created,repo:f.repo,...w?{connection:w}:{}}),w&&a({type:"status",text:`Git credential: ${w.kind} · ${w.host}${w.hasSecret?"":" (no token stored)"} · push: ${C.CHATPANEL_SCM_PUSH==="own"?`${f?.branch} only`:C.CHATPANEL_SCM_PUSH}`})}const V=t.approvals===!0,P={...t.options||{},...f?{workingDir:f.path}:{},...W?{runEnv:W}:{},approvals:V};let $=null;(t.pageTools?.specs?.length||V)&&($=ft(y,t.pageTools?.specs||[]),P.permissionSession=$,t.pageTools?.specs?.length&&(P.mcp={url:`http://${k}:${b}/mcp/${$.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));try{await ne(P.sandbox,()=>fe(t.agent,P,d.signal,()=>o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:P,images:Array.isArray(t.images)?t.images:[]},y,{signal:d.signal})))}catch(p){u("error",`${t.agent} chat failed: ${p?.message||p}`),p?.detail&&u("error",`${t.agent} said: ${p.detail}`),a({type:"error",error:p?.message||String(p)})}finally{if(!s){const p=await Ct(Y,A).catch(()=>null);p&&y({type:"scm",phase:"after",...p})}j(c),$&&q($.id),e.writableEnded||e.end()}}async function
|
|
4
|
+
`)};let s=!1;const c=`run_${Math.random().toString(36).slice(2,10)}`,l=ue(c),d={signal:l.signal,abort:()=>l.cancel("client")},h=()=>{s=!0,l.cancel("disconnected")};n.on("close",h),e.on("close",h),e.on("error",h);const y=p=>{s||a(p)};a({type:"run",id:c}),r.note&&a({type:"status",text:r.note});let f=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const p=t.options.workspace;if(f=await re({repo:p.repo,projectId:p.projectId,jobId:p.jobId,base:p.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),j(c),e.writableEnded||e.end();return}}const Y=f?f.path:St(t.options?.workingDir);let A=null;{const p=Y,C=!!f||!wt(t.options?.workingDir),w=bt(t.agent,t.options?.permissionMode,p,Et(p,{grant:t.options?.sandbox}));a({type:"workdir",path:p,isDefault:!C,writeScope:w||void 0}),a({type:"status",text:`Working in ${p}${C?"":" (default)"}`}),w&&a({type:"status",text:w}),A=await At(p),A&&a({type:"scm",phase:"before",...A})}let W=null;if(A||f){const p=Array.isArray(t.options?.grants)?t.options.grants:[],{env:C,connection:w}=Rt({remote:A?.remote||null,grants:p,branch:f?.branch||null,connectionId:t.options?.connectionId||null});W=_t(C),f&&a({type:"workspace",path:f.path,branch:f.branch,base:f.base,created:f.created,repo:f.repo,...w?{connection:w}:{}}),w&&a({type:"status",text:`Git credential: ${w.kind} · ${w.host}${w.hasSecret?"":" (no token stored)"} · push: ${C.CHATPANEL_SCM_PUSH==="own"?`${f?.branch} only`:C.CHATPANEL_SCM_PUSH}`})}const V=t.approvals===!0,P={...t.options||{},...f?{workingDir:f.path}:{},...W?{runEnv:W}:{},approvals:V};let $=null;(t.pageTools?.specs?.length||V)&&($=ft(y,t.pageTools?.specs||[]),P.permissionSession=$,t.pageTools?.specs?.length&&(P.mcp={url:`http://${k}:${b}/mcp/${$.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));try{await ne(P.sandbox,()=>fe(t.agent,P,d.signal,()=>o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:P,images:Array.isArray(t.images)?t.images:[]},y,{signal:d.signal})))}catch(p){u("error",`${t.agent} chat failed: ${p?.message||p}`),p?.detail&&u("error",`${t.agent} said: ${p.detail}`),a({type:"error",error:p?.message||String(p)})}finally{if(!s){const p=await Ct(Y,A).catch(()=>null);p&&y({type:"scm",phase:"after",...p})}j(c),$&&q($.id),e.writableEnded||e.end()}}async function ro(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:xt(),secretBackend:oe()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await m(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:Pt(o.connection||o,{token:o.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const r=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return r?r[2]==="delete"?i(e,200,{ok:$t(r[1])}):i(e,200,It(r[1],o.remote||"")):i(e,404,{error:"Not found"})}async function ao(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:ae,worktrees:await Nt()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await m(n);if(t==="/worktrees"){const r=await re({repo:o.repo,projectId:o.projectId,jobId:o.jobId,base:o.base||null});return i(e,r.error?400:200,r.error?{error:r.error}:{ok:!0,...r})}if(t==="/worktrees/remove"){const r=await Dt({projectId:o.projectId,jobId:o.jobId,force:!!o.force});return i(e,r.ok?200:400,r)}return i(e,404,{error:"Not found"})}async function E(n,e,t){const o=O[n.agent];if(!o||o.hidden)throw new R(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const r=await o.engine.available().catch(d=>({ok:!1,reason:d?.message||String(d)}));if(!r.ok)throw new R(r.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=ue(a),c=()=>s.cancel("disconnected");t.on("close",c);let l="";try{return await ne(n.options?.sandbox,()=>fe(n.agent,n.options,s.signal,()=>o.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},d=>{d?.type==="delta"&&d.text?(l+=d.text,e(d.text)):d?.type==="done"&&d.text&&!l&&(l=d.text,e(d.text))},{signal:s.signal}))),l}finally{t.off("close",c),j(a)}}function M(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
6
|
`)}function B(n,e,t){n.writableEnded||n.write(`event: ${e}
|
|
7
7
|
data: ${JSON.stringify(t)}
|
|
8
8
|
|
|
9
|
-
`)}async function U(n,e,t,o){try{const r=t(await m(n)),a=X(n,r.agent,r.options||{});if(a.error)throw new R(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new R(`Bad JSON: ${r.message}`):r)),null}}async function ro(n,e){const t=await U(n,e,mn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,un(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=cn(t.requestedModel,r=>x(e,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){x(e,S(r))}x(e,"[DONE]"),e.end()}async function ao(n,e){const t=await U(n,e,gn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,hn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=ln(t.requestedModel,r=>x(e,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){x(e,S(r))}x(e,"[DONE]"),e.end()}async function io(n,e){const t=await U(n,e,yn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,pn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=wn(t.requestedModel,r=>B(e,r.type,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...S(r)};B(e,"error",a)}e.end()}async function so(n,e){const t=await U(n,e,fn,F);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,dn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,F(r))}M(e);const o=sn(t.requestedModel,(r,a)=>B(e,r,a));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){B(e,"error",F(r))}e.end()}async function co(n,e){let t={};try{t=await m(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?zt(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function Oe(n,e,t){let o;try{o=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=t?ee(t):mt(),a=l=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:l})},s=(l,d)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:l,message:d}});if(o.id==null)return e.writeHead(202),e.end();if(o.method==="initialize")return a({protocolVersion:o.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const c=ht();if(o.method==="tools/list"){const l=r?r.specs.map(d=>({name:d.name,description:d.description,inputSchema:d.parameters||{type:"object",properties:{}}})):[];return a({tools:[...c,...l]})}if(o.method==="tools/call"){const l=await pt(o.params?.name,o.params?.arguments||{});if(l)return a(l);if(!r)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 gt(r,o.params?.name,o.params?.arguments||{}))}catch(d){return a({content:[{type:"text",text:`error: ${d?.message||d}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function lo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{},r=t.message;if(!o.command||!r)return i(e,400,{error:"need server.command and message"});try{const a=await jt({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox},r);return r.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function uo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{};if(!o.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 r={key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox};try{return i(e,200,t.status?Xt(r):await Jt(r))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function ho(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const{url:o,headers:r,message:a}=t||{};if(!o||!a)return i(e,400,{error:"need url and message"});let s;try{s=le(o)}catch(h){return i(e,400,{error:String(h?.message||h)})}const c={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[h,y]of Object.entries(r)){const f=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(c[h]=String(y))}const l=new AbortController,d=setTimeout(()=>l.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:c,body:JSON.stringify(a),redirect:"follow",signal:l.signal});try{h.url&&le(h.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const y=await h.text().catch(()=>"");return i(e,200,{status:h.status,sessionId:h.headers.get("Mcp-Session-Id")||null,contentType:h.headers.get("Content-Type")||"",authenticate:h.headers.get("WWW-Authenticate")||"",body:y})}catch(h){const y=h?.name==="AbortError"?"timed out":String(h?.message||h);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(d)}}const Ae=256*1024,po=5,fo=8e3;async function mo(n){let e=de(n);const t=new AbortController,o=setTimeout(()=>t.abort(),fo);try{for(let r=0;r<=po;r++){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/${g} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=de(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:wo(await go(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function go(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,Ae);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(r+=s.byteLength,o+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(o)||r>=Ae))break}}finally{try{await e.cancel()}catch{}}return o}function yo(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 wo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?yo(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function So(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=t&&t.url;if(!o||typeof o!="string")return i(e,400,{error:"need url"});try{const r=await mo(o);return i(e,200,{title:r.title||null,url:r.url||o})}catch(r){const a=r?.name==="AbortError"?"timed out":String(r?.message||r);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function bo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=ee(t.session);if(!o)return i(e,404,{error:"no such session"});const r=o.pending.get(t.id);return r?(o.pending.delete(t.id),r.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function ko(n,e){let t;try{t=await m(n)}catch(l){return i(e,400,{error:"Bad JSON: "+l.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=String(t.prompt||"").slice(0,6e3);if(!r)return i(e,400,{error:"Empty prompt"});const a=t.model||"",s=X(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const c=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 l="";return typeof o.engine.complete=="function"?l=await o.engine.complete({prompt:r,system:c,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:c,options:s.options},d=>{d.type==="delta"?l+=d.text||"":d.type==="done"&&d.text&&(l+=d.text)}),i(e,200,{text:(l||"").trim()})}catch(l){return i(e,502,{error:l?.message||String(l)})}}async function To(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof o.engine.listModels!="function")return i(e,200,{models:[]});try{const r=await o.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return i(e,502,{error:r?.message||String(r)})}}async function Eo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(t.command||"").trim();if(!o)return i(e,400,{error:"No command"});let r=null;try{r=ie(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}async function vo(n,e,t){let o;try{o=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(o?.agent||"");if(!he.includes(r))return i(e,404,{error:`${r||"that agent"} keeps no sessions Chap can read (it can: ${he.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await Qt(r,{limit:o.limit})});if(t==="/agent-sessions/read"){const a=await Zt(r,String(o.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=pe({id:o.thread?.id??o.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const s=await qt(r,String(o.id||""),a.id);return s?i(e,200,{session:s}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=pe({id:o.thread?.id??o.thread});return a?i(e,200,await en(r,a.id,Array.isArray(o.messages)?o.messages:[])):i(e,400,{error:"catchup needs the Chap conversation: { thread: { id } }"})}return i(e,404,{error:"Not found"})}catch(a){return i(e,a?.status||500,{error:a?.message||String(a)})}}const K=xe(async(n,e)=>{if(Cn(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 o=Mn(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return Ln(e,{fresh:t.searchParams.get("fresh")==="1"});const r=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return Gn(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-context"){const s=await m(n).catch(()=>({})),c=s?.options&&typeof s.options=="object"?s.options:{},l={...c.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof c.permissionMode=="string"?{permissionMode:c.permissionMode}:{},...typeof c.workingDir=="string"&&c.workingDir?{workingDir:c.workingDir}:{},...typeof c.model=="string"&&c.model?{model:c.model}:{}};return i(e,200,await tn({agent:typeof s?.agent=="string"?s.agent:"claude",options:l}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return jn(e,r,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return Yn(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return Qn(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return Zn(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return Vn(e,decodeURIComponent(t.pathname.slice(12)),r,a);if(n.method==="POST"&&t.pathname==="/skills")return Xn(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?n.method==="DELETE"?Kn(e,decodeURIComponent(s)):i(e,405,{ok:!1,error:"use POST /skills to save a skill"}):n.method==="DELETE"?i(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):zn(n,e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?Fn(e,decodeURIComponent(s),r,a):Jn(e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return no(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return oo(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return ve(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return ve(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:g,agents:Object.fromEntries(Ht.map(c=>[c,s?Lt(c)||ie(c)?.kind||null:Mt(c)])),...s?{home:v.homedir(),path:process.env.PATH,installDirs:Bt(v.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return vo(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return to(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Rn(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return $n(e);if(n.method==="POST"&&t.pathname==="/whoami")return In(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return ro(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return ao(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return io(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return so(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return Oe(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const s=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return Oe(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return q(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return we(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return we(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return co(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return bo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await m(n)}catch{s=null}const c=vt(s||{});return e.writeHead(c?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return lo(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return uo(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return ho(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return So(n,e);if(n.method==="POST"&&t.pathname==="/complete")return ko(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return To(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Eo(n,e);if(n.method==="POST"&&t.pathname==="/update")return eo(e);i(e,404,{error:"Not found"})}catch(r){i(e,500,{error:r?.message||String(r)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Oo(n){let e="";const t=[];let o=!1,r=!1;const a=()=>{r&&!o&&!t.length&&process.exit(0)},s=async()=>{if(!o){for(o=!0;t.length;){const c=t.shift();let l;try{l=JSON.parse(c)}catch{continue}try{const d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:c});if(l.id==null)continue;const h=(await d.text()).trim();h&&process.stdout.write(h+`
|
|
9
|
+
`)}async function U(n,e,t,o){try{const r=t(await m(n)),a=X(n,r.agent,r.options||{});if(a.error)throw new R(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new R(`Bad JSON: ${r.message}`):r)),null}}async function io(n,e){const t=await U(n,e,yn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,pn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=dn(t.requestedModel,r=>x(e,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){x(e,S(r))}x(e,"[DONE]"),e.end()}async function so(n,e){const t=await U(n,e,wn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,fn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=un(t.requestedModel,r=>x(e,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){x(e,S(r))}x(e,"[DONE]"),e.end()}async function co(n,e){const t=await U(n,e,Sn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,mn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=bn(t.requestedModel,r=>B(e,r.type,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...S(r)};B(e,"error",a)}e.end()}async function lo(n,e){const t=await U(n,e,gn,F);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,hn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,F(r))}M(e);const o=ln(t.requestedModel,(r,a)=>B(e,r,a));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){B(e,"error",F(r))}e.end()}async function uo(n,e){let t={};try{t=await m(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?Yt(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function Oe(n,e,t){let o;try{o=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=t?ee(t):mt(),a=l=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:l})},s=(l,d)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:l,message:d}});if(o.id==null)return e.writeHead(202),e.end();if(o.method==="initialize")return a({protocolVersion:o.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const c=ht();if(o.method==="tools/list"){const l=r?r.specs.map(d=>({name:d.name,description:d.description,inputSchema:d.parameters||{type:"object",properties:{}}})):[];return a({tools:[...c,...l]})}if(o.method==="tools/call"){const l=await pt(o.params?.name,o.params?.arguments||{});if(l)return a(l);if(!r)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 gt(r,o.params?.name,o.params?.arguments||{}))}catch(d){return a({content:[{type:"text",text:`error: ${d?.message||d}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function ho(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{},r=t.message;if(!o.command||!r)return i(e,400,{error:"need server.command and message"});try{const a=await Jt({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox},r);return r.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function po(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{};if(!o.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 r={key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox};try{return i(e,200,t.status?Kt(r):await zt(r))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function fo(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const{url:o,headers:r,message:a}=t||{};if(!o||!a)return i(e,400,{error:"need url and message"});let s;try{s=le(o)}catch(h){return i(e,400,{error:String(h?.message||h)})}const c={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[h,y]of Object.entries(r)){const f=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(c[h]=String(y))}const l=new AbortController,d=setTimeout(()=>l.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:c,body:JSON.stringify(a),redirect:"follow",signal:l.signal});try{h.url&&le(h.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const y=await h.text().catch(()=>"");return i(e,200,{status:h.status,sessionId:h.headers.get("Mcp-Session-Id")||null,contentType:h.headers.get("Content-Type")||"",authenticate:h.headers.get("WWW-Authenticate")||"",body:y})}catch(h){const y=h?.name==="AbortError"?"timed out":String(h?.message||h);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(d)}}const Ae=256*1024,mo=5,go=8e3;async function yo(n){let e=de(n);const t=new AbortController,o=setTimeout(()=>t.abort(),go);try{for(let r=0;r<=mo;r++){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/${g} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=de(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:bo(await wo(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function wo(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,Ae);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(r+=s.byteLength,o+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(o)||r>=Ae))break}}finally{try{await e.cancel()}catch{}}return o}function So(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 bo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?So(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function ko(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=t&&t.url;if(!o||typeof o!="string")return i(e,400,{error:"need url"});try{const r=await yo(o);return i(e,200,{title:r.title||null,url:r.url||o})}catch(r){const a=r?.name==="AbortError"?"timed out":String(r?.message||r);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function To(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=ee(t.session);if(!o)return i(e,404,{error:"no such session"});const r=o.pending.get(t.id);return r?(o.pending.delete(t.id),r.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function Eo(n,e){let t;try{t=await m(n)}catch(l){return i(e,400,{error:"Bad JSON: "+l.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=String(t.prompt||"").slice(0,6e3);if(!r)return i(e,400,{error:"Empty prompt"});const a=t.model||"",s=X(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const c=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 l="";return typeof o.engine.complete=="function"?l=await o.engine.complete({prompt:r,system:c,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:c,options:s.options},d=>{d.type==="delta"?l+=d.text||"":d.type==="done"&&d.text&&(l+=d.text)}),i(e,200,{text:(l||"").trim()})}catch(l){return i(e,502,{error:l?.message||String(l)})}}async function vo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof o.engine.listModels!="function")return i(e,200,{models:[]});try{const r=await o.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return i(e,502,{error:r?.message||String(r)})}}async function Oo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(t.command||"").trim();if(!o)return i(e,400,{error:"No command"});let r=null;try{r=ie(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}async function Ao(n,e,t){let o;try{o=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(o?.agent||"");if(!he.includes(r))return i(e,404,{error:`${r||"that agent"} keeps no sessions Chap can read (it can: ${he.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await qt(r,{limit:o.limit})});if(t==="/agent-sessions/read"){const a=await en(r,String(o.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=pe({id:o.thread?.id??o.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const s=await tn(r,String(o.id||""),a.id);return s?i(e,200,{session:s}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=pe({id:o.thread?.id??o.thread});return a?i(e,200,await nn(r,a.id,Array.isArray(o.messages)?o.messages:[])):i(e,400,{error:"catchup needs the Chap conversation: { thread: { id } }"})}return i(e,404,{error:"Not found"})}catch(a){return i(e,a?.status||500,{error:a?.message||String(a)})}}const K=xe(async(n,e)=>{if(Pn(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 o=Un(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return jn(e,{fresh:t.searchParams.get("fresh")==="1"});const r=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return Fn(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-context"){const s=await m(n).catch(()=>({})),c=s?.options&&typeof s.options=="object"?s.options:{},l={...c.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof c.permissionMode=="string"?{permissionMode:c.permissionMode}:{},...typeof c.workingDir=="string"&&c.workingDir?{workingDir:c.workingDir}:{},...typeof c.model=="string"&&c.model?{model:c.model}:{}};return i(e,200,await on({agent:typeof s?.agent=="string"?s.agent:"claude",options:l}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return Jn(e,r,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return Qn(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return qn(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return eo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return Zn(e,decodeURIComponent(t.pathname.slice(12)),r,a);if(n.method==="POST"&&t.pathname==="/skills")return Kn(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?n.method==="DELETE"?Vn(e,decodeURIComponent(s)):i(e,405,{ok:!1,error:"use POST /skills to save a skill"}):n.method==="DELETE"?i(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):Yn(n,e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?Xn(e,decodeURIComponent(s),r,a):zn(e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return ro(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return ao(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return ve(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return ve(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:g,agents:Object.fromEntries(Ht.map(c=>[c,s?Lt(c)||ie(c)?.kind||null:Mt(c)])),...s?{home:v.homedir(),path:process.env.PATH,installDirs:Bt(v.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Ao(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return oo(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Nn(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return In(e);if(n.method==="POST"&&t.pathname==="/whoami")return Dn(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return io(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return so(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return co(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return lo(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return Oe(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const s=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return Oe(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return q(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return we(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return we(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return uo(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return To(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await m(n)}catch{s=null}const c=vt(s||{});return e.writeHead(c?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return ho(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return po(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return fo(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return ko(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Eo(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return vo(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Oo(n,e);if(n.method==="POST"&&t.pathname==="/update")return no(e);i(e,404,{error:"Not found"})}catch(r){i(e,500,{error:r?.message||String(r)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Co(n){let e="";const t=[];let o=!1,r=!1;const a=()=>{r&&!o&&!t.length&&process.exit(0)},s=async()=>{if(!o){for(o=!0;t.length;){const c=t.shift();let l;try{l=JSON.parse(c)}catch{continue}try{const d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:c});if(l.id==null)continue;const h=(await d.text()).trim();h&&process.stdout.write(h+`
|
|
10
10
|
`)}catch(d){l.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:l.id,error:{code:-32e3,message:String(d?.message||d)}})+`
|
|
11
11
|
`)}}o=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",c=>{e+=c;let l;for(;(l=e.indexOf(`
|
|
12
|
-
`))>=0;){const d=e.slice(0,l).trim();e=e.slice(l+1),d&&t.push(d)}s()}),process.stdin.on("end",()=>{r=!0,a()}),process.stdin.resume()}function
|
|
12
|
+
`))>=0;){const d=e.slice(0,l).trim();e=e.slice(l+1),d&&t.push(d)}s()}),process.stdin.on("end",()=>{r=!0,a()}),process.stdin.resume()}function xo(){Ut(),Wt(),Rn();let n=!1;K.on("error",e=>{if(e&&e.code==="EADDRINUSE"){fetch(`http://127.0.0.1:${b}/health`,{signal:AbortSignal.timeout(1500)}).then(t=>t.ok?t.json():null).catch(()=>null).then(t=>{const o=!!(t?.version&&Array.isArray(t.agents)),r=rn({name:"bridge",self:g,holder:o?{ours:o,version:t.version}:null,managedBy:an(process.env),port:b});if(r.action==="standby"||n&&!t){if(!n)for(const a of r.lines)u("info",a);n=!0,setTimeout(()=>K.listen(b,k),sn);return}if(o)for(const a of r.lines)u("error",a);else u("error",`Port ${b} 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)});return}u("error",`bridge server error: ${e?.message||e}`),process.exit(1)});for(const e of["SIGINT","SIGTERM"])process.on(e,()=>{const t=Vt("shutdown");t&&u("info",`shutdown: stopped ${t} running agent${t===1?"":"s"}`);const o=Qt("shutdown");o&&u("info",`shutdown: closed ${o} warm agent process${o===1?"":"es"}`),te().close(),setTimeout(()=>process.exit(0),t||o?300:0).unref?.(),!t&&!o&&process.exit(0)});K.listen(b,k,async()=>{n&&u("info","standby: the other bridge is gone — this copy has the port now"),n=!1,u("info",`listening on http://${k}:${b}`),ke.warm(),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:e,label:t,hidden:o}]of Object.entries(O)){if(o)continue;const r=await e.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${t}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),ye().then(e=>e.startIfConfigured()).then(e=>{e?.skipped||(e?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${e?.error||"unknown error"}`))}).catch(e=>u("error",`channels: ${e?.message||e}`))})}function Po(){console.log(`ChatPanel Bridge v${g}
|
|
13
13
|
|
|
14
14
|
Usage:
|
|
15
15
|
chatpanel-bridge start the bridge (foreground) on ${k}:${b}
|
|
@@ -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 $o(){const n=process.argv,e=(...t)=>t.some(o=>n.includes(o));if(e("--help","-h"))return Po(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=Q(D,"utf8").trim()}catch{}const o=`http://${k}:${b}`;try{if(!t)throw new Error(`no token at ${D} — is the bridge running?`);const r=await fetch(`${o}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),a=await r.json().catch(()=>({}));if(!r.ok)throw new Error(a.error||`HTTP ${r.status}`);console.log(`Pairing code: ${An(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(r){u("error",`could not get a pairing code from the bridge at ${o}: ${r?.message||r}`),process.exitCode=1}})(),!0;if(n.includes("sandbox"))return kt(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{Xe(),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{ze(),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=Ke()}catch(o){u("error",String(o?.message||o))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const Ce=process.argv.indexOf("--mcp-stdio");if(Ce>=0){const n=process.argv[Ce+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Co(n)}else process.argv.includes("--update")?(async()=>{try{const n=await se(g);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),Z()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():$o()||xo();
|
package/src/sign-in.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as y}from"node:child_process";import{buildSpawnSpec as
|
|
1
|
+
import{spawn as y}from"node:child_process";import{buildSpawnSpec as S}from"./env.js";const I=Object.freeze({claude:"open a terminal, run `claude`, and type `/login`",codex:"open a terminal and run `codex login`",copilot:"open a terminal, run `copilot`, and type `/login`",opencode:"open a terminal and run `opencode auth login`",kiro:"open a terminal and run `kiro-cli login`",hermes:"open a terminal and run `hermes setup`",antigravity:"open a terminal, run `agy`, and sign in",deepseek:"open a terminal and sign in to the DeepSeek CLI",pi:"open a terminal, run `pi`, and sign in"}),w=/not logged in|please run \/login|authentication_failed|invalid api key(?:\s*·\s*please run)?|please (?:log|sign) ?in|login required|not authenticated|unauthenticated|missing bearer token|no credentials|\b401\b.*unauthori[sz]ed|token (?:has )?expired.*(?:log|sign) ?in|run `?(?:codex|claude) login`?/i;function T(n){const e=String(n||"");return!e||/\bmcp\b/i.test(e)&&!/not logged in|please run \/login|authentication_failed/i.test(e)?!1:w.test(e)}function D(n,e){const o=e?d.get(e):null;if(o?.signedIn===!0&&Date.now()-o.at<k)return`${n} is signed in on this machine, but the ChatPanel sandbox kept its login from it, so your message was not sent. This is ChatPanel's problem, not your sign-in: update ChatPanel, or turn on "Run outside the ChatPanel sandbox" for this agent until it is fixed.`;const a=I[e]||`sign in to ${n} in your terminal`;return`${n} isn't signed in on this machine, so your message was not sent. ChatPanel uses your own ${n} login and can't sign in for you: ${a}, finish the sign-in in the browser, then send your message again.`}const x={claude:{args:["auth","status"],read:n=>{try{const e=JSON.parse(n.slice(n.indexOf("{")));return typeof e.loggedIn=="boolean"?e.loggedIn:null}catch{return null}}},codex:{args:["login","status"],read:n=>/not logged in/i.test(n)?!1:/logged in/i.test(n)?!0:null}},g=new Map,_=15e3,b=5*6e4,d=new Map,k=10*6e4;async function L(n,e,{timeoutMs:o=5e3,now:a=Date.now(),spawnImpl:h=y}={}){const u=x[n];if(!u||!e)return null;const s=g.get(n);if(s&&a-s.at<(s.signedIn===!0?b:_))return s.signedIn;const r=await new Promise(l=>{let c="",t;try{const[i,m,f]=S(e,u.args,process.cwd(),null);t=h(i,m,{...f,stdio:["ignore","pipe","pipe"]})}catch{return l(null)}const p=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}l(null)},o);t.stdout?.on("data",i=>{c+=i.toString()}),t.stderr?.on("data",i=>{c+=i.toString()}),t.on("error",()=>{clearTimeout(p),l(null)}),t.on("close",()=>{clearTimeout(p),l(u.read(c))})});return g.set(n,{at:a,signedIn:r}),r!==null&&d.set(n,{at:Date.now(),signedIn:r}),r}function M(){g.clear(),d.clear()}export{I as SIGN_IN_HINTS,T as loginRequired,M as resetSignInCache,D as signInMessage,L as signInStatus};
|