@uncarved/jade 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/dist/api.d.ts +1 -1
  2. package/dist/api.js +1 -1
  3. package/dist/host.d.ts +2 -0
  4. package/dist/host.js +39 -5
  5. package/dist/host.js.map +1 -1
  6. package/dist/remote.js +5 -0
  7. package/dist/remote.js.map +1 -1
  8. package/dist/session.d.ts +7 -0
  9. package/dist/session.js +482 -27
  10. package/dist/session.js.map +1 -1
  11. package/package.json +4 -4
  12. package/plugins/approval/index.ts +36 -14
  13. package/plugins/approval/policy.ts +15 -10
  14. package/plugins/approval/review.ts +9 -5
  15. package/plugins/checks/checks.ts +10 -7
  16. package/plugins/checks/index.ts +13 -13
  17. package/plugins/checks/plugin.json +1 -1
  18. package/plugins/checks/project.ts +37 -38
  19. package/plugins/commands/index.ts +27 -3
  20. package/plugins/compact/compact.ts +13 -5
  21. package/plugins/compact/index.ts +20 -3
  22. package/plugins/compact/style.ts +13 -14
  23. package/plugins/completions/index.ts +35 -0
  24. package/plugins/completions/plugin.json +7 -0
  25. package/plugins/copy/index.ts +46 -0
  26. package/plugins/copy/plugin.json +7 -0
  27. package/plugins/editor/index.ts +10 -4
  28. package/plugins/fs/diff.ts +7 -6
  29. package/plugins/fs/fs.ts +8 -4
  30. package/plugins/fs/grep.ts +42 -9
  31. package/plugins/fs/index.ts +2 -7
  32. package/plugins/fs/plugin.json +1 -1
  33. package/plugins/fs/renderers.ts +16 -15
  34. package/plugins/fs/style.ts +16 -15
  35. package/plugins/hooks/index.ts +3 -2
  36. package/plugins/keys/index.ts +5 -1
  37. package/plugins/mcp/index.ts +197 -78
  38. package/plugins/mcp/install.ts +5 -3
  39. package/plugins/mcp/mcp.ts +163 -11
  40. package/plugins/mcp/plugin.json +2 -1
  41. package/plugins/mcp/project.ts +47 -50
  42. package/plugins/memory/index.ts +4 -4
  43. package/plugins/memory/style.ts +13 -14
  44. package/plugins/mentions/candidates.ts +67 -0
  45. package/plugins/mentions/index.ts +12 -5
  46. package/plugins/mentions/plugin.json +1 -1
  47. package/plugins/mentions/style.ts +13 -14
  48. package/plugins/models/configure.ts +10 -9
  49. package/plugins/models/index.ts +27 -1
  50. package/plugins/modes/index.ts +13 -2
  51. package/plugins/print/index.ts +7 -4
  52. package/plugins/prompts/index.ts +0 -0
  53. package/plugins/renderers/index.ts +10 -5
  54. package/plugins/repeats/index.ts +8 -8
  55. package/plugins/schedule/index.ts +2 -0
  56. package/plugins/screenshot/browser.ts +10 -0
  57. package/plugins/sessions/index.ts +48 -2
  58. package/plugins/shell/index.ts +20 -25
  59. package/plugins/shell/plugin.json +1 -2
  60. package/plugins/shell/renderers.ts +9 -7
  61. package/plugins/shell/shell.ts +3 -1
  62. package/plugins/skills/index.ts +28 -19
  63. package/plugins/skills/project.ts +12 -7
  64. package/plugins/steer/index.ts +5 -4
  65. package/plugins/task/index.ts +80 -50
  66. package/plugins/task/plugin.json +6 -2
  67. package/plugins/task/style.ts +13 -14
  68. package/plugins/task/subagent.ts +67 -184
  69. package/plugins/todo/index.ts +39 -9
  70. package/plugins/tools/index.ts +9 -2
  71. package/plugins/tui/frontend.ts +139 -89
  72. package/plugins/tui/index.ts +2 -3
  73. package/plugins/tui/mentions.ts +11 -80
  74. package/plugins/tui/plugin.json +1 -1
  75. package/plugins/tui/screen.ts +55 -5
  76. package/plugins/tui/transcript.ts +17 -7
  77. package/plugins/tui/tui.ts +337 -101
  78. package/plugins/tui/vendor.ts +1 -1
  79. package/plugins/undo/checkpoint.ts +5 -3
  80. package/plugins/undo/index.ts +43 -14
  81. package/plugins/undo/style.ts +13 -14
  82. package/plugins/web/index.ts +7 -18
  83. package/plugins/web/plugin.json +1 -1
  84. package/plugins-dist/approval/index.js +363 -418
  85. package/plugins-dist/approval/policy.js +391 -508
  86. package/plugins-dist/approval/review.js +132 -158
  87. package/plugins-dist/approval/schema.js +50 -55
  88. package/plugins-dist/ask/index.js +115 -129
  89. package/plugins-dist/budget/index.js +27 -31
  90. package/plugins-dist/checks/checks.js +293 -329
  91. package/plugins-dist/checks/index.js +119 -139
  92. package/plugins-dist/checks/plugin.json +2 -1
  93. package/plugins-dist/checks/project.js +57 -65
  94. package/plugins-dist/commands/index.js +47 -29
  95. package/plugins-dist/compact/compact.js +233 -249
  96. package/plugins-dist/compact/index.js +98 -95
  97. package/plugins-dist/compact/style.js +9 -14
  98. package/plugins-dist/completions/index.js +30 -0
  99. package/plugins-dist/completions/plugin.json +9 -0
  100. package/plugins-dist/continue/index.js +40 -52
  101. package/plugins-dist/copy/index.js +40 -0
  102. package/plugins-dist/copy/plugin.json +9 -0
  103. package/plugins-dist/cost/index.js +98 -115
  104. package/plugins-dist/custom-commands/index.js +55 -72
  105. package/plugins-dist/editor/index.js +64 -72
  106. package/plugins-dist/fs/diff.js +111 -124
  107. package/plugins-dist/fs/fs.js +426 -469
  108. package/plugins-dist/fs/grep.js +262 -253
  109. package/plugins-dist/fs/index.js +20 -34
  110. package/plugins-dist/fs/plugin.json +1 -2
  111. package/plugins-dist/fs/renderers.js +100 -112
  112. package/plugins-dist/fs/style.js +11 -15
  113. package/plugins-dist/fs/sys.js +31 -43
  114. package/plugins-dist/hooks/index.js +107 -127
  115. package/plugins-dist/keys/index.js +27 -31
  116. package/plugins-dist/mcp/index.js +271 -199
  117. package/plugins-dist/mcp/install.js +123 -137
  118. package/plugins-dist/mcp/mcp.js +638 -577
  119. package/plugins-dist/mcp/plugin.json +3 -1
  120. package/plugins-dist/mcp/project.js +98 -115
  121. package/plugins-dist/memory/index.js +83 -88
  122. package/plugins-dist/memory/memory.js +111 -128
  123. package/plugins-dist/memory/style.js +9 -14
  124. package/plugins-dist/mentions/attach.js +91 -99
  125. package/plugins-dist/mentions/candidates.js +49 -0
  126. package/plugins-dist/mentions/index.js +71 -81
  127. package/plugins-dist/mentions/plugin.json +2 -1
  128. package/plugins-dist/mentions/style.js +9 -14
  129. package/plugins-dist/models/config.js +29 -43
  130. package/plugins-dist/models/configure.js +392 -473
  131. package/plugins-dist/models/context.js +14 -22
  132. package/plugins-dist/models/index.js +182 -189
  133. package/plugins-dist/models/provider.js +243 -307
  134. package/plugins-dist/models/saved.js +59 -71
  135. package/plugins-dist/modes/index.js +138 -165
  136. package/plugins-dist/plugins/index.js +34 -34
  137. package/plugins-dist/print/index.js +192 -175
  138. package/plugins-dist/prompts/index.js +81 -89
  139. package/plugins-dist/prompts/notes.js +31 -37
  140. package/plugins-dist/prompts/prompts.js +155 -193
  141. package/plugins-dist/prompts/results.js +40 -53
  142. package/plugins-dist/prompts/sys.js +39 -50
  143. package/plugins-dist/renderers/index.js +32 -32
  144. package/plugins-dist/repeats/index.js +131 -174
  145. package/plugins-dist/schedule/cron.js +49 -56
  146. package/plugins-dist/schedule/index.js +229 -247
  147. package/plugins-dist/schedule/store.js +93 -109
  148. package/plugins-dist/scratch/index.js +12 -18
  149. package/plugins-dist/screenshot/browser.js +136 -154
  150. package/plugins-dist/screenshot/index.js +37 -46
  151. package/plugins-dist/screenshot/sys.js +53 -65
  152. package/plugins-dist/screenshot/tool.js +98 -126
  153. package/plugins-dist/sessions/index.js +149 -117
  154. package/plugins-dist/shell/index.js +115 -135
  155. package/plugins-dist/shell/plugin.json +1 -2
  156. package/plugins-dist/shell/renderers.js +28 -33
  157. package/plugins-dist/shell/service.js +17 -23
  158. package/plugins-dist/shell/shell.js +307 -362
  159. package/plugins-dist/shell/sys.js +64 -79
  160. package/plugins-dist/skills/index.js +193 -211
  161. package/plugins-dist/skills/install.js +122 -149
  162. package/plugins-dist/skills/project.js +65 -73
  163. package/plugins-dist/skills/skills.js +135 -171
  164. package/plugins-dist/steer/index.js +108 -125
  165. package/plugins-dist/suggest/index.js +235 -259
  166. package/plugins-dist/task/index.js +130 -117
  167. package/plugins-dist/task/plugin.json +5 -2
  168. package/plugins-dist/task/style.js +9 -14
  169. package/plugins-dist/task/subagent.js +156 -279
  170. package/plugins-dist/todo/index.js +79 -63
  171. package/plugins-dist/tools/index.js +36 -42
  172. package/plugins-dist/tui/editor.js +145 -160
  173. package/plugins-dist/tui/frontend.js +639 -678
  174. package/plugins-dist/tui/history.js +34 -37
  175. package/plugins-dist/tui/index.js +16 -18
  176. package/plugins-dist/tui/markdown.js +203 -247
  177. package/plugins-dist/tui/mascot.js +266 -355
  178. package/plugins-dist/tui/mentions.js +67 -144
  179. package/plugins-dist/tui/plugin.json +1 -2
  180. package/plugins-dist/tui/render.js +35 -45
  181. package/plugins-dist/tui/screen.js +197 -180
  182. package/plugins-dist/tui/transcript.js +436 -468
  183. package/plugins-dist/tui/tui.js +1554 -1656
  184. package/plugins-dist/undo/checkpoint.js +95 -118
  185. package/plugins-dist/undo/index.js +185 -192
  186. package/plugins-dist/undo/snapshot.js +83 -99
  187. package/plugins-dist/undo/style.js +9 -14
  188. package/plugins-dist/update/index.js +26 -28
  189. package/plugins-dist/web/env.js +55 -68
  190. package/plugins-dist/web/index.js +80 -110
  191. package/plugins-dist/web/plugin.json +1 -2
  192. package/plugins-dist/web/renderers.js +4 -5
  193. package/plugins-dist/web/web.js +514 -593
  194. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  195. package/sdk/python/jade_plugin.py +9 -2
  196. package/src/api.ts +1 -1
  197. package/src/host.ts +39 -4
  198. package/src/remote.ts +6 -1
  199. package/src/session.ts +489 -34
