@uncarved/jade 0.3.0 → 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 (207) 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 +482 -27
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +49 -24
  14. package/plugins/approval/policy.ts +48 -25
  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 +55 -12
  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 +10 -9
  50. package/plugins/models/index.ts +31 -4
  51. package/plugins/models/provider.ts +12 -1
  52. package/plugins/modes/index.ts +13 -2
  53. package/plugins/print/index.ts +7 -4
  54. package/plugins/prompts/index.ts +0 -0
  55. package/plugins/renderers/index.ts +10 -5
  56. package/plugins/repeats/index.ts +39 -9
  57. package/plugins/schedule/index.ts +2 -0
  58. package/plugins/screenshot/browser.ts +231 -0
  59. package/plugins/screenshot/index.ts +3 -2
  60. package/plugins/screenshot/tool.ts +27 -51
  61. package/plugins/sessions/index.ts +48 -2
  62. package/plugins/shell/index.ts +75 -22
  63. package/plugins/shell/plugin.json +1 -2
  64. package/plugins/shell/renderers.ts +9 -7
  65. package/plugins/shell/shell.ts +93 -34
  66. package/plugins/skills/index.ts +28 -19
  67. package/plugins/skills/project.ts +12 -7
  68. package/plugins/steer/index.ts +5 -4
  69. package/plugins/task/index.ts +81 -81
  70. package/plugins/task/plugin.json +5 -2
  71. package/plugins/task/style.ts +13 -14
  72. package/plugins/task/subagent.ts +67 -184
  73. package/plugins/todo/index.ts +39 -9
  74. package/plugins/tools/index.ts +57 -0
  75. package/plugins/tools/plugin.json +7 -0
  76. package/plugins/tui/frontend.ts +161 -87
  77. package/plugins/tui/index.ts +2 -3
  78. package/plugins/tui/mascot.ts +8 -7
  79. package/plugins/tui/mentions.ts +11 -80
  80. package/plugins/tui/plugin.json +1 -1
  81. package/plugins/tui/screen.ts +55 -5
  82. package/plugins/tui/transcript.ts +17 -7
  83. package/plugins/tui/tui.ts +356 -104
  84. package/plugins/tui/vendor.ts +1 -1
  85. package/plugins/undo/checkpoint.ts +5 -3
  86. package/plugins/undo/index.ts +43 -14
  87. package/plugins/undo/style.ts +13 -14
  88. package/plugins/web/index.ts +7 -18
  89. package/plugins/web/plugin.json +1 -1
  90. package/plugins-dist/approval/index.js +363 -414
  91. package/plugins-dist/approval/policy.js +395 -497
  92. package/plugins-dist/approval/review.js +132 -158
  93. package/plugins-dist/approval/schema.js +50 -55
  94. package/plugins-dist/ask/index.js +115 -129
  95. package/plugins-dist/budget/index.js +27 -31
  96. package/plugins-dist/checks/checks.js +293 -329
  97. package/plugins-dist/checks/index.js +119 -139
  98. package/plugins-dist/checks/plugin.json +2 -1
  99. package/plugins-dist/checks/project.js +57 -65
  100. package/plugins-dist/commands/index.js +47 -29
  101. package/plugins-dist/compact/compact.js +233 -249
  102. package/plugins-dist/compact/index.js +98 -95
  103. package/plugins-dist/compact/style.js +9 -14
  104. package/plugins-dist/completions/index.js +30 -0
  105. package/plugins-dist/completions/plugin.json +9 -0
  106. package/plugins-dist/continue/index.js +40 -52
  107. package/plugins-dist/copy/index.js +40 -0
  108. package/plugins-dist/copy/plugin.json +9 -0
  109. package/plugins-dist/cost/index.js +98 -115
  110. package/plugins-dist/custom-commands/index.js +55 -72
  111. package/plugins-dist/editor/index.js +64 -72
  112. package/plugins-dist/fs/diff.js +111 -124
  113. package/plugins-dist/fs/fs.js +426 -469
  114. package/plugins-dist/fs/grep.js +262 -244
  115. package/plugins-dist/fs/index.js +20 -34
  116. package/plugins-dist/fs/plugin.json +1 -2
  117. package/plugins-dist/fs/renderers.js +100 -112
  118. package/plugins-dist/fs/style.js +11 -15
  119. package/plugins-dist/fs/sys.js +31 -43
  120. package/plugins-dist/hooks/index.js +107 -127
  121. package/plugins-dist/keys/index.js +27 -31
  122. package/plugins-dist/mcp/index.js +271 -199
  123. package/plugins-dist/mcp/install.js +123 -137
  124. package/plugins-dist/mcp/mcp.js +638 -577
  125. package/plugins-dist/mcp/plugin.json +3 -1
  126. package/plugins-dist/mcp/project.js +98 -115
  127. package/plugins-dist/memory/index.js +83 -88
  128. package/plugins-dist/memory/memory.js +111 -128
  129. package/plugins-dist/memory/style.js +9 -14
  130. package/plugins-dist/mentions/attach.js +91 -99
  131. package/plugins-dist/mentions/candidates.js +49 -0
  132. package/plugins-dist/mentions/index.js +71 -81
  133. package/plugins-dist/mentions/plugin.json +2 -1
  134. package/plugins-dist/mentions/style.js +9 -14
  135. package/plugins-dist/models/config.js +29 -43
  136. package/plugins-dist/models/configure.js +392 -473
  137. package/plugins-dist/models/context.js +14 -22
  138. package/plugins-dist/models/index.js +182 -188
  139. package/plugins-dist/models/provider.js +243 -295
  140. package/plugins-dist/models/saved.js +59 -71
  141. package/plugins-dist/modes/index.js +138 -165
  142. package/plugins-dist/plugins/index.js +34 -34
  143. package/plugins-dist/print/index.js +192 -175
  144. package/plugins-dist/prompts/index.js +81 -89
  145. package/plugins-dist/prompts/notes.js +31 -37
  146. package/plugins-dist/prompts/prompts.js +155 -193
  147. package/plugins-dist/prompts/results.js +40 -53
  148. package/plugins-dist/prompts/sys.js +39 -50
  149. package/plugins-dist/renderers/index.js +32 -32
  150. package/plugins-dist/repeats/index.js +134 -151
  151. package/plugins-dist/schedule/cron.js +49 -56
  152. package/plugins-dist/schedule/index.js +229 -247
  153. package/plugins-dist/schedule/store.js +93 -109
  154. package/plugins-dist/scratch/index.js +12 -18
  155. package/plugins-dist/screenshot/browser.js +169 -0
  156. package/plugins-dist/screenshot/index.js +37 -45
  157. package/plugins-dist/screenshot/sys.js +53 -65
  158. package/plugins-dist/screenshot/tool.js +101 -151
  159. package/plugins-dist/sessions/index.js +149 -117
  160. package/plugins-dist/shell/index.js +117 -74
  161. package/plugins-dist/shell/plugin.json +1 -2
  162. package/plugins-dist/shell/renderers.js +28 -33
  163. package/plugins-dist/shell/service.js +17 -23
  164. package/plugins-dist/shell/shell.js +317 -320
  165. package/plugins-dist/shell/sys.js +64 -79
  166. package/plugins-dist/skills/index.js +193 -211
  167. package/plugins-dist/skills/install.js +122 -149
  168. package/plugins-dist/skills/project.js +65 -73
  169. package/plugins-dist/skills/skills.js +135 -171
  170. package/plugins-dist/steer/index.js +108 -125
  171. package/plugins-dist/suggest/index.js +235 -259
  172. package/plugins-dist/task/index.js +130 -148
  173. package/plugins-dist/task/plugin.json +5 -4
  174. package/plugins-dist/task/style.js +9 -14
  175. package/plugins-dist/task/subagent.js +156 -279
  176. package/plugins-dist/todo/index.js +79 -63
  177. package/plugins-dist/tools/index.js +43 -0
  178. package/plugins-dist/tools/plugin.json +9 -0
  179. package/plugins-dist/tui/editor.js +145 -160
  180. package/plugins-dist/tui/frontend.js +641 -655
  181. package/plugins-dist/tui/history.js +34 -37
  182. package/plugins-dist/tui/index.js +16 -18
  183. package/plugins-dist/tui/markdown.js +203 -247
  184. package/plugins-dist/tui/mascot.js +266 -353
  185. package/plugins-dist/tui/mentions.js +67 -144
  186. package/plugins-dist/tui/plugin.json +1 -2
  187. package/plugins-dist/tui/render.js +35 -45
  188. package/plugins-dist/tui/screen.js +197 -180
  189. package/plugins-dist/tui/transcript.js +436 -468
  190. package/plugins-dist/tui/tui.js +1554 -1645
  191. package/plugins-dist/tui/vendor.js +1388 -1088
  192. package/plugins-dist/undo/checkpoint.js +95 -118
  193. package/plugins-dist/undo/index.js +185 -192
  194. package/plugins-dist/undo/snapshot.js +83 -99
  195. package/plugins-dist/undo/style.js +9 -14
  196. package/plugins-dist/update/index.js +26 -28
  197. package/plugins-dist/web/env.js +55 -68
  198. package/plugins-dist/web/index.js +80 -110
  199. package/plugins-dist/web/plugin.json +1 -2
  200. package/plugins-dist/web/renderers.js +4 -5
  201. package/plugins-dist/web/web.js +514 -593
  202. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  203. package/sdk/python/jade_plugin.py +9 -2
  204. package/src/api.ts +1 -1
  205. package/src/host.ts +39 -4
  206. package/src/remote.ts +6 -1
  207. package/src/session.ts +489 -34
