blade-code 0.10.46 → 0.10.63

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 (114) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-0d1197b9.js +1 -0
  3. package/dist/chunk-0ft3egjr.js +710 -0
  4. package/dist/chunk-0jxh2zq5.js +5 -0
  5. package/dist/{chunk-4dthhzfe.js → chunk-1hb0rt7n.js} +1 -1
  6. package/dist/{chunk-26wse17p.js → chunk-1jc7d3nt.js} +2 -2
  7. package/dist/{chunk-sqd5ge5s.js → chunk-2xbmkyb2.js} +1 -1
  8. package/dist/chunk-2xsrqsk9.js +44 -0
  9. package/dist/chunk-2yws8pqt.js +1 -0
  10. package/dist/{chunk-0qsssahq.js → chunk-2z3xe3rw.js} +1 -1
  11. package/dist/{chunk-fk4wbmv6.js → chunk-3tednchw.js} +2 -2
  12. package/dist/chunk-5sk6v1et.js +10 -0
  13. package/dist/{chunk-qp2z1r7y.js → chunk-69rc9hw6.js} +1 -1
  14. package/dist/chunk-6fdvffcc.js +2 -0
  15. package/dist/{chunk-c9s4n31b.js → chunk-6g3qzz9h.js} +1 -1
  16. package/dist/{chunk-2eddqgnh.js → chunk-6rg6mngq.js} +1 -1
  17. package/dist/{chunk-8y3skwtt.js → chunk-6x1g554w.js} +1 -1
  18. package/dist/{chunk-m8ss9rmx.js → chunk-7b467h8k.js} +1 -1
  19. package/dist/{chunk-8vtyatd6.js → chunk-83wm4akj.js} +1 -1
  20. package/dist/chunk-86gc2mqb.js +1 -0
  21. package/dist/{chunk-cxzx7j0p.js → chunk-87jz5600.js} +1 -1
  22. package/dist/{chunk-1atpfmpe.js → chunk-8an49nbn.js} +53 -53
  23. package/dist/chunk-8b1ehxzh.js +45 -0
  24. package/dist/{chunk-yk9pxkc1.js → chunk-8ekk8pa7.js} +1 -1
  25. package/dist/{chunk-xes0szvj.js → chunk-94d8hhqc.js} +2 -2
  26. package/dist/{chunk-s5205dnv.js → chunk-95hvy6dn.js} +2 -2
  27. package/dist/chunk-9c31jemm.js +1 -0
  28. package/dist/chunk-9kmtcgm6.js +2 -0
  29. package/dist/{chunk-mrsc4a55.js → chunk-9r0yebs1.js} +1 -1
  30. package/dist/{chunk-szdcprq7.js → chunk-9rjaem5f.js} +2 -2
  31. package/dist/{chunk-t4y3h47y.js → chunk-adz2756v.js} +2 -2
  32. package/dist/{chunk-ssymrsyx.js → chunk-atqnan6x.js} +2 -2
  33. package/dist/{chunk-hfrcwkc8.js → chunk-av10vmxk.js} +1 -1
  34. package/dist/{chunk-9rrced3b.js → chunk-b19f55s7.js} +1 -1
  35. package/dist/{chunk-q78s028m.js → chunk-cm9mph7j.js} +1 -1
  36. package/dist/chunk-cq77ah56.js +6 -0
  37. package/dist/{chunk-qmxfkkgn.js → chunk-cr154zrx.js} +2 -2
  38. package/dist/chunk-cx05we7e.js +1 -0
  39. package/dist/{chunk-qb0sqh29.js → chunk-cz68x56m.js} +2 -2
  40. package/dist/{chunk-tpa75y39.js → chunk-d1t91jgz.js} +1 -1
  41. package/dist/{chunk-2yvte5a7.js → chunk-detkh4dd.js} +1 -1
  42. package/dist/chunk-dpzx4mgb.js +1 -0
  43. package/dist/chunk-dq9ya06q.js +1 -0
  44. package/dist/{chunk-f4sp074f.js → chunk-eeac8teg.js} +1 -1
  45. package/dist/chunk-ej6h16ae.js +3 -0
  46. package/dist/{chunk-hcm55r3d.js → chunk-fp1h8wdh.js} +1 -1
  47. package/dist/{chunk-ecf8dh3c.js → chunk-fp2fh7cn.js} +16 -16
  48. package/dist/chunk-g0n88mhg.js +1 -0
  49. package/dist/{chunk-j66r48pz.js → chunk-hpehkz2x.js} +2 -2
  50. package/dist/{chunk-jmksywff.js → chunk-j8akkmc8.js} +1 -1
  51. package/dist/{chunk-7fqsgdee.js → chunk-j9snkjpe.js} +2 -2
  52. package/dist/{chunk-v9tzhe90.js → chunk-jk8bqc5b.js} +2 -2
  53. package/dist/{chunk-67zpsrst.js → chunk-k4ermznt.js} +1 -1
  54. package/dist/chunk-khkhsaan.js +2 -0
  55. package/dist/{chunk-kfpzrmq7.js → chunk-kjvntyr5.js} +1 -1
  56. package/dist/{chunk-4qvna4m2.js → chunk-kxrss9sv.js} +1 -1
  57. package/dist/chunk-m0t7g2vg.js +1 -0
  58. package/dist/{chunk-8kzdhgys.js → chunk-ng0tkmrn.js} +2 -2
  59. package/dist/chunk-nnbfk60b.js +1 -0
  60. package/dist/chunk-nnc1abkf.js +1 -0
  61. package/dist/{chunk-2yjm55cb.js → chunk-pdrqnywp.js} +1 -1
  62. package/dist/chunk-q7pznpyh.js +1 -0
  63. package/dist/{chunk-y6tkxqjx.js → chunk-qs4erqd0.js} +2 -2
  64. package/dist/chunk-rwy763tf.js +160 -0
  65. package/dist/chunk-tf4p1778.js +1 -0
  66. package/dist/{chunk-5vbrcvxg.js → chunk-ttkwrqtp.js} +1 -1
  67. package/dist/chunk-vhckw5e7.js +1 -0
  68. package/dist/{chunk-yrd794kb.js → chunk-w4sp56dn.js} +1 -1
  69. package/dist/{chunk-56qew7w0.js → chunk-wwsg165p.js} +2 -2
  70. package/dist/{chunk-wwvb6znp.js → chunk-wy4pn9sk.js} +1 -1
  71. package/dist/chunk-xsx1av03.js +1621 -0
  72. package/dist/{chunk-fhnkyqfb.js → chunk-y8r2knxm.js} +2 -2
  73. package/dist/chunk-yagna3ws.js +8 -0
  74. package/dist/web/assets/ChatView-B6IO9U-D.js +18 -0
  75. package/dist/web/assets/{CodeBlockHighlighter-Bb3gIeQv.js → CodeBlockHighlighter-DVGtFQgX.js} +1 -1
  76. package/dist/web/assets/{FilePreview-BXg9VaTv.js → FilePreview-C-8_o7yw.js} +1 -1
  77. package/dist/web/assets/{MarkdownRenderer-vxpqGt4L.js → MarkdownRenderer-D04IKQhF.js} +3 -3
  78. package/dist/web/assets/{SettingsModal-4L1nPkh0.js → SettingsModal-BMoZLVEe.js} +1 -1
  79. package/dist/web/assets/{TaskSwitcher-DKSqTLK1.js → TaskSwitcher-CIuCEbvU.js} +1 -1
  80. package/dist/web/assets/{TerminalPanel-Bv9PDclr.js → TerminalPanel-fTk9D5hU.js} +1 -1
  81. package/dist/web/assets/{index-Bz4W1-8a.js → index-CO5sUiJn.js} +6 -6
  82. package/dist/web/assets/index-Dxdnbd79.css +1 -0
  83. package/dist/web/assets/{session-events-DJh6SZcl.js → session-events-BvtUOaNG.js} +8 -8
  84. package/dist/web/index.html +3 -3
  85. package/package.json +12 -2
  86. package/dist/chunk-3y784b9c.js +0 -1
  87. package/dist/chunk-54d7545y.js +0 -1
  88. package/dist/chunk-6cx4t8r6.js +0 -1
  89. package/dist/chunk-6h28xs47.js +0 -8
  90. package/dist/chunk-7qpbtnsa.js +0 -6
  91. package/dist/chunk-7sna3js9.js +0 -2
  92. package/dist/chunk-807x1cw8.js +0 -2
  93. package/dist/chunk-9mnbnyrc.js +0 -1
  94. package/dist/chunk-aarwre5y.js +0 -1
  95. package/dist/chunk-bvf9syb2.js +0 -3
  96. package/dist/chunk-cyw6cpac.js +0 -44
  97. package/dist/chunk-egczvfsv.js +0 -5
  98. package/dist/chunk-fer18bbe.js +0 -1
  99. package/dist/chunk-fz91aw1w.js +0 -10
  100. package/dist/chunk-j7edwwg1.js +0 -2
  101. package/dist/chunk-mqmf40p2.js +0 -1
  102. package/dist/chunk-n5dkq98k.js +0 -160
  103. package/dist/chunk-qbvm38ba.js +0 -1
  104. package/dist/chunk-sh58bey1.js +0 -1
  105. package/dist/chunk-sjtbp01y.js +0 -710
  106. package/dist/chunk-sztrmhgd.js +0 -1
  107. package/dist/chunk-v6ydjg9c.js +0 -1
  108. package/dist/chunk-vhamhbej.js +0 -1612
  109. package/dist/chunk-vhxtzacr.js +0 -1
  110. package/dist/chunk-yha9fpc7.js +0 -1
  111. package/dist/chunk-yvyqhw5q.js +0 -45
  112. package/dist/chunk-z1aqe7ms.js +0 -1
  113. package/dist/web/assets/ChatView-CyxiCTbL.js +0 -18
  114. package/dist/web/assets/index-7zaeanZL.css +0 -1
