@chatpanel/bridge 0.13.8 → 0.13.9

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.13.8",
3
+ "version": "0.13.9",
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,6 +1,6 @@
1
- import{spawn as N,spawnSync as P}from"node:child_process";import{writeFileSync as F,unlinkSync as z}from"node:fs";import"node:os";import I from"node:path";import{findAgentBin as O}from"../env.js";import{buildCliPrompt as R}from"./prompt.js";import{summarizeCliError as U}from"../cli-errors.js";import{killOnAbort as j,spawnGroupOpts as B}from"../proc.js";import{pushExtraArgs as G,FORBIDDEN as H}from"./args.js";import{resolveWorkdir as J}from"../workdir.js";const D=Number(process.env.CHATPANEL_AGY_TIMEOUT_MS)||18e4;async function at(){try{const p=O("agy")||"agy",l=P(p,["models"],{encoding:"utf8",timeout:15e3}),e=[],a=new Set;for(const r of String(l.stdout||"").split(`
2
- `)){const n=r.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),e.push(n),e.length>=100))break}return e}catch{return[]}}const C=()=>({started:new Set,finalText:""});function K(p,l,e=C()){const a=String(p||"").trim();if(!a)return{streamed:!1};let r;try{r=JSON.parse(a)}catch{return l({type:"delta",text:`${a}
3
- `}),{streamed:!0}}const n=r.event||r.type||"";if(n==="init")return l({type:"status",text:"Antigravity working"}),{streamed:!1};if(n==="result"){const s=r.result||{};return e.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 o=r.step_update||{};if(o.step_type==="tool"){const s=`agy_${o.step_index??e.started.size}`,i=o.tool_info&&typeof o.tool_info=="object"?o.tool_info:{},m=o.tool_name||i.name||"tool";if(e.started.has(s)||(e.started.add(s),l({type:"tool",name:m,phase:"start",callId:s,input:i.parameters&&typeof i.parameters=="object"?i.parameters:{}})),o.state==="DONE"){const d=!!i.error||o.state==="ERROR",y=i.output==null?"":typeof i.output=="string"?i.output:JSON.stringify(i.output);l({type:"tool",name:m,phase:"done",callId:s,status:d?`error: ${String(i.error||"failed").slice(0,80)}`:"ok",result:String(d?i.error||"":y).slice(0,4e3)})}return{streamed:!1}}return o.step_type==="agent_response"&&typeof o.text_delta=="string"&&o.text_delta?(l({type:"delta",text:o.text_delta}),{streamed:!0}):{streamed:!1}}let w=!1,L=0;async function it(){if(Date.now()-L>(w?3e4:4e3)){L=Date.now();try{w=!!O("agy")}catch{w=!1}}return w?{ok:!0}:{ok:!1,reason:"agy not found on PATH. Install Antigravity, then run `agy` once to sign in."}}function W(p,l){const e=[];for(let a=0;a<(p?.length||0);a++){const r=/^data:([^;]+);base64,(.+)$/s.exec(p[a]?.dataUrl||"");if(!r)continue;const n=(r[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",o=I.join(l,`chatpanel-img-${Date.now()}-${a}.${n}`);try{F(o,Buffer.from(r[2],"base64")),e.push(o)}catch{}}return e}async function lt({messages:p,system:l,options:e,images:a},r,{signal:n}={}){const o=J(e.workingDir),s=W(a,o),i=()=>s.forEach(t=>{try{z(t)}catch{}});let m=R(p,l);s.length&&(m+=`
1
+ import{spawn as N,spawnSync as F}from"node:child_process";import{writeFileSync as z,unlinkSync as B}from"node:fs";import"node:os";import O from"node:path";import{findAgentBin as C}from"../env.js";import{fitCliPrompt as R,argvPromptBudget as U}from"./prompt.js";import{summarizeCliError as j}from"../cli-errors.js";import{killOnAbort as G,spawnGroupOpts as H}from"../proc.js";import{pushExtraArgs as J,FORBIDDEN as K}from"./args.js";import{resolveWorkdir as W}from"../workdir.js";const D=Number(process.env.CHATPANEL_AGY_TIMEOUT_MS)||18e4;async function pt(){try{const u=C("agy")||"agy",l=F(u,["models"],{encoding:"utf8",timeout:15e3}),r=[],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),r.push(n),r.length>=100))break}return r}catch{return[]}}const P=()=>({started:new Set,finalText:""});function Y(u,l,r=P()){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 r.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 o=e.step_update||{};if(o.step_type==="tool"){const s=`agy_${o.step_index??r.started.size}`,i=o.tool_info&&typeof o.tool_info=="object"?o.tool_info:{},d=o.tool_name||i.name||"tool";if(r.started.has(s)||(r.started.add(s),l({type:"tool",name:d,phase:"start",callId:s,input:i.parameters&&typeof i.parameters=="object"?i.parameters:{}})),o.state==="DONE"){const y=!!i.error||o.state==="ERROR",f=i.output==null?"":typeof i.output=="string"?i.output:JSON.stringify(i.output);l({type:"tool",name:d,phase:"done",callId:s,status:y?`error: ${String(i.error||"failed").slice(0,80)}`:"ok",result:String(y?i.error||"":f).slice(0,4e3)})}return{streamed:!1}}return o.step_type==="agent_response"&&typeof o.text_delta=="string"&&o.text_delta?(l({type:"delta",text:o.text_delta}),{streamed:!0}):{streamed:!1}}let w=!1,L=0;async function ut(){if(Date.now()-L>(w?3e4:4e3)){L=Date.now();try{w=!!C("agy")}catch{w=!1}}return w?{ok:!0}:{ok:!1,reason:"agy not found on PATH. Install Antigravity, then run `agy` once to sign in."}}function Z(u,l){const r=[];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",o=O.join(l,`chatpanel-img-${Date.now()}-${a}.${n}`);try{z(o,Buffer.from(e[2],"base64")),r.push(o)}catch{}}return r}async function dt({messages:u,system:l,options:r,images:a},e,{signal:n}={}){const o=W(r.workingDir),s=Z(a,o),i=()=>s.forEach(t=>{try{B(t)}catch{}}),d=R(u,l,U({otherArgsChars:400}));let y=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&&(y+=`
4
4
 
5
- The user attached image(s): ${s.map(t=>"@"+I.basename(t)).join(" ")}`);const d=["-p",m];e.model&&d.push("--model",e.model),e.permissionMode==="bypassPermissions"&&d.push("--dangerously-skip-permissions"),G(d,e.extraArgs,H.antigravity,r);const y=t=>new Promise((v,x)=>{const M=t?[...d,"--output-format","stream-json"]:d;let f;try{f=N("agy",M,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.runEnv||{}},...B})}catch(u){return x(new Error(`Failed to start agy: ${u.message}`))}const A=j(f,n);let k="",E="",c="",b=!1;const T=C();let g;const S=()=>{clearTimeout(g),g=setTimeout(()=>{f.kill("SIGKILL"),x(new Error(`Antigravity timed out — no output for ${Math.round(D/1e3)}s.`))},D)};S();const $=u=>{K(u,r,T).streamed&&(b=!0)};f.stdout.on("data",u=>{S();const h=u.toString();if(k+=h,!t){b=!0,r({type:"delta",text:h});return}c+=h;let _;for(;(_=c.indexOf(`
6
- `))>=0;)$(c.slice(0,_)),c=c.slice(_+1)}),f.stderr.on("data",u=>{S(),E+=u.toString()}),f.on("error",u=>{clearTimeout(g),A(),x(new Error(`Failed to start agy: ${u.message}`))}),f.on("close",u=>{if(clearTimeout(g),A(),n?.aborted){v({code:0,aborted:!0});return}t&&c.trim()&&$(c),v({code:u,out:k,err:E,streamed:b,state:T})})});try{let t=await y(!0);if(t.aborted||t.code!==0&&!t.streamed&&/output-format|unknown flag|flag provided but not defined/i.test(t.err)&&(r({type:"status",text:"This Antigravity CLI has no structured output; showing its text only. Update it with `agy update` to see tool activity."}),t=await y(!1),t.aborted))return;if(t.code!==0)throw new Error(U("Antigravity",t.code,t.err,t.out));t.streamed||r({type:"delta",text:(t.state?.finalText||t.out).trim()||"(no output)"}),r({type:"done",text:""})}finally{i()}}export{it as available,lt as chat,K as forwardAgyLine,at as listModels,C as newAgyState};
5
+ The user attached image(s): ${s.map(t=>"@"+O.basename(t)).join(" ")}`);const f=["-p",y];r.model&&f.push("--model",r.model),r.permissionMode==="bypassPermissions"&&f.push("--dangerously-skip-permissions"),J(f,r.extraArgs,K.antigravity,e);const A=t=>new Promise((_,x)=>{const M=t?[...f,"--output-format","stream-json"]:f;let c;try{c=N("agy",M,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,...r.runEnv||{}},...H})}catch(p){return x(new Error(`Failed to start agy: ${p.message}`))}const k=G(c,n);let $="",E="",m="",b=!1;const T=P();let g;const v=()=>{clearTimeout(g),g=setTimeout(()=>{c.kill("SIGKILL"),x(new Error(`Antigravity timed out — no output for ${Math.round(D/1e3)}s.`))},D)};v();const I=p=>{Y(p,e,T).streamed&&(b=!0)};c.stdout.on("data",p=>{v();const h=p.toString();if($+=h,!t){b=!0,e({type:"delta",text:h});return}m+=h;let S;for(;(S=m.indexOf(`
6
+ `))>=0;)I(m.slice(0,S)),m=m.slice(S+1)}),c.stderr.on("data",p=>{v(),E+=p.toString()}),c.on("error",p=>{clearTimeout(g),k(),x(new Error(`Failed to start agy: ${p.message}`))}),c.on("close",p=>{if(clearTimeout(g),k(),n?.aborted){_({code:0,aborted:!0});return}t&&m.trim()&&I(m),_({code:p,out:$,err:E,streamed:b,state:T})})});try{let t=await A(!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 A(!1),t.aborted))return;if(t.code!==0)throw new Error(j("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{ut as available,dt as chat,Y as forwardAgyLine,pt as listModels,P as newAgyState};
@@ -1,7 +1,7 @@
1
- import{runSpec as h,listSpecModels as A,runForStdout as d,CHATPANEL_STABLE_MCP_URL as m}from"./custom.js";import{findAgentBin as b,selfMcpStdio as u}from"../env.js";function i(e,o,a,t={}){let r=!1,s=0;const n={...o,command:e};return{spec:n,async available(){if(Date.now()-s>(r?3e4:4e3)){s=Date.now();try{r=!!b(e)}catch{r=!1}}return r?{ok:!0}:{ok:!1,reason:a}},listModels(l={}){return t.listModels?t.listModels(e,l):A(e,o.listModelsArgs,l.workingDir)},chat(l,c,p){return h(n,l,c,p)}}}const H=i("pi",{args:"-p",promptVia:"arg",modelArg:"--model {model}",imageArg:"@{path}",toolAdapter:"pi-extension",listModelsArgs:"--list-models",label:"Pi"},"pi not found on PATH. Install Pi, then run `pi` once to sign in."),D=i("opencode",{args:"run --format json --dangerously-skip-permissions",promptVia:"arg",modelArg:"-m {model}",imageArg:"-f {path}",format:"opencode-json",requiresStableMcp:!0,stableMcpConfigCheck:"opencode",listModelsArgs:"models",label:"OpenCode"},"opencode not found on PATH. Install opencode, then sign in."),P=i("kiro-cli",{args:"chat --no-interactive --require-mcp-startup",promptVia:"arg",modelArg:"--model {model}",trustAllToolsForMcp:!0,trustAllToolsArg:"--trust-all-tools",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"kiro",stableMcpSetupArgs:["mcp","add","--scope","global","--name","chatpanel_browser","--url","http://127.0.0.1:4319/mcp","--force"],stableMcpSetupCommand:"kiro-cli mcp add --scope global --name chatpanel_browser --url http://127.0.0.1:4319/mcp --force",listModelsArgs:"--list-models",label:"Kiro"},"kiro-cli not found on PATH. Install Kiro CLI, then sign in."),S=["-p","{prompt}","--output-format","json","--no-color","--log-level","none","--no-ask-user","--no-auto-update","--no-remote","--no-remote-export"],_=i("copilot",{args:S,promptVia:"arg",modelArg:"--model {model}",imageArg:"--attachment {path}",format:"copilot-json",mcpArg:"--additional-mcp-config @{file}",permissionArgs:{default:["--allow-all-tools"],acceptEdits:["--allow-all-tools","--allow-all-paths"],bypassPermissions:["--allow-all"]},forbidden:"copilot",label:"GitHub Copilot"},"copilot not found on PATH. Install GitHub Copilot CLI, then run `copilot login`.",{listModels:(e,o)=>M(e,o.workingDir)});async function M(e="copilot",o){const a=await d(e,["help","config"],o),t=[],r=new Set;let s=!1;for(const n of String(a||"").split(`
2
- `)){const l=/^\s*`([A-Za-z][\w.]*)`\s*:/.exec(n);if(l){s=l[1]==="model";continue}if(!s)continue;const c=/^\s*-\s*"([^"]+)"\s*$/.exec(n);if(!c)continue;const p=c[1];if(!r.has(p)&&(r.add(p),t.push(p),t.length>=200))break}return t.length?["auto",...t]:[]}const T=i("dsh",{args:["--profile","headless","{prompt}"],promptVia:"arg",format:"text",modelPatch:{arg:"--patch {file}",build:e=>`- id: ${g}
1
+ import{runSpec as h,listSpecModels as A,runForStdout as d,CHATPANEL_STABLE_MCP_URL as m}from"./custom.js";import{findAgentBin as b,selfMcpStdio as u}from"../env.js";function a(e,o,i,t={}){let r=!1,s=0;const n={...o,command:e};return{spec:n,async available(){if(Date.now()-s>(r?3e4:4e3)){s=Date.now();try{r=!!b(e)}catch{r=!1}}return r?{ok:!0}:{ok:!1,reason:i}},listModels(l={}){return t.listModels?t.listModels(e,l):A(e,o.listModelsArgs,l.workingDir)},chat(l,c,p){return h(n,l,c,p)}}}const H=a("pi",{args:"-p",promptVia:"stdin",modelArg:"--model {model}",imageArg:"@{path}",toolAdapter:"pi-extension",listModelsArgs:"--list-models",label:"Pi"},"pi not found on PATH. Install Pi, then run `pi` once to sign in."),D=a("opencode",{args:"run --format json --dangerously-skip-permissions",promptVia:"stdin",modelArg:"-m {model}",imageArg:"-f {path}",format:"opencode-json",requiresStableMcp:!0,stableMcpConfigCheck:"opencode",listModelsArgs:"models",label:"OpenCode"},"opencode not found on PATH. Install opencode, then sign in."),P=a("kiro-cli",{args:"chat --no-interactive --require-mcp-startup",promptVia:"stdin",modelArg:"--model {model}",trustAllToolsForMcp:!0,trustAllToolsArg:"--trust-all-tools",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"kiro",stableMcpSetupArgs:["mcp","add","--scope","global","--name","chatpanel_browser","--url","http://127.0.0.1:4319/mcp","--force"],stableMcpSetupCommand:"kiro-cli mcp add --scope global --name chatpanel_browser --url http://127.0.0.1:4319/mcp --force",listModelsArgs:"--list-models",label:"Kiro"},"kiro-cli not found on PATH. Install Kiro CLI, then sign in."),S=["--output-format","json","--no-color","--log-level","none","--no-ask-user","--no-auto-update","--no-remote","--no-remote-export"],_=a("copilot",{args:S,promptVia:"stdin",modelArg:"--model {model}",imageArg:"--attachment {path}",format:"copilot-json",mcpArg:"--additional-mcp-config @{file}",permissionArgs:{default:["--allow-all-tools"],acceptEdits:["--allow-all-tools","--allow-all-paths"],bypassPermissions:["--allow-all"]},forbidden:"copilot",label:"GitHub Copilot"},"copilot not found on PATH. Install GitHub Copilot CLI, then run `copilot login`.",{listModels:(e,o)=>M(e,o.workingDir)});async function M(e="copilot",o){const i=await d(e,["help","config"],o),t=[],r=new Set;let s=!1;for(const n of String(i||"").split(`
2
+ `)){const l=/^\s*`([A-Za-z][\w.]*)`\s*:/.exec(n);if(l){s=l[1]==="model";continue}if(!s)continue;const c=/^\s*-\s*"([^"]+)"\s*$/.exec(n);if(!c)continue;const p=c[1];if(!r.has(p)&&(r.add(p),t.push(p),t.length>=200))break}return t.length?["auto",...t]:[]}const T=a("dsh",{args:["--profile","headless","{prompt}"],promptVia:"arg",format:"text",modelPatch:{arg:"--patch {file}",build:e=>`- id: ${g}
3
3
  config:
4
4
  provider: ${k}
5
5
  model: ${JSON.stringify(e)}
6
- `},label:"DeepSeek Harness"},'dsh not found on PATH. Install DeepSeek Harness, then run `dsh --profile headless "hi"` once to check the profile.',{listModels:(e,o)=>w(e,o.workingDir)}),g="agent-default-model",k="deepseek-official",f=["deepseek-v4-flash","deepseek-v4-pro"];async function w(e="dsh",o){const a=await d(e,["--profile","headless","--dump-config"],o,6e4),t=String(a||"").split(`
7
- `),r=new RegExp(`^-\\s*id:\\s*${g}\\s*$`);for(let s=0;s<t.length;s++)if(r.test(t[s]))for(let n=s+1;n<t.length&&!/^-\s*id:/.test(t[n]);n++){const l=/^\s*model:\s*['"]?([\w.:-]+)['"]?\s*$/.exec(t[n]);if(l)return[...new Set([l[1],...f])]}return[...f]}const y=i("hermes",{args:"-z {prompt}",promptVia:"arg",modelArg:"-m {model}",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"hermes",stableMcpSetupArgs:()=>{const{command:e,args:o}=u(m);return["mcp","add","chatpanel_browser","--command",e,"--args",...o]},stableMcpSetupCommand:(()=>{const{command:e,args:o}=u(m);return`hermes mcp add chatpanel_browser --command ${e} --args ${o.join(" ")}`})(),label:"Hermes"},"hermes not found on PATH. Install Hermes Agent, then run `hermes setup` to sign in.",{listModels:async(e,o={})=>{try{const a=await d(e,["config","get","model"],o.workingDir),t=/^\s*default:\s*(\S+)/m.exec(a||"");return t?[t[1]]:[]}catch{return[]}}});export{_ as copilot,T as deepseek,y as hermes,P as kiro,M as listCopilotModels,w as listDshModels,D as opencode,H as pi};
6
+ `},label:"DeepSeek Harness"},'dsh not found on PATH. Install DeepSeek Harness, then run `dsh --profile headless "hi"` once to check the profile.',{listModels:(e,o)=>w(e,o.workingDir)}),g="agent-default-model",k="deepseek-official",f=["deepseek-v4-flash","deepseek-v4-pro"];async function w(e="dsh",o){const i=await d(e,["--profile","headless","--dump-config"],o,6e4),t=String(i||"").split(`
7
+ `),r=new RegExp(`^-\\s*id:\\s*${g}\\s*$`);for(let s=0;s<t.length;s++)if(r.test(t[s]))for(let n=s+1;n<t.length&&!/^-\s*id:/.test(t[n]);n++){const l=/^\s*model:\s*['"]?([\w.:-]+)['"]?\s*$/.exec(t[n]);if(l)return[...new Set([l[1],...f])]}return[...f]}const y=a("hermes",{args:"-z {prompt}",promptVia:"arg",modelArg:"-m {model}",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"hermes",stableMcpSetupArgs:()=>{const{command:e,args:o}=u(m);return["mcp","add","chatpanel_browser","--command",e,"--args",...o]},stableMcpSetupCommand:(()=>{const{command:e,args:o}=u(m);return`hermes mcp add chatpanel_browser --command ${e} --args ${o.join(" ")}`})(),label:"Hermes"},"hermes not found on PATH. Install Hermes Agent, then run `hermes setup` to sign in.",{listModels:async(e,o={})=>{try{const i=await d(e,["config","get","model"],o.workingDir),t=/^\s*default:\s*(\S+)/m.exec(i||"");return t?[t[1]]:[]}catch{return[]}}});export{_ as copilot,T as deepseek,y as hermes,P as kiro,M as listCopilotModels,w as listDshModels,D as opencode,H as pi};
@@ -1,5 +1,5 @@
1
- import{spawn as O}from"node:child_process";import{readFile as G,writeFile as P,unlink as K}from"node:fs/promises";import A from"node:os";import C from"node:path";import{resolveCommand as L,buildSpawnSpec as _,selfMcpStdio as Z}from"../env.js";import{isProEntitled as R}from"../entitlement.js";import{killOnAbort as q}from"../proc.js";import{buildCliPrompt as V}from"./prompt.js";import{pushExtraArgs as W,FORBIDDEN as B}from"./args.js";import{createStreamParser as X,STREAM_FORMATS as Q}from"./stream-formats.js";import{resolveWorkdir as Y}from"../workdir.js";async function tt(t,n){const e=[];for(let r=0;r<(t?.length||0);r++){const o=/^data:([^;]+);base64,(.+)$/s.exec(t[r]?.dataUrl||"");if(!o)continue;const i=(o[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",d=C.join(A.tmpdir(),`chatpanel-custom-img-${n}-${r}.${i}`);await P(d,Buffer.from(o[2],"base64")),e.push(d)}return e}function et(t,n){const e=String(t||"").trim();if(!e||!n.length)return[];const r=[];for(const o of n)r.push(...e.includes("{path}")?e.replaceAll("{path}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]);return r}const j=Number(process.env.CHATPANEL_CUSTOM_TIMEOUT_MS)||18e4,rt="http://127.0.0.1:4319/mcp",F="http://127.0.0.1:4319/mcp";async function vt(){return{ok:!0}}function nt(t){const n=[],e=new Set;for(const r of String(t||"").split(`
2
- `)){const o=r.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),n.push(o),n.length>=200))break}return n}async function It(t={}){if(!await R(t.entitlement))throw new Error("Custom agents require ChatPanel Pro.");const n=t.custom||{};return ot(n.command,n.listModelsArgs,t.workingDir)}async function ot(t,n,e){const r=String(n||"").trim();if(!t||!r)return[];const o=await it(t,r.split(/\s+/).filter(Boolean),e);return nt(o)}async function it(t,n,e,r=2e4){if(!t)return"";const o=L(t);if(!o)throw new Error(`Couldn't find "${t}".`);const i=e?C.resolve(e):null,[d,u,a]=_(o,n,i);return a.env={...a.env||process.env,NO_COLOR:"1",CLICOLOR:"0"},new Promise((f,l)=>{let h;try{h=O(d,u,a)}catch(S){return l(new Error(`Failed to start ${t}: ${S.message}`))}let m="";const c=setTimeout(()=>{h.kill("SIGKILL"),l(new Error(`${t} timed out.`))},r);h.stdout.on("data",S=>m+=S.toString()),h.on("error",S=>{clearTimeout(c),l(new Error(`Failed to start ${t}: ${S.message}`))}),h.on("close",()=>{clearTimeout(c),f(m)});try{h.stdin.end()}catch{}})}function U(t){return(t?.specs||[]).filter(n=>n?.name)}function D(t,n){const e=String(t).replace(/[^A-Za-z0-9_$]/g,"_");return/^[A-Za-z_$]/.test(e)?e:`tool_${n}_${e}`}function st(t,n){return["--extension",t]}function at(t,n){const e=String(t||"").trim(),r=U(n).map(i=>i.name).filter(Boolean);if(!e||!r.length)return[];const o=r.join(",");return e.includes("{tools}")?e.replaceAll("{tools}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]}function lt(t={},n){return t.trustAllToolsForMcp?[t.trustAllToolsArg||"--trust-all-tools"]:t.trustToolsArg?at(t.trustToolsArg,n):[]}function ct(t={}){return t.stableMcpSetupCommand?t.stableMcpSetupCommand:`opencode mcp add chatpanel --url ${F}`}function mt(t={}){const n=typeof t.stableMcpSetupArgs=="function"?t.stableMcpSetupArgs():t.stableMcpSetupArgs,e=Array.isArray(n)?n.filter(r=>r!=null).map(String):null;return e?.length?{command:t.stableMcpSetupCommandName||t.command,args:e}:null}function ut(t){const n=U(t),e=n.map((o,i)=>{const d=D(o.name,i),u=o.parameters||{type:"object",properties:{}};return`const ${d}Tool = {
1
+ import{spawn as O}from"node:child_process";import{readFile as G,writeFile as P,unlink as K}from"node:fs/promises";import b from"node:os";import $ from"node:path";import{resolveCommand as L,buildSpawnSpec as v,selfMcpStdio as Z}from"../env.js";import{isProEntitled as R}from"../entitlement.js";import{killOnAbort as q}from"../proc.js";import{buildCliPrompt as V,fitCliPrompt as W,argvPromptBudget as X}from"./prompt.js";import{pushExtraArgs as Q,FORBIDDEN as B}from"./args.js";import{createStreamParser as Y,STREAM_FORMATS as tt}from"./stream-formats.js";import{resolveWorkdir as et}from"../workdir.js";async function rt(t,n){const e=[];for(let r=0;r<(t?.length||0);r++){const o=/^data:([^;]+);base64,(.+)$/s.exec(t[r]?.dataUrl||"");if(!o)continue;const i=(o[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",f=$.join(b.tmpdir(),`chatpanel-custom-img-${n}-${r}.${i}`);await P(f,Buffer.from(o[2],"base64")),e.push(f)}return e}function nt(t,n){const e=String(t||"").trim();if(!e||!n.length)return[];const r=[];for(const o of n)r.push(...e.includes("{path}")?e.replaceAll("{path}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]);return r}const j=Number(process.env.CHATPANEL_CUSTOM_TIMEOUT_MS)||18e4,ot="http://127.0.0.1:4319/mcp",F="http://127.0.0.1:4319/mcp";async function Ft(){return{ok:!0}}function it(t){const n=[],e=new Set;for(const r of String(t||"").split(`
2
+ `)){const o=r.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),n.push(o),n.length>=200))break}return n}async function Nt(t={}){if(!await R(t.entitlement))throw new Error("Custom agents require ChatPanel Pro.");const n=t.custom||{};return st(n.command,n.listModelsArgs,t.workingDir)}async function st(t,n,e){const r=String(n||"").trim();if(!t||!r)return[];const o=await at(t,r.split(/\s+/).filter(Boolean),e);return it(o)}async function at(t,n,e,r=2e4){if(!t)return"";const o=L(t);if(!o)throw new Error(`Couldn't find "${t}".`);const i=e?$.resolve(e):null,[f,u,s]=v(o,n,i);return s.env={...s.env||process.env,NO_COLOR:"1",CLICOLOR:"0"},new Promise((g,a)=>{let S;try{S=O(f,u,s)}catch(w){return a(new Error(`Failed to start ${t}: ${w.message}`))}let p="";const c=setTimeout(()=>{S.kill("SIGKILL"),a(new Error(`${t} timed out.`))},r);S.stdout.on("data",w=>p+=w.toString()),S.on("error",w=>{clearTimeout(c),a(new Error(`Failed to start ${t}: ${w.message}`))}),S.on("close",()=>{clearTimeout(c),g(p)});try{S.stdin.end()}catch{}})}function U(t){return(t?.specs||[]).filter(n=>n?.name)}function D(t,n){const e=String(t).replace(/[^A-Za-z0-9_$]/g,"_");return/^[A-Za-z_$]/.test(e)?e:`tool_${n}_${e}`}function lt(t,n){return["--extension",t]}function ct(t,n){const e=String(t||"").trim(),r=U(n).map(i=>i.name).filter(Boolean);if(!e||!r.length)return[];const o=r.join(",");return e.includes("{tools}")?e.replaceAll("{tools}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]}function mt(t={},n){return t.trustAllToolsForMcp?[t.trustAllToolsArg||"--trust-all-tools"]:t.trustToolsArg?ct(t.trustToolsArg,n):[]}function ut(t={}){return t.stableMcpSetupCommand?t.stableMcpSetupCommand:`opencode mcp add chatpanel --url ${F}`}function pt(t={}){const n=typeof t.stableMcpSetupArgs=="function"?t.stableMcpSetupArgs():t.stableMcpSetupArgs,e=Array.isArray(n)?n.filter(r=>r!=null).map(String):null;return e?.length?{command:t.stableMcpSetupCommandName||t.command,args:e}:null}function dt(t){const n=U(t),e=n.map((o,i)=>{const f=D(o.name,i),u=o.parameters||{type:"object",properties:{}};return`const ${f}Tool = {
3
3
  name: ${JSON.stringify(o.name)},
4
4
  label: ${JSON.stringify(o.name)},
5
5
  description: ${JSON.stringify(o.description||o.name)},
@@ -65,7 +65,7 @@ ${e}
65
65
  export default function (pi: ExtensionAPI) {
66
66
  ${r}
67
67
  }
68
- `}async function pt(t,n){const e=C.join(A.tmpdir(),`chatpanel-pi-tools-${n}.ts`);return await P(e,ut(t)),e}async function dt(){const t=process.env.XDG_CONFIG_HOME||C.join(A.homedir(),".config"),n=[C.join(t,"opencode","opencode.jsonc"),C.join(A.homedir(),"Library","Application Support","opencode","opencode.jsonc")];for(const e of n)try{if((await G(e,"utf8")).includes(rt))return!0}catch{}return!1}async function H(t,n,e){const r=L(t);if(!r)return"";const[o,i,d]=_(r,n,e||null);return new Promise(u=>{const a=O(o,i,d);let f="",l="";const h=setTimeout(()=>{a.kill("SIGKILL"),u(f+l)},4e3);a.stdout.on("data",m=>f+=m.toString()),a.stderr.on("data",m=>l+=m.toString()),a.on("error",()=>{clearTimeout(h),u(f+l)}),a.on("close",()=>{clearTimeout(h),u(f+l)});try{a.stdin.end()}catch{}})}async function ft(t,n){for(const e of["workspace","global","default"]){const r=await H(t,["mcp","list",e],n);if(r.includes(F)||/chatpanel_browser/i.test(r))return!0}return!1}async function gt(t,n){const e=await H(t,["mcp","list"],n);return e.includes(F)||/chatpanel_browser/i.test(e)}async function ht(t,n){return t.stableMcpConfigCheck==="kiro"?ft(t.command||"kiro-cli",n):t.stableMcpConfigCheck==="opencode"?dt():t.stableMcpConfigCheck==="hermes"?gt(t.command||"hermes",n):!1}async function St(t,n){const e=L(t.command);if(!e)throw new Error(`Couldn't find "${t.command}" to set up browser tools.`);const[r,o,i]=_(e,t.args,n||null);i.env={...i.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"},await new Promise((d,u)=>{let a;try{a=O(r,o,i)}catch(m){return u(new Error(`Failed to start ${t.command}: ${m.message}`))}let f="",l="";const h=setTimeout(()=>{a.kill("SIGKILL"),u(new Error(`${t.command} MCP setup timed out.`))},2e4);a.stderr.on("data",m=>f+=m.toString()),a.stdout?.on("data",m=>l+=m.toString()),a.on("error",m=>{clearTimeout(h),u(new Error(`Failed to start ${t.command}: ${m.message}`))}),a.on("close",m=>{if(clearTimeout(h),m===0)return d(`${l}
69
- ${f}`.trim());u(new Error(`${t.command} MCP setup exited ${m}: ${f.trim().split(`
70
- `).pop()||"failed"}`))});try{a.stdin.end()}catch{}})}function wt(t,n){const e=String(n?.message||n||"");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 yt(t,n,e,r,o={}){if(!t.requiresStableMcp)return!0;const i=o.hasConfig||ht,d=o.runSetup||St;if(await i(t,n))return!0;const u=ct(t);if(!t.autoSetupStableMcp){const l=`${e} needs one-time browser-tool setup: ${u}`;throw r({type:"status",text:l}),new Error(l)}const a=mt(t);if(!a?.command){const l=`${e} needs one-time browser-tool setup: ${u}`;throw r({type:"status",text:l}),new Error(l)}r({type:"status",text:`${e} is setting up one-time browser tools...`});const f=String(await d(a,n)||"").trim();if(await i(t,n))return!0;throw new Error(`${e} browser-tool setup did not register the server.`+(f?` ${f.split(`
71
- `).filter(Boolean).slice(-3).join(" ")}`:"")+` Run: ${u}`)}async function Ft({messages:t,system:n,options:e,images:r},o,{signal:i}={}){if(!await R(e.entitlement))throw new Error("Custom agents require ChatPanel Pro. Upgrade in Settings to bring your own CLI agent.");return Ct(e.custom||{},{messages:t,system:n,options:e,images:r},o,{signal:i})}async function Ct(t,{messages:n,system:e,options:r={},images:o},i,{signal:d}={}){if(!t.command)throw new Error("This agent has no command configured.");const u=L(t.command);if(!u)throw new Error(`Couldn't find "${t.command}". Enter its full path, or install it on your PATH (or in WSL).`);const a=V(n,e);let f=Y(r.workingDir);const l=t.label||t.command,h=Object.hasOwn(Q,t.format)?t.format:"text",m=t.promptVia==="arg"?"arg":"stdin";let c=Array.isArray(t.args)?t.args.slice():t.args?String(t.args).split(/\s+/).filter(Boolean):[];if(W(c,r.extraArgs,B[t.forbidden]||B.custom,i),r.model&&t.modelArg){const s=String(t.modelArg),p=s.includes("{model}")?s.replaceAll("{model}",r.model).split(/\s+/).filter(Boolean):[...s.split(/\s+/).filter(Boolean),r.model];c=[...c,...p]}if(t.permissionArgs){const s=String(r.permissionMode||"default"),p=t.permissionArgs[s]||t.permissionArgs.default||[];c=[...c,...p.map(String)]}const S=`${Date.now()}-${Math.random().toString(36).slice(2)}`,N=t.imageArg?await tt(o,S):[],x=[],T=()=>[...N,...x].forEach(s=>K(s).catch(()=>{}));if(r.mcp?.url&&t.toolAdapter==="pi-extension"){const s=await pt(r.mcp,S);x.push(s),c=[...st(s,r.mcp),...c]}else if(r.mcp?.url&&t.mcpArg){const s=r.mcp.serverName||"chatpanel_browser",{command:p,args:g}=Z(r.mcp.url),y=C.join(A.tmpdir(),`chatpanel-mcp-${S}.json`);await P(y,JSON.stringify({mcpServers:{[s]:{command:p,args:g}}})),x.push(y);const b=String(t.mcpArg);c=[...b.includes("{file}")?b.replaceAll("{file}",y).split(/\s+/).filter(Boolean):[...b.split(/\s+/).filter(Boolean),y],...c]}if(r.mcp?.url)try{await yt(t,f,l,i)}catch(s){i({type:"status",text:`${l}: continuing without ChatPanel's browser tools — ${wt(l,s)}`}),r={...r,mcp:null}}if(r.mcp?.url&&c.push(...lt(t,r.mcp)),r.model&&typeof t.modelPatch?.build=="function"){const s=/^[A-Za-z0-9][\w.:-]{0,79}$/.test(String(r.model))?String(r.model):"";if(s){const p=C.join(A.tmpdir(),`chatpanel-modelpatch-${S}.yml`);await P(p,t.modelPatch.build(s)),x.push(p);const g=String(t.modelPatch.arg||"--patch {file}");c=[...g.includes("{file}")?g.replaceAll("{file}",p).split(/\s+/).filter(Boolean):[...g.split(/\s+/).filter(Boolean),p],...c]}}const $=et(t.imageArg,N);let k=!1;if($.length&&(c=c.flatMap(s=>s==="{images}"?(k=!0,$):[s])),m==="arg"){let s=!1;c=c.map(p=>p.includes("{prompt}")?(s=!0,p.replaceAll("{prompt}",a)):p),s||($.length&&!k&&c.push(...$),c.push(a))}else $.length&&!k&&c.push(...$);const[J,z,v]=_(u,c,f,r.runEnv||null);v.env={...v.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"},await new Promise((s,p)=>{let g;try{g=O(J,z,v)}catch(w){return T(),p(new Error(`Failed to start ${l}: ${w.message}`))}const y=q(g,d);let b="";const M=X(h,i);let E;const I=()=>{clearTimeout(E),E=setTimeout(()=>{g.kill("SIGKILL"),T(),p(new Error(`${l} timed out — no output for ${Math.round(j/1e3)}s.`))},j)};I(),g.stdout.on("data",w=>{I(),M.push(w.toString())}),g.stderr.on("data",w=>{I(),b+=w.toString()}),g.on("error",w=>{clearTimeout(E),y(),T(),p(new Error(`Failed to start ${l}: ${w.message}`))}),g.on("close",w=>{if(clearTimeout(E),y(),T(),d?.aborted){s();return}w===0?(i({type:"done",text:M.streamed?"":M.finish()}),s()):p(new Error(summarizeCliError(l,w,b)))}),m==="stdin"&&g.stdin.write(a),g.stdin.end()})}export{F as CHATPANEL_STABLE_MCP_URL,vt as available,ut as buildPiExtensionSource,Ft as chat,H as commandOutput,yt as ensureStableMcpConfig,It as listModels,ot as listSpecModels,wt as mcpSetupHint,lt as mcpTrustArgs,st as piToolArgs,it as runForStdout,Ct as runSpec,ct as stableMcpSetupCommand,mt as stableMcpSetupPlan,at as trustToolArgs};
68
+ `}async function ft(t,n){const e=$.join(b.tmpdir(),`chatpanel-pi-tools-${n}.ts`);return await P(e,dt(t)),e}async function gt(){const t=process.env.XDG_CONFIG_HOME||$.join(b.homedir(),".config"),n=[$.join(t,"opencode","opencode.jsonc"),$.join(b.homedir(),"Library","Application Support","opencode","opencode.jsonc")];for(const e of n)try{if((await G(e,"utf8")).includes(ot))return!0}catch{}return!1}async function H(t,n,e){const r=L(t);if(!r)return"";const[o,i,f]=v(r,n,e||null);return new Promise(u=>{const s=O(o,i,f);let g="",a="";const S=setTimeout(()=>{s.kill("SIGKILL"),u(g+a)},4e3);s.stdout.on("data",p=>g+=p.toString()),s.stderr.on("data",p=>a+=p.toString()),s.on("error",()=>{clearTimeout(S),u(g+a)}),s.on("close",()=>{clearTimeout(S),u(g+a)});try{s.stdin.end()}catch{}})}async function ht(t,n){for(const e of["workspace","global","default"]){const r=await H(t,["mcp","list",e],n);if(r.includes(F)||/chatpanel_browser/i.test(r))return!0}return!1}async function St(t,n){const e=await H(t,["mcp","list"],n);return e.includes(F)||/chatpanel_browser/i.test(e)}async function wt(t,n){return t.stableMcpConfigCheck==="kiro"?ht(t.command||"kiro-cli",n):t.stableMcpConfigCheck==="opencode"?gt():t.stableMcpConfigCheck==="hermes"?St(t.command||"hermes",n):!1}async function yt(t,n){const e=L(t.command);if(!e)throw new Error(`Couldn't find "${t.command}" to set up browser tools.`);const[r,o,i]=v(e,t.args,n||null);i.env={...i.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"},await new Promise((f,u)=>{let s;try{s=O(r,o,i)}catch(p){return u(new Error(`Failed to start ${t.command}: ${p.message}`))}let g="",a="";const S=setTimeout(()=>{s.kill("SIGKILL"),u(new Error(`${t.command} MCP setup timed out.`))},2e4);s.stderr.on("data",p=>g+=p.toString()),s.stdout?.on("data",p=>a+=p.toString()),s.on("error",p=>{clearTimeout(S),u(new Error(`Failed to start ${t.command}: ${p.message}`))}),s.on("close",p=>{if(clearTimeout(S),p===0)return f(`${a}
69
+ ${g}`.trim());u(new Error(`${t.command} MCP setup exited ${p}: ${g.trim().split(`
70
+ `).pop()||"failed"}`))});try{s.stdin.end()}catch{}})}function Ct(t,n){const e=String(n?.message||n||"");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 $t(t,n,e,r,o={}){if(!t.requiresStableMcp)return!0;const i=o.hasConfig||wt,f=o.runSetup||yt;if(await i(t,n))return!0;const u=ut(t);if(!t.autoSetupStableMcp){const a=`${e} needs one-time browser-tool setup: ${u}`;throw r({type:"status",text:a}),new Error(a)}const s=pt(t);if(!s?.command){const a=`${e} needs one-time browser-tool setup: ${u}`;throw r({type:"status",text:a}),new Error(a)}r({type:"status",text:`${e} is setting up one-time browser tools...`});const g=String(await f(s,n)||"").trim();if(await i(t,n))return!0;throw new Error(`${e} browser-tool setup did not register the server.`+(g?` ${g.split(`
71
+ `).filter(Boolean).slice(-3).join(" ")}`:"")+` Run: ${u}`)}async function Rt({messages:t,system:n,options:e,images:r},o,{signal:i}={}){if(!await R(e.entitlement))throw new Error("Custom agents require ChatPanel Pro. Upgrade in Settings to bring your own CLI agent.");return At(e.custom||{},{messages:t,system:n,options:e,images:r},o,{signal:i})}async function At(t,{messages:n,system:e,options:r={},images:o},i,{signal:f}={}){if(!t.command)throw new Error("This agent has no command configured.");const u=L(t.command);if(!u)throw new Error(`Couldn't find "${t.command}". Enter its full path, or install it on your PATH (or in WSL).`);let s=V(n,e),g=et(r.workingDir);const a=t.label||t.command,S=Object.hasOwn(tt,t.format)?t.format:"text",p=t.promptVia==="arg"?"arg":"stdin";let c=Array.isArray(t.args)?t.args.slice():t.args?String(t.args).split(/\s+/).filter(Boolean):[];if(Q(c,r.extraArgs,B[t.forbidden]||B.custom,i),r.model&&t.modelArg){const l=String(t.modelArg),m=l.includes("{model}")?l.replaceAll("{model}",r.model).split(/\s+/).filter(Boolean):[...l.split(/\s+/).filter(Boolean),r.model];c=[...c,...m]}if(t.permissionArgs){const l=String(r.permissionMode||"default"),m=t.permissionArgs[l]||t.permissionArgs.default||[];c=[...c,...m.map(String)]}const w=`${Date.now()}-${Math.random().toString(36).slice(2)}`,N=t.imageArg?await rt(o,w):[],x=[],T=()=>[...N,...x].forEach(l=>K(l).catch(()=>{}));if(r.mcp?.url&&t.toolAdapter==="pi-extension"){const l=await ft(r.mcp,w);x.push(l),c=[...lt(l,r.mcp),...c]}else if(r.mcp?.url&&t.mcpArg){const l=r.mcp.serverName||"chatpanel_browser",{command:m,args:d}=Z(r.mcp.url),h=$.join(b.tmpdir(),`chatpanel-mcp-${w}.json`);await P(h,JSON.stringify({mcpServers:{[l]:{command:m,args:d}}})),x.push(h);const y=String(t.mcpArg);c=[...y.includes("{file}")?y.replaceAll("{file}",h).split(/\s+/).filter(Boolean):[...y.split(/\s+/).filter(Boolean),h],...c]}if(r.mcp?.url)try{await $t(t,g,a,i)}catch(l){i({type:"status",text:`${a}: continuing without ChatPanel's browser tools — ${Ct(a,l)}`}),r={...r,mcp:null}}if(r.mcp?.url&&c.push(...mt(t,r.mcp)),r.model&&typeof t.modelPatch?.build=="function"){const l=/^[A-Za-z0-9][\w.:-]{0,79}$/.test(String(r.model))?String(r.model):"";if(l){const m=$.join(b.tmpdir(),`chatpanel-modelpatch-${w}.yml`);await P(m,t.modelPatch.build(l)),x.push(m);const d=String(t.modelPatch.arg||"--patch {file}");c=[...d.includes("{file}")?d.replaceAll("{file}",m).split(/\s+/).filter(Boolean):[...d.split(/\s+/).filter(Boolean),m],...c]}}const A=nt(t.imageArg,N);let k=!1;if(A.length&&(c=c.flatMap(l=>l==="{images}"?(k=!0,A):[l])),p==="arg"){const l=c.reduce((h,y)=>h+String(y).length+3,0)+A.reduce((h,y)=>h+String(y).length+3,0),m=W(n,e,X({viaCmdExe:u.kind==="cmd",otherArgsChars:l}));(m.dropped||m.prompt!==s)&&(s=m.prompt,i({type:"status",text:`${a} takes the prompt as a command-line argument, which this system caps — the oldest ${m.dropped||"part of the"} turn${m.dropped===1?"":"s"} of this conversation ${m.dropped?"were":"was"} left out to fit.`}));let d=!1;c=c.map(h=>h.includes("{prompt}")?(d=!0,h.replaceAll("{prompt}",s)):h),d||(A.length&&!k&&c.push(...A),c.push(s))}else A.length&&!k&&c.push(...A);const[J,z,_]=v(u,c,g,r.runEnv||null);_.env={..._.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"},await new Promise((l,m)=>{let d;try{d=O(J,z,_)}catch(C){return T(),m(new Error(`Failed to start ${a}: ${C.message}`))}const h=q(d,f);let y="";const M=Y(S,i);let E;const I=()=>{clearTimeout(E),E=setTimeout(()=>{d.kill("SIGKILL"),T(),m(new Error(`${a} timed out — no output for ${Math.round(j/1e3)}s.`))},j)};I(),d.stdout.on("data",C=>{I(),M.push(C.toString())}),d.stderr.on("data",C=>{I(),y+=C.toString()}),d.on("error",C=>{clearTimeout(E),h(),T(),m(new Error(`Failed to start ${a}: ${C.message}`))}),d.on("close",C=>{if(clearTimeout(E),h(),T(),f?.aborted){l();return}C===0?(i({type:"done",text:M.streamed?"":M.finish()}),l()):m(new Error(summarizeCliError(a,C,y)))}),p==="stdin"&&d.stdin.write(s),d.stdin.end()})}export{F as CHATPANEL_STABLE_MCP_URL,Ft as available,dt as buildPiExtensionSource,Rt as chat,H as commandOutput,$t as ensureStableMcpConfig,Nt as listModels,st as listSpecModels,Ct as mcpSetupHint,mt as mcpTrustArgs,lt as piToolArgs,at as runForStdout,At as runSpec,ut as stableMcpSetupCommand,pt as stableMcpSetupPlan,ct as trustToolArgs};
@@ -1,9 +1,10 @@
1
- import{stripHidden as u}from"../sanitize.js";function a(t){return t==="assistant"?"Assistant":"User"}function p(t=[],c=""){const o=String(c||"").trim(),r=Array.isArray(t)?t:[],e=r.slice(0,-1),s=r[r.length-1],n=[];if(o&&n.push(o),e.length){const l=e.map(i=>`${a(i.role)}: ${String(i.content||"").trim()}`).join(`
1
+ import{stripHidden as h}from"../sanitize.js";function a(n){return n==="assistant"?"Assistant":"User"}function c(n=[],o=""){const e=String(o||"").trim(),r=Array.isArray(n)?n:[],s=r.slice(0,-1),t=r[r.length-1],i=[];if(e&&i.push(e),s.length){const p=s.map(l=>`${a(l.role)}: ${String(l.content||"").trim()}`).join(`
2
2
 
3
- `);n.push(`Conversation history (context only; do not answer these prior turns):
4
- ${l}`)}return s&&n.push(`Current ${a(s.role).toLowerCase()} message (answer this message now; use the history above only as context):
5
- ${String(s.content||"").trim()}`),u(n.join(`
3
+ `);i.push(`Conversation history (context only; do not answer these prior turns):
4
+ ${p}`)}return t&&i.push(`Current ${a(t.role).toLowerCase()} message (answer this message now; use the history above only as context):
5
+ ${String(t.content||"").trim()}`),h(i.join(`
6
6
 
7
7
  ---
8
8
 
9
- `))}export{p as buildCliPrompt};
9
+ `))}function m({platform:n=process.platform,viaCmdExe:o=!1,otherArgsChars:e=0}={}){return Math.max(2e3,(o?8191:n==="win32"?32767:n==="linux"?131072:262144)-1500-e)}function f(n=[],o="",e=1/0){let r=Array.isArray(n)?n:[],s=0,t=c(r,o);for(;t.length>e&&r.length>1;)r=r.slice(1),s+=1,t=c(r,o);if(t.length>e){const i=`[…earlier part of the message omitted to fit the command line…]
10
+ `;t=i+t.slice(t.length-(e-i.length))}return{prompt:t,dropped:s}}export{m as argvPromptBudget,c as buildCliPrompt,f as fitCliPrompt};
package/src/server.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as fe}from"node:http";import A from"node:os";import{randomBytes as ge,randomInt as ye,timingSafeEqual as we}from"node:crypto";import{mkdirSync as be,writeFileSync as Se,readFileSync as K,existsSync as ke}from"node:fs";import{join as _}from"node:path";import*as Te from"./engines/claude.js";import*as ve from"./engines/codex.js";import*as Ce from"./engines/antigravity.js";import{pi as Ee,opencode as Oe,kiro as Pe,copilot as Ae,deepseek as xe,hermes as $e}from"./engines/cli-agents.js";import{connectorsFor as Ie}from"./connectors.js";import*as Ne from"./engines/custom.js";import{installService as Re,uninstallService as _e,serviceStatus as He,restartService as V}from"./service.js";import{skillIndex as D,listRecords as Me,readRecord as Be,readPackageFile as Ge,skillsHealth as Ue,quarantinedSkills as De}from"./skills.js";import{capabilityToolSpecs as Le,runCapabilityTool as je}from"./mcp-capabilities.js";import{createSession as We,deleteSession as X,getSession as Y,activeSession as Fe,relayToolCall as Je}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ze,isDefaultWorkdir as Ke,resolveWorkdir as Ve,writeScopeNote as Xe}from"./workdir.js";import{gitState as Ye,gitDelta as Qe}from"./scm.js";import{listConnections as Ze,putConnection as qe,removeConnection as et,runEnvFor as tt,testConnection as nt,secretBackend as Q}from"./connections.js";import{worktreeFor as Z,listWorktrees as rt,removeWorktree as ot,withHook as at,WORKTREE_ROOT as q}from"./worktree.js";import{AGENT_CLIS as it,enrichPath as st,enrichAgentEnv as ct,findAgentBin as ee,resolveCommand as lt}from"./env.js";import"./sanitize.js";import{checkForUpdate as dt,selfUpdate as te,isEmbedded as ut}from"./update.js";import{callLocalMcp as ht}from"./mcp-local.js";import{assertPublicHttpUrl as ne,assertPublicWebUrl as re}from"./ssrf.js";import{startRun as oe,endRun as L,cancelRun as pt,cancelAll as mt}from"./runs.js";import{closeWarmPools as ft,warmStatus as gt}from"./warm.js";import{CompatError as x,anthropicError as j,anthropicStream as yt,chatCompletionStream as wt,completionStream as bt,createAnthropicMessage as St,createChatCompletion as kt,createCompletion as Tt,createResponse as vt,openAIError as w,parseAnthropicMessage as Ct,parseChatCompletion as Et,parseCompletion as Ot,parseResponse as Pt,responseStream as At}from"./api-compat.js";import{callerTrust as xt,isPaired as $,parseExtensionIds as $t,capRunOptions as It,engineHonoursReach as Nt,createPairingStore as Rt,formatPairingCode as _t}from"./pii/trust.js";const g="0.13.8",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Te,label:"Claude Code"},codex:{engine:ve,label:"Codex"},antigravity:{engine:Ce,label:"Antigravity",tools:!1},pi:{engine:Ee,label:"Pi"},opencode:{engine:Oe,label:"OpenCode"},hermes:{engine:$e,label:"Hermes"},kiro:{engine:Pe,label:"Kiro"},copilot:{engine:Ae,label:"GitHub Copilot"},deepseek:{engine:xe,label:"DeepSeek Harness"},custom:{engine:Ne,label:"Custom",hidden:!0}};function ae(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Ht=$t(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function I(n){return n.chatpanelTrust||(n.chatpanelTrust=xt({origin:n.headers.origin||"",hasToken:le(n),extensionIds:Ht})),n.chatpanelTrust}function Mt(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Bt(n,e){const t=n.headers.origin||"",o=ae(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const W=new Set(["127.0.0.1","localhost","::1"]);function Gt(n){if(!W.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return W.has(t)}const N=_(A.homedir(),".chatpanel","bridge-token");let S="";function Ut(){try{ke(N)&&(S=K(N,"utf8").trim()),S||(S=ge(32).toString("hex"),be(_(A.homedir(),".chatpanel"),{recursive:!0}),Se(N,S,{mode:384}))}catch(n){d("error",`could not initialise bridge token: ${n?.message||n}`)}}const ie=Rt({random:()=>ye(0,1e6)/1e6});function Dt(n){if(!S)return a(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ie.issue();return d("info","pairing code issued — valid for 5 minutes, one use"),a(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Lt(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=ie.claim(t?.code);return o.ok?(d("info",`paired a ${I(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),a(e,200,{ok:!0,token:S})):(d("info",`pairing refused (${o.reason}) from ${I(n)} caller`),a(e,403,{error:o.reason}))}function jt(n,e){const t=I(n);return a(e,200,{ok:!0,trust:t,paired:$(t),version:g})}let H=null;async function se(){if(H)return H;const{createChannelService:n}=await import("./channels/service.js");return H=n({home:_(A.homedir(),".chatpanel"),dataDir:_(A.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>d("info",e),warn:e=>d("info",e),error:e=>d("error",e)}}),H}async function ce(n,e,t){try{const o=await se(),r=n.method==="POST"?await f(n):{};if(t==="status")return a(e,200,await o.status());if(t==="connect"){const i=await o.connect(r);return a(e,200,{ok:!0,...i})}return t==="pair"?a(e,200,await o.pair()):t==="unpair"?a(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?a(e,200,await o.update(r)):t==="disconnect"?a(e,200,await o.stop({forget:!!r.forget})):a(e,404,{error:"unknown channel action"})}catch(o){return a(e,400,{error:o?.message||String(o)})}}function le(n){if(!S)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(S);return o.length===r.length&&we(o,r)}const Wt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),Ft=new Set(["/debug"]),Jt=n=>Ft.has(n);function zt(n,e){if(!Gt(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ae(t))return"forbidden origin";const o=n.method==="POST"&&Wt.has(e)||n.method==="GET"&&Jt(e);return o&&!(Mt(t)||le(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!$(I(n))&&!Vt.has(e)?Kt:null}const Kt="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",Vt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(n,e,t){const o=I(n),r=It(t,o);if(!Nt(e,r.reach))return{error:`${$(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${$(o)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const i=r.reach,s=$(o)?i==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":i==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:r,note:s}}function a(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}async function Xt(n){const e=await Promise.all(Object.entries(C).filter(([,r])=>!r.hidden).map(async([r,{engine:i,label:s,tools:u}])=>{const c=await i.available().catch(h=>({ok:!1,reason:String(h?.message||h)})),l=await Ie(r).catch(()=>[]);return{id:r,label:s,available:c.ok,reason:c.reason,connectors:l,...u===!1?{tools:!1}:{}}})),t=ut()?{current:g,updateAvailable:!1,embedded:"gateway"}:await dt(g).catch(()=>({current:g,updateAvailable:!1})),o=await Ue().catch(()=>null);a(n,200,{ok:!0,version:g,agents:e,update:t,workspace:ze,worktrees:q,secretBackend:Q(),warm:gt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...o?{skills:o}:{}})}async function Yt(n,e,t){const{index:o,problems:r}=await D({extraDirs:e,workdir:t});a(n,200,{ok:!0,skills:Me(o),problems:r})}async function Qt(n,e,t){a(n,200,{ok:!0,quarantined:await De(e,t)})}async function Zt(n,e,t,o){const{index:r}=await D({extraDirs:t,workdir:o}),i=Be(r,e);if(!i)return a(n,404,{ok:!1,error:"unknown skill"});a(n,200,{ok:!0,skill:i})}async function qt(n,e,t,o,r){const{index:i}=await D({extraDirs:o,workdir:r}),s=await Ge(i,e,t);if(s.error)return a(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});a(n,200,{ok:!0,...s})}async function en(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function de(n,e=""){const t=await en();if(e){const o=t.find(r=>r.id===e);return o?a(n,200,o):a(n,404,w(new x(`Model "${e}" not found`,404,"model")))}return a(n,200,{object:"list",data:t})}async function tn(n){try{const e=await te(g);a(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){a(n,400,{ok:!1,error:String(e?.message||e)})}}async function nn(n,e){let t;try{t=await f(n)}catch(p){return a(e,400,{error:"Bad JSON: "+p.message})}const o=C[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});const r=F(n,t.agent,t.options||{});if(r.error)return a(e,403,{error:r.error});t.options=r.options,Array.isArray(t.images)&&t.images.length&&d("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const i=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
2
+ import{createServer as fe}from"node:http";import A from"node:os";import{randomBytes as ge,randomInt as ye,timingSafeEqual as we}from"node:crypto";import{mkdirSync as be,writeFileSync as Se,readFileSync as K,existsSync as ke}from"node:fs";import{join as _}from"node:path";import*as Te from"./engines/claude.js";import*as ve from"./engines/codex.js";import*as Ce from"./engines/antigravity.js";import{pi as Ee,opencode as Oe,kiro as Pe,copilot as Ae,deepseek as xe,hermes as $e}from"./engines/cli-agents.js";import{connectorsFor as Ie}from"./connectors.js";import*as Ne from"./engines/custom.js";import{installService as Re,uninstallService as _e,serviceStatus as He,restartService as V}from"./service.js";import{skillIndex as D,listRecords as Me,readRecord as Be,readPackageFile as Ge,skillsHealth as Ue,quarantinedSkills as De}from"./skills.js";import{capabilityToolSpecs as Le,runCapabilityTool as je}from"./mcp-capabilities.js";import{createSession as We,deleteSession as X,getSession as Y,activeSession as Fe,relayToolCall as Je}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ze,isDefaultWorkdir as Ke,resolveWorkdir as Ve,writeScopeNote as Xe}from"./workdir.js";import{gitState as Ye,gitDelta as Qe}from"./scm.js";import{listConnections as Ze,putConnection as qe,removeConnection as et,runEnvFor as tt,testConnection as nt,secretBackend as Q}from"./connections.js";import{worktreeFor as Z,listWorktrees as rt,removeWorktree as ot,withHook as at,WORKTREE_ROOT as q}from"./worktree.js";import{AGENT_CLIS as it,enrichPath as st,enrichAgentEnv as ct,findAgentBin as ee,resolveCommand as lt}from"./env.js";import"./sanitize.js";import{checkForUpdate as dt,selfUpdate as te,isEmbedded as ut}from"./update.js";import{callLocalMcp as ht}from"./mcp-local.js";import{assertPublicHttpUrl as ne,assertPublicWebUrl as re}from"./ssrf.js";import{startRun as oe,endRun as L,cancelRun as pt,cancelAll as mt}from"./runs.js";import{closeWarmPools as ft,warmStatus as gt}from"./warm.js";import{CompatError as x,anthropicError as j,anthropicStream as yt,chatCompletionStream as wt,completionStream as bt,createAnthropicMessage as St,createChatCompletion as kt,createCompletion as Tt,createResponse as vt,openAIError as w,parseAnthropicMessage as Ct,parseChatCompletion as Et,parseCompletion as Ot,parseResponse as Pt,responseStream as At}from"./api-compat.js";import{callerTrust as xt,isPaired as $,parseExtensionIds as $t,capRunOptions as It,engineHonoursReach as Nt,createPairingStore as Rt,formatPairingCode as _t}from"./pii/trust.js";const g="0.13.9",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Te,label:"Claude Code"},codex:{engine:ve,label:"Codex"},antigravity:{engine:Ce,label:"Antigravity",tools:!1},pi:{engine:Ee,label:"Pi"},opencode:{engine:Oe,label:"OpenCode"},hermes:{engine:$e,label:"Hermes"},kiro:{engine:Pe,label:"Kiro"},copilot:{engine:Ae,label:"GitHub Copilot"},deepseek:{engine:xe,label:"DeepSeek Harness"},custom:{engine:Ne,label:"Custom",hidden:!0}};function ae(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Ht=$t(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function I(n){return n.chatpanelTrust||(n.chatpanelTrust=xt({origin:n.headers.origin||"",hasToken:le(n),extensionIds:Ht})),n.chatpanelTrust}function Mt(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Bt(n,e){const t=n.headers.origin||"",o=ae(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const W=new Set(["127.0.0.1","localhost","::1"]);function Gt(n){if(!W.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return W.has(t)}const N=_(A.homedir(),".chatpanel","bridge-token");let S="";function Ut(){try{ke(N)&&(S=K(N,"utf8").trim()),S||(S=ge(32).toString("hex"),be(_(A.homedir(),".chatpanel"),{recursive:!0}),Se(N,S,{mode:384}))}catch(n){d("error",`could not initialise bridge token: ${n?.message||n}`)}}const ie=Rt({random:()=>ye(0,1e6)/1e6});function Dt(n){if(!S)return a(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ie.issue();return d("info","pairing code issued — valid for 5 minutes, one use"),a(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Lt(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=ie.claim(t?.code);return o.ok?(d("info",`paired a ${I(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),a(e,200,{ok:!0,token:S})):(d("info",`pairing refused (${o.reason}) from ${I(n)} caller`),a(e,403,{error:o.reason}))}function jt(n,e){const t=I(n);return a(e,200,{ok:!0,trust:t,paired:$(t),version:g})}let H=null;async function se(){if(H)return H;const{createChannelService:n}=await import("./channels/service.js");return H=n({home:_(A.homedir(),".chatpanel"),dataDir:_(A.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>d("info",e),warn:e=>d("info",e),error:e=>d("error",e)}}),H}async function ce(n,e,t){try{const o=await se(),r=n.method==="POST"?await f(n):{};if(t==="status")return a(e,200,await o.status());if(t==="connect"){const i=await o.connect(r);return a(e,200,{ok:!0,...i})}return t==="pair"?a(e,200,await o.pair()):t==="unpair"?a(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?a(e,200,await o.update(r)):t==="disconnect"?a(e,200,await o.stop({forget:!!r.forget})):a(e,404,{error:"unknown channel action"})}catch(o){return a(e,400,{error:o?.message||String(o)})}}function le(n){if(!S)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(S);return o.length===r.length&&we(o,r)}const Wt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),Ft=new Set(["/debug"]),Jt=n=>Ft.has(n);function zt(n,e){if(!Gt(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ae(t))return"forbidden origin";const o=n.method==="POST"&&Wt.has(e)||n.method==="GET"&&Jt(e);return o&&!(Mt(t)||le(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!$(I(n))&&!Vt.has(e)?Kt:null}const Kt="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",Vt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(n,e,t){const o=I(n),r=It(t,o);if(!Nt(e,r.reach))return{error:`${$(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${$(o)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const i=r.reach,s=$(o)?i==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":i==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:r,note:s}}function a(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}async function Xt(n){const e=await Promise.all(Object.entries(C).filter(([,r])=>!r.hidden).map(async([r,{engine:i,label:s,tools:u}])=>{const c=await i.available().catch(h=>({ok:!1,reason:String(h?.message||h)})),l=await Ie(r).catch(()=>[]);return{id:r,label:s,available:c.ok,reason:c.reason,connectors:l,...u===!1?{tools:!1}:{}}})),t=ut()?{current:g,updateAvailable:!1,embedded:"gateway"}:await dt(g).catch(()=>({current:g,updateAvailable:!1})),o=await Ue().catch(()=>null);a(n,200,{ok:!0,version:g,agents:e,update:t,workspace:ze,worktrees:q,secretBackend:Q(),warm:gt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...o?{skills:o}:{}})}async function Yt(n,e,t){const{index:o,problems:r}=await D({extraDirs:e,workdir:t});a(n,200,{ok:!0,skills:Me(o),problems:r})}async function Qt(n,e,t){a(n,200,{ok:!0,quarantined:await De(e,t)})}async function Zt(n,e,t,o){const{index:r}=await D({extraDirs:t,workdir:o}),i=Be(r,e);if(!i)return a(n,404,{ok:!1,error:"unknown skill"});a(n,200,{ok:!0,skill:i})}async function qt(n,e,t,o,r){const{index:i}=await D({extraDirs:o,workdir:r}),s=await Ge(i,e,t);if(s.error)return a(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});a(n,200,{ok:!0,...s})}async function en(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function de(n,e=""){const t=await en();if(e){const o=t.find(r=>r.id===e);return o?a(n,200,o):a(n,404,w(new x(`Model "${e}" not found`,404,"model")))}return a(n,200,{object:"list",data:t})}async function tn(n){try{const e=await te(g);a(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){a(n,400,{ok:!1,error:String(e?.message||e)})}}async function nn(n,e){let t;try{t=await f(n)}catch(p){return a(e,400,{error:"Bad JSON: "+p.message})}const o=C[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});const r=F(n,t.agent,t.options||{});if(r.error)return a(e,403,{error:r.error});t.options=r.options,Array.isArray(t.images)&&t.images.length&&d("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const i=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
3
3
 
4
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 b=p=>{s||i(p)};i({type:"run",id:u}),r.note&&i({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){i({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),y=Xe(t.agent,t.options?.permissionMode,p);i({type:"workdir",path:p,isDefault:!O,writeScope:y||void 0}),i({type:"status",text:`Working in ${p}${O?"":" (default)"}`}),y&&i({type:"status",text:y}),E=await Ye(p),E&&i({type:"scm",phase:"before",...E})}let U=null;if(E||m){const p=Array.isArray(t.options?.grants)?t.options.grants:[],{env:O,connection:y}=tt({remote:E?.remote||null,grants:p,branch:m?.branch||null,connectionId:t.options?.connectionId||null});U=at(O),m&&i({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&i({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const z={...t.options||{},...m?{workingDir:m.path}:{},...U?{runEnv:U}:{}};let R=null;t.pageTools?.specs?.length&&(R=We(b,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:[]},b,{signal:l.signal})}catch(p){d("error",`${t.agent} chat failed: ${p?.message||p}`),i({type:"error",error:p?.message||String(p)})}finally{if(!s){const p=await Qe(J,E).catch(()=>null);p&&b({type:"scm",phase:"after",...p})}L(u),R&&X(R.id),e.writableEnded||e.end()}}async function rn(n,e,t){if(n.method==="GET"&&t==="/connections")return a(e,200,{ok:!0,connections:Ze(),secretBackend:Q()});if(n.method!=="POST")return a(e,405,{error:"method not allowed"});const o=await f(n);if(t==="/connections")try{return a(e,200,{ok:!0,connection:qe(o.connection||o,{token:o.token||null})})}catch(i){return a(e,400,{error:String(i?.message||i)})}const r=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return r?r[2]==="delete"?a(e,200,{ok:et(r[1])}):a(e,200,nt(r[1],o.remote||"")):a(e,404,{error:"Not found"})}async function on(n,e,t){if(n.method==="GET"&&t==="/worktrees")return a(e,200,{ok:!0,root:q,worktrees:await rt()});if(n.method!=="POST")return a(e,405,{error:"method not allowed"});const o=await f(n);if(t==="/worktrees"){const r=await Z({repo:o.repo,projectId:o.projectId,jobId:o.jobId,base:o.base||null});return a(e,r.error?400:200,r.error?{error:r.error}:{ok:!0,...r})}if(t==="/worktrees/remove"){const r=await ot({projectId:o.projectId,jobId:o.jobId,force:!!o.force});return a(e,r.ok?200:400,r)}return a(e,404,{error:"Not found"})}async function 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 i=`run_${Math.random().toString(36).slice(2,10)}`,s=oe(i),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(i)}}function M(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function P(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
5
5