@@ -1,132 +1,120 @@
1
- // 文件工具在对话和审批里怎么显示(登记到 renderers@1)。从旧 jade 的 ui/renderers.ts 移植,去掉了检查点。
2
- //
3
- // 审批插件的 tool.before 把 path 换成了绝对路径,审批预览、before、result 拿到的都是绝对路径;
4
- // 显示时用 display 换回工作目录内的相对路径。没有登记 renderer 的部分用前端的默认显示。
5
1
  import { readFileSync } from "node:fs";
6
2
  import { readFile } from "node:fs/promises";
7
3
  import path from "node:path";
8
4
  import { diffLines, diffStats, renderDiff } from "./diff.js";
9
5
  import { applyEditsToText, display } from "./fs.js";
10
- import { clip, dim, green, red, yellow } from "./style.js";
11
- const args = (input) => (input !== null && typeof input === "object" ? input : {});
12
- /** 显示用的路径;工作目录本身显示成 "."(display 对它给的是绝对路径,审批插件会把 "." 换成工作目录) */
6
+ import { added, clip, dim, lines as joinLines, removed, warn } from "./style.js";
7
+ const args = (input) => input !== null && typeof input === "object" ? input : {};
13
8
  function pathOf(cwd, i) {
14
- if (typeof i.path !== "string")
15
- return "";
16
- const full = path.resolve(cwd, i.path);
17
- return path.relative(cwd, full) === "" ? "." : display(cwd, full);
9
+ if (typeof i.path !== "string")
10
+ return "";
11
+ const full = path.resolve(cwd, i.path);
12
+ return path.relative(cwd, full) === "" ? "." : display(cwd, full);
18
13
  }
