@chatpanel/bridge 0.11.25 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +12 -0
- package/package.json +1 -1
- package/src/engines/claude-warm.js +3 -0
- package/src/engines/claude.js +6 -6
- package/src/engines/codex-appserver.js +12 -0
- package/src/engines/codex.js +6 -6
- package/src/mcp-sessions.js +1 -0
- package/src/proc.js +3 -2
- package/src/rpc-child.js +3 -0
- package/src/server.js +9 -9
- package/src/warm-pool.js +1 -0
- package/src/warm.js +1 -0
package/.env.example
CHANGED
|
@@ -10,3 +10,15 @@ CHATPANEL_BRIDGE_PORT=4319
|
|
|
10
10
|
# Safety rails.
|
|
11
11
|
CHATPANEL_MAX_TURNS=20
|
|
12
12
|
CHATPANEL_CODEX_TIMEOUT_MS=180000
|
|
13
|
+
|
|
14
|
+
# Warm agent processes (Codex app-server, Claude Code stream-json): the CLI stays up between a
|
|
15
|
+
# conversation's turns so the next message skips its boot and MCP start-up, and the answer
|
|
16
|
+
# streams as it is written. Sized to the machine by default (RAM ≥32 GB: 3 per agent, ≥16 GB:
|
|
17
|
+
# 2, else 1; idle 10/5 min; ≤20% of RAM or 3 GB resident in total). Set to override.
|
|
18
|
+
# CHATPANEL_WARM=off # every turn cold, as before
|
|
19
|
+
# CHATPANEL_CODEX_APPSERVER=off # Codex only: back to `codex exec --json` (no token streaming)
|
|
20
|
+
# CHATPANEL_CLAUDE_WARM=off # Claude Code only: a fresh `claude --print` per turn
|
|
21
|
+
# CHATPANEL_WARM_MAX=2 # warm processes per agent
|
|
22
|
+
# CHATPANEL_WARM_IDLE_MS=600000 # reap an idle one after this long
|
|
23
|
+
# CHATPANEL_WARM_BUDGET_MB=1500 # resident memory every warm process may hold together
|
|
24
|
+
# CHATPANEL_WARM_LOG=1 # log start/reuse/eviction/measured size to stderr
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
|
|
6
6
|
"keywords": [
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{unlink as P}from"node:fs/promises";import{spawnRpcChild as N}from"../rpc-child.js";import{createWarmPool as O}from"../warm-pool.js";import{registerWarmPool as q}from"../warm.js";import{createSession as R,deleteSession as T,rebindSession as W,releaseSession as I}from"../mcp-sessions.js";import{resolveClaude as H,buildSpawnSpec as j}from"../env.js";import{loginRequired as _,signInMessage as M}from"../sign-in.js";import{pushExtraArgs as L,FORBIDDEN as k}from"./args.js";import{buildClaudeLaunch as U,claudePrompt as B,handleMessage as F,writeImages as G}from"./claude.js";const D=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,J=5e3,f=q("claude",O({log:u=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${u}`)}}));function z(u={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||u.warm===!1)}function K({spec:u,args:y,cwd:t,env:v,spawnImpl:p,log:w=()=>{}}){const $=[...y,"--input-format","stream-json"],[C,A,S]=j(u,$,t,v);let e=null;const m=new Set;let o="",x=0;const l=N(C,A,{spawnOpts:S,spawnImpl:p,jsonrpc:!1,onStderr:s=>{o=(o+s).slice(-2e3),e&&e.touch()},onExit:s=>{if(w(`claude exited: ${s.signal||s.code}${o?` — ${o.trim().split(`
|
|
2
|
+
`).pop()}`:""}`),e){const i=e.apiError&&_(e.apiError)?M("Claude Code","claude"):e.apiError?`Claude Code reported an error: ${e.apiError}`:`Claude Code exited (${s.signal||s.code})${o?`: ${o.trim().split(`
|
|
3
|
+
`).pop().slice(0,200)}`:""}`;e.finish({status:"died",error:i})}for(const i of m)try{i(s)}catch{}},onMessage:s=>{if(!e||(e.touch(),s.type==="control_response"))return;const i=F(s,e.emit,e.streamedAny,t,e.flow);i.streamed&&(e.streamedAny=!0),i.result!=null&&(e.resultText=i.result),i.apiError&&(e.apiError=i.apiError),s.type==="result"&&(e.apiError&&_(e.apiError)?e.finish({status:"failed",error:M("Claude Code","claude")}):e.apiError?e.finish({status:"failed",error:`Claude Code reported an error: ${e.apiError}`}):e.finish({status:"completed",error:null}))}});return{get pid(){return l.pid},get alive(){return!l.exited},onExit(s){m.add(s)},close(){l.close()},async turn({prompt:s,emit:i,signal:h}){if(l.exited)throw new Error("Claude Code process is gone");if(e)throw new Error("a turn is already running on this process");let n=null,a;const c=new Promise(g=>{a=g}),r={emit:i,flow:{sawText:!1,tail:"",boundary:!1},streamedAny:!1,resultText:"",apiError:null,touch(){clearTimeout(n),n=setTimeout(()=>r.finish({status:"timeout",error:`Claude Code timed out — no output for ${Math.round(D/1e3)}s.`}),D)},finish(g){e===r&&(clearTimeout(n),e=null,a(g))}};e=r,r.touch();const E=()=>{if(e===r){r.interrupted=!0;try{l.send({type:"control_request",request_id:`stop_${++x}`,request:{subtype:"interrupt"}})}catch{}setTimeout(()=>{e===r&&(r.finish({status:"killed",error:null}),l.kill())},J).unref?.()}};if(h?.aborted)return r.finish({status:"killed",error:null}),{streamedAny:!1,resultText:"",status:"killed"};h?.addEventListener("abort",E,{once:!0});try{l.send({type:"user",message:{role:"user",content:s}})}catch(g){r.finish({status:"failed",error:g.message})}const d=await c;h?.removeEventListener("abort",E),d.status==="timeout"&&l.kill();const b=d.status==="killed"?"killed":r.interrupted?"interrupted":d.status;return{streamedAny:r.streamedAny,resultText:r.resultText,status:b,error:d.error}}}}async function ne({messages:u,system:y,options:t,images:v},p,{signal:w,launch:$=K}={}){if(!z(t))return{handled:!1,reason:"not eligible"};const C=H();if(!C)return{handled:!1,reason:"claude not resolvable"};const A=`${Date.now()}-${Math.random().toString(36).slice(2)}`,S=(t.mcp?.specs||[]).map(a=>a?.name).filter(Boolean),e=[];L(e,t.extraArgs,k.claude,()=>{});const m=JSON.stringify({agent:"claude",cwd:t.workingDir||"",mode:t.permissionMode||"default",model:t.model||"",local:t.useLocalConfig!==!1,system:String(y||""),reach:t.reach||"",tools:[...S].sort(),extra:e,env:t.runEnv?Object.keys(t.runEnv).sort().map(a=>`${a}=${t.runEnv[a]}`):[]});let o=f.acquire({key:m,messages:u}),x=!1;if(!o){if(o=f.reserve({key:m,label:`claude ${t.workingDir||"home"}`}),!o)return{handled:!1,reason:"all warm slots busy"};x=!0;let a=null,c=null;try{let r=t.mcp;r?.url&&S.length&&(a=R(p,r.specs),r={...r,url:`${r.url.replace(/\/[^/]*$/,"")}/${a.id}`}),c=await U({system:y,options:{...t,mcp:r},tag:A});const E=[...c.args];L(E,t.extraArgs,k.claude,p);const d=$({spec:C,args:E,cwd:c.cwd,env:c.runEnv});d.mcpSession=a,f.attach(o,d);const b=c.cleanup;d.onExit(()=>{a&&T(a.id),b()})}catch(r){return a&&T(a.id),c?.cleanup(),f.drop(o,`launch failed: ${r.message}`),{handled:!1,reason:r.message}}}const l=o.session;l.mcpSession&&W(l.mcpSession,p,t.mcp?.specs);const s=u[u.length-1],i=await G(v,A),h=B(x?u:[s],i);let n;try{n=await l.turn({prompt:h,emit:p,signal:w})}finally{i.forEach(a=>P(a).catch(()=>{})),l.mcpSession&&I(l.mcpSession)}if(w?.aborted||n.status==="interrupted")return n.status==="interrupted"&&l.alive?f.release(o,{user:String(s?.content||""),answered:n.streamedAny}):f.drop(o,"stopped"),{handled:!0};if(n.status!=="completed"){if(f.drop(o,n.error||n.status),!n.streamedAny)return{handled:!1,reason:n.error||n.status};throw new Error(n.error||`Claude Code ${n.status}`)}return p({type:"done",text:n.streamedAny?"":n.resultText}),f.release(o,{user:String(s?.content||""),answered:!0}),{handled:!0}}export{ne as chatWarm,K as launchClaudeSession,f as pool,z as warmEligible};
|
package/src/engines/claude.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{spawn as J}from"node:child_process";import{writeFile as
|
|
2
|
-
`))>=0;){const
|
|
3
|
-
`)),
|
|
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:`
|
|
4
4
|
|
|
5
|
-
`}),e.boundary=!1)}function q(e,
|
|
6
|
-
`)||String(e.error||"api error"),n;for(const r of e.message?.content||[])r.type==="tool_use"?(s&&(s.boundary=!0),
|
|
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=[]){let o=R(e);return t.length&&(o+=`
|
|
7
7
|
|
|
8
|
-
The user attached ${
|
|
8
|
+
The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),o}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};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import R from"node:os";import _ from"node:path";import{unlink as q}from"node:fs/promises";import{spawnRpcChild as L}from"../rpc-child.js";import{createWarmPool as H}from"../warm-pool.js";import{createSession as W,deleteSession as P,rebindSession as j,releaseSession as z}from"../mcp-sessions.js";import{buildCliPrompt as M}from"./prompt.js";import{codexMcpConfigArgs as U,codexDisableArgs as B,configuredMcpServers as X,ensureIsolatedHome as F,writeImages as J}from"./codex.js";import{disabledMcpServers as G}from"../mcp-quarantine.js";import{resolveWorkdir as V}from"../workdir.js";import{registerWarmPool as K}from"../warm.js";const O=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,D=process.env.CHATPANEL_CODEX_EFFORT??"low",Q=9e4,N=5e3,v=K("codex",H({log:e=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[codex] ${e}`)}}));let T=0;function ge(){T=0}function Y({agent:e="codex",cwd:p,options:s={},mcpNames:f=[],runEnv:i=null,disabled:u=[]}){return JSON.stringify({agent:e,cwd:p,mode:s.permissionMode||"default",model:s.model||"",local:s.useLocalConfig!==!1,tools:[...f].sort(),env:i?Object.keys(i).sort().map(x=>`${x}=${i[x]}`):[],disabled:[...u].sort()})}function Z(e={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CODEX_APPSERVER==="off"||e.warm===!1||e.extraArgs&&String(e.extraArgs).trim()||Date.now()<T)}function ee(e){return e==="bypassPermissions"?"danger-full-access":e==="acceptEdits"?"workspace-write":"read-only"}function te(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e?.content))return e.content.map(p=>typeof p=="string"?p:p?.text||"").filter(Boolean).join(`
|
|
2
|
+
`);try{return JSON.stringify(e)}catch{return String(e)}}function re(e,p,s,f){const i=e?.type||"",u=e?.id||`i_${f.n++}`,x=(l,o)=>{f.started.has(u)||(f.started.add(u),s({type:"tool",name:l,phase:"start",callId:u,input:o}))};if(i==="agentMessage"){p&&e.text&&!f.deltaItems.has(u)&&!f.said.has(u)&&(f.said.add(u),s({type:"delta",text:`${f.saidAny?`
|
|
3
|
+
|
|
4
|
+
`:""}${e.text}`}),f.saidAny=!0);return}if(i==="commandExecution"){if(x("shell",{command:e.command||""}),p){const l=e.exitCode===0||e.exitCode==null;s({type:"tool",name:"shell",phase:"done",callId:u,status:l?"ok":`exit ${e.exitCode}`,result:String(e.aggregatedOutput||"").slice(0,4e3)})}return}if(i==="fileChange"){const l=Array.isArray(e.changes)?e.changes.map(o=>o?.path||o?.file).filter(Boolean):[];x("edit",{files:l}),p&&s({type:"tool",name:"edit",phase:"done",callId:u,status:e.status==="failed"?"error":"ok"});return}if(i==="webSearch"){const l=e.action&&typeof e.action=="object"?e.action:{},o=e.query||l.query||"",t=l.url||"";x("web_search",{query:o,...t?{url:t}:{}}),p&&s({type:"tool",name:"web_search",phase:"done",callId:u,status:"ok",result:t?`Opened ${t}`:o?`Searched the web for ${o}`:"Searched the web"});return}if(i==="mcpToolCall"){const l=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(x(l,e.arguments&&typeof e.arguments=="object"?e.arguments:{}),p){const o=e.status==="failed"||e.error!=null,t=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error;s({type:"tool",name:l,phase:"done",callId:u,status:o?`error: ${String(t||"failed").slice(0,80)}`:"ok",result:String(o?t||"":te(e.result)).slice(0,4e3)})}return}if(i==="plan"&&p&&e.text&&f.lastPlan!==e.text){f.lastPlan=e.text,s({type:"status",text:`Plan:
|
|
5
|
+
${e.text}`});return}if(i==="reasoning"&&p){if(f.deltaItems.has(u))return;const l=(Array.isArray(e.summary)?e.summary:[]).map(o=>typeof o=="string"?o:o?.text||"").filter(Boolean).join(`
|
|
6
|
+
`);l&&!f.reasoned.has(u)&&(f.reasoned.add(u),s({type:"reasoning",text:`${l}
|
|
7
|
+
`}))}}function se(){return{n:0,started:new Set,said:new Set,reasoned:new Set,deltaItems:new Set,saidAny:!1,lastPlan:null}}async function ae({bin:e="codex",cwd:p,env:s,configArgs:f=[],options:i={},spawnImpl:u,log:x=()=>{}}){const l=i.permissionMode||"default",o=l==="bypassPermissions";let t=null;const E=new Set;let b="";const g=L(e,["app-server",...f],{cwd:p,env:s,spawnImpl:u,onStderr:r=>{b=(b+r).slice(-2e3)},onExit:r=>{x(`app-server exited: ${r.signal||r.code}${b?` — ${b.trim().split(`
|
|
8
|
+
`).pop()}`:""}`),t&&t.finish({status:"died",error:r.error?.message||`Codex exited (${r.signal||r.code})`});for(const a of E)try{a(r)}catch{}},onRequest:async(r,a)=>{if(r==="item/commandExecution/requestApproval"||r==="execCommandApproval")return o||t?.emit({type:"status",text:"Codex asked to run a command outside its sandbox — declined (set Permissions to full access to allow)."}),r==="execCommandApproval"?{decision:o?"approved":"denied"}:{decision:o?"accept":"decline"};if(r==="item/fileChange/requestApproval"||r==="applyPatchApproval")return o||t?.emit({type:"status",text:"Codex asked to change files outside its sandbox — declined (set Permissions to auto-edit or full access to allow)."}),r==="applyPatchApproval"?{decision:o?"approved":"denied"}:{decision:o?"accept":"decline"}},onMessage:r=>{if(!r.method||!t)return;const a=r.params||{};if(a.threadId&&a.threadId!==t.threadId)return;t.touch();const d=r.method;if(d==="item/agentMessage/delta"){if(!a.delta)return;t.state.deltaItems.add(a.itemId),t.state.said.has(a.itemId)||(t.state.said.add(a.itemId),t.state.saidAny&&t.emit({type:"delta",text:`
|
|
9
|
+
|
|
10
|
+
`})),t.state.saidAny=!0,t.streamed=!0,t.emit({type:"delta",text:a.delta})}else if(d==="item/reasoning/summaryTextDelta"||d==="item/reasoning/textDelta"){if(!a.delta)return;t.state.deltaItems.add(a.itemId),t.streamed=!0,t.emit({type:"reasoning",text:a.delta})}else if(d==="item/reasoning/summaryPartAdded")t.state.deltaItems.has(a.itemId)&&t.emit({type:"reasoning",text:`
|
|
11
|
+
`});else if(d==="item/started"||d==="item/completed"){const n=t.state.started.size+t.state.said.size;re(a.item,d==="item/completed",t.emit,t.state),t.state.started.size+t.state.said.size>n&&(t.streamed=!0)}else if(d==="thread/tokenUsage/updated"){const n=a.tokenUsage?.last||a.tokenUsage?.total;n&&(t.usage={type:"usage",provider:"bridge",inputTokens:n.inputTokens||0,outputTokens:n.outputTokens||0,cacheReadTokens:n.cachedInputTokens||0,cacheWriteTokens:n.cacheWriteInputTokens||0,costUsd:null})}else if(d==="error"){const n=a.error?.message||"error";a.willRetry?t.emit({type:"status",text:`Codex: ${n.slice(0,200)} — retrying`}):t.lastError=n}else if(d==="turn/completed"){const n=a.turn||{};if(t.turnId&&n.id&&n.id!==t.turnId)return;t.finish({status:n.status||"completed",error:n.error?.message||t.lastError||null})}}});let w;try{if(await g.request("initialize",{clientInfo:{name:"chatpanel-bridge",version:"1"},capabilities:{experimentalApi:!0}},{timeoutMs:2e4}),g.notify("initialized"),w=(await g.request("thread/start",{cwd:p||void 0,sandbox:ee(l),approvalPolicy:"never",...i.model?{model:i.model}:{}},{timeoutMs:Q}))?.thread?.id,!w)throw new Error("Codex app-server started no thread")}catch(r){g.kill();const a=b.trim().split(`
|
|
12
|
+
`).filter(Boolean).pop()||"";throw new Error(a?`${r.message}: ${a.slice(-300)}`:r.message)}return{threadId:w,get pid(){return g.pid},get alive(){return!g.exited},onExit(r){E.add(r)},close(){g.close()},async turn({prompt:r,imageFiles:a=[],emit:d,signal:n}){if(g.exited)throw new Error("Codex process is gone");if(t)throw new Error("a turn is already running on this thread");const A=se();let S=null,I;const k=new Promise(y=>{I=y}),m={threadId:w,turnId:null,emit:d,state:A,streamed:!1,usage:null,lastError:null,touch(){clearTimeout(S),S=setTimeout(()=>m.finish({status:"timeout",error:`Codex timed out — no output for ${Math.round(O/1e3)}s.`}),O)},finish(y){t===m&&(clearTimeout(S),t=null,I(y))}};t=m,m.touch();const h=async()=>{if(t===m){try{await g.request("turn/interrupt",{threadId:w,turnId:m.turnId},{timeoutMs:N})}catch{}setTimeout(()=>{t===m&&(m.finish({status:"killed",error:null}),g.kill())},N).unref?.()}};if(n?.aborted)return m.finish({status:"killed",error:null}),{streamed:!1,said:!1,status:"killed",usage:null};n?.addEventListener("abort",h,{once:!0}),d({type:"status",text:"Codex working"});try{const y=[{type:"text",text:r},...a.map($=>({type:"localImage",path:$}))],C=await g.request("turn/start",{threadId:w,input:y,summary:"auto",...D?{effort:D}:{}},{timeoutMs:3e4});m.turnId=C?.turn?.id||null}catch(y){m.finish({status:"failed",error:y.message})}const c=await k;return n?.removeEventListener("abort",h),c.status==="timeout"&&g.kill(),m.usage&&d(m.usage),{streamed:m.streamed,said:A.saidAny,status:c.status,error:c.error,usage:m.usage}}}}async function ye({messages:e,system:p,options:s,images:f},i,{signal:u,launch:x=ae}={}){if(!Z(s))return{handled:!1,reason:"not eligible"};const l=V(s.workingDir),o={...process.env,...s.runEnv||{}};if(s.useLocalConfig===!1){const c=F();c&&(o.CODEX_HOME=c)}const t=s.mcp?.serverName||"chatpanel_browser",E=X(o.CODEX_HOME||_.join(R.homedir(),".codex")),b=G("codex",s,[t]).filter(c=>E.has(c)),g=(s.mcp?.specs||[]).map(c=>c?.name).filter(Boolean),w=Y({cwd:l,options:s,mcpNames:g,runEnv:s.runEnv||null,disabled:b});let r=v.acquire({key:w,messages:e}),a=!1,d=null;if(!r){if(r=v.reserve({key:w,label:`codex ${_.basename(l||"")}`}),!r)return{handled:!1,reason:"all warm slots busy"};a=!0;try{const c=[];if(s.mcp?.url&&g.length){d=W(i,s.mcp.specs);const $=s.mcp.url.replace(/\/[^/]*$/,"");c.push(...U({url:`${$}/${d.id}`,serverName:t,specs:s.mcp.specs}))}c.push(...B(b));const y=await x({cwd:l,env:o,configArgs:c,options:s});y.mcpSession=d,y.systemSent="",v.attach(r,y);const C=d;y.onExit(()=>{C&&P(C.id)})}catch(c){return d&&P(d.id),v.drop(r,`launch failed: ${c.message}`),/unknown|unrecognized|unexpected argument|app-server/i.test(c.message)&&(T=Date.now()+10*6e4),{handled:!1,reason:c.message}}}const n=r.session;n.mcpSession&&j(n.mcpSession,i,s.mcp?.specs);const A=e[e.length-1],S=String(p||""),I=a?M(e,S):M([A],S&&S!==n.systemSent?S:""),k=`${Date.now()}-${Math.random().toString(36).slice(2)}`,m=await J(f,k);let h;try{h=await n.turn({prompt:I,imageFiles:m,emit:i,signal:u})}finally{m.forEach(c=>q(c).catch(()=>{})),n.mcpSession&&z(n.mcpSession)}if(n.systemSent=S,u?.aborted||h.status==="interrupted")return h.status==="interrupted"&&n.alive?v.release(r,{user:String(A?.content||""),answered:h.streamed}):v.drop(r,"stopped"),{handled:!0};if(h.status!=="completed"){if(v.drop(r,h.error||h.status),!h.streamed)return{handled:!1,reason:h.error||h.status};throw new Error(h.error||`Codex ${h.status}`)}return h.said||i({type:"delta",text:"(no output)"}),i({type:"done",text:""}),v.release(r,{user:String(A?.content||""),answered:!0}),{handled:!0}}export{ye as chatWarm,re as forwardV2Item,ae as launchCodexSession,se as newTurnState,v as pool,ge as resetSupport,Z as warmEligible,Y as warmKey};
|
package/src/engines/codex.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{spawn as T}from"node:child_process";import{killOnAbort as P,spawnGroupOpts as B}from"../proc.js";import{readFile as H,unlink as A,writeFile as F}from"node:fs/promises";import{existsSync as I,mkdirSync as L,symlinkSync as X,readFileSync as C}from"node:fs";import
|
|
2
|
-
`))>=0;){const c=m.slice(0,h).trim();if(m=m.slice(h+1),!!c.startsWith("{"))try{
|
|
1
|
+
import{spawn as T}from"node:child_process";import{killOnAbort as P,spawnGroupOpts as B}from"../proc.js";import{readFile as H,unlink as A,writeFile as F}from"node:fs/promises";import{existsSync as I,mkdirSync as L,symlinkSync as X,readFileSync as C}from"node:fs";import _ from"node:os";import y from"node:path";import{findAgentBin as J,selfMcpStdio as R,resolveCommand as q}from"../env.js";import{relayTimeoutMax as W}from"../relay-timeout.js";import{buildCliPrompt as z}from"./prompt.js";import{pushExtraArgs as G,FORBIDDEN as K}from"./args.js";import{resolveWorkdir as U}from"../workdir.js";import{summarizeCliError as Z}from"../cli-errors.js";import{signInStatus as Q,signInMessage as V}from"../sign-in.js";import{disabledMcpServers as Y,planMcpRetry as ee,quarantine as te}from"../mcp-quarantine.js";import{chatWarm as re}from"./codex-appserver.js";const M=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,N=process.env.CHATPANEL_CODEX_EFFORT??"low",oe=["gpt-5-codex","gpt-5","o3","o4-mini"];let k=!1;function Ae(){k=!1}async function Ie(){const n=new Set;try{const r=process.env.CODEX_HOME||y.join(_.homedir(),".codex"),t=C(y.join(r,"config.toml"),"utf8");for(const s of t.matchAll(/(?:^|\n)\s*model\s*=\s*["']([^"'\n]+)["']/g))n.add(s[1].trim())}catch{}for(const r of oe)n.add(r);return[...n]}const O=y.join(_.homedir(),".chatpanel","codex-home");let D=!1;function ne(){if(!D)try{L(O,{recursive:!0});const n=y.join(_.homedir(),".codex","auth.json"),r=y.join(O,"auth.json");if(I(n)&&!I(r))try{X(n,r)}catch{}D=!0}catch{return null}return O}let b=!1,j=0;async function Ce(){if(Date.now()-j>(b?3e4:4e3)){j=Date.now();try{b=!!J("codex")}catch{b=!1}}return b?await Q("codex",q("codex")).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:V("Codex","codex")}:{ok:!0}:{ok:!1,reason:"codex not found on PATH. Install it and run `codex login`."}}function se(n){if(!n?.url)return[];const r=n.serverName||"chatpanel_browser",{command:t,args:s}=R(n.url),e=["-c",`mcp_servers.${r}.command=${JSON.stringify(t)}`,"-c",`mcp_servers.${r}.args=${JSON.stringify(s)}`,"-c",`mcp_servers.${r}.default_tools_approval_mode="approve"`,"-c",`mcp_servers.${r}.startup_timeout_sec=30`,"-c",`mcp_servers.${r}.tool_timeout_sec=${Math.ceil(W(n.specs)/1e3)}`],a=[...new Set((n.specs||[]).map(d=>d?.name).filter(Boolean))];return a.length&&e.push("-c",`mcp_servers.${r}.enabled_tools=${JSON.stringify(a)}`),e}function ae(n){try{const r=C(y.join(n,"config.toml"),"utf8"),t=new Set;for(const s of r.matchAll(/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*[.\]]/gm))t.add(s[1]);return t}catch{return new Set}}function ie(n=[]){return n.flatMap(r=>["-c",`mcp_servers.${r}.enabled=false`])}async function ce(n,r){const t=[];for(let s=0;s<(n?.length||0);s++){const e=/^data:([^;]+);base64,(.+)$/s.exec(n[s]?.dataUrl||"");if(!e)continue;const a=(e[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",d=y.join(_.tmpdir(),`chatpanel-codex-img-${r}-${s}.${a}`);await F(d,Buffer.from(e[2],"base64")),t.push(d)}return t}function le({args:n,cwd:r,env:t,prompt:s,outFile:e,emit:a,signal:d}){return new Promise((o,i)=>{let l;try{l=T("codex",n,{cwd:r,stdio:["pipe","pipe","pipe"],env:t,...B})}catch(u){return i(new Error(`Failed to start codex: ${u.message}`))}const f=P(l,d);let m="",$="",v=!1;const S=u=>{u?.type!=="status"&&(v=!0),a(u)},w={started:new Set,reasoned:new Set,n:0};let x;const g=()=>{clearTimeout(x),x=setTimeout(()=>{l.kill("SIGKILL"),i(new Error(`Codex timed out — no output for ${Math.round(M/1e3)}s.`))},M)};g(),l.stdout.on("data",u=>{g(),m+=u.toString();let h;for(;(h=m.indexOf(`
|
|
2
|
+
`))>=0;){const c=m.slice(0,h).trim();if(m=m.slice(h+1),!!c.startsWith("{"))try{pe(JSON.parse(c),S,w)}catch{}}}),l.stderr.on("data",u=>{g(),$+=u.toString()}),l.on("error",u=>{clearTimeout(x),f(),i(u)}),l.on("close",async u=>{clearTimeout(x),f();let h="";try{h=(await H(e,"utf8")).trim()}catch{}A(e).catch(()=>{}),o({code:u,stderr:$,text:h,streamed:v,said:!!w.saidAny,policyBlocked:!!w.policyBlocked})}),l.stdin.write(s),l.stdin.end()})}async function Me({messages:n,system:r,options:t,images:s},e,{signal:a}={}){const d=await re({messages:n,system:r,options:t,images:s},e,{signal:a}).catch(o=>({handled:!1,reason:o?.message||String(o),thrown:!0}));if(!d.handled&&!a?.aborted){if(d.thrown)throw new Error(d.reason);return de({messages:n,system:r,options:t,images:s},e,{signal:a})}}async function de({messages:n,system:r,options:t,images:s},e,{signal:a}={}){const d=`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=y.join(_.tmpdir(),`chatpanel-codex-${d}.txt`),i=await ce(s,d),l=()=>i.forEach(c=>A(c).catch(()=>{})),f=U(t.workingDir),m=[];G(m,t.extraArgs,K.codex,e);const $=c=>{const p=["exec","--json","--skip-git-repo-check","-o",o];if(t.permissionMode==="bypassPermissions")p.push("--dangerously-bypass-approvals-and-sandbox");else{const E=t.permissionMode==="acceptEdits"?"workspace-write":"read-only";p.push("-s",E),k||p.push("-c","approval_policy=never")}N&&p.push("-c",`model_reasoning_effort=${N}`),p.push("-c","model_reasoning_summary=auto"),p.push(...se(t.mcp)),p.push(...ie(c)),t.model&&p.push("-m",t.model),p.push(...m);for(const E of i)p.push("-i",E);return p.push("-"),p},v=t.useLocalConfig!==!1,S={...process.env,...t.runEnv||{}};if(!v){const c=ne();c&&(S.CODEX_HOME=c)}const w=t.mcp?.serverName||"chatpanel_browser",x=ae(S.CODEX_HOME||process.env.CODEX_HOME||y.join(_.homedir(),".codex"));let g=Y("codex",t,[w]).filter(c=>x.has(c));const u=z(n,r),h=()=>le({args:$(g),cwd:f,env:S,prompt:u,outFile:o,emit:e,signal:a});try{let c=await h();if(c.policyBlocked&&(k=!0),!a?.aborted&&c.code!==0&&!c.streamed){const p=ee({agent:"codex",text:c.stderr,protect:[w],already:g});p&&x.has(p.server)&&(te("codex",p.server),e({type:"status",text:`MCP server "${p.server}" failed to load — ${p.short}. Skipping it and retrying.`}),g=[...g,p.server],c=await h())}if(a?.aborted)return;if(c.code!==0)throw new Error(Z("Codex",c.code,c.stderr,"",{agentId:"codex"}));c.said||e({type:"delta",text:c.text||"(no output)"}),e({type:"done",text:""})}finally{l()}}function pe(n,r,t={started:new Set,reasoned:new Set,n:0}){const s=n.type||"",e=n.item||{},a=e.type||"",d=s==="item.completed"||e.status==="completed"||e.status==="failed";if(a==="agent_message"&&d){const o=e.id||`msg_${t.n++}`,i=String(e.text||"");i&&!t.said?.has(o)&&((t.said||=new Set).add(o),r({type:"delta",text:`${t.saidAny?`
|
|
3
3
|
|
|
4
|
-
`:""}${
|
|
5
|
-
`);t.lastTodo!==
|
|
6
|
-
${
|
|
7
|
-
`}));return}(
|
|
4
|
+
`:""}${i}`}),t.saidAny=!0);return}if(a==="command_execution"||!a&&s.includes("command")){const o=e.id||`cmd_${t.n++}`;if(t.started.has(o)||(t.started.add(o),r({type:"tool",name:"shell",phase:"start",callId:o,input:{command:e.command||""}})),d){const i=e.exit_code===0||e.exit_code==null;r({type:"tool",name:"shell",phase:"done",callId:o,status:i?"ok":`exit ${e.exit_code}`,result:String(e.aggregated_output||"").slice(0,4e3)})}return}if(a==="file_change"||!a&&s.includes("patch")){const o=e.id||`edit_${t.n++}`,i=Array.isArray(e.changes)?e.changes.map(l=>l.path||l.file).filter(Boolean):[];t.started.has(o)||(t.started.add(o),r({type:"tool",name:"edit",phase:"start",callId:o,input:{files:i}})),d&&r({type:"tool",name:"edit",phase:"done",callId:o,status:"ok"});return}if(a==="web_search"){const o=e.id||`ws_${t.n++}`,i=e.action&&typeof e.action=="object"?e.action:{},l=e.query||i.query||"",f=i.url||"";t.started.has(o)||(t.started.add(o),r({type:"tool",name:"web_search",phase:"start",callId:o,input:{query:l,...f?{url:f}:{}}})),(d||s==="item.completed")&&r({type:"tool",name:"web_search",phase:"done",callId:o,status:"ok",result:f?`Opened ${f}`:l?`Searched the web for ${l}`:"Searched the web"});return}if(a==="mcp_tool_call"){const o=e.id||`mcp_${t.n++}`,i=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(t.started.has(o)||(t.started.add(o),r({type:"tool",name:i,phase:"start",callId:o,input:e.arguments&&typeof e.arguments=="object"?e.arguments:{}})),d){const l=e.status==="failed"||e.error!=null,f=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error,m=e.result==null?"":typeof e.result=="string"?e.result:JSON.stringify(e.result);r({type:"tool",name:i,phase:"done",callId:o,status:l?`error: ${String(f||"failed").slice(0,80)}`:"ok",result:String(l?f||"":m).slice(0,4e3)})}return}if(a==="todo_list"&&Array.isArray(e.items)&&e.items.length){const o=e.items.map(i=>`${i.completed?"☑":"☐"} ${i.text||""}`).join(`
|
|
5
|
+
`);t.lastTodo!==o&&(t.lastTodo=o,r({type:"status",text:`Plan:
|
|
6
|
+
${o}`}));return}if(a==="error"||s==="error"){const o=String(e.message||n.message||"");if(!o)return;if(/approval_policy.*(disallowed|not in the allowed set)/i.test(o)){t.policyBlocked=!0,t.policyNoted||(t.policyNoted=!0,r({type:"status",text:"Codex: your organisation pins approval_policy, so Codex will ask before actions it cannot run on its own. ChatPanel will stop passing its own setting."}));return}r({type:"status",text:`Codex: ${o.slice(0,300)}`});return}if(a==="reasoning"||!a&&s.includes("reasoning")){const o=e.id||`r_${t.n++}`,i=e.text||e.summary||"";i&&!t.reasoned.has(o)&&(t.reasoned.add(o),r({type:"reasoning",text:`${i}
|
|
7
|
+
`}));return}(s==="turn.started"||s==="thread.started")&&r({type:"status",text:"Codex working"})}export{Ce as available,Me as chat,de as chatCold,ie as codexDisableArgs,se as codexMcpConfigArgs,ae as configuredMcpServers,ne as ensureIsolatedHome,pe as forwardEvent,Ie as listModels,Ae as resetApprovalPolicy,ce as writeImages};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUID as u}from"node:crypto";import{relayTimeoutFor as f}from"./relay-timeout.js";import{stripHidden as d}from"./sanitize.js";const o=new Map;let r=null;const s=()=>{throw new Error("no chat is attached to this tool session")};function y(t,n){const e=u(),c={id:e,emit:t,specs:n,pending:new Map,nextId:0};return o.set(e,c),r=e,c}function w(t){return o.get(t)||null}function S(t,n,e){t.emit=n,e&&(t.specs=e),r=t.id}function T(t){for(const n of t.pending.values())n.reject(new Error("chat ended"));t.pending.clear(),t.emit=s}function k(t){const n=o.get(t);if(n){for(const e of n.pending.values())e.reject(new Error("chat ended"));if(o.delete(t),r===t){const e=[...o.keys()];r=e.length?e[e.length-1]:null}}}function v(){return r&&o.get(r)||null}function E(t,n,e){return new Promise((c,a)=>{const p=`t${++t.nextId}`,l=setTimeout(()=>{t.pending.delete(p),a(new Error("tool call timed out"))},f(t.specs,n));t.pending.set(p,{resolve:i=>{clearTimeout(l),c(m(i))},reject:i=>{clearTimeout(l),a(i)}});try{t.emit({type:"tool_request",session:t.id,id:p,name:n,input:e})}catch(i){t.pending.delete(p),clearTimeout(l),a(i)}})}function m(t){if(t==null)return{content:[{type:"text",text:"ok"}]};if(typeof t=="string")return{content:[{type:"text",text:d(t)}]};const n=[];if(t.text&&n.push({type:"text",text:d(String(t.text))}),typeof t.image=="string"){const e=/^data:([^;]+);base64,(.+)$/s.exec(t.image);e&&n.push({type:"image",data:e[2],mimeType:e[1]})}return n.length||n.push({type:"text",text:"ok"}),{content:n}}export{v as activeSession,y as createSession,k as deleteSession,w as getSession,S as rebindSession,E as relayToolCall,T as releaseSession,m as toMcpContent};
|
package/src/proc.js
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import{execFileSync as f}from"node:child_process";const
|
|
2
|
-
`)){const[
|
|
1
|
+
import{execFileSync as f}from"node:child_process";import m from"node:os";const b=process.platform==="win32"?{}:{detached:!0};function c(t){if(!t||process.platform==="win32")return[];let e="";try{e=f("ps",["-eo","pid=,ppid="],{encoding:"utf8",timeout:2e3})}catch{return[]}const r=new Map;for(const n of e.split(`
|
|
2
|
+
`)){const[u,i]=n.trim().split(/\s+/).map(Number);!u||!i||(r.has(i)||r.set(i,[]),r.get(i).push(u))}const o=[],s=(n,u=0)=>{if(!(u>20))for(const i of r.get(n)||[])o.push(i),s(i,u+1)};return s(t),o}function p(t,e,r=[]){if(t?.pid){for(const o of r.length?r:c(t.pid))try{process.kill(o,e)}catch{}try{process.kill(-t.pid,e);return}catch{}try{t.kill(e)}catch{}}}function y(t,e,{graceMs:r=1500}={}){if(!e||!t)return()=>{};const o=()=>{const s=c(t.pid);p(t,"SIGTERM",s);const n=setTimeout(()=>p(t,"SIGKILL",s),r);n.unref&&n.unref()};return e.aborted?(o(),()=>{}):(e.addEventListener("abort",o,{once:!0}),()=>{try{e.removeEventListener("abort",o)}catch{}})}function k(t,{graceMs:e=1500}={}){if(!t?.pid)return;const r=c(t.pid);p(t,"SIGTERM",r);const o=setTimeout(()=>p(t,"SIGKILL",r),e);o.unref&&o.unref()}function d(t){if(!t||process.platform==="win32")return 0;const e=[t,...c(t)];try{const r=f("ps",["-o","rss=","-p",e.join(",")],{encoding:"utf8",timeout:2e3});let o=0;for(const s of r.split(`
|
|
3
|
+
`)){const n=Number(s.trim());Number.isFinite(n)&&(o+=n)}return o*1024}catch{return 0}}function x(){return m.totalmem()}export{y as killOnAbort,p as killTree,b as spawnGroupOpts,k as terminateTree,x as totalMemoryBytes,d as treeRssBytes};
|
package/src/rpc-child.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{spawn as I}from"node:child_process";import{spawnGroupOpts as J,terminateTree as T}from"./proc.js";function N(p){let s="";return f=>{s+=f.toString();let d;for(;(d=s.indexOf(`
|
|
2
|
+
`))>=0;){const a=s.slice(0,d).trim();s=s.slice(d+1),a&&p(a)}}}function q(p,s,{cwd:f,env:d,spawnOpts:a=null,onMessage:j=()=>{},onRequest:g=null,onStderr:E=()=>{},onExit:O=()=>{},jsonrpc:x=!0,spawnImpl:$=I}={}){const n=$(p,s,{...a||{cwd:f||void 0,env:d,...J},stdio:["pipe","pipe","pipe"]}),i=new Map;let v=0,o=!1,l=null;const m=new Set,c=r=>{if(o||!n.stdin.writable)throw new Error("agent process is not running");n.stdin.write(`${JSON.stringify(r)}
|
|
3
|
+
`)},P=r=>{for(const e of i.values())clearTimeout(e.timer),e.reject(r);i.clear()};n.stdout.on("data",N(r=>{if(!r.startsWith("{"))return;let e;try{e=JSON.parse(r)}catch{return}if(x&&e.id!=null&&!e.method&&i.has(e.id)){const t=i.get(e.id);i.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Object.assign(new Error(e.error.message||"rpc error"),{code:e.error.code,data:e.error.data})):t.resolve(e.result);return}if(x&&e.id!=null&&e.method){Promise.resolve().then(()=>g?g(e.method,e.params||{}):void 0).then(t=>{c(t===void 0?{jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`unsupported request: ${e.method}`}}:{jsonrpc:"2.0",id:e.id,result:t})}).catch(t=>{try{c({jsonrpc:"2.0",id:e.id,error:{code:-32e3,message:String(t?.message||t)}})}catch{}});return}try{j(e)}catch{}})),n.stderr.on("data",r=>{try{E(r.toString())}catch{}});const y=(r,e,t)=>{if(!o){o=!0,l={code:r,signal:e,error:t||null},P(t||new Error(`agent process exited (${e||r})`));try{O(l)}catch{}for(const h of m)h(l);m.clear()}};return n.on("error",r=>y(null,null,r)),n.on("close",(r,e)=>y(r,e)),{child:n,get pid(){return n.pid},get exited(){return o},get exitInfo(){return l},request(r,e={},{timeoutMs:t=3e4}={}){return new Promise((h,w)=>{const u=++v,S=setTimeout(()=>{i.delete(u),w(new Error(`${r}: no reply in ${Math.round(t/1e3)}s`))},t);i.set(u,{resolve:h,reject:w,timer:S});try{c({jsonrpc:"2.0",id:u,method:r,params:e})}catch(b){i.delete(u),clearTimeout(S),w(b)}})},notify(r,e={}){c({jsonrpc:"2.0",method:r,params:e})},send(r){c(r)},waitExit(){return o?Promise.resolve(l):new Promise(r=>m.add(r))},close({graceMs:r=1500}={}){if(o)return;try{n.stdin.end()}catch{}const e=setTimeout(()=>{o||T(n,{graceMs:r})},r);e.unref&&e.unref()},kill(){o||T(n,{graceMs:0})}}}export{q as spawnRpcChild,N as splitLines};
|
package/src/server.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createServer as
|
|
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 rt,selfUpdate as X,isEmbedded as ot}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.0",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"},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||"",o=ee(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const 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){u("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=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),N}async function ne(n,e,t){try{const o=await te(),r=n.method==="POST"?await f(n):{};if(t==="status")return a(e,200,await o.status());if(t==="connect"){const i=await o.connect(r);return a(e,200,{ok:!0,...i})}return t==="pair"?a(e,200,await o.pair()):t==="unpair"?a(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?a(e,200,await o.update(r)):t==="disconnect"?a(e,200,await o.stop({forget:!!r.forget})):a(e,404,{error:"unknown channel action"})}catch(o){return a(e,400,{error:o?.message||String(o)})}}function 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 o=Buffer.from(t),r=Buffer.from(v);return o.length===r.length&&de(o,r)}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 o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}async function It(n){const e=await Promise.all(Object.entries(T).filter(([,r])=>!r.hidden).map(async([r,{engine:i,label:l}])=>{const d=await i.available().catch(s=>({ok:!1,reason:String(s?.message||s)})),c=await Ce(r).catch(()=>[]);return{id:r,label:l,available:d.ok,reason:d.reason,connectors:c}})),t=ot()?{current:g,updateAvailable:!1,embedded:"gateway"}:await rt(g).catch(()=>({current:g,updateAvailable:!1})),o=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)}:{},...o?{skills:o}:{}})}async function Nt(n,e){const{index:t,problems:o}=await B({extraDirs:e});a(n,200,{ok:!0,skills:Pe(t),problems:o})}async function Rt(n,e){a(n,200,{ok:!0,quarantined:await Re(e)})}async function Ht(n,e,t){const{index:o}=await B({extraDirs:t}),r=$e(o,e);if(!r)return a(n,404,{ok:!1,error:"unknown skill"});a(n,200,{ok:!0,skill:r})}async function _t(n,e,t,o){const{index:r}=await B({extraDirs:o}),i=await Ie(r,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 re(n,e=""){const t=await Mt();if(e){const o=t.find(r=>r.id===e);return o?a(n,200,o):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 o=T[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});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 r=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
|
|
3
3
|
|
|
4
|
-
`)};let i=!1;const
|
|
4
|
+
`)};let i=!1;const l=`run_${Math.random().toString(36).slice(2,10)}`,d=q(l),c={signal:d.signal,abort:()=>d.cancel("client")},s=()=>{i=!0,d.cancel("disconnected")};n.on("close",s),e.on("close",s),e.on("error",s);const h=p=>{i||r(p)};r({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){r({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);r({type:"workdir",path:p,isDefault:!E,writeScope:y||void 0}),r({type:"status",text:`Working in ${p}${E?"":" (default)"}`}),y&&r({type:"status",text:y}),C=await je(p),C&&r({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&&r({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&r({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(h,t.pageTools.specs),W.mcp={url:`http://${k}:${O}/mcp/${P.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs});try{await o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:W,images:Array.isArray(t.images)?t.images:[]},h,{signal:c.signal})}catch(p){u("error",`${t.agent} chat failed: ${p?.message||p}`),r({type:"error",error:p?.message||String(p)})}finally{if(!i){const p=await Je(b,C).catch(()=>null);p&&h({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 o=await f(n);if(t==="/connections")try{return a(e,200,{ok:!0,connection:Ke(o.connection||o,{token:o.token||null})})}catch(i){return a(e,400,{error:String(i?.message||i)})}const r=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return r?r[2]==="delete"?a(e,200,{ok:ze(r[1])}):a(e,200,Ye(r[1],o.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 o=await f(n);if(t==="/worktrees"){const r=await z({repo:o.repo,projectId:o.projectId,jobId:o.jobId,base:o.base||null});return a(e,r.error?400:200,r.error?{error:r.error}:{ok:!0,...r})}if(t==="/worktrees/remove"){const r=await Qe({projectId:o.projectId,jobId:o.jobId,force:!!o.force});return a(e,r.ok?200:400,r)}return a(e,404,{error:"Not found"})}async function S(n,e,t){const o=T[n.agent];if(!o||o.hidden)throw new I(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const r=await o.engine.available().catch(s=>({ok:!1,reason:s?.message||String(s)}));if(!r.ok)throw new I(r.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 c="";try{return await o.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},s=>{s?.type==="delta"&&s.text?(c+=s.text,e(s.text)):s?.type==="done"&&s.text&&!c&&(c=s.text,e(s.text))},{signal:l.signal}),c}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
|
|
|
6
|
-
`)}function
|
|
7
|
-
data: ${JSON.stringify(
|
|
6
|
+
`)}function H(n,e,t){n.writableEnded||n.write(`event: ${e}
|
|
7
|
+
data: ${JSON.stringify(t)}
|
|
8
8
|
|
|
9
|
-
`)}async function B(t,e,n,r){try{return n(await f(t))}catch(o){return a(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new R(`Bad JSON: ${o.message}`):o)),null}}async function Ft(t,e){const n=await B(t,e,yt,w);if(!n)return;if(!n.stream)try{const o=await S(n,()=>{},e);return a(e,200,ht(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,w(o))}_(e);const r=dt(n.requestedModel,o=>A(e,o));try{await S(n,o=>r.delta(o),e),r.done()}catch(o){A(e,w(o))}A(e,"[DONE]"),e.end()}async function Jt(t,e){const n=await B(t,e,wt,w);if(!n)return;if(!n.stream)try{const o=await S(n,()=>{},e);return a(e,200,mt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,w(o))}_(e);const r=ut(n.requestedModel,o=>A(e,o));try{await S(n,o=>r.delta(o),e),r.done()}catch(o){A(e,w(o))}A(e,"[DONE]"),e.end()}async function Kt(t,e){const n=await B(t,e,bt,w);if(!n)return;if(!n.stream)try{const o=await S(n,()=>{},e);return a(e,200,ft(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,w(o))}_(e);const r=St(n.requestedModel,o=>M(e,o.type,o));try{await S(n,o=>r.delta(o),e),r.done()}catch(o){const i={type:"error",sequence_number:0,...w(o)};M(e,"error",i)}e.end()}async function zt(t,e){const n=await B(t,e,gt,L);if(!n)return;if(!n.stream)try{const o=await S(n,()=>{},e);return a(e,200,pt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,L(o))}_(e);const r=lt(n.requestedModel,(o,i)=>M(e,o,i));try{await S(n,o=>r.delta(o),e),r.done()}catch(o){M(e,"error",L(o))}e.end()}async function Vt(t,e){let n={};try{n=await f(t)||{}}catch{}const r=String(n.id||"").trim(),o=r?st(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),a(e,200,{ok:!0,cancelled:o})}async function ie(t,e,n){let r;try{r=await f(t)}catch{return a(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=n?v.get(n):Tt(),i=l=>{o&&e.setHeader("Mcp-Session-Id",o.id),a(e,200,{jsonrpc:"2.0",id:r.id??null,result:l})},s=(l,c)=>a(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:l,message:c}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return i({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const d=Be();if(r.method==="tools/list"){const l=o?o.specs.map(c=>({name:c.name,description:c.description,inputSchema:c.parameters||{type:"object",properties:{}}})):[];return i({tools:[...d,...l]})}if(r.method==="tools/call"){const l=await Ge(r.params?.name,r.params?.arguments||{});if(l)return i(l);if(!o)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return i(await vt(o,r.params?.name,r.params?.arguments||{}))}catch(c){return i({content:[{type:"text",text:`error: ${c?.message||c}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function Yt(t,e){let n;try{n=await f(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=n.server||{},o=n.message;if(!r.command||!o)return a(e,400,{error:"need server.command and message"});try{const i=await it({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd},o);return o.id==null?(e.writeHead(202),e.end()):a(e,200,i)}catch(i){return a(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(i?.message||i)}})}}async function Xt(t,e){let n;try{n=await f(t)}catch(p){return a(e,400,{error:"Bad JSON: "+p.message})}const{url:r,headers:o,message:i}=n||{};if(!r||!i)return a(e,400,{error:"need url and message"});let s;try{s=Z(r)}catch(p){return a(e,400,{error:String(p?.message||p)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[p,m]of Object.entries(o)){const b=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(b)||b.startsWith("x-"))&&(d[p]=String(m))}const l=new AbortController,c=setTimeout(()=>l.abort(),3e4);try{const p=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(i),redirect:"follow",signal:l.signal});try{p.url&&Z(p.url)}catch(b){return a(e,400,{error:String(b?.message||b)})}const m=await p.text().catch(()=>"");return a(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",body:m})}catch(p){const m=p?.name==="AbortError"?"timed out":String(p?.message||p);return a(e,502,{error:`couldn't reach MCP server ${s.host}: ${m}`})}finally{clearTimeout(c)}}const se=256*1024,Qt=5,Zt=8e3;async function qt(t){let e=q(t);const n=new AbortController,r=setTimeout(()=>n.abort(),Zt);try{for(let o=0;o<=Qt;o++){const i=await fetch(e.href,{method:"GET",redirect:"manual",signal:n.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${g} (+link-title)`}});if(i.status>=300&&i.status<400&&i.headers.get("location")){if(e=q(new URL(i.headers.get("location"),e).href),i.body)try{await i.body.cancel()}catch{}continue}if(!i.ok){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}const s=i.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}return{title:nn(await en(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function en(t){if(!t.body?.getReader)return(await t.text().catch(()=>"")).slice(0,se);const e=t.body.getReader(),n=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:i,value:s}=await e.read();if(i||(o+=s.byteLength,r+=n.decode(s,{stream:!0}),/<\/title\s*>/i.test(r)||o>=se))break}}finally{try{await e.cancel()}catch{}}return r}function tn(t){return String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,n)=>{try{return String.fromCodePoint(+n)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,n)=>{try{return String.fromCodePoint(parseInt(n,16))}catch{return""}})}function nn(t){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(t);return e?tn(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function on(t,e){let n;try{n=await f(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=n&&n.url;if(!r||typeof r!="string")return a(e,400,{error:"need url"});try{const o=await qt(r);return a(e,200,{title:o.title||null,url:o.url||r})}catch(o){const i=o?.name==="AbortError"?"timed out":String(o?.message||o);return a(e,400,{error:`couldn't fetch title: ${i}`})}}async function rn(t,e){let n;try{n=await f(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=v.get(n.session);if(!r)return a(e,404,{error:"no such session"});const o=r.pending.get(n.id);return o?(r.pending.delete(n.id),o.resolve(n.result),a(e,200,{ok:!0})):a(e,404,{error:"no such pending call"})}async function an(t,e){let n;try{n=await f(t)}catch(d){return a(e,400,{error:"Bad JSON: "+d.message})}const r=T[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});const o=String(n.prompt||"").slice(0,6e3);if(!o)return a(e,400,{error:"Empty prompt"});const i=n.model||"",s=String(n.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let d="";return typeof r.engine.complete=="function"?d=await r.engine.complete({prompt:o,system:s,model:i}):await r.engine.chat({messages:[{role:"user",content:o}],system:s,options:{model:i}},l=>{l.type==="delta"?d+=l.text||"":l.type==="done"&&l.text&&(d+=l.text)}),a(e,200,{text:(d||"").trim()})}catch(d){return a(e,502,{error:d?.message||String(d)})}}async function sn(t,e){let n;try{n=await f(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=T[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});if(typeof r.engine.listModels!="function")return a(e,200,{models:[]});try{const o=await r.engine.listModels(n.options||{});return a(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return a(e,502,{error:o?.message||String(o)})}}async function cn(t,e){let n;try{n=await f(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=String(n.command||"").trim();if(!r)return a(e,400,{error:"No command"});let o=null;try{o=ot(r)}catch{o=null}return a(e,200,{ok:!!o,via:o?o.kind:null})}const ce=de(async(t,e)=>{if(xt(t,e),t.method==="OPTIONS")return e.writeHead(204),e.end();let n;try{n=new URL(t.url,`http://${t.headers.host||"127.0.0.1"}`)}catch{return a(e,400,{error:"bad request"})}const r=Rt(t,n.pathname);if(r)return a(e,403,{error:r});try{if(t.method==="GET"&&n.pathname==="/health")return Ht(e);const o=n.searchParams.getAll("dir");if(t.method==="GET"&&n.pathname==="/skills")return _t(e,o);if(t.method==="GET"&&n.pathname==="/skills-quarantined")return Mt(e,o);if(t.method==="GET"&&n.pathname.startsWith("/skills/")){const i=n.pathname.slice(8),s=i.indexOf("/file/");return s===-1?Bt(e,decodeURIComponent(i),o):Gt(e,decodeURIComponent(i.slice(0,s)),decodeURIComponent(i.slice(s+6)),o)}if(n.pathname==="/connections"||n.pathname.startsWith("/connections/"))return jt(t,e,n.pathname);if(n.pathname==="/worktrees"||n.pathname.startsWith("/worktrees/"))return Wt(t,e,n.pathname);if(t.method==="GET"&&n.pathname==="/v1/models")return ae(e);if(t.method==="GET"&&n.pathname.startsWith("/v1/models/"))return ae(e,decodeURIComponent(n.pathname.slice(11)));if(t.method==="GET"&&n.pathname==="/debug"){const i=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return a(e,200,{version:g,agents:Object.fromEntries(et.map(s=>[s,i?Y(s)||null:!!Y(s)])),...i?{home:P.homedir(),path:process.env.PATH}:{}})}if(t.method==="POST"&&n.pathname==="/chat")return Lt(t,e);if(t.method==="POST"&&n.pathname==="/v1/chat/completions")return Ft(t,e);if(t.method==="POST"&&n.pathname==="/v1/completions")return Jt(t,e);if(t.method==="POST"&&n.pathname==="/v1/responses")return Kt(t,e);if(t.method==="POST"&&n.pathname==="/v1/messages")return zt(t,e);if(n.pathname==="/mcp"){if(t.method==="POST")return ie(t,e,null);if(t.method==="GET")return e.writeHead(405),e.end()}if(n.pathname.startsWith("/mcp/")){const i=decodeURIComponent(n.pathname.slice(5));if(t.method==="POST")return ie(t,e,i);if(t.method==="GET")return e.writeHead(405),e.end();if(t.method==="DELETE")return te(i),e.writeHead(204),e.end()}if(t.method==="GET"&&n.pathname==="/channels")return re(t,e,"status");if(t.method==="POST"&&n.pathname.startsWith("/channels/"))return re(t,e,n.pathname.slice(10));if(t.method==="POST"&&n.pathname==="/cancel")return Vt(t,e);if(t.method==="POST"&&n.pathname==="/tool-result")return rn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-local")return Yt(t,e);if(t.method==="POST"&&n.pathname==="/mcp-remote")return Xt(t,e);if(t.method==="POST"&&n.pathname==="/fetch-title")return on(t,e);if(t.method==="POST"&&n.pathname==="/complete")return an(t,e);if(t.method==="POST"&&n.pathname==="/list-models")return sn(t,e);if(t.method==="POST"&&n.pathname==="/agent-check")return cn(t,e);if(t.method==="POST"&&n.pathname==="/update")return Dt(e);a(e,404,{error:"Not found"})}catch(o){a(e,500,{error:o?.message||String(o)})}});function u(t,e){(t==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function ln(t){let e="";const n=[];let r=!1,o=!1;const i=()=>{o&&!r&&!n.length&&process.exit(0)},s=async()=>{if(!r){for(r=!0;n.length;){const d=n.shift();let l;try{l=JSON.parse(d)}catch{continue}try{const c=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(l.id==null)continue;const p=(await c.text()).trim();p&&process.stdout.write(p+`
|
|
10
|
-
`)}catch(
|
|
11
|
-
`)}}
|
|
12
|
-
`))>=0;){const
|
|
9
|
+
`)}async function _(n,e,t,o){try{return t(await f(n))}catch(r){return a(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new I(`Bad JSON: ${r.message}`):r)),null}}async function Lt(n,e){const t=await _(n,e,wt,w);if(!t)return;if(!t.stream)try{const r=await S(t,()=>{},e);return a(e,200,mt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,w(r))}R(e);const o=ut(t.requestedModel,r=>A(e,r));try{await S(t,r=>o.delta(r),e),o.done()}catch(r){A(e,w(r))}A(e,"[DONE]"),e.end()}async function Wt(n,e){const t=await _(n,e,bt,w);if(!t)return;if(!t.stream)try{const r=await S(t,()=>{},e);return a(e,200,ft(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,w(r))}R(e);const o=ht(t.requestedModel,r=>A(e,r));try{await S(t,r=>o.delta(r),e),o.done()}catch(r){A(e,w(r))}A(e,"[DONE]"),e.end()}async function jt(n,e){const t=await _(n,e,St,w);if(!t)return;if(!t.stream)try{const r=await S(t,()=>{},e);return a(e,200,gt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,w(r))}R(e);const o=kt(t.requestedModel,r=>H(e,r.type,r));try{await S(t,r=>o.delta(r),e),o.done()}catch(r){const i={type:"error",sequence_number:0,...w(r)};H(e,"error",i)}e.end()}async function Jt(n,e){const t=await _(n,e,yt,U);if(!t)return;if(!t.stream)try{const r=await S(t,()=>{},e);return a(e,200,pt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,U(r))}R(e);const o=dt(t.requestedModel,(r,i)=>H(e,r,i));try{await S(t,r=>o.delta(r),e),o.done()}catch(r){H(e,"error",U(r))}e.end()}async function Ft(n,e){let t={};try{t=await f(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?it(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),a(e,200,{ok:!0,cancelled:r})}async function oe(n,e,t){let o;try{o=await f(n)}catch{return a(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=t?F(t):Be(),i=c=>{r&&e.setHeader("Mcp-Session-Id",r.id),a(e,200,{jsonrpc:"2.0",id:o.id??null,result:c})},l=(c,s)=>a(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:c,message:s}});if(o.id==null)return e.writeHead(202),e.end();if(o.method==="initialize")return i({protocolVersion:o.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const d=He();if(o.method==="tools/list"){const c=r?r.specs.map(s=>({name:s.name,description:s.description,inputSchema:s.parameters||{type:"object",properties:{}}})):[];return i({tools:[...d,...c]})}if(o.method==="tools/call"){const c=await _e(o.params?.name,o.params?.arguments||{});if(c)return i(c);if(!r)return l(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return i(await Ge(r,o.params?.name,o.params?.arguments||{}))}catch(s){return i({content:[{type:"text",text:`error: ${s?.message||s}`}],isError:!0})}}return l(-32601,`Method not found: ${o.method}`)}async function Kt(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const o=t.server||{},r=t.message;if(!o.command||!r)return a(e,400,{error:"need server.command and message"});try{const i=await at({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd},r);return r.id==null?(e.writeHead(202),e.end()):a(e,200,i)}catch(i){return a(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:-32e3,message:String(i?.message||i)}})}}async function zt(n,e){let t;try{t=await f(n)}catch(h){return a(e,400,{error:"Bad JSON: "+h.message})}const{url:o,headers:r,message:i}=t||{};if(!o||!i)return a(e,400,{error:"need url and message"});let l;try{l=Q(o)}catch(h){return a(e,400,{error:String(h?.message||h)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[h,m]of Object.entries(r)){const b=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(b)||b.startsWith("x-"))&&(d[h]=String(m))}const c=new AbortController,s=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(l.href,{method:"POST",headers:d,body:JSON.stringify(i),redirect:"follow",signal:c.signal});try{h.url&&Q(h.url)}catch(b){return a(e,400,{error:String(b?.message||b)})}const m=await h.text().catch(()=>"");return a(e,200,{status:h.status,sessionId:h.headers.get("Mcp-Session-Id")||null,contentType:h.headers.get("Content-Type")||"",body:m})}catch(h){const m=h?.name==="AbortError"?"timed out":String(h?.message||h);return a(e,502,{error:`couldn't reach MCP server ${l.host}: ${m}`})}finally{clearTimeout(s)}}const ae=256*1024,Vt=5,Yt=8e3;async function Xt(n){let e=Z(n);const t=new AbortController,o=setTimeout(()=>t.abort(),Yt);try{for(let r=0;r<=Vt;r++){const i=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${g} (+link-title)`}});if(i.status>=300&&i.status<400&&i.headers.get("location")){if(e=Z(new URL(i.headers.get("location"),e).href),i.body)try{await i.body.cancel()}catch{}continue}if(!i.ok){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}const l=i.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(l)){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}return{title:qt(await Qt(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function Qt(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,ae);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:i,value:l}=await e.read();if(i||(r+=l.byteLength,o+=t.decode(l,{stream:!0}),/<\/title\s*>/i.test(o)||r>=ae))break}}finally{try{await e.cancel()}catch{}}return o}function Zt(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function qt(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Zt(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function en(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=t&&t.url;if(!o||typeof o!="string")return a(e,400,{error:"need url"});try{const r=await Xt(o);return a(e,200,{title:r.title||null,url:r.url||o})}catch(r){const i=r?.name==="AbortError"?"timed out":String(r?.message||r);return a(e,400,{error:`couldn't fetch title: ${i}`})}}async function tn(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const o=F(t.session);if(!o)return a(e,404,{error:"no such session"});const r=o.pending.get(t.id);return r?(o.pending.delete(t.id),r.resolve(t.result),a(e,200,{ok:!0})):a(e,404,{error:"no such pending call"})}async function nn(n,e){let t;try{t=await f(n)}catch(d){return a(e,400,{error:"Bad JSON: "+d.message})}const o=T[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});const r=String(t.prompt||"").slice(0,6e3);if(!r)return a(e,400,{error:"Empty prompt"});const i=t.model||"",l=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let d="";return typeof o.engine.complete=="function"?d=await o.engine.complete({prompt:r,system:l,model:i}):await o.engine.chat({messages:[{role:"user",content:r}],system:l,options:{model:i}},c=>{c.type==="delta"?d+=c.text||"":c.type==="done"&&c.text&&(d+=c.text)}),a(e,200,{text:(d||"").trim()})}catch(d){return a(e,502,{error:d?.message||String(d)})}}async function rn(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=T[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof o.engine.listModels!="function")return a(e,200,{models:[]});try{const r=await o.engine.listModels(t.options||{});return a(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return a(e,502,{error:r?.message||String(r)})}}async function on(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const o=String(t.command||"").trim();if(!o)return a(e,400,{error:"No command"});let r=null;try{r=nt(o)}catch{r=null}return a(e,200,{ok:!!r,via:r?r.kind:null})}const ie=ce(async(n,e)=>{if(vt(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return a(e,400,{error:"bad request"})}const o=$t(n,t.pathname);if(o)return a(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return It(e);const r=t.searchParams.getAll("dir");if(n.method==="GET"&&t.pathname==="/skills")return Nt(e,r);if(n.method==="GET"&&t.pathname==="/skills-quarantined")return Rt(e,r);if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const i=t.pathname.slice(8),l=i.indexOf("/file/");return l===-1?Ht(e,decodeURIComponent(i),r):_t(e,decodeURIComponent(i.slice(0,l)),decodeURIComponent(i.slice(l+6)),r)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return Ut(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Dt(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return re(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return re(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const i=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return a(e,200,{version:g,agents:Object.fromEntries(qe.map(l=>[l,i?Y(l)||null:!!Y(l)])),...i?{home:x.homedir(),path:process.env.PATH}:{}})}if(n.method==="POST"&&t.pathname==="/chat")return Gt(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return Lt(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Wt(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return jt(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return Jt(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return oe(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const i=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return oe(n,e,i);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return J(i),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ne(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ne(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Ft(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return tn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local")return Kt(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return zt(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return en(n,e);if(n.method==="POST"&&t.pathname==="/complete")return nn(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return rn(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return on(n,e);if(n.method==="POST"&&t.pathname==="/update")return Bt(e);a(e,404,{error:"Not found"})}catch(r){a(e,500,{error:r?.message||String(r)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function an(n){let e="";const t=[];let o=!1,r=!1;const i=()=>{r&&!o&&!t.length&&process.exit(0)},l=async()=>{if(!o){for(o=!0;t.length;){const d=t.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const h=(await s.text()).trim();h&&process.stdout.write(h+`
|
|
10
|
+
`)}catch(s){c.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:c.id,error:{code:-32e3,message:String(s?.message||s)}})+`
|
|
11
|
+
`)}}o=!1,i()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",d=>{e+=d;let c;for(;(c=e.indexOf(`
|
|
12
|
+
`))>=0;){const s=e.slice(0,c).trim();e=e.slice(c+1),s&&t.push(s)}l()}),process.stdin.on("end",()=>{r=!0,i()}),process.stdin.resume()}function sn(){et(),tt(),Et(),ie.on("error",n=>{n&&n.code==="EADDRINUSE"&&(u("error",`Port ${O} is already in use — another app (or a second bridge) has it.`),u("error","Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings."),process.exit(1)),u("error",`bridge server error: ${n?.message||n}`),process.exit(1)});for(const n of["SIGINT","SIGTERM"])process.on(n,()=>{const e=st("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const t=ct("shutdown");t&&u("info",`shutdown: closed ${t} warm agent process${t===1?"":"es"}`),setTimeout(()=>process.exit(0),e||t?300:0).unref?.(),!e&&!t&&process.exit(0)});ie.listen(O,k,async()=>{u("info",`listening on http://${k}:${O}`),D.has(k)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:n,label:e,hidden:t}]of Object.entries(T)){if(t)continue;const o=await n.available().catch(()=>({ok:!1}));u("info",` ${o.ok?"✓":"✕"} ${e}${o.ok?"":" — "+(o.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),te().then(n=>n.startIfConfigured()).then(n=>{n?.skipped||(n?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${n?.error||"unknown error"}`))}).catch(n=>u("error",`channels: ${n?.message||n}`))})}function cn(){console.log(`ChatPanel Bridge v${g}
|
|
13
13
|
|
|
14
14
|
Usage:
|
|
15
15
|
chatpanel-bridge start the bridge (foreground) on ${k}:${O}
|
|
@@ -19,4 +19,4 @@ Usage:
|
|
|
19
19
|
chatpanel-bridge --update download & install the latest version, then restart
|
|
20
20
|
chatpanel-bridge --version print the version
|
|
21
21
|
|
|
22
|
-
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT`)}function
|
|
22
|
+
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT`)}function ln(){const n=process.argv,e=(...t)=>t.some(o=>n.includes(o));if(e("--help","-h"))return cn(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("--install")){try{Oe(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(t){u("error","Install failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--uninstall")){try{Ae(),u("info","Removed the login auto-start.")}catch(t){u("error","Uninstall failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--status")){let t=!1;try{t=xe()}catch(o){u("error",String(o?.message||o))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const se=process.argv.indexOf("--mcp-stdio");if(se>=0){const n=process.argv[se+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),an(n)}else process.argv.includes("--update")?(async()=>{try{const n=await X(g);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),j()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():ln()||sn();
|
package/src/warm-pool.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{treeRssBytes as S,totalMemoryBytes as U}from"./proc.js";const $=1024**3,w=U(),B=Number(process.env.CHATPANEL_WARM_MAX)||(w>=32*$?3:w>=16*$?2:1),L=Number(process.env.CHATPANEL_WARM_IDLE_MS)||(w>=16*$?10*6e4:5*6e4),D=Number(process.env.CHATPANEL_WARM_BUDGET_MB)*1024**2||Math.min(Math.floor(w*.2),3*$),N=400*1024**2,R=new Set;function z(a=[]){const n=(Array.isArray(a)?a:[]).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 I(a,i){if(a.answers!==i.answers||a.users.length!==i.users.length)return!1;for(let n=0;n<a.users.length;n++)if(a.users[n]!==i.users[n])return!1;return!0}function W({max:a=B,idleMs:i=L,budgetBytes:n=D,group:d=R,now:f=Date.now,measure:l=r=>S(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 b(){const e=f();for(const s of[...r])!s.busy&&e-s.lastUsed>i&&m(s,"idle")}function T(){h||!Number.isFinite(i)||i<=0||(h=setInterval(b,Math.min(i,6e4)),h.unref?.())}const M={get size(){return r.size},get bytes(){let e=0;for(const s of r)e+=s.bytes||0;return e},acquire({key:e,messages:s}){const u=z(s);for(const t of r)if(!(t.busy||!t.alive||t.key!==e)){if(!I(t.shape,u)){p(`warm ${t.label}: shape differs (have ${t.shape.users.length}u/${t.shape.answers}a, asked ${u.users.length}u/${u.answers}a)`);continue}return t.busy=!0,t.lastUsed=f(),p(`warm ${t.label}: reused`),t}return null},reserve({key:e,label:s=e}){const u=()=>{let o=null;for(const A of r)!A.busy&&(!o||A.lastUsed<o.lastUsed)&&(o=A);return o};if(r.size>=a){const o=u();if(!o)return null;m(o,"evicted")}const t=_||N;for(;v()+t>n;){const o=u();if(!o)return p(`warm ${s}: not kept — ${c(v())} warm + ~${c(t)} would pass the ${c(n)} budget`),null;m(o,`evicted for memory (${c(v())} warm)`)}const E={key:e,label:s,session:null,shape:{users:[],answers:0},busy:!0,alive:!0,lastUsed:f(),bytes:t};return r.add(E),p(`warm ${s}: starting (${r.size} live, ~${c(v())} of ${c(n)})`),T(),E},attach(e,s){return e.session=s,s.onExit?.(()=>{e.alive&&m(e,"process exited")}),e},release(e,{user:s,answered:u}){e.alive&&(typeof s=="string"&&(e.shape={users:[...e.shape.users,s.trim()],answers:e.shape.answers+(u?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)},reap:b};return d.add(M),M}export{D as WARM_BUDGET_BYTES,W as createWarmPool,z as historyShape};
|
package/src/warm.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{WARM_BUDGET_BYTES as n}from"./warm-pool.js";const r=new Map;function u(t,o){return r.set(t,o),o}function a(t="shutdown"){let o=0;for(const e of r.values())o+=e.size,e.closeAll(t);return o}function c(){const t={budgetMb:Math.round(n/1048576)};for(const[o,e]of r)t[o]={live:e.size,mb:Math.round(e.bytes/1024**2)};return t}export{a as closeWarmPools,u as registerWarmPool,c as warmStatus};
|