@uncarved/jade 0.0.0-stage → 0.1.1

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 (168) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +191 -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 +97 -0
  14. package/dist/distro.js +311 -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 +27 -0
  20. package/dist/index.js +28 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/main.d.ts +2 -0
  23. package/dist/main.js +1214 -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 +80 -0
  59. package/dist/plugins/policy.js +541 -0
  60. package/dist/plugins/policy.js.map +1 -0
  61. package/dist/plugins/prompts.d.ts +30 -0
  62. package/dist/plugins/prompts.js +182 -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 +90 -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 +111 -0
  71. package/dist/provider.js +326 -0
  72. package/dist/provider.js.map +1 -0
  73. package/dist/sessions.d.ts +22 -0
  74. package/dist/sessions.js +53 -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 +48 -0
  80. package/dist/sys.js +116 -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/screenshot.d.ts +15 -0
  92. package/dist/tools/screenshot.js +162 -0
  93. package/dist/tools/screenshot.js.map +1 -0
  94. package/dist/tools/shell.d.ts +55 -0
  95. package/dist/tools/shell.js +314 -0
  96. package/dist/tools/shell.js.map +1 -0
  97. package/dist/tools/task.d.ts +31 -0
  98. package/dist/tools/task.js +86 -0
  99. package/dist/tools/task.js.map +1 -0
  100. package/dist/tools/todo.d.ts +10 -0
  101. package/dist/tools/todo.js +55 -0
  102. package/dist/tools/todo.js.map +1 -0
  103. package/dist/tools/web.d.ts +23 -0
  104. package/dist/tools/web.js +426 -0
  105. package/dist/tools/web.js.map +1 -0
  106. package/dist/ui/configure.d.ts +20 -0
  107. package/dist/ui/configure.js +369 -0
  108. package/dist/ui/configure.js.map +1 -0
  109. package/dist/ui/diff.d.ts +20 -0
  110. package/dist/ui/diff.js +142 -0
  111. package/dist/ui/diff.js.map +1 -0
  112. package/dist/ui/editor.d.ts +33 -0
  113. package/dist/ui/editor.js +128 -0
  114. package/dist/ui/editor.js.map +1 -0
  115. package/dist/ui/render.d.ts +13 -0
  116. package/dist/ui/render.js +84 -0
  117. package/dist/ui/render.js.map +1 -0
  118. package/dist/ui/screen.d.ts +95 -0
  119. package/dist/ui/screen.js +105 -0
  120. package/dist/ui/screen.js.map +1 -0
  121. package/dist/ui/transcript.d.ts +33 -0
  122. package/dist/ui/transcript.js +372 -0
  123. package/dist/ui/transcript.js.map +1 -0
  124. package/dist/ui/tui.d.ts +45 -0
  125. package/dist/ui/tui.js +1107 -0
  126. package/dist/ui/tui.js.map +1 -0
  127. package/package.json +59 -4
  128. package/src/commands.ts +120 -0
  129. package/src/config.ts +146 -0
  130. package/src/context.ts +64 -0
  131. package/src/distro.ts +395 -0
  132. package/src/history.ts +55 -0
  133. package/src/index.ts +27 -0
  134. package/src/main.ts +1267 -0
  135. package/src/mcp.ts +693 -0
  136. package/src/memory.ts +135 -0
  137. package/src/mentions.ts +135 -0
  138. package/src/plugin-cli.ts +239 -0
  139. package/src/plugins/budget.ts +37 -0
  140. package/src/plugins/builtins.ts +31 -0
  141. package/src/plugins/checks.ts +390 -0
  142. package/src/plugins/compact.ts +257 -0
  143. package/src/plugins/core.ts +217 -0
  144. package/src/plugins/install.ts +429 -0
  145. package/src/plugins/loader.ts +386 -0
  146. package/src/plugins/policy.ts +578 -0
  147. package/src/plugins/prompts.ts +215 -0
  148. package/src/plugins/repeats.ts +96 -0
  149. package/src/plugins/schema.ts +67 -0
  150. package/src/provider.ts +363 -0
  151. package/src/sessions.ts +61 -0
  152. package/src/skills.ts +197 -0
  153. package/src/sys.ts +136 -0
  154. package/src/tools/checkpoint.ts +164 -0
  155. package/src/tools/fs.ts +432 -0
  156. package/src/tools/grep.ts +268 -0
  157. package/src/tools/screenshot.ts +171 -0
  158. package/src/tools/shell.ts +357 -0
  159. package/src/tools/task.ts +105 -0
  160. package/src/tools/todo.ts +67 -0
  161. package/src/tools/web.ts +451 -0
  162. package/src/ui/configure.ts +397 -0
  163. package/src/ui/diff.ts +136 -0
  164. package/src/ui/editor.ts +136 -0
  165. package/src/ui/render.ts +74 -0
  166. package/src/ui/screen.ts +166 -0
  167. package/src/ui/transcript.ts +377 -0
  168. package/src/ui/tui.tsx +1662 -0
