@chatpanel/bridge 0.14.0 → 0.19.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.14.0",
3
+ "version": "0.19.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": [
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
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.
2
+ import{readFileSync as r,writeFileSync as h,existsSync as i,mkdirSync as d}from"node:fs";import{fileURLToPath as f}from"node:url";import{dirname as m,join as n}from"node:path";const c=n(m(f(import.meta.url)),".."),v=["scopes.js","skill-manifest.js","skill-scan.js","ref.js","event.js","view.js","capability.js","reach.js","scm-connection.js","sandbox-policy.js","sandbox-grant.js","mcp-errors.js","mcp-signin.js","mcp-config-import.js","mcp-launcher.js"];function u(){return[n(c,"node_modules","@chatpanel","events"),n(c,"..","chatpanel-events")].find(e=>i(n(e,"skill-manifest.js")))}const s=process.argv.includes("--check"),a=u();if(!a){const e="chatpanel-events not found (check out ../chatpanel-events).";s&&(console.error(`sync-events --check: ${e}`),process.exit(1)),console.warn(`sync-events: ${e} Leaving src/events as-is.`),process.exit(0)}const l=n(c,"src","events");s||d(l,{recursive:!0});const j=e=>`// GENERATED — do not edit.
3
3
  // Source of truth: chatpanel-events/${e} (npm @chatpanel/events).
4
4
  // Edit there, then run: npm run sync:events
5
5
  //
@@ -7,4 +7,4 @@ import{readFileSync as r,writeFileSync as d,existsSync as i,mkdirSync as f}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}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 ✓"));
10
+ `;let p=0;for(const e of v){const o=j(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`),p+=1;continue}h(t,o),console.log(`sync-events: updated src/events/${e}`)}}s&&(p&&(console.error("Run `npm run sync:events` and commit the result."),process.exit(1)),console.log("sync-events --check: src/events matches chatpanel-events ✓"));
@@ -0,0 +1,2 @@
1
+ import{execFile as y}from"node:child_process";import{mkdir as h,readFile as C,stat as d,writeFile as E}from"node:fs/promises";import{existsSync as I}from"node:fs";import w from"node:os";import p from"node:path";import{promisify as T}from"node:util";const x=T(y),S=720*6e4,b=2e4,o="-----BEGIN CERTIFICATE-----",A=()=>process.env.CHATPANEL_CA_BUNDLE||p.join(w.homedir(),".cache","chatpanel","ca-bundle.pem");function R(e){try{const t=Buffer.from(String(e).replace(/\s+/g,""),"base64");return t.length>64&&t[0]===48&&(t[1]&128)!==0}catch{return!1}}function s(...e){const t=new Set,r=[];for(const i of e)for(const n of String(i||"").split(o).slice(1)){const u=n.indexOf("-----END CERTIFICATE-----");if(u<0)continue;const f=n.slice(0,u);if(!R(f))continue;const l=`${o}${f}-----END CERTIFICATE-----
2
+ `,m=l.replace(/\s+/g,"");t.has(m)||(t.add(m),r.push(l))}return r.join("")}function g(e){return String(e||"").split(o).length-1}async function a(e,t){try{const{stdout:r}=await x(e,t,{timeout:b,maxBuffer:33554432});return r||""}catch{return""}}async function N(e=process.platform){if(e==="darwin"){const[t,r]=await Promise.all([a("/usr/bin/security",["find-certificate","-a","-p","/System/Library/Keychains/SystemRootCertificates.keychain"]),a("/usr/bin/security",["find-certificate","-a","-p","/Library/Keychains/System.keychain"])]);return s(t,r)}if(e==="win32")return s(await a("powershell.exe",["-NoProfile","-NonInteractive","-Command","$ErrorActionPreference='SilentlyContinue';foreach ($s in @('Cert:\\LocalMachine\\Root','Cert:\\CurrentUser\\Root')) { foreach ($c in Get-ChildItem $s) { '-----BEGIN CERTIFICATE-----'; [Convert]::ToBase64String($c.RawData,'InsertLineBreaks'); '-----END CERTIFICATE-----' } }"]));for(const t of["/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/ssl/ca-bundle.pem","/etc/ssl/cert.pem"])if(I(t))return s(await C(t,"utf8").catch(()=>""));return""}let c=null;async function $({now:e=Date.now(),platform:t=process.platform,source:r=N}={}){const i=A();try{const n=await d(i);if(n.size>0&&e-n.mtimeMs<S)return i}catch{}return c||(c=(async()=>{try{const n=await r(t);return g(n)<10?"":(await h(p.dirname(i),{recursive:!0}),await E(i,n,{mode:420}),i)}catch{return""}finally{c=null}})(),c)}export{g as countPem,$ as ensureCaBundle,s as mergePem,N as systemCaPem};
@@ -1,6 +1,6 @@
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+=`
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{track as K,sandbox as W,noteSandbox as Y}from"../sandbox.js";import{pushExtraArgs as Z,FORBIDDEN as q}from"./args.js";import{resolveWorkdir as Q}from"../workdir.js";const P=Number(process.env.CHATPANEL_AGY_TIMEOUT_MS)||18e4;async function mt(){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 V(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 gt(){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 X(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 yt({messages:u,system:l,options:o,images:a},e,{signal:n}={}){const r=Q(o.workingDir),s=X(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=>"@"+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};
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"),Z(c,o.extraArgs,q.antigravity,e);const _=async t=>{const N=t?[...c,"--output-format","stream-json"]:c,y=await W().wrap("agy",N,{cwd:r,stdio:["ignore","pipe","pipe"],env:{...process.env,...o.runEnv||{}},...J},{engine:"antigravity",cwd:r});return Y(e,y.record),new Promise((k,b)=>{let f;try{f=K(F(y.bin,y.argv,y.opts),y,{kind:"agent"})}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=>{V(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{gt as available,yt as chat,V as forwardAgyLine,mt as listModels,L as newAgyState};
@@ -1,3 +1,3 @@
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};
1
+ import{unlink as F}from"node:fs/promises";import{spawnRpcChild as j}from"../rpc-child.js";import{spawn as G}from"node:child_process";import{track as J,sandbox as z}from"../sandbox.js";import{createWarmPool as K}from"../warm-pool.js";import{registerWarmPool as Q}from"../warm.js";import{createSession as R,deleteSession as L,rebindSession as V,releaseSession as X}from"../mcp-sessions.js";import{resolveClaude as Y,buildSpawnSpec as Z}from"../env.js";import{loginRequired as I,signInMessage as O}from"../sign-in.js";import{pushExtraArgs as P,FORBIDDEN as k}from"./args.js";import{buildClaudeLaunch as W,claudePrompt as ee,handleMessage as re,harnessChars as te,writeImages as se}from"./claude.js";const q=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,ae=5e3,c=Q("claude",K({log:n=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${n}`)}}));function ne(n={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||n.warm===!1)}async function U({spec:n,args:w,cwd:t,env:C,spawnImpl:h,log:S=()=>{}}){const x=[...w,"--input-format","stream-json"],[m,d,p]=Z(n,x,t,C),o=await z().wrap(m,d,p,{engine:"claude",cwd:t});o.record.layer==="none"&&S(`sandbox: claude session runs outside a sandbox — ${o.record.reason}`);const[E,l,f]=[o.bin,o.argv,o.opts];let e=null;const A=new Set;let g="",$=0,b=0;const s=j(E,l,{spawnOpts:f,spawnImpl:(r,a,i)=>J((h||G)(r,a,i),o,{kind:"warm"}),jsonrpc:!1,onStderr:r=>{g=(g+r).slice(-2e3),e&&e.touch()},onExit:r=>{if(S(`claude exited: ${r.signal||r.code}${g?` — ${g.trim().split(`
2
+ `).pop()}`:""}`),e){const a=e.apiError&&I(e.apiError)?O("Claude Code","claude"):e.apiError?`Claude Code reported an error: ${e.apiError}`:`Claude Code exited (${r.signal||r.code})${g?`: ${g.trim().split(`
3
+ `).pop().slice(0,200)}`:""}`;e.finish({status:"died",error:a})}for(const a of A)try{a(r)}catch{}},onMessage:r=>{if(!e||(e.touch(),r.type==="control_response"))return;const a=re(r,e.emit,e.streamedAny,t,e.flow);a.streamed&&(e.streamedAny=!0),a.result!=null&&(e.resultText=a.result),a.apiError&&(e.apiError=a.apiError),r.type==="result"&&(e.apiError&&I(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 s.pid},get alive(){return!s.exited},onExit(r){A.add(r)},close(){s.close()},async turn({prompt:r,emit:a,signal:i,harness:T=null}){if(s.exited)throw new Error("Claude Code process is gone");if(e)throw new Error("a turn is already running on this process");let y=null,_;const H=new Promise(v=>{_=v}),u={emit:a,flow:{sawText:!1,tail:"",boundary:!1,costUsdBefore:b,harnessChars:T},streamedAny:!1,resultText:"",apiError:null,touch(){clearTimeout(y),y=setTimeout(()=>u.finish({status:"timeout",error:`Claude Code timed out — no output for ${Math.round(q/1e3)}s.`}),q)},finish(v){e===u&&(clearTimeout(y),e=null,_(v))}};e=u,u.touch();const N=()=>{if(e===u){u.interrupted=!0;try{s.send({type:"control_request",request_id:`stop_${++$}`,request:{subtype:"interrupt"}})}catch{}setTimeout(()=>{e===u&&(u.finish({status:"killed",error:null}),s.kill())},ae).unref?.()}};if(i?.aborted)return u.finish({status:"killed",error:null}),{streamedAny:!1,resultText:"",status:"killed"};i?.addEventListener("abort",N,{once:!0});try{s.send({type:"user",message:{role:"user",content:r}})}catch(v){u.finish({status:"failed",error:v.message})}const M=await H;u.flow.costUsdTotal!=null&&(b=u.flow.costUsdTotal),i?.removeEventListener("abort",N),M.status==="timeout"&&s.kill();const B=M.status==="killed"?"killed":u.interrupted?"interrupted":M.status;return{streamedAny:u.streamedAny,resultText:u.resultText,status:B,error:M.error}}}}const D=new Set;async function oe({key:n,spec:w,options:t,label:C,launch:h=U,log:S=()=>{},force:x=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!x||!n||!w||D.has(n)||c.peek({key:n,messages:[{role:"user",content:""}]}))return!1;D.add(n);const m=c.reserve({key:n,label:`${C} (spare)`,evict:!1});if(!m)return D.delete(n),!1;let d=null,p=null;try{let o=t.mcp;const E=t.mcp?.specs||[];o?.url&&E.length&&(d=R(()=>{},E),o={...o,url:`${o.url.replace(/\/[^/]*$/,"")}/${d.id}`}),p=await W({system:"",options:{...t,mcp:o},tag:`spare-${Date.now()}-${Math.random().toString(36).slice(2)}`});const l=[...p.args];P(l,t.extraArgs,k.claude,()=>{});const f=await h({spec:w,args:l,cwd:p.cwd,env:p.runEnv});f.mcpSession=d,f.systemSent="",c.attach(m,f);const e=p.cleanup;return f.onExit(()=>{d&&L(d.id),e()}),c.release(m,{user:null,answered:!1}),S(`warm ${C}: spare ready`),!0}catch(o){return d&&L(d.id),p?.cleanup?.(),c.drop(m,`spare launch failed: ${o.message}`),!1}finally{D.delete(n)}}async function Ee({messages:n,system:w,options:t,images:C},h,{signal:S,launch:x=U}={}){if(!ne(t))return{handled:!1,reason:"not eligible"};const m=Y();if(!m)return{handled:!1,reason:"claude not resolvable"};const d=`${Date.now()}-${Math.random().toString(36).slice(2)}`,p=(t.mcp?.specs||[]).map(r=>r?.name).filter(Boolean),o=[];P(o,t.extraArgs,k.claude,()=>{});const E=JSON.stringify({agent:"claude",cwd:t.workingDir||"",mode:t.permissionMode||"default",model:t.model||"",local:t.useLocalConfig!==!1,reach:t.reach||"",tools:[...p].sort(),extra:o,env:t.runEnv?Object.keys(t.runEnv).sort().map(r=>`${r}=${t.runEnv[r]}`):[],hosts:t.sandbox?.hosts?(Array.isArray(t.sandbox.hosts)?t.sandbox.hosts:String(t.sandbox.hosts).split(/[\s,;]+/)).map(r=>String(r).trim().toLowerCase()).filter(Boolean).sort():[]});let l=c.acquire({key:E,messages:n}),f=!1;if(!l){if(l=c.reserve({key:E,label:`claude ${t.workingDir||"home"}`}),!l)return{handled:!1,reason:"all warm slots busy"};f=!0;let r=null,a=null;try{let i=t.mcp;i?.url&&p.length&&(r=R(h,i.specs),i={...i,url:`${i.url.replace(/\/[^/]*$/,"")}/${r.id}`}),a=await W({system:w,options:{...t,mcp:i},tag:d});const T=[...a.args];P(T,t.extraArgs,k.claude,h);const y=await x({spec:m,args:T,cwd:a.cwd,env:a.runEnv});y.mcpSession=r,y.systemSent=String(w||""),c.attach(l,y);const _=a.cleanup;y.onExit(()=>{r&&L(r.id),_()})}catch(i){return r&&L(r.id),a?.cleanup(),c.drop(l,`launch failed: ${i.message}`),{handled:!1,reason:i.message}}}const e=l.session;e.mcpSession&&V(e.mcpSession,h,t.mcp?.specs);const A=n[n.length-1],g=await se(C,d),$=String(w||""),b=ee(f?n:[A],g,!f&&$!==e.systemSent?$:"");e.systemSent=$;let s;try{s=await e.turn({prompt:b,emit:h,signal:S,harness:te({prompt:b,system:f?$:"",specs:f?t.mcp?.specs:null})})}finally{g.forEach(r=>F(r).catch(()=>{})),e.mcpSession&&X(e.mcpSession)}if(S?.aborted||s.status==="interrupted")return s.status==="interrupted"&&e.alive?c.release(l,{user:String(A?.content||""),answered:s.streamedAny}):c.drop(l,"stopped"),{handled:!0};if(s.status!=="completed"){if(c.drop(l,s.error||s.status),!s.streamedAny)return{handled:!1,reason:s.error||s.status};throw new Error(s.error||`Claude Code ${s.status}`)}return h({type:"done",text:s.streamedAny?"":s.resultText}),c.release(l,{user:String(A?.content||""),answered:!0}),setTimeout(()=>{oe({key:E,spec:m,options:t,label:`claude ${t.workingDir||"home"}`,launch:x}).catch(()=>{})},250).unref?.(),{handled:!0}}export{Ee as chatWarm,U as launchClaudeSession,c as pool,oe as prewarmClaude,ne as warmEligible};
@@ -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 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
- `)),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:`
1
+ import{spawn as R}from"node:child_process";import{writeFile as O,unlink as F}from"node:fs/promises";import S from"node:os";import P from"node:path";import{resolveClaude as x,buildSpawnSpec as j,isCompiledBinary as re,selfMcpStdio as oe}from"../env.js";import{signInStatus as ne,signInMessage as D,loginRequired as se}from"../sign-in.js";import{buildCliPrompt as H}from"./prompt.js";import{summarizeCliError as ae}from"../cli-errors.js";import{killOnAbort as ie}from"../proc.js";import{sandbox as le,noteSandbox as ce,track as ue}from"../sandbox.js";import{pushExtraArgs as de,FORBIDDEN as pe}from"./args.js";import{relayTimeoutMax as fe}from"../relay-timeout.js";import{displayPath as he,resolveWorkdir as U}from"../workdir.js";import{connectorsFor as me}from"../connectors.js";import{chatWarm as ye}from"./claude-warm.js";async function be(e,t){const o=[];for(let i=0;i<(e?.length||0);i++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[i]?.dataUrl||"");if(!s)continue;const n=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",r=P.join(S.tmpdir(),`chatpanel-claude-img-${t}-${i}.${n}`);await O(r,Buffer.from(s[2],"base64")),o.push(r)}return o}const z=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,B=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task"],G=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),_e=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"])}),ge=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),we=Object.freeze(["remember","forget"]),q=Object.freeze({device:Object.freeze([]),trusted:ge});function Te(e,t=[]){const o=q[e]||q.device,i=(t||[]).filter(r=>typeof r=="string"&&/^chatpanel/i.test(r)),s=[],n=[];for(const r of i){for(const a of o)s.push(`mcp__${r}__${a}`);for(const a of we)n.push(`mcp__${r}__${a}`)}return{allow:s,deny:n}}function xe(e){if(!e||e==="any")return null;const t=G[e]?e:"device";return{allow:[...G[t]],deny:[..._e[t]]}}let A="Claude Code not found.",J=0,w=!1;async function Ye(){if(Date.now()-J>(w?3e4:4e3)){J=Date.now();try{x()||!re()&&await $()?w=!0:(w=!1,A=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{w=!1}}return w?await ne("claude",x()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:D("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:A}}async function Xe(){return["opus","sonnet","haiku"]}function Ee(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:o,args:i}=oe(e.url),s=[...new Set(e.specs.map(n=>n?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:o,args:i}}},allowedTools:s.map(n=>`mcp__${t}__${n}`)}}function Y({prompt:e,args:t,cwd:o,env:i=null,emit:s,signal:n,harness:r=null}){const a=x();if(!a)return null;const[c,h,_]=j(a,t,o,i);return new Promise((b,d)=>{le().wrap(c,h,_,{engine:"claude",cwd:o}).then(l=>{ce(s,l.record);let u;try{u=ue(R(l.bin,l.argv,l.opts),l,{kind:"agent"})}catch(f){return d(new Error(`Failed to start claude: ${f.message}`))}const g=ie(u,n);let m="",C="",p=!1,y=null;const te={sawText:!1,tail:"",boundary:!1,harnessChars:r};let v="",k;const N=()=>{clearTimeout(k),k=setTimeout(()=>{u.kill("SIGKILL"),d(new Error(`Claude Code timed out — no output for ${Math.round(z/1e3)}s.`))},z)};N(),u.stdout.on("data",f=>{N(),m+=f.toString();let M;for(;(M=m.indexOf(`
2
+ `))>=0;){const W=m.slice(0,M).trim();if(m=m.slice(M+1),!W.startsWith("{"))continue;let I;try{I=JSON.parse(W)}catch{continue}const T=Q(I,s,p,o,te);T.streamed&&(p=!0),T.result!=null&&(v=T.result),T.apiError&&(y=T.apiError)}}),u.stderr.on("data",f=>{N(),C+=f.toString()}),u.on("error",f=>{clearTimeout(k),g(),d(new Error(`Failed to start claude (${c}): ${f.message}`))}),u.on("close",f=>{if(clearTimeout(k),g(),n?.aborted){b({streamedAny:p,resultText:v});return}if(y&&se(y))return d(new Error(D("Claude Code","claude")));if(f===0&&y)return d(new Error(`Claude Code reported an error: ${y}`));f===0?b({streamedAny:p,resultText:v}):d(new Error(ae("Claude Code",f,C,y||"",{agentId:"claude"})))}),u.stdin.write(e),u.stdin.end()}).catch(d)})}function Ce(e){let t="";return typeof e=="string"?t=e:Array.isArray(e)&&(t=e.map(o=>typeof o=="string"?o:o?.text||"").filter(Boolean).join(`
3
+ `)),t.length>4e3?`${t.slice(0,4e3)}…`:t}function X(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
4
4
 
5
- `}),e.boundary=!1)}function X(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function K(e,t,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: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+=`
5
+ `}),e.boundary=!1)}function K(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function Q(e,t,o,i="",s=null){const n={streamed:!1,result:null};if(e.type==="stream_event"){const r=e.event;r?.type==="content_block_delta"&&(r.delta?.type==="text_delta"?(n.streamed=!0,X(s,t),t({type:"delta",text:r.delta.text}),K(s,r.delta.text)):r.delta?.type==="thinking_delta"&&t({type:"reasoning",text:r.delta.thinking||""}))}else if(e.type==="assistant"){if(e.is_api_error_message||e.error)return n.apiError=(e.message?.content||[]).filter(r=>r.type==="text").map(r=>r.text).join(`
6
+ `)||String(e.error||"api error"),n;for(const r of e.message?.content||[])r.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:r.name,phase:"start",callId:r.id,input:r.input,summary:Me(r,i)})):r.type==="text"&&!o&&(n.streamed=!0,X(s,t),t({type:"delta",text:r.text}),K(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:Ce(r.content)});else if(e.type==="result"){e.is_error?n.apiError=n.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?n.result=e.result||"":t({type:"status",text:`(${e.subtype})`});const r=e.usage||e.message?.usage;if(r){const a=Number.isFinite(Number(e.total_cost_usd))?Number(e.total_cost_usd):null,c=Number(s?.costUsdBefore)||0;s&&a!=null&&(s.costUsdTotal=a),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:a!=null?Math.max(0,a-c):null,costBasis:"list",...s?.harnessChars!=null?{harnessChars:s.harnessChars}:{}})}}return n}const V=process.env.CHATPANEL_CLAUDE_EFFORT??"low";let E=null;function Z({probe:e=null}={}){return E||(E=(async()=>{try{return String(await(e?e():new Promise(t=>{const[o,i,s]=j(x(),["--help"],null),n=R(o,i,{...s,stdio:["ignore","pipe","pipe"]});let r="";n.stdout.on("data",a=>{r+=a}),n.on("error",()=>t("")),n.on("close",()=>t(r)),setTimeout(()=>{try{n.kill()}catch{}t(r)},8e3).unref?.()}))||"")}catch{return""}})(),E)}async function ke(e={}){return/--effort\b/.test(await Z(e))}async function Se(e={}){return/--append-system-prompt(?:-file\b|\[-file\])/.test(await Z(e))}function Ke(){E=null}async function Ae({system:e,options:t,tag:o}){const i=t.permissionMode||"default",s=U(t.workingDir),n=["--print","--output-format","stream-json","--include-partial-messages","--verbose"];V&&await ke()&&n.push("--effort",V);const r=[],a=[],c=Ee(t.mcp);if(c){const l=P.join(S.tmpdir(),`chatpanel-mcp-${o}.json`);await O(l,JSON.stringify(c.config)),r.push(l),n.push("--mcp-config",l),a.push(...c.allowedTools)}const h=xe(t.reach);if(h){const l=Te(t.reach,await me("claude").catch(()=>[]));n.push("--allowedTools",...h.allow,...a,...l.allow),n.push("--disallowedTools",...h.deny,...l.deny)}else i==="bypassPermissions"?n.push("--permission-mode","bypassPermissions"):i==="acceptEdits"?(n.push("--permission-mode","acceptEdits"),a.length&&n.push("--allowedTools",...a)):n.push("--allowedTools",...B,...a);if(e)if(x()?.kind!=="wsl"&&await Se()){const u=P.join(S.tmpdir(),`chatpanel-system-${o}.md`);await O(u,e,{mode:384}),r.push(u),n.push("--append-system-prompt-file",u)}else n.push("--append-system-prompt",e);t.model&&n.push("--model",t.model),t.useLocalConfig===!1&&n.push("--setting-sources","");const _=c&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(fe(t.mcp?.specs))}:null,b=_||t.runEnv?{...t.runEnv||{},..._||{}}:null;return{args:n,cwd:s,runEnv:b,cleanup:()=>r.forEach(l=>F(l).catch(()=>{})),hasMcp:!!c}}function ee({prompt:e="",system:t="",specs:o=null}={}){const i=Array.isArray(o)&&o.length?JSON.stringify(o).length:0;return String(e).length+String(t).length+i}function ve(e,t=[],o=""){let i=H(e,o);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 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};
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 Qe({messages:e,system:t,options:o,images:i},s,{signal:n}={}){const r=await ye({messages:e,system:t,options:o,images:i},s,{signal:n}).catch(a=>({handled:!1,reason:a?.message||String(a),thrown:!0}));if(!r.handled&&!n?.aborted){if(r.thrown)throw new Error(r.reason);return Ne({messages:e,system:t,options:o,images:i},s,{signal:n})}}async function Ne({messages:e,system:t,options:o,images:i},s,{signal:n}={}){const r=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=await Ae({system:t,options:o,tag:r}),{args:c,cwd:h,runEnv:_}=a,b=await be(i,r),d=()=>{b.forEach(g=>F(g).catch(()=>{})),a.cleanup()},l=ve(e,b);de(c,o.extraArgs,pe.claude,s);const u=Y({prompt:l,args:c,cwd:h,env:_,emit:s,signal:n,harness:ee({prompt:l,system:t,specs:o.mcp?.specs})});if(u===null)return d(),Oe({messages:e,system:t,options:o},s,{signal:n});try{const{streamedAny:g,resultText:m}=await u;s({type:"done",text:g?"":m})}finally{d()}}async function Ve({prompt:e,system:t,model:o}){const i=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",o||"haiku","--system-prompt",t||"Continue the user's text briefly. Reply with only the continuation."];let s="";const n=Y({prompt:e,args:i,cwd:null,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(n===null)return Pe({prompt:e,system:t,model:o});const{resultText:r}=await n;return(s||r||"").trim()}function Me(e,t=""){const o=e.input||{};return o.command?String(o.command).slice(0,60):o.file_path?he(o.file_path,t):o.pattern?o.pattern:o.url?o.url:o.description?String(o.description).slice(0,80):o.query?String(o.query).slice(0,80):o.prompt?String(o.prompt).slice(0,80):""}let L=null;function $(){return L||(L=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),L}async function Oe({messages:e,system:t,options:o},i,{signal:s}={}){const n=await $();if(!n)throw new Error(A);const{query:r}=n,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const c=o.permissionMode||"default",h=U(o.workingDir),_=c==="acceptEdits"||c==="bypassPermissions",b=new Set(B),d=async p=>b.has(p)||_?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${p} blocked — set this agent's permission mode in ChatPanel to enable it.`};let l=!1;const u=H(e),g={sawText:!1,tail:"",boundary:!1,harnessChars:ee({prompt:u,system:t})};let m="";const C=r({prompt:u,options:{cwd:h,permissionMode:c,includePartialMessages:!0,canUseTool:d,abortController:a,settingSources:o.useLocalConfig===!1?[]:["user","project"],systemPrompt:t?{type:"preset",preset:"claude_code",append:t}:{type:"preset",preset:"claude_code"},...o.model?{model:o.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const p of C){const y=Q(p,i,l,h,g);y.streamed&&(l=!0),y.result!=null&&(m=y.result)}}catch(p){if(s?.aborted||a.signal.aborted)return;throw p}i({type:"done",text:l?"":m})}async function Pe({prompt:e,system:t,model:o}){const i=await $();if(!i)throw new Error(A);const{query:s}=i;let n="";const r=s({prompt:e,options:{cwd:S.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:t||"Continue the user's text briefly. Reply with only the continuation.",model:o||"haiku"}});for await(const a of r)if(a.type==="assistant")for(const c of a.message.content)c.type==="text"&&(n+=c.text);else a.type==="result"&&a.subtype==="success"&&!n&&(n=a.result||"");return n.trim()}export{Ke as _resetEffortProbe,Ye as available,Ae as buildClaudeLaunch,Te as channelMcpTools,xe as channelToolPolicy,Qe as chat,Ne as chatCold,Ee as claudeMcpConfig,ve as claudePrompt,ke as claudeSupportsEffort,Se as claudeSupportsSystemPromptFile,Ve as complete,Q as handleMessage,ee as harnessChars,Xe as listModels,be as writeImages};
@@ -1,12 +1,12 @@
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?`
1
+ import z from"node:os";import M from"node:path";import{unlink as B}from"node:fs/promises";import{spawnRpcChild as U}from"../rpc-child.js";import{spawnGroupOpts as F}from"../proc.js";import{spawn as X}from"node:child_process";import{track as G,sandbox as J}from"../sandbox.js";import{createWarmPool as V}from"../warm-pool.js";import{createSession as N,deleteSession as T,rebindSession as K,releaseSession as Q}from"../mcp-sessions.js";import{buildCliPrompt as D}from"./prompt.js";import{codexMcpConfigArgs as R,codexDisableArgs as L,configuredMcpServers as Y,redundantChatpanelServers as Z,ensureIsolatedHome as ee,writeImages as te}from"./codex.js";import{disabledMcpServers as re}from"../mcp-quarantine.js";import{resolveWorkdir as se}from"../workdir.js";import{registerWarmPool as ae}from"../warm.js";const q=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,H=process.env.CHATPANEL_CODEX_EFFORT??"low",ne=9e4,W=5e3,w=ae("codex",V({log:e=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[codex] ${e}`)}}));let O=0;function Te(){O=0}const oe=e=>e&&typeof e=="object"?(Array.isArray(e.hosts)?e.hosts:String(e.hosts||"").split(/[\s,;]+/)).map(d=>String(d).trim().toLowerCase()).filter(Boolean).sort():[];function ie({agent:e="codex",cwd:d,options:s={},mcpNames:f=[],runEnv:o=null,disabled:u=[]}){return JSON.stringify({agent:e,cwd:d,mode:s.permissionMode||"default",model:s.model||"",local:s.useLocalConfig!==!1,tools:[...f].sort(),env:o?Object.keys(o).sort().map(x=>`${x}=${o[x]}`):[],disabled:[...u].sort(),hosts:oe(s.sandbox)})}function le(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 de(e){return e==="bypassPermissions"?"danger-full-access":e==="acceptEdits"?"workspace-write":"read-only"}function ce(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 ue(e,d,s,f){const o=e?.type||"",u=e?.id||`i_${f.n++}`,x=(l,a)=>{f.started.has(u)||(f.started.add(u),s({type:"tool",name:l,phase:"start",callId:u,input:a}))};if(o==="agentMessage"){d&&e.text&&!f.deltaItems.has(u)&&!f.said.has(u)&&(f.said.add(u),s({type:"delta",text:`${f.saidAny?`
3
3
 
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
- `);l&&!u.reasoned.has(c)&&(u.reasoned.add(c),s({type:"reasoning",text:`${l}
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:`
4
+ `:""}${e.text}`}),f.saidAny=!0);return}if(o==="commandExecution"){if(x("shell",{command:e.command||""}),d){const l=e.exitCode===0||e.exitCode==null;s({type:"tool",name:"shell",phase:"done",callId:u,status:l?"ok":`exit ${e.exitCode}`,result:String(e.aggregatedOutput||"").slice(0,4e3)})}return}if(o==="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:u,status:e.status==="failed"?"error":"ok"});return}if(o==="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:u,status:"ok",result:t?`Opened ${t}`:a?`Searched the web for ${a}`:"Searched the web"});return}if(o==="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:u,status:a?`error: ${String(t||"failed").slice(0,80)}`:"ok",result:String(a?t||"":ce(e.result)).slice(0,4e3)})}return}if(o==="plan"&&d&&e.text&&f.lastPlan!==e.text){f.lastPlan=e.text,s({type:"status",text:`Plan:
5
+ ${e.text}`});return}if(o==="reasoning"&&d){if(f.deltaItems.has(u))return;const l=(Array.isArray(e.summary)?e.summary:[]).map(a=>typeof a=="string"?a:a?.text||"").filter(Boolean).join(`
6
+ `);l&&!f.reasoned.has(u)&&(f.reasoned.add(u),s({type:"reasoning",text:`${l}
7
+ `}))}}function fe(){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:f=[],options:o={},spawnImpl:u,log:x=()=>{}}){const l=o.permissionMode||"default",a=l==="bypassPermissions";let t=null;const A=new Set;let S="";const y=await J().wrap(e,["app-server",...f],{cwd:d||void 0,env:s,...F},{engine:"codex",cwd:d});y.record.layer==="none"&&x(`sandbox: codex app-server runs outside a sandbox — ${y.record.reason}`);const m=U(y.bin,y.argv,{cwd:d,env:s,spawnImpl:(r,n,c)=>G((u||X)(r,n,c),y,{kind:"warm"}),spawnOpts:y.opts,onStderr:r=>{S=(S+r).slice(-2e3)},onExit:r=>{x(`app-server exited: ${r.signal||r.code}${S?` — ${S.trim().split(`
8
+ `).pop()}`:""}`),t&&t.finish({status:"died",error:r.error?.message||`Codex exited (${r.signal||r.code})`});for(const n of A)try{n(r)}catch{}},onRequest:async(r,n)=>{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 n=r.params||{};if(n.threadId&&n.threadId!==t.threadId)return;t.touch();const c=r.method;if(c==="item/agentMessage/delta"){if(!n.delta)return;t.state.deltaItems.add(n.itemId),t.state.said.has(n.itemId)||(t.state.said.add(n.itemId),t.state.saidAny&&t.emit({type:"delta",text:`
9
9
 
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};
10
+ `})),t.state.saidAny=!0,t.streamed=!0,t.emit({type:"delta",text:n.delta})}else if(c==="item/reasoning/summaryTextDelta"||c==="item/reasoning/textDelta"){if(!n.delta)return;t.state.deltaItems.add(n.itemId),t.streamed=!0,t.emit({type:"reasoning",text:n.delta})}else if(c==="item/reasoning/summaryPartAdded")t.state.deltaItems.has(n.itemId)&&t.emit({type:"reasoning",text:`
11
+ `});else if(c==="item/started"||c==="item/completed"){const i=t.state.started.size+t.state.said.size;ue(n.item,c==="item/completed",t.emit,t.state),t.state.started.size+t.state.said.size>i&&(t.streamed=!0)}else if(c==="thread/tokenUsage/updated"){const i=n.tokenUsage?.last||n.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(c==="error"){const i=n.error?.message||"error";n.willRetry?t.emit({type:"status",text:`Codex: ${i.slice(0,200)} — retrying`}):t.lastError=i}else if(c==="turn/completed"){const i=n.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 v;try{if(await m.request("initialize",{clientInfo:{name:"chatpanel-bridge",version:"1"},capabilities:{experimentalApi:!0}},{timeoutMs:2e4}),m.notify("initialized"),v=(await m.request("thread/start",{cwd:d||void 0,sandbox:de(l),approvalPolicy:"never",...o.model?{model:o.model}:{}},{timeoutMs:ne}))?.thread?.id,!v)throw new Error("Codex app-server started no thread")}catch(r){m.kill();const n=S.trim().split(`
12
+ `).filter(Boolean).pop()||"";throw new Error(n?`${r.message}: ${n.slice(-300)}`:r.message)}return{threadId:v,get pid(){return m.pid},get alive(){return!m.exited},onExit(r){A.add(r)},close(){m.close()},async turn({prompt:r,imageFiles:n=[],emit:c,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=fe();let E=null,I;const _=new Promise(b=>{I=b}),h={threadId:v,turnId:null,emit:c,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:v,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}),c({type:"status",text:"Codex working"});try{const b=[{type:"text",text:r},...n.map(P=>({type:"localImage",path:P}))],$=await m.request("turn/start",{threadId:v,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 _;return i?.removeEventListener("abort",g),p.status==="timeout"&&m.kill(),h.usage&&c(h.usage),{streamed:h.streamed,said:C.saidAny,status:p.status,error:p.error,usage:h.usage}}}}const k=new Set;async function pe({key:e,cwd:d,env:s,configArgs:f,options:o,label:u,launch:x=j,force:l=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!l||!e||k.has(e)||w.peek({key:e,messages:[{role:"user",content:""}]}))return!1;k.add(e);const a=w.reserve({key:e,label:`${u} (spare)`,evict:!1});if(!a)return k.delete(e),!1;let t=null;try{const A=[...f];if(o.mcp?.url&&(o.mcp?.specs||[]).length){t=N(()=>{},o.mcp.specs);const m=o.mcp.url.replace(/\/[^/]*$/,"");A.unshift(...R({url:`${m}/${t.id}`,serverName:o.mcp?.serverName||"chatpanel_browser",specs:o.mcp.specs}))}const S=await x({cwd:d,env:s,configArgs:A,options:o});S.mcpSession=t,S.systemSent="",w.attach(a,S);const y=t;return S.onExit(()=>{y&&T(y.id)}),w.release(a,{user:null,answered:!1}),!0}catch(A){return t&&T(t.id),w.drop(a,`spare launch failed: ${A.message}`),!1}finally{k.delete(e)}}async function ke({messages:e,system:d,options:s,images:f},o,{signal:u,launch:x=j}={}){if(!le(s))return{handled:!1,reason:"not eligible"};const l=se(s.workingDir),a={...process.env,...s.runEnv||{}};if(s.useLocalConfig===!1){const p=ee();p&&(a.CODEX_HOME=p)}const t=s.mcp?.serverName||"chatpanel_browser",A=a.CODEX_HOME||M.join(z.homedir(),".codex"),S=Y(A),y=(s.mcp?.specs||[]).map(p=>p?.name).filter(Boolean),m=[...new Set([...re("codex",s,[t]),...y.length?Z(A):[]])].filter(p=>S.has(p)),v=ie({cwd:l,options:s,mcpNames:y,runEnv:s.runEnv||null,disabled:m});let r=w.acquire({key:v,messages:e}),n=!1,c=null;if(!r){if(r=w.reserve({key:v,label:`codex ${M.basename(l||"")}`}),!r)return{handled:!1,reason:"all warm slots busy"};n=!0;try{const p=[];if(s.mcp?.url&&y.length){c=N(o,s.mcp.specs);const P=s.mcp.url.replace(/\/[^/]*$/,"");p.push(...R({url:`${P}/${c.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=c,b.systemSent="",w.attach(r,b);const $=c;b.onExit(()=>{$&&T($.id)})}catch(p){return c&&T(c.id),w.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&&K(i.mcpSession,o,s.mcp?.specs);const C=e[e.length-1],E=String(d||""),I=n?D(e,E):D([C],E&&E!==i.systemSent?E:""),_=`${Date.now()}-${Math.random().toString(36).slice(2)}`,h=await te(f,_);let g;try{g=await i.turn({prompt:I,imageFiles:h,emit:o,signal:u})}finally{h.forEach(p=>B(p).catch(()=>{})),i.mcpSession&&Q(i.mcpSession)}if(i.systemSent=E,u?.aborted||g.status==="interrupted")return g.status==="interrupted"&&i.alive?w.release(r,{user:String(C?.content||""),answered:g.streamed}):w.drop(r,"stopped"),{handled:!0};if(g.status!=="completed"){if(w.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||o({type:"delta",text:"(no output)"}),o({type:"done",text:""}),w.release(r,{user:String(C?.content||""),answered:!0}),setTimeout(()=>{pe({key:v,cwd:l,env:a,configArgs:L(m),options:s,label:`codex ${M.basename(l||"")}`,launch:x}).catch(()=>{})},250).unref?.(),{handled:!0}}export{ke as chatWarm,ue as forwardV2Item,j as launchCodexSession,fe as newTurnState,w as pool,pe as prewarmCodex,Te as resetSupport,le as warmEligible,ie as warmKey};
@@ -1,7 +1,7 @@
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?`
1
+ import{spawn as B}from"node:child_process";import{killOnAbort as H,spawnGroupOpts as F}from"../proc.js";import{track as L,sandbox as X,noteSandbox as J}from"../sandbox.js";import{readFile as R,unlink as M,writeFile as q}from"node:fs/promises";import{existsSync as N,mkdirSync as z,symlinkSync as W,readFileSync as O}from"node:fs";import S from"node:os";import m from"node:path";import{findAgentBin as G,selfMcpStdio as K,resolveCommand as U}from"../env.js";import{relayTimeoutMax as Z}from"../relay-timeout.js";import{buildCliPrompt as Q}from"./prompt.js";import{pushExtraArgs as V,FORBIDDEN as Y}from"./args.js";import{resolveWorkdir as ee}from"../workdir.js";import{summarizeCliError as te}from"../cli-errors.js";import{signInStatus as oe,signInMessage as re}from"../sign-in.js";import{disabledMcpServers as ne,planMcpRetry as se,quarantine as ae}from"../mcp-quarantine.js";import{chatWarm as ce}from"./codex-appserver.js";const j=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,D=process.env.CHATPANEL_CODEX_EFFORT??"low",ie=["gpt-5-codex","gpt-5","o3","o4-mini"];let C=!1;function Te(){C=!1}async function Pe(){const n=new Set;try{const r=process.env.CODEX_HOME||m.join(S.homedir(),".codex"),t=O(m.join(r,"config.toml"),"utf8");for(const a of t.matchAll(/(?:^|\n)\s*model\s*=\s*["']([^"'\n]+)["']/g))n.add(a[1].trim())}catch{}for(const r of ie)n.add(r);return[...n]}const I=m.join(S.homedir(),".chatpanel","codex-home");let T=!1;function le(){if(!T)try{z(I,{recursive:!0});const n=m.join(S.homedir(),".codex","auth.json"),r=m.join(I,"auth.json");if(N(n)&&!N(r))try{W(n,r)}catch{}T=!0}catch{return null}return I}let A=!1,P=0;async function Be(){if(Date.now()-P>(A?3e4:4e3)){P=Date.now();try{A=!!G("codex")}catch{A=!1}}return A?await oe("codex",U("codex")).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:re("Codex","codex")}:{ok:!0}:{ok:!1,reason:"codex not found on PATH. Install it and run `codex login`."}}function de(n){if(!n?.url)return[];const r=n.serverName||"chatpanel_browser",{command:t,args:a}=K(n.url),e=["-c",`mcp_servers.${r}.command=${JSON.stringify(t)}`,"-c",`mcp_servers.${r}.args=${JSON.stringify(a)}`,"-c",`mcp_servers.${r}.default_tools_approval_mode="approve"`,"-c",`mcp_servers.${r}.startup_timeout_sec=30`,"-c",`mcp_servers.${r}.tool_timeout_sec=${Math.ceil(Z(n.specs)/1e3)}`],s=[...new Set((n.specs||[]).map(i=>i?.name).filter(Boolean))];return s.length&&e.push("-c",`mcp_servers.${r}.enabled_tools=${JSON.stringify(s)}`),e}function pe(n){try{const r=O(m.join(n,"config.toml"),"utf8"),t=new Set;for(const a of r.matchAll(/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*[.\]]/gm))t.add(a[1]);return t}catch{return new Set}}function ue(n){const r=new Set;try{const t=O(m.join(n,"config.toml"),"utf8"),a=/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*\]\s*$([\s\S]*?)(?=^\s*\[|$(?![\r\n]))/gm;for(const e of t.matchAll(a)){const s=e[2]||"",i=/^\s*command\s*=\s*"([^"]*)"/m.exec(s)?.[1]||"",o=/^\s*url\s*=\s*"([^"]*)"/m.exec(s)?.[1]||"";(/chatpanel-(gateway|bridge)(\.js|\.cmd|\.exe)?$/.test(i)||/^https?:\/\/(127\.0\.0\.1|localhost):43(19|20)\//.test(o))&&r.add(e[1])}}catch{}return r}function fe(n=[]){return n.flatMap(r=>["-c",`mcp_servers.${r}.enabled=false`])}async function me(n,r){const t=[];for(let a=0;a<(n?.length||0);a++){const e=/^data:([^;]+);base64,(.+)$/s.exec(n[a]?.dataUrl||"");if(!e)continue;const s=(e[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",i=m.join(S.tmpdir(),`chatpanel-codex-img-${r}-${a}.${s}`);await q(i,Buffer.from(e[2],"base64")),t.push(i)}return t}async function he({args:n,cwd:r,env:t,prompt:a,outFile:e,emit:s,signal:i}){const o=await X().wrap("codex",n,{cwd:r,stdio:["pipe","pipe","pipe"],env:t,...F},{engine:"codex",cwd:r});return J(s,o.record),new Promise((c,f)=>{let l;try{l=L(B(o.bin,o.argv,o.opts),o,{kind:"agent"})}catch(u){return f(new Error(`Failed to start codex: ${u.message}`))}const g=H(l,i);let y="",b="",w=!1;const k=u=>{u?.type!=="status"&&(w=!0),s(u)},_={started:new Set,reasoned:new Set,n:0};let x;const $=()=>{clearTimeout(x),x=setTimeout(()=>{l.kill("SIGKILL"),f(new Error(`Codex timed out — no output for ${Math.round(j/1e3)}s.`))},j)};$(),l.stdout.on("data",u=>{$(),y+=u.toString();let h;for(;(h=y.indexOf(`
2
+ `))>=0;){const v=y.slice(0,h).trim();if(y=y.slice(h+1),!!v.startsWith("{"))try{ye(JSON.parse(v),k,_)}catch{}}}),l.stderr.on("data",u=>{$(),b+=u.toString()}),l.on("error",u=>{clearTimeout(x),g(),f(u)}),l.on("close",async u=>{clearTimeout(x),g();let h="";try{h=(await R(e,"utf8")).trim()}catch{}M(e).catch(()=>{}),c({code:u,stderr:b,text:h,streamed:w,said:!!_.saidAny,policyBlocked:!!_.policyBlocked})}),l.stdin.write(a),l.stdin.end()})}async function He({messages:n,system:r,options:t,images:a},e,{signal:s}={}){const i=await ce({messages:n,system:r,options:t,images:a},e,{signal:s}).catch(o=>({handled:!1,reason:o?.message||String(o),thrown:!0}));if(!i.handled&&!s?.aborted){if(i.thrown)throw new Error(i.reason);return ge({messages:n,system:r,options:t,images:a},e,{signal:s})}}async function ge({messages:n,system:r,options:t,images:a},e,{signal:s}={}){const i=`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=m.join(S.tmpdir(),`chatpanel-codex-${i}.txt`),c=await me(a,i),f=()=>c.forEach(d=>M(d).catch(()=>{})),l=ee(t.workingDir),g=[];V(g,t.extraArgs,Y.codex,e);const y=d=>{const p=["exec","--json","--skip-git-repo-check","-o",o];if(t.permissionMode==="bypassPermissions")p.push("--dangerously-bypass-approvals-and-sandbox");else{const E=t.permissionMode==="acceptEdits"?"workspace-write":"read-only";p.push("-s",E),C||p.push("-c","approval_policy=never")}D&&p.push("-c",`model_reasoning_effort=${D}`),p.push("-c","model_reasoning_summary=auto"),p.push(...de(t.mcp)),p.push(...fe(d)),t.model&&p.push("-m",t.model),p.push(...g);for(const E of c)p.push("-i",E);return p.push("-"),p},b=t.useLocalConfig!==!1,w={...process.env,...t.runEnv||{}};if(!b){const d=le();d&&(w.CODEX_HOME=d)}const k=t.mcp?.serverName||"chatpanel_browser",_=w.CODEX_HOME||process.env.CODEX_HOME||m.join(S.homedir(),".codex"),x=pe(_),$=(t.mcp?.specs||[]).length>0;let u=[...new Set([...ne("codex",t,[k]),...$?ue(_):[]])].filter(d=>x.has(d));const h=Q(n,r),v=()=>he({args:y(u),cwd:l,env:w,prompt:h,outFile:o,emit:e,signal:s});try{let d=await v();if(d.policyBlocked&&(C=!0),!s?.aborted&&d.code!==0&&!d.streamed){const p=se({agent:"codex",text:d.stderr,protect:[k],already:u});p&&x.has(p.server)&&(ae("codex",p.server),e({type:"status",text:`MCP server "${p.server}" failed to load — ${p.short}. Skipping it and retrying.`}),u=[...u,p.server],d=await v())}if(s?.aborted)return;if(d.code!==0)throw new Error(te("Codex",d.code,d.stderr,"",{agentId:"codex"}));d.said||e({type:"delta",text:d.text||"(no output)"}),e({type:"done",text:""})}finally{f()}}function ye(n,r,t={started:new Set,reasoned:new Set,n:0}){const a=n.type||"",e=n.item||{},s=e.type||"",i=a==="item.completed"||e.status==="completed"||e.status==="failed";if(s==="agent_message"&&i){const o=e.id||`msg_${t.n++}`,c=String(e.text||"");c&&!t.said?.has(o)&&((t.said||=new Set).add(o),r({type:"delta",text:`${t.saidAny?`
3
3
 
4
4
  `:""}${c}`}),t.saidAny=!0);return}if(s==="command_execution"||!s&&a.includes("command")){const o=e.id||`cmd_${t.n++}`;if(t.started.has(o)||(t.started.add(o),r({type:"tool",name:"shell",phase:"start",callId:o,input:{command:e.command||""}})),i){const c=e.exit_code===0||e.exit_code==null;r({type:"tool",name:"shell",phase:"done",callId:o,status:c?"ok":`exit ${e.exit_code}`,result:String(e.aggregated_output||"").slice(0,4e3)})}return}if(s==="file_change"||!s&&a.includes("patch")){const o=e.id||`edit_${t.n++}`,c=Array.isArray(e.changes)?e.changes.map(f=>f.path||f.file).filter(Boolean):[];t.started.has(o)||(t.started.add(o),r({type:"tool",name:"edit",phase:"start",callId:o,input:{files:c}})),i&&r({type:"tool",name:"edit",phase:"done",callId:o,status:"ok"});return}if(s==="web_search"){const o=e.id||`ws_${t.n++}`,c=e.action&&typeof e.action=="object"?e.action:{},f=e.query||c.query||"",l=c.url||"";t.started.has(o)||(t.started.add(o),r({type:"tool",name:"web_search",phase:"start",callId:o,input:{query:f,...l?{url:l}:{}}})),(i||a==="item.completed")&&r({type:"tool",name:"web_search",phase:"done",callId:o,status:"ok",result:l?`Opened ${l}`:f?`Searched the web for ${f}`:"Searched the web"});return}if(s==="mcp_tool_call"){const o=e.id||`mcp_${t.n++}`,c=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(t.started.has(o)||(t.started.add(o),r({type:"tool",name:c,phase:"start",callId:o,input:e.arguments&&typeof e.arguments=="object"?e.arguments:{}})),i){const f=e.status==="failed"||e.error!=null,l=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error,g=e.result==null?"":typeof e.result=="string"?e.result:JSON.stringify(e.result);r({type:"tool",name:c,phase:"done",callId:o,status:f?`error: ${String(l||"failed").slice(0,80)}`:"ok",result:String(f?l||"":g).slice(0,4e3)})}return}if(s==="todo_list"&&Array.isArray(e.items)&&e.items.length){const o=e.items.map(c=>`${c.completed?"☑":"☐"} ${c.text||""}`).join(`
5
5
  `);t.lastTodo!==o&&(t.lastTodo=o,r({type:"status",text:`Plan:
6
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};
7
+ `}));return}(a==="turn.started"||a==="thread.started")&&r({type:"status",text:"Codex working"})}export{Be as available,He as chat,ge as chatCold,fe as codexDisableArgs,de as codexMcpConfigArgs,pe as configuredMcpServers,le as ensureIsolatedHome,ye as forwardEvent,Pe as listModels,ue as redundantChatpanelServers,Te as resetApprovalPolicy,me as writeImages};
@@ -1,15 +1,15 @@
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 = {
1
+ import{spawn as v}from"node:child_process";import{readFile as Q,writeFile as k,unlink as Y}from"node:fs/promises";import T from"node:os";import A from"node:path";import{resolveCommand as L,buildSpawnSpec as _,selfMcpStdio as tt}from"../env.js";import{missingCommandMessage as U}from"../events/mcp-errors.js";import{sandbox as I,noteSandbox as et,track as F}from"../sandbox.js";import{isProEntitled as D}from"../entitlement.js";import{killOnAbort as rt}from"../proc.js";import{buildCliPrompt as nt,fitCliPrompt as ot,argvPromptBudget as it}from"./prompt.js";import{pushExtraArgs as st,FORBIDDEN as H}from"./args.js";import{createStreamParser as at,STREAM_FORMATS as lt}from"./stream-formats.js";import{resolveWorkdir as ct}from"../workdir.js";async function mt(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",d=A.join(T.tmpdir(),`chatpanel-custom-img-${r}-${n}.${s}`);await k(d,Buffer.from(o[2],"base64")),e.push(d)}return e}function ut(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 J=Number(process.env.CHATPANEL_CUSTOM_TIMEOUT_MS)||18e4,pt="http://127.0.0.1:4319/mcp",j="http://127.0.0.1:4319/mcp";async function Gt(){return{ok:!0}}function dt(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 Kt(t={}){if(!await D(t.entitlement))throw new Error("Custom agents require ChatPanel Pro.");const r=t.custom||{};return ft(r.command,r.listModelsArgs,t.workingDir)}async function ft(t,r,e){const n=String(r||"").trim();if(!t||!n)return[];const o=await gt(t,n.split(/\s+/).filter(Boolean),e);return dt(o)}async function gt(t,r,e,n=2e4){if(!t)return"";const o=L(t);if(!o)throw new Error(U(t,{platform:process.platform}));const s=e?A.resolve(e):null,[d,f,g]=_(o,r,s);g.env={...g.env||process.env,NO_COLOR:"1",CLICOLOR:"0"};const y=await I().wrap(d,f,g,{engine:"custom",cwd:s}),{bin:m,argv:$,opts:u}=y;return new Promise((i,h)=>{let S;try{S=F(v(m,$,u),y,{kind:"probe"})}catch(C){return h(new Error(`Failed to start ${t}: ${C.message}`))}let l="";const M=setTimeout(()=>{S.kill("SIGKILL"),h(new Error(`${t} timed out.`))},n);S.stdout.on("data",C=>l+=C.toString()),S.on("error",C=>{clearTimeout(M),h(new Error(`Failed to start ${t}: ${C.message}`))}),S.on("close",()=>{clearTimeout(M),i(l)});try{S.stdin.end()}catch{}})}function z(t){return(t?.specs||[]).filter(r=>r?.name)}function G(t,r){const e=String(t).replace(/[^A-Za-z0-9_$]/g,"_");return/^[A-Za-z_$]/.test(e)?e:`tool_${r}_${e}`}function ht(t,r){return["--extension",t]}function wt(t,r){const e=String(t||"").trim(),n=z(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 St(t={},r){return t.trustAllToolsForMcp?[t.trustAllToolsArg||"--trust-all-tools"]:t.trustToolsArg?wt(t.trustToolsArg,r):[]}function yt(t={}){return t.stableMcpSetupCommand?t.stableMcpSetupCommand:`opencode mcp add chatpanel --url ${j}`}function Ct(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 $t(t){const r=z(t),e=r.map((o,s)=>{const d=G(o.name,s),f=o.parameters||{type:"object",properties:{}};return`const ${d}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(w)},
6
+ parameters: ${JSON.stringify(f)},
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
- `),n=r.map((o,s)=>` pi.registerTool(${J(o.name,s)}Tool);`).join(`
12
+ `),n=r.map((o,s)=>` pi.registerTool(${G(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)};
@@ -65,7 +65,7 @@ ${e}
65
65
  export default function (pi: ExtensionAPI) {
66
66
  ${n}
67
67
  }
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};
68
+ `}async function bt(t,r){const e=A.join(T.tmpdir(),`chatpanel-pi-tools-${r}.ts`);return await k(e,$t(t)),e}async function xt(){const t=process.env.XDG_CONFIG_HOME||A.join(T.homedir(),".config"),r=[A.join(t,"opencode","opencode.jsonc"),A.join(T.homedir(),"Library","Application Support","opencode","opencode.jsonc")];for(const e of r)try{if((await Q(e,"utf8")).includes(pt))return!0}catch{}return!1}async function K(t,r,e){const n=L(t);if(!n)return"";const[o,s,d]=_(n,r,e||null),f=await I().wrap(o,s,d,{engine:"custom",cwd:e||null}),{bin:g,argv:y,opts:m}=f;return new Promise($=>{const u=F(v(g,y,m),f,{kind:"probe"});let i="",h="";const S=setTimeout(()=>{u.kill("SIGKILL"),$(i+h)},4e3);u.stdout.on("data",l=>i+=l.toString()),u.stderr.on("data",l=>h+=l.toString()),u.on("error",()=>{clearTimeout(S),$(i+h)}),u.on("close",()=>{clearTimeout(S),$(i+h)});try{u.stdin.end()}catch{}})}async function At(t,r){for(const e of["workspace","global","default"]){const n=await K(t,["mcp","list",e],r);if(n.includes(j)||/chatpanel_browser/i.test(n))return!0}return!1}async function Mt(t,r){const e=await K(t,["mcp","list"],r);return e.includes(j)||/chatpanel_browser/i.test(e)}async function Tt(t,r){return t.stableMcpConfigCheck==="kiro"?At(t.command||"kiro-cli",r):t.stableMcpConfigCheck==="opencode"?xt():t.stableMcpConfigCheck==="hermes"?Mt(t.command||"hermes",r):!1}async function Et(t,r){const e=L(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 d=await I().wrap(n,o,s,{engine:"custom",cwd:r||null}),{bin:f,argv:g,opts:y}=d;await new Promise((m,$)=>{let u;try{u=F(v(f,g,y),d,{kind:"probe"})}catch(l){return $(new Error(`Failed to start ${t.command}: ${l.message}`))}let i="",h="";const S=setTimeout(()=>{u.kill("SIGKILL"),$(new Error(`${t.command} MCP setup timed out.`))},2e4);u.stderr.on("data",l=>i+=l.toString()),u.stdout?.on("data",l=>h+=l.toString()),u.on("error",l=>{clearTimeout(S),$(new Error(`Failed to start ${t.command}: ${l.message}`))}),u.on("close",l=>{if(clearTimeout(S),l===0)return m(`${h}
69
+ ${i}`.trim());$(new Error(`${t.command} MCP setup exited ${l}: ${i.trim().split(`
70
+ `).pop()||"failed"}`))});try{u.stdin.end()}catch{}})}function Ot(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 Pt(t,r,e,n,o={}){if(!t.requiresStableMcp)return!0;const s=o.hasConfig||Tt,d=o.runSetup||Et;if(await s(t,r))return!0;const f=yt(t);if(!t.autoSetupStableMcp){const m=`${e} needs one-time browser-tool setup: ${f}`;throw n({type:"status",text:m}),new Error(m)}const g=Ct(t);if(!g?.command){const m=`${e} needs one-time browser-tool setup: ${f}`;throw n({type:"status",text:m}),new Error(m)}n({type:"status",text:`${e} is setting up one-time browser tools...`});const y=String(await d(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: ${f}`)}async function Zt({messages:t,system:r,options:e,images:n},o,{signal:s}={}){if(!await D(e.entitlement))throw new Error("Custom agents require ChatPanel Pro. Upgrade in Settings to bring your own CLI agent.");return vt(e.custom||{},{messages:t,system:r,options:e,images:n},o,{signal:s})}async function vt(t,{messages:r,system:e,options:n={},images:o},s,{signal:d}={}){if(!t.command)throw new Error("This agent has no command configured.");const f=L(t.command);if(!f)throw new Error(U(t.command,{platform:process.platform}));let g=nt(r,e),y=ct(n.workingDir);const m=t.label||t.command,$=Object.hasOwn(lt,t.format)?t.format:"text",u=t.promptVia==="arg"?"arg":"stdin";let i=Array.isArray(t.args)?t.args.slice():t.args?String(t.args).split(/\s+/).filter(Boolean):[];if(st(i,n.extraArgs,H[t.forbidden]||H.custom,s),n.model&&t.modelArg){const a=String(t.modelArg),c=a.includes("{model}")?a.replaceAll("{model}",n.model).split(/\s+/).filter(Boolean):[...a.split(/\s+/).filter(Boolean),n.model];i=[...i,...c]}if(t.permissionArgs){const a=String(n.permissionMode||"default"),c=t.permissionArgs[a]||t.permissionArgs.default||[];i=[...i,...c.map(String)]}const h=`${Date.now()}-${Math.random().toString(36).slice(2)}`,S=t.imageArg?await mt(o,h):[],l=[],M=()=>[...S,...l].forEach(a=>Y(a).catch(()=>{}));if(n.mcp?.url&&t.toolAdapter==="pi-extension"){const a=await bt(n.mcp,h);l.push(a),i=[...ht(a,n.mcp),...i]}else if(n.mcp?.url&&t.mcpArg){const a=n.mcp.serverName||"chatpanel_browser",{command:c,args:p}=tt(n.mcp.url),w=A.join(T.tmpdir(),`chatpanel-mcp-${h}.json`);await k(w,JSON.stringify({mcpServers:{[a]:{command:c,args:p}}})),l.push(w);const b=String(t.mcpArg);i=[...b.includes("{file}")?b.replaceAll("{file}",w).split(/\s+/).filter(Boolean):[...b.split(/\s+/).filter(Boolean),w],...i]}if(n.mcp?.url)try{await Pt(t,y,m,s)}catch(a){s({type:"status",text:`${m}: continuing without ChatPanel's browser tools — ${Ot(m,a)}`}),n={...n,mcp:null}}if(n.mcp?.url&&i.push(...St(t,n.mcp)),n.model&&typeof t.modelPatch?.build=="function"){const a=/^[A-Za-z0-9][\w.:-]{0,79}$/.test(String(n.model))?String(n.model):"";if(a){const c=A.join(T.tmpdir(),`chatpanel-modelpatch-${h}.yml`);await k(c,t.modelPatch.build(a)),l.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 C=ut(t.imageArg,S);let N=!1;if(C.length&&(i=i.flatMap(a=>a==="{images}"?(N=!0,C):[a])),u==="arg"){const a=i.reduce((w,b)=>w+String(b).length+3,0)+C.reduce((w,b)=>w+String(b).length+3,0),c=ot(r,e,it({viaCmdExe:f.kind==="cmd",otherArgsChars:a}));(c.dropped||c.prompt!==g)&&(g=c.prompt,s({type:"status",text:`${m} 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(w=>w.includes("{prompt}")?(p=!0,w.replaceAll("{prompt}",g)):w),p||(C.length&&!N&&i.push(...C),i.push(g))}else C.length&&!N&&i.push(...C);const[Z,q,R]=_(f,i,y,n.runEnv||null);R.env={...R.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"};const E=await I().wrap(Z,q,R,{engine:"custom",cwd:y});et(s,E.record);const[V,W,X]=[E.bin,E.argv,E.opts];await new Promise((a,c)=>{let p;try{p=F(v(V,W,X),E,{kind:"agent"})}catch(x){return M(),c(new Error(`Failed to start ${m}: ${x.message}`))}const w=rt(p,d);let b="";const O=at($,s);let P;const B=()=>{clearTimeout(P),P=setTimeout(()=>{p.kill("SIGKILL"),M(),c(new Error(`${m} timed out — no output for ${Math.round(J/1e3)}s.`))},J)};B(),p.stdout.on("data",x=>{B(),O.push(x.toString())}),p.stderr.on("data",x=>{B(),b+=x.toString()}),p.on("error",x=>{clearTimeout(P),w(),M(),c(new Error(`Failed to start ${m}: ${x.message}`))}),p.on("close",x=>{if(clearTimeout(P),w(),M(),d?.aborted){a();return}x===0?(s({type:"done",text:O.streamed?"":O.finish()}),a()):c(new Error(summarizeCliError(m,x,b)))}),u==="stdin"&&p.stdin.write(g),p.stdin.end()})}export{j as CHATPANEL_STABLE_MCP_URL,Gt as available,$t as buildPiExtensionSource,Zt as chat,K as commandOutput,Pt as ensureStableMcpConfig,Kt as listModels,ft as listSpecModels,Ot as mcpSetupHint,St as mcpTrustArgs,ht as piToolArgs,gt as runForStdout,vt as runSpec,yt as stableMcpSetupCommand,Ct as stableMcpSetupPlan,wt as trustToolArgs};
@@ -0,0 +1,6 @@
1
+ function W(n){const t=String(n||"").trim();if(!t)return[];const e=A(t);return e?v(e):b(t)}function S(n){if(Array.isArray(n))return n.map(String).filter(Boolean);const t=String(n||"").trim();return t?t.startsWith("[")?h(t):w(t).map(e=>e.replace(/,+$/,"")).filter(Boolean):[]}function T(n){return Array.isArray(n)?n.join(`
2
+ `):String(n||"")}function _(n){if(n&&typeof n=="object"&&!Array.isArray(n))return Object.fromEntries(Object.entries(n).filter(([e,i])=>e&&String(i??"")!=="").map(([e,i])=>[e,String(i)]));const t={};for(const e of String(n||"").split(/\n|,(?=\s*[A-Za-z_][A-Za-z0-9_]*\s*=)/)){const i=e.indexOf("=");if(i<=0)continue;const r=e.slice(0,i).trim(),s=e.slice(i+1).trim();r&&s&&(t[r]=s)}return t}function z(n){return(Array.isArray(n)?n:[]).map(String).filter(t=>/^[A-Z][A-Z0-9_]*=/.test(t.trim()))}function I(n){return Object.entries(n||{}).map(([t,e])=>`${t}=${e}`).join(`
3
+ `)}function A(n){try{return JSON.parse(n)}catch{return null}}function v(n){const t=n?.mcpServers||n?.mcp_servers||n?.servers||n;return!t||typeof t!="object"?[]:t.command||t.url?[f("Imported MCP server",t)]:Object.entries(t).map(([e,i])=>f(e,i)).filter(Boolean)}function b(n){const t=[],e=/^\s*\[(mcp_servers|mcpServers)\.([^\]]+)\]\s*$/gm;let i;for(;i=e.exec(n);)t.push({name:i[2].trim().replace(/^["']|["']$/g,""),start:e.lastIndex});return t.map((r,s)=>{const o=t[s+1]?.start?n.lastIndexOf(`
4
+ `,t[s+1].start-t[s+1].name.length-15):n.length,l=n.slice(r.start,o<r.start?n.length:o);return f(r.name,j(l))}).filter(Boolean)}function j(n){const t={};for(const o of["type","transport","command","url"]){const l=u(n,o);l!=null&&(t[o]=p(l))}const e=u(n,"args");e!=null&&(t.args=h(e));const i=u(n,"env")??u(n,"environment")??u(n,"environmentVariables");i!=null&&(t.env=m(i));const r=u(n,"headers");r!=null&&(t.headers=m(r));const s=u(n,"authorization")??u(n,"auth_header");return s!=null&&(t.headers={...t.headers||{},Authorization:p(s)}),t}function f(n,t={}){if(!t||typeof t!="object")return null;const e=d(t.command),i=d(t.url),r=String(t.type||t.transport||(e?"stdio":"http")).toLowerCase(),s={name:$(n),enabled:t.enabled!==!1};return e||r==="stdio"?e?{...s,transport:"stdio",command:e,args:S(t.args),env:g(t.env||t.environment||t.environmentVariables)}:null:i?{...s,transport:"http",url:i,headers:g(t.headers)}:null}function u(n,t){const e=String(n||"").split(/\r?\n/);for(let i=0;i<e.length;i++){const r=new RegExp(`^\\s*${C(t)}\\s*=\\s*(.*)$`).exec(e[i]);if(!r)continue;let s=x(r[1]).trim();if(!s)return"";const o=s[0],l=o==="["?"]":o==="{"?"}":"";if(!l)return s;let a=y(s,o,l);for(;a>0&&i+1<e.length;)i+=1,s+=`
5
+ ${x(e[i])}`,a=y(s,o,l);return s.trim()}return null}function h(n){const t=String(n||"").trim(),e=t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t,i=[];let r=0;for(;r<e.length;){for(;r<e.length&&/[\s,]/.test(e[r]);)r+=1;if(r>=e.length)break;const s=e[r];if(s==='"'||s==="'"){const a=c(e,r);i.push(a.value),r=a.next;continue}let o=r;for(;o<e.length&&e[o]!==",";)o+=1;const l=e.slice(r,o).trim();l&&i.push(l),r=o+1}return i}function m(n){const t=String(n||"").trim(),e=t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t,i={};let r=0;for(;r<e.length;){for(;r<e.length&&/[\s,]/.test(e[r]);)r+=1;if(r>=e.length)break;let s="";if(e[r]==='"'||e[r]==="'"){const o=c(e,r);s=o.value,r=o.next}else{let o=r;for(;o<e.length&&e[o]!=="="&&e[o]!==":";)o+=1;s=e.slice(r,o).trim(),r=o}for(;r<e.length&&/[\s=:]/.test(e[r]);)r+=1;if(!s)break;if(e[r]==='"'||e[r]==="'"){const o=c(e,r);i[s]=o.value,r=o.next}else{let o=r;for(;o<e.length&&e[o]!==",";)o+=1;i[s]=p(e.slice(r,o).trim()),r=o+1}}return i}function w(n){const t=[];let e="",i="",r=!1;for(const s of String(n||"")){if(r){e+=s,r=!1;continue}if(s==="\\"){r=!0;continue}if(i){s===i?i="":e+=s;continue}if(s==='"'||s==="'"){i=s;continue}if(/\s/.test(s)){e&&(t.push(e),e="");continue}e+=s}return e&&t.push(e),t}function c(n,t){const e=n[t];let i="",r=!1;for(let s=t+1;s<n.length;s++){const o=n[s];if(r){i+=e==='"'?O(o):o,r=!1;continue}if(o==="\\"&&e==='"'){r=!0;continue}if(o===e)return{value:i,next:s+1};i+=o}return{value:i,next:n.length}}function p(n){const t=String(n||"").trim().replace(/,+$/,"");return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?c(t,0).value:t==="true"?!0:t==="false"?!1:t}function g(n){return!n||typeof n!="object"||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).map(([t,e])=>[t,String(e)]))}function $(n){return String(n||"MCP server").replace(/[_-]+/g," ").replace(/\b[a-z]/g,t=>t.toUpperCase())}function d(n){return typeof n=="string"?n.trim():""}function x(n){let t="";for(let e=0;e<n.length;e++){const i=n[e];if(t){i===t&&(t=""),i==="\\"&&t==='"'&&(e+=1);continue}if(i==='"'||i==="'")t=i;else if(i==="#")return n.slice(0,e)}return n}function y(n,t,e){let i=0,r="";for(let s=0;s<n.length;s++){const o=n[s];if(r){o==="\\"&&r==='"'?s+=1:o===r&&(r="");continue}o==='"'||o==="'"?r=o:o===t?i+=1:o===e&&(i-=1)}return i}function O(n){return{n:`
6
+ `,r:"\r",t:" ",'"':'"',"\\":"\\"}[n]??n}function C(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}export{T as argsToText,z as envLikeArgs,I as envToText,S as parseArgsInput,_ as parseEnvInput,W as parseMcpConfig};
@@ -0,0 +1 @@
1
+ const c=[{tool:"uv",match:/^(uvx?|uv-?run)$/,ships:"is part of uv, the Python package runner from Astral",install:{mac:"brew install uv",linux:"curl -LsSf https://astral.sh/uv/install.sh | sh",windows:"winget install astral-sh.uv"}},{tool:"Node.js",match:/^(node|npx|npm|corepack|pnpm|yarn)$/,ships:"ships with Node.js",install:{mac:"brew install node",linux:"nvm install --lts (or the package from https://nodejs.org)",windows:"winget install OpenJS.NodeJS.LTS"}},{tool:"Python",match:/^(python[0-9.]*|py|pip[0-9.]*)$/,ships:"ships with Python 3",install:{mac:"brew install python",linux:"sudo apt install python3 python3-pip (or your distribution's package)",windows:"winget install Python.Python.3.12"}},{tool:"pipx",match:/^pipx$/,ships:"is pipx, the isolated installer for Python apps",install:{mac:"brew install pipx",linux:"python3 -m pip install --user pipx && python3 -m pipx ensurepath",windows:"python -m pip install --user pipx && python -m pipx ensurepath"}},{tool:"Docker",match:/^docker$/,ships:"is the Docker CLI",install:{mac:"brew install --cask docker (Docker Desktop), then start it once",linux:"https://docs.docker.com/engine/install/",windows:"winget install Docker.DockerDesktop, then start it once"}},{tool:"Bun",match:/^bunx?$/,ships:"ships with Bun",install:{mac:"curl -fsSL https://bun.sh/install | bash",linux:"curl -fsSL https://bun.sh/install | bash",windows:'powershell -c "irm bun.sh/install.ps1 | iex"'}},{tool:"Deno",match:/^deno$/,ships:"is Deno",install:{mac:"brew install deno",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"irm https://deno.land/install.ps1 | iex"}}];function p(t){const s=String(t||"");return/mac|darwin|iphone|ipad/i.test(s)?"mac":/win/i.test(s)?"windows":/linux|x11|android|freebsd/i.test(s)?"linux":""}const d=t=>String(t||"").trim().split(/[\\/]/).pop().replace(/\.(exe|cmd|bat|ps1)$/i,"").toLowerCase();function o(t,{platform:s=""}={}){const n=d(t);if(!n)return null;const i=p(s),e=c.find(h=>h.match.test(n))||null,a=e?i?e.install[i]:`macOS: ${e.install.mac} · Linux: ${e.install.linux} · Windows: ${e.install.windows}`:"",l=i==="windows"?`"where ${n}" prints it`:i?`"which ${n}" prints it`:`"which ${n}" (macOS/Linux) or "where ${n}" (Windows) prints it`;return{command:n,tool:e?e.tool:null,ships:e?e.ships:"",install:a,verify:`${n} --version`,fullPath:l}}function w(t,{platform:s=""}={}){const n=o(t,{platform:s}),i=String(t||"").trim();if(!n)return"No command to run.";const e=n.tool?`"${i}" ${n.ships}, and it is not installed here (or not on the PATH the bridge sees).`:`Couldn't find "${i}" — it is not installed, or not on the PATH the bridge sees.`,a=n.tool?` Install it: ${n.install} — then open a new terminal, check that "${n.verify}" works, and try again.`:` Install it, then open a new terminal, check that "${n.verify}" works, and try again.`;return`${e}${a} Already installed? Enter its full path instead: ${n.fullPath}.`}const u=[/Couldn'?t find "([^"]+)"/i,/\bspawn (\S+) ENOENT\b/,/'([^']+)' is not recognized as an internal or external command/i,/The term '([^']+)' is not recognized/i,/command not found:\s*(\S+)/i,/(?:^|[\n:]\s*)([\w./\\-]+): (?:command )?not found/i];function r(t){const s=String(t||"");for(const n of u){const i=n.exec(s);if(i&&i[1])return i[1]}return""}const m=[{id:"missing-shebang",test:t=>/(import|const|export):\s*(command not found|not found)/i.test(t)||/syntax error near unexpected token/i.test(t)&&/command not found/i.test(t),explain:t=>({summary:`${t||"This MCP server"} cannot start: its executable is missing a shebang.`,detail:"The package's entry file is JavaScript but has no `#!/usr/bin/env node` first line, so the shell tries to run it as a shell script. That is a bug in the published package, not in your setup — nothing you configure here can fix it.",fix:"Report it to the package author, pin an earlier version that worked, or use a different server.",blame:"package"})},{id:"runtime-missing",test:t=>!!r(t),explain:(t,{text:s,platform:n}={})=>{const i=r(s),e=o(i,{platform:n}),a=e?.tool?`"${i}" ${e.ships}.`:`"${i}" is the command this server is launched with.`;return{summary:`"${i}" is not installed, or not on the PATH the bridge sees${t?` — ${t} cannot start`:""}.`,detail:`${a} Nothing about the server itself has been checked yet: the launcher has to exist before it can be tried.`,fix:e?.tool?`Install it: ${e.install} — then open a new terminal, check that "${e.verify}" works, and test again. Already installed? Enter its full path instead: ${e.fullPath}.`:`Install it, then open a new terminal, check that "${e?.verify||`${i} --version`}" works, and test again. Already installed? Enter its full path instead: ${e?.fullPath||"which/where prints it"}.`,blame:"setup",command:i}}},{id:"not-found",test:t=>/npm ERR!.*(404|E404)|could not determine executable/i.test(t),explain:t=>({summary:`${t||"The package"} could not be found or has no runnable command.`,detail:"npm resolved nothing to run for this package name and version.",fix:"Check the package name and version, and that the registry in use publishes it.",blame:"config"})},{id:"no-bridge",test:t=>/can'?t reach the chatpanel bridge|ECONNREFUSED.*4319/i.test(t),explain:()=>({summary:"The ChatPanel Bridge is not running.",detail:"Local MCP servers are launched by the bridge, so nothing can start without it.",fix:"Install ChatPanel — the gateway, which brings the bridge (`npm i -g @chatpanel/gateway`, then `chatpanel-gateway --install`; or https://dl.chatpanel.net/install.sh) — or start a bridge with `npx @chatpanel/bridge`, then try again.",blame:"setup"})},{id:"node-version",test:t=>/requires node|unsupported engine|SyntaxError: Unexpected token '\?\?'/i.test(t),explain:t=>({summary:`${t||"This server"} needs a newer Node than the one launching it.`,detail:"The process started but failed on syntax its Node version does not support.",fix:"Upgrade Node, or run the server with a version manager that selects a newer one.",blame:"setup"})}];function g(t,{packageName:s="",platform:n=""}={}){const i=String(t||"");if(!i.trim())return null;for(const e of m)if(e.test(i))return{id:e.id,...e.explain(s,{text:i,platform:n}),raw:i};return null}function x(t=[]){for(const s of t){const n=String(s);if(!n.startsWith("-")&&!(n==="npx"||n==="node"))return n}return""}const f=/\b(session (not found|expired|invalid|unknown)|invalid session|no (valid )?session|not initialized|before initialization|initialization was (not )?complete|-32002)\b/i;function b(t,{status:s}={}){if(s===404)return!0;const n=String(t||"");return n?/\bHTTP 404\b/.test(n)?!0:f.test(n):!1}export{g as explainMcpError,o as installHintFor,b as isStaleMcpSession,r as missingCommandIn,w as missingCommandMessage,p as normalizePlatform,x as packageFromArgs};
@@ -0,0 +1 @@
1
+ function c(r){for(const t of r){const n=/^git\+[^@\s]+@(.+)$/.exec(String(t));if(n)return n[1];if(/^git\+/.test(String(t)))return""}return null}const l=/^[0-9a-f]{7,40}$/i;function d(r,t){const n=Array.isArray(t)?t.map(String):String(t||"").split(/\s+/).filter(Boolean),e=String(r||"").trim().toLowerCase(),i=c(n);if(i!=null)return l.test(i)?null:{kind:"git",what:i||"the default branch",why:i?`"${i}" is a branch or tag, and ${e||"the launcher"} resolves it once and keeps the checkout — a later fix on it never arrives.`:`No ref is given, so ${e||"the launcher"} takes the default branch, resolves it once and keeps the checkout — a later fix never arrives.`,fix:"Pin a commit (…@a1b2c3d) so what runs is what was tested, or use Refresh to fetch once."};const o=n.find(a=>!a.startsWith("-")&&!/^(--from|--python|--with|-y|--package)$/.test(a));return!o||/[@=]/.test(o.replace(/^@[^/]+\//,""))?null:{kind:"package",what:o,why:`"${o}" names no version, so ${e||"the launcher"} resolves one once and serves it from cache afterwards.`,fix:"Pin a version, or use Refresh to fetch the latest once."}}function f(r,t){const n=Array.isArray(t)?t.map(String):String(t||"").split(/\s+/).filter(Boolean),e=String(r||"").trim().toLowerCase().replace(/\.(exe|cmd|bat)$/,"").split(/[\\/]/).pop();return e==="uvx"||e==="uv"?n.includes("--refresh")?n:["--refresh",...n]:e==="npx"?n.includes("--ignore-existing")?n:["--ignore-existing",...n]:null}function g(r){return f(r,[])!==null}function m({serverInfo:r=null,since:t=0,now:n=Date.now()}={}){const e=r?.name?String(r.name):"",i=r?.version?String(r.version):"",o=t?Math.max(0,n-t):0,a=Math.floor(o/6e4),s=t?a<1?"just started":a<60?`started ${a} min ago`:`started ${Math.floor(a/60)} h ago`:"",u=[e&&i?`${e} ${i}`:e||i,s].filter(Boolean).join(" · ");return{name:e,version:i,age:s,label:u}}function p(r){const t=(Array.isArray(r)?r:[]).filter(e=>{if(!e?.name||(e.inputSchema?.required||e.parameters?.required||[]).length)return!1;const o=e.annotations||{};return o.readOnlyHint===!1||o.destructiveHint===!0?!1:o.readOnlyHint===!0});return t.length?(t.find(e=>e.annotations?.openWorldHint===!1)||t[0]).name:null}const h=15*6e4;function x({since:r=0,now:t=Date.now(),ttlMs:n=h}={}){if(!r)return{expired:!0,remainingMs:0};const e=Math.max(0,r+n-t);return{expired:e<=0,remainingMs:e}}export{h as SIGN_IN_TTL_MS,g as canRefresh,m as describeRuntime,d as mutableRef,p as pickProbeTool,f as refreshArgs,x as signInCountdown};
@@ -0,0 +1 @@
1
+ const _=-32011,s=/https?:\/\/[^\s"'<>)\]]+/,h=/\b(?:code|passcode)\b[:\s]+([A-Z0-9][A-Z0-9-]{3,}[A-Z0-9])\b/,i=/sign[ -]?in|log[ -]?in|authenticate|authoriz|verify|devicelogin|login\/device|oauth/i,f=/opening (?:your |the |a )?browser|open(?:ed|ing)? .*browser .*sign/i,w=/[?&]redirect_uri=https?%3A%2F%2F(?:localhost|127\.0\.0\.1)|[?&]redirect_uri=https?:\/\/(?:localhost|127\.0\.0\.1)/i;function v(n){const e=String(n||"");return/response_type=code/i.test(e)?w.test(e):!1}function b(n){const e=String(n||"");if(!e.trim())return null;const o=e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),u=o.join(" "),l=h.exec(u)?.[1]||null,c=o.filter(t=>i.test(t)||s.test(t)),a=c.find(t=>s.test(t)&&i.test(t))||c.find(t=>s.test(t)),r=a?s.exec(a)[0].replace(/[.,;]+$/,""):null;if(r&&(l||i.test(u))){const t=(c.find(g=>i.test(g))||a).slice(0,300);return!l&&v(r)?{url:r,code:null,message:t,browser:!0,interactive:!0}:{url:r,code:l,message:t,browser:!1,interactive:!1}}const d=o.find(t=>f.test(t));return d?{url:null,code:null,message:d.slice(0,300),browser:!0,interactive:!0}:null}function I(n){const e=n.url?` Open ${n.url}${n.code?` and enter the code ${n.code}`:""}.`:"";return{code:-32011,message:`Sign-in required: ${n.message}${e}`,data:{signIn:{url:n.url,code:n.code,message:n.message,browser:!!n.browser,interactive:!!n.interactive}}}}function E(n){if(!n||n.code!==-32011)return null;const e=n.data?.signIn;return e?{url:e.url||null,code:e.code||null,message:e.message||"",browser:!!e.browser,interactive:!!e.interactive}:{url:null,code:null,message:String(n.message||""),browser:!1,interactive:!1}}function S(n,e){return{error:"sign_in_required",server:n,...e.url&&!e.interactive?{url:e.url}:{},...e.code?{code:e.code}:{},...e.browser?{browser:!0}:{},next:e.interactive?"The server opened its own browser window for the user to sign in, and any link it printed works only in that window, right now. Tell them to finish signing in there and then ask again. Do NOT paste the link, and do not invent a result.":"The user has been shown this sign-in prompt. Give them the url and the code exactly, ask them to complete it, then call this tool again. Do not invent a result."}}export{_ as MCP_SIGN_IN_CODE,b as parseSignInPrompt,I as signInError,E as signInFromError,S as signInToolResult};
@@ -0,0 +1 @@
1
+ import{EventError as n}from"./event.js";const a=t=>!!t&&typeof t=="object"&&!Array.isArray(t),e=t=>[...new Set(t)],i=(t,o)=>{if(!t)throw new n("SHAPE",o)},f=/^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d{1,5})?$/i;function p(t){return e(String(t||"").split(/[\s,;]+/).map(o=>o.trim().toLowerCase()).filter(Boolean))}function h(t){if(t==null)return{hosts:[],write:[]};i(a(t),"grant: must be an object");const o=Array.isArray(t.hosts)?t.hosts:typeof t.hosts=="string"?p(t.hosts):[],s=Array.isArray(t.write)?t.write:typeof t.write=="string"?t.write.split(/[\n,]+/).map(r=>r.trim()).filter(Boolean):[];for(const r of o)i(typeof r=="string"&&r!=="*"&&f.test(r),`grant: not a host pattern: ${JSON.stringify(r)}`);for(const r of s)i(typeof r=="string"&&r.length>0&&r.length<1024&&!r.includes("\0"),`grant: not a path: ${JSON.stringify(r)}`);return{hosts:e(o.map(r=>r.toLowerCase())),write:e(s)}}function c(...t){const o=t.map(h);return{hosts:e(o.flatMap(s=>s.hosts)),write:e(o.flatMap(s=>s.write))}}export{c as mergeGrants,h as normalizeGrant,p as parseHostList};
@@ -1 +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};
1
+ import{EventError as A}from"./event.js";import{normalizeGrant as b}from"./sandbox-grant.js";const y=Object.freeze(["none","process","container","kubernetes"]),E=Object.freeze(["open","allowlist","none","gateway"]),_=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),x=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),h=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:[]}),extract:Object.freeze({hosts:[],write:[]})}),R=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"]),u=e=>!!e&&typeof e=="object"&&!Array.isArray(e),g=e=>Array.isArray(e)&&e.every(o=>typeof o=="string"&&o.length>0),c=(e,o)=>{if(!e)throw new A("SHAPE",o)},f=e=>[...new Set(e)];function O(e){c(u(e),"kit: must be an object"),c(typeof e.id=="string"&&e.id.length>0,"kit: id required"),c(u(e.network)&&E.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${E.join(", ")}`),c(g(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),c(g(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),c(u(e.filesystem),`kit ${e.id}: filesystem required`);for(const o of["allowWrite","denyWrite","allowRead","denyRead"])c(g(e.filesystem[o]||[]),`kit ${e.id}: filesystem.${o} must be string[]`);return c(g(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),e.image!=null&&c(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&c(Array.isArray(e.credentials)&&e.credentials.every(o=>u(o)&&typeof o.name=="string"&&typeof o.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:f(e.network.allowedDomains||[]),deniedDomains:f(e.network.deniedDomains||[])},filesystem:{allowWrite:f(e.filesystem.allowWrite),denyWrite:f(e.filesystem.denyWrite||[]),allowRead:f(e.filesystem.allowRead||[]),denyRead:f(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:u(e.limits)?{...e.limits}:{}}}import{normalizeGrant as M,mergeGrants as k,parseHostList as q}from"./sandbox-grant.js";function N({engine:e="custom",cwd:o,mode:t="open",extraHosts:r=[],extraWrite:n=[],extraDenyRead:s=[],grant:l=null}={}){const d=h[e]||h.custom;c(typeof o=="string"&&o.length>0,"kit: cwd required");const a=b(l);return O({id:`${e}:${t}`,kind:"process",network:{mode:t,allowedDomains:t==="open"?["*"]:t==="none"?[]:f([...d.hosts,...R,...r,...a.hosts]),deniedDomains:[]},filesystem:{allowWrite:f([o,...x,...d.write,...n,...a.write.filter(i=>!_.some(p=>i===p||i.startsWith(`${p}/`)))]),denyWrite:[],allowRead:[o],denyRead:f([..._,...s])}})}function z(e,{loopback:o=[],home:t="",platform:r="darwin"}={}){const n=O(e),s=d=>t&&d.startsWith("~")?t+d.slice(1):d,l=n.network.mode==="none"?[]:o.map(d=>`127.0.0.1:${d}`);return{network:{allowedDomains:f([...n.network.allowedDomains,...l]),deniedDomains:n.network.deniedDomains,allowLocalBinding:r==="darwin"&&l.length>0},filesystem:{denyRead:n.filesystem.denyRead.map(s),allowRead:n.filesystem.allowRead.map(s),allowWrite:n.filesystem.allowWrite.map(s),denyWrite:n.filesystem.denyWrite.map(s)}}}function C({layer:e="none",runtime:o=null,kitId:t=null,mode:r=null,reason:n=null,hosts:s=null}={}){return c(y.includes(e),`sandbox record: layer must be one of ${y.join(", ")}`),{layer:e,runtime:o,kit:t,mode:r,...e==="none"&&n?{reason:n}:{},...Array.isArray(s)&&s.length?{hosts:f(s)}:{}}}function S(e,{platform:o="darwin"}={}){const t=String(e);if(o==="win32"){c(!/[\r\n]/.test(t),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=t;if(t===""||/[ \t\v"]/.test(t)){r='"';for(let n=0;n<t.length;n++){let s=0;for(;n<t.length&&t[n]==="\\";)s++,n++;if(n===t.length){r+="\\".repeat(s*2);break}t[n]==='"'?r+="\\".repeat(s*2+1)+'"':r+="\\".repeat(s)+t[n]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return t===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}const I=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function H(e={},{platform:o="darwin",caBundle:t=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(t)for(const n of I)e[n]||(r[n]=t);if(o==="linux")for(const n of["no_proxy","NO_PROXY"])typeof e[n]=="string"&&(r[n]=e[n].split(",").map(s=>s.trim()).filter(s=>s&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(s)).join(","));return r}function L(e,o=[],{platform:t="darwin"}={}){return[e,...o].map(r=>S(r,{platform:t})).join(" ")}const T=/[\\/]+/,m=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),D=e=>/^[a-z]:$/i.test(m(e))||m(e)==="";function w(e,o){const t=m(e),r=m(o);return!!r&&t!==r&&t.startsWith(r+"\\")}function W(e){const o=String(e||"").replace(/\//g,"\\").split("\\");if(o.length<2)return"";const t=o.findIndex(r=>r.toLowerCase()==="node_modules");return(t>0?o.slice(0,t):o.slice(0,-1)).join("\\")}function K({kit:e,files:o=[],home:t}){c(typeof t=="string"&&t.length>0,"windows grants: home required");const r=a=>(a.startsWith("~")?t+a.slice(1):a).replace(/\//g,"\\"),n=[];for(const a of e?.filesystem?.allowWrite||[]){const i=r(a);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(c(!D(i)&&m(i)!==m(t),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),w(i,t)&&n.push(i))}const s=(a,i)=>i.some(p=>m(a)===m(p)||w(a,p)),l=[];for(const a of o){const i=W(a);i&&w(i,t)&&l.push(i)}for(const a of e?.filesystem?.allowRead||[]){const i=r(a);w(i,t)&&l.push(i)}const d=f(l).filter(a=>!s(a,n));return{read:d.filter(a=>!d.some(i=>i!==a&&w(a,i))),write:f(n)}}const j=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","CODEX_HOME","GEMINI_API_KEY","GOOGLE_API_KEY","DEEPSEEK_API_KEY","DSH_HOME","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"]);function Y({engine:e="custom",home:o,env:t={},base:r={},carry:n=j}={}){c(typeof o=="string"&&o.length>0,"windows env: home required");const s=o.replace(/\//g,"\\"),l=/^[a-z]:/i.test(s)?s.slice(0,2):"",d={USERPROFILE:s,...l?{HOMEDRIVE:l,HOMEPATH:s.slice(2)}:{}};for(const[a,i]of Object.entries(t))typeof i=="string"&&(r[a]!==i||n.includes(a))&&(d[a]=i);return e==="codex"&&!d.CODEX_HOME&&(d.CODEX_HOME=s+"\\.codex"),d}function v(e,o){c(Array.isArray(e),"srt-win argv: must be an array");const t=e.indexOf("exec"),r=t>=0?e.indexOf("--",t+1):-1;c(t>=0&&r>t,"srt-win argv: expected `exec … -- <shell> <command>`");const n=new Set;for(let l=t+1;l<r;l++)e[l]==="--env"&&typeof e[l+1]=="string"&&n.add(e[l+1].split("=")[0].toUpperCase());const s=[];for(const[l,d]of Object.entries(o||{}))c(/^[A-Za-z_][A-Za-z0-9_]*$/.test(l),`srt-win env: bad key ${l}`),c(!/[\r\n]/.test(d),`srt-win env: ${l} holds a newline`),n.has(l.toUpperCase())||s.push("--env",`${l}=${d}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{x as COMMON_WRITE,R as DEVELOPER_HOSTS,h as ENGINE_KITS,E as NETWORK_MODES,y as SANDBOX_LAYERS,_ as SECRET_PATHS,j as WINDOWS_CARRY_KEYS,N as kitFor,k as mergeGrants,M as normalizeGrant,q as parseHostList,H as sandboxEnvOverlay,C as sandboxRecord,L as shellJoin,S as shellQuote,z as toSrtSettings,w as underWindowsHome,O as validateKit,K as windowsGrantsFor,W as windowsInstallRoot,Y as windowsSandboxEnv,v as withSrtWinEnv};
@@ -1 +1 @@
1
- import{DATA_SCOPES as a}from"./scopes.js";class o extends Error{constructor(t,r){super(r),this.name="SkillManifestError",this.code=t}}const u=2,S=Object.freeze(["auto","page","selection","tabs","none"]),l=Object.freeze(["none","chats","meetings","all"]),d=Object.freeze(["none","selected","default"]),I=Object.freeze(["built-in","user","community"]),m=Object.freeze(["references","scripts","assets","templates","examples"]),s=e=>typeof e=="string"&&e.length>0,h=/^[a-z0-9][a-z0-9_-]*$/;function w(e){return!(!s(e)||e.length>255||e!==e.trim()||e.includes("\\")||/[\u0000-\u001f\u007f]/.test(e)||e.startsWith("/")||/^[a-z]:/i.test(e)||e.split("/").some(r=>r===""||r==="."||r===".."))}function f(e){const t=e?.origin;return t&&typeof t=="object"&&s(t.source)&&s(t.id)?t:null}function y(e){return f(e)?"community":e?.builtin?"built-in":"user"}function p(e){const t=e?.files,r={};if(!t||typeof t!="object")return r;for(const i of m){const n=Array.isArray(t[i])?t[i].filter(w):[];n.length&&(r[i]=[...new Set(n)])}return r}function g(e){return(p(e).scripts||[]).length>0}function E(e={}){const t=p(e),r=d.includes(e.mcpMode)?e.mcpMode:"none",i=S.includes(e.context)?e.context:"auto",n=l.includes(e.historyContext)?e.historyContext:"none",c=new Set(Array.isArray(e.reads)?e.reads.filter(b=>a.includes(b)):[]);return i!=="none"&&c.add("page"),(n==="chats"||n==="all")&&c.add("chats"),(n==="meetings"||n==="all")&&c.add("meetings"),{trust:y(e),reads:[...c].sort(),page:i,history:n,mcp:r,mcpServerIds:r==="selected"&&Array.isArray(e.mcpServerIds)?[...e.mcpServerIds]:[],sources:Array.isArray(e.sources)?[...new Set(e.sources.filter(s))].sort():[],surfaces:Array.isArray(e.surfaces)?[...new Set(e.surfaces.filter(s))].sort():[],scripts:t.scripts||[],needsBridge:g(e),meeting:!!e.meeting}}function v(e){const t=f(e);return t?t.id.length>48?`${t.source} · …${t.id.slice(-40)}`:`${t.source} · ${t.id}`:y(e)==="built-in"?"Built-in":"Written here"}function O(e,t){const r=f(e),i=f(t);return!!r&&!!i&&r.source===i.source&&r.id===i.id}function j(e,t){const r=f(e);return!r||!s(r.hash)||!s(t)?null:r.hash!==t}function P(e){if(!e||typeof e!="object")throw new o("SHAPE","skill must be an object");if(!s(e.id))throw new o("SHAPE","skill.id required");if(!s(e.name))throw new o("SHAPE",`skill '${e.id}': name required`);if(e.prompt!=null&&typeof e.prompt!="string")throw new o("SHAPE",`skill '${e.id}': prompt must be a string`);if(e.command!=null&&e.command!==""&&!h.test(String(e.command)))throw new o("SHAPE",`skill '${e.id}': command must match ${h}`);for(const[t,r]of[["context",S],["historyContext",l],["mcpMode",d]])if(e[t]!=null&&!r.includes(e[t]))throw new o("SHAPE",`skill '${e.id}': ${t} must be one of ${r}`);if(e.reads!=null&&(!Array.isArray(e.reads)||!e.reads.every(t=>a.includes(t))))throw new o("SHAPE",`skill '${e.id}': reads must be within ${a}`);for(const t of["sources","surfaces"])if(e[t]!=null&&(!Array.isArray(e[t])||!e[t].every(s)))throw new o("SHAPE",`skill '${e.id}': ${t} must be an array of ids`);if(e.origin!=null){const t=e.origin;if(typeof t!="object")throw new o("SHAPE",`skill '${e.id}': origin must be an object`);if(!s(t.source)||!s(t.id))throw new o("ORIGIN",`skill '${e.id}': origin needs both source and id`)}if(e.files!=null){if(typeof e.files!="object")throw new o("SHAPE",`skill '${e.id}': files must be an object`);for(const t of Object.keys(e.files)){if(!m.includes(t))throw new o("FILES",`skill '${e.id}': unknown file kind '${t}'`);const r=e.files[t];if(!Array.isArray(r)||!r.every(s))throw new o("FILES",`skill '${e.id}': files.${t} must be an array of paths`);const i=r.find(n=>!w(n));if(i)throw new o("PATH",`skill '${e.id}': unsafe path in files.${t}: ${JSON.stringify(i)}`)}}if(!f(e)&&(e.files?.scripts||[]).length)throw new o("ORIGIN",`skill '${e.id}': scripts require an origin to be scannable`);return e}const x=Object.freeze({1:e=>({...e,v:u})});function A(e){if(!e||typeof e!="object")throw new o("SHAPE","skill must be an object");let t=typeof e.v=="number"?e:{...e,v:1},r=0;for(;t.v<u;){const i=x[t.v];if(!i)throw new o("UPCAST",`no upcaster from v${t.v}`);if(t=i(t),++r>64)throw new o("UPCAST","upcaster chain did not terminate")}if(t.v>u)throw new o("UPCAST",`skill is v${t.v}; this reader only knows v${u}`);return t}function L(e){return(Array.isArray(e)?e:[]).map(A)}function M(e){if(!e||typeof e!="object")return e;const t={...A(e)};t.enabled=t.enabled!==!1;const r=String(t.mcpMode||"none").toLowerCase();t.mcpMode=d.includes(r)?r:"none";const i=Array.isArray(t.mcpServerIds)?t.mcpServerIds:[];t.mcpServerIds=t.mcpMode==="selected"?[...new Set(i.map(c=>String(c||"").trim()).filter(Boolean))]:[],delete t.trust;const n=f(t);n?(t.builtin=!1,t.origin={source:n.source,id:n.id,...s(n.url)?{url:n.url}:{},...s(n.hash)?{hash:n.hash}:{},...n.scanned&&typeof n.scanned=="object"?{scanned:{...n.scanned}}:{}}):t.origin!=null&&delete t.origin,t.reads!=null&&(t.reads=[...new Set((Array.isArray(t.reads)?t.reads:[]).filter(c=>a.includes(c)))].sort());for(const c of["sources","surfaces"])t[c]!=null&&(t[c]=[...new Set((Array.isArray(t[c])?t[c]:[]).filter(s))]);if(t.files!=null){const c=p(t);Object.keys(c).length?t.files=c:delete t.files}return t.version!=null&&!s(t.version)&&delete t.version,t}export{S as SKILL_CONTEXTS,m as SKILL_FILE_KINDS,l as SKILL_HISTORY_SCOPES,u as SKILL_MANIFEST_VERSION,d as SKILL_MCP_MODES,I as SKILL_TRUST,x as SKILL_UPCASTERS,o as SkillManifestError,E as declaredAccess,w as isSafeSkillPath,g as needsBridge,M as normalizeSkill,v as originLabel,f as originOf,O as sameSkillOrigin,p as skillFiles,j as skillIsStale,y as trustOf,A as upcastSkill,L as upcastSkills,P as validateSkill};
1
+ import{DATA_SCOPES as u}from"./scopes.js";import{normalizeGrant as S,parseHostList as g}from"./sandbox-grant.js";class n extends Error{constructor(t,r){super(r),this.name="SkillManifestError",this.code=t}}const d=2,h=Object.freeze(["auto","page","selection","tabs","none"]),l=Object.freeze(["none","chats","meetings","all"]),p=Object.freeze(["none","selected","default"]),v=Object.freeze(["built-in","user","community"]),y=Object.freeze(["references","scripts","assets","templates","examples"]),s=e=>typeof e=="string"&&e.length>0,b=/^[a-z0-9][a-z0-9_-]*$/;function w(e){return!(!s(e)||e.length>255||e!==e.trim()||e.includes("\\")||/[\u0000-\u001f\u007f]/.test(e)||e.startsWith("/")||/^[a-z]:/i.test(e)||e.split("/").some(r=>r===""||r==="."||r===".."))}function f(e){const t=e?.origin;return t&&typeof t=="object"&&s(t.source)&&s(t.id)?t:null}function A(e){return f(e)?"community":e?.builtin?"built-in":"user"}function m(e){const t=e?.files,r={};if(!t||typeof t!="object")return r;for(const o of y){const a=Array.isArray(t[o])?t[o].filter(w):[];a.length&&(r[o]=[...new Set(a)])}return r}function $(e){return(m(e).scripts||[]).length>0}function O(e={}){const t=m(e),r=p.includes(e.mcpMode)?e.mcpMode:"none",o=h.includes(e.context)?e.context:"auto",a=l.includes(e.historyContext)?e.historyContext:"none",i=new Set(Array.isArray(e.reads)?e.reads.filter(c=>u.includes(c)):[]);return o!=="none"&&i.add("page"),(a==="chats"||a==="all")&&i.add("chats"),(a==="meetings"||a==="all")&&i.add("meetings"),{trust:A(e),reads:[...i].sort(),page:o,history:a,mcp:r,mcpServerIds:r==="selected"&&Array.isArray(e.mcpServerIds)?[...e.mcpServerIds]:[],hosts:Array.isArray(e.sandboxHosts)?[...e.sandboxHosts].sort():[],sources:Array.isArray(e.sources)?[...new Set(e.sources.filter(s))].sort():[],surfaces:Array.isArray(e.surfaces)?[...new Set(e.surfaces.filter(s))].sort():[],scripts:t.scripts||[],needsBridge:$(e),meeting:!!e.meeting}}function P(e){const t=f(e);return t?t.id.length>48?`${t.source} · …${t.id.slice(-40)}`:`${t.source} · ${t.id}`:A(e)==="built-in"?"Built-in":"Written here"}function j(e,t){const r=f(e),o=f(t);return!!r&&!!o&&r.source===o.source&&r.id===o.id}function L(e,t){const r=f(e);return!r||!s(r.hash)||!s(t)?null:r.hash!==t}function M(e){if(!e||typeof e!="object")throw new n("SHAPE","skill must be an object");if(!s(e.id))throw new n("SHAPE","skill.id required");if(!s(e.name))throw new n("SHAPE",`skill '${e.id}': name required`);if(e.prompt!=null&&typeof e.prompt!="string")throw new n("SHAPE",`skill '${e.id}': prompt must be a string`);if(e.command!=null&&e.command!==""&&!b.test(String(e.command)))throw new n("SHAPE",`skill '${e.id}': command must match ${b}`);for(const[t,r]of[["context",h],["historyContext",l],["mcpMode",p]])if(e[t]!=null&&!r.includes(e[t]))throw new n("SHAPE",`skill '${e.id}': ${t} must be one of ${r}`);if(e.reads!=null&&(!Array.isArray(e.reads)||!e.reads.every(t=>u.includes(t))))throw new n("SHAPE",`skill '${e.id}': reads must be within ${u}`);for(const t of["sources","surfaces"])if(e[t]!=null&&(!Array.isArray(e[t])||!e[t].every(s)))throw new n("SHAPE",`skill '${e.id}': ${t} must be an array of ids`);if(e.sandboxHosts!=null)try{S({hosts:e.sandboxHosts})}catch(t){throw new n("SHAPE",`skill '${e.id}': sandboxHosts — ${t.message}`)}if(e.origin!=null){const t=e.origin;if(typeof t!="object")throw new n("SHAPE",`skill '${e.id}': origin must be an object`);if(!s(t.source)||!s(t.id))throw new n("ORIGIN",`skill '${e.id}': origin needs both source and id`)}if(e.files!=null){if(typeof e.files!="object")throw new n("SHAPE",`skill '${e.id}': files must be an object`);for(const t of Object.keys(e.files)){if(!y.includes(t))throw new n("FILES",`skill '${e.id}': unknown file kind '${t}'`);const r=e.files[t];if(!Array.isArray(r)||!r.every(s))throw new n("FILES",`skill '${e.id}': files.${t} must be an array of paths`);const o=r.find(a=>!w(a));if(o)throw new n("PATH",`skill '${e.id}': unsafe path in files.${t}: ${JSON.stringify(o)}`)}}if(!f(e)&&(e.files?.scripts||[]).length)throw new n("ORIGIN",`skill '${e.id}': scripts require an origin to be scannable`);return e}const E=Object.freeze({1:e=>({...e,v:d})});function x(e){if(!e||typeof e!="object")throw new n("SHAPE","skill must be an object");let t=typeof e.v=="number"?e:{...e,v:1},r=0;for(;t.v<d;){const o=E[t.v];if(!o)throw new n("UPCAST",`no upcaster from v${t.v}`);if(t=o(t),++r>64)throw new n("UPCAST","upcaster chain did not terminate")}if(t.v>d)throw new n("UPCAST",`skill is v${t.v}; this reader only knows v${d}`);return t}function C(e){return(Array.isArray(e)?e:[]).map(x)}function _(e){if(!e||typeof e!="object")return e;const t={...x(e)};t.enabled=t.enabled!==!1;const r=String(t.mcpMode||"none").toLowerCase();t.mcpMode=p.includes(r)?r:"none";const o=Array.isArray(t.mcpServerIds)?t.mcpServerIds:[];t.mcpServerIds=t.mcpMode==="selected"?[...new Set(o.map(c=>String(c||"").trim()).filter(Boolean))]:[];const a=Array.isArray(t.sandboxHosts)?t.sandboxHosts:g(t.sandboxHosts);t.sandboxHosts=a.filter(c=>{try{return S({hosts:[c]}),!0}catch{return!1}}),t.sandboxHosts.length||delete t.sandboxHosts,delete t.trust;const i=f(t);i?(t.builtin=!1,t.origin={source:i.source,id:i.id,...s(i.url)?{url:i.url}:{},...s(i.hash)?{hash:i.hash}:{},...i.scanned&&typeof i.scanned=="object"?{scanned:{...i.scanned}}:{}}):t.origin!=null&&delete t.origin,t.reads!=null&&(t.reads=[...new Set((Array.isArray(t.reads)?t.reads:[]).filter(c=>u.includes(c)))].sort());for(const c of["sources","surfaces"])t[c]!=null&&(t[c]=[...new Set((Array.isArray(t[c])?t[c]:[]).filter(s))]);if(t.files!=null){const c=m(t);Object.keys(c).length?t.files=c:delete t.files}return t.version!=null&&!s(t.version)&&delete t.version,t}export{h as SKILL_CONTEXTS,y as SKILL_FILE_KINDS,l as SKILL_HISTORY_SCOPES,d as SKILL_MANIFEST_VERSION,p as SKILL_MCP_MODES,v as SKILL_TRUST,E as SKILL_UPCASTERS,n as SkillManifestError,O as declaredAccess,w as isSafeSkillPath,$ as needsBridge,_ as normalizeSkill,P as originLabel,f as originOf,j as sameSkillOrigin,m as skillFiles,L as skillIsStale,A as trustOf,x as upcastSkill,C as upcastSkills,M as validateSkill};
package/src/mcp-local.js CHANGED
@@ -1,6 +1,6 @@
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,`
1
+ import{spawn as R}from"node:child_process";import F from"node:os";import _ from"node:path";import{resolveCommand as G,buildSpawnSpec as J}from"./env.js";import{sandbox as U,refusalsFor as q,track as H}from"./sandbox.js";import{missingCommandMessage as K}from"./events/mcp-errors.js";import{parseSignInPrompt as V,signInError as E,signInFromError as W}from"./events/mcp-signin.js";import{pickProbeTool as Q}from"./events/mcp-launcher.js";import{envLikeArgs as X}from"./events/mcp-config-import.js";const d=new Map,v=new Map,$=10*6e4,Y=6e4,Z=5*6e4,C=Object.freeze({protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"ChatPanel",version:"1.0"}}),nn=150,en=8*6e4,tn=16*6e4,S=4e3;function j(n){const e=F.homedir(),t={};for(const[r,s]of Object.entries(n||{})){const o=String(s);t[r]=o==="~"?e:o.startsWith("~/")?_.join(e,o.slice(2)):o}return t}const x=n=>n.key||`${n.command}\0${(Array.isArray(n.args)?n.args.join(" "):n.args)||""}`,O=n=>JSON.stringify([n.command,Array.isArray(n.args)?n.args:String(n.args||""),n.env||{},n.cwd||null,n.sandbox||null]);function y(n,e){clearTimeout(n.idleTimer);for(const{reject:t,timer:r}of n.pending.values())clearTimeout(r),t(e);n.pending.clear(),d.get(n.key)===n&&d.delete(n.key);try{n.child.kill()}catch{}}function f(n){clearTimeout(n.idleTimer);const e=n.pendingSignIn?Math.max($,tn):$;n.idleTimer=setTimeout(()=>{try{n.child.kill()}catch{}d.delete(n.key)},e)}function rn(n){const e=String(n||"").replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\r/g,`
2
2
  `).split(`
3
- `).map(i=>i.trimEnd()).filter(Boolean).join(`
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};
3
+ `).map(t=>t.trimEnd()).filter(Boolean).join(`
4
+ `).trim();return e?e.length>S?`…${e.slice(-S)}`:e:""}function M(n,e){const t=rn(e?.stderr);return t?`${n}: ${t}`:n}const T=new Map,z=new Set;function wn(){const n=[];for(const e of d.values())e.child.exitCode!=null||e.child.killed||n.push({id:e.key,command:_.basename(String(e.command||"")),pid:e.child.pid??null,sandbox:e.sandbox,commandId:e.commandId,since:e.startedAt,refused:q(e.commandId)});return n}async function L(n){const e=x(n),t=O(n);if(T.has(e)){const o=await T.get(e);if(o.sig===t)return o}const r=d.get(e);if(r&&r.child.exitCode==null&&!r.child.killed){if(r.sig===t)return f(r),r;y(r,new Error("local MCP server restarted: its configuration changed"))}const s=on(n,e,t).finally(()=>T.delete(e));return T.set(e,s),s}async function on(n,e,t=O(n)){const r=G(n.command);if(!r)throw new Error(K(n.command,{platform:process.platform}));const s=Array.isArray(n.args)?n.args:String(n.args||"").split(/\s+/).filter(Boolean),o={};for(const a of X(s)){const l=a.indexOf("=");o[a.slice(0,l).trim()]=a.slice(l+1).trim()}const[p,I,u]=J(r,s,n.cwd||null);u.env={...u.env||process.env,...j(o),...j(n.env||{})},Object.keys(o).length&&console.error(`[bridge] local MCP "${n.command}": ${Object.keys(o).join(", ")} looked like environment variables in Arguments, so they were applied as env too`),u.stdio=["pipe","pipe","pipe"];const c=await U().wrap(p,I,u,{engine:"mcp",cwd:n.cwd||null,commandId:`mcp:${String(e).slice(0,48)}`,...n.sandbox?{grant:n.sandbox}:{}}),[D,N,B]=[c.bin,c.argv,c.opts];c.record.layer==="none"&&!z.has(c.record.reason)&&(z.add(c.record.reason),console.error(`[bridge] local MCP "${n.command}" runs outside a sandbox — ${c.record.reason}`));const g=H(R(D,N,B),c,{kind:"mcp",label:e}),i={key:e,sig:t,child:g,command:n.command,sandbox:c.record,commandId:c.commandId,startedAt:Date.now(),pending:new Map,buf:"",stderr:"",idleTimer:null,initialized:!1,handshake:null,pendingSignIn:null,pendingSignInAt:0,signInIds:null},A=a=>y(i,a);return g.stdout.setEncoding("utf8"),g.stdout.on("data",a=>{i.buf+=a;let l;for(;(l=i.buf.indexOf(`
5
+ `))>=0;){const h=i.buf.slice(0,l).trim();if(i.buf=i.buf.slice(l+1),h[0]!=="{"&&h[0]!=="[")continue;let w;try{w=JSON.parse(h)}catch{continue}for(const m of Array.isArray(w)?w:[w]){m&&m.id!=null&&i.signInIds?.has(m.id)&&(i.signInIds.delete(m.id),i.signInIds.size||(i.pendingSignIn=null,i.signedInAt=Date.now(),f(i)));const k=m&&m.id!=null?i.pending.get(m.id):null;k&&(clearTimeout(k.timer),i.pending.delete(m.id),k.resolve(m))}}}),g.stderr.setEncoding("utf8"),g.stderr.on("data",a=>{i.stderr+=a,i.stderr.length>S*2&&(i.stderr=i.stderr.slice(-S*2)),i.pending.size&&(i.promptBuf=((i.promptBuf||"")+a).slice(-2e3),clearTimeout(i.promptTimer),i.promptTimer=setTimeout(()=>{const l=V(i.promptBuf);l&&(i.promptBuf="",sn(i,l))},nn))}),g.on("error",a=>A(new Error(M(`local MCP "${n.command}" failed to start: ${a.message}`,i)))),g.on("close",(a,l)=>{const h=l?`exited with signal ${l}`:a==null?"exited":`exited with code ${a}`;A(new Error(M(`local MCP "${n.command}" ${h}`,i)))}),d.set(e,i),f(i),i}function sn(n,e){if(f(n),e.code&&(n.pendingSignIn=e,n.pendingSignInAt=Date.now(),n.signInIds=new Set(n.pending.keys()),f(n)),e.browser){for(const r of n.pending.values())clearTimeout(r.timer),r.timer=setTimeout(()=>{r.reject(new Error(M("local MCP call timed out waiting for the sign-in",n)))},Z);return}const t=E(e);for(const[r,s]of n.pending)clearTimeout(s.timer),n.pending.delete(r),s.resolve({jsonrpc:"2.0",id:r,error:t})}function P(n,e){const t=()=>n.child.stdin.write(JSON.stringify(e)+`
6
+ `);return e.id==null?(t(),Promise.resolve(null)):new Promise((r,s)=>{const o=setTimeout(()=>{n.pending.delete(e.id),s(new Error(M("local MCP call timed out",n)))},Y);n.pending.set(e.id,{resolve:r,reject:s,timer:o}),t()})}function an(n,e){return n.initialized?Promise.resolve():(n.handshake||(n.handshake=(async()=>{const t=await P(n,{jsonrpc:"2.0",id:`cp-init-${Date.now()}`,method:"initialize",params:e});if(t?.error)throw new Error(`local MCP re-initialize failed: ${t.error.message||t.error.code}`);await P(n,{jsonrpc:"2.0",method:"notifications/initialized"}),n.initialized=!0})().finally(()=>{n.handshake=null})),n.handshake)}async function Sn(n,{initializeParams:e=C}={}){const t=await L(n);if(t.pendingSignIn)return{state:"prompt",signIn:t.pendingSignIn,since:t.pendingSignInAt};await b(n,{jsonrpc:"2.0",id:`cp-si-init-${Date.now()}`,method:"initialize",params:e}).catch(()=>{});const s=(await b(n,{jsonrpc:"2.0",id:`cp-si-list-${Date.now()}`,method:"tools/list",params:{}}).catch(()=>null))?.result?.tools||[],o=Q(s);if(!o)return{state:"unsupported",error:"This server declares no read-only tool that takes no arguments, so there is nothing safe to call to make it sign in."};const p=await b(n,{jsonrpc:"2.0",id:`cp-si-${Date.now()}`,method:"tools/call",params:{name:o,arguments:{}}}).catch(u=>({error:{message:String(u?.message||u)}})),I=W(p?.error);return I?{state:"prompt",signIn:I,since:d.get(x(n))?.pendingSignInAt||Date.now(),probe:o}:p?.error?{state:"failed",error:p.error.message||"the server refused",probe:o}:{state:"signed-in",probe:o}}function yn(n){const e=d.get(x(n));return!e||e.child.exitCode!=null?{state:"gone"}:e.pendingSignIn?{state:"prompt",signIn:e.pendingSignIn,since:e.pendingSignInAt}:{state:e.signedInAt?"signed-in":"idle"}}function ln(n){const e=d.get(n);return e?(y(e,new Error("local MCP server stopped")),!0):!1}function Mn(){let n=0;for(const e of[...d.keys()])ln(e)&&(n+=1);return n}function Tn(n){return d.get(n)||null}function bn(n){return v.has(n)}async function b(n,e){if(!n?.command)throw new Error("no command for local MCP server");const t=await L(n);if(f(t),e.method==="initialize")v.set(t.key,e.params||{}),t.initialized=!0;else if(e.method!=="notifications/initialized"){if(e.id!=null&&t.pendingSignIn&&Date.now()-t.pendingSignInAt<en)return{jsonrpc:"2.0",id:e.id,error:E(t.pendingSignIn)};if(e.id!=null&&t.pendingSignIn)return y(t,new Error("local MCP sign-in expired: starting a new one")),b(n,e);t.initialized||await an(t,v.get(t.key)||C)}return P(t,e)}export{Tn as _procForTest,b as callLocalMcp,bn as hasInitParams,wn as localMcpStatus,Sn as signInLocalMcp,yn as signInStatusLocalMcp,Mn as stopAllLocalMcp,ln as stopLocalMcp};
@@ -1 +1 @@
1
- import{stripHidden as I,confusablesSkeleton as Z}from"./sanitize.js";const y=/\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]/g,m=Object.freeze(["PERSON","ORG","LOCATION","ADDRESS","EMAIL","PHONE","ID","SSN","IBAN","CREDITCARD","CARD","POST","FAC","GROUP","NRP","ENTITY","KEY","SECRET","TERM","PII","OTHER"]);function $(e){const t=String(e??"").trim().replace(/^\[{1,2}|\]{1,2}$/g,""),n=/^([A-Z][A-Z0-9]*)_\d+$/.exec(t);return!!n&&m.includes(n[1])}const k=/\[{0,2}([A-Z][A-Z0-9]*_\d+)\]{0,2}/g;function b(){return{byToken:new Map,byValue:new Map,counts:new Map,aliases:new Map}}function v(e){return{entries:[...e?.byToken||new Map].map(([t,n])=>({token:t,value:n})),aliases:[...e?.aliases||new Map].map(([t,n])=>({alias:t,value:n}))}}function D(e){const t=b();for(const{token:n,value:r}of e?.entries||[]){const s=/^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(n);t.byToken.set(n,r),t.byValue.set(r,n),s&&t.counts.set(s[1],Math.max(t.counts.get(s[1])||0,Number(s[2])))}for(const{alias:n,value:r}of e?.aliases||[])t.aliases.set(n,r);return t}function h(e,t,n){const r=e.byValue.get(n);if(r)return r;const s=String(t||"PII").toUpperCase().replace(/[^A-Z0-9]/g,"")||"PII",l=(e.counts.get(s)||0)+1;e.counts.set(s,l);const c=`[[${s}_${l}]]`;return e.byToken.set(c,n),e.byValue.set(n,c),c}function x(e){return String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _(e){return!(typeof e!="string"||e.length===0||e.length>200||/\([^)]*[+*}][^)]*\)\s*[+*{]/.test(e)||/[+*]\s*[+*]/.test(e))}function O(e,t){if(!t||t.length===0)return e;let n="",r=0;const s=e.length;for(;r<=s;){let l=null,c=null;for(const a of t){a.re.lastIndex=r;const f=a.re.exec(e);if(f&&(l===null||f.index<l.index)&&(l=f,c=a,f.index===r))break}if(!l){n+=e.slice(r);break}n+=e.slice(r,l.index),l[0].length===0?(n+=e[l.index]??"",r=l.index+1):(n+=c.repl(l),r=l.index+l[0].length)}return n}function N(e){let t=0,n=!1;for(let r=e.length-1;r>=0;r--){let s=e.charCodeAt(r)-48;n&&(s*=2,s>9&&(s-=9)),t+=s,n=!n}return t%10===0}function P(e){if(!/^[0-9A-Fa-f:]+$/.test(e)||(e.match(/:/g)||[]).length<2)return!1;const t=e.split(":");return t.some(n=>n.length>4)?!1:e.includes("::")?t.filter(Boolean).length>=1&&t.filter(Boolean).length<=7:t.length===8&&t.every(n=>n.length>=1)}const z=[{type:"SECRET",re:/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----/g},{type:"EMAIL",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{type:"SSN",re:/\b\d{3}[-\s]\d{2}[-\s]\d{4}\b/g},{type:"KEY",re:/\b(?:sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[0-9A-Za-z_]{22,}|xox[baprs]-[A-Za-z0-9-]{10,}|xapp-[0-9]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{35}|[rs]k_(?:live|test)_[0-9A-Za-z]{16,})\b/g},{type:"KEY",re:/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{type:"IP",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{type:"IP",re:/(?<![:\w])(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}(?![:\w])/g,valid:e=>P(e)},{type:"PHONE",re:/(?<![\w.])\+?\d[\d ().-]{6,}\d(?![\w])/g,valid:e=>{const t=e.replace(/\D/g,"");return t.length>=7&&t.length<=15&&(/[ ().-]/.test(e)||e.trimStart().startsWith("+")||t.length===10)}},{type:"CARD",re:/\b(?:\d[ -]?){13,19}\b/g,valid:e=>{const t=e.replace(/\D/g,"");return t.length>=13&&t.length<=19&&N(t)}}];function E(e,t,{tier:n="basic",entities:r=[],dictionary:s=[],sanitize:l=!0,sanitizeOpts:c=void 0}={}){if(e==null||e==="")return e;let a=l?I(String(e),c):String(e);const f=t||b(),g=n==="full"||n==="entities",A=[];for(const o of s||[]){if(!o)continue;let i;try{i=o.pattern?_(o.pattern)?new RegExp(o.pattern,o.flags&&/g/.test(o.flags)?o.flags:`${o.flags||""}g`):null:o.value?new RegExp(`(?<![\\w])${x(o.value)}(?![\\w])`,"gi"):null}catch{i=null}if(i)if(o.alias!=null&&o.alias!=="")o.value&&f.aliases.set(o.alias,o.value),A.push({re:i,repl:()=>o.alias});else{const u=o.type||(o.pattern?"PII":"TERM");A.push({re:i,repl:p=>h(f,u,o.pattern?p[0]:o.value)})}}if(a=O(a,A),g){const o=[...r||[]].filter(i=>i&&i.value).sort((i,u)=>String(u.value).length-String(i.value).length);for(const i of o){const u=new RegExp(`(?<![\\w])${x(i.value)}(?![\\w])`,"gi");a=a.replace(u,()=>h(f,i.type||"PERSON",i.value))}}const R=Z(a),d=[],S=(o,i)=>d.some(u=>o<u.end&&i>u.start);for(const o of z){o.re.lastIndex=0;let i;for(;(i=o.re.exec(R))!==null;){if(i[0].length===0){o.re.lastIndex++;continue}const u=i.index,p=u+i[0].length;o.valid&&!o.valid(i[0])||S(u,p)||d.push({start:u,end:p,type:o.type})}}if(d.length){d.sort((u,p)=>u.start-p.start);let o="",i=0;for(const u of d)o+=a.slice(i,u.start)+h(f,u.type,a.slice(u.start,u.end)),i=u.end;a=o+a.slice(i)}return a}function T(e,t,n){if(e==null||typeof e=="string")return e==null?e:E(e,t,n);if(Array.isArray(e))return e.map(r=>T(r,t,n));if(typeof e=="object"){let r=e;return typeof e.text=="string"&&(r={...r,text:E(e.text,t,n)}),Array.isArray(e.content)&&(r={...r,content:e.content.map(s=>T(s,t,n))}),e.resource&&typeof e.resource=="object"&&typeof e.resource.text=="string"&&(r={...r,resource:{...e.resource,text:E(e.resource.text,t,n)}}),r}return e}function C(e,t){return e==null||!t?e:String(e).replace(k,(n,r)=>{const s=`[[${r}]]`;return t.byToken.has(s)?t.byToken.get(s):n})}function K(e,t){let n=C(e,t);if(t?.aliases?.size){const r=[...t.aliases.keys()].filter(Boolean).sort((s,l)=>l.length-s.length);if(r.length){const s=new RegExp(`(?<![\\w])(?:${r.map(x).join("|")})(?![\\w])`,"g");n=n.replace(s,l=>t.aliases.has(l)?t.aliases.get(l):l)}}return n}function w(e,t){const n=String(e??"");if(!n)return{text:n,unresolved:[]};const r=[],s=n.replace(y,l=>{const c=t?.byToken?.get(l);return c??(r.push(l),l)});return y.lastIndex=0,{text:s,unresolved:r}}function V(e){return y.lastIndex=0,y.test(String(e||""))}function Y(e,{includeValues:t=!1,maxPairs:n=200}={}){const r=new Map,s=[];for(const[c,a]of e?.byToken||new Map){const f=/^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(c),g=f?f[1]:"OTHER";r.set(g,(r.get(g)||0)+1),t&&s.length<n&&s.push({token:c,value:a,type:g})}const l=[...r.entries()].map(([c,a])=>({type:c,count:a})).sort((c,a)=>a.count-c.count||c.type.localeCompare(a.type));return{total:l.reduce((c,a)=>c+a.count,0),types:l,...t?{pairs:s}:{}}}function F(e){const t=new Map;for(const r of e||[])for(const s of r?.types||[])t.set(s.type,(t.get(s.type)||0)+s.count);const n=[...t.entries()].map(([r,s])=>({type:r,count:s})).sort((r,s)=>s.count-r.count||r.type.localeCompare(s.type));return{total:n.reduce((r,s)=>r+s.count,0),types:n}}export{m as REDACTION_TOKEN_TYPES,b as createVault,V as hasToken,$ as isRedactionToken,F as mergeRedactionSummaries,T as redactResultShape,E as redactText,Y as redactionSummary,C as restoreText,K as restoreWithAliases,w as scrubPlaceholders,D as vaultFromJSON,v as vaultToJSON};
1
+ import{stripHidden as I,confusablesSkeleton as Z}from"./sanitize.js";const A=/\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]/g,m=Object.freeze(["PERSON","ORG","LOCATION","ADDRESS","EMAIL","PHONE","ID","SSN","IBAN","CREDITCARD","CARD","POST","FAC","GROUP","NRP","ENTITY","KEY","SECRET","TERM","PII","OTHER"]);function K(e){const t=String(e??"").trim().replace(/^\[{1,2}|\]{1,2}$/g,""),n=/^([A-Z][A-Z0-9]*)_\d+$/.exec(t);return!!n&&m.includes(n[1])}const v=/\[{0,2}([A-Z][A-Z0-9]*_\d+)\]{0,2}/g,O=/^(?:[^\n()[\]]|\[\[[A-Z][A-Z0-9]*_\d+\]\])*\]\(/;function _(e,t,n,r){const s=t.startsWith("[[["),o=t.endsWith("]]]");if(!s&&!o)return r;const a=e.slice(n+t.length),l=s&&O.test(o?`]${a}`:a),f=o&&a.startsWith("(");return`${l?"[":""}${r}${f?"]":""}`}function x(){return{byToken:new Map,byValue:new Map,counts:new Map,aliases:new Map}}function L(e){return{entries:[...e?.byToken||new Map].map(([t,n])=>({token:t,value:n})),aliases:[...e?.aliases||new Map].map(([t,n])=>({alias:t,value:n}))}}function w(e){const t=x();for(const{token:n,value:r}of e?.entries||[]){const s=/^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(n);t.byToken.set(n,r),t.byValue.set(r,n),s&&t.counts.set(s[1],Math.max(t.counts.get(s[1])||0,Number(s[2])))}for(const{alias:n,value:r}of e?.aliases||[])t.aliases.set(n,r);return t}function h(e,t,n){const r=e.byValue.get(n);if(r)return r;const s=String(t||"PII").toUpperCase().replace(/[^A-Z0-9]/g,"")||"PII",o=(e.counts.get(s)||0)+1;e.counts.set(s,o);const a=`[[${s}_${o}]]`;return e.byToken.set(a,n),e.byValue.set(n,a),a}function E(e){return String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function k(e){return!(typeof e!="string"||e.length===0||e.length>200||/\([^)]*[+*}][^)]*\)\s*[+*{]/.test(e)||/[+*]\s*[+*]/.test(e))}function N(e,t){if(!t||t.length===0)return e;let n="",r=0;const s=e.length;for(;r<=s;){let o=null,a=null;for(const l of t){l.re.lastIndex=r;const f=l.re.exec(e);if(f&&(o===null||f.index<o.index)&&(o=f,a=l,f.index===r))break}if(!o){n+=e.slice(r);break}n+=e.slice(r,o.index),o[0].length===0?(n+=e[o.index]??"",r=o.index+1):(n+=a.repl(o),r=o.index+o[0].length)}return n}function P(e){let t=0,n=!1;for(let r=e.length-1;r>=0;r--){let s=e.charCodeAt(r)-48;n&&(s*=2,s>9&&(s-=9)),t+=s,n=!n}return t%10===0}function D(e){if(!/^[0-9A-Fa-f:]+$/.test(e)||(e.match(/:/g)||[]).length<2)return!1;const t=e.split(":");return t.some(n=>n.length>4)?!1:e.includes("::")?t.filter(Boolean).length>=1&&t.filter(Boolean).length<=7:t.length===8&&t.every(n=>n.length>=1)}const $=[{type:"SECRET",re:/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----/g},{type:"EMAIL",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{type:"SSN",re:/\b\d{3}[-\s]\d{2}[-\s]\d{4}\b/g},{type:"KEY",re:/\b(?:sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[0-9A-Za-z_]{22,}|xox[baprs]-[A-Za-z0-9-]{10,}|xapp-[0-9]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{35}|[rs]k_(?:live|test)_[0-9A-Za-z]{16,})\b/g},{type:"KEY",re:/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{type:"IP",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{type:"IP",re:/(?<![:\w])(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}(?![:\w])/g,valid:e=>D(e)},{type:"PHONE",re:/(?<![\w.])\+?\d[\d ().-]{6,}\d(?![\w])/g,valid:e=>{const t=e.replace(/\D/g,"");return t.length<7||t.length>15||/^(?:19|20)\d\d[-./](?:0[1-9]|1[0-2])[-./](?:0[1-9]|[12]\d|3[01])(?![\d])/.test(e.trimStart())?!1:/[ ().-]/.test(e)||e.trimStart().startsWith("+")||t.length===10}},{type:"CARD",re:/\b(?:\d[ -]?){13,19}\b/g,valid:e=>{const t=e.replace(/\D/g,"");return t.length>=13&&t.length<=19&&P(t)}}];function b(e,t,{tier:n="basic",entities:r=[],dictionary:s=[],sanitize:o=!0,sanitizeOpts:a=void 0}={}){if(e==null||e==="")return e;let l=o?I(String(e),a):String(e);const f=t||x(),g=n==="full"||n==="entities",y=[];for(const i of s||[]){if(!i)continue;let c;try{c=i.pattern?k(i.pattern)?new RegExp(i.pattern,i.flags&&/g/.test(i.flags)?i.flags:`${i.flags||""}g`):null:i.value?new RegExp(`(?<![\\w])${E(i.value)}(?![\\w])`,"gi"):null}catch{c=null}if(c)if(i.alias!=null&&i.alias!=="")i.value&&f.aliases.set(i.alias,i.value),y.push({re:c,repl:()=>i.alias});else{const u=i.type||(i.pattern?"PII":"TERM");y.push({re:c,repl:p=>h(f,u,p[0])})}}if(l=N(l,y),g){const i=[...r||[]].filter(c=>c&&c.value).sort((c,u)=>String(u.value).length-String(c.value).length);for(const c of i){const u=new RegExp(`(?<![\\w])${E(c.value)}(?![\\w])`,"gi");l=l.replace(u,p=>h(f,c.type||"PERSON",p))}}const R=Z(l),d=[],S=(i,c)=>d.some(u=>i<u.end&&c>u.start);for(const i of $){i.re.lastIndex=0;let c;for(;(c=i.re.exec(R))!==null;){if(c[0].length===0){i.re.lastIndex++;continue}const u=c.index,p=u+c[0].length;i.valid&&!i.valid(c[0])||S(u,p)||d.push({start:u,end:p,type:i.type})}}if(d.length){d.sort((u,p)=>u.start-p.start);let i="",c=0;for(const u of d)i+=l.slice(c,u.start)+h(f,u.type,l.slice(u.start,u.end)),c=u.end;l=i+l.slice(c)}return l}function T(e,t,n){if(e==null||typeof e=="string")return e==null?e:b(e,t,n);if(Array.isArray(e))return e.map(r=>T(r,t,n));if(typeof e=="object"){let r=e;return typeof e.text=="string"&&(r={...r,text:b(e.text,t,n)}),Array.isArray(e.content)&&(r={...r,content:e.content.map(s=>T(s,t,n))}),e.resource&&typeof e.resource=="object"&&typeof e.resource.text=="string"&&(r={...r,resource:{...e.resource,text:b(e.resource.text,t,n)}}),r}return e}function z(e,t){if(e==null||!t)return e;const n=String(e);return n.replace(/\[{0,3}([A-Z][A-Z0-9]*_\d+)\]{0,3}/g,(r,s,o)=>{const a=`[[${s}]]`;return t.byToken.has(a)?_(n,r,o,t.byToken.get(a)):r})}function H(e,t){let n=z(e,t);if(t?.aliases?.size){const r=[...t.aliases.keys()].filter(Boolean).sort((s,o)=>o.length-s.length);if(r.length){const s=new RegExp(`(?<![\\w])(?:${r.map(E).join("|")})(?![\\w])`,"g");n=n.replace(s,o=>t.aliases.has(o)?t.aliases.get(o):o)}}return n}const C=Object.freeze({PERSON:"someone",EMAIL:"an email address",PHONE:"a phone number",ADDRESS:"an address",ORG:"an organisation",URL:"a link",IP:"an IP address",CARD:"a card number",SSN:"an ID number",DATE:"a date",ID:"an identifier"});function V(e,t){const n=String(e??"");if(!n)return{text:n,unresolved:[]};const r=[],s=n.replace(A,(o,a)=>{const l=t?.byToken?.get(o);return l??(r.push(o),C[a]||"redacted")});return A.lastIndex=0,{text:s,unresolved:r}}function Y(e){return A.lastIndex=0,A.test(String(e||""))}function B(e,{includeValues:t=!1,maxPairs:n=200}={}){const r=new Map,s=[];for(const[a,l]of e?.byToken||new Map){const f=/^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(a),g=f?f[1]:"OTHER";r.set(g,(r.get(g)||0)+1),t&&s.length<n&&s.push({token:a,value:l,type:g})}const o=[...r.entries()].map(([a,l])=>({type:a,count:l})).sort((a,l)=>l.count-a.count||a.type.localeCompare(l.type));return{total:o.reduce((a,l)=>a+l.count,0),types:o,...t?{pairs:s}:{}}}function F(e){const t=new Map;for(const r of e||[])for(const s of r?.types||[])t.set(s.type,(t.get(s.type)||0)+s.count);const n=[...t.entries()].map(([r,s])=>({type:r,count:s})).sort((r,s)=>s.count-r.count||r.type.localeCompare(s.type));return{total:n.reduce((r,s)=>r+s.count,0),types:n}}export{m as REDACTION_TOKEN_TYPES,x as createVault,Y as hasToken,K as isRedactionToken,F as mergeRedactionSummaries,T as redactResultShape,b as redactText,B as redactionSummary,z as restoreText,H as restoreWithAliases,V as scrubPlaceholders,w as vaultFromJSON,L as vaultToJSON};
package/src/pii/trust.js CHANGED
@@ -1 +1 @@
1
- const f=Object.freeze(["icemacffhbgnfoofclgdbcdmnlkkklem","jkmmbleapaognlonbnllpaoeibmfkjmp"]),p=/^[a-p]{32}$/;function E(n){return String(n||"").split(/[\s,]+/).map(t=>t.trim().toLowerCase().replace(/^chrome-extension:\/\//,"").replace(/\/+$/,"")).filter(t=>p.test(t))}function d(n,{extensionIds:t=[]}={}){const o=String(n||"").trim();if(!o)return"none";const r=/^chrome-extension:\/\/([a-p]{32})\/?$/i.exec(o);if(r){const e=r[1].toLowerCase();return f.includes(e)||(t||[]).includes(e)?"pinned":"extension"}return/^(chrome|moz)-extension:\/\//i.test(o)?"extension":/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?\/?$/i.test(o)?"localhost":"web"}function I({origin:n,hasToken:t=!1,extensionIds:o=[]}={}){if(t)return"token";const r=d(n,{extensionIds:o});return r==="pinned"?"pinned":r==="extension"||r==="localhost"?"unpaired":r==="none"?"local":"web"}function x(n){return n==="token"||n==="pinned"}const a=Object.freeze({device:0,trusted:1,any:2});function g(n,t){const o=a[n]??0,r=a[t]??0,e=o<=r?n:t;return a[e]===void 0?"device":e}function m(n){return x(n)?null:"device"}const k=Object.freeze(["workingDir","workspace","grants","connectionId","permissionMode","extraArgs","env","runEnv","reach"]);function N(n,t){const o=m(t),r=n&&typeof n=="object"?n:{};if(!o)return{...r};const e={};for(const[c,s]of Object.entries(r))k.includes(c)||(e[c]=s);return e.reach=g(r.reach||o,o),e}const h=Object.freeze(["claude"]);function R(n,t){return!t||t==="any"?!0:h.includes(String(n||""))}const A=300*1e3,S=5;function b(n){const t=String(n||"").replace(/\D/g,"");return t.length===6?`${t.slice(0,3)}-${t.slice(3)}`:t}function _({now:n=()=>Date.now(),random:t=Math.random,ttlMs:o=A,maxAttempts:r=S}={}){let e=null;function c(){const i=String(Math.floor(t()*1e6)).padStart(6,"0");return e={code:i,expiresAt:n()+o,attempts:0},{code:i,display:b(i),expiresAt:e.expiresAt}}function s(i){if(!e)return{ok:!1,reason:"no pairing code is active — ask the server for one"};if(n()>e.expiresAt)return e=null,{ok:!1,reason:"pairing code expired — ask for a new one"};e.attempts+=1;const u=String(i||"").replace(/\D/g,"");return u.length===6&&u===e.code?(e=null,{ok:!0}):e.attempts>=r?(e=null,{ok:!1,reason:"too many wrong codes — ask for a new one"}):{ok:!1,reason:"wrong pairing code"}}function l(){return e&&n()>e.expiresAt&&(e=null),e?{expiresAt:e.expiresAt,attemptsLeft:r-e.attempts}:null}return{issue:c,claim:s,active:l}}export{f as CHATPANEL_EXTENSION_IDS,S as PAIRING_MAX_ATTEMPTS,A as PAIRING_TTL_MS,h as REACH_ENFORCING_ENGINES,I as callerTrust,N as capRunOptions,d as classifyOrigin,_ as createPairingStore,R as engineHonoursReach,b as formatPairingCode,x as isPaired,g as minReach,E as parseExtensionIds,m as reachCeiling};
1
+ const f=Object.freeze(["icemacffhbgnfoofclgdbcdmnlkkklem","jkmmbleapaognlonbnllpaoeibmfkjmp"]),p=/^[a-p]{32}$/;function E(n){return String(n||"").split(/[\s,]+/).map(t=>t.trim().toLowerCase().replace(/^chrome-extension:\/\//,"").replace(/\/+$/,"")).filter(t=>p.test(t))}function d(n,{extensionIds:t=[]}={}){const o=String(n||"").trim();if(!o)return"none";const r=/^chrome-extension:\/\/([a-p]{32})\/?$/i.exec(o);if(r){const e=r[1].toLowerCase();return f.includes(e)||(t||[]).includes(e)?"pinned":"extension"}return/^(chrome|moz)-extension:\/\//i.test(o)?"extension":/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?\/?$/i.test(o)?"localhost":"web"}function I({origin:n,hasToken:t=!1,extensionIds:o=[]}={}){if(t)return"token";const r=d(n,{extensionIds:o});return r==="pinned"?"pinned":r==="extension"||r==="localhost"?"unpaired":r==="none"?"local":"web"}function x(n){return n==="token"||n==="pinned"}const a=Object.freeze({device:0,trusted:1,any:2});function g(n,t){const o=a[n]??0,r=a[t]??0,e=o<=r?n:t;return a[e]===void 0?"device":e}function m(n){return x(n)?null:"device"}const k=Object.freeze(["workingDir","workspace","grants","connectionId","permissionMode","extraArgs","env","runEnv","reach","sandbox"]);function N(n,t){const o=m(t),r=n&&typeof n=="object"?n:{};if(!o)return{...r};const e={};for(const[c,s]of Object.entries(r))k.includes(c)||(e[c]=s);return e.reach=g(r.reach||o,o),e}const h=Object.freeze(["claude"]);function R(n,t){return!t||t==="any"?!0:h.includes(String(n||""))}const A=300*1e3,b=5;function S(n){const t=String(n||"").replace(/\D/g,"");return t.length===6?`${t.slice(0,3)}-${t.slice(3)}`:t}function _({now:n=()=>Date.now(),random:t=Math.random,ttlMs:o=A,maxAttempts:r=b}={}){let e=null;function c(){const i=String(Math.floor(t()*1e6)).padStart(6,"0");return e={code:i,expiresAt:n()+o,attempts:0},{code:i,display:S(i),expiresAt:e.expiresAt}}function s(i){if(!e)return{ok:!1,reason:"no pairing code is active — ask the server for one"};if(n()>e.expiresAt)return e=null,{ok:!1,reason:"pairing code expired — ask for a new one"};e.attempts+=1;const u=String(i||"").replace(/\D/g,"");return u.length===6&&u===e.code?(e=null,{ok:!0}):e.attempts>=r?(e=null,{ok:!1,reason:"too many wrong codes — ask for a new one"}):{ok:!1,reason:"wrong pairing code"}}function l(){return e&&n()>e.expiresAt&&(e=null),e?{expiresAt:e.expiresAt,attemptsLeft:r-e.attempts}:null}return{issue:c,claim:s,active:l}}export{f as CHATPANEL_EXTENSION_IDS,b as PAIRING_MAX_ATTEMPTS,A as PAIRING_TTL_MS,h as REACH_ENFORCING_ENGINES,I as callerTrust,N as capRunOptions,d as classifyOrigin,_ as createPairingStore,R as engineHonoursReach,S as formatPairingCode,x as isPaired,g as minReach,E as parseExtensionIds,m as reachCeiling};
@@ -0,0 +1 @@
1
+ import{readFileSync as d,unlinkSync as p}from"node:fs";import{spawn as l}from"node:child_process";import{createSandbox as h}from"./sandbox.js";const n=process.argv[2];n||(console.error("sandbox-host: a spec file is required"),process.exit(2));let o;try{o=JSON.parse(d(n,"utf8"))}catch(r){console.error(`sandbox-host: cannot read the spec: ${r.message}`),process.exit(2)}try{p(n)}catch{}const m=(r,t,i)=>{o.report?.url&&fetch(o.report.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:o.report.token,commandId:o.commandId,host:r,port:t,reason:i}),signal:AbortSignal.timeout(2e3)}).catch(()=>{})},a=h({config:o.config,loadSrt:()=>import(o.srt),compiled:!1,loopback:o.loopback||[],onRefusal:r=>m(r.host,r.port,r.reason),log:r=>console.error(`[sandbox-host] ${r}`)}),e=await a.wrap(o.bin,o.argv,{cwd:o.cwd||void 0,env:process.env},{engine:o.engine,cwd:o.workdir,grant:o.grant,commandId:o.commandId});e.record.layer==="none"&&console.error(`[sandbox-host] running outside the sandbox — ${e.record.reason}`);const s=l(e.bin,e.argv,{...e.opts,stdio:"inherit"}),c=r=>{try{s.kill(r)}catch{}};process.on("SIGTERM",()=>c("SIGTERM")),process.on("SIGINT",()=>c("SIGINT")),process.on("SIGHUP",()=>c("SIGHUP")),s.on("error",r=>{console.error(`[sandbox-host] could not start ${o.bin}: ${r.message}`),process.exit(127)}),s.on("exit",async(r,t)=>{try{a.close()}catch{}try{await(await import(o.srt)).SandboxManager.reset()}catch{}if(t)try{process.kill(process.pid,t)}catch{}process.exit(r??1)});
package/src/sandbox.js CHANGED
@@ -1 +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};
1
+ import{spawn as $t,spawnSync as kt}from"node:child_process";import{writeFileSync as lt,mkdirSync as pt,existsSync as Mt}from"node:fs";import{createHash as Bt,randomBytes as wt}from"node:crypto";import{AsyncLocalStorage as jt}from"node:async_hooks";import{fileURLToPath as ht}from"node:url";import F from"node:os";import C from"node:path";import{ensureCaBundle as Ft}from"./ca-bundle.js";import{kitFor as It,toSrtSettings as ft,sandboxRecord as xt,shellJoin as bt,sandboxEnvOverlay as Z,normalizeGrant as mt,windowsGrantsFor as Xt,windowsSandboxEnv as Ut,withSrtWinEnv as Gt,NETWORK_MODES as Vt,ENGINE_KITS as zt,DEVELOPER_HOSTS as Jt,SECRET_PATHS as Kt,COMMON_WRITE as Yt}from"./events/sandbox-policy.js";const St=new jt;function ye(t,e){let r;try{r=mt(t)}catch{r=null}return St.run(r,e)}function qt(){return St.getStore()||null}const Qt=/deny network-outbound\s+(\S+?):(\d+)\s*(?:\((.*)\))?/;function Zt(t){const e=Qt.exec(String(t||""));return e?{host:e[1].toLowerCase(),port:Number(e[2])||0,reason:e[3]||""}:null}const U=new Map,I=[],G=new Map,tt=new Set,te=50;function gt({commandId:t,host:e,port:r=0,reason:c="",at:w=Date.now()}){if(!t||!e)return;let d=U.get(t);for(d||(d=new Map,U.set(t,d)),d.set(e,{at:w,reason:c,port:r}),I.push({id:t,engine:G.get(t)||String(t).split(":")[0],host:e,at:w});I.length>te;)I.shift()}function ee(t){const e=U.get(t);return e?[...e.entries()].sort((r,c)=>c[1].at-r[1].at).map(([r])=>r):[]}function ne(t=20){return I.slice(-t).reverse()}function ve(){U.clear(),I.length=0,G.clear(),tt.clear()}const yt=new Map;function Ae(t={}){const e=yt.get(String(t?.token||""));return!e||e!==t.commandId?!1:(gt({commandId:e,host:String(t.host||"").toLowerCase().slice(0,253),port:Number(t.port)||0,reason:String(t.reason||"").slice(0,200)}),!0)}let se=0;const re=t=>`${t}:${(++se).toString(36)}${Date.now().toString(36).slice(-4)}`,V=new Map;function oe(t,e,{kind:r="agent",label:c=""}={}){if(!t||!e)return t;try{t.sandbox=e.record}catch{}if(typeof t.on!="function")return t;const w=e.commandId||"";V.set(t,{id:w,kind:r,engine:G.get(w)||String(w).split(":")[0]||"custom",command:e.label||"",label:c,pid:t.pid??null,since:Date.now(),sandbox:e.record});const d=()=>V.delete(t);return t.once("exit",d),t.once("error",d),t}function We(){return[...V.values()].map(t=>({...t,refused:ee(t.id)}))}function Ee(){V.clear()}function vt(t){if(t)return"";try{return ht(new URL("./sandbox-host.js",import.meta.url))}catch{return""}}function ae(t=process.env.CHATPANEL_SRT_MODULE){if(!t)return"";try{const e=t.startsWith("file:")?ht(new URL("./cli.js",t)):C.join(C.dirname(t),"cli.js");return Mt(e)?e:""}catch{return""}}const At="open",et="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)",ie=()=>[Number(process.env.CHATPANEL_GATEWAY_PORT)||4320,Number(process.env.CHATPANEL_BRIDGE_PORT)||Number(process.env.PORT)||4319],nt=t=>String(t||"").split(",").map(e=>e.trim()).filter(Boolean);function ce(t=process.env){const e=String(t.CHATPANEL_SANDBOX||At).toLowerCase(),r=e!=="off"&&e!=="0"&&e!=="false",c=Vt.includes(e)?e:At;return{enabled:r,mode:c,extraHosts:nt(t.CHATPANEL_SANDBOX_ALLOW_HOSTS),extraWrite:nt(t.CHATPANEL_SANDBOX_ALLOW_WRITE),extraDenyRead:nt(t.CHATPANEL_SANDBOX_DENY_READ),windows:t.CHATPANEL_SANDBOX_WINDOWS==="1"}}const Wt=new Set;function Et(t,e=C.join(F.tmpdir(),"chatpanel-srt")){const r=JSON.stringify(t),c=C.join(e,`${Bt("sha256").update(r).digest("hex").slice(0,16)}.json`);return Wt.has(c)||(pt(e,{recursive:!0,mode:448}),lt(c,r,{mode:384}),Wt.add(c)),c}function de(){try{const t=kt(process.platform==="win32"?"where":"which",["srt"],{encoding:"utf8",timeout:3e3});return t.status===0&&String(t.stdout||"").trim().length>0}catch{return!1}}function ue({config:t=ce(),loadSrt:e=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:r=de,cliEntry:c=ae(),onRefusal:w=p=>gt(p),reportUrl:d=process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT?`http://127.0.0.1:${process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT}/sandbox/refused`:"http://127.0.0.1:4319/sandbox/refused",hostEntry:_=null,compiled:h=!1,platform:a=process.platform,home:v=F.homedir(),loopback:J=ie(),selfFiles:Ot=[process.execPath,process.argv[1]||""],onExit:Tt=p=>process.on("exit",p),log:H=()=>{}}={}){let p=null,x=null,u=null,K=null,$=null,O=null,P=null;const k=new Set;let ot=!1;const Nt="Windows: the sandbox runs a process as a separate account, and mapping your sign-in, the CLI and its environment into it is built but not yet proved on a signed-in machine — CHATPANEL_SANDBOX_WINDOWS=1 turns it on (docs/sandboxing.md S1)",Lt="Windows: the sandbox account needs the runtime the gateway carries (the `srt` CLI cannot map your sign-in into it) — run the bridge through chatpanel-gateway";async function Rt(){if(!t.windows){x=Nt;return}if(h){x=Lt;return}try{u=await e()}catch(s){x=`sandbox-runtime is not installed — it ships with the gateway (${s.message})`;return}if(!u?.SandboxManager?.wrapWithSandboxArgv||typeof u.grantWindowsAcl!="function"||typeof u.getWindowsSandboxUserStatusAsync!="function"){x="Windows: this sandbox-runtime is older than 0.0.77, which the account mapping needs";return}try{O=u.resolveSrtWin({path:u.VENDORED_SRT_WIN_EXE})}catch(s){x=`Windows: srt-win.exe is not beside sandbox-runtime (${s.message})`;return}let n;try{n=await u.getWindowsSandboxUserStatusAsync({srtWin:O})}catch(s){P=!1,x=`Windows: srt-win could not be asked whether the sandbox account exists (${s.message}) — ${et}`;return}if(P=!!(n?.provisioned&&n.sid),!P){x=`Windows: the sandbox account is not installed — ${et}`;return}$=n.sid,p="srt-lib"}async function at(){if(!(p||x)){if(!t.enabled){x="sandboxing is off (CHATPANEL_SANDBOX=off)";return}if(a==="win32")return Rt();if(!h)try{if(u=await e(),u?.SandboxManager?.wrapWithSandboxArgv){p="srt-lib";return}}catch(n){H(`sandbox: library not available (${n.message})`)}if(r()){p="srt-cli";return}x=h?"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"}}let it=!1;function Y(){return c&&!h?{bin:process.execPath,argv:[c]}:p==="srt-cli"||r()?{bin:"srt",argv:[]}:null}function Dt(){const n=Array.isArray(t.exactHosts)?t.exactHosts:t.mode==="open"?["*"]:t.mode==="none"?[]:[...new Set([...Object.values(zt).flatMap(l=>l.hosts),...Jt,...t.extraHosts])],s={id:`session:${t.mode}`,network:{mode:t.mode,allowedDomains:n},filesystem:{allowWrite:[F.tmpdir(),...Yt,...t.extraWrite],denyRead:[...Kt,...t.extraDenyRead]}},o=ft(s,{loopback:J,home:a==="linux"?v:"",platform:a});return O?{...o,windows:{srtWin:{path:O.exe}}}:o}async function ct(){return K||(K=u.SandboxManager.initialize(Dt()).then(()=>{try{u.SandboxManager.getSandboxViolationStore?.()?.subscribe?.(n=>{for(const s of n||[]){const o=Zt(s?.line);if(!o||!s?.encodedCommand)continue;let l="";try{l=Buffer.from(s.encodedCommand,"base64").toString("utf8")}catch{continue}const m=`${l}|${o.host}|${s.timestamp instanceof Date?s.timestamp.getTime():String(s.timestamp)}`;tt.has(m)||(tt.add(m),w({commandId:l,...o,at:s.timestamp instanceof Date?s.timestamp.getTime():Date.now()}))}})}catch(n){H(`sandbox: violations not subscribed (${n.message})`)}})),K}function Ct(n){const s=C.join(F.tmpdir(),"chatpanel-srt");pt(s,{recursive:!0,mode:448});const o=C.join(s,`host-${wt(8).toString("hex")}.json`);return lt(o,JSON.stringify(n),{mode:384}),o}function Pt(n,s){const o=(i,T)=>u.expandWindowsFsPaths(i,{mode:T}).filter(g=>!k.has(`${T}:${g.toLowerCase()}`)),l=o(n,"grant"),m=o(s,"grant");if(!(!l.length&&!m.length)){u.grantWindowsAcl({sandboxUserSid:$,read:l,write:m,srtWin:O});for(const i of l)k.add(`grant:${i.toLowerCase()}`);for(const i of m)k.add(`grant:${i.toLowerCase()}`);ot||(ot=!0,Tt(()=>{try{u.revokeWindowsAcl({sandboxUserSid:$,srtWin:O})}catch{}}))}}async function Ht(n,s,o,{engine:l,workdir:m,kit:i,settings:T,commandId:g,record:A,caBundle:M=""}){await ct();const B=b=>typeof b=="string"&&/^[a-z]:\\/i.test(b),{read:W,write:y}=Xt({kit:i,files:[n,...B(s[0])?[s[0]]:[],...Ot].filter(Boolean),home:v});Pt(W,y);const N=bt(n,s,{platform:"win32"}),L=await u.SandboxManager.wrapWithSandboxArgv(N,void 0,{filesystem:{denyRead:T.filesystem.denyRead,denyWrite:T.filesystem.denyWrite}},void 0,m,{commandId:g,commandText:N}),R=o?.env||process.env,D={...Ut({engine:l,home:v,env:R,base:process.env}),...Z({},{platform:a,caBundle:M})},E=Gt(L.argv,D),j={};for(const[b,f]of Object.entries(L.env||{}))process.env[b]!==f&&(j[b]=f);return{bin:E[0],argv:E.slice(1),opts:{...o,env:{...R,...j},shell:!1},record:A,commandId:g}}return{config:t,async status(){return await at(),{enabled:t.enabled,mode:t.mode,runtime:p,platform:a,...x?{reason:x}:{},extras:{hosts:t.extraHosts,write:t.extraWrite,denyRead:t.extraDenyRead},ownSessions:!!(p&&(p==="srt-lib"&&(_??vt(h))||a!=="win32"&&Y())),refused:ne(),...a==="win32"&&P!==null?{provisioned:P,...P?{}:{install:et}}:{}}},close(){if(!(!$||!k.size)){try{u.revokeWindowsAcl({sandboxUserSid:$,srtWin:O})}catch(n){H(`sandbox: could not release the Windows grants: ${n.message}`)}k.clear()}},async wrap(n,s,o,{engine:l="custom",cwd:m=null,commandId:i=null,grant:T=qt()}={}){await at(),i=i||re(l),G.set(i,l);const g=m||o?.cwd||process.cwd(),A=C.basename(String(n||"")),M=f=>({bin:n,argv:s,opts:o,record:xt({layer:"none",reason:f}),commandId:i,label:A});if(!p)return M(x);const B=await Ft().catch(()=>"");let W,y;try{y=mt(T),W=It({engine:l,cwd:g,mode:t.mode,extraHosts:t.extraHosts,extraWrite:[F.tmpdir(),...t.extraWrite],extraDenyRead:t.extraDenyRead,grant:y})}catch(f){return M(`kit: ${f.message}`)}const N=ft(W,{loopback:J,home:a==="linux"?v:"",platform:a}),L=bt(n,s),R=t.mode==="allowlist"&&y.hosts.length>0&&!Array.isArray(t.exactHosts),D=R&&p==="srt-lib"?_??vt(h):"",E=R&&!D&&a!=="win32"?Y():null,j=!!(D||E),b=xt({layer:"process",runtime:D?"srt-host":E?"srt-cli":p,kitId:W.id,mode:W.network.mode,hosts:j||!R?y.hosts:[]});R&&!j&&(b.hostsDropped=y.hosts,it||(it=!0,H(`sandbox: hosts granted to ${l} (${y.hosts.join(", ")}) need a session of their own — no sandbox host or srt CLI here, so the process runs with the shared allow list`)));try{if(D){const S=wt(16).toString("hex");yt.set(S,i);const q={bin:n,argv:s,cwd:o?.cwd||null,engine:l,workdir:g,grant:y,commandId:i,config:{enabled:!0,mode:t.mode,extraHosts:[],extraWrite:t.extraWrite,extraDenyRead:t.extraDenyRead,windows:t.windows,exactHosts:W.network.allowedDomains},loopback:J,srt:process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime",report:d?{url:d,token:S}:null},X={...o?.env||process.env};return{bin:process.execPath,argv:[D,Ct(q)],opts:{...o,env:X,shell:!1},record:b,commandId:i,label:A}}if(E){const S={...o?.env||process.env};return Object.assign(S,Z(S,{platform:a,caBundle:B})),{bin:E.bin,argv:[...E.argv,"-s",Et(N),"-c",L],opts:{...o,env:S,shell:!1},record:b,commandId:i,label:A}}if(p==="srt-lib"&&a==="win32")return{...await Ht(n,s,o,{engine:l,workdir:g,kit:W,settings:N,commandId:i,record:b,caBundle:B}),label:A};if(p==="srt-lib"){await ct();const S=await u.SandboxManager.wrapWithSandboxArgv(L,void 0,{filesystem:N.filesystem},void 0,g,{commandId:i,commandText:L}),q=o?.env||process.env,X={};for(const[dt,ut]of Object.entries(S.env||{}))process.env[dt]!==ut&&(X[dt]=ut);const Q={...q,...X};return Object.assign(Q,Z(Q,{platform:a,caBundle:B})),{bin:S.argv[0],argv:S.argv.slice(1),opts:{...o,env:Q,shell:!1},record:b,commandId:i,label:A}}const f=Y();return{bin:f.bin,argv:[...f.argv,"-s",Et(N),"-c",L],opts:{...o,shell:!1},record:b,commandId:i,label:A}}catch(f){return H(`sandbox: could not wrap ${n}: ${f.message}`),M(f?.code==="SHAPE"?`the sandbox policy refused this run: ${f.message}`:`sandbox-runtime failed to wrap the command: ${f.message}`)}},violations(n){try{return u?.SandboxManager?.getSandboxViolationStore?.()?.getViolationsForCommand?.(n)||[]}catch{return[]}}}}let z=null;function _t(){if(!z){const{isCompiledBinary:t}=le();z=ue({compiled:t(),log:e=>console.error(`[bridge] ${e}`)})}return z}function _e(t){z=t}let st=null;function le(){return st||(st={isCompiledBinary:()=>{const t=(process.execPath||"").split(/[\\/]/).pop().toLowerCase();return!(t.startsWith("node")||t.startsWith("bun"))}}),st}const rt=new Set;function Oe(t,e){if(!e||e.layer!=="none"||typeof t!="function")return;const r=e.reason||"unknown";rt.has(r)||(rt.add(r),t({type:"status",text:`Running outside a sandbox — ${r}`}))}function Te(){rt.clear()}async function Ne(t,e,r,c={},{spawnImpl:w=$t,box:d=_t(),kind:_="agent",label:h=""}={}){const a=await d.wrap(t,e,r,c);return oe(w(a.bin,a.argv,a.opts),a,{kind:_,label:h})}async function Le(t,{box:e=_t(),platform:r=process.platform,loadSrt:c=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),out:w=console.log,err:d=console.error}={}){const _=t[0]||"status";if(_==="status")return w(JSON.stringify(await e.status(),null,2)),0;if(_!=="install")return d("usage: chatpanel-bridge sandbox [status|install]"),2;if(r!=="win32")return w("Nothing to install here: on macOS and Linux the sandbox runs as you. Only Windows has the one-time account setup."),0;let h;try{h=await c()}catch(a){return d(`sandbox-runtime is not installed — it ships with the gateway, so run \`chatpanel-gateway sandbox install\` (${a.message})`),1}try{const a=h.resolveSrtWin({path:h.VENDORED_SRT_WIN_EXE}),v=await h.installWindowsSandboxAsync({srtWin:a});return v?.cancelled?(d("Cancelled at the administrator prompt — nothing was installed."),1):(w(`The sandbox account is installed${v?.user?.sid?` (${v.user.sid})`:""}. Start the bridge with CHATPANEL_SANDBOX_WINDOWS=1; /health.sandbox says what the next run gets.`),0)}catch(a){d(`install failed: ${a.message}`);try{d(h.windowsInstallInstructions())}catch{}return 1}}export{Ee as _resetLiveForTest,Te as _resetNotedForTest,ve as _resetRefusalsForTest,_e as _setSandboxForTest,Ae as acceptRefusalReport,ue as createSandbox,qt as currentGrant,We as liveProcesses,Oe as noteSandbox,Zt as parseRefusalLine,ne as recentRefusals,gt as recordRefusal,ee as refusalsFor,Le as runSandboxCli,_t as sandbox,ce as sandboxConfigFromEnv,Ne as sandboxedSpawn,oe as track,ye as withGrant};
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{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)}
2
+ import{createServer as we}from"node:http";import A from"node:os";import{randomBytes as ye,randomInt as be,timingSafeEqual as Se}from"node:crypto";import{mkdirSync as ke,writeFileSync as Te,readFileSync as z,existsSync as ve}from"node:fs";import{join as _}from"node:path";import*as Ce from"./engines/claude.js";import*as Ee from"./engines/codex.js";import*as Oe from"./engines/antigravity.js";import{pi as xe,opencode as Ae,kiro as Pe,copilot as $e,deepseek as Ie,hermes as Ne}from"./engines/cli-agents.js";import{connectorsFor as Re}from"./connectors.js";import*as _e from"./engines/custom.js";import{installService as He,uninstallService as Me,serviceStatus as Be,restartService as K}from"./service.js";import{skillIndex as W,listRecords as Ge,readRecord as De,readPackageFile as Ue,skillsHealth as We,quarantinedSkills as Le}from"./skills.js";import{capabilityToolSpecs as je,runCapabilityTool as Je}from"./mcp-capabilities.js";import{createSession as Fe,deleteSession as V,getSession as Y,activeSession as Xe,relayToolCall as ze}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ke,isDefaultWorkdir as Ve,resolveWorkdir as Ye,writeScopeNote as Qe}from"./workdir.js";import{sandbox as Q,runSandboxCli as Ze,withGrant as Z,acceptRefusalReport as qe,liveProcesses as et}from"./sandbox.js";import{gitState as tt,gitDelta as nt}from"./scm.js";import{listConnections as ot,putConnection as rt,removeConnection as at,runEnvFor as it,testConnection as st,secretBackend as q}from"./connections.js";import{worktreeFor as ee,listWorktrees as ct,removeWorktree as lt,withHook as dt,WORKTREE_ROOT as te}from"./worktree.js";import{AGENT_CLIS as ut,enrichPath as ht,enrichAgentEnv as pt,findAgentBin as ne,resolveCommand as mt}from"./env.js";import"./sanitize.js";import{checkForUpdate as ft,selfUpdate as oe,isEmbedded as gt}from"./update.js";import{callLocalMcp as wt,localMcpStatus as yt,signInLocalMcp as bt,signInStatusLocalMcp as St}from"./mcp-local.js";import{assertPublicHttpUrl as re,assertPublicWebUrl as ae}from"./ssrf.js";import{startRun as ie,endRun as L,cancelRun as kt,cancelAll as Tt}from"./runs.js";import{closeWarmPools as vt,warmStatus as Ct}from"./warm.js";import{CompatError as P,anthropicError as j,anthropicStream as Et,chatCompletionStream as Ot,completionStream as xt,createAnthropicMessage as At,createChatCompletion as Pt,createCompletion as $t,createResponse as It,openAIError as b,parseAnthropicMessage as Nt,parseChatCompletion as Rt,parseCompletion as _t,parseResponse as Ht,responseStream as Mt}from"./api-compat.js";import{callerTrust as Bt,isPaired as $,parseExtensionIds as Gt,capRunOptions as Dt,engineHonoursReach as Ut,createPairingStore as Wt,formatPairingCode as Lt}from"./pii/trust.js";const w="0.19.0",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Ce,label:"Claude Code"},codex:{engine:Ee,label:"Codex"},antigravity:{engine:Oe,label:"Antigravity",tools:!1},pi:{engine:xe,label:"Pi"},opencode:{engine:Ae,label:"OpenCode"},hermes:{engine:Ne,label:"Hermes"},kiro:{engine:Pe,label:"Kiro"},copilot:{engine:$e,label:"GitHub Copilot"},deepseek:{engine:Ie,label:"DeepSeek Harness"},custom:{engine:_e,label:"Custom",hidden:!0}};function se(t){return!t||t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}const jt=Gt(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function I(t){return t.chatpanelTrust||(t.chatpanelTrust=Bt({origin:t.headers.origin||"",hasToken:ue(t),extensionIds:jt})),t.chatpanelTrust}function Jt(t){return t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}function Ft(t,e){const n=t.headers.origin||"",r=se(n);e.setHeader("Access-Control-Allow-Origin",r?n||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function Xt(t){if(!J.has(k))return!0;const e=String(t.headers.host||"");if(!e)return!1;const n=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(n)}const N=_(A.homedir(),".chatpanel","bridge-token");let S="";function zt(){try{ve(N)&&(S=z(N,"utf8").trim()),S||(S=ye(32).toString("hex"),ke(_(A.homedir(),".chatpanel"),{recursive:!0}),Te(N,S,{mode:384}))}catch(t){u("error",`could not initialise bridge token: ${t?.message||t}`)}}const ce=Wt({random:()=>be(0,1e6)/1e6});function Kt(t){if(!S)return i(t,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ce.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(t,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Vt(t,e){let n;try{n=await f(t)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=ce.claim(n?.code);return r.ok?(u("info",`paired a ${I(t)} client${t.headers.origin?` (${t.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${I(t)} caller`),i(e,403,{error:r.reason}))}function Yt(t,e){const n=I(t);return i(e,200,{ok:!0,trust:n,paired:$(n),version:w})}let H=null;async function le(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:_(A.homedir(),".chatpanel"),dataDir:_(A.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function de(t,e,n){try{const r=await le(),o=t.method==="POST"?await f(t):{};if(n==="status")return i(e,200,await r.status());if(n==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return n==="pair"?i(e,200,await r.pair()):n==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):n==="settings"?i(e,200,await r.update(o)):n==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function ue(t){if(!S)return!1;const e=String(t.headers.authorization||""),n=(e.startsWith("Bearer ")?e.slice(7):String(t.headers["x-api-key"]||t.headers["x-chatpanel-token"]||"")).trim();if(!n)return!1;const r=Buffer.from(n),o=Buffer.from(S);return r.length===o.length&&Se(r,o)}const Qt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),Zt=new Set(["/debug"]),qt=t=>Zt.has(t);function en(t,e){if(!Xt(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!se(n))return"forbidden origin";const r=t.method==="POST"&&Qt.has(e)||t.method==="GET"&&qt(e);return r&&!(Jt(n)||ue(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!$(I(t))&&!nn.has(e)?tn:null}const tn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",nn=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(t,e,n){const r=I(t),o=Dt(n,r);if(!Ut(e,o.reach))return{error:`${$(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${$(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=o.reach,s=$(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:o,note:s}}function i(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function f(t){return new Promise((e,n)=>{let r="";t.on("data",o=>{r+=o,r.length>50*1024*1024&&n(new Error("Body too large"))}),t.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){n(o)}}),t.on("error",n)})}async function on(t){const e=await Promise.all(Object.entries(C).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:d,tools:c}])=>{const l=await s.available().catch(g=>({ok:!1,reason:String(g?.message||g)})),h=await Re(a).catch(()=>[]);return{id:a,label:d,available:l.ok,reason:l.reason,connectors:h,...c===!1?{tools:!1}:{}}})),n=gt()?{current:w,updateAvailable:!1,embedded:"gateway"}:await ft(w).catch(()=>({current:w,updateAvailable:!1})),r=await We().catch(()=>null),o=await Q().status().catch(a=>({enabled:!1,reason:a.message}));i(t,200,{ok:!0,version:w,agents:e,update:n,workspace:Ke,sandbox:o,localMcp:yt(),processes:et(),worktrees:te,secretBackend:q(),warm:Ct(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function rn(t,e,n){const{index:r,problems:o}=await W({extraDirs:e,workdir:n});i(t,200,{ok:!0,skills:Ge(r),problems:o})}async function an(t,e,n){i(t,200,{ok:!0,quarantined:await Le(e,n)})}async function sn(t,e,n,r){const{index:o}=await W({extraDirs:n,workdir:r}),a=De(o,e);if(!a)return i(t,404,{ok:!1,error:"unknown skill"});i(t,200,{ok:!0,skill:a})}async function cn(t,e,n,r,o){const{index:a}=await W({extraDirs:r,workdir:o}),s=await Ue(a,e,n);if(s.error)return i(t,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(t,200,{ok:!0,...s})}async function ln(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,n])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await n.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...n})=>n)}async function he(t,e=""){const n=await ln();if(e){const r=n.find(o=>o.id===e);return r?i(t,200,r):i(t,404,b(new P(`Model "${e}" not found`,404,"model")))}return i(t,200,{object:"list",data:n})}async function dn(t){try{const e=await oe(w);i(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>K(),400))}catch(e){i(t,400,{ok:!1,error:String(e?.message||e)})}}async function un(t,e){let n;try{n=await f(t)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const r=C[n.agent];if(!r)return i(e,404,{error:`Unknown agent "${n.agent}"`});const o=F(t,n.agent,n.options||{});if(o.error)return i(e,403,{error:o.error});n.options=o.options,Array.isArray(n.images)&&n.images.length&&u("info",`chat: ${n.agent} received ${n.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 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)}
4
+ `)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=ie(d),l={signal:c.signal,abort:()=>c.cancel("client")},h=()=>{s=!0,c.cancel("disconnected")};t.on("close",h),e.on("close",h),e.on("error",h);const g=p=>{s||a(p)};a({type:"run",id:d}),o.note&&a({type:"status",text:o.note});let m=null;if(n.options?.workspace&&typeof n.options.workspace=="object"){const p=n.options.workspace;if(m=await ee({repo:p.repo,projectId:p.projectId,jobId:p.jobId,base:p.base||null}),m.error){a({type:"error",error:`workspace: ${m.error}`}),L(d),e.writableEnded||e.end();return}}const X=m?m.path:Ye(n.options?.workingDir);let E=null;{const p=X,O=!!m||!Ve(n.options?.workingDir),y=Qe(n.agent,n.options?.permissionMode,p);a({type:"workdir",path:p,isDefault:!O,writeScope:y||void 0}),a({type:"status",text:`Working in ${p}${O?"":" (default)"}`}),y&&a({type:"status",text:y}),E=await tt(p),E&&a({type:"scm",phase:"before",...E})}let D=null;if(E||m){const p=Array.isArray(n.options?.grants)?n.options.grants:[],{env:O,connection:y}=it({remote:E?.remote||null,grants:p,branch:m?.branch||null,connectionId:n.options?.connectionId||null});D=dt(O),m&&a({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&a({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const U={...n.options||{},...m?{workingDir:m.path}:{},...D?{runEnv:D}:{}};let R=null;n.pageTools?.specs?.length&&(R=Fe(g,n.pageTools.specs),U.mcp={url:`http://${k}:${v}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:n.pageTools.specs});try{await Z(U.sandbox,()=>r.engine.chat({messages:Array.isArray(n.messages)?n.messages:[],system:n.system||"",options:U,images:Array.isArray(n.images)?n.images:[]},g,{signal:l.signal}))}catch(p){u("error",`${n.agent} chat failed: ${p?.message||p}`),a({type:"error",error:p?.message||String(p)})}finally{if(!s){const p=await nt(X,E).catch(()=>null);p&&g({type:"scm",phase:"after",...p})}L(d),R&&V(R.id),e.writableEnded||e.end()}}async function hn(t,e,n){if(t.method==="GET"&&n==="/connections")return i(e,200,{ok:!0,connections:ot(),secretBackend:q()});if(t.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(t);if(n==="/connections")try{return i(e,200,{ok:!0,connection:rt(r.connection||r,{token:r.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(n);return o?o[2]==="delete"?i(e,200,{ok:at(o[1])}):i(e,200,st(o[1],r.remote||"")):i(e,404,{error:"Not found"})}async function pn(t,e,n){if(t.method==="GET"&&n==="/worktrees")return i(e,200,{ok:!0,root:te,worktrees:await ct()});if(t.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(t);if(n==="/worktrees"){const o=await ee({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return i(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(n==="/worktrees/remove"){const o=await lt({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return i(e,o.ok?200:400,o)}return i(e,404,{error:"Not found"})}async function T(t,e,n){const r=C[t.agent];if(!r||r.hidden)throw new P(`Unknown ChatPanel agent "${t.agent}"`,400,"model");const o=await r.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!o.ok)throw new P(o.reason||`${t.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=ie(a),d=()=>s.cancel("disconnected");n.on("close",d);let c="";try{return await Z(t.options?.sandbox,()=>r.engine.chat({messages:t.messages,system:t.system,options:t.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{n.off("close",d),L(a)}}function M(t){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(t,e){t.writableEnded||t.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
5
5
 
6
- `)}function B(n,e,t){n.writableEnded||n.write(`event: ${e}
7
- data: ${JSON.stringify(t)}
6
+ `)}function B(t,e,n){t.writableEnded||t.write(`event: ${e}
7
+ data: ${JSON.stringify(n)}
8
8
 
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(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function 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+`
9
+ `)}async function G(t,e,n,r){try{const o=n(await f(t)),a=F(t,o.agent,o.options||{});if(a.error)throw new P(a.error,403,"permission");return o.options=a.options,o}catch(o){return i(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${o.message}`):o)),null}}async function mn(t,e){const n=await G(t,e,Rt,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,Pt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}M(e);const r=Ot(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function fn(t,e){const n=await G(t,e,_t,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,$t(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}M(e);const r=xt(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function gn(t,e){const n=await G(t,e,Ht,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,It(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}M(e);const r=Mt(n.requestedModel,o=>B(e,o.type,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...b(o)};B(e,"error",a)}e.end()}async function wn(t,e){const n=await G(t,e,Nt,j);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,At(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,j(o))}M(e);const r=Et(n.requestedModel,(o,a)=>B(e,o,a));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){B(e,"error",j(o))}e.end()}async function yn(t,e){let n={};try{n=await f(t)||{}}catch{}const r=String(n.id||"").trim(),o=r?kt(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function pe(t,e,n){let r;try{r=await f(t)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=n?Y(n):Xe(),a=c=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:c})},s=(c,l)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:c,message:l}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return a({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:w}});const d=je();if(r.method==="tools/list"){const c=o?o.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...d,...c]})}if(r.method==="tools/call"){const c=await Je(r.params?.name,r.params?.arguments||{});if(c)return a(c);if(!o)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await ze(o,r.params?.name,r.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function bn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=n.server||{},o=n.message;if(!r.command||!o)return i(e,400,{error:"need server.command and message"});try{const a=await wt({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox},o);return o.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function Sn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=n.server||{};if(!r.command)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const o={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};try{return i(e,200,n.status?St(o):await bt(o))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function kn(t,e){let n;try{n=await f(t)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const{url:r,headers:o,message:a}=n||{};if(!r||!a)return i(e,400,{error:"need url and message"});let s;try{s=re(r)}catch(h){return i(e,400,{error:String(h?.message||h)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[h,g]of Object.entries(o)){const m=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(m)||m.startsWith("x-"))&&(d[h]=String(g))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(a),redirect:"follow",signal:c.signal});try{h.url&&re(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")||"",authenticate:h.headers.get("WWW-Authenticate")||"",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 me=256*1024,Tn=5,vn=8e3;async function Cn(t){let e=ae(t);const n=new AbortController,r=setTimeout(()=>n.abort(),vn);try{for(let o=0;o<=Tn;o++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:n.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${w} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=ae(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:xn(await En(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function En(t){if(!t.body?.getReader)return(await t.text().catch(()=>"")).slice(0,me);const e=t.body.getReader(),n=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(o+=s.byteLength,r+=n.decode(s,{stream:!0}),/<\/title\s*>/i.test(r)||o>=me))break}}finally{try{await e.cancel()}catch{}}return r}function On(t){return String(t).replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(e,n)=>{try{return String.fromCodePoint(+n)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,n)=>{try{return String.fromCodePoint(parseInt(n,16))}catch{return""}})}function xn(t){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(t);return e?On(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function An(t,e){let n;try{n=await f(t)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=n&&n.url;if(!r||typeof r!="string")return i(e,400,{error:"need url"});try{const o=await Cn(r);return i(e,200,{title:o.title||null,url:o.url||r})}catch(o){const a=o?.name==="AbortError"?"timed out":String(o?.message||o);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function Pn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=Y(n.session);if(!r)return i(e,404,{error:"no such session"});const o=r.pending.get(n.id);return o?(r.pending.delete(n.id),o.resolve(n.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function $n(t,e){let n;try{n=await f(t)}catch(c){return i(e,400,{error:"Bad JSON: "+c.message})}const r=C[n.agent];if(!r)return i(e,404,{error:`Unknown agent "${n.agent}"`});const o=String(n.prompt||"").slice(0,6e3);if(!o)return i(e,400,{error:"Empty prompt"});const a=n.model||"",s=F(t,n.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const d=String(n.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let c="";return typeof r.engine.complete=="function"?c=await r.engine.complete({prompt:o,system:d,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:d,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),i(e,200,{text:(c||"").trim()})}catch(c){return i(e,502,{error:c?.message||String(c)})}}async function In(t,e){let n;try{n=await f(t)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=C[n.agent];if(!r)return i(e,404,{error:`Unknown agent "${n.agent}"`});if(typeof r.engine.listModels!="function")return i(e,200,{models:[]});try{const o=await r.engine.listModels(n.options||{});return i(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return i(e,502,{error:o?.message||String(o)})}}async function Nn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(n.command||"").trim();if(!r)return i(e,400,{error:"No command"});let o=null;try{o=mt(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}const fe=we(async(t,e)=>{if(Ft(t,e),t.method==="OPTIONS")return e.writeHead(204),e.end();let n;try{n=new URL(t.url,`http://${t.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const r=en(t,n.pathname);if(r)return i(e,403,{error:r});try{if(t.method==="GET"&&n.pathname==="/health")return on(e);const o=n.searchParams.getAll("dir"),a=n.searchParams.get("workdir")||"";if(t.method==="GET"&&n.pathname==="/skills")return rn(e,o,a);if(t.method==="GET"&&n.pathname==="/skills-quarantined")return an(e,o,a);if(t.method==="GET"&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?sn(e,decodeURIComponent(s),o,a):cn(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,a)}if(n.pathname==="/connections"||n.pathname.startsWith("/connections/"))return hn(t,e,n.pathname);if(n.pathname==="/worktrees"||n.pathname.startsWith("/worktrees/"))return pn(t,e,n.pathname);if(t.method==="GET"&&n.pathname==="/v1/models")return he(e);if(t.method==="GET"&&n.pathname.startsWith("/v1/models/"))return he(e,decodeURIComponent(n.pathname.slice(11)));if(t.method==="GET"&&n.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:w,agents:Object.fromEntries(ut.map(d=>[d,s?ne(d)||null:!!ne(d)])),...s?{home:A.homedir(),path:process.env.PATH}:{}})}if(t.method==="POST"&&n.pathname==="/chat")return un(t,e);if(t.method==="POST"&&n.pathname==="/pair")return Vt(t,e);if(t.method==="POST"&&n.pathname==="/pair/code")return Kt(e);if(t.method==="POST"&&n.pathname==="/whoami")return Yt(t,e);if(t.method==="POST"&&n.pathname==="/v1/chat/completions")return mn(t,e);if(t.method==="POST"&&n.pathname==="/v1/completions")return fn(t,e);if(t.method==="POST"&&n.pathname==="/v1/responses")return gn(t,e);if(t.method==="POST"&&n.pathname==="/v1/messages")return wn(t,e);if(n.pathname==="/mcp"){if(t.method==="POST")return pe(t,e,null);if(t.method==="GET")return e.writeHead(405),e.end()}if(n.pathname.startsWith("/mcp/")){const s=decodeURIComponent(n.pathname.slice(5));if(t.method==="POST")return pe(t,e,s);if(t.method==="GET")return e.writeHead(405),e.end();if(t.method==="DELETE")return V(s),e.writeHead(204),e.end()}if(t.method==="GET"&&n.pathname==="/channels")return de(t,e,"status");if(t.method==="POST"&&n.pathname.startsWith("/channels/"))return de(t,e,n.pathname.slice(10));if(t.method==="POST"&&n.pathname==="/cancel")return yn(t,e);if(t.method==="POST"&&n.pathname==="/tool-result")return Pn(t,e);if(t.method==="POST"&&n.pathname==="/sandbox/refused"){let s=null;try{s=await f(t)}catch{s=null}const d=qe(s||{});return e.writeHead(d?204:403),e.end()}if(t.method==="POST"&&n.pathname==="/mcp-local")return bn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-local/signin")return Sn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-remote")return kn(t,e);if(t.method==="POST"&&n.pathname==="/fetch-title")return An(t,e);if(t.method==="POST"&&n.pathname==="/complete")return $n(t,e);if(t.method==="POST"&&n.pathname==="/list-models")return In(t,e);if(t.method==="POST"&&n.pathname==="/agent-check")return Nn(t,e);if(t.method==="POST"&&n.pathname==="/update")return dn(e);i(e,404,{error:"Not found"})}catch(o){i(e,500,{error:o?.message||String(o)})}});function u(t,e){(t==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Rn(t){let e="";const n=[];let r=!1,o=!1;const a=()=>{o&&!r&&!n.length&&process.exit(0)},s=async()=>{if(!r){for(r=!0;n.length;){const d=n.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});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,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}
11
+ `)}}r=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",d=>{e+=d;let c;for(;(c=e.indexOf(`
12
+ `))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&n.push(l)}s()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function _n(){ht(),pt(),zt(),fe.on("error",t=>{t&&t.code==="EADDRINUSE"&&(u("error",`Port ${v} is already in use — another app (or a second bridge) has it.`),u("error","Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings."),process.exit(1)),u("error",`bridge server error: ${t?.message||t}`),process.exit(1)});for(const t of["SIGINT","SIGTERM"])process.on(t,()=>{const e=Tt("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const n=vt("shutdown");n&&u("info",`shutdown: closed ${n} warm agent process${n===1?"":"es"}`),Q().close(),setTimeout(()=>process.exit(0),e||n?300:0).unref?.(),!e&&!n&&process.exit(0)});fe.listen(v,k,async()=>{u("info",`listening on http://${k}:${v}`),J.has(k)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:t,label:e,hidden:n}]of Object.entries(C)){if(n)continue;const r=await t.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${e}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),le().then(t=>t.startIfConfigured()).then(t=>{t?.skipped||(t?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${t?.error||"unknown error"}`))}).catch(t=>u("error",`channels: ${t?.message||t}`))})}function Hn(){console.log(`ChatPanel Bridge v${w}
13
13
 
14
14
  Usage:
15
15
  chatpanel-bridge start the bridge (foreground) on ${k}:${v}
@@ -19,5 +19,6 @@ Usage:
19
19
  chatpanel-bridge --update download & install the latest version, then restart
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
+ chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
22
23
 
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();
24
+ Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function Mn(){const t=process.argv,e=(...n)=>n.some(r=>t.includes(r));if(e("--help","-h"))return Hn(),!0;if(e("--version","-v"))return console.log(w),!0;if(e("pair","--pair"))return(async()=>{let n="";try{n=z(N,"utf8").trim()}catch{}const r=`http://${k}:${v}`;try{if(!n)throw new Error(`no token at ${N} — is the bridge running?`);const o=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(2500)}),a=await o.json().catch(()=>({}));if(!o.ok)throw new Error(a.error||`HTTP ${o.status}`);console.log(`Pairing code: ${Lt(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(o){u("error",`could not get a pairing code from the bridge at ${r}: ${o?.message||o}`),process.exitCode=1}})(),!0;if(t.includes("sandbox"))return Ze(t.slice(t.indexOf("sandbox")+1)).then(n=>{process.exitCode=n}),!0;if(e("--install")){try{He(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(n){u("error","Install failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--uninstall")){try{Me(),u("info","Removed the login auto-start.")}catch(n){u("error","Uninstall failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--status")){let n=!1;try{n=Be()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${n?"installed":"not installed"}`),!0}return!1}const ge=process.argv.indexOf("--mcp-stdio");if(ge>=0){const t=process.argv[ge+1];t||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Rn(t)}else process.argv.includes("--update")?(async()=>{try{const t=await oe(w);u("info",`Updated v${t.from} → v${t.to}. Restarting the background service…`),K()}catch(t){u("error","Update failed: "+(t?.message||t)),process.exitCode=1}})():Mn()||_n();