@chatpanel/bridge 0.13.9 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/scripts/sync-events.mjs +2 -2
- package/src/engines/antigravity.js +5 -5
- package/src/engines/claude-warm.js +3 -3
- package/src/engines/claude.js +4 -4
- package/src/engines/codex-appserver.js +9 -9
- package/src/engines/codex.js +6 -6
- package/src/engines/custom.js +9 -9
- package/src/events/sandbox-policy.js +1 -0
- package/src/mcp-local.js +4 -4
- package/src/pii/pii-detect.js +2 -2
- package/src/sandbox.js +1 -0
- package/src/server.js +6 -6
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
|
|
6
6
|
"keywords": [
|
package/scripts/sync-events.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFileSync as r,writeFileSync as
|
|
2
|
+
import{readFileSync as r,writeFileSync as d,existsSync as i,mkdirSync as f}from"node:fs";import{fileURLToPath as v}from"node:url";import{dirname as p,join as n}from"node:path";const c=n(p(v(import.meta.url)),".."),u=["scopes.js","skill-manifest.js","skill-scan.js","ref.js","event.js","view.js","capability.js","reach.js","scm-connection.js","sandbox-policy.js"];function m(){return[n(c,"node_modules","@chatpanel","events"),n(c,"..","chatpanel-events")].find(e=>i(n(e,"skill-manifest.js")))}const s=process.argv.includes("--check"),a=m();if(!a){const e="chatpanel-events not found (check out ../chatpanel-events).";s&&(console.error(`sync-events --check: ${e}`),process.exit(1)),console.warn(`sync-events: ${e} Leaving src/events as-is.`),process.exit(0)}const l=n(c,"src","events");s||f(l,{recursive:!0});const y=e=>`// GENERATED — do not edit.
|
|
3
3
|
// Source of truth: chatpanel-events/${e} (npm @chatpanel/events).
|
|
4
4
|
// Edit there, then run: npm run sync:events
|
|
5
5
|
//
|
|
@@ -7,4 +7,4 @@ import{readFileSync as r,writeFileSync as f,existsSync as i,mkdirSync as v}from"
|
|
|
7
7
|
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
8
8
|
// single-file binary has nothing to resolve.
|
|
9
9
|
|
|
10
|
-
`;let h=0;for(const e of u){const o=y(e)+r(n(a,e),"utf8"),t=n(l,e);if((i(t)?r(t,"utf8"):null)!==o){if(s){console.error(`sync-events --check: src/events/${e} differs from chatpanel-events`),h+=1;continue}
|
|
10
|
+
`;let h=0;for(const e of u){const o=y(e)+r(n(a,e),"utf8"),t=n(l,e);if((i(t)?r(t,"utf8"):null)!==o){if(s){console.error(`sync-events --check: src/events/${e} differs from chatpanel-events`),h+=1;continue}d(t,o),console.log(`sync-events: updated src/events/${e}`)}}s&&(h&&(console.error("Run `npm run sync:events` and commit the result."),process.exit(1)),console.log("sync-events --check: src/events matches chatpanel-events ✓"));
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{spawn as
|
|
2
|
-
`)){const n=e.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(n)&&!/^(name|model|models|id|provider|available)$/i.test(n)&&!a.has(n)&&(a.add(n),
|
|
3
|
-
`}),{streamed:!0}}const n=e.event||e.type||"";if(n==="init")return l({type:"status",text:"Antigravity working"}),{streamed:!1};if(n==="result"){const s=e.result||{};return
|
|
1
|
+
import{spawn as F,spawnSync as z}from"node:child_process";import{writeFileSync as B,unlinkSync as R}from"node:fs";import"node:os";import C from"node:path";import{findAgentBin as D}from"../env.js";import{fitCliPrompt as U,argvPromptBudget as j}from"./prompt.js";import{summarizeCliError as G}from"../cli-errors.js";import{killOnAbort as H,spawnGroupOpts as J}from"../proc.js";import{sandbox as K,noteSandbox as W}from"../sandbox.js";import{pushExtraArgs as Y,FORBIDDEN as Z}from"./args.js";import{resolveWorkdir as q}from"../workdir.js";const P=Number(process.env.CHATPANEL_AGY_TIMEOUT_MS)||18e4;async function ft(){try{const u=D("agy")||"agy",l=z(u,["models"],{encoding:"utf8",timeout:15e3}),o=[],a=new Set;for(const e of String(l.stdout||"").split(`
|
|
2
|
+
`)){const n=e.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(n)&&!/^(name|model|models|id|provider|available)$/i.test(n)&&!a.has(n)&&(a.add(n),o.push(n),o.length>=100))break}return o}catch{return[]}}const L=()=>({started:new Set,finalText:""});function Q(u,l,o=L()){const a=String(u||"").trim();if(!a)return{streamed:!1};let e;try{e=JSON.parse(a)}catch{return l({type:"delta",text:`${a}
|
|
3
|
+
`}),{streamed:!0}}const n=e.event||e.type||"";if(n==="init")return l({type:"status",text:"Antigravity working"}),{streamed:!1};if(n==="result"){const s=e.result||{};return o.finalText=typeof s.response=="string"?s.response:"",s.status&&s.status!=="SUCCESS"&&l({type:"status",text:`Antigravity: ${s.status}`}),{streamed:!1}}if(n!=="step_update")return{streamed:!1};const r=e.step_update||{};if(r.step_type==="tool"){const s=`agy_${r.step_index??o.started.size}`,i=r.tool_info&&typeof r.tool_info=="object"?r.tool_info:{},d=r.tool_name||i.name||"tool";if(o.started.has(s)||(o.started.add(s),l({type:"tool",name:d,phase:"start",callId:s,input:i.parameters&&typeof i.parameters=="object"?i.parameters:{}})),r.state==="DONE"){const g=!!i.error||r.state==="ERROR",c=i.output==null?"":typeof i.output=="string"?i.output:JSON.stringify(i.output);l({type:"tool",name:d,phase:"done",callId:s,status:g?`error: ${String(i.error||"failed").slice(0,80)}`:"ok",result:String(g?i.error||"":c).slice(0,4e3)})}return{streamed:!1}}return r.step_type==="agent_response"&&typeof r.text_delta=="string"&&r.text_delta?(l({type:"delta",text:r.text_delta}),{streamed:!0}):{streamed:!1}}let x=!1,M=0;async function mt(){if(Date.now()-M>(x?3e4:4e3)){M=Date.now();try{x=!!D("agy")}catch{x=!1}}return x?{ok:!0}:{ok:!1,reason:"agy not found on PATH. Install Antigravity, then run `agy` once to sign in."}}function V(u,l){const o=[];for(let a=0;a<(u?.length||0);a++){const e=/^data:([^;]+);base64,(.+)$/s.exec(u[a]?.dataUrl||"");if(!e)continue;const n=(e[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",r=C.join(l,`chatpanel-img-${Date.now()}-${a}.${n}`);try{B(r,Buffer.from(e[2],"base64")),o.push(r)}catch{}}return o}async function gt({messages:u,system:l,options:o,images:a},e,{signal:n}={}){const r=q(o.workingDir),s=V(a,r),i=()=>s.forEach(t=>{try{R(t)}catch{}}),d=U(u,l,j({otherArgsChars:400}));let g=d.prompt;d.dropped&&e({type:"status",text:`Antigravity takes the prompt as a command-line argument, which this system caps — the oldest ${d.dropped} turn${d.dropped===1?"":"s"} of this conversation were left out to fit.`}),s.length&&(g+=`
|
|
4
4
|
|
|
5
|
-
The user attached image(s): ${s.map(t=>"@"+
|
|
6
|
-
`))>=0;)
|
|
5
|
+
The user attached image(s): ${s.map(t=>"@"+C.basename(t)).join(" ")}`);const c=["-p",g];o.model&&c.push("--model",o.model),o.permissionMode==="bypassPermissions"&&c.push("--dangerously-skip-permissions"),Y(c,o.extraArgs,Z.antigravity,e);const _=async t=>{const N=t?[...c,"--output-format","stream-json"]:c,y=await K().wrap("agy",N,{cwd:r,stdio:["ignore","pipe","pipe"],env:{...process.env,...o.runEnv||{}},...J},{engine:"antigravity",cwd:r});return W(e,y.record),new Promise((k,b)=>{let f;try{f=F(y.bin,y.argv,y.opts)}catch(p){return b(new Error(`Failed to start agy: ${p.message}`))}const $=H(f,n);let E="",T="",m="",v=!1;const I=L();let h;const S=()=>{clearTimeout(h),h=setTimeout(()=>{f.kill("SIGKILL"),b(new Error(`Antigravity timed out — no output for ${Math.round(P/1e3)}s.`))},P)};S();const O=p=>{Q(p,e,I).streamed&&(v=!0)};f.stdout.on("data",p=>{S();const w=p.toString();if(E+=w,!t){v=!0,e({type:"delta",text:w});return}m+=w;let A;for(;(A=m.indexOf(`
|
|
6
|
+
`))>=0;)O(m.slice(0,A)),m=m.slice(A+1)}),f.stderr.on("data",p=>{S(),T+=p.toString()}),f.on("error",p=>{clearTimeout(h),$(),b(new Error(`Failed to start agy: ${p.message}`))}),f.on("close",p=>{if(clearTimeout(h),$(),n?.aborted){k({code:0,aborted:!0});return}t&&m.trim()&&O(m),k({code:p,out:E,err:T,streamed:v,state:I})})})};try{let t=await _(!0);if(t.aborted||t.code!==0&&!t.streamed&&/output-format|unknown flag|flag provided but not defined/i.test(t.err)&&(e({type:"status",text:"This Antigravity CLI has no structured output; showing its text only. Update it with `agy update` to see tool activity."}),t=await _(!1),t.aborted))return;if(t.code!==0)throw new Error(G("Antigravity",t.code,t.err,t.out));t.streamed||e({type:"delta",text:(t.state?.finalText||t.out).trim()||"(no output)"}),e({type:"done",text:""})}finally{i()}}export{mt as available,gt as chat,Q as forwardAgyLine,ft as listModels,L as newAgyState};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{unlink as
|
|
2
|
-
`).pop()}`:""}`),e){const
|
|
3
|
-
`).pop().slice(0,200)}`:""}`;e.finish({status:"died",error:
|
|
1
|
+
import{unlink as j}from"node:fs/promises";import{spawnRpcChild as F}from"../rpc-child.js";import{sandbox as U}from"../sandbox.js";import{createWarmPool as B}from"../warm-pool.js";import{registerWarmPool as G}from"../warm.js";import{createSession as R,deleteSession as M,rebindSession as J,releaseSession as z}from"../mcp-sessions.js";import{resolveClaude as K,buildSpawnSpec as Q}from"../env.js";import{loginRequired as k,signInMessage as O}from"../sign-in.js";import{pushExtraArgs as D,FORBIDDEN as P}from"./args.js";import{buildClaudeLaunch as W,claudePrompt as V,handleMessage as X,writeImages as Y}from"./claude.js";const q=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,Z=5e3,u=G("claude",B({log:n=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${n}`)}}));function ee(n={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||n.warm===!1)}async function I({spec:n,args:E,cwd:t,env:A,spawnImpl:g,log:S=()=>{}}){const C=[...E,"--input-format","stream-json"],[f,c,d]=Q(n,C,t,A),a=await U().wrap(f,c,d,{engine:"claude",cwd:t});a.record.layer==="none"&&S(`sandbox: claude session runs outside a sandbox — ${a.record.reason}`);const[y,o,p]=[a.bin,a.argv,a.opts];let e=null;const $=new Set;let w="",v=0;const m=F(y,o,{spawnOpts:p,spawnImpl:g,jsonrpc:!1,onStderr:r=>{w=(w+r).slice(-2e3),e&&e.touch()},onExit:r=>{if(S(`claude exited: ${r.signal||r.code}${w?` — ${w.trim().split(`
|
|
2
|
+
`).pop()}`:""}`),e){const s=e.apiError&&k(e.apiError)?O("Claude Code","claude"):e.apiError?`Claude Code reported an error: ${e.apiError}`:`Claude Code exited (${r.signal||r.code})${w?`: ${w.trim().split(`
|
|
3
|
+
`).pop().slice(0,200)}`:""}`;e.finish({status:"died",error:s})}for(const s of $)try{s(r)}catch{}},onMessage:r=>{if(!e||(e.touch(),r.type==="control_response"))return;const s=X(r,e.emit,e.streamedAny,t,e.flow);s.streamed&&(e.streamedAny=!0),s.result!=null&&(e.resultText=s.result),s.apiError&&(e.apiError=s.apiError),r.type==="result"&&(e.apiError&&k(e.apiError)?e.finish({status:"failed",error:O("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 m.pid},get alive(){return!m.exited},onExit(r){$.add(r)},close(){m.close()},async turn({prompt:r,emit:s,signal:h}){if(m.exited)throw new Error("Claude Code process is gone");if(e)throw new Error("a turn is already running on this process");let i=null,b;const x=new Promise(T=>{b=T}),l={emit:s,flow:{sawText:!1,tail:"",boundary:!1},streamedAny:!1,resultText:"",apiError:null,touch(){clearTimeout(i),i=setTimeout(()=>l.finish({status:"timeout",error:`Claude Code timed out — no output for ${Math.round(q/1e3)}s.`}),q)},finish(T){e===l&&(clearTimeout(i),e=null,b(T))}};e=l,l.touch();const N=()=>{if(e===l){l.interrupted=!0;try{m.send({type:"control_request",request_id:`stop_${++v}`,request:{subtype:"interrupt"}})}catch{}setTimeout(()=>{e===l&&(l.finish({status:"killed",error:null}),m.kill())},Z).unref?.()}};if(h?.aborted)return l.finish({status:"killed",error:null}),{streamedAny:!1,resultText:"",status:"killed"};h?.addEventListener("abort",N,{once:!0});try{m.send({type:"user",message:{role:"user",content:r}})}catch(T){l.finish({status:"failed",error:T.message})}const _=await x;h?.removeEventListener("abort",N),_.status==="timeout"&&m.kill();const H=_.status==="killed"?"killed":l.interrupted?"interrupted":_.status;return{streamedAny:l.streamedAny,resultText:l.resultText,status:H,error:_.error}}}}const L=new Set;async function re({key:n,spec:E,options:t,label:A,launch:g=I,log:S=()=>{},force:C=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!C||!n||!E||L.has(n)||u.peek({key:n,messages:[{role:"user",content:""}]}))return!1;L.add(n);const f=u.reserve({key:n,label:`${A} (spare)`,evict:!1});if(!f)return L.delete(n),!1;let c=null,d=null;try{let a=t.mcp;const y=t.mcp?.specs||[];a?.url&&y.length&&(c=R(()=>{},y),a={...a,url:`${a.url.replace(/\/[^/]*$/,"")}/${c.id}`}),d=await W({system:"",options:{...t,mcp:a},tag:`spare-${Date.now()}-${Math.random().toString(36).slice(2)}`});const o=[...d.args];D(o,t.extraArgs,P.claude,()=>{});const p=await g({spec:E,args:o,cwd:d.cwd,env:d.runEnv});p.mcpSession=c,p.systemSent="",u.attach(f,p);const e=d.cleanup;return p.onExit(()=>{c&&M(c.id),e()}),u.release(f,{user:null,answered:!1}),S(`warm ${A}: spare ready`),!0}catch(a){return c&&M(c.id),d?.cleanup?.(),u.drop(f,`spare launch failed: ${a.message}`),!1}finally{L.delete(n)}}async function fe({messages:n,system:E,options:t,images:A},g,{signal:S,launch:C=I}={}){if(!ee(t))return{handled:!1,reason:"not eligible"};const f=K();if(!f)return{handled:!1,reason:"claude not resolvable"};const c=`${Date.now()}-${Math.random().toString(36).slice(2)}`,d=(t.mcp?.specs||[]).map(s=>s?.name).filter(Boolean),a=[];D(a,t.extraArgs,P.claude,()=>{});const y=JSON.stringify({agent:"claude",cwd:t.workingDir||"",mode:t.permissionMode||"default",model:t.model||"",local:t.useLocalConfig!==!1,reach:t.reach||"",tools:[...d].sort(),extra:a,env:t.runEnv?Object.keys(t.runEnv).sort().map(s=>`${s}=${t.runEnv[s]}`):[]});let o=u.acquire({key:y,messages:n}),p=!1;if(!o){if(o=u.reserve({key:y,label:`claude ${t.workingDir||"home"}`}),!o)return{handled:!1,reason:"all warm slots busy"};p=!0;let s=null,h=null;try{let i=t.mcp;i?.url&&d.length&&(s=R(g,i.specs),i={...i,url:`${i.url.replace(/\/[^/]*$/,"")}/${s.id}`}),h=await W({system:E,options:{...t,mcp:i},tag:c});const b=[...h.args];D(b,t.extraArgs,P.claude,g);const x=await C({spec:f,args:b,cwd:h.cwd,env:h.runEnv});x.mcpSession=s,x.systemSent=String(E||""),u.attach(o,x);const l=h.cleanup;x.onExit(()=>{s&&M(s.id),l()})}catch(i){return s&&M(s.id),h?.cleanup(),u.drop(o,`launch failed: ${i.message}`),{handled:!1,reason:i.message}}}const e=o.session;e.mcpSession&&J(e.mcpSession,g,t.mcp?.specs);const $=n[n.length-1],w=await Y(A,c),v=String(E||""),m=V(p?n:[$],w,!p&&v!==e.systemSent?v:"");e.systemSent=v;let r;try{r=await e.turn({prompt:m,emit:g,signal:S})}finally{w.forEach(s=>j(s).catch(()=>{})),e.mcpSession&&z(e.mcpSession)}if(S?.aborted||r.status==="interrupted")return r.status==="interrupted"&&e.alive?u.release(o,{user:String($?.content||""),answered:r.streamedAny}):u.drop(o,"stopped"),{handled:!0};if(r.status!=="completed"){if(u.drop(o,r.error||r.status),!r.streamedAny)return{handled:!1,reason:r.error||r.status};throw new Error(r.error||`Claude Code ${r.status}`)}return g({type:"done",text:r.streamedAny?"":r.resultText}),u.release(o,{user:String($?.content||""),answered:!0}),setTimeout(()=>{re({key:y,spec:f,options:t,label:`claude ${t.workingDir||"home"}`,launch:C}).catch(()=>{})},250).unref?.(),{handled:!0}}export{fe as chatWarm,I as launchClaudeSession,u as pool,re as prewarmClaude,ee as warmEligible};
|
package/src/engines/claude.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{spawn as I}from"node:child_process";import{writeFile as O,unlink as R}from"node:fs/promises";import k from"node:os";import P from"node:path";import{resolveClaude as
|
|
2
|
-
`))>=0;){const $=d.slice(0,M).trim();if(d=d.slice(M+1),!$.startsWith("{"))continue;let W;try{W=JSON.parse($)}catch{continue}const
|
|
1
|
+
import{spawn as I}from"node:child_process";import{writeFile as O,unlink as R}from"node:fs/promises";import k from"node:os";import P from"node:path";import{resolveClaude as x,buildSpawnSpec as F,isCompiledBinary as ee,selfMcpStdio as te}from"../env.js";import{signInStatus as re,signInMessage as j,loginRequired as oe}from"../sign-in.js";import{buildCliPrompt as D}from"./prompt.js";import{summarizeCliError as ne}from"../cli-errors.js";import{killOnAbort as se}from"../proc.js";import{sandbox as ae,noteSandbox as ie}from"../sandbox.js";import{pushExtraArgs as le,FORBIDDEN as ce}from"./args.js";import{relayTimeoutMax as ue}from"../relay-timeout.js";import{displayPath as de,resolveWorkdir as H}from"../workdir.js";import{connectorsFor as pe}from"../connectors.js";import{chatWarm as fe}from"./claude-warm.js";async function me(e,t){const n=[];for(let i=0;i<(e?.length||0);i++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[i]?.dataUrl||"");if(!s)continue;const o=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",r=P.join(k.tmpdir(),`chatpanel-claude-img-${t}-${i}.${o}`);await O(r,Buffer.from(s[2],"base64")),n.push(r)}return n}const z=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,U=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task"],B=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),he=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task","ToolSearch"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch"])}),ye=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),be=Object.freeze(["remember","forget"]),G=Object.freeze({device:Object.freeze([]),trusted:ye});function _e(e,t=[]){const n=G[e]||G.device,i=(t||[]).filter(r=>typeof r=="string"&&/^chatpanel/i.test(r)),s=[],o=[];for(const r of i){for(const a of n)s.push(`mcp__${r}__${a}`);for(const a of be)o.push(`mcp__${r}__${a}`)}return{allow:s,deny:o}}function we(e){if(!e||e==="any")return null;const t=B[e]?e:"device";return{allow:[...B[t]],deny:[...he[t]]}}let S="Claude Code not found.",q=0,T=!1;async function Ge(){if(Date.now()-q>(T?3e4:4e3)){q=Date.now();try{x()||!ee()&&await L()?T=!0:(T=!1,S=process.platform==="win32"?"Claude Code not found on Windows PATH or in WSL. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in — in Windows or in your WSL distro.":"Claude Code not found on PATH. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in.")}catch{T=!1}}return T?await re("claude",x()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:j("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:S}}async function qe(){return["opus","sonnet","haiku"]}function Te(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:n,args:i}=te(e.url),s=[...new Set(e.specs.map(o=>o?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:n,args:i}}},allowedTools:s.map(o=>`mcp__${t}__${o}`)}}function Y({prompt:e,args:t,cwd:n,env:i=null,emit:s,signal:o}){const r=x();if(!r)return null;const[a,c,h]=F(r,t,n,i);return new Promise((_,u)=>{ae().wrap(a,c,h,{engine:"claude",cwd:n}).then(y=>{ie(s,y.record);let l;try{l=I(y.bin,y.argv,y.opts)}catch(m){return u(new Error(`Failed to start claude: ${m.message}`))}const p=se(l,o);let d="",w="",f=!1,b=null;const Z={sawText:!1,tail:"",boundary:!1};let A="",C;const v=()=>{clearTimeout(C),C=setTimeout(()=>{l.kill("SIGKILL"),u(new Error(`Claude Code timed out — no output for ${Math.round(z/1e3)}s.`))},z)};v(),l.stdout.on("data",m=>{v(),d+=m.toString();let M;for(;(M=d.indexOf(`
|
|
2
|
+
`))>=0;){const $=d.slice(0,M).trim();if(d=d.slice(M+1),!$.startsWith("{"))continue;let W;try{W=JSON.parse($)}catch{continue}const g=K(W,s,f,n,Z);g.streamed&&(f=!0),g.result!=null&&(A=g.result),g.apiError&&(b=g.apiError)}}),l.stderr.on("data",m=>{v(),w+=m.toString()}),l.on("error",m=>{clearTimeout(C),p(),u(new Error(`Failed to start claude (${a}): ${m.message}`))}),l.on("close",m=>{if(clearTimeout(C),p(),o?.aborted){_({streamedAny:f,resultText:A});return}if(b&&oe(b))return u(new Error(j("Claude Code","claude")));if(m===0&&b)return u(new Error(`Claude Code reported an error: ${b}`));m===0?_({streamedAny:f,resultText:A}):u(new Error(ne("Claude Code",m,w,b||"",{agentId:"claude"})))}),l.stdin.write(e),l.stdin.end()}).catch(u)})}function ge(e){let t="";return typeof e=="string"?t=e:Array.isArray(e)&&(t=e.map(n=>typeof n=="string"?n:n?.text||"").filter(Boolean).join(`
|
|
3
3
|
`)),t.length>4e3?`${t.slice(0,4e3)}…`:t}function J(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
|
|
4
4
|
|
|
5
5
|
`}),e.boundary=!1)}function X(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function K(e,t,n,i="",s=null){const o={streamed:!1,result:null};if(e.type==="stream_event"){const r=e.event;r?.type==="content_block_delta"&&(r.delta?.type==="text_delta"?(o.streamed=!0,J(s,t),t({type:"delta",text:r.delta.text}),X(s,r.delta.text)):r.delta?.type==="thinking_delta"&&t({type:"reasoning",text:r.delta.thinking||""}))}else if(e.type==="assistant"){if(e.is_api_error_message||e.error)return o.apiError=(e.message?.content||[]).filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
6
|
-
`)||String(e.error||"api error"),o;for(const r of e.message?.content||[])r.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:r.name,phase:"start",callId:r.id,input:r.input,summary:
|
|
6
|
+
`)||String(e.error||"api error"),o;for(const r of e.message?.content||[])r.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:r.name,phase:"start",callId:r.id,input:r.input,summary:Ae(r,i)})):r.type==="text"&&!n&&(o.streamed=!0,J(s,t),t({type:"delta",text:r.text}),X(s,r.text))}else if(e.type==="user")for(const r of e.message?.content||[])r.type==="tool_result"&&t({type:"tool",phase:"done",callId:r.tool_use_id,status:r.is_error?"error":"ok",result:ge(r.content)});else if(e.type==="result"){e.is_error?o.apiError=o.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?o.result=e.result||"":t({type:"status",text:`(${e.subtype})`});const r=e.usage||e.message?.usage;r&&t({type:"usage",provider:"bridge",inputTokens:r.input_tokens||0,outputTokens:r.output_tokens||0,cacheReadTokens:r.cache_read_input_tokens||0,cacheWriteTokens:r.cache_creation_input_tokens||0,costUsd:e.total_cost_usd!=null?e.total_cost_usd:null})}return o}const Q=process.env.CHATPANEL_CLAUDE_EFFORT??"low";let E=null;function V({probe:e=null}={}){return E||(E=(async()=>{try{return String(await(e?e():new Promise(t=>{const[n,i,s]=F(x(),["--help"],null),o=I(n,i,{...s,stdio:["ignore","pipe","pipe"]});let r="";o.stdout.on("data",a=>{r+=a}),o.on("error",()=>t("")),o.on("close",()=>t(r)),setTimeout(()=>{try{o.kill()}catch{}t(r)},8e3).unref?.()}))||"")}catch{return""}})(),E)}async function xe(e={}){return/--effort\b/.test(await V(e))}async function Ee(e={}){return/--append-system-prompt(?:-file\b|\[-file\])/.test(await V(e))}function Ye(){E=null}async function Ce({system:e,options:t,tag:n}){const i=t.permissionMode||"default",s=H(t.workingDir),o=["--print","--output-format","stream-json","--include-partial-messages","--verbose"];Q&&await xe()&&o.push("--effort",Q);const r=[],a=[],c=Te(t.mcp);if(c){const l=P.join(k.tmpdir(),`chatpanel-mcp-${n}.json`);await O(l,JSON.stringify(c.config)),r.push(l),o.push("--mcp-config",l),a.push(...c.allowedTools)}const h=we(t.reach);if(h){const l=_e(t.reach,await pe("claude").catch(()=>[]));o.push("--allowedTools",...h.allow,...a,...l.allow),o.push("--disallowedTools",...h.deny,...l.deny)}else i==="bypassPermissions"?o.push("--permission-mode","bypassPermissions"):i==="acceptEdits"?(o.push("--permission-mode","acceptEdits"),a.length&&o.push("--allowedTools",...a)):o.push("--allowedTools",...U,...a);if(e)if(x()?.kind!=="wsl"&&await Ee()){const p=P.join(k.tmpdir(),`chatpanel-system-${n}.md`);await O(p,e,{mode:384}),r.push(p),o.push("--append-system-prompt-file",p)}else o.push("--append-system-prompt",e);t.model&&o.push("--model",t.model),t.useLocalConfig===!1&&o.push("--setting-sources","");const _=c&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(ue(t.mcp?.specs))}:null,u=_||t.runEnv?{...t.runEnv||{},..._||{}}:null;return{args:o,cwd:s,runEnv:u,cleanup:()=>r.forEach(l=>R(l).catch(()=>{})),hasMcp:!!c}}function ke(e,t=[],n=""){let i=D(e,n);return t.length&&(i+=`
|
|
7
7
|
|
|
8
|
-
The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}async function
|
|
8
|
+
The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}async function Je({messages:e,system:t,options:n,images:i},s,{signal:o}={}){const r=await fe({messages:e,system:t,options:n,images:i},s,{signal:o}).catch(a=>({handled:!1,reason:a?.message||String(a),thrown:!0}));if(!r.handled&&!o?.aborted){if(r.thrown)throw new Error(r.reason);return Se({messages:e,system:t,options:n,images:i},s,{signal:o})}}async function Se({messages:e,system:t,options:n,images:i},s,{signal:o}={}){const r=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=await Ce({system:t,options:n,tag:r}),{args:c,cwd:h,runEnv:_}=a,u=await me(i,r),y=()=>{u.forEach(d=>R(d).catch(()=>{})),a.cleanup()},l=ke(e,u);le(c,n.extraArgs,ce.claude,s);const p=Y({prompt:l,args:c,cwd:h,env:_,emit:s,signal:o});if(p===null)return y(),ve({messages:e,system:t,options:n},s,{signal:o});try{const{streamedAny:d,resultText:w}=await p;s({type:"done",text:d?"":w})}finally{y()}}async function Xe({prompt:e,system:t,model:n}){const i=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",n||"haiku","--system-prompt",t||"Continue the user's text briefly. Reply with only the continuation."];let s="";const o=Y({prompt:e,args:i,cwd:null,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(o===null)return Me({prompt:e,system:t,model:n});const{resultText:r}=await o;return(s||r||"").trim()}function Ae(e,t=""){const n=e.input||{};return n.command?String(n.command).slice(0,60):n.file_path?de(n.file_path,t):n.pattern?n.pattern:n.url?n.url:n.description?String(n.description).slice(0,80):n.query?String(n.query).slice(0,80):n.prompt?String(n.prompt).slice(0,80):""}let N=null;function L(){return N||(N=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),N}async function ve({messages:e,system:t,options:n},i,{signal:s}={}){const o=await L();if(!o)throw new Error(S);const{query:r}=o,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const c=n.permissionMode||"default",h=H(n.workingDir),_=c==="acceptEdits"||c==="bypassPermissions",u=new Set(U),y=async f=>u.has(f)||_?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${f} blocked — set this agent's permission mode in ChatPanel to enable it.`};let l=!1;const p={sawText:!1,tail:"",boundary:!1};let d="";const w=r({prompt:D(e),options:{cwd:h,permissionMode:c,includePartialMessages:!0,canUseTool:y,abortController:a,settingSources:n.useLocalConfig===!1?[]:["user","project"],systemPrompt:t?{type:"preset",preset:"claude_code",append:t}:{type:"preset",preset:"claude_code"},...n.model?{model:n.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const f of w){const b=K(f,i,l,h,p);b.streamed&&(l=!0),b.result!=null&&(d=b.result)}}catch(f){if(s?.aborted||a.signal.aborted)return;throw f}i({type:"done",text:l?"":d})}async function Me({prompt:e,system:t,model:n}){const i=await L();if(!i)throw new Error(S);const{query:s}=i;let o="";const r=s({prompt:e,options:{cwd:k.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:t||"Continue the user's text briefly. Reply with only the continuation.",model:n||"haiku"}});for await(const a of r)if(a.type==="assistant")for(const c of a.message.content)c.type==="text"&&(o+=c.text);else a.type==="result"&&a.subtype==="success"&&!o&&(o=a.result||"");return o.trim()}export{Ye as _resetEffortProbe,Ge as available,Ce as buildClaudeLaunch,_e as channelMcpTools,we as channelToolPolicy,Je as chat,Se as chatCold,Te as claudeMcpConfig,ke as claudePrompt,xe as claudeSupportsEffort,Ee as claudeSupportsSystemPromptFile,Xe as complete,K as handleMessage,qe as listModels,me as writeImages};
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import z from"node:os";import
|
|
2
|
-
`);try{return JSON.stringify(e)}catch{return String(e)}}function
|
|
1
|
+
import z from"node:os";import M from"node:path";import{unlink as U}from"node:fs/promises";import{spawnRpcChild as B}from"../rpc-child.js";import{spawnGroupOpts as F}from"../proc.js";import{sandbox as X}from"../sandbox.js";import{createWarmPool as G}from"../warm-pool.js";import{createSession as N,deleteSession as T,rebindSession as J,releaseSession as V}from"../mcp-sessions.js";import{buildCliPrompt as D}from"./prompt.js";import{codexMcpConfigArgs as R,codexDisableArgs as L,configuredMcpServers as K,redundantChatpanelServers as Q,ensureIsolatedHome as Y,writeImages as Z}from"./codex.js";import{disabledMcpServers as ee}from"../mcp-quarantine.js";import{resolveWorkdir as te}from"../workdir.js";import{registerWarmPool as re}from"../warm.js";const q=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,H=process.env.CHATPANEL_CODEX_EFFORT??"low",se=9e4,W=5e3,y=re("codex",G({log:e=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[codex] ${e}`)}}));let O=0;function Ee(){O=0}function ae({agent:e="codex",cwd:d,options:s={},mcpNames:u=[],runEnv:n=null,disabled:c=[]}){return JSON.stringify({agent:e,cwd:d,mode:s.permissionMode||"default",model:s.model||"",local:s.useLocalConfig!==!1,tools:[...u].sort(),env:n?Object.keys(n).sort().map(x=>`${x}=${n[x]}`):[],disabled:[...c].sort()})}function ne(e={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CODEX_APPSERVER==="off"||e.warm===!1||e.extraArgs&&String(e.extraArgs).trim()||Date.now()<O)}function oe(e){return e==="bypassPermissions"?"danger-full-access":e==="acceptEdits"?"workspace-write":"read-only"}function ie(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e?.content))return e.content.map(d=>typeof d=="string"?d:d?.text||"").filter(Boolean).join(`
|
|
2
|
+
`);try{return JSON.stringify(e)}catch{return String(e)}}function le(e,d,s,u){const n=e?.type||"",c=e?.id||`i_${u.n++}`,x=(l,a)=>{u.started.has(c)||(u.started.add(c),s({type:"tool",name:l,phase:"start",callId:c,input:a}))};if(n==="agentMessage"){d&&e.text&&!u.deltaItems.has(c)&&!u.said.has(c)&&(u.said.add(c),s({type:"delta",text:`${u.saidAny?`
|
|
3
3
|
|
|
4
|
-
`:""}${e.text}`}),u.saidAny=!0);return}if(
|
|
5
|
-
${e.text}`});return}if(
|
|
4
|
+
`:""}${e.text}`}),u.saidAny=!0);return}if(n==="commandExecution"){if(x("shell",{command:e.command||""}),d){const l=e.exitCode===0||e.exitCode==null;s({type:"tool",name:"shell",phase:"done",callId:c,status:l?"ok":`exit ${e.exitCode}`,result:String(e.aggregatedOutput||"").slice(0,4e3)})}return}if(n==="fileChange"){const l=Array.isArray(e.changes)?e.changes.map(a=>a?.path||a?.file).filter(Boolean):[];x("edit",{files:l}),d&&s({type:"tool",name:"edit",phase:"done",callId:c,status:e.status==="failed"?"error":"ok"});return}if(n==="webSearch"){const l=e.action&&typeof e.action=="object"?e.action:{},a=e.query||l.query||"",t=l.url||"";x("web_search",{query:a,...t?{url:t}:{}}),d&&s({type:"tool",name:"web_search",phase:"done",callId:c,status:"ok",result:t?`Opened ${t}`:a?`Searched the web for ${a}`:"Searched the web"});return}if(n==="mcpToolCall"){const l=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(x(l,e.arguments&&typeof e.arguments=="object"?e.arguments:{}),d){const a=e.status==="failed"||e.error!=null,t=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error;s({type:"tool",name:l,phase:"done",callId:c,status:a?`error: ${String(t||"failed").slice(0,80)}`:"ok",result:String(a?t||"":ie(e.result)).slice(0,4e3)})}return}if(n==="plan"&&d&&e.text&&u.lastPlan!==e.text){u.lastPlan=e.text,s({type:"status",text:`Plan:
|
|
5
|
+
${e.text}`});return}if(n==="reasoning"&&d){if(u.deltaItems.has(c))return;const l=(Array.isArray(e.summary)?e.summary:[]).map(a=>typeof a=="string"?a:a?.text||"").filter(Boolean).join(`
|
|
6
6
|
`);l&&!u.reasoned.has(c)&&(u.reasoned.add(c),s({type:"reasoning",text:`${l}
|
|
7
|
-
`}))}}function
|
|
8
|
-
`).pop()}`:""}`),t&&t.finish({status:"died",error:
|
|
7
|
+
`}))}}function de(){return{n:0,started:new Set,said:new Set,reasoned:new Set,deltaItems:new Set,saidAny:!1,lastPlan:null}}async function j({bin:e="codex",cwd:d,env:s,configArgs:u=[],options:n={},spawnImpl:c,log:x=()=>{}}){const l=n.permissionMode||"default",a=l==="bypassPermissions";let t=null;const v=new Set;let w="";const S=await X().wrap(e,["app-server",...u],{cwd:d||void 0,env:s,...F},{engine:"codex",cwd:d});S.record.layer==="none"&&x(`sandbox: codex app-server runs outside a sandbox — ${S.record.reason}`);const m=B(S.bin,S.argv,{cwd:d,env:s,spawnImpl:c,spawnOpts:S.opts,onStderr:r=>{w=(w+r).slice(-2e3)},onExit:r=>{x(`app-server exited: ${r.signal||r.code}${w?` — ${w.trim().split(`
|
|
8
|
+
`).pop()}`:""}`),t&&t.finish({status:"died",error:r.error?.message||`Codex exited (${r.signal||r.code})`});for(const o of v)try{o(r)}catch{}},onRequest:async(r,o)=>{if(r==="item/commandExecution/requestApproval"||r==="execCommandApproval")return a||t?.emit({type:"status",text:"Codex asked to run a command outside its sandbox — declined (set Permissions to full access to allow)."}),r==="execCommandApproval"?{decision:a?"approved":"denied"}:{decision:a?"accept":"decline"};if(r==="item/fileChange/requestApproval"||r==="applyPatchApproval")return a||t?.emit({type:"status",text:"Codex asked to change files outside its sandbox — declined (set Permissions to auto-edit or full access to allow)."}),r==="applyPatchApproval"?{decision:a?"approved":"denied"}:{decision:a?"accept":"decline"}},onMessage:r=>{if(!r.method||!t)return;const o=r.params||{};if(o.threadId&&o.threadId!==t.threadId)return;t.touch();const f=r.method;if(f==="item/agentMessage/delta"){if(!o.delta)return;t.state.deltaItems.add(o.itemId),t.state.said.has(o.itemId)||(t.state.said.add(o.itemId),t.state.saidAny&&t.emit({type:"delta",text:`
|
|
9
9
|
|
|
10
|
-
`})),t.state.saidAny=!0,t.streamed=!0,t.emit({type:"delta",text:
|
|
11
|
-
`});else if(
|
|
12
|
-
`).filter(Boolean).pop()||"";throw new Error(
|
|
10
|
+
`})),t.state.saidAny=!0,t.streamed=!0,t.emit({type:"delta",text:o.delta})}else if(f==="item/reasoning/summaryTextDelta"||f==="item/reasoning/textDelta"){if(!o.delta)return;t.state.deltaItems.add(o.itemId),t.streamed=!0,t.emit({type:"reasoning",text:o.delta})}else if(f==="item/reasoning/summaryPartAdded")t.state.deltaItems.has(o.itemId)&&t.emit({type:"reasoning",text:`
|
|
11
|
+
`});else if(f==="item/started"||f==="item/completed"){const i=t.state.started.size+t.state.said.size;le(o.item,f==="item/completed",t.emit,t.state),t.state.started.size+t.state.said.size>i&&(t.streamed=!0)}else if(f==="thread/tokenUsage/updated"){const i=o.tokenUsage?.last||o.tokenUsage?.total;i&&(t.usage={type:"usage",provider:"bridge",inputTokens:i.inputTokens||0,outputTokens:i.outputTokens||0,cacheReadTokens:i.cachedInputTokens||0,cacheWriteTokens:i.cacheWriteInputTokens||0,costUsd:null})}else if(f==="error"){const i=o.error?.message||"error";o.willRetry?t.emit({type:"status",text:`Codex: ${i.slice(0,200)} — retrying`}):t.lastError=i}else if(f==="turn/completed"){const i=o.turn||{};if(t.turnId&&i.id&&i.id!==t.turnId)return;t.finish({status:i.status||"completed",error:i.error?.message||t.lastError||null})}}});let A;try{if(await m.request("initialize",{clientInfo:{name:"chatpanel-bridge",version:"1"},capabilities:{experimentalApi:!0}},{timeoutMs:2e4}),m.notify("initialized"),A=(await m.request("thread/start",{cwd:d||void 0,sandbox:oe(l),approvalPolicy:"never",...n.model?{model:n.model}:{}},{timeoutMs:se}))?.thread?.id,!A)throw new Error("Codex app-server started no thread")}catch(r){m.kill();const o=w.trim().split(`
|
|
12
|
+
`).filter(Boolean).pop()||"";throw new Error(o?`${r.message}: ${o.slice(-300)}`:r.message)}return{threadId:A,get pid(){return m.pid},get alive(){return!m.exited},onExit(r){v.add(r)},close(){m.close()},async turn({prompt:r,imageFiles:o=[],emit:f,signal:i}){if(m.exited)throw new Error("Codex process is gone");if(t)throw new Error("a turn is already running on this thread");const C=de();let E=null,I;const k=new Promise(b=>{I=b}),h={threadId:A,turnId:null,emit:f,state:C,streamed:!1,usage:null,lastError:null,touch(){clearTimeout(E),E=setTimeout(()=>h.finish({status:"timeout",error:`Codex timed out — no output for ${Math.round(q/1e3)}s.`}),q)},finish(b){t===h&&(clearTimeout(E),t=null,I(b))}};t=h,h.touch();const g=async()=>{if(t===h){try{await m.request("turn/interrupt",{threadId:A,turnId:h.turnId},{timeoutMs:W})}catch{}setTimeout(()=>{t===h&&(h.finish({status:"killed",error:null}),m.kill())},W).unref?.()}};if(i?.aborted)return h.finish({status:"killed",error:null}),{streamed:!1,said:!1,status:"killed",usage:null};i?.addEventListener("abort",g,{once:!0}),f({type:"status",text:"Codex working"});try{const b=[{type:"text",text:r},...o.map(P=>({type:"localImage",path:P}))],$=await m.request("turn/start",{threadId:A,input:b,summary:"auto",...H?{effort:H}:{}},{timeoutMs:3e4});h.turnId=$?.turn?.id||null}catch(b){h.finish({status:"failed",error:b.message})}const p=await k;return i?.removeEventListener("abort",g),p.status==="timeout"&&m.kill(),h.usage&&f(h.usage),{streamed:h.streamed,said:C.saidAny,status:p.status,error:p.error,usage:h.usage}}}}const _=new Set;async function ce({key:e,cwd:d,env:s,configArgs:u,options:n,label:c,launch:x=j,force:l=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!l||!e||_.has(e)||y.peek({key:e,messages:[{role:"user",content:""}]}))return!1;_.add(e);const a=y.reserve({key:e,label:`${c} (spare)`,evict:!1});if(!a)return _.delete(e),!1;let t=null;try{const v=[...u];if(n.mcp?.url&&(n.mcp?.specs||[]).length){t=N(()=>{},n.mcp.specs);const m=n.mcp.url.replace(/\/[^/]*$/,"");v.unshift(...R({url:`${m}/${t.id}`,serverName:n.mcp?.serverName||"chatpanel_browser",specs:n.mcp.specs}))}const w=await x({cwd:d,env:s,configArgs:v,options:n});w.mcpSession=t,w.systemSent="",y.attach(a,w);const S=t;return w.onExit(()=>{S&&T(S.id)}),y.release(a,{user:null,answered:!1}),!0}catch(v){return t&&T(t.id),y.drop(a,`spare launch failed: ${v.message}`),!1}finally{_.delete(e)}}async function Ce({messages:e,system:d,options:s,images:u},n,{signal:c,launch:x=j}={}){if(!ne(s))return{handled:!1,reason:"not eligible"};const l=te(s.workingDir),a={...process.env,...s.runEnv||{}};if(s.useLocalConfig===!1){const p=Y();p&&(a.CODEX_HOME=p)}const t=s.mcp?.serverName||"chatpanel_browser",v=a.CODEX_HOME||M.join(z.homedir(),".codex"),w=K(v),S=(s.mcp?.specs||[]).map(p=>p?.name).filter(Boolean),m=[...new Set([...ee("codex",s,[t]),...S.length?Q(v):[]])].filter(p=>w.has(p)),A=ae({cwd:l,options:s,mcpNames:S,runEnv:s.runEnv||null,disabled:m});let r=y.acquire({key:A,messages:e}),o=!1,f=null;if(!r){if(r=y.reserve({key:A,label:`codex ${M.basename(l||"")}`}),!r)return{handled:!1,reason:"all warm slots busy"};o=!0;try{const p=[];if(s.mcp?.url&&S.length){f=N(n,s.mcp.specs);const P=s.mcp.url.replace(/\/[^/]*$/,"");p.push(...R({url:`${P}/${f.id}`,serverName:t,specs:s.mcp.specs}))}p.push(...L(m));const b=await x({cwd:l,env:a,configArgs:p,options:s});b.mcpSession=f,b.systemSent="",y.attach(r,b);const $=f;b.onExit(()=>{$&&T($.id)})}catch(p){return f&&T(f.id),y.drop(r,`launch failed: ${p.message}`),/unknown|unrecognized|unexpected argument|app-server/i.test(p.message)&&(O=Date.now()+10*6e4),{handled:!1,reason:p.message}}}const i=r.session;i.mcpSession&&J(i.mcpSession,n,s.mcp?.specs);const C=e[e.length-1],E=String(d||""),I=o?D(e,E):D([C],E&&E!==i.systemSent?E:""),k=`${Date.now()}-${Math.random().toString(36).slice(2)}`,h=await Z(u,k);let g;try{g=await i.turn({prompt:I,imageFiles:h,emit:n,signal:c})}finally{h.forEach(p=>U(p).catch(()=>{})),i.mcpSession&&V(i.mcpSession)}if(i.systemSent=E,c?.aborted||g.status==="interrupted")return g.status==="interrupted"&&i.alive?y.release(r,{user:String(C?.content||""),answered:g.streamed}):y.drop(r,"stopped"),{handled:!0};if(g.status!=="completed"){if(y.drop(r,g.error||g.status),!g.streamed)return{handled:!1,reason:g.error||g.status};throw new Error(g.error||`Codex ${g.status}`)}return g.said||n({type:"delta",text:"(no output)"}),n({type:"done",text:""}),y.release(r,{user:String(C?.content||""),answered:!0}),setTimeout(()=>{ce({key:A,cwd:l,env:a,configArgs:L(m),options:s,label:`codex ${M.basename(l||"")}`,launch:x}).catch(()=>{})},250).unref?.(),{handled:!0}}export{Ce as chatWarm,le as forwardV2Item,j as launchCodexSession,de as newTurnState,y as pool,ce as prewarmCodex,Ee as resetSupport,ne as warmEligible,ae as warmKey};
|
package/src/engines/codex.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{spawn as B}from"node:child_process";import{killOnAbort as H,spawnGroupOpts as F}from"../proc.js";import{
|
|
2
|
-
`))>=0;){const
|
|
1
|
+
import{spawn as B}from"node:child_process";import{killOnAbort as H,spawnGroupOpts as F}from"../proc.js";import{sandbox as L,noteSandbox as X}from"../sandbox.js";import{readFile as J,unlink as M,writeFile as R}from"node:fs/promises";import{existsSync as N,mkdirSync as q,symlinkSync as z,readFileSync as O}from"node:fs";import S from"node:os";import m from"node:path";import{findAgentBin as W,selfMcpStdio as G,resolveCommand as K}from"../env.js";import{relayTimeoutMax as U}from"../relay-timeout.js";import{buildCliPrompt as Z}from"./prompt.js";import{pushExtraArgs as Q,FORBIDDEN as V}from"./args.js";import{resolveWorkdir as Y}from"../workdir.js";import{summarizeCliError as ee}from"../cli-errors.js";import{signInStatus as te,signInMessage as oe}from"../sign-in.js";import{disabledMcpServers as re,planMcpRetry as ne,quarantine as se}from"../mcp-quarantine.js";import{chatWarm as ae}from"./codex-appserver.js";const j=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,D=process.env.CHATPANEL_CODEX_EFFORT??"low",ce=["gpt-5-codex","gpt-5","o3","o4-mini"];let C=!1;function De(){C=!1}async function Te(){const n=new Set;try{const r=process.env.CODEX_HOME||m.join(S.homedir(),".codex"),t=O(m.join(r,"config.toml"),"utf8");for(const a of t.matchAll(/(?:^|\n)\s*model\s*=\s*["']([^"'\n]+)["']/g))n.add(a[1].trim())}catch{}for(const r of ce)n.add(r);return[...n]}const I=m.join(S.homedir(),".chatpanel","codex-home");let T=!1;function ie(){if(!T)try{q(I,{recursive:!0});const n=m.join(S.homedir(),".codex","auth.json"),r=m.join(I,"auth.json");if(N(n)&&!N(r))try{z(n,r)}catch{}T=!0}catch{return null}return I}let E=!1,P=0;async function Pe(){if(Date.now()-P>(E?3e4:4e3)){P=Date.now();try{E=!!W("codex")}catch{E=!1}}return E?await te("codex",K("codex")).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:oe("Codex","codex")}:{ok:!0}:{ok:!1,reason:"codex not found on PATH. Install it and run `codex login`."}}function le(n){if(!n?.url)return[];const r=n.serverName||"chatpanel_browser",{command:t,args:a}=G(n.url),e=["-c",`mcp_servers.${r}.command=${JSON.stringify(t)}`,"-c",`mcp_servers.${r}.args=${JSON.stringify(a)}`,"-c",`mcp_servers.${r}.default_tools_approval_mode="approve"`,"-c",`mcp_servers.${r}.startup_timeout_sec=30`,"-c",`mcp_servers.${r}.tool_timeout_sec=${Math.ceil(U(n.specs)/1e3)}`],s=[...new Set((n.specs||[]).map(i=>i?.name).filter(Boolean))];return s.length&&e.push("-c",`mcp_servers.${r}.enabled_tools=${JSON.stringify(s)}`),e}function de(n){try{const r=O(m.join(n,"config.toml"),"utf8"),t=new Set;for(const a of r.matchAll(/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*[.\]]/gm))t.add(a[1]);return t}catch{return new Set}}function pe(n){const r=new Set;try{const t=O(m.join(n,"config.toml"),"utf8"),a=/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*\]\s*$([\s\S]*?)(?=^\s*\[|$(?![\r\n]))/gm;for(const e of t.matchAll(a)){const s=e[2]||"",i=/^\s*command\s*=\s*"([^"]*)"/m.exec(s)?.[1]||"",o=/^\s*url\s*=\s*"([^"]*)"/m.exec(s)?.[1]||"";(/chatpanel-(gateway|bridge)(\.js|\.cmd|\.exe)?$/.test(i)||/^https?:\/\/(127\.0\.0\.1|localhost):43(19|20)\//.test(o))&&r.add(e[1])}}catch{}return r}function ue(n=[]){return n.flatMap(r=>["-c",`mcp_servers.${r}.enabled=false`])}async function fe(n,r){const t=[];for(let a=0;a<(n?.length||0);a++){const e=/^data:([^;]+);base64,(.+)$/s.exec(n[a]?.dataUrl||"");if(!e)continue;const s=(e[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",i=m.join(S.tmpdir(),`chatpanel-codex-img-${r}-${a}.${s}`);await R(i,Buffer.from(e[2],"base64")),t.push(i)}return t}async function me({args:n,cwd:r,env:t,prompt:a,outFile:e,emit:s,signal:i}){const o=await L().wrap("codex",n,{cwd:r,stdio:["pipe","pipe","pipe"],env:t,...F},{engine:"codex",cwd:r});return X(s,o.record),new Promise((c,f)=>{let l;try{l=B(o.bin,o.argv,o.opts)}catch(u){return f(new Error(`Failed to start codex: ${u.message}`))}const g=H(l,i);let y="",b="",w=!1;const A=u=>{u?.type!=="status"&&(w=!0),s(u)},_={started:new Set,reasoned:new Set,n:0};let x;const $=()=>{clearTimeout(x),x=setTimeout(()=>{l.kill("SIGKILL"),f(new Error(`Codex timed out — no output for ${Math.round(j/1e3)}s.`))},j)};$(),l.stdout.on("data",u=>{$(),y+=u.toString();let h;for(;(h=y.indexOf(`
|
|
2
|
+
`))>=0;){const v=y.slice(0,h).trim();if(y=y.slice(h+1),!!v.startsWith("{"))try{ge(JSON.parse(v),A,_)}catch{}}}),l.stderr.on("data",u=>{$(),b+=u.toString()}),l.on("error",u=>{clearTimeout(x),g(),f(u)}),l.on("close",async u=>{clearTimeout(x),g();let h="";try{h=(await J(e,"utf8")).trim()}catch{}M(e).catch(()=>{}),c({code:u,stderr:b,text:h,streamed:w,said:!!_.saidAny,policyBlocked:!!_.policyBlocked})}),l.stdin.write(a),l.stdin.end()})}async function Be({messages:n,system:r,options:t,images:a},e,{signal:s}={}){const i=await ae({messages:n,system:r,options:t,images:a},e,{signal:s}).catch(o=>({handled:!1,reason:o?.message||String(o),thrown:!0}));if(!i.handled&&!s?.aborted){if(i.thrown)throw new Error(i.reason);return he({messages:n,system:r,options:t,images:a},e,{signal:s})}}async function he({messages:n,system:r,options:t,images:a},e,{signal:s}={}){const i=`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=m.join(S.tmpdir(),`chatpanel-codex-${i}.txt`),c=await fe(a,i),f=()=>c.forEach(d=>M(d).catch(()=>{})),l=Y(t.workingDir),g=[];Q(g,t.extraArgs,V.codex,e);const y=d=>{const p=["exec","--json","--skip-git-repo-check","-o",o];if(t.permissionMode==="bypassPermissions")p.push("--dangerously-bypass-approvals-and-sandbox");else{const k=t.permissionMode==="acceptEdits"?"workspace-write":"read-only";p.push("-s",k),C||p.push("-c","approval_policy=never")}D&&p.push("-c",`model_reasoning_effort=${D}`),p.push("-c","model_reasoning_summary=auto"),p.push(...le(t.mcp)),p.push(...ue(d)),t.model&&p.push("-m",t.model),p.push(...g);for(const k of c)p.push("-i",k);return p.push("-"),p},b=t.useLocalConfig!==!1,w={...process.env,...t.runEnv||{}};if(!b){const d=ie();d&&(w.CODEX_HOME=d)}const A=t.mcp?.serverName||"chatpanel_browser",_=w.CODEX_HOME||process.env.CODEX_HOME||m.join(S.homedir(),".codex"),x=de(_),$=(t.mcp?.specs||[]).length>0;let u=[...new Set([...re("codex",t,[A]),...$?pe(_):[]])].filter(d=>x.has(d));const h=Z(n,r),v=()=>me({args:y(u),cwd:l,env:w,prompt:h,outFile:o,emit:e,signal:s});try{let d=await v();if(d.policyBlocked&&(C=!0),!s?.aborted&&d.code!==0&&!d.streamed){const p=ne({agent:"codex",text:d.stderr,protect:[A],already:u});p&&x.has(p.server)&&(se("codex",p.server),e({type:"status",text:`MCP server "${p.server}" failed to load — ${p.short}. Skipping it and retrying.`}),u=[...u,p.server],d=await v())}if(s?.aborted)return;if(d.code!==0)throw new Error(ee("Codex",d.code,d.stderr,"",{agentId:"codex"}));d.said||e({type:"delta",text:d.text||"(no output)"}),e({type:"done",text:""})}finally{f()}}function ge(n,r,t={started:new Set,reasoned:new Set,n:0}){const a=n.type||"",e=n.item||{},s=e.type||"",i=a==="item.completed"||e.status==="completed"||e.status==="failed";if(s==="agent_message"&&i){const o=e.id||`msg_${t.n++}`,c=String(e.text||"");c&&!t.said?.has(o)&&((t.said||=new Set).add(o),r({type:"delta",text:`${t.saidAny?`
|
|
3
3
|
|
|
4
|
-
`:""}${c}`}),t.saidAny=!0);return}if(
|
|
5
|
-
`);t.lastTodo!==
|
|
6
|
-
${
|
|
7
|
-
`}));return}(a==="turn.started"||a==="thread.started")&&
|
|
4
|
+
`:""}${c}`}),t.saidAny=!0);return}if(s==="command_execution"||!s&&a.includes("command")){const o=e.id||`cmd_${t.n++}`;if(t.started.has(o)||(t.started.add(o),r({type:"tool",name:"shell",phase:"start",callId:o,input:{command:e.command||""}})),i){const c=e.exit_code===0||e.exit_code==null;r({type:"tool",name:"shell",phase:"done",callId:o,status:c?"ok":`exit ${e.exit_code}`,result:String(e.aggregated_output||"").slice(0,4e3)})}return}if(s==="file_change"||!s&&a.includes("patch")){const o=e.id||`edit_${t.n++}`,c=Array.isArray(e.changes)?e.changes.map(f=>f.path||f.file).filter(Boolean):[];t.started.has(o)||(t.started.add(o),r({type:"tool",name:"edit",phase:"start",callId:o,input:{files:c}})),i&&r({type:"tool",name:"edit",phase:"done",callId:o,status:"ok"});return}if(s==="web_search"){const o=e.id||`ws_${t.n++}`,c=e.action&&typeof e.action=="object"?e.action:{},f=e.query||c.query||"",l=c.url||"";t.started.has(o)||(t.started.add(o),r({type:"tool",name:"web_search",phase:"start",callId:o,input:{query:f,...l?{url:l}:{}}})),(i||a==="item.completed")&&r({type:"tool",name:"web_search",phase:"done",callId:o,status:"ok",result:l?`Opened ${l}`:f?`Searched the web for ${f}`:"Searched the web"});return}if(s==="mcp_tool_call"){const o=e.id||`mcp_${t.n++}`,c=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(t.started.has(o)||(t.started.add(o),r({type:"tool",name:c,phase:"start",callId:o,input:e.arguments&&typeof e.arguments=="object"?e.arguments:{}})),i){const f=e.status==="failed"||e.error!=null,l=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error,g=e.result==null?"":typeof e.result=="string"?e.result:JSON.stringify(e.result);r({type:"tool",name:c,phase:"done",callId:o,status:f?`error: ${String(l||"failed").slice(0,80)}`:"ok",result:String(f?l||"":g).slice(0,4e3)})}return}if(s==="todo_list"&&Array.isArray(e.items)&&e.items.length){const o=e.items.map(c=>`${c.completed?"☑":"☐"} ${c.text||""}`).join(`
|
|
5
|
+
`);t.lastTodo!==o&&(t.lastTodo=o,r({type:"status",text:`Plan:
|
|
6
|
+
${o}`}));return}if(s==="error"||a==="error"){const o=String(e.message||n.message||"");if(!o)return;if(/approval_policy.*(disallowed|not in the allowed set)/i.test(o)){t.policyBlocked=!0,t.policyNoted||(t.policyNoted=!0,r({type:"status",text:"Codex: your organisation pins approval_policy, so Codex will ask before actions it cannot run on its own. ChatPanel will stop passing its own setting."}));return}r({type:"status",text:`Codex: ${o.slice(0,300)}`});return}if(s==="reasoning"||!s&&a.includes("reasoning")){const o=e.id||`r_${t.n++}`,c=e.text||e.summary||"";c&&!t.reasoned.has(o)&&(t.reasoned.add(o),r({type:"reasoning",text:`${c}
|
|
7
|
+
`}));return}(a==="turn.started"||a==="thread.started")&&r({type:"status",text:"Codex working"})}export{Pe as available,Be as chat,he as chatCold,ue as codexDisableArgs,le as codexMcpConfigArgs,de as configuredMcpServers,ie as ensureIsolatedHome,ge as forwardEvent,Te as listModels,pe as redundantChatpanelServers,De as resetApprovalPolicy,fe as writeImages};
|
package/src/engines/custom.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import{spawn as
|
|
2
|
-
`)){const o=
|
|
1
|
+
import{spawn as v}from"node:child_process";import{readFile as W,writeFile as L,unlink as X}from"node:fs/promises";import M from"node:os";import A from"node:path";import{resolveCommand as k,buildSpawnSpec as _,selfMcpStdio as Q}from"../env.js";import{sandbox as I,noteSandbox as Y}from"../sandbox.js";import{isProEntitled as j}from"../entitlement.js";import{killOnAbort as tt}from"../proc.js";import{buildCliPrompt as et,fitCliPrompt as rt,argvPromptBudget as nt}from"./prompt.js";import{pushExtraArgs as ot,FORBIDDEN as U}from"./args.js";import{createStreamParser as it,STREAM_FORMATS as st}from"./stream-formats.js";import{resolveWorkdir as at}from"../workdir.js";async function lt(t,r){const e=[];for(let n=0;n<(t?.length||0);n++){const o=/^data:([^;]+);base64,(.+)$/s.exec(t[n]?.dataUrl||"");if(!o)continue;const s=(o[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",f=A.join(M.tmpdir(),`chatpanel-custom-img-${r}-${n}.${s}`);await L(f,Buffer.from(o[2],"base64")),e.push(f)}return e}function ct(t,r){const e=String(t||"").trim();if(!e||!r.length)return[];const n=[];for(const o of r)n.push(...e.includes("{path}")?e.replaceAll("{path}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]);return n}const D=Number(process.env.CHATPANEL_CUSTOM_TIMEOUT_MS)||18e4,mt="http://127.0.0.1:4319/mcp",B="http://127.0.0.1:4319/mcp";async function Ht(){return{ok:!0}}function ut(t){const r=[],e=new Set;for(const n of String(t||"").split(`
|
|
2
|
+
`)){const o=n.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(o)&&!/^(name|model|models|id|provider|available|usage|options|commands)$/i.test(o)&&!e.has(o)&&(e.add(o),r.push(o),r.length>=200))break}return r}async function Jt(t={}){if(!await j(t.entitlement))throw new Error("Custom agents require ChatPanel Pro.");const r=t.custom||{};return pt(r.command,r.listModelsArgs,t.workingDir)}async function pt(t,r,e){const n=String(r||"").trim();if(!t||!n)return[];const o=await dt(t,n.split(/\s+/).filter(Boolean),e);return ut(o)}async function dt(t,r,e,n=2e4){if(!t)return"";const o=k(t);if(!o)throw new Error(`Couldn't find "${t}".`);const s=e?A.resolve(e):null,[f,w,g]=_(o,r,s);g.env={...g.env||process.env,NO_COLOR:"1",CLICOLOR:"0"};const{bin:y,argv:a,opts:u}=await I().wrap(f,w,g,{engine:"custom",cwd:s});return new Promise((S,i)=>{let d;try{d=v(y,a,u)}catch(C){return i(new Error(`Failed to start ${t}: ${C.message}`))}let m="";const x=setTimeout(()=>{d.kill("SIGKILL"),i(new Error(`${t} timed out.`))},n);d.stdout.on("data",C=>m+=C.toString()),d.on("error",C=>{clearTimeout(x),i(new Error(`Failed to start ${t}: ${C.message}`))}),d.on("close",()=>{clearTimeout(x),S(m)});try{d.stdin.end()}catch{}})}function H(t){return(t?.specs||[]).filter(r=>r?.name)}function J(t,r){const e=String(t).replace(/[^A-Za-z0-9_$]/g,"_");return/^[A-Za-z_$]/.test(e)?e:`tool_${r}_${e}`}function ft(t,r){return["--extension",t]}function gt(t,r){const e=String(t||"").trim(),n=H(r).map(s=>s.name).filter(Boolean);if(!e||!n.length)return[];const o=n.join(",");return e.includes("{tools}")?e.replaceAll("{tools}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]}function ht(t={},r){return t.trustAllToolsForMcp?[t.trustAllToolsArg||"--trust-all-tools"]:t.trustToolsArg?gt(t.trustToolsArg,r):[]}function wt(t={}){return t.stableMcpSetupCommand?t.stableMcpSetupCommand:`opencode mcp add chatpanel --url ${B}`}function St(t={}){const r=typeof t.stableMcpSetupArgs=="function"?t.stableMcpSetupArgs():t.stableMcpSetupArgs,e=Array.isArray(r)?r.filter(n=>n!=null).map(String):null;return e?.length?{command:t.stableMcpSetupCommandName||t.command,args:e}:null}function yt(t){const r=H(t),e=r.map((o,s)=>{const f=J(o.name,s),w=o.parameters||{type:"object",properties:{}};return`const ${f}Tool = {
|
|
3
3
|
name: ${JSON.stringify(o.name)},
|
|
4
4
|
label: ${JSON.stringify(o.name)},
|
|
5
5
|
description: ${JSON.stringify(o.description||o.name)},
|
|
6
|
-
parameters: ${JSON.stringify(
|
|
6
|
+
parameters: ${JSON.stringify(w)},
|
|
7
7
|
async execute(toolCallId, params, signal) {
|
|
8
8
|
return callMcpTool(${JSON.stringify(o.name)}, toolCallId, params, signal);
|
|
9
9
|
},
|
|
10
10
|
};`}).join(`
|
|
11
11
|
|
|
12
|
-
`),r
|
|
12
|
+
`),n=r.map((o,s)=>` pi.registerTool(${J(o.name,s)}Tool);`).join(`
|
|
13
13
|
`);return`import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
14
14
|
|
|
15
15
|
const MCP_URL = ${JSON.stringify(t.url)};
|
|
@@ -63,9 +63,9 @@ async function callMcpTool(toolName, toolCallId, params, signal) {
|
|
|
63
63
|
${e}
|
|
64
64
|
|
|
65
65
|
export default function (pi: ExtensionAPI) {
|
|
66
|
-
${
|
|
66
|
+
${n}
|
|
67
67
|
}
|
|
68
|
-
`}async function
|
|
69
|
-
${
|
|
70
|
-
`).pop()||"failed"}`))});try{
|
|
71
|
-
`).filter(Boolean).slice(-3).join(" ")}`:"")+` Run: ${
|
|
68
|
+
`}async function Ct(t,r){const e=A.join(M.tmpdir(),`chatpanel-pi-tools-${r}.ts`);return await L(e,yt(t)),e}async function $t(){const t=process.env.XDG_CONFIG_HOME||A.join(M.homedir(),".config"),r=[A.join(t,"opencode","opencode.jsonc"),A.join(M.homedir(),"Library","Application Support","opencode","opencode.jsonc")];for(const e of r)try{if((await W(e,"utf8")).includes(mt))return!0}catch{}return!1}async function z(t,r,e){const n=k(t);if(!n)return"";const[o,s,f]=_(n,r,e||null),{bin:w,argv:g,opts:y}=await I().wrap(o,s,f,{engine:"custom",cwd:e||null});return new Promise(a=>{const u=v(w,g,y);let S="",i="";const d=setTimeout(()=>{u.kill("SIGKILL"),a(S+i)},4e3);u.stdout.on("data",m=>S+=m.toString()),u.stderr.on("data",m=>i+=m.toString()),u.on("error",()=>{clearTimeout(d),a(S+i)}),u.on("close",()=>{clearTimeout(d),a(S+i)});try{u.stdin.end()}catch{}})}async function bt(t,r){for(const e of["workspace","global","default"]){const n=await z(t,["mcp","list",e],r);if(n.includes(B)||/chatpanel_browser/i.test(n))return!0}return!1}async function At(t,r){const e=await z(t,["mcp","list"],r);return e.includes(B)||/chatpanel_browser/i.test(e)}async function xt(t,r){return t.stableMcpConfigCheck==="kiro"?bt(t.command||"kiro-cli",r):t.stableMcpConfigCheck==="opencode"?$t():t.stableMcpConfigCheck==="hermes"?At(t.command||"hermes",r):!1}async function Tt(t,r){const e=k(t.command);if(!e)throw new Error(`Couldn't find "${t.command}" to set up browser tools.`);const[n,o,s]=_(e,t.args,r||null);s.env={...s.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"};const{bin:f,argv:w,opts:g}=await I().wrap(n,o,s,{engine:"custom",cwd:r||null});await new Promise((y,a)=>{let u;try{u=v(f,w,g)}catch(m){return a(new Error(`Failed to start ${t.command}: ${m.message}`))}let S="",i="";const d=setTimeout(()=>{u.kill("SIGKILL"),a(new Error(`${t.command} MCP setup timed out.`))},2e4);u.stderr.on("data",m=>S+=m.toString()),u.stdout?.on("data",m=>i+=m.toString()),u.on("error",m=>{clearTimeout(d),a(new Error(`Failed to start ${t.command}: ${m.message}`))}),u.on("close",m=>{if(clearTimeout(d),m===0)return y(`${i}
|
|
69
|
+
${S}`.trim());a(new Error(`${t.command} MCP setup exited ${m}: ${S.trim().split(`
|
|
70
|
+
`).pop()||"failed"}`))});try{u.stdin.end()}catch{}})}function Mt(t,r){const e=String(r?.message||r||"");return/mcp['" ]* Python SDK|No module named ['"]?mcp|MCP support/i.test(e)?`${t} has no MCP support installed. Run \`hermes setup\` (or install the \`mcp\` package in its environment), then retry.`:/streamable_http|HTTP transport/i.test(e)?`${t}'s MCP client has no HTTP transport; ChatPanel registers a stdio server instead. Upgrade its \`mcp\` package if this persists.`:e.slice(0,200)||"the CLI could not register the tools"}async function Et(t,r,e,n,o={}){if(!t.requiresStableMcp)return!0;const s=o.hasConfig||xt,f=o.runSetup||Tt;if(await s(t,r))return!0;const w=wt(t);if(!t.autoSetupStableMcp){const a=`${e} needs one-time browser-tool setup: ${w}`;throw n({type:"status",text:a}),new Error(a)}const g=St(t);if(!g?.command){const a=`${e} needs one-time browser-tool setup: ${w}`;throw n({type:"status",text:a}),new Error(a)}n({type:"status",text:`${e} is setting up one-time browser tools...`});const y=String(await f(g,r)||"").trim();if(await s(t,r))return!0;throw new Error(`${e} browser-tool setup did not register the server.`+(y?` ${y.split(`
|
|
71
|
+
`).filter(Boolean).slice(-3).join(" ")}`:"")+` Run: ${w}`)}async function zt({messages:t,system:r,options:e,images:n},o,{signal:s}={}){if(!await j(e.entitlement))throw new Error("Custom agents require ChatPanel Pro. Upgrade in Settings to bring your own CLI agent.");return Ot(e.custom||{},{messages:t,system:r,options:e,images:n},o,{signal:s})}async function Ot(t,{messages:r,system:e,options:n={},images:o},s,{signal:f}={}){if(!t.command)throw new Error("This agent has no command configured.");const w=k(t.command);if(!w)throw new Error(`Couldn't find "${t.command}". Enter its full path, or install it on your PATH (or in WSL).`);let g=et(r,e),y=at(n.workingDir);const a=t.label||t.command,u=Object.hasOwn(st,t.format)?t.format:"text",S=t.promptVia==="arg"?"arg":"stdin";let i=Array.isArray(t.args)?t.args.slice():t.args?String(t.args).split(/\s+/).filter(Boolean):[];if(ot(i,n.extraArgs,U[t.forbidden]||U.custom,s),n.model&&t.modelArg){const l=String(t.modelArg),c=l.includes("{model}")?l.replaceAll("{model}",n.model).split(/\s+/).filter(Boolean):[...l.split(/\s+/).filter(Boolean),n.model];i=[...i,...c]}if(t.permissionArgs){const l=String(n.permissionMode||"default"),c=t.permissionArgs[l]||t.permissionArgs.default||[];i=[...i,...c.map(String)]}const d=`${Date.now()}-${Math.random().toString(36).slice(2)}`,m=t.imageArg?await lt(o,d):[],x=[],C=()=>[...m,...x].forEach(l=>X(l).catch(()=>{}));if(n.mcp?.url&&t.toolAdapter==="pi-extension"){const l=await Ct(n.mcp,d);x.push(l),i=[...ft(l,n.mcp),...i]}else if(n.mcp?.url&&t.mcpArg){const l=n.mcp.serverName||"chatpanel_browser",{command:c,args:p}=Q(n.mcp.url),h=A.join(M.tmpdir(),`chatpanel-mcp-${d}.json`);await L(h,JSON.stringify({mcpServers:{[l]:{command:c,args:p}}})),x.push(h);const $=String(t.mcpArg);i=[...$.includes("{file}")?$.replaceAll("{file}",h).split(/\s+/).filter(Boolean):[...$.split(/\s+/).filter(Boolean),h],...i]}if(n.mcp?.url)try{await Et(t,y,a,s)}catch(l){s({type:"status",text:`${a}: continuing without ChatPanel's browser tools — ${Mt(a,l)}`}),n={...n,mcp:null}}if(n.mcp?.url&&i.push(...ht(t,n.mcp)),n.model&&typeof t.modelPatch?.build=="function"){const l=/^[A-Za-z0-9][\w.:-]{0,79}$/.test(String(n.model))?String(n.model):"";if(l){const c=A.join(M.tmpdir(),`chatpanel-modelpatch-${d}.yml`);await L(c,t.modelPatch.build(l)),x.push(c);const p=String(t.modelPatch.arg||"--patch {file}");i=[...p.includes("{file}")?p.replaceAll("{file}",c).split(/\s+/).filter(Boolean):[...p.split(/\s+/).filter(Boolean),c],...i]}}const T=ct(t.imageArg,m);let F=!1;if(T.length&&(i=i.flatMap(l=>l==="{images}"?(F=!0,T):[l])),S==="arg"){const l=i.reduce((h,$)=>h+String($).length+3,0)+T.reduce((h,$)=>h+String($).length+3,0),c=rt(r,e,nt({viaCmdExe:w.kind==="cmd",otherArgsChars:l}));(c.dropped||c.prompt!==g)&&(g=c.prompt,s({type:"status",text:`${a} takes the prompt as a command-line argument, which this system caps — the oldest ${c.dropped||"part of the"} turn${c.dropped===1?"":"s"} of this conversation ${c.dropped?"were":"was"} left out to fit.`}));let p=!1;i=i.map(h=>h.includes("{prompt}")?(p=!0,h.replaceAll("{prompt}",g)):h),p||(T.length&&!F&&i.push(...T),i.push(g))}else T.length&&!F&&i.push(...T);const[G,K,N]=_(w,i,y,n.runEnv||null);N.env={...N.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"};const E=await I().wrap(G,K,N,{engine:"custom",cwd:y});Y(s,E.record);const[Z,q,V]=[E.bin,E.argv,E.opts];await new Promise((l,c)=>{let p;try{p=v(Z,q,V)}catch(b){return C(),c(new Error(`Failed to start ${a}: ${b.message}`))}const h=tt(p,f);let $="";const O=it(u,s);let P;const R=()=>{clearTimeout(P),P=setTimeout(()=>{p.kill("SIGKILL"),C(),c(new Error(`${a} timed out — no output for ${Math.round(D/1e3)}s.`))},D)};R(),p.stdout.on("data",b=>{R(),O.push(b.toString())}),p.stderr.on("data",b=>{R(),$+=b.toString()}),p.on("error",b=>{clearTimeout(P),h(),C(),c(new Error(`Failed to start ${a}: ${b.message}`))}),p.on("close",b=>{if(clearTimeout(P),h(),C(),f?.aborted){l();return}b===0?(s({type:"done",text:O.streamed?"":O.finish()}),l()):c(new Error(summarizeCliError(a,b,$)))}),S==="stdin"&&p.stdin.write(g),p.stdin.end()})}export{B as CHATPANEL_STABLE_MCP_URL,Ht as available,yt as buildPiExtensionSource,zt as chat,z as commandOutput,Et as ensureStableMcpConfig,Jt as listModels,pt as listSpecModels,Mt as mcpSetupHint,ht as mcpTrustArgs,ft as piToolArgs,dt as runForStdout,Ot as runSpec,wt as stableMcpSetupCommand,St as stableMcpSetupPlan,gt as trustToolArgs};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{EventError as y}from"./event.js";const f=Object.freeze(["none","process","container","kubernetes"]),g=Object.freeze(["open","allowlist","gateway"]),w=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),h=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),u=Object.freeze({codex:Object.freeze({hosts:["api.openai.com","chatgpt.com","auth.openai.com","*.openai.com"],write:["~/.codex"]}),claude:Object.freeze({hosts:["api.anthropic.com","*.anthropic.com","claude.ai","statsig.anthropic.com"],write:["~/.claude","~/.claude.json"]}),antigravity:Object.freeze({hosts:["*.googleapis.com","*.google.com","oauth2.googleapis.com"],write:["~/.gemini","~/.antigravity","~/.config/antigravity"]}),custom:Object.freeze({hosts:[],write:[]}),mcp:Object.freeze({hosts:[],write:[]})}),b=Object.freeze(["github.com","*.github.com","*.githubusercontent.com","gitlab.com","bitbucket.org","registry.npmjs.org","pypi.org","files.pythonhosted.org","crates.io","static.crates.io","proxy.golang.org","sum.golang.org","huggingface.co","*.huggingface.co"]),c=e=>!!e&&typeof e=="object"&&!Array.isArray(e),m=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0),n=(e,t)=>{if(!e)throw new y("SHAPE",t)},i=e=>[...new Set(e)];function p(e){n(c(e),"kit: must be an object"),n(typeof e.id=="string"&&e.id.length>0,"kit: id required"),n(c(e.network)&&g.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${g.join(", ")}`),n(m(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),n(m(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),n(c(e.filesystem),`kit ${e.id}: filesystem required`);for(const t of["allowWrite","denyWrite","allowRead","denyRead"])n(m(e.filesystem[t]||[]),`kit ${e.id}: filesystem.${t} must be string[]`);return n(m(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),e.image!=null&&n(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&n(Array.isArray(e.credentials)&&e.credentials.every(t=>c(t)&&typeof t.name=="string"&&typeof t.forHost=="string"),`kit ${e.id}: credentials must be [{ name, forHost }]`),{id:e.id,kind:e.kind||"process",image:e.image||null,network:{mode:e.network.mode,allowedDomains:i(e.network.allowedDomains||[]),deniedDomains:i(e.network.deniedDomains||[])},filesystem:{allowWrite:i(e.filesystem.allowWrite),denyWrite:i(e.filesystem.denyWrite||[]),allowRead:i(e.filesystem.allowRead||[]),denyRead:i(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:c(e.limits)?{...e.limits}:{}}}function j({engine:e="custom",cwd:t,mode:r="open",extraHosts:s=[],extraWrite:o=[],extraDenyRead:a=[]}={}){const d=u[e]||u.custom;return n(typeof t=="string"&&t.length>0,"kit: cwd required"),p({id:`${e}:${r}`,kind:"process",network:{mode:r,allowedDomains:r==="open"?["*"]:i([...d.hosts,...b,...s]),deniedDomains:[]},filesystem:{allowWrite:i([t,...h,...d.write,...o]),denyWrite:[],allowRead:[t],denyRead:i([...w,...a])}})}function R(e,{loopback:t=[],home:r="",platform:s="darwin"}={}){const o=p(e),a=l=>r&&l.startsWith("~")?r+l.slice(1):l,d=t.map(l=>`127.0.0.1:${l}`);return{network:{allowedDomains:i([...o.network.allowedDomains,...d]),deniedDomains:o.network.deniedDomains,allowLocalBinding:s==="darwin"&&t.length>0},filesystem:{denyRead:o.filesystem.denyRead.map(a),allowRead:o.filesystem.allowRead.map(a),allowWrite:o.filesystem.allowWrite.map(a),denyWrite:o.filesystem.denyWrite.map(a)}}}function D({layer:e="none",runtime:t=null,kitId:r=null,mode:s=null,reason:o=null}={}){return n(f.includes(e),`sandbox record: layer must be one of ${f.join(", ")}`),{layer:e,runtime:t,kit:r,mode:s,...e==="none"&&o?{reason:o}:{}}}function O(e){const t=String(e);return t===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function E(e={},{platform:t="darwin"}={}){const r={NODE_USE_ENV_PROXY:"1"};if(t==="linux")for(const s of["no_proxy","NO_PROXY"])typeof e[s]=="string"&&(r[s]=e[s].split(",").map(o=>o.trim()).filter(o=>o&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(o)).join(","));return r}function W(e,t=[]){return[e,...t].map(O).join(" ")}export{h as COMMON_WRITE,b as DEVELOPER_HOSTS,u as ENGINE_KITS,g as NETWORK_MODES,f as SANDBOX_LAYERS,w as SECRET_PATHS,j as kitFor,E as sandboxEnvOverlay,D as sandboxRecord,W as shellJoin,O as shellQuote,R as toSrtSettings,p as validateKit};
|
package/src/mcp-local.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{spawn as
|
|
1
|
+
import{spawn as z}from"node:child_process";import{resolveCommand as S,buildSpawnSpec as x}from"./env.js";import{sandbox as C}from"./sandbox.js";const c=new Map,h=new Map,A=10*6e4,I=6e4,w=4e3,_=n=>n.key||`${n.command}\0${(Array.isArray(n.args)?n.args.join(" "):n.args)||""}`;function v(n){clearTimeout(n.idleTimer),n.idleTimer=setTimeout(()=>{try{n.child.kill()}catch{}c.delete(n.key)},A)}function L(n){const e=String(n||"").replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\r/g,`
|
|
2
2
|
`).split(`
|
|
3
3
|
`).map(i=>i.trimEnd()).filter(Boolean).join(`
|
|
4
|
-
`).trim();return
|
|
5
|
-
`))>=0;){const a=t.buf.slice(0,o).trim();if(t.buf=t.buf.slice(o+1),a[0]!=="{"&&a[0]!=="[")continue;let m;try{m=JSON.parse(a)}catch{continue}for(const d of Array.isArray(m)?m:[m]){const
|
|
6
|
-
`);return
|
|
4
|
+
`).trim();return e?e.length>w?`…${e.slice(-w)}`:e:""}function M(n,e){const i=L(e?.stderr);return i?`${n}: ${i}`:n}const g=new Map;async function O(n){const e=_(n),i=c.get(e);if(i&&i.child.exitCode==null&&!i.child.killed)return v(i),i;if(g.has(e))return g.get(e);const s=j(n,e).finally(()=>g.delete(e));return g.set(e,s),s}async function j(n,e){const i=S(n.command);if(!i)throw new Error(`Couldn't find "${n.command}" — enter its full path or install it on PATH.`);const s=Array.isArray(n.args)?n.args:String(n.args||"").split(/\s+/).filter(Boolean),[u,y,f]=x(i,s,n.cwd||null);f.env={...f.env||process.env,...n.env||{}},f.stdio=["pipe","pipe","pipe"];const p=await C().wrap(u,y,f,{engine:"mcp",cwd:n.cwd||null}),[E,P,k]=[p.bin,p.argv,p.opts],l=z(E,P,k),t={key:e,child:l,pending:new Map,buf:"",stderr:"",idleTimer:null,initialized:!1,handshake:null},b=r=>{clearTimeout(t.idleTimer);for(const{reject:o,timer:a}of t.pending.values())clearTimeout(a),o(r);t.pending.clear(),c.get(e)===t&&c.delete(e)};return l.stdout.setEncoding("utf8"),l.stdout.on("data",r=>{t.buf+=r;let o;for(;(o=t.buf.indexOf(`
|
|
5
|
+
`))>=0;){const a=t.buf.slice(0,o).trim();if(t.buf=t.buf.slice(o+1),a[0]!=="{"&&a[0]!=="[")continue;let m;try{m=JSON.parse(a)}catch{continue}for(const d of Array.isArray(m)?m:[m]){const T=d&&d.id!=null?t.pending.get(d.id):null;T&&(clearTimeout(T.timer),t.pending.delete(d.id),T.resolve(d))}}}),l.stderr.setEncoding("utf8"),l.stderr.on("data",r=>{t.stderr+=r,t.stderr.length>w*2&&(t.stderr=t.stderr.slice(-w*2))}),l.on("error",r=>b(new Error(M(`local MCP "${n.command}" failed to start: ${r.message}`,t)))),l.on("close",(r,o)=>{const a=o?`exited with signal ${o}`:r==null?"exited":`exited with code ${r}`;b(new Error(M(`local MCP "${n.command}" ${a}`,t)))}),c.set(e,t),v(t),t}function $(n,e){const i=()=>n.child.stdin.write(JSON.stringify(e)+`
|
|
6
|
+
`);return e.id==null?(i(),Promise.resolve(null)):new Promise((s,u)=>{const y=setTimeout(()=>{n.pending.delete(e.id),u(new Error(M("local MCP call timed out",n)))},I);n.pending.set(e.id,{resolve:s,reject:u,timer:y}),i()})}function B(n,e){return n.initialized?Promise.resolve():(n.handshake||(n.handshake=(async()=>{const i=await $(n,{jsonrpc:"2.0",id:`cp-init-${Date.now()}`,method:"initialize",params:e});if(i?.error)throw new Error(`local MCP re-initialize failed: ${i.error.message||i.error.code}`);await $(n,{jsonrpc:"2.0",method:"notifications/initialized"}),n.initialized=!0})().finally(()=>{n.handshake=null})),n.handshake)}function R(n){return h.has(n)}async function q(n,e){if(!n?.command)throw new Error("no command for local MCP server");const i=await O(n);return v(i),e.method==="initialize"?(h.set(i.key,e.params||{}),i.initialized=!0):e.method==="notifications/initialized"||!i.initialized&&h.has(i.key)&&await B(i,h.get(i.key)),$(i,e)}export{q as callLocalMcp,R as hasInitParams};
|
package/src/pii/pii-detect.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{assertEndpointUrl as
|
|
1
|
+
import{assertEndpointUrl as D}from"./net.js";const A=new Map,m=300;function x(){A.clear()}function T(t,e){let n=5381;const a=`${e?.backend}|${e?.url}|${e?.model}|${t}`;for(let o=0;o<a.length;o++)n=(n<<5)+n+a.charCodeAt(o)|0;return`${a.length}:${n}`}function p(t,e,n){return new Promise((a,o)=>{const r=setTimeout(()=>o(new Error("detect timeout")),Math.max(200,e||1500)),i=()=>{clearTimeout(r),o(new Error("aborted"))};n&&n.addEventListener?.("abort",i,{once:!0}),t.then(s=>{clearTimeout(r),a(s)},s=>{clearTimeout(r),o(s)})})}function y(t){const e=String(t||"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"}[e]||e}const w=new Set(["EMAIL","PHONE","SSN","CREDITCARD","IBAN","ID","SECRET"]),C=new Set(["LOCATION","FAC","ADDRESS","GROUP","NRP"]);function P(t,e,n){const a=r=>!n||n[r]!==!1;return w.has(e)?!0:e==="PERSON"?a("person"):e==="ORG"?a("org"):C.has(e)?a("location"):(String(t).match(/\d/g)||[]).length>=7?a("number"):!1}function R(t,e){let n=[];Array.isArray(t)?n=t:t&&Array.isArray(t.entities)?n=t.entities:t&&Array.isArray(t.ents)?n=t.ents:t&&Array.isArray(t.results)&&(n=t.results);const a=[],o=new Set;for(const r of n){if(!r)continue;const i=String(r.value??r.text??r.entity??r.word??"").trim(),s=y(r.type??r.label??r.entity_group??r.entity_type??r.tag);if(!i||i.length>200||!P(i,s,e))continue;const E=`${s}:${i.toLowerCase()}`;o.has(E)||(o.add(E),a.push({value:i,type:s}))}return a}const d=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 $(t){const e=String(t||"");let n=!1;return{text:e.replace(new RegExp("(^|[^\\p{L}\\p{N}'’])(\\p{Ll})(\\p{L}*)","gu"),(o,r,i,s)=>{const E=i+s;if(d.has(E))return o;const c=i.toUpperCase();return c.length!==1||c===i?o:(n=!0,r+c+s)}),changed:n}}function g(t){if(!t)return null;const e=String(t).indexOf("{"),n=String(t).lastIndexOf("}");if(e<0||n<=e)return null;try{return JSON.parse(String(t).slice(e,n+1))}catch{return null}}const L="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.",M='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 b(t,e,n,a){const o=await a(e.url,{method:"POST",headers:{"Content-Type":"application/json",...e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}},body:JSON.stringify({text:t}),signal:n});if(!o.ok)throw new Error(`detect HTTP ${o.status}`);return R(await o.json(),e.types)}async function k(t,e,n,a,o=f){const r=String(e.url||"").replace(/\/$/,""),i=/\/chat\/completions$/.test(r)?r:/\/v\d+$/.test(r)?`${r}/chat/completions`:`${r}/v1/chat/completions`,s=`${L}
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${o.block||M}`,E=async l=>{const u=o.format?o.format(l):null,h=await a(i,{method:"POST",headers:{"Content-Type":"application/json",...e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}},body:JSON.stringify({model:e.model||"local",temperature:0,max_tokens:e.maxTokens||256,messages:[{role:"system",content:s},{role:"user",content:t}],...u||{}}),signal:n});if(!h.ok){const O=new Error(`detect HTTP ${h.status}`);throw O.status=h.status,O}return h.json()};let c=null;if(o.format)for(const l of["schema","object","none"])try{c=await E(l);break}catch(u){if(l==="none"||u.status!==400&&u.status!==422)throw u}else c=await E("none");const S=c?.choices?.[0]?.message?.content??c?.content??"",N=o.parse?o.parse(S):g(S);return R(N,e.types)}function I(t,e,n,a,o,r){if(typeof t=="function")try{t({backend:e.backend||"",host:U(e.url),chars:n.length,entities:o,ms:Date.now()-a,ok:!r,error:r?String(r.message||r).slice(0,200):""})}catch{}}const U=t=>{try{return new URL(String(t)).host}catch{return""}};async function H(t,e,{signal:n,fetchImpl:a=globalThis.fetch,strict:o=!1,structured:r=f,onEgress:i=null}={}){const s=e?.detection;if(!s||!s.backend||s.backend==="off"||!s.url||typeof a!="function")return[];const E=s.transport==="in-process";if(E&&a===globalThis.fetch)throw new Error("detection.transport 'in-process' needs an injected fetch; refusing to treat a network call as in-process");const c=String(t||"").slice(0,s.maxChars||8e3);if(c.trim().length<8)return[];const S=T(c,s);if(!o&&A.has(S))return A.get(S);const N=s.backend==="endpoint"?b:k;let l=[];try{E||D(s.url);const u=Date.now();try{l=await p(N(c,s,n,a,r),s.timeoutMs||1500,n),E||I(i,s,c,u,l.length,null)}catch(h){throw E||I(i,s,c,u,0,h),h}}catch(u){if(o)throw u;l=[]}return A.size>=m&&A.clear(),o||A.set(S,l),l}export{L as EXTRACT_SYS,x as clearDetectCache,H as detectEntities,R as normalizeEntities,g as parseJsonLoose,$ as recaseForDetection,p as withTimeout};
|
package/src/sandbox.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawn as G,spawnSync as K}from"node:child_process";import{writeFileSync as V,mkdirSync as J}from"node:fs";import{createHash as U}from"node:crypto";import w from"node:os";import H from"node:path";import{kitFor as Y,toSrtSettings as W,sandboxRecord as M,shellJoin as z,sandboxEnvOverlay as q,NETWORK_MODES as Q,ENGINE_KITS as Z,DEVELOPER_HOSTS as ee,SECRET_PATHS as te,COMMON_WRITE as ne}from"./events/sandbox-policy.js";const k="open",re=()=>[Number(process.env.CHATPANEL_GATEWAY_PORT)||4320,Number(process.env.CHATPANEL_BRIDGE_PORT)||Number(process.env.PORT)||4319],O=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean);function se(e=process.env){const t=String(e.CHATPANEL_SANDBOX||k).toLowerCase(),n=t!=="off"&&t!=="0"&&t!=="false",r=Q.includes(t)?t:k;return{enabled:n,mode:r,extraHosts:O(e.CHATPANEL_SANDBOX_ALLOW_HOSTS),extraWrite:O(e.CHATPANEL_SANDBOX_ALLOW_WRITE),extraDenyRead:O(e.CHATPANEL_SANDBOX_DENY_READ)}}const B=new Set;function oe(e,t=H.join(w.tmpdir(),"chatpanel-srt")){const n=JSON.stringify(e),r=H.join(t,`${U("sha256").update(n).digest("hex").slice(0,16)}.json`);return B.has(r)||(J(t,{recursive:!0,mode:448}),V(r,n,{mode:384}),B.add(r)),r}function ae(){try{const e=K(process.platform==="win32"?"where":"which",["srt"],{encoding:"utf8",timeout:3e3});return e.status===0&&String(e.stdout||"").trim().length>0}catch{return!1}}function ie({config:e=se(),loadSrt:t=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:n=ae,compiled:r=!1,platform:s=process.platform,home:p=w.homedir(),loopback:i=re(),log:u=()=>{}}={}){let d=null,l=null,m=null,S=null;async function v(){if(!(d||l)){if(!e.enabled){l="sandboxing is off (CHATPANEL_SANDBOX=off)";return}if(!r)try{if(m=await t(),m?.SandboxManager?.wrapWithSandboxArgv){d="srt-lib";return}}catch(o){u(`sandbox: library not available (${o.message})`)}if(n()){d="srt-cli";return}l=r?"srt is not on PATH — the compiled bridge cannot carry it: npm i -g @anthropic-ai/sandbox-runtime":"sandbox-runtime is not installed — it ships with the gateway; standalone: npm i -g @anthropic-ai/sandbox-runtime"}}function $(){const o=e.mode==="open"?["*"]:[...new Set([...Object.values(Z).flatMap(c=>c.hosts),...ee,...e.extraHosts])],x={id:`session:${e.mode}`,network:{mode:e.mode,allowedDomains:o},filesystem:{allowWrite:[w.tmpdir(),...ne,...e.extraWrite],denyRead:[...te,...e.extraDenyRead]}};return W(x,{loopback:i,home:s==="linux"?p:"",platform:s})}async function F(){return S||(S=m.SandboxManager.initialize($())),S}return{config:e,async status(){return await v(),{enabled:e.enabled,mode:e.mode,runtime:d,platform:s,...l?{reason:l}:{}}},async wrap(o,x,c,{engine:j="custom",cwd:I=null,commandId:N=null}={}){await v();const R=I||c?.cwd||process.cwd(),h=a=>({bin:o,argv:x,opts:c,record:M({layer:"none",reason:a})});if(!d)return h(l);let b;try{b=Y({engine:j,cwd:R,mode:e.mode,extraHosts:e.extraHosts,extraWrite:[w.tmpdir(),...e.extraWrite],extraDenyRead:e.extraDenyRead})}catch(a){return h(`kit: ${a.message}`)}const f=W(b,{loopback:i,home:s==="linux"?p:"",platform:s}),A=z(o,x),L=M({layer:"process",runtime:d,kitId:b.id,mode:b.network.mode});try{if(d==="srt-lib"){await F();const a=s==="win32"?{denyRead:f.filesystem.denyRead,denyWrite:f.filesystem.denyWrite}:f.filesystem,_=await m.SandboxManager.wrapWithSandboxArgv(A,void 0,{filesystem:a},void 0,R,N?{commandId:N,commandText:A}:void 0),X=c?.env||process.env,C={};for(const[D,P]of Object.entries(_.env||{}))process.env[D]!==P&&(C[D]=P);const E={...X,...C};return Object.assign(E,q(E,{platform:s})),{bin:_.argv[0],argv:_.argv.slice(1),opts:{...c,env:E,shell:!1},record:L}}return{bin:"srt",argv:["-s",oe(f),"-c",A],opts:{...c,shell:!1},record:L}}catch(a){return u(`sandbox: could not wrap ${o}: ${a.message}`),h(`sandbox-runtime failed to wrap the command: ${a.message}`)}},violations(o){try{return m?.SandboxManager?.getSandboxViolationStore?.()?.getViolationsForCommand?.(o)||[]}catch{return[]}}}}let y=null;function de(){if(!y){const{isCompiledBinary:e}=ce();y=ie({compiled:e(),log:t=>console.error(`[bridge] ${t}`)})}return y}function fe(e){y=e}let T=null;function ce(){return T||(T={isCompiledBinary:()=>{const e=(process.execPath||"").split(/[\\/]/).pop().toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}}),T}const g=new Set;function we(e,t){if(!t||t.layer!=="none"||typeof e!="function")return;const n=t.reason||"unknown";g.has(n)||(g.add(n),e({type:"status",text:`Running outside a sandbox — ${n}`}))}function ye(){g.clear()}async function Se(e,t,n,r={},{spawnImpl:s=G,box:p=de()}={}){const i=await p.wrap(e,t,n,r),u=s(i.bin,i.argv,i.opts);try{u.sandbox=i.record}catch{}return u}export{ye as _resetNotedForTest,fe as _setSandboxForTest,ie as createSandbox,we as noteSandbox,de as sandbox,se as sandboxConfigFromEnv,Se as sandboxedSpawn};
|
package/src/server.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createServer as fe}from"node:http";import A from"node:os";import{randomBytes as ge,randomInt as ye,timingSafeEqual as we}from"node:crypto";import{mkdirSync as be,writeFileSync as Se,readFileSync as K,existsSync as ke}from"node:fs";import{join as _}from"node:path";import*as Te from"./engines/claude.js";import*as ve from"./engines/codex.js";import*as Ce from"./engines/antigravity.js";import{pi as Ee,opencode as Oe,kiro as Pe,copilot as Ae,deepseek as xe,hermes as $e}from"./engines/cli-agents.js";import{connectorsFor as Ie}from"./connectors.js";import*as Ne from"./engines/custom.js";import{installService as Re,uninstallService as _e,serviceStatus as He,restartService as V}from"./service.js";import{skillIndex as D,listRecords as Me,readRecord as Be,readPackageFile as Ge,skillsHealth as Ue,quarantinedSkills as De}from"./skills.js";import{capabilityToolSpecs as Le,runCapabilityTool as je}from"./mcp-capabilities.js";import{createSession as We,deleteSession as X,getSession as Y,activeSession as Fe,relayToolCall as Je}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ze,isDefaultWorkdir as Ke,resolveWorkdir as Ve,writeScopeNote as Xe}from"./workdir.js";import{gitState as Ye,gitDelta as Qe}from"./scm.js";import{listConnections as Ze,putConnection as qe,removeConnection as et,runEnvFor as tt,testConnection as nt,secretBackend as Q}from"./connections.js";import{worktreeFor as Z,listWorktrees as rt,removeWorktree as ot,withHook as at,WORKTREE_ROOT as q}from"./worktree.js";import{AGENT_CLIS as it,enrichPath as st,enrichAgentEnv as ct,findAgentBin as ee,resolveCommand as lt}from"./env.js";import"./sanitize.js";import{checkForUpdate as dt,selfUpdate as te,isEmbedded as ut}from"./update.js";import{callLocalMcp as ht}from"./mcp-local.js";import{assertPublicHttpUrl as ne,assertPublicWebUrl as re}from"./ssrf.js";import{startRun as oe,endRun as L,cancelRun as pt,cancelAll as mt}from"./runs.js";import{closeWarmPools as ft,warmStatus as gt}from"./warm.js";import{CompatError as x,anthropicError as j,anthropicStream as yt,chatCompletionStream as wt,completionStream as bt,createAnthropicMessage as St,createChatCompletion as kt,createCompletion as Tt,createResponse as vt,openAIError as w,parseAnthropicMessage as Ct,parseChatCompletion as Et,parseCompletion as Ot,parseResponse as Pt,responseStream as At}from"./api-compat.js";import{callerTrust as xt,isPaired as $,parseExtensionIds as $t,capRunOptions as It,engineHonoursReach as Nt,createPairingStore as Rt,formatPairingCode as _t}from"./pii/trust.js";const g="0.13.9",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Te,label:"Claude Code"},codex:{engine:ve,label:"Codex"},antigravity:{engine:Ce,label:"Antigravity",tools:!1},pi:{engine:Ee,label:"Pi"},opencode:{engine:Oe,label:"OpenCode"},hermes:{engine:$e,label:"Hermes"},kiro:{engine:Pe,label:"Kiro"},copilot:{engine:Ae,label:"GitHub Copilot"},deepseek:{engine:xe,label:"DeepSeek Harness"},custom:{engine:Ne,label:"Custom",hidden:!0}};function ae(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Ht=$t(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function I(n){return n.chatpanelTrust||(n.chatpanelTrust=xt({origin:n.headers.origin||"",hasToken:le(n),extensionIds:Ht})),n.chatpanelTrust}function Mt(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Bt(n,e){const t=n.headers.origin||"",o=ae(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const W=new Set(["127.0.0.1","localhost","::1"]);function Gt(n){if(!W.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return W.has(t)}const N=_(A.homedir(),".chatpanel","bridge-token");let S="";function Ut(){try{ke(N)&&(S=K(N,"utf8").trim()),S||(S=ge(32).toString("hex"),be(_(A.homedir(),".chatpanel"),{recursive:!0}),Se(N,S,{mode:384}))}catch(n){d("error",`could not initialise bridge token: ${n?.message||n}`)}}const ie=Rt({random:()=>ye(0,1e6)/1e6});function Dt(n){if(!S)return a(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ie.issue();return d("info","pairing code issued — valid for 5 minutes, one use"),a(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Lt(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=ie.claim(t?.code);return o.ok?(d("info",`paired a ${I(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),a(e,200,{ok:!0,token:S})):(d("info",`pairing refused (${o.reason}) from ${I(n)} caller`),a(e,403,{error:o.reason}))}function jt(n,e){const t=I(n);return a(e,200,{ok:!0,trust:t,paired:$(t),version:g})}let H=null;async function se(){if(H)return H;const{createChannelService:n}=await import("./channels/service.js");return H=n({home:_(A.homedir(),".chatpanel"),dataDir:_(A.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>d("info",e),warn:e=>d("info",e),error:e=>d("error",e)}}),H}async function ce(n,e,t){try{const o=await se(),r=n.method==="POST"?await f(n):{};if(t==="status")return a(e,200,await o.status());if(t==="connect"){const i=await o.connect(r);return a(e,200,{ok:!0,...i})}return t==="pair"?a(e,200,await o.pair()):t==="unpair"?a(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?a(e,200,await o.update(r)):t==="disconnect"?a(e,200,await o.stop({forget:!!r.forget})):a(e,404,{error:"unknown channel action"})}catch(o){return a(e,400,{error:o?.message||String(o)})}}function le(n){if(!S)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(S);return o.length===r.length&&we(o,r)}const Wt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),Ft=new Set(["/debug"]),Jt=n=>Ft.has(n);function zt(n,e){if(!Gt(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ae(t))return"forbidden origin";const o=n.method==="POST"&&Wt.has(e)||n.method==="GET"&&Jt(e);return o&&!(Mt(t)||le(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!$(I(n))&&!Vt.has(e)?Kt:null}const Kt="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",Vt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(n,e,t){const o=I(n),r=It(t,o);if(!Nt(e,r.reach))return{error:`${$(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${$(o)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const i=r.reach,s=$(o)?i==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":i==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:r,note:s}}function a(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}async function Xt(n){const e=await Promise.all(Object.entries(C).filter(([,r])=>!r.hidden).map(async([r,{engine:i,label:s,tools:u}])=>{const c=await i.available().catch(h=>({ok:!1,reason:String(h?.message||h)})),l=await Ie(r).catch(()=>[]);return{id:r,label:s,available:c.ok,reason:c.reason,connectors:l,...u===!1?{tools:!1}:{}}})),t=ut()?{current:g,updateAvailable:!1,embedded:"gateway"}:await dt(g).catch(()=>({current:g,updateAvailable:!1})),o=await Ue().catch(()=>null);a(n,200,{ok:!0,version:g,agents:e,update:t,workspace:ze,worktrees:q,secretBackend:Q(),warm:gt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...o?{skills:o}:{}})}async function Yt(n,e,t){const{index:o,problems:r}=await D({extraDirs:e,workdir:t});a(n,200,{ok:!0,skills:Me(o),problems:r})}async function Qt(n,e,t){a(n,200,{ok:!0,quarantined:await De(e,t)})}async function Zt(n,e,t,o){const{index:r}=await D({extraDirs:t,workdir:o}),i=Be(r,e);if(!i)return a(n,404,{ok:!1,error:"unknown skill"});a(n,200,{ok:!0,skill:i})}async function qt(n,e,t,o,r){const{index:i}=await D({extraDirs:o,workdir:r}),s=await Ge(i,e,t);if(s.error)return a(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});a(n,200,{ok:!0,...s})}async function en(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function de(n,e=""){const t=await en();if(e){const o=t.find(r=>r.id===e);return o?a(n,200,o):a(n,404,w(new x(`Model "${e}" not found`,404,"model")))}return a(n,200,{object:"list",data:t})}async function tn(n){try{const e=await te(g);a(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){a(n,400,{ok:!1,error:String(e?.message||e)})}}async function nn(n,e){let t;try{t=await f(n)}catch(p){return a(e,400,{error:"Bad JSON: "+p.message})}const o=C[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});const r=F(n,t.agent,t.options||{});if(r.error)return a(e,403,{error:r.error});t.options=r.options,Array.isArray(t.images)&&t.images.length&&d("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const i=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
|
|
2
|
+
import{createServer as fe}from"node:http";import A from"node:os";import{randomBytes as ge,randomInt as ye,timingSafeEqual as we}from"node:crypto";import{mkdirSync as be,writeFileSync as Se,readFileSync as K,existsSync as ke}from"node:fs";import{join as _}from"node:path";import*as Te from"./engines/claude.js";import*as ve from"./engines/codex.js";import*as Ce from"./engines/antigravity.js";import{pi as Ee,opencode as Oe,kiro as Pe,copilot as Ae,deepseek as xe,hermes as $e}from"./engines/cli-agents.js";import{connectorsFor as Ie}from"./connectors.js";import*as Ne from"./engines/custom.js";import{installService as Re,uninstallService as _e,serviceStatus as He,restartService as V}from"./service.js";import{skillIndex as D,listRecords as Me,readRecord as Be,readPackageFile as Ge,skillsHealth as Ue,quarantinedSkills as De}from"./skills.js";import{capabilityToolSpecs as Le,runCapabilityTool as je}from"./mcp-capabilities.js";import{createSession as We,deleteSession as X,getSession as Y,activeSession as Fe,relayToolCall as Je}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ze,isDefaultWorkdir as Ke,resolveWorkdir as Ve,writeScopeNote as Xe}from"./workdir.js";import{sandbox as Ye}from"./sandbox.js";import{gitState as Qe,gitDelta as Ze}from"./scm.js";import{listConnections as qe,putConnection as et,removeConnection as tt,runEnvFor as nt,testConnection as rt,secretBackend as Q}from"./connections.js";import{worktreeFor as Z,listWorktrees as ot,removeWorktree as at,withHook as it,WORKTREE_ROOT as q}from"./worktree.js";import{AGENT_CLIS as st,enrichPath as ct,enrichAgentEnv as lt,findAgentBin as ee,resolveCommand as dt}from"./env.js";import"./sanitize.js";import{checkForUpdate as ut,selfUpdate as te,isEmbedded as ht}from"./update.js";import{callLocalMcp as pt}from"./mcp-local.js";import{assertPublicHttpUrl as ne,assertPublicWebUrl as re}from"./ssrf.js";import{startRun as oe,endRun as L,cancelRun as mt,cancelAll as ft}from"./runs.js";import{closeWarmPools as gt,warmStatus as yt}from"./warm.js";import{CompatError as x,anthropicError as j,anthropicStream as wt,chatCompletionStream as bt,completionStream as St,createAnthropicMessage as kt,createChatCompletion as Tt,createCompletion as vt,createResponse as Ct,openAIError as b,parseAnthropicMessage as Et,parseChatCompletion as Ot,parseCompletion as Pt,parseResponse as At,responseStream as xt}from"./api-compat.js";import{callerTrust as $t,isPaired as $,parseExtensionIds as It,capRunOptions as Nt,engineHonoursReach as Rt,createPairingStore as _t,formatPairingCode as Ht}from"./pii/trust.js";const y="0.14.0",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Te,label:"Claude Code"},codex:{engine:ve,label:"Codex"},antigravity:{engine:Ce,label:"Antigravity",tools:!1},pi:{engine:Ee,label:"Pi"},opencode:{engine:Oe,label:"OpenCode"},hermes:{engine:$e,label:"Hermes"},kiro:{engine:Pe,label:"Kiro"},copilot:{engine:Ae,label:"GitHub Copilot"},deepseek:{engine:xe,label:"DeepSeek Harness"},custom:{engine:Ne,label:"Custom",hidden:!0}};function ae(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Mt=It(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function I(n){return n.chatpanelTrust||(n.chatpanelTrust=$t({origin:n.headers.origin||"",hasToken:le(n),extensionIds:Mt})),n.chatpanelTrust}function Bt(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 Gt(n,e){const t=n.headers.origin||"",o=ae(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const W=new Set(["127.0.0.1","localhost","::1"]);function Ut(n){if(!W.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return W.has(t)}const N=_(A.homedir(),".chatpanel","bridge-token");let S="";function Dt(){try{ke(N)&&(S=K(N,"utf8").trim()),S||(S=ge(32).toString("hex"),be(_(A.homedir(),".chatpanel"),{recursive:!0}),Se(N,S,{mode:384}))}catch(n){d("error",`could not initialise bridge token: ${n?.message||n}`)}}const ie=_t({random:()=>ye(0,1e6)/1e6});function Lt(n){if(!S)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ie.issue();return d("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function jt(n,e){let t;try{t=await f(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=ie.claim(t?.code);return o.ok?(d("info",`paired a ${I(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(d("info",`pairing refused (${o.reason}) from ${I(n)} caller`),i(e,403,{error:o.reason}))}function Wt(n,e){const t=I(n);return i(e,200,{ok:!0,trust:t,paired:$(t),version:y})}let H=null;async function se(){if(H)return H;const{createChannelService:n}=await import("./channels/service.js");return H=n({home:_(A.homedir(),".chatpanel"),dataDir:_(A.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>d("info",e),warn:e=>d("info",e),error:e=>d("error",e)}}),H}async function ce(n,e,t){try{const o=await se(),r=n.method==="POST"?await f(n):{};if(t==="status")return 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 le(n){if(!S)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(S);return o.length===r.length&&we(o,r)}const Ft=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),Jt=new Set(["/debug"]),zt=n=>Jt.has(n);function Kt(n,e){if(!Ut(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ae(t))return"forbidden origin";const o=n.method==="POST"&&Ft.has(e)||n.method==="GET"&&zt(e);return o&&!(Bt(t)||le(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!$(I(n))&&!Xt.has(e)?Vt:null}const Vt="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",Xt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(n,e,t){const o=I(n),r=Nt(t,o);if(!Rt(e,r.reach))return{error:`${$(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${$(o)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=r.reach,s=$(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 → Agent Tools 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 f(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}async function Yt(n){const e=await Promise.all(Object.entries(C).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:u,tools:c}])=>{const l=await s.available().catch(g=>({ok:!1,reason:String(g?.message||g)})),h=await Ie(a).catch(()=>[]);return{id:a,label:u,available:l.ok,reason:l.reason,connectors:h,...c===!1?{tools:!1}:{}}})),t=ht()?{current:y,updateAvailable:!1,embedded:"gateway"}:await ut(y).catch(()=>({current:y,updateAvailable:!1})),o=await Ue().catch(()=>null),r=await Ye().status().catch(a=>({enabled:!1,reason:a.message}));i(n,200,{ok:!0,version:y,agents:e,update:t,workspace:ze,sandbox:r,worktrees:q,secretBackend:Q(),warm:yt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...o?{skills:o}:{}})}async function Qt(n,e,t){const{index:o,problems:r}=await D({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:Me(o),problems:r})}async function Zt(n,e,t){i(n,200,{ok:!0,quarantined:await De(e,t)})}async function qt(n,e,t,o){const{index:r}=await D({extraDirs:t,workdir:o}),a=Be(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function en(n,e,t,o,r){const{index:a}=await D({extraDirs:o,workdir:r}),s=await Ge(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 tn(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function de(n,e=""){const t=await tn();if(e){const o=t.find(r=>r.id===e);return o?i(n,200,o):i(n,404,b(new x(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function nn(n){try{const e=await te(y);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function rn(n,e){let t;try{t=await f(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const o=C[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=F(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&&d("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
|
|
3
3
|
|
|
4
|
-
`)};let s=!1;const u=`run_${Math.random().toString(36).slice(2,10)}`,c=oe(u),l={signal:c.signal,abort:()=>c.cancel("client")},h=()=>{s=!0,c.cancel("disconnected")};n.on("close",h),e.on("close",h),e.on("error",h);const
|
|
4
|
+
`)};let s=!1;const u=`run_${Math.random().toString(36).slice(2,10)}`,c=oe(u),l={signal:c.signal,abort:()=>c.cancel("client")},h=()=>{s=!0,c.cancel("disconnected")};n.on("close",h),e.on("close",h),e.on("error",h);const g=p=>{s||a(p)};a({type:"run",id:u}),r.note&&a({type:"status",text:r.note});let m=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const p=t.options.workspace;if(m=await Z({repo:p.repo,projectId:p.projectId,jobId:p.jobId,base:p.base||null}),m.error){a({type:"error",error:`workspace: ${m.error}`}),L(u),e.writableEnded||e.end();return}}const J=m?m.path:Ve(t.options?.workingDir);let E=null;{const p=J,O=!!m||!Ke(t.options?.workingDir),w=Xe(t.agent,t.options?.permissionMode,p);a({type:"workdir",path:p,isDefault:!O,writeScope:w||void 0}),a({type:"status",text:`Working in ${p}${O?"":" (default)"}`}),w&&a({type:"status",text:w}),E=await Qe(p),E&&a({type:"scm",phase:"before",...E})}let U=null;if(E||m){const p=Array.isArray(t.options?.grants)?t.options.grants:[],{env:O,connection:w}=nt({remote:E?.remote||null,grants:p,branch:m?.branch||null,connectionId:t.options?.connectionId||null});U=it(O),m&&a({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...w?{connection:w}:{}}),w&&a({type:"status",text:`Git credential: ${w.kind} · ${w.host}${w.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const z={...t.options||{},...m?{workingDir:m.path}:{},...U?{runEnv:U}:{}};let R=null;t.pageTools?.specs?.length&&(R=We(g,t.pageTools.specs),z.mcp={url:`http://${k}:${v}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs});try{await o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:z,images:Array.isArray(t.images)?t.images:[]},g,{signal:l.signal})}catch(p){d("error",`${t.agent} chat failed: ${p?.message||p}`),a({type:"error",error:p?.message||String(p)})}finally{if(!s){const p=await Ze(J,E).catch(()=>null);p&&g({type:"scm",phase:"after",...p})}L(u),R&&X(R.id),e.writableEnded||e.end()}}async function on(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:qe(),secretBackend:Q()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await f(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:et(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:tt(r[1])}):i(e,200,rt(r[1],o.remote||"")):i(e,404,{error:"Not found"})}async function an(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:q,worktrees:await ot()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await f(n);if(t==="/worktrees"){const r=await Z({repo:o.repo,projectId:o.projectId,jobId:o.jobId,base:o.base||null});return i(e,r.error?400:200,r.error?{error:r.error}:{ok:!0,...r})}if(t==="/worktrees/remove"){const r=await at({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 T(n,e,t){const o=C[n.agent];if(!o||o.hidden)throw new x(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const r=await o.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!r.ok)throw new x(r.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=oe(a),u=()=>s.cancel("disconnected");t.on("close",u);let c="";try{return await o.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal}),c}finally{t.off("close",u),L(a)}}function M(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function P(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
|
|
5
5
|
|
|
6
6
|
`)}function B(n,e,t){n.writableEnded||n.write(`event: ${e}
|
|
7
7
|
data: ${JSON.stringify(t)}
|
|
8
8
|
|
|
9
|
-
`)}async function G(n,e,t,o){try{const r=t(await f(n)),i=F(n,r.agent,r.options||{});if(i.error)throw new x(i.error,403,"permission");return r.options=i.options,r}catch(r){return a(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new x(`Bad JSON: ${r.message}`):r)),null}}async function an(n,e){const t=await G(n,e,Et,w);if(!t)return;if(!t.stream)try{const r=await T(t,()=>{},e);return a(e,200,kt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,w(r))}M(e);const o=wt(t.requestedModel,r=>P(e,r));try{await T(t,r=>o.delta(r),e),o.done()}catch(r){P(e,w(r))}P(e,"[DONE]"),e.end()}async function sn(n,e){const t=await G(n,e,Ot,w);if(!t)return;if(!t.stream)try{const r=await T(t,()=>{},e);return a(e,200,Tt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,w(r))}M(e);const o=bt(t.requestedModel,r=>P(e,r));try{await T(t,r=>o.delta(r),e),o.done()}catch(r){P(e,w(r))}P(e,"[DONE]"),e.end()}async function cn(n,e){const t=await G(n,e,Pt,w);if(!t)return;if(!t.stream)try{const r=await T(t,()=>{},e);return a(e,200,vt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,w(r))}M(e);const o=At(t.requestedModel,r=>B(e,r.type,r));try{await T(t,r=>o.delta(r),e),o.done()}catch(r){const i={type:"error",sequence_number:0,...w(r)};B(e,"error",i)}e.end()}async function ln(n,e){const t=await G(n,e,Ct,j);if(!t)return;if(!t.stream)try{const r=await T(t,()=>{},e);return a(e,200,St(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,j(r))}M(e);const o=yt(t.requestedModel,(r,i)=>B(e,r,i));try{await T(t,r=>o.delta(r),e),o.done()}catch(r){B(e,"error",j(r))}e.end()}async function dn(n,e){let t={};try{t=await f(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?pt(o,"stopped"):!1;return r&&d("info",`cancel: ${o} stopped by client`),a(e,200,{ok:!0,cancelled:r})}async function ue(n,e,t){let o;try{o=await f(n)}catch{return a(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=t?Y(t):Fe(),i=c=>{r&&e.setHeader("Mcp-Session-Id",r.id),a(e,200,{jsonrpc:"2.0",id:o.id??null,result:c})},s=(c,l)=>a(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:c,message:l}});if(o.id==null)return e.writeHead(202),e.end();if(o.method==="initialize")return i({protocolVersion:o.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const u=Le();if(o.method==="tools/list"){const c=r?r.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return i({tools:[...u,...c]})}if(o.method==="tools/call"){const c=await je(o.params?.name,o.params?.arguments||{});if(c)return i(c);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 i(await Je(r,o.params?.name,o.params?.arguments||{}))}catch(l){return i({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function un(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const o=t.server||{},r=t.message;if(!o.command||!r)return a(e,400,{error:"need server.command and message"});try{const i=await ht({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd},r);return r.id==null?(e.writeHead(202),e.end()):a(e,200,i)}catch(i){return a(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:-32e3,message:String(i?.message||i)}})}}async function hn(n,e){let t;try{t=await f(n)}catch(h){return a(e,400,{error:"Bad JSON: "+h.message})}const{url:o,headers:r,message:i}=t||{};if(!o||!i)return a(e,400,{error:"need url and message"});let s;try{s=ne(o)}catch(h){return a(e,400,{error:String(h?.message||h)})}const u={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[h,b]of Object.entries(r)){const m=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(m)||m.startsWith("x-"))&&(u[h]=String(b))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:u,body:JSON.stringify(i),redirect:"follow",signal:c.signal});try{h.url&&ne(h.url)}catch(m){return a(e,400,{error:String(m?.message||m)})}const b=await h.text().catch(()=>"");return a(e,200,{status:h.status,sessionId:h.headers.get("Mcp-Session-Id")||null,contentType:h.headers.get("Content-Type")||"",body:b})}catch(h){const b=h?.name==="AbortError"?"timed out":String(h?.message||h);return a(e,502,{error:`couldn't reach MCP server ${s.host}: ${b}`})}finally{clearTimeout(l)}}const he=256*1024,pn=5,mn=8e3;async function fn(n){let e=re(n);const t=new AbortController,o=setTimeout(()=>t.abort(),mn);try{for(let r=0;r<=pn;r++){const i=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${g} (+link-title)`}});if(i.status>=300&&i.status<400&&i.headers.get("location")){if(e=re(new URL(i.headers.get("location"),e).href),i.body)try{await i.body.cancel()}catch{}continue}if(!i.ok){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}const s=i.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}return{title:wn(await gn(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function gn(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,he);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:i,value:s}=await e.read();if(i||(r+=s.byteLength,o+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(o)||r>=he))break}}finally{try{await e.cancel()}catch{}}return o}function yn(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 wn(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?yn(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function bn(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=t&&t.url;if(!o||typeof o!="string")return a(e,400,{error:"need url"});try{const r=await fn(o);return a(e,200,{title:r.title||null,url:r.url||o})}catch(r){const i=r?.name==="AbortError"?"timed out":String(r?.message||r);return a(e,400,{error:`couldn't fetch title: ${i}`})}}async function Sn(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const o=Y(t.session);if(!o)return a(e,404,{error:"no such session"});const r=o.pending.get(t.id);return r?(o.pending.delete(t.id),r.resolve(t.result),a(e,200,{ok:!0})):a(e,404,{error:"no such pending call"})}async function kn(n,e){let t;try{t=await f(n)}catch(c){return a(e,400,{error:"Bad JSON: "+c.message})}const o=C[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});const r=String(t.prompt||"").slice(0,6e3);if(!r)return a(e,400,{error:"Empty prompt"});const i=t.model||"",s=F(n,t.agent,{model:i});if(s.error)return a(e,403,{error:s.error});const u=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let c="";return typeof o.engine.complete=="function"?c=await o.engine.complete({prompt:r,system:u,model:i}):await o.engine.chat({messages:[{role:"user",content:r}],system:u,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),a(e,200,{text:(c||"").trim()})}catch(c){return a(e,502,{error:c?.message||String(c)})}}async function Tn(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=C[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof o.engine.listModels!="function")return a(e,200,{models:[]});try{const r=await o.engine.listModels(t.options||{});return a(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return a(e,502,{error:r?.message||String(r)})}}async function vn(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const o=String(t.command||"").trim();if(!o)return a(e,400,{error:"No command"});let r=null;try{r=lt(o)}catch{r=null}return a(e,200,{ok:!!r,via:r?r.kind:null})}const pe=fe(async(n,e)=>{if(Bt(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return a(e,400,{error:"bad request"})}const o=zt(n,t.pathname);if(o)return a(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return Xt(e);const r=t.searchParams.getAll("dir"),i=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return Yt(e,r,i);if(n.method==="GET"&&t.pathname==="/skills-quarantined")return Qt(e,r,i);if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),u=s.indexOf("/file/");return u===-1?Zt(e,decodeURIComponent(s),r,i):qt(e,decodeURIComponent(s.slice(0,u)),decodeURIComponent(s.slice(u+6)),r,i)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return rn(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return on(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return de(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return de(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 a(e,200,{version:g,agents:Object.fromEntries(it.map(u=>[u,s?ee(u)||null:!!ee(u)])),...s?{home:A.homedir(),path:process.env.PATH}:{}})}if(n.method==="POST"&&t.pathname==="/chat")return nn(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Lt(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return Dt(e);if(n.method==="POST"&&t.pathname==="/whoami")return jt(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return an(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return sn(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return cn(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return ln(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return ue(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 ue(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return X(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ce(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ce(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return dn(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Sn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local")return un(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return hn(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return bn(n,e);if(n.method==="POST"&&t.pathname==="/complete")return kn(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Tn(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return vn(n,e);if(n.method==="POST"&&t.pathname==="/update")return tn(e);a(e,404,{error:"Not found"})}catch(r){a(e,500,{error:r?.message||String(r)})}});function d(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Cn(n){let e="";const t=[];let o=!1,r=!1;const i=()=>{r&&!o&&!t.length&&process.exit(0)},s=async()=>{if(!o){for(o=!0;t.length;){const u=t.shift();let c;try{c=JSON.parse(u)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:u});if(c.id==null)continue;const h=(await l.text()).trim();h&&process.stdout.write(h+`
|
|
9
|
+
`)}async function G(n,e,t,o){try{const r=t(await f(n)),a=F(n,r.agent,r.options||{});if(a.error)throw new x(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new x(`Bad JSON: ${r.message}`):r)),null}}async function sn(n,e){const t=await G(n,e,Ot,b);if(!t)return;if(!t.stream)try{const r=await T(t,()=>{},e);return i(e,200,Tt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,b(r))}M(e);const o=bt(t.requestedModel,r=>P(e,r));try{await T(t,r=>o.delta(r),e),o.done()}catch(r){P(e,b(r))}P(e,"[DONE]"),e.end()}async function cn(n,e){const t=await G(n,e,Pt,b);if(!t)return;if(!t.stream)try{const r=await T(t,()=>{},e);return i(e,200,vt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,b(r))}M(e);const o=St(t.requestedModel,r=>P(e,r));try{await T(t,r=>o.delta(r),e),o.done()}catch(r){P(e,b(r))}P(e,"[DONE]"),e.end()}async function ln(n,e){const t=await G(n,e,At,b);if(!t)return;if(!t.stream)try{const r=await T(t,()=>{},e);return i(e,200,Ct(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,b(r))}M(e);const o=xt(t.requestedModel,r=>B(e,r.type,r));try{await T(t,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...b(r)};B(e,"error",a)}e.end()}async function dn(n,e){const t=await G(n,e,Et,j);if(!t)return;if(!t.stream)try{const r=await T(t,()=>{},e);return i(e,200,kt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,j(r))}M(e);const o=wt(t.requestedModel,(r,a)=>B(e,r,a));try{await T(t,r=>o.delta(r),e),o.done()}catch(r){B(e,"error",j(r))}e.end()}async function un(n,e){let t={};try{t=await f(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?mt(o,"stopped"):!1;return r&&d("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function ue(n,e,t){let o;try{o=await f(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=t?Y(t):Fe(),a=c=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:c})},s=(c,l)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:c,message:l}});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:y}});const u=Le();if(o.method==="tools/list"){const c=r?r.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...u,...c]})}if(o.method==="tools/call"){const c=await je(o.params?.name,o.params?.arguments||{});if(c)return a(c);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 Je(r,o.params?.name,o.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function hn(n,e){let t;try{t=await f(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 pt({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd},r);return r.id==null?(e.writeHead(202),e.end()):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 pn(n,e){let t;try{t=await f(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=ne(o)}catch(h){return i(e,400,{error:String(h?.message||h)})}const u={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[h,g]of Object.entries(r)){const m=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(m)||m.startsWith("x-"))&&(u[h]=String(g))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:u,body:JSON.stringify(a),redirect:"follow",signal:c.signal});try{h.url&&ne(h.url)}catch(m){return i(e,400,{error:String(m?.message||m)})}const g=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")||"",body:g})}catch(h){const g=h?.name==="AbortError"?"timed out":String(h?.message||h);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${g}`})}finally{clearTimeout(l)}}const he=256*1024,mn=5,fn=8e3;async function gn(n){let e=re(n);const t=new AbortController,o=setTimeout(()=>t.abort(),fn);try{for(let r=0;r<=mn;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/${y} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=re(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:bn(await yn(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function yn(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,he);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>=he))break}}finally{try{await e.cancel()}catch{}}return o}function wn(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 bn(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?wn(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Sn(n,e){let t;try{t=await f(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 gn(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 kn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=Y(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 Tn(n,e){let t;try{t=await f(n)}catch(c){return i(e,400,{error:"Bad JSON: "+c.message})}const o=C[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=F(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const u=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let c="";return typeof o.engine.complete=="function"?c=await o.engine.complete({prompt:r,system:u,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:u,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),i(e,200,{text:(c||"").trim()})}catch(c){return i(e,502,{error:c?.message||String(c)})}}async function vn(n,e){let t;try{t=await f(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=C[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 Cn(n,e){let t;try{t=await f(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=dt(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}const pe=fe(async(n,e)=>{if(Gt(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=Kt(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return Yt(e);const r=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return Qt(e,r,a);if(n.method==="GET"&&t.pathname==="/skills-quarantined")return Zt(e,r,a);if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),u=s.indexOf("/file/");return u===-1?qt(e,decodeURIComponent(s),r,a):en(e,decodeURIComponent(s.slice(0,u)),decodeURIComponent(s.slice(u+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return on(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return an(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return de(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return de(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:y,agents:Object.fromEntries(st.map(u=>[u,s?ee(u)||null:!!ee(u)])),...s?{home:A.homedir(),path:process.env.PATH}:{}})}if(n.method==="POST"&&t.pathname==="/chat")return rn(n,e);if(n.method==="POST"&&t.pathname==="/pair")return jt(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return Lt(e);if(n.method==="POST"&&t.pathname==="/whoami")return Wt(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return sn(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return cn(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return ln(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return dn(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return ue(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 ue(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return X(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ce(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ce(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return un(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return kn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local")return hn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return pn(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Sn(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Tn(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return vn(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Cn(n,e);if(n.method==="POST"&&t.pathname==="/update")return nn(e);i(e,404,{error:"Not found"})}catch(r){i(e,500,{error:r?.message||String(r)})}});function d(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function En(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 u=t.shift();let c;try{c=JSON.parse(u)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:u});if(c.id==null)continue;const h=(await l.text()).trim();h&&process.stdout.write(h+`
|
|
10
10
|
`)}catch(l){c.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:c.id,error:{code:-32e3,message:String(l?.message||l)}})+`
|
|
11
|
-
`)}}o=!1,
|
|
12
|
-
`))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&t.push(l)}s()}),process.stdin.on("end",()=>{r=!0,
|
|
11
|
+
`)}}o=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",u=>{e+=u;let c;for(;(c=e.indexOf(`
|
|
12
|
+
`))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&t.push(l)}s()}),process.stdin.on("end",()=>{r=!0,a()}),process.stdin.resume()}function On(){ct(),lt(),Dt(),pe.on("error",n=>{n&&n.code==="EADDRINUSE"&&(d("error",`Port ${v} is already in use — another app (or a second bridge) has it.`),d("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)),d("error",`bridge server error: ${n?.message||n}`),process.exit(1)});for(const n of["SIGINT","SIGTERM"])process.on(n,()=>{const e=ft("shutdown");e&&d("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const t=gt("shutdown");t&&d("info",`shutdown: closed ${t} warm agent process${t===1?"":"es"}`),setTimeout(()=>process.exit(0),e||t?300:0).unref?.(),!e&&!t&&process.exit(0)});pe.listen(v,k,async()=>{d("info",`listening on http://${k}:${v}`),W.has(k)||d("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:n,label:e,hidden:t}]of Object.entries(C)){if(t)continue;const o=await n.available().catch(()=>({ok:!1}));d("info",` ${o.ok?"✓":"✕"} ${e}${o.ok?"":" — "+(o.reason||"unavailable")}`)}d("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),se().then(n=>n.startIfConfigured()).then(n=>{n?.skipped||(n?.ok?d("info","channels: telegram connected — polling for messages"):d("error",`channels: telegram not started — ${n?.error||"unknown error"}`))}).catch(n=>d("error",`channels: ${n?.message||n}`))})}function Pn(){console.log(`ChatPanel Bridge v${y}
|
|
13
13
|
|
|
14
14
|
Usage:
|
|
15
15
|
chatpanel-bridge start the bridge (foreground) on ${k}:${v}
|
|
@@ -20,4 +20,4 @@ Usage:
|
|
|
20
20
|
chatpanel-bridge --version print the version
|
|
21
21
|
chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
|
|
22
22
|
|
|
23
|
-
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT`)}function
|
|
23
|
+
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT`)}function An(){const n=process.argv,e=(...t)=>t.some(o=>n.includes(o));if(e("--help","-h"))return Pn(),!0;if(e("--version","-v"))return console.log(y),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=K(N,"utf8").trim()}catch{}const o=`http://${k}:${v}`;try{if(!t)throw new Error(`no token at ${N} — 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: ${Ht(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(r){d("error",`could not get a pairing code from the bridge at ${o}: ${r?.message||r}`),process.exitCode=1}})(),!0;if(e("--install")){try{Re(),d("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(t){d("error","Install failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--uninstall")){try{_e(),d("info","Removed the login auto-start.")}catch(t){d("error","Uninstall failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--status")){let t=!1;try{t=He()}catch(o){d("error",String(o?.message||o))}return d("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const me=process.argv.indexOf("--mcp-stdio");if(me>=0){const n=process.argv[me+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),En(n)}else process.argv.includes("--update")?(async()=>{try{const n=await te(y);d("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),V()}catch(n){d("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():An()||On();
|