@uncarved/jade 0.3.1 → 0.4.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 (206) hide show
  1. package/README.md +1 -0
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/host.d.ts +2 -0
  5. package/dist/host.js +39 -5
  6. package/dist/host.js.map +1 -1
  7. package/dist/remote.js +5 -0
  8. package/dist/remote.js.map +1 -1
  9. package/dist/session.d.ts +7 -0
  10. package/dist/session.js +490 -29
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +36 -14
  14. package/plugins/approval/policy.ts +15 -10
  15. package/plugins/approval/review.ts +9 -5
  16. package/plugins/checks/checks.ts +10 -7
  17. package/plugins/checks/index.ts +13 -13
  18. package/plugins/checks/plugin.json +1 -1
  19. package/plugins/checks/project.ts +37 -38
  20. package/plugins/commands/index.ts +27 -3
  21. package/plugins/compact/compact.ts +13 -5
  22. package/plugins/compact/index.ts +20 -3
  23. package/plugins/compact/style.ts +13 -14
  24. package/plugins/completions/index.ts +35 -0
  25. package/plugins/completions/plugin.json +7 -0
  26. package/plugins/copy/index.ts +46 -0
  27. package/plugins/copy/plugin.json +7 -0
  28. package/plugins/editor/index.ts +10 -4
  29. package/plugins/fs/diff.ts +7 -6
  30. package/plugins/fs/fs.ts +8 -4
  31. package/plugins/fs/grep.ts +42 -9
  32. package/plugins/fs/index.ts +2 -7
  33. package/plugins/fs/plugin.json +1 -1
  34. package/plugins/fs/renderers.ts +16 -15
  35. package/plugins/fs/style.ts +16 -15
  36. package/plugins/hooks/index.ts +3 -2
  37. package/plugins/keys/index.ts +5 -1
  38. package/plugins/mcp/index.ts +197 -78
  39. package/plugins/mcp/install.ts +5 -3
  40. package/plugins/mcp/mcp.ts +163 -11
  41. package/plugins/mcp/plugin.json +2 -1
  42. package/plugins/mcp/project.ts +47 -50
  43. package/plugins/memory/index.ts +4 -4
  44. package/plugins/memory/style.ts +13 -14
  45. package/plugins/mentions/candidates.ts +67 -0
  46. package/plugins/mentions/index.ts +12 -5
  47. package/plugins/mentions/plugin.json +1 -1
  48. package/plugins/mentions/style.ts +13 -14
  49. package/plugins/models/configure.ts +47 -12
  50. package/plugins/models/index.ts +27 -1
  51. package/plugins/models/provider.ts +24 -0
  52. package/plugins/models/saved.ts +1 -1
  53. package/plugins/modes/index.ts +13 -2
  54. package/plugins/print/index.ts +7 -4
  55. package/plugins/prompts/index.ts +0 -0
  56. package/plugins/renderers/index.ts +10 -5
  57. package/plugins/repeats/index.ts +8 -8
  58. package/plugins/schedule/index.ts +5 -1
  59. package/plugins/screenshot/browser.ts +10 -0
  60. package/plugins/sessions/index.ts +48 -2
  61. package/plugins/shell/index.ts +27 -28
  62. package/plugins/shell/plugin.json +1 -1
  63. package/plugins/shell/renderers.ts +9 -7
  64. package/plugins/shell/shell.ts +3 -1
  65. package/plugins/skills/index.ts +28 -19
  66. package/plugins/skills/project.ts +12 -7
  67. package/plugins/steer/index.ts +5 -4
  68. package/plugins/task/index.ts +80 -50
  69. package/plugins/task/plugin.json +6 -2
  70. package/plugins/task/style.ts +13 -14
  71. package/plugins/task/subagent.ts +67 -184
  72. package/plugins/todo/index.ts +39 -9
  73. package/plugins/tools/index.ts +9 -2
  74. package/plugins/tui/frontend.ts +139 -89
  75. package/plugins/tui/index.ts +2 -3
  76. package/plugins/tui/mentions.ts +11 -80
  77. package/plugins/tui/plugin.json +1 -1
  78. package/plugins/tui/screen.ts +55 -5
  79. package/plugins/tui/transcript.ts +17 -7
  80. package/plugins/tui/tui.ts +337 -101
  81. package/plugins/tui/vendor.ts +1 -1
  82. package/plugins/undo/checkpoint.ts +8 -4
  83. package/plugins/undo/index.ts +170 -31
  84. package/plugins/undo/plugin.json +1 -0
  85. package/plugins/undo/snapshot.ts +87 -14
  86. package/plugins/undo/style.ts +13 -14
  87. package/plugins/web/index.ts +7 -18
  88. package/plugins/web/plugin.json +1 -1
  89. package/plugins-dist/approval/index.js +363 -418
  90. package/plugins-dist/approval/policy.js +391 -508
  91. package/plugins-dist/approval/review.js +132 -158
  92. package/plugins-dist/approval/schema.js +50 -55
  93. package/plugins-dist/ask/index.js +115 -129
  94. package/plugins-dist/budget/index.js +27 -31
  95. package/plugins-dist/checks/checks.js +293 -329
  96. package/plugins-dist/checks/index.js +119 -139
  97. package/plugins-dist/checks/plugin.json +2 -1
  98. package/plugins-dist/checks/project.js +57 -65
  99. package/plugins-dist/commands/index.js +47 -29
  100. package/plugins-dist/compact/compact.js +233 -249
  101. package/plugins-dist/compact/index.js +98 -95
  102. package/plugins-dist/compact/style.js +9 -14
  103. package/plugins-dist/completions/index.js +30 -0
  104. package/plugins-dist/completions/plugin.json +9 -0
  105. package/plugins-dist/continue/index.js +40 -52
  106. package/plugins-dist/copy/index.js +40 -0
  107. package/plugins-dist/copy/plugin.json +9 -0
  108. package/plugins-dist/cost/index.js +98 -115
  109. package/plugins-dist/custom-commands/index.js +55 -72
  110. package/plugins-dist/editor/index.js +64 -72
  111. package/plugins-dist/fs/diff.js +111 -124
  112. package/plugins-dist/fs/fs.js +426 -469
  113. package/plugins-dist/fs/grep.js +262 -253
  114. package/plugins-dist/fs/index.js +20 -34
  115. package/plugins-dist/fs/plugin.json +1 -2
  116. package/plugins-dist/fs/renderers.js +100 -112
  117. package/plugins-dist/fs/style.js +11 -15
  118. package/plugins-dist/fs/sys.js +31 -43
  119. package/plugins-dist/hooks/index.js +107 -127
  120. package/plugins-dist/keys/index.js +27 -31
  121. package/plugins-dist/mcp/index.js +271 -199
  122. package/plugins-dist/mcp/install.js +123 -137
  123. package/plugins-dist/mcp/mcp.js +638 -577
  124. package/plugins-dist/mcp/plugin.json +3 -1
  125. package/plugins-dist/mcp/project.js +98 -115
  126. package/plugins-dist/memory/index.js +83 -88
  127. package/plugins-dist/memory/memory.js +111 -128
  128. package/plugins-dist/memory/style.js +9 -14
  129. package/plugins-dist/mentions/attach.js +91 -99
  130. package/plugins-dist/mentions/candidates.js +49 -0
  131. package/plugins-dist/mentions/index.js +71 -81
  132. package/plugins-dist/mentions/plugin.json +2 -1
  133. package/plugins-dist/mentions/style.js +9 -14
  134. package/plugins-dist/models/config.js +29 -43
  135. package/plugins-dist/models/configure.js +421 -474
  136. package/plugins-dist/models/context.js +14 -22
  137. package/plugins-dist/models/index.js +182 -189
  138. package/plugins-dist/models/provider.js +263 -307
  139. package/plugins-dist/models/saved.js +60 -72
  140. package/plugins-dist/modes/index.js +138 -165
  141. package/plugins-dist/plugins/index.js +34 -34
  142. package/plugins-dist/print/index.js +192 -175
  143. package/plugins-dist/prompts/index.js +86 -89
  144. package/plugins-dist/prompts/notes.js +31 -37
  145. package/plugins-dist/prompts/prompts.js +155 -193
  146. package/plugins-dist/prompts/results.js +40 -53
  147. package/plugins-dist/prompts/sys.js +39 -50
  148. package/plugins-dist/renderers/index.js +32 -32
  149. package/plugins-dist/repeats/index.js +131 -174
  150. package/plugins-dist/schedule/cron.js +49 -56
  151. package/plugins-dist/schedule/index.js +230 -247
  152. package/plugins-dist/schedule/store.js +93 -109
  153. package/plugins-dist/scratch/index.js +12 -18
  154. package/plugins-dist/screenshot/browser.js +136 -154
  155. package/plugins-dist/screenshot/index.js +37 -46
  156. package/plugins-dist/screenshot/sys.js +53 -65
  157. package/plugins-dist/screenshot/tool.js +98 -126
  158. package/plugins-dist/sessions/index.js +149 -117
  159. package/plugins-dist/shell/index.js +117 -135
  160. package/plugins-dist/shell/plugin.json +1 -1
  161. package/plugins-dist/shell/renderers.js +28 -33
  162. package/plugins-dist/shell/service.js +17 -23
  163. package/plugins-dist/shell/shell.js +307 -362
  164. package/plugins-dist/shell/sys.js +64 -79
  165. package/plugins-dist/skills/index.js +193 -211
  166. package/plugins-dist/skills/install.js +122 -149
  167. package/plugins-dist/skills/project.js +65 -73
  168. package/plugins-dist/skills/skills.js +135 -171
  169. package/plugins-dist/steer/index.js +108 -125
  170. package/plugins-dist/suggest/index.js +235 -259
  171. package/plugins-dist/task/index.js +130 -117
  172. package/plugins-dist/task/plugin.json +5 -2
  173. package/plugins-dist/task/style.js +9 -14
  174. package/plugins-dist/task/subagent.js +156 -279
  175. package/plugins-dist/todo/index.js +79 -63
  176. package/plugins-dist/tools/index.js +36 -42
  177. package/plugins-dist/tui/editor.js +145 -160
  178. package/plugins-dist/tui/frontend.js +639 -678
  179. package/plugins-dist/tui/history.js +34 -37
  180. package/plugins-dist/tui/index.js +16 -18
  181. package/plugins-dist/tui/markdown.js +203 -247
  182. package/plugins-dist/tui/mascot.js +266 -355
  183. package/plugins-dist/tui/mentions.js +67 -144
  184. package/plugins-dist/tui/plugin.json +1 -2
  185. package/plugins-dist/tui/render.js +35 -45
  186. package/plugins-dist/tui/screen.js +197 -180
  187. package/plugins-dist/tui/transcript.js +436 -468
  188. package/plugins-dist/tui/tui.js +1554 -1656
  189. package/plugins-dist/tui/vendor.js +1088 -1388
  190. package/plugins-dist/undo/checkpoint.js +97 -118
  191. package/plugins-dist/undo/index.js +281 -192
  192. package/plugins-dist/undo/plugin.json +3 -0
  193. package/plugins-dist/undo/snapshot.js +134 -99
  194. package/plugins-dist/undo/style.js +9 -14
  195. package/plugins-dist/update/index.js +26 -28
  196. package/plugins-dist/web/env.js +55 -68
  197. package/plugins-dist/web/index.js +80 -110
  198. package/plugins-dist/web/plugin.json +1 -2
  199. package/plugins-dist/web/renderers.js +4 -5
  200. package/plugins-dist/web/web.js +514 -593
  201. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  202. package/sdk/python/jade_plugin.py +9 -2
  203. package/src/api.ts +1 -1
  204. package/src/host.ts +39 -4
  205. package/src/remote.ts +6 -1
  206. package/src/session.ts +496 -36
