@chatpanel/bridge 0.21.1 → 0.27.2

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/README.md CHANGED
@@ -187,7 +187,7 @@ available; unsupported tool requests return HTTP 400, and usage counts are zero.
187
187
  workspace, credential or permission-mode option from the request body. The reply
188
188
  tells the user why.
189
189
  - **Pairing.** `chatpanel-bridge pair` prints a one-time code (5 minutes, 5 attempts).
190
- Enter it in ChatPanel → Settings → Agent Tools and that browser holds the token from then
190
+ Enter it in ChatPanel → Settings → Coding Agents and that browser holds the token from then
191
191
  on. A dev build can instead be pinned by id: `CHATPANEL_BRIDGE_EXTENSION_IDS=<id>`.
192
192
  Ask the bridge what it thinks of you with `POST /whoami` → `{ trust, paired }`.
193
193
  - Claude tools are **read-only by default** (Read/Grep/Glob/WebFetch). Writes and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.21.1",
3
+ "version": "0.27.2",
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 h,existsSync as i,mkdirSync as m}from"node:fs";import{fileURLToPath as d}from"node:url";import{dirname as f,join as n}from"node:path";const c=n(f(d(import.meta.url)),".."),v=["scopes.js","skill-manifest.js","skill-scan.js","ref.js","event.js","view.js","capability.js","reach.js","scm-connection.js","sandbox-policy.js","sandbox-grant.js","mcp-errors.js","mcp-signin.js","mcp-config-import.js","mcp-launcher.js","agent-permission.js"];function u(){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=u();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||m(l,{recursive:!0});const j=e=>`// GENERATED — do not edit.
2
+ import{readFileSync as r,writeFileSync as p,existsSync as i,mkdirSync as m}from"node:fs";import{fileURLToPath as j}from"node:url";import{dirname as h,join as n}from"node:path";const c=n(h(j(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","sandbox-grant.js","mcp-errors.js","registries.js","mcp-signin.js","mcp-config-import.js","toml-lite.js","frontmatter.js","skill-package.js","agent-portability.js","agent-dialects.js","agent-card.js","dialect-claude.js","dialect-codex.js","dialect-a2a.js","dialect-chatpanel.js","agent.js","team.js","engine.js","budget.js","mcp-args-env.js","mcp-launcher.js","agent-permission.js"];function v(){return[n(c,"node_modules","@chatpanel","events"),n(c,"..","chatpanel-events")].find(e=>i(n(e,"skill-manifest.js")))}const s=process.argv.includes("--check"),a=v();if(!a){const e="chatpanel-events not found (check out ../chatpanel-events).";s&&(console.error(`sync-events --check: ${e}`),process.exit(1)),console.warn(`sync-events: ${e} Leaving src/events as-is.`),process.exit(0)}const l=n(c,"src","events");s||m(l,{recursive:!0});const u=e=>`// GENERATED — do not edit.
3
3
  // Source of truth: chatpanel-events/${e} (npm @chatpanel/events).
4
4
  // Edit there, then run: npm run sync:events
5
5
  //
@@ -7,4 +7,4 @@ import{readFileSync as r,writeFileSync as h,existsSync as i,mkdirSync as m}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 p=0;for(const e of v){const o=j(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`),p+=1;continue}h(t,o),console.log(`sync-events: updated src/events/${e}`)}}s&&(p&&(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=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}p(t,o),console.log(`sync-events: updated src/events/${e}`)}}s&&(d&&(console.error("Run `npm run sync:events` and commit the result."),process.exit(1)),console.log("sync-events --check: src/events matches chatpanel-events ✓"));
@@ -0,0 +1,2 @@
1
+ import{readFile as S,writeFile as E,readdir as M,stat as N,realpath as k,mkdir as O,copyFile as H}from"node:fs/promises";import{createHash as _}from"node:crypto";import w from"node:os";import{isAbsolute as I,join as p,resolve as j,sep as g}from"node:path";import{agentDialects as y,importAgent as X,translateAgent as q}from"./events/agent-portability.js";import{scanSkill as G,admits as J}from"./events/skill-scan.js";const U=256*1024,C=400,B=3,K=new Set([".git",".svn",".hg",".cache","node_modules",".DS_Store"]);class F extends Error{constructor(e,n){super(n),this.name="AgentDefError",this.code=e}}const A=Object.freeze([{source:"chatpanel",label:"ChatPanel",segments:[".chatpanel","agents"],dialect:"chatpanel",writable:!0},{source:"claude",label:"Claude Code",segments:[".claude","agents"],dialect:"claude"},{source:"codex",label:"Codex",segments:[".codex","agents"],dialect:"codex"},{source:"agents-dir",label:"Shared (~/.agents)",segments:[".agents","agents"],dialect:""}]);function W(a){const e=String(a||"").trim();if(!e||!I(e))return[];const n=j(e);return A.map(s=>({dir:p(n,...s.segments),source:s.source,label:s.label,dialect:s.dialect,writable:!1,project:n}))}function Y(a=process.env,e=w.homedir(),n=[],s=""){const i=(Array.isArray(n)?n:[]).map(t=>String(t||"").trim()).filter(t=>t&&I(t)).slice(0,16);return[...W(s),...A.map(t=>({dir:p(e,...t.segments),source:t.source,label:t.label,dialect:t.dialect,writable:!!t.writable})),...i.map(t=>({dir:j(t),source:"external",label:"Custom folder",dialect:"",writable:!1}))]}async function L({roots:a=[],registry:e=y()}={}){const n=new Map,s=[],i=[];for(const t of a){let r;try{r=await k(t.dir)}catch{continue}await $(r,r,t,0,n,s,i,e)}return{index:n,quarantined:s,problems:i}}async function $(a,e,n,s,i,t,r,c){if(s>B||i.size>=C)return;const D=await M(a,{withFileTypes:!0}).catch(()=>[]);for(const d of D){if(i.size>=C)return;if(K.has(d.name))continue;const l=p(a,d.name);if(d.isDirectory()){await $(l,e,n,s+1,i,t,r,c);continue}if(!/\.(md|toml|json)$/i.test(d.name))continue;const o=await k(l).catch(()=>null);if(!o||o!==e&&!o.startsWith(e+g))continue;const f=await N(o).catch(()=>null);if(!f?.isFile()||f.size>U)continue;const b=await S(o,"utf8").catch(()=>null);if(b===null)continue;const x=l.slice(e.length+1).split(g).join("/"),R=d.name.replace(/\.(md|toml|json)$/i,""),v=`sha256-${_("sha256").update(b).digest("hex").slice(0,32)}`,u=X(b,{filename:l,name:R,source:n.source,hash:v,registry:c});if(!u.ok){u.dialect&&r.push({path:x,source:n.source,errors:u.errors});continue}const h=G({name:u.agent.name,prompt:u.agent.prompt,files:[]}),m={agent:{...u.agent,origin:{...u.agent.origin||{},id:x,source:n.source,hash:v,scanned:{verdict:h.verdict,scanner:h.scanner,findings:h.findings.length}}},dialect:u.dialect,source:n.source,label:n.label,dir:o.slice(0,o.lastIndexOf(g)),file:o,relPath:x,writable:!!n.writable,warnings:u.warnings};if(!J(h.verdict)){t.push({...m,scan:h});continue}i.has(m.agent.id)||i.set(m.agent.id,m)}}function ie(a){return[...a.values()].map(e=>({id:e.agent.id,name:e.agent.name,purpose:e.agent.purpose,dialect:e.dialect,source:e.source,label:e.label,path:e.relPath,writable:e.writable,engine:e.agent.engine,grants:e.agent.grants,skills:e.agent.skills,promptChars:String(e.agent.prompt||"").length,warnings:e.warnings,scanned:e.agent.origin?.scanned}))}function re(a,e){const n=a.get(String(e||""));return n?{agent:n.agent,dialect:n.dialect,source:n.source,path:n.relPath}:null}const P=[".chatpanel","exports.json"];async function T(a){const e=p(a,...P);try{return JSON.parse(await S(e,"utf8"))||{}}catch{return{}}}async function Q(a,e){const n=p(a,...P);await O(n.slice(0,n.lastIndexOf(g)),{recursive:!0}),await E(n,`${JSON.stringify(e,null,2)}
2
+ `,"utf8")}async function V({agent:a,to:e,home:n=w.homedir(),registry:s=y()}={}){const i=A.find(f=>f.dialect===e);if(!i)throw new F("TARGET",`nothing here writes ${e} definitions`);const t=q(a,e,{registry:s}),r=p(n,...i.segments),c=p(r,t.filename),d=(await T(n))[c],l=await S(c,"utf8").catch(()=>null),o=l!==null&&d&&d.hash===z(l);return{to:e,label:i.label,path:c,text:t.text,fidelity:t.fidelity,exists:l!==null,status:l===null?"new":o?"ours":"theirs"}}async function ce({agent:a,to:e,overwrite:n=!1,home:s=w.homedir(),registry:i=y()}={}){const t=await V({agent:a,to:e,home:s,registry:i});if(t.status==="theirs"&&!n)throw new F("NOT_OURS",`${t.path} was not written by ChatPanel, or has been edited since — it will not be overwritten without being asked`);const r=t.path.slice(0,t.path.lastIndexOf(g));await O(r,{recursive:!0}),t.exists&&await H(t.path,`${t.path}.bak.chatpanel`).catch(()=>{}),await E(t.path,t.text,"utf8");const c=await T(s);return c[t.path]={hash:z(t.text),at:new Date().toISOString(),agentId:a?.id||"",dialect:e},await Q(s,c),{ok:!0,path:t.path,to:e,backedUp:t.exists,fidelity:t.fidelity,status:t.status}}const z=a=>`sha256-${_("sha256").update(String(a)).digest("hex").slice(0,32)}`;async function oe(a=[],e=""){const n=Y(process.env,w.homedir(),a,e),{index:s,quarantined:i,problems:t}=await L({roots:n}),r=[...new Set([...s.values()].map(c=>c.source))];return{count:s.size,sources:r,...i.length?{quarantined:i.length}:{},...t.length?{problems:t.length}:{}}}export{A as AGENT_DEF_DIRS,F as AgentDefError,Y as agentDefRoots,oe as agentDefsHealth,ce as exportAgentDef,ie as listAgentDefs,V as planAgentExport,W as projectAgentRoots,re as readAgentDef,L as scanAgentDefs};
@@ -1,6 +1,6 @@
1
- import{spawn as F,spawnSync as z}from"node:child_process";import{writeFileSync as B,unlinkSync as R}from"node:fs";import"node:os";import C from"node:path";import{findAgentBin as D}from"../env.js";import{fitCliPrompt as U,argvPromptBudget as j}from"./prompt.js";import{summarizeCliError as G}from"../cli-errors.js";import{killOnAbort as H,spawnGroupOpts as J}from"../proc.js";import{track as K,sandbox as W,noteSandbox as Y}from"../sandbox.js";import{pushExtraArgs as Z,FORBIDDEN as q}from"./args.js";import{resolveWorkdir as Q}from"../workdir.js";const P=Number(process.env.CHATPANEL_AGY_TIMEOUT_MS)||18e4;async function mt(){try{const u=D("agy")||"agy",l=z(u,["models"],{encoding:"utf8",timeout:15e3}),o=[],a=new Set;for(const e of String(l.stdout||"").split(`
2
- `)){const n=e.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(n)&&!/^(name|model|models|id|provider|available)$/i.test(n)&&!a.has(n)&&(a.add(n),o.push(n),o.length>=100))break}return o}catch{return[]}}const L=()=>({started:new Set,finalText:""});function V(u,l,o=L()){const a=String(u||"").trim();if(!a)return{streamed:!1};let e;try{e=JSON.parse(a)}catch{return l({type:"delta",text:`${a}
3
- `}),{streamed:!0}}const n=e.event||e.type||"";if(n==="init")return l({type:"status",text:"Antigravity working"}),{streamed:!1};if(n==="result"){const s=e.result||{};return o.finalText=typeof s.response=="string"?s.response:"",s.status&&s.status!=="SUCCESS"&&l({type:"status",text:`Antigravity: ${s.status}`}),{streamed:!1}}if(n!=="step_update")return{streamed:!1};const r=e.step_update||{};if(r.step_type==="tool"){const s=`agy_${r.step_index??o.started.size}`,i=r.tool_info&&typeof r.tool_info=="object"?r.tool_info:{},d=r.tool_name||i.name||"tool";if(o.started.has(s)||(o.started.add(s),l({type:"tool",name:d,phase:"start",callId:s,input:i.parameters&&typeof i.parameters=="object"?i.parameters:{}})),r.state==="DONE"){const g=!!i.error||r.state==="ERROR",c=i.output==null?"":typeof i.output=="string"?i.output:JSON.stringify(i.output);l({type:"tool",name:d,phase:"done",callId:s,status:g?`error: ${String(i.error||"failed").slice(0,80)}`:"ok",result:String(g?i.error||"":c).slice(0,4e3)})}return{streamed:!1}}return r.step_type==="agent_response"&&typeof r.text_delta=="string"&&r.text_delta?(l({type:"delta",text:r.text_delta}),{streamed:!0}):{streamed:!1}}let x=!1,M=0;async function gt(){if(Date.now()-M>(x?3e4:4e3)){M=Date.now();try{x=!!D("agy")}catch{x=!1}}return x?{ok:!0}:{ok:!1,reason:"agy not found on PATH. Install Antigravity, then run `agy` once to sign in."}}function X(u,l){const o=[];for(let a=0;a<(u?.length||0);a++){const e=/^data:([^;]+);base64,(.+)$/s.exec(u[a]?.dataUrl||"");if(!e)continue;const n=(e[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",r=C.join(l,`chatpanel-img-${Date.now()}-${a}.${n}`);try{B(r,Buffer.from(e[2],"base64")),o.push(r)}catch{}}return o}async function yt({messages:u,system:l,options:o,images:a},e,{signal:n}={}){const r=Q(o.workingDir),s=X(a,r),i=()=>s.forEach(t=>{try{R(t)}catch{}}),d=U(u,l,j({otherArgsChars:400}));let g=d.prompt;d.dropped&&e({type:"status",text:`Antigravity takes the prompt as a command-line argument, which this system caps — the oldest ${d.dropped} turn${d.dropped===1?"":"s"} of this conversation were left out to fit.`}),s.length&&(g+=`
1
+ import{spawn as N,spawnSync as F}from"node:child_process";import{writeFileSync as z,unlinkSync as R}from"node:fs";import"node:os";import O from"node:path";import{agentAvailable as U,resolveCommand as j,buildSpawnSpec as B}from"../env.js";import{fitCliPrompt as G,argvPromptBudget as H}from"./prompt.js";import{summarizeCliError as J}from"../cli-errors.js";import{killOnAbort as K,spawnGroupOpts as W}from"../proc.js";import{track as Y,sandbox as Z,noteSandbox as q}from"../sandbox.js";import{pushExtraArgs as Q,FORBIDDEN as V}from"./args.js";import{resolveWorkdir as X}from"../workdir.js";const D=Number(process.env.CHATPANEL_AGY_TIMEOUT_MS)||18e4;async function yt(){try{const u=j("agy");if(!u)return[];const[a,n,i]=B(u,["models"],null),r=F(a,n,{...i,encoding:"utf8",timeout:15e3}),l=[],t=new Set;for(const s of String(r.stdout||"").split(`
2
+ `)){const o=s.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(o)&&!/^(name|model|models|id|provider|available)$/i.test(o)&&!t.has(o)&&(t.add(o),l.push(o),l.length>=100))break}return l}catch{return[]}}const P=()=>({started:new Set,finalText:""});function tt(u,a,n=P()){const i=String(u||"").trim();if(!i)return{streamed:!1};let r;try{r=JSON.parse(i)}catch{return a({type:"delta",text:`${i}
3
+ `}),{streamed:!0}}const l=r.event||r.type||"";if(l==="init")return a({type:"status",text:"Antigravity working"}),{streamed:!1};if(l==="result"){const s=r.result||{};return n.finalText=typeof s.response=="string"?s.response:"",s.status&&s.status!=="SUCCESS"&&a({type:"status",text:`Antigravity: ${s.status}`}),{streamed:!1}}if(l!=="step_update")return{streamed:!1};const t=r.step_update||{};if(t.step_type==="tool"){const s=`agy_${t.step_index??n.started.size}`,o=t.tool_info&&typeof t.tool_info=="object"?t.tool_info:{},d=t.tool_name||o.name||"tool";if(n.started.has(s)||(n.started.add(s),a({type:"tool",name:d,phase:"start",callId:s,input:o.parameters&&typeof o.parameters=="object"?o.parameters:{}})),t.state==="DONE"){const g=!!o.error||t.state==="ERROR",c=o.output==null?"":typeof o.output=="string"?o.output:JSON.stringify(o.output);a({type:"tool",name:d,phase:"done",callId:s,status:g?`error: ${String(o.error||"failed").slice(0,80)}`:"ok",result:String(g?o.error||"":c).slice(0,4e3)})}return{streamed:!1}}return t.step_type==="agent_response"&&typeof t.text_delta=="string"&&t.text_delta?(a({type:"delta",text:t.text_delta}),{streamed:!0}):{streamed:!1}}let x=!1,L=0;async function ht(){if(Date.now()-L>(x?3e4:4e3)){L=Date.now();try{x=U("agy")}catch{x=!1}}return x?{ok:!0}:{ok:!1,reason:"agy not found on PATH. Install Antigravity, then run `agy` once to sign in."}}function et(u,a){const n=[];for(let i=0;i<(u?.length||0);i++){const r=/^data:([^;]+);base64,(.+)$/s.exec(u[i]?.dataUrl||"");if(!r)continue;const l=(r[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",t=O.join(a,`chatpanel-img-${Date.now()}-${i}.${l}`);try{z(t,Buffer.from(r[2],"base64")),n.push(t)}catch{}}return n}async function wt({messages:u,system:a,options:n,images:i},r,{signal:l}={}){const t=X(n.workingDir),s=et(i,t),o=()=>s.forEach(e=>{try{R(e)}catch{}}),d=G(u,a,H({otherArgsChars:400}));let g=d.prompt;d.dropped&&r({type:"status",text:`Antigravity takes the prompt as a command-line argument, which this system caps — the oldest ${d.dropped} turn${d.dropped===1?"":"s"} of this conversation were left out to fit.`}),s.length&&(g+=`
4
4
 
5
- The user attached image(s): ${s.map(t=>"@"+C.basename(t)).join(" ")}`);const c=["-p",g];o.model&&c.push("--model",o.model),o.permissionMode==="bypassPermissions"&&c.push("--dangerously-skip-permissions"),Z(c,o.extraArgs,q.antigravity,e);const _=async t=>{const N=t?[...c,"--output-format","stream-json"]:c,y=await W().wrap("agy",N,{cwd:r,stdio:["ignore","pipe","pipe"],env:{...process.env,...o.runEnv||{}},...J},{engine:"antigravity",cwd:r});return Y(e,y.record),new Promise((k,b)=>{let f;try{f=K(F(y.bin,y.argv,y.opts),y,{kind:"agent"})}catch(p){return b(new Error(`Failed to start agy: ${p.message}`))}const $=H(f,n);let E="",T="",m="",v=!1;const I=L();let h;const S=()=>{clearTimeout(h),h=setTimeout(()=>{f.kill("SIGKILL"),b(new Error(`Antigravity timed out — no output for ${Math.round(P/1e3)}s.`))},P)};S();const O=p=>{V(p,e,I).streamed&&(v=!0)};f.stdout.on("data",p=>{S();const w=p.toString();if(E+=w,!t){v=!0,e({type:"delta",text:w});return}m+=w;let A;for(;(A=m.indexOf(`
6
- `))>=0;)O(m.slice(0,A)),m=m.slice(A+1)}),f.stderr.on("data",p=>{S(),T+=p.toString()}),f.on("error",p=>{clearTimeout(h),$(),b(new Error(`Failed to start agy: ${p.message}`))}),f.on("close",p=>{if(clearTimeout(h),$(),n?.aborted){k({code:0,aborted:!0});return}t&&m.trim()&&O(m),k({code:p,out:E,err:T,streamed:v,state:I})})})};try{let t=await _(!0);if(t.aborted||t.code!==0&&!t.streamed&&/output-format|unknown flag|flag provided but not defined/i.test(t.err)&&(e({type:"status",text:"This Antigravity CLI has no structured output; showing its text only. Update it with `agy update` to see tool activity."}),t=await _(!1),t.aborted))return;if(t.code!==0)throw new Error(G("Antigravity",t.code,t.err,t.out));t.streamed||e({type:"delta",text:(t.state?.finalText||t.out).trim()||"(no output)"}),e({type:"done",text:""})}finally{i()}}export{gt as available,yt as chat,V as forwardAgyLine,mt as listModels,L as newAgyState};
5
+ The user attached image(s): ${s.map(e=>"@"+O.basename(e)).join(" ")}`);const c=["-p",g];n.model&&c.push("--model",n.model),n.permissionMode==="bypassPermissions"&&c.push("--dangerously-skip-permissions"),Q(c,n.extraArgs,V.antigravity,r);const _=async e=>{const M=e?[...c,"--output-format","stream-json"]:c,y=await Z().wrap("agy",M,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,...n.runEnv||{}},...W},{engine:"antigravity",cwd:t});return q(r,y.record),new Promise((k,b)=>{let f;try{f=Y(N(y.bin,y.argv,y.opts),y,{kind:"agent"})}catch(p){return b(new Error(`Failed to start agy: ${p.message}`))}const $=K(f,l);let E="",T="",m="",v=!1;const I=P();let h;const S=()=>{clearTimeout(h),h=setTimeout(()=>{f.kill("SIGKILL"),b(new Error(`Antigravity timed out — no output for ${Math.round(D/1e3)}s.`))},D)};S();const C=p=>{tt(p,r,I).streamed&&(v=!0)};f.stdout.on("data",p=>{S();const w=p.toString();if(E+=w,!e){v=!0,r({type:"delta",text:w});return}m+=w;let A;for(;(A=m.indexOf(`
6
+ `))>=0;)C(m.slice(0,A)),m=m.slice(A+1)}),f.stderr.on("data",p=>{S(),T+=p.toString()}),f.on("error",p=>{clearTimeout(h),$(),b(new Error(`Failed to start agy: ${p.message}`))}),f.on("close",p=>{if(clearTimeout(h),$(),l?.aborted){k({code:0,aborted:!0});return}e&&m.trim()&&C(m),k({code:p,out:E,err:T,streamed:v,state:I})})})};try{let e=await _(!0);if(e.aborted||e.code!==0&&!e.streamed&&/output-format|unknown flag|flag provided but not defined/i.test(e.err)&&(r({type:"status",text:"This Antigravity CLI has no structured output; showing its text only. Update it with `agy update` to see tool activity."}),e=await _(!1),e.aborted))return;if(e.code!==0)throw new Error(J("Antigravity",e.code,e.err,e.out));e.streamed||r({type:"delta",text:(e.state?.finalText||e.out).trim()||"(no output)"}),r({type:"done",text:""})}finally{o()}}export{ht as available,wt as chat,tt as forwardAgyLine,yt as listModels,P as newAgyState};
@@ -1,4 +1,4 @@
1
- import{runSpec as h,listSpecModels as A,runForStdout as d,CHATPANEL_STABLE_MCP_URL as m}from"./custom.js";import{findAgentBin as b,selfMcpStdio as u}from"../env.js";function a(e,o,i,t={}){let r=!1,s=0;const n={...o,command:e};return{spec:n,async available(){if(Date.now()-s>(r?3e4:4e3)){s=Date.now();try{r=!!b(e)}catch{r=!1}}return r?{ok:!0}:{ok:!1,reason:i}},listModels(l={}){return t.listModels?t.listModels(e,l):A(e,o.listModelsArgs,l.workingDir)},chat(l,c,p){return h(n,l,c,p)}}}const H=a("pi",{args:"-p",promptVia:"stdin",modelArg:"--model {model}",imageArg:"@{path}",toolAdapter:"pi-extension",listModelsArgs:"--list-models",label:"Pi"},"pi not found on PATH. Install Pi, then run `pi` once to sign in."),D=a("opencode",{args:"run --format json --dangerously-skip-permissions",promptVia:"stdin",modelArg:"-m {model}",imageArg:"-f {path}",format:"opencode-json",requiresStableMcp:!0,stableMcpConfigCheck:"opencode",listModelsArgs:"models",label:"OpenCode"},"opencode not found on PATH. Install opencode, then sign in."),P=a("kiro-cli",{args:"chat --no-interactive --require-mcp-startup",promptVia:"stdin",modelArg:"--model {model}",trustAllToolsForMcp:!0,trustAllToolsArg:"--trust-all-tools",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"kiro",stableMcpSetupArgs:["mcp","add","--scope","global","--name","chatpanel_browser","--url","http://127.0.0.1:4319/mcp","--force"],stableMcpSetupCommand:"kiro-cli mcp add --scope global --name chatpanel_browser --url http://127.0.0.1:4319/mcp --force",listModelsArgs:"--list-models",label:"Kiro"},"kiro-cli not found on PATH. Install Kiro CLI, then sign in."),S=["--output-format","json","--no-color","--log-level","none","--no-ask-user","--no-auto-update","--no-remote","--no-remote-export"],_=a("copilot",{args:S,promptVia:"stdin",modelArg:"--model {model}",imageArg:"--attachment {path}",format:"copilot-json",mcpArg:"--additional-mcp-config @{file}",permissionArgs:{default:["--allow-all-tools"],acceptEdits:["--allow-all-tools","--allow-all-paths"],bypassPermissions:["--allow-all"]},forbidden:"copilot",label:"GitHub Copilot"},"copilot not found on PATH. Install GitHub Copilot CLI, then run `copilot login`.",{listModels:(e,o)=>M(e,o.workingDir)});async function M(e="copilot",o){const i=await d(e,["help","config"],o),t=[],r=new Set;let s=!1;for(const n of String(i||"").split(`
1
+ import{runSpec as h,listSpecModels as A,runForStdout as d,CHATPANEL_STABLE_MCP_URL as m}from"./custom.js";import{agentAvailable as b,selfMcpStdio as u}from"../env.js";function a(e,o,i,t={}){let r=!1,s=0;const n={...o,command:e};return{spec:n,async available(){if(Date.now()-s>(r?3e4:4e3)){s=Date.now();try{r=b(e)}catch{r=!1}}return r?{ok:!0}:{ok:!1,reason:i}},listModels(l={}){return t.listModels?t.listModels(e,l):A(e,o.listModelsArgs,l.workingDir)},chat(l,c,p){return h(n,l,c,p)}}}const H=a("pi",{args:"-p",promptVia:"stdin",modelArg:"--model {model}",imageArg:"@{path}",toolAdapter:"pi-extension",listModelsArgs:"--list-models",label:"Pi"},"pi not found on PATH. Install Pi, then run `pi` once to sign in."),D=a("opencode",{args:"run --format json --dangerously-skip-permissions",promptVia:"stdin",modelArg:"-m {model}",imageArg:"-f {path}",format:"opencode-json",requiresStableMcp:!0,stableMcpConfigCheck:"opencode",listModelsArgs:"models",label:"OpenCode"},"opencode not found on PATH. Install opencode, then sign in."),P=a("kiro-cli",{args:"chat --no-interactive --require-mcp-startup",promptVia:"stdin",modelArg:"--model {model}",trustAllToolsForMcp:!0,trustAllToolsArg:"--trust-all-tools",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"kiro",stableMcpSetupArgs:["mcp","add","--scope","global","--name","chatpanel_browser","--url","http://127.0.0.1:4319/mcp","--force"],stableMcpSetupCommand:"kiro-cli mcp add --scope global --name chatpanel_browser --url http://127.0.0.1:4319/mcp --force",listModelsArgs:"--list-models",label:"Kiro"},"kiro-cli not found on PATH. Install Kiro CLI, then sign in."),S=["--output-format","json","--no-color","--log-level","none","--no-ask-user","--no-auto-update","--no-remote","--no-remote-export"],_=a("copilot",{args:S,promptVia:"stdin",modelArg:"--model {model}",imageArg:"--attachment {path}",format:"copilot-json",mcpArg:"--additional-mcp-config @{file}",permissionArgs:{default:["--allow-all-tools"],acceptEdits:["--allow-all-tools","--allow-all-paths"],bypassPermissions:["--allow-all"]},forbidden:"copilot",label:"GitHub Copilot"},"copilot not found on PATH. Install GitHub Copilot CLI, then run `copilot login`.",{listModels:(e,o)=>M(e,o.workingDir)});async function M(e="copilot",o){const i=await d(e,["help","config"],o),t=[],r=new Set;let s=!1;for(const n of String(i||"").split(`
2
2
  `)){const l=/^\s*`([A-Za-z][\w.]*)`\s*:/.exec(n);if(l){s=l[1]==="model";continue}if(!s)continue;const c=/^\s*-\s*"([^"]+)"\s*$/.exec(n);if(!c)continue;const p=c[1];if(!r.has(p)&&(r.add(p),t.push(p),t.length>=200))break}return t.length?["auto",...t]:[]}const T=a("dsh",{args:["--profile","headless","{prompt}"],promptVia:"arg",format:"text",modelPatch:{arg:"--patch {file}",build:e=>`- id: ${g}
3
3
  config:
4
4
  provider: ${k}
@@ -1,4 +1,4 @@
1
- import{spawn as B}from"node:child_process";import{killOnAbort as H,spawnGroupOpts as F}from"../proc.js";import{track as L,sandbox as X,noteSandbox as J}from"../sandbox.js";import{readFile as R,unlink as M,writeFile as q}from"node:fs/promises";import{existsSync as N,mkdirSync as z,symlinkSync as W,readFileSync as O}from"node:fs";import S from"node:os";import m from"node:path";import{findAgentBin as G,selfMcpStdio as K,resolveCommand as U}from"../env.js";import{relayTimeoutMax as Z}from"../relay-timeout.js";import{buildCliPrompt as Q}from"./prompt.js";import{pushExtraArgs as V,FORBIDDEN as Y}from"./args.js";import{resolveWorkdir as ee}from"../workdir.js";import{summarizeCliError as te}from"../cli-errors.js";import{signInStatus as oe,signInMessage as re}from"../sign-in.js";import{disabledMcpServers as ne,planMcpRetry as se,quarantine as ae}from"../mcp-quarantine.js";import{chatWarm as ce}from"./codex-appserver.js";const j=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,D=process.env.CHATPANEL_CODEX_EFFORT??"low",ie=["gpt-5-codex","gpt-5","o3","o4-mini"];let C=!1;function Te(){C=!1}async function Pe(){const n=new Set;try{const r=process.env.CODEX_HOME||m.join(S.homedir(),".codex"),t=O(m.join(r,"config.toml"),"utf8");for(const a of t.matchAll(/(?:^|\n)\s*model\s*=\s*["']([^"'\n]+)["']/g))n.add(a[1].trim())}catch{}for(const r of ie)n.add(r);return[...n]}const I=m.join(S.homedir(),".chatpanel","codex-home");let T=!1;function le(){if(!T)try{z(I,{recursive:!0});const n=m.join(S.homedir(),".codex","auth.json"),r=m.join(I,"auth.json");if(N(n)&&!N(r))try{W(n,r)}catch{}T=!0}catch{return null}return I}let A=!1,P=0;async function Be(){if(Date.now()-P>(A?3e4:4e3)){P=Date.now();try{A=!!G("codex")}catch{A=!1}}return A?await oe("codex",U("codex")).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:re("Codex","codex")}:{ok:!0}:{ok:!1,reason:"codex not found on PATH. Install it and run `codex login`."}}function de(n){if(!n?.url)return[];const r=n.serverName||"chatpanel_browser",{command:t,args:a}=K(n.url),e=["-c",`mcp_servers.${r}.command=${JSON.stringify(t)}`,"-c",`mcp_servers.${r}.args=${JSON.stringify(a)}`,"-c",`mcp_servers.${r}.default_tools_approval_mode="approve"`,"-c",`mcp_servers.${r}.startup_timeout_sec=30`,"-c",`mcp_servers.${r}.tool_timeout_sec=${Math.ceil(Z(n.specs)/1e3)}`],s=[...new Set((n.specs||[]).map(i=>i?.name).filter(Boolean))];return s.length&&e.push("-c",`mcp_servers.${r}.enabled_tools=${JSON.stringify(s)}`),e}function pe(n){try{const r=O(m.join(n,"config.toml"),"utf8"),t=new Set;for(const a of r.matchAll(/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*[.\]]/gm))t.add(a[1]);return t}catch{return new Set}}function ue(n){const r=new Set;try{const t=O(m.join(n,"config.toml"),"utf8"),a=/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*\]\s*$([\s\S]*?)(?=^\s*\[|$(?![\r\n]))/gm;for(const e of t.matchAll(a)){const s=e[2]||"",i=/^\s*command\s*=\s*"([^"]*)"/m.exec(s)?.[1]||"",o=/^\s*url\s*=\s*"([^"]*)"/m.exec(s)?.[1]||"";(/chatpanel-(gateway|bridge)(\.js|\.cmd|\.exe)?$/.test(i)||/^https?:\/\/(127\.0\.0\.1|localhost):43(19|20)\//.test(o))&&r.add(e[1])}}catch{}return r}function fe(n=[]){return n.flatMap(r=>["-c",`mcp_servers.${r}.enabled=false`])}async function me(n,r){const t=[];for(let a=0;a<(n?.length||0);a++){const e=/^data:([^;]+);base64,(.+)$/s.exec(n[a]?.dataUrl||"");if(!e)continue;const s=(e[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",i=m.join(S.tmpdir(),`chatpanel-codex-img-${r}-${a}.${s}`);await q(i,Buffer.from(e[2],"base64")),t.push(i)}return t}async function he({args:n,cwd:r,env:t,prompt:a,outFile:e,emit:s,signal:i}){const o=await X().wrap("codex",n,{cwd:r,stdio:["pipe","pipe","pipe"],env:t,...F},{engine:"codex",cwd:r});return J(s,o.record),new Promise((c,f)=>{let l;try{l=L(B(o.bin,o.argv,o.opts),o,{kind:"agent"})}catch(u){return f(new Error(`Failed to start codex: ${u.message}`))}const g=H(l,i);let y="",b="",w=!1;const k=u=>{u?.type!=="status"&&(w=!0),s(u)},_={started:new Set,reasoned:new Set,n:0};let x;const $=()=>{clearTimeout(x),x=setTimeout(()=>{l.kill("SIGKILL"),f(new Error(`Codex timed out — no output for ${Math.round(j/1e3)}s.`))},j)};$(),l.stdout.on("data",u=>{$(),y+=u.toString();let h;for(;(h=y.indexOf(`
1
+ import{spawn as B}from"node:child_process";import{killOnAbort as H,spawnGroupOpts as F}from"../proc.js";import{track as L,sandbox as X,noteSandbox as J}from"../sandbox.js";import{readFile as R,unlink as M,writeFile as q}from"node:fs/promises";import{existsSync as N,mkdirSync as z,symlinkSync as W,readFileSync as O}from"node:fs";import S from"node:os";import m from"node:path";import{agentAvailable as G,selfMcpStdio as K,resolveCommand as U}from"../env.js";import{relayTimeoutMax as Z}from"../relay-timeout.js";import{buildCliPrompt as Q}from"./prompt.js";import{pushExtraArgs as V,FORBIDDEN as Y}from"./args.js";import{resolveWorkdir as ee}from"../workdir.js";import{summarizeCliError as te}from"../cli-errors.js";import{signInStatus as oe,signInMessage as re}from"../sign-in.js";import{disabledMcpServers as ne,planMcpRetry as se,quarantine as ae}from"../mcp-quarantine.js";import{chatWarm as ce}from"./codex-appserver.js";const j=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,D=process.env.CHATPANEL_CODEX_EFFORT??"low",ie=["gpt-5-codex","gpt-5","o3","o4-mini"];let C=!1;function Te(){C=!1}async function Pe(){const n=new Set;try{const r=process.env.CODEX_HOME||m.join(S.homedir(),".codex"),t=O(m.join(r,"config.toml"),"utf8");for(const a of t.matchAll(/(?:^|\n)\s*model\s*=\s*["']([^"'\n]+)["']/g))n.add(a[1].trim())}catch{}for(const r of ie)n.add(r);return[...n]}const I=m.join(S.homedir(),".chatpanel","codex-home");let T=!1;function le(){if(!T)try{z(I,{recursive:!0});const n=m.join(S.homedir(),".codex","auth.json"),r=m.join(I,"auth.json");if(N(n)&&!N(r))try{W(n,r)}catch{}T=!0}catch{return null}return I}let A=!1,P=0;async function Be(){if(Date.now()-P>(A?3e4:4e3)){P=Date.now();try{A=G("codex")}catch{A=!1}}return A?await oe("codex",U("codex")).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:re("Codex","codex")}:{ok:!0}:{ok:!1,reason:"codex not found on PATH. Install it and run `codex login`."}}function de(n){if(!n?.url)return[];const r=n.serverName||"chatpanel_browser",{command:t,args:a}=K(n.url),e=["-c",`mcp_servers.${r}.command=${JSON.stringify(t)}`,"-c",`mcp_servers.${r}.args=${JSON.stringify(a)}`,"-c",`mcp_servers.${r}.default_tools_approval_mode="approve"`,"-c",`mcp_servers.${r}.startup_timeout_sec=30`,"-c",`mcp_servers.${r}.tool_timeout_sec=${Math.ceil(Z(n.specs)/1e3)}`],s=[...new Set((n.specs||[]).map(i=>i?.name).filter(Boolean))];return s.length&&e.push("-c",`mcp_servers.${r}.enabled_tools=${JSON.stringify(s)}`),e}function pe(n){try{const r=O(m.join(n,"config.toml"),"utf8"),t=new Set;for(const a of r.matchAll(/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*[.\]]/gm))t.add(a[1]);return t}catch{return new Set}}function ue(n){const r=new Set;try{const t=O(m.join(n,"config.toml"),"utf8"),a=/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*\]\s*$([\s\S]*?)(?=^\s*\[|$(?![\r\n]))/gm;for(const e of t.matchAll(a)){const s=e[2]||"",i=/^\s*command\s*=\s*"([^"]*)"/m.exec(s)?.[1]||"",o=/^\s*url\s*=\s*"([^"]*)"/m.exec(s)?.[1]||"";(/chatpanel-(gateway|bridge)(\.js|\.cmd|\.exe)?$/.test(i)||/^https?:\/\/(127\.0\.0\.1|localhost):43(19|20)\//.test(o))&&r.add(e[1])}}catch{}return r}function fe(n=[]){return n.flatMap(r=>["-c",`mcp_servers.${r}.enabled=false`])}async function me(n,r){const t=[];for(let a=0;a<(n?.length||0);a++){const e=/^data:([^;]+);base64,(.+)$/s.exec(n[a]?.dataUrl||"");if(!e)continue;const s=(e[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",i=m.join(S.tmpdir(),`chatpanel-codex-img-${r}-${a}.${s}`);await q(i,Buffer.from(e[2],"base64")),t.push(i)}return t}async function he({args:n,cwd:r,env:t,prompt:a,outFile:e,emit:s,signal:i}){const o=await X().wrap("codex",n,{cwd:r,stdio:["pipe","pipe","pipe"],env:t,...F},{engine:"codex",cwd:r});return J(s,o.record),new Promise((c,f)=>{let l;try{l=L(B(o.bin,o.argv,o.opts),o,{kind:"agent"})}catch(u){return f(new Error(`Failed to start codex: ${u.message}`))}const g=H(l,i);let y="",b="",w=!1;const k=u=>{u?.type!=="status"&&(w=!0),s(u)},_={started:new Set,reasoned:new Set,n:0};let x;const $=()=>{clearTimeout(x),x=setTimeout(()=>{l.kill("SIGKILL"),f(new Error(`Codex timed out — no output for ${Math.round(j/1e3)}s.`))},j)};$(),l.stdout.on("data",u=>{$(),y+=u.toString();let h;for(;(h=y.indexOf(`
2
2
  `))>=0;){const v=y.slice(0,h).trim();if(y=y.slice(h+1),!!v.startsWith("{"))try{ye(JSON.parse(v),k,_)}catch{}}}),l.stderr.on("data",u=>{$(),b+=u.toString()}),l.on("error",u=>{clearTimeout(x),g(),f(u)}),l.on("close",async u=>{clearTimeout(x),g();let h="";try{h=(await R(e,"utf8")).trim()}catch{}M(e).catch(()=>{}),c({code:u,stderr:b,text:h,streamed:w,said:!!_.saidAny,policyBlocked:!!_.policyBlocked})}),l.stdin.write(a),l.stdin.end()})}async function He({messages:n,system:r,options:t,images:a},e,{signal:s}={}){const i=await ce({messages:n,system:r,options:t,images:a},e,{signal:s}).catch(o=>({handled:!1,reason:o?.message||String(o),thrown:!0}));if(!i.handled&&!s?.aborted){if(i.thrown)throw new Error(i.reason);return ge({messages:n,system:r,options:t,images:a},e,{signal:s})}}async function ge({messages:n,system:r,options:t,images:a},e,{signal:s}={}){const i=`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=m.join(S.tmpdir(),`chatpanel-codex-${i}.txt`),c=await me(a,i),f=()=>c.forEach(d=>M(d).catch(()=>{})),l=ee(t.workingDir),g=[];V(g,t.extraArgs,Y.codex,e);const y=d=>{const p=["exec","--json","--skip-git-repo-check","-o",o];if(t.permissionMode==="bypassPermissions")p.push("--dangerously-bypass-approvals-and-sandbox");else{const E=t.permissionMode==="acceptEdits"?"workspace-write":"read-only";p.push("-s",E),C||p.push("-c","approval_policy=never")}D&&p.push("-c",`model_reasoning_effort=${D}`),p.push("-c","model_reasoning_summary=auto"),p.push(...de(t.mcp)),p.push(...fe(d)),t.model&&p.push("-m",t.model),p.push(...g);for(const E of c)p.push("-i",E);return p.push("-"),p},b=t.useLocalConfig!==!1,w={...process.env,...t.runEnv||{}};if(!b){const d=le();d&&(w.CODEX_HOME=d)}const k=t.mcp?.serverName||"chatpanel_browser",_=w.CODEX_HOME||process.env.CODEX_HOME||m.join(S.homedir(),".codex"),x=pe(_),$=(t.mcp?.specs||[]).length>0;let u=[...new Set([...ne("codex",t,[k]),...$?ue(_):[]])].filter(d=>x.has(d));const h=Q(n,r),v=()=>he({args:y(u),cwd:l,env:w,prompt:h,outFile:o,emit:e,signal:s});try{let d=await v();if(d.policyBlocked&&(C=!0),!s?.aborted&&d.code!==0&&!d.streamed){const p=se({agent:"codex",text:d.stderr,protect:[k],already:u});p&&x.has(p.server)&&(ae("codex",p.server),e({type:"status",text:`MCP server "${p.server}" failed to load — ${p.short}. Skipping it and retrying.`}),u=[...u,p.server],d=await v())}if(s?.aborted)return;if(d.code!==0)throw new Error(te("Codex",d.code,d.stderr,"",{agentId:"codex"}));d.said||e({type:"delta",text:d.text||"(no output)"}),e({type:"done",text:""})}finally{f()}}function ye(n,r,t={started:new Set,reasoned:new Set,n:0}){const a=n.type||"",e=n.item||{},s=e.type||"",i=a==="item.completed"||e.status==="completed"||e.status==="failed";if(s==="agent_message"&&i){const o=e.id||`msg_${t.n++}`,c=String(e.text||"");c&&!t.said?.has(o)&&((t.said||=new Set).add(o),r({type:"delta",text:`${t.saidAny?`
3
3
 
4
4
  `:""}${c}`}),t.saidAny=!0);return}if(s==="command_execution"||!s&&a.includes("command")){const o=e.id||`cmd_${t.n++}`;if(t.started.has(o)||(t.started.add(o),r({type:"tool",name:"shell",phase:"start",callId:o,input:{command:e.command||""}})),i){const c=e.exit_code===0||e.exit_code==null;r({type:"tool",name:"shell",phase:"done",callId:o,status:c?"ok":`exit ${e.exit_code}`,result:String(e.aggregated_output||"").slice(0,4e3)})}return}if(s==="file_change"||!s&&a.includes("patch")){const o=e.id||`edit_${t.n++}`,c=Array.isArray(e.changes)?e.changes.map(f=>f.path||f.file).filter(Boolean):[];t.started.has(o)||(t.started.add(o),r({type:"tool",name:"edit",phase:"start",callId:o,input:{files:c}})),i&&r({type:"tool",name:"edit",phase:"done",callId:o,status:"ok"});return}if(s==="web_search"){const o=e.id||`ws_${t.n++}`,c=e.action&&typeof e.action=="object"?e.action:{},f=e.query||c.query||"",l=c.url||"";t.started.has(o)||(t.started.add(o),r({type:"tool",name:"web_search",phase:"start",callId:o,input:{query:f,...l?{url:l}:{}}})),(i||a==="item.completed")&&r({type:"tool",name:"web_search",phase:"done",callId:o,status:"ok",result:l?`Opened ${l}`:f?`Searched the web for ${f}`:"Searched the web"});return}if(s==="mcp_tool_call"){const o=e.id||`mcp_${t.n++}`,c=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(t.started.has(o)||(t.started.add(o),r({type:"tool",name:c,phase:"start",callId:o,input:e.arguments&&typeof e.arguments=="object"?e.arguments:{}})),i){const f=e.status==="failed"||e.error!=null,l=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error,g=e.result==null?"":typeof e.result=="string"?e.result:JSON.stringify(e.result);r({type:"tool",name:c,phase:"done",callId:o,status:f?`error: ${String(l||"failed").slice(0,80)}`:"ok",result:String(f?l||"":g).slice(0,4e3)})}return}if(s==="todo_list"&&Array.isArray(e.items)&&e.items.length){const o=e.items.map(c=>`${c.completed?"☑":"☐"} ${c.text||""}`).join(`
package/src/env.js CHANGED
@@ -1,3 +1,2 @@
1
- import d from"node:os";import{spawnGroupOpts as C}from"./proc.js";import c from"node:path";import{spawnSync as f}from"node:child_process";import{readdirSync as m,readFileSync as A,existsSync as u}from"node:fs";let g=!1,x=!1;const k=["codex","claude","agy","pi","opencode","kiro-cli","copilot","dsh"];function O(n){return j(process.env.PATH||"",process.platform).some(o=>o&&(u(c.join(o,n))||u(c.join(o,n+".exe"))))}function K(n){for(const e of $(n))if(u(e))return e;return E(n)||null}function P(){const n=c.basename(process.execPath).toLowerCase();return!(n.startsWith("node")||n.startsWith("bun"))}function pn(n){const e=["--mcp-stdio",n];if(P())return{command:process.execPath,args:e};const o=process.argv[1]||c.join(process.cwd(),"src","server.js"),t=process.env.CHATPANEL_BRIDGE_EMBEDDED==="1"?["--bridge"]:[];return{command:process.execPath,args:[o,...t,...e]}}function E(n){if(process.platform==="win32")return"";try{const e=process.env.SHELL||"/bin/zsh",t=(f(e,["-lc",`command -v ${n} 2>/dev/null`],{encoding:"utf8",timeout:4e3}).stdout||"").trim().split(`
2
- `).pop().trim();return t&&t.startsWith("/")?t:""}catch{return""}}function dn(){return process.env.CHATPANEL_CLAUDE_PATH?_(process.env.CHATPANEL_CLAUDE_PATH):_("claude")}function _(n){if(!n)return null;if(n.includes("/")||n.includes("\\")||/\.[a-z0-9]+$/i.test(n)){if(!u(n))return null;const t=c.extname(n).toLowerCase();return!P()&&/^\.(c?js|mjs)$/.test(t)?{kind:"script",script:n}:process.platform==="win32"&&(t===".cmd"||t===".bat")?{kind:"cmd",bin:n}:process.platform==="win32"&&t===""&&!D(n)?null:{kind:"native",bin:n}}if(process.platform==="win32"){const t=z(n);return t||(/^[\w.-]+$/.test(n)&&Z(n)?{kind:"wsl",command:n}:null)}const o=K(n);return o?{kind:"native",bin:o}:null}const F="HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",Y="HKCU\\Environment",B=4e3;let v=0;function V(n,e="Path"){const o=String(e).toLowerCase();for(const t of String(n||"").split(/\r?\n/)){const i=/^\s*(\S+)\s+REG_(?:EXPAND_)?SZ\s+(.*?)\s*$/.exec(t);if(i&&i[1].toLowerCase()===o)return i[2]}return""}function S(n,e=process.env){const o=new Map(Object.keys(e||{}).map(t=>[t.toLowerCase(),e[t]]));return String(n||"").replace(/%([^%]+)%/g,(t,i)=>{const r=o.get(String(i).toLowerCase());return r==null?t:String(r)})}function G(n,e){try{const o=c.win32.join(process.env.SystemRoot||"C:\\Windows","System32","reg.exe"),t=f(u(o)?o:"reg",["query",n,"/v",e],{encoding:"utf8",timeout:3e3,windowsHide:!0});return t.status===0?V(t.stdout,e):""}catch{return""}}function U({query:n=G,env:e=process.env}={}){const o=S(n(F,"Path"),e),t=S(n(Y,"Path"),e);return b([...j(o,"win32"),...j(t,"win32")])}function L({force:n=!1,now:e=Date.now(),registry:o=U,env:t=process.env,home:i=d.homedir()}={}){if(process.platform!=="win32"&&!n||!n&&e-v<B)return!1;v=e;const r=j(t.PATH||"","win32"),s=b([...r,...o({env:t}),...h(i,"win32",t)]);return s.length===r.length?!1:(t.PATH=s.join(T("win32")),!0)}function z(n){return y(n)||(L()?y(n):null)}function y(n){const e=w("win32");for(const o of $(n,d.homedir(),"win32",process.env)){if(!u(o))continue;const t=e.dirname(o),i=e.extname(o).toLowerCase(),r=n==="claude"&&Q(t)||q(t,n)||(/^\.(c?js|mjs)$/.test(i)?o:null);if(r){if(!P())return{kind:"script",script:r};const s=X(t);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===""&&D(o))return{kind:"native",bin:o}}return null}function X(n,{env:e=process.env,exists:o=u}={}){const t=c.win32,i=b([n,...j(e.PATH||"","win32"),...e.NVM_SYMLINK?[e.NVM_SYMLINK]:[],t.join(e.ProgramFiles||"C:\\Program Files","nodejs")]);for(const r of i){const s=t.join(r,"node.exe");if(o(s))return s}return null}function Q(n){const e=[["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 e){const t=c.join(n,...o);if(u(t))return t}return null}function q(n,e){for(const o of[`${e}.cmd`,e,`${e}.ps1`]){let t;try{t=A(c.join(n,o),"utf8")}catch{continue}const i=t.match(/(?:%~?dp0%|\$basedir|\$\{basedir\})[\\/]+([^"'\s]+\.[cm]?js)/i);if(i){const r=c.join(n,i[1].replace(/[\\/]+/g,c.sep));if(u(r))return r}}return null}const I=new Map,J=15e3;function Z(n){const e=I.get(n);if(e&&(e.ok||Date.now()-e.at<J))return e.ok;let o=!1;try{const t=f("wsl.exe",["-e","bash","-lic",`command -v ${n}`],{encoding:"utf8",timeout:8e3,windowsHide:!0});o=t.status===0&&/\S/.test(N(t.stdout||""))}catch{o=!1}return I.set(n,{ok:o,at:Date.now()}),o}function fn(n,e,o,t=null){const i=t&&typeof t=="object"&&Object.keys(t).length?{...process.env,...t}:process.env;if(n.kind==="wsl"){const s=[];if(o){const l=nn(o);l&&s.push("--cd",l)}return["wsl.exe",[...s,"-e","bash","-lic",`exec ${n.command} "$@"`,"chatpanel",...e],{stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...C}]}const r={cwd:o||d.homedir(),stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...C};return n.kind==="script"?[n.runtime||process.execPath,[n.script,...e],r]:n.kind==="cmd"?["cmd.exe",["/d","/s","/c",n.bin,...e],r]:[n.bin,e,r]}function nn(n){try{const e=f("wsl.exe",["-e","wslpath","-a",n],{encoding:"utf8",timeout:5e3,windowsHide:!0}),o=N(e.stdout||"").trim();return o.startsWith("/")?o:null}catch{return null}}function N(n){return n.replace(/^/,"").trim()}function tn(n=d.homedir(),e=process.env){const o=c.join(e.NVM_DIR||c.join(n,".nvm"),"versions","node");let t;try{t=m(o).filter(r=>/^v\d+\./.test(r))}catch{return null}if(!t.length)return null;const i=(r,s)=>{const a=r.slice(1).split(".").map(Number),l=s.slice(1).split(".").map(Number);for(let p=0;p<3;p+=1)if((a[p]||0)!==(l[p]||0))return(l[p]||0)-(a[p]||0);return 0};try{const r=A(c.join(e.NVM_DIR||c.join(n,".nvm"),"alias","default"),"utf8").trim(),s=r.startsWith("v")?r:`v${r}`;if(t.includes(s))return c.join(o,s,"bin")}catch{}return c.join(o,t.sort(i)[0],"bin")}function on(n){const e=[],o=(t,i)=>{try{for(const r of m(t))e.push(c.join(t,r,i))}catch{}};return o(c.join(process.env.NVM_DIR||c.join(n,".nvm"),"versions","node"),"bin"),o(c.join(n,".local","share","fnm","node-versions"),c.join("installation","bin")),o(c.join(n,"Library","Application Support","fnm","node-versions"),c.join("installation","bin")),e.push(c.join(n,".volta","bin")),e.push(c.join(n,".asdf","shims")),e}function w(n){return n==="win32"?c.win32:c}function T(n){return n==="win32"?";":c.delimiter}function j(n,e){return(n||"").split(T(e)).filter(Boolean)}function b(n){return[...new Set(n.filter(Boolean))]}function h(n,e=process.platform,o=process.env){const t=w(e);if(e==="win32"){const i=o.APPDATA||t.join(n,"AppData","Roaming"),r=o.LOCALAPPDATA||t.join(n,"AppData","Local"),s=o.ProgramFiles||"C:\\Program Files",a=o["ProgramFiles(x86)"]||"C:\\Program Files (x86)",l=o.ProgramData||"C:\\ProgramData";return[t.join(n,".local","bin"),t.join(n,".codex","bin"),t.join(n,".claude","bin"),t.join(n,".claude","local"),t.join(n,".claude","local","bin"),t.join(i,"npm"),...o.NVM_SYMLINK?[o.NVM_SYMLINK]:[],t.join(s,"nodejs"),...en(i,r),t.join(r,"pnpm"),t.join(r,"Yarn","bin"),t.join(r,"Volta","bin"),t.join(n,".yarn","bin"),t.join(n,".bun","bin"),t.join(n,".deno","bin"),t.join(n,"scoop","shims"),t.join(l,"chocolatey","bin"),t.join(r,"Microsoft","WindowsApps"),t.join(r,"Programs","Claude Code"),t.join(r,"Anthropic","Claude Code"),t.join(s,"Claude Code"),t.join(s,"Anthropic","Claude Code"),t.join(a,"Claude Code"),t.join(a,"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")]}function en(n,e){const o=c.win32,t=[];for(const i of[o.join(e,"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,a)=>a.localeCompare(s,void 0,{numeric:!0}))}catch{}for(const s of r)t.push(o.join(i,"node-versions",s,"installation"))}return t}function H(n,e=process.platform){const o=w(e),t=o.join(n,".local","share","claude","versions");let i=[];try{i=m(t).filter(r=>/^\d+\.\d+\.\d+/.test(r)).sort((r,s)=>s.localeCompare(r,void 0,{numeric:!0}))}catch{}return i.map(r=>o.join(t,r))}function M(n,e){return e!=="win32"?[n]:/\.(cmd|exe|bat|ps1)$/i.test(n)?[n]:[`${n}.exe`,`${n}.cmd`,`${n}.bat`,n,`${n}.ps1`]}function D(n,e=A){try{const o=e(n).subarray(0,2);return o.length===2&&o[0]===77&&o[1]===90}catch{return!1}}function rn(n,e=d.homedir(),o=process.platform,t=process.env){const i=w(o),r=i.join(e,".local","bin",n),s=o==="win32"?t.LOCALAPPDATA||i.join(e,"AppData","Local"):null,a=o==="win32"?t.ProgramFiles||"C:\\Program Files":null,l=o==="win32"?t["ProgramFiles(x86)"]||"C:\\Program Files (x86)":null,p={claude:[r,i.join(e,".claude","bin","claude"),i.join(e,".claude","local","claude"),i.join(e,".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(a,"Claude Code","claude.exe"),i.join(a,"Anthropic","Claude Code","claude.exe"),i.join(l,"Claude Code","claude.exe"),i.join(l,"Anthropic","Claude Code","claude.exe"),...H(e,o)]:H(e,o)],codex:[r,i.join(e,".codex","bin","codex")],agy:[r,"/Applications/Antigravity.app/Contents/MacOS/agy","/Applications/Antigravity IDE.app/Contents/MacOS/agy"],pi:[r],opencode:[i.join(e,".opencode","bin","opencode"),r],"kiro-cli":[r,"/Applications/Kiro CLI.app/Contents/MacOS/kiro-cli"]};return b((p[n]||[r]).flatMap(W=>M(W,o)))}function $(n,e=d.homedir(),o=process.platform,t=process.env){const i=w(o),r=b([...j(t.PATH||"",o),...h(e,o,t)]).flatMap(s=>M(i.join(s,n),o));return b([...r,...rn(n,e,o,t)])}const R=["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 jn(){if(x||(x=!0,process.platform==="win32"))return;const n=R.filter(e=>!process.env[e]);if(n.length)try{const e=process.env.SHELL||"/bin/zsh",o=`${n.map(i=>`[ -n "\${${i}:-}" ] && printf '%s\\t%s\\n' ${i} "$${i}"`).join("; ")}; true`,t=f(e,["-lic",o],{encoding:"utf8",timeout:6e3,env:{...process.env,TERM:"dumb"}});for(const i of String(t.stdout||"").split(`
3
- `)){const r=i.indexOf(" ");if(r<=0)continue;const s=i.slice(0,r).trim(),a=i.slice(r+1);R.includes(s)&&!process.env[s]&&a&&(process.env[s]=a)}}catch{}}function bn(){if(g)return;g=!0;const n=d.homedir();if(process.platform==="win32"){L({force:!0,home:n});return}const e=tn(n),o=[...e?[e]:[],"/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"),...h(n),...on(n)];let t="";try{const s=process.env.SHELL||"/bin/zsh",a=f(s,["-lc",'command -p echo "$PATH"'],{encoding:"utf8",timeout:4e3});a.status===0&&(t=(a.stdout||"").trim())}catch{}const i=new Set,r=[...e?[e]:[],...t?t.split(":"):[],...process.env.PATH?process.env.PATH.split(c.delimiter):[],...o].filter(s=>s&&!i.has(s)&&(i.add(s),!0));process.env.PATH=r.join(c.delimiter);for(const s of k){if(O(s))continue;const a=E(s);a&&(process.env.PATH=c.dirname(a)+c.delimiter+process.env.PATH)}}export{k as AGENT_CLIS,rn as agentCandidateBins,h as agentInstallDirs,fn as buildSpawnSpec,$ as commandCandidateFiles,jn as enrichAgentEnv,bn as enrichPath,S as expandWindowsEnv,K as findAgentBin,P as isCompiledBinary,D as isWindowsExecutable,X as nodeRuntimeWindows,tn as nvmCurrentBin,V as parseRegValue,L as refreshWindowsPath,U as registryPathWindows,dn as resolveClaude,_ as resolveCommand,pn as selfMcpStdio,nn as toWslPath};
1
+ import f from"node:os";import{spawnGroupOpts as O}from"./proc.js";import s from"node:path";import{spawnSync as b}from"node:child_process";import{readdirSync as h,readFileSync as _,existsSync as u}from"node:fs";let N=!1,y=!1;const D=["codex","claude","agy","pi","opencode","kiro-cli","copilot","dsh"];function J(n){return d(process.env.PATH||"",process.platform).some(o=>o&&(u(s.join(o,n))||u(s.join(o,n+".exe"))))}function Z(n){const t=R(n);if(t)return t;if(k()){const o=R(n);if(o)return o}return sn(n)||null}function Hn(n){return!!v(n)}function R(n){for(const t of q(n))if(u(t))return t;return null}function g(){const n=s.basename(process.execPath).toLowerCase();return!(n.startsWith("node")||n.startsWith("bun"))}function On(n){const t=["--mcp-stdio",n];if(g())return{command:process.execPath,args:t};const o=process.argv[1]||s.join(process.cwd(),"src","server.js"),i=process.env.CHATPANEL_BRIDGE_EMBEDDED==="1"?["--bridge"]:[];return{command:process.execPath,args:[o,...i,...t]}}const m="CHATPANEL_ENV",$=6e3;function x(n){for(const t of String(n||"").split(/\r?\n/)){const o=t.indexOf(" ");if(o>0&&t.slice(0,o).trim().endsWith(m))return t.slice(o+1).trim()}return""}function nn(n){return/^[\w.+-]+$/.test(String(n||""))}function E(){if(process.env.SHELL)return process.env.SHELL;try{const{shell:n}=f.userInfo();if(n&&n!=="/usr/bin/false"&&n!=="/sbin/nologin")return n}catch{}return"/bin/sh"}function W(n,{interactive:t}={}){if(process.platform==="win32")return"";try{const o=t?["-l","-i","-c"]:["-l","-c"];return b(E(),[...o,n],{encoding:"utf8",timeout:$,stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}}).stdout||""}catch{return""}}function tn(n){let t="";for(const o of String(n||"").split(/\r?\n/))o.startsWith("PATH=")&&(t=o.slice(5).trim());return t}function on({interactive:n=!0,ask:t=W}={}){const o=x(t(`command -p printf '%s\\t%s\\n' ${m} "$PATH"`,{interactive:n}));return d(o||tn(t("/usr/bin/env",{interactive:n})),process.platform)}const C=1e4,en=3e5;let S=0,P=C;function k({force:n=!1,now:t=Date.now(),read:o=on,env:i=process.env}={}){if(process.platform==="win32"||!n&&t-S<P)return!1;S=t;const e=d(i.PATH||"",process.platform),r=L(j([...o({interactive:!0}),...e])),c=r.length>e.length;return P=c?C:Math.min(P*2,en),c?(i.PATH=r.join(s.delimiter),!0):!1}function Nn(){S=0,P=C,T.clear()}const T=new Map,rn=15e3;function sn(n){if(process.platform==="win32"||!nn(n))return"";const t=T.get(n);if(t&&(t.bin||Date.now()-t.at<rn))return t.bin;const o=[`command -p printf '%s\\t%s\\n' ${m} "$(command -v ${n} 2>/dev/null)"`,`type -p ${n}`];let i="";for(const e of[!1,!0]){for(const r of o){const c=W(r,{interactive:e}),l=x(c)||String(c||"").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.startsWith("/")).pop()||"";if(l.startsWith("/")&&u(l)){i=l;break}}if(i)break}return T.set(n,{bin:i,at:Date.now()}),i}function yn(){return process.env.CHATPANEL_CLAUDE_PATH?v(process.env.CHATPANEL_CLAUDE_PATH):v("claude")}function v(n){if(!n)return null;if(n.includes("/")||n.includes("\\")||/\.[a-z0-9]+$/i.test(n)){if(!u(n))return null;const i=s.extname(n).toLowerCase();return!g()&&/^\.(c?js|mjs)$/.test(i)?{kind:"script",script:n}:process.platform==="win32"&&(i===".cmd"||i===".bat")?{kind:"cmd",bin:n}:process.platform==="win32"&&i===""&&!Q(n)?null:{kind:"native",bin:n}}if(process.platform==="win32"){const i=bn(n);return i||(/^[\w.-]+$/.test(n)&&Pn(n)?{kind:"wsl",command:n}:null)}const o=Z(n);return o?{kind:"native",bin:o}:null}const cn="HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",ln="HKCU\\Environment",an=4e3;let V=0;function un(n,t="Path"){const o=String(t).toLowerCase();for(const i of String(n||"").split(/\r?\n/)){const e=/^\s*(\S+)\s+REG_(?:EXPAND_)?SZ\s+(.*?)\s*$/.exec(i);if(e&&e[1].toLowerCase()===o)return e[2]}return""}function B(n,t=process.env){const o=new Map(Object.keys(t||{}).map(i=>[i.toLowerCase(),t[i]]));return String(n||"").replace(/%([^%]+)%/g,(i,e)=>{const r=o.get(String(e).toLowerCase());return r==null?i:String(r)})}function pn(n,t){try{const o=s.win32.join(process.env.SystemRoot||"C:\\Windows","System32","reg.exe"),i=b(u(o)?o:"reg",["query",n,"/v",t],{encoding:"utf8",timeout:3e3,windowsHide:!0});return i.status===0?un(i.stdout,t):""}catch{return""}}function dn({query:n=pn,env:t=process.env}={}){const o=B(n(cn,"Path"),t),i=B(n(ln,"Path"),t);return j([...d(o,"win32"),...d(i,"win32")])}function fn({run:n=jn}={}){const t=n(`[Console]::Out.Write("${m}\`t" + $env:PATH + "\`n")`);return d(x(t),"win32")}function jn(n){for(const t of["pwsh.exe","powershell.exe"])try{const o=b(t,["-NoLogo","-NonInteractive","-ExecutionPolicy","Bypass","-Command",n],{encoding:"utf8",timeout:$,stdio:["ignore","pipe","ignore"],windowsHide:!0}),i=M(o.stdout||"");if(i)return i}catch{}return""}function F({force:n=!1,now:t=Date.now(),registry:o=dn,profile:i=fn,env:e=process.env,home:r=f.homedir()}={}){if(process.platform!=="win32"&&!n||!n&&t-V<an)return!1;V=t;const c=d(e.PATH||"","win32"),l=j([...c,...o({env:e}),...H(r,"win32",e)]);D.some(p=>!l.some(A=>u(s.win32.join(A,`${p}.cmd`))||u(s.win32.join(A,`${p}.exe`))))&&l.push(...i());const a=L(j(l),"win32");return a.length===c.length?!1:(e.PATH=a.join(I("win32")),!0)}function bn(n){return K(n)||(F()?K(n):null)}function K(n){const t=w("win32");for(const o of q(n,f.homedir(),"win32",process.env)){if(!u(o))continue;const i=t.dirname(o),e=t.extname(o).toLowerCase(),r=n==="claude"&&An(i)||hn(i,n)||(/^\.(c?js|mjs)$/.test(e)?o:null);if(r){if(!g())return{kind:"script",script:r};const c=wn(i);if(c)return{kind:"script",script:r,runtime:c}}if(e===".exe")return{kind:"native",bin:o};if(e===".cmd"||e===".bat")return{kind:"cmd",bin:o};if(e===""&&Q(o))return{kind:"native",bin:o}}return null}function wn(n,{env:t=process.env,exists:o=u}={}){const i=s.win32,e=j([n,...d(t.PATH||"","win32"),...t.NVM_SYMLINK?[t.NVM_SYMLINK]:[],i.join(t.ProgramFiles||"C:\\Program Files","nodejs")]);for(const r of e){const c=i.join(r,"node.exe");if(o(c))return c}return null}function An(n){const t=[["node_modules","@anthropic-ai","claude-code","cli.js"],["..","node_modules","@anthropic-ai","claude-code","cli.js"],["..","lib","node_modules","@anthropic-ai","claude-code","cli.js"]];for(const o of t){const i=s.join(n,...o);if(u(i))return i}return null}function hn(n,t){for(const o of[`${t}.cmd`,t,`${t}.ps1`]){let i;try{i=_(s.join(n,o),"utf8")}catch{continue}const e=i.match(/(?:%~?dp0%|\$basedir|\$\{basedir\})[\\/]+([^"'\s]+\.[cm]?js)/i);if(e){const r=s.join(n,e[1].replace(/[\\/]+/g,s.sep));if(u(r))return r}}return null}const Y=new Map,mn=15e3;function Pn(n){const t=Y.get(n);if(t&&(t.ok||Date.now()-t.at<mn))return t.ok;let o=!1;try{const i=b("wsl.exe",["-e","bash","-lic",`command -v ${n}`],{encoding:"utf8",timeout:8e3,windowsHide:!0});o=i.status===0&&/\S/.test(M(i.stdout||""))}catch{o=!1}return Y.set(n,{ok:o,at:Date.now()}),o}function Dn(n,t,o,i=null){const e=i&&typeof i=="object"&&Object.keys(i).length?{...process.env,...i}:process.env;if(n.kind==="wsl"){const c=[];if(o){const a=_n(o);a&&c.push("--cd",a)}return["wsl.exe",[...c,"-e","bash","-lic",`exec ${n.command} "$@"`,"chatpanel",...t],{stdio:["pipe","pipe","pipe"],env:e,windowsHide:!0,...O}]}const r={cwd:o||f.homedir(),stdio:["pipe","pipe","pipe"],env:e,windowsHide:!0,...O};return n.kind==="script"?[n.runtime||process.execPath,[n.script,...t],r]:n.kind==="cmd"?["cmd.exe",["/d","/s","/c",n.bin,...t],r]:[n.bin,t,r]}function _n(n){try{const t=b("wsl.exe",["-e","wslpath","-a",n],{encoding:"utf8",timeout:5e3,windowsHide:!0}),o=M(t.stdout||"").trim();return o.startsWith("/")?o:null}catch{return null}}function M(n){return n.replace(/^/,"").trim()}function gn(n=f.homedir(),t=process.env){const o=s.join(t.NVM_DIR||s.join(n,".nvm"),"versions","node");let i;try{i=h(o).filter(r=>/^v\d+\./.test(r))}catch{return null}if(!i.length)return null;const e=(r,c)=>{const l=r.slice(1).split(".").map(Number),a=c.slice(1).split(".").map(Number);for(let p=0;p<3;p+=1)if((l[p]||0)!==(a[p]||0))return(a[p]||0)-(l[p]||0);return 0};try{const r=_(s.join(t.NVM_DIR||s.join(n,".nvm"),"alias","default"),"utf8").trim(),c=r.startsWith("v")?r:`v${r}`;if(i.includes(c))return s.join(o,c,"bin")}catch{}return s.join(o,i.sort(e)[0],"bin")}function xn(n,t=process.env){return[s.join(t.MISE_DATA_DIR||s.join(n,".local","share","mise"),"shims"),s.join(n,".local","share","rtx","shims"),s.join(t.ASDF_DATA_DIR||s.join(n,".asdf"),"shims"),s.join(t.PYENV_ROOT||s.join(n,".pyenv"),"shims"),s.join(t.RBENV_ROOT||s.join(n,".rbenv"),"shims"),s.join(t.NODENV_ROOT||s.join(n,".nodenv"),"shims"),s.join(t.PROTO_HOME||s.join(n,".proto"),"shims"),s.join(t.PROTO_HOME||s.join(n,".proto"),"bin"),s.join(t.VOLTA_HOME||s.join(n,".volta"),"bin")]}function En(n,t=process.env){const o=[],i=(e,r)=>{try{for(const c of h(e))o.push(s.join(e,c,r))}catch{}};return i(s.join(t.NVM_DIR||s.join(n,".nvm"),"versions","node"),"bin"),i(s.join(n,".local","share","fnm","node-versions"),s.join("installation","bin")),i(s.join(n,"Library","Application Support","fnm","node-versions"),s.join("installation","bin")),i(s.join(t.MISE_DATA_DIR||s.join(n,".local","share","mise"),"installs","node"),"bin"),o}function w(n){return n==="win32"?s.win32:s}function I(n){return n==="win32"?";":s.delimiter}function d(n,t){return(n||"").split(I(t)).filter(Boolean)}function j(n){return[...new Set(n.filter(Boolean))]}const G={win32:3e4,other:65536};function L(n,t=process.platform){const o=t==="win32"?G.win32:G.other,i=I(t),e=[];let r=0;for(const c of n){const l=c.length+(e.length?i.length:0);if(r+l>o)break;e.push(c),r+=l}return e}function H(n,t=process.platform,o=process.env){const i=w(t);if(t==="win32"){const e=o.APPDATA||i.join(n,"AppData","Roaming"),r=o.LOCALAPPDATA||i.join(n,"AppData","Local"),c=o.ProgramFiles||"C:\\Program Files",l=o["ProgramFiles(x86)"]||"C:\\Program Files (x86)",a=o.ProgramData||"C:\\ProgramData";return[i.join(n,".local","bin"),i.join(n,".codex","bin"),i.join(n,".claude","bin"),i.join(n,".claude","local"),i.join(n,".claude","local","bin"),i.join(e,"npm"),...o.NVM_SYMLINK?[o.NVM_SYMLINK]:[],i.join(c,"nodejs"),...Cn(e,r),i.join(r,"pnpm"),i.join(r,"Yarn","bin"),i.join(r,"Volta","bin"),i.join(n,".yarn","bin"),i.join(n,".bun","bin"),i.join(n,".deno","bin"),i.join(o.SCOOP||i.join(n,"scoop"),"shims"),i.join(a,"chocolatey","bin"),i.join(r,"Microsoft","WindowsApps"),i.join(r,"Microsoft","WinGet","Links"),i.join(o.MISE_DATA_DIR||i.join(r,"mise"),"shims"),i.join(o.PROTO_HOME||i.join(n,".proto"),"shims"),i.join(o.PROTO_HOME||i.join(n,".proto"),"bin"),i.join(r,"Programs","Claude Code"),i.join(r,"Anthropic","Claude Code"),i.join(c,"Claude Code"),i.join(c,"Anthropic","Claude Code"),i.join(l,"Claude Code"),i.join(l,"Anthropic","Claude Code")]}return[s.join(n,".local","bin"),s.join(n,".opencode","bin"),s.join(n,".codex","bin"),s.join(n,".claude","bin"),s.join(n,".claude","local"),s.join(n,".claude","local","bin"),o.PNPM_HOME||s.join(n,"Library","pnpm"),s.join(n,".local","share","pnpm"),s.join(n,".nix-profile","bin"),"/nix/var/nix/profiles/default/bin",s.join(n,".guix-profile","bin"),"/home/linuxbrew/.linuxbrew/bin","/snap/bin",...xn(n,o)]}function Cn(n,t){const o=s.win32,i=[];for(const e of[o.join(t,"fnm"),o.join(n,"fnm")]){let r=[];try{r=h(o.join(e,"node-versions")).filter(c=>/^v?\d+\.\d+\.\d+/.test(c)).sort((c,l)=>l.localeCompare(c,void 0,{numeric:!0}))}catch{}for(const c of r)i.push(o.join(e,"node-versions",c,"installation"))}return i}function U(n,t=process.platform){const o=w(t),i=o.join(n,".local","share","claude","versions");let e=[];try{e=h(i).filter(r=>/^\d+\.\d+\.\d+/.test(r)).sort((r,c)=>c.localeCompare(r,void 0,{numeric:!0}))}catch{}return e.map(r=>o.join(i,r))}function X(n,t){return t!=="win32"?[n]:/\.(cmd|exe|bat|ps1)$/i.test(n)?[n]:[`${n}.exe`,`${n}.cmd`,`${n}.bat`,n,`${n}.ps1`]}function Q(n,t=_){try{const o=t(n).subarray(0,2);return o.length===2&&o[0]===77&&o[1]===90}catch{return!1}}function Sn(n,t=f.homedir(),o=process.platform,i=process.env){const e=w(o),r=e.join(t,".local","bin",n),c=o==="win32"?i.LOCALAPPDATA||e.join(t,"AppData","Local"):null,l=o==="win32"?i.ProgramFiles||"C:\\Program Files":null,a=o==="win32"?i["ProgramFiles(x86)"]||"C:\\Program Files (x86)":null,p={claude:[r,e.join(t,".claude","bin","claude"),e.join(t,".claude","local","claude"),e.join(t,".claude","local","bin","claude"),...o==="win32"?[e.join(c,"Microsoft","WindowsApps","claude.exe"),e.join(c,"Programs","Claude Code","claude.exe"),e.join(c,"Anthropic","Claude Code","claude.exe"),e.join(l,"Claude Code","claude.exe"),e.join(l,"Anthropic","Claude Code","claude.exe"),e.join(a,"Claude Code","claude.exe"),e.join(a,"Anthropic","Claude Code","claude.exe"),...U(t,o)]:U(t,o)],codex:[r,e.join(t,".codex","bin","codex")],agy:[r,"/Applications/Antigravity.app/Contents/MacOS/agy","/Applications/Antigravity IDE.app/Contents/MacOS/agy"],pi:[r],opencode:[e.join(t,".opencode","bin","opencode"),r],"kiro-cli":[r,"/Applications/Kiro CLI.app/Contents/MacOS/kiro-cli"]};return j((p[n]||[r]).flatMap(A=>X(A,o)))}function q(n,t=f.homedir(),o=process.platform,i=process.env){const e=w(o),r=j([...d(i.PATH||"",o),...H(t,o,i)]).flatMap(c=>X(e.join(c,n),o));return j([...r,...Sn(n,t,o,i)])}const z=["DEEPSEEK_API_KEY","DSH_HOME","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","GEMINI_API_KEY","GOOGLE_API_KEY","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"];function Rn(){if(y||(y=!0,process.platform==="win32"))return;const n=z.filter(t=>!process.env[t]);if(n.length)try{const t=E(),o=`${n.map(e=>`[ -n "\${${e}:-}" ] && printf '%s\\t%s\\n' ${e} "$${e}"`).join("; ")}; true`,i=b(t,["-l","-i","-c",o],{encoding:"utf8",timeout:6e3,env:{...process.env,TERM:"dumb"}});for(const e of String(i.stdout||"").split(`
2
+ `)){const r=e.indexOf(" ");if(r<=0)continue;const c=e.slice(0,r).trim(),l=e.slice(r+1);z.includes(c)&&!process.env[c]&&l&&(process.env[c]=l)}}catch{}}function $n(){if(N)return;N=!0;const n=f.homedir();if(process.platform==="win32"){F({force:!0,home:n});return}const t=gn(n),o=[...t?[t]:[],"/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",s.join(n,".local","bin"),s.join(n,"bin"),s.join(n,".npm-global","bin"),s.join(n,".cargo","bin"),s.join(n,".deno","bin"),s.join(n,".bun","bin"),...H(n),...En(n)];let i="";try{const c=E(),l=b(c,["-l","-c",'command -p echo "$PATH"'],{encoding:"utf8",timeout:4e3});l.status===0&&(i=(l.stdout||"").trim())}catch{}const e=new Set,r=[...t?[t]:[],...i?i.split(":"):[],...process.env.PATH?process.env.PATH.split(s.delimiter):[],...o].filter(c=>c&&!e.has(c)&&(e.add(c),!0));process.env.PATH=L(r).join(s.delimiter),D.some(c=>!J(c))&&k({force:!0})}export{D as AGENT_CLIS,Hn as agentAvailable,Sn as agentCandidateBins,H as agentInstallDirs,Dn as buildSpawnSpec,L as capPathList,q as commandCandidateFiles,Rn as enrichAgentEnv,$n as enrichPath,B as expandWindowsEnv,Z as findAgentBin,g as isCompiledBinary,Q as isWindowsExecutable,wn as nodeRuntimeWindows,gn as nvmCurrentBin,tn as parseEnvPath,un as parseRegValue,x as parseSentinel,fn as profilePathWindows,k as refreshShellPath,F as refreshWindowsPath,dn as registryPathWindows,Nn as resetShellProbes,yn as resolveClaude,v as resolveCommand,On as selfMcpStdio,on as shellPath,_n as toWslPath};
@@ -0,0 +1 @@
1
+ class f extends Error{constructor(e,r){super(r),this.name="AgentCardError",this.code=e}}const P="/.well-known/agent-card.json",g="1.0",y=Object.freeze(["0.3","1.0"]),k=Object.freeze(["JSONRPC","GRPC","HTTP+JSON"]),A=Object.freeze(["text/plain"]),j=Object.freeze(["name","description","supportedInterfaces","provider","version","documentationUrl","capabilities","securitySchemes","securityRequirements","defaultInputModes","defaultOutputModes","skills","signatures","iconUrl"]),M=Object.freeze(["id","name","description","tags","examples","inputModes","outputModes","securityRequirements"]),z=Object.freeze(["url","preferredTransport","additionalInterfaces","protocolVersion","supportsAuthenticatedExtendedCard","security"]),n=t=>typeof t=="string"?t.trim():"",l=t=>Array.isArray(t)?t.filter(e=>e!=null):[],p=t=>[...new Set(l(t).map(n).filter(Boolean))],d=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:null;function L(t){const e=d(t);return e?Array.isArray(e.supportedInterfaces)?"1.0":n(e.url)||n(e.preferredTransport)||Array.isArray(e.additionalInterfaces)?"0.3":g:g}const O=Object.freeze({"0.3":t=>{const e=n(t.url)?[{url:n(t.url),protocolBinding:n(t.preferredTransport)||"JSONRPC",protocolVersion:"0.3"}]:[],r=l(t.additionalInterfaces).map(s=>({url:n(s?.url),protocolBinding:n(s?.transport)||n(s?.protocolBinding)||"JSONRPC",protocolVersion:n(s?.protocolVersion)||"0.3"})).filter(s=>s.url),o=d(t.capabilities)||{};return{...t,supportedInterfaces:C([...e,...r]),capabilities:{...o,...t.supportsAuthenticatedExtendedCard!==void 0?{extendedAgentCard:!!t.supportsAuthenticatedExtendedCard}:{}},...t.security!==void 0?{securityRequirements:t.security}:{}}}});function $(t){let e=d(t)?{...t}:{},r=L(e),o=0;for(;r!==g&&O[r];){e=O[r](e);const s=y[y.indexOf(r)+1];if(!s||(o+=1)>y.length)break;r=s}return e}function x(t){const e=$(t),r=d(e.capabilities)||{},o=new Set([...j,...z,"extras"]),s={...d(e.extras)||{}};for(const[i,m]of Object.entries(e))o.has(i)||(s[i]=m);const a={name:n(e.name),description:n(e.description),version:n(e.version),supportedInterfaces:C(l(e.supportedInterfaces).map(T).filter(i=>i.url)),capabilities:{streaming:!!r.streaming,pushNotifications:!!r.pushNotifications,extendedAgentCard:!!r.extendedAgentCard,extensions:l(r.extensions).map(U).filter(i=>i.uri),...b(r,["streaming","pushNotifications","extendedAgentCard","extensions"])},defaultInputModes:p(e.defaultInputModes).length?p(e.defaultInputModes):[...A],defaultOutputModes:p(e.defaultOutputModes).length?p(e.defaultOutputModes):[...A],skills:l(e.skills).map(_).filter(i=>i.id)},u=d(e.provider);u&&(n(u.organization)||n(u.url))&&(a.provider={organization:n(u.organization),url:n(u.url)}),n(e.documentationUrl)&&(a.documentationUrl=n(e.documentationUrl)),n(e.iconUrl)&&(a.iconUrl=n(e.iconUrl));const c=d(e.securitySchemes);c&&Object.keys(c).length&&(a.securitySchemes=c),l(e.securityRequirements).length&&(a.securityRequirements=l(e.securityRequirements));const S=l(e.signatures).filter(i=>d(i)&&n(i.protected)&&n(i.signature));return S.length&&(a.signatures=S.map(i=>({protected:n(i.protected),signature:n(i.signature),...d(i.header)?{header:i.header}:{}}))),Object.keys(s).length&&(a.extras=s),a}function T(t){const e=d(t)||{},r={url:n(e.url),protocolBinding:n(e.protocolBinding)||n(e.transport)||"JSONRPC",protocolVersion:n(e.protocolVersion)||g};return n(e.tenant)&&(r.tenant=n(e.tenant)),r}function C(t){const e=new Set,r=[];for(const o of t){const s=`${o.url}\0${o.protocolBinding}\0${o.protocolVersion}`;e.has(s)||(e.add(s),r.push(o))}return r}function U(t){const e=d(t)||{},r={uri:n(e.uri),required:!!e.required};return n(e.description)&&(r.description=n(e.description)),d(e.params)&&(r.params=e.params),r}function _(t){const e=d(t)||{},r={id:n(e.id),name:n(e.name)||n(e.id),description:n(e.description),tags:p(e.tags)};p(e.examples).length&&(r.examples=p(e.examples)),p(e.inputModes).length&&(r.inputModes=p(e.inputModes)),p(e.outputModes).length&&(r.outputModes=p(e.outputModes)),l(e.securityRequirements).length&&(r.securityRequirements=l(e.securityRequirements));const o={...d(e.extras)||{},...b(e,[...M,"extras"])};return Object.keys(o).length&&(r.extras=o),r}function b(t,e){const r={},o=new Set(e);for(const[s,a]of Object.entries(t||{}))o.has(s)||(r[s]=a);return r}function V(t){const e=x(t);if(!e.name)throw new f("NAME","an agent card needs a name");if(!e.description)throw new f("DESCRIPTION","an agent card needs a description");if(!e.version)throw new f("VERSION",`${e.name}: an agent card needs a version`);if(!e.supportedInterfaces.length)throw new f("INTERFACES",`${e.name}: an agent card needs at least one supported interface — an agent nobody can reach cannot be published`);for(const r of e.supportedInterfaces)if(!/^[a-z][a-z0-9+.-]*:\/\//i.test(r.url)&&!/^[\w.-]+:\d+$/.test(r.url))throw new f("INTERFACE_URL",`${e.name}: "${r.url}" is neither an absolute URL nor a host:port`);if(!e.skills.length)throw new f("SKILLS",`${e.name}: an agent card names what it can do — it has no skills`);for(const r of e.skills){if(!r.id)throw new f("SKILL_ID",`${e.name}: a skill needs an id`);if(!r.description)throw new f("SKILL_DESCRIPTION",`${e.name}: skill "${r.id}" needs a description`)}return e}function B(t,e=g){const r=x(t),{extras:o,...s}=r,a={...s,...o||{},skills:r.skills.map(({extras:h,...N})=>({...N,...h||{}}))};if(e!=="0.3")return a;const[u,...c]=r.supportedInterfaces,{supportedInterfaces:S,capabilities:i,securityRequirements:m,...R}=a,{extendedAgentCard:E,...w}=i;return{...R,protocolVersion:"0.3",...u?{url:u.url,preferredTransport:u.protocolBinding}:{},...c.length?{additionalInterfaces:c.map(h=>({url:h.url,transport:h.protocolBinding}))}:{},capabilities:w,...E?{supportsAuthenticatedExtendedCard:!0}:{},...m?{security:m}:{}}}function D(t,{bindings:e=k,version:r=g}={}){const o=x(t),s=new Set(e.map(c=>String(c).toUpperCase())),a=String(r).split(".")[0],u=o.supportedInterfaces.filter(c=>s.has(c.protocolBinding.toUpperCase()));return u.find(c=>c.protocolVersion===r)??u.find(c=>String(c.protocolVersion).split(".")[0]===a)??u[0]??null}function K(t){const e=I(x(t));let r=2166136261;for(let o=0;o<e.length;o++)r^=e.charCodeAt(o),r=Math.imul(r,16777619)>>>0;return r.toString(16).padStart(8,"0")}function I(t){return Array.isArray(t)?`[${t.map(I).join(",")}]`:t&&typeof t=="object"?`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${I(t[e])}`).join(",")}}`:JSON.stringify(t??null)}export{g as A2A_VERSION,P as AGENT_CARD_WELL_KNOWN,f as AgentCardError,y as CARD_PROFILES,O as CARD_UPCASTERS,k as KNOWN_BINDINGS,K as cardFingerprint,L as cardProfile,B as cardToProfile,x as normalizeCard,_ as normalizeCardSkill,D as preferredInterface,$ as upcastCard,V as validateCard};
@@ -0,0 +1 @@
1
+ class c extends Error{constructor(e,r){super(r),this.name="AgentDialectError",this.code=e}}const f=Object.freeze(["id","name","purpose","prompt","engine","grants","skills","mcpServers","workdir","tools","denyTools","permissionMode","sandboxMode","effort","maxTurns","memoryScope","isolation","color","background","hooks","provider","version","iconUrl","documentationUrl","tags","examples","inputModes","outputModes"]);function g({id:t,label:e,filename:r,detect:o,parse:s,render:i,carries:n=[],notes:a={}}){if(!t||typeof t!="string")throw new c("ID","a dialect needs an id");if(typeof s!="function"||typeof i!="function")throw new c("SHAPE",`${t}: a dialect needs both parse and render — a format we can read and not write is a trap`);const l=n.filter(d=>!f.includes(d));if(l.length)throw new c("CARRIES",`${t}: not portable fields: ${l.join(", ")}`);return Object.freeze({id:t,label:e||t,filename:typeof r=="function"?r:d=>`${d?.id||"agent"}.txt`,detect:typeof o=="function"?o:()=>0,parse:s,render:i,carries:Object.freeze([...new Set(n)]),notes:Object.freeze({...a})})}function S(){const t=new Map;return{register(e){if(!e?.id)throw new c("SHAPE","register a dialect made by defineAgentDialect");return t.set(e.id,e),e},get(e){return t.get(String(e||""))||null},list(){return[...t.values()]},has(e){return t.has(String(e||""))},detect(e,{filename:r=""}={}){let o=null,s=0;for(const i of t.values()){let n=0;try{n=Number(i.detect(String(e??""),{filename:String(r||"")}))||0}catch{n=0}n>s&&(s=n,o=i)}return s>0?{dialect:o,confidence:s}:{dialect:null,confidence:0}},parse(e,{id:r="",filename:o="",name:s=""}={}){const i=r?this.get(r):this.detect(e,{filename:o}).dialect;if(!i)throw new c("UNKNOWN","nothing here reads like an agent definition");const n=i.parse(String(e??""),{name:String(s||"")})||{};return{dialect:i.id,form:n.form||{},extras:n.extras||{},warnings:n.warnings||[]}},render(e,r){const o=this.get(r);if(!o)throw new c("UNKNOWN",`no dialect called "${r}"`);return{dialect:o.id,filename:o.filename(e),text:o.render(e),fidelity:h(e,o)}}}}function h(t,e){if(!e?.carries)throw new c("SHAPE","fidelity needs a dialect");const r=new Set(e.carries),o=w(t),s=[],i=[];for(const n of f)o.has(n)&&(r.has(n)?s.push(n):i.push({field:n,why:e.notes[n]||`${e.label} has no equivalent`}));return{dialect:e.id,carried:s,dropped:i,lossless:i.length===0}}function w(t){const e=new Set;for(const r of f)u(t?.[r])&&e.add(r);for(const r of Object.values(t?.dialectExtras||{}))for(const[o,s]of Object.entries(r||{}))f.includes(o)&&u(s)&&e.add(o);return t?.memoryScope&&t.memoryScope===`agent:${t.id}`&&e.delete("memoryScope"),e}function u(t){return t==null||t===""?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}const m=Object.freeze({bash:"shell",shell:"shell",run:"shell",terminal:"shell",execute:"shell",write:"fs:write",edit:"fs:write",multiedit:"fs:write",notebookedit:"fs:write",apply_patch:"fs:write",webfetch:"web",websearch:"web",web_search:"web",browser:"web",fetch:"web"}),b=Object.freeze(["read","grep","glob","ls","todowrite","task","view","search"]);function y(t){const e=p(t),r=new Set,o=new Set,s=[];for(const i of e){const n=i.toLowerCase(),a=/^mcp__([^_]+(?:_[^_]+)*?)__/.exec(n)||/^mcp:(.+)$/.exec(n);if(a){o.add(a[1]),r.add(`mcp:${a[1]}`);continue}if(n==="mcp"||n==="*"){r.add("mcp");continue}if(b.includes(n))continue;const l=m[n];l?r.add(l):s.push(i)}return{grants:[...r],mcpServers:[...o],unmapped:s}}function x(t,{dialect:e="claude"}={}){const r=new Set(p(t)),o=[],s=e==="claude";r.has("shell")&&o.push(s?"Bash":"shell"),r.has("fs:write")&&o.push(...s?["Write","Edit"]:["write"]),r.has("web")&&o.push(...s?["WebFetch","WebSearch"]:["web_search"]);for(const i of r){const n=/^mcp:(.+)$/.exec(i);n&&o.push(s?`mcp__${n[1]}__*`:`mcp:${n[1]}`)}return o}function p(t){return Array.isArray(t)?t.map(e=>String(e??"").trim()).filter(Boolean):typeof t=="string"?t.split(/[,\n]+/).map(e=>e.trim()).filter(Boolean):[]}export{c as AgentDialectError,b as IMPLIED_TOOLS,f as PORTABLE_FIELDS,m as TOOL_GRANTS,S as createDialectRegistry,g as defineAgentDialect,h as fidelity,y as grantsFromTools,p as toNameList,x as toolsFromGrants};
@@ -0,0 +1 @@
1
+ import{createDialectRegistry as p,fidelity as u}from"./agent-dialects.js";import{claudeDialect as x}from"./dialect-claude.js";import{codexDialect as D}from"./dialect-codex.js";import{a2aDialect as b}from"./dialect-a2a.js";import{chatpanelDialect as k}from"./dialect-chatpanel.js";import{agentFromForm as w,slugAgentId as y}from"./agent.js";const A=Object.freeze([k,x,D,b]);let n=null;function l(){if(!n){n=p();for(const t of A)n.register(t)}return n}function F(t,{dialect:a="",filename:i="",name:r="",source:c="",hash:s="",registry:f=l()}={}){let e;try{e=f.parse(t,{id:a,filename:i,name:r})}catch(g){return{ok:!1,dialect:"",errors:[g?.message||"unreadable"],warnings:[]}}const d=String(e.form.id||"").trim()||y(e.form.name||r||"agent"),m={...e.form,id:d,createdBy:e.dialect,...c?{origin:{source:c,id:i||d,...s?{hash:s}:{}}}:{},...Object.keys(e.extras).length?{dialectExtras:{...e.form.dialectExtras||{},[e.dialect]:e.extras}}:{}},o=w(m);return o.ok?{ok:!0,dialect:e.dialect,agent:o.agent,warnings:e.warnings}:{ok:!1,dialect:e.dialect,errors:o.errors,warnings:e.warnings}}function L(t,a,{registry:i=l()}={}){return i.render(t,a)}function O(t,{registry:a=l(),exclude:i=[]}={}){return a.list().filter(r=>!i.includes(r.id)).map(r=>({id:r.id,label:r.label,filename:r.filename(t),...u(t,r)}))}export{A as BUILT_IN_DIALECTS,l as agentDialects,O as exportTargets,F as importAgent,L as translateAgent};
@@ -0,0 +1,3 @@
1
+ import{normalizeGrants as k,GRANT_RE as E,TeamError as A,normalizeTeam as R,slugTeamName as I}from"./team.js";import{normalizeEngineSpec as u,validateEngineSpec as N,describeEngine as O,engineRef as $,tierOf as z}from"./engine.js";const B=/^[a-z][a-z0-9_-]{0,63}$/i,m=Object.freeze(["jobs","meetings","notes"]),g=Object.freeze(["redacted","delegated"]),j=32,f="assistant";class _ extends Error{constructor(r,t){super(t),this.name="AgentError",this.code=r}}const p=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),d=(e,r,t)=>[...new Set((Array.isArray(e)?e:typeof e=="string"?e.split(/[,\s]+/):[]).map(s=>String(s||"").trim().slice(0,r)).filter(Boolean))].slice(0,t);function S(e){const r=[];if(!p(e))return{ok:!1,errors:["agent must be an object"]};B.test(String(e.id||""))||r.push("id: a short identifier (letters, digits, _ -)"),String(e.name||e.id||"").trim()||r.push("name: what to call it"),!String(e.prompt||"").trim()&&String(e.id)!==f&&r.push("prompt: what this agent does"),r.push(...N(e.engine,"engine"));const t=(Array.isArray(e.grants)?e.grants:[]).filter(s=>!E.test(String(s)));return t.length&&r.push(`grants: not grantable: ${t.join(", ")}${t.some(s=>/^page/.test(String(s)))?" (a tab is one person's; an agent may not act on it)":""}`),e.egress!==void 0&&e.egress!==null&&!g.includes(e.egress)&&r.push(`egress: one of ${g.join(", ")}`),e.appliesTo!==void 0&&(!Array.isArray(e.appliesTo)||e.appliesTo.some(s=>!m.includes(s)))&&r.push(`appliesTo: a list of ${m.join(", ")}`),e.skills!==void 0&&!Array.isArray(e.skills)&&typeof e.skills!="string"&&r.push("skills: a list of skill names"),{ok:r.length===0,errors:r}}function b(e,{builtin:r=!1}={}){const t=S(e);if(!t.ok)throw new _("INVALID",t.errors.join("; "));const s=String(e.id);return{id:s,name:String(e.name||s).trim().slice(0,60),purpose:String(e.purpose||"").trim().slice(0,300),prompt:String(e.prompt||"").trim().slice(0,8e3),skills:d(e.skills,80,j),grants:k(e.grants),engine:u(e.engine),...g.includes(e.egress)?{egress:e.egress}:{},appliesTo:Array.isArray(e.appliesTo)&&e.appliesTo.length?[...new Set(e.appliesTo.filter(i=>m.includes(i)))]:["jobs"],memoryScope:String(e.memoryScope||"").trim().slice(0,120)||`agent:${s}`,...e.workdir?{workdir:String(e.workdir).trim().slice(0,400)}:{},createdBy:String(e.createdBy||"person").slice(0,80),enabled:e.enabled!==!1,...e.origin&&p(e.origin)?{origin:{...e.origin}}:{},...Y(e),...r?{builtin:!0}:{},...e.createdAt?{createdAt:e.createdAt}:{}}}function Y(e){const r={},t=(s,i)=>String(s||"").trim().slice(0,i);t(e.version,40)&&(r.version=t(e.version,40)),t(e.iconUrl,400)&&(r.iconUrl=t(e.iconUrl,400)),t(e.documentationUrl,400)&&(r.documentationUrl=t(e.documentationUrl,400)),p(e.provider)&&(e.provider.organization||e.provider.url)&&(r.provider={organization:t(e.provider.organization,120),url:t(e.provider.url,400)});for(const s of["tags","examples","inputModes","outputModes"]){const i=d(e[s],120,24);i.length&&(r[s]=i)}return p(e.dialectExtras)&&Object.keys(e.dialectExtras).length&&(r.dialectExtras={...e.dialectExtras}),r}function D(e,r){return Object.freeze(b(e,r))}function P({grants:e=["data","web","history","mcp"]}={}){return D({id:f,name:"Assistant",purpose:"The chat itself: answers, uses the tools you connected, remembers what you tell it.",prompt:"",engine:"assistant",grants:e,appliesTo:["jobs","meetings","notes"],createdBy:"chatpanel"},{builtin:!0})}function U(e,{chatModel:r=null}={}){const t=e||{};if(t.engine!==void 0&&t.engine!==null){const i=u(t.engine);return i.kind!=="assistant"?i:r?u(typeof r=="string"?r:{kind:"model",providerId:r.providerId,model:r.model||r.id}):{kind:"auto",policy:{prefer:"balanced"}}}return t.model?u({kind:"model",model:t.model}):{kind:"auto",policy:{prefer:{cheap:"cheapest-that-clears",strong:"best-quality",balanced:"balanced"}[t.prefer]||"balanced"}}}function q(e){const r=e||{};return r.origin&&p(r.origin)&&r.origin.source?"community":r.builtin?"built-in":"user"}function C(e,r){const t=e||{};return`${t.name||t.id} — ${O(t.engine,r)} · tools: ${(t.grants||["none"]).join(", ")}${t.skills?.length?` · skills: ${t.skills.join(", ")}`:""}`}function L(e){return I(e)}function J(e,r=[],{chatModel:t=null,targetFor:s=null}={}){const i=R(e),c=new Map((Array.isArray(r)?r:[]).filter(n=>n&&n.id).map(n=>[String(n.id),n])),a={},T=i.roles.map(n=>{if(!n.agent)return n;const h=c.get(n.agent)||(n.agent===f?P():null);if(!h)throw new A("NO_AGENT",`role "${n.id}" names agent "${n.agent}", which is not in the pool`);const o=b(h,{builtin:!!h.builtin});if(o.enabled===!1)throw new A("NO_AGENT",`agent "${o.id}" is disabled`);a[n.id]=o;const l=U(n.engine?{engine:n.engine}:o,{chatModel:t}),y=$(l)?s?s(l,o):l.kind==="harness"?l.harnessId:l.model:null,v=Array.isArray(n.grants)?o.grants.includes("none")?["none"]:k(n.grants.filter(w=>o.grants.includes(w)||w.startsWith("mcp:")&&o.grants.includes("mcp"))):o.grants,x=[o.prompt,n.prompt?`In this team: ${n.prompt}`:""].filter(Boolean).join(`
2
+
3
+ `).slice(0,8e3);return{...n,name:n.name===n.id?o.name:n.name,prompt:x,grants:v,engine:l,prefer:l.kind==="auto"?z(l):n.prefer,...y?{model:n.model||y}:{},...o.skills.length?{skills:[...o.skills]}:{},...o.workdir?{workdir:o.workdir}:{},...o.egress?{egress:o.egress}:{},...o.memoryScope?{memoryScope:o.memoryScope}:{}}});return{...i,roles:T,agents:a}}const G=Object.freeze([{id:"executive",name:"Executive",purpose:"Runs a project: posts the jobs for the goal, recruits from the pool, reads the results, posts follow-ups, asks before spending or changing scope, closes when done-when holds.",prompt:"You are the Executive. You hold one goal and its done-when. Break the goal into jobs a stranger could act on, each naming the skills and tools it needs; prefer jobs that run at the same time and use dependsOn only when one truly needs another's result. Read every result against done-when as written — say it holds only when it does on the results as they are, not as they could be. Post follow-up jobs only for what would move done-when. Say plainly what was not found. You never do a job yourself and never create an agent, tool or skill without a person's approval.",skills:["planning","management"],grants:["none"],engine:{kind:"auto",policy:{prefer:"best-quality"}},appliesTo:["jobs"]},{id:"architect",name:"Architect",purpose:"Reads the docs and the repos; writes the project page and the jobs.",prompt:"You are the Architect. Read the feature doc, ROADMAP.md, naming-revamp.md and architecture-pillars.md before deciding anything. Write the project page (goal, done-when, budget) and post one job per repo that must change, saying which repo and what the guard is. Propose a new agent type only when no one in the pool fits. Never run a shell.",skills:[],grants:["data","history"],engine:{kind:"auto",policy:{prefer:"best-quality"}},appliesTo:["jobs"]},{id:"implementer",name:"Implementer",purpose:"Builds one job on a branch in one repo; runs the guard; posts on the thread. Never pushes to main, never publishes.",prompt:"You are an Implementer. Work only in the repository you were given, on the branch named for this job. Read the job thread first. Make the change, run the repository's guard (tools/test-*.mjs or npm test) until it passes, commit with a message that says what and why, and post a summary with the diff stat on the job thread. Do not push to main, do not publish, do not touch another repository.",skills:[],grants:["shell","fs:write","scm:read","scm:push","scm:pr"],engine:{kind:"harness",harnessId:"claude"},appliesTo:["jobs"]},{id:"reviewer",name:"Reviewer",purpose:"Reads the branch diff; posts findings on the thread. Approve or reject is a person's.",prompt:"You are the Reviewer. Read the diff of the job's branch against its base. Post each finding as a reply on the job thread: what, where (file:line), why it matters, what to do instead. Do not edit files. Do not approve or reject — say what you found and let a person decide.",skills:["review"],grants:["shell","scm:read"],engine:{kind:"harness",harnessId:"claude"},appliesTo:["jobs"]},{id:"tester",name:"Tester",purpose:"Runs the repository's guard on the branch; reports the result. No writes.",prompt:"You are the Tester. Check out the job's branch in its worktree and run the repository's guard (tools/test-*.mjs, npm test, the build). Report pass/fail with the failing output verbatim. Do not change any file.",skills:[],grants:["shell","scm:read"],engine:{kind:"harness",harnessId:"claude"},appliesTo:["jobs"]},{id:"librarian",name:"Librarian",purpose:"Before every job: what was already done for this, and where.",prompt:'You are the Librarian. Before a job starts, search the runs, boards, briefs and docs for work that already covers it. Reply on the job thread with "already done in …" pointers and what could be reused or extended. Never do the job yourself.',skills:[],grants:["data","history"],engine:{kind:"auto",policy:{prefer:"cheapest-that-clears"}},appliesTo:["jobs"]},{id:"scribe",name:"Scribe",purpose:"Writes what the run taught into the roadmap and the status row — proposed, a person lands it.",prompt:`You are the Scribe. From the run's board and scorecards, write the "what this run taught" paragraph for the feature doc, the ROADMAP.md entry and the IMPLEMENTATION-STATUS.md row. Post them as a proposal on the thread; a person lands them. Say plainly what did not work.`,skills:[],grants:["data","history"],engine:{kind:"auto",policy:{prefer:"balanced"}},appliesTo:["jobs","notes"]},{id:"release",name:"Release",purpose:"Version bump and changelog on the merged branch; asks before publish or push.",prompt:"You are Release. On the merged branch: bump the version, write the changelog line, run the guard. Before `npm publish` or any `git push`, stop and ask on the thread — a person answers. Never publish or push without that answer.",skills:[],grants:["shell","fs:write","scm:read","scm:push"],engine:{kind:"harness",harnessId:"claude"},appliesTo:["jobs"]}]);function V(){return G.map(e=>JSON.parse(JSON.stringify(e)))}function K(){return{id:"",name:"",purpose:"",prompt:"",skills:[],grants:["none"],engine:{kind:"auto",policy:{prefer:"balanced"}},appliesTo:["jobs"],memoryScope:""}}function X(e){const r=e||{},t=String(r.id||"").trim()||L(r.name),s=p(r.engine)&&r.engine.kind==="auto"?{kind:"auto",policy:{prefer:r.engine.prefer||r.engine.policy?.prefer||"balanced",...r.engine.policy||{}}}:r.engine,i={id:t,name:String(r.name||"").trim()||t,purpose:String(r.purpose||"").trim(),prompt:String(r.prompt||""),skills:d(r.skills,80,j),grants:d(r.grants,80,32).length?d(r.grants,80,32):["none"],engine:s,...r.egress?{egress:r.egress}:{},appliesTo:Array.isArray(r.appliesTo)&&r.appliesTo.length?r.appliesTo:["jobs"],...r.memoryScope?{memoryScope:r.memoryScope}:{},...r.workdir?{workdir:r.workdir}:{},createdBy:r.createdBy||"person",enabled:r.enabled!==!1,...r.origin&&p(r.origin)?{origin:r.origin}:{},...Object.fromEntries(["version","iconUrl","documentationUrl","provider","tags","examples","inputModes","outputModes","dialectExtras"].filter(a=>r[a]!==void 0&&r[a]!==null).map(a=>[a,r[a]])),...r.createdAt?{createdAt:r.createdAt}:{}},c=S(i);return c.ok?{ok:!0,agent:b(i)}:{ok:!1,errors:c.errors}}function H(e,r="jobs"){return(Array.isArray(e)?e:[]).filter(t=>t&&t.enabled!==!1&&(Array.isArray(t.appliesTo)?t.appliesTo:["jobs"]).includes(r))}export{B as AGENT_ID_RE,m as APPLIES_TO,f as ASSISTANT_ID,_ as AgentError,g as EGRESS_CLASSES,j as MAX_SKILLS,G as STARTER_AGENTS,X as agentFromForm,q as agentTrust,P as assistantAgent,K as blankAgent,D as defineAgent,C as describeAgent,U as engineOf,b as normalizeAgent,H as poolFor,J as resolveTeam,L as slugAgentId,V as starterAgents,S as validateAgent};
@@ -0,0 +1 @@
1
+ const i=Object.freeze(["tokens","calls","ms","usd"]);class k extends Error{constructor(n,r){super(r),this.name="BudgetError",this.code=n}}function p(t){const n=[];if(!t||typeof t!="object")return{ok:!1,errors:["budget must be an object"]};let r=!1;for(const e of i){if(t[e]===void 0||t[e]===null)continue;const f=Number(t[e]);!Number.isFinite(f)||f<=0?n.push(`${e}: a positive number`):r=!0}for(const e of Object.keys(t))i.includes(e)||n.push(`${e}: not a budget dimension (${i.join(", ")})`);return r||n.push("a budget must cap at least one of tokens, calls, ms, usd"),{ok:n.length===0,errors:n}}function b(t){const n={};for(const r of i){const e=Number(t?.[r]);Number.isFinite(e)&&e>0&&(n[r]=e)}return n}function m(t={}){const n=Number(t.tokens??t.total_tokens??(Number(t.input_tokens??t.prompt_tokens)||0)+(Number(t.output_tokens??t.completion_tokens)||0));return{tokens:Number.isFinite(n)?n:0,calls:Number(t.calls??1)||0,usd:Number(t.usd??t.cost)||0}}function h(t,{now:n=()=>Date.now()}={}){const r=p(t);if(!r.ok)throw new k("INVALID",r.errors.join("; "));const e={...b(t)},f=n(),c={tokens:0,calls:0,usd:0},a=()=>n()-f,l=()=>{const s={};for(const o of i)e[o]!==void 0&&(s[o]=Math.max(0,e[o]-(o==="ms"?a():c[o])));return s},d=()=>{for(const s of i)if(e[s]!==void 0&&(s==="ms"?a():c[s])>=e[s])return s;return null};return{cap:e,charge(s){const o=m(s);return c.tokens+=o.tokens,c.calls+=o.calls,c.usd+=o.usd,l()},canAfford(s={}){if(d())return!1;const o=m({calls:1,...s});for(const u of["tokens","calls","usd"])if(e[u]!==void 0&&c[u]+o[u]>e[u])return!1;return!0},remaining:l,exhausted:d,raise(s=1.5){const o=Math.max(1,Number(s)||1);for(const u of Object.keys(e))e[u]!==void 0&&(e[u]=Math.ceil(e[u]*o));return{...e}},snapshot(){return{cap:e,spent:{...c,ms:a()},remaining:l(),exhausted:d()}}}}export{i as BUDGET_DIMENSIONS,k as BudgetError,h as createBudget,b as normalizeBudget,m as usageOf,p as validateBudget};
@@ -0,0 +1,3 @@
1
+ import{normalizeCard as s,cardToProfile as p,A2A_VERSION as u}from"./agent-card.js";import{defineAgentDialect as h}from"./agent-dialects.js";const a=t=>typeof t=="string"?t.trim():t==null?"":String(t).trim(),y=h({id:"a2a",label:"A2A agent card",filename:t=>`${t?.id||"agent"}.agent-card.json`,detect(t,{filename:r=""}={}){let n;try{n=JSON.parse(String(t??""))}catch{return 0}if(!n||typeof n!="object"||Array.isArray(n))return 0;const i=!!a(n.name)&&!!a(n.description),e=Array.isArray(n.supportedInterfaces)||!!a(n.url)||!!n.capabilities;return/agent-card\.json$/i.test(r)&&i?.99:i&&e&&Array.isArray(n.skills)?.9:i&&e?.6:0},parse(t,{name:r=""}={}){let n;try{n=JSON.parse(String(t??""))}catch{return{form:{},extras:{},warnings:["not JSON"]}}const i=s(n),e=[];return i.supportedInterfaces.length||e.push("this card names no endpoint, so there is nowhere to reach the agent"),e.push("a card advertises a remote agent: its engine is a placeholder until ChatPanel can call an A2A endpoint"),{form:{id:"",name:i.name||a(r),purpose:i.description,prompt:m(i),engine:{kind:"auto",policy:{prefer:"balanced"}},grants:["none"],skills:i.skills.map(o=>o.id)},extras:{card:i},warnings:e}},render(t){return`${JSON.stringify(g(t),null,2)}
2
+ `},carries:["id","name","purpose","skills","provider","version","iconUrl","documentationUrl","tags","examples","inputModes","outputModes"],notes:{prompt:"a card is served to strangers — an agent's own instructions are never published in one",engine:"a card says where to reach an agent, never what model is behind it",grants:"what a remote agent may touch is its own operator's business, not ours to declare",tools:"a card advertises skills, not the tools behind them",denyTools:"a card advertises skills, not the tools behind them",mcpServers:"an agent's own connections are not published",permissionMode:"no equivalent — authorization is expressed with security schemes",sandboxMode:"no equivalent — how a remote agent is contained is its operator's business",maxTurns:"no equivalent in a card",effort:"no equivalent in a card",isolation:"no equivalent in a card",color:"no equivalent in a card",background:"no equivalent in a card",hooks:"no equivalent in a card",memoryScope:"no equivalent in a card",workdir:"a local path has no meaning to whoever reads the card"}});function m(t){const r=s(t),n=[];if(r.description&&n.push(r.description),r.skills.length){n.push("","What it offers:");for(const e of r.skills)n.push(`- ${e.name||e.id}${e.description?` — ${e.description}`:""}`)}const i=r.supportedInterfaces[0];return i&&n.push("",`Reached over A2A at ${i.url} (${i.protocolBinding}).`),r.provider?.organization&&n.push(`Published by ${r.provider.organization}.`),n.join(`
3
+ `).trim()}function g(t,{interfaces:r=[],profile:n=u,skills:i=[]}={}){const e=t||{},o=e.dialectExtras?.a2a?.card,c=i.length?i:(e.skills||[]).map(l=>f(l,e)),d=s({...o||{},name:e.name||e.id||"",description:e.purpose||"",version:e.version||o?.version||"0.1.0",...e.provider?{provider:e.provider}:{},...e.iconUrl?{iconUrl:e.iconUrl}:{},...e.documentationUrl?{documentationUrl:e.documentationUrl}:{},supportedInterfaces:r.length?r:o?.supportedInterfaces||[],capabilities:{streaming:!0,pushNotifications:!1,...o?.capabilities||{}},defaultInputModes:e.inputModes?.length?e.inputModes:o?.defaultInputModes,defaultOutputModes:e.outputModes?.length?e.outputModes:o?.defaultOutputModes,skills:c});return delete d.signatures,p(d,n)}function f(t,r){const n=String(t||"").trim();return{id:n,name:n,description:`${n}, as performed by ${r?.name||r?.id||"this agent"}`,tags:r?.tags?.length?[...r.tags]:[]}}export{y as a2aDialect,m as briefFromCard,g as cardFromAgent};
@@ -0,0 +1,2 @@
1
+ import{defineAgentDialect as a,PORTABLE_FIELDS as i}from"./agent-dialects.js";const o=a({id:"chatpanel",label:"ChatPanel",filename:n=>`${n?.id||"agent"}.json`,detect(n,{filename:t=""}={}){let e;try{e=JSON.parse(String(n??""))}catch{return 0}if(!e||typeof e!="object"||Array.isArray(e))return 0;const r=e.engine!==void 0&&e.grants!==void 0;return r&&/(^|\/)(\.chatpanel\/)?agents\//.test(t)?.99:r?.9:e.purpose!==void 0&&e.prompt!==void 0?.5:0},parse(n,{name:t=""}={}){let e;try{e=JSON.parse(String(n??""))}catch{return{form:{},extras:{},warnings:["not JSON"]}}const r={...e};return r.name||(r.name=String(t||"")),{form:{...r,id:String(e.id||"")},extras:{},warnings:[]}},render(n){return`${JSON.stringify(n??{},null,2)}
2
+ `},carries:[...i]});export{o as chatpanelDialect};
@@ -0,0 +1,3 @@
1
+ import{parseFrontmatter as p,renderFrontmatter as k}from"./frontmatter.js";import{defineAgentDialect as w,grantsFromTools as S,toolsFromGrants as b,toNameList as d}from"./agent-dialects.js";const T=Object.freeze(["name","description","tools","disallowedTools","model","permissionMode","maxTurns","skills","mcpServers","hooks","memory","background","omitClaudeMd","effort","isolation","color","initialPrompt","experimental"]),x=Object.freeze(["tools","disallowedTools","model","permissionMode","maxTurns","isolation","color","hooks","initialPrompt"]),m=t=>typeof t=="string"?t.trim():t==null?"":String(t).trim(),A=w({id:"claude",label:"Claude Code",filename:t=>`${t?.id||"agent"}.md`,detect(t,{filename:o=""}={}){const{meta:e,body:n}=p(t);if(!e.name&&!e.description)return 0;const i=/(^|\/)agents\//.test(o)&&/\.md$/i.test(o),r=x.some(s=>e[s]!==void 0);return/(^|\/)SKILL\.md$/i.test(o)||!i&&/(^|\/)skills\//.test(o)?0:i&&r?.95:i?.8:r?.7:n.trim()?.35:.2},parse(t,{name:o=""}={}){const{meta:e,body:n}=p(t),i=[],r=d(e.tools),{grants:s,mcpServers:c,unmapped:u}=S(r);u.length&&i.push(`tools with no ChatPanel equivalent, left ungranted rather than guessed at: ${u.join(", ")}`);const f=d(e.mcpServers),h={id:"",name:m(e.name)||m(o),purpose:m(e.description),prompt:n.trim(),engine:y(e.model),grants:s.length?s:["none"],skills:d(e.skills)},a={raw:{}};for(const[l,g]of Object.entries(e))T.includes(l)||(a.raw[l]=g);Object.keys(a.raw).length||delete a.raw,r.length&&(a.tools=r),d(e.disallowedTools).length&&(a.disallowedTools=d(e.disallowedTools)),f.length&&(a.mcpServers=f);for(const l of["permissionMode","maxTurns","memory","background","omitClaudeMd","effort","isolation","color","initialPrompt","experimental","hooks"])e[l]!==void 0&&(a[l]=e[l]);return m(e.model)&&(a.model=m(e.model)),{form:h,extras:a,warnings:i}},render(t){const o=t||{},e=o.dialectExtras?.claude||{},n={name:o.id||o.name||"agent",description:o.purpose||o.name||""},i=o.grants?.length?b(o.grants,{dialect:"claude"}):d(e.tools);i.length&&(n.tools=i),e.disallowedTools&&(n.disallowedTools=e.disallowedTools);const r=v(o,e);r&&(n.model=r),o.skills?.length&&(n.skills=[...o.skills]),e.mcpServers&&(n.mcpServers=e.mcpServers);for(const s of["permissionMode","maxTurns","memory","background","omitClaudeMd","effort","isolation","color","initialPrompt","experimental","hooks"])e[s]!==void 0&&(n[s]=e[s]);for(const[s,c]of Object.entries(e.raw||{}))n[s]===void 0&&(n[s]=c);return k(n,`
2
+ ${String(o.prompt||"").trim()}
3
+ `)},carries:["id","name","purpose","prompt","engine","grants","skills","mcpServers","tools","denyTools","permissionMode","maxTurns","effort","isolation","color","background","hooks"],notes:{sandboxMode:"Claude Code has no sandbox_mode; its equivalent is permissionMode plus the tools allowed",memoryScope:"Claude Code scopes memory to user, project or local — not to a named namespace",workdir:"a Claude Code agent runs wherever the session runs; a working directory is not part of its definition",provider:"a definition file describes an agent, not who publishes it — that is A2A card territory",version:"a definition file carries no version of its own",iconUrl:"no icon in the format",documentationUrl:"no documentation link in the format",tags:"no tags in the format",examples:'no examples in the format — the description is where the "use this when" goes',inputModes:"media types are an A2A idea",outputModes:"media types are an A2A idea"}});function y(t){const o=m(t);return!o||o==="inherit"?o==="inherit"?{kind:"assistant"}:{kind:"harness",harnessId:"claude"}:{kind:"harness",harnessId:"claude",model:o}}function v(t,o){const e=t?.engine;return e?.kind==="assistant"?"inherit":e?.kind==="harness"&&e.harnessId==="claude"&&e.model||e?.kind==="model"&&e.model&&/claude|sonnet|opus|haiku/i.test(String(e.model))?String(e.model):o.model?String(o.model):""}export{A as claudeDialect};
@@ -0,0 +1 @@
1
+ import{parseToml as m,renderToml as u}from"./toml-lite.js";import{defineAgentDialect as g,toolsFromGrants as _,toNameList as h}from"./agent-dialects.js";const x=Object.freeze(["name","description","developer_instructions","model","model_reasoning_effort","sandbox_mode","approval_policy","mcp_servers","skills"]),f=Object.freeze({"read-only":[],"workspace-write":["fs:write"],"danger-full-access":["fs:write","shell"]}),s=n=>typeof n=="string"?n.trim():n==null?"":String(n).trim(),A=g({id:"codex",label:"Codex",filename:n=>`${n?.id||"agent"}.toml`,detect(n,{filename:o=""}={}){const e=String(n??"");if(/^\s*---\s*$/m.test(e.slice(0,8)))return 0;const r=m(e),t=!!s(r.developer_instructions),i=!!s(r.name)&&!!s(r.description),a=/(^|\/)(\.codex\/)?agents\//.test(o)&&/\.toml$/i.test(o);return t&&(i||a)?.95:t?.85:i&&a?.8:i&&(r.model||r.sandbox_mode)?.6:0},parse(n,{name:o=""}={}){const e=m(n),r=[],t=s(e.sandbox_mode),i=[...f[t]||[]];t&&!(t in f)&&r.push(`unknown sandbox_mode "${t}" — no file or shell grant was inferred from it`);const a=Object.keys(e.mcp_servers||{});for(const d of a)i.push(`mcp:${d}`);const c={id:"",name:s(e.name)||s(o),purpose:s(e.description),prompt:s(e.developer_instructions),engine:k(e.model),grants:i.length?i:["none"],skills:w(e.skills)},l={raw:{}};for(const[d,p]of Object.entries(e))x.includes(d)||(l.raw[d]=p);Object.keys(l.raw).length||delete l.raw;for(const d of["model","model_reasoning_effort","sandbox_mode","approval_policy"])e[d]!==void 0&&(l[d]=e[d]);return e.mcp_servers!==void 0&&(l.mcp_servers=e.mcp_servers),e.skills!==void 0&&(l.skills=e.skills),{form:c,extras:l,warnings:r}},render(n){const o=n||{},e=o.dialectExtras?.codex||{},r={name:o.id||o.name||"agent",description:o.purpose||o.name||"",developer_instructions:String(o.prompt||"").trim()},t=y(o,e);t&&(r.model=t),e.model_reasoning_effort&&(r.model_reasoning_effort=e.model_reasoning_effort);const i=b(o,e);i&&(r.sandbox_mode=i),e.approval_policy&&(r.approval_policy=e.approval_policy),e.skills!==void 0?r.skills=e.skills:o.skills?.length&&(r.skills={config:o.skills.map(a=>({name:String(a)}))});for(const[a,c]of Object.entries(e.raw||{}))r[a]===void 0&&(r[a]=c);return e.mcp_servers!==void 0&&(r.mcp_servers=e.mcp_servers),u(r)},carries:["id","name","purpose","prompt","engine","grants","skills","mcpServers","sandboxMode","effort","permissionMode"],notes:{tools:"Codex states a boundary with one sandbox_mode, not a list of tools",denyTools:"Codex has no per-tool deny list",maxTurns:"no turn cap in a Codex agent file",isolation:"no git-worktree isolation in the format",color:"no display colour in the format",background:"no background flag in the format",hooks:"Codex has no lifecycle hooks in an agent definition",memoryScope:"no memory namespace in the format",workdir:"a Codex agent runs where the session runs",provider:"a definition file describes an agent, not who publishes it",version:"a definition file carries no version of its own",iconUrl:"no icon in the format",documentationUrl:"no documentation link in the format",tags:"no tags in the format",examples:"no examples in the format",inputModes:"media types are an A2A idea",outputModes:"media types are an A2A idea"}});function k(n){const o=s(n);return o?{kind:"harness",harnessId:"codex",model:o}:{kind:"harness",harnessId:"codex"}}function y(n,o){const e=n?.engine;return e?.kind==="harness"&&e.harnessId==="codex"&&e.model||e?.kind==="model"&&e.model&&/gpt|o\d|codex/i.test(String(e.model))?String(e.model):o.model?String(o.model):""}function b(n,o){const e=new Set(h(n?.grants));return s(o.sandbox_mode)==="danger-full-access"?"danger-full-access":e.has("fs:write")||e.has("shell")?"workspace-write":e.size&&!e.has("none")?"read-only":s(o.sandbox_mode)||""}function w(n){if(!n)return[];const o=Array.isArray(n)?n:n.config;return Array.isArray(o)?o.map(e=>typeof e=="string"?e:s(e?.name)).filter(Boolean):[]}function O(n){return _(n,{dialect:"codex"})}export{f as SANDBOX_GRANTS,A as codexDialect,O as codexToolNames};
@@ -0,0 +1 @@
1
+ const f=Object.freeze(["model","harness","auto","assistant"]),p=Object.freeze(["cheapest-that-clears","best-quality","fastest","balanced"]),$=/^[a-zA-Z0-9_.:@+-]{1,120}$/,a=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),s=(n,i=200)=>n==null||n===""?void 0:String(n).trim().slice(0,i)||void 0,l=n=>{const i=Number(n);return n===""||n==null||!Number.isFinite(i)?void 0:i},k=n=>Array.isArray(n)?[...new Set(n.map(i=>s(typeof i=="string"?i:I(i),200)).filter(Boolean))]:void 0;function d(n){const i=a(n)?n:{},t={},e={},r=l(i.floor?.quality);r!==void 0&&(t.quality=Math.max(0,Math.min(1,r)));const o=l(i.floor?.availability);o!==void 0&&(t.availability=Math.max(0,Math.min(1,o)));const c=l(i.ceiling?.costPerTask);c!==void 0&&c>=0&&(e.costPerTask=c);const u=l(i.ceiling?.latencyMs);u!==void 0&&u>=0&&(e.latencyMs=Math.round(u));const h=k(i.allow),y=k(i.deny);return{prefer:p.includes(i.prefer)?i.prefer:"balanced",...Object.keys(t).length?{floor:t}:{},...Object.keys(e).length?{ceiling:e}:{},...h?.length?{allow:h}:{},...y?.length?{deny:y}:{}}}function m(n){if(n==null||n==="")return{kind:"auto",policy:d()};if(typeof n=="string"){const r=n.trim();if(r==="assistant"||r==="auto")return r==="assistant"?{kind:"assistant"}:{kind:"auto",policy:d()};const o=/^(model|harness):(.+)$/.exec(r);return o?o[1]==="harness"?{kind:"harness",harnessId:o[2].trim()}:{kind:"model",model:o[2].trim()}:{kind:"model",model:r}}if(!a(n))return{kind:"auto",policy:d()};const i=f.includes(n.kind)?n.kind:n.harnessId?"harness":n.model?"model":(n.policy,"auto");if(i==="assistant")return{kind:i};if(i==="auto")return{kind:i,policy:d(n.policy)};if(i==="harness"){const r=s(n.harnessId||n.id,120);if(!r)return{kind:"auto",policy:d()};const o=s(n.model,200);return{kind:i,harnessId:r,...o?{model:o}:{}}}const t=s(n.model||n.id,200);if(!t)return{kind:"auto",policy:d()};const e=s(n.providerId||n.destination||n.endpointId,120);return{kind:"model",...e?{providerId:e}:{},model:t}}function b(n,i="engine"){const t=[];return n==null||n===""||typeof n=="string"?t:a(n)?(n.kind!==void 0&&!f.includes(n.kind)&&t.push(`${i}.kind: one of ${f.join(", ")}`),n.kind==="harness"&&!s(n.harnessId||n.id)&&t.push(`${i}.harnessId: which harness`),n.kind==="harness"&&s(n.harnessId||n.id)&&!$.test(String(n.harnessId||n.id).trim())&&t.push(`${i}.harnessId: a short identifier`),n.kind==="model"&&!s(n.model||n.id)&&t.push(`${i}.model: which model`),n.kind==="auto"&&n.policy!==void 0&&!a(n.policy)&&t.push(`${i}.policy: an object`),n.kind==="auto"&&a(n.policy)&&n.policy.prefer!==void 0&&!p.includes(n.policy.prefer)&&t.push(`${i}.policy.prefer: one of ${p.join(", ")}`),t):[`${i}: a string or an object`]}function g(n){const i=m(n);return i.kind==="harness"?{kind:"harness",id:i.harnessId,...i.model?{model:i.model}:{}}:i.kind==="model"?i.providerId?{kind:"model",id:i.providerId,model:i.model}:{kind:"model",id:i.model}:null}function I(n){const i=g(n);return i?`${i.kind}:${i.id}${i.model&&i.model!==i.id?`/${i.model}`:""}`:null}function x(n,{harnessName:i=e=>e,providerName:t=e=>e}={}){const e=m(n);return e.kind==="assistant"?"the chat’s model":e.kind==="auto"?`auto · ${e.policy.prefer.replace(/-/g," ")}`:e.kind==="harness"?`${i(e.harnessId)}${e.model?` (${e.model})`:""}`:`${e.model}${e.providerId?` at ${t(e.providerId)}`:""}`}function E(n){const i=m(n);return i.kind!=="auto"?"balanced":{"best-quality":"strong","cheapest-that-clears":"cheap",fastest:"cheap",balanced:"balanced"}[i.policy.prefer]||"balanced"}export{f as ENGINE_KINDS,$ as HARNESS_ID_RE,p as ROUTE_PREFERS,x as describeEngine,I as engineKeyOf,g as engineRef,m as normalizeEngineSpec,d as normalizePolicy,E as tierOf,b as validateEngineSpec};
@@ -0,0 +1,14 @@
1
+ const W=/^---\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)\r?\n?/;function E(t){const n=String(t??""),e=W.exec(n);return e?{meta:A(e[1]),body:n.slice(e[0].length)}:{meta:{},body:n}}function Y(t,n=""){return`---
2
+ ${m(t&&typeof t=="object"?t:{})}---
3
+ ${String(n??"")}`}function A(t){const n=[];for(const i of String(t??"").split(/\r?\n/)){const r=i.trim();n.push({indent:i.length-i.trimStart().length,text:r,raw:i,blank:!r,comment:r.startsWith("#")})}const[e]=d(n,l(n,0),-1);return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function l(t,n){let e=n;for(;e<t.length&&(t[e].blank||t[e].comment);)e+=1;return e}const b=/^(?:(["'])((?:\\.|(?!\1).)*)\1|([^\s:#][^:]*?))\s*:(?:\s+(.*))?$/;function d(t,n,e){const i={};let r=l(t,n);for(;r<t.length;){const o=t[r];if(o.indent<=e)break;const u=o.indent,s=b.exec(o.text);if(!s){r=l(t,r+1);continue}const c=(s[2]!==void 0?S(s[2]):s[3]).trim(),f=(s[4]??"").trim();if(!c){r=l(t,r+1);continue}if(f==="|"||f===">"||f==="|-"||f===">-"||f==="|+"||f===">+"){const[a,h]=j(t,r+1,u,f);i[c]=a,r=l(t,h);continue}if(f===""){const a=l(t,r+1);if(a<t.length&&t[a].indent>u){const[h,$]=t[a].text.startsWith("- ")||t[a].text==="-"?g(t,a,u):d(t,a,u);i[c]=h,r=l(t,$);continue}if(a<t.length&&t[a].indent===u&&t[a].text.startsWith("- ")){const[h,$]=g(t,a,u-1);i[c]=h,r=l(t,$);continue}i[c]="",r=a;continue}i[c]=p(f),r=l(t,r+1)}return[i,r]}function g(t,n,e){const i=[];let r=l(t,n);for(;r<t.length;){const o=t[r];if(o.indent<=e||!(o.text==="-"||o.text.startsWith("- ")))break;const u=o.indent,s=o.text==="-"?"":o.text.slice(2).trim();if(s&&b.test(s)){const c=[{indent:u+2,text:s,raw:s,blank:!1,comment:!1},...t.slice(r+1)],[f,a]=d(c,0,u+1);i.push(f),r=l(t,a===0?r+1:r+a);continue}if(s===""){const c=l(t,r+1);if(c<t.length&&t[c].indent>u){const[f,a]=t[c].text.startsWith("- ")?g(t,c,u):d(t,c,u);i.push(f),r=l(t,a);continue}r=c;continue}i.push(p(s)),r=l(t,r+1)}return[i,r]}function j(t,n,e,i){const r=[];let o=n,u=null;for(;o<t.length;o++){const c=t[o];if(c.blank){r.push("");continue}if(c.indent<=e)break;u===null&&(u=c.indent),r.push(c.raw.slice(Math.min(u,c.indent)))}for(;r.length&&r[r.length-1]==="";)r.pop();const s=i.startsWith(">")?r.reduce((c,f)=>f===""?`${c}
4
+ `:c&&!c.endsWith(`
5
+ `)?`${c} ${f}`:c+f,""):r.join(`
6
+ `);return i.endsWith("-")?[s,o]:[`${s}
7
+ `,o]}function p(t){let n=String(t).trim();if(/^(['"])/.test(n)){const e=n[0],i=w(n,e);if(i>0)return e==='"'?S(n.slice(1,i)):n.slice(1,i)}if(n=N(n).trim(),n.startsWith("[")&&n.endsWith("]"))return x(n.slice(1,-1)).map(p).filter(e=>e!=="");if(n.startsWith("{")&&n.endsWith("}")){const e={};for(const i of x(n.slice(1,-1))){const r=i.indexOf(":");r<0||(e[p(i.slice(0,r))]=p(i.slice(r+1)))}return e}return n==="true"||n==="yes"?!0:n==="false"||n==="no"?!1:n==="null"||n==="~"||n===""?n===""?"":null:/^[+-]?\d+$/.test(n)||/^[+-]?\d*\.\d+$/.test(n)?Number(n):n}function w(t,n){for(let e=1;e<t.length;e++){if(t[e]==="\\"&&n==='"'){e+=1;continue}if(t[e]===n)return e}return-1}function N(t){let n="";for(let e=0;e<t.length;e++){const i=t[e];if(n){if(i==="\\"&&n==='"'){e+=1;continue}i===n&&(n="");continue}if(i==='"'||i==="'")n=i;else if(i==="#"&&(e===0||/\s/.test(t[e-1])))return t.slice(0,e)}return t}function x(t){const n=[];let e="",i=0,r="";for(let o=0;o<t.length;o++){const u=t[o];if(r){if(e+=u,u==="\\"&&r==='"'){e+=t[o+1]??"",o+=1;continue}u===r&&(r="");continue}if(u==='"'||u==="'"){r=u,e+=u;continue}if((u==="["||u==="{")&&(i+=1),(u==="]"||u==="}")&&(i-=1),u===","&&i===0){n.push(e.trim()),e="";continue}e+=u}return e.trim()&&n.push(e.trim()),n}function S(t){return t.replace(/\\(.)/g,(n,e)=>({n:`
8
+ `,r:"\r",t:" ",'"':'"',"'":"'","\\":"\\"})[e]??e)}function m(t,n=0){const e=" ".repeat(n),i=[];for(const[r,o]of Object.entries(t||{})){if(o==null)continue;const u=F(r);if(Array.isArray(o)){if(!o.length){i.push(`${e}${u}: []`);continue}if(o.every(s=>!y(s)&&!Array.isArray(s))){i.push(`${e}${u}: [${o.map(k).join(", ")}]`);continue}i.push(`${e}${u}:`);for(const s of o)if(y(s)){const c=m(s,n+4).split(`
9
+ `).filter(Boolean);i.push(`${e} - ${c[0].trimStart()}`);for(const f of c.slice(1))i.push(f)}else i.push(`${e} - ${k(s)}`);continue}if(y(o)){if(!Object.keys(o).length){i.push(`${e}${u}: {}`);continue}i.push(`${e}${u}:`),i.push(m(o,n+2).replace(/\n$/,""));continue}if(typeof o=="string"&&o.includes(`
10
+ `)){i.push(`${e}${u}: |${o.endsWith(`
11
+ `)?"":"-"}`);for(const s of o.replace(/\n$/,"").split(`
12
+ `))i.push(s?`${e} ${s}`:"");continue}i.push(`${e}${u}: ${B(o)}`)}return`${i.join(`
13
+ `)}
14
+ `}const O=/^[A-Za-z_][\w.-]*$/,F=t=>O.test(String(t))?String(t):JSON.stringify(String(t)),y=t=>!!t&&typeof t=="object"&&!Array.isArray(t);function B(t){if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number")return Number.isFinite(t)?String(t):"0";const n=String(t);return n===""?"''":/^[\s>|*&!%@`'"[{]/.test(n)||/[:#]\s/.test(n)||/\s$/.test(n)||/^(true|false|yes|no|null|~)$/i.test(n)||/^[+-]?\d*\.?\d+$/.test(n)?JSON.stringify(n):n}function k(t){if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number")return Number.isFinite(t)?String(t):"0";const n=String(t);return/^[A-Za-z0-9_./:@+-]+$/.test(n)?n:JSON.stringify(n)}export{E as parseFrontmatter,A as parseYamlBlock,Y as renderFrontmatter,m as renderYamlBlock};
@@ -0,0 +1,3 @@
1
+ function u(r){if(Array.isArray(r))return r.map(String).filter(Boolean);const e=String(r||"").trim();return e?e.startsWith("[")?c(e):f(e,t=>/\s/.test(t)).map(t=>t.replace(/,+$/,"")).filter(Boolean):[]}function a(r){return Array.isArray(r)?r.join(`
2
+ `):String(r||"")}function p(r){if(r&&typeof r=="object"&&!Array.isArray(r))return Object.fromEntries(Object.entries(r).filter(([t,n])=>t&&String(n??"")!=="").map(([t,n])=>[t,String(n)]));const e={};for(const t of String(r||"").split(/\n|,(?=\s*[A-Za-z_][A-Za-z0-9_]*\s*=)/)){const n=t.indexOf("=");if(n<=0)continue;const o=t.slice(0,n).trim(),s=t.slice(n+1).trim();o&&s&&(e[o]=s)}return e}function l(r){return(Array.isArray(r)?r:[]).map(String).filter(e=>/^[A-Z][A-Z0-9_]*=/.test(e.trim()))}function A(r){return Object.entries(r||{}).map(([e,t])=>`${e}=${t}`).join(`
3
+ `)}function c(r){try{const t=JSON.parse(r);if(Array.isArray(t))return t.map(String).filter(Boolean)}catch{}const e=r.replace(/^\[/,"").replace(/\]$/,"");return f(e,t=>t===",").map(t=>t.trim()).filter(Boolean)}function f(r,e){const t=[];let n="",o="",s=!1;for(const i of String(r||"")){if(s){n+=i,s=!1;continue}if(i==="\\"){s=!0;continue}if(o){i===o?o="":n+=i;continue}if(i==='"'||i==="'"){o=i;continue}if(e(i)){n&&(t.push(n),n="");continue}n+=i}return n&&t.push(n),t}export{a as argsToText,l as envLikeArgs,A as envToText,u as parseArgsInput,p as parseEnvInput};
@@ -1,6 +1,2 @@
1
- function W(n){const t=String(n||"").trim();if(!t)return[];const e=A(t);return e?v(e):b(t)}function S(n){if(Array.isArray(n))return n.map(String).filter(Boolean);const t=String(n||"").trim();return t?t.startsWith("[")?h(t):w(t).map(e=>e.replace(/,+$/,"")).filter(Boolean):[]}function T(n){return Array.isArray(n)?n.join(`
2
- `):String(n||"")}function _(n){if(n&&typeof n=="object"&&!Array.isArray(n))return Object.fromEntries(Object.entries(n).filter(([e,i])=>e&&String(i??"")!=="").map(([e,i])=>[e,String(i)]));const t={};for(const e of String(n||"").split(/\n|,(?=\s*[A-Za-z_][A-Za-z0-9_]*\s*=)/)){const i=e.indexOf("=");if(i<=0)continue;const r=e.slice(0,i).trim(),s=e.slice(i+1).trim();r&&s&&(t[r]=s)}return t}function z(n){return(Array.isArray(n)?n:[]).map(String).filter(t=>/^[A-Z][A-Z0-9_]*=/.test(t.trim()))}function I(n){return Object.entries(n||{}).map(([t,e])=>`${t}=${e}`).join(`
3
- `)}function A(n){try{return JSON.parse(n)}catch{return null}}function v(n){const t=n?.mcpServers||n?.mcp_servers||n?.servers||n;return!t||typeof t!="object"?[]:t.command||t.url?[f("Imported MCP server",t)]:Object.entries(t).map(([e,i])=>f(e,i)).filter(Boolean)}function b(n){const t=[],e=/^\s*\[(mcp_servers|mcpServers)\.([^\]]+)\]\s*$/gm;let i;for(;i=e.exec(n);)t.push({name:i[2].trim().replace(/^["']|["']$/g,""),start:e.lastIndex});return t.map((r,s)=>{const o=t[s+1]?.start?n.lastIndexOf(`
4
- `,t[s+1].start-t[s+1].name.length-15):n.length,l=n.slice(r.start,o<r.start?n.length:o);return f(r.name,j(l))}).filter(Boolean)}function j(n){const t={};for(const o of["type","transport","command","url"]){const l=u(n,o);l!=null&&(t[o]=p(l))}const e=u(n,"args");e!=null&&(t.args=h(e));const i=u(n,"env")??u(n,"environment")??u(n,"environmentVariables");i!=null&&(t.env=m(i));const r=u(n,"headers");r!=null&&(t.headers=m(r));const s=u(n,"authorization")??u(n,"auth_header");return s!=null&&(t.headers={...t.headers||{},Authorization:p(s)}),t}function f(n,t={}){if(!t||typeof t!="object")return null;const e=d(t.command),i=d(t.url),r=String(t.type||t.transport||(e?"stdio":"http")).toLowerCase(),s={name:$(n),enabled:t.enabled!==!1};return e||r==="stdio"?e?{...s,transport:"stdio",command:e,args:S(t.args),env:g(t.env||t.environment||t.environmentVariables)}:null:i?{...s,transport:"http",url:i,headers:g(t.headers)}:null}function u(n,t){const e=String(n||"").split(/\r?\n/);for(let i=0;i<e.length;i++){const r=new RegExp(`^\\s*${C(t)}\\s*=\\s*(.*)$`).exec(e[i]);if(!r)continue;let s=x(r[1]).trim();if(!s)return"";const o=s[0],l=o==="["?"]":o==="{"?"}":"";if(!l)return s;let a=y(s,o,l);for(;a>0&&i+1<e.length;)i+=1,s+=`
5
- ${x(e[i])}`,a=y(s,o,l);return s.trim()}return null}function h(n){const t=String(n||"").trim(),e=t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t,i=[];let r=0;for(;r<e.length;){for(;r<e.length&&/[\s,]/.test(e[r]);)r+=1;if(r>=e.length)break;const s=e[r];if(s==='"'||s==="'"){const a=c(e,r);i.push(a.value),r=a.next;continue}let o=r;for(;o<e.length&&e[o]!==",";)o+=1;const l=e.slice(r,o).trim();l&&i.push(l),r=o+1}return i}function m(n){const t=String(n||"").trim(),e=t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t,i={};let r=0;for(;r<e.length;){for(;r<e.length&&/[\s,]/.test(e[r]);)r+=1;if(r>=e.length)break;let s="";if(e[r]==='"'||e[r]==="'"){const o=c(e,r);s=o.value,r=o.next}else{let o=r;for(;o<e.length&&e[o]!=="="&&e[o]!==":";)o+=1;s=e.slice(r,o).trim(),r=o}for(;r<e.length&&/[\s=:]/.test(e[r]);)r+=1;if(!s)break;if(e[r]==='"'||e[r]==="'"){const o=c(e,r);i[s]=o.value,r=o.next}else{let o=r;for(;o<e.length&&e[o]!==",";)o+=1;i[s]=p(e.slice(r,o).trim()),r=o+1}}return i}function w(n){const t=[];let e="",i="",r=!1;for(const s of String(n||"")){if(r){e+=s,r=!1;continue}if(s==="\\"){r=!0;continue}if(i){s===i?i="":e+=s;continue}if(s==='"'||s==="'"){i=s;continue}if(/\s/.test(s)){e&&(t.push(e),e="");continue}e+=s}return e&&t.push(e),t}function c(n,t){const e=n[t];let i="",r=!1;for(let s=t+1;s<n.length;s++){const o=n[s];if(r){i+=e==='"'?O(o):o,r=!1;continue}if(o==="\\"&&e==='"'){r=!0;continue}if(o===e)return{value:i,next:s+1};i+=o}return{value:i,next:n.length}}function p(n){const t=String(n||"").trim().replace(/,+$/,"");return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?c(t,0).value:t==="true"?!0:t==="false"?!1:t}function g(n){return!n||typeof n!="object"||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).map(([t,e])=>[t,String(e)]))}function $(n){return String(n||"MCP server").replace(/[_-]+/g," ").replace(/\b[a-z]/g,t=>t.toUpperCase())}function d(n){return typeof n=="string"?n.trim():""}function x(n){let t="";for(let e=0;e<n.length;e++){const i=n[e];if(t){i===t&&(t=""),i==="\\"&&t==='"'&&(e+=1);continue}if(i==='"'||i==="'")t=i;else if(i==="#")return n.slice(0,e)}return n}function y(n,t,e){let i=0,r="";for(let s=0;s<n.length;s++){const o=n[s];if(r){o==="\\"&&r==='"'?s+=1:o===r&&(r="");continue}o==='"'||o==="'"?r=o:o===t?i+=1:o===e&&(i-=1)}return i}function O(n){return{n:`
6
- `,r:"\r",t:" ",'"':'"',"\\":"\\"}[n]??n}function C(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}export{T as argsToText,z as envLikeArgs,I as envToText,S as parseArgsInput,_ as parseEnvInput,W as parseMcpConfig};
1
+ import{tomlValue as o,parseArray as d,parseInlineTable as l,parseScalar as m}from"./toml-lite.js";import{parseArgsInput as h}from"./mcp-args-env.js";import{parseArgsInput as b,argsToText as j,parseEnvInput as z,envToText as _,envLikeArgs as w}from"./mcp-args-env.js";function I(e){const r=String(e||"").trim();if(!r)return[];const n=v(r);return n?g(n):y(r)}function v(e){try{return JSON.parse(e)}catch{return null}}function g(e){const r=e?.mcpServers||e?.mcp_servers||e?.servers||e;return!r||typeof r!="object"?[]:r.command||r.url?[p("Imported MCP server",r)]:Object.entries(r).map(([n,t])=>p(n,t)).filter(Boolean)}function y(e){const r=[],n=/^\s*\[(mcp_servers|mcpServers)\.([^\]]+)\]\s*$/gm;let t;for(;t=n.exec(e);)r.push({name:t[2].trim().replace(/^["']|["']$/g,""),start:n.lastIndex});return r.map((a,s)=>{const i=r[s+1]?.start?e.lastIndexOf(`
2
+ `,r[s+1].start-r[s+1].name.length-15):e.length,u=e.slice(a.start,i<a.start?e.length:i);return p(a.name,S(u))}).filter(Boolean)}function S(e){const r={};for(const i of["type","transport","command","url"]){const u=o(e,i);u!=null&&(r[i]=m(u))}const n=o(e,"args");n!=null&&(r.args=d(n));const t=o(e,"env")??o(e,"environment")??o(e,"environmentVariables");t!=null&&(r.env=l(t));const a=o(e,"headers");a!=null&&(r.headers=l(a));const s=o(e,"authorization")??o(e,"auth_header");return s!=null&&(r.headers={...r.headers||{},Authorization:m(s)}),r}function p(e,r={}){if(!r||typeof r!="object")return null;const n=f(r.command),t=f(r.url),a=String(r.type||r.transport||(n?"stdio":"http")).toLowerCase(),s={name:x(e),enabled:r.enabled!==!1};return n||a==="stdio"?n?{...s,transport:"stdio",command:n,args:h(r.args),env:c(r.env||r.environment||r.environmentVariables)}:null:t?{...s,transport:"http",url:t,headers:c(r.headers)}:null}function c(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).map(([r,n])=>[r,String(n)]))}function x(e){return String(e||"MCP server").replace(/[_-]+/g," ").replace(/\b[a-z]/g,r=>r.toUpperCase())}function f(e){return typeof e=="string"?e.trim():""}export{j as argsToText,w as envLikeArgs,_ as envToText,b as parseArgsInput,z as parseEnvInput,I as parseMcpConfig};
@@ -0,0 +1 @@
1
+ const p=Object.freeze({npm:"https://registry.npmjs.org",pypi:"https://pypi.org/simple",models:"https://huggingface.co",github:"https://api.github.com"}),a=Object.freeze(Object.keys(p));function h(r){const t=String(r??"").trim();if(!t)return"";let n;try{n=new URL(t)}catch{throw new Error(`registry: ${JSON.stringify(t)} is not a URL`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error(`registry: ${n.protocol} is not http(s)`);if(n.username||n.password)throw new Error("registry: put credentials in your package manager's own config, not here");return`${n.origin}${n.pathname.replace(/\/+$/,"")}`}function u(r={}){const t={};for(const n of a){if(!(n in(r||{})))continue;const e=h(r[n]);e&&(t[n]=e)}return t}function f(r,t={}){if(!a.includes(r))throw new Error(`registry: unknown kind ${JSON.stringify(r)}`);return t&&t[r]||p[r]}function m(r={}){return a.some(t=>r?.[t]&&r[t]!==p[t])}function y(r,t,n={}){const e=f(r,n),i=p[r];if(e===i)return String(t);let o;try{o=new URL(String(t))}catch{return String(t)}const s=new URL(i);if(o.origin!==s.origin)return String(t);const c=o.pathname.startsWith(s.pathname)?o.pathname.slice(s.pathname.length):o.pathname;return`${e}${c.startsWith("/")?"":"/"}${c}${o.search}`}function l(r={},t={}){const n={...t},e=(c,g)=>{g&&(n[c]=g)},i=r?.npm,o=r?.pypi,s=r?.models;return e("npm_config_registry",i),e("NPM_CONFIG_REGISTRY",i),e("UV_INDEX_URL",o),e("PIP_INDEX_URL",o),e("HF_ENDPOINT",s),n}export{p as DEFAULT_REGISTRIES,a as REGISTRY_KINDS,m as hasOverrides,y as mirrorUrl,u as normalizeRegistries,l as registryEnv,f as registryFor,h as validRegistry};
@@ -0,0 +1,3 @@
1
+ import{parseFrontmatter as y,renderFrontmatter as L}from"./frontmatter.js";import{isSafeSkillPath as $,normalizeSkill as w,SKILL_FILE_KINDS as u,SkillManifestError as c}from"./skill-manifest.js";const m="SKILL.md",S=/^[a-z0-9][a-z0-9_-]*$/,I=512*1024,b=200,x=Object.freeze(["name","description","version","platforms","command","icon"]);function P(t){const{meta:e,body:n}=y(t);return{meta:e,body:n.trim()}}function A({meta:t={},body:e="",dirName:n="",relPath:a="",source:o="",files:f=[],hash:s=""}={}){const r=i(t.name)||n,l=S.test(String(r))?String(r):n,g={};for(const p of u){const d=f.filter(k=>k.startsWith(`${p}/`)).map(k=>k.slice(p.length+1));d.length&&(g[p]=d)}const h={};for(const[p,d]of Object.entries(t))x.includes(p)||(h[p]=d);return w({id:l,name:String(r),command:S.test(l)?l:"",description:i(t.description),prompt:String(e||"").trim(),...i(t.version)?{version:i(t.version)}:{},...i(t.icon)?{icon:i(t.icon)}:{},...Array.isArray(t.platforms)?{platforms:t.platforms.map(i).filter(Boolean)}:{},...Object.keys(g).length?{files:g}:{},...Object.keys(h).length?{packageMeta:h}:{},...o?{origin:{source:o,id:a||l,...s?{hash:s}:{}}}:{}})}function M(t){const e=t||{},n={name:i(e.id)||i(e.name)||"skill",description:i(e.description)||i(e.name)};i(e.version)&&(n.version=i(e.version)),i(e.icon)&&(n.icon=i(e.icon)),Array.isArray(e.platforms)&&e.platforms.length&&(n.platforms=[...e.platforms]);for(const[a,o]of Object.entries(e.packageMeta||{}))n[a]===void 0&&(n[a]=o);return L(n,`
2
+ ${String(e.prompt||"").trim()}
3
+ `)}function F(t,{files:e=[]}={}){const n=w(t||{});if(!i(n.id))throw new c("ID","a skill package needs an id — it is the directory name");if(!S.test(String(n.id)))throw new c("ID",`"${n.id}" cannot be a directory name (letters, digits, _ and - only)`);if(!i(n.prompt))throw new c("PROMPT",`${n.id}: a skill package with no instructions is an empty folder`);const a=M(n);if(a.length>I)throw new c("SIZE",`${n.id}: SKILL.md is ${a.length} bytes — a procedure document, not a corpus`);const o=[{path:m,text:a,kind:"skill"}],f=new Set([m.toLowerCase()]);for(const s of e){const r=String(s?.path||"").trim();if(!r)continue;if(!$(r))throw new c("PATH",`${n.id}: "${r}" is not a safe path inside a package`);const l=r.split("/")[0];if(!u.includes(l))throw new c("PATH",`${n.id}: "${r}" is not in one of ${u.join(", ")}`);if(f.has(r.toLowerCase()))throw new c("PATH",`${n.id}: "${r}" is written twice`);f.add(r.toLowerCase()),o.push({path:r,text:String(s.text??""),kind:l})}if(o.length>b)throw new c("SIZE",`${n.id}: ${o.length} files is not a skill, it is a repository`);return o}function K(t,{dirName:e="",source:n="local"}={}){const a=t.find(s=>s.path===m),{meta:o,body:f}=P(a?.text||"");return A({meta:o,body:f,dirName:e||i(o.name),relPath:e||i(o.name),source:n,files:t.filter(s=>s.path!==m).map(s=>s.path)})}function i(t){return t==null?"":typeof t=="string"?t.trim():typeof t=="number"||typeof t=="boolean"?String(t):""}export{m as SKILL_FILE,P as parseSkillMd,M as renderSkillMd,A as skillFromPackage,K as skillFromPlan,F as skillPackagePlan};
@@ -0,0 +1 @@
1
+ import{validateBudget as y,normalizeBudget as x}from"./budget.js";import{normalizeEngineSpec as O,validateEngineSpec as j,tierOf as $}from"./engine.js";const k=/^[a-z][a-z0-9_-]{0,63}$/i,E=/^[a-z][a-z0-9_-]{0,31}$/i,c=Object.freeze(["model","subagent","recipe"]),l=Object.freeze(["cheap","balanced","strong"]),p=Object.freeze(["judge","converge","concat","first"]),g=Object.freeze(["fixed","planner"]),N=Object.freeze(["none","data","web","mcp","history","shell","fs:write","scm:read","scm:push","scm:pr","scm:merge"]),M=Object.freeze(["shell","fs:write","scm:read","scm:push","scm:pr","scm:merge"]),f=/^(none|data|web|history|mcp|mcp:[a-zA-Z0-9_.:-]{1,64}|shell|fs:write|scm:(read|push|pr|merge))$/,h=8,R=/^[a-z][a-z0-9_-]{0,63}$/i;class T extends Error{constructor(t,i){super(i),this.name="TeamError",this.code=t}}const u=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function m(e){const t=(Array.isArray(e)?e:typeof e=="string"?[e]:[]).map(n=>String(n||"").trim()).filter(Boolean),i=[...new Set(t.filter(n=>f.test(n)))];return!i.length||i.includes("none")?["none"]:i}function b(e){const t=[];if(!u(e))return{ok:!1,errors:["team must be an object"]};if(k.test(String(e.name||""))||t.push("name: a short identifier (letters, digits, _ -)"),!Array.isArray(e.roles)||!e.roles.length)t.push("roles: a non-empty array");else{e.roles.length>h&&t.push(`roles: at most ${h}`);const n=new Set;e.roles.forEach((s,o)=>{const r=`roles[${o}]`;if(!u(s)){t.push(`${r}: must be an object`);return}E.test(String(s.id||""))?n.has(s.id)&&t.push(`${r}.id: duplicate "${s.id}"`):t.push(`${r}.id: a short identifier`),n.add(s.id),s.mode!==void 0&&!c.includes(s.mode)&&t.push(`${r}.mode: one of ${c.join(", ")}`),s.prefer!==void 0&&!l.includes(s.prefer)&&t.push(`${r}.prefer: one of ${l.join(", ")}`),(s.mode||"model")==="recipe"&&!s.recipe&&t.push(`${r}.recipe: a recipe name is required in recipe mode`),s.agent!==void 0&&s.agent!==null&&!R.test(String(s.agent))&&t.push(`${r}.agent: an agent id`),(s.mode||"model")!=="recipe"&&!s.agent&&!String(s.prompt||"").trim()&&t.push(`${r}.prompt: what this role does`),t.push(...j(s.engine,`${r}.engine`));const a=(Array.isArray(s.grants)?s.grants:[]).filter(d=>!f.test(String(d)));a.length&&t.push(`${r}.grants: not grantable: ${a.join(", ")}${a.some(d=>/^page/.test(String(d)))?" (a tab is one person's; a team may not act on it)":""}`)})}e.merge!==void 0&&!p.includes(e.merge)&&t.push(`merge: one of ${p.join(", ")}`),e.plan!==void 0&&!g.includes(e.plan)&&t.push(`plan: one of ${g.join(", ")}`),e.judge!==void 0&&e.judge!==null&&!(Array.isArray(e.roles)&&e.roles.some(n=>n?.id===e.judge))&&t.push("judge: must name one of the roles");const i=y(e.budget);return i.ok||t.push(...i.errors.map(n=>`budget: ${n}`)),{ok:t.length===0,errors:t}}function S(e,{builtin:t=!1}={}){const i=b(e);if(!i.ok)throw new T("INVALID",i.errors.join("; "));return{name:String(e.name),description:String(e.description||"").trim().slice(0,300),plan:g.includes(e.plan)?e.plan:"fixed",merge:p.includes(e.merge)?e.merge:e.judge?"judge":"concat",judge:e.judge||null,roles:e.roles.map(n=>({id:String(n.id),name:String(n.name||n.id).slice(0,60),mode:c.includes(n.mode)?n.mode:"model",prefer:l.includes(n.prefer)?n.prefer:n.engine?$(n.engine):"balanced",...n.model?{model:String(n.model)}:{},...n.agent?{agent:String(n.agent)}:{},...n.engine?{engine:O(n.engine)}:{},prompt:String(n.prompt||"").trim().slice(0,4e3),...n.agent&&!(Array.isArray(n.grants)&&n.grants.length)?{}:{grants:m(n.grants)},...n.recipe?{recipe:String(n.recipe)}:{},...Array.isArray(n.dependsOn)?{dependsOn:n.dependsOn.map(String).filter(s=>s!==n.id)}:{},...Array.isArray(n.skills)&&n.skills.length?{skills:n.skills.map(String).slice(0,32)}:{},...n.workdir?{workdir:String(n.workdir).slice(0,400)}:{},...n.egress==="redacted"||n.egress==="delegated"?{egress:n.egress}:{},...n.memoryScope?{memoryScope:String(n.memoryScope).slice(0,120)}:{}})),budget:x(e.budget),enabled:e.enabled!==!1,...e.origin&&u(e.origin)?{origin:{...e.origin}}:{},...t?{builtin:!0}:{},...e.createdAt?{createdAt:e.createdAt}:{}}}function D(e){return Object.freeze(S(e))}function G(e,t,i=""){const n=m(e);return n.includes("none")||t==="page"?!1:t==="mcp"?n.includes("mcp")||!!i&&n.includes(`mcp:${i}`):n.includes(t)}const w=["read","push","pr","merge"];function B(e,t){const i=m(e),n=w.indexOf(String(t||"").replace(/^scm:/,""));return n<0||i.includes("none")?!1:Math.max(-1,...i.filter(o=>o.startsWith("scm:")).map(o=>w.indexOf(o.slice(4))))>=n}function F(e){const t=e.model||e.prefer||"balanced",i=(e.grants||["none"]).join(", ");return`${e.name||e.id}${e.agent?` (agent: ${e.agent})`:""} — ${t}${e.mode&&e.mode!=="model"?` (${e.mode})`:""} · tools: ${i}`}const z=Object.freeze([{name:"research",description:"Research a question from the web and your own notes, then write it up.",plan:"fixed",merge:"judge",judge:"writer",roles:[{id:"researcher",prompt:"Research the request thoroughly. Search the web and the user's own history. Report each fact as a finding with where it came from; note disagreements between sources.",prefer:"balanced",grants:["web","data"]},{id:"writer",prompt:"Write the answer the user asked for from the board's findings, citing them. Say plainly what was not found.",prefer:"strong",grants:["none"]}],budget:{tokens:4e4,ms:3e5}},{name:"review",description:"Two independent reads of a draft, reconciled into one set of comments.",plan:"fixed",merge:"converge",roles:[{id:"editor",prompt:"Read the draft as an editor: structure, clarity, what is missing. One finding per issue, with the passage it refers to.",prefer:"strong",grants:["none"]},{id:"checker",prompt:"Read the draft as a fact-checker: every claim that could be wrong, with what you checked against. Use the user's history and the web.",prefer:"balanced",grants:["data","web"]}],budget:{tokens:3e4,ms:24e4}},{name:"feature",description:"Architect plans, an Implementer builds on a branch, Reviewer and Tester check, Scribe writes it up. The Architect judges.",plan:"planner",merge:"judge",judge:"architect",roles:[{id:"architect",agent:"architect"},{id:"implementer",agent:"implementer",dependsOn:["architect"]},{id:"reviewer",agent:"reviewer",dependsOn:["implementer"]},{id:"tester",agent:"tester",dependsOn:["implementer"]},{id:"scribe",agent:"scribe",dependsOn:["reviewer","tester"]}],budget:{tokens:4e5,ms:36e5}},{name:"fix",description:"One Implementer fixes it on a branch, the Tester runs the guard, the Scribe notes it.",plan:"fixed",merge:"concat",roles:[{id:"implementer",agent:"implementer"},{id:"tester",agent:"tester",dependsOn:["implementer"]},{id:"scribe",agent:"scribe",dependsOn:["tester"]}],budget:{tokens:15e4,ms:18e5}},{name:"docs",description:"The Architect decides what the docs should say; the Scribe proposes the text.",plan:"fixed",merge:"concat",roles:[{id:"architect",agent:"architect"},{id:"scribe",agent:"scribe",dependsOn:["architect"]}],budget:{tokens:8e4,ms:9e5}},{name:"release",description:"The Tester runs the guard on the merged branch, Release bumps and asks before publishing, the Scribe records the version.",plan:"fixed",merge:"concat",roles:[{id:"tester",agent:"tester"},{id:"release",agent:"release",dependsOn:["tester"]},{id:"scribe",agent:"scribe",dependsOn:["release"]}],budget:{tokens:6e4,ms:18e5}}]);function _(e){return String(e||"").trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^[^a-z]+/,"").replace(/-+$/,"").slice(0,64)}function I(){return z.map(e=>({...e,roles:e.roles.map(t=>({...t,...t.grants?{grants:[...t.grants]}:{},...t.dependsOn?{dependsOn:[...t.dependsOn]}:{}})),budget:{...e.budget}}))}function q(){return{name:"",description:"",plan:"fixed",merge:"concat",judge:null,roles:[{id:"role1",prompt:"",prefer:"balanced",grants:["none"]}],budget:{tokens:2e4,ms:3e5}}}const A=e=>String(Array.isArray(e)?e.join(","):e||"").split(/[,\s]+/).map(t=>t.trim()).filter(Boolean);function C(e){const t=(Array.isArray(e.roles)?e.roles:[]).map(r=>({id:String(r.id||"").trim(),name:String(r.name||"").trim()||void 0,prompt:String(r.prompt||""),prefer:r.prefer||"balanced",...r.model?{model:String(r.model)}:{},...r.agent?{agent:String(r.agent).trim()}:{},...r.engine?{engine:r.engine}:{},...Array.isArray(r.dependsOn)?{dependsOn:r.dependsOn.map(String)}:{},...A(r.grants).length?{grants:A(r.grants)}:r.agent?{}:{grants:["none"]}})),i={};for(const r of["tokens","calls","ms","usd"]){const a=Number(e.budget?.[r]);e.budget?.[r]!==""&&e.budget?.[r]!=null&&Number.isFinite(a)&&a>0&&(i[r]=a)}const n=e.merge||"concat",s={name:_(e.name),description:String(e.description||"").trim(),plan:e.plan||"fixed",merge:n,judge:n==="judge"&&(e.judge||t[t.length-1]?.id)||null,roles:t,budget:i,enabled:e.enabled!==!1,...e.createdAt?{createdAt:e.createdAt}:{}},o=b(s);return o.ok?{ok:!0,team:S(s)}:{ok:!1,errors:o.errors}}export{R as AGENT_REF_RE,N as GRANTABLE,f as GRANT_RE,h as MAX_ROLES,p as MERGE_POLICIES,g as PLAN_MODES,E as ROLE_ID_RE,c as ROLE_MODES,l as ROLE_PREFERS,z as STARTER_TEAMS,k as TEAM_NAME_RE,T as TeamError,M as WORK_GRANTS,q as blankTeam,D as defineTeam,F as describeRole,G as grantAllows,m as normalizeGrants,S as normalizeTeam,B as scmAllows,_ as slugTeamName,I as starterTeams,C as teamFromForm,b as validateTeam};
@@ -0,0 +1,12 @@
1
+ function F(r){const n={};let e=n;const i=String(r||"").split(/\r?\n/);for(let t=0;t<i.length;t++){const s=i[t].trim();if(!s||s.startsWith("#"))continue;const l=/^\[\[\s*(.+?)\s*\]\]\s*(?:#.*)?$/.exec(s);if(l){e=z(n,S(l[1]));continue}const c=/^\[\s*(.+?)\s*\]\s*(?:#.*)?$/.exec(s);if(c){e=W(n,S(c[1]));continue}const f=_(s);if(f<0)continue;const h=S(s.slice(0,f).trim());if(!h.length)continue;let u=s.slice(f+1).trim();const a=/^("""|''')/.exec(u);if(a){const p=a[1],j=u.slice(3),N=j.indexOf(p);let w;if(N>=0)w=j.slice(0,N);else{const k=[j];for(;t+1<i.length;){t+=1;const R=i[t].indexOf(p);if(R>=0){k.push(i[t].slice(0,R));break}k.push(i[t])}w=k.join(`
2
+ `)}q(e,h,P(w,p==='"""'));continue}const b=u[0]==="["?"[":u[0]==="{"?"{":"";if(b){const p=b==="["?"]":"}";for(u=d(u);$(u,b,p)>0&&t+1<i.length;)t+=1,u+=`
3
+ ${d(i[t])}`;q(e,h,b==="["?E(u):O(u));continue}q(e,h,T(d(u).trim()))}return n}function I(r,{header:n=""}={}){const e=[];if(n)for(const i of String(n).split(`
4
+ `))e.push(`# ${i}`.trimEnd());return n&&e.push(""),A(r&&typeof r=="object"?r:{},[],e),`${e.join(`
5
+ `).replace(/\n{3,}/g,`
6
+
7
+ `).trim()}
8
+ `}function A(r,n,e){const i=[],t=[],o=[];for(const[s,l]of Object.entries(r))l!=null&&(m(l)?t.push([s,l]):Array.isArray(l)&&l.length&&l.every(m)?o.push([s,l]):i.push([s,l]));n.length&&(i.length||!t.length&&!o.length)&&e.push(`[${n.map(g).join(".")}]`);for(const[s,l]of i)e.push(`${g(s)} = ${x(l)}`);i.length&&e.push("");for(const[s,l]of t)A(l,[...n,s],e),e.push("");for(const[s,l]of o)for(const c of l){e.push(`[[${[...n,s].map(g).join(".")}]]`);for(const[f,h]of Object.entries(c))h!=null&&(m(h)?A(h,[...n,s,f],e):e.push(`${g(f)} = ${x(h)}`));e.push("")}}const M=/^[A-Za-z0-9_-]+$/,g=r=>M.test(String(r))?String(r):`"${C(String(r))}"`;function x(r){if(typeof r=="boolean")return r?"true":"false";if(typeof r=="number")return Number.isFinite(r)?String(r):"0";if(Array.isArray(r))return`[${r.filter(e=>e!=null).map(x).join(", ")}]`;if(m(r))return`{ ${Object.entries(r).filter(([,e])=>e!=null).map(([e,i])=>`${g(e)} = ${x(i)}`).join(", ")} }`;const n=String(r);return n.includes(`
9
+ `)?`"""
10
+ ${n.replace(/\\/g,"\\\\").replace(/"""/g,'\\"\\"\\"')}"""`:`"${C(n)}"`}function C(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}const m=r=>!!r&&typeof r=="object"&&!Array.isArray(r);function P(r,n){const e=r.replace(/^\r?\n/,"");return n?e.replace(/\\(.)/g,(i,t)=>B(t)):e}function S(r){const n=[];let e="",i="";for(let t=0;t<r.length;t++){const o=r[t];if(i){if(o==="\\"&&i==='"'){e+=B(r[t+1]??""),t+=1;continue}if(o===i){i="";continue}e+=o;continue}if(o==='"'||o==="'"){i=o;continue}if(o==="."){n.push(e.trim()),e="";continue}e+=o}return e.trim()&&n.push(e.trim()),n.filter(Boolean)}function _(r){let n="",e=0;for(let i=0;i<r.length;i++){const t=r[i];if(n){if(t==="\\"&&n==='"'){i+=1;continue}t===n&&(n="");continue}if(t==='"'||t==="'")n=t;else if(t==="["||t==="{")e+=1;else if(t==="]"||t==="}")e-=1;else if(t==="="&&e===0)return i}return-1}function W(r,n){let e=r;for(const i of n){let t=e[i];Array.isArray(t)&&(t=t[t.length-1]),m(t)||(t={},e[i]=t),e=t}return e}function z(r,n){const e=W(r,n.slice(0,-1)),i=n[n.length-1];Array.isArray(e[i])||(e[i]=[]);const t={};return e[i].push(t),t}function q(r,n,e){const i=n.length>1?W(r,n.slice(0,-1)):r;i[n[n.length-1]]=e}function K(r,n){const e=String(r||"").split(/\r?\n/);for(let i=0;i<e.length;i++){const t=new RegExp(`^\\s*${D(n)}\\s*=\\s*(.*)$`).exec(e[i]);if(!t)continue;let o=d(t[1]).trim();if(!o)return"";const s=o[0],l=s==="["?"]":s==="{"?"}":"";if(!l)return o;let c=$(o,s,l);for(;c>0&&i+1<e.length;)i+=1,o+=`
11
+ ${d(e[i])}`,c=$(o,s,l);return o.trim()}return null}function E(r){const n=String(r||"").trim(),e=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n,i=[];let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t+=1;if(t>=e.length)break;const o=e[t];if(o==='"'||o==="'"){const c=y(e,t);i.push(c.value),t=c.next;continue}if(o==="{"||o==="["){const c=o==="{"?"}":"]";let f=t,h=0;for(;f<e.length;f++){const a=$(e.slice(t,f+1),o,c);if(h=a,a===0)break}const u=e.slice(t,Math.min(f+1,e.length));i.push(o==="{"?O(u):E(u)),t=f+1;continue}let s=t;for(;s<e.length&&e[s]!==",";)s+=1;const l=e.slice(t,s).trim();l&&i.push(T(l)),t=s+1}return i}function O(r){const n=String(r||"").trim(),e=n.startsWith("{")&&n.endsWith("}")?n.slice(1,-1):n,i={};let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t+=1;if(t>=e.length)break;let o="";if(e[t]==='"'||e[t]==="'"){const s=y(e,t);o=s.value,t=s.next}else{let s=t;for(;s<e.length&&e[s]!=="="&&e[s]!==":";)s+=1;o=e.slice(t,s).trim(),t=s}for(;t<e.length&&/[\s=:]/.test(e[t]);)t+=1;if(!o)break;if(e[t]==='"'||e[t]==="'"){const s=y(e,t);i[o]=s.value,t=s.next}else if(e[t]==="{"||e[t]==="["){const s=e[t],l=s==="{"?"}":"]";let c=t;for(;c<e.length&&$(e.slice(t,c+1),s,l)!==0;c++);const f=e.slice(t,Math.min(c+1,e.length));i[o]=s==="{"?O(f):E(f),t=c+1}else{let s=t;for(;s<e.length&&e[s]!==",";)s+=1;i[o]=T(e.slice(t,s).trim()),t=s+1}}return i}function T(r){const n=String(r||"").trim().replace(/,+$/,"");return n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?y(n,0).value:n==="true"?!0:n==="false"?!1:/^[+-]?\d+$/.test(n)||/^[+-]?(?:\d+\.\d+|\d+[eE][+-]?\d+|\d+\.\d+[eE][+-]?\d+)$/.test(n)?Number(n):n}function y(r,n){const e=r[n];let i="",t=!1;for(let o=n+1;o<r.length;o++){const s=r[o];if(t){i+=e==='"'?B(s):s,t=!1;continue}if(s==="\\"&&e==='"'){t=!0;continue}if(s===e)return{value:i,next:o+1};i+=s}return{value:i,next:r.length}}function d(r){let n="";for(let e=0;e<r.length;e++){const i=r[e];if(n){i===n&&(n=""),i==="\\"&&n==='"'&&(e+=1);continue}if(i==='"'||i==="'")n=i;else if(i==="#")return r.slice(0,e)}return r}function $(r,n,e){let i=0,t="";for(let o=0;o<r.length;o++){const s=r[o];if(t){s==="\\"&&t==='"'?o+=1:s===t&&(t="");continue}s==='"'||s==="'"?t=s:s===n?i+=1:s===e&&(i-=1)}return i}function B(r){return{n:`
12
+ `,r:"\r",t:" ",'"':'"',"\\":"\\"}[r]??r}function D(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}export{$ as bracketDepth,E as parseArray,O as parseInlineTable,T as parseScalar,F as parseToml,y as readQuoted,I as renderToml,S as splitKeyPath,d as stripComment,K as tomlValue};
package/src/mcp-local.js CHANGED
@@ -1,6 +1,6 @@
1
- import{spawn as R}from"node:child_process";import F from"node:os";import _ from"node:path";import{resolveCommand as G,buildSpawnSpec as J}from"./env.js";import{sandbox as U,refusalsFor as q,track as H}from"./sandbox.js";import{missingCommandMessage as K}from"./events/mcp-errors.js";import{parseSignInPrompt as V,signInError as E,signInFromError as W}from"./events/mcp-signin.js";import{pickProbeTool as Q}from"./events/mcp-launcher.js";import{envLikeArgs as X}from"./events/mcp-config-import.js";const d=new Map,v=new Map,$=10*6e4,Y=6e4,Z=5*6e4,C=Object.freeze({protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"ChatPanel",version:"1.0"}}),nn=150,en=8*6e4,tn=16*6e4,S=4e3;function j(n){const e=F.homedir(),t={};for(const[r,s]of Object.entries(n||{})){const o=String(s);t[r]=o==="~"?e:o.startsWith("~/")?_.join(e,o.slice(2)):o}return t}const x=n=>n.key||`${n.command}\0${(Array.isArray(n.args)?n.args.join(" "):n.args)||""}`,O=n=>JSON.stringify([n.command,Array.isArray(n.args)?n.args:String(n.args||""),n.env||{},n.cwd||null,n.sandbox||null]);function y(n,e){clearTimeout(n.idleTimer);for(const{reject:t,timer:r}of n.pending.values())clearTimeout(r),t(e);n.pending.clear(),d.get(n.key)===n&&d.delete(n.key);try{n.child.kill()}catch{}}function f(n){clearTimeout(n.idleTimer);const e=n.pendingSignIn?Math.max($,tn):$;n.idleTimer=setTimeout(()=>{try{n.child.kill()}catch{}d.delete(n.key)},e)}function rn(n){const e=String(n||"").replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\r/g,`
1
+ import{spawn as B}from"node:child_process";import{registryEnv as G,normalizeRegistries as H}from"./events/registries.js";function F(n){try{return H({npm:n.CHATPANEL_REGISTRY_NPM,pypi:n.CHATPANEL_REGISTRY_PYPI,models:n.CHATPANEL_REGISTRY_MODELS,github:n.CHATPANEL_REGISTRY_GITHUB})}catch{return{}}}import Y from"node:os";import k from"node:path";import{resolveCommand as U,buildSpawnSpec as J}from"./env.js";import{sandbox as q,refusalsFor as K,track as V}from"./sandbox.js";import{missingCommandMessage as W}from"./events/mcp-errors.js";import{parseSignInPrompt as Q,signInError as x,signInFromError as X}from"./events/mcp-signin.js";import{pickProbeTool as Z}from"./events/mcp-launcher.js";import{envLikeArgs as nn}from"./events/mcp-args-env.js";const d=new Map,b=new Map,C=10*6e4,en=6e4,tn=5*6e4,$=Object.freeze({protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"ChatPanel",version:"1.0"}}),rn=150,on=8*6e4,sn=16*6e4,S=4e3;function L(n){const e=Y.homedir(),t={};for(const[i,s]of Object.entries(n||{})){const o=String(s);t[i]=o==="~"?e:o.startsWith("~/")?k.join(e,o.slice(2)):o}return t}const A=n=>n.key||`${n.command}\0${(Array.isArray(n.args)?n.args.join(" "):n.args)||""}`,O=n=>JSON.stringify([n.command,Array.isArray(n.args)?n.args:String(n.args||""),n.env||{},n.cwd||null,n.sandbox||null]);function T(n,e){clearTimeout(n.idleTimer);for(const{reject:t,timer:i}of n.pending.values())clearTimeout(i),t(e);n.pending.clear(),d.get(n.key)===n&&d.delete(n.key);try{n.child.kill()}catch{}}function f(n){clearTimeout(n.idleTimer);const e=n.pendingSignIn?Math.max(C,sn):C;n.idleTimer=setTimeout(()=>{try{n.child.kill()}catch{}d.delete(n.key)},e)}function an(n){const e=String(n||"").replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\r/g,`
2
2
  `).split(`
3
3
  `).map(t=>t.trimEnd()).filter(Boolean).join(`
4
- `).trim();return e?e.length>S?`…${e.slice(-S)}`:e:""}function M(n,e){const t=rn(e?.stderr);return t?`${n}: ${t}`:n}const T=new Map,z=new Set;function wn(){const n=[];for(const e of d.values())e.child.exitCode!=null||e.child.killed||n.push({id:e.key,command:_.basename(String(e.command||"")),pid:e.child.pid??null,sandbox:e.sandbox,commandId:e.commandId,since:e.startedAt,refused:q(e.commandId)});return n}async function L(n){const e=x(n),t=O(n);if(T.has(e)){const o=await T.get(e);if(o.sig===t)return o}const r=d.get(e);if(r&&r.child.exitCode==null&&!r.child.killed){if(r.sig===t)return f(r),r;y(r,new Error("local MCP server restarted: its configuration changed"))}const s=on(n,e,t).finally(()=>T.delete(e));return T.set(e,s),s}async function on(n,e,t=O(n)){const r=G(n.command);if(!r)throw new Error(K(n.command,{platform:process.platform}));const s=Array.isArray(n.args)?n.args:String(n.args||"").split(/\s+/).filter(Boolean),o={};for(const a of X(s)){const l=a.indexOf("=");o[a.slice(0,l).trim()]=a.slice(l+1).trim()}const[p,I,u]=J(r,s,n.cwd||null);u.env={...u.env||process.env,...j(o),...j(n.env||{})},Object.keys(o).length&&console.error(`[bridge] local MCP "${n.command}": ${Object.keys(o).join(", ")} looked like environment variables in Arguments, so they were applied as env too`),u.stdio=["pipe","pipe","pipe"];const c=await U().wrap(p,I,u,{engine:"mcp",cwd:n.cwd||null,commandId:`mcp:${String(e).slice(0,48)}`,...n.sandbox?{grant:n.sandbox}:{}}),[D,N,B]=[c.bin,c.argv,c.opts];c.record.layer==="none"&&!z.has(c.record.reason)&&(z.add(c.record.reason),console.error(`[bridge] local MCP "${n.command}" runs outside a sandbox — ${c.record.reason}`));const g=H(R(D,N,B),c,{kind:"mcp",label:e}),i={key:e,sig:t,child:g,command:n.command,sandbox:c.record,commandId:c.commandId,startedAt:Date.now(),pending:new Map,buf:"",stderr:"",idleTimer:null,initialized:!1,handshake:null,pendingSignIn:null,pendingSignInAt:0,signInIds:null},A=a=>y(i,a);return g.stdout.setEncoding("utf8"),g.stdout.on("data",a=>{i.buf+=a;let l;for(;(l=i.buf.indexOf(`
5
- `))>=0;){const h=i.buf.slice(0,l).trim();if(i.buf=i.buf.slice(l+1),h[0]!=="{"&&h[0]!=="[")continue;let w;try{w=JSON.parse(h)}catch{continue}for(const m of Array.isArray(w)?w:[w]){m&&m.id!=null&&i.signInIds?.has(m.id)&&(i.signInIds.delete(m.id),i.signInIds.size||(i.pendingSignIn=null,i.signedInAt=Date.now(),f(i)));const k=m&&m.id!=null?i.pending.get(m.id):null;k&&(clearTimeout(k.timer),i.pending.delete(m.id),k.resolve(m))}}}),g.stderr.setEncoding("utf8"),g.stderr.on("data",a=>{i.stderr+=a,i.stderr.length>S*2&&(i.stderr=i.stderr.slice(-S*2)),i.pending.size&&(i.promptBuf=((i.promptBuf||"")+a).slice(-2e3),clearTimeout(i.promptTimer),i.promptTimer=setTimeout(()=>{const l=V(i.promptBuf);l&&(i.promptBuf="",sn(i,l))},nn))}),g.on("error",a=>A(new Error(M(`local MCP "${n.command}" failed to start: ${a.message}`,i)))),g.on("close",(a,l)=>{const h=l?`exited with signal ${l}`:a==null?"exited":`exited with code ${a}`;A(new Error(M(`local MCP "${n.command}" ${h}`,i)))}),d.set(e,i),f(i),i}function sn(n,e){if(f(n),e.code&&(n.pendingSignIn=e,n.pendingSignInAt=Date.now(),n.signInIds=new Set(n.pending.keys()),f(n)),e.browser){for(const r of n.pending.values())clearTimeout(r.timer),r.timer=setTimeout(()=>{r.reject(new Error(M("local MCP call timed out waiting for the sign-in",n)))},Z);return}const t=E(e);for(const[r,s]of n.pending)clearTimeout(s.timer),n.pending.delete(r),s.resolve({jsonrpc:"2.0",id:r,error:t})}function P(n,e){const t=()=>n.child.stdin.write(JSON.stringify(e)+`
6
- `);return e.id==null?(t(),Promise.resolve(null)):new Promise((r,s)=>{const o=setTimeout(()=>{n.pending.delete(e.id),s(new Error(M("local MCP call timed out",n)))},Y);n.pending.set(e.id,{resolve:r,reject:s,timer:o}),t()})}function an(n,e){return n.initialized?Promise.resolve():(n.handshake||(n.handshake=(async()=>{const t=await P(n,{jsonrpc:"2.0",id:`cp-init-${Date.now()}`,method:"initialize",params:e});if(t?.error)throw new Error(`local MCP re-initialize failed: ${t.error.message||t.error.code}`);await P(n,{jsonrpc:"2.0",method:"notifications/initialized"}),n.initialized=!0})().finally(()=>{n.handshake=null})),n.handshake)}async function Sn(n,{initializeParams:e=C}={}){const t=await L(n);if(t.pendingSignIn)return{state:"prompt",signIn:t.pendingSignIn,since:t.pendingSignInAt};await b(n,{jsonrpc:"2.0",id:`cp-si-init-${Date.now()}`,method:"initialize",params:e}).catch(()=>{});const s=(await b(n,{jsonrpc:"2.0",id:`cp-si-list-${Date.now()}`,method:"tools/list",params:{}}).catch(()=>null))?.result?.tools||[],o=Q(s);if(!o)return{state:"unsupported",error:"This server declares no read-only tool that takes no arguments, so there is nothing safe to call to make it sign in."};const p=await b(n,{jsonrpc:"2.0",id:`cp-si-${Date.now()}`,method:"tools/call",params:{name:o,arguments:{}}}).catch(u=>({error:{message:String(u?.message||u)}})),I=W(p?.error);return I?{state:"prompt",signIn:I,since:d.get(x(n))?.pendingSignInAt||Date.now(),probe:o}:p?.error?{state:"failed",error:p.error.message||"the server refused",probe:o}:{state:"signed-in",probe:o}}function yn(n){const e=d.get(x(n));return!e||e.child.exitCode!=null?{state:"gone"}:e.pendingSignIn?{state:"prompt",signIn:e.pendingSignIn,since:e.pendingSignInAt}:{state:e.signedInAt?"signed-in":"idle"}}function ln(n){const e=d.get(n);return e?(y(e,new Error("local MCP server stopped")),!0):!1}function Mn(){let n=0;for(const e of[...d.keys()])ln(e)&&(n+=1);return n}function Tn(n){return d.get(n)||null}function bn(n){return v.has(n)}async function b(n,e){if(!n?.command)throw new Error("no command for local MCP server");const t=await L(n);if(f(t),e.method==="initialize")v.set(t.key,e.params||{}),t.initialized=!0;else if(e.method!=="notifications/initialized"){if(e.id!=null&&t.pendingSignIn&&Date.now()-t.pendingSignInAt<en)return{jsonrpc:"2.0",id:e.id,error:E(t.pendingSignIn)};if(e.id!=null&&t.pendingSignIn)return y(t,new Error("local MCP sign-in expired: starting a new one")),b(n,e);t.initialized||await an(t,v.get(t.key)||C)}return P(t,e)}export{Tn as _procForTest,b as callLocalMcp,bn as hasInitParams,wn as localMcpStatus,Sn as signInLocalMcp,yn as signInStatusLocalMcp,Mn as stopAllLocalMcp,ln as stopLocalMcp};
4
+ `).trim();return e?e.length>S?`…${e.slice(-S)}`:e:""}function y(n,e){const t=an(e?.stderr);return t?`${n}: ${t}`:n}const M=new Map,j=new Set;function Mn(){const n=[];for(const e of d.values())e.child.exitCode!=null||e.child.killed||n.push({id:e.key,command:k.basename(String(e.command||"")),pid:e.child.pid??null,sandbox:e.sandbox,commandId:e.commandId,since:e.startedAt,refused:K(e.commandId)});return n}async function z(n){const e=A(n),t=O(n);if(M.has(e)){const o=await M.get(e);if(o.sig===t)return o}const i=d.get(e);if(i&&i.child.exitCode==null&&!i.child.killed){if(i.sig===t)return f(i),i;T(i,new Error("local MCP server restarted: its configuration changed"))}const s=ln(n,e,t).finally(()=>M.delete(e));return M.set(e,s),s}async function ln(n,e,t=O(n)){const i=U(n.command);if(!i)throw new Error(W(n.command,{platform:process.platform}));const s=Array.isArray(n.args)?n.args:String(n.args||"").split(/\s+/).filter(Boolean),o={};for(const a of nn(s)){const l=a.indexOf("=");o[a.slice(0,l).trim()]=a.slice(l+1).trim()}const[p,h,u]=J(i,s,n.cwd||null);u.env={...u.env||process.env,...G(F(u.env||process.env)),...L(o),...L(n.env||{})},Object.keys(o).length&&console.error(`[bridge] local MCP "${n.command}": ${Object.keys(o).join(", ")} looked like environment variables in Arguments, so they were applied as env too`),u.stdio=["pipe","pipe","pipe"];const c=await q().wrap(p,h,u,{engine:"mcp",cwd:n.cwd||null,commandId:`mcp:${String(e).slice(0,48)}`,...n.sandbox?{grant:n.sandbox}:{}}),[N,R,D]=[c.bin,c.argv,c.opts];c.record.layer==="none"&&!j.has(c.record.reason)&&(j.add(c.record.reason),console.error(`[bridge] local MCP "${n.command}" runs outside a sandbox — ${c.record.reason}`));const g=V(B(N,R,D),c,{kind:"mcp",label:e}),r={key:e,sig:t,child:g,command:n.command,sandbox:c.record,commandId:c.commandId,startedAt:Date.now(),pending:new Map,buf:"",stderr:"",idleTimer:null,initialized:!1,handshake:null,pendingSignIn:null,pendingSignInAt:0,signInIds:null},v=a=>T(r,a);return g.stdout.setEncoding("utf8"),g.stdout.on("data",a=>{r.buf+=a;let l;for(;(l=r.buf.indexOf(`
5
+ `))>=0;){const I=r.buf.slice(0,l).trim();if(r.buf=r.buf.slice(l+1),I[0]!=="{"&&I[0]!=="[")continue;let w;try{w=JSON.parse(I)}catch{continue}for(const m of Array.isArray(w)?w:[w]){m&&m.id!=null&&r.signInIds?.has(m.id)&&(r.signInIds.delete(m.id),r.signInIds.size||(r.pendingSignIn=null,r.signedInAt=Date.now(),f(r)));const P=m&&m.id!=null?r.pending.get(m.id):null;P&&(clearTimeout(P.timer),r.pending.delete(m.id),P.resolve(m))}}}),g.stderr.setEncoding("utf8"),g.stderr.on("data",a=>{r.stderr+=a,r.stderr.length>S*2&&(r.stderr=r.stderr.slice(-S*2)),r.pending.size&&(r.promptBuf=((r.promptBuf||"")+a).slice(-2e3),clearTimeout(r.promptTimer),r.promptTimer=setTimeout(()=>{const l=Q(r.promptBuf);l&&(r.promptBuf="",dn(r,l))},rn))}),g.on("error",a=>v(new Error(y(`local MCP "${n.command}" failed to start: ${a.message}`,r)))),g.on("close",(a,l)=>{const I=l?`exited with signal ${l}`:a==null?"exited":`exited with code ${a}`;v(new Error(y(`local MCP "${n.command}" ${I}`,r)))}),d.set(e,r),f(r),r}function dn(n,e){if(f(n),e.code&&(n.pendingSignIn=e,n.pendingSignInAt=Date.now(),n.signInIds=new Set(n.pending.keys()),f(n)),e.browser){for(const i of n.pending.values())clearTimeout(i.timer),i.timer=setTimeout(()=>{i.reject(new Error(y("local MCP call timed out waiting for the sign-in",n)))},tn);return}const t=x(e);for(const[i,s]of n.pending)clearTimeout(s.timer),n.pending.delete(i),s.resolve({jsonrpc:"2.0",id:i,error:t})}function _(n,e){const t=()=>n.child.stdin.write(JSON.stringify(e)+`
6
+ `);return e.id==null?(t(),Promise.resolve(null)):new Promise((i,s)=>{const o=setTimeout(()=>{n.pending.delete(e.id),s(new Error(y("local MCP call timed out",n)))},en);n.pending.set(e.id,{resolve:i,reject:s,timer:o}),t()})}function cn(n,e){return n.initialized?Promise.resolve():(n.handshake||(n.handshake=(async()=>{const t=await _(n,{jsonrpc:"2.0",id:`cp-init-${Date.now()}`,method:"initialize",params:e});if(t?.error)throw new Error(`local MCP re-initialize failed: ${t.error.message||t.error.code}`);await _(n,{jsonrpc:"2.0",method:"notifications/initialized"}),n.initialized=!0})().finally(()=>{n.handshake=null})),n.handshake)}async function En(n,{initializeParams:e=$}={}){const t=await z(n);if(t.pendingSignIn)return{state:"prompt",signIn:t.pendingSignIn,since:t.pendingSignInAt};await E(n,{jsonrpc:"2.0",id:`cp-si-init-${Date.now()}`,method:"initialize",params:e}).catch(()=>{});const s=(await E(n,{jsonrpc:"2.0",id:`cp-si-list-${Date.now()}`,method:"tools/list",params:{}}).catch(()=>null))?.result?.tools||[],o=Z(s);if(!o)return{state:"unsupported",error:"This server declares no read-only tool that takes no arguments, so there is nothing safe to call to make it sign in."};const p=await E(n,{jsonrpc:"2.0",id:`cp-si-${Date.now()}`,method:"tools/call",params:{name:o,arguments:{}}}).catch(u=>({error:{message:String(u?.message||u)}})),h=X(p?.error);return h?{state:"prompt",signIn:h,since:d.get(A(n))?.pendingSignInAt||Date.now(),probe:o}:p?.error?{state:"failed",error:p.error.message||"the server refused",probe:o}:{state:"signed-in",probe:o}}function Pn(n){const e=d.get(A(n));return!e||e.child.exitCode!=null?{state:"gone"}:e.pendingSignIn?{state:"prompt",signIn:e.pendingSignIn,since:e.pendingSignInAt}:{state:e.signedInAt?"signed-in":"idle"}}function mn(n){const e=d.get(n);return e?(T(e,new Error("local MCP server stopped")),!0):!1}function bn(){let n=0;for(const e of[...d.keys()])mn(e)&&(n+=1);return n}function An(n){return d.get(n)||null}function _n(n){return b.has(n)}async function E(n,e){if(!n?.command)throw new Error("no command for local MCP server");const t=await z(n);if(f(t),e.method==="initialize")b.set(t.key,e.params||{}),t.initialized=!0;else if(e.method!=="notifications/initialized"){if(e.id!=null&&t.pendingSignIn&&Date.now()-t.pendingSignInAt<on)return{jsonrpc:"2.0",id:e.id,error:x(t.pendingSignIn)};if(e.id!=null&&t.pendingSignIn)return T(t,new Error("local MCP sign-in expired: starting a new one")),E(n,e);t.initialized||await cn(t,b.get(t.key)||$)}return _(t,e)}export{An as _procForTest,E as callLocalMcp,_n as hasInitParams,Mn as localMcpStatus,En as signInLocalMcp,Pn as signInStatusLocalMcp,bn as stopAllLocalMcp,mn as stopLocalMcp};
@@ -1 +1 @@
1
- import{stripHidden as I,confusablesSkeleton as Z}from"./sanitize.js";const A=/\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]/g,m=Object.freeze(["PERSON","ORG","LOCATION","ADDRESS","EMAIL","PHONE","ID","SSN","IBAN","CREDITCARD","CARD","POST","FAC","GROUP","NRP","ENTITY","KEY","SECRET","TERM","PII","OTHER"]);function K(e){const t=String(e??"").trim().replace(/^\[{1,2}|\]{1,2}$/g,""),n=/^([A-Z][A-Z0-9]*)_\d+$/.exec(t);return!!n&&m.includes(n[1])}const v=/\[{0,2}([A-Z][A-Z0-9]*_\d+)\]{0,2}/g,O=/^(?:[^\n()[\]]|\[\[[A-Z][A-Z0-9]*_\d+\]\])*\]\(/;function _(e,t,n,r){const s=t.startsWith("[[["),o=t.endsWith("]]]");if(!s&&!o)return r;const a=e.slice(n+t.length),l=s&&O.test(o?`]${a}`:a),f=o&&a.startsWith("(");return`${l?"[":""}${r}${f?"]":""}`}function x(){return{byToken:new Map,byValue:new Map,counts:new Map,aliases:new Map}}function L(e){return{entries:[...e?.byToken||new Map].map(([t,n])=>({token:t,value:n})),aliases:[...e?.aliases||new Map].map(([t,n])=>({alias:t,value:n}))}}function w(e){const t=x();for(const{token:n,value:r}of e?.entries||[]){const s=/^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(n);t.byToken.set(n,r),t.byValue.set(r,n),s&&t.counts.set(s[1],Math.max(t.counts.get(s[1])||0,Number(s[2])))}for(const{alias:n,value:r}of e?.aliases||[])t.aliases.set(n,r);return t}function h(e,t,n){const r=e.byValue.get(n);if(r)return r;const s=String(t||"PII").toUpperCase().replace(/[^A-Z0-9]/g,"")||"PII",o=(e.counts.get(s)||0)+1;e.counts.set(s,o);const a=`[[${s}_${o}]]`;return e.byToken.set(a,n),e.byValue.set(n,a),a}function E(e){return String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function k(e){return!(typeof e!="string"||e.length===0||e.length>200||/\([^)]*[+*}][^)]*\)\s*[+*{]/.test(e)||/[+*]\s*[+*]/.test(e))}function N(e,t){if(!t||t.length===0)return e;let n="",r=0;const s=e.length;for(;r<=s;){let o=null,a=null;for(const l of t){l.re.lastIndex=r;const f=l.re.exec(e);if(f&&(o===null||f.index<o.index)&&(o=f,a=l,f.index===r))break}if(!o){n+=e.slice(r);break}n+=e.slice(r,o.index),o[0].length===0?(n+=e[o.index]??"",r=o.index+1):(n+=a.repl(o),r=o.index+o[0].length)}return n}function P(e){let t=0,n=!1;for(let r=e.length-1;r>=0;r--){let s=e.charCodeAt(r)-48;n&&(s*=2,s>9&&(s-=9)),t+=s,n=!n}return t%10===0}function D(e){if(!/^[0-9A-Fa-f:]+$/.test(e)||(e.match(/:/g)||[]).length<2)return!1;const t=e.split(":");return t.some(n=>n.length>4)?!1:e.includes("::")?t.filter(Boolean).length>=1&&t.filter(Boolean).length<=7:t.length===8&&t.every(n=>n.length>=1)}const $=[{type:"SECRET",re:/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----/g},{type:"EMAIL",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{type:"SSN",re:/\b\d{3}[-\s]\d{2}[-\s]\d{4}\b/g},{type:"KEY",re:/\b(?:sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[0-9A-Za-z_]{22,}|xox[baprs]-[A-Za-z0-9-]{10,}|xapp-[0-9]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{35}|[rs]k_(?:live|test)_[0-9A-Za-z]{16,})\b/g},{type:"KEY",re:/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{type:"IP",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{type:"IP",re:/(?<![:\w])(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}(?![:\w])/g,valid:e=>D(e)},{type:"PHONE",re:/(?<![\w.])\+?\d[\d ().-]{6,}\d(?![\w])/g,valid:e=>{const t=e.replace(/\D/g,"");return t.length<7||t.length>15||/^(?:19|20)\d\d[-./](?:0[1-9]|1[0-2])[-./](?:0[1-9]|[12]\d|3[01])(?![\d])/.test(e.trimStart())?!1:/[ ().-]/.test(e)||e.trimStart().startsWith("+")||t.length===10}},{type:"CARD",re:/\b(?:\d[ -]?){13,19}\b/g,valid:e=>{const t=e.replace(/\D/g,"");return t.length>=13&&t.length<=19&&P(t)}}];function b(e,t,{tier:n="basic",entities:r=[],dictionary:s=[],sanitize:o=!0,sanitizeOpts:a=void 0}={}){if(e==null||e==="")return e;let l=o?I(String(e),a):String(e);const f=t||x(),g=n==="full"||n==="entities",y=[];for(const i of s||[]){if(!i)continue;let c;try{c=i.pattern?k(i.pattern)?new RegExp(i.pattern,i.flags&&/g/.test(i.flags)?i.flags:`${i.flags||""}g`):null:i.value?new RegExp(`(?<![\\w])${E(i.value)}(?![\\w])`,"gi"):null}catch{c=null}if(c)if(i.alias!=null&&i.alias!=="")i.value&&f.aliases.set(i.alias,i.value),y.push({re:c,repl:()=>i.alias});else{const u=i.type||(i.pattern?"PII":"TERM");y.push({re:c,repl:p=>h(f,u,p[0])})}}if(l=N(l,y),g){const i=[...r||[]].filter(c=>c&&c.value).sort((c,u)=>String(u.value).length-String(c.value).length);for(const c of i){const u=new RegExp(`(?<![\\w])${E(c.value)}(?![\\w])`,"gi");l=l.replace(u,p=>h(f,c.type||"PERSON",p))}}const R=Z(l),d=[],S=(i,c)=>d.some(u=>i<u.end&&c>u.start);for(const i of $){i.re.lastIndex=0;let c;for(;(c=i.re.exec(R))!==null;){if(c[0].length===0){i.re.lastIndex++;continue}const u=c.index,p=u+c[0].length;i.valid&&!i.valid(c[0])||S(u,p)||d.push({start:u,end:p,type:i.type})}}if(d.length){d.sort((u,p)=>u.start-p.start);let i="",c=0;for(const u of d)i+=l.slice(c,u.start)+h(f,u.type,l.slice(u.start,u.end)),c=u.end;l=i+l.slice(c)}return l}function T(e,t,n){if(e==null||typeof e=="string")return e==null?e:b(e,t,n);if(Array.isArray(e))return e.map(r=>T(r,t,n));if(typeof e=="object"){let r=e;return typeof e.text=="string"&&(r={...r,text:b(e.text,t,n)}),Array.isArray(e.content)&&(r={...r,content:e.content.map(s=>T(s,t,n))}),e.resource&&typeof e.resource=="object"&&typeof e.resource.text=="string"&&(r={...r,resource:{...e.resource,text:b(e.resource.text,t,n)}}),r}return e}function z(e,t){if(e==null||!t)return e;const n=String(e);return n.replace(/\[{0,3}([A-Z][A-Z0-9]*_\d+)\]{0,3}/g,(r,s,o)=>{const a=`[[${s}]]`;return t.byToken.has(a)?_(n,r,o,t.byToken.get(a)):r})}function H(e,t){let n=z(e,t);if(t?.aliases?.size){const r=[...t.aliases.keys()].filter(Boolean).sort((s,o)=>o.length-s.length);if(r.length){const s=new RegExp(`(?<![\\w])(?:${r.map(E).join("|")})(?![\\w])`,"g");n=n.replace(s,o=>t.aliases.has(o)?t.aliases.get(o):o)}}return n}const C=Object.freeze({PERSON:"someone",EMAIL:"an email address",PHONE:"a phone number",ADDRESS:"an address",ORG:"an organisation",URL:"a link",IP:"an IP address",CARD:"a card number",SSN:"an ID number",DATE:"a date",ID:"an identifier"});function V(e,t){const n=String(e??"");if(!n)return{text:n,unresolved:[]};const r=[],s=n.replace(A,(o,a)=>{const l=t?.byToken?.get(o);return l??(r.push(o),C[a]||"redacted")});return A.lastIndex=0,{text:s,unresolved:r}}function Y(e){return A.lastIndex=0,A.test(String(e||""))}function B(e,{includeValues:t=!1,maxPairs:n=200}={}){const r=new Map,s=[];for(const[a,l]of e?.byToken||new Map){const f=/^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(a),g=f?f[1]:"OTHER";r.set(g,(r.get(g)||0)+1),t&&s.length<n&&s.push({token:a,value:l,type:g})}const o=[...r.entries()].map(([a,l])=>({type:a,count:l})).sort((a,l)=>l.count-a.count||a.type.localeCompare(l.type));return{total:o.reduce((a,l)=>a+l.count,0),types:o,...t?{pairs:s}:{}}}function F(e){const t=new Map;for(const r of e||[])for(const s of r?.types||[])t.set(s.type,(t.get(s.type)||0)+s.count);const n=[...t.entries()].map(([r,s])=>({type:r,count:s})).sort((r,s)=>s.count-r.count||r.type.localeCompare(s.type));return{total:n.reduce((r,s)=>r+s.count,0),types:n}}export{m as REDACTION_TOKEN_TYPES,x as createVault,Y as hasToken,K as isRedactionToken,F as mergeRedactionSummaries,T as redactResultShape,b as redactText,B as redactionSummary,z as restoreText,H as restoreWithAliases,V as scrubPlaceholders,w as vaultFromJSON,L as vaultToJSON};
1
+ import{stripHidden as k,confusablesSkeleton as m}from"./sanitize.js";const A=/\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]/g,O=Object.freeze(["PERSON","ORG","LOCATION","ADDRESS","EMAIL","PHONE","ID","SSN","IBAN","CREDITCARD","CARD","POST","FAC","GROUP","NRP","ENTITY","KEY","SECRET","TERM","PII","OTHER"]);function L(e){const t=String(e??"").trim().replace(/^\[{1,2}|\]{1,2}$/g,""),n=/^([A-Z][A-Z0-9]*)_\d+$/.exec(t);return!!n&&O.includes(n[1])}const w=/\[{0,2}([A-Z][A-Z0-9]*_\d+)\]{0,2}/g,_=/^(?:[^\n()[\]]|\[\[[A-Z][A-Z0-9]*_\d+\]\])*\]\(/;function N(e,t,n,r){const s=t.startsWith("[[["),o=t.endsWith("]]]");if(!s&&!o)return r;const i=e.slice(n+t.length),a=s&&_.test(o?`]${i}`:i),f=o&&i.startsWith("(");return`${a?"[":""}${r}${f?"]":""}`}function S(){return{byToken:new Map,byValue:new Map,counts:new Map,aliases:new Map}}function H(e){return{entries:[...e?.byToken||new Map].map(([t,n])=>({token:t,value:n})),aliases:[...e?.aliases||new Map].map(([t,n])=>({alias:t,value:n}))}}function V(e){const t=S();for(const{token:n,value:r}of e?.entries||[]){const s=/^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(n);t.byToken.set(n,r),t.byValue.set(r,n),s&&t.counts.set(s[1],Math.max(t.counts.get(s[1])||0,Number(s[2])))}for(const{alias:n,value:r}of e?.aliases||[])t.aliases.set(n,r);return t}function E(e,t,n){const r=e.byValue.get(n);if(r)return r;const s=String(t||"PII").toUpperCase().replace(/[^A-Z0-9]/g,"")||"PII",o=(e.counts.get(s)||0)+1;e.counts.set(s,o);const i=`[[${s}_${o}]]`;return e.byToken.set(i,n),e.byValue.set(n,i),i}function x(e){return String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function P(e){return!(typeof e!="string"||e.length===0||e.length>200||/\([^)]*[+*}][^)]*\)\s*[+*{]/.test(e)||/[+*]\s*[+*]/.test(e))}function D(e,t){if(!t||t.length===0)return e;let n="",r=0;const s=e.length;for(;r<=s;){let o=null,i=null;for(const a of t){a.re.lastIndex=r;const f=a.re.exec(e);if(f&&(o===null||f.index<o.index)&&(o=f,i=a,f.index===r))break}if(!o){n+=e.slice(r);break}n+=e.slice(r,o.index),o[0].length===0?(n+=e[o.index]??"",r=o.index+1):(n+=i.repl(o),r=o.index+o[0].length)}return n}function $(e){let t=0,n=!1;for(let r=e.length-1;r>=0;r--){let s=e.charCodeAt(r)-48;n&&(s*=2,s>9&&(s-=9)),t+=s,n=!n}return t%10===0}function z(e){if(!/^[0-9A-Fa-f:]+$/.test(e)||(e.match(/:/g)||[]).length<2)return!1;const t=e.split(":");return t.some(n=>n.length>4)?!1:e.includes("::")?t.filter(Boolean).length>=1&&t.filter(Boolean).length<=7:t.length===8&&t.every(n=>n.length>=1)}const C=[{type:"SECRET",re:/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----/g},{type:"EMAIL",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{type:"SSN",re:/\b\d{3}[-\s]\d{2}[-\s]\d{4}\b/g},{type:"KEY",re:/\b(?:sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[0-9A-Za-z_]{22,}|xox[baprs]-[A-Za-z0-9-]{10,}|xapp-[0-9]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{35}|[rs]k_(?:live|test)_[0-9A-Za-z]{16,})\b/g},{type:"KEY",re:/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{type:"IP",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{type:"IP",re:/(?<![:\w])(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}(?![:\w])/g,valid:e=>z(e)},{type:"PHONE",re:/(?<![\w.])\+?\d[\d ().-]{6,}\d(?![\w])/g,valid:e=>{const t=e.replace(/\D/g,"");return t.length<7||t.length>15||/^(?:19|20)\d\d[-./](?:0[1-9]|1[0-2])[-./](?:0[1-9]|[12]\d|3[01])(?![\d])/.test(e.trimStart())?!1:/[ ().-]/.test(e)||e.trimStart().startsWith("+")||t.length===10}},{type:"CARD",re:/\b(?:\d[ -]?){13,19}\b/g,valid:e=>{const t=e.replace(/\D/g,"");return t.length>=13&&t.length<=19&&$(t)}}];function b(e,t,{tier:n="basic",entities:r=[],dictionary:s=[],sanitize:o=!0,sanitizeOpts:i=void 0}={}){if(e==null||e==="")return e;let a=o?k(String(e),i):String(e);const f=t||S(),d=n==="full"||n==="entities",y=[];for(const l of s||[]){if(!l)continue;let c;try{c=l.pattern?P(l.pattern)?new RegExp(l.pattern,l.flags&&/g/.test(l.flags)?l.flags:`${l.flags||""}g`):null:l.value?new RegExp(`(?<![\\w])${x(l.value)}(?![\\w])`,"gi"):null}catch{c=null}if(c)if(l.alias!=null&&l.alias!=="")l.value&&f.aliases.set(l.alias,l.value),y.push({re:c,repl:()=>l.alias});else{const u=l.type||(l.pattern?"PII":"TERM");y.push({re:c,repl:p=>E(f,u,p[0])})}}a=D(a,y);const Z=m(a),g=[],R=(l,c)=>g.some(u=>l<u.end&&c>u.start);for(const l of C){l.re.lastIndex=0;let c;for(;(c=l.re.exec(Z))!==null;){if(c[0].length===0){l.re.lastIndex++;continue}const u=c.index,p=u+c[0].length;l.valid&&!l.valid(c[0])||R(u,p)||g.push({start:u,end:p,type:l.type})}}if(d){const l=[...r||[]].filter(c=>c&&c.value).sort((c,u)=>String(u.value).length-String(c.value).length);for(const c of l){const u=new RegExp(`(?<![\\w])${x(c.value)}(?![\\w])`,"gi");u.lastIndex=0;let p;for(;(p=u.exec(a))!==null;){if(p[0].length===0){u.lastIndex++;continue}const h=p.index,T=h+p[0].length;R(h,T)||g.push({start:h,end:T,type:c.type||"PERSON",token:E(f,c.type||"PERSON",p[0])})}}}if(g.length){g.sort((u,p)=>u.start-p.start);let l="",c=0;for(const u of g)l+=a.slice(c,u.start)+(u.token||E(f,u.type,a.slice(u.start,u.end))),c=u.end;a=l+a.slice(c)}return a}function I(e,t,n){if(e==null||typeof e=="string")return e==null?e:b(e,t,n);if(Array.isArray(e))return e.map(r=>I(r,t,n));if(typeof e=="object"){let r=e;return typeof e.text=="string"&&(r={...r,text:b(e.text,t,n)}),Array.isArray(e.content)&&(r={...r,content:e.content.map(s=>I(s,t,n))}),e.resource&&typeof e.resource=="object"&&typeof e.resource.text=="string"&&(r={...r,resource:{...e.resource,text:b(e.resource.text,t,n)}}),r}return e}function M(e,t){if(e==null||!t)return e;const n=String(e);return n.replace(/\[{0,3}([A-Z][A-Z0-9]*_\d+)\]{0,3}/g,(r,s,o)=>{const i=`[[${s}]]`;return t.byToken.has(i)?N(n,r,o,t.byToken.get(i)):r})}function Y(e,t){let n=M(e,t);if(t?.aliases?.size){const r=[...t.aliases.keys()].filter(Boolean).sort((s,o)=>o.length-s.length);if(r.length){const s=new RegExp(`(?<![\\w])(?:${r.map(x).join("|")})(?![\\w])`,"g");n=n.replace(s,o=>t.aliases.has(o)?t.aliases.get(o):o)}}return n}const K=Object.freeze({PERSON:"someone",EMAIL:"an email address",PHONE:"a phone number",ADDRESS:"an address",ORG:"an organisation",URL:"a link",IP:"an IP address",CARD:"a card number",SSN:"an ID number",DATE:"a date",ID:"an identifier"});function B(e,t){const n=String(e??"");if(!n)return{text:n,unresolved:[]};const r=[],s=n.replace(A,(o,i)=>{const a=t?.byToken?.get(o);return a??(r.push(o),K[i]||"redacted")});return A.lastIndex=0,{text:s,unresolved:r}}function F(e){return A.lastIndex=0,A.test(String(e||""))}function j(e,{includeValues:t=!1,maxPairs:n=200}={}){const r=new Map,s=[];for(const[i,a]of e?.byToken||new Map){const f=/^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(i),d=f?f[1]:"OTHER";r.set(d,(r.get(d)||0)+1),t&&s.length<n&&s.push({token:i,value:a,type:d})}const o=[...r.entries()].map(([i,a])=>({type:i,count:a})).sort((i,a)=>a.count-i.count||i.type.localeCompare(a.type));return{total:o.reduce((i,a)=>i+a.count,0),types:o,...t?{pairs:s}:{}}}function W(e){const t=new Map;for(const r of e||[])for(const s of r?.types||[])t.set(s.type,(t.get(s.type)||0)+s.count);const n=[...t.entries()].map(([r,s])=>({type:r,count:s})).sort((r,s)=>s.count-r.count||r.type.localeCompare(s.type));return{total:n.reduce((r,s)=>r+s.count,0),types:n}}export{O as REDACTION_TOKEN_TYPES,S as createVault,F as hasToken,L as isRedactionToken,W as mergeRedactionSummaries,I as redactResultShape,b as redactText,j as redactionSummary,M as restoreText,Y as restoreWithAliases,B as scrubPlaceholders,V as vaultFromJSON,H as vaultToJSON};
package/src/server.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as ye}from"node:http";import P from"node:os";import{randomBytes as be,randomInt as Se,timingSafeEqual as ke}from"node:crypto";import{mkdirSync as Te,writeFileSync as ve,readFileSync as K,existsSync as Ce}from"node:fs";import{join as H}from"node:path";import*as Ee from"./engines/claude.js";import*as Oe from"./engines/codex.js";import*as xe from"./engines/antigravity.js";import{pi as Ae,opencode as Pe,kiro as $e,copilot as Ie,deepseek as Ne,hermes as Re}from"./engines/cli-agents.js";import{connectorsFor as _e}from"./connectors.js";import*as He from"./engines/custom.js";import{installService as Me,uninstallService as Be,serviceStatus as Ge,restartService as V}from"./service.js";import{skillIndex as W,listRecords as De,readRecord as Ue,readPackageFile as We,skillsHealth as Le,quarantinedSkills as je}from"./skills.js";import{capabilityToolSpecs as Je,runCapabilityTool as Fe}from"./mcp-capabilities.js";import{createSession as Xe,deleteSession as Y,getSession as Q,activeSession as ze,relayToolCall as Ke}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ve,isDefaultWorkdir as Ye,resolveWorkdir as Qe,writeScopeNote as Ze}from"./workdir.js";import{sandbox as Z,runSandboxCli as qe,withGrant as q,acceptRefusalReport as et,liveProcesses as tt}from"./sandbox.js";import{gitState as nt,gitDelta as ot}from"./scm.js";import{listConnections as rt,putConnection as at,removeConnection as it,runEnvFor as st,testConnection as ct,secretBackend as ee}from"./connections.js";import{worktreeFor as te,listWorktrees as lt,removeWorktree as dt,withHook as ut,WORKTREE_ROOT as ne}from"./worktree.js";import{AGENT_CLIS as pt,enrichPath as ht,enrichAgentEnv as mt,findAgentBin as oe,resolveCommand as ft}from"./env.js";import"./sanitize.js";import{checkForUpdate as gt,selfUpdate as re,isEmbedded as wt}from"./update.js";import{callLocalMcp as yt,localMcpStatus as bt,signInLocalMcp as St,signInStatusLocalMcp as kt}from"./mcp-local.js";import{assertPublicHttpUrl as ae,assertPublicWebUrl as ie}from"./ssrf.js";import{startRun as se,endRun as L,cancelRun as Tt,cancelAll as vt}from"./runs.js";import{closeWarmPools as Ct,warmStatus as Et}from"./warm.js";import{CompatError as $,anthropicError as j,anthropicStream as Ot,chatCompletionStream as xt,completionStream as At,createAnthropicMessage as Pt,createChatCompletion as $t,createCompletion as It,createResponse as Nt,openAIError as b,parseAnthropicMessage as Rt,parseChatCompletion as _t,parseCompletion as Ht,parseResponse as Mt,responseStream as Bt}from"./api-compat.js";import{callerTrust as Gt,isPaired as I,parseExtensionIds as Dt,capRunOptions as Ut,engineHonoursReach as Wt,createPairingStore as Lt,formatPairingCode as jt}from"./pii/trust.js";const w="0.21.1",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Ee,label:"Claude Code"},codex:{engine:Oe,label:"Codex"},antigravity:{engine:xe,label:"Antigravity",tools:!1},pi:{engine:Ae,label:"Pi"},opencode:{engine:Pe,label:"OpenCode"},hermes:{engine:Re,label:"Hermes"},kiro:{engine:$e,label:"Kiro"},copilot:{engine:Ie,label:"GitHub Copilot"},deepseek:{engine:Ne,label:"DeepSeek Harness"},custom:{engine:He,label:"Custom",hidden:!0}};function ce(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Jt=Dt(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Gt({origin:n.headers.origin||"",hasToken:pe(n),extensionIds:Jt})),n.chatpanelTrust}function Ft(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Xt(n,e){const t=n.headers.origin||"",r=ce(t);e.setHeader("Access-Control-Allow-Origin",r?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function zt(n){if(!J.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(t)}const R=H(P.homedir(),".chatpanel","bridge-token");let S="";function Kt(){try{Ce(R)&&(S=K(R,"utf8").trim()),S||(S=be(32).toString("hex"),Te(H(P.homedir(),".chatpanel"),{recursive:!0}),ve(R,S,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const le=Lt({random:()=>Se(0,1e6)/1e6});function Vt(n){if(!S)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=le.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Yt(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=le.claim(t?.code);return r.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${N(n)} caller`),i(e,403,{error:r.reason}))}function Qt(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:w})}let M=null;async function de(){if(M)return M;const{createChannelService:n}=await import("./channels/service.js");return M=n({home:H(P.homedir(),".chatpanel"),dataDir:H(P.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),M}async function ue(n,e,t){try{const r=await de(),o=n.method==="POST"?await f(n):{};if(t==="status")return i(e,200,await r.status());if(t==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await r.pair()):t==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?i(e,200,await r.update(o)):t==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function pe(n){if(!S)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const r=Buffer.from(t),o=Buffer.from(S);return r.length===o.length&&ke(r,o)}const Zt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),qt=new Set(["/debug"]),en=n=>qt.has(n);function tn(n,e){if(!zt(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ce(t))return"forbidden origin";const r=n.method==="POST"&&Zt.has(e)||n.method==="GET"&&en(e);return r&&!(Ft(t)||pe(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I(N(n))&&!on.has(e)?nn:null}const nn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",on=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(n,e,t){const r=N(n),o=Ut(t,r);if(!Wt(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=o.reach,s=I(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:o,note:s}}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let r="";n.on("data",o=>{r+=o,r.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){t(o)}}),n.on("error",t)})}async function rn(n){const e=await Promise.all(Object.entries(C).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:d,tools:c}])=>{const l=await s.available().catch(g=>({ok:!1,reason:String(g?.message||g)})),p=await _e(a).catch(()=>[]);return{id:a,label:d,available:l.ok,reason:l.reason,connectors:p,...c===!1?{tools:!1}:{}}})),t=wt()?{current:w,updateAvailable:!1,embedded:"gateway"}:await gt(w).catch(()=>({current:w,updateAvailable:!1})),r=await Le().catch(()=>null),o=await Z().status().catch(a=>({enabled:!1,reason:a.message}));i(n,200,{ok:!0,version:w,agents:e,update:t,workspace:Ve,sandbox:o,localMcp:bt(),processes:tt(),worktrees:ne,secretBackend:ee(),warm:Et(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function an(n,e,t){const{index:r,problems:o}=await W({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:De(r),problems:o})}async function sn(n,e,t){i(n,200,{ok:!0,quarantined:await je(e,t)})}async function cn(n,e,t,r){const{index:o}=await W({extraDirs:t,workdir:r}),a=Ue(o,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function ln(n,e,t,r,o){const{index:a}=await W({extraDirs:r,workdir:o}),s=await We(a,e,t);if(s.error)return i(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(n,200,{ok:!0,...s})}async function dn(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function he(n,e=""){const t=await dn();if(e){const r=t.find(o=>o.id===e);return r?i(n,200,r):i(n,404,b(new $(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function un(n){try{const e=await re(w);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function pn(n,e){let t;try{t=await f(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=F(n,t.agent,t.options||{});if(o.error)return i(e,403,{error:o.error});t.options=o.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
2
+ import{createServer as Te}from"node:http";import E from"node:os";import{randomBytes as Ee,randomInt as ve,timingSafeEqual as Oe}from"node:crypto";import{mkdirSync as Ae,writeFileSync as Ce,readFileSync as Y,existsSync as xe}from"node:fs";import{join as _}from"node:path";import*as Pe from"./engines/claude.js";import*as Re from"./engines/codex.js";import*as Ie from"./engines/antigravity.js";import{pi as $e,opencode as Ne,kiro as De,copilot as _e,deepseek as He,hermes as Me}from"./engines/cli-agents.js";import{connectorsFor as Ue}from"./connectors.js";import*as Be from"./engines/custom.js";import{installService as We,uninstallService as Ge,serviceStatus as Le,restartService as Q}from"./service.js";import{skillIndex as G,listRecords as je,readRecord as Fe,readPackageFile as Je,skillsHealth as Xe,quarantinedSkills as ze,clearSkillCache as L}from"./skills.js";import{writeSkillPackage as Ke,writeSkillFile as Ve,deleteSkillPackage as Ye,SkillWriteError as Qe}from"./skill-write.js";import{agentDefRoots as Ze,scanAgentDefs as qe,listAgentDefs as et,readAgentDef as tt,planAgentExport as nt,exportAgentDef as ot,agentDefsHealth as rt,AgentDefError as at}from"./agent-defs.js";import{capabilityToolSpecs as it,runCapabilityTool as st}from"./mcp-capabilities.js";import{createSession as ct,deleteSession as Z,getSession as q,activeSession as lt,relayToolCall as dt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ut,isDefaultWorkdir as ht,resolveWorkdir as pt,writeScopeNote as ft}from"./workdir.js";import{sandbox as ee,runSandboxCli as mt,withGrant as te,acceptRefusalReport as gt,liveProcesses as yt}from"./sandbox.js";import{gitState as wt,gitDelta as bt}from"./scm.js";import{listConnections as St,putConnection as kt,removeConnection as Tt,runEnvFor as Et,testConnection as vt,secretBackend as ne}from"./connections.js";import{worktreeFor as oe,listWorktrees as Ot,removeWorktree as At,withHook as Ct,WORKTREE_ROOT as re}from"./worktree.js";import{AGENT_CLIS as xt,agentAvailable as Pt,agentInstallDirs as Rt,enrichPath as It,enrichAgentEnv as $t,findAgentBin as Nt,resolveCommand as ae}from"./env.js";import"./sanitize.js";import{checkForUpdate as Dt,selfUpdate as ie,isEmbedded as _t}from"./update.js";import{callLocalMcp as Ht,localMcpStatus as Mt,signInLocalMcp as Ut,signInStatusLocalMcp as Bt}from"./mcp-local.js";import{assertPublicHttpUrl as se,assertPublicWebUrl as ce}from"./ssrf.js";import{startRun as le,endRun as j,cancelRun as Wt,cancelAll as Gt}from"./runs.js";import{closeWarmPools as Lt,warmStatus as jt}from"./warm.js";import{CompatError as R,anthropicError as F,anthropicStream as Ft,chatCompletionStream as Jt,completionStream as Xt,createAnthropicMessage as zt,createChatCompletion as Kt,createCompletion as Vt,createResponse as Yt,openAIError as b,parseAnthropicMessage as Qt,parseChatCompletion as Zt,parseCompletion as qt,parseResponse as en,responseStream as tn}from"./api-compat.js";import{callerTrust as nn,isPaired as I,parseExtensionIds as on,capRunOptions as rn,engineHonoursReach as an,createPairingStore as sn,formatPairingCode as cn}from"./pii/trust.js";const g="0.27.2",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,O={claude:{engine:Pe,label:"Claude Code"},codex:{engine:Re,label:"Codex"},antigravity:{engine:Ie,label:"Antigravity",tools:!1},pi:{engine:$e,label:"Pi"},opencode:{engine:Ne,label:"OpenCode"},hermes:{engine:Me,label:"Hermes"},kiro:{engine:De,label:"Kiro"},copilot:{engine:_e,label:"GitHub Copilot"},deepseek:{engine:He,label:"DeepSeek Harness"},custom:{engine:Be,label:"Custom",hidden:!0}};function de(t){return!t||t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}const ln=on(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function $(t){return t.chatpanelTrust||(t.chatpanelTrust=nn({origin:t.headers.origin||"",hasToken:fe(t),extensionIds:ln})),t.chatpanelTrust}function dn(t){return t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}function un(t,e){const n=t.headers.origin||"",r=de(n);e.setHeader("Access-Control-Allow-Origin",r?n||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function hn(t){if(!J.has(k))return!0;const e=String(t.headers.host||"");if(!e)return!1;const n=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(n)}const N=_(E.homedir(),".chatpanel","bridge-token");let S="";function pn(){try{xe(N)&&(S=Y(N,"utf8").trim()),S||(S=Ee(32).toString("hex"),Ae(_(E.homedir(),".chatpanel"),{recursive:!0}),Ce(N,S,{mode:384}))}catch(t){u("error",`could not initialise bridge token: ${t?.message||t}`)}}const ue=sn({random:()=>ve(0,1e6)/1e6});function fn(t){if(!S)return a(t,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ue.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),a(t,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function mn(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=ue.claim(n?.code);return r.ok?(u("info",`paired a ${$(t)} client${t.headers.origin?` (${t.headers.origin})`:""}`),a(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${$(t)} caller`),a(e,403,{error:r.reason}))}function gn(t,e){const n=$(t);return a(e,200,{ok:!0,trust:n,paired:I(n),version:g})}let H=null;async function he(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:_(E.homedir(),".chatpanel"),dataDir:_(E.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function pe(t,e,n){try{const r=await he(),o=t.method==="POST"?await m(t):{};if(n==="status")return a(e,200,await r.status());if(n==="connect"){const i=await r.connect(o);return a(e,200,{ok:!0,...i})}return n==="pair"?a(e,200,await r.pair()):n==="unpair"?a(e,200,await r.unpair(String(o.actorId||""))):n==="settings"?a(e,200,await r.update(o)):n==="disconnect"?a(e,200,await r.stop({forget:!!o.forget})):a(e,404,{error:"unknown channel action"})}catch(r){return a(e,400,{error:r?.message||String(r)})}}function fe(t){if(!S)return!1;const e=String(t.headers.authorization||""),n=(e.startsWith("Bearer ")?e.slice(7):String(t.headers["x-api-key"]||t.headers["x-chatpanel-token"]||"")).trim();if(!n)return!1;const r=Buffer.from(n),o=Buffer.from(S);return r.length===o.length&&Oe(r,o)}const yn=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),wn=new Set(["/debug"]),bn=t=>wn.has(t),Sn=(t,e)=>t!=="GET"&&t!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function kn(t,e){if(!hn(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!de(n))return"forbidden origin";const r=t.method==="POST"&&yn.has(e)||t.method==="GET"&&bn(e)||Sn(t.method,e);return r&&!(dn(n)||fe(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I($(t))&&!En.has(e)?Tn:null}const Tn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",En=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function X(t,e,n){const r=$(t),o=rn(n,r);if(!an(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const i=o.reach,s=I(r)?i==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":i==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:o,note:s}}function a(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function m(t){return new Promise((e,n)=>{let r="";t.on("data",o=>{r+=o,r.length>50*1024*1024&&n(new Error("Body too large"))}),t.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){n(o)}}),t.on("error",n)})}async function vn(t){const e=await Promise.all(Object.entries(O).filter(([,s])=>!s.hidden).map(async([s,{engine:d,label:c,tools:l}])=>{const h=await d.available().catch(p=>({ok:!1,reason:String(p?.message||p)})),y=await Ue(s).catch(()=>[]);return{id:s,label:c,available:h.ok,reason:h.reason,connectors:y,...l===!1?{tools:!1}:{}}})),n=_t()?{current:g,updateAvailable:!1,embedded:"gateway"}:await Dt(g).catch(()=>({current:g,updateAvailable:!1})),r=await Xe().catch(()=>null),o=await rt().catch(()=>null),i=await ee().status().catch(s=>({enabled:!1,reason:s.message}));a(t,200,{ok:!0,version:g,agents:e,update:n,workspace:ut,sandbox:i,localMcp:Mt(),processes:yt(),worktrees:re,secretBackend:ne(),warm:jt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{},...o?{agentDefs:o}:{}})}async function On(t,e,n){const{index:r,problems:o}=await G({extraDirs:e,workdir:n});a(t,200,{ok:!0,skills:je(r),problems:o})}async function An(t,e,n){a(t,200,{ok:!0,quarantined:await ze(e,n)})}async function Cn(t,e,n,r){const{index:o}=await G({extraDirs:n,workdir:r}),i=Fe(o,e);if(!i)return a(t,404,{ok:!1,error:"unknown skill"});a(t,200,{ok:!0,skill:i})}async function xn(t,e,n,r,o){const{index:i}=await G({extraDirs:r,workdir:o}),s=await Je(i,e,n);if(s.error)return a(t,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});a(t,200,{ok:!0,...s})}async function Pn(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{const r=await Ke({skill:n?.skill,files:n?.files||[],overwrite:!!n?.overwrite});return L(),a(e,200,r)}catch(r){return a(e,z(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function Rn(t,e,n,r){let o;try{o=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}try{const i=await Ve({name:n,path:r,text:o?.text??""});return L(),a(e,200,i)}catch(i){return a(e,z(i),{ok:!1,error:i.message,code:i.code||"ERROR"})}}async function In(t,e){try{const n=await Ye({name:e});return L(),a(t,200,n)}catch(n){return a(t,z(n),{ok:!1,error:n.message,code:n.code||"ERROR"})}}function z(t){return t instanceof Qe?t.code==="NOT_FOUND"?404:t.code==="EXISTS"||t.code==="FULL"?409:t.code==="REFUSED"||t.code==="OUTSIDE"?403:400:400}async function me(t,e){return qe({roots:Ze(process.env,E.homedir(),t,e)})}async function $n(t,e,n){const{index:r,quarantined:o,problems:i}=await me(e,n);a(t,200,{ok:!0,agents:et(r),...o.length?{quarantined:o.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...i.length?{problems:i}:{}})}async function Nn(t,e,n,r){const{index:o}=await me(n,r),i=tt(o,e);if(!i)return a(t,404,{ok:!1,error:"unknown agent definition"});a(t,200,{ok:!0,...i})}async function Dn(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{return a(e,200,{ok:!0,...await nt({agent:n?.agent,to:n?.to})})}catch(r){return a(e,ge(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function _n(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{return a(e,200,await ot({agent:n?.agent,to:n?.to,overwrite:!!n?.overwrite}))}catch(r){return a(e,ge(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}function ge(t){if(t instanceof at){if(t.code==="NOT_OURS")return 409;if(t.code==="TARGET")return 400}return 400}async function Hn(){return(await Promise.all(Object.entries(O).filter(([,e])=>!e.hidden).map(async([e,n])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await n.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...n})=>n)}async function ye(t,e=""){const n=await Hn();if(e){const r=n.find(o=>o.id===e);return r?a(t,200,r):a(t,404,b(new R(`Model "${e}" not found`,404,"model")))}return a(t,200,{object:"list",data:n})}async function Mn(t){try{const e=await ie(g);a(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>Q(),400))}catch(e){a(t,400,{ok:!1,error:String(e?.message||e)})}}async function Un(t,e){let n;try{n=await m(t)}catch(f){return a(e,400,{error:"Bad JSON: "+f.message})}const r=O[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});const o=X(t,n.agent,n.options||{});if(o.error)return a(e,403,{error:o.error});n.options=o.options,Array.isArray(n.images)&&n.images.length&&u("info",`chat: ${n.agent} received ${n.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const i=f=>{e.writableEnded||e.write(`data: ${JSON.stringify(f)}
3
3
 
4
- `)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=se(d),l={signal:c.signal,abort:()=>c.cancel("client")},p=()=>{s=!0,c.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const g=h=>{s||a(h)};a({type:"run",id:d}),o.note&&a({type:"status",text:o.note});let m=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(m=await te({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),m.error){a({type:"error",error:`workspace: ${m.error}`}),L(d),e.writableEnded||e.end();return}}const X=m?m.path:Qe(t.options?.workingDir);let E=null;{const h=X,O=!!m||!Ye(t.options?.workingDir),y=Ze(t.agent,t.options?.permissionMode,h);a({type:"workdir",path:h,isDefault:!O,writeScope:y||void 0}),a({type:"status",text:`Working in ${h}${O?"":" (default)"}`}),y&&a({type:"status",text:y}),E=await nt(h),E&&a({type:"scm",phase:"before",...E})}let U=null;if(E||m){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:O,connection:y}=st({remote:E?.remote||null,grants:h,branch:m?.branch||null,connectionId:t.options?.connectionId||null});U=ut(O),m&&a({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&a({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const z=t.approvals===!0,_={...t.options||{},...m?{workingDir:m.path}:{},...U?{runEnv:U}:{},approvals:z};let A=null;(t.pageTools?.specs?.length||z)&&(A=Xe(g,t.pageTools?.specs||[]),_.permissionSession=A,t.pageTools?.specs?.length&&(_.mcp={url:`http://${k}:${v}/mcp/${A.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));try{await q(_.sandbox,()=>r.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:_,images:Array.isArray(t.images)?t.images:[]},g,{signal:l.signal}))}catch(h){u("error",`${t.agent} chat failed: ${h?.message||h}`),a({type:"error",error:h?.message||String(h)})}finally{if(!s){const h=await ot(X,E).catch(()=>null);h&&g({type:"scm",phase:"after",...h})}L(d),A&&Y(A.id),e.writableEnded||e.end()}}async function hn(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:rt(),secretBackend:ee()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:at(r.connection||r,{token:r.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return o?o[2]==="delete"?i(e,200,{ok:it(o[1])}):i(e,200,ct(o[1],r.remote||"")):i(e,404,{error:"Not found"})}async function mn(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:ne,worktrees:await lt()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/worktrees"){const o=await te({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return i(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(t==="/worktrees/remove"){const o=await dt({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return i(e,o.ok?200:400,o)}return i(e,404,{error:"Not found"})}async function T(n,e,t){const r=C[n.agent];if(!r||r.hidden)throw new $(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const o=await r.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!o.ok)throw new $(o.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=se(a),d=()=>s.cancel("disconnected");t.on("close",d);let c="";try{return await q(n.options?.sandbox,()=>r.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal})),c}finally{t.off("close",d),L(a)}}function B(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
4
+ `)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=le(d),l={signal:c.signal,abort:()=>c.cancel("client")},h=()=>{s=!0,c.cancel("disconnected")};t.on("close",h),e.on("close",h),e.on("error",h);const y=f=>{s||i(f)};i({type:"run",id:d}),o.note&&i({type:"status",text:o.note});let p=null;if(n.options?.workspace&&typeof n.options.workspace=="object"){const f=n.options.workspace;if(p=await oe({repo:f.repo,projectId:f.projectId,jobId:f.jobId,base:f.base||null}),p.error){i({type:"error",error:`workspace: ${p.error}`}),j(d),e.writableEnded||e.end();return}}const K=p?p.path:pt(n.options?.workingDir);let A=null;{const f=K,C=!!p||!ht(n.options?.workingDir),w=ft(n.agent,n.options?.permissionMode,f);i({type:"workdir",path:f,isDefault:!C,writeScope:w||void 0}),i({type:"status",text:`Working in ${f}${C?"":" (default)"}`}),w&&i({type:"status",text:w}),A=await wt(f),A&&i({type:"scm",phase:"before",...A})}let W=null;if(A||p){const f=Array.isArray(n.options?.grants)?n.options.grants:[],{env:C,connection:w}=Et({remote:A?.remote||null,grants:f,branch:p?.branch||null,connectionId:n.options?.connectionId||null});W=Ct(C),p&&i({type:"workspace",path:p.path,branch:p.branch,base:p.base,created:p.created,repo:p.repo,...w?{connection:w}:{}}),w&&i({type:"status",text:`Git credential: ${w.kind} · ${w.host}${w.hasSecret?"":" (no token stored)"} · push: ${C.CHATPANEL_SCM_PUSH==="own"?`${p?.branch} only`:C.CHATPANEL_SCM_PUSH}`})}const V=n.approvals===!0,D={...n.options||{},...p?{workingDir:p.path}:{},...W?{runEnv:W}:{},approvals:V};let P=null;(n.pageTools?.specs?.length||V)&&(P=ct(y,n.pageTools?.specs||[]),D.permissionSession=P,n.pageTools?.specs?.length&&(D.mcp={url:`http://${k}:${v}/mcp/${P.id}`,serverName:"chatpanel_browser",specs:n.pageTools.specs}));try{await te(D.sandbox,()=>r.engine.chat({messages:Array.isArray(n.messages)?n.messages:[],system:n.system||"",options:D,images:Array.isArray(n.images)?n.images:[]},y,{signal:l.signal}))}catch(f){u("error",`${n.agent} chat failed: ${f?.message||f}`),i({type:"error",error:f?.message||String(f)})}finally{if(!s){const f=await bt(K,A).catch(()=>null);f&&y({type:"scm",phase:"after",...f})}j(d),P&&Z(P.id),e.writableEnded||e.end()}}async function Bn(t,e,n){if(t.method==="GET"&&n==="/connections")return a(e,200,{ok:!0,connections:St(),secretBackend:ne()});if(t.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await m(t);if(n==="/connections")try{return a(e,200,{ok:!0,connection:kt(r.connection||r,{token:r.token||null})})}catch(i){return a(e,400,{error:String(i?.message||i)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(n);return o?o[2]==="delete"?a(e,200,{ok:Tt(o[1])}):a(e,200,vt(o[1],r.remote||"")):a(e,404,{error:"Not found"})}async function Wn(t,e,n){if(t.method==="GET"&&n==="/worktrees")return a(e,200,{ok:!0,root:re,worktrees:await Ot()});if(t.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await m(t);if(n==="/worktrees"){const o=await oe({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return a(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(n==="/worktrees/remove"){const o=await At({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return a(e,o.ok?200:400,o)}return a(e,404,{error:"Not found"})}async function T(t,e,n){const r=O[t.agent];if(!r||r.hidden)throw new R(`Unknown ChatPanel agent "${t.agent}"`,400,"model");const o=await r.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!o.ok)throw new R(o.reason||`${t.agent} is unavailable`,503,"model");const i=`run_${Math.random().toString(36).slice(2,10)}`,s=le(i),d=()=>s.cancel("disconnected");n.on("close",d);let c="";try{return await te(t.options?.sandbox,()=>r.engine.chat({messages:t.messages,system:t.system,options:t.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal})),c}finally{n.off("close",d),j(i)}}function M(t){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(t,e){t.writableEnded||t.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
5
5
 
6
- `)}function G(n,e,t){n.writableEnded||n.write(`event: ${e}
7
- data: ${JSON.stringify(t)}
6
+ `)}function U(t,e,n){t.writableEnded||t.write(`event: ${e}
7
+ data: ${JSON.stringify(n)}
8
8
 
9
- `)}async function D(n,e,t,r){try{const o=t(await f(n)),a=F(n,o.agent,o.options||{});if(a.error)throw new $(a.error,403,"permission");return o.options=a.options,o}catch(o){return i(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new $(`Bad JSON: ${o.message}`):o)),null}}async function fn(n,e){const t=await D(n,e,_t,b);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,$t(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}B(e);const r=xt(t.requestedModel,o=>x(e,o));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function gn(n,e){const t=await D(n,e,Ht,b);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,It(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}B(e);const r=At(t.requestedModel,o=>x(e,o));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function wn(n,e){const t=await D(n,e,Mt,b);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,Nt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}B(e);const r=Bt(t.requestedModel,o=>G(e,o.type,o));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...b(o)};G(e,"error",a)}e.end()}async function yn(n,e){const t=await D(n,e,Rt,j);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,Pt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,j(o))}B(e);const r=Ot(t.requestedModel,(o,a)=>G(e,o,a));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){G(e,"error",j(o))}e.end()}async function bn(n,e){let t={};try{t=await f(n)||{}}catch{}const r=String(t.id||"").trim(),o=r?Tt(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function me(n,e,t){let r;try{r=await f(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=t?Q(t):ze(),a=c=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:c})},s=(c,l)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:c,message:l}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return a({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:w}});const d=Je();if(r.method==="tools/list"){const c=o?o.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...d,...c]})}if(r.method==="tools/call"){const c=await Fe(r.params?.name,r.params?.arguments||{});if(c)return a(c);if(!o)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await Ke(o,r.params?.name,r.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function Sn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=t.server||{},o=t.message;if(!r.command||!o)return i(e,400,{error:"need server.command and message"});try{const a=await yt({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox},o);return o.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function kn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=t.server||{};if(!r.command)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const o={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};try{return i(e,200,t.status?kt(o):await St(o))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function Tn(n,e){let t;try{t=await f(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const{url:r,headers:o,message:a}=t||{};if(!r||!a)return i(e,400,{error:"need url and message"});let s;try{s=ae(r)}catch(p){return i(e,400,{error:String(p?.message||p)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[p,g]of Object.entries(o)){const m=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(m)||m.startsWith("x-"))&&(d[p]=String(g))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const p=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(a),redirect:"follow",signal:c.signal});try{p.url&&ae(p.url)}catch(m){return i(e,400,{error:String(m?.message||m)})}const g=await p.text().catch(()=>"");return i(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",authenticate:p.headers.get("WWW-Authenticate")||"",body:g})}catch(p){const g=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${g}`})}finally{clearTimeout(l)}}const fe=256*1024,vn=5,Cn=8e3;async function En(n){let e=ie(n);const t=new AbortController,r=setTimeout(()=>t.abort(),Cn);try{for(let o=0;o<=vn;o++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${w} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=ie(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const s=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:An(await On(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function On(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,fe);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(o+=s.byteLength,r+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(r)||o>=fe))break}}finally{try{await e.cancel()}catch{}}return r}function xn(n){return String(n).replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function An(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?xn(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Pn(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t&&t.url;if(!r||typeof r!="string")return i(e,400,{error:"need url"});try{const o=await En(r);return i(e,200,{title:o.title||null,url:o.url||r})}catch(o){const a=o?.name==="AbortError"?"timed out":String(o?.message||o);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function $n(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=Q(t.session);if(!r)return i(e,404,{error:"no such session"});const o=r.pending.get(t.id);return o?(r.pending.delete(t.id),o.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function In(n,e){let t;try{t=await f(n)}catch(c){return i(e,400,{error:"Bad JSON: "+c.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=String(t.prompt||"").slice(0,6e3);if(!o)return i(e,400,{error:"Empty prompt"});const a=t.model||"",s=F(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const d=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let c="";return typeof r.engine.complete=="function"?c=await r.engine.complete({prompt:o,system:d,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:d,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),i(e,200,{text:(c||"").trim()})}catch(c){return i(e,502,{error:c?.message||String(c)})}}async function Nn(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof r.engine.listModels!="function")return i(e,200,{models:[]});try{const o=await r.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return i(e,502,{error:o?.message||String(o)})}}async function Rn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(t.command||"").trim();if(!r)return i(e,400,{error:"No command"});let o=null;try{o=ft(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}const ge=ye(async(n,e)=>{if(Xt(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const r=tn(n,t.pathname);if(r)return i(e,403,{error:r});try{if(n.method==="GET"&&t.pathname==="/health")return rn(e);const o=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return an(e,o,a);if(n.method==="GET"&&t.pathname==="/skills-quarantined")return sn(e,o,a);if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),d=s.indexOf("/file/");return d===-1?cn(e,decodeURIComponent(s),o,a):ln(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return hn(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return mn(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return he(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return he(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:w,agents:Object.fromEntries(pt.map(d=>[d,s?oe(d)||null:!!oe(d)])),...s?{home:P.homedir(),path:process.env.PATH}:{}})}if(n.method==="POST"&&t.pathname==="/chat")return pn(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Yt(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return Vt(e);if(n.method==="POST"&&t.pathname==="/whoami")return Qt(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return fn(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return gn(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return wn(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return yn(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return me(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const s=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return me(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return Y(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ue(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ue(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return bn(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return $n(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await f(n)}catch{s=null}const d=et(s||{});return e.writeHead(d?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return Sn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return kn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return Tn(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Pn(n,e);if(n.method==="POST"&&t.pathname==="/complete")return In(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Nn(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Rn(n,e);if(n.method==="POST"&&t.pathname==="/update")return un(e);i(e,404,{error:"Not found"})}catch(o){i(e,500,{error:o?.message||String(o)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function _n(n){let e="";const t=[];let r=!1,o=!1;const a=()=>{o&&!r&&!t.length&&process.exit(0)},s=async()=>{if(!r){for(r=!0;t.length;){const d=t.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const p=(await l.text()).trim();p&&process.stdout.write(p+`
9
+ `)}async function B(t,e,n,r){try{const o=n(await m(t)),i=X(t,o.agent,o.options||{});if(i.error)throw new R(i.error,403,"permission");return o.options=i.options,o}catch(o){return a(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new R(`Bad JSON: ${o.message}`):o)),null}}async function Gn(t,e){const n=await B(t,e,Zt,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Kt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=Jt(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function Ln(t,e){const n=await B(t,e,qt,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Vt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=Xt(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function jn(t,e){const n=await B(t,e,en,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Yt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=tn(n.requestedModel,o=>U(e,o.type,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){const i={type:"error",sequence_number:0,...b(o)};U(e,"error",i)}e.end()}async function Fn(t,e){const n=await B(t,e,Qt,F);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,zt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,F(o))}M(e);const r=Ft(n.requestedModel,(o,i)=>U(e,o,i));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){U(e,"error",F(o))}e.end()}async function Jn(t,e){let n={};try{n=await m(t)||{}}catch{}const r=String(n.id||"").trim(),o=r?Wt(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),a(e,200,{ok:!0,cancelled:o})}async function we(t,e,n){let r;try{r=await m(t)}catch{return a(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=n?q(n):lt(),i=c=>{o&&e.setHeader("Mcp-Session-Id",o.id),a(e,200,{jsonrpc:"2.0",id:r.id??null,result:c})},s=(c,l)=>a(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:c,message:l}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return i({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const d=it();if(r.method==="tools/list"){const c=o?o.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return i({tools:[...d,...c]})}if(r.method==="tools/call"){const c=await st(r.params?.name,r.params?.arguments||{});if(c)return i(c);if(!o)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return i(await dt(o,r.params?.name,r.params?.arguments||{}))}catch(l){return i({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function Xn(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=n.server||{},o=n.message;if(!r.command||!o)return a(e,400,{error:"need server.command and message"});try{const i=await Ht({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox},o);return o.id==null?(e.writeHead(202),e.end()):a(e,200,i)}catch(i){return a(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(i?.message||i)}})}}async function zn(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=n.server||{};if(!r.command)return a(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const o={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};try{return a(e,200,n.status?Bt(o):await Ut(o))}catch(i){return a(e,200,{state:"failed",error:String(i?.message||i)})}}async function Kn(t,e){let n;try{n=await m(t)}catch(h){return a(e,400,{error:"Bad JSON: "+h.message})}const{url:r,headers:o,message:i}=n||{};if(!r||!i)return a(e,400,{error:"need url and message"});let s;try{s=se(r)}catch(h){return a(e,400,{error:String(h?.message||h)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[h,y]of Object.entries(o)){const p=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(p)||p.startsWith("x-"))&&(d[h]=String(y))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(i),redirect:"follow",signal:c.signal});try{h.url&&se(h.url)}catch(p){return a(e,400,{error:String(p?.message||p)})}const y=await h.text().catch(()=>"");return a(e,200,{status:h.status,sessionId:h.headers.get("Mcp-Session-Id")||null,contentType:h.headers.get("Content-Type")||"",authenticate:h.headers.get("WWW-Authenticate")||"",body:y})}catch(h){const y=h?.name==="AbortError"?"timed out":String(h?.message||h);return a(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(l)}}const be=256*1024,Vn=5,Yn=8e3;async function Qn(t){let e=ce(t);const n=new AbortController,r=setTimeout(()=>n.abort(),Yn);try{for(let o=0;o<=Vn;o++){const i=await fetch(e.href,{method:"GET",redirect:"manual",signal:n.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${g} (+link-title)`}});if(i.status>=300&&i.status<400&&i.headers.get("location")){if(e=ce(new URL(i.headers.get("location"),e).href),i.body)try{await i.body.cancel()}catch{}continue}if(!i.ok){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}const s=i.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}return{title:eo(await Zn(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function Zn(t){if(!t.body?.getReader)return(await t.text().catch(()=>"")).slice(0,be);const e=t.body.getReader(),n=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:i,value:s}=await e.read();if(i||(o+=s.byteLength,r+=n.decode(s,{stream:!0}),/<\/title\s*>/i.test(r)||o>=be))break}}finally{try{await e.cancel()}catch{}}return r}function qn(t){return String(t).replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(e,n)=>{try{return String.fromCodePoint(+n)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,n)=>{try{return String.fromCodePoint(parseInt(n,16))}catch{return""}})}function eo(t){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(t);return e?qn(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function to(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=n&&n.url;if(!r||typeof r!="string")return a(e,400,{error:"need url"});try{const o=await Qn(r);return a(e,200,{title:o.title||null,url:o.url||r})}catch(o){const i=o?.name==="AbortError"?"timed out":String(o?.message||o);return a(e,400,{error:`couldn't fetch title: ${i}`})}}async function no(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=q(n.session);if(!r)return a(e,404,{error:"no such session"});const o=r.pending.get(n.id);return o?(r.pending.delete(n.id),o.resolve(n.result),a(e,200,{ok:!0})):a(e,404,{error:"no such pending call"})}async function oo(t,e){let n;try{n=await m(t)}catch(c){return a(e,400,{error:"Bad JSON: "+c.message})}const r=O[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});const o=String(n.prompt||"").slice(0,6e3);if(!o)return a(e,400,{error:"Empty prompt"});const i=n.model||"",s=X(t,n.agent,{model:i});if(s.error)return a(e,403,{error:s.error});const d=String(n.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let c="";return typeof r.engine.complete=="function"?c=await r.engine.complete({prompt:o,system:d,model:i}):await r.engine.chat({messages:[{role:"user",content:o}],system:d,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),a(e,200,{text:(c||"").trim()})}catch(c){return a(e,502,{error:c?.message||String(c)})}}async function ro(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=O[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});if(typeof r.engine.listModels!="function")return a(e,200,{models:[]});try{const o=await r.engine.listModels(n.options||{});return a(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return a(e,502,{error:o?.message||String(o)})}}async function ao(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=String(n.command||"").trim();if(!r)return a(e,400,{error:"No command"});let o=null;try{o=ae(r)}catch{o=null}return a(e,200,{ok:!!o,via:o?o.kind:null})}const Se=Te(async(t,e)=>{if(un(t,e),t.method==="OPTIONS")return e.writeHead(204),e.end();let n;try{n=new URL(t.url,`http://${t.headers.host||"127.0.0.1"}`)}catch{return a(e,400,{error:"bad request"})}const r=kn(t,n.pathname);if(r)return a(e,403,{error:r});try{if(t.method==="GET"&&n.pathname==="/health")return vn(e);const o=n.searchParams.getAll("dir"),i=n.searchParams.get("workdir")||"";if(t.method==="GET"&&n.pathname==="/skills")return On(e,o,i);if(t.method==="GET"&&n.pathname==="/skills-quarantined")return An(e,o,i);if(t.method==="GET"&&n.pathname==="/agent-defs")return $n(e,o,i);if(t.method==="POST"&&n.pathname==="/agent-defs/export-plan")return Dn(t,e);if(t.method==="POST"&&n.pathname==="/agent-defs/export")return _n(t,e);if(t.method==="GET"&&n.pathname.startsWith("/agent-defs/"))return Nn(e,decodeURIComponent(n.pathname.slice(12)),o,i);if(t.method==="POST"&&n.pathname==="/skills")return Pn(t,e);if((t.method==="PUT"||t.method==="POST"||t.method==="DELETE")&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?t.method==="DELETE"?In(e,decodeURIComponent(s)):a(e,405,{ok:!1,error:"use POST /skills to save a skill"}):t.method==="DELETE"?a(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):Rn(t,e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)))}if(t.method==="GET"&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?Cn(e,decodeURIComponent(s),o,i):xn(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,i)}if(n.pathname==="/connections"||n.pathname.startsWith("/connections/"))return Bn(t,e,n.pathname);if(n.pathname==="/worktrees"||n.pathname.startsWith("/worktrees/"))return Wn(t,e,n.pathname);if(t.method==="GET"&&n.pathname==="/v1/models")return ye(e);if(t.method==="GET"&&n.pathname.startsWith("/v1/models/"))return ye(e,decodeURIComponent(n.pathname.slice(11)));if(t.method==="GET"&&n.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return a(e,200,{version:g,agents:Object.fromEntries(xt.map(d=>[d,s?Nt(d)||ae(d)?.kind||null:Pt(d)])),...s?{home:E.homedir(),path:process.env.PATH,installDirs:Rt(E.homedir())}:{}})}if(t.method==="POST"&&n.pathname==="/chat")return Un(t,e);if(t.method==="POST"&&n.pathname==="/pair")return mn(t,e);if(t.method==="POST"&&n.pathname==="/pair/code")return fn(e);if(t.method==="POST"&&n.pathname==="/whoami")return gn(t,e);if(t.method==="POST"&&n.pathname==="/v1/chat/completions")return Gn(t,e);if(t.method==="POST"&&n.pathname==="/v1/completions")return Ln(t,e);if(t.method==="POST"&&n.pathname==="/v1/responses")return jn(t,e);if(t.method==="POST"&&n.pathname==="/v1/messages")return Fn(t,e);if(n.pathname==="/mcp"){if(t.method==="POST")return we(t,e,null);if(t.method==="GET")return e.writeHead(405),e.end()}if(n.pathname.startsWith("/mcp/")){const s=decodeURIComponent(n.pathname.slice(5));if(t.method==="POST")return we(t,e,s);if(t.method==="GET")return e.writeHead(405),e.end();if(t.method==="DELETE")return Z(s),e.writeHead(204),e.end()}if(t.method==="GET"&&n.pathname==="/channels")return pe(t,e,"status");if(t.method==="POST"&&n.pathname.startsWith("/channels/"))return pe(t,e,n.pathname.slice(10));if(t.method==="POST"&&n.pathname==="/cancel")return Jn(t,e);if(t.method==="POST"&&n.pathname==="/tool-result")return no(t,e);if(t.method==="POST"&&n.pathname==="/sandbox/refused"){let s=null;try{s=await m(t)}catch{s=null}const d=gt(s||{});return e.writeHead(d?204:403),e.end()}if(t.method==="POST"&&n.pathname==="/mcp-local")return Xn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-local/signin")return zn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-remote")return Kn(t,e);if(t.method==="POST"&&n.pathname==="/fetch-title")return to(t,e);if(t.method==="POST"&&n.pathname==="/complete")return oo(t,e);if(t.method==="POST"&&n.pathname==="/list-models")return ro(t,e);if(t.method==="POST"&&n.pathname==="/agent-check")return ao(t,e);if(t.method==="POST"&&n.pathname==="/update")return Mn(e);a(e,404,{error:"Not found"})}catch(o){a(e,500,{error:o?.message||String(o)})}});function u(t,e){(t==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function io(t){let e="";const n=[];let r=!1,o=!1;const i=()=>{o&&!r&&!n.length&&process.exit(0)},s=async()=>{if(!r){for(r=!0;n.length;){const d=n.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const h=(await l.text()).trim();h&&process.stdout.write(h+`
10
10
  `)}catch(l){c.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:c.id,error:{code:-32e3,message:String(l?.message||l)}})+`
11
- `)}}r=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",d=>{e+=d;let c;for(;(c=e.indexOf(`
12
- `))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&t.push(l)}s()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function Hn(){ht(),mt(),Kt(),ge.on("error",n=>{n&&n.code==="EADDRINUSE"&&(u("error",`Port ${v} is already in use — another app (or a second bridge) has it.`),u("error","Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings."),process.exit(1)),u("error",`bridge server error: ${n?.message||n}`),process.exit(1)});for(const n of["SIGINT","SIGTERM"])process.on(n,()=>{const e=vt("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const t=Ct("shutdown");t&&u("info",`shutdown: closed ${t} warm agent process${t===1?"":"es"}`),Z().close(),setTimeout(()=>process.exit(0),e||t?300:0).unref?.(),!e&&!t&&process.exit(0)});ge.listen(v,k,async()=>{u("info",`listening on http://${k}:${v}`),J.has(k)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:n,label:e,hidden:t}]of Object.entries(C)){if(t)continue;const r=await n.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${e}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),de().then(n=>n.startIfConfigured()).then(n=>{n?.skipped||(n?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${n?.error||"unknown error"}`))}).catch(n=>u("error",`channels: ${n?.message||n}`))})}function Mn(){console.log(`ChatPanel Bridge v${w}
11
+ `)}}r=!1,i()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",d=>{e+=d;let c;for(;(c=e.indexOf(`
12
+ `))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&n.push(l)}s()}),process.stdin.on("end",()=>{o=!0,i()}),process.stdin.resume()}function so(){It(),$t(),pn(),Se.on("error",t=>{t&&t.code==="EADDRINUSE"&&(u("error",`Port ${v} is already in use — another app (or a second bridge) has it.`),u("error","Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings."),process.exit(1)),u("error",`bridge server error: ${t?.message||t}`),process.exit(1)});for(const t of["SIGINT","SIGTERM"])process.on(t,()=>{const e=Gt("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const n=Lt("shutdown");n&&u("info",`shutdown: closed ${n} warm agent process${n===1?"":"es"}`),ee().close(),setTimeout(()=>process.exit(0),e||n?300:0).unref?.(),!e&&!n&&process.exit(0)});Se.listen(v,k,async()=>{u("info",`listening on http://${k}:${v}`),J.has(k)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:t,label:e,hidden:n}]of Object.entries(O)){if(n)continue;const r=await t.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${e}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),he().then(t=>t.startIfConfigured()).then(t=>{t?.skipped||(t?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${t?.error||"unknown error"}`))}).catch(t=>u("error",`channels: ${t?.message||t}`))})}function co(){console.log(`ChatPanel Bridge v${g}
13
13
 
14
14
  Usage:
15
15
  chatpanel-bridge start the bridge (foreground) on ${k}:${v}
@@ -21,4 +21,4 @@ Usage:
21
21
  chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
22
22
  chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
23
23
 
24
- Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function Bn(){const n=process.argv,e=(...t)=>t.some(r=>n.includes(r));if(e("--help","-h"))return Mn(),!0;if(e("--version","-v"))return console.log(w),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=K(R,"utf8").trim()}catch{}const r=`http://${k}:${v}`;try{if(!t)throw new Error(`no token at ${R} — is the bridge running?`);const o=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),a=await o.json().catch(()=>({}));if(!o.ok)throw new Error(a.error||`HTTP ${o.status}`);console.log(`Pairing code: ${jt(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(o){u("error",`could not get a pairing code from the bridge at ${r}: ${o?.message||o}`),process.exitCode=1}})(),!0;if(n.includes("sandbox"))return qe(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{Me(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(t){u("error","Install failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--uninstall")){try{Be(),u("info","Removed the login auto-start.")}catch(t){u("error","Uninstall failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--status")){let t=!1;try{t=Ge()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const we=process.argv.indexOf("--mcp-stdio");if(we>=0){const n=process.argv[we+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),_n(n)}else process.argv.includes("--update")?(async()=>{try{const n=await re(w);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),V()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():Bn()||Hn();
24
+ Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function lo(){const t=process.argv,e=(...n)=>n.some(r=>t.includes(r));if(e("--help","-h"))return co(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("pair","--pair"))return(async()=>{let n="";try{n=Y(N,"utf8").trim()}catch{}const r=`http://${k}:${v}`;try{if(!n)throw new Error(`no token at ${N} — is the bridge running?`);const o=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(2500)}),i=await o.json().catch(()=>({}));if(!o.ok)throw new Error(i.error||`HTTP ${o.status}`);console.log(`Pairing code: ${cn(i.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(o){u("error",`could not get a pairing code from the bridge at ${r}: ${o?.message||o}`),process.exitCode=1}})(),!0;if(t.includes("sandbox"))return mt(t.slice(t.indexOf("sandbox")+1)).then(n=>{process.exitCode=n}),!0;if(e("--install")){try{We(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(n){u("error","Install failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--uninstall")){try{Ge(),u("info","Removed the login auto-start.")}catch(n){u("error","Uninstall failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--status")){let n=!1;try{n=Le()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${n?"installed":"not installed"}`),!0}return!1}const ke=process.argv.indexOf("--mcp-stdio");if(ke>=0){const t=process.argv[ke+1];t||(console.error("--mcp-stdio requires a URL"),process.exit(1)),io(t)}else process.argv.includes("--update")?(async()=>{try{const t=await ie(g);u("info",`Updated v${t.from} → v${t.to}. Restarting the background service…`),Q()}catch(t){u("error","Update failed: "+(t?.message||t)),process.exitCode=1}})():lo()||so();
@@ -0,0 +1 @@
1
+ import{mkdir as p,writeFile as N,rm as A,readdir as P,realpath as k,stat as v}from"node:fs/promises";import{join as $,resolve as b,sep as E}from"node:path";import g from"node:os";import{skillPackagePlan as D,skillFromPlan as L,SKILL_FILE as F}from"./events/skill-package.js";import{scanSkill as U,admits as M,scanSummary as R}from"./events/skill-scan.js";import{skillRoots as B}from"./skills.js";const x=/^[a-z0-9][a-z0-9_-]*$/,I=2*1024*1024,_=500;class i extends Error{constructor(e,r){super(r),this.name="SkillWriteError",this.code=e}}function O(o=process.env,e=g.homedir()){const r=B(o,e).find(c=>c.writable);if(!r)throw new i("NO_ROOT","no writable skill directory is configured");return r.dir}async function C({skill:o,files:e=[],overwrite:r=!1,env:c=process.env,home:s=g.homedir()}={}){const n=O(c,s),t=String(o?.id||"").trim();if(!x.test(t))throw new i("NAME",`"${t}" cannot be a directory name (letters, digits, _ and - only)`);const a=D(o,{files:e}),d=a.reduce((l,u)=>l+Buffer.byteLength(u.text,"utf8"),0);if(d>I)throw new i("SIZE",`${t}: ${Math.round(d/1024)} KB is more than a skill package should be`);const w=L(a,{dirName:t,source:"local"}),f=U({name:w.name,prompt:w.prompt,files:a.map(l=>l.path)});if(!M(f.verdict))throw new i("REFUSED",`${t}: refused before writing — ${R(f)}`);await p(n,{recursive:!0});const m=await k(n);if(await X(m)>=_)throw new i("FULL",`${n} already holds ${_} skills`);const h=$(m,t),S=await v(h).catch(()=>null);if(S&&!r)throw new i("EXISTS",`${t} already exists — pass overwrite to replace it`);if(S&&!S.isDirectory())throw new i("EXISTS",`${t} exists and is not a directory`);await p(h,{recursive:!0}),await y(h,m);for(const l of a){const u=b(h,l.path),T=u.slice(0,u.lastIndexOf(E));await p(T,{recursive:!0}),await y(T,m),await N(u,l.text,"utf8")}return{ok:!0,name:t,dir:h,files:a.map(l=>l.path),skill:w,scan:{verdict:f.verdict,findings:f.findings.length}}}async function G({name:o,path:e,text:r="",env:c=process.env,home:s=g.homedir()}={}){const n=O(c,s),t=String(o||"").trim();if(!x.test(t))throw new i("NAME",`"${t}" is not a skill name`);const a=await k(n).catch(()=>{throw new i("NOT_FOUND","no skills have been written yet")}),d=$(a,t);if(!(await v(d).catch(()=>null))?.isDirectory())throw new i("NOT_FOUND",`${t} is not a skill in ${n}`);if(String(e)===F)throw new i("PATH",`write ${F} by saving the skill, so it is rendered and scanned`);if(D({id:t,name:t,description:"x",prompt:"x"},{files:[{path:e,text:""}]}),Buffer.byteLength(String(r),"utf8")>I)throw new i("SIZE",`${e} is too large for a package file`);const w=b(d,e),f=w.slice(0,w.lastIndexOf(E));return await p(f,{recursive:!0}),await y(f,a),await N(w,String(r),"utf8"),{ok:!0,name:t,path:e}}async function Y({name:o,env:e=process.env,home:r=g.homedir()}={}){const c=O(e,r),s=String(o||"").trim();if(!x.test(s))throw new i("NAME",`"${s}" is not a skill name`);const n=await k(c).catch(()=>null);if(!n)throw new i("NOT_FOUND","no skills have been written yet");const t=$(n,s);if(!(await v(t).catch(()=>null))?.isDirectory())throw new i("NOT_FOUND",`${s} is not a skill in ${c}`);return await y(t,n),await A(t,{recursive:!0,force:!0}),{ok:!0,name:s}}async function y(o,e){const r=await k(o).catch(()=>null);if(!r)throw new i("PATH","that path does not resolve");if(r!==e&&!r.startsWith(e+E))throw new i("OUTSIDE","that path resolves outside the skills directory")}async function X(o){return(await P(o,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).length}export{i as SkillWriteError,Y as deleteSkillPackage,O as writableRoot,G as writeSkillFile,C as writeSkillPackage};
package/src/skills.js CHANGED
@@ -1 +1 @@
1
- import{readFile as v,readdir as H,stat as A,realpath as _}from"node:fs/promises";import{createHash as q}from"node:crypto";import w from"node:os";import{delimiter as T,isAbsolute as L,join as g,resolve as k,sep as O}from"node:path";import{isSafeSkillPath as j,normalizeSkill as W,SKILL_FILE_KINDS as I}from"./events/skill-manifest.js";import{scanSkill as X,admits as B}from"./events/skill-scan.js";const G=512*1024,N=4*1024*1024,C=500,P=3,Z=new Set([".git",".svn",".hg",".cache",".DS_Store","node_modules"]),R=Object.freeze([{source:"local",label:"ChatPanel",segments:[".chatpanel","skills"],writable:!0},{source:"agents-dir",label:"Shared (~/.agents)",segments:[".agents","skills"]},{source:"claude",label:"Claude Code",segments:[".claude","skills"]},{source:"codex",label:"Codex",segments:[".codex","skills"]},{source:"copilot",label:"GitHub Copilot",segments:[".copilot","skills"],projectSegments:[".github","skills"]},{source:"gemini",label:"Antigravity / Gemini",segments:[".gemini","skills"]},{source:"opencode",label:"OpenCode",segments:[".opencode","skills"]},{source:"kiro",label:"Kiro",segments:[".kiro","skills"]},{source:"pi",label:"Pi",segments:[".pi","skills"]},{source:"hermes",label:"Hermes",segments:[".hermes","skills"]}]);function $(t){return(Array.isArray(t)?t:[]).map(e=>String(e||"").trim()).filter(Boolean).filter(e=>L(e)).slice(0,16)}function z(t){const e=String(t||"").trim();if(!e||!L(e))return[];const n=k(e);return R.map(r=>({dir:g(n,...r.projectSegments||r.segments),source:r.source,label:r.label,writable:!1,project:n}))}function D(t=process.env,e=w.homedir(),n=[],r=""){const s=String(t.CHATPANEL_SKILL_DIRS||"").split(/\r?\n/).flatMap(o=>o.split(T)).map(o=>o.trim()).filter(Boolean),i=[...new Set([...s,...$(n)])];return[...z(r),...R.map(o=>({dir:g(e,...o.segments),source:o.source,label:o.label,writable:!!o.writable})),...i.map(o=>({dir:k(o),source:"external",label:"Custom folder",writable:!1}))]}function J(t){const e=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(String(t||""));if(!e)return{meta:{},body:String(t||"")};const n={},r=[{indent:-1,obj:n}];for(const s of e[1].split(/\r?\n/)){if(!s.trim()||s.trim().startsWith("#"))continue;const i=s.length-s.trimStart().length,o=s.trim(),l=/^([A-Za-z_][\w.-]*)\s*:\s*(.*)$/.exec(o);if(!l)continue;for(;r.length>1&&i<=r[r.length-1].indent;)r.pop();const c=r[r.length-1].obj,[,a,u]=l;if(u===""){const p={};c[a]=p,r.push({indent:i,obj:p});continue}c[a]=Q(u)}return{meta:n,body:String(t).slice(e[0].length)}}function Q(t){const e=t.trim().replace(/\s+#.*$/,"").trim();return/^\[.*\]$/.test(e)?e.slice(1,-1).split(",").map(n=>F(n.trim())).filter(Boolean):e==="true"?!0:e==="false"?!1:F(e)}const F=t=>/^(['"]).*\1$/.test(t)?t.slice(1,-1):t,K=/^[a-z0-9][a-z0-9_-]*$/;function U({meta:t,body:e,dirName:n,relPath:r,source:s,files:i,hash:o}){const l=typeof t.name=="string"&&t.name.trim()?t.name.trim():n,c=K.test(String(l))?String(l):n,a={};for(const u of I){const p=i.filter(m=>m.startsWith(`${u}/`)).map(m=>m.slice(u.length+1));p.length&&(a[u]=p)}return W({id:c,name:String(l),command:K.test(c)?c:"",description:typeof t.description=="string"?t.description:"",prompt:e.trim(),...typeof t.version=="string"?{version:t.version}:{},...Array.isArray(t.platforms)?{platforms:t.platforms}:{},...Object.keys(a).length?{files:a}:{},origin:{source:s,id:r,hash:o}})}function V(t,e=process.platform){const n=t?.platforms;if(!Array.isArray(n)||!n.length)return!0;const r=e==="darwin"?"macos":e==="win32"?"windows":"linux";return n.includes(r)}async function M(t){try{return await H(t,{withFileTypes:!0})}catch{return[]}}async function Y(t){const e=[];for(const n of I)for(const r of await M(g(t,n))){if(!r.isFile())continue;const s=`${n}/${r.name}`;if(j(s)&&e.push(s),e.length>=200)return e}return e}async function tt(t,e,n){let r;try{const p=await A(g(t,"SKILL.md"));if(!p.isFile()||p.size>G)return null;r=await v(g(t,"SKILL.md"),"utf8")}catch{return null}const{meta:s,body:i}=J(r),o=`sha256-${q("sha256").update(r).digest("hex").slice(0,32)}`,l=e.split("/").pop(),c=await Y(t),a=U({meta:s,body:i,dirName:l,relPath:e,source:n,files:c,hash:o}),u=X({name:a.name,prompt:a.prompt,files:c||[]});return a.origin={...a.origin,scanned:{verdict:u.verdict,scanner:u.scanner,findings:u.findings.length}},{skill:a,dir:t,scan:u}}async function et({roots:t,extraDirs:e=[],workdir:n="",platform:r=process.platform}={}){t=t||D(process.env,w.homedir(),e,n);const s=new Map,i=[],o=[];for(const{dir:l,source:c,project:a}of t){const u=async(p,m,b)=>{if(!(s.size>=C||b>P))for(const d of await M(p)){if(s.size>=C)return;if(!d.isDirectory()||Z.has(d.name))continue;const S=m?`${m}/${d.name}`:d.name,y=g(p,d.name),f=d.name.startsWith(".")?null:await tt(y,S,c).catch(x=>(i.push({path:S,reason:String(x?.message||x)}),null));f?B(f.scan?.verdict)?!s.has(f.skill.id)&&V(f.skill,r)&&(a&&(f.skill.origin={...f.skill.origin,project:a}),s.set(f.skill.id,{...f,root:l,source:c})):o.push({id:f.skill.id,path:S,verdict:f.scan.verdict,findings:f.scan.findings}):await u(y,S,b+1)}};await u(l,"",1)}return{index:s,problems:i,quarantined:o}}function ct(t){return[...t.values()].map(({skill:e})=>{const{prompt:n,...r}=e;return{...r,promptChars:(n||"").length}})}function ut(t,e){const n=t.get(String(e||""));return n?n.skill:null}async function pt(t,e,n){const r=t.get(String(e||""));if(!r)return{error:"unknown skill"};if(!j(n))return{error:"unsafe path"};if(String(n).split("/")[0]==="scripts")return{error:"scripts are not readable as text"};const s=k(r.dir,n);let i;try{i=await _(s)}catch{return{error:"not found"}}const o=await _(r.dir).catch(()=>r.dir);if(i!==o&&!i.startsWith(o+O))return{error:"outside package"};const l=await A(i).catch(()=>null);return l?.isFile()?l.size>N?{error:"file too large"}:{path:n,text:await v(i,"utf8")}:{error:"not found"}}const nt=5e3;let h=null;async function E({force:t=!1,now:e=Date.now,extraDirs:n=[],workdir:r=""}={}){const s=e(),o=[z(r)[0]?.project||"",...$(n).map(c=>k(c)).sort()].join("|");if(!t&&h&&h.key===o&&s-h.at<nt)return h.value;const l=await et({extraDirs:n,workdir:r});return h={at:s,key:o,value:l},l}function ft(){h=null}async function mt(t=[]){const{index:e,problems:n,quarantined:r}=await E({extraDirs:t}),s=new Set([...e.values()].map(i=>i.root));return{count:e.size,roots:D(process.env,w.homedir(),t).filter(i=>s.has(i.dir)).map(i=>i.dir),sources:[...new Set([...e.values()].map(i=>i.source))].sort(),...n.length?{problems:n.length}:{},...r?.length?{quarantined:r.length}:{}}}async function dt(t=[],e=""){const{quarantined:n}=await E({extraDirs:t,workdir:e});return n||[]}export{R as AGENT_SKILL_DIRS,ft as clearSkillCache,ct as listRecords,J as parseFrontmatter,V as platformOk,z as projectSkillRoots,dt as quarantinedSkills,pt as readPackageFile,ut as readRecord,et as scanSkills,E as skillIndex,U as skillRecord,D as skillRoots,mt as skillsHealth};
1
+ import{readFile as v,readdir as E,stat as L,realpath as _}from"node:fs/promises";import{createHash as H}from"node:crypto";import S from"node:os";import{delimiter as $,isAbsolute as A,join as f,resolve as k,sep as q}from"node:path";import{isSafeSkillPath as I,SKILL_FILE_KINDS as T}from"./events/skill-manifest.js";import{skillFromPackage as N}from"./events/skill-package.js";import{parseFrontmatter as C}from"./events/frontmatter.js";import{scanSkill as P,admits as X}from"./events/skill-scan.js";const G=512*1024,O=4*1024*1024,j=500,B=3,W=new Set([".git",".svn",".hg",".cache",".DS_Store","node_modules"]),F=Object.freeze([{source:"local",label:"ChatPanel",segments:[".chatpanel","skills"],writable:!0},{source:"agents-dir",label:"Shared (~/.agents)",segments:[".agents","skills"]},{source:"claude",label:"Claude Code",segments:[".claude","skills"]},{source:"codex",label:"Codex",segments:[".codex","skills"]},{source:"copilot",label:"GitHub Copilot",segments:[".copilot","skills"],projectSegments:[".github","skills"]},{source:"gemini",label:"Antigravity / Gemini",segments:[".gemini","skills"]},{source:"opencode",label:"OpenCode",segments:[".opencode","skills"]},{source:"kiro",label:"Kiro",segments:[".kiro","skills"]},{source:"pi",label:"Pi",segments:[".pi","skills"]},{source:"hermes",label:"Hermes",segments:[".hermes","skills"]}]);function R(t){return(Array.isArray(t)?t:[]).map(e=>String(e||"").trim()).filter(Boolean).filter(e=>A(e)).slice(0,16)}function D(t){const e=String(t||"").trim();if(!e||!A(e))return[];const r=k(e);return F.map(n=>({dir:f(r,...n.projectSegments||n.segments),source:n.source,label:n.label,writable:!1,project:r}))}function K(t=process.env,e=S.homedir(),r=[],n=""){const o=String(t.CHATPANEL_SKILL_DIRS||"").split(/\r?\n/).flatMap(i=>i.split($)).map(i=>i.trim()).filter(Boolean),s=[...new Set([...o,...R(r)])];return[...D(n),...F.map(i=>({dir:f(e,...i.segments),source:i.source,label:i.label,writable:!!i.writable})),...s.map(i=>({dir:k(i),source:"external",label:"Custom folder",writable:!1}))]}const ce=/^[a-z0-9][a-z0-9_-]*$/,J=N;function Q(t,e=process.platform){const r=t?.platforms;if(!Array.isArray(r)||!r.length)return!0;const n=e==="darwin"?"macos":e==="win32"?"windows":"linux";return r.includes(n)}async function z(t){try{return await E(t,{withFileTypes:!0})}catch{return[]}}async function U(t){const e=[];for(const r of T)for(const n of await z(f(t,r))){if(!n.isFile())continue;const o=`${r}/${n.name}`;if(I(o)&&e.push(o),e.length>=200)return e}return e}async function V(t,e,r){let n;try{const g=await L(f(t,"SKILL.md"));if(!g.isFile()||g.size>G)return null;n=await v(f(t,"SKILL.md"),"utf8")}catch{return null}const{meta:o,body:s}=C(n),i=`sha256-${H("sha256").update(n).digest("hex").slice(0,32)}`,l=e.split("/").pop(),u=await U(t),c=J({meta:o,body:s,dirName:l,relPath:e,source:r,files:u,hash:i}),p=P({name:c.name,prompt:c.prompt,files:u||[]});return c.origin={...c.origin,scanned:{verdict:p.verdict,scanner:p.scanner,findings:p.findings.length}},{skill:c,dir:t,scan:p}}async function Y({roots:t,extraDirs:e=[],workdir:r="",platform:n=process.platform}={}){t=t||K(process.env,S.homedir(),e,r);const o=new Map,s=[],i=[];for(const{dir:l,source:u,project:c}of t){const p=async(g,w,b)=>{if(!(o.size>=j||b>B))for(const m of await z(g)){if(o.size>=j)return;if(!m.isDirectory()||W.has(m.name))continue;const h=w?`${w}/${m.name}`:m.name,x=f(g,m.name),a=m.name.startsWith(".")?null:await V(x,h,u).catch(y=>(s.push({path:h,reason:String(y?.message||y)}),null));a?X(a.scan?.verdict)?!o.has(a.skill.id)&&Q(a.skill,n)&&(c&&(a.skill.origin={...a.skill.origin,project:c}),o.set(a.skill.id,{...a,root:l,source:u})):i.push({id:a.skill.id,path:h,verdict:a.scan.verdict,findings:a.scan.findings}):await p(x,h,b+1)}};await p(l,"",1)}return{index:o,problems:s,quarantined:i}}function ue(t){return[...t.values()].map(({skill:e})=>{const{prompt:r,...n}=e;return{...n,promptChars:(r||"").length}})}function pe(t,e){const r=t.get(String(e||""));return r?r.skill:null}async function me(t,e,r){const n=t.get(String(e||""));if(!n)return{error:"unknown skill"};if(!I(r))return{error:"unsafe path"};if(String(r).split("/")[0]==="scripts")return{error:"scripts are not readable as text"};const o=k(n.dir,r);let s;try{s=await _(o)}catch{return{error:"not found"}}const i=await _(n.dir).catch(()=>n.dir);if(s!==i&&!s.startsWith(i+q))return{error:"outside package"};const l=await L(s).catch(()=>null);return l?.isFile()?l.size>O?{error:"file too large"}:{path:r,text:await v(s,"utf8")}:{error:"not found"}}const Z=5e3;let d=null;async function M({force:t=!1,now:e=Date.now,extraDirs:r=[],workdir:n=""}={}){const o=e(),i=[D(n)[0]?.project||"",...R(r).map(u=>k(u)).sort()].join("|");if(!t&&d&&d.key===i&&o-d.at<Z)return d.value;const l=await Y({extraDirs:r,workdir:n});return d={at:o,key:i,value:l},l}function fe(){d=null}async function de(t=[]){const{index:e,problems:r,quarantined:n}=await M({extraDirs:t}),o=new Set([...e.values()].map(s=>s.root));return{count:e.size,roots:K(process.env,S.homedir(),t).filter(s=>o.has(s.dir)).map(s=>s.dir),sources:[...new Set([...e.values()].map(s=>s.source))].sort(),...r.length?{problems:r.length}:{},...n?.length?{quarantined:n.length}:{}}}async function ge(t=[],e=""){const{quarantined:r}=await M({extraDirs:t,workdir:e});return r||[]}export{F as AGENT_SKILL_DIRS,fe as clearSkillCache,ue as listRecords,C as parseFrontmatter,Q as platformOk,D as projectSkillRoots,ge as quarantinedSkills,me as readPackageFile,pe as readRecord,Y as scanSkills,M as skillIndex,J as skillRecord,K as skillRoots,de as skillsHealth};