browserpaw 0.0.0-stage → 5.0.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 (45) hide show
  1. package/LICENSE +681 -0
  2. package/README.md +4 -2
  3. package/dist/v5/cli-files.cjs +147 -0
  4. package/dist/v5/cli.cjs +4028 -0
  5. package/dist/v5/extension/assets/popup-Djl4pI1R.css +359 -0
  6. package/dist/v5/extension/background.js +37712 -0
  7. package/dist/v5/extension/browserpaw-build.json +184 -0
  8. package/dist/v5/extension/chunks/popup-DjxqduQH.js +6542 -0
  9. package/dist/v5/extension/content-scripts/agent-cursor.js +1459 -0
  10. package/dist/v5/extension/icon/128.png +0 -0
  11. package/dist/v5/extension/icon/16.png +0 -0
  12. package/dist/v5/extension/icon/32.png +0 -0
  13. package/dist/v5/extension/icon/48.png +0 -0
  14. package/dist/v5/extension/icon/96.png +0 -0
  15. package/dist/v5/extension/images/cursor-chat.png +0 -0
  16. package/dist/v5/extension/inject-scripts/accessibility-tree-helper.js +1883 -0
  17. package/dist/v5/extension/inject-scripts/keyboard-helper.js +402 -0
  18. package/dist/v5/extension/inject-scripts/network-helper.js +213 -0
  19. package/dist/v5/extension/inject-scripts/screenshot-helper.js +408 -0
  20. package/dist/v5/extension/inpage-engine.js +9300 -0
  21. package/dist/v5/extension/manifest.json +1 -0
  22. package/dist/v5/extension/popup.html +14 -0
  23. package/dist/v5/host.cjs +19441 -0
  24. package/dist/v5/recipes/developer.mozilla.org.md +15 -0
  25. package/dist/v5/recipes/github-releases.json +177 -0
  26. package/dist/v5/recipes/mdn-search.json +174 -0
  27. package/dist/v5/recipes/npm-compare.json +456 -0
  28. package/dist/v5/recipes/x-search-thread.json +321 -0
  29. package/dist/v5/recipes/x-visible-thread.json +303 -0
  30. package/dist/v5/run_host.bat +7 -0
  31. package/dist/v5/run_host.sh +6 -0
  32. package/dist/v5/skill/browserpaw/SKILL.md +48 -0
  33. package/dist/v5/skill/browserpaw/assets/recipes/developer.mozilla.org.md +15 -0
  34. package/dist/v5/skill/browserpaw/assets/recipes/github-releases.json +177 -0
  35. package/dist/v5/skill/browserpaw/assets/recipes/mdn-search.json +174 -0
  36. package/dist/v5/skill/browserpaw/assets/recipes/npm-compare.json +456 -0
  37. package/dist/v5/skill/browserpaw/assets/recipes/x-search-thread.json +321 -0
  38. package/dist/v5/skill/browserpaw/assets/recipes/x-visible-thread.json +303 -0
  39. package/dist/v5/skill/browserpaw/references/TROUBLESHOOTING.md +7 -0
  40. package/dist/v5/skill/browserpaw/references/TROUBLESHOOTING.zh-CN.md +5 -0
  41. package/dist/v5/skill/browserpaw/references/browser-data.md +33 -0
  42. package/dist/v5/skill/browserpaw/references/commands.md +103 -0
  43. package/dist/v5/skill/browserpaw/references/debugging.md +32 -0
  44. package/dist/v5/skill/browserpaw/references/recipe-contract.md +46 -0
  45. package/package.json +67 -4
