@chatpanel/bridge 0.42.0 → 0.44.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/scripts/sync-events.mjs +2 -2
- package/src/agent-context.js +1 -0
- package/src/cli-errors.js +6 -3
- package/src/engines/antigravity.js +4 -4
- package/src/engines/claude.js +4 -4
- package/src/engines/codex.js +2 -2
- package/src/engines/custom.js +5 -5
- package/src/env.js +2 -2
- package/src/events/context-breakdown.js +5 -0
- package/src/events/context-window.js +1 -1
- package/src/events/mcp-signin.js +1 -1
- package/src/health-snapshot.js +1 -0
- package/src/pii/pii-detect.js +2 -2
- package/src/server.js +8 -8
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.44.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
|
|
6
6
|
"keywords": [
|
package/scripts/sync-events.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFileSync as r,writeFileSync as j,existsSync as i,mkdirSync as p}from"node:fs";import{fileURLToPath as m}from"node:url";import{dirname as h,join as
|
|
2
|
+
import{readFileSync as r,writeFileSync as j,existsSync as i,mkdirSync as p}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","agent-thread.js","compaction.js","context-window.js","mcp-errors.js","registries.js","mcp-signin.js","context-breakdown.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","service-standby.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||p(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
|
//
|
|
@@ -7,4 +7,4 @@ import{readFileSync as r,writeFileSync as j,existsSync as i,mkdirSync as p}from"
|
|
|
7
7
|
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
8
8
|
// single-file binary has nothing to resolve.
|
|
9
9
|
|
|
10
|
-
`;let d=0;for(const e of f){const o=u(e)+r(
|
|
10
|
+
`;let d=0;for(const e of f){const o=u(e)+r(n(a,e),"utf8"),t=n(l,e);if((i(t)?r(t,"utf8"):null)!==o){if(s){console.error(`sync-events --check: src/events/${e} differs from chatpanel-events`),d+=1;continue}j(t,o),console.log(`sync-events: updated src/events/${e}`)}}s&&(d&&(console.error("Run `npm run sync:events` and commit the result."),process.exit(1)),console.log("sync-events --check: src/events matches chatpanel-events ✓"));
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawn as l}from"node:child_process";import{buildSpawnSpec as d,resolveClaude as m}from"./env.js";import{buildClaudeLaunch as f}from"./engines/claude.js";import{parseAgentContext as h}from"./events/context-breakdown.js";const x=10*6e4,p=new Map,w=new Set(["--output-format","--input-format","--name","-n"]),C=new Set(["--print","-p","--include-partial-messages","--verbose"]);function g(e){const r=[];for(let t=0;t<e.length;t++)if(!C.has(e[t])){if(w.has(e[t])){t++;continue}r.push(e[t])}return["-p","/context","--output-format","text",...r]}function y(e,r){return new Promise(t=>{const[s,a,c]=d(m(),e,r);let i="",o;try{o=l(s,a,{...c,stdio:["ignore","pipe","pipe"]})}catch{t("");return}const n=setTimeout(()=>{try{o.kill()}catch{}t(i)},2e4);n.unref?.(),o.stdout.on("data",u=>{i+=u}),o.on("error",()=>{clearTimeout(n),t("")}),o.on("close",()=>{clearTimeout(n),t(i)})})}async function k({agent:e="claude",options:r={},run:t=y,now:s=Date.now}={}){if(e!=="claude")return{ok:!1,error:`${e} cannot itemize its own context; its share is the provider's count less ours`};const a=await f({system:null,options:{...r,ephemeral:!0,mcp:void 0,approvals:!1},tag:`ctx-${process.pid}`});try{const c=g(a.args),i=JSON.stringify([a.cwd||"",c]),o=p.get(i);if(o&&s()-o.at<x)return{...o.value,cached:!0};const n=h(await t(c,a.cwd));if(!n)return{ok:!1,error:"Claude Code did not report its context (an older CLI has no /context in print mode)"};const u={ok:!0,agent:e,items:n.items,total:n.total,measuredAt:s()};return p.set(i,{at:s(),value:u}),{...u,cached:!1}}finally{a.cleanup?.()}}function A(){p.clear()}export{A as _resetAgentContext,k as agentContext,g as probeArgs};
|
package/src/cli-errors.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
-
import{loginRequired as
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import{loginRequired as g,signInMessage as m}from"./sign-in.js";const p=[/^\s*$/,/^\s*at\s+/,/^\s*[.#]?[\w-]+\s*\{/,/^\s*[\w-]+:\s*[^;]+;$/,/^\s*<\//];function l(e){return String(e||"").replace(/<script[\s\S]*?<\/script>/gi," ").replace(/<style[\s\S]*?<\/style>/gi," ").replace(/<svg[\s\S]*?<\/svg>/gi," ").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/[ \t]+/g," ")}const k=[/(?:refresh OAuth tokens|refresh tools) for (?:MCP )?server ['"`]?([\w.-]+)['"`]?/i,/MCP server ['"`]([\w.-]+)['"`]/i,/server ['"]?([\w.-]+)['"]? (?:requires|failed) auth/i];function h(e){for(const t of k){const n=t.exec(String(e||""))?.[1];if(n)return n}return null}const b=/api error|authentication_error|invalid (?:x-)?api[- ]key|bearer token|anthropic|openai|x-api-key/i,v=e=>/\b401\b/.test(e)&&!b.test(e)&&(/\bmcp\b/i.test(e)||!!h(e)),x=[{kind:"expired",test:/refresh token (?:does not exist|was rejected)|invalid_grant/i,short:"its saved login has expired",say:e=>`${e} needs re-authentication — its saved OAuth token has expired or been revoked. Re-login to that server in the agent's own config; ChatPanel can't refresh it.`},{kind:"unauthorized",test:e=>/invalid_token|AuthRequired|www-authenticate/i.test(e)||e.split(`
|
|
2
|
+
`).some(v),short:"it rejected the agent's token",say:e=>`${e} rejected the agent's token (401/invalid_token). Re-authenticate that server in the agent, then retry.`},{kind:"refused",test:/HTTP 403|\b403\b/,short:"it is refusing requests",say:e=>`${e} returned 403 and an error page — that server is refusing requests or is temporarily down. This is outside ChatPanel; retry when it recovers.`},{kind:"unreachable",requiresMcpContext:!0,test:/handshaking with MCP server failed|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|dns error|connection (?:refused|reset)|failed to start and is unavailable|network is unreachable/i,short:"it could not be reached",say:e=>`${e} could not be reached — it is offline, or needs a network (VPN) this machine is not on. ChatPanel can't reach it either; retry when it is available.`}];function $(e){const t=String(e||""),n=h(t),s=/\bmcp\b/i.test(t)||!!n;for(const i of x)if(!(i.requiresMcpContext&&!s)&&(typeof i.test=="function"?i.test(t):i.test.test(t)))return{server:n,kind:i.kind,short:i.short,say:i.say(n?`its MCP server "${n}"`:"one of its MCP servers")};return null}function w(e){const t=$(e);return t?t.say:/ENOENT|command not found/i.test(e)?"the command could not be found on PATH.":null}const A={"claude code":"claude",claude:"claude",codex:"codex","github copilot":"copilot",copilot:"copilot",opencode:"opencode",kiro:"kiro",hermes:"hermes",antigravity:"antigravity",pi:"pi"};function y(e,t,n,s="",{agentId:i=null}={}){const r=`${n||""}
|
|
3
|
+
${s||""}`;if(g(r))return m(e,i||A[String(e).toLowerCase()]||null);const o=w(r);if(o)return`${e} exited ${t}: ${o}`;const c=l(r).split(`
|
|
4
|
+
`).map(a=>a.trim()).filter(a=>a&&!p.some(f=>f.test(a))),u=c.filter(a=>/error|fail|fatal|panic|refused|denied|timeout/i.test(a)),d=(u.length?u:c).pop()||"failed";return`${e} exited ${t}: ${d.length>300?`${d.slice(0,300)}…`:d}`}const C=[[/(bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,"$1…"],[/\b(sk-|sk_|ghp_|gho_|xox[abpr]-|AKIA)[A-Za-z0-9_-]{6,}/g,"$1…"],[/\b[A-Za-z0-9_-]{24,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g,"…"],[/\b[A-Za-z0-9+/_-]{40,}={0,2}/g,"…"]];function E(e,t="",{lines:n=6,width:s=300}={}){return l(`${e||""}
|
|
5
|
+
${t||""}`).split(`
|
|
6
|
+
`).map(r=>r.trim()).filter(r=>r&&!p.some(o=>o.test(r))&&/error|fail|fatal|panic|refused|denied|timeout|unauthori[sz]ed|\b40[13]\b/i.test(r)).slice(-n).map(r=>C.reduce((o,[c,u])=>o.replace(c,u),r)).map(r=>r.length>s?`${r.slice(0,s)}…`:r).join(" ⏎ ")}function S(e,t,n,s="",i={}){return Object.assign(new Error(y(e,t,n,s,i)),{detail:E(n,s)})}export{S as cliError,E as errorTail,$ as mcpFailure,h as mcpServerName,l as stripMarkup,y as summarizeCliError};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{spawn as N,spawnSync as F}from"node:child_process";import{writeFileSync as
|
|
1
|
+
import{spawn as N,spawnSync as F}from"node:child_process";import{writeFileSync as R,unlinkSync as U}from"node:fs";import"node:os";import C from"node:path";import{agentAvailable as j,resolveCommand as z,buildSpawnSpec as B}from"../env.js";import{fitCliPrompt as G,argvPromptBudget as H}from"./prompt.js";import{cliError as J}from"../cli-errors.js";import{killOnAbort as K,spawnGroupOpts as W}from"../proc.js";import{track as Y,sandbox as Z,noteSandbox as q}from"../sandbox.js";import{pushExtraArgs as Q,FORBIDDEN as V}from"./args.js";import{resolveWorkdir as X}from"../workdir.js";const D=Number(process.env.CHATPANEL_AGY_TIMEOUT_MS)||18e4;async function yt(){try{const u=z("agy");if(!u)return[];const[a,n,i]=B(u,["models"],null),r=F(a,n,{...i,encoding:"utf8",timeout:15e3}),l=[],t=new Set;for(const s of String(r.stdout||"").split(`
|
|
2
2
|
`)){const o=s.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(o)&&!/^(name|model|models|id|provider|available)$/i.test(o)&&!t.has(o)&&(t.add(o),l.push(o),l.length>=100))break}return l}catch{return[]}}const P=()=>({started:new Set,finalText:""});function tt(u,a,n=P()){const i=String(u||"").trim();if(!i)return{streamed:!1};let r;try{r=JSON.parse(i)}catch{return a({type:"delta",text:`${i}
|
|
3
|
-
`}),{streamed:!0}}const l=r.event||r.type||"";if(l==="init")return a({type:"status",text:"Antigravity working"}),{streamed:!1};if(l==="result"){const s=r.result||{};return n.finalText=typeof s.response=="string"?s.response:"",s.status&&s.status!=="SUCCESS"&&a({type:"status",text:`Antigravity: ${s.status}`}),{streamed:!1}}if(l!=="step_update")return{streamed:!1};const t=r.step_update||{};if(t.step_type==="tool"){const s=`agy_${t.step_index??n.started.size}`,o=t.tool_info&&typeof t.tool_info=="object"?t.tool_info:{},d=t.tool_name||o.name||"tool";if(n.started.has(s)||(n.started.add(s),a({type:"tool",name:d,phase:"start",callId:s,input:o.parameters&&typeof o.parameters=="object"?o.parameters:{}})),t.state==="DONE"){const g=!!o.error||t.state==="ERROR",c=o.output==null?"":typeof o.output=="string"?o.output:JSON.stringify(o.output);a({type:"tool",name:d,phase:"done",callId:s,status:g?`error: ${String(o.error||"failed").slice(0,80)}`:"ok",result:String(g?o.error||"":c).slice(0,4e3)})}return{streamed:!1}}return t.step_type==="agent_response"&&typeof t.text_delta=="string"&&t.text_delta?(a({type:"delta",text:t.text_delta}),{streamed:!0}):{streamed:!1}}let x=!1,L=0;async function ht(){if(Date.now()-L>(x?3e4:4e3)){L=Date.now();try{x=
|
|
3
|
+
`}),{streamed:!0}}const l=r.event||r.type||"";if(l==="init")return a({type:"status",text:"Antigravity working"}),{streamed:!1};if(l==="result"){const s=r.result||{};return n.finalText=typeof s.response=="string"?s.response:"",s.status&&s.status!=="SUCCESS"&&a({type:"status",text:`Antigravity: ${s.status}`}),{streamed:!1}}if(l!=="step_update")return{streamed:!1};const t=r.step_update||{};if(t.step_type==="tool"){const s=`agy_${t.step_index??n.started.size}`,o=t.tool_info&&typeof t.tool_info=="object"?t.tool_info:{},d=t.tool_name||o.name||"tool";if(n.started.has(s)||(n.started.add(s),a({type:"tool",name:d,phase:"start",callId:s,input:o.parameters&&typeof o.parameters=="object"?o.parameters:{}})),t.state==="DONE"){const g=!!o.error||t.state==="ERROR",c=o.output==null?"":typeof o.output=="string"?o.output:JSON.stringify(o.output);a({type:"tool",name:d,phase:"done",callId:s,status:g?`error: ${String(o.error||"failed").slice(0,80)}`:"ok",result:String(g?o.error||"":c).slice(0,4e3)})}return{streamed:!1}}return t.step_type==="agent_response"&&typeof t.text_delta=="string"&&t.text_delta?(a({type:"delta",text:t.text_delta}),{streamed:!0}):{streamed:!1}}let x=!1,L=0;async function ht(){if(Date.now()-L>(x?3e4:4e3)){L=Date.now();try{x=j("agy")}catch{x=!1}}return x?{ok:!0}:{ok:!1,reason:"agy not found on PATH. Install Antigravity, then run `agy` once to sign in."}}function et(u,a){const n=[];for(let i=0;i<(u?.length||0);i++){const r=/^data:([^;]+);base64,(.+)$/s.exec(u[i]?.dataUrl||"");if(!r)continue;const l=(r[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",t=C.join(a,`chatpanel-img-${Date.now()}-${i}.${l}`);try{R(t,Buffer.from(r[2],"base64")),n.push(t)}catch{}}return n}async function wt({messages:u,system:a,options:n,images:i},r,{signal:l}={}){const t=X(n.workingDir),s=et(i,t),o=()=>s.forEach(e=>{try{U(e)}catch{}}),d=G(u,a,H({otherArgsChars:400}));let g=d.prompt;d.dropped&&r({type:"status",text:`Antigravity takes the prompt as a command-line argument, which this system caps — the oldest ${d.dropped} turn${d.dropped===1?"":"s"} of this conversation were left out to fit.`}),s.length&&(g+=`
|
|
4
4
|
|
|
5
|
-
The user attached image(s): ${s.map(e=>"@"+
|
|
6
|
-
`))>=0;)
|
|
5
|
+
The user attached image(s): ${s.map(e=>"@"+C.basename(e)).join(" ")}`);const c=["-p",g];n.model&&c.push("--model",n.model),n.permissionMode==="bypassPermissions"&&c.push("--dangerously-skip-permissions"),Q(c,n.extraArgs,V.antigravity,r);const _=async e=>{const M=e?[...c,"--output-format","stream-json"]:c,y=await Z().wrap("agy",M,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,...n.runEnv||{}},...W},{engine:"antigravity",cwd:t});return q(r,y.record),new Promise((k,b)=>{let f;try{f=Y(N(y.bin,y.argv,y.opts),y,{kind:"agent"})}catch(p){return b(new Error(`Failed to start agy: ${p.message}`))}const $=K(f,l);let E="",T="",m="",v=!1;const I=P();let h;const S=()=>{clearTimeout(h),h=setTimeout(()=>{f.kill("SIGKILL"),b(new Error(`Antigravity timed out — no output for ${Math.round(D/1e3)}s.`))},D)};S();const O=p=>{tt(p,r,I).streamed&&(v=!0)};f.stdout.on("data",p=>{S();const w=p.toString();if(E+=w,!e){v=!0,r({type:"delta",text:w});return}m+=w;let A;for(;(A=m.indexOf(`
|
|
6
|
+
`))>=0;)O(m.slice(0,A)),m=m.slice(A+1)}),f.stderr.on("data",p=>{S(),T+=p.toString()}),f.on("error",p=>{clearTimeout(h),$(),b(new Error(`Failed to start agy: ${p.message}`))}),f.on("close",p=>{if(clearTimeout(h),$(),l?.aborted){k({code:0,aborted:!0});return}e&&m.trim()&&O(m),k({code:p,out:E,err:T,streamed:v,state:I})})})};try{let e=await _(!0);if(e.aborted||e.code!==0&&!e.streamed&&/output-format|unknown flag|flag provided but not defined/i.test(e.err)&&(r({type:"status",text:"This Antigravity CLI has no structured output; showing its text only. Update it with `agy update` to see tool activity."}),e=await _(!1),e.aborted))return;if(e.code!==0)throw J("Antigravity",e.code,e.err,e.out);e.streamed||r({type:"delta",text:(e.state?.finalText||e.out).trim()||"(no output)"}),r({type:"done",text:""})}finally{o()}}export{ht as available,wt as chat,tt as forwardAgyLine,yt as listModels,P as newAgyState};
|
package/src/engines/claude.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{spawn as
|
|
1
|
+
import{spawn as z}from"node:child_process";import{writeFile as R,unlink as G}from"node:fs/promises";import P from"node:os";import D from"node:path";import{resolveClaude as v,buildSpawnSpec as J,isCompiledBinary as ue,selfMcpStdio as de}from"../env.js";import{signInStatus as pe,signInMessage as Y,loginRequired as fe}from"../sign-in.js";import{buildCliPrompt as K}from"./prompt.js";import{cliError as he}from"../cli-errors.js";import{killOnAbort as me}from"../proc.js";import{sandbox as ye,noteSandbox as _e,track as be,grantedWriteRoots as we}from"../sandbox.js";import{harnessDirArgs as Te,harnessSessionArgs as j}from"../events/harness-cards.js";import{threadTurn as ge}from"../threads.js";import{liveClaudeSessions as Ee}from"../agent-sessions.js";import{pushExtraArgs as xe,FORBIDDEN as Ce}from"./args.js";import{relayTimeoutMax as Se}from"../relay-timeout.js";import{displayPath as ke,resolveWorkdir as F}from"../workdir.js";import{connectorsFor as Ae}from"../connectors.js";import{chatWarm as ve}from"./claude-warm.js";import{claudePermissionResponse as Ne,permissionAnswer as Me}from"../events/agent-permission.js";import{relayPermission as Pe}from"../mcp-sessions.js";async function Oe(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=D.join(P.tmpdir(),`chatpanel-claude-img-${t}-${i}.${o}`);await R(n,Buffer.from(s[2],"base64")),r.push(n)}return r}const X=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,V=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task","ListAgents"],Q=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),Ie=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task","ToolSearch","ListAgents","SendMessage"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch","SendMessage"])}),Le=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),$e=Object.freeze(["remember","forget"]),We=Object.freeze(["ask_model","ask_status"]),Z=Object.freeze({device:Object.freeze([]),trusted:Le});function Re(e,t=[]){const r=Z[e]||Z.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[...$e,...We])o.push(`mcp__${n}__${a}`)}return{allow:s,deny:o}}function De(e){if(!e||e==="any")return null;const t=Q[e]?e:"device";return{allow:[...Q[t]],deny:[...Ie[t]]}}let O="Claude Code not found.",ee=0,k=!1;async function yt(){if(Date.now()-ee>(k?3e4:4e3)){ee=Date.now();try{v()||!ue()&&await q()?k=!0:(k=!1,O=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{k=!1}}return k?await pe("claude",v()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:Y("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:O}}async function _t(){return["opus","sonnet","haiku"]}function je(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:r,args:i}=de(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 Fe(e,t,r){const i=e?.request_id,s=e?.request?.subtype;if(s==="can_use_tool"){const o=t?await t(e.request):Me("deny","This run has no approval surface.");return r(Ne(i,o,e.request)),!0}return r({type:"control_response",response:{subtype:"error",request_id:i,error:`unsupported control request: ${s||"unknown"}`}}),!1}function te({prompt:e,args:t,cwd:r,env:i=null,emit:s,signal:o,harness:n=null,host:a=!1,ask:c=null,peers:u=!0}){const d=v();if(!d)return null;const[y,g,w]=J(d,a?[...t,"--input-format","stream-json"]:t,r,i);return new Promise((_,p)=>{ye().wrap(y,g,w,{engine:"claude",cwd:r,peers:u}).then(T=>{_e(s,T.record);let l;try{l=be(z(T.bin,T.argv,T.opts),T,{kind:"agent"})}catch(m){return p(new Error(`Failed to start claude: ${m.message}`))}const f=me(l,o);let b="",E="",h=!1,C=null;const le={sawText:!1,tail:"",boundary:!1,harnessChars:n};let I="",L=null,A,$=0;const M=()=>{clearTimeout(A),!$&&(A=setTimeout(()=>{l.kill("SIGKILL"),p(new Error(`Claude Code timed out — no output for ${Math.round(X/1e3)}s.`))},X))};M();const ce=m=>{try{l.stdin.write(`${JSON.stringify(m)}
|
|
2
2
|
`)}catch{}};l.stdout.on("data",m=>{M(),b+=m.toString();let W;for(;(W=b.indexOf(`
|
|
3
|
-
`))>=0;){const
|
|
3
|
+
`))>=0;){const B=b.slice(0,W).trim();if(b=b.slice(W+1),!B.startsWith("{"))continue;let S;try{S=JSON.parse(B)}catch{continue}if(S.type==="control_request"){$++,clearTimeout(A),Fe(S,c,ce).catch(()=>{}).finally(()=>{$--,M()});continue}if(S.type==="control_response")continue;const x=oe(S,s,h,r,le);x.streamed&&(h=!0),x.result!=null&&(I=x.result),x.apiError&&(C=x.apiError),x.sessionId&&(L=x.sessionId),a&&S.type==="result"&&l.stdin.end()}}),l.stderr.on("data",m=>{M(),E+=m.toString()}),l.on("error",m=>{clearTimeout(A),f(),p(new Error(`Failed to start claude (${y}): ${m.message}`))}),l.on("close",m=>{if(clearTimeout(A),f(),o?.aborted){_({streamedAny:h,resultText:I,sessionId:L,stopped:!0});return}if(C&&fe(C))return p(new Error(Y("Claude Code","claude")));if(m===0&&C)return p(new Error(`Claude Code reported an error: ${C}`));m===0?_({streamedAny:h,resultText:I,sessionId:L}):p(he("Claude Code",m,E,C||"",{agentId:"claude"}))}),a?l.stdin.write(`${JSON.stringify({type:"user",message:{role:"user",content:e}})}
|
|
4
4
|
`):(l.stdin.write(e),l.stdin.end())}).catch(p)})}function He(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 re(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
|
|
6
6
|
|
|
7
7
|
`}),e.boundary=!1)}function ne(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function oe(e,t,r,i="",s=null){const o={streamed:!1,result:null};if(typeof e?.session_id=="string"&&e.session_id&&(o.sessionId=e.session_id),e.type==="stream_event"){const n=e.event;n?.type==="content_block_delta"&&(n.delta?.type==="text_delta"?(o.streamed=!0,re(s,t),t({type:"delta",text:n.delta.text}),ne(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:Je(n,i)})):n.type==="text"&&!r&&(o.streamed=!0,re(s,t),t({type:"delta",text:n.text}),ne(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:He(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,c=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-c):null,costBasis:"list",...s?.harnessChars!=null?{harnessChars:s.harnessChars}:{}})}}return o}const se=process.env.CHATPANEL_CLAUDE_EFFORT??"low";let N=null;function ae({probe:e=null}={}){return N||(N=(async()=>{try{return String(await(e?e():new Promise(t=>{const[r,i,s]=J(v(),["--help"],null),o=
|
|
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:Je(n,i),...typeof e.parent_tool_use_id=="string"&&e.parent_tool_use_id?{parent:e.parent_tool_use_id}:{}})):n.type==="text"&&!r&&(o.streamed=!0,re(s,t),t({type:"delta",text:n.text}),ne(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:He(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,c=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-c):null,costBasis:"list",...s?.harnessChars!=null?{harnessChars:s.harnessChars}:{}})}}return o}const se=process.env.CHATPANEL_CLAUDE_EFFORT??"low";let N=null;function ae({probe:e=null}={}){return N||(N=(async()=>{try{return String(await(e?e():new Promise(t=>{const[r,i,s]=J(v(),["--help"],null),o=z(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""}})(),N)}async function Ue(e={}){return/--effort\b/.test(await ae(e))}async function qe(e={}){return/--append-system-prompt(?:-file\b|\[-file\])/.test(await ae(e))}function bt(){N=null}async function Be({system:e,options:t,tag:r,resume:i=null,name:s=""}){const o=t.permissionMode||"default",n=F(t.workingDir),a=["--print","--output-format","stream-json","--include-partial-messages","--verbose"];se&&await Ue()&&a.push("--effort",se),a.push(...Te({harness:"claude",roots:we(n),dirs:t.dirs}));const c=[],u=[],d=je(t.mcp);if(d){const l=D.join(P.tmpdir(),`chatpanel-mcp-${r}.json`);await R(l,JSON.stringify(d.config)),c.push(l),a.push("--mcp-config",l),u.push(...d.allowedTools)}const y=De(t.reach);if(y){const l=Re(t.reach,await Ae("claude").catch(()=>[]));a.push("--allowedTools",...y.allow,...u,...l.allow),a.push("--disallowedTools",...y.deny,...l.deny)}else o==="bypassPermissions"?a.push("--permission-mode","bypassPermissions"):o==="acceptEdits"?(a.push("--permission-mode","acceptEdits"),u.length&&a.push("--allowedTools",...u)):a.push("--allowedTools",...V,...u);const g=!y&&t.approvals===!0;if(g&&a.push("--permission-prompt-tool","stdio"),e)if(v()?.kind!=="wsl"&&await qe()){const f=D.join(P.tmpdir(),`chatpanel-system-${r}.md`);await R(f,e,{mode:384}),c.push(f),a.push("--append-system-prompt-file",f)}else a.push("--append-system-prompt",e);t.model&&a.push("--model",t.model),t.useLocalConfig===!1&&a.push("--setting-sources",""),i?a.push(...j({harness:"claude",mode:"resume",id:i})):t.ephemeral===!0&&a.push(...j({harness:"claude",mode:"off"})),t.ephemeral||a.push(...j({harness:"claude",mode:"name",name:s}));const w=d&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(Se(t.mcp?.specs))}:null,_=t.askDepth?{CHATPANEL_ASK_DEPTH:String(Math.max(0,Math.min(8,Number(t.askDepth)||0)))}:null,p=w||_||t.runEnv?{...t.runEnv||{},...w||{},..._||{}}:null;return{args:a,cwd:n,runEnv:p,cleanup:()=>c.forEach(l=>G(l).catch(()=>{})),hasMcp:!!d,approvals:g,peers:!y}}function ie({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 ze(e,t=[],r=""){let i=K(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}const Ge="This Claude Code session is in the middle of a turn in another window (VS Code or a terminal). Send again when it finishes — both sides continue the same session.";async function wt({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=ge("claude",e,r,{cwd:F(r.workingDir)}),a=n?.plan.mode==="resume"?Ee().get(n.plan.sessionId):void 0;if(a==="busy")throw new Error(Ge);if(a){const d=await H({messages:e,system:t,options:r,images:i,thread:n},s,{signal:o});d?.completed&&d.thread?.record(d.sessionId);return}const c=await ve({messages:e,system:t,options:r,images:i,thread:n},s,{signal:o}).catch(d=>({handled:!1,reason:d?.message||String(d),thrown:!0}));if(c.handled){c.completed&&n?.record(c.sessionId);return}if(o?.aborted)return;if(c.thrown)throw new Error(c.reason);const u=await H({messages:e,system:t,options:r,images:i,thread:n},s,{signal:o});u?.completed&&u.thread?.record(u.sessionId)}async function H({messages:e,system:t,options:r,images:i,thread:s=null},o,{signal:n}={}){const a=`${Date.now()}-${Math.random().toString(36).slice(2)}`,c=s?.plan.mode==="resume"?s.plan.sessionId:null,u=await
|
|
10
|
+
The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}const Ge="This Claude Code session is in the middle of a turn in another window (VS Code or a terminal). Send again when it finishes — both sides continue the same session.";async function wt({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=ge("claude",e,r,{cwd:F(r.workingDir)}),a=n?.plan.mode==="resume"?Ee().get(n.plan.sessionId):void 0;if(a==="busy")throw new Error(Ge);if(a){const d=await H({messages:e,system:t,options:r,images:i,thread:n},s,{signal:o});d?.completed&&d.thread?.record(d.sessionId);return}const c=await ve({messages:e,system:t,options:r,images:i,thread:n},s,{signal:o}).catch(d=>({handled:!1,reason:d?.message||String(d),thrown:!0}));if(c.handled){c.completed&&n?.record(c.sessionId);return}if(o?.aborted)return;if(c.thrown)throw new Error(c.reason);const u=await H({messages:e,system:t,options:r,images:i,thread:n},s,{signal:o});u?.completed&&u.thread?.record(u.sessionId)}async function H({messages:e,system:t,options:r,images:i,thread:s=null},o,{signal:n}={}){const a=`${Date.now()}-${Math.random().toString(36).slice(2)}`,c=s?.plan.mode==="resume"?s.plan.sessionId:null,u=await Be({system:t,options:r,tag:a,resume:c,name:s?.thread.title||""}),{args:d,cwd:y,runEnv:g}=u,w=await Oe(i,a),_=()=>{w.forEach(h=>G(h).catch(()=>{})),u.cleanup()},p=ze(c?s.plan.tail||e.slice(-1):e,w);xe(d,r.extraArgs,Ce.claude,o);const T=u.approvals&&r.permissionSession?h=>Pe(r.permissionSession,h):null;let l=!1;const b=te({prompt:p,args:d,cwd:y,env:g,emit:c?h=>{(h?.type==="delta"||h?.type==="tool")&&(l=!0),o(h)}:o,signal:n,harness:ie({prompt:p,system:t,specs:r.mcp?.specs}),host:u.approvals,ask:T,peers:u.peers});if(b===null)return _(),await Ye({messages:e,system:t,options:r},o,{signal:n}),null;let E;try{E=await b}catch(h){if(_(),c&&!l&&!n?.aborted)return s.forget(),H({messages:e,system:t,options:r,images:i,thread:s.restart()},o,{signal:n});throw h}return _(),E.stopped?{completed:!1,thread:s}:(o({type:"done",text:E.streamedAny?"":E.resultText}),{completed:!0,sessionId:E.sessionId,thread:s})}async function Tt({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.","--no-session-persistence"];let s="";const o=te({prompt:e,args:i,cwd:null,peers:!1,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(o===null)return Ke({prompt:e,system:t,model:r});const{resultText:n}=await o;return(s||n||"").trim()}function Je(e,t=""){const r=e.input||{};return r.command?String(r.command).slice(0,60):r.file_path?ke(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 U=null;function q(){return U||(U=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),U}async function Ye({messages:e,system:t,options:r},i,{signal:s}={}){const o=await q();if(!o)throw new Error(O);const{query:n}=o,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const c=r.permissionMode||"default",u=F(r.workingDir),d=c==="acceptEdits"||c==="bypassPermissions",y=new Set(V),g=async f=>y.has(f)||d?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${f} blocked — set this agent's permission mode in ChatPanel to enable it.`};let w=!1;const _=K(e),p={sawText:!1,tail:"",boundary:!1,harnessChars:ie({prompt:_,system:t})};let T="";const l=n({prompt:_,options:{cwd:u,permissionMode:c,includePartialMessages:!0,canUseTool:g,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 f of l){const b=oe(f,i,w,u,p);b.streamed&&(w=!0),b.result!=null&&(T=b.result)}}catch(f){if(s?.aborted||a.signal.aborted)return;throw f}i({type:"done",text:w?"":T})}async function Ke({prompt:e,system:t,model:r}){const i=await q();if(!i)throw new Error(O);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 c of a.message.content)c.type==="text"&&(o+=c.text);else a.type==="result"&&a.subtype==="success"&&!o&&(o=a.result||"");return o.trim()}export{Ge as SESSION_BUSY,bt as _resetEffortProbe,Fe as answerControlRequest,yt as available,Be as buildClaudeLaunch,Re as channelMcpTools,De as channelToolPolicy,wt as chat,H as chatCold,je as claudeMcpConfig,ze as claudePrompt,Ue as claudeSupportsEffort,qe as claudeSupportsSystemPromptFile,Tt as complete,oe as handleMessage,ie as harnessChars,_t as listModels,Oe as writeImages};
|
package/src/engines/codex.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{spawn as R}from"node:child_process";import{killOnAbort as W,spawnGroupOpts as q}from"../proc.js";import{track as z,sandbox as G,noteSandbox as K,grantedWriteRoots as U}from"../sandbox.js";import{harnessDirArgs as Z,harnessSessionArgs as j}from"../events/harness-cards.js";import{threadTurn as Q}from"../threads.js";import{readFile as V,unlink as T,writeFile as Y}from"node:fs/promises";import{existsSync as P,mkdirSync as ee,symlinkSync as te,readFileSync as M}from"node:fs";import $ from"node:os";import g from"node:path";import{agentAvailable as re,selfMcpStdio as oe,resolveCommand as se}from"../env.js";import{relayTimeoutMax as ne}from"../relay-timeout.js";import{buildCliPrompt as ae}from"./prompt.js";import{pushExtraArgs as ce,FORBIDDEN as ie}from"./args.js";import{resolveWorkdir as B}from"../workdir.js";import{
|
|
2
|
-
`))>=0;){const A=y.slice(0,h).trim();if(y=y.slice(h+1),!!A.startsWith("{"))try{be(JSON.parse(A),b,w)}catch{}}}),f.stderr.on("data",m=>{S(),I+=m.toString()}),f.on("error",m=>{clearTimeout(_),v(),u(m)}),f.on("close",async m=>{clearTimeout(_),v();let h="";try{h=(await V(n,"utf8")).trim()}catch{}T(n).catch(()=>{}),l({code:m,stderr:I,text:h,streamed:k,said:!!w.saidAny,policyBlocked:!!w.policyBlocked,threadId:w.threadId||null})}),f.stdin.write(e),f.stdin.end()})}async function Ge({messages:s,system:o,options:t,images:c},e,{signal:n}={}){const i=Q("codex",s,t,{cwd:B(t.workingDir)}),r=await he({messages:s,system:o,options:t,images:c,thread:i},e,{signal:n}).catch(l=>({handled:!1,reason:l?.message||String(l),thrown:!0}));if(r.handled){r.completed&&(r.thread||i)?.record(r.sessionId);return}if(n?.aborted)return;if(r.thrown)throw new Error(r.reason);const a=await J({messages:s,system:o,options:t,images:c,thread:i},e,{signal:n});a?.completed&&a.thread?.record(a.sessionId)}async function J({messages:s,system:o,options:t,images:c,thread:e=null},n,{signal:i}={}){const r=e?.plan.mode==="resume"?e.plan.sessionId:null,a=`${Date.now()}-${Math.random().toString(36).slice(2)}`,l=g.join($.tmpdir(),`chatpanel-codex-${a}.txt`),u=await $e(c,a),f=()=>u.forEach(d=>T(d).catch(()=>{})),v=B(t.workingDir),y=[];ce(y,t.extraArgs,ie.codex,n);const I=(d,x=!0)=>{const p=["exec","--json","--skip-git-repo-check","-o",l];if(t.permissionMode==="bypassPermissions")p.push("--dangerously-bypass-approvals-and-sandbox");else if(!x)p.push("-s","danger-full-access"),
|
|
1
|
+
import{spawn as R}from"node:child_process";import{killOnAbort as W,spawnGroupOpts as q}from"../proc.js";import{track as z,sandbox as G,noteSandbox as K,grantedWriteRoots as U}from"../sandbox.js";import{harnessDirArgs as Z,harnessSessionArgs as j}from"../events/harness-cards.js";import{threadTurn as Q}from"../threads.js";import{readFile as V,unlink as T,writeFile as Y}from"node:fs/promises";import{existsSync as P,mkdirSync as ee,symlinkSync as te,readFileSync as M}from"node:fs";import $ from"node:os";import g from"node:path";import{agentAvailable as re,selfMcpStdio as oe,resolveCommand as se}from"../env.js";import{relayTimeoutMax as ne}from"../relay-timeout.js";import{buildCliPrompt as ae}from"./prompt.js";import{pushExtraArgs as ce,FORBIDDEN as ie}from"./args.js";import{resolveWorkdir as B}from"../workdir.js";import{cliError as de}from"../cli-errors.js";import{signInStatus as le,signInMessage as pe}from"../sign-in.js";import{disabledMcpServers as ue,planMcpRetry as fe,quarantine as me}from"../mcp-quarantine.js";import{chatWarm as he}from"./codex-appserver.js";const F=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,H=process.env.CHATPANEL_CODEX_EFFORT??"low",ge=["gpt-5-codex","gpt-5","o3","o4-mini"];let O=!1;function We(){O=!1}async function qe(){const s=new Set;try{const o=process.env.CODEX_HOME||g.join($.homedir(),".codex"),t=M(g.join(o,"config.toml"),"utf8");for(const c of t.matchAll(/(?:^|\n)\s*model\s*=\s*["']([^"'\n]+)["']/g))s.add(c[1].trim())}catch{}for(const o of ge)s.add(o);return[...s]}const N=g.join($.homedir(),".chatpanel","codex-home");let L=!1;function ye(){if(!L)try{ee(N,{recursive:!0});const s=g.join($.homedir(),".codex","auth.json"),o=g.join(N,"auth.json");if(P(s)&&!P(o))try{te(s,o)}catch{}L=!0}catch{return null}return N}let E=!1,X=0;async function ze(){if(Date.now()-X>(E?3e4:4e3)){X=Date.now();try{E=re("codex")}catch{E=!1}}return E?await le("codex",se("codex")).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:pe("Codex","codex")}:{ok:!0}:{ok:!1,reason:"codex not found on PATH. Install it and run `codex login`."}}function xe(s){if(!s?.url)return[];const o=s.serverName||"chatpanel_browser",{command:t,args:c}=oe(s.url),e=["-c",`mcp_servers.${o}.command=${JSON.stringify(t)}`,"-c",`mcp_servers.${o}.args=${JSON.stringify(c)}`,"-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(ne(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 we(s){try{const o=M(g.join(s,"config.toml"),"utf8"),t=new Set;for(const c of o.matchAll(/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*[.\]]/gm))t.add(c[1]);return t}catch{return new Set}}function _e(s){const o=new Set;try{const t=M(g.join(s,"config.toml"),"utf8"),c=/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*\]\s*$([\s\S]*?)(?=^\s*\[|$(?![\r\n]))/gm;for(const e of t.matchAll(c)){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 Se(s=[]){return s.flatMap(o=>["-c",`mcp_servers.${o}.enabled=false`])}async function $e(s,o){const t=[];for(let c=0;c<(s?.length||0);c++){const e=/^data:([^;]+);base64,(.+)$/s.exec(s[c]?.dataUrl||"");if(!e)continue;const n=(e[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",i=g.join($.tmpdir(),`chatpanel-codex-img-${o}-${c}.${n}`);await Y(i,Buffer.from(e[2],"base64")),t.push(i)}return t}async function ve({argsFor:s,readOnly:o=!1,cwd:t,env:c,prompt:e,outFile:n,emit:i,signal:r}){const a=await G().wrapOwn("codex",s,{cwd:t,stdio:["pipe","pipe","pipe"],env:c,...q},{engine:"codex",cwd:t,readOnly:o});return K(i,a.record),new Promise((l,u)=>{let f;try{f=z(R(a.bin,a.argv,a.opts),a,{kind:"agent"})}catch(m){return u(new Error(`Failed to start codex: ${m.message}`))}const v=W(f,r);let y="",I="",k=!1;const b=m=>{m?.type!=="status"&&(k=!0),i(m)},w={started:new Set,reasoned:new Set,n:0};let _;const S=()=>{clearTimeout(_),_=setTimeout(()=>{f.kill("SIGKILL"),u(new Error(`Codex timed out — no output for ${Math.round(F/1e3)}s.`))},F)};S(),f.stdout.on("data",m=>{S(),y+=m.toString();let h;for(;(h=y.indexOf(`
|
|
2
|
+
`))>=0;){const A=y.slice(0,h).trim();if(y=y.slice(h+1),!!A.startsWith("{"))try{be(JSON.parse(A),b,w)}catch{}}}),f.stderr.on("data",m=>{S(),I+=m.toString()}),f.on("error",m=>{clearTimeout(_),v(),u(m)}),f.on("close",async m=>{clearTimeout(_),v();let h="";try{h=(await V(n,"utf8")).trim()}catch{}T(n).catch(()=>{}),l({code:m,stderr:I,text:h,streamed:k,said:!!w.saidAny,policyBlocked:!!w.policyBlocked,threadId:w.threadId||null})}),f.stdin.write(e),f.stdin.end()})}async function Ge({messages:s,system:o,options:t,images:c},e,{signal:n}={}){const i=Q("codex",s,t,{cwd:B(t.workingDir)}),r=await he({messages:s,system:o,options:t,images:c,thread:i},e,{signal:n}).catch(l=>({handled:!1,reason:l?.message||String(l),thrown:!0}));if(r.handled){r.completed&&(r.thread||i)?.record(r.sessionId);return}if(n?.aborted)return;if(r.thrown)throw new Error(r.reason);const a=await J({messages:s,system:o,options:t,images:c,thread:i},e,{signal:n});a?.completed&&a.thread?.record(a.sessionId)}async function J({messages:s,system:o,options:t,images:c,thread:e=null},n,{signal:i}={}){const r=e?.plan.mode==="resume"?e.plan.sessionId:null,a=`${Date.now()}-${Math.random().toString(36).slice(2)}`,l=g.join($.tmpdir(),`chatpanel-codex-${a}.txt`),u=await $e(c,a),f=()=>u.forEach(d=>T(d).catch(()=>{})),v=B(t.workingDir),y=[];ce(y,t.extraArgs,ie.codex,n);const I=(d,x=!0)=>{const p=["exec","--json","--skip-git-repo-check","-o",l];if(t.permissionMode==="bypassPermissions")p.push("--dangerously-bypass-approvals-and-sandbox");else if(!x)p.push("-s","danger-full-access"),O||p.push("-c","approval_policy=never");else{const C=t.permissionMode==="acceptEdits"?"workspace-write":"read-only";p.push("-s",C),p.push(...Z({harness:"codex",roots:U(v),dirs:t.dirs})),O||p.push("-c","approval_policy=never")}H&&p.push("-c",`model_reasoning_effort=${H}`),p.push("-c","model_reasoning_summary=auto"),p.push(...xe(t.mcp)),p.push(...Se(d)),t.model&&p.push("-m",t.model),p.push(...y);for(const C of u)p.push("-i",C);return r?p.push(...j({harness:"codex",mode:"resume",id:r})):t.ephemeral===!0&&p.splice(1,0,...j({harness:"codex",mode:"off"})),p.push("-"),p},k=t.useLocalConfig!==!1,b={...process.env,...t.runEnv||{}};if(!k){const d=ye();d&&(b.CODEX_HOME=d)}const w=t.mcp?.serverName||"chatpanel_browser",_=b.CODEX_HOME||process.env.CODEX_HOME||g.join($.homedir(),".codex"),S=we(_),m=(t.mcp?.specs||[]).length>0;let h=[...new Set([...ue("codex",t,[w]),...m?_e(_):[]])].filter(d=>S.has(d));const A=ae(r?e.plan.tail||s.slice(-1):s,o),D=()=>ve({argsFor:d=>I(h,d),readOnly:t.permissionMode!=="acceptEdits"&&t.permissionMode!=="bypassPermissions",cwd:v,env:b,prompt:A,outFile:l,emit:n,signal:i});try{let d=await D();if(d.policyBlocked&&(O=!0),!i?.aborted&&d.code!==0&&!d.streamed){const x=fe({agent:"codex",text:d.stderr,protect:[w],already:h});x&&S.has(x.server)&&(me("codex",x.server),n({type:"status",text:`MCP server "${x.server}" failed to load — ${x.short}. Skipping it and retrying.`}),h=[...h,x.server],d=await D())}if(i?.aborted)return null;if(r&&d.code!==0&&!d.streamed)return e.forget(),f(),J({messages:s,system:o,options:t,images:c,thread:e.restart()},n,{signal:i});if(d.code!==0)throw de("Codex",d.code,d.stderr,"",{agentId:"codex"});return d.said||n({type:"delta",text:d.text||"(no output)"}),n({type:"done",text:""}),{completed:!0,sessionId:d.threadId||r,thread:e}}finally{f()}}function be(s,o,t={started:new Set,reasoned:new Set,n:0}){const c=s.type||"";c==="thread.started"&&typeof s.thread_id=="string"&&(t.threadId=s.thread_id);const e=s.item||{},n=e.type||"",i=c==="item.completed"||e.status==="completed"||e.status==="failed";if(n==="agent_message"&&i){const r=e.id||`msg_${t.n++}`,a=String(e.text||"");a&&!t.said?.has(r)&&((t.said||=new Set).add(r),o({type:"delta",text:`${t.saidAny?`
|
|
3
3
|
|
|
4
4
|
`:""}${a}`}),t.saidAny=!0);return}if(n==="command_execution"||!n&&c.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 a=e.exit_code===0||e.exit_code==null;o({type:"tool",name:"shell",phase:"done",callId:r,status:a?"ok":`exit ${e.exit_code}`,result:String(e.aggregated_output||"").slice(0,4e3)})}return}if(n==="file_change"||!n&&c.includes("patch")){const r=e.id||`edit_${t.n++}`,a=Array.isArray(e.changes)?e.changes.map(l=>l.path||l.file).filter(Boolean):[];t.started.has(r)||(t.started.add(r),o({type:"tool",name:"edit",phase:"start",callId:r,input:{files:a}})),i&&o({type:"tool",name:"edit",phase:"done",callId:r,status:"ok"});return}if(n==="web_search"){const r=e.id||`ws_${t.n++}`,a=e.action&&typeof e.action=="object"?e.action:{},l=e.query||a.query||"",u=a.url||"";t.started.has(r)||(t.started.add(r),o({type:"tool",name:"web_search",phase:"start",callId:r,input:{query:l,...u?{url:u}:{}}})),(i||c==="item.completed")&&o({type:"tool",name:"web_search",phase:"done",callId:r,status:"ok",result:u?`Opened ${u}`:l?`Searched the web for ${l}`:"Searched the web"});return}if(n==="mcp_tool_call"){const r=e.id||`mcp_${t.n++}`,a=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(t.started.has(r)||(t.started.add(r),o({type:"tool",name:a,phase:"start",callId:r,input:e.arguments&&typeof e.arguments=="object"?e.arguments:{}})),i){const l=e.status==="failed"||e.error!=null,u=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error,f=e.result==null?"":typeof e.result=="string"?e.result:JSON.stringify(e.result);o({type:"tool",name:a,phase:"done",callId:r,status:l?`error: ${String(u||"failed").slice(0,80)}`:"ok",result:String(l?u||"":f).slice(0,4e3)})}return}if(n==="todo_list"&&Array.isArray(e.items)&&e.items.length){const r=e.items.map(a=>`${a.completed?"☑":"☐"} ${a.text||""}`).join(`
|
|
5
5
|
`);t.lastTodo!==r&&(t.lastTodo=r,o({type:"status",text:`Plan:
|
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 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
|
|
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
|
|
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";import{cliError as pt}from"../cli-errors.js";async function dt(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 ft(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,gt="http://127.0.0.1:4319/mcp",j="http://127.0.0.1:4319/mcp";async function Wt(){return{ok:!0}}function ht(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 Xt(t={}){if(!await D(t.entitlement))throw new Error("Custom agents require ChatPanel Pro.");const n=t.custom||{};return wt(n.command,n.listModelsArgs,t.workingDir)}async function wt(t,n,e){const r=String(n||"").trim();if(!t||!r)return[];const o=await St(t,r.split(/\s+/).filter(Boolean),e);return ht(o)}async function St(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 yt(t,n){return["--extension",t]}function Ct(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 $t(t={},n){return t.trustAllToolsForMcp?[t.trustAllToolsArg||"--trust-all-tools"]:t.trustToolsArg?Ct(t.trustToolsArg,n):[]}function bt(t={}){return t.stableMcpSetupCommand?t.stableMcpSetupCommand:`opencode mcp add chatpanel --url ${j}`}function At(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 xt(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)},
|
|
@@ -65,7 +65,7 @@ ${e}
|
|
|
65
65
|
export default function (pi: ExtensionAPI) {
|
|
66
66
|
${r}
|
|
67
67
|
}
|
|
68
|
-
`}async function
|
|
68
|
+
`}async function Mt(t,n){const e=x.join(T.tmpdir(),`chatpanel-pi-tools-${n}.ts`);return await k(e,xt(t)),e}async function Tt(){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(gt))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 Et(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 Ot(t,n){const e=await K(t,["mcp","list"],n);return e.includes(j)||/chatpanel_browser/i.test(e)}async function Pt(t,n){return t.stableMcpConfigCheck==="kiro"?Et(t.command||"kiro-cli",n):t.stableMcpConfigCheck==="opencode"?Tt():t.stableMcpConfigCheck==="hermes"?Ot(t.command||"hermes",n):!1}async function vt(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 kt(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 Lt(t,n,e,r,o={}){if(!t.requiresStableMcp)return!0;const s=o.hasConfig||Pt,d=o.runSetup||vt;if(await s(t,n))return!0;const f=bt(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=At(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 Qt({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 _t(e.custom||{},{messages:t,system:n,options:e,images:r},o,{signal:s})}async function _t(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 dt(o,h):[],l=[],M=()=>[...S,...l].forEach(a=>Y(a).catch(()=>{}));if(r.mcp?.url&&t.toolAdapter==="pi-extension"){const a=await Mt(r.mcp,h);l.push(a),i=[...yt(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 Lt(t,y,m,s)}catch(a){s({type:"status",text:`${m}: continuing without ChatPanel's browser tools — ${kt(m,a)}`}),r={...r,mcp:null}}if(r.mcp?.url&&i.push(...$t(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=ft(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(pt(m,A,b))}),u==="stdin"&&p.stdin.write(g),p.stdin.end()})}export{j as CHATPANEL_STABLE_MCP_URL,Wt as available,xt as buildPiExtensionSource,Qt as chat,K as commandOutput,Lt as ensureStableMcpConfig,Xt as listModels,wt as listSpecModels,kt as mcpSetupHint,$t as mcpTrustArgs,yt as piToolArgs,St as runForStdout,_t as runSpec,bt as stableMcpSetupCommand,At as stableMcpSetupPlan,Ct as trustToolArgs};
|
package/src/env.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import f from"node:os";import{spawnGroupOpts as O}from"./proc.js";import s from"node:path";import{spawnSync as b}from"node:child_process";import{readdirSync as h,readFileSync as _,existsSync as u}from"node:fs";let N=!1,y=!1;const D=["codex","claude","agy","pi","opencode","kiro-cli","copilot","dsh"];function J(n){return d(process.env.PATH||"",process.platform).some(o=>o&&(u(s.join(o,n))||u(s.join(o,n+".exe"))))}function Z(n){const t=R(n);if(t)return t;if(k()){const o=R(n);if(o)return o}return sn(n)||null}function Hn(n){return!!v(n)}function R(n){for(const t of q(n))if(u(t))return t;return null}function g(){const n=s.basename(process.execPath).toLowerCase();return!(n.startsWith("node")||n.startsWith("bun"))}function On(n){const t=["--mcp-stdio",n];if(g())return{command:process.execPath,args:t};const o=process.argv[1]||s.join(process.cwd(),"src","server.js"),i=process.env.CHATPANEL_BRIDGE_EMBEDDED==="1"?["--bridge"]:[];return{command:process.execPath,args:[o,...i,...t]}}const m="CHATPANEL_ENV",$=6e3;function x(n){for(const t of String(n||"").split(/\r?\n/)){const o=t.indexOf(" ");if(o>0&&t.slice(0,o).trim().endsWith(m))return t.slice(o+1).trim()}return""}function nn(n){return/^[\w.+-]+$/.test(String(n||""))}function E(){if(process.env.SHELL)return process.env.SHELL;try{const{shell:n}=f.userInfo();if(n&&n!=="/usr/bin/false"&&n!=="/sbin/nologin")return n}catch{}return"/bin/sh"}function W(n,{interactive:t}={}){if(process.platform==="win32")return"";try{const o=t?["-l","-i","-c"]:["-l","-c"];return b(E(),[...o,n],{encoding:"utf8",timeout:$,stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}}).stdout||""}catch{return""}}function tn(n){let t="";for(const o of String(n||"").split(/\r?\n/))o.startsWith("PATH=")&&(t=o.slice(5).trim());return t}function on({interactive:n=!0,ask:t=W}={}){const o=x(t(`command -p printf '%s\\t%s\\n' ${m} "$PATH"`,{interactive:n}));return d(o||tn(t("/usr/bin/env",{interactive:n})),process.platform)}const C=1e4,en=3e5;let S=0,P=C;function k({force:n=!1,now:t=Date.now(),read:o=on,env:i=process.env}={}){if(process.platform==="win32"||!n&&t-S<P)return!1;S=t;const e=d(i.PATH||"",process.platform),r=L(j([...o({interactive:!0}),...e])),c=r.length>e.length;return P=c?C:Math.min(P*2,en),c?(i.PATH=r.join(s.delimiter),!0):!1}function Nn(){S=0,P=C,T.clear()}const T=new Map,rn=15e3;function sn(n){if(process.platform==="win32"||!nn(n))return"";const t=T.get(n);if(t&&(t.bin||Date.now()-t.at<rn))return t.bin;const o=[`command -p printf '%s\\t%s\\n' ${m} "$(command -v ${n} 2>/dev/null)"`,`type -p ${n}`];let i="";for(const e of[!1,!0]){for(const r of o){const c=W(r,{interactive:e}),l=x(c)||String(c||"").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.startsWith("/")).pop()||"";if(l.startsWith("/")&&u(l)){i=l;break}}if(i)break}return T.set(n,{bin:i,at:Date.now()}),i}function yn(){return process.env.CHATPANEL_CLAUDE_PATH?v(process.env.CHATPANEL_CLAUDE_PATH):v("claude")}function v(n){if(!n)return null;if(n.includes("/")||n.includes("\\")||/\.[a-z0-9]+$/i.test(n)){if(!u(n))return null;const i=s.extname(n).toLowerCase();return!g()&&/^\.(c?js|mjs)$/.test(i)?{kind:"script",script:n}:process.platform==="win32"&&(i===".cmd"||i===".bat")?{kind:"cmd",bin:n}:process.platform==="win32"&&i===""&&!Q(n)?null:{kind:"native",bin:n}}if(process.platform==="win32"){const i=bn(n);return i||(/^[\w.-]+$/.test(n)&&Pn(n)?{kind:"wsl",command:n}:null)}const o=Z(n);return o?{kind:"native",bin:o}:null}const cn="HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",ln="HKCU\\Environment",an=4e3;let V=0;function un(n,t="Path"){const o=String(t).toLowerCase();for(const i of String(n||"").split(/\r?\n/)){const e=/^\s*(\S+)\s+REG_(?:EXPAND_)?SZ\s+(.*?)\s*$/.exec(i);if(e&&e[1].toLowerCase()===o)return e[2]}return""}function B(n,t=process.env){const o=new Map(Object.keys(t||{}).map(i=>[i.toLowerCase(),t[i]]));return String(n||"").replace(/%([^%]+)%/g,(i,e)=>{const r=o.get(String(e).toLowerCase());return r==null?i:String(r)})}function pn(n,t){try{const o=s.win32.join(process.env.SystemRoot||"C:\\Windows","System32","reg.exe"),i=b(u(o)?o:"reg",["query",n,"/v",t],{encoding:"utf8",timeout:3e3,windowsHide:!0});return i.status===0?un(i.stdout,t):""}catch{return""}}function dn({query:n=pn,env:t=process.env}={}){const o=B(n(cn,"Path"),t),i=B(n(ln,"Path"),t);return j([...d(o,"win32"),...d(i,"win32")])}function fn({run:n=jn}={}){const t=n(`[Console]::Out.Write("${m}\`t" + $env:PATH + "\`n")`);return d(x(t),"win32")}function jn(n){for(const t of["pwsh.exe","powershell.exe"])try{const o=b(t,["-NoLogo","-NonInteractive","-ExecutionPolicy","Bypass","-Command",n],{encoding:"utf8",timeout:$,stdio:["ignore","pipe","ignore"],windowsHide:!0}),i=M(o.stdout||"");if(i)return i}catch{}return""}function F({force:n=!1,now:t=Date.now(),registry:o=dn,profile:i=fn,env:e=process.env,home:r=f.homedir()}={}){if(process.platform!=="win32"&&!n||!n&&t-V<an)return!1;V=t;const c=d(e.PATH||"","win32"),l=j([...c,...o({env:e}),...H(r,"win32",e)]);D.some(p=>!l.some(A=>u(s.win32.join(A,`${p}.cmd`))||u(s.win32.join(A,`${p}.exe`))))&&l.push(...i());const a=L(j(l),"win32");return a.length===c.length?!1:(e.PATH=a.join(I("win32")),!0)}function bn(n){return K(n)||(F()?K(n):null)}function K(n){const t=w("win32");for(const o of q(n,f.homedir(),"win32",process.env)){if(!u(o))continue;const i=t.dirname(o),e=t.extname(o).toLowerCase(),r=n==="claude"&&An(i)||hn(i,n)||(/^\.(c?js|mjs)$/.test(e)?o:null);if(r){if(!g())return{kind:"script",script:r};const c=wn(i);if(c)return{kind:"script",script:r,runtime:c}}if(e===".exe")return{kind:"native",bin:o};if(e===".cmd"||e===".bat")return{kind:"cmd",bin:o};if(e===""&&Q(o))return{kind:"native",bin:o}}return null}function wn(n,{env:t=process.env,exists:o=u}={}){const i=s.win32,e=j([n,...d(t.PATH||"","win32"),...t.NVM_SYMLINK?[t.NVM_SYMLINK]:[],i.join(t.ProgramFiles||"C:\\Program Files","nodejs")]);for(const r of e){const c=i.join(r,"node.exe");if(o(c))return c}return null}function An(n){const t=[["node_modules","@anthropic-ai","claude-code","cli.js"],["..","node_modules","@anthropic-ai","claude-code","cli.js"],["..","lib","node_modules","@anthropic-ai","claude-code","cli.js"]];for(const o of t){const i=s.join(n,...o);if(u(i))return i}return null}function hn(n,t){for(const o of[`${t}.cmd`,t,`${t}.ps1`]){let i;try{i=_(s.join(n,o),"utf8")}catch{continue}const e=i.match(/(?:%~?dp0%|\$basedir|\$\{basedir\})[\\/]+([^"'\s]+\.[cm]?js)/i);if(e){const r=s.join(n,e[1].replace(/[\\/]+/g,s.sep));if(u(r))return r}}return null}const Y=new Map,mn=15e3;function Pn(n){const t=Y.get(n);if(t&&(t.ok||Date.now()-t.at<mn))return t.ok;let o=!1;try{const i=b("wsl.exe",["-e","bash","-lic",`command -v ${n}`],{encoding:"utf8",timeout:8e3,windowsHide:!0});o=i.status===0&&/\S/.test(M(i.stdout||""))}catch{o=!1}return Y.set(n,{ok:o,at:Date.now()}),o}function Dn(n,t,o,i=null){const e=i&&typeof i=="object"&&Object.keys(i).length?{...process.env,...i}:process.env;if(n.kind==="wsl"){const c=[];if(o){const a=_n(o);a&&c.push("--cd",a)}return["wsl.exe",[...c,"-e","bash","-lic",`exec ${n.command} "$@"`,"chatpanel",...t],{stdio:["pipe","pipe","pipe"],env:e,windowsHide:!0,...O}]}const r={cwd:o||f.homedir(),stdio:["pipe","pipe","pipe"],env:e,windowsHide:!0,...O};return n.kind==="script"?[n.runtime||process.execPath,[n.script,...t],r]:n.kind==="cmd"?["cmd.exe",["/d","/s","/c",n.bin,...t],r]:[n.bin,t,r]}function _n(n){try{const t=b("wsl.exe",["-e","wslpath","-a",n],{encoding:"utf8",timeout:5e3,windowsHide:!0}),o=M(t.stdout||"").trim();return o.startsWith("/")?o:null}catch{return null}}function M(n){return n.replace(/^/,"").trim()}function gn(n=f.homedir(),t=process.env){const o=s.join(t.NVM_DIR||s.join(n,".nvm"),"versions","node");let i;try{i=h(o).filter(r=>/^v\d+\./.test(r))}catch{return null}if(!i.length)return null;const e=(r,c)=>{const l=r.slice(1).split(".").map(Number),a=c.slice(1).split(".").map(Number);for(let p=0;p<3;p+=1)if((l[p]||0)!==(a[p]||0))return(a[p]||0)-(l[p]||0);return 0};try{const r=_(s.join(t.NVM_DIR||s.join(n,".nvm"),"alias","default"),"utf8").trim(),c=r.startsWith("v")?r:`v${r}`;if(i.includes(c))return s.join(o,c,"bin")}catch{}return s.join(o,i.sort(e)[0],"bin")}function xn(n,t=process.env){return[s.join(t.MISE_DATA_DIR||s.join(n,".local","share","mise"),"shims"),s.join(n,".local","share","rtx","shims"),s.join(t.ASDF_DATA_DIR||s.join(n,".asdf"),"shims"),s.join(t.PYENV_ROOT||s.join(n,".pyenv"),"shims"),s.join(t.RBENV_ROOT||s.join(n,".rbenv"),"shims"),s.join(t.NODENV_ROOT||s.join(n,".nodenv"),"shims"),s.join(t.PROTO_HOME||s.join(n,".proto"),"shims"),s.join(t.PROTO_HOME||s.join(n,".proto"),"bin"),s.join(t.VOLTA_HOME||s.join(n,".volta"),"bin")]}function En(n,t=process.env){const o=[],i=(e,r)=>{try{for(const c of h(e))o.push(s.join(e,c,r))}catch{}};return i(s.join(t.NVM_DIR||s.join(n,".nvm"),"versions","node"),"bin"),i(s.join(n,".local","share","fnm","node-versions"),s.join("installation","bin")),i(s.join(n,"Library","Application Support","fnm","node-versions"),s.join("installation","bin")),i(s.join(t.MISE_DATA_DIR||s.join(n,".local","share","mise"),"installs","node"),"bin"),o}function w(n){return n==="win32"?s.win32:s}function I(n){return n==="win32"?";":s.delimiter}function d(n,t){return(n||"").split(I(t)).filter(Boolean)}function j(n){return[...new Set(n.filter(Boolean))]}const G={win32:3e4,other:65536};function L(n,t=process.platform){const o=t==="win32"?G.win32:G.other,i=I(t),e=[];let r=0;for(const c of n){const l=c.length+(e.length?i.length:0);if(r+l>o)break;e.push(c),r+=l}return e}function H(n,t=process.platform,o=process.env){const i=w(t);if(t==="win32"){const e=o.APPDATA||i.join(n,"AppData","Roaming"),r=o.LOCALAPPDATA||i.join(n,"AppData","Local"),c=o.ProgramFiles||"C:\\Program Files",l=o["ProgramFiles(x86)"]||"C:\\Program Files (x86)",a=o.ProgramData||"C:\\ProgramData";return[i.join(n,".local","bin"),i.join(n,".codex","bin"),i.join(n,".claude","bin"),i.join(n,".claude","local"),i.join(n,".claude","local","bin"),i.join(e,"npm"),...o.NVM_SYMLINK?[o.NVM_SYMLINK]:[],i.join(c,"nodejs"),...Cn(e,r),i.join(r,"pnpm"),i.join(r,"Yarn","bin"),i.join(r,"Volta","bin"),i.join(n,".yarn","bin"),i.join(n,".bun","bin"),i.join(n,".deno","bin"),i.join(o.SCOOP||i.join(n,"scoop"),"shims"),i.join(a,"chocolatey","bin"),i.join(r,"Microsoft","WindowsApps"),i.join(r,"Microsoft","WinGet","Links"),i.join(o.MISE_DATA_DIR||i.join(r,"mise"),"shims"),i.join(o.PROTO_HOME||i.join(n,".proto"),"shims"),i.join(o.PROTO_HOME||i.join(n,".proto"),"bin"),i.join(r,"Programs","Claude Code"),i.join(r,"Anthropic","Claude Code"),i.join(c,"Claude Code"),i.join(c,"Anthropic","Claude Code"),i.join(l,"Claude Code"),i.join(l,"Anthropic","Claude Code")]}return[s.join(n,".local","bin"),s.join(n,".opencode","bin"),s.join(n,".codex","bin"),s.join(n,".claude","bin"),s.join(n,".claude","local"),s.join(n,".claude","local","bin"),o.PNPM_HOME||s.join(n,"Library","pnpm"),s.join(n,".local","share","pnpm"),s.join(n,".nix-profile","bin"),"/nix/var/nix/profiles/default/bin",s.join(n,".guix-profile","bin"),"/home/linuxbrew/.linuxbrew/bin","/snap/bin",...xn(n,o)]}function Cn(n,t){const o=s.win32,i=[];for(const e of[o.join(t,"fnm"),o.join(n,"fnm")]){let r=[];try{r=h(o.join(e,"node-versions")).filter(c=>/^v?\d+\.\d+\.\d+/.test(c)).sort((c,l)=>l.localeCompare(c,void 0,{numeric:!0}))}catch{}for(const c of r)i.push(o.join(e,"node-versions",c,"installation"))}return i}function U(n,t=process.platform){const o=w(t),i=o.join(n,".local","share","claude","versions");let e=[];try{e=h(i).filter(r=>/^\d+\.\d+\.\d+/.test(r)).sort((r,c)=>c.localeCompare(r,void 0,{numeric:!0}))}catch{}return e.map(r=>o.join(i,r))}function X(n,t){return t!=="win32"?[n]:/\.(cmd|exe|bat|ps1)$/i.test(n)?[n]:[`${n}.exe`,`${n}.cmd`,`${n}.bat`,n,`${n}.ps1`]}function Q(n,t=_){try{const o=t(n).subarray(0,2);return o.length===2&&o[0]===77&&o[1]===90}catch{return!1}}function Sn(n,t=f.homedir(),o=process.platform,i=process.env){const e=w(o),r=e.join(t,".local","bin",n),c=o==="win32"?i.LOCALAPPDATA||e.join(t,"AppData","Local"):null,l=o==="win32"?i.ProgramFiles||"C:\\Program Files":null,a=o==="win32"?i["ProgramFiles(x86)"]||"C:\\Program Files (x86)":null,p={claude:[r,e.join(t,".claude","bin","claude"),e.join(t,".claude","local","claude"),e.join(t,".claude","local","bin","claude"),...o==="win32"?[e.join(c,"Microsoft","WindowsApps","claude.exe"),e.join(c,"Programs","Claude Code","claude.exe"),e.join(c,"Anthropic","Claude Code","claude.exe"),e.join(l,"Claude Code","claude.exe"),e.join(l,"Anthropic","Claude Code","claude.exe"),e.join(a,"Claude Code","claude.exe"),e.join(a,"Anthropic","Claude Code","claude.exe"),...U(t,o)]:U(t,o)],codex:[r,e.join(t,".codex","bin","codex")],agy:[r,"/Applications/Antigravity.app/Contents/MacOS/agy","/Applications/Antigravity IDE.app/Contents/MacOS/agy"],pi:[r],opencode:[e.join(t,".opencode","bin","opencode"),r],"kiro-cli":[r,"/Applications/Kiro CLI.app/Contents/MacOS/kiro-cli"]};return j((p[n]||[r]).flatMap(A=>X(A,o)))}function q(n,t=f.homedir(),o=process.platform,i=process.env){const e=w(o),r=j([...d(i.PATH||"",o),...H(t,o,i)]).flatMap(c=>X(e.join(c,n),o));return j([...r,...Sn(n,t,o,i)])}const z=["DEEPSEEK_API_KEY","DSH_HOME","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","GEMINI_API_KEY","GOOGLE_API_KEY","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"];function Rn(){if(y||(y=!0,process.platform==="win32"))return;const n=z.filter(t=>!process.env[t]);if(n.length)try{const t=E(),o=`${n.map(e=>`[ -n "\${${e}:-}" ] && printf '%s\\t%s\\n' ${e} "$${e}"`).join("; ")}; true`,i=b(t,["-l","-i","-c",o],{encoding:"utf8",timeout:6e3,env:{...process.env,TERM:"dumb"}});for(const e of String(i.stdout||"").split(`
|
|
2
|
-
`)){const r=
|
|
1
|
+
import m from"node:os";import{spawnGroupOpts as F}from"./proc.js";import s from"node:path";import{spawn as ln,spawnSync as w}from"node:child_process";import{readdirSync as E,readFileSync as y,existsSync as p}from"node:fs";let Y=!1,G=!1;const O=["codex","claude","agy","pi","opencode","kiro-cli","copilot","dsh"];function an(n){return f(process.env.PATH||"",process.platform).some(e=>e&&(p(s.join(e,n))||p(s.join(e,n+".exe"))))}function un(n){const t=S(n);if(t)return t;if($()){const e=S(n);if(e)return e}return mn(n)||null}function Fn(n){return!!R(n)}function S(n){for(const t of sn(n))if(p(t))return t;return null}function N(){const n=s.basename(process.execPath).toLowerCase();return!(n.startsWith("node")||n.startsWith("bun"))}function Yn(n){const t=["--mcp-stdio",n];if(N())return{command:process.execPath,args:t};const e=process.argv[1]||s.join(process.cwd(),"src","server.js"),o=process.env.CHATPANEL_BRIDGE_EMBEDDED==="1"?["--bridge"]:[];return{command:process.execPath,args:[e,...o,...t]}}const b="CHATPANEL_ENV",D=6e3;function C(n){for(const t of String(n||"").split(/\r?\n/)){const e=t.indexOf(" ");if(e>0&&t.slice(0,e).trim().endsWith(b))return t.slice(e+1).trim()}return""}function U(n){return/^[\w.+-]+$/.test(String(n||""))}function M(){if(process.env.SHELL)return process.env.SHELL;try{const{shell:n}=m.userInfo();if(n&&n!=="/usr/bin/false"&&n!=="/sbin/nologin")return n}catch{}return"/bin/sh"}function X(n,{interactive:t}={}){if(process.platform==="win32")return"";try{const e=t?["-l","-i","-c"]:["-l","-c"];return w(M(),[...e,n],{encoding:"utf8",timeout:D,stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}}).stdout||""}catch{return""}}function pn(n){let t="";for(const e of String(n||"").split(/\r?\n/))e.startsWith("PATH=")&&(t=e.slice(5).trim());return t}function fn({interactive:n=!0,ask:t=X}={}){const e=C(t(`command -p printf '%s\\t%s\\n' ${b} "$PATH"`,{interactive:n}));return f(e||pn(t("/usr/bin/env",{interactive:n})),process.platform)}const v=1e4,dn=3e5;let T=0,g=v;function $({force:n=!1,now:t=Date.now(),read:e=fn,env:o=process.env}={}){if(process.platform==="win32"||!n&&(t-T<g||t<A))return!1;T=t;const i=f(o.PATH||"",process.platform),r=B(j([...e({interactive:!0}),...i])),c=r.length>i.length;return g=c?v:Math.min(g*2,dn),c?(o.PATH=r.join(s.delimiter),!0):!1}function Gn(){T=0,g=v,h.clear(),A=0,P=I,L=!1}const h=new Map,jn=15e3;function mn(n){if(process.platform==="win32"||!U(n))return"";const t=h.get(n);if(t&&(t.bin||Date.now()-t.at<jn||Date.now()<A))return t.bin;const e=[`command -p printf '%s\\t%s\\n' ${b} "$(command -v ${n} 2>/dev/null)"`,`type -p ${n}`];let o="";for(const i of[!1,!0]){for(const r of e){const c=X(r,{interactive:i}),l=C(c)||String(c||"").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.startsWith("/")).pop()||"";if(l.startsWith("/")&&p(l)){o=l;break}}if(o)break}return h.set(n,{bin:o,at:Date.now()}),o}const I=15e3,hn=3e5;let A=0,P=I,L=!1,_=null;function wn(n,{interactive:t}={}){return new Promise(e=>{let o="",i;try{i=ln(M(),[...t?["-l","-i","-c"]:["-l","-c"],n],{stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}})}catch{e("");return}const r=setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},D);i.stdout.on("data",c=>{o+=c}),i.on("error",()=>{clearTimeout(r),e("")}),i.on("close",()=>{clearTimeout(r),e(o)})})}const bn=new RegExp(`${b}=([\\w.+-]+)$`);function z(n){const t=new Map;for(const e of String(n||"").split(/\r?\n/)){const o=e.indexOf(" ");if(o<=0)continue;const i=bn.exec(e.slice(0,o).trim());i&&t.set(i[1],e.slice(o+1).trim())}return t}function Un({names:n=O,ask:t=wn,now:e=()=>Date.now()}={}){if(process.platform==="win32"||L)return Promise.resolve(!1);if(_)return _;if(e()<A)return Promise.resolve(!1);const o=j([...n,...h.keys()]).filter(r=>U(r)&&!S(r)&&!h.get(r)?.bin);if(!o.length)return Promise.resolve(!1);const i=[`command -p printf '%s\\t%s\\n' ${b} "$PATH"`,...o.map(r=>`command -p printf '%s\\t%s\\n' ${b}=${r} "$(command -v ${r} 2>/dev/null)"`)].join("; ");return _=(async()=>{let r=await t(i,{interactive:!0}),c=z(r);if(c.size||(r=await t(i,{interactive:!1}),c=z(r)),!c.size)return L=!0,!0;const l=e();let a=!1;const u=f(C(r),process.platform);u.length&&$({force:!0,now:l,read:()=>u})&&(a=!0);for(const d of o){if(!c.has(d))continue;const H=c.get(d),V=H.startsWith("/")&&p(H)?H:"";(V||S(d))&&(a=!0),h.set(d,{bin:V,at:l})}return a&&(P=I),A=l+P,a||(P=Math.min(P*2,hn)),!0})().catch(()=>!0).finally(()=>{_=null}),_}function Xn(){A=0,P=I,L=!1,T=0,g=v;for(const[n,t]of h)t.bin||h.delete(n)}function zn(){return process.env.CHATPANEL_CLAUDE_PATH?R(process.env.CHATPANEL_CLAUDE_PATH):R("claude")}function R(n){if(!n)return null;if(n.includes("/")||n.includes("\\")||/\.[a-z0-9]+$/i.test(n)){if(!p(n))return null;const o=s.extname(n).toLowerCase();return!N()&&/^\.(c?js|mjs)$/.test(o)?{kind:"script",script:n}:process.platform==="win32"&&(o===".cmd"||o===".bat")?{kind:"cmd",bin:n}:process.platform==="win32"&&o===""&&!rn(n)?null:{kind:"native",bin:n}}if(process.platform==="win32"){const o=Mn(n);return o||(/^[\w.-]+$/.test(n)&&Hn(n)?{kind:"wsl",command:n}:null)}const e=un(n);return e?{kind:"native",bin:e}:null}const An="HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",Pn="HKCU\\Environment",gn=4e3;let Q=0;function _n(n,t="Path"){const e=String(t).toLowerCase();for(const o of String(n||"").split(/\r?\n/)){const i=/^\s*(\S+)\s+REG_(?:EXPAND_)?SZ\s+(.*?)\s*$/.exec(o);if(i&&i[1].toLowerCase()===e)return i[2]}return""}function q(n,t=process.env){const e=new Map(Object.keys(t||{}).map(o=>[o.toLowerCase(),t[o]]));return String(n||"").replace(/%([^%]+)%/g,(o,i)=>{const r=e.get(String(i).toLowerCase());return r==null?o:String(r)})}function xn(n,t){try{const e=s.win32.join(process.env.SystemRoot||"C:\\Windows","System32","reg.exe"),o=w(p(e)?e:"reg",["query",n,"/v",t],{encoding:"utf8",timeout:3e3,windowsHide:!0});return o.status===0?_n(o.stdout,t):""}catch{return""}}function En({query:n=xn,env:t=process.env}={}){const e=q(n(An,"Path"),t),o=q(n(Pn,"Path"),t);return j([...f(e,"win32"),...f(o,"win32")])}function Sn({run:n=Cn}={}){const t=n(`[Console]::Out.Write("${b}\`t" + $env:PATH + "\`n")`);return f(C(t),"win32")}function Cn(n){for(const t of["pwsh.exe","powershell.exe"])try{const e=w(t,["-NoLogo","-NonInteractive","-ExecutionPolicy","Bypass","-Command",n],{encoding:"utf8",timeout:D,stdio:["ignore","pipe","ignore"],windowsHide:!0}),o=W(e.stdout||"");if(o)return o}catch{}return""}function J({force:n=!1,now:t=Date.now(),registry:e=En,profile:o=Sn,env:i=process.env,home:r=m.homedir()}={}){if(process.platform!=="win32"&&!n||!n&&t-Q<gn)return!1;Q=t;const c=f(i.PATH||"","win32"),l=j([...c,...e({env:i}),...K(r,"win32",i)]);O.some(u=>!l.some(d=>p(s.win32.join(d,`${u}.cmd`))||p(s.win32.join(d,`${u}.exe`))))&&l.push(...o());const a=B(j(l),"win32");return a.length===c.length?!1:(i.PATH=a.join(k("win32")),!0)}function Mn(n){return Z(n)||(J()?Z(n):null)}function Z(n){const t=x("win32");for(const e of sn(n,m.homedir(),"win32",process.env)){if(!p(e))continue;const o=t.dirname(e),i=t.extname(e).toLowerCase(),r=n==="claude"&&Tn(o)||In(o,n)||(/^\.(c?js|mjs)$/.test(i)?e:null);if(r){if(!N())return{kind:"script",script:r};const c=vn(o);if(c)return{kind:"script",script:r,runtime:c}}if(i===".exe")return{kind:"native",bin:e};if(i===".cmd"||i===".bat")return{kind:"cmd",bin:e};if(i===""&&rn(e))return{kind:"native",bin:e}}return null}function vn(n,{env:t=process.env,exists:e=p}={}){const o=s.win32,i=j([n,...f(t.PATH||"","win32"),...t.NVM_SYMLINK?[t.NVM_SYMLINK]:[],o.join(t.ProgramFiles||"C:\\Program Files","nodejs")]);for(const r of i){const c=o.join(r,"node.exe");if(e(c))return c}return null}function Tn(n){const t=[["node_modules","@anthropic-ai","claude-code","cli.js"],["..","node_modules","@anthropic-ai","claude-code","cli.js"],["..","lib","node_modules","@anthropic-ai","claude-code","cli.js"]];for(const e of t){const o=s.join(n,...e);if(p(o))return o}return null}function In(n,t){for(const e of[`${t}.cmd`,t,`${t}.ps1`]){let o;try{o=y(s.join(n,e),"utf8")}catch{continue}const i=o.match(/(?:%~?dp0%|\$basedir|\$\{basedir\})[\\/]+([^"'\s]+\.[cm]?js)/i);if(i){const r=s.join(n,i[1].replace(/[\\/]+/g,s.sep));if(p(r))return r}}return null}const nn=new Map,Ln=15e3;function Hn(n){const t=nn.get(n);if(t&&(t.ok||Date.now()-t.at<Ln))return t.ok;let e=!1;try{const o=w("wsl.exe",["-e","bash","-lic",`command -v ${n}`],{encoding:"utf8",timeout:8e3,windowsHide:!0});e=o.status===0&&/\S/.test(W(o.stdout||""))}catch{e=!1}return nn.set(n,{ok:e,at:Date.now()}),e}function Qn(n,t,e,o=null){const i=o&&typeof o=="object"&&Object.keys(o).length?{...process.env,...o}:process.env;if(n.kind==="wsl"){const c=[];if(e){const a=yn(e);a&&c.push("--cd",a)}return["wsl.exe",[...c,"-e","bash","-lic",`exec ${n.command} "$@"`,"chatpanel",...t],{stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...F}]}const r={cwd:e||m.homedir(),stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...F};return n.kind==="script"?[n.runtime||process.execPath,[n.script,...t],r]:n.kind==="cmd"?["cmd.exe",["/d","/s","/c",n.bin,...t],r]:[n.bin,t,r]}function yn(n){try{const t=w("wsl.exe",["-e","wslpath","-a",n],{encoding:"utf8",timeout:5e3,windowsHide:!0}),e=W(t.stdout||"").trim();return e.startsWith("/")?e:null}catch{return null}}function W(n){return n.replace(/^/,"").trim()}function On(n=m.homedir(),t=process.env){const e=s.join(t.NVM_DIR||s.join(n,".nvm"),"versions","node");let o;try{o=E(e).filter(r=>/^v\d+\./.test(r))}catch{return null}if(!o.length)return null;const i=(r,c)=>{const l=r.slice(1).split(".").map(Number),a=c.slice(1).split(".").map(Number);for(let u=0;u<3;u+=1)if((l[u]||0)!==(a[u]||0))return(a[u]||0)-(l[u]||0);return 0};try{const r=y(s.join(t.NVM_DIR||s.join(n,".nvm"),"alias","default"),"utf8").trim(),c=r.startsWith("v")?r:`v${r}`;if(o.includes(c))return s.join(e,c,"bin")}catch{}return s.join(e,o.sort(i)[0],"bin")}function Nn(n,t=process.env){return[s.join(t.MISE_DATA_DIR||s.join(n,".local","share","mise"),"shims"),s.join(n,".local","share","rtx","shims"),s.join(t.ASDF_DATA_DIR||s.join(n,".asdf"),"shims"),s.join(t.PYENV_ROOT||s.join(n,".pyenv"),"shims"),s.join(t.RBENV_ROOT||s.join(n,".rbenv"),"shims"),s.join(t.NODENV_ROOT||s.join(n,".nodenv"),"shims"),s.join(t.PROTO_HOME||s.join(n,".proto"),"shims"),s.join(t.PROTO_HOME||s.join(n,".proto"),"bin"),s.join(t.VOLTA_HOME||s.join(n,".volta"),"bin")]}function Dn(n,t=process.env){const e=[],o=(i,r)=>{try{for(const c of E(i))e.push(s.join(i,c,r))}catch{}};return o(s.join(t.NVM_DIR||s.join(n,".nvm"),"versions","node"),"bin"),o(s.join(n,".local","share","fnm","node-versions"),s.join("installation","bin")),o(s.join(n,"Library","Application Support","fnm","node-versions"),s.join("installation","bin")),o(s.join(t.MISE_DATA_DIR||s.join(n,".local","share","mise"),"installs","node"),"bin"),e}function x(n){return n==="win32"?s.win32:s}function k(n){return n==="win32"?";":s.delimiter}function f(n,t){return(n||"").split(k(t)).filter(Boolean)}function j(n){return[...new Set(n.filter(Boolean))]}const tn={win32:3e4,other:65536};function B(n,t=process.platform){const e=t==="win32"?tn.win32:tn.other,o=k(t),i=[];let r=0;for(const c of n){const l=c.length+(i.length?o.length:0);if(r+l>e)break;i.push(c),r+=l}return i}function K(n,t=process.platform,e=process.env){const o=x(t);if(t==="win32"){const i=e.APPDATA||o.join(n,"AppData","Roaming"),r=e.LOCALAPPDATA||o.join(n,"AppData","Local"),c=e.ProgramFiles||"C:\\Program Files",l=e["ProgramFiles(x86)"]||"C:\\Program Files (x86)",a=e.ProgramData||"C:\\ProgramData";return[o.join(n,".local","bin"),o.join(n,".codex","bin"),o.join(n,".claude","bin"),o.join(n,".claude","local"),o.join(n,".claude","local","bin"),o.join(i,"npm"),...e.NVM_SYMLINK?[e.NVM_SYMLINK]:[],o.join(c,"nodejs"),...$n(i,r),o.join(r,"pnpm"),o.join(r,"Yarn","bin"),o.join(r,"Volta","bin"),o.join(n,".yarn","bin"),o.join(n,".bun","bin"),o.join(n,".deno","bin"),o.join(e.SCOOP||o.join(n,"scoop"),"shims"),o.join(a,"chocolatey","bin"),o.join(r,"Microsoft","WindowsApps"),o.join(r,"Microsoft","WinGet","Links"),o.join(e.MISE_DATA_DIR||o.join(r,"mise"),"shims"),o.join(e.PROTO_HOME||o.join(n,".proto"),"shims"),o.join(e.PROTO_HOME||o.join(n,".proto"),"bin"),o.join(r,"Programs","Claude Code"),o.join(r,"Anthropic","Claude Code"),o.join(c,"Claude Code"),o.join(c,"Anthropic","Claude Code"),o.join(l,"Claude Code"),o.join(l,"Anthropic","Claude Code")]}return[s.join(n,".local","bin"),s.join(n,".opencode","bin"),s.join(n,".codex","bin"),s.join(n,".claude","bin"),s.join(n,".claude","local"),s.join(n,".claude","local","bin"),e.PNPM_HOME||s.join(n,"Library","pnpm"),s.join(n,".local","share","pnpm"),s.join(n,".nix-profile","bin"),"/nix/var/nix/profiles/default/bin",s.join(n,".guix-profile","bin"),"/home/linuxbrew/.linuxbrew/bin","/snap/bin",...Nn(n,e)]}function $n(n,t){const e=s.win32,o=[];for(const i of[e.join(t,"fnm"),e.join(n,"fnm")]){let r=[];try{r=E(e.join(i,"node-versions")).filter(c=>/^v?\d+\.\d+\.\d+/.test(c)).sort((c,l)=>l.localeCompare(c,void 0,{numeric:!0}))}catch{}for(const c of r)o.push(e.join(i,"node-versions",c,"installation"))}return o}function en(n,t=process.platform){const e=x(t),o=e.join(n,".local","share","claude","versions");let i=[];try{i=E(o).filter(r=>/^\d+\.\d+\.\d+/.test(r)).sort((r,c)=>c.localeCompare(r,void 0,{numeric:!0}))}catch{}return i.map(r=>e.join(o,r))}function on(n,t){return t!=="win32"?[n]:/\.(cmd|exe|bat|ps1)$/i.test(n)?[n]:[`${n}.exe`,`${n}.cmd`,`${n}.bat`,n,`${n}.ps1`]}function rn(n,t=y){try{const e=t(n).subarray(0,2);return e.length===2&&e[0]===77&&e[1]===90}catch{return!1}}function Rn(n,t=m.homedir(),e=process.platform,o=process.env){const i=x(e),r=i.join(t,".local","bin",n),c=e==="win32"?o.LOCALAPPDATA||i.join(t,"AppData","Local"):null,l=e==="win32"?o.ProgramFiles||"C:\\Program Files":null,a=e==="win32"?o["ProgramFiles(x86)"]||"C:\\Program Files (x86)":null,u={claude:[r,i.join(t,".claude","bin","claude"),i.join(t,".claude","local","claude"),i.join(t,".claude","local","bin","claude"),...e==="win32"?[i.join(c,"Microsoft","WindowsApps","claude.exe"),i.join(c,"Programs","Claude Code","claude.exe"),i.join(c,"Anthropic","Claude Code","claude.exe"),i.join(l,"Claude Code","claude.exe"),i.join(l,"Anthropic","Claude Code","claude.exe"),i.join(a,"Claude Code","claude.exe"),i.join(a,"Anthropic","Claude Code","claude.exe"),...en(t,e)]:en(t,e)],codex:[r,i.join(t,".codex","bin","codex")],agy:[r,"/Applications/Antigravity.app/Contents/MacOS/agy","/Applications/Antigravity IDE.app/Contents/MacOS/agy"],pi:[r],opencode:[i.join(t,".opencode","bin","opencode"),r],"kiro-cli":[r,"/Applications/Kiro CLI.app/Contents/MacOS/kiro-cli"]};return j((u[n]||[r]).flatMap(d=>on(d,e)))}function sn(n,t=m.homedir(),e=process.platform,o=process.env){const i=x(e),r=j([...f(o.PATH||"",e),...K(t,e,o)]).flatMap(c=>on(i.join(c,n),e));return j([...r,...Rn(n,t,e,o)])}const cn=["DEEPSEEK_API_KEY","DSH_HOME","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","GEMINI_API_KEY","GOOGLE_API_KEY","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"];function qn(){if(G||(G=!0,process.platform==="win32"))return;const n=cn.filter(t=>!process.env[t]);if(n.length)try{const t=M(),e=`${n.map(i=>`[ -n "\${${i}:-}" ] && printf '%s\\t%s\\n' ${i} "$${i}"`).join("; ")}; true`,o=w(t,["-l","-i","-c",e],{encoding:"utf8",timeout:6e3,env:{...process.env,TERM:"dumb"}});for(const i of String(o.stdout||"").split(`
|
|
2
|
+
`)){const r=i.indexOf(" ");if(r<=0)continue;const c=i.slice(0,r).trim(),l=i.slice(r+1);cn.includes(c)&&!process.env[c]&&l&&(process.env[c]=l)}}catch{}}function Jn(){if(Y)return;Y=!0;const n=m.homedir();if(process.platform==="win32"){J({force:!0,home:n});return}const t=On(n),e=[...t?[t]:[],"/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",s.join(n,".local","bin"),s.join(n,"bin"),s.join(n,".npm-global","bin"),s.join(n,".cargo","bin"),s.join(n,".deno","bin"),s.join(n,".bun","bin"),...K(n),...Dn(n)];let o="";try{const c=M(),l=w(c,["-l","-c",'command -p echo "$PATH"'],{encoding:"utf8",timeout:4e3});l.status===0&&(o=(l.stdout||"").trim())}catch{}const i=new Set,r=[...t?[t]:[],...o?o.split(":"):[],...process.env.PATH?process.env.PATH.split(s.delimiter):[],...e].filter(c=>c&&!i.has(c)&&(i.add(c),!0));process.env.PATH=B(r).join(s.delimiter),O.some(c=>!an(c))&&$({force:!0})}export{O as AGENT_CLIS,Fn as agentAvailable,Rn as agentCandidateBins,K as agentInstallDirs,Qn as buildSpawnSpec,B as capPathList,sn as commandCandidateFiles,qn as enrichAgentEnv,Jn as enrichPath,q as expandWindowsEnv,un as findAgentBin,Xn as forgetMisses,N as isCompiledBinary,rn as isWindowsExecutable,vn as nodeRuntimeWindows,On as nvmCurrentBin,pn as parseEnvPath,_n as parseRegValue,C as parseSentinel,z as parseWhich,Un as primeAgentLookups,Sn as profilePathWindows,$ as refreshShellPath,J as refreshWindowsPath,En as registryPathWindows,Gn as resetShellProbes,zn as resolveClaude,R as resolveCommand,Yn as selfMcpStdio,fn as shellPath,yn as toWslPath};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
const u=t=>t==null?0:Math.round((typeof t=="string"?t:JSON.stringify(t)).length/4),k=t=>typeof t=="string"?t:Array.isArray(t)?t.map(o=>o?.type==="text"&&o.text||"").join(`
|
|
2
|
+
`):"",L=t=>Array.isArray(t)?t.filter(o=>o&&o.type!=="text").length:0,K=/<context source="[^"]*">\n# \[([\w-]+)\][^\n]*\n[\s\S]*?\n<\/context>/g,W=/<presence>\n[\s\S]*?\n<\/presence>/g,j=/\n*\[Chap\] Likely useful for this message[^\n]*/g;function M(t){const o=String(t||""),c=[];let r=o.replace(K,(l,a)=>(c.push({kind:a==="prefetch"?"fetched":"attached",of:a,tokens:u(l)}),""));r=r.replace(W,l=>(c.push({kind:"presence",tokens:u(l)}),""));let d=0;return r=r.replace(j,l=>(d+=u(l),"")),{words:u(r.trim()),blocks:c,hint:d}}function B(t){const o=String(t||"");return o.trim()?o.split(/\n(?=## )/).map(r=>{const d=(r.match(/^## ([^\n]+)/)||[])[1];return{label:d?d.trim().slice(0,60):"Instructions",tokens:u(r)}}).filter(r=>r.tokens>0):[]}const v=Object.freeze({instructions:"The system prompt: who the assistant is, how to answer, what it may use. Sent on every turn so the model behaves the same way each time.",toolText:"The tools' rules and catalog: which actions exist and when to use them. Sent every turn; the provider caches it.",toolSchemas:"The tool definitions the model can call — kept to one tool (`tools`) so a turn carries one schema, not one per action.",history:'The earlier messages of this conversation, so a follow-up ("how many in south?") is read against what came before.',historyCarried:"Context that rode on earlier messages — fetched results, attachments, presence — kept with them so the model can refer back.",toolExchange:"Tool calls and their results from earlier rounds.",fetched:"Looked up before the model ran (the weather, a search, the page), so it answers instead of calling a tool.",attached:"What the person attached to this message, or the client added as context.",presence:"What exists around the turn (the open page, notes, what was fetched before) — names, not contents.",hint:"The actions likely useful for this message — appended to the message, not the system prompt, so the prompt cache holds.",words:"The person's own words.",agentOwn:"The agent's own context: its system prompt, its built-in tools, its skills and MCP servers, its session. Not sent by us; it reads it every turn.",cached:"Read from the provider's prompt cache — already there, billed at a fraction, and fast."});function H({messages:t=[],tools:o=null,usage:c=null,agent:r=!1,agentContext:d=null}={}){const l=Array.isArray(t)?t:[],a=[],i=(e,n,s,h={})=>{(s>0||h.always)&&a.push({id:e,label:n,tokens:s,why:v[e]||"",...h})},y=l.filter(e=>e?.role==="system").map(e=>k(e.content)).join(`
|
|
3
|
+
|
|
4
|
+
`),b=String(o?.system||""),E=b&&y.includes(b)?y.replace(b,""):y,S=B(E);i("instructions","Instructions (system prompt)",S.reduce((e,n)=>e+n.tokens,0),S.length>1?{items:S}:{}),i("toolText","Tool rules & catalog",u(b));const C=Array.isArray(o?.specs)?o.specs:[];i("toolSchemas",`Tool definitions (${C.length})`,u(C),{count:C.length});const g=l.filter(e=>e&&e.role!=="system");let p=-1;for(let e=g.length-1;e>=0;e--)if(g[e].role==="user"){p=e;break}const q=p>=0?g.slice(0,p):g,I=p>=0?g.slice(p+1):[];let N=0,O=0,A=0,x=0;const T=new Map;for(const e of q){if((e.role==="tool"||e.tool_calls)&&(A+=u(k(e.content))+u(e.tool_calls),e.role==="tool")||e.role!=="user"&&e.role!=="assistant")continue;e.role==="user"&&(x+=1);const n=M(k(e.content));N+=n.words+n.hint;for(const s of n.blocks)O+=s.tokens,T.set(s.of||s.kind,(T.get(s.of||s.kind)||0)+s.tokens)}i("history",`Conversation history (${x} earlier ${x===1?"question":"questions"})`,N,{count:x}),i("historyCarried","Context carried in the history",O,T.size?{items:[...T].map(([e,n])=>({label:e,tokens:n}))}:{});for(const e of I)A+=u(k(e.content))+u(e.tool_calls);if(i("toolExchange","Tool calls & results",A),p>=0){const e=g[p],n=M(k(e.content)),s=m=>n.blocks.filter(f=>f.kind===m),h=m=>m.reduce((f,$)=>f+$.tokens,0);i("fetched","Fetched for this message",h(s("fetched")),{count:s("fetched").length}),i("attached","Attached to this message",h(s("attached")),{count:s("attached").length,...s("attached").length?{items:s("attached").map(m=>({label:m.of,tokens:m.tokens}))}:{}}),i("presence","Presence (what is around the turn)",h(s("presence"))),i("hint","Hint (likely actions)",n.hint),i("words","Your message",n.words,{always:!0,...L(e.content)?{images:L(e.content)}:{}})}const _=a.reduce((e,n)=>e+n.tokens,0),w={rows:a,ours:_};if(c){const e=h=>Math.max(0,Number(h)||0),n=e(c.cacheReadTokens),s=e(c.inputTokens)+n+e(c.cacheWriteTokens);if(s>0&&(w.reported=s,w.cached=n,w.requests=e(c.requests)||e(c.calls)||1,r)){const h=Math.max(0,s-_*w.requests),m=Array.isArray(d)?d.filter(f=>f&&Number(f.tokens)>0).map(f=>({label:String(f.label),tokens:Math.round(Number(f.tokens))})):null;w.agentOwn=h,a.push({id:"agentOwn",label:"The agent's own context",tokens:h,why:v.agentOwn,...m?.length?{items:m}:{}})}}return w}function P(t){const o=[],c=String(t||""),r=c.match(/\*\*Tokens:\*\*\s*([\d.]+)(k|m)?\s*\//i)||[];for(const l of c.split(`
|
|
5
|
+
`)){const a=l.match(/^\|\s*([^|]+?)\s*\|\s*([\d.,]+)\s*(k|m)?\s*\|\s*[\d.]+%\s*\|$/i);if(!a)continue;const i=a[1].trim();if(/deferred|free space|autocompact|^category$/i.test(i))continue;const y=Number(a[2].replace(/,/g,""))*(a[3]?.toLowerCase()==="k"?1e3:a[3]?.toLowerCase()==="m"?1e6:1);y>0&&o.push({label:i,tokens:Math.round(y)})}if(!o.length)return null;const d=r[1]?Math.round(Number(r[1])*(r[2]?.toLowerCase()==="k"?1e3:r[2]?.toLowerCase()==="m"?1e6:1)):o.reduce((l,a)=>l+a.tokens,0);return{items:o,total:d}}export{H as contextBreakdown,P as parseAgentContext,M as splitMessage,B as systemSections};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const d=[[/gpt-4\.1/,1e6],[/gpt-5|o3|o4|o1/,2e5],[/gpt-4o|gpt-4-turbo/,128e3],[/claude-(3|4|5|opus|sonnet|haiku|fable)/,2e5],[/gemini-(1\.5|2|2\.5|3)/,1e6],[/gemini/,1e6],[/deepseek/,128e3],[/mistral-large|mixtral|codestral/,128e3],[/grok/,128e3],[/llama-3\.[1-3]|llama-4/,128e3]];function x(
|
|
1
|
+
const d=[[/^apple-on-device$|apple[-_ ]?foundation/,4096],[/gemini-?nano/,4096]],l=[[/gpt-4\.1/,1e6],[/gpt-5|o3|o4|o1/,2e5],[/gpt-4o|gpt-4-turbo/,128e3],[/claude-(3|4|5|opus|sonnet|haiku|fable)/,2e5],[/gemini-(1\.5|2|2\.5|3)/,1e6],[/gemini/,1e6],[/deepseek/,128e3],[/mistral-large|mixtral|codestral/,128e3],[/grok/,128e3],[/llama-3\.[1-3]|llama-4/,128e3]];function x(n={},t=null){const e=String(n.id||""),r=String(n.model||n.id||"").toLowerCase(),c=t&&(t[a(n)]||t[r]||t[String(n.model||"")]||(n.gateway?0:t[e]));if(Number(c)>0)return Number(c);const i=Number(n.window||n.contextLength||n.contextWindow||0);if(i>0)return i;for(const[o,u]of d)if(o.test(r))return u;if(n.reach==="device"||n.kind==="webllm")return 0;for(const[o,u]of l)if(o.test(r))return u;return 0}function a(n={}){const t=String(n.id||""),e=String(n.model||"");return e?`${t}:${e}`:t}const s=.85,f=8192,p=n=>Number(n)>0&&Number(n)<=f,w=2;function _({promptTokens:n=0,floorTokens:t=0,window:e=0,reserve:r=1024,headroom:c=s}={}){const i=Number(e)||0;if(!i)return{status:"unknown",budget:0,over:0,window:0};const o=Math.max(0,Math.floor(i*c)-Math.max(0,Number(r)||0)),u=Math.max(0,Number(n)||0),m=Math.max(0,Number(t)||0);return u<=o?{status:"ok",budget:o,over:0,window:i}:m<=o?{status:"compact",budget:o,over:u-o,window:i}:{status:"too-big",budget:o,over:m-o,window:i}}function b(n=0){const t=Number(n)||0;return t?t<=8e3?2:t<=32768?4:t<=128e3?8:12:4}function h({floorTokens:n=0,reserve:t=1024,headroom:e=s}={}){const r=Math.max(0,Number(n)||0);return r?Math.ceil((r+Math.max(0,Number(t)||0))/e):0}function N(n){return/context.{0,8}(length|window|size)|context_length_exceeded|prompt is too long|too many tokens|maximum context|exceed.{0,20}context|reduce the (length|number|size)|input is too long|token limit|n_ctx|kv cache|longer than .{0,80}\bwindow\b|exceed.{0,30}\bwindow\b/i.test(String(n?.message||n||""))}export{s as FIT_HEADROOM,f as SMALL_WINDOW,w as SMALL_WINDOW_ROUNDS,_ as fitFor,N as isContextLimitError,p as isSmallWindow,b as keepRecentFor,h as minWindowFor,a as observedKey,x as windowOf};
|
package/src/events/mcp-signin.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const m=-32011,d=/https?:\/\/[^\s"'<>)\]]+/,w=/\b(?:code|passcode)\b[:\s]+([A-Z0-9][A-Z0-9-]{3,}[A-Z0-9])\b/,g=/sign[ -]?in|log[ -]?in|authenticate|authoriz|verify|devicelogin|login\/device|oauth/i,b=/opening (?:your |the |a )?browser|open(?:ed|ing)? .*browser .*sign/i,_=/[?&]redirect_uri=https?%3A%2F%2F(?:localhost|127\.0\.0\.1)|[?&]redirect_uri=https?:\/\/(?:localhost|127\.0\.0\.1)/i;function I(n){const e=String(n||"");return/response_type=code/i.test(e)?_.test(e):!1}function A(n){const e=String(n||"");if(!e.trim())return null;const o=e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),c=o.join(" "),a=w.exec(c)?.[1]||null,u=o.filter(t=>g.test(t)||d.test(t)),s=u.find(t=>d.test(t)&&g.test(t))||u.find(t=>d.test(t)),i=s?d.exec(s)[0].replace(/[.,;]+$/,""):null;if(i&&(a||g.test(c))){const t=(u.find(r=>g.test(r))||s).slice(0,300);return!a&&I(i)?{url:i,code:null,message:t,browser:!0,interactive:!0}:{url:i,code:a,message:t,browser:!1,interactive:!1}}const l=o.find(t=>b.test(t));return l?{url:null,code:null,message:l.slice(0,300),browser:!0,interactive:!0}:null}function E(n){const e=n.url?` Open ${n.url}${n.code?` and enter the code ${n.code}`:""}.`:"";return{code:-32011,message:`Sign-in required: ${n.message}${e}`,data:{signIn:{url:n.url,code:n.code,message:n.message,browser:!!n.browser,interactive:!!n.interactive}}}}function N(n){if(!n||n.code!==-32011)return null;const e=n.data?.signIn;return e?{url:e.url||null,code:e.code||null,message:e.message||"",browser:!!e.browser,interactive:!!e.interactive}:{url:null,code:null,message:String(n.message||""),browser:!1,interactive:!1}}function x(n,e){return{error:"sign_in_required",server:n,...e.url&&!e.interactive?{url:e.url}:{},...e.code?{code:e.code}:{},...e.browser?{browser:!0}:{},next:e.interactive?"The server opened its own browser window for the user to sign in, and any link it printed works only in that window, right now. Tell them to finish signing in there and then ask again. Do NOT paste the link, and do not invent a result.":"The user has been shown this sign-in prompt. Give them the url and the code exactly, ask them to complete it, then call this tool again. Do not invent a result."}}const y=/"error"\s*:\s*"sign_in_failed"|\bAADSTS\d{5,}\b|could not obtain an? [\w ]{0,20}token|\binvalid_grant\b|\bsign[- ]?in (?:failed|was declined)\b/i;function S(n){const e=typeof n=="string"?n:n&&typeof n.text=="string"?n.text:"";return!!e&&y.test(e)}const v=1440*60*1e3;function h(n){const e=n||{};return JSON.stringify([e.url||"",e.command||"",Array.isArray(e.args)?e.args:[],Object.keys(e.env||{}).sort(),Object.keys(e.headers||{}).sort()])}function C(n,e,{text:o="",now:c=Date.now(),ttlMs:a=v}={}){const u=Array.isArray(n)?n:[],s=e&&typeof e=="object"?e:{},i=new Set(String(o||"").toLowerCase().match(/[a-z][a-z0-9]+/g)||[]),l=t=>String(t?.name||"").toLowerCase().match(/[a-z][a-z0-9]+/g)?.some(r=>r.length>1&&!["mcp","server","the","my"].includes(r)&&i.has(r));return u.filter(t=>{const r=s[t?.name];return!r||c-Number(r.at||0)>a||r.fingerprint&&r.fingerprint!==h(t)?!0:!!l(t)})}function D(n,e,o,{prefixOf:c}={}){if(!n||!o||typeof c!="function")return n;const a=Array.isArray(e)?e:[],u=s=>a.find(i=>String(s||"").startsWith(c(i.name)))||null;return{...n,async execute(s,i,l){const t=await n.execute(s,i,l),r=u(i?.action||s);if(r)try{const f=S(t)?o.failed(r.name,h(r)):o.recovered(r.name);f&&typeof f.catch=="function"&&f.catch(()=>{})}catch{}return t}}}export{m as MCP_SIGN_IN_CODE,v as SIGN_IN_FAILED_TTL_MS,A as parseSignInPrompt,h as serverFingerprint,E as signInError,S as signInFailedIn,N as signInFromError,x as signInToolResult,D as watchSignIns,C as withoutFailedSignIns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function c({compute:u,freshMs:s=1e4,now:l=()=>Date.now(),defer:f=e=>setImmediate(e)}={}){let e=null,t=null,n=!1;const r=()=>(t||=Promise.resolve().then(u).then(a=>(e={at:l(),value:a},e)).finally(()=>{t=null}),t);return{async get({fresh:a=!1}={}){return!e||a?r():(l()-e.at>s&&!t&&!n&&(n=!0,f(()=>{n=!1,r().catch(()=>{})})),e)},warm(){e||r().catch(()=>{})}}}export{c as createSnapshot};
|
package/src/pii/pii-detect.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{assertEndpointUrl as D}from"./net.js";const A=new Map,m=300;function
|
|
1
|
+
import{assertEndpointUrl as D}from"./net.js";const A=new Map,m=300;function G(){A.clear()}function T(e,t){let o=5381;const r=`${t?.backend}|${t?.url}|${t?.model}|${t?.strictness||""}|${JSON.stringify(t?.types||null)}|${e}`;for(let n=0;n<r.length;n++)o=(o<<5)+o+r.charCodeAt(n)|0;return`${r.length}:${o}`}function p(e,t,o){return new Promise((r,n)=>{const a=setTimeout(()=>n(new Error("detect timeout")),Math.max(200,t||1500)),i=()=>{clearTimeout(a),n(new Error("aborted"))};o&&o.addEventListener?.("abort",i,{once:!0}),e.then(s=>{clearTimeout(a),r(s)},s=>{clearTimeout(a),n(s)})})}function y(e){const t=String(e||"ENTITY").toUpperCase().replace(/[^A-Z0-9]/g,"")||"ENTITY";return{PER:"PERSON",PERSON:"PERSON",PERSONNAME:"PERSON",PRIVATEPERSON:"PERSON",GIVENNAME:"PERSON",FIRSTNAME:"PERSON",MIDDLENAME:"PERSON",SURNAME:"PERSON",LASTNAME:"PERSON",FULLNAME:"PERSON",ORG:"ORG",ORGANIZATION:"ORG",COMPANYNAME:"ORG",COMPANY:"ORG",GPE:"LOCATION",LOC:"LOCATION",LOCATION:"LOCATION",CITY:"LOCATION",STATE:"LOCATION",COUNTY:"LOCATION",COUNTRY:"LOCATION",STREET:"ADDRESS",BUILDINGNUM:"ADDRESS",BUILDINGNUMBER:"ADDRESS",ZIPCODE:"ADDRESS",POSTCODE:"ADDRESS",SECADDRESS:"ADDRESS",ADDRESS:"ADDRESS",PRIVATEADDRESS:"ADDRESS",NORP:"GROUP",EMAIL:"EMAIL",EMAILADDRESS:"EMAIL",PRIVATEEMAIL:"EMAIL",PHONE:"PHONE",PHONENUMBER:"PHONE",TELEPHONENUM:"PHONE",PRIVATEPHONE:"PHONE",PHONEIMEI:"ID",SOCIALNUM:"SSN",USSSN:"SSN",SSN:"SSN",CREDITCARDNUMBER:"CREDITCARD",CREDITCARD:"CREDITCARD",IBAN:"IBAN",IBANCODE:"IBAN",ACCOUNTNUM:"ID",ACCOUNTNUMBER:"ID",TAXNUM:"ID",IDCARDNUM:"ID",DRIVERLICENSENUM:"ID",PASSPORTNUM:"ID",VEHICLEVRM:"ID",DATEOFBIRTH:"ID",DOB:"ID",PRIVATEDATE:"ID",PRIVATEURL:"ID",USERNAME:"ID",USERID:"ID",IP:"ID",IPADDRESS:"ID",MAC:"ID",PASSWORD:"SECRET",APIKEY:"SECRET",SECRET:"SECRET"}[t]||t}const w=new Set(["EMAIL","PHONE","SSN","CREDITCARD","IBAN","ID","SECRET"]),C=new Set(["LOCATION","FAC","ADDRESS","GROUP","NRP"]),d=/(?:^|[\s$€£])\$?\d+(?:[.,]\d+)?\s?(?:[kmb]n?|mm|million|billion|thousand|%)(?=[\s.,;:!?)]|$)/i,P=/(?:^|\s)\d{1,6}(?=\s|,|$)/;function g(e){const t=String(e||"").trim();return d.test(t)&&!P.test(t)}const Y=Object.freeze(["balanced","strict"]),L=e=>e?.strictness==="strict"||e?.detection?.strictness==="strict"?"strict":"balanced";function b(e,t,o,r="balanced"){const n=i=>!o||o[i]!==!1;return r!=="strict"&&t==="ADDRESS"&&g(e)?!1:w.has(t)?!0:t==="PERSON"?n("person"):t==="ORG"?n("org"):C.has(t)?n("location"):(String(e).match(/\d/g)||[]).length>=7?n("number"):!1}function R(e,t,{strictness:o="balanced"}={}){let r=[];Array.isArray(e)?r=e:e&&Array.isArray(e.entities)?r=e.entities:e&&Array.isArray(e.ents)?r=e.ents:e&&Array.isArray(e.results)&&(r=e.results);const n=[],a=new Set;for(const i of r){if(!i)continue;const s=String(i.value??i.text??i.entity??i.word??"").trim(),l=y(i.type??i.label??i.entity_group??i.entity_type??i.tag);if(!s||s.length>200||!b(s,l,t,o))continue;const c=`${l}:${s.toLowerCase()}`;a.has(c)||(a.add(c),n.push({value:s,type:l}))}return n}const M=new Set("a an the i am is are was were be been being to of in on at for and or but if so not no yes ok okay hi hello hey you your yours me my mine we us our ours they them their he him his she her it its this that these those what where when who whom why how which do does did done have has had having will would can could should may might must shall there here now then last next first time day days week month year today tomorrow yesterday see saw seen say said tell told go went gone come came get got give gave take took make made know knew think thought want need like just also very really with from into onto over under about after before between through during without within up down out off again still used use using live lived move moved work worked help please thanks thank sorry new old good bad more most some any all each because as than too so such only own same other another much many few both either neither every never always often".split(/\s+/));function V(e){const t=String(e||"");let o=!1;return{text:t.replace(new RegExp("(^|[^\\p{L}\\p{N}'’])(\\p{Ll})(\\p{L}*)","gu"),(n,a,i,s)=>{const l=i+s;if(M.has(l))return n;const c=i.toUpperCase();return c.length!==1||c===i?n:(o=!0,a+c+s)}),changed:o}}function U(e){if(!e)return null;const t=String(e).indexOf("{"),o=String(e).lastIndexOf("}");if(t<0||o<=t)return null;try{return JSON.parse(String(e).slice(t,o+1))}catch{return null}}const k="You extract sensitive entities from text for redaction. Copy each value exactly as it appears. Include people, organizations, locations, and account/ID numbers. No commentary, no code fences.",$='Return ONLY JSON: {"entities":[{"value":"<verbatim text>","type":"PERSON|ORG|LOCATION|ID|EMAIL|PHONE|OTHER"}]}. No commentary, no code fences.',f=Object.freeze({block:"",format:null,parse:null});async function x(e,t,o,r){const n=await r(t.url,{method:"POST",headers:{"Content-Type":"application/json",...t.apiKey?{Authorization:`Bearer ${t.apiKey}`}:{}},body:JSON.stringify({text:e,...t.strictness==="strict"?{strict:!0}:{}}),signal:o});if(!n.ok)throw new Error(`detect HTTP ${n.status}`);return R(await n.json(),t.types,{strictness:t.strictness})}async function v(e,t,o,r,n=f){const a=String(t.url||"").replace(/\/$/,""),i=/\/chat\/completions$/.test(a)?a:/\/v\d+$/.test(a)?`${a}/chat/completions`:`${a}/v1/chat/completions`,s=`${k}
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${n.block||$}`,l=async E=>{const u=n.format?n.format(E):null,h=await r(i,{method:"POST",headers:{"Content-Type":"application/json",...t.apiKey?{Authorization:`Bearer ${t.apiKey}`}:{}},body:JSON.stringify({model:t.model||"local",temperature:0,max_tokens:t.maxTokens||256,messages:[{role:"system",content:s},{role:"user",content:e}],...u||{}}),signal:o});if(!h.ok){const O=new Error(`detect HTTP ${h.status}`);throw O.status=h.status,O}return h.json()};let c=null;if(n.format)for(const E of["schema","object","none"])try{c=await l(E);break}catch(u){if(E==="none"||u.status!==400&&u.status!==422)throw u}else c=await l("none");const S=c?.choices?.[0]?.message?.content??c?.content??"",N=n.parse?n.parse(S):U(S);return R(N,t.types,{strictness:t.strictness})}function I(e,t,o,r,n,a){if(typeof e=="function")try{e({backend:t.backend||"",host:H(t.url),chars:o.length,entities:n,ms:Date.now()-r,ok:!a,error:a?String(a.message||a).slice(0,200):""})}catch{}}const H=e=>{try{return new URL(String(e)).host}catch{return""}};async function _(e,t,{signal:o,fetchImpl:r=globalThis.fetch,strict:n=!1,structured:a=f,onEgress:i=null}={}){const s=t?.detection?{...t.detection,strictness:L(t)}:null;if(!s||!s.backend||s.backend==="off"||!s.url||typeof r!="function")return[];const l=s.transport==="in-process";if(l&&r===globalThis.fetch)throw new Error("detection.transport 'in-process' needs an injected fetch; refusing to treat a network call as in-process");const c=String(e||"").slice(0,s.maxChars||8e3);if(c.trim().length<8)return[];const S=T(c,s);if(!n&&A.has(S))return A.get(S);const N=s.backend==="endpoint"?x:v;let E=[];try{l||D(s.url);const u=Date.now();try{E=await p(N(c,s,o,r,a),s.timeoutMs||1500,o),l||I(i,s,c,u,E.length,null)}catch(h){throw l||I(i,s,c,u,0,h),h}}catch(u){if(n)throw u;E=[]}return A.size>=m&&A.clear(),n||A.set(S,E),E}export{k as EXTRACT_SYS,Y as REDACTION_STRICTNESS,G as clearDetectCache,_ as detectEntities,y as normType,R as normalizeEntities,U as parseJsonLoose,g as quantityNotAddress,V as recaseForDetection,L as strictnessOf,p as withTimeout};
|
package/src/server.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createServer as Oe}from"node:http";import v from"node:os";import{randomBytes as Ae,randomInt as Ce,timingSafeEqual as xe}from"node:crypto";import{mkdirSync as Pe,writeFileSync as $e,readFileSync as Q,existsSync as Re}from"node:fs";import{join as _}from"node:path";import*as Ie from"./engines/claude.js";import*as Ne from"./engines/codex.js";import*as De from"./engines/antigravity.js";import{pi as _e,opencode as He,kiro as Be,copilot as Me,deepseek as Ue,hermes as We}from"./engines/cli-agents.js";import{connectorsFor as Ge}from"./connectors.js";import*as Le from"./engines/custom.js";import{installService as je,uninstallService as Fe,serviceStatus as Je,restartService as Z}from"./service.js";import{skillIndex as G,listRecords as Xe,readRecord as ze,readPackageFile as Ke,skillsHealth as Ye,quarantinedSkills as Ve,clearSkillCache as L}from"./skills.js";import{writeSkillPackage as Qe,writeSkillFile as Ze,deleteSkillPackage as qe,SkillWriteError as et}from"./skill-write.js";import{agentDefRoots as tt,scanAgentDefs as nt,listAgentDefs as ot,readAgentDef as rt,planAgentExport as at,exportAgentDef as it,agentDefsHealth as st,AgentDefError as ct}from"./agent-defs.js";import{capabilityToolSpecs as lt,runCapabilityTool as dt}from"./mcp-capabilities.js";import{createSession as ut,deleteSession as q,getSession as ee,activeSession as ht,relayToolCall as pt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ft,isDefaultWorkdir as mt,resolveWorkdir as gt,writeScopeNote as yt}from"./workdir.js";import{sandbox as te,runSandboxCli as wt,withGrant as ne,withoutOutsideWhenCapped as St,grantedWriteRoots as bt,acceptRefusalReport as kt,liveProcesses as Tt}from"./sandbox.js";import{gitState as Et,gitDelta as vt}from"./scm.js";import{listConnections as Ot,putConnection as At,removeConnection as Ct,runEnvFor as xt,testConnection as Pt,secretBackend as oe}from"./connections.js";import{worktreeFor as re,listWorktrees as $t,removeWorktree as Rt,withHook as It,WORKTREE_ROOT as ae}from"./worktree.js";import{AGENT_CLIS as Nt,agentAvailable as Dt,agentInstallDirs as _t,enrichPath as Ht,enrichAgentEnv as Bt,findAgentBin as Mt,resolveCommand as ie}from"./env.js";import"./sanitize.js";import{checkForUpdate as Ut,selfUpdate as se,isEmbedded as Wt}from"./update.js";import{callLocalMcp as Gt,localMcpStatus as Lt,signInLocalMcp as jt,signInStatusLocalMcp as Ft}from"./mcp-local.js";import{assertPublicHttpUrl as ce,assertPublicWebUrl as le}from"./ssrf.js";import{startRun as de,endRun as j,cancelRun as Jt,cancelAll as Xt}from"./runs.js";import{closeWarmPools as zt,warmStatus as Kt}from"./warm.js";import{SESSION_AGENTS as ue,listSessions as Yt,readSession as Vt,adoptSession as Qt,catchUp as Zt}from"./agent-sessions.js";import{normalizeThread as he}from"./events/agent-thread.js";import{portClashPlan as qt,serviceManagerOf as en,STANDBY_POLL_MS as tn}from"./events/service-standby.js";import{holdThread as pe}from"./threads.js";import{CompatError as R,anthropicError as F,anthropicStream as nn,chatCompletionStream as on,completionStream as rn,createAnthropicMessage as an,createChatCompletion as sn,createCompletion as cn,createResponse as ln,openAIError as S,parseAnthropicMessage as dn,parseChatCompletion as un,parseCompletion as hn,parseResponse as pn,responseStream as fn}from"./api-compat.js";import{callerTrust as mn,isPaired as I,parseExtensionIds as gn,capRunOptions as yn,engineHonoursReach as wn,createPairingStore as Sn,formatPairingCode as bn}from"./pii/trust.js";const g="0.42.0",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",b=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,O={claude:{engine:Ie,label:"Claude Code"},codex:{engine:Ne,label:"Codex"},antigravity:{engine:De,label:"Antigravity",tools:!1},pi:{engine:_e,label:"Pi"},opencode:{engine:He,label:"OpenCode"},hermes:{engine:We,label:"Hermes"},kiro:{engine:Be,label:"Kiro"},copilot:{engine:Me,label:"GitHub Copilot"},deepseek:{engine:Ue,label:"DeepSeek Harness"},custom:{engine:Le,label:"Custom",hidden:!0}};function fe(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const kn=gn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=mn({origin:n.headers.origin||"",hasToken:we(n),extensionIds:kn})),n.chatpanelTrust}function Tn(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function En(n,e){const t=n.headers.origin||"",o=fe(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function vn(n){if(!J.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(t)}const D=_(v.homedir(),".chatpanel","bridge-token");let T="";function On(){try{Re(D)&&(T=Q(D,"utf8").trim()),T||(T=Ae(32).toString("hex"),Pe(_(v.homedir(),".chatpanel"),{recursive:!0}),$e(D,T,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const me=Sn({random:()=>Ce(0,1e6)/1e6});function An(n){if(!T)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=me.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Cn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=me.claim(t?.code);return o.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:T})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function xn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:g})}let H=null;async function ge(){if(H)return H;const{createChannelService:n}=await import("./channels/service.js");return H=n({home:_(v.homedir(),".chatpanel"),dataDir:_(v.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${b}`,token:T},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function ye(n,e,t){try{const o=await ge(),r=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await o.status());if(t==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await o.pair()):t==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?i(e,200,await o.update(r)):t==="disconnect"?i(e,200,await o.stop({forget:!!r.forget})):i(e,404,{error:"unknown channel action"})}catch(o){return i(e,400,{error:o?.message||String(o)})}}function we(n){if(!T)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(T);return o.length===r.length&&xe(o,r)}const Pn=new Set(["/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/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"]),$n=new Set(["/debug"]),Rn=n=>$n.has(n),In=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function Nn(n,e){if(!vn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!fe(t))return"forbidden origin";const o=n.method==="POST"&&Pn.has(e)||n.method==="GET"&&Rn(e)||In(n.method,e);return o&&!(Tn(t)||we(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!_n.has(e)?Dn:null}const Dn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",_n=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function X(n,e,t){const o=N(n),r=St(yn(t,o));if(!wn(e,r.reach))return{error:`${I(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(o)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=r.reach,s=I(o)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:r,note:s}}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function m(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}async function Hn(n){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 Ge(s).catch(()=>[]);return{id:s,label:c,available:h.ok,reason:h.reason,connectors:y,...l===!1?{tools:!1}:{}}})),t=Wt()?{current:g,updateAvailable:!1,embedded:"gateway"}:await Ut(g).catch(()=>({current:g,updateAvailable:!1})),o=await Ye().catch(()=>null),r=await st().catch(()=>null),a=await te().status().catch(s=>({enabled:!1,reason:s.message}));i(n,200,{ok:!0,version:g,agents:e,update:t,workspace:ft,sandbox:a,localMcp:Lt(),processes:Tt(),worktrees:ae,secretBackend:oe(),warm:Kt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...o?{skills:o}:{},...r?{agentDefs:r}:{}})}async function Bn(n,e,t){const{index:o,problems:r}=await G({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:Xe(o),problems:r})}async function Mn(n,e,t){i(n,200,{ok:!0,quarantined:await Ve(e,t)})}async function Un(n,e,t,o){const{index:r}=await G({extraDirs:t,workdir:o}),a=ze(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function Wn(n,e,t,o,r){const{index:a}=await G({extraDirs:o,workdir:r}),s=await Ke(a,e,t);if(s.error)return i(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(n,200,{ok:!0,...s})}async function Gn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{const o=await Qe({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return L(),i(e,200,o)}catch(o){return i(e,z(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function Ln(n,e,t,o){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}try{const a=await Ze({name:t,path:o,text:r?.text??""});return L(),i(e,200,a)}catch(a){return i(e,z(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function jn(n,e){try{const t=await qe({name:e});return L(),i(n,200,t)}catch(t){return i(n,z(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function z(n){return n instanceof et?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Se(n,e){return nt({roots:tt(process.env,v.homedir(),n,e)})}async function Fn(n,e,t){const{index:o,quarantined:r,problems:a}=await Se(e,t);i(n,200,{ok:!0,agents:ot(o),...r.length?{quarantined:r.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...a.length?{problems:a}:{}})}async function Jn(n,e,t,o){const{index:r}=await Se(t,o),a=rt(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function Xn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,{ok:!0,...await at({agent:t?.agent,to:t?.to})})}catch(o){return i(e,be(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function zn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,await it({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(o){return i(e,be(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}function be(n){if(n instanceof ct){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function Kn(){return(await Promise.all(Object.entries(O).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function ke(n,e=""){const t=await Kn();if(e){const o=t.find(r=>r.id===e);return o?i(n,200,o):i(n,404,S(new R(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function Yn(n){try{const e=await se(g);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>Z(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function Vn(n,e){let t;try{t=await m(n)}catch(f){return i(e,400,{error:"Bad JSON: "+f.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=X(n,t.agent,t.options||{});if(r.error)return i(e,403,{error:r.error});t.options=r.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=f=>{e.writableEnded||e.write(`data: ${JSON.stringify(f)}
|
|
2
|
+
import{createServer as xe}from"node:http";import v from"node:os";import{randomBytes as Pe,randomInt as $e,timingSafeEqual as Re}from"node:crypto";import{mkdirSync as Ie,writeFileSync as Ne,readFileSync as Q,existsSync as De}from"node:fs";import{join as _}from"node:path";import*as _e from"./engines/claude.js";import*as He from"./engines/codex.js";import*as Me from"./engines/antigravity.js";import{pi as Be,opencode as Ue,kiro as We,copilot as Le,deepseek as Ge,hermes as je}from"./engines/cli-agents.js";import{connectorsFor as Fe}from"./connectors.js";import*as Je from"./engines/custom.js";import{installService as Xe,uninstallService as ze,serviceStatus as Ke,restartService as Z}from"./service.js";import{skillIndex as L,listRecords as Ye,readRecord as Ve,readPackageFile as Qe,skillsHealth as Ze,quarantinedSkills as qe,clearSkillCache as G}from"./skills.js";import{writeSkillPackage as et,writeSkillFile as tt,deleteSkillPackage as nt,SkillWriteError as ot}from"./skill-write.js";import{agentDefRoots as rt,scanAgentDefs as at,listAgentDefs as it,readAgentDef as st,planAgentExport as ct,exportAgentDef as lt,agentDefsHealth as dt,AgentDefError as ut}from"./agent-defs.js";import{capabilityToolSpecs as ht,runCapabilityTool as pt}from"./mcp-capabilities.js";import{createSession as ft,deleteSession as q,getSession as ee,activeSession as mt,relayToolCall as gt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as yt,isDefaultWorkdir as wt,resolveWorkdir as St,writeScopeNote as bt}from"./workdir.js";import{sandbox as te,runSandboxCli as kt,withGrant as ne,withoutOutsideWhenCapped as Tt,grantedWriteRoots as Et,acceptRefusalReport as vt,liveProcesses as Ot}from"./sandbox.js";import{gitState as At,gitDelta as Ct}from"./scm.js";import{listConnections as xt,putConnection as Pt,removeConnection as $t,runEnvFor as Rt,testConnection as It,secretBackend as oe}from"./connections.js";import{worktreeFor as re,listWorktrees as Nt,removeWorktree as Dt,withHook as _t,WORKTREE_ROOT as ae}from"./worktree.js";import{AGENT_CLIS as Ht,agentAvailable as Mt,agentInstallDirs as Bt,enrichPath as Ut,enrichAgentEnv as Wt,findAgentBin as Lt,forgetMisses as Gt,primeAgentLookups as jt,resolveCommand as ie}from"./env.js";import"./sanitize.js";import{checkForUpdate as Ft,selfUpdate as se,isEmbedded as ce}from"./update.js";import{callLocalMcp as Jt,localMcpStatus as Xt,signInLocalMcp as zt,signInStatusLocalMcp as Kt}from"./mcp-local.js";import{assertPublicHttpUrl as le,assertPublicWebUrl as de}from"./ssrf.js";import{startRun as ue,endRun as j,cancelRun as Yt,cancelAll as Vt}from"./runs.js";import{closeWarmPools as Qt,warmStatus as Zt}from"./warm.js";import{SESSION_AGENTS as he,listSessions as qt,readSession as en,adoptSession as tn,catchUp as nn}from"./agent-sessions.js";import{agentContext as on}from"./agent-context.js";import{normalizeThread as pe}from"./events/agent-thread.js";import{portClashPlan as rn,serviceManagerOf as an,STANDBY_POLL_MS as sn}from"./events/service-standby.js";import{holdThread as fe}from"./threads.js";import{createSnapshot as cn}from"./health-snapshot.js";import{CompatError as R,anthropicError as F,anthropicStream as ln,chatCompletionStream as dn,completionStream as un,createAnthropicMessage as hn,createChatCompletion as pn,createCompletion as fn,createResponse as mn,openAIError as S,parseAnthropicMessage as gn,parseChatCompletion as yn,parseCompletion as wn,parseResponse as Sn,responseStream as bn}from"./api-compat.js";import{callerTrust as kn,isPaired as I,parseExtensionIds as Tn,capRunOptions as En,engineHonoursReach as vn,createPairingStore as On,formatPairingCode as An}from"./pii/trust.js";const g="0.44.1",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",b=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,O={claude:{engine:_e,label:"Claude Code"},codex:{engine:He,label:"Codex"},antigravity:{engine:Me,label:"Antigravity",tools:!1},pi:{engine:Be,label:"Pi"},opencode:{engine:Ue,label:"OpenCode"},hermes:{engine:je,label:"Hermes"},kiro:{engine:We,label:"Kiro"},copilot:{engine:Le,label:"GitHub Copilot"},deepseek:{engine:Ge,label:"DeepSeek Harness"},custom:{engine:Je,label:"Custom",hidden:!0}};function me(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Cn=Tn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=kn({origin:n.headers.origin||"",hasToken:Se(n),extensionIds:Cn})),n.chatpanelTrust}function xn(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Pn(n,e){const t=n.headers.origin||"",o=me(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function $n(n){if(!J.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(t)}const D=_(v.homedir(),".chatpanel","bridge-token");let T="";function Rn(){try{De(D)&&(T=Q(D,"utf8").trim()),T||(T=Pe(32).toString("hex"),Ie(_(v.homedir(),".chatpanel"),{recursive:!0}),Ne(D,T,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const ge=On({random:()=>$e(0,1e6)/1e6});function In(n){if(!T)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ge.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Nn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=ge.claim(t?.code);return o.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:T})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function Dn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:g})}let H=null;async function ye(){if(H)return H;const{createChannelService:n}=await import("./channels/service.js");return H=n({home:_(v.homedir(),".chatpanel"),dataDir:_(v.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${b}`,token:T},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function we(n,e,t){try{const o=await ye(),r=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await o.status());if(t==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await o.pair()):t==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?i(e,200,await o.update(r)):t==="disconnect"?i(e,200,await o.stop({forget:!!r.forget})):i(e,404,{error:"unknown channel action"})}catch(o){return i(e,400,{error:o?.message||String(o)})}}function Se(n){if(!T)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(T);return o.length===r.length&&Re(o,r)}const _n=new Set(["/agent-context","/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/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"]),Hn=new Set(["/debug"]),Mn=n=>Hn.has(n),Bn=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function Un(n,e){if(!$n(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!me(t))return"forbidden origin";const o=n.method==="POST"&&_n.has(e)||n.method==="GET"&&Mn(e)||Bn(n.method,e);return o&&!(xn(t)||Se(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!Ln.has(e)?Wn:null}const be=()=>ce()?"chatpanel-gateway pair":"chatpanel-bridge pair",Wn=`forbidden: this client is not paired with the bridge — run \`${be()}\` and enter the code in ChatPanel Settings`,Ln=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function X(n,e,t){const o=N(n),r=Tt(En(t,o));if(!vn(e,r.reach))return{error:`${I(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(o)?"raise the tier":`pair this client (${be()})`} to use ${e}`};const a=r.reach,s=I(o)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:r,note:s}}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function m(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}const ke=cn({compute:Gn});async function Gn(){await jt();const n=await Promise.all(Object.entries(O).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:c,tools:l}])=>{const d=await s.available().catch(y=>({ok:!1,reason:String(y?.message||y)})),h=await Fe(a).catch(()=>[]);return{id:a,label:c,available:d.ok,reason:d.reason,connectors:h,...l===!1?{tools:!1}:{}}})),e=ce()?{current:g,updateAvailable:!1,embedded:"gateway"}:await Ft(g).catch(()=>({current:g,updateAvailable:!1})),t=await Ze().catch(()=>null),o=await dt().catch(()=>null),r=await te().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:o,sandboxStatus:r}}async function jn(n,{fresh:e=!1}={}){e&&Gt();const{at:t,value:{agents:o,update:r,skills:a,agentDefs:s,sandboxStatus:c}}=await ke.get({fresh:e});i(n,200,{ok:!0,version:g,agents:o,update:r,checkedAt:t,workspace:yt,sandbox:c,localMcp:Xt(),processes:Ot(),worktrees:ae,secretBackend:oe(),warm:Zt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...a?{skills:a}:{},...s?{agentDefs:s}:{}})}async function Fn(n,e,t){const{index:o,problems:r}=await L({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:Ye(o),problems:r})}async function Jn(n,e,t){i(n,200,{ok:!0,quarantined:await qe(e,t)})}async function Xn(n,e,t,o){const{index:r}=await L({extraDirs:t,workdir:o}),a=Ve(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function zn(n,e,t,o,r){const{index:a}=await L({extraDirs:o,workdir:r}),s=await Qe(a,e,t);if(s.error)return i(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(n,200,{ok:!0,...s})}async function Kn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{const o=await et({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return G(),i(e,200,o)}catch(o){return i(e,z(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function Yn(n,e,t,o){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}try{const a=await tt({name:t,path:o,text:r?.text??""});return G(),i(e,200,a)}catch(a){return i(e,z(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function Vn(n,e){try{const t=await nt({name:e});return G(),i(n,200,t)}catch(t){return i(n,z(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function z(n){return n instanceof ot?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Te(n,e){return at({roots:rt(process.env,v.homedir(),n,e)})}async function Qn(n,e,t){const{index:o,quarantined:r,problems:a}=await Te(e,t);i(n,200,{ok:!0,agents:it(o),...r.length?{quarantined:r.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...a.length?{problems:a}:{}})}async function Zn(n,e,t,o){const{index:r}=await Te(t,o),a=st(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function qn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,{ok:!0,...await ct({agent:t?.agent,to:t?.to})})}catch(o){return i(e,Ee(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function eo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,await lt({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(o){return i(e,Ee(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}function Ee(n){if(n instanceof ut){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function to(){return(await Promise.all(Object.entries(O).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function ve(n,e=""){const t=await to();if(e){const o=t.find(r=>r.id===e);return o?i(n,200,o):i(n,404,S(new R(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function no(n){try{const e=await se(g);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>Z(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function oo(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=X(n,t.agent,t.options||{});if(r.error)return i(e,403,{error:r.error});t.options=r.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
|
|
3
3
|
|
|
4
|
-
`)};let s=!1;const
|
|
4
|
+
`)};let s=!1;const c=`run_${Math.random().toString(36).slice(2,10)}`,l=ue(c),d={signal:l.signal,abort:()=>l.cancel("client")},h=()=>{s=!0,l.cancel("disconnected")};n.on("close",h),e.on("close",h),e.on("error",h);const y=p=>{s||a(p)};a({type:"run",id:c}),r.note&&a({type:"status",text:r.note});let f=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const p=t.options.workspace;if(f=await re({repo:p.repo,projectId:p.projectId,jobId:p.jobId,base:p.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),j(c),e.writableEnded||e.end();return}}const Y=f?f.path:St(t.options?.workingDir);let A=null;{const p=Y,C=!!f||!wt(t.options?.workingDir),w=bt(t.agent,t.options?.permissionMode,p,Et(p,{grant:t.options?.sandbox}));a({type:"workdir",path:p,isDefault:!C,writeScope:w||void 0}),a({type:"status",text:`Working in ${p}${C?"":" (default)"}`}),w&&a({type:"status",text:w}),A=await At(p),A&&a({type:"scm",phase:"before",...A})}let W=null;if(A||f){const p=Array.isArray(t.options?.grants)?t.options.grants:[],{env:C,connection:w}=Rt({remote:A?.remote||null,grants:p,branch:f?.branch||null,connectionId:t.options?.connectionId||null});W=_t(C),f&&a({type:"workspace",path:f.path,branch:f.branch,base:f.base,created:f.created,repo:f.repo,...w?{connection:w}:{}}),w&&a({type:"status",text:`Git credential: ${w.kind} · ${w.host}${w.hasSecret?"":" (no token stored)"} · push: ${C.CHATPANEL_SCM_PUSH==="own"?`${f?.branch} only`:C.CHATPANEL_SCM_PUSH}`})}const V=t.approvals===!0,P={...t.options||{},...f?{workingDir:f.path}:{},...W?{runEnv:W}:{},approvals:V};let $=null;(t.pageTools?.specs?.length||V)&&($=ft(y,t.pageTools?.specs||[]),P.permissionSession=$,t.pageTools?.specs?.length&&(P.mcp={url:`http://${k}:${b}/mcp/${$.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));try{await ne(P.sandbox,()=>fe(t.agent,P,d.signal,()=>o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:P,images:Array.isArray(t.images)?t.images:[]},y,{signal:d.signal})))}catch(p){u("error",`${t.agent} chat failed: ${p?.message||p}`),p?.detail&&u("error",`${t.agent} said: ${p.detail}`),a({type:"error",error:p?.message||String(p)})}finally{if(!s){const p=await Ct(Y,A).catch(()=>null);p&&y({type:"scm",phase:"after",...p})}j(c),$&&q($.id),e.writableEnded||e.end()}}async function ro(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:xt(),secretBackend:oe()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await m(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:Pt(o.connection||o,{token:o.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const r=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return r?r[2]==="delete"?i(e,200,{ok:$t(r[1])}):i(e,200,It(r[1],o.remote||"")):i(e,404,{error:"Not found"})}async function ao(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:ae,worktrees:await Nt()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await m(n);if(t==="/worktrees"){const r=await re({repo:o.repo,projectId:o.projectId,jobId:o.jobId,base:o.base||null});return i(e,r.error?400:200,r.error?{error:r.error}:{ok:!0,...r})}if(t==="/worktrees/remove"){const r=await Dt({projectId:o.projectId,jobId:o.jobId,force:!!o.force});return i(e,r.ok?200:400,r)}return i(e,404,{error:"Not found"})}async function E(n,e,t){const o=O[n.agent];if(!o||o.hidden)throw new R(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const r=await o.engine.available().catch(d=>({ok:!1,reason:d?.message||String(d)}));if(!r.ok)throw new R(r.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=ue(a),c=()=>s.cancel("disconnected");t.on("close",c);let l="";try{return await ne(n.options?.sandbox,()=>fe(n.agent,n.options,s.signal,()=>o.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},d=>{d?.type==="delta"&&d.text?(l+=d.text,e(d.text)):d?.type==="done"&&d.text&&!l&&(l=d.text,e(d.text))},{signal:s.signal}))),l}finally{t.off("close",c),j(a)}}function M(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
|
|
5
5
|
|
|
6
|
-
`)}function
|
|
6
|
+
`)}function B(n,e,t){n.writableEnded||n.write(`event: ${e}
|
|
7
7
|
data: ${JSON.stringify(t)}
|
|
8
8
|
|
|
9
|
-
`)}async function U(n,e,t,o){try{const r=t(await m(n)),a=X(n,r.agent,r.options||{});if(a.error)throw new R(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new R(`Bad JSON: ${r.message}`):r)),null}}async function qn(n,e){const t=await U(n,e,un,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,sn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}B(e);const o=on(t.requestedModel,r=>x(e,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){x(e,S(r))}x(e,"[DONE]"),e.end()}async function eo(n,e){const t=await U(n,e,hn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,cn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}B(e);const o=rn(t.requestedModel,r=>x(e,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){x(e,S(r))}x(e,"[DONE]"),e.end()}async function to(n,e){const t=await U(n,e,pn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,ln(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}B(e);const o=fn(t.requestedModel,r=>M(e,r.type,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...S(r)};M(e,"error",a)}e.end()}async function no(n,e){const t=await U(n,e,dn,F);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,an(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,F(r))}B(e);const o=nn(t.requestedModel,(r,a)=>M(e,r,a));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){M(e,"error",F(r))}e.end()}async function oo(n,e){let t={};try{t=await m(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?Jt(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function Te(n,e,t){let o;try{o=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=t?ee(t):ht(),a=c=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:c})},s=(c,l)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:c,message:l}});if(o.id==null)return e.writeHead(202),e.end();if(o.method==="initialize")return a({protocolVersion:o.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const d=lt();if(o.method==="tools/list"){const c=r?r.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...d,...c]})}if(o.method==="tools/call"){const c=await dt(o.params?.name,o.params?.arguments||{});if(c)return a(c);if(!r)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 a(await pt(r,o.params?.name,o.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function ro(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{},r=t.message;if(!o.command||!r)return i(e,400,{error:"need server.command and message"});try{const a=await Gt({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox},r);return r.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function ao(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{};if(!o.command)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const r={key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox};try{return i(e,200,t.status?Ft(r):await jt(r))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function io(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const{url:o,headers:r,message:a}=t||{};if(!o||!a)return i(e,400,{error:"need url and message"});let s;try{s=ce(o)}catch(h){return i(e,400,{error:String(h?.message||h)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[h,y]of Object.entries(r)){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(a),redirect:"follow",signal:c.signal});try{h.url&&ce(h.url)}catch(p){return i(e,400,{error:String(p?.message||p)})}const y=await h.text().catch(()=>"");return i(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 i(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(l)}}const Ee=256*1024,so=5,co=8e3;async function lo(n){let e=le(n);const t=new AbortController,o=setTimeout(()=>t.abort(),co);try{for(let r=0;r<=so;r++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${g} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=le(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const s=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:po(await uo(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function uo(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,Ee);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(r+=s.byteLength,o+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(o)||r>=Ee))break}}finally{try{await e.cancel()}catch{}}return o}function ho(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function po(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?ho(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function fo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=t&&t.url;if(!o||typeof o!="string")return i(e,400,{error:"need url"});try{const r=await lo(o);return i(e,200,{title:r.title||null,url:r.url||o})}catch(r){const a=r?.name==="AbortError"?"timed out":String(r?.message||r);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function mo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=ee(t.session);if(!o)return i(e,404,{error:"no such session"});const r=o.pending.get(t.id);return r?(o.pending.delete(t.id),r.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function go(n,e){let t;try{t=await m(n)}catch(c){return i(e,400,{error:"Bad JSON: "+c.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=String(t.prompt||"").slice(0,6e3);if(!r)return i(e,400,{error:"Empty prompt"});const a=t.model||"",s=X(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const d=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let c="";return typeof o.engine.complete=="function"?c=await o.engine.complete({prompt:r,system:d,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:d,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),i(e,200,{text:(c||"").trim()})}catch(c){return i(e,502,{error:c?.message||String(c)})}}async function yo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof o.engine.listModels!="function")return i(e,200,{models:[]});try{const r=await o.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return i(e,502,{error:r?.message||String(r)})}}async function wo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(t.command||"").trim();if(!o)return i(e,400,{error:"No command"});let r=null;try{r=ie(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}async function So(n,e,t){let o;try{o=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(o?.agent||"");if(!ue.includes(r))return i(e,404,{error:`${r||"that agent"} keeps no sessions Chap can read (it can: ${ue.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await Yt(r,{limit:o.limit})});if(t==="/agent-sessions/read"){const a=await Vt(r,String(o.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=he({id:o.thread?.id??o.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const s=await Qt(r,String(o.id||""),a.id);return s?i(e,200,{session:s}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=he({id:o.thread?.id??o.thread});return a?i(e,200,await Zt(r,a.id,Array.isArray(o.messages)?o.messages:[])):i(e,400,{error:"catchup needs the Chap conversation: { thread: { id } }"})}return i(e,404,{error:"Not found"})}catch(a){return i(e,a?.status||500,{error:a?.message||String(a)})}}const K=Oe(async(n,e)=>{if(En(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const o=Nn(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return Hn(e);const r=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return Bn(e,r,a);if(n.method==="GET"&&t.pathname==="/skills-quarantined")return Mn(e,r,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return Fn(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return Xn(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return zn(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return Jn(e,decodeURIComponent(t.pathname.slice(12)),r,a);if(n.method==="POST"&&t.pathname==="/skills")return Gn(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),d=s.indexOf("/file/");return d===-1?n.method==="DELETE"?jn(e,decodeURIComponent(s)):i(e,405,{ok:!1,error:"use POST /skills to save a skill"}):n.method==="DELETE"?i(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):Ln(n,e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),d=s.indexOf("/file/");return d===-1?Un(e,decodeURIComponent(s),r,a):Wn(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return Qn(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Zn(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return ke(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return ke(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:g,agents:Object.fromEntries(Nt.map(d=>[d,s?Mt(d)||ie(d)?.kind||null:Dt(d)])),...s?{home:v.homedir(),path:process.env.PATH,installDirs:_t(v.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return So(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return Vn(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Cn(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return An(e);if(n.method==="POST"&&t.pathname==="/whoami")return xn(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return qn(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return eo(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return to(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return no(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return Te(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const s=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return Te(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return q(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ye(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ye(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return oo(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return mo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await m(n)}catch{s=null}const d=kt(s||{});return e.writeHead(d?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return ro(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return ao(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return io(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return fo(n,e);if(n.method==="POST"&&t.pathname==="/complete")return go(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return yo(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return wo(n,e);if(n.method==="POST"&&t.pathname==="/update")return Yn(e);i(e,404,{error:"Not found"})}catch(r){i(e,500,{error:r?.message||String(r)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function bo(n){let e="";const t=[];let o=!1,r=!1;const a=()=>{r&&!o&&!t.length&&process.exit(0)},s=async()=>{if(!o){for(o=!0;t.length;){const d=t.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(n,{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
|
-
`)}catch(
|
|
11
|
-
`)}}o=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",
|
|
12
|
-
`))>=0;){const
|
|
9
|
+
`)}async function U(n,e,t,o){try{const r=t(await m(n)),a=X(n,r.agent,r.options||{});if(a.error)throw new R(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new R(`Bad JSON: ${r.message}`):r)),null}}async function io(n,e){const t=await U(n,e,yn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,pn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=dn(t.requestedModel,r=>x(e,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){x(e,S(r))}x(e,"[DONE]"),e.end()}async function so(n,e){const t=await U(n,e,wn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,fn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=un(t.requestedModel,r=>x(e,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){x(e,S(r))}x(e,"[DONE]"),e.end()}async function co(n,e){const t=await U(n,e,Sn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,mn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=bn(t.requestedModel,r=>B(e,r.type,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...S(r)};B(e,"error",a)}e.end()}async function lo(n,e){const t=await U(n,e,gn,F);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,hn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,F(r))}M(e);const o=ln(t.requestedModel,(r,a)=>B(e,r,a));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){B(e,"error",F(r))}e.end()}async function uo(n,e){let t={};try{t=await m(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?Yt(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function Oe(n,e,t){let o;try{o=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=t?ee(t):mt(),a=l=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:l})},s=(l,d)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:l,message:d}});if(o.id==null)return e.writeHead(202),e.end();if(o.method==="initialize")return a({protocolVersion:o.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const c=ht();if(o.method==="tools/list"){const l=r?r.specs.map(d=>({name:d.name,description:d.description,inputSchema:d.parameters||{type:"object",properties:{}}})):[];return a({tools:[...c,...l]})}if(o.method==="tools/call"){const l=await pt(o.params?.name,o.params?.arguments||{});if(l)return a(l);if(!r)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 a(await gt(r,o.params?.name,o.params?.arguments||{}))}catch(d){return a({content:[{type:"text",text:`error: ${d?.message||d}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function ho(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{},r=t.message;if(!o.command||!r)return i(e,400,{error:"need server.command and message"});try{const a=await Jt({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox},r);return r.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function po(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{};if(!o.command)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const r={key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox};try{return i(e,200,t.status?Kt(r):await zt(r))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function fo(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const{url:o,headers:r,message:a}=t||{};if(!o||!a)return i(e,400,{error:"need url and message"});let s;try{s=le(o)}catch(h){return i(e,400,{error:String(h?.message||h)})}const c={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[h,y]of Object.entries(r)){const f=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(c[h]=String(y))}const l=new AbortController,d=setTimeout(()=>l.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:c,body:JSON.stringify(a),redirect:"follow",signal:l.signal});try{h.url&&le(h.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const y=await h.text().catch(()=>"");return i(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 i(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(d)}}const Ae=256*1024,mo=5,go=8e3;async function yo(n){let e=de(n);const t=new AbortController,o=setTimeout(()=>t.abort(),go);try{for(let r=0;r<=mo;r++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${g} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=de(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const s=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:bo(await wo(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function wo(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,Ae);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(r+=s.byteLength,o+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(o)||r>=Ae))break}}finally{try{await e.cancel()}catch{}}return o}function So(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function bo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?So(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function ko(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=t&&t.url;if(!o||typeof o!="string")return i(e,400,{error:"need url"});try{const r=await yo(o);return i(e,200,{title:r.title||null,url:r.url||o})}catch(r){const a=r?.name==="AbortError"?"timed out":String(r?.message||r);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function To(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=ee(t.session);if(!o)return i(e,404,{error:"no such session"});const r=o.pending.get(t.id);return r?(o.pending.delete(t.id),r.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function Eo(n,e){let t;try{t=await m(n)}catch(l){return i(e,400,{error:"Bad JSON: "+l.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=String(t.prompt||"").slice(0,6e3);if(!r)return i(e,400,{error:"Empty prompt"});const a=t.model||"",s=X(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const c=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let l="";return typeof o.engine.complete=="function"?l=await o.engine.complete({prompt:r,system:c,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:c,options:s.options},d=>{d.type==="delta"?l+=d.text||"":d.type==="done"&&d.text&&(l+=d.text)}),i(e,200,{text:(l||"").trim()})}catch(l){return i(e,502,{error:l?.message||String(l)})}}async function vo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof o.engine.listModels!="function")return i(e,200,{models:[]});try{const r=await o.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return i(e,502,{error:r?.message||String(r)})}}async function Oo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(t.command||"").trim();if(!o)return i(e,400,{error:"No command"});let r=null;try{r=ie(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}async function Ao(n,e,t){let o;try{o=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(o?.agent||"");if(!he.includes(r))return i(e,404,{error:`${r||"that agent"} keeps no sessions Chap can read (it can: ${he.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await qt(r,{limit:o.limit})});if(t==="/agent-sessions/read"){const a=await en(r,String(o.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=pe({id:o.thread?.id??o.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const s=await tn(r,String(o.id||""),a.id);return s?i(e,200,{session:s}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=pe({id:o.thread?.id??o.thread});return a?i(e,200,await nn(r,a.id,Array.isArray(o.messages)?o.messages:[])):i(e,400,{error:"catchup needs the Chap conversation: { thread: { id } }"})}return i(e,404,{error:"Not found"})}catch(a){return i(e,a?.status||500,{error:a?.message||String(a)})}}const K=xe(async(n,e)=>{if(Pn(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const o=Un(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return jn(e,{fresh:t.searchParams.get("fresh")==="1"});const r=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return Fn(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-context"){const s=await m(n).catch(()=>({})),c=s?.options&&typeof s.options=="object"?s.options:{},l={...c.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof c.permissionMode=="string"?{permissionMode:c.permissionMode}:{},...typeof c.workingDir=="string"&&c.workingDir?{workingDir:c.workingDir}:{},...typeof c.model=="string"&&c.model?{model:c.model}:{}};return i(e,200,await on({agent:typeof s?.agent=="string"?s.agent:"claude",options:l}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return Jn(e,r,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return Qn(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return qn(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return eo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return Zn(e,decodeURIComponent(t.pathname.slice(12)),r,a);if(n.method==="POST"&&t.pathname==="/skills")return Kn(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?n.method==="DELETE"?Vn(e,decodeURIComponent(s)):i(e,405,{ok:!1,error:"use POST /skills to save a skill"}):n.method==="DELETE"?i(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):Yn(n,e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?Xn(e,decodeURIComponent(s),r,a):zn(e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return ro(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return ao(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return ve(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return ve(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:g,agents:Object.fromEntries(Ht.map(c=>[c,s?Lt(c)||ie(c)?.kind||null:Mt(c)])),...s?{home:v.homedir(),path:process.env.PATH,installDirs:Bt(v.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Ao(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return oo(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Nn(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return In(e);if(n.method==="POST"&&t.pathname==="/whoami")return Dn(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return io(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return so(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return co(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return lo(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return Oe(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const s=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return Oe(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return q(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return we(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return we(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return uo(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return To(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await m(n)}catch{s=null}const c=vt(s||{});return e.writeHead(c?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return ho(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return po(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return fo(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return ko(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Eo(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return vo(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Oo(n,e);if(n.method==="POST"&&t.pathname==="/update")return no(e);i(e,404,{error:"Not found"})}catch(r){i(e,500,{error:r?.message||String(r)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Co(n){let e="";const t=[];let o=!1,r=!1;const a=()=>{r&&!o&&!t.length&&process.exit(0)},s=async()=>{if(!o){for(o=!0;t.length;){const c=t.shift();let l;try{l=JSON.parse(c)}catch{continue}try{const d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:c});if(l.id==null)continue;const h=(await d.text()).trim();h&&process.stdout.write(h+`
|
|
10
|
+
`)}catch(d){l.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:l.id,error:{code:-32e3,message:String(d?.message||d)}})+`
|
|
11
|
+
`)}}o=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",c=>{e+=c;let l;for(;(l=e.indexOf(`
|
|
12
|
+
`))>=0;){const d=e.slice(0,l).trim();e=e.slice(l+1),d&&t.push(d)}s()}),process.stdin.on("end",()=>{r=!0,a()}),process.stdin.resume()}function xo(){Ut(),Wt(),Rn();let n=!1;K.on("error",e=>{if(e&&e.code==="EADDRINUSE"){fetch(`http://127.0.0.1:${b}/health`,{signal:AbortSignal.timeout(1500)}).then(t=>t.ok?t.json():null).catch(()=>null).then(t=>{const o=!!(t?.version&&Array.isArray(t.agents)),r=rn({name:"bridge",self:g,holder:o?{ours:o,version:t.version}:null,managedBy:an(process.env),port:b});if(r.action==="standby"||n&&!t){if(!n)for(const a of r.lines)u("info",a);n=!0,setTimeout(()=>K.listen(b,k),sn);return}if(o)for(const a of r.lines)u("error",a);else u("error",`Port ${b} 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)});return}u("error",`bridge server error: ${e?.message||e}`),process.exit(1)});for(const e of["SIGINT","SIGTERM"])process.on(e,()=>{const t=Vt("shutdown");t&&u("info",`shutdown: stopped ${t} running agent${t===1?"":"s"}`);const o=Qt("shutdown");o&&u("info",`shutdown: closed ${o} warm agent process${o===1?"":"es"}`),te().close(),setTimeout(()=>process.exit(0),t||o?300:0).unref?.(),!t&&!o&&process.exit(0)});K.listen(b,k,async()=>{n&&u("info","standby: the other bridge is gone — this copy has the port now"),n=!1,u("info",`listening on http://${k}:${b}`),ke.warm(),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:e,label:t,hidden:o}]of Object.entries(O)){if(o)continue;const r=await e.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${t}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),ye().then(e=>e.startIfConfigured()).then(e=>{e?.skipped||(e?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${e?.error||"unknown error"}`))}).catch(e=>u("error",`channels: ${e?.message||e}`))})}function Po(){console.log(`ChatPanel Bridge v${g}
|
|
13
13
|
|
|
14
14
|
Usage:
|
|
15
15
|
chatpanel-bridge start the bridge (foreground) on ${k}:${b}
|
|
@@ -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 $o(){const n=process.argv,e=(...t)=>t.some(o=>n.includes(o));if(e("--help","-h"))return Po(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=Q(D,"utf8").trim()}catch{}const o=`http://${k}:${b}`;try{if(!t)throw new Error(`no token at ${D} — is the bridge running?`);const r=await fetch(`${o}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),a=await r.json().catch(()=>({}));if(!r.ok)throw new Error(a.error||`HTTP ${r.status}`);console.log(`Pairing code: ${An(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(r){u("error",`could not get a pairing code from the bridge at ${o}: ${r?.message||r}`),process.exitCode=1}})(),!0;if(n.includes("sandbox"))return kt(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{Xe(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(t){u("error","Install failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--uninstall")){try{ze(),u("info","Removed the login auto-start.")}catch(t){u("error","Uninstall failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--status")){let t=!1;try{t=Ke()}catch(o){u("error",String(o?.message||o))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const Ce=process.argv.indexOf("--mcp-stdio");if(Ce>=0){const n=process.argv[Ce+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Co(n)}else process.argv.includes("--update")?(async()=>{try{const n=await se(g);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),Z()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():$o()||xo();
|