@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,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
  });
@@ -1,109 +1,88 @@
1
- // 用 DevTools 协议(CDP)让无头浏览器截一张图。
2
- //
3
- // 不用命令行的 --window-size + --screenshot:Windows 上浏览器窗口最窄 500px,要 390 宽时页面仍按 500 排版,
4
- // 只截到左边 390px,看起来像内容被裁掉;也不能滚动到页面中间的某一段,页面一直不"加载完"时只有一句超时。
5
- // 这里用 Emulation.setDeviceMetricsOverride 设视口(多窄都按给的宽度排版),可以先滚动到某个元素再截,
6
- // 页面迟迟不触发 load 时照样截下当时的样子并说明。
7
- //
8
- // 连接用 --remote-debugging-port=0 加 WebSocket(Bun 和 Node ≥22 都有全局的 WebSocket);
9
- // --remote-debugging-pipe 在 Bun 下收不到数据。端口只监听本机,用完就连同临时用户目录一起关掉。
10
1
  import { readFile } from "node:fs/promises";
11
2
  import path from "node:path";
12
3
  import { spawn } from "./sys.js";
13
- /** 浏览器启动到能连接的最长时间 */
14
- const READY_MS = 10_000;
15
- /** 等页面 load 事件的最长时间;到时间还没有就按当时的样子截 */
16
- const LOAD_MS = 15_000;
17
- /** load 之后等网络安静下来(脚本、图片、字体)的最长时间 */
4
+ const READY_MS = 1e4;
5
+ const LOAD_MS = 15000;
18
6
  const SETTLE_MS = 3000;
19
- /** 滚动之后给懒加载的图片、滚动触发的动画的时间 */
7
+ const CLOSE_MS = 5000;
20
8
  const SCROLL_SETTLE_MS = 400;
21
- /** 截图失败、原因可以直接告诉模型的错误 */
9
+
22
10
  export class CaptureError extends Error {
23
11
  }
24
12
  function connect(url) {
25
- return new Promise((resolve, reject) => {
26
- const ws = new WebSocket(url);
27
- let next = 0;
28
- let closed = false;
29
- const waiting = new Map();
30
- const events = new Set();
31
- const listeners = new Set();
32
- ws.onerror = () => reject(new CaptureError("could not connect to the browser"));
33
- ws.onclose = () => {
34
- closed = true;
35
- for (const w of waiting.values())
36
- w.reject(new CaptureError("the browser closed before the screenshot was taken"));
37
- waiting.clear();
38
- };
39
- ws.onmessage = (e) => {
40
- const m = JSON.parse(String(e.data));
41
- if (m.id !== undefined) {
42
- const w = waiting.get(m.id);
43
- waiting.delete(m.id);
44
- if (m.error)
45
- w?.reject(new CaptureError(m.error.message));
46
- else
47
- w?.resolve(m.result);
48
- }
49
- else if (m.method) {
50
- // Page.lifecycleEvent 的名字在参数里:load、networkIdle……
51
- const name = m.method === "Page.lifecycleEvent" ? `lifecycle:${m.params?.name}` : m.method;
52
- events.add(name);
53
- for (const l of listeners)
54
- l(name);
55
- }
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);
56
58
  };
57
- ws.onopen = () => resolve({
58
- send: (method, params = {}, sessionId) => new Promise((res, rej) => {
59
- if (closed)
60
- return rej(new CaptureError("the browser closed before the screenshot was taken"));
61
- const id = ++next;
62
- waiting.set(id, { resolve: res, reject: rej });
63
- ws.send(JSON.stringify({ id, method, params, sessionId }));
64
- }),
65
- seen: (method, ms) => new Promise((res) => {
66
- if (events.has(method))
67
- return res(true);
68
- const done = (ok) => {
69
- clearTimeout(timer);
70
- listeners.delete(l);
71
- res(ok);
72
- };
73
- const l = (name) => name === method && done(true);
74
- const timer = setTimeout(() => done(false), ms);
75
- listeners.add(l);
76
- }),
77
- close: () => ws.close(),
78
- });
59
+ const l = (name) => name === method && done(true);
60
+ const timer = setTimeout(() => done(false), ms);
61
+ listeners.add(l);
62
+ }),
63
+ close: () => ws.close()
79
64
  });
65
+ });
80
66
  }