@@ -1,147 +1,130 @@
1
- // 记忆:跨会话记住的用户习惯和项目知识。
2
- //
3
- // 两个范围:user(所有项目通用,$JADE_HOME/MEMORY.md)和 project(这个仓库,$JADE_HOME/projects/<key>/MEMORY.md)。
4
- // 都放在配置目录而不是仓库里:不会被提交,也不会被别人的仓库带进来。
5
- // 文件是 Markdown 列表,一行一条,用户可以直接编辑。会话开始时经 prompts@1 读进系统提示词,
6
- // 模型用 memory 工具增删,用户用 /memory 查看和管理。从旧 jade 的 memory.ts 移植,文件位置和格式不变。
7
1
  import { createHash } from "node:crypto";
8
2
  import { existsSync, realpathSync } from "node:fs";
9
3
  import { mkdir, readFile, writeFile } from "node:fs/promises";
10
4
  import path from "node:path";
11
5
  export const MEMORY_SCOPES = ["user", "project"];
12
- /** 每个范围最多保留的条数;系统提示词里放不下太多 */
13
6
  const MAX_ENTRIES = 100;
14
7
  const MAX_ENTRY_CHARS = 500;
8
+
15
9
  export class Memory {
16
- files;
17
- /** root:项目的根目录(git 仓库根,否则是工作目录),决定项目记忆存在哪里 */
18
- constructor(home, root) {
19
- this.files = { user: path.join(home, "MEMORY.md"), project: path.join(home, "projects", projectKey(root), "MEMORY.md") };
10
+ files;
11
+ constructor(home, root) {
12
+ this.files = { user: path.join(home, "MEMORY.md"), project: path.join(home, "projects", projectKey(root), "MEMORY.md") };
13
+ }
14
+ async list(scope) {
15
+ let text;
16
+ try {
17
+ text = await readFile(this.files[scope], "utf8");
18
+ } catch {
19
+ return [];
20
20
  }
21
- async list(scope) {
22
- let text;
23
- try {
24
- text = await readFile(this.files[scope], "utf8");
25
- }
26
- catch {
27
- return [];
28
- }
29
- return text
30
- .split(/\r?\n/)
31
- .map((l) => l.replace(/^\s*[-*]\s+/, "").trim())
32
- .filter((l) => l && !l.startsWith("#"));
33
- }
34
- /** 加一条;已经有同样的一条时不重复。返回是否加入 */
35
- async add(scope, text) {
36
- const entry = text.replace(/\s+/g, " ").trim();
37
- if (!entry)
38
- throw new Error("the memory is empty");
39
- if (entry.length > MAX_ENTRY_CHARS)
40
- throw new Error(`a memory is at most ${MAX_ENTRY_CHARS} characters; make it shorter`);
41
- const all = await this.list(scope);
42
- if (all.includes(entry))
43
- return false;
44
- if (all.length >= MAX_ENTRIES)
45
- throw new Error(`the ${scope} memory already has ${MAX_ENTRIES} entries; remove outdated ones first`);
46
- await this.#write(scope, [...all, entry]);
47
- return true;
48
- }
49
- /** 删掉内容完全相同的一条,或者唯一包含 text 的那一条。返回删掉的那条 */
50
- async remove(scope, text) {
51
- const all = await this.list(scope);
52
- const needle = text.replace(/\s+/g, " ").trim();
53
- let i = all.indexOf(needle);
54
- if (i < 0) {
55
- const hits = all.flatMap((e, j) => (e.includes(needle) ? [j] : []));
56
- if (hits.length > 1)
57
- throw new Error(`${hits.length} ${scope} memories contain "${needle}"; give the exact text of the one to remove`);
58
- i = hits[0] ?? -1;
59
- }
60
- if (i < 0)
61
- return undefined;
62
- const [removed] = all.splice(i, 1);
63
- await this.#write(scope, all);
64
- return removed;
21
+ return text.split(/\r?\n/).map((l) => l.replace(/^\s*[-*]\s+/, "").trim()).filter((l) => l && !l.startsWith("#"));
22
+ }
23
+ async add(scope, text) {
24
+ const entry = text.replace(/\s+/g, " ").trim();
25
+ if (!entry)
26
+ throw new Error("the memory is empty");
27
+ if (entry.length > MAX_ENTRY_CHARS)
28
+ throw new Error(`a memory is at most ${MAX_ENTRY_CHARS} characters; make it shorter`);
29
+ const all = await this.list(scope);
30
+ if (all.includes(entry))
31
+ return false;
32
+ if (all.length >= MAX_ENTRIES)
33
+ throw new Error(`the ${scope} memory already has ${MAX_ENTRIES} entries; remove outdated ones first`);
34
+ await this.#write(scope, [...all, entry]);
35
+ return true;
36
+ }
37
+ async remove(scope, text) {
38
+ const all = await this.list(scope);
39
+ const needle = text.replace(/\s+/g, " ").trim();
40
+ let i = all.indexOf(needle);
41
+ if (i < 0) {
42
+ const hits = all.flatMap((e, j) => e.includes(needle) ? [j] : []);
43
+ if (hits.length > 1)
44
+ throw new Error(`${hits.length} ${scope} memories contain "${needle}"; give the exact text of the one to remove`);
45
+ i = hits[0] ?? -1;
65
46
  }
66
- /** 系统提示词里的一段;没有记忆时返回 undefined */
67
- async prompt() {
68
- const sections = [];
69
- for (const scope of MEMORY_SCOPES) {
70
- const all = await this.list(scope);
71
- if (all.length)
72
- sections.push(`## ${scope === "user" ? "About the user (all projects)" : "About this project"}\n${all.map((e) => `- ${e}`).join("\n")}`);
73
- }
74
- if (!sections.length)
75
- return undefined;
76
- return ("# Memory\n" +
77
- "What you saved with the memory tool in earlier sessions. Follow it unless the user says otherwise now; " +
78
- "if an entry turns out to be wrong or outdated, fix it with the memory tool.\n\n" +
79
- sections.join("\n\n"));
80
- }
81
- async #write(scope, entries) {
82
- const file = this.files[scope];
83
- await mkdir(path.dirname(file), { recursive: true });
84
- await writeFile(file, entries.map((e) => `- ${e}`).join("\n") + (entries.length ? "\n" : ""));
47
+ if (i < 0)
48
+ return;
49
+ const [removed] = all.splice(i, 1);
50
+ await this.#write(scope, all);
51
+ return removed;
52
+ }
53
+ async prompt() {
54
+ const sections = [];
55
+ for (const scope of MEMORY_SCOPES) {
56
+ const all = await this.list(scope);
57
+ if (all.length)
58
+ sections.push(`## ${scope === "user" ? "About the user (all projects)" : "About this project"}
59
+ ${all.map((e) => `- ${e}`).join(`
60
+ `)}`);
85
61
  }
62
+ if (!sections.length)
63
+ return;
64
+ return `# Memory
65
+ ` + "What you saved with the memory tool in earlier sessions. Follow it unless the user says otherwise now; " + `if an entry turns out to be wrong or outdated, fix it with the memory tool.
66
+
67
+ ` + sections.join(`
68
+
69
+ `);
70
+ }
71
+ async#write(scope, entries) {
72
+ const file = this.files[scope];
73
+ await mkdir(path.dirname(file), { recursive: true });
74
+ await writeFile(file, entries.map((e) => `- ${e}`).join(`
75
+ `) + (entries.length ? `
76
+ ` : ""));
77
+ }
86
78
  }
87
- /** 项目记忆的目录名:可读的路径加上短哈希,避免不同路径化简后撞名 */
88
79
  export function projectKey(root) {
89
- const full = path.resolve(root);
90
- const readable = full.replace(/[^A-Za-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(-60);
91
- return `${readable}-${createHash("sha256").update(full.toLowerCase()).digest("hex").slice(0, 8)}`;
80
+ const full = path.resolve(root);
81
+ const readable = full.replace(/[^A-Za-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(-60);
82
+ return `${readable}-${createHash("sha256").update(full.toLowerCase()).digest("hex").slice(0, 8)}`;
92
83
  }
93
- /** git 仓库的根目录(往上找 .git);不在仓库里时是 cwd 本身。和旧 jade 的 git rev-parse 结果相同,项目记忆的位置不变 */
94
84
  export function projectRoot(cwd) {
95
- let dir = path.resolve(cwd);
96
- for (;;) {
97
- if (existsSync(path.join(dir, ".git"))) {
98
- try {
99
- return realpathSync.native(dir);
100
- }
101
- catch {
102
- return dir;
103
- }
104
- }
105
- const up = path.dirname(dir);
106
- if (up === dir)
107
- return path.resolve(cwd);
108
- dir = up;
85
+ let dir = path.resolve(cwd);
86
+ for (;; ) {
87
+ if (existsSync(path.join(dir, ".git"))) {
88
+ try {
89
+ return realpathSync.native(dir);
90
+ } catch {
91
+ return dir;
92
+ }
109
93
  }
94
+ const up = path.dirname(dir);
95
+ if (up === dir)
96
+ return path.resolve(cwd);
97
+ dir = up;
98
+ }
110
99
  }
111
100
  export function memoryTool(memory) {
112
- return {
113
- name: "memory",
114
- description: "Save or remove a memory that is loaded into the system prompt of every future session. " +
115
- "Save when the user states a lasting preference or corrects how you work (scope user, e.g. language, style, tools they like), " +
116
- "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). " +
117
- "Do not save what the code or the instruction files already say, secrets, or details that only matter for the current task. " +
118
- "One short, self-contained sentence per memory. To change one, remove it and add the new version.",
119
- inputSchema: {
120
- type: "object",
121
- properties: {
122
- action: { type: "string", enum: ["add", "remove"] },
123
- scope: { type: "string", enum: [...MEMORY_SCOPES] },
124
- text: { type: "string", description: "The memory to add, or the exact text (or a unique part) of the one to remove" },
125
- },
126
- required: ["action", "scope", "text"],
127
- additionalProperties: false,
128
- },
129
- // 写在配置目录里,影响之后的每个会话
130
- effect: "write",
131
- concurrency: "exclusive",
132
- idempotent: true,
133
- async execute(input) {
134
- const { action, scope, text } = input;
135
- try {
136
- if (action === "add") {
137
- return { content: (await memory.add(scope, text)) ? `Saved to ${scope} memory.` : `The ${scope} memory already has this.` };
138
- }
139
- const removed = await memory.remove(scope, text);
140
- return removed ? { content: `Removed from ${scope} memory: ${removed}` } : { content: `No ${scope} memory matches "${text}".`, isError: true };
141
- }
142
- catch (err) {
143
- return { content: err instanceof Error ? err.message : String(err), isError: true };
144
- }
145
- },
146
- };
101
+ return {
102
+ name: "memory",
103
+ description: "Save or remove a memory that is loaded into the system prompt of every future session. " + "Save when the user states a lasting preference or corrects how you work (scope user, e.g. language, style, tools they like), " + "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). " + "Do not save what the code or the instruction files already say, secrets, or details that only matter for the current task. " + "One short, self-contained sentence per memory. To change one, remove it and add the new version.",
104
+ inputSchema: {
105
+ type: "object",
106
+ properties: {
107
+ action: { type: "string", enum: ["add", "remove"] },
108
+ scope: { type: "string", enum: [...MEMORY_SCOPES] },
109
+ text: { type: "string", description: "The memory to add, or the exact text (or a unique part) of the one to remove" }
110
+ },
111
+ required: ["action", "scope", "text"],
112
+ additionalProperties: false
113
+ },
114
+ effect: "write",
115
+ concurrency: "exclusive",
116
+ idempotent: true,
117
+ async execute(input) {
118
+ const { action, scope, text } = input;
119
+ try {
120
+ if (action === "add") {
121
+ return { content: await memory.add(scope, text) ? `Saved to ${scope} memory.` : `The ${scope} memory already has this.` };
122
+ }
123
+ const removed = await memory.remove(scope, text);
124
+ return removed ? { content: `Removed from ${scope} memory: ${removed}` } : { content: `No ${scope} memory matches "${text}".`, isError: true };
125
+ } catch (err) {
126
+ return { content: err instanceof Error ? err.message : String(err), isError: true };
127
+ }
128
+ }
129
+ };
147
130
  }
@@ -1,14 +1,9 @@
1
- // 显示用的小工具:截断和 ANSI 颜色。插件之间不共享代码(只能共享类型),所以这里也有一份(同 jade/fs 的 style.ts)。
2
- export const clip = (s, n) => (s.length > n ? s.slice(0, n) + "…" : s);
3
- // 设了 NO_COLOR(非空)或标准输出不是终端时不输出颜色,见 https://no-color.org
4
- const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
5
- /**
6
- * 每种样式用自己的关闭码,不用 \x1b[0m 全部重置:外面套着别的样式时,后面的文字仍保持外层样式。
7
- * 里面出现同一个关闭码(例如 dim 里套 bold,两者都用 22 关闭)时紧接着重新打开外层的样式
8
- */
9
- const paint = (open, close) => (s) => colors ? `\x1b[${open}m${s.replaceAll(`\x1b[${close}m`, `\x1b[${close}m\x1b[${open}m`)}\x1b[${close}m` : s;
10
- export const dim = paint("2", "22");
11
- export const red = paint("31", "39");
12
- export const green = paint("32", "39");
13
- export const yellow = paint("33", "39");
14
- export const bold = paint("1", "22");
1
+ export const clip = (s, n) => s.length > n ? s.slice(0, n) + "…" : s;
2
+ const styled = (style) => (text) => ({ text, style });
3
+ export const dim = styled("dim");
4
+ export const bold = styled("bold");
5
+ export const ok = styled("ok");
6
+ export const warn = styled("warn");
7
+ export const error = styled("error");
8
+ export const lines = (rows) => rows.flatMap((r, i) => i ? [`
9
+ `, r] : [r]);
@@ -1,120 +1,112 @@
1
- // 读取消息里 @ 引用的文件和目录。只有存在的路径才算引用,所以消息里普通的 @someone 原样保留。
2
- //
3
- // 旧 jade 用 read_file / list_dir 工具本身读取,读到的文件算作"读过";jade/fs 的工具是它会话里的私有对象,
4
- // 别的插件拿不到,所以这里自己读,格式和 read_file、list_dir 返回的一样(带行号)。
5
1
  import { readdir, readFile, stat } from "node:fs/promises";
6
2
  import os from "node:os";
7
3
  import path from "node:path";
8
- /** @ 后面的路径:@"带 空格 的路径" 或者到空白为止 */
9
4
  const MENTION = /(?<=^|\s)@(?:"([^"\n]+)"|([^\s"]+))/g;
10
5
  const MAX_LINES = 2000;
11
6
  const MAX_LINE_CHARS = 2000;
12
- const MAX_READ_CHARS = 100_000;
13
- const MAX_IMAGE_BYTES = 5_000_000;
14
- const MAX_PDF_BYTES = 10_000_000;
15
- /** 一条消息最多附上几个引用 */
7
+ const MAX_READ_CHARS = 1e5;
8
+ const MAX_IMAGE_BYTES = 5000000;
9
+ const MAX_PDF_BYTES = 1e7;
16
10
  const MAX_MENTIONS = 20;
17
11
  const IMAGE_TYPES = {
18
- ".png": "image/png",
19
- ".jpg": "image/jpeg",
20
- ".jpeg": "image/jpeg",
21
- ".gif": "image/gif",
22
- ".webp": "image/webp",
12
+ ".png": "image/png",
13
+ ".jpg": "image/jpeg",
14
+ ".jpeg": "image/jpeg",
15
+ ".gif": "image/gif",
16
+ ".webp": "image/webp"
23
17
  };
24
- /** 消息里引用的路径,去重,按出现顺序;末尾的标点(句号、逗号……)不算路径 */
25
18
  export function parseMentions(text) {
26
- const out = [];
27
- for (const m of text.matchAll(MENTION)) {
28
- const p = m[1] ?? m[2].replace(/[.,;:!?)\]},。;:!?)】]+$/u, "");
29
- if (p && !out.includes(p))
30
- out.push(p);
31
- }
32
- return out;
19
+ const out = [];
20
+ for (const m of text.matchAll(MENTION)) {
21
+ const p = m[1] ?? m[2].replace(/[.,;:!?)\]},。;:!?)】]+$/u, "");
22
+ if (p && !out.includes(p))
23
+ out.push(p);
24
+ }
25
+ return out;
33
26
  }
