web-forager 0.0.0-stage → 1.3.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 (82) hide show
  1. package/.claude-plugin/marketplace.json +16 -0
  2. package/.claude-plugin/plugin.json +20 -0
  3. package/.clinerules/web-forager.md +85 -0
  4. package/.codebuddy-plugin/marketplace.json +14 -0
  5. package/.codebuddy-plugin/plugin.json +25 -0
  6. package/.codex-plugin/marketplace.json +12 -0
  7. package/.codex-plugin/mcp.json +20 -0
  8. package/.codex-plugin/plugin.json +15 -0
  9. package/.continue/rules/web-forager.md +90 -0
  10. package/.cursor/rules/web-forager.mdc +80 -0
  11. package/.dsh-plugin/index.js +11 -0
  12. package/.dsh-plugin/plugin.json +5 -0
  13. package/.github/copilot-instructions.md +85 -0
  14. package/.mcp.json +12 -0
  15. package/.roo/rules/web-forager.md +85 -0
  16. package/.windsurf/rules/web-forager.md +90 -0
  17. package/AGENTS.md +112 -0
  18. package/CHANGELOG.md +454 -0
  19. package/LICENSE +21 -0
  20. package/README.md +477 -3
  21. package/README_zh.md +477 -0
  22. package/SKILL.md +351 -0
  23. package/THIRD_PARTY_LICENSES.txt +35 -0
  24. package/browser/bridges/playwright-bridge.js +375 -0
  25. package/browser/launch_chrome.py +144 -0
  26. package/browser/lib/backend.js +302 -0
  27. package/browser/lib/bili-api.js +79 -0
  28. package/browser/lib/bridge.js +83 -0
  29. package/browser/lib/context.js +60 -0
  30. package/browser/lib/doctor.js +97 -0
  31. package/browser/lib/errors.js +17 -0
  32. package/browser/lib/netguard.js +149 -0
  33. package/browser/lib/playbooks.js +30 -0
  34. package/browser/lib/record.js +109 -0
  35. package/browser/lib/robots.js +195 -0
  36. package/browser/lib/safety.js +115 -0
  37. package/browser/lib/selectors.js +80 -0
  38. package/browser/lib/session.js +116 -0
  39. package/browser/lib/snapshot.js +229 -0
  40. package/browser/lib/untrusted.js +56 -0
  41. package/browser/lib/workspace.js +40 -0
  42. package/browser/mcp_server.js +272 -0
  43. package/browser/package.json +40 -0
  44. package/browser/playbooks/bili-chain.js +58 -0
  45. package/browser/playbooks/bili-danmaku.js +102 -0
  46. package/browser/playbooks/bili-feed.js +66 -0
  47. package/browser/playbooks/bili-video.js +38 -0
  48. package/browser/playbooks/search-dig.js +105 -0
  49. package/browser/playbooks/shared.js +138 -0
  50. package/browser/playbooks/wechat-dig.js +78 -0
  51. package/browser/playbooks/xhs-dig.js +89 -0
  52. package/browser/playbooks/zhihu-dig.js +89 -0
  53. package/browser/run.js +432 -0
  54. package/commands/browse.md +53 -0
  55. package/commands/fetch.md +29 -0
  56. package/commands/map.md +24 -0
  57. package/commands/scholar.md +28 -0
  58. package/commands/surf.md +28 -0
  59. package/cordis.patch.yml +19 -0
  60. package/docs/ACKNOWLEDGEMENTS.md +15 -0
  61. package/docs/ACKNOWLEDGEMENTS_zh.md +15 -0
  62. package/docs/DEPENDENCIES.md +40 -0
  63. package/docs/INSTALL_COMMANDS.md +113 -0
  64. package/docs/INSTALL_COMMANDS_zh.md +113 -0
  65. package/docs/REFERENCE.md +308 -0
  66. package/docs/REFERENCE_zh.md +309 -0
  67. package/index.js +7 -0
  68. package/install.py +254 -0
  69. package/manifest.json +97 -0
  70. package/mcp_server.py +597 -0
  71. package/package.json +80 -6
  72. package/requirements.txt +12 -0
  73. package/run.py +852 -0
  74. package/scripts/__init__.py +1 -0
  75. package/scripts/bilibili.py +874 -0
  76. package/scripts/documents.py +437 -0
  77. package/scripts/engine.py +4220 -0
  78. package/scripts/feeds.py +180 -0
  79. package/scripts/pdf.py +135 -0
  80. package/scripts/scholar.py +354 -0
  81. package/scripts/sitemap.py +180 -0
  82. package/scripts/untrusted.py +95 -0