19
- /** 预览里的多行文字:每行前面加上标记,最多 max 行 */
20
14
  function marked(s, mark, color, max = 30) {
21
- const all = s.split("\n");
22
- const shown = all.slice(0, max).map((l) => color(`${mark} ${l}`));
23
- if (all.length > max)
24
- shown.push(dim(` … ${all.length - max} more lines`));
25
- return shown.join("\n");
15
+ const all = s.split(`
16
+ `);
17
+ const shown = all.slice(0, max).map((l) => color(`${mark} ${l}`));
18
+ if (all.length > max)
19
+ shown.push(dim(` … ${all.length - max} more lines`));
20
+ return joinLines(shown);
26
21
  }
27
- /** 折叠内容里的多行文字(缩进由前端加),最多 max 行 */
28
- function capped(lines, color, max) {
29
- const shown = lines.slice(0, max).map(color);
30
- if (lines.length > max)
31
- shown.push(dim(`… ${lines.length - max} more lines`));
32
- return shown.join("\n");
22
+ function capped(lines, max) {
23
+ const shown = lines.slice(0, max);
24
+ if (lines.length > max)
25
+ shown.push(dim(`… ${lines.length - max} more lines`));
26
+ return joinLines(shown);
33
27
  }
34
- const editsOf = (tool, i) => (tool === "edit_file" ? [i] : Array.isArray(i.edits) ? i.edits : []);
35
- /**
36
- * 审批时的预览:带行号和上下文的 diff(读出文件、按工具的规则算出修改后的内容)。
37
- * 文件读不了、替换不成立时退回到只显示参数里的新旧文本
38
- */
28
+ const editsOf = (tool, i) => tool === "edit_file" ? [i] : Array.isArray(i.edits) ? i.edits : [];
39
29
  async function filePreview(cwd, tool, input) {
40
- const i = args(input);
41
- const file = typeof i.path === "string" ? path.resolve(cwd, i.path) : undefined;
42
- const current = file ? await readFile(file, "utf8").catch(() => undefined) : undefined;
43
- if (tool === "write_file") {
44
- const content = String(i.content ?? "");
45
- if (current !== undefined)
46
- return `${dim(" overwrites the existing file:")}\n${renderDiff(current, content)}`;
47
- return marked(content, "+", green, 20);
48
- }
49
- if (tool === "multi_edit" && !Array.isArray(i.edits))
50
- return dim(clip(JSON.stringify(input, null, 2), 2000));
51
- const edits = editsOf(tool, i);
52
- const raw = (e) => `${marked(String(e.old_string ?? ""), "-", red)}\n${marked(String(e.new_string ?? ""), "+", green)}`;
53
- const fallback = () => edits.map((e) => raw(e)).join(dim("\n ⋯\n"));
54
- if (current === undefined)
55
- return fallback();
56
- const r = applyEditsToText(current, edits, display(cwd, file));
57
- if (typeof r === "string")
58
- return `${fallback()}\n${yellow(` (this edit will fail: ${clip(r, 200)})`)}`;
59
- return renderDiff(current, r.text);
30
+ const i = args(input);
31
+ const file = typeof i.path === "string" ? path.resolve(cwd, i.path) : undefined;
32
+ const current = file ? await readFile(file, "utf8").catch(() => {
33
+ return;
34
+ }) : undefined;
35
+ if (tool === "write_file") {
36
+ const content = String(i.content ?? "");
37
+ if (current !== undefined)
38
+ return [dim(" overwrites the existing file:"), `
39
+ `, renderDiff(current, content)];
40
+ return marked(content, "+", added, 20);
41
+ }
42
+ if (tool === "multi_edit" && !Array.isArray(i.edits))
43
+ return dim(clip(JSON.stringify(input, null, 2), 2000));
44
+ const edits = editsOf(tool, i);
45
+ const raw = (e) => [marked(String(e.old_string ?? ""), "-", removed), `
46
+ `, marked(String(e.new_string ?? ""), "+", added)];
47
+ const fallback = () => edits.map((e) => raw(e)).flatMap((t, k) => k ? [dim(`
48
+ ⋯
49
+ `), t] : [t]);
50
+ if (current === undefined)
51
+ return fallback();
52
+ const r = applyEditsToText(current, edits, display(cwd, file));
53
+ if (typeof r === "string")
54
+ return [fallback(), `
55
+ `, warn(` (this edit will fail: ${clip(r, 200)})`)];
56
+ return renderDiff(current, r.text);
60
57
  }
61
- /** 对话里折叠的 diff 最多显示这么多行 */
62
58
  const MAX_DIFF_LINES = 400;
63
- /** 结果文字(例如编辑后检查的输出)折叠起来最多这么多行 */
64
59
  const MAX_RESULT_LINES = 2000;
65
- /**
66
- * 执行前后的差异。在工具执行之前调用(读的是修改前的文件),同步读文件:
67
- * 执行前的通知是同步的,等异步读完文件可能已经改了。替换不成立时返回 undefined
68
- */
69
60
  function fileDiff(cwd, tool, input) {
70
- const i = args(input);
71
- if (typeof i.path !== "string")
72
- return undefined;
73
- const file = path.resolve(cwd, i.path);
74
- let before;
75
- try {
76
- before = readFileSync(file, "utf8");
77
- }
78
- catch { }
79
- let after;
80
- if (tool === "write_file") {
81
- after = String(i.content ?? "");
82
- }
83
- else {
84
- if (before === undefined)
85
- return undefined;
86
- const r = applyEditsToText(before, editsOf(tool, i), display(cwd, file));
87
- if (typeof r === "string")
88
- return undefined;
89
- after = r.text;
90
- }
91
- const lines = diffLines(before ?? "", after);
92
- const { added, removed } = diffStats(lines);
93
- return { added, removed, text: renderDiff(before ?? "", after, MAX_DIFF_LINES, lines) };
61
+ const i = args(input);
62
+ if (typeof i.path !== "string")
63
+ return;
64
+ const file = path.resolve(cwd, i.path);
65
+ let before;
66
+ try {
67
+ before = readFileSync(file, "utf8");
68
+ } catch {}
69
+ let after;
70
+ if (tool === "write_file") {
71
+ after = String(i.content ?? "");
72
+ } else {
73
+ if (before === undefined)
74
+ return;
75
+ const r = applyEditsToText(before, editsOf(tool, i), display(cwd, file));
76
+ if (typeof r === "string")
77
+ return;
78
+ after = r.text;
79
+ }
80
+ const lines = diffLines(before ?? "", after);
81
+ const { added, removed } = diffStats(lines);
82
+ return { added, removed, text: renderDiff(before ?? "", after, MAX_DIFF_LINES, lines) };
94
83
  }
95
- /** 修改文件的工具:预览是 diff;结果行后面是增删的行数,展开看完整的 diff */
96
84
  function fileRenderer(cwd, tool, summary) {
97
- return {
98
- tool,
99
- summary,
100
- preview: (input) => filePreview(cwd, tool, input),
101
- before: (input) => fileDiff(cwd, tool, input),
102
- result: ({ text, isError, before }) => {
103
- const diff = before;
104
- if (!diff || isError)
105
- return undefined;
106
- const [first = "", ...rest] = text.split("\n");
107
- const extra = rest.length ? [capped(rest, (s) => s, MAX_RESULT_LINES)] : [];
108
- return { line: dim(`${clip(first, 150)} `) + `${green(`+${diff.added}`)} ${red(`-${diff.removed}`)}`, details: [...extra, diff.text].join("\n") };
109
- },
110
- };
85
+ return {
86
+ tool,
87
+ summary,
88
+ preview: (input) => filePreview(cwd, tool, input),
89
+ before: (input) => fileDiff(cwd, tool, input),
90
+ result: ({ text, isError, before }) => {
91
+ const diff = before;
92
+ if (!diff || isError)
93
+ return;
94
+ const [first = "", ...rest] = text.split(`
95
+ `);
96
+ const extra = rest.length ? [capped(rest, MAX_RESULT_LINES)] : [];
97
+ return { line: [dim(`${clip(first, 150)} `), added(`+${diff.added}`), " ", removed(`-${diff.removed}`)], details: joinLines([...extra, diff.text]) };
98
+ }
99
+ };
111
100
  }
112
101
  export function fsRenderers(cwd) {
113
- // 默认摘要是 path 参数,审批插件换成绝对路径后太长:统一换回相对路径
114
- const where = (input) => pathOf(cwd, args(input));
115
- const search = (input) => {
116
- const i = args(input);
117
- const at = pathOf(cwd, i);
118
- return `${i.pattern}${at && at !== "." ? ` in ${at}` : ""}`;
119
- };
120
- return [
121
- { tool: "read_file", summary: where },
122
- { tool: "list_dir", summary: where },
123
- fileRenderer(cwd, "edit_file", where),
124
- fileRenderer(cwd, "multi_edit", (input) => {
125
- const i = args(input);
126
- return `${pathOf(cwd, i)}, ${Array.isArray(i.edits) ? i.edits.length : 0} edits`;
127
- }),
128
- fileRenderer(cwd, "write_file", where),
129
- { tool: "grep", summary: search },
130
- { tool: "glob", summary: search },
131
- ];
102
+ const where = (input) => pathOf(cwd, args(input));
103
+ const search = (input) => {
104
+ const i = args(input);
105
+ const at = pathOf(cwd, i);
106
+ return `${i.pattern}${at && at !== "." ? ` in ${at}` : ""}`;
107
+ };
108
+ return [
109
+ { tool: "read_file", summary: where },
110
+ { tool: "list_dir", summary: where },
111
+ fileRenderer(cwd, "edit_file", where),
112
+ fileRenderer(cwd, "multi_edit", (input) => {
113
+ const i = args(input);
114
+ return `${pathOf(cwd, i)}, ${Array.isArray(i.edits) ? i.edits.length : 0} edits`;
115
+ }),
116
+ fileRenderer(cwd, "write_file", where),
117
+ { tool: "grep", summary: search },
118
+ { tool: "glob", summary: search }
119
+ ];
132
120
  }
@@ -1,15 +1,11 @@
1
- // 显示用的小工具:截断和 ANSI 颜色。从旧 jade 的 ui/render.ts、ui/screen.ts 复制过来:
2
- // 插件之间不共享代码(只能共享类型),所以 shell 插件也有一份。
3
- export const clip = (s, n) => (s.length > n ? s.slice(0, n) + "…" : s);
4
- // 设了 NO_COLOR(非空)或标准输出不是终端时不输出颜色,见 https://no-color.org
5
- const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
6
- /**
7
- * 每种样式用自己的关闭码,不用 \x1b[0m 全部重置:外面套着别的样式时,后面的文字仍保持外层样式。
8
- * 里面出现同一个关闭码(例如 dim 里套 bold,两者都用 22 关闭)时紧接着重新打开外层的样式
9
- */
10
- const paint = (open, close) => (s) => colors ? `\x1b[${open}m${s.replaceAll(`\x1b[${close}m`, `\x1b[${close}m\x1b[${open}m`)}\x1b[${close}m` : s;
11
- export const dim = paint("2", "22");
12
- export const red = paint("31", "39");
13
- export const green = paint("32", "39");
14
- export const yellow = paint("33", "39");
15
- 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 added = styled("added");
9
+ export const removed = styled("removed");
10
+ export const lines = (rows) => rows.flatMap((r, i) => i ? [`
11
+ `, r] : [r]);
@@ -1,54 +1,42 @@
1
- // 跨运行时的进程和 glob:只用 Node 的标准库,Bun 和 Node ≥22.18 下走同一套代码。
2
1
  import { spawn as nodeSpawn } from "node:child_process";
3
2
  import picomatch from "picomatch";
4
- const EMPTY = { async *[Symbol.asyncIterator]() { } };
5
- /**
6
- * 启动进程,等到确实启动了才返回。程序不存在(ENOENT)等启动错误会 reject,
7
- * 调用方用 try/catch 判断"没装",和 Bun.spawn 同步抛错的用法一致
8
- */
3
+ const EMPTY = { async* [Symbol.asyncIterator]() {} };
9
4
  export function spawn(cmd, opts = {}) {
10
- const child = nodeSpawn(cmd[0], cmd.slice(1), {
11
- cwd: opts.cwd,
12
- stdio: ["ignore", opts.stdout ?? "pipe", opts.stderr ?? "pipe"],
13
- detached: opts.detached ?? false,
14
- env: opts.env,
15
- // Windows 上不弹出控制台窗口
16
- windowsHide: true,
17
- });
18
- const exited = new Promise((resolve) => child.once("exit", (code) => resolve(code)));
19
- return new Promise((resolve, reject) => {
20
- child.once("error", reject);
21
- child.once("spawn", () => {
22
- child.off("error", reject);
23
- // 启动之后的错误(例如 kill 一个已经退出的进程)不应该变成未处理的异常
24
- child.on("error", () => { });
25
- resolve({
26
- pid: child.pid,
27
- stdout: child.stdout ?? EMPTY,
28
- stderr: child.stderr ?? EMPTY,
29
- exited,
30
- kill: () => void child.kill(),
31
- });
32
- });
5
+ const child = nodeSpawn(cmd[0], cmd.slice(1), {
6
+ cwd: opts.cwd,
7
+ stdio: ["ignore", opts.stdout ?? "pipe", opts.stderr ?? "pipe"],
8
+ detached: opts.detached ?? false,
9
+ env: opts.env,
10
+ windowsHide: true
11
+ });
12
+ const exited = new Promise((resolve) => child.once("exit", (code) => resolve(code)));
13
+ return new Promise((resolve, reject) => {
14
+ child.once("error", reject);
15
+ child.once("spawn", () => {
16
+ child.off("error", reject);
17
+ child.on("error", () => {});
18
+ resolve({
19
+ pid: child.pid,
20
+ stdout: child.stdout ?? EMPTY,
21
+ stderr: child.stderr ?? EMPTY,
22
+ exited,
23
+ kill: () => void child.kill()
24
+ });
33
25
  });
26
+ });
34
27
  }
35
- /** 运行一条命令,返回 stdout 文本和退出码;启动失败时 reject */
36
28
  export async function run(cmd, opts = {}) {
37
- const proc = await spawn(cmd, { cwd: opts.cwd, stderr: "ignore" });
38
- const [stdout, code] = await Promise.all([text(proc.stdout), proc.exited]);
39
- return { code, stdout };
29
+ const proc = await spawn(cmd, { cwd: opts.cwd, stderr: "ignore" });
30
+ const [stdout, code] = await Promise.all([text(proc.stdout), proc.exited]);
31
+ return { code, stdout };
40
32
  }
41
33
  export async function text(stream) {
42
- const decoder = new TextDecoder();
43
- let out = "";
44
- for await (const chunk of stream)
45
- out += decoder.decode(chunk, { stream: true });
46
- return out + decoder.decode();
34
+ const decoder = new TextDecoder;
35
+ let out = "";
36
+ for await (const chunk of stream)
37
+ out += decoder.decode(chunk, { stream: true });
38
+ return out + decoder.decode();
47
39
  }
48
- /**
49
- * 编译 glob,返回匹配函数。路径用正斜杠、相对于搜索根目录。
50
- * 和原先的 Bun.Glob#match 一致:* 也匹配点开头的文件,反斜杠是转义符而不是分隔符
51
- */
52
40
  export function globMatcher(pattern) {
53
- return picomatch(pattern, { dot: true, windows: false });
41
+ return picomatch(pattern, { dot: true, windows: false });
54
42
  }
@@ -1,18 +1,3 @@
1
- // jade/hooks:不写插件,在配置里写几条 shell 命令,就能在工具调用前后、一轮结束时做点事。
2
- //
3
- // $JADE_HOME/config.json(项目层的配置设不了这一项:克隆的仓库不能让你的机器跑命令):
4
- //
5
- // { "jade/hooks": { "hooks": [
6
- // { "on": "before", "tool": "bash", "command": "python ~/.jade/guard.py" },
7
- // { "on": "after", "tool": "edit_file", "command": "bunx prettier --write \"$JADE_TOOL_PATH\"" },
8
- // { "on": "turn", "command": "powershell -c \"New-BurntToastNotification -Text 'jade is done'\"" }
9
- // ] } }
10
- //
11
- // - before:工具执行前(审批的关卡里)运行。退出码不是 0 时这次调用被拒绝,命令的输出作为理由告诉模型;是 0 时不表态。
12
- // - after:工具成功执行后运行。退出码不是 0 时把输出留给模型看(下一次请求时附上),不改工具的结果。
13
- // - turn:一轮结束后运行,结果不影响会话。
14
- // tool 是工具名,不写或写 "*" 表示所有工具。命令经 shell@1 在工作目录里运行(和 bash 工具同一个 shell),环境变量:
15
- // JADE_TOOL(工具名)、JADE_TOOL_INPUT(参数的 JSON 文件的路径)、JADE_TOOL_PATH(参数里有 path 时)。
16
1
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
17
2
  import os from "node:os";
18
3
  import path from "node:path";
@@ -20,126 +5,121 @@ import { definePlugin } from "@uncarved/jade-api";
20
5
  const DEFAULT_TIMEOUT_SECONDS = 60;
21
6
  const MAX_TIMEOUT_SECONDS = 600;
22
7
  const MAX_OUTPUT_CHARS = 4000;
23
- /** 检查配置里的 hooks;写错的条目说明原因,其余的照用 */
24
8
  export function parseHooks(value) {
25
- if (value === undefined)
26
- return { hooks: [], problems: [] };
27
- if (!Array.isArray(value))
28
- return { hooks: [], problems: ["hooks must be a list"] };
29
- const hooks = [];
30
- const problems = [];
31
- for (const [i, raw] of value.entries()) {
32
- const h = (raw ?? {});
33
- const where = `hooks[${i}]`;
34
- if (h.on !== "before" && h.on !== "after" && h.on !== "turn")
35
- problems.push(`${where}: "on" must be "before", "after" or "turn"`);
36
- else if (typeof h.command !== "string" || !h.command.trim())
37
- problems.push(`${where}: "command" must be a shell command`);
38
- else if (h.tool !== undefined && typeof h.tool !== "string")
39
- problems.push(`${where}: "tool" must be a tool name`);
40
- else if (h.timeoutSeconds !== undefined && !(typeof h.timeoutSeconds === "number" && h.timeoutSeconds > 0 && h.timeoutSeconds <= MAX_TIMEOUT_SECONDS)) {
41
- problems.push(`${where}: "timeoutSeconds" must be a number up to ${MAX_TIMEOUT_SECONDS}`);
42
- }
43
- else {
44
- hooks.push({
45
- on: h.on,
46
- command: h.command,
47
- timeoutMs: (h.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1000,
48
- ...(typeof h.tool === "string" && h.tool !== "*" ? { tool: h.tool } : {}),
49
- });
50
- }
9
+ if (value === undefined)
10
+ return { hooks: [], problems: [] };
11
+ if (!Array.isArray(value))
12
+ return { hooks: [], problems: ["hooks must be a list"] };
13
+ const hooks = [];
14
+ const problems = [];
15
+ for (const [i, raw] of value.entries()) {
16
+ const h = raw ?? {};
17
+ const where = `hooks[${i}]`;
18
+ if (h.on !== "before" && h.on !== "after" && h.on !== "turn")
19
+ problems.push(`${where}: "on" must be "before", "after" or "turn"`);
20
+ else if (typeof h.command !== "string" || !h.command.trim())
21
+ problems.push(`${where}: "command" must be a shell command`);
22
+ else if (h.tool !== undefined && typeof h.tool !== "string")
23
+ problems.push(`${where}: "tool" must be a tool name`);
24
+ else if (h.timeoutSeconds !== undefined && !(typeof h.timeoutSeconds === "number" && h.timeoutSeconds > 0 && h.timeoutSeconds <= MAX_TIMEOUT_SECONDS)) {
25
+ problems.push(`${where}: "timeoutSeconds" must be a number up to ${MAX_TIMEOUT_SECONDS}`);
26
+ } else {
27
+ hooks.push({
28
+ on: h.on,
29
+ command: h.command,
30
+ timeoutMs: (h.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1000,
31
+ ...typeof h.tool === "string" && h.tool !== "*" ? { tool: h.tool } : {}
32
+ });
51
33
  }
52
- return { hooks, problems };
34
+ }
35
+ return { hooks, problems };
53
36
  }
54
- /** 单引号括起来,给 POSIX shell 用 */
55
37
  const quote = (s) => `'${s.replaceAll("'", `'\\''`)}'`;
56
- const clip = (s) => (s.length > MAX_OUTPUT_CHARS ? `${s.slice(0, MAX_OUTPUT_CHARS)}\n… (${s.length - MAX_OUTPUT_CHARS} more characters)` : s);
38
+ const clip = (s) => s.length > MAX_OUTPUT_CHARS ? `${s.slice(0, MAX_OUTPUT_CHARS)}
39
+ … (${s.length - MAX_OUTPUT_CHARS} more characters)` : s;
57
40
  let warned = false;
58
41
  export default definePlugin({
59
- session(ctx) {
60
- const { hooks, problems } = parseHooks(ctx.config.hooks);
61
- const ui = () => ctx.service("ui@1");
62
- if (problems.length > 0 && !warned) {
63
- warned = true;
64
- ui()?.notify(`jade/hooks: ${problems.join("; ")}`, "warning");
42
+ session(ctx) {
43
+ const { hooks, problems } = parseHooks(ctx.config.hooks);
44
+ const ui = () => ctx.service("ui@1");
45
+ if (problems.length > 0 && !warned) {
46
+ warned = true;
47
+ ui()?.notify(`jade/hooks: ${problems.join("; ")}`, "warning");
48
+ }
49
+ if (hooks.length === 0)
50
+ return;
51
+ const shell = ctx.require("shell@1");
52
+ const sessionId = ctx.session.id;
53
+ const run = async (hook, call, signal) => {
54
+ let dir;
55
+ try {
56
+ let exports = "";
57
+ if (call) {
58
+ dir = await mkdtemp(path.join(os.tmpdir(), "jade-hook-"));
59
+ const file = path.join(dir, "input.json");
60
+ await writeFile(file, JSON.stringify(call.input ?? null));
61
+ const p = call.input?.path;
62
+ const vars = { JADE_TOOL: call.name, JADE_TOOL_INPUT: file.split(path.sep).join("/"), ...typeof p === "string" ? { JADE_TOOL_PATH: p.split(path.sep).join("/") } : {} };
63
+ exports = `export ${Object.entries(vars).map(([k, v]) => `${k}=${quote(v)}`).join(" ")}; `;
65
64
  }
66
- if (hooks.length === 0)
67
- return;
68
- const shell = ctx.require("shell@1");
69
- const sessionId = ctx.session.id;
70
- /** 运行一条 hook;call 给了就把工具名和参数经环境变量交给它 */
71
- const run = async (hook, call, signal) => {
72
- let dir;
73
- try {
74
- let exports = "";
75
- if (call) {
76
- dir = await mkdtemp(path.join(os.tmpdir(), "jade-hook-"));
77
- const file = path.join(dir, "input.json");
78
- await writeFile(file, JSON.stringify(call.input ?? null));
79
- const p = call.input?.path;
80
- // 路径用正斜杠:Git Bash 里反斜杠是转义符
81
- const vars = { JADE_TOOL: call.name, JADE_TOOL_INPUT: file.split(path.sep).join("/"), ...(typeof p === "string" ? { JADE_TOOL_PATH: p.split(path.sep).join("/") } : {}) };
82
- exports = `export ${Object.entries(vars).map(([k, v]) => `${k}=${quote(v)}`).join(" ")}; `;
83
- }
84
- const r = await shell.run(exports + hook.command, { cwd: ctx.cwd, timeoutMs: hook.timeoutMs, ...(signal ? { signal } : {}) });
85
- return { ok: r.code === 0, output: r.timedOut ? `timed out after ${hook.timeoutMs / 1000}s` : clip(r.output.trim()) };
86
- }
87
- finally {
88
- if (dir)
89
- await rm(dir, { recursive: true, force: true }).catch(() => { });
90
- }
91
- };
92
- const matching = (on, tool) => hooks.filter((h) => h.on === on && (h.tool === undefined || h.tool === tool));
93
- if (hooks.some((h) => h.on === "before")) {
94
- ctx.kernel.hook({
95
- kind: "gate",
96
- point: "tool.gate",
97
- timeoutMs: MAX_TIMEOUT_SECONDS * 1000,
98
- fn: async (call, hook) => {
99
- for (const h of matching("before", call.name)) {
100
- const r = await run(h, call, hook.signal);
101
- if (!r.ok)
102
- return { decision: "deny", reason: `A hook the user configured (${h.command}) refused this ${call.name} call${r.output ? `:\n${r.output}` : "."}` };
103
- }
104
- return { decision: "abstain" };
105
- },
106
- });
65
+ const r = await shell.run(exports + hook.command, { cwd: ctx.cwd, timeoutMs: hook.timeoutMs, ...signal ? { signal } : {} });
66
+ return { ok: r.code === 0, output: r.timedOut ? `timed out after ${hook.timeoutMs / 1000}s` : clip(r.output.trim()) };
67
+ } finally {
68
+ if (dir)
69
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
70
+ }
71
+ };
72
+ const matching = (on, tool) => hooks.filter((h) => h.on === on && (h.tool === undefined || h.tool === tool));
73
+ if (hooks.some((h) => h.on === "before")) {
74
+ ctx.kernel.hook({
75
+ kind: "gate",
76
+ point: "tool.gate",
77
+ timeoutMs: MAX_TIMEOUT_SECONDS * 1000,
78
+ fn: async (call, hook) => {
79
+ for (const h of matching("before", call.name)) {
80
+ const r = await run(h, call, hook.signal);
81
+ if (!r.ok)
82
+ return { decision: "deny", reason: `A hook the user configured (${h.command}) refused this ${call.name} call${r.output ? `:
83
+ ${r.output}` : "."}` };
84
+ }
85
+ return { decision: "abstain" };
107
86
  }
108
- if (hooks.some((h) => h.on === "after")) {
109
- ctx.kernel.hook({
110
- kind: "transform",
111
- point: "tool.after",
112
- timeoutMs: MAX_TIMEOUT_SECONDS * 1000,
113
- // 出错时只是这条 hook 没跑,不影响工具的结果
114
- optional: true,
115
- fn: async (out) => {
116
- if (out.isError)
117
- return undefined;
118
- for (const h of matching("after", out.call.name)) {
119
- const r = await run(h, out.call);
120
- if (r.ok)
121
- continue;
122
- const text = `The user's hook after ${out.call.name} (${h.command}) failed${r.output ? `:\n${r.output}` : "."}`;
123
- ui()?.notify(text, "warning");
124
- ctx.service("prompts@1")?.note(sessionId, text);
125
- }
126
- return undefined;
127
- },
128
- });
87
+ });
88
+ }
89
+ if (hooks.some((h) => h.on === "after")) {
90
+ ctx.kernel.hook({
91
+ kind: "transform",
92
+ point: "tool.after",
93
+ timeoutMs: MAX_TIMEOUT_SECONDS * 1000,
94
+ optional: true,
95
+ fn: async (out) => {
96
+ if (out.isError)
97
+ return;
98
+ for (const h of matching("after", out.call.name)) {
99
+ const r = await run(h, out.call);
100
+ if (r.ok)
101
+ continue;
102
+ const text = `The user's hook after ${out.call.name} (${h.command}) failed${r.output ? `:
103
+ ${r.output}` : "."}`;
104
+ ui()?.notify(text, "warning");
105
+ ctx.service("prompts@1")?.note(sessionId, text);
106
+ }
107
+ return;
129
108
  }
130
- if (hooks.some((h) => h.on === "turn")) {
131
- ctx.kernel.hook({
132
- kind: "observe",
133
- point: "event",
134
- fn: (e) => {
135
- if (e.type !== "turn.ended")
136
- return;
137
- // 不等它:一轮结束不该被用户的命令拖住
138
- for (const h of matching("turn")) {
139
- void run(h, undefined, ctx.signal).then((r) => void (r.ok || ui()?.notify(`jade/hooks: ${h.command} failed${r.output ? `: ${r.output}` : ""}`, "warning")), () => { });
140
- }
141
- },
142
- });
109
+ });
110
+ }
111
+ if (hooks.some((h) => h.on === "turn") && !ctx.session.parent) {
112
+ ctx.kernel.hook({
113
+ kind: "observe",
114
+ point: "event",
115
+ fn: (e) => {
116
+ if (e.type !== "turn.ended")
117
+ return;
118
+ for (const h of matching("turn")) {
119
+ run(h, undefined, ctx.signal).then((r) => void (r.ok || ui()?.notify(`jade/hooks: ${h.command} failed${r.output ? `: ${r.output}` : ""}`, "warning")), () => {});
120
+ }
143
121
  }
144
- },
122
+ });
123
+ }
124
+ }
145
125
  });