blade-code 0.10.24 → 0.10.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/chunk-01n8k1jj.js +1 -0
- package/dist/{chunk-1gkpjhts.js → chunk-0q4jbbm5.js} +1 -1
- package/dist/{chunk-9c3jjbgd.js → chunk-1g5h4zv6.js} +1 -1
- package/dist/{chunk-xzdpdwhz.js → chunk-1hzj6s0f.js} +2 -2
- package/dist/chunk-1mh2285d.js +200 -0
- package/dist/{chunk-26zhy301.js → chunk-20kg90zt.js} +2 -2
- package/dist/{chunk-18n15nn8.js → chunk-35d5gdgw.js} +1 -1
- package/dist/{chunk-f8zz4se0.js → chunk-46yg6dfr.js} +2 -2
- package/dist/{chunk-f4ksxskk.js → chunk-4aem0m2n.js} +1 -1
- package/dist/chunk-58tpe6nx.js +44 -0
- package/dist/{chunk-phzy5kqq.js → chunk-58yqrbey.js} +1 -1
- package/dist/{chunk-5xph8r1k.js → chunk-5mtryjjc.js} +1 -1
- package/dist/chunk-5yr2c8gz.js +25 -0
- package/dist/chunk-6axhk4r7.js +2 -0
- package/dist/chunk-6k74z0eb.js +2 -0
- package/dist/{chunk-yac1ga9w.js → chunk-6srz3q5d.js} +1 -1
- package/dist/{chunk-d2kzet1k.js → chunk-7jv8thn1.js} +2 -2
- package/dist/{chunk-3fkj59nv.js → chunk-89gswfb2.js} +1 -1
- package/dist/{chunk-w56y2pvk.js → chunk-8htfb5zn.js} +2 -2
- package/dist/{chunk-hpmxmkzc.js → chunk-9ka0bdry.js} +1 -1
- package/dist/{chunk-m13jrgp9.js → chunk-a4cyec1y.js} +2 -2
- package/dist/chunk-aa28p37g.js +2 -0
- package/dist/chunk-acf5v2fv.js +2 -0
- package/dist/chunk-b5fegjt7.js +6 -0
- package/dist/chunk-bbjtt28z.js +1 -0
- package/dist/{chunk-6vfe3409.js → chunk-ct2x59pr.js} +1 -1
- package/dist/chunk-d9jz1edf.js +100 -0
- package/dist/chunk-dxgzyy09.js +1 -0
- package/dist/{chunk-j8ggq1z4.js → chunk-ebffhjma.js} +2 -2
- package/dist/{chunk-bp886b8j.js → chunk-edyxa2jw.js} +1 -1
- package/dist/{chunk-k2b95m2p.js → chunk-eqa706gn.js} +2 -2
- package/dist/chunk-f88wkyfm.js +1 -0
- package/dist/{chunk-aw8s1sej.js → chunk-fbc5zfq7.js} +1 -1
- package/dist/chunk-fkwqgqsw.js +1 -0
- package/dist/{chunk-m27w377p.js → chunk-fnt1z0y8.js} +1 -1
- package/dist/chunk-gahvpbbs.js +1 -0
- package/dist/{chunk-57q5wn4g.js → chunk-gn37wxwg.js} +1 -1
- package/dist/chunk-h2npwqz9.js +10 -0
- package/dist/{chunk-c674mmtj.js → chunk-jt55ct49.js} +2 -2
- package/dist/{chunk-xjqcc0nt.js → chunk-k99rbzqw.js} +1 -1
- package/dist/{chunk-wjqctwyr.js → chunk-kskg7crs.js} +26 -41
- package/dist/{chunk-p1dp2xgq.js → chunk-kvd5nexw.js} +1 -1
- package/dist/chunk-kwe0a3xw.js +1 -0
- package/dist/chunk-m7x4ya6m.js +1 -0
- package/dist/chunk-mqsxghqb.js +1 -0
- package/dist/chunk-nar8qz5t.js +1 -0
- package/dist/{chunk-5sw8j9ae.js → chunk-nt6xmzk0.js} +1 -1
- package/dist/chunk-p6nhdbdw.js +116 -0
- package/dist/{chunk-67ekta7b.js → chunk-pja0tttq.js} +1 -1
- package/dist/{chunk-my2jwz6y.js → chunk-px3t1rxa.js} +2 -2
- package/dist/chunk-pyfag66h.js +1 -0
- package/dist/chunk-q1papzdc.js +1 -0
- package/dist/{chunk-pccn8ndq.js → chunk-r46ws0q8.js} +2 -2
- package/dist/{chunk-bw7vknjr.js → chunk-rgafk34p.js} +1 -1
- package/dist/chunk-rth3jfdq.js +2 -0
- package/dist/{chunk-nqpcwa0k.js → chunk-rtktz9v1.js} +233 -231
- package/dist/{chunk-s14wmzm3.js → chunk-s1khjfye.js} +2 -2
- package/dist/{chunk-vns8g2rv.js → chunk-sprjrvn6.js} +1 -1
- package/dist/chunk-ss449b56.js +1 -0
- package/dist/{chunk-yaxapgbm.js → chunk-tg1mf1tf.js} +1 -1
- package/dist/{chunk-x6tns9d8.js → chunk-tnrrnzzv.js} +1 -1
- package/dist/chunk-v508x7cg.js +0 -0
- package/dist/chunk-vc2c8wkx.js +2 -0
- package/dist/chunk-vp50e95n.js +3 -0
- package/dist/chunk-wg8p9g0z.js +1 -0
- package/dist/chunk-xkb48pvz.js +1 -0
- package/dist/{chunk-t327cwnb.js → chunk-xp44jtsd.js} +1 -1
- package/dist/chunk-y2en7qvs.js +6 -0
- package/dist/{chunk-86zsjamb.js → chunk-zs9mwd17.js} +3 -3
- package/dist/web/assets/{ChatView-CCxjYDmJ.js → ChatView-Crna6-ID.js} +2 -2
- package/dist/web/assets/{CodeBlockHighlighter-D9MqsrZP.js → CodeBlockHighlighter-coWjWCyT.js} +1 -1
- package/dist/web/assets/{FilePreview-Cn5HOlPw.js → FilePreview-BKcCbpvz.js} +2 -2
- package/dist/web/assets/{MarkdownRenderer-ALTOCdfi.js → MarkdownRenderer-BqV1nvf1.js} +3 -3
- package/dist/web/assets/{SettingsModal-Dk69F1bS.js → SettingsModal-BOMswk9P.js} +2 -2
- package/dist/web/assets/{TaskSwitcher-DRZZocE1.js → TaskSwitcher-BEW2DhW3.js} +1 -1
- package/dist/web/assets/{TerminalPanel-ByAqKZ47.js → TerminalPanel-BXzypTz6.js} +1 -1
- package/dist/web/assets/index-DqXKkjcp.js +11 -0
- package/dist/web/index.html +1 -1
- package/package.json +2 -1
- package/dist/chunk-014rwj5b.js +0 -1
- package/dist/chunk-0568ndm9.js +0 -200
- package/dist/chunk-1pkca2km.js +0 -3
- package/dist/chunk-2wpnzjme.js +0 -1
- package/dist/chunk-3ak60ndt.js +0 -1
- package/dist/chunk-3qmwt188.js +0 -100
- package/dist/chunk-4a02yjg9.js +0 -2
- package/dist/chunk-6pb6zs96.js +0 -2
- package/dist/chunk-7dqc10sc.js +0 -1
- package/dist/chunk-ag07wwer.js +0 -2
- package/dist/chunk-bpz0g8ej.js +0 -2
- package/dist/chunk-bvwq5wth.js +0 -6
- package/dist/chunk-c29y2s8g.js +0 -2
- package/dist/chunk-d70mtcp4.js +0 -1
- package/dist/chunk-e71qm105.js +0 -1
- package/dist/chunk-edqtngzr.js +0 -44
- package/dist/chunk-f0mt91sr.js +0 -1
- package/dist/chunk-gwe547ww.js +0 -1
- package/dist/chunk-m486vmtn.js +0 -1
- package/dist/chunk-n00mknme.js +0 -25
- package/dist/chunk-n54tp9wr.js +0 -1
- package/dist/chunk-pq7tk058.js +0 -6
- package/dist/chunk-q5sewfn5.js +0 -1
- package/dist/chunk-qg87zezq.js +0 -1
- package/dist/chunk-r14bz8va.js +0 -1
- package/dist/chunk-rtkhyp1g.js +0 -1
- package/dist/chunk-s4mqw4wa.js +0 -116
- package/dist/chunk-sgnjekfb.js +0 -1
- package/dist/chunk-tetxqw28.js +0 -1
- package/dist/chunk-vmzf4nvh.js +0 -2
- package/dist/chunk-zm3zn23k.js +0 -10
- package/dist/web/assets/index-CRCirUK7.js +0 -11
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{$d as Z0,_d as L1,ae as G1}from"./chunk-5mtryjjc.js";import{ee as $O,fe as HO}from"./chunk-nt6xmzk0.js";import{ie as Y1}from"./chunk-35d5gdgw.js";import{je as B0,le as M0}from"./chunk-zs9mwd17.js";import{Te as V0,Ue as o1,cf as S0}from"./chunk-58tpe6nx.js";import{ff as u,hf as W,kf as R1}from"./chunk-9ka0bdry.js";import{rf as b}from"./chunk-kvd5nexw.js";import{vf as h,wf as z}from"./chunk-8htfb5zn.js";import{Jf as p0}from"./chunk-acf5v2fv.js";import{Of as w}from"./chunk-r46ws0q8.js";import J1 from"node:path";import Y$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import zO from"yaml";var u$={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 c$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
|
|
2
2
|
|
|
3
3
|
You are a fresh, independent, adversarial verifier. The parent Agent has claimed
|
|
4
4
|
that a persisted goal is complete. Your job is to refute that claim unless the
|
|
@@ -32,7 +32,7 @@ Submit the host-requested structured final object with:
|
|
|
32
32
|
- findings: concrete gaps with file or command locators
|
|
33
33
|
|
|
34
34
|
PASS is allowed only when every requirement is directly proven and no relevant
|
|
35
|
-
check fails.`,K1={name:Z0,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:UO,permissionMode:"yolo",maxTurns:12,source:"builtin"};var
|
|
35
|
+
check fails.`,K1={name:Z0,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:UO,permissionMode:"yolo",maxTurns:12,source:"builtin"};var jO=`# Code Review Agent
|
|
36
36
|
|
|
37
37
|
You are an independent senior code reviewer. Find actionable defects introduced
|
|
38
38
|
by the requested change. Do not implement fixes and do not praise the author.
|
|
@@ -87,7 +87,7 @@ Your final response must be exactly one JSON object and no Markdown fence:
|
|
|
87
87
|
|
|
88
88
|
Use workspace-relative paths. Keep line ranges within 10 lines and overlapping
|
|
89
89
|
the reviewed diff. Return an empty findings array when no qualifying defect is
|
|
90
|
-
found.`,W1={name:G1,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:
|
|
90
|
+
found.`,W1={name:G1,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:jO,source:"builtin"};var i$={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 t$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var SO=`# Verification Agent
|
|
91
91
|
|
|
92
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
93
|
|
|
@@ -97,6 +97,7 @@ You are an **independent verification engineer**. Your sole purpose is to find p
|
|
|
97
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
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
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.
|
|
100
101
|
|
|
101
102
|
## Verification Workflow
|
|
102
103
|
|
|
@@ -149,28 +150,12 @@ Think like an attacker or a hostile user:
|
|
|
149
150
|
|
|
150
151
|
## Output Format
|
|
151
152
|
|
|
152
|
-
|
|
153
|
+
Reserve your final model turn for the host-requested structured output object.
|
|
154
|
+
Submit exactly these fields:
|
|
153
155
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
### Automated Checks
|
|
158
|
-
- [ ] Type check: PASS/FAIL — [details]
|
|
159
|
-
- [ ] Tests: PASS/FAIL — [details, including test count]
|
|
160
|
-
- [ ] Lint: PASS/FAIL — [details]
|
|
161
|
-
- [ ] Build: PASS/FAIL — [details]
|
|
162
|
-
|
|
163
|
-
### Code Review Findings
|
|
164
|
-
- [Issue severity: HIGH/MEDIUM/LOW] [file:line] Description
|
|
165
|
-
Evidence: [exact code or output]
|
|
166
|
-
|
|
167
|
-
### Adversarial Analysis
|
|
168
|
-
- [Risk level: HIGH/MEDIUM/LOW] Description
|
|
169
|
-
Impact: [what could go wrong]
|
|
170
|
-
|
|
171
|
-
### Summary
|
|
172
|
-
[1-3 sentence overall assessment with specific evidence]
|
|
173
|
-
\`\`\`
|
|
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
|
|
174
159
|
|
|
175
160
|
### Verdict Rules
|
|
176
161
|
|
|
@@ -178,7 +163,7 @@ You MUST end your response with a structured verification report. Emit exactly o
|
|
|
178
163
|
- **FAIL**: Any automated check fails OR any HIGH severity issue found.
|
|
179
164
|
- **PARTIAL**: All automated checks pass BUT MEDIUM severity issues exist.
|
|
180
165
|
|
|
181
|
-
Be thorough. Be skeptical. Find the bugs.`,source:"builtin"};var
|
|
166
|
+
Be thorough. Be skeptical. Find the bugs.`,X1={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:SO,source:"builtin"};var T0=[{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
|
|
182
167
|
|
|
183
168
|
You are a specialized code exploration agent. Your job is to **directly execute searches** using the tools available to you.
|
|
184
169
|
|
|
@@ -245,9 +230,9 @@ You are a software architect specializing in implementation planning.
|
|
|
245
230
|
**Risks**:
|
|
246
231
|
- [Potential issue and mitigation]
|
|
247
232
|
|
|
248
|
-
Be thorough but concise. Focus on actionable steps.`},{name:"statusline-setup",description:"Use this agent to configure the user's Claude Code status line setting.",tools:["Read","Edit"]},W1,X1,K1];var K0=h("Agent"),D0=new Set([L1,Z0]);class
|
|
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"]},W1,X1,K1];var K0=h("Agent"),D0=new Set([L1,Z0]);class v{workspaceRoot;static instances=new Map;subagents=new Map;constructor(O=b()){this.workspaceRoot=O}static getInstance(O=b()){let $=R.resolve(O),Q=v.instances.get($);if(!Q)Q=new v($),v.instances.set($,Q);return Q}static resetInstances(){v.instances.clear()}register(O){if(D0.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(D0.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:
|
|
249
234
|
${O.map((Q)=>{let q=!Q.tools||Q.tools.length===0?"All tools":Q.tools.join(", ");return`- ${Q.name}: ${Q.description} (Tools: ${q})`}).join(`
|
|
250
|
-
`)}`}loadFromDirectory(O,$){if(!C0.existsSync(O))return;let Q=C0.readdirSync(O);for(let q of Q){if(!q.endsWith(".md"))continue;let Z=R.join(O,q);try{let J=this.parseConfigFile(Z,$);if(D0.has(J.name)){K0.warn(`Skipping reserved subagent configuration: ${J.name}`);continue}this.subagents.set(J.name,J)}catch(J){K0.warn(`Failed to load subagent config from ${Z}:`,J)}}}parseConfigFile(O,$){let q=C0.readFileSync(O,"utf-8").match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(!q)throw Error(`No YAML frontmatter found in ${O}`);let[,Z,J]=q,K=
|
|
235
|
+
`)}`}loadFromDirectory(O,$){if(!C0.existsSync(O))return;let Q=C0.readdirSync(O);for(let q of Q){if(!q.endsWith(".md"))continue;let Z=R.join(O,q);try{let J=this.parseConfigFile(Z,$);if(D0.has(J.name)){K0.warn(`Skipping reserved subagent configuration: ${J.name}`);continue}this.subagents.set(J.name,J)}catch(J){K0.warn(`Failed to load subagent config from ${Z}:`,J)}}}parseConfigFile(O,$){let q=C0.readFileSync(O,"utf-8").match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(!q)throw Error(`No YAML frontmatter found in ${O}`);let[,Z,J]=q,K=zO.parse(Z);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=J.trim(),G=this.parseStringOrArray(K.tools),L=this.parseStringOrArray(K.skills),Y=Y1(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:L,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??w.getInstance().isTrustedCached(this.workspaceRoot);this.loadBuiltinAgents();let Q=R.join(J0.homedir(),".claude","agents");if(this.loadFromDirectory(Q,"claude-code-user"),$){let J=R.join(this.workspaceRoot,".claude","agents");this.loadFromDirectory(J,"claude-code-project")}let q=R.join(J0.homedir(),".blade","agents");if(this.loadFromDirectory(q,"blade-user"),$){let J=R.join(this.workspaceRoot,".blade","agents");this.loadFromDirectory(J,"blade-project")}let Z=this.getAllNames().length;return K0.debug(`Loaded ${Z} subagents from standard locations`),Z}loadBuiltinAgents(){for(let O of T0)this.subagents.set(O.name,{...O,model:O.model||"inherit",source:"builtin"});K0.debug(`Loaded ${T0.length} builtin subagents`)}clear(){this.subagents.clear()}snapshot(){let O=new v(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",q=Q.startsWith("plugin:")?"plugin":Q;O[q].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(J0.homedir(),".claude","agents");return R.join(b(),".claude","agents")}static getBladeAgentsDir(O){if(O==="user")return R.join(J0.homedir(),".blade","agents");return R.join(b(),".blade","agents")}}function i(O=b()){return v.getInstance(O)}var H4=new Proxy({},{get(O,$){let Q=i(),q=Reflect.get(Q,$,Q);return typeof q==="function"?q.bind(Q):q}});import*as H0 from"node:fs/promises";import{homedir as x1}from"node:os";import*as _ from"node:path";var G0={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 H1(){return{metadata:G0,instructions:`# Skill Creator
|
|
251
236
|
|
|
252
237
|
帮助用户创建新的 Blade Skills。
|
|
253
238
|
|
|
@@ -445,7 +430,7 @@ Blade 采用三层配置,优先级从低到高:
|
|
|
445
430
|
| Local | \`.blade/settings.local.json\` | 本地覆盖,.gitignore | \`local\` |
|
|
446
431
|
|
|
447
432
|
**选择原则:**
|
|
448
|
-
- 个人偏好(
|
|
433
|
+
- 个人偏好(codeTheme, language, fontSize)→ \`global\`
|
|
449
434
|
- 团队共享(hooks, permissions, env)→ \`project\`
|
|
450
435
|
- 临时调试(debug, maxTurns)→ \`local\`
|
|
451
436
|
|
|
@@ -504,7 +489,7 @@ ConfigTool({ operation: "list" })
|
|
|
504
489
|
| maxContextTokens | number | 上下文窗口大小 |
|
|
505
490
|
| maxOutputTokens | number | 输出 token 限制 |
|
|
506
491
|
| timeout | number | HTTP 请求超时(毫秒)|
|
|
507
|
-
|
|
|
492
|
+
| codeTheme | string | 代码与终端主题 |
|
|
508
493
|
| uiTheme | string | Web UI 主题 |
|
|
509
494
|
| language | string | 界面语言 |
|
|
510
495
|
| fontSize | number | 字体大小 |
|
|
@@ -702,24 +687,24 @@ ConfigTool({
|
|
|
702
687
|
1. **hooks 字段使用 deep-merge 策略**:设置新的 hook 不会覆盖已有的 hook。但如果同一事件下设置新的 matcher 数组,会替换该事件的整个 matcher 列表
|
|
703
688
|
2. **permissions 字段使用 replace 策略**:设置 permissions 会完全替换现有值。如果只想添加规则,先 GET 当前值,合并后再 SET
|
|
704
689
|
3. **env 字段使用 deep-merge 策略**:可以逐个添加环境变量
|
|
705
|
-
4. **scope 默认值**:不指定 scope 时,根据字段路由表决定(hooks/permissions/env 默认 local,temperature/
|
|
706
|
-
`}}import{exec as
|
|
707
|
-
`)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}snapshot(){let O=new k({...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 q of this.pluginSkills.values())if(q.originalName===O)Q.push(q);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 P(O){return k.getInstance(O)}async function
|
|
690
|
+
4. **scope 默认值**:不指定 scope 时,根据字段路由表决定(hooks/permissions/env 默认 local,temperature/codeTheme 等默认 global)
|
|
691
|
+
`}}import{exec as BO}from"node:child_process";import*as U from"node:fs/promises";import{homedir as MO}from"node:os";import*as I from"node:path";import{promisify as xO}from"node:util";var X0=xO(BO),x=h("General"),R0={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class V1{skillsDir;constructor(O){this.skillsDir=O||I.join(MO(),".blade","skills")}async isInstalled(O){let $=I.join(this.skillsDir,O,"SKILL.md");try{return await U.access($),!0}catch{return!1}}async isGitAvailable(){try{return await X0("git --version"),!0}catch{return!1}}async installOfficialSkill(O){let{url:$,branch:Q}=R0,q=I.join(this.skillsDir,O),Z=I.join(this.skillsDir,`.tmp-${O}-${Date.now()}`);try{if(!await this.isGitAvailable())return x.warn("Git not available, skipping skill installation"),!1;x.info(`Installing official skill: ${O}...`),await U.mkdir(this.skillsDir,{recursive:!0,mode:493}),await X0(`git clone --depth 1 --branch ${Q} --single-branch ${$} "${Z}"`,{timeout:30000});let J=I.join(Z,"skills",O);try{await U.access(J)}catch{return x.warn(`Skill ${O} not found in official repository`),await U.rm(Z,{recursive:!0,force:!0}),!1}try{await U.rm(q,{recursive:!0,force:!0})}catch{}return await U.cp(J,q,{recursive:!0}),await U.rm(Z,{recursive:!0,force:!0}),x.info(`Successfully installed: ${O}`),!0}catch(J){try{await U.rm(Z,{recursive:!0,force:!0})}catch{}return x.warn(`Failed to install ${O}: ${J instanceof Error?J.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await U.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let O of R0.defaultSkills)if(!await this.isInstalled(O))await this.installOfficialSkill(O)}async installFromRepo(O,$){let Q=$||this.extractRepoName(O),q=I.join(this.skillsDir,Q),Z=I.join(this.skillsDir,`.tmp-repo-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return x.warn("Git not available, cannot install from repo"),!1;x.info(`Installing skill from repo: ${O}...`),await U.mkdir(this.skillsDir,{recursive:!0,mode:493}),await X0(`git clone --depth 1 "${O}" "${Z}"`,{timeout:60000});let J=I.join(Z,"SKILL.md");try{await U.access(J)}catch{return x.warn(`No SKILL.md found in repository ${O}`),await U.rm(Z,{recursive:!0,force:!0}),!1}await U.rm(q,{recursive:!0,force:!0}),await U.rename(Z,q);try{await U.rm(I.join(q,".git"),{recursive:!0,force:!0})}catch{}return x.info(`Successfully installed skill from repo: ${Q}`),!0}catch(J){try{await U.rm(Z,{recursive:!0,force:!0})}catch{}return x.warn(`Failed to install from repo ${O}: ${J instanceof Error?J.message:"Unknown error"}`),!1}}async installFromLocal(O,$,Q=!0){let q=$||I.basename(O),Z=I.join(this.skillsDir,q);try{let J=I.resolve(O);try{await U.access(J)}catch{return x.warn(`Local path does not exist: ${J}`),!1}let K=I.join(J,"SKILL.md");try{await U.access(K)}catch{return x.warn(`No SKILL.md found in local path: ${J}`),!1}if(x.info(`Installing skill from local path: ${J}...`),await U.mkdir(this.skillsDir,{recursive:!0,mode:493}),await U.rm(Z,{recursive:!0,force:!0}),Q)await U.symlink(J,Z,"dir"),x.info(`Created symlink for skill: ${q}`);else await U.cp(J,Z,{recursive:!0}),x.info(`Copied skill to: ${q}`);return!0}catch(J){return x.warn(`Failed to install from local path ${O}: ${J instanceof Error?J.message:"Unknown error"}`),!1}}extractRepoName(O){return O.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:O,branch:$}=R0,Q=I.join(this.skillsDir,`.tmp-all-${Date.now()}`),q=[],Z=[];try{if(!await this.isGitAvailable())return x.warn("Git not available, skipping skill installation"),{installed:q,failed:Z};await U.mkdir(this.skillsDir,{recursive:!0,mode:493}),x.info("Cloning official skills repository..."),await X0(`git clone --depth 1 --branch ${$} --single-branch ${O} "${Q}"`,{timeout:60000});let J=I.join(Q,"skills"),K=await U.readdir(J,{withFileTypes:!0});for(let X of K){if(!X.isDirectory())continue;let G=X.name,L=I.join(J,G),Y=I.join(this.skillsDir,G);try{await U.access(I.join(L,"SKILL.md")),await U.rm(Y,{recursive:!0,force:!0}),await U.cp(L,Y,{recursive:!0}),x.info(`Installed: ${G}`),q.push(G)}catch(V){x.warn(`Failed to install ${G}`),Z.push(G)}}await U.rm(Q,{recursive:!0,force:!0})}catch(J){try{await U.rm(Q,{recursive:!0,force:!0})}catch{}x.warn(`Failed to install skills: ${J instanceof Error?J.message:"Unknown error"}`)}return{installed:q,failed:Z}}}var y0=null;function U1(O){if(!y0)y0=new V1(O);return y0}import*as t from"node:fs/promises";import*as L0 from"node:path";import{parse as IO}from"yaml";var bO=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,AO=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,j1=1024;function _O(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 S1(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 wO(O,$){if(!O.name)return{valid:!1,error:"Missing required field: name"};if(!AO.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>j1)return{valid:!1,error:`Description too long: ${O.description.length} characters (max ${j1})`};let Q;if(O.model)Q=O.model==="inherit"?"inherit":O.model;return{valid:!0,metadata:{name:O.name,description:O.description.trim(),allowedTools:_O(O["allowed-tools"]),version:O.version,argumentHint:O["argument-hint"]?.trim(),userInvocable:S1(O["user-invocable"]),disableModelInvocation:S1(O["disable-model-invocation"]),model:Q,whenToUse:O.when_to_use?.trim()}}}function z1(O,$,Q){let q=O.match(bO);if(!q)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,Z,J]=q,K;try{K=IO(Z)}catch(L){return{success:!1,error:`Failed to parse YAML frontmatter: ${L instanceof Error?L.message:String(L)}`}}let X=wO(K,$);if(!X.valid)return{success:!1,error:X.error};let G=L0.dirname($);return{success:!0,content:{metadata:{...X.metadata,path:$,basePath:G,source:Q},instructions:J.trim()}}}async function Y0(O,$){try{let Q=await t.readFile(O,"utf-8");return z1(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 B1(O){try{let $=await t.readFile(O.path,"utf-8"),Q=z1($,O.path,O.source);return Q.success?Q.content:null}catch{return null}}async function M1(O){try{return await t.access(L0.join(O,"SKILL.md")),!0}catch{return!1}}var TO={userSkillsDir:_.join(x1(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:_.join(x1(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},v0=new Map;function CO(O){return _.resolve(O?.cwd??b())}class k{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(O){this.config={...TO,cwd:b(),...O}}static getInstance(O){let $=CO(O),Q=v0.get($);if(!Q)Q=new k({...O,cwd:_.resolve(O?.cwd??b())}),v0.set($,Q);return Q}static resetInstance(){v0.clear()}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let O=[],$=[];try{await U1(this.config.userSkillsDir).ensureDefaultSkillsInstalled()}catch(J){O.push({path:"SkillInstaller",error:`Failed to install default skills: ${J instanceof Error?J.message:"Unknown error"}`})}this.loadBuiltinSkills();let Q=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");$.push(...Q.skills),O.push(...Q.errors);let q=await this.scanDirectory(this.config.userSkillsDir,"user");if($.push(...q.skills),O.push(...q.errors),(await w.getInstance().getStatus(this.config.cwd)).state==="trusted"){let J=_.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:_.join(this.config.cwd,this.config.claudeProjectSkillsDir),K=await this.scanDirectory(J,"project");$.push(...K.skills),O.push(...K.errors);let X=_.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:_.join(this.config.cwd,this.config.projectSkillsDir),G=await this.scanDirectory(X,"project");$.push(...G.skills),O.push(...G.errors)}for(let J of $)this.skills.set(J.name,J);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:O}}loadBuiltinSkills(){this.skills.set(G0.name,G0),this.skills.set(W0.name,W0)}async scanDirectory(O,$){let Q=[],q=[];try{await H0.access(O)}catch{return{skills:Q,errors:q}}try{let Z=await H0.readdir(O,{withFileTypes:!0});for(let J of Z){if(!J.isDirectory())continue;let K=_.join(O,J.name),X=_.join(K,"SKILL.md");if(!await M1(K))continue;let G=await Y0(X,$);if(G.success&&G.content)Q.push(G.content.metadata);else q.push({path:X,error:G.error||"Unknown error"})}}catch(Z){q.push({path:O,error:`Failed to scan directory: ${Z instanceof Error?Z.message:String(Z)}`})}return{skills:Q,errors:q}}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 B1($)}loadBuiltinContent(O){switch(O){case"skill-creator":return H1();case"update-config":return F1();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();if(O.length===0)return"";let $=[];for(let Q of O){let q=Q.description.length>100?`${Q.description.substring(0,97)}...`:Q.description,Z=Q.argumentHint?`${Q.name} ${Q.argumentHint}`:Q.name;$.push(`- ${Z}: ${q}`)}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 k({...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 q of this.pluginSkills.values())if(q.originalName===O)Q.push(q);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 P(O){return k.getInstance(O)}async function DO(O){return P(O).initialize()}import vO from"node:path";import{execSync as NO}from"node:child_process";import I1 from"node:fs";import b1 from"node:path";class E0{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 q=`$${Q}`,Z=$[Q-1]??"";O=O.split(q).join(Z)}return O}async executeBashEmbeds(O,$){let Q=/!`([^`]+)`/g,q=[];for(let J of O.matchAll(Q))q.push({match:J[0],command:J[1]});let Z=O;for(let{match:J,command:K}of q){if($.signal?.aborted){Z=Z.replace(J,"[Execution aborted]");continue}try{let X=NO(K,{cwd:$.workspaceRoot,encoding:"utf-8",timeout:30000,maxBuffer:1048576,stdio:["pipe","pipe","pipe"]}).trim();Z=Z.replace(J,X)}catch(X){let G=X instanceof Error?X.message:String(X);Z=Z.replace(J,`[Error executing '${K}': ${G}]`)}}return Z}async resolveFileReferences(O,$){let Q=/@([\w./-]+(?:\/[\w./-]+|\.[\w]+))/g,q=[];for(let J of O.matchAll(Q))q.push({match:J[0],relativePath:J[1]});let Z=O;for(let{match:J,relativePath:K}of q){let X=b1.resolve($,K);try{if(I1.statSync(X).isFile()){let L=I1.readFileSync(X,"utf-8"),V=`\`\`\`${b1.extname(K).slice(1)||"text"}
|
|
708
693
|
${L}
|
|
709
|
-
\`\`\``;Z=Z.replace(J,V)}}catch{}}return Z}hasDynamicContent(O){return{hasArgs:/\$ARGUMENTS|\$\d/.test(O),hasBashEmbeds:/!`[^`]+`/.test(O),hasFileRefs:/@[\w./-]+(?:\/[\w./-]+|\.[\w]+)/.test(O)}}}import h0 from"node:fs";import _1 from"node:os";import E from"node:path";import
|
|
694
|
+
\`\`\``;Z=Z.replace(J,V)}}catch{}}return Z}hasDynamicContent(O){return{hasArgs:/\$ARGUMENTS|\$\d/.test(O),hasBashEmbeds:/!`[^`]+`/.test(O),hasFileRefs:/@[\w./-]+(?:\/[\w./-]+|\.[\w]+)/.test(O)}}}import h0 from"node:fs";import _1 from"node:os";import E from"node:path";import RO from"node:fs";import A1 from"node:path";import yO from"gray-matter";class f0{parse(O,$,Q,q){try{let Z=RO.readFileSync(O,"utf-8"),{data:J,content:K}=yO(Z),{name:X,namespace:G}=this.extractNameAndNamespace(O,$);if(!X)return null;return{name:X,namespace:G,config:this.normalizeConfig(J),content:K.trim(),path:O,source:Q,sourceDir:q}}catch(Z){return console.error(`Failed to parse command file: ${O}`,Z),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 q=A1.relative($,O).split(A1.sep),Z=q.pop();if(!Z)return{name:""};let J=Z.replace(/\.md$/i,""),K=q.length>0?q.join("/"):void 0;return{name:J,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 k0{parser=new f0;async discover(O){let $=[],Q=[],q=[],Z=this.getSearchDirs(O);for(let J of Z){if(!h0.existsSync(J.path))continue;Q.push(J.path);try{let K=await this.scanDirectory(J.path);for(let X of K)try{let G=this.parser.parse(X,J.path,J.source,J.sourceDir);if(G)$.push(G)}catch(G){q.push({path:X,error:G instanceof Error?G.message:String(G)})}}catch(K){q.push({path:J.path,error:K instanceof Error?K.message:String(K)})}}return{commands:$,scannedDirs:Q,errors:q}}getSearchDirs(O){let $=_1.homedir();return[{path:E.join($,".blade","commands"),source:"user",sourceDir:"blade"},{path:E.join($,".claude","commands"),source:"user",sourceDir:"claude"},{path:E.join(O,".blade","commands"),source:"project",sourceDir:"blade"},{path:E.join(O,".claude","commands"),source:"project",sourceDir:"claude"}]}async scanDirectory(O){let $=[],Q=async(q)=>{let Z=await h0.promises.readdir(q,{withFileTypes:!0});for(let J of Z){let K=E.join(q,J.name);if(J.isDirectory())await Q(K);else if(J.isFile()&&J.name.endsWith(".md"))$.push(K)}};return await Q(O),$}async hasCommands(O){let $=this.getSearchDirs(O);for(let Q of $){if(!h0.existsSync(Q.path))continue;if((await this.scanDirectory(Q.path)).length>0)return!0}return!1}getCommandDirs(O){let $=_1.homedir();return{projectBlade:E.join(O,".blade","commands"),projectClaude:E.join(O,".claude","commands"),userBlade:E.join($,".blade","commands"),userClaude:E.join($,".claude","commands")}}}class T{static instances=new Map;commands=new Map;pluginCommands=new Map;loader=new k0;executor=new E0;initialized=!1;workspaceRoot="";lastDiscoveryResult=null;static getInstance(O=b()){let $=vO.resolve(O),Q=T.instances.get($);if(!Q)Q=new T,T.instances.set($,Q);return Q}static resetInstance(){T.instances.clear()}constructor(){}async initialize(O){this.workspaceRoot=O;let $=await this.loader.discover(O),Q=(await w.getInstance().getStatus(O)).state==="trusted",q={...$,commands:$.commands.filter((Z)=>Z.source!=="project"||Q)};this.lastDiscoveryResult=q,this.commands.clear();for(let Z of q.commands)this.commands.set(Z.name,Z);return this.initialized=!0,q}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 q=`Available custom commands:
|
|
710
695
|
|
|
711
696
|
`,Z=q.length,J=0;for(let K of $){let X=K.argumentHint?` ${K.argumentHint}`:"",G=`- /${K.name}${X}: ${K.description} ${K.label}
|
|
712
697
|
`;if(Z+G.length>O)break;q+=G,Z+=G.length,J++}if(J<Q)q+=`
|
|
713
|
-
(${J} of ${Q} commands shown due to character budget)`;return{text:q,includedCount:J,totalCount:Q}}snapshot(){let O=new w;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 q of this.pluginCommands.values())if(q.originalName===O)Q.push(q);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 q={name:Q.namespacedName,config:Q.config,content:Q.content,path:Q.path,source:"project",sourceDir:"blade"};return this.executor.execute(q,$)}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 X$ from"node:path";import{satisfies as P0,validRange as T1}from"semver";var yO=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function p0(O){if(O.bladeVersion!==void 0&&(!O.bladeVersion.trim()||!T1(O.bladeVersion)))throw Error(`Invalid Blade version range in plugin "${O.name}": ${O.bladeVersion}`);for(let[$,Q]of Object.entries(O.dependencies??{})){if(!yO.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()||!T1(Q))throw Error(`Invalid dependency range for ${$} in plugin "${O.name}": ${Q}`)}}function C1(O,$=d0()){if(p0(O),O.bladeVersion&&!P0($,O.bladeVersion))throw Error(`Plugin "${O.name}" requires Blade ${O.bladeVersion}, current ${$}`)}function w1(O,$){O.status="error",O.compatibilityIssues=[...O.compatibilityIssues??[],$],O.error=O.compatibilityIssues.map((Q)=>Q.message).join("; ")}function D1(O,$=d0()){let Q=[],q=new Map(O.map((J)=>[J.manifest.name,J]));for(let J of O){if(J.status!=="active")continue;if(J.manifest.bladeVersion&&!P0($,J.manifest.bladeVersion)){let K={code:"blade-version",expected:J.manifest.bladeVersion,actual:$,message:`Requires Blade ${J.manifest.bladeVersion}, current ${$}`};w1(J,K),Q.push(K)}}let Z=!0;while(Z){Z=!1;for(let J of O){if(J.status!=="active")continue;for(let[K,X]of Object.entries(J.manifest.dependencies??{})){let G=q.get(K),L;if(!G)L={code:"dependency-missing",dependency:K,expected:X,message:`Missing dependency ${K}@${X}`};else if(!P0(G.manifest.version,X))L={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")L={code:"dependency-inactive",dependency:K,expected:X,actual:G.status,message:`Dependency ${K} is ${G.status}`};if(!L)continue;w1(J,L),Q.push(L),Z=!0;break}}}return Q}import{execFile as iO}from"node:child_process";import{createHash as tO,randomUUID as p1}from"node:crypto";import{constants as e,promises as F}from"node:fs";import{homedir as u0}from"node:os";import S from"node:path";import{promisify as aO}from"node:util";import{Mutex as rO}from"async-mutex";import{satisfies as c0}from"semver";import eO from"write-file-atomic";import*as F0 from"node:fs/promises";import*as k1 from"node:path";var c=W.String({minLength:2,maxLength:64,pattern:"^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]{1,2}$"}),m0=W.String({pattern:"^\\d+\\.\\d+\\.\\d+(-[\\w.]+)?(\\+[\\w.]+)?$"}),EO=W.Object({name:W.String({minLength:1}),email:W.Optional(W.String({format:"email"})),url:W.Optional(W.String({format:"uri"}))}),v1=W.Object({name:c,description:W.String({minLength:1,maxLength:500}),version:m0,author:W.Optional(EO),license:W.Optional(W.String()),repository:W.Optional(W.String({format:"uri"})),homepage:W.Optional(W.String({format:"uri"})),keywords:W.Optional(W.Array(W.String())),dependencies:W.Optional(W.Record(W.String(),W.String())),bladeVersion:W.Optional(W.String())}),fO=W.Union([W.Object({type:W.Literal("git"),url:W.String({minLength:1}),ref:W.Optional(W.String({minLength:1}))},{additionalProperties:!1}),W.Object({type:W.Literal("local"),path:W.String({minLength:1})},{additionalProperties:!1}),W.Object({type:W.Literal("marketplace"),marketplace:c},{additionalProperties:!1})]),hO=W.Object({name:c,source:fO,installPath:W.String({minLength:1}),version:m0,revision:W.String({minLength:1,maxLength:128}),contentDigest:W.String({pattern:"^[a-f0-9]{64}$"}),installedAt:W.String({format:"date-time"}),updatedAt:W.String({format:"date-time"})},{additionalProperties:!1}),kO=W.Union([W.Object({type:W.Literal("git"),url:W.String({minLength:1}),ref:W.Optional(W.String({minLength:1}))},{additionalProperties:!1}),W.Object({type:W.Literal("local"),path:W.String({minLength:1})},{additionalProperties:!1})]),PO=W.Object({name:c,source:kO,installPath:W.String({minLength:1}),revision:W.String({minLength:1,maxLength:128}),contentDigest:W.String({pattern:"^[a-f0-9]{64}$"}),addedAt:W.String({format:"date-time"}),updatedAt:W.String({format:"date-time"})},{additionalProperties:!1}),dO=W.Object({version:W.Literal(1),installed:W.Record(W.String(),hO),marketplaces:W.Record(W.String(),PO)},{additionalProperties:!1}),y1=W.Object({name:W.String({minLength:1}),email:W.Optional(W.String({format:"email"})),url:W.Optional(W.String({format:"uri"}))}),pO=W.Object({name:c,description:W.Optional(W.String({maxLength:500})),version:W.Optional(m0),author:W.Optional(W.Union([W.String({minLength:1}),y1])),source:W.Union([W.String({minLength:1}),W.Object({source:W.Literal("url"),url:W.String({minLength:1}),ref:W.Optional(W.String({minLength:1})),sha:W.Optional(W.String({pattern:"^[a-fA-F0-9]{40}$"}))})]),category:W.Optional(W.String()),homepage:W.Optional(W.String({format:"uri"})),tags:W.Optional(W.Array(W.String()))}),mO=W.Object({name:c,description:W.Optional(W.String({maxLength:500})),owner:W.Optional(y1),metadata:W.Optional(W.Object({description:W.Optional(W.String({maxLength:500})),version:W.Optional(W.String())})),plugins:W.Array(pO,{maxItems:5000})}),N1=W.Object({type:R1(["stdio","sse","http"]),command:W.Optional(W.String()),args:W.Optional(W.Array(W.String())),env:W.Optional(W.Record(W.String(),W.String())),cwd:W.Optional(W.String()),url:W.Optional(W.String({format:"uri"})),headers:W.Optional(W.Record(W.String(),W.String())),timeout:W.Optional(W.Integer({minimum:1000,maximum:1800000})),idleTimeout:W.Optional(W.Integer({minimum:1000,maximum:1800000})),sampling:W.Optional(W.Object({enabled:W.Boolean(),maxTokens:W.Optional(W.Integer({minimum:1,maximum:4096})),maxRequestsPerToolCall:W.Optional(W.Integer({minimum:1,maximum:8})),maxInputBytes:W.Optional(W.Integer({minimum:1,maximum:1048576}))})),oauth:W.Optional(W.Object({enabled:W.Optional(W.Boolean()),clientId:W.Optional(W.String({minLength:1,maxLength:4096})),scopes:W.Optional(W.Array(W.String({minLength:1,maxLength:128}),{maxItems:32})),callbackPort:W.Optional(W.Integer({minimum:1024,maximum:65535}))},{additionalProperties:!1})),healthCheck:W.Optional(W.Object({enabled:W.Optional(W.Boolean()),interval:W.Optional(W.Number({exclusiveMinimum:0})),timeout:W.Optional(W.Number({exclusiveMinimum:0})),failureThreshold:W.Optional(W.Number({exclusiveMinimum:0}))}))}),gO=W.Union([W.Object({mcpServers:W.Record(W.String(),N1)}),W.Record(W.String(),N1)]);function E1(O){return u(gO,O)}function f1(O){return u(dO,O)}function h1(O){return u(mO,O)}var uO=[{dir:".blade-plugin",source:"blade"},{dir:".claude-plugin",source:"claude"}];async function a(O){for(let{dir:$,source:Q}of uO){let q=k1.join(O,$,"plugin.json");try{await F0.access(q)}catch{continue}try{let Z=await F0.readFile(q,"utf-8"),J=JSON.parse(Z),K=u(v1,J);if(!K.success){let X=K.error.issues.map((G)=>`${G.path.join(".")}: ${G.message}`).join("; ");throw Error(`Invalid plugin.json: ${X}`)}return p0(K.data),z.debug(`Parsed plugin manifest from ${q}`),{manifest:K.data,source:Q,manifestPath:q}}catch(Z){if(Z instanceof SyntaxError)throw Error(`Invalid JSON in ${q}: ${Z.message}`);throw Z}}return null}import{realpathSync as cO}from"node:fs";import g0 from"node:path";var lO=/^[a-fA-F0-9]{40}$/;class v extends Error{code;constructor(O,$){super($);this.code=O;this.name="PluginSourcePolicyError"}}function sO(O,$){let Q=(Z)=>{try{return cO.native(Z)}catch{return g0.resolve(Z)}},q=g0.relative(Q(O),Q($));return q===""||!q.startsWith("..")&&!g0.isAbsolute(q)}function nO(O){let $=O.match(/^[^@]+@([^:]+):/);if($?.[1])return $[1].toLowerCase();try{return new URL(O).hostname.toLowerCase()}catch{return}}function oO(O,$){if(!$.startsWith("*."))return O===$;let Q=$.slice(1);return O.endsWith(Q)&&O.length>Q.length}function P1(O,$,Q){if(O.requireGitCommitSha&&(!$.ref||!lO.test($.ref)))throw new v("PLUGIN_GIT_SHA_REQUIRED",`${Q} must pin a full 40-character Git commit SHA`);if(!O.restrictToAllowedSources)return;let q=nO($.url);if(!q||!O.allowedGitHosts.some((Z)=>oO(q,Z)))throw new v("PLUGIN_SOURCE_BLOCKED",`${Q} Git host is not allowed by plugin source policy`)}function d1(O,$,Q){if(!O.restrictToAllowedSources)return;if(!O.allowedLocalRoots.some((q)=>sO(q,$)))throw new v("PLUGIN_SOURCE_BLOCKED",`${Q} local path is not allowed by plugin source policy`)}function l(O,$,Q="Marketplace"){if($.type==="git")P1(O,$,Q);else d1(O,$.path,Q)}function r(O,$,Q,q="Plugin"){if($.type==="git"){P1(O,$,q);return}if($.type==="local"){d1(O,$.path,q);return}if(O.restrictToAllowedSources&&!O.allowedMarketplaces.includes($.marketplace))throw new v("PLUGIN_SOURCE_BLOCKED",`Marketplace "${$.marketplace}" is not allowed by plugin source policy`);let Z=Q[$.marketplace];if(!Z)throw new v("MARKETPLACE_NOT_FOUND",`Marketplace "${$.marketplace}" is not configured`);l(O,Z.source,`Marketplace "${$.marketplace}"`)}var O$=aO(iO),$$=1,m1=2097152,g1=1e4,u1=104857600,Q$=120000,q$=15000,Z$=600000,n0=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,c1=/^[a-fA-F0-9]{40}$/,J$=[S.join(".blade-plugin","marketplace.json"),S.join(".claude-plugin","marketplace.json"),"marketplace.json"];class H extends Error{code;constructor(O,$){super($);this.code=O;this.name="PluginPackageError"}}function K$(){return{version:$$,installed:{},marketplaces:{}}}function s(O){return O.code==="ENOENT"}function n(O){if(O instanceof H||O instanceof v)return{code:O.code,message:O.message};return{code:"PLUGIN_PACKAGE_ERROR",message:O instanceof Error?O.message:String(O)}}function l0(O){return S.isAbsolute(O)||O.startsWith("./")||O.startsWith("../")||O==="~"||O.startsWith("~/")}function O0(O,$){let Q=S.relative(O,$);return Q===""||!Q.startsWith("..")&&!S.isAbsolute(Q)}function o(O,$="plugin"){if(!n0.test(O))throw new H("INVALID_PLUGIN_NAME",`Invalid ${$} name: ${O}`);return O}function G$(O){if(O.startsWith("git@"))return;let $=O.lastIndexOf("@");if($<=0||$===O.length-1)return;let Q=O.slice(0,$),q=O.slice($+1);if(!n0.test(Q)||!n0.test(q))return;return{pluginName:Q,marketplace:q}}class l1{userPluginsDir;stateRoot;statePath;mutex=new rO;constructor(O,$){this.userPluginsDir=O??S.join(u0(),".blade","plugins"),this.stateRoot=$??S.join(S.dirname(this.userPluginsDir),"plugin-state"),this.statePath=S.join(this.stateRoot,"state.json")}async install(O,$={}){return this.runMutation(async()=>{let Q=[];try{this.requireSourceTrust($.trusted);let q=await this.readState(),Z=await this.resolvePluginSource(O,q,$),J=this.effectivePolicy($.policy);if(r(J,Z.recordSource,q.marketplaces),Z.expectedName&&q.installed[Z.expectedName])throw new H("PLUGIN_ALREADY_INSTALLED",`Plugin "${Z.expectedName}" is already installed`);let K=await this.preparePluginClosure({state:q,source:Z.source,recordSource:Z.recordSource,expectedName:Z.expectedName,policy:J,updateRoot:!1});Q=K.prepared;let X=await this.commitPreparedPlugins(q,Q),G=X.records.get(K.root.name);if(!G)throw new H("PLUGIN_PACKAGE_ERROR","Root plugin was not committed");let L=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:L,changed:X.changed.has(K.root.name)}}catch(q){await this.cleanupPreparedPlugins(Q);let Z=n(q);return{success:!1,code:Z.code,error:Z.message}}})}async update(O,$={}){return this.runMutation(async()=>{let Q=[];try{this.requireSourceTrust($.trusted),o(O);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`);let J=this.effectivePolicy($.policy);r(J,Z.source,q.marketplaces);let K=await this.preparePluginClosure({state:q,source:Z.source,recordSource:Z.source,expectedName:O,policy:J,updateRoot:!0});Q=K.prepared;let X=await this.commitPreparedPlugins(q,Q),G=X.records.get(O);if(!G)throw new H("PLUGIN_PACKAGE_ERROR","Updated root plugin was not committed");let L=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:L,changed:X.changed.has(O)}}catch(q){await this.cleanupPreparedPlugins(Q);let Z=n(q);return{success:!1,pluginName:O,code:Z.code,error:Z.message}}})}async uninstall(O,$=!1){return this.runMutation(async()=>{try{if(o(O),!$)throw new H("CONFIRMATION_REQUIRED",`Uninstalling "${O}" requires explicit confirmation`);let Q=await this.readState(),q=Q.installed[O];if(!q)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:q}}catch(Q){let q=n(Q);return{success:!1,pluginName:O,code:q.code,error:q.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),q=await F.realpath(O.installPath);if(!O0(Q,q))throw new H("PLUGIN_PACKAGE_TAMPERED",`Managed plugin "${O.name}" has an invalid package path`);if(await this.digestTree(q)!==O.contentDigest)throw new H("PLUGIN_PACKAGE_TAMPERED",`Managed plugin "${O.name}" failed content verification`);let J=await a(q);if(!J||J.manifest.name!==O.name||J.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 q=await this.normalizeMarketplaceSource(O,$);l(this.effectivePolicy($.policy),q);let Z=await this.readState();Q=await this.materializeSource(q);let J=await this.readMarketplaceManifest(Q.stagingPath),K=o(J.name,"marketplace");if(Z.marketplaces[K])throw new H("MARKETPLACE_ALREADY_EXISTS",`Marketplace "${K}" is already configured`);let{revision:X,contentDigest:G}=Q,L=await this.publishPackage("marketplaces",K,Q);Q=void 0;let Y=new Date().toISOString(),V={name:K,source:q,installPath:L,revision:X,contentDigest:G,addedAt:Y,updatedAt:Y};return Z.marketplaces[K]=V,await this.writeState(Z),{success:!0,marketplace:V,manifest:J,changed:!0}}catch(q){if(Q)await F.rm(Q.stagingPath,{recursive:!0,force:!0});let Z=n(q);return{success:!1,code:Z.code,error:Z.message}}})}async refreshMarketplace(O,$){return this.runMutation(async()=>{let Q;try{o(O,"marketplace");let q=await this.readState(),Z=q.marketplaces[O];if(!Z)throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${O}" is not configured`);l(this.effectivePolicy($),Z.source,`Marketplace "${O}"`),Q=await this.materializeSource(Z.source);let J=await this.readMarketplaceManifest(Q.stagingPath);if(J.name!==O)throw new H("MARKETPLACE_IDENTITY_MISMATCH",`Marketplace "${O}" now declares "${J.name}"`);if(Z.revision===Q.revision&&Z.contentDigest===Q.contentDigest)return await F.rm(Q.stagingPath,{recursive:!0,force:!0}),Q=void 0,{success:!0,marketplace:Z,manifest:J,changed:!1};let{revision:K,contentDigest:X}=Q,G=await this.publishPackage("marketplaces",O,Q);Q=void 0;let L={...Z,installPath:G,revision:K,contentDigest:X,updatedAt:new Date().toISOString()};return q.marketplaces[O]=L,await this.writeState(q),{success:!0,marketplace:L,manifest:J,changed:!0}}catch(q){if(Q)await F.rm(Q.stagingPath,{recursive:!0,force:!0});let Z=n(q);return{success:!1,code:Z.code,error:Z.message}}})}async removeMarketplace(O,$=!1){return this.runMutation(async()=>{try{if(o(O,"marketplace"),!$)throw new H("CONFIRMATION_REQUIRED",`Removing marketplace "${O}" requires explicit confirmation`);let Q=await this.readState(),q=Q.marketplaces[O];if(!q)throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${O}" is not configured`);let Z=Object.values(Q.installed).filter((J)=>J.source.type==="marketplace"&&J.source.marketplace===O).map((J)=>J.name).sort();if(Z.length>0)throw new H("MARKETPLACE_IN_USE",`Marketplace "${O}" still owns installed plugins: ${Z.join(", ")}`);return delete Q.marketplaces[O],await this.writeState(Q),{success:!0,marketplace:q,changed:!0}}catch(Q){let q=n(Q);return{success:!1,code:q.code,error:q.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=S.join(this.stateRoot,".operation.lock"),$=p1(),Q=Date.now()+q$;while(Date.now()<Q)try{let q=await F.open(O,e.O_CREAT|e.O_EXCL|e.O_WRONLY,384);return await q.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:$,createdAt:new Date().toISOString()})}
|
|
714
|
-
`,"utf8"),await q.close(),async()=>{try{if(JSON.parse(await F.readFile(O,"utf8")).token===$)await F.unlink(O)}catch(Z){if(!s(Z))z.warn(`Failed to release plugin package lock: ${Z}`)}}}catch(q){if(q.code!=="EEXIST")throw q;await this.removeStaleStoreLock(O),await new Promise((Z)=>setTimeout(Z,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<Z$)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??V0.pluginSourcePolicy}async preparePluginClosure(O){let $=[],Q=new Map,q=[],Z=(K,X,G,L)=>{if(!c0(X,G))throw new H("DEPENDENCY_VERSION_MISMATCH",`Plugin "${L}" requires ${K}@${G}, found ${X}`)},J=async(K)=>{let X=K.expectedName?O.state.installed[K.expectedName]:void 0;if(X&&!K.root&&K.requiredRange){if(c0(X.version,K.requiredRange))return X;if(K.recordSource.type!=="marketplace"||X.source.type!=="marketplace"||X.source.marketplace!==K.recordSource.marketplace)Z(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 j=Q.get(K.expectedName);if(j){if(K.requiredRange)Z(j.name,j.manifest.version,K.requiredRange,K.requiredBy??"dependency");return j}if(q.includes(K.expectedName))throw new H("DEPENDENCY_CYCLE",`Plugin dependency cycle: ${[...q,K.expectedName].join(" -> ")}`)}let G=await this.materializePluginSource(K.source,O.state,K.expectedName,O.policy),L=await a(G.stagingPath);if(!L)throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("INVALID_PLUGIN","Plugin manifest was not found");let Y=o(L.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(q.includes(Y))throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("DEPENDENCY_CYCLE",`Plugin dependency cycle: ${[...q,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{C1(L.manifest)}catch(j){throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("VERSION_INCOMPATIBLE",j instanceof Error?j.message:String(j))}let V={name:Y,source:K.recordSource,manifest:L.manifest,materialized:G,existing:O.state.installed[Y]};q.push(Y);try{for(let[j,g]of Object.entries(L.manifest.dependencies??{}).sort(([q0],[N])=>q0.localeCompare(N))){let q0=Q.get(j);if(q0){Z(j,q0.manifest.version,g,Y);continue}let N=O.state.installed[j];if(N&&c0(N.version,g))continue;if(K.recordSource.type!=="marketplace")throw new H(N?"DEPENDENCY_VERSION_MISMATCH":"DEPENDENCY_MISSING",N?`Plugin "${Y}" requires ${j}@${g}, found ${N.version}`:`Plugin "${Y}" requires missing dependency ${j}@${g}; direct sources cannot auto-install dependencies`);let T0=await J({source:N?.source.type==="marketplace"&&N.source.marketplace===K.recordSource.marketplace?N.source:{type:"marketplace",marketplace:K.recordSource.marketplace},recordSource:{type:"marketplace",marketplace:K.recordSource.marketplace},expectedName:j,requiredRange:g,requiredBy:Y,root:!1});Z(j,"manifest"in T0?T0.manifest.version:T0.version,g,Y)}}catch(j){throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),j}finally{q.pop()}return Q.set(Y,V),$.push(V),V};try{let K=await J({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,q=new Set,Z=new Date().toISOString();for(let J of $){let K=J.existing;if(K?.revision===J.materialized.revision&&K.contentDigest===J.materialized.contentDigest){await F.rm(J.materialized.stagingPath,{recursive:!0,force:!0}),Q.set(J.name,K);continue}let X=await this.publishPackage("packages",J.name,J.materialized),G={name:J.name,source:J.source,installPath:X,version:J.manifest.version,revision:J.materialized.revision,contentDigest:J.materialized.contentDigest,installedAt:K?.installedAt??Z,updatedAt:Z};O.installed[J.name]=G,Q.set(J.name,G),q.add(J.name)}if(q.size>0)await this.writeState(O);return{records:Q,changed:q}}async cleanupPreparedPlugins(O){await Promise.all(O.map(($)=>F.rm($.materialized.stagingPath,{recursive:!0,force:!0})))}async resolvePluginSource(O,$,Q){let q=O.trim();if(!q)throw new H("INVALID_SOURCE","Plugin source is required");let Z=G$(q);if(Z){if(!$.marketplaces[Z.marketplace])throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${Z.marketplace}" is not configured`);return{source:{type:"marketplace",marketplace:Z.marketplace},recordSource:{type:"marketplace",marketplace:Z.marketplace},expectedName:Z.pluginName}}if(!l0(q)&&!this.looksLikeGitSource(q)){let K=[];for(let X of await this.catalogsFromState($))if(X.manifest.plugins.some((G)=>G.name===q))K.push({pluginName:q,marketplace:X.marketplace.name});if(K.length===1)return{source:{type:"marketplace",marketplace:K[0].marketplace},recordSource:{type:"marketplace",marketplace:K[0].marketplace},expectedName:q};if(K.length>1)throw new H("AMBIGUOUS_PLUGIN_SOURCE",`Plugin "${q}" exists in multiple marketplaces; use name@marketplace`)}if(l0(q)){let X={type:"local",path:await this.resolveLocalSource(q,Q.workspaceRoot)};return{source:X,recordSource:X}}let J=this.normalizeGitSource(q,Q.ref);return{source:J,recordSource:J}}async materializePluginSource(O,$,Q,q){if(O.type!=="marketplace")return this.materializeSource(O);let Z=$.marketplaces[O.marketplace];if(!Z)throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${O.marketplace}" is not configured`);let J=await this.readMarketplaceManifest(Z.installPath),K=Q?J.plugins.filter((X)=>X.name===Q):J.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(Z,K[0],q)}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 q=await F.realpath(O.installPath),Z=S.resolve(q,$.source);if(!O0(q,Z)||Z===q)throw new H("MARKETPLACE_PATH_ESCAPE",`Plugin "${$.name}" source escapes its marketplace`);let J=await F.realpath(Z);if(!O0(q,J))throw new H("MARKETPLACE_PATH_ESCAPE",`Plugin "${$.name}" source escapes its marketplace`);return this.materializeSource({type:"local",path:J})}async normalizeMarketplaceSource(O,$){let Q=O.trim();if(!Q)throw new H("INVALID_SOURCE","Marketplace source is required");if(l0(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 q;try{q=new URL(O)}catch{throw new H("INVALID_SOURCE","Invalid Git source")}if(q.protocol!=="https:"&&q.protocol!=="ssh:")throw new H("UNSAFE_GIT_PROTOCOL","Git sources must use HTTPS or SSH");if(q.password||q.protocol==="https:"&&q.username)throw new H("GIT_CREDENTIALS_IN_URL","Git credentials must not be embedded in plugin source URLs");if(q.hash||q.search)throw new H("INVALID_SOURCE","Use the ref option instead of URL query or fragment parameters");Q=q.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==="~"?u0():O.startsWith("~/")?S.join(u0(),O.slice(2)):O,q=S.resolve($??process.cwd(),Q),Z;try{Z=await F.realpath(q)}catch{throw new H("LOCAL_SOURCE_NOT_FOUND",`Local source does not exist: ${O}`)}let J=await F.lstat(Z);if(!J.isDirectory()||J.isSymbolicLink())throw new H("INVALID_LOCAL_SOURCE","Local plugin sources must be regular directories");return Z}async materializeSource(O){await this.ensureStoreDirectory();let $=S.join(this.stateRoot,"staging",p1());if(await F.mkdir(S.dirname($),{recursive:!0,mode:448}),O.type==="git"){await this.cloneGitSource(O,$);let q=await this.runGit(["rev-parse","HEAD"],$);if(O.ref&&c1.test(O.ref)&&q.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(S.join($,".git"),{recursive:!0,force:!0});let Z=await this.digestTree($);return{stagingPath:$,revision:q,contentDigest:Z}}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&&c1.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 O$("git",O,{cwd:$,encoding:"utf8",timeout:Q$,maxBuffer:4194304,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),q=typeof Q==="string"?Q:Q.stdout;if(q===void 0)throw Error("Git process returned an invalid result");return String(q).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!S.relative(O,Q).split(S.sep).includes(".git")}})}async digestTree(O){let $=[],Q=0,q=async(J)=>{let K=await F.readdir(J,{withFileTypes:!0});K.sort((X,G)=>X.name.localeCompare(G.name));for(let X of K){if(X.name===".git")continue;let G=S.join(J,X.name),L=S.relative(O,G),Y=await F.lstat(G);if(Y.isSymbolicLink())throw new H("PACKAGE_SYMLINK_FORBIDDEN",`Plugin packages may not contain symbolic links: ${L}`);if(Y.isDirectory()){await q(G);continue}if(!Y.isFile())throw new H("PACKAGE_ENTRY_FORBIDDEN",`Plugin packages may contain only files and directories: ${L}`);if(Q+=Y.size,$.push({relative:L,absolute:G,executable:(Y.mode&73)!==0}),$.length>g1||Q>u1)throw new H("PACKAGE_TOO_LARGE",`Plugin package exceeds ${g1} files or ${u1} bytes`)}};await q(O);let Z=tO("sha256");for(let J of $)Z.update(J.relative),Z.update("\x00"),Z.update(J.executable?"x":"-"),Z.update("\x00"),Z.update(await F.readFile(J.absolute)),Z.update("\x00");return Z.digest("hex")}async publishPackage(O,$,Q){let q=S.join(this.stateRoot,O,$,Q.contentDigest);await F.mkdir(S.dirname(q),{recursive:!0,mode:448});try{let Z=await F.lstat(q);if(!Z.isDirectory()||Z.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}),q}catch(Z){if(!s(Z))throw Z}return await F.rename(Q.stagingPath,q),q}async readMarketplaceManifest(O){for(let $ of J$){let Q=S.join(O,$);try{let q=await F.lstat(Q);if(!q.isFile()||q.isSymbolicLink()||q.size>m1)throw new H("INVALID_MARKETPLACE","Marketplace manifest must be a regular bounded file");let Z=JSON.parse(await F.readFile(Q,"utf8")),J=h1(Z);if(!J.success)throw new H("INVALID_MARKETPLACE",`Invalid marketplace manifest: ${J.error.issues.map((X)=>`${X.path.join(".")}: ${X.message}`).join("; ")}`);let K=new Set;for(let X of J.data.plugins){if(K.has(X.name))throw new H("INVALID_MARKETPLACE",`Marketplace contains duplicate plugin: ${X.name}`);K.add(X.name)}return J.data}catch(q){if(s(q))continue;if(q instanceof SyntaxError)throw new H("INVALID_MARKETPLACE","Marketplace manifest contains invalid JSON");throw q}}throw new H("INVALID_MARKETPLACE","Marketplace manifest was not found")}async catalogsFromState(O){let $=Object.values(O.marketplaces).sort((Q,q)=>Q.name.localeCompare(q.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,e.O_RDONLY|e.O_NOFOLLOW)}catch($){if(s($))return K$();throw new H("PLUGIN_STATE_INVALID","Plugin package state must be a regular file")}try{let $=await O.stat();if(!$.isFile()||$.size>m1)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")),q=f1(Q);if(!q.success)throw new H("PLUGIN_STATE_INVALID","Plugin package state schema is invalid");let Z=q.data;for(let[J,K]of Object.entries(Z.installed)){let X=S.join(this.stateRoot,"packages",J);if(J!==K.name||!S.isAbsolute(K.installPath)||!O0(X,K.installPath)||S.basename(K.installPath)!==K.contentDigest||K.source.type==="local"&&!S.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[J,K]of Object.entries(Z.marketplaces)){let X=S.join(this.stateRoot,"marketplaces",J);if(J!==K.name||!S.isAbsolute(K.installPath)||!O0(X,K.installPath)||S.basename(K.installPath)!==K.contentDigest||K.source.type==="local"&&!S.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 J of Object.values(Z.installed))if(J.source.type==="marketplace"&&!Z.marketplaces[J.source.marketplace])throw new H("PLUGIN_STATE_INVALID","Plugin package state references a missing marketplace");return Z}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 eO(this.statePath,`${JSON.stringify(O,null,2)}
|
|
715
|
-
`,{mode:384,encoding:"utf8"}),await F.chmod(this.statePath,384)}async ensureStoreDirectory(){try{let O=await F.lstat(this.stateRoot);if(!O.isDirectory()||O.isSymbolicLink())throw new H("PLUGIN_STORE_INVALID","Plugin package store must be a regular directory");if(process.getuid&&O.uid!==process.getuid())throw new H("PLUGIN_STORE_INVALID","Plugin package store must be owned by the current user");if((O.mode&511)!==448)throw new H("PLUGIN_STORE_INVALID","Plugin package store permissions must be 0700")}catch(O){if(!s(O))throw O;await F.mkdir(this.stateRoot,{recursive:!0,mode:448}),await F.chmod(this.stateRoot,448)}}}var s0=null;function o0(O,$){if(!s0)s0=new l1(O,$);return s0}import*as A from"node:fs/promises";import{homedir as W$}from"node:os";import*as M from"node:path";import n1 from"gray-matter";function U0(O,$){return`${O}:${$}`}function s1(O,$){return`${O}__${$}`}class S0{async loadPlugin(O,$,Q={}){let q=await a(O);if(!q)throw Error(`Not a valid plugin directory: ${O}`);let{manifest:Z,source:J}=q,K=Z.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),L=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),j=Q.skipLsp?void 0:await this.loadLspConfig(O,K);return z.debug(`Plugin "${K}" loaded: ${X.length} commands, ${G.length} agents, ${L.length} skills`),{manifest:Z,basePath:O,source:$,manifestSource:J,commands:X,agents:G,skills:L,hooks:Y,mcpServers:V,lspServers:j,status:"active",loadedAt:new Date}}async loadCommands(O,$){let Q=M.join(O,"commands"),q=[];if(!await this.dirExists(Q))return q;let Z=await this.scanMarkdownFiles(Q);for(let J of Z)try{let K=await this.parseCommandFile(J,Q,$);if(K)q.push(K)}catch(K){z.warn(`Failed to load command from ${J}: ${K instanceof Error?K.message:String(K)}`)}return q}async parseCommandFile(O,$,Q){let q=await A.readFile(O,"utf-8"),{data:Z,content:J}=n1(q),X=M.relative($,O).split(M.sep),G=X.pop();if(!G)return null;let L=G.replace(/\.md$/i,""),Y=L;if(X.length>0)Y=[...X,L].join("/");let V=U0(Q,Y),j=this.normalizeCommandConfig(Z);return{originalName:Y,namespacedName:V,pluginName:Q,config:j,content:J.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=M.join(O,"agents"),q=[];if(!await this.dirExists(Q))return q;let Z=await this.scanMarkdownFiles(Q);for(let J of Z)try{let K=await this.parseAgentFile(J,Q,$);if(K)q.push(K)}catch(K){z.warn(`Failed to load agent from ${J}: ${K instanceof Error?K.message:String(K)}`)}return q}async parseAgentFile(O,$,Q){let q=await A.readFile(O,"utf-8"),{data:Z,content:J}=n1(q),K=M.relative($,O),X=M.basename(K,".md"),G=Z.name||X,L=U0(Q,G),Y={name:L,description:this.asString(Z.description)||"",tools:this.parseStringArray(Z.tools),color:this.asString(Z.color),model:this.asString(Z.model),permissionMode:this.asString(Z.permissionMode),skills:this.parseStringArray(Z.skills),systemPrompt:J.trim(),source:`plugin:${Q}`};return{originalName:G,namespacedName:L,pluginName:Q,config:Y,path:O}}async loadSkills(O,$){let Q=M.join(O,"skills"),q=[];if(!await this.dirExists(Q))return q;let Z=await A.readdir(Q,{withFileTypes:!0});for(let J of Z){if(!J.isDirectory())continue;let K=M.join(Q,J.name),X=M.join(K,"SKILL.md");try{let G=await Y0(X,"project");if(G.success&&G.content){let L=G.content.metadata.name,Y=U0($,L);q.push({originalName:L,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 q}async loadHooks(O){let $=M.join(O,"hooks","hooks.json");try{let Q=await A.readFile($,"utf-8"),q=JSON.parse(Q);return q.hooks||q}catch{return}}async loadMcpConfig(O,$){let Q=M.join(O,".mcp.json");try{let q=await A.readFile(Q,"utf-8"),Z=JSON.parse(q),J=E1(Z);if(!J.success){z.warn(`Invalid .mcp.json in ${O}: ${J.error}`);return}let K="mcpServers"in Z?Z.mcpServers:Z,X={};for(let[G,L]of Object.entries(K)){let Y=s1($,G);X[Y]=L}return X}catch{return}}async loadLspConfig(O,$){let Q=M.join(O,".lsp.json");try{let q=JSON.parse(await A.readFile(Q,"utf8")),Z=q&&typeof q==="object"&&!Array.isArray(q)&&"lspServers"in q?q.lspServers:q,J=o1(Z),K={};for(let[X,G]of Object.entries(J)){let L=(Y)=>Y.replaceAll("${CLAUDE_PLUGIN_ROOT}",O).replaceAll("${BLADE_PLUGIN_ROOT}",O);K[`plugin:${$}:${X}`]={...G,command:L(G.command),args:G.args?.map(L),env:G.env?Object.fromEntries(Object.entries(G.env).map(([Y,V])=>[Y,L(V)])):void 0}}return K}catch(q){if(q.code!=="ENOENT")z.warn(`Invalid .lsp.json in ${O}: ${q instanceof Error?q.message:String(q)}`);return}}async scanMarkdownFiles(O){let $=[],Q=async(q)=>{let Z=await A.readdir(q,{withFileTypes:!0});for(let J of Z){let K=M.join(q,J.name);if(J.isDirectory())await Q(K);else if(J.name.endsWith(".md"))$.push(K)}};return await Q(O),$}async dirExists(O){try{return(await A.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 $=W$();return[{path:M.join($,".claude","plugins"),source:"user",type:"claude"},{path:M.join($,".blade","plugins"),source:"user",type:"blade"},{path:M.join(O,".claude","plugins"),source:"project",type:"claude"},{path:M.join(O,".blade","plugins"),source:"project",type:"blade"}]}async discoverPluginsInDir(O,$){let Q=[],q=[];try{await A.access(O)}catch{return{plugins:Q,errors:q}}let Z=await A.readdir(O,{withFileTypes:!0});for(let J of Z){if(!J.isDirectory())continue;let K=M.join(O,J.name);try{let X=await this.loadPlugin(K,$);Q.push(X)}catch(X){q.push({path:K,error:X instanceof Error?X.message:String(X)})}}return{plugins:Q,errors:q}}}class f{static instances=new Map;plugins=new Map;loader=new S0;initialized=!1;workspaceRoot="";cliPluginDirs=[];enabledSettings={};sourcePolicy={...V0.pluginSourcePolicy};marketplaces={};constructor(O){this.workspaceRoot=O}static getInstance(O=b()){let $=X$.resolve(O),Q=f.instances.get($);if(!Q)Q=new f($),f.instances.set($,Q);return Q}static resetInstance(){f.instances.clear()}static getInitializedInstances(){return Array.from(f.instances.values()).filter((O)=>O.isInitialized())}async initialize(O,$=[]){this.workspaceRoot=O,this.cliPluginDirs=$,this.enabledSettings=await j0.getInstance().loadWorkspacePluginSettings(O),await this.refreshPolicyContext();let Q=[],q=[];for(let G of $)try{let L=await this.loader.loadPlugin(G,"cli");this.plugins.set(L.manifest.name,L),Q.push(L),z.info(`Loaded CLI plugin: ${L.manifest.name} from ${G}`)}catch(L){q.push({path:G,error:L instanceof Error?L.message:String(L)}),z.warn(`Failed to load CLI plugin from ${G}: ${L}`)}let Z=(await T.getInstance().getStatus(O)).state==="trusted",J=S0.getPluginDirs(O).filter((G)=>G.source!=="project"||Z),K=!1,X=async()=>{if(K)return;K=!0;let G=o0(),L=await G.listInstallationRecords();for(let Y of L)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 j=this.plugins.get(V.manifest.name);if(!j||j.source==="user")this.plugins.set(V.manifest.name,V),Q.push(V)}catch(V){q.push({path:Y.installPath,code:"IO_ERROR",error:V instanceof Error?V.message:String(V)})}};for(let{path:G,source:L}of J){if(L==="project")await X();let Y=await this.loader.discoverPluginsInDir(G,L);for(let V of Y.plugins){let j=this.plugins.get(V.manifest.name);if(!j||j.source!=="cli")this.plugins.set(V.manifest.name,V),Q.push(V)}q.push(...Y.errors)}await X(),this.applyEnabledSettings();for(let G of this.plugins.values()){if(G.status!=="error")continue;q.push({path:G.basePath,code:G.compatibilityIssues?.some((L)=>L.code==="source-policy")?"SOURCE_POLICY_BLOCKED":G.compatibilityIssues?.some((L)=>L.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`+(q.length>0?`, ${q.length} errors`:"")),{plugins:Array.from(this.plugins.values()),errors:q}}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 j0.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{r(this.sourcePolicy,O.installation?.source??{type:"local",path:O.basePath},this.marketplaces,`Plugin "${O.manifest.name}"`)}catch($){if(!($ instanceof v))throw $;O.status="error",O.error=$.message,O.compatibilityIssues=[{code:"source-policy",message:$.message}]}}D1(Array.from(this.plugins.values()))}async refreshPolicyContext(){this.sourcePolicy=await j0.getInstance().loadWorkspacePluginSourcePolicy(this.workspaceRoot),this.marketplaces=Object.fromEntries((await o0().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 q of Q.commands)if(q.namespacedName===O)return q}let $=[];for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let q of Q.commands)if(q.originalName===O)$.push(q)}if($.length===1)return $[0];return}findSkill(O){for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let q of Q.skills)if(q.namespacedName===O)return q}let $=[];for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let q of Q.skills)if(q.originalName===O)$.push(q)}if($.length===1)return $[0];return}findAgent(O){for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let q of Q.agents)if(q.namespacedName===O)return q}let $=[];for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let q of Q.agents)if(q.originalName===O)$.push(q)}if($.length===1)return $[0];return}hasCommandConflict(O){let $=0;for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let q of Q.commands)if(q.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 q of Q.commands)if(q.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,q=0,Z=0;for(let J of this.plugins.values())if(J.status==="active")O++,Q+=J.commands.length,q+=J.skills.length,Z+=J.agents.length;else $++;return{total:this.plugins.size,active:O,inactive:$,commands:Q,skills:q,agents:Z}}formatPluginList(){if(this.getAll().length===0)return"没有已加载的插件。";let $=[],Q=this.getBySource();if(Q.cli.length>0){$.push("## CLI 指定的插件");for(let q of Q.cli){let Z=q.status==="inactive"?" (禁用)":"";$.push(`- **${q.manifest.name}** v${q.manifest.version}${Z}`),$.push(` ${q.manifest.description}`)}$.push("")}if(Q.project.length>0){$.push("## 项目级插件");for(let q of Q.project){let Z=q.status==="inactive"?" (禁用)":"";$.push(`- **${q.manifest.name}** v${q.manifest.version}${Z}`),$.push(` ${q.manifest.description}`)}$.push("")}if(Q.user.length>0){$.push("## 用户级插件");for(let q of Q.user){let Z=q.status==="inactive"?" (禁用)":"";$.push(`- **${q.manifest.name}** v${q.manifest.version}${Z}`),$.push(` ${q.manifest.description}`)}}return $.join(`
|
|
716
|
-
`)}}function z0(O=b()){return f.getInstance(O)}var d=new Map,i1=Object.values(B0);function i0(O){let $={...O};for(let Q of i1)$[Q]=(O[Q]??[]).map((q)=>({...q,matcher:q.matcher?{...q.matcher}:void 0,hooks:q.hooks.map((Z)=>({...Z}))}));return $}class t0{commandRegistry;hookManager;skillRegistry;subagentRegistry;workspaceRoot;constructor(O=b()){this.workspaceRoot=L$.resolve(O),this.commandRegistry=w.getInstance(this.workspaceRoot),this.hookManager=M0.getInstance(),this.skillRegistry=P({cwd:this.workspaceRoot}),this.subagentRegistry=i(this.workspaceRoot)}clearAllPluginResources(){this.commandRegistry.clearPluginCommands(),this.skillRegistry.clearPluginSkills(),this.subagentRegistry.clearPluginAgents();let O=d.get(this.workspaceRoot);if(O)this.hookManager.loadConfig(O,this.workspaceRoot),d.delete(this.workspaceRoot);z.debug("Cleared all plugin resources from subsystems")}async integrateAll(){let $=z0(this.workspaceRoot).getActive(),Q=[],q=[],Z=0,J=0,K=0,X=0,G=0;for(let L of $){let Y=this.integratePlugin(L);Q.push(Y),Z+=Y.commandsRegistered,J+=Y.skillsRegistered,K+=Y.agentsRegistered,X+=Y.mcpServersRegistered,G+=Y.lspServersRegistered,q.push(...Y.errors)}if(this.integrateHooks($),Z+J+K>0)z.info(`Plugin integration complete: ${Z} commands, ${J} skills, ${K} agents, ${X} MCP servers, ${G} LSP servers`);return{plugins:Q,totalCommands:Z,totalSkills:J,totalAgents:K,totalMcpServers:X,errors:q}}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 $=O.filter((J)=>J.hooks);if($.length===0){let J=d.get(this.workspaceRoot);if(J)this.hookManager.loadConfig(J,this.workspaceRoot),d.delete(this.workspaceRoot);return}let Q=i0(this.hookManager.getConfig(this.workspaceRoot));if(!d.has(this.workspaceRoot))d.set(this.workspaceRoot,i0(Q));let q=d.get(this.workspaceRoot)??Q,Z=i0(q);Z.enabled=!0;for(let J of i1){let K=q.enabled?[...q[J]??[]]:[],X=[];for(let G of $)for(let L of G.hooks?.[J]??[])X.push({...L,name:L.name?`plugin:${G.manifest.name}:${L.name}`:`plugin:${G.manifest.name}:${J}`,hooks:L.hooks.map((Y)=>({...Y,source:{kind:"plugin",pluginName:G.manifest.name,pluginSource:G.source,pluginRoot:G.basePath}}))});Z[J]=[...K,...X]}this.hookManager.loadConfig(Z,this.workspaceRoot)}integrateMcp(O){return Object.keys(O.mcpServers??{}).length}}async function a0(O=b()){return new t0(O).integrateAll()}function x0(O=b()){new t0(O).clearAllPluginResources()}import{createHash as Y$}from"node:crypto";import*as D from"node:fs/promises";import H$ from"node:os";import C from"node:path";import F$ from"gray-matter";var I0=32,t1=24576,a1=16384,r1=131072,b0=4,e1=80,OO=256,QO=/^[a-z0-9][a-z0-9._-]{0,63}$/,V$=h("Agent");function r0(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 U$(O,$,Q){let q=typeof O==="string"?O.trim():"",Z=$.split(/\r?\n/).map((K)=>K.trim()).find(Boolean)?.replace(/^#+\s*/,"")??"",J=q||Z||Q;if(J.length>OO)throw Error(`Description exceeds ${OO} characters`);if(r0(J))throw Error("Description contains hidden control characters");return J}function S$(O,$){let Q=typeof O==="string"&&O.trim()?O.trim():$;if(Q.length>e1)throw Error(`Name exceeds ${e1} characters`);if(r0(Q))throw Error("Name contains hidden control characters");return Q}function j$(O){let Q=O.replace(/\.md$/i,"").split(C.sep);if(Q.length===0||Q.length>b0||Q.some((q)=>!QO.test(q)))throw Error(`Style path must use 1-${b0} lowercase safe segments`);return Q.join(":")}async function z$(O){let $;try{$=await D.lstat(O)}catch(J){if(J.code==="ENOENT")return[];throw J}if($.isSymbolicLink())throw Error(`Output style root cannot be a symlink: ${O}`);if(!$.isDirectory())return[];let Q=await D.realpath(O),q=[],Z=async(J,K)=>{if(K>b0)throw Error(`Output style directory exceeds depth ${b0}`);let X=await D.readdir(J,{withFileTypes:!0});X.sort((G,L)=>G.name.localeCompare(L.name));for(let G of X){let L=C.join(J,G.name);if(G.isSymbolicLink())throw Error(`Output style path cannot be a symlink: ${L}`);if(G.isDirectory()){await Z(L,K+1);continue}if(!G.isFile()||!G.name.toLowerCase().endsWith(".md"))continue;let Y=await D.realpath(L),V=C.relative(Q,Y);if(!V||V.startsWith("..")||C.isAbsolute(V))throw Error(`Output style path escapes its source root: ${L}`);if(q.push(Y),q.length>I0)throw Error(`Output style catalog exceeds ${I0} files`)}};return await Z(Q,1),q}async function B$(O,$,Q){let q=await D.lstat(Q);if(!q.isFile()||q.isSymbolicLink())throw Error("Output style must be a regular file");if(q.size>t1)throw Error(`Output style exceeds ${t1} bytes`);let Z=await D.readFile(Q,"utf8"),J=F$(Z),K=J.content.trim(),X=Buffer.byteLength(K);if(X===0)throw Error("Output style prompt must not be empty");if(X>a1)throw Error(`Output style prompt exceeds ${a1} bytes`);if(r0(K))throw Error("Output style prompt contains hidden control characters");let G=C.relative($,Q),L=j$(G);return{id:`${O.idPrefix}:${L}`,name:S$(J.data.name,L),description:U$(J.data.description,K,`Custom ${L} communication style`),source:O.source,contentSha256:Y$("sha256").update(K,"utf8").digest("hex"),prompt:K}}async function M$(O,$){let Q=await z$(O.directory);if(Q.length===0)return;let q=await D.realpath(O.directory);for(let Z of Q)try{let J=await B$(O,q,Z);$.set(J.id,J)}catch(J){V$.warn(`[CommunicationStyles] Ignoring ${O.source} style: ${J instanceof Error?J.message:String(J)}`)}}function x$(O,$,Q,q){let Z=[{directory:C.join(q,".claude","output-styles"),source:"user",idPrefix:"user"},{directory:C.join(q,".blade","output-styles"),source:"user",idPrefix:"user"}];if($)Z.push({directory:C.join(O,".claude","output-styles"),source:"project",idPrefix:"project"},{directory:C.join(O,".blade","output-styles"),source:"project",idPrefix:"project"});for(let J of Q){if(J.status!=="active"||!QO.test(J.manifest.name))continue;Z.push({directory:C.join(J.basePath,"output-styles"),source:"plugin",idPrefix:`plugin:${J.manifest.name}`})}return Z}async function e0(O,$){let Q=new Map;for(let Z of x$(C.resolve(O),$.projectTrusted,$.plugins??[],$.homeDirectory??H$.homedir()))await M$(Z,Q);let q=0;for(let Z of Q.values())q+=Buffer.byteLength(Z.prompt??"");if(Q.size>I0)throw Error(`Output style catalog exceeds ${I0} styles`);if(q>r1)throw Error(`Output style catalog exceeds ${r1} bytes`);return new $O([...Q.values()])}import{createHash as I$}from"node:crypto";import{existsSync as A0,realpathSync as b$}from"node:fs";import*as m from"node:fs/promises";import B from"node:path";import A$ from"fast-glob";import _$ from"gray-matter";import XO from"picomatch";var qO=128,ZO=32768,JO=262144,T$=49152,w$=32768,C$=24,KO=16,D$=256,N$=h("Agent"),R$=["**/CLAUDE.md","**/.claude/CLAUDE.md","**/CLAUDE.local.md","**/AGENTS.md","**/AGENTS.override.md","**/BLADE.md","**/.claude/rules/**/*.md","**/.blade/rules/**/*.md"],v$=["**/.git/**","**/node_modules/**","**/.venv/**","**/dist/**","**/build/**","**/coverage/**","**/target/**"];function _0(O){return I$("sha256").update(O,"utf8").digest("hex")}function LO(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 q1(O){return O.split(B.sep).join("/")}function O1(O){let $=B.resolve(O),Q=[];while(!0)try{return B.join(b$($),...Q.reverse())}catch(q){if(q.code!=="ENOENT")return B.resolve(O);let Z=B.dirname($);if(Z===$)return B.resolve(O);Q.push(B.basename($)),$=Z}}function y$(O){let $=B.resolve(O),Q;while(!0){if(A0(B.join($,".git")))return $;if(!Q&&(A0(B.join($,".blade"))||A0(B.join($,".claude"))||A0(B.join($,"package.json"))))Q=$;let q=B.dirname($);if(q===$)return Q??B.resolve(O);$=q}}function Z1(O){return Boolean(O)&&O!==".."&&!O.startsWith("../")}function $1(O,$){return O===""||$===O||$.startsWith(`${O}/`)}function GO(O){return O.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}function E$(O){let $=typeof O==="string"?O.split(/[,\n]/u):Array.isArray(O)?O:[],Q=[...new Set($.filter((q)=>typeof q==="string").map((q)=>q.trim().replaceAll("\\","/")).filter(Boolean))];if(Q.length===0||Q.every((q)=>q==="**"))return;if(Q.length>KO)throw Error(`paths exceeds ${KO} patterns`);for(let q of Q){if(q.length>D$||B.posix.isAbsolute(q)||q.split("/").includes("..")||LO(q))throw Error(`Unsafe project rule path pattern: ${q.slice(0,80)}`);XO(q,{dot:!0})}return Q}function f$(O){if(O.endsWith("/CLAUDE.local.md")||O==="CLAUDE.local.md")return{source:"local",kind:"instruction",scopeDirectory:B.posix.dirname(O).replace(/^\.$/u,""),priority:90};for(let q of[".claude/rules/",".blade/rules/"]){let Z=O.indexOf(q);if(Z>=0)return{source:"project",kind:"rule",scopeDirectory:O.slice(0,Z).replace(/\/$/u,""),priority:q.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 $=B.posix.basename(O),Q=$==="CLAUDE.md"?20:$==="AGENTS.md"?40:$==="AGENTS.override.md"?50:60;return{source:"project",kind:"instruction",scopeDirectory:B.posix.dirname(O).replace(/^\.$/u,""),priority:Q}}function Q1(O,$){let Q=O.scopeDirectory?O.scopeDirectory.split("/").length:0,q=$.scopeDirectory?$.scopeDirectory.split("/").length:0;return Q-q||O.priority-$.priority||O.relativePath.localeCompare($.relativePath)}function h$(O){return{id:O.id,relativePath:O.relativePath,source:O.source,contentSha256:O.contentSha256}}function $0(O,$,Q){let q=O.map((K)=>{let X=K.conditional?' conditional="true"':"";return`<instruction-file path="${GO(K.relativePath)}" source="${K.source}" sha256="${K.contentSha256}"${X}>
|
|
698
|
+
(${J} of ${Q} commands shown due to character budget)`;return{text:q,includedCount:J,totalCount:Q}}snapshot(){let O=new T;return O.workspaceRoot=this.workspaceRoot,O.commands=new Map(Array.from(this.commands,([$,Q])=>[$,{...Q,config:{...Q.config,...Q.config.allowedTools?{allowedTools:[...Q.config.allowedTools]}:{}}}])),O.pluginCommands=new Map(Array.from(this.pluginCommands,([$,Q])=>[$,{...Q,config:{...Q.config,...Q.config.allowedTools?{allowedTools:[...Q.config.allowedTools]}:{}}}])),O.initialized=this.initialized,O.lastDiscoveryResult=this.lastDiscoveryResult?{commands:Array.from(O.commands.values()),scannedDirs:[...this.lastDiscoveryResult.scannedDirs],errors:this.lastDiscoveryResult.errors.map(($)=>({...$}))}:null,O}registerPluginCommand(O){this.pluginCommands.set(O.namespacedName,O)}findPluginCommand(O){let $=this.pluginCommands.get(O);if($)return $;let Q=[];for(let q of this.pluginCommands.values())if(q.originalName===O)Q.push(q);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 q={name:Q.namespacedName,config:Q.config,content:Q.content,path:Q.path,source:"project",sourceDir:"blade"};return this.executor.execute(q,$)}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 L$ from"node:path";import{satisfies as P0,validRange as w1}from"semver";var EO=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function d0(O){if(O.bladeVersion!==void 0&&(!O.bladeVersion.trim()||!w1(O.bladeVersion)))throw Error(`Invalid Blade version range in plugin "${O.name}": ${O.bladeVersion}`);for(let[$,Q]of Object.entries(O.dependencies??{})){if(!EO.test($))throw Error(`Invalid dependency name in plugin "${O.name}": ${$}`);if($===O.name)throw Error(`Plugin "${O.name}" cannot depend on itself`);if(!Q.trim()||!w1(Q))throw Error(`Invalid dependency range for ${$} in plugin "${O.name}": ${Q}`)}}function C1(O,$=p0()){if(d0(O),O.bladeVersion&&!P0($,O.bladeVersion))throw Error(`Plugin "${O.name}" requires Blade ${O.bladeVersion}, current ${$}`)}function T1(O,$){O.status="error",O.compatibilityIssues=[...O.compatibilityIssues??[],$],O.error=O.compatibilityIssues.map((Q)=>Q.message).join("; ")}function D1(O,$=p0()){let Q=[],q=new Map(O.map((J)=>[J.manifest.name,J]));for(let J of O){if(J.status!=="active")continue;if(J.manifest.bladeVersion&&!P0($,J.manifest.bladeVersion)){let K={code:"blade-version",expected:J.manifest.bladeVersion,actual:$,message:`Requires Blade ${J.manifest.bladeVersion}, current ${$}`};T1(J,K),Q.push(K)}}let Z=!0;while(Z){Z=!1;for(let J of O){if(J.status!=="active")continue;for(let[K,X]of Object.entries(J.manifest.dependencies??{})){let G=q.get(K),L;if(!G)L={code:"dependency-missing",dependency:K,expected:X,message:`Missing dependency ${K}@${X}`};else if(!P0(G.manifest.version,X))L={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")L={code:"dependency-inactive",dependency:K,expected:X,actual:G.status,message:`Dependency ${K} is ${G.status}`};if(!L)continue;T1(J,L),Q.push(L),Z=!0;break}}}return Q}import{execFile as tO}from"node:child_process";import{createHash as aO,randomUUID as d1}from"node:crypto";import{constants as e,promises as F}from"node:fs";import{homedir as u0}from"node:os";import j from"node:path";import{promisify as rO}from"node:util";import{Mutex as eO}from"async-mutex";import{satisfies as c0}from"semver";import O$ from"write-file-atomic";import*as F0 from"node:fs/promises";import*as k1 from"node:path";var c=W.String({minLength:2,maxLength:64,pattern:"^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]{1,2}$"}),m0=W.String({pattern:"^\\d+\\.\\d+\\.\\d+(-[\\w.]+)?(\\+[\\w.]+)?$"}),fO=W.Object({name:W.String({minLength:1}),email:W.Optional(W.String({format:"email"})),url:W.Optional(W.String({format:"uri"}))}),y1=W.Object({name:c,description:W.String({minLength:1,maxLength:500}),version:m0,author:W.Optional(fO),license:W.Optional(W.String()),repository:W.Optional(W.String({format:"uri"})),homepage:W.Optional(W.String({format:"uri"})),keywords:W.Optional(W.Array(W.String())),dependencies:W.Optional(W.Record(W.String(),W.String())),bladeVersion:W.Optional(W.String())}),hO=W.Union([W.Object({type:W.Literal("git"),url:W.String({minLength:1}),ref:W.Optional(W.String({minLength:1}))},{additionalProperties:!1}),W.Object({type:W.Literal("local"),path:W.String({minLength:1})},{additionalProperties:!1}),W.Object({type:W.Literal("marketplace"),marketplace:c},{additionalProperties:!1})]),kO=W.Object({name:c,source:hO,installPath:W.String({minLength:1}),version:m0,revision:W.String({minLength:1,maxLength:128}),contentDigest:W.String({pattern:"^[a-f0-9]{64}$"}),installedAt:W.String({format:"date-time"}),updatedAt:W.String({format:"date-time"})},{additionalProperties:!1}),PO=W.Union([W.Object({type:W.Literal("git"),url:W.String({minLength:1}),ref:W.Optional(W.String({minLength:1}))},{additionalProperties:!1}),W.Object({type:W.Literal("local"),path:W.String({minLength:1})},{additionalProperties:!1})]),pO=W.Object({name:c,source:PO,installPath:W.String({minLength:1}),revision:W.String({minLength:1,maxLength:128}),contentDigest:W.String({pattern:"^[a-f0-9]{64}$"}),addedAt:W.String({format:"date-time"}),updatedAt:W.String({format:"date-time"})},{additionalProperties:!1}),dO=W.Object({version:W.Literal(1),installed:W.Record(W.String(),kO),marketplaces:W.Record(W.String(),pO)},{additionalProperties:!1}),v1=W.Object({name:W.String({minLength:1}),email:W.Optional(W.String({format:"email"})),url:W.Optional(W.String({format:"uri"}))}),mO=W.Object({name:c,description:W.Optional(W.String({maxLength:500})),version:W.Optional(m0),author:W.Optional(W.Union([W.String({minLength:1}),v1])),source:W.Union([W.String({minLength:1}),W.Object({source:W.Literal("url"),url:W.String({minLength:1}),ref:W.Optional(W.String({minLength:1})),sha:W.Optional(W.String({pattern:"^[a-fA-F0-9]{40}$"}))})]),category:W.Optional(W.String()),homepage:W.Optional(W.String({format:"uri"})),tags:W.Optional(W.Array(W.String()))}),gO=W.Object({name:c,description:W.Optional(W.String({maxLength:500})),owner:W.Optional(v1),metadata:W.Optional(W.Object({description:W.Optional(W.String({maxLength:500})),version:W.Optional(W.String())})),plugins:W.Array(mO,{maxItems:5000})}),N1=W.Object({type:R1(["stdio","sse","http"]),command:W.Optional(W.String()),args:W.Optional(W.Array(W.String())),env:W.Optional(W.Record(W.String(),W.String())),cwd:W.Optional(W.String()),url:W.Optional(W.String({format:"uri"})),headers:W.Optional(W.Record(W.String(),W.String())),timeout:W.Optional(W.Integer({minimum:1000,maximum:1800000})),idleTimeout:W.Optional(W.Integer({minimum:1000,maximum:1800000})),sampling:W.Optional(W.Object({enabled:W.Boolean(),maxTokens:W.Optional(W.Integer({minimum:1,maximum:4096})),maxRequestsPerToolCall:W.Optional(W.Integer({minimum:1,maximum:8})),maxInputBytes:W.Optional(W.Integer({minimum:1,maximum:1048576}))})),oauth:W.Optional(W.Object({enabled:W.Optional(W.Boolean()),clientId:W.Optional(W.String({minLength:1,maxLength:4096})),scopes:W.Optional(W.Array(W.String({minLength:1,maxLength:128}),{maxItems:32})),callbackPort:W.Optional(W.Integer({minimum:1024,maximum:65535}))},{additionalProperties:!1})),healthCheck:W.Optional(W.Object({enabled:W.Optional(W.Boolean()),interval:W.Optional(W.Number({exclusiveMinimum:0})),timeout:W.Optional(W.Number({exclusiveMinimum:0})),failureThreshold:W.Optional(W.Number({exclusiveMinimum:0}))}))}),uO=W.Union([W.Object({mcpServers:W.Record(W.String(),N1)}),W.Record(W.String(),N1)]);function E1(O){return u(uO,O)}function f1(O){return u(dO,O)}function h1(O){return u(gO,O)}var cO=[{dir:".blade-plugin",source:"blade"},{dir:".claude-plugin",source:"claude"}];async function a(O){for(let{dir:$,source:Q}of cO){let q=k1.join(O,$,"plugin.json");try{await F0.access(q)}catch{continue}try{let Z=await F0.readFile(q,"utf-8"),J=JSON.parse(Z),K=u(y1,J);if(!K.success){let X=K.error.issues.map((G)=>`${G.path.join(".")}: ${G.message}`).join("; ");throw Error(`Invalid plugin.json: ${X}`)}return d0(K.data),z.debug(`Parsed plugin manifest from ${q}`),{manifest:K.data,source:Q,manifestPath:q}}catch(Z){if(Z instanceof SyntaxError)throw Error(`Invalid JSON in ${q}: ${Z.message}`);throw Z}}return null}import{realpathSync as lO}from"node:fs";import g0 from"node:path";var sO=/^[a-fA-F0-9]{40}$/;class y extends Error{code;constructor(O,$){super($);this.code=O;this.name="PluginSourcePolicyError"}}function nO(O,$){let Q=(Z)=>{try{return lO.native(Z)}catch{return g0.resolve(Z)}},q=g0.relative(Q(O),Q($));return q===""||!q.startsWith("..")&&!g0.isAbsolute(q)}function oO(O){let $=O.match(/^[^@]+@([^:]+):/);if($?.[1])return $[1].toLowerCase();try{return new URL(O).hostname.toLowerCase()}catch{return}}function iO(O,$){if(!$.startsWith("*."))return O===$;let Q=$.slice(1);return O.endsWith(Q)&&O.length>Q.length}function P1(O,$,Q){if(O.requireGitCommitSha&&(!$.ref||!sO.test($.ref)))throw new y("PLUGIN_GIT_SHA_REQUIRED",`${Q} must pin a full 40-character Git commit SHA`);if(!O.restrictToAllowedSources)return;let q=oO($.url);if(!q||!O.allowedGitHosts.some((Z)=>iO(q,Z)))throw new y("PLUGIN_SOURCE_BLOCKED",`${Q} Git host is not allowed by plugin source policy`)}function p1(O,$,Q){if(!O.restrictToAllowedSources)return;if(!O.allowedLocalRoots.some((q)=>nO(q,$)))throw new y("PLUGIN_SOURCE_BLOCKED",`${Q} local path is not allowed by plugin source policy`)}function l(O,$,Q="Marketplace"){if($.type==="git")P1(O,$,Q);else p1(O,$.path,Q)}function r(O,$,Q,q="Plugin"){if($.type==="git"){P1(O,$,q);return}if($.type==="local"){p1(O,$.path,q);return}if(O.restrictToAllowedSources&&!O.allowedMarketplaces.includes($.marketplace))throw new y("PLUGIN_SOURCE_BLOCKED",`Marketplace "${$.marketplace}" is not allowed by plugin source policy`);let Z=Q[$.marketplace];if(!Z)throw new y("MARKETPLACE_NOT_FOUND",`Marketplace "${$.marketplace}" is not configured`);l(O,Z.source,`Marketplace "${$.marketplace}"`)}var $$=rO(tO),Q$=1,m1=2097152,g1=1e4,u1=104857600,q$=120000,Z$=15000,J$=600000,n0=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,c1=/^[a-fA-F0-9]{40}$/,K$=[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 G$(){return{version:Q$,installed:{},marketplaces:{}}}function s(O){return O.code==="ENOENT"}function n(O){if(O instanceof H||O instanceof y)return{code:O.code,message:O.message};return{code:"PLUGIN_PACKAGE_ERROR",message:O instanceof Error?O.message:String(O)}}function l0(O){return j.isAbsolute(O)||O.startsWith("./")||O.startsWith("../")||O==="~"||O.startsWith("~/")}function O0(O,$){let Q=j.relative(O,$);return Q===""||!Q.startsWith("..")&&!j.isAbsolute(Q)}function o(O,$="plugin"){if(!n0.test(O))throw new H("INVALID_PLUGIN_NAME",`Invalid ${$} name: ${O}`);return O}function W$(O){if(O.startsWith("git@"))return;let $=O.lastIndexOf("@");if($<=0||$===O.length-1)return;let Q=O.slice(0,$),q=O.slice($+1);if(!n0.test(Q)||!n0.test(q))return;return{pluginName:Q,marketplace:q}}class l1{userPluginsDir;stateRoot;statePath;mutex=new eO;constructor(O,$){this.userPluginsDir=O??j.join(u0(),".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 q=await this.readState(),Z=await this.resolvePluginSource(O,q,$),J=this.effectivePolicy($.policy);if(r(J,Z.recordSource,q.marketplaces),Z.expectedName&&q.installed[Z.expectedName])throw new H("PLUGIN_ALREADY_INSTALLED",`Plugin "${Z.expectedName}" is already installed`);let K=await this.preparePluginClosure({state:q,source:Z.source,recordSource:Z.recordSource,expectedName:Z.expectedName,policy:J,updateRoot:!1});Q=K.prepared;let X=await this.commitPreparedPlugins(q,Q),G=X.records.get(K.root.name);if(!G)throw new H("PLUGIN_PACKAGE_ERROR","Root plugin was not committed");let L=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:L,changed:X.changed.has(K.root.name)}}catch(q){await this.cleanupPreparedPlugins(Q);let Z=n(q);return{success:!1,code:Z.code,error:Z.message}}})}async update(O,$={}){return this.runMutation(async()=>{let Q=[];try{this.requireSourceTrust($.trusted),o(O);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`);let J=this.effectivePolicy($.policy);r(J,Z.source,q.marketplaces);let K=await this.preparePluginClosure({state:q,source:Z.source,recordSource:Z.source,expectedName:O,policy:J,updateRoot:!0});Q=K.prepared;let X=await this.commitPreparedPlugins(q,Q),G=X.records.get(O);if(!G)throw new H("PLUGIN_PACKAGE_ERROR","Updated root plugin was not committed");let L=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:L,changed:X.changed.has(O)}}catch(q){await this.cleanupPreparedPlugins(Q);let Z=n(q);return{success:!1,pluginName:O,code:Z.code,error:Z.message}}})}async uninstall(O,$=!1){return this.runMutation(async()=>{try{if(o(O),!$)throw new H("CONFIRMATION_REQUIRED",`Uninstalling "${O}" requires explicit confirmation`);let Q=await this.readState(),q=Q.installed[O];if(!q)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:q}}catch(Q){let q=n(Q);return{success:!1,pluginName:O,code:q.code,error:q.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),q=await F.realpath(O.installPath);if(!O0(Q,q))throw new H("PLUGIN_PACKAGE_TAMPERED",`Managed plugin "${O.name}" has an invalid package path`);if(await this.digestTree(q)!==O.contentDigest)throw new H("PLUGIN_PACKAGE_TAMPERED",`Managed plugin "${O.name}" failed content verification`);let J=await a(q);if(!J||J.manifest.name!==O.name||J.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 q=await this.normalizeMarketplaceSource(O,$);l(this.effectivePolicy($.policy),q);let Z=await this.readState();Q=await this.materializeSource(q);let J=await this.readMarketplaceManifest(Q.stagingPath),K=o(J.name,"marketplace");if(Z.marketplaces[K])throw new H("MARKETPLACE_ALREADY_EXISTS",`Marketplace "${K}" is already configured`);let{revision:X,contentDigest:G}=Q,L=await this.publishPackage("marketplaces",K,Q);Q=void 0;let Y=new Date().toISOString(),V={name:K,source:q,installPath:L,revision:X,contentDigest:G,addedAt:Y,updatedAt:Y};return Z.marketplaces[K]=V,await this.writeState(Z),{success:!0,marketplace:V,manifest:J,changed:!0}}catch(q){if(Q)await F.rm(Q.stagingPath,{recursive:!0,force:!0});let Z=n(q);return{success:!1,code:Z.code,error:Z.message}}})}async refreshMarketplace(O,$){return this.runMutation(async()=>{let Q;try{o(O,"marketplace");let q=await this.readState(),Z=q.marketplaces[O];if(!Z)throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${O}" is not configured`);l(this.effectivePolicy($),Z.source,`Marketplace "${O}"`),Q=await this.materializeSource(Z.source);let J=await this.readMarketplaceManifest(Q.stagingPath);if(J.name!==O)throw new H("MARKETPLACE_IDENTITY_MISMATCH",`Marketplace "${O}" now declares "${J.name}"`);if(Z.revision===Q.revision&&Z.contentDigest===Q.contentDigest)return await F.rm(Q.stagingPath,{recursive:!0,force:!0}),Q=void 0,{success:!0,marketplace:Z,manifest:J,changed:!1};let{revision:K,contentDigest:X}=Q,G=await this.publishPackage("marketplaces",O,Q);Q=void 0;let L={...Z,installPath:G,revision:K,contentDigest:X,updatedAt:new Date().toISOString()};return q.marketplaces[O]=L,await this.writeState(q),{success:!0,marketplace:L,manifest:J,changed:!0}}catch(q){if(Q)await F.rm(Q.stagingPath,{recursive:!0,force:!0});let Z=n(q);return{success:!1,code:Z.code,error:Z.message}}})}async removeMarketplace(O,$=!1){return this.runMutation(async()=>{try{if(o(O,"marketplace"),!$)throw new H("CONFIRMATION_REQUIRED",`Removing marketplace "${O}" requires explicit confirmation`);let Q=await this.readState(),q=Q.marketplaces[O];if(!q)throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${O}" is not configured`);let Z=Object.values(Q.installed).filter((J)=>J.source.type==="marketplace"&&J.source.marketplace===O).map((J)=>J.name).sort();if(Z.length>0)throw new H("MARKETPLACE_IN_USE",`Marketplace "${O}" still owns installed plugins: ${Z.join(", ")}`);return delete Q.marketplaces[O],await this.writeState(Q),{success:!0,marketplace:q,changed:!0}}catch(Q){let q=n(Q);return{success:!1,code:q.code,error:q.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"),$=d1(),Q=Date.now()+Z$;while(Date.now()<Q)try{let q=await F.open(O,e.O_CREAT|e.O_EXCL|e.O_WRONLY,384);return await q.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:$,createdAt:new Date().toISOString()})}
|
|
699
|
+
`,"utf8"),await q.close(),async()=>{try{if(JSON.parse(await F.readFile(O,"utf8")).token===$)await F.unlink(O)}catch(Z){if(!s(Z))z.warn(`Failed to release plugin package lock: ${Z}`)}}}catch(q){if(q.code!=="EEXIST")throw q;await this.removeStaleStoreLock(O),await new Promise((Z)=>setTimeout(Z,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<J$)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??V0.pluginSourcePolicy}async preparePluginClosure(O){let $=[],Q=new Map,q=[],Z=(K,X,G,L)=>{if(!c0(X,G))throw new H("DEPENDENCY_VERSION_MISMATCH",`Plugin "${L}" requires ${K}@${G}, found ${X}`)},J=async(K)=>{let X=K.expectedName?O.state.installed[K.expectedName]:void 0;if(X&&!K.root&&K.requiredRange){if(c0(X.version,K.requiredRange))return X;if(K.recordSource.type!=="marketplace"||X.source.type!=="marketplace"||X.source.marketplace!==K.recordSource.marketplace)Z(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 S=Q.get(K.expectedName);if(S){if(K.requiredRange)Z(S.name,S.manifest.version,K.requiredRange,K.requiredBy??"dependency");return S}if(q.includes(K.expectedName))throw new H("DEPENDENCY_CYCLE",`Plugin dependency cycle: ${[...q,K.expectedName].join(" -> ")}`)}let G=await this.materializePluginSource(K.source,O.state,K.expectedName,O.policy),L=await a(G.stagingPath);if(!L)throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("INVALID_PLUGIN","Plugin manifest was not found");let Y=o(L.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(q.includes(Y))throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("DEPENDENCY_CYCLE",`Plugin dependency cycle: ${[...q,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{C1(L.manifest)}catch(S){throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),new H("VERSION_INCOMPATIBLE",S instanceof Error?S.message:String(S))}let V={name:Y,source:K.recordSource,manifest:L.manifest,materialized:G,existing:O.state.installed[Y]};q.push(Y);try{for(let[S,g]of Object.entries(L.manifest.dependencies??{}).sort(([q0],[N])=>q0.localeCompare(N))){let q0=Q.get(S);if(q0){Z(S,q0.manifest.version,g,Y);continue}let N=O.state.installed[S];if(N&&c0(N.version,g))continue;if(K.recordSource.type!=="marketplace")throw new H(N?"DEPENDENCY_VERSION_MISMATCH":"DEPENDENCY_MISSING",N?`Plugin "${Y}" requires ${S}@${g}, found ${N.version}`:`Plugin "${Y}" requires missing dependency ${S}@${g}; direct sources cannot auto-install dependencies`);let w0=await J({source:N?.source.type==="marketplace"&&N.source.marketplace===K.recordSource.marketplace?N.source:{type:"marketplace",marketplace:K.recordSource.marketplace},recordSource:{type:"marketplace",marketplace:K.recordSource.marketplace},expectedName:S,requiredRange:g,requiredBy:Y,root:!1});Z(S,"manifest"in w0?w0.manifest.version:w0.version,g,Y)}}catch(S){throw await F.rm(G.stagingPath,{recursive:!0,force:!0}),S}finally{q.pop()}return Q.set(Y,V),$.push(V),V};try{let K=await J({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,q=new Set,Z=new Date().toISOString();for(let J of $){let K=J.existing;if(K?.revision===J.materialized.revision&&K.contentDigest===J.materialized.contentDigest){await F.rm(J.materialized.stagingPath,{recursive:!0,force:!0}),Q.set(J.name,K);continue}let X=await this.publishPackage("packages",J.name,J.materialized),G={name:J.name,source:J.source,installPath:X,version:J.manifest.version,revision:J.materialized.revision,contentDigest:J.materialized.contentDigest,installedAt:K?.installedAt??Z,updatedAt:Z};O.installed[J.name]=G,Q.set(J.name,G),q.add(J.name)}if(q.size>0)await this.writeState(O);return{records:Q,changed:q}}async cleanupPreparedPlugins(O){await Promise.all(O.map(($)=>F.rm($.materialized.stagingPath,{recursive:!0,force:!0})))}async resolvePluginSource(O,$,Q){let q=O.trim();if(!q)throw new H("INVALID_SOURCE","Plugin source is required");let Z=W$(q);if(Z){if(!$.marketplaces[Z.marketplace])throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${Z.marketplace}" is not configured`);return{source:{type:"marketplace",marketplace:Z.marketplace},recordSource:{type:"marketplace",marketplace:Z.marketplace},expectedName:Z.pluginName}}if(!l0(q)&&!this.looksLikeGitSource(q)){let K=[];for(let X of await this.catalogsFromState($))if(X.manifest.plugins.some((G)=>G.name===q))K.push({pluginName:q,marketplace:X.marketplace.name});if(K.length===1)return{source:{type:"marketplace",marketplace:K[0].marketplace},recordSource:{type:"marketplace",marketplace:K[0].marketplace},expectedName:q};if(K.length>1)throw new H("AMBIGUOUS_PLUGIN_SOURCE",`Plugin "${q}" exists in multiple marketplaces; use name@marketplace`)}if(l0(q)){let X={type:"local",path:await this.resolveLocalSource(q,Q.workspaceRoot)};return{source:X,recordSource:X}}let J=this.normalizeGitSource(q,Q.ref);return{source:J,recordSource:J}}async materializePluginSource(O,$,Q,q){if(O.type!=="marketplace")return this.materializeSource(O);let Z=$.marketplaces[O.marketplace];if(!Z)throw new H("MARKETPLACE_NOT_FOUND",`Marketplace "${O.marketplace}" is not configured`);let J=await this.readMarketplaceManifest(Z.installPath),K=Q?J.plugins.filter((X)=>X.name===Q):J.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(Z,K[0],q)}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 q=await F.realpath(O.installPath),Z=j.resolve(q,$.source);if(!O0(q,Z)||Z===q)throw new H("MARKETPLACE_PATH_ESCAPE",`Plugin "${$.name}" source escapes its marketplace`);let J=await F.realpath(Z);if(!O0(q,J))throw new H("MARKETPLACE_PATH_ESCAPE",`Plugin "${$.name}" source escapes its marketplace`);return this.materializeSource({type:"local",path:J})}async normalizeMarketplaceSource(O,$){let Q=O.trim();if(!Q)throw new H("INVALID_SOURCE","Marketplace source is required");if(l0(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 q;try{q=new URL(O)}catch{throw new H("INVALID_SOURCE","Invalid Git source")}if(q.protocol!=="https:"&&q.protocol!=="ssh:")throw new H("UNSAFE_GIT_PROTOCOL","Git sources must use HTTPS or SSH");if(q.password||q.protocol==="https:"&&q.username)throw new H("GIT_CREDENTIALS_IN_URL","Git credentials must not be embedded in plugin source URLs");if(q.hash||q.search)throw new H("INVALID_SOURCE","Use the ref option instead of URL query or fragment parameters");Q=q.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==="~"?u0():O.startsWith("~/")?j.join(u0(),O.slice(2)):O,q=j.resolve($??process.cwd(),Q),Z;try{Z=await F.realpath(q)}catch{throw new H("LOCAL_SOURCE_NOT_FOUND",`Local source does not exist: ${O}`)}let J=await F.lstat(Z);if(!J.isDirectory()||J.isSymbolicLink())throw new H("INVALID_LOCAL_SOURCE","Local plugin sources must be regular directories");return Z}async materializeSource(O){await this.ensureStoreDirectory();let $=j.join(this.stateRoot,"staging",d1());if(await F.mkdir(j.dirname($),{recursive:!0,mode:448}),O.type==="git"){await this.cloneGitSource(O,$);let q=await this.runGit(["rev-parse","HEAD"],$);if(O.ref&&c1.test(O.ref)&&q.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 Z=await this.digestTree($);return{stagingPath:$,revision:q,contentDigest:Z}}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&&c1.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 $$("git",O,{cwd:$,encoding:"utf8",timeout:q$,maxBuffer:4194304,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),q=typeof Q==="string"?Q:Q.stdout;if(q===void 0)throw Error("Git process returned an invalid result");return String(q).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,q=async(J)=>{let K=await F.readdir(J,{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(J,X.name),L=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: ${L}`);if(Y.isDirectory()){await q(G);continue}if(!Y.isFile())throw new H("PACKAGE_ENTRY_FORBIDDEN",`Plugin packages may contain only files and directories: ${L}`);if(Q+=Y.size,$.push({relative:L,absolute:G,executable:(Y.mode&73)!==0}),$.length>g1||Q>u1)throw new H("PACKAGE_TOO_LARGE",`Plugin package exceeds ${g1} files or ${u1} bytes`)}};await q(O);let Z=aO("sha256");for(let J of $)Z.update(J.relative),Z.update("\x00"),Z.update(J.executable?"x":"-"),Z.update("\x00"),Z.update(await F.readFile(J.absolute)),Z.update("\x00");return Z.digest("hex")}async publishPackage(O,$,Q){let q=j.join(this.stateRoot,O,$,Q.contentDigest);await F.mkdir(j.dirname(q),{recursive:!0,mode:448});try{let Z=await F.lstat(q);if(!Z.isDirectory()||Z.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}),q}catch(Z){if(!s(Z))throw Z}return await F.rename(Q.stagingPath,q),q}async readMarketplaceManifest(O){for(let $ of K$){let Q=j.join(O,$);try{let q=await F.lstat(Q);if(!q.isFile()||q.isSymbolicLink()||q.size>m1)throw new H("INVALID_MARKETPLACE","Marketplace manifest must be a regular bounded file");let Z=JSON.parse(await F.readFile(Q,"utf8")),J=h1(Z);if(!J.success)throw new H("INVALID_MARKETPLACE",`Invalid marketplace manifest: ${J.error.issues.map((X)=>`${X.path.join(".")}: ${X.message}`).join("; ")}`);let K=new Set;for(let X of J.data.plugins){if(K.has(X.name))throw new H("INVALID_MARKETPLACE",`Marketplace contains duplicate plugin: ${X.name}`);K.add(X.name)}return J.data}catch(q){if(s(q))continue;if(q instanceof SyntaxError)throw new H("INVALID_MARKETPLACE","Marketplace manifest contains invalid JSON");throw q}}throw new H("INVALID_MARKETPLACE","Marketplace manifest was not found")}async catalogsFromState(O){let $=Object.values(O.marketplaces).sort((Q,q)=>Q.name.localeCompare(q.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,e.O_RDONLY|e.O_NOFOLLOW)}catch($){if(s($))return G$();throw new H("PLUGIN_STATE_INVALID","Plugin package state must be a regular file")}try{let $=await O.stat();if(!$.isFile()||$.size>m1)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")),q=f1(Q);if(!q.success)throw new H("PLUGIN_STATE_INVALID","Plugin package state schema is invalid");let Z=q.data;for(let[J,K]of Object.entries(Z.installed)){let X=j.join(this.stateRoot,"packages",J);if(J!==K.name||!j.isAbsolute(K.installPath)||!O0(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[J,K]of Object.entries(Z.marketplaces)){let X=j.join(this.stateRoot,"marketplaces",J);if(J!==K.name||!j.isAbsolute(K.installPath)||!O0(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 J of Object.values(Z.installed))if(J.source.type==="marketplace"&&!Z.marketplaces[J.source.marketplace])throw new H("PLUGIN_STATE_INVALID","Plugin package state references a missing marketplace");return Z}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 O$(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 s0=null;function o0(O,$){if(!s0)s0=new l1(O,$);return s0}import*as A from"node:fs/promises";import{homedir as X$}from"node:os";import*as M from"node:path";import n1 from"gray-matter";function U0(O,$){return`${O}:${$}`}function s1(O,$){return`${O}__${$}`}class j0{async loadPlugin(O,$,Q={}){let q=await a(O);if(!q)throw Error(`Not a valid plugin directory: ${O}`);let{manifest:Z,source:J}=q,K=Z.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),L=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),S=Q.skipLsp?void 0:await this.loadLspConfig(O,K);return z.debug(`Plugin "${K}" loaded: ${X.length} commands, ${G.length} agents, ${L.length} skills`),{manifest:Z,basePath:O,source:$,manifestSource:J,commands:X,agents:G,skills:L,hooks:Y,mcpServers:V,lspServers:S,status:"active",loadedAt:new Date}}async loadCommands(O,$){let Q=M.join(O,"commands"),q=[];if(!await this.dirExists(Q))return q;let Z=await this.scanMarkdownFiles(Q);for(let J of Z)try{let K=await this.parseCommandFile(J,Q,$);if(K)q.push(K)}catch(K){z.warn(`Failed to load command from ${J}: ${K instanceof Error?K.message:String(K)}`)}return q}async parseCommandFile(O,$,Q){let q=await A.readFile(O,"utf-8"),{data:Z,content:J}=n1(q),X=M.relative($,O).split(M.sep),G=X.pop();if(!G)return null;let L=G.replace(/\.md$/i,""),Y=L;if(X.length>0)Y=[...X,L].join("/");let V=U0(Q,Y),S=this.normalizeCommandConfig(Z);return{originalName:Y,namespacedName:V,pluginName:Q,config:S,content:J.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=M.join(O,"agents"),q=[];if(!await this.dirExists(Q))return q;let Z=await this.scanMarkdownFiles(Q);for(let J of Z)try{let K=await this.parseAgentFile(J,Q,$);if(K)q.push(K)}catch(K){z.warn(`Failed to load agent from ${J}: ${K instanceof Error?K.message:String(K)}`)}return q}async parseAgentFile(O,$,Q){let q=await A.readFile(O,"utf-8"),{data:Z,content:J}=n1(q),K=M.relative($,O),X=M.basename(K,".md"),G=Z.name||X,L=U0(Q,G),Y={name:L,description:this.asString(Z.description)||"",tools:this.parseStringArray(Z.tools),color:this.asString(Z.color),model:this.asString(Z.model),permissionMode:this.asString(Z.permissionMode),skills:this.parseStringArray(Z.skills),systemPrompt:J.trim(),source:`plugin:${Q}`};return{originalName:G,namespacedName:L,pluginName:Q,config:Y,path:O}}async loadSkills(O,$){let Q=M.join(O,"skills"),q=[];if(!await this.dirExists(Q))return q;let Z=await A.readdir(Q,{withFileTypes:!0});for(let J of Z){if(!J.isDirectory())continue;let K=M.join(Q,J.name),X=M.join(K,"SKILL.md");try{let G=await Y0(X,"project");if(G.success&&G.content){let L=G.content.metadata.name,Y=U0($,L);q.push({originalName:L,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 q}async loadHooks(O){let $=M.join(O,"hooks","hooks.json");try{let Q=await A.readFile($,"utf-8"),q=JSON.parse(Q);return q.hooks||q}catch{return}}async loadMcpConfig(O,$){let Q=M.join(O,".mcp.json");try{let q=await A.readFile(Q,"utf-8"),Z=JSON.parse(q),J=E1(Z);if(!J.success){z.warn(`Invalid .mcp.json in ${O}: ${J.error}`);return}let K="mcpServers"in Z?Z.mcpServers:Z,X={};for(let[G,L]of Object.entries(K)){let Y=s1($,G);X[Y]=L}return X}catch{return}}async loadLspConfig(O,$){let Q=M.join(O,".lsp.json");try{let q=JSON.parse(await A.readFile(Q,"utf8")),Z=q&&typeof q==="object"&&!Array.isArray(q)&&"lspServers"in q?q.lspServers:q,J=o1(Z),K={};for(let[X,G]of Object.entries(J)){let L=(Y)=>Y.replaceAll("${CLAUDE_PLUGIN_ROOT}",O).replaceAll("${BLADE_PLUGIN_ROOT}",O);K[`plugin:${$}:${X}`]={...G,command:L(G.command),args:G.args?.map(L),env:G.env?Object.fromEntries(Object.entries(G.env).map(([Y,V])=>[Y,L(V)])):void 0}}return K}catch(q){if(q.code!=="ENOENT")z.warn(`Invalid .lsp.json in ${O}: ${q instanceof Error?q.message:String(q)}`);return}}async scanMarkdownFiles(O){let $=[],Q=async(q)=>{let Z=await A.readdir(q,{withFileTypes:!0});for(let J of Z){let K=M.join(q,J.name);if(J.isDirectory())await Q(K);else if(J.name.endsWith(".md"))$.push(K)}};return await Q(O),$}async dirExists(O){try{return(await A.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 $=X$();return[{path:M.join($,".claude","plugins"),source:"user",type:"claude"},{path:M.join($,".blade","plugins"),source:"user",type:"blade"},{path:M.join(O,".claude","plugins"),source:"project",type:"claude"},{path:M.join(O,".blade","plugins"),source:"project",type:"blade"}]}async discoverPluginsInDir(O,$){let Q=[],q=[];try{await A.access(O)}catch{return{plugins:Q,errors:q}}let Z=await A.readdir(O,{withFileTypes:!0});for(let J of Z){if(!J.isDirectory())continue;let K=M.join(O,J.name);try{let X=await this.loadPlugin(K,$);Q.push(X)}catch(X){q.push({path:K,error:X instanceof Error?X.message:String(X)})}}return{plugins:Q,errors:q}}}class f{static instances=new Map;plugins=new Map;loader=new j0;initialized=!1;workspaceRoot="";cliPluginDirs=[];enabledSettings={};sourcePolicy={...V0.pluginSourcePolicy};marketplaces={};constructor(O){this.workspaceRoot=O}static getInstance(O=b()){let $=L$.resolve(O),Q=f.instances.get($);if(!Q)Q=new f($),f.instances.set($,Q);return Q}static resetInstance(){f.instances.clear()}static getInitializedInstances(){return Array.from(f.instances.values()).filter((O)=>O.isInitialized())}async initialize(O,$=[]){this.workspaceRoot=O,this.cliPluginDirs=$,this.enabledSettings=await S0.getInstance().loadWorkspacePluginSettings(O),await this.refreshPolicyContext();let Q=[],q=[];for(let G of $)try{let L=await this.loader.loadPlugin(G,"cli");this.plugins.set(L.manifest.name,L),Q.push(L),z.info(`Loaded CLI plugin: ${L.manifest.name} from ${G}`)}catch(L){q.push({path:G,error:L instanceof Error?L.message:String(L)}),z.warn(`Failed to load CLI plugin from ${G}: ${L}`)}let Z=(await w.getInstance().getStatus(O)).state==="trusted",J=j0.getPluginDirs(O).filter((G)=>G.source!=="project"||Z),K=!1,X=async()=>{if(K)return;K=!0;let G=o0(),L=await G.listInstallationRecords();for(let Y of L)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 S=this.plugins.get(V.manifest.name);if(!S||S.source==="user")this.plugins.set(V.manifest.name,V),Q.push(V)}catch(V){q.push({path:Y.installPath,code:"IO_ERROR",error:V instanceof Error?V.message:String(V)})}};for(let{path:G,source:L}of J){if(L==="project")await X();let Y=await this.loader.discoverPluginsInDir(G,L);for(let V of Y.plugins){let S=this.plugins.get(V.manifest.name);if(!S||S.source!=="cli")this.plugins.set(V.manifest.name,V),Q.push(V)}q.push(...Y.errors)}await X(),this.applyEnabledSettings();for(let G of this.plugins.values()){if(G.status!=="error")continue;q.push({path:G.basePath,code:G.compatibilityIssues?.some((L)=>L.code==="source-policy")?"SOURCE_POLICY_BLOCKED":G.compatibilityIssues?.some((L)=>L.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`+(q.length>0?`, ${q.length} errors`:"")),{plugins:Array.from(this.plugins.values()),errors:q}}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 S0.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{r(this.sourcePolicy,O.installation?.source??{type:"local",path:O.basePath},this.marketplaces,`Plugin "${O.manifest.name}"`)}catch($){if(!($ instanceof y))throw $;O.status="error",O.error=$.message,O.compatibilityIssues=[{code:"source-policy",message:$.message}]}}D1(Array.from(this.plugins.values()))}async refreshPolicyContext(){this.sourcePolicy=await S0.getInstance().loadWorkspacePluginSourcePolicy(this.workspaceRoot),this.marketplaces=Object.fromEntries((await o0().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 q of Q.commands)if(q.namespacedName===O)return q}let $=[];for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let q of Q.commands)if(q.originalName===O)$.push(q)}if($.length===1)return $[0];return}findSkill(O){for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let q of Q.skills)if(q.namespacedName===O)return q}let $=[];for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let q of Q.skills)if(q.originalName===O)$.push(q)}if($.length===1)return $[0];return}findAgent(O){for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let q of Q.agents)if(q.namespacedName===O)return q}let $=[];for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let q of Q.agents)if(q.originalName===O)$.push(q)}if($.length===1)return $[0];return}hasCommandConflict(O){let $=0;for(let Q of this.plugins.values()){if(Q.status!=="active")continue;for(let q of Q.commands)if(q.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 q of Q.commands)if(q.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,q=0,Z=0;for(let J of this.plugins.values())if(J.status==="active")O++,Q+=J.commands.length,q+=J.skills.length,Z+=J.agents.length;else $++;return{total:this.plugins.size,active:O,inactive:$,commands:Q,skills:q,agents:Z}}formatPluginList(){if(this.getAll().length===0)return"没有已加载的插件。";let $=[],Q=this.getBySource();if(Q.cli.length>0){$.push("## CLI 指定的插件");for(let q of Q.cli){let Z=q.status==="inactive"?" (禁用)":"";$.push(`- **${q.manifest.name}** v${q.manifest.version}${Z}`),$.push(` ${q.manifest.description}`)}$.push("")}if(Q.project.length>0){$.push("## 项目级插件");for(let q of Q.project){let Z=q.status==="inactive"?" (禁用)":"";$.push(`- **${q.manifest.name}** v${q.manifest.version}${Z}`),$.push(` ${q.manifest.description}`)}$.push("")}if(Q.user.length>0){$.push("## 用户级插件");for(let q of Q.user){let Z=q.status==="inactive"?" (禁用)":"";$.push(`- **${q.manifest.name}** v${q.manifest.version}${Z}`),$.push(` ${q.manifest.description}`)}}return $.join(`
|
|
701
|
+
`)}}function z0(O=b()){return f.getInstance(O)}var p=new Map,i1=Object.values(B0);function i0(O){let $={...O};for(let Q of i1)$[Q]=(O[Q]??[]).map((q)=>({...q,matcher:q.matcher?{...q.matcher}:void 0,hooks:q.hooks.map((Z)=>({...Z}))}));return $}class t0{commandRegistry;hookManager;skillRegistry;subagentRegistry;workspaceRoot;constructor(O=b()){this.workspaceRoot=Y$.resolve(O),this.commandRegistry=T.getInstance(this.workspaceRoot),this.hookManager=M0.getInstance(),this.skillRegistry=P({cwd:this.workspaceRoot}),this.subagentRegistry=i(this.workspaceRoot)}clearAllPluginResources(){this.commandRegistry.clearPluginCommands(),this.skillRegistry.clearPluginSkills(),this.subagentRegistry.clearPluginAgents();let O=p.get(this.workspaceRoot);if(O)this.hookManager.loadConfig(O,this.workspaceRoot),p.delete(this.workspaceRoot);z.debug("Cleared all plugin resources from subsystems")}async integrateAll(){let $=z0(this.workspaceRoot).getActive(),Q=[],q=[],Z=0,J=0,K=0,X=0,G=0;for(let L of $){let Y=this.integratePlugin(L);Q.push(Y),Z+=Y.commandsRegistered,J+=Y.skillsRegistered,K+=Y.agentsRegistered,X+=Y.mcpServersRegistered,G+=Y.lspServersRegistered,q.push(...Y.errors)}if(this.integrateHooks($),Z+J+K>0)z.info(`Plugin integration complete: ${Z} commands, ${J} skills, ${K} agents, ${X} MCP servers, ${G} LSP servers`);return{plugins:Q,totalCommands:Z,totalSkills:J,totalAgents:K,totalMcpServers:X,errors:q}}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 $=O.filter((J)=>J.hooks);if($.length===0){let J=p.get(this.workspaceRoot);if(J)this.hookManager.loadConfig(J,this.workspaceRoot),p.delete(this.workspaceRoot);return}let Q=i0(this.hookManager.getConfig(this.workspaceRoot));if(!p.has(this.workspaceRoot))p.set(this.workspaceRoot,i0(Q));let q=p.get(this.workspaceRoot)??Q,Z=i0(q);Z.enabled=!0;for(let J of i1){let K=q.enabled?[...q[J]??[]]:[],X=[];for(let G of $)for(let L of G.hooks?.[J]??[])X.push({...L,name:L.name?`plugin:${G.manifest.name}:${L.name}`:`plugin:${G.manifest.name}:${J}`,hooks:L.hooks.map((Y)=>({...Y,source:{kind:"plugin",pluginName:G.manifest.name,pluginSource:G.source,pluginRoot:G.basePath}}))});Z[J]=[...K,...X]}this.hookManager.loadConfig(Z,this.workspaceRoot)}integrateMcp(O){return Object.keys(O.mcpServers??{}).length}}async function a0(O=b()){return new t0(O).integrateAll()}function x0(O=b()){new t0(O).clearAllPluginResources()}import{createHash as H$}from"node:crypto";import*as D from"node:fs/promises";import F$ from"node:os";import C from"node:path";import V$ from"gray-matter";var I0=32,t1=24576,a1=16384,r1=131072,b0=4,e1=80,OO=256,QO=/^[a-z0-9][a-z0-9._-]{0,63}$/,U$=h("Agent");function r0(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 j$(O,$,Q){let q=typeof O==="string"?O.trim():"",Z=$.split(/\r?\n/).map((K)=>K.trim()).find(Boolean)?.replace(/^#+\s*/,"")??"",J=q||Z||Q;if(J.length>OO)throw Error(`Description exceeds ${OO} characters`);if(r0(J))throw Error("Description contains hidden control characters");return J}function S$(O,$){let Q=typeof O==="string"&&O.trim()?O.trim():$;if(Q.length>e1)throw Error(`Name exceeds ${e1} characters`);if(r0(Q))throw Error("Name contains hidden control characters");return Q}function z$(O){let Q=O.replace(/\.md$/i,"").split(C.sep);if(Q.length===0||Q.length>b0||Q.some((q)=>!QO.test(q)))throw Error(`Style path must use 1-${b0} lowercase safe segments`);return Q.join(":")}async function B$(O){let $;try{$=await D.lstat(O)}catch(J){if(J.code==="ENOENT")return[];throw J}if($.isSymbolicLink())throw Error(`Output style root cannot be a symlink: ${O}`);if(!$.isDirectory())return[];let Q=await D.realpath(O),q=[],Z=async(J,K)=>{if(K>b0)throw Error(`Output style directory exceeds depth ${b0}`);let X=await D.readdir(J,{withFileTypes:!0});X.sort((G,L)=>G.name.localeCompare(L.name));for(let G of X){let L=C.join(J,G.name);if(G.isSymbolicLink())throw Error(`Output style path cannot be a symlink: ${L}`);if(G.isDirectory()){await Z(L,K+1);continue}if(!G.isFile()||!G.name.toLowerCase().endsWith(".md"))continue;let Y=await D.realpath(L),V=C.relative(Q,Y);if(!V||V.startsWith("..")||C.isAbsolute(V))throw Error(`Output style path escapes its source root: ${L}`);if(q.push(Y),q.length>I0)throw Error(`Output style catalog exceeds ${I0} files`)}};return await Z(Q,1),q}async function M$(O,$,Q){let q=await D.lstat(Q);if(!q.isFile()||q.isSymbolicLink())throw Error("Output style must be a regular file");if(q.size>t1)throw Error(`Output style exceeds ${t1} bytes`);let Z=await D.readFile(Q,"utf8"),J=V$(Z),K=J.content.trim(),X=Buffer.byteLength(K);if(X===0)throw Error("Output style prompt must not be empty");if(X>a1)throw Error(`Output style prompt exceeds ${a1} bytes`);if(r0(K))throw Error("Output style prompt contains hidden control characters");let G=C.relative($,Q),L=z$(G);return{id:`${O.idPrefix}:${L}`,name:S$(J.data.name,L),description:j$(J.data.description,K,`Custom ${L} communication style`),source:O.source,contentSha256:H$("sha256").update(K,"utf8").digest("hex"),prompt:K}}async function x$(O,$){let Q=await B$(O.directory);if(Q.length===0)return;let q=await D.realpath(O.directory);for(let Z of Q)try{let J=await M$(O,q,Z);$.set(J.id,J)}catch(J){U$.warn(`[CommunicationStyles] Ignoring ${O.source} style: ${J instanceof Error?J.message:String(J)}`)}}function I$(O,$,Q,q){let Z=[{directory:C.join(q,".claude","output-styles"),source:"user",idPrefix:"user"},{directory:C.join(q,".blade","output-styles"),source:"user",idPrefix:"user"}];if($)Z.push({directory:C.join(O,".claude","output-styles"),source:"project",idPrefix:"project"},{directory:C.join(O,".blade","output-styles"),source:"project",idPrefix:"project"});for(let J of Q){if(J.status!=="active"||!QO.test(J.manifest.name))continue;Z.push({directory:C.join(J.basePath,"output-styles"),source:"plugin",idPrefix:`plugin:${J.manifest.name}`})}return Z}async function e0(O,$){let Q=new Map;for(let Z of I$(C.resolve(O),$.projectTrusted,$.plugins??[],$.homeDirectory??F$.homedir()))await x$(Z,Q);let q=0;for(let Z of Q.values())q+=Buffer.byteLength(Z.prompt??"");if(Q.size>I0)throw Error(`Output style catalog exceeds ${I0} styles`);if(q>r1)throw Error(`Output style catalog exceeds ${r1} bytes`);return new $O([...Q.values()])}import{createHash as b$}from"node:crypto";import{existsSync as A0,realpathSync as A$}from"node:fs";import*as m from"node:fs/promises";import B from"node:path";import _$ from"fast-glob";import w$ from"gray-matter";import XO from"picomatch";var qO=128,ZO=32768,JO=262144,T$=49152,C$=32768,D$=24,KO=16,N$=256,R$=h("Agent"),y$=["**/CLAUDE.md","**/.claude/CLAUDE.md","**/CLAUDE.local.md","**/AGENTS.md","**/AGENTS.override.md","**/BLADE.md","**/.claude/rules/**/*.md","**/.blade/rules/**/*.md"],v$=["**/.git/**","**/node_modules/**","**/.venv/**","**/dist/**","**/build/**","**/coverage/**","**/target/**"];function _0(O){return b$("sha256").update(O,"utf8").digest("hex")}function LO(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 q1(O){return O.split(B.sep).join("/")}function O1(O){let $=B.resolve(O),Q=[];while(!0)try{return B.join(A$($),...Q.reverse())}catch(q){if(q.code!=="ENOENT")return B.resolve(O);let Z=B.dirname($);if(Z===$)return B.resolve(O);Q.push(B.basename($)),$=Z}}function E$(O){let $=B.resolve(O),Q;while(!0){if(A0(B.join($,".git")))return $;if(!Q&&(A0(B.join($,".blade"))||A0(B.join($,".claude"))||A0(B.join($,"package.json"))))Q=$;let q=B.dirname($);if(q===$)return Q??B.resolve(O);$=q}}function Z1(O){return Boolean(O)&&O!==".."&&!O.startsWith("../")}function $1(O,$){return O===""||$===O||$.startsWith(`${O}/`)}function GO(O){return O.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}function f$(O){let $=typeof O==="string"?O.split(/[,\n]/u):Array.isArray(O)?O:[],Q=[...new Set($.filter((q)=>typeof q==="string").map((q)=>q.trim().replaceAll("\\","/")).filter(Boolean))];if(Q.length===0||Q.every((q)=>q==="**"))return;if(Q.length>KO)throw Error(`paths exceeds ${KO} patterns`);for(let q of Q){if(q.length>N$||B.posix.isAbsolute(q)||q.split("/").includes("..")||LO(q))throw Error(`Unsafe project rule path pattern: ${q.slice(0,80)}`);XO(q,{dot:!0})}return Q}function h$(O){if(O.endsWith("/CLAUDE.local.md")||O==="CLAUDE.local.md")return{source:"local",kind:"instruction",scopeDirectory:B.posix.dirname(O).replace(/^\.$/u,""),priority:90};for(let q of[".claude/rules/",".blade/rules/"]){let Z=O.indexOf(q);if(Z>=0)return{source:"project",kind:"rule",scopeDirectory:O.slice(0,Z).replace(/\/$/u,""),priority:q.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 $=B.posix.basename(O),Q=$==="CLAUDE.md"?20:$==="AGENTS.md"?40:$==="AGENTS.override.md"?50:60;return{source:"project",kind:"instruction",scopeDirectory:B.posix.dirname(O).replace(/^\.$/u,""),priority:Q}}function Q1(O,$){let Q=O.scopeDirectory?O.scopeDirectory.split("/").length:0,q=$.scopeDirectory?$.scopeDirectory.split("/").length:0;return Q-q||O.priority-$.priority||O.relativePath.localeCompare($.relativePath)}function k$(O){return{id:O.id,relativePath:O.relativePath,source:O.source,contentSha256:O.contentSha256}}function $0(O,$,Q){let q=O.map((K)=>{let X=K.conditional?' conditional="true"':"";return`<instruction-file path="${GO(K.relativePath)}" source="${K.source}" sha256="${K.contentSha256}"${X}>
|
|
717
702
|
${K.content}
|
|
718
703
|
</instruction-file>`}),Z=Q==="contextual-project-instructions"&&$.length>0?` trigger-paths="${GO($.join(","))}"`:"",J=q.length>0?`<${Q}${Z}>
|
|
719
704
|
${q.join(`
|
|
720
705
|
|
|
721
706
|
`)}
|
|
722
|
-
</${Q}>`:"";return{content:J,files:[...O],references:O.map(
|
|
723
|
-
`))}}function WO(O,$){let Q=$,q=[];for(let Z=O.length-1;Z>=0;Z-=1){let J=O[Z];if(!J)continue;let K=Buffer.byteLength(J.content,"utf8");if(K>Q)continue;q.push(J),Q-=K}return q.reverse()}class
|
|
724
|
-
`))}static empty(O){return new
|
|
725
|
-
export{
|
|
707
|
+
</${Q}>`:"";return{content:J,files:[...O],references:O.map(k$),triggerPaths:[...$],contentBytes:Buffer.byteLength(J,"utf8"),provenanceSha256:_0(O.map((K)=>`${K.id}:${K.contentSha256}`).join(`
|
|
708
|
+
`))}}function WO(O,$){let Q=$,q=[];for(let Z=O.length-1;Z>=0;Z-=1){let J=O[Z];if(!J)continue;let K=Buffer.byteLength(J.content,"utf8");if(K>Q)continue;q.push(J),Q-=K}return q.reverse()}class d{projectRoot;catalogSha256;definitions;byId;constructor(O,$=[]){this.projectRoot=O;this.projectRoot=O1(O),this.definitions=Object.freeze([...$].sort(Q1).map((Q)=>Object.freeze({...Q}))),this.byId=new Map(this.definitions.map((Q)=>[Q.id,Q])),this.catalogSha256=_0(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,$=T$){if(this.definitions.length===0)return $0([],[],"project-instructions");let Q=this.relativeSourcePath(O),q=this.definitions.filter((Z)=>!Z.conditional&&$1(Z.scopeDirectory,Q));return $0(WO(q,$),[],"project-instructions")}contextualRules(O,$,Q,q=C$){if(this.definitions.length===0)return $0([],[],"contextual-project-instructions");let Z=this.relativeSourcePath(O),J=[...new Set($.map((G)=>q1(B.relative(this.projectRoot,O1(G)))).filter(Z1))].sort(),K=new Map;for(let G of J)for(let L of this.definitions){if(Q.has(L.id))continue;if(!$1(L.scopeDirectory,G))continue;if(L.conditional){let Y=B.posix.relative(L.scopeDirectory||".",G);if(!L.patterns?.some((V)=>XO(V,{dot:!0})(Y)))continue}else if($1(L.scopeDirectory,Z))continue;K.set(L.id,L)}let X=WO([...K.values()].sort(Q1),q);return $0(X,J,"contextual-project-instructions")}hydrate(O){let $=O.map((Q)=>{let q=this.byId.get(Q.id);if(!q||q.contentSha256!==Q.contentSha256||q.relativePath!==Q.relativePath||q.source!==Q.source)throw Error(`Project rule provenance mismatch: ${Q.relativePath}`);return q});return $0([...new Map($.map((Q)=>[Q.id,Q])).values()].sort(Q1),[],"contextual-project-instructions")}relativeSourcePath(O){let $=q1(B.relative(this.projectRoot,O1(O)));if($&&!Z1($))throw Error("Project instruction source is outside the catalog root");return $}}async function P$(O,$){let Q=await m.lstat($);if(!Q.isFile()||Q.isSymbolicLink())throw Error("Project rule must be a regular file");if(Q.size>ZO)throw Error(`Project rule exceeds ${ZO} bytes`);let q=await m.realpath($),Z=q1(B.relative(O,q));if(!Z1(Z))throw Error("Project rule escapes its repository root");let J=await m.readFile(q,"utf8");if(LO(J))throw Error("Project rule contains hidden control characters");let K=w$(J),X=K.content.trim();if(!X)throw Error("Project rule content must not be empty");let G=f$(K.data.paths),L=h$(Z),Y=_0(JSON.stringify({relativePath:Z,patterns:G??[],content:X}));return{id:`${L.source}:${_0(Z).slice(0,20)}`,relativePath:Z,source:L.source,kind:L.kind,scopeDirectory:L.scopeDirectory,priority:L.priority,conditional:Boolean(G),...G?{patterns:G}:{},content:X,contentSha256:Y}}async function YO(O,$){let Q=E$(O);if(!$.projectTrusted)return d.empty(Q);let q=await m.realpath(Q),Z=_$.stream([...y$],{cwd:q,absolute:!0,dot:!0,deep:D$,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:[...v$]}),J=[];for await(let L of Z)if(J.push(L.toString()),J.length>qO)throw Error(`Project rule catalog exceeds ${qO} files`);J.sort();let K=new Set(J.filter((L)=>B.basename(L)==="AGENTS.override.md").map((L)=>B.dirname(L))),X=[],G=0;for(let L of J){if(B.basename(L)==="AGENTS.md"&&K.has(B.dirname(L)))continue;try{let Y=await P$(q,L);if(G+=Buffer.byteLength(Y.content,"utf8"),G>JO)throw Error(`Project rule catalog exceeds ${JO} bytes`);X.push(Y)}catch(Y){R$.warn(`[ProjectRules] Ignoring rule: ${Y instanceof Error?Y.message:String(Y)}`)}}return new d(q,X)}var Q0=new Map,FO=[];async function p$(O){let $=await w.getInstance().getStatus(O.workspaceRoot);O.communicationStyles=await e0(O.workspaceRoot,{projectTrusted:$.state==="trusted",plugins:O.plugins.getActive()})}function d$(O){let $={...O};for(let Q of Object.values(B0))$[Q]=(O[Q]??[]).map((q)=>({...q,matcher:q.matcher?{...q.matcher}:void 0,hooks:q.hooks.map((Z)=>({...Z}))}));return $}function f2(O){FO=[...new Set(O.map(($)=>J1.resolve($)))]}async function h2(O,$={}){let Q=J1.resolve(O),q=Q0.get(Q);if(!q)q=(async()=>{let J=await w.getInstance().getStatus(Q),K=i(Q),X=P({cwd:Q}),G=T.getInstance(Q),L=z0(Q);if(K.getAllNames().length===0)K.loadFromStandardLocations(J.state==="trusted");await Promise.all([X.initialize(),G.isInitialized()?void 0:G.initialize(Q),L.isInitialized()?void 0:L.initialize(Q,[...$.cliPluginDirs??FO])]),x0(Q),await a0(Q);let Y=await e0(Q,{projectTrusted:J.state==="trusted",plugins:L.getActive()}),V=await YO(Q,{projectTrusted:J.state==="trusted"});return{workspaceRoot:Q,subagents:K,skills:X,commands:G,plugins:L,communicationStyles:Y,projectRules:V}})().catch((J)=>{throw Q0.delete(Q),J}),Q0.set(Q,q);let Z=await q;if($.reconcilePlugins)x0(Q),await a0(Q),await p$(Z);return Z}function k2(O){let $="projectRoot"in O?O.projectRoot:O.workspaceRoot;return{projectRoot:J1.resolve($),subagents:O.subagents.snapshot(),skills:O.skills.snapshot(),commands:O.commands.snapshot(),communicationStyles:O.communicationStyles?.snapshot()??HO.snapshot(),projectRules:O.projectRules?.snapshot()??d.empty($),hooks:d$("hooks"in O&&O.hooks?O.hooks:M0.getInstance().getConfig($))}}function P2(){for(let O of Q0.keys())x0(O);Q0.clear(),v.resetInstances(),k.resetInstance(),T.resetInstance(),f.resetInstance()}
|
|
710
|
+
export{u$ as Dd,c$ as Ed,W1 as Fd,i$ as Gd,t$ as Hd,i as Id,H4 as Jd,U1 as Kd,P as Ld,DO as Md,T as Nd,o0 as Od,j0 as Pd,f as Qd,z0 as Rd,a0 as Sd,x0 as Td,d as Ud,p$ as Vd,f2 as Wd,h2 as Xd,k2 as Yd,P2 as Zd};
|