@@ -0,0 +1,217 @@
1
+ // 内置插件里和界面有关的部分:/memory、/skills、/mcp、/checks、/compact 这些斜杠命令,
2
+ // 以及把一段系统提示词、一个"第几次回复"计数器挂到插件上的小工具。
3
+ // 命令用的是第三方插件同样的 PluginCommand 接口(ctx.ui 交互、ctx.note 告诉模型),停用插件时命令也一起消失。
4
+
5
+ import path from "node:path";
6
+ import type { HookSpec, SystemSegment, Trust } from "uncarved";
7
+ import type { Check, Checks } from "./checks.ts";
8
+ import type { Compactor } from "./compact.ts";
9
+ import type { JadePlugin, PluginCommand } from "./loader.ts";
10
+ import { MEMORY_SCOPES, type Memory, type MemoryScope } from "../memory.ts";
11
+ import { describeServer, type McpClient } from "../mcp.ts";
12
+ import type { Skill } from "../skills.ts";
13
+ import { display } from "../tools/fs.ts";
14
+ import { clip } from "../ui/render.ts";
15
+ import { bold, dim, green, red, yellow } from "../ui/screen.ts";
16
+
17
+ /** 给插件加一个 context.build hook,把这些段落接在已有的系统提示词后面 */
18
+ export function withSystem<T extends JadePlugin>(plugin: T, parts: { text: string; trust: Trust }[]): T {
19
+ if (parts.length === 0) return plugin;
20
+ const segments: SystemSegment[] = parts.map(({ text, trust }) => ({ text, trust, stability: "stable", origin: { by: "plugin", id: plugin.id } }));
21
+ return addHook(plugin, { kind: "transform", point: "context.build", fn: (req) => ({ ...req, system: [...req.system, ...segments] }) });
22
+ }
23
+
24
+ /** 每次请求模型前加一:工具据此判断两个调用是不是同一次回复里发出的 */
25
+ export function withCounter<T extends JadePlugin>(plugin: T, counter: { calls: number }): T {
26
+ return addHook(plugin, {
27
+ kind: "transform",
28
+ point: "model.before",
29
+ fn: () => {
30
+ counter.calls++;
31
+ },
32
+ });
33
+ }
34
+
35
+ function addHook<T extends JadePlugin>(plugin: T, hook: HookSpec): T {
36
+ const need = `${hook.kind}:${hook.point}`;
37
+ return { ...plugin, hooks: [...(plugin.hooks ?? []), hook], needs: [...new Set([...(plugin.needs ?? []), need])] };
38
+ }
39
+
40
+ // ---------- /memory ----------
41
+
42
+ export function memoryCommand(memory: Memory): PluginCommand {
43
+ return {
44
+ name: "memory",
45
+ args: "[text]",
46
+ description: "see and remove what jade remembers across sessions, or remember text",
47
+ instant: true,
48
+ async run(args, { ui, note }) {
49
+ let text = args.trim();
50
+ if (!text) {
51
+ const entries = (await Promise.all(MEMORY_SCOPES.map(async (scope) => (await memory.list(scope)).map((t) => ({ scope, text: t }))))).flat();
52
+ if (!ui.interactive) return entries.length ? entries.map((e) => `${e.scope}: ${e.text}`).join("\n") : "jade does not remember anything yet";
53
+ const choice = await ui.select<{ scope: MemoryScope; text: string } | "add">(
54
+ entries.length ? "Memory: choose an entry to remove it, or add one" : "jade does not remember anything yet",
55
+ [{ label: "Add a memory…", value: "add" as const }, ...entries.map((e) => ({ label: e.text, value: e, hint: e.scope }))],
56
+ { body: dim(`user (all projects): ${memory.files.user}\nproject: ${memory.files.project}`) },
57
+ );
58
+ if (!choice) return;
59
+ if (choice !== "add") {
60
+ const ok = await ui.select(
61
+ `Remove this ${choice.scope} memory?`,
62
+ [
63
+ { label: "No", value: false },
64
+ { label: "Yes, remove it", value: true },
65
+ ],
66
+ { body: choice.text },
67
+ );
68
+ if (!ok) return;
69
+ await memory.remove(choice.scope, choice.text);
70
+ note(`The user removed this ${choice.scope} memory, so stop following it: ${choice.text}`);
71
+ return green(`Removed from ${choice.scope} memory: ${choice.text}`);
72
+ }
73
+ text = (await ui.input("What should jade remember?", { placeholder: "e.g. Reply in Chinese; run tests with bun test" })) ?? "";
74
+ if (!text) return;
75
+ }
76
+ const scope = await ui.select<MemoryScope>("Remember it for", [
77
+ { label: "All projects", value: "user", hint: "user memory" },
78
+ { label: "This project only", value: "project", hint: "project memory" },
79
+ ]);
80
+ if (!scope) return;
81
+ const added = await memory.add(scope, text);
82
+ if (added) note(`The user saved a ${scope} memory; follow it from now on: ${text}`);
83
+ return added ? green(`Saved to ${scope} memory.`) : dim(`The ${scope} memory already has this.`);
84
+ },
85
+ };
86
+ }
87
+
88
+ // ---------- /skills ----------
89
+
90
+ export function skillsCommand(skills: Skill[], opts: { cwd: string; home: string }): PluginCommand {
91
+ return {
92
+ name: "skills",
93
+ description: "skills the agent can use",
94
+ instant: true,
95
+ run() {
96
+ if (skills.length === 0) {
97
+ return dim(`(no skills) put them in ${display(opts.cwd, path.join(opts.home, "skills"))}/<name>/SKILL.md or .jade/skills/<name>/SKILL.md`);
98
+ }
99
+ return skills
100
+ .map((sk) => {
101
+ const from = sk.plugin ? `plugin ${sk.plugin}` : sk.layer;
102
+ return `${bold(sk.name)} ${dim(`${from} · ${display(opts.cwd, sk.dir)}`)}\n ${clip(sk.description.replace(/\s+/g, " "), 300)}`;
103
+ })
104
+ .join("\n");
105
+ },
106
+ };
107
+ }
108
+
109
+ // ---------- /mcp ----------
110
+
111
+ export function mcpCommand(clients: McpClient[], opts: { cwd: string; home: string }): PluginCommand {
112
+ return {
113
+ name: "mcp",
114
+ args: "[reconnect <name>]",
115
+ description: "MCP servers: status and tools",
116
+ instant: true,
117
+ async run(args) {
118
+ const words = args.trim().split(/\s+/).filter(Boolean);
119
+ if (words[0] === "reconnect") {
120
+ const c = clients.find((x) => x.name === words[1]);
121
+ if (!c) return red(`usage: /mcp reconnect <name>; servers: ${clients.map((x) => x.name).join(", ") || "(none)"}`);
122
+ await c.close();
123
+ try {
124
+ await c.connect();
125
+ return green(`${c.name} connected, ${c.tools.length} tools`);
126
+ } catch (err) {
127
+ return red(`${c.name}: ${err instanceof Error ? err.message : String(err)}`);
128
+ }
129
+ }
130
+ if (clients.length === 0) {
131
+ return dim(`(no MCP servers) configure them in ${display(opts.cwd, path.join(opts.home, "mcp.json"))}, .mcp.json or .jade/mcp.json`);
132
+ }
133
+ const lines: string[] = [];
134
+ for (const c of clients) {
135
+ const state = c.status === "connected" ? green("connected") : c.status === "failed" ? red("failed") : yellow(c.status);
136
+ const info = c.serverInfo?.name ? ` · ${c.serverInfo.name}${c.serverInfo.version ? ` ${c.serverInfo.version}` : ""}` : "";
137
+ const from = c.entry.plugin ? `plugin ${c.entry.plugin}` : `${c.entry.layer} · ${display(opts.cwd, c.entry.file)}`;
138
+ lines.push(`${bold(c.name)} ${state} ${dim(`${from} · ${describeServer(c.entry.config)}${info}`)}`);
139
+ if (c.error) lines.push(red(` ${c.error}`));
140
+ if (c.tools.length) {
141
+ lines.push(` tools ${c.tools.map((t) => `${t.name}${t.annotations?.readOnlyHint ? dim(" (read)") : ""}`).join(", ")}`);
142
+ }
143
+ if (c.status === "failed" && c.stderr.length) lines.push(dim(c.stderr.map((l) => ` │ ${clip(l, 200)}`).join("\n")));
144
+ }
145
+ return lines.join("\n");
146
+ },
147
+ };
148
+ }
149
+
150
+ /** MCP 服务在初始化时给出的使用说明,放进系统提示词(来自外部,untrusted) */
151
+ export function mcpInstructions(clients: McpClient[]): { text: string; trust: Trust }[] {
152
+ return clients
153
+ .filter((c) => c.status === "connected" && c.instructions)
154
+ .map((c) => ({ text: `# Instructions from the MCP server "${c.name}" (about its mcp__${c.name}__* tools)\n\n${c.instructions}`, trust: "untrusted" as const }));
155
+ }
156
+
157
+ // ---------- /checks ----------
158
+
159
+ export interface ChecksCommandOptions {
160
+ cwd: string;
161
+ home: string;
162
+ /** 本会话改过的文件 */
163
+ changed(sessionId: string): Promise<string[]>;
164
+ /** 这条检查命令用户是否已经确认过 */
165
+ confirmed?(check: Check): Promise<boolean>;
166
+ /** 没有检查时的原因 */
167
+ unavailable?: string;
168
+ }
169
+
170
+ export function checksCommand(checks: Checks | undefined, opts: ChecksCommandOptions): PluginCommand {
171
+ return {
172
+ name: "checks",
173
+ args: "[on|off]",
174
+ description: "checks jade runs after the agent edits files (type checker, linter)",
175
+ instant: true,
176
+ async run(args, { sessionId }) {
177
+ if (!checks) return dim(opts.unavailable ?? "Edit-time checks are not available.");
178
+ const arg = args.trim();
179
+ if (arg === "on" || arg === "off") {
180
+ checks.enabled = arg === "on";
181
+ if (arg === "on") checks.reset();
182
+ return `checks: ${arg}`;
183
+ }
184
+ if (arg) return red("usage: /checks [on|off]");
185
+ const files = await opts.changed(sessionId);
186
+ const found = await checks.resolve(files);
187
+ const lines = [`Edit-time checks are ${checks.enabled ? "on" : "off"} in this session.`];
188
+ if (found.length > 0) {
189
+ lines.push("For the files changed in this session:");
190
+ for (const c of found) {
191
+ const pending = opts.confirmed && !(await opts.confirmed(c)) ? ", not confirmed yet" : "";
192
+ lines.push(` ${bold(c.name)} ${dim(`in ${display(opts.cwd, c.cwd) || "."}${pending}`)}\n ${dim(c.command)}`);
193
+ }
194
+ } else lines.push(dim(files.length ? "No checks apply to the files changed in this session." : "No files changed in this session yet."));
195
+ lines.push(
196
+ dim(
197
+ "Detected per file: TypeScript (nearest tsconfig.json + the project's typescript), Python (ruff), Go (go vet).\n" +
198
+ `Add your own in .jade/checks.json or ${path.join(opts.home, "checks.json")}; JADE_CHECKS=off turns them off.`,
199
+ ),
200
+ );
201
+ return lines.join("\n");
202
+ },
203
+ };
204
+ }
205
+
206
+ // ---------- /compact ----------
207
+
208
+ export function compactCommand(compact: Compactor): PluginCommand {
209
+ return {
210
+ name: "compact",
211
+ description: "compact the history before the next request",
212
+ run() {
213
+ compact.request();
214
+ return dim("History will be compacted before the next request.");
215
+ },
216
+ };
217
+ }
@@ -0,0 +1,429 @@
1
+ // 插件的安装、更新、卸载(jade plugin …)。
2
+ //
3
+ // 来源有三种:
4
+ // - git:https://…、git@…、github:user/repo、user/repo(本地没有这个路径时),可以用 #ref 指定分支、tag 或提交;
5
+ // - npm:包名(可以带 @版本)、npm:<任意 bun add 认识的写法>、本地的 .tgz;
6
+ // - 本地目录:复制过来;--link 时只建一个链接,方便开发插件。
7
+ // 先下载到插件目录里的 .staging-* 临时目录(以 . 开头,发现插件时会跳过),检查确实是插件、装好依赖之后再改名就位,
8
+ // 失败时不会留下装了一半的插件。安装记录在插件目录的 .installed.json 里,jade plugin update 按记录重新下载。
9
+ //
10
+ // 安装不执行插件的代码;插件的 package.json 有 dependencies 时安装依赖(Bun 下用 bun,Node 下用 npm,都不运行安装脚本)。
11
+
12
+ import { execFile } from "node:child_process";
13
+ import { randomBytes } from "node:crypto";
14
+ import { cp, lstat, mkdir, readdir, readFile, rename, rm, rmdir, stat, symlink, unlink, writeFile } from "node:fs/promises";
15
+ import path from "node:path";
16
+ import { inspectPlugin, type PluginInfo } from "./loader.ts";
17
+ import { npmCommand } from "../sys.ts";
18
+
19
+ export type SourceKind = "git" | "npm" | "local";
20
+
21
+ export interface PluginSource {
22
+ kind: SourceKind;
23
+ /** git:仓库地址;npm:交给 bun add 的写法;local:绝对路径 */
24
+ location: string;
25
+ /** git 的分支、tag 或提交 */
26
+ ref?: string;
27
+ }
28
+
29
+ export interface InstallRecord {
30
+ /** 用户写的来源(本地路径换成了绝对路径) */
31
+ source: string;
32
+ kind: SourceKind | "link";
33
+ /** 只安装来源里的这个子目录 */
34
+ subdir?: string;
35
+ /** git:安装的提交 */
36
+ commit?: string;
37
+ version?: string;
38
+ installedAt: string;
39
+ updatedAt?: string;
40
+ }
41
+
42
+ export interface InstallOptions {
43
+ /** 插件目录:$JADE_HOME/plugins 或 <仓库>/.jade/plugins */
44
+ pluginsDir: string;
45
+ /** 解析相对路径用 */
46
+ cwd: string;
47
+ /** 安装后的目录名,默认取插件声明的 name、包名或仓库名 */
48
+ name?: string;
49
+ subdir?: string;
50
+ /** 本地目录:建链接而不是复制 */
51
+ link?: boolean;
52
+ /** 已经有同名插件时替换它 */
53
+ force?: boolean;
54
+ /** 进度(正在下载、正在安装依赖) */
55
+ log?: (text: string) => void;
56
+ }
57
+
58
+ export interface Installed {
59
+ name: string;
60
+ dir: string;
61
+ record: InstallRecord;
62
+ info: PluginInfo;
63
+ }
64
+
65
+ /** 插件目录名 */
66
+ export const PLUGIN_NAME = /^[a-z0-9][a-z0-9._-]*$/;
67
+ const RECORDS = ".installed.json";
68
+
69
+ /** 识别来源的种类 */
70
+ export async function parseSource(spec: string, cwd: string): Promise<PluginSource> {
71
+ const s = spec.trim();
72
+ if (!s) throw new Error("no plugin source given");
73
+ if (s.startsWith("npm:")) return { kind: "npm", location: s.slice(4) };
74
+ const [base, ref] = splitRef(s);
75
+ if (/^github:/.test(base)) return { kind: "git", location: `https://github.com/${base.slice(7).replace(/\.git$/, "")}.git`, ref };
76
+ if (/^gitlab:/.test(base)) return { kind: "git", location: `https://gitlab.com/${base.slice(7).replace(/\.git$/, "")}.git`, ref };
77
+ if (/^git\+/.test(base)) return { kind: "git", location: base.slice(4), ref };
78
+ if (/^(git@|ssh:\/\/|git:\/\/)/.test(base)) return { kind: "git", location: base, ref };
79
+ if (/^https?:\/\//.test(base)) {
80
+ if (/\.(tgz|tar\.gz)$/.test(base)) return { kind: "npm", location: s };
81
+ return { kind: "git", location: base, ref };
82
+ }
83
+ const local = path.resolve(cwd, s.replace(/^~(?=$|[\\/])/, process.env.HOME ?? process.env.USERPROFILE ?? "~"));
84
+ const info = await stat(local).catch(() => undefined);
85
+ if (info?.isDirectory()) return { kind: "local", location: local };
86
+ if (info?.isFile()) {
87
+ if (/\.(tgz|tar\.gz)$/.test(local)) return { kind: "npm", location: local };
88
+ throw new Error(`${s} is a file; give a plugin directory, a .tgz package, a git URL or an npm package`);
89
+ }
90
+ // user/repo:本地没有这个路径时按 GitHub 仓库处理(npm 的包名不含 /,带作用域的以 @ 开头)
91
+ if (/^[\w.-]+\/[\w.-]+$/.test(base) && !s.startsWith(".")) {
92
+ return { kind: "git", location: `https://github.com/${base.replace(/\.git$/, "")}.git`, ref };
93
+ }
94
+ if (/^(\.|\/|[a-zA-Z]:[\\/])/.test(s)) throw new Error(`${s} does not exist`);
95
+ return { kind: "npm", location: s };
96
+ }
97
+
98
+ /** "url#ref" 拆成两部分 */
99
+ function splitRef(s: string): [string, string | undefined] {
100
+ const i = s.lastIndexOf("#");
101
+ return i > 0 ? [s.slice(0, i), s.slice(i + 1) || undefined] : [s, undefined];
102
+ }
103
+
104
+ export async function addPlugin(spec: string, opts: InstallOptions): Promise<Installed> {
105
+ const source = await parseSource(spec, opts.cwd);
106
+ await mkdir(opts.pluginsDir, { recursive: true });
107
+
108
+ if (opts.link) {
109
+ if (source.kind !== "local") throw new Error("--link only works with a local directory");
110
+ const dir = opts.subdir ? inSubdir(source.location, opts.subdir) : source.location;
111
+ const info = await inspectPlugin(dir);
112
+ const name = pickName(opts.name, info, dir);
113
+ const target = path.join(opts.pluginsDir, name);
114
+ await makeRoom(target, name, opts.force);
115
+ await symlink(dir, target, process.platform === "win32" ? "junction" : "dir");
116
+ const record: InstallRecord = { source: dir, kind: "link", installedAt: now(), ...(info.version ? { version: info.version } : {}) };
117
+ await saveRecord(opts.pluginsDir, name, record);
118
+ return { name, dir: target, record, info };
119
+ }
120
+
121
+ const staging = path.join(opts.pluginsDir, `.staging-${randomBytes(4).toString("hex")}`);
122
+ try {
123
+ const fetched = await fetchInto(source, staging, opts.subdir, opts.log);
124
+ const name = pickName(opts.name, fetched.info, opts.subdir ?? nameHint(source));
125
+ const target = path.join(opts.pluginsDir, name);
126
+ await makeRoom(target, name, opts.force);
127
+ await rename(fetched.dir, target);
128
+ const record: InstallRecord = {
129
+ source: source.kind === "local" ? source.location : spec.trim(),
130
+ kind: source.kind,
131
+ ...(opts.subdir ? { subdir: opts.subdir } : {}),
132
+ ...(fetched.commit ? { commit: fetched.commit } : {}),
133
+ ...(fetched.info.version ? { version: fetched.info.version } : {}),
134
+ installedAt: now(),
135
+ };
136
+ await saveRecord(opts.pluginsDir, name, record);
137
+ return { name, dir: target, record, info: fetched.info };
138
+ } finally {
139
+ await rm(staging, { recursive: true, force: true }).catch(() => {});
140
+ }
141
+ }
142
+
143
+ export interface UpdateResult {
144
+ name: string;
145
+ status: "updated" | "current" | "linked" | "unmanaged" | "failed";
146
+ from?: string;
147
+ to?: string;
148
+ error?: string;
149
+ }
150
+
151
+ /** 按安装记录重新下载;没给名字时更新这个插件目录里所有用 jade plugin add 装的插件 */
152
+ export async function updatePlugins(names: string[], opts: Omit<InstallOptions, "name" | "subdir" | "link" | "force">): Promise<UpdateResult[]> {
153
+ const records = await readRecords(opts.pluginsDir);
154
+ const targets = names.length ? names : Object.keys(records).sort();
155
+ const out: UpdateResult[] = [];
156
+ for (const name of targets) {
157
+ const rec = records[name];
158
+ const target = path.join(opts.pluginsDir, name);
159
+ if (!rec) {
160
+ const exists = await stat(target).catch(() => undefined);
161
+ out.push({ name, status: exists ? "unmanaged" : "failed", ...(exists ? {} : { error: "not installed" }) });
162
+ continue;
163
+ }
164
+ if (rec.kind === "link") {
165
+ out.push({ name, status: "linked" });
166
+ continue;
167
+ }
168
+ const staging = path.join(opts.pluginsDir, `.staging-${randomBytes(4).toString("hex")}`);
169
+ try {
170
+ opts.log?.(`${name}: fetching ${rec.source}`);
171
+ const source = await parseSource(rec.source, opts.cwd);
172
+ const fetched = await fetchInto(source, staging, rec.subdir, opts.log);
173
+ const from = rec.commit?.slice(0, 7) ?? rec.version;
174
+ const to = fetched.commit?.slice(0, 7) ?? fetched.info.version;
175
+ // git 看提交,npm 看版本;本地目录每次都重新复制
176
+ const same = rec.kind === "git" ? rec.commit === fetched.commit : rec.kind === "npm" ? rec.version !== undefined && rec.version === fetched.info.version : false;
177
+ if (same && (await stat(target).catch(() => undefined))) {
178
+ out.push({ name, status: "current", to });
179
+ continue;
180
+ }
181
+ const old = path.join(opts.pluginsDir, `.old-${randomBytes(4).toString("hex")}`);
182
+ const had = Boolean(await lstat(target).catch(() => undefined));
183
+ if (had) await rename(target, old);
184
+ try {
185
+ await rename(fetched.dir, target);
186
+ } catch (err) {
187
+ if (had) await rename(old, target).catch(() => {});
188
+ throw err;
189
+ }
190
+ if (had) await removeDir(old);
191
+ const next: InstallRecord = {
192
+ ...rec,
193
+ ...(fetched.commit ? { commit: fetched.commit } : {}),
194
+ ...(fetched.info.version ? { version: fetched.info.version } : {}),
195
+ updatedAt: now(),
196
+ };
197
+ await saveRecord(opts.pluginsDir, name, next);
198
+ out.push({ name, status: "updated", from, to });
199
+ } catch (err) {
200
+ out.push({ name, status: "failed", error: err instanceof Error ? err.message : String(err) });
201
+ } finally {
202
+ await rm(staging, { recursive: true, force: true }).catch(() => {});
203
+ }
204
+ }
205
+ return out;
206
+ }
207
+
208
+ /** 删除插件目录(链接只删链接本身)和安装记录;不存在时返回 false */
209
+ export async function removePlugin(name: string, pluginsDir: string): Promise<boolean> {
210
+ if (!PLUGIN_NAME.test(name)) throw new Error(`invalid plugin name ${JSON.stringify(name)}`);
211
+ const target = path.join(pluginsDir, name);
212
+ const existed = Boolean(await lstat(target).catch(() => undefined));
213
+ if (existed) await removeDir(target);
214
+ const records = await readRecords(pluginsDir);
215
+ const recorded = name in records;
216
+ if (recorded) {
217
+ delete records[name];
218
+ await writeRecords(pluginsDir, records);
219
+ }
220
+ return existed || recorded;
221
+ }
222
+
223
+ export async function readRecords(pluginsDir: string): Promise<Record<string, InstallRecord>> {
224
+ try {
225
+ const json = JSON.parse(await readFile(path.join(pluginsDir, RECORDS), "utf8"));
226
+ return typeof json?.plugins === "object" && json.plugins !== null ? json.plugins : {};
227
+ } catch {
228
+ return {};
229
+ }
230
+ }
231
+
232
+ async function writeRecords(pluginsDir: string, records: Record<string, InstallRecord>) {
233
+ const sorted = Object.fromEntries(Object.entries(records).sort(([a], [b]) => a.localeCompare(b)));
234
+ await writeFile(path.join(pluginsDir, RECORDS), `${JSON.stringify({ plugins: sorted }, null, 2)}\n`);
235
+ }
236
+
237
+ async function saveRecord(pluginsDir: string, name: string, record: InstallRecord) {
238
+ const records = await readRecords(pluginsDir);
239
+ records[name] = record;
240
+ await writeRecords(pluginsDir, records);
241
+ }
242
+
243
+ // ---------- 下载 ----------
244
+
245
+ /** 下载到 staging 里,返回插件目录(staging 里的某个子目录) */
246
+ async function fetchInto(source: PluginSource, staging: string, subdir: string | undefined, log?: (text: string) => void) {
247
+ await mkdir(staging, { recursive: true });
248
+ let root: string;
249
+ let commit: string | undefined;
250
+ if (source.kind === "git") {
251
+ root = path.join(staging, "repo");
252
+ log?.(`cloning ${source.location}${source.ref ? ` (${source.ref})` : ""}`);
253
+ try {
254
+ await run("git", ["clone", "--depth", "1", ...(source.ref ? ["--branch", source.ref] : []), "--", source.location, root], staging);
255
+ } catch (err) {
256
+ // --branch 不认提交哈希:完整克隆后再切过去
257
+ if (!source.ref) throw err;
258
+ await rm(root, { recursive: true, force: true });
259
+ await run("git", ["clone", "--", source.location, root], staging);
260
+ await run("git", ["checkout", "--detach", source.ref], root);
261
+ }
262
+ commit = (await run("git", ["rev-parse", "HEAD"], root)).trim();
263
+ await rm(path.join(root, ".git"), { recursive: true, force: true });
264
+ } else if (source.kind === "npm") {
265
+ const work = path.join(staging, "npm");
266
+ await mkdir(work);
267
+ await writeFile(path.join(work, "package.json"), JSON.stringify({ name: "jade-plugin-download", private: true }));
268
+ log?.(`downloading ${source.location}`);
269
+ const pm = packageManager();
270
+ await run(pm.cmd, [...pm.prefix, ...pm.add(source.location)], work);
271
+ const deps = Object.keys((JSON.parse(await readFile(path.join(work, "package.json"), "utf8")).dependencies ?? {}) as Record<string, string>);
272
+ if (deps.length !== 1) throw new Error(`could not tell which package ${source.location} installed`);
273
+ root = path.join(staging, "package");
274
+ // 包的依赖装在外层的 node_modules 里,复制过去之后重新安装
275
+ await cp(path.join(work, "node_modules", deps[0]!), root, { recursive: true, dereference: true });
276
+ // bun 在包目录里留下的标记,不属于插件
277
+ await rm(path.join(root, ".bun-tag"), { force: true });
278
+ await rm(work, { recursive: true, force: true });
279
+ } else {
280
+ root = path.join(staging, "local");
281
+ log?.(`copying ${source.location}`);
282
+ await cp(source.location, root, {
283
+ recursive: true,
284
+ filter: (src) => !/[\\/](node_modules|\.git)$/.test(src),
285
+ });
286
+ }
287
+ const dir = subdir ? inSubdir(root, subdir) : root;
288
+ const info = await inspectPlugin(dir);
289
+ await installDependencies(dir, log);
290
+ return { dir, commit, info };
291
+ }
292
+
293
+ async function installDependencies(dir: string, log?: (text: string) => void) {
294
+ let pkg: { dependencies?: Record<string, string> };
295
+ try {
296
+ pkg = JSON.parse(await readFile(path.join(dir, "package.json"), "utf8"));
297
+ } catch {
298
+ return;
299
+ }
300
+ if (!pkg.dependencies || Object.keys(pkg.dependencies).length === 0) return;
301
+ log?.("installing dependencies");
302
+ const pm = packageManager();
303
+ await run(pm.cmd, [...pm.prefix, ...pm.install], dir);
304
+ }
305
+
306
+ function inSubdir(root: string, subdir: string): string {
307
+ const full = path.resolve(root, subdir);
308
+ const rel = path.relative(root, full);
309
+ if (rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) throw new Error(`--path ${subdir} points outside the source`);
310
+ return full;
311
+ }
312
+
313
+ function nameHint(source: PluginSource): string {
314
+ if (source.kind === "npm") return source.location.replace(/^(@[^/]+\/)?/, "").replace(/@.*$/, "").replace(/\.(tgz|tar\.gz)$/, "");
315
+ return source.location.replace(/[\\/]+$/, "").replace(/\.git$/, "");
316
+ }
317
+
318
+ /** --name,否则插件声明的名字,否则来源的最后一段;整理成合法的目录名 */
319
+ function pickName(given: string | undefined, info: PluginInfo, hint: string): string {
320
+ if (given !== undefined) {
321
+ if (!PLUGIN_NAME.test(given)) throw new Error(`--name may only contain lowercase letters, digits, '.', '_' and '-'`);
322
+ return given;
323
+ }
324
+ const raw = info.name ?? path.basename(hint);
325
+ const name = raw
326
+ .toLowerCase()
327
+ .replace(/^@[^/]+\//, "")
328
+ .replace(/[^a-z0-9._-]+/g, "-")
329
+ .replace(/^[^a-z0-9]+/, "")
330
+ .replace(/-+$/, "");
331
+ if (!PLUGIN_NAME.test(name)) throw new Error(`cannot derive a directory name from ${JSON.stringify(raw)}; pass --name`);
332
+ return name;
333
+ }
334
+
335
+ async function makeRoom(target: string, name: string, force?: boolean) {
336
+ if (!(await lstat(target).catch(() => undefined))) return;
337
+ if (!force) throw new Error(`plugin ${name} is already installed (${target}); use jade plugin update, or --force to replace it`);
338
+ await removeDir(target);
339
+ }
340
+
341
+ /** 链接(包括 Windows 的 junction)只删链接本身,不碰它指向的目录 */
342
+ async function removeDir(p: string) {
343
+ const info = await lstat(p);
344
+ if (info.isSymbolicLink()) {
345
+ await unlink(p).catch(() => rmdir(p));
346
+ return;
347
+ }
348
+ await rm(p, { recursive: true, force: true });
349
+ }
350
+
351
+ const now = () => new Date().toISOString();
352
+
353
+ interface PackageManager {
354
+ cmd: string;
355
+ /** 放在子命令前面的参数(npm 的 CLI 脚本路径) */
356
+ prefix: string[];
357
+ add(spec: string): string[];
358
+ install: string[];
359
+ }
360
+
361
+ /** 跑在 Bun 下用 bun 自己;跑在 Node 下用 npm(Windows 上的 npm.cmd 不能直接执行,用 node 运行 npm 的 CLI 脚本) */
362
+ function packageManager(): PackageManager {
363
+ if (process.versions.bun) {
364
+ return { cmd: process.execPath, prefix: [], add: (spec) => ["add", "--ignore-scripts", spec], install: ["install", "--production"] };
365
+ }
366
+ const npm = npmCommand();
367
+ if (!npm) throw new Error("npm was not found; it is needed to install plugins from npm or plugins with dependencies");
368
+ const quiet = ["--ignore-scripts", "--no-audit", "--no-fund", "--loglevel=error"];
369
+ return { cmd: npm[0]!, prefix: npm.slice(1), add: (spec) => ["install", ...quiet, spec], install: ["install", "--omit=dev", ...quiet] };
370
+ }
371
+
372
+ function run(cmd: string, args: string[], cwd: string): Promise<string> {
373
+ return new Promise((resolve, reject) => {
374
+ execFile(cmd, args, { cwd, windowsHide: true, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } }, (err, stdout, stderr) => {
375
+ if (err) {
376
+ const detail = `${stderr || stdout}`.trim().split(/\r?\n/).slice(-6).join("\n");
377
+ const missing = (err as NodeJS.ErrnoException).code === "ENOENT";
378
+ const name = args[0]?.endsWith(".js") ? `npm ${args[1]}` : `${path.basename(cmd)} ${args[0]}`;
379
+ reject(new Error(missing ? `${cmd} is not installed or not on PATH` : `${name} failed${detail ? `:\n${detail}` : ""}`));
380
+ } else resolve(stdout);
381
+ });
382
+ });
383
+ }
384
+
385
+ // ---------- 启用、停用 ----------
386
+
387
+ /** $JADE_HOME/plugins.json:只有用户层能停用插件,仓库不能停用用户的插件或内置插件 */
388
+ export interface PluginSettings {
389
+ /** 停用的插件:内置插件的 id(jade/web),或者插件的目录名 */
390
+ disabled: string[];
391
+ }
392
+
393
+ export async function readPluginSettings(home: string): Promise<PluginSettings> {
394
+ try {
395
+ const json = JSON.parse(await readFile(path.join(home, "plugins.json"), "utf8"));
396
+ const disabled = Array.isArray(json?.disabled) ? json.disabled.filter((x: unknown): x is string => typeof x === "string") : [];
397
+ return { disabled };
398
+ } catch {
399
+ return { disabled: [] };
400
+ }
401
+ }
402
+
403
+ export async function setDisabled(home: string, name: string, disabled: boolean): Promise<boolean> {
404
+ const s = await readPluginSettings(home);
405
+ const has = s.disabled.includes(name);
406
+ if (has === disabled) return false;
407
+ const next = disabled ? [...s.disabled, name].sort() : s.disabled.filter((x) => x !== name);
408
+ await mkdir(home, { recursive: true });
409
+ let json: Record<string, unknown> = {};
410
+ try {
411
+ json = JSON.parse(await readFile(path.join(home, "plugins.json"), "utf8"));
412
+ } catch {
413
+ // 不存在或格式不对时重写
414
+ }
415
+ await writeFile(path.join(home, "plugins.json"), `${JSON.stringify({ ...json, disabled: next }, null, 2)}\n`);
416
+ return true;
417
+ }
418
+
419
+ /** 插件目录里的子目录名(不含 . 开头的临时目录) */
420
+ export async function installedNames(pluginsDir: string): Promise<string[]> {
421
+ try {
422
+ const names = (await readdir(pluginsDir)).filter((n) => !n.startsWith("."));
423
+ const out: string[] = [];
424
+ for (const n of names.sort()) if ((await stat(path.join(pluginsDir, n)).catch(() => undefined))?.isDirectory()) out.push(n);
425
+ return out;
426
+ } catch {
427
+ return [];
428
+ }
429
+ }