@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
package/src/memory.ts ADDED
@@ -0,0 +1,135 @@
1
+ // 记忆:跨会话记住的用户习惯和项目知识。
2
+ //
3
+ // 两个范围:user(所有项目通用,$JADE_HOME/MEMORY.md)和 project(这个仓库,$JADE_HOME/projects/<key>/MEMORY.md)。
4
+ // 都放在配置目录而不是仓库里:不会被提交,也不会被别人的仓库带进来。
5
+ // 文件是 Markdown 列表,一行一条,用户可以直接编辑。会话开始时由 prompts 插件读进系统提示词,
6
+ // 模型用 memory 工具增删,用户用 /memory 查看和管理。
7
+
8
+ import { createHash } from "node:crypto";
9
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
10
+ import path from "node:path";
11
+ import type { Tool } from "uncarved";
12
+
13
+ export const MEMORY_SCOPES = ["user", "project"] as const;
14
+ export type MemoryScope = (typeof MEMORY_SCOPES)[number];
15
+
16
+ /** 每个范围最多保留的条数;系统提示词里放不下太多 */
17
+ const MAX_ENTRIES = 100;
18
+ const MAX_ENTRY_CHARS = 500;
19
+
20
+ export class Memory {
21
+ readonly files: Record<MemoryScope, string>;
22
+
23
+ /** root:项目的根目录(git 仓库根,否则是工作目录),决定项目记忆存在哪里 */
24
+ constructor(home: string, root: string) {
25
+ this.files = { user: path.join(home, "MEMORY.md"), project: path.join(home, "projects", projectKey(root), "MEMORY.md") };
26
+ }
27
+
28
+ async list(scope: MemoryScope): Promise<string[]> {
29
+ let text: string;
30
+ try {
31
+ text = await readFile(this.files[scope], "utf8");
32
+ } catch {
33
+ return [];
34
+ }
35
+ return text
36
+ .split(/\r?\n/)
37
+ .map((l) => l.replace(/^\s*[-*]\s+/, "").trim())
38
+ .filter((l) => l && !l.startsWith("#"));
39
+ }
40
+
41
+ /** 加一条;已经有同样的一条时不重复。返回是否加入 */
42
+ async add(scope: MemoryScope, text: string): Promise<boolean> {
43
+ const entry = text.replace(/\s+/g, " ").trim();
44
+ if (!entry) throw new Error("the memory is empty");
45
+ if (entry.length > MAX_ENTRY_CHARS) throw new Error(`a memory is at most ${MAX_ENTRY_CHARS} characters; make it shorter`);
46
+ const all = await this.list(scope);
47
+ if (all.includes(entry)) return false;
48
+ if (all.length >= MAX_ENTRIES) throw new Error(`the ${scope} memory already has ${MAX_ENTRIES} entries; remove outdated ones first`);
49
+ await this.#write(scope, [...all, entry]);
50
+ return true;
51
+ }
52
+
53
+ /** 删掉内容完全相同的一条,或者唯一包含 text 的那一条。返回删掉的那条 */
54
+ async remove(scope: MemoryScope, text: string): Promise<string | undefined> {
55
+ const all = await this.list(scope);
56
+ const needle = text.replace(/\s+/g, " ").trim();
57
+ let i = all.indexOf(needle);
58
+ if (i < 0) {
59
+ const hits = all.flatMap((e, j) => (e.includes(needle) ? [j] : []));
60
+ if (hits.length > 1) throw new Error(`${hits.length} ${scope} memories contain "${needle}"; give the exact text of the one to remove`);
61
+ i = hits[0] ?? -1;
62
+ }
63
+ if (i < 0) return undefined;
64
+ const [removed] = all.splice(i, 1);
65
+ await this.#write(scope, all);
66
+ return removed;
67
+ }
68
+
69
+ /** 系统提示词里的一段;没有记忆时返回 undefined */
70
+ async prompt(): Promise<string | undefined> {
71
+ const sections: string[] = [];
72
+ for (const scope of MEMORY_SCOPES) {
73
+ const all = await this.list(scope);
74
+ if (all.length) sections.push(`## ${scope === "user" ? "About the user (all projects)" : "About this project"}\n${all.map((e) => `- ${e}`).join("\n")}`);
75
+ }
76
+ if (!sections.length) return undefined;
77
+ return (
78
+ "# Memory\n" +
79
+ "What you saved with the memory tool in earlier sessions. Follow it unless the user says otherwise now; " +
80
+ "if an entry turns out to be wrong or outdated, fix it with the memory tool.\n\n" +
81
+ sections.join("\n\n")
82
+ );
83
+ }
84
+
85
+ async #write(scope: MemoryScope, entries: string[]) {
86
+ const file = this.files[scope];
87
+ await mkdir(path.dirname(file), { recursive: true });
88
+ await writeFile(file, entries.map((e) => `- ${e}`).join("\n") + (entries.length ? "\n" : ""));
89
+ }
90
+ }
91
+
92
+ /** 项目记忆的目录名:可读的路径加上短哈希,避免不同路径化简后撞名 */
93
+ export function projectKey(root: string): string {
94
+ const full = path.resolve(root);
95
+ const readable = full.replace(/[^A-Za-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(-60);
96
+ return `${readable}-${createHash("sha256").update(full.toLowerCase()).digest("hex").slice(0, 8)}`;
97
+ }
98
+
99
+ export function memoryTool(memory: Memory): Tool {
100
+ return {
101
+ name: "memory",
102
+ description:
103
+ "Save or remove a memory that is loaded into the system prompt of every future session. " +
104
+ "Save when the user states a lasting preference or corrects how you work (scope user, e.g. language, style, tools they like), " +
105
+ "or when you learn a non-obvious fact about this project that future sessions need (scope project, e.g. how to run the tests, where a subsystem lives, a pitfall). " +
106
+ "Do not save what the code or the instruction files already say, secrets, or details that only matter for the current task. " +
107
+ "One short, self-contained sentence per memory. To change one, remove it and add the new version.",
108
+ inputSchema: {
109
+ type: "object",
110
+ properties: {
111
+ action: { type: "string", enum: ["add", "remove"] },
112
+ scope: { type: "string", enum: [...MEMORY_SCOPES] },
113
+ text: { type: "string", description: "The memory to add, or the exact text (or a unique part) of the one to remove" },
114
+ },
115
+ required: ["action", "scope", "text"],
116
+ additionalProperties: false,
117
+ },
118
+ // 写在配置目录里,影响之后的每个会话
119
+ effect: "write",
120
+ concurrency: "exclusive",
121
+ idempotent: true,
122
+ async execute(input) {
123
+ const { action, scope, text } = input as { action: "add" | "remove"; scope: MemoryScope; text: string };
124
+ try {
125
+ if (action === "add") {
126
+ return { content: (await memory.add(scope, text)) ? `Saved to ${scope} memory.` : `The ${scope} memory already has this.` };
127
+ }
128
+ const removed = await memory.remove(scope, text);
129
+ return removed ? { content: `Removed from ${scope} memory: ${removed}` } : { content: `No ${scope} memory matches "${text}".`, isError: true };
130
+ } catch (err) {
131
+ return { content: err instanceof Error ? err.message : String(err), isError: true };
132
+ }
133
+ },
134
+ };
135
+ }
@@ -0,0 +1,135 @@
1
+ // @ 引用文件:输入框里打 @ 时补全路径,发送时把引用的文件内容随消息一起交给模型。
2
+ //
3
+ // 内容用 read_file / list_dir 工具本身读取,格式和模型自己读到的一样(带行号),
4
+ // 而且算作"读过":模型可以直接修改引用的文件,不用先再读一遍。
5
+ // 只有存在的路径才算引用,所以消息里普通的 @someone 原样保留。
6
+
7
+ import { stat } from "node:fs/promises";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import type { Block, Tool, ToolContext } from "uncarved";
11
+ import { display, listFiles } from "./tools/fs.ts";
12
+
13
+ /** 补全用的候选最多这么多个(文件加目录) */
14
+ const MAX_CANDIDATES = 20_000;
15
+
16
+ /** @ 后面的路径:@"带 空格 的路径" 或者到空白为止 */
17
+ const MENTION = /(?<=^|\s)@(?:"([^"\n]+)"|([^\s"]+))/g;
18
+
19
+ /** 光标正在输入的 @ 引用:@ 的下标和已经输入的部分;不在引用里时返回 undefined */
20
+ export function mentionAt(value: string, cursor: number): { start: number; query: string } | undefined {
21
+ const m = /(?:^|\s)@("?[^\s"]*)$/.exec(value.slice(0, cursor));
22
+ if (!m) return undefined;
23
+ return { start: cursor - m[1]!.length - 1, query: m[1]!.replace(/^"/, "") };
24
+ }
25
+
26
+ /** 补全后的文本:@ 引用加一个空格,含空白的路径加引号 */
27
+ export const mentionText = (p: string) => (/\s/.test(p) ? `@"${p}"` : `@${p}`);
28
+
29
+ /** 消息里引用的路径,去重,按出现顺序;末尾的标点(句号、逗号……)不算路径 */
30
+ export function parseMentions(text: string): string[] {
31
+ const out: string[] = [];
32
+ for (const m of text.matchAll(MENTION)) {
33
+ const p = m[1] ?? m[2]!.replace(/[.,;:!?)\]},。;:!?)】]+$/u, "");
34
+ if (p && !out.includes(p)) out.push(p);
35
+ }
36
+ return out;
37
+ }
38
+
39
+ /**
40
+ * 按 query 给候选路径排序:文件名以 query 开头的最前,其次文件名包含、路径包含,
41
+ * 最后是按顺序出现 query 每个字符的模糊匹配;同一档里短的在前
42
+ */
43
+ export function rankPaths(paths: string[], query: string, limit: number): string[] {
44
+ const q = query.toLowerCase().replaceAll("\\", "/");
45
+ if (!q) return paths.filter((p) => !p.slice(0, -1).includes("/")).slice(0, limit);
46
+ const scored: { p: string; score: number }[] = [];
47
+ for (const p of paths) {
48
+ const lower = p.toLowerCase();
49
+ const base = lower.replace(/\/$/, "").split("/").pop()!;
50
+ let score: number;
51
+ if (lower.startsWith(q)) score = 0;
52
+ else if (base.startsWith(q)) score = 1;
53
+ else if (base.includes(q)) score = 2;
54
+ else if (lower.includes(q)) score = 3;
55
+ else if (subsequence(lower, q)) score = 4;
56
+ else continue;
57
+ scored.push({ p, score });
58
+ }
59
+ scored.sort((a, b) => a.score - b.score || a.p.length - b.p.length || a.p.localeCompare(b.p));
60
+ return scored.slice(0, limit).map((s) => s.p);
61
+ }
62
+
63
+ function subsequence(text: string, q: string): boolean {
64
+ let i = 0;
65
+ for (const ch of text) if (ch === q[i] && ++i === q.length) return true;
66
+ return false;
67
+ }
68
+
69
+ /** 补全的候选:工作目录里未被 git 忽略的文件和它们所在的目录(目录以 / 结尾),相对路径、正斜杠 */
70
+ export async function mentionCandidates(cwd: string): Promise<string[]> {
71
+ const files: string[] = [];
72
+ const dirs = new Set<string>();
73
+ for await (const full of await listFiles(cwd, AbortSignal.timeout(5000))) {
74
+ const rel = display(cwd, full);
75
+ files.push(rel);
76
+ for (let i = rel.lastIndexOf("/"); i > 0; i = rel.lastIndexOf("/", i - 1)) {
77
+ const dir = rel.slice(0, i + 1);
78
+ if (dirs.has(dir)) break;
79
+ dirs.add(dir);
80
+ }
81
+ if (files.length + dirs.size >= MAX_CANDIDATES) break;
82
+ }
83
+ return [...dirs, ...files];
84
+ }
85
+
86
+ export interface Attachments {
87
+ /** 随消息发出的内容 */
88
+ blocks: Block[];
89
+ /** 附上了的路径(显示用) */
90
+ attached: string[];
91
+ /** 存在但读不了的 */
92
+ failed: { path: string; reason: string }[];
93
+ }
94
+
95
+ /** 读取消息里引用的文件和目录;tools 里要有 read_file 和 list_dir */
96
+ export async function attachMentions(text: string, opts: { cwd: string; tools: Tool[]; sessionId: string; signal: AbortSignal }): Promise<Attachments> {
97
+ const out: Attachments = { blocks: [], attached: [], failed: [] };
98
+ const tool = (name: string) => opts.tools.find((t) => t.name === name);
99
+ let n = 0;
100
+ for (const p of parseMentions(text)) {
101
+ const full = path.resolve(opts.cwd, p.replace(/^~(?=$|[\\/])/, os.homedir()));
102
+ const info = await stat(full).catch(() => undefined);
103
+ if (!info) continue;
104
+ const name = info.isDirectory() ? "list_dir" : "read_file";
105
+ const t = tool(name);
106
+ if (!t) continue;
107
+ const ctx: ToolContext = {
108
+ sessionId: opts.sessionId,
109
+ toolUseId: `mention-${Date.now()}-${n++}`,
110
+ signal: opts.signal,
111
+ parent: { sessionId: opts.sessionId, eventId: "" },
112
+ progress: () => {},
113
+ };
114
+ const shown = display(opts.cwd, full);
115
+ try {
116
+ const r = await t.execute({ path: full }, ctx);
117
+ if (r.isError) {
118
+ out.failed.push({ path: shown, reason: typeof r.content === "string" ? r.content : "could not be read" });
119
+ continue;
120
+ }
121
+ const what = name === "list_dir" ? "the directory" : "the file";
122
+ const head = `[Note from jade] The user referenced ${what} ${shown}. Its content, as ${name} returns it:`;
123
+ out.blocks.push({ kind: "text", text: head, origin: { by: "host" }, trust: "trusted" });
124
+ out.blocks.push(
125
+ ...(typeof r.content === "string"
126
+ ? [{ kind: "text" as const, text: r.content, origin: { by: "tool" as const, name }, trust: "untrusted" as const }]
127
+ : r.content),
128
+ );
129
+ out.attached.push(shown);
130
+ } catch (err) {
131
+ out.failed.push({ path: shown, reason: err instanceof Error ? err.message : String(err) });
132
+ }
133
+ }
134
+ return out;
135
+ }
@@ -0,0 +1,239 @@
1
+ // jade plugin …:安装、更新、卸载、停用插件。在会话外运行,不需要配置模型。
2
+
3
+ import { readdir, readFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { hashDir, type TrustStore } from "uncarved";
6
+ import { BUILTINS, BUILTIN_IDS, REQUIRED_IDS } from "./plugins/builtins.ts";
7
+ import {
8
+ addPlugin,
9
+ installedNames,
10
+ readPluginSettings,
11
+ readRecords,
12
+ removePlugin,
13
+ setDisabled,
14
+ updatePlugins,
15
+ type InstallRecord,
16
+ } from "./plugins/install.ts";
17
+ import { inspectPlugin, type PluginInfo } from "./plugins/loader.ts";
18
+ import { bold, dim, green, red, yellow } from "./ui/screen.ts";
19
+
20
+ export const PLUGIN_HELP = `Usage: jade plugin <command>
21
+
22
+ list built-in and installed plugins
23
+ add <source> [options] install a plugin
24
+ <source>: a git URL (https://…, git@…, github:user/repo, user/repo; #branch, #tag or #commit),
25
+ an npm package (name, name@version, @scope/name, npm:<spec>, a .tgz file),
26
+ or a local directory
27
+ --project install into <repository>/.jade/plugins instead of $JADE_HOME/plugins
28
+ --name <name> directory name (default: the plugin's name)
29
+ --path <dir> use this subdirectory of the source (for repositories with several plugins)
30
+ --link local directory: link it instead of copying (for plugin development)
31
+ --force replace a plugin with the same name
32
+ update [name…] [--project] fetch again what jade plugin add installed (all of them when no name is given)
33
+ remove <name> [--project] delete an installed plugin
34
+ disable <name|id> stop loading a plugin, or a built-in plugin such as jade/web
35
+ enable <name|id> undo disable
36
+
37
+ Plugins are loaded when jade starts; restart running sessions to pick up changes.`;
38
+
39
+ export interface PluginCliOptions {
40
+ home: string;
41
+ cwd: string;
42
+ /** 仓库根目录(--project 用) */
43
+ root: string;
44
+ /** --project 安装的插件代码已经由用户看过,写进确认记录 */
45
+ trust: TrustStore;
46
+ out?: (text: string) => void;
47
+ err?: (text: string) => void;
48
+ }
49
+
50
+ /** 返回退出码 */
51
+ export async function pluginCli(argv: string[], o: PluginCliOptions): Promise<number> {
52
+ const out = o.out ?? ((t: string) => console.log(t));
53
+ const err = o.err ?? ((t: string) => console.error(t));
54
+ const [sub, ...rest] = argv;
55
+ const flags = { project: false, link: false, force: false } as { project: boolean; link: boolean; force: boolean; name?: string; path?: string };
56
+ const args: string[] = [];
57
+ for (let i = 0; i < rest.length; i++) {
58
+ const a = rest[i]!;
59
+ const value = () => {
60
+ const v = rest[++i];
61
+ if (v === undefined) throw new UsageError(`${a} needs a value`);
62
+ return v;
63
+ };
64
+ if (a === "--project") flags.project = true;
65
+ else if (a === "--link") flags.link = true;
66
+ else if (a === "--force" || a === "-f") flags.force = true;
67
+ else if (a === "--name") flags.name = value();
68
+ else if (a === "--path") flags.path = value();
69
+ else if (a === "-h" || a === "--help") {
70
+ out(PLUGIN_HELP);
71
+ return 0;
72
+ } else if (a.startsWith("-")) throw new UsageError(`unknown option ${a}`);
73
+ else args.push(a);
74
+ }
75
+ const userDir = path.join(o.home, "plugins");
76
+ const projectDir = path.join(o.root, ".jade", "plugins");
77
+ const dir = flags.project ? projectDir : userDir;
78
+ const log = (t: string) => err(dim(t));
79
+
80
+ switch (sub) {
81
+ case undefined:
82
+ case "help":
83
+ case "-h":
84
+ case "--help":
85
+ out(PLUGIN_HELP);
86
+ return 0;
87
+ case "list":
88
+ case "ls":
89
+ await list(o, out);
90
+ return 0;
91
+ case "add":
92
+ case "install": {
93
+ if (args.length !== 1) throw new UsageError("usage: jade plugin add <source> [--project] [--name <name>] [--path <dir>] [--link] [--force]");
94
+ const r = await addPlugin(args[0]!, { pluginsDir: dir, cwd: o.cwd, name: flags.name, subdir: flags.path, link: flags.link, force: flags.force, log });
95
+ if (flags.project && r.info.kind === "module") await trustProject(r.dir, o.trust);
96
+ out(green(`Installed ${bold(r.name)}${r.info.version ? ` ${r.info.version}` : ""} into ${r.dir}`) + dim(` (${origin(r.record)})`));
97
+ for (const line of await provides(r.dir, r.info)) out(` ${line}`);
98
+ if (r.info.bundle.unsupported.length) out(yellow(` jade does not support the plugin's ${r.info.bundle.unsupported.join(" and ")} yet; they are ignored`));
99
+ if (flags.project) out(dim(" Commit .jade/plugins to share it; others confirm it the first time jade loads it."));
100
+ out(dim("Restart jade to load it."));
101
+ return 0;
102
+ }
103
+ case "update":
104
+ case "upgrade": {
105
+ const results = await updatePlugins(args, { pluginsDir: dir, cwd: o.cwd, log });
106
+ if (results.length === 0) out(dim(`No plugins were installed with jade plugin add in ${dir}.`));
107
+ let failed = false;
108
+ for (const r of results) {
109
+ if (r.status === "updated") {
110
+ out(green(`${r.name}: updated${r.from || r.to ? ` ${r.from ?? "?"} → ${r.to ?? "?"}` : ""}`));
111
+ if (flags.project) {
112
+ const info = await inspectPlugin(path.join(dir, r.name)).catch(() => undefined);
113
+ if (info?.kind === "module") await trustProject(path.join(dir, r.name), o.trust);
114
+ }
115
+ } else if (r.status === "current") out(`${r.name}: up to date${r.to ? ` (${r.to})` : ""}`);
116
+ else if (r.status === "linked") out(dim(`${r.name}: linked to a local directory; nothing to fetch`));
117
+ else if (r.status === "unmanaged") out(dim(`${r.name}: not installed with jade plugin add; update it by hand`));
118
+ else {
119
+ failed = true;
120
+ err(red(`${r.name}: ${r.error}`));
121
+ }
122
+ }
123
+ if (results.some((r) => r.status === "updated")) out(dim("Restart jade to load the new versions."));
124
+ return failed ? 1 : 0;
125
+ }
126
+ case "remove":
127
+ case "rm":
128
+ case "uninstall": {
129
+ if (args.length !== 1) throw new UsageError("usage: jade plugin remove <name> [--project]");
130
+ if (!(await removePlugin(args[0]!, dir))) {
131
+ err(red(`plugin ${args[0]} is not installed in ${dir}`));
132
+ return 1;
133
+ }
134
+ await setDisabled(o.home, args[0]!, false);
135
+ out(green(`Removed ${args[0]}.`));
136
+ return 0;
137
+ }
138
+ case "disable":
139
+ case "enable": {
140
+ if (args.length !== 1) throw new UsageError(`usage: jade plugin ${sub} <name|id>`);
141
+ const name = args[0]!;
142
+ if (sub === "disable" && REQUIRED_IDS.has(name)) {
143
+ err(red(`${name} cannot be disabled: it decides which tool calls need your approval. Plugins can only make it stricter, with gate hooks.`));
144
+ return 1;
145
+ }
146
+ if (!BUILTIN_IDS.has(name) && !(await knownPlugin(o, name)) && sub === "disable") {
147
+ err(yellow(`note: no built-in or installed plugin is called ${name}; it is disabled anyway in case it is a plugin id`));
148
+ }
149
+ const changed = await setDisabled(o.home, name, sub === "disable");
150
+ out(changed ? green(`${name} ${sub}d.`) + dim(" Restart jade to apply it.") : dim(`${name} is already ${sub}d.`));
151
+ return 0;
152
+ }
153
+ default:
154
+ throw new UsageError(`unknown command ${sub}`);
155
+ }
156
+ }
157
+
158
+ export class UsageError extends Error {}
159
+
160
+ async function list(o: PluginCliOptions, out: (t: string) => void) {
161
+ const { disabled } = await readPluginSettings(o.home);
162
+ const off = new Set(disabled);
163
+ out(bold("Built-in") + dim(" (jade plugin disable <id> turns one off)"));
164
+ const width = Math.max(...BUILTINS.map((b) => b.id.length)) + 2;
165
+ for (const b of BUILTINS) {
166
+ const state = b.required ? dim(" required") : off.has(b.id) ? yellow(" disabled") : "";
167
+ out(` ${b.id.padEnd(width)}${dim(b.about)}${state}`);
168
+ }
169
+ for (const [title, dir] of [
170
+ ["User", path.join(o.home, "plugins")],
171
+ ["Project", path.join(o.root, ".jade", "plugins")],
172
+ ] as const) {
173
+ const names = await installedNames(dir);
174
+ out("");
175
+ out(bold(title) + dim(` ${dir}`));
176
+ if (names.length === 0) {
177
+ out(dim(" (none)"));
178
+ continue;
179
+ }
180
+ const records = await readRecords(dir);
181
+ for (const name of names) {
182
+ const rec = records[name];
183
+ let info: PluginInfo | undefined;
184
+ let problem: string | undefined;
185
+ try {
186
+ info = await inspectPlugin(path.join(dir, name));
187
+ } catch (e) {
188
+ problem = e instanceof Error ? e.message : String(e);
189
+ }
190
+ const version = info?.version ?? rec?.version;
191
+ const state = off.has(name) ? yellow(" disabled") : problem ? red(` broken: ${problem}`) : "";
192
+ out(` ${bold(name)}${version ? ` ${version}` : ""}${info ? dim(` ${info.kind}`) : ""}${rec ? dim(` · ${origin(rec)}`) : dim(" · copied by hand")}${state}`);
193
+ if (info?.description) out(dim(` ${info.description}`));
194
+ if (info) for (const line of await provides(path.join(dir, name), info)) out(dim(` ${line}`));
195
+ }
196
+ }
197
+ }
198
+
199
+ function origin(rec: InstallRecord): string {
200
+ if (rec.kind === "link") return `linked to ${rec.source}`;
201
+ const at = rec.commit ? `@${rec.commit.slice(0, 7)}` : "";
202
+ return `${rec.source}${rec.subdir ? ` (${rec.subdir})` : ""}${at}`;
203
+ }
204
+
205
+ /** 插件带了哪些东西(代码的工具和 hook 要加载后才知道,这里只说它是什么形式) */
206
+ async function provides(dir: string, info: PluginInfo): Promise<string[]> {
207
+ const lines: string[] = [];
208
+ if (info.kind === "module") lines.push(`code: ${info.entry}`);
209
+ if (info.kind === "process") lines.push(`process: ${[info.json.command, ...(info.json.args ?? [])].join(" ")}`);
210
+ const skills: string[] = [];
211
+ for (const d of info.bundle.skills) {
212
+ for (const n of await readdir(d).catch(() => [] as string[])) {
213
+ if (await readFile(path.join(d, n, "SKILL.md")).then(() => true, () => false)) skills.push(n);
214
+ }
215
+ }
216
+ if (skills.length) lines.push(`skills: ${skills.sort().join(", ")}`);
217
+ const commands: string[] = [];
218
+ for (const d of info.bundle.commands) for (const n of await readdir(d).catch(() => [] as string[])) if (n.endsWith(".md")) commands.push(`/${n.slice(0, -3)}`);
219
+ if (commands.length) lines.push(`commands: ${commands.sort().join(", ")}`);
220
+ if (info.bundle.mcp) {
221
+ let servers = info.bundle.mcp.servers;
222
+ if (servers === undefined) servers = await readFile(info.bundle.mcp.file, "utf8").then((t) => JSON.parse(t)?.mcpServers, () => undefined);
223
+ const names = servers && typeof servers === "object" ? Object.keys(servers) : [];
224
+ lines.push(`MCP servers: ${names.length ? names.join(", ") : path.relative(dir, info.bundle.mcp.file)}`);
225
+ }
226
+ return lines;
227
+ }
228
+
229
+ async function knownPlugin(o: PluginCliOptions, name: string): Promise<boolean> {
230
+ for (const dir of [path.join(o.home, "plugins"), path.join(o.root, ".jade", "plugins")]) if ((await installedNames(dir)).includes(name)) return true;
231
+ return false;
232
+ }
233
+
234
+ /** 自己用 --project 装的插件不用在启动时再确认一次(别人拉取仓库后第一次加载时仍要确认) */
235
+ async function trustProject(dir: string, trust: TrustStore) {
236
+ const root = path.resolve(dir);
237
+ const { hash } = await hashDir(root);
238
+ if (!(await trust.has(hash))) await trust.add({ hash, path: root, at: new Date().toISOString() });
239
+ }
@@ -0,0 +1,37 @@
1
+ // 预算插件:一轮里模型调用次数超过上限就停下(turn.continue)。
2
+
3
+ import type { Plugin, State } from "uncarved";
4
+
5
+ export interface BudgetOptions {
6
+ /** 一轮最多调用模型的次数,默认 100 */
7
+ maxSteps?: number;
8
+ id?: string;
9
+ }
10
+
11
+ /** 本轮(最近一条用户输入之后)模型已经回复了几次 */
12
+ export function stepsThisTurn(s: State): number {
13
+ let steps = 0;
14
+ for (let i = s.messages.length - 1; i >= 0; i--) {
15
+ const m = s.messages[i]!;
16
+ if (m.role === "assistant") steps++;
17
+ else if (m.content.some((b) => b.kind !== "tool_result")) break;
18
+ }
19
+ return steps;
20
+ }
21
+
22
+ export function budget(opts: BudgetOptions = {}): Plugin {
23
+ const max = opts.maxSteps ?? 100;
24
+ return {
25
+ id: opts.id ?? "jade/budget",
26
+ version: "0.1.0",
27
+ kernel: "^0.1",
28
+ needs: ["gate:turn.continue"],
29
+ hooks: [
30
+ {
31
+ kind: "gate",
32
+ point: "turn.continue",
33
+ fn: (s) => (stepsThisTurn(s) >= max ? { decision: "deny" } : { decision: "abstain" }),
34
+ },
35
+ ],
36
+ };
37
+ }
@@ -0,0 +1,31 @@
1
+ // jade 自带的插件。内核之外的功能都以插件的形式提供,和第三方插件用同一套接口:
2
+ // 每个都可以在 $JADE_HOME/plugins.json 里停用(jade plugin disable <id>),
3
+ // 或者由第三方插件用 replaces 代替。jade/policy 负责审批,不能停用或代替,第三方插件只能用 gate hook 让它更严格。
4
+
5
+ export interface BuiltinInfo {
6
+ id: string;
7
+ /** 提供什么(jade plugin list、/plugins 显示) */
8
+ about: string;
9
+ /** 不能停用或代替 */
10
+ required?: boolean;
11
+ }
12
+
13
+ export const BUILTINS: readonly BuiltinInfo[] = [
14
+ { id: "jade/policy", about: "permission modes and approvals", required: true },
15
+ { id: "jade/prompts", about: "system prompt, environment, AGENTS.md / CLAUDE.md instructions" },
16
+ { id: "jade/fs", about: "read_file, write_file, edit_file, multi_edit, list_dir, glob, grep" },
17
+ { id: "jade/shell", about: "bash, bash_output, kill_shell" },
18
+ { id: "jade/web", about: "web_fetch, web_search" },
19
+ { id: "jade/todo", about: "todo_write" },
20
+ { id: "jade/memory", about: "memory tool, memories in the system prompt, /memory" },
21
+ { id: "jade/task", about: "task tool (read-only sub-agents)" },
22
+ { id: "jade/skills", about: "skill tool, skill list in the system prompt, /skills" },
23
+ { id: "jade/mcp", about: "tools of the MCP servers, /mcp" },
24
+ { id: "jade/checks", about: "project checks after edits, /checks" },
25
+ { id: "jade/compact", about: "compacts the history near the context limit, /compact" },
26
+ { id: "jade/budget", about: "limits the steps of a turn" },
27
+ { id: "jade/repeats", about: "rejects calls repeated in one response, warns about repeated failures" },
28
+ ];
29
+
30
+ export const BUILTIN_IDS: ReadonlySet<string> = new Set(BUILTINS.map((b) => b.id));
31
+ export const REQUIRED_IDS: ReadonlySet<string> = new Set(BUILTINS.filter((b) => b.required).map((b) => b.id));