@@ -0,0 +1,4028 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __commonJS = (cb, mod) => function __require() {
13
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
14
+ };
15
+ var __export = (target, all) => {
16
+ for (var name in all)
17
+ __defProp(target, name, { get: all[name], enumerable: true });
18
+ };
19
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") {
21
+ for (let key of __getOwnPropNames(from))
22
+ if (!__hasOwnProp.call(to, key) && key !== except)
23
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
24
+ }
25
+ return to;
26
+ };
27
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
28
+ // If the importer is in node compatibility mode or this is not an ESM
29
+ // file that has been converted to a CommonJS file using a Babel-
30
+ // compatible transform (i.e. "__esModule" has not been set), then set
31
+ // "default" to the CommonJS "module.exports" for node compatibility.
32
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
33
+ mod
34
+ ));
35
+
36
+ // ../../packages/shared/dist/index.mjs
37
+ function parseSemver(versionStr) {
38
+ if (!versionStr || typeof versionStr !== "string") return null;
39
+ const trimmed = versionStr.trim();
40
+ if (!trimmed) return null;
41
+ const clean = trimmed.replace(/^refs\/tags\//, "").replace(/^release-/i, "").replace(/^[vV]/, "").trim();
42
+ if (!clean) return null;
43
+ const plusIdx = clean.indexOf("+");
44
+ const withoutBuild = plusIdx !== -1 ? clean.slice(0, plusIdx) : clean;
45
+ const dashIdx = withoutBuild.indexOf("-");
46
+ const corePart = dashIdx !== -1 ? withoutBuild.slice(0, dashIdx) : withoutBuild;
47
+ const prereleasePart = dashIdx !== -1 ? withoutBuild.slice(dashIdx + 1) : void 0;
48
+ const segments = corePart.split(".");
49
+ if (segments.length === 0 || segments.length > 4) return null;
50
+ const numSegments = [];
51
+ for (const seg of segments) {
52
+ if (!/^\d+$/.test(seg)) return null;
53
+ const num = Number.parseInt(seg, 10);
54
+ if (!Number.isFinite(num) || num < 0) return null;
55
+ numSegments.push(num);
56
+ }
57
+ const major = numSegments[0];
58
+ const minor = numSegments.length > 1 ? numSegments[1] : 0;
59
+ const patch = numSegments.length > 2 ? numSegments[2] : 0;
60
+ const build = numSegments.length > 3 ? numSegments[3] : void 0;
61
+ return {
62
+ major,
63
+ minor,
64
+ patch,
65
+ build,
66
+ prerelease: prereleasePart && prereleasePart.trim() ? prereleasePart.trim() : void 0,
67
+ raw: trimmed
68
+ };
69
+ }
70
+ function compareSemver(aStr, bStr) {
71
+ const a = parseSemver(aStr);
72
+ const b = parseSemver(bStr);
73
+ if (!a || !b) return 0;
74
+ if (a.major !== b.major) return a.major > b.major ? 1 : -1;
75
+ if (a.minor !== b.minor) return a.minor > b.minor ? 1 : -1;
76
+ if (a.patch !== b.patch) return a.patch > b.patch ? 1 : -1;
77
+ const aBuild = a.build ?? 0;
78
+ const bBuild = b.build ?? 0;
79
+ if (aBuild !== bBuild) return aBuild > bBuild ? 1 : -1;
80
+ if (!a.prerelease && b.prerelease) return 1;
81
+ if (a.prerelease && !b.prerelease) return -1;
82
+ if (!a.prerelease && !b.prerelease) return 0;
83
+ const aParts = a.prerelease.split(".");
84
+ const bParts = b.prerelease.split(".");
85
+ const maxLen = Math.max(aParts.length, bParts.length);
86
+ for (let i = 0; i < maxLen; i++) {
87
+ const aP = aParts[i];
88
+ const bP = bParts[i];
89
+ if (aP === void 0) return -1;
90
+ if (bP === void 0) return 1;
91
+ if (aP === bP) continue;
92
+ const aNum = /^\d+$/.test(aP) ? Number.parseInt(aP, 10) : null;
93
+ const bNum = /^\d+$/.test(bP) ? Number.parseInt(bP, 10) : null;
94
+ if (aNum !== null && bNum !== null) {
95
+ return aNum > bNum ? 1 : -1;
96
+ }
97
+ if (aNum !== null && bNum === null) {
98
+ return -1;
99
+ }
100
+ if (aNum === null && bNum !== null) {
101
+ return 1;
102
+ }
103
+ return aP.localeCompare(bP);
104
+ }
105
+ return 0;
106
+ }
107
+ function isNewerVersion(remoteVersion, currentVersion) {
108
+ const remote = parseSemver(remoteVersion);
109
+ const current = parseSemver(currentVersion);
110
+ if (!remote || !current) return false;
111
+ return compareSemver(remote.raw, current.raw) > 0;
112
+ }
113
+ function isProfileCommand(name) {
114
+ return /^(history|bookmark|downloads|cookies|window|group) /.test(name) || name === "tab move";
115
+ }
116
+ function parseCommand(argv) {
117
+ const qualified = `${argv[0]} ${argv[1]}`;
118
+ const name = isCommand(qualified) ? qualified : argv[0];
119
+ if (!isCommand(name)) throw new Error("Unknown command. Run browserpaw help.");
120
+ const usage = COMMANDS[name].usage;
121
+ const spec = new Map(
122
+ [...(usage + " " + globalOptions).matchAll(/--([a-z-]+)(?: ([A-Z][A-Z:-]*))?/g)].map(
123
+ ([, key, value]) => [key, Boolean(value)]
124
+ )
125
+ );
126
+ if (name === "tabs") spec.set("windows", false);
127
+ if (name === "select") spec.set("list", false);
128
+ const options = /* @__PURE__ */ Object.create(null);
129
+ const operands = [];
130
+ const input = argv.slice(name.split(" ").length);
131
+ for (let index = 0; index < input.length; index++) {
132
+ const token = input[index];
133
+ if (token === "--") {
134
+ operands.push(...input.slice(index + 1));
135
+ break;
136
+ }
137
+ if (!token.startsWith("--")) {
138
+ operands.push(token);
139
+ continue;
140
+ }
141
+ const separator = token.indexOf("=");
142
+ const key = token.slice(2, separator === -1 ? void 0 : separator);
143
+ const inlineValue = separator === -1 ? void 0 : token.slice(separator + 1);
144
+ if (!spec.has(key)) throw new Error(`Unknown option ${token} for ${name}.`);
145
+ if (options[key] !== void 0 && !repeated.has(key))
146
+ throw new Error(`Repeated option ${token}.`);
147
+ if (!spec.get(key)) {
148
+ if (inlineValue !== void 0) throw new Error(`Option --${key} does not take a value.`);
149
+ options[key] = true;
150
+ continue;
151
+ }
152
+ const value = inlineValue ?? input[++index];
153
+ if (value === void 0 || inlineValue === void 0 && value.startsWith("--"))
154
+ throw new Error(`Missing value for ${token}.`);
155
+ options[key] = repeated.has(key) ? [...options[key] ?? [], value] : value;
156
+ }
157
+ if (name === "tabs" && options.windows) {
158
+ if (operands.length || options.content || options.limit !== void 0)
159
+ throw new Error("Use window list without a query, --content or --limit.");
160
+ delete options.windows;
161
+ return { name: "window list", operands, options };
162
+ }
163
+ if (name === "select" && options.list) {
164
+ if (operands.length !== 1) throw new Error("Use select TARGET to list available choices.");
165
+ delete options.list;
166
+ }
167
+ return { name, operands, options };
168
+ }
169
+ function searchWords(text) {
170
+ return text.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
171
+ }
172
+ function searchCommands(query) {
173
+ const terms = [...new Set(searchWords(query))];
174
+ if (!terms.length) return [];
175
+ const phrase = terms.join(" ");
176
+ return Object.keys(COMMANDS).flatMap((name) => {
177
+ const spec = COMMANDS[name];
178
+ const commandWords = searchWords(name);
179
+ const topic = Object.entries(commandTopics).find(
180
+ ([, members]) => members.includes(name.split(" ")[0])
181
+ )?.[0];
182
+ const fields = [
183
+ { words: commandWords, weight: 10 },
184
+ { words: searchWords(spec.keywords?.join(" ") ?? ""), weight: 6 },
185
+ { words: searchWords(spec.summary), weight: 4 },
186
+ { words: searchWords(spec.usage + " " + (topic ?? "")), weight: 2 }
187
+ ];
188
+ let score = commandWords.join(" ") === phrase ? 30 : 0;
189
+ for (const term of terms) {
190
+ const best = Math.max(
191
+ ...fields.map(
192
+ ({ words, weight }) => words.includes(term) ? weight : term.length >= 2 && words.some((word) => word.startsWith(term)) ? weight - 1 : 0
193
+ )
194
+ );
195
+ if (!best) return [];
196
+ score += best;
197
+ }
198
+ return [
199
+ {
200
+ score,
201
+ item: {
202
+ name,
203
+ usage: `browserpaw ${spec.usage}`,
204
+ summary: spec.summary,
205
+ ...examples[name]?.[0] ? { example: `browserpaw ${examples[name][0]}` } : {}
206
+ }
207
+ }
208
+ ];
209
+ }).sort((a, b) => b.score - a.score).map(({ item }) => item);
210
+ }
211
+ function commandHelp(topic) {
212
+ if (topic === "targets") return TARGET_HELP;
213
+ if (topic === "recipes")
214
+ return "Learned skills and recipes live under ~/.browserpaw. Use recipe find to match by intent or URL, recipe show ID for inputs, recipe patch ID --step INDEX -- ARGS... to create a candidate revision, recipe run ID key=value to execute, recipe save FILE to save a candidate or propose a verified skill, and recipe validate ID key=value to activate only a verified read-only candidate.";
215
+ if (topic && isCommand(topic)) {
216
+ const spec = COMMANDS[topic];
217
+ return [
218
+ `browserpaw ${spec.usage}`,
219
+ spec.summary,
220
+ topic === "search" ? "Returns 8 matches by default. Use --limit 1\u201350 to change the count, --json for structured results, and -- before an option used as a keyword." : `Common options: ${topic === "task resume" ? "--json" : globalOptions}`,
221
+ exitHelp,
222
+ ...(examples[topic] ?? []).map((example) => `Example: browserpaw ${example}`)
223
+ ].join("\n");
224
+ }
225
+ if (topic) {
226
+ const members = Object.prototype.hasOwnProperty.call(commandTopics, topic) ? commandTopics[topic] : void 0;
227
+ const group = Object.entries(COMMANDS).filter(
228
+ ([name]) => members ? members.includes(name.split(" ")[0]) : name.startsWith(topic + " ")
229
+ );
230
+ if (group.length)
231
+ return group.map(([, spec]) => `browserpaw ${spec.usage}
232
+ ${spec.summary}`).join("\n");
233
+ throw new Error(`Unknown help topic ${topic}.`);
234
+ }
235
+ return [
236
+ "BrowserPaw CLI \u2014 control Chrome through the BrowserPaw extension.",
237
+ "Run browserpaw status to verify the connection, or browserpaw setup to install.",
238
+ "Workflow: task start \u2192 open --task ID \u2192 observe --task ID \u2192 act \u2192 verify \u2192 task finish --task ID.",
239
+ "Use --tab ID to select an existing tab, or --task ID for a task page. --json emits a single receipt.",
240
+ exitHelp,
241
+ "Run browserpaw search KEYWORD to find commands by name, purpose, or option.",
242
+ "Run browserpaw help GROUP for a list, help COMMAND for usage, or help targets for locator syntax.",
243
+ "",
244
+ ...Object.entries(commandTopics).map(
245
+ ([name, members]) => ` ${name.padEnd(9)} ${members.join(", ")}`
246
+ )
247
+ ].join("\n");
248
+ }
249
+ var DEFAULT_SERVER_PORT, HOST_NAME, TASK_ID, EXPLICIT_TARGET_SCHEMA, CAPTURE_NETWORK_SCHEMA, BROWSER_DATA_SCHEMA, TOOL_NAMES, schemas, TOOL_SCHEMAS, GITHUB_REPO_OWNER, GITHUB_REPO_NAME, GITHUB_REPO_URL, GITHUB_API_LATEST_RELEASE_URL, CURRENT_VERSION, DEFAULT_CACHE_TTL_MS, DEFAULT_MAX_SLIDING_WINDOW_MS, MemoryVersionCacheStorage, defaultMemoryCacheStorage, dataCommands, debugCommands, pageCommands, COMMANDS, globalOptions, repeated, isCommand, TARGET_HELP, examples, commandTopics, exitHelp;
250
+ var init_dist = __esm({
251
+ "../../packages/shared/dist/index.mjs"() {
252
+ "use strict";
253
+ DEFAULT_SERVER_PORT = 12307;
254
+ HOST_NAME = "com.browserpaw.nativehost";
255
+ TASK_ID = { type: "string" };
256
+ EXPLICIT_TARGET_SCHEMA = {
257
+ type: "object",
258
+ properties: {
259
+ index: { type: "number" },
260
+ frameId: { type: "integer", minimum: 0 },
261
+ ref: { type: ["string", "number"] },
262
+ selector: { type: "string" },
263
+ text: { type: "string" },
264
+ role: { type: "string" },
265
+ label: { type: "string" },
266
+ exact: { type: "boolean" }
267
+ },
268
+ additionalProperties: false,
269
+ anyOf: [
270
+ { required: ["index"] },
271
+ { required: ["ref"] },
272
+ { required: ["selector"] },
273
+ { required: ["text"] },
274
+ { required: ["role"] },
275
+ { required: ["label"] }
276
+ ]
277
+ };
278
+ CAPTURE_NETWORK_SCHEMA = {
279
+ type: "object",
280
+ properties: {
281
+ urlPattern: { type: "string" },
282
+ method: { type: "string" },
283
+ timeoutMs: { type: "number" },
284
+ statusCodes: { type: "array", items: { type: "number" } }
285
+ },
286
+ required: ["urlPattern"]
287
+ };
288
+ BROWSER_DATA_SCHEMA = {
289
+ type: "object",
290
+ properties: { action: { type: "string" } },
291
+ required: ["action"]
292
+ };
293
+ TOOL_NAMES = {
294
+ BROWSER: {
295
+ GET_WINDOWS_AND_TABS: "get_windows_and_tabs",
296
+ NAVIGATE: "chrome_navigate",
297
+ SCREENSHOT: "chrome_screenshot",
298
+ CLOSE_TABS: "chrome_close_tabs",
299
+ SWITCH_TAB: "chrome_switch_tab",
300
+ CLICK: "chrome_click_element",
301
+ NETWORK_CAPTURE: "chrome_network_capture",
302
+ NETWORK_REQUEST: "chrome_network_request",
303
+ KEYBOARD: "chrome_keyboard",
304
+ HISTORY: "chrome_history",
305
+ BOOKMARKS: "chrome_bookmarks",
306
+ DOWNLOADS: "chrome_downloads",
307
+ COOKIES: "chrome_cookies",
308
+ JAVASCRIPT: "chrome_javascript",
309
+ CONSOLE: "chrome_console",
310
+ FILE_UPLOAD: "chrome_upload_file",
311
+ HANDLE_DIALOG: "chrome_handle_dialog",
312
+ HANDLE_DOWNLOAD: "chrome_handle_download",
313
+ PERFORMANCE_START_TRACE: "performance_start_trace",
314
+ PERFORMANCE_STOP_TRACE: "performance_stop_trace",
315
+ PERFORMANCE_ANALYZE_INSIGHT: "performance_analyze_insight",
316
+ READ_DOM: "chrome_read_dom",
317
+ INTERACT_INDEX: "chrome_interact_index",
318
+ FILL_INDEX: "chrome_fill_index",
319
+ BATCH_ACTIONS: "chrome_batch_actions",
320
+ GET_MARKDOWN: "chrome_get_markdown",
321
+ GET_DROPDOWN_OPTIONS: "chrome_get_dropdown_options",
322
+ TAB_GROUP_CREATE: "chrome_tab_group_create",
323
+ TAB_GROUP_UPDATE: "chrome_tab_group_update",
324
+ TAB_GROUP_LIST: "chrome_tab_group_list",
325
+ TAB_GROUP_UNGROUP: "chrome_tab_group_ungroup",
326
+ TAB_GROUP_CLOSE: "chrome_tab_group_close",
327
+ SMART_SCROLL: "chrome_smart_scroll",
328
+ STORAGE: "chrome_storage",
329
+ INSPECT_MEDIA: "chrome_inspect_media",
330
+ REQUEST_HUMAN_INTERVENTION: "chrome_request_human_intervention",
331
+ DOCTOR: "chrome_doctor",
332
+ CDP_EXECUTE: "chrome_cdp_execute",
333
+ GREP: "chrome_grep",
334
+ DISMISS_OVERLAY: "chrome_dismiss_overlay",
335
+ SCROLL_UNTIL_FOUND: "chrome_scroll_until_found"
336
+ },
337
+ NATIVE: {
338
+ TASK: "chrome_task",
339
+ SKILL: "chrome_skill"
340
+ }
341
+ };
342
+ schemas = [
343
+ ...[
344
+ TOOL_NAMES.BROWSER.HISTORY,
345
+ TOOL_NAMES.BROWSER.BOOKMARKS,
346
+ TOOL_NAMES.BROWSER.DOWNLOADS,
347
+ TOOL_NAMES.BROWSER.COOKIES,
348
+ TOOL_NAMES.BROWSER.STORAGE,
349
+ "chrome_debug",
350
+ "chrome_page",
351
+ TOOL_NAMES.BROWSER.TAB_GROUP_LIST,
352
+ TOOL_NAMES.BROWSER.TAB_GROUP_CREATE,
353
+ TOOL_NAMES.BROWSER.TAB_GROUP_UPDATE,
354
+ TOOL_NAMES.BROWSER.TAB_GROUP_UNGROUP,
355
+ TOOL_NAMES.BROWSER.TAB_GROUP_CLOSE,
356
+ TOOL_NAMES.BROWSER.INSPECT_MEDIA,
357
+ TOOL_NAMES.BROWSER.DISMISS_OVERLAY
358
+ ].map((name) => ({ name, inputSchema: BROWSER_DATA_SCHEMA })),
359
+ {
360
+ name: TOOL_NAMES.NATIVE.TASK,
361
+ inputSchema: {
362
+ type: "object",
363
+ properties: {
364
+ action: {
365
+ type: "string",
366
+ enum: [
367
+ "start",
368
+ "list",
369
+ "status",
370
+ "resume",
371
+ "takeOver",
372
+ "open",
373
+ "borrow",
374
+ "handOff",
375
+ "finish",
376
+ "cancel"
377
+ ]
378
+ },
379
+ taskId: { type: "string" },
380
+ name: { type: "string" },
381
+ goal: { type: "string" },
382
+ url: { type: "string" },
383
+ tabId: { type: "integer", minimum: 1 },
384
+ keep: { type: "array", items: { type: "integer", minimum: 1 } },
385
+ keepUnknownPages: { type: "boolean" },
386
+ adopt: { type: "boolean" },
387
+ confirm: { type: "boolean" }
388
+ },
389
+ required: ["action"],
390
+ additionalProperties: false
391
+ }
392
+ },
393
+ {
394
+ name: TOOL_NAMES.NATIVE.SKILL,
395
+ inputSchema: {
396
+ type: "object",
397
+ properties: {
398
+ action: {
399
+ type: "string",
400
+ enum: ["find", "list", "get", "propose", "validate", "run", "disable", "rollback"]
401
+ },
402
+ id: { type: "string", pattern: "^[a-z][a-z0-9-]{0,63}$" },
403
+ url: { type: "string" },
404
+ intent: { type: "string" },
405
+ version: { type: "integer", minimum: 1 },
406
+ definitionHash: { type: "string", pattern: "^[a-f0-9]{64}$" },
407
+ taskId: { type: "string" },
408
+ inputs: { type: "object", additionalProperties: true },
409
+ definition: { type: "object", additionalProperties: true }
410
+ },
411
+ required: ["action"],
412
+ additionalProperties: false
413
+ }
414
+ },
415
+ {
416
+ name: TOOL_NAMES.BROWSER.GET_WINDOWS_AND_TABS,
417
+ inputSchema: { type: "object", properties: {}, required: [] }
418
+ },
419
+ {
420
+ name: TOOL_NAMES.BROWSER.NAVIGATE,
421
+ inputSchema: {
422
+ type: "object",
423
+ properties: {
424
+ url: { type: "string" },
425
+ action: { type: "string", enum: ["back", "forward"] },
426
+ newWindow: { type: "boolean" },
427
+ newTab: { type: "boolean" },
428
+ tabId: { type: "number" },
429
+ windowId: { type: "number" },
430
+ background: { type: "boolean" },
431
+ width: { type: "number" },
432
+ height: { type: "number" },
433
+ refresh: { type: "boolean" },
434
+ groupTitle: { type: "string" },
435
+ groupColor: {
436
+ type: "string",
437
+ enum: ["grey", "blue", "red", "yellow", "green", "pink", "purple", "cyan", "orange"]
438
+ },
439
+ autoGroup: { type: "boolean" },
440
+ dismissOverlays: { type: "boolean" }
441
+ },
442
+ required: []
443
+ }
444
+ },
445
+ {
446
+ name: TOOL_NAMES.BROWSER.SCREENSHOT,
447
+ inputSchema: {
448
+ type: "object",
449
+ properties: {
450
+ name: { type: "string" },
451
+ selector: { type: "string" },
452
+ assetIndex: { type: "number" },
453
+ tabId: { type: "number" },
454
+ windowId: { type: "number" },
455
+ background: { type: "boolean" },
456
+ width: { type: "number" },
457
+ height: { type: "number" },
458
+ maxWidth: { type: "number" },
459
+ maxDimension: { type: "number" },
460
+ maxPixels: { type: "number" },
461
+ storeBase64: { type: "boolean" },
462
+ fullPage: { type: "boolean" },
463
+ maxHeight: { type: "number" },
464
+ savePng: { type: "boolean" },
465
+ saveToDisk: { type: "boolean" },
466
+ som: { type: "boolean" },
467
+ highlight: { type: "boolean" },
468
+ targetIndex: { type: "number" },
469
+ index: { type: "number" },
470
+ padding: { type: "number" },
471
+ region: {
472
+ type: "object",
473
+ properties: {
474
+ x0: { type: "number" },
475
+ y0: { type: "number" },
476
+ x1: { type: "number" },
477
+ y1: { type: "number" }
478
+ }
479
+ },
480
+ crop: { type: "object" },
481
+ grid: { type: "boolean" },
482
+ enableGrid: { type: "boolean" },
483
+ expandSearchArea: { type: "boolean" },
484
+ format: { type: "string", enum: ["png", "jpeg"] },
485
+ quality: { type: "number" },
486
+ highClarity: { type: "boolean" },
487
+ sessionId: { type: "string" }
488
+ },
489
+ required: []
490
+ }
491
+ },
492
+ {
493
+ name: TOOL_NAMES.BROWSER.CLOSE_TABS,
494
+ inputSchema: {
495
+ type: "object",
496
+ properties: {
497
+ tabId: { type: "number" },
498
+ tabIds: { type: "array", items: { type: "number" } },
499
+ expectedTabs: {
500
+ type: "array",
501
+ items: {
502
+ type: "object",
503
+ properties: {
504
+ tabId: { type: "number" },
505
+ documentId: { type: "string" },
506
+ browserInstanceId: { type: "string" }
507
+ },
508
+ required: ["tabId", "documentId", "browserInstanceId"]
509
+ }
510
+ },
511
+ url: { type: "string" },
512
+ confirm: { type: "boolean" },
513
+ allManagedGroups: { type: "boolean" }
514
+ },
515
+ required: []
516
+ }
517
+ },
518
+ {
519
+ name: TOOL_NAMES.BROWSER.SWITCH_TAB,
520
+ inputSchema: {
521
+ type: "object",
522
+ properties: {
523
+ tabId: { type: "number" },
524
+ windowId: { type: "number" },
525
+ background: { type: "boolean" }
526
+ },
527
+ required: ["tabId"]
528
+ }
529
+ },
530
+ {
531
+ name: TOOL_NAMES.BROWSER.NETWORK_REQUEST,
532
+ inputSchema: {
533
+ type: "object",
534
+ properties: {
535
+ url: { type: "string" },
536
+ method: { type: "string" },
537
+ headers: { type: "object" },
538
+ body: { type: "string" },
539
+ timeout: { type: "number" },
540
+ formData: { type: "object" },
541
+ tabId: { type: "number" },
542
+ tabUrl: { type: "string" },
543
+ sessionId: { type: "string" },
544
+ sessionContext: { type: "string" }
545
+ },
546
+ required: ["url"]
547
+ }
548
+ },
549
+ {
550
+ name: TOOL_NAMES.BROWSER.NETWORK_CAPTURE,
551
+ inputSchema: {
552
+ type: "object",
553
+ properties: {
554
+ action: { type: "string", enum: ["start", "stop", "list", "show", "clear", "status"] },
555
+ requestId: { type: "string" },
556
+ outputPath: { type: "string" },
557
+ method: { type: "string" },
558
+ status: { type: "integer" },
559
+ resourceType: { type: "string" },
560
+ limit: { type: "integer" },
561
+ needResponseBody: { type: "boolean" },
562
+ url: { type: "string" },
563
+ requestUrlPattern: { type: "string" },
564
+ maxCaptureTime: { type: "number" },
565
+ inactivityTimeout: { type: "number" },
566
+ includeStatic: { type: "boolean" }
567
+ },
568
+ required: ["action"]
569
+ }
570
+ },
571
+ {
572
+ name: TOOL_NAMES.BROWSER.HANDLE_DOWNLOAD,
573
+ inputSchema: {
574
+ type: "object",
575
+ properties: {
576
+ tabId: { type: "integer", minimum: 1 },
577
+ guid: { type: "string", minLength: 1, maxLength: 128 },
578
+ clickTargetIndex: { type: "integer", minimum: 1 },
579
+ index: { type: "number" },
580
+ frameId: { type: "integer", minimum: 0 },
581
+ filenameContains: { type: "string" },
582
+ timeoutMs: { type: "integer", minimum: 50, maximum: 3e5 },
583
+ waitForComplete: { type: "boolean" }
584
+ },
585
+ required: [],
586
+ oneOf: [
587
+ {
588
+ required: ["guid"],
589
+ anyOf: [{ required: ["tabId"] }, { required: ["taskId"] }],
590
+ not: { anyOf: [{ required: ["clickTargetIndex"] }, { required: ["frameId"] }] }
591
+ },
592
+ {
593
+ required: ["clickTargetIndex"],
594
+ anyOf: [{ required: ["tabId"] }, { required: ["taskId"] }],
595
+ not: { required: ["guid"] }
596
+ },
597
+ {
598
+ not: {
599
+ anyOf: [
600
+ { required: ["tabId"] },
601
+ { required: ["taskId"] },
602
+ { required: ["guid"] },
603
+ { required: ["clickTargetIndex"] },
604
+ { required: ["frameId"] }
605
+ ]
606
+ }
607
+ }
608
+ ]
609
+ }
610
+ },
611
+ {
612
+ name: TOOL_NAMES.BROWSER.JAVASCRIPT,
613
+ inputSchema: {
614
+ type: "object",
615
+ properties: {
616
+ code: { type: "string" },
617
+ frameId: { type: "integer", minimum: 0 },
618
+ tabId: { type: "number" },
619
+ timeoutMs: { type: "number" },
620
+ maxOutputBytes: { type: "number" }
621
+ },
622
+ required: ["code"]
623
+ }
624
+ },
625
+ {
626
+ name: TOOL_NAMES.BROWSER.KEYBOARD,
627
+ inputSchema: {
628
+ type: "object",
629
+ properties: {
630
+ keys: { type: "string" },
631
+ index: { type: "integer" },
632
+ selector: { type: "string" },
633
+ text: { type: "string" },
634
+ role: { type: "string" },
635
+ label: { type: "string" },
636
+ exact: { type: "boolean" },
637
+ selectorType: { type: "string", enum: ["css", "xpath"] },
638
+ delay: { type: "number" },
639
+ tabId: { type: "number" },
640
+ windowId: { type: "number" },
641
+ frameId: { type: "number" },
642
+ sessionId: { type: "string" }
643
+ },
644
+ required: ["keys"]
645
+ }
646
+ },
647
+ {
648
+ name: TOOL_NAMES.BROWSER.CONSOLE,
649
+ inputSchema: {
650
+ type: "object",
651
+ properties: {
652
+ url: { type: "string" },
653
+ tabId: { type: "number" },
654
+ windowId: { type: "number" },
655
+ background: { type: "boolean" },
656
+ includeExceptions: { type: "boolean" },
657
+ maxMessages: { type: "number" },
658
+ mode: { type: "string", enum: ["snapshot", "buffer", "stop"] },
659
+ buffer: { type: "boolean" },
660
+ clear: { type: "boolean" },
661
+ clearAfterRead: { type: "boolean" },
662
+ pattern: { type: "string" },
663
+ onlyErrors: { type: "boolean" },
664
+ limit: { type: "number" }
665
+ },
666
+ required: []
667
+ }
668
+ },
669
+ {
670
+ name: TOOL_NAMES.BROWSER.FILE_UPLOAD,
671
+ inputSchema: {
672
+ type: "object",
673
+ properties: {
674
+ tabId: { type: "number" },
675
+ frameId: { type: "integer", minimum: 0 },
676
+ windowId: { type: "number" },
677
+ selector: { type: "string" },
678
+ index: { type: "number" },
679
+ clickTargetIndex: { type: "number" },
680
+ filePath: { type: "string" },
681
+ fileUrl: { type: "string" },
682
+ base64Data: { type: "string" },
683
+ fileName: { type: "string" },
684
+ multiple: { type: "boolean" },
685
+ sessionId: { type: "string" }
686
+ },
687
+ required: []
688
+ }
689
+ },
690
+ {
691
+ name: TOOL_NAMES.BROWSER.HANDLE_DIALOG,
692
+ inputSchema: {
693
+ type: "object",
694
+ properties: {
695
+ dialogId: { type: "string" },
696
+ action: { type: "string", enum: ["accept", "dismiss"] },
697
+ promptText: { type: "string" },
698
+ tabId: { type: "number" },
699
+ windowId: { type: "number" },
700
+ sessionId: { type: "string" }
701
+ },
702
+ required: ["action"]
703
+ }
704
+ },
705
+ {
706
+ name: TOOL_NAMES.BROWSER.READ_DOM,
707
+ inputSchema: {
708
+ type: "object",
709
+ properties: {
710
+ selector: { type: "string" },
711
+ scope: { type: "string" },
712
+ isolateModal: { type: "boolean" },
713
+ exclude: {
714
+ oneOf: [{ type: "string" }, { type: "array", items: { type: "string" } }]
715
+ },
716
+ viewportThreshold: { type: "number" },
717
+ tabId: { type: "number" },
718
+ windowId: { type: "number" },
719
+ highlight: { type: "boolean" },
720
+ sessionId: { type: "string" },
721
+ cursor: { type: "number" },
722
+ limit: { type: "number" },
723
+ maxTextLength: { type: "number" },
724
+ includeDetails: { type: "boolean" },
725
+ viewportOnly: { type: "boolean" },
726
+ activeViewportOnly: { type: "boolean" },
727
+ format: { type: "string", enum: ["compact", "html", "fast"] },
728
+ fast: { type: "boolean" },
729
+ legacyVisibility: { type: "boolean" },
730
+ deltaOnly: { type: "boolean" },
731
+ dismissOverlays: { type: "boolean" },
732
+ virtualizeViewport: { type: "boolean" },
733
+ flattenCards: { type: "boolean" }
734
+ },
735
+ required: []
736
+ }
737
+ },
738
+ {
739
+ name: TOOL_NAMES.BROWSER.INTERACT_INDEX,
740
+ inputSchema: {
741
+ type: "object",
742
+ properties: {
743
+ index: { type: "number" },
744
+ frameId: { type: "integer", minimum: 0 },
745
+ coordinate: {
746
+ oneOf: [
747
+ {
748
+ type: "object",
749
+ properties: { x: { type: "number" }, y: { type: "number" } },
750
+ required: ["x", "y"]
751
+ },
752
+ { type: "array", items: { type: "number" } }
753
+ ]
754
+ },
755
+ coordinateSpace: { type: "string", enum: ["viewport", "screenshot"] },
756
+ captureId: { type: "string" },
757
+ autoSnap: { type: "boolean" },
758
+ points: {
759
+ type: "array",
760
+ items: {
761
+ type: "object",
762
+ properties: { x: { type: "number" }, y: { type: "number" } },
763
+ required: ["x", "y"]
764
+ }
765
+ },
766
+ intervalMs: { type: "number" },
767
+ action: {
768
+ type: "string",
769
+ enum: ["click", "hover", "double_click", "right_click", "drag"]
770
+ },
771
+ path: {
772
+ type: "array",
773
+ items: {
774
+ type: "object",
775
+ properties: { x: { type: "number" }, y: { type: "number" } },
776
+ required: ["x", "y"]
777
+ }
778
+ },
779
+ end: {
780
+ type: "object",
781
+ properties: {
782
+ index: { type: "number" },
783
+ coordinate: {
784
+ type: "object",
785
+ properties: { x: { type: "number" }, y: { type: "number" } },
786
+ required: ["x", "y"]
787
+ }
788
+ }
789
+ },
790
+ steps: { type: "number" },
791
+ holdMs: { type: "number" },
792
+ dnd: { type: "boolean" },
793
+ modifiers: {
794
+ type: "array",
795
+ items: { type: "string", enum: ["Alt", "Control", "Meta", "Shift"] }
796
+ },
797
+ tabId: { type: "number" },
798
+ windowId: { type: "number" },
799
+ waitForSettle: { type: "boolean" },
800
+ settleTimeoutMs: { type: "number" },
801
+ humanize: { type: "boolean" },
802
+ includeDelta: { type: "boolean" },
803
+ sessionId: { type: "string" },
804
+ pierceOverlay: { type: "boolean" },
805
+ waitForNetworkQuiescence: { type: "boolean" },
806
+ quiescenceTimeoutMs: { type: "number" },
807
+ captureNetwork: CAPTURE_NETWORK_SCHEMA
808
+ },
809
+ required: []
810
+ }
811
+ },
812
+ {
813
+ name: TOOL_NAMES.BROWSER.FILL_INDEX,
814
+ inputSchema: {
815
+ type: "object",
816
+ properties: {
817
+ index: { type: "number" },
818
+ frameId: { type: "integer", minimum: 0 },
819
+ text: { type: "string" },
820
+ value: { type: "string" },
821
+ clear: { type: "boolean" },
822
+ pressEnter: { type: "boolean" },
823
+ submit: { type: "boolean" },
824
+ submitTarget: EXPLICIT_TARGET_SCHEMA,
825
+ tabId: { type: "number" },
826
+ windowId: { type: "number" },
827
+ waitForSettle: { type: "boolean" },
828
+ settleTimeoutMs: { type: "number" },
829
+ includeDelta: { type: "boolean" },
830
+ sessionId: { type: "string" }
831
+ },
832
+ required: ["index"]
833
+ }
834
+ },
835
+ {
836
+ name: TOOL_NAMES.BROWSER.BATCH_ACTIONS,
837
+ inputSchema: {
838
+ type: "object",
839
+ properties: {
840
+ actions: {
841
+ type: "array",
842
+ items: {
843
+ type: "object",
844
+ properties: {
845
+ type: {
846
+ type: "string",
847
+ enum: [
848
+ "click",
849
+ "double_click",
850
+ "right_click",
851
+ "fill",
852
+ "hover",
853
+ "scroll",
854
+ "press_key",
855
+ "wait",
856
+ "key",
857
+ "fill_form",
858
+ "assert",
859
+ "extract"
860
+ ]
861
+ },
862
+ index: { type: "number" },
863
+ frameId: { type: "integer", minimum: 0 },
864
+ ref: { type: ["string", "number"] },
865
+ selector: { type: "string" },
866
+ targetText: { type: "string" },
867
+ role: { type: "string" },
868
+ label: { type: "string" },
869
+ exact: { type: "boolean" },
870
+ clear: { type: "boolean" },
871
+ pressEnter: { type: "boolean" },
872
+ submit: { type: "boolean" },
873
+ submitTarget: EXPLICIT_TARGET_SCHEMA,
874
+ fields: {
875
+ type: "array",
876
+ items: {
877
+ type: "object",
878
+ properties: {
879
+ ref: { type: ["string", "number"] },
880
+ index: { type: "number" },
881
+ selector: { type: "string" },
882
+ value: { type: ["string", "number", "boolean"] },
883
+ text: { type: "string" },
884
+ clear: { type: "boolean" }
885
+ },
886
+ required: []
887
+ }
888
+ },
889
+ text: { type: "string" },
890
+ value: { type: "string" },
891
+ key: { type: "string" },
892
+ coordinate: {
893
+ oneOf: [
894
+ {
895
+ type: "object",
896
+ properties: { x: { type: "number" }, y: { type: "number" } },
897
+ required: ["x", "y"]
898
+ },
899
+ { type: "array", items: { type: "number" } }
900
+ ]
901
+ },
902
+ x: { type: "number" },
903
+ y: { type: "number" },
904
+ at: { type: "number" },
905
+ direction: { type: "string", enum: ["up", "down", "left", "right"] },
906
+ amount: { type: "number" },
907
+ note: { type: "string" },
908
+ durationMs: { type: "number" },
909
+ waitForSettle: { type: "boolean" },
910
+ settleTimeoutMs: { type: "number" },
911
+ waitForNetworkQuiescence: { type: "boolean" },
912
+ quiescenceTimeoutMs: { type: "number" },
913
+ pierceOverlay: { type: "boolean" },
914
+ preferComposer: { type: "boolean" },
915
+ expectedText: { type: "string" },
916
+ condition: {
917
+ type: "string",
918
+ enum: [
919
+ "contains",
920
+ "not_contains",
921
+ "equals",
922
+ "matches",
923
+ "visible",
924
+ "not_visible",
925
+ "enabled",
926
+ "disabled",
927
+ "valid",
928
+ "invalid",
929
+ "checked",
930
+ "unchecked"
931
+ ]
932
+ },
933
+ timeoutMs: { type: "number" },
934
+ abortOnFailure: { type: "boolean" },
935
+ property: { type: "string", enum: ["text", "value", "attribute"] },
936
+ attributeName: { type: "string" },
937
+ variableName: { type: "string" },
938
+ captureNetwork: CAPTURE_NETWORK_SCHEMA
939
+ },
940
+ required: ["type"]
941
+ }
942
+ },
943
+ tabId: { type: "number" },
944
+ windowId: { type: "number" },
945
+ waitForSettle: { type: "boolean" },
946
+ settleTimeoutMs: { type: "number" },
947
+ waitForNetworkQuiescence: { type: "boolean" },
948
+ quiescenceTimeoutMs: { type: "number" },
949
+ includeDelta: { type: "boolean" },
950
+ sessionId: { type: "string" },
951
+ captureNetwork: CAPTURE_NETWORK_SCHEMA
952
+ },
953
+ required: ["actions"]
954
+ }
955
+ },
956
+ {
957
+ name: TOOL_NAMES.BROWSER.GET_MARKDOWN,
958
+ inputSchema: {
959
+ type: "object",
960
+ properties: {
961
+ includeLinks: { type: "boolean" },
962
+ fit: { type: "boolean" },
963
+ tabId: { type: "number" },
964
+ windowId: { type: "number" },
965
+ sessionId: { type: "string" }
966
+ },
967
+ required: []
968
+ }
969
+ },
970
+ {
971
+ name: TOOL_NAMES.BROWSER.GET_DROPDOWN_OPTIONS,
972
+ inputSchema: {
973
+ type: "object",
974
+ properties: {
975
+ index: { type: "number" },
976
+ selector: { type: "string" },
977
+ tabId: { type: "number" },
978
+ windowId: { type: "number" },
979
+ sessionId: { type: "string" }
980
+ },
981
+ required: []
982
+ }
983
+ },
984
+ {
985
+ name: TOOL_NAMES.BROWSER.SMART_SCROLL,
986
+ inputSchema: {
987
+ type: "object",
988
+ properties: {
989
+ tabId: { type: "number" },
990
+ sessionId: { type: "string" },
991
+ direction: { type: "string", enum: ["down", "up", "left", "right"] },
992
+ amount: { type: "string" },
993
+ selector: { type: "string" },
994
+ ref: { type: "number" },
995
+ index: { type: "number" },
996
+ coordinate: {
997
+ oneOf: [
998
+ {
999
+ type: "object",
1000
+ properties: { x: { type: "number" }, y: { type: "number" } },
1001
+ required: ["x", "y"]
1002
+ },
1003
+ { type: "array", items: { type: "number" } }
1004
+ ]
1005
+ },
1006
+ smooth: { type: "boolean" },
1007
+ waitForSettle: { type: "boolean" },
1008
+ settleTimeoutMs: { type: "number" },
1009
+ note: { type: "string" }
1010
+ },
1011
+ required: []
1012
+ }
1013
+ },
1014
+ {
1015
+ name: TOOL_NAMES.BROWSER.CDP_EXECUTE,
1016
+ inputSchema: {
1017
+ type: "object",
1018
+ properties: {
1019
+ tabId: { type: "number" },
1020
+ method: { type: "string" },
1021
+ params: { type: "object" },
1022
+ timeoutMs: { type: "number" }
1023
+ },
1024
+ required: ["method"]
1025
+ }
1026
+ },
1027
+ {
1028
+ name: TOOL_NAMES.BROWSER.REQUEST_HUMAN_INTERVENTION,
1029
+ inputSchema: {
1030
+ type: "object",
1031
+ properties: {
1032
+ reason: { type: "string" },
1033
+ timeoutMs: { type: "number" },
1034
+ tabId: { type: "number" }
1035
+ },
1036
+ required: ["reason"]
1037
+ }
1038
+ },
1039
+ {
1040
+ name: TOOL_NAMES.BROWSER.DOCTOR,
1041
+ inputSchema: {
1042
+ type: "object",
1043
+ properties: { verbose: { type: "boolean" } },
1044
+ required: [],
1045
+ additionalProperties: false
1046
+ }
1047
+ },
1048
+ {
1049
+ name: TOOL_NAMES.BROWSER.GREP,
1050
+ inputSchema: {
1051
+ type: "object",
1052
+ properties: {
1053
+ query: { type: "string" },
1054
+ isRegex: { type: "boolean" },
1055
+ searchType: { type: "string", enum: ["interactive_only", "all_dom", "page_text"] },
1056
+ limit: { type: "number" },
1057
+ autoScroll: { type: "boolean" },
1058
+ maxSteps: { type: "number" },
1059
+ stepPx: { type: "number" },
1060
+ tabId: { type: "number" },
1061
+ sessionId: { type: "string" }
1062
+ },
1063
+ required: ["query"]
1064
+ }
1065
+ }
1066
+ ];
1067
+ TOOL_SCHEMAS = schemas.map((tool) => ({
1068
+ ...tool,
1069
+ inputSchema: {
1070
+ ...tool.inputSchema,
1071
+ properties: { ...tool.inputSchema.properties, taskId: TASK_ID }
1072
+ }
1073
+ }));
1074
+ GITHUB_REPO_OWNER = "GoldenLoaf24h";
1075
+ GITHUB_REPO_NAME = "browserpaw";
1076
+ GITHUB_REPO_URL = `https://github.com/${GITHUB_REPO_OWNER}/${GITHUB_REPO_NAME}`;
1077
+ GITHUB_API_LATEST_RELEASE_URL = `https://api.github.com/repos/${GITHUB_REPO_OWNER}/${GITHUB_REPO_NAME}/releases/latest`;
1078
+ CURRENT_VERSION = "5.0.0";
1079
+ DEFAULT_CACHE_TTL_MS = 60 * 60 * 1e3;
1080
+ DEFAULT_MAX_SLIDING_WINDOW_MS = 24 * 60 * 60 * 1e3;
1081
+ MemoryVersionCacheStorage = class {
1082
+ constructor() {
1083
+ this.entry = null;
1084
+ }
1085
+ get() {
1086
+ return this.entry;
1087
+ }
1088
+ set(entry) {
1089
+ this.entry = entry;
1090
+ }
1091
+ };
1092
+ defaultMemoryCacheStorage = new MemoryVersionCacheStorage();
1093
+ dataCommands = {
1094
+ "history search": {
1095
+ usage: "history search [QUERY] [--since T] [--until T] [--limit N]",
1096
+ summary: "Find visited pages by text and time.",
1097
+ keywords: ["browsing history", "browser history", "\u5386\u53F2", "\u6D4F\u89C8\u5386\u53F2", "\u6D4F\u89C8\u8BB0\u5F55", "\u67E5\u5386\u53F2"]
1098
+ },
1099
+ "history visits": {
1100
+ usage: "history visits URL [--since T] [--until T] [--limit N]",
1101
+ summary: "Read individual visits to an exact URL."
1102
+ },
1103
+ "history top": {
1104
+ usage: "history top [--since T] [--until T] [--limit N]",
1105
+ summary: "Rank hosts by visits among up to 200 recently matching URLs."
1106
+ },
1107
+ "history rm": {
1108
+ usage: "history rm [URL...] [--since T] [--until T] [--yes]",
1109
+ summary: "Remove exact URLs or a bounded time range with both dates and --yes."
1110
+ },
1111
+ "bookmark tree": {
1112
+ usage: "bookmark tree [--folder ID_OR_PATH]",
1113
+ summary: "List the bookmark tree or one folder subtree."
1114
+ },
1115
+ "bookmark search": {
1116
+ usage: "bookmark search QUERY [--limit N]",
1117
+ summary: "Find bookmarks and folders by title or URL.",
1118
+ keywords: ["favorites", "\u4E66\u7B7E", "\u6536\u85CF\u5939", "\u67E5\u627E\u4E66\u7B7E"]
1119
+ },
1120
+ "bookmark add": {
1121
+ usage: "bookmark add URL [--title TITLE] [--folder ID_OR_PATH]",
1122
+ summary: "Add a URL to the selected bookmark folder."
1123
+ },
1124
+ "bookmark mkdir": {
1125
+ usage: "bookmark mkdir PATH [--folder ID_OR_PATH]",
1126
+ summary: "Create folders under an existing root or selected folder."
1127
+ },
1128
+ "bookmark mv": {
1129
+ usage: "bookmark mv ID --folder ID_OR_PATH [--index N]",
1130
+ summary: "Move a bookmark or folder to an explicit destination.",
1131
+ keywords: ["organize bookmarks favorites", "\u6574\u7406\u4E66\u7B7E", "\u6574\u7406\u6536\u85CF\u5939", "\u79FB\u52A8\u4E66\u7B7E"]
1132
+ },
1133
+ "bookmark rename": { usage: "bookmark rename ID TITLE", summary: "Rename a bookmark or folder." },
1134
+ "bookmark rm": {
1135
+ usage: "bookmark rm ID... [--recursive]",
1136
+ summary: "Remove selected entries. Nonempty folders require --recursive."
1137
+ },
1138
+ "bookmark dedupe": {
1139
+ usage: "bookmark dedupe [--folder ID_OR_PATH] [--apply]",
1140
+ summary: "Preview exact duplicate URLs within each folder. --apply requires --folder.",
1141
+ keywords: ["find duplicate bookmarks", "deduplicate favorites"]
1142
+ },
1143
+ "bookmark export": {
1144
+ usage: "bookmark export --out FILE [--folder ID_OR_PATH] [--format FORMAT]",
1145
+ summary: "Write a JSON or Chrome-importable HTML backup.",
1146
+ keywords: ["export bookmarks favorites", "\u5BFC\u51FA\u4E66\u7B7E", "\u5907\u4EFD\u4E66\u7B7E", "\u5BFC\u51FA\u6536\u85CF\u5939"]
1147
+ },
1148
+ "downloads list": {
1149
+ usage: "downloads list [--limit N] [--state STATE]",
1150
+ summary: "List recent Chrome downloads, optionally by state.",
1151
+ keywords: ["download history", "download manager"]
1152
+ },
1153
+ "downloads reveal": {
1154
+ usage: "downloads reveal ID",
1155
+ summary: "Show a completed download in the OS file manager."
1156
+ },
1157
+ "downloads rm": {
1158
+ usage: "downloads rm ID [--file]",
1159
+ summary: "Erase one download record. --file also removes the downloaded file."
1160
+ },
1161
+ "storage get": {
1162
+ usage: "storage get [KEY] [--session]",
1163
+ summary: "Read an entry or list keys in the selected page storage.",
1164
+ keywords: ["read localStorage", "read sessionStorage"]
1165
+ },
1166
+ "storage set": {
1167
+ usage: "storage set KEY VALUE [--session]",
1168
+ summary: "Write one string into the selected page storage.",
1169
+ keywords: ["write localStorage", "write sessionStorage"]
1170
+ },
1171
+ "storage rm": {
1172
+ usage: "storage rm KEY [--session]",
1173
+ summary: "Remove one entry from the selected page storage."
1174
+ },
1175
+ "storage clear": {
1176
+ usage: "storage clear [--session]",
1177
+ summary: "Clear the selected page origin and storage area."
1178
+ },
1179
+ "cookies list": {
1180
+ usage: "cookies list [--url URL|--domain DOMAIN] [--values] [--limit N]",
1181
+ summary: "List unpartitioned cookies in the default store. Values require an explicit scope."
1182
+ },
1183
+ "cookies set": {
1184
+ usage: "cookies set URL NAME VALUE [--path PATH] [--secure] [--http-only] [--same-site MODE] [--expires T]",
1185
+ summary: "Set a host-only cookie in the default store."
1186
+ },
1187
+ "cookies rm": {
1188
+ usage: "cookies rm URL NAME",
1189
+ summary: "Remove the unpartitioned cookie selected by Chrome for this URL and name."
1190
+ }
1191
+ };
1192
+ debugCommands = {
1193
+ console: {
1194
+ usage: "console [--level LEVEL] [--grep PATTERN] [--limit N] [--clear] [--no-exceptions]",
1195
+ summary: "Read buffered console output with level and text filters; --level accepts comma-separated levels.",
1196
+ keywords: ["browser console logs", "JavaScript errors", "\u63A7\u5236\u53F0", "\u63A7\u5236\u53F0\u65E5\u5FD7"]
1197
+ },
1198
+ "network start": {
1199
+ usage: "network start [--filter PATTERN] [--bodies] [--static] [--max-time MS] [--idle MS]",
1200
+ summary: "Start a page recording. --filter matches captured request URLs. --bodies captures textual responses.",
1201
+ keywords: ["network capture traffic", "\u5F00\u59CB\u6293\u5305", "\u7F51\u7EDC\u6293\u5305", "\u6293\u5305"]
1202
+ },
1203
+ "network stop": {
1204
+ usage: "network stop [--bodies]",
1205
+ summary: "Stop the selected page recording and return captured events."
1206
+ },
1207
+ "network show": {
1208
+ usage: "network show ID [--out FILE]",
1209
+ summary: "Inspect one request by its recorded ID. --out writes its textual body.",
1210
+ keywords: ["export response body", "save response body", "\u54CD\u5E94\u4F53", "\u54CD\u5E94\u6B63\u6587", "\u5BFC\u51FA\u54CD\u5E94\u6B63\u6587"]
1211
+ },
1212
+ "network list": {
1213
+ usage: "network list [--filter PATTERN] [--method METHOD] [--status CODE] [--type TYPE] [--limit N]",
1214
+ summary: "List captured requests with URL, method, status, type, and result-limit filters.",
1215
+ keywords: ["filter network requests", "HTTP status codes"]
1216
+ },
1217
+ "network clear": {
1218
+ usage: "network clear",
1219
+ summary: "Clear the selected page network capture while leaving recording active."
1220
+ },
1221
+ "perf metrics": {
1222
+ usage: "perf metrics",
1223
+ summary: "Read Chrome performance counters for the selected page."
1224
+ },
1225
+ "perf trace": {
1226
+ usage: "perf trace start|stop|analyze [NAME] [--reload] [--auto-stop] [--duration MS] [--out FILE]",
1227
+ summary: "Record, stop, or summarize a Chrome performance trace; trace files stay in the Native temp area.",
1228
+ keywords: ["performance profile", "record timeline", "profiling trace", "\u6027\u80FD\u5206\u6790", "\u6027\u80FD\u8FFD\u8E2A"]
1229
+ },
1230
+ emulate: {
1231
+ usage: "emulate [--viewport WIDTHxHEIGHT] [--dpr NUMBER] [--mobile] [--user-agent TEXT] [--color-scheme SCHEME] [--timezone ID] [--locale LOCALE] [--cpu-rate NUMBER] [--offline] [--latency MS] [--download-kbps N] [--upload-kbps N]",
1232
+ summary: "Apply device, media, locale, CPU, or network emulation to the selected page.",
1233
+ keywords: ["network throttling", "mobile emulation", "device simulation"]
1234
+ },
1235
+ "emulate reset": {
1236
+ usage: "emulate reset",
1237
+ summary: "Clear viewport, media, locale, CPU, and network emulation on the selected page."
1238
+ },
1239
+ pdf: {
1240
+ usage: "pdf [--out FILE] [--landscape] [--no-background] [--paper PAPER] [--margin INCH] [--scale N] [--header] [--footer]",
1241
+ summary: "Print the selected page to PDF and save its bytes outside Agent context.",
1242
+ keywords: ["save page as PDF", "print to PDF"]
1243
+ }
1244
+ };
1245
+ pageCommands = {
1246
+ tabs: {
1247
+ usage: "tabs [QUERY...] [--content] [--limit N]",
1248
+ summary: "List windows and tabs or search titles and URLs. --content also searches loaded pages.",
1249
+ keywords: ["open tabs", "search across tabs"]
1250
+ },
1251
+ "window list": {
1252
+ usage: "window list",
1253
+ summary: "List browser windows with explicit window IDs."
1254
+ },
1255
+ "window open": {
1256
+ usage: "window open URL [--width N] [--height N] [--background]",
1257
+ summary: "Open a URL in a new browser window."
1258
+ },
1259
+ "window focus": {
1260
+ usage: "window focus ID",
1261
+ summary: "Focus one explicitly identified browser window."
1262
+ },
1263
+ "window close": {
1264
+ usage: "window close ID",
1265
+ summary: "Close one explicitly identified browser window."
1266
+ },
1267
+ "group list": {
1268
+ usage: "group list [--window ID] [--title TITLE]",
1269
+ summary: "List tab groups and their explicit tab IDs."
1270
+ },
1271
+ "group create": {
1272
+ usage: "group create TAB... [--group ID] [--window ID] [--title TITLE] [--color COLOR] [--collapsed]",
1273
+ summary: "Create a tab group from explicitly named tabs, or add them to --group ID."
1274
+ },
1275
+ "group update": {
1276
+ usage: "group update ID [--title TITLE] [--color COLOR] [--collapsed]",
1277
+ summary: "Update one explicitly identified tab group."
1278
+ },
1279
+ "group ungroup": {
1280
+ usage: "group ungroup TAB...",
1281
+ summary: "Remove explicitly named tabs from their groups without closing them."
1282
+ },
1283
+ "group close": {
1284
+ usage: "group close ID",
1285
+ summary: "Close agent-owned tabs in one explicitly identified tab group."
1286
+ },
1287
+ "tab move": {
1288
+ usage: "tab move TAB INDEX [--window ID]",
1289
+ summary: "Move one explicitly identified tab to a zero-based index."
1290
+ },
1291
+ text: {
1292
+ usage: "text [TARGET] [--links|--media|--content] [--max-chars N] [--limit N]",
1293
+ summary: "Read page text, extract the main content, list links, or inspect one image or media element.",
1294
+ keywords: ["page text extraction", "extract hyperlinks", "inspect media"]
1295
+ },
1296
+ select: {
1297
+ usage: "select TARGET [VALUE...]",
1298
+ summary: "List available choices or select by value."
1299
+ },
1300
+ scroll: {
1301
+ usage: "scroll [TARGET] [--up|--down|--top|--bottom] [--by PX] [--until TEXT|--selector CSS] [--max N] [--step PX] [--timeout MS] [--regex]",
1302
+ summary: "Scroll the page or a scroll container, optionally until text or a selector is found."
1303
+ },
1304
+ dismiss: {
1305
+ usage: "dismiss [--max N]",
1306
+ summary: "Dismiss visible overlays on the selected page."
1307
+ }
1308
+ };
1309
+ COMMANDS = {
1310
+ setup: {
1311
+ usage: "setup [--browser BROWSER] [--skill-scope SCOPE] [--skill-dir DIR] [--no-skill]",
1312
+ summary: "Install or refresh the host and base Skill. Prepare the bundled extension on first setup only."
1313
+ },
1314
+ status: {
1315
+ usage: "status",
1316
+ summary: "Show local host and extension connection and build identity."
1317
+ },
1318
+ doctor: {
1319
+ usage: "doctor [--fix]",
1320
+ summary: "Diagnose installation and connection. Use --fix to repair registration."
1321
+ },
1322
+ uninstall: {
1323
+ usage: "uninstall [--purge]",
1324
+ summary: "Remove the managed installation. Purge also removes its user data."
1325
+ },
1326
+ help: {
1327
+ usage: "help [COMMAND|TOPIC]",
1328
+ summary: "Show usage and examples without opening Chrome."
1329
+ },
1330
+ search: {
1331
+ usage: "search KEYWORD... [--limit N]",
1332
+ summary: "Find CLI commands offline by name, purpose, option, or English and Chinese keywords.",
1333
+ keywords: ["tool search", "command discovery", "\u67E5\u627E\u547D\u4EE4", "\u641C\u7D22\u5DE5\u5177"]
1334
+ },
1335
+ open: {
1336
+ usage: "open URL [--foreground]",
1337
+ summary: "Open a new tab. --foreground applies only to non-task opens."
1338
+ },
1339
+ nav: { usage: "nav URL|back|forward|reload", summary: "Navigate the selected page." },
1340
+ "tab focus": { usage: "tab focus ID", summary: "Bring the selected tab to the foreground." },
1341
+ "tab close": { usage: "tab close ID...", summary: "Close explicitly named tabs." },
1342
+ observe: {
1343
+ usage: "observe [--scope CSS] [--delta] [--max N]",
1344
+ summary: "Read page structure, frame IDs, and actionable refs.",
1345
+ keywords: ["DOM snapshot", "inspect elements", "\u7F51\u9875\u7ED3\u6784", "\u5143\u7D20\u5B9A\u4F4D"]
1346
+ },
1347
+ find: {
1348
+ usage: "find PATTERN [--regex] [--scroll]",
1349
+ summary: "Find matching elements in the page."
1350
+ },
1351
+ screenshot: {
1352
+ usage: "screenshot [TARGET] [--full] [--out FILE]",
1353
+ summary: "Save an image locally and return its capture ID.",
1354
+ keywords: ["screen capture", "full page screenshot", "\u622A\u56FE", "\u9875\u9762\u622A\u56FE", "\u622A\u5C4F"]
1355
+ },
1356
+ wait: {
1357
+ usage: "wait [TARGET] [--text TEXT|--url URL] [--gone] [--timeout MS]",
1358
+ summary: "Wait for a target, page text, or URL condition."
1359
+ },
1360
+ click: {
1361
+ usage: "click TARGET [--double|--right] [--capture ID]",
1362
+ summary: "Click the target from the current observation or capture."
1363
+ },
1364
+ fill: {
1365
+ usage: "fill TARGET TEXT [--append] [--input FILE|-]",
1366
+ summary: "Replace or append text. Use -- before option-like text.",
1367
+ keywords: ["form input", "type into a field"]
1368
+ },
1369
+ hover: { usage: "hover TARGET [--capture ID]", summary: "Move the pointer to a target." },
1370
+ press: {
1371
+ usage: "press KEYS [TARGET]",
1372
+ summary: "Send a key sequence, optionally to a strict target.",
1373
+ keywords: ["keyboard shortcut", "hotkey"]
1374
+ },
1375
+ drag: {
1376
+ usage: "drag FROM TO [--capture ID]",
1377
+ summary: "Drag between two observed refs or capture coordinates."
1378
+ },
1379
+ upload: {
1380
+ usage: "upload TARGET FILE...",
1381
+ summary: "Choose local files for the specified input."
1382
+ },
1383
+ dialog: {
1384
+ usage: "dialog accept|dismiss [--id ID] [--text TEXT]",
1385
+ summary: "Handle a dialog from the selected page."
1386
+ },
1387
+ download: {
1388
+ usage: "download [TARGET] [--url URL] [--out DIR] [--timeout MS]",
1389
+ summary: "Trigger and wait for a verified download from this page."
1390
+ },
1391
+ eval: {
1392
+ usage: "eval [CODE] [--file FILE|-] [--timeout MS]",
1393
+ summary: "Evaluate explicit JavaScript in the selected page.",
1394
+ keywords: ["execute JavaScript", "run page script"]
1395
+ },
1396
+ fetch: {
1397
+ usage: "fetch URL [--method METHOD] [--header KEY:VALUE]... [--body BODY]",
1398
+ summary: "Send an explicit request from the selected page."
1399
+ },
1400
+ cdp: {
1401
+ usage: "cdp METHOD [JSON]",
1402
+ summary: "Call a supported DevTools command in the selected tab.",
1403
+ keywords: ["Chrome DevTools Protocol"]
1404
+ },
1405
+ "ask-human": {
1406
+ usage: "ask-human MESSAGE [--timeout MS]",
1407
+ summary: "Pause at a page and ask the user to intervene."
1408
+ },
1409
+ "task start": {
1410
+ usage: "task start NAME [--goal TEXT]",
1411
+ summary: "Start a durable task and return its ID."
1412
+ },
1413
+ "task list": { usage: "task list", summary: "List local tasks." },
1414
+ "task status": {
1415
+ usage: "task status [ID]",
1416
+ summary: "Inspect task pages and known and uncertain outcomes."
1417
+ },
1418
+ "task resume": {
1419
+ usage: "task resume --task ID [--adopt]",
1420
+ summary: "Revalidate task pages. After inspecting the page, use --adopt to accept a recorded pending document.",
1421
+ keywords: ["recover task", "pending navigation", "document identity", "\u6062\u590D\u4EFB\u52A1", "\u6587\u6863\u8EAB\u4EFD"]
1422
+ },
1423
+ "task finish": {
1424
+ usage: "task finish [--keep ID]... [--keep-unknown]",
1425
+ summary: "Close verified owned pages and preserve borrowed pages."
1426
+ },
1427
+ "task cancel": {
1428
+ usage: "task cancel",
1429
+ summary: "Stop the task without rolling back dispatched work."
1430
+ },
1431
+ "task borrow": {
1432
+ usage: "task borrow ID",
1433
+ summary: "Associate an existing user tab with the task."
1434
+ },
1435
+ "task release": { usage: "task release ID", summary: "Hand an owned tab back to the user." },
1436
+ batch: {
1437
+ usage: "batch FILE|-",
1438
+ summary: "Run JSON argument arrays in order, stopping at the first failure."
1439
+ },
1440
+ "recipe list": {
1441
+ usage: "recipe list [--url URL] [--query TEXT] [--all]",
1442
+ summary: "List learned skills and saved workflows under ~/.browserpaw."
1443
+ },
1444
+ "recipe find": {
1445
+ usage: "recipe find [QUERY...] [--url URL] [--all]",
1446
+ summary: "Match learned skills and workflows by intent or URL."
1447
+ },
1448
+ "recipe show": {
1449
+ usage: "recipe show ID",
1450
+ summary: "Inspect a learned skill or saved workflow and its inputs."
1451
+ },
1452
+ "recipe run": {
1453
+ usage: "recipe run ID [KEY=VALUE...]",
1454
+ summary: "Run a learned skill or saved workflow with typed inputs."
1455
+ },
1456
+ "recipe save": {
1457
+ usage: "recipe save FILE|-",
1458
+ summary: "Save a candidate learned workflow or propose a verified skill."
1459
+ },
1460
+ "recipe patch": {
1461
+ usage: "recipe patch ID --step INDEX -- ARGS...",
1462
+ summary: "Replace one candidate recipe step after static validation."
1463
+ },
1464
+ "recipe validate": {
1465
+ usage: "recipe validate ID [KEY=VALUE...]",
1466
+ summary: "Validate a candidate and activate only a verified read-only workflow."
1467
+ },
1468
+ "recipe rm": {
1469
+ usage: "recipe rm ID",
1470
+ summary: "Remove a saved workflow or disable a learned skill."
1471
+ },
1472
+ ...pageCommands,
1473
+ ...dataCommands,
1474
+ ...debugCommands
1475
+ };
1476
+ globalOptions = "--task ID --tab ID --frame ID --json";
1477
+ repeated = /* @__PURE__ */ new Set(["header", "keep"]);
1478
+ isCommand = (key) => Object.prototype.hasOwnProperty.call(COMMANDS, key);
1479
+ TARGET_HELP = "Targets: 12 (observed ref), css:SELECTOR, text:TEXT, role:ROLE[:NAME], label:LABEL, or @X,Y --capture ID. Use --frame ID to select a frame. After navigation or a stale ref, observe again.";
1480
+ examples = {
1481
+ search: [
1482
+ "search network response body",
1483
+ "search network throttling",
1484
+ "search \u5BFC\u51FA\u4E66\u7B7E --limit 3 --json",
1485
+ "search screenshot -- --full"
1486
+ ],
1487
+ setup: [
1488
+ "setup",
1489
+ "setup --skill-scope project",
1490
+ "setup --browser chromium --skill-dir ./custom-skills"
1491
+ ],
1492
+ open: ["open https://example.com --task TASK_ID", "open https://example.com --foreground"],
1493
+ observe: ["observe --task TASK_ID --json", "observe --scope css:main --tab 12"],
1494
+ click: ["click 7 --task TASK_ID --frame 0", "click @120,240 --capture CAPTURE_ID --tab 12"],
1495
+ fill: ["fill label:Email agent@example.com --tab 12", "fill 8 --task TASK_ID --input draft.txt"],
1496
+ select: ["select 19 --tab 12", "select 19 blue red --tab 12"],
1497
+ screenshot: ["screenshot --task TASK_ID --out page.png", "screenshot --tab 12 --full"],
1498
+ batch: ["batch steps.json --task TASK_ID", "batch - --tab 12"],
1499
+ "task resume": ["task resume --task TASK_ID --adopt"],
1500
+ "task finish": ["task finish --task TASK_ID", "task finish --task TASK_ID --keep 12"],
1501
+ "recipe find": ["recipe find twitter search", "recipe find --url https://x.com/search?q=ai"],
1502
+ "recipe show": ["recipe show x-search-thread"],
1503
+ "recipe patch": ["recipe patch x-search-thread --step 1 -- wait css:main"],
1504
+ "recipe run": [
1505
+ "recipe run read-title selector=h1 --tab 12",
1506
+ "recipe run x-search-thread query=typescript limit=5"
1507
+ ],
1508
+ "recipe validate": ["recipe validate x-search-thread", "recipe validate x-hot query=ai"],
1509
+ "history search": ["history search example.com --since 7d --limit 20"],
1510
+ "history visits": ["history visits https://example.com/ --since 24h"],
1511
+ "history top": ["history top --since 7d --limit 10"],
1512
+ "history rm": ["history rm https://example.com/"],
1513
+ "bookmark tree": ["bookmark tree --folder 18"],
1514
+ "bookmark search": ["bookmark search Research"],
1515
+ "bookmark add": ["bookmark add https://example.com/ --title Example --folder 18"],
1516
+ "bookmark mkdir": ["bookmark mkdir Research --folder 18"],
1517
+ "bookmark mv": ["bookmark mv 27 --folder 18 --index 0"],
1518
+ "bookmark rename": ["bookmark rename 27 Research"],
1519
+ "bookmark rm": ["bookmark rm 27"],
1520
+ "bookmark dedupe": ["bookmark dedupe --folder 18"],
1521
+ "bookmark export": ["bookmark export --folder 18 --format html --out backup.html"],
1522
+ "downloads list": ["downloads list --state complete --limit 10"],
1523
+ "downloads reveal": ["downloads reveal 9"],
1524
+ "downloads rm": ["downloads rm 9"],
1525
+ "storage get": ["storage get theme --tab 12"],
1526
+ "storage set": ["storage set theme dark --tab 12"],
1527
+ "storage rm": ["storage rm theme --tab 12"],
1528
+ "storage clear": ["storage clear --session --tab 12"],
1529
+ "cookies list": ["cookies list --domain example.com"],
1530
+ "cookies set": ["cookies set https://example.com/ theme dark --secure"],
1531
+ "cookies rm": ["cookies rm https://example.com/ theme"],
1532
+ "network start": ["network start --tab 12 --bodies --filter /api/"],
1533
+ "network list": ["network list --tab 12 --status 200"],
1534
+ "network show": ["network show REQUEST_ID --tab 12"],
1535
+ "network stop": ["network stop --tab 12"],
1536
+ "network clear": ["network clear --tab 12"],
1537
+ console: ["console --tab 12 --level error,warning --grep fixture"],
1538
+ "perf metrics": ["perf metrics --tab 12"],
1539
+ "perf trace": ["perf trace start --tab 12", "perf trace stop --tab 12"],
1540
+ emulate: ["emulate --viewport 390x844 --mobile --tab 12"],
1541
+ "emulate reset": ["emulate reset --tab 12"],
1542
+ pdf: ["pdf --tab 12 --out page.pdf"],
1543
+ tabs: ["tabs", "tabs example.com --limit 10"],
1544
+ "tab move": ["tab move 12 0 --window 5"],
1545
+ "window list": ["window list"],
1546
+ "window open": ["window open https://example.com/ --background"],
1547
+ "window focus": ["window focus 5"],
1548
+ "window close": ["window close 5"],
1549
+ "group list": ["group list --window 5"],
1550
+ "group create": ["group create 12 13 --title Research"],
1551
+ "group update": ["group update 8 --color blue"],
1552
+ "group ungroup": ["group ungroup 12 13"],
1553
+ "group close": ["group close 8"],
1554
+ text: ["text --links --tab 12", "text css:article --tab 12"],
1555
+ scroll: ["scroll --until Results --max 10 --tab 12"],
1556
+ dismiss: ["dismiss --tab 12"]
1557
+ };
1558
+ commandTopics = {
1559
+ install: ["setup", "status", "doctor", "uninstall"],
1560
+ page: ["tabs", "tab", "window", "group", "open", "nav"],
1561
+ read: ["observe", "text", "find", "screenshot", "wait"],
1562
+ act: [
1563
+ "click",
1564
+ "fill",
1565
+ "select",
1566
+ "hover",
1567
+ "press",
1568
+ "scroll",
1569
+ "drag",
1570
+ "upload",
1571
+ "dialog",
1572
+ "dismiss",
1573
+ "ask-human",
1574
+ "batch"
1575
+ ],
1576
+ data: ["history", "bookmark", "download", "downloads", "storage", "cookies"],
1577
+ debug: ["console", "network", "perf", "emulate", "pdf", "eval", "fetch", "cdp"],
1578
+ task: ["task"],
1579
+ recipe: ["recipe"]
1580
+ };
1581
+ exitHelp = "Exit codes: 0 success, 1 failure, 2 usage error, 3 disconnected, 4 outcome unknown. Observe before acting again after exit 4.";
1582
+ }
1583
+ });
1584
+
1585
+ // src/command-utils.ts
1586
+ function assertBatchStep({ name, options }) {
1587
+ if (STANDALONE_COMMANDS.has(name) || isProfileCommand(name) || name.startsWith("recipe ") || options.file || options.input || name !== "download" && options.out !== void 0)
1588
+ throw new CommandError(`Command ${name} is unavailable inside a batch.`);
1589
+ }
1590
+ var CommandError, STANDALONE_COMMANDS;
1591
+ var init_command_utils = __esm({
1592
+ "src/command-utils.ts"() {
1593
+ "use strict";
1594
+ init_dist();
1595
+ CommandError = class extends Error {
1596
+ constructor(message, code = "invalid_arguments") {
1597
+ super(message);
1598
+ this.code = code;
1599
+ }
1600
+ };
1601
+ STANDALONE_COMMANDS = /* @__PURE__ */ new Set([
1602
+ "setup",
1603
+ "status",
1604
+ "uninstall",
1605
+ "help",
1606
+ "search",
1607
+ "batch",
1608
+ "task resume"
1609
+ ]);
1610
+ }
1611
+ });
1612
+
1613
+ // package.json
1614
+ var require_package = __commonJS({
1615
+ "package.json"(exports2, module2) {
1616
+ module2.exports = {
1617
+ name: "browserpaw",
1618
+ version: "5.0.0",
1619
+ description: "Command-line browser automation through the BrowserPaw Chrome extension",
1620
+ author: "hangye",
1621
+ repository: {
1622
+ type: "git",
1623
+ url: "https://github.com/GoldenLoaf24h/browserpaw.git",
1624
+ directory: "app/native-server"
1625
+ },
1626
+ homepage: "https://github.com/GoldenLoaf24h/browserpaw",
1627
+ bin: {
1628
+ browserpaw: "./dist/v5/cli.cjs"
1629
+ },
1630
+ scripts: {
1631
+ clean: 'rimraf "dist/v5"',
1632
+ dev: 'nodemon --watch src --ext ts,js,json --ignore dist/v5/ --exec "npm run build"',
1633
+ build: "ts-node src/scripts/build.ts",
1634
+ test: "jest --runInBand",
1635
+ "test:watch": "jest --watch",
1636
+ lint: "eslint src --max-warnings=0",
1637
+ "lint:fix": "eslint src --fix",
1638
+ format: "prettier --write 'src/**/*.{js,ts,json}'",
1639
+ prepack: "node scripts/pack-assets.cjs"
1640
+ },
1641
+ files: [
1642
+ "LICENSE",
1643
+ "dist/v5/cli.cjs",
1644
+ "dist/v5/host.cjs",
1645
+ "dist/v5/cli-files.cjs",
1646
+ "dist/v5/run_host.bat",
1647
+ "dist/v5/run_host.sh",
1648
+ "dist/v5/extension",
1649
+ "dist/v5/recipes",
1650
+ "dist/v5/skill"
1651
+ ],
1652
+ engines: {
1653
+ node: ">=22.6.0"
1654
+ },
1655
+ keywords: [
1656
+ "cli",
1657
+ "chrome",
1658
+ "browser"
1659
+ ],
1660
+ license: "AGPL-3.0-or-later",
1661
+ devDependencies: {
1662
+ "chrome-mcp-shared": "workspace:*",
1663
+ "@types/node-fetch": "2",
1664
+ ajv: "^8.17.1",
1665
+ "ajv-formats": "^3.0.1",
1666
+ "node-fetch": "2",
1667
+ tsup: "^8.5.1",
1668
+ "@jest/globals": "^29.7.0",
1669
+ "@types/chrome": "^0.0.318",
1670
+ "@types/jest": "^29.5.14",
1671
+ "@types/node": "^22.15.3",
1672
+ "@types/supertest": "^6.0.3",
1673
+ "@typescript-eslint/parser": "^8.31.1",
1674
+ "cross-env": "^7.0.3",
1675
+ husky: "^9.1.7",
1676
+ jest: "^29.7.0",
1677
+ "lint-staged": "^15.5.1",
1678
+ nodemon: "^3.1.10",
1679
+ rimraf: "^6.0.1",
1680
+ supertest: "^7.1.0",
1681
+ "ts-jest": "^29.3.2",
1682
+ "ts-node": "^10.9.2"
1683
+ }
1684
+ };
1685
+ }
1686
+ });
1687
+
1688
+ // src/skill-install.ts
1689
+ function assertNoLinks(target) {
1690
+ let current = import_node_path.default.resolve(target);
1691
+ while (true) {
1692
+ const stat = import_node_fs.default.lstatSync(current, { throwIfNoEntry: false });
1693
+ const isMacSystemRootLink = stat?.isSymbolicLink() && (current === "/var" || current === "/tmp" || current === "/etc") && import_node_path.default.resolve(import_node_path.default.dirname(current), import_node_fs.default.readlinkSync(current)) === `/private${current}`;
1694
+ if (stat?.isSymbolicLink() && !isMacSystemRootLink) {
1695
+ throw new Error(`Refusing symlink or junction in target path: ${current}`);
1696
+ }
1697
+ const parent = import_node_path.default.dirname(current);
1698
+ if (parent === current) return;
1699
+ current = parent;
1700
+ }
1701
+ }
1702
+ function assertPlainTree(root) {
1703
+ const visit = (directory) => {
1704
+ for (const entry of import_node_fs.default.readdirSync(directory, { withFileTypes: true })) {
1705
+ const full = import_node_path.default.join(directory, entry.name);
1706
+ const stat = import_node_fs.default.lstatSync(full);
1707
+ if (stat.isSymbolicLink()) throw new Error(`Bundled skill contains a symlink: ${full}`);
1708
+ if (stat.isDirectory()) visit(full);
1709
+ else if (!stat.isFile()) throw new Error(`Unsupported bundled skill entry: ${full}`);
1710
+ }
1711
+ };
1712
+ visit(root);
1713
+ }
1714
+ function assertSkillSource(root) {
1715
+ const skillFile = import_node_path.default.join(root, "SKILL.md");
1716
+ if (!import_node_fs.default.existsSync(skillFile) || !import_node_fs.default.statSync(skillFile).isFile()) {
1717
+ throw new Error(`Packaged BrowserPaw skill is missing SKILL.md: ${root}`);
1718
+ }
1719
+ const frontmatter = import_node_fs.default.readFileSync(skillFile, "utf8").match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1];
1720
+ if (!frontmatter || !/^name:\s*browserpaw\s*$/m.test(frontmatter)) {
1721
+ throw new Error("Packaged skill must declare name: browserpaw");
1722
+ }
1723
+ assertPlainTree(root);
1724
+ }
1725
+ function readMarker(directory) {
1726
+ const marker = import_node_path.default.join(directory, markerName);
1727
+ if (!import_node_fs.default.existsSync(marker)) return null;
1728
+ try {
1729
+ assertNoLinks(marker);
1730
+ return JSON.parse(import_node_fs.default.readFileSync(marker, "utf8"));
1731
+ } catch {
1732
+ return null;
1733
+ }
1734
+ }
1735
+ function extractFrontmatterDescription(markdown) {
1736
+ const frontmatter = markdown.match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1];
1737
+ if (!frontmatter) return "";
1738
+ const raw = frontmatter.match(/^description:\s*(.+)\s*$/m)?.[1]?.trim() ?? "";
1739
+ if (raw.startsWith('"') && raw.endsWith('"') || raw.startsWith("'") && raw.endsWith("'")) {
1740
+ return raw.slice(1, -1).replace(/\\"/g, '"').trim();
1741
+ }
1742
+ return raw;
1743
+ }
1744
+ function cleanInlineText(value) {
1745
+ return value.replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim();
1746
+ }
1747
+ function escapeMarkdownCell(value) {
1748
+ return cleanInlineText(value).replace(/\|/g, "\\|");
1749
+ }
1750
+ function formatFrontmatterDescription(base, entries) {
1751
+ const normalizedBase = cleanInlineText(base).split(learnedDescriptionPrefix)[0].trim();
1752
+ if (!entries.length) return normalizedBase;
1753
+ const maxTotalChars = 480;
1754
+ const parts = [];
1755
+ let length = normalizedBase.length + learnedDescriptionPrefix.length;
1756
+ for (const entry of entries.slice(0, 8)) {
1757
+ const sites = entry.domains.slice(0, 2).join("/");
1758
+ const token = sites ? `${entry.id} (${sites})` : entry.id;
1759
+ const nextLength = length + (parts.length ? 2 : 0) + token.length;
1760
+ if (parts.length > 0 && nextLength > maxTotalChars) break;
1761
+ parts.push(token);
1762
+ length = nextLength;
1763
+ }
1764
+ if (!parts.length) return normalizedBase;
1765
+ const suffix = entries.length > parts.length ? `, and ${entries.length - parts.length} more` : "";
1766
+ return `${normalizedBase}${learnedDescriptionPrefix}${parts.join(", ")}${suffix}.`;
1767
+ }
1768
+ function renderLearnedSection(entries) {
1769
+ if (!entries.length) return "";
1770
+ const visible = entries.slice(0, 20);
1771
+ const rows = visible.map((entry) => {
1772
+ const sites = entry.domains.length ? entry.domains.slice(0, 3).map((d) => `\`${d}\``).join(", ") : "-";
1773
+ const summary = escapeMarkdownCell(entry.description || entry.name).slice(0, 110);
1774
+ const cmd = escapeMarkdownCell(entry.command);
1775
+ return `| \`${entry.id}\` | ${entry.kind} | ${sites} | ${summary} | \`${cmd}\` |`;
1776
+ });
1777
+ const overflow = entries.length > visible.length ? `
1778
+
1779
+ Run \`browserpaw recipe find <query>\` to search all ${entries.length} learned workflows in \`~/.browserpaw\`.` : "";
1780
+ return [
1781
+ learnedStartMarker,
1782
+ "## Learned Workflows (`~/.browserpaw`)",
1783
+ "",
1784
+ "Auto-synced from `~/.browserpaw`. Match and call these directly with `browserpaw recipe run` before manually browsing:",
1785
+ "",
1786
+ "| ID | Type | Sites | Summary | CLI Command |",
1787
+ "| --- | --- | --- | --- | --- |",
1788
+ ...rows,
1789
+ ...overflow ? [overflow] : [],
1790
+ learnedEndMarker
1791
+ ].join("\n");
1792
+ }
1793
+ function packageVersion() {
1794
+ return String(require_package().version);
1795
+ }
1796
+ function defaultSkillTargetRoot() {
1797
+ return import_node_path.default.join(import_node_os.default.homedir(), ".agents", "skills");
1798
+ }
1799
+ function projectSkillTargetRoot(cwd = process.cwd()) {
1800
+ return import_node_path.default.resolve(cwd, ".agents", "skills");
1801
+ }
1802
+ function resolveSkillTargetRoot(options = {}) {
1803
+ if (options.scope && options.targetRoot) {
1804
+ throw new Error("Use either --skill-scope or --skill-dir, not both.");
1805
+ }
1806
+ if (options.targetRoot) {
1807
+ return { targetRoot: import_node_path.default.resolve(options.targetRoot), scope: "custom" };
1808
+ }
1809
+ const normalized = (options.scope ?? "user").toLowerCase();
1810
+ if (normalized === "user" || normalized === "global") {
1811
+ return { targetRoot: defaultSkillTargetRoot(), scope: "user" };
1812
+ }
1813
+ if (normalized === "project") {
1814
+ return { targetRoot: projectSkillTargetRoot(options.cwd), scope: "project" };
1815
+ }
1816
+ throw new Error("Use --skill-scope user or project.");
1817
+ }
1818
+ function installSkill(options = {}) {
1819
+ const sourceDir = import_node_path.default.resolve(options.sourceDir ?? import_node_path.default.join(__dirname, "skill", skillName));
1820
+ const version = options.version ?? packageVersion();
1821
+ const resolved = resolveSkillTargetRoot({
1822
+ scope: options.scope,
1823
+ targetRoot: options.targetRoot,
1824
+ cwd: options.cwd
1825
+ });
1826
+ const targetRoot = resolved.targetRoot;
1827
+ const destination = import_node_path.default.join(targetRoot, skillName);
1828
+ let scope = resolved.scope;
1829
+ assertNoLinks(targetRoot);
1830
+ assertNoLinks(destination);
1831
+ assertSkillSource(sourceDir);
1832
+ const baseDescription = extractFrontmatterDescription(
1833
+ import_node_fs.default.readFileSync(import_node_path.default.join(sourceDir, "SKILL.md"), "utf8")
1834
+ );
1835
+ if (import_node_fs.default.existsSync(destination)) {
1836
+ const marker = readMarker(destination);
1837
+ if (!marker || marker.name !== skillName) {
1838
+ throw new Error(
1839
+ `Refusing to replace ${destination}: it has no BrowserPaw installation marker`
1840
+ );
1841
+ }
1842
+ if (!options.force) {
1843
+ throw new Error(
1844
+ `BrowserPaw skill already exists at ${destination}; use --force to replace it`
1845
+ );
1846
+ }
1847
+ if (options.targetRoot && (marker.scope === "user" || marker.scope === "project")) {
1848
+ scope = marker.scope;
1849
+ }
1850
+ }
1851
+ import_node_fs.default.mkdirSync(targetRoot, { recursive: true });
1852
+ assertNoLinks(targetRoot);
1853
+ const staging = import_node_path.default.join(targetRoot, `.${skillName}-staging-${(0, import_node_crypto.randomUUID)()}`);
1854
+ const backup = import_node_path.default.join(targetRoot, `.${skillName}-backup-${(0, import_node_crypto.randomUUID)()}`);
1855
+ try {
1856
+ import_node_fs.default.mkdirSync(staging, { recursive: false });
1857
+ import_node_fs.default.cpSync(sourceDir, staging, { recursive: true, dereference: false });
1858
+ } catch (error) {
1859
+ import_node_fs.default.rmSync(staging, { recursive: true, force: true });
1860
+ throw error;
1861
+ }
1862
+ try {
1863
+ import_node_fs.default.writeFileSync(
1864
+ import_node_path.default.join(staging, markerName),
1865
+ `${JSON.stringify(
1866
+ {
1867
+ name: skillName,
1868
+ version,
1869
+ scope,
1870
+ source: "bundled:skills/browserpaw",
1871
+ baseDescription,
1872
+ installedAt: (/* @__PURE__ */ new Date()).toISOString()
1873
+ },
1874
+ null,
1875
+ 2
1876
+ )}
1877
+ `
1878
+ );
1879
+ } catch (error) {
1880
+ import_node_fs.default.rmSync(staging, { recursive: true, force: true });
1881
+ throw error;
1882
+ }
1883
+ const existed = import_node_fs.default.existsSync(destination);
1884
+ if (existed) {
1885
+ try {
1886
+ import_node_fs.default.renameSync(destination, backup);
1887
+ } catch (error) {
1888
+ import_node_fs.default.rmSync(staging, { recursive: true, force: true });
1889
+ throw error;
1890
+ }
1891
+ }
1892
+ try {
1893
+ import_node_fs.default.renameSync(staging, destination);
1894
+ } catch (error) {
1895
+ import_node_fs.default.rmSync(staging, { recursive: true, force: true });
1896
+ if (existed && import_node_fs.default.existsSync(backup)) {
1897
+ try {
1898
+ import_node_fs.default.renameSync(backup, destination);
1899
+ } catch {
1900
+ }
1901
+ }
1902
+ throw error;
1903
+ }
1904
+ try {
1905
+ import_node_fs.default.rmSync(backup, { recursive: true, force: true });
1906
+ } catch {
1907
+ }
1908
+ return { installedPath: destination, version, scope };
1909
+ }
1910
+ function upgradeInstalledSkill(installedPath, options) {
1911
+ if (import_node_path.default.basename(installedPath) !== skillName || !import_node_fs.default.existsSync(installedPath)) return;
1912
+ assertNoLinks(installedPath);
1913
+ const marker = readMarker(installedPath);
1914
+ const version = options.version ?? packageVersion();
1915
+ if (marker?.name !== skillName || marker.version && !isNewerVersion(version, marker.version))
1916
+ return;
1917
+ return installSkill({
1918
+ ...options,
1919
+ version,
1920
+ targetRoot: import_node_path.default.dirname(installedPath),
1921
+ force: true
1922
+ });
1923
+ }
1924
+ function syncInstalledSkillRouting(installedSkillDir, entries) {
1925
+ const targetDir = import_node_path.default.resolve(installedSkillDir);
1926
+ if (!import_node_fs.default.existsSync(targetDir)) return false;
1927
+ assertNoLinks(targetDir);
1928
+ const marker = readMarker(targetDir);
1929
+ if (!marker || marker.name !== skillName) return false;
1930
+ const skillFile = import_node_path.default.join(targetDir, "SKILL.md");
1931
+ if (!import_node_fs.default.existsSync(skillFile)) return false;
1932
+ assertNoLinks(skillFile);
1933
+ const current = import_node_fs.default.readFileSync(skillFile, "utf8");
1934
+ const frontmatterMatch = current.match(/^(---\r?\n)([\s\S]*?)(\r?\n---)/);
1935
+ if (!frontmatterMatch) return false;
1936
+ const baseDescription = marker.baseDescription?.trim() || extractFrontmatterDescription(current);
1937
+ const nextDescription = formatFrontmatterDescription(baseDescription, entries);
1938
+ const yamlDescription = `description: ${JSON.stringify(nextDescription)}`;
1939
+ const updatedFrontmatter = /^description:\s*.*$/m.test(frontmatterMatch[2]) ? frontmatterMatch[2].replace(/^description:\s*.*$/m, yamlDescription) : `${frontmatterMatch[2]}
1940
+ ${yamlDescription}`;
1941
+ let updated = `${frontmatterMatch[1]}${updatedFrontmatter}${frontmatterMatch[3]}${current.slice(
1942
+ frontmatterMatch[0].length
1943
+ )}`;
1944
+ const starts = [...updated.matchAll(new RegExp(learnedStartMarker, "g"))];
1945
+ const ends = [...updated.matchAll(new RegExp(learnedEndMarker, "g"))];
1946
+ if (starts.length + ends.length > 0 && (starts.length !== 1 || ends.length !== 1 || starts[0].index === void 0 || ends[0].index === void 0 || starts[0].index > ends[0].index)) {
1947
+ const error = new Error(
1948
+ `Malformed BrowserPaw Learned Workflows markers in ${skillFile}. Keep at most one start marker followed by one end marker, then run setup again.`
1949
+ );
1950
+ error.code = "ERR_BROWSERPAW_SKILL_MARKERS";
1951
+ throw error;
1952
+ }
1953
+ const blockPattern = new RegExp(
1954
+ `\\r?\\n?${learnedStartMarker}[\\s\\S]*?${learnedEndMarker}`,
1955
+ "m"
1956
+ );
1957
+ const section = renderLearnedSection(entries);
1958
+ if (blockPattern.test(updated)) {
1959
+ updated = updated.replace(blockPattern, section ? `
1960
+ ${section}` : "");
1961
+ } else if (section) {
1962
+ updated = `${updated.trimEnd()}
1963
+
1964
+ ${section}
1965
+ `;
1966
+ }
1967
+ if (!updated.endsWith("\n")) updated += "\n";
1968
+ if (updated === current) return true;
1969
+ const temporary = import_node_path.default.join(targetDir, `.SKILL.md.${(0, import_node_crypto.randomUUID)()}.tmp`);
1970
+ try {
1971
+ import_node_fs.default.writeFileSync(temporary, updated, { flag: "wx", mode: 384 });
1972
+ import_node_fs.default.renameSync(temporary, skillFile);
1973
+ } finally {
1974
+ import_node_fs.default.rmSync(temporary, { force: true });
1975
+ }
1976
+ return true;
1977
+ }
1978
+ var import_node_fs, import_node_os, import_node_path, import_node_crypto, markerName, skillName, learnedStartMarker, learnedEndMarker, learnedDescriptionPrefix;
1979
+ var init_skill_install = __esm({
1980
+ "src/skill-install.ts"() {
1981
+ "use strict";
1982
+ import_node_fs = __toESM(require("fs"));
1983
+ import_node_os = __toESM(require("os"));
1984
+ import_node_path = __toESM(require("path"));
1985
+ import_node_crypto = require("crypto");
1986
+ init_dist();
1987
+ markerName = ".browserpaw-skill.json";
1988
+ skillName = "browserpaw";
1989
+ learnedStartMarker = "<!-- browserpaw:learned:start -->";
1990
+ learnedEndMarker = "<!-- browserpaw:learned:end -->";
1991
+ learnedDescriptionPrefix = " Learned workflows ready: ";
1992
+ }
1993
+ });
1994
+
1995
+ // src/cli-files.cjs
1996
+ var require_cli_files = __commonJS({
1997
+ "src/cli-files.cjs"(exports2, module2) {
1998
+ "use strict";
1999
+ var fs4 = require("fs");
2000
+ var path5 = require("path");
2001
+ var { randomUUID: randomUUID4 } = require("crypto");
2002
+ var STALE_LOCK_AGE_MS = 10 * 60 * 1e3;
2003
+ function assertNoLinks2(target) {
2004
+ let current = path5.resolve(target);
2005
+ for (; ; ) {
2006
+ const stat = fs4.lstatSync(current, { throwIfNoEntry: false });
2007
+ const isMacSystemRootLink = stat?.isSymbolicLink() && (current === "/var" || current === "/tmp" || current === "/etc") && path5.resolve(path5.dirname(current), fs4.readlinkSync(current)) === `/private${current}`;
2008
+ if (stat?.isSymbolicLink() && !isMacSystemRootLink)
2009
+ throw new Error(`Symlink or junction forbidden: ${current}`);
2010
+ const parent = path5.dirname(current);
2011
+ if (parent === current) return;
2012
+ current = parent;
2013
+ }
2014
+ }
2015
+ function ensureDirectory(target) {
2016
+ assertNoLinks2(target);
2017
+ fs4.mkdirSync(target, { recursive: true, mode: 448 });
2018
+ assertNoLinks2(target);
2019
+ if (!fs4.statSync(target).isDirectory()) throw new Error(`Not a directory: ${target}`);
2020
+ }
2021
+ function readJson2(target) {
2022
+ assertNoLinks2(target);
2023
+ const stat = fs4.lstatSync(target, { throwIfNoEntry: false });
2024
+ if (!stat) return void 0;
2025
+ if (!stat.isFile()) throw new Error(`Not a regular file: ${target}`);
2026
+ return JSON.parse(fs4.readFileSync(target, "utf8"));
2027
+ }
2028
+ function atomicWrite(target, data) {
2029
+ assertNoLinks2(target);
2030
+ const temporary = path5.join(
2031
+ path5.dirname(target),
2032
+ `.${path5.basename(target)}.${randomUUID4()}.tmp`
2033
+ );
2034
+ try {
2035
+ fs4.writeFileSync(temporary, data, { flag: "wx", mode: 384 });
2036
+ fs4.renameSync(temporary, target);
2037
+ } finally {
2038
+ fs4.rmSync(temporary, { force: true });
2039
+ }
2040
+ }
2041
+ function acquireLock(target) {
2042
+ assertNoLinks2(target);
2043
+ const busy = () => new Error(
2044
+ "Session busy or stale lock; verify the previous CLI has stopped before removing its .lock file. Unknown actions must not be replayed."
2045
+ );
2046
+ const reapTarget = `${target}.reap`;
2047
+ const token = randomUUID4();
2048
+ const payload = { pid: process.pid, token, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
2049
+ const readLock = () => {
2050
+ try {
2051
+ const value = JSON.parse(fs4.readFileSync(target, "utf8"));
2052
+ if (!Number.isInteger(value.pid) || value.pid < 1 || typeof value.token !== "string")
2053
+ return void 0;
2054
+ return value;
2055
+ } catch {
2056
+ return void 0;
2057
+ }
2058
+ };
2059
+ const isDead = (pid) => {
2060
+ try {
2061
+ process.kill(pid, 0);
2062
+ return false;
2063
+ } catch (error) {
2064
+ if (error.code === "ESRCH") return true;
2065
+ return false;
2066
+ }
2067
+ };
2068
+ const isStaleCorruptLock = () => {
2069
+ const stat = fs4.lstatSync(target, { throwIfNoEntry: false });
2070
+ return Boolean(stat?.isFile()) && Date.now() - stat.mtimeMs > STALE_LOCK_AGE_MS && !readLock();
2071
+ };
2072
+ const writeFresh = (allowReapGuard = false) => {
2073
+ let descriptor;
2074
+ try {
2075
+ descriptor = fs4.openSync(target, "wx", 384);
2076
+ fs4.writeFileSync(descriptor, JSON.stringify(payload));
2077
+ } catch (error) {
2078
+ if (descriptor !== void 0) fs4.closeSync(descriptor);
2079
+ if (readLock()?.token === token) fs4.rmSync(target, { force: true });
2080
+ throw error;
2081
+ }
2082
+ fs4.closeSync(descriptor);
2083
+ if (!allowReapGuard && fs4.existsSync(reapTarget)) {
2084
+ const current = readLock();
2085
+ if (current?.token === token) fs4.rmSync(target, { force: true });
2086
+ throw busy();
2087
+ }
2088
+ };
2089
+ try {
2090
+ writeFresh();
2091
+ } catch (error) {
2092
+ if (error.code !== "EEXIST") throw error;
2093
+ const existing = readLock();
2094
+ if (!existing && !isStaleCorruptLock()) throw busy();
2095
+ if (existing && !isDead(existing.pid)) throw busy();
2096
+ let reapDescriptor;
2097
+ try {
2098
+ assertNoLinks2(reapTarget);
2099
+ reapDescriptor = fs4.openSync(reapTarget, "wx", 384);
2100
+ } catch (reapError) {
2101
+ if (reapError.code === "EEXIST") throw busy();
2102
+ throw reapError;
2103
+ }
2104
+ try {
2105
+ const confirmed = readLock();
2106
+ if (existing) {
2107
+ if (!confirmed || confirmed.token !== existing.token || !isDead(confirmed.pid)) throw busy();
2108
+ } else if (confirmed || !isStaleCorruptLock()) {
2109
+ throw busy();
2110
+ }
2111
+ fs4.rmSync(target, { force: true });
2112
+ writeFresh(true);
2113
+ } finally {
2114
+ fs4.closeSync(reapDescriptor);
2115
+ fs4.rmSync(reapTarget, { force: true });
2116
+ }
2117
+ }
2118
+ return () => {
2119
+ const current = readLock();
2120
+ if (current?.token === token) fs4.rmSync(target, { force: true });
2121
+ };
2122
+ }
2123
+ module2.exports = { assertNoLinks: assertNoLinks2, ensureDirectory, readJson: readJson2, atomicWrite, acquireLock };
2124
+ }
2125
+ });
2126
+
2127
+ // src/learned-recipes.ts
2128
+ var learned_recipes_exports = {};
2129
+ __export(learned_recipes_exports, {
2130
+ assertNoStoredCredentials: () => assertNoStoredCredentials,
2131
+ browserPawHome: () => browserPawHome,
2132
+ candidateRecipeFilePath: () => candidateRecipeFilePath,
2133
+ coerceWorkflowInputs: () => coerceWorkflowInputs,
2134
+ domainMatchesHost: () => domainMatchesHost,
2135
+ expandRecipeSteps: () => expandRecipeSteps,
2136
+ findLearnedWorkflows: () => findLearnedWorkflows,
2137
+ formatRunCommand: () => formatRunCommand,
2138
+ inspectLearnedWorkflow: () => inspectLearnedWorkflow,
2139
+ isVerifiedSkillPayload: () => isVerifiedSkillPayload,
2140
+ listLearnedWorkflows: () => listLearnedWorkflows,
2141
+ loadLearnedWorkflows: () => loadLearnedWorkflows,
2142
+ matchLearnedWorkflows: () => matchLearnedWorkflows,
2143
+ parseRecipeKeyValues: () => parseRecipeKeyValues,
2144
+ patchSavedRecipe: () => patchSavedRecipe,
2145
+ recipesDirectory: () => recipesDirectory,
2146
+ resolveBundledRecipesDirectory: () => resolveBundledRecipesDirectory,
2147
+ savedRecipeFilePath: () => savedRecipeFilePath,
2148
+ savedRecipeInputs: () => savedRecipeInputs,
2149
+ schemaToInputSpecs: () => schemaToInputSpecs,
2150
+ showLearnedWorkflow: () => showLearnedWorkflow,
2151
+ skillsDirectory: () => skillsDirectory,
2152
+ syncLearnedRouting: () => syncLearnedRouting,
2153
+ validateSavedRecipe: () => validateSavedRecipe
2154
+ });
2155
+ function browserPawHome(override) {
2156
+ return import_node_path2.default.resolve(
2157
+ override || process.env.BROWSERPAW_HOME || import_node_path2.default.join(import_node_os2.default.homedir(), ".browserpaw")
2158
+ );
2159
+ }
2160
+ function recipesDirectory(homeDir = browserPawHome()) {
2161
+ return import_node_path2.default.join(homeDir, "recipes");
2162
+ }
2163
+ function skillsDirectory(homeDir = browserPawHome()) {
2164
+ return import_node_path2.default.join(homeDir, "skills");
2165
+ }
2166
+ function savedRecipeFilePath(id, homeDir = browserPawHome()) {
2167
+ if (typeof id !== "string" || !RECIPE_ID_PATTERN.test(id)) {
2168
+ throw new Error(
2169
+ "Recipe ID must begin with a lowercase letter and contain only letters, digits, or hyphens."
2170
+ );
2171
+ }
2172
+ return import_node_path2.default.join(recipesDirectory(homeDir), `${id}.json`);
2173
+ }
2174
+ function candidateRecipeFilePath(id, homeDir = browserPawHome()) {
2175
+ if (typeof id !== "string" || !RECIPE_ID_PATTERN.test(id)) {
2176
+ throw new Error(
2177
+ "Recipe ID must begin with a lowercase letter and contain only letters, digits, or hyphens."
2178
+ );
2179
+ }
2180
+ return import_node_path2.default.join(recipesDirectory(homeDir), `${id}.candidate.json`);
2181
+ }
2182
+ function domainMatchesHost(hostname, domain) {
2183
+ const host = hostname.toLowerCase().replace(/\.$/, "");
2184
+ const normalized = domain.toLowerCase().replace(/\.$/, "");
2185
+ if (!host || !normalized) return false;
2186
+ return host === normalized || host.endsWith(`.${normalized}`);
2187
+ }
2188
+ function assertNoStoredCredentials(value) {
2189
+ if (typeof value === "string") {
2190
+ if (/\b(?:sk|ghp|github_pat|xox[baprs])_[A-Za-z0-9_-]{10,}\b/i.test(value) || /\bAKIA[0-9A-Z]{16}\b/.test(value) || /\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/i.test(value) || /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/.test(value)) {
2191
+ throw new Error("Do not persist credential-like values in a recipe");
2192
+ }
2193
+ try {
2194
+ const url = new URL(value);
2195
+ if (url.username || url.password) throw new Error("Recipe URLs must not contain userinfo");
2196
+ for (const keyName of url.searchParams.keys()) {
2197
+ if (/token|key|secret|password|auth|cookie/i.test(keyName)) {
2198
+ throw new Error(`Do not persist credential query parameter: ${keyName}`);
2199
+ }
2200
+ }
2201
+ } catch (error) {
2202
+ if (error instanceof Error && /Recipe URLs|credential/.test(error.message)) throw error;
2203
+ }
2204
+ return;
2205
+ }
2206
+ if (Array.isArray(value)) {
2207
+ value.forEach(assertNoStoredCredentials);
2208
+ return;
2209
+ }
2210
+ if (!value || typeof value !== "object") return;
2211
+ for (const [key, item] of Object.entries(value)) {
2212
+ if (/^(authorization|auth|api.?key|access.?token|cookie|password|secret|token|session.?id|tab.?id|document.?id|file.?path)$/i.test(
2213
+ key
2214
+ )) {
2215
+ throw new Error(`Do not persist credentials or ephemeral identity: ${key}`);
2216
+ }
2217
+ assertNoStoredCredentials(item);
2218
+ }
2219
+ }
2220
+ function isVerifiedSkillPayload(input) {
2221
+ if (!input || typeof input !== "object" || Array.isArray(input)) return false;
2222
+ const candidate = input;
2223
+ return typeof candidate.startUrl === "string" && typeof candidate.inputSchema === "object" && typeof candidate.outputSchema === "object" && Array.isArray(candidate.tests);
2224
+ }
2225
+ function extractPlaceholders(steps) {
2226
+ const keys = /* @__PURE__ */ new Set();
2227
+ for (const step of steps) {
2228
+ for (const part of step) {
2229
+ for (const match of part.matchAll(PLACEHOLDER_PATTERN)) {
2230
+ keys.add(match[1]);
2231
+ }
2232
+ }
2233
+ }
2234
+ return [...keys];
2235
+ }
2236
+ function inferDomainsFromSteps(steps) {
2237
+ const domains = /* @__PURE__ */ new Set();
2238
+ for (const step of steps) {
2239
+ for (const part of step) {
2240
+ if (!/^https?:\/\//i.test(part)) continue;
2241
+ try {
2242
+ const sanitized = part.replace(PLACEHOLDER_PATTERN, "placeholder");
2243
+ const host = new URL(sanitized).hostname.toLowerCase();
2244
+ if (host && host !== "localhost" && host !== "127.0.0.1" && DOMAIN_PATTERN.test(host)) {
2245
+ domains.add(host);
2246
+ }
2247
+ } catch {
2248
+ continue;
2249
+ }
2250
+ }
2251
+ }
2252
+ return [...domains];
2253
+ }
2254
+ function validateSavedRecipe(input) {
2255
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
2256
+ throw new Error("Expected a recipe object with id and steps.");
2257
+ }
2258
+ const raw = input;
2259
+ if (typeof raw.id !== "string" || !RECIPE_ID_PATTERN.test(raw.id)) {
2260
+ throw new Error(
2261
+ "Recipe ID must begin with a lowercase letter and contain only letters, digits, or hyphens."
2262
+ );
2263
+ }
2264
+ if (!Array.isArray(raw.steps) || raw.steps.length === 0 || raw.steps.length > 100) {
2265
+ throw new Error("Expected an array of 1\u2013100 command argument arrays.");
2266
+ }
2267
+ const steps = raw.steps.map((args) => {
2268
+ if (!Array.isArray(args) || args.length === 0 || args.some((part) => typeof part !== "string")) {
2269
+ throw new Error("Each batch step must be an array of arguments.");
2270
+ }
2271
+ const separator = args.indexOf("--");
2272
+ for (const token of args.slice(0, separator < 0 ? args.length : separator)) {
2273
+ const volatile = /^--(tab|task|session|recipe)(?:=|$)/.exec(token);
2274
+ if (volatile)
2275
+ throw new Error(
2276
+ `Recipe steps cannot persist volatile targeting option --${volatile[1]}. Choose that context when running the recipe.`
2277
+ );
2278
+ }
2279
+ const parsed = parseCommand(args);
2280
+ assertBatchStep(parsed);
2281
+ for (const index of TARGET_ARGUMENTS.get(parsed.name) ?? []) {
2282
+ const target = parsed.operands[index] ?? "";
2283
+ if (/^\d+$/.test(target))
2284
+ throw new Error(
2285
+ `Recipe step ${parsed.name} ${target} uses a volatile observed ref. Use a durable css:, text:, role:, or label: selector.`
2286
+ );
2287
+ }
2288
+ return args;
2289
+ });
2290
+ assertNoStoredCredentials(raw);
2291
+ const recipe = { id: raw.id, steps };
2292
+ if (raw.status !== void 0) {
2293
+ if (raw.status !== "active" && raw.status !== "candidate") {
2294
+ throw new Error("Recipe status must be active or candidate.");
2295
+ }
2296
+ recipe.status = raw.status;
2297
+ }
2298
+ if (raw.name !== void 0) {
2299
+ if (typeof raw.name !== "string" || !raw.name.trim() || raw.name.length > 120) {
2300
+ throw new Error("Recipe name must be a non-empty string up to 120 characters.");
2301
+ }
2302
+ recipe.name = raw.name.trim();
2303
+ }
2304
+ if (raw.description !== void 0) {
2305
+ if (typeof raw.description !== "string" || raw.description.length > 500) {
2306
+ throw new Error("Recipe description must be a string up to 500 characters.");
2307
+ }
2308
+ recipe.description = raw.description.trim();
2309
+ }
2310
+ if (raw.notes !== void 0) {
2311
+ if (typeof raw.notes !== "string" || raw.notes.length > 2e3) {
2312
+ throw new Error("Recipe notes must be a string up to 2000 characters.");
2313
+ }
2314
+ recipe.notes = raw.notes.trim();
2315
+ }
2316
+ if (raw.domains !== void 0) {
2317
+ if (!Array.isArray(raw.domains) || raw.domains.length > 20) {
2318
+ throw new Error("Recipe domains must be an array of up to 20 hostnames.");
2319
+ }
2320
+ recipe.domains = raw.domains.map((entry) => {
2321
+ if (typeof entry !== "string") throw new Error("Each recipe domain must be a hostname.");
2322
+ const normalized = entry.trim().toLowerCase().replace(/^https?:\/\//, "").replace(/\/.*$/, "");
2323
+ if (!DOMAIN_PATTERN.test(normalized)) throw new Error(`Invalid recipe domain: ${entry}`);
2324
+ return normalized;
2325
+ });
2326
+ }
2327
+ if (raw.keywords !== void 0) {
2328
+ if (!Array.isArray(raw.keywords) || raw.keywords.length > 40 || raw.keywords.some((item) => typeof item !== "string" || !item.trim())) {
2329
+ throw new Error("Recipe keywords must be an array of up to 40 non-empty strings.");
2330
+ }
2331
+ recipe.keywords = raw.keywords.map((item) => item.trim());
2332
+ }
2333
+ if (raw.sourceUrls !== void 0) {
2334
+ if (!Array.isArray(raw.sourceUrls) || raw.sourceUrls.length > 10 || raw.sourceUrls.some((item) => typeof item !== "string" || !/^https?:\/\//.test(item))) {
2335
+ throw new Error("Recipe sourceUrls must be HTTP(S) URLs.");
2336
+ }
2337
+ recipe.sourceUrls = raw.sourceUrls;
2338
+ }
2339
+ if (raw.inputs !== void 0) {
2340
+ if (!raw.inputs || typeof raw.inputs !== "object" || Array.isArray(raw.inputs)) {
2341
+ throw new Error("Recipe inputs must be an object mapping input names to specs.");
2342
+ }
2343
+ const validatedInputs = {};
2344
+ for (const [key, specRaw] of Object.entries(raw.inputs)) {
2345
+ if (!/^[a-zA-Z0-9_-]{1,64}$/.test(key)) throw new Error(`Invalid recipe input name: ${key}`);
2346
+ if (!specRaw || typeof specRaw !== "object" || Array.isArray(specRaw)) {
2347
+ throw new Error(`Invalid recipe input spec for ${key}.`);
2348
+ }
2349
+ const spec = specRaw;
2350
+ const out = {};
2351
+ if (spec.type !== void 0) {
2352
+ if (typeof spec.type !== "string" || !INPUT_TYPES.has(spec.type)) {
2353
+ throw new Error(`Unsupported input type for ${key}: ${String(spec.type)}`);
2354
+ }
2355
+ out.type = spec.type;
2356
+ }
2357
+ if (spec.required !== void 0) out.required = Boolean(spec.required);
2358
+ if (spec.default !== void 0) out.default = spec.default;
2359
+ if (typeof spec.description === "string") out.description = spec.description.trim();
2360
+ validatedInputs[key] = out;
2361
+ }
2362
+ recipe.inputs = validatedInputs;
2363
+ }
2364
+ recipe.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2365
+ return recipe;
2366
+ }
2367
+ function schemaToInputSpecs(schema) {
2368
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) return {};
2369
+ const record = schema;
2370
+ const properties = record.properties && typeof record.properties === "object" && !Array.isArray(record.properties) ? record.properties : {};
2371
+ const required = new Set(
2372
+ Array.isArray(record.required) ? record.required.filter((item) => typeof item === "string") : []
2373
+ );
2374
+ const specs = {};
2375
+ for (const [key, prop] of Object.entries(properties)) {
2376
+ if (!prop || typeof prop !== "object") continue;
2377
+ specs[key] = {
2378
+ ...typeof prop.type === "string" && INPUT_TYPES.has(prop.type) ? { type: prop.type } : {},
2379
+ required: required.has(key),
2380
+ ...prop.default !== void 0 ? { default: prop.default } : {},
2381
+ ...typeof prop.description === "string" ? { description: prop.description } : {}
2382
+ };
2383
+ }
2384
+ return specs;
2385
+ }
2386
+ function savedRecipeInputs(recipe) {
2387
+ const merged = { ...recipe.inputs ?? {} };
2388
+ for (const key of extractPlaceholders(recipe.steps)) {
2389
+ if (!merged[key]) {
2390
+ merged[key] = { type: "string", required: true };
2391
+ }
2392
+ }
2393
+ return merged;
2394
+ }
2395
+ function formatRunCommand(id, inputs) {
2396
+ const args = Object.entries(inputs).filter(([, spec]) => spec.required !== false && spec.default === void 0).map(([key]) => `${key}=<${key}>`);
2397
+ return ["browserpaw recipe run", id, ...args].join(" ");
2398
+ }
2399
+ function resolveBundledRecipesDirectory(homeDir = browserPawHome()) {
2400
+ const candidates = [
2401
+ import_node_path2.default.join(__dirname, "recipes"),
2402
+ import_node_path2.default.join(homeDir, "host", "recipes"),
2403
+ import_node_path2.default.join(__dirname, "..", "dist", "v5", "recipes"),
2404
+ import_node_path2.default.join(__dirname, "..", "dist", "recipes"),
2405
+ import_node_path2.default.resolve(__dirname, "..", "..", "..", "skills", "browserpaw", "assets", "recipes")
2406
+ ];
2407
+ return candidates.find((candidate) => import_node_fs2.default.existsSync(candidate));
2408
+ }
2409
+ function readJsonSafe(filePath, maxBytes = 4 * 1024 * 1024) {
2410
+ const stat = import_node_fs2.default.lstatSync(filePath, { throwIfNoEntry: false });
2411
+ if (!stat || stat.isSymbolicLink() || !stat.isFile() || stat.size > maxBytes) return void 0;
2412
+ try {
2413
+ return JSON.parse(import_node_fs2.default.readFileSync(filePath, "utf8"));
2414
+ } catch {
2415
+ return void 0;
2416
+ }
2417
+ }
2418
+ function loadLearnedWorkflows(homeDir = browserPawHome(), options = {}) {
2419
+ const byId = /* @__PURE__ */ new Map();
2420
+ const recipesDir = recipesDirectory(homeDir);
2421
+ if (import_node_fs2.default.existsSync(recipesDir) && !import_node_fs2.default.lstatSync(recipesDir).isSymbolicLink()) {
2422
+ for (const file of import_node_fs2.default.readdirSync(recipesDir).filter((name) => /^[a-z][a-z0-9-]{0,63}(?:\.candidate)?\.json$/.test(name)).sort()) {
2423
+ const fullPath = import_node_path2.default.join(recipesDir, file);
2424
+ const parsed = readJsonSafe(fullPath, 256 * 1024);
2425
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue;
2426
+ const rec = parsed;
2427
+ if (typeof rec.id !== "string" || !Array.isArray(rec.steps)) continue;
2428
+ const candidateFile = file.endsWith(".candidate.json");
2429
+ const status = candidateFile || rec.status === "candidate" ? "candidate" : "active";
2430
+ if (status === "candidate" && !options.includeCandidates) continue;
2431
+ if (byId.has(rec.id)) continue;
2432
+ const inputs = savedRecipeInputs(rec);
2433
+ const domains = rec.domains?.length ? rec.domains : inferDomainsFromSteps(rec.steps);
2434
+ byId.set(rec.id, {
2435
+ id: rec.id,
2436
+ kind: "recipe",
2437
+ status,
2438
+ name: rec.name || rec.id,
2439
+ description: rec.description || `Saved BrowserPaw CLI workflow (${rec.steps.length} steps).`,
2440
+ domains,
2441
+ keywords: rec.keywords ?? [],
2442
+ inputs,
2443
+ ...rec.notes ? { notes: rec.notes } : {},
2444
+ command: formatRunCommand(rec.id, inputs),
2445
+ sourcePath: fullPath
2446
+ });
2447
+ }
2448
+ }
2449
+ const skillsDir = skillsDirectory(homeDir);
2450
+ if (import_node_fs2.default.existsSync(skillsDir) && !import_node_fs2.default.lstatSync(skillsDir).isSymbolicLink()) {
2451
+ for (const file of import_node_fs2.default.readdirSync(skillsDir).filter((name) => /^[a-z][a-z0-9-]{0,63}\.json$/.test(name)).sort()) {
2452
+ const fullPath = import_node_path2.default.join(skillsDir, file);
2453
+ const parsed = readJsonSafe(fullPath);
2454
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue;
2455
+ const record = parsed;
2456
+ if (typeof record.id !== "string" || !Array.isArray(record.versions)) continue;
2457
+ const active = record.versions.find(
2458
+ (item) => item.version === record.activeVersion && item.status === "active"
2459
+ );
2460
+ const chosen = active ?? (options.includeCandidates ? [...record.versions].reverse().find((item) => item.status === "candidate") : void 0);
2461
+ if (!chosen?.definition) continue;
2462
+ if (byId.has(record.id) && chosen.status !== "active") continue;
2463
+ const def = chosen.definition;
2464
+ const inputs = schemaToInputSpecs(def.inputSchema);
2465
+ byId.set(record.id, {
2466
+ id: record.id,
2467
+ kind: "skill",
2468
+ status: chosen.status === "active" ? "active" : "candidate",
2469
+ name: def.name || record.id,
2470
+ description: def.description || "",
2471
+ domains: Array.isArray(def.domains) ? def.domains : [],
2472
+ keywords: Array.isArray(def.keywords) ? def.keywords : [],
2473
+ inputs,
2474
+ command: formatRunCommand(record.id, inputs),
2475
+ sourcePath: fullPath
2476
+ });
2477
+ }
2478
+ }
2479
+ if (options.includeCandidates) {
2480
+ const bundledDir = options.bundledDir ?? resolveBundledRecipesDirectory(homeDir);
2481
+ if (bundledDir && import_node_fs2.default.existsSync(bundledDir) && !import_node_fs2.default.lstatSync(bundledDir).isSymbolicLink()) {
2482
+ for (const file of import_node_fs2.default.readdirSync(bundledDir).filter((name) => /^[a-z][a-z0-9-]{0,63}\.json$/.test(name)).sort()) {
2483
+ const fullPath = import_node_path2.default.join(bundledDir, file);
2484
+ const parsed = readJsonSafe(fullPath, 256 * 1024);
2485
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue;
2486
+ const def = parsed;
2487
+ if (typeof def.id !== "string" || byId.has(def.id)) continue;
2488
+ const inputs = schemaToInputSpecs(def.inputSchema);
2489
+ byId.set(def.id, {
2490
+ id: def.id,
2491
+ kind: "skill",
2492
+ status: "candidate",
2493
+ name: def.name || def.id,
2494
+ description: def.description || "",
2495
+ domains: Array.isArray(def.domains) ? def.domains : [],
2496
+ keywords: Array.isArray(def.keywords) ? def.keywords : [],
2497
+ inputs,
2498
+ command: formatRunCommand(def.id, inputs),
2499
+ sourcePath: fullPath
2500
+ });
2501
+ }
2502
+ }
2503
+ }
2504
+ return [...byId.values()].sort((left, right) => {
2505
+ if (left.status !== right.status) return left.status === "active" ? -1 : 1;
2506
+ return left.id.localeCompare(right.id);
2507
+ });
2508
+ }
2509
+ function extractQuerySignals(query) {
2510
+ const raw = query.trim().toLowerCase();
2511
+ const tokens = /* @__PURE__ */ new Set();
2512
+ const domains = /* @__PURE__ */ new Set();
2513
+ for (const match of raw.matchAll(/https?:\/\/([a-z0-9.-]+)/gi)) {
2514
+ domains.add(match[1].toLowerCase());
2515
+ }
2516
+ for (const match of raw.matchAll(/\b([a-z0-9-]+(?:\.[a-z0-9-]+)+)\b/gi)) {
2517
+ domains.add(match[1].toLowerCase());
2518
+ }
2519
+ for (const part of raw.split(/[\s,,。、/|;:()()【】[\]]+/).filter(Boolean)) {
2520
+ tokens.add(part);
2521
+ }
2522
+ for (const [pattern, expansions] of QUERY_ALIASES) {
2523
+ if (pattern.test(raw)) {
2524
+ for (const word of expansions) {
2525
+ tokens.add(word);
2526
+ if (word.includes(".")) domains.add(word);
2527
+ }
2528
+ }
2529
+ }
2530
+ return { tokens: [...tokens], domains: [...domains], raw };
2531
+ }
2532
+ function matchLearnedWorkflows(entries, filter = {}) {
2533
+ let pool = entries.slice();
2534
+ if (filter.url) {
2535
+ const hostname = new URL(filter.url).hostname.toLowerCase();
2536
+ pool = pool.filter(
2537
+ (entry) => entry.domains.some((domain) => domainMatchesHost(hostname, domain))
2538
+ );
2539
+ }
2540
+ const query = filter.query?.trim() ?? "";
2541
+ if (!query) {
2542
+ return pool.map((entry) => ({ ...entry, score: filter.url ? 10 : 1 }));
2543
+ }
2544
+ const signals = extractQuerySignals(query);
2545
+ const scored = [];
2546
+ for (const entry of pool) {
2547
+ let score = 0;
2548
+ const idLower = entry.id.toLowerCase();
2549
+ const nameLower = entry.name.toLowerCase();
2550
+ const descLower = `${entry.description} ${entry.notes ?? ""}`.toLowerCase();
2551
+ const keywordsLower = entry.keywords.map((item) => item.toLowerCase());
2552
+ const domainsLower = entry.domains.map((item) => item.toLowerCase());
2553
+ if (idLower === signals.raw) score += 100;
2554
+ else if (nameLower === signals.raw || keywordsLower.includes(signals.raw)) score += 60;
2555
+ else if (signals.raw.length >= 2 && (idLower.includes(signals.raw) || nameLower.includes(signals.raw) || keywordsLower.some((kw) => kw.includes(signals.raw) || signals.raw.includes(kw)) || descLower.includes(signals.raw))) {
2556
+ score += 24;
2557
+ }
2558
+ for (const domain of signals.domains) {
2559
+ if (domainsLower.some((candidate) => domainMatchesHost(domain, candidate))) {
2560
+ score += 30;
2561
+ }
2562
+ }
2563
+ for (const token of signals.tokens) {
2564
+ if (idLower === token || keywordsLower.includes(token)) score += 16;
2565
+ else if (domainsLower.some((candidate) => domainMatchesHost(token, candidate))) score += 20;
2566
+ else if (token.length >= 2 && (idLower.includes(token) || nameLower.includes(token) || keywordsLower.some((kw) => kw.includes(token)))) {
2567
+ score += 10;
2568
+ } else if (token.length >= 2 && descLower.includes(token)) {
2569
+ score += 5;
2570
+ }
2571
+ }
2572
+ if (score > 0) scored.push({ ...entry, score });
2573
+ }
2574
+ return scored.sort((left, right) => {
2575
+ if (left.status !== right.status) return left.status === "active" ? -1 : 1;
2576
+ if (right.score !== left.score) return right.score - left.score;
2577
+ return left.id.localeCompare(right.id);
2578
+ });
2579
+ }
2580
+ function listLearnedWorkflows(homeDir = browserPawHome(), options = {}) {
2581
+ const all = loadLearnedWorkflows(homeDir, { includeCandidates: options.includeCandidates });
2582
+ const workflows = options.url || options.query ? matchLearnedWorkflows(all, { url: options.url, query: options.query }) : all;
2583
+ return {
2584
+ homeDir,
2585
+ count: workflows.length,
2586
+ workflows: workflows.map(({ sourcePath: _ignored, ...item }) => item),
2587
+ saved: workflows.filter((item) => item.kind === "recipe").map((item) => item.id)
2588
+ };
2589
+ }
2590
+ function findLearnedWorkflows(homeDir = browserPawHome(), options = {}) {
2591
+ const all = loadLearnedWorkflows(homeDir, { includeCandidates: options.includeCandidates });
2592
+ const matches = matchLearnedWorkflows(all, { url: options.url, query: options.query });
2593
+ return {
2594
+ homeDir,
2595
+ ...options.query ? { query: options.query } : {},
2596
+ ...options.url ? { url: options.url } : {},
2597
+ count: matches.length,
2598
+ matches: matches.map(({ sourcePath: _ignored, ...item }) => item)
2599
+ };
2600
+ }
2601
+ function parseRecipeKeyValues(operands) {
2602
+ const inputs = {};
2603
+ for (const part of operands) {
2604
+ const index = part.indexOf("=");
2605
+ if (index < 1) throw new Error("Recipe inputs use KEY=VALUE.");
2606
+ inputs[part.slice(0, index)] = part.slice(index + 1);
2607
+ }
2608
+ return inputs;
2609
+ }
2610
+ function coerceWorkflowInputs(raw, specs = {}) {
2611
+ const result = {};
2612
+ for (const [key, spec] of Object.entries(specs)) {
2613
+ if (!Object.prototype.hasOwnProperty.call(raw, key) && spec.default !== void 0) {
2614
+ result[key] = spec.default;
2615
+ }
2616
+ }
2617
+ for (const [key, value] of Object.entries(raw)) {
2618
+ const type = specs[key]?.type;
2619
+ if (type === "integer") {
2620
+ if (!/^-?\d+$/.test(value)) throw new Error(`Recipe input ${key} must be an integer.`);
2621
+ const parsed = Number(value);
2622
+ if (!Number.isSafeInteger(parsed)) throw new Error(`Recipe input ${key} must be an integer.`);
2623
+ result[key] = parsed;
2624
+ } else if (type === "number") {
2625
+ const parsed = Number(value);
2626
+ if (!Number.isFinite(parsed)) throw new Error(`Recipe input ${key} must be a number.`);
2627
+ result[key] = parsed;
2628
+ } else if (type === "boolean") {
2629
+ if (value === "true") result[key] = true;
2630
+ else if (value === "false") result[key] = false;
2631
+ else throw new Error(`Recipe input ${key} must be true or false.`);
2632
+ } else if (type === "object" || type === "array") {
2633
+ let parsed;
2634
+ try {
2635
+ parsed = JSON.parse(value);
2636
+ } catch {
2637
+ throw new Error(`Recipe input ${key} must be valid JSON.`);
2638
+ }
2639
+ if (type === "array" ? !Array.isArray(parsed) : !parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
2640
+ throw new Error(`Recipe input ${key} must be a JSON ${type}.`);
2641
+ }
2642
+ result[key] = parsed;
2643
+ } else {
2644
+ result[key] = value;
2645
+ }
2646
+ }
2647
+ return result;
2648
+ }
2649
+ function expandRecipeSteps(steps, inputs) {
2650
+ return steps.map(
2651
+ (step) => step.map((part) => {
2652
+ const embeddedInUrl = /^https?:\/\//i.test(part) && !/^\{\{[a-zA-Z0-9_-]+\}\}$/.test(part.trim());
2653
+ return part.replace(PLACEHOLDER_PATTERN, (_match, key) => {
2654
+ if (!Object.prototype.hasOwnProperty.call(inputs, key) || inputs[key] === void 0) {
2655
+ throw new Error(`Missing recipe input ${key}.`);
2656
+ }
2657
+ const text = typeof inputs[key] === "string" ? inputs[key] : JSON.stringify(inputs[key]);
2658
+ return embeddedInUrl ? encodeURIComponent(text) : text;
2659
+ });
2660
+ })
2661
+ );
2662
+ }
2663
+ function inspectLearnedWorkflow(id, homeDir = browserPawHome(), bundledDir, preferActive = false) {
2664
+ if (!RECIPE_ID_PATTERN.test(id)) {
2665
+ throw new Error(
2666
+ "Recipe ID must begin with a lowercase letter and contain only letters, digits, or hyphens."
2667
+ );
2668
+ }
2669
+ const active = preferActive ? loadLearnedWorkflows(homeDir, { includeCandidates: false, bundledDir }).find(
2670
+ (item) => item.id === id
2671
+ ) : void 0;
2672
+ const candidatePath = candidateRecipeFilePath(id, homeDir);
2673
+ const candidate = active ? void 0 : readJsonSafe(candidatePath, 256 * 1024);
2674
+ if (candidate && typeof candidate === "object" && !Array.isArray(candidate)) {
2675
+ const recipe = validateSavedRecipe(candidate);
2676
+ const inputs = savedRecipeInputs(recipe);
2677
+ return {
2678
+ summary: {
2679
+ id: recipe.id,
2680
+ kind: "recipe",
2681
+ status: "candidate",
2682
+ name: recipe.name || recipe.id,
2683
+ description: recipe.description || `Saved BrowserPaw CLI workflow (${recipe.steps.length} steps).`,
2684
+ domains: recipe.domains?.length ? recipe.domains : inferDomainsFromSteps(recipe.steps),
2685
+ keywords: recipe.keywords ?? [],
2686
+ inputs,
2687
+ ...recipe.notes ? { notes: recipe.notes } : {},
2688
+ command: formatRunCommand(recipe.id, inputs),
2689
+ sourcePath: candidatePath
2690
+ },
2691
+ definition: recipe
2692
+ };
2693
+ }
2694
+ const summary = active ?? loadLearnedWorkflows(homeDir, { includeCandidates: true, bundledDir }).find(
2695
+ (item) => item.id === id
2696
+ );
2697
+ if (!summary) return void 0;
2698
+ const raw = readJsonSafe(summary.sourcePath);
2699
+ if (summary.kind === "skill" && raw && typeof raw === "object" && Array.isArray(raw.versions)) {
2700
+ const record = raw;
2701
+ const selected = record.versions.find((item) => item.version === record.activeVersion) ?? record.versions[record.versions.length - 1];
2702
+ return { summary, definition: selected?.definition ?? raw };
2703
+ }
2704
+ return { summary, definition: raw };
2705
+ }
2706
+ function patchSavedRecipe(id, stepIndex, args, homeDir = browserPawHome()) {
2707
+ const index = typeof stepIndex === "number" ? stepIndex : typeof stepIndex === "string" && /^\d+$/.test(stepIndex) ? Number(stepIndex) : NaN;
2708
+ const activePath = savedRecipeFilePath(id, homeDir);
2709
+ const active = readJsonSafe(activePath, 256 * 1024);
2710
+ const candidatePath = candidateRecipeFilePath(id, homeDir);
2711
+ const candidate = readJsonSafe(candidatePath, 256 * 1024);
2712
+ const source = candidate ?? active;
2713
+ if (!source || typeof source !== "object" || Array.isArray(source)) {
2714
+ throw new Error(`Unknown saved recipe: ${id}.`);
2715
+ }
2716
+ const recipe = validateSavedRecipe(source);
2717
+ if (!Number.isSafeInteger(index) || index < 0 || index >= recipe.steps.length) {
2718
+ throw new Error(`Recipe step index must be from 0 to ${recipe.steps.length - 1}.`);
2719
+ }
2720
+ if (!Array.isArray(args) || !args.length || args.some((part) => typeof part !== "string")) {
2721
+ throw new Error("Replacement step must be a command argument array.");
2722
+ }
2723
+ const steps = recipe.steps.map(
2724
+ (step, current) => current === index ? [...args] : step
2725
+ );
2726
+ const patched = validateSavedRecipe({ ...recipe, status: "candidate", steps });
2727
+ const { ensureDirectory, atomicWrite } = require_cli_files();
2728
+ ensureDirectory(recipesDirectory(homeDir));
2729
+ atomicWrite(candidatePath, JSON.stringify(patched, null, 2) + "\n");
2730
+ return patched;
2731
+ }
2732
+ function showLearnedWorkflow(id, homeDir = browserPawHome(), bundledDir) {
2733
+ const inspected = inspectLearnedWorkflow(id, homeDir, bundledDir);
2734
+ if (!inspected) return void 0;
2735
+ const { sourcePath: _ignored, ...summary } = inspected.summary;
2736
+ return { summary, definition: inspected.definition };
2737
+ }
2738
+ function syncLearnedRouting(homeDir = browserPawHome(), extraSkillPaths = []) {
2739
+ const { ensureDirectory, atomicWrite, readJson: readJson2 } = require_cli_files();
2740
+ const activeWorkflows = loadLearnedWorkflows(homeDir, { includeCandidates: false });
2741
+ const indexPath = import_node_path2.default.join(homeDir, "learned-index.json");
2742
+ ensureDirectory(homeDir);
2743
+ atomicWrite(
2744
+ indexPath,
2745
+ `${JSON.stringify(
2746
+ {
2747
+ version: 1,
2748
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2749
+ homeDir,
2750
+ workflows: activeWorkflows.map(({ sourcePath: _ignored, ...item }) => item)
2751
+ },
2752
+ null,
2753
+ 2
2754
+ )}
2755
+ `
2756
+ );
2757
+ const installation = readJson2(import_node_path2.default.join(homeDir, "installation.json"));
2758
+ const candidates = /* @__PURE__ */ new Set();
2759
+ for (const candidate of [
2760
+ ...Array.isArray(installation?.skillPaths) ? installation.skillPaths : [],
2761
+ ...typeof installation?.skillPath === "string" ? [installation.skillPath] : [],
2762
+ ...extraSkillPaths
2763
+ ]) {
2764
+ if (typeof candidate === "string" && candidate.trim()) {
2765
+ candidates.add(import_node_path2.default.resolve(candidate));
2766
+ }
2767
+ }
2768
+ const routingEntries = activeWorkflows.map((item) => ({
2769
+ id: item.id,
2770
+ kind: item.kind,
2771
+ name: item.name,
2772
+ description: item.description,
2773
+ domains: item.domains,
2774
+ command: item.command
2775
+ }));
2776
+ const syncedSkillPaths = [];
2777
+ for (const skillDir of candidates) {
2778
+ try {
2779
+ if (syncInstalledSkillRouting(skillDir, routingEntries)) {
2780
+ syncedSkillPaths.push(skillDir);
2781
+ }
2782
+ } catch (error) {
2783
+ if (error instanceof Error && error.code === "ERR_BROWSERPAW_SKILL_MARKERS")
2784
+ throw error;
2785
+ }
2786
+ }
2787
+ return { indexPath, workflowCount: activeWorkflows.length, syncedSkillPaths };
2788
+ }
2789
+ var import_node_fs2, import_node_os2, import_node_path2, RECIPE_ID_PATTERN, DOMAIN_PATTERN, PLACEHOLDER_PATTERN, INPUT_TYPES, TARGET_ARGUMENTS, QUERY_ALIASES;
2790
+ var init_learned_recipes = __esm({
2791
+ "src/learned-recipes.ts"() {
2792
+ "use strict";
2793
+ import_node_fs2 = __toESM(require("fs"));
2794
+ import_node_os2 = __toESM(require("os"));
2795
+ import_node_path2 = __toESM(require("path"));
2796
+ init_dist();
2797
+ init_command_utils();
2798
+ init_skill_install();
2799
+ RECIPE_ID_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
2800
+ DOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/;
2801
+ PLACEHOLDER_PATTERN = /\{\{([a-zA-Z0-9_-]+)\}\}/g;
2802
+ INPUT_TYPES = /* @__PURE__ */ new Set([
2803
+ "string",
2804
+ "integer",
2805
+ "number",
2806
+ "boolean",
2807
+ "object",
2808
+ "array"
2809
+ ]);
2810
+ TARGET_ARGUMENTS = /* @__PURE__ */ new Map([
2811
+ ["text", [0]],
2812
+ ["screenshot", [0]],
2813
+ ["wait", [0]],
2814
+ ["click", [0]],
2815
+ ["hover", [0]],
2816
+ ["fill", [0]],
2817
+ ["select", [0]],
2818
+ ["press", [1]],
2819
+ ["scroll", [0]],
2820
+ ["drag", [0, 1]],
2821
+ ["upload", [0]],
2822
+ ["download", [0]]
2823
+ ]);
2824
+ QUERY_ALIASES = [
2825
+ [/推特|推文|twitter/i, ["twitter", "x", "x.com", "twitter.com"]],
2826
+ [/搜索|查找|搜一下|搜一搜|检索/i, ["search", "find", "query"]],
2827
+ [/帖子|动态|话题|讨论|串|thread/i, ["posts", "thread", "status"]],
2828
+ [/版本|发布|发行版|更新日志/i, ["releases", "release", "version"]],
2829
+ [/文档|手册|参考/i, ["docs", "documentation", "reference", "mdn"]],
2830
+ [/对比|比较/i, ["compare", "comparison"]],
2831
+ [/包|依赖|npm/i, ["npm", "package"]],
2832
+ [/下载/i, ["download"]]
2833
+ ];
2834
+ }
2835
+ });
2836
+
2837
+ // src/scripts/constant.ts
2838
+ var init_constant = __esm({
2839
+ "src/scripts/constant.ts"() {
2840
+ "use strict";
2841
+ init_dist();
2842
+ }
2843
+ });
2844
+
2845
+ // src/scripts/browser-config.ts
2846
+ function getUserManifestPathForBrowser(browser) {
2847
+ const platform2 = os4.platform();
2848
+ if (platform2 === "win32") {
2849
+ const appData = process.env.APPDATA || path4.join(os4.homedir(), "AppData", "Roaming");
2850
+ switch (browser) {
2851
+ case "chrome" /* CHROME */:
2852
+ return path4.join(appData, "Google", "Chrome", "NativeMessagingHosts", `${HOST_NAME}.json`);
2853
+ case "chromium" /* CHROMIUM */:
2854
+ return path4.join(appData, "Chromium", "NativeMessagingHosts", `${HOST_NAME}.json`);
2855
+ default:
2856
+ return path4.join(appData, "Google", "Chrome", "NativeMessagingHosts", `${HOST_NAME}.json`);
2857
+ }
2858
+ } else if (platform2 === "darwin") {
2859
+ const home = os4.homedir();
2860
+ switch (browser) {
2861
+ case "chrome" /* CHROME */:
2862
+ return path4.join(
2863
+ home,
2864
+ "Library",
2865
+ "Application Support",
2866
+ "Google",
2867
+ "Chrome",
2868
+ "NativeMessagingHosts",
2869
+ `${HOST_NAME}.json`
2870
+ );
2871
+ case "chromium" /* CHROMIUM */:
2872
+ return path4.join(
2873
+ home,
2874
+ "Library",
2875
+ "Application Support",
2876
+ "Chromium",
2877
+ "NativeMessagingHosts",
2878
+ `${HOST_NAME}.json`
2879
+ );
2880
+ default:
2881
+ return path4.join(
2882
+ home,
2883
+ "Library",
2884
+ "Application Support",
2885
+ "Google",
2886
+ "Chrome",
2887
+ "NativeMessagingHosts",
2888
+ `${HOST_NAME}.json`
2889
+ );
2890
+ }
2891
+ } else {
2892
+ const home = os4.homedir();
2893
+ switch (browser) {
2894
+ case "chrome" /* CHROME */:
2895
+ return path4.join(
2896
+ home,
2897
+ ".config",
2898
+ "google-chrome",
2899
+ "NativeMessagingHosts",
2900
+ `${HOST_NAME}.json`
2901
+ );
2902
+ case "chromium" /* CHROMIUM */:
2903
+ return path4.join(home, ".config", "chromium", "NativeMessagingHosts", `${HOST_NAME}.json`);
2904
+ default:
2905
+ return path4.join(
2906
+ home,
2907
+ ".config",
2908
+ "google-chrome",
2909
+ "NativeMessagingHosts",
2910
+ `${HOST_NAME}.json`
2911
+ );
2912
+ }
2913
+ }
2914
+ }
2915
+ function getSystemManifestPathForBrowser(browser) {
2916
+ const platform2 = os4.platform();
2917
+ if (platform2 === "win32") {
2918
+ const programFiles = process.env.ProgramFiles || "C:\\Program Files";
2919
+ switch (browser) {
2920
+ case "chrome" /* CHROME */:
2921
+ return path4.join(
2922
+ programFiles,
2923
+ "Google",
2924
+ "Chrome",
2925
+ "NativeMessagingHosts",
2926
+ `${HOST_NAME}.json`
2927
+ );
2928
+ case "chromium" /* CHROMIUM */:
2929
+ return path4.join(programFiles, "Chromium", "NativeMessagingHosts", `${HOST_NAME}.json`);
2930
+ default:
2931
+ return path4.join(
2932
+ programFiles,
2933
+ "Google",
2934
+ "Chrome",
2935
+ "NativeMessagingHosts",
2936
+ `${HOST_NAME}.json`
2937
+ );
2938
+ }
2939
+ } else if (platform2 === "darwin") {
2940
+ switch (browser) {
2941
+ case "chrome" /* CHROME */:
2942
+ return path4.join(
2943
+ "/Library",
2944
+ "Google",
2945
+ "Chrome",
2946
+ "NativeMessagingHosts",
2947
+ `${HOST_NAME}.json`
2948
+ );
2949
+ case "chromium" /* CHROMIUM */:
2950
+ return path4.join(
2951
+ "/Library",
2952
+ "Application Support",
2953
+ "Chromium",
2954
+ "NativeMessagingHosts",
2955
+ `${HOST_NAME}.json`
2956
+ );
2957
+ default:
2958
+ return path4.join(
2959
+ "/Library",
2960
+ "Google",
2961
+ "Chrome",
2962
+ "NativeMessagingHosts",
2963
+ `${HOST_NAME}.json`
2964
+ );
2965
+ }
2966
+ } else {
2967
+ switch (browser) {
2968
+ case "chrome" /* CHROME */:
2969
+ return path4.join("/etc", "opt", "chrome", "native-messaging-hosts", `${HOST_NAME}.json`);
2970
+ case "chromium" /* CHROMIUM */:
2971
+ return path4.join("/etc", "chromium", "native-messaging-hosts", `${HOST_NAME}.json`);
2972
+ default:
2973
+ return path4.join("/etc", "opt", "chrome", "native-messaging-hosts", `${HOST_NAME}.json`);
2974
+ }
2975
+ }
2976
+ }
2977
+ function getRegistryKeys(browser) {
2978
+ if (os4.platform() !== "win32") return void 0;
2979
+ const browserPaths = {
2980
+ ["chrome" /* CHROME */]: {
2981
+ user: `HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts\\${HOST_NAME}`,
2982
+ system: `HKLM\\Software\\Google\\Chrome\\NativeMessagingHosts\\${HOST_NAME}`
2983
+ },
2984
+ ["chromium" /* CHROMIUM */]: {
2985
+ user: `HKCU\\Software\\Chromium\\NativeMessagingHosts\\${HOST_NAME}`,
2986
+ system: `HKLM\\Software\\Chromium\\NativeMessagingHosts\\${HOST_NAME}`
2987
+ }
2988
+ };
2989
+ return browserPaths[browser];
2990
+ }
2991
+ function getBrowserConfig(browser) {
2992
+ const registryKeys = getRegistryKeys(browser);
2993
+ return {
2994
+ type: browser,
2995
+ displayName: browser.charAt(0).toUpperCase() + browser.slice(1),
2996
+ userManifestPath: getUserManifestPathForBrowser(browser),
2997
+ systemManifestPath: getSystemManifestPathForBrowser(browser),
2998
+ registryKey: registryKeys?.user,
2999
+ systemRegistryKey: registryKeys?.system
3000
+ };
3001
+ }
3002
+ var os4, path4;
3003
+ var init_browser_config = __esm({
3004
+ "src/scripts/browser-config.ts"() {
3005
+ "use strict";
3006
+ os4 = __toESM(require("os"));
3007
+ path4 = __toESM(require("path"));
3008
+ init_constant();
3009
+ }
3010
+ });
3011
+
3012
+ // src/cli-setup.ts
3013
+ var cli_setup_exports = {};
3014
+ __export(cli_setup_exports, {
3015
+ manageInstallation: () => manageInstallation
3016
+ });
3017
+ function readJson(path5) {
3018
+ if (!(0, import_node_fs4.existsSync)(path5)) return void 0;
3019
+ return JSON.parse((0, import_node_fs4.readFileSync)(path5, "utf8"));
3020
+ }
3021
+ function writeJson(path5, value) {
3022
+ const temporary = path5 + "." + (0, import_node_crypto2.randomUUID)() + ".tmp";
3023
+ try {
3024
+ (0, import_node_fs4.writeFileSync)(temporary, JSON.stringify(value, null, 2) + "\n", { flag: "wx", mode: 384 });
3025
+ (0, import_node_fs4.renameSync)(temporary, path5);
3026
+ } finally {
3027
+ (0, import_node_fs4.rmSync)(temporary, { force: true });
3028
+ }
3029
+ }
3030
+ function manifestFor(root, extensionId) {
3031
+ return {
3032
+ name: HOST_NAME,
3033
+ description: "BrowserPaw Native Messaging host",
3034
+ path: (0, import_node_path5.join)(root, "host", process.platform === "win32" ? "run_host.bat" : "run_host.sh"),
3035
+ type: "stdio",
3036
+ allowed_origins: [`chrome-extension://${extensionId}/`]
3037
+ };
3038
+ }
3039
+ function register(root, browser, extensionId) {
3040
+ const config = getBrowserConfig(browser);
3041
+ const manifest = manifestFor(root, extensionId);
3042
+ const existing = readJson(config.userManifestPath);
3043
+ if (existing && existing.path !== manifest.path)
3044
+ throw new Error(
3045
+ `BrowserPaw is already registered from another installation: ${config.userManifestPath}`
3046
+ );
3047
+ (0, import_node_fs4.mkdirSync)((0, import_node_path5.dirname)(config.userManifestPath), { recursive: true });
3048
+ writeJson(config.userManifestPath, manifest);
3049
+ if (config.registryKey)
3050
+ (0, import_node_child_process.execFileSync)("reg.exe", [
3051
+ "add",
3052
+ config.registryKey,
3053
+ "/ve",
3054
+ "/t",
3055
+ "REG_SZ",
3056
+ "/d",
3057
+ config.userManifestPath,
3058
+ "/f"
3059
+ ]);
3060
+ }
3061
+ function unregister(root, browser, extensionId) {
3062
+ const config = getBrowserConfig(browser);
3063
+ const manifest = readJson(config.userManifestPath);
3064
+ if (!manifest || manifest.path !== manifestFor(root, extensionId).path) return;
3065
+ if (config.registryKey) {
3066
+ let value = "";
3067
+ try {
3068
+ value = (0, import_node_child_process.execFileSync)("reg.exe", ["query", config.registryKey, "/ve"], {
3069
+ encoding: "utf8",
3070
+ stdio: ["ignore", "pipe", "ignore"]
3071
+ });
3072
+ } catch (error) {
3073
+ if (error.status !== 1) throw error;
3074
+ }
3075
+ const registeredPath = /REG_SZ\s+(.+)\s*$/.exec(value.trim())?.[1];
3076
+ if (registeredPath === config.userManifestPath)
3077
+ (0, import_node_child_process.execFileSync)("reg.exe", ["delete", config.registryKey, "/ve", "/f"]);
3078
+ }
3079
+ (0, import_node_fs4.rmSync)(config.userManifestPath);
3080
+ }
3081
+ function replaceDirectory(destination, prepare) {
3082
+ const staging = destination + ".staging-" + (0, import_node_crypto2.randomUUID)();
3083
+ const backup = destination + ".backup-" + (0, import_node_crypto2.randomUUID)();
3084
+ (0, import_node_fs4.mkdirSync)(staging);
3085
+ try {
3086
+ prepare(staging);
3087
+ if ((0, import_node_fs4.existsSync)(destination)) (0, import_node_fs4.renameSync)(destination, backup);
3088
+ try {
3089
+ (0, import_node_fs4.renameSync)(staging, destination);
3090
+ } catch (error) {
3091
+ if ((0, import_node_fs4.existsSync)(backup)) (0, import_node_fs4.renameSync)(backup, destination);
3092
+ throw error;
3093
+ }
3094
+ (0, import_node_fs4.rmSync)(backup, { recursive: true, force: true });
3095
+ } finally {
3096
+ (0, import_node_fs4.rmSync)(staging, { recursive: true, force: true });
3097
+ }
3098
+ }
3099
+ function installHost(destination) {
3100
+ (0, import_node_fs4.mkdirSync)(destination, { recursive: true, mode: 448 });
3101
+ const replace = (file, bytes, mode) => {
3102
+ const target = (0, import_node_path5.join)(destination, file);
3103
+ if ((0, import_node_fs4.existsSync)(target) && (0, import_node_fs4.readFileSync)(target).equals(bytes)) return;
3104
+ const staging = target + "." + (0, import_node_crypto2.randomUUID)() + ".tmp";
3105
+ try {
3106
+ (0, import_node_fs4.writeFileSync)(staging, bytes, { flag: "wx", mode });
3107
+ (0, import_node_fs4.renameSync)(staging, target);
3108
+ } finally {
3109
+ (0, import_node_fs4.rmSync)(staging, { force: true });
3110
+ }
3111
+ };
3112
+ for (const file of files) {
3113
+ const source = (0, import_node_path5.join)(__dirname, file);
3114
+ replace(file, (0, import_node_fs4.readFileSync)(source), (0, import_node_fs4.statSync)(source).mode & 511);
3115
+ if (file === "run_host.sh" && process.platform !== "win32")
3116
+ (0, import_node_fs4.chmodSync)((0, import_node_path5.join)(destination, file), 493);
3117
+ }
3118
+ replace("node_path.txt", Buffer.from(process.execPath + "\n"), 384);
3119
+ replaceDirectory(
3120
+ (0, import_node_path5.join)(destination, "recipes"),
3121
+ (staging) => (0, import_node_fs4.cpSync)((0, import_node_path5.join)(__dirname, "recipes"), staging, { recursive: true })
3122
+ );
3123
+ }
3124
+ async function manageInstallation(command, requestHost2) {
3125
+ const root = installationRoot();
3126
+ const recordPath = (0, import_node_path5.join)(root, "installation.json");
3127
+ const previous = readJson(recordPath);
3128
+ if (command.name === "uninstall") {
3129
+ if (!previous) return { installed: false };
3130
+ for (const browser2 of previous.browsers) unregister(root, browser2, previous.extensionId);
3131
+ const managedSkills = /* @__PURE__ */ new Set([
3132
+ ...Array.isArray(previous.skillPaths) ? previous.skillPaths : [],
3133
+ ...previous.skillPath ? [previous.skillPath] : []
3134
+ ]);
3135
+ for (const candidate of managedSkills) {
3136
+ const marker = readJson((0, import_node_path5.join)(candidate, ".browserpaw-skill.json"));
3137
+ if (marker?.name === "browserpaw") (0, import_node_fs4.rmSync)(candidate, { recursive: true, force: true });
3138
+ }
3139
+ for (const target of ["host", "extension"])
3140
+ (0, import_node_fs4.rmSync)((0, import_node_path5.join)(root, target), { recursive: true, force: true });
3141
+ (0, import_node_fs4.rmSync)(recordPath, { force: true });
3142
+ if (command.options.purge) {
3143
+ for (const target of [
3144
+ "tasks.json",
3145
+ "skills",
3146
+ "recipes",
3147
+ "learned-index.json",
3148
+ "out",
3149
+ "logs",
3150
+ "token",
3151
+ "host.json"
3152
+ ])
3153
+ (0, import_node_fs4.rmSync)((0, import_node_path5.join)(root, target), { recursive: true, force: true });
3154
+ }
3155
+ return { installed: false, dataPreserved: !command.options.purge };
3156
+ }
3157
+ if (command.name === "doctor") {
3158
+ if (command.options.fix && !previous) throw new Error("Run browserpaw setup first.");
3159
+ if (command.options.fix && previous) {
3160
+ for (const browser2 of previous.browsers) register(root, browser2, previous.extensionId);
3161
+ syncLearnedRouting(root);
3162
+ }
3163
+ const installedHost = (0, import_node_fs4.existsSync)((0, import_node_path5.join)(root, "host", "host.cjs"));
3164
+ const extension2 = (0, import_node_path5.join)(root, "extension");
3165
+ const host = await requestHost2("status", void 0, 4e3).then(async (response) => response.ok ? await response.json() : void 0).catch(() => void 0);
3166
+ const learnedCount = loadLearnedWorkflows(root, { includeCandidates: false }).length;
3167
+ return {
3168
+ installed: previous?.version,
3169
+ hostPresent: installedHost,
3170
+ extension: extension2,
3171
+ extensionPresent: (0, import_node_fs4.existsSync)((0, import_node_path5.join)(extension2, "manifest.json")),
3172
+ ...previous?.skillPath ? {
3173
+ skillPath: previous.skillPath,
3174
+ skillScope: previous.skillScope ?? "user",
3175
+ skillPresent: (0, import_node_fs4.existsSync)((0, import_node_path5.join)(previous.skillPath, "SKILL.md"))
3176
+ } : {},
3177
+ learnedHome: root,
3178
+ learnedCount,
3179
+ host,
3180
+ registeredBrowsers: previous?.browsers.map((browser2) => {
3181
+ const path5 = getBrowserConfig(browser2).userManifestPath;
3182
+ return {
3183
+ browser: browser2,
3184
+ path: path5,
3185
+ registered: readJson(path5)?.path === manifestFor(root, previous.extensionId).path
3186
+ };
3187
+ }) ?? [],
3188
+ next: !installedHost ? "Run browserpaw setup." : !host?.connected ? "Load the installed directory in chrome://extensions." : "Run browserpaw status."
3189
+ };
3190
+ }
3191
+ const browser = command.options.browser;
3192
+ if (browser !== void 0 && browser !== "chrome" && browser !== "chromium" && browser !== "all")
3193
+ throw new Error("Use --browser chrome, chromium, or all.");
3194
+ const browsers = browser === "all" ? ["chrome" /* CHROME */, "chromium" /* CHROMIUM */] : browser ? [browser] : previous?.browsers ?? ["chrome" /* CHROME */];
3195
+ const extensionSource = (0, import_node_path5.join)(__dirname, "extension");
3196
+ const extension = readJson((0, import_node_path5.join)(extensionSource, "manifest.json"));
3197
+ if (typeof extension?.key !== "string")
3198
+ throw new Error("Packaged extension is missing its public key.");
3199
+ const extensionId = (0, import_node_crypto2.createHash)("sha256").update(Buffer.from(extension.key, "base64")).digest("hex").slice(0, 32).replace(/[\da-f]/g, (char) => String.fromCharCode(97 + Number.parseInt(char, 16)));
3200
+ for (const browser2 of browsers) {
3201
+ const config = getBrowserConfig(browser2);
3202
+ const oldManifest = readJson(config.userManifestPath);
3203
+ if (oldManifest && oldManifest.path !== manifestFor(root, extensionId).path)
3204
+ throw new Error(`A different installation owns ${config.userManifestPath}.`);
3205
+ }
3206
+ (0, import_node_fs4.mkdirSync)(root, { recursive: true, mode: 448 });
3207
+ const { acquireLock, assertNoLinks: assertNoLinks2 } = require_cli_files();
3208
+ assertNoLinks2(root);
3209
+ const unlock = acquireLock((0, import_node_path5.join)(root, ".installation.lock"));
3210
+ try {
3211
+ const managedArtifactDirectory = (name) => {
3212
+ const directory = (0, import_node_path5.join)(root, name);
3213
+ if (name === "host") return files.some((file) => (0, import_node_fs4.existsSync)((0, import_node_path5.join)(directory, file)));
3214
+ try {
3215
+ return readJson((0, import_node_path5.join)(directory, "manifest.json"))?.name === "browserpaw";
3216
+ } catch {
3217
+ return false;
3218
+ }
3219
+ };
3220
+ for (const name of ["host", "extension"]) {
3221
+ const entry = (0, import_node_fs4.lstatSync)((0, import_node_path5.join)(root, name), { throwIfNoEntry: false });
3222
+ if (entry && (!entry.isDirectory() || entry.isSymbolicLink() || !previous && !managedArtifactDirectory(name)))
3223
+ throw new Error(
3224
+ `Existing directory is outside the managed installation: ${(0, import_node_path5.join)(root, name)}`
3225
+ );
3226
+ }
3227
+ let skillPath = previous?.skillPath;
3228
+ let skillScope = previous?.skillScope;
3229
+ const skillPaths = /* @__PURE__ */ new Set([
3230
+ ...Array.isArray(previous?.skillPaths) ? previous.skillPaths : [],
3231
+ ...previous?.skillPath ? [previous.skillPath] : []
3232
+ ]);
3233
+ const updatedSkillPaths = [];
3234
+ const requestedScope = typeof command.options["skill-scope"] === "string" ? command.options["skill-scope"] : void 0;
3235
+ const requestedDir = typeof command.options["skill-dir"] === "string" ? command.options["skill-dir"] : void 0;
3236
+ if (command.options["no-skill"] && (requestedScope || requestedDir)) {
3237
+ throw new Error("Do not combine --no-skill with --skill-scope or --skill-dir.");
3238
+ }
3239
+ const usesPluginSkill = previous?.skillMode === "plugin" && !requestedScope && !requestedDir;
3240
+ let skillMode = command.options["no-skill"] ? "disabled" : usesPluginSkill ? "plugin" : "managed";
3241
+ if (!command.options["no-skill"] && !usesPluginSkill) {
3242
+ const installedSkill = installSkill({
3243
+ force: true,
3244
+ version: CURRENT_VERSION,
3245
+ ...requestedScope ? { scope: requestedScope } : {},
3246
+ ...requestedDir ? { targetRoot: requestedDir } : !requestedScope && skillPath ? { targetRoot: (0, import_node_path5.dirname)(skillPath) } : {}
3247
+ });
3248
+ skillPath = installedSkill.installedPath;
3249
+ skillScope = requestedScope || requestedDir ? installedSkill.scope : previous?.skillScope ?? installedSkill.scope;
3250
+ skillMode = "managed";
3251
+ skillPaths.add(skillPath);
3252
+ updatedSkillPaths.push(skillPath);
3253
+ for (const candidate of skillPaths) {
3254
+ if (candidate !== skillPath && upgradeInstalledSkill(candidate, { version: CURRENT_VERSION })) {
3255
+ updatedSkillPaths.push(candidate);
3256
+ }
3257
+ }
3258
+ }
3259
+ const extensionTarget = (0, import_node_path5.join)(root, "extension");
3260
+ const manifestPath = (0, import_node_path5.join)(extensionTarget, "manifest.json");
3261
+ let hasValidManifest = false;
3262
+ if ((0, import_node_fs4.existsSync)(manifestPath)) {
3263
+ try {
3264
+ const parsed = JSON.parse((0, import_node_fs4.readFileSync)(manifestPath, "utf8"));
3265
+ hasValidManifest = parsed !== null && typeof parsed === "object" && typeof parsed.name === "string" && parsed.name.trim().length > 0;
3266
+ } catch {
3267
+ hasValidManifest = false;
3268
+ }
3269
+ }
3270
+ const extensionPrepared = !previous || !hasValidManifest;
3271
+ if (extensionPrepared) {
3272
+ replaceDirectory(
3273
+ extensionTarget,
3274
+ (target) => (0, import_node_fs4.cpSync)(extensionSource, target, { recursive: true })
3275
+ );
3276
+ }
3277
+ installHost((0, import_node_path5.join)(root, "host"));
3278
+ for (const browser2 of browsers) register(root, browser2, extensionId);
3279
+ for (const browser2 of previous?.browsers ?? []) {
3280
+ if (!browsers.includes(browser2)) unregister(root, browser2, previous.extensionId);
3281
+ }
3282
+ const routing = syncLearnedRouting(root, [...skillPaths]);
3283
+ writeJson(recordPath, {
3284
+ version: CURRENT_VERSION,
3285
+ browsers,
3286
+ skillMode,
3287
+ skillPath,
3288
+ skillScope,
3289
+ skillPaths: [...skillPaths],
3290
+ extensionId
3291
+ });
3292
+ const releaseAsset = `${GITHUB_REPO_URL}/releases/download/v${CURRENT_VERSION}/browserpaw-extension.zip`;
3293
+ return {
3294
+ installed: true,
3295
+ extension: (0, import_node_path5.join)(root, "extension"),
3296
+ extensionId,
3297
+ skillPath,
3298
+ updatedSkillPaths,
3299
+ ...skillScope ? { skillScope } : {},
3300
+ learnedHome: root,
3301
+ learnedCount: routing.workflowCount,
3302
+ extensionPrepared,
3303
+ ...previous && !extensionPrepared ? { releaseAsset } : {},
3304
+ next: extensionPrepared ? "Open chrome://extensions, enable Developer mode, then load the installed extension directory." : "If the extension version differs, download and unpack the release ZIP from releaseAsset. Load it in chrome://extensions or reload after replacing the files in the loaded directory. Reload an already matching extension to reconnect the host, then run browserpaw status."
3305
+ };
3306
+ } finally {
3307
+ unlock();
3308
+ }
3309
+ }
3310
+ var import_node_crypto2, import_node_child_process, import_node_fs4, import_node_os3, import_node_path5, installationRoot, files;
3311
+ var init_cli_setup = __esm({
3312
+ "src/cli-setup.ts"() {
3313
+ "use strict";
3314
+ import_node_crypto2 = require("crypto");
3315
+ import_node_child_process = require("child_process");
3316
+ import_node_fs4 = require("fs");
3317
+ import_node_os3 = require("os");
3318
+ import_node_path5 = require("path");
3319
+ init_dist();
3320
+ init_browser_config();
3321
+ init_skill_install();
3322
+ init_learned_recipes();
3323
+ installationRoot = () => (0, import_node_path5.resolve)(process.env.BROWSERPAW_HOME || (0, import_node_path5.join)((0, import_node_os3.homedir)(), ".browserpaw"));
3324
+ files = ["host.cjs", "run_host.bat", "run_host.sh"];
3325
+ }
3326
+ });
3327
+
3328
+ // src/command-client.ts
3329
+ var import_node_crypto3 = require("crypto");
3330
+ var import_promises2 = require("fs/promises");
3331
+ var import_node_fs5 = require("fs");
3332
+ var import_node_os4 = require("os");
3333
+ var import_node_path6 = require("path");
3334
+ init_dist();
3335
+
3336
+ // src/cli-update.ts
3337
+ var import_node_fs3 = require("fs");
3338
+ var import_node_path3 = require("path");
3339
+ init_dist();
3340
+ init_learned_recipes();
3341
+ var registryUrl = "https://registry.npmjs.org/browserpaw/latest";
3342
+ var checkInterval = 24 * 60 * 60 * 1e3;
3343
+ var stableVersion = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/;
3344
+ async function checkForCliUpdate() {
3345
+ if (process.env.BROWSERPAW_NO_UPDATE_CHECK === "1") return;
3346
+ const root = browserPawHome();
3347
+ const statePath = (0, import_node_path3.join)(root, "cli-update.json");
3348
+ const { ensureDirectory, acquireLock, readJson: readJson2, atomicWrite } = require_cli_files();
3349
+ try {
3350
+ ensureDirectory(root);
3351
+ const unlock = acquireLock((0, import_node_path3.join)(root, ".cli-update.lock"));
3352
+ try {
3353
+ let state;
3354
+ try {
3355
+ state = readJson2(statePath);
3356
+ } catch (error) {
3357
+ if (!(error instanceof SyntaxError)) throw error;
3358
+ const backup = `${statePath}.corrupt.${Date.now()}-${process.pid}`;
3359
+ (0, import_node_fs3.renameSync)(statePath, backup);
3360
+ console.error(
3361
+ `BrowserPaw update state was corrupt; moved it to ${backup} and started from empty state.`
3362
+ );
3363
+ state = void 0;
3364
+ }
3365
+ const notified = Array.isArray(state?.notified) ? state.notified : [];
3366
+ const now = Date.now();
3367
+ const age = now - (state?.checkedAt ?? NaN);
3368
+ const check = !(age >= 0 && age < checkInterval);
3369
+ let latest = state?.latest;
3370
+ if (check) {
3371
+ latest = await fetch(registryUrl, { redirect: "error", signal: AbortSignal.timeout(1e3) }).then(async (response) => {
3372
+ if (!response.ok) return void 0;
3373
+ const manifest = await response.json();
3374
+ const repository = manifest?.repository?.url;
3375
+ if (manifest?.name !== "browserpaw" || typeof repository !== "string" || repository.replace(/^git\+/, "").replace(/\.git$/, "") !== GITHUB_REPO_URL)
3376
+ return;
3377
+ const version = manifest.version;
3378
+ if (typeof version === "string" && stableVersion.test(version)) return version;
3379
+ }).catch(() => void 0);
3380
+ }
3381
+ const shouldNotify = typeof latest === "string" && stableVersion.test(latest) && isNewerVersion(latest, CURRENT_VERSION) && !notified.includes(latest);
3382
+ if (check || shouldNotify) {
3383
+ atomicWrite(
3384
+ statePath,
3385
+ JSON.stringify({
3386
+ checkedAt: check ? now : state?.checkedAt,
3387
+ latest,
3388
+ notified: shouldNotify ? [...notified, latest] : notified
3389
+ }) + "\n"
3390
+ );
3391
+ }
3392
+ return shouldNotify ? latest : void 0;
3393
+ } finally {
3394
+ unlock();
3395
+ }
3396
+ } catch {
3397
+ return void 0;
3398
+ }
3399
+ }
3400
+
3401
+ // src/server/token.ts
3402
+ var os3 = __toESM(require("os"));
3403
+ var fs3 = __toESM(require("fs"));
3404
+ var path3 = __toESM(require("path"));
3405
+ var crypto = __toESM(require("crypto"));
3406
+ var TOKEN_DIR = path3.resolve(
3407
+ process.env.BROWSERPAW_HOME || path3.join(os3.homedir(), ".browserpaw")
3408
+ );
3409
+ var TOKEN_FILE = path3.join(TOKEN_DIR, "token");
3410
+ var TOKEN_PATTERN = /^[0-9a-fA-F]{48}$|^[0-9a-fA-F]{64}$/;
3411
+ function isValidTokenFormat(token) {
3412
+ return typeof token === "string" && TOKEN_PATTERN.test(token.trim());
3413
+ }
3414
+ function readBridgeToken() {
3415
+ let content;
3416
+ try {
3417
+ content = fs3.readFileSync(TOKEN_FILE, "utf8");
3418
+ } catch (err) {
3419
+ throw new Error("Bridge token not found or unreadable at " + TOKEN_FILE + ": " + err.message);
3420
+ }
3421
+ const trimmed = content.trim();
3422
+ if (!isValidTokenFormat(trimmed)) {
3423
+ throw new Error("Corrupt bridge token in " + TOKEN_FILE + ": format invalid");
3424
+ }
3425
+ return trimmed;
3426
+ }
3427
+
3428
+ // src/output-retention.ts
3429
+ var import_promises = require("fs/promises");
3430
+ var import_node_path4 = require("path");
3431
+ var uuid = /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i;
3432
+ var managedFile = /^(?:result\.json|bookmarks|item-[1-9]\d*\.(?:bin|jpg|png|txt|webp))$/;
3433
+ var day = 24 * 60 * 60 * 1e3;
3434
+ async function pruneOutput(root, current, now = Date.now()) {
3435
+ const { assertNoLinks: assertNoLinks2, readJson: readJson2 } = require_cli_files();
3436
+ assertNoLinks2(root);
3437
+ const ledger = readJson2((0, import_node_path4.join)((0, import_node_path4.dirname)(root), "tasks.json"));
3438
+ const active = ledger?.tasks ?? {};
3439
+ const requests = [];
3440
+ for (const bucket of await (0, import_promises.readdir)(root, { withFileTypes: true })) {
3441
+ if (!bucket.isDirectory() || bucket.name !== "misc" && !uuid.test(bucket.name)) continue;
3442
+ const directory = (0, import_node_path4.join)(root, bucket.name);
3443
+ if (bucket.name !== "misc" && (directory === (0, import_node_path4.dirname)(current) || active[bucket.name]?.status === "active" || active[bucket.name]?.status === "paused"))
3444
+ continue;
3445
+ assertNoLinks2(directory);
3446
+ const children = await (0, import_promises.readdir)(directory, { withFileTypes: true }).catch(() => []);
3447
+ for (const request of children) {
3448
+ if (!request.isDirectory() || !uuid.test(request.name)) continue;
3449
+ const path5 = (0, import_node_path4.join)(directory, request.name);
3450
+ if (path5 === current) continue;
3451
+ const stat = await (0, import_promises.lstat)(path5).catch(() => void 0);
3452
+ if (stat?.isDirectory()) requests.push({ bucket: directory, path: path5, mtimeMs: stat.mtimeMs });
3453
+ }
3454
+ }
3455
+ requests.sort((left, right) => right.mtimeMs - left.mtimeMs);
3456
+ for (const [index, request] of requests.entries()) {
3457
+ const age = now - request.mtimeMs;
3458
+ if (age <= 7 * day && (index < 200 || age < 10 * 60 * 1e3)) continue;
3459
+ assertNoLinks2(request.path);
3460
+ const files2 = await (0, import_promises.readdir)(request.path, { withFileTypes: true }).catch(() => void 0);
3461
+ if (!files2?.every((file) => file.isFile() && managedFile.test(file.name))) continue;
3462
+ for (const file of files2) await (0, import_promises.unlink)((0, import_node_path4.join)(request.path, file.name)).catch(() => {
3463
+ });
3464
+ await (0, import_promises.rmdir)(request.path).catch(() => {
3465
+ });
3466
+ await (0, import_promises.rmdir)(request.bucket).catch(() => {
3467
+ });
3468
+ }
3469
+ }
3470
+
3471
+ // src/command-client.ts
3472
+ var outputRoot = () => (0, import_node_path6.resolve)(process.env.BROWSERPAW_HOME || (0, import_node_path6.join)((0, import_node_os4.homedir)(), ".browserpaw"), "out");
3473
+ function resultData(result) {
3474
+ if (result.structuredContent) return result.structuredContent;
3475
+ for (const block of result.content ?? []) {
3476
+ if (block.type !== "text" || typeof block.text !== "string" || !block.text.startsWith("{"))
3477
+ continue;
3478
+ try {
3479
+ const data = JSON.parse(block.text);
3480
+ if (data && typeof data === "object" && !Array.isArray(data)) return data;
3481
+ } catch {
3482
+ continue;
3483
+ }
3484
+ }
3485
+ }
3486
+ async function requestHost(route, body, timeout = 36e4, signal) {
3487
+ const configuration = await (0, import_promises2.readFile)((0, import_node_path6.resolve)(outputRoot(), "..", "host.json"), "utf8").then((value) => JSON.parse(value)).catch((error) => {
3488
+ if (error.code !== "ENOENT") throw error;
3489
+ return {};
3490
+ });
3491
+ const port = Number(process.env.BROWSERPAW_PORT || configuration.port || DEFAULT_SERVER_PORT);
3492
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
3493
+ throw new Error("Invalid BROWSERPAW_PORT.");
3494
+ const timeLimit = AbortSignal.timeout(timeout);
3495
+ return fetch(`http://127.0.0.1:${port}/v1/${route}`, {
3496
+ method: body ? "POST" : "GET",
3497
+ redirect: "error",
3498
+ headers: {
3499
+ "x-browserpaw-token": readBridgeToken(),
3500
+ ...body ? { "content-type": "application/json" } : {}
3501
+ },
3502
+ ...body ? { body: JSON.stringify(body) } : {},
3503
+ signal: signal ? AbortSignal.any([signal, timeLimit]) : timeLimit
3504
+ });
3505
+ }
3506
+ function writeReceipt(result, json) {
3507
+ if (!json && !result.ok) {
3508
+ const error = result.error;
3509
+ console.error([error.message, error.hint].filter(Boolean).join("\n"));
3510
+ if (result.data) console.log(JSON.stringify(result.data, null, 2));
3511
+ return;
3512
+ }
3513
+ console.log(JSON.stringify(json ? result : result.data, null, json ? void 0 : 2));
3514
+ }
3515
+ function receiptDirectory(command, requestId) {
3516
+ return (0, import_node_path6.join)(
3517
+ outputRoot(),
3518
+ typeof command.options.task === "string" && /^[a-f0-9-]{36}$/i.test(command.options.task) ? command.options.task : "misc",
3519
+ requestId
3520
+ );
3521
+ }
3522
+ async function saveOutput(result, command, requestId) {
3523
+ const directory = receiptDirectory(command, requestId);
3524
+ const { ensureDirectory, atomicWrite, assertNoLinks: assertNoLinks2 } = require_cli_files();
3525
+ const rawPath = (0, import_node_path6.join)(directory, "result.json");
3526
+ const raw = JSON.stringify(result) + "\n";
3527
+ const saveRaw = () => {
3528
+ ensureDirectory(directory);
3529
+ atomicWrite(rawPath, raw);
3530
+ return rawPath;
3531
+ };
3532
+ let resultPath = raw.length > 8e3 || command.name === "screenshot" ? saveRaw() : void 0;
3533
+ let artifactNumber = 0;
3534
+ const references = /* @__PURE__ */ new Map();
3535
+ function save(block, bytes, stamp, extension) {
3536
+ if (references.has(stamp)) return references.get(stamp);
3537
+ ensureDirectory(directory);
3538
+ const path5 = (0, import_node_path6.join)(directory, `item-${++artifactNumber}${extension}`);
3539
+ atomicWrite(path5, bytes);
3540
+ const reference = {
3541
+ type: "artifact_ref",
3542
+ originalType: block.type,
3543
+ path: path5,
3544
+ mimeType: block.mimeType,
3545
+ bytes: bytes.length,
3546
+ sha256: (0, import_node_crypto3.createHash)("sha256").update(bytes).digest("hex")
3547
+ };
3548
+ references.set(stamp, reference);
3549
+ return reference;
3550
+ }
3551
+ function discover(value) {
3552
+ if (Array.isArray(value)) {
3553
+ value.forEach(discover);
3554
+ return;
3555
+ }
3556
+ if (!value || typeof value !== "object") return;
3557
+ const item = value;
3558
+ const data2 = item.type === "image" || item.type === "audio" ? item.data : item.type === "resource" ? item.resource?.blob : void 0;
3559
+ if (typeof data2 === "string") {
3560
+ const mimeType = item.mimeType ?? item.resource?.mimeType;
3561
+ const extension = mimeType === "image/png" ? ".png" : mimeType === "image/jpeg" ? ".jpg" : mimeType === "image/webp" ? ".webp" : mimeType?.startsWith("text/") ? ".txt" : ".bin";
3562
+ const bytes = Buffer.from(data2, "base64");
3563
+ if (bytes.toString("base64") !== data2) throw new Error("Invalid media in browser receipt.");
3564
+ save({ ...item, mimeType }, bytes, data2, extension);
3565
+ return;
3566
+ }
3567
+ Object.values(value).forEach(discover);
3568
+ }
3569
+ if (command.name === "bookmark export" && !result.isError && typeof command.options.out === "string") {
3570
+ const body = result.content?.find((block) => block.type === "text")?.text;
3571
+ if (!body) throw new Error("Browser did not return a bookmark export.");
3572
+ const target = (0, import_node_path6.resolve)(command.options.out);
3573
+ ensureDirectory((0, import_node_path6.dirname)(target));
3574
+ const temp = (0, import_node_path6.join)(directory, "bookmarks");
3575
+ ensureDirectory(directory);
3576
+ atomicWrite(temp, body);
3577
+ await (0, import_promises2.copyFile)(temp, target, import_node_fs5.constants.COPYFILE_EXCL);
3578
+ return { ...resultData(result), outputPath: target, bytes: Buffer.byteLength(body) };
3579
+ }
3580
+ discover(result);
3581
+ function compact(value) {
3582
+ if (Array.isArray(value)) return value.map(compact);
3583
+ if (value && typeof value === "object") {
3584
+ const item = value;
3585
+ const payload = item.data ?? item.resource?.blob;
3586
+ if (payload && references.has(payload)) return references.get(payload);
3587
+ return Object.fromEntries(Object.entries(value).map(([key, part]) => [key, compact(part)]));
3588
+ }
3589
+ if (typeof value !== "string") return value;
3590
+ if (references.has(value)) return references.get(value);
3591
+ const max = typeof command.options["max-chars"] === "string" ? Math.min(Number(command.options["max-chars"]), 3e4) : 8e3;
3592
+ if (value.length > max)
3593
+ return save({ type: "text", mimeType: "text/plain" }, Buffer.from(value), value, ".txt");
3594
+ for (const [payload, reference] of references) {
3595
+ if (payload && value.includes(payload))
3596
+ return value.split(payload).join(`[file: ${reference.path}]`);
3597
+ }
3598
+ return value;
3599
+ }
3600
+ const data = resultData(result);
3601
+ const content = result.content?.filter((block, index) => {
3602
+ if (!data || index !== 0 || block.type !== "text") return true;
3603
+ try {
3604
+ return JSON.stringify(JSON.parse(block.text ?? "")) !== JSON.stringify(data);
3605
+ } catch {
3606
+ return true;
3607
+ }
3608
+ });
3609
+ const view = compact({ ...data, ...content?.length ? { content } : {} });
3610
+ if (["screenshot", "network show", "pdf", "perf trace"].includes(command.name) && typeof command.options.out === "string" && !result.isError && data?.success !== false) {
3611
+ let source;
3612
+ if (command.name === "screenshot" || command.name === "network show") {
3613
+ const type = command.name === "screenshot" ? "image" : "resource";
3614
+ const file = [...references.values()].find((item) => item.originalType === type);
3615
+ if (!file)
3616
+ throw new Error(
3617
+ `Browser did not return a captured ${type === "image" ? "image" : "response body"}.`
3618
+ );
3619
+ source = String(file.path);
3620
+ } else {
3621
+ const file = data?.file;
3622
+ if (typeof file?.path !== "string")
3623
+ throw new Error("Browser did not return a trace or PDF file.");
3624
+ source = (0, import_node_path6.resolve)(file.path);
3625
+ const inside = (0, import_node_path6.relative)((0, import_node_path6.join)((0, import_node_os4.tmpdir)(), "chrome-mcp-uploads"), source);
3626
+ const expected = command.name === "pdf" ? ".pdf" : ".json";
3627
+ if (!inside || inside === ".." || inside.startsWith(".." + import_node_path6.sep) || (0, import_node_path6.isAbsolute)(inside) || (0, import_node_path6.extname)(source) !== expected)
3628
+ throw new Error("Browser output is outside the Native temporary files.");
3629
+ assertNoLinks2(source);
3630
+ if (!(await (0, import_promises2.lstat)(source)).isFile())
3631
+ throw new Error("Browser output must be a regular file.");
3632
+ }
3633
+ const target = (0, import_node_path6.resolve)(command.options.out);
3634
+ ensureDirectory((0, import_node_path6.dirname)(target));
3635
+ await (0, import_promises2.copyFile)(source, target, import_node_fs5.constants.COPYFILE_EXCL);
3636
+ view.outputPath = target;
3637
+ }
3638
+ if (artifactNumber || JSON.stringify(view).length > 3e4) {
3639
+ resultPath ??= saveRaw();
3640
+ if (JSON.stringify(view).length > 3e4) {
3641
+ return {
3642
+ resultPath,
3643
+ artifacts: [...references.values()].slice(0, 12),
3644
+ ...view.outputPath ? { outputPath: view.outputPath } : {},
3645
+ ...view.captureId ? { captureId: view.captureId } : {},
3646
+ ...view.task ? { task: view.task } : {}
3647
+ };
3648
+ }
3649
+ }
3650
+ if (resultPath) view.resultPath = resultPath;
3651
+ return view;
3652
+ }
3653
+ async function inputFor(command) {
3654
+ const file = command.name === "batch" || command.name === "recipe save" ? command.operands[0] : command.name === "fill" ? command.options.input : command.name === "eval" ? command.options.file : void 0;
3655
+ if (typeof file !== "string") return void 0;
3656
+ const data = file === "-" ? await readStdin() : await (0, import_promises2.readFile)(file, "utf8");
3657
+ if (command.name === "eval" || command.name === "fill") return data;
3658
+ try {
3659
+ return JSON.parse(data);
3660
+ } catch {
3661
+ throw new Error("Input is not valid JSON.");
3662
+ }
3663
+ }
3664
+ async function readStdin() {
3665
+ let text = "";
3666
+ process.stdin.setEncoding("utf8");
3667
+ for await (const chunk of process.stdin) {
3668
+ text += chunk;
3669
+ if (text.length > 8 * 1024 * 1024) throw new Error("Input is too large.");
3670
+ }
3671
+ return text;
3672
+ }
3673
+ async function runCommands(inputArgs) {
3674
+ const argv = inputArgs.slice();
3675
+ if (argv[0] === "--json") {
3676
+ argv.shift();
3677
+ const end = argv.indexOf("--");
3678
+ argv.splice(end === -1 ? argv.length : end, 0, "--json");
3679
+ }
3680
+ let json = argv.slice(0, argv.indexOf("--") === -1 ? void 0 : argv.indexOf("--")).includes("--json");
3681
+ let command;
3682
+ let accepted = false;
3683
+ let knownResult;
3684
+ let update;
3685
+ const controller = new AbortController();
3686
+ const requestId = (0, import_node_crypto3.randomUUID)();
3687
+ const interrupt = () => {
3688
+ if (!accepted) return;
3689
+ void requestHost("cancel", { requestId }, 1500).catch(() => {
3690
+ }).finally(() => controller.abort());
3691
+ };
3692
+ const failure = (code, errorCode, message, data) => {
3693
+ const receipt = knownResult ? resultData(knownResult) : void 0;
3694
+ const status = code === 4 ? "unknown" : receipt?.status === "blocked" || ["busy", "extension_disconnected", "host_unavailable"].includes(errorCode) ? "blocked" : receipt?.status === "cancelled" ? "cancelled" : "failed";
3695
+ const requestDispatched = typeof receipt?.requestDispatched === "boolean" ? receipt.requestDispatched : !accepted || code === 2 || code === 3 || errorCode === "busy" ? false : knownResult && status !== "blocked" ? true : null;
3696
+ writeReceipt(
3697
+ {
3698
+ ok: false,
3699
+ command: command?.name ?? argv[0],
3700
+ requestId,
3701
+ outcome: code === 4 ? "unknown" : "failed",
3702
+ status,
3703
+ requestDispatched,
3704
+ ...command?.options.task ? { taskId: command.options.task } : {},
3705
+ ...command?.options.tab ? { tabId: Number(command.options.tab) } : {},
3706
+ ...data === void 0 ? {} : { data },
3707
+ error: {
3708
+ code: errorCode,
3709
+ message,
3710
+ retry: false,
3711
+ ...code === 4 ? { hint: "Observe the page or check task status before acting again." } : code === 3 ? { hint: "Run browserpaw status and check the BrowserPaw extension." } : {}
3712
+ }
3713
+ },
3714
+ json
3715
+ );
3716
+ return code;
3717
+ };
3718
+ try {
3719
+ if (!argv.length || argv[0] === "--help" || argv[0] === "-h") {
3720
+ console.log(commandHelp());
3721
+ return 0;
3722
+ }
3723
+ if (argv[0] === "--version" || argv[0] === "-V") {
3724
+ console.log(CURRENT_VERSION);
3725
+ return 0;
3726
+ }
3727
+ const terminator = argv.indexOf("--");
3728
+ const flags = argv.slice(0, terminator < 0 ? void 0 : terminator);
3729
+ if (flags.includes("--help") || flags.includes("-h") || argv[0] === "help") {
3730
+ const topic = flags.filter((arg) => !["help", "--help", "-h", "--json"].includes(arg)).join(" ");
3731
+ console.log(commandHelp(topic || void 0));
3732
+ return 0;
3733
+ }
3734
+ command = parseCommand(argv);
3735
+ json = command.options.json === true;
3736
+ if (command.name === "search") {
3737
+ const { options, operands } = command;
3738
+ const query = operands.join(" ").trim();
3739
+ if (!query)
3740
+ return failure(2, "invalid_arguments", "Provide keywords. Run browserpaw help search.");
3741
+ if (options.task || options.tab || options.frame)
3742
+ return failure(2, "invalid_arguments", "Command search does not accept a page or task.");
3743
+ const limit = options.limit === void 0 ? 8 : Number(options.limit);
3744
+ if (options.limit !== void 0 && !/^\d+$/.test(String(options.limit)) || !Number.isInteger(limit) || limit < 1 || limit > 50)
3745
+ return failure(2, "invalid_arguments", "--limit must be an integer from 1 to 50.");
3746
+ const matches = searchCommands(query);
3747
+ const items = matches.slice(0, limit);
3748
+ if (json)
3749
+ writeReceipt(
3750
+ {
3751
+ ok: true,
3752
+ command: "search",
3753
+ outcome: "done",
3754
+ data: { query, totalMatches: matches.length, items }
3755
+ },
3756
+ true
3757
+ );
3758
+ else if (!items.length)
3759
+ console.log("No matching commands. Try another keyword or run browserpaw help.");
3760
+ else {
3761
+ console.log(
3762
+ items.map(
3763
+ ({ usage, summary, example }) => [usage, ` ${summary}`, ...example ? [` Example: ${example}`] : []].join("\n")
3764
+ ).join("\n\n")
3765
+ );
3766
+ if (items.length < matches.length)
3767
+ console.log(
3768
+ `
3769
+ Showing ${items.length} of ${matches.length} matches. Refine the query or increase --limit.`
3770
+ );
3771
+ }
3772
+ return 0;
3773
+ }
3774
+ if (command.name !== "setup" && command.name !== "uninstall") update = checkForCliUpdate();
3775
+ if (!command.options.task && !command.options.tab && !(command.name === "task status" && command.operands.length) && process.env.BROWSERPAW_TASK && !isProfileCommand(command.name) && ![
3776
+ "task start",
3777
+ "task list",
3778
+ "tab close",
3779
+ "status",
3780
+ "doctor",
3781
+ "setup",
3782
+ "uninstall",
3783
+ "recipe list",
3784
+ "recipe find",
3785
+ "recipe show",
3786
+ "recipe save",
3787
+ "recipe patch",
3788
+ "recipe validate",
3789
+ "recipe rm"
3790
+ ].includes(command.name)) {
3791
+ const end = argv.indexOf("--");
3792
+ argv.splice(end === -1 ? argv.length : end, 0, "--task", process.env.BROWSERPAW_TASK);
3793
+ command = parseCommand(argv);
3794
+ }
3795
+ if (["recipe list", "recipe find", "recipe show"].includes(command.name)) {
3796
+ const { browserPawHome: browserPawHome2, findLearnedWorkflows: findLearnedWorkflows2, listLearnedWorkflows: listLearnedWorkflows2, showLearnedWorkflow: showLearnedWorkflow2 } = await Promise.resolve().then(() => (init_learned_recipes(), learned_recipes_exports));
3797
+ const homeDir = browserPawHome2();
3798
+ if (command.name === "recipe list") {
3799
+ if (command.operands.length)
3800
+ return failure(
3801
+ 2,
3802
+ "invalid_arguments",
3803
+ "Usage: browserpaw recipe list [--url URL] [--query TEXT] [--all]."
3804
+ );
3805
+ const url = typeof command.options.url === "string" ? command.options.url : void 0;
3806
+ const query = typeof command.options.query === "string" ? command.options.query : void 0;
3807
+ writeReceipt(
3808
+ {
3809
+ ok: true,
3810
+ command: command.name,
3811
+ outcome: "done",
3812
+ data: listLearnedWorkflows2(homeDir, {
3813
+ includeCandidates: Boolean(command.options.all),
3814
+ url,
3815
+ query
3816
+ })
3817
+ },
3818
+ json
3819
+ );
3820
+ return 0;
3821
+ }
3822
+ if (command.name === "recipe find") {
3823
+ const url = typeof command.options.url === "string" ? command.options.url : void 0;
3824
+ const query = command.operands.join(" ").trim();
3825
+ writeReceipt(
3826
+ {
3827
+ ok: true,
3828
+ command: command.name,
3829
+ outcome: "done",
3830
+ data: findLearnedWorkflows2(homeDir, {
3831
+ includeCandidates: Boolean(command.options.all),
3832
+ url,
3833
+ query
3834
+ })
3835
+ },
3836
+ json
3837
+ );
3838
+ return 0;
3839
+ }
3840
+ if (command.operands.length !== 1)
3841
+ return failure(2, "invalid_arguments", "Usage: browserpaw recipe show ID.");
3842
+ const inspected = showLearnedWorkflow2(command.operands[0], homeDir);
3843
+ if (!inspected)
3844
+ return failure(
3845
+ 1,
3846
+ "recipe_not_found",
3847
+ `Unknown learned skill or recipe: ${command.operands[0]}.`
3848
+ );
3849
+ writeReceipt(
3850
+ {
3851
+ ok: true,
3852
+ command: command.name,
3853
+ outcome: "done",
3854
+ data: { ...inspected.summary, definition: inspected.definition }
3855
+ },
3856
+ json
3857
+ );
3858
+ return 0;
3859
+ }
3860
+ if (["setup", "uninstall", "doctor"].includes(command.name)) {
3861
+ if (command.operands.length)
3862
+ return failure(2, "invalid_arguments", "Unexpected command operands.");
3863
+ const { manageInstallation: manageInstallation2 } = await Promise.resolve().then(() => (init_cli_setup(), cli_setup_exports));
3864
+ const data2 = await manageInstallation2(command, requestHost);
3865
+ writeReceipt({ ok: true, command: command.name, outcome: "done", data: data2 }, json);
3866
+ return 0;
3867
+ }
3868
+ if (command.name === "status") {
3869
+ if (command.operands.length)
3870
+ return failure(2, "invalid_arguments", "Usage: browserpaw status.");
3871
+ const response2 = await requestHost("status", void 0, 4e3);
3872
+ if (!response2.ok) return failure(3, "host_unavailable", "Cannot read the local host status.");
3873
+ const data2 = await response2.json();
3874
+ if (!data2.connected)
3875
+ return failure(3, "extension_disconnected", "The extension is disconnected.", data2);
3876
+ const extension = data2.extension;
3877
+ if (data2.version === CURRENT_VERSION && typeof extension?.manifestVersion !== "string")
3878
+ return failure(
3879
+ 3,
3880
+ "extension_status_unavailable",
3881
+ "Could not read extension diagnostics.",
3882
+ data2
3883
+ );
3884
+ if (data2.version !== CURRENT_VERSION || extension?.manifestVersion !== CURRENT_VERSION) {
3885
+ return failure(
3886
+ 3,
3887
+ "version_mismatch",
3888
+ `BrowserPaw requires the ${CURRENT_VERSION} host and extension. Run setup with the matching CLI to update the host and Skill. For a mismatched extension, manually install ${GITHUB_REPO_URL}/releases/download/v${CURRENT_VERSION}/browserpaw-extension.zip and reload it.`,
3889
+ data2
3890
+ );
3891
+ }
3892
+ const syncDir = !process.env.BROWSERPAW_HOME && process.env.BROWSERPAW_EXTENSION_SYNC_DIR?.trim() ? (0, import_node_path6.resolve)(process.env.BROWSERPAW_EXTENSION_SYNC_DIR) : void 0;
3893
+ const extensionDir = syncDir ?? (0, import_node_path6.resolve)(outputRoot(), "..", "extension");
3894
+ const readExtensionJson = (file) => (0, import_promises2.readFile)((0, import_node_path6.join)(extensionDir, file), "utf8").then((value) => JSON.parse(value)).catch((error) => {
3895
+ if (error.code !== "ENOENT") throw error;
3896
+ return void 0;
3897
+ });
3898
+ const localManifest = await readExtensionJson("manifest.json");
3899
+ const localBuild = localManifest?.version === CURRENT_VERSION ? await readExtensionJson("browserpaw-build.json") : void 0;
3900
+ if (localBuild?.buildId && localBuild.buildId !== extension?.buildId)
3901
+ return failure(
3902
+ 3,
3903
+ "build_mismatch",
3904
+ "Reload the installed BrowserPaw extension in chrome://extensions.",
3905
+ data2
3906
+ );
3907
+ writeReceipt({ ok: true, command: command.name, outcome: "done", data: data2 }, json);
3908
+ return 0;
3909
+ }
3910
+ if (command.name === "upload") {
3911
+ const paths = command.operands.slice(1).map((file) => (0, import_node_path6.resolve)(file));
3912
+ const global = Object.entries(command.options).flatMap(
3913
+ ([key, value]) => value === true ? ["--" + key] : ["--" + key, String(value)]
3914
+ );
3915
+ argv.splice(0, argv.length, "upload", ...global, "--", command.operands[0], ...paths);
3916
+ }
3917
+ if (command.name === "download" && typeof command.options.out === "string") {
3918
+ const out = (0, import_node_path6.resolve)(command.options.out);
3919
+ const index = argv.findIndex((token) => token === "--out" || token.startsWith("--out="));
3920
+ if (argv[index] === "--out") argv[index + 1] = out;
3921
+ else argv[index] = "--out=" + out;
3922
+ }
3923
+ const input = await inputFor(command);
3924
+ process.once("SIGINT", interrupt);
3925
+ accepted = true;
3926
+ const response = await requestHost(
3927
+ "run",
3928
+ { requestId, argv, input },
3929
+ 36e4,
3930
+ controller.signal
3931
+ );
3932
+ const body = await response.json();
3933
+ if (!response.ok)
3934
+ return failure(
3935
+ response.status === 400 ? 2 : response.status >= 500 ? 4 : response.status === 409 ? 1 : 3,
3936
+ body.code ?? "host_error",
3937
+ body.message ?? `Host returned HTTP ${response.status}.`
3938
+ );
3939
+ if (!body.result || !Array.isArray(body.result.content))
3940
+ throw new Error("Invalid local host receipt.");
3941
+ const result = knownResult = body.result;
3942
+ const data = resultData(result);
3943
+ const errorText = typeof data?.error === "string" ? data.error : String(
3944
+ result.content?.find((block) => block.type === "text")?.text ?? "Browser operation failed."
3945
+ );
3946
+ let view;
3947
+ try {
3948
+ view = await saveOutput(result, command, requestId);
3949
+ } catch (error) {
3950
+ if (!(result.isError || data?.ok === false || data?.success === false)) throw error;
3951
+ view = { ...data, outputError: error instanceof Error ? error.message : String(error) };
3952
+ }
3953
+ if (data?.status === "unknown" || data?.outcome === "unknown" || data?.requestDispatched === true && data?.status === "cancelled")
3954
+ return failure(4, "outcome_unknown", errorText.slice(0, 500), view);
3955
+ if (result.isError || data?.ok === false || data?.success === false)
3956
+ return failure(
3957
+ data?.code === "extension_disconnected" || /extension is not connected/i.test(errorText) ? 3 : 1,
3958
+ String(data?.code ?? data?.status ?? "command_failed"),
3959
+ errorText.slice(0, 500),
3960
+ view
3961
+ );
3962
+ writeReceipt(
3963
+ {
3964
+ ok: true,
3965
+ command: command.name,
3966
+ requestId,
3967
+ outcome: "done",
3968
+ ...command.options.task ? { taskId: command.options.task } : {},
3969
+ ...data?.tabId ?? command.options.tab ? { tabId: Number(data?.tabId ?? command.options.tab) } : {},
3970
+ data: view
3971
+ },
3972
+ json
3973
+ );
3974
+ return 0;
3975
+ } catch (error) {
3976
+ const message = error instanceof Error ? error.message : String(error);
3977
+ if (knownResult && command) {
3978
+ const resultPath = (0, import_node_path6.join)(receiptDirectory(command, requestId), "result.json");
3979
+ const saved = await (0, import_promises2.access)(resultPath).then(
3980
+ () => true,
3981
+ () => false
3982
+ );
3983
+ const outcome = resultData(knownResult)?.status;
3984
+ return failure(outcome === "unknown" ? 4 : 1, "output_failed", message, {
3985
+ ...saved ? { resultPath } : {},
3986
+ ...outcome ? { browserStatus: outcome } : {}
3987
+ });
3988
+ }
3989
+ if (!accepted)
3990
+ return failure(
3991
+ command?.name === "status" ? 3 : command ? 1 : 2,
3992
+ command ? "local_error" : "invalid_arguments",
3993
+ message
3994
+ );
3995
+ const cause = error.cause?.code;
3996
+ if (cause === "ECONNREFUSED" || /bridge token/i.test(message))
3997
+ return failure(3, "host_unavailable", message);
3998
+ return failure(4, "outcome_unknown", message);
3999
+ } finally {
4000
+ process.removeListener("SIGINT", interrupt);
4001
+ if (knownResult && command) {
4002
+ const directory = receiptDirectory(command, requestId);
4003
+ if (await (0, import_promises2.access)(directory).then(
4004
+ () => true,
4005
+ () => false
4006
+ ))
4007
+ await pruneOutput(outputRoot(), directory).catch(() => {
4008
+ });
4009
+ }
4010
+ const latest = await update;
4011
+ if (latest) {
4012
+ console.error(
4013
+ [
4014
+ `BrowserPaw ${latest} is available (installed: ${CURRENT_VERSION}).`,
4015
+ "Finish the current task before upgrading with your existing installation method.",
4016
+ `Global npm: npm install -g browserpaw@${latest}, then browserpaw setup.`,
4017
+ `npx: npx browserpaw@${latest} setup. Setup refreshes the host and managed base Skills.`,
4018
+ `Chrome extension (manual download, unpack and load): ${GITHUB_REPO_URL}/releases/download/v${latest}/browserpaw-extension.zip`
4019
+ ].join("\n")
4020
+ );
4021
+ }
4022
+ }
4023
+ }
4024
+
4025
+ // src/cli.ts
4026
+ void runCommands(process.argv.slice(2)).then((code) => {
4027
+ process.exitCode = code;
4028
+ });