@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,41 +1,21 @@
1
- // 编辑后自动检查:模型一次回复里改了文件,下一次请求模型之前对改过的文件跑项目的检查(类型检查、lint),
2
- // 把发现的问题附在这批修改的最后一个结果后面,模型马上就能看到自己引入的错误。
3
- //
4
- // 在 context.project 里做,而不是 tool.after:一次回复里的几处修改常常要合起来才成立
5
- // (先改函数签名、再改调用方),逐个检查会报出很快就不存在的错误,同一个检查也要多跑几遍。
6
- // 结果先用 ctx.record 写进日志(I-5)再投影进消息,恢复会话后不会重新检查,每次投影都一样。
7
- //
8
- // 检查来源:
9
- // - 自动发现:TypeScript(离文件最近的 tsconfig.json,加上项目里装的 typescript)、Python(PATH 里的 ruff)、Go(go.mod 和 go)
10
- // - 配置:仓库根目录的 .jade/checks.json 和 $JADE_HOME/checks.json,见 CheckConfigFile
11
- // 检查会执行仓库里的代码(node_modules 里的 tsc、配置里的命令),每条命令第一次运行前请用户确认(approve,见 index.ts)。
12
- // 从旧 jade 的 src/plugins/checks.ts 移植,只是把内核插件换成一个 hook(交给 ctx.kernel.hook)。
13
- //
14
- // 只报告改过的文件里的问题;其他文件里的问题只在数量比上一次检查多时报告(例如改了签名,调用方报错)。
15
1
  import { createHash } from "node:crypto";
16
2
  import { existsSync, realpathSync } from "node:fs";
17
3
  import { readFile } from "node:fs/promises";
18
4
  import path from "node:path";
19
- /** 老版本把整个 ChecksState 记在这一个 key 下、每次检查整份重记;恢复老会话时还要读它 */
20
5
  export const CHECKS_KEY = "jade/checks";
21
- /** 每份报告单独一个 key:每次检查日志里只多记这一份,不随会话变长而整份重记 */
22
6
  const RESULT_PREFIX = `${CHECKS_KEY}/result/`;
23
7
  const OTHERS_KEY = `${CHECKS_KEY}/others`;
24
8
  function stateOf(derived) {
25
- const legacy = derived[CHECKS_KEY];
26
- const results = { ...legacy?.results };
27
- for (const [k, v] of Object.entries(derived))
28
- if (k.startsWith(RESULT_PREFIX))
29
- results[k.slice(RESULT_PREFIX.length)] = v;
30
- return { results, others: derived[OTHERS_KEY] ?? legacy?.others ?? {} };
9
+ const legacy = derived[CHECKS_KEY];
10
+ const results = { ...legacy?.results };
11
+ for (const [k, v] of Object.entries(derived))
12
+ if (k.startsWith(RESULT_PREFIX))
13
+ results[k.slice(RESULT_PREFIX.length)] = v;
14
+ return { results, others: derived[OTHERS_KEY] ?? legacy?.others ?? {} };
31
15
  }
32
- export const WRITE_TOOLS = new Set(["write_file", "edit_file", "multi_edit"]);
33
- const DEFAULT_TIMEOUT_MS = 120_000;
34
- /** 附给模型的文字上限 */
16
+ const DEFAULT_TIMEOUT_MS = 120000;
35
17
  const MAX_REPORT_CHARS = 6000;
36
- /** 每个检查最多列出的问题数 */
37
18
  const MAX_PROBLEMS = 30;
38
- /** 第一次运行时列出的其他文件里的问题条数 */
39
19
  const FIRST_RUN_OTHERS = 10;
40
20
  const HEADER = "[Checks jade ran after your edits; this is tool output, not a message from the user]";
41
21
  const TS_EXT = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
@@ -43,325 +23,309 @@ const slash = (p) => p.split(path.sep).join("/");
43
23
  const quote = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
44
24
  const sameFile = process.platform === "win32" ? (a, b) => a.toLowerCase() === b.toLowerCase() : (a, b) => a === b;
45
25
  function canonical(p) {
46
- try {
47
- return realpathSync.native(p);
48
- }
49
- catch {
50
- return p;
51
- }
26
+ try {
27
+ return realpathSync.native(p);
28
+ } catch {
29
+ return p;
30
+ }
52
31
  }
