@uncarved/jade 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +187 -2
  3. package/bin/jade.js +20 -0
  4. package/dist/commands.d.ts +30 -0
  5. package/dist/commands.js +106 -0
  6. package/dist/commands.js.map +1 -0
  7. package/dist/config.d.ts +34 -0
  8. package/dist/config.js +130 -0
  9. package/dist/config.js.map +1 -0
  10. package/dist/context.d.ts +17 -0
  11. package/dist/context.js +53 -0
  12. package/dist/context.js.map +1 -0
  13. package/dist/distro.d.ts +93 -0
  14. package/dist/distro.js +277 -0
  15. package/dist/distro.js.map +1 -0
  16. package/dist/history.d.ts +10 -0
  17. package/dist/history.js +47 -0
  18. package/dist/history.js.map +1 -0
  19. package/dist/index.d.ts +26 -0
  20. package/dist/index.js +27 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/main.d.ts +2 -0
  23. package/dist/main.js +1124 -0
  24. package/dist/main.js.map +1 -0
  25. package/dist/mcp.d.ts +114 -0
  26. package/dist/mcp.js +640 -0
  27. package/dist/mcp.js.map +1 -0
  28. package/dist/memory.d.ts +19 -0
  29. package/dist/memory.js +129 -0
  30. package/dist/memory.js.map +1 -0
  31. package/dist/mentions.d.ts +35 -0
  32. package/dist/mentions.js +130 -0
  33. package/dist/mentions.js.map +1 -0
  34. package/dist/plugin-cli.d.ts +16 -0
  35. package/dist/plugin-cli.js +251 -0
  36. package/dist/plugin-cli.js.map +1 -0
  37. package/dist/plugins/budget.d.ts +9 -0
  38. package/dist/plugins/budget.js +30 -0
  39. package/dist/plugins/budget.js.map +1 -0
  40. package/dist/plugins/builtins.d.ts +10 -0
  41. package/dist/plugins/builtins.js +22 -0
  42. package/dist/plugins/builtins.js.map +1 -0
  43. package/dist/plugins/checks.d.ts +70 -0
  44. package/dist/plugins/checks.js +335 -0
  45. package/dist/plugins/checks.js.map +1 -0
  46. package/dist/plugins/compact.d.ts +26 -0
  47. package/dist/plugins/compact.js +216 -0
  48. package/dist/plugins/compact.js.map +1 -0
  49. package/dist/plugins/core.d.ts +42 -0
  50. package/dist/plugins/core.js +190 -0
  51. package/dist/plugins/core.js.map +1 -0
  52. package/dist/plugins/install.d.ts +68 -0
  53. package/dist/plugins/install.js +377 -0
  54. package/dist/plugins/install.js.map +1 -0
  55. package/dist/plugins/loader.d.ts +182 -0
  56. package/dist/plugins/loader.js +253 -0
  57. package/dist/plugins/loader.js.map +1 -0
  58. package/dist/plugins/policy.d.ts +64 -0
  59. package/dist/plugins/policy.js +269 -0
  60. package/dist/plugins/policy.js.map +1 -0
  61. package/dist/plugins/prompts.d.ts +28 -0
  62. package/dist/plugins/prompts.js +169 -0
  63. package/dist/plugins/prompts.js.map +1 -0
  64. package/dist/plugins/repeats.d.ts +9 -0
  65. package/dist/plugins/repeats.js +55 -0
  66. package/dist/plugins/repeats.js.map +1 -0
  67. package/dist/plugins/schema.d.ts +2 -0
  68. package/dist/plugins/schema.js +64 -0
  69. package/dist/plugins/schema.js.map +1 -0
  70. package/dist/provider.d.ts +52 -0
  71. package/dist/provider.js +187 -0
  72. package/dist/provider.js.map +1 -0
  73. package/dist/sessions.d.ts +13 -0
  74. package/dist/sessions.js +40 -0
  75. package/dist/sessions.js.map +1 -0
  76. package/dist/skills.d.ts +37 -0
  77. package/dist/skills.js +179 -0
  78. package/dist/skills.js.map +1 -0
  79. package/dist/sys.d.ts +44 -0
  80. package/dist/sys.js +115 -0
  81. package/dist/sys.js.map +1 -0
  82. package/dist/tools/checkpoint.d.ts +43 -0
  83. package/dist/tools/checkpoint.js +144 -0
  84. package/dist/tools/checkpoint.js.map +1 -0
  85. package/dist/tools/fs.d.ts +35 -0
  86. package/dist/tools/fs.js +417 -0
  87. package/dist/tools/fs.js.map +1 -0
  88. package/dist/tools/grep.d.ts +6 -0
  89. package/dist/tools/grep.js +243 -0
  90. package/dist/tools/grep.js.map +1 -0
  91. package/dist/tools/shell.d.ts +49 -0
  92. package/dist/tools/shell.js +295 -0
  93. package/dist/tools/shell.js.map +1 -0
  94. package/dist/tools/task.d.ts +31 -0
  95. package/dist/tools/task.js +86 -0
  96. package/dist/tools/task.js.map +1 -0
  97. package/dist/tools/todo.d.ts +10 -0
  98. package/dist/tools/todo.js +55 -0
  99. package/dist/tools/todo.js.map +1 -0
  100. package/dist/tools/web.d.ts +23 -0
  101. package/dist/tools/web.js +426 -0
  102. package/dist/tools/web.js.map +1 -0
  103. package/dist/ui/configure.d.ts +20 -0
  104. package/dist/ui/configure.js +285 -0
  105. package/dist/ui/configure.js.map +1 -0
  106. package/dist/ui/diff.d.ts +20 -0
  107. package/dist/ui/diff.js +142 -0
  108. package/dist/ui/diff.js.map +1 -0
  109. package/dist/ui/editor.d.ts +33 -0
  110. package/dist/ui/editor.js +128 -0
  111. package/dist/ui/editor.js.map +1 -0
  112. package/dist/ui/render.d.ts +13 -0
  113. package/dist/ui/render.js +84 -0
  114. package/dist/ui/render.js.map +1 -0
  115. package/dist/ui/screen.d.ts +90 -0
  116. package/dist/ui/screen.js +105 -0
  117. package/dist/ui/screen.js.map +1 -0
  118. package/dist/ui/transcript.d.ts +33 -0
  119. package/dist/ui/transcript.js +336 -0
  120. package/dist/ui/transcript.js.map +1 -0
  121. package/dist/ui/tui.d.ts +28 -0
  122. package/dist/ui/tui.js +884 -0
  123. package/dist/ui/tui.js.map +1 -0
  124. package/package.json +59 -4
  125. package/src/commands.ts +120 -0
  126. package/src/config.ts +146 -0
  127. package/src/context.ts +64 -0
  128. package/src/distro.ts +358 -0
  129. package/src/history.ts +55 -0
  130. package/src/index.ts +26 -0
  131. package/src/main.ts +1180 -0
  132. package/src/mcp.ts +693 -0
  133. package/src/memory.ts +135 -0
  134. package/src/mentions.ts +135 -0
  135. package/src/plugin-cli.ts +239 -0
  136. package/src/plugins/budget.ts +37 -0
  137. package/src/plugins/builtins.ts +31 -0
  138. package/src/plugins/checks.ts +390 -0
  139. package/src/plugins/compact.ts +257 -0
  140. package/src/plugins/core.ts +217 -0
  141. package/src/plugins/install.ts +429 -0
  142. package/src/plugins/loader.ts +386 -0
  143. package/src/plugins/policy.ts +304 -0
  144. package/src/plugins/prompts.ts +200 -0
  145. package/src/plugins/repeats.ts +62 -0
  146. package/src/plugins/schema.ts +67 -0
  147. package/src/provider.ts +208 -0
  148. package/src/sessions.ts +48 -0
  149. package/src/skills.ts +197 -0
  150. package/src/sys.ts +133 -0
  151. package/src/tools/checkpoint.ts +164 -0
  152. package/src/tools/fs.ts +432 -0
  153. package/src/tools/grep.ts +268 -0
  154. package/src/tools/shell.ts +339 -0
  155. package/src/tools/task.ts +105 -0
  156. package/src/tools/todo.ts +67 -0
  157. package/src/tools/web.ts +451 -0
  158. package/src/ui/configure.ts +310 -0
  159. package/src/ui/diff.ts +136 -0
  160. package/src/ui/editor.ts +136 -0
  161. package/src/ui/render.ts +74 -0
  162. package/src/ui/screen.ts +164 -0
  163. package/src/ui/transcript.ts +345 -0
  164. package/src/ui/tui.tsx +1374 -0