@@ -1,125 +1,109 @@
1
- // 定时任务的存储:$JADE_HOME/state/schedules.json。同一台机器上可能开着好几个 jade,
2
- // 所有读写都在一把目录锁(schedules.lock,mkdir 是原子的)里进行,到点的任务由先拿到锁的进程认领,只投递一次。
3
1
  import { randomBytes } from "node:crypto";
4
2
  import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
5
3
  import path from "node:path";
6
4
  import { nextRun } from "./cron.js";
7
- /** 锁超过这么久没释放,当作持有它的进程已经不在了 */
8
- const STALE_MS = 10_000;
9
- const WAIT_MS = 5_000;
5
+ const STALE_MS = 1e4;
6
+ const WAIT_MS = 5000;
7
+
10
8
  export class ScheduleStore {
11
- file;
12
- #lock;
13
- constructor(home) {
14
- this.file = path.join(home, "state", "schedules.json");
15
- this.#lock = path.join(home, "state", "schedules.lock");
16
- }
17
- /** 读全部任务 */
18
- list() {
19
- return this.#locked(() => this.#read());
20
- }
21
- /** 在锁里读出全部任务交给 fn,fn 改了就写回。fn 抛错时不写 */
22
- update(fn) {
23
- return this.#locked(async () => {
24
- const tasks = await this.#read();
25
- const before = JSON.stringify(tasks);
26
- const out = fn(tasks);
27
- if (JSON.stringify(tasks) !== before) {
28
- const tmp = `${this.file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
29
- await writeFile(tmp, `${JSON.stringify({ version: 1, tasks }, null, 2)}\n`);
30
- await rename(tmp, this.file);
31
- }
32
- return out;
33
- });
9
+ file;
10
+ #lock;
11
+ constructor(home) {
12
+ this.file = path.join(home, "state", "schedules.json");
13
+ this.#lock = path.join(home, "state", "schedules.lock");
14
+ }
15
+ list() {
16
+ return this.#locked(() => this.#read());
17
+ }
18
+ update(fn) {
19
+ return this.#locked(async () => {
20
+ const tasks = await this.#read();
21
+ const before = JSON.stringify(tasks);
22
+ const out = fn(tasks);
23
+ if (JSON.stringify(tasks) !== before) {
24
+ const tmp = `${this.file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
25
+ await writeFile(tmp, `${JSON.stringify({ version: 1, tasks }, null, 2)}
26
+ `);
27
+ await rename(tmp, this.file);
28
+ }
29
+ return out;
30
+ });
31
+ }
32
+ async#read() {
33
+ let text;
34
+ try {
35
+ text = await readFile(this.file, "utf8");
36
+ } catch (e) {
37
+ if (e.code === "ENOENT")
38
+ return [];
39
+ throw e;
34
40
  }
