blade-code 0.10.75 → 0.10.76

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.
Files changed (104) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-rjgfy07e.js → chunk-01k69v34.js} +2 -2
  3. package/dist/chunk-0z6fn1mt.js +1 -0
  4. package/dist/chunk-25q79gk4.js +6 -0
  5. package/dist/chunk-2nnfx3s7.js +1 -0
  6. package/dist/{chunk-h4d37zt2.js → chunk-426sb4tk.js} +1 -1
  7. package/dist/chunk-5b0tejhz.js +1 -0
  8. package/dist/{chunk-5tat9wy9.js → chunk-625krpnt.js} +1 -1
  9. package/dist/{chunk-g3fbgp1k.js → chunk-66w68q81.js} +44 -42
  10. package/dist/{chunk-gbrwzpyg.js → chunk-68stvfdj.js} +2 -2
  11. package/dist/{chunk-57jj40er.js → chunk-6h3x4jv0.js} +2 -2
  12. package/dist/chunk-6r150c8y.js +1 -0
  13. package/dist/{chunk-p7ww2tcn.js → chunk-79cxktz1.js} +1 -1
  14. package/dist/{chunk-rc7jnds2.js → chunk-8bsse16j.js} +1 -1
  15. package/dist/{chunk-kb5xaar0.js → chunk-8chhdkg2.js} +445 -444
  16. package/dist/{chunk-v4ek6q8t.js → chunk-90yjhvjb.js} +1 -1
  17. package/dist/{chunk-1zwq624e.js → chunk-9dspha54.js} +2 -2
  18. package/dist/chunk-9eah1889.js +1 -0
  19. package/dist/{chunk-22aaybx2.js → chunk-9fm80wbr.js} +1 -1
  20. package/dist/{chunk-egp0crrc.js → chunk-9k3tg2hs.js} +3 -3
  21. package/dist/{chunk-qp8mejbn.js → chunk-9ra452yc.js} +1 -1
  22. package/dist/chunk-9tcrrjzg.js +1 -0
  23. package/dist/{chunk-qw5j84ny.js → chunk-9x141v5g.js} +2 -2
  24. package/dist/{chunk-m6yfwyva.js → chunk-abzn9eba.js} +1 -1
  25. package/dist/{chunk-2v10cw32.js → chunk-aq15mcwm.js} +1 -1
  26. package/dist/chunk-bpf84msg.js +1 -0
  27. package/dist/{chunk-99nevk7k.js → chunk-bvhbc0wr.js} +1 -1
  28. package/dist/chunk-c074qee7.js +1 -0
  29. package/dist/chunk-c80pzvhs.js +2 -0
  30. package/dist/{chunk-xkz9ecdx.js → chunk-c9e0fbyh.js} +1 -1
  31. package/dist/{chunk-yk8s8kjt.js → chunk-cgd0vjw2.js} +2 -2
  32. package/dist/{chunk-n0x5z56v.js → chunk-chmf8s1j.js} +2 -2
  33. package/dist/chunk-ckvq6z49.js +1 -0
  34. package/dist/chunk-d8gn6hw5.js +1 -0
  35. package/dist/{chunk-hzy5jzkp.js → chunk-db2v383v.js} +1 -1
  36. package/dist/chunk-eesa8c5h.js +2 -0
  37. package/dist/chunk-egv5k7t5.js +1 -0
  38. package/dist/{chunk-fj297dmj.js → chunk-ehks2r00.js} +1 -1
  39. package/dist/chunk-et3d69av.js +1 -0
  40. package/dist/{chunk-yz80dp1a.js → chunk-fmkntp49.js} +2 -2
  41. package/dist/{chunk-nfyxb2q5.js → chunk-gpxvyxz1.js} +1 -1
  42. package/dist/{chunk-pdansrbx.js → chunk-gx1wx7z5.js} +1 -1
  43. package/dist/{chunk-6bka1j4q.js → chunk-h0ys86rn.js} +1 -1
  44. package/dist/{chunk-s7gf2ds9.js → chunk-j67n7v73.js} +2 -2
  45. package/dist/{chunk-c03xn5s3.js → chunk-js4aekf1.js} +1 -1
  46. package/dist/{chunk-xbj18hxh.js → chunk-js4vqnds.js} +1 -1
  47. package/dist/{chunk-c74e0jx1.js → chunk-kxgr18gy.js} +2 -2
  48. package/dist/chunk-mjq7rrq1.js +1 -0
  49. package/dist/{chunk-0cbpjhq7.js → chunk-n5d0d6q7.js} +1 -1
  50. package/dist/{chunk-03947xkg.js → chunk-psy247es.js} +1 -1
  51. package/dist/{chunk-qtt17d5s.js → chunk-qnj3dajb.js} +1 -1
  52. package/dist/{chunk-4ppgfhqd.js → chunk-r8ayexxd.js} +2 -2
  53. package/dist/{chunk-fbgzeb3m.js → chunk-r8wbvxn7.js} +1 -1
  54. package/dist/{chunk-qyxbee3w.js → chunk-skw3b17a.js} +1 -1
  55. package/dist/chunk-t1bvxk3s.js +2 -0
  56. package/dist/{chunk-44zkyzrj.js → chunk-tnaxxgje.js} +1 -1
  57. package/dist/chunk-tppvhg2n.js +1 -0
  58. package/dist/{chunk-agxs6rwh.js → chunk-ts96epcd.js} +1 -1
  59. package/dist/{chunk-zph2jekm.js → chunk-tssmnn37.js} +2 -2
  60. package/dist/{chunk-22sw5bv4.js → chunk-ttbq1xmz.js} +2 -2
  61. package/dist/{chunk-r297pq3s.js → chunk-vdtma2yq.js} +2 -2
  62. package/dist/{chunk-bj5msq36.js → chunk-vn1r6z64.js} +1 -1
  63. package/dist/{chunk-rdtgv0n8.js → chunk-vpn2e8tj.js} +30 -24
  64. package/dist/{chunk-d2eahefk.js → chunk-vwa2kczj.js} +2 -2
  65. package/dist/{chunk-2faga011.js → chunk-wx9zxzgm.js} +2 -2
  66. package/dist/{chunk-tnjq10zs.js → chunk-xmty01x3.js} +1 -1
  67. package/dist/{chunk-1zkwxaa0.js → chunk-yg7cacsc.js} +1 -1
  68. package/dist/{chunk-xts31qj4.js → chunk-yhyqcmh1.js} +2 -2
  69. package/dist/{chunk-2qqmmxqf.js → chunk-z37v80c1.js} +2 -2
  70. package/dist/chunk-zjfdj7be.js +10 -0
  71. package/dist/{chunk-gz2fx7th.js → chunk-zk34d9mm.js} +2 -2
  72. package/dist/{chunk-m88zk362.js → chunk-zvpr8s8r.js} +2 -2
  73. package/dist/{chunk-2m4mgw58.js → chunk-zwd5q6dt.js} +2 -2
  74. package/dist/web/assets/{ChatView-Bjl8VJFM.js → ChatView-tu6nu0Yw.js} +5 -5
  75. package/dist/web/assets/{CodeBlockHighlighter-i8Yc4Qe4.js → CodeBlockHighlighter-DFj0ZWq6.js} +1 -1
  76. package/dist/web/assets/{FilePreview-DbU1IMtz.js → FilePreview-CLJNHlXO.js} +1 -1
  77. package/dist/web/assets/{KanbanBoard-Fe4qkgpi.js → KanbanBoard-B63UlcNr.js} +1 -1
  78. package/dist/web/assets/{MarkdownRenderer-CdeC66uL.js → MarkdownRenderer-D7ap0LLK.js} +3 -3
  79. package/dist/web/assets/{SettingsModal-mbG701yW.js → SettingsModal-B8Gp0bXw.js} +1 -1
  80. package/dist/web/assets/{TaskSwitcher-DF-q_rMi.js → TaskSwitcher-gxALR-zu.js} +1 -1
  81. package/dist/web/assets/{TerminalPanel-BxAmwOXK.js → TerminalPanel-dnC4oh4w.js} +1 -1
  82. package/dist/web/assets/{index-BTj86SSJ.js → index-Dn4vZglG.js} +3 -3
  83. package/dist/web/assets/{teamService-Cnno2N5h.js → teamService-CoJLtqAq.js} +1 -1
  84. package/dist/web/index.html +1 -1
  85. package/package.json +1 -1
  86. package/dist/chunk-0jmvv2vb.js +0 -1
  87. package/dist/chunk-22s3r2xy.js +0 -2
  88. package/dist/chunk-4mgjj8zg.js +0 -1
  89. package/dist/chunk-5a132j64.js +0 -1
  90. package/dist/chunk-5dz30k5z.js +0 -6
  91. package/dist/chunk-7yppfbgr.js +0 -1
  92. package/dist/chunk-a6kbpq05.js +0 -1
  93. package/dist/chunk-fefz145r.js +0 -1
  94. package/dist/chunk-ffkdx471.js +0 -1
  95. package/dist/chunk-fpkq3ch3.js +0 -1
  96. package/dist/chunk-kaf6m50a.js +0 -2
  97. package/dist/chunk-qxjsfp2c.js +0 -1
  98. package/dist/chunk-ssfvcnat.js +0 -1
  99. package/dist/chunk-swvp6j18.js +0 -1
  100. package/dist/chunk-v0znd20r.js +0 -1
  101. package/dist/chunk-vbxtqh24.js +0 -1
  102. package/dist/chunk-vkpddj6a.js +0 -1
  103. package/dist/chunk-w1m7wz1y.js +0 -10
  104. package/dist/chunk-yjbq4jeg.js +0 -2
