@chatpanel/bridge 0.12.3 → 0.12.4

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.12.3",
3
+ "version": "0.12.4",
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,8 +1,8 @@
1
- import{spawn as J}from"node:child_process";import{writeFile as L,unlink as N}from"node:fs/promises";import A from"node:os";import W from"node:path";import{resolveClaude as v,buildSpawnSpec as X,isCompiledBinary as K,selfMcpStdio as Q}from"../env.js";import{signInStatus as V,signInMessage as I,loginRequired as Z}from"../sign-in.js";import{buildCliPrompt as R}from"./prompt.js";import{summarizeCliError as ee}from"../cli-errors.js";import{killOnAbort as te}from"../proc.js";import{pushExtraArgs as re,FORBIDDEN as oe}from"./args.js";import{relayTimeoutMax as ne}from"../relay-timeout.js";import{displayPath as se,resolveWorkdir as j}from"../workdir.js";import{connectorsFor as ae}from"../connectors.js";import{chatWarm as le}from"./claude-warm.js";async function ie(e,t){const o=[];for(let l=0;l<(e?.length||0);l++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[l]?.dataUrl||"");if(!s)continue;const n=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",r=W.join(A.tmpdir(),`chatpanel-claude-img-${t}-${l}.${n}`);await L(r,Buffer.from(s[2],"base64")),o.push(r)}return o}const D=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,H=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task"],z=Object.freeze({device:Object.freeze(["TodoWrite","Task"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),ce=Object.freeze(["Bash","Edit","Write","WebFetch","WebSearch"]),ue=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),de=Object.freeze(["remember","forget"]),U=Object.freeze({device:Object.freeze([]),trusted:ue});function pe(e,t=[]){const o=U[e]||U.device,l=(t||[]).filter(r=>typeof r=="string"&&/^chatpanel/i.test(r)),s=[],n=[];for(const r of l){for(const a of o)s.push(`mcp__${r}__${a}`);for(const a of de)n.push(`mcp__${r}__${a}`)}return{allow:s,deny:n}}function fe(e){return!e||e==="any"?null:{allow:[...z[e]||z.device],deny:[...ce]}}let C="Claude Code not found.",B=0,b=!1;async function Ie(){if(Date.now()-B>(b?3e4:4e3)){B=Date.now();try{v()||!K()&&await O()?b=!0:(b=!1,C=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{b=!1}}return b?await V("claude",v()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:I("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:C}}async function Re(){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:o,args:l}=Q(e.url),s=[...new Set(e.specs.map(n=>n?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:o,args:l}}},allowedTools:s.map(n=>`mcp__${t}__${n}`)}}function F({prompt:e,args:t,cwd:o,env:l=null,emit:s,signal:n}){const r=v();if(!r)return null;const[a,i,m]=X(r,t,o,l);return new Promise((y,d)=>{let u;try{u=J(a,i,m)}catch(f){return d(new Error(`Failed to start claude: ${f.message}`))}const c=te(u,n);let h="",_="",w=!1,p=null;const T={sawText:!1,tail:"",boundary:!1};let E="",x;const k=()=>{clearTimeout(x),x=setTimeout(()=>{u.kill("SIGKILL"),d(new Error(`Claude Code timed out — no output for ${Math.round(D/1e3)}s.`))},D)};k(),u.stdout.on("data",f=>{k(),h+=f.toString();let S;for(;(S=h.indexOf(`
2
- `))>=0;){const P=h.slice(0,S).trim();if(h=h.slice(S+1),!P.startsWith("{"))continue;let $;try{$=JSON.parse(P)}catch{continue}const g=Y($,s,w,o,T);g.streamed&&(w=!0),g.result!=null&&(E=g.result),g.apiError&&(p=g.apiError)}}),u.stderr.on("data",f=>{k(),_+=f.toString()}),u.on("error",f=>{clearTimeout(x),c(),d(new Error(`Failed to start claude (${a}): ${f.message}`))}),u.on("close",f=>{if(clearTimeout(x),c(),n?.aborted){y({streamedAny:w,resultText:E});return}if(p&&Z(p))return d(new Error(I("Claude Code","claude")));if(f===0&&p)return d(new Error(`Claude Code reported an error: ${p}`));f===0?y({streamedAny:w,resultText:E}):d(new Error(ee("Claude Code",f,_,p||"",{agentId:"claude"})))}),u.stdin.write(e),u.stdin.end()})}function he(e){let t="";return typeof e=="string"?t=e:Array.isArray(e)&&(t=e.map(o=>typeof o=="string"?o:o?.text||"").filter(Boolean).join(`
3
- `)),t.length>4e3?`${t.slice(0,4e3)}…`:t}function G(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
1
+ import{spawn as $}from"node:child_process";import{writeFile as W,unlink as I}from"node:fs/promises";import M from"node:os";import R from"node:path";import{resolveClaude as C,buildSpawnSpec as D,isCompiledBinary as V,selfMcpStdio as Z}from"../env.js";import{signInStatus as ee,signInMessage as j,loginRequired as te}from"../sign-in.js";import{buildCliPrompt as F}from"./prompt.js";import{summarizeCliError as re}from"../cli-errors.js";import{killOnAbort as oe}from"../proc.js";import{pushExtraArgs as ne,FORBIDDEN as se}from"./args.js";import{relayTimeoutMax as ae}from"../relay-timeout.js";import{displayPath as le,resolveWorkdir as H}from"../workdir.js";import{connectorsFor as ie}from"../connectors.js";import{chatWarm as ce}from"./claude-warm.js";async function ue(e,t){const o=[];for(let l=0;l<(e?.length||0);l++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[l]?.dataUrl||"");if(!s)continue;const n=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",r=R.join(M.tmpdir(),`chatpanel-claude-img-${t}-${l}.${n}`);await W(r,Buffer.from(s[2],"base64")),o.push(r)}return o}const U=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,z=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task"],B=Object.freeze({device:Object.freeze(["TodoWrite","Task"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),de=Object.freeze(["Bash","Edit","Write","WebFetch","WebSearch"]),pe=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),fe=Object.freeze(["remember","forget"]),G=Object.freeze({device:Object.freeze([]),trusted:pe});function me(e,t=[]){const o=G[e]||G.device,l=(t||[]).filter(r=>typeof r=="string"&&/^chatpanel/i.test(r)),s=[],n=[];for(const r of l){for(const a of o)s.push(`mcp__${r}__${a}`);for(const a of fe)n.push(`mcp__${r}__${a}`)}return{allow:s,deny:n}}function he(e){return!e||e==="any"?null:{allow:[...B[e]||B.device],deny:[...de]}}let k="Claude Code not found.",q=0,b=!1;async function je(){if(Date.now()-q>(b?3e4:4e3)){q=Date.now();try{C()||!V()&&await O()?b=!0:(b=!1,k=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{b=!1}}return b?await ee("claude",C()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:j("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:k}}async function Fe(){return["opus","sonnet","haiku"]}function ye(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:o,args:l}=Z(e.url),s=[...new Set(e.specs.map(n=>n?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:o,args:l}}},allowedTools:s.map(n=>`mcp__${t}__${n}`)}}function Y({prompt:e,args:t,cwd:o,env:l=null,emit:s,signal:n}){const r=C();if(!r)return null;const[a,i,m]=D(r,t,o,l);return new Promise((y,d)=>{let u;try{u=$(a,i,m)}catch(f){return d(new Error(`Failed to start claude: ${f.message}`))}const c=oe(u,n);let h="",_="",w=!1,p=null;const T={sawText:!1,tail:"",boundary:!1};let S="",E;const A=()=>{clearTimeout(E),E=setTimeout(()=>{u.kill("SIGKILL"),d(new Error(`Claude Code timed out — no output for ${Math.round(U/1e3)}s.`))},U)};A(),u.stdout.on("data",f=>{A(),h+=f.toString();let v;for(;(v=h.indexOf(`
2
+ `))>=0;){const L=h.slice(0,v).trim();if(h=h.slice(v+1),!L.startsWith("{"))continue;let N;try{N=JSON.parse(L)}catch{continue}const g=K(N,s,w,o,T);g.streamed&&(w=!0),g.result!=null&&(S=g.result),g.apiError&&(p=g.apiError)}}),u.stderr.on("data",f=>{A(),_+=f.toString()}),u.on("error",f=>{clearTimeout(E),c(),d(new Error(`Failed to start claude (${a}): ${f.message}`))}),u.on("close",f=>{if(clearTimeout(E),c(),n?.aborted){y({streamedAny:w,resultText:S});return}if(p&&te(p))return d(new Error(j("Claude Code","claude")));if(f===0&&p)return d(new Error(`Claude Code reported an error: ${p}`));f===0?y({streamedAny:w,resultText:S}):d(new Error(re("Claude Code",f,_,p||"",{agentId:"claude"})))}),u.stdin.write(e),u.stdin.end()})}function _e(e){let t="";return typeof e=="string"?t=e:Array.isArray(e)&&(t=e.map(o=>typeof o=="string"?o:o?.text||"").filter(Boolean).join(`
3
+ `)),t.length>4e3?`${t.slice(0,4e3)}…`:t}function J(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
4
4
 
5
- `}),e.boundary=!1)}function q(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function Y(e,t,o,l="",s=null){const n={streamed:!1,result:null};if(e.type==="stream_event"){const r=e.event;r?.type==="content_block_delta"&&(r.delta?.type==="text_delta"?(n.streamed=!0,G(s,t),t({type:"delta",text:r.delta.text}),q(s,r.delta.text)):r.delta?.type==="thinking_delta"&&t({type:"reasoning",text:r.delta.thinking||""}))}else if(e.type==="assistant"){if(e.is_api_error_message||e.error)return n.apiError=(e.message?.content||[]).filter(r=>r.type==="text").map(r=>r.text).join(`
6
- `)||String(e.error||"api error"),n;for(const r of e.message?.content||[])r.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:r.name,phase:"start",callId:r.id,input:r.input,summary:be(r,l)})):r.type==="text"&&!o&&(n.streamed=!0,G(s,t),t({type:"delta",text:r.text}),q(s,r.text))}else if(e.type==="user")for(const r of e.message?.content||[])r.type==="tool_result"&&t({type:"tool",phase:"done",callId:r.tool_use_id,status:r.is_error?"error":"ok",result:he(r.content)});else if(e.type==="result"){e.is_error?n.apiError=n.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?n.result=e.result||"":t({type:"status",text:`(${e.subtype})`});const r=e.usage||e.message?.usage;r&&t({type:"usage",provider:"bridge",inputTokens:r.input_tokens||0,outputTokens:r.output_tokens||0,cacheReadTokens:r.cache_read_input_tokens||0,cacheWriteTokens:r.cache_creation_input_tokens||0,costUsd:e.total_cost_usd!=null?e.total_cost_usd:null})}return n}async function ye({system:e,options:t,tag:o}){const l=t.permissionMode||"default",s=j(t.workingDir),n=["--print","--output-format","stream-json","--include-partial-messages","--verbose"],r=[],a=[],i=me(t.mcp);if(i){const c=W.join(A.tmpdir(),`chatpanel-mcp-${o}.json`);await L(c,JSON.stringify(i.config)),r.push(c),n.push("--mcp-config",c),a.push(...i.allowedTools)}const m=fe(t.reach);if(m){const c=pe(t.reach,await ae("claude").catch(()=>[]));n.push("--allowedTools",...m.allow,...a,...c.allow),n.push("--disallowedTools",...m.deny,...c.deny)}else l==="bypassPermissions"?n.push("--permission-mode","bypassPermissions"):l==="acceptEdits"?(n.push("--permission-mode","acceptEdits"),a.length&&n.push("--allowedTools",...a)):n.push("--allowedTools",...H,...a);e&&n.push("--append-system-prompt",e),t.model&&n.push("--model",t.model),t.useLocalConfig===!1&&n.push("--setting-sources","");const y=i&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(ne(t.mcp?.specs))}:null,d=y||t.runEnv?{...t.runEnv||{},...y||{}}:null;return{args:n,cwd:s,runEnv:d,cleanup:()=>r.forEach(c=>N(c).catch(()=>{})),hasMcp:!!i}}function _e(e,t=[],o=""){let l=R(e,o);return t.length&&(l+=`
5
+ `}),e.boundary=!1)}function X(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function K(e,t,o,l="",s=null){const n={streamed:!1,result:null};if(e.type==="stream_event"){const r=e.event;r?.type==="content_block_delta"&&(r.delta?.type==="text_delta"?(n.streamed=!0,J(s,t),t({type:"delta",text:r.delta.text}),X(s,r.delta.text)):r.delta?.type==="thinking_delta"&&t({type:"reasoning",text:r.delta.thinking||""}))}else if(e.type==="assistant"){if(e.is_api_error_message||e.error)return n.apiError=(e.message?.content||[]).filter(r=>r.type==="text").map(r=>r.text).join(`
6
+ `)||String(e.error||"api error"),n;for(const r of e.message?.content||[])r.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:r.name,phase:"start",callId:r.id,input:r.input,summary:xe(r,l)})):r.type==="text"&&!o&&(n.streamed=!0,J(s,t),t({type:"delta",text:r.text}),X(s,r.text))}else if(e.type==="user")for(const r of e.message?.content||[])r.type==="tool_result"&&t({type:"tool",phase:"done",callId:r.tool_use_id,status:r.is_error?"error":"ok",result:_e(r.content)});else if(e.type==="result"){e.is_error?n.apiError=n.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?n.result=e.result||"":t({type:"status",text:`(${e.subtype})`});const r=e.usage||e.message?.usage;r&&t({type:"usage",provider:"bridge",inputTokens:r.input_tokens||0,outputTokens:r.output_tokens||0,cacheReadTokens:r.cache_read_input_tokens||0,cacheWriteTokens:r.cache_creation_input_tokens||0,costUsd:e.total_cost_usd!=null?e.total_cost_usd:null})}return n}const Q=process.env.CHATPANEL_CLAUDE_EFFORT??"low";let x=null;function we({probe:e=null}={}){return x||(x=(async()=>{try{const t=e?await e():await new Promise(o=>{const[l,s,n]=D(C(),["--help"],null),r=$(l,s,{...n,stdio:["ignore","pipe","pipe"]});let a="";r.stdout.on("data",i=>{a+=i}),r.on("error",()=>o("")),r.on("close",()=>o(a)),setTimeout(()=>{try{r.kill()}catch{}o(a)},8e3).unref?.()});return/--effort\b/.test(String(t||""))}catch{return!1}})(),x)}function He(){x=null}async function be({system:e,options:t,tag:o}){const l=t.permissionMode||"default",s=H(t.workingDir),n=["--print","--output-format","stream-json","--include-partial-messages","--verbose"];Q&&await we()&&n.push("--effort",Q);const r=[],a=[],i=ye(t.mcp);if(i){const c=R.join(M.tmpdir(),`chatpanel-mcp-${o}.json`);await W(c,JSON.stringify(i.config)),r.push(c),n.push("--mcp-config",c),a.push(...i.allowedTools)}const m=he(t.reach);if(m){const c=me(t.reach,await ie("claude").catch(()=>[]));n.push("--allowedTools",...m.allow,...a,...c.allow),n.push("--disallowedTools",...m.deny,...c.deny)}else l==="bypassPermissions"?n.push("--permission-mode","bypassPermissions"):l==="acceptEdits"?(n.push("--permission-mode","acceptEdits"),a.length&&n.push("--allowedTools",...a)):n.push("--allowedTools",...z,...a);e&&n.push("--append-system-prompt",e),t.model&&n.push("--model",t.model),t.useLocalConfig===!1&&n.push("--setting-sources","");const y=i&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(ae(t.mcp?.specs))}:null,d=y||t.runEnv?{...t.runEnv||{},...y||{}}:null;return{args:n,cwd:s,runEnv:d,cleanup:()=>r.forEach(c=>I(c).catch(()=>{})),hasMcp:!!i}}function Te(e,t=[],o=""){let l=F(e,o);return t.length&&(l+=`
7
7
 
8
- The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),l}async function je({messages:e,system:t,options:o,images:l},s,{signal:n}={}){const r=await le({messages:e,system:t,options:o,images:l},s,{signal:n}).catch(a=>({handled:!1,reason:a?.message||String(a),thrown:!0}));if(!r.handled&&!n?.aborted){if(r.thrown)throw new Error(r.reason);return we({messages:e,system:t,options:o,images:l},s,{signal:n})}}async function we({messages:e,system:t,options:o,images:l},s,{signal:n}={}){const r=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=await ye({system:t,options:o,tag:r}),{args:i,cwd:m,runEnv:y}=a,d=await ie(l,r),u=()=>{d.forEach(_=>N(_).catch(()=>{})),a.cleanup()},c=_e(e,d);re(i,o.extraArgs,oe.claude,s);const h=F({prompt:c,args:i,cwd:m,env:y,emit:s,signal:n});if(h===null)return u(),Te({messages:e,system:t,options:o},s,{signal:n});try{const{streamedAny:_,resultText:w}=await h;s({type:"done",text:_?"":w})}finally{u()}}async function De({prompt:e,system:t,model:o}){const l=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",o||"haiku","--system-prompt",t||"Continue the user's text briefly. Reply with only the continuation."];let s="";const n=F({prompt:e,args:l,cwd:null,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(n===null)return ge({prompt:e,system:t,model:o});const{resultText:r}=await n;return(s||r||"").trim()}function be(e,t=""){const o=e.input||{};return o.command?String(o.command).slice(0,60):o.file_path?se(o.file_path,t):o.pattern?o.pattern:o.url?o.url:o.description?String(o.description).slice(0,80):o.query?String(o.query).slice(0,80):o.prompt?String(o.prompt).slice(0,80):""}let M=null;function O(){return M||(M=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),M}async function Te({messages:e,system:t,options:o},l,{signal:s}={}){const n=await O();if(!n)throw new Error(C);const{query:r}=n,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const i=o.permissionMode||"default",m=j(o.workingDir),y=i==="acceptEdits"||i==="bypassPermissions",d=new Set(H),u=async p=>d.has(p)||y?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${p} blocked — set this agent's permission mode in ChatPanel to enable it.`};let c=!1;const h={sawText:!1,tail:"",boundary:!1};let _="";const w=r({prompt:R(e),options:{cwd:m,permissionMode:i,includePartialMessages:!0,canUseTool:u,abortController:a,settingSources:o.useLocalConfig===!1?[]:["user","project"],systemPrompt:t?{type:"preset",preset:"claude_code",append:t}:{type:"preset",preset:"claude_code"},...o.model?{model:o.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const p of w){const T=Y(p,l,c,m,h);T.streamed&&(c=!0),T.result!=null&&(_=T.result)}}catch(p){if(s?.aborted||a.signal.aborted)return;throw p}l({type:"done",text:c?"":_})}async function ge({prompt:e,system:t,model:o}){const l=await O();if(!l)throw new Error(C);const{query:s}=l;let n="";const r=s({prompt:e,options:{cwd:A.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:t||"Continue the user's text briefly. Reply with only the continuation.",model:o||"haiku"}});for await(const a of r)if(a.type==="assistant")for(const i of a.message.content)i.type==="text"&&(n+=i.text);else a.type==="result"&&a.subtype==="success"&&!n&&(n=a.result||"");return n.trim()}export{Ie as available,ye as buildClaudeLaunch,pe as channelMcpTools,fe as channelToolPolicy,je as chat,we as chatCold,me as claudeMcpConfig,_e as claudePrompt,De as complete,Y as handleMessage,Re as listModels,ie as writeImages};
8
+ The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),l}async function Ue({messages:e,system:t,options:o,images:l},s,{signal:n}={}){const r=await ce({messages:e,system:t,options:o,images:l},s,{signal:n}).catch(a=>({handled:!1,reason:a?.message||String(a),thrown:!0}));if(!r.handled&&!n?.aborted){if(r.thrown)throw new Error(r.reason);return ge({messages:e,system:t,options:o,images:l},s,{signal:n})}}async function ge({messages:e,system:t,options:o,images:l},s,{signal:n}={}){const r=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=await be({system:t,options:o,tag:r}),{args:i,cwd:m,runEnv:y}=a,d=await ue(l,r),u=()=>{d.forEach(_=>I(_).catch(()=>{})),a.cleanup()},c=Te(e,d);ne(i,o.extraArgs,se.claude,s);const h=Y({prompt:c,args:i,cwd:m,env:y,emit:s,signal:n});if(h===null)return u(),Ee({messages:e,system:t,options:o},s,{signal:n});try{const{streamedAny:_,resultText:w}=await h;s({type:"done",text:_?"":w})}finally{u()}}async function ze({prompt:e,system:t,model:o}){const l=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",o||"haiku","--system-prompt",t||"Continue the user's text briefly. Reply with only the continuation."];let s="";const n=Y({prompt:e,args:l,cwd:null,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(n===null)return Ce({prompt:e,system:t,model:o});const{resultText:r}=await n;return(s||r||"").trim()}function xe(e,t=""){const o=e.input||{};return o.command?String(o.command).slice(0,60):o.file_path?le(o.file_path,t):o.pattern?o.pattern:o.url?o.url:o.description?String(o.description).slice(0,80):o.query?String(o.query).slice(0,80):o.prompt?String(o.prompt).slice(0,80):""}let P=null;function O(){return P||(P=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),P}async function Ee({messages:e,system:t,options:o},l,{signal:s}={}){const n=await O();if(!n)throw new Error(k);const{query:r}=n,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const i=o.permissionMode||"default",m=H(o.workingDir),y=i==="acceptEdits"||i==="bypassPermissions",d=new Set(z),u=async p=>d.has(p)||y?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${p} blocked — set this agent's permission mode in ChatPanel to enable it.`};let c=!1;const h={sawText:!1,tail:"",boundary:!1};let _="";const w=r({prompt:F(e),options:{cwd:m,permissionMode:i,includePartialMessages:!0,canUseTool:u,abortController:a,settingSources:o.useLocalConfig===!1?[]:["user","project"],systemPrompt:t?{type:"preset",preset:"claude_code",append:t}:{type:"preset",preset:"claude_code"},...o.model?{model:o.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const p of w){const T=K(p,l,c,m,h);T.streamed&&(c=!0),T.result!=null&&(_=T.result)}}catch(p){if(s?.aborted||a.signal.aborted)return;throw p}l({type:"done",text:c?"":_})}async function Ce({prompt:e,system:t,model:o}){const l=await O();if(!l)throw new Error(k);const{query:s}=l;let n="";const r=s({prompt:e,options:{cwd:M.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:t||"Continue the user's text briefly. Reply with only the continuation.",model:o||"haiku"}});for await(const a of r)if(a.type==="assistant")for(const i of a.message.content)i.type==="text"&&(n+=i.text);else a.type==="result"&&a.subtype==="success"&&!n&&(n=a.result||"");return n.trim()}export{He as _resetEffortProbe,je as available,be as buildClaudeLaunch,me as channelMcpTools,he as channelToolPolicy,Ue as chat,ge as chatCold,ye as claudeMcpConfig,Te as claudePrompt,we as claudeSupportsEffort,ze as complete,K as handleMessage,Fe as listModels,ue as writeImages};
package/src/server.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as ce}from"node:http";import x from"node:os";import{randomBytes as le,timingSafeEqual as de}from"node:crypto";import{mkdirSync as ue,writeFileSync as he,readFileSync as pe,existsSync as me}from"node:fs";import{join as $}from"node:path";import*as fe from"./engines/claude.js";import*as ge from"./engines/codex.js";import*as ye from"./engines/antigravity.js";import{pi as we,opencode as be,kiro as Se,copilot as ke,deepseek as Te,hermes as ve}from"./engines/cli-agents.js";import{connectorsFor as Ce}from"./connectors.js";import*as Ee from"./engines/custom.js";import{installService as Oe,uninstallService as Ae,serviceStatus as xe,restartService as j}from"./service.js";import{skillIndex as B,listRecords as Pe,readRecord as $e,readPackageFile as Ie,skillsHealth as Ne,quarantinedSkills as Re}from"./skills.js";import{capabilityToolSpecs as He,runCapabilityTool as _e}from"./mcp-capabilities.js";import{createSession as Me,deleteSession as J,getSession as F,activeSession as Be,relayToolCall as Ge}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ue,isDefaultWorkdir as De,resolveWorkdir as Le,writeScopeNote as We}from"./workdir.js";import{gitState as je,gitDelta as Je}from"./scm.js";import{listConnections as Fe,putConnection as Ke,removeConnection as ze,runEnvFor as Ve,testConnection as Ye,secretBackend as K}from"./connections.js";import{worktreeFor as z,listWorktrees as Xe,removeWorktree as Qe,withHook as Ze,WORKTREE_ROOT as V}from"./worktree.js";import{AGENT_CLIS as qe,enrichPath as et,enrichAgentEnv as tt,findAgentBin as Y,resolveCommand as nt}from"./env.js";import"./sanitize.js";import{checkForUpdate as ot,selfUpdate as X,isEmbedded as rt}from"./update.js";import{callLocalMcp as at}from"./mcp-local.js";import{assertPublicHttpUrl as Q,assertPublicWebUrl as Z}from"./ssrf.js";import{startRun as q,endRun as G,cancelRun as it,cancelAll as st}from"./runs.js";import{closeWarmPools as ct,warmStatus as lt}from"./warm.js";import{CompatError as I,anthropicError as U,anthropicStream as dt,chatCompletionStream as ut,completionStream as ht,createAnthropicMessage as pt,createChatCompletion as mt,createCompletion as ft,createResponse as gt,openAIError as w,parseAnthropicMessage as yt,parseChatCompletion as wt,parseCompletion as bt,parseResponse as St,responseStream as kt}from"./api-compat.js";const g="0.12.3",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",O=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,T={claude:{engine:fe,label:"Claude Code"},codex:{engine:ge,label:"Codex"},antigravity:{engine:ye,label:"Antigravity",tools:!1},pi:{engine:we,label:"Pi"},opencode:{engine:be,label:"OpenCode"},hermes:{engine:ve,label:"Hermes"},kiro:{engine:Se,label:"Kiro"},copilot:{engine:ke,label:"GitHub Copilot"},deepseek:{engine:Te,label:"DeepSeek Harness"},custom:{engine:Ee,label:"Custom",hidden:!0}};function ee(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]")}function Tt(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 vt(n,e){const t=n.headers.origin||"",r=ee(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 D=new Set(["127.0.0.1","localhost","::1"]);function Ct(n){if(!D.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return D.has(t)}const L=$(x.homedir(),".chatpanel","bridge-token");let v="";function Et(){try{me(L)&&(v=pe(L,"utf8").trim()),v||(v=le(32).toString("hex"),ue($(x.homedir(),".chatpanel"),{recursive:!0}),he(L,v,{mode:384}))}catch(n){h("error",`could not initialise bridge token: ${n?.message||n}`)}}let N=null;async function te(){if(N)return N;const{createChannelService:n}=await import("./channels/service.js");return N=n({home:$(x.homedir(),".chatpanel"),dataDir:$(x.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${O}`,token:v},logger:{log:e=>h("info",e),warn:e=>h("info",e),error:e=>h("error",e)}}),N}async function ne(n,e,t){try{const r=await te(),o=n.method==="POST"?await f(n):{};if(t==="status")return a(e,200,await r.status());if(t==="connect"){const i=await r.connect(o);return a(e,200,{ok:!0,...i})}return t==="pair"?a(e,200,await r.pair()):t==="unpair"?a(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?a(e,200,await r.update(o)):t==="disconnect"?a(e,200,await r.stop({forget:!!o.forget})):a(e,404,{error:"unknown channel action"})}catch(r){return a(e,400,{error:r?.message||String(r)})}}function Ot(n){if(!v)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(v);return r.length===o.length&&de(r,o)}const At=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"]),xt=new Set(["/debug"]),Pt=n=>xt.has(n);function $t(n,e){if(!Ct(n))return"forbidden host";const t=n.headers.origin||"";return t&&!ee(t)?"forbidden origin":(n.method==="POST"&&At.has(e)||n.method==="GET"&&Pt(e))&&!(Tt(t)||Ot(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":null}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 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 It(n){const e=await Promise.all(Object.entries(T).filter(([,o])=>!o.hidden).map(async([o,{engine:i,label:l,tools:d}])=>{const s=await i.available().catch(u=>({ok:!1,reason:String(u?.message||u)})),c=await Ce(o).catch(()=>[]);return{id:o,label:l,available:s.ok,reason:s.reason,connectors:c,...d===!1?{tools:!1}:{}}})),t=rt()?{current:g,updateAvailable:!1,embedded:"gateway"}:await ot(g).catch(()=>({current:g,updateAvailable:!1})),r=await Ne().catch(()=>null);a(n,200,{ok:!0,version:g,agents:e,update:t,workspace:Ue,worktrees:V,secretBackend:K(),warm:lt(),...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function Nt(n,e){const{index:t,problems:r}=await B({extraDirs:e});a(n,200,{ok:!0,skills:Pe(t),problems:r})}async function Rt(n,e){a(n,200,{ok:!0,quarantined:await Re(e)})}async function Ht(n,e,t){const{index:r}=await B({extraDirs:t}),o=$e(r,e);if(!o)return a(n,404,{ok:!1,error:"unknown skill"});a(n,200,{ok:!0,skill:o})}async function _t(n,e,t,r){const{index:o}=await B({extraDirs:r}),i=await Ie(o,e,t);if(i.error)return a(n,i.error==="unknown skill"?404:400,{ok:!1,error:i.error});a(n,200,{ok:!0,...i})}async function Mt(){return(await Promise.all(Object.entries(T).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 oe(n,e=""){const t=await Mt();if(e){const r=t.find(o=>o.id===e);return r?a(n,200,r):a(n,404,w(new I(`Model "${e}" not found`,404,"model")))}return a(n,200,{object:"list",data:t})}async function Bt(n){try{const e=await X(g);a(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>j(),400))}catch(e){a(n,400,{ok:!1,error:String(e?.message||e)})}}async function Gt(n,e){let t;try{t=await f(n)}catch(p){return a(e,400,{error:"Bad JSON: "+p.message})}const r=T[t.agent];if(!r)return a(e,404,{error:`Unknown agent "${t.agent}"`});Array.isArray(t.images)&&t.images.length&&h("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 o=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
2
+ import{createServer as ce}from"node:http";import x from"node:os";import{randomBytes as le,timingSafeEqual as de}from"node:crypto";import{mkdirSync as ue,writeFileSync as he,readFileSync as pe,existsSync as me}from"node:fs";import{join as $}from"node:path";import*as fe from"./engines/claude.js";import*as ge from"./engines/codex.js";import*as ye from"./engines/antigravity.js";import{pi as we,opencode as be,kiro as Se,copilot as ke,deepseek as Te,hermes as ve}from"./engines/cli-agents.js";import{connectorsFor as Ce}from"./connectors.js";import*as Ee from"./engines/custom.js";import{installService as Oe,uninstallService as Ae,serviceStatus as xe,restartService as j}from"./service.js";import{skillIndex as B,listRecords as Pe,readRecord as $e,readPackageFile as Ie,skillsHealth as Ne,quarantinedSkills as Re}from"./skills.js";import{capabilityToolSpecs as He,runCapabilityTool as _e}from"./mcp-capabilities.js";import{createSession as Me,deleteSession as J,getSession as F,activeSession as Be,relayToolCall as Ge}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ue,isDefaultWorkdir as De,resolveWorkdir as Le,writeScopeNote as We}from"./workdir.js";import{gitState as je,gitDelta as Je}from"./scm.js";import{listConnections as Fe,putConnection as Ke,removeConnection as ze,runEnvFor as Ve,testConnection as Ye,secretBackend as K}from"./connections.js";import{worktreeFor as z,listWorktrees as Xe,removeWorktree as Qe,withHook as Ze,WORKTREE_ROOT as V}from"./worktree.js";import{AGENT_CLIS as qe,enrichPath as et,enrichAgentEnv as tt,findAgentBin as Y,resolveCommand as nt}from"./env.js";import"./sanitize.js";import{checkForUpdate as ot,selfUpdate as X,isEmbedded as rt}from"./update.js";import{callLocalMcp as at}from"./mcp-local.js";import{assertPublicHttpUrl as Q,assertPublicWebUrl as Z}from"./ssrf.js";import{startRun as q,endRun as G,cancelRun as it,cancelAll as st}from"./runs.js";import{closeWarmPools as ct,warmStatus as lt}from"./warm.js";import{CompatError as I,anthropicError as U,anthropicStream as dt,chatCompletionStream as ut,completionStream as ht,createAnthropicMessage as pt,createChatCompletion as mt,createCompletion as ft,createResponse as gt,openAIError as w,parseAnthropicMessage as yt,parseChatCompletion as wt,parseCompletion as bt,parseResponse as St,responseStream as kt}from"./api-compat.js";const g="0.12.4",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",O=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,T={claude:{engine:fe,label:"Claude Code"},codex:{engine:ge,label:"Codex"},antigravity:{engine:ye,label:"Antigravity",tools:!1},pi:{engine:we,label:"Pi"},opencode:{engine:be,label:"OpenCode"},hermes:{engine:ve,label:"Hermes"},kiro:{engine:Se,label:"Kiro"},copilot:{engine:ke,label:"GitHub Copilot"},deepseek:{engine:Te,label:"DeepSeek Harness"},custom:{engine:Ee,label:"Custom",hidden:!0}};function ee(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]")}function Tt(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 vt(n,e){const t=n.headers.origin||"",r=ee(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 D=new Set(["127.0.0.1","localhost","::1"]);function Ct(n){if(!D.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return D.has(t)}const L=$(x.homedir(),".chatpanel","bridge-token");let v="";function Et(){try{me(L)&&(v=pe(L,"utf8").trim()),v||(v=le(32).toString("hex"),ue($(x.homedir(),".chatpanel"),{recursive:!0}),he(L,v,{mode:384}))}catch(n){h("error",`could not initialise bridge token: ${n?.message||n}`)}}let N=null;async function te(){if(N)return N;const{createChannelService:n}=await import("./channels/service.js");return N=n({home:$(x.homedir(),".chatpanel"),dataDir:$(x.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${O}`,token:v},logger:{log:e=>h("info",e),warn:e=>h("info",e),error:e=>h("error",e)}}),N}async function ne(n,e,t){try{const r=await te(),o=n.method==="POST"?await f(n):{};if(t==="status")return a(e,200,await r.status());if(t==="connect"){const i=await r.connect(o);return a(e,200,{ok:!0,...i})}return t==="pair"?a(e,200,await r.pair()):t==="unpair"?a(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?a(e,200,await r.update(o)):t==="disconnect"?a(e,200,await r.stop({forget:!!o.forget})):a(e,404,{error:"unknown channel action"})}catch(r){return a(e,400,{error:r?.message||String(r)})}}function Ot(n){if(!v)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(v);return r.length===o.length&&de(r,o)}const At=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"]),xt=new Set(["/debug"]),Pt=n=>xt.has(n);function $t(n,e){if(!Ct(n))return"forbidden host";const t=n.headers.origin||"";return t&&!ee(t)?"forbidden origin":(n.method==="POST"&&At.has(e)||n.method==="GET"&&Pt(e))&&!(Tt(t)||Ot(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":null}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 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 It(n){const e=await Promise.all(Object.entries(T).filter(([,o])=>!o.hidden).map(async([o,{engine:i,label:l,tools:d}])=>{const s=await i.available().catch(u=>({ok:!1,reason:String(u?.message||u)})),c=await Ce(o).catch(()=>[]);return{id:o,label:l,available:s.ok,reason:s.reason,connectors:c,...d===!1?{tools:!1}:{}}})),t=rt()?{current:g,updateAvailable:!1,embedded:"gateway"}:await ot(g).catch(()=>({current:g,updateAvailable:!1})),r=await Ne().catch(()=>null);a(n,200,{ok:!0,version:g,agents:e,update:t,workspace:Ue,worktrees:V,secretBackend:K(),warm:lt(),...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function Nt(n,e){const{index:t,problems:r}=await B({extraDirs:e});a(n,200,{ok:!0,skills:Pe(t),problems:r})}async function Rt(n,e){a(n,200,{ok:!0,quarantined:await Re(e)})}async function Ht(n,e,t){const{index:r}=await B({extraDirs:t}),o=$e(r,e);if(!o)return a(n,404,{ok:!1,error:"unknown skill"});a(n,200,{ok:!0,skill:o})}async function _t(n,e,t,r){const{index:o}=await B({extraDirs:r}),i=await Ie(o,e,t);if(i.error)return a(n,i.error==="unknown skill"?404:400,{ok:!1,error:i.error});a(n,200,{ok:!0,...i})}async function Mt(){return(await Promise.all(Object.entries(T).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 oe(n,e=""){const t=await Mt();if(e){const r=t.find(o=>o.id===e);return r?a(n,200,r):a(n,404,w(new I(`Model "${e}" not found`,404,"model")))}return a(n,200,{object:"list",data:t})}async function Bt(n){try{const e=await X(g);a(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>j(),400))}catch(e){a(n,400,{ok:!1,error:String(e?.message||e)})}}async function Gt(n,e){let t;try{t=await f(n)}catch(p){return a(e,400,{error:"Bad JSON: "+p.message})}const r=T[t.agent];if(!r)return a(e,404,{error:`Unknown agent "${t.agent}"`});Array.isArray(t.images)&&t.images.length&&h("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 o=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
3
3
 
4
4
  `)};let i=!1;const l=`run_${Math.random().toString(36).slice(2,10)}`,d=q(l),s={signal:d.signal,abort:()=>d.cancel("client")},c=()=>{i=!0,d.cancel("disconnected")};n.on("close",c),e.on("close",c),e.on("error",c);const u=p=>{i||o(p)};o({type:"run",id:l});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){o({type:"error",error:`workspace: ${m.error}`}),G(l),e.writableEnded||e.end();return}}const b=m?m.path:Le(t.options?.workingDir);let C=null;{const p=b,E=!!m||!De(t.options?.workingDir),y=We(t.agent,t.options?.permissionMode,p);o({type:"workdir",path:p,isDefault:!E,writeScope:y||void 0}),o({type:"status",text:`Working in ${p}${E?"":" (default)"}`}),y&&o({type:"status",text:y}),C=await je(p),C&&o({type:"scm",phase:"before",...C})}let M=null;if(C||m){const p=Array.isArray(t.options?.grants)?t.options.grants:[],{env:E,connection:y}=Ve({remote:C?.remote||null,grants:p,branch:m?.branch||null,connectionId:t.options?.connectionId||null});M=Ze(E),m&&o({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&o({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${E.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:E.CHATPANEL_SCM_PUSH}`})}const W={...t.options||{},...m?{workingDir:m.path}:{},...M?{runEnv:M}:{}};let P=null;t.pageTools?.specs?.length&&(P=Me(u,t.pageTools.specs),W.mcp={url:`http://${k}:${O}/mcp/${P.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs});try{await r.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:W,images:Array.isArray(t.images)?t.images:[]},u,{signal:s.signal})}catch(p){h("error",`${t.agent} chat failed: ${p?.message||p}`),o({type:"error",error:p?.message||String(p)})}finally{if(!i){const p=await Je(b,C).catch(()=>null);p&&u({type:"scm",phase:"after",...p})}G(l),P&&J(P.id),e.writableEnded||e.end()}}async function Ut(n,e,t){if(n.method==="GET"&&t==="/connections")return a(e,200,{ok:!0,connections:Fe(),secretBackend:K()});if(n.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/connections")try{return a(e,200,{ok:!0,connection:Ke(r.connection||r,{token:r.token||null})})}catch(i){return a(e,400,{error:String(i?.message||i)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return o?o[2]==="delete"?a(e,200,{ok:ze(o[1])}):a(e,200,Ye(o[1],r.remote||"")):a(e,404,{error:"Not found"})}async function Dt(n,e,t){if(n.method==="GET"&&t==="/worktrees")return a(e,200,{ok:!0,root:V,worktrees:await Xe()});if(n.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/worktrees"){const o=await z({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return a(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(t==="/worktrees/remove"){const o=await Qe({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return a(e,o.ok?200:400,o)}return a(e,404,{error:"Not found"})}async function S(n,e,t){const r=T[n.agent];if(!r||r.hidden)throw new I(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const o=await r.engine.available().catch(c=>({ok:!1,reason:c?.message||String(c)}));if(!o.ok)throw new I(o.reason||`${n.agent} is unavailable`,503,"model");const i=`run_${Math.random().toString(36).slice(2,10)}`,l=q(i),d=()=>l.cancel("disconnected");t.on("close",d);let s="";try{return await r.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},c=>{c?.type==="delta"&&c.text?(s+=c.text,e(c.text)):c?.type==="done"&&c.text&&!s&&(s=c.text,e(c.text))},{signal:l.signal}),s}finally{t.off("close",d),G(i)}}function R(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function A(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
5
5