35
- async #read() {
36
- let text;
41
+ const data = JSON.parse(text);
42
+ if (data.version !== 1 || !Array.isArray(data.tasks))
43
+ throw new Error(`${this.file}: unsupported format`);
44
+ return data.tasks;
45
+ }
46
+ async#locked(fn) {
47
+ await mkdir(path.dirname(this.#lock), { recursive: true });
48
+ const deadline = Date.now() + WAIT_MS;
49
+ const mine = randomBytes(8).toString("hex");
50
+ for (;; ) {
51
+ try {
52
+ await mkdir(this.#lock);
37
53
  try {
38
- text = await readFile(this.file, "utf8");
54
+ await writeFile(path.join(this.#lock, "owner"), mine);
55
+ } catch (e) {
56
+ await rm(this.#lock, { recursive: true, force: true });
57
+ throw e;
39
58
  }
40
- catch (e) {
41
- if (e.code === "ENOENT")
42
- return [];
43
- throw e;
44
- }
45
- const data = JSON.parse(text);
46
- if (data.version !== 1 || !Array.isArray(data.tasks))
47
- throw new Error(`${this.file}: unsupported format`);
48
- return data.tasks;
59
+ break;
60
+ } catch (e) {
61
+ if (e.code !== "EEXIST")
62
+ throw e;
63
+ const age = await stat(this.#lock).then((s) => Date.now() - s.mtimeMs, () => 0);
64
+ if (age > STALE_MS)
65
+ await rm(this.#lock, { recursive: true, force: true });
66
+ else if (Date.now() > deadline)
67
+ throw new Error(`${this.#lock} is held by another jade; remove it if no jade is running`);
68
+ else
69
+ await new Promise((r) => setTimeout(r, 20));
70
+ }
49
71
  }
50
- async #locked(fn) {
51
- await mkdir(path.dirname(this.#lock), { recursive: true });
52
- const deadline = Date.now() + WAIT_MS;
53
- // 在锁目录里放一个随机标记,释放时只删自己的锁:持有太久被别人当成过期删掉、重新上了锁时,不去删别人的。
54
- // 不用目录的文件号:Linux 上删掉目录马上重建,常常拿到同一个文件号
55
- const mine = randomBytes(8).toString("hex");
56
- for (;;) {
57
- try {
58
- await mkdir(this.#lock);
59
- try {
60
- await writeFile(path.join(this.#lock, "owner"), mine);
61
- }
62
- catch (e) {
63
- await rm(this.#lock, { recursive: true, force: true });
64
- throw e;
65
- }
66
- break;
67
- }
68
- catch (e) {
69
- if (e.code !== "EEXIST")
70
- throw e;
71
- const age = await stat(this.#lock).then((s) => Date.now() - s.mtimeMs, () => 0);
72
- if (age > STALE_MS)
73
- await rm(this.#lock, { recursive: true, force: true });
74
- else if (Date.now() > deadline)
75
- throw new Error(`${this.#lock} is held by another jade; remove it if no jade is running`);
76
- else
77
- await new Promise((r) => setTimeout(r, 20));
78
- }
79
- }
80
- try {
81
- return await fn();
82
- }
83
- finally {
84
- const owner = await readFile(path.join(this.#lock, "owner"), "utf8").catch(() => undefined);
85
- if (owner === mine)
86
- await rm(this.#lock, { recursive: true, force: true });
87
- }
72
+ try {
73
+ return await fn();
74
+ } finally {
75
+ const owner = await readFile(path.join(this.#lock, "owner"), "utf8").catch(() => {
76
+ return;
77
+ });
78
+ if (owner === mine)
79
+ await rm(this.#lock, { recursive: true, force: true });
88
80
  }
81
+ }
89
82
  }
90
- /**
91
- * 两个目录是不是同一个:比较绝对路径(不看末尾的分隔符),Windows 上不分大小写。
92
- * 和 jade/sessions 的 cwdKey 相同,插件之间不共享代码(只能共享类型),所以这里留一份
93
- */
94
83
  export function sameDir(a, b) {
95
- const key = (p) => (process.platform === "win32" ? path.resolve(p).toLowerCase() : path.resolve(p));
96
- return key(a) === key(b);
84
+ const key = (p) => process.platform === "win32" ? path.resolve(p).toLowerCase() : path.resolve(p);
85
+ return key(a) === key(b);
97
86
  }
98
- /** 下一次触发时间;没有了时 undefined */
99
87
  export function nextAt(cron, from) {
100
- return nextRun(cron, from)?.toISOString();
88
+ return nextRun(cron, from)?.toISOString();
101
89
  }
102
- /**
103
- * 认领 cwd 里到点的任务:记下这次投递,推进到 now 之后的下一次(错过的几次只算一次),
104
- * 一次性的任务结束。skip 里的任务(上一次还没跑完)不认领,留到下次检查
105
- */
106
- export function claimDue(store, cwd, session, now, skip = new Set()) {
107
- return store.update((tasks) => {
108
- const due = [];
109
- for (const t of tasks) {
110
- if (t.status !== "active" || !sameDir(t.cwd, cwd) || !t.next || Date.parse(t.next) > now.getTime() || skip.has(t.id))
111
- continue;
112
- t.last = { at: now.toISOString(), session };
113
- t.updatedAt = now.toISOString();
114
- const next = t.recurring ? nextAt(t.cron, now) : undefined;
115
- if (next)
116
- t.next = next;
117
- else {
118
- t.status = "ended";
119
- delete t.next;
120
- }
121
- due.push({ ...t });
122
- }
123
- return due;
124
- });
90
+ export function claimDue(store, cwd, session, now, skip = new Set) {
91
+ return store.update((tasks) => {
92
+ const due = [];
93
+ for (const t of tasks) {
94
+ if (t.status !== "active" || !sameDir(t.cwd, cwd) || !t.next || Date.parse(t.next) > now.getTime() || skip.has(t.id))
95
+ continue;
96
+ t.last = { at: now.toISOString(), session };
97
+ t.updatedAt = now.toISOString();
98
+ const next = t.recurring ? nextAt(t.cron, now) : undefined;
99
+ if (next)
100
+ t.next = next;
101
+ else {
102
+ t.status = "ended";
103
+ delete t.next;
104
+ }
105
+ due.push({ ...t });
106
+ }
107
+ return due;
108
+ });
125
109
  }
@@ -1,26 +1,20 @@
1
- // jade/scratch:每个会话一个临时目录,放不属于项目的临时文件(试跑的脚本、中间结果),免得弄脏工作目录。
2
- // 目录在系统临时目录下、按会话 id 命名,恢复会话时还是同一个;不主动删除,由系统清理临时目录。
3
1
  import { realpathSync } from "node:fs";
4
2
  import { mkdir } from "node:fs/promises";
5
3
  import os from "node:os";
6
4
  import path from "node:path";
7
5
  import { definePlugin } from "@uncarved/jade-api";
8
- /** 会话 id 对应的临时目录 */
9
6
  export const scratchDir = (session) => path.join(os.tmpdir(), "jade-scratch", session);
10
7
  export default definePlugin({
11
- async session(ctx) {
12
- // 恢复时的 id 来自命令行,还没经过校验;只用单级、不含路径分隔符的名字,免得目录落到 jade-scratch 外面
13
- if (!/^[A-Za-z0-9_-][A-Za-z0-9._-]*$/.test(ctx.session.id))
14
- return;
15
- const created = scratchDir(ctx.session.id);
16
- await mkdir(created, { recursive: true });
17
- // 提示词和审批都用真实路径:Windows 上 os.tmpdir() 可能是 8.3 短路径
18
- const dir = realpathSync.native(created);
19
- // 在里面改文件和在工作目录里一样对待;会话关闭时撤销
20
- ctx.service("approval@1")?.allowWrite(dir);
21
- ctx.service("prompts@1")?.add({
22
- text: `- Scratch directory for this session: ${dir}\n` +
23
- " Put temporary files there (throwaway scripts, intermediate output, files that do not belong in the project) instead of the working directory or /tmp.",
24
- });
25
- },
8
+ async session(ctx) {
9
+ if (!/^[A-Za-z0-9_-][A-Za-z0-9._-]*$/.test(ctx.session.id))
10
+ return;
11
+ const created = scratchDir(ctx.session.id);
12
+ await mkdir(created, { recursive: true });
13
+ const dir = realpathSync.native(created);
14
+ ctx.service("approval@1")?.allowWrite(dir);
15
+ ctx.service("prompts@1")?.add({
16
+ text: `- Scratch directory for this session: ${dir}
17
+ ` + " Put temporary files there (throwaway scripts, intermediate output, files that do not belong in the project) instead of the working directory or /tmp."
18
+ });
19
+ }
26
20
  });
@@ -0,0 +1,169 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { spawn } from "./sys.js";
4
+ const READY_MS = 1e4;
5
+ const LOAD_MS = 15000;
6
+ const SETTLE_MS = 3000;
7
+ const CLOSE_MS = 5000;
8
+ const SCROLL_SETTLE_MS = 400;
9
+
10
+ export class CaptureError extends Error {
11
+ }
12
+ function connect(url) {
13
+ return new Promise((resolve, reject) => {
14
+ const ws = new WebSocket(url);
15
+ let next = 0;
16
+ let closed = false;
17
+ const waiting = new Map;
18
+ const events = new Set;
19
+ const listeners = new Set;
20
+ ws.onerror = () => reject(new CaptureError("could not connect to the browser"));
21
+ ws.onclose = () => {
22
+ closed = true;
23
+ for (const w of waiting.values())
24
+ w.reject(new CaptureError("the browser closed before the screenshot was taken"));
25
+ waiting.clear();
26
+ };
27
+ ws.onmessage = (e) => {
28
+ const m = JSON.parse(String(e.data));
29
+ if (m.id !== undefined) {
30
+ const w = waiting.get(m.id);
31
+ waiting.delete(m.id);
32
+ if (m.error)
33
+ w?.reject(new CaptureError(m.error.message));
34
+ else
35
+ w?.resolve(m.result);
36
+ } else if (m.method) {
37
+ const name = m.method === "Page.lifecycleEvent" ? `lifecycle:${m.params?.name}` : m.method;
38
+ events.add(name);
39
+ for (const l of listeners)
40
+ l(name);
41
+ }
42
+ };
43
+ ws.onopen = () => resolve({
44
+ send: (method, params = {}, sessionId) => new Promise((res, rej) => {
45
+ if (closed)
46
+ return rej(new CaptureError("the browser closed before the screenshot was taken"));
47
+ const id = ++next;
48
+ waiting.set(id, { resolve: res, reject: rej });
49
+ ws.send(JSON.stringify({ id, method, params, sessionId }));
50
+ }),
51
+ seen: (method, ms) => new Promise((res) => {
52
+ if (events.has(method))
53
+ return res(true);
54
+ const done = (ok) => {
55
+ clearTimeout(timer);
56
+ listeners.delete(l);
57
+ res(ok);
58
+ };
59
+ const l = (name) => name === method && done(true);
60
+ const timer = setTimeout(() => done(false), ms);
61
+ listeners.add(l);
62
+ }),
63
+ close: () => ws.close()
64
+ });
65
+ });
66
+ }
67
+ async function debuggerUrl(profile, proc, signal) {
68
+ let exited = false;
69
+ proc.exited.then(() => exited = true);
70
+ const deadline = Date.now() + READY_MS;
71
+ for (;; ) {
72
+ signal.throwIfAborted();
73
+ try {
74
+ const [port, wsPath] = (await readFile(path.join(profile, "DevToolsActivePort"), "utf8")).trim().split(`
75
+ `);
76
+ if (port && wsPath)
77
+ return `ws://127.0.0.1:${port}${wsPath}`;
78
+ } catch {}
79
+ if (exited)
80
+ throw new CaptureError("the browser exited before it was ready");
81
+ if (Date.now() > deadline)
82
+ throw new CaptureError(`the browser was not ready within ${READY_MS / 1000}s`);
83
+ await new Promise((r) => setTimeout(r, 50));
84
+ }
85
+ }
86
+ const SCROLL = (what) => `(() => {
87
+ const what = ${JSON.stringify(what)};
88
+ let el = null;
89
+ try { el = document.querySelector(what); } catch {}
90
+ if (!el) {
91
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
92
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
93
+ if (n.nodeValue.includes(what) && n.parentElement && n.parentElement.getClientRects().length) { el = n.parentElement; break; }
94
+ }
95
+ }
96
+ if (!el) return null;
97
+ el.scrollIntoView({ block: el.getBoundingClientRect().height > innerHeight ? "start" : "center", behavior: "instant" });
98
+ const text = (el.textContent || "").trim().replace(/\\s+/g, " ");
99
+ return "<" + el.tagName.toLowerCase() + ">" + (text ? ' "' + (text.length > 40 ? text.slice(0, 40) + "…" : text) + '"' : "");
100
+ })()`;
101
+ const METRICS = "JSON.stringify({ h: Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0), y: Math.round(scrollY) })";
102
+ export const capture = async (browser, req, signal) => {
103
+ const proc = await spawn([
104
+ browser,
105
+ "--headless=new",
106
+ "--disable-gpu",
107
+ "--hide-scrollbars",
108
+ "--no-first-run",
109
+ "--no-default-browser-check",
110
+ "--disable-extensions",
111
+ "--mute-audio",
112
+ "--remote-debugging-port=0",
113
+ `--user-data-dir=${req.profile}`,
114
+ "about:blank"
115
+ ], { stdout: "ignore", stderr: "ignore" });
116
+ let abort;
117
+ const aborted = new Promise((_, reject) => abort = () => reject(signal.reason));
118
+ signal.addEventListener("abort", abort, { once: true });
119
+ let cdp;
120
+ const work = async () => {
121
+ cdp = await connect(await debuggerUrl(req.profile, proc, signal));
122
+ const { targetId } = await cdp.send("Target.createTarget", { url: "about:blank" });
123
+ const { sessionId } = await cdp.send("Target.attachToTarget", { targetId, flatten: true });
124
+ const page = (method, params) => cdp.send(method, params, sessionId);
125
+ const evaluate = async (expression) => (await page("Runtime.evaluate", { expression, returnByValue: true })).result.value;
126
+ await page("Emulation.setDeviceMetricsOverride", { width: req.width, height: req.height, deviceScaleFactor: 1, mobile: false });
127
+ await page("Page.enable");
128
+ await page("Page.setLifecycleEventsEnabled", { enabled: true });
129
+ const { errorText } = await page("Page.navigate", { url: req.target });
130
+ if (errorText)
131
+ throw new CaptureError(`the page could not be loaded: ${errorText}`);
132
+ const loaded = await cdp.seen("Page.loadEventFired", LOAD_MS);
133
+ if (loaded)
134
+ await cdp.seen("lifecycle:networkIdle", SETTLE_MS);
135
+ signal.throwIfAborted();
136
+ let scrolledTo;
137
+ if (req.scrollTo !== undefined) {
138
+ const found = await evaluate(SCROLL(req.scrollTo));
139
+ if (found === null) {
140
+ throw new CaptureError(`nothing on the page matches scroll_to ${JSON.stringify(req.scrollTo)} (tried as a CSS selector, then as text)` + (loaded ? "" : `; the page had not finished loading after ${LOAD_MS / 1000}s`));
141
+ }
142
+ scrolledTo = found;
143
+ await new Promise((r) => setTimeout(r, SCROLL_SETTLE_MS));
144
+ }
145
+ const { h, y } = JSON.parse(await evaluate(METRICS));
146
+ const { data } = await page("Page.captureScreenshot", { format: "png" });
147
+ return {
148
+ png: Buffer.from(data, "base64"),
149
+ pageHeight: h,
150
+ scrollY: y,
151
+ scrolledTo,
152
+ note: loaded ? undefined : `The page had not finished loading after ${LOAD_MS / 1000}s; this is how it looked at that point.`
153
+ };
154
+ };
155
+ try {
156
+ return await Promise.race([work(), aborted]);
157
+ } finally {
158
+ signal.removeEventListener("abort", abort);
159
+ if (cdp && !signal.aborted) {
160
+ cdp.send("Browser.close").catch(() => {});
161
+ let timer;
162
+ await Promise.race([proc.exited, new Promise((r) => timer = setTimeout(r, CLOSE_MS))]);
163
+ clearTimeout(timer);
164
+ }
165
+ cdp?.close();
166
+ proc.kill();
167
+ await proc.exited;
168
+ }
169
+ };
@@ -1,49 +1,41 @@
1
- // jade/screenshot:截图工具(见 tool.ts)。本机没有能无头截图的浏览器时不注册这个工具。
2
- // 模型能不能看图片由 jade/models 的 models@1 给出(JADE_VISION):不能看时请求里没有这个工具和提示,调用了也不截图。
3
- // 访问网络的 URL 由 jade/approval 的关卡决定要不要问用户(effect 是 read,路径之外的 URL 会问)。
4
1
  import { definePlugin } from "@uncarved/jade-api";
5
2
  import { findBrowser, screenshotTool } from "./tool.js";
6
- /** 提示词里的一段:有截图工具时才加 */
7
- const NOTE = "- When the work is visual (a page, a drawing, styles), take a screenshot of the result and look at it instead of guessing from the source.";
3
+ const NOTE = "- When the work is visual (a page, a drawing, styles), take a screenshot of the result and look at it instead of guessing from the source. " + "If screenshots keep failing, or keep showing something you cannot explain after a couple of attempts, stop changing code to chase it: tell the user what you see and let them look.";
8
4
  export default definePlugin({
9
- process(ctx) {
10
- const renderers = ctx.service("renderers@1");
11
- // 显示方式和会话无关,登记一次留到进程结束
12
- renderers?.tool({
13
- tool: "screenshot",
14
- summary: (input) => String(input?.url ?? input?.path ?? ""),
15
- });
16
- },
17
- session(ctx) {
18
- const browser = findBrowser(process.env);
19
- if (!browser)
20
- return;
21
- const models = ctx.service("models@1");
22
- // 换了模型(/model)之后也按新的配置判断
23
- const available = () => models?.current()?.vision !== false;
24
- const tool = screenshotTool({ cwd: ctx.cwd, browser, available });
25
- if (!tool)
26
- return;
27
- ctx.kernel.tool(tool);
28
- // 不能看图片的模型不给这个工具,也不加那句提示:给了它多半会试一次,白费一轮。
29
- // 排在 jade/prompts 的 context.build 之前(order -1),它组装系统提示词时读到的段落和工具已经是这一次的
30
- const prompts = ctx.service("prompts@1");
31
- let note;
32
- ctx.effect(() => () => note?.());
33
- ctx.kernel.hook({
34
- kind: "transform",
35
- point: "context.build",
36
- order: -1,
37
- fn: (req) => {
38
- const can = available();
39
- if (can && !note)
40
- note = prompts?.add({ text: NOTE, stable: false });
41
- else if (!can && note) {
42
- note();
43
- note = undefined;
44
- }
45
- return can ? req : { ...req, tools: req.tools.filter((t) => t.name !== tool.name) };
46
- },
47
- });
48
- },
5
+ process(ctx) {
6
+ const renderers = ctx.service("renderers@1");
7
+ renderers?.tool({
8
+ tool: "screenshot",
9
+ summary: (input) => String(input?.url ?? input?.path ?? "")
10
+ });
11
+ },
12
+ session(ctx) {
13
+ const browser = findBrowser(process.env);
14
+ if (!browser)
15
+ return;
16
+ const models = ctx.service("models@1");
17
+ const available = () => models?.current()?.vision !== false;
18
+ const tool = screenshotTool({ cwd: ctx.cwd, browser, available });
19
+ if (!tool)
20
+ return;
21
+ ctx.kernel.tool(tool);
22
+ const prompts = ctx.service("prompts@1");
23
+ let note;
24
+ ctx.effect(() => () => note?.());
25
+ ctx.kernel.hook({
26
+ kind: "transform",
27
+ point: "context.build",
28
+ order: -1,
29
+ fn: (req) => {
30
+ const can = available();
31
+ if (can && !note)
32
+ note = prompts?.add({ text: NOTE, stable: false });
33
+ else if (!can && note) {
34
+ note();
35
+ note = undefined;
36
+ }
37
+ return can ? req : { ...req, tools: req.tools.filter((t) => t.name !== tool.name) };
38
+ }
39
+ });
40
+ }
49
41
  });
@@ -1,76 +1,64 @@
1
- // 跨运行时的进程和可执行文件查找:只用 Node 的标准库,Bun 和 Node ≥22.18 下走同一套代码。
2
- // 和 jade/shell 里的 sys.ts 是同一份:插件之间不共享代码(见 docs/design/jade.md 3.5)。
3
1
  import { spawn as nodeSpawn } from "node:child_process";
4
2
  import { accessSync, constants, statSync } from "node:fs";
5
3
  import path from "node:path";
6
- /**
7
- * 启动进程,等到确实启动了才返回。程序不存在(ENOENT)等启动错误会 reject,
8
- * 调用方用 try/catch 判断"没装",和 Bun.spawn 同步抛错的用法一致
9
- */
10
4
  export function spawn(cmd, opts = {}) {
11
- const child = nodeSpawn(cmd[0], cmd.slice(1), {
12
- stdio: ["ignore", opts.stdout ?? "pipe", opts.stderr ?? "pipe"],
13
- // Windows 上不弹出控制台窗口
14
- windowsHide: true,
15
- });
16
- const exited = new Promise((resolve) => child.once("exit", (code) => resolve(code)));
17
- return new Promise((resolve, reject) => {
18
- child.once("error", reject);
19
- child.once("spawn", () => {
20
- child.off("error", reject);
21
- // 启动之后的错误(例如 kill 一个已经退出的进程)不应该变成未处理的异常
22
- child.on("error", () => { });
23
- resolve({ pid: child.pid, exited, kill: () => void child.kill() });
24
- });
5
+ const child = nodeSpawn(cmd[0], cmd.slice(1), {
6
+ stdio: ["ignore", opts.stdout ?? "pipe", opts.stderr ?? "pipe"],
7
+ windowsHide: true
8
+ });
9
+ const exited = new Promise((resolve) => child.once("exit", (code) => resolve(code)));
10
+ return new Promise((resolve, reject) => {
11
+ child.once("error", reject);
12
+ child.once("spawn", () => {
13
+ child.off("error", reject);
14
+ child.on("error", () => {});
15
+ resolve({ pid: child.pid, exited, kill: () => void child.kill() });
25
16
  });
17
+ });
26
18
  }
27
- /** which 的结果,按 PATH 和 PATHEXT 记;找不到的过一会儿再查 */
28
- const found = new Map();
29
- const MISS_TTL_MS = 30_000;
30
- /** 在 PATH 里找可执行文件,找不到返回 undefined。Windows 上按 PATHEXT 补扩展名;带路径分隔符时只检查那个文件 */
19
+ const found = new Map;
20
+ const MISS_TTL_MS = 30000;
31
21
  export function which(bin) {
32
- if (bin.includes("/") || (process.platform === "win32" && bin.includes("\\")))
33
- return lookup(bin);
34
- const key = `${bin}\0${process.env.PATH ?? process.env.Path ?? ""}\0${process.env.PATHEXT ?? ""}`;
35
- const hit = found.get(key);
36
- if (hit && (hit.file !== undefined || Date.now() - hit.at < MISS_TTL_MS))
37
- return hit.file;
38
- const file = lookup(bin);
39
- found.set(key, { file, at: Date.now() });
40
- return file;
22
+ if (bin.includes("/") || process.platform === "win32" && bin.includes("\\"))
23
+ return lookup(bin);
24
+ const key = `${bin}\x00${process.env.PATH ?? process.env.Path ?? ""}\x00${process.env.PATHEXT ?? ""}`;
25
+ const hit = found.get(key);
26
+ if (hit && (hit.file !== undefined || Date.now() - hit.at < MISS_TTL_MS))
27
+ return hit.file;
28
+ const file = lookup(bin);
29
+ found.set(key, { file, at: Date.now() });
30
+ return file;
41
31
  }
42
32
  function lookup(bin) {
43
- const win = process.platform === "win32";
44
- const exts = win ? ["", ...(process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""];
45
- const ok = (file) => {
46
- try {
47
- if (!statSync(file).isFile())
48
- return false;
49
- if (!win)
50
- accessSync(file, constants.X_OK);
51
- return true;
52
- }
53
- catch {
54
- return false;
55
- }
56
- };
57
- const tryAll = (base) => {
58
- for (const ext of exts) {
59
- // Windows 上没有扩展名的文件不能直接执行
60
- if (win && ext === "" && !path.extname(base))
61
- continue;
62
- if (ok(base + ext))
63
- return base + ext;
64
- }
65
- return undefined;
66
- };
67
- if (bin.includes("/") || (win && bin.includes("\\")))
68
- return tryAll(path.resolve(bin));
69
- const dirs = (process.env.PATH ?? process.env.Path ?? "").split(path.delimiter).filter(Boolean);
70
- for (const dir of dirs) {
71
- const hit = tryAll(path.join(dir.replace(/^"(.*)"$/, "$1"), bin));
72
- if (hit)
73
- return hit;
33
+ const win = process.platform === "win32";
34
+ const exts = win ? ["", ...(process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""];
35
+ const ok = (file) => {
36
+ try {
37
+ if (!statSync(file).isFile())
38
+ return false;
39
+ if (!win)
40
+ accessSync(file, constants.X_OK);
41
+ return true;
42
+ } catch {
43
+ return false;
44
+ }
45
+ };
46
+ const tryAll = (base) => {
47
+ for (const ext of exts) {
48
+ if (win && ext === "" && !path.extname(base))
49
+ continue;
50
+ if (ok(base + ext))
51
+ return base + ext;
74
52
  }
75
- return undefined;
53
+ return;
54
+ };
55
+ if (bin.includes("/") || win && bin.includes("\\"))
56
+ return tryAll(path.resolve(bin));
57
+ const dirs = (process.env.PATH ?? process.env.Path ?? "").split(path.delimiter).filter(Boolean);
58
+ for (const dir of dirs) {
59
+ const hit = tryAll(path.join(dir.replace(/^"(.*)"$/, "$1"), bin));
60
+ if (hit)
61
+ return hit;
62
+ }
63
+ return;
76
64
  }