@@ -0,0 +1,386 @@
1
+ // 第三方插件的发现与加载。
2
+ //
3
+ // 插件放在 $JADE_HOME/plugins/<name>/(用户层)和 .jade/plugins/<name>/(项目层,从仓库根目录到工作目录逐级查找)。
4
+ // 一个目录就是一个插件,两种形式:
5
+ // - 进程内:TypeScript / JavaScript 模块,默认导出插件对象,或者返回插件对象的工厂函数(每个会话调用一次);
6
+ // - 进程外:plugin.json 里写了 command,jade 启动这个进程,经 stdio 用 JSON-RPC 通信(@uncarved/plugin-stdio),
7
+ // 可以用任何语言编写,只能提供 hook。
8
+ // 两种形式之外(或者没有代码时),插件目录还可以带上内容:skills/、commands/、mcp.json(或 .mcp.json),
9
+ // 和 jade 自己的 skills、自定义命令、MCP 配置格式相同。也认 Claude Code 插件的 .claude-plugin/plugin.json。
10
+ // 项目层插件随仓库分发,首次加载和内容变化后要用户确认(宪法 7.1);用户层插件是用户自己装的,不再确认。
11
+ // 只带内容的项目层插件不执行代码,不用确认(skills 和命令是给模型的文字,MCP 服务另有确认)。
12
+
13
+ import { readFileSync } from "node:fs";
14
+ import { readdir, readFile, stat } from "node:fs/promises";
15
+ import type { Choice } from "../ui/screen.ts";
16
+ import path from "node:path";
17
+ import { pathToFileURL } from "node:url";
18
+ import { spawnPlugin, type StdioPlugin } from "@uncarved/plugin-stdio";
19
+ import { definePlugin, loadProjectPluginFactory, type Awaitable, type Plugin, type TrustStore } from "uncarved";
20
+ import { projectDirs } from "../commands.ts";
21
+ import type { RunCommand } from "../tools/shell.ts";
22
+
23
+ export const JADE_VERSION: string = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
24
+
25
+ export type PluginLayer = "user" | "project";
26
+
27
+ /** jade 创建插件实例时传给工厂函数的参数 */
28
+ export interface JadePluginContext {
29
+ /** jade 的版本 */
30
+ jade: string;
31
+ /** 工作目录(已解析符号链接) */
32
+ cwd: string;
33
+ /** 仓库根目录;不在 git 仓库里时等于 cwd */
34
+ root: string;
35
+ /** jade 的数据目录($JADE_HOME) */
36
+ home: string;
37
+ /** 插件自己的目录 */
38
+ dir: string;
39
+ layer: PluginLayer;
40
+ /** 同 uncarved 的 definePlugin:补上 kernel 和 hooks 用到的 needs。项目层插件通常 import 不到 uncarved,用这个 */
41
+ definePlugin: <T extends JadePluginDraft>(draft: T) => T & JadePlugin;
42
+ /** 用 jade 的 shell 执行命令,超时或中断时连同子进程一起结束;找不到 shell 时没有 */
43
+ run?: RunCommand;
44
+ }
45
+
46
+ /** 斜杠命令和用户交互用的界面。非交互运行(-p)时 select / input 直接返回 undefined */
47
+ export interface CommandUI {
48
+ readonly interactive: boolean;
49
+ /** 输出一段文字(可以带 ANSI 颜色) */
50
+ log(text: string): void;
51
+ /** 让用户从几项里选一项;取消时返回 undefined */
52
+ select<T>(title: string, choices: Choice<T>[], opts?: { body?: string }): Promise<T | undefined>;
53
+ /** 让用户输入一行;取消时返回 undefined */
54
+ input(title: string, opts?: { initial?: string; placeholder?: string }): Promise<string | undefined>;
55
+ }
56
+
57
+ export interface PluginCommandContext {
58
+ sessionId: string;
59
+ cwd: string;
60
+ /** 用户按 esc 或退出时中断 */
61
+ signal: AbortSignal;
62
+ /** 当前会话的派生数据(各插件用 ctx.record 写入的) */
63
+ derived: Readonly<Record<string, unknown>>;
64
+ ui: CommandUI;
65
+ /** 附在用户下一条消息前面告诉模型的话,例如"用户删掉了某条记忆" */
66
+ note(text: string): void;
67
+ }
68
+
69
+ /** 字符串:显示给用户;{ prompt }:作为用户消息发给模型;不返回:什么也不做 */
70
+ export type PluginCommandResult = string | { prompt: string } | void | undefined;
71
+
72
+ /** 插件提供的斜杠命令 */
73
+ export interface PluginCommand {
74
+ name: string;
75
+ description?: string;
76
+ /** 参数提示,例如 "<file>" */
77
+ args?: string;
78
+ /**
79
+ * 不碰会话状态(只查看、只改插件自己的设置)的命令设为 true:模型工作时也立即执行,不排队。
80
+ * 这种命令返回 { prompt } 无效
81
+ */
82
+ instant?: boolean;
83
+ run(args: string, ctx: PluginCommandContext): Awaitable<PluginCommandResult>;
84
+ }
85
+
86
+ /** jade 的插件:内核的 Plugin,外加 jade 认识的扩展字段 */
87
+ export interface JadePlugin extends Plugin {
88
+ commands?: PluginCommand[];
89
+ /**
90
+ * 代替的内置插件的 id(例如 "jade/web"):被代替的内置插件不再加载,它的工具名可以由本插件提供。
91
+ * jade/policy 不能代替
92
+ */
93
+ replaces?: string[];
94
+ }
95
+
96
+ /** definePlugin 的输入:kernel、needs 可以省略 */
97
+ export type JadePluginDraft = Omit<JadePlugin, "kernel" | "needs"> & { kernel?: string; needs?: string[] };
98
+
99
+ export type JadePluginFactory = (ctx: JadePluginContext) => Awaitable<JadePlugin>;
100
+
101
+ /** 宿主(createJade)提供的那部分上下文 */
102
+ export type HostContext = Omit<JadePluginContext, "dir" | "layer">;
103
+
104
+ /** plugin.json,可以没有 */
105
+ export interface PluginJson {
106
+ /** jade plugin add 安装时用作目录名;/plugins 显示 */
107
+ name?: string;
108
+ version?: string;
109
+ description?: string;
110
+ /** 进程内插件的入口,默认依次找 index.ts、index.js、index.mjs */
111
+ entry?: string;
112
+ /** 进程外插件的启动命令;"./"、"../" 开头的相对于插件目录 */
113
+ command?: string;
114
+ args?: string[];
115
+ env?: Record<string, string>;
116
+ /** 默认 true:继承 jade 的全部环境变量 */
117
+ inheritEnv?: boolean;
118
+ /** 等插件回复 initialize 的时间,默认 10 秒 */
119
+ initTimeoutMs?: number;
120
+ }
121
+
122
+ /** 插件目录带的内容(都是绝对路径) */
123
+ export interface PluginBundle {
124
+ /** 每个目录里的 <name>/SKILL.md 是一个 skill */
125
+ skills: string[];
126
+ /** 每个目录里的 <name>.md 是一个斜杠命令 */
127
+ commands: string[];
128
+ /** MCP 服务:配置文件,或者 Claude Code 的 plugin.json 里直接写的 mcpServers */
129
+ mcp?: { file: string; servers?: unknown };
130
+ /** 认出来但 jade 还不支持的内容,例如 Claude Code 插件的 hooks、agents */
131
+ unsupported: string[];
132
+ }
133
+
134
+ /** 不执行代码就能知道的插件信息 */
135
+ export interface PluginInfo {
136
+ name?: string;
137
+ version?: string;
138
+ description?: string;
139
+ /** module:TS/JS 模块;process:plugin.json 写了 command;content:没有代码,只有 skills、命令、MCP 配置 */
140
+ kind: "module" | "process" | "content";
141
+ /** module 的入口文件(相对于插件目录) */
142
+ entry?: string;
143
+ json: PluginJson;
144
+ bundle: PluginBundle;
145
+ }
146
+
147
+ export interface FoundPlugin {
148
+ /** 目录名 */
149
+ name: string;
150
+ dir: string;
151
+ layer: PluginLayer;
152
+ }
153
+
154
+ export interface LoadedPlugin extends FoundPlugin {
155
+ kind: PluginInfo["kind"];
156
+ /** 模块入口(相对于插件目录),或者进程外插件的启动命令;只有内容的插件为空字符串 */
157
+ entry: string;
158
+ info: PluginInfo;
159
+ /** 创建一套实例,每个会话调用一次;进程外插件只有一个进程,每次返回同一个对象。只有内容的插件没有 */
160
+ create?(host: HostContext): Promise<JadePlugin>;
161
+ /** 进程外插件:结束进程 */
162
+ close?(): Promise<void>;
163
+ /** 进程外插件的状态:退出信息和最近的 stderr */
164
+ process?: { exited?: { code: number | null; signal: string | null }; stderr: string[] };
165
+ }
166
+
167
+ export interface ConfirmPlugin {
168
+ (request: { path: string; hash: string; files: string[]; command?: string }): Promise<boolean>;
169
+ }
170
+
171
+ export interface LoadOptions {
172
+ trust: TrustStore;
173
+ /** 项目层插件新出现或内容变化时请用户确认 */
174
+ confirm: ConfirmPlugin;
175
+ /** 进程外插件意外退出 */
176
+ onExit?(plugin: LoadedPlugin, exit: { code: number | null; signal: string | null }): void;
177
+ }
178
+
179
+ const ENTRIES = ["index.ts", "index.js", "index.mjs"];
180
+ const STDERR_LINES = 20;
181
+
182
+ /** 用户层在前;项目层从仓库根目录往下,同名目录近的覆盖远的 */
183
+ export async function discoverPlugins(opts: { home: string; root: string; cwd: string }): Promise<FoundPlugin[]> {
184
+ const out = new Map<string, FoundPlugin>();
185
+ await scan(path.join(opts.home, "plugins"), "user", out);
186
+ for (const d of projectDirs(opts.root, opts.cwd)) await scan(path.join(d, ".jade", "plugins"), "project", out);
187
+ return [...out.values()];
188
+ }
189
+
190
+ async function scan(root: string, layer: PluginLayer, out: Map<string, FoundPlugin>) {
191
+ let names: string[];
192
+ try {
193
+ names = (await readdir(root)).filter((n) => !n.startsWith(".")).sort();
194
+ } catch {
195
+ return;
196
+ }
197
+ for (const name of names) {
198
+ const dir = path.join(root, name);
199
+ // 跟随符号链接判断:用户层常把开发中的插件链接进来(项目层的链接会在计算哈希时被拒绝)
200
+ if (!(await stat(dir).catch(() => undefined))?.isDirectory()) continue;
201
+ out.set(`${layer}:${name}`, { name, dir, layer });
202
+ }
203
+ }
204
+
205
+ export async function loadPlugin(found: FoundPlugin, opts: LoadOptions): Promise<LoadedPlugin> {
206
+ const info = await inspectPlugin(found.dir);
207
+ if (info.kind === "process") return loadProcess(found, info, opts);
208
+ if (info.kind === "content") return { ...found, kind: "content", entry: "", info };
209
+
210
+ const entry = info.entry!;
211
+ const ctx = (host: HostContext): JadePluginContext => ({ ...host, dir: found.dir, layer: found.layer });
212
+
213
+ if (found.layer === "project") {
214
+ // 内核负责:先哈希整个目录、确认,再 import;检查 import 不越出插件目录
215
+ const make = await loadProjectPluginFactory(found.dir, { trust: opts.trust, confirm: opts.confirm, entry });
216
+ return { ...found, kind: "module", entry, info, create: async (host) => (await make(ctx(host))) as JadePlugin };
217
+ }
218
+
219
+ const file = path.resolve(found.dir, entry);
220
+ const exported = ((await import(pathToFileURL(file).href)) as { default?: unknown }).default;
221
+ if (typeof exported !== "function" && !isPlugin(exported)) throw new Error("default export is neither a plugin nor a function returning one");
222
+ return {
223
+ ...found,
224
+ kind: "module",
225
+ entry,
226
+ info,
227
+ async create(host) {
228
+ const made = typeof exported === "function" ? await (exported as JadePluginFactory)(ctx(host)) : exported;
229
+ if (!isPlugin(made)) throw new Error("plugin factory did not return a plugin");
230
+ return { ...made, layer: "user" };
231
+ },
232
+ };
233
+ }
234
+
235
+ async function loadProcess(found: FoundPlugin, info: PluginInfo, opts: LoadOptions): Promise<LoadedPlugin> {
236
+ const json = info.json;
237
+ // Windows 上相对路径的命令按 jade 的工作目录查找,而不是子进程的,所以先换成绝对路径
238
+ const command = /^\.\.?[\\/]/.test(json.command!) ? path.resolve(found.dir, json.command!) : json.command!;
239
+ const shown = [json.command!, ...(json.args ?? [])].join(" ");
240
+ const status: NonNullable<LoadedPlugin["process"]> = { stderr: [] };
241
+ let partial = "";
242
+ const proc: StdioPlugin = await spawnPlugin({
243
+ command,
244
+ args: json.args,
245
+ env: json.env,
246
+ inheritEnv: json.inheritEnv,
247
+ cwd: found.dir,
248
+ layer: found.layer,
249
+ trust: found.layer === "project" ? { trust: opts.trust, confirm: (r) => opts.confirm({ ...r, command: shown }), dir: found.dir } : undefined,
250
+ initTimeoutMs: json.initTimeoutMs,
251
+ onStderr: (text) => {
252
+ const lines = (partial + text).split(/\r?\n/);
253
+ partial = lines.pop() ?? "";
254
+ status.stderr.push(...lines);
255
+ status.stderr.splice(0, Math.max(0, status.stderr.length - STDERR_LINES));
256
+ },
257
+ });
258
+ const loaded: LoadedPlugin = {
259
+ ...found,
260
+ kind: "process",
261
+ entry: shown,
262
+ info,
263
+ create: async () => proc,
264
+ close: () => proc.close(),
265
+ process: status,
266
+ };
267
+ void proc.exited.then((exit) => {
268
+ status.exited = exit;
269
+ if (partial) status.stderr.push(partial);
270
+ try {
271
+ opts.onExit?.(loaded, exit);
272
+ } catch {
273
+ // 通知失败不能变成未处理的 rejection
274
+ }
275
+ });
276
+ return loaded;
277
+ }
278
+
279
+ /**
280
+ * 读插件目录,不执行其中的代码:jade plugin add 用它检查和命名,loadPlugin 用它决定怎么加载。
281
+ * 什么都提供不了的目录抛出错误
282
+ */
283
+ export async function inspectPlugin(dir: string): Promise<PluginInfo> {
284
+ const json = await readPluginJson(dir);
285
+ const claude = await readJsonObject(path.join(dir, ".claude-plugin", "plugin.json"));
286
+ const pkg = (await readJsonObject(path.join(dir, "package.json"), true)) ?? {};
287
+ const str = (v: unknown) => (typeof v === "string" && v ? v : undefined);
288
+ const inside = (rel: unknown, what: string): string => {
289
+ if (typeof rel !== "string" || !rel) throw new Error(`.claude-plugin/plugin.json: "${what}" must be a path`);
290
+ const full = path.resolve(dir, rel);
291
+ const r = path.relative(dir, full);
292
+ if (r === ".." || r.startsWith(`..${path.sep}`) || path.isAbsolute(r)) throw new Error(`.claude-plugin/plugin.json: "${what}" points outside the plugin`);
293
+ return full;
294
+ };
295
+ const paths = (v: unknown, what: string) => (v === undefined ? undefined : (Array.isArray(v) ? v : [v]).map((x) => inside(x, what)));
296
+ const isDir = async (p: string) => Boolean((await stat(p).catch(() => undefined))?.isDirectory());
297
+
298
+ const bundle: PluginBundle = { skills: [], commands: [], unsupported: [] };
299
+ for (const d of paths(claude?.skills, "skills") ?? [path.join(dir, "skills")]) if (await isDir(d)) bundle.skills.push(d);
300
+ for (const d of paths(claude?.commands, "commands") ?? [path.join(dir, "commands")]) if (await isDir(d)) bundle.commands.push(d);
301
+ const servers = claude?.mcpServers;
302
+ if (typeof servers === "object" && servers !== null && !Array.isArray(servers)) {
303
+ bundle.mcp = { file: path.join(dir, ".claude-plugin", "plugin.json"), servers };
304
+ } else if (servers !== undefined) {
305
+ bundle.mcp = { file: inside(servers, "mcpServers") };
306
+ } else {
307
+ const file = await firstFile(dir, ["mcp.json", ".mcp.json"]);
308
+ if (file) bundle.mcp = { file: path.join(dir, file) };
309
+ }
310
+ if (claude?.hooks !== undefined || (await firstFile(path.join(dir, "hooks"), ["hooks.json"]))) bundle.unsupported.push("hooks");
311
+ if (claude?.agents !== undefined || (await isDir(path.join(dir, "agents")))) bundle.unsupported.push("agents");
312
+
313
+ const meta = {
314
+ name: str(json.name) ?? str(claude?.name) ?? str(pkg.name)?.replace(/^@[^/]+\//, ""),
315
+ version: str(json.version) ?? str(claude?.version) ?? str(pkg.version),
316
+ description: str(json.description) ?? str(claude?.description) ?? str(pkg.description),
317
+ };
318
+ if (json.command !== undefined) return { ...meta, kind: "process", json, bundle };
319
+ const entry = json.entry ?? (await firstFile(dir, ENTRIES));
320
+ if (entry) return { ...meta, kind: "module", entry, json, bundle };
321
+ if (bundle.skills.length || bundle.commands.length || bundle.mcp) return { ...meta, kind: "content", json, bundle };
322
+ throw new Error(`no ${ENTRIES.join(", ")}, no plugin.json, and no skills/, commands/ or mcp.json`);
323
+ }
324
+
325
+ /** 读一个 JSON 对象;文件不存在时返回 undefined。lenient:格式不对也返回 undefined(package.json 不归插件规范管) */
326
+ async function readJsonObject(file: string, lenient = false): Promise<Record<string, unknown> | undefined> {
327
+ let text: string;
328
+ try {
329
+ text = await readFile(file, "utf8");
330
+ } catch {
331
+ return undefined;
332
+ }
333
+ try {
334
+ const v = JSON.parse(text);
335
+ if (typeof v === "object" && v !== null && !Array.isArray(v)) return v as Record<string, unknown>;
336
+ } catch (err) {
337
+ if (!lenient) throw new Error(`${path.basename(path.dirname(file))}/${path.basename(file)}: ${err instanceof Error ? err.message : String(err)}`);
338
+ return undefined;
339
+ }
340
+ if (!lenient) throw new Error(`${path.basename(path.dirname(file))}/${path.basename(file)}: must be an object`);
341
+ return undefined;
342
+ }
343
+
344
+ async function readPluginJson(dir: string): Promise<PluginJson> {
345
+ let text: string;
346
+ try {
347
+ text = await readFile(path.join(dir, "plugin.json"), "utf8");
348
+ } catch {
349
+ return {};
350
+ }
351
+ let json: PluginJson;
352
+ try {
353
+ json = JSON.parse(text) as PluginJson;
354
+ } catch (err) {
355
+ throw new Error(`plugin.json: ${err instanceof Error ? err.message : String(err)}`);
356
+ }
357
+ const strings = (v: unknown) => Array.isArray(v) && v.every((x) => typeof x === "string");
358
+ const problem =
359
+ typeof json !== "object" || json === null || Array.isArray(json)
360
+ ? "must be an object"
361
+ : json.entry !== undefined && typeof json.entry !== "string"
362
+ ? '"entry" must be a string'
363
+ : json.command !== undefined && (typeof json.command !== "string" || !json.command)
364
+ ? '"command" must be a non-empty string'
365
+ : json.args !== undefined && !strings(json.args)
366
+ ? '"args" must be an array of strings'
367
+ : json.env !== undefined && (typeof json.env !== "object" || json.env === null || !Object.values(json.env).every((v) => typeof v === "string"))
368
+ ? '"env" must map names to strings'
369
+ : json.entry !== undefined && json.command !== undefined
370
+ ? 'use either "entry" (in-process) or "command" (separate process), not both'
371
+ : undefined;
372
+ if (problem) throw new Error(`plugin.json: ${problem}`);
373
+ return json;
374
+ }
375
+
376
+ async function firstFile(dir: string, names: string[]): Promise<string | undefined> {
377
+ for (const n of names) if ((await stat(path.join(dir, n)).catch(() => undefined))?.isFile()) return n;
378
+ return undefined;
379
+ }
380
+
381
+ function isPlugin(v: unknown): v is JadePlugin {
382
+ return typeof v === "object" && v !== null && typeof (v as Plugin).id === "string";
383
+ }
384
+
385
+ /** 斜杠命令名:字母数字开头,之后可以有 - 和 _ */
386
+ export const COMMAND_NAME = /^[a-z0-9][a-z0-9_-]*$/i;