@@ -0,0 +1,302 @@
1
+ "use strict";
2
+
3
+ const { spawn } = require("node:child_process");
4
+ const { ActorError } = require("./errors");
5
+ const { splitCommand } = require("./bridge");
6
+
7
+ const BACKENDS = {
8
+ iab: "in-app browser session driven by a bridge process",
9
+ extension: "the user's logged-in browser through an extension bridge",
10
+ cdp: "a Chrome DevTools Protocol endpoint you already control",
11
+ };
12
+
13
+ class UnavailableBackend {
14
+ constructor(reason = "no browser bridge configured", backend = "unavailable") {
15
+ this.name = backend;
16
+ this.available = false;
17
+ this.reason = reason;
18
+ }
19
+
20
+ capabilities() {
21
+ return {
22
+ backend: this.name,
23
+ source: "unavailable",
24
+ declared: false,
25
+ loginState: false,
26
+ screenshot: false,
27
+ cua: false,
28
+ observe: false,
29
+ };
30
+ }
31
+
32
+ async goto() {
33
+ throw new ActorError(
34
+ "backend_unavailable",
35
+ this.reason,
36
+ "Set WEB_FORAGER_BRIDGE to a bridge command (for example `node bridge.js`) or pass --bridge.",
37
+ );
38
+ }
39
+
40
+ async snapshot() {
41
+ return this.goto();
42
+ }
43
+
44
+ async click() {
45
+ return this.goto();
46
+ }
47
+
48
+ async scroll() {
49
+ return this.goto();
50
+ }
51
+
52
+ async screenshot() {
53
+ return this.goto();
54
+ }
55
+
56
+ async currentUrl() {
57
+ const result = await this.request("url", {}, 3000);
58
+ return (result && result.url) || "";
59
+ }
60
+
61
+ async tabs() {
62
+ return this.goto();
63
+ }
64
+
65
+ async observe() {
66
+ return this.goto();
67
+ }
68
+
69
+ async close() {}
70
+ }
71
+
72
+ class BridgeBackend {
73
+ constructor(command, options = {}) {
74
+ this.name = options.name || "iab";
75
+ this.available = true;
76
+ this.command = command;
77
+ try {
78
+ this.argv = splitCommand(command);
79
+ } catch (error) {
80
+ throw new ActorError("argument", error.message, "Quote the whole path, or drop the stray quote.");
81
+ }
82
+ if (!this.argv.length) {
83
+ throw new ActorError(
84
+ "argument",
85
+ "empty browser bridge command",
86
+ "Pass --bridge, or unset WEB_FORAGER_BRIDGE to use the bundled bridge.",
87
+ );
88
+ }
89
+ this.timeout = options.timeout || 30000;
90
+ this.child = null;
91
+ this.buffer = "";
92
+ this.nextId = 1;
93
+ this.pending = new Map();
94
+ this.declared = null;
95
+ this.describeError = "";
96
+ this.closed = false;
97
+ this.stderr = "";
98
+ this.stderrLines = [];
99
+ }
100
+
101
+ // Capabilities are reported by the bridge itself through an optional
102
+ // `describe` call. A bridge that does not implement it gets the conservative
103
+ // answer instead of an optimistic one: every capability is false, so the
104
+ // playbooks never assume a call the bridge cannot serve.
105
+ async capabilities() {
106
+ if (this.declared) return { backend: this.name, source: "declared", declared: true, ...this.declared };
107
+ if (this.closed) {
108
+ return {
109
+ backend: this.name,
110
+ source: "undeclared",
111
+ declared: false,
112
+ reason: "the bridge was already closed",
113
+ loginState: false,
114
+ screenshot: false,
115
+ cua: false,
116
+ observe: false,
117
+ };
118
+ }
119
+ if (this.describeError) {
120
+ return {
121
+ backend: this.name,
122
+ source: "undeclared",
123
+ declared: false,
124
+ reason: this.describeError,
125
+ loginState: false,
126
+ screenshot: false,
127
+ cua: false,
128
+ observe: false,
129
+ };
130
+ }
131
+ try {
132
+ const described = await this.request("describe", {}, 2000);
133
+ const declared = (described && (described.capabilities || described)) || {};
134
+ this.declared = {
135
+ loginState: declared.loginState === true,
136
+ screenshot: declared.screenshot === true,
137
+ cua: declared.cua === true,
138
+ observe: declared.observe === true,
139
+ };
140
+ return { backend: this.name, source: "declared", declared: true, ...this.declared };
141
+ } catch (error) {
142
+ this.describeError = error && error.message ? error.message : String(error);
143
+ return {
144
+ backend: this.name,
145
+ source: "undeclared",
146
+ declared: false,
147
+ reason: this.describeError,
148
+ loginState: false,
149
+ screenshot: false,
150
+ cua: false,
151
+ observe: false,
152
+ };
153
+ }
154
+ }
155
+
156
+ start() {
157
+ if (this.child) return;
158
+ const [file, ...args] = this.argv;
159
+ // No shell: the command was split into an executable and its arguments, so
160
+ // a path or an environment value cannot smuggle a second command in.
161
+ const child = spawn(file, args, { shell: false, stdio: ["pipe", "pipe", "pipe"] });
162
+ this.child = child;
163
+ child.stdout.setEncoding("utf8");
164
+ child.stdout.on("data", (chunk) => this.onData(chunk));
165
+ // Keep the tail of stderr: when a bridge dies on startup its message is the
166
+ // only explanation the caller gets.
167
+ child.stderr.setEncoding("utf8");
168
+ child.stderr.on("data", (chunk) => {
169
+ for (const line of String(chunk).split(/\r?\n/)) {
170
+ if (!line.trim()) continue;
171
+ this.stderrLines.push(line);
172
+ if (this.stderrLines.length > 50) this.stderrLines.shift();
173
+ }
174
+ this.stderr = this.stderrLines.join("\n").slice(-4000);
175
+ });
176
+ child.on("exit", (code) => {
177
+ // Only clear the handle if this is still the current process: a restarted
178
+ // bridge must not be detached by the previous one's exit event.
179
+ if (this.child === child) {
180
+ this.child = null;
181
+ this.failAll(
182
+ new ActorError(
183
+ "backend_unavailable",
184
+ `browser bridge exited with code ${code}${this.stderr ? `: ${this.stderr.trim().slice(-500)}` : ""}`,
185
+ "Run the bridge command by hand to see its full output.",
186
+ ),
187
+ );
188
+ }
189
+ });
190
+ }
191
+
192
+ onData(chunk) {
193
+ this.buffer += chunk;
194
+ let newline = this.buffer.indexOf("\n");
195
+ while (newline >= 0) {
196
+ const line = this.buffer.slice(0, newline).trim();
197
+ this.buffer = this.buffer.slice(newline + 1);
198
+ if (line) this.onLine(line);
199
+ newline = this.buffer.indexOf("\n");
200
+ }
201
+ }
202
+
203
+ onLine(line) {
204
+ let message;
205
+ try {
206
+ message = JSON.parse(line);
207
+ } catch {
208
+ return;
209
+ }
210
+ const pending = this.pending.get(message.id);
211
+ if (!pending) return;
212
+ this.pending.delete(message.id);
213
+ clearTimeout(pending.timer);
214
+ if (message.error) {
215
+ pending.reject(new ActorError(message.error.code || "navigation", message.error.message || "bridge error"));
216
+ } else {
217
+ pending.resolve(message.result);
218
+ }
219
+ }
220
+
221
+ failAll(error) {
222
+ for (const [, pending] of this.pending) {
223
+ clearTimeout(pending.timer);
224
+ pending.reject(error);
225
+ }
226
+ this.pending.clear();
227
+ }
228
+
229
+ request(method, params = {}, timeoutMs) {
230
+ if (this.closed) {
231
+ return Promise.reject(new ActorError("backend_unavailable", "the browser bridge was closed"));
232
+ }
233
+ this.start();
234
+ const id = this.nextId++;
235
+ const budget = Number(timeoutMs) > 0 ? Number(timeoutMs) : this.timeout;
236
+ return new Promise((resolve, reject) => {
237
+ const timer = setTimeout(() => {
238
+ this.pending.delete(id);
239
+ const tail = this.stderrLines.length
240
+ ? ` (bridge stderr: ${this.stderrLines.slice(-3).join(" | ")})`
241
+ : "";
242
+ reject(new ActorError("navigation", `bridge request timed out: ${method}${tail}`));
243
+ }, budget);
244
+ this.pending.set(id, { resolve, reject, timer });
245
+ this.child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
246
+ });
247
+ }
248
+
249
+ async goto(url) {
250
+ await this.request("goto", { url });
251
+ }
252
+
253
+ async snapshot() {
254
+ return this.request("snapshot");
255
+ }
256
+
257
+ async click(locator) {
258
+ await this.request("click", { locator });
259
+ }
260
+
261
+ async scroll(dy) {
262
+ await this.request("scroll", { dy });
263
+ }
264
+
265
+ async screenshot() {
266
+ return this.request("screenshot");
267
+ }
268
+
269
+ async tabs() {
270
+ return this.request("tabs");
271
+ }
272
+
273
+ async observe(topic, ms) {
274
+ return this.request("observe", { topic, ms });
275
+ }
276
+
277
+ async close() {
278
+ this.closed = true;
279
+ if (!this.child) return;
280
+ this.child.kill();
281
+ this.child = null;
282
+ }
283
+ }
284
+
285
+ function createBackend(options = {}) {
286
+ const backend = options.backend || "iab";
287
+ if (!BACKENDS[backend]) {
288
+ throw new ActorError(
289
+ "argument",
290
+ `unknown backend: ${backend}`,
291
+ `Use one of: ${Object.keys(BACKENDS).join(", ")}.`,
292
+ );
293
+ }
294
+ const command = options.bridge || process.env.WEB_FORAGER_BRIDGE;
295
+ if (command) return new BridgeBackend(command, { ...options, name: backend });
296
+ return new UnavailableBackend(
297
+ options.reason || `no bridge command for backend "${backend}"`,
298
+ backend,
299
+ );
300
+ }
301
+
302
+ module.exports = { BACKENDS, UnavailableBackend, BridgeBackend, createBackend };
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+
3
+ // Bilibili's own search JSON, used before the result page is scraped.
4
+ //
5
+ // The page is a React app whose card markup changes without notice, and a
6
+ // screenshot-free snapshot of it yields "views + duration" instead of titles
7
+ // whenever the selectors drift. The public endpoint returns the same videos
8
+ // with stable fields, and it needs no login — only the `buvid3` cookie that any
9
+ // visit to the home page sets. Without that cookie the endpoint answers 412.
10
+
11
+ const UA =
12
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
13
+ const HOME = "https://www.bilibili.com/";
14
+ const SEARCH = "https://api.bilibili.com/x/web-interface/search/type";
15
+
16
+ function disabled() {
17
+ return String(process.env.WEB_FORAGER_BILI_API || "").toLowerCase() === "off";
18
+ }
19
+
20
+ function stripTags(value) {
21
+ return String(value || "")
22
+ .replace(/<[^>]*>/g, "")
23
+ .replace(/&amp;/g, "&")
24
+ .replace(/&quot;/g, '"')
25
+ .replace(/&#39;/g, "'")
26
+ .replace(/\s+/g, " ")
27
+ .trim();
28
+ }
29
+
30
+ async function collectCookies() {
31
+ const jar = [];
32
+ try {
33
+ const response = await fetch(HOME, { headers: { "user-agent": UA }, redirect: "follow" });
34
+ const raw =
35
+ typeof response.headers.getSetCookie === "function"
36
+ ? response.headers.getSetCookie()
37
+ : String(response.headers.get("set-cookie") || "").split(/,(?=[^ ;]+=)/);
38
+ for (const entry of raw) {
39
+ const pair = String(entry).split(";")[0];
40
+ if (pair.includes("=")) jar.push(pair.trim());
41
+ }
42
+ } catch (error) {
43
+ // The search call still works without a cookie on some networks; if it does
44
+ // not, the caller falls back to the page.
45
+ }
46
+ return jar.join("; ");
47
+ }
48
+
49
+ async function searchVideos(query, limit = 20) {
50
+ if (disabled()) throw new Error("disabled");
51
+ const cookie = await collectCookies();
52
+ const url = `${SEARCH}?search_type=video&keyword=${encodeURIComponent(query)}&page=1`;
53
+ const response = await fetch(url, {
54
+ headers: {
55
+ "user-agent": UA,
56
+ referer: HOME,
57
+ accept: "application/json",
58
+ ...(cookie ? { cookie } : {}),
59
+ },
60
+ });
61
+ if (!response.ok) throw new Error(`search API returned HTTP ${response.status}`);
62
+ const payload = await response.json();
63
+ if (payload.code !== 0) {
64
+ throw new Error(`search API code ${payload.code}: ${payload.message || "no message"}`);
65
+ }
66
+ const items = (payload.data && payload.data.result) || [];
67
+ return items.slice(0, limit).map((item) => ({
68
+ title: stripTags(item.title),
69
+ url: item.arcurl || `https://www.bilibili.com/video/${item.bvid}/`,
70
+ bvid: item.bvid || "",
71
+ author: item.author || "",
72
+ play: item.play,
73
+ duration: item.duration || "",
74
+ description: stripTags(item.description),
75
+ source: "bilibili-api",
76
+ }));
77
+ }
78
+
79
+ module.exports = { searchVideos, stripTags, disabled };
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+
3
+ // Where the bridge command comes from.
4
+ //
5
+ // Order:
6
+ // 1. an explicit --bridge value,
7
+ // 2. WEB_FORAGER_BRIDGE when it is set (an empty value disables discovery,
8
+ // which is what the tests use to exercise the no-bridge path),
9
+ // 3. the reference bridge that ships next to this file, if it exists.
10
+ //
11
+ // Step 3 is what makes a first run work without any configuration: the bridge
12
+ // lives in the same package as the playbooks, so requiring an environment
13
+ // variable to find it only produced a confusing `backend_unavailable`.
14
+
15
+ const fs = require("node:fs");
16
+ const path = require("node:path");
17
+
18
+ const BUNDLED_BRIDGE = path.join(__dirname, "..", "bridges", "playwright-bridge.js");
19
+
20
+ function bundledBridge() {
21
+ try {
22
+ return fs.existsSync(BUNDLED_BRIDGE) ? BUNDLED_BRIDGE : "";
23
+ } catch (error) {
24
+ return "";
25
+ }
26
+ }
27
+
28
+ function quote(value) {
29
+ return /\s/.test(value) ? `"${value}"` : value;
30
+ }
31
+
32
+ // The bridge command is executed directly, never through a shell. Split it on
33
+ // whitespace, keeping quoted paths together; backslashes are literal so a
34
+ // Windows path is not mistaken for an escape. Shell operators (pipes, `&&`,
35
+ // redirections) are therefore not interpreted.
36
+ function splitCommand(command) {
37
+ const text = String(command == null ? "" : command).trim();
38
+ if (!text) return [];
39
+ const parts = [];
40
+ let current = "";
41
+ let quoted = "";
42
+ let started = false;
43
+ for (const char of text) {
44
+ if (quoted) {
45
+ if (char === quoted) quoted = "";
46
+ else current += char;
47
+ continue;
48
+ }
49
+ if (char === '"' || char === "'") {
50
+ quoted = char;
51
+ started = true;
52
+ continue;
53
+ }
54
+ if (/\s/.test(char)) {
55
+ if (started) {
56
+ parts.push(current);
57
+ current = "";
58
+ started = false;
59
+ }
60
+ continue;
61
+ }
62
+ current += char;
63
+ started = true;
64
+ }
65
+ if (quoted) {
66
+ throw new Error(`unterminated ${quoted} quote in the bridge command`);
67
+ }
68
+ if (started) parts.push(current);
69
+ return parts;
70
+ }
71
+
72
+ function resolveBridge(explicit) {
73
+ const given = typeof explicit === "string" ? explicit.trim() : "";
74
+ if (given) return given;
75
+
76
+ const env = process.env.WEB_FORAGER_BRIDGE;
77
+ if (env !== undefined) return env.trim();
78
+
79
+ const bundled = bundledBridge();
80
+ return bundled ? `node ${quote(bundled)}` : "";
81
+ }
82
+
83
+ module.exports = { BUNDLED_BRIDGE, bundledBridge, resolveBridge, splitCommand };
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+
3
+ const { ActorError } = require("./errors");
4
+
5
+ function makeContext(options) {
6
+ const ctx = {
7
+ backend: options.backend,
8
+ session: options.session,
9
+ options: options.options || {},
10
+ sleep: options.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
11
+ lastActionAt: 0,
12
+ trace: [],
13
+ warnings: [],
14
+ records: [],
15
+ log: options.log || (() => {}),
16
+ // Compliance state is copied into every record, so a reader can tell
17
+ // whether robots.txt was consulted for this run without reading the CLI
18
+ // flags that produced it.
19
+ compliance: {
20
+ strict_robots: Boolean((options.options || {}).strictRobots),
21
+ robots_checked: false,
22
+ checks: [],
23
+ },
24
+ };
25
+ ctx.capture = (fields) => {
26
+ const record = options.makeRecord({
27
+ ...fields,
28
+ backend: ctx.backend.name,
29
+ interaction_trace: ctx.trace.slice(),
30
+ compliance: {
31
+ ...ctx.compliance,
32
+ robots_checked: ctx.compliance.checks.length > 0,
33
+ checks: ctx.compliance.checks.slice(-20),
34
+ },
35
+ });
36
+ ctx.records.push(record);
37
+ return record;
38
+ };
39
+ ctx.warn = (message) => {
40
+ ctx.warnings.push(message);
41
+ ctx.log(`warning: ${message}`);
42
+ };
43
+ return ctx;
44
+ }
45
+
46
+ async function withBackend(backend, fn) {
47
+ try {
48
+ return await fn();
49
+ } finally {
50
+ if (backend && typeof backend.close === "function") await backend.close();
51
+ }
52
+ }
53
+
54
+ function requireOption(ctx, key, message) {
55
+ const value = ctx.options[key];
56
+ if (!value) throw new ActorError("argument", message || `missing --${key}`);
57
+ return value;
58
+ }
59
+
60
+ module.exports = { makeContext, withBackend, requireOption };
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+
3
+ // Answer "why did my first browser run fail" before the playbook does.
4
+ //
5
+ // Two layers can be missing and they produce different errors: the playwright
6
+ // npm package (the bridge exits with a module error) and the Chromium binary it
7
+ // downloads separately (the launch fails). The report names both, plus where the
8
+ // bridge, the profile and Node itself are.
9
+
10
+ const fs = require("node:fs");
11
+ const os = require("node:os");
12
+ const path = require("node:path");
13
+ const { createRequire } = require("node:module");
14
+
15
+ const { BUNDLED_BRIDGE, resolveBridge } = require("./bridge");
16
+
17
+ const DEFAULT_PROFILE = path.join(os.homedir(), ".web-forager", "browser", "profile");
18
+
19
+ function resolveFrom(root, name) {
20
+ try {
21
+ return createRequire(path.join(root, "doctor.js")).resolve(name);
22
+ } catch (error) {
23
+ return "";
24
+ }
25
+ }
26
+
27
+ function playwrightReport(extraRoots = []) {
28
+ const roots = [...extraRoots, path.dirname(BUNDLED_BRIDGE), process.cwd()];
29
+ let resolved = "";
30
+ for (const root of roots) {
31
+ resolved = resolveFrom(root, "playwright");
32
+ if (resolved) break;
33
+ }
34
+ if (!resolved) {
35
+ return {
36
+ installed: false,
37
+ hint: "npm i playwright && npx playwright install chromium",
38
+ };
39
+ }
40
+ let version = "";
41
+ let chromium = "";
42
+ try {
43
+ const playwright = require(resolved);
44
+ version = (playwright && playwright._version) || "";
45
+ if (!version) {
46
+ try {
47
+ version = require(path.join(path.dirname(resolved), "package.json")).version || "";
48
+ } catch (error) {
49
+ version = "";
50
+ }
51
+ }
52
+ chromium = playwright.chromium.executablePath();
53
+ } catch (error) {
54
+ return { installed: true, path: resolved, version, chromium: "", error: String(error.message || error) };
55
+ }
56
+ const chromiumInstalled = Boolean(chromium) && fs.existsSync(chromium);
57
+ return {
58
+ installed: true,
59
+ path: resolved,
60
+ version,
61
+ chromium: chromiumInstalled ? chromium : "",
62
+ chromium_installed: chromiumInstalled,
63
+ ...(chromiumInstalled ? {} : { hint: "npx playwright install chromium" }),
64
+ };
65
+ }
66
+
67
+ function doctorReport() {
68
+ const command = resolveBridge("");
69
+ const bridgePath = command.startsWith("node ") ? command.slice(5).replace(/^"|"$/g, "") : "";
70
+ const playwright = playwrightReport(bridgePath ? [path.dirname(bridgePath)] : []);
71
+ const profile = (process.env.WEB_FORAGER_BROWSER_PROFILE || "").trim();
72
+ const profileDir = ["off", "0", "false", "none"].includes(profile.toLowerCase())
73
+ ? ""
74
+ : path.resolve(profile || DEFAULT_PROFILE);
75
+ const hints = [];
76
+ if (!command) hints.push("No bridge command: install the playwright package or set WEB_FORAGER_BRIDGE.");
77
+ if (!playwright.installed) hints.push("Playwright is not resolvable: npm i playwright.");
78
+ if (playwright.installed && playwright.chromium_installed === false) {
79
+ hints.push("Chromium is not downloaded: npx playwright install chromium.");
80
+ }
81
+ if (!profileDir) hints.push("The browser profile is disabled; each run starts without cookies.");
82
+ return {
83
+ ok: Boolean(command) && playwright.installed && playwright.chromium_installed !== false,
84
+ node: process.version,
85
+ bridge: {
86
+ command: command || "",
87
+ bundled: Boolean(bridgePath) && path.resolve(bridgePath) === path.resolve(BUNDLED_BRIDGE),
88
+ exists: Boolean(bridgePath) && fs.existsSync(bridgePath),
89
+ },
90
+ playwright,
91
+ profile: { dir: profileDir, exists: profileDir ? fs.existsSync(profileDir) : false },
92
+ cdp: process.env.WEB_FORAGER_BROWSER_CDP || "",
93
+ hints,
94
+ };
95
+ }
96
+
97
+ module.exports = { doctorReport, DEFAULT_PROFILE };
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+
3
+ class ActorError extends Error {
4
+ constructor(code, message, hint = "") {
5
+ super(message);
6
+ this.name = "ActorError";
7
+ this.code = code;
8
+ this.hint = hint;
9
+ }
10
+ }
11
+
12
+ function asActorError(error) {
13
+ if (error instanceof ActorError) return error;
14
+ return new ActorError("unexpected", error && error.message ? error.message : String(error));
15
+ }
16
+
17
+ module.exports = { ActorError, asActorError };