@chatpanel/bridge 0.27.2 → 0.29.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/scripts/sync-events.mjs +1 -1
- package/src/engines/claude.js +6 -6
- package/src/engines/codex.js +6 -6
- package/src/engines/custom.js +7 -7
- package/src/events/harness-cards.js +1 -0
- package/src/events/sandbox-policy.js +1 -1
- package/src/events/secret-names.js +1 -0
- package/src/net.js +1 -1
- package/src/pii/net.js +1 -1
- package/src/sandbox-runtime.js +1 -0
- package/src/sandbox-srt.js +1 -0
- package/src/sandbox.js +1 -1
- package/src/server.js +5 -5
- package/src/workdir.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.29.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
|
|
6
6
|
"keywords": [
|
package/scripts/sync-events.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFileSync as r,writeFileSync as p,existsSync as i,mkdirSync as
|
|
2
|
+
import{readFileSync as r,writeFileSync as p,existsSync as i,mkdirSync as j}from"node:fs";import{fileURLToPath as m}from"node:url";import{dirname as h,join as n}from"node:path";const c=n(h(m(import.meta.url)),".."),f=["scopes.js","skill-manifest.js","skill-scan.js","ref.js","event.js","view.js","capability.js","reach.js","scm-connection.js","sandbox-policy.js","secret-names.js","sandbox-grant.js","harness-cards.js","mcp-errors.js","registries.js","mcp-signin.js","mcp-config-import.js","toml-lite.js","frontmatter.js","skill-package.js","agent-portability.js","agent-dialects.js","agent-card.js","dialect-claude.js","dialect-codex.js","dialect-a2a.js","dialect-chatpanel.js","agent.js","team.js","engine.js","budget.js","mcp-args-env.js","mcp-launcher.js","agent-permission.js"];function v(){return[n(c,"node_modules","@chatpanel","events"),n(c,"..","chatpanel-events")].find(e=>i(n(e,"skill-manifest.js")))}const s=process.argv.includes("--check"),a=v();if(!a){const e="chatpanel-events not found (check out ../chatpanel-events).";s&&(console.error(`sync-events --check: ${e}`),process.exit(1)),console.warn(`sync-events: ${e} Leaving src/events as-is.`),process.exit(0)}const l=n(c,"src","events");s||j(l,{recursive:!0});const u=e=>`// GENERATED — do not edit.
|
|
3
3
|
// Source of truth: chatpanel-events/${e} (npm @chatpanel/events).
|
|
4
4
|
// Edit there, then run: npm run sync:events
|
|
5
5
|
//
|
package/src/engines/claude.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{spawn as F}from"node:child_process";import{writeFile as W,unlink as H}from"node:fs/promises";import P from"node:os";import R from"node:path";import{resolveClaude as S,buildSpawnSpec as q,isCompiledBinary as ae,selfMcpStdio as ie}from"../env.js";import{signInStatus as le,signInMessage as z,loginRequired as ce}from"../sign-in.js";import{buildCliPrompt as U}from"./prompt.js";import{summarizeCliError as ue}from"../cli-errors.js";import{killOnAbort as
|
|
2
|
-
`)}catch{}};l.stdout.on("data",
|
|
3
|
-
`))>=0;){const
|
|
4
|
-
`):(l.stdin.write(e),l.stdin.end())}).catch(
|
|
1
|
+
import{spawn as F}from"node:child_process";import{writeFile as W,unlink as H}from"node:fs/promises";import P from"node:os";import R from"node:path";import{resolveClaude as S,buildSpawnSpec as q,isCompiledBinary as ae,selfMcpStdio as ie}from"../env.js";import{signInStatus as le,signInMessage as z,loginRequired as ce}from"../sign-in.js";import{buildCliPrompt as U}from"./prompt.js";import{summarizeCliError as ue}from"../cli-errors.js";import{killOnAbort as de}from"../proc.js";import{sandbox as pe,noteSandbox as fe,track as he,grantedWriteRoots as me}from"../sandbox.js";import{harnessDirArgs as ye}from"../events/harness-cards.js";import{pushExtraArgs as _e,FORBIDDEN as be}from"./args.js";import{relayTimeoutMax as we}from"../relay-timeout.js";import{displayPath as ge,resolveWorkdir as B}from"../workdir.js";import{connectorsFor as Te}from"../connectors.js";import{chatWarm as xe}from"./claude-warm.js";import{claudePermissionResponse as Ee,permissionAnswer as Ce}from"../events/agent-permission.js";import{relayPermission as ke}from"../mcp-sessions.js";async function Se(e,t){const r=[];for(let i=0;i<(e?.length||0);i++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[i]?.dataUrl||"");if(!s)continue;const o=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",n=R.join(P.tmpdir(),`chatpanel-claude-img-${t}-${i}.${o}`);await W(n,Buffer.from(s[2],"base64")),r.push(n)}return r}const G=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,J=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task"],K=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),Ae=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task","ToolSearch"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch"])}),ve=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),Ne=Object.freeze(["remember","forget"]),Pe=Object.freeze(["ask_model","ask_status"]),Y=Object.freeze({device:Object.freeze([]),trusted:ve});function Me(e,t=[]){const r=Y[e]||Y.device,i=(t||[]).filter(n=>typeof n=="string"&&/^chatpanel/i.test(n)),s=[],o=[];for(const n of i){for(const a of r)s.push(`mcp__${n}__${a}`);for(const a of[...Ne,...Pe])o.push(`mcp__${n}__${a}`)}return{allow:s,deny:o}}function Oe(e){if(!e||e==="any")return null;const t=K[e]?e:"device";return{allow:[...K[t]],deny:[...Ae[t]]}}let M="Claude Code not found.",X=0,E=!1;async function lt(){if(Date.now()-X>(E?3e4:4e3)){X=Date.now();try{S()||!ae()&&await D()?E=!0:(E=!1,M=process.platform==="win32"?"Claude Code not found on Windows PATH or in WSL. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in — in Windows or in your WSL distro.":"Claude Code not found on PATH. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in.")}catch{E=!1}}return E?await le("claude",S()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:z("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:M}}async function ct(){return["opus","sonnet","haiku"]}function Le(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:r,args:i}=ie(e.url),s=[...new Set(e.specs.map(o=>o?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:r,args:i}}},allowedTools:s.map(o=>`mcp__${t}__${o}`)}}async function $e(e,t,r){const i=e?.request_id,s=e?.request?.subtype;if(s==="can_use_tool"){const o=t?await t(e.request):Ce("deny","This run has no approval surface.");return r(Ee(i,o,e.request)),!0}return r({type:"control_response",response:{subtype:"error",request_id:i,error:`unsupported control request: ${s||"unknown"}`}}),!1}function Q({prompt:e,args:t,cwd:r,env:i=null,emit:s,signal:o,harness:n=null,host:a=!1,ask:u=null}){const f=S();if(!f)return null;const[y,_,b]=q(f,a?[...t,"--input-format","stream-json"]:t,r,i);return new Promise((m,d)=>{pe().wrap(y,_,b,{engine:"claude",cwd:r}).then(c=>{fe(s,c.record);let l;try{l=he(F(c.bin,c.argv,c.opts),c,{kind:"agent"})}catch(p){return d(new Error(`Failed to start claude: ${p.message}`))}const w=de(l,o);let h="",g="",v=!1,T=null;const oe={sawText:!1,tail:"",boundary:!1,harnessChars:n};let O="",C,L=0;const N=()=>{clearTimeout(C),!L&&(C=setTimeout(()=>{l.kill("SIGKILL"),d(new Error(`Claude Code timed out — no output for ${Math.round(G/1e3)}s.`))},G))};N();const se=p=>{try{l.stdin.write(`${JSON.stringify(p)}
|
|
2
|
+
`)}catch{}};l.stdout.on("data",p=>{N(),h+=p.toString();let $;for(;($=h.indexOf(`
|
|
3
|
+
`))>=0;){const j=h.slice(0,$).trim();if(h=h.slice($+1),!j.startsWith("{"))continue;let x;try{x=JSON.parse(j)}catch{continue}if(x.type==="control_request"){L++,clearTimeout(C),$e(x,u,se).catch(()=>{}).finally(()=>{L--,N()});continue}if(x.type==="control_response")continue;const k=ee(x,s,v,r,oe);k.streamed&&(v=!0),k.result!=null&&(O=k.result),k.apiError&&(T=k.apiError),a&&x.type==="result"&&l.stdin.end()}}),l.stderr.on("data",p=>{N(),g+=p.toString()}),l.on("error",p=>{clearTimeout(C),w(),d(new Error(`Failed to start claude (${y}): ${p.message}`))}),l.on("close",p=>{if(clearTimeout(C),w(),o?.aborted){m({streamedAny:v,resultText:O});return}if(T&&ce(T))return d(new Error(z("Claude Code","claude")));if(p===0&&T)return d(new Error(`Claude Code reported an error: ${T}`));p===0?m({streamedAny:v,resultText:O}):d(new Error(ue("Claude Code",p,g,T||"",{agentId:"claude"})))}),a?l.stdin.write(`${JSON.stringify({type:"user",message:{role:"user",content:e}})}
|
|
4
|
+
`):(l.stdin.write(e),l.stdin.end())}).catch(d)})}function We(e){let t="";return typeof e=="string"?t=e:Array.isArray(e)&&(t=e.map(r=>typeof r=="string"?r:r?.text||"").filter(Boolean).join(`
|
|
5
5
|
`)),t.length>4e3?`${t.slice(0,4e3)}…`:t}function V(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
|
|
6
6
|
|
|
7
7
|
`}),e.boundary=!1)}function Z(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function ee(e,t,r,i="",s=null){const o={streamed:!1,result:null};if(e.type==="stream_event"){const n=e.event;n?.type==="content_block_delta"&&(n.delta?.type==="text_delta"?(o.streamed=!0,V(s,t),t({type:"delta",text:n.delta.text}),Z(s,n.delta.text)):n.delta?.type==="thinking_delta"&&t({type:"reasoning",text:n.delta.thinking||""}))}else if(e.type==="assistant"){if(e.is_api_error_message||e.error)return o.apiError=(e.message?.content||[]).filter(n=>n.type==="text").map(n=>n.text).join(`
|
|
8
|
-
`)||String(e.error||"api error"),o;for(const n of e.message?.content||[])n.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:n.name,phase:"start",callId:n.id,input:n.input,summary:
|
|
8
|
+
`)||String(e.error||"api error"),o;for(const n of e.message?.content||[])n.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:n.name,phase:"start",callId:n.id,input:n.input,summary:He(n,i)})):n.type==="text"&&!r&&(o.streamed=!0,V(s,t),t({type:"delta",text:n.text}),Z(s,n.text))}else if(e.type==="user")for(const n of e.message?.content||[])n.type==="tool_result"&&t({type:"tool",phase:"done",callId:n.tool_use_id,status:n.is_error?"error":"ok",result:We(n.content)});else if(e.type==="result"){e.is_error?o.apiError=o.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?o.result=e.result||"":t({type:"status",text:`(${e.subtype})`});const n=e.usage||e.message?.usage;if(n){const a=Number.isFinite(Number(e.total_cost_usd))?Number(e.total_cost_usd):null,u=Number(s?.costUsdBefore)||0;s&&a!=null&&(s.costUsdTotal=a),t({type:"usage",provider:"bridge",inputTokens:n.input_tokens||0,outputTokens:n.output_tokens||0,cacheReadTokens:n.cache_read_input_tokens||0,cacheWriteTokens:n.cache_creation_input_tokens||0,costUsd:a!=null?Math.max(0,a-u):null,costBasis:"list",...s?.harnessChars!=null?{harnessChars:s.harnessChars}:{}})}}return o}const te=process.env.CHATPANEL_CLAUDE_EFFORT??"low";let A=null;function re({probe:e=null}={}){return A||(A=(async()=>{try{return String(await(e?e():new Promise(t=>{const[r,i,s]=q(S(),["--help"],null),o=F(r,i,{...s,stdio:["ignore","pipe","pipe"]});let n="";o.stdout.on("data",a=>{n+=a}),o.on("error",()=>t("")),o.on("close",()=>t(n)),setTimeout(()=>{try{o.kill()}catch{}t(n)},8e3).unref?.()}))||"")}catch{return""}})(),A)}async function Re(e={}){return/--effort\b/.test(await re(e))}async function Ie(e={}){return/--append-system-prompt(?:-file\b|\[-file\])/.test(await re(e))}function ut(){A=null}async function De({system:e,options:t,tag:r}){const i=t.permissionMode||"default",s=B(t.workingDir),o=["--print","--output-format","stream-json","--include-partial-messages","--verbose"];te&&await Re()&&o.push("--effort",te),o.push(...ye({harness:"claude",roots:me(s),dirs:t.dirs}));const n=[],a=[],u=Le(t.mcp);if(u){const c=R.join(P.tmpdir(),`chatpanel-mcp-${r}.json`);await W(c,JSON.stringify(u.config)),n.push(c),o.push("--mcp-config",c),a.push(...u.allowedTools)}const f=Oe(t.reach);if(f){const c=Me(t.reach,await Te("claude").catch(()=>[]));o.push("--allowedTools",...f.allow,...a,...c.allow),o.push("--disallowedTools",...f.deny,...c.deny)}else i==="bypassPermissions"?o.push("--permission-mode","bypassPermissions"):i==="acceptEdits"?(o.push("--permission-mode","acceptEdits"),a.length&&o.push("--allowedTools",...a)):o.push("--allowedTools",...J,...a);const y=!f&&t.approvals===!0;if(y&&o.push("--permission-prompt-tool","stdio"),e)if(S()?.kind!=="wsl"&&await Ie()){const l=R.join(P.tmpdir(),`chatpanel-system-${r}.md`);await W(l,e,{mode:384}),n.push(l),o.push("--append-system-prompt-file",l)}else o.push("--append-system-prompt",e);t.model&&o.push("--model",t.model),t.useLocalConfig===!1&&o.push("--setting-sources","");const _=u&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(we(t.mcp?.specs))}:null,b=t.askDepth?{CHATPANEL_ASK_DEPTH:String(Math.max(0,Math.min(8,Number(t.askDepth)||0)))}:null,m=_||b||t.runEnv?{...t.runEnv||{},..._||{},...b||{}}:null;return{args:o,cwd:s,runEnv:m,cleanup:()=>n.forEach(c=>H(c).catch(()=>{})),hasMcp:!!u,approvals:y}}function ne({prompt:e="",system:t="",specs:r=null}={}){const i=Array.isArray(r)&&r.length?JSON.stringify(r).length:0;return String(e).length+String(t).length+i}function je(e,t=[],r=""){let i=U(e,r);return t.length&&(i+=`
|
|
9
9
|
|
|
10
|
-
The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}async function
|
|
10
|
+
The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}async function dt({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=await xe({messages:e,system:t,options:r,images:i},s,{signal:o}).catch(a=>({handled:!1,reason:a?.message||String(a),thrown:!0}));if(!n.handled&&!o?.aborted){if(n.thrown)throw new Error(n.reason);return Fe({messages:e,system:t,options:r,images:i},s,{signal:o})}}async function Fe({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=await De({system:t,options:r,tag:n}),{args:u,cwd:f,runEnv:y}=a,_=await Se(i,n),b=()=>{_.forEach(l=>H(l).catch(()=>{})),a.cleanup()},m=je(e,_);_e(u,r.extraArgs,be.claude,s);const d=a.approvals&&r.permissionSession?l=>ke(r.permissionSession,l):null,c=Q({prompt:m,args:u,cwd:f,env:y,emit:s,signal:o,harness:ne({prompt:m,system:t,specs:r.mcp?.specs}),host:a.approvals,ask:d});if(c===null)return b(),qe({messages:e,system:t,options:r},s,{signal:o});try{const{streamedAny:l,resultText:w}=await c;s({type:"done",text:l?"":w})}finally{b()}}async function pt({prompt:e,system:t,model:r}){const i=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",r||"haiku","--system-prompt",t||"Continue the user's text briefly. Reply with only the continuation."];let s="";const o=Q({prompt:e,args:i,cwd:null,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(o===null)return ze({prompt:e,system:t,model:r});const{resultText:n}=await o;return(s||n||"").trim()}function He(e,t=""){const r=e.input||{};return r.command?String(r.command).slice(0,60):r.file_path?ge(r.file_path,t):r.pattern?r.pattern:r.url?r.url:r.description?String(r.description).slice(0,80):r.query?String(r.query).slice(0,80):r.prompt?String(r.prompt).slice(0,80):""}let I=null;function D(){return I||(I=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),I}async function qe({messages:e,system:t,options:r},i,{signal:s}={}){const o=await D();if(!o)throw new Error(M);const{query:n}=o,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const u=r.permissionMode||"default",f=B(r.workingDir),y=u==="acceptEdits"||u==="bypassPermissions",_=new Set(J),b=async h=>_.has(h)||y?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${h} blocked — set this agent's permission mode in ChatPanel to enable it.`};let m=!1;const d=U(e),c={sawText:!1,tail:"",boundary:!1,harnessChars:ne({prompt:d,system:t})};let l="";const w=n({prompt:d,options:{cwd:f,permissionMode:u,includePartialMessages:!0,canUseTool:b,abortController:a,settingSources:r.useLocalConfig===!1?[]:["user","project"],systemPrompt:t?{type:"preset",preset:"claude_code",append:t}:{type:"preset",preset:"claude_code"},...r.model?{model:r.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const h of w){const g=ee(h,i,m,f,c);g.streamed&&(m=!0),g.result!=null&&(l=g.result)}}catch(h){if(s?.aborted||a.signal.aborted)return;throw h}i({type:"done",text:m?"":l})}async function ze({prompt:e,system:t,model:r}){const i=await D();if(!i)throw new Error(M);const{query:s}=i;let o="";const n=s({prompt:e,options:{cwd:P.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:t||"Continue the user's text briefly. Reply with only the continuation.",model:r||"haiku"}});for await(const a of n)if(a.type==="assistant")for(const u of a.message.content)u.type==="text"&&(o+=u.text);else a.type==="result"&&a.subtype==="success"&&!o&&(o=a.result||"");return o.trim()}export{ut as _resetEffortProbe,$e as answerControlRequest,lt as available,De as buildClaudeLaunch,Me as channelMcpTools,Oe as channelToolPolicy,dt as chat,Fe as chatCold,Le as claudeMcpConfig,je as claudePrompt,Re as claudeSupportsEffort,Ie as claudeSupportsSystemPromptFile,pt as complete,ee as handleMessage,ne as harnessChars,ct as listModels,Se as writeImages};
|
package/src/engines/codex.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{spawn as B}from"node:child_process";import{killOnAbort as H,spawnGroupOpts as F}from"../proc.js";import{track as L,sandbox as X,noteSandbox as J}from"../sandbox.js";import{readFile as
|
|
2
|
-
`))>=0;){const v=y.slice(0,h).trim();if(y=y.slice(h+1),!!v.startsWith("{"))try{
|
|
1
|
+
import{spawn as B}from"node:child_process";import{killOnAbort as H,spawnGroupOpts as F}from"../proc.js";import{track as L,sandbox as X,noteSandbox as J,grantedWriteRoots as R}from"../sandbox.js";import{harnessDirArgs as W}from"../events/harness-cards.js";import{readFile as q,unlink as M,writeFile as z}from"node:fs/promises";import{existsSync as N,mkdirSync as G,symlinkSync as K,readFileSync as O}from"node:fs";import S from"node:os";import m from"node:path";import{agentAvailable as U,selfMcpStdio as Z,resolveCommand as Q}from"../env.js";import{relayTimeoutMax as V}from"../relay-timeout.js";import{buildCliPrompt as Y}from"./prompt.js";import{pushExtraArgs as ee,FORBIDDEN as te}from"./args.js";import{resolveWorkdir as re}from"../workdir.js";import{summarizeCliError as oe}from"../cli-errors.js";import{signInStatus as se,signInMessage as ne}from"../sign-in.js";import{disabledMcpServers as ae,planMcpRetry as ce,quarantine as ie}from"../mcp-quarantine.js";import{chatWarm as le}from"./codex-appserver.js";const j=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,D=process.env.CHATPANEL_CODEX_EFFORT??"low",de=["gpt-5-codex","gpt-5","o3","o4-mini"];let C=!1;function He(){C=!1}async function Fe(){const s=new Set;try{const o=process.env.CODEX_HOME||m.join(S.homedir(),".codex"),t=O(m.join(o,"config.toml"),"utf8");for(const a of t.matchAll(/(?:^|\n)\s*model\s*=\s*["']([^"'\n]+)["']/g))s.add(a[1].trim())}catch{}for(const o of de)s.add(o);return[...s]}const I=m.join(S.homedir(),".chatpanel","codex-home");let T=!1;function pe(){if(!T)try{G(I,{recursive:!0});const s=m.join(S.homedir(),".codex","auth.json"),o=m.join(I,"auth.json");if(N(s)&&!N(o))try{K(s,o)}catch{}T=!0}catch{return null}return I}let A=!1,P=0;async function Le(){if(Date.now()-P>(A?3e4:4e3)){P=Date.now();try{A=U("codex")}catch{A=!1}}return A?await se("codex",Q("codex")).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:ne("Codex","codex")}:{ok:!0}:{ok:!1,reason:"codex not found on PATH. Install it and run `codex login`."}}function ue(s){if(!s?.url)return[];const o=s.serverName||"chatpanel_browser",{command:t,args:a}=Z(s.url),e=["-c",`mcp_servers.${o}.command=${JSON.stringify(t)}`,"-c",`mcp_servers.${o}.args=${JSON.stringify(a)}`,"-c",`mcp_servers.${o}.default_tools_approval_mode="approve"`,"-c",`mcp_servers.${o}.startup_timeout_sec=30`,"-c",`mcp_servers.${o}.tool_timeout_sec=${Math.ceil(V(s.specs)/1e3)}`],n=[...new Set((s.specs||[]).map(i=>i?.name).filter(Boolean))];return n.length&&e.push("-c",`mcp_servers.${o}.enabled_tools=${JSON.stringify(n)}`),e}function fe(s){try{const o=O(m.join(s,"config.toml"),"utf8"),t=new Set;for(const a of o.matchAll(/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*[.\]]/gm))t.add(a[1]);return t}catch{return new Set}}function me(s){const o=new Set;try{const t=O(m.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]||"",i=/^\s*command\s*=\s*"([^"]*)"/m.exec(n)?.[1]||"",r=/^\s*url\s*=\s*"([^"]*)"/m.exec(n)?.[1]||"";(/chatpanel-(gateway|bridge)(\.js|\.cmd|\.exe)?$/.test(i)||/^https?:\/\/(127\.0\.0\.1|localhost):43(19|20)\//.test(r))&&o.add(e[1])}}catch{}return o}function he(s=[]){return s.flatMap(o=>["-c",`mcp_servers.${o}.enabled=false`])}async function ge(s,o){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",i=m.join(S.tmpdir(),`chatpanel-codex-img-${o}-${a}.${n}`);await z(i,Buffer.from(e[2],"base64")),t.push(i)}return t}async function ye({args:s,cwd:o,env:t,prompt:a,outFile:e,emit:n,signal:i}){const r=await X().wrap("codex",s,{cwd:o,stdio:["pipe","pipe","pipe"],env:t,...F},{engine:"codex",cwd:o});return J(n,r.record),new Promise((c,f)=>{let l;try{l=L(B(r.bin,r.argv,r.opts),r,{kind:"agent"})}catch(u){return f(new Error(`Failed to start codex: ${u.message}`))}const g=H(l,i);let y="",b="",w=!1;const k=u=>{u?.type!=="status"&&(w=!0),n(u)},_={started:new Set,reasoned:new Set,n:0};let x;const $=()=>{clearTimeout(x),x=setTimeout(()=>{l.kill("SIGKILL"),f(new Error(`Codex timed out — no output for ${Math.round(j/1e3)}s.`))},j)};$(),l.stdout.on("data",u=>{$(),y+=u.toString();let h;for(;(h=y.indexOf(`
|
|
2
|
+
`))>=0;){const v=y.slice(0,h).trim();if(y=y.slice(h+1),!!v.startsWith("{"))try{we(JSON.parse(v),k,_)}catch{}}}),l.stderr.on("data",u=>{$(),b+=u.toString()}),l.on("error",u=>{clearTimeout(x),g(),f(u)}),l.on("close",async u=>{clearTimeout(x),g();let h="";try{h=(await q(e,"utf8")).trim()}catch{}M(e).catch(()=>{}),c({code:u,stderr:b,text:h,streamed:w,said:!!_.saidAny,policyBlocked:!!_.policyBlocked})}),l.stdin.write(a),l.stdin.end()})}async function Xe({messages:s,system:o,options:t,images:a},e,{signal:n}={}){const i=await le({messages:s,system:o,options:t,images:a},e,{signal:n}).catch(r=>({handled:!1,reason:r?.message||String(r),thrown:!0}));if(!i.handled&&!n?.aborted){if(i.thrown)throw new Error(i.reason);return xe({messages:s,system:o,options:t,images:a},e,{signal:n})}}async function xe({messages:s,system:o,options:t,images:a},e,{signal:n}={}){const i=`${Date.now()}-${Math.random().toString(36).slice(2)}`,r=m.join(S.tmpdir(),`chatpanel-codex-${i}.txt`),c=await ge(a,i),f=()=>c.forEach(p=>M(p).catch(()=>{})),l=re(t.workingDir),g=[];ee(g,t.extraArgs,te.codex,e);const y=p=>{const d=["exec","--json","--skip-git-repo-check","-o",r];if(t.permissionMode==="bypassPermissions")d.push("--dangerously-bypass-approvals-and-sandbox");else{const E=t.permissionMode==="acceptEdits"?"workspace-write":"read-only";d.push("-s",E),d.push(...W({harness:"codex",roots:R(l),dirs:t.dirs})),C||d.push("-c","approval_policy=never")}D&&d.push("-c",`model_reasoning_effort=${D}`),d.push("-c","model_reasoning_summary=auto"),d.push(...ue(t.mcp)),d.push(...he(p)),t.model&&d.push("-m",t.model),d.push(...g);for(const E of c)d.push("-i",E);return d.push("-"),d},b=t.useLocalConfig!==!1,w={...process.env,...t.runEnv||{}};if(!b){const p=pe();p&&(w.CODEX_HOME=p)}const k=t.mcp?.serverName||"chatpanel_browser",_=w.CODEX_HOME||process.env.CODEX_HOME||m.join(S.homedir(),".codex"),x=fe(_),$=(t.mcp?.specs||[]).length>0;let u=[...new Set([...ae("codex",t,[k]),...$?me(_):[]])].filter(p=>x.has(p));const h=Y(s,o),v=()=>ye({args:y(u),cwd:l,env:w,prompt:h,outFile:r,emit:e,signal:n});try{let p=await v();if(p.policyBlocked&&(C=!0),!n?.aborted&&p.code!==0&&!p.streamed){const d=ce({agent:"codex",text:p.stderr,protect:[k],already:u});d&&x.has(d.server)&&(ie("codex",d.server),e({type:"status",text:`MCP server "${d.server}" failed to load — ${d.short}. Skipping it and retrying.`}),u=[...u,d.server],p=await v())}if(n?.aborted)return;if(p.code!==0)throw new Error(oe("Codex",p.code,p.stderr,"",{agentId:"codex"}));p.said||e({type:"delta",text:p.text||"(no output)"}),e({type:"done",text:""})}finally{f()}}function we(s,o,t={started:new Set,reasoned:new Set,n:0}){const a=s.type||"",e=s.item||{},n=e.type||"",i=a==="item.completed"||e.status==="completed"||e.status==="failed";if(n==="agent_message"&&i){const r=e.id||`msg_${t.n++}`,c=String(e.text||"");c&&!t.said?.has(r)&&((t.said||=new Set).add(r),o({type:"delta",text:`${t.saidAny?`
|
|
3
3
|
|
|
4
|
-
`:""}${c}`}),t.saidAny=!0);return}if(
|
|
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 r=e.id||`cmd_${t.n++}`;if(t.started.has(r)||(t.started.add(r),o({type:"tool",name:"shell",phase:"start",callId:r,input:{command:e.command||""}})),i){const c=e.exit_code===0||e.exit_code==null;o({type:"tool",name:"shell",phase:"done",callId:r,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 r=e.id||`edit_${t.n++}`,c=Array.isArray(e.changes)?e.changes.map(f=>f.path||f.file).filter(Boolean):[];t.started.has(r)||(t.started.add(r),o({type:"tool",name:"edit",phase:"start",callId:r,input:{files:c}})),i&&o({type:"tool",name:"edit",phase:"done",callId:r,status:"ok"});return}if(n==="web_search"){const r=e.id||`ws_${t.n++}`,c=e.action&&typeof e.action=="object"?e.action:{},f=e.query||c.query||"",l=c.url||"";t.started.has(r)||(t.started.add(r),o({type:"tool",name:"web_search",phase:"start",callId:r,input:{query:f,...l?{url:l}:{}}})),(i||a==="item.completed")&&o({type:"tool",name:"web_search",phase:"done",callId:r,status:"ok",result:l?`Opened ${l}`:f?`Searched the web for ${f}`:"Searched the web"});return}if(n==="mcp_tool_call"){const r=e.id||`mcp_${t.n++}`,c=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(t.started.has(r)||(t.started.add(r),o({type:"tool",name:c,phase:"start",callId:r,input:e.arguments&&typeof e.arguments=="object"?e.arguments:{}})),i){const f=e.status==="failed"||e.error!=null,l=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error,g=e.result==null?"":typeof e.result=="string"?e.result:JSON.stringify(e.result);o({type:"tool",name:c,phase:"done",callId:r,status:f?`error: ${String(l||"failed").slice(0,80)}`:"ok",result:String(f?l||"":g).slice(0,4e3)})}return}if(n==="todo_list"&&Array.isArray(e.items)&&e.items.length){const r=e.items.map(c=>`${c.completed?"☑":"☐"} ${c.text||""}`).join(`
|
|
5
|
+
`);t.lastTodo!==r&&(t.lastTodo=r,o({type:"status",text:`Plan:
|
|
6
|
+
${r}`}));return}if(n==="error"||a==="error"){const r=String(e.message||s.message||"");if(!r)return;if(/approval_policy.*(disallowed|not in the allowed set)/i.test(r)){t.policyBlocked=!0,t.policyNoted||(t.policyNoted=!0,o({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}o({type:"status",text:`Codex: ${r.slice(0,300)}`});return}if(n==="reasoning"||!n&&a.includes("reasoning")){const r=e.id||`r_${t.n++}`,c=e.text||e.summary||"";c&&!t.reasoned.has(r)&&(t.reasoned.add(r),o({type:"reasoning",text:`${c}
|
|
7
|
+
`}));return}(a==="turn.started"||a==="thread.started")&&o({type:"status",text:"Codex working"})}export{Le as available,Xe as chat,xe as chatCold,he as codexDisableArgs,ue as codexMcpConfigArgs,fe as configuredMcpServers,pe as ensureIsolatedHome,we as forwardEvent,Fe as listModels,me as redundantChatpanelServers,He as resetApprovalPolicy,ge as writeImages};
|
package/src/engines/custom.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{spawn as v}from"node:child_process";import{readFile as Q,writeFile as k,unlink as Y}from"node:fs/promises";import T from"node:os";import
|
|
2
|
-
`)){const o=
|
|
1
|
+
import{spawn as v}from"node:child_process";import{readFile as Q,writeFile as k,unlink as Y}from"node:fs/promises";import T from"node:os";import x from"node:path";import{resolveCommand as L,buildSpawnSpec as _,selfMcpStdio as tt}from"../env.js";import{missingCommandMessage as U}from"../events/mcp-errors.js";import{sandbox as I,noteSandbox as et,track as F,grantedWriteRoots as rt}from"../sandbox.js";import{harnessDirArgs as nt}from"../events/harness-cards.js";import{isProEntitled as D}from"../entitlement.js";import{killOnAbort as ot}from"../proc.js";import{buildCliPrompt as it,fitCliPrompt as st,argvPromptBudget as at}from"./prompt.js";import{pushExtraArgs as lt,FORBIDDEN as H}from"./args.js";import{createStreamParser as ct,STREAM_FORMATS as mt}from"./stream-formats.js";import{resolveWorkdir as ut}from"../workdir.js";async function pt(t,n){const e=[];for(let r=0;r<(t?.length||0);r++){const o=/^data:([^;]+);base64,(.+)$/s.exec(t[r]?.dataUrl||"");if(!o)continue;const s=(o[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",d=x.join(T.tmpdir(),`chatpanel-custom-img-${n}-${r}.${s}`);await k(d,Buffer.from(o[2],"base64")),e.push(d)}return e}function dt(t,n){const e=String(t||"").trim();if(!e||!n.length)return[];const r=[];for(const o of n)r.push(...e.includes("{path}")?e.replaceAll("{path}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]);return r}const J=Number(process.env.CHATPANEL_CUSTOM_TIMEOUT_MS)||18e4,ft="http://127.0.0.1:4319/mcp",j="http://127.0.0.1:4319/mcp";async function qt(){return{ok:!0}}function gt(t){const n=[],e=new Set;for(const r of String(t||"").split(`
|
|
2
|
+
`)){const o=r.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(o)&&!/^(name|model|models|id|provider|available|usage|options|commands)$/i.test(o)&&!e.has(o)&&(e.add(o),n.push(o),n.length>=200))break}return n}async function Vt(t={}){if(!await D(t.entitlement))throw new Error("Custom agents require ChatPanel Pro.");const n=t.custom||{};return ht(n.command,n.listModelsArgs,t.workingDir)}async function ht(t,n,e){const r=String(n||"").trim();if(!t||!r)return[];const o=await wt(t,r.split(/\s+/).filter(Boolean),e);return gt(o)}async function wt(t,n,e,r=2e4){if(!t)return"";const o=L(t);if(!o)throw new Error(U(t,{platform:process.platform}));const s=e?x.resolve(e):null,[d,f,g]=_(o,n,s);g.env={...g.env||process.env,NO_COLOR:"1",CLICOLOR:"0"};const y=await I().wrap(d,f,g,{engine:"custom",cwd:s}),{bin:m,argv:$,opts:u}=y;return new Promise((i,h)=>{let S;try{S=F(v(m,$,u),y,{kind:"probe"})}catch(C){return h(new Error(`Failed to start ${t}: ${C.message}`))}let l="";const M=setTimeout(()=>{S.kill("SIGKILL"),h(new Error(`${t} timed out.`))},r);S.stdout.on("data",C=>l+=C.toString()),S.on("error",C=>{clearTimeout(M),h(new Error(`Failed to start ${t}: ${C.message}`))}),S.on("close",()=>{clearTimeout(M),i(l)});try{S.stdin.end()}catch{}})}function z(t){return(t?.specs||[]).filter(n=>n?.name)}function G(t,n){const e=String(t).replace(/[^A-Za-z0-9_$]/g,"_");return/^[A-Za-z_$]/.test(e)?e:`tool_${n}_${e}`}function St(t,n){return["--extension",t]}function yt(t,n){const e=String(t||"").trim(),r=z(n).map(s=>s.name).filter(Boolean);if(!e||!r.length)return[];const o=r.join(",");return e.includes("{tools}")?e.replaceAll("{tools}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]}function Ct(t={},n){return t.trustAllToolsForMcp?[t.trustAllToolsArg||"--trust-all-tools"]:t.trustToolsArg?yt(t.trustToolsArg,n):[]}function $t(t={}){return t.stableMcpSetupCommand?t.stableMcpSetupCommand:`opencode mcp add chatpanel --url ${j}`}function bt(t={}){const n=typeof t.stableMcpSetupArgs=="function"?t.stableMcpSetupArgs():t.stableMcpSetupArgs,e=Array.isArray(n)?n.filter(r=>r!=null).map(String):null;return e?.length?{command:t.stableMcpSetupCommandName||t.command,args:e}:null}function At(t){const n=z(t),e=n.map((o,s)=>{const d=G(o.name,s),f=o.parameters||{type:"object",properties:{}};return`const ${d}Tool = {
|
|
3
3
|
name: ${JSON.stringify(o.name)},
|
|
4
4
|
label: ${JSON.stringify(o.name)},
|
|
5
5
|
description: ${JSON.stringify(o.description||o.name)},
|
|
@@ -9,7 +9,7 @@ import{spawn as v}from"node:child_process";import{readFile as Q,writeFile as k,u
|
|
|
9
9
|
},
|
|
10
10
|
};`}).join(`
|
|
11
11
|
|
|
12
|
-
`),n
|
|
12
|
+
`),r=n.map((o,s)=>` pi.registerTool(${G(o.name,s)}Tool);`).join(`
|
|
13
13
|
`);return`import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
14
14
|
|
|
15
15
|
const MCP_URL = ${JSON.stringify(t.url)};
|
|
@@ -63,9 +63,9 @@ async function callMcpTool(toolName, toolCallId, params, signal) {
|
|
|
63
63
|
${e}
|
|
64
64
|
|
|
65
65
|
export default function (pi: ExtensionAPI) {
|
|
66
|
-
${
|
|
66
|
+
${r}
|
|
67
67
|
}
|
|
68
|
-
`}async function
|
|
68
|
+
`}async function xt(t,n){const e=x.join(T.tmpdir(),`chatpanel-pi-tools-${n}.ts`);return await k(e,At(t)),e}async function Mt(){const t=process.env.XDG_CONFIG_HOME||x.join(T.homedir(),".config"),n=[x.join(t,"opencode","opencode.jsonc"),x.join(T.homedir(),"Library","Application Support","opencode","opencode.jsonc")];for(const e of n)try{if((await Q(e,"utf8")).includes(ft))return!0}catch{}return!1}async function K(t,n,e){const r=L(t);if(!r)return"";const[o,s,d]=_(r,n,e||null),f=await I().wrap(o,s,d,{engine:"custom",cwd:e||null}),{bin:g,argv:y,opts:m}=f;return new Promise($=>{const u=F(v(g,y,m),f,{kind:"probe"});let i="",h="";const S=setTimeout(()=>{u.kill("SIGKILL"),$(i+h)},4e3);u.stdout.on("data",l=>i+=l.toString()),u.stderr.on("data",l=>h+=l.toString()),u.on("error",()=>{clearTimeout(S),$(i+h)}),u.on("close",()=>{clearTimeout(S),$(i+h)});try{u.stdin.end()}catch{}})}async function Tt(t,n){for(const e of["workspace","global","default"]){const r=await K(t,["mcp","list",e],n);if(r.includes(j)||/chatpanel_browser/i.test(r))return!0}return!1}async function Et(t,n){const e=await K(t,["mcp","list"],n);return e.includes(j)||/chatpanel_browser/i.test(e)}async function Ot(t,n){return t.stableMcpConfigCheck==="kiro"?Tt(t.command||"kiro-cli",n):t.stableMcpConfigCheck==="opencode"?Mt():t.stableMcpConfigCheck==="hermes"?Et(t.command||"hermes",n):!1}async function Pt(t,n){const e=L(t.command);if(!e)throw new Error(`Couldn't find "${t.command}" to set up browser tools.`);const[r,o,s]=_(e,t.args,n||null);s.env={...s.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"};const d=await I().wrap(r,o,s,{engine:"custom",cwd:n||null}),{bin:f,argv:g,opts:y}=d;await new Promise((m,$)=>{let u;try{u=F(v(f,g,y),d,{kind:"probe"})}catch(l){return $(new Error(`Failed to start ${t.command}: ${l.message}`))}let i="",h="";const S=setTimeout(()=>{u.kill("SIGKILL"),$(new Error(`${t.command} MCP setup timed out.`))},2e4);u.stderr.on("data",l=>i+=l.toString()),u.stdout?.on("data",l=>h+=l.toString()),u.on("error",l=>{clearTimeout(S),$(new Error(`Failed to start ${t.command}: ${l.message}`))}),u.on("close",l=>{if(clearTimeout(S),l===0)return m(`${h}
|
|
69
69
|
${i}`.trim());$(new Error(`${t.command} MCP setup exited ${l}: ${i.trim().split(`
|
|
70
|
-
`).pop()||"failed"}`))});try{u.stdin.end()}catch{}})}function
|
|
71
|
-
`).filter(Boolean).slice(-3).join(" ")}`:"")+` Run: ${f}`)}async function
|
|
70
|
+
`).pop()||"failed"}`))});try{u.stdin.end()}catch{}})}function vt(t,n){const e=String(n?.message||n||"");return/mcp['" ]* Python SDK|No module named ['"]?mcp|MCP support/i.test(e)?`${t} has no MCP support installed. Run \`hermes setup\` (or install the \`mcp\` package in its environment), then retry.`:/streamable_http|HTTP transport/i.test(e)?`${t}'s MCP client has no HTTP transport; ChatPanel registers a stdio server instead. Upgrade its \`mcp\` package if this persists.`:e.slice(0,200)||"the CLI could not register the tools"}async function kt(t,n,e,r,o={}){if(!t.requiresStableMcp)return!0;const s=o.hasConfig||Ot,d=o.runSetup||Pt;if(await s(t,n))return!0;const f=$t(t);if(!t.autoSetupStableMcp){const m=`${e} needs one-time browser-tool setup: ${f}`;throw r({type:"status",text:m}),new Error(m)}const g=bt(t);if(!g?.command){const m=`${e} needs one-time browser-tool setup: ${f}`;throw r({type:"status",text:m}),new Error(m)}r({type:"status",text:`${e} is setting up one-time browser tools...`});const y=String(await d(g,n)||"").trim();if(await s(t,n))return!0;throw new Error(`${e} browser-tool setup did not register the server.`+(y?` ${y.split(`
|
|
71
|
+
`).filter(Boolean).slice(-3).join(" ")}`:"")+` Run: ${f}`)}async function Wt({messages:t,system:n,options:e,images:r},o,{signal:s}={}){if(!await D(e.entitlement))throw new Error("Custom agents require ChatPanel Pro. Upgrade in Settings to bring your own CLI agent.");return Lt(e.custom||{},{messages:t,system:n,options:e,images:r},o,{signal:s})}async function Lt(t,{messages:n,system:e,options:r={},images:o},s,{signal:d}={}){if(!t.command)throw new Error("This agent has no command configured.");const f=L(t.command);if(!f)throw new Error(U(t.command,{platform:process.platform}));let g=it(n,e),y=ut(r.workingDir);const m=t.label||t.command,$=Object.hasOwn(mt,t.format)?t.format:"text",u=t.promptVia==="arg"?"arg":"stdin";let i=Array.isArray(t.args)?t.args.slice():t.args?String(t.args).split(/\s+/).filter(Boolean):[];if(lt(i,r.extraArgs,H[t.forbidden]||H.custom,s),r.model&&t.modelArg){const a=String(t.modelArg),c=a.includes("{model}")?a.replaceAll("{model}",r.model).split(/\s+/).filter(Boolean):[...a.split(/\s+/).filter(Boolean),r.model];i=[...i,...c]}if(t.permissionArgs){const a=String(r.permissionMode||"default"),c=t.permissionArgs[a]||t.permissionArgs.default||[];i=[...i,...c.map(String)]}i=[...i,...nt({harness:t.dirsHarness||t.command,roots:rt(y),dirs:t.dirs!==void 0?t.dirs:r.dirs})];const h=`${Date.now()}-${Math.random().toString(36).slice(2)}`,S=t.imageArg?await pt(o,h):[],l=[],M=()=>[...S,...l].forEach(a=>Y(a).catch(()=>{}));if(r.mcp?.url&&t.toolAdapter==="pi-extension"){const a=await xt(r.mcp,h);l.push(a),i=[...St(a,r.mcp),...i]}else if(r.mcp?.url&&t.mcpArg){const a=r.mcp.serverName||"chatpanel_browser",{command:c,args:p}=tt(r.mcp.url),w=x.join(T.tmpdir(),`chatpanel-mcp-${h}.json`);await k(w,JSON.stringify({mcpServers:{[a]:{command:c,args:p}}})),l.push(w);const b=String(t.mcpArg);i=[...b.includes("{file}")?b.replaceAll("{file}",w).split(/\s+/).filter(Boolean):[...b.split(/\s+/).filter(Boolean),w],...i]}if(r.mcp?.url)try{await kt(t,y,m,s)}catch(a){s({type:"status",text:`${m}: continuing without ChatPanel's browser tools — ${vt(m,a)}`}),r={...r,mcp:null}}if(r.mcp?.url&&i.push(...Ct(t,r.mcp)),r.model&&typeof t.modelPatch?.build=="function"){const a=/^[A-Za-z0-9][\w.:-]{0,79}$/.test(String(r.model))?String(r.model):"";if(a){const c=x.join(T.tmpdir(),`chatpanel-modelpatch-${h}.yml`);await k(c,t.modelPatch.build(a)),l.push(c);const p=String(t.modelPatch.arg||"--patch {file}");i=[...p.includes("{file}")?p.replaceAll("{file}",c).split(/\s+/).filter(Boolean):[...p.split(/\s+/).filter(Boolean),c],...i]}}const C=dt(t.imageArg,S);let N=!1;if(C.length&&(i=i.flatMap(a=>a==="{images}"?(N=!0,C):[a])),u==="arg"){const a=i.reduce((w,b)=>w+String(b).length+3,0)+C.reduce((w,b)=>w+String(b).length+3,0),c=st(n,e,at({viaCmdExe:f.kind==="cmd",otherArgsChars:a}));(c.dropped||c.prompt!==g)&&(g=c.prompt,s({type:"status",text:`${m} takes the prompt as a command-line argument, which this system caps — the oldest ${c.dropped||"part of the"} turn${c.dropped===1?"":"s"} of this conversation ${c.dropped?"were":"was"} left out to fit.`}));let p=!1;i=i.map(w=>w.includes("{prompt}")?(p=!0,w.replaceAll("{prompt}",g)):w),p||(C.length&&!N&&i.push(...C),i.push(g))}else C.length&&!N&&i.push(...C);const[Z,q,R]=_(f,i,y,r.runEnv||null);R.env={...R.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"};const E=await I().wrap(Z,q,R,{engine:"custom",cwd:y});et(s,E.record);const[V,W,X]=[E.bin,E.argv,E.opts];await new Promise((a,c)=>{let p;try{p=F(v(V,W,X),E,{kind:"agent"})}catch(A){return M(),c(new Error(`Failed to start ${m}: ${A.message}`))}const w=ot(p,d);let b="";const O=ct($,s);let P;const B=()=>{clearTimeout(P),P=setTimeout(()=>{p.kill("SIGKILL"),M(),c(new Error(`${m} timed out — no output for ${Math.round(J/1e3)}s.`))},J)};B(),p.stdout.on("data",A=>{B(),O.push(A.toString())}),p.stderr.on("data",A=>{B(),b+=A.toString()}),p.on("error",A=>{clearTimeout(P),w(),M(),c(new Error(`Failed to start ${m}: ${A.message}`))}),p.on("close",A=>{if(clearTimeout(P),w(),M(),d?.aborted){a();return}A===0?(s({type:"done",text:O.streamed?"":O.finish()}),a()):c(new Error(summarizeCliError(m,A,b)))}),u==="stdin"&&p.stdin.write(g),p.stdin.end()})}export{j as CHATPANEL_STABLE_MCP_URL,qt as available,At as buildPiExtensionSource,Wt as chat,K as commandOutput,kt as ensureStableMcpConfig,Vt as listModels,ht as listSpecModels,vt as mcpSetupHint,Ct as mcpTrustArgs,St as piToolArgs,wt as runForStdout,Lt as runSpec,$t as stableMcpSetupCommand,bt as stableMcpSetupPlan,yt as trustToolArgs};
|
|
@@ -0,0 +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 +1 @@
|
|
|
1
|
-
import{EventError as b}from"./event.js";import{normalizeGrant as A}from"./sandbox-grant.js";const y=Object.freeze(["none","process","container","kubernetes"]),E=Object.freeze(["open","allowlist","none","gateway"]),h=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),x=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),_=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:[]})}),R=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"]),p=e=>!!e&&typeof e=="object"&&!Array.isArray(e),g=e=>Array.isArray(e)&&e.every(o=>typeof o=="string"&&o.length>0),l=(e,o)=>{if(!e)throw new b("SHAPE",o)},f=e=>[...new Set(e)];function O(e){l(p(e),"kit: must be an object"),l(typeof e.id=="string"&&e.id.length>0,"kit: id required"),l(p(e.network)&&E.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${E.join(", ")}`),l(g(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),l(g(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),l(p(e.filesystem),`kit ${e.id}: filesystem required`);for(const o of["allowWrite","denyWrite","allowRead","denyRead"])l(g(e.filesystem[o]||[]),`kit ${e.id}: filesystem.${o} must be string[]`);return l(g(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),e.image!=null&&l(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&l(Array.isArray(e.credentials)&&e.credentials.every(o=>p(o)&&typeof o.name=="string"&&typeof o.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:f(e.network.allowedDomains||[]),deniedDomains:f(e.network.deniedDomains||[])},filesystem:{allowWrite:f(e.filesystem.allowWrite),denyWrite:f(e.filesystem.denyWrite||[]),allowRead:f(e.filesystem.allowRead||[]),denyRead:f(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:p(e.limits)?{...e.limits}:{}}}import{normalizeGrant as M,mergeGrants as k,parseHostList as q}from"./sandbox-grant.js";function z({engine:e="custom",cwd:o,mode:t="open",extraHosts:r=[],extraWrite:n=[],extraDenyRead:s=[],grant:c=null}={}){const d=_[e]||_.custom;l(typeof o=="string"&&o.length>0,"kit: cwd required");const a=A(c);return O({id:`${e}:${t}`,kind:"process",network:{mode:t,allowedDomains:t==="open"?["*"]:t==="none"?[]:f([...d.hosts,...R,...r,...a.hosts]),deniedDomains:[]},filesystem:{allowWrite:f([o,...x,...d.write,...n,...a.write.filter(i=>!h.some(u=>i===u||i.startsWith(`${u}/`)))]),denyWrite:[],allowRead:[o],denyRead:f([...h,...s])}})}function N(e,{loopback:o=[],home:t="",platform:r="darwin"}={}){const n=O(e),s=d=>t&&d.startsWith("~")?t+d.slice(1):d,c=n.network.mode==="none"?[]:o.map(d=>`127.0.0.1:${d}`);return{network:{allowedDomains:f([...n.network.allowedDomains,...c]),deniedDomains:n.network.deniedDomains,allowLocalBinding:r==="darwin"&&c.length>0},filesystem:{denyRead:n.filesystem.denyRead.map(s),allowRead:n.filesystem.allowRead.map(s),allowWrite:n.filesystem.allowWrite.map(s),denyWrite:n.filesystem.denyWrite.map(s)}}}function C({layer:e="none",runtime:o=null,kitId:t=null,mode:r=null,reason:n=null,hosts:s=null}={}){return l(y.includes(e),`sandbox record: layer must be one of ${y.join(", ")}`),{layer:e,runtime:o,kit:t,mode:r,...e==="none"&&n?{reason:n}:{},...Array.isArray(s)&&s.length?{hosts:f(s)}:{}}}function S(e,{platform:o="darwin"}={}){const t=String(e);if(o==="win32"){l(!/[\r\n]/.test(t),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=t;if(t===""||/[ \t\v"]/.test(t)){r='"';for(let n=0;n<t.length;n++){let s=0;for(;n<t.length&&t[n]==="\\";)s++,n++;if(n===t.length){r+="\\".repeat(s*2);break}t[n]==='"'?r+="\\".repeat(s*2+1)+'"':r+="\\".repeat(s)+t[n]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return t===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}const I=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function H(e={},{platform:o="darwin",caBundle:t=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(t)for(const n of I)e[n]||(r[n]=t);if(o==="linux")for(const n of["no_proxy","NO_PROXY"])typeof e[n]=="string"&&(r[n]=e[n].split(",").map(s=>s.trim()).filter(s=>s&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(s)).join(","));return r}function L(e,o=[],{platform:t="darwin"}={}){return[e,...o].map(r=>S(r,{platform:t})).join(" ")}const T=/[\\/]+/,m=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),D=e=>/^[a-z]:$/i.test(m(e))||m(e)==="";function w(e,o){const t=m(e),r=m(o);return!!r&&t!==r&&t.startsWith(r+"\\")}function j(e){const o=String(e||"").replace(/\//g,"\\").split("\\");if(o.length<2)return"";const t=o.findIndex(r=>r.toLowerCase()==="node_modules");return(t>0?o.slice(0,t):o.slice(0,-1)).join("\\")}function K({kit:e,files:o=[],home:t}){l(typeof t=="string"&&t.length>0,"windows grants: home required");const r=a=>(a.startsWith("~")?t+a.slice(1):a).replace(/\//g,"\\"),n=[];for(const a of e?.filesystem?.allowWrite||[]){const i=r(a);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(l(!D(i)&&m(i)!==m(t),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),w(i,t)&&n.push(i))}const s=(a,i)=>i.some(u=>m(a)===m(u)||w(a,u)),c=[];for(const a of o){const i=j(a);i&&w(i,t)&&c.push(i)}for(const a of e?.filesystem?.allowRead||[]){const i=r(a);w(i,t)&&c.push(i)}const d=f(c).filter(a=>!s(a,n));return{read:d.filter(a=>!d.some(i=>i!==a&&w(a,i))),write:f(n)}}const W=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 v({engine:e="custom",home:o,env:t={},base:r={},carry:n=W}={}){l(typeof o=="string"&&o.length>0,"windows env: home required");const s=o.replace(/\//g,"\\"),c=/^[a-z]:/i.test(s)?s.slice(0,2):"",d={USERPROFILE:s,...c?{HOMEDRIVE:c,HOMEPATH:s.slice(2)}:{}};for(const[a,i]of Object.entries(t))typeof i=="string"&&(r[a]!==i||n.includes(a))&&(d[a]=i);return e==="codex"&&!d.CODEX_HOME&&(d.CODEX_HOME=s+"\\.codex"),d}function Y(e,o){l(Array.isArray(e),"srt-win argv: must be an array");const t=e.indexOf("exec"),r=t>=0?e.indexOf("--",t+1):-1;l(t>=0&&r>t,"srt-win argv: expected `exec … -- <shell> <command>`");const n=new Set;for(let c=t+1;c<r;c++)e[c]==="--env"&&typeof e[c+1]=="string"&&n.add(e[c+1].split("=")[0].toUpperCase());const s=[];for(const[c,d]of Object.entries(o||{}))l(/^[A-Za-z_][A-Za-z0-9_]*$/.test(c),`srt-win env: bad key ${c}`),l(!/[\r\n]/.test(d),`srt-win env: ${c} holds a newline`),n.has(c.toUpperCase())||s.push("--env",`${c}=${d}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{x as COMMON_WRITE,R as DEVELOPER_HOSTS,_ as ENGINE_KITS,E as NETWORK_MODES,y as SANDBOX_LAYERS,h as SECRET_PATHS,W as WINDOWS_CARRY_KEYS,z as kitFor,k as mergeGrants,M as normalizeGrant,q as parseHostList,H as sandboxEnvOverlay,C as sandboxRecord,L as shellJoin,S as shellQuote,N as toSrtSettings,w as underWindowsHome,O as validateKit,K as windowsGrantsFor,j as windowsInstallRoot,v as windowsSandboxEnv,Y as withSrtWinEnv};
|
|
1
|
+
import{EventError as D}from"./event.js";import{normalizeGrant as O}from"./sandbox-grant.js";import{SECRET_DIR_NAMES as $,SECRET_DIR_PAIRS as j}from"./secret-names.js";const b=Object.freeze(["none","process","container","kubernetes"]),A=Object.freeze(["open","allowlist","none","gateway"]),_=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},R=(e,t)=>t&&(e==="~"||e.startsWith("~/")||e.startsWith("~\\"))?t+e.slice(1):e,y=e=>String(e||"").replace(/\\/g,"/"),x=(e,t)=>{const n=y(g(e)),r=y(g(t));return!!n&&!!r&&(n===r||n.startsWith(`${r}/`))},C=_.map(e=>y(g(e)).replace(/^~\//,"").split("/").filter(Boolean));function S(e,t=""){const n=y(g(R(g(e),t)));if(!n)return!1;for(const o of _)if(x(n,o)||t&&x(n,R(o,t)))return!0;const r=n.split("/").filter(Boolean).map(o=>o.toLowerCase());return C.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 P=Object.freeze([...[...$].map(e=>`~/**/${e}`),...j.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}`)]),v=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"]),I=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:[]})}),N=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"]),w=e=>!!e&&typeof e=="object"&&!Array.isArray(e),E=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0),f=(e,t)=>{if(!e)throw new D("SHAPE",t)},p=e=>[...new Set(e)];function W(e){f(w(e),"kit: must be an object"),f(typeof e.id=="string"&&e.id.length>0,"kit: id required"),f(w(e.network)&&A.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${A.join(", ")}`),f(E(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),f(E(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),f(w(e.filesystem),`kit ${e.id}: filesystem required`);for(const t of["allowWrite","denyWrite","allowRead","denyRead"])f(E(e.filesystem[t]||[]),`kit ${e.id}: filesystem.${t} must be string[]`);return f(E(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),e.image!=null&&f(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&f(Array.isArray(e.credentials)&&e.credentials.every(t=>w(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:p(e.network.allowedDomains||[]),deniedDomains:p(e.network.deniedDomains||[])},filesystem:{allowWrite:p(e.filesystem.allowWrite),denyWrite:p(e.filesystem.denyWrite||[]),allowRead:p(e.filesystem.allowRead||[]),denyRead:p(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:w(e.limits)?{...e.limits}:{}}}import{normalizeGrant as oe,mergeGrants as re,parseHostList as se}from"./sandbox-grant.js";function B({engine:e="custom",cwd:t,mode:n="open",extraHosts:r=[],extraWrite:o=[],extraDenyRead:i=[],grant:c=null,home:l="",reads:a="enumerated"}={}){const s=I[e]||I.custom;f(typeof t=="string"&&t.length>0,"kit: cwd required");const d=O(c);return W({id:`${e}:${n}`,kind:"process",network:{mode:n,allowedDomains:n==="open"?["*"]:n==="none"?[]:p([...s.hosts,...N,...r,...d.hosts]),deniedDomains:[]},filesystem:{allowWrite:p([t,...z,...s.write,...[...o,...d.write].filter(u=>!S(u,l))]),denyWrite:[],allowRead:a==="inverted"?p([t,...v,...s.write,...L({grant:d,extraWrite:o,cwd:t,home:l})]):[t],denyRead:p([...a==="inverted"?["~",...l?[l]:[]]:[],..._,...P,...i])}})}function L({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 d=String(s||"").trim();for(;d.length>1&&(d.endsWith("/")||d.endsWith("\\"));)d=d.slice(0,-1);return d},c=(s,d)=>s===d||s.startsWith(`${d}/`)||s.startsWith(`${d}\\`),l=i(o(n)),a=[];for(const s of[...O(e).write,...Array.isArray(t)?t:[]]){const d=i(o(i(s)));if(d&&!S(d,r)&&!(l&&c(d,l))&&!a.some(u=>c(d,u))){for(let u=a.length-1;u>=0;u--)c(a[u],d)&&a.splice(u,1);a.push(d)}}return a}function q(e,{loopback:t=[],home:n="",platform:r="darwin"}={}){const o=W(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:p([...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 X({layer:e="none",runtime:t=null,kitId:n=null,mode:r=null,reason:o=null,hosts:i=null}={}){return f(b.includes(e),`sandbox record: layer must be one of ${b.join(", ")}`),{layer:e,runtime:t,kit:n,mode:r,...e==="none"&&o?{reason:o}:{},...Array.isArray(i)&&i.length?{hosts:p(i)}:{}}}function T(e,{platform:t="darwin"}={}){const n=String(e);if(t==="win32"){f(!/[\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 H=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function F(e={},{platform:t="darwin",caBundle:n=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(n)for(const o of H)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 V(e,t=[],{platform:n="darwin"}={}){return[e,...t].map(r=>T(r,{platform:n})).join(" ")}const Q=/[\\/]+/,m=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),k=e=>/^[a-z]:$/i.test(m(e))||m(e)==="";function h(e,t){const n=m(e),r=m(t);return!!r&&n!==r&&n.startsWith(r+"\\")}function K(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 Z({kit:e,files:t=[],home:n}){f(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("\\\\")||(f(!k(s)&&m(s)!==m(n),`windows grants: a write on ${s} would hand the sandbox account the whole profile`),h(s,n)&&o.push(s))}const i=(a,s)=>s.some(d=>m(a)===m(d)||h(a,d)),c=[];for(const a of t){const s=K(a);s&&h(s,n)&&c.push(s)}for(const a of e?.filesystem?.allowRead||[]){const s=r(a);h(s,n)&&c.push(s)}const l=p(c).filter(a=>!i(a,o));return{read:l.filter(a=>!l.some(s=>s!==a&&h(a,s))),write:p(o)}}const Y=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 J({engine:e="custom",home:t,env:n={},base:r={},carry:o=Y}={}){f(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 ee(e,t){f(Array.isArray(e),"srt-win argv: must be an array");const n=e.indexOf("exec"),r=n>=0?e.indexOf("--",n+1):-1;f(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||{}))f(/^[A-Za-z_][A-Za-z0-9_]*$/.test(c),`srt-win env: bad key ${c}`),f(!/[\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{z as COMMON_WRITE,N as DEVELOPER_HOSTS,I as ENGINE_KITS,A as NETWORK_MODES,b as SANDBOX_LAYERS,_ as SECRET_PATHS,P as SECRET_READ_GLOBS,v as TOOLCHAIN_READ,Y as WINDOWS_CARRY_KEYS,S as isSecretWritePath,B as kitFor,re as mergeGrants,oe as normalizeGrant,se as parseHostList,F as sandboxEnvOverlay,X as sandboxRecord,V as shellJoin,T as shellQuote,q as toSrtSettings,h as underWindowsHome,W as validateKit,Z as windowsGrantsFor,K as windowsInstallRoot,J as windowsSandboxEnv,ee as withSrtWinEnv,L as writableRoots};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=new Set([".ssh",".aws",".gnupg",".gpg",".kube",".azure",".gcloud",".docker",".chatpanel",".password-store",".1password",".op","Keychains",".vault-token",".oci",".bluemix",".ibmcloud",".doctl",".linode",".scaleway",".hcloud",".civo",".terraform.d",".pulumi",".wrangler",".netlify",".vercel",".supabase",".heroku",".databricks",".snowflake",".kaggle",".circleci",".okta",".aliyun",".tencentcloud"]),s=[[".config","gh"],[".config","gcloud"],[".config","hub"],["Library","Keychains"],["Library","Cookies"],[".config","doctl"],[".config","fly"],[".config","openstack"],[".config","containers"],[".m2","settings.xml"],[".gradle","gradle.properties"],[".cargo","credentials.toml"],[".cargo","credentials"],[".gem","credentials"],[".composer","auth.json"],[".cache","huggingface"],[".ansible","vault_pass"],[".aws","sso"]],a=[/^\.env(\..+)?$/i,/^id_(rsa|dsa|ecdsa|ed25519)$/,/\.(pem|key|p12|pfx|jks|keystore|kdbx|ppk|gpg|pgp|asc|keychain|keychain-db)$/i,/^(credentials(\.json)?|\.netrc|_netrc|\.npmrc|\.pypirc|\.git-credentials|\.htpasswd|\.pgpass|\.my\.cnf|token\.json|\.vault-token)$/i,/^secrets?(\.(json|ya?ml|toml|env|txt))?$/i,/\.tfstate(\.backup)?$/i,/\.tfvars$/i,/^service[-_]?account.*\.json$/i,/^\.(bash|zsh|sh|python|node_repl|mysql|psql|irb|lesshst)_?history$/],o=/^\.env\.(example|sample|template|dist)$/i;export{e as SECRET_DIR_NAMES,s as SECRET_DIR_PAIRS,o as SECRET_FILE_ALLOW,a as SECRET_FILE_RES};
|
package/src/net.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export*from"./pii/net.js";
|
package/src/pii/net.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function f(n){const t=String(n).match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(!t)return null;const r=t.slice(1).map(Number);return r.some(e=>e>255)?null:r}function s(n){if(!n.includes(":"))return null;let t=n;const r=t.match(/^(.*:)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);if(r){const i=f(r[2]);if(!i)return null;t=`${r[1]}${((i[0]<<8|i[1])>>>0).toString(16)}:${((i[2]<<8|i[3])>>>0).toString(16)}`}const e=t.split("::");if(e.length>2)return null;const o=i=>(i?i.split(":"):[]).map(h=>/^[0-9a-f]{1,4}$/.test(h)?parseInt(h,16):NaN),u=o(e[0]),c=e.length===2?o(e[1]):[];if(u.concat(c).some(Number.isNaN))return null;const a=8-u.length-c.length;return(e.length===2?a<0:a!==0)?null:u.concat(new Array(e.length===2?a:0).fill(0),c)}function d(n){const t=s(n);return!t||t[0]||t[1]||t[2]||t[3]||t[4]||t[5]!==65535?n:[t[6]>>8,t[6]&255,t[7]>>8,t[7]&255].join(".")}const l=n=>d(String(n||"").trim().toLowerCase().replace(/^\[|\]$/g,""));function x(n){const t=l(n);if(!t)return!1;if(t==="localhost"||t.endsWith(".localhost"))return!0;const r=s(t);if(r)return r.slice(0,7).every(o=>o===0)&&r[7]===1;const e=f(t);return!!(e&&e[0]===127)}function m(n){const t=l(n);if(t==="metadata.google.internal"||t==="metadata")return!0;const r=s(t);if(r)return r[0]===64768&&r[1]===3778&&!r[2]&&!r[3]&&!r[4]&&!r[5]&&!r[6]&&r[7]===596;const e=f(t);return e?e[0]===169&&e[1]===254||e[0]===100&&e[1]===100&&e[2]===100&&e[3]===200:!1}function g(n){const t=l(n);if(!t||t.endsWith(".local"))return!0;const r=s(t);if(r)return!!(r.every(o=>o===0)||(r[0]&65024)===64512||(r[0]&65472)===65152||(r[0]&65472)===65216||r.slice(0,6).every(o=>o===0)||r[0]===100&&r[1]===65435);const e=f(t);if(e){const[o,u]=e;if(o===0||o===10||o===169&&u===254||o===172&&u>=16&&u<=31||o===192&&u===168||o===100&&u>=64&&u<=127)return!0}return!1}function w(n,{allowLoopback:t=!0,allowPrivate:r=!0}={}){const e=l(n);return!e||m(e)?!0:x(e)?!t:g(e)?!r:!1}function p(n,t={}){let r;try{r=new URL(n)}catch{throw new Error(`invalid URL: ${n}`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`only http(s) URLs allowed (got "${r.protocol}")`);if(w(r.hostname,t))throw new Error(`refusing to reach a blocked address (${r.hostname})`);return r}const b=(n,t={})=>p(n,{allowLoopback:!0,allowPrivate:!0,...t}),v=n=>p(n,{allowLoopback:!1,allowPrivate:!1});export{b as assertEndpointUrl,p as assertFetchableUrl,v as assertPublicWebUrl,w as isBlockedHost,x as isLoopbackHost,m as isMetadataHost,g as isPrivateHost};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{EventError as f}from"./events/event.js";const e=(n,t)=>{if(!n)throw new f("SHAPE",t)};function m({id:n,label:t,detect:o,wrap:s,violations:r,close:u}){return e(typeof n=="string"&&/^[a-z][a-z0-9-]*$/.test(n),"sandbox runtime: id must be a lowercase slug"),e(typeof t=="string"&&t.length>0,`sandbox runtime ${n}: label required`),e(typeof o=="function",`sandbox runtime ${n}: detect() required`),e(typeof s=="function",`sandbox runtime ${n}: wrap() required`),e(r==null||typeof r=="function",`sandbox runtime ${n}: violations must be a function`),e(u==null||typeof u=="function",`sandbox runtime ${n}: close must be a function`),Object.freeze({id:n,label:t,detect:o,wrap:s,violations:r||(()=>[]),close:u||(()=>{})})}const i=new Map;function b(n,t){return e(typeof n=="string"&&n.length>0,"sandbox runtime: id required"),e(typeof t=="function",`sandbox runtime ${n}: factory must be a function`),i.set(n,t),n}function a(){return[...i.keys()]}function x(n,t={}){const o=i.get(n);if(!o)throw new f("SHAPE",`sandbox runtime ${JSON.stringify(n)} is not registered — known: ${a().join(", ")||"none"}`);return o(t)}export{x as createSandboxRuntime,m as defineSandboxRuntime,b as registerSandboxRuntime,a as sandboxRuntimeIds};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawnSync as pe}from"node:child_process";import{writeFileSync as Y,mkdirSync as Z,existsSync as xe}from"node:fs";import{createHash as Se,randomBytes as ye}from"node:crypto";import{fileURLToPath as ge}from"node:url";import P from"node:os";import L from"node:path";import{toSrtSettings as ee,sandboxRecord as ve,shellJoin as te,sandboxEnvOverlay as k,windowsGrantsFor as We,windowsSandboxEnv as Ae,withSrtWinEnv as Ee,ENGINE_KITS as Oe,DEVELOPER_HOSTS as $e,SECRET_PATHS as De,COMMON_WRITE as Le}from"./events/sandbox-policy.js";import{defineSandboxRuntime as Re,registerSandboxRuntime as Te}from"./sandbox-runtime.js";function Ne(t=process.env.CHATPANEL_SRT_MODULE){if(!t)return"";try{const r=t.startsWith("file:")?ge(new URL("./cli.js",t)):L.join(L.dirname(t),"cli.js");return xe(r)?r:""}catch{return""}}const ne=new Set;function se(t,r=L.join(P.tmpdir(),"chatpanel-srt")){const S=JSON.stringify(t),p=L.join(r,`${Se("sha256").update(S).digest("hex").slice(0,16)}.json`);return ne.has(p)||(Z(r,{recursive:!0,mode:448}),Y(p,S,{mode:384}),ne.add(p)),p}function Ce(){try{const t=pe(process.platform==="win32"?"where":"which",["srt"],{encoding:"utf8",timeout:3e3});return t.status===0&&String(t.stdout||"").trim().length>0}catch{return!1}}const I="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)";function _e({config:t,platform:r=process.platform,home:S=P.homedir(),loopback:p=[],compiled:v=!1,selfFiles:re=[process.execPath,process.argv[1]||""],onExit:oe=H=>process.on("exit",H),hostEntry:U=null,reportUrl:V="",mintReportToken:ie=()=>"",onRefusal:ae=()=>{},parseRefusal:ce=()=>null,loadSrt:F=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:z=Ce,cliEntry:B=Ne(),hostEntryFor:J=()=>"",log:R=()=>{}}={}){const H=new Set;let c=null,u=null,o=null,j=null,T=null,y=null,W=null;const N=new Set;let X=!1;const de="Windows: the sandbox runs a process as a separate account, and mapping your sign-in, the CLI and its environment into it is built but not yet proved on a signed-in machine — CHATPANEL_SANDBOX_WINDOWS=1 turns it on (docs/sandboxing.md S1)",le="Windows: the sandbox account needs the runtime the gateway carries (the `srt` CLI cannot map your sign-in into it) — run the bridge through chatpanel-gateway";async function ue(){if(!t.windows){u=de;return}if(v){u=le;return}try{o=await F()}catch(e){u=`sandbox-runtime is not installed — it ships with the gateway (${e.message})`;return}if(!o?.SandboxManager?.wrapWithSandboxArgv||typeof o.grantWindowsAcl!="function"||typeof o.getWindowsSandboxUserStatusAsync!="function"){u="Windows: this sandbox-runtime is older than 0.0.77, which the account mapping needs";return}try{y=o.resolveSrtWin({path:o.VENDORED_SRT_WIN_EXE})}catch(e){u=`Windows: srt-win.exe is not beside sandbox-runtime (${e.message})`;return}let n;try{n=await o.getWindowsSandboxUserStatusAsync({srtWin:y})}catch(e){W=!1,u=`Windows: srt-win could not be asked whether the sandbox account exists (${e.message}) — ${I}`;return}if(W=!!(n?.provisioned&&n.sid),!W){u=`Windows: the sandbox account is not installed — ${I}`;return}T=n.sid,c="srt-lib"}async function he(){if(!(c||u)){if(!t.enabled){u="sandboxing is off (CHATPANEL_SANDBOX=off)";return}if(r==="win32")return ue();if(!v)try{if(o=await F(),o?.SandboxManager?.wrapWithSandboxArgv){c="srt-lib";return}}catch(n){R(`sandbox: library not available (${n.message})`)}if(z()){c="srt-cli";return}u=v?"srt is not on PATH — the compiled bridge cannot carry it: npm i -g @anthropic-ai/sandbox-runtime":"sandbox-runtime is not installed — it ships with the gateway; standalone: npm i -g @anthropic-ai/sandbox-runtime"}}let G=!1;function M(){return B&&!v?{bin:process.execPath,argv:[B]}:c==="srt-cli"||z()?{bin:"srt",argv:[]}:null}function we(){const n=Array.isArray(t.exactHosts)?t.exactHosts:t.mode==="open"?["*"]:t.mode==="none"?[]:[...new Set([...Object.values(Oe).flatMap(a=>a.hosts),...$e,...t.extraHosts])],e={id:`session:${t.mode}`,network:{mode:t.mode,allowedDomains:n},filesystem:{allowWrite:[P.tmpdir(),...Le,...t.extraWrite],denyRead:[...De,...t.extraDenyRead]}},s=ee(e,{loopback:p,home:r==="linux"?S:"",platform:r});return y?{...s,windows:{srtWin:{path:y.exe}}}:s}async function K(){return j||(j=o.SandboxManager.initialize(we()).then(()=>{try{o.SandboxManager.getSandboxViolationStore?.()?.subscribe?.(n=>{for(const e of n||[]){const s=ce(e?.line);if(!s||!e?.encodedCommand)continue;let a="";try{a=Buffer.from(e.encodedCommand,"base64").toString("utf8")}catch{continue}const i=`${a}|${s.host}|${e.timestamp instanceof Date?e.timestamp.getTime():String(e.timestamp)}`;H.has(i)||(H.add(i),ae({commandId:a,...s,at:e.timestamp instanceof Date?e.timestamp.getTime():Date.now()}))}})}catch(n){R(`sandbox: violations not subscribed (${n.message})`)}})),j}function fe(n){const e=L.join(P.tmpdir(),"chatpanel-srt");Z(e,{recursive:!0,mode:448});const s=L.join(e,`host-${ye(8).toString("hex")}.json`);return Y(s,JSON.stringify(n),{mode:384}),s}function be(n,e){const s=(h,f)=>o.expandWindowsFsPaths(h,{mode:f}).filter(d=>!N.has(`${f}:${d.toLowerCase()}`)),a=s(n,"grant"),i=s(e,"grant");if(!(!a.length&&!i.length)){o.grantWindowsAcl({sandboxUserSid:T,read:a,write:i,srtWin:y});for(const h of a)N.add(`grant:${h.toLowerCase()}`);for(const h of i)N.add(`grant:${h.toLowerCase()}`);X||(X=!0,oe(()=>{try{o.revokeWindowsAcl({sandboxUserSid:T,srtWin:y})}catch{}}))}}async function me(n,e,s,{engine:a,workdir:i,kit:h,settings:f,commandId:d,record:C,caBundle:A=""}){await K();const E=w=>typeof w=="string"&&/^[a-z]:\\/i.test(w),{read:O,write:g}=We({kit:h,files:[n,...E(e[0])?[e[0]]:[],...re].filter(Boolean),home:S});be(O,g);const x=te(n,e,{platform:"win32"}),_=await o.SandboxManager.wrapWithSandboxArgv(x,void 0,{filesystem:{denyRead:f.filesystem.denyRead,denyWrite:f.filesystem.denyWrite}},void 0,i,{commandId:d,commandText:x}),b=s?.env||process.env,m={...Ae({engine:a,home:S,env:b,base:process.env}),...k({},{platform:r,caBundle:A})},l=Ee(_.argv,m),$={};for(const[w,D]of Object.entries(_.env||{}))process.env[w]!==D&&($[w]=D);return{bin:l[0],argv:l.slice(1),opts:{...s,env:{...b,...$},shell:!1},record:C,commandId:d}}return Re({id:"srt",label:"Anthropic sandbox-runtime",async detect(){return await he(),{ok:!!c,runtime:c,reason:u,ownSessions:!!(c&&(c==="srt-lib"&&(U??J(v))||r!=="win32"&&M())),...r==="win32"&&W!==null?{provisioned:W,...W?{}:{install:I}}:{}}},async wrap({kit:n,grant:e,bin:s,argv:a,opts:i,engine:h,workdir:f,commandId:d,caBundle:C=""}){const A=ee(n,{loopback:p,home:r==="linux"?S:"",platform:r}),E=te(s,a),O=t.mode==="allowlist"&&e.hosts.length>0&&!Array.isArray(t.exactHosts),g=O&&c==="srt-lib"?U??J(v):"",x=O&&!g&&r!=="win32"?M():null,_=!!(g||x),b=ve({layer:"process",runtime:g?"srt-host":x?"srt-cli":c,kitId:n.id,mode:n.network.mode,hosts:_||!O?e.hosts:[]});O&&!_&&(b.hostsDropped=e.hosts,G||(G=!0,R(`sandbox: hosts granted to ${h} (${e.hosts.join(", ")}) need a session of their own — no sandbox host or srt CLI here, so the process runs with the shared allow list`)));try{if(g){const l=ie(d),$={bin:s,argv:a,cwd:i?.cwd||null,engine:h,workdir:f,grant:e,commandId:d,config:{enabled:!0,mode:t.mode,extraHosts:[],extraWrite:t.extraWrite,extraDenyRead:t.extraDenyRead,windows:t.windows,exactHosts:n.network.allowedDomains},loopback:p,srt:process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime",report:V?{url:V,token:l}:null},w={...i?.env||process.env};return{bin:process.execPath,argv:[g,fe($)],opts:{...i,env:w,shell:!1},record:b,commandId:d}}if(x){const l={...i?.env||process.env};return Object.assign(l,k(l,{platform:r,caBundle:C})),{bin:x.bin,argv:[...x.argv,"-s",se(A),"-c",E],opts:{...i,env:l,shell:!1},record:b,commandId:d}}if(c==="srt-lib"&&r==="win32")return{...await me(s,a,i,{engine:h,workdir:f,kit:n,settings:A,commandId:d,record:b,caBundle:C})};if(c==="srt-lib"){await K();const l=await o.SandboxManager.wrapWithSandboxArgv(E,void 0,{filesystem:A.filesystem},void 0,f,{commandId:d,commandText:E}),$=i?.env||process.env,w={};for(const[q,Q]of Object.entries(l.env||{}))process.env[q]!==Q&&(w[q]=Q);const D={...$,...w};return Object.assign(D,k(D,{platform:r,caBundle:C})),{bin:l.argv[0],argv:l.argv.slice(1),opts:{...i,env:D,shell:!1},record:b,commandId:d}}const m=M();return{bin:m.bin,argv:[...m.argv,"-s",se(A),"-c",E],opts:{...i,shell:!1},record:b,commandId:d}}catch(m){return R(`sandbox: could not wrap ${s}: ${m.message}`),{passReason:m?.code==="SHAPE"?`the sandbox policy refused this run: ${m.message}`:`sandbox-runtime failed to wrap the command: ${m.message}`}}},violations(n){try{return o?.SandboxManager?.getSandboxViolationStore?.()?.getViolationsForCommand?.(n)||[]}catch{return[]}},close(){if(!(!T||!N.size)){try{o.revokeWindowsAcl({sandboxUserSid:T,srtWin:y})}catch(n){R(`sandbox: could not release the Windows grants: ${n.message}`)}N.clear()}}})}Te("srt",t=>_e(t));export{_e as createSrtRuntime};
|
package/src/sandbox.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as $t,spawnSync as kt}from"node:child_process";import{writeFileSync as lt,mkdirSync as pt,existsSync as Mt}from"node:fs";import{createHash as Bt,randomBytes as wt}from"node:crypto";import{AsyncLocalStorage as jt}from"node:async_hooks";import{fileURLToPath as ht}from"node:url";import F from"node:os";import C from"node:path";import{ensureCaBundle as Ft}from"./ca-bundle.js";import{kitFor as It,toSrtSettings as ft,sandboxRecord as xt,shellJoin as bt,sandboxEnvOverlay as Z,normalizeGrant as mt,windowsGrantsFor as Xt,windowsSandboxEnv as Ut,withSrtWinEnv as Gt,NETWORK_MODES as Vt,ENGINE_KITS as zt,DEVELOPER_HOSTS as Jt,SECRET_PATHS as Kt,COMMON_WRITE as Yt}from"./events/sandbox-policy.js";const St=new jt;function ye(t,e){let r;try{r=mt(t)}catch{r=null}return St.run(r,e)}function qt(){return St.getStore()||null}const Qt=/deny network-outbound\s+(\S+?):(\d+)\s*(?:\((.*)\))?/;function Zt(t){const e=Qt.exec(String(t||""));return e?{host:e[1].toLowerCase(),port:Number(e[2])||0,reason:e[3]||""}:null}const U=new Map,I=[],G=new Map,tt=new Set,te=50;function gt({commandId:t,host:e,port:r=0,reason:c="",at:w=Date.now()}){if(!t||!e)return;let d=U.get(t);for(d||(d=new Map,U.set(t,d)),d.set(e,{at:w,reason:c,port:r}),I.push({id:t,engine:G.get(t)||String(t).split(":")[0],host:e,at:w});I.length>te;)I.shift()}function ee(t){const e=U.get(t);return e?[...e.entries()].sort((r,c)=>c[1].at-r[1].at).map(([r])=>r):[]}function ne(t=20){return I.slice(-t).reverse()}function ve(){U.clear(),I.length=0,G.clear(),tt.clear()}const yt=new Map;function Ae(t={}){const e=yt.get(String(t?.token||""));return!e||e!==t.commandId?!1:(gt({commandId:e,host:String(t.host||"").toLowerCase().slice(0,253),port:Number(t.port)||0,reason:String(t.reason||"").slice(0,200)}),!0)}let se=0;const re=t=>`${t}:${(++se).toString(36)}${Date.now().toString(36).slice(-4)}`,V=new Map;function oe(t,e,{kind:r="agent",label:c=""}={}){if(!t||!e)return t;try{t.sandbox=e.record}catch{}if(typeof t.on!="function")return t;const w=e.commandId||"";V.set(t,{id:w,kind:r,engine:G.get(w)||String(w).split(":")[0]||"custom",command:e.label||"",label:c,pid:t.pid??null,since:Date.now(),sandbox:e.record});const d=()=>V.delete(t);return t.once("exit",d),t.once("error",d),t}function We(){return[...V.values()].map(t=>({...t,refused:ee(t.id)}))}function Ee(){V.clear()}function vt(t){if(t)return"";try{return ht(new URL("./sandbox-host.js",import.meta.url))}catch{return""}}function ae(t=process.env.CHATPANEL_SRT_MODULE){if(!t)return"";try{const e=t.startsWith("file:")?ht(new URL("./cli.js",t)):C.join(C.dirname(t),"cli.js");return Mt(e)?e:""}catch{return""}}const At="open",et="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)",ie=()=>[Number(process.env.CHATPANEL_GATEWAY_PORT)||4320,Number(process.env.CHATPANEL_BRIDGE_PORT)||Number(process.env.PORT)||4319],nt=t=>String(t||"").split(",").map(e=>e.trim()).filter(Boolean);function ce(t=process.env){const e=String(t.CHATPANEL_SANDBOX||At).toLowerCase(),r=e!=="off"&&e!=="0"&&e!=="false",c=Vt.includes(e)?e:At;return{enabled:r,mode:c,extraHosts:nt(t.CHATPANEL_SANDBOX_ALLOW_HOSTS),extraWrite:nt(t.CHATPANEL_SANDBOX_ALLOW_WRITE),extraDenyRead:nt(t.CHATPANEL_SANDBOX_DENY_READ),windows:t.CHATPANEL_SANDBOX_WINDOWS==="1"}}const Wt=new Set;function Et(t,e=C.join(F.tmpdir(),"chatpanel-srt")){const r=JSON.stringify(t),c=C.join(e,`${Bt("sha256").update(r).digest("hex").slice(0,16)}.json`);return Wt.has(c)||(pt(e,{recursive:!0,mode:448}),lt(c,r,{mode:384}),Wt.add(c)),c}function de(){try{const t=kt(process.platform==="win32"?"where":"which",["srt"],{encoding:"utf8",timeout:3e3});return t.status===0&&String(t.stdout||"").trim().length>0}catch{return!1}}function ue({config:t=ce(),loadSrt:e=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:r=de,cliEntry:c=ae(),onRefusal:w=p=>gt(p),reportUrl:d=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:_=null,compiled:h=!1,platform:a=process.platform,home:v=F.homedir(),loopback:J=ie(),selfFiles:Ot=[process.execPath,process.argv[1]||""],onExit:Tt=p=>process.on("exit",p),log:H=()=>{}}={}){let p=null,x=null,u=null,K=null,$=null,O=null,P=null;const k=new Set;let ot=!1;const Nt="Windows: the sandbox runs a process as a separate account, and mapping your sign-in, the CLI and its environment into it is built but not yet proved on a signed-in machine — CHATPANEL_SANDBOX_WINDOWS=1 turns it on (docs/sandboxing.md S1)",Lt="Windows: the sandbox account needs the runtime the gateway carries (the `srt` CLI cannot map your sign-in into it) — run the bridge through chatpanel-gateway";async function Rt(){if(!t.windows){x=Nt;return}if(h){x=Lt;return}try{u=await e()}catch(s){x=`sandbox-runtime is not installed — it ships with the gateway (${s.message})`;return}if(!u?.SandboxManager?.wrapWithSandboxArgv||typeof u.grantWindowsAcl!="function"||typeof u.getWindowsSandboxUserStatusAsync!="function"){x="Windows: this sandbox-runtime is older than 0.0.77, which the account mapping needs";return}try{O=u.resolveSrtWin({path:u.VENDORED_SRT_WIN_EXE})}catch(s){x=`Windows: srt-win.exe is not beside sandbox-runtime (${s.message})`;return}let n;try{n=await u.getWindowsSandboxUserStatusAsync({srtWin:O})}catch(s){P=!1,x=`Windows: srt-win could not be asked whether the sandbox account exists (${s.message}) — ${et}`;return}if(P=!!(n?.provisioned&&n.sid),!P){x=`Windows: the sandbox account is not installed — ${et}`;return}$=n.sid,p="srt-lib"}async function at(){if(!(p||x)){if(!t.enabled){x="sandboxing is off (CHATPANEL_SANDBOX=off)";return}if(a==="win32")return Rt();if(!h)try{if(u=await e(),u?.SandboxManager?.wrapWithSandboxArgv){p="srt-lib";return}}catch(n){H(`sandbox: library not available (${n.message})`)}if(r()){p="srt-cli";return}x=h?"srt is not on PATH — the compiled bridge cannot carry it: npm i -g @anthropic-ai/sandbox-runtime":"sandbox-runtime is not installed — it ships with the gateway; standalone: npm i -g @anthropic-ai/sandbox-runtime"}}let it=!1;function Y(){return c&&!h?{bin:process.execPath,argv:[c]}:p==="srt-cli"||r()?{bin:"srt",argv:[]}:null}function Dt(){const n=Array.isArray(t.exactHosts)?t.exactHosts:t.mode==="open"?["*"]:t.mode==="none"?[]:[...new Set([...Object.values(zt).flatMap(l=>l.hosts),...Jt,...t.extraHosts])],s={id:`session:${t.mode}`,network:{mode:t.mode,allowedDomains:n},filesystem:{allowWrite:[F.tmpdir(),...Yt,...t.extraWrite],denyRead:[...Kt,...t.extraDenyRead]}},o=ft(s,{loopback:J,home:a==="linux"?v:"",platform:a});return O?{...o,windows:{srtWin:{path:O.exe}}}:o}async function ct(){return K||(K=u.SandboxManager.initialize(Dt()).then(()=>{try{u.SandboxManager.getSandboxViolationStore?.()?.subscribe?.(n=>{for(const s of n||[]){const o=Zt(s?.line);if(!o||!s?.encodedCommand)continue;let l="";try{l=Buffer.from(s.encodedCommand,"base64").toString("utf8")}catch{continue}const m=`${l}|${o.host}|${s.timestamp instanceof Date?s.timestamp.getTime():String(s.timestamp)}`;tt.has(m)||(tt.add(m),w({commandId:l,...o,at:s.timestamp instanceof Date?s.timestamp.getTime():Date.now()}))}})}catch(n){H(`sandbox: violations not subscribed (${n.message})`)}})),K}function Ct(n){const s=C.join(F.tmpdir(),"chatpanel-srt");pt(s,{recursive:!0,mode:448});const o=C.join(s,`host-${wt(8).toString("hex")}.json`);return lt(o,JSON.stringify(n),{mode:384}),o}function Pt(n,s){const o=(i,T)=>u.expandWindowsFsPaths(i,{mode:T}).filter(g=>!k.has(`${T}:${g.toLowerCase()}`)),l=o(n,"grant"),m=o(s,"grant");if(!(!l.length&&!m.length)){u.grantWindowsAcl({sandboxUserSid:$,read:l,write:m,srtWin:O});for(const i of l)k.add(`grant:${i.toLowerCase()}`);for(const i of m)k.add(`grant:${i.toLowerCase()}`);ot||(ot=!0,Tt(()=>{try{u.revokeWindowsAcl({sandboxUserSid:$,srtWin:O})}catch{}}))}}async function Ht(n,s,o,{engine:l,workdir:m,kit:i,settings:T,commandId:g,record:A,caBundle:M=""}){await ct();const B=b=>typeof b=="string"&&/^[a-z]:\\/i.test(b),{read:W,write:y}=Xt({kit:i,files:[n,...B(s[0])?[s[0]]:[],...Ot].filter(Boolean),home:v});Pt(W,y);const N=bt(n,s,{platform:"win32"}),L=await u.SandboxManager.wrapWithSandboxArgv(N,void 0,{filesystem:{denyRead:T.filesystem.denyRead,denyWrite:T.filesystem.denyWrite}},void 0,m,{commandId:g,commandText:N}),R=o?.env||process.env,D={...Ut({engine:l,home:v,env:R,base:process.env}),...Z({},{platform:a,caBundle:M})},E=Gt(L.argv,D),j={};for(const[b,f]of Object.entries(L.env||{}))process.env[b]!==f&&(j[b]=f);return{bin:E[0],argv:E.slice(1),opts:{...o,env:{...R,...j},shell:!1},record:A,commandId:g}}return{config:t,async status(){return await at(),{enabled:t.enabled,mode:t.mode,runtime:p,platform:a,...x?{reason:x}:{},extras:{hosts:t.extraHosts,write:t.extraWrite,denyRead:t.extraDenyRead},ownSessions:!!(p&&(p==="srt-lib"&&(_??vt(h))||a!=="win32"&&Y())),refused:ne(),...a==="win32"&&P!==null?{provisioned:P,...P?{}:{install:et}}:{}}},close(){if(!(!$||!k.size)){try{u.revokeWindowsAcl({sandboxUserSid:$,srtWin:O})}catch(n){H(`sandbox: could not release the Windows grants: ${n.message}`)}k.clear()}},async wrap(n,s,o,{engine:l="custom",cwd:m=null,commandId:i=null,grant:T=qt()}={}){await at(),i=i||re(l),G.set(i,l);const g=m||o?.cwd||process.cwd(),A=C.basename(String(n||"")),M=f=>({bin:n,argv:s,opts:o,record:xt({layer:"none",reason:f}),commandId:i,label:A});if(!p)return M(x);const B=await Ft().catch(()=>"");let W,y;try{y=mt(T),W=It({engine:l,cwd:g,mode:t.mode,extraHosts:t.extraHosts,extraWrite:[F.tmpdir(),...t.extraWrite],extraDenyRead:t.extraDenyRead,grant:y})}catch(f){return M(`kit: ${f.message}`)}const N=ft(W,{loopback:J,home:a==="linux"?v:"",platform:a}),L=bt(n,s),R=t.mode==="allowlist"&&y.hosts.length>0&&!Array.isArray(t.exactHosts),D=R&&p==="srt-lib"?_??vt(h):"",E=R&&!D&&a!=="win32"?Y():null,j=!!(D||E),b=xt({layer:"process",runtime:D?"srt-host":E?"srt-cli":p,kitId:W.id,mode:W.network.mode,hosts:j||!R?y.hosts:[]});R&&!j&&(b.hostsDropped=y.hosts,it||(it=!0,H(`sandbox: hosts granted to ${l} (${y.hosts.join(", ")}) need a session of their own — no sandbox host or srt CLI here, so the process runs with the shared allow list`)));try{if(D){const S=wt(16).toString("hex");yt.set(S,i);const q={bin:n,argv:s,cwd:o?.cwd||null,engine:l,workdir:g,grant:y,commandId:i,config:{enabled:!0,mode:t.mode,extraHosts:[],extraWrite:t.extraWrite,extraDenyRead:t.extraDenyRead,windows:t.windows,exactHosts:W.network.allowedDomains},loopback:J,srt:process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime",report:d?{url:d,token:S}:null},X={...o?.env||process.env};return{bin:process.execPath,argv:[D,Ct(q)],opts:{...o,env:X,shell:!1},record:b,commandId:i,label:A}}if(E){const S={...o?.env||process.env};return Object.assign(S,Z(S,{platform:a,caBundle:B})),{bin:E.bin,argv:[...E.argv,"-s",Et(N),"-c",L],opts:{...o,env:S,shell:!1},record:b,commandId:i,label:A}}if(p==="srt-lib"&&a==="win32")return{...await Ht(n,s,o,{engine:l,workdir:g,kit:W,settings:N,commandId:i,record:b,caBundle:B}),label:A};if(p==="srt-lib"){await ct();const S=await u.SandboxManager.wrapWithSandboxArgv(L,void 0,{filesystem:N.filesystem},void 0,g,{commandId:i,commandText:L}),q=o?.env||process.env,X={};for(const[dt,ut]of Object.entries(S.env||{}))process.env[dt]!==ut&&(X[dt]=ut);const Q={...q,...X};return Object.assign(Q,Z(Q,{platform:a,caBundle:B})),{bin:S.argv[0],argv:S.argv.slice(1),opts:{...o,env:Q,shell:!1},record:b,commandId:i,label:A}}const f=Y();return{bin:f.bin,argv:[...f.argv,"-s",Et(N),"-c",L],opts:{...o,shell:!1},record:b,commandId:i,label:A}}catch(f){return H(`sandbox: could not wrap ${n}: ${f.message}`),M(f?.code==="SHAPE"?`the sandbox policy refused this run: ${f.message}`:`sandbox-runtime failed to wrap the command: ${f.message}`)}},violations(n){try{return u?.SandboxManager?.getSandboxViolationStore?.()?.getViolationsForCommand?.(n)||[]}catch{return[]}}}}let z=null;function _t(){if(!z){const{isCompiledBinary:t}=le();z=ue({compiled:t(),log:e=>console.error(`[bridge] ${e}`)})}return z}function _e(t){z=t}let st=null;function le(){return st||(st={isCompiledBinary:()=>{const t=(process.execPath||"").split(/[\\/]/).pop().toLowerCase();return!(t.startsWith("node")||t.startsWith("bun"))}}),st}const rt=new Set;function Oe(t,e){if(!e||e.layer!=="none"||typeof t!="function")return;const r=e.reason||"unknown";rt.has(r)||(rt.add(r),t({type:"status",text:`Running outside a sandbox — ${r}`}))}function Te(){rt.clear()}async function Ne(t,e,r,c={},{spawnImpl:w=$t,box:d=_t(),kind:_="agent",label:h=""}={}){const a=await d.wrap(t,e,r,c);return oe(w(a.bin,a.argv,a.opts),a,{kind:_,label:h})}async function Le(t,{box:e=_t(),platform:r=process.platform,loadSrt:c=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),out:w=console.log,err:d=console.error}={}){const _=t[0]||"status";if(_==="status")return w(JSON.stringify(await e.status(),null,2)),0;if(_!=="install")return d("usage: chatpanel-bridge sandbox [status|install]"),2;if(r!=="win32")return w("Nothing to install here: on macOS and Linux the sandbox runs as you. Only Windows has the one-time account setup."),0;let h;try{h=await c()}catch(a){return d(`sandbox-runtime is not installed — it ships with the gateway, so run \`chatpanel-gateway sandbox install\` (${a.message})`),1}try{const a=h.resolveSrtWin({path:h.VENDORED_SRT_WIN_EXE}),v=await h.installWindowsSandboxAsync({srtWin:a});return v?.cancelled?(d("Cancelled at the administrator prompt — nothing was installed."),1):(w(`The sandbox account is installed${v?.user?.sid?` (${v.user.sid})`:""}. Start the bridge with CHATPANEL_SANDBOX_WINDOWS=1; /health.sandbox says what the next run gets.`),0)}catch(a){d(`install failed: ${a.message}`);try{d(h.windowsInstallInstructions())}catch{}return 1}}export{Ee as _resetLiveForTest,Te as _resetNotedForTest,ve as _resetRefusalsForTest,_e as _setSandboxForTest,Ae as acceptRefusalReport,ue as createSandbox,qt as currentGrant,We as liveProcesses,Oe as noteSandbox,Zt as parseRefusalLine,ne as recentRefusals,gt as recordRefusal,ee as refusalsFor,Le as runSandboxCli,_t as sandbox,ce as sandboxConfigFromEnv,Ne as sandboxedSpawn,oe as track,ye as withGrant};
|
|
1
|
+
import{spawn as re}from"node:child_process";import"node:fs";import{randomBytes as se}from"node:crypto";import{AsyncLocalStorage as oe}from"node:async_hooks";import{fileURLToPath as ae}from"node:url";import N from"node:os";import ie from"node:path";import{ensureCaBundle as ue}from"./ca-bundle.js";import{kitFor as ce,sandboxRecord as le,normalizeGrant as I,writableRoots as de,NETWORK_MODES as pe}from"./events/sandbox-policy.js";import{createSandboxRuntime as fe,sandboxRuntimeIds as xe}from"./sandbox-runtime.js";import"./sandbox-srt.js";const U=new oe;function Ge(e,t){let n;try{n=I(e)}catch{n=null}return U.run(n,t)}function K(){return U.getStore()||null}function Ie(e,{config:t=Q(),grant:n=K(),home:s=N.homedir()}={}){try{return de({grant:n,extraWrite:t.extraWrite,cwd:e,home:s})}catch{return[]}}const me=/deny network-outbound\s+(\S+?):(\d+)\s*(?:\((.*)\))?/;function V(e){const t=me.exec(String(e||""));return t?{host:t[1].toLowerCase(),port:Number(t[2])||0,reason:t[3]||""}:null}const T=new Map,A=[],g=new Map,we=new Set,Se=50;function Y({commandId:e,host:t,port:n=0,reason:s="",at:a=Date.now()}){if(!e||!t)return;let o=T.get(e);for(o||(o=new Map,T.set(e,o)),o.set(t,{at:a,reason:s,port:n}),A.push({id:e,engine:g.get(e)||String(e).split(":")[0],host:t,at:a});A.length>Se;)A.shift()}function he(e){const t=T.get(e);return t?[...t.entries()].sort((n,s)=>s[1].at-n[1].at).map(([n])=>n):[]}function Ae(e=20){return A.slice(-e).reverse()}function Ue(){T.clear(),A.length=0,g.clear(),we.clear()}const j=new Map;function z(e){const t=se(16).toString("hex");return j.set(t,e),t}function Ke(e={}){const t=j.get(String(e?.token||""));return!t||t!==e.commandId?!1:(Y({commandId:t,host:String(e.host||"").toLowerCase().slice(0,253),port:Number(e.port)||0,reason:String(e.reason||"").slice(0,200)}),!0)}let be=0;const _e=e=>`${e}:${(++be).toString(36)}${Date.now().toString(36).slice(-4)}`,E=new Map;function Re(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||"";E.set(e,{id:a,kind:n,engine:g.get(a)||String(a).split(":")[0]||"custom",command:t.label||"",label:s,pid:e.pid??null,since:Date.now(),sandbox:t.record});const o=()=>E.delete(e);return e.once("exit",o),e.once("error",o),e}function Ve(){return[...E.values()].map(e=>({...e,refused:he(e.id)}))}function Ye(){E.clear()}function J(e){if(e)return"";try{return ae(new URL("./sandbox-host.js",import.meta.url))}catch{return""}}const q="open",je="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)",ye=()=>[Number(process.env.CHATPANEL_GATEWAY_PORT)||4320,Number(process.env.CHATPANEL_BRIDGE_PORT)||Number(process.env.PORT)||4319],C=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean);function Q(e=process.env){const t=String(e.CHATPANEL_SANDBOX||q).toLowerCase(),n=t!=="off"&&t!=="0"&&t!=="false",s=pe.includes(t)?t:q;return{enabled:n,mode:s,extraHosts:C(e.CHATPANEL_SANDBOX_ALLOW_HOSTS),extraWrite:C(e.CHATPANEL_SANDBOX_ALLOW_WRITE),extraDenyRead:C(e.CHATPANEL_SANDBOX_DENY_READ),windows:e.CHATPANEL_SANDBOX_WINDOWS==="1",reads:e.CHATPANEL_SANDBOX_READS==="inverted"?"inverted":"enumerated"}}function Ne({config:e=Q(),loadSrt:t=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:n=void 0,cliEntry:s=void 0,onRefusal:a=c=>Y(c),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:d=null,compiled:u=!1,platform:i=process.platform,home:p=N.homedir(),loopback:v=ye(),selfFiles:H=[process.execPath,process.argv[1]||""],onExit:$=c=>process.on("exit",c),runtimeId:b=process.env.CHATPANEL_SANDBOX_RUNTIME||"srt",makeRuntime:B=null,log:S=()=>{}}={}){let c=null,_=null,l={ok:!1,runtime:null,reason:null,ownSessions:!1};function h(){if(c||_)return c;try{c=B?B({config:e,platform:i,home:p,loopback:v,compiled:u,selfFiles:H,onExit:$,hostEntry:d,reportUrl:o,mintReportToken:z,onRefusal:a,parseRefusal:V,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:J,log:S}):fe(b,{config:e,platform:i,home:p,loopback:v,compiled:u,selfFiles:H,onExit:$,hostEntry:d,reportUrl:o,mintReportToken:z,onRefusal:a,parseRefusal:V,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:J,log:S})}catch(r){_=r?.message||String(r),S(`sandbox: ${_}`)}return c}async function k(){if(!e.enabled)return l={ok:!1,runtime:null,reason:"sandboxing is off (CHATPANEL_SANDBOX=off)",ownSessions:!1},l;const r=h();if(!r)return l={ok:!1,runtime:null,reason:_,ownSessions:!1},l;try{l={...l,...await r.detect()}}catch(f){l={ok:!1,runtime:null,reason:`the ${r.id} sandbox could not be started: ${f.message}`,ownSessions:!1}}return l}return{config:e,async status(){const r=await k(),f=h();return{enabled:e.enabled,mode:e.mode,runtime:r.runtime,platform:i,layer:f?.id||b,layers:xe(),...r.reason?{reason:r.reason}:{},extras:{hosts:e.extraHosts,write:e.extraWrite,denyRead:e.extraDenyRead},ownSessions:!!r.ownSessions,refused:Ae(),...r.provisioned!==void 0?{provisioned:r.provisioned}:{},...r.install?{install:r.install}:{}}},close(){try{h()?.close()}catch(r){S(`sandbox: close failed: ${r.message}`)}},async wrap(r,f,O,{engine:R="custom",cwd:ee=null,commandId:x=null,grant:te=K()}={}){const M=await k();x=x||_e(R),g.set(x,R);const F=ee||O?.cwd||process.cwd(),X=ie.basename(String(r||"")),y=w=>({bin:r,argv:f,opts:O,record:le({layer:"none",reason:w}),commandId:x,label:X});if(!M.ok)return y(M.reason);const ne=await ue().catch(()=>"");let G,D;try{D=I(te),G=ce({engine:R,cwd:F,mode:e.mode,extraHosts:e.extraHosts,extraWrite:[N.tmpdir(),...e.extraWrite],extraDenyRead:e.extraDenyRead,grant:D,home:N.homedir(),reads:e.reads})}catch(w){return y(`kit: ${w.message}`)}let m;try{m=await h().wrap({kit:G,grant:D,bin:r,argv:f,opts:O,engine:R,workdir:F,commandId:x,caBundle:ne})}catch(w){return S(`sandbox: could not wrap ${r}: ${w.message}`),y(`the ${b} sandbox failed to wrap the command: ${w.message}`)}return!m||m.passReason?y(m?.passReason||`the ${b} sandbox returned nothing`):{...m,commandId:m.commandId||x,label:X}},violations(r){try{return h()?.violations(r)||[]}catch{return[]}}}}let L=null;function Z(){if(!L){const{isCompiledBinary:e}=Te();L=Ne({compiled:e(),log:t=>console.error(`[bridge] ${t}`)})}return L}function ze(e){L=e}let P=null;function Te(){return P||(P={isCompiledBinary:()=>{const e=(process.execPath||"").split(/[\\/]/).pop().toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}}),P}const W=new Set;function Je(e,t){if(!t||t.layer!=="none"||typeof e!="function")return;const n=t.reason||"unknown";W.has(n)||(W.add(n),e({type:"status",text:`Running outside a sandbox — ${n}`}))}function qe(){W.clear()}async function Qe(e,t,n,s={},{spawnImpl:a=re,box:o=Z(),kind:d="agent",label:u=""}={}){const i=await o.wrap(e,t,n,s);return Re(a(i.bin,i.argv,i.opts),i,{kind:d,label:u})}async function Ze(e,{box:t=Z(),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 d=e[0]||"status";if(d==="status")return a(JSON.stringify(await t.status(),null,2)),0;if(d!=="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}),p=await u.installWindowsSandboxAsync({srtWin:i});return p?.cancelled?(o("Cancelled at the administrator prompt — nothing was installed."),1):(a(`The sandbox account is installed${p?.user?.sid?` (${p.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{Ye as _resetLiveForTest,qe as _resetNotedForTest,Ue as _resetRefusalsForTest,ze as _setSandboxForTest,Ke as acceptRefusalReport,Ne as createSandbox,K as currentGrant,Ie as grantedWriteRoots,Ve as liveProcesses,Je as noteSandbox,V as parseRefusalLine,Ae as recentRefusals,Y as recordRefusal,he as refusalsFor,Ze as runSandboxCli,Z as sandbox,Q as sandboxConfigFromEnv,Qe as sandboxedSpawn,Re as track,Ge as withGrant};
|
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,acceptRefusalReport as gt,liveProcesses as yt}from"./sandbox.js";import{gitState as wt,gitDelta as bt}from"./scm.js";import{listConnections as St,putConnection as kt,removeConnection as Tt,runEnvFor as Et,testConnection as vt,secretBackend as ne}from"./connections.js";import{worktreeFor as oe,listWorktrees as Ot,removeWorktree as At,withHook as Ct,WORKTREE_ROOT as re}from"./worktree.js";import{AGENT_CLIS as xt,agentAvailable as Pt,agentInstallDirs as Rt,enrichPath as It,enrichAgentEnv as $t,findAgentBin as Nt,resolveCommand as ae}from"./env.js";import"./sanitize.js";import{checkForUpdate as Dt,selfUpdate as ie,isEmbedded as _t}from"./update.js";import{callLocalMcp as Ht,localMcpStatus as Mt,signInLocalMcp as Ut,signInStatusLocalMcp as Bt}from"./mcp-local.js";import{assertPublicHttpUrl as se,assertPublicWebUrl as ce}from"./ssrf.js";import{startRun as le,endRun as j,cancelRun as Wt,cancelAll as Gt}from"./runs.js";import{closeWarmPools as Lt,warmStatus as jt}from"./warm.js";import{CompatError as R,anthropicError as F,anthropicStream as Ft,chatCompletionStream as Jt,completionStream as Xt,createAnthropicMessage as zt,createChatCompletion as Kt,createCompletion as Vt,createResponse as Yt,openAIError as b,parseAnthropicMessage as Qt,parseChatCompletion as Zt,parseCompletion as qt,parseResponse as en,responseStream as tn}from"./api-compat.js";import{callerTrust as nn,isPaired as I,parseExtensionIds as on,capRunOptions as rn,engineHonoursReach as an,createPairingStore as sn,formatPairingCode as cn}from"./pii/trust.js";const g="0.27.2",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 ln=on(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function $(t){return t.chatpanelTrust||(t.chatpanelTrust=nn({origin:t.headers.origin||"",hasToken:fe(t),extensionIds:ln})),t.chatpanelTrust}function dn(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 un(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 hn(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 pn(){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=sn({random:()=>ve(0,1e6)/1e6});function fn(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 mn(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 gn(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 yn=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"]),wn=new Set(["/debug"]),bn=t=>wn.has(t),Sn=(t,e)=>t!=="GET"&&t!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function kn(t,e){if(!hn(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!de(n))return"forbidden origin";const r=t.method==="POST"&&yn.has(e)||t.method==="GET"&&bn(e)||Sn(t.method,e);return r&&!(dn(n)||fe(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I($(t))&&!En.has(e)?Tn:null}const Tn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",En=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=rn(n,r);if(!an(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 vn(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=_t()?{current:g,updateAvailable:!1,embedded:"gateway"}:await Dt(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:Mt(),processes:yt(),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 On(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 An(t,e,n){a(t,200,{ok:!0,quarantined:await ze(e,n)})}async function Cn(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 xn(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 Pn(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 Rn(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 In(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 $n(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 Nn(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 Dn(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 _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,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 Hn(){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 Hn();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 Mn(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 Un(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 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.4",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)}
|
|
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 A=null;{const f=K,C=!!p||!ht(n.options?.workingDir),w=ft(n.agent,n.options?.permissionMode,f);i({type:"workdir",path:f,isDefault:!C,writeScope:w||void 0}),i({type:"status",text:`Working in ${f}${C?"":" (default)"}`}),w&&i({type:"status",text:w}),A=await
|
|
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 A=null;{const f=K,C=!!p||!ht(n.options?.workingDir),w=ft(n.agent,n.options?.permissionMode,f,gt(f,{grant:n.options?.sandbox}));i({type:"workdir",path:f,isDefault:!C,writeScope:w||void 0}),i({type:"status",text:`Working in ${f}${C?"":" (default)"}`}),w&&i({type:"status",text:w}),A=await bt(f),A&&i({type:"scm",phase:"before",...A})}let W=null;if(A||p){const f=Array.isArray(n.options?.grants)?n.options.grants:[],{env:C,connection:w}=vt({remote:A?.remote||null,grants:f,branch:p?.branch||null,connectionId:n.options?.connectionId||null});W=xt(C),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: ${C.CHATPANEL_SCM_PUSH==="own"?`${p?.branch} only`:C.CHATPANEL_SCM_PUSH}`})}const V=n.approvals===!0,D={...n.options||{},...p?{workingDir:p.path}:{},...W?{runEnv:W}:{},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 St(K,A).catch(()=>null);f&&y({type:"scm",phase:"after",...f})}j(d),P&&Z(P.id),e.writableEnded||e.end()}}async function Wn(t,e,n){if(t.method==="GET"&&n==="/connections")return a(e,200,{ok:!0,connections:kt(),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:Tt(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:Et(o[1])}):a(e,200,Ot(o[1],r.remote||"")):a(e,404,{error:"Not found"})}async function Gn(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 Ct({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 Gn(t,e){const n=await B(t,e,Zt,b);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,b(o))}M(e);const r=Jt(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 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=tn(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 Fn(t,e){const n=await B(t,e,Qt,F);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,F(o))}M(e);const r=Ft(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 Jn(t,e){let n={};try{n=await m(t)||{}}catch{}const r=String(n.id||"").trim(),o=r?Wt(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 Xn(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 Ht({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 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||{};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?Bt(o):await Ut(o))}catch(i){return a(e,200,{state:"failed",error:String(i?.message||i)})}}async function Kn(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,Vn=5,Yn=8e3;async function Qn(t){let e=ce(t);const n=new AbortController,r=setTimeout(()=>n.abort(),Yn);try{for(let o=0;o<=Vn;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:eo(await Zn(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function Zn(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 qn(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 eo(t){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(t);return e?qn(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function to(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 no(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 oo(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 ro(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 ao(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(un(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=kn(t,n.pathname);if(r)return a(e,403,{error:r});try{if(t.method==="GET"&&n.pathname==="/health")return vn(e);const o=n.searchParams.getAll("dir"),i=n.searchParams.get("workdir")||"";if(t.method==="GET"&&n.pathname==="/skills")return On(e,o,i);if(t.method==="GET"&&n.pathname==="/skills-quarantined")return An(e,o,i);if(t.method==="GET"&&n.pathname==="/agent-defs")return $n(e,o,i);if(t.method==="POST"&&n.pathname==="/agent-defs/export-plan")return Dn(t,e);if(t.method==="POST"&&n.pathname==="/agent-defs/export")return _n(t,e);if(t.method==="GET"&&n.pathname.startsWith("/agent-defs/"))return Nn(e,decodeURIComponent(n.pathname.slice(12)),o,i);if(t.method==="POST"&&n.pathname==="/skills")return Pn(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"?In(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"}):Rn(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?Cn(e,decodeURIComponent(s),o,i):xn(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,i)}if(n.pathname==="/connections"||n.pathname.startsWith("/connections/"))return Bn(t,e,n.pathname);if(n.pathname==="/worktrees"||n.pathname.startsWith("/worktrees/"))return Wn(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(xt.map(d=>[d,s?Nt(d)||ae(d)?.kind||null:Pt(d)])),...s?{home:E.homedir(),path:process.env.PATH,installDirs:Rt(E.homedir())}:{}})}if(t.method==="POST"&&n.pathname==="/chat")return Un(t,e);if(t.method==="POST"&&n.pathname==="/pair")return mn(t,e);if(t.method==="POST"&&n.pathname==="/pair/code")return fn(e);if(t.method==="POST"&&n.pathname==="/whoami")return gn(t,e);if(t.method==="POST"&&n.pathname==="/v1/chat/completions")return Gn(t,e);if(t.method==="POST"&&n.pathname==="/v1/completions")return Ln(t,e);if(t.method==="POST"&&n.pathname==="/v1/responses")return jn(t,e);if(t.method==="POST"&&n.pathname==="/v1/messages")return Fn(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 Jn(t,e);if(t.method==="POST"&&n.pathname==="/tool-result")return no(t,e);if(t.method==="POST"&&n.pathname==="/sandbox/refused"){let s=null;try{s=await m(t)}catch{s=null}const d=gt(s||{});return e.writeHead(d?204:403),e.end()}if(t.method==="POST"&&n.pathname==="/mcp-local")return Xn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-local/signin")return zn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-remote")return Kn(t,e);if(t.method==="POST"&&n.pathname==="/fetch-title")return to(t,e);if(t.method==="POST"&&n.pathname==="/complete")return oo(t,e);if(t.method==="POST"&&n.pathname==="/list-models")return ro(t,e);if(t.method==="POST"&&n.pathname==="/agent-check")return ao(t,e);if(t.method==="POST"&&n.pathname==="/update")return Mn(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 io(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 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+`
|
|
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 co(){$t(),Nt(),fn(),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=Lt("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const n=jt("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 lo(){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 uo(){const t=process.argv,e=(...n)=>n.some(r=>t.includes(r));if(e("--help","-h"))return lo(),!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: ${ln(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{We(),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)),so(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}})():uo()||co();
|
package/src/workdir.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync as s}from"node:fs";import
|
|
1
|
+
import{mkdirSync as s}from"node:fs";import a from"node:os";import n from"node:path";const u=n.join(a.homedir(),".chatpanel","workspace");function h(t){const r=t&&String(t).trim()?n.resolve(String(t).trim()):u;try{s(r,{recursive:!0})}catch{}return r}function p(t){return!(t&&String(t).trim())}function m(t,r,i=n){const e=String(t||"");if(!e)return"";if(!r||!i.isAbsolute(e))return e;const o=i.relative(r,e);return o?o.startsWith("..")||i.isAbsolute(o)?e:o:"."}function y(t,r,i,e=[]){if(t!=="codex"||r==="bypassPermissions")return"";if(r!=="acceptEdits")return"Codex is read-only in this mode — set Permissions to “auto-edit files” to let it write.";const o=Array.isArray(e)?e.filter(Boolean):[];return`Codex may only create or edit files inside ${o.length?`${i}, ${o.join(", ")}`:String(i)}. To work on another project, set this agent’s Working directory to it${o.length?"":", or allow the folder in Settings › Runtime"}.`}export{u as DEFAULT_WORKSPACE,m as displayPath,p as isDefaultWorkdir,h as resolveWorkdir,y as writeScopeNote};
|