81
- /** 浏览器把调试端口和连接路径写在用户目录的 DevToolsActivePort 里;等它出现 */
82
67
  async function debuggerUrl(profile, proc, signal) {
83
- let exited = false;
84
- void proc.exited.then(() => (exited = true));
85
- const deadline = Date.now() + READY_MS;
86
- for (;;) {
87
- signal.throwIfAborted();
88
- try {
89
- const [port, wsPath] = (await readFile(path.join(profile, "DevToolsActivePort"), "utf8")).trim().split("\n");
90
- if (port && wsPath)
91
- return `ws://127.0.0.1:${port}${wsPath}`;
92
- }
93
- catch {
94
- // 还没写出来
95
- }
96
- if (exited)
97
- throw new CaptureError("the browser exited before it was ready");
98
- if (Date.now() > deadline)
99
- throw new CaptureError(`the browser was not ready within ${READY_MS / 1000}s`);
100
- await new Promise((r) => setTimeout(r, 50));
101
- }
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
+ }
102
85
  }
103
- /**
104
- * 在页面里执行:滚动到 CSS 选择器匹配的第一个元素;选择器无效或没有匹配时,找第一个包含这段文字的元素。
105
- * 比视口高的元素对齐到顶部,其余的放在中间
106
- */
107
86
  const SCROLL = (what) => `(() => {
108
87
  const what = ${JSON.stringify(what)};
109
88
  let el = null;
@@ -121,67 +100,70 @@ const SCROLL = (what) => `(() => {
121
100
  })()`;
122
101
  const METRICS = "JSON.stringify({ h: Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0), y: Math.round(scrollY) })";
123
102
  export const capture = async (browser, req, signal) => {
124
- const proc = await spawn([
125
- browser,
126
- "--headless=new",
127
- "--disable-gpu",
128
- "--hide-scrollbars",
129
- "--no-first-run",
130
- "--no-default-browser-check",
131
- "--disable-extensions",
132
- "--mute-audio",
133
- "--remote-debugging-port=0",
134
- `--user-data-dir=${req.profile}`,
135
- "about:blank",
136
- ], { stdout: "ignore", stderr: "ignore" });
137
- // 中止(用户打断、总的超时)时不等页面:下面的等待都按自己的时间走,这里直接结束
138
- let abort;
139
- const aborted = new Promise((_, reject) => (abort = () => reject(signal.reason)));
140
- signal.addEventListener("abort", abort, { once: true });
141
- let cdp;
142
- const work = async () => {
143
- cdp = await connect(await debuggerUrl(req.profile, proc, signal));
144
- const { targetId } = await cdp.send("Target.createTarget", { url: "about:blank" });
145
- const { sessionId } = await cdp.send("Target.attachToTarget", { targetId, flatten: true });
146
- const page = (method, params) => cdp.send(method, params, sessionId);
147
- const evaluate = async (expression) => (await page("Runtime.evaluate", { expression, returnByValue: true })).result.value;
148
- await page("Emulation.setDeviceMetricsOverride", { width: req.width, height: req.height, deviceScaleFactor: 1, mobile: false });
149
- await page("Page.enable");
150
- await page("Page.setLifecycleEventsEnabled", { enabled: true });
151
- const { errorText } = await page("Page.navigate", { url: req.target });
152
- if (errorText)
153
- throw new CaptureError(`the page could not be loaded: ${errorText}`);
154
- const loaded = await cdp.seen("Page.loadEventFired", LOAD_MS);
155
- if (loaded)
156
- await cdp.seen("lifecycle:networkIdle", SETTLE_MS);
157
- signal.throwIfAborted();
158
- let scrolledTo;
159
- if (req.scrollTo !== undefined) {
160
- const found = await evaluate(SCROLL(req.scrollTo));
161
- if (found === null) {
162
- throw new CaptureError(`nothing on the page matches scroll_to ${JSON.stringify(req.scrollTo)} (tried as a CSS selector, then as text)` +
163
- (loaded ? "" : `; the page had not finished loading after ${LOAD_MS / 1000}s`));
164
- }
165
- scrolledTo = found;
166
- await new Promise((r) => setTimeout(r, SCROLL_SETTLE_MS));
167
- }
168
- const { h, y } = JSON.parse(await evaluate(METRICS));
169
- const { data } = await page("Page.captureScreenshot", { format: "png" });
170
- return {
171
- png: Buffer.from(data, "base64"),
172
- pageHeight: h,
173
- scrollY: y,
174
- scrolledTo,
175
- note: loaded ? undefined : `The page had not finished loading after ${LOAD_MS / 1000}s; this is how it looked at that point.`,
176
- };
177
- };
178
- try {
179
- return await Promise.race([work(), aborted]);
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));
180
144
  }
181
- finally {
182
- signal.removeEventListener("abort", abort);
183
- cdp?.close();
184
- proc.kill();
185
- await proc.exited;
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);
186
164
  }
165
+ cdp?.close();
166
+ proc.kill();
167
+ await proc.exited;
168
+ }
187
169
  };