@chatpanel/bridge 0.44.2 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.44.2",
3
+ "version": "0.46.0",
4
4
  "type": "module",
5
5
  "description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
@@ -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 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.
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 s}from"node:path";const c=s(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","runtime-host.js","sandbox-choice.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","access-request.js","policy.js","service-standby.js"];function u(){return[s(c,"node_modules","@chatpanel","events"),s(c,"..","chatpanel-events")].find(e=>i(s(e,"skill-manifest.js")))}const n=process.argv.includes("--check"),a=u();if(!a){const e="chatpanel-events not found (check out ../chatpanel-events).";n&&(console.error(`sync-events --check: ${e}`),process.exit(1)),console.warn(`sync-events: ${e} Leaving src/events as-is.`),process.exit(0)}const l=s(c,"src","events");n||p(l,{recursive:!0});const v=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(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 ✓"));
10
+ `;let d=0;for(const e of f){const o=v(e)+r(s(a,e),"utf8"),t=s(l,e);if((i(t)?r(t,"utf8"):null)!==o){if(n){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}`)}}n&&(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{statSync as B,realpathSync as E}from"node:fs";import q from"node:os";import S from"node:path";import{decideAccess as I,rememberAccess as W,isTooBroadRoot as _,pathInside as A,describeDecision as j,permissionAccessTarget as z}from"./events/access-request.js";import{permissionRequestFromClaude as G,permissionAnswer as u,permissionAllowed as D}from"./events/agent-permission.js";import{normalizeThread as H}from"./events/agent-thread.js";import{COMMON_WRITE as J}from"./events/sandbox-policy.js";import{relayPermission as k}from"./mcp-sessions.js";const p=new Map;function nt(){p.clear()}function st(t,e={}){const o=H(e?.thread);return o&&e?.ephemeral!==!0?`${t}|${e.reach||"local"}|${o.id}`:""}function ot(t){return(p.get(t)||[]).filter(e=>e.allow&&e.what.kind==="path").map(e=>e.what.value)}const w=(t,e)=>t==="~"||t.startsWith("~/")?e+t.slice(1):t,v=t=>{try{return E(t)}catch{return t}},m=(t,e)=>e&&A(t,e)?`~${t.slice(e.length)}`:t;function K(t,{cwd:e,home:o,isDir:i=r=>{try{return B(r).isDirectory()}catch{return!1}}}){const r=S.resolve(e||o,w(String(t),o));return i(r)?r:S.dirname(r)}function L(t,{cwd:e,roots:o=[],home:i}){const r=q.tmpdir();return[e,...o,...J.map(c=>w(c,i)),r,v(r)].filter(Boolean).some(c=>A(t,w(c,i))||A(v(t),v(w(c,i))))}function M(t){return`Not run yet: ChatPanel's sandbox did not include ${t} when you started. The person has just allowed it, and ChatPanel restarts you with that access and resumes this conversation straight after this turn. End this turn now in one short sentence — do not retry, and do not try another way.`}function it({agent:t,label:e=t,key:o="",cwd:i,home:r=q.homedir(),roots:C=()=>[],enabled:c=!0,policy:N=null,now:O=Date.now}={}){let y=o?p.get(o)||[]:[];const a=[],g=[],P=n=>{try{return`${n.tool}\0${JSON.stringify(n.input||{})}`}catch{return""}},F=n=>{y=n,o&&p.set(o,n)},f=(n,d)=>{try{n?.emit?.({type:"status",text:d})}catch{}};return{async ask(n,d,{request:R=null}={}){const l=R||G(d),b=g.indexOf(P(l));if(b>=0&&!a.length)return g.splice(b,1),f(n,"Allowed (you allowed this before the restart)"),u("allow");const T=c?z(l):null;if(!T)return k(n,d,{request:l});const s=K(T,{cwd:i,home:r});if(L(s,{cwd:i,roots:C(),home:r}))return k(n,d,{request:l});if(_(s,r))return f(n,`${e} asked to write in ${m(s,r)} — not offered: ChatPanel never opens a whole home folder or disk to an agent`),u("deny",`ChatPanel's sandbox will not open ${s} — it is a whole home folder or disk. Ask the person for a folder inside it, or write in your working folder.`);const $={what:{kind:"path",value:s,mode:"write"},engine:e,asked:"ahead",scope:"session"},h=I({request:$,grants:y,policy:N,home:r,now:O()});if(h.verdict==="deny")return f(n,j($,h)),u("deny",`ChatPanel's sandbox does not allow writing in ${s} (${h.reason}). Do not retry; tell the person.`);if(h.verdict==="grant")return a.includes(s)||a.push(s),u("deny",M(s));const x=await k(n,d,{request:{...l,access:{folder:m(s,r),mode:"write"}}});return F(W(y,$,D(x)?"allow":"deny",{now:O(),home:r})),D(x)?(a.includes(s)||a.push(s),g.push(P(l)),f(n,`${m(s,r)} is open to ${e} for this chat — restarting it with that access`),u("deny",M(s))):x},restart(){return[...a]},take(){return a.splice(0)},short:n=>m(n,r)}}export{nt as _resetAccessForTest,ot as chatFolders,st as chatKeyOf,it as createAccessGate,K as folderOf,M as restartMessage,L as writableNow};
@@ -0,0 +1,4 @@
1
+ import{exec as C}from"node:child_process";import{readFileSync as O,writeFileSync as L,mkdirSync as P}from"node:fs";import{createHash as R}from"node:crypto";import N from"node:os";import E from"node:path";import{harnessCard as k}from"./events/harness-cards.js";const g="CHATPANEL_AWS_CRED_",T=5,W=10*6e4,K=5*6e4,$=3e4,j=(s,e)=>s==="~"||s.startsWith("~/")?e+s.slice(1):s;function b(s,{home:e=N.homedir(),read:t=r=>O(r,"utf8")}={}){const r={};for(const n of k(s)?.envFrom||[])try{const o=JSON.parse(t(j(n,e)))?.env;if(o&&typeof o=="object"&&!Array.isArray(o))for(const[a,i]of Object.entries(o))typeof i=="string"&&(r[a]=i)}catch{}return r}function M(s){const e=new Map;let t=null;return String(s||"").split(`
2
+ `).forEach((r,n)=>{const o=/^\s*\[\s*([^\]]+?)\s*\]\s*$/.exec(r);if(o){const l=/^(?:profile\s+(.+)|(default))$/.exec(o[1]);t=l?{props:{},lines:{}}:null,t&&e.set((l[1]||l[2]).trim(),t);return}if(!t||/^\s/.test(r)||/^[#;]/.test(r))return;const a=r.indexOf("=");if(a<=0)return;const i=r.slice(0,a).trim().toLowerCase();t.props[i]=r.slice(a+1).trim(),t.lines[i]=n}),e}function v(s,e){let t=e;for(let r=0;r<T;r++){const n=s.get(t);if(!n)return[];if(n.props.credential_process)return[{profile:t,command:n.props.credential_process,line:n.lines.credential_process}];if(!n.props.source_profile||n.props.source_profile===t)return[];t=n.props.source_profile}return[]}function H(s){let e;try{e=JSON.parse(String(s||""))}catch{throw new Error("it did not print JSON")}if(!e||typeof e!="object"||e.Version!==1)throw new Error("its output is not Version 1 of the credential_process format");if(typeof e.AccessKeyId!="string"||!e.AccessKeyId||typeof e.SecretAccessKey!="string"||!e.SecretAccessKey)throw new Error("its output has no AccessKeyId and SecretAccessKey");const t=typeof e.Expiration=="string"?Date.parse(e.Expiration):NaN;return{json:JSON.stringify({Version:1,AccessKeyId:e.AccessKeyId,SecretAccessKey:e.SecretAccessKey,...typeof e.SessionToken=="string"&&e.SessionToken?{SessionToken:e.SessionToken}:{},...Number.isFinite(t)?{Expiration:new Date(t).toISOString()}:{}}),expiresAt:Number.isFinite(t)?t:0}}const D=/^\s*(aws_access_key_id|aws_secret_access_key|aws_session_token)\s*=/i;function G(s,e){const t=String(s||"").split(`
3
+ `);return e.forEach((r,n)=>{t[r.line]=`credential_process = /bin/sh -c 'printf %s "$${g}${n}"'`}),t.filter(r=>!D.test(r)).join(`
4
+ `)}function J(s,e){return new Promise((t,r)=>{C(s,{env:e,timeout:$,windowsHide:!0,maxBuffer:256*1024},(n,o)=>{if(n)return r(new Error(n.killed?`it did not answer in ${$/1e3} s`:`it exited ${n.code??n.signal??"with an error"}`));t(o)})})}const m=new Map;function z(){m.clear()}async function Q({env:s=process.env,engine:e="custom",home:t=N.homedir(),base:r=process.env,platform:n=process.platform,read:o=p=>O(p,"utf8"),run:a=J,now:i=()=>Date.now(),write:l=(p,u)=>{P(E.dirname(p),{recursive:!0,mode:448}),L(p,u,{mode:384})}}={}){if(n==="win32"||s[`${g}0`])return null;const p=b(e,{home:t,read:o}),u=s.AWS_CONFIG_FILE||p.AWS_CONFIG_FILE||E.join(t,".aws","config");let h;try{h=o(u)}catch{return null}const x=s.AWS_PROFILE||p.AWS_PROFILE||s.AWS_DEFAULT_PROFILE||"default",A=v(M(h),x);if(!A.length)return null;const I={};let _=0;for(const[y,d]of A.entries()){const w=`${u}|${d.profile}|${d.command}`;let c=m.get(w);if(!c||i()>=c.until)try{const f=H(await a(d.command,{...r,AWS_PROFILE:d.profile,AWS_CONFIG_FILE:u}));if(f.expiresAt&&f.expiresAt<=i())throw new Error("the credentials it returned have already expired");c={...f,until:f.expiresAt?f.expiresAt-K:i()+W},m.set(w,c)}catch(f){return m.delete(w),{failed:`AWS sign-in: the credential_process of profile "${d.profile}" failed when ChatPanel ran it for this agent — ${f.message}. Run it in a terminal to see why; the agent will try on its own and may not be able to sign in.`}}I[`${g}${y}`]=c.json,c.expiresAt&&(!_||c.expiresAt<_)&&(_=c.expiresAt)}const F=G(h,A),S=E.join(t,".cache","chatpanel","aws",`config-${R("sha256").update(F).digest("hex").slice(0,16)}`);try{l(S,F)}catch(y){return{failed:`AWS sign-in: could not write ${S} (${y.message}) — the agent will try on its own.`}}return{env:{...I,AWS_CONFIG_FILE:S},expiresAt:_,profile:x}}export{z as _resetAwsCacheForTest,Q as awsSignIn,v as credentialProcessChain,b as harnessEnvFrom,M as parseAwsConfig,H as parseProcessOutput,G as shimConfig};
package/src/cli-errors.js CHANGED
@@ -1,6 +1,7 @@
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(/&nbsp;/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||""}
1
+ import{loginRequired as m,signInMessage as k}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(/&nbsp;/g," ").replace(/[ \t]+/g," ")}const b=[/(?: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 b){const n=t.exec(String(e||""))?.[1];if(n)return n}return null}const f=/api error|authentication_error|invalid (?:x-)?api[- ]key|bearer token|anthropic|openai|x-api-key|\baws\b|bedrock|security token/i,v=e=>/\b401\b/.test(e)&&!f.test(e)&&(/\bmcp\b/i.test(e)||!!h(e)),x=e=>/HTTP 403|\b403\b/.test(e)&&!f.test(e),$=[{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:e=>e.split(`
3
+ `).some(x),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 w(e){const t=String(e||""),n=h(t),s=/\bmcp\b/i.test(t)||!!n;for(const i of $)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 y(e){const t=w(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 C(e,t,n,s="",{agentId:i=null}={}){const r=`${n||""}
4
+ ${s||""}`;if(m(r))return k(e,i||A[String(e).toLowerCase()]||null);const o=y(r);if(o)return`${e} exited ${t}: ${o}`;const c=l(r).split(`
5
+ `).map(a=>a.trim()).filter(a=>a&&!p.some(g=>g.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 E=[[/(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,t="",{lines:n=6,width:s=300}={}){return l(`${e||""}
5
6
  ${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};
7
+ `).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=>E.reduce((o,[c,u])=>o.replace(c,u),r)).map(r=>r.length>s?`${r.slice(0,s)}…`:r).join(" ⏎ ")}function P(e,t,n,s="",i={}){return Object.assign(new Error(C(e,t,n,s,i)),{detail:_(n,s)})}export{P as cliError,_ as errorTail,w as mcpFailure,h as mcpServerName,l as stripMarkup,C as summarizeCliError};
@@ -1,3 +1,3 @@
1
- import{unlink as z}from"node:fs/promises";import{spawnRpcChild as K}from"../rpc-child.js";import{spawn as Q}from"node:child_process";import{track as V,sandbox as X}from"../sandbox.js";import{createWarmPool as Y}from"../warm-pool.js";import{registerWarmPool as Z}from"../warm.js";import{createSession as W,deleteSession as P,rebindSession as ee,releaseSession as re,relayPermission as U}from"../mcp-sessions.js";import{resolveClaude as se,buildSpawnSpec as te}from"../env.js";import{loginRequired as B,signInMessage as H}from"../sign-in.js";import{pushExtraArgs as R,FORBIDDEN as q}from"./args.js";import{buildClaudeLaunch as F,claudePrompt as ae,handleMessage as ne,harnessChars as le,writeImages as oe,answerControlRequest as ie}from"./claude.js";const j=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,ue=5e3,d=Z("claude",Y({log:n=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${n}`)}}));function ce(n={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||n.warm===!1)}async function G({spec:n,args:E,cwd:r,env:b,spawnImpl:S,log:g=()=>{},ask:$=null,peers:w=!0}){const u=[...E,"--input-format","stream-json"],[f,c,v]=te(n,u,r,b),p=await X().wrap(f,c,v,{engine:"claude",cwd:r,peers:w});p.record.layer==="none"&&g(`sandbox: claude session runs outside a sandbox — ${p.record.reason}`);const[i,m,C]=[p.bin,p.argv,p.opts];let e=null;const x=new Set;let y="",T=0,I=0,l=null;const h=K(i,m,{spawnOpts:C,spawnImpl:(s,t,a)=>V((S||Q)(s,t,a),p,{kind:"warm"}),jsonrpc:!1,onStderr:s=>{y=(y+s).slice(-2e3),e&&e.touch()},onExit:s=>{if(g(`claude exited: ${s.signal||s.code}${y?` — ${y.trim().split(`
2
- `).pop()}`:""}`),e){const t=e.apiError&&B(e.apiError)?H("Claude Code","claude"):e.apiError?`Claude Code reported an error: ${e.apiError}`:`Claude Code exited (${s.signal||s.code})${y?`: ${y.trim().split(`
3
- `).pop().slice(0,200)}`:""}`;e.finish({status:"died",error:t})}for(const t of x)try{t(s)}catch{}},onMessage:s=>{if(!e||(e.touch(),s.type==="control_response"))return;if(s.type==="control_request"){const a=e;a.asking++,a.touch(),ie(s,$,_=>{try{h.send(_)}catch{}}).catch(()=>{}).finally(()=>{a.asking--,e===a&&a.touch()});return}const t=ne(s,e.emit,e.streamedAny,r,e.flow);t.sessionId&&(l=t.sessionId),t.streamed&&(e.streamedAny=!0),t.result!=null&&(e.resultText=t.result),t.apiError&&(e.apiError=t.apiError),s.type==="result"&&(e.apiError&&B(e.apiError)?e.finish({status:"failed",error:H("Claude Code","claude")}):e.apiError?e.finish({status:"failed",error:`Claude Code reported an error: ${e.apiError}`}):e.finish({status:"completed",error:null}))}});return{get pid(){return h.pid},get alive(){return!h.exited},get sessionId(){return l},onExit(s){x.add(s)},close(){h.close()},async turn({prompt:s,emit:t,signal:a,harness:_=null}){if(h.exited)throw new Error("Claude Code process is gone");if(e)throw new Error("a turn is already running on this process");let k=null,A;const N=new Promise(M=>{A=M}),o={emit:t,flow:{sawText:!1,tail:"",boundary:!1,costUsdBefore:I,harnessChars:_},streamedAny:!1,resultText:"",apiError:null,asking:0,touch(){clearTimeout(k),!o.asking&&(k=setTimeout(()=>o.finish({status:"timeout",error:`Claude Code timed out — no output for ${Math.round(j/1e3)}s.`}),j))},finish(M){e===o&&(clearTimeout(k),e=null,A(M))}};e=o,o.touch();const O=()=>{if(e===o){o.interrupted=!0;try{h.send({type:"control_request",request_id:`stop_${++T}`,request:{subtype:"interrupt"}})}catch{}setTimeout(()=>{e===o&&(o.finish({status:"killed",error:null}),h.kill())},ue).unref?.()}};if(a?.aborted)return o.finish({status:"killed",error:null}),{streamedAny:!1,resultText:"",status:"killed"};a?.addEventListener("abort",O,{once:!0});try{h.send({type:"user",message:{role:"user",content:s}})}catch(M){o.finish({status:"failed",error:M.message})}const L=await N;o.flow.costUsdTotal!=null&&(I=o.flow.costUsdTotal),a?.removeEventListener("abort",O),L.status==="timeout"&&h.kill();const J=L.status==="killed"?"killed":o.interrupted?"interrupted":L.status;return{streamedAny:o.streamedAny,resultText:o.resultText,status:J,error:L.error,sessionId:l}}}}const D=new Set;async function de({key:n,spec:E,options:r,label:b,launch:S=G,log:g=()=>{},force:$=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!$||!n||!E||r?.ephemeral===!0||D.has(n)||d.peek({key:n,messages:[{role:"user",content:""}]}))return!1;D.add(n);const w=d.reserve({key:n,label:`${b} (spare)`,evict:!1});if(!w)return D.delete(n),!1;let u=null,f=null;try{let c=r.mcp;const v=r.mcp?.specs||[];(c?.url&&v.length||r.approvals===!0)&&(u=W(()=>{},v),c?.url&&v.length&&(c={...c,url:`${c.url.replace(/\/[^/]*$/,"")}/${u.id}`})),f=await F({system:"",options:{...r,mcp:c},tag:`spare-${Date.now()}-${Math.random().toString(36).slice(2)}`});const p=[...f.args];R(p,r.extraArgs,q.claude,()=>{});const i=u,m=await S({spec:E,args:p,cwd:f.cwd,env:f.runEnv,ask:f.approvals&&i?e=>U(i,e):null,peers:f.peers});m.mcpSession=u,m.systemSent="",d.attach(w,m);const C=f.cleanup;return m.onExit(()=>{u&&P(u.id),C()}),d.release(w,{user:null,answered:!1}),g(`warm ${b}: spare ready`),!0}catch(c){return u&&P(u.id),f?.cleanup?.(),d.drop(w,`spare launch failed: ${c.message}`),!1}finally{D.delete(n)}}async function xe({messages:n,system:E,options:r,images:b,thread:S=null},g,{signal:$,launch:w=G}={}){if(!ce(r))return{handled:!1,reason:"not eligible"};const u=se();if(!u)return{handled:!1,reason:"claude not resolvable"};const f=`${Date.now()}-${Math.random().toString(36).slice(2)}`,c=(r.mcp?.specs||[]).map(s=>s?.name).filter(Boolean),v=[];R(v,r.extraArgs,q.claude,()=>{});const p=JSON.stringify({agent:"claude",cwd:r.workingDir||"",mode:r.permissionMode||"default",model:r.model||"",local:r.useLocalConfig!==!1,reach:r.reach||"",tools:[...c].sort(),extra:v,approvals:r.approvals===!0,env:r.runEnv?Object.keys(r.runEnv).sort().map(s=>`${s}=${r.runEnv[s]}`):[],hosts:r.sandbox?.hosts?(Array.isArray(r.sandbox.hosts)?r.sandbox.hosts:String(r.sandbox.hosts).split(/[\s,;]+/)).map(s=>String(s).trim().toLowerCase()).filter(Boolean).sort():[],outside:r.sandbox?.outside===!0,ephemeral:r.ephemeral===!0});let i=d.acquire({key:p,messages:n}),m=!1;const C=!i&&S?.plan.mode==="resume"?S.plan.sessionId:null;if(!i){if(i=d.reserve({key:p,label:`claude ${r.workingDir||"home"}`,evict:r.ephemeral!==!0}),!i)return{handled:!1,reason:"all warm slots busy"};m=!0;let s=null,t=null;try{let a=r.mcp;(a?.url&&c.length||r.approvals===!0)&&(s=W(g,a?.specs||[]),a?.url&&c.length&&(a={...a,url:`${a.url.replace(/\/[^/]*$/,"")}/${s.id}`})),t=await F({system:E,options:{...r,mcp:a},tag:f,resume:C,name:S?.thread.title||""});const _=[...t.args];R(_,r.extraArgs,q.claude,g);const k=s,A=await w({spec:u,args:_,cwd:t.cwd,env:t.runEnv,ask:t.approvals&&k?o=>U(k,o):null,peers:t.peers});A.mcpSession=s,A.systemSent=String(E||""),d.attach(i,A),C&&d.holds(i,n);const N=t.cleanup;A.onExit(()=>{s&&P(s.id),N()})}catch(a){return s&&P(s.id),t?.cleanup(),d.drop(i,`launch failed: ${a.message}`),{handled:!1,reason:a.message}}}const e=i.session;e.mcpSession&&ee(e.mcpSession,g,r.mcp?.specs);const x=n[n.length-1],y=await oe(b,f),T=String(E||""),I=ae(m&&!C?n:C?S.plan.tail||[x]:[x],y,!m&&T!==e.systemSent?T:"");e.systemSent=T;let l;try{l=await e.turn({prompt:I,emit:g,signal:$,harness:le({prompt:I,system:m?T:"",specs:m?r.mcp?.specs:null})})}finally{y.forEach(s=>z(s).catch(()=>{})),e.mcpSession&&re(e.mcpSession)}if($?.aborted||l.status==="interrupted")return l.status==="interrupted"&&e.alive?d.release(i,{user:String(x?.content||""),answered:l.streamedAny}):d.drop(i,"stopped"),{handled:!0};if(l.status!=="completed"){if(d.drop(i,l.error||l.status),!l.streamedAny)return{handled:!1,reason:l.error||l.status};throw new Error(l.error||`Claude Code ${l.status}`)}g({type:"done",text:l.streamedAny?"":l.resultText}),d.release(i,{user:String(x?.content||""),answered:!0});const h=l.sessionId||e.sessionId||null;return setTimeout(()=>{de({key:p,spec:u,options:r,label:`claude ${r.workingDir||"home"}`,launch:w}).catch(()=>{})},250).unref?.(),{handled:!0,completed:!0,sessionId:h}}export{xe as chatWarm,G as launchClaudeSession,d as pool,de as prewarmClaude,ce as warmEligible};
1
+ import{unlink as z}from"node:fs/promises";import{spawnRpcChild as K}from"../rpc-child.js";import{spawn as Q}from"node:child_process";import{track as V,sandbox as X}from"../sandbox.js";import{createWarmPool as Y}from"../warm-pool.js";import{registerWarmPool as Z}from"../warm.js";import{createSession as O,deleteSession as D,rebindSession as ee,releaseSession as re,relayPermission as W}from"../mcp-sessions.js";import{resolveClaude as se,buildSpawnSpec as te}from"../env.js";import{loginRequired as U,signInMessage as B}from"../sign-in.js";import{pushExtraArgs as q,FORBIDDEN as G}from"./args.js";import{buildClaudeLaunch as H,claudePrompt as ae,handleMessage as ne,harnessChars as le,writeImages as oe,answerControlRequest as ie}from"./claude.js";const F=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,ue=5e3,u=Z("claude",Y({log:o=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${o}`)}}));function ce(o={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||o.warm===!1)}async function j({spec:o,args:A,cwd:e,env:$,spawnImpl:w,log:g=()=>{},ask:T=null,peers:y=!0}){const c=[...A,"--input-format","stream-json"],[p,d,E]=te(o,c,e,$),f=await X().wrap(p,d,E,{engine:"claude",cwd:e,peers:y});f.record.layer==="none"&&g(`sandbox: claude session runs outside a sandbox — ${f.record.reason}`);const[i,m,S]=[f.bin,f.argv,f.opts];let r=null;const b=new Set;let x="",I=0,M=0,l=null;const h=K(i,m,{spawnOpts:S,spawnImpl:(s,t,a)=>V((w||Q)(s,t,a),f,{kind:"warm"}),jsonrpc:!1,onStderr:s=>{x=(x+s).slice(-2e3),r&&r.touch()},onExit:s=>{if(g(`claude exited: ${s.signal||s.code}${x?` — ${x.trim().split(`
2
+ `).pop()}`:""}`),r){const t=r.apiError&&U(r.apiError)?B("Claude Code","claude"):r.apiError?`Claude Code reported an error: ${r.apiError}`:`Claude Code exited (${s.signal||s.code})${x?`: ${x.trim().split(`
3
+ `).pop().slice(0,200)}`:""}`;r.finish({status:"died",error:t})}for(const t of b)try{t(s)}catch{}},onMessage:s=>{if(!r||(r.touch(),s.type==="control_response"))return;if(s.type==="control_request"){const a=r;a.asking++,a.touch(),ie(s,T,_=>{try{h.send(_)}catch{}}).catch(()=>{}).finally(()=>{a.asking--,r===a&&a.touch()});return}const t=ne(s,r.emit,r.streamedAny,e,r.flow);t.sessionId&&(l=t.sessionId),t.streamed&&(r.streamedAny=!0),t.result!=null&&(r.resultText=t.result),t.apiError&&(r.apiError=t.apiError),s.type==="result"&&(r.apiError&&U(r.apiError)?r.finish({status:"failed",error:B("Claude Code","claude")}):r.apiError?r.finish({status:"failed",error:`Claude Code reported an error: ${r.apiError}`}):r.finish({status:"completed",error:null}))}});return{get pid(){return h.pid},get alive(){return!h.exited},expiresAt:f.expiresAt||0,get sessionId(){return l},onExit(s){b.add(s)},close(){h.close()},async turn({prompt:s,emit:t,signal:a,harness:_=null}){if(h.exited)throw new Error("Claude Code process is gone");if(r)throw new Error("a turn is already running on this process");let v=null,k;const R=new Promise(L=>{k=L}),n={emit:t,flow:{sawText:!1,tail:"",boundary:!1,costUsdBefore:M,harnessChars:_},streamedAny:!1,resultText:"",apiError:null,asking:0,touch(){clearTimeout(v),!n.asking&&(v=setTimeout(()=>n.finish({status:"timeout",error:`Claude Code timed out — no output for ${Math.round(F/1e3)}s.`}),F))},finish(L){r===n&&(clearTimeout(v),r=null,k(L))}};r=n,n.touch();const P=()=>{if(r===n){n.interrupted=!0;try{h.send({type:"control_request",request_id:`stop_${++I}`,request:{subtype:"interrupt"}})}catch{}setTimeout(()=>{r===n&&(n.finish({status:"killed",error:null}),h.kill())},ue).unref?.()}};if(a?.aborted)return n.finish({status:"killed",error:null}),{streamedAny:!1,resultText:"",status:"killed"};a?.addEventListener("abort",P,{once:!0});try{h.send({type:"user",message:{role:"user",content:s}})}catch(L){n.finish({status:"failed",error:L.message})}const C=await R;n.flow.costUsdTotal!=null&&(M=n.flow.costUsdTotal),a?.removeEventListener("abort",P),C.status==="timeout"&&h.kill();const J=C.status==="killed"?"killed":n.interrupted?"interrupted":C.status;return{streamedAny:n.streamedAny,resultText:n.resultText,status:J,error:C.error,sessionId:l}}}}const N=new Set;async function de({key:o,spec:A,options:e,label:$,launch:w=j,log:g=()=>{},force:T=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!T||!o||!A||e?.ephemeral===!0||N.has(o)||u.peek({key:o,messages:[{role:"user",content:""}]}))return!1;N.add(o);const y=u.reserve({key:o,label:`${$} (spare)`,evict:!1});if(!y)return N.delete(o),!1;let c=null,p=null;try{let d=e.mcp;const E=e.mcp?.specs||[];(d?.url&&E.length||e.approvals===!0)&&(c=O(()=>{},E),d?.url&&E.length&&(d={...d,url:`${d.url.replace(/\/[^/]*$/,"")}/${c.id}`})),p=await H({system:"",options:{...e,mcp:d},tag:`spare-${Date.now()}-${Math.random().toString(36).slice(2)}`});const f=[...p.args];q(f,e.extraArgs,G.claude,()=>{});const i=c,m=await w({spec:A,args:f,cwd:p.cwd,env:p.runEnv,ask:p.approvals&&i?r=>W(i,r):null,peers:p.peers});m.mcpSession=c,m.systemSent="",u.attach(y,m);const S=p.cleanup;return m.onExit(()=>{c&&D(c.id),S()}),u.release(y,{user:null,answered:!1}),g(`warm ${$}: spare ready`),!0}catch(d){return c&&D(c.id),p?.cleanup?.(),u.drop(y,`spare launch failed: ${d.message}`),!1}finally{N.delete(o)}}async function be({messages:o,system:A,options:e,images:$,thread:w=null},g,{signal:T,launch:y=j}={}){if(!ce(e))return{handled:!1,reason:"not eligible"};const c=se();if(!c)return{handled:!1,reason:"claude not resolvable"};const p=`${Date.now()}-${Math.random().toString(36).slice(2)}`,d=(e.mcp?.specs||[]).map(s=>s?.name).filter(Boolean),E=[];q(E,e.extraArgs,G.claude,()=>{});const f=JSON.stringify({agent:"claude",cwd:e.workingDir||"",mode:e.permissionMode||"default",model:e.model||"",local:e.useLocalConfig!==!1,reach:e.reach||"",tools:[...d].sort(),extra:E,approvals:e.approvals===!0,env:e.runEnv?Object.keys(e.runEnv).sort().map(s=>`${s}=${e.runEnv[s]}`):[],hosts:e.sandbox?.hosts?(Array.isArray(e.sandbox.hosts)?e.sandbox.hosts:String(e.sandbox.hosts).split(/[\s,;]+/)).map(s=>String(s).trim().toLowerCase()).filter(Boolean).sort():[],outside:e.sandbox?.outside===!0,...Array.isArray(e.sandbox?.signIn)&&e.sandbox.signIn.length?{signIn:[...e.sandbox.signIn].sort()}:{},ephemeral:e.ephemeral===!0,...Array.isArray(e.sandbox?.write)&&e.sandbox.write.length?{write:[...e.sandbox.write].map(String).sort()}:{}});let i=u.acquire({key:f,messages:o}),m=!1;const S=!i&&w?.plan.mode==="resume"?w.plan.sessionId:null;if(!i){if(i=u.reserve({key:f,label:`claude ${e.workingDir||"home"}`,evict:e.ephemeral!==!0}),!i)return{handled:!1,reason:"all warm slots busy"};m=!0;let s=null,t=null;try{let a=e.mcp;(a?.url&&d.length||e.approvals===!0)&&(s=O(g,a?.specs||[]),a?.url&&d.length&&(a={...a,url:`${a.url.replace(/\/[^/]*$/,"")}/${s.id}`})),t=await H({system:A,options:{...e,mcp:a},tag:p,resume:S,name:w?.thread.title||""});const _=[...t.args];q(_,e.extraArgs,G.claude,g);const v=s;let k=null;const R=t.approvals&&v?C=>k?.accessGate?k.accessGate.ask(v,C):W(v,C):null,n=await y({spec:c,args:_,cwd:t.cwd,env:t.runEnv,ask:R,peers:t.peers});k=n,n.mcpSession=s,n.systemSent=String(A||""),u.attach(i,n),S&&u.holds(i,o);const P=t.cleanup;n.onExit(()=>{s&&D(s.id),P()})}catch(a){return s&&D(s.id),t?.cleanup(),u.drop(i,`launch failed: ${a.message}`),{handled:!1,reason:a.message}}}const r=i.session;r.accessGate=e.accessGate||null,r.mcpSession&&ee(r.mcpSession,g,e.mcp?.specs);const b=o[o.length-1],x=await oe($,p),I=String(A||""),M=ae(m&&!S?o:S?w.plan.tail?.length?w.plan.tail:[b]:[b],x,!m&&I!==r.systemSent?I:"");r.systemSent=I;let l;try{l=await r.turn({prompt:M,emit:g,signal:T,harness:le({prompt:M,system:m?I:"",specs:m?e.mcp?.specs:null})})}finally{x.forEach(s=>z(s).catch(()=>{})),r.mcpSession&&re(r.mcpSession)}if(T?.aborted||l.status==="interrupted")return l.status==="interrupted"&&r.alive?u.release(i,{user:String(b?.content||""),answered:l.streamedAny}):u.drop(i,"stopped"),{handled:!0};if(l.status!=="completed"){if(u.drop(i,l.error||l.status),!l.streamedAny)return{handled:!1,reason:l.error||l.status};throw new Error(l.error||`Claude Code ${l.status}`)}if(g({type:"done",text:l.streamedAny?"":l.resultText}),e.accessGate?.restart().length)return u.drop(i,"a folder was opened to it"),r.accessGate=null,{handled:!0,completed:!0,sessionId:l.sessionId||r.sessionId||null};r.accessGate=null,u.release(i,{user:String(b?.content||""),answered:!0});const h=l.sessionId||r.sessionId||null;return setTimeout(()=>{de({key:f,spec:c,options:e,label:`claude ${e.workingDir||"home"}`,launch:y}).catch(()=>{})},250).unref?.(),{handled:!0,completed:!0,sessionId:h}}export{be as chatWarm,j as launchClaudeSession,u as pool,de as prewarmClaude,ce as warmEligible};
@@ -1,10 +1,10 @@
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({probe:"async"})||!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)}
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({probe:"async"})||!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((_,f)=>{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 f(new Error(`Failed to start claude: ${m.message}`))}const h=me(l,o);let b="",E="",p=!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"),f(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 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
- `):(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(`
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=se(S,s,p,r,le);x.streamed&&(p=!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),h(),f(new Error(`Failed to start claude (${y}): ${m.message}`))}),l.on("close",m=>{if(clearTimeout(A),h(),o?.aborted){_({streamedAny:p,resultText:I,sessionId:L,stopped:!0});return}if(C&&fe(C))return f(new Error(Y("Claude Code","claude")));if(m===0&&C)return f(new Error(`Claude Code reported an error: ${C}`));m===0?_({streamedAny:p,resultText:I,sessionId:L}):f(he("Claude Code",m,E,C||"",{agentId:"claude"}))}),a?l.stdin.write(`${JSON.stringify({type:"user",message:{role:"user",content:e}})}
4
+ `):(l.stdin.write(e),l.stdin.end())}).catch(f)})}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
- `}),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),...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+=`
7
+ `}),e.boundary=!1)}function ne(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function se(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),...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 oe=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"];oe&&await Ue()&&a.push("--effort",oe),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 h=D.join(P.tmpdir(),`chatpanel-system-${r}.md`);await R(h,e,{mode:384}),c.push(h),a.push("--append-system-prompt-file",h)}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,f=w||_||t.runEnv?{...t.runEnv||{},...w||{},..._||{}}:null;return{args:a,cwd:n,runEnv:f,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 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};
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(p=>G(p).catch(()=>{})),u.cleanup()},f=ze(c?s.plan.tail?.length?s.plan.tail:e.slice(-1):e,w);xe(d,r.extraArgs,Ce.claude,o);const T=u.approvals&&r.permissionSession?p=>r.accessGate?r.accessGate.ask(r.permissionSession,p):Pe(r.permissionSession,p):null;let l=!1;const b=te({prompt:f,args:d,cwd:y,env:g,emit:c?p=>{(p?.type==="delta"||p?.type==="tool")&&(l=!0),o(p)}:o,signal:n,harness:ie({prompt:f,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(p){if(_(),c&&!l&&!n?.aborted)return s.forget(),H({messages:e,system:t,options:r,images:i,thread:s.restart()},o,{signal:n});throw p}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 h=>y.has(h)||d?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${h} blocked — set this agent's permission mode in ChatPanel to enable it.`};let w=!1;const _=K(e),f={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 h of l){const b=se(h,i,w,u,f);b.streamed&&(w=!0),b.result!=null&&(T=b.result)}}catch(h){if(s?.aborted||a.signal.aborted)return;throw h}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,se as handleMessage,ie as harnessChars,_t as listModels,Oe as writeImages};
@@ -1,13 +1,13 @@
1
- import Z from"node:os";import L from"node:path";import{unlink as ee}from"node:fs/promises";import{spawnRpcChild as te}from"../rpc-child.js";import{spawnGroupOpts as re}from"../proc.js";import{spawn as se}from"node:child_process";import{track as ne,sandbox as ae,nestedSandboxLine as oe,grantedWriteRoots as H}from"../sandbox.js";import{createWarmPool as ie}from"../warm-pool.js";import{createSession as W,deleteSession as M,rebindSession as le,releaseSession as de,relayPermission as ce}from"../mcp-sessions.js";import{buildCliPrompt as U}from"./prompt.js";import{codexMcpConfigArgs as B,codexDisableArgs as z,configuredMcpServers as ue,redundantChatpanelServers as fe,ensureIsolatedHome as pe,writeImages as me}from"./codex.js";import{disabledMcpServers as he}from"../mcp-quarantine.js";import{resolveWorkdir as ge}from"../workdir.js";import{registerWarmPool as ye}from"../warm.js";const F=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,X=process.env.CHATPANEL_CODEX_EFFORT??"low",xe=9e4,J=5e3,A=ye("codex",ie({log:e=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[codex] ${e}`)}}));let j=0;function Fe(){j=0}const we=e=>e&&typeof e=="object"?(Array.isArray(e.hosts)?e.hosts:String(e.hosts||"").split(/[\s,;]+/)).map(n=>String(n).trim().toLowerCase()).filter(Boolean).sort():[];function Se({agent:e="codex",cwd:n,options:t={},mcpNames:c=[],runEnv:a=null,disabled:f=[],roots:g=[]}){return JSON.stringify({agent:e,cwd:n,mode:t.permissionMode||"default",model:t.model||"",local:t.useLocalConfig!==!1,tools:[...c].sort(),env:a?Object.keys(a).sort().map(l=>`${l}=${a[l]}`):[],disabled:[...f].sort(),hosts:we(t.sandbox),outside:t.sandbox?.outside===!0,ephemeral:t.ephemeral===!0,roots:[...g].sort()})}function be(e={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CODEX_APPSERVER==="off"||e.warm===!1||e.extraArgs&&String(e.extraArgs).trim()||Date.now()<j)}function G(e){return e==="bypassPermissions"?"danger-full-access":e==="acceptEdits"?"workspace-write":"read-only"}function V(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e?.content))return e.content.map(n=>typeof n=="string"?n:n?.text||"").filter(Boolean).join(`
1
+ import Z from"node:os";import L from"node:path";import{unlink as ee}from"node:fs/promises";import{spawnRpcChild as te}from"../rpc-child.js";import{spawnGroupOpts as re}from"../proc.js";import{spawn as se}from"node:child_process";import{track as ne,sandbox as ae,nestedSandboxLine as oe,grantedWriteRoots as H}from"../sandbox.js";import{createWarmPool as ie}from"../warm-pool.js";import{createSession as W,deleteSession as M,rebindSession as le,releaseSession as de,relayPermission as ce}from"../mcp-sessions.js";import{buildCliPrompt as U}from"./prompt.js";import{codexMcpConfigArgs as B,codexDisableArgs as z,configuredMcpServers as ue,redundantChatpanelServers as fe,ensureIsolatedHome as pe,writeImages as me}from"./codex.js";import{disabledMcpServers as he}from"../mcp-quarantine.js";import{resolveWorkdir as ge}from"../workdir.js";import{registerWarmPool as ye}from"../warm.js";const F=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,X=process.env.CHATPANEL_CODEX_EFFORT??"low",xe=9e4,J=5e3,A=ye("codex",ie({log:e=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[codex] ${e}`)}}));let j=0;function Fe(){j=0}const we=e=>e&&typeof e=="object"?(Array.isArray(e.hosts)?e.hosts:String(e.hosts||"").split(/[\s,;]+/)).map(n=>String(n).trim().toLowerCase()).filter(Boolean).sort():[];function be({agent:e="codex",cwd:n,options:t={},mcpNames:c=[],runEnv:a=null,disabled:f=[],roots:g=[]}){return JSON.stringify({agent:e,cwd:n,mode:t.permissionMode||"default",model:t.model||"",local:t.useLocalConfig!==!1,tools:[...c].sort(),env:a?Object.keys(a).sort().map(l=>`${l}=${a[l]}`):[],disabled:[...f].sort(),hosts:we(t.sandbox),...Array.isArray(t.sandbox?.signIn)&&t.sandbox.signIn.length?{signIn:[...t.sandbox.signIn].sort()}:{},outside:t.sandbox?.outside===!0,ephemeral:t.ephemeral===!0,roots:[...g].sort()})}function Se(e={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CODEX_APPSERVER==="off"||e.warm===!1||e.extraArgs&&String(e.extraArgs).trim()||Date.now()<j)}function G(e){return e==="bypassPermissions"?"danger-full-access":e==="acceptEdits"?"workspace-write":"read-only"}function V(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e?.content))return e.content.map(n=>typeof n=="string"?n:n?.text||"").filter(Boolean).join(`
2
2
  `);try{return JSON.stringify(e)}catch{return String(e)}}function Ae(e,n,t,c){const a=e?.type||"",f=e?.id||`i_${c.n++}`,g=(l,d)=>{c.started.has(f)||(c.started.add(f),t({type:"tool",name:l,phase:"start",callId:f,input:d}))};if(a==="agentMessage"){n&&e.text&&!c.deltaItems.has(f)&&!c.said.has(f)&&(c.said.add(f),t({type:"delta",text:`${c.saidAny?`
3
3
 
4
4
  `:""}${e.text}`}),c.saidAny=!0);return}if(a==="commandExecution"){if(g("shell",{command:e.command||""}),n){const l=e.exitCode===0||e.exitCode==null;t({type:"tool",name:"shell",phase:"done",callId:f,status:l?"ok":`exit ${e.exitCode}`,result:String(e.aggregatedOutput||"").slice(0,4e3)})}return}if(a==="fileChange"){const l=Array.isArray(e.changes)?e.changes.map(d=>d?.path||d?.file).filter(Boolean):[];g("edit",{files:l}),n&&t({type:"tool",name:"edit",phase:"done",callId:f,status:e.status==="failed"?"error":"ok"});return}if(a==="webSearch"){const l=e.action&&typeof e.action=="object"?e.action:{},d=e.query||l.query||"",m=l.url||"";g("web_search",{query:d,...m?{url:m}:{}}),n&&t({type:"tool",name:"web_search",phase:"done",callId:f,status:"ok",result:m?`Opened ${m}`:d?`Searched the web for ${d}`:"Searched the web"});return}if(a==="mcpToolCall"){const l=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(g(l,e.arguments&&typeof e.arguments=="object"?e.arguments:{}),n){const d=e.status==="failed"||e.error!=null,m=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error;t({type:"tool",name:l,phase:"done",callId:f,status:d?`error: ${String(m||"failed").slice(0,80)}`:"ok",result:String(d?m||"":V(e.result)).slice(0,4e3)});const r=!c.saidNested&&oe(`${m||""}
5
5
  ${V(e.result)}`,"Codex");r&&(c.saidNested=!0,t({type:"status",text:r}))}return}if(a==="plan"&&n&&e.text&&c.lastPlan!==e.text){c.lastPlan=e.text,t({type:"status",text:`Plan:
6
6
  ${e.text}`});return}if(a==="reasoning"&&n){if(c.deltaItems.has(f))return;const l=(Array.isArray(e.summary)?e.summary:[]).map(d=>typeof d=="string"?d:d?.text||"").filter(Boolean).join(`
7
7
  `);l&&!c.reasoned.has(f)&&(c.reasoned.add(f),t({type:"reasoning",text:`${l}
8
- `}))}}const ve="mcpServer/elicitation/request",Ce={"item/commandExecution/requestApproval":{kind:"command",legacy:!1},execCommandApproval:{kind:"command",legacy:!0},"item/fileChange/requestApproval":{kind:"files",legacy:!1},applyPatchApproval:{kind:"files",legacy:!0}};function ke(e,n={}){const t=n&&typeof n=="object"?n:{};if(e==="command"){const a=w(Array.isArray(t.command)?t.command.join(" "):t.command);return{tool:"Bash",displayName:"Codex",input:{command:a},description:w(t.reason),path:null,rules:a?[{tool:"Bash",content:a}]:[],toolUseId:w(t.itemId||t.callId)||null}}const c=w(t.grantRoot);return{tool:"Edit",displayName:"Codex",input:c?{file_path:c}:{},description:w(t.reason)||"change files outside its working folder",path:c||null,rules:c?[{tool:"Edit",content:c}]:[],toolUseId:w(t.itemId)||null}}function Ie(e,n=!1){const t=e?.behavior==="allow";return n?{decision:t?"approved":"denied"}:{decision:t?e.scope==="chat"?"acceptForSession":"accept":"decline"}}const w=e=>String(e??"").replace(/\s+/g," ").trim().slice(0,200);function Ee(e={}){const n=e&&typeof e=="object"?e:{},t=n._meta&&typeof n._meta=="object"?n._meta:{},c=n.requestedSchema?.properties,a=!c||typeof c=="object"&&!Object.keys(c).length;if(n.mode==="url"||!a||!w(n.message))return null;const f=w(t.tool_name)||`${w(n.serverName)||"plugin"}_elicitation`,g=t.tool_params&&typeof t.tool_params=="object"&&!Array.isArray(t.tool_params)?t.tool_params:{};let l=w(t.origin||g.origin);if(!l)try{l=JSON.stringify(g)}catch{l=""}return{tool:f,displayName:w(t.connector_name||t.tool_title)||f,input:g,description:w(n.message),path:null,rules:[{tool:f,content:l&&l!=="{}"?l:w(n.message)}],toolUseId:w(t.callId)||null}}function _e(e){return e?.behavior==="allow"?{action:"accept",content:{}}:{action:"decline"}}function $e(){return{n:0,started:new Set,said:new Set,reasoned:new Set,deltaItems:new Set,saidAny:!1,lastPlan:null}}async function K({bin:e="codex",cwd:n,env:t,configArgs:c=[],options:a={},spawnImpl:f,log:g=()=>{},resume:l=null}){const d=a.permissionMode||"default",m=d==="bypassPermissions";let r=null,_=!1;const P=new Set;let k="";const N=d!=="acceptEdits"&&d!=="bypassPermissions",I=await ae().wrap(e,["app-server",...c],{cwd:n||void 0,env:t,...re},{engine:"codex",cwd:n,readOnly:N}),S=I.record.layer==="none"?G(d):"danger-full-access";I.record.layer==="none"&&g(`sandbox: codex app-server runs outside a sandbox — ${I.record.reason}`);const y=te(I.bin,I.argv,{cwd:n,env:t,spawnImpl:(i,s,u)=>ne((f||se)(i,s,u),I,{kind:"warm"}),spawnOpts:I.opts,onStderr:i=>{k=(k+i).slice(-2e3)},onExit:i=>{g(`app-server exited: ${i.signal||i.code}${k?` — ${k.trim().split(`
9
- `).pop()}`:""}`),r&&r.finish({status:"died",error:i.error?.message||`Codex exited (${i.signal||i.code})`});for(const s of P)try{s(i)}catch{}},onRequest:async(i,s)=>{const u=Ce[i];if(u){if(m)return u.legacy?{decision:"approved"}:{decision:"accept"};const o=r,C=ke(u.kind,s);if(o?.ask){o.hold();try{return Ie(await o.ask(C),u.legacy)}finally{r===o&&o.touch()}}return o?.emit({type:"status",text:u.kind==="command"?"Codex asked to run a command outside its sandbox — declined (ChatPanel could not ask you here; set Permissions to full access to allow).":"Codex asked to change files outside its folders — declined (ChatPanel could not ask you here; add the folder under Settings › Runtime, or set Permissions to full access)."}),u.legacy?{decision:"denied"}:{decision:"decline"}}if(i===ve){const o=r,C=Ee(s);if(C&&o?.ask){o.hold();try{return _e(await o.ask(C))}finally{r===o&&o.touch()}}return o?.emit({type:"status",text:`Codex asked: ${w(s?.message)||`a question from ${s?.serverName||"a plugin"}`} — declined (${C?"ChatPanel could not ask you here":"ChatPanel cannot answer this kind of question yet"}).`}),{action:"decline"}}r?.emit({type:"status",text:`Codex asked for ${w(i)} — declined (ChatPanel cannot answer it).`})},onMessage:i=>{if(!i.method||!r)return;const s=i.params||{};if(s.threadId&&s.threadId!==r.threadId)return;r.touch();const u=i.method;if(u==="item/agentMessage/delta"){if(!s.delta)return;r.state.deltaItems.add(s.itemId),r.state.said.has(s.itemId)||(r.state.said.add(s.itemId),r.state.saidAny&&r.emit({type:"delta",text:`
8
+ `}))}}const Ie="mcpServer/elicitation/request",ve={"item/commandExecution/requestApproval":{kind:"command",legacy:!1},execCommandApproval:{kind:"command",legacy:!0},"item/fileChange/requestApproval":{kind:"files",legacy:!1},applyPatchApproval:{kind:"files",legacy:!0}};function Ce(e,n={}){const t=n&&typeof n=="object"?n:{};if(e==="command"){const a=w(Array.isArray(t.command)?t.command.join(" "):t.command);return{tool:"Bash",displayName:"Codex",input:{command:a},description:w(t.reason),path:null,rules:a?[{tool:"Bash",content:a}]:[],toolUseId:w(t.itemId||t.callId)||null}}const c=w(t.grantRoot);return{tool:"Edit",displayName:"Codex",input:c?{file_path:c}:{},description:w(t.reason)||"change files outside its working folder",path:c||null,rules:c?[{tool:"Edit",content:c}]:[],toolUseId:w(t.itemId)||null}}function ke(e,n=!1){const t=e?.behavior==="allow";return n?{decision:t?"approved":"denied"}:{decision:t?e.scope==="chat"?"acceptForSession":"accept":"decline"}}const w=e=>String(e??"").replace(/\s+/g," ").trim().slice(0,200);function Ee(e={}){const n=e&&typeof e=="object"?e:{},t=n._meta&&typeof n._meta=="object"?n._meta:{},c=n.requestedSchema?.properties,a=!c||typeof c=="object"&&!Object.keys(c).length;if(n.mode==="url"||!a||!w(n.message))return null;const f=w(t.tool_name)||`${w(n.serverName)||"plugin"}_elicitation`,g=t.tool_params&&typeof t.tool_params=="object"&&!Array.isArray(t.tool_params)?t.tool_params:{};let l=w(t.origin||g.origin);if(!l)try{l=JSON.stringify(g)}catch{l=""}return{tool:f,displayName:w(t.connector_name||t.tool_title)||f,input:g,description:w(n.message),path:null,rules:[{tool:f,content:l&&l!=="{}"?l:w(n.message)}],toolUseId:w(t.callId)||null}}function _e(e){return e?.behavior==="allow"?{action:"accept",content:{}}:{action:"decline"}}function $e(){return{n:0,started:new Set,said:new Set,reasoned:new Set,deltaItems:new Set,saidAny:!1,lastPlan:null}}async function K({bin:e="codex",cwd:n,env:t,configArgs:c=[],options:a={},spawnImpl:f,log:g=()=>{},resume:l=null}){const d=a.permissionMode||"default",m=d==="bypassPermissions";let r=null,_=!1;const P=new Set;let C="";const N=d!=="acceptEdits"&&d!=="bypassPermissions",k=await ae().wrap(e,["app-server",...c],{cwd:n||void 0,env:t,...re},{engine:"codex",cwd:n,readOnly:N}),b=k.record.layer==="none"?G(d):"danger-full-access";k.record.layer==="none"&&g(`sandbox: codex app-server runs outside a sandbox — ${k.record.reason}`);const y=te(k.bin,k.argv,{cwd:n,env:t,spawnImpl:(i,s,u)=>ne((f||se)(i,s,u),k,{kind:"warm"}),spawnOpts:k.opts,onStderr:i=>{C=(C+i).slice(-2e3)},onExit:i=>{g(`app-server exited: ${i.signal||i.code}${C?` — ${C.trim().split(`
9
+ `).pop()}`:""}`),r&&r.finish({status:"died",error:i.error?.message||`Codex exited (${i.signal||i.code})`});for(const s of P)try{s(i)}catch{}},onRequest:async(i,s)=>{const u=ve[i];if(u){if(m)return u.legacy?{decision:"approved"}:{decision:"accept"};const o=r,v=Ce(u.kind,s);if(o?.ask){o.hold();try{return ke(await o.ask(v),u.legacy)}finally{r===o&&o.touch()}}return o?.emit({type:"status",text:u.kind==="command"?"Codex asked to run a command outside its sandbox — declined (ChatPanel could not ask you here; set Permissions to full access to allow).":"Codex asked to change files outside its folders — declined (ChatPanel could not ask you here; add the folder under Settings › Runtime, or set Permissions to full access)."}),u.legacy?{decision:"denied"}:{decision:"decline"}}if(i===Ie){const o=r,v=Ee(s);if(v&&o?.ask){o.hold();try{return _e(await o.ask(v))}finally{r===o&&o.touch()}}return o?.emit({type:"status",text:`Codex asked: ${w(s?.message)||`a question from ${s?.serverName||"a plugin"}`} — declined (${v?"ChatPanel could not ask you here":"ChatPanel cannot answer this kind of question yet"}).`}),{action:"decline"}}r?.emit({type:"status",text:`Codex asked for ${w(i)} — declined (ChatPanel cannot answer it).`})},onMessage:i=>{if(!i.method||!r)return;const s=i.params||{};if(s.threadId&&s.threadId!==r.threadId)return;r.touch();const u=i.method;if(u==="item/agentMessage/delta"){if(!s.delta)return;r.state.deltaItems.add(s.itemId),r.state.said.has(s.itemId)||(r.state.said.add(s.itemId),r.state.saidAny&&r.emit({type:"delta",text:`
10
10
 
11
11
  `})),r.state.saidAny=!0,r.streamed=!0,r.emit({type:"delta",text:s.delta})}else if(u==="item/reasoning/summaryTextDelta"||u==="item/reasoning/textDelta"){if(!s.delta)return;r.state.deltaItems.add(s.itemId),r.streamed=!0,r.emit({type:"reasoning",text:s.delta})}else if(u==="item/reasoning/summaryPartAdded")r.state.deltaItems.has(s.itemId)&&r.emit({type:"reasoning",text:`
12
- `});else if(u==="item/started"||u==="item/completed"){const o=r.state.started.size+r.state.said.size;Ae(s.item,u==="item/completed",r.emit,r.state),r.state.started.size+r.state.said.size>o&&(r.streamed=!0)}else if(u==="thread/tokenUsage/updated"){const o=s.tokenUsage?.last||s.tokenUsage?.total;o&&(r.usage={type:"usage",provider:"bridge",inputTokens:o.inputTokens||0,outputTokens:o.outputTokens||0,cacheReadTokens:o.cachedInputTokens||0,cacheWriteTokens:o.cacheWriteInputTokens||0,costUsd:null})}else if(u==="error"){const o=s.error?.message||"error";s.willRetry?r.emit({type:"status",text:`Codex: ${o.slice(0,200)} — retrying`}):r.lastError=o}else if(u==="turn/completed"){const o=s.turn||{};if(r.turnId&&o.id&&o.id!==r.turnId)return;r.finish({status:o.status||"completed",error:o.error?.message||r.lastError||null})}}});let b,$=!1;try{await y.request("initialize",{clientInfo:{name:"chatpanel-bridge",version:"1"},capabilities:{experimentalApi:!0}},{timeoutMs:2e4}),y.notify("initialized");const i=H(n),s=C=>y.request(l?"thread/resume":"thread/start",{...l?{threadId:l,excludeTurns:!0}:a.ephemeral===!0?{ephemeral:!0}:{},cwd:n||void 0,sandbox:C,approvalPolicy:"never",...a.model?{model:a.model}:{},...i.length?{config:{sandbox_workspace_write:{writable_roots:i}}}:{}},{timeoutMs:xe});let u=await s(S);const o=String(u?.sandbox?.type||"");if(S==="danger-full-access"&&o&&o!=="dangerFullAccess"&&(u=await s(G(d)),$=!0),b=u?.thread?.id,!b)throw new Error("Codex app-server started no thread")}catch(i){y.kill();const s=k.trim().split(`
13
- `).filter(Boolean).pop()||"";throw new Error(s?`${i.message}: ${s.slice(-300)}`:i.message)}let v="";return{threadId:b,async setName(i){const s=String(i||"").trim();if(!(!s||s===v||y.exited)){v=s;try{await y.request("thread/name/set",{threadId:b,name:s},{timeoutMs:5e3})}catch{}}},get pid(){return y.pid},get alive(){return!y.exited},onExit(i){P.add(i)},close(){y.close()},async turn({prompt:i,imageFiles:s=[],emit:u,signal:o,ask:C=null}){if(y.exited)throw new Error("Codex process is gone");if(r)throw new Error("a turn is already running on this thread");const x=$e();let p=null,E;const O=new Promise(T=>{E=T}),h={threadId:b,turnId:null,emit:u,state:x,streamed:!1,usage:null,lastError:null,ask:C,hold(){clearTimeout(p)},touch(){clearTimeout(p),p=setTimeout(()=>h.finish({status:"timeout",error:`Codex timed out — no output for ${Math.round(F/1e3)}s.`}),F)},finish(T){r===h&&(clearTimeout(p),r=null,E(T))}};r=h,h.touch();const D=async()=>{if(r===h){try{await y.request("turn/interrupt",{threadId:b,turnId:h.turnId},{timeoutMs:J})}catch{}setTimeout(()=>{r===h&&(h.finish({status:"killed",error:null}),y.kill())},J).unref?.()}};if(o?.aborted)return h.finish({status:"killed",error:null}),{streamed:!1,said:!1,status:"killed",usage:null};o?.addEventListener("abort",D,{once:!0}),$&&!_&&(_=!0,u({type:"status",text:"Your organisation’s Codex policy does not let ChatPanel’s sandbox replace Codex’s own, and Codex’s cannot start inside ChatPanel’s — so Codex will ask you before each command. “Allow for this chat” stops it asking again for the same command."})),u({type:"status",text:"Codex working"});try{const T=[{type:"text",text:i},...s.map(Q=>({type:"localImage",path:Q}))],Y=await y.request("turn/start",{threadId:b,input:T,summary:"auto",...X?{effort:X}:{}},{timeoutMs:3e4});h.turnId=Y?.turn?.id||null}catch(T){h.finish({status:"failed",error:T.message})}const q=await O;return o?.removeEventListener("abort",D),q.status==="timeout"&&y.kill(),h.usage&&u(h.usage),{streamed:h.streamed,said:x.saidAny,status:q.status,error:q.error,usage:h.usage}}}}const R=new Set;async function Pe({key:e,cwd:n,env:t,configArgs:c,options:a,label:f,launch:g=K,force:l=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!l||!e||R.has(e)||A.peek({key:e,messages:[{role:"user",content:""}]}))return!1;R.add(e);const d=A.reserve({key:e,label:`${f} (spare)`,evict:!1});if(!d)return R.delete(e),!1;let m=null;try{const r=[...c];if(a.mcp?.url&&(a.mcp?.specs||[]).length){m=W(()=>{},a.mcp.specs);const k=a.mcp.url.replace(/\/[^/]*$/,"");r.unshift(...B({url:`${k}/${m.id}`,serverName:a.mcp?.serverName||"chatpanel_browser",specs:a.mcp.specs}))}const _=await g({cwd:n,env:t,configArgs:r,options:a});_.mcpSession=m,_.systemSent="",A.attach(d,_);const P=m;return _.onExit(()=>{P&&M(P.id)}),A.release(d,{user:null,answered:!1}),!0}catch(r){return m&&M(m.id),A.drop(d,`spare launch failed: ${r.message}`),!1}finally{R.delete(e)}}async function Xe({messages:e,system:n,options:t,images:c,thread:a=null},f,{signal:g,launch:l=K}={}){if(!be(t))return{handled:!1,reason:"not eligible"};const d=ge(t.workingDir),m={...process.env,...t.runEnv||{}};if(t.useLocalConfig===!1){const p=pe();p&&(m.CODEX_HOME=p)}const r=t.mcp?.serverName||"chatpanel_browser",_=m.CODEX_HOME||L.join(Z.homedir(),".codex"),P=ue(_),k=(t.mcp?.specs||[]).map(p=>p?.name).filter(Boolean),N=[...new Set([...he("codex",t,[r]),...k.length?fe(_):[]])].filter(p=>P.has(p)),I=Se({cwd:d,options:t,mcpNames:k,runEnv:t.runEnv||null,disabled:N,roots:H(d)});let S=A.acquire({key:I,messages:e}),y=!1,b=null,$=!S&&a?.plan.mode==="resume"?a.plan.sessionId:null;if(!S){if(S=A.reserve({key:I,label:`codex ${L.basename(d||"")}`}),!S)return{handled:!1,reason:"all warm slots busy"};y=!0;try{const p=[];if(t.mcp?.url&&k.length){b=W(f,t.mcp.specs);const h=t.mcp.url.replace(/\/[^/]*$/,"");p.push(...B({url:`${h}/${b.id}`,serverName:r,specs:t.mcp.specs}))}p.push(...z(N));let E;try{E=await l({cwd:d,env:m,configArgs:p,options:t,resume:$})}catch(h){if(!$)throw h;a.forget(),a=a.restart(),$=null,E=await l({cwd:d,env:m,configArgs:p,options:t})}E.mcpSession=b,E.systemSent="",A.attach(S,E),$&&A.holds(S,e);const O=b;E.onExit(()=>{O&&M(O.id)})}catch(p){return b&&M(b.id),A.drop(S,`launch failed: ${p.message}`),/unknown|unrecognized|unexpected argument|app-server/i.test(p.message)&&(j=Date.now()+10*6e4),{handled:!1,reason:p.message}}}const v=S.session;v.mcpSession&&le(v.mcpSession,f,t.mcp?.specs);const i=e[e.length-1],s=String(n||""),u=y&&!$?U(e,s):U($?a.plan.tail||[i]:[i],s&&($||s!==v.systemSent)?s:""),o=`${Date.now()}-${Math.random().toString(36).slice(2)}`,C=await me(c,o);let x;try{const p=t.approvals===!0&&t.permissionSession?E=>ce(t.permissionSession,null,{request:E}):null;x=await v.turn({prompt:u,imageFiles:C,emit:f,signal:g,ask:p})}finally{C.forEach(p=>ee(p).catch(()=>{})),v.mcpSession&&de(v.mcpSession)}if(v.systemSent=s,g?.aborted||x.status==="interrupted")return x.status==="interrupted"&&v.alive?A.release(S,{user:String(i?.content||""),answered:x.streamed}):A.drop(S,"stopped"),{handled:!0};if(x.status!=="completed"){if(A.drop(S,x.error||x.status),!x.streamed)return{handled:!1,reason:x.error||x.status};throw new Error(x.error||`Codex ${x.status}`)}return x.said||f({type:"delta",text:"(no output)"}),f({type:"done",text:""}),a?.thread.title&&v.setName?.(a.thread.title).catch(()=>{}),A.release(S,{user:String(i?.content||""),answered:!0}),setTimeout(()=>{Pe({key:I,cwd:d,env:m,configArgs:z(N),options:t,label:`codex ${L.basename(d||"")}`,launch:l}).catch(()=>{})},250).unref?.(),{handled:!0,completed:!0,sessionId:v.threadId||null,thread:a}}export{Xe as chatWarm,ke as codexApprovalRequest,Ie as codexApprovalResponse,Ee as codexElicitationRequest,_e as codexElicitationResponse,Ae as forwardV2Item,K as launchCodexSession,$e as newTurnState,A as pool,Pe as prewarmCodex,Fe as resetSupport,be as warmEligible,Se as warmKey};
12
+ `});else if(u==="item/started"||u==="item/completed"){const o=r.state.started.size+r.state.said.size;Ae(s.item,u==="item/completed",r.emit,r.state),r.state.started.size+r.state.said.size>o&&(r.streamed=!0)}else if(u==="thread/tokenUsage/updated"){const o=s.tokenUsage?.last||s.tokenUsage?.total;o&&(r.usage={type:"usage",provider:"bridge",inputTokens:o.inputTokens||0,outputTokens:o.outputTokens||0,cacheReadTokens:o.cachedInputTokens||0,cacheWriteTokens:o.cacheWriteInputTokens||0,costUsd:null})}else if(u==="error"){const o=s.error?.message||"error";s.willRetry?r.emit({type:"status",text:`Codex: ${o.slice(0,200)} — retrying`}):r.lastError=o}else if(u==="turn/completed"){const o=s.turn||{};if(r.turnId&&o.id&&o.id!==r.turnId)return;r.finish({status:o.status||"completed",error:o.error?.message||r.lastError||null})}}});let S,$=!1;try{await y.request("initialize",{clientInfo:{name:"chatpanel-bridge",version:"1"},capabilities:{experimentalApi:!0}},{timeoutMs:2e4}),y.notify("initialized");const i=H(n),s=v=>y.request(l?"thread/resume":"thread/start",{...l?{threadId:l,excludeTurns:!0}:a.ephemeral===!0?{ephemeral:!0}:{},cwd:n||void 0,sandbox:v,approvalPolicy:"never",...a.model?{model:a.model}:{},...i.length?{config:{sandbox_workspace_write:{writable_roots:i}}}:{}},{timeoutMs:xe});let u=await s(b);const o=String(u?.sandbox?.type||"");if(b==="danger-full-access"&&o&&o!=="dangerFullAccess"&&(u=await s(G(d)),$=!0),S=u?.thread?.id,!S)throw new Error("Codex app-server started no thread")}catch(i){y.kill();const s=C.trim().split(`
13
+ `).filter(Boolean).pop()||"";throw new Error(s?`${i.message}: ${s.slice(-300)}`:i.message)}let I="";return{threadId:S,async setName(i){const s=String(i||"").trim();if(!(!s||s===I||y.exited)){I=s;try{await y.request("thread/name/set",{threadId:S,name:s},{timeoutMs:5e3})}catch{}}},get pid(){return y.pid},get alive(){return!y.exited},onExit(i){P.add(i)},close(){y.close()},async turn({prompt:i,imageFiles:s=[],emit:u,signal:o,ask:v=null}){if(y.exited)throw new Error("Codex process is gone");if(r)throw new Error("a turn is already running on this thread");const x=$e();let p=null,E;const O=new Promise(T=>{E=T}),h={threadId:S,turnId:null,emit:u,state:x,streamed:!1,usage:null,lastError:null,ask:v,hold(){clearTimeout(p)},touch(){clearTimeout(p),p=setTimeout(()=>h.finish({status:"timeout",error:`Codex timed out — no output for ${Math.round(F/1e3)}s.`}),F)},finish(T){r===h&&(clearTimeout(p),r=null,E(T))}};r=h,h.touch();const D=async()=>{if(r===h){try{await y.request("turn/interrupt",{threadId:S,turnId:h.turnId},{timeoutMs:J})}catch{}setTimeout(()=>{r===h&&(h.finish({status:"killed",error:null}),y.kill())},J).unref?.()}};if(o?.aborted)return h.finish({status:"killed",error:null}),{streamed:!1,said:!1,status:"killed",usage:null};o?.addEventListener("abort",D,{once:!0}),$&&!_&&(_=!0,u({type:"status",text:"Your organisation’s Codex policy does not let ChatPanel’s sandbox replace Codex’s own, and Codex’s cannot start inside ChatPanel’s — so Codex will ask you before each command. “Allow for this chat” stops it asking again for the same command."})),u({type:"status",text:"Codex working"});try{const T=[{type:"text",text:i},...s.map(Q=>({type:"localImage",path:Q}))],Y=await y.request("turn/start",{threadId:S,input:T,summary:"auto",...X?{effort:X}:{}},{timeoutMs:3e4});h.turnId=Y?.turn?.id||null}catch(T){h.finish({status:"failed",error:T.message})}const q=await O;return o?.removeEventListener("abort",D),q.status==="timeout"&&y.kill(),h.usage&&u(h.usage),{streamed:h.streamed,said:x.saidAny,status:q.status,error:q.error,usage:h.usage}}}}const R=new Set;async function Pe({key:e,cwd:n,env:t,configArgs:c,options:a,label:f,launch:g=K,force:l=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!l||!e||R.has(e)||A.peek({key:e,messages:[{role:"user",content:""}]}))return!1;R.add(e);const d=A.reserve({key:e,label:`${f} (spare)`,evict:!1});if(!d)return R.delete(e),!1;let m=null;try{const r=[...c];if(a.mcp?.url&&(a.mcp?.specs||[]).length){m=W(()=>{},a.mcp.specs);const C=a.mcp.url.replace(/\/[^/]*$/,"");r.unshift(...B({url:`${C}/${m.id}`,serverName:a.mcp?.serverName||"chatpanel_browser",specs:a.mcp.specs}))}const _=await g({cwd:n,env:t,configArgs:r,options:a});_.mcpSession=m,_.systemSent="",A.attach(d,_);const P=m;return _.onExit(()=>{P&&M(P.id)}),A.release(d,{user:null,answered:!1}),!0}catch(r){return m&&M(m.id),A.drop(d,`spare launch failed: ${r.message}`),!1}finally{R.delete(e)}}async function Xe({messages:e,system:n,options:t,images:c,thread:a=null},f,{signal:g,launch:l=K}={}){if(!Se(t))return{handled:!1,reason:"not eligible"};const d=ge(t.workingDir),m={...process.env,...t.runEnv||{}};if(t.useLocalConfig===!1){const p=pe();p&&(m.CODEX_HOME=p)}const r=t.mcp?.serverName||"chatpanel_browser",_=m.CODEX_HOME||L.join(Z.homedir(),".codex"),P=ue(_),C=(t.mcp?.specs||[]).map(p=>p?.name).filter(Boolean),N=[...new Set([...he("codex",t,[r]),...C.length?fe(_):[]])].filter(p=>P.has(p)),k=be({cwd:d,options:t,mcpNames:C,runEnv:t.runEnv||null,disabled:N,roots:H(d)});let b=A.acquire({key:k,messages:e}),y=!1,S=null,$=!b&&a?.plan.mode==="resume"?a.plan.sessionId:null;if(!b){if(b=A.reserve({key:k,label:`codex ${L.basename(d||"")}`}),!b)return{handled:!1,reason:"all warm slots busy"};y=!0;try{const p=[];if(t.mcp?.url&&C.length){S=W(f,t.mcp.specs);const h=t.mcp.url.replace(/\/[^/]*$/,"");p.push(...B({url:`${h}/${S.id}`,serverName:r,specs:t.mcp.specs}))}p.push(...z(N));let E;try{E=await l({cwd:d,env:m,configArgs:p,options:t,resume:$})}catch(h){if(!$)throw h;a.forget(),a=a.restart(),$=null,E=await l({cwd:d,env:m,configArgs:p,options:t})}E.mcpSession=S,E.systemSent="",A.attach(b,E),$&&A.holds(b,e);const O=S;E.onExit(()=>{O&&M(O.id)})}catch(p){return S&&M(S.id),A.drop(b,`launch failed: ${p.message}`),/unknown|unrecognized|unexpected argument|app-server/i.test(p.message)&&(j=Date.now()+10*6e4),{handled:!1,reason:p.message}}}const I=b.session;I.mcpSession&&le(I.mcpSession,f,t.mcp?.specs);const i=e[e.length-1],s=String(n||""),u=y&&!$?U(e,s):U($?a.plan.tail||[i]:[i],s&&($||s!==I.systemSent)?s:""),o=`${Date.now()}-${Math.random().toString(36).slice(2)}`,v=await me(c,o);let x;try{const p=t.approvals===!0&&t.permissionSession?E=>ce(t.permissionSession,null,{request:E}):null;x=await I.turn({prompt:u,imageFiles:v,emit:f,signal:g,ask:p})}finally{v.forEach(p=>ee(p).catch(()=>{})),I.mcpSession&&de(I.mcpSession)}if(I.systemSent=s,g?.aborted||x.status==="interrupted")return x.status==="interrupted"&&I.alive?A.release(b,{user:String(i?.content||""),answered:x.streamed}):A.drop(b,"stopped"),{handled:!0};if(x.status!=="completed"){if(A.drop(b,x.error||x.status),!x.streamed)return{handled:!1,reason:x.error||x.status};throw new Error(x.error||`Codex ${x.status}`)}return x.said||f({type:"delta",text:"(no output)"}),f({type:"done",text:""}),a?.thread.title&&I.setName?.(a.thread.title).catch(()=>{}),A.release(b,{user:String(i?.content||""),answered:!0}),setTimeout(()=>{Pe({key:k,cwd:d,env:m,configArgs:z(N),options:t,label:`codex ${L.basename(d||"")}`,launch:l}).catch(()=>{})},250).unref?.(),{handled:!0,completed:!0,sessionId:I.threadId||null,thread:a}}export{Xe as chatWarm,Ce as codexApprovalRequest,ke as codexApprovalResponse,Ee as codexElicitationRequest,_e as codexElicitationResponse,Ae as forwardV2Item,K as launchCodexSession,$e as newTurnState,A as pool,Pe as prewarmCodex,Fe as resetSupport,Se as warmEligible,be as warmKey};
package/src/env.js CHANGED
@@ -1,2 +1,2 @@
1
- import j from"node:os";import{spawnGroupOpts as U}from"./proc.js";import c from"node:path";import{spawn as X,spawnSync as w}from"node:child_process";import{readdirSync as M,readFileSync as D,existsSync as f}from"node:fs";let z=!1,Q=!1;const R=["codex","claude","agy","pi","opencode","kiro-cli","copilot","dsh"];function jn(n){return d(process.env.PATH||"",process.platform).some(o=>o&&(f(c.join(o,n))||f(c.join(o,n+".exe"))))}function hn(n){const t=I(n);if(t)return t;if(k()){const o=I(n);if(o)return o}return _n(n)||null}function Jn(n){return!!B(n,{probe:"async"})}function I(n){for(const t of dn(n))if(f(t))return t;return null}function $(){const n=c.basename(process.execPath).toLowerCase();return!(n.startsWith("node")||n.startsWith("bun"))}function Zn(n){const t=["--mcp-stdio",n];if($())return{command:process.execPath,args:t};const o=process.argv[1]||c.join(process.cwd(),"src","server.js"),e=process.env.CHATPANEL_BRIDGE_EMBEDDED==="1"?["--bridge"]:[];return{command:process.execPath,args:[o,...e,...t]}}const b="CHATPANEL_ENV",W=6e3;function T(n){for(const t of String(n||"").split(/\r?\n/)){const o=t.indexOf(" ");if(o>0&&t.slice(0,o).trim().endsWith(b))return t.slice(o+1).trim()}return""}function q(n){return/^[\w.+-]+$/.test(String(n||""))}function v(){if(process.env.SHELL)return process.env.SHELL;try{const{shell:n}=j.userInfo();if(n&&n!=="/usr/bin/false"&&n!=="/sbin/nologin")return n}catch{}return"/bin/sh"}function J(n,{interactive:t}={}){if(process.platform==="win32")return"";try{const o=t?["-l","-i","-c"]:["-l","-c"];return w(v(),[...o,n],{encoding:"utf8",timeout:W,stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}}).stdout||""}catch{return""}}function wn(n){let t="";for(const o of String(n||"").split(/\r?\n/))o.startsWith("PATH=")&&(t=o.slice(5).trim());return t}function bn({interactive:n=!0,ask:t=J}={}){const o=T(t(`command -p printf '%s\\t%s\\n' ${b} "$PATH"`,{interactive:n}));return d(o||wn(t("/usr/bin/env",{interactive:n})),process.platform)}const y=1e4,Pn=3e5;let L=0,x=y;function k({force:n=!1,now:t=Date.now(),read:o=bn,env:e=process.env}={}){if(process.platform==="win32"||!n&&(t-L<x||t<_))return!1;L=t;const i=d(e.PATH||"",process.platform),r=Y(m([...o({interactive:!0}),...i])),s=r.length>i.length;return x=s?y:Math.min(x*2,Pn),s?(e.PATH=r.join(c.delimiter),!0):!1}function nt(){L=0,x=y,h.clear(),_=0,A=H,O=!1}const h=new Map,gn=15e3;function _n(n){if(process.platform==="win32"||!q(n))return"";const t=h.get(n);if(t&&(t.bin||Date.now()-t.at<gn||Date.now()<_))return t.bin;const o=[`command -p printf '%s\\t%s\\n' ${b} "$(command -v ${n} 2>/dev/null)"`,`type -p ${n}`];let e="";for(const i of[!1,!0]){for(const r of o){const s=J(r,{interactive:i}),l=T(s)||String(s||"").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.startsWith("/")).pop()||"";if(l.startsWith("/")&&f(l)){e=l;break}}if(e)break}return h.set(n,{bin:e,at:Date.now()}),e}const H=15e3,An=3e5;let _=0,A=H,O=!1,E=null;function xn(n,{interactive:t}={}){return new Promise(o=>{let e="",i;try{i=X(v(),[...t?["-l","-i","-c"]:["-l","-c"],n],{stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}})}catch{o("");return}const r=setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},W);i.stdout.on("data",s=>{e+=s}),i.on("error",()=>{clearTimeout(r),o("")}),i.on("close",()=>{clearTimeout(r),o(e)})})}const En=new RegExp(`${b}=([\\w.+-]+)$`);function Z(n){const t=new Map;for(const o of String(n||"").split(/\r?\n/)){const e=o.indexOf(" ");if(e<=0)continue;const i=En.exec(o.slice(0,e).trim());i&&t.set(i[1],o.slice(e+1).trim())}return t}function tt({names:n=R,ask:t=xn,now:o=()=>Date.now()}={}){if(process.platform==="win32"||O)return Promise.resolve(!1);if(E)return E;if(o()<_)return Promise.resolve(!1);const e=m([...n,...h.keys()]).filter(r=>q(r)&&!I(r)&&!h.get(r)?.bin);if(!e.length)return Promise.resolve(!1);const i=[`command -p printf '%s\\t%s\\n' ${b} "$PATH"`,...e.map(r=>`command -p printf '%s\\t%s\\n' ${b}=${r} "$(command -v ${r} 2>/dev/null)"`)].join("; ");return E=(async()=>{let r=await t(i,{interactive:!0}),s=Z(r);if(s.size||(r=await t(i,{interactive:!1}),s=Z(r)),!s.size)return O=!0,!0;const l=o();let a=!1;const u=d(T(r),process.platform);u.length&&k({force:!0,now:l,read:()=>u})&&(a=!0);for(const p of e){if(!s.has(p))continue;const P=s.get(p),g=P.startsWith("/")&&f(P)?P:"";(g||I(p))&&(a=!0),h.set(p,{bin:g,at:l})}return a&&(A=H),_=l+A,a||(A=Math.min(A*2,An)),!0})().catch(()=>!0).finally(()=>{E=null}),E}function et(){_=0,A=H,O=!1,L=0,x=y,F=0;for(const[n,t]of h)t.bin||h.delete(n);for(const[n,t]of S)t.ok||S.delete(n)}function ot({probe:n="sync"}={}){return process.env.CHATPANEL_CLAUDE_PATH?B(process.env.CHATPANEL_CLAUDE_PATH,{probe:n}):B("claude",{probe:n})}function B(n,{probe:t="sync"}={}){if(!n)return null;if(n.includes("/")||n.includes("\\")||/\.[a-z0-9]+$/i.test(n)){if(!f(n))return null;const i=c.extname(n).toLowerCase();return!$()&&/^\.(c?js|mjs)$/.test(i)?{kind:"script",script:n}:process.platform==="win32"&&(i===".cmd"||i===".bat")?{kind:"cmd",bin:n}:process.platform==="win32"&&i===""&&!fn(n)?null:{kind:"native",bin:n}}if(process.platform==="win32"){const i=On(n);return i||(/^[\w.-]+$/.test(n)&&kn(n,{probe:t})?{kind:"wsl",command:n}:null)}const e=hn(n);return e?{kind:"native",bin:e}:null}const Sn="HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",Cn="HKCU\\Environment",Mn=4e3,In=3e5;let F=0,nn=0;function Tn(n,t="Path"){const o=String(t).toLowerCase();for(const e of String(n||"").split(/\r?\n/)){const i=/^\s*(\S+)\s+REG_(?:EXPAND_)?SZ\s+(.*?)\s*$/.exec(e);if(i&&i[1].toLowerCase()===o)return i[2]}return""}function tn(n,t=process.env){const o=new Map(Object.keys(t||{}).map(e=>[e.toLowerCase(),t[e]]));return String(n||"").replace(/%([^%]+)%/g,(e,i)=>{const r=o.get(String(i).toLowerCase());return r==null?e:String(r)})}function vn(n,t){try{const o=c.win32.join(process.env.SystemRoot||"C:\\Windows","System32","reg.exe"),e=w(f(o)?o:"reg",["query",n,"/v",t],{encoding:"utf8",timeout:3e3,windowsHide:!0});return e.status===0?Tn(e.stdout,t):""}catch{return""}}function yn({query:n=vn,env:t=process.env}={}){const o=tn(n(Sn,"Path"),t),e=tn(n(Cn,"Path"),t);return m([...d(o,"win32"),...d(e,"win32")])}function Ln({run:n=Hn}={}){const t=n(`[Console]::Out.Write("${b}\`t" + $env:PATH + "\`n")`);return d(T(t),"win32")}function Hn(n){for(const t of["pwsh.exe","powershell.exe"])try{const o=w(t,["-NoLogo","-NonInteractive","-ExecutionPolicy","Bypass","-Command",n],{encoding:"utf8",timeout:W,stdio:["ignore","pipe","ignore"],windowsHide:!0}),e=K(o.stdout||"");if(e)return e}catch{}return""}function en({force:n=!1,now:t=Date.now(),registry:o=yn,profile:e=Ln,env:i=process.env,home:r=j.homedir()}={}){if(process.platform!=="win32"&&!n||!n&&t-nn<Mn)return!1;nn=t;const s=d(i.PATH||"","win32"),l=m([...s,...o({env:i}),...G(r,"win32",i)]);t-F>=In&&R.some(u=>!l.some(p=>f(c.win32.join(p,`${u}.cmd`))||f(c.win32.join(p,`${u}.exe`))))&&(F=t,l.push(...e()));const a=Y(m(l),"win32");return a.length===s.length?!1:(i.PATH=a.join(V("win32")),!0)}function On(n){return on(n)||(en()?on(n):null)}function on(n){const t=C("win32");for(const o of dn(n,j.homedir(),"win32",process.env)){if(!f(o))continue;const e=t.dirname(o),i=t.extname(o).toLowerCase(),r=n==="claude"&&Dn(e)||Rn(e,n)||(/^\.(c?js|mjs)$/.test(i)?o:null);if(r){if(!$())return{kind:"script",script:r};const s=Nn(e);if(s)return{kind:"script",script:r,runtime:s}}if(i===".exe")return{kind:"native",bin:o};if(i===".cmd"||i===".bat")return{kind:"cmd",bin:o};if(i===""&&fn(o))return{kind:"native",bin:o}}return null}function Nn(n,{env:t=process.env,exists:o=f}={}){const e=c.win32,i=m([n,...d(t.PATH||"","win32"),...t.NVM_SYMLINK?[t.NVM_SYMLINK]:[],e.join(t.ProgramFiles||"C:\\Program Files","nodejs")]);for(const r of i){const s=e.join(r,"node.exe");if(o(s))return s}return null}function Dn(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 e=c.join(n,...o);if(f(e))return e}return null}function Rn(n,t){for(const o of[`${t}.cmd`,t,`${t}.ps1`]){let e;try{e=D(c.join(n,o),"utf8")}catch{continue}const i=e.match(/(?:%~?dp0%|\$basedir|\$\{basedir\})[\\/]+([^"'\s]+\.[cm]?js)/i);if(i){const r=c.join(n,i[1].replace(/[\\/]+/g,c.sep));if(f(r))return r}}return null}const S=new Map,N=new Map,$n=15e3,Wn=3e5,rn=8e3,sn=n=>["-e","bash","-lic",`command -v ${n}`];function cn(n,t){return n!==0?!1:(K(String(t||"")).replace(/\0/g,"").split(/\r?\n/).map(e=>e.trim()).filter(Boolean).pop()||"").startsWith("/")}function ln(n,t,o){const e=S.get(n),i=t?0:Math.min(e&&!e.ok&&e.ttl?e.ttl*2:$n,Wn);S.set(n,{ok:t,at:o,ttl:i})}function kn(n,{probe:t="sync",now:o=Date.now(),spawnSyncImpl:e=w,spawnImpl:i=X}={}){const r=S.get(n);if(r&&(r.ok||o-r.at<r.ttl))return r.ok;if(t==="async"){if(!N.has(n)){const l=new Promise(a=>{let u="",p;try{p=i("wsl.exe",sn(n),{windowsHide:!0,stdio:["ignore","pipe","ignore"]})}catch{a(!1);return}const P=setTimeout(()=>{try{p.kill()}catch{}},rn);p.stdout?.on("data",g=>{u+=g}),p.on("error",()=>{clearTimeout(P),a(!1)}),p.on("close",g=>{clearTimeout(P),a(cn(g,u))})}).then(a=>(ln(n,a,Date.now()),a)).finally(()=>N.delete(n));N.set(n,l)}return!1}let s=!1;try{const l=e("wsl.exe",sn(n),{encoding:"utf8",timeout:rn,windowsHide:!0});s=cn(l.status,l.stdout)}catch{s=!1}return ln(n,s,o),s}function it(n){return N.get(n)||null}function rt(n,t,o,e=null){const i=e&&typeof e=="object"&&Object.keys(e).length?{...process.env,...e}:process.env;if(n.kind==="wsl"){const s=[];if(o){const a=Bn(o);a&&s.push("--cd",a)}return["wsl.exe",[...s,"-e","bash","-lic",`exec ${n.command} "$@"`,"chatpanel",...t],{stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...U}]}const r={cwd:o||j.homedir(),stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...U};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 Bn(n){try{const t=w("wsl.exe",["-e","wslpath","-a",n],{encoding:"utf8",timeout:5e3,windowsHide:!0}),o=K(t.stdout||"").trim();return o.startsWith("/")?o:null}catch{return null}}function K(n){return n.replace(/^/,"").trim()}function Fn(n=j.homedir(),t=process.env){const o=c.join(t.NVM_DIR||c.join(n,".nvm"),"versions","node");let e;try{e=M(o).filter(r=>/^v\d+\./.test(r))}catch{return null}if(!e.length)return null;const i=(r,s)=>{const l=r.slice(1).split(".").map(Number),a=s.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=D(c.join(t.NVM_DIR||c.join(n,".nvm"),"alias","default"),"utf8").trim(),s=r.startsWith("v")?r:`v${r}`;if(e.includes(s))return c.join(o,s,"bin")}catch{}return c.join(o,e.sort(i)[0],"bin")}function Kn(n,t=process.env){return[c.join(t.MISE_DATA_DIR||c.join(n,".local","share","mise"),"shims"),c.join(n,".local","share","rtx","shims"),c.join(t.ASDF_DATA_DIR||c.join(n,".asdf"),"shims"),c.join(t.PYENV_ROOT||c.join(n,".pyenv"),"shims"),c.join(t.RBENV_ROOT||c.join(n,".rbenv"),"shims"),c.join(t.NODENV_ROOT||c.join(n,".nodenv"),"shims"),c.join(t.PROTO_HOME||c.join(n,".proto"),"shims"),c.join(t.PROTO_HOME||c.join(n,".proto"),"bin"),c.join(t.VOLTA_HOME||c.join(n,".volta"),"bin")]}function Vn(n,t=process.env){const o=[],e=(i,r)=>{try{for(const s of M(i))o.push(c.join(i,s,r))}catch{}};return e(c.join(t.NVM_DIR||c.join(n,".nvm"),"versions","node"),"bin"),e(c.join(n,".local","share","fnm","node-versions"),c.join("installation","bin")),e(c.join(n,"Library","Application Support","fnm","node-versions"),c.join("installation","bin")),e(c.join(t.MISE_DATA_DIR||c.join(n,".local","share","mise"),"installs","node"),"bin"),o}function C(n){return n==="win32"?c.win32:c}function V(n){return n==="win32"?";":c.delimiter}function d(n,t){return(n||"").split(V(t)).filter(Boolean)}function m(n){return[...new Set(n.filter(Boolean))]}const an={win32:3e4,other:65536};function Y(n,t=process.platform){const o=t==="win32"?an.win32:an.other,e=V(t),i=[];let r=0;for(const s of n){const l=s.length+(i.length?e.length:0);if(r+l>o)break;i.push(s),r+=l}return i}function G(n,t=process.platform,o=process.env){const e=C(t);if(t==="win32"){const i=o.APPDATA||e.join(n,"AppData","Roaming"),r=o.LOCALAPPDATA||e.join(n,"AppData","Local"),s=o.ProgramFiles||"C:\\Program Files",l=o["ProgramFiles(x86)"]||"C:\\Program Files (x86)",a=o.ProgramData||"C:\\ProgramData";return[e.join(n,".local","bin"),e.join(n,".codex","bin"),e.join(n,".claude","bin"),e.join(n,".claude","local"),e.join(n,".claude","local","bin"),e.join(i,"npm"),...o.NVM_SYMLINK?[o.NVM_SYMLINK]:[],e.join(s,"nodejs"),...Yn(i,r),e.join(r,"pnpm"),e.join(r,"Yarn","bin"),e.join(r,"Volta","bin"),e.join(n,".yarn","bin"),e.join(n,".bun","bin"),e.join(n,".deno","bin"),e.join(o.SCOOP||e.join(n,"scoop"),"shims"),e.join(a,"chocolatey","bin"),e.join(r,"Microsoft","WindowsApps"),e.join(r,"Microsoft","WinGet","Links"),e.join(o.MISE_DATA_DIR||e.join(r,"mise"),"shims"),e.join(o.PROTO_HOME||e.join(n,".proto"),"shims"),e.join(o.PROTO_HOME||e.join(n,".proto"),"bin"),e.join(r,"Programs","Claude Code"),e.join(r,"Anthropic","Claude Code"),e.join(s,"Claude Code"),e.join(s,"Anthropic","Claude Code"),e.join(l,"Claude Code"),e.join(l,"Anthropic","Claude Code")]}return[c.join(n,".local","bin"),c.join(n,".opencode","bin"),c.join(n,".codex","bin"),c.join(n,".claude","bin"),c.join(n,".claude","local"),c.join(n,".claude","local","bin"),o.PNPM_HOME||c.join(n,"Library","pnpm"),c.join(n,".local","share","pnpm"),c.join(n,".nix-profile","bin"),"/nix/var/nix/profiles/default/bin",c.join(n,".guix-profile","bin"),"/home/linuxbrew/.linuxbrew/bin","/snap/bin",...Kn(n,o)]}function Yn(n,t){const o=c.win32,e=[];for(const i of[o.join(t,"fnm"),o.join(n,"fnm")]){let r=[];try{r=M(o.join(i,"node-versions")).filter(s=>/^v?\d+\.\d+\.\d+/.test(s)).sort((s,l)=>l.localeCompare(s,void 0,{numeric:!0}))}catch{}for(const s of r)e.push(o.join(i,"node-versions",s,"installation"))}return e}function un(n,t=process.platform){const o=C(t),e=o.join(n,".local","share","claude","versions");let i=[];try{i=M(e).filter(r=>/^\d+\.\d+\.\d+/.test(r)).sort((r,s)=>s.localeCompare(r,void 0,{numeric:!0}))}catch{}return i.map(r=>o.join(e,r))}function pn(n,t){return t!=="win32"?[n]:/\.(cmd|exe|bat|ps1)$/i.test(n)?[n]:[`${n}.exe`,`${n}.cmd`,`${n}.bat`,n,`${n}.ps1`]}function fn(n,t=D){try{const o=t(n).subarray(0,2);return o.length===2&&o[0]===77&&o[1]===90}catch{return!1}}function Gn(n,t=j.homedir(),o=process.platform,e=process.env){const i=C(o),r=i.join(t,".local","bin",n),s=o==="win32"?e.LOCALAPPDATA||i.join(t,"AppData","Local"):null,l=o==="win32"?e.ProgramFiles||"C:\\Program Files":null,a=o==="win32"?e["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"),...o==="win32"?[i.join(s,"Microsoft","WindowsApps","claude.exe"),i.join(s,"Programs","Claude Code","claude.exe"),i.join(s,"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"),...un(t,o)]:un(t,o)],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 m((u[n]||[r]).flatMap(p=>pn(p,o)))}function dn(n,t=j.homedir(),o=process.platform,e=process.env){const i=C(o),r=m([...d(e.PATH||"",o),...G(t,o,e)]).flatMap(s=>pn(i.join(s,n),o));return m([...r,...Gn(n,t,o,e)])}const mn=["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 st(){if(Q||(Q=!0,process.platform==="win32"))return;const n=mn.filter(t=>!process.env[t]);if(n.length)try{const t=v(),o=`${n.map(i=>`[ -n "\${${i}:-}" ] && printf '%s\\t%s\\n' ${i} "$${i}"`).join("; ")}; true`,e=w(t,["-l","-i","-c",o],{encoding:"utf8",timeout:6e3,env:{...process.env,TERM:"dumb"}});for(const i of String(e.stdout||"").split(`
2
- `)){const r=i.indexOf(" ");if(r<=0)continue;const s=i.slice(0,r).trim(),l=i.slice(r+1);mn.includes(s)&&!process.env[s]&&l&&(process.env[s]=l)}}catch{}}function ct(){if(z)return;z=!0;const n=j.homedir();if(process.platform==="win32"){en({force:!0,home:n});return}const t=Fn(n),o=[...t?[t]:[],"/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",c.join(n,".local","bin"),c.join(n,"bin"),c.join(n,".npm-global","bin"),c.join(n,".cargo","bin"),c.join(n,".deno","bin"),c.join(n,".bun","bin"),...G(n),...Vn(n)];let e="";try{const s=v(),l=w(s,["-l","-c",'command -p echo "$PATH"'],{encoding:"utf8",timeout:4e3});l.status===0&&(e=(l.stdout||"").trim())}catch{}const i=new Set,r=[...t?[t]:[],...e?e.split(":"):[],...process.env.PATH?process.env.PATH.split(c.delimiter):[],...o].filter(s=>s&&!i.has(s)&&(i.add(s),!0));process.env.PATH=Y(r).join(c.delimiter),R.some(s=>!jn(s))&&k({force:!0})}export{R as AGENT_CLIS,Jn as agentAvailable,Gn as agentCandidateBins,G as agentInstallDirs,rt as buildSpawnSpec,Y as capPathList,dn as commandCandidateFiles,kn as commandInWsl,st as enrichAgentEnv,ct as enrichPath,tn as expandWindowsEnv,hn as findAgentBin,et as forgetMisses,$ as isCompiledBinary,fn as isWindowsExecutable,Nn as nodeRuntimeWindows,Fn as nvmCurrentBin,wn as parseEnvPath,Tn as parseRegValue,T as parseSentinel,Z as parseWhich,tt as primeAgentLookups,Ln as profilePathWindows,k as refreshShellPath,en as refreshWindowsPath,yn as registryPathWindows,nt as resetShellProbes,ot as resolveClaude,B as resolveCommand,Zn as selfMcpStdio,bn as shellPath,Bn as toWslPath,cn as wslAnswer,it as wslProbeInFlight};
1
+ import{isCompiledBinary as jn,hostFacts as wn}from"./events/runtime-host.js";import j from"node:os";import{spawnGroupOpts as U}from"./proc.js";import c from"node:path";import{spawn as X,spawnSync as h}from"node:child_process";import{readdirSync as M,readFileSync as D,existsSync as f}from"node:fs";let z=!1,Q=!1;const R=["codex","claude","agy","pi","opencode","kiro-cli","copilot","dsh"];function hn(n){return d(process.env.PATH||"",process.platform).some(o=>o&&(f(c.join(o,n))||f(c.join(o,n+".exe"))))}function bn(n){const t=I(n);if(t)return t;if(k()){const o=I(n);if(o)return o}return xn(n)||null}function tt(n){return!!B(n,{probe:"async"})}function I(n){for(const t of dn(n))if(f(t))return t;return null}function $(){return jn(wn())}function et(n){const t=["--mcp-stdio",n];if($())return{command:process.execPath,args:t};const o=process.argv[1]||c.join(process.cwd(),"src","server.js"),e=process.env.CHATPANEL_BRIDGE_EMBEDDED==="1"?["--bridge"]:[];return{command:process.execPath,args:[o,...e,...t]}}const b="CHATPANEL_ENV",W=6e3;function T(n){for(const t of String(n||"").split(/\r?\n/)){const o=t.indexOf(" ");if(o>0&&t.slice(0,o).trim().endsWith(b))return t.slice(o+1).trim()}return""}function q(n){return/^[\w.+-]+$/.test(String(n||""))}function v(){if(process.env.SHELL)return process.env.SHELL;try{const{shell:n}=j.userInfo();if(n&&n!=="/usr/bin/false"&&n!=="/sbin/nologin")return n}catch{}return"/bin/sh"}function J(n,{interactive:t}={}){if(process.platform==="win32")return"";try{const o=t?["-l","-i","-c"]:["-l","-c"];return h(v(),[...o,n],{encoding:"utf8",timeout:W,stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}}).stdout||""}catch{return""}}function gn(n){let t="";for(const o of String(n||"").split(/\r?\n/))o.startsWith("PATH=")&&(t=o.slice(5).trim());return t}function Pn({interactive:n=!0,ask:t=J}={}){const o=T(t(`command -p printf '%s\\t%s\\n' ${b} "$PATH"`,{interactive:n}));return d(o||gn(t("/usr/bin/env",{interactive:n})),process.platform)}const y=1e4,_n=3e5;let L=0,x=y;function k({force:n=!1,now:t=Date.now(),read:o=Pn,env:e=process.env}={}){if(process.platform==="win32"||!n&&(t-L<x||t<_))return!1;L=t;const i=d(e.PATH||"",process.platform),r=Y(m([...o({interactive:!0}),...i])),s=r.length>i.length;return x=s?y:Math.min(x*2,_n),s?(e.PATH=r.join(c.delimiter),!0):!1}function ot(){L=0,x=y,w.clear(),_=0,A=H,O=!1}const w=new Map,An=15e3;function xn(n){if(process.platform==="win32"||!q(n))return"";const t=w.get(n);if(t&&(t.bin||Date.now()-t.at<An||Date.now()<_))return t.bin;const o=[`command -p printf '%s\\t%s\\n' ${b} "$(command -v ${n} 2>/dev/null)"`,`type -p ${n}`];let e="";for(const i of[!1,!0]){for(const r of o){const s=J(r,{interactive:i}),l=T(s)||String(s||"").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.startsWith("/")).pop()||"";if(l.startsWith("/")&&f(l)){e=l;break}}if(e)break}return w.set(n,{bin:e,at:Date.now()}),e}const H=15e3,En=3e5;let _=0,A=H,O=!1,E=null;function Sn(n,{interactive:t}={}){return new Promise(o=>{let e="",i;try{i=X(v(),[...t?["-l","-i","-c"]:["-l","-c"],n],{stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}})}catch{o("");return}const r=setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},W);i.stdout.on("data",s=>{e+=s}),i.on("error",()=>{clearTimeout(r),o("")}),i.on("close",()=>{clearTimeout(r),o(e)})})}const Cn=new RegExp(`${b}=([\\w.+-]+)$`);function Z(n){const t=new Map;for(const o of String(n||"").split(/\r?\n/)){const e=o.indexOf(" ");if(e<=0)continue;const i=Cn.exec(o.slice(0,e).trim());i&&t.set(i[1],o.slice(e+1).trim())}return t}function it({names:n=R,ask:t=Sn,now:o=()=>Date.now()}={}){if(process.platform==="win32"||O)return Promise.resolve(!1);if(E)return E;if(o()<_)return Promise.resolve(!1);const e=m([...n,...w.keys()]).filter(r=>q(r)&&!I(r)&&!w.get(r)?.bin);if(!e.length)return Promise.resolve(!1);const i=[`command -p printf '%s\\t%s\\n' ${b} "$PATH"`,...e.map(r=>`command -p printf '%s\\t%s\\n' ${b}=${r} "$(command -v ${r} 2>/dev/null)"`)].join("; ");return E=(async()=>{let r=await t(i,{interactive:!0}),s=Z(r);if(s.size||(r=await t(i,{interactive:!1}),s=Z(r)),!s.size)return O=!0,!0;const l=o();let a=!1;const u=d(T(r),process.platform);u.length&&k({force:!0,now:l,read:()=>u})&&(a=!0);for(const p of e){if(!s.has(p))continue;const g=s.get(p),P=g.startsWith("/")&&f(g)?g:"";(P||I(p))&&(a=!0),w.set(p,{bin:P,at:l})}return a&&(A=H),_=l+A,a||(A=Math.min(A*2,En)),!0})().catch(()=>!0).finally(()=>{E=null}),E}function rt(){_=0,A=H,O=!1,L=0,x=y,F=0;for(const[n,t]of w)t.bin||w.delete(n);for(const[n,t]of S)t.ok||S.delete(n)}function st({probe:n="sync"}={}){return process.env.CHATPANEL_CLAUDE_PATH?B(process.env.CHATPANEL_CLAUDE_PATH,{probe:n}):B("claude",{probe:n})}function B(n,{probe:t="sync"}={}){if(!n)return null;if(n.includes("/")||n.includes("\\")||/\.[a-z0-9]+$/i.test(n)){if(!f(n))return null;const i=c.extname(n).toLowerCase();return!$()&&/^\.(c?js|mjs)$/.test(i)?{kind:"script",script:n}:process.platform==="win32"&&(i===".cmd"||i===".bat")?{kind:"cmd",bin:n}:process.platform==="win32"&&i===""&&!fn(n)?null:{kind:"native",bin:n}}if(process.platform==="win32"){const i=Dn(n);return i||(/^[\w.-]+$/.test(n)&&Fn(n,{probe:t})?{kind:"wsl",command:n}:null)}const e=bn(n);return e?{kind:"native",bin:e}:null}const Mn="HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",In="HKCU\\Environment",Tn=4e3,vn=3e5;let F=0,nn=0;function yn(n,t="Path"){const o=String(t).toLowerCase();for(const e of String(n||"").split(/\r?\n/)){const i=/^\s*(\S+)\s+REG_(?:EXPAND_)?SZ\s+(.*?)\s*$/.exec(e);if(i&&i[1].toLowerCase()===o)return i[2]}return""}function tn(n,t=process.env){const o=new Map(Object.keys(t||{}).map(e=>[e.toLowerCase(),t[e]]));return String(n||"").replace(/%([^%]+)%/g,(e,i)=>{const r=o.get(String(i).toLowerCase());return r==null?e:String(r)})}function Ln(n,t){try{const o=c.win32.join(process.env.SystemRoot||"C:\\Windows","System32","reg.exe"),e=h(f(o)?o:"reg",["query",n,"/v",t],{encoding:"utf8",timeout:3e3,windowsHide:!0});return e.status===0?yn(e.stdout,t):""}catch{return""}}function Hn({query:n=Ln,env:t=process.env}={}){const o=tn(n(Mn,"Path"),t),e=tn(n(In,"Path"),t);return m([...d(o,"win32"),...d(e,"win32")])}function On({run:n=Nn}={}){const t=n(`[Console]::Out.Write("${b}\`t" + $env:PATH + "\`n")`);return d(T(t),"win32")}function Nn(n){for(const t of["pwsh.exe","powershell.exe"])try{const o=h(t,["-NoLogo","-NonInteractive","-ExecutionPolicy","Bypass","-Command",n],{encoding:"utf8",timeout:W,stdio:["ignore","pipe","ignore"],windowsHide:!0}),e=K(o.stdout||"");if(e)return e}catch{}return""}function en({force:n=!1,now:t=Date.now(),registry:o=Hn,profile:e=On,env:i=process.env,home:r=j.homedir()}={}){if(process.platform!=="win32"&&!n||!n&&t-nn<Tn)return!1;nn=t;const s=d(i.PATH||"","win32"),l=m([...s,...o({env:i}),...G(r,"win32",i)]);t-F>=vn&&R.some(u=>!l.some(p=>f(c.win32.join(p,`${u}.cmd`))||f(c.win32.join(p,`${u}.exe`))))&&(F=t,l.push(...e()));const a=Y(m(l),"win32");return a.length===s.length?!1:(i.PATH=a.join(V("win32")),!0)}function Dn(n){return on(n)||(en()?on(n):null)}function on(n){const t=C("win32");for(const o of dn(n,j.homedir(),"win32",process.env)){if(!f(o))continue;const e=t.dirname(o),i=t.extname(o).toLowerCase(),r=n==="claude"&&$n(e)||Wn(e,n)||(/^\.(c?js|mjs)$/.test(i)?o:null);if(r){if(!$())return{kind:"script",script:r};const s=Rn(e);if(s)return{kind:"script",script:r,runtime:s}}if(i===".exe")return{kind:"native",bin:o};if(i===".cmd"||i===".bat")return{kind:"cmd",bin:o};if(i===""&&fn(o))return{kind:"native",bin:o}}return null}function Rn(n,{env:t=process.env,exists:o=f}={}){const e=c.win32,i=m([n,...d(t.PATH||"","win32"),...t.NVM_SYMLINK?[t.NVM_SYMLINK]:[],e.join(t.ProgramFiles||"C:\\Program Files","nodejs")]);for(const r of i){const s=e.join(r,"node.exe");if(o(s))return s}return null}function $n(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 e=c.join(n,...o);if(f(e))return e}return null}function Wn(n,t){for(const o of[`${t}.cmd`,t,`${t}.ps1`]){let e;try{e=D(c.join(n,o),"utf8")}catch{continue}const i=e.match(/(?:%~?dp0%|\$basedir|\$\{basedir\})[\\/]+([^"'\s]+\.[cm]?js)/i);if(i){const r=c.join(n,i[1].replace(/[\\/]+/g,c.sep));if(f(r))return r}}return null}const S=new Map,N=new Map,kn=15e3,Bn=3e5,rn=8e3,sn=n=>["-e","bash","-lic",`command -v ${n}`];function cn(n,t){return n!==0?!1:(K(String(t||"")).replace(/\0/g,"").split(/\r?\n/).map(e=>e.trim()).filter(Boolean).pop()||"").startsWith("/")}function ln(n,t,o){const e=S.get(n),i=t?0:Math.min(e&&!e.ok&&e.ttl?e.ttl*2:kn,Bn);S.set(n,{ok:t,at:o,ttl:i})}function Fn(n,{probe:t="sync",now:o=Date.now(),spawnSyncImpl:e=h,spawnImpl:i=X}={}){const r=S.get(n);if(r&&(r.ok||o-r.at<r.ttl))return r.ok;if(t==="async"){if(!N.has(n)){const l=new Promise(a=>{let u="",p;try{p=i("wsl.exe",sn(n),{windowsHide:!0,stdio:["ignore","pipe","ignore"]})}catch{a(!1);return}const g=setTimeout(()=>{try{p.kill()}catch{}},rn);p.stdout?.on("data",P=>{u+=P}),p.on("error",()=>{clearTimeout(g),a(!1)}),p.on("close",P=>{clearTimeout(g),a(cn(P,u))})}).then(a=>(ln(n,a,Date.now()),a)).finally(()=>N.delete(n));N.set(n,l)}return!1}let s=!1;try{const l=e("wsl.exe",sn(n),{encoding:"utf8",timeout:rn,windowsHide:!0});s=cn(l.status,l.stdout)}catch{s=!1}return ln(n,s,o),s}function ct(n){return N.get(n)||null}function lt(n,t,o,e=null){const i=e&&typeof e=="object"&&Object.keys(e).length?{...process.env,...e}:process.env;if(n.kind==="wsl"){const s=[];if(o){const a=Kn(o);a&&s.push("--cd",a)}return["wsl.exe",[...s,"-e","bash","-lic",`exec ${n.command} "$@"`,"chatpanel",...t],{stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...U}]}const r={cwd:o||j.homedir(),stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...U};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 Kn(n){try{const t=h("wsl.exe",["-e","wslpath","-a",n],{encoding:"utf8",timeout:5e3,windowsHide:!0}),o=K(t.stdout||"").trim();return o.startsWith("/")?o:null}catch{return null}}function K(n){return n.replace(/^/,"").trim()}function Vn(n=j.homedir(),t=process.env){const o=c.join(t.NVM_DIR||c.join(n,".nvm"),"versions","node");let e;try{e=M(o).filter(r=>/^v\d+\./.test(r))}catch{return null}if(!e.length)return null;const i=(r,s)=>{const l=r.slice(1).split(".").map(Number),a=s.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=D(c.join(t.NVM_DIR||c.join(n,".nvm"),"alias","default"),"utf8").trim(),s=r.startsWith("v")?r:`v${r}`;if(e.includes(s))return c.join(o,s,"bin")}catch{}return c.join(o,e.sort(i)[0],"bin")}function Yn(n,t=process.env){return[c.join(t.MISE_DATA_DIR||c.join(n,".local","share","mise"),"shims"),c.join(n,".local","share","rtx","shims"),c.join(t.ASDF_DATA_DIR||c.join(n,".asdf"),"shims"),c.join(t.PYENV_ROOT||c.join(n,".pyenv"),"shims"),c.join(t.RBENV_ROOT||c.join(n,".rbenv"),"shims"),c.join(t.NODENV_ROOT||c.join(n,".nodenv"),"shims"),c.join(t.PROTO_HOME||c.join(n,".proto"),"shims"),c.join(t.PROTO_HOME||c.join(n,".proto"),"bin"),c.join(t.VOLTA_HOME||c.join(n,".volta"),"bin")]}function Gn(n,t=process.env){const o=[],e=(i,r)=>{try{for(const s of M(i))o.push(c.join(i,s,r))}catch{}};return e(c.join(t.NVM_DIR||c.join(n,".nvm"),"versions","node"),"bin"),e(c.join(n,".local","share","fnm","node-versions"),c.join("installation","bin")),e(c.join(n,"Library","Application Support","fnm","node-versions"),c.join("installation","bin")),e(c.join(t.MISE_DATA_DIR||c.join(n,".local","share","mise"),"installs","node"),"bin"),o}function C(n){return n==="win32"?c.win32:c}function V(n){return n==="win32"?";":c.delimiter}function d(n,t){return(n||"").split(V(t)).filter(Boolean)}function m(n){return[...new Set(n.filter(Boolean))]}const an={win32:3e4,other:65536};function Y(n,t=process.platform){const o=t==="win32"?an.win32:an.other,e=V(t),i=[];let r=0;for(const s of n){const l=s.length+(i.length?e.length:0);if(r+l>o)break;i.push(s),r+=l}return i}function G(n,t=process.platform,o=process.env){const e=C(t);if(t==="win32"){const i=o.APPDATA||e.join(n,"AppData","Roaming"),r=o.LOCALAPPDATA||e.join(n,"AppData","Local"),s=o.ProgramFiles||"C:\\Program Files",l=o["ProgramFiles(x86)"]||"C:\\Program Files (x86)",a=o.ProgramData||"C:\\ProgramData";return[e.join(n,".local","bin"),e.join(n,".codex","bin"),e.join(n,".claude","bin"),e.join(n,".claude","local"),e.join(n,".claude","local","bin"),e.join(i,"npm"),...o.NVM_SYMLINK?[o.NVM_SYMLINK]:[],e.join(s,"nodejs"),...Un(i,r),e.join(r,"pnpm"),e.join(r,"Yarn","bin"),e.join(r,"Volta","bin"),e.join(n,".yarn","bin"),e.join(n,".bun","bin"),e.join(n,".deno","bin"),e.join(o.SCOOP||e.join(n,"scoop"),"shims"),e.join(a,"chocolatey","bin"),e.join(r,"Microsoft","WindowsApps"),e.join(r,"Microsoft","WinGet","Links"),e.join(o.MISE_DATA_DIR||e.join(r,"mise"),"shims"),e.join(o.PROTO_HOME||e.join(n,".proto"),"shims"),e.join(o.PROTO_HOME||e.join(n,".proto"),"bin"),e.join(r,"Programs","Claude Code"),e.join(r,"Anthropic","Claude Code"),e.join(s,"Claude Code"),e.join(s,"Anthropic","Claude Code"),e.join(l,"Claude Code"),e.join(l,"Anthropic","Claude Code")]}return[c.join(n,".local","bin"),c.join(n,".opencode","bin"),c.join(n,".codex","bin"),c.join(n,".claude","bin"),c.join(n,".claude","local"),c.join(n,".claude","local","bin"),o.PNPM_HOME||c.join(n,"Library","pnpm"),c.join(n,".local","share","pnpm"),c.join(n,".nix-profile","bin"),"/nix/var/nix/profiles/default/bin",c.join(n,".guix-profile","bin"),"/home/linuxbrew/.linuxbrew/bin","/snap/bin",...Yn(n,o)]}function Un(n,t){const o=c.win32,e=[];for(const i of[o.join(t,"fnm"),o.join(n,"fnm")]){let r=[];try{r=M(o.join(i,"node-versions")).filter(s=>/^v?\d+\.\d+\.\d+/.test(s)).sort((s,l)=>l.localeCompare(s,void 0,{numeric:!0}))}catch{}for(const s of r)e.push(o.join(i,"node-versions",s,"installation"))}return e}function un(n,t=process.platform){const o=C(t),e=o.join(n,".local","share","claude","versions");let i=[];try{i=M(e).filter(r=>/^\d+\.\d+\.\d+/.test(r)).sort((r,s)=>s.localeCompare(r,void 0,{numeric:!0}))}catch{}return i.map(r=>o.join(e,r))}function pn(n,t){return t!=="win32"?[n]:/\.(cmd|exe|bat|ps1)$/i.test(n)?[n]:[`${n}.exe`,`${n}.cmd`,`${n}.bat`,n,`${n}.ps1`]}function fn(n,t=D){try{const o=t(n).subarray(0,2);return o.length===2&&o[0]===77&&o[1]===90}catch{return!1}}function Xn(n,t=j.homedir(),o=process.platform,e=process.env){const i=C(o),r=i.join(t,".local","bin",n),s=o==="win32"?e.LOCALAPPDATA||i.join(t,"AppData","Local"):null,l=o==="win32"?e.ProgramFiles||"C:\\Program Files":null,a=o==="win32"?e["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"),...o==="win32"?[i.join(s,"Microsoft","WindowsApps","claude.exe"),i.join(s,"Programs","Claude Code","claude.exe"),i.join(s,"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"),...un(t,o)]:un(t,o)],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 m((u[n]||[r]).flatMap(p=>pn(p,o)))}function dn(n,t=j.homedir(),o=process.platform,e=process.env){const i=C(o),r=m([...d(e.PATH||"",o),...G(t,o,e)]).flatMap(s=>pn(i.join(s,n),o));return m([...r,...Xn(n,t,o,e)])}const mn=["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 at(){if(Q||(Q=!0,process.platform==="win32"))return;const n=mn.filter(t=>!process.env[t]);if(n.length)try{const t=v(),o=`${n.map(i=>`[ -n "\${${i}:-}" ] && printf '%s\\t%s\\n' ${i} "$${i}"`).join("; ")}; true`,e=h(t,["-l","-i","-c",o],{encoding:"utf8",timeout:6e3,env:{...process.env,TERM:"dumb"}});for(const i of String(e.stdout||"").split(`
2
+ `)){const r=i.indexOf(" ");if(r<=0)continue;const s=i.slice(0,r).trim(),l=i.slice(r+1);mn.includes(s)&&!process.env[s]&&l&&(process.env[s]=l)}}catch{}}function ut(){if(z)return;z=!0;const n=j.homedir();if(process.platform==="win32"){en({force:!0,home:n});return}const t=Vn(n),o=[...t?[t]:[],"/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",c.join(n,".local","bin"),c.join(n,"bin"),c.join(n,".npm-global","bin"),c.join(n,".cargo","bin"),c.join(n,".deno","bin"),c.join(n,".bun","bin"),...G(n),...Gn(n)];let e="";try{const s=v(),l=h(s,["-l","-c",'command -p echo "$PATH"'],{encoding:"utf8",timeout:4e3});l.status===0&&(e=(l.stdout||"").trim())}catch{}const i=new Set,r=[...t?[t]:[],...e?e.split(":"):[],...process.env.PATH?process.env.PATH.split(c.delimiter):[],...o].filter(s=>s&&!i.has(s)&&(i.add(s),!0));process.env.PATH=Y(r).join(c.delimiter),R.some(s=>!hn(s))&&k({force:!0})}export{R as AGENT_CLIS,tt as agentAvailable,Xn as agentCandidateBins,G as agentInstallDirs,lt as buildSpawnSpec,Y as capPathList,dn as commandCandidateFiles,Fn as commandInWsl,at as enrichAgentEnv,ut as enrichPath,tn as expandWindowsEnv,bn as findAgentBin,rt as forgetMisses,$ as isCompiledBinary,fn as isWindowsExecutable,Rn as nodeRuntimeWindows,Vn as nvmCurrentBin,gn as parseEnvPath,yn as parseRegValue,T as parseSentinel,Z as parseWhich,it as primeAgentLookups,On as profilePathWindows,k as refreshShellPath,en as refreshWindowsPath,Hn as registryPathWindows,ot as resetShellProbes,st as resolveClaude,B as resolveCommand,et as selfMcpStdio,Pn as shellPath,Kn as toWslPath,cn as wslAnswer,ct as wslProbeInFlight};
@@ -0,0 +1 @@
1
+ import{EventError as j}from"./event.js";import{SECRET_PATHS as z}from"./sandbox-policy.js";import{egressAllowed as N}from"./policy.js";const p=e=>!!e&&typeof e=="object"&&!Array.isArray(e),c=(e,n)=>{if(!e)throw new j("SHAPE",n)},R=e=>[...new Set(e)],f=Object.freeze(["path","host"]),v=Object.freeze(["once","session","always"]),x=Object.freeze(["read","write"]),I=Object.freeze(["refused","ahead"]),H=Object.freeze(["grant","deny","ask"]),O=500,u=e=>{let n=String(e||"").trim();for(;n.length>1&&(n.endsWith("/")||n.endsWith("\\"));)n=n.slice(0,-1);return n},w=(e,n)=>n&&(e==="~"||e.startsWith("~/")||e.startsWith("~\\"))?n+e.slice(1):e;function g(e,n){const t=u(e),s=u(n);return!t||!s?!1:t===s||t.startsWith(`${s}/`)||t.startsWith(`${s}\\`)}function E(e,n=""){const t=u(w(u(e),n));return z.some(s=>g(t,u(s))||g(t,u(w(s,n))))}function M(e,n=""){const t=u(w(u(e),n));if(!t||t==="/"||t==="~"||/^[a-z]:$/i.test(t)||/^[a-z]:\\?$/i.test(t)||n&&t===u(n))return!0;const s=t.split(/[/\\]/).filter(Boolean).length;return t.startsWith("/")&&s<2}function b(e){c(p(e),"access request: must be an object");const n=e.what;c(p(n),"access request: what { kind, value, mode } required");const t=String(n.kind||"");c(f.includes(t),`access request: kind must be one of ${f.join(", ")}`);const s=t==="path"?u(n.value):String(n.value||"").trim().toLowerCase();c(s.length>0&&s.length<1024&&!s.includes("\0"),`access request: not a ${t}: ${JSON.stringify(n.value)}`);const o=n.mode==null?"write":String(n.mode);c(x.includes(o),`access request: mode must be one of ${x.join(", ")}`);const a=e.scope==null?"session":String(e.scope);c(v.includes(a),`access request: scope must be one of ${v.join(", ")}`);const i=e.asked==null?"refused":String(e.asked);return c(I.includes(i),`access request: asked must be one of ${I.join(", ")}`),{id:String(e.id||""),at:Number(e.at)||0,commandId:String(e.commandId||""),engine:String(e.engine||""),agentId:String(e.agentId||""),runId:String(e.runId||""),what:{kind:t,value:s,mode:o},why:String(e.why||"").slice(0,O),scope:a,asked:i,state:"pending"}}function P(e,{home:n=""}={}){c(p(e),"delegation: must be an object");const t=e.what;c(p(t),"delegation: what { kind, under | host, mode } required");const s=String(t.kind||"");c(f.includes(s),`delegation: kind must be one of ${f.join(", ")}`);const o=t.mode==null?"write":String(t.mode);c(x.includes(o),`delegation: mode must be one of ${x.join(", ")}`);const a=e.scope==null?"session":String(e.scope);c(a==="once"||a==="session","delegation: scope must be once or session — a standing grant is a person's decision, not a rule's");const i={id:String(e.id||""),label:String(e.label||"").slice(0,120),enabled:e.enabled!==!1,what:{kind:s,mode:o},scope:a};if(s==="path"){const r=u(t.under);c(r.length>0,"delegation: what.under is required — a rule without a root is not a bounded rule"),c(!E(r,n),`delegation: ${r} is a secret path and can never be granted`),c(!M(r,n),`delegation: ${r} is too broad to delegate — name the project folder, not the disk`),i.what.under=r}else{const r=String(t.host||t.under||"").trim().toLowerCase();c(/^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i.test(r)&&r!=="*",`delegation: not a host pattern: ${JSON.stringify(t.host)}`),i.what.host=r}return i.ttlMs=Math.max(0,Math.min(Number(e.ttlMs)||0,365*24*3600*1e3)),i.maxPerRun=e.maxPerRun==null?0:Math.max(0,Math.min(Number(e.maxPerRun)||0,1e3)),i.agents=R((Array.isArray(e.agents)?e.agents:[]).map(r=>String(r).trim()).filter(Boolean)),i.expiresAt=Number(e.expiresAt)||0,i.createdBy=String(e.createdBy||""),i}function _(e,n,{home:t=""}={}){if(!e?.enabled||e.what.kind!==n.what.kind||e.what.mode==="read"&&n.what.mode==="write"||e.agents.length&&!e.agents.includes(n.engine)&&!e.agents.includes(n.agentId))return!1;if(e.what.kind==="path")return g(w(n.what.value,t),w(e.what.under,t));const s=n.what.value;return e.what.host.startsWith("*.")?s===e.what.host.slice(2)||s.endsWith(e.what.host.slice(1)):s===e.what.host}const k=Object.freeze({ALLOW:"allow",ALWAYS:"allow_always",DENY:"deny"});function D(e){return e===k.ALWAYS?"always":"session"}function C(e,{home:n=""}={}){c(p(e),"access grant: must be an object");const t=e.what;c(p(t),"access grant: what required");const s=String(t.kind||"");c(f.includes(s),`access grant: kind must be one of ${f.join(", ")}`);const o=s==="path"?u(t.value):String(t.value||"").trim().toLowerCase();c(o.length>0,"access grant: what.value required"),c(!(s==="path"&&E(o,n)),`access grant: ${o} is a secret path and can never be granted`);const a=String(e.scope||"session");return c(v.includes(a),`access grant: scope must be one of ${v.join(", ")}`),{id:String(e.id||""),what:{kind:s,value:o,mode:t.mode==="read"?"read":"write"},scope:a,allow:e.allow!==!1,at:Number(e.at)||0,expiresAt:Number(e.expiresAt)||0,by:String(e.by||""),label:String(e.label||"").slice(0,200)}}function F(e,n,t,{now:s=0,newId:o=()=>"",home:a=""}={}){const i=b(n);if(t===k.DENY)return[...y(e,a),C({id:o(),what:i.what,scope:"session",allow:!1,at:s,by:"person"},{home:a})];const r=D(t),d=C({id:o(),what:i.what,scope:r,allow:!0,at:s,by:"person",label:i.what.value},{home:a}),m=[];for(const h of y(e,a)){if(h.allow&&W(h,i,{home:a,now:s})&&$(h.scope)>=$(r))return y(e,a);h.allow===d.allow&&h.what.kind===d.what.kind&&$(h.scope)<=$(r)&&W(d,{what:h.what,engine:i.engine},{home:a})||m.push(h)}return[...m,d]}const $=e=>e==="always"?2:e==="session"?1:0,y=(e,n="")=>(Array.isArray(e)?e:[]).map(t=>{try{return C(t,{home:n})}catch{return null}}).filter(Boolean);function W(e,n,{home:t="",now:s=0}={}){if(!e||e.expiresAt&&s&&s>e.expiresAt||e.what.kind!==n.what.kind||e.allow&&e.what.mode==="read"&&n.what.mode==="write")return!1;if(e.what.kind==="path")return g(w(n.what.value,t),w(e.what.value,t));const o=n.what.value;return e.what.value.startsWith("*.")?o===e.what.value.slice(2)||o.endsWith(e.what.value.slice(1)):o===e.what.value}function L(e,n,{home:t="",now:s=0}={}){const o=b(n),a=y(e,t).filter(r=>W(r,o,{home:t,now:s}));if(!a.length)return null;const i=a.find(r=>r.allow);return i?{verdict:"grant",by:{kind:"person",id:i.by},ruleId:i.id,reason:i.scope==="always"?"you allowed this folder":"you allowed this earlier in this chat",scope:i.scope,expiresAt:i.expiresAt||0}:{verdict:"deny",by:{kind:"person",id:a[0].by},ruleId:a[0].id,reason:"you denied this earlier in this chat",scope:"session"}}function G(e,n,{home:t=""}={}){return y(e,t).filter(s=>s.id!==String(n))}function J(e,{now:n=0,home:t=""}={}){return y(e,t).filter(s=>s.allow&&s.scope==="always"&&!(s.expiresAt&&n&&n>s.expiresAt))}const S=(e,n,t={})=>({verdict:e,by:n,ruleId:"",reason:"",...t});function K({request:e,delegations:n=[],policy:t=null,now:s=0,usedPerRule:o={},home:a="",canAsk:i=!0,grants:r=[]}={}){const d=b(e);if(d.what.kind==="path"&&E(d.what.value,a))return S("deny",{kind:"floor"},{reason:`${d.what.value} holds credentials or ChatPanel's own store, and is never grantable`});if(t&&d.what.kind==="host"&&!N(t,d.what.value))return S("deny",{kind:"policy"},{reason:`your organisation does not allow ${d.what.value}`});if(t&&d.what.kind==="path"&&Array.isArray(t.access?.deny)){const A=t.access.deny.find(l=>g(w(d.what.value,a),w(u(l),a)));if(A)return S("deny",{kind:"policy"},{reason:`your organisation does not allow access under ${A}`})}const m=L(r,d,{home:a,now:s});if(m)return m;const h=t?.access?.delegation!=="never";if(h)for(const A of n){let l;try{l=P(A,{home:a})}catch{continue}if(_(l,d,{home:a})&&!(l.expiresAt&&s&&s>l.expiresAt)&&!(l.maxPerRun&&(o[l.id]||0)>=l.maxPerRun))return S("grant",{kind:"delegation",id:l.createdBy||""},{ruleId:l.id,reason:l.label?`allowed by your rule “${l.label}”`:"allowed by a rule you set",scope:l.scope,expiresAt:l.ttlMs&&s?s+l.ttlMs:0})}return i?S("ask",{kind:"person"},{scope:d.scope}):S("deny",{kind:"floor"},{reason:h?"nothing here can approve this, and an unanswered request is a denial":"your organisation requires a person to approve this, and this run has nobody to ask"})}function V(e={},{newId:n=()=>"",now:t=0}={}){const s=e.path?"path":"host";return b({id:e.id||n()||"",at:e.at||t||0,commandId:e.commandId||"",engine:e.engine||"",agentId:e.agentId||"",runId:e.runId||"",what:{kind:s,value:s==="path"?e.path:e.host,mode:e.mode||"write"},why:e.why||"",scope:"session",asked:"refused"})}function X(e={}){const n=p(e.input)?e.input:{},t=String(e.tool||"");let o=((/^(Write|Edit|MultiEdit|NotebookEdit)$/.test(t)?String(n.file_path||n.notebook_path||""):"")||String(e.path||"")).trim();if(!o)for(const a of Array.isArray(e.rules)?e.rules:[]){if(!/^(Read|Edit|Write|MultiEdit|NotebookEdit)$/.test(String(a?.tool||"")))continue;const i=String(a.content||"").trim().replace(/\/\*\*$|\/\*$/,"");if(i.startsWith("//")){o=i.slice(1);break}if(i==="~"||i.startsWith("~/")){o=i;break}}return o&&!o.includes("\0")?o:null}function Q(e,{home:n=""}={}){const t=b(e),s=t.engine||t.agentId||"This agent",o=d=>n&&g(d,u(n))?`~${d.slice(u(n).length)}`:d,a=t.what.kind==="path",i=a?o(t.what.value):t.what.value,r=t.what.mode==="read"?"read":a?"write in":"reach";return{title:`${s} wants to ${r} ${a&&i.split(/[/\\]/).filter(Boolean).pop()||i}`,detail:i,kind:t.what.kind,why:t.why,answers:[{id:k.ALLOW,label:"Allow",hint:"for the rest of this chat"},{id:k.ALWAYS,label:`Always allow ${i}`,hint:"revoke any time in Settings › Runtime"},{id:k.DENY,label:"Deny",hint:""}]}}function U(e,n){const t=b(e),s=(t.what.kind==="path",t.what.value),o=t.engine||t.agentId||"the agent",a=t.what.mode==="read"?"read":"write in";if(n?.verdict==="grant"){const i=n.by?.kind==="delegation"?n.reason||"allowed by a rule you set":"allowed by you";return`${o} asked to ${a} ${s} — ${i}`}return n?.verdict==="deny"?`${o} asked to ${a} ${s} — denied${n.reason?` (${n.reason})`:""}`:`${o} is asking to ${a} ${s}`}export{k as ACCESS_ANSWERS,I as ACCESS_ASKED,f as ACCESS_KINDS,x as ACCESS_MODES,v as ACCESS_SCOPES,H as ACCESS_VERDICTS,O as WHY_MAX,V as accessRequestFromRefusal,K as decideAccess,_ as delegationCovers,Q as describeAccessCard,U as describeDecision,W as grantCovers,E as isSecretPath,M as isTooBroadRoot,C as normalizeAccessGrant,b as normalizeAccessRequest,P as normalizeDelegation,g as pathInside,X as permissionAccessTarget,L as recallAccess,F as rememberAccess,G as revokeAccess,D as scopeForAnswer,J as standingGrants};
@@ -1,2 +1,2 @@
1
- const $="permission_request",p=Object.freeze({ALLOW:"allow",ALLOW_CHAT:"allow_chat",DENY:"deny"}),W=600*1e3,_="permission_prompt";function N(){return{name:_,description:"Chap-internal: the person answers the agent's permission prompt. Not for the model.",parameters:{type:"object",properties:{tool:{type:"string"},input:{type:"object"},description:{type:"string"},path:{type:"string"},rules:{type:"array"}}}}}const T=t=>t===_,u=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),a=t=>typeof t=="string"?t:t==null?"":String(t);function k(t={}){const e=u(t)?t:{},o=a(e.tool_name||e.toolName||e.tool),n=[];for(const s of Array.isArray(e.permission_suggestions)?e.permission_suggestions:[])if(!(!u(s)||s.type!=="addRules"||s.behavior==="deny"))for(const r of Array.isArray(s.rules)?s.rules:[]){if(!u(r))continue;const c=a(r.toolName||o),i=a(r.ruleContent);c&&!n.some(f=>f.tool===c&&f.content===i)&&n.push({tool:c,content:i})}return{tool:o,displayName:a(e.display_name||e.displayName)||o,input:u(e.input)?e.input:{},description:a(e.description),path:a(e.blocked_path||e.path)||null,rules:n,toolUseId:a(e.tool_use_id||e.toolUseId)||null}}function g(t={}){const e=Array.isArray(t.rules)?t.rules.filter(o=>o&&o.tool):[];return e.length?e.map(o=>o.content?`${o.tool}(${o.content})`:o.tool):t.tool?[String(t.tool)]:[]}function L(t={}){const e=a(t.tool),o=u(t.input)?t.input:{},n=(l,d=240)=>l.length>d?`${l.slice(0,d-1)}…`:l;let s,r;if(e==="Bash")s="Run a command",r=n(a(o.command).trim()||a(t.description)||"a shell command");else if(e==="Edit"||e==="MultiEdit"||e==="NotebookEdit")s="Edit a file",r=a(o.file_path||o.notebook_path||t.path)||"a file";else if(e==="Write"){s="Write a file";const l=a(o.file_path||t.path)||"a file",d=a(o.content).length;r=d?`${l} (${d.toLocaleString()} chars)`:l}else if(/^mcp__/.test(e))s="Use a connected server",r=e.replace(/^mcp__/,"").replace(/__/," › ");else{s=`Use ${t.displayName||e||"a tool"}`;let l="";try{l=JSON.stringify(o)}catch{l=""}r=a(t.description)||(l&&l!=="{}"?n(l,200):e)}const c=g(t),i=Array.isArray(t.rules)?t.rules.filter(l=>l?.content):[],f=i.length&&i.some(l=>l.content!==r)?i.map(l=>l.content).join(", "):c.length&&!i.length?`every ${e} call`:null;return{title:s,detail:r,scope:f,description:a(t.description)||null}}function h(t,e=""){return t===p.ALLOW?{behavior:"allow",scope:"once"}:t===p.ALLOW_CHAT?{behavior:"allow",scope:"chat"}:{behavior:"deny",scope:"once",...e?{message:String(e)}:{}}}function w(t){return u(t)&&t.behavior==="allow"}function E(t,e){const o=new Set(Array.isArray(t)?t:[]);for(const n of g(e))o.add(n);return[...o].sort()}const b="*";function O(t,e){const o=new Set(Array.isArray(t)?t:[]);if(o.has(b))return h(p.ALLOW);const n=g(e);return n.length&&n.every(s=>o.has(s))?h(p.ALLOW):null}function R(t,e,o={}){const n=u(o)?o:{},s=w(e);let r;if(s){if(r={behavior:"allow",updatedInput:u(n.input)?n.input:{}},e.scope==="chat"){const c=(Array.isArray(n.permission_suggestions)?n.permission_suggestions:[]).filter(i=>u(i)&&i.type==="addRules"&&i.behavior!=="deny"&&Array.isArray(i.rules)&&i.rules.length).map(i=>({type:"addRules",rules:i.rules,behavior:"allow",destination:"session"}));c.length&&(r.updatedPermissions=c)}}else r={behavior:"deny",message:a(e?.message)||"The user declined this action in Chap. Continue without it, or explain what it was for and ask."};return{type:"control_response",response:{subtype:"success",request_id:String(t),response:r}}}function C(t,e){const{detail:o}=L(t),n=w(e),s=n&&e.scope==="chat"?" for this chat":"";return`${n?"Allowed":"Declined"}${s}: ${o}`}function x(t){return t==="Bash"?"code":/^(Edit|MultiEdit|NotebookEdit)$/.test(String(t))?"pencil":t==="Write"?"file":/^mcp__/.test(String(t))?"plug":"bot"}function P({memory:t=new Map}={}){const e=t;async function o(n,{convId:s=null,confirm:r,agentName:c="The agent"}={}){const i=O(await e.get(s)||[],n);if(i)return i;const{title:f,detail:l,scope:d,description:y}=L(n),S=[l,y&&y!==l?y:"",d?`“Allow for this chat” also covers: ${d}`:""].filter(Boolean).join(`
2
- `);let m;try{if(typeof r!="function")throw new Error("no card");m=await r(S,{title:`${c} asks — ${f.toLowerCase()}?`,iconName:x(n.tool),scopeLabel:"Allow for this chat",allLabel:"Allow all in this chat"})}catch(A){return h(p.DENY,`Chap could not show the permission card (${A?.message||A}).`)}return m==="all"?(await e.set(s,[b]),h(p.ALLOW_CHAT)):m==="site"||m==="always"?(await e.set(s,E(await e.get(s)||[],n)),h(p.ALLOW_CHAT)):h(m==="allow"?p.ALLOW:p.DENY)}return{ask:o,forget(n){e.delete(n)},standing(n){return e.get(n)||[]},provider({convId:n=null,confirm:s,agentName:r="The agent"}={}){return{id:"permission",specs:[N()],execute:async(c,i)=>JSON.stringify(await o(i&&typeof i=="object"?i:{},{convId:n,confirm:s,agentName:r}))}}}}export{b as ALLOW_ALL,p as PERMISSION_ANSWERS,$ as PERMISSION_EVENT,W as PERMISSION_TIMEOUT_MS,_ as PERMISSION_TOOL_NAME,R as claudePermissionResponse,P as createPermissionDesk,L as describePermission,T as isPermissionTool,w as permissionAllowed,h as permissionAnswer,x as permissionIcon,g as permissionKeys,C as permissionLine,k as permissionRequestFromClaude,N as permissionToolSpec,O as recallPermission,E as rememberPermission};
1
+ const T="permission_request",u=Object.freeze({ALLOW:"allow",ALLOW_CHAT:"allow_chat",DENY:"deny"}),W=600*1e3,w="permission_prompt";function E(){return{name:w,description:"Chap-internal: the person answers the agent's permission prompt. Not for the model.",parameters:{type:"object",properties:{tool:{type:"string"},input:{type:"object"},description:{type:"string"},path:{type:"string"},rules:{type:"array"}}}}}const k=t=>t===w,p=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),a=t=>typeof t=="string"?t:t==null?"":String(t);function R(t={}){const e=p(t)?t:{},o=a(e.tool_name||e.toolName||e.tool),s=[];for(const n of Array.isArray(e.permission_suggestions)?e.permission_suggestions:[])if(!(!p(n)||n.type!=="addRules"||n.behavior==="deny"))for(const l of Array.isArray(n.rules)?n.rules:[]){if(!p(l))continue;const c=a(l.toolName||o),i=a(l.ruleContent);c&&!s.some(f=>f.tool===c&&f.content===i)&&s.push({tool:c,content:i})}return{tool:o,displayName:a(e.display_name||e.displayName)||o,input:p(e.input)?e.input:{},description:a(e.description),path:a(e.blocked_path||e.path)||null,rules:s,toolUseId:a(e.tool_use_id||e.toolUseId)||null}}function A(t={}){const e=Array.isArray(t.rules)?t.rules.filter(o=>o&&o.tool):[];return e.length?e.map(o=>o.content?`${o.tool}(${o.content})`:o.tool):t.tool?[String(t.tool)]:[]}function L(t={}){const e=a(t.tool),o=p(t.input)?t.input:{},s=(r,d=240)=>r.length>d?`${r.slice(0,d-1)}…`:r;let n,l;if(e==="Bash")n="Run a command",l=s(a(o.command).trim()||a(t.description)||"a shell command");else if(e==="Edit"||e==="MultiEdit"||e==="NotebookEdit")n="Edit a file",l=a(o.file_path||o.notebook_path||t.path)||"a file";else if(e==="Write"){n="Write a file";const r=a(o.file_path||t.path)||"a file",d=a(o.content).length;l=d?`${r} (${d.toLocaleString()} chars)`:r}else if(/^mcp__/.test(e))n="Use a connected server",l=e.replace(/^mcp__/,"").replace(/__/," › ");else{n=`Use ${t.displayName||e||"a tool"}`;let r="";try{r=JSON.stringify(o)}catch{r=""}l=a(t.description)||(r&&r!=="{}"?s(r,200):e)}const c=A(t),i=Array.isArray(t.rules)?t.rules.filter(r=>r?.content):[],f=i.length&&i.some(r=>r.content!==l)?i.map(r=>r.content).join(", "):c.length&&!i.length?`every ${e} call`:null,h=p(t.access)?a(t.access.folder):"",g=h?`This works in ${h}, outside the folders it may change. Allowing it opens ${h} to it for the rest of this chat.`:null;return{title:n,detail:l,scope:f,description:a(t.description)||null,access:g}}function m(t,e=""){return t===u.ALLOW?{behavior:"allow",scope:"once"}:t===u.ALLOW_CHAT?{behavior:"allow",scope:"chat"}:{behavior:"deny",scope:"once",...e?{message:String(e)}:{}}}function b(t){return p(t)&&t.behavior==="allow"}function O(t,e){const o=new Set(Array.isArray(t)?t:[]);for(const s of A(e))o.add(s);return[...o].sort()}const S="*";function x(t,e){const o=new Set(Array.isArray(t)?t:[]);if(o.has(S))return m(u.ALLOW);const s=A(e);return s.length&&s.every(n=>o.has(n))?m(u.ALLOW):null}function C(t,e,o={}){const s=p(o)?o:{},n=b(e);let l;if(n){if(l={behavior:"allow",updatedInput:p(s.input)?s.input:{}},e.scope==="chat"){const c=(Array.isArray(s.permission_suggestions)?s.permission_suggestions:[]).filter(i=>p(i)&&i.type==="addRules"&&i.behavior!=="deny"&&Array.isArray(i.rules)&&i.rules.length).map(i=>({type:"addRules",rules:i.rules,behavior:"allow",destination:"session"}));c.length&&(l.updatedPermissions=c)}}else l={behavior:"deny",message:a(e?.message)||"The user declined this action in Chap. Continue without it, or explain what it was for and ask."};return{type:"control_response",response:{subtype:"success",request_id:String(t),response:l}}}function P(t,e){const{detail:o}=L(t),s=b(e),n=s&&e.scope==="chat"?" for this chat":"";return`${s?"Allowed":"Declined"}${n}: ${o}`}function $(t){return t==="Bash"?"code":/^(Edit|MultiEdit|NotebookEdit)$/.test(String(t))?"pencil":t==="Write"?"file":/^mcp__/.test(String(t))?"plug":"bot"}function I({memory:t=new Map}={}){const e=t;async function o(s,{convId:n=null,confirm:l,agentName:c="The agent"}={}){const i=p(s.access)?null:x(await e.get(n)||[],s);if(i)return i;const{title:f,detail:h,scope:g,description:r,access:d}=L(s),N=[d,h,r&&r!==h?r:"",g?`“Allow for this chat” also covers: ${g}`:""].filter(Boolean).join(`
2
+ `);let y;try{if(typeof l!="function")throw new Error("no card");y=await l(N,{title:`${c} asks — ${f.toLowerCase()}?`,iconName:$(s.tool),scopeLabel:"Allow for this chat",allLabel:"Allow all in this chat"})}catch(_){return m(u.DENY,`Chap could not show the permission card (${_?.message||_}).`)}return y==="all"?(await e.set(n,[S]),m(u.ALLOW_CHAT)):y==="site"||y==="always"?(await e.set(n,O(await e.get(n)||[],s)),m(u.ALLOW_CHAT)):m(y==="allow"?u.ALLOW:u.DENY)}return{ask:o,forget(s){e.delete(s)},standing(s){return e.get(s)||[]},provider({convId:s=null,confirm:n,agentName:l="The agent"}={}){return{id:"permission",specs:[E()],execute:async(c,i)=>JSON.stringify(await o(i&&typeof i=="object"?i:{},{convId:s,confirm:n,agentName:l}))}}}}export{S as ALLOW_ALL,u as PERMISSION_ANSWERS,T as PERMISSION_EVENT,W as PERMISSION_TIMEOUT_MS,w as PERMISSION_TOOL_NAME,C as claudePermissionResponse,I as createPermissionDesk,L as describePermission,k as isPermissionTool,b as permissionAllowed,m as permissionAnswer,$ as permissionIcon,A as permissionKeys,P as permissionLine,R as permissionRequestFromClaude,E as permissionToolSpec,x as recallPermission,O as rememberPermission};