@chatpanel/bridge 0.20.1 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.20.1",
3
+ "version": "0.21.1",
4
4
  "type": "module",
5
5
  "description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
@@ -1,10 +1,10 @@
1
- import{spawn as q}from"node:child_process";import{writeFile as W,unlink as D}from"node:fs/promises";import O from"node:os";import R from"node:path";import{resolveClaude as S,buildSpawnSpec as H,isCompiledBinary as ae,selfMcpStdio as ie}from"../env.js";import{signInStatus as le,signInMessage as U,loginRequired as ce}from"../sign-in.js";import{buildCliPrompt as z}from"./prompt.js";import{summarizeCliError as ue}from"../cli-errors.js";import{killOnAbort as pe}from"../proc.js";import{sandbox as de,noteSandbox as fe,track as he}from"../sandbox.js";import{pushExtraArgs as me,FORBIDDEN as ye}from"./args.js";import{relayTimeoutMax as be}from"../relay-timeout.js";import{displayPath as _e,resolveWorkdir as B}from"../workdir.js";import{connectorsFor as we}from"../connectors.js";import{chatWarm as ge}from"./claude-warm.js";import{claudePermissionResponse as Te,permissionAnswer as xe}from"../events/agent-permission.js";import{relayPermission as Ee}from"../mcp-sessions.js";async function Ce(e,t){const r=[];for(let i=0;i<(e?.length||0);i++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[i]?.dataUrl||"");if(!s)continue;const o=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",n=R.join(O.tmpdir(),`chatpanel-claude-img-${t}-${i}.${o}`);await W(n,Buffer.from(s[2],"base64")),r.push(n)}return r}const G=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,J=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task"],Y=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),ke=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task","ToolSearch"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch"])}),Se=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),ve=Object.freeze(["remember","forget"]),X=Object.freeze({device:Object.freeze([]),trusted:Se});function Ae(e,t=[]){const r=X[e]||X.device,i=(t||[]).filter(n=>typeof n=="string"&&/^chatpanel/i.test(n)),s=[],o=[];for(const n of i){for(const a of r)s.push(`mcp__${n}__${a}`);for(const a of ve)o.push(`mcp__${n}__${a}`)}return{allow:s,deny:o}}function Ne(e){if(!e||e==="any")return null;const t=Y[e]?e:"device";return{allow:[...Y[t]],deny:[...ke[t]]}}let P="Claude Code not found.",K=0,E=!1;async function ot(){if(Date.now()-K>(E?3e4:4e3)){K=Date.now();try{S()||!ae()&&await F()?E=!0:(E=!1,P=process.platform==="win32"?"Claude Code not found on Windows PATH or in WSL. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in — in Windows or in your WSL distro.":"Claude Code not found on PATH. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in.")}catch{E=!1}}return E?await le("claude",S()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:U("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:P}}async function st(){return["opus","sonnet","haiku"]}function Oe(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:r,args:i}=ie(e.url),s=[...new Set(e.specs.map(o=>o?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:r,args:i}}},allowedTools:s.map(o=>`mcp__${t}__${o}`)}}async function Pe(e,t,r){const i=e?.request_id,s=e?.request?.subtype;if(s==="can_use_tool"){const o=t?await t(e.request):xe("deny","This run has no approval surface.");return r(Te(i,o,e.request)),!0}return r({type:"control_response",response:{subtype:"error",request_id:i,error:`unsupported control request: ${s||"unknown"}`}}),!1}function Q({prompt:e,args:t,cwd:r,env:i=null,emit:s,signal:o,harness:n=null,host:a=!1,ask:u=null}){const f=S();if(!f)return null;const[y,b,_]=H(f,a?[...t,"--input-format","stream-json"]:t,r,i);return new Promise((m,l)=>{de().wrap(y,b,_,{engine:"claude",cwd:r}).then(p=>{fe(s,p.record);let c;try{c=he(q(p.bin,p.argv,p.opts),p,{kind:"agent"})}catch(d){return l(new Error(`Failed to start claude: ${d.message}`))}const w=pe(c,o);let h="",g="",A=!1,T=null;const oe={sawText:!1,tail:"",boundary:!1,harnessChars:n};let M="",C,$=0;const N=()=>{clearTimeout(C),!$&&(C=setTimeout(()=>{c.kill("SIGKILL"),l(new Error(`Claude Code timed out — no output for ${Math.round(G/1e3)}s.`))},G))};N();const se=d=>{try{c.stdin.write(`${JSON.stringify(d)}
2
- `)}catch{}};c.stdout.on("data",d=>{N(),h+=d.toString();let L;for(;(L=h.indexOf(`
3
- `))>=0;){const j=h.slice(0,L).trim();if(h=h.slice(L+1),!j.startsWith("{"))continue;let x;try{x=JSON.parse(j)}catch{continue}if(x.type==="control_request"){$++,clearTimeout(C),Pe(x,u,se).catch(()=>{}).finally(()=>{$--,N()});continue}if(x.type==="control_response")continue;const k=ee(x,s,A,r,oe);k.streamed&&(A=!0),k.result!=null&&(M=k.result),k.apiError&&(T=k.apiError),a&&x.type==="result"&&c.stdin.end()}}),c.stderr.on("data",d=>{N(),g+=d.toString()}),c.on("error",d=>{clearTimeout(C),w(),l(new Error(`Failed to start claude (${y}): ${d.message}`))}),c.on("close",d=>{if(clearTimeout(C),w(),o?.aborted){m({streamedAny:A,resultText:M});return}if(T&&ce(T))return l(new Error(U("Claude Code","claude")));if(d===0&&T)return l(new Error(`Claude Code reported an error: ${T}`));d===0?m({streamedAny:A,resultText:M}):l(new Error(ue("Claude Code",d,g,T||"",{agentId:"claude"})))}),a?c.stdin.write(`${JSON.stringify({type:"user",message:{role:"user",content:e}})}
4
- `):(c.stdin.write(e),c.stdin.end())}).catch(l)})}function Me(e){let t="";return typeof e=="string"?t=e:Array.isArray(e)&&(t=e.map(r=>typeof r=="string"?r:r?.text||"").filter(Boolean).join(`
1
+ import{spawn as F}from"node:child_process";import{writeFile as W,unlink as H}from"node:fs/promises";import P from"node:os";import R from"node:path";import{resolveClaude as S,buildSpawnSpec as q,isCompiledBinary as ae,selfMcpStdio as ie}from"../env.js";import{signInStatus as le,signInMessage as z,loginRequired as ce}from"../sign-in.js";import{buildCliPrompt as U}from"./prompt.js";import{summarizeCliError as ue}from"../cli-errors.js";import{killOnAbort as pe}from"../proc.js";import{sandbox as de,noteSandbox as fe,track as he}from"../sandbox.js";import{pushExtraArgs as me,FORBIDDEN as ye}from"./args.js";import{relayTimeoutMax as _e}from"../relay-timeout.js";import{displayPath as be,resolveWorkdir as B}from"../workdir.js";import{connectorsFor as we}from"../connectors.js";import{chatWarm as Te}from"./claude-warm.js";import{claudePermissionResponse as ge,permissionAnswer as xe}from"../events/agent-permission.js";import{relayPermission as Ee}from"../mcp-sessions.js";async function Ce(e,t){const r=[];for(let i=0;i<(e?.length||0);i++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[i]?.dataUrl||"");if(!s)continue;const o=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",n=R.join(P.tmpdir(),`chatpanel-claude-img-${t}-${i}.${o}`);await W(n,Buffer.from(s[2],"base64")),r.push(n)}return r}const G=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,J=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task"],K=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),ke=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task","ToolSearch"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch"])}),Se=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),Ae=Object.freeze(["remember","forget"]),ve=Object.freeze(["ask_model","ask_status"]),Y=Object.freeze({device:Object.freeze([]),trusted:Se});function Ne(e,t=[]){const r=Y[e]||Y.device,i=(t||[]).filter(n=>typeof n=="string"&&/^chatpanel/i.test(n)),s=[],o=[];for(const n of i){for(const a of r)s.push(`mcp__${n}__${a}`);for(const a of[...Ae,...ve])o.push(`mcp__${n}__${a}`)}return{allow:s,deny:o}}function Pe(e){if(!e||e==="any")return null;const t=K[e]?e:"device";return{allow:[...K[t]],deny:[...ke[t]]}}let M="Claude Code not found.",X=0,E=!1;async function st(){if(Date.now()-X>(E?3e4:4e3)){X=Date.now();try{S()||!ae()&&await j()?E=!0:(E=!1,M=process.platform==="win32"?"Claude Code not found on Windows PATH or in WSL. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in — in Windows or in your WSL distro.":"Claude Code not found on PATH. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in.")}catch{E=!1}}return E?await le("claude",S()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:z("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:M}}async function at(){return["opus","sonnet","haiku"]}function Me(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:r,args:i}=ie(e.url),s=[...new Set(e.specs.map(o=>o?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:r,args:i}}},allowedTools:s.map(o=>`mcp__${t}__${o}`)}}async function Oe(e,t,r){const i=e?.request_id,s=e?.request?.subtype;if(s==="can_use_tool"){const o=t?await t(e.request):xe("deny","This run has no approval surface.");return r(ge(i,o,e.request)),!0}return r({type:"control_response",response:{subtype:"error",request_id:i,error:`unsupported control request: ${s||"unknown"}`}}),!1}function Q({prompt:e,args:t,cwd:r,env:i=null,emit:s,signal:o,harness:n=null,host:a=!1,ask:u=null}){const f=S();if(!f)return null;const[y,_,b]=q(f,a?[...t,"--input-format","stream-json"]:t,r,i);return new Promise((m,p)=>{de().wrap(y,_,b,{engine:"claude",cwd:r}).then(c=>{fe(s,c.record);let l;try{l=he(F(c.bin,c.argv,c.opts),c,{kind:"agent"})}catch(d){return p(new Error(`Failed to start claude: ${d.message}`))}const w=pe(l,o);let h="",T="",v=!1,g=null;const oe={sawText:!1,tail:"",boundary:!1,harnessChars:n};let O="",C,L=0;const N=()=>{clearTimeout(C),!L&&(C=setTimeout(()=>{l.kill("SIGKILL"),p(new Error(`Claude Code timed out — no output for ${Math.round(G/1e3)}s.`))},G))};N();const se=d=>{try{l.stdin.write(`${JSON.stringify(d)}
2
+ `)}catch{}};l.stdout.on("data",d=>{N(),h+=d.toString();let $;for(;($=h.indexOf(`
3
+ `))>=0;){const D=h.slice(0,$).trim();if(h=h.slice($+1),!D.startsWith("{"))continue;let x;try{x=JSON.parse(D)}catch{continue}if(x.type==="control_request"){L++,clearTimeout(C),Oe(x,u,se).catch(()=>{}).finally(()=>{L--,N()});continue}if(x.type==="control_response")continue;const k=ee(x,s,v,r,oe);k.streamed&&(v=!0),k.result!=null&&(O=k.result),k.apiError&&(g=k.apiError),a&&x.type==="result"&&l.stdin.end()}}),l.stderr.on("data",d=>{N(),T+=d.toString()}),l.on("error",d=>{clearTimeout(C),w(),p(new Error(`Failed to start claude (${y}): ${d.message}`))}),l.on("close",d=>{if(clearTimeout(C),w(),o?.aborted){m({streamedAny:v,resultText:O});return}if(g&&ce(g))return p(new Error(z("Claude Code","claude")));if(d===0&&g)return p(new Error(`Claude Code reported an error: ${g}`));d===0?m({streamedAny:v,resultText:O}):p(new Error(ue("Claude Code",d,T,g||"",{agentId:"claude"})))}),a?l.stdin.write(`${JSON.stringify({type:"user",message:{role:"user",content:e}})}
4
+ `):(l.stdin.write(e),l.stdin.end())}).catch(p)})}function Le(e){let t="";return typeof e=="string"?t=e:Array.isArray(e)&&(t=e.map(r=>typeof r=="string"?r:r?.text||"").filter(Boolean).join(`
5
5
  `)),t.length>4e3?`${t.slice(0,4e3)}…`:t}function V(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
6
6
 
7
7
  `}),e.boundary=!1)}function Z(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function ee(e,t,r,i="",s=null){const o={streamed:!1,result:null};if(e.type==="stream_event"){const n=e.event;n?.type==="content_block_delta"&&(n.delta?.type==="text_delta"?(o.streamed=!0,V(s,t),t({type:"delta",text:n.delta.text}),Z(s,n.delta.text)):n.delta?.type==="thinking_delta"&&t({type:"reasoning",text:n.delta.thinking||""}))}else if(e.type==="assistant"){if(e.is_api_error_message||e.error)return o.apiError=(e.message?.content||[]).filter(n=>n.type==="text").map(n=>n.text).join(`
8
- `)||String(e.error||"api error"),o;for(const n of e.message?.content||[])n.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:n.name,phase:"start",callId:n.id,input:n.input,summary:Fe(n,i)})):n.type==="text"&&!r&&(o.streamed=!0,V(s,t),t({type:"delta",text:n.text}),Z(s,n.text))}else if(e.type==="user")for(const n of e.message?.content||[])n.type==="tool_result"&&t({type:"tool",phase:"done",callId:n.tool_use_id,status:n.is_error?"error":"ok",result:Me(n.content)});else if(e.type==="result"){e.is_error?o.apiError=o.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?o.result=e.result||"":t({type:"status",text:`(${e.subtype})`});const n=e.usage||e.message?.usage;if(n){const a=Number.isFinite(Number(e.total_cost_usd))?Number(e.total_cost_usd):null,u=Number(s?.costUsdBefore)||0;s&&a!=null&&(s.costUsdTotal=a),t({type:"usage",provider:"bridge",inputTokens:n.input_tokens||0,outputTokens:n.output_tokens||0,cacheReadTokens:n.cache_read_input_tokens||0,cacheWriteTokens:n.cache_creation_input_tokens||0,costUsd:a!=null?Math.max(0,a-u):null,costBasis:"list",...s?.harnessChars!=null?{harnessChars:s.harnessChars}:{}})}}return o}const te=process.env.CHATPANEL_CLAUDE_EFFORT??"low";let v=null;function re({probe:e=null}={}){return v||(v=(async()=>{try{return String(await(e?e():new Promise(t=>{const[r,i,s]=H(S(),["--help"],null),o=q(r,i,{...s,stdio:["ignore","pipe","pipe"]});let n="";o.stdout.on("data",a=>{n+=a}),o.on("error",()=>t("")),o.on("close",()=>t(n)),setTimeout(()=>{try{o.kill()}catch{}t(n)},8e3).unref?.()}))||"")}catch{return""}})(),v)}async function $e(e={}){return/--effort\b/.test(await re(e))}async function Le(e={}){return/--append-system-prompt(?:-file\b|\[-file\])/.test(await re(e))}function at(){v=null}async function We({system:e,options:t,tag:r}){const i=t.permissionMode||"default",s=B(t.workingDir),o=["--print","--output-format","stream-json","--include-partial-messages","--verbose"];te&&await $e()&&o.push("--effort",te);const n=[],a=[],u=Oe(t.mcp);if(u){const l=R.join(O.tmpdir(),`chatpanel-mcp-${r}.json`);await W(l,JSON.stringify(u.config)),n.push(l),o.push("--mcp-config",l),a.push(...u.allowedTools)}const f=Ne(t.reach);if(f){const l=Ae(t.reach,await we("claude").catch(()=>[]));o.push("--allowedTools",...f.allow,...a,...l.allow),o.push("--disallowedTools",...f.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",...J,...a);const y=!f&&t.approvals===!0;if(y&&o.push("--permission-prompt-tool","stdio"),e)if(S()?.kind!=="wsl"&&await Le()){const p=R.join(O.tmpdir(),`chatpanel-system-${r}.md`);await W(p,e,{mode:384}),n.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 b=u&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(be(t.mcp?.specs))}:null,_=b||t.runEnv?{...t.runEnv||{},...b||{}}:null;return{args:o,cwd:s,runEnv:_,cleanup:()=>n.forEach(l=>D(l).catch(()=>{})),hasMcp:!!u,approvals:y}}function ne({prompt:e="",system:t="",specs:r=null}={}){const i=Array.isArray(r)&&r.length?JSON.stringify(r).length:0;return String(e).length+String(t).length+i}function Re(e,t=[],r=""){let i=z(e,r);return t.length&&(i+=`
8
+ `)||String(e.error||"api error"),o;for(const n of e.message?.content||[])n.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:n.name,phase:"start",callId:n.id,input:n.input,summary:De(n,i)})):n.type==="text"&&!r&&(o.streamed=!0,V(s,t),t({type:"delta",text:n.text}),Z(s,n.text))}else if(e.type==="user")for(const n of e.message?.content||[])n.type==="tool_result"&&t({type:"tool",phase:"done",callId:n.tool_use_id,status:n.is_error?"error":"ok",result:Le(n.content)});else if(e.type==="result"){e.is_error?o.apiError=o.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?o.result=e.result||"":t({type:"status",text:`(${e.subtype})`});const n=e.usage||e.message?.usage;if(n){const a=Number.isFinite(Number(e.total_cost_usd))?Number(e.total_cost_usd):null,u=Number(s?.costUsdBefore)||0;s&&a!=null&&(s.costUsdTotal=a),t({type:"usage",provider:"bridge",inputTokens:n.input_tokens||0,outputTokens:n.output_tokens||0,cacheReadTokens:n.cache_read_input_tokens||0,cacheWriteTokens:n.cache_creation_input_tokens||0,costUsd:a!=null?Math.max(0,a-u):null,costBasis:"list",...s?.harnessChars!=null?{harnessChars:s.harnessChars}:{}})}}return o}const te=process.env.CHATPANEL_CLAUDE_EFFORT??"low";let A=null;function re({probe:e=null}={}){return A||(A=(async()=>{try{return String(await(e?e():new Promise(t=>{const[r,i,s]=q(S(),["--help"],null),o=F(r,i,{...s,stdio:["ignore","pipe","pipe"]});let n="";o.stdout.on("data",a=>{n+=a}),o.on("error",()=>t("")),o.on("close",()=>t(n)),setTimeout(()=>{try{o.kill()}catch{}t(n)},8e3).unref?.()}))||"")}catch{return""}})(),A)}async function $e(e={}){return/--effort\b/.test(await re(e))}async function We(e={}){return/--append-system-prompt(?:-file\b|\[-file\])/.test(await re(e))}function it(){A=null}async function Re({system:e,options:t,tag:r}){const i=t.permissionMode||"default",s=B(t.workingDir),o=["--print","--output-format","stream-json","--include-partial-messages","--verbose"];te&&await $e()&&o.push("--effort",te);const n=[],a=[],u=Me(t.mcp);if(u){const c=R.join(P.tmpdir(),`chatpanel-mcp-${r}.json`);await W(c,JSON.stringify(u.config)),n.push(c),o.push("--mcp-config",c),a.push(...u.allowedTools)}const f=Pe(t.reach);if(f){const c=Ne(t.reach,await we("claude").catch(()=>[]));o.push("--allowedTools",...f.allow,...a,...c.allow),o.push("--disallowedTools",...f.deny,...c.deny)}else i==="bypassPermissions"?o.push("--permission-mode","bypassPermissions"):i==="acceptEdits"?(o.push("--permission-mode","acceptEdits"),a.length&&o.push("--allowedTools",...a)):o.push("--allowedTools",...J,...a);const y=!f&&t.approvals===!0;if(y&&o.push("--permission-prompt-tool","stdio"),e)if(S()?.kind!=="wsl"&&await We()){const l=R.join(P.tmpdir(),`chatpanel-system-${r}.md`);await W(l,e,{mode:384}),n.push(l),o.push("--append-system-prompt-file",l)}else o.push("--append-system-prompt",e);t.model&&o.push("--model",t.model),t.useLocalConfig===!1&&o.push("--setting-sources","");const _=u&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(_e(t.mcp?.specs))}:null,b=t.askDepth?{CHATPANEL_ASK_DEPTH:String(Math.max(0,Math.min(8,Number(t.askDepth)||0)))}:null,m=_||b||t.runEnv?{...t.runEnv||{},..._||{},...b||{}}:null;return{args:o,cwd:s,runEnv:m,cleanup:()=>n.forEach(c=>H(c).catch(()=>{})),hasMcp:!!u,approvals:y}}function ne({prompt:e="",system:t="",specs:r=null}={}){const i=Array.isArray(r)&&r.length?JSON.stringify(r).length:0;return String(e).length+String(t).length+i}function Ie(e,t=[],r=""){let i=U(e,r);return t.length&&(i+=`
9
9
 
10
- The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}async function it({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=await ge({messages:e,system:t,options:r,images:i},s,{signal:o}).catch(a=>({handled:!1,reason:a?.message||String(a),thrown:!0}));if(!n.handled&&!o?.aborted){if(n.thrown)throw new Error(n.reason);return Ie({messages:e,system:t,options:r,images:i},s,{signal:o})}}async function Ie({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=await We({system:t,options:r,tag:n}),{args:u,cwd:f,runEnv:y}=a,b=await Ce(i,n),_=()=>{b.forEach(c=>D(c).catch(()=>{})),a.cleanup()},m=Re(e,b);me(u,r.extraArgs,ye.claude,s);const l=a.approvals&&r.permissionSession?c=>Ee(r.permissionSession,c):null,p=Q({prompt:m,args:u,cwd:f,env:y,emit:s,signal:o,harness:ne({prompt:m,system:t,specs:r.mcp?.specs}),host:a.approvals,ask:l});if(p===null)return _(),je({messages:e,system:t,options:r},s,{signal:o});try{const{streamedAny:c,resultText:w}=await p;s({type:"done",text:c?"":w})}finally{_()}}async function lt({prompt:e,system:t,model:r}){const i=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",r||"haiku","--system-prompt",t||"Continue the user's text briefly. Reply with only the continuation."];let s="";const o=Q({prompt:e,args:i,cwd:null,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(o===null)return qe({prompt:e,system:t,model:r});const{resultText:n}=await o;return(s||n||"").trim()}function Fe(e,t=""){const r=e.input||{};return r.command?String(r.command).slice(0,60):r.file_path?_e(r.file_path,t):r.pattern?r.pattern:r.url?r.url:r.description?String(r.description).slice(0,80):r.query?String(r.query).slice(0,80):r.prompt?String(r.prompt).slice(0,80):""}let I=null;function F(){return I||(I=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),I}async function je({messages:e,system:t,options:r},i,{signal:s}={}){const o=await F();if(!o)throw new Error(P);const{query:n}=o,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const u=r.permissionMode||"default",f=B(r.workingDir),y=u==="acceptEdits"||u==="bypassPermissions",b=new Set(J),_=async h=>b.has(h)||y?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${h} blocked — set this agent's permission mode in ChatPanel to enable it.`};let m=!1;const l=z(e),p={sawText:!1,tail:"",boundary:!1,harnessChars:ne({prompt:l,system:t})};let c="";const w=n({prompt:l,options:{cwd:f,permissionMode:u,includePartialMessages:!0,canUseTool:_,abortController:a,settingSources:r.useLocalConfig===!1?[]:["user","project"],systemPrompt:t?{type:"preset",preset:"claude_code",append:t}:{type:"preset",preset:"claude_code"},...r.model?{model:r.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const h of w){const g=ee(h,i,m,f,p);g.streamed&&(m=!0),g.result!=null&&(c=g.result)}}catch(h){if(s?.aborted||a.signal.aborted)return;throw h}i({type:"done",text:m?"":c})}async function qe({prompt:e,system:t,model:r}){const i=await F();if(!i)throw new Error(P);const{query:s}=i;let o="";const n=s({prompt:e,options:{cwd:O.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:t||"Continue the user's text briefly. Reply with only the continuation.",model:r||"haiku"}});for await(const a of n)if(a.type==="assistant")for(const u of a.message.content)u.type==="text"&&(o+=u.text);else a.type==="result"&&a.subtype==="success"&&!o&&(o=a.result||"");return o.trim()}export{at as _resetEffortProbe,Pe as answerControlRequest,ot as available,We as buildClaudeLaunch,Ae as channelMcpTools,Ne as channelToolPolicy,it as chat,Ie as chatCold,Oe as claudeMcpConfig,Re as claudePrompt,$e as claudeSupportsEffort,Le as claudeSupportsSystemPromptFile,lt as complete,ee as handleMessage,ne as harnessChars,st as listModels,Ce as writeImages};
10
+ The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}async function lt({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=await Te({messages:e,system:t,options:r,images:i},s,{signal:o}).catch(a=>({handled:!1,reason:a?.message||String(a),thrown:!0}));if(!n.handled&&!o?.aborted){if(n.thrown)throw new Error(n.reason);return je({messages:e,system:t,options:r,images:i},s,{signal:o})}}async function je({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=await Re({system:t,options:r,tag:n}),{args:u,cwd:f,runEnv:y}=a,_=await Ce(i,n),b=()=>{_.forEach(l=>H(l).catch(()=>{})),a.cleanup()},m=Ie(e,_);me(u,r.extraArgs,ye.claude,s);const p=a.approvals&&r.permissionSession?l=>Ee(r.permissionSession,l):null,c=Q({prompt:m,args:u,cwd:f,env:y,emit:s,signal:o,harness:ne({prompt:m,system:t,specs:r.mcp?.specs}),host:a.approvals,ask:p});if(c===null)return b(),Fe({messages:e,system:t,options:r},s,{signal:o});try{const{streamedAny:l,resultText:w}=await c;s({type:"done",text:l?"":w})}finally{b()}}async function ct({prompt:e,system:t,model:r}){const i=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",r||"haiku","--system-prompt",t||"Continue the user's text briefly. Reply with only the continuation."];let s="";const o=Q({prompt:e,args:i,cwd:null,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(o===null)return He({prompt:e,system:t,model:r});const{resultText:n}=await o;return(s||n||"").trim()}function De(e,t=""){const r=e.input||{};return r.command?String(r.command).slice(0,60):r.file_path?be(r.file_path,t):r.pattern?r.pattern:r.url?r.url:r.description?String(r.description).slice(0,80):r.query?String(r.query).slice(0,80):r.prompt?String(r.prompt).slice(0,80):""}let I=null;function j(){return I||(I=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),I}async function Fe({messages:e,system:t,options:r},i,{signal:s}={}){const o=await j();if(!o)throw new Error(M);const{query:n}=o,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const u=r.permissionMode||"default",f=B(r.workingDir),y=u==="acceptEdits"||u==="bypassPermissions",_=new Set(J),b=async h=>_.has(h)||y?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${h} blocked — set this agent's permission mode in ChatPanel to enable it.`};let m=!1;const p=U(e),c={sawText:!1,tail:"",boundary:!1,harnessChars:ne({prompt:p,system:t})};let l="";const w=n({prompt:p,options:{cwd:f,permissionMode:u,includePartialMessages:!0,canUseTool:b,abortController:a,settingSources:r.useLocalConfig===!1?[]:["user","project"],systemPrompt:t?{type:"preset",preset:"claude_code",append:t}:{type:"preset",preset:"claude_code"},...r.model?{model:r.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const h of w){const T=ee(h,i,m,f,c);T.streamed&&(m=!0),T.result!=null&&(l=T.result)}}catch(h){if(s?.aborted||a.signal.aborted)return;throw h}i({type:"done",text:m?"":l})}async function He({prompt:e,system:t,model:r}){const i=await j();if(!i)throw new Error(M);const{query:s}=i;let o="";const n=s({prompt:e,options:{cwd:P.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:t||"Continue the user's text briefly. Reply with only the continuation.",model:r||"haiku"}});for await(const a of n)if(a.type==="assistant")for(const u of a.message.content)u.type==="text"&&(o+=u.text);else a.type==="result"&&a.subtype==="success"&&!o&&(o=a.result||"");return o.trim()}export{it as _resetEffortProbe,Oe as answerControlRequest,st as available,Re as buildClaudeLaunch,Ne as channelMcpTools,Pe as channelToolPolicy,lt as chat,je as chatCold,Me as claudeMcpConfig,Ie as claudePrompt,$e as claudeSupportsEffort,We as claudeSupportsSystemPromptFile,ct as complete,ee as handleMessage,ne as harnessChars,at as listModels,Ce as writeImages};
@@ -1 +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};
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 --ignore-scripts`, 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};
package/src/server.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as ye}from"node:http";import P from"node:os";import{randomBytes as be,randomInt as Se,timingSafeEqual as ke}from"node:crypto";import{mkdirSync as Te,writeFileSync as ve,readFileSync as K,existsSync as Ce}from"node:fs";import{join as H}from"node:path";import*as Ee from"./engines/claude.js";import*as Oe from"./engines/codex.js";import*as xe from"./engines/antigravity.js";import{pi as Ae,opencode as Pe,kiro as $e,copilot as Ie,deepseek as Ne,hermes as Re}from"./engines/cli-agents.js";import{connectorsFor as _e}from"./connectors.js";import*as He from"./engines/custom.js";import{installService as Me,uninstallService as Be,serviceStatus as Ge,restartService as V}from"./service.js";import{skillIndex as W,listRecords as De,readRecord as Ue,readPackageFile as We,skillsHealth as Le,quarantinedSkills as je}from"./skills.js";import{capabilityToolSpecs as Je,runCapabilityTool as Fe}from"./mcp-capabilities.js";import{createSession as Xe,deleteSession as Y,getSession as Q,activeSession as ze,relayToolCall as Ke}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ve,isDefaultWorkdir as Ye,resolveWorkdir as Qe,writeScopeNote as Ze}from"./workdir.js";import{sandbox as Z,runSandboxCli as qe,withGrant as q,acceptRefusalReport as et,liveProcesses as tt}from"./sandbox.js";import{gitState as nt,gitDelta as ot}from"./scm.js";import{listConnections as rt,putConnection as at,removeConnection as it,runEnvFor as st,testConnection as ct,secretBackend as ee}from"./connections.js";import{worktreeFor as te,listWorktrees as lt,removeWorktree as dt,withHook as ut,WORKTREE_ROOT as ne}from"./worktree.js";import{AGENT_CLIS as pt,enrichPath as ht,enrichAgentEnv as mt,findAgentBin as oe,resolveCommand as ft}from"./env.js";import"./sanitize.js";import{checkForUpdate as gt,selfUpdate as re,isEmbedded as wt}from"./update.js";import{callLocalMcp as yt,localMcpStatus as bt,signInLocalMcp as St,signInStatusLocalMcp as kt}from"./mcp-local.js";import{assertPublicHttpUrl as ae,assertPublicWebUrl as ie}from"./ssrf.js";import{startRun as se,endRun as L,cancelRun as Tt,cancelAll as vt}from"./runs.js";import{closeWarmPools as Ct,warmStatus as Et}from"./warm.js";import{CompatError as $,anthropicError as j,anthropicStream as Ot,chatCompletionStream as xt,completionStream as At,createAnthropicMessage as Pt,createChatCompletion as $t,createCompletion as It,createResponse as Nt,openAIError as b,parseAnthropicMessage as Rt,parseChatCompletion as _t,parseCompletion as Ht,parseResponse as Mt,responseStream as Bt}from"./api-compat.js";import{callerTrust as Gt,isPaired as I,parseExtensionIds as Dt,capRunOptions as Ut,engineHonoursReach as Wt,createPairingStore as Lt,formatPairingCode as jt}from"./pii/trust.js";const w="0.20.1",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Ee,label:"Claude Code"},codex:{engine:Oe,label:"Codex"},antigravity:{engine:xe,label:"Antigravity",tools:!1},pi:{engine:Ae,label:"Pi"},opencode:{engine:Pe,label:"OpenCode"},hermes:{engine:Re,label:"Hermes"},kiro:{engine:$e,label:"Kiro"},copilot:{engine:Ie,label:"GitHub Copilot"},deepseek:{engine:Ne,label:"DeepSeek Harness"},custom:{engine:He,label:"Custom",hidden:!0}};function ce(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Jt=Dt(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Gt({origin:n.headers.origin||"",hasToken:pe(n),extensionIds:Jt})),n.chatpanelTrust}function Ft(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Xt(n,e){const t=n.headers.origin||"",r=ce(t);e.setHeader("Access-Control-Allow-Origin",r?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function zt(n){if(!J.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(t)}const R=H(P.homedir(),".chatpanel","bridge-token");let S="";function Kt(){try{Ce(R)&&(S=K(R,"utf8").trim()),S||(S=be(32).toString("hex"),Te(H(P.homedir(),".chatpanel"),{recursive:!0}),ve(R,S,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const le=Lt({random:()=>Se(0,1e6)/1e6});function Vt(n){if(!S)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=le.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Yt(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=le.claim(t?.code);return r.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${N(n)} caller`),i(e,403,{error:r.reason}))}function Qt(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:w})}let M=null;async function de(){if(M)return M;const{createChannelService:n}=await import("./channels/service.js");return M=n({home:H(P.homedir(),".chatpanel"),dataDir:H(P.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),M}async function ue(n,e,t){try{const r=await de(),o=n.method==="POST"?await f(n):{};if(t==="status")return i(e,200,await r.status());if(t==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await r.pair()):t==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?i(e,200,await r.update(o)):t==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function pe(n){if(!S)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const r=Buffer.from(t),o=Buffer.from(S);return r.length===o.length&&ke(r,o)}const Zt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),qt=new Set(["/debug"]),en=n=>qt.has(n);function tn(n,e){if(!zt(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ce(t))return"forbidden origin";const r=n.method==="POST"&&Zt.has(e)||n.method==="GET"&&en(e);return r&&!(Ft(t)||pe(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I(N(n))&&!on.has(e)?nn:null}const nn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",on=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(n,e,t){const r=N(n),o=Ut(t,r);if(!Wt(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=o.reach,s=I(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:o,note:s}}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let r="";n.on("data",o=>{r+=o,r.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){t(o)}}),n.on("error",t)})}async function rn(n){const e=await Promise.all(Object.entries(C).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:d,tools:c}])=>{const l=await s.available().catch(g=>({ok:!1,reason:String(g?.message||g)})),p=await _e(a).catch(()=>[]);return{id:a,label:d,available:l.ok,reason:l.reason,connectors:p,...c===!1?{tools:!1}:{}}})),t=wt()?{current:w,updateAvailable:!1,embedded:"gateway"}:await gt(w).catch(()=>({current:w,updateAvailable:!1})),r=await Le().catch(()=>null),o=await Z().status().catch(a=>({enabled:!1,reason:a.message}));i(n,200,{ok:!0,version:w,agents:e,update:t,workspace:Ve,sandbox:o,localMcp:bt(),processes:tt(),worktrees:ne,secretBackend:ee(),warm:Et(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function an(n,e,t){const{index:r,problems:o}=await W({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:De(r),problems:o})}async function sn(n,e,t){i(n,200,{ok:!0,quarantined:await je(e,t)})}async function cn(n,e,t,r){const{index:o}=await W({extraDirs:t,workdir:r}),a=Ue(o,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function ln(n,e,t,r,o){const{index:a}=await W({extraDirs:r,workdir:o}),s=await We(a,e,t);if(s.error)return i(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(n,200,{ok:!0,...s})}async function dn(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function he(n,e=""){const t=await dn();if(e){const r=t.find(o=>o.id===e);return r?i(n,200,r):i(n,404,b(new $(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function un(n){try{const e=await re(w);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function pn(n,e){let t;try{t=await f(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=F(n,t.agent,t.options||{});if(o.error)return i(e,403,{error:o.error});t.options=o.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
2
+ import{createServer as ye}from"node:http";import P from"node:os";import{randomBytes as be,randomInt as Se,timingSafeEqual as ke}from"node:crypto";import{mkdirSync as Te,writeFileSync as ve,readFileSync as K,existsSync as Ce}from"node:fs";import{join as H}from"node:path";import*as Ee from"./engines/claude.js";import*as Oe from"./engines/codex.js";import*as xe from"./engines/antigravity.js";import{pi as Ae,opencode as Pe,kiro as $e,copilot as Ie,deepseek as Ne,hermes as Re}from"./engines/cli-agents.js";import{connectorsFor as _e}from"./connectors.js";import*as He from"./engines/custom.js";import{installService as Me,uninstallService as Be,serviceStatus as Ge,restartService as V}from"./service.js";import{skillIndex as W,listRecords as De,readRecord as Ue,readPackageFile as We,skillsHealth as Le,quarantinedSkills as je}from"./skills.js";import{capabilityToolSpecs as Je,runCapabilityTool as Fe}from"./mcp-capabilities.js";import{createSession as Xe,deleteSession as Y,getSession as Q,activeSession as ze,relayToolCall as Ke}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ve,isDefaultWorkdir as Ye,resolveWorkdir as Qe,writeScopeNote as Ze}from"./workdir.js";import{sandbox as Z,runSandboxCli as qe,withGrant as q,acceptRefusalReport as et,liveProcesses as tt}from"./sandbox.js";import{gitState as nt,gitDelta as ot}from"./scm.js";import{listConnections as rt,putConnection as at,removeConnection as it,runEnvFor as st,testConnection as ct,secretBackend as ee}from"./connections.js";import{worktreeFor as te,listWorktrees as lt,removeWorktree as dt,withHook as ut,WORKTREE_ROOT as ne}from"./worktree.js";import{AGENT_CLIS as pt,enrichPath as ht,enrichAgentEnv as mt,findAgentBin as oe,resolveCommand as ft}from"./env.js";import"./sanitize.js";import{checkForUpdate as gt,selfUpdate as re,isEmbedded as wt}from"./update.js";import{callLocalMcp as yt,localMcpStatus as bt,signInLocalMcp as St,signInStatusLocalMcp as kt}from"./mcp-local.js";import{assertPublicHttpUrl as ae,assertPublicWebUrl as ie}from"./ssrf.js";import{startRun as se,endRun as L,cancelRun as Tt,cancelAll as vt}from"./runs.js";import{closeWarmPools as Ct,warmStatus as Et}from"./warm.js";import{CompatError as $,anthropicError as j,anthropicStream as Ot,chatCompletionStream as xt,completionStream as At,createAnthropicMessage as Pt,createChatCompletion as $t,createCompletion as It,createResponse as Nt,openAIError as b,parseAnthropicMessage as Rt,parseChatCompletion as _t,parseCompletion as Ht,parseResponse as Mt,responseStream as Bt}from"./api-compat.js";import{callerTrust as Gt,isPaired as I,parseExtensionIds as Dt,capRunOptions as Ut,engineHonoursReach as Wt,createPairingStore as Lt,formatPairingCode as jt}from"./pii/trust.js";const w="0.21.1",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Ee,label:"Claude Code"},codex:{engine:Oe,label:"Codex"},antigravity:{engine:xe,label:"Antigravity",tools:!1},pi:{engine:Ae,label:"Pi"},opencode:{engine:Pe,label:"OpenCode"},hermes:{engine:Re,label:"Hermes"},kiro:{engine:$e,label:"Kiro"},copilot:{engine:Ie,label:"GitHub Copilot"},deepseek:{engine:Ne,label:"DeepSeek Harness"},custom:{engine:He,label:"Custom",hidden:!0}};function ce(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Jt=Dt(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Gt({origin:n.headers.origin||"",hasToken:pe(n),extensionIds:Jt})),n.chatpanelTrust}function Ft(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Xt(n,e){const t=n.headers.origin||"",r=ce(t);e.setHeader("Access-Control-Allow-Origin",r?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function zt(n){if(!J.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(t)}const R=H(P.homedir(),".chatpanel","bridge-token");let S="";function Kt(){try{Ce(R)&&(S=K(R,"utf8").trim()),S||(S=be(32).toString("hex"),Te(H(P.homedir(),".chatpanel"),{recursive:!0}),ve(R,S,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const le=Lt({random:()=>Se(0,1e6)/1e6});function Vt(n){if(!S)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=le.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Yt(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=le.claim(t?.code);return r.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${N(n)} caller`),i(e,403,{error:r.reason}))}function Qt(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:w})}let M=null;async function de(){if(M)return M;const{createChannelService:n}=await import("./channels/service.js");return M=n({home:H(P.homedir(),".chatpanel"),dataDir:H(P.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),M}async function ue(n,e,t){try{const r=await de(),o=n.method==="POST"?await f(n):{};if(t==="status")return i(e,200,await r.status());if(t==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await r.pair()):t==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?i(e,200,await r.update(o)):t==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function pe(n){if(!S)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const r=Buffer.from(t),o=Buffer.from(S);return r.length===o.length&&ke(r,o)}const Zt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),qt=new Set(["/debug"]),en=n=>qt.has(n);function tn(n,e){if(!zt(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ce(t))return"forbidden origin";const r=n.method==="POST"&&Zt.has(e)||n.method==="GET"&&en(e);return r&&!(Ft(t)||pe(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I(N(n))&&!on.has(e)?nn:null}const nn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",on=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(n,e,t){const r=N(n),o=Ut(t,r);if(!Wt(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=o.reach,s=I(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:o,note:s}}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let r="";n.on("data",o=>{r+=o,r.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){t(o)}}),n.on("error",t)})}async function rn(n){const e=await Promise.all(Object.entries(C).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:d,tools:c}])=>{const l=await s.available().catch(g=>({ok:!1,reason:String(g?.message||g)})),p=await _e(a).catch(()=>[]);return{id:a,label:d,available:l.ok,reason:l.reason,connectors:p,...c===!1?{tools:!1}:{}}})),t=wt()?{current:w,updateAvailable:!1,embedded:"gateway"}:await gt(w).catch(()=>({current:w,updateAvailable:!1})),r=await Le().catch(()=>null),o=await Z().status().catch(a=>({enabled:!1,reason:a.message}));i(n,200,{ok:!0,version:w,agents:e,update:t,workspace:Ve,sandbox:o,localMcp:bt(),processes:tt(),worktrees:ne,secretBackend:ee(),warm:Et(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function an(n,e,t){const{index:r,problems:o}=await W({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:De(r),problems:o})}async function sn(n,e,t){i(n,200,{ok:!0,quarantined:await je(e,t)})}async function cn(n,e,t,r){const{index:o}=await W({extraDirs:t,workdir:r}),a=Ue(o,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function ln(n,e,t,r,o){const{index:a}=await W({extraDirs:r,workdir:o}),s=await We(a,e,t);if(s.error)return i(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(n,200,{ok:!0,...s})}async function dn(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function he(n,e=""){const t=await dn();if(e){const r=t.find(o=>o.id===e);return r?i(n,200,r):i(n,404,b(new $(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function un(n){try{const e=await re(w);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function pn(n,e){let t;try{t=await f(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=F(n,t.agent,t.options||{});if(o.error)return i(e,403,{error:o.error});t.options=o.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
3
3
 
4
4
  `)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=se(d),l={signal:c.signal,abort:()=>c.cancel("client")},p=()=>{s=!0,c.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const g=h=>{s||a(h)};a({type:"run",id:d}),o.note&&a({type:"status",text:o.note});let m=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(m=await te({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),m.error){a({type:"error",error:`workspace: ${m.error}`}),L(d),e.writableEnded||e.end();return}}const X=m?m.path:Qe(t.options?.workingDir);let E=null;{const h=X,O=!!m||!Ye(t.options?.workingDir),y=Ze(t.agent,t.options?.permissionMode,h);a({type:"workdir",path:h,isDefault:!O,writeScope:y||void 0}),a({type:"status",text:`Working in ${h}${O?"":" (default)"}`}),y&&a({type:"status",text:y}),E=await nt(h),E&&a({type:"scm",phase:"before",...E})}let U=null;if(E||m){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:O,connection:y}=st({remote:E?.remote||null,grants:h,branch:m?.branch||null,connectionId:t.options?.connectionId||null});U=ut(O),m&&a({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&a({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const z=t.approvals===!0,_={...t.options||{},...m?{workingDir:m.path}:{},...U?{runEnv:U}:{},approvals:z};let A=null;(t.pageTools?.specs?.length||z)&&(A=Xe(g,t.pageTools?.specs||[]),_.permissionSession=A,t.pageTools?.specs?.length&&(_.mcp={url:`http://${k}:${v}/mcp/${A.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));try{await q(_.sandbox,()=>r.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:_,images:Array.isArray(t.images)?t.images:[]},g,{signal:l.signal}))}catch(h){u("error",`${t.agent} chat failed: ${h?.message||h}`),a({type:"error",error:h?.message||String(h)})}finally{if(!s){const h=await ot(X,E).catch(()=>null);h&&g({type:"scm",phase:"after",...h})}L(d),A&&Y(A.id),e.writableEnded||e.end()}}async function hn(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:rt(),secretBackend:ee()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:at(r.connection||r,{token:r.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return o?o[2]==="delete"?i(e,200,{ok:it(o[1])}):i(e,200,ct(o[1],r.remote||"")):i(e,404,{error:"Not found"})}async function mn(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:ne,worktrees:await lt()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/worktrees"){const o=await te({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return i(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(t==="/worktrees/remove"){const o=await dt({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return i(e,o.ok?200:400,o)}return i(e,404,{error:"Not found"})}async function T(n,e,t){const r=C[n.agent];if(!r||r.hidden)throw new $(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const o=await r.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!o.ok)throw new $(o.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=se(a),d=()=>s.cancel("disconnected");t.on("close",d);let c="";try{return await q(n.options?.sandbox,()=>r.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal})),c}finally{t.off("close",d),L(a)}}function B(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
5
5
 
package/src/warm-pool.js CHANGED
@@ -1 +1 @@
1
- import{treeRssBytes as B,totalMemoryBytes as L}from"./proc.js";const $=1024**3,w=L(),D=Number(process.env.CHATPANEL_WARM_MAX)||(w>=32*$?3:w>=16*$?2:1),N=Number(process.env.CHATPANEL_WARM_IDLE_MS)||(w>=16*$?10*6e4:5*6e4),R=Number(process.env.CHATPANEL_WARM_BUDGET_MB)*1024**2||Math.min(Math.floor(w*.2),3*$),k=400*1024**2,z=new Set;function S(i=[]){const n=(Array.isArray(i)?i:[]).slice(0,-1),d=n.filter(l=>l?.role==="user").map(l=>String(l.content||"").trim()),f=n.filter(l=>l?.role==="assistant").length;return{users:d,answers:f}}function U(i,u){if(i.answers!==u.answers||i.users.length!==u.users.length)return!1;for(let n=0;n<i.users.length;n++)if(i.users[n]!==u.users[n])return!1;return!0}function x({max:i=D,idleMs:u=N,budgetBytes:n=R,group:d=z,now:f=Date.now,measure:l=r=>B(r?.pid),log:p=()=>{}}={}){const r=new Set;let h=null;const v=()=>{let e=0;for(const s of d)e+=s.bytes;return e};let _=0;const c=e=>`${Math.round(e/1024**2)} MB`;function m(e,s="dropped"){if(r.has(e)){r.delete(e),e.alive=!1;try{e.session?.close?.(s)}catch{}p(`warm ${e.label}: ${s} (${r.size} live)`),!r.size&&h&&(clearInterval(h),h=null)}}function M(){const e=f();for(const s of[...r])!s.busy&&e-s.lastUsed>u&&m(s,"idle")}function y(){h||!Number.isFinite(u)||u<=0||(h=setInterval(M,Math.min(u,6e4)),h.unref?.())}const E={get size(){return r.size},get bytes(){let e=0;for(const s of r)e+=s.bytes||0;return e},peek({key:e,messages:s}){const o=S(s);for(const t of r)if(!t.busy&&t.alive&&t.key===e&&U(t.shape,o))return!0;return!1},acquire({key:e,messages:s}){const o=S(s);for(const t of r)if(!(t.busy||!t.alive||t.key!==e)){if(!U(t.shape,o)){p(`warm ${t.label}: shape differs (have ${t.shape.users.length}u/${t.shape.answers}a, asked ${o.users.length}u/${o.answers}a)`);continue}return t.busy=!0,t.lastUsed=f(),p(`warm ${t.label}: reused`),t}return null},reserve({key:e,label:s=e,evict:o=!0}){const t=()=>{let a=null;for(const b of r)!b.busy&&(!a||b.lastUsed<a.lastUsed)&&(a=b);return a};if(r.size>=i){const a=o?t():null;if(!a)return null;m(a,"evicted")}const A=_||k;for(;v()+A>n;){const a=o?t():null;if(!a)return p(`warm ${s}: not kept — ${c(v())} warm + ~${c(A)} would pass the ${c(n)} budget`),null;m(a,`evicted for memory (${c(v())} warm)`)}const T={key:e,label:s,session:null,shape:{users:[],answers:0},busy:!0,alive:!0,lastUsed:f(),bytes:A};return r.add(T),p(`warm ${s}: starting (${r.size} live, ~${c(v())} of ${c(n)})`),y(),T},attach(e,s){return e.session=s,s.onExit?.(()=>{e.alive&&m(e,"process exited")}),e},release(e,{user:s,answered:o}){e.alive&&(typeof s=="string"&&(e.shape={users:[...e.shape.users,s.trim()],answers:e.shape.answers+(o?1:0)}),e.busy=!1,e.lastUsed=f(),setImmediate(()=>{if(!e.alive)return;const t=l(e.session);t>0&&(e.bytes=t,_=t,p(`warm ${e.label}: ${c(t)} resident`))}))},drop:m,closeAll(e="shutdown"){for(const s of[...r])m(s,e)},keys(){return[...r].map(e=>e.key)},reap:M};return d.add(E),E}export{R as WARM_BUDGET_BYTES,x as createWarmPool,S as historyShape};
1
+ import{treeRssBytes as R,totalMemoryBytes as B}from"./proc.js";const v=1024**3,A=B(),D=Number(process.env.CHATPANEL_WARM_IDLE_MS)||(A>=16*v?10*6e4:5*6e4),S=Number(process.env.CHATPANEL_WARM_BUDGET_MB)*1024**2||Math.min(Math.floor(A*.2),3*v),U=400*1024**2;function N(n,a,o=U){const p=Math.floor(a/o),l=n>=48*v?4:n>=24*v?3:n>=12*v?2:1;return Math.max(1,Math.min(p,l))}const k=Number(process.env.CHATPANEL_WARM_MAX)||N(A,S),z=new Set;function x(n=[]){const o=(Array.isArray(n)?n:[]).slice(0,-1),p=o.filter(c=>c?.role==="user").map(c=>String(c.content||"").trim()),l=o.filter(c=>c?.role==="assistant").length;return{users:p,answers:l}}function y(n,a){if(n.answers!==a.answers||n.users.length!==a.users.length)return!1;for(let o=0;o<n.users.length;o++)if(n.users[o]!==a.users[o])return!1;return!0}function W({max:n=k,idleMs:a=D,budgetBytes:o=S,group:p=z,now:l=Date.now,measure:c=r=>R(r?.pid),log:h=()=>{}}={}){const r=new Set;let m=null;const $=()=>{let e=0;for(const s of p)e+=s.bytes;return e};let M=0;const f=e=>`${Math.round(e/1024**2)} MB`;function d(e,s="dropped"){if(r.has(e)){r.delete(e),e.alive=!1;try{e.session?.close?.(s)}catch{}h(`warm ${e.label}: ${s} (${r.size} live)`),!r.size&&m&&(clearInterval(m),m=null)}}function _(){const e=l();for(const s of[...r])!s.busy&&e-s.lastUsed>a&&d(s,"idle")}function L(){m||!Number.isFinite(a)||a<=0||(m=setInterval(_,Math.min(a,6e4)),m.unref?.())}const E={get size(){return r.size},get bytes(){let e=0;for(const s of r)e+=s.bytes||0;return e},peek({key:e,messages:s}){const i=x(s);for(const t of r)if(!t.busy&&t.alive&&t.key===e&&y(t.shape,i))return!0;return!1},acquire({key:e,messages:s}){const i=x(s);for(const t of r)if(!(t.busy||!t.alive||t.key!==e)){if(!y(t.shape,i)){h(`warm ${t.label}: shape differs (have ${t.shape.users.length}u/${t.shape.answers}a, asked ${i.users.length}u/${i.answers}a)`);continue}return t.busy=!0,t.lastUsed=l(),h(`warm ${t.label}: reused`),t}return null},reserve({key:e,label:s=e,evict:i=!0}){const t=()=>{let u=null;for(const b of r)!b.busy&&(!u||b.lastUsed<u.lastUsed)&&(u=b);return u};if(r.size>=n){const u=i?t():null;if(!u)return null;d(u,"evicted")}const w=M||U;for(;$()+w>o;){const u=i?t():null;if(!u)return h(`warm ${s}: not kept — ${f($())} warm + ~${f(w)} would pass the ${f(o)} budget`),null;d(u,`evicted for memory (${f($())} warm)`)}const T={key:e,label:s,session:null,shape:{users:[],answers:0},busy:!0,alive:!0,lastUsed:l(),bytes:w};return r.add(T),h(`warm ${s}: starting (${r.size} live, ~${f($())} of ${f(o)})`),L(),T},attach(e,s){return e.session=s,s.onExit?.(()=>{e.alive&&d(e,"process exited")}),e},release(e,{user:s,answered:i}){e.alive&&(typeof s=="string"&&(e.shape={users:[...e.shape.users,s.trim()],answers:e.shape.answers+(i?1:0)}),e.busy=!1,e.lastUsed=l(),setImmediate(()=>{if(!e.alive)return;const t=c(e.session);t>0&&(e.bytes=t,M=t,h(`warm ${e.label}: ${f(t)} resident`))}))},drop:d,closeAll(e="shutdown"){for(const s of[...r])d(s,e)},keys(){return[...r].map(e=>e.key)},reap:_};return p.add(E),E}export{S as WARM_BUDGET_BYTES,W as createWarmPool,x as historyShape,N as warmMaxFor};