53
32
  function within(base, p) {
54
- const rel = path.relative(base, p);
55
- return rel === "" || !(rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel));
33
+ const rel = path.relative(base, p);
34
+ return rel === "" || !(rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel));
56
35
  }
57
- /** 从 dir 往上(不超过 root)找第一个含 name 的目录 */
58
36
  function findUp(dir, root, name) {
59
- let d = dir;
60
- for (;;) {
61
- if (!within(root, d))
62
- return undefined;
63
- if (existsSync(path.join(d, name)))
64
- return d;
65
- if (sameFile(d, root))
66
- return undefined;
67
- const parent = path.dirname(d);
68
- if (parent === d)
69
- return undefined;
70
- d = parent;
71
- }
37
+ let d = dir;
38
+ for (;; ) {
39
+ if (!within(root, d))
40
+ return;
41
+ if (existsSync(path.join(d, name)))
42
+ return d;
43
+ if (sameFile(d, root))
44
+ return;
45
+ const parent = path.dirname(d);
46
+ if (parent === d)
47
+ return;
48
+ d = parent;
49
+ }
72
50
  }
73
- /**
74
- * 把检查的输出分成一个个问题。以"路径:行"或"路径(行,列)"开头的行开始一个新问题,
75
- * 后面认不出路径的行(多行说明、代码片段)归到它下面;第一个问题之前的行单独算一个没有文件的问题
76
- */
77
51
  export function parseProblems(output, cwd) {
78
- // 路径里可以有括号(Next.js 的 app/(group)/page.tsx),只是不能以括号开头
79
- const START = /^\s*((?:[A-Za-z]:[\\/])?[^\s:()][^:]*?)(?:\(\d+,\d+\)|:\d+(?::\d+)?)(?=[:\s]|$)/;
80
- const out = [];
81
- let cur;
82
- for (const line of output.split(/\r?\n/)) {
83
- const m = START.exec(line);
84
- if (m && /[\\/.]/.test(m[1])) {
85
- cur = { file: path.resolve(cwd, m[1].replace(/^\.\//, "")), text: line.trimEnd() };
86
- out.push(cur);
87
- }
88
- else if (line.trim()) {
89
- if (cur)
90
- cur.text += `\n${line.trimEnd()}`;
91
- else {
92
- cur = { text: line.trimEnd() };
93
- out.push(cur);
94
- }
95
- }
52
+ const START = /^\s*((?:[A-Za-z]:[\\/])?[^\s:()][^:]*?)(?:\(\d+,\d+\)|:\d+(?::\d+)?)(?=[:\s]|$)/;
53
+ const out = [];
54
+ let cur;
55
+ for (const line of output.split(/\r?\n/)) {
56
+ const m = START.exec(line);
57
+ if (m && /[\\/.]/.test(m[1])) {
58
+ cur = { file: path.resolve(cwd, m[1].replace(/^\.\//, "")), text: line.trimEnd() };
59
+ out.push(cur);
60
+ } else if (line.trim()) {
61
+ if (cur)
62
+ cur.text += `
63
+ ${line.trimEnd()}`;
64
+ else {
65
+ cur = { text: line.trimEnd() };
66
+ out.push(cur);
67
+ }
96
68
  }
97
- return out;
69
+ }
70
+ return out;
98
71
  }
99
72
  export function checks(opts) {
100
- const id = opts.id ?? "jade/checks";
101
- const which = opts.which ?? (() => null);
102
- const runtime = opts.runtime ?? process.execPath;
103
- /** 本会话里不再运行的检查:用户拒绝了,或者输出认不出来 */
104
- const disabled = new Set();
105
- const keyOf = (c) => `${c.name}\0${c.cwd}`;
106
- let config;
107
- const loadConfig = () => (config ??= (async () => {
108
- let auto = true;
109
- const list = [];
110
- for (const [file, base] of [
111
- [path.join(opts.home, "checks.json"), opts.root],
112
- [path.join(opts.root, ".jade", "checks.json"), opts.root],
113
- ]) {
114
- let parsed;
115
- try {
116
- parsed = JSON.parse(await readFile(file, "utf8"));
117
- }
118
- catch {
119
- continue;
120
- }
121
- if (parsed.auto === false)
122
- auto = false;
123
- for (const c of parsed.checks ?? []) {
124
- if (typeof c?.name !== "string" || typeof c.command !== "string")
125
- continue;
126
- list.push({
127
- name: c.name,
128
- command: c.command,
129
- cwd: path.resolve(base, c.cwd ?? "."),
130
- extensions: (c.extensions ?? []).map((e) => (e.startsWith(".") ? e : `.${e}`).toLowerCase()),
131
- timeoutMs: typeof c.timeout_ms === "number" && c.timeout_ms > 0 ? c.timeout_ms : DEFAULT_TIMEOUT_MS,
132
- source: "config",
133
- });
134
- }
135
- }
136
- return { auto, checks: list };
137
- })());
138
- /** 自动发现:对一个文件适用的检查 */
139
- function detect(file) {
140
- const ext = path.extname(file).toLowerCase();
141
- const dir = path.dirname(file);
142
- if (TS_EXT.includes(ext)) {
143
- const project = findUp(dir, opts.root, "tsconfig.json");
144
- if (!project)
145
- return undefined;
146
- const modules = findUp(project, opts.root, path.join("node_modules", "typescript", "bin", "tsc"));
147
- if (!modules)
148
- return undefined;
149
- const tsc = path.join(modules, "node_modules", "typescript", "bin", "tsc");
150
- const cache = path.join(opts.home, "cache", `tsc-${createHash("sha256").update(project).digest("hex").slice(0, 16)}.tsbuildinfo`);
151
- return {
152
- name: "tsc",
153
- command: `${quote(slash(runtime))} ${quote(slash(tsc))} --noEmit --pretty false --incremental --tsBuildInfoFile ${quote(slash(cache))} -p .`,
154
- cwd: project,
155
- extensions: TS_EXT,
156
- timeoutMs: DEFAULT_TIMEOUT_MS,
157
- source: "auto",
158
- };
159
- }
160
- if (ext === ".py" || ext === ".pyi") {
161
- if (!which("ruff"))
162
- return undefined;
163
- return {
164
- name: "ruff",
165
- command: "ruff check --output-format concise --no-fix --quiet {files}",
166
- cwd: opts.root,
167
- extensions: [".py", ".pyi"],
168
- timeoutMs: DEFAULT_TIMEOUT_MS,
169
- source: "auto",
170
- };
171
- }
172
- if (ext === ".go") {
173
- const mod = findUp(dir, opts.root, "go.mod");
174
- if (!mod || !which("go"))
175
- return undefined;
176
- return { name: "go vet", command: "go vet {dirs}", cwd: mod, extensions: [".go"], timeoutMs: DEFAULT_TIMEOUT_MS, source: "auto" };
177
- }
178
- return undefined;
73
+ const id = opts.id ?? "jade/checks";
74
+ const which = opts.which ?? (() => null);
75
+ const runtime = opts.runtime ?? process.execPath;
76
+ const disabled = new Set;
77
+ const keyOf = (c) => `${c.name}\x00${c.cwd}`;
78
+ let config;
79
+ const loadConfig = () => config ??= (async () => {
80
+ let auto = true;
81
+ const list = [];
82
+ for (const [file, base] of [
83
+ [path.join(opts.home, "checks.json"), opts.root],
84
+ [path.join(opts.root, ".jade", "checks.json"), opts.root]
85
+ ]) {
86
+ let parsed;
87
+ try {
88
+ parsed = JSON.parse(await readFile(file, "utf8"));
89
+ } catch {
90
+ continue;
91
+ }
92
+ if (parsed.auto === false)
93
+ auto = false;
94
+ for (const c of parsed.checks ?? []) {
95
+ if (typeof c?.name !== "string" || typeof c.command !== "string")
96
+ continue;
97
+ list.push({
98
+ name: c.name,
99
+ command: c.command,
100
+ cwd: path.resolve(base, c.cwd ?? "."),
101
+ extensions: (c.extensions ?? []).map((e) => (e.startsWith(".") ? e : `.${e}`).toLowerCase()),
102
+ timeoutMs: typeof c.timeout_ms === "number" && c.timeout_ms > 0 ? c.timeout_ms : DEFAULT_TIMEOUT_MS,
103
+ source: "config"
104
+ });
105
+ }
179
106
  }
180
- /** 检查 → 它要检查的文件 */
181
- async function plan(files) {
182
- const { auto, checks: configured } = await loadConfig();
183
- const out = new Map();
184
- const add = (check, file) => {
185
- const k = keyOf(check);
186
- const entry = out.get(k) ?? { check, files: [] };
187
- if (!entry.files.some((f) => sameFile(f, file)))
188
- entry.files.push(file);
189
- out.set(k, entry);
190
- };
191
- for (const file of files) {
192
- const ext = path.extname(file).toLowerCase();
193
- let matched = false;
194
- for (const c of configured) {
195
- if ((c.extensions.length === 0 || c.extensions.includes(ext)) && within(c.cwd, file)) {
196
- add(c, file);
197
- matched = true;
198
- }
199
- }
200
- // 配置了同类文件的检查时,不再自动发现
201
- if (!matched && auto) {
202
- const c = detect(file);
203
- if (c)
204
- add(c, file);
205
- }
206
- }
207
- return out;
107
+ return { auto, checks: list };
108
+ })();
109
+ function detect(file) {
110
+ const ext = path.extname(file).toLowerCase();
111
+ const dir = path.dirname(file);
112
+ if (TS_EXT.includes(ext)) {
113
+ const project = findUp(dir, opts.root, "tsconfig.json");
114
+ if (!project)
115
+ return;
116
+ const modules = findUp(project, opts.root, path.join("node_modules", "typescript", "bin", "tsc"));
117
+ if (!modules)
118
+ return;
119
+ const tsc = path.join(modules, "node_modules", "typescript", "bin", "tsc");
120
+ const cache = path.join(opts.home, "cache", `tsc-${createHash("sha256").update(project).digest("hex").slice(0, 16)}.tsbuildinfo`);
121
+ return {
122
+ name: "tsc",
123
+ command: `${quote(slash(runtime))} ${quote(slash(tsc))} --noEmit --pretty false --incremental --tsBuildInfoFile ${quote(slash(cache))} -p .`,
124
+ cwd: project,
125
+ extensions: TS_EXT,
126
+ timeoutMs: DEFAULT_TIMEOUT_MS,
127
+ source: "auto"
128
+ };
208
129
  }
209
- function commandFor(check, files) {
210
- const rel = files.map((f) => slash(path.relative(check.cwd, f)) || ".");
211
- const dirs = [...new Set(rel.map((f) => `./${path.posix.dirname(f)}`.replace(/\/\.$/, "")))];
212
- return check.command.replaceAll("{files}", rel.map(quote).join(" ")).replaceAll("{dirs}", dirs.map(quote).join(" "));
130
+ if (ext === ".py" || ext === ".pyi") {
131
+ if (!which("ruff"))
132
+ return;
133
+ return {
134
+ name: "ruff",
135
+ command: "ruff check --output-format concise --no-fix --quiet {files}",
136
+ cwd: opts.root,
137
+ extensions: [".py", ".pyi"],
138
+ timeoutMs: DEFAULT_TIMEOUT_MS,
139
+ source: "auto"
140
+ };
213
141
  }
214
- const clip = (s, n) => (s.length > n ? `${s.slice(0, n)}\n…` : s);
215
- /** 运行一批修改对应的检查,返回给模型的报告(没有要说的时为空串)和给用户看的摘要 */
216
- async function runAll(files, state, ctx) {
217
- const parts = [];
218
- const summary = [];
219
- const others = { ...state.others };
220
- for (const { check, files: targets } of (await plan(files)).values()) {
221
- const k = keyOf(check);
222
- if (disabled.has(k))
223
- continue;
224
- if (!(await opts.approve(check, ctx.signal))) {
225
- disabled.add(k);
226
- continue;
227
- }
228
- const where = sameFile(check.cwd, opts.cwd) ? "" : ` (in ${slash(path.relative(opts.cwd, check.cwd)) || "."})`;
229
- const r = await opts.run(commandFor(check, targets), { cwd: check.cwd, timeoutMs: check.timeoutMs, signal: ctx.signal });
230
- if (r.timedOut) {
231
- parts.push(`${check.name}${where}: timed out after ${Math.round(check.timeoutMs / 1000)}s; jade will not run it again in this session.`);
232
- summary.push({ name: check.name, problems: 0, failed: "timed out" });
233
- disabled.add(k);
234
- continue;
235
- }
236
- const problems = r.code === 0 ? [] : parseProblems(r.output, check.cwd);
237
- const mine = problems.filter((p) => p.file && targets.some((t) => sameFile(t, p.file)));
238
- const elsewhere = problems.filter((p) => p.file && !targets.some((t) => sameFile(t, p.file)));
239
- if (r.code !== 0 && mine.length === 0 && elsewhere.length === 0) {
240
- // 失败了却认不出任何问题:多半是检查本身的问题(配置、环境),说一次就停用
241
- parts.push(`${check.name}${where} failed (exit code ${r.code}) without reporting problems in files; jade will not run it again in this session:\n${clip(r.output.trim(), 1500)}`);
242
- summary.push({ name: check.name, problems: 0, failed: `exit code ${r.code}` });
243
- disabled.add(k);
244
- continue;
245
- }
246
- const before = state.others[k];
247
- others[k] = elsewhere.length;
248
- const lines = [];
249
- if (mine.length > 0) {
250
- lines.push(`${check.name}${where}: ${mine.length} problem${mine.length > 1 ? "s" : ""} in the files you changed:`);
251
- lines.push(...mine.slice(0, MAX_PROBLEMS).map((p) => p.text));
252
- if (mine.length > MAX_PROBLEMS)
253
- lines.push(`… ${mine.length - MAX_PROBLEMS} more`);
254
- }
255
- else
256
- lines.push(`${check.name}${where}: no problems in the files you changed.`);
257
- if (before !== undefined && elsewhere.length > before) {
258
- lines.push(`${check.name}: ${elsewhere.length - before} more problem${elsewhere.length - before > 1 ? "s" : ""} in other files than before your edits (${elsewhere.length} in total), possibly caused by them:`);
259
- lines.push(...elsewhere.slice(0, 10).map((p) => p.text));
260
- }
261
- else if (before === undefined && elsewhere.length > 0) {
262
- // 本会话第一次运行,没有基线:列出几条让模型自己判断,改了函数签名弄坏的调用方也在这里
263
- lines.push(`${check.name}: also ${elsewhere.length} problem${elsewhere.length > 1 ? "s" : ""} in other files. This is the first check in this session, so jade cannot tell which predate your edits; check whether your changes caused any of these:`);
264
- lines.push(...elsewhere.slice(0, FIRST_RUN_OTHERS).map((p) => p.text));
265
- if (elsewhere.length > FIRST_RUN_OTHERS)
266
- lines.push(`… ${elsewhere.length - FIRST_RUN_OTHERS} more`);
267
- }
268
- parts.push(lines.join("\n"));
269
- summary.push({ name: check.name, problems: mine.length, others: before !== undefined && elsewhere.length > before ? elsewhere.length - before : undefined });
270
- }
271
- const text = parts.length ? clip(`${HEADER}\n${parts.join("\n\n")}`, MAX_REPORT_CHARS) : "";
272
- return { text, summary, others };
142
+ if (ext === ".go") {
143
+ const mod = findUp(dir, opts.root, "go.mod");
144
+ if (!mod || !which("go"))
145
+ return;
146
+ return { name: "go vet", command: "go vet {dirs}", cwd: mod, extensions: [".go"], timeoutMs: DEFAULT_TIMEOUT_MS, source: "auto" };
273
147
  }
274
- /** 最后一批修改:最后一条消息是工具结果,前一条是发出这些调用的回复。返回成功的写入调用 */
275
- function lastBatch(messages) {
276
- const results = messages.at(-1);
277
- const reply = messages.at(-2);
278
- if (results?.role !== "user" || reply?.role !== "assistant")
279
- return undefined;
280
- const ok = new Set(results.content.flatMap((b) => (b.kind === "tool_result" && !b.isError ? [b.toolUseId] : [])));
281
- const ids = [];
282
- const files = [];
283
- for (const b of reply.content) {
284
- if (b.kind !== "tool_use" || !WRITE_TOOLS.has(b.name) || !ok.has(b.id))
285
- continue;
286
- const p = b.input?.path;
287
- if (typeof p !== "string")
288
- continue;
289
- ids.push(b.id);
290
- // 和 root 一样解析符号链接、短文件名,否则判断不出文件在不在某个目录里
291
- const full = canonical(path.resolve(opts.cwd, p));
292
- if (!files.some((f) => sameFile(f, full)))
293
- files.push(full);
148
+ return;
149
+ }
150
+ async function plan(files) {
151
+ const { auto, checks: configured } = await loadConfig();
152
+ const out = new Map;
153
+ const add = (check, file) => {
154
+ const k = keyOf(check);
155
+ const entry = out.get(k) ?? { check, files: [] };
156
+ if (!entry.files.some((f) => sameFile(f, file)))
157
+ entry.files.push(file);
158
+ out.set(k, entry);
159
+ };
160
+ for (const file of files) {
161
+ const ext = path.extname(file).toLowerCase();
162
+ let matched = false;
163
+ for (const c of configured) {
164
+ if ((c.extensions.length === 0 || c.extensions.includes(ext)) && within(c.cwd, file)) {
165
+ add(c, file);
166
+ matched = true;
294
167
  }
295
- return ids.length ? { ids, files } : undefined;
168
+ }
169
+ if (!matched && auto) {
170
+ const c = detect(file);
171
+ if (c)
172
+ add(c, file);
173
+ }
296
174
  }
297
- /** 把记下的报告附到对应的工具结果后面 */
298
- function inject(messages, results) {
299
- return messages.map((m) => {
300
- if (m.role !== "user" || !m.content.some((b) => b.kind === "tool_result" && results[b.toolUseId]))
301
- return m;
302
- return {
303
- ...m,
304
- content: m.content.map((b) => {
305
- if (b.kind !== "tool_result" || !results[b.toolUseId])
306
- return b;
307
- // 检查输出来自仓库里的代码,不受信任
308
- return { ...b, content: [...b.content, { kind: "text", text: results[b.toolUseId], origin: { by: "plugin", id }, trust: "untrusted" }] };
309
- }),
310
- };
311
- });
175
+ return out;
176
+ }
177
+ function commandFor(check, files) {
178
+ const rel = files.map((f) => slash(path.relative(check.cwd, f)) || ".");
179
+ const dirs = [...new Set(rel.map((f) => `./${path.posix.dirname(f)}`.replace(/\/\.$/, "")))];
180
+ return check.command.replaceAll("{files}", rel.map(quote).join(" ")).replaceAll("{dirs}", dirs.map(quote).join(" "));
181
+ }
182
+ const clip = (s, n) => s.length > n ? `${s.slice(0, n)}
183
+ …` : s;
184
+ async function runAll(files, state, ctx) {
185
+ const parts = [];
186
+ const summary = [];
187
+ const others = { ...state.others };
188
+ for (const { check, files: targets } of (await plan(files)).values()) {
189
+ const k = keyOf(check);
190
+ if (disabled.has(k))
191
+ continue;
192
+ if (!await opts.approve(check, ctx.signal)) {
193
+ disabled.add(k);
194
+ continue;
195
+ }
196
+ const where = sameFile(check.cwd, opts.cwd) ? "" : ` (in ${slash(path.relative(opts.cwd, check.cwd)) || "."})`;
197
+ const r = await opts.run(commandFor(check, targets), { cwd: check.cwd, timeoutMs: check.timeoutMs, signal: ctx.signal });
198
+ if (r.timedOut) {
199
+ parts.push(`${check.name}${where}: timed out after ${Math.round(check.timeoutMs / 1000)}s; jade will not run it again in this session.`);
200
+ summary.push({ name: check.name, problems: 0, failed: "timed out" });
201
+ disabled.add(k);
202
+ continue;
203
+ }
204
+ const problems = r.code === 0 ? [] : parseProblems(r.output, check.cwd);
205
+ const mine = problems.filter((p) => p.file && targets.some((t) => sameFile(t, p.file)));
206
+ const elsewhere = problems.filter((p) => p.file && !targets.some((t) => sameFile(t, p.file)));
207
+ if (r.code !== 0 && mine.length === 0 && elsewhere.length === 0) {
208
+ parts.push(`${check.name}${where} failed (exit code ${r.code}) without reporting problems in files; jade will not run it again in this session:
209
+ ${clip(r.output.trim(), 1500)}`);
210
+ summary.push({ name: check.name, problems: 0, failed: `exit code ${r.code}` });
211
+ disabled.add(k);
212
+ continue;
213
+ }
214
+ const before = state.others[k];
215
+ others[k] = elsewhere.length;
216
+ const lines = [];
217
+ if (mine.length > 0) {
218
+ lines.push(`${check.name}${where}: ${mine.length} problem${mine.length > 1 ? "s" : ""} in the files you changed:`);
219
+ lines.push(...mine.slice(0, MAX_PROBLEMS).map((p) => p.text));
220
+ if (mine.length > MAX_PROBLEMS)
221
+ lines.push(`… ${mine.length - MAX_PROBLEMS} more`);
222
+ } else
223
+ lines.push(`${check.name}${where}: no problems in the files you changed.`);
224
+ if (before !== undefined && elsewhere.length > before) {
225
+ lines.push(`${check.name}: ${elsewhere.length - before} more problem${elsewhere.length - before > 1 ? "s" : ""} in other files than before your edits (${elsewhere.length} in total), possibly caused by them:`);
226
+ lines.push(...elsewhere.slice(0, 10).map((p) => p.text));
227
+ } else if (before === undefined && elsewhere.length > 0) {
228
+ lines.push(`${check.name}: also ${elsewhere.length} problem${elsewhere.length > 1 ? "s" : ""} in other files. This is the first check in this session, so jade cannot tell which predate your edits; check whether your changes caused any of these:`);
229
+ lines.push(...elsewhere.slice(0, FIRST_RUN_OTHERS).map((p) => p.text));
230
+ if (elsewhere.length > FIRST_RUN_OTHERS)
231
+ lines.push(`… ${elsewhere.length - FIRST_RUN_OTHERS} more`);
232
+ }
233
+ parts.push(lines.join(`
234
+ `));
235
+ summary.push({ name: check.name, problems: mine.length, others: before !== undefined && elsewhere.length > before ? elsewhere.length - before : undefined });
312
236
  }
313
- const self = {
314
- enabled: true,
315
- reset() {
316
- disabled.clear();
317
- },
318
- async resolve(files) {
319
- return [...(await plan(files)).values()].map((e) => e.check);
320
- },
321
- hook: {
322
- kind: "transform",
323
- point: "context.project",
324
- // 检查可能要跑一两分钟,第一次还要等用户确认;出错或超时就跳过,不让这一轮失败
325
- timeoutMs: 900_000,
326
- optional: true,
327
- fn: async (messages, ctx) => {
328
- const state = stateOf(ctx.derived);
329
- const batch = self.enabled ? lastBatch(messages) : undefined;
330
- const last = batch?.ids.at(-1);
331
- if (batch && last && !(last in state.results)) {
332
- const { text, summary, others } = await runAll(batch.files, state, ctx);
333
- if (summary.length > 0 || text) {
334
- await ctx.record(`${RESULT_PREFIX}${last}`, text);
335
- // others 是 state.others 加上这次的数,有变化才记
336
- if (Object.keys(others).some((k) => others[k] !== state.others[k]))
337
- await ctx.record(OTHERS_KEY, others);
338
- await ctx.emit("checked", { toolUseId: last, files: batch.files, summary, report: text });
339
- return inject(messages, { ...state.results, [last]: text });
340
- }
341
- }
342
- return inject(messages, state.results);
343
- },
344
- },
345
- };
346
- return self;
347
- }
348
- /** 会话里成功改过的文件(/checks 显示用):所有写入调用里结果不是错误的 */
349
- export function changedFiles(messages, cwd) {
350
- const ok = new Set(messages.flatMap((m) => (m.role === "user" ? m.content.flatMap((b) => (b.kind === "tool_result" && !b.isError ? [b.toolUseId] : [])) : [])));
237
+ const text = parts.length ? clip(`${HEADER}
238
+ ${parts.join(`
239
+
240
+ `)}`, MAX_REPORT_CHARS) : "";
241
+ return { text, summary, others };
242
+ }
243
+ function lastBatch(messages) {
244
+ const results = messages.at(-1);
245
+ const reply = messages.at(-2);
246
+ if (results?.role !== "user" || reply?.role !== "assistant")
247
+ return;
248
+ const ok = new Set(results.content.flatMap((b) => b.kind === "tool_result" && !b.isError ? [b.toolUseId] : []));
249
+ const ids = [];
351
250
  const files = [];
352
- for (const m of messages) {
353
- if (m.role !== "assistant")
354
- continue;
355
- for (const b of m.content) {
356
- if (b.kind !== "tool_use" || !WRITE_TOOLS.has(b.name) || !ok.has(b.id))
357
- continue;
358
- const p = b.input?.path;
359
- if (typeof p !== "string")
360
- continue;
361
- const full = canonical(path.resolve(cwd, p));
362
- if (!files.some((f) => sameFile(f, full)))
363
- files.push(full);
251
+ for (const b of reply.content) {
252
+ const field = b.kind === "tool_use" && ok.has(b.id) ? opts.writes(b.name) : undefined;
253
+ if (field === undefined || b.kind !== "tool_use")
254
+ continue;
255
+ const p = b.input?.[field];
256
+ if (typeof p !== "string")
257
+ continue;
258
+ ids.push(b.id);
259
+ const full = canonical(path.resolve(opts.cwd, p));
260
+ if (!files.some((f) => sameFile(f, full)))
261
+ files.push(full);
262
+ }
263
+ return ids.length ? { ids, files } : undefined;
264
+ }
265
+ function inject(messages, results) {
266
+ return messages.map((m) => {
267
+ if (m.role !== "user" || !m.content.some((b) => b.kind === "tool_result" && results[b.toolUseId]))
268
+ return m;
269
+ return {
270
+ ...m,
271
+ content: m.content.map((b) => {
272
+ if (b.kind !== "tool_result" || !results[b.toolUseId])
273
+ return b;
274
+ return { ...b, content: [...b.content, { kind: "text", text: results[b.toolUseId], origin: { by: "plugin", id }, trust: "untrusted" }] };
275
+ })
276
+ };
277
+ });
278
+ }
279
+ const self = {
280
+ enabled: true,
281
+ reset() {
282
+ disabled.clear();
283
+ },
284
+ async resolve(files) {
285
+ return [...(await plan(files)).values()].map((e) => e.check);
286
+ },
287
+ hook: {
288
+ kind: "transform",
289
+ point: "context.project",
290
+ timeoutMs: 900000,
291
+ optional: true,
292
+ fn: async (messages, ctx) => {
293
+ const state = stateOf(ctx.derived);
294
+ const batch = self.enabled ? lastBatch(messages) : undefined;
295
+ const last = batch?.ids.at(-1);
296
+ if (batch && last && !(last in state.results)) {
297
+ const { text, summary, others } = await runAll(batch.files, state, ctx);
298
+ if (summary.length > 0 || text) {
299
+ await ctx.record(`${RESULT_PREFIX}${last}`, text);
300
+ if (Object.keys(others).some((k) => others[k] !== state.others[k]))
301
+ await ctx.record(OTHERS_KEY, others);
302
+ await ctx.emit("checked", { toolUseId: last, files: batch.files, summary, report: text });
303
+ return inject(messages, { ...state.results, [last]: text });
304
+ }
364
305
  }
306
+ return inject(messages, state.results);
307
+ }
308
+ }
309
+ };
310
+ return self;
311
+ }
312
+ export function changedFiles(messages, cwd, writes) {
313
+ const ok = new Set(messages.flatMap((m) => m.role === "user" ? m.content.flatMap((b) => b.kind === "tool_result" && !b.isError ? [b.toolUseId] : []) : []));
314
+ const files = [];
315
+ for (const m of messages) {
316
+ if (m.role !== "assistant")
317
+ continue;
318
+ for (const b of m.content) {
319
+ const field = b.kind === "tool_use" && ok.has(b.id) ? writes(b.name) : undefined;
320
+ if (field === undefined || b.kind !== "tool_use")
321
+ continue;
322
+ const p = b.input?.[field];
323
+ if (typeof p !== "string")
324
+ continue;
325
+ const full = canonical(path.resolve(cwd, p));
326
+ if (!files.some((f) => sameFile(f, full)))
327
+ files.push(full);
365
328
  }
366
- return files;
329
+ }
330
+ return files;
367
331
  }