browserpilot-cdp 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2,13 +2,13 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { spawn as spawn3 } from "node:child_process";
5
- import fs5 from "node:fs/promises";
6
- import os3 from "node:os";
7
- import path6 from "node:path";
5
+ import fs6 from "node:fs/promises";
6
+ import os5 from "node:os";
7
+ import path7 from "node:path";
8
8
  import { fileURLToPath as fileURLToPath3 } from "node:url";
9
9
 
10
10
  // ../protocol/dist/constants.js
11
- var BROWSERPILOT_VERSION = "1.1.0";
11
+ var BROWSERPILOT_VERSION = "1.2.1";
12
12
  var DEFAULT_DAEMON_HOST = "127.0.0.1";
13
13
  var DEFAULT_DAEMON_PORT = 19888;
14
14
  var NATIVE_HOST_NAME = "com.browserpilot.bridge";
@@ -32,6 +32,23 @@ var BLOCKED_PROFILE_WIDE_CDP_COMMANDS = /* @__PURE__ */ new Set([
32
32
  "Network.clearBrowserCookies",
33
33
  "Network.clearBrowserCache"
34
34
  ]);
35
+ var RESTRICTED_URL_PREFIXES = [
36
+ "chrome://",
37
+ "chrome-extension://",
38
+ "chrome-untrusted://",
39
+ "devtools://",
40
+ "edge://",
41
+ "brave://",
42
+ "about:blank#blocked",
43
+ "https://chrome.google.com/webstore",
44
+ "https://chromewebstore.google.com"
45
+ ];
46
+ function isRestrictedUrl(url) {
47
+ if (!url)
48
+ return false;
49
+ const lower = url.toLowerCase();
50
+ return RESTRICTED_URL_PREFIXES.some((prefix) => lower.startsWith(prefix));
51
+ }
35
52
  function isBlockedProfileWideCommand(method) {
36
53
  return BLOCKED_PROFILE_WIDE_CDP_COMMANDS.has(method);
37
54
  }
@@ -594,6 +611,8 @@ var ExtensionBridgeTransport = class {
594
611
  tabId: Number(params.tabId),
595
612
  url: String(params.url ?? "")
596
613
  });
614
+ } else if (ev.event === "download.updated" && params.download) {
615
+ this.events.emit("download-event", params.download);
597
616
  }
598
617
  this.events.emit("extension-event", ev);
599
618
  }
@@ -645,6 +664,14 @@ var ExtensionBridgeTransport = class {
645
664
  this.events.on("popup-opened", listener);
646
665
  return () => this.events.off("popup-opened", listener);
647
666
  }
667
+ onDownloadEvent(listener) {
668
+ this.events.on("download-event", listener);
669
+ return () => this.events.off("download-event", listener);
670
+ }
671
+ async listDownloads() {
672
+ const res = await this.rpc("downloads.list");
673
+ return res.downloads ?? [];
674
+ }
648
675
  onClose(listener) {
649
676
  this.events.on("closed", listener);
650
677
  return () => this.events.off("closed", listener);
@@ -3772,7 +3799,94 @@ var PerformanceProfiler = class {
3772
3799
  // ../core/dist/recorder.js
3773
3800
  import { spawn as spawn2 } from "node:child_process";
3774
3801
  import fs3 from "node:fs/promises";
3802
+ import os2 from "node:os";
3775
3803
  import path4 from "node:path";
3804
+ var AUDIO_BINDING_NAME = "__browserpilotAudioChunk";
3805
+ var AUDIO_TAP_SCRIPT = `(() => {
3806
+ if (globalThis.__bpAudioTapActive) return;
3807
+ globalThis.__bpAudioTapActive = true;
3808
+ try {
3809
+ const AudioCtx = globalThis.AudioContext || globalThis.webkitAudioContext;
3810
+ if (!AudioCtx || typeof MediaRecorder === 'undefined') return;
3811
+ const mixCtx = new AudioCtx();
3812
+ const dest = mixCtx.createMediaStreamDestination();
3813
+ const connected = new WeakSet();
3814
+
3815
+ function tapMediaEl(el) {
3816
+ if (connected.has(el)) return;
3817
+ try {
3818
+ const src = mixCtx.createMediaElementSource(el);
3819
+ src.connect(dest);
3820
+ src.connect(mixCtx.destination);
3821
+ connected.add(el);
3822
+ } catch {}
3823
+ }
3824
+
3825
+ for (const el of document.querySelectorAll('audio, video')) tapMediaEl(el);
3826
+ const mo = new MutationObserver(() => {
3827
+ for (const el of document.querySelectorAll('audio, video')) tapMediaEl(el);
3828
+ });
3829
+ if (document.documentElement) mo.observe(document.documentElement, { childList: true, subtree: true });
3830
+
3831
+ // Also patch AudioNode.prototype.connect so Web Audio synthesis graphs feed our tap
3832
+ const origConnect = AudioNode.prototype.connect;
3833
+ if (!origConnect.__bpPatched) {
3834
+ const wrapped = function(...args) {
3835
+ const res = origConnect.apply(this, args);
3836
+ try {
3837
+ if (args[0] && this.context && args[0] === this.context.destination) {
3838
+ if (!this.context.__bpTapDest) {
3839
+ const d = this.context.createMediaStreamDestination();
3840
+ this.context.__bpTapDest = d;
3841
+ const subRec = new MediaRecorder(d.stream, { mimeType: 'audio/webm;codecs=opus' });
3842
+ subRec.ondataavailable = (ev) => {
3843
+ if (ev.data && ev.data.size > 0 && typeof globalThis.${AUDIO_BINDING_NAME} === 'function') {
3844
+ const reader = new FileReader();
3845
+ reader.onloadend = () => {
3846
+ const b64 = String(reader.result || '').split(',')[1] || '';
3847
+ if (b64) globalThis.${AUDIO_BINDING_NAME}(b64);
3848
+ };
3849
+ reader.readAsDataURL(ev.data);
3850
+ }
3851
+ };
3852
+ subRec.start(250);
3853
+ globalThis.__bpAudioRecorders = globalThis.__bpAudioRecorders || [];
3854
+ globalThis.__bpAudioRecorders.push(subRec);
3855
+ }
3856
+ origConnect.call(this, this.context.__bpTapDest);
3857
+ }
3858
+ } catch {}
3859
+ return res;
3860
+ };
3861
+ wrapped.__bpPatched = true;
3862
+ AudioNode.prototype.connect = wrapped;
3863
+ }
3864
+
3865
+ const mimeType = MediaRecorder.isTypeSupported('audio/webm;codecs=opus') ? 'audio/webm;codecs=opus' : 'audio/webm';
3866
+ const rec = new MediaRecorder(dest.stream, { mimeType });
3867
+ rec.ondataavailable = (ev) => {
3868
+ if (ev.data && ev.data.size > 0 && typeof globalThis.${AUDIO_BINDING_NAME} === 'function') {
3869
+ const reader = new FileReader();
3870
+ reader.onloadend = () => {
3871
+ const b64 = String(reader.result || '').split(',')[1] || '';
3872
+ if (b64) globalThis.${AUDIO_BINDING_NAME}(b64);
3873
+ };
3874
+ reader.readAsDataURL(ev.data);
3875
+ }
3876
+ };
3877
+ rec.start(250);
3878
+ globalThis.__bpAudioRecorders = globalThis.__bpAudioRecorders || [];
3879
+ globalThis.__bpAudioRecorders.push(rec);
3880
+ globalThis.__bpStopAudioTap = () => {
3881
+ globalThis.__bpAudioTapActive = false;
3882
+ mo.disconnect();
3883
+ for (const r of globalThis.__bpAudioRecorders || []) {
3884
+ try { if (r.state !== 'inactive') r.stop(); } catch {}
3885
+ }
3886
+ globalThis.__bpAudioRecorders = [];
3887
+ };
3888
+ } catch {}
3889
+ })()`;
3776
3890
  var ScreenRecorder = class {
3777
3891
  session;
3778
3892
  active = null;
@@ -3793,6 +3907,9 @@ var ScreenRecorder = class {
3793
3907
  }
3794
3908
  const outputPath = path4.resolve(options.outputPath);
3795
3909
  await fs3.mkdir(path4.dirname(outputPath), { recursive: true });
3910
+ const audioEnabled = Boolean(options.audio);
3911
+ const videoOnlyPath = audioEnabled ? path4.join(os2.tmpdir(), `bp-video-${Date.now()}-${Math.random().toString(36).slice(2, 6)}${path4.extname(outputPath) || ".mp4"}`) : outputPath;
3912
+ const audioTempPath = audioEnabled ? path4.join(os2.tmpdir(), `bp-audio-${Date.now()}-${Math.random().toString(36).slice(2, 6)}.webm`) : null;
3796
3913
  const frameRate = Math.min(60, Math.max(5, options.frameRate ?? 24));
3797
3914
  const quality = Math.min(100, Math.max(20, options.quality ?? 85));
3798
3915
  const maxWidth = options.maxWidth ?? 1280;
@@ -3813,7 +3930,7 @@ var ScreenRecorder = class {
3813
3930
  "-vf",
3814
3931
  "pad=ceil(iw/2)*2:ceil(ih/2)*2",
3815
3932
  ...codecArgs,
3816
- outputPath
3933
+ videoOnlyPath
3817
3934
  ], { stdio: ["pipe", "ignore", "pipe"] });
3818
3935
  const stderr = [];
3819
3936
  ffmpeg.stderr?.on("data", (chunk) => {
@@ -3826,16 +3943,20 @@ var ScreenRecorder = class {
3826
3943
  });
3827
3944
  const rec = {
3828
3945
  outputPath,
3946
+ videoOnlyPath,
3947
+ audioTempPath,
3948
+ audioChunks: [],
3949
+ audioEnabled,
3950
+ audioScriptId: null,
3829
3951
  ffmpeg,
3830
3952
  startedAt: Date.now(),
3831
3953
  frameCount: 0,
3832
3954
  actionTimestamps: [],
3833
- unsub: () => {
3834
- },
3955
+ unsubs: [],
3835
3956
  maxTimer: null,
3836
3957
  stderr
3837
3958
  };
3838
- rec.unsub = this.session.on("Page.screencastFrame", (params) => {
3959
+ rec.unsubs.push(this.session.on("Page.screencastFrame", (params) => {
3839
3960
  const data = params.data;
3840
3961
  const sessionId = params.sessionId;
3841
3962
  if (sessionId !== void 0) {
@@ -3846,7 +3967,20 @@ var ScreenRecorder = class {
3846
3967
  rec.frameCount++;
3847
3968
  rec.ffmpeg.stdin.write(Buffer.from(data, "base64"));
3848
3969
  }
3849
- });
3970
+ }));
3971
+ if (audioEnabled) {
3972
+ await this.session.send("Runtime.addBinding", { name: AUDIO_BINDING_NAME }).catch(() => {
3973
+ });
3974
+ const added = await this.session.send("Page.addScriptToEvaluateOnNewDocument", { source: AUDIO_TAP_SCRIPT }).catch(() => ({ identifier: void 0 }));
3975
+ rec.audioScriptId = added.identifier ?? null;
3976
+ await this.session.send("Runtime.evaluate", { expression: AUDIO_TAP_SCRIPT }).catch(() => {
3977
+ });
3978
+ rec.unsubs.push(this.session.on("Runtime.bindingCalled", (params) => {
3979
+ if (params.name === AUDIO_BINDING_NAME && typeof params.payload === "string" && params.payload) {
3980
+ rec.audioChunks.push(Buffer.from(params.payload, "base64"));
3981
+ }
3982
+ }));
3983
+ }
3850
3984
  if (maxDurationMs > 0) {
3851
3985
  rec.maxTimer = setTimeout(() => {
3852
3986
  void this.stop().catch(() => {
@@ -3865,7 +3999,7 @@ var ScreenRecorder = class {
3865
3999
  await this.cancel();
3866
4000
  throw new Error(`ffmpeg failed to start (install via "brew install ffmpeg" or "apt install ffmpeg"): ${spawnErr.message}`);
3867
4001
  }
3868
- return { outputPath };
4002
+ return { outputPath, audio: audioEnabled };
3869
4003
  }
3870
4004
  async stop() {
3871
4005
  if (!this.active) {
@@ -3875,7 +4009,17 @@ var ScreenRecorder = class {
3875
4009
  this.active = null;
3876
4010
  if (rec.maxTimer)
3877
4011
  clearTimeout(rec.maxTimer);
3878
- rec.unsub();
4012
+ if (rec.audioEnabled) {
4013
+ await this.session.send("Runtime.evaluate", { expression: "globalThis.__bpStopAudioTap?.()" }).catch(() => {
4014
+ });
4015
+ if (rec.audioScriptId) {
4016
+ await this.session.send("Page.removeScriptToEvaluateOnNewDocument", { identifier: rec.audioScriptId }).catch(() => {
4017
+ });
4018
+ }
4019
+ await new Promise((r) => setTimeout(r, 180));
4020
+ }
4021
+ for (const off of rec.unsubs)
4022
+ off();
3879
4023
  await this.session.send("Page.stopScreencast").catch(() => {
3880
4024
  });
3881
4025
  if (rec.frameCount === 0) {
@@ -3898,13 +4042,50 @@ var ScreenRecorder = class {
3898
4042
  if (exitCode !== 0 && exitCode !== null) {
3899
4043
  throw new Error(`ffmpeg exited with code ${exitCode}: ${rec.stderr.join("").slice(-500)}`);
3900
4044
  }
4045
+ let hasAudio = false;
4046
+ if (rec.audioEnabled) {
4047
+ if (rec.audioChunks.length > 0 && rec.audioTempPath) {
4048
+ try {
4049
+ await fs3.writeFile(rec.audioTempPath, Buffer.concat(rec.audioChunks));
4050
+ const ext = path4.extname(rec.outputPath).toLowerCase();
4051
+ const audioCodec = ext === ".webm" ? ["-c:a", "libopus"] : ["-c:a", "aac", "-b:a", "128k"];
4052
+ await runFfmpeg([
4053
+ "-y",
4054
+ "-i",
4055
+ rec.videoOnlyPath,
4056
+ "-i",
4057
+ rec.audioTempPath,
4058
+ "-c:v",
4059
+ "copy",
4060
+ ...audioCodec,
4061
+ "-shortest",
4062
+ rec.outputPath
4063
+ ]);
4064
+ hasAudio = true;
4065
+ } catch {
4066
+ await fs3.copyFile(rec.videoOnlyPath, rec.outputPath);
4067
+ } finally {
4068
+ await fs3.rm(rec.videoOnlyPath, { force: true }).catch(() => {
4069
+ });
4070
+ await fs3.rm(rec.audioTempPath, { force: true }).catch(() => {
4071
+ });
4072
+ }
4073
+ } else {
4074
+ await fs3.rename(rec.videoOnlyPath, rec.outputPath).catch(async () => {
4075
+ await fs3.copyFile(rec.videoOnlyPath, rec.outputPath);
4076
+ await fs3.rm(rec.videoOnlyPath, { force: true }).catch(() => {
4077
+ });
4078
+ });
4079
+ }
4080
+ }
3901
4081
  const stat = await fs3.stat(rec.outputPath);
3902
4082
  return {
3903
4083
  path: rec.outputPath,
3904
4084
  durationMs: Date.now() - rec.startedAt,
3905
4085
  frameCount: rec.frameCount,
3906
4086
  sizeBytes: stat.size,
3907
- actionTimestamps: rec.actionTimestamps
4087
+ actionTimestamps: rec.actionTimestamps,
4088
+ hasAudio
3908
4089
  };
3909
4090
  }
3910
4091
  async cancel() {
@@ -3914,21 +4095,74 @@ var ScreenRecorder = class {
3914
4095
  this.active = null;
3915
4096
  if (rec.maxTimer)
3916
4097
  clearTimeout(rec.maxTimer);
3917
- rec.unsub();
4098
+ for (const off of rec.unsubs)
4099
+ off();
3918
4100
  await this.session.send("Page.stopScreencast").catch(() => {
3919
4101
  });
3920
4102
  rec.ffmpeg.kill("SIGTERM");
3921
4103
  await fs3.rm(rec.outputPath, { force: true }).catch(() => {
3922
4104
  });
4105
+ if (rec.videoOnlyPath !== rec.outputPath)
4106
+ await fs3.rm(rec.videoOnlyPath, { force: true }).catch(() => {
4107
+ });
4108
+ if (rec.audioTempPath)
4109
+ await fs3.rm(rec.audioTempPath, { force: true }).catch(() => {
4110
+ });
3923
4111
  }
3924
4112
  };
3925
- async function createDemoVideo(options) {
3926
- const input = path4.resolve(options.recordingPath);
3927
- const ext = path4.extname(input) || ".mp4";
3928
- const output = path4.resolve(options.outputPath ?? input.replace(ext, `.demo${ext}`));
3929
- const speed = Math.max(1, options.speed ?? 2);
4113
+ function computeDemoSegments(durationMs, actionTimestamps, options = {}) {
4114
+ const totalSec = Math.max(0.1, durationMs / 1e3);
4115
+ const padMs = options.paddingMs ?? 750;
4116
+ const minIdleGapMs = options.minIdleGapMs ?? 400;
4117
+ if (!actionTimestamps.length || durationMs <= 0) {
4118
+ return [{ startSec: 0, endSec: totalSec, kind: "idle" }];
4119
+ }
4120
+ const sorted = [...actionTimestamps].filter((t) => Number.isFinite(t) && t >= 0 && t <= durationMs).sort((a, b) => a - b);
4121
+ if (!sorted.length) {
4122
+ return [{ startSec: 0, endSec: totalSec, kind: "idle" }];
4123
+ }
4124
+ const windows = [];
4125
+ for (const ts of sorted) {
4126
+ const start = Math.max(0, ts - padMs);
4127
+ const end = Math.min(durationMs, ts + padMs);
4128
+ const prev = windows[windows.length - 1];
4129
+ if (prev && start <= prev.end + minIdleGapMs) {
4130
+ prev.end = Math.max(prev.end, end);
4131
+ } else {
4132
+ windows.push({ start, end });
4133
+ }
4134
+ }
4135
+ const segments = [];
4136
+ let cursor = 0;
4137
+ for (const w of windows) {
4138
+ if (w.start > cursor + 50) {
4139
+ segments.push({ startSec: cursor / 1e3, endSec: w.start / 1e3, kind: "idle" });
4140
+ }
4141
+ segments.push({ startSec: w.start / 1e3, endSec: w.end / 1e3, kind: "active" });
4142
+ cursor = w.end;
4143
+ }
4144
+ if (durationMs > cursor + 50) {
4145
+ segments.push({ startSec: cursor / 1e3, endSec: totalSec, kind: "idle" });
4146
+ }
4147
+ return segments.filter((s) => s.endSec - s.startSec >= 0.05);
4148
+ }
4149
+ async function probeVideoDurationSec(filePath) {
4150
+ return await new Promise((resolve) => {
4151
+ const proc = spawn2("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filePath], { stdio: ["ignore", "pipe", "ignore"] });
4152
+ let out = "";
4153
+ proc.stdout.on("data", (c) => {
4154
+ out += c.toString("utf8");
4155
+ });
4156
+ proc.once("error", () => resolve(null));
4157
+ proc.once("close", () => {
4158
+ const n = Number.parseFloat(out.trim());
4159
+ resolve(Number.isFinite(n) && n > 0 ? n : null);
4160
+ });
4161
+ });
4162
+ }
4163
+ async function runFfmpeg(args) {
3930
4164
  await new Promise((resolve, reject) => {
3931
- const proc = spawn2("ffmpeg", ["-y", "-i", input, "-filter:v", `setpts=${(1 / speed).toFixed(4)}*PTS`, "-an", output], { stdio: ["ignore", "ignore", "pipe"] });
4165
+ const proc = spawn2("ffmpeg", args, { stdio: ["ignore", "ignore", "pipe"] });
3932
4166
  const errChunks = [];
3933
4167
  proc.stderr?.on("data", (c) => errChunks.push(c.toString("utf8")));
3934
4168
  proc.once("error", reject);
@@ -3936,12 +4170,520 @@ async function createDemoVideo(options) {
3936
4170
  if (code === 0)
3937
4171
  resolve();
3938
4172
  else
3939
- reject(new Error(`createDemoVideo ffmpeg failed (${code}): ${errChunks.join("").slice(-400)}`));
4173
+ reject(new Error(`ffmpeg failed (${code}): ${errChunks.join("").slice(-500)}`));
3940
4174
  });
3941
4175
  });
4176
+ }
4177
+ async function createDemoVideo(options) {
4178
+ const input = path4.resolve(options.recordingPath);
4179
+ const ext = path4.extname(input) || ".mp4";
4180
+ const output = path4.resolve(options.outputPath ?? input.replace(ext, `.demo${ext}`));
4181
+ const speed = Math.max(1, options.speed ?? (options.actionTimestamps?.length ? 6 : 2));
4182
+ if (options.actionTimestamps && options.actionTimestamps.length > 0) {
4183
+ const probedSec = await probeVideoDurationSec(input);
4184
+ const durationMs = options.durationMs ?? (probedSec ? Math.round(probedSec * 1e3) : 0);
4185
+ const segments = computeDemoSegments(durationMs, options.actionTimestamps, {
4186
+ paddingMs: options.paddingMs
4187
+ });
4188
+ if (segments.length > 1) {
4189
+ const filters = [];
4190
+ const concatInputs = [];
4191
+ segments.forEach((seg, idx) => {
4192
+ const factor = seg.kind === "idle" ? (1 / speed).toFixed(4) : "1.0";
4193
+ filters.push(`[0:v]trim=start=${seg.startSec.toFixed(3)}:end=${seg.endSec.toFixed(3)},setpts=${factor}*(PTS-STARTPTS)[v${idx}]`);
4194
+ concatInputs.push(`[v${idx}]`);
4195
+ });
4196
+ filters.push(`${concatInputs.join("")}concat=n=${segments.length}:v=1:a=0[vout]`);
4197
+ await runFfmpeg([
4198
+ "-y",
4199
+ "-i",
4200
+ input,
4201
+ "-filter_complex",
4202
+ filters.join(";"),
4203
+ "-map",
4204
+ "[vout]",
4205
+ "-c:v",
4206
+ ext === ".webm" ? "libvpx" : "libx264",
4207
+ ...ext === ".webm" ? ["-b:v", "1M"] : ["-pix_fmt", "yuv420p", "-preset", "veryfast", "-movflags", "+faststart"],
4208
+ output
4209
+ ]);
4210
+ return output;
4211
+ }
4212
+ }
4213
+ await runFfmpeg(["-y", "-i", input, "-filter:v", `setpts=${(1 / speed).toFixed(4)}*PTS`, "-an", output]);
3942
4214
  return output;
3943
4215
  }
3944
4216
 
4217
+ // ../core/dist/downloads.js
4218
+ import { EventEmitter as EventEmitter4 } from "node:events";
4219
+ import fs4 from "node:fs/promises";
4220
+ import os3 from "node:os";
4221
+ import path5 from "node:path";
4222
+ function sanitizeFilename(name) {
4223
+ const base = path5.basename(name || "download.bin").replace(/[<>:"/\\|?*\x00-\x1f]/g, "_");
4224
+ return base || "download.bin";
4225
+ }
4226
+ async function resolveUniquePath(dir, filename) {
4227
+ const safe = sanitizeFilename(filename);
4228
+ const ext = path5.extname(safe);
4229
+ const stem = ext ? safe.slice(0, -ext.length) : safe;
4230
+ let candidate = path5.join(dir, safe);
4231
+ for (let i = 1; i <= 200; i++) {
4232
+ try {
4233
+ await fs4.access(candidate);
4234
+ candidate = path5.join(dir, `${stem}-${i}${ext}`);
4235
+ } catch {
4236
+ return candidate;
4237
+ }
4238
+ }
4239
+ return path5.join(dir, `${stem}-${Date.now()}${ext}`);
4240
+ }
4241
+ var DownloadManager = class {
4242
+ session;
4243
+ entries = /* @__PURE__ */ new Map();
4244
+ emitter = new EventEmitter4();
4245
+ downloadDir = null;
4246
+ configured = false;
4247
+ unsubs = [];
4248
+ constructor(session) {
4249
+ this.session = session;
4250
+ this.emitter.setMaxListeners(50);
4251
+ const onBegin = (params) => {
4252
+ const id = String(params.guid ?? `dl_${Date.now()}`);
4253
+ const entry = {
4254
+ id,
4255
+ url: String(params.url ?? ""),
4256
+ suggestedFilename: sanitizeFilename(String(params.suggestedFilename ?? "download.bin")),
4257
+ state: "in_progress",
4258
+ receivedBytes: 0,
4259
+ startedAt: Date.now()
4260
+ };
4261
+ this.entries.set(id, entry);
4262
+ this.emitter.emit("update", entry);
4263
+ };
4264
+ const onProgress = (params) => {
4265
+ const id = String(params.guid ?? "");
4266
+ const entry = this.entries.get(id);
4267
+ if (!entry)
4268
+ return;
4269
+ if (typeof params.receivedBytes === "number")
4270
+ entry.receivedBytes = params.receivedBytes;
4271
+ if (typeof params.totalBytes === "number" && params.totalBytes > 0)
4272
+ entry.totalBytes = params.totalBytes;
4273
+ const rawState = String(params.state ?? "");
4274
+ if (rawState === "completed") {
4275
+ void this.finalizeDirectDownload(entry);
4276
+ } else if (rawState === "canceled") {
4277
+ entry.state = "canceled";
4278
+ entry.completedAt = Date.now();
4279
+ this.emitter.emit("update", entry);
4280
+ }
4281
+ };
4282
+ this.unsubs.push(session.on("Browser.downloadWillBegin", onBegin), session.on("Page.downloadWillBegin", onBegin), session.on("Browser.downloadProgress", onProgress), session.on("Page.downloadProgress", onProgress));
4283
+ if (session.transport.onDownloadEvent) {
4284
+ this.unsubs.push(session.transport.onDownloadEvent((entry) => {
4285
+ this.entries.set(entry.id, entry);
4286
+ this.emitter.emit("update", entry);
4287
+ }));
4288
+ }
4289
+ }
4290
+ async finalizeDirectDownload(entry) {
4291
+ if (this.downloadDir) {
4292
+ const guidPath = path5.join(this.downloadDir, entry.id);
4293
+ const directNamedPath = path5.join(this.downloadDir, entry.suggestedFilename);
4294
+ try {
4295
+ await fs4.access(guidPath);
4296
+ const targetPath = await resolveUniquePath(this.downloadDir, entry.suggestedFilename);
4297
+ await fs4.rename(guidPath, targetPath);
4298
+ entry.filePath = targetPath;
4299
+ } catch {
4300
+ try {
4301
+ await fs4.access(directNamedPath);
4302
+ entry.filePath = directNamedPath;
4303
+ } catch {
4304
+ }
4305
+ }
4306
+ }
4307
+ entry.state = "completed";
4308
+ entry.completedAt = Date.now();
4309
+ this.emitter.emit("update", entry);
4310
+ }
4311
+ async configure(downloadDir) {
4312
+ if (this.session.transport.mode === "extension") {
4313
+ this.configured = true;
4314
+ return { downloadDir: null, mode: "extension" };
4315
+ }
4316
+ const dir = path5.resolve(downloadDir ?? path5.join(os3.tmpdir(), "browserpilot-downloads"));
4317
+ await fs4.mkdir(dir, { recursive: true });
4318
+ this.downloadDir = dir;
4319
+ if (this.session.transport.sendBrowser) {
4320
+ await this.session.transport.sendBrowser("Browser.setDownloadBehavior", {
4321
+ behavior: "allowAndName",
4322
+ downloadPath: dir,
4323
+ eventsEnabled: true
4324
+ });
4325
+ } else {
4326
+ await this.session.send("Page.setDownloadBehavior", {
4327
+ behavior: "allow",
4328
+ downloadPath: dir
4329
+ });
4330
+ }
4331
+ this.configured = true;
4332
+ return { downloadDir: dir, mode: "direct-cdp" };
4333
+ }
4334
+ async ensureConfigured() {
4335
+ if (!this.configured) {
4336
+ await this.configure();
4337
+ }
4338
+ }
4339
+ async list() {
4340
+ if (this.session.transport.mode === "extension" && this.session.transport.listDownloads) {
4341
+ const remote = await this.session.transport.listDownloads().catch(() => []);
4342
+ for (const item of remote) {
4343
+ this.entries.set(item.id, item);
4344
+ }
4345
+ }
4346
+ return Array.from(this.entries.values()).sort((a, b) => a.startedAt - b.startedAt);
4347
+ }
4348
+ async waitForDownload(options = {}) {
4349
+ await this.ensureConfigured();
4350
+ const timeoutMs = options.timeoutMs ?? 2e4;
4351
+ const sinceTs = options.sinceTimestamp ?? 0;
4352
+ const regex = options.filenamePattern instanceof RegExp ? options.filenamePattern : typeof options.filenamePattern === "string" ? new RegExp(options.filenamePattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i") : null;
4353
+ const matches = (e) => e.state === "completed" && (e.completedAt ?? e.startedAt) >= sinceTs && (!regex || regex.test(e.suggestedFilename) || (e.filePath ? regex.test(e.filePath) : false));
4354
+ const existing = Array.from(this.entries.values()).reverse().find(matches);
4355
+ if (existing)
4356
+ return existing;
4357
+ return await new Promise((resolve, reject) => {
4358
+ const timer = setTimeout(() => {
4359
+ this.emitter.off("update", onUpdate);
4360
+ reject(new Error(`Timed out after ${timeoutMs}ms waiting for download to complete`));
4361
+ }, timeoutMs);
4362
+ const onUpdate = (entry) => {
4363
+ if (matches(entry)) {
4364
+ clearTimeout(timer);
4365
+ this.emitter.off("update", onUpdate);
4366
+ resolve(entry);
4367
+ } else if (entry.state === "canceled" && entry.startedAt >= sinceTs && (!regex || regex.test(entry.suggestedFilename))) {
4368
+ clearTimeout(timer);
4369
+ this.emitter.off("update", onUpdate);
4370
+ reject(new Error(`Download canceled: ${entry.suggestedFilename}`));
4371
+ }
4372
+ };
4373
+ this.emitter.on("update", onUpdate);
4374
+ });
4375
+ }
4376
+ clear() {
4377
+ this.entries.clear();
4378
+ }
4379
+ dispose() {
4380
+ for (const off of this.unsubs)
4381
+ off();
4382
+ this.unsubs = [];
4383
+ this.emitter.removeAllListeners();
4384
+ }
4385
+ };
4386
+
4387
+ // ../core/dist/action-recorder.js
4388
+ var BINDING_NAME = "__browserpilotRecordEvent";
4389
+ function buildCaptureScript(maskPasswords) {
4390
+ return `(() => {
4391
+ if (globalThis.__bpActionRecorderInstalled) {
4392
+ globalThis.__bpActionRecorderEnabled = true;
4393
+ return;
4394
+ }
4395
+ globalThis.__bpActionRecorderInstalled = true;
4396
+ globalThis.__bpActionRecorderEnabled = true;
4397
+
4398
+ function emit(payload) {
4399
+ if (!globalThis.__bpActionRecorderEnabled) return;
4400
+ if (typeof globalThis.${BINDING_NAME} === 'function') {
4401
+ try { globalThis.${BINDING_NAME}(JSON.stringify(payload)); } catch {}
4402
+ }
4403
+ }
4404
+
4405
+ function stableSelector(el) {
4406
+ if (!el || !(el instanceof Element)) return '';
4407
+ const tid = el.getAttribute('data-testid');
4408
+ if (tid) return '[data-testid="' + tid.replace(/"/g, '\\\\"') + '"]';
4409
+ if (el.id) return '#' + CSS.escape(el.id);
4410
+ const tag = el.tagName.toLowerCase();
4411
+ const nameAttr = el.getAttribute('name');
4412
+ if (nameAttr) return tag + '[name="' + nameAttr.replace(/"/g, '\\\\"') + '"]';
4413
+ const aria = el.getAttribute('aria-label');
4414
+ if (aria) return tag + '[aria-label="' + aria.replace(/"/g, '\\\\"') + '"]';
4415
+ const ph = el.getAttribute('placeholder');
4416
+ if (ph) return 'placeholder=' + ph;
4417
+ const role = el.getAttribute('role') || (tag === 'button' ? 'button' : tag === 'a' ? 'link' : '');
4418
+ const text = (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim();
4419
+ if (role && text && text.length <= 60) {
4420
+ return 'role=' + role + '[name="' + text.replace(/"/g, '\\\\"') + '"]';
4421
+ }
4422
+ const classes = Array.from(el.classList || []).slice(0, 2).map((c) => '.' + CSS.escape(c)).join('');
4423
+ return tag + classes;
4424
+ }
4425
+
4426
+ function interactiveTarget(raw) {
4427
+ if (!(raw instanceof Element)) return null;
4428
+ return raw.closest('button, a, input, textarea, select, [role="button"], [role="link"], [role="tab"], [role="menuitem"], label') || raw;
4429
+ }
4430
+
4431
+ document.addEventListener('click', (e) => {
4432
+ const el = interactiveTarget(e.target);
4433
+ if (!el) return;
4434
+ const tag = el.tagName.toLowerCase();
4435
+ // Skip redundant click right on text inputs when followed by fill
4436
+ emit({
4437
+ action: 'click',
4438
+ url: location.href,
4439
+ target: stableSelector(el),
4440
+ text: (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 80) || undefined,
4441
+ coordinates: { x: Math.round(e.clientX), y: Math.round(e.clientY) },
4442
+ tag,
4443
+ });
4444
+ }, true);
4445
+
4446
+ const inputTimers = new WeakMap();
4447
+ const recordInput = (el) => {
4448
+ const tag = el.tagName.toLowerCase();
4449
+ const sel = stableSelector(el);
4450
+ if (tag === 'select') {
4451
+ emit({ action: 'select_option', url: location.href, target: sel, value: el.value });
4452
+ return;
4453
+ }
4454
+ if (tag === 'input' && (el.type === 'checkbox' || el.type === 'radio')) {
4455
+ return; // captured via click
4456
+ }
4457
+ const isPassword = ${maskPasswords} && tag === 'input' && el.type === 'password';
4458
+ const val = el.isContentEditable ? (el.innerText || '') : (el.value || '');
4459
+ emit({
4460
+ action: 'fill',
4461
+ url: location.href,
4462
+ target: sel,
4463
+ value: isPassword ? '<REDACTED_PASSWORD>' : val,
4464
+ });
4465
+ };
4466
+
4467
+ document.addEventListener('input', (e) => {
4468
+ const el = e.target;
4469
+ if (!(el instanceof Element)) return;
4470
+ const prev = inputTimers.get(el);
4471
+ if (prev) clearTimeout(prev);
4472
+ inputTimers.set(el, setTimeout(() => recordInput(el), 350));
4473
+ }, true);
4474
+
4475
+ document.addEventListener('change', (e) => {
4476
+ const el = e.target;
4477
+ if (!(el instanceof Element)) return;
4478
+ const prev = inputTimers.get(el);
4479
+ if (prev) clearTimeout(prev);
4480
+ recordInput(el);
4481
+ }, true);
4482
+
4483
+ document.addEventListener('keydown', (e) => {
4484
+ if (['Enter', 'Escape', 'Tab'].includes(e.key)) {
4485
+ emit({ action: 'press_key', url: location.href, key: e.key });
4486
+ }
4487
+ }, true);
4488
+
4489
+ let lastScrollY = Math.round(window.scrollY || 0);
4490
+ let scrollTimer = null;
4491
+ window.addEventListener('scroll', () => {
4492
+ if (scrollTimer) clearTimeout(scrollTimer);
4493
+ scrollTimer = setTimeout(() => {
4494
+ const curY = Math.round(window.scrollY || 0);
4495
+ const delta = curY - lastScrollY;
4496
+ if (Math.abs(delta) >= 180) {
4497
+ emit({ action: 'scroll', url: location.href, value: String(delta) });
4498
+ lastScrollY = curY;
4499
+ }
4500
+ }, 300);
4501
+ }, { passive: true });
4502
+ })()`;
4503
+ }
4504
+ function buildActionRecordingResult(rawSteps, durationMs) {
4505
+ const steps = [];
4506
+ for (const s of rawSteps) {
4507
+ const prev = steps[steps.length - 1];
4508
+ if (s.action === "fill" && prev?.action === "fill" && prev.target === s.target) {
4509
+ prev.value = s.value;
4510
+ prev.timestamp = s.timestamp;
4511
+ continue;
4512
+ }
4513
+ if ((s.action === "fill" || s.action === "select_option") && prev?.action === "click" && prev.target === s.target) {
4514
+ steps.pop();
4515
+ }
4516
+ if (s.action === "navigate" && prev?.action === "navigate" && prev.url === s.url) {
4517
+ continue;
4518
+ }
4519
+ steps.push({ ...s });
4520
+ }
4521
+ const batchSteps = steps.map((s) => {
4522
+ switch (s.action) {
4523
+ case "navigate":
4524
+ return { action: "navigate", url: s.url };
4525
+ case "click":
4526
+ return { action: "click", target: s.target };
4527
+ case "fill":
4528
+ return { action: "fill", target: s.target, value: s.value ?? "" };
4529
+ case "select_option":
4530
+ return { action: "select_option", target: s.target, value: s.value ?? "" };
4531
+ case "press_key":
4532
+ return { action: "press_key", key: s.key ?? "Enter" };
4533
+ case "scroll": {
4534
+ const dy = Number(s.value ?? 400);
4535
+ return { action: "scroll", direction: dy >= 0 ? "down" : "up", amount: Math.abs(dy) };
4536
+ }
4537
+ }
4538
+ });
4539
+ const scriptLines = [
4540
+ "// Recorded by BrowserPilot Action Recorder",
4541
+ "const t = await tabs.current();"
4542
+ ];
4543
+ for (const s of steps) {
4544
+ switch (s.action) {
4545
+ case "navigate":
4546
+ scriptLines.push(`await t.page.navigate(${JSON.stringify(s.url)});`);
4547
+ break;
4548
+ case "click":
4549
+ scriptLines.push(`await t.page.click(${JSON.stringify(s.target ?? "")});`);
4550
+ break;
4551
+ case "fill":
4552
+ scriptLines.push(`await t.page.fill(${JSON.stringify(s.target ?? "")}, ${JSON.stringify(s.value ?? "")});`);
4553
+ break;
4554
+ case "select_option":
4555
+ scriptLines.push(`await t.page.selectOption(${JSON.stringify(s.target ?? "")}, ${JSON.stringify(s.value ?? "")});`);
4556
+ break;
4557
+ case "press_key":
4558
+ scriptLines.push(`await t.page.pressKey(${JSON.stringify(s.key ?? "Enter")});`);
4559
+ break;
4560
+ case "scroll": {
4561
+ const dy = Number(s.value ?? 400);
4562
+ scriptLines.push(`await t.page.scroll({ deltaY: ${dy} });`);
4563
+ break;
4564
+ }
4565
+ }
4566
+ }
4567
+ const execScript = scriptLines.join("\n");
4568
+ const mdLines = [
4569
+ "# Recorded BrowserPilot Workflow",
4570
+ "",
4571
+ `Recorded ${steps.length} step(s) in ${(durationMs / 1e3).toFixed(1)}s.`,
4572
+ "",
4573
+ "## Steps"
4574
+ ];
4575
+ steps.forEach((s, idx) => {
4576
+ const desc = s.action === "navigate" ? `Navigate to \`${s.url}\`` : s.action === "click" ? `Click \`${s.target}\`${s.text ? ` ("${s.text}")` : ""}` : s.action === "fill" ? `Fill \`${s.target}\` with \`${s.value ?? ""}\`` : s.action === "select_option" ? `Select \`${s.value ?? ""}\` in \`${s.target}\`` : s.action === "press_key" ? `Press key \`${s.key}\`` : `Scroll ${Number(s.value ?? 0) >= 0 ? "down" : "up"} ${Math.abs(Number(s.value ?? 0))}px`;
4577
+ mdLines.push(`${idx + 1}. ${desc}`);
4578
+ });
4579
+ mdLines.push("", "## Replay Script (`browserpilot exec`)", "```js", execScript, "```");
4580
+ return {
4581
+ durationMs,
4582
+ steps,
4583
+ batchSteps,
4584
+ execScript,
4585
+ skillMarkdown: mdLines.join("\n")
4586
+ };
4587
+ }
4588
+ var ActionRecorder = class {
4589
+ session;
4590
+ recording = false;
4591
+ startedAt = 0;
4592
+ steps = [];
4593
+ scriptId = null;
4594
+ unsubs = [];
4595
+ constructor(session) {
4596
+ this.session = session;
4597
+ }
4598
+ isRecording() {
4599
+ return this.recording;
4600
+ }
4601
+ getSteps() {
4602
+ return [...this.steps];
4603
+ }
4604
+ async start(options = {}) {
4605
+ if (this.recording) {
4606
+ throw new Error("Action recorder is already running on this tab");
4607
+ }
4608
+ await this.session.ensureBaseDomains();
4609
+ const maskPasswords = options.maskPasswords !== false;
4610
+ this.steps = [];
4611
+ this.startedAt = Date.now();
4612
+ this.recording = true;
4613
+ const initialUrlRes = await this.session.send("Runtime.evaluate", {
4614
+ expression: "location.href",
4615
+ returnByValue: true
4616
+ });
4617
+ const initialUrl = initialUrlRes.result?.value ?? "";
4618
+ if (initialUrl && initialUrl !== "about:blank") {
4619
+ this.steps.push({ timestamp: this.startedAt, action: "navigate", url: initialUrl });
4620
+ }
4621
+ await this.session.send("Runtime.addBinding", { name: BINDING_NAME });
4622
+ const scriptSource = buildCaptureScript(maskPasswords);
4623
+ const added = await this.session.send("Page.addScriptToEvaluateOnNewDocument", {
4624
+ source: scriptSource
4625
+ });
4626
+ this.scriptId = added.identifier ?? null;
4627
+ await this.session.send("Runtime.evaluate", { expression: scriptSource });
4628
+ this.unsubs.push(this.session.on("Runtime.bindingCalled", (params) => {
4629
+ if (!this.recording || params.name !== BINDING_NAME)
4630
+ return;
4631
+ try {
4632
+ const parsed = JSON.parse(String(params.payload ?? "{}"));
4633
+ if (!parsed.action)
4634
+ return;
4635
+ this.steps.push({
4636
+ timestamp: Date.now(),
4637
+ action: parsed.action,
4638
+ url: parsed.url ?? "",
4639
+ target: parsed.target,
4640
+ value: parsed.value,
4641
+ key: parsed.key,
4642
+ text: parsed.text,
4643
+ coordinates: parsed.coordinates
4644
+ });
4645
+ } catch {
4646
+ }
4647
+ }), this.session.on("Page.frameNavigated", (params) => {
4648
+ if (!this.recording)
4649
+ return;
4650
+ const frame = params.frame;
4651
+ if (frame && !frame.parentId && frame.url && frame.url !== "about:blank") {
4652
+ this.steps.push({
4653
+ timestamp: Date.now(),
4654
+ action: "navigate",
4655
+ url: frame.url
4656
+ });
4657
+ }
4658
+ }));
4659
+ return { startedAt: this.startedAt, url: initialUrl };
4660
+ }
4661
+ async stop() {
4662
+ if (!this.recording) {
4663
+ throw new Error("Action recorder is not running on this tab");
4664
+ }
4665
+ this.recording = false;
4666
+ const durationMs = Date.now() - this.startedAt;
4667
+ for (const off of this.unsubs)
4668
+ off();
4669
+ this.unsubs = [];
4670
+ if (this.scriptId) {
4671
+ await this.session.send("Page.removeScriptToEvaluateOnNewDocument", { identifier: this.scriptId }).catch(() => {
4672
+ });
4673
+ this.scriptId = null;
4674
+ }
4675
+ await this.session.send("Runtime.evaluate", { expression: "globalThis.__bpActionRecorderEnabled = false;" }).catch(() => {
4676
+ });
4677
+ return buildActionRecordingResult(this.steps, durationMs);
4678
+ }
4679
+ dispose() {
4680
+ this.recording = false;
4681
+ for (const off of this.unsubs)
4682
+ off();
4683
+ this.unsubs = [];
4684
+ }
4685
+ };
4686
+
3945
4687
  // ../core/dist/tab.js
3946
4688
  var BrowserPilotTab = class {
3947
4689
  tabId;
@@ -3956,6 +4698,8 @@ var BrowserPilotTab = class {
3956
4698
  editor;
3957
4699
  performance;
3958
4700
  recorder;
4701
+ downloads;
4702
+ actionRecorder;
3959
4703
  initialized = false;
3960
4704
  constructor(transport, tabId) {
3961
4705
  this.tabId = tabId;
@@ -3970,6 +4714,8 @@ var BrowserPilotTab = class {
3970
4714
  this.editor = new LiveEditor(this.session, this.debugger);
3971
4715
  this.performance = new PerformanceProfiler(this.session);
3972
4716
  this.recorder = new ScreenRecorder(this.session);
4717
+ this.downloads = new DownloadManager(this.session);
4718
+ this.actionRecorder = new ActionRecorder(this.session);
3973
4719
  }
3974
4720
  async ensureInitialized() {
3975
4721
  if (this.initialized)
@@ -4013,6 +4759,8 @@ var BrowserPilotTab = class {
4013
4759
  dispose() {
4014
4760
  void this.recorder.cancel().catch(() => {
4015
4761
  });
4762
+ this.downloads.dispose();
4763
+ this.actionRecorder.dispose();
4016
4764
  this.console.dispose();
4017
4765
  this.network.dispose();
4018
4766
  this.styles.dispose();
@@ -4054,6 +4802,9 @@ var SessionManager = class {
4054
4802
  getTransport() {
4055
4803
  return this.transport;
4056
4804
  }
4805
+ getAttachedTabCount() {
4806
+ return this.tabs.size;
4807
+ }
4057
4808
  async getOrAttachTab(tabId, options) {
4058
4809
  await this.transport.attachTab(tabId, options);
4059
4810
  let tab = this.tabs.get(tabId);
@@ -4107,7 +4858,8 @@ var SessionManager = class {
4107
4858
  session.activeTabId = void 0;
4108
4859
  }
4109
4860
  const allTabs = await this.listTabs();
4110
- const candidate = allTabs.find((t) => t.active && !t.url.startsWith("chrome://")) ?? allTabs.find((t) => !t.url.startsWith("chrome://"));
4861
+ const attachable = allTabs.filter((t) => !isRestrictedUrl(t.url));
4862
+ const candidate = attachable.find((t) => t.active && /^https?:\/\//i.test(t.url)) ?? attachable.find((t) => t.active) ?? attachable.find((t) => /^https?:\/\//i.test(t.url)) ?? attachable[0];
4111
4863
  if (candidate) {
4112
4864
  const tab = await this.getOrAttachTab(candidate.tabId, groupOpts);
4113
4865
  if (session)
@@ -4297,6 +5049,16 @@ var SessionManager = class {
4297
5049
  const t = await getTab(tab);
4298
5050
  return await t.session.send(method, params);
4299
5051
  },
5052
+ downloads: {
5053
+ configure: async (downloadDir, tab) => (await getTab(tab)).downloads.configure(downloadDir),
5054
+ list: async (tab) => (await getTab(tab)).downloads.list(),
5055
+ waitFor: async (opts) => (await getTab(opts?.tab)).downloads.waitForDownload(opts)
5056
+ },
5057
+ actionRecorder: {
5058
+ start: async (opts) => (await getTab(opts?.tab)).actionRecorder.start(opts),
5059
+ stop: async (tab) => (await getTab(tab)).actionRecorder.stop(),
5060
+ steps: async (tab) => (await getTab(tab)).actionRecorder.getSteps()
5061
+ },
4300
5062
  createDemoVideo
4301
5063
  };
4302
5064
  const context = vm.createContext(helpers);
@@ -4340,6 +5102,16 @@ ${code}
4340
5102
  function textResult(text, meta) {
4341
5103
  return { content: [{ type: "text", text }], meta };
4342
5104
  }
5105
+ function normalizeNavigationUrl(raw) {
5106
+ const trimmed = (raw ?? "").trim();
5107
+ if (!trimmed) return "about:blank";
5108
+ if (/^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(trimmed)) {
5109
+ return `http://${trimmed}`;
5110
+ }
5111
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed)) return trimmed;
5112
+ if (/^(about|data|file|javascript|mailto|blob|view-source):/i.test(trimmed)) return trimmed;
5113
+ return `https://${trimmed}`;
5114
+ }
4343
5115
  function formatFeedbackSuffix(fb) {
4344
5116
  const parts = [`URL: ${fb.url}`];
4345
5117
  if (fb.newConsoleErrors.length > 0) {
@@ -4934,7 +5706,7 @@ var TOOL_DEFINITIONS = [
4934
5706
  },
4935
5707
  {
4936
5708
  name: "browser_record",
4937
- description: "Record the active tab as an MP4/WebM video via CDP screencast + ffmpeg, or speed up a recording into a demo video.",
5709
+ description: "Record the active tab as an MP4/WebM video via CDP screencast + ffmpeg (optional page audio capture), or create a smart idle-sped-up demo video.",
4938
5710
  inputSchema: {
4939
5711
  type: "object",
4940
5712
  properties: {
@@ -4942,7 +5714,43 @@ var TOOL_DEFINITIONS = [
4942
5714
  outputPath: { type: "string" },
4943
5715
  recordingPath: { type: "string" },
4944
5716
  frameRate: { type: "number" },
4945
- speed: { type: "number" },
5717
+ audio: { type: "boolean", description: "Tap page <audio>/<video>/AudioContext into the recording (default false)" },
5718
+ speed: { type: "number", description: "Speed multiplier for idle gaps (default 6 when actionTimestamps given, else 2)" },
5719
+ durationMs: { type: "number" },
5720
+ actionTimestamps: { type: "array", items: { type: "number" }, description: "Timestamps from stop() so only idle gaps are sped up while interactions stay 1x" },
5721
+ paddingMs: { type: "number" },
5722
+ tabId: { type: "number" },
5723
+ sessionId: { type: "string" }
5724
+ },
5725
+ required: ["action"]
5726
+ }
5727
+ },
5728
+ {
5729
+ name: "browser_downloads",
5730
+ description: "Configure download directory, list downloads, or wait for a file download to finish and return its local file path.",
5731
+ inputSchema: {
5732
+ type: "object",
5733
+ properties: {
5734
+ action: { type: "string", enum: ["configure", "list", "wait", "clear"] },
5735
+ downloadDir: { type: "string", description: "Target folder for Direct CDP downloads" },
5736
+ filenamePattern: { type: "string", description: "Optional substring/regex to match downloaded filename" },
5737
+ timeoutMs: { type: "number" },
5738
+ sinceTimestamp: { type: "number" },
5739
+ tabId: { type: "number" },
5740
+ sessionId: { type: "string" }
5741
+ },
5742
+ required: ["action"]
5743
+ }
5744
+ },
5745
+ {
5746
+ name: "browser_action_recorder",
5747
+ description: "Record live user interactions (clicks, fills, selects, keys, scrolls, navigations) across page loads and generate reusable browser_batch steps, exec JS script, and Agent Skill Markdown.",
5748
+ inputSchema: {
5749
+ type: "object",
5750
+ properties: {
5751
+ action: { type: "string", enum: ["start", "stop", "status"] },
5752
+ maskPasswords: { type: "boolean", description: "Mask password inputs as <REDACTED_PASSWORD> (default true)" },
5753
+ format: { type: "string", enum: ["all", "batch", "script", "skill"] },
4946
5754
  tabId: { type: "number" },
4947
5755
  sessionId: { type: "string" }
4948
5756
  },
@@ -5031,15 +5839,23 @@ async function executeTool(ctx, name, args = {}) {
5031
5839
  return textResult(formatted || "(no tabs open)", { tabs });
5032
5840
  }
5033
5841
  case "browser_open_tab": {
5842
+ const targetUrl = normalizeNavigationUrl(args.url);
5034
5843
  const tab = await manager.openTab({
5035
- url: args.url,
5844
+ url: targetUrl,
5036
5845
  active: args.active,
5037
5846
  tabGroup: args.tabGroup,
5038
5847
  tabGroupColor: args.tabGroupColor
5039
5848
  });
5040
5849
  if (sessionId) manager.getOrCreateSession(sessionId).activeTabId = tab.tabId;
5041
- const meta = await tab.page.getUrlAndTitle().catch(() => ({ url: String(args.url ?? "about:blank"), title: "" }));
5042
- return textResult(`Opened and attached tab [${tab.tabId}]: ${meta.url}`, { tabId: tab.tabId, ...meta });
5850
+ if (/^https?:\/\//i.test(targetUrl)) {
5851
+ await waitForPageLoad(tab.session, { timeoutMs: 6e3, idleMs: 200 }).catch(() => {
5852
+ });
5853
+ }
5854
+ const meta = await tab.page.getUrlAndTitle().catch(() => ({ url: targetUrl, title: "" }));
5855
+ return textResult(`Opened and attached tab [${tab.tabId}]: ${meta.url}${meta.title ? ` ("${meta.title}")` : ""}`, {
5856
+ tabId: tab.tabId,
5857
+ ...meta
5858
+ });
5043
5859
  }
5044
5860
  case "browser_close_tab": {
5045
5861
  await manager.closeTab(Number(args.tabId));
@@ -5062,8 +5878,9 @@ async function executeTool(ctx, name, args = {}) {
5062
5878
  }
5063
5879
  case "browser_navigate": {
5064
5880
  const tab = await resolveTab();
5881
+ const targetUrl = normalizeNavigationUrl(String(args.url));
5065
5882
  const { result, feedback } = await tab.runWithFeedback(
5066
- () => tab.page.navigate(String(args.url), {
5883
+ () => tab.page.navigate(targetUrl, {
5067
5884
  waitUntil: args.waitUntil ?? "domcontentloaded",
5068
5885
  timeoutMs: args.timeoutMs
5069
5886
  })
@@ -5519,9 +6336,10 @@ ${formatFeedbackSuffix(feedback)}`);
5519
6336
  if (action === "start") {
5520
6337
  const out = await tab.recorder.start({
5521
6338
  outputPath: String(args.outputPath ?? `./browserpilot-recording-${Date.now()}.mp4`),
5522
- frameRate: args.frameRate
6339
+ frameRate: args.frameRate,
6340
+ audio: args.audio
5523
6341
  });
5524
- return textResult(`Recording started -> ${out.outputPath}`);
6342
+ return textResult(`Recording started -> ${out.outputPath}${out.audio ? " (audio tap enabled)" : ""}`);
5525
6343
  }
5526
6344
  if (action === "stop") {
5527
6345
  const res = await tab.recorder.stop();
@@ -5535,12 +6353,71 @@ ${formatFeedbackSuffix(feedback)}`);
5535
6353
  const out = await createDemoVideo({
5536
6354
  recordingPath: String(args.recordingPath),
5537
6355
  outputPath: args.outputPath,
5538
- speed: args.speed
6356
+ speed: args.speed,
6357
+ durationMs: args.durationMs,
6358
+ actionTimestamps: args.actionTimestamps,
6359
+ paddingMs: args.paddingMs
5539
6360
  });
5540
6361
  return textResult(`Created demo video -> ${out}`);
5541
6362
  }
5542
6363
  throw new Error(`Unknown record action: ${action}`);
5543
6364
  }
6365
+ case "browser_downloads": {
6366
+ const tab = await resolveTab();
6367
+ const action = String(args.action);
6368
+ if (action === "configure") {
6369
+ const res = await tab.downloads.configure(args.downloadDir);
6370
+ return textResult(JSON.stringify(res, null, 2));
6371
+ }
6372
+ if (action === "list") {
6373
+ const list = await tab.downloads.list();
6374
+ return textResult(JSON.stringify(list, null, 2));
6375
+ }
6376
+ if (action === "wait") {
6377
+ const entry = await tab.downloads.waitForDownload({
6378
+ timeoutMs: args.timeoutMs,
6379
+ filenamePattern: args.filenamePattern,
6380
+ sinceTimestamp: args.sinceTimestamp
6381
+ });
6382
+ return textResult(JSON.stringify(entry, null, 2));
6383
+ }
6384
+ if (action === "clear") {
6385
+ tab.downloads.clear();
6386
+ return textResult("Cleared tracked downloads");
6387
+ }
6388
+ throw new Error(`Unknown downloads action: ${action}`);
6389
+ }
6390
+ case "browser_action_recorder": {
6391
+ const tab = await resolveTab();
6392
+ const action = String(args.action);
6393
+ if (action === "start") {
6394
+ const res = await tab.actionRecorder.start({
6395
+ maskPasswords: args.maskPasswords
6396
+ });
6397
+ return textResult(`Action recording started on ${res.url || `tab [${tab.tabId}]`}`);
6398
+ }
6399
+ if (action === "status") {
6400
+ return textResult(
6401
+ JSON.stringify(
6402
+ {
6403
+ recording: tab.actionRecorder.isRecording(),
6404
+ recordedSteps: tab.actionRecorder.getSteps().length
6405
+ },
6406
+ null,
6407
+ 2
6408
+ )
6409
+ );
6410
+ }
6411
+ if (action === "stop") {
6412
+ const res = await tab.actionRecorder.stop();
6413
+ const fmt = String(args.format ?? "all");
6414
+ if (fmt === "skill") return textResult(res.skillMarkdown);
6415
+ if (fmt === "script") return textResult(res.execScript);
6416
+ if (fmt === "batch") return textResult(JSON.stringify(res.batchSteps, null, 2));
6417
+ return textResult(JSON.stringify(res, null, 2));
6418
+ }
6419
+ throw new Error(`Unknown action_recorder action: ${action}`);
6420
+ }
5544
6421
  case "browser_exec": {
5545
6422
  const res = await manager.exec(sessionId ?? "default", String(args.code), {
5546
6423
  timeoutMs: args.timeoutMs,
@@ -5767,6 +6644,15 @@ var BrowserPilotDaemon = class {
5767
6644
  };
5768
6645
  this.backends.set(clientId, { info, transport, manager });
5769
6646
  this.primaryClientId = clientId;
6647
+ if (ws.readyState === ws.OPEN) {
6648
+ ws.send(
6649
+ JSON.stringify({
6650
+ type: "event",
6651
+ event: "bridge.ready",
6652
+ params: { version: BROWSERPILOT_VERSION, clientId }
6653
+ })
6654
+ );
6655
+ }
5770
6656
  ws.on("close", () => {
5771
6657
  manager.dispose();
5772
6658
  this.backends.delete(clientId);
@@ -5809,7 +6695,10 @@ var BrowserPilotDaemon = class {
5809
6695
  return info;
5810
6696
  }
5811
6697
  listClients() {
5812
- return Array.from(this.backends.values()).map((b) => b.info);
6698
+ return Array.from(this.backends.values()).map((b) => ({
6699
+ ...b.info,
6700
+ attachedTabCount: b.manager.getAttachedTabCount()
6701
+ }));
5813
6702
  }
5814
6703
  getManager(clientId) {
5815
6704
  const targetId = clientId ?? this.primaryClientId;
@@ -5842,6 +6731,7 @@ var BrowserPilotDaemon = class {
5842
6731
  this.sendJson(res, 200, {
5843
6732
  ok: true,
5844
6733
  version: BROWSERPILOT_VERSION,
6734
+ pid: process.pid,
5845
6735
  uptimeMs: Date.now() - this.startedAt,
5846
6736
  clients: this.listClients()
5847
6737
  });
@@ -5974,14 +6864,27 @@ async function startMcpServer(options = {}) {
5974
6864
  };
5975
6865
  result = await executeTool(ctx, name, args);
5976
6866
  } else {
5977
- if (!daemonClient) {
5978
- daemonClient = await DaemonClient.connectOrStart({
5979
- host: options.daemonHost,
5980
- port: options.daemonPort,
5981
- token: options.daemonToken
5982
- });
6867
+ const ensureDaemon = async () => {
6868
+ if (!daemonClient) {
6869
+ daemonClient = await DaemonClient.connectOrStart({
6870
+ host: options.daemonHost,
6871
+ port: options.daemonPort,
6872
+ token: options.daemonToken
6873
+ });
6874
+ }
6875
+ return daemonClient;
6876
+ };
6877
+ try {
6878
+ result = await (await ensureDaemon()).callTool(name, args);
6879
+ } catch (err) {
6880
+ const msg = err instanceof Error ? err.message : String(err);
6881
+ if (/fetch failed|ECONNREFUSED|ECONNRESET|socket|Unauthorized/i.test(msg)) {
6882
+ daemonClient = null;
6883
+ result = await (await ensureDaemon()).callTool(name, args);
6884
+ } else {
6885
+ throw err;
6886
+ }
5983
6887
  }
5984
- result = await daemonClient.callTool(name, args);
5985
6888
  }
5986
6889
  return {
5987
6890
  isError: result.isError,
@@ -5998,41 +6901,189 @@ async function startMcpServer(options = {}) {
5998
6901
  }
5999
6902
 
6000
6903
  // src/native-install.ts
6001
- import fs4 from "node:fs/promises";
6002
- import os2 from "node:os";
6003
- import path5 from "node:path";
6904
+ import crypto3 from "node:crypto";
6905
+ import fs5 from "node:fs/promises";
6906
+ import os4 from "node:os";
6907
+ import path6 from "node:path";
6004
6908
  import { fileURLToPath as fileURLToPath2 } from "node:url";
6005
- var __dirname2 = path5.dirname(fileURLToPath2(import.meta.url));
6909
+ var __dirname2 = path6.dirname(fileURLToPath2(import.meta.url));
6006
6910
  function getNativeMessagingHostDirs(platform = process.platform) {
6007
- const home = os2.homedir();
6911
+ const home = os4.homedir();
6008
6912
  if (platform === "darwin") {
6009
- const appSupport = path5.join(home, "Library", "Application Support");
6913
+ const appSupport = path6.join(home, "Library", "Application Support");
6010
6914
  return [
6011
- { name: "Google Chrome", dir: path5.join(appSupport, "Google", "Chrome", "NativeMessagingHosts") },
6012
- { name: "Google Chrome Canary", dir: path5.join(appSupport, "Google", "Chrome Canary", "NativeMessagingHosts") },
6013
- { name: "Google Chrome for Testing", dir: path5.join(appSupport, "Google", "Chrome for Testing", "NativeMessagingHosts") },
6014
- { name: "Chromium", dir: path5.join(appSupport, "Chromium", "NativeMessagingHosts") },
6015
- { name: "Brave", dir: path5.join(appSupport, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts") },
6016
- { name: "Microsoft Edge", dir: path5.join(appSupport, "Microsoft Edge", "NativeMessagingHosts") },
6017
- { name: "Arc", dir: path5.join(appSupport, "Arc", "User Data", "NativeMessagingHosts") }
6915
+ {
6916
+ name: "Google Chrome",
6917
+ userDataDir: path6.join(appSupport, "Google", "Chrome"),
6918
+ dir: path6.join(appSupport, "Google", "Chrome", "NativeMessagingHosts")
6919
+ },
6920
+ {
6921
+ name: "Google Chrome Canary",
6922
+ userDataDir: path6.join(appSupport, "Google", "Chrome Canary"),
6923
+ dir: path6.join(appSupport, "Google", "Chrome Canary", "NativeMessagingHosts")
6924
+ },
6925
+ {
6926
+ name: "Google Chrome for Testing",
6927
+ userDataDir: path6.join(appSupport, "Google", "Chrome for Testing"),
6928
+ dir: path6.join(appSupport, "Google", "Chrome for Testing", "NativeMessagingHosts")
6929
+ },
6930
+ {
6931
+ name: "Chromium",
6932
+ userDataDir: path6.join(appSupport, "Chromium"),
6933
+ dir: path6.join(appSupport, "Chromium", "NativeMessagingHosts")
6934
+ },
6935
+ {
6936
+ name: "Brave",
6937
+ userDataDir: path6.join(appSupport, "BraveSoftware", "Brave-Browser"),
6938
+ dir: path6.join(appSupport, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts")
6939
+ },
6940
+ {
6941
+ name: "Microsoft Edge",
6942
+ userDataDir: path6.join(appSupport, "Microsoft Edge"),
6943
+ dir: path6.join(appSupport, "Microsoft Edge", "NativeMessagingHosts")
6944
+ },
6945
+ {
6946
+ name: "Arc",
6947
+ userDataDir: path6.join(appSupport, "Arc", "User Data"),
6948
+ dir: path6.join(appSupport, "Arc", "User Data", "NativeMessagingHosts")
6949
+ }
6018
6950
  ];
6019
6951
  }
6020
6952
  if (platform === "linux") {
6021
- const config = path5.join(home, ".config");
6953
+ const config = path6.join(home, ".config");
6022
6954
  return [
6023
- { name: "Google Chrome", dir: path5.join(config, "google-chrome", "NativeMessagingHosts") },
6024
- { name: "Chromium", dir: path5.join(config, "chromium", "NativeMessagingHosts") },
6025
- { name: "Brave", dir: path5.join(config, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts") },
6026
- { name: "Microsoft Edge", dir: path5.join(config, "microsoft-edge", "NativeMessagingHosts") }
6955
+ {
6956
+ name: "Google Chrome",
6957
+ userDataDir: path6.join(config, "google-chrome"),
6958
+ dir: path6.join(config, "google-chrome", "NativeMessagingHosts")
6959
+ },
6960
+ {
6961
+ name: "Chromium",
6962
+ userDataDir: path6.join(config, "chromium"),
6963
+ dir: path6.join(config, "chromium", "NativeMessagingHosts")
6964
+ },
6965
+ {
6966
+ name: "Brave",
6967
+ userDataDir: path6.join(config, "BraveSoftware", "Brave-Browser"),
6968
+ dir: path6.join(config, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts")
6969
+ },
6970
+ {
6971
+ name: "Microsoft Edge",
6972
+ userDataDir: path6.join(config, "microsoft-edge"),
6973
+ dir: path6.join(config, "microsoft-edge", "NativeMessagingHosts")
6974
+ }
6027
6975
  ];
6028
6976
  }
6029
6977
  return [];
6030
6978
  }
6979
+ function computeChromeExtensionId(unpackedDir) {
6980
+ const normalized = path6.resolve(unpackedDir);
6981
+ const hash = crypto3.createHash("sha256").update(normalized, "utf8").digest("hex").slice(0, 32);
6982
+ return hash.replace(/[0-9a-f]/g, (ch) => String.fromCharCode(97 + Number.parseInt(ch, 16)));
6983
+ }
6984
+ function getStableExtensionDir() {
6985
+ return path6.join(getBrowserPilotHomeDir(), "extension");
6986
+ }
6987
+ async function syncExtensionToHome(sourceExtDir, options = {}) {
6988
+ const destDir = getStableExtensionDir();
6989
+ let version = null;
6990
+ try {
6991
+ const manifestRaw = await fs5.readFile(path6.join(sourceExtDir, "manifest.json"), "utf8");
6992
+ const manifest = JSON.parse(manifestRaw);
6993
+ version = manifest.version ?? null;
6994
+ } catch {
6995
+ }
6996
+ let synced = false;
6997
+ if (!options.dryRun) {
6998
+ await ensureBrowserPilotHome();
6999
+ const resolvedSrc = await fs5.realpath(sourceExtDir).catch(() => path6.resolve(sourceExtDir));
7000
+ const resolvedDest = await fs5.realpath(destDir).catch(() => path6.resolve(destDir));
7001
+ if (resolvedSrc !== resolvedDest) {
7002
+ await fs5.rm(destDir, { recursive: true, force: true });
7003
+ await fs5.cp(sourceExtDir, destDir, { recursive: true });
7004
+ synced = true;
7005
+ }
7006
+ }
7007
+ const realDest = await fs5.realpath(destDir).catch(() => path6.resolve(destDir));
7008
+ return {
7009
+ extensionDir: realDest,
7010
+ extensionId: computeChromeExtensionId(realDest),
7011
+ version,
7012
+ synced
7013
+ };
7014
+ }
7015
+ async function discoverInstalledExtensionIds(platform = process.platform) {
7016
+ const found = [];
7017
+ const seen = /* @__PURE__ */ new Set();
7018
+ for (const target of getNativeMessagingHostDirs(platform)) {
7019
+ let entries;
7020
+ try {
7021
+ entries = await fs5.readdir(target.userDataDir);
7022
+ } catch {
7023
+ continue;
7024
+ }
7025
+ const profiles = entries.filter((e) => e === "Default" || e.startsWith("Profile "));
7026
+ for (const profile of profiles) {
7027
+ for (const fileName of ["Secure Preferences", "Preferences"]) {
7028
+ const prefPath = path6.join(target.userDataDir, profile, fileName);
7029
+ let parsed;
7030
+ try {
7031
+ parsed = JSON.parse(await fs5.readFile(prefPath, "utf8"));
7032
+ } catch {
7033
+ continue;
7034
+ }
7035
+ const settings = parsed.extensions?.settings;
7036
+ if (!settings || typeof settings !== "object") continue;
7037
+ for (const [extId, meta] of Object.entries(settings)) {
7038
+ if (!meta || !/^[a-p]{32}$/.test(extId)) continue;
7039
+ const manifestName = meta.manifest?.name || "";
7040
+ const extPath = meta.path || "";
7041
+ let isBrowserPilot = /^browserpilot$/i.test(manifestName) || /browserpilot/i.test(extPath);
7042
+ if (!isBrowserPilot && meta.location === 4 && extPath) {
7043
+ try {
7044
+ const m = JSON.parse(await fs5.readFile(path6.join(extPath, "manifest.json"), "utf8"));
7045
+ if (/^browserpilot$/i.test(m.name || "")) isBrowserPilot = true;
7046
+ } catch {
7047
+ }
7048
+ }
7049
+ if (isBrowserPilot && !seen.has(extId)) {
7050
+ seen.add(extId);
7051
+ found.push({ browser: target.name, profile, extensionId: extId, path: extPath || void 0 });
7052
+ }
7053
+ }
7054
+ }
7055
+ }
7056
+ }
7057
+ return found;
7058
+ }
7059
+ async function readInstalledNativeHosts(platform = process.platform) {
7060
+ const results = [];
7061
+ for (const target of getNativeMessagingHostDirs(platform)) {
7062
+ const mp = path6.join(target.dir, `${NATIVE_HOST_NAME}.json`);
7063
+ try {
7064
+ const parsed = JSON.parse(await fs5.readFile(mp, "utf8"));
7065
+ results.push({
7066
+ browser: target.name,
7067
+ installed: true,
7068
+ path: mp,
7069
+ allowedOrigins: Array.isArray(parsed.allowed_origins) ? parsed.allowed_origins : [],
7070
+ wrapperPath: parsed.path
7071
+ });
7072
+ } catch {
7073
+ results.push({ browser: target.name, installed: false, path: mp, allowedOrigins: [] });
7074
+ }
7075
+ }
7076
+ return results;
7077
+ }
6031
7078
  async function installNativeHost(options) {
6032
- const nativeHostJs = path5.resolve(__dirname2, "native-host.js");
6033
- const binDir = path5.join(getBrowserPilotHomeDir(), "bin");
6034
- const wrapperPath = path5.join(binDir, "browserpilot-native-host");
6035
- const allowedOrigins = options.extensionIds.map((id) => id.trim()).filter(Boolean).map((id) => id.startsWith("chrome-extension://") ? id : `chrome-extension://${id}/`);
7079
+ const nativeHostJs = path6.resolve(__dirname2, "native-host.js");
7080
+ const binDir = path6.join(getBrowserPilotHomeDir(), "bin");
7081
+ const wrapperPath = path6.join(binDir, "browserpilot-native-host");
7082
+ const allowedOrigins = Array.from(
7083
+ new Set(
7084
+ options.extensionIds.map((id) => id.trim()).filter(Boolean).map((id) => id.startsWith("chrome-extension://") ? id.endsWith("/") ? id : `${id}/` : `chrome-extension://${id}/`)
7085
+ )
7086
+ );
6036
7087
  const manifestJson = {
6037
7088
  name: NATIVE_HOST_NAME,
6038
7089
  description: "BrowserPilot Zero-Click Browser Control & DevTools Bridge",
@@ -6047,30 +7098,30 @@ exec ${JSON.stringify(process.execPath)} ${JSON.stringify(nativeHostJs)} "$@"
6047
7098
  const installedManifests = [];
6048
7099
  if (!options.dryRun) {
6049
7100
  await ensureBrowserPilotHome();
6050
- await fs4.mkdir(binDir, { recursive: true, mode: 448 });
6051
- await fs4.writeFile(wrapperPath, wrapperScript, { mode: 493 });
7101
+ await fs5.mkdir(binDir, { recursive: true, mode: 448 });
7102
+ await fs5.writeFile(wrapperPath, wrapperScript, { mode: 493 });
6052
7103
  for (const target of targets) {
6053
- const parentDir = path5.dirname(target.dir);
7104
+ const parentDir = path6.dirname(target.dir);
6054
7105
  let exists = target.name === "Google Chrome";
6055
7106
  if (!exists) {
6056
7107
  try {
6057
- await fs4.access(parentDir);
7108
+ await fs5.access(parentDir);
6058
7109
  exists = true;
6059
7110
  } catch {
6060
7111
  exists = false;
6061
7112
  }
6062
7113
  }
6063
7114
  if (!exists) continue;
6064
- await fs4.mkdir(target.dir, { recursive: true });
6065
- const manifestPath = path5.join(target.dir, `${NATIVE_HOST_NAME}.json`);
6066
- await fs4.writeFile(manifestPath, JSON.stringify(manifestJson, null, 2) + "\n", "utf8");
7115
+ await fs5.mkdir(target.dir, { recursive: true });
7116
+ const manifestPath = path6.join(target.dir, `${NATIVE_HOST_NAME}.json`);
7117
+ await fs5.writeFile(manifestPath, JSON.stringify(manifestJson, null, 2) + "\n", "utf8");
6067
7118
  installedManifests.push({ browser: target.name, manifestPath });
6068
7119
  }
6069
7120
  } else {
6070
7121
  for (const target of targets) {
6071
7122
  installedManifests.push({
6072
7123
  browser: target.name,
6073
- manifestPath: path5.join(target.dir, `${NATIVE_HOST_NAME}.json`)
7124
+ manifestPath: path6.join(target.dir, `${NATIVE_HOST_NAME}.json`)
6074
7125
  });
6075
7126
  }
6076
7127
  }
@@ -6103,7 +7154,9 @@ BrowserPilot controls your real logged-in Chrome browser (existing cookies, logi
6103
7154
  - \`browser_live_edit\` \u2014 grep loaded scripts and live-patch JS/CSS in memory.
6104
7155
  - \`browser_performance\` \u2014 Core Web Vitals (LCP/CLS/FCP/TTFB), heap summary, CPU profiler, Tracing insights.
6105
7156
  - \`browser_emulate\` \u2014 viewport, mobile, dark mode, CPU throttling, Slow 3G / offline.
6106
- - \`browser_record\` \u2014 record MP4/WebM screencast video via \`ffmpeg\`.
7157
+ - \`browser_downloads\` \u2014 configure download folder, list downloads, or wait for a file download to complete with its local path.
7158
+ - \`browser_action_recorder\` \u2014 record user clicks/fills/selects/navigations into reusable batch steps, exec JS script, and Agent Skill Markdown.
7159
+ - \`browser_record\` \u2014 record MP4/WebM screencast video via \`ffmpeg\` (optional \`audio: true\`) and create smart idle-sped-up demo videos.
6107
7160
  6. **Multi-step Stateful Sandbox (Playwriter replacement)**:
6108
7161
  - \`browserpilot session new --tab-group docs\` -> returns session ID (e.g. \`1\`)
6109
7162
  - \`browserpilot exec -s 1 -e 'const t = await tabs.open("https://example.com"); console.log(await snapshot({ tab: t }))'\`
@@ -6115,7 +7168,7 @@ BrowserPilot controls your real logged-in Chrome browser (existing cookies, logi
6115
7168
  `;
6116
7169
 
6117
7170
  // src/cli.ts
6118
- var __dirname3 = path6.dirname(fileURLToPath3(import.meta.url));
7171
+ var __dirname3 = path7.dirname(fileURLToPath3(import.meta.url));
6119
7172
  function parseFlags(argv) {
6120
7173
  const positional = [];
6121
7174
  const flags = {};
@@ -6162,42 +7215,77 @@ function printToolOutput(res) {
6162
7215
  if (res.isError) process.exitCode = 1;
6163
7216
  }
6164
7217
  async function getExtensionDistPath() {
6165
- const bundled = path6.resolve(__dirname3, "..", "extension");
7218
+ const bundled = path7.resolve(__dirname3, "..", "extension");
6166
7219
  try {
6167
- await fs5.access(path6.join(bundled, "manifest.json"));
7220
+ await fs6.access(path7.join(bundled, "manifest.json"));
6168
7221
  return bundled;
6169
7222
  } catch {
6170
- return path6.resolve(__dirname3, "..", "..", "extension", "dist");
7223
+ return path7.resolve(__dirname3, "..", "..", "extension", "dist");
6171
7224
  }
6172
7225
  }
7226
+ async function findDynamicCachedChrome() {
7227
+ const found = [];
7228
+ const home = os5.homedir();
7229
+ const searchRoots = [
7230
+ path7.join(home, ".cache", "browserpilot-chrome", "chrome"),
7231
+ path7.join(home, "Library", "Caches", "ms-playwright"),
7232
+ path7.join(home, ".cache", "ms-playwright")
7233
+ ];
7234
+ for (const root of searchRoots) {
7235
+ let entries;
7236
+ try {
7237
+ entries = (await fs6.readdir(root)).sort().reverse();
7238
+ } catch {
7239
+ continue;
7240
+ }
7241
+ for (const entry of entries) {
7242
+ if (!entry.startsWith("chromium-") && !entry.startsWith("mac") && !entry.startsWith("linux")) continue;
7243
+ const candidates = [
7244
+ path7.join(root, entry, "chrome-mac-arm64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"),
7245
+ path7.join(root, entry, "chrome-mac-x64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"),
7246
+ path7.join(root, entry, "chrome-linux64", "chrome"),
7247
+ path7.join(root, entry, "chrome-linux", "chrome")
7248
+ ];
7249
+ for (const c of candidates) {
7250
+ try {
7251
+ await fs6.access(c);
7252
+ found.push(c);
7253
+ } catch {
7254
+ }
7255
+ }
7256
+ }
7257
+ }
7258
+ return found;
7259
+ }
6173
7260
  async function findChromeBinary() {
6174
- const candidates = [
7261
+ const staticCandidates = [
6175
7262
  process.env.BROWSERPILOT_CHROME_BIN,
6176
- path6.join(
6177
- os3.homedir(),
6178
- "Library/Caches/ms-playwright/chromium-1248/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
6179
- ),
6180
7263
  "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
7264
+ "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
6181
7265
  "/Applications/Chromium.app/Contents/MacOS/Chromium",
7266
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
6182
7267
  "/usr/bin/google-chrome",
6183
- "/usr/bin/chromium"
7268
+ "/usr/bin/google-chrome-stable",
7269
+ "/usr/bin/chromium",
7270
+ "/usr/bin/chromium-browser"
6184
7271
  ].filter(Boolean);
6185
- for (const bin of candidates) {
7272
+ for (const bin of staticCandidates) {
6186
7273
  try {
6187
- await fs5.access(bin);
7274
+ await fs6.access(bin);
6188
7275
  return bin;
6189
7276
  } catch {
6190
7277
  }
6191
7278
  }
6192
- return null;
7279
+ const cached = await findDynamicCachedChrome();
7280
+ return cached[0] ?? null;
6193
7281
  }
6194
7282
  function printHelp() {
6195
7283
  console.log(`BrowserPilot v${BROWSERPILOT_VERSION} \u2014 Zero-Click Pure-CDP Browser Control & DevTools CLI
6196
7284
 
6197
7285
  Usage:
6198
- browserpilot setup [--extension-id <id>] [--dry-run] Install Native Messaging host & print MCP setup
6199
- browserpilot doctor Diagnose extension, Native Messaging, Chrome, ffmpeg & daemon
6200
- browserpilot daemon start | stop | status | run Manage local authenticated bridge daemon
7286
+ browserpilot setup [--extension-id <id>] [--dry-run] Sync extension, auto-install Native Messaging & print MCP config
7287
+ browserpilot doctor [--json] Diagnose extension, Native Messaging, Chrome, ffmpeg & daemon
7288
+ browserpilot daemon start | stop | restart | status | run Manage local authenticated bridge daemon
6201
7289
  browserpilot mcp [--cdp <url>] Start MCP stdio server (for Claude/Cursor/Codex/Antigravity)
6202
7290
  browserpilot connect-cdp <url> Attach daemon directly to a --remote-debugging-port Chrome
6203
7291
  browserpilot browser start [--headless] [--cdp-port N] Launch Chrome/Chrome for Testing with BrowserPilot ready
@@ -6208,9 +7296,11 @@ Stateful Sessions (Playwriter replacement):
6208
7296
  browserpilot exec -s <id> -e '<js>' | -f <script.js> [--timeout <ms>]
6209
7297
 
6210
7298
  Direct Quick Commands:
7299
+ browserpilot status
6211
7300
  browserpilot tabs
6212
7301
  browserpilot open <url> [--tab-group <name>]
6213
7302
  browserpilot close <tabId>
7303
+ browserpilot navigate <url> [--tab <id>]
6214
7304
  browserpilot snapshot [--tab <id>] [--search <regex>] [--scope <css>] [--full]
6215
7305
  browserpilot click <ref|selector> [--tab <id>]
6216
7306
  browserpilot fill <ref|selector> <value> [--tab <id>]
@@ -6222,6 +7312,8 @@ Direct Quick Commands:
6222
7312
  browserpilot react <ref|selector> [--tab <id>]
6223
7313
  browserpilot eval '<js>' [--tab <id>]
6224
7314
  browserpilot perf [metrics|heap|trace_start|trace_stop|cpu_start|cpu_stop] [--tab <id>]
7315
+ browserpilot downloads [list|wait|clear] [--dir <path>] [--tab <id>]
7316
+ browserpilot record-actions [start|stop|status] [--format all|skill|script|batch] [--tab <id>]
6225
7317
  browserpilot skill Output complete AI agent skill documentation
6226
7318
  `);
6227
7319
  }
@@ -6244,65 +7336,93 @@ async function main() {
6244
7336
  const extDist = await getExtensionDistPath();
6245
7337
  let extBuilt = false;
6246
7338
  try {
6247
- await fs5.access(path6.join(extDist, "manifest.json"));
6248
- await fs5.access(path6.join(extDist, "background.js"));
7339
+ await fs6.access(path7.join(extDist, "manifest.json"));
7340
+ await fs6.access(path7.join(extDist, "background.js"));
6249
7341
  extBuilt = true;
6250
7342
  } catch {
6251
7343
  }
7344
+ const stableExtDir = getStableExtensionDir();
7345
+ let stableExtVersion = null;
7346
+ try {
7347
+ const m = JSON.parse(await fs6.readFile(path7.join(stableExtDir, "manifest.json"), "utf8"));
7348
+ stableExtVersion = m.version ?? null;
7349
+ } catch {
7350
+ }
7351
+ const expectedStableExtId = computeChromeExtensionId(await fs6.realpath(stableExtDir).catch(() => stableExtDir));
6252
7352
  const chromeBin = await findChromeBinary();
6253
7353
  let hasFfmpeg = false;
6254
- for (const dir of (process.env.PATH || "").split(path6.delimiter)) {
7354
+ for (const dir of (process.env.PATH || "").split(path7.delimiter)) {
6255
7355
  if (!dir) continue;
6256
7356
  try {
6257
- await fs5.access(path6.join(dir, process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg"));
7357
+ await fs6.access(path7.join(dir, process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg"));
6258
7358
  hasFfmpeg = true;
6259
7359
  break;
6260
7360
  } catch {
6261
7361
  }
6262
7362
  }
6263
- const nativeHosts = [];
6264
- for (const target of getNativeMessagingHostDirs()) {
6265
- const mp = path6.join(target.dir, `${NATIVE_HOST_NAME}.json`);
6266
- let installed = false;
6267
- try {
6268
- await fs5.access(mp);
6269
- installed = true;
6270
- } catch {
6271
- }
6272
- nativeHosts.push({ browser: target.name, installed, path: mp });
6273
- }
7363
+ const nativeHosts = await readInstalledNativeHosts();
7364
+ const discoveredExts = await discoverInstalledExtensionIds();
6274
7365
  const cfg = await readDaemonConfig();
6275
7366
  const daemonRunning = cfg ? await isDaemonReachable(cfg) : false;
6276
- let connectedClients = 0;
7367
+ let health = null;
6277
7368
  if (daemonRunning && cfg) {
6278
- const h = await new DaemonClient(cfg).health().catch(() => null);
6279
- connectedClients = h?.clients.length ?? 0;
7369
+ health = await new DaemonClient(cfg).health().catch(() => null);
6280
7370
  }
7371
+ const connectedClients = health?.clients ?? [];
7372
+ const versionMismatch = Boolean(health?.version && health.version !== BROWSERPILOT_VERSION);
6281
7373
  const report = {
6282
7374
  version: BROWSERPILOT_VERSION,
6283
7375
  node: process.version,
6284
7376
  extensionBuilt: extBuilt,
6285
7377
  extensionDistPath: extDist,
7378
+ stableExtensionDir: stableExtDir,
7379
+ stableExtensionVersion: stableExtVersion,
7380
+ expectedExtensionId: expectedStableExtId,
7381
+ discoveredChromeExtensions: discoveredExts,
6286
7382
  chromeBinary: chromeBin,
6287
7383
  ffmpegAvailable: hasFfmpeg,
6288
7384
  daemonConfigPresent: Boolean(cfg),
6289
7385
  daemonRunning,
6290
- connectedBrowsers: connectedClients,
6291
- nativeMessagingInstalled: nativeHosts.filter((n) => n.installed).map((n) => n.browser)
7386
+ daemonVersion: health?.version ?? null,
7387
+ daemonPid: health?.pid ?? cfg?.pid ?? null,
7388
+ daemonAddress: cfg ? `${cfg.host}:${cfg.port}` : null,
7389
+ daemonVersionMismatch: versionMismatch,
7390
+ connectedBrowsers: connectedClients.length,
7391
+ clients: connectedClients,
7392
+ nativeMessagingInstalled: nativeHosts.filter((n) => n.installed).map((n) => n.browser),
7393
+ nativeMessagingHosts: nativeHosts.filter((n) => n.installed)
6292
7394
  };
6293
7395
  if (flags.json) {
6294
7396
  console.log(JSON.stringify(report, null, 2));
6295
7397
  return;
6296
7398
  }
6297
7399
  console.log(`BrowserPilot Doctor (v${BROWSERPILOT_VERSION})`);
6298
- console.log(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`);
7400
+ console.log(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`);
6299
7401
  console.log(`Node.js : ${report.node}`);
6300
7402
  console.log(`Extension dist/ : ${extBuilt ? "OK" : "MISSING (run pnpm build)"} (${extDist})`);
7403
+ console.log(
7404
+ `Stable ext copy : ${stableExtVersion ? `v${stableExtVersion} (${stableExtDir}, id: ${expectedStableExtId})` : `Not synced yet (run: browserpilot setup)`}`
7405
+ );
7406
+ console.log(
7407
+ `Chrome loaded : ${discoveredExts.length ? discoveredExts.map((e) => `${e.browser}/${e.profile} (${e.extensionId})`).join(", ") : "Not detected yet (load ~/.browserpilot/extension in chrome://extensions)"}`
7408
+ );
6301
7409
  console.log(`Chrome binary : ${chromeBin ?? "Not found (set BROWSERPILOT_CHROME_BIN)"}`);
6302
7410
  console.log(`ffmpeg : ${hasFfmpeg ? "OK (video recording ready)" : "Not found (optional for recording)"}`);
6303
- console.log(`Daemon status : ${daemonRunning ? `RUNNING (browsers: ${connectedClients})` : "STOPPED"}`);
6304
7411
  console.log(
6305
- `Native Messaging : ${report.nativeMessagingInstalled.length ? `Installed (${report.nativeMessagingInstalled.join(", ")})` : "Not installed (run: browserpilot setup --extension-id <id>)"}`
7412
+ `Daemon status : ${daemonRunning ? `RUNNING v${health?.version ?? "?"} @ ${cfg?.host}:${cfg?.port} (pid: ${health?.pid ?? cfg?.pid ?? "?"}, browsers: ${connectedClients.length})` : "STOPPED"}`
7413
+ );
7414
+ if (versionMismatch) {
7415
+ console.log(
7416
+ ` \u26A0 Version mismatch: CLI is v${BROWSERPILOT_VERSION}, running daemon is v${health?.version}. Run: browserpilot daemon restart`
7417
+ );
7418
+ }
7419
+ for (const c of connectedClients) {
7420
+ console.log(
7421
+ ` \u2022 ${c.browser} [${c.transport}]${c.extensionVersion ? ` ext v${c.extensionVersion}` : ""}${c.extensionId ? ` (${c.extensionId})` : ""} \u2014 attached tabs: ${c.attachedTabCount}`
7422
+ );
7423
+ }
7424
+ console.log(
7425
+ `Native Messaging : ${report.nativeMessagingInstalled.length ? `Installed (${report.nativeMessagingInstalled.join(", ")})` : "Not installed (run: browserpilot setup)"}`
6306
7426
  );
6307
7427
  return;
6308
7428
  }
@@ -6318,33 +7438,52 @@ async function main() {
6318
7438
  if (cmd === "setup") {
6319
7439
  const cfg = await loadOrCreateDaemonConfig();
6320
7440
  const extDist = await getExtensionDistPath();
6321
- const extId = typeof flags["extension-id"] === "string" ? flags["extension-id"] : "";
7441
+ const explicitExtId = typeof flags["extension-id"] === "string" ? flags["extension-id"] : "";
6322
7442
  const dryRun = Boolean(flags["dry-run"]);
7443
+ const skipNative = Boolean(flags["no-native-host"]);
7444
+ const synced = await syncExtensionToHome(extDist, { dryRun });
7445
+ const discovered = await discoverInstalledExtensionIds();
7446
+ const bundledReal = await fs6.realpath(extDist).catch(() => path7.resolve(extDist));
7447
+ const bundledExtId = computeChromeExtensionId(bundledReal);
7448
+ const allExtIds = Array.from(
7449
+ new Set(
7450
+ [
7451
+ synced.extensionId,
7452
+ bundledExtId,
7453
+ ...discovered.map((d) => d.extensionId),
7454
+ ...explicitExtId.split(",").map((s) => s.trim())
7455
+ ].filter(Boolean)
7456
+ )
7457
+ );
6323
7458
  console.log(`
6324
7459
  BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
6325
7460
  console.log(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`);
6326
- console.log(`1. Unpacked Extension Path:
6327
- ${extDist}`);
6328
- console.log(` -> Open chrome://extensions -> Enable "Developer mode" -> "Load unpacked" -> select the path above.`);
7461
+ console.log(`1. Stable Unpacked Extension Path (upgrade-safe):`);
7462
+ console.log(` ${synced.extensionDir}`);
7463
+ console.log(` Expected Chrome Extension ID : ${synced.extensionId}`);
7464
+ if (discovered.length > 0) {
7465
+ console.log(
7466
+ ` Already detected in Chrome : ${discovered.map((d) => `${d.browser}/${d.profile} (${d.extensionId})`).join(", ")}`
7467
+ );
7468
+ } else {
7469
+ console.log(` -> Open chrome://extensions -> Enable "Developer mode" -> "Load unpacked" -> select the path above.`);
7470
+ }
6329
7471
  console.log(`
6330
7472
  2. Local Daemon Config (~/.browserpilot/daemon.json):`);
6331
7473
  console.log(` WebSocket URL : ws://${cfg.host}:${cfg.port}/extension`);
6332
7474
  console.log(` Auth Token : ${cfg.token}`);
6333
- if (extId) {
6334
- const res = await installNativeHost({ extensionIds: [extId], dryRun });
7475
+ if (!skipNative) {
7476
+ const res = await installNativeHost({ extensionIds: allExtIds, dryRun });
6335
7477
  console.log(`
6336
- 3. Chrome Native Messaging Host (${dryRun ? "dry-run" : "installed"}):`);
6337
- console.log(` Wrapper: ${res.wrapperPath}`);
7478
+ 3. Chrome Native Messaging Host (${dryRun ? "dry-run" : "installed automatically"}):`);
7479
+ console.log(` Wrapper : ${res.wrapperPath}`);
7480
+ console.log(` Allowed : ${allExtIds.join(", ")}`);
6338
7481
  for (const m of res.installedManifests) {
6339
7482
  console.log(` - ${m.browser}: ${m.manifestPath}`);
6340
7483
  }
6341
- } else {
6342
- console.log(`
6343
- 3. Optional (Recommended) Native Messaging Auto-Auth:`);
6344
- console.log(` After loading the unpacked extension, copy its Extension ID from chrome://extensions and run:`);
6345
- console.log(` browserpilot setup --extension-id <YOUR_EXTENSION_ID>`);
7484
+ console.log(` -> Zero manual token entry or --extension-id needed! Extension connects automatically once loaded.`);
6346
7485
  }
6347
- const cliBin = path6.resolve(__dirname3, "cli.js");
7486
+ const cliBin = path7.resolve(__dirname3, "cli.js");
6348
7487
  console.log(`
6349
7488
  4. MCP Server Config (Claude Code / Cursor / Codex / Antigravity):`);
6350
7489
  console.log(
@@ -6383,7 +7522,7 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
6383
7522
  if (sub === "start") {
6384
7523
  const client2 = await DaemonClient.connectOrStart();
6385
7524
  const h = await client2.health();
6386
- console.log(`BrowserPilot daemon running on http://${client2.config.host}:${client2.config.port} (clients: ${h.clients.length})`);
7525
+ console.log(`BrowserPilot daemon v${h.version} running on http://${client2.config.host}:${client2.config.port} (clients: ${h.clients.length})`);
6387
7526
  return;
6388
7527
  }
6389
7528
  if (sub === "stop") {
@@ -6396,6 +7535,20 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
6396
7535
  console.log("BrowserPilot daemon stopped.");
6397
7536
  return;
6398
7537
  }
7538
+ if (sub === "restart") {
7539
+ const cfg = await readDaemonConfig();
7540
+ if (cfg && await isDaemonReachable(cfg)) {
7541
+ await new DaemonClient(cfg).shutdown();
7542
+ for (let i = 0; i < 20; i++) {
7543
+ await new Promise((r) => setTimeout(r, 100));
7544
+ if (!await isDaemonReachable(cfg)) break;
7545
+ }
7546
+ }
7547
+ const client2 = await DaemonClient.connectOrStart();
7548
+ const h = await client2.health();
7549
+ console.log(`BrowserPilot daemon restarted (v${h.version}) on http://${client2.config.host}:${client2.config.port} (clients: ${h.clients.length})`);
7550
+ return;
7551
+ }
6399
7552
  if (sub === "status") {
6400
7553
  const cfg = await readDaemonConfig();
6401
7554
  if (!cfg || !await isDaemonReachable(cfg)) {
@@ -6412,8 +7565,8 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
6412
7565
  const chromeBin = await findChromeBinary();
6413
7566
  if (!chromeBin) throw new Error("No Chrome/Chromium binary found. Set BROWSERPILOT_CHROME_BIN.");
6414
7567
  const cdpPort = typeof flags["cdp-port"] === "string" ? Number(flags["cdp-port"]) : 9222;
6415
- const profileDir = typeof flags["user-data-dir"] === "string" ? path6.resolve(flags["user-data-dir"]) : path6.join(os3.homedir(), ".browserpilot", "chrome-profile");
6416
- await fs5.mkdir(profileDir, { recursive: true });
7568
+ const profileDir = typeof flags["user-data-dir"] === "string" ? path7.resolve(flags["user-data-dir"]) : path7.join(os5.homedir(), ".browserpilot", "chrome-profile");
7569
+ await fs6.mkdir(profileDir, { recursive: true });
6417
7570
  const args = [
6418
7571
  "--no-first-run",
6419
7572
  "--no-default-browser-check",
@@ -6489,7 +7642,7 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
6489
7642
  if (cmd === "exec") {
6490
7643
  let code = typeof flags.e === "string" ? flags.e : "";
6491
7644
  if (!code && typeof flags.f === "string") {
6492
- code = await fs5.readFile(path6.resolve(flags.f), "utf8");
7645
+ code = await fs6.readFile(path7.resolve(flags.f), "utf8");
6493
7646
  }
6494
7647
  if (!code) throw new Error('Provide code with -e "<js>" or -f <file>');
6495
7648
  const res = await client.callTool("browser_exec", {
@@ -6502,6 +7655,9 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
6502
7655
  return;
6503
7656
  }
6504
7657
  switch (cmd) {
7658
+ case "status":
7659
+ printToolOutput(await client.callTool("browser_status"));
7660
+ return;
6505
7661
  case "tabs":
6506
7662
  printToolOutput(await client.callTool("browser_tabs"));
6507
7663
  return;
@@ -6598,6 +7754,28 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
6598
7754
  case "perf":
6599
7755
  printToolOutput(await client.callTool("browser_performance", { action: positional[1] || "metrics", tabId, sessionId }));
6600
7756
  return;
7757
+ case "downloads":
7758
+ printToolOutput(
7759
+ await client.callTool("browser_downloads", {
7760
+ action: positional[1] || "list",
7761
+ downloadDir: typeof flags.dir === "string" ? flags.dir : void 0,
7762
+ filenamePattern: typeof flags.pattern === "string" ? flags.pattern : void 0,
7763
+ timeoutMs: typeof flags.timeout === "string" ? Number(flags.timeout) : void 0,
7764
+ tabId,
7765
+ sessionId
7766
+ })
7767
+ );
7768
+ return;
7769
+ case "record-actions":
7770
+ printToolOutput(
7771
+ await client.callTool("browser_action_recorder", {
7772
+ action: positional[1] || "status",
7773
+ format: typeof flags.format === "string" ? flags.format : void 0,
7774
+ tabId,
7775
+ sessionId
7776
+ })
7777
+ );
7778
+ return;
6601
7779
  default:
6602
7780
  throw new Error(`Unknown command "${cmd}". Run "browserpilot --help" for usage.`);
6603
7781
  }