34
- /** 显示用:工作目录内的路径用相对形式,统一为正斜杠 */
35
27
  export function display(cwd, full) {
36
- const rel = path.relative(cwd, full);
37
- const shown = rel && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) ? rel : full;
38
- return shown.split(path.sep).join("/");
28
+ const rel = path.relative(cwd, full);
29
+ const shown = rel && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) ? rel : full;
30
+ return shown.split(path.sep).join("/");
39
31
  }
40
- /** 读取消息里引用的文件和目录 */
41
32
  export async function attachMentions(text, opts) {
42
- const out = { blocks: [], attached: [], failed: [] };
43
- const origin = { by: "plugin", id: opts.plugin };
44
- for (const p of parseMentions(text).slice(0, MAX_MENTIONS)) {
45
- opts.signal?.throwIfAborted();
46
- const full = path.resolve(opts.cwd, p.replace(/^~(?=$|[\\/])/, os.homedir()));
47
- const info = await stat(full).catch(() => undefined);
48
- if (!info)
49
- continue;
50
- const shown = display(opts.cwd, full);
51
- try {
52
- const dir = info.isDirectory();
53
- const content = dir ? await listDir(full) : await readAny(full, shown, info.size);
54
- if (typeof content === "object" && "error" in content) {
55
- out.failed.push({ path: shown, reason: content.error });
56
- continue;
57
- }
58
- const head = dir
59
- ? `[Note from jade] The user referenced the directory ${shown}. Its entries, as list_dir returns them:`
60
- : `[Note from jade] The user referenced the file ${shown}. Its content, as read_file returns it (read it with read_file before editing it):`;
61
- out.blocks.push({ kind: "text", text: head, origin, trust: "trusted" });
62
- if (typeof content === "string")
63
- out.blocks.push({ kind: "text", text: content, origin, trust: "untrusted" });
64
- else
65
- out.blocks.push(content.block);
66
- out.attached.push(shown);
67
- }
68
- catch (err) {
69
- out.failed.push({ path: shown, reason: err instanceof Error ? err.message : String(err) });
70
- }
33
+ const out = { blocks: [], attached: [], failed: [] };
34
+ const origin = { by: "plugin", id: opts.plugin };
35
+ for (const p of parseMentions(text).slice(0, MAX_MENTIONS)) {
36
+ opts.signal?.throwIfAborted();
37
+ const full = path.resolve(opts.cwd, p.replace(/^~(?=$|[\\/])/, os.homedir()));
38
+ const info = await stat(full).catch(() => {
39
+ return;
40
+ });
41
+ if (!info)
42
+ continue;
43
+ const shown = display(opts.cwd, full);
44
+ try {
45
+ const dir = info.isDirectory();
46
+ const content = dir ? await listDir(full) : await readAny(full, shown, info.size);
47
+ if (typeof content === "object" && "error" in content) {
48
+ out.failed.push({ path: shown, reason: content.error });
49
+ continue;
50
+ }
51
+ const head = dir ? `[Note from jade] The user referenced the directory ${shown}. Its entries, as list_dir returns them:` : `[Note from jade] The user referenced the file ${shown}. Its content, as read_file returns it (read it with read_file before editing it):`;
52
+ out.blocks.push({ kind: "text", text: head, origin, trust: "trusted" });
53
+ if (typeof content === "string")
54
+ out.blocks.push({ kind: "text", text: content, origin, trust: "untrusted" });
55
+ else
56
+ out.blocks.push(content.block);
57
+ out.attached.push(shown);
58
+ } catch (err) {
59
+ out.failed.push({ path: shown, reason: err instanceof Error ? err.message : String(err) });
60
+ }
61
+ }
62
+ return out;
63
+ async function readAny(full, shown, size) {
64
+ const ext = path.extname(full).toLowerCase();
65
+ const mediaType = IMAGE_TYPES[ext];
66
+ if (mediaType) {
67
+ if (size > MAX_IMAGE_BYTES)
68
+ return { error: `image is ${size} bytes; at most ${MAX_IMAGE_BYTES} can be attached` };
69
+ const data = (await readFile(full)).toString("base64");
70
+ return { block: { kind: "image", source: { type: "base64", media_type: mediaType, data }, origin, trust: "untrusted" } };
71
71
  }
72
- return out;
73
- async function readAny(full, shown, size) {
74
- const ext = path.extname(full).toLowerCase();
75
- const mediaType = IMAGE_TYPES[ext];
76
- if (mediaType) {
77
- if (size > MAX_IMAGE_BYTES)
78
- return { error: `image is ${size} bytes; at most ${MAX_IMAGE_BYTES} can be attached` };
79
- const data = (await readFile(full)).toString("base64");
80
- return { block: { kind: "image", source: { type: "base64", media_type: mediaType, data }, origin, trust: "untrusted" } };
81
- }
82
- if (ext === ".pdf") {
83
- if (size > MAX_PDF_BYTES)
84
- return { error: `PDF is ${size} bytes; at most ${MAX_PDF_BYTES} can be attached` };
85
- const data = (await readFile(full)).toString("base64");
86
- return { block: { kind: "document", source: { type: "base64", media_type: "application/pdf", data }, origin, trust: "untrusted" } };
87
- }
88
- const buf = await readFile(full);
89
- if (buf.subarray(0, 8000).includes(0))
90
- return { error: `${shown} is a binary file (${buf.length} bytes) and cannot be shown as text` };
91
- return numbered(buf.toString("utf8"));
72
+ if (ext === ".pdf") {
73
+ if (size > MAX_PDF_BYTES)
74
+ return { error: `PDF is ${size} bytes; at most ${MAX_PDF_BYTES} can be attached` };
75
+ const data = (await readFile(full)).toString("base64");
76
+ return { block: { kind: "document", source: { type: "base64", media_type: "application/pdf", data }, origin, trust: "untrusted" } };
92
77
  }
78
+ const buf = await readFile(full);
79
+ if (buf.subarray(0, 8000).includes(0))
80
+ return { error: `${shown} is a binary file (${buf.length} bytes) and cannot be shown as text` };
81
+ return numbered(buf.toString("utf8"));
82
+ }
93
83
  }
94
- /** 和 read_file 一样:每行前面是从 1 开始的行号和一个制表符,超长的截断 */
95
84
  function numbered(text) {
96
- if (text.length === 0)
97
- return "(empty file)";
98
- const lines = text.split(/\r?\n/);
99
- if (lines.at(-1) === "")
100
- lines.pop();
101
- const slice = lines.slice(0, MAX_LINES);
102
- const out = [];
103
- let size = 0;
104
- for (const [i, l] of slice.entries()) {
105
- const row = `${i + 1}\t${l.length > MAX_LINE_CHARS ? `${l.slice(0, MAX_LINE_CHARS)}… [line truncated: ${l.length} characters]` : l}`;
106
- if (out.length > 0 && size + row.length + 1 > MAX_READ_CHARS)
107
- break;
108
- out.push(row);
109
- size += row.length + 1;
110
- }
111
- const body = out.join("\n");
112
- if (out.length < lines.length)
113
- return `${body}\n(showing lines 1-${out.length} of ${lines.length}; read_file with offset ${out.length + 1} for the rest)`;
114
- return body;
85
+ if (text.length === 0)
86
+ return "(empty file)";
87
+ const lines = text.split(/\r?\n/);
88
+ if (lines.at(-1) === "")
89
+ lines.pop();
90
+ const slice = lines.slice(0, MAX_LINES);
91
+ const out = [];
92
+ let size = 0;
93
+ for (const [i, l] of slice.entries()) {
94
+ const row = `${i + 1} ${l.length > MAX_LINE_CHARS ? `${l.slice(0, MAX_LINE_CHARS)}… [line truncated: ${l.length} characters]` : l}`;
95
+ if (out.length > 0 && size + row.length + 1 > MAX_READ_CHARS)
96
+ break;
97
+ out.push(row);
98
+ size += row.length + 1;
99
+ }
100
+ const body = out.join(`
101
+ `);
102
+ if (out.length < lines.length)
103
+ return `${body}
104
+ (showing lines 1-${out.length} of ${lines.length}; read_file with offset ${out.length + 1} for the rest)`;
105
+ return body;
115
106
  }
116
107
  async function listDir(full) {
117
- const entries = await readdir(full, { withFileTypes: true });
118
- const names = entries.map((e) => e.name + (e.isDirectory() ? "/" : "")).sort();
119
- return names.length > 0 ? names.join("\n") : "(empty directory)";
108
+ const entries = await readdir(full, { withFileTypes: true });
109
+ const names = entries.map((e) => e.name + (e.isDirectory() ? "/" : "")).sort();
110
+ return names.length > 0 ? names.join(`
111
+ `) : "(empty directory)";
120
112
  }
@@ -0,0 +1,49 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readdir } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { display } from "./attach.js";
5
+ const MAX_CANDIDATES = 20000;
6
+ export async function mentionCandidates(cwd, signal = AbortSignal.timeout(5000)) {
7
+ const files = [];
8
+ const dirs = new Set;
9
+ try {
10
+ for await (const full of await listFiles(cwd, signal)) {
11
+ const rel = display(cwd, full);
12
+ files.push(rel);
13
+ for (let i = rel.lastIndexOf("/");i > 0; i = rel.lastIndexOf("/", i - 1)) {
14
+ const dir = rel.slice(0, i + 1);
15
+ if (dirs.has(dir))
16
+ break;
17
+ dirs.add(dir);
18
+ }
19
+ if (files.length + dirs.size >= MAX_CANDIDATES)
20
+ break;
21
+ }
22
+ } catch {}
23
+ return [...dirs, ...files];
24
+ }
25
+ const SKIP_DIRS = new Set([".git", "node_modules"]);
26
+ function gitFiles(root) {
27
+ return new Promise((resolve) => {
28
+ execFile("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], { cwd: root, maxBuffer: 256 * 1024 * 1024, windowsHide: true }, (err, out) => resolve(err ? undefined : [...new Set(out.split("\x00").filter(Boolean))]));
29
+ });
30
+ }
31
+ async function listFiles(root, signal) {
32
+ const tracked = await gitFiles(root);
33
+ if (!tracked)
34
+ return walk(root, signal);
35
+ return tracked.filter((rel) => !rel.split("/").some((seg) => SKIP_DIRS.has(seg))).map((rel) => path.join(root, rel));
36
+ }
37
+ async function* walk(dir, signal) {
38
+ signal.throwIfAborted();
39
+ const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
40
+ for (const e of entries) {
41
+ const full = path.join(dir, e.name);
42
+ if (e.isDirectory()) {
43
+ if (!SKIP_DIRS.has(e.name))
44
+ yield* walk(full, signal);
45
+ } else if (e.isFile()) {
46
+ yield full;
47
+ }
48
+ }
49
+ }