@chatpanel/bridge 0.29.5 → 0.32.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/engines/claude-warm.js +2 -2
- package/src/engines/codex-appserver.js +11 -10
- package/src/engines/codex.js +6 -6
- package/src/events/harness-cards.js +1 -1
- package/src/events/sandbox-grant.js +1 -1
- package/src/events/sandbox-policy.js +1 -1
- package/src/mcp-sessions.js +1 -1
- package/src/sandbox.js +1 -1
- package/src/server.js +5 -5
- package/src/sign-in.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.32.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
|
|
6
6
|
"keywords": [
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{unlink as G}from"node:fs/promises";import{spawnRpcChild as J}from"../rpc-child.js";import{spawn as z}from"node:child_process";import{track as K,sandbox as Q}from"../sandbox.js";import{createWarmPool as V}from"../warm-pool.js";import{registerWarmPool as X}from"../warm.js";import{createSession as I,deleteSession as L,rebindSession as Y,releaseSession as Z,relayPermission as O}from"../mcp-sessions.js";import{resolveClaude as ee,buildSpawnSpec as re}from"../env.js";import{loginRequired as W,signInMessage as U}from"../sign-in.js";import{pushExtraArgs as N,FORBIDDEN as R}from"./args.js";import{buildClaudeLaunch as H,claudePrompt as te,handleMessage as se,harnessChars as ae,writeImages as ne,answerControlRequest as le}from"./claude.js";const B=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,oe=5e3,h=X("claude",V({log:n=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${n}`)}}));function ie(n={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||n.warm===!1)}async function F({spec:n,args:S,cwd:r,env:A,spawnImpl:E,log:v=()=>{},ask
|
|
1
|
+
import{unlink as G}from"node:fs/promises";import{spawnRpcChild as J}from"../rpc-child.js";import{spawn as z}from"node:child_process";import{track as K,sandbox as Q}from"../sandbox.js";import{createWarmPool as V}from"../warm-pool.js";import{registerWarmPool as X}from"../warm.js";import{createSession as I,deleteSession as L,rebindSession as Y,releaseSession as Z,relayPermission as O}from"../mcp-sessions.js";import{resolveClaude as ee,buildSpawnSpec as re}from"../env.js";import{loginRequired as W,signInMessage as U}from"../sign-in.js";import{pushExtraArgs as N,FORBIDDEN as R}from"./args.js";import{buildClaudeLaunch as H,claudePrompt as te,handleMessage as se,harnessChars as ae,writeImages as ne,answerControlRequest as le}from"./claude.js";const B=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,oe=5e3,h=X("claude",V({log:n=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${n}`)}}));function ie(n={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||n.warm===!1)}async function F({spec:n,args:S,cwd:r,env:A,spawnImpl:E,log:v=()=>{},ask:b=null}){const w=[...S,"--input-format","stream-json"],[f,p,m]=re(n,w,r,A),c=await Q().wrap(f,p,m,{engine:"claude",cwd:r});c.record.layer==="none"&&v(`sandbox: claude session runs outside a sandbox — ${c.record.reason}`);const[i,y,u]=[c.bin,c.argv,c.opts];let e=null;const x=new Set;let g="",_=0,l=0;const t=J(i,y,{spawnOpts:u,spawnImpl:(s,a,d)=>K((E||z)(s,a,d),c,{kind:"warm"}),jsonrpc:!1,onStderr:s=>{g=(g+s).slice(-2e3),e&&e.touch()},onExit:s=>{if(v(`claude exited: ${s.signal||s.code}${g?` — ${g.trim().split(`
|
|
2
2
|
`).pop()}`:""}`),e){const a=e.apiError&&W(e.apiError)?U("Claude Code","claude"):e.apiError?`Claude Code reported an error: ${e.apiError}`:`Claude Code exited (${s.signal||s.code})${g?`: ${g.trim().split(`
|
|
3
|
-
`).pop().slice(0,200)}`:""}`;e.finish({status:"died",error:a})}for(const a of x)try{a(s)}catch{}},onMessage:s=>{if(!e||(e.touch(),s.type==="control_response"))return;if(s.type==="control_request"){const d=e;d.asking++,d.touch(),le(s
|
|
3
|
+
`).pop().slice(0,200)}`:""}`;e.finish({status:"died",error:a})}for(const a of x)try{a(s)}catch{}},onMessage:s=>{if(!e||(e.touch(),s.type==="control_response"))return;if(s.type==="control_request"){const d=e;d.asking++,d.touch(),le(s,b,$=>{try{t.send($)}catch{}}).catch(()=>{}).finally(()=>{d.asking--,e===d&&d.touch()});return}const a=se(s,e.emit,e.streamedAny,r,e.flow);a.streamed&&(e.streamedAny=!0),a.result!=null&&(e.resultText=a.result),a.apiError&&(e.apiError=a.apiError),s.type==="result"&&(e.apiError&&W(e.apiError)?e.finish({status:"failed",error:U("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 t.pid},get alive(){return!t.exited},onExit(s){x.add(s)},close(){t.close()},async turn({prompt:s,emit:a,signal:d,harness:$=null}){if(t.exited)throw new Error("Claude Code process is gone");if(e)throw new Error("a turn is already running on this process");let C=null,k;const D=new Promise(T=>{k=T}),o={emit:a,flow:{sawText:!1,tail:"",boundary:!1,costUsdBefore:l,harnessChars:$},streamedAny:!1,resultText:"",apiError:null,asking:0,touch(){clearTimeout(C),!o.asking&&(C=setTimeout(()=>o.finish({status:"timeout",error:`Claude Code timed out — no output for ${Math.round(B/1e3)}s.`}),B))},finish(T){e===o&&(clearTimeout(C),e=null,k(T))}};e=o,o.touch();const q=()=>{if(e===o){o.interrupted=!0;try{t.send({type:"control_request",request_id:`stop_${++_}`,request:{subtype:"interrupt"}})}catch{}setTimeout(()=>{e===o&&(o.finish({status:"killed",error:null}),t.kill())},oe).unref?.()}};if(d?.aborted)return o.finish({status:"killed",error:null}),{streamedAny:!1,resultText:"",status:"killed"};d?.addEventListener("abort",q,{once:!0});try{t.send({type:"user",message:{role:"user",content:s}})}catch(T){o.finish({status:"failed",error:T.message})}const M=await D;o.flow.costUsdTotal!=null&&(l=o.flow.costUsdTotal),d?.removeEventListener("abort",q),M.status==="timeout"&&t.kill();const j=M.status==="killed"?"killed":o.interrupted?"interrupted":M.status;return{streamedAny:o.streamedAny,resultText:o.resultText,status:j,error:M.error}}}}const P=new Set;async function ue({key:n,spec:S,options:r,label:A,launch:E=F,log:v=()=>{},force:b=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!b||!n||!S||P.has(n)||h.peek({key:n,messages:[{role:"user",content:""}]}))return!1;P.add(n);const w=h.reserve({key:n,label:`${A} (spare)`,evict:!1});if(!w)return P.delete(n),!1;let f=null,p=null;try{let m=r.mcp;const c=r.mcp?.specs||[];(m?.url&&c.length||r.approvals===!0)&&(f=I(()=>{},c),m?.url&&c.length&&(m={...m,url:`${m.url.replace(/\/[^/]*$/,"")}/${f.id}`})),p=await H({system:"",options:{...r,mcp:m},tag:`spare-${Date.now()}-${Math.random().toString(36).slice(2)}`});const i=[...p.args];N(i,r.extraArgs,R.claude,()=>{});const y=f,u=await E({spec:S,args:i,cwd:p.cwd,env:p.runEnv,ask:p.approvals&&y?x=>O(y,x):null});u.mcpSession=f,u.systemSent="",h.attach(w,u);const e=p.cleanup;return u.onExit(()=>{f&&L(f.id),e()}),h.release(w,{user:null,answered:!1}),v(`warm ${A}: spare ready`),!0}catch(m){return f&&L(f.id),p?.cleanup?.(),h.drop(w,`spare launch failed: ${m.message}`),!1}finally{P.delete(n)}}async function Ce({messages:n,system:S,options:r,images:A},E,{signal:v,launch:b=F}={}){if(!ie(r))return{handled:!1,reason:"not eligible"};const w=ee();if(!w)return{handled:!1,reason:"claude not resolvable"};const f=`${Date.now()}-${Math.random().toString(36).slice(2)}`,p=(r.mcp?.specs||[]).map(t=>t?.name).filter(Boolean),m=[];N(m,r.extraArgs,R.claude,()=>{});const c=JSON.stringify({agent:"claude",cwd:r.workingDir||"",mode:r.permissionMode||"default",model:r.model||"",local:r.useLocalConfig!==!1,reach:r.reach||"",tools:[...p].sort(),extra:m,approvals:r.approvals===!0,env:r.runEnv?Object.keys(r.runEnv).sort().map(t=>`${t}=${r.runEnv[t]}`):[],hosts:r.sandbox?.hosts?(Array.isArray(r.sandbox.hosts)?r.sandbox.hosts:String(r.sandbox.hosts).split(/[\s,;]+/)).map(t=>String(t).trim().toLowerCase()).filter(Boolean).sort():[],outside:r.sandbox?.outside===!0});let i=h.acquire({key:c,messages:n}),y=!1;if(!i){if(i=h.reserve({key:c,label:`claude ${r.workingDir||"home"}`}),!i)return{handled:!1,reason:"all warm slots busy"};y=!0;let t=null,s=null;try{let a=r.mcp;(a?.url&&p.length||r.approvals===!0)&&(t=I(E,a?.specs||[]),a?.url&&p.length&&(a={...a,url:`${a.url.replace(/\/[^/]*$/,"")}/${t.id}`})),s=await H({system:S,options:{...r,mcp:a},tag:f});const d=[...s.args];N(d,r.extraArgs,R.claude,E);const $=t,C=await b({spec:w,args:d,cwd:s.cwd,env:s.runEnv,ask:s.approvals&&$?D=>O($,D):null});C.mcpSession=t,C.systemSent=String(S||""),h.attach(i,C);const k=s.cleanup;C.onExit(()=>{t&&L(t.id),k()})}catch(a){return t&&L(t.id),s?.cleanup(),h.drop(i,`launch failed: ${a.message}`),{handled:!1,reason:a.message}}}const u=i.session;u.mcpSession&&Y(u.mcpSession,E,r.mcp?.specs);const e=n[n.length-1],x=await ne(A,f),g=String(S||""),_=te(y?n:[e],x,!y&&g!==u.systemSent?g:"");u.systemSent=g;let l;try{l=await u.turn({prompt:_,emit:E,signal:v,harness:ae({prompt:_,system:y?g:"",specs:y?r.mcp?.specs:null})})}finally{x.forEach(t=>G(t).catch(()=>{})),u.mcpSession&&Z(u.mcpSession)}if(v?.aborted||l.status==="interrupted")return l.status==="interrupted"&&u.alive?h.release(i,{user:String(e?.content||""),answered:l.streamedAny}):h.drop(i,"stopped"),{handled:!0};if(l.status!=="completed"){if(h.drop(i,l.error||l.status),!l.streamedAny)return{handled:!1,reason:l.error||l.status};throw new Error(l.error||`Claude Code ${l.status}`)}return E({type:"done",text:l.streamedAny?"":l.resultText}),h.release(i,{user:String(e?.content||""),answered:!0}),setTimeout(()=>{ue({key:c,spec:w,options:r,label:`claude ${r.workingDir||"home"}`,launch:b}).catch(()=>{})},250).unref?.(),{handled:!0}}export{Ce as chatWarm,F as launchClaudeSession,h as pool,ue as prewarmClaude,ie as warmEligible};
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import
|
|
2
|
-
`);try{return JSON.stringify(e)}catch{return String(e)}}function
|
|
1
|
+
import Y from"node:os";import R from"node:path";import{unlink as Q}from"node:fs/promises";import{spawnRpcChild as Z}from"../rpc-child.js";import{spawnGroupOpts as ee}from"../proc.js";import{spawn as te}from"node:child_process";import{track as re,sandbox as se,nestedSandboxLine as ne,grantedWriteRoots as j}from"../sandbox.js";import{createWarmPool as oe}from"../warm-pool.js";import{createSession as D,deleteSession as N,rebindSession as ae,releaseSession as ie,relayPermission as le}from"../mcp-sessions.js";import{buildCliPrompt as H}from"./prompt.js";import{codexMcpConfigArgs as W,codexDisableArgs as U,configuredMcpServers as de,redundantChatpanelServers as ce,ensureIsolatedHome as ue,writeImages as fe}from"./codex.js";import{disabledMcpServers as pe}from"../mcp-quarantine.js";import{resolveWorkdir as me}from"../workdir.js";import{registerWarmPool as he}from"../warm.js";const B=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,z=process.env.CHATPANEL_CODEX_EFFORT??"low",ge=9e4,F=5e3,A=he("codex",oe({log:e=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[codex] ${e}`)}}));let q=0;function Be(){q=0}const ye=e=>e&&typeof e=="object"?(Array.isArray(e.hosts)?e.hosts:String(e.hosts||"").split(/[\s,;]+/)).map(s=>String(s).trim().toLowerCase()).filter(Boolean).sort():[];function xe({agent:e="codex",cwd:s,options:t={},mcpNames:l=[],runEnv:i=null,disabled:f=[],roots:m=[]}){return JSON.stringify({agent:e,cwd:s,mode:t.permissionMode||"default",model:t.model||"",local:t.useLocalConfig!==!1,tools:[...l].sort(),env:i?Object.keys(i).sort().map(o=>`${o}=${i[o]}`):[],disabled:[...f].sort(),hosts:ye(t.sandbox),outside:t.sandbox?.outside===!0,roots:[...m].sort()})}function we(e={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CODEX_APPSERVER==="off"||e.warm===!1||e.extraArgs&&String(e.extraArgs).trim()||Date.now()<q)}function X(e){return e==="bypassPermissions"?"danger-full-access":e==="acceptEdits"?"workspace-write":"read-only"}function J(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e?.content))return e.content.map(s=>typeof s=="string"?s:s?.text||"").filter(Boolean).join(`
|
|
2
|
+
`);try{return JSON.stringify(e)}catch{return String(e)}}function Se(e,s,t,l){const i=e?.type||"",f=e?.id||`i_${l.n++}`,m=(o,u)=>{l.started.has(f)||(l.started.add(f),t({type:"tool",name:o,phase:"start",callId:f,input:u}))};if(i==="agentMessage"){s&&e.text&&!l.deltaItems.has(f)&&!l.said.has(f)&&(l.said.add(f),t({type:"delta",text:`${l.saidAny?`
|
|
3
3
|
|
|
4
|
-
`:""}${e.text}`}),
|
|
5
|
-
${e.text}
|
|
6
|
-
`);l
|
|
7
|
-
`
|
|
8
|
-
`)
|
|
4
|
+
`:""}${e.text}`}),l.saidAny=!0);return}if(i==="commandExecution"){if(m("shell",{command:e.command||""}),s){const o=e.exitCode===0||e.exitCode==null;t({type:"tool",name:"shell",phase:"done",callId:f,status:o?"ok":`exit ${e.exitCode}`,result:String(e.aggregatedOutput||"").slice(0,4e3)})}return}if(i==="fileChange"){const o=Array.isArray(e.changes)?e.changes.map(u=>u?.path||u?.file).filter(Boolean):[];m("edit",{files:o}),s&&t({type:"tool",name:"edit",phase:"done",callId:f,status:e.status==="failed"?"error":"ok"});return}if(i==="webSearch"){const o=e.action&&typeof e.action=="object"?e.action:{},u=e.query||o.query||"",r=o.url||"";m("web_search",{query:u,...r?{url:r}:{}}),s&&t({type:"tool",name:"web_search",phase:"done",callId:f,status:"ok",result:r?`Opened ${r}`:u?`Searched the web for ${u}`:"Searched the web"});return}if(i==="mcpToolCall"){const o=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(m(o,e.arguments&&typeof e.arguments=="object"?e.arguments:{}),s){const u=e.status==="failed"||e.error!=null,r=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error;t({type:"tool",name:o,phase:"done",callId:f,status:u?`error: ${String(r||"failed").slice(0,80)}`:"ok",result:String(u?r||"":J(e.result)).slice(0,4e3)});const w=!l.saidNested&&ne(`${r||""}
|
|
5
|
+
${J(e.result)}`,"Codex");w&&(l.saidNested=!0,t({type:"status",text:w}))}return}if(i==="plan"&&s&&e.text&&l.lastPlan!==e.text){l.lastPlan=e.text,t({type:"status",text:`Plan:
|
|
6
|
+
${e.text}`});return}if(i==="reasoning"&&s){if(l.deltaItems.has(f))return;const o=(Array.isArray(e.summary)?e.summary:[]).map(u=>typeof u=="string"?u:u?.text||"").filter(Boolean).join(`
|
|
7
|
+
`);o&&!l.reasoned.has(f)&&(l.reasoned.add(f),t({type:"reasoning",text:`${o}
|
|
8
|
+
`}))}}const be="mcpServer/elicitation/request",Ae={"item/commandExecution/requestApproval":{kind:"command",legacy:!1},execCommandApproval:{kind:"command",legacy:!0},"item/fileChange/requestApproval":{kind:"files",legacy:!1},applyPatchApproval:{kind:"files",legacy:!0}};function ve(e,s={}){const t=s&&typeof s=="object"?s:{};if(e==="command"){const i=y(Array.isArray(t.command)?t.command.join(" "):t.command);return{tool:"Bash",displayName:"Codex",input:{command:i},description:y(t.reason),path:null,rules:i?[{tool:"Bash",content:i}]:[],toolUseId:y(t.itemId||t.callId)||null}}const l=y(t.grantRoot);return{tool:"Edit",displayName:"Codex",input:l?{file_path:l}:{},description:y(t.reason)||"change files outside its working folder",path:l||null,rules:l?[{tool:"Edit",content:l}]:[],toolUseId:y(t.itemId)||null}}function Ce(e,s=!1){const t=e?.behavior==="allow";return s?{decision:t?"approved":"denied"}:{decision:t?e.scope==="chat"?"acceptForSession":"accept":"decline"}}const y=e=>String(e??"").replace(/\s+/g," ").trim().slice(0,200);function ke(e={}){const s=e&&typeof e=="object"?e:{},t=s._meta&&typeof s._meta=="object"?s._meta:{},l=s.requestedSchema?.properties,i=!l||typeof l=="object"&&!Object.keys(l).length;if(s.mode==="url"||!i||!y(s.message))return null;const f=y(t.tool_name)||`${y(s.serverName)||"plugin"}_elicitation`,m=t.tool_params&&typeof t.tool_params=="object"&&!Array.isArray(t.tool_params)?t.tool_params:{};let o=y(t.origin||m.origin);if(!o)try{o=JSON.stringify(m)}catch{o=""}return{tool:f,displayName:y(t.connector_name||t.tool_title)||f,input:m,description:y(s.message),path:null,rules:[{tool:f,content:o&&o!=="{}"?o:y(s.message)}],toolUseId:y(t.callId)||null}}function Ie(e){return e?.behavior==="allow"?{action:"accept",content:{}}:{action:"decline"}}function Ee(){return{n:0,started:new Set,said:new Set,reasoned:new Set,deltaItems:new Set,saidAny:!1,lastPlan:null}}async function G({bin:e="codex",cwd:s,env:t,configArgs:l=[],options:i={},spawnImpl:f,log:m=()=>{}}){const o=i.permissionMode||"default",u=o==="bypassPermissions";let r=null,w=!1;const E=new Set;let v="";const _=o!=="acceptEdits"&&o!=="bypassPermissions",k=await se().wrap(e,["app-server",...l],{cwd:s||void 0,env:t,...ee},{engine:"codex",cwd:s,readOnly:_}),S=k.record.layer==="none"?X(o):"danger-full-access";k.record.layer==="none"&&m(`sandbox: codex app-server runs outside a sandbox — ${k.record.reason}`);const x=Z(k.bin,k.argv,{cwd:s,env:t,spawnImpl:(d,n,c)=>re((f||te)(d,n,c),k,{kind:"warm"}),spawnOpts:k.opts,onStderr:d=>{v=(v+d).slice(-2e3)},onExit:d=>{m(`app-server exited: ${d.signal||d.code}${v?` — ${v.trim().split(`
|
|
9
|
+
`).pop()}`:""}`),r&&r.finish({status:"died",error:d.error?.message||`Codex exited (${d.signal||d.code})`});for(const n of E)try{n(d)}catch{}},onRequest:async(d,n)=>{const c=Ae[d];if(c){if(u)return c.legacy?{decision:"approved"}:{decision:"accept"};const a=r,C=ve(c.kind,n);if(a?.ask){a.hold();try{return Ce(await a.ask(C),c.legacy)}finally{r===a&&a.touch()}}return a?.emit({type:"status",text:c.kind==="command"?"Codex asked to run a command outside its sandbox — declined (ChatPanel could not ask you here; set Permissions to full access to allow).":"Codex asked to change files outside its folders — declined (ChatPanel could not ask you here; add the folder under Settings › Runtime, or set Permissions to full access)."}),c.legacy?{decision:"denied"}:{decision:"decline"}}if(d===be){const a=r,C=ke(n);if(C&&a?.ask){a.hold();try{return Ie(await a.ask(C))}finally{r===a&&a.touch()}}return a?.emit({type:"status",text:`Codex asked: ${y(n?.message)||`a question from ${n?.serverName||"a plugin"}`} — declined (${C?"ChatPanel could not ask you here":"ChatPanel cannot answer this kind of question yet"}).`}),{action:"decline"}}r?.emit({type:"status",text:`Codex asked for ${y(d)} — declined (ChatPanel cannot answer it).`})},onMessage:d=>{if(!d.method||!r)return;const n=d.params||{};if(n.threadId&&n.threadId!==r.threadId)return;r.touch();const c=d.method;if(c==="item/agentMessage/delta"){if(!n.delta)return;r.state.deltaItems.add(n.itemId),r.state.said.has(n.itemId)||(r.state.said.add(n.itemId),r.state.saidAny&&r.emit({type:"delta",text:`
|
|
9
10
|
|
|
10
|
-
`})),
|
|
11
|
-
`});else if(c==="item/started"||c==="item/completed"){const
|
|
12
|
-
`).filter(Boolean).pop()||"";throw new Error(n?`${
|
|
11
|
+
`})),r.state.saidAny=!0,r.streamed=!0,r.emit({type:"delta",text:n.delta})}else if(c==="item/reasoning/summaryTextDelta"||c==="item/reasoning/textDelta"){if(!n.delta)return;r.state.deltaItems.add(n.itemId),r.streamed=!0,r.emit({type:"reasoning",text:n.delta})}else if(c==="item/reasoning/summaryPartAdded")r.state.deltaItems.has(n.itemId)&&r.emit({type:"reasoning",text:`
|
|
12
|
+
`});else if(c==="item/started"||c==="item/completed"){const a=r.state.started.size+r.state.said.size;Se(n.item,c==="item/completed",r.emit,r.state),r.state.started.size+r.state.said.size>a&&(r.streamed=!0)}else if(c==="thread/tokenUsage/updated"){const a=n.tokenUsage?.last||n.tokenUsage?.total;a&&(r.usage={type:"usage",provider:"bridge",inputTokens:a.inputTokens||0,outputTokens:a.outputTokens||0,cacheReadTokens:a.cachedInputTokens||0,cacheWriteTokens:a.cacheWriteInputTokens||0,costUsd:null})}else if(c==="error"){const a=n.error?.message||"error";n.willRetry?r.emit({type:"status",text:`Codex: ${a.slice(0,200)} — retrying`}):r.lastError=a}else if(c==="turn/completed"){const a=n.turn||{};if(r.turnId&&a.id&&a.id!==r.turnId)return;r.finish({status:a.status||"completed",error:a.error?.message||r.lastError||null})}}});let b,I=!1;try{await x.request("initialize",{clientInfo:{name:"chatpanel-bridge",version:"1"},capabilities:{experimentalApi:!0}},{timeoutMs:2e4}),x.notify("initialized");const d=j(s),n=C=>x.request("thread/start",{cwd:s||void 0,sandbox:C,approvalPolicy:"never",...i.model?{model:i.model}:{},...d.length?{config:{sandbox_workspace_write:{writable_roots:d}}}:{}},{timeoutMs:ge});let c=await n(S);const a=String(c?.sandbox?.type||"");if(S==="danger-full-access"&&a&&a!=="dangerFullAccess"&&(c=await n(X(o)),I=!0),b=c?.thread?.id,!b)throw new Error("Codex app-server started no thread")}catch(d){x.kill();const n=v.trim().split(`
|
|
13
|
+
`).filter(Boolean).pop()||"";throw new Error(n?`${d.message}: ${n.slice(-300)}`:d.message)}return{threadId:b,get pid(){return x.pid},get alive(){return!x.exited},onExit(d){E.add(d)},close(){x.close()},async turn({prompt:d,imageFiles:n=[],emit:c,signal:a,ask:C=null}){if(x.exited)throw new Error("Codex process is gone");if(r)throw new Error("a turn is already running on this thread");const g=Ee();let p=null,$;const T=new Promise(P=>{$=P}),h={threadId:b,turnId:null,emit:c,state:g,streamed:!1,usage:null,lastError:null,ask:C,hold(){clearTimeout(p)},touch(){clearTimeout(p),p=setTimeout(()=>h.finish({status:"timeout",error:`Codex timed out — no output for ${Math.round(B/1e3)}s.`}),B)},finish(P){r===h&&(clearTimeout(p),r=null,$(P))}};r=h,h.touch();const L=async()=>{if(r===h){try{await x.request("turn/interrupt",{threadId:b,turnId:h.turnId},{timeoutMs:F})}catch{}setTimeout(()=>{r===h&&(h.finish({status:"killed",error:null}),x.kill())},F).unref?.()}};if(a?.aborted)return h.finish({status:"killed",error:null}),{streamed:!1,said:!1,status:"killed",usage:null};a?.addEventListener("abort",L,{once:!0}),I&&!w&&(w=!0,c({type:"status",text:"Your organisation’s Codex policy does not let ChatPanel’s sandbox replace Codex’s own, and Codex’s cannot start inside ChatPanel’s — so Codex will ask you before each command. “Allow for this chat” stops it asking again for the same command."})),c({type:"status",text:"Codex working"});try{const P=[{type:"text",text:d},...n.map(K=>({type:"localImage",path:K}))],V=await x.request("turn/start",{threadId:b,input:P,summary:"auto",...z?{effort:z}:{}},{timeoutMs:3e4});h.turnId=V?.turn?.id||null}catch(P){h.finish({status:"failed",error:P.message})}const M=await T;return a?.removeEventListener("abort",L),M.status==="timeout"&&x.kill(),h.usage&&c(h.usage),{streamed:h.streamed,said:g.saidAny,status:M.status,error:M.error,usage:h.usage}}}}const O=new Set;async function $e({key:e,cwd:s,env:t,configArgs:l,options:i,label:f,launch:m=G,force:o=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!o||!e||O.has(e)||A.peek({key:e,messages:[{role:"user",content:""}]}))return!1;O.add(e);const u=A.reserve({key:e,label:`${f} (spare)`,evict:!1});if(!u)return O.delete(e),!1;let r=null;try{const w=[...l];if(i.mcp?.url&&(i.mcp?.specs||[]).length){r=D(()=>{},i.mcp.specs);const _=i.mcp.url.replace(/\/[^/]*$/,"");w.unshift(...W({url:`${_}/${r.id}`,serverName:i.mcp?.serverName||"chatpanel_browser",specs:i.mcp.specs}))}const E=await m({cwd:s,env:t,configArgs:w,options:i});E.mcpSession=r,E.systemSent="",A.attach(u,E);const v=r;return E.onExit(()=>{v&&N(v.id)}),A.release(u,{user:null,answered:!1}),!0}catch(w){return r&&N(r.id),A.drop(u,`spare launch failed: ${w.message}`),!1}finally{O.delete(e)}}async function ze({messages:e,system:s,options:t,images:l},i,{signal:f,launch:m=G}={}){if(!we(t))return{handled:!1,reason:"not eligible"};const o=me(t.workingDir),u={...process.env,...t.runEnv||{}};if(t.useLocalConfig===!1){const p=ue();p&&(u.CODEX_HOME=p)}const r=t.mcp?.serverName||"chatpanel_browser",w=u.CODEX_HOME||R.join(Y.homedir(),".codex"),E=de(w),v=(t.mcp?.specs||[]).map(p=>p?.name).filter(Boolean),_=[...new Set([...pe("codex",t,[r]),...v.length?ce(w):[]])].filter(p=>E.has(p)),k=xe({cwd:o,options:t,mcpNames:v,runEnv:t.runEnv||null,disabled:_,roots:j(o)});let S=A.acquire({key:k,messages:e}),x=!1,b=null;if(!S){if(S=A.reserve({key:k,label:`codex ${R.basename(o||"")}`}),!S)return{handled:!1,reason:"all warm slots busy"};x=!0;try{const p=[];if(t.mcp?.url&&v.length){b=D(i,t.mcp.specs);const h=t.mcp.url.replace(/\/[^/]*$/,"");p.push(...W({url:`${h}/${b.id}`,serverName:r,specs:t.mcp.specs}))}p.push(...U(_));const $=await m({cwd:o,env:u,configArgs:p,options:t});$.mcpSession=b,$.systemSent="",A.attach(S,$);const T=b;$.onExit(()=>{T&&N(T.id)})}catch(p){return b&&N(b.id),A.drop(S,`launch failed: ${p.message}`),/unknown|unrecognized|unexpected argument|app-server/i.test(p.message)&&(q=Date.now()+10*6e4),{handled:!1,reason:p.message}}}const I=S.session;I.mcpSession&&ae(I.mcpSession,i,t.mcp?.specs);const d=e[e.length-1],n=String(s||""),c=x?H(e,n):H([d],n&&n!==I.systemSent?n:""),a=`${Date.now()}-${Math.random().toString(36).slice(2)}`,C=await fe(l,a);let g;try{const p=t.approvals===!0&&t.permissionSession?$=>le(t.permissionSession,null,{request:$}):null;g=await I.turn({prompt:c,imageFiles:C,emit:i,signal:f,ask:p})}finally{C.forEach(p=>Q(p).catch(()=>{})),I.mcpSession&&ie(I.mcpSession)}if(I.systemSent=n,f?.aborted||g.status==="interrupted")return g.status==="interrupted"&&I.alive?A.release(S,{user:String(d?.content||""),answered:g.streamed}):A.drop(S,"stopped"),{handled:!0};if(g.status!=="completed"){if(A.drop(S,g.error||g.status),!g.streamed)return{handled:!1,reason:g.error||g.status};throw new Error(g.error||`Codex ${g.status}`)}return g.said||i({type:"delta",text:"(no output)"}),i({type:"done",text:""}),A.release(S,{user:String(d?.content||""),answered:!0}),setTimeout(()=>{$e({key:k,cwd:o,env:u,configArgs:U(_),options:t,label:`codex ${R.basename(o||"")}`,launch:m}).catch(()=>{})},250).unref?.(),{handled:!0}}export{ze as chatWarm,ve as codexApprovalRequest,Ce as codexApprovalResponse,ke as codexElicitationRequest,Ie as codexElicitationResponse,Se as forwardV2Item,G as launchCodexSession,Ee as newTurnState,A as pool,$e as prewarmCodex,Be as resetSupport,we as warmEligible,xe as warmKey};
|
package/src/engines/codex.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{spawn as
|
|
2
|
-
`))>=0;){const
|
|
1
|
+
import{spawn as F}from"node:child_process";import{killOnAbort as H,spawnGroupOpts as L}from"../proc.js";import{track as X,sandbox as J,noteSandbox as R,grantedWriteRoots as W}from"../sandbox.js";import{harnessDirArgs as q}from"../events/harness-cards.js";import{readFile as z,unlink as N,writeFile as G}from"node:fs/promises";import{existsSync as j,mkdirSync as K,symlinkSync as U,readFileSync as I}from"node:fs";import $ from"node:os";import h from"node:path";import{agentAvailable as Z,selfMcpStdio as Q,resolveCommand as V}from"../env.js";import{relayTimeoutMax as Y}from"../relay-timeout.js";import{buildCliPrompt as ee}from"./prompt.js";import{pushExtraArgs as te,FORBIDDEN as re}from"./args.js";import{resolveWorkdir as oe}from"../workdir.js";import{summarizeCliError as se}from"../cli-errors.js";import{signInStatus as ne,signInMessage as ae}from"../sign-in.js";import{disabledMcpServers as ce,planMcpRetry as ie,quarantine as le}from"../mcp-quarantine.js";import{chatWarm as de}from"./codex-appserver.js";const D=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,T=process.env.CHATPANEL_CODEX_EFFORT??"low",pe=["gpt-5-codex","gpt-5","o3","o4-mini"];let E=!1;function He(){E=!1}async function Le(){const s=new Set;try{const r=process.env.CODEX_HOME||h.join($.homedir(),".codex"),t=I(h.join(r,"config.toml"),"utf8");for(const a of t.matchAll(/(?:^|\n)\s*model\s*=\s*["']([^"'\n]+)["']/g))s.add(a[1].trim())}catch{}for(const r of pe)s.add(r);return[...s]}const M=h.join($.homedir(),".chatpanel","codex-home");let P=!1;function ue(){if(!P)try{K(M,{recursive:!0});const s=h.join($.homedir(),".codex","auth.json"),r=h.join(M,"auth.json");if(j(s)&&!j(r))try{U(s,r)}catch{}P=!0}catch{return null}return M}let O=!1,B=0;async function Xe(){if(Date.now()-B>(O?3e4:4e3)){B=Date.now();try{O=Z("codex")}catch{O=!1}}return O?await ne("codex",V("codex")).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:ae("Codex","codex")}:{ok:!0}:{ok:!1,reason:"codex not found on PATH. Install it and run `codex login`."}}function fe(s){if(!s?.url)return[];const r=s.serverName||"chatpanel_browser",{command:t,args:a}=Q(s.url),e=["-c",`mcp_servers.${r}.command=${JSON.stringify(t)}`,"-c",`mcp_servers.${r}.args=${JSON.stringify(a)}`,"-c",`mcp_servers.${r}.default_tools_approval_mode="approve"`,"-c",`mcp_servers.${r}.startup_timeout_sec=30`,"-c",`mcp_servers.${r}.tool_timeout_sec=${Math.ceil(Y(s.specs)/1e3)}`],n=[...new Set((s.specs||[]).map(l=>l?.name).filter(Boolean))];return n.length&&e.push("-c",`mcp_servers.${r}.enabled_tools=${JSON.stringify(n)}`),e}function me(s){try{const r=I(h.join(s,"config.toml"),"utf8"),t=new Set;for(const a of r.matchAll(/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*[.\]]/gm))t.add(a[1]);return t}catch{return new Set}}function he(s){const r=new Set;try{const t=I(h.join(s,"config.toml"),"utf8"),a=/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*\]\s*$([\s\S]*?)(?=^\s*\[|$(?![\r\n]))/gm;for(const e of t.matchAll(a)){const n=e[2]||"",l=/^\s*command\s*=\s*"([^"]*)"/m.exec(n)?.[1]||"",o=/^\s*url\s*=\s*"([^"]*)"/m.exec(n)?.[1]||"";(/chatpanel-(gateway|bridge)(\.js|\.cmd|\.exe)?$/.test(l)||/^https?:\/\/(127\.0\.0\.1|localhost):43(19|20)\//.test(o))&&r.add(e[1])}}catch{}return r}function ge(s=[]){return s.flatMap(r=>["-c",`mcp_servers.${r}.enabled=false`])}async function ye(s,r){const t=[];for(let a=0;a<(s?.length||0);a++){const e=/^data:([^;]+);base64,(.+)$/s.exec(s[a]?.dataUrl||"");if(!e)continue;const n=(e[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",l=h.join($.tmpdir(),`chatpanel-codex-img-${r}-${a}.${n}`);await G(l,Buffer.from(e[2],"base64")),t.push(l)}return t}async function xe({argsFor:s,readOnly:r=!1,cwd:t,env:a,prompt:e,outFile:n,emit:l,signal:o}){const c=await J().wrapOwn("codex",s,{cwd:t,stdio:["pipe","pipe","pipe"],env:a,...L},{engine:"codex",cwd:t,readOnly:r});return R(l,c.record),new Promise((m,p)=>{let u;try{u=X(F(c.bin,c.argv,c.opts),c,{kind:"agent"})}catch(f){return p(new Error(`Failed to start codex: ${f.message}`))}const k=H(u,o);let w="",_="",b=!1;const A=f=>{f?.type!=="status"&&(b=!0),l(f)},S={started:new Set,reasoned:new Set,n:0};let v;const y=()=>{clearTimeout(v),v=setTimeout(()=>{u.kill("SIGKILL"),p(new Error(`Codex timed out — no output for ${Math.round(D/1e3)}s.`))},D)};y(),u.stdout.on("data",f=>{y(),w+=f.toString();let g;for(;(g=w.indexOf(`
|
|
2
|
+
`))>=0;){const i=w.slice(0,g).trim();if(w=w.slice(g+1),!!i.startsWith("{"))try{_e(JSON.parse(i),A,S)}catch{}}}),u.stderr.on("data",f=>{y(),_+=f.toString()}),u.on("error",f=>{clearTimeout(v),k(),p(f)}),u.on("close",async f=>{clearTimeout(v),k();let g="";try{g=(await z(n,"utf8")).trim()}catch{}N(n).catch(()=>{}),m({code:f,stderr:_,text:g,streamed:b,said:!!S.saidAny,policyBlocked:!!S.policyBlocked})}),u.stdin.write(e),u.stdin.end()})}async function Je({messages:s,system:r,options:t,images:a},e,{signal:n}={}){const l=await de({messages:s,system:r,options:t,images:a},e,{signal:n}).catch(o=>({handled:!1,reason:o?.message||String(o),thrown:!0}));if(!l.handled&&!n?.aborted){if(l.thrown)throw new Error(l.reason);return we({messages:s,system:r,options:t,images:a},e,{signal:n})}}async function we({messages:s,system:r,options:t,images:a},e,{signal:n}={}){const l=`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=h.join($.tmpdir(),`chatpanel-codex-${l}.txt`),c=await ye(a,l),m=()=>c.forEach(i=>N(i).catch(()=>{})),p=oe(t.workingDir),u=[];te(u,t.extraArgs,re.codex,e);const k=(i,x=!0)=>{const d=["exec","--json","--skip-git-repo-check","-o",o];if(t.permissionMode==="bypassPermissions")d.push("--dangerously-bypass-approvals-and-sandbox");else if(!x)d.push("-s","danger-full-access"),E||d.push("-c","approval_policy=never");else{const C=t.permissionMode==="acceptEdits"?"workspace-write":"read-only";d.push("-s",C),d.push(...q({harness:"codex",roots:W(p),dirs:t.dirs})),E||d.push("-c","approval_policy=never")}T&&d.push("-c",`model_reasoning_effort=${T}`),d.push("-c","model_reasoning_summary=auto"),d.push(...fe(t.mcp)),d.push(...ge(i)),t.model&&d.push("-m",t.model),d.push(...u);for(const C of c)d.push("-i",C);return d.push("-"),d},w=t.useLocalConfig!==!1,_={...process.env,...t.runEnv||{}};if(!w){const i=ue();i&&(_.CODEX_HOME=i)}const b=t.mcp?.serverName||"chatpanel_browser",A=_.CODEX_HOME||process.env.CODEX_HOME||h.join($.homedir(),".codex"),S=me(A),v=(t.mcp?.specs||[]).length>0;let y=[...new Set([...ce("codex",t,[b]),...v?he(A):[]])].filter(i=>S.has(i));const f=ee(s,r),g=()=>xe({argsFor:i=>k(y,i),readOnly:t.permissionMode!=="acceptEdits"&&t.permissionMode!=="bypassPermissions",cwd:p,env:_,prompt:f,outFile:o,emit:e,signal:n});try{let i=await g();if(i.policyBlocked&&(E=!0),!n?.aborted&&i.code!==0&&!i.streamed){const x=ie({agent:"codex",text:i.stderr,protect:[b],already:y});x&&S.has(x.server)&&(le("codex",x.server),e({type:"status",text:`MCP server "${x.server}" failed to load — ${x.short}. Skipping it and retrying.`}),y=[...y,x.server],i=await g())}if(n?.aborted)return;if(i.code!==0)throw new Error(se("Codex",i.code,i.stderr,"",{agentId:"codex"}));i.said||e({type:"delta",text:i.text||"(no output)"}),e({type:"done",text:""})}finally{m()}}function _e(s,r,t={started:new Set,reasoned:new Set,n:0}){const a=s.type||"",e=s.item||{},n=e.type||"",l=a==="item.completed"||e.status==="completed"||e.status==="failed";if(n==="agent_message"&&l){const o=e.id||`msg_${t.n++}`,c=String(e.text||"");c&&!t.said?.has(o)&&((t.said||=new Set).add(o),r({type:"delta",text:`${t.saidAny?`
|
|
3
3
|
|
|
4
|
-
`:""}${c}`}),t.saidAny=!0);return}if(n==="command_execution"||!n&&a.includes("command")){const
|
|
5
|
-
`);t.lastTodo!==
|
|
6
|
-
${
|
|
7
|
-
`}));return}(a==="turn.started"||a==="thread.started")&&
|
|
4
|
+
`:""}${c}`}),t.saidAny=!0);return}if(n==="command_execution"||!n&&a.includes("command")){const o=e.id||`cmd_${t.n++}`;if(t.started.has(o)||(t.started.add(o),r({type:"tool",name:"shell",phase:"start",callId:o,input:{command:e.command||""}})),l){const c=e.exit_code===0||e.exit_code==null;r({type:"tool",name:"shell",phase:"done",callId:o,status:c?"ok":`exit ${e.exit_code}`,result:String(e.aggregated_output||"").slice(0,4e3)})}return}if(n==="file_change"||!n&&a.includes("patch")){const o=e.id||`edit_${t.n++}`,c=Array.isArray(e.changes)?e.changes.map(m=>m.path||m.file).filter(Boolean):[];t.started.has(o)||(t.started.add(o),r({type:"tool",name:"edit",phase:"start",callId:o,input:{files:c}})),l&&r({type:"tool",name:"edit",phase:"done",callId:o,status:"ok"});return}if(n==="web_search"){const o=e.id||`ws_${t.n++}`,c=e.action&&typeof e.action=="object"?e.action:{},m=e.query||c.query||"",p=c.url||"";t.started.has(o)||(t.started.add(o),r({type:"tool",name:"web_search",phase:"start",callId:o,input:{query:m,...p?{url:p}:{}}})),(l||a==="item.completed")&&r({type:"tool",name:"web_search",phase:"done",callId:o,status:"ok",result:p?`Opened ${p}`:m?`Searched the web for ${m}`:"Searched the web"});return}if(n==="mcp_tool_call"){const o=e.id||`mcp_${t.n++}`,c=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(t.started.has(o)||(t.started.add(o),r({type:"tool",name:c,phase:"start",callId:o,input:e.arguments&&typeof e.arguments=="object"?e.arguments:{}})),l){const m=e.status==="failed"||e.error!=null,p=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error,u=e.result==null?"":typeof e.result=="string"?e.result:JSON.stringify(e.result);r({type:"tool",name:c,phase:"done",callId:o,status:m?`error: ${String(p||"failed").slice(0,80)}`:"ok",result:String(m?p||"":u).slice(0,4e3)})}return}if(n==="todo_list"&&Array.isArray(e.items)&&e.items.length){const o=e.items.map(c=>`${c.completed?"☑":"☐"} ${c.text||""}`).join(`
|
|
5
|
+
`);t.lastTodo!==o&&(t.lastTodo=o,r({type:"status",text:`Plan:
|
|
6
|
+
${o}`}));return}if(n==="error"||a==="error"){const o=String(e.message||s.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(n==="reasoning"||!n&&a.includes("reasoning")){const o=e.id||`r_${t.n++}`,c=e.text||e.summary||"";c&&!t.reasoned.has(o)&&(t.reasoned.add(o),r({type:"reasoning",text:`${c}
|
|
7
|
+
`}));return}(a==="turn.started"||a==="thread.started")&&r({type:"status",text:"Codex working"})}export{Xe as available,Je as chat,we as chatCold,ge as codexDisableArgs,fe as codexMcpConfigArgs,me as configuredMcpServers,ue as ensureIsolatedHome,_e as forwardEvent,Le as listModels,he as redundantChatpanelServers,He as resetApprovalPolicy,ye as writeImages};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as l}from"./event.js";const i=Object.freeze({claude:{label:"Claude Code",vendor:"Anthropic",hosts:["api.anthropic.com"],repoint:"limited",how:"ANTHROPIC_BASE_URL (+ ANTHROPIC_AUTH_TOKEN) to an Anthropic-compatible endpoint — this gateway’s /v1/messages qualifies",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud"},codex:{label:"Codex",vendor:"OpenAI",hosts:["api.openai.com","chatgpt.com"],repoint:"limited",how:"OPENAI_BASE_URL, or a model_provider in ~/.codex/config.toml pointing at an OpenAI-compatible endpoint",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud"},antigravity:{label:"Antigravity",vendor:"Google",hosts:["*.googleapis.com"],repoint:"no",how:"",dirs:null,defaultModel:"cloud"},kiro:{label:"Kiro",vendor:"AWS",hosts:["*.amazonaws.com"],repoint:"no",how:"",dirs:null,defaultModel:"cloud"},copilot:{label:"GitHub Copilot",vendor:"GitHub",hosts:["api.githubcopilot.com","*.github.com"],repoint:"no",how:"",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud"},deepseek:{label:"DeepSeek Harness",vendor:"DeepSeek",hosts:["api.deepseek.com"],repoint:"limited",how:"its base URL setting, to an OpenAI-compatible endpoint",dirs:null,defaultModel:"cloud"},opencode:{label:"OpenCode",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — any OpenAI-compatible endpoint, Ollama, LM Studio, or this gateway",dirs:null,defaultModel:"configurable"},pi:{label:"Pi",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — any OpenAI-compatible endpoint, or this gateway",dirs:null,defaultModel:"configurable"},hermes:{label:"Hermes",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — a local model is a first-class choice",dirs:null,defaultModel:"configurable"}}),c=t=>String(t||"").toLowerCase().replace(/[^a-z]/g,""),s={claudecode:"claude",githubcopilot:"copilot",copilotcli:"copilot",deepseekharness:"deepseek",gemini:"antigravity",geminicli:"antigravity"};function d(t){const o=c(t);if(i[o])return{id:o,...i[o]};if(s[o])return{id:s[o],...i[s[o]]};const e=Object.entries(i).find(([r,n])=>o.includes(r)||o.includes(c(n.label)));return e?{id:e[0],...e[1]}:null}function g(t,{repointed:o=null}={}){const e=d(t);return e?o?{egress:"configurable",where:`a coding agent · model at ${o}`,note:`Re-pointed by you; ${e.how||"its own setting"}.`}:e.repoint==="yes"?{egress:"configurable",where:"a coding agent · model of your choosing",note:`Its model is a setting of its own — ${e.how}. Until you set one, whatever it defaults to.`}:e.repoint==="limited"?{egress:"internet",where:`a coding agent · model at ${e.vendor}`,note:`The conversation goes to ${e.vendor} with your own login. It can be re-pointed: ${e.how}.`}:{egress:"internet",where:`a coding agent · model at ${e.vendor}`,note:`The conversation goes to ${e.vendor} with your own login; this agent cannot be pointed elsewhere.`}:{egress:"internet",where:"a coding agent · its own model, elsewhere",note:"No card for this agent — assume its model is a vendor’s until you know otherwise."}}function u(t){if(t==null)return null;if(typeof t=="string")return u({flag:t,repeat:!0});if(typeof t!="object"||Array.isArray(t))throw new l("SHAPE","dirs: must be { flag, repeat } or { flag, separator }");const o=String(t.flag||"").trim();if(!/^--?[A-Za-z][\w-]*$/.test(o))throw new l("SHAPE",`dirs: not a flag: ${JSON.stringify(t.flag)}`);const e=t.separator==null?null:String(t.separator);if(e!=null&&(e.length===0||/\s/.test(e)))throw new l("SHAPE","dirs: separator must be a non-empty run of non-space characters");return e!=null?{flag:o,separator:e}:{flag:o,repeat:!0}}function f({harness:t,roots:o=[],dirs:e}={}){const r=(Array.isArray(o)?o:[]).map(a=>String(a||"").trim()).filter(Boolean);if(!r.length)return[];const n=u(e!==void 0?e:d(t)?.dirs??null);return n?n.separator?[n.flag,r.join(n.separator)]:r.flatMap(a=>[n.flag,a]):[]}function h(t,o){try{return!!u(o!==void 0?o:d(t)?.dirs??null)}catch{return!1}}export{i as HARNESS_CARDS,d as harnessCard,f as harnessDirArgs,g as harnessEgress,h as harnessTakesDirs,u as normalizeDirsSpec};
|
|
1
|
+
import{EventError as l}from"./event.js";const i=Object.freeze({claude:{label:"Claude Code",vendor:"Anthropic",hosts:["api.anthropic.com"],repoint:"limited",how:"ANTHROPIC_BASE_URL (+ ANTHROPIC_AUTH_TOKEN) to an Anthropic-compatible endpoint — this gateway’s /v1/messages qualifies",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud"},codex:{label:"Codex",vendor:"OpenAI",hosts:["api.openai.com","chatgpt.com"],repoint:"limited",how:"OPENAI_BASE_URL, or a model_provider in ~/.codex/config.toml pointing at an OpenAI-compatible endpoint",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",ownSandbox:"computer use (controlling the browser and other apps)"},antigravity:{label:"Antigravity",vendor:"Google",hosts:["*.googleapis.com"],repoint:"no",how:"",dirs:null,defaultModel:"cloud"},kiro:{label:"Kiro",vendor:"AWS",hosts:["*.amazonaws.com"],repoint:"no",how:"",dirs:null,defaultModel:"cloud"},copilot:{label:"GitHub Copilot",vendor:"GitHub",hosts:["api.githubcopilot.com","*.github.com"],repoint:"no",how:"",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud"},deepseek:{label:"DeepSeek Harness",vendor:"DeepSeek",hosts:["api.deepseek.com"],repoint:"limited",how:"its base URL setting, to an OpenAI-compatible endpoint",dirs:null,defaultModel:"cloud"},opencode:{label:"OpenCode",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — any OpenAI-compatible endpoint, Ollama, LM Studio, or this gateway",dirs:null,defaultModel:"configurable"},pi:{label:"Pi",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — any OpenAI-compatible endpoint, or this gateway",dirs:null,defaultModel:"configurable"},hermes:{label:"Hermes",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — a local model is a first-class choice",dirs:null,defaultModel:"configurable"}}),c=t=>String(t||"").toLowerCase().replace(/[^a-z]/g,""),s={claudecode:"claude",githubcopilot:"copilot",copilotcli:"copilot",deepseekharness:"deepseek",gemini:"antigravity",geminicli:"antigravity"};function d(t){const o=c(t);if(i[o])return{id:o,...i[o]};if(s[o])return{id:s[o],...i[s[o]]};const e=Object.entries(i).find(([r,n])=>o.includes(r)||o.includes(c(n.label)));return e?{id:e[0],...e[1]}:null}function g(t,{repointed:o=null}={}){const e=d(t);return e?o?{egress:"configurable",where:`a coding agent · model at ${o}`,note:`Re-pointed by you; ${e.how||"its own setting"}.`}:e.repoint==="yes"?{egress:"configurable",where:"a coding agent · model of your choosing",note:`Its model is a setting of its own — ${e.how}. Until you set one, whatever it defaults to.`}:e.repoint==="limited"?{egress:"internet",where:`a coding agent · model at ${e.vendor}`,note:`The conversation goes to ${e.vendor} with your own login. It can be re-pointed: ${e.how}.`}:{egress:"internet",where:`a coding agent · model at ${e.vendor}`,note:`The conversation goes to ${e.vendor} with your own login; this agent cannot be pointed elsewhere.`}:{egress:"internet",where:"a coding agent · its own model, elsewhere",note:"No card for this agent — assume its model is a vendor’s until you know otherwise."}}function u(t){if(t==null)return null;if(typeof t=="string")return u({flag:t,repeat:!0});if(typeof t!="object"||Array.isArray(t))throw new l("SHAPE","dirs: must be { flag, repeat } or { flag, separator }");const o=String(t.flag||"").trim();if(!/^--?[A-Za-z][\w-]*$/.test(o))throw new l("SHAPE",`dirs: not a flag: ${JSON.stringify(t.flag)}`);const e=t.separator==null?null:String(t.separator);if(e!=null&&(e.length===0||/\s/.test(e)))throw new l("SHAPE","dirs: separator must be a non-empty run of non-space characters");return e!=null?{flag:o,separator:e}:{flag:o,repeat:!0}}function f({harness:t,roots:o=[],dirs:e}={}){const r=(Array.isArray(o)?o:[]).map(a=>String(a||"").trim()).filter(Boolean);if(!r.length)return[];const n=u(e!==void 0?e:d(t)?.dirs??null);return n?n.separator?[n.flag,r.join(n.separator)]:r.flatMap(a=>[n.flag,a]):[]}function h(t,o){try{return!!u(o!==void 0?o:d(t)?.dirs??null)}catch{return!1}}export{i as HARNESS_CARDS,d as harnessCard,f as harnessDirArgs,g as harnessEgress,h as harnessTakesDirs,u as normalizeDirsSpec};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as n}from"./event.js";const a=t=>!!t&&typeof t=="object"&&!Array.isArray(t),e=t=>[...new Set(t)],i=(t,
|
|
1
|
+
import{EventError as n}from"./event.js";const a=t=>!!t&&typeof t=="object"&&!Array.isArray(t),e=t=>[...new Set(t)],i=(t,r)=>{if(!t)throw new n("SHAPE",r)},f=/^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d{1,5})?$/i;function p(t){return e(String(t||"").split(/[\s,;]+/).map(r=>r.trim().toLowerCase()).filter(Boolean))}function h(t){if(t==null)return{hosts:[],write:[]};i(a(t),"grant: must be an object");const r=Array.isArray(t.hosts)?t.hosts:typeof t.hosts=="string"?p(t.hosts):[],s=Array.isArray(t.write)?t.write:typeof t.write=="string"?t.write.split(/[\n,]+/).map(o=>o.trim()).filter(Boolean):[];for(const o of r)i(typeof o=="string"&&o!=="*"&&f.test(o),`grant: not a host pattern: ${JSON.stringify(o)}`);for(const o of s)i(typeof o=="string"&&o.length>0&&o.length<1024&&!o.includes("\0"),`grant: not a path: ${JSON.stringify(o)}`);return{hosts:e(r.map(o=>o.toLowerCase())),write:e(s),...t.outside===!0?{outside:!0}:{}}}function c(...t){const r=t.map(h);return{hosts:e(r.flatMap(s=>s.hosts)),write:e(r.flatMap(s=>s.write))}}export{c as mergeGrants,h as normalizeGrant,p as parseHostList};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as j}from"./event.js";import{normalizeGrant as A}from"./sandbox-grant.js";import{SECRET_DIR_NAMES as C,SECRET_DIR_PAIRS as P}from"./secret-names.js";const x=Object.freeze(["none","process","container","kubernetes"]),R=Object.freeze(["open","allowlist","none","gateway"]),y=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),g=e=>{let t=String(e||"").trim();for(;t.length>1&&(t.endsWith("/")||t.endsWith("\\"));)t=t.slice(0,-1);return t},_=(e,t)=>t&&(e==="~"||e.startsWith("~/")||e.startsWith("~\\"))?t+e.slice(1):e,m=e=>String(e||"").replace(/\\/g,"/"),O=(e,t)=>{const n=m(g(e)),r=m(g(t));return!!n&&!!r&&(n===r||n.startsWith(`${r}/`))},L=y.map(e=>m(g(e)).replace(/^~\//,"").split("/").filter(Boolean));function S(e,t=""){const n=m(g(_(g(e),t)));if(!n)return!1;for(const o of y)if(O(n,o)||t&&O(n,_(o,t)))return!0;const r=n.split("/").filter(Boolean).map(o=>o.toLowerCase());return L.some(o=>{for(let i=0;i+o.length<=r.length;i+=1)if(o.every((c,l)=>c.toLowerCase()===r[i+l]))return!0;return!1})}const $=Object.freeze([...[...C].map(e=>`~/**/${e}`),...P.map(([e,t])=>`~/**/${e}/${t}`),...[".env",".netrc","_netrc",".git-credentials",".pgpass",".my.cnf",".npmrc",".pypirc",".htpasswd",".terraformrc",".vault-token","credentials","credentials.toml","id_rsa","id_dsa","id_ecdsa","id_ed25519","*.pem","*.p12","*.pfx","*.jks","*.keystore","*.kdbx","*.ppk"].map(e=>`~/**/${e}`)]);function F(e,{home:t="",globs:n=[...y,...$]}={}){const r=m(g(_(g(e),t)));if(!r)return null;const o=r.split("/").filter(Boolean),i=m(g(t));for(const c of n){const l=m(g(c));if(l){if(l.startsWith("~/**/")){if(i&&!O(r,i))continue;const a=l.slice(5).split("/").filter(Boolean).map(v);for(let s=0;s+a.length<=o.length;s+=1)if(a.every((f,p)=>f.test(o[s+p])))return c;continue}if(O(r,_(l,t)))return c}}return null}function v(e){return new RegExp(`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")}$`,"i")}const I=".cache/chatpanel/ca-bundle.crt",X=".cache/chatpanel/ca-bundle.pem";function V(e=""){const t=m(g(e));return t?`${t}/${I}`:`~/${I}`}const N=Object.freeze(["~/.npm","~/.cache","~/.local","~/Library/Caches","~/.nvm","~/.volta","~/.asdf","~/.nodenv","~/.bun","~/.deno","~/.pyenv","~/.rye","~/.pdm","~/.cargo","~/.rustup","~/go","~/.goenv","~/.m2","~/.gradle","~/.sdkman","~/.jenv","~/.gem","~/.rbenv","~/.bundle","~/.composer","~/.nuget","~/.dotnet","~/.stack","~/.ghcup","~/.opam","~/.pub-cache","~/.gitconfig","~/.config/git"]),z=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),W=Object.freeze({codex:Object.freeze({hosts:["api.openai.com","chatgpt.com","auth.openai.com","*.openai.com"],write:["~/.codex"]}),claude:Object.freeze({hosts:["api.anthropic.com","*.anthropic.com","claude.ai","statsig.anthropic.com"],write:["~/.claude","~/.claude.json"]}),antigravity:Object.freeze({hosts:["*.googleapis.com","*.google.com","oauth2.googleapis.com"],write:["~/.gemini","~/.antigravity","~/.config/antigravity"]}),custom:Object.freeze({hosts:[],write:[]}),mcp:Object.freeze({hosts:[],write:[]}),extract:Object.freeze({hosts:[],write:[]}),"model-server":Object.freeze({hosts:["huggingface.co","*.huggingface.co","*.hf.co","cdn-lfs.huggingface.co","cas-bridge.xethub.hf.co","dl.chatpanel.net"],write:[]})}),T=Object.freeze(["github.com","*.github.com","*.githubusercontent.com","gitlab.com","bitbucket.org","registry.npmjs.org","pypi.org","files.pythonhosted.org","crates.io","static.crates.io","proxy.golang.org","sum.golang.org","huggingface.co","*.huggingface.co"]),h=e=>!!e&&typeof e=="object"&&!Array.isArray(e),b=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0),d=(e,t)=>{if(!e)throw new j("SHAPE",t)},u=e=>[...new Set(e)];function D(e){d(h(e),"kit: must be an object"),d(typeof e.id=="string"&&e.id.length>0,"kit: id required"),d(h(e.network)&&R.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${R.join(", ")}`),d(b(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),d(b(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),d(h(e.filesystem),`kit ${e.id}: filesystem required`);for(const t of["allowWrite","denyWrite","allowRead","denyRead"])d(b(e.filesystem[t]||[]),`kit ${e.id}: filesystem.${t} must be string[]`);return d(b(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),e.image!=null&&d(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&d(Array.isArray(e.credentials)&&e.credentials.every(t=>h(t)&&typeof t.name=="string"&&typeof t.forHost=="string"),`kit ${e.id}: credentials must be [{ name, forHost }]`),{id:e.id,kind:e.kind||"process",image:e.image||null,network:{mode:e.network.mode,allowedDomains:u(e.network.allowedDomains||[]),deniedDomains:u(e.network.deniedDomains||[])},filesystem:{allowWrite:u(e.filesystem.allowWrite),denyWrite:u(e.filesystem.denyWrite||[]),allowRead:u(e.filesystem.allowRead||[]),denyRead:u(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:h(e.limits)?{...e.limits}:{}}}import{normalizeGrant as ce,mergeGrants as le,parseHostList as fe}from"./sandbox-grant.js";function Q({engine:e="custom",cwd:t,mode:n="open",extraHosts:r=[],extraWrite:o=[],extraDenyRead:i=[],grant:c=null,home:l="",reads:a="enumerated"}={}){const s=W[e]||W.custom;d(typeof t=="string"&&t.length>0,"kit: cwd required");const f=A(c);return D({id:`${e}:${n}`,kind:"process",network:{mode:n,allowedDomains:n==="open"?["*"]:n==="none"?[]:u([...s.hosts,...T,...r,...f.hosts]),deniedDomains:[]},filesystem:{allowWrite:u([t,...z,...s.write,...[...o,...f.write].filter(p=>!S(p,l))]),denyWrite:[],allowRead:a==="inverted"?u([t,...N,...s.write,...H({grant:f,extraWrite:o,cwd:t,home:l})]):[t],denyRead:u([...a==="inverted"?["~",...l?[l]:[]]:[],...y,...$,...i])}})}function H({grant:e=null,extraWrite:t=[],cwd:n="",home:r=""}={}){const o=s=>r&&(s==="~"||s.startsWith("~/")||s.startsWith("~\\"))?r+s.slice(1):s,i=s=>{let f=String(s||"").trim();for(;f.length>1&&(f.endsWith("/")||f.endsWith("\\"));)f=f.slice(0,-1);return f},c=(s,f)=>s===f||s.startsWith(`${f}/`)||s.startsWith(`${f}\\`),l=i(o(n)),a=[];for(const s of[...A(e).write,...Array.isArray(t)?t:[]]){const f=i(o(i(s)));if(f&&!S(f,r)&&!(l&&c(f,l))&&!a.some(p=>c(f,p))){for(let p=a.length-1;p>=0;p--)c(a[p],f)&&a.splice(p,1);a.push(f)}}return a}function Z(e,{loopback:t=[],home:n="",platform:r="darwin"}={}){const o=D(e),i=l=>n&&l.startsWith("~")?n+l.slice(1):l,c=o.network.mode==="none"?[]:t.map(l=>`127.0.0.1:${l}`);return{network:{allowedDomains:u([...o.network.allowedDomains,...c]),deniedDomains:o.network.deniedDomains,allowLocalBinding:r==="darwin"&&c.length>0},filesystem:{denyRead:o.filesystem.denyRead.map(i),allowRead:o.filesystem.allowRead.map(i),allowWrite:o.filesystem.allowWrite.map(i),denyWrite:o.filesystem.denyWrite.map(i)}}}function J({layer:e="none",runtime:t=null,kitId:n=null,mode:r=null,reason:o=null,hosts:i=null}={}){return d(x.includes(e),`sandbox record: layer must be one of ${x.join(", ")}`),{layer:e,runtime:t,kit:n,mode:r,...e==="none"&&o?{reason:o}:{},...Array.isArray(i)&&i.length?{hosts:u(i)}:{}}}function k(e,{platform:t="darwin"}={}){const n=String(e);if(t==="win32"){d(!/[\r\n]/.test(n),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=n;if(n===""||/[ \t\v"]/.test(n)){r='"';for(let o=0;o<n.length;o++){let i=0;for(;o<n.length&&n[o]==="\\";)i++,o++;if(o===n.length){r+="\\".repeat(i*2);break}n[o]==='"'?r+="\\".repeat(i*2+1)+'"':r+="\\".repeat(i)+n[o]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return n===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}const K=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function ee(e={},{platform:t="darwin",caBundle:n=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(n)for(const o of K)e[o]||(r[o]=n);if(t==="linux")for(const o of["no_proxy","NO_PROXY"])typeof e[o]=="string"&&(r[o]=e[o].split(",").map(i=>i.trim()).filter(i=>i&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(i)).join(","));return r}function te(e,t=[],{platform:n="darwin"}={}){return[e,...t].map(r=>k(r,{platform:n})).join(" ")}const ne=/[\\/]+/,w=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),U=e=>/^[a-z]:$/i.test(w(e))||w(e)==="";function E(e,t){const n=w(e),r=w(t);return!!r&&n!==r&&n.startsWith(r+"\\")}function Y(e){const t=String(e||"").replace(/\//g,"\\").split("\\");if(t.length<2)return"";const n=t.findIndex(r=>r.toLowerCase()==="node_modules");return(n>0?t.slice(0,n):t.slice(0,-1)).join("\\")}function oe({kit:e,files:t=[],home:n}){d(typeof n=="string"&&n.length>0,"windows grants: home required");const r=a=>(a.startsWith("~")?n+a.slice(1):a).replace(/\//g,"\\"),o=[];for(const a of e?.filesystem?.allowWrite||[]){const s=r(a);!/^[a-z]:\\/i.test(s)&&!s.startsWith("\\\\")||(d(!U(s)&&w(s)!==w(n),`windows grants: a write on ${s} would hand the sandbox account the whole profile`),E(s,n)&&o.push(s))}const i=(a,s)=>s.some(f=>w(a)===w(f)||E(a,f)),c=[];for(const a of t){const s=Y(a);s&&E(s,n)&&c.push(s)}for(const a of e?.filesystem?.allowRead||[]){const s=r(a);E(s,n)&&c.push(s)}const l=u(c).filter(a=>!i(a,o));return{read:l.filter(a=>!l.some(s=>s!==a&&E(a,s))),write:u(o)}}const B=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","CODEX_HOME","GEMINI_API_KEY","GOOGLE_API_KEY","DEEPSEEK_API_KEY","DSH_HOME","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"]);function re({engine:e="custom",home:t,env:n={},base:r={},carry:o=B}={}){d(typeof t=="string"&&t.length>0,"windows env: home required");const i=t.replace(/\//g,"\\"),c=/^[a-z]:/i.test(i)?i.slice(0,2):"",l={USERPROFILE:i,...c?{HOMEDRIVE:c,HOMEPATH:i.slice(2)}:{}};for(const[a,s]of Object.entries(n))typeof s=="string"&&(r[a]!==s||o.includes(a))&&(l[a]=s);return e==="codex"&&!l.CODEX_HOME&&(l.CODEX_HOME=i+"\\.codex"),l}function se(e,t){d(Array.isArray(e),"srt-win argv: must be an array");const n=e.indexOf("exec"),r=n>=0?e.indexOf("--",n+1):-1;d(n>=0&&r>n,"srt-win argv: expected `exec … -- <shell> <command>`");const o=new Set;for(let c=n+1;c<r;c++)e[c]==="--env"&&typeof e[c+1]=="string"&&o.add(e[c+1].split("=")[0].toUpperCase());const i=[];for(const[c,l]of Object.entries(t||{}))d(/^[A-Za-z_][A-Za-z0-9_]*$/.test(c),`srt-win env: bad key ${c}`),d(!/[\r\n]/.test(l),`srt-win env: ${c} holds a newline`),o.has(c.toUpperCase())||i.push("--env",`${c}=${l}`);return[...e.slice(0,r),...i,...e.slice(r)]}export{I as CA_BUNDLE_RELPATH,X as CA_BUNDLE_RELPATH_LEGACY,z as COMMON_WRITE,T as DEVELOPER_HOSTS,W as ENGINE_KITS,R as NETWORK_MODES,x as SANDBOX_LAYERS,y as SECRET_PATHS,$ as SECRET_READ_GLOBS,N as TOOLCHAIN_READ,B as WINDOWS_CARRY_KEYS,V as caBundlePath,S as isSecretWritePath,Q as kitFor,le as mergeGrants,ce as normalizeGrant,fe as parseHostList,F as readDenialFor,ee as sandboxEnvOverlay,J as sandboxRecord,te as shellJoin,k as shellQuote,Z as toSrtSettings,E as underWindowsHome,D as validateKit,oe as windowsGrantsFor,Y as windowsInstallRoot,re as windowsSandboxEnv,se as withSrtWinEnv,H as writableRoots};
|
|
1
|
+
import{EventError as L}from"./event.js";import{normalizeGrant as x}from"./sandbox-grant.js";import{SECRET_DIR_NAMES as P,SECRET_DIR_PAIRS as N}from"./secret-names.js";const R=Object.freeze(["none","process","container","kubernetes"]),S=Object.freeze(["open","allowlist","none","gateway"]),E=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),g=e=>{let t=String(e||"").trim();for(;t.length>1&&(t.endsWith("/")||t.endsWith("\\"));)t=t.slice(0,-1);return t},_=(e,t)=>t&&(e==="~"||e.startsWith("~/")||e.startsWith("~\\"))?t+e.slice(1):e,m=e=>String(e||"").replace(/\\/g,"/"),b=(e,t)=>{const n=m(g(e)),r=m(g(t));return!!n&&!!r&&(n===r||n.startsWith(`${r}/`))},v=E.map(e=>m(g(e)).replace(/^~\//,"").split("/").filter(Boolean));function I(e,t=""){const n=m(g(_(g(e),t)));if(!n)return!1;for(const o of E)if(b(n,o)||t&&b(n,_(o,t)))return!0;const r=n.split("/").filter(Boolean).map(o=>o.toLowerCase());return v.some(o=>{for(let s=0;s+o.length<=r.length;s+=1)if(o.every((c,l)=>c.toLowerCase()===r[s+l]))return!0;return!1})}const $=Object.freeze([...[...P].map(e=>`~/**/${e}`),...N.map(([e,t])=>`~/**/${e}/${t}`),...[".env",".netrc","_netrc",".git-credentials",".pgpass",".my.cnf",".npmrc",".pypirc",".htpasswd",".terraformrc",".vault-token","credentials","credentials.toml","id_rsa","id_dsa","id_ecdsa","id_ed25519","*.pem","*.p12","*.pfx","*.jks","*.keystore","*.kdbx","*.ppk"].map(e=>`~/**/${e}`)]);function Z(e,{home:t="",globs:n=[...E,...$]}={}){const r=m(g(_(g(e),t)));if(!r)return null;const o=r.split("/").filter(Boolean),s=m(g(t));for(const c of n){const l=m(g(c));if(l){if(l.startsWith("~/**/")){if(s&&!b(r,s))continue;const a=l.slice(5).split("/").filter(Boolean).map(z);for(let i=0;i+a.length<=o.length;i+=1)if(a.every((f,p)=>f.test(o[i+p])))return c;continue}if(b(r,_(l,t)))return c}}return null}function z(e){return new RegExp(`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")}$`,"i")}const W=".cache/chatpanel/ca-bundle.crt",J=".cache/chatpanel/ca-bundle.pem";function ee(e=""){const t=m(g(e));return t?`${t}/${W}`:`~/${W}`}const H=Object.freeze(["~/.npm","~/.cache","~/.local","~/Library/Caches","~/.nvm","~/.volta","~/.asdf","~/.nodenv","~/.bun","~/.deno","~/.pyenv","~/.rye","~/.pdm","~/.cargo","~/.rustup","~/go","~/.goenv","~/.m2","~/.gradle","~/.sdkman","~/.jenv","~/.gem","~/.rbenv","~/.bundle","~/.composer","~/.nuget","~/.dotnet","~/.stack","~/.ghcup","~/.opam","~/.pub-cache","~/.gitconfig","~/.config/git"]),D=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),C=Object.freeze({codex:Object.freeze({hosts:["api.openai.com","chatgpt.com","auth.openai.com","*.openai.com"],write:["~/.codex"]}),claude:Object.freeze({hosts:["api.anthropic.com","*.anthropic.com","claude.ai","statsig.anthropic.com"],write:["~/.claude","~/.claude.json"],keychain:!0}),antigravity:Object.freeze({hosts:["*.googleapis.com","*.google.com","oauth2.googleapis.com"],write:["~/.gemini","~/.antigravity","~/.config/antigravity"]}),custom:Object.freeze({hosts:[],write:[]}),mcp:Object.freeze({hosts:[],write:[]}),extract:Object.freeze({hosts:[],write:[]}),"model-server":Object.freeze({hosts:["huggingface.co","*.huggingface.co","*.hf.co","cdn-lfs.huggingface.co","cas-bridge.xethub.hf.co","dl.chatpanel.net"],write:[]})}),T="~/Library/Keychains",K=/(^|\/)Keychains\/?$/,k=Object.freeze(["github.com","*.github.com","*.githubusercontent.com","gitlab.com","bitbucket.org","registry.npmjs.org","pypi.org","files.pythonhosted.org","crates.io","static.crates.io","proxy.golang.org","sum.golang.org","huggingface.co","*.huggingface.co"]),h=e=>!!e&&typeof e=="object"&&!Array.isArray(e),O=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0),d=(e,t)=>{if(!e)throw new L("SHAPE",t)},u=e=>[...new Set(e)];function j(e){d(h(e),"kit: must be an object"),d(typeof e.id=="string"&&e.id.length>0,"kit: id required"),d(h(e.network)&&S.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${S.join(", ")}`),d(O(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),d(O(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),d(h(e.filesystem),`kit ${e.id}: filesystem required`);for(const t of["allowWrite","denyWrite","allowRead","denyRead"])d(O(e.filesystem[t]||[]),`kit ${e.id}: filesystem.${t} must be string[]`);return d(O(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),e.image!=null&&d(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&d(Array.isArray(e.credentials)&&e.credentials.every(t=>h(t)&&typeof t.name=="string"&&typeof t.forHost=="string"),`kit ${e.id}: credentials must be [{ name, forHost }]`),{id:e.id,kind:e.kind||"process",image:e.image||null,network:{mode:e.network.mode,allowedDomains:u(e.network.allowedDomains||[]),deniedDomains:u(e.network.deniedDomains||[])},filesystem:{allowWrite:u(e.filesystem.allowWrite),denyWrite:u(e.filesystem.denyWrite||[]),allowRead:u(e.filesystem.allowRead||[]),denyRead:u(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:h(e.limits)?{...e.limits}:{}}}import{normalizeGrant as ue,mergeGrants as pe,parseHostList as ge}from"./sandbox-grant.js";function te({engine:e="custom",cwd:t,mode:n="open",extraHosts:r=[],extraWrite:o=[],extraDenyRead:s=[],grant:c=null,home:l="",reads:a="enumerated",readOnly:i=!1}={}){const f=C[e]||C.custom;d(typeof t=="string"&&t.length>0,"kit: cwd required");const p=x(c);return j({id:`${e}:${n}`,kind:"process",network:{mode:n,allowedDomains:n==="open"?["*"]:n==="none"?[]:u([...f.hosts,...k,...r,...p.hosts]),deniedDomains:[]},filesystem:{allowWrite:u(i?[...D,...f.write]:[t,...D,...f.write,...[...o,...p.write].filter(A=>!I(A,l))]),denyWrite:[],allowRead:a==="inverted"?u([t,...H,...f.write,...f.keychain?[T]:[],...U({grant:p,extraWrite:o,cwd:t,home:l})]):[t],denyRead:u([...a==="inverted"?["~",...l?[l]:[]]:[],...[...E,...$].filter(A=>!(f.keychain&&K.test(A))),...s])}})}function Y(e){if(!/[*?[{]/.test(e))return e;const t=e.split(/[\\/]/),n=t.findIndex(s=>/[*?[{]/.test(s)),r=e.includes("\\")&&!e.includes("/")?"\\":"/",o=t.slice(0,n).join(r);return o&&o!=="~"?o:""}function U({grant:e=null,extraWrite:t=[],cwd:n="",home:r=""}={}){const o=i=>r&&(i==="~"||i.startsWith("~/")||i.startsWith("~\\"))?r+i.slice(1):i,s=i=>{let f=String(i||"").trim();for(;f.length>1&&(f.endsWith("/")||f.endsWith("\\"));)f=f.slice(0,-1);return f},c=(i,f)=>i===f||i.startsWith(`${f}/`)||i.startsWith(`${f}\\`),l=s(o(n)),a=[];for(const i of[...x(e).write,...Array.isArray(t)?t:[]]){const f=Y(s(o(s(i))));if(f&&!I(f,r)&&!(l&&c(f,l))&&!a.some(p=>c(f,p))){for(let p=a.length-1;p>=0;p--)c(a[p],f)&&a.splice(p,1);a.push(f)}}return a}function ne(e,{loopback:t=[],home:n="",platform:r="darwin"}={}){const o=j(e),s=l=>n&&l.startsWith("~")?n+l.slice(1):l,c=o.network.mode==="none"?[]:t.map(l=>`127.0.0.1:${l}`);return{network:{allowedDomains:u([...o.network.allowedDomains,...c]),deniedDomains:o.network.deniedDomains,allowLocalBinding:r==="darwin"&&c.length>0},filesystem:{denyRead:o.filesystem.denyRead.map(s),allowRead:o.filesystem.allowRead.map(s),allowWrite:o.filesystem.allowWrite.map(s),denyWrite:o.filesystem.denyWrite.map(s)}}}function oe({layer:e="none",runtime:t=null,kitId:n=null,mode:r=null,reason:o=null,hosts:s=null}={}){return d(R.includes(e),`sandbox record: layer must be one of ${R.join(", ")}`),{layer:e,runtime:t,kit:n,mode:r,...e==="none"&&o?{reason:o}:{},...Array.isArray(s)&&s.length?{hosts:u(s)}:{}}}function B(e,{platform:t="darwin"}={}){const n=String(e);if(t==="win32"){d(!/[\r\n]/.test(n),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=n;if(n===""||/[ \t\v"]/.test(n)){r='"';for(let o=0;o<n.length;o++){let s=0;for(;o<n.length&&n[o]==="\\";)s++,o++;if(o===n.length){r+="\\".repeat(s*2);break}n[o]==='"'?r+="\\".repeat(s*2+1)+'"':r+="\\".repeat(s)+n[o]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return n===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}const G=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function re(e={},{platform:t="darwin",caBundle:n=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(n)for(const o of G)e[o]||(r[o]=n);if(t==="linux")for(const o of["no_proxy","NO_PROXY"])typeof e[o]=="string"&&(r[o]=e[o].split(",").map(s=>s.trim()).filter(s=>s&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(s)).join(","));return r}function se(e,t=[],{platform:n="darwin"}={}){return[e,...t].map(r=>B(r,{platform:n})).join(" ")}const ie=/[\\/]+/,w=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),M=e=>/^[a-z]:$/i.test(w(e))||w(e)==="";function y(e,t){const n=w(e),r=w(t);return!!r&&n!==r&&n.startsWith(r+"\\")}function q(e){const t=String(e||"").replace(/\//g,"\\").split("\\");if(t.length<2)return"";const n=t.findIndex(r=>r.toLowerCase()==="node_modules");return(n>0?t.slice(0,n):t.slice(0,-1)).join("\\")}function ae({kit:e,files:t=[],home:n}){d(typeof n=="string"&&n.length>0,"windows grants: home required");const r=a=>(a.startsWith("~")?n+a.slice(1):a).replace(/\//g,"\\"),o=[];for(const a of e?.filesystem?.allowWrite||[]){const i=r(a);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(d(!M(i)&&w(i)!==w(n),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),y(i,n)&&o.push(i))}const s=(a,i)=>i.some(f=>w(a)===w(f)||y(a,f)),c=[];for(const a of t){const i=q(a);i&&y(i,n)&&c.push(i)}for(const a of e?.filesystem?.allowRead||[]){const i=r(a);y(i,n)&&c.push(i)}const l=u(c).filter(a=>!s(a,o));return{read:l.filter(a=>!l.some(i=>i!==a&&y(a,i))),write:u(o)}}const F=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","CODEX_HOME","GEMINI_API_KEY","GOOGLE_API_KEY","DEEPSEEK_API_KEY","DSH_HOME","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"]);function ce({engine:e="custom",home:t,env:n={},base:r={},carry:o=F}={}){d(typeof t=="string"&&t.length>0,"windows env: home required");const s=t.replace(/\//g,"\\"),c=/^[a-z]:/i.test(s)?s.slice(0,2):"",l={USERPROFILE:s,...c?{HOMEDRIVE:c,HOMEPATH:s.slice(2)}:{}};for(const[a,i]of Object.entries(n))typeof i=="string"&&(r[a]!==i||o.includes(a))&&(l[a]=i);return e==="codex"&&!l.CODEX_HOME&&(l.CODEX_HOME=s+"\\.codex"),l}function le(e,t){d(Array.isArray(e),"srt-win argv: must be an array");const n=e.indexOf("exec"),r=n>=0?e.indexOf("--",n+1):-1;d(n>=0&&r>n,"srt-win argv: expected `exec … -- <shell> <command>`");const o=new Set;for(let c=n+1;c<r;c++)e[c]==="--env"&&typeof e[c+1]=="string"&&o.add(e[c+1].split("=")[0].toUpperCase());const s=[];for(const[c,l]of Object.entries(t||{}))d(/^[A-Za-z_][A-Za-z0-9_]*$/.test(c),`srt-win env: bad key ${c}`),d(!/[\r\n]/.test(l),`srt-win env: ${c} holds a newline`),o.has(c.toUpperCase())||s.push("--env",`${c}=${l}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{W as CA_BUNDLE_RELPATH,J as CA_BUNDLE_RELPATH_LEGACY,D as COMMON_WRITE,k as DEVELOPER_HOSTS,C as ENGINE_KITS,S as NETWORK_MODES,R as SANDBOX_LAYERS,E as SECRET_PATHS,$ as SECRET_READ_GLOBS,H as TOOLCHAIN_READ,F as WINDOWS_CARRY_KEYS,ee as caBundlePath,I as isSecretWritePath,te as kitFor,pe as mergeGrants,ue as normalizeGrant,ge as parseHostList,Z as readDenialFor,re as sandboxEnvOverlay,oe as sandboxRecord,se as shellJoin,B as shellQuote,ne as toSrtSettings,y as underWindowsHome,j as validateKit,ae as windowsGrantsFor,q as windowsInstallRoot,ce as windowsSandboxEnv,le as withSrtWinEnv,U as writableRoots};
|
package/src/mcp-sessions.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as f}from"node:crypto";import{relayTimeoutFor as y}from"./relay-timeout.js";import{stripHidden as m}from"./sanitize.js";import{PERMISSION_EVENT as h,PERMISSION_TIMEOUT_MS as x,permissionRequestFromClaude as g,permissionAnswer as d,permissionAllowed as w,permissionLine as S}from"./events/agent-permission.js";const
|
|
1
|
+
import{randomUUID as f}from"node:crypto";import{relayTimeoutFor as y}from"./relay-timeout.js";import{stripHidden as m}from"./sanitize.js";import{PERMISSION_EVENT as h,PERMISSION_TIMEOUT_MS as x,permissionRequestFromClaude as g,permissionAnswer as d,permissionAllowed as w,permissionLine as S}from"./events/agent-permission.js";const a=new Map;let s=null;const T=()=>{throw new Error("no chat is attached to this tool session")};function C(e,n){const t=f(),r={id:t,emit:e,specs:n,pending:new Map,nextId:0};return a.set(t,r),s=t,r}function _(e){return a.get(e)||null}function b(e,n,t){e.emit=n,t&&(e.specs=t),s=e.id}function v(e){for(const n of e.pending.values())n.reject(new Error("chat ended"));e.pending.clear(),e.emit=T}function N(e){const n=a.get(e);if(n){for(const t of n.pending.values())t.reject(new Error("chat ended"));if(a.delete(e),s===e){const t=[...a.keys()];s=t.length?t[t.length-1]:null}}}function q(){return s&&a.get(s)||null}function u(e,n,t,r){return new Promise((i,o)=>{const c=`t${++e.nextId}`,l=setTimeout(()=>{e.pending.delete(c),r(i,o)},t);e.pending.set(c,{resolve:p=>{clearTimeout(l),i(p)},reject:p=>{clearTimeout(l),o(p)}});try{e.emit({...n,session:e.id,id:c})}catch(p){e.pending.delete(c),clearTimeout(l),o(p)}})}async function A(e,n,t){const r=await u(e,{type:"tool_request",name:n,input:t},y(e.specs,n),(i,o)=>o(new Error("tool call timed out")));return E(r)}async function O(e,n,{request:t=null}={}){const r=t||g(n);let i;try{const o=await u(e,{type:h,...r},x,c=>c(d("deny","Nobody answered the permission prompt in ChatPanel in time.")));i=w(o)?{behavior:"allow",scope:o.scope==="chat"?"chat":"once"}:d("deny",o?.message||"")}catch(o){i=d("deny",`The permission prompt could not reach ChatPanel (${o?.message||o}).`)}try{e.emit({type:"status",text:S(r,i)})}catch{}return i}function E(e){if(e==null)return{content:[{type:"text",text:"ok"}]};if(typeof e=="string")return{content:[{type:"text",text:m(e)}]};const n=[];if(e.text&&n.push({type:"text",text:m(String(e.text))}),typeof e.image=="string"){const t=/^data:([^;]+);base64,(.+)$/s.exec(e.image);t&&n.push({type:"image",data:t[2],mimeType:t[1]})}return n.length||n.push({type:"text",text:"ok"}),{content:n}}export{q as activeSession,C as createSession,N as deleteSession,_ as getSession,b as rebindSession,O as relayPermission,A as relayToolCall,v as releaseSession,E as toMcpContent};
|
package/src/sandbox.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as
|
|
1
|
+
import{spawn as oe}from"node:child_process";import"node:fs";import{randomBytes as ae}from"node:crypto";import{AsyncLocalStorage as ie}from"node:async_hooks";import{fileURLToPath as ue}from"node:url";import N from"node:os";import ce from"node:path";import{ensureCaBundle as le}from"./ca-bundle.js";import{kitFor as de,sandboxRecord as pe,normalizeGrant as P,writableRoots as fe,NETWORK_MODES as xe}from"./events/sandbox-policy.js";import{createSandboxRuntime as me,sandboxRuntimeIds as he}from"./sandbox-runtime.js";import"./sandbox-srt.js";const V=new ie,we=new Set(["codex","claude","antigravity","custom"]);function Ke(e,t){let n;try{n=P(e)}catch{n=null}return V.run(n,t)}function Ve(e){const t=e&&typeof e=="object"?e:{};if(!t.reach||t.reach==="any"||!t.sandbox||typeof t.sandbox!="object"||!("outside"in t.sandbox))return t;const{outside:n,...s}=t.sandbox;return{...t,sandbox:s}}function Y(){return V.getStore()||null}function Ye(e,{config:t=te(),grant:n=Y(),home:s=N.homedir()}={}){try{return fe({grant:n,extraWrite:t.extraWrite,cwd:e,home:s})}catch{return[]}}const Se=/deny network-outbound\s+(\S+?):(\d+)\s*(?:\((.*)\))?/;function z(e){const t=Se.exec(String(e||""));return t?{host:t[1].toLowerCase(),port:Number(t[2])||0,reason:t[3]||""}:null}const g=new Map,R=[],O=new Map,be=new Set,Ae=50;function J({commandId:e,host:t,port:n=0,reason:s="",at:a=Date.now()}){if(!e||!t)return;let o=g.get(e);for(o||(o=new Map,g.set(e,o)),o.set(t,{at:a,reason:s,port:n}),R.push({id:e,engine:O.get(e)||String(e).split(":")[0],host:t,at:a});R.length>Ae;)R.shift()}function ye(e){const t=g.get(e);return t?[...t.entries()].sort((n,s)=>s[1].at-n[1].at).map(([n])=>n):[]}function _e(e=20){return R.slice(-e).reverse()}function ze(){g.clear(),R.length=0,O.clear(),be.clear()}const q=new Map;function Q(e){const t=ae(16).toString("hex");return q.set(t,e),t}function Je(e={}){const t=q.get(String(e?.token||""));return!t||t!==e.commandId?!1:(J({commandId:t,host:String(e.host||"").toLowerCase().slice(0,253),port:Number(e.port)||0,reason:String(e.reason||"").slice(0,200)}),!0)}let Ne=0;const Re=e=>`${e}:${(++Ne).toString(36)}${Date.now().toString(36).slice(-4)}`,L=new Map;function Te(e,t,{kind:n="agent",label:s=""}={}){if(!e||!t)return e;try{e.sandbox=t.record}catch{}if(typeof e.on!="function")return e;const a=t.commandId||"";L.set(e,{id:a,kind:n,engine:O.get(a)||String(a).split(":")[0]||"custom",command:t.label||"",label:s,pid:e.pid??null,since:Date.now(),sandbox:t.record});const o=()=>L.delete(e);return e.once("exit",o),e.once("error",o),e}function qe(){return[...L.values()].map(e=>({...e,refused:ye(e.id)}))}function Qe(){L.clear()}function Z(e){if(e)return"";try{return ue(new URL("./sandbox-host.js",import.meta.url))}catch{return""}}const ee="open",Ze="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)",Ee=()=>[Number(process.env.CHATPANEL_GATEWAY_PORT)||4320,Number(process.env.CHATPANEL_BRIDGE_PORT)||Number(process.env.PORT)||4319],W=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean);function te(e=process.env){const t=String(e.CHATPANEL_SANDBOX||ee).toLowerCase(),n=t!=="off"&&t!=="0"&&t!=="false",s=xe.includes(t)?t:ee;return{enabled:n,mode:s,extraHosts:W(e.CHATPANEL_SANDBOX_ALLOW_HOSTS),extraWrite:W(e.CHATPANEL_SANDBOX_ALLOW_WRITE),extraDenyRead:W(e.CHATPANEL_SANDBOX_DENY_READ),windows:e.CHATPANEL_SANDBOX_WINDOWS==="1",reads:e.CHATPANEL_SANDBOX_READS==="inverted"?"inverted":"enumerated"}}function ge({config:e=te(),loadSrt:t=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:n=void 0,cliEntry:s=void 0,onRefusal:a=l=>J(l),reportUrl:o=process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT?`http://127.0.0.1:${process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT}/sandbox/refused`:"http://127.0.0.1:4319/sandbox/refused",hostEntry:p=null,compiled:u=!1,platform:i=process.platform,home:x=N.homedir(),loopback:$=Ee(),selfFiles:B=[process.execPath,process.argv[1]||""],onExit:k=l=>process.on("exit",l),runtimeId:T=process.env.CHATPANEL_SANDBOX_RUNTIME||"srt",makeRuntime:M=null,log:m=()=>{}}={}){let l=null,E=null,d={ok:!1,runtime:null,reason:null,ownSessions:!1};function b(){if(l||E)return l;try{l=M?M({config:e,platform:i,home:x,loopback:$,compiled:u,selfFiles:B,onExit:k,hostEntry:p,reportUrl:o,mintReportToken:Q,onRefusal:a,parseRefusal:z,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:Z,log:m}):me(T,{config:e,platform:i,home:x,loopback:$,compiled:u,selfFiles:B,onExit:k,hostEntry:p,reportUrl:o,mintReportToken:Q,onRefusal:a,parseRefusal:z,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:Z,log:m})}catch(r){E=r?.message||String(r),m(`sandbox: ${E}`)}return l}async function X(){if(!e.enabled)return d={ok:!1,runtime:null,reason:"sandboxing is off (CHATPANEL_SANDBOX=off)",ownSessions:!1},d;const r=b();if(!r)return d={ok:!1,runtime:null,reason:E,ownSessions:!1},d;try{d={...d,...await r.detect()}}catch(c){d={ok:!1,runtime:null,reason:`the ${r.id} sandbox could not be started: ${c.message}`,ownSessions:!1}}return d}return{config:e,async status(){const r=await X(),c=b();return{enabled:e.enabled,mode:e.mode,runtime:r.runtime,platform:i,layer:c?.id||T,layers:he(),...r.reason?{reason:r.reason}:{},extras:{hosts:e.extraHosts,write:e.extraWrite,denyRead:e.extraDenyRead},ownSessions:!!r.ownSessions,refused:_e(),...r.provisioned!==void 0?{provisioned:r.provisioned}:{},...r.install?{install:r.install}:{}}},close(){try{b()?.close()}catch(r){m(`sandbox: close failed: ${r.message}`)}},async wrap(r,c,A,{engine:f="custom",cwd:y=null,commandId:h=null,grant:F=Y(),readOnly:re=!1}={}){const G=await X();h=h||Re(f),O.set(h,f);const I=y||A?.cwd||process.cwd(),U=ce.basename(String(r||"")),_=S=>({bin:r,argv:c,opts:A,record:pe({layer:"none",reason:S}),commandId:h,label:U});let j=!1;try{j=P(F).outside===!0}catch{}if(j&&we.has(f))return _("you allowed this agent to run outside the ChatPanel sandbox (its own sandbox still applies)");if(!G.ok)return _(G.reason);const se=await le({home:N.homedir(),log:m}).catch(()=>"");let K,D;try{D=P(F),K=de({engine:f,cwd:I,mode:e.mode,extraHosts:e.extraHosts,extraWrite:[N.tmpdir(),...e.extraWrite],extraDenyRead:e.extraDenyRead,grant:D,home:N.homedir(),reads:e.reads,readOnly:re})}catch(S){return _(`kit: ${S.message}`)}let w;try{w=await b().wrap({kit:K,grant:D,bin:r,argv:c,opts:A,engine:f,workdir:I,commandId:h,caBundle:se})}catch(S){return m(`sandbox: could not wrap ${r}: ${S.message}`),_(`the ${T} sandbox failed to wrap the command: ${S.message}`)}return!w||w.passReason?_(w?.passReason||`the ${T} sandbox returned nothing`):{...w,commandId:w.commandId||h,label:U}},async wrapOwn(r,c,A,f={}){const y=await this.wrap(r,c(!1),A,f);return y.record.layer==="none"?{...y,argv:c(!0),inner:!0}:{...y,inner:!1}},violations(r){try{return b()?.violations(r)||[]}catch{return[]}}}}let C=null;function ne(){if(!C){const{isCompiledBinary:e}=Oe();C=ge({compiled:e(),log:t=>console.error(`[bridge] ${t}`)})}return C}function et(e){C=e}let v=null;function Oe(){return v||(v={isCompiledBinary:()=>{const e=(process.execPath||"").split(/[\\/]/).pop().toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}}),v}const H=new Set;function tt(e,t){if(!t||t.layer!=="none"||typeof e!="function")return;const n=t.reason||"unknown";H.has(n)||(H.add(n),e({type:"status",text:`Running outside a sandbox — ${n}`}))}function nt(){H.clear()}const Le=/sandbox_apply: Operation not permitted/;function rt(e,t="This agent"){return Le.test(String(e||""))?`${t} tried to start a sandbox of its own inside the ChatPanel sandbox, and macOS does not allow one inside another — so that tool could not run. To let it, turn on "Run outside the ChatPanel sandbox" in this agent's settings.`:null}async function st(e,t,n,s={},{spawnImpl:a=oe,box:o=ne(),kind:p="agent",label:u=""}={}){const i=await o.wrap(e,t,n,s);return Te(a(i.bin,i.argv,i.opts),i,{kind:p,label:u})}async function ot(e,{box:t=ne(),platform:n=process.platform,loadSrt:s=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),out:a=console.log,err:o=console.error}={}){const p=e[0]||"status";if(p==="status")return a(JSON.stringify(await t.status(),null,2)),0;if(p!=="install")return o("usage: chatpanel-bridge sandbox [status|install]"),2;if(n!=="win32")return a("Nothing to install here: on macOS and Linux the sandbox runs as you. Only Windows has the one-time account setup."),0;let u;try{u=await s()}catch(i){return o(`sandbox-runtime is not installed — it ships with the gateway, so run \`chatpanel-gateway sandbox install\` (${i.message})`),1}try{const i=u.resolveSrtWin({path:u.VENDORED_SRT_WIN_EXE}),x=await u.installWindowsSandboxAsync({srtWin:i});return x?.cancelled?(o("Cancelled at the administrator prompt — nothing was installed."),1):(a(`The sandbox account is installed${x?.user?.sid?` (${x.user.sid})`:""}. Start the bridge with CHATPANEL_SANDBOX_WINDOWS=1; /health.sandbox says what the next run gets.`),0)}catch(i){o(`install failed: ${i.message}`);try{o(u.windowsInstallInstructions())}catch{}return 1}}export{Qe as _resetLiveForTest,nt as _resetNotedForTest,ze as _resetRefusalsForTest,et as _setSandboxForTest,Je as acceptRefusalReport,ge as createSandbox,Y as currentGrant,Ye as grantedWriteRoots,qe as liveProcesses,rt as nestedSandboxLine,tt as noteSandbox,z as parseRefusalLine,_e as recentRefusals,J as recordRefusal,ye as refusalsFor,ot as runSandboxCli,ne as sandbox,te as sandboxConfigFromEnv,st as sandboxedSpawn,Te as track,Ke as withGrant,Ve as withoutOutsideWhenCapped};
|
package/src/server.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createServer as Te}from"node:http";import E from"node:os";import{randomBytes as Ee,randomInt as ve,timingSafeEqual as Oe}from"node:crypto";import{mkdirSync as Ae,writeFileSync as Ce,readFileSync as Y,existsSync as xe}from"node:fs";import{join as _}from"node:path";import*as Pe from"./engines/claude.js";import*as Re from"./engines/codex.js";import*as Ie from"./engines/antigravity.js";import{pi as $e,opencode as Ne,kiro as De,copilot as _e,deepseek as He,hermes as Me}from"./engines/cli-agents.js";import{connectorsFor as Ue}from"./connectors.js";import*as Be from"./engines/custom.js";import{installService as We,uninstallService as Ge,serviceStatus as Le,restartService as Q}from"./service.js";import{skillIndex as G,listRecords as je,readRecord as Fe,readPackageFile as Je,skillsHealth as Xe,quarantinedSkills as ze,clearSkillCache as L}from"./skills.js";import{writeSkillPackage as Ke,writeSkillFile as Ve,deleteSkillPackage as Ye,SkillWriteError as Qe}from"./skill-write.js";import{agentDefRoots as Ze,scanAgentDefs as qe,listAgentDefs as et,readAgentDef as tt,planAgentExport as nt,exportAgentDef as ot,agentDefsHealth as rt,AgentDefError as at}from"./agent-defs.js";import{capabilityToolSpecs as it,runCapabilityTool as st}from"./mcp-capabilities.js";import{createSession as ct,deleteSession as Z,getSession as q,activeSession as lt,relayToolCall as dt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ut,isDefaultWorkdir as ht,resolveWorkdir as pt,writeScopeNote as ft}from"./workdir.js";import{sandbox as ee,runSandboxCli as mt,withGrant as te,grantedWriteRoots as gt,acceptRefusalReport as yt,liveProcesses as wt}from"./sandbox.js";import{gitState as bt,gitDelta as St}from"./scm.js";import{listConnections as kt,putConnection as Tt,removeConnection as Et,runEnvFor as vt,testConnection as Ot,secretBackend as ne}from"./connections.js";import{worktreeFor as oe,listWorktrees as At,removeWorktree as Ct,withHook as xt,WORKTREE_ROOT as re}from"./worktree.js";import{AGENT_CLIS as Pt,agentAvailable as Rt,agentInstallDirs as It,enrichPath as $t,enrichAgentEnv as Nt,findAgentBin as Dt,resolveCommand as ae}from"./env.js";import"./sanitize.js";import{checkForUpdate as _t,selfUpdate as ie,isEmbedded as Ht}from"./update.js";import{callLocalMcp as Mt,localMcpStatus as Ut,signInLocalMcp as Bt,signInStatusLocalMcp as Wt}from"./mcp-local.js";import{assertPublicHttpUrl as se,assertPublicWebUrl as ce}from"./ssrf.js";import{startRun as le,endRun as j,cancelRun as Gt,cancelAll as Lt}from"./runs.js";import{closeWarmPools as jt,warmStatus as Ft}from"./warm.js";import{CompatError as R,anthropicError as F,anthropicStream as Jt,chatCompletionStream as Xt,completionStream as zt,createAnthropicMessage as Kt,createChatCompletion as Vt,createCompletion as Yt,createResponse as Qt,openAIError as b,parseAnthropicMessage as Zt,parseChatCompletion as qt,parseCompletion as en,parseResponse as tn,responseStream as nn}from"./api-compat.js";import{callerTrust as on,isPaired as I,parseExtensionIds as rn,capRunOptions as an,engineHonoursReach as sn,createPairingStore as cn,formatPairingCode as ln}from"./pii/trust.js";const g="0.29.5",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,O={claude:{engine:Pe,label:"Claude Code"},codex:{engine:Re,label:"Codex"},antigravity:{engine:Ie,label:"Antigravity",tools:!1},pi:{engine:$e,label:"Pi"},opencode:{engine:Ne,label:"OpenCode"},hermes:{engine:Me,label:"Hermes"},kiro:{engine:De,label:"Kiro"},copilot:{engine:_e,label:"GitHub Copilot"},deepseek:{engine:He,label:"DeepSeek Harness"},custom:{engine:Be,label:"Custom",hidden:!0}};function de(t){return!t||t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}const dn=rn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function $(t){return t.chatpanelTrust||(t.chatpanelTrust=on({origin:t.headers.origin||"",hasToken:fe(t),extensionIds:dn})),t.chatpanelTrust}function un(t){return t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}function hn(t,e){const n=t.headers.origin||"",r=de(n);e.setHeader("Access-Control-Allow-Origin",r?n||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function pn(t){if(!J.has(k))return!0;const e=String(t.headers.host||"");if(!e)return!1;const n=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(n)}const N=_(E.homedir(),".chatpanel","bridge-token");let S="";function fn(){try{xe(N)&&(S=Y(N,"utf8").trim()),S||(S=Ee(32).toString("hex"),Ae(_(E.homedir(),".chatpanel"),{recursive:!0}),Ce(N,S,{mode:384}))}catch(t){u("error",`could not initialise bridge token: ${t?.message||t}`)}}const ue=cn({random:()=>ve(0,1e6)/1e6});function mn(t){if(!S)return a(t,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ue.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),a(t,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function gn(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=ue.claim(n?.code);return r.ok?(u("info",`paired a ${$(t)} client${t.headers.origin?` (${t.headers.origin})`:""}`),a(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${$(t)} caller`),a(e,403,{error:r.reason}))}function yn(t,e){const n=$(t);return a(e,200,{ok:!0,trust:n,paired:I(n),version:g})}let H=null;async function he(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:_(E.homedir(),".chatpanel"),dataDir:_(E.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function pe(t,e,n){try{const r=await he(),o=t.method==="POST"?await m(t):{};if(n==="status")return a(e,200,await r.status());if(n==="connect"){const i=await r.connect(o);return a(e,200,{ok:!0,...i})}return n==="pair"?a(e,200,await r.pair()):n==="unpair"?a(e,200,await r.unpair(String(o.actorId||""))):n==="settings"?a(e,200,await r.update(o)):n==="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 fe(t){if(!S)return!1;const e=String(t.headers.authorization||""),n=(e.startsWith("Bearer ")?e.slice(7):String(t.headers["x-api-key"]||t.headers["x-chatpanel-token"]||"")).trim();if(!n)return!1;const r=Buffer.from(n),o=Buffer.from(S);return r.length===o.length&&Oe(r,o)}const wn=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),bn=new Set(["/debug"]),Sn=t=>bn.has(t),kn=(t,e)=>t!=="GET"&&t!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function Tn(t,e){if(!pn(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!de(n))return"forbidden origin";const r=t.method==="POST"&&wn.has(e)||t.method==="GET"&&Sn(e)||kn(t.method,e);return r&&!(un(n)||fe(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I($(t))&&!vn.has(e)?En:null}const En="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",vn=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function X(t,e,n){const r=$(t),o=an(n,r);if(!sn(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const i=o.reach,s=I(r)?i==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":i==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:o,note:s}}function a(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function m(t){return new Promise((e,n)=>{let r="";t.on("data",o=>{r+=o,r.length>50*1024*1024&&n(new Error("Body too large"))}),t.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){n(o)}}),t.on("error",n)})}async function On(t){const e=await Promise.all(Object.entries(O).filter(([,s])=>!s.hidden).map(async([s,{engine:d,label:c,tools:l}])=>{const h=await d.available().catch(p=>({ok:!1,reason:String(p?.message||p)})),y=await Ue(s).catch(()=>[]);return{id:s,label:c,available:h.ok,reason:h.reason,connectors:y,...l===!1?{tools:!1}:{}}})),n=Ht()?{current:g,updateAvailable:!1,embedded:"gateway"}:await _t(g).catch(()=>({current:g,updateAvailable:!1})),r=await Xe().catch(()=>null),o=await rt().catch(()=>null),i=await ee().status().catch(s=>({enabled:!1,reason:s.message}));a(t,200,{ok:!0,version:g,agents:e,update:n,workspace:ut,sandbox:i,localMcp:Ut(),processes:wt(),worktrees:re,secretBackend:ne(),warm:Ft(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{},...o?{agentDefs:o}:{}})}async function An(t,e,n){const{index:r,problems:o}=await G({extraDirs:e,workdir:n});a(t,200,{ok:!0,skills:je(r),problems:o})}async function Cn(t,e,n){a(t,200,{ok:!0,quarantined:await ze(e,n)})}async function xn(t,e,n,r){const{index:o}=await G({extraDirs:n,workdir:r}),i=Fe(o,e);if(!i)return a(t,404,{ok:!1,error:"unknown skill"});a(t,200,{ok:!0,skill:i})}async function Pn(t,e,n,r,o){const{index:i}=await G({extraDirs:r,workdir:o}),s=await Je(i,e,n);if(s.error)return a(t,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});a(t,200,{ok:!0,...s})}async function Rn(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{const r=await Ke({skill:n?.skill,files:n?.files||[],overwrite:!!n?.overwrite});return L(),a(e,200,r)}catch(r){return a(e,z(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function In(t,e,n,r){let o;try{o=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}try{const i=await Ve({name:n,path:r,text:o?.text??""});return L(),a(e,200,i)}catch(i){return a(e,z(i),{ok:!1,error:i.message,code:i.code||"ERROR"})}}async function $n(t,e){try{const n=await Ye({name:e});return L(),a(t,200,n)}catch(n){return a(t,z(n),{ok:!1,error:n.message,code:n.code||"ERROR"})}}function z(t){return t instanceof Qe?t.code==="NOT_FOUND"?404:t.code==="EXISTS"||t.code==="FULL"?409:t.code==="REFUSED"||t.code==="OUTSIDE"?403:400:400}async function me(t,e){return qe({roots:Ze(process.env,E.homedir(),t,e)})}async function Nn(t,e,n){const{index:r,quarantined:o,problems:i}=await me(e,n);a(t,200,{ok:!0,agents:et(r),...o.length?{quarantined:o.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...i.length?{problems:i}:{}})}async function Dn(t,e,n,r){const{index:o}=await me(n,r),i=tt(o,e);if(!i)return a(t,404,{ok:!1,error:"unknown agent definition"});a(t,200,{ok:!0,...i})}async function _n(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{return a(e,200,{ok:!0,...await nt({agent:n?.agent,to:n?.to})})}catch(r){return a(e,ge(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function Hn(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{return a(e,200,await ot({agent:n?.agent,to:n?.to,overwrite:!!n?.overwrite}))}catch(r){return a(e,ge(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}function ge(t){if(t instanceof at){if(t.code==="NOT_OURS")return 409;if(t.code==="TARGET")return 400}return 400}async function Mn(){return(await Promise.all(Object.entries(O).filter(([,e])=>!e.hidden).map(async([e,n])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await n.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...n})=>n)}async function ye(t,e=""){const n=await Mn();if(e){const r=n.find(o=>o.id===e);return r?a(t,200,r):a(t,404,b(new R(`Model "${e}" not found`,404,"model")))}return a(t,200,{object:"list",data:n})}async function Un(t){try{const e=await ie(g);a(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>Q(),400))}catch(e){a(t,400,{ok:!1,error:String(e?.message||e)})}}async function Bn(t,e){let n;try{n=await m(t)}catch(f){return a(e,400,{error:"Bad JSON: "+f.message})}const r=O[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});const o=X(t,n.agent,n.options||{});if(o.error)return a(e,403,{error:o.error});n.options=o.options,Array.isArray(n.images)&&n.images.length&&u("info",`chat: ${n.agent} received ${n.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const i=f=>{e.writableEnded||e.write(`data: ${JSON.stringify(f)}
|
|
2
|
+
import{createServer as Te}from"node:http";import E from"node:os";import{randomBytes as Ee,randomInt as ve,timingSafeEqual as Oe}from"node:crypto";import{mkdirSync as Ce,writeFileSync as Ae,readFileSync as Y,existsSync as xe}from"node:fs";import{join as _}from"node:path";import*as Pe from"./engines/claude.js";import*as Re from"./engines/codex.js";import*as Ie from"./engines/antigravity.js";import{pi as $e,opencode as Ne,kiro as De,copilot as _e,deepseek as He,hermes as Me}from"./engines/cli-agents.js";import{connectorsFor as Ue}from"./connectors.js";import*as We from"./engines/custom.js";import{installService as Be,uninstallService as Ge,serviceStatus as Le,restartService as Q}from"./service.js";import{skillIndex as G,listRecords as je,readRecord as Fe,readPackageFile as Je,skillsHealth as Xe,quarantinedSkills as ze,clearSkillCache as L}from"./skills.js";import{writeSkillPackage as Ke,writeSkillFile as Ve,deleteSkillPackage as Ye,SkillWriteError as Qe}from"./skill-write.js";import{agentDefRoots as Ze,scanAgentDefs as qe,listAgentDefs as et,readAgentDef as tt,planAgentExport as nt,exportAgentDef as ot,agentDefsHealth as rt,AgentDefError as at}from"./agent-defs.js";import{capabilityToolSpecs as it,runCapabilityTool as st}from"./mcp-capabilities.js";import{createSession as ct,deleteSession as Z,getSession as q,activeSession as lt,relayToolCall as dt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ut,isDefaultWorkdir as ht,resolveWorkdir as pt,writeScopeNote as ft}from"./workdir.js";import{sandbox as ee,runSandboxCli as mt,withGrant as te,withoutOutsideWhenCapped as gt,grantedWriteRoots as yt,acceptRefusalReport as wt,liveProcesses as bt}from"./sandbox.js";import{gitState as St,gitDelta as kt}from"./scm.js";import{listConnections as Tt,putConnection as Et,removeConnection as vt,runEnvFor as Ot,testConnection as Ct,secretBackend as ne}from"./connections.js";import{worktreeFor as oe,listWorktrees as At,removeWorktree as xt,withHook as Pt,WORKTREE_ROOT as re}from"./worktree.js";import{AGENT_CLIS as Rt,agentAvailable as It,agentInstallDirs as $t,enrichPath as Nt,enrichAgentEnv as Dt,findAgentBin as _t,resolveCommand as ae}from"./env.js";import"./sanitize.js";import{checkForUpdate as Ht,selfUpdate as ie,isEmbedded as Mt}from"./update.js";import{callLocalMcp as Ut,localMcpStatus as Wt,signInLocalMcp as Bt,signInStatusLocalMcp as Gt}from"./mcp-local.js";import{assertPublicHttpUrl as se,assertPublicWebUrl as ce}from"./ssrf.js";import{startRun as le,endRun as j,cancelRun as Lt,cancelAll as jt}from"./runs.js";import{closeWarmPools as Ft,warmStatus as Jt}from"./warm.js";import{CompatError as R,anthropicError as F,anthropicStream as Xt,chatCompletionStream as zt,completionStream as Kt,createAnthropicMessage as Vt,createChatCompletion as Yt,createCompletion as Qt,createResponse as Zt,openAIError as b,parseAnthropicMessage as qt,parseChatCompletion as en,parseCompletion as tn,parseResponse as nn,responseStream as on}from"./api-compat.js";import{callerTrust as rn,isPaired as I,parseExtensionIds as an,capRunOptions as sn,engineHonoursReach as cn,createPairingStore as ln,formatPairingCode as dn}from"./pii/trust.js";const g="0.32.1",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,O={claude:{engine:Pe,label:"Claude Code"},codex:{engine:Re,label:"Codex"},antigravity:{engine:Ie,label:"Antigravity",tools:!1},pi:{engine:$e,label:"Pi"},opencode:{engine:Ne,label:"OpenCode"},hermes:{engine:Me,label:"Hermes"},kiro:{engine:De,label:"Kiro"},copilot:{engine:_e,label:"GitHub Copilot"},deepseek:{engine:He,label:"DeepSeek Harness"},custom:{engine:We,label:"Custom",hidden:!0}};function de(t){return!t||t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}const un=an(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function $(t){return t.chatpanelTrust||(t.chatpanelTrust=rn({origin:t.headers.origin||"",hasToken:fe(t),extensionIds:un})),t.chatpanelTrust}function hn(t){return t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}function pn(t,e){const n=t.headers.origin||"",r=de(n);e.setHeader("Access-Control-Allow-Origin",r?n||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function fn(t){if(!J.has(k))return!0;const e=String(t.headers.host||"");if(!e)return!1;const n=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(n)}const N=_(E.homedir(),".chatpanel","bridge-token");let S="";function mn(){try{xe(N)&&(S=Y(N,"utf8").trim()),S||(S=Ee(32).toString("hex"),Ce(_(E.homedir(),".chatpanel"),{recursive:!0}),Ae(N,S,{mode:384}))}catch(t){u("error",`could not initialise bridge token: ${t?.message||t}`)}}const ue=ln({random:()=>ve(0,1e6)/1e6});function gn(t){if(!S)return a(t,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ue.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),a(t,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function yn(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=ue.claim(n?.code);return r.ok?(u("info",`paired a ${$(t)} client${t.headers.origin?` (${t.headers.origin})`:""}`),a(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${$(t)} caller`),a(e,403,{error:r.reason}))}function wn(t,e){const n=$(t);return a(e,200,{ok:!0,trust:n,paired:I(n),version:g})}let H=null;async function he(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:_(E.homedir(),".chatpanel"),dataDir:_(E.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function pe(t,e,n){try{const r=await he(),o=t.method==="POST"?await m(t):{};if(n==="status")return a(e,200,await r.status());if(n==="connect"){const i=await r.connect(o);return a(e,200,{ok:!0,...i})}return n==="pair"?a(e,200,await r.pair()):n==="unpair"?a(e,200,await r.unpair(String(o.actorId||""))):n==="settings"?a(e,200,await r.update(o)):n==="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 fe(t){if(!S)return!1;const e=String(t.headers.authorization||""),n=(e.startsWith("Bearer ")?e.slice(7):String(t.headers["x-api-key"]||t.headers["x-chatpanel-token"]||"")).trim();if(!n)return!1;const r=Buffer.from(n),o=Buffer.from(S);return r.length===o.length&&Oe(r,o)}const bn=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),Sn=new Set(["/debug"]),kn=t=>Sn.has(t),Tn=(t,e)=>t!=="GET"&&t!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function En(t,e){if(!fn(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!de(n))return"forbidden origin";const r=t.method==="POST"&&bn.has(e)||t.method==="GET"&&kn(e)||Tn(t.method,e);return r&&!(hn(n)||fe(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I($(t))&&!On.has(e)?vn:null}const vn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",On=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function X(t,e,n){const r=$(t),o=gt(sn(n,r));if(!cn(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const i=o.reach,s=I(r)?i==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":i==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:o,note:s}}function a(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function m(t){return new Promise((e,n)=>{let r="";t.on("data",o=>{r+=o,r.length>50*1024*1024&&n(new Error("Body too large"))}),t.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){n(o)}}),t.on("error",n)})}async function Cn(t){const e=await Promise.all(Object.entries(O).filter(([,s])=>!s.hidden).map(async([s,{engine:d,label:c,tools:l}])=>{const h=await d.available().catch(p=>({ok:!1,reason:String(p?.message||p)})),y=await Ue(s).catch(()=>[]);return{id:s,label:c,available:h.ok,reason:h.reason,connectors:y,...l===!1?{tools:!1}:{}}})),n=Mt()?{current:g,updateAvailable:!1,embedded:"gateway"}:await Ht(g).catch(()=>({current:g,updateAvailable:!1})),r=await Xe().catch(()=>null),o=await rt().catch(()=>null),i=await ee().status().catch(s=>({enabled:!1,reason:s.message}));a(t,200,{ok:!0,version:g,agents:e,update:n,workspace:ut,sandbox:i,localMcp:Wt(),processes:bt(),worktrees:re,secretBackend:ne(),warm:Jt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{},...o?{agentDefs:o}:{}})}async function An(t,e,n){const{index:r,problems:o}=await G({extraDirs:e,workdir:n});a(t,200,{ok:!0,skills:je(r),problems:o})}async function xn(t,e,n){a(t,200,{ok:!0,quarantined:await ze(e,n)})}async function Pn(t,e,n,r){const{index:o}=await G({extraDirs:n,workdir:r}),i=Fe(o,e);if(!i)return a(t,404,{ok:!1,error:"unknown skill"});a(t,200,{ok:!0,skill:i})}async function Rn(t,e,n,r,o){const{index:i}=await G({extraDirs:r,workdir:o}),s=await Je(i,e,n);if(s.error)return a(t,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});a(t,200,{ok:!0,...s})}async function In(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{const r=await Ke({skill:n?.skill,files:n?.files||[],overwrite:!!n?.overwrite});return L(),a(e,200,r)}catch(r){return a(e,z(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function $n(t,e,n,r){let o;try{o=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}try{const i=await Ve({name:n,path:r,text:o?.text??""});return L(),a(e,200,i)}catch(i){return a(e,z(i),{ok:!1,error:i.message,code:i.code||"ERROR"})}}async function Nn(t,e){try{const n=await Ye({name:e});return L(),a(t,200,n)}catch(n){return a(t,z(n),{ok:!1,error:n.message,code:n.code||"ERROR"})}}function z(t){return t instanceof Qe?t.code==="NOT_FOUND"?404:t.code==="EXISTS"||t.code==="FULL"?409:t.code==="REFUSED"||t.code==="OUTSIDE"?403:400:400}async function me(t,e){return qe({roots:Ze(process.env,E.homedir(),t,e)})}async function Dn(t,e,n){const{index:r,quarantined:o,problems:i}=await me(e,n);a(t,200,{ok:!0,agents:et(r),...o.length?{quarantined:o.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...i.length?{problems:i}:{}})}async function _n(t,e,n,r){const{index:o}=await me(n,r),i=tt(o,e);if(!i)return a(t,404,{ok:!1,error:"unknown agent definition"});a(t,200,{ok:!0,...i})}async function Hn(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{return a(e,200,{ok:!0,...await nt({agent:n?.agent,to:n?.to})})}catch(r){return a(e,ge(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function Mn(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{return a(e,200,await ot({agent:n?.agent,to:n?.to,overwrite:!!n?.overwrite}))}catch(r){return a(e,ge(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}function ge(t){if(t instanceof at){if(t.code==="NOT_OURS")return 409;if(t.code==="TARGET")return 400}return 400}async function Un(){return(await Promise.all(Object.entries(O).filter(([,e])=>!e.hidden).map(async([e,n])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await n.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...n})=>n)}async function ye(t,e=""){const n=await Un();if(e){const r=n.find(o=>o.id===e);return r?a(t,200,r):a(t,404,b(new R(`Model "${e}" not found`,404,"model")))}return a(t,200,{object:"list",data:n})}async function Wn(t){try{const e=await ie(g);a(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>Q(),400))}catch(e){a(t,400,{ok:!1,error:String(e?.message||e)})}}async function Bn(t,e){let n;try{n=await m(t)}catch(f){return a(e,400,{error:"Bad JSON: "+f.message})}const r=O[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});const o=X(t,n.agent,n.options||{});if(o.error)return a(e,403,{error:o.error});n.options=o.options,Array.isArray(n.images)&&n.images.length&&u("info",`chat: ${n.agent} received ${n.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const i=f=>{e.writableEnded||e.write(`data: ${JSON.stringify(f)}
|
|
3
3
|
|
|
4
|
-
`)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=le(d),l={signal:c.signal,abort:()=>c.cancel("client")},h=()=>{s=!0,c.cancel("disconnected")};t.on("close",h),e.on("close",h),e.on("error",h);const y=f=>{s||i(f)};i({type:"run",id:d}),o.note&&i({type:"status",text:o.note});let p=null;if(n.options?.workspace&&typeof n.options.workspace=="object"){const f=n.options.workspace;if(p=await oe({repo:f.repo,projectId:f.projectId,jobId:f.jobId,base:f.base||null}),p.error){i({type:"error",error:`workspace: ${p.error}`}),j(d),e.writableEnded||e.end();return}}const K=p?p.path:pt(n.options?.workingDir);let
|
|
4
|
+
`)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=le(d),l={signal:c.signal,abort:()=>c.cancel("client")},h=()=>{s=!0,c.cancel("disconnected")};t.on("close",h),e.on("close",h),e.on("error",h);const y=f=>{s||i(f)};i({type:"run",id:d}),o.note&&i({type:"status",text:o.note});let p=null;if(n.options?.workspace&&typeof n.options.workspace=="object"){const f=n.options.workspace;if(p=await oe({repo:f.repo,projectId:f.projectId,jobId:f.jobId,base:f.base||null}),p.error){i({type:"error",error:`workspace: ${p.error}`}),j(d),e.writableEnded||e.end();return}}const K=p?p.path:pt(n.options?.workingDir);let C=null;{const f=K,A=!!p||!ht(n.options?.workingDir),w=ft(n.agent,n.options?.permissionMode,f,yt(f,{grant:n.options?.sandbox}));i({type:"workdir",path:f,isDefault:!A,writeScope:w||void 0}),i({type:"status",text:`Working in ${f}${A?"":" (default)"}`}),w&&i({type:"status",text:w}),C=await St(f),C&&i({type:"scm",phase:"before",...C})}let B=null;if(C||p){const f=Array.isArray(n.options?.grants)?n.options.grants:[],{env:A,connection:w}=Ot({remote:C?.remote||null,grants:f,branch:p?.branch||null,connectionId:n.options?.connectionId||null});B=Pt(A),p&&i({type:"workspace",path:p.path,branch:p.branch,base:p.base,created:p.created,repo:p.repo,...w?{connection:w}:{}}),w&&i({type:"status",text:`Git credential: ${w.kind} · ${w.host}${w.hasSecret?"":" (no token stored)"} · push: ${A.CHATPANEL_SCM_PUSH==="own"?`${p?.branch} only`:A.CHATPANEL_SCM_PUSH}`})}const V=n.approvals===!0,D={...n.options||{},...p?{workingDir:p.path}:{},...B?{runEnv:B}:{},approvals:V};let P=null;(n.pageTools?.specs?.length||V)&&(P=ct(y,n.pageTools?.specs||[]),D.permissionSession=P,n.pageTools?.specs?.length&&(D.mcp={url:`http://${k}:${v}/mcp/${P.id}`,serverName:"chatpanel_browser",specs:n.pageTools.specs}));try{await te(D.sandbox,()=>r.engine.chat({messages:Array.isArray(n.messages)?n.messages:[],system:n.system||"",options:D,images:Array.isArray(n.images)?n.images:[]},y,{signal:l.signal}))}catch(f){u("error",`${n.agent} chat failed: ${f?.message||f}`),i({type:"error",error:f?.message||String(f)})}finally{if(!s){const f=await kt(K,C).catch(()=>null);f&&y({type:"scm",phase:"after",...f})}j(d),P&&Z(P.id),e.writableEnded||e.end()}}async function Gn(t,e,n){if(t.method==="GET"&&n==="/connections")return a(e,200,{ok:!0,connections:Tt(),secretBackend:ne()});if(t.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await m(t);if(n==="/connections")try{return a(e,200,{ok:!0,connection:Et(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(n);return o?o[2]==="delete"?a(e,200,{ok:vt(o[1])}):a(e,200,Ct(o[1],r.remote||"")):a(e,404,{error:"Not found"})}async function Ln(t,e,n){if(t.method==="GET"&&n==="/worktrees")return a(e,200,{ok:!0,root:re,worktrees:await At()});if(t.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await m(t);if(n==="/worktrees"){const o=await oe({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(n==="/worktrees/remove"){const o=await xt({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 T(t,e,n){const r=O[t.agent];if(!r||r.hidden)throw new R(`Unknown ChatPanel agent "${t.agent}"`,400,"model");const o=await r.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!o.ok)throw new R(o.reason||`${t.agent} is unavailable`,503,"model");const i=`run_${Math.random().toString(36).slice(2,10)}`,s=le(i),d=()=>s.cancel("disconnected");n.on("close",d);let c="";try{return await te(t.options?.sandbox,()=>r.engine.chat({messages:t.messages,system:t.system,options:t.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal})),c}finally{n.off("close",d),j(i)}}function M(t){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(t,e){t.writableEnded||t.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
|
|
5
5
|
|
|
6
6
|
`)}function U(t,e,n){t.writableEnded||t.write(`event: ${e}
|
|
7
7
|
data: ${JSON.stringify(n)}
|
|
8
8
|
|
|
9
|
-
`)}async function B(t,e,n,r){try{const o=n(await m(t)),i=X(t,o.agent,o.options||{});if(i.error)throw new R(i.error,403,"permission");return o.options=i.options,o}catch(o){return a(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new R(`Bad JSON: ${o.message}`):o)),null}}async function Ln(t,e){const n=await B(t,e,qt,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Vt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=Xt(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function jn(t,e){const n=await B(t,e,en,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Yt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=zt(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function Fn(t,e){const n=await B(t,e,tn,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Qt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=nn(n.requestedModel,o=>U(e,o.type,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){const i={type:"error",sequence_number:0,...b(o)};U(e,"error",i)}e.end()}async function Jn(t,e){const n=await B(t,e,Zt,F);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Kt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,F(o))}M(e);const r=Jt(n.requestedModel,(o,i)=>U(e,o,i));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){U(e,"error",F(o))}e.end()}async function Xn(t,e){let n={};try{n=await m(t)||{}}catch{}const r=String(n.id||"").trim(),o=r?Gt(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),a(e,200,{ok:!0,cancelled:o})}async function we(t,e,n){let r;try{r=await m(t)}catch{return a(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=n?q(n):lt(),i=c=>{o&&e.setHeader("Mcp-Session-Id",o.id),a(e,200,{jsonrpc:"2.0",id:r.id??null,result:c})},s=(c,l)=>a(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:c,message:l}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return i({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const d=it();if(r.method==="tools/list"){const c=o?o.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return i({tools:[...d,...c]})}if(r.method==="tools/call"){const c=await st(r.params?.name,r.params?.arguments||{});if(c)return i(c);if(!o)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return i(await dt(o,r.params?.name,r.params?.arguments||{}))}catch(l){return i({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function zn(t,e){let n;try{n=await m(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 Mt({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox},o);return o.id==null?(e.writeHead(202),e.end()):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 Kn(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=n.server||{};if(!r.command)return a(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const o={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};try{return a(e,200,n.status?Wt(o):await Bt(o))}catch(i){return a(e,200,{state:"failed",error:String(i?.message||i)})}}async function Vn(t,e){let n;try{n=await m(t)}catch(h){return a(e,400,{error:"Bad JSON: "+h.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=se(r)}catch(h){return a(e,400,{error:String(h?.message||h)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[h,y]of Object.entries(o)){const p=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(p)||p.startsWith("x-"))&&(d[h]=String(y))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(i),redirect:"follow",signal:c.signal});try{h.url&&se(h.url)}catch(p){return a(e,400,{error:String(p?.message||p)})}const y=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")||"",authenticate:h.headers.get("WWW-Authenticate")||"",body:y})}catch(h){const y=h?.name==="AbortError"?"timed out":String(h?.message||h);return a(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(l)}}const be=256*1024,Yn=5,Qn=8e3;async function Zn(t){let e=ce(t);const n=new AbortController,r=setTimeout(()=>n.abort(),Qn);try{for(let o=0;o<=Yn;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=ce(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:to(await qn(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function qn(t){if(!t.body?.getReader)return(await t.text().catch(()=>"")).slice(0,be);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>=be))break}}finally{try{await e.cancel()}catch{}}return r}function eo(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 to(t){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(t);return e?eo(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function no(t,e){let n;try{n=await m(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 Zn(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 oo(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=q(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 ro(t,e){let n;try{n=await m(t)}catch(c){return a(e,400,{error:"Bad JSON: "+c.message})}const r=O[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=X(t,n.agent,{model:i});if(s.error)return a(e,403,{error:s.error});const d=String(n.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let c="";return typeof r.engine.complete=="function"?c=await r.engine.complete({prompt:o,system:d,model:i}):await r.engine.chat({messages:[{role:"user",content:o}],system:d,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),a(e,200,{text:(c||"").trim()})}catch(c){return a(e,502,{error:c?.message||String(c)})}}async function ao(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=O[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 io(t,e){let n;try{n=await m(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=ae(r)}catch{o=null}return a(e,200,{ok:!!o,via:o?o.kind:null})}const Se=Te(async(t,e)=>{if(hn(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=Tn(t,n.pathname);if(r)return a(e,403,{error:r});try{if(t.method==="GET"&&n.pathname==="/health")return On(e);const o=n.searchParams.getAll("dir"),i=n.searchParams.get("workdir")||"";if(t.method==="GET"&&n.pathname==="/skills")return An(e,o,i);if(t.method==="GET"&&n.pathname==="/skills-quarantined")return Cn(e,o,i);if(t.method==="GET"&&n.pathname==="/agent-defs")return Nn(e,o,i);if(t.method==="POST"&&n.pathname==="/agent-defs/export-plan")return _n(t,e);if(t.method==="POST"&&n.pathname==="/agent-defs/export")return Hn(t,e);if(t.method==="GET"&&n.pathname.startsWith("/agent-defs/"))return Dn(e,decodeURIComponent(n.pathname.slice(12)),o,i);if(t.method==="POST"&&n.pathname==="/skills")return Rn(t,e);if((t.method==="PUT"||t.method==="POST"||t.method==="DELETE")&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?t.method==="DELETE"?$n(e,decodeURIComponent(s)):a(e,405,{ok:!1,error:"use POST /skills to save a skill"}):t.method==="DELETE"?a(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):In(t,e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)))}if(t.method==="GET"&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?xn(e,decodeURIComponent(s),o,i):Pn(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,i)}if(n.pathname==="/connections"||n.pathname.startsWith("/connections/"))return Wn(t,e,n.pathname);if(n.pathname==="/worktrees"||n.pathname.startsWith("/worktrees/"))return Gn(t,e,n.pathname);if(t.method==="GET"&&n.pathname==="/v1/models")return ye(e);if(t.method==="GET"&&n.pathname.startsWith("/v1/models/"))return ye(e,decodeURIComponent(n.pathname.slice(11)));if(t.method==="GET"&&n.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return a(e,200,{version:g,agents:Object.fromEntries(Pt.map(d=>[d,s?Dt(d)||ae(d)?.kind||null:Rt(d)])),...s?{home:E.homedir(),path:process.env.PATH,installDirs:It(E.homedir())}:{}})}if(t.method==="POST"&&n.pathname==="/chat")return Bn(t,e);if(t.method==="POST"&&n.pathname==="/pair")return gn(t,e);if(t.method==="POST"&&n.pathname==="/pair/code")return mn(e);if(t.method==="POST"&&n.pathname==="/whoami")return yn(t,e);if(t.method==="POST"&&n.pathname==="/v1/chat/completions")return Ln(t,e);if(t.method==="POST"&&n.pathname==="/v1/completions")return jn(t,e);if(t.method==="POST"&&n.pathname==="/v1/responses")return Fn(t,e);if(t.method==="POST"&&n.pathname==="/v1/messages")return Jn(t,e);if(n.pathname==="/mcp"){if(t.method==="POST")return we(t,e,null);if(t.method==="GET")return e.writeHead(405),e.end()}if(n.pathname.startsWith("/mcp/")){const s=decodeURIComponent(n.pathname.slice(5));if(t.method==="POST")return we(t,e,s);if(t.method==="GET")return e.writeHead(405),e.end();if(t.method==="DELETE")return Z(s),e.writeHead(204),e.end()}if(t.method==="GET"&&n.pathname==="/channels")return pe(t,e,"status");if(t.method==="POST"&&n.pathname.startsWith("/channels/"))return pe(t,e,n.pathname.slice(10));if(t.method==="POST"&&n.pathname==="/cancel")return Xn(t,e);if(t.method==="POST"&&n.pathname==="/tool-result")return oo(t,e);if(t.method==="POST"&&n.pathname==="/sandbox/refused"){let s=null;try{s=await m(t)}catch{s=null}const d=yt(s||{});return e.writeHead(d?204:403),e.end()}if(t.method==="POST"&&n.pathname==="/mcp-local")return zn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-local/signin")return Kn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-remote")return Vn(t,e);if(t.method==="POST"&&n.pathname==="/fetch-title")return no(t,e);if(t.method==="POST"&&n.pathname==="/complete")return ro(t,e);if(t.method==="POST"&&n.pathname==="/list-models")return ao(t,e);if(t.method==="POST"&&n.pathname==="/agent-check")return io(t,e);if(t.method==="POST"&&n.pathname==="/update")return Un(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 so(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 c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const h=(await l.text()).trim();h&&process.stdout.write(h+`
|
|
9
|
+
`)}async function W(t,e,n,r){try{const o=n(await m(t)),i=X(t,o.agent,o.options||{});if(i.error)throw new R(i.error,403,"permission");return o.options=i.options,o}catch(o){return a(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new R(`Bad JSON: ${o.message}`):o)),null}}async function jn(t,e){const n=await W(t,e,en,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Yt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=zt(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function Fn(t,e){const n=await W(t,e,tn,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Qt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=Kt(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function Jn(t,e){const n=await W(t,e,nn,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Zt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=on(n.requestedModel,o=>U(e,o.type,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){const i={type:"error",sequence_number:0,...b(o)};U(e,"error",i)}e.end()}async function Xn(t,e){const n=await W(t,e,qt,F);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Vt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,F(o))}M(e);const r=Xt(n.requestedModel,(o,i)=>U(e,o,i));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){U(e,"error",F(o))}e.end()}async function zn(t,e){let n={};try{n=await m(t)||{}}catch{}const r=String(n.id||"").trim(),o=r?Lt(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),a(e,200,{ok:!0,cancelled:o})}async function we(t,e,n){let r;try{r=await m(t)}catch{return a(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=n?q(n):lt(),i=c=>{o&&e.setHeader("Mcp-Session-Id",o.id),a(e,200,{jsonrpc:"2.0",id:r.id??null,result:c})},s=(c,l)=>a(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:c,message:l}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return i({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const d=it();if(r.method==="tools/list"){const c=o?o.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return i({tools:[...d,...c]})}if(r.method==="tools/call"){const c=await st(r.params?.name,r.params?.arguments||{});if(c)return i(c);if(!o)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return i(await dt(o,r.params?.name,r.params?.arguments||{}))}catch(l){return i({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function Kn(t,e){let n;try{n=await m(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 Ut({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox},o);return o.id==null?(e.writeHead(202),e.end()):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 Vn(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=n.server||{};if(!r.command)return a(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const o={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};try{return a(e,200,n.status?Gt(o):await Bt(o))}catch(i){return a(e,200,{state:"failed",error:String(i?.message||i)})}}async function Yn(t,e){let n;try{n=await m(t)}catch(h){return a(e,400,{error:"Bad JSON: "+h.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=se(r)}catch(h){return a(e,400,{error:String(h?.message||h)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[h,y]of Object.entries(o)){const p=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(p)||p.startsWith("x-"))&&(d[h]=String(y))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(i),redirect:"follow",signal:c.signal});try{h.url&&se(h.url)}catch(p){return a(e,400,{error:String(p?.message||p)})}const y=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")||"",authenticate:h.headers.get("WWW-Authenticate")||"",body:y})}catch(h){const y=h?.name==="AbortError"?"timed out":String(h?.message||h);return a(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(l)}}const be=256*1024,Qn=5,Zn=8e3;async function qn(t){let e=ce(t);const n=new AbortController,r=setTimeout(()=>n.abort(),Zn);try{for(let o=0;o<=Qn;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=ce(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:no(await eo(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function eo(t){if(!t.body?.getReader)return(await t.text().catch(()=>"")).slice(0,be);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>=be))break}}finally{try{await e.cancel()}catch{}}return r}function to(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 no(t){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(t);return e?to(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function oo(t,e){let n;try{n=await m(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 qn(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 ro(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=q(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 ao(t,e){let n;try{n=await m(t)}catch(c){return a(e,400,{error:"Bad JSON: "+c.message})}const r=O[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=X(t,n.agent,{model:i});if(s.error)return a(e,403,{error:s.error});const d=String(n.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let c="";return typeof r.engine.complete=="function"?c=await r.engine.complete({prompt:o,system:d,model:i}):await r.engine.chat({messages:[{role:"user",content:o}],system:d,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),a(e,200,{text:(c||"").trim()})}catch(c){return a(e,502,{error:c?.message||String(c)})}}async function io(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=O[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 so(t,e){let n;try{n=await m(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=ae(r)}catch{o=null}return a(e,200,{ok:!!o,via:o?o.kind:null})}const Se=Te(async(t,e)=>{if(pn(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=En(t,n.pathname);if(r)return a(e,403,{error:r});try{if(t.method==="GET"&&n.pathname==="/health")return Cn(e);const o=n.searchParams.getAll("dir"),i=n.searchParams.get("workdir")||"";if(t.method==="GET"&&n.pathname==="/skills")return An(e,o,i);if(t.method==="GET"&&n.pathname==="/skills-quarantined")return xn(e,o,i);if(t.method==="GET"&&n.pathname==="/agent-defs")return Dn(e,o,i);if(t.method==="POST"&&n.pathname==="/agent-defs/export-plan")return Hn(t,e);if(t.method==="POST"&&n.pathname==="/agent-defs/export")return Mn(t,e);if(t.method==="GET"&&n.pathname.startsWith("/agent-defs/"))return _n(e,decodeURIComponent(n.pathname.slice(12)),o,i);if(t.method==="POST"&&n.pathname==="/skills")return In(t,e);if((t.method==="PUT"||t.method==="POST"||t.method==="DELETE")&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?t.method==="DELETE"?Nn(e,decodeURIComponent(s)):a(e,405,{ok:!1,error:"use POST /skills to save a skill"}):t.method==="DELETE"?a(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):$n(t,e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)))}if(t.method==="GET"&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?Pn(e,decodeURIComponent(s),o,i):Rn(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,i)}if(n.pathname==="/connections"||n.pathname.startsWith("/connections/"))return Gn(t,e,n.pathname);if(n.pathname==="/worktrees"||n.pathname.startsWith("/worktrees/"))return Ln(t,e,n.pathname);if(t.method==="GET"&&n.pathname==="/v1/models")return ye(e);if(t.method==="GET"&&n.pathname.startsWith("/v1/models/"))return ye(e,decodeURIComponent(n.pathname.slice(11)));if(t.method==="GET"&&n.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return a(e,200,{version:g,agents:Object.fromEntries(Rt.map(d=>[d,s?_t(d)||ae(d)?.kind||null:It(d)])),...s?{home:E.homedir(),path:process.env.PATH,installDirs:$t(E.homedir())}:{}})}if(t.method==="POST"&&n.pathname==="/chat")return Bn(t,e);if(t.method==="POST"&&n.pathname==="/pair")return yn(t,e);if(t.method==="POST"&&n.pathname==="/pair/code")return gn(e);if(t.method==="POST"&&n.pathname==="/whoami")return wn(t,e);if(t.method==="POST"&&n.pathname==="/v1/chat/completions")return jn(t,e);if(t.method==="POST"&&n.pathname==="/v1/completions")return Fn(t,e);if(t.method==="POST"&&n.pathname==="/v1/responses")return Jn(t,e);if(t.method==="POST"&&n.pathname==="/v1/messages")return Xn(t,e);if(n.pathname==="/mcp"){if(t.method==="POST")return we(t,e,null);if(t.method==="GET")return e.writeHead(405),e.end()}if(n.pathname.startsWith("/mcp/")){const s=decodeURIComponent(n.pathname.slice(5));if(t.method==="POST")return we(t,e,s);if(t.method==="GET")return e.writeHead(405),e.end();if(t.method==="DELETE")return Z(s),e.writeHead(204),e.end()}if(t.method==="GET"&&n.pathname==="/channels")return pe(t,e,"status");if(t.method==="POST"&&n.pathname.startsWith("/channels/"))return pe(t,e,n.pathname.slice(10));if(t.method==="POST"&&n.pathname==="/cancel")return zn(t,e);if(t.method==="POST"&&n.pathname==="/tool-result")return ro(t,e);if(t.method==="POST"&&n.pathname==="/sandbox/refused"){let s=null;try{s=await m(t)}catch{s=null}const d=wt(s||{});return e.writeHead(d?204:403),e.end()}if(t.method==="POST"&&n.pathname==="/mcp-local")return Kn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-local/signin")return Vn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-remote")return Yn(t,e);if(t.method==="POST"&&n.pathname==="/fetch-title")return oo(t,e);if(t.method==="POST"&&n.pathname==="/complete")return ao(t,e);if(t.method==="POST"&&n.pathname==="/list-models")return io(t,e);if(t.method==="POST"&&n.pathname==="/agent-check")return so(t,e);if(t.method==="POST"&&n.pathname==="/update")return Wn(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 co(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 c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const h=(await l.text()).trim();h&&process.stdout.write(h+`
|
|
10
10
|
`)}catch(l){c.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:c.id,error:{code:-32e3,message:String(l?.message||l)}})+`
|
|
11
11
|
`)}}r=!1,i()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",d=>{e+=d;let c;for(;(c=e.indexOf(`
|
|
12
|
-
`))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&n.push(l)}s()}),process.stdin.on("end",()=>{o=!0,i()}),process.stdin.resume()}function
|
|
12
|
+
`))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&n.push(l)}s()}),process.stdin.on("end",()=>{o=!0,i()}),process.stdin.resume()}function lo(){Nt(),Dt(),mn(),Se.on("error",t=>{t&&t.code==="EADDRINUSE"&&(u("error",`Port ${v} is already in use — another app (or a second bridge) has it.`),u("error","Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings."),process.exit(1)),u("error",`bridge server error: ${t?.message||t}`),process.exit(1)});for(const t of["SIGINT","SIGTERM"])process.on(t,()=>{const e=jt("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const n=Ft("shutdown");n&&u("info",`shutdown: closed ${n} warm agent process${n===1?"":"es"}`),ee().close(),setTimeout(()=>process.exit(0),e||n?300:0).unref?.(),!e&&!n&&process.exit(0)});Se.listen(v,k,async()=>{u("info",`listening on http://${k}:${v}`),J.has(k)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:t,label:e,hidden:n}]of Object.entries(O)){if(n)continue;const r=await t.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${e}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),he().then(t=>t.startIfConfigured()).then(t=>{t?.skipped||(t?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${t?.error||"unknown error"}`))}).catch(t=>u("error",`channels: ${t?.message||t}`))})}function uo(){console.log(`ChatPanel Bridge v${g}
|
|
13
13
|
|
|
14
14
|
Usage:
|
|
15
15
|
chatpanel-bridge start the bridge (foreground) on ${k}:${v}
|
|
@@ -21,4 +21,4 @@ Usage:
|
|
|
21
21
|
chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
|
|
22
22
|
chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
|
|
23
23
|
|
|
24
|
-
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function
|
|
24
|
+
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function ho(){const t=process.argv,e=(...n)=>n.some(r=>t.includes(r));if(e("--help","-h"))return uo(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("pair","--pair"))return(async()=>{let n="";try{n=Y(N,"utf8").trim()}catch{}const r=`http://${k}:${v}`;try{if(!n)throw new Error(`no token at ${N} — is the bridge running?`);const o=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(2500)}),i=await o.json().catch(()=>({}));if(!o.ok)throw new Error(i.error||`HTTP ${o.status}`);console.log(`Pairing code: ${dn(i.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(o){u("error",`could not get a pairing code from the bridge at ${r}: ${o?.message||o}`),process.exitCode=1}})(),!0;if(t.includes("sandbox"))return mt(t.slice(t.indexOf("sandbox")+1)).then(n=>{process.exitCode=n}),!0;if(e("--install")){try{Be(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(n){u("error","Install failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--uninstall")){try{Ge(),u("info","Removed the login auto-start.")}catch(n){u("error","Uninstall failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--status")){let n=!1;try{n=Le()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${n?"installed":"not installed"}`),!0}return!1}const ke=process.argv.indexOf("--mcp-stdio");if(ke>=0){const t=process.argv[ke+1];t||(console.error("--mcp-stdio requires a URL"),process.exit(1)),co(t)}else process.argv.includes("--update")?(async()=>{try{const t=await ie(g);u("info",`Updated v${t.from} → v${t.to}. Restarting the background service…`),Q()}catch(t){u("error","Update failed: "+(t?.message||t)),process.exitCode=1}})():ho()||lo();
|
package/src/sign-in.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as
|
|
1
|
+
import{spawn as y}from"node:child_process";import{buildSpawnSpec as w}from"./env.js";const S=Object.freeze({claude:"open a terminal, run `claude`, and type `/login`",codex:"open a terminal and run `codex login`",copilot:"open a terminal, run `copilot`, and type `/login`",opencode:"open a terminal and run `opencode auth login`",kiro:"open a terminal and run `kiro-cli login`",hermes:"open a terminal and run `hermes setup`",antigravity:"open a terminal, run `agy`, and sign in",deepseek:"open a terminal and sign in to the DeepSeek CLI",pi:"open a terminal, run `pi`, and sign in"}),x=/not logged in|please run \/login|authentication_failed|invalid api key(?:\s*·\s*please run)?|please (?:log|sign) ?in|login required|not authenticated|unauthenticated|missing bearer token|no credentials|\b401\b.*unauthori[sz]ed|token (?:has )?expired.*(?:log|sign) ?in|run `?(?:codex|claude) login`?/i;function D(n){const e=String(n||"");return!e||/\bmcp\b/i.test(e)&&!/not logged in|please run \/login|authentication_failed/i.test(e)?!1:x.test(e)}function N(n,e){const o=e?d.get(e):null;if(o?.signedIn===!0&&Date.now()-o.at<k)return`${n} is signed in on this machine, but the ChatPanel sandbox kept its login from it, so your message was not sent. This is ChatPanel's problem, not your sign-in: update ChatPanel, or turn on "Run outside the ChatPanel sandbox" for this agent until it is fixed.`;const a=S[e]||`sign in to ${n} in your terminal`;return`${n} isn't signed in on this machine, so your message was not sent. ChatPanel uses your own ${n} login and can't sign in for you: ${a}, finish the sign-in in the browser, then send your message again.`}const I={claude:{args:["auth","status"],read:n=>{try{const e=JSON.parse(n.slice(n.indexOf("{")));return typeof e.loggedIn=="boolean"?e.loggedIn:null}catch{return null}}},codex:{args:["login","status"],read:n=>/not logged in/i.test(n)?!1:/logged in/i.test(n)?!0:null}},g=new Map,b=15e3,d=new Map,k=10*6e4;async function T(n,e,{timeoutMs:o=5e3,now:a=Date.now(),spawnImpl:h=y}={}){const l=I[n];if(!l||!e)return null;const u=g.get(n);if(u&&a-u.at<b)return u.signedIn;const s=await new Promise(r=>{let c="",t;try{const[i,m,f]=w(e,l.args,process.cwd(),null);t=h(i,m,{...f,stdio:["ignore","pipe","pipe"]})}catch{return r(null)}const p=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}r(null)},o);t.stdout?.on("data",i=>{c+=i.toString()}),t.stderr?.on("data",i=>{c+=i.toString()}),t.on("error",()=>{clearTimeout(p),r(null)}),t.on("close",()=>{clearTimeout(p),r(l.read(c))})});return g.set(n,{at:a,signedIn:s}),s!==null&&d.set(n,{at:Date.now(),signedIn:s}),s}function P(){g.clear(),d.clear()}export{S as SIGN_IN_HINTS,D as loginRequired,P as resetSignInCache,N as signInMessage,T as signInStatus};
|