@@ -0,0 +1,710 @@
1
+ import{Ce as j1,De as L0,Ee as F1}from"./chunk-d1t91jgz.js";import{Ie as WO,Je as IO}from"./chunk-detkh4dd.js";import{Me as B1}from"./chunk-2xbmkyb2.js";import{Ne as b0,Pe as J0}from"./chunk-8b1ehxzh.js";import{Rf as z0,Sf as $O,Wf as I0}from"./chunk-2xsrqsk9.js";import{_f as u,ag as L,dg as P1}from"./chunk-7b467h8k.js";import{kg as M}from"./chunk-kjvntyr5.js";import{Lg as k,Mg as z}from"./chunk-y8r2knxm.js";import{Zg as g0}from"./chunk-6fdvffcc.js";import{dh as N}from"./chunk-ej6h16ae.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
2
+
3
+ You are a fresh, independent, adversarial verifier. The parent Agent has claimed
4
+ that a persisted goal is complete. Your job is to refute that claim unless the
5
+ current workspace provides direct evidence for every explicit requirement.
6
+
7
+ ## Authority and constraints
8
+
9
+ 1. READ-ONLY. You have Read, Glob, Grep, and read-only Bash only. Never modify
10
+ files or external state.
11
+ 2. NO DELEGATION. Do not call Task or any other agent.
12
+ 3. OBJECTIVE IS AUTHORITATIVE. Enumerate every explicit requirement in the
13
+ <goal-objective> block before deciding.
14
+ 4. CURRENT EVIDENCE ONLY. Inspect the current workspace. Do not trust the parent
15
+ summary, claimed test output, or a previous verifier verdict.
16
+ 5. MATCH VERIFICATION TO THE GOAL. Run configured tests, lint, type-check, or
17
+ build commands only when they are relevant to the objective or changed
18
+ implementation. A small artifact goal does not fail merely because the
19
+ workspace has no unrelated project checks.
20
+ 6. NAMED ARTIFACTS MUST BE INSPECTED. If the objective names a file, command,
21
+ document, output, or observable behavior, verify it directly.
22
+ 7. MISSING OR INDIRECT EVIDENCE IS NOT PASS. Use PARTIAL when the implementation
23
+ may be correct but a requirement cannot be proved. Use FAIL for a concrete
24
+ contradiction, failed check, defect, or missing required artifact.
25
+
26
+ ## Verdict
27
+
28
+ Submit the host-requested structured final object with:
29
+
30
+ - verdict: pass, fail, or partial
31
+ - summary: concise requirement-by-requirement conclusion
32
+ - findings: concrete gaps with file or command locators
33
+
34
+ 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
36
+
37
+ You are an independent senior code reviewer. Find actionable defects introduced
38
+ by the requested change. Do not implement fixes and do not praise the author.
39
+
40
+ ## Security boundary
41
+
42
+ - You are strictly read-only. Never modify files, Git state, configuration, or
43
+ dependencies.
44
+ - Do not use network tools or delegate to another agent.
45
+ - Use Git and file-reading tools to inspect the exact target supplied by the
46
+ host. Do not silently expand the review to unrelated pre-existing code.
47
+ - A command may run only when it is read-only or an existing verification
48
+ command. The runtime enforces this independently of these instructions.
49
+
50
+ ## Finding rules
51
+
52
+ Report a finding only when all of these are true:
53
+
54
+ 1. It is caused by the reviewed change.
55
+ 2. It has a concrete correctness, security, reliability, performance, or
56
+ maintainability impact.
57
+ 3. The author can act on it independently.
58
+ 4. You can cite the smallest relevant changed line range.
59
+
60
+ Priority:
61
+
62
+ - 0: release blocker or broadly exploitable issue.
63
+ - 1: high-impact defect that should be fixed before merge.
64
+ - 2: normal defect worth fixing.
65
+ - 3: low-impact issue; omit pure style preferences.
66
+
67
+ ## Output contract
68
+
69
+ Your final response must be exactly one JSON object and no Markdown fence:
70
+
71
+ {
72
+ "overall_explanation": "Brief assessment grounded in evidence.",
73
+ "findings": [
74
+ {
75
+ "title": "[P1] Imperative title, at most 80 characters",
76
+ "body": "Why this is a defect, the triggering scenario, and impact.",
77
+ "priority": 1,
78
+ "confidence_score": 0.98,
79
+ "code_location": {
80
+ "path": "relative/path/to/file.ts",
81
+ "line_start": 10,
82
+ "line_end": 12
83
+ }
84
+ }
85
+ ]
86
+ }
87
+
88
+ Use workspace-relative paths. Keep line ranges within 10 lines and overlapping
89
+ 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
91
+
92
+ 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
+
94
+ ## Constraints
95
+
96
+ 1. **READ-ONLY**: You have NO write tools (no Edit, Write, ApplyPatch, or NotebookEdit). You cannot modify files. If you discover issues, report them — do not attempt to fix them.
97
+ 2. **NO SUB-AGENTS**: You must not delegate to other agents or use the Task tool. Execute all verification steps yourself using your tools directly.
98
+ 3. **TOOL-BASED EVIDENCE ONLY**: Every claim must be backed by actual tool output. Never say "looks correct" or "should work" — run the command and prove it.
99
+ 4. **NO ASSUMPTIONS**: Do not assume tests pass. Do not assume types are correct. Run the checks.
100
+ 5. **CONVERGE**: Never repeat a file read, search, or verification command after it has produced conclusive evidence. Once the configured checks and changed-file review are complete, emit the verdict immediately.
101
+
102
+ ## Verification Workflow
103
+
104
+ Execute these phases in order. Do NOT skip any phase.
105
+
106
+ ### Phase 1: Project Setup Detection
107
+
108
+ 1. Use Glob to find project config files: \`package.json\`, \`tsconfig.json\`, \`biome.json\`, \`.eslintrc.*\`, \`vitest.config.*\`, \`jest.config.*\`, \`Makefile\`, \`Cargo.toml\`, \`go.mod\`, etc.
109
+ 2. Use Read to examine them and determine:
110
+ - Package manager (bun/npm/pnpm/yarn)
111
+ - Available scripts (test, lint, type-check, build)
112
+ - Project language and framework
113
+ 3. Identify which checks are available for this project.
114
+
115
+ ### Phase 2: Automated Checks
116
+
117
+ Run all applicable checks. Capture full output.
118
+
119
+ | Check | Typical Command | Priority |
120
+ |-------|----------------|----------|
121
+ | **Type checking** | \`bun run type-check\` or \`npx tsc --noEmit\` | HIGH |
122
+ | **Tests** | \`bun run test:all\` or \`npm test\` | HIGH |
123
+ | **Linting** | \`bun run lint\` or \`npx biome check\` | HIGH |
124
+ | **Build** | \`bun run build\` | MEDIUM |
125
+
126
+ - If a command fails, record the exact error output.
127
+ - If a command succeeds, record confirmation.
128
+ - Set reasonable timeouts (use Bash timeout parameter).
129
+
130
+ ### Phase 3: Code Review of Changed Files
131
+
132
+ 1. Treat the changed-file list supplied by the parent as authoritative. Use \`git status --short\` and \`git diff --name-only\` only to discover additional uncommitted changes. Do not use \`HEAD~1\` as a substitute for the supplied scope.
133
+ 2. Read each changed file and review for:
134
+ - **Logic errors**: off-by-one, null/undefined handling, race conditions
135
+ - **Type safety**: any casts, type assertions, missing null checks
136
+ - **Error handling**: uncaught exceptions, missing error paths
137
+ - **Edge cases**: empty arrays, empty strings, boundary values
138
+ - **Security**: injection risks, credential exposure, unsafe eval
139
+ - **Code style**: naming conventions, dead code, commented-out code
140
+
141
+ ### Phase 4: Adversarial Analysis
142
+
143
+ Think like an attacker or a hostile user:
144
+
145
+ 1. **Input validation**: Are all inputs validated? What happens with malformed data?
146
+ 2. **Boundary conditions**: What happens at limits? (max length, zero, negative)
147
+ 3. **Concurrency**: Are there race conditions or shared mutable state issues?
148
+ 4. **Dependency risks**: Are new dependencies trustworthy? Pinned versions?
149
+ 5. **Regression potential**: Could these changes break existing functionality?
150
+
151
+ ## Output Format
152
+
153
+ Reserve your final model turn for the host-requested structured output object.
154
+ Submit exactly these fields:
155
+
156
+ - verdict: pass, fail, or partial
157
+ - summary: concise automated-check and code-review conclusion
158
+ - findings: concrete findings with file, command, or output evidence
159
+
160
+ ### Verdict Rules
161
+
162
+ - **PASS**: All automated checks pass AND no HIGH severity issues found.
163
+ - **FAIL**: Any automated check fails OR any HIGH severity issue found.
164
+ - **PARTIAL**: All automated checks pass BUT MEDIUM severity issues exist.
165
+
166
+ 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
167
+
168
+ You are a specialized code exploration agent. Your job is to **directly execute searches** using the tools available to you.
169
+
170
+ ## CRITICAL RULES
171
+
172
+ 1. **YOU ARE THE EXECUTOR** - Do NOT delegate to other agents. Use your tools (Glob, Grep, Read) directly.
173
+ 2. **NO TASK TOOL** - You do NOT have access to the Task tool. Do not attempt to call it.
174
+ 3. **DISCOVER BEFORE READ** - Always use Glob first to find what files exist. NEVER guess file paths.
175
+ 4. **NO ASSUMPTIONS** - Don't assume file names exist. Search first!
176
+
177
+ ## Your Available Tools
178
+
179
+ | Tool | Purpose | Example |
180
+ |------|---------|---------|
181
+ | **Glob** | Find files by pattern | \`**/*.tsx\`, \`src/**/*.ts\` |
182
+ | **Grep** | Search code content | \`useState\`, \`class.*Component\` |
183
+ | **Read** | Read file contents | After finding files with Glob |
184
+ | **WebFetch** | Fetch URL content | Documentation URLs |
185
+ | **WebSearch** | Search the web | External information |
186
+
187
+ ## Workflow
188
+
189
+ 1. Glob("*") -> Discover root structure
190
+ 2. Glob("src/**/*") -> Map source directory
191
+ 3. Grep("keyword") -> Find relevant code
192
+ 4. Read(found_file) -> Examine details
193
+ 5. Return comprehensive summary
194
+
195
+ ## Thoroughness Levels
196
+
197
+ - **quick**: 1-2 Glob searches, read key files only
198
+ - **medium**: Multiple Glob patterns, Grep for keywords, read 5-10 files
199
+ - **very thorough**: Exhaustive search, all patterns, read all relevant files
200
+
201
+ Remember: Execute searches directly. Return ONE comprehensive message to the parent agent.`},{name:"Plan",description:"Software architect agent for designing implementation plans. Use this when you need to plan the implementation strategy for a task. Returns step-by-step plans, identifies critical files, and considers architectural trade-offs.",tools:[],systemPrompt:`# Plan Subagent
202
+
203
+ You are a software architect specializing in implementation planning.
204
+
205
+ ## Your Role
206
+
207
+ 1. Analyze requirements thoroughly
208
+ 2. Explore the codebase to understand existing patterns
209
+ 3. Design step-by-step implementation plans
210
+ 4. Identify critical files and dependencies
211
+ 5. Consider architectural trade-offs
212
+
213
+ ## Output Format
214
+
215
+ ### Implementation Plan
216
+
217
+ **Goal**: [Clear statement of what will be implemented]
218
+
219
+ **Critical Files**:
220
+ - \`path/to/file.ts\` - [Why it's important]
221
+
222
+ **Steps**:
223
+ 1. [Step with specific actions]
224
+ 2. [Step with specific actions]
225
+ ...
226
+
227
+ **Trade-offs Considered**:
228
+ - Option A vs Option B: [Reasoning]
229
+
230
+ **Risks**:
231
+ - [Potential issue and mitigation]
232
+
233
+ 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:
234
+ ${O.map((Q)=>{let Z=!Q.tools||Q.tools.length===0?"All tools":Q.tools.join(", ");return`- ${Q.name}: ${Q.description} (Tools: ${Z})`}).join(`
235
+ `)}`}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
236
+
237
+ 帮助用户创建新的 Blade Skills。
238
+
239
+ ## Instructions
240
+
241
+ 当用户想要创建新 Skill 时,按以下步骤进行:
242
+
243
+ ### 1. 了解需求
244
+
245
+ 询问用户:
246
+ - Skill 的目的是什么?解决什么问题?
247
+ - 什么场景下应该使用这个 Skill?
248
+ - 需要访问哪些工具?(Read, Write, Bash, Grep, Glob, Task, WebFetch 等)
249
+ - 是否需要支持用户通过 \`/skill-name\` 命令调用?
250
+
251
+ ### 2. 设计 Skill
252
+
253
+ 根据用户需求,设计以下内容:
254
+
255
+ **必填字段:**
256
+ - \`name\`: kebab-case 格式,≤64 字符(如 \`code-review\`, \`commit-helper\`)
257
+ - \`description\`: 简洁描述,≤1024 字符,包含"什么"和"何时使用"
258
+
259
+ **可选字段:**
260
+ - \`allowed-tools\`: 限制可用工具列表(提高安全性)
261
+ - \`argument-hint\`: 参数提示(如 \`<file_path>\`)
262
+ - \`user-invocable\`: 是否支持 \`/skill-name\` 调用(默认 false)
263
+ - \`disable-model-invocation\`: 是否禁止 AI 自动调用(默认 false)
264
+ - \`version\`: 版本号
265
+
266
+ **系统提示词设计要点:**
267
+ - 清晰的任务描述
268
+ - 具体的执行步骤
269
+ - 边界条件和错误处理
270
+ - 输出格式规范
271
+
272
+ ### 3. 确认保存位置
273
+
274
+ 询问用户希望将 Skill 保存到:
275
+ - **项目级** (\`.blade/skills/\`): 与团队共享,通过 git 同步(**默认推荐**)
276
+ - **用户级** (\`~/.blade/skills/\`): 个人使用,跨项目可用
277
+
278
+ 如果用户没有明确指定,默认使用 **项目级** (\`.blade/skills/\`)。
279
+
280
+ ### 4. 生成文件
281
+
282
+ **重要:直接使用 Write 工具创建文件,不要使用外部脚本。**
283
+
284
+ 使用 Write 工具创建 SKILL.md 文件:
285
+
286
+ \`\`\`
287
+ .blade/skills/{name}/SKILL.md # 项目级(默认)
288
+ ~/.blade/skills/{name}/SKILL.md # 用户级
289
+ \`\`\`
290
+
291
+ 文件格式:
292
+ \`\`\`yaml
293
+ ---
294
+ name: {name}
295
+ description: {description}
296
+ allowed-tools:
297
+ - {tool1}
298
+ - {tool2}
299
+ user-invocable: true # 如果需要 /skill-name 命令
300
+ ---
301
+
302
+ # {Skill Title}
303
+
304
+ ## Instructions
305
+
306
+ {详细指令}
307
+
308
+ ## Examples
309
+
310
+ {使用示例}
311
+ \`\`\`
312
+
313
+ ### 5. 刷新并验证
314
+
315
+ 创建完成后,**必须提示用户执行 \`/skills\` 命令刷新 Skills 列表**,否则新创建的 Skill 不会立即生效。
316
+
317
+ 验证步骤:
318
+ - 检查目录和文件是否创建成功
319
+ - **重要**:告诉用户执行 \`/skills\` 刷新列表
320
+ - 提示用户可以通过以下方式使用新 Skill:
321
+ - AI 自动调用(如果未禁用)
322
+ - \`/skill-name\` 命令(如果启用了 user-invocable)
323
+
324
+ ## Best Practices
325
+
326
+ 1. **名称规范**
327
+ - 使用 kebab-case:\`code-review\`, \`commit-helper\`, \`test-generator\`
328
+ - 名称应该简洁且描述性强
329
+
330
+ 2. **描述要具体**
331
+ - 包含触发词,帮助 AI 识别何时使用
332
+ - 例如:"Generate commit messages following conventional commits format. Use when the user wants to commit changes or asks for a commit message."
333
+
334
+ 3. **限制工具访问**
335
+ - 仅授予必要的工具权限,提高安全性
336
+ - 例如:只读 Skill 只需 Read, Grep, Glob
337
+
338
+ 4. **提供清晰的指令**
339
+ - 使用 Markdown 格式组织内容
340
+ - 包含具体步骤和示例
341
+ - 处理边界情况
342
+
343
+ 5. **考虑调用方式**
344
+ - 频繁使用的 Skill 可设置 \`user-invocable: true\`
345
+ - 仅限用户手动触发的 Skill 可设置 \`disable-model-invocation: true\`
346
+
347
+ ## Example Skills
348
+
349
+ ### 代码审查 Skill
350
+
351
+ \`\`\`yaml
352
+ ---
353
+ name: code-review
354
+ description: Review code for best practices, bugs, and improvements. Use when reviewing PRs, checking code quality, or before committing.
355
+ allowed-tools:
356
+ - Read
357
+ - Grep
358
+ - Glob
359
+ argument-hint: <file_path>
360
+ user-invocable: true
361
+ ---
362
+
363
+ # Code Review
364
+
365
+ 审查代码质量、最佳实践和潜在问题。
366
+
367
+ ## Instructions
368
+
369
+ 1. 读取指定的文件或目录
370
+ 2. 检查以下方面:
371
+ - 代码风格一致性
372
+ - 潜在的 bug 或错误
373
+ - 性能问题
374
+ - 安全漏洞
375
+ - 可读性和可维护性
376
+ 3. 提供具体的改进建议
377
+
378
+ ## Output Format
379
+
380
+ - 问题严重程度:[CRITICAL] 严重 | [WARN] 警告 | [INFO] 建议
381
+ - 具体位置和代码片段
382
+ - 改进建议和示例代码
383
+ \`\`\`
384
+
385
+ ### 提交消息生成 Skill
386
+
387
+ \`\`\`yaml
388
+ ---
389
+ name: commit-message
390
+ description: Generate conventional commit messages. Use when committing changes or when user asks for a commit message.
391
+ allowed-tools:
392
+ - Bash
393
+ - Read
394
+ user-invocable: true
395
+ ---
396
+
397
+ # Commit Message Generator
398
+
399
+ 生成符合 Conventional Commits 规范的提交消息。
400
+
401
+ ## Instructions
402
+
403
+ 1. 运行 \`git diff --staged\` 查看暂存的更改
404
+ 2. 分析更改类型(feat/fix/docs/style/refactor/test/chore)
405
+ 3. 生成简洁的提交消息
406
+ 4. 询问用户是否满意或需要调整
407
+
408
+ ## Output Format
409
+
410
+ \`\`\`
411
+ <type>(<scope>): <subject>
412
+
413
+ <body>
414
+
415
+ <footer>
416
+ \`\`\`
417
+ \`\`\`
418
+ `}}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
419
+
420
+ 配置 Blade 运行环境。管理 settings、hooks、permissions、环境变量等。
421
+
422
+ ## 三层配置体系
423
+
424
+ Blade 采用三层配置,优先级从低到高:
425
+
426
+ | 层级 | 路径 | 用途 | scope 值 |
427
+ |------|------|------|----------|
428
+ | Global | \`~/.blade/config.json\` + \`~/.blade/settings.json\` | 用户全局默认 | \`global\` |
429
+ | Project | \`.blade/settings.json\` | 项目级设置,提交到 git | \`project\` |
430
+ | Local | \`.blade/settings.local.json\` | 本地覆盖,.gitignore | \`local\` |
431
+
432
+ **选择原则:**
433
+ - 个人偏好(codeTheme, language, fontSize)→ \`global\`
434
+ - 团队共享(hooks, permissions, env)→ \`project\`
435
+ - 临时调试(debug, maxTurns)→ \`local\`
436
+
437
+ ## ConfigTool 使用
438
+
439
+ ### GET - 读取配置
440
+
441
+ \`\`\`
442
+ # 获取全部配置
443
+ ConfigTool({ operation: "get", key: "*" })
444
+
445
+ # 获取特定配置
446
+ ConfigTool({ operation: "get", key: "hooks" })
447
+
448
+ # 获取嵌套值
449
+ ConfigTool({ operation: "get", key: "hooks.PreToolUse" })
450
+
451
+ # 获取权限设置
452
+ ConfigTool({ operation: "get", key: "permissions" })
453
+ \`\`\`
454
+
455
+ ### SET - 设置配置
456
+
457
+ \`\`\`
458
+ # 设置温度
459
+ ConfigTool({ operation: "set", key: "temperature", value: 0.7, scope: "global" })
460
+
461
+ # 设置语言
462
+ ConfigTool({ operation: "set", key: "language", value: "zh-CN", scope: "global" })
463
+
464
+ # 设置最大轮次
465
+ ConfigTool({ operation: "set", key: "maxTurns", value: 50, scope: "local" })
466
+
467
+ # 启用调试
468
+ ConfigTool({ operation: "set", key: "debug", value: true, scope: "local" })
469
+
470
+ # 设置环境变量
471
+ ConfigTool({ operation: "set", key: "env", value: { "NODE_ENV": "development" }, scope: "project" })
472
+ \`\`\`
473
+
474
+ ### LIST - 列举可配置项
475
+
476
+ \`\`\`
477
+ ConfigTool({ operation: "list" })
478
+ \`\`\`
479
+
480
+ 返回所有白名单配置项及其当前值。
481
+
482
+ ## 白名单字段
483
+
484
+ 以下字段可通过 ConfigTool SET 修改:
485
+
486
+ | 字段 | 类型 | 说明 |
487
+ |------|------|------|
488
+ | temperature | number | 模型温度 |
489
+ | maxContextTokens | number | 上下文窗口大小 |
490
+ | maxOutputTokens | number | 输出 token 限制 |
491
+ | timeout | number | HTTP 请求超时(毫秒)|
492
+ | codeTheme | string | 代码与终端主题 |
493
+ | uiTheme | string | Web UI 主题 |
494
+ | language | string | 界面语言 |
495
+ | fontSize | number | 字体大小 |
496
+ | debug | boolean/string | 调试模式 |
497
+ | autoSaveSessions | boolean | 自动保存会话 |
498
+ | maxTurns | number | Agent 最大轮次 |
499
+ | disableAllHooks | boolean | 禁用所有 hooks |
500
+ | permissions | object | 权限规则 |
501
+ | hooks | object | Hooks 配置 |
502
+ | env | object | 环境变量 |
503
+ | mcpServers | object | MCP 服务器配置 |
504
+
505
+ **禁止修改的字段:** models、currentModelId(保护 API Key 安全)
506
+
507
+ ## Hooks 安装指南
508
+
509
+ Hooks 是 Blade 的自动化机制,在特定事件发生时执行 shell 命令。
510
+
511
+ ### HookEvent 类型
512
+
513
+ | 事件 | 触发时机 | 典型用途 |
514
+ |------|----------|----------|
515
+ | PreToolUse | 工具执行前 | 代码检查、格式化验证 |
516
+ | PostToolUse | 工具执行后 | 自动运行 lint/test |
517
+ | PostToolUseFailure | 工具执行失败后 | 错误日志 |
518
+ | PermissionRequest | 权限请求时 | 自动批准/拒绝 |
519
+ | UserPromptSubmit | 用户提交提示时 | 注入上下文 |
520
+ | SessionStart | 会话启动时 | 环境初始化 |
521
+ | SessionEnd | 会话结束时 | 清理操作 |
522
+ | Stop | Agent 停止时 | 阻止过早停止 |
523
+ | SubagentStop | 子 Agent 停止时 | 同上 |
524
+ | Notification | 通知事件时 | 自定义通知 |
525
+ | Compaction | 上下文压缩时 | 阻止压缩 |
526
+
527
+ ### HookMatcher 结构
528
+
529
+ 每个 HookMatcher 包含:
530
+ - \`name\`(可选): 名称,用于日志
531
+ - \`matcher\`(可选): 匹配器,不指定则匹配所有
532
+ - \`tools\`: 工具名匹配(支持字符串或数组,如 \`"Edit"\` 或 \`["Edit", "Write"]\`)
533
+ - \`paths\`: 文件路径匹配(glob 模式,如 \`"**/*.ts"\`)
534
+ - \`commands\`: 命令匹配(正则,如 \`"^git"\`)
535
+ - \`hooks\`: Hook 列表
536
+
537
+ ### CommandHook 结构
538
+
539
+ \`\`\`json
540
+ {
541
+ "type": "command",
542
+ "command": "shell command to execute",
543
+ "timeout": 30,
544
+ "statusMessage": "Running check..."
545
+ }
546
+ \`\`\`
547
+
548
+ Hook 接收 JSON 格式的输入通过 stdin,输出 JSON 到 stdout。
549
+
550
+ ### 完整安装示例
551
+
552
+ **示例 1:安装 biome check 作为 PostToolUse hook**
553
+
554
+ 当 Edit 或 Write 工具修改 .ts/.tsx 文件后,自动运行 biome check:
555
+
556
+ \`\`\`
557
+ ConfigTool({
558
+ operation: "set",
559
+ key: "hooks",
560
+ value: {
561
+ "PostToolUse": [
562
+ {
563
+ "name": "biome-check",
564
+ "matcher": {
565
+ "tools": ["Edit", "Write"],
566
+ "paths": ["**/*.ts", "**/*.tsx"]
567
+ },
568
+ "hooks": [
569
+ {
570
+ "type": "command",
571
+ "command": "biome check --write $(echo $TOOL_INPUT | jq -r '.file_path // empty')",
572
+ "timeout": 30,
573
+ "statusMessage": "Running biome check..."
574
+ }
575
+ ]
576
+ }
577
+ ]
578
+ },
579
+ scope: "project"
580
+ })
581
+ \`\`\`
582
+
583
+ **示例 2:安装 eslint 作为 PostToolUse hook**
584
+
585
+ \`\`\`
586
+ ConfigTool({
587
+ operation: "set",
588
+ key: "hooks",
589
+ value: {
590
+ "PostToolUse": [
591
+ {
592
+ "name": "eslint-fix",
593
+ "matcher": {
594
+ "tools": ["Edit", "Write"],
595
+ "paths": ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx"]
596
+ },
597
+ "hooks": [
598
+ {
599
+ "type": "command",
600
+ "command": "eslint --fix $(echo $TOOL_INPUT | jq -r '.file_path // empty')",
601
+ "timeout": 30,
602
+ "statusMessage": "Running ESLint..."
603
+ }
604
+ ]
605
+ }
606
+ ]
607
+ },
608
+ scope: "project"
609
+ })
610
+ \`\`\`
611
+
612
+ **示例 3:安装 SessionStart hook 打印环境信息**
613
+
614
+ \`\`\`
615
+ ConfigTool({
616
+ operation: "set",
617
+ key: "hooks",
618
+ value: {
619
+ "SessionStart": [
620
+ {
621
+ "name": "env-info",
622
+ "hooks": [
623
+ {
624
+ "type": "command",
625
+ "command": "echo 'Node:' $(node -v) '| Git branch:' $(git branch --show-current)",
626
+ "timeout": 10,
627
+ "statusMessage": "Gathering environment info..."
628
+ }
629
+ ]
630
+ }
631
+ ]
632
+ },
633
+ scope: "project"
634
+ })
635
+ \`\`\`
636
+
637
+ **示例 4:设置权限白名单**
638
+
639
+ \`\`\`
640
+ ConfigTool({
641
+ operation: "set",
642
+ key: "permissions",
643
+ value: {
644
+ "allow": [
645
+ "Bash(git:*)",
646
+ "Bash(npm:*)",
647
+ "Bash(bun:*)",
648
+ "Read(**/*.ts)"
649
+ ],
650
+ "ask": [],
651
+ "deny": [
652
+ "Bash(rm -rf:*)"
653
+ ]
654
+ },
655
+ scope: "project"
656
+ })
657
+ \`\`\`
658
+
659
+ ## 自动行为关键词映射
660
+
661
+ 当用户使用以下关键词时,映射到对应的配置操作:
662
+
663
+ | 用户说的 | 映射到 |
664
+ |----------|--------|
665
+ | "从现在起 lint 每个文件" | PostToolUse hook(Edit/Write 后运行 lint)|
666
+ | "每次提交前运行测试" | PreToolUse hook(Bash git commit 前运行 test)|
667
+ | "当编辑 TS 文件时检查类型" | PostToolUse hook(Edit 后运行 tsc)|
668
+ | "允许所有 git 命令" | permissions.allow 添加 \`Bash(git:*)\` |
669
+ | "设置调试模式" | debug = true |
670
+ | "改成中文" | language = "zh-CN" |
671
+ | "提高温度" | temperature 调整 |
672
+ | "限制 50 轮" | maxTurns = 50 |
673
+ | "禁用 hooks" | disableAllHooks = true |
674
+ | "添加环境变量" | env 对象更新 |
675
+
676
+ ## 验证流程
677
+
678
+ 每次安装 hook 或修改配置后,**必须**验证:
679
+
680
+ 1. 用 \`ConfigTool({ operation: "get", key: "<modified-key>" })\` 确认值已生效
681
+ 2. 如果是 hooks,检查结构是否正确(包含 matcher 和 hooks 数组)
682
+ 3. 如果是 permissions,确认 allow/ask/deny 数组格式正确
683
+ 4. 告知用户配置已保存到哪个文件(根据 scope 判断)
684
+
685
+ ## 注意事项
686
+
687
+ 1. **hooks 字段使用 deep-merge 策略**:设置新的 hook 不会覆盖已有的 hook。但如果同一事件下设置新的 matcher 数组,会替换该事件的整个 matcher 列表
688
+ 2. **permissions 字段使用 replace 策略**:设置 permissions 会完全替换现有值。如果只想添加规则,先 GET 当前值,合并后再 SET
689
+ 3. **env 字段使用 deep-merge 策略**:可以逐个添加环境变量
690
+ 4. **scope 默认值**:不指定 scope 时,根据字段路由表决定(hooks/permissions/env 默认 local,temperature/codeTheme 等默认 global)
691
+ `}}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(`
692
+ `)}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"}
693
+ ${W}
694
+ \`\`\``;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:
695
+
696
+ `,J=Z.length,q=0;for(let K of $){let X=K.argumentHint?` ${K.argumentHint}`:"",G=`- /${K.name}${X}: ${K.description} ${K.label}
697
+ `;if(J+G.length>O)break;Z+=G,J+=G.length,q++}if(q<Q)Z+=`
698
+ (${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()})}
699
+ `,"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)}
700
+ `,{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(`
701
+ `)}}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}>
702
+ ${K.content}
703
+ </instruction-file>`}),J=Q==="contextual-project-instructions"&&$.length>0?` trigger-paths="${jO($.join(","))}"`:"",q=Z.length>0?`<${Q}${J}>
704
+ ${Z.join(`
705
+
706
+ `)}
707
+ </${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(`
708
+ `))}}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(`
709
+ `))}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()}
710
+ export{Q4 as be,Z4 as ce,V1 as de,L4 as ee,X4 as fe,o as ge,_4 as he,I1 as ie,g as je,_ as ke,t0 as le,M0 as me,D as ne,Q0 as oe,Q1 as pe,A0 as qe,d as re,bO as se,D0 as te,AO as ue,o$ as ve,o2 as we,a2 as xe,t2 as ye,r2 as ze,e2 as Ae,O5 as Be};