@@ -1,4 +1,8 @@
1
- import{Xe as j1,Ye as L0,Ze as F1}from"./chunk-kaf6m50a.js";import{bf as WO,cf as IO}from"./chunk-0cbpjhq7.js";import{ff as B1}from"./chunk-rc7jnds2.js";import{gf as b0,if as J0}from"./chunk-egp0crrc.js";import{kg as z0,lg as $O,pg as I0}from"./chunk-zph2jekm.js";import{tg as u,vg as L,yg as P1}from"./chunk-c03xn5s3.js";import{Fg as M}from"./chunk-22aaybx2.js";import{fh as k,gh as z}from"./chunk-2qqmmxqf.js";import{th as g0}from"./chunk-c74e0jx1.js";import{Ah as N}from"./chunk-yz80dp1a.js";import Y1 from"node:path";import QO from"node:path";import R0 from"node:fs";import X0 from"node:os";import R from"node:path";import EO from"yaml";var Q4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function Z4(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var NO=`# Goal Completion Verifier
1
+ import{Xe as b1,Ye as L0,Ze as z1,cf as N0}from"./chunk-c80pzvhs.js";import{hf as jO,if as wO}from"./chunk-n5d0d6q7.js";import{lf as A1}from"./chunk-8bsse16j.js";import{mf as b0,of as J0}from"./chunk-9k3tg2hs.js";import{qg as S0,rg as GO,vg as I0}from"./chunk-tssmnn37.js";import{Bg as L,Eg as c1,zg as u}from"./chunk-js4aekf1.js";import{Lg as M}from"./chunk-9fm80wbr.js";import{lh as k,mh as S}from"./chunk-z37v80c1.js";import{zh as u0}from"./chunk-kxgr18gy.js";import{Gh as N}from"./chunk-fmkntp49.js";import H1 from"node:path";import LO from"node:path";import v0 from"node:fs";import W0 from"node:os";import E from"node:path";import dO from"yaml";var U1=2000,V1=50,j1=1000,Y4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:U1},findings:{type:"array",maxItems:V1,items:{type:"string",minLength:1,maxLength:j1}}},required:["verdict","summary","findings"],additionalProperties:!1};function F1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function hO(O){if(O.length<=N0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,N0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function B1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>U1||!Array.isArray($.findings)||$.findings.length>V1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=j1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function X4(O,$){let Q=B1(O);if(!Q)return;let Z=F1(Q.summary,$),J=Q.findings.map((K)=>F1(K,$));return hO([Z,J.length>0?`Findings:
2
+ ${J.map((K)=>`- ${K}`).join(`
3
+ `)}`:""].filter(Boolean).join(`
4
+
5
+ `))}function H4(O){return B1(O)?.verdict}var kO=`# Goal Completion Verifier
2
6
 
3
7
  You are a fresh, independent, adversarial verifier. The parent Agent has claimed
4
8
  that a persisted goal is complete. Your job is to refute that claim unless the
@@ -22,6 +26,8 @@ current workspace provides direct evidence for every explicit requirement.
22
26
  7. MISSING OR INDIRECT EVIDENCE IS NOT PASS. Use PARTIAL when the implementation
23
27
  may be correct but a requirement cannot be proved. Use FAIL for a concrete
24
28
  contradiction, failed check, defect, or missing required artifact.
29
+ 8. SAFE FEEDBACK. Keep summary and findings concise, use workspace-relative
30
+ file locations, and never include credentials or secret values.
25
31
 
26
32
  ## Verdict
27
33
 
@@ -32,7 +38,7 @@ Submit the host-requested structured final object with:
32
38
  - findings: concrete gaps with file or command locators
33
39
 
34
40
  PASS is allowed only when every requirement is directly proven and no relevant
35
- check fails.`,H1={name:L0,description:"Host-reserved adversarial verifier for persisted Goal completion claims. Read-only, objective-scoped, and evidence-driven.",tools:["Read","Glob","Grep","Bash"],disallowedTools:["Task"],systemPrompt:NO,permissionMode:"yolo",maxTurns:12,source:"builtin"};var RO=`# Code Review Agent
41
+ check fails.`,S1={name:L0,description:"Host-reserved adversarial verifier for persisted Goal completion claims. Read-only, objective-scoped, and evidence-driven.",tools:["Read","Glob","Grep","Bash"],disallowedTools:["Task"],systemPrompt:kO,permissionMode:"yolo",maxTurns:12,source:"builtin"};var PO=`# Code Review Agent
36
42
 
37
43
  You are an independent senior code reviewer. Find actionable defects introduced
38
44
  by the requested change. Do not implement fixes and do not praise the author.
@@ -87,7 +93,7 @@ Your final response must be exactly one JSON object and no Markdown fence:
87
93
 
88
94
  Use workspace-relative paths. Keep line ranges within 10 lines and overlapping
89
95
  the reviewed diff. Return an empty findings array when no qualifying defect is
90
- found.`,V1={name:F1,description:"Independent read-only code reviewer for uncommitted changes, base branches, and commits.",tools:["Read","Glob","Grep","Bash"],disallowedTools:["Task","WebFetch","WebSearch"],permissionMode:"default",maxTurns:24,systemPrompt:RO,source:"builtin"};var L4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function X4(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var vO=`# Verification Agent
96
+ found.`,M1={name:z1,description:"Independent read-only code reviewer for uncommitted changes, base branches, and commits.",tools:["Read","Glob","Grep","Bash"],disallowedTools:["Task","WebFetch","WebSearch"],permissionMode:"default",maxTurns:24,systemPrompt:PO,source:"builtin"};var B4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function S4(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var mO=`# Verification Agent
91
97
 
92
98
  You are an **independent verification engineer**. Your sole purpose is to find problems — not to praise or reassure. You are the last line of defense before code ships.
93
99
 
@@ -172,7 +178,7 @@ Submit exactly these fields:
172
178
  - **FAIL**: Any automated check fails OR any HIGH severity issue found.
173
179
  - **PARTIAL**: All automated checks pass BUT MEDIUM severity issues exist.
174
180
 
175
- Be thorough. Be skeptical. Find the bugs.`,U1={name:"verification",description:"Independent verification agent that validates implementation by running builds, tests, linters, and adversarial"+" probes. Strictly read-only — cannot modify code. Use"+" after completing implementation to get an independent quality assessment.",tools:["Read","Glob","Grep","Bash"],maxTurns:24,systemPrompt:vO,source:"builtin"};var N0=[{name:"general-purpose",description:"General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",tools:[]},{name:"Explore",description:'Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.',tools:["Glob","Grep","Read","WebFetch","WebSearch"],systemPrompt:`# Explore Subagent
181
+ Be thorough. Be skeptical. Find the bugs.`,I1={name:"verification",description:"Independent verification agent that validates implementation by running builds, tests, linters, and adversarial"+" probes. Strictly read-only — cannot modify code. Use"+" after completing implementation to get an independent quality assessment.",tools:["Read","Glob","Grep","Bash"],maxTurns:24,systemPrompt:mO,source:"builtin"};var E0=[{name:"general-purpose",description:"General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",tools:[]},{name:"Explore",description:'Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.',tools:["Glob","Grep","Read","WebFetch","WebSearch"],systemPrompt:`# Explore Subagent
176
182
 
177
183
  You are a specialized code exploration agent. Your job is to **directly execute searches** using the tools available to you.
178
184
 
@@ -239,9 +245,9 @@ You are a software architect specializing in implementation planning.
239
245
  **Risks**:
240
246
  - [Potential issue and mitigation]
241
247
 
242
- Be thorough but concise. Focus on actionable steps.`},{name:"statusline-setup",description:"Use this agent to configure the user's Claude Code status line setting.",tools:["Read","Edit"]},V1,U1,H1];var W0=k("Agent"),v0=new Set([j1,L0]);class C{workspaceRoot;static instances=new Map;subagents=new Map;constructor(O=M()){this.workspaceRoot=O}static getInstance(O=M()){let $=R.resolve(O),Q=C.instances.get($);if(!Q)Q=new C($),C.instances.set($,Q);return Q}static resetInstances(){C.instances.clear()}static releaseInstance(O,$){let Q=R.resolve(O),Z=C.instances.get(Q);if(!Z||$&&Z!==$)return!1;return C.instances.delete(Q)}register(O){if(v0.has(O.name))throw Error(`Subagent '${O.name}' is reserved by Blade`);if(this.subagents.has(O.name))throw Error(`Subagent '${O.name}' already registered`);this.subagents.set(O.name,O)}applyOverrides(O){for(let $ of O){if(v0.has($.name))throw Error(`Subagent '${$.name}' is reserved by Blade`);this.subagents.set($.name,$)}}getSubagent(O){return this.subagents.get(O)}getAllNames(){return Array.from(this.subagents.keys())}getAllSubagents(){return Array.from(this.subagents.values())}getDescriptionsForPrompt(){let O=this.getAllSubagents();if(O.length===0)return"No subagents available.";return`Available agent types and the tools they have access to:
248
+ Be thorough but concise. Focus on actionable steps.`},{name:"statusline-setup",description:"Use this agent to configure the user's Claude Code status line setting.",tools:["Read","Edit"]},M1,I1,S1];var Y0=k("Agent"),R0=new Set([b1,L0]);class C{workspaceRoot;static instances=new Map;subagents=new Map;constructor(O=M()){this.workspaceRoot=O}static getInstance(O=M()){let $=E.resolve(O),Q=C.instances.get($);if(!Q)Q=new C($),C.instances.set($,Q);return Q}static resetInstances(){C.instances.clear()}static releaseInstance(O,$){let Q=E.resolve(O),Z=C.instances.get(Q);if(!Z||$&&Z!==$)return!1;return C.instances.delete(Q)}register(O){if(R0.has(O.name))throw Error(`Subagent '${O.name}' is reserved by Blade`);if(this.subagents.has(O.name))throw Error(`Subagent '${O.name}' already registered`);this.subagents.set(O.name,O)}applyOverrides(O){for(let $ of O){if(R0.has($.name))throw Error(`Subagent '${$.name}' is reserved by Blade`);this.subagents.set($.name,$)}}getSubagent(O){return this.subagents.get(O)}getAllNames(){return Array.from(this.subagents.keys())}getAllSubagents(){return Array.from(this.subagents.values())}getDescriptionsForPrompt(){let O=this.getAllSubagents();if(O.length===0)return"No subagents available.";return`Available agent types and the tools they have access to:
243
249
  ${O.map((Q)=>{let Z=!Q.tools||Q.tools.length===0?"All tools":Q.tools.join(", ");return`- ${Q.name}: ${Q.description} (Tools: ${Z})`}).join(`
244
- `)}`}loadFromDirectory(O,$){if(!R0.existsSync(O))return;let Q=R0.readdirSync(O);for(let Z of Q){if(!Z.endsWith(".md"))continue;let J=R.join(O,Z);try{let q=this.parseConfigFile(J,$);if(v0.has(q.name)){W0.warn(`Skipping reserved subagent configuration: ${q.name}`);continue}this.subagents.set(q.name,q)}catch(q){W0.warn(`Failed to load subagent config from ${J}:`,q)}}}parseConfigFile(O,$){let Z=R0.readFileSync(O,"utf-8").match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(!Z)throw Error(`No YAML frontmatter found in ${O}`);let[,J,q]=Z,K=EO.parse(J);if(!K.name||!K.description)throw Error(`Missing required fields (name, description) in ${O}`);if(K.isolation!==void 0&&K.isolation!=="none"&&K.isolation!=="worktree")throw Error(`Invalid isolation mode "${String(K.isolation)}" in ${O}`);let X=q.trim(),G=this.parseStringOrArray(K.tools),W=this.parseStringOrArray(K.skills),Y=B1(K.permissionMode);return{name:K.name,description:K.description,systemPrompt:X,tools:G,color:K.color,configPath:O,model:K.model||"inherit",permissionMode:Y,skills:W,isolation:K.isolation,source:$}}parseStringOrArray(O){if(!O)return;if(Array.isArray(O))return O.map(($)=>$.trim()).filter(Boolean);return O.split(",").map(($)=>$.trim()).filter(Boolean)}loadFromStandardLocations(O){let $=O??N.getInstance().isTrustedCached(this.workspaceRoot);this.loadBuiltinAgents();let Q=R.join(X0.homedir(),".claude","agents");if(this.loadFromDirectory(Q,"claude-code-user"),$){let q=R.join(this.workspaceRoot,".claude","agents");this.loadFromDirectory(q,"claude-code-project")}let Z=R.join(X0.homedir(),".blade","agents");if(this.loadFromDirectory(Z,"blade-user"),$){let q=R.join(this.workspaceRoot,".blade","agents");this.loadFromDirectory(q,"blade-project")}let J=this.getAllNames().length;return W0.debug(`Loaded ${J} subagents from standard locations`),J}loadBuiltinAgents(){for(let O of N0)this.subagents.set(O.name,{...O,model:O.model||"inherit",source:"builtin"});W0.debug(`Loaded ${N0.length} builtin subagents`)}clear(){this.subagents.clear()}snapshot(){let O=new C(this.workspaceRoot);for(let $ of this.subagents.values())O.subagents.set($.name,{...$,...$.tools?{tools:[...$.tools]}:{},...$.disallowedTools?{disallowedTools:[...$.disallowedTools]}:{},...$.skills?{skills:[...$.skills]}:{}});return O}getSubagentsBySource(){let O={builtin:[],"claude-code-user":[],"claude-code-project":[],"blade-user":[],"blade-project":[],flag:[],plugin:[]};for(let $ of this.subagents.values()){let Q=$.source||"builtin",Z=Q.startsWith("plugin:")?"plugin":Q;O[Z].push($)}return O}clearPluginAgents(){let O=[];for(let[$,Q]of this.subagents.entries())if(Q.source?.startsWith("plugin:"))O.push($);for(let $ of O)this.subagents.delete($)}static getClaudeCodeAgentsDir(O){if(O==="user")return R.join(X0.homedir(),".claude","agents");return R.join(M(),".claude","agents")}static getBladeAgentsDir(O){if(O==="user")return R.join(X0.homedir(),".blade","agents");return R.join(M(),".blade","agents")}}function o(O=M()){return C.getInstance(O)}var _4=new Proxy({},{get(O,$){let Q=o(),Z=Reflect.get(Q,$,Q);return typeof Z==="function"?Z.bind(Q):Z}});import*as j0 from"node:fs/promises";import{homedir as w1}from"node:os";import*as w from"node:path";var Y0={name:"skill-creator",description:"Create new Skills interactively. Use when the user wants to create a new Skill, define a custom workflow, or add a specialized capability to Blade.",allowedTools:["Read","Write","Glob","Bash","AskUserQuestion"],version:"1.0.0",argumentHint:void 0,userInvocable:!0,disableModelInvocation:!1,model:void 0,whenToUse:"User wants to create a new skill, define a custom workflow, or add a specialized capability.",path:"builtin://skill-creator",basePath:"",source:"builtin"};function z1(){return{metadata:Y0,instructions:`# Skill Creator
250
+ `)}`}loadFromDirectory(O,$){if(!v0.existsSync(O))return;let Q=v0.readdirSync(O);for(let Z of Q){if(!Z.endsWith(".md"))continue;let J=E.join(O,Z);try{let K=this.parseConfigFile(J,$);if(R0.has(K.name)){Y0.warn(`Skipping reserved subagent configuration: ${K.name}`);continue}this.subagents.set(K.name,K)}catch(K){Y0.warn(`Failed to load subagent config from ${J}:`,K)}}}parseConfigFile(O,$){let Z=v0.readFileSync(O,"utf-8").match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(!Z)throw Error(`No YAML frontmatter found in ${O}`);let[,J,K]=Z,q=dO.parse(J);if(!q.name||!q.description)throw Error(`Missing required fields (name, description) in ${O}`);if(q.isolation!==void 0&&q.isolation!=="none"&&q.isolation!=="worktree")throw Error(`Invalid isolation mode "${String(q.isolation)}" in ${O}`);let W=K.trim(),G=this.parseStringOrArray(q.tools),Y=this.parseStringOrArray(q.skills),X=A1(q.permissionMode);return{name:q.name,description:q.description,systemPrompt:W,tools:G,color:q.color,configPath:O,model:q.model||"inherit",permissionMode:X,skills:Y,isolation:q.isolation,source:$}}parseStringOrArray(O){if(!O)return;if(Array.isArray(O))return O.map(($)=>$.trim()).filter(Boolean);return O.split(",").map(($)=>$.trim()).filter(Boolean)}loadFromStandardLocations(O){let $=O??N.getInstance().isTrustedCached(this.workspaceRoot);this.loadBuiltinAgents();let Q=E.join(W0.homedir(),".claude","agents");if(this.loadFromDirectory(Q,"claude-code-user"),$){let K=E.join(this.workspaceRoot,".claude","agents");this.loadFromDirectory(K,"claude-code-project")}let Z=E.join(W0.homedir(),".blade","agents");if(this.loadFromDirectory(Z,"blade-user"),$){let K=E.join(this.workspaceRoot,".blade","agents");this.loadFromDirectory(K,"blade-project")}let J=this.getAllNames().length;return Y0.debug(`Loaded ${J} subagents from standard locations`),J}loadBuiltinAgents(){for(let O of E0)this.subagents.set(O.name,{...O,model:O.model||"inherit",source:"builtin"});Y0.debug(`Loaded ${E0.length} builtin subagents`)}clear(){this.subagents.clear()}snapshot(){let O=new C(this.workspaceRoot);for(let $ of this.subagents.values())O.subagents.set($.name,{...$,...$.tools?{tools:[...$.tools]}:{},...$.disallowedTools?{disallowedTools:[...$.disallowedTools]}:{},...$.skills?{skills:[...$.skills]}:{}});return O}getSubagentsBySource(){let O={builtin:[],"claude-code-user":[],"claude-code-project":[],"blade-user":[],"blade-project":[],flag:[],plugin:[]};for(let $ of this.subagents.values()){let Q=$.source||"builtin",Z=Q.startsWith("plugin:")?"plugin":Q;O[Z].push($)}return O}clearPluginAgents(){let O=[];for(let[$,Q]of this.subagents.entries())if(Q.source?.startsWith("plugin:"))O.push($);for(let $ of O)this.subagents.delete($)}static getClaudeCodeAgentsDir(O){if(O==="user")return E.join(W0.homedir(),".claude","agents");return E.join(M(),".claude","agents")}static getBladeAgentsDir(O){if(O==="user")return E.join(W0.homedir(),".blade","agents");return E.join(M(),".blade","agents")}}function o(O=M()){return C.getInstance(O)}var y4=new Proxy({},{get(O,$){let Q=o(),Z=Reflect.get(Q,$,Q);return typeof Z==="function"?Z.bind(Q):Z}});import*as j0 from"node:fs/promises";import{homedir as R1}from"node:os";import*as w from"node:path";var X0={name:"skill-creator",description:"Create new Skills interactively. Use when the user wants to create a new Skill, define a custom workflow, or add a specialized capability to Blade.",allowedTools:["Read","Write","Glob","Bash","AskUserQuestion"],version:"1.0.0",argumentHint:void 0,userInvocable:!0,disableModelInvocation:!1,model:void 0,whenToUse:"User wants to create a new skill, define a custom workflow, or add a specialized capability.",path:"builtin://skill-creator",basePath:"",source:"builtin"};function x1(){return{metadata:X0,instructions:`# Skill Creator
245
251
 
246
252
  帮助用户创建新的 Blade Skills。
247
253
 
@@ -424,7 +430,7 @@ user-invocable: true
424
430
  <footer>
425
431
  \`\`\`
426
432
  \`\`\`
427
- `}}var H0={name:"update-config",description:"配置 Blade harness(settings/hooks/permissions)。"+"用户请求自动化行为时使用此 Skill。",allowedTools:["ConfigTool","Read","Bash","AskUserQuestion"],version:"1.0.0",userInvocable:!0,disableModelInvocation:!1,whenToUse:'用户说"从现在起..."、"每次..."、"当...时..."、'+"需要改配置、安装 hooks、修改权限",path:"builtin://update-config",basePath:"",source:"builtin"};function S1(){return{metadata:H0,instructions:`# Update Config Skill
433
+ `}}var H0={name:"update-config",description:"配置 Blade harness(settings/hooks/permissions)。"+"用户请求自动化行为时使用此 Skill。",allowedTools:["ConfigTool","Read","Bash","AskUserQuestion"],version:"1.0.0",userInvocable:!0,disableModelInvocation:!1,whenToUse:'用户说"从现在起..."、"每次..."、"当...时..."、'+"需要改配置、安装 hooks、修改权限",path:"builtin://update-config",basePath:"",source:"builtin"};function T1(){return{metadata:H0,instructions:`# Update Config Skill
428
434
 
429
435
  配置 Blade 运行环境。管理 settings、hooks、permissions、环境变量等。
430
436
 
@@ -697,23 +703,23 @@ ConfigTool({
697
703
  2. **permissions 字段使用 replace 策略**:设置 permissions 会完全替换现有值。如果只想添加规则,先 GET 当前值,合并后再 SET
698
704
  3. **env 字段使用 deep-merge 策略**:可以逐个添加环境变量
699
705
  4. **scope 默认值**:不指定 scope 时,根据字段路由表决定(hooks/permissions/env 默认 local,temperature/codeTheme 等默认 global)
700
- `}}import{exec as yO}from"node:child_process";import*as U from"node:fs/promises";import{homedir as fO}from"node:os";import*as A from"node:path";import{promisify as hO}from"node:util";var F0=hO(yO),b=k("General"),y0={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class M1{skillsDir;constructor(O){this.skillsDir=O||A.join(fO(),".blade","skills")}async isInstalled(O){let $=A.join(this.skillsDir,O,"SKILL.md");try{return await U.access($),!0}catch{return!1}}async isGitAvailable(){try{return await F0("git --version"),!0}catch{return!1}}async installOfficialSkill(O){let{url:$,branch:Q}=y0,Z=A.join(this.skillsDir,O),J=A.join(this.skillsDir,`.tmp-${O}-${Date.now()}`);try{if(!await this.isGitAvailable())return b.warn("Git not available, skipping skill installation"),!1;b.info(`Installing official skill: ${O}...`),await U.mkdir(this.skillsDir,{recursive:!0,mode:493}),await F0(`git clone --depth 1 --branch ${Q} --single-branch ${$} "${J}"`,{timeout:30000});let q=A.join(J,"skills",O);try{await U.access(q)}catch{return b.warn(`Skill ${O} not found in official repository`),await U.rm(J,{recursive:!0,force:!0}),!1}try{await U.rm(Z,{recursive:!0,force:!0})}catch{}return await U.cp(q,Z,{recursive:!0}),await U.rm(J,{recursive:!0,force:!0}),b.info(`Successfully installed: ${O}`),!0}catch(q){try{await U.rm(J,{recursive:!0,force:!0})}catch{}return b.warn(`Failed to install ${O}: ${q instanceof Error?q.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await U.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let O of y0.defaultSkills)if(!await this.isInstalled(O))await this.installOfficialSkill(O)}async installFromRepo(O,$){let Q=$||this.extractRepoName(O),Z=A.join(this.skillsDir,Q),J=A.join(this.skillsDir,`.tmp-repo-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return b.warn("Git not available, cannot install from repo"),!1;b.info(`Installing skill from repo: ${O}...`),await U.mkdir(this.skillsDir,{recursive:!0,mode:493}),await F0(`git clone --depth 1 "${O}" "${J}"`,{timeout:60000});let q=A.join(J,"SKILL.md");try{await U.access(q)}catch{return b.warn(`No SKILL.md found in repository ${O}`),await U.rm(J,{recursive:!0,force:!0}),!1}await U.rm(Z,{recursive:!0,force:!0}),await U.rename(J,Z);try{await U.rm(A.join(Z,".git"),{recursive:!0,force:!0})}catch{}return b.info(`Successfully installed skill from repo: ${Q}`),!0}catch(q){try{await U.rm(J,{recursive:!0,force:!0})}catch{}return b.warn(`Failed to install from repo ${O}: ${q instanceof Error?q.message:"Unknown error"}`),!1}}async installFromLocal(O,$,Q=!0){let Z=$||A.basename(O),J=A.join(this.skillsDir,Z);try{let q=A.resolve(O);try{await U.access(q)}catch{return b.warn(`Local path does not exist: ${q}`),!1}let K=A.join(q,"SKILL.md");try{await U.access(K)}catch{return b.warn(`No SKILL.md found in local path: ${q}`),!1}if(b.info(`Installing skill from local path: ${q}...`),await U.mkdir(this.skillsDir,{recursive:!0,mode:493}),await U.rm(J,{recursive:!0,force:!0}),Q)await U.symlink(q,J,"dir"),b.info(`Created symlink for skill: ${Z}`);else await U.cp(q,J,{recursive:!0}),b.info(`Copied skill to: ${Z}`);return!0}catch(q){return b.warn(`Failed to install from local path ${O}: ${q instanceof Error?q.message:"Unknown error"}`),!1}}extractRepoName(O){return O.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:O,branch:$}=y0,Q=A.join(this.skillsDir,`.tmp-all-${Date.now()}`),Z=[],J=[];try{if(!await this.isGitAvailable())return b.warn("Git not available, skipping skill installation"),{installed:Z,failed:J};await U.mkdir(this.skillsDir,{recursive:!0,mode:493}),b.info("Cloning official skills repository..."),await F0(`git clone --depth 1 --branch ${$} --single-branch ${O} "${Q}"`,{timeout:60000});let q=A.join(Q,"skills"),K=await U.readdir(q,{withFileTypes:!0});for(let X of K){if(!X.isDirectory())continue;let G=X.name,W=A.join(q,G),Y=A.join(this.skillsDir,G);try{await U.access(A.join(W,"SKILL.md")),await U.rm(Y,{recursive:!0,force:!0}),await U.cp(W,Y,{recursive:!0}),b.info(`Installed: ${G}`),Z.push(G)}catch(V){b.warn(`Failed to install ${G}`),J.push(G)}}await U.rm(Q,{recursive:!0,force:!0})}catch(q){try{await U.rm(Q,{recursive:!0,force:!0})}catch{}b.warn(`Failed to install skills: ${q instanceof Error?q.message:"Unknown error"}`)}return{installed:Z,failed:J}}}var f0=null;function I1(O){if(!f0)f0=new M1(O);return f0}import*as a from"node:fs/promises";import*as V0 from"node:path";import{parse as kO}from"yaml";var PO=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,dO=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,b1=1024;function mO(O){if(!O)return;if(typeof O==="string")return O.split(",").map(($)=>$.trim()).filter(Boolean);if(Array.isArray(O))return O.map(($)=>String($).trim()).filter(Boolean);return}function A1(O){if(O===void 0)return;if(typeof O==="boolean")return O;if(typeof O==="string"){let $=O.toLowerCase().trim();if($==="true"||$==="yes"||$==="1")return!0;if($==="false"||$==="no"||$==="0")return!1}return}function pO(O,$){if(!O.name)return{valid:!1,error:"Missing required field: name"};if(!dO.test(O.name))return{valid:!1,error:`Invalid name "${O.name}": must be lowercase letters, numbers, and hyphens only, 1-64 characters`};if(!O.description)return{valid:!1,error:"Missing required field: description"};if(O.description.length>b1)return{valid:!1,error:`Description too long: ${O.description.length} characters (max ${b1})`};let Q;if(O.model)Q=O.model==="inherit"?"inherit":O.model;return{valid:!0,metadata:{name:O.name,description:O.description.trim(),allowedTools:mO(O["allowed-tools"]),version:O.version,argumentHint:O["argument-hint"]?.trim(),userInvocable:A1(O["user-invocable"]),disableModelInvocation:A1(O["disable-model-invocation"]),model:Q,whenToUse:O.when_to_use?.trim()}}}function x1(O,$,Q){let Z=O.match(PO);if(!Z)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,J,q]=Z,K;try{K=kO(J)}catch(W){return{success:!1,error:`Failed to parse YAML frontmatter: ${W instanceof Error?W.message:String(W)}`}}let X=pO(K,$);if(!X.valid)return{success:!1,error:X.error};let G=V0.dirname($);return{success:!0,content:{metadata:{...X.metadata,path:$,basePath:G,source:Q},instructions:q.trim()}}}async function U0(O,$){try{let Q=await a.readFile(O,"utf-8");return x1(Q,O,$)}catch(Q){if(Q.code==="ENOENT")return{success:!1,error:`File not found: ${O}`};return{success:!1,error:`Failed to read file: ${Q instanceof Error?Q.message:String(Q)}`}}}async function _1(O){try{let $=await a.readFile(O.path,"utf-8"),Q=x1($,O.path,O.source);return Q.success?Q.content:null}catch{return null}}async function T1(O){try{return await a.access(V0.join(O,"SKILL.md")),!0}catch{return!1}}var gO={userSkillsDir:w.join(w1(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:w.join(w1(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},t=new Map;function D1(O){return w.resolve(O?.cwd??M())}class P{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(O){this.config={...gO,cwd:M(),...O}}static getInstance(O){let $=D1(O),Q=t.get($);if(!Q)Q=new P({...O,cwd:w.resolve(O?.cwd??M())}),t.set($,Q);return Q}static resetInstance(){t.clear()}static releaseInstance(O,$){let Q=D1(O),Z=t.get(Q);if(!Z||$&&Z!==$)return!1;return t.delete(Q)}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let O=[],$=[];try{await I1(this.config.userSkillsDir).ensureDefaultSkillsInstalled()}catch(q){O.push({path:"SkillInstaller",error:`Failed to install default skills: ${q instanceof Error?q.message:"Unknown error"}`})}this.loadBuiltinSkills();let Q=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");$.push(...Q.skills),O.push(...Q.errors);let Z=await this.scanDirectory(this.config.userSkillsDir,"user");if($.push(...Z.skills),O.push(...Z.errors),(await N.getInstance().getStatus(this.config.cwd)).state==="trusted"){let q=w.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:w.join(this.config.cwd,this.config.claudeProjectSkillsDir),K=await this.scanDirectory(q,"project");$.push(...K.skills),O.push(...K.errors);let X=w.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:w.join(this.config.cwd,this.config.projectSkillsDir),G=await this.scanDirectory(X,"project");$.push(...G.skills),O.push(...G.errors)}for(let q of $)this.skills.set(q.name,q);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:O}}loadBuiltinSkills(){this.skills.set(Y0.name,Y0),this.skills.set(H0.name,H0)}async scanDirectory(O,$){let Q=[],Z=[];try{await j0.access(O)}catch{return{skills:Q,errors:Z}}try{let J=await j0.readdir(O,{withFileTypes:!0});for(let q of J){if(!q.isDirectory())continue;let K=w.join(O,q.name),X=w.join(K,"SKILL.md");if(!await T1(K))continue;let G=await U0(X,$);if(G.success&&G.content)Q.push(G.content.metadata);else Z.push({path:X,error:G.error||"Unknown error"})}}catch(J){Z.push({path:O,error:`Failed to scan directory: ${J instanceof Error?J.message:String(J)}`})}return{skills:Q,errors:Z}}getAll(){return Array.from(this.skills.values())}get(O){return this.skills.get(O)}has(O){return this.skills.has(O)}async loadContent(O){let $=this.skills.get(O);if(!$)return null;if($.source==="builtin")return this.loadBuiltinContent(O);return _1($)}loadBuiltinContent(O){switch(O){case"skill-creator":return z1();case"update-config":return S1();default:return null}}getModelInvocableSkills(){return Array.from(this.skills.values()).filter((O)=>!O.disableModelInvocation)}getUserInvocableSkills(){return Array.from(this.skills.values()).filter((O)=>O.userInvocable===!0)}generateAvailableSkillsList(){let O=this.getModelInvocableSkills().sort((Q,Z)=>Q.name<Z.name?-1:Q.name>Z.name?1:0);if(O.length===0)return"";let $=[];for(let Q of O){let Z=Q.description.length>100?`${Q.description.substring(0,97)}...`:Q.description,J=Q.argumentHint?`${Q.name} ${Q.argumentHint}`:Q.name;$.push(`- ${J}: ${Z}`)}return $.join(`
701
- `)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}snapshot(){let O=new P({...this.config});return O.skills=new Map(Array.from(this.skills,([$,Q])=>[$,{...Q,...Q.allowedTools?{allowedTools:[...Q.allowedTools]}:{}}])),O.pluginSkills=new Map(Array.from(this.pluginSkills,([$,Q])=>[$,{...Q,metadata:{...Q.metadata,...Q.metadata.allowedTools?{allowedTools:[...Q.metadata.allowedTools]}:{}}}])),O.initialized=this.initialized,O}registerPluginSkill(O){this.pluginSkills.set(O.namespacedName,O),this.skills.set(O.namespacedName,O.metadata)}findPluginSkill(O){let $=this.pluginSkills.get(O);if($)return $;let Q=[];for(let Z of this.pluginSkills.values())if(Z.originalName===O)Q.push(Z);if(Q.length===1)return Q[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let O of this.pluginSkills.values())this.skills.delete(O.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function g(O){return P.getInstance(O)}import m0 from"node:path";import{execSync as uO}from"node:child_process";import C1 from"node:fs";import N1 from"node:path";class h0{async execute(O,$){let Q=O.content;if($.signal?.aborted)throw Error("Command execution aborted");return Q=this.interpolateArgs(Q,$.args),Q=await this.executeBashEmbeds(Q,$),Q=await this.resolveFileReferences(Q,$.workspaceRoot),Q}interpolateArgs(O,$){O=O.replace(/\$ARGUMENTS/g,$.join(" "));for(let Q=9;Q>=1;Q--){let Z=`$${Q}`,J=$[Q-1]??"";O=O.split(Z).join(J)}return O}async executeBashEmbeds(O,$){let Q=/!`([^`]+)`/g,Z=[];for(let q of O.matchAll(Q))Z.push({match:q[0],command:q[1]});let J=O;for(let{match:q,command:K}of Z){if($.signal?.aborted){J=J.replace(q,"[Execution aborted]");continue}try{let X=uO(K,{cwd:$.workspaceRoot,encoding:"utf-8",timeout:30000,maxBuffer:1048576,stdio:["pipe","pipe","pipe"]}).trim();J=J.replace(q,X)}catch(X){let G=X instanceof Error?X.message:String(X);J=J.replace(q,`[Error executing '${K}': ${G}]`)}}return J}async resolveFileReferences(O,$){let Q=/@([\w./-]+(?:\/[\w./-]+|\.[\w]+))/g,Z=[];for(let q of O.matchAll(Q))Z.push({match:q[0],relativePath:q[1]});let J=O;for(let{match:q,relativePath:K}of Z){let X=N1.resolve($,K);try{if(C1.statSync(X).isFile()){let W=C1.readFileSync(X,"utf-8"),V=`\`\`\`${N1.extname(K).slice(1)||"text"}
702
- ${W}
703
- \`\`\``;J=J.replace(q,V)}}catch{}}return J}hasDynamicContent(O){return{hasArgs:/\$ARGUMENTS|\$\d/.test(O),hasBashEmbeds:/!`[^`]+`/.test(O),hasFileRefs:/@[\w./-]+(?:\/[\w./-]+|\.[\w]+)/.test(O)}}}import P0 from"node:fs";import v1 from"node:os";import h from"node:path";import cO from"node:fs";import R1 from"node:path";import lO from"gray-matter";class k0{parse(O,$,Q,Z){try{let J=cO.readFileSync(O,"utf-8"),{data:q,content:K}=lO(J),{name:X,namespace:G}=this.extractNameAndNamespace(O,$);if(!X)return null;return{name:X,namespace:G,config:this.normalizeConfig(q),content:K.trim(),path:O,source:Q,sourceDir:Z}}catch(J){return console.error(`Failed to parse command file: ${O}`,J),null}}normalizeConfig(O){return{description:this.asString(O.description),allowedTools:this.parseAllowedTools(O["allowed-tools"]),argumentHint:this.asString(O["argument-hint"]),model:this.asString(O.model),disableModelInvocation:O["disable-model-invocation"]===!0}}asString(O){if(typeof O==="string"&&O.trim())return O.trim();return}parseAllowedTools(O){if(!O)return;if(Array.isArray(O))return O.map(($)=>String($).trim()).filter(Boolean);if(typeof O==="string")return O.split(",").map(($)=>$.trim()).filter(Boolean);return}extractNameAndNamespace(O,$){let Z=R1.relative($,O).split(R1.sep),J=Z.pop();if(!J)return{name:""};let q=J.replace(/\.md$/i,""),K=Z.length>0?Z.join("/"):void 0;return{name:q,namespace:K}}validateConfig(O){let $=[];if(O.model&&!this.isValidModelId(O.model))$.push(`Invalid model ID: ${O.model}`);return $}isValidModelId(O){return O.length>0&&O.length<200}}class d0{parser=new k0;async discover(O){let $=[],Q=[],Z=[],J=this.getSearchDirs(O);for(let q of J){if(!P0.existsSync(q.path))continue;Q.push(q.path);try{let K=await this.scanDirectory(q.path);for(let X of K)try{let G=this.parser.parse(X,q.path,q.source,q.sourceDir);if(G)$.push(G)}catch(G){Z.push({path:X,error:G instanceof Error?G.message:String(G)})}}catch(K){Z.push({path:q.path,error:K instanceof Error?K.message:String(K)})}}return{commands:$,scannedDirs:Q,errors:Z}}getSearchDirs(O){let $=v1.homedir();return[{path:h.join($,".blade","commands"),source:"user",sourceDir:"blade"},{path:h.join($,".claude","commands"),source:"user",sourceDir:"claude"},{path:h.join(O,".blade","commands"),source:"project",sourceDir:"blade"},{path:h.join(O,".claude","commands"),source:"project",sourceDir:"claude"}]}async scanDirectory(O){let $=[],Q=async(Z)=>{let J=await P0.promises.readdir(Z,{withFileTypes:!0});for(let q of J){let K=h.join(Z,q.name);if(q.isDirectory())await Q(K);else if(q.isFile()&&q.name.endsWith(".md"))$.push(K)}};return await Q(O),$}async hasCommands(O){let $=this.getSearchDirs(O);for(let Q of $){if(!P0.existsSync(Q.path))continue;if((await this.scanDirectory(Q.path)).length>0)return!0}return!1}getCommandDirs(O){let $=v1.homedir();return{projectBlade:h.join(O,".blade","commands"),projectClaude:h.join(O,".claude","commands"),userBlade:h.join($,".blade","commands"),userClaude:h.join($,".claude","commands")}}}class _{static instances=new Map;commands=new Map;pluginCommands=new Map;loader=new d0;executor=new h0;initialized=!1;workspaceRoot="";lastDiscoveryResult=null;static getInstance(O=M()){let $=m0.resolve(O),Q=_.instances.get($);if(!Q)Q=new _,_.instances.set($,Q);return Q}static resetInstance(){_.instances.clear()}static releaseInstance(O,$){let Q=m0.resolve(O),Z=_.instances.get(Q);if(!Z||$&&Z!==$)return!1;return _.instances.delete(Q)}static getExistingInstance(O=M()){return _.instances.get(m0.resolve(O))}constructor(){}async initialize(O){this.workspaceRoot=O;let $=await this.loader.discover(O),Q=(await N.getInstance().getStatus(O)).state==="trusted",Z={...$,commands:$.commands.filter((J)=>J.source!=="project"||Q)};this.lastDiscoveryResult=Z,this.commands.clear();for(let J of Z.commands)this.commands.set(J.name,J);return this.initialized=!0,Z}async refresh(){if(!this.workspaceRoot)throw Error("Registry not initialized. Call initialize() first.");return this.initialize(this.workspaceRoot)}isInitialized(){return this.initialized}getWorkspaceRoot(){return this.workspaceRoot}getCommand(O){return this.commands.get(O)}hasCommand(O){return this.commands.has(O)}getAllCommands(){return Array.from(this.commands.values())}getCommandCount(){return this.commands.size}getModelInvocableCommands(){return this.getAllCommands().filter((O)=>O.config.description&&!O.config.disableModelInvocation)}getModelInvocablePluginCommands(){return this.getAllPluginCommands().filter((O)=>O.config.description&&!O.config.disableModelInvocation)}async executeCommand(O,$){let Q=this.getCommand(O);if(!Q)return null;return this.executor.execute(Q,$)}getCommandLabel(O){let $=O.source==="project"?"project":"user";if(O.namespace)return`(${$}:${O.namespace})`;return`(${$})`}getCommandDisplayName(O){let $=[`/${O.name}`];if(O.config.argumentHint)$.push(O.config.argumentHint);if(O.config.description)$.push("-",O.config.description);return $.push(this.getCommandLabel(O)),$.join(" ")}getCommandsBySource(){let O=[],$=[];for(let Q of this.commands.values())if(Q.source==="project")O.push(Q);else $.push(Q);return{project:O,user:$}}getLastDiscoveryResult(){return this.lastDiscoveryResult}getCommandDirs(){if(!this.workspaceRoot)return null;return this.loader.getCommandDirs(this.workspaceRoot)}generateCommandListDescription(O=15000){let $=[...this.getModelInvocableCommands().map((K)=>({name:K.name,description:K.config.description,argumentHint:K.config.argumentHint,label:this.getCommandLabel(K)})),...this.getModelInvocablePluginCommands().map((K)=>({name:K.namespacedName,description:K.config.description,argumentHint:K.config.argumentHint,label:`(plugin:${K.pluginName})`}))],Q=$.length;if(Q===0)return{text:"No custom commands available.",includedCount:0,totalCount:0};let Z=`Available custom commands:
704
-
705
- `,J=Z.length,q=0;for(let K of $){let X=K.argumentHint?` ${K.argumentHint}`:"",G=`- /${K.name}${X}: ${K.description} ${K.label}
706
- `;if(J+G.length>O)break;Z+=G,J+=G.length,q++}if(q<Q)Z+=`
707
- (${q} of ${Q} commands shown due to character budget)`;return{text:Z,includedCount:q,totalCount:Q}}snapshot(){let O=new _;return O.workspaceRoot=this.workspaceRoot,O.commands=new Map(Array.from(this.commands,([$,Q])=>[$,{...Q,config:{...Q.config,...Q.config.allowedTools?{allowedTools:[...Q.config.allowedTools]}:{}}}])),O.pluginCommands=new Map(Array.from(this.pluginCommands,([$,Q])=>[$,{...Q,config:{...Q.config,...Q.config.allowedTools?{allowedTools:[...Q.config.allowedTools]}:{}}}])),O.initialized=this.initialized,O.lastDiscoveryResult=this.lastDiscoveryResult?{commands:Array.from(O.commands.values()),scannedDirs:[...this.lastDiscoveryResult.scannedDirs],errors:this.lastDiscoveryResult.errors.map(($)=>({...$}))}:null,O}registerPluginCommand(O){this.pluginCommands.set(O.namespacedName,O)}findPluginCommand(O){let $=this.pluginCommands.get(O);if($)return $;let Q=[];for(let Z of this.pluginCommands.values())if(Z.originalName===O)Q.push(Z);if(Q.length===1)return Q[0];return}hasPluginCommand(O){return this.findPluginCommand(O)!==void 0}getAllPluginCommands(){return Array.from(this.pluginCommands.values())}async executePluginCommand(O,$){let Q=this.findPluginCommand(O);if(!Q)return null;let Z={name:Q.namespacedName,config:Q.config,content:Q.content,path:Q.path,source:"project",sourceDir:"blade"};return this.executor.execute(Z,$)}clearPluginCommands(){this.pluginCommands.clear()}getPluginCommandCount(){return this.pluginCommands.size}hasPluginCommandConflict(O){let $=0;for(let Q of this.pluginCommands.values())if(Q.originalName===O){if($++,$>1)return!0}return!1}getPluginCommandProviders(O){let $=[];for(let Q of this.pluginCommands.values())if(Q.originalName===O)$.push(Q.pluginName);return $}}import r0 from"node:path";import{satisfies as p0,validRange as E1}from"semver";var sO=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function u0(O){if(O.bladeVersion!==void 0&&(!O.bladeVersion.trim()||!E1(O.bladeVersion)))throw Error(`Invalid Blade version range in plugin "${O.name}": ${O.bladeVersion}`);for(let[$,Q]of Object.entries(O.dependencies??{})){if(!sO.test($))throw Error(`Invalid dependency name in plugin "${O.name}": ${$}`);if($===O.name)throw Error(`Plugin "${O.name}" cannot depend on itself`);if(!Q.trim()||!E1(Q))throw Error(`Invalid dependency range for ${$} in plugin "${O.name}": ${Q}`)}}function f1(O,$=g0()){if(u0(O),O.bladeVersion&&!p0($,O.bladeVersion))throw Error(`Plugin "${O.name}" requires Blade ${O.bladeVersion}, current ${$}`)}function y1(O,$){O.status="error",O.compatibilityIssues=[...O.compatibilityIssues??[],$],O.error=O.compatibilityIssues.map((Q)=>Q.message).join("; ")}function h1(O,$=g0()){let Q=[],Z=new Map(O.map((q)=>[q.manifest.name,q]));for(let q of O){if(q.status!=="active")continue;if(q.manifest.bladeVersion&&!p0($,q.manifest.bladeVersion)){let K={code:"blade-version",expected:q.manifest.bladeVersion,actual:$,message:`Requires Blade ${q.manifest.bladeVersion}, current ${$}`};y1(q,K),Q.push(K)}}let J=!0;while(J){J=!1;for(let q of O){if(q.status!=="active")continue;for(let[K,X]of Object.entries(q.manifest.dependencies??{})){let G=Z.get(K),W;if(!G)W={code:"dependency-missing",dependency:K,expected:X,message:`Missing dependency ${K}@${X}`};else if(!p0(G.manifest.version,X))W={code:"dependency-version",dependency:K,expected:X,actual:G.manifest.version,message:`Dependency ${K} requires ${X}, found ${G.manifest.version}`};else if(G.status!=="active")W={code:"dependency-inactive",dependency:K,expected:X,actual:G.status,message:`Dependency ${K} is ${G.status}`};if(!W)continue;y1(q,W),Q.push(W),J=!0;break}}}return Q}import{execFile as L$}from"node:child_process";import{createHash as X$,randomUUID as n1}from"node:crypto";import{constants as O0,promises as F}from"node:fs";import{homedir as s0}from"node:os";import j from"node:path";import{promisify as W$}from"node:util";import{Mutex as Y$}from"async-mutex";import{satisfies as n0}from"semver";import H$ from"write-file-atomic";import*as B0 from"node:fs/promises";import*as c1 from"node:path";var c=L.String({minLength:2,maxLength:64,pattern:"^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]{1,2}$"}),c0=L.String({pattern:"^\\d+\\.\\d+\\.\\d+(-[\\w.]+)?(\\+[\\w.]+)?$"}),nO=L.Object({name:L.String({minLength:1}),email:L.Optional(L.String({format:"email"})),url:L.Optional(L.String({format:"uri"}))}),d1=L.Object({name:c,description:L.String({minLength:1,maxLength:500}),version:c0,author:L.Optional(nO),license:L.Optional(L.String()),repository:L.Optional(L.String({format:"uri"})),homepage:L.Optional(L.String({format:"uri"})),keywords:L.Optional(L.Array(L.String())),dependencies:L.Optional(L.Record(L.String(),L.String())),bladeVersion:L.Optional(L.String())}),iO=L.Union([L.Object({type:L.Literal("git"),url:L.String({minLength:1}),ref:L.Optional(L.String({minLength:1}))},{additionalProperties:!1}),L.Object({type:L.Literal("local"),path:L.String({minLength:1})},{additionalProperties:!1}),L.Object({type:L.Literal("marketplace"),marketplace:c},{additionalProperties:!1})]),oO=L.Object({name:c,source:iO,installPath:L.String({minLength:1}),version:c0,revision:L.String({minLength:1,maxLength:128}),contentDigest:L.String({pattern:"^[a-f0-9]{64}$"}),installedAt:L.String({format:"date-time"}),updatedAt:L.String({format:"date-time"})},{additionalProperties:!1}),aO=L.Union([L.Object({type:L.Literal("git"),url:L.String({minLength:1}),ref:L.Optional(L.String({minLength:1}))},{additionalProperties:!1}),L.Object({type:L.Literal("local"),path:L.String({minLength:1})},{additionalProperties:!1})]),tO=L.Object({name:c,source:aO,installPath:L.String({minLength:1}),revision:L.String({minLength:1,maxLength:128}),contentDigest:L.String({pattern:"^[a-f0-9]{64}$"}),addedAt:L.String({format:"date-time"}),updatedAt:L.String({format:"date-time"})},{additionalProperties:!1}),rO=L.Object({version:L.Literal(1),installed:L.Record(L.String(),oO),marketplaces:L.Record(L.String(),tO)},{additionalProperties:!1}),m1=L.Object({name:L.String({minLength:1}),email:L.Optional(L.String({format:"email"})),url:L.Optional(L.String({format:"uri"}))}),eO=L.Object({name:c,description:L.Optional(L.String({maxLength:500})),version:L.Optional(c0),author:L.Optional(L.Union([L.String({minLength:1}),m1])),source:L.Union([L.String({minLength:1}),L.Object({source:L.Literal("url"),url:L.String({minLength:1}),ref:L.Optional(L.String({minLength:1})),sha:L.Optional(L.String({pattern:"^[a-fA-F0-9]{40}$"}))})]),category:L.Optional(L.String()),homepage:L.Optional(L.String({format:"uri"})),tags:L.Optional(L.Array(L.String()))}),O$=L.Object({name:c,description:L.Optional(L.String({maxLength:500})),owner:L.Optional(m1),metadata:L.Optional(L.Object({description:L.Optional(L.String({maxLength:500})),version:L.Optional(L.String())})),plugins:L.Array(eO,{maxItems:5000})}),k1=L.Object({type:P1(["stdio","sse","http"]),command:L.Optional(L.String()),args:L.Optional(L.Array(L.String())),env:L.Optional(L.Record(L.String(),L.String())),cwd:L.Optional(L.String()),url:L.Optional(L.String({format:"uri"})),headers:L.Optional(L.Record(L.String(),L.String())),timeout:L.Optional(L.Integer({minimum:1000,maximum:1800000})),idleTimeout:L.Optional(L.Integer({minimum:1000,maximum:1800000})),sampling:L.Optional(L.Object({enabled:L.Boolean(),maxTokens:L.Optional(L.Integer({minimum:1,maximum:4096})),maxRequestsPerToolCall:L.Optional(L.Integer({minimum:1,maximum:8})),maxInputBytes:L.Optional(L.Integer({minimum:1,maximum:1048576}))})),oauth:L.Optional(L.Object({enabled:L.Optional(L.Boolean()),clientId:L.Optional(L.String({minLength:1,maxLength:4096})),scopes:L.Optional(L.Array(L.String({minLength:1,maxLength:128}),{maxItems:32})),callbackPort:L.Optional(L.Integer({minimum:1024,maximum:65535}))},{additionalProperties:!1})),healthCheck:L.Optional(L.Object({enabled:L.Optional(L.Boolean()),interval:L.Optional(L.Number({exclusiveMinimum:0})),timeout:L.Optional(L.Number({exclusiveMinimum:0})),failureThreshold:L.Optional(L.Number({exclusiveMinimum:0}))}))}),$$=L.Union([L.Object({mcpServers:L.Record(L.String(),k1)}),L.Record(L.String(),k1)]);function p1(O){return u($$,O)}function g1(O){return u(rO,O)}function u1(O){return u(O$,O)}var Q$=[{dir:".blade-plugin",source:"blade"},{dir:".claude-plugin",source:"claude"}];async function r(O){for(let{dir:$,source:Q}of Q$){let Z=c1.join(O,$,"plugin.json");try{await B0.access(Z)}catch{continue}try{let J=await B0.readFile(Z,"utf-8"),q=JSON.parse(J),K=u(d1,q);if(!K.success){let X=K.error.issues.map((G)=>`${G.path.join(".")}: ${G.message}`).join("; ");throw Error(`Invalid plugin.json: ${X}`)}return u0(K.data),z.debug(`Parsed plugin manifest from ${Z}`),{manifest:K.data,source:Q,manifestPath:Z}}catch(J){if(J instanceof SyntaxError)throw Error(`Invalid JSON in ${Z}: ${J.message}`);throw J}}return null}import{realpathSync as Z$}from"node:fs";import l0 from"node:path";var J$=/^[a-fA-F0-9]{40}$/;class f extends Error{code;constructor(O,$){super($);this.code=O;this.name="PluginSourcePolicyError"}}function K$(O,$){let Q=(J)=>{try{return Z$.native(J)}catch{return l0.resolve(J)}},Z=l0.relative(Q(O),Q($));return Z===""||!Z.startsWith("..")&&!l0.isAbsolute(Z)}function q$(O){let $=O.match(/^[^@]+@([^:]+):/);if($?.[1])return $[1].toLowerCase();try{return new URL(O).hostname.toLowerCase()}catch{return}}function G$(O,$){if(!$.startsWith("*."))return O===$;let Q=$.slice(1);return O.endsWith(Q)&&O.length>Q.length}function l1(O,$,Q){if(O.requireGitCommitSha&&(!$.ref||!J$.test($.ref)))throw new f("PLUGIN_GIT_SHA_REQUIRED",`${Q} must pin a full 40-character Git commit SHA`);if(!O.restrictToAllowedSources)return;let Z=q$($.url);if(!Z||!O.allowedGitHosts.some((J)=>G$(Z,J)))throw new f("PLUGIN_SOURCE_BLOCKED",`${Q} Git host is not allowed by plugin source policy`)}function s1(O,$,Q){if(!O.restrictToAllowedSources)return;if(!O.allowedLocalRoots.some((Z)=>K$(Z,$)))throw new f("PLUGIN_SOURCE_BLOCKED",`${Q} local path is not allowed by plugin source policy`)}function l(O,$,Q="Marketplace"){if($.type==="git")l1(O,$,Q);else s1(O,$.path,Q)}function e(O,$,Q,Z="Plugin"){if($.type==="git"){l1(O,$,Z);return}if($.type==="local"){s1(O,$.path,Z);return}if(O.restrictToAllowedSources&&!O.allowedMarketplaces.includes($.marketplace))throw new f("PLUGIN_SOURCE_BLOCKED",`Marketplace "${$.marketplace}" is not allowed by plugin source policy`);let J=Q[$.marketplace];if(!J)throw new f("MARKETPLACE_NOT_FOUND",`Marketplace "${$.marketplace}" is not configured`);l(O,J.source,`Marketplace "${$.marketplace}"`)}var F$=W$(L$),V$=1,i1=2097152,o1=1e4,a1=104857600,U$=120000,j$=15000,B$=600000,a0=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,t1=/^[a-fA-F0-9]{40}$/,z$=[j.join(".blade-plugin","marketplace.json"),j.join(".claude-plugin","marketplace.json"),"marketplace.json"];class H extends Error{code;constructor(O,$){super($);this.code=O;this.name="PluginPackageError"}}function S$(){return{version:V$,installed:{},marketplaces:{}}}function s(O){return O.code==="ENOENT"}function n(O){if(O instanceof H||O instanceof f)return{code:O.code,message:O.message};return{code:"PLUGIN_PACKAGE_ERROR",message:O instanceof Error?O.message:String(O)}}function i0(O){return j.isAbsolute(O)||O.startsWith("./")||O.startsWith("../")||O==="~"||O.startsWith("~/")}function $0(O,$){let Q=j.relative(O,$);return Q===""||!Q.startsWith("..")&&!j.isAbsolute(Q)}function i(O,$="plugin"){if(!a0.test(O))throw new H("INVALID_PLUGIN_NAME",`Invalid ${$} name: ${O}`);return O}function M$(O){if(O.startsWith("git@"))return;let $=O.lastIndexOf("@");if($<=0||$===O.length-1)return;let Q=O.slice(0,$),Z=O.slice($+1);if(!a0.test(Q)||!a0.test(Z))return;return{pluginName:Q,marketplace:Z}}class r1{userPluginsDir;stateRoot;statePath;mutex=new Y$;constructor(O,$){this.userPluginsDir=O??j.join(s0(),".blade","plugins"),this.stateRoot=$??j.join(j.dirname(this.userPluginsDir),"plugin-state"),this.statePath=j.join(this.stateRoot,"state.json")}async install(O,$={}){return this.runMutation(async()=>{let Q=[];try{this.requireSourceTrust($.trusted);let Z=await this.readState(),J=await this.resolvePluginSource(O,Z,$),q=this.effectivePolicy($.policy);if(e(q,J.recordSource,Z.marketplaces),J.expectedName&&Z.installed[J.expectedName])throw new H("PLUGIN_ALREADY_INSTALLED",`Plugin "${J.expectedName}" is already installed`);let K=await this.preparePluginClosure({state:Z,source:J.source,recordSource:J.recordSource,expectedName:J.expectedName,policy:q,updateRoot:!1});Q=K.prepared;let X=await this.commitPreparedPlugins(Z,Q),G=X.records.get(K.root.name);if(!G)throw new H("PLUGIN_PACKAGE_ERROR","Root plugin was not committed");let W=Q.map((Y)=>Y.name).filter((Y)=>Y!==K.root.name);return z.info(`Installed managed plugin ${K.root.name} at revision ${G.revision}`),{success:!0,pluginName:K.root.name,pluginPath:G.installPath,manifest:K.root.manifest,installation:G,installedDependencies:W,changed:X.changed.has(K.root.name)}}catch(Z){await this.cleanupPreparedPlugins(Q);let J=n(Z);return{success:!1,code:J.code,error:J.message}}})}async update(O,$={}){return this.runMutation(async()=>{let Q=[];try{this.requireSourceTrust($.trusted),i(O);let Z=await this.readState(),J=Z.installed[O];if(!J)throw new H("PLUGIN_NOT_MANAGED",`Plugin "${O}" is not managed by Blade's package store`);let q=this.effectivePolicy($.policy);e(q,J.source,Z.marketplaces);let K=await this.preparePluginClosure({state:Z,source:J.source,recordSource:J.source,expectedName:O,policy:q,updateRoot:!0});Q=K.prepared;let X=await this.commitPreparedPlugins(Z,Q),G=X.records.get(O);if(!G)throw new H("PLUGIN_PACKAGE_ERROR","Updated root plugin was not committed");let W=Q.map((Y)=>Y.name).filter((Y)=>Y!==O&&X.changed.has(Y));return z.info(`Updated managed plugin ${O} to revision ${G.revision}`),{success:!0,pluginName:O,pluginPath:G.installPath,manifest:K.root.manifest,installation:G,updatedDependencies:W,changed:X.changed.has(O)}}catch(Z){await this.cleanupPreparedPlugins(Q);let J=n(Z);return{success:!1,pluginName:O,code:J.code,error:J.message}}})}async uninstall(O,$=!1){return this.runMutation(async()=>{try{if(i(O),!$)throw new H("CONFIRMATION_REQUIRED",`Uninstalling "${O}" requires explicit confirmation`);let Q=await this.readState(),Z=Q.installed[O];if(!Z)throw new H("PLUGIN_NOT_MANAGED",`Plugin "${O}" is not managed by Blade's package store`);return delete Q.installed[O],await this.writeState(Q),z.info(`Uninstalled managed plugin ${O}`),{success:!0,pluginName:O,installation:Z}}catch(Q){let Z=n(Q);return{success:!1,pluginName:O,code:Z.code,error:Z.message}}})}async listInstalled(){return Object.keys((await this.readState()).installed).sort()}async listInstallationRecords(){return Object.values((await this.readState()).installed).sort((O,$)=>O.name.localeCompare($.name))}async getInstallation(O){return(await this.readState()).installed[O]}async verifyInstallation(O){let $=await F.lstat(O.installPath);if(!$.isDirectory()||$.isSymbolicLink())throw new H("PLUGIN_PACKAGE_TAMPERED",`Managed plugin "${O.name}" has an invalid package path`);let Q=await F.realpath(this.stateRoot),Z=await F.realpath(O.installPath);if(!$0(Q,Z))throw new H("PLUGIN_PACKAGE_TAMPERED",`Managed plugin "${O.name}" has an invalid package path`);if(await this.digestTree(Z)!==O.contentDigest)throw new H("PLUGIN_PACKAGE_TAMPERED",`Managed plugin "${O.name}" failed content verification`);let q=await r(Z);if(!q||q.manifest.name!==O.name||q.manifest.version!==O.version)throw new H("PLUGIN_PACKAGE_TAMPERED",`Managed plugin "${O.name}" failed manifest verification`)}async addMarketplace(O,$={}){return this.runMutation(async()=>{let Q;try{let Z=await this.normalizeMarketplaceSource(O,$);l(this.effectivePolicy($.policy),Z);let J=await this.readState();Q=await this.materializeSource(Z);let q=await this.readMarketplaceManifest(Q.stagingPath),K=i(q.name,"marketplace");if(J.marketplaces[K])throw new H("MARKETPLACE_ALREADY_EXISTS",`Marketplace "${K}" is already configured`);let{revision:X,contentDigest:G}=Q,W=await this.publishPackage("marketplaces",K,Q);Q=void 0;let Y=new Date().toISOString(),V={name:K,source:Z,installPath:W,revision:X,contentDigest:G,addedAt:Y,updatedAt:Y};return J.marketplaces[K]=V,await this.writeState(J),{success:!0,marketplace:V,manifest:q,changed:!0}}catch(Z){if(Q)await F.rm(Q.stagingPath,{recursive:!0,force:!0});let J=n(Z);return{success:!1,code:J.code,error:J.message}}})}async refreshMarketplace(O,$){return this.runMutation(async()=>{let Q;try{i(O,"marketplace");let Z=await this.readState(),J=Z.marketplaces[O];if(!J)throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${O}" is not configured`);l(this.effectivePolicy($),J.source,`Marketplace "${O}"`),Q=await this.materializeSource(J.source);let q=await this.readMarketplaceManifest(Q.stagingPath);if(q.name!==O)throw new H("MARKETPLACE_IDENTITY_MISMATCH",`Marketplace "${O}" now declares "${q.name}"`);if(J.revision===Q.revision&&J.contentDigest===Q.contentDigest)return await F.rm(Q.stagingPath,{recursive:!0,force:!0}),Q=void 0,{success:!0,marketplace:J,manifest:q,changed:!1};let{revision:K,contentDigest:X}=Q,G=await this.publishPackage("marketplaces",O,Q);Q=void 0;let W={...J,installPath:G,revision:K,contentDigest:X,updatedAt:new Date().toISOString()};return Z.marketplaces[O]=W,await this.writeState(Z),{success:!0,marketplace:W,manifest:q,changed:!0}}catch(Z){if(Q)await F.rm(Q.stagingPath,{recursive:!0,force:!0});let J=n(Z);return{success:!1,code:J.code,error:J.message}}})}async removeMarketplace(O,$=!1){return this.runMutation(async()=>{try{if(i(O,"marketplace"),!$)throw new H("CONFIRMATION_REQUIRED",`Removing marketplace "${O}" requires explicit confirmation`);let Q=await this.readState(),Z=Q.marketplaces[O];if(!Z)throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${O}" is not configured`);let J=Object.values(Q.installed).filter((q)=>q.source.type==="marketplace"&&q.source.marketplace===O).map((q)=>q.name).sort();if(J.length>0)throw new H("MARKETPLACE_IN_USE",`Marketplace "${O}" still owns installed plugins: ${J.join(", ")}`);return delete Q.marketplaces[O],await this.writeState(Q),{success:!0,marketplace:Z,changed:!0}}catch(Q){let Z=n(Q);return{success:!1,code:Z.code,error:Z.message}}})}async listMarketplaces(){return Object.values((await this.readState()).marketplaces).sort((O,$)=>O.name.localeCompare($.name))}async listCatalogs(){let O=await this.listMarketplaces();return Promise.all(O.map(async($)=>({marketplace:$,manifest:await this.readMarketplaceManifest($.installPath)})))}async runMutation(O){return this.mutex.runExclusive(async()=>{let $=await this.acquireStoreLock();try{return await O()}finally{await $()}})}async acquireStoreLock(){await this.ensureStoreDirectory();let O=j.join(this.stateRoot,".operation.lock"),$=n1(),Q=Date.now()+j$;while(Date.now()<Q)try{let Z=await F.open(O,O0.O_CREAT|O0.O_EXCL|O0.O_WRONLY,384);return await Z.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:$,createdAt:new Date().toISOString()})}
708
- `,"utf8"),await Z.close(),async()=>{try{if(JSON.parse(await F.readFile(O,"utf8")).token===$)await F.unlink(O)}catch(J){if(!s(J))z.warn(`Failed to release plugin package lock: ${J}`)}}}catch(Z){if(Z.code!=="EEXIST")throw Z;await this.removeStaleStoreLock(O),await new Promise((J)=>setTimeout(J,50))}throw new H("PLUGIN_STORE_BUSY","Plugin package store is busy; retry the operation")}async removeStaleStoreLock(O){try{let $=await F.lstat(O);if(!$.isFile()||$.isSymbolicLink())throw new H("PLUGIN_STORE_INVALID","Plugin package lock must be a regular file");if(process.getuid&&$.uid!==process.getuid()||($.mode&511)!==384)throw new H("PLUGIN_STORE_INVALID","Plugin package lock ownership or permissions are invalid");if(Date.now()-$.mtimeMs<B$)return;await F.unlink(O)}catch($){if(!s($)&&$ instanceof H)throw $}}requireSourceTrust(O){if(O!==!0)throw new H("SOURCE_TRUST_REQUIRED","Plugin installation or update requires explicit source trust")}effectivePolicy(O){return O??z0.pluginSourcePolicy}async preparePluginClosure(O){let $=[],Q=new Map,Z=[],J=(K,X,G,W)=>{if(!n0(X,G))throw new H("DEPENDENCY_VERSION_MISMATCH",`Plugin "${W}" requires ${K}@${G}, found ${X}`)},q=async(K)=>{let X=K.expectedName?O.state.installed[K.expectedName]:void 0;if(X&&!K.root&&K.requiredRange){if(n0(X.version,K.requiredRange))return X;if(K.recordSource.type!=="marketplace"||X.source.type!=="marketplace"||X.source.marketplace!==K.recordSource.marketplace)J(X.name,X.version,K.requiredRange,K.requiredBy??"dependency");K={...K,source:X.source,recordSource:X.source}}if(X&&K.root&&!O.updateRoot)throw new H("PLUGIN_ALREADY_INSTALLED",`Plugin "${X.name}" is already installed`);if(K.expectedName){let B=Q.get(K.expectedName);if(B){if(K.requiredRange)J(B.name,B.manifest.version,K.requiredRange,K.requiredBy??"dependency");return B}if(Z.includes(K.expectedName))throw new H("DEPENDENCY_CYCLE",`Plugin dependency cycle: ${[...Z,K.expectedName].join(" -> ")}`)}let G=await this.materializePluginSource(K.source,O.state,K.expectedName,O.policy),W=await r(G.stagingPath);if(!W)throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("INVALID_PLUGIN","Plugin manifest was not found");let Y=i(W.manifest.name);if(K.expectedName&&K.expectedName!==Y)throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("PLUGIN_IDENTITY_MISMATCH",`Requested "${K.expectedName}" but source declares "${Y}"`);if(Z.includes(Y))throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("DEPENDENCY_CYCLE",`Plugin dependency cycle: ${[...Z,Y].join(" -> ")}`);if(K.root&&O.state.installed[Y]&&!O.updateRoot)throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("PLUGIN_ALREADY_INSTALLED",`Plugin "${Y}" is already installed`);try{f1(W.manifest)}catch(B){throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("VERSION_INCOMPATIBLE",B instanceof Error?B.message:String(B))}let V={name:Y,source:K.recordSource,manifest:W.manifest,materialized:G,existing:O.state.installed[Y]};Z.push(Y);try{for(let[B,p]of Object.entries(W.manifest.dependencies??{}).sort(([G0],[y])=>G0.localeCompare(y))){let G0=Q.get(B);if(G0){J(B,G0.manifest.version,p,Y);continue}let y=O.state.installed[B];if(y&&n0(y.version,p))continue;if(K.recordSource.type!=="marketplace")throw new H(y?"DEPENDENCY_VERSION_MISMATCH":"DEPENDENCY_MISSING",y?`Plugin "${Y}" requires ${B}@${p}, found ${y.version}`:`Plugin "${Y}" requires missing dependency ${B}@${p}; direct sources cannot auto-install dependencies`);let C0=await q({source:y?.source.type==="marketplace"&&y.source.marketplace===K.recordSource.marketplace?y.source:{type:"marketplace",marketplace:K.recordSource.marketplace},recordSource:{type:"marketplace",marketplace:K.recordSource.marketplace},expectedName:B,requiredRange:p,requiredBy:Y,root:!1});J(B,"manifest"in C0?C0.manifest.version:C0.version,p,Y)}}catch(B){throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),B}finally{Z.pop()}return Q.set(Y,V),$.push(V),V};try{let K=await q({source:O.source,recordSource:O.recordSource,expectedName:O.expectedName,root:!0});if(!("manifest"in K))throw new H("PLUGIN_PACKAGE_ERROR","Root plugin unexpectedly resolved to an existing dependency");return{root:K,prepared:$}}catch(K){throw await this.cleanupPreparedPlugins($),K}}async commitPreparedPlugins(O,$){let Q=new Map,Z=new Set,J=new Date().toISOString();for(let q of $){let K=q.existing;if(K?.revision===q.materialized.revision&&K.contentDigest===q.materialized.contentDigest){await F.rm(q.materialized.stagingPath,{recursive:!0,force:!0}),Q.set(q.name,K);continue}let X=await this.publishPackage("packages",q.name,q.materialized),G={name:q.name,source:q.source,installPath:X,version:q.manifest.version,revision:q.materialized.revision,contentDigest:q.materialized.contentDigest,installedAt:K?.installedAt??J,updatedAt:J};O.installed[q.name]=G,Q.set(q.name,G),Z.add(q.name)}if(Z.size>0)await this.writeState(O);return{records:Q,changed:Z}}async cleanupPreparedPlugins(O){await Promise.all(O.map(($)=>F.rm($.materialized.stagingPath,{recursive:!0,force:!0})))}async resolvePluginSource(O,$,Q){let Z=O.trim();if(!Z)throw new H("INVALID_SOURCE","Plugin source is required");let J=M$(Z);if(J){if(!$.marketplaces[J.marketplace])throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${J.marketplace}" is not configured`);return{source:{type:"marketplace",marketplace:J.marketplace},recordSource:{type:"marketplace",marketplace:J.marketplace},expectedName:J.pluginName}}if(!i0(Z)&&!this.looksLikeGitSource(Z)){let K=[];for(let X of await this.catalogsFromState($))if(X.manifest.plugins.some((G)=>G.name===Z))K.push({pluginName:Z,marketplace:X.marketplace.name});if(K.length===1)return{source:{type:"marketplace",marketplace:K[0].marketplace},recordSource:{type:"marketplace",marketplace:K[0].marketplace},expectedName:Z};if(K.length>1)throw new H("AMBIGUOUS_PLUGIN_SOURCE",`Plugin "${Z}" exists in multiple marketplaces; use name@marketplace`)}if(i0(Z)){let X={type:"local",path:await this.resolveLocalSource(Z,Q.workspaceRoot)};return{source:X,recordSource:X}}let q=this.normalizeGitSource(Z,Q.ref);return{source:q,recordSource:q}}async materializePluginSource(O,$,Q,Z){if(O.type!=="marketplace")return this.materializeSource(O);let J=$.marketplaces[O.marketplace];if(!J)throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${O.marketplace}" is not configured`);let q=await this.readMarketplaceManifest(J.installPath),K=Q?q.plugins.filter((X)=>X.name===Q):q.plugins;if(K.length!==1)throw new H("MARKETPLACE_PLUGIN_NOT_FOUND",Q?`Plugin "${Q}" was not found in marketplace "${O.marketplace}"`:`Marketplace "${O.marketplace}" requires an explicit plugin name`);return this.materializeMarketplaceEntry(J,K[0],Z)}async materializeMarketplaceEntry(O,$,Q){if(typeof $.source!=="string"){let K=this.normalizeGitSource($.source.url,$.source.sha??$.source.ref);return l(Q,K,`Plugin "${$.name}"`),this.materializeSource(K)}if($.source.startsWith("https://")||$.source.startsWith("ssh://")||$.source.startsWith("git@")){let K=this.normalizeGitSource($.source);return l(Q,K,`Plugin "${$.name}"`),this.materializeSource(K)}let Z=await F.realpath(O.installPath),J=j.resolve(Z,$.source);if(!$0(Z,J)||J===Z)throw new H("MARKETPLACE_PATH_ESCAPE",`Plugin "${$.name}" source escapes its marketplace`);let q=await F.realpath(J);if(!$0(Z,q))throw new H("MARKETPLACE_PATH_ESCAPE",`Plugin "${$.name}" source escapes its marketplace`);return this.materializeSource({type:"local",path:q})}async normalizeMarketplaceSource(O,$){let Q=O.trim();if(!Q)throw new H("INVALID_SOURCE","Marketplace source is required");if(i0(Q))return{type:"local",path:await this.resolveLocalSource(Q,$.workspaceRoot)};return this.normalizeGitSource(Q,$.ref)}normalizeGitSource(O,$){let Q=O;if(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(O))Q=`https://github.com/${O}.git`;else if(O.startsWith("git@")){if(!/^git@[A-Za-z0-9.-]+:[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:\.git)?$/.test(O))throw new H("INVALID_SOURCE","Invalid SSH Git source")}else{let Z;try{Z=new URL(O)}catch{throw new H("INVALID_SOURCE","Invalid Git source")}if(Z.protocol!=="https:"&&Z.protocol!=="ssh:")throw new H("UNSAFE_GIT_PROTOCOL","Git sources must use HTTPS or SSH");if(Z.password||Z.protocol==="https:"&&Z.username)throw new H("GIT_CREDENTIALS_IN_URL","Git credentials must not be embedded in plugin source URLs");if(Z.hash||Z.search)throw new H("INVALID_SOURCE","Use the ref option instead of URL query or fragment parameters");Q=Z.toString()}if($&&(!$.trim()||$.startsWith("-")||$.includes("\x00")))throw new H("INVALID_GIT_REF","Invalid Git ref");return{type:"git",url:Q,...$?{ref:$}:{}}}looksLikeGitSource(O){return O.startsWith("https://")||O.startsWith("ssh://")||O.startsWith("git@")||/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(O)}async resolveLocalSource(O,$){let Q=O==="~"?s0():O.startsWith("~/")?j.join(s0(),O.slice(2)):O,Z=j.resolve($??process.cwd(),Q),J;try{J=await F.realpath(Z)}catch{throw new H("LOCAL_SOURCE_NOT_FOUND",`Local source does not exist: ${O}`)}let q=await F.lstat(J);if(!q.isDirectory()||q.isSymbolicLink())throw new H("INVALID_LOCAL_SOURCE","Local plugin sources must be regular directories");return J}async materializeSource(O){await this.ensureStoreDirectory();let $=j.join(this.stateRoot,"staging",n1());if(await F.mkdir(j.dirname($),{recursive:!0,mode:448}),O.type==="git"){await this.cloneGitSource(O,$);let Z=await this.runGit(["rev-parse","HEAD"],$);if(O.ref&&t1.test(O.ref)&&Z.toLowerCase()!==O.ref.toLowerCase())throw await F.rm($,{recursive:!0,force:!0}),new H("GIT_PIN_MISMATCH","Plugin checkout does not match the requested Git commit SHA");await F.rm(j.join($,".git"),{recursive:!0,force:!0});let J=await this.digestTree($);return{stagingPath:$,revision:Z,contentDigest:J}}await this.copyLocalSource(O.path,$);let Q=await this.digestTree($);return{stagingPath:$,revision:`local-${Q.slice(0,40)}`,contentDigest:Q}}async cloneGitSource(O,$){try{if(O.ref&&t1.test(O.ref))await F.mkdir($,{recursive:!0,mode:448}),await this.runGit(["init"],$),await this.runGit(["remote","add","origin",O.url],$),await this.runGit(["fetch","--depth","1","origin",O.ref],$),await this.runGit(["checkout","--detach","FETCH_HEAD"],$);else{let Q=["clone","--depth","1","--no-tags"];if(O.ref)Q.push("--branch",O.ref);Q.push("--",O.url,$),await this.runGit(Q)}}catch(Q){throw await F.rm($,{recursive:!0,force:!0}),new H("GIT_CLONE_FAILED",`Failed to clone plugin source: ${this.sanitizeError(Q)}`)}}async runGit(O,$){let Q=await F$("git",O,{cwd:$,encoding:"utf8",timeout:U$,maxBuffer:4194304,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),Z=typeof Q==="string"?Q:Q.stdout;if(Z===void 0)throw Error("Git process returned an invalid result");return String(Z).trim()}sanitizeError(O){return(O instanceof Error?O.message:String(O)).replaceAll(this.stateRoot,"<plugin-store>").slice(0,500)}async copyLocalSource(O,$){await this.digestTree(O),await F.cp(O,$,{recursive:!0,force:!1,errorOnExist:!0,filter:(Q)=>{return!j.relative(O,Q).split(j.sep).includes(".git")}})}async digestTree(O){let $=[],Q=0,Z=async(q)=>{let K=await F.readdir(q,{withFileTypes:!0});K.sort((X,G)=>X.name.localeCompare(G.name));for(let X of K){if(X.name===".git")continue;let G=j.join(q,X.name),W=j.relative(O,G),Y=await F.lstat(G);if(Y.isSymbolicLink())throw new H("PACKAGE_SYMLINK_FORBIDDEN",`Plugin packages may not contain symbolic links: ${W}`);if(Y.isDirectory()){await Z(G);continue}if(!Y.isFile())throw new H("PACKAGE_ENTRY_FORBIDDEN",`Plugin packages may contain only files and directories: ${W}`);if(Q+=Y.size,$.push({relative:W,absolute:G,executable:(Y.mode&73)!==0}),$.length>o1||Q>a1)throw new H("PACKAGE_TOO_LARGE",`Plugin package exceeds ${o1} files or ${a1} bytes`)}};await Z(O);let J=X$("sha256");for(let q of $)J.update(q.relative),J.update("\x00"),J.update(q.executable?"x":"-"),J.update("\x00"),J.update(await F.readFile(q.absolute)),J.update("\x00");return J.digest("hex")}async publishPackage(O,$,Q){let Z=j.join(this.stateRoot,O,$,Q.contentDigest);await F.mkdir(j.dirname(Z),{recursive:!0,mode:448});try{let J=await F.lstat(Z);if(!J.isDirectory()||J.isSymbolicLink())throw new H("PACKAGE_STORE_CONFLICT","Plugin package destination is not a regular directory");return await F.rm(Q.stagingPath,{recursive:!0,force:!0}),Z}catch(J){if(!s(J))throw J}return await F.rename(Q.stagingPath,Z),Z}async readMarketplaceManifest(O){for(let $ of z$){let Q=j.join(O,$);try{let Z=await F.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink()||Z.size>i1)throw new H("INVALID_MARKETPLACE","Marketplace manifest must be a regular bounded file");let J=JSON.parse(await F.readFile(Q,"utf8")),q=u1(J);if(!q.success)throw new H("INVALID_MARKETPLACE",`Invalid marketplace manifest: ${q.error.issues.map((X)=>`${X.path.join(".")}: ${X.message}`).join("; ")}`);let K=new Set;for(let X of q.data.plugins){if(K.has(X.name))throw new H("INVALID_MARKETPLACE",`Marketplace contains duplicate plugin: ${X.name}`);K.add(X.name)}return q.data}catch(Z){if(s(Z))continue;if(Z instanceof SyntaxError)throw new H("INVALID_MARKETPLACE","Marketplace manifest contains invalid JSON");throw Z}}throw new H("INVALID_MARKETPLACE","Marketplace manifest was not found")}async catalogsFromState(O){let $=Object.values(O.marketplaces).sort((Q,Z)=>Q.name.localeCompare(Z.name));return Promise.all($.map(async(Q)=>({marketplace:Q,manifest:await this.readMarketplaceManifest(Q.installPath)})))}async readState(){let O;try{O=await F.open(this.statePath,O0.O_RDONLY|O0.O_NOFOLLOW)}catch($){if(s($))return S$();throw new H("PLUGIN_STATE_INVALID","Plugin package state must be a regular file")}try{let $=await O.stat();if(!$.isFile()||$.size>i1)throw new H("PLUGIN_STATE_INVALID","Plugin package state is invalid");if(process.getuid&&$.uid!==process.getuid())throw new H("PLUGIN_STATE_INVALID","Plugin package state must be owned by the current user");if(($.mode&511)!==384)throw new H("PLUGIN_STATE_INVALID","Plugin package state permissions must be 0600");let Q=JSON.parse(await O.readFile("utf8")),Z=g1(Q);if(!Z.success)throw new H("PLUGIN_STATE_INVALID","Plugin package state schema is invalid");let J=Z.data;for(let[q,K]of Object.entries(J.installed)){let X=j.join(this.stateRoot,"packages",q);if(q!==K.name||!j.isAbsolute(K.installPath)||!$0(X,K.installPath)||j.basename(K.installPath)!==K.contentDigest||K.source.type==="local"&&!j.isAbsolute(K.source.path))throw new H("PLUGIN_STATE_INVALID","Plugin package state contains an invalid installation");if(K.source.type==="git"){let G=this.normalizeGitSource(K.source.url,K.source.ref);if(G.url!==K.source.url||G.ref!==K.source.ref)throw new H("PLUGIN_STATE_INVALID","Plugin package state contains an invalid Git source")}}for(let[q,K]of Object.entries(J.marketplaces)){let X=j.join(this.stateRoot,"marketplaces",q);if(q!==K.name||!j.isAbsolute(K.installPath)||!$0(X,K.installPath)||j.basename(K.installPath)!==K.contentDigest||K.source.type==="local"&&!j.isAbsolute(K.source.path))throw new H("PLUGIN_STATE_INVALID","Plugin package state contains an invalid marketplace");if(K.source.type==="git"){let G=this.normalizeGitSource(K.source.url,K.source.ref);if(G.url!==K.source.url||G.ref!==K.source.ref)throw new H("PLUGIN_STATE_INVALID","Plugin package state contains an invalid Marketplace Git source")}}for(let q of Object.values(J.installed))if(q.source.type==="marketplace"&&!J.marketplaces[q.source.marketplace])throw new H("PLUGIN_STATE_INVALID","Plugin package state references a missing marketplace");return J}catch($){if($ instanceof SyntaxError)throw new H("PLUGIN_STATE_INVALID","Plugin package state contains invalid JSON");throw $}finally{await O.close()}}async writeState(O){await this.ensureStoreDirectory(),await H$(this.statePath,`${JSON.stringify(O,null,2)}
709
- `,{mode:384,encoding:"utf8"}),await F.chmod(this.statePath,384)}async ensureStoreDirectory(){try{let O=await F.lstat(this.stateRoot);if(!O.isDirectory()||O.isSymbolicLink())throw new H("PLUGIN_STORE_INVALID","Plugin package store must be a regular directory");if(process.getuid&&O.uid!==process.getuid())throw new H("PLUGIN_STORE_INVALID","Plugin package store must be owned by the current user");if((O.mode&511)!==448)throw new H("PLUGIN_STORE_INVALID","Plugin package store permissions must be 0700")}catch(O){if(!s(O))throw O;await F.mkdir(this.stateRoot,{recursive:!0,mode:448}),await F.chmod(this.stateRoot,448)}}}var o0=null;function t0(O,$){if(!o0)o0=new r1(O,$);return o0}import*as T from"node:fs/promises";import{homedir as I$}from"node:os";import*as I from"node:path";import OO from"gray-matter";function S0(O,$){return`${O}:${$}`}function e1(O,$){return`${O}__${$}`}class M0{async loadPlugin(O,$,Q={}){let Z=await r(O);if(!Z)throw Error(`Not a valid plugin directory: ${O}`);let{manifest:J,source:q}=Z,K=J.name;z.debug(`Loading plugin "${K}" from ${O}`);let X=Q.skipCommands?[]:await this.loadCommands(O,K),G=Q.skipAgents?[]:await this.loadAgents(O,K),W=Q.skipSkills?[]:await this.loadSkills(O,K),Y=Q.skipHooks?void 0:await this.loadHooks(O),V=Q.skipMcp?void 0:await this.loadMcpConfig(O,K),B=Q.skipLsp?void 0:await this.loadLspConfig(O,K);return z.debug(`Plugin "${K}" loaded: ${X.length} commands, ${G.length} agents, ${W.length} skills`),{manifest:J,basePath:O,source:$,manifestSource:q,commands:X,agents:G,skills:W,hooks:Y,mcpServers:V,lspServers:B,status:"active",loadedAt:new Date}}async loadCommands(O,$){let Q=I.join(O,"commands"),Z=[];if(!await this.dirExists(Q))return Z;let J=await this.scanMarkdownFiles(Q);for(let q of J)try{let K=await this.parseCommandFile(q,Q,$);if(K)Z.push(K)}catch(K){z.warn(`Failed to load command from ${q}: ${K instanceof Error?K.message:String(K)}`)}return Z}async parseCommandFile(O,$,Q){let Z=await T.readFile(O,"utf-8"),{data:J,content:q}=OO(Z),X=I.relative($,O).split(I.sep),G=X.pop();if(!G)return null;let W=G.replace(/\.md$/i,""),Y=W;if(X.length>0)Y=[...X,W].join("/");let V=S0(Q,Y),B=this.normalizeCommandConfig(J);return{originalName:Y,namespacedName:V,pluginName:Q,config:B,content:q.trim(),path:O}}normalizeCommandConfig(O){return{description:this.asString(O.description),allowedTools:this.parseStringArray(O["allowed-tools"]),argumentHint:this.asString(O["argument-hint"]),model:this.asString(O.model),disableModelInvocation:O["disable-model-invocation"]===!0}}async loadAgents(O,$){let Q=I.join(O,"agents"),Z=[];if(!await this.dirExists(Q))return Z;let J=await this.scanMarkdownFiles(Q);for(let q of J)try{let K=await this.parseAgentFile(q,Q,$);if(K)Z.push(K)}catch(K){z.warn(`Failed to load agent from ${q}: ${K instanceof Error?K.message:String(K)}`)}return Z}async parseAgentFile(O,$,Q){let Z=await T.readFile(O,"utf-8"),{data:J,content:q}=OO(Z),K=I.relative($,O),X=I.basename(K,".md"),G=J.name||X,W=S0(Q,G),Y={name:W,description:this.asString(J.description)||"",tools:this.parseStringArray(J.tools),color:this.asString(J.color),model:this.asString(J.model),permissionMode:this.asString(J.permissionMode),skills:this.parseStringArray(J.skills),systemPrompt:q.trim(),source:`plugin:${Q}`};return{originalName:G,namespacedName:W,pluginName:Q,config:Y,path:O}}async loadSkills(O,$){let Q=I.join(O,"skills"),Z=[];if(!await this.dirExists(Q))return Z;let J=await T.readdir(Q,{withFileTypes:!0});for(let q of J){if(!q.isDirectory())continue;let K=I.join(Q,q.name),X=I.join(K,"SKILL.md");try{let G=await U0(X,"project");if(G.success&&G.content){let W=G.content.metadata.name,Y=S0($,W);Z.push({originalName:W,namespacedName:Y,pluginName:$,metadata:{...G.content.metadata,name:Y},path:K})}}catch(G){z.warn(`Failed to load skill from ${X}: ${G instanceof Error?G.message:String(G)}`)}}return Z}async loadHooks(O){let $=I.join(O,"hooks","hooks.json");try{let Q=await T.readFile($,"utf-8"),Z=JSON.parse(Q);return Z.hooks||Z}catch{return}}async loadMcpConfig(O,$){let Q=I.join(O,".mcp.json");try{let Z=await T.readFile(Q,"utf-8"),J=JSON.parse(Z),q=p1(J);if(!q.success){z.warn(`Invalid .mcp.json in ${O}: ${q.error}`);return}let K="mcpServers"in J?J.mcpServers:J,X={};for(let[G,W]of Object.entries(K)){let Y=e1($,G);X[Y]=W}return X}catch{return}}async loadLspConfig(O,$){let Q=I.join(O,".lsp.json");try{let Z=JSON.parse(await T.readFile(Q,"utf8")),J=Z&&typeof Z==="object"&&!Array.isArray(Z)&&"lspServers"in Z?Z.lspServers:Z,q=$O(J),K={};for(let[X,G]of Object.entries(q)){let W=(Y)=>Y.replaceAll("${CLAUDE_PLUGIN_ROOT}",O).replaceAll("${BLADE_PLUGIN_ROOT}",O);K[`plugin:${$}:${X}`]={...G,command:W(G.command),args:G.args?.map(W),env:G.env?Object.fromEntries(Object.entries(G.env).map(([Y,V])=>[Y,W(V)])):void 0}}return K}catch(Z){if(Z.code!=="ENOENT")z.warn(`Invalid .lsp.json in ${O}: ${Z instanceof Error?Z.message:String(Z)}`);return}}async scanMarkdownFiles(O){let $=[],Q=async(Z)=>{let J=await T.readdir(Z,{withFileTypes:!0});for(let q of J){let K=I.join(Z,q.name);if(q.isDirectory())await Q(K);else if(q.name.endsWith(".md"))$.push(K)}};return await Q(O),$}async dirExists(O){try{return(await T.stat(O)).isDirectory()}catch{return!1}}asString(O){if(typeof O==="string"&&O.trim())return O.trim();return}parseStringArray(O){if(!O)return;if(Array.isArray(O))return O.map(($)=>String($).trim()).filter(Boolean);if(typeof O==="string")return O.split(",").map(($)=>$.trim()).filter(Boolean);return}static getPluginDirs(O){let $=I$();return[{path:I.join($,".claude","plugins"),source:"user",type:"claude"},{path:I.join($,".blade","plugins"),source:"user",type:"blade"},{path:I.join(O,".claude","plugins"),source:"project",type:"claude"},{path:I.join(O,".blade","plugins"),source:"project",type:"blade"}]}async discoverPluginsInDir(O,$){let Q=[],Z=[];try{await T.access(O)}catch{return{plugins:Q,errors:Z}}let J=await T.readdir(O,{withFileTypes:!0});for(let q of J){if(!q.isDirectory())continue;let K=I.join(O,q.name);try{let X=await this.loadPlugin(K,$);Q.push(X)}catch(X){Z.push({path:K,error:X instanceof Error?X.message:String(X)})}}return{plugins:Q,errors:Z}}}class D{static instances=new Map;plugins=new Map;loader=new M0;initialized=!1;workspaceRoot="";cliPluginDirs=[];enabledSettings={};sourcePolicy={...z0.pluginSourcePolicy};marketplaces={};constructor(O){this.workspaceRoot=O}static getInstance(O=M()){let $=r0.resolve(O),Q=D.instances.get($);if(!Q)Q=new D($),D.instances.set($,Q);return Q}static resetInstance(){D.instances.clear()}static releaseInstance(O,$){let Q=r0.resolve(O),Z=D.instances.get(Q);if(!Z||$&&Z!==$)return!1;return D.instances.delete(Q)}static getExistingInstance(O=M()){return D.instances.get(r0.resolve(O))}static getInitializedInstances(){return Array.from(D.instances.values()).filter((O)=>O.isInitialized())}async initialize(O,$=[]){this.workspaceRoot=O,this.cliPluginDirs=$,this.enabledSettings=await I0.getInstance().loadWorkspacePluginSettings(O),await this.refreshPolicyContext();let Q=[],Z=[];for(let G of $)try{let W=await this.loader.loadPlugin(G,"cli");this.plugins.set(W.manifest.name,W),Q.push(W),z.info(`Loaded CLI plugin: ${W.manifest.name} from ${G}`)}catch(W){Z.push({path:G,error:W instanceof Error?W.message:String(W)}),z.warn(`Failed to load CLI plugin from ${G}: ${W}`)}let J=(await N.getInstance().getStatus(O)).state==="trusted",q=M0.getPluginDirs(O).filter((G)=>G.source!=="project"||J),K=!1,X=async()=>{if(K)return;K=!0;let G=t0(),W=await G.listInstallationRecords();for(let Y of W)try{await G.verifyInstallation(Y);let V=await this.loader.loadPlugin(Y.installPath,"user");if(V.manifest.name!==Y.name)throw Error(`Managed plugin identity mismatch: ${Y.name}`);V.installation=Object.freeze({...Y});let B=this.plugins.get(V.manifest.name);if(!B||B.source==="user")this.plugins.set(V.manifest.name,V),Q.push(V)}catch(V){Z.push({path:Y.installPath,code:"IO_ERROR",error:V instanceof Error?V.message:String(V)})}};for(let{path:G,source:W}of q){if(W==="project")await X();let Y=await this.loader.discoverPluginsInDir(G,W);for(let V of Y.plugins){let B=this.plugins.get(V.manifest.name);if(!B||B.source!=="cli")this.plugins.set(V.manifest.name,V),Q.push(V)}Z.push(...Y.errors)}await X(),this.applyEnabledSettings();for(let G of this.plugins.values()){if(G.status!=="error")continue;Z.push({path:G.basePath,code:G.compatibilityIssues?.some((W)=>W.code==="source-policy")?"SOURCE_POLICY_BLOCKED":G.compatibilityIssues?.some((W)=>W.code==="blade-version")?"VERSION_INCOMPATIBLE":"DEPENDENCY_MISSING",error:G.error??"Plugin compatibility check failed"})}return this.initialized=!0,z.info(`Plugin system initialized: ${this.plugins.size} plugins loaded`+(Z.length>0?`, ${Z.length} errors`:"")),{plugins:Array.from(this.plugins.values()),errors:Z}}isInitialized(){return this.initialized}getWorkspaceRoot(){return this.workspaceRoot}getSourcePolicy(){return{...this.sourcePolicy,allowedGitHosts:[...this.sourcePolicy.allowedGitHosts],allowedMarketplaces:[...this.sourcePolicy.allowedMarketplaces],allowedLocalRoots:[...this.sourcePolicy.allowedLocalRoots]}}getAll(){return Array.from(this.plugins.values())}getActive(){return Array.from(this.plugins.values()).filter((O)=>O.status==="active")}get(O){return this.plugins.get(O)}has(O){return this.plugins.has(O)}async reapplyEnabledSettings(){this.enabledSettings=await I0.getInstance().loadWorkspacePluginSettings(this.workspaceRoot),await this.refreshPolicyContext(),this.applyEnabledSettings()}applyEnabledSettings(){for(let O of this.plugins.values()){if(O.compatibilityIssues=[],O.error=void 0,O.status=O.source==="cli"||this.enabledSettings[O.manifest.name]!==!1?"active":"inactive",O.status!=="active")continue;try{e(this.sourcePolicy,O.installation?.source??{type:"local",path:O.basePath},this.marketplaces,`Plugin "${O.manifest.name}"`)}catch($){if(!($ instanceof f))throw $;O.status="error",O.error=$.message,O.compatibilityIssues=[{code:"source-policy",message:$.message}]}}h1(Array.from(this.plugins.values()))}async refreshPolicyContext(){this.sourcePolicy=await I0.getInstance().loadWorkspacePluginSourcePolicy(this.workspaceRoot),this.marketplaces=Object.fromEntries((await t0().listMarketplaces()).map((O)=>[O.name,O]))}getBySource(){let O={cli:[],project:[],user:[]};for(let $ of this.plugins.values())O[$.source].push($);return O}getAllCommands(){let O=[];for(let $ of this.plugins.values())if($.status==="active")O.push(...$.commands);return O}getAllSkills(){let O=[];for(let $ of this.plugins.values())if($.status==="active")O.push(...$.skills);return O}getAllAgents(){let O=[];for(let $ of this.plugins.values())if($.status==="active")O.push(...$.agents);return O}findCommand(O){for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.commands)if(Z.namespacedName===O)return Z}let $=[];for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.commands)if(Z.originalName===O)$.push(Z)}if($.length===1)return $[0];return}findSkill(O){for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.skills)if(Z.namespacedName===O)return Z}let $=[];for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.skills)if(Z.originalName===O)$.push(Z)}if($.length===1)return $[0];return}findAgent(O){for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.agents)if(Z.namespacedName===O)return Z}let $=[];for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.agents)if(Z.originalName===O)$.push(Z)}if($.length===1)return $[0];return}hasCommandConflict(O){let $=0;for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.commands)if(Z.originalName===O){if($++,$>1)return!0}}return!1}getCommandProviders(O){let $=[];for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.commands)if(Z.originalName===O){$.push(Q.manifest.name);break}}return $}disable(O){let $=this.plugins.get(O);if($&&$.status==="active")return $.status="inactive",z.info(`Plugin "${O}" disabled`),!0;return!1}enable(O){let $=this.plugins.get(O);if($&&$.status==="inactive")return $.status="active",z.info(`Plugin "${O}" enabled`),!0;return!1}async refresh(){return z.info("Refreshing plugin list..."),this.plugins.clear(),this.initialized=!1,this.initialize(this.workspaceRoot,this.cliPluginDirs)}getStats(){let O=0,$=0,Q=0,Z=0,J=0;for(let q of this.plugins.values())if(q.status==="active")O++,Q+=q.commands.length,Z+=q.skills.length,J+=q.agents.length;else $++;return{total:this.plugins.size,active:O,inactive:$,commands:Q,skills:Z,agents:J}}formatPluginList(){if(this.getAll().length===0)return"没有已加载的插件。";let $=[],Q=this.getBySource();if(Q.cli.length>0){$.push("## CLI 指定的插件");for(let Z of Q.cli){let J=Z.status==="inactive"?" (禁用)":"";$.push(`- **${Z.manifest.name}** v${Z.manifest.version}${J}`),$.push(` ${Z.manifest.description}`)}$.push("")}if(Q.project.length>0){$.push("## 项目级插件");for(let Z of Q.project){let J=Z.status==="inactive"?" (禁用)":"";$.push(`- **${Z.manifest.name}** v${Z.manifest.version}${J}`),$.push(` ${Z.manifest.description}`)}$.push("")}if(Q.user.length>0){$.push("## 用户级插件");for(let Z of Q.user){let J=Z.status==="inactive"?" (禁用)":"";$.push(`- **${Z.manifest.name}** v${Z.manifest.version}${J}`),$.push(` ${Z.manifest.description}`)}}return $.join(`
710
- `)}}function Q0(O=M()){return D.getInstance(O)}var Z0=new Map,ZO=Object.values(b0);function O1(O,$){let Q=QO.resolve(O),Z=Z0.get(Q);if(!Z||$&&Z.registry!==$)return!1;return J0.getInstance().loadConfig(Z.base,Q),Z0.delete(Q),!0}function e0(O){let $={...O};for(let Q of ZO)$[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((J)=>({...J}))}));return $}class $1{commandRegistry;hookManager;skillRegistry;subagentRegistry;workspaceRoot;constructor(O=M()){this.workspaceRoot=QO.resolve(O),this.commandRegistry=_.getInstance(this.workspaceRoot),this.hookManager=J0.getInstance(),this.skillRegistry=g({cwd:this.workspaceRoot}),this.subagentRegistry=o(this.workspaceRoot)}clearAllPluginResources(){this.commandRegistry.clearPluginCommands(),this.skillRegistry.clearPluginSkills(),this.subagentRegistry.clearPluginAgents(),O1(this.workspaceRoot,Q0(this.workspaceRoot)),z.debug("Cleared all plugin resources from subsystems")}async integrateAll(){let O=Q0(this.workspaceRoot),$=O.getActive(),Q=[],Z=[],J=0,q=0,K=0,X=0,G=0;for(let W of $){let Y=this.integratePlugin(W);Q.push(Y),J+=Y.commandsRegistered,q+=Y.skillsRegistered,K+=Y.agentsRegistered,X+=Y.mcpServersRegistered,G+=Y.lspServersRegistered,Z.push(...Y.errors)}if(this.integrateHooks($,O),J+q+K>0)z.info(`Plugin integration complete: ${J} commands, ${q} skills, ${K} agents, ${X} MCP servers, ${G} LSP servers`);return{plugins:Q,totalCommands:J,totalSkills:q,totalAgents:K,totalMcpServers:X,errors:Z}}integratePlugin(O){let $={pluginName:O.manifest.name,commandsRegistered:0,skillsRegistered:0,agentsRegistered:0,hooksRegistered:!1,mcpServersRegistered:0,lspServersRegistered:0,errors:[]};try{$.commandsRegistered=this.integrateCommands(O)}catch(Q){$.errors.push(`Failed to integrate commands: ${Q instanceof Error?Q.message:String(Q)}`)}try{$.skillsRegistered=this.integrateSkills(O)}catch(Q){$.errors.push(`Failed to integrate skills: ${Q instanceof Error?Q.message:String(Q)}`)}try{$.agentsRegistered=this.integrateAgents(O)}catch(Q){$.errors.push(`Failed to integrate agents: ${Q instanceof Error?Q.message:String(Q)}`)}$.hooksRegistered=O.hooks!==void 0;try{$.mcpServersRegistered=this.integrateMcp(O)}catch(Q){$.errors.push(`Failed to integrate MCP servers: ${Q instanceof Error?Q.message:String(Q)}`)}return $.lspServersRegistered=Object.keys(O.lspServers??{}).length,z.debug(`Integrated plugin "${O.manifest.name}": ${$.commandsRegistered} commands, ${$.skillsRegistered} skills, ${$.agentsRegistered} agents`),$}integrateCommands(O){let $=0;for(let Q of O.commands)this.commandRegistry.registerPluginCommand(Q),$++;return $}integrateSkills(O){let $=0;for(let Q of O.skills)this.skillRegistry.registerPluginSkill(Q),$++;return $}integrateAgents(O){let $=0;for(let Q of O.agents)this.subagentRegistry.register({...Q.config,name:Q.namespacedName}),$++;return $}integrateHooks(O,$){let Q=O.filter((K)=>K.hooks);if(Q.length===0){O1(this.workspaceRoot,$);return}let Z=e0(this.hookManager.getConfig(this.workspaceRoot));if(!Z0.has(this.workspaceRoot))Z0.set(this.workspaceRoot,{base:e0(Z),registry:$});let J=Z0.get(this.workspaceRoot)?.base??Z,q=e0(J);q.enabled=!0;for(let K of ZO){let X=J.enabled?[...J[K]??[]]:[],G=[];for(let W of Q)for(let Y of W.hooks?.[K]??[])G.push({...Y,name:Y.name?`plugin:${W.manifest.name}:${Y.name}`:`plugin:${W.manifest.name}:${K}`,hooks:Y.hooks.map((V)=>({...V,source:{kind:"plugin",pluginName:W.manifest.name,pluginSource:W.source,pluginRoot:W.basePath}}))});q[K]=[...X,...G]}this.hookManager.loadConfig(q,this.workspaceRoot)}integrateMcp(O){return Object.keys(O.mcpServers??{}).length}}async function Q1(O=M()){return new $1(O).integrateAll()}function A0(O=M()){new $1(O).clearAllPluginResources()}function JO(O=M(),$){O1(O,$)}import{createHash as b$}from"node:crypto";import*as E from"node:fs/promises";import A$ from"node:os";import v from"node:path";import x$ from"gray-matter";var x0=32,KO=24576,qO=16384,GO=131072,_0=4,LO=80,XO=256,YO=/^[a-z0-9][a-z0-9._-]{0,63}$/,_$=k("Agent");function Z1(O){for(let $ of O){let Q=$.codePointAt(0)??0;if(Q<=8||Q===11||Q===12||Q>=14&&Q<=31||Q===127||Q>=8203&&Q<=8207||Q>=8234&&Q<=8238||Q>=8288&&Q<=8303||Q===65279)return!0}return!1}function T$(O,$,Q){let Z=typeof O==="string"?O.trim():"",J=$.split(/\r?\n/).map((K)=>K.trim()).find(Boolean)?.replace(/^#+\s*/,"")??"",q=Z||J||Q;if(q.length>XO)throw Error(`Description exceeds ${XO} characters`);if(Z1(q))throw Error("Description contains hidden control characters");return q}function w$(O,$){let Q=typeof O==="string"&&O.trim()?O.trim():$;if(Q.length>LO)throw Error(`Name exceeds ${LO} characters`);if(Z1(Q))throw Error("Name contains hidden control characters");return Q}function D$(O){let Q=O.replace(/\.md$/i,"").split(v.sep);if(Q.length===0||Q.length>_0||Q.some((Z)=>!YO.test(Z)))throw Error(`Style path must use 1-${_0} lowercase safe segments`);return Q.join(":")}async function C$(O){let $;try{$=await E.lstat(O)}catch(q){if(q.code==="ENOENT")return[];throw q}if($.isSymbolicLink())throw Error(`Output style root cannot be a symlink: ${O}`);if(!$.isDirectory())return[];let Q=await E.realpath(O),Z=[],J=async(q,K)=>{if(K>_0)throw Error(`Output style directory exceeds depth ${_0}`);let X=await E.readdir(q,{withFileTypes:!0});X.sort((G,W)=>G.name.localeCompare(W.name));for(let G of X){let W=v.join(q,G.name);if(G.isSymbolicLink())throw Error(`Output style path cannot be a symlink: ${W}`);if(G.isDirectory()){await J(W,K+1);continue}if(!G.isFile()||!G.name.toLowerCase().endsWith(".md"))continue;let Y=await E.realpath(W),V=v.relative(Q,Y);if(!V||V.startsWith("..")||v.isAbsolute(V))throw Error(`Output style path escapes its source root: ${W}`);if(Z.push(Y),Z.length>x0)throw Error(`Output style catalog exceeds ${x0} files`)}};return await J(Q,1),Z}async function N$(O,$,Q){let Z=await E.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Output style must be a regular file");if(Z.size>KO)throw Error(`Output style exceeds ${KO} bytes`);let J=await E.readFile(Q,"utf8"),q=x$(J),K=q.content.trim(),X=Buffer.byteLength(K);if(X===0)throw Error("Output style prompt must not be empty");if(X>qO)throw Error(`Output style prompt exceeds ${qO} bytes`);if(Z1(K))throw Error("Output style prompt contains hidden control characters");let G=v.relative($,Q),W=D$(G);return{id:`${O.idPrefix}:${W}`,name:w$(q.data.name,W),description:T$(q.data.description,K,`Custom ${W} communication style`),source:O.source,contentSha256:b$("sha256").update(K,"utf8").digest("hex"),prompt:K}}async function R$(O,$){let Q=await C$(O.directory);if(Q.length===0)return;let Z=await E.realpath(O.directory);for(let J of Q)try{let q=await N$(O,Z,J);$.set(q.id,q)}catch(q){_$.warn(`[CommunicationStyles] Ignoring ${O.source} style: ${q instanceof Error?q.message:String(q)}`)}}function v$(O,$,Q,Z){let J=[{directory:v.join(Z,".claude","output-styles"),source:"user",idPrefix:"user"},{directory:v.join(Z,".blade","output-styles"),source:"user",idPrefix:"user"}];if($)J.push({directory:v.join(O,".claude","output-styles"),source:"project",idPrefix:"project"},{directory:v.join(O,".blade","output-styles"),source:"project",idPrefix:"project"});for(let q of Q){if(q.status!=="active"||!YO.test(q.manifest.name))continue;J.push({directory:v.join(q.basePath,"output-styles"),source:"plugin",idPrefix:`plugin:${q.manifest.name}`})}return J}async function J1(O,$){let Q=new Map;for(let J of v$(v.resolve(O),$.projectTrusted,$.plugins??[],$.homeDirectory??A$.homedir()))await R$(J,Q);let Z=0;for(let J of Q.values())Z+=Buffer.byteLength(J.prompt??"");if(Q.size>x0)throw Error(`Output style catalog exceeds ${x0} styles`);if(Z>GO)throw Error(`Output style catalog exceeds ${GO} bytes`);return new WO([...Q.values()])}import{createHash as E$}from"node:crypto";import{existsSync as T0,realpathSync as y$}from"node:fs";import*as m from"node:fs/promises";import S from"node:path";import f$ from"fast-glob";import h$ from"gray-matter";import zO from"picomatch";var HO=128,FO=32768,VO=262144,k$=49152,P$=32768,d$=24,UO=16,m$=256,p$=k("Agent"),g$=["**/CLAUDE.md","**/.claude/CLAUDE.md","**/CLAUDE.local.md","**/AGENTS.md","**/AGENTS.override.md","**/BLADE.md","**/.claude/rules/**/*.md","**/.blade/rules/**/*.md"],u$=["**/.git/**","**/node_modules/**","**/.venv/**","**/dist/**","**/build/**","**/coverage/**","**/target/**"];function w0(O){return E$("sha256").update(O,"utf8").digest("hex")}function SO(O){for(let $ of O){let Q=$.codePointAt(0)??0;if(Q<=8||Q===11||Q===12||Q>=14&&Q<=31||Q===127||Q>=8203&&Q<=8207||Q>=8234&&Q<=8238||Q>=8288&&Q<=8303||Q===65279)return!0}return!1}function L1(O){return O.split(S.sep).join("/")}function K1(O){let $=S.resolve(O),Q=[];while(!0)try{return S.join(y$($),...Q.reverse())}catch(Z){if(Z.code!=="ENOENT")return S.resolve(O);let J=S.dirname($);if(J===$)return S.resolve(O);Q.push(S.basename($)),$=J}}function c$(O){let $=S.resolve(O),Q;while(!0){if(T0(S.join($,".git")))return $;if(!Q&&(T0(S.join($,".blade"))||T0(S.join($,".claude"))||T0(S.join($,"package.json"))))Q=$;let Z=S.dirname($);if(Z===$)return Q??S.resolve(O);$=Z}}function X1(O){return Boolean(O)&&O!==".."&&!O.startsWith("../")}function q1(O,$){return O===""||$===O||$.startsWith(`${O}/`)}function jO(O){return O.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function l$(O){let $=typeof O==="string"?O.split(/[,\n]/u):Array.isArray(O)?O:[],Q=[...new Set($.filter((Z)=>typeof Z==="string").map((Z)=>Z.trim().replaceAll("\\","/")).filter(Boolean))];if(Q.length===0||Q.every((Z)=>Z==="**"))return;if(Q.length>UO)throw Error(`paths exceeds ${UO} patterns`);for(let Z of Q){if(Z.length>m$||S.posix.isAbsolute(Z)||Z.split("/").includes("..")||SO(Z))throw Error(`Unsafe project rule path pattern: ${Z.slice(0,80)}`);zO(Z,{dot:!0})}return Q}function s$(O){if(O.endsWith("/CLAUDE.local.md")||O==="CLAUDE.local.md")return{source:"local",kind:"instruction",scopeDirectory:S.posix.dirname(O).replace(/^\.$/u,""),priority:90};for(let Z of[".claude/rules/",".blade/rules/"]){let J=O.indexOf(Z);if(J>=0)return{source:"project",kind:"rule",scopeDirectory:O.slice(0,J).replace(/\/$/u,""),priority:Z.startsWith(".blade")?80:70}}if(O.endsWith("/.claude/CLAUDE.md")||O===".claude/CLAUDE.md")return{source:"project",kind:"instruction",scopeDirectory:O.slice(0,-17).replace(/\/$/u,""),priority:30};let $=S.posix.basename(O),Q=$==="CLAUDE.md"?20:$==="AGENTS.md"?40:$==="AGENTS.override.md"?50:60;return{source:"project",kind:"instruction",scopeDirectory:S.posix.dirname(O).replace(/^\.$/u,""),priority:Q}}function G1(O,$){let Q=O.scopeDirectory?O.scopeDirectory.split("/").length:0,Z=$.scopeDirectory?$.scopeDirectory.split("/").length:0;return Q-Z||O.priority-$.priority||O.relativePath.localeCompare($.relativePath)}function n$(O){return{id:O.id,relativePath:O.relativePath,source:O.source,contentSha256:O.contentSha256}}function K0(O,$,Q){let Z=O.map((K)=>{let X=K.conditional?' conditional="true"':"";return`<instruction-file path="${jO(K.relativePath)}" source="${K.source}" sha256="${K.contentSha256}"${X}>
711
- ${K.content}
712
- </instruction-file>`}),J=Q==="contextual-project-instructions"&&$.length>0?` trigger-paths="${jO($.join(","))}"`:"",q=Z.length>0?`<${Q}${J}>
706
+ `}}import{exec as pO}from"node:child_process";import*as V from"node:fs/promises";import{homedir as gO}from"node:os";import*as A from"node:path";import{promisify as uO}from"node:util";var F0=uO(pO),b=k("General"),f0={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class _1{skillsDir;constructor(O){this.skillsDir=O||A.join(gO(),".blade","skills")}async isInstalled(O){let $=A.join(this.skillsDir,O,"SKILL.md");try{return await V.access($),!0}catch{return!1}}async isGitAvailable(){try{return await F0("git --version"),!0}catch{return!1}}async installOfficialSkill(O){let{url:$,branch:Q}=f0,Z=A.join(this.skillsDir,O),J=A.join(this.skillsDir,`.tmp-${O}-${Date.now()}`);try{if(!await this.isGitAvailable())return b.warn("Git not available, skipping skill installation"),!1;b.info(`Installing official skill: ${O}...`),await V.mkdir(this.skillsDir,{recursive:!0,mode:493}),await F0(`git clone --depth 1 --branch ${Q} --single-branch ${$} "${J}"`,{timeout:30000});let K=A.join(J,"skills",O);try{await V.access(K)}catch{return b.warn(`Skill ${O} not found in official repository`),await V.rm(J,{recursive:!0,force:!0}),!1}try{await V.rm(Z,{recursive:!0,force:!0})}catch{}return await V.cp(K,Z,{recursive:!0}),await V.rm(J,{recursive:!0,force:!0}),b.info(`Successfully installed: ${O}`),!0}catch(K){try{await V.rm(J,{recursive:!0,force:!0})}catch{}return b.warn(`Failed to install ${O}: ${K instanceof Error?K.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await V.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let O of f0.defaultSkills)if(!await this.isInstalled(O))await this.installOfficialSkill(O)}async installFromRepo(O,$){let Q=$||this.extractRepoName(O),Z=A.join(this.skillsDir,Q),J=A.join(this.skillsDir,`.tmp-repo-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return b.warn("Git not available, cannot install from repo"),!1;b.info(`Installing skill from repo: ${O}...`),await V.mkdir(this.skillsDir,{recursive:!0,mode:493}),await F0(`git clone --depth 1 "${O}" "${J}"`,{timeout:60000});let K=A.join(J,"SKILL.md");try{await V.access(K)}catch{return b.warn(`No SKILL.md found in repository ${O}`),await V.rm(J,{recursive:!0,force:!0}),!1}await V.rm(Z,{recursive:!0,force:!0}),await V.rename(J,Z);try{await V.rm(A.join(Z,".git"),{recursive:!0,force:!0})}catch{}return b.info(`Successfully installed skill from repo: ${Q}`),!0}catch(K){try{await V.rm(J,{recursive:!0,force:!0})}catch{}return b.warn(`Failed to install from repo ${O}: ${K instanceof Error?K.message:"Unknown error"}`),!1}}async installFromLocal(O,$,Q=!0){let Z=$||A.basename(O),J=A.join(this.skillsDir,Z);try{let K=A.resolve(O);try{await V.access(K)}catch{return b.warn(`Local path does not exist: ${K}`),!1}let q=A.join(K,"SKILL.md");try{await V.access(q)}catch{return b.warn(`No SKILL.md found in local path: ${K}`),!1}if(b.info(`Installing skill from local path: ${K}...`),await V.mkdir(this.skillsDir,{recursive:!0,mode:493}),await V.rm(J,{recursive:!0,force:!0}),Q)await V.symlink(K,J,"dir"),b.info(`Created symlink for skill: ${Z}`);else await V.cp(K,J,{recursive:!0}),b.info(`Copied skill to: ${Z}`);return!0}catch(K){return b.warn(`Failed to install from local path ${O}: ${K instanceof Error?K.message:"Unknown error"}`),!1}}extractRepoName(O){return O.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:O,branch:$}=f0,Q=A.join(this.skillsDir,`.tmp-all-${Date.now()}`),Z=[],J=[];try{if(!await this.isGitAvailable())return b.warn("Git not available, skipping skill installation"),{installed:Z,failed:J};await V.mkdir(this.skillsDir,{recursive:!0,mode:493}),b.info("Cloning official skills repository..."),await F0(`git clone --depth 1 --branch ${$} --single-branch ${O} "${Q}"`,{timeout:60000});let K=A.join(Q,"skills"),q=await V.readdir(K,{withFileTypes:!0});for(let W of q){if(!W.isDirectory())continue;let G=W.name,Y=A.join(K,G),X=A.join(this.skillsDir,G);try{await V.access(A.join(Y,"SKILL.md")),await V.rm(X,{recursive:!0,force:!0}),await V.cp(Y,X,{recursive:!0}),b.info(`Installed: ${G}`),Z.push(G)}catch(U){b.warn(`Failed to install ${G}`),J.push(G)}}await V.rm(Q,{recursive:!0,force:!0})}catch(K){try{await V.rm(Q,{recursive:!0,force:!0})}catch{}b.warn(`Failed to install skills: ${K instanceof Error?K.message:"Unknown error"}`)}return{installed:Z,failed:J}}}var h0=null;function w1(O){if(!h0)h0=new _1(O);return h0}import*as a from"node:fs/promises";import*as U0 from"node:path";import{parse as cO}from"yaml";var lO=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,sO=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,D1=1024;function nO(O){if(!O)return;if(typeof O==="string")return O.split(",").map(($)=>$.trim()).filter(Boolean);if(Array.isArray(O))return O.map(($)=>String($).trim()).filter(Boolean);return}function C1(O){if(O===void 0)return;if(typeof O==="boolean")return O;if(typeof O==="string"){let $=O.toLowerCase().trim();if($==="true"||$==="yes"||$==="1")return!0;if($==="false"||$==="no"||$==="0")return!1}return}function iO(O,$){if(!O.name)return{valid:!1,error:"Missing required field: name"};if(!sO.test(O.name))return{valid:!1,error:`Invalid name "${O.name}": must be lowercase letters, numbers, and hyphens only, 1-64 characters`};if(!O.description)return{valid:!1,error:"Missing required field: description"};if(O.description.length>D1)return{valid:!1,error:`Description too long: ${O.description.length} characters (max ${D1})`};let Q;if(O.model)Q=O.model==="inherit"?"inherit":O.model;return{valid:!0,metadata:{name:O.name,description:O.description.trim(),allowedTools:nO(O["allowed-tools"]),version:O.version,argumentHint:O["argument-hint"]?.trim(),userInvocable:C1(O["user-invocable"]),disableModelInvocation:C1(O["disable-model-invocation"]),model:Q,whenToUse:O.when_to_use?.trim()}}}function N1(O,$,Q){let Z=O.match(lO);if(!Z)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,J,K]=Z,q;try{q=cO(J)}catch(Y){return{success:!1,error:`Failed to parse YAML frontmatter: ${Y instanceof Error?Y.message:String(Y)}`}}let W=iO(q,$);if(!W.valid)return{success:!1,error:W.error};let G=U0.dirname($);return{success:!0,content:{metadata:{...W.metadata,path:$,basePath:G,source:Q},instructions:K.trim()}}}async function V0(O,$){try{let Q=await a.readFile(O,"utf-8");return N1(Q,O,$)}catch(Q){if(Q.code==="ENOENT")return{success:!1,error:`File not found: ${O}`};return{success:!1,error:`Failed to read file: ${Q instanceof Error?Q.message:String(Q)}`}}}async function E1(O){try{let $=await a.readFile(O.path,"utf-8"),Q=N1($,O.path,O.source);return Q.success?Q.content:null}catch{return null}}async function v1(O){try{return await a.access(U0.join(O,"SKILL.md")),!0}catch{return!1}}var oO={userSkillsDir:w.join(R1(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:w.join(R1(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},t=new Map;function y1(O){return w.resolve(O?.cwd??M())}class P{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(O){this.config={...oO,cwd:M(),...O}}static getInstance(O){let $=y1(O),Q=t.get($);if(!Q)Q=new P({...O,cwd:w.resolve(O?.cwd??M())}),t.set($,Q);return Q}static resetInstance(){t.clear()}static releaseInstance(O,$){let Q=y1(O),Z=t.get(Q);if(!Z||$&&Z!==$)return!1;return t.delete(Q)}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let O=[],$=[];try{await w1(this.config.userSkillsDir).ensureDefaultSkillsInstalled()}catch(K){O.push({path:"SkillInstaller",error:`Failed to install default skills: ${K instanceof Error?K.message:"Unknown error"}`})}this.loadBuiltinSkills();let Q=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");$.push(...Q.skills),O.push(...Q.errors);let Z=await this.scanDirectory(this.config.userSkillsDir,"user");if($.push(...Z.skills),O.push(...Z.errors),(await N.getInstance().getStatus(this.config.cwd)).state==="trusted"){let K=w.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:w.join(this.config.cwd,this.config.claudeProjectSkillsDir),q=await this.scanDirectory(K,"project");$.push(...q.skills),O.push(...q.errors);let W=w.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:w.join(this.config.cwd,this.config.projectSkillsDir),G=await this.scanDirectory(W,"project");$.push(...G.skills),O.push(...G.errors)}for(let K of $)this.skills.set(K.name,K);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:O}}loadBuiltinSkills(){this.skills.set(X0.name,X0),this.skills.set(H0.name,H0)}async scanDirectory(O,$){let Q=[],Z=[];try{await j0.access(O)}catch{return{skills:Q,errors:Z}}try{let J=await j0.readdir(O,{withFileTypes:!0});for(let K of J){if(!K.isDirectory())continue;let q=w.join(O,K.name),W=w.join(q,"SKILL.md");if(!await v1(q))continue;let G=await V0(W,$);if(G.success&&G.content)Q.push(G.content.metadata);else Z.push({path:W,error:G.error||"Unknown error"})}}catch(J){Z.push({path:O,error:`Failed to scan directory: ${J instanceof Error?J.message:String(J)}`})}return{skills:Q,errors:Z}}getAll(){return Array.from(this.skills.values())}get(O){return this.skills.get(O)}has(O){return this.skills.has(O)}async loadContent(O){let $=this.skills.get(O);if(!$)return null;if($.source==="builtin")return this.loadBuiltinContent(O);return E1($)}loadBuiltinContent(O){switch(O){case"skill-creator":return x1();case"update-config":return T1();default:return null}}getModelInvocableSkills(){return Array.from(this.skills.values()).filter((O)=>!O.disableModelInvocation)}getUserInvocableSkills(){return Array.from(this.skills.values()).filter((O)=>O.userInvocable===!0)}generateAvailableSkillsList(){let O=this.getModelInvocableSkills().sort((Q,Z)=>Q.name<Z.name?-1:Q.name>Z.name?1:0);if(O.length===0)return"";let $=[];for(let Q of O){let Z=Q.description.length>100?`${Q.description.substring(0,97)}...`:Q.description,J=Q.argumentHint?`${Q.name} ${Q.argumentHint}`:Q.name;$.push(`- ${J}: ${Z}`)}return $.join(`
707
+ `)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}snapshot(){let O=new P({...this.config});return O.skills=new Map(Array.from(this.skills,([$,Q])=>[$,{...Q,...Q.allowedTools?{allowedTools:[...Q.allowedTools]}:{}}])),O.pluginSkills=new Map(Array.from(this.pluginSkills,([$,Q])=>[$,{...Q,metadata:{...Q.metadata,...Q.metadata.allowedTools?{allowedTools:[...Q.metadata.allowedTools]}:{}}}])),O.initialized=this.initialized,O}registerPluginSkill(O){this.pluginSkills.set(O.namespacedName,O),this.skills.set(O.namespacedName,O.metadata)}findPluginSkill(O){let $=this.pluginSkills.get(O);if($)return $;let Q=[];for(let Z of this.pluginSkills.values())if(Z.originalName===O)Q.push(Z);if(Q.length===1)return Q[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let O of this.pluginSkills.values())this.skills.delete(O.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function g(O){return P.getInstance(O)}import p0 from"node:path";import{execSync as aO}from"node:child_process";import f1 from"node:fs";import h1 from"node:path";class k0{async execute(O,$){let Q=O.content;if($.signal?.aborted)throw Error("Command execution aborted");return Q=this.interpolateArgs(Q,$.args),Q=await this.executeBashEmbeds(Q,$),Q=await this.resolveFileReferences(Q,$.workspaceRoot),Q}interpolateArgs(O,$){O=O.replace(/\$ARGUMENTS/g,$.join(" "));for(let Q=9;Q>=1;Q--){let Z=`$${Q}`,J=$[Q-1]??"";O=O.split(Z).join(J)}return O}async executeBashEmbeds(O,$){let Q=/!`([^`]+)`/g,Z=[];for(let K of O.matchAll(Q))Z.push({match:K[0],command:K[1]});let J=O;for(let{match:K,command:q}of Z){if($.signal?.aborted){J=J.replace(K,"[Execution aborted]");continue}try{let W=aO(q,{cwd:$.workspaceRoot,encoding:"utf-8",timeout:30000,maxBuffer:1048576,stdio:["pipe","pipe","pipe"]}).trim();J=J.replace(K,W)}catch(W){let G=W instanceof Error?W.message:String(W);J=J.replace(K,`[Error executing '${q}': ${G}]`)}}return J}async resolveFileReferences(O,$){let Q=/@([\w./-]+(?:\/[\w./-]+|\.[\w]+))/g,Z=[];for(let K of O.matchAll(Q))Z.push({match:K[0],relativePath:K[1]});let J=O;for(let{match:K,relativePath:q}of Z){let W=h1.resolve($,q);try{if(f1.statSync(W).isFile()){let Y=f1.readFileSync(W,"utf-8"),U=`\`\`\`${h1.extname(q).slice(1)||"text"}
708
+ ${Y}
709
+ \`\`\``;J=J.replace(K,U)}}catch{}}return J}hasDynamicContent(O){return{hasArgs:/\$ARGUMENTS|\$\d/.test(O),hasBashEmbeds:/!`[^`]+`/.test(O),hasFileRefs:/@[\w./-]+(?:\/[\w./-]+|\.[\w]+)/.test(O)}}}import m0 from"node:fs";import P1 from"node:os";import h from"node:path";import tO from"node:fs";import k1 from"node:path";import rO from"gray-matter";class P0{parse(O,$,Q,Z){try{let J=tO.readFileSync(O,"utf-8"),{data:K,content:q}=rO(J),{name:W,namespace:G}=this.extractNameAndNamespace(O,$);if(!W)return null;return{name:W,namespace:G,config:this.normalizeConfig(K),content:q.trim(),path:O,source:Q,sourceDir:Z}}catch(J){return console.error(`Failed to parse command file: ${O}`,J),null}}normalizeConfig(O){return{description:this.asString(O.description),allowedTools:this.parseAllowedTools(O["allowed-tools"]),argumentHint:this.asString(O["argument-hint"]),model:this.asString(O.model),disableModelInvocation:O["disable-model-invocation"]===!0}}asString(O){if(typeof O==="string"&&O.trim())return O.trim();return}parseAllowedTools(O){if(!O)return;if(Array.isArray(O))return O.map(($)=>String($).trim()).filter(Boolean);if(typeof O==="string")return O.split(",").map(($)=>$.trim()).filter(Boolean);return}extractNameAndNamespace(O,$){let Z=k1.relative($,O).split(k1.sep),J=Z.pop();if(!J)return{name:""};let K=J.replace(/\.md$/i,""),q=Z.length>0?Z.join("/"):void 0;return{name:K,namespace:q}}validateConfig(O){let $=[];if(O.model&&!this.isValidModelId(O.model))$.push(`Invalid model ID: ${O.model}`);return $}isValidModelId(O){return O.length>0&&O.length<200}}class d0{parser=new P0;async discover(O){let $=[],Q=[],Z=[],J=this.getSearchDirs(O);for(let K of J){if(!m0.existsSync(K.path))continue;Q.push(K.path);try{let q=await this.scanDirectory(K.path);for(let W of q)try{let G=this.parser.parse(W,K.path,K.source,K.sourceDir);if(G)$.push(G)}catch(G){Z.push({path:W,error:G instanceof Error?G.message:String(G)})}}catch(q){Z.push({path:K.path,error:q instanceof Error?q.message:String(q)})}}return{commands:$,scannedDirs:Q,errors:Z}}getSearchDirs(O){let $=P1.homedir();return[{path:h.join($,".blade","commands"),source:"user",sourceDir:"blade"},{path:h.join($,".claude","commands"),source:"user",sourceDir:"claude"},{path:h.join(O,".blade","commands"),source:"project",sourceDir:"blade"},{path:h.join(O,".claude","commands"),source:"project",sourceDir:"claude"}]}async scanDirectory(O){let $=[],Q=async(Z)=>{let J=await m0.promises.readdir(Z,{withFileTypes:!0});for(let K of J){let q=h.join(Z,K.name);if(K.isDirectory())await Q(q);else if(K.isFile()&&K.name.endsWith(".md"))$.push(q)}};return await Q(O),$}async hasCommands(O){let $=this.getSearchDirs(O);for(let Q of $){if(!m0.existsSync(Q.path))continue;if((await this.scanDirectory(Q.path)).length>0)return!0}return!1}getCommandDirs(O){let $=P1.homedir();return{projectBlade:h.join(O,".blade","commands"),projectClaude:h.join(O,".claude","commands"),userBlade:h.join($,".blade","commands"),userClaude:h.join($,".claude","commands")}}}class T{static instances=new Map;commands=new Map;pluginCommands=new Map;loader=new d0;executor=new k0;initialized=!1;workspaceRoot="";lastDiscoveryResult=null;static getInstance(O=M()){let $=p0.resolve(O),Q=T.instances.get($);if(!Q)Q=new T,T.instances.set($,Q);return Q}static resetInstance(){T.instances.clear()}static releaseInstance(O,$){let Q=p0.resolve(O),Z=T.instances.get(Q);if(!Z||$&&Z!==$)return!1;return T.instances.delete(Q)}static getExistingInstance(O=M()){return T.instances.get(p0.resolve(O))}constructor(){}async initialize(O){this.workspaceRoot=O;let $=await this.loader.discover(O),Q=(await N.getInstance().getStatus(O)).state==="trusted",Z={...$,commands:$.commands.filter((J)=>J.source!=="project"||Q)};this.lastDiscoveryResult=Z,this.commands.clear();for(let J of Z.commands)this.commands.set(J.name,J);return this.initialized=!0,Z}async refresh(){if(!this.workspaceRoot)throw Error("Registry not initialized. Call initialize() first.");return this.initialize(this.workspaceRoot)}isInitialized(){return this.initialized}getWorkspaceRoot(){return this.workspaceRoot}getCommand(O){return this.commands.get(O)}hasCommand(O){return this.commands.has(O)}getAllCommands(){return Array.from(this.commands.values())}getCommandCount(){return this.commands.size}getModelInvocableCommands(){return this.getAllCommands().filter((O)=>O.config.description&&!O.config.disableModelInvocation)}getModelInvocablePluginCommands(){return this.getAllPluginCommands().filter((O)=>O.config.description&&!O.config.disableModelInvocation)}async executeCommand(O,$){let Q=this.getCommand(O);if(!Q)return null;return this.executor.execute(Q,$)}getCommandLabel(O){let $=O.source==="project"?"project":"user";if(O.namespace)return`(${$}:${O.namespace})`;return`(${$})`}getCommandDisplayName(O){let $=[`/${O.name}`];if(O.config.argumentHint)$.push(O.config.argumentHint);if(O.config.description)$.push("-",O.config.description);return $.push(this.getCommandLabel(O)),$.join(" ")}getCommandsBySource(){let O=[],$=[];for(let Q of this.commands.values())if(Q.source==="project")O.push(Q);else $.push(Q);return{project:O,user:$}}getLastDiscoveryResult(){return this.lastDiscoveryResult}getCommandDirs(){if(!this.workspaceRoot)return null;return this.loader.getCommandDirs(this.workspaceRoot)}generateCommandListDescription(O=15000){let $=[...this.getModelInvocableCommands().map((q)=>({name:q.name,description:q.config.description,argumentHint:q.config.argumentHint,label:this.getCommandLabel(q)})),...this.getModelInvocablePluginCommands().map((q)=>({name:q.namespacedName,description:q.config.description,argumentHint:q.config.argumentHint,label:`(plugin:${q.pluginName})`}))],Q=$.length;if(Q===0)return{text:"No custom commands available.",includedCount:0,totalCount:0};let Z=`Available custom commands:
710
+
711
+ `,J=Z.length,K=0;for(let q of $){let W=q.argumentHint?` ${q.argumentHint}`:"",G=`- /${q.name}${W}: ${q.description} ${q.label}
712
+ `;if(J+G.length>O)break;Z+=G,J+=G.length,K++}if(K<Q)Z+=`
713
+ (${K} of ${Q} commands shown due to character budget)`;return{text:Z,includedCount:K,totalCount:Q}}snapshot(){let O=new T;return O.workspaceRoot=this.workspaceRoot,O.commands=new Map(Array.from(this.commands,([$,Q])=>[$,{...Q,config:{...Q.config,...Q.config.allowedTools?{allowedTools:[...Q.config.allowedTools]}:{}}}])),O.pluginCommands=new Map(Array.from(this.pluginCommands,([$,Q])=>[$,{...Q,config:{...Q.config,...Q.config.allowedTools?{allowedTools:[...Q.config.allowedTools]}:{}}}])),O.initialized=this.initialized,O.lastDiscoveryResult=this.lastDiscoveryResult?{commands:Array.from(O.commands.values()),scannedDirs:[...this.lastDiscoveryResult.scannedDirs],errors:this.lastDiscoveryResult.errors.map(($)=>({...$}))}:null,O}registerPluginCommand(O){this.pluginCommands.set(O.namespacedName,O)}findPluginCommand(O){let $=this.pluginCommands.get(O);if($)return $;let Q=[];for(let Z of this.pluginCommands.values())if(Z.originalName===O)Q.push(Z);if(Q.length===1)return Q[0];return}hasPluginCommand(O){return this.findPluginCommand(O)!==void 0}getAllPluginCommands(){return Array.from(this.pluginCommands.values())}async executePluginCommand(O,$){let Q=this.findPluginCommand(O);if(!Q)return null;let Z={name:Q.namespacedName,config:Q.config,content:Q.content,path:Q.path,source:"project",sourceDir:"blade"};return this.executor.execute(Z,$)}clearPluginCommands(){this.pluginCommands.clear()}getPluginCommandCount(){return this.pluginCommands.size}hasPluginCommandConflict(O){let $=0;for(let Q of this.pluginCommands.values())if(Q.originalName===O){if($++,$>1)return!0}return!1}getPluginCommandProviders(O){let $=[];for(let Q of this.pluginCommands.values())if(Q.originalName===O)$.push(Q.pluginName);return $}}import e0 from"node:path";import{satisfies as g0,validRange as m1}from"semver";var eO=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function c0(O){if(O.bladeVersion!==void 0&&(!O.bladeVersion.trim()||!m1(O.bladeVersion)))throw Error(`Invalid Blade version range in plugin "${O.name}": ${O.bladeVersion}`);for(let[$,Q]of Object.entries(O.dependencies??{})){if(!eO.test($))throw Error(`Invalid dependency name in plugin "${O.name}": ${$}`);if($===O.name)throw Error(`Plugin "${O.name}" cannot depend on itself`);if(!Q.trim()||!m1(Q))throw Error(`Invalid dependency range for ${$} in plugin "${O.name}": ${Q}`)}}function p1(O,$=u0()){if(c0(O),O.bladeVersion&&!g0($,O.bladeVersion))throw Error(`Plugin "${O.name}" requires Blade ${O.bladeVersion}, current ${$}`)}function d1(O,$){O.status="error",O.compatibilityIssues=[...O.compatibilityIssues??[],$],O.error=O.compatibilityIssues.map((Q)=>Q.message).join("; ")}function g1(O,$=u0()){let Q=[],Z=new Map(O.map((K)=>[K.manifest.name,K]));for(let K of O){if(K.status!=="active")continue;if(K.manifest.bladeVersion&&!g0($,K.manifest.bladeVersion)){let q={code:"blade-version",expected:K.manifest.bladeVersion,actual:$,message:`Requires Blade ${K.manifest.bladeVersion}, current ${$}`};d1(K,q),Q.push(q)}}let J=!0;while(J){J=!1;for(let K of O){if(K.status!=="active")continue;for(let[q,W]of Object.entries(K.manifest.dependencies??{})){let G=Z.get(q),Y;if(!G)Y={code:"dependency-missing",dependency:q,expected:W,message:`Missing dependency ${q}@${W}`};else if(!g0(G.manifest.version,W))Y={code:"dependency-version",dependency:q,expected:W,actual:G.manifest.version,message:`Dependency ${q} requires ${W}, found ${G.manifest.version}`};else if(G.status!=="active")Y={code:"dependency-inactive",dependency:q,expected:W,actual:G.status,message:`Dependency ${q} is ${G.status}`};if(!Y)continue;d1(K,Y),Q.push(Y),J=!0;break}}}return Q}import{execFile as V$}from"node:child_process";import{createHash as j$,randomUUID as e1}from"node:crypto";import{constants as O0,promises as F}from"node:fs";import{homedir as n0}from"node:os";import j from"node:path";import{promisify as B$}from"node:util";import{Mutex as S$}from"async-mutex";import{satisfies as i0}from"semver";import z$ from"write-file-atomic";import*as B0 from"node:fs/promises";import*as a1 from"node:path";var c=L.String({minLength:2,maxLength:64,pattern:"^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]{1,2}$"}),l0=L.String({pattern:"^\\d+\\.\\d+\\.\\d+(-[\\w.]+)?(\\+[\\w.]+)?$"}),O$=L.Object({name:L.String({minLength:1}),email:L.Optional(L.String({format:"email"})),url:L.Optional(L.String({format:"uri"}))}),l1=L.Object({name:c,description:L.String({minLength:1,maxLength:500}),version:l0,author:L.Optional(O$),license:L.Optional(L.String()),repository:L.Optional(L.String({format:"uri"})),homepage:L.Optional(L.String({format:"uri"})),keywords:L.Optional(L.Array(L.String())),dependencies:L.Optional(L.Record(L.String(),L.String())),bladeVersion:L.Optional(L.String())}),$$=L.Union([L.Object({type:L.Literal("git"),url:L.String({minLength:1}),ref:L.Optional(L.String({minLength:1}))},{additionalProperties:!1}),L.Object({type:L.Literal("local"),path:L.String({minLength:1})},{additionalProperties:!1}),L.Object({type:L.Literal("marketplace"),marketplace:c},{additionalProperties:!1})]),Q$=L.Object({name:c,source:$$,installPath:L.String({minLength:1}),version:l0,revision:L.String({minLength:1,maxLength:128}),contentDigest:L.String({pattern:"^[a-f0-9]{64}$"}),installedAt:L.String({format:"date-time"}),updatedAt:L.String({format:"date-time"})},{additionalProperties:!1}),Z$=L.Union([L.Object({type:L.Literal("git"),url:L.String({minLength:1}),ref:L.Optional(L.String({minLength:1}))},{additionalProperties:!1}),L.Object({type:L.Literal("local"),path:L.String({minLength:1})},{additionalProperties:!1})]),J$=L.Object({name:c,source:Z$,installPath:L.String({minLength:1}),revision:L.String({minLength:1,maxLength:128}),contentDigest:L.String({pattern:"^[a-f0-9]{64}$"}),addedAt:L.String({format:"date-time"}),updatedAt:L.String({format:"date-time"})},{additionalProperties:!1}),q$=L.Object({version:L.Literal(1),installed:L.Record(L.String(),Q$),marketplaces:L.Record(L.String(),J$)},{additionalProperties:!1}),s1=L.Object({name:L.String({minLength:1}),email:L.Optional(L.String({format:"email"})),url:L.Optional(L.String({format:"uri"}))}),K$=L.Object({name:c,description:L.Optional(L.String({maxLength:500})),version:L.Optional(l0),author:L.Optional(L.Union([L.String({minLength:1}),s1])),source:L.Union([L.String({minLength:1}),L.Object({source:L.Literal("url"),url:L.String({minLength:1}),ref:L.Optional(L.String({minLength:1})),sha:L.Optional(L.String({pattern:"^[a-fA-F0-9]{40}$"}))})]),category:L.Optional(L.String()),homepage:L.Optional(L.String({format:"uri"})),tags:L.Optional(L.Array(L.String()))}),G$=L.Object({name:c,description:L.Optional(L.String({maxLength:500})),owner:L.Optional(s1),metadata:L.Optional(L.Object({description:L.Optional(L.String({maxLength:500})),version:L.Optional(L.String())})),plugins:L.Array(K$,{maxItems:5000})}),u1=L.Object({type:c1(["stdio","sse","http"]),command:L.Optional(L.String()),args:L.Optional(L.Array(L.String())),env:L.Optional(L.Record(L.String(),L.String())),cwd:L.Optional(L.String()),url:L.Optional(L.String({format:"uri"})),headers:L.Optional(L.Record(L.String(),L.String())),timeout:L.Optional(L.Integer({minimum:1000,maximum:1800000})),idleTimeout:L.Optional(L.Integer({minimum:1000,maximum:1800000})),sampling:L.Optional(L.Object({enabled:L.Boolean(),maxTokens:L.Optional(L.Integer({minimum:1,maximum:4096})),maxRequestsPerToolCall:L.Optional(L.Integer({minimum:1,maximum:8})),maxInputBytes:L.Optional(L.Integer({minimum:1,maximum:1048576}))})),oauth:L.Optional(L.Object({enabled:L.Optional(L.Boolean()),clientId:L.Optional(L.String({minLength:1,maxLength:4096})),scopes:L.Optional(L.Array(L.String({minLength:1,maxLength:128}),{maxItems:32})),callbackPort:L.Optional(L.Integer({minimum:1024,maximum:65535}))},{additionalProperties:!1})),healthCheck:L.Optional(L.Object({enabled:L.Optional(L.Boolean()),interval:L.Optional(L.Number({exclusiveMinimum:0})),timeout:L.Optional(L.Number({exclusiveMinimum:0})),failureThreshold:L.Optional(L.Number({exclusiveMinimum:0}))}))}),L$=L.Union([L.Object({mcpServers:L.Record(L.String(),u1)}),L.Record(L.String(),u1)]);function n1(O){return u(L$,O)}function i1(O){return u(q$,O)}function o1(O){return u(G$,O)}var W$=[{dir:".blade-plugin",source:"blade"},{dir:".claude-plugin",source:"claude"}];async function r(O){for(let{dir:$,source:Q}of W$){let Z=a1.join(O,$,"plugin.json");try{await B0.access(Z)}catch{continue}try{let J=await B0.readFile(Z,"utf-8"),K=JSON.parse(J),q=u(l1,K);if(!q.success){let W=q.error.issues.map((G)=>`${G.path.join(".")}: ${G.message}`).join("; ");throw Error(`Invalid plugin.json: ${W}`)}return c0(q.data),S.debug(`Parsed plugin manifest from ${Z}`),{manifest:q.data,source:Q,manifestPath:Z}}catch(J){if(J instanceof SyntaxError)throw Error(`Invalid JSON in ${Z}: ${J.message}`);throw J}}return null}import{realpathSync as Y$}from"node:fs";import s0 from"node:path";var X$=/^[a-fA-F0-9]{40}$/;class f extends Error{code;constructor(O,$){super($);this.code=O;this.name="PluginSourcePolicyError"}}function H$(O,$){let Q=(J)=>{try{return Y$.native(J)}catch{return s0.resolve(J)}},Z=s0.relative(Q(O),Q($));return Z===""||!Z.startsWith("..")&&!s0.isAbsolute(Z)}function F$(O){let $=O.match(/^[^@]+@([^:]+):/);if($?.[1])return $[1].toLowerCase();try{return new URL(O).hostname.toLowerCase()}catch{return}}function U$(O,$){if(!$.startsWith("*."))return O===$;let Q=$.slice(1);return O.endsWith(Q)&&O.length>Q.length}function t1(O,$,Q){if(O.requireGitCommitSha&&(!$.ref||!X$.test($.ref)))throw new f("PLUGIN_GIT_SHA_REQUIRED",`${Q} must pin a full 40-character Git commit SHA`);if(!O.restrictToAllowedSources)return;let Z=F$($.url);if(!Z||!O.allowedGitHosts.some((J)=>U$(Z,J)))throw new f("PLUGIN_SOURCE_BLOCKED",`${Q} Git host is not allowed by plugin source policy`)}function r1(O,$,Q){if(!O.restrictToAllowedSources)return;if(!O.allowedLocalRoots.some((Z)=>H$(Z,$)))throw new f("PLUGIN_SOURCE_BLOCKED",`${Q} local path is not allowed by plugin source policy`)}function l(O,$,Q="Marketplace"){if($.type==="git")t1(O,$,Q);else r1(O,$.path,Q)}function e(O,$,Q,Z="Plugin"){if($.type==="git"){t1(O,$,Z);return}if($.type==="local"){r1(O,$.path,Z);return}if(O.restrictToAllowedSources&&!O.allowedMarketplaces.includes($.marketplace))throw new f("PLUGIN_SOURCE_BLOCKED",`Marketplace "${$.marketplace}" is not allowed by plugin source policy`);let J=Q[$.marketplace];if(!J)throw new f("MARKETPLACE_NOT_FOUND",`Marketplace "${$.marketplace}" is not configured`);l(O,J.source,`Marketplace "${$.marketplace}"`)}var M$=B$(V$),I$=1,OO=2097152,$O=1e4,QO=104857600,b$=120000,A$=15000,x$=600000,t0=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,ZO=/^[a-fA-F0-9]{40}$/,T$=[j.join(".blade-plugin","marketplace.json"),j.join(".claude-plugin","marketplace.json"),"marketplace.json"];class H extends Error{code;constructor(O,$){super($);this.code=O;this.name="PluginPackageError"}}function _$(){return{version:I$,installed:{},marketplaces:{}}}function s(O){return O.code==="ENOENT"}function n(O){if(O instanceof H||O instanceof f)return{code:O.code,message:O.message};return{code:"PLUGIN_PACKAGE_ERROR",message:O instanceof Error?O.message:String(O)}}function o0(O){return j.isAbsolute(O)||O.startsWith("./")||O.startsWith("../")||O==="~"||O.startsWith("~/")}function $0(O,$){let Q=j.relative(O,$);return Q===""||!Q.startsWith("..")&&!j.isAbsolute(Q)}function i(O,$="plugin"){if(!t0.test(O))throw new H("INVALID_PLUGIN_NAME",`Invalid ${$} name: ${O}`);return O}function w$(O){if(O.startsWith("git@"))return;let $=O.lastIndexOf("@");if($<=0||$===O.length-1)return;let Q=O.slice(0,$),Z=O.slice($+1);if(!t0.test(Q)||!t0.test(Z))return;return{pluginName:Q,marketplace:Z}}class JO{userPluginsDir;stateRoot;statePath;mutex=new S$;constructor(O,$){this.userPluginsDir=O??j.join(n0(),".blade","plugins"),this.stateRoot=$??j.join(j.dirname(this.userPluginsDir),"plugin-state"),this.statePath=j.join(this.stateRoot,"state.json")}async install(O,$={}){return this.runMutation(async()=>{let Q=[];try{this.requireSourceTrust($.trusted);let Z=await this.readState(),J=await this.resolvePluginSource(O,Z,$),K=this.effectivePolicy($.policy);if(e(K,J.recordSource,Z.marketplaces),J.expectedName&&Z.installed[J.expectedName])throw new H("PLUGIN_ALREADY_INSTALLED",`Plugin "${J.expectedName}" is already installed`);let q=await this.preparePluginClosure({state:Z,source:J.source,recordSource:J.recordSource,expectedName:J.expectedName,policy:K,updateRoot:!1});Q=q.prepared;let W=await this.commitPreparedPlugins(Z,Q),G=W.records.get(q.root.name);if(!G)throw new H("PLUGIN_PACKAGE_ERROR","Root plugin was not committed");let Y=Q.map((X)=>X.name).filter((X)=>X!==q.root.name);return S.info(`Installed managed plugin ${q.root.name} at revision ${G.revision}`),{success:!0,pluginName:q.root.name,pluginPath:G.installPath,manifest:q.root.manifest,installation:G,installedDependencies:Y,changed:W.changed.has(q.root.name)}}catch(Z){await this.cleanupPreparedPlugins(Q);let J=n(Z);return{success:!1,code:J.code,error:J.message}}})}async update(O,$={}){return this.runMutation(async()=>{let Q=[];try{this.requireSourceTrust($.trusted),i(O);let Z=await this.readState(),J=Z.installed[O];if(!J)throw new H("PLUGIN_NOT_MANAGED",`Plugin "${O}" is not managed by Blade's package store`);let K=this.effectivePolicy($.policy);e(K,J.source,Z.marketplaces);let q=await this.preparePluginClosure({state:Z,source:J.source,recordSource:J.source,expectedName:O,policy:K,updateRoot:!0});Q=q.prepared;let W=await this.commitPreparedPlugins(Z,Q),G=W.records.get(O);if(!G)throw new H("PLUGIN_PACKAGE_ERROR","Updated root plugin was not committed");let Y=Q.map((X)=>X.name).filter((X)=>X!==O&&W.changed.has(X));return S.info(`Updated managed plugin ${O} to revision ${G.revision}`),{success:!0,pluginName:O,pluginPath:G.installPath,manifest:q.root.manifest,installation:G,updatedDependencies:Y,changed:W.changed.has(O)}}catch(Z){await this.cleanupPreparedPlugins(Q);let J=n(Z);return{success:!1,pluginName:O,code:J.code,error:J.message}}})}async uninstall(O,$=!1){return this.runMutation(async()=>{try{if(i(O),!$)throw new H("CONFIRMATION_REQUIRED",`Uninstalling "${O}" requires explicit confirmation`);let Q=await this.readState(),Z=Q.installed[O];if(!Z)throw new H("PLUGIN_NOT_MANAGED",`Plugin "${O}" is not managed by Blade's package store`);return delete Q.installed[O],await this.writeState(Q),S.info(`Uninstalled managed plugin ${O}`),{success:!0,pluginName:O,installation:Z}}catch(Q){let Z=n(Q);return{success:!1,pluginName:O,code:Z.code,error:Z.message}}})}async listInstalled(){return Object.keys((await this.readState()).installed).sort()}async listInstallationRecords(){return Object.values((await this.readState()).installed).sort((O,$)=>O.name.localeCompare($.name))}async getInstallation(O){return(await this.readState()).installed[O]}async verifyInstallation(O){let $=await F.lstat(O.installPath);if(!$.isDirectory()||$.isSymbolicLink())throw new H("PLUGIN_PACKAGE_TAMPERED",`Managed plugin "${O.name}" has an invalid package path`);let Q=await F.realpath(this.stateRoot),Z=await F.realpath(O.installPath);if(!$0(Q,Z))throw new H("PLUGIN_PACKAGE_TAMPERED",`Managed plugin "${O.name}" has an invalid package path`);if(await this.digestTree(Z)!==O.contentDigest)throw new H("PLUGIN_PACKAGE_TAMPERED",`Managed plugin "${O.name}" failed content verification`);let K=await r(Z);if(!K||K.manifest.name!==O.name||K.manifest.version!==O.version)throw new H("PLUGIN_PACKAGE_TAMPERED",`Managed plugin "${O.name}" failed manifest verification`)}async addMarketplace(O,$={}){return this.runMutation(async()=>{let Q;try{let Z=await this.normalizeMarketplaceSource(O,$);l(this.effectivePolicy($.policy),Z);let J=await this.readState();Q=await this.materializeSource(Z);let K=await this.readMarketplaceManifest(Q.stagingPath),q=i(K.name,"marketplace");if(J.marketplaces[q])throw new H("MARKETPLACE_ALREADY_EXISTS",`Marketplace "${q}" is already configured`);let{revision:W,contentDigest:G}=Q,Y=await this.publishPackage("marketplaces",q,Q);Q=void 0;let X=new Date().toISOString(),U={name:q,source:Z,installPath:Y,revision:W,contentDigest:G,addedAt:X,updatedAt:X};return J.marketplaces[q]=U,await this.writeState(J),{success:!0,marketplace:U,manifest:K,changed:!0}}catch(Z){if(Q)await F.rm(Q.stagingPath,{recursive:!0,force:!0});let J=n(Z);return{success:!1,code:J.code,error:J.message}}})}async refreshMarketplace(O,$){return this.runMutation(async()=>{let Q;try{i(O,"marketplace");let Z=await this.readState(),J=Z.marketplaces[O];if(!J)throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${O}" is not configured`);l(this.effectivePolicy($),J.source,`Marketplace "${O}"`),Q=await this.materializeSource(J.source);let K=await this.readMarketplaceManifest(Q.stagingPath);if(K.name!==O)throw new H("MARKETPLACE_IDENTITY_MISMATCH",`Marketplace "${O}" now declares "${K.name}"`);if(J.revision===Q.revision&&J.contentDigest===Q.contentDigest)return await F.rm(Q.stagingPath,{recursive:!0,force:!0}),Q=void 0,{success:!0,marketplace:J,manifest:K,changed:!1};let{revision:q,contentDigest:W}=Q,G=await this.publishPackage("marketplaces",O,Q);Q=void 0;let Y={...J,installPath:G,revision:q,contentDigest:W,updatedAt:new Date().toISOString()};return Z.marketplaces[O]=Y,await this.writeState(Z),{success:!0,marketplace:Y,manifest:K,changed:!0}}catch(Z){if(Q)await F.rm(Q.stagingPath,{recursive:!0,force:!0});let J=n(Z);return{success:!1,code:J.code,error:J.message}}})}async removeMarketplace(O,$=!1){return this.runMutation(async()=>{try{if(i(O,"marketplace"),!$)throw new H("CONFIRMATION_REQUIRED",`Removing marketplace "${O}" requires explicit confirmation`);let Q=await this.readState(),Z=Q.marketplaces[O];if(!Z)throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${O}" is not configured`);let J=Object.values(Q.installed).filter((K)=>K.source.type==="marketplace"&&K.source.marketplace===O).map((K)=>K.name).sort();if(J.length>0)throw new H("MARKETPLACE_IN_USE",`Marketplace "${O}" still owns installed plugins: ${J.join(", ")}`);return delete Q.marketplaces[O],await this.writeState(Q),{success:!0,marketplace:Z,changed:!0}}catch(Q){let Z=n(Q);return{success:!1,code:Z.code,error:Z.message}}})}async listMarketplaces(){return Object.values((await this.readState()).marketplaces).sort((O,$)=>O.name.localeCompare($.name))}async listCatalogs(){let O=await this.listMarketplaces();return Promise.all(O.map(async($)=>({marketplace:$,manifest:await this.readMarketplaceManifest($.installPath)})))}async runMutation(O){return this.mutex.runExclusive(async()=>{let $=await this.acquireStoreLock();try{return await O()}finally{await $()}})}async acquireStoreLock(){await this.ensureStoreDirectory();let O=j.join(this.stateRoot,".operation.lock"),$=e1(),Q=Date.now()+A$;while(Date.now()<Q)try{let Z=await F.open(O,O0.O_CREAT|O0.O_EXCL|O0.O_WRONLY,384);return await Z.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:$,createdAt:new Date().toISOString()})}
714
+ `,"utf8"),await Z.close(),async()=>{try{if(JSON.parse(await F.readFile(O,"utf8")).token===$)await F.unlink(O)}catch(J){if(!s(J))S.warn(`Failed to release plugin package lock: ${J}`)}}}catch(Z){if(Z.code!=="EEXIST")throw Z;await this.removeStaleStoreLock(O),await new Promise((J)=>setTimeout(J,50))}throw new H("PLUGIN_STORE_BUSY","Plugin package store is busy; retry the operation")}async removeStaleStoreLock(O){try{let $=await F.lstat(O);if(!$.isFile()||$.isSymbolicLink())throw new H("PLUGIN_STORE_INVALID","Plugin package lock must be a regular file");if(process.getuid&&$.uid!==process.getuid()||($.mode&511)!==384)throw new H("PLUGIN_STORE_INVALID","Plugin package lock ownership or permissions are invalid");if(Date.now()-$.mtimeMs<x$)return;await F.unlink(O)}catch($){if(!s($)&&$ instanceof H)throw $}}requireSourceTrust(O){if(O!==!0)throw new H("SOURCE_TRUST_REQUIRED","Plugin installation or update requires explicit source trust")}effectivePolicy(O){return O??S0.pluginSourcePolicy}async preparePluginClosure(O){let $=[],Q=new Map,Z=[],J=(q,W,G,Y)=>{if(!i0(W,G))throw new H("DEPENDENCY_VERSION_MISMATCH",`Plugin "${Y}" requires ${q}@${G}, found ${W}`)},K=async(q)=>{let W=q.expectedName?O.state.installed[q.expectedName]:void 0;if(W&&!q.root&&q.requiredRange){if(i0(W.version,q.requiredRange))return W;if(q.recordSource.type!=="marketplace"||W.source.type!=="marketplace"||W.source.marketplace!==q.recordSource.marketplace)J(W.name,W.version,q.requiredRange,q.requiredBy??"dependency");q={...q,source:W.source,recordSource:W.source}}if(W&&q.root&&!O.updateRoot)throw new H("PLUGIN_ALREADY_INSTALLED",`Plugin "${W.name}" is already installed`);if(q.expectedName){let B=Q.get(q.expectedName);if(B){if(q.requiredRange)J(B.name,B.manifest.version,q.requiredRange,q.requiredBy??"dependency");return B}if(Z.includes(q.expectedName))throw new H("DEPENDENCY_CYCLE",`Plugin dependency cycle: ${[...Z,q.expectedName].join(" -> ")}`)}let G=await this.materializePluginSource(q.source,O.state,q.expectedName,O.policy),Y=await r(G.stagingPath);if(!Y)throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("INVALID_PLUGIN","Plugin manifest was not found");let X=i(Y.manifest.name);if(q.expectedName&&q.expectedName!==X)throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("PLUGIN_IDENTITY_MISMATCH",`Requested "${q.expectedName}" but source declares "${X}"`);if(Z.includes(X))throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("DEPENDENCY_CYCLE",`Plugin dependency cycle: ${[...Z,X].join(" -> ")}`);if(q.root&&O.state.installed[X]&&!O.updateRoot)throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("PLUGIN_ALREADY_INSTALLED",`Plugin "${X}" is already installed`);try{p1(Y.manifest)}catch(B){throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("VERSION_INCOMPATIBLE",B instanceof Error?B.message:String(B))}let U={name:X,source:q.recordSource,manifest:Y.manifest,materialized:G,existing:O.state.installed[X]};Z.push(X);try{for(let[B,p]of Object.entries(Y.manifest.dependencies??{}).sort(([G0],[y])=>G0.localeCompare(y))){let G0=Q.get(B);if(G0){J(B,G0.manifest.version,p,X);continue}let y=O.state.installed[B];if(y&&i0(y.version,p))continue;if(q.recordSource.type!=="marketplace")throw new H(y?"DEPENDENCY_VERSION_MISMATCH":"DEPENDENCY_MISSING",y?`Plugin "${X}" requires ${B}@${p}, found ${y.version}`:`Plugin "${X}" requires missing dependency ${B}@${p}; direct sources cannot auto-install dependencies`);let C0=await K({source:y?.source.type==="marketplace"&&y.source.marketplace===q.recordSource.marketplace?y.source:{type:"marketplace",marketplace:q.recordSource.marketplace},recordSource:{type:"marketplace",marketplace:q.recordSource.marketplace},expectedName:B,requiredRange:p,requiredBy:X,root:!1});J(B,"manifest"in C0?C0.manifest.version:C0.version,p,X)}}catch(B){throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),B}finally{Z.pop()}return Q.set(X,U),$.push(U),U};try{let q=await K({source:O.source,recordSource:O.recordSource,expectedName:O.expectedName,root:!0});if(!("manifest"in q))throw new H("PLUGIN_PACKAGE_ERROR","Root plugin unexpectedly resolved to an existing dependency");return{root:q,prepared:$}}catch(q){throw await this.cleanupPreparedPlugins($),q}}async commitPreparedPlugins(O,$){let Q=new Map,Z=new Set,J=new Date().toISOString();for(let K of $){let q=K.existing;if(q?.revision===K.materialized.revision&&q.contentDigest===K.materialized.contentDigest){await F.rm(K.materialized.stagingPath,{recursive:!0,force:!0}),Q.set(K.name,q);continue}let W=await this.publishPackage("packages",K.name,K.materialized),G={name:K.name,source:K.source,installPath:W,version:K.manifest.version,revision:K.materialized.revision,contentDigest:K.materialized.contentDigest,installedAt:q?.installedAt??J,updatedAt:J};O.installed[K.name]=G,Q.set(K.name,G),Z.add(K.name)}if(Z.size>0)await this.writeState(O);return{records:Q,changed:Z}}async cleanupPreparedPlugins(O){await Promise.all(O.map(($)=>F.rm($.materialized.stagingPath,{recursive:!0,force:!0})))}async resolvePluginSource(O,$,Q){let Z=O.trim();if(!Z)throw new H("INVALID_SOURCE","Plugin source is required");let J=w$(Z);if(J){if(!$.marketplaces[J.marketplace])throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${J.marketplace}" is not configured`);return{source:{type:"marketplace",marketplace:J.marketplace},recordSource:{type:"marketplace",marketplace:J.marketplace},expectedName:J.pluginName}}if(!o0(Z)&&!this.looksLikeGitSource(Z)){let q=[];for(let W of await this.catalogsFromState($))if(W.manifest.plugins.some((G)=>G.name===Z))q.push({pluginName:Z,marketplace:W.marketplace.name});if(q.length===1)return{source:{type:"marketplace",marketplace:q[0].marketplace},recordSource:{type:"marketplace",marketplace:q[0].marketplace},expectedName:Z};if(q.length>1)throw new H("AMBIGUOUS_PLUGIN_SOURCE",`Plugin "${Z}" exists in multiple marketplaces; use name@marketplace`)}if(o0(Z)){let W={type:"local",path:await this.resolveLocalSource(Z,Q.workspaceRoot)};return{source:W,recordSource:W}}let K=this.normalizeGitSource(Z,Q.ref);return{source:K,recordSource:K}}async materializePluginSource(O,$,Q,Z){if(O.type!=="marketplace")return this.materializeSource(O);let J=$.marketplaces[O.marketplace];if(!J)throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${O.marketplace}" is not configured`);let K=await this.readMarketplaceManifest(J.installPath),q=Q?K.plugins.filter((W)=>W.name===Q):K.plugins;if(q.length!==1)throw new H("MARKETPLACE_PLUGIN_NOT_FOUND",Q?`Plugin "${Q}" was not found in marketplace "${O.marketplace}"`:`Marketplace "${O.marketplace}" requires an explicit plugin name`);return this.materializeMarketplaceEntry(J,q[0],Z)}async materializeMarketplaceEntry(O,$,Q){if(typeof $.source!=="string"){let q=this.normalizeGitSource($.source.url,$.source.sha??$.source.ref);return l(Q,q,`Plugin "${$.name}"`),this.materializeSource(q)}if($.source.startsWith("https://")||$.source.startsWith("ssh://")||$.source.startsWith("git@")){let q=this.normalizeGitSource($.source);return l(Q,q,`Plugin "${$.name}"`),this.materializeSource(q)}let Z=await F.realpath(O.installPath),J=j.resolve(Z,$.source);if(!$0(Z,J)||J===Z)throw new H("MARKETPLACE_PATH_ESCAPE",`Plugin "${$.name}" source escapes its marketplace`);let K=await F.realpath(J);if(!$0(Z,K))throw new H("MARKETPLACE_PATH_ESCAPE",`Plugin "${$.name}" source escapes its marketplace`);return this.materializeSource({type:"local",path:K})}async normalizeMarketplaceSource(O,$){let Q=O.trim();if(!Q)throw new H("INVALID_SOURCE","Marketplace source is required");if(o0(Q))return{type:"local",path:await this.resolveLocalSource(Q,$.workspaceRoot)};return this.normalizeGitSource(Q,$.ref)}normalizeGitSource(O,$){let Q=O;if(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(O))Q=`https://github.com/${O}.git`;else if(O.startsWith("git@")){if(!/^git@[A-Za-z0-9.-]+:[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:\.git)?$/.test(O))throw new H("INVALID_SOURCE","Invalid SSH Git source")}else{let Z;try{Z=new URL(O)}catch{throw new H("INVALID_SOURCE","Invalid Git source")}if(Z.protocol!=="https:"&&Z.protocol!=="ssh:")throw new H("UNSAFE_GIT_PROTOCOL","Git sources must use HTTPS or SSH");if(Z.password||Z.protocol==="https:"&&Z.username)throw new H("GIT_CREDENTIALS_IN_URL","Git credentials must not be embedded in plugin source URLs");if(Z.hash||Z.search)throw new H("INVALID_SOURCE","Use the ref option instead of URL query or fragment parameters");Q=Z.toString()}if($&&(!$.trim()||$.startsWith("-")||$.includes("\x00")))throw new H("INVALID_GIT_REF","Invalid Git ref");return{type:"git",url:Q,...$?{ref:$}:{}}}looksLikeGitSource(O){return O.startsWith("https://")||O.startsWith("ssh://")||O.startsWith("git@")||/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(O)}async resolveLocalSource(O,$){let Q=O==="~"?n0():O.startsWith("~/")?j.join(n0(),O.slice(2)):O,Z=j.resolve($??process.cwd(),Q),J;try{J=await F.realpath(Z)}catch{throw new H("LOCAL_SOURCE_NOT_FOUND",`Local source does not exist: ${O}`)}let K=await F.lstat(J);if(!K.isDirectory()||K.isSymbolicLink())throw new H("INVALID_LOCAL_SOURCE","Local plugin sources must be regular directories");return J}async materializeSource(O){await this.ensureStoreDirectory();let $=j.join(this.stateRoot,"staging",e1());if(await F.mkdir(j.dirname($),{recursive:!0,mode:448}),O.type==="git"){await this.cloneGitSource(O,$);let Z=await this.runGit(["rev-parse","HEAD"],$);if(O.ref&&ZO.test(O.ref)&&Z.toLowerCase()!==O.ref.toLowerCase())throw await F.rm($,{recursive:!0,force:!0}),new H("GIT_PIN_MISMATCH","Plugin checkout does not match the requested Git commit SHA");await F.rm(j.join($,".git"),{recursive:!0,force:!0});let J=await this.digestTree($);return{stagingPath:$,revision:Z,contentDigest:J}}await this.copyLocalSource(O.path,$);let Q=await this.digestTree($);return{stagingPath:$,revision:`local-${Q.slice(0,40)}`,contentDigest:Q}}async cloneGitSource(O,$){try{if(O.ref&&ZO.test(O.ref))await F.mkdir($,{recursive:!0,mode:448}),await this.runGit(["init"],$),await this.runGit(["remote","add","origin",O.url],$),await this.runGit(["fetch","--depth","1","origin",O.ref],$),await this.runGit(["checkout","--detach","FETCH_HEAD"],$);else{let Q=["clone","--depth","1","--no-tags"];if(O.ref)Q.push("--branch",O.ref);Q.push("--",O.url,$),await this.runGit(Q)}}catch(Q){throw await F.rm($,{recursive:!0,force:!0}),new H("GIT_CLONE_FAILED",`Failed to clone plugin source: ${this.sanitizeError(Q)}`)}}async runGit(O,$){let Q=await M$("git",O,{cwd:$,encoding:"utf8",timeout:b$,maxBuffer:4194304,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),Z=typeof Q==="string"?Q:Q.stdout;if(Z===void 0)throw Error("Git process returned an invalid result");return String(Z).trim()}sanitizeError(O){return(O instanceof Error?O.message:String(O)).replaceAll(this.stateRoot,"<plugin-store>").slice(0,500)}async copyLocalSource(O,$){await this.digestTree(O),await F.cp(O,$,{recursive:!0,force:!1,errorOnExist:!0,filter:(Q)=>{return!j.relative(O,Q).split(j.sep).includes(".git")}})}async digestTree(O){let $=[],Q=0,Z=async(K)=>{let q=await F.readdir(K,{withFileTypes:!0});q.sort((W,G)=>W.name.localeCompare(G.name));for(let W of q){if(W.name===".git")continue;let G=j.join(K,W.name),Y=j.relative(O,G),X=await F.lstat(G);if(X.isSymbolicLink())throw new H("PACKAGE_SYMLINK_FORBIDDEN",`Plugin packages may not contain symbolic links: ${Y}`);if(X.isDirectory()){await Z(G);continue}if(!X.isFile())throw new H("PACKAGE_ENTRY_FORBIDDEN",`Plugin packages may contain only files and directories: ${Y}`);if(Q+=X.size,$.push({relative:Y,absolute:G,executable:(X.mode&73)!==0}),$.length>$O||Q>QO)throw new H("PACKAGE_TOO_LARGE",`Plugin package exceeds ${$O} files or ${QO} bytes`)}};await Z(O);let J=j$("sha256");for(let K of $)J.update(K.relative),J.update("\x00"),J.update(K.executable?"x":"-"),J.update("\x00"),J.update(await F.readFile(K.absolute)),J.update("\x00");return J.digest("hex")}async publishPackage(O,$,Q){let Z=j.join(this.stateRoot,O,$,Q.contentDigest);await F.mkdir(j.dirname(Z),{recursive:!0,mode:448});try{let J=await F.lstat(Z);if(!J.isDirectory()||J.isSymbolicLink())throw new H("PACKAGE_STORE_CONFLICT","Plugin package destination is not a regular directory");return await F.rm(Q.stagingPath,{recursive:!0,force:!0}),Z}catch(J){if(!s(J))throw J}return await F.rename(Q.stagingPath,Z),Z}async readMarketplaceManifest(O){for(let $ of T$){let Q=j.join(O,$);try{let Z=await F.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink()||Z.size>OO)throw new H("INVALID_MARKETPLACE","Marketplace manifest must be a regular bounded file");let J=JSON.parse(await F.readFile(Q,"utf8")),K=o1(J);if(!K.success)throw new H("INVALID_MARKETPLACE",`Invalid marketplace manifest: ${K.error.issues.map((W)=>`${W.path.join(".")}: ${W.message}`).join("; ")}`);let q=new Set;for(let W of K.data.plugins){if(q.has(W.name))throw new H("INVALID_MARKETPLACE",`Marketplace contains duplicate plugin: ${W.name}`);q.add(W.name)}return K.data}catch(Z){if(s(Z))continue;if(Z instanceof SyntaxError)throw new H("INVALID_MARKETPLACE","Marketplace manifest contains invalid JSON");throw Z}}throw new H("INVALID_MARKETPLACE","Marketplace manifest was not found")}async catalogsFromState(O){let $=Object.values(O.marketplaces).sort((Q,Z)=>Q.name.localeCompare(Z.name));return Promise.all($.map(async(Q)=>({marketplace:Q,manifest:await this.readMarketplaceManifest(Q.installPath)})))}async readState(){let O;try{O=await F.open(this.statePath,O0.O_RDONLY|O0.O_NOFOLLOW)}catch($){if(s($))return _$();throw new H("PLUGIN_STATE_INVALID","Plugin package state must be a regular file")}try{let $=await O.stat();if(!$.isFile()||$.size>OO)throw new H("PLUGIN_STATE_INVALID","Plugin package state is invalid");if(process.getuid&&$.uid!==process.getuid())throw new H("PLUGIN_STATE_INVALID","Plugin package state must be owned by the current user");if(($.mode&511)!==384)throw new H("PLUGIN_STATE_INVALID","Plugin package state permissions must be 0600");let Q=JSON.parse(await O.readFile("utf8")),Z=i1(Q);if(!Z.success)throw new H("PLUGIN_STATE_INVALID","Plugin package state schema is invalid");let J=Z.data;for(let[K,q]of Object.entries(J.installed)){let W=j.join(this.stateRoot,"packages",K);if(K!==q.name||!j.isAbsolute(q.installPath)||!$0(W,q.installPath)||j.basename(q.installPath)!==q.contentDigest||q.source.type==="local"&&!j.isAbsolute(q.source.path))throw new H("PLUGIN_STATE_INVALID","Plugin package state contains an invalid installation");if(q.source.type==="git"){let G=this.normalizeGitSource(q.source.url,q.source.ref);if(G.url!==q.source.url||G.ref!==q.source.ref)throw new H("PLUGIN_STATE_INVALID","Plugin package state contains an invalid Git source")}}for(let[K,q]of Object.entries(J.marketplaces)){let W=j.join(this.stateRoot,"marketplaces",K);if(K!==q.name||!j.isAbsolute(q.installPath)||!$0(W,q.installPath)||j.basename(q.installPath)!==q.contentDigest||q.source.type==="local"&&!j.isAbsolute(q.source.path))throw new H("PLUGIN_STATE_INVALID","Plugin package state contains an invalid marketplace");if(q.source.type==="git"){let G=this.normalizeGitSource(q.source.url,q.source.ref);if(G.url!==q.source.url||G.ref!==q.source.ref)throw new H("PLUGIN_STATE_INVALID","Plugin package state contains an invalid Marketplace Git source")}}for(let K of Object.values(J.installed))if(K.source.type==="marketplace"&&!J.marketplaces[K.source.marketplace])throw new H("PLUGIN_STATE_INVALID","Plugin package state references a missing marketplace");return J}catch($){if($ instanceof SyntaxError)throw new H("PLUGIN_STATE_INVALID","Plugin package state contains invalid JSON");throw $}finally{await O.close()}}async writeState(O){await this.ensureStoreDirectory(),await z$(this.statePath,`${JSON.stringify(O,null,2)}
715
+ `,{mode:384,encoding:"utf8"}),await F.chmod(this.statePath,384)}async ensureStoreDirectory(){try{let O=await F.lstat(this.stateRoot);if(!O.isDirectory()||O.isSymbolicLink())throw new H("PLUGIN_STORE_INVALID","Plugin package store must be a regular directory");if(process.getuid&&O.uid!==process.getuid())throw new H("PLUGIN_STORE_INVALID","Plugin package store must be owned by the current user");if((O.mode&511)!==448)throw new H("PLUGIN_STORE_INVALID","Plugin package store permissions must be 0700")}catch(O){if(!s(O))throw O;await F.mkdir(this.stateRoot,{recursive:!0,mode:448}),await F.chmod(this.stateRoot,448)}}}var a0=null;function r0(O,$){if(!a0)a0=new JO(O,$);return a0}import*as _ from"node:fs/promises";import{homedir as D$}from"node:os";import*as I from"node:path";import KO from"gray-matter";function z0(O,$){return`${O}:${$}`}function qO(O,$){return`${O}__${$}`}class M0{async loadPlugin(O,$,Q={}){let Z=await r(O);if(!Z)throw Error(`Not a valid plugin directory: ${O}`);let{manifest:J,source:K}=Z,q=J.name;S.debug(`Loading plugin "${q}" from ${O}`);let W=Q.skipCommands?[]:await this.loadCommands(O,q),G=Q.skipAgents?[]:await this.loadAgents(O,q),Y=Q.skipSkills?[]:await this.loadSkills(O,q),X=Q.skipHooks?void 0:await this.loadHooks(O),U=Q.skipMcp?void 0:await this.loadMcpConfig(O,q),B=Q.skipLsp?void 0:await this.loadLspConfig(O,q);return S.debug(`Plugin "${q}" loaded: ${W.length} commands, ${G.length} agents, ${Y.length} skills`),{manifest:J,basePath:O,source:$,manifestSource:K,commands:W,agents:G,skills:Y,hooks:X,mcpServers:U,lspServers:B,status:"active",loadedAt:new Date}}async loadCommands(O,$){let Q=I.join(O,"commands"),Z=[];if(!await this.dirExists(Q))return Z;let J=await this.scanMarkdownFiles(Q);for(let K of J)try{let q=await this.parseCommandFile(K,Q,$);if(q)Z.push(q)}catch(q){S.warn(`Failed to load command from ${K}: ${q instanceof Error?q.message:String(q)}`)}return Z}async parseCommandFile(O,$,Q){let Z=await _.readFile(O,"utf-8"),{data:J,content:K}=KO(Z),W=I.relative($,O).split(I.sep),G=W.pop();if(!G)return null;let Y=G.replace(/\.md$/i,""),X=Y;if(W.length>0)X=[...W,Y].join("/");let U=z0(Q,X),B=this.normalizeCommandConfig(J);return{originalName:X,namespacedName:U,pluginName:Q,config:B,content:K.trim(),path:O}}normalizeCommandConfig(O){return{description:this.asString(O.description),allowedTools:this.parseStringArray(O["allowed-tools"]),argumentHint:this.asString(O["argument-hint"]),model:this.asString(O.model),disableModelInvocation:O["disable-model-invocation"]===!0}}async loadAgents(O,$){let Q=I.join(O,"agents"),Z=[];if(!await this.dirExists(Q))return Z;let J=await this.scanMarkdownFiles(Q);for(let K of J)try{let q=await this.parseAgentFile(K,Q,$);if(q)Z.push(q)}catch(q){S.warn(`Failed to load agent from ${K}: ${q instanceof Error?q.message:String(q)}`)}return Z}async parseAgentFile(O,$,Q){let Z=await _.readFile(O,"utf-8"),{data:J,content:K}=KO(Z),q=I.relative($,O),W=I.basename(q,".md"),G=J.name||W,Y=z0(Q,G),X={name:Y,description:this.asString(J.description)||"",tools:this.parseStringArray(J.tools),color:this.asString(J.color),model:this.asString(J.model),permissionMode:this.asString(J.permissionMode),skills:this.parseStringArray(J.skills),systemPrompt:K.trim(),source:`plugin:${Q}`};return{originalName:G,namespacedName:Y,pluginName:Q,config:X,path:O}}async loadSkills(O,$){let Q=I.join(O,"skills"),Z=[];if(!await this.dirExists(Q))return Z;let J=await _.readdir(Q,{withFileTypes:!0});for(let K of J){if(!K.isDirectory())continue;let q=I.join(Q,K.name),W=I.join(q,"SKILL.md");try{let G=await V0(W,"project");if(G.success&&G.content){let Y=G.content.metadata.name,X=z0($,Y);Z.push({originalName:Y,namespacedName:X,pluginName:$,metadata:{...G.content.metadata,name:X},path:q})}}catch(G){S.warn(`Failed to load skill from ${W}: ${G instanceof Error?G.message:String(G)}`)}}return Z}async loadHooks(O){let $=I.join(O,"hooks","hooks.json");try{let Q=await _.readFile($,"utf-8"),Z=JSON.parse(Q);return Z.hooks||Z}catch{return}}async loadMcpConfig(O,$){let Q=I.join(O,".mcp.json");try{let Z=await _.readFile(Q,"utf-8"),J=JSON.parse(Z),K=n1(J);if(!K.success){S.warn(`Invalid .mcp.json in ${O}: ${K.error}`);return}let q="mcpServers"in J?J.mcpServers:J,W={};for(let[G,Y]of Object.entries(q)){let X=qO($,G);W[X]=Y}return W}catch{return}}async loadLspConfig(O,$){let Q=I.join(O,".lsp.json");try{let Z=JSON.parse(await _.readFile(Q,"utf8")),J=Z&&typeof Z==="object"&&!Array.isArray(Z)&&"lspServers"in Z?Z.lspServers:Z,K=GO(J),q={};for(let[W,G]of Object.entries(K)){let Y=(X)=>X.replaceAll("${CLAUDE_PLUGIN_ROOT}",O).replaceAll("${BLADE_PLUGIN_ROOT}",O);q[`plugin:${$}:${W}`]={...G,command:Y(G.command),args:G.args?.map(Y),env:G.env?Object.fromEntries(Object.entries(G.env).map(([X,U])=>[X,Y(U)])):void 0}}return q}catch(Z){if(Z.code!=="ENOENT")S.warn(`Invalid .lsp.json in ${O}: ${Z instanceof Error?Z.message:String(Z)}`);return}}async scanMarkdownFiles(O){let $=[],Q=async(Z)=>{let J=await _.readdir(Z,{withFileTypes:!0});for(let K of J){let q=I.join(Z,K.name);if(K.isDirectory())await Q(q);else if(K.name.endsWith(".md"))$.push(q)}};return await Q(O),$}async dirExists(O){try{return(await _.stat(O)).isDirectory()}catch{return!1}}asString(O){if(typeof O==="string"&&O.trim())return O.trim();return}parseStringArray(O){if(!O)return;if(Array.isArray(O))return O.map(($)=>String($).trim()).filter(Boolean);if(typeof O==="string")return O.split(",").map(($)=>$.trim()).filter(Boolean);return}static getPluginDirs(O){let $=D$();return[{path:I.join($,".claude","plugins"),source:"user",type:"claude"},{path:I.join($,".blade","plugins"),source:"user",type:"blade"},{path:I.join(O,".claude","plugins"),source:"project",type:"claude"},{path:I.join(O,".blade","plugins"),source:"project",type:"blade"}]}async discoverPluginsInDir(O,$){let Q=[],Z=[];try{await _.access(O)}catch{return{plugins:Q,errors:Z}}let J=await _.readdir(O,{withFileTypes:!0});for(let K of J){if(!K.isDirectory())continue;let q=I.join(O,K.name);try{let W=await this.loadPlugin(q,$);Q.push(W)}catch(W){Z.push({path:q,error:W instanceof Error?W.message:String(W)})}}return{plugins:Q,errors:Z}}}class D{static instances=new Map;plugins=new Map;loader=new M0;initialized=!1;workspaceRoot="";cliPluginDirs=[];enabledSettings={};sourcePolicy={...S0.pluginSourcePolicy};marketplaces={};constructor(O){this.workspaceRoot=O}static getInstance(O=M()){let $=e0.resolve(O),Q=D.instances.get($);if(!Q)Q=new D($),D.instances.set($,Q);return Q}static resetInstance(){D.instances.clear()}static releaseInstance(O,$){let Q=e0.resolve(O),Z=D.instances.get(Q);if(!Z||$&&Z!==$)return!1;return D.instances.delete(Q)}static getExistingInstance(O=M()){return D.instances.get(e0.resolve(O))}static getInitializedInstances(){return Array.from(D.instances.values()).filter((O)=>O.isInitialized())}async initialize(O,$=[]){this.workspaceRoot=O,this.cliPluginDirs=$,this.enabledSettings=await I0.getInstance().loadWorkspacePluginSettings(O),await this.refreshPolicyContext();let Q=[],Z=[];for(let G of $)try{let Y=await this.loader.loadPlugin(G,"cli");this.plugins.set(Y.manifest.name,Y),Q.push(Y),S.info(`Loaded CLI plugin: ${Y.manifest.name} from ${G}`)}catch(Y){Z.push({path:G,error:Y instanceof Error?Y.message:String(Y)}),S.warn(`Failed to load CLI plugin from ${G}: ${Y}`)}let J=(await N.getInstance().getStatus(O)).state==="trusted",K=M0.getPluginDirs(O).filter((G)=>G.source!=="project"||J),q=!1,W=async()=>{if(q)return;q=!0;let G=r0(),Y=await G.listInstallationRecords();for(let X of Y)try{await G.verifyInstallation(X);let U=await this.loader.loadPlugin(X.installPath,"user");if(U.manifest.name!==X.name)throw Error(`Managed plugin identity mismatch: ${X.name}`);U.installation=Object.freeze({...X});let B=this.plugins.get(U.manifest.name);if(!B||B.source==="user")this.plugins.set(U.manifest.name,U),Q.push(U)}catch(U){Z.push({path:X.installPath,code:"IO_ERROR",error:U instanceof Error?U.message:String(U)})}};for(let{path:G,source:Y}of K){if(Y==="project")await W();let X=await this.loader.discoverPluginsInDir(G,Y);for(let U of X.plugins){let B=this.plugins.get(U.manifest.name);if(!B||B.source!=="cli")this.plugins.set(U.manifest.name,U),Q.push(U)}Z.push(...X.errors)}await W(),this.applyEnabledSettings();for(let G of this.plugins.values()){if(G.status!=="error")continue;Z.push({path:G.basePath,code:G.compatibilityIssues?.some((Y)=>Y.code==="source-policy")?"SOURCE_POLICY_BLOCKED":G.compatibilityIssues?.some((Y)=>Y.code==="blade-version")?"VERSION_INCOMPATIBLE":"DEPENDENCY_MISSING",error:G.error??"Plugin compatibility check failed"})}return this.initialized=!0,S.info(`Plugin system initialized: ${this.plugins.size} plugins loaded`+(Z.length>0?`, ${Z.length} errors`:"")),{plugins:Array.from(this.plugins.values()),errors:Z}}isInitialized(){return this.initialized}getWorkspaceRoot(){return this.workspaceRoot}getSourcePolicy(){return{...this.sourcePolicy,allowedGitHosts:[...this.sourcePolicy.allowedGitHosts],allowedMarketplaces:[...this.sourcePolicy.allowedMarketplaces],allowedLocalRoots:[...this.sourcePolicy.allowedLocalRoots]}}getAll(){return Array.from(this.plugins.values())}getActive(){return Array.from(this.plugins.values()).filter((O)=>O.status==="active")}get(O){return this.plugins.get(O)}has(O){return this.plugins.has(O)}async reapplyEnabledSettings(){this.enabledSettings=await I0.getInstance().loadWorkspacePluginSettings(this.workspaceRoot),await this.refreshPolicyContext(),this.applyEnabledSettings()}applyEnabledSettings(){for(let O of this.plugins.values()){if(O.compatibilityIssues=[],O.error=void 0,O.status=O.source==="cli"||this.enabledSettings[O.manifest.name]!==!1?"active":"inactive",O.status!=="active")continue;try{e(this.sourcePolicy,O.installation?.source??{type:"local",path:O.basePath},this.marketplaces,`Plugin "${O.manifest.name}"`)}catch($){if(!($ instanceof f))throw $;O.status="error",O.error=$.message,O.compatibilityIssues=[{code:"source-policy",message:$.message}]}}g1(Array.from(this.plugins.values()))}async refreshPolicyContext(){this.sourcePolicy=await I0.getInstance().loadWorkspacePluginSourcePolicy(this.workspaceRoot),this.marketplaces=Object.fromEntries((await r0().listMarketplaces()).map((O)=>[O.name,O]))}getBySource(){let O={cli:[],project:[],user:[]};for(let $ of this.plugins.values())O[$.source].push($);return O}getAllCommands(){let O=[];for(let $ of this.plugins.values())if($.status==="active")O.push(...$.commands);return O}getAllSkills(){let O=[];for(let $ of this.plugins.values())if($.status==="active")O.push(...$.skills);return O}getAllAgents(){let O=[];for(let $ of this.plugins.values())if($.status==="active")O.push(...$.agents);return O}findCommand(O){for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.commands)if(Z.namespacedName===O)return Z}let $=[];for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.commands)if(Z.originalName===O)$.push(Z)}if($.length===1)return $[0];return}findSkill(O){for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.skills)if(Z.namespacedName===O)return Z}let $=[];for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.skills)if(Z.originalName===O)$.push(Z)}if($.length===1)return $[0];return}findAgent(O){for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.agents)if(Z.namespacedName===O)return Z}let $=[];for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.agents)if(Z.originalName===O)$.push(Z)}if($.length===1)return $[0];return}hasCommandConflict(O){let $=0;for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.commands)if(Z.originalName===O){if($++,$>1)return!0}}return!1}getCommandProviders(O){let $=[];for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let Z of Q.commands)if(Z.originalName===O){$.push(Q.manifest.name);break}}return $}disable(O){let $=this.plugins.get(O);if($&&$.status==="active")return $.status="inactive",S.info(`Plugin "${O}" disabled`),!0;return!1}enable(O){let $=this.plugins.get(O);if($&&$.status==="inactive")return $.status="active",S.info(`Plugin "${O}" enabled`),!0;return!1}async refresh(){return S.info("Refreshing plugin list..."),this.plugins.clear(),this.initialized=!1,this.initialize(this.workspaceRoot,this.cliPluginDirs)}getStats(){let O=0,$=0,Q=0,Z=0,J=0;for(let K of this.plugins.values())if(K.status==="active")O++,Q+=K.commands.length,Z+=K.skills.length,J+=K.agents.length;else $++;return{total:this.plugins.size,active:O,inactive:$,commands:Q,skills:Z,agents:J}}formatPluginList(){if(this.getAll().length===0)return"没有已加载的插件。";let $=[],Q=this.getBySource();if(Q.cli.length>0){$.push("## CLI 指定的插件");for(let Z of Q.cli){let J=Z.status==="inactive"?" (禁用)":"";$.push(`- **${Z.manifest.name}** v${Z.manifest.version}${J}`),$.push(` ${Z.manifest.description}`)}$.push("")}if(Q.project.length>0){$.push("## 项目级插件");for(let Z of Q.project){let J=Z.status==="inactive"?" (禁用)":"";$.push(`- **${Z.manifest.name}** v${Z.manifest.version}${J}`),$.push(` ${Z.manifest.description}`)}$.push("")}if(Q.user.length>0){$.push("## 用户级插件");for(let Z of Q.user){let J=Z.status==="inactive"?" (禁用)":"";$.push(`- **${Z.manifest.name}** v${Z.manifest.version}${J}`),$.push(` ${Z.manifest.description}`)}}return $.join(`
716
+ `)}}function Q0(O=M()){return D.getInstance(O)}var Z0=new Map,WO=Object.values(b0);function $1(O,$){let Q=LO.resolve(O),Z=Z0.get(Q);if(!Z||$&&Z.registry!==$)return!1;return J0.getInstance().loadConfig(Z.base,Q),Z0.delete(Q),!0}function O1(O){let $={...O};for(let Q of WO)$[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((J)=>({...J}))}));return $}class Q1{commandRegistry;hookManager;skillRegistry;subagentRegistry;workspaceRoot;constructor(O=M()){this.workspaceRoot=LO.resolve(O),this.commandRegistry=T.getInstance(this.workspaceRoot),this.hookManager=J0.getInstance(),this.skillRegistry=g({cwd:this.workspaceRoot}),this.subagentRegistry=o(this.workspaceRoot)}clearAllPluginResources(){this.commandRegistry.clearPluginCommands(),this.skillRegistry.clearPluginSkills(),this.subagentRegistry.clearPluginAgents(),$1(this.workspaceRoot,Q0(this.workspaceRoot)),S.debug("Cleared all plugin resources from subsystems")}async integrateAll(){let O=Q0(this.workspaceRoot),$=O.getActive(),Q=[],Z=[],J=0,K=0,q=0,W=0,G=0;for(let Y of $){let X=this.integratePlugin(Y);Q.push(X),J+=X.commandsRegistered,K+=X.skillsRegistered,q+=X.agentsRegistered,W+=X.mcpServersRegistered,G+=X.lspServersRegistered,Z.push(...X.errors)}if(this.integrateHooks($,O),J+K+q>0)S.info(`Plugin integration complete: ${J} commands, ${K} skills, ${q} agents, ${W} MCP servers, ${G} LSP servers`);return{plugins:Q,totalCommands:J,totalSkills:K,totalAgents:q,totalMcpServers:W,errors:Z}}integratePlugin(O){let $={pluginName:O.manifest.name,commandsRegistered:0,skillsRegistered:0,agentsRegistered:0,hooksRegistered:!1,mcpServersRegistered:0,lspServersRegistered:0,errors:[]};try{$.commandsRegistered=this.integrateCommands(O)}catch(Q){$.errors.push(`Failed to integrate commands: ${Q instanceof Error?Q.message:String(Q)}`)}try{$.skillsRegistered=this.integrateSkills(O)}catch(Q){$.errors.push(`Failed to integrate skills: ${Q instanceof Error?Q.message:String(Q)}`)}try{$.agentsRegistered=this.integrateAgents(O)}catch(Q){$.errors.push(`Failed to integrate agents: ${Q instanceof Error?Q.message:String(Q)}`)}$.hooksRegistered=O.hooks!==void 0;try{$.mcpServersRegistered=this.integrateMcp(O)}catch(Q){$.errors.push(`Failed to integrate MCP servers: ${Q instanceof Error?Q.message:String(Q)}`)}return $.lspServersRegistered=Object.keys(O.lspServers??{}).length,S.debug(`Integrated plugin "${O.manifest.name}": ${$.commandsRegistered} commands, ${$.skillsRegistered} skills, ${$.agentsRegistered} agents`),$}integrateCommands(O){let $=0;for(let Q of O.commands)this.commandRegistry.registerPluginCommand(Q),$++;return $}integrateSkills(O){let $=0;for(let Q of O.skills)this.skillRegistry.registerPluginSkill(Q),$++;return $}integrateAgents(O){let $=0;for(let Q of O.agents)this.subagentRegistry.register({...Q.config,name:Q.namespacedName}),$++;return $}integrateHooks(O,$){let Q=O.filter((q)=>q.hooks);if(Q.length===0){$1(this.workspaceRoot,$);return}let Z=O1(this.hookManager.getConfig(this.workspaceRoot));if(!Z0.has(this.workspaceRoot))Z0.set(this.workspaceRoot,{base:O1(Z),registry:$});let J=Z0.get(this.workspaceRoot)?.base??Z,K=O1(J);K.enabled=!0;for(let q of WO){let W=J.enabled?[...J[q]??[]]:[],G=[];for(let Y of Q)for(let X of Y.hooks?.[q]??[])G.push({...X,name:X.name?`plugin:${Y.manifest.name}:${X.name}`:`plugin:${Y.manifest.name}:${q}`,hooks:X.hooks.map((U)=>({...U,source:{kind:"plugin",pluginName:Y.manifest.name,pluginSource:Y.source,pluginRoot:Y.basePath}}))});K[q]=[...W,...G]}this.hookManager.loadConfig(K,this.workspaceRoot)}integrateMcp(O){return Object.keys(O.mcpServers??{}).length}}async function Z1(O=M()){return new Q1(O).integrateAll()}function A0(O=M()){new Q1(O).clearAllPluginResources()}function YO(O=M(),$){$1(O,$)}import{createHash as C$}from"node:crypto";import*as R from"node:fs/promises";import N$ from"node:os";import v from"node:path";import E$ from"gray-matter";var x0=32,XO=24576,HO=16384,FO=131072,T0=4,UO=80,VO=256,BO=/^[a-z0-9][a-z0-9._-]{0,63}$/,v$=k("Agent");function J1(O){for(let $ of O){let Q=$.codePointAt(0)??0;if(Q<=8||Q===11||Q===12||Q>=14&&Q<=31||Q===127||Q>=8203&&Q<=8207||Q>=8234&&Q<=8238||Q>=8288&&Q<=8303||Q===65279)return!0}return!1}function R$(O,$,Q){let Z=typeof O==="string"?O.trim():"",J=$.split(/\r?\n/).map((q)=>q.trim()).find(Boolean)?.replace(/^#+\s*/,"")??"",K=Z||J||Q;if(K.length>VO)throw Error(`Description exceeds ${VO} characters`);if(J1(K))throw Error("Description contains hidden control characters");return K}function y$(O,$){let Q=typeof O==="string"&&O.trim()?O.trim():$;if(Q.length>UO)throw Error(`Name exceeds ${UO} characters`);if(J1(Q))throw Error("Name contains hidden control characters");return Q}function f$(O){let Q=O.replace(/\.md$/i,"").split(v.sep);if(Q.length===0||Q.length>T0||Q.some((Z)=>!BO.test(Z)))throw Error(`Style path must use 1-${T0} lowercase safe segments`);return Q.join(":")}async function h$(O){let $;try{$=await R.lstat(O)}catch(K){if(K.code==="ENOENT")return[];throw K}if($.isSymbolicLink())throw Error(`Output style root cannot be a symlink: ${O}`);if(!$.isDirectory())return[];let Q=await R.realpath(O),Z=[],J=async(K,q)=>{if(q>T0)throw Error(`Output style directory exceeds depth ${T0}`);let W=await R.readdir(K,{withFileTypes:!0});W.sort((G,Y)=>G.name.localeCompare(Y.name));for(let G of W){let Y=v.join(K,G.name);if(G.isSymbolicLink())throw Error(`Output style path cannot be a symlink: ${Y}`);if(G.isDirectory()){await J(Y,q+1);continue}if(!G.isFile()||!G.name.toLowerCase().endsWith(".md"))continue;let X=await R.realpath(Y),U=v.relative(Q,X);if(!U||U.startsWith("..")||v.isAbsolute(U))throw Error(`Output style path escapes its source root: ${Y}`);if(Z.push(X),Z.length>x0)throw Error(`Output style catalog exceeds ${x0} files`)}};return await J(Q,1),Z}async function k$(O,$,Q){let Z=await R.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Output style must be a regular file");if(Z.size>XO)throw Error(`Output style exceeds ${XO} bytes`);let J=await R.readFile(Q,"utf8"),K=E$(J),q=K.content.trim(),W=Buffer.byteLength(q);if(W===0)throw Error("Output style prompt must not be empty");if(W>HO)throw Error(`Output style prompt exceeds ${HO} bytes`);if(J1(q))throw Error("Output style prompt contains hidden control characters");let G=v.relative($,Q),Y=f$(G);return{id:`${O.idPrefix}:${Y}`,name:y$(K.data.name,Y),description:R$(K.data.description,q,`Custom ${Y} communication style`),source:O.source,contentSha256:C$("sha256").update(q,"utf8").digest("hex"),prompt:q}}async function P$(O,$){let Q=await h$(O.directory);if(Q.length===0)return;let Z=await R.realpath(O.directory);for(let J of Q)try{let K=await k$(O,Z,J);$.set(K.id,K)}catch(K){v$.warn(`[CommunicationStyles] Ignoring ${O.source} style: ${K instanceof Error?K.message:String(K)}`)}}function m$(O,$,Q,Z){let J=[{directory:v.join(Z,".claude","output-styles"),source:"user",idPrefix:"user"},{directory:v.join(Z,".blade","output-styles"),source:"user",idPrefix:"user"}];if($)J.push({directory:v.join(O,".claude","output-styles"),source:"project",idPrefix:"project"},{directory:v.join(O,".blade","output-styles"),source:"project",idPrefix:"project"});for(let K of Q){if(K.status!=="active"||!BO.test(K.manifest.name))continue;J.push({directory:v.join(K.basePath,"output-styles"),source:"plugin",idPrefix:`plugin:${K.manifest.name}`})}return J}async function q1(O,$){let Q=new Map;for(let J of m$(v.resolve(O),$.projectTrusted,$.plugins??[],$.homeDirectory??N$.homedir()))await P$(J,Q);let Z=0;for(let J of Q.values())Z+=Buffer.byteLength(J.prompt??"");if(Q.size>x0)throw Error(`Output style catalog exceeds ${x0} styles`);if(Z>FO)throw Error(`Output style catalog exceeds ${FO} bytes`);return new jO([...Q.values()])}import{createHash as d$}from"node:crypto";import{existsSync as _0,realpathSync as p$}from"node:fs";import*as d from"node:fs/promises";import z from"node:path";import g$ from"fast-glob";import u$ from"gray-matter";import xO from"picomatch";var SO=128,zO=32768,MO=262144,c$=49152,l$=32768,s$=24,IO=16,n$=256,i$=k("Agent"),o$=["**/CLAUDE.md","**/.claude/CLAUDE.md","**/CLAUDE.local.md","**/AGENTS.md","**/AGENTS.override.md","**/BLADE.md","**/.claude/rules/**/*.md","**/.blade/rules/**/*.md"],a$=["**/.git/**","**/node_modules/**","**/.venv/**","**/dist/**","**/build/**","**/coverage/**","**/target/**"];function w0(O){return d$("sha256").update(O,"utf8").digest("hex")}function TO(O){for(let $ of O){let Q=$.codePointAt(0)??0;if(Q<=8||Q===11||Q===12||Q>=14&&Q<=31||Q===127||Q>=8203&&Q<=8207||Q>=8234&&Q<=8238||Q>=8288&&Q<=8303||Q===65279)return!0}return!1}function W1(O){return O.split(z.sep).join("/")}function K1(O){let $=z.resolve(O),Q=[];while(!0)try{return z.join(p$($),...Q.reverse())}catch(Z){if(Z.code!=="ENOENT")return z.resolve(O);let J=z.dirname($);if(J===$)return z.resolve(O);Q.push(z.basename($)),$=J}}function t$(O){let $=z.resolve(O),Q;while(!0){if(_0(z.join($,".git")))return $;if(!Q&&(_0(z.join($,".blade"))||_0(z.join($,".claude"))||_0(z.join($,"package.json"))))Q=$;let Z=z.dirname($);if(Z===$)return Q??z.resolve(O);$=Z}}function Y1(O){return Boolean(O)&&O!==".."&&!O.startsWith("../")}function G1(O,$){return O===""||$===O||$.startsWith(`${O}/`)}function bO(O){return O.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function r$(O){let $=typeof O==="string"?O.split(/[,\n]/u):Array.isArray(O)?O:[],Q=[...new Set($.filter((Z)=>typeof Z==="string").map((Z)=>Z.trim().replaceAll("\\","/")).filter(Boolean))];if(Q.length===0||Q.every((Z)=>Z==="**"))return;if(Q.length>IO)throw Error(`paths exceeds ${IO} patterns`);for(let Z of Q){if(Z.length>n$||z.posix.isAbsolute(Z)||Z.split("/").includes("..")||TO(Z))throw Error(`Unsafe project rule path pattern: ${Z.slice(0,80)}`);xO(Z,{dot:!0})}return Q}function e$(O){if(O.endsWith("/CLAUDE.local.md")||O==="CLAUDE.local.md")return{source:"local",kind:"instruction",scopeDirectory:z.posix.dirname(O).replace(/^\.$/u,""),priority:90};for(let Z of[".claude/rules/",".blade/rules/"]){let J=O.indexOf(Z);if(J>=0)return{source:"project",kind:"rule",scopeDirectory:O.slice(0,J).replace(/\/$/u,""),priority:Z.startsWith(".blade")?80:70}}if(O.endsWith("/.claude/CLAUDE.md")||O===".claude/CLAUDE.md")return{source:"project",kind:"instruction",scopeDirectory:O.slice(0,-17).replace(/\/$/u,""),priority:30};let $=z.posix.basename(O),Q=$==="CLAUDE.md"?20:$==="AGENTS.md"?40:$==="AGENTS.override.md"?50:60;return{source:"project",kind:"instruction",scopeDirectory:z.posix.dirname(O).replace(/^\.$/u,""),priority:Q}}function L1(O,$){let Q=O.scopeDirectory?O.scopeDirectory.split("/").length:0,Z=$.scopeDirectory?$.scopeDirectory.split("/").length:0;return Q-Z||O.priority-$.priority||O.relativePath.localeCompare($.relativePath)}function O4(O){return{id:O.id,relativePath:O.relativePath,source:O.source,contentSha256:O.contentSha256}}function q0(O,$,Q){let Z=O.map((q)=>{let W=q.conditional?' conditional="true"':"";return`<instruction-file path="${bO(q.relativePath)}" source="${q.source}" sha256="${q.contentSha256}"${W}>
717
+ ${q.content}
718
+ </instruction-file>`}),J=Q==="contextual-project-instructions"&&$.length>0?` trigger-paths="${bO($.join(","))}"`:"",K=Z.length>0?`<${Q}${J}>
713
719
  ${Z.join(`
714
720
 
715
721
  `)}
716
- </${Q}>`:"";return{content:q,files:[...O],references:O.map(n$),triggerPaths:[...$],contentBytes:Buffer.byteLength(q,"utf8"),provenanceSha256:w0(O.map((K)=>`${K.id}:${K.contentSha256}`).join(`
717
- `))}}function BO(O,$){let Q=$,Z=[];for(let J=O.length-1;J>=0;J-=1){let q=O[J];if(!q)continue;let K=Buffer.byteLength(q.content,"utf8");if(K>Q)continue;Z.push(q),Q-=K}return Z.reverse()}class d{projectRoot;catalogSha256;definitions;byId;constructor(O,$=[]){this.projectRoot=O;this.projectRoot=K1(O),this.definitions=Object.freeze([...$].sort(G1).map((Q)=>Object.freeze({...Q}))),this.byId=new Map(this.definitions.map((Q)=>[Q.id,Q])),this.catalogSha256=w0(this.definitions.map((Q)=>`${Q.id}:${Q.contentSha256}`).join(`
718
- `))}static empty(O){return new d(O)}list(){return this.definitions.map((O)=>({id:O.id,relativePath:O.relativePath,source:O.source,kind:O.kind,conditional:O.conditional,contentSha256:O.contentSha256}))}snapshot(){return new d(this.projectRoot,this.definitions.map((O)=>({...O,patterns:O.patterns?[...O.patterns]:void 0})))}staticRules(O,$=k$){if(this.definitions.length===0)return K0([],[],"project-instructions");let Q=this.relativeSourcePath(O),Z=this.definitions.filter((J)=>!J.conditional&&q1(J.scopeDirectory,Q));return K0(BO(Z,$),[],"project-instructions")}contextualRules(O,$,Q,Z=P$){if(this.definitions.length===0)return K0([],[],"contextual-project-instructions");let J=this.relativeSourcePath(O),q=[...new Set($.map((G)=>L1(S.relative(this.projectRoot,K1(G)))).filter(X1))].sort(),K=new Map;for(let G of q)for(let W of this.definitions){if(Q.has(W.id))continue;if(!q1(W.scopeDirectory,G))continue;if(W.conditional){let Y=S.posix.relative(W.scopeDirectory||".",G);if(!W.patterns?.some((V)=>zO(V,{dot:!0})(Y)))continue}else if(q1(W.scopeDirectory,J))continue;K.set(W.id,W)}let X=BO([...K.values()].sort(G1),Z);return K0(X,q,"contextual-project-instructions")}hydrate(O){let $=O.map((Q)=>{let Z=this.byId.get(Q.id);if(!Z||Z.contentSha256!==Q.contentSha256||Z.relativePath!==Q.relativePath||Z.source!==Q.source)throw Error(`Project rule provenance mismatch: ${Q.relativePath}`);return Z});return K0([...new Map($.map((Q)=>[Q.id,Q])).values()].sort(G1),[],"contextual-project-instructions")}relativeSourcePath(O){let $=L1(S.relative(this.projectRoot,K1(O)));if($&&!X1($))throw Error("Project instruction source is outside the catalog root");return $}}async function i$(O,$){let Q=await m.lstat($);if(!Q.isFile()||Q.isSymbolicLink())throw Error("Project rule must be a regular file");if(Q.size>FO)throw Error(`Project rule exceeds ${FO} bytes`);let Z=await m.realpath($),J=L1(S.relative(O,Z));if(!X1(J))throw Error("Project rule escapes its repository root");let q=await m.readFile(Z,"utf8");if(SO(q))throw Error("Project rule contains hidden control characters");let K=h$(q),X=K.content.trim();if(!X)throw Error("Project rule content must not be empty");let G=l$(K.data.paths),W=s$(J),Y=w0(JSON.stringify({relativePath:J,patterns:G??[],content:X}));return{id:`${W.source}:${w0(J).slice(0,20)}`,relativePath:J,source:W.source,kind:W.kind,scopeDirectory:W.scopeDirectory,priority:W.priority,conditional:Boolean(G),...G?{patterns:G}:{},content:X,contentSha256:Y}}async function MO(O,$){let Q=c$(O);if(!$.projectTrusted)return d.empty(Q);let Z=await m.realpath(Q),J=f$.stream([...g$],{cwd:Z,absolute:!0,dot:!0,deep:d$,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:[...u$]}),q=[];for await(let W of J)if(q.push(W.toString()),q.length>HO)throw Error(`Project rule catalog exceeds ${HO} files`);q.sort();let K=new Set(q.filter((W)=>S.basename(W)==="AGENTS.override.md").map((W)=>S.dirname(W))),X=[],G=0;for(let W of q){if(S.basename(W)==="AGENTS.md"&&K.has(S.dirname(W)))continue;try{let Y=await i$(Z,W);if(G+=Buffer.byteLength(Y.content,"utf8"),G>VO)throw Error(`Project rule catalog exceeds ${VO} bytes`);X.push(Y)}catch(Y){p$.warn(`[ProjectRules] Ignoring rule: ${Y instanceof Error?Y.message:String(Y)}`)}}return new d(Z,X)}var bO=32,D0=64;class AO extends Error{capacity=D0;constructor(){super(`Workspace agent resource capacity is full (${D0})`);this.name="WorkspaceAgentResourceCapacityError"}}var x=new Map,W1=0,xO=[];async function o$(O){let $=await N.getInstance().getStatus(O.workspaceRoot);O.communicationStyles=await J1(O.workspaceRoot,{projectTrusted:$.state==="trusted",plugins:O.plugins.getActive()})}function a$(O){let $={...O};for(let Q of Object.values(b0))$[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((J)=>({...J}))}));return $}function o2(O){xO=[...new Set(O.map(($)=>Y1.resolve($)))]}function _O(O,$){JO(O,$.plugins),C.releaseInstance(O,$.subagents),P.releaseInstance({cwd:O},$.skills),_.releaseInstance(O,$.commands),D.releaseInstance(O,$.plugins)}function TO(O){_O(O.workspaceRoot,O)}function q0(){while(x.size>bO){let O=!1;for(let[$,Q]of x){if(!Q.resources||Q.users>0)continue;if(x.get($)!==Q)continue;x.delete($),TO(Q.resources),O=!0;break}if(!O)return}}function t$(O){setImmediate(()=>{O.users=Math.max(0,O.users-1),q0()}).unref?.()}async function r$(O,$){let Q=await N.getInstance().getStatus(O),Z=o(O),J=g({cwd:O}),q=_.getInstance(O),K=Q0(O);try{if(Z.getAllNames().length===0)Z.loadFromStandardLocations(Q.state==="trusted");await Promise.all([J.initialize(),q.isInitialized()?void 0:q.initialize(O),K.isInitialized()?void 0:K.initialize(O,[...$.cliPluginDirs??xO])]),A0(O),await Q1(O);let X=await J1(O,{projectTrusted:Q.state==="trusted",plugins:K.getActive()}),G=await MO(O,{projectTrusted:Q.state==="trusted"});return{workspaceRoot:O,subagents:Z,skills:J,commands:q,plugins:K,communicationStyles:X,projectRules:G}}catch(X){throw _O(O,{subagents:Z,skills:J,commands:q,plugins:K}),X}}function e$(O,$){let Q={generation:W1,users:0};return Q.promise=r$(O,$).then((Z)=>{if(Q.generation!==W1||x.get(O)!==Q)return TO(Z),Z;return Q.resources=Z,q0(),Z},(Z)=>{if(x.get(O)===Q)x.delete(O);throw Z}),x.set(O,Q),Q}async function wO(O,$){let Q=Y1.resolve(O),Z=x.get(Q);if(!Z){if(q0(),x.size>=D0)throw new AO;Z=e$(Q,$)}else x.delete(Q),x.set(Q,Z);Z.users++;let J;try{J=await Z.promise}catch(q){throw Z.users=Math.max(0,Z.users-1),q0(),q}return{entry:Z,resources:J}}async function DO(O,$){if(!$)return;A0(O.workspaceRoot),await Q1(O.workspaceRoot),await o$(O)}async function a2(O,$={}){let Q=await wO(O,$);try{return await DO(Q.resources,$.reconcilePlugins),Q.resources}finally{t$(Q.entry)}}async function t2(O,$,Q={}){let Z=await wO(O,Q);try{return await DO(Z.resources,Q.reconcilePlugins),await $(Z.resources)}finally{Z.entry.users=Math.max(0,Z.entry.users-1),q0()}}function r2(){let O=0,$=0;for(let Q of x.values()){if(Q.resources)O++;$+=Q.users}return{capacity:bO,activeCapacity:D0,entries:x.size,initialized:O,inFlight:x.size-O,activeUsers:$}}function e2(O){let $="projectRoot"in O?O.projectRoot:O.workspaceRoot;return{projectRoot:Y1.resolve($),subagents:O.subagents.snapshot(),skills:O.skills.snapshot(),commands:O.commands.snapshot(),communicationStyles:O.communicationStyles?.snapshot()??IO.snapshot(),projectRules:O.projectRules?.snapshot()??d.empty($),hooks:a$("hooks"in O&&O.hooks?O.hooks:J0.getInstance().getConfig($))}}function O5(){W1++;for(let[O,$]of x)if($.resources)A0(O);x.clear(),C.resetInstances(),P.resetInstance(),_.resetInstance(),D.resetInstance()}
719
- export{Q4 as we,Z4 as xe,V1 as ye,L4 as ze,X4 as Ae,o as Be,_4 as Ce,I1 as De,g as Ee,_ as Fe,t0 as Ge,M0 as He,D as Ie,Q0 as Je,Q1 as Ke,A0 as Le,d as Me,bO as Ne,D0 as Oe,AO as Pe,o$ as Qe,o2 as Re,a2 as Se,t2 as Te,r2 as Ue,e2 as Ve,O5 as We};
722
+ </${Q}>`:"";return{content:K,files:[...O],references:O.map(O4),triggerPaths:[...$],contentBytes:Buffer.byteLength(K,"utf8"),provenanceSha256:w0(O.map((q)=>`${q.id}:${q.contentSha256}`).join(`
723
+ `))}}function AO(O,$){let Q=$,Z=[];for(let J=O.length-1;J>=0;J-=1){let K=O[J];if(!K)continue;let q=Buffer.byteLength(K.content,"utf8");if(q>Q)continue;Z.push(K),Q-=q}return Z.reverse()}class m{projectRoot;catalogSha256;definitions;byId;constructor(O,$=[]){this.projectRoot=O;this.projectRoot=K1(O),this.definitions=Object.freeze([...$].sort(L1).map((Q)=>Object.freeze({...Q}))),this.byId=new Map(this.definitions.map((Q)=>[Q.id,Q])),this.catalogSha256=w0(this.definitions.map((Q)=>`${Q.id}:${Q.contentSha256}`).join(`
724
+ `))}static empty(O){return new m(O)}list(){return this.definitions.map((O)=>({id:O.id,relativePath:O.relativePath,source:O.source,kind:O.kind,conditional:O.conditional,contentSha256:O.contentSha256}))}snapshot(){return new m(this.projectRoot,this.definitions.map((O)=>({...O,patterns:O.patterns?[...O.patterns]:void 0})))}staticRules(O,$=c$){if(this.definitions.length===0)return q0([],[],"project-instructions");let Q=this.relativeSourcePath(O),Z=this.definitions.filter((J)=>!J.conditional&&G1(J.scopeDirectory,Q));return q0(AO(Z,$),[],"project-instructions")}contextualRules(O,$,Q,Z=l$){if(this.definitions.length===0)return q0([],[],"contextual-project-instructions");let J=this.relativeSourcePath(O),K=[...new Set($.map((G)=>W1(z.relative(this.projectRoot,K1(G)))).filter(Y1))].sort(),q=new Map;for(let G of K)for(let Y of this.definitions){if(Q.has(Y.id))continue;if(!G1(Y.scopeDirectory,G))continue;if(Y.conditional){let X=z.posix.relative(Y.scopeDirectory||".",G);if(!Y.patterns?.some((U)=>xO(U,{dot:!0})(X)))continue}else if(G1(Y.scopeDirectory,J))continue;q.set(Y.id,Y)}let W=AO([...q.values()].sort(L1),Z);return q0(W,K,"contextual-project-instructions")}hydrate(O){let $=O.map((Q)=>{let Z=this.byId.get(Q.id);if(!Z||Z.contentSha256!==Q.contentSha256||Z.relativePath!==Q.relativePath||Z.source!==Q.source)throw Error(`Project rule provenance mismatch: ${Q.relativePath}`);return Z});return q0([...new Map($.map((Q)=>[Q.id,Q])).values()].sort(L1),[],"contextual-project-instructions")}relativeSourcePath(O){let $=W1(z.relative(this.projectRoot,K1(O)));if($&&!Y1($))throw Error("Project instruction source is outside the catalog root");return $}}async function $4(O,$){let Q=await d.lstat($);if(!Q.isFile()||Q.isSymbolicLink())throw Error("Project rule must be a regular file");if(Q.size>zO)throw Error(`Project rule exceeds ${zO} bytes`);let Z=await d.realpath($),J=W1(z.relative(O,Z));if(!Y1(J))throw Error("Project rule escapes its repository root");let K=await d.readFile(Z,"utf8");if(TO(K))throw Error("Project rule contains hidden control characters");let q=u$(K),W=q.content.trim();if(!W)throw Error("Project rule content must not be empty");let G=r$(q.data.paths),Y=e$(J),X=w0(JSON.stringify({relativePath:J,patterns:G??[],content:W}));return{id:`${Y.source}:${w0(J).slice(0,20)}`,relativePath:J,source:Y.source,kind:Y.kind,scopeDirectory:Y.scopeDirectory,priority:Y.priority,conditional:Boolean(G),...G?{patterns:G}:{},content:W,contentSha256:X}}async function _O(O,$){let Q=t$(O);if(!$.projectTrusted)return m.empty(Q);let Z=await d.realpath(Q),J=g$.stream([...o$],{cwd:Z,absolute:!0,dot:!0,deep:s$,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:[...a$]}),K=[];for await(let Y of J)if(K.push(Y.toString()),K.length>SO)throw Error(`Project rule catalog exceeds ${SO} files`);K.sort();let q=new Set(K.filter((Y)=>z.basename(Y)==="AGENTS.override.md").map((Y)=>z.dirname(Y))),W=[],G=0;for(let Y of K){if(z.basename(Y)==="AGENTS.md"&&q.has(z.dirname(Y)))continue;try{let X=await $4(Z,Y);if(G+=Buffer.byteLength(X.content,"utf8"),G>MO)throw Error(`Project rule catalog exceeds ${MO} bytes`);W.push(X)}catch(X){i$.warn(`[ProjectRules] Ignoring rule: ${X instanceof Error?X.message:String(X)}`)}}return new m(Z,W)}var DO=32,D0=64;class CO extends Error{capacity=D0;constructor(){super(`Workspace agent resource capacity is full (${D0})`);this.name="WorkspaceAgentResourceCapacityError"}}var x=new Map,X1=0,NO=[];async function Q4(O){let $=await N.getInstance().getStatus(O.workspaceRoot);O.communicationStyles=await q1(O.workspaceRoot,{projectTrusted:$.state==="trusted",plugins:O.plugins.getActive()})}function Z4(O){let $={...O};for(let Q of Object.values(b0))$[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((J)=>({...J}))}));return $}function J5(O){NO=[...new Set(O.map(($)=>H1.resolve($)))]}function EO(O,$){YO(O,$.plugins),C.releaseInstance(O,$.subagents),P.releaseInstance({cwd:O},$.skills),T.releaseInstance(O,$.commands),D.releaseInstance(O,$.plugins)}function vO(O){EO(O.workspaceRoot,O)}function K0(){while(x.size>DO){let O=!1;for(let[$,Q]of x){if(!Q.resources||Q.users>0)continue;if(x.get($)!==Q)continue;x.delete($),vO(Q.resources),O=!0;break}if(!O)return}}function J4(O){setImmediate(()=>{O.users=Math.max(0,O.users-1),K0()}).unref?.()}async function q4(O,$){let Q=await N.getInstance().getStatus(O),Z=o(O),J=g({cwd:O}),K=T.getInstance(O),q=Q0(O);try{if(Z.getAllNames().length===0)Z.loadFromStandardLocations(Q.state==="trusted");await Promise.all([J.initialize(),K.isInitialized()?void 0:K.initialize(O),q.isInitialized()?void 0:q.initialize(O,[...$.cliPluginDirs??NO])]),A0(O),await Z1(O);let W=await q1(O,{projectTrusted:Q.state==="trusted",plugins:q.getActive()}),G=await _O(O,{projectTrusted:Q.state==="trusted"});return{workspaceRoot:O,subagents:Z,skills:J,commands:K,plugins:q,communicationStyles:W,projectRules:G}}catch(W){throw EO(O,{subagents:Z,skills:J,commands:K,plugins:q}),W}}function K4(O,$){let Q={generation:X1,users:0};return Q.promise=q4(O,$).then((Z)=>{if(Q.generation!==X1||x.get(O)!==Q)return vO(Z),Z;return Q.resources=Z,K0(),Z},(Z)=>{if(x.get(O)===Q)x.delete(O);throw Z}),x.set(O,Q),Q}async function RO(O,$){let Q=H1.resolve(O),Z=x.get(Q);if(!Z){if(K0(),x.size>=D0)throw new CO;Z=K4(Q,$)}else x.delete(Q),x.set(Q,Z);Z.users++;let J;try{J=await Z.promise}catch(K){throw Z.users=Math.max(0,Z.users-1),K0(),K}return{entry:Z,resources:J}}async function yO(O,$){if(!$)return;A0(O.workspaceRoot),await Z1(O.workspaceRoot),await Q4(O)}async function q5(O,$={}){let Q=await RO(O,$);try{return await yO(Q.resources,$.reconcilePlugins),Q.resources}finally{J4(Q.entry)}}async function K5(O,$,Q={}){let Z=await RO(O,Q);try{return await yO(Z.resources,Q.reconcilePlugins),await $(Z.resources)}finally{Z.entry.users=Math.max(0,Z.entry.users-1),K0()}}function G5(){let O=0,$=0;for(let Q of x.values()){if(Q.resources)O++;$+=Q.users}return{capacity:DO,activeCapacity:D0,entries:x.size,initialized:O,inFlight:x.size-O,activeUsers:$}}function L5(O){let $="projectRoot"in O?O.projectRoot:O.workspaceRoot;return{projectRoot:H1.resolve($),subagents:O.subagents.snapshot(),skills:O.skills.snapshot(),commands:O.commands.snapshot(),communicationStyles:O.communicationStyles?.snapshot()??wO.snapshot(),projectRules:O.projectRules?.snapshot()??m.empty($),hooks:Z4("hooks"in O&&O.hooks?O.hooks:J0.getInstance().getConfig($))}}function W5(){X1++;for(let[O,$]of x)if($.resources)A0(O);x.clear(),C.resetInstances(),P.resetInstance(),T.resetInstance(),D.resetInstance()}
725
+ export{Y4 as ve,X4 as we,H4 as xe,M1 as ye,B4 as ze,S4 as Ae,o as Be,y4 as Ce,w1 as De,g as Ee,T as Fe,r0 as Ge,M0 as He,D as Ie,Q0 as Je,Z1 as Ke,A0 as Le,m as Me,DO as Ne,D0 as Oe,CO as Pe,Q4 as Qe,J5 as Re,q5 as Se,K5 as Te,G5 as Ue,L5 as Ve,W5 as We};