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/README.md +8 -11
- package/dist/cli.js +1304 -126
- package/dist/cli.js.map +4 -4
- package/dist/index.js +1128 -69
- package/dist/index.js.map +4 -4
- package/dist/native-host.js +34 -6
- package/dist/native-host.js.map +2 -2
- package/extension/background.js +69 -3
- package/extension/background.js.map +2 -2
- package/extension/manifest.json +2 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import os from "node:os";
|
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
|
|
7
7
|
// ../protocol/dist/constants.js
|
|
8
|
-
var BROWSERPILOT_VERSION = "1.1
|
|
8
|
+
var BROWSERPILOT_VERSION = "1.2.1";
|
|
9
9
|
var DEFAULT_DAEMON_HOST = "127.0.0.1";
|
|
10
10
|
var DEFAULT_DAEMON_PORT = 19888;
|
|
11
11
|
var NATIVE_HOST_NAME = "com.browserpilot.bridge";
|
|
@@ -29,6 +29,23 @@ var BLOCKED_PROFILE_WIDE_CDP_COMMANDS = /* @__PURE__ */ new Set([
|
|
|
29
29
|
"Network.clearBrowserCookies",
|
|
30
30
|
"Network.clearBrowserCache"
|
|
31
31
|
]);
|
|
32
|
+
var RESTRICTED_URL_PREFIXES = [
|
|
33
|
+
"chrome://",
|
|
34
|
+
"chrome-extension://",
|
|
35
|
+
"chrome-untrusted://",
|
|
36
|
+
"devtools://",
|
|
37
|
+
"edge://",
|
|
38
|
+
"brave://",
|
|
39
|
+
"about:blank#blocked",
|
|
40
|
+
"https://chrome.google.com/webstore",
|
|
41
|
+
"https://chromewebstore.google.com"
|
|
42
|
+
];
|
|
43
|
+
function isRestrictedUrl(url) {
|
|
44
|
+
if (!url)
|
|
45
|
+
return false;
|
|
46
|
+
const lower = url.toLowerCase();
|
|
47
|
+
return RESTRICTED_URL_PREFIXES.some((prefix) => lower.startsWith(prefix));
|
|
48
|
+
}
|
|
32
49
|
function isBlockedProfileWideCommand(method) {
|
|
33
50
|
return BLOCKED_PROFILE_WIDE_CDP_COMMANDS.has(method);
|
|
34
51
|
}
|
|
@@ -507,6 +524,8 @@ var ExtensionBridgeTransport = class {
|
|
|
507
524
|
tabId: Number(params.tabId),
|
|
508
525
|
url: String(params.url ?? "")
|
|
509
526
|
});
|
|
527
|
+
} else if (ev.event === "download.updated" && params.download) {
|
|
528
|
+
this.events.emit("download-event", params.download);
|
|
510
529
|
}
|
|
511
530
|
this.events.emit("extension-event", ev);
|
|
512
531
|
}
|
|
@@ -558,6 +577,14 @@ var ExtensionBridgeTransport = class {
|
|
|
558
577
|
this.events.on("popup-opened", listener);
|
|
559
578
|
return () => this.events.off("popup-opened", listener);
|
|
560
579
|
}
|
|
580
|
+
onDownloadEvent(listener) {
|
|
581
|
+
this.events.on("download-event", listener);
|
|
582
|
+
return () => this.events.off("download-event", listener);
|
|
583
|
+
}
|
|
584
|
+
async listDownloads() {
|
|
585
|
+
const res = await this.rpc("downloads.list");
|
|
586
|
+
return res.downloads ?? [];
|
|
587
|
+
}
|
|
561
588
|
onClose(listener) {
|
|
562
589
|
this.events.on("closed", listener);
|
|
563
590
|
return () => this.events.off("closed", listener);
|
|
@@ -3685,7 +3712,94 @@ var PerformanceProfiler = class {
|
|
|
3685
3712
|
// ../core/dist/recorder.js
|
|
3686
3713
|
import { spawn } from "node:child_process";
|
|
3687
3714
|
import fs3 from "node:fs/promises";
|
|
3715
|
+
import os2 from "node:os";
|
|
3688
3716
|
import path3 from "node:path";
|
|
3717
|
+
var AUDIO_BINDING_NAME = "__browserpilotAudioChunk";
|
|
3718
|
+
var AUDIO_TAP_SCRIPT = `(() => {
|
|
3719
|
+
if (globalThis.__bpAudioTapActive) return;
|
|
3720
|
+
globalThis.__bpAudioTapActive = true;
|
|
3721
|
+
try {
|
|
3722
|
+
const AudioCtx = globalThis.AudioContext || globalThis.webkitAudioContext;
|
|
3723
|
+
if (!AudioCtx || typeof MediaRecorder === 'undefined') return;
|
|
3724
|
+
const mixCtx = new AudioCtx();
|
|
3725
|
+
const dest = mixCtx.createMediaStreamDestination();
|
|
3726
|
+
const connected = new WeakSet();
|
|
3727
|
+
|
|
3728
|
+
function tapMediaEl(el) {
|
|
3729
|
+
if (connected.has(el)) return;
|
|
3730
|
+
try {
|
|
3731
|
+
const src = mixCtx.createMediaElementSource(el);
|
|
3732
|
+
src.connect(dest);
|
|
3733
|
+
src.connect(mixCtx.destination);
|
|
3734
|
+
connected.add(el);
|
|
3735
|
+
} catch {}
|
|
3736
|
+
}
|
|
3737
|
+
|
|
3738
|
+
for (const el of document.querySelectorAll('audio, video')) tapMediaEl(el);
|
|
3739
|
+
const mo = new MutationObserver(() => {
|
|
3740
|
+
for (const el of document.querySelectorAll('audio, video')) tapMediaEl(el);
|
|
3741
|
+
});
|
|
3742
|
+
if (document.documentElement) mo.observe(document.documentElement, { childList: true, subtree: true });
|
|
3743
|
+
|
|
3744
|
+
// Also patch AudioNode.prototype.connect so Web Audio synthesis graphs feed our tap
|
|
3745
|
+
const origConnect = AudioNode.prototype.connect;
|
|
3746
|
+
if (!origConnect.__bpPatched) {
|
|
3747
|
+
const wrapped = function(...args) {
|
|
3748
|
+
const res = origConnect.apply(this, args);
|
|
3749
|
+
try {
|
|
3750
|
+
if (args[0] && this.context && args[0] === this.context.destination) {
|
|
3751
|
+
if (!this.context.__bpTapDest) {
|
|
3752
|
+
const d = this.context.createMediaStreamDestination();
|
|
3753
|
+
this.context.__bpTapDest = d;
|
|
3754
|
+
const subRec = new MediaRecorder(d.stream, { mimeType: 'audio/webm;codecs=opus' });
|
|
3755
|
+
subRec.ondataavailable = (ev) => {
|
|
3756
|
+
if (ev.data && ev.data.size > 0 && typeof globalThis.${AUDIO_BINDING_NAME} === 'function') {
|
|
3757
|
+
const reader = new FileReader();
|
|
3758
|
+
reader.onloadend = () => {
|
|
3759
|
+
const b64 = String(reader.result || '').split(',')[1] || '';
|
|
3760
|
+
if (b64) globalThis.${AUDIO_BINDING_NAME}(b64);
|
|
3761
|
+
};
|
|
3762
|
+
reader.readAsDataURL(ev.data);
|
|
3763
|
+
}
|
|
3764
|
+
};
|
|
3765
|
+
subRec.start(250);
|
|
3766
|
+
globalThis.__bpAudioRecorders = globalThis.__bpAudioRecorders || [];
|
|
3767
|
+
globalThis.__bpAudioRecorders.push(subRec);
|
|
3768
|
+
}
|
|
3769
|
+
origConnect.call(this, this.context.__bpTapDest);
|
|
3770
|
+
}
|
|
3771
|
+
} catch {}
|
|
3772
|
+
return res;
|
|
3773
|
+
};
|
|
3774
|
+
wrapped.__bpPatched = true;
|
|
3775
|
+
AudioNode.prototype.connect = wrapped;
|
|
3776
|
+
}
|
|
3777
|
+
|
|
3778
|
+
const mimeType = MediaRecorder.isTypeSupported('audio/webm;codecs=opus') ? 'audio/webm;codecs=opus' : 'audio/webm';
|
|
3779
|
+
const rec = new MediaRecorder(dest.stream, { mimeType });
|
|
3780
|
+
rec.ondataavailable = (ev) => {
|
|
3781
|
+
if (ev.data && ev.data.size > 0 && typeof globalThis.${AUDIO_BINDING_NAME} === 'function') {
|
|
3782
|
+
const reader = new FileReader();
|
|
3783
|
+
reader.onloadend = () => {
|
|
3784
|
+
const b64 = String(reader.result || '').split(',')[1] || '';
|
|
3785
|
+
if (b64) globalThis.${AUDIO_BINDING_NAME}(b64);
|
|
3786
|
+
};
|
|
3787
|
+
reader.readAsDataURL(ev.data);
|
|
3788
|
+
}
|
|
3789
|
+
};
|
|
3790
|
+
rec.start(250);
|
|
3791
|
+
globalThis.__bpAudioRecorders = globalThis.__bpAudioRecorders || [];
|
|
3792
|
+
globalThis.__bpAudioRecorders.push(rec);
|
|
3793
|
+
globalThis.__bpStopAudioTap = () => {
|
|
3794
|
+
globalThis.__bpAudioTapActive = false;
|
|
3795
|
+
mo.disconnect();
|
|
3796
|
+
for (const r of globalThis.__bpAudioRecorders || []) {
|
|
3797
|
+
try { if (r.state !== 'inactive') r.stop(); } catch {}
|
|
3798
|
+
}
|
|
3799
|
+
globalThis.__bpAudioRecorders = [];
|
|
3800
|
+
};
|
|
3801
|
+
} catch {}
|
|
3802
|
+
})()`;
|
|
3689
3803
|
var ScreenRecorder = class {
|
|
3690
3804
|
session;
|
|
3691
3805
|
active = null;
|
|
@@ -3706,6 +3820,9 @@ var ScreenRecorder = class {
|
|
|
3706
3820
|
}
|
|
3707
3821
|
const outputPath = path3.resolve(options.outputPath);
|
|
3708
3822
|
await fs3.mkdir(path3.dirname(outputPath), { recursive: true });
|
|
3823
|
+
const audioEnabled = Boolean(options.audio);
|
|
3824
|
+
const videoOnlyPath = audioEnabled ? path3.join(os2.tmpdir(), `bp-video-${Date.now()}-${Math.random().toString(36).slice(2, 6)}${path3.extname(outputPath) || ".mp4"}`) : outputPath;
|
|
3825
|
+
const audioTempPath = audioEnabled ? path3.join(os2.tmpdir(), `bp-audio-${Date.now()}-${Math.random().toString(36).slice(2, 6)}.webm`) : null;
|
|
3709
3826
|
const frameRate = Math.min(60, Math.max(5, options.frameRate ?? 24));
|
|
3710
3827
|
const quality = Math.min(100, Math.max(20, options.quality ?? 85));
|
|
3711
3828
|
const maxWidth = options.maxWidth ?? 1280;
|
|
@@ -3726,7 +3843,7 @@ var ScreenRecorder = class {
|
|
|
3726
3843
|
"-vf",
|
|
3727
3844
|
"pad=ceil(iw/2)*2:ceil(ih/2)*2",
|
|
3728
3845
|
...codecArgs,
|
|
3729
|
-
|
|
3846
|
+
videoOnlyPath
|
|
3730
3847
|
], { stdio: ["pipe", "ignore", "pipe"] });
|
|
3731
3848
|
const stderr = [];
|
|
3732
3849
|
ffmpeg.stderr?.on("data", (chunk) => {
|
|
@@ -3739,16 +3856,20 @@ var ScreenRecorder = class {
|
|
|
3739
3856
|
});
|
|
3740
3857
|
const rec = {
|
|
3741
3858
|
outputPath,
|
|
3859
|
+
videoOnlyPath,
|
|
3860
|
+
audioTempPath,
|
|
3861
|
+
audioChunks: [],
|
|
3862
|
+
audioEnabled,
|
|
3863
|
+
audioScriptId: null,
|
|
3742
3864
|
ffmpeg,
|
|
3743
3865
|
startedAt: Date.now(),
|
|
3744
3866
|
frameCount: 0,
|
|
3745
3867
|
actionTimestamps: [],
|
|
3746
|
-
|
|
3747
|
-
},
|
|
3868
|
+
unsubs: [],
|
|
3748
3869
|
maxTimer: null,
|
|
3749
3870
|
stderr
|
|
3750
3871
|
};
|
|
3751
|
-
rec.
|
|
3872
|
+
rec.unsubs.push(this.session.on("Page.screencastFrame", (params) => {
|
|
3752
3873
|
const data = params.data;
|
|
3753
3874
|
const sessionId = params.sessionId;
|
|
3754
3875
|
if (sessionId !== void 0) {
|
|
@@ -3759,7 +3880,20 @@ var ScreenRecorder = class {
|
|
|
3759
3880
|
rec.frameCount++;
|
|
3760
3881
|
rec.ffmpeg.stdin.write(Buffer.from(data, "base64"));
|
|
3761
3882
|
}
|
|
3762
|
-
});
|
|
3883
|
+
}));
|
|
3884
|
+
if (audioEnabled) {
|
|
3885
|
+
await this.session.send("Runtime.addBinding", { name: AUDIO_BINDING_NAME }).catch(() => {
|
|
3886
|
+
});
|
|
3887
|
+
const added = await this.session.send("Page.addScriptToEvaluateOnNewDocument", { source: AUDIO_TAP_SCRIPT }).catch(() => ({ identifier: void 0 }));
|
|
3888
|
+
rec.audioScriptId = added.identifier ?? null;
|
|
3889
|
+
await this.session.send("Runtime.evaluate", { expression: AUDIO_TAP_SCRIPT }).catch(() => {
|
|
3890
|
+
});
|
|
3891
|
+
rec.unsubs.push(this.session.on("Runtime.bindingCalled", (params) => {
|
|
3892
|
+
if (params.name === AUDIO_BINDING_NAME && typeof params.payload === "string" && params.payload) {
|
|
3893
|
+
rec.audioChunks.push(Buffer.from(params.payload, "base64"));
|
|
3894
|
+
}
|
|
3895
|
+
}));
|
|
3896
|
+
}
|
|
3763
3897
|
if (maxDurationMs > 0) {
|
|
3764
3898
|
rec.maxTimer = setTimeout(() => {
|
|
3765
3899
|
void this.stop().catch(() => {
|
|
@@ -3778,7 +3912,7 @@ var ScreenRecorder = class {
|
|
|
3778
3912
|
await this.cancel();
|
|
3779
3913
|
throw new Error(`ffmpeg failed to start (install via "brew install ffmpeg" or "apt install ffmpeg"): ${spawnErr.message}`);
|
|
3780
3914
|
}
|
|
3781
|
-
return { outputPath };
|
|
3915
|
+
return { outputPath, audio: audioEnabled };
|
|
3782
3916
|
}
|
|
3783
3917
|
async stop() {
|
|
3784
3918
|
if (!this.active) {
|
|
@@ -3788,7 +3922,17 @@ var ScreenRecorder = class {
|
|
|
3788
3922
|
this.active = null;
|
|
3789
3923
|
if (rec.maxTimer)
|
|
3790
3924
|
clearTimeout(rec.maxTimer);
|
|
3791
|
-
rec.
|
|
3925
|
+
if (rec.audioEnabled) {
|
|
3926
|
+
await this.session.send("Runtime.evaluate", { expression: "globalThis.__bpStopAudioTap?.()" }).catch(() => {
|
|
3927
|
+
});
|
|
3928
|
+
if (rec.audioScriptId) {
|
|
3929
|
+
await this.session.send("Page.removeScriptToEvaluateOnNewDocument", { identifier: rec.audioScriptId }).catch(() => {
|
|
3930
|
+
});
|
|
3931
|
+
}
|
|
3932
|
+
await new Promise((r) => setTimeout(r, 180));
|
|
3933
|
+
}
|
|
3934
|
+
for (const off of rec.unsubs)
|
|
3935
|
+
off();
|
|
3792
3936
|
await this.session.send("Page.stopScreencast").catch(() => {
|
|
3793
3937
|
});
|
|
3794
3938
|
if (rec.frameCount === 0) {
|
|
@@ -3811,13 +3955,50 @@ var ScreenRecorder = class {
|
|
|
3811
3955
|
if (exitCode !== 0 && exitCode !== null) {
|
|
3812
3956
|
throw new Error(`ffmpeg exited with code ${exitCode}: ${rec.stderr.join("").slice(-500)}`);
|
|
3813
3957
|
}
|
|
3958
|
+
let hasAudio = false;
|
|
3959
|
+
if (rec.audioEnabled) {
|
|
3960
|
+
if (rec.audioChunks.length > 0 && rec.audioTempPath) {
|
|
3961
|
+
try {
|
|
3962
|
+
await fs3.writeFile(rec.audioTempPath, Buffer.concat(rec.audioChunks));
|
|
3963
|
+
const ext = path3.extname(rec.outputPath).toLowerCase();
|
|
3964
|
+
const audioCodec = ext === ".webm" ? ["-c:a", "libopus"] : ["-c:a", "aac", "-b:a", "128k"];
|
|
3965
|
+
await runFfmpeg([
|
|
3966
|
+
"-y",
|
|
3967
|
+
"-i",
|
|
3968
|
+
rec.videoOnlyPath,
|
|
3969
|
+
"-i",
|
|
3970
|
+
rec.audioTempPath,
|
|
3971
|
+
"-c:v",
|
|
3972
|
+
"copy",
|
|
3973
|
+
...audioCodec,
|
|
3974
|
+
"-shortest",
|
|
3975
|
+
rec.outputPath
|
|
3976
|
+
]);
|
|
3977
|
+
hasAudio = true;
|
|
3978
|
+
} catch {
|
|
3979
|
+
await fs3.copyFile(rec.videoOnlyPath, rec.outputPath);
|
|
3980
|
+
} finally {
|
|
3981
|
+
await fs3.rm(rec.videoOnlyPath, { force: true }).catch(() => {
|
|
3982
|
+
});
|
|
3983
|
+
await fs3.rm(rec.audioTempPath, { force: true }).catch(() => {
|
|
3984
|
+
});
|
|
3985
|
+
}
|
|
3986
|
+
} else {
|
|
3987
|
+
await fs3.rename(rec.videoOnlyPath, rec.outputPath).catch(async () => {
|
|
3988
|
+
await fs3.copyFile(rec.videoOnlyPath, rec.outputPath);
|
|
3989
|
+
await fs3.rm(rec.videoOnlyPath, { force: true }).catch(() => {
|
|
3990
|
+
});
|
|
3991
|
+
});
|
|
3992
|
+
}
|
|
3993
|
+
}
|
|
3814
3994
|
const stat = await fs3.stat(rec.outputPath);
|
|
3815
3995
|
return {
|
|
3816
3996
|
path: rec.outputPath,
|
|
3817
3997
|
durationMs: Date.now() - rec.startedAt,
|
|
3818
3998
|
frameCount: rec.frameCount,
|
|
3819
3999
|
sizeBytes: stat.size,
|
|
3820
|
-
actionTimestamps: rec.actionTimestamps
|
|
4000
|
+
actionTimestamps: rec.actionTimestamps,
|
|
4001
|
+
hasAudio
|
|
3821
4002
|
};
|
|
3822
4003
|
}
|
|
3823
4004
|
async cancel() {
|
|
@@ -3827,21 +4008,74 @@ var ScreenRecorder = class {
|
|
|
3827
4008
|
this.active = null;
|
|
3828
4009
|
if (rec.maxTimer)
|
|
3829
4010
|
clearTimeout(rec.maxTimer);
|
|
3830
|
-
rec.
|
|
4011
|
+
for (const off of rec.unsubs)
|
|
4012
|
+
off();
|
|
3831
4013
|
await this.session.send("Page.stopScreencast").catch(() => {
|
|
3832
4014
|
});
|
|
3833
4015
|
rec.ffmpeg.kill("SIGTERM");
|
|
3834
4016
|
await fs3.rm(rec.outputPath, { force: true }).catch(() => {
|
|
3835
4017
|
});
|
|
4018
|
+
if (rec.videoOnlyPath !== rec.outputPath)
|
|
4019
|
+
await fs3.rm(rec.videoOnlyPath, { force: true }).catch(() => {
|
|
4020
|
+
});
|
|
4021
|
+
if (rec.audioTempPath)
|
|
4022
|
+
await fs3.rm(rec.audioTempPath, { force: true }).catch(() => {
|
|
4023
|
+
});
|
|
3836
4024
|
}
|
|
3837
4025
|
};
|
|
3838
|
-
|
|
3839
|
-
const
|
|
3840
|
-
const
|
|
3841
|
-
const
|
|
3842
|
-
|
|
4026
|
+
function computeDemoSegments(durationMs, actionTimestamps, options = {}) {
|
|
4027
|
+
const totalSec = Math.max(0.1, durationMs / 1e3);
|
|
4028
|
+
const padMs = options.paddingMs ?? 750;
|
|
4029
|
+
const minIdleGapMs = options.minIdleGapMs ?? 400;
|
|
4030
|
+
if (!actionTimestamps.length || durationMs <= 0) {
|
|
4031
|
+
return [{ startSec: 0, endSec: totalSec, kind: "idle" }];
|
|
4032
|
+
}
|
|
4033
|
+
const sorted = [...actionTimestamps].filter((t) => Number.isFinite(t) && t >= 0 && t <= durationMs).sort((a, b) => a - b);
|
|
4034
|
+
if (!sorted.length) {
|
|
4035
|
+
return [{ startSec: 0, endSec: totalSec, kind: "idle" }];
|
|
4036
|
+
}
|
|
4037
|
+
const windows = [];
|
|
4038
|
+
for (const ts of sorted) {
|
|
4039
|
+
const start = Math.max(0, ts - padMs);
|
|
4040
|
+
const end = Math.min(durationMs, ts + padMs);
|
|
4041
|
+
const prev = windows[windows.length - 1];
|
|
4042
|
+
if (prev && start <= prev.end + minIdleGapMs) {
|
|
4043
|
+
prev.end = Math.max(prev.end, end);
|
|
4044
|
+
} else {
|
|
4045
|
+
windows.push({ start, end });
|
|
4046
|
+
}
|
|
4047
|
+
}
|
|
4048
|
+
const segments = [];
|
|
4049
|
+
let cursor = 0;
|
|
4050
|
+
for (const w of windows) {
|
|
4051
|
+
if (w.start > cursor + 50) {
|
|
4052
|
+
segments.push({ startSec: cursor / 1e3, endSec: w.start / 1e3, kind: "idle" });
|
|
4053
|
+
}
|
|
4054
|
+
segments.push({ startSec: w.start / 1e3, endSec: w.end / 1e3, kind: "active" });
|
|
4055
|
+
cursor = w.end;
|
|
4056
|
+
}
|
|
4057
|
+
if (durationMs > cursor + 50) {
|
|
4058
|
+
segments.push({ startSec: cursor / 1e3, endSec: totalSec, kind: "idle" });
|
|
4059
|
+
}
|
|
4060
|
+
return segments.filter((s) => s.endSec - s.startSec >= 0.05);
|
|
4061
|
+
}
|
|
4062
|
+
async function probeVideoDurationSec(filePath) {
|
|
4063
|
+
return await new Promise((resolve) => {
|
|
4064
|
+
const proc = spawn("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filePath], { stdio: ["ignore", "pipe", "ignore"] });
|
|
4065
|
+
let out = "";
|
|
4066
|
+
proc.stdout.on("data", (c) => {
|
|
4067
|
+
out += c.toString("utf8");
|
|
4068
|
+
});
|
|
4069
|
+
proc.once("error", () => resolve(null));
|
|
4070
|
+
proc.once("close", () => {
|
|
4071
|
+
const n = Number.parseFloat(out.trim());
|
|
4072
|
+
resolve(Number.isFinite(n) && n > 0 ? n : null);
|
|
4073
|
+
});
|
|
4074
|
+
});
|
|
4075
|
+
}
|
|
4076
|
+
async function runFfmpeg(args) {
|
|
3843
4077
|
await new Promise((resolve, reject) => {
|
|
3844
|
-
const proc = spawn("ffmpeg",
|
|
4078
|
+
const proc = spawn("ffmpeg", args, { stdio: ["ignore", "ignore", "pipe"] });
|
|
3845
4079
|
const errChunks = [];
|
|
3846
4080
|
proc.stderr?.on("data", (c) => errChunks.push(c.toString("utf8")));
|
|
3847
4081
|
proc.once("error", reject);
|
|
@@ -3849,12 +4083,520 @@ async function createDemoVideo(options) {
|
|
|
3849
4083
|
if (code === 0)
|
|
3850
4084
|
resolve();
|
|
3851
4085
|
else
|
|
3852
|
-
reject(new Error(`
|
|
4086
|
+
reject(new Error(`ffmpeg failed (${code}): ${errChunks.join("").slice(-500)}`));
|
|
3853
4087
|
});
|
|
3854
4088
|
});
|
|
4089
|
+
}
|
|
4090
|
+
async function createDemoVideo(options) {
|
|
4091
|
+
const input = path3.resolve(options.recordingPath);
|
|
4092
|
+
const ext = path3.extname(input) || ".mp4";
|
|
4093
|
+
const output = path3.resolve(options.outputPath ?? input.replace(ext, `.demo${ext}`));
|
|
4094
|
+
const speed = Math.max(1, options.speed ?? (options.actionTimestamps?.length ? 6 : 2));
|
|
4095
|
+
if (options.actionTimestamps && options.actionTimestamps.length > 0) {
|
|
4096
|
+
const probedSec = await probeVideoDurationSec(input);
|
|
4097
|
+
const durationMs = options.durationMs ?? (probedSec ? Math.round(probedSec * 1e3) : 0);
|
|
4098
|
+
const segments = computeDemoSegments(durationMs, options.actionTimestamps, {
|
|
4099
|
+
paddingMs: options.paddingMs
|
|
4100
|
+
});
|
|
4101
|
+
if (segments.length > 1) {
|
|
4102
|
+
const filters = [];
|
|
4103
|
+
const concatInputs = [];
|
|
4104
|
+
segments.forEach((seg, idx) => {
|
|
4105
|
+
const factor = seg.kind === "idle" ? (1 / speed).toFixed(4) : "1.0";
|
|
4106
|
+
filters.push(`[0:v]trim=start=${seg.startSec.toFixed(3)}:end=${seg.endSec.toFixed(3)},setpts=${factor}*(PTS-STARTPTS)[v${idx}]`);
|
|
4107
|
+
concatInputs.push(`[v${idx}]`);
|
|
4108
|
+
});
|
|
4109
|
+
filters.push(`${concatInputs.join("")}concat=n=${segments.length}:v=1:a=0[vout]`);
|
|
4110
|
+
await runFfmpeg([
|
|
4111
|
+
"-y",
|
|
4112
|
+
"-i",
|
|
4113
|
+
input,
|
|
4114
|
+
"-filter_complex",
|
|
4115
|
+
filters.join(";"),
|
|
4116
|
+
"-map",
|
|
4117
|
+
"[vout]",
|
|
4118
|
+
"-c:v",
|
|
4119
|
+
ext === ".webm" ? "libvpx" : "libx264",
|
|
4120
|
+
...ext === ".webm" ? ["-b:v", "1M"] : ["-pix_fmt", "yuv420p", "-preset", "veryfast", "-movflags", "+faststart"],
|
|
4121
|
+
output
|
|
4122
|
+
]);
|
|
4123
|
+
return output;
|
|
4124
|
+
}
|
|
4125
|
+
}
|
|
4126
|
+
await runFfmpeg(["-y", "-i", input, "-filter:v", `setpts=${(1 / speed).toFixed(4)}*PTS`, "-an", output]);
|
|
3855
4127
|
return output;
|
|
3856
4128
|
}
|
|
3857
4129
|
|
|
4130
|
+
// ../core/dist/downloads.js
|
|
4131
|
+
import { EventEmitter as EventEmitter4 } from "node:events";
|
|
4132
|
+
import fs4 from "node:fs/promises";
|
|
4133
|
+
import os3 from "node:os";
|
|
4134
|
+
import path4 from "node:path";
|
|
4135
|
+
function sanitizeFilename(name) {
|
|
4136
|
+
const base = path4.basename(name || "download.bin").replace(/[<>:"/\\|?*\x00-\x1f]/g, "_");
|
|
4137
|
+
return base || "download.bin";
|
|
4138
|
+
}
|
|
4139
|
+
async function resolveUniquePath(dir, filename) {
|
|
4140
|
+
const safe = sanitizeFilename(filename);
|
|
4141
|
+
const ext = path4.extname(safe);
|
|
4142
|
+
const stem = ext ? safe.slice(0, -ext.length) : safe;
|
|
4143
|
+
let candidate = path4.join(dir, safe);
|
|
4144
|
+
for (let i = 1; i <= 200; i++) {
|
|
4145
|
+
try {
|
|
4146
|
+
await fs4.access(candidate);
|
|
4147
|
+
candidate = path4.join(dir, `${stem}-${i}${ext}`);
|
|
4148
|
+
} catch {
|
|
4149
|
+
return candidate;
|
|
4150
|
+
}
|
|
4151
|
+
}
|
|
4152
|
+
return path4.join(dir, `${stem}-${Date.now()}${ext}`);
|
|
4153
|
+
}
|
|
4154
|
+
var DownloadManager = class {
|
|
4155
|
+
session;
|
|
4156
|
+
entries = /* @__PURE__ */ new Map();
|
|
4157
|
+
emitter = new EventEmitter4();
|
|
4158
|
+
downloadDir = null;
|
|
4159
|
+
configured = false;
|
|
4160
|
+
unsubs = [];
|
|
4161
|
+
constructor(session) {
|
|
4162
|
+
this.session = session;
|
|
4163
|
+
this.emitter.setMaxListeners(50);
|
|
4164
|
+
const onBegin = (params) => {
|
|
4165
|
+
const id = String(params.guid ?? `dl_${Date.now()}`);
|
|
4166
|
+
const entry = {
|
|
4167
|
+
id,
|
|
4168
|
+
url: String(params.url ?? ""),
|
|
4169
|
+
suggestedFilename: sanitizeFilename(String(params.suggestedFilename ?? "download.bin")),
|
|
4170
|
+
state: "in_progress",
|
|
4171
|
+
receivedBytes: 0,
|
|
4172
|
+
startedAt: Date.now()
|
|
4173
|
+
};
|
|
4174
|
+
this.entries.set(id, entry);
|
|
4175
|
+
this.emitter.emit("update", entry);
|
|
4176
|
+
};
|
|
4177
|
+
const onProgress = (params) => {
|
|
4178
|
+
const id = String(params.guid ?? "");
|
|
4179
|
+
const entry = this.entries.get(id);
|
|
4180
|
+
if (!entry)
|
|
4181
|
+
return;
|
|
4182
|
+
if (typeof params.receivedBytes === "number")
|
|
4183
|
+
entry.receivedBytes = params.receivedBytes;
|
|
4184
|
+
if (typeof params.totalBytes === "number" && params.totalBytes > 0)
|
|
4185
|
+
entry.totalBytes = params.totalBytes;
|
|
4186
|
+
const rawState = String(params.state ?? "");
|
|
4187
|
+
if (rawState === "completed") {
|
|
4188
|
+
void this.finalizeDirectDownload(entry);
|
|
4189
|
+
} else if (rawState === "canceled") {
|
|
4190
|
+
entry.state = "canceled";
|
|
4191
|
+
entry.completedAt = Date.now();
|
|
4192
|
+
this.emitter.emit("update", entry);
|
|
4193
|
+
}
|
|
4194
|
+
};
|
|
4195
|
+
this.unsubs.push(session.on("Browser.downloadWillBegin", onBegin), session.on("Page.downloadWillBegin", onBegin), session.on("Browser.downloadProgress", onProgress), session.on("Page.downloadProgress", onProgress));
|
|
4196
|
+
if (session.transport.onDownloadEvent) {
|
|
4197
|
+
this.unsubs.push(session.transport.onDownloadEvent((entry) => {
|
|
4198
|
+
this.entries.set(entry.id, entry);
|
|
4199
|
+
this.emitter.emit("update", entry);
|
|
4200
|
+
}));
|
|
4201
|
+
}
|
|
4202
|
+
}
|
|
4203
|
+
async finalizeDirectDownload(entry) {
|
|
4204
|
+
if (this.downloadDir) {
|
|
4205
|
+
const guidPath = path4.join(this.downloadDir, entry.id);
|
|
4206
|
+
const directNamedPath = path4.join(this.downloadDir, entry.suggestedFilename);
|
|
4207
|
+
try {
|
|
4208
|
+
await fs4.access(guidPath);
|
|
4209
|
+
const targetPath = await resolveUniquePath(this.downloadDir, entry.suggestedFilename);
|
|
4210
|
+
await fs4.rename(guidPath, targetPath);
|
|
4211
|
+
entry.filePath = targetPath;
|
|
4212
|
+
} catch {
|
|
4213
|
+
try {
|
|
4214
|
+
await fs4.access(directNamedPath);
|
|
4215
|
+
entry.filePath = directNamedPath;
|
|
4216
|
+
} catch {
|
|
4217
|
+
}
|
|
4218
|
+
}
|
|
4219
|
+
}
|
|
4220
|
+
entry.state = "completed";
|
|
4221
|
+
entry.completedAt = Date.now();
|
|
4222
|
+
this.emitter.emit("update", entry);
|
|
4223
|
+
}
|
|
4224
|
+
async configure(downloadDir) {
|
|
4225
|
+
if (this.session.transport.mode === "extension") {
|
|
4226
|
+
this.configured = true;
|
|
4227
|
+
return { downloadDir: null, mode: "extension" };
|
|
4228
|
+
}
|
|
4229
|
+
const dir = path4.resolve(downloadDir ?? path4.join(os3.tmpdir(), "browserpilot-downloads"));
|
|
4230
|
+
await fs4.mkdir(dir, { recursive: true });
|
|
4231
|
+
this.downloadDir = dir;
|
|
4232
|
+
if (this.session.transport.sendBrowser) {
|
|
4233
|
+
await this.session.transport.sendBrowser("Browser.setDownloadBehavior", {
|
|
4234
|
+
behavior: "allowAndName",
|
|
4235
|
+
downloadPath: dir,
|
|
4236
|
+
eventsEnabled: true
|
|
4237
|
+
});
|
|
4238
|
+
} else {
|
|
4239
|
+
await this.session.send("Page.setDownloadBehavior", {
|
|
4240
|
+
behavior: "allow",
|
|
4241
|
+
downloadPath: dir
|
|
4242
|
+
});
|
|
4243
|
+
}
|
|
4244
|
+
this.configured = true;
|
|
4245
|
+
return { downloadDir: dir, mode: "direct-cdp" };
|
|
4246
|
+
}
|
|
4247
|
+
async ensureConfigured() {
|
|
4248
|
+
if (!this.configured) {
|
|
4249
|
+
await this.configure();
|
|
4250
|
+
}
|
|
4251
|
+
}
|
|
4252
|
+
async list() {
|
|
4253
|
+
if (this.session.transport.mode === "extension" && this.session.transport.listDownloads) {
|
|
4254
|
+
const remote = await this.session.transport.listDownloads().catch(() => []);
|
|
4255
|
+
for (const item of remote) {
|
|
4256
|
+
this.entries.set(item.id, item);
|
|
4257
|
+
}
|
|
4258
|
+
}
|
|
4259
|
+
return Array.from(this.entries.values()).sort((a, b) => a.startedAt - b.startedAt);
|
|
4260
|
+
}
|
|
4261
|
+
async waitForDownload(options = {}) {
|
|
4262
|
+
await this.ensureConfigured();
|
|
4263
|
+
const timeoutMs = options.timeoutMs ?? 2e4;
|
|
4264
|
+
const sinceTs = options.sinceTimestamp ?? 0;
|
|
4265
|
+
const regex = options.filenamePattern instanceof RegExp ? options.filenamePattern : typeof options.filenamePattern === "string" ? new RegExp(options.filenamePattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i") : null;
|
|
4266
|
+
const matches = (e) => e.state === "completed" && (e.completedAt ?? e.startedAt) >= sinceTs && (!regex || regex.test(e.suggestedFilename) || (e.filePath ? regex.test(e.filePath) : false));
|
|
4267
|
+
const existing = Array.from(this.entries.values()).reverse().find(matches);
|
|
4268
|
+
if (existing)
|
|
4269
|
+
return existing;
|
|
4270
|
+
return await new Promise((resolve, reject) => {
|
|
4271
|
+
const timer = setTimeout(() => {
|
|
4272
|
+
this.emitter.off("update", onUpdate);
|
|
4273
|
+
reject(new Error(`Timed out after ${timeoutMs}ms waiting for download to complete`));
|
|
4274
|
+
}, timeoutMs);
|
|
4275
|
+
const onUpdate = (entry) => {
|
|
4276
|
+
if (matches(entry)) {
|
|
4277
|
+
clearTimeout(timer);
|
|
4278
|
+
this.emitter.off("update", onUpdate);
|
|
4279
|
+
resolve(entry);
|
|
4280
|
+
} else if (entry.state === "canceled" && entry.startedAt >= sinceTs && (!regex || regex.test(entry.suggestedFilename))) {
|
|
4281
|
+
clearTimeout(timer);
|
|
4282
|
+
this.emitter.off("update", onUpdate);
|
|
4283
|
+
reject(new Error(`Download canceled: ${entry.suggestedFilename}`));
|
|
4284
|
+
}
|
|
4285
|
+
};
|
|
4286
|
+
this.emitter.on("update", onUpdate);
|
|
4287
|
+
});
|
|
4288
|
+
}
|
|
4289
|
+
clear() {
|
|
4290
|
+
this.entries.clear();
|
|
4291
|
+
}
|
|
4292
|
+
dispose() {
|
|
4293
|
+
for (const off of this.unsubs)
|
|
4294
|
+
off();
|
|
4295
|
+
this.unsubs = [];
|
|
4296
|
+
this.emitter.removeAllListeners();
|
|
4297
|
+
}
|
|
4298
|
+
};
|
|
4299
|
+
|
|
4300
|
+
// ../core/dist/action-recorder.js
|
|
4301
|
+
var BINDING_NAME = "__browserpilotRecordEvent";
|
|
4302
|
+
function buildCaptureScript(maskPasswords) {
|
|
4303
|
+
return `(() => {
|
|
4304
|
+
if (globalThis.__bpActionRecorderInstalled) {
|
|
4305
|
+
globalThis.__bpActionRecorderEnabled = true;
|
|
4306
|
+
return;
|
|
4307
|
+
}
|
|
4308
|
+
globalThis.__bpActionRecorderInstalled = true;
|
|
4309
|
+
globalThis.__bpActionRecorderEnabled = true;
|
|
4310
|
+
|
|
4311
|
+
function emit(payload) {
|
|
4312
|
+
if (!globalThis.__bpActionRecorderEnabled) return;
|
|
4313
|
+
if (typeof globalThis.${BINDING_NAME} === 'function') {
|
|
4314
|
+
try { globalThis.${BINDING_NAME}(JSON.stringify(payload)); } catch {}
|
|
4315
|
+
}
|
|
4316
|
+
}
|
|
4317
|
+
|
|
4318
|
+
function stableSelector(el) {
|
|
4319
|
+
if (!el || !(el instanceof Element)) return '';
|
|
4320
|
+
const tid = el.getAttribute('data-testid');
|
|
4321
|
+
if (tid) return '[data-testid="' + tid.replace(/"/g, '\\\\"') + '"]';
|
|
4322
|
+
if (el.id) return '#' + CSS.escape(el.id);
|
|
4323
|
+
const tag = el.tagName.toLowerCase();
|
|
4324
|
+
const nameAttr = el.getAttribute('name');
|
|
4325
|
+
if (nameAttr) return tag + '[name="' + nameAttr.replace(/"/g, '\\\\"') + '"]';
|
|
4326
|
+
const aria = el.getAttribute('aria-label');
|
|
4327
|
+
if (aria) return tag + '[aria-label="' + aria.replace(/"/g, '\\\\"') + '"]';
|
|
4328
|
+
const ph = el.getAttribute('placeholder');
|
|
4329
|
+
if (ph) return 'placeholder=' + ph;
|
|
4330
|
+
const role = el.getAttribute('role') || (tag === 'button' ? 'button' : tag === 'a' ? 'link' : '');
|
|
4331
|
+
const text = (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim();
|
|
4332
|
+
if (role && text && text.length <= 60) {
|
|
4333
|
+
return 'role=' + role + '[name="' + text.replace(/"/g, '\\\\"') + '"]';
|
|
4334
|
+
}
|
|
4335
|
+
const classes = Array.from(el.classList || []).slice(0, 2).map((c) => '.' + CSS.escape(c)).join('');
|
|
4336
|
+
return tag + classes;
|
|
4337
|
+
}
|
|
4338
|
+
|
|
4339
|
+
function interactiveTarget(raw) {
|
|
4340
|
+
if (!(raw instanceof Element)) return null;
|
|
4341
|
+
return raw.closest('button, a, input, textarea, select, [role="button"], [role="link"], [role="tab"], [role="menuitem"], label') || raw;
|
|
4342
|
+
}
|
|
4343
|
+
|
|
4344
|
+
document.addEventListener('click', (e) => {
|
|
4345
|
+
const el = interactiveTarget(e.target);
|
|
4346
|
+
if (!el) return;
|
|
4347
|
+
const tag = el.tagName.toLowerCase();
|
|
4348
|
+
// Skip redundant click right on text inputs when followed by fill
|
|
4349
|
+
emit({
|
|
4350
|
+
action: 'click',
|
|
4351
|
+
url: location.href,
|
|
4352
|
+
target: stableSelector(el),
|
|
4353
|
+
text: (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 80) || undefined,
|
|
4354
|
+
coordinates: { x: Math.round(e.clientX), y: Math.round(e.clientY) },
|
|
4355
|
+
tag,
|
|
4356
|
+
});
|
|
4357
|
+
}, true);
|
|
4358
|
+
|
|
4359
|
+
const inputTimers = new WeakMap();
|
|
4360
|
+
const recordInput = (el) => {
|
|
4361
|
+
const tag = el.tagName.toLowerCase();
|
|
4362
|
+
const sel = stableSelector(el);
|
|
4363
|
+
if (tag === 'select') {
|
|
4364
|
+
emit({ action: 'select_option', url: location.href, target: sel, value: el.value });
|
|
4365
|
+
return;
|
|
4366
|
+
}
|
|
4367
|
+
if (tag === 'input' && (el.type === 'checkbox' || el.type === 'radio')) {
|
|
4368
|
+
return; // captured via click
|
|
4369
|
+
}
|
|
4370
|
+
const isPassword = ${maskPasswords} && tag === 'input' && el.type === 'password';
|
|
4371
|
+
const val = el.isContentEditable ? (el.innerText || '') : (el.value || '');
|
|
4372
|
+
emit({
|
|
4373
|
+
action: 'fill',
|
|
4374
|
+
url: location.href,
|
|
4375
|
+
target: sel,
|
|
4376
|
+
value: isPassword ? '<REDACTED_PASSWORD>' : val,
|
|
4377
|
+
});
|
|
4378
|
+
};
|
|
4379
|
+
|
|
4380
|
+
document.addEventListener('input', (e) => {
|
|
4381
|
+
const el = e.target;
|
|
4382
|
+
if (!(el instanceof Element)) return;
|
|
4383
|
+
const prev = inputTimers.get(el);
|
|
4384
|
+
if (prev) clearTimeout(prev);
|
|
4385
|
+
inputTimers.set(el, setTimeout(() => recordInput(el), 350));
|
|
4386
|
+
}, true);
|
|
4387
|
+
|
|
4388
|
+
document.addEventListener('change', (e) => {
|
|
4389
|
+
const el = e.target;
|
|
4390
|
+
if (!(el instanceof Element)) return;
|
|
4391
|
+
const prev = inputTimers.get(el);
|
|
4392
|
+
if (prev) clearTimeout(prev);
|
|
4393
|
+
recordInput(el);
|
|
4394
|
+
}, true);
|
|
4395
|
+
|
|
4396
|
+
document.addEventListener('keydown', (e) => {
|
|
4397
|
+
if (['Enter', 'Escape', 'Tab'].includes(e.key)) {
|
|
4398
|
+
emit({ action: 'press_key', url: location.href, key: e.key });
|
|
4399
|
+
}
|
|
4400
|
+
}, true);
|
|
4401
|
+
|
|
4402
|
+
let lastScrollY = Math.round(window.scrollY || 0);
|
|
4403
|
+
let scrollTimer = null;
|
|
4404
|
+
window.addEventListener('scroll', () => {
|
|
4405
|
+
if (scrollTimer) clearTimeout(scrollTimer);
|
|
4406
|
+
scrollTimer = setTimeout(() => {
|
|
4407
|
+
const curY = Math.round(window.scrollY || 0);
|
|
4408
|
+
const delta = curY - lastScrollY;
|
|
4409
|
+
if (Math.abs(delta) >= 180) {
|
|
4410
|
+
emit({ action: 'scroll', url: location.href, value: String(delta) });
|
|
4411
|
+
lastScrollY = curY;
|
|
4412
|
+
}
|
|
4413
|
+
}, 300);
|
|
4414
|
+
}, { passive: true });
|
|
4415
|
+
})()`;
|
|
4416
|
+
}
|
|
4417
|
+
function buildActionRecordingResult(rawSteps, durationMs) {
|
|
4418
|
+
const steps = [];
|
|
4419
|
+
for (const s of rawSteps) {
|
|
4420
|
+
const prev = steps[steps.length - 1];
|
|
4421
|
+
if (s.action === "fill" && prev?.action === "fill" && prev.target === s.target) {
|
|
4422
|
+
prev.value = s.value;
|
|
4423
|
+
prev.timestamp = s.timestamp;
|
|
4424
|
+
continue;
|
|
4425
|
+
}
|
|
4426
|
+
if ((s.action === "fill" || s.action === "select_option") && prev?.action === "click" && prev.target === s.target) {
|
|
4427
|
+
steps.pop();
|
|
4428
|
+
}
|
|
4429
|
+
if (s.action === "navigate" && prev?.action === "navigate" && prev.url === s.url) {
|
|
4430
|
+
continue;
|
|
4431
|
+
}
|
|
4432
|
+
steps.push({ ...s });
|
|
4433
|
+
}
|
|
4434
|
+
const batchSteps = steps.map((s) => {
|
|
4435
|
+
switch (s.action) {
|
|
4436
|
+
case "navigate":
|
|
4437
|
+
return { action: "navigate", url: s.url };
|
|
4438
|
+
case "click":
|
|
4439
|
+
return { action: "click", target: s.target };
|
|
4440
|
+
case "fill":
|
|
4441
|
+
return { action: "fill", target: s.target, value: s.value ?? "" };
|
|
4442
|
+
case "select_option":
|
|
4443
|
+
return { action: "select_option", target: s.target, value: s.value ?? "" };
|
|
4444
|
+
case "press_key":
|
|
4445
|
+
return { action: "press_key", key: s.key ?? "Enter" };
|
|
4446
|
+
case "scroll": {
|
|
4447
|
+
const dy = Number(s.value ?? 400);
|
|
4448
|
+
return { action: "scroll", direction: dy >= 0 ? "down" : "up", amount: Math.abs(dy) };
|
|
4449
|
+
}
|
|
4450
|
+
}
|
|
4451
|
+
});
|
|
4452
|
+
const scriptLines = [
|
|
4453
|
+
"// Recorded by BrowserPilot Action Recorder",
|
|
4454
|
+
"const t = await tabs.current();"
|
|
4455
|
+
];
|
|
4456
|
+
for (const s of steps) {
|
|
4457
|
+
switch (s.action) {
|
|
4458
|
+
case "navigate":
|
|
4459
|
+
scriptLines.push(`await t.page.navigate(${JSON.stringify(s.url)});`);
|
|
4460
|
+
break;
|
|
4461
|
+
case "click":
|
|
4462
|
+
scriptLines.push(`await t.page.click(${JSON.stringify(s.target ?? "")});`);
|
|
4463
|
+
break;
|
|
4464
|
+
case "fill":
|
|
4465
|
+
scriptLines.push(`await t.page.fill(${JSON.stringify(s.target ?? "")}, ${JSON.stringify(s.value ?? "")});`);
|
|
4466
|
+
break;
|
|
4467
|
+
case "select_option":
|
|
4468
|
+
scriptLines.push(`await t.page.selectOption(${JSON.stringify(s.target ?? "")}, ${JSON.stringify(s.value ?? "")});`);
|
|
4469
|
+
break;
|
|
4470
|
+
case "press_key":
|
|
4471
|
+
scriptLines.push(`await t.page.pressKey(${JSON.stringify(s.key ?? "Enter")});`);
|
|
4472
|
+
break;
|
|
4473
|
+
case "scroll": {
|
|
4474
|
+
const dy = Number(s.value ?? 400);
|
|
4475
|
+
scriptLines.push(`await t.page.scroll({ deltaY: ${dy} });`);
|
|
4476
|
+
break;
|
|
4477
|
+
}
|
|
4478
|
+
}
|
|
4479
|
+
}
|
|
4480
|
+
const execScript = scriptLines.join("\n");
|
|
4481
|
+
const mdLines = [
|
|
4482
|
+
"# Recorded BrowserPilot Workflow",
|
|
4483
|
+
"",
|
|
4484
|
+
`Recorded ${steps.length} step(s) in ${(durationMs / 1e3).toFixed(1)}s.`,
|
|
4485
|
+
"",
|
|
4486
|
+
"## Steps"
|
|
4487
|
+
];
|
|
4488
|
+
steps.forEach((s, idx) => {
|
|
4489
|
+
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`;
|
|
4490
|
+
mdLines.push(`${idx + 1}. ${desc}`);
|
|
4491
|
+
});
|
|
4492
|
+
mdLines.push("", "## Replay Script (`browserpilot exec`)", "```js", execScript, "```");
|
|
4493
|
+
return {
|
|
4494
|
+
durationMs,
|
|
4495
|
+
steps,
|
|
4496
|
+
batchSteps,
|
|
4497
|
+
execScript,
|
|
4498
|
+
skillMarkdown: mdLines.join("\n")
|
|
4499
|
+
};
|
|
4500
|
+
}
|
|
4501
|
+
var ActionRecorder = class {
|
|
4502
|
+
session;
|
|
4503
|
+
recording = false;
|
|
4504
|
+
startedAt = 0;
|
|
4505
|
+
steps = [];
|
|
4506
|
+
scriptId = null;
|
|
4507
|
+
unsubs = [];
|
|
4508
|
+
constructor(session) {
|
|
4509
|
+
this.session = session;
|
|
4510
|
+
}
|
|
4511
|
+
isRecording() {
|
|
4512
|
+
return this.recording;
|
|
4513
|
+
}
|
|
4514
|
+
getSteps() {
|
|
4515
|
+
return [...this.steps];
|
|
4516
|
+
}
|
|
4517
|
+
async start(options = {}) {
|
|
4518
|
+
if (this.recording) {
|
|
4519
|
+
throw new Error("Action recorder is already running on this tab");
|
|
4520
|
+
}
|
|
4521
|
+
await this.session.ensureBaseDomains();
|
|
4522
|
+
const maskPasswords = options.maskPasswords !== false;
|
|
4523
|
+
this.steps = [];
|
|
4524
|
+
this.startedAt = Date.now();
|
|
4525
|
+
this.recording = true;
|
|
4526
|
+
const initialUrlRes = await this.session.send("Runtime.evaluate", {
|
|
4527
|
+
expression: "location.href",
|
|
4528
|
+
returnByValue: true
|
|
4529
|
+
});
|
|
4530
|
+
const initialUrl = initialUrlRes.result?.value ?? "";
|
|
4531
|
+
if (initialUrl && initialUrl !== "about:blank") {
|
|
4532
|
+
this.steps.push({ timestamp: this.startedAt, action: "navigate", url: initialUrl });
|
|
4533
|
+
}
|
|
4534
|
+
await this.session.send("Runtime.addBinding", { name: BINDING_NAME });
|
|
4535
|
+
const scriptSource = buildCaptureScript(maskPasswords);
|
|
4536
|
+
const added = await this.session.send("Page.addScriptToEvaluateOnNewDocument", {
|
|
4537
|
+
source: scriptSource
|
|
4538
|
+
});
|
|
4539
|
+
this.scriptId = added.identifier ?? null;
|
|
4540
|
+
await this.session.send("Runtime.evaluate", { expression: scriptSource });
|
|
4541
|
+
this.unsubs.push(this.session.on("Runtime.bindingCalled", (params) => {
|
|
4542
|
+
if (!this.recording || params.name !== BINDING_NAME)
|
|
4543
|
+
return;
|
|
4544
|
+
try {
|
|
4545
|
+
const parsed = JSON.parse(String(params.payload ?? "{}"));
|
|
4546
|
+
if (!parsed.action)
|
|
4547
|
+
return;
|
|
4548
|
+
this.steps.push({
|
|
4549
|
+
timestamp: Date.now(),
|
|
4550
|
+
action: parsed.action,
|
|
4551
|
+
url: parsed.url ?? "",
|
|
4552
|
+
target: parsed.target,
|
|
4553
|
+
value: parsed.value,
|
|
4554
|
+
key: parsed.key,
|
|
4555
|
+
text: parsed.text,
|
|
4556
|
+
coordinates: parsed.coordinates
|
|
4557
|
+
});
|
|
4558
|
+
} catch {
|
|
4559
|
+
}
|
|
4560
|
+
}), this.session.on("Page.frameNavigated", (params) => {
|
|
4561
|
+
if (!this.recording)
|
|
4562
|
+
return;
|
|
4563
|
+
const frame = params.frame;
|
|
4564
|
+
if (frame && !frame.parentId && frame.url && frame.url !== "about:blank") {
|
|
4565
|
+
this.steps.push({
|
|
4566
|
+
timestamp: Date.now(),
|
|
4567
|
+
action: "navigate",
|
|
4568
|
+
url: frame.url
|
|
4569
|
+
});
|
|
4570
|
+
}
|
|
4571
|
+
}));
|
|
4572
|
+
return { startedAt: this.startedAt, url: initialUrl };
|
|
4573
|
+
}
|
|
4574
|
+
async stop() {
|
|
4575
|
+
if (!this.recording) {
|
|
4576
|
+
throw new Error("Action recorder is not running on this tab");
|
|
4577
|
+
}
|
|
4578
|
+
this.recording = false;
|
|
4579
|
+
const durationMs = Date.now() - this.startedAt;
|
|
4580
|
+
for (const off of this.unsubs)
|
|
4581
|
+
off();
|
|
4582
|
+
this.unsubs = [];
|
|
4583
|
+
if (this.scriptId) {
|
|
4584
|
+
await this.session.send("Page.removeScriptToEvaluateOnNewDocument", { identifier: this.scriptId }).catch(() => {
|
|
4585
|
+
});
|
|
4586
|
+
this.scriptId = null;
|
|
4587
|
+
}
|
|
4588
|
+
await this.session.send("Runtime.evaluate", { expression: "globalThis.__bpActionRecorderEnabled = false;" }).catch(() => {
|
|
4589
|
+
});
|
|
4590
|
+
return buildActionRecordingResult(this.steps, durationMs);
|
|
4591
|
+
}
|
|
4592
|
+
dispose() {
|
|
4593
|
+
this.recording = false;
|
|
4594
|
+
for (const off of this.unsubs)
|
|
4595
|
+
off();
|
|
4596
|
+
this.unsubs = [];
|
|
4597
|
+
}
|
|
4598
|
+
};
|
|
4599
|
+
|
|
3858
4600
|
// ../core/dist/tab.js
|
|
3859
4601
|
var BrowserPilotTab = class {
|
|
3860
4602
|
tabId;
|
|
@@ -3869,6 +4611,8 @@ var BrowserPilotTab = class {
|
|
|
3869
4611
|
editor;
|
|
3870
4612
|
performance;
|
|
3871
4613
|
recorder;
|
|
4614
|
+
downloads;
|
|
4615
|
+
actionRecorder;
|
|
3872
4616
|
initialized = false;
|
|
3873
4617
|
constructor(transport, tabId) {
|
|
3874
4618
|
this.tabId = tabId;
|
|
@@ -3883,6 +4627,8 @@ var BrowserPilotTab = class {
|
|
|
3883
4627
|
this.editor = new LiveEditor(this.session, this.debugger);
|
|
3884
4628
|
this.performance = new PerformanceProfiler(this.session);
|
|
3885
4629
|
this.recorder = new ScreenRecorder(this.session);
|
|
4630
|
+
this.downloads = new DownloadManager(this.session);
|
|
4631
|
+
this.actionRecorder = new ActionRecorder(this.session);
|
|
3886
4632
|
}
|
|
3887
4633
|
async ensureInitialized() {
|
|
3888
4634
|
if (this.initialized)
|
|
@@ -3926,6 +4672,8 @@ var BrowserPilotTab = class {
|
|
|
3926
4672
|
dispose() {
|
|
3927
4673
|
void this.recorder.cancel().catch(() => {
|
|
3928
4674
|
});
|
|
4675
|
+
this.downloads.dispose();
|
|
4676
|
+
this.actionRecorder.dispose();
|
|
3929
4677
|
this.console.dispose();
|
|
3930
4678
|
this.network.dispose();
|
|
3931
4679
|
this.styles.dispose();
|
|
@@ -3967,6 +4715,9 @@ var SessionManager = class {
|
|
|
3967
4715
|
getTransport() {
|
|
3968
4716
|
return this.transport;
|
|
3969
4717
|
}
|
|
4718
|
+
getAttachedTabCount() {
|
|
4719
|
+
return this.tabs.size;
|
|
4720
|
+
}
|
|
3970
4721
|
async getOrAttachTab(tabId, options) {
|
|
3971
4722
|
await this.transport.attachTab(tabId, options);
|
|
3972
4723
|
let tab = this.tabs.get(tabId);
|
|
@@ -4020,7 +4771,8 @@ var SessionManager = class {
|
|
|
4020
4771
|
session.activeTabId = void 0;
|
|
4021
4772
|
}
|
|
4022
4773
|
const allTabs = await this.listTabs();
|
|
4023
|
-
const
|
|
4774
|
+
const attachable = allTabs.filter((t) => !isRestrictedUrl(t.url));
|
|
4775
|
+
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];
|
|
4024
4776
|
if (candidate) {
|
|
4025
4777
|
const tab = await this.getOrAttachTab(candidate.tabId, groupOpts);
|
|
4026
4778
|
if (session)
|
|
@@ -4210,6 +4962,16 @@ var SessionManager = class {
|
|
|
4210
4962
|
const t = await getTab(tab);
|
|
4211
4963
|
return await t.session.send(method, params);
|
|
4212
4964
|
},
|
|
4965
|
+
downloads: {
|
|
4966
|
+
configure: async (downloadDir, tab) => (await getTab(tab)).downloads.configure(downloadDir),
|
|
4967
|
+
list: async (tab) => (await getTab(tab)).downloads.list(),
|
|
4968
|
+
waitFor: async (opts) => (await getTab(opts?.tab)).downloads.waitForDownload(opts)
|
|
4969
|
+
},
|
|
4970
|
+
actionRecorder: {
|
|
4971
|
+
start: async (opts) => (await getTab(opts?.tab)).actionRecorder.start(opts),
|
|
4972
|
+
stop: async (tab) => (await getTab(tab)).actionRecorder.stop(),
|
|
4973
|
+
steps: async (tab) => (await getTab(tab)).actionRecorder.getSteps()
|
|
4974
|
+
},
|
|
4213
4975
|
createDemoVideo
|
|
4214
4976
|
};
|
|
4215
4977
|
const context = vm.createContext(helpers);
|
|
@@ -4253,6 +5015,16 @@ ${code}
|
|
|
4253
5015
|
function textResult(text, meta) {
|
|
4254
5016
|
return { content: [{ type: "text", text }], meta };
|
|
4255
5017
|
}
|
|
5018
|
+
function normalizeNavigationUrl(raw) {
|
|
5019
|
+
const trimmed = (raw ?? "").trim();
|
|
5020
|
+
if (!trimmed) return "about:blank";
|
|
5021
|
+
if (/^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(trimmed)) {
|
|
5022
|
+
return `http://${trimmed}`;
|
|
5023
|
+
}
|
|
5024
|
+
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed)) return trimmed;
|
|
5025
|
+
if (/^(about|data|file|javascript|mailto|blob|view-source):/i.test(trimmed)) return trimmed;
|
|
5026
|
+
return `https://${trimmed}`;
|
|
5027
|
+
}
|
|
4256
5028
|
function formatFeedbackSuffix(fb) {
|
|
4257
5029
|
const parts = [`URL: ${fb.url}`];
|
|
4258
5030
|
if (fb.newConsoleErrors.length > 0) {
|
|
@@ -4847,7 +5619,7 @@ var TOOL_DEFINITIONS = [
|
|
|
4847
5619
|
},
|
|
4848
5620
|
{
|
|
4849
5621
|
name: "browser_record",
|
|
4850
|
-
description: "Record the active tab as an MP4/WebM video via CDP screencast + ffmpeg, or
|
|
5622
|
+
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.",
|
|
4851
5623
|
inputSchema: {
|
|
4852
5624
|
type: "object",
|
|
4853
5625
|
properties: {
|
|
@@ -4855,7 +5627,43 @@ var TOOL_DEFINITIONS = [
|
|
|
4855
5627
|
outputPath: { type: "string" },
|
|
4856
5628
|
recordingPath: { type: "string" },
|
|
4857
5629
|
frameRate: { type: "number" },
|
|
4858
|
-
|
|
5630
|
+
audio: { type: "boolean", description: "Tap page <audio>/<video>/AudioContext into the recording (default false)" },
|
|
5631
|
+
speed: { type: "number", description: "Speed multiplier for idle gaps (default 6 when actionTimestamps given, else 2)" },
|
|
5632
|
+
durationMs: { type: "number" },
|
|
5633
|
+
actionTimestamps: { type: "array", items: { type: "number" }, description: "Timestamps from stop() so only idle gaps are sped up while interactions stay 1x" },
|
|
5634
|
+
paddingMs: { type: "number" },
|
|
5635
|
+
tabId: { type: "number" },
|
|
5636
|
+
sessionId: { type: "string" }
|
|
5637
|
+
},
|
|
5638
|
+
required: ["action"]
|
|
5639
|
+
}
|
|
5640
|
+
},
|
|
5641
|
+
{
|
|
5642
|
+
name: "browser_downloads",
|
|
5643
|
+
description: "Configure download directory, list downloads, or wait for a file download to finish and return its local file path.",
|
|
5644
|
+
inputSchema: {
|
|
5645
|
+
type: "object",
|
|
5646
|
+
properties: {
|
|
5647
|
+
action: { type: "string", enum: ["configure", "list", "wait", "clear"] },
|
|
5648
|
+
downloadDir: { type: "string", description: "Target folder for Direct CDP downloads" },
|
|
5649
|
+
filenamePattern: { type: "string", description: "Optional substring/regex to match downloaded filename" },
|
|
5650
|
+
timeoutMs: { type: "number" },
|
|
5651
|
+
sinceTimestamp: { type: "number" },
|
|
5652
|
+
tabId: { type: "number" },
|
|
5653
|
+
sessionId: { type: "string" }
|
|
5654
|
+
},
|
|
5655
|
+
required: ["action"]
|
|
5656
|
+
}
|
|
5657
|
+
},
|
|
5658
|
+
{
|
|
5659
|
+
name: "browser_action_recorder",
|
|
5660
|
+
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.",
|
|
5661
|
+
inputSchema: {
|
|
5662
|
+
type: "object",
|
|
5663
|
+
properties: {
|
|
5664
|
+
action: { type: "string", enum: ["start", "stop", "status"] },
|
|
5665
|
+
maskPasswords: { type: "boolean", description: "Mask password inputs as <REDACTED_PASSWORD> (default true)" },
|
|
5666
|
+
format: { type: "string", enum: ["all", "batch", "script", "skill"] },
|
|
4859
5667
|
tabId: { type: "number" },
|
|
4860
5668
|
sessionId: { type: "string" }
|
|
4861
5669
|
},
|
|
@@ -4944,15 +5752,23 @@ async function executeTool(ctx, name, args = {}) {
|
|
|
4944
5752
|
return textResult(formatted || "(no tabs open)", { tabs });
|
|
4945
5753
|
}
|
|
4946
5754
|
case "browser_open_tab": {
|
|
5755
|
+
const targetUrl = normalizeNavigationUrl(args.url);
|
|
4947
5756
|
const tab = await manager.openTab({
|
|
4948
|
-
url:
|
|
5757
|
+
url: targetUrl,
|
|
4949
5758
|
active: args.active,
|
|
4950
5759
|
tabGroup: args.tabGroup,
|
|
4951
5760
|
tabGroupColor: args.tabGroupColor
|
|
4952
5761
|
});
|
|
4953
5762
|
if (sessionId) manager.getOrCreateSession(sessionId).activeTabId = tab.tabId;
|
|
4954
|
-
|
|
4955
|
-
|
|
5763
|
+
if (/^https?:\/\//i.test(targetUrl)) {
|
|
5764
|
+
await waitForPageLoad(tab.session, { timeoutMs: 6e3, idleMs: 200 }).catch(() => {
|
|
5765
|
+
});
|
|
5766
|
+
}
|
|
5767
|
+
const meta = await tab.page.getUrlAndTitle().catch(() => ({ url: targetUrl, title: "" }));
|
|
5768
|
+
return textResult(`Opened and attached tab [${tab.tabId}]: ${meta.url}${meta.title ? ` ("${meta.title}")` : ""}`, {
|
|
5769
|
+
tabId: tab.tabId,
|
|
5770
|
+
...meta
|
|
5771
|
+
});
|
|
4956
5772
|
}
|
|
4957
5773
|
case "browser_close_tab": {
|
|
4958
5774
|
await manager.closeTab(Number(args.tabId));
|
|
@@ -4975,8 +5791,9 @@ async function executeTool(ctx, name, args = {}) {
|
|
|
4975
5791
|
}
|
|
4976
5792
|
case "browser_navigate": {
|
|
4977
5793
|
const tab = await resolveTab();
|
|
5794
|
+
const targetUrl = normalizeNavigationUrl(String(args.url));
|
|
4978
5795
|
const { result, feedback } = await tab.runWithFeedback(
|
|
4979
|
-
() => tab.page.navigate(
|
|
5796
|
+
() => tab.page.navigate(targetUrl, {
|
|
4980
5797
|
waitUntil: args.waitUntil ?? "domcontentloaded",
|
|
4981
5798
|
timeoutMs: args.timeoutMs
|
|
4982
5799
|
})
|
|
@@ -5432,9 +6249,10 @@ ${formatFeedbackSuffix(feedback)}`);
|
|
|
5432
6249
|
if (action === "start") {
|
|
5433
6250
|
const out = await tab.recorder.start({
|
|
5434
6251
|
outputPath: String(args.outputPath ?? `./browserpilot-recording-${Date.now()}.mp4`),
|
|
5435
|
-
frameRate: args.frameRate
|
|
6252
|
+
frameRate: args.frameRate,
|
|
6253
|
+
audio: args.audio
|
|
5436
6254
|
});
|
|
5437
|
-
return textResult(`Recording started -> ${out.outputPath}`);
|
|
6255
|
+
return textResult(`Recording started -> ${out.outputPath}${out.audio ? " (audio tap enabled)" : ""}`);
|
|
5438
6256
|
}
|
|
5439
6257
|
if (action === "stop") {
|
|
5440
6258
|
const res = await tab.recorder.stop();
|
|
@@ -5448,12 +6266,71 @@ ${formatFeedbackSuffix(feedback)}`);
|
|
|
5448
6266
|
const out = await createDemoVideo({
|
|
5449
6267
|
recordingPath: String(args.recordingPath),
|
|
5450
6268
|
outputPath: args.outputPath,
|
|
5451
|
-
speed: args.speed
|
|
6269
|
+
speed: args.speed,
|
|
6270
|
+
durationMs: args.durationMs,
|
|
6271
|
+
actionTimestamps: args.actionTimestamps,
|
|
6272
|
+
paddingMs: args.paddingMs
|
|
5452
6273
|
});
|
|
5453
6274
|
return textResult(`Created demo video -> ${out}`);
|
|
5454
6275
|
}
|
|
5455
6276
|
throw new Error(`Unknown record action: ${action}`);
|
|
5456
6277
|
}
|
|
6278
|
+
case "browser_downloads": {
|
|
6279
|
+
const tab = await resolveTab();
|
|
6280
|
+
const action = String(args.action);
|
|
6281
|
+
if (action === "configure") {
|
|
6282
|
+
const res = await tab.downloads.configure(args.downloadDir);
|
|
6283
|
+
return textResult(JSON.stringify(res, null, 2));
|
|
6284
|
+
}
|
|
6285
|
+
if (action === "list") {
|
|
6286
|
+
const list = await tab.downloads.list();
|
|
6287
|
+
return textResult(JSON.stringify(list, null, 2));
|
|
6288
|
+
}
|
|
6289
|
+
if (action === "wait") {
|
|
6290
|
+
const entry = await tab.downloads.waitForDownload({
|
|
6291
|
+
timeoutMs: args.timeoutMs,
|
|
6292
|
+
filenamePattern: args.filenamePattern,
|
|
6293
|
+
sinceTimestamp: args.sinceTimestamp
|
|
6294
|
+
});
|
|
6295
|
+
return textResult(JSON.stringify(entry, null, 2));
|
|
6296
|
+
}
|
|
6297
|
+
if (action === "clear") {
|
|
6298
|
+
tab.downloads.clear();
|
|
6299
|
+
return textResult("Cleared tracked downloads");
|
|
6300
|
+
}
|
|
6301
|
+
throw new Error(`Unknown downloads action: ${action}`);
|
|
6302
|
+
}
|
|
6303
|
+
case "browser_action_recorder": {
|
|
6304
|
+
const tab = await resolveTab();
|
|
6305
|
+
const action = String(args.action);
|
|
6306
|
+
if (action === "start") {
|
|
6307
|
+
const res = await tab.actionRecorder.start({
|
|
6308
|
+
maskPasswords: args.maskPasswords
|
|
6309
|
+
});
|
|
6310
|
+
return textResult(`Action recording started on ${res.url || `tab [${tab.tabId}]`}`);
|
|
6311
|
+
}
|
|
6312
|
+
if (action === "status") {
|
|
6313
|
+
return textResult(
|
|
6314
|
+
JSON.stringify(
|
|
6315
|
+
{
|
|
6316
|
+
recording: tab.actionRecorder.isRecording(),
|
|
6317
|
+
recordedSteps: tab.actionRecorder.getSteps().length
|
|
6318
|
+
},
|
|
6319
|
+
null,
|
|
6320
|
+
2
|
|
6321
|
+
)
|
|
6322
|
+
);
|
|
6323
|
+
}
|
|
6324
|
+
if (action === "stop") {
|
|
6325
|
+
const res = await tab.actionRecorder.stop();
|
|
6326
|
+
const fmt = String(args.format ?? "all");
|
|
6327
|
+
if (fmt === "skill") return textResult(res.skillMarkdown);
|
|
6328
|
+
if (fmt === "script") return textResult(res.execScript);
|
|
6329
|
+
if (fmt === "batch") return textResult(JSON.stringify(res.batchSteps, null, 2));
|
|
6330
|
+
return textResult(JSON.stringify(res, null, 2));
|
|
6331
|
+
}
|
|
6332
|
+
throw new Error(`Unknown action_recorder action: ${action}`);
|
|
6333
|
+
}
|
|
5457
6334
|
case "browser_exec": {
|
|
5458
6335
|
const res = await manager.exec(sessionId ?? "default", String(args.code), {
|
|
5459
6336
|
timeoutMs: args.timeoutMs,
|
|
@@ -5680,6 +6557,15 @@ var BrowserPilotDaemon = class {
|
|
|
5680
6557
|
};
|
|
5681
6558
|
this.backends.set(clientId, { info, transport, manager });
|
|
5682
6559
|
this.primaryClientId = clientId;
|
|
6560
|
+
if (ws.readyState === ws.OPEN) {
|
|
6561
|
+
ws.send(
|
|
6562
|
+
JSON.stringify({
|
|
6563
|
+
type: "event",
|
|
6564
|
+
event: "bridge.ready",
|
|
6565
|
+
params: { version: BROWSERPILOT_VERSION, clientId }
|
|
6566
|
+
})
|
|
6567
|
+
);
|
|
6568
|
+
}
|
|
5683
6569
|
ws.on("close", () => {
|
|
5684
6570
|
manager.dispose();
|
|
5685
6571
|
this.backends.delete(clientId);
|
|
@@ -5722,7 +6608,10 @@ var BrowserPilotDaemon = class {
|
|
|
5722
6608
|
return info;
|
|
5723
6609
|
}
|
|
5724
6610
|
listClients() {
|
|
5725
|
-
return Array.from(this.backends.values()).map((b) =>
|
|
6611
|
+
return Array.from(this.backends.values()).map((b) => ({
|
|
6612
|
+
...b.info,
|
|
6613
|
+
attachedTabCount: b.manager.getAttachedTabCount()
|
|
6614
|
+
}));
|
|
5726
6615
|
}
|
|
5727
6616
|
getManager(clientId) {
|
|
5728
6617
|
const targetId = clientId ?? this.primaryClientId;
|
|
@@ -5755,6 +6644,7 @@ var BrowserPilotDaemon = class {
|
|
|
5755
6644
|
this.sendJson(res, 200, {
|
|
5756
6645
|
ok: true,
|
|
5757
6646
|
version: BROWSERPILOT_VERSION,
|
|
6647
|
+
pid: process.pid,
|
|
5758
6648
|
uptimeMs: Date.now() - this.startedAt,
|
|
5759
6649
|
clients: this.listClients()
|
|
5760
6650
|
});
|
|
@@ -5847,9 +6737,9 @@ var BrowserPilotDaemon = class {
|
|
|
5847
6737
|
|
|
5848
6738
|
// src/client.ts
|
|
5849
6739
|
import { spawn as spawn2 } from "node:child_process";
|
|
5850
|
-
import
|
|
6740
|
+
import path5 from "node:path";
|
|
5851
6741
|
import { fileURLToPath } from "node:url";
|
|
5852
|
-
var __dirname =
|
|
6742
|
+
var __dirname = path5.dirname(fileURLToPath(import.meta.url));
|
|
5853
6743
|
var DaemonClient = class _DaemonClient {
|
|
5854
6744
|
config;
|
|
5855
6745
|
constructor(config) {
|
|
@@ -5860,7 +6750,7 @@ var DaemonClient = class _DaemonClient {
|
|
|
5860
6750
|
if (await isDaemonReachable(cfg)) {
|
|
5861
6751
|
return new _DaemonClient(cfg);
|
|
5862
6752
|
}
|
|
5863
|
-
const cliEntry =
|
|
6753
|
+
const cliEntry = path5.resolve(__dirname, "cli.js");
|
|
5864
6754
|
const child = spawn2(
|
|
5865
6755
|
process.execPath,
|
|
5866
6756
|
[cliEntry, "daemon", "run", "--host", cfg.host, "--port", String(cfg.port)],
|
|
@@ -5968,14 +6858,27 @@ async function startMcpServer(options = {}) {
|
|
|
5968
6858
|
};
|
|
5969
6859
|
result = await executeTool(ctx, name, args);
|
|
5970
6860
|
} else {
|
|
5971
|
-
|
|
5972
|
-
daemonClient
|
|
5973
|
-
|
|
5974
|
-
|
|
5975
|
-
|
|
5976
|
-
|
|
6861
|
+
const ensureDaemon = async () => {
|
|
6862
|
+
if (!daemonClient) {
|
|
6863
|
+
daemonClient = await DaemonClient.connectOrStart({
|
|
6864
|
+
host: options.daemonHost,
|
|
6865
|
+
port: options.daemonPort,
|
|
6866
|
+
token: options.daemonToken
|
|
6867
|
+
});
|
|
6868
|
+
}
|
|
6869
|
+
return daemonClient;
|
|
6870
|
+
};
|
|
6871
|
+
try {
|
|
6872
|
+
result = await (await ensureDaemon()).callTool(name, args);
|
|
6873
|
+
} catch (err) {
|
|
6874
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
6875
|
+
if (/fetch failed|ECONNREFUSED|ECONNRESET|socket|Unauthorized/i.test(msg)) {
|
|
6876
|
+
daemonClient = null;
|
|
6877
|
+
result = await (await ensureDaemon()).callTool(name, args);
|
|
6878
|
+
} else {
|
|
6879
|
+
throw err;
|
|
6880
|
+
}
|
|
5977
6881
|
}
|
|
5978
|
-
result = await daemonClient.callTool(name, args);
|
|
5979
6882
|
}
|
|
5980
6883
|
return {
|
|
5981
6884
|
isError: result.isError,
|
|
@@ -5992,41 +6895,189 @@ async function startMcpServer(options = {}) {
|
|
|
5992
6895
|
}
|
|
5993
6896
|
|
|
5994
6897
|
// src/native-install.ts
|
|
5995
|
-
import
|
|
5996
|
-
import
|
|
5997
|
-
import
|
|
6898
|
+
import crypto3 from "node:crypto";
|
|
6899
|
+
import fs5 from "node:fs/promises";
|
|
6900
|
+
import os4 from "node:os";
|
|
6901
|
+
import path6 from "node:path";
|
|
5998
6902
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
5999
|
-
var __dirname2 =
|
|
6903
|
+
var __dirname2 = path6.dirname(fileURLToPath2(import.meta.url));
|
|
6000
6904
|
function getNativeMessagingHostDirs(platform = process.platform) {
|
|
6001
|
-
const home =
|
|
6905
|
+
const home = os4.homedir();
|
|
6002
6906
|
if (platform === "darwin") {
|
|
6003
|
-
const appSupport =
|
|
6907
|
+
const appSupport = path6.join(home, "Library", "Application Support");
|
|
6004
6908
|
return [
|
|
6005
|
-
{
|
|
6006
|
-
|
|
6007
|
-
|
|
6008
|
-
|
|
6009
|
-
|
|
6010
|
-
{
|
|
6011
|
-
|
|
6909
|
+
{
|
|
6910
|
+
name: "Google Chrome",
|
|
6911
|
+
userDataDir: path6.join(appSupport, "Google", "Chrome"),
|
|
6912
|
+
dir: path6.join(appSupport, "Google", "Chrome", "NativeMessagingHosts")
|
|
6913
|
+
},
|
|
6914
|
+
{
|
|
6915
|
+
name: "Google Chrome Canary",
|
|
6916
|
+
userDataDir: path6.join(appSupport, "Google", "Chrome Canary"),
|
|
6917
|
+
dir: path6.join(appSupport, "Google", "Chrome Canary", "NativeMessagingHosts")
|
|
6918
|
+
},
|
|
6919
|
+
{
|
|
6920
|
+
name: "Google Chrome for Testing",
|
|
6921
|
+
userDataDir: path6.join(appSupport, "Google", "Chrome for Testing"),
|
|
6922
|
+
dir: path6.join(appSupport, "Google", "Chrome for Testing", "NativeMessagingHosts")
|
|
6923
|
+
},
|
|
6924
|
+
{
|
|
6925
|
+
name: "Chromium",
|
|
6926
|
+
userDataDir: path6.join(appSupport, "Chromium"),
|
|
6927
|
+
dir: path6.join(appSupport, "Chromium", "NativeMessagingHosts")
|
|
6928
|
+
},
|
|
6929
|
+
{
|
|
6930
|
+
name: "Brave",
|
|
6931
|
+
userDataDir: path6.join(appSupport, "BraveSoftware", "Brave-Browser"),
|
|
6932
|
+
dir: path6.join(appSupport, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts")
|
|
6933
|
+
},
|
|
6934
|
+
{
|
|
6935
|
+
name: "Microsoft Edge",
|
|
6936
|
+
userDataDir: path6.join(appSupport, "Microsoft Edge"),
|
|
6937
|
+
dir: path6.join(appSupport, "Microsoft Edge", "NativeMessagingHosts")
|
|
6938
|
+
},
|
|
6939
|
+
{
|
|
6940
|
+
name: "Arc",
|
|
6941
|
+
userDataDir: path6.join(appSupport, "Arc", "User Data"),
|
|
6942
|
+
dir: path6.join(appSupport, "Arc", "User Data", "NativeMessagingHosts")
|
|
6943
|
+
}
|
|
6012
6944
|
];
|
|
6013
6945
|
}
|
|
6014
6946
|
if (platform === "linux") {
|
|
6015
|
-
const config =
|
|
6947
|
+
const config = path6.join(home, ".config");
|
|
6016
6948
|
return [
|
|
6017
|
-
{
|
|
6018
|
-
|
|
6019
|
-
|
|
6020
|
-
|
|
6949
|
+
{
|
|
6950
|
+
name: "Google Chrome",
|
|
6951
|
+
userDataDir: path6.join(config, "google-chrome"),
|
|
6952
|
+
dir: path6.join(config, "google-chrome", "NativeMessagingHosts")
|
|
6953
|
+
},
|
|
6954
|
+
{
|
|
6955
|
+
name: "Chromium",
|
|
6956
|
+
userDataDir: path6.join(config, "chromium"),
|
|
6957
|
+
dir: path6.join(config, "chromium", "NativeMessagingHosts")
|
|
6958
|
+
},
|
|
6959
|
+
{
|
|
6960
|
+
name: "Brave",
|
|
6961
|
+
userDataDir: path6.join(config, "BraveSoftware", "Brave-Browser"),
|
|
6962
|
+
dir: path6.join(config, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts")
|
|
6963
|
+
},
|
|
6964
|
+
{
|
|
6965
|
+
name: "Microsoft Edge",
|
|
6966
|
+
userDataDir: path6.join(config, "microsoft-edge"),
|
|
6967
|
+
dir: path6.join(config, "microsoft-edge", "NativeMessagingHosts")
|
|
6968
|
+
}
|
|
6021
6969
|
];
|
|
6022
6970
|
}
|
|
6023
6971
|
return [];
|
|
6024
6972
|
}
|
|
6973
|
+
function computeChromeExtensionId(unpackedDir) {
|
|
6974
|
+
const normalized = path6.resolve(unpackedDir);
|
|
6975
|
+
const hash = crypto3.createHash("sha256").update(normalized, "utf8").digest("hex").slice(0, 32);
|
|
6976
|
+
return hash.replace(/[0-9a-f]/g, (ch) => String.fromCharCode(97 + Number.parseInt(ch, 16)));
|
|
6977
|
+
}
|
|
6978
|
+
function getStableExtensionDir() {
|
|
6979
|
+
return path6.join(getBrowserPilotHomeDir(), "extension");
|
|
6980
|
+
}
|
|
6981
|
+
async function syncExtensionToHome(sourceExtDir, options = {}) {
|
|
6982
|
+
const destDir = getStableExtensionDir();
|
|
6983
|
+
let version = null;
|
|
6984
|
+
try {
|
|
6985
|
+
const manifestRaw = await fs5.readFile(path6.join(sourceExtDir, "manifest.json"), "utf8");
|
|
6986
|
+
const manifest = JSON.parse(manifestRaw);
|
|
6987
|
+
version = manifest.version ?? null;
|
|
6988
|
+
} catch {
|
|
6989
|
+
}
|
|
6990
|
+
let synced = false;
|
|
6991
|
+
if (!options.dryRun) {
|
|
6992
|
+
await ensureBrowserPilotHome();
|
|
6993
|
+
const resolvedSrc = await fs5.realpath(sourceExtDir).catch(() => path6.resolve(sourceExtDir));
|
|
6994
|
+
const resolvedDest = await fs5.realpath(destDir).catch(() => path6.resolve(destDir));
|
|
6995
|
+
if (resolvedSrc !== resolvedDest) {
|
|
6996
|
+
await fs5.rm(destDir, { recursive: true, force: true });
|
|
6997
|
+
await fs5.cp(sourceExtDir, destDir, { recursive: true });
|
|
6998
|
+
synced = true;
|
|
6999
|
+
}
|
|
7000
|
+
}
|
|
7001
|
+
const realDest = await fs5.realpath(destDir).catch(() => path6.resolve(destDir));
|
|
7002
|
+
return {
|
|
7003
|
+
extensionDir: realDest,
|
|
7004
|
+
extensionId: computeChromeExtensionId(realDest),
|
|
7005
|
+
version,
|
|
7006
|
+
synced
|
|
7007
|
+
};
|
|
7008
|
+
}
|
|
7009
|
+
async function discoverInstalledExtensionIds(platform = process.platform) {
|
|
7010
|
+
const found = [];
|
|
7011
|
+
const seen = /* @__PURE__ */ new Set();
|
|
7012
|
+
for (const target of getNativeMessagingHostDirs(platform)) {
|
|
7013
|
+
let entries;
|
|
7014
|
+
try {
|
|
7015
|
+
entries = await fs5.readdir(target.userDataDir);
|
|
7016
|
+
} catch {
|
|
7017
|
+
continue;
|
|
7018
|
+
}
|
|
7019
|
+
const profiles = entries.filter((e) => e === "Default" || e.startsWith("Profile "));
|
|
7020
|
+
for (const profile of profiles) {
|
|
7021
|
+
for (const fileName of ["Secure Preferences", "Preferences"]) {
|
|
7022
|
+
const prefPath = path6.join(target.userDataDir, profile, fileName);
|
|
7023
|
+
let parsed;
|
|
7024
|
+
try {
|
|
7025
|
+
parsed = JSON.parse(await fs5.readFile(prefPath, "utf8"));
|
|
7026
|
+
} catch {
|
|
7027
|
+
continue;
|
|
7028
|
+
}
|
|
7029
|
+
const settings = parsed.extensions?.settings;
|
|
7030
|
+
if (!settings || typeof settings !== "object") continue;
|
|
7031
|
+
for (const [extId, meta] of Object.entries(settings)) {
|
|
7032
|
+
if (!meta || !/^[a-p]{32}$/.test(extId)) continue;
|
|
7033
|
+
const manifestName = meta.manifest?.name || "";
|
|
7034
|
+
const extPath = meta.path || "";
|
|
7035
|
+
let isBrowserPilot = /^browserpilot$/i.test(manifestName) || /browserpilot/i.test(extPath);
|
|
7036
|
+
if (!isBrowserPilot && meta.location === 4 && extPath) {
|
|
7037
|
+
try {
|
|
7038
|
+
const m = JSON.parse(await fs5.readFile(path6.join(extPath, "manifest.json"), "utf8"));
|
|
7039
|
+
if (/^browserpilot$/i.test(m.name || "")) isBrowserPilot = true;
|
|
7040
|
+
} catch {
|
|
7041
|
+
}
|
|
7042
|
+
}
|
|
7043
|
+
if (isBrowserPilot && !seen.has(extId)) {
|
|
7044
|
+
seen.add(extId);
|
|
7045
|
+
found.push({ browser: target.name, profile, extensionId: extId, path: extPath || void 0 });
|
|
7046
|
+
}
|
|
7047
|
+
}
|
|
7048
|
+
}
|
|
7049
|
+
}
|
|
7050
|
+
}
|
|
7051
|
+
return found;
|
|
7052
|
+
}
|
|
7053
|
+
async function readInstalledNativeHosts(platform = process.platform) {
|
|
7054
|
+
const results = [];
|
|
7055
|
+
for (const target of getNativeMessagingHostDirs(platform)) {
|
|
7056
|
+
const mp = path6.join(target.dir, `${NATIVE_HOST_NAME}.json`);
|
|
7057
|
+
try {
|
|
7058
|
+
const parsed = JSON.parse(await fs5.readFile(mp, "utf8"));
|
|
7059
|
+
results.push({
|
|
7060
|
+
browser: target.name,
|
|
7061
|
+
installed: true,
|
|
7062
|
+
path: mp,
|
|
7063
|
+
allowedOrigins: Array.isArray(parsed.allowed_origins) ? parsed.allowed_origins : [],
|
|
7064
|
+
wrapperPath: parsed.path
|
|
7065
|
+
});
|
|
7066
|
+
} catch {
|
|
7067
|
+
results.push({ browser: target.name, installed: false, path: mp, allowedOrigins: [] });
|
|
7068
|
+
}
|
|
7069
|
+
}
|
|
7070
|
+
return results;
|
|
7071
|
+
}
|
|
6025
7072
|
async function installNativeHost(options) {
|
|
6026
|
-
const nativeHostJs =
|
|
6027
|
-
const binDir =
|
|
6028
|
-
const wrapperPath =
|
|
6029
|
-
const allowedOrigins =
|
|
7073
|
+
const nativeHostJs = path6.resolve(__dirname2, "native-host.js");
|
|
7074
|
+
const binDir = path6.join(getBrowserPilotHomeDir(), "bin");
|
|
7075
|
+
const wrapperPath = path6.join(binDir, "browserpilot-native-host");
|
|
7076
|
+
const allowedOrigins = Array.from(
|
|
7077
|
+
new Set(
|
|
7078
|
+
options.extensionIds.map((id) => id.trim()).filter(Boolean).map((id) => id.startsWith("chrome-extension://") ? id.endsWith("/") ? id : `${id}/` : `chrome-extension://${id}/`)
|
|
7079
|
+
)
|
|
7080
|
+
);
|
|
6030
7081
|
const manifestJson = {
|
|
6031
7082
|
name: NATIVE_HOST_NAME,
|
|
6032
7083
|
description: "BrowserPilot Zero-Click Browser Control & DevTools Bridge",
|
|
@@ -6041,30 +7092,30 @@ exec ${JSON.stringify(process.execPath)} ${JSON.stringify(nativeHostJs)} "$@"
|
|
|
6041
7092
|
const installedManifests = [];
|
|
6042
7093
|
if (!options.dryRun) {
|
|
6043
7094
|
await ensureBrowserPilotHome();
|
|
6044
|
-
await
|
|
6045
|
-
await
|
|
7095
|
+
await fs5.mkdir(binDir, { recursive: true, mode: 448 });
|
|
7096
|
+
await fs5.writeFile(wrapperPath, wrapperScript, { mode: 493 });
|
|
6046
7097
|
for (const target of targets) {
|
|
6047
|
-
const parentDir =
|
|
7098
|
+
const parentDir = path6.dirname(target.dir);
|
|
6048
7099
|
let exists = target.name === "Google Chrome";
|
|
6049
7100
|
if (!exists) {
|
|
6050
7101
|
try {
|
|
6051
|
-
await
|
|
7102
|
+
await fs5.access(parentDir);
|
|
6052
7103
|
exists = true;
|
|
6053
7104
|
} catch {
|
|
6054
7105
|
exists = false;
|
|
6055
7106
|
}
|
|
6056
7107
|
}
|
|
6057
7108
|
if (!exists) continue;
|
|
6058
|
-
await
|
|
6059
|
-
const manifestPath =
|
|
6060
|
-
await
|
|
7109
|
+
await fs5.mkdir(target.dir, { recursive: true });
|
|
7110
|
+
const manifestPath = path6.join(target.dir, `${NATIVE_HOST_NAME}.json`);
|
|
7111
|
+
await fs5.writeFile(manifestPath, JSON.stringify(manifestJson, null, 2) + "\n", "utf8");
|
|
6061
7112
|
installedManifests.push({ browser: target.name, manifestPath });
|
|
6062
7113
|
}
|
|
6063
7114
|
} else {
|
|
6064
7115
|
for (const target of targets) {
|
|
6065
7116
|
installedManifests.push({
|
|
6066
7117
|
browser: target.name,
|
|
6067
|
-
manifestPath:
|
|
7118
|
+
manifestPath: path6.join(target.dir, `${NATIVE_HOST_NAME}.json`)
|
|
6068
7119
|
});
|
|
6069
7120
|
}
|
|
6070
7121
|
}
|
|
@@ -6097,7 +7148,9 @@ BrowserPilot controls your real logged-in Chrome browser (existing cookies, logi
|
|
|
6097
7148
|
- \`browser_live_edit\` \u2014 grep loaded scripts and live-patch JS/CSS in memory.
|
|
6098
7149
|
- \`browser_performance\` \u2014 Core Web Vitals (LCP/CLS/FCP/TTFB), heap summary, CPU profiler, Tracing insights.
|
|
6099
7150
|
- \`browser_emulate\` \u2014 viewport, mobile, dark mode, CPU throttling, Slow 3G / offline.
|
|
6100
|
-
- \`
|
|
7151
|
+
- \`browser_downloads\` \u2014 configure download folder, list downloads, or wait for a file download to complete with its local path.
|
|
7152
|
+
- \`browser_action_recorder\` \u2014 record user clicks/fills/selects/navigations into reusable batch steps, exec JS script, and Agent Skill Markdown.
|
|
7153
|
+
- \`browser_record\` \u2014 record MP4/WebM screencast video via \`ffmpeg\` (optional \`audio: true\`) and create smart idle-sped-up demo videos.
|
|
6101
7154
|
6. **Multi-step Stateful Sandbox (Playwriter replacement)**:
|
|
6102
7155
|
- \`browserpilot session new --tab-group docs\` -> returns session ID (e.g. \`1\`)
|
|
6103
7156
|
- \`browserpilot exec -s 1 -e 'const t = await tabs.open("https://example.com"); console.log(await snapshot({ tab: t }))'\`
|
|
@@ -6112,17 +7165,23 @@ export {
|
|
|
6112
7165
|
BrowserPilotDaemon,
|
|
6113
7166
|
DaemonClient,
|
|
6114
7167
|
TOOL_DEFINITIONS,
|
|
7168
|
+
computeChromeExtensionId,
|
|
7169
|
+
discoverInstalledExtensionIds,
|
|
6115
7170
|
ensureBrowserPilotHome,
|
|
6116
7171
|
executeTool,
|
|
6117
7172
|
getBrowserPilotHomeDir,
|
|
6118
7173
|
getDaemonConfigPath,
|
|
6119
7174
|
getDaemonLogPath,
|
|
6120
7175
|
getNativeMessagingHostDirs,
|
|
7176
|
+
getStableExtensionDir,
|
|
6121
7177
|
installNativeHost,
|
|
6122
7178
|
isDaemonReachable,
|
|
6123
7179
|
loadOrCreateDaemonConfig,
|
|
7180
|
+
normalizeNavigationUrl,
|
|
6124
7181
|
readDaemonConfig,
|
|
7182
|
+
readInstalledNativeHosts,
|
|
6125
7183
|
startMcpServer,
|
|
7184
|
+
syncExtensionToHome,
|
|
6126
7185
|
writeDaemonRuntimeInfo
|
|
6127
7186
|
};
|
|
6128
7187
|
//# sourceMappingURL=index.js.map
|