@parcha/pi-browser 0.1.0-beta.30 → 0.1.0-beta.301
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/CHANGELOG.md +239 -0
- package/NOTICE +39 -4
- package/README.md +125 -236
- package/dist/core/contract.d.ts +17 -5
- package/dist/core/contract.js +36 -33
- package/dist/core/custody.d.ts +19 -2
- package/dist/core/custody.js +28 -6
- package/dist/core/downloads.d.ts +44 -3
- package/dist/core/downloads.js +94 -58
- package/dist/core/driving-guard.d.ts +20 -0
- package/dist/core/driving-guard.js +190 -23
- package/dist/core/driving.d.ts +56 -2
- package/dist/core/driving.js +189 -10
- package/dist/core/effects.d.ts +80 -6
- package/dist/core/effects.js +374 -41
- package/dist/core/evidence.d.ts +1 -1
- package/dist/core/failures.d.ts +15 -1
- package/dist/core/failures.js +7 -0
- package/dist/core/files.d.ts +20 -2
- package/dist/core/files.js +161 -10
- package/dist/core/host.d.ts +29 -77
- package/dist/core/images.d.ts +32 -4
- package/dist/core/images.js +81 -16
- package/dist/core/lease.d.ts +2 -1
- package/dist/core/page-scan.d.ts +81 -2
- package/dist/core/page-scan.js +487 -13
- package/dist/core/public-fetch.d.ts +70 -9
- package/dist/core/public-fetch.js +348 -51
- package/dist/core/read-page-worker.js +5 -4
- package/dist/core/read-page.d.ts +23 -8
- package/dist/core/read-page.js +64 -20
- package/dist/core/redact.d.ts +0 -2
- package/dist/core/redact.js +0 -32
- package/dist/core/session-control.d.ts +0 -2
- package/dist/core/session-control.js +0 -5
- package/dist/core/tools.d.ts +46 -1
- package/dist/core/tools.js +88 -12
- package/dist/core/usage.d.ts +4 -3
- package/dist/core/usage.js +5 -4
- package/dist/core/vault.d.ts +0 -10
- package/dist/core/vault.js +0 -13
- package/dist/core/web.d.ts +2 -111
- package/dist/core/web.js +0 -443
- package/dist/driver/cdp.d.ts +6 -0
- package/dist/driver/cdp.js +245 -0
- package/dist/driver/page-driver.js +110 -7
- package/dist/driver/sealed.d.ts +4 -12
- package/dist/driver/sealed.js +23 -37
- package/dist/driver/stagehand.d.ts +12 -15
- package/dist/driver/stagehand.js +21 -17
- package/dist/durable/result.d.ts +1 -2
- package/dist/durable/result.js +2 -2
- package/dist/durable/store.d.ts +17 -3
- package/dist/durable/store.js +231 -64
- package/dist/durable.d.ts +50 -17
- package/dist/durable.js +107 -106
- package/dist/index.d.ts +3 -3
- package/dist/index.js +5 -3
- package/dist/live-view/index.d.ts +4 -1
- package/dist/live-view/index.js +5 -0
- package/dist/live-view/protocol.d.ts +39 -7
- package/dist/live-view/protocol.js +2 -0
- package/dist/live-view/provider.d.ts +2 -2
- package/dist/live-view/provider.js +2 -2
- package/dist/live-view/server.d.ts +55 -2
- package/dist/live-view/server.js +282 -35
- package/dist/live-view/stream.js +16 -3
- package/dist/live-view/viewer.js +106 -13
- package/dist/providers/cdp.d.ts +0 -1
- package/dist/providers/cdp.js +35 -13
- package/dist/providers/chrome-args.d.ts +3 -0
- package/dist/providers/chrome-args.js +13 -2
- package/dist/providers/profiles.d.ts +1 -15
- package/dist/providers/profiles.js +1 -64
- package/dist/providers/shared.d.ts +1 -47
- package/dist/providers/shared.js +1 -82
- package/dist/providers/worker-extension.d.ts +20 -1
- package/dist/providers/worker-extension.js +86 -7
- package/dist/testing/backend.d.ts +6 -24
- package/dist/testing/backend.js +7 -30
- package/dist/vault-session.d.ts +4 -7
- package/dist/vault-session.js +26 -81
- package/dist/vendor/browser-use-pi/ax.d.ts +106 -0
- package/dist/vendor/browser-use-pi/ax.js +642 -0
- package/dist/vendor/browser-use-pi/cdp.d.ts +19 -0
- package/dist/vendor/browser-use-pi/cdp.js +106 -0
- package/dist/vendor/browser-use-pi/page.d.ts +29 -0
- package/dist/vendor/browser-use-pi/page.js +99 -0
- package/package.json +15 -46
- package/src/vendor/browser-use-pi/UPSTREAM.json +25 -0
- package/src/vendor/stagehand-facade/UPSTREAM.json +0 -4
- package/dist/coding-agent-local.d.ts +0 -12
- package/dist/coding-agent-local.js +0 -72
- package/dist/coding-agent.d.ts +0 -134
- package/dist/coding-agent.js +0 -640
- package/dist/core/sites.d.ts +0 -33
- package/dist/core/sites.js +0 -104
- package/dist/driver/extension-worker.d.ts +0 -9
- package/dist/driver/extension-worker.js +0 -185
- package/dist/durable/web.d.ts +0 -47
- package/dist/durable/web.js +0 -41
- package/dist/providers/assigned.d.ts +0 -18
- package/dist/providers/assigned.js +0 -75
- package/dist/providers/browserbase-net.d.ts +0 -12
- package/dist/providers/browserbase-net.js +0 -95
- package/dist/providers/browserbase.d.ts +0 -169
- package/dist/providers/browserbase.js +0 -319
- package/dist/providers/kernel.d.ts +0 -58
- package/dist/providers/kernel.js +0 -291
- package/dist/recorder/credential.d.ts +0 -9
- package/dist/recorder/credential.js +0 -49
- package/dist/recorder/follow.d.ts +0 -36
- package/dist/recorder/follow.js +0 -163
- package/dist/recorder/frames.d.ts +0 -87
- package/dist/recorder/frames.js +0 -377
- package/dist/recorder/index.d.ts +0 -4
- package/dist/recorder/index.js +0 -7
- package/dist/recorder/jpeg.d.ts +0 -8
- package/dist/recorder/jpeg.js +0 -70
- package/dist/recorder/track.d.ts +0 -107
- package/dist/recorder/track.js +0 -280
- package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +0 -15
- package/dist/vendor/stagehand-facade/screenshot-transport.js +0 -51
- /package/dist/{providers → core}/cdp-call.d.ts +0 -0
- /package/dist/{providers → core}/cdp-call.js +0 -0
package/dist/live-view/viewer.js
CHANGED
|
@@ -5,6 +5,9 @@
|
|
|
5
5
|
// its first message; nothing else is sent before the server has answered. Frames arrive as binary [u16 w][u16 h][jpeg] and are drawn to the canvas; mouse, wheel, key and paste on the canvas go
|
|
6
6
|
// back as protocol.ts messages in the page's own CSS pixels (the w and h of the latest frame), and the address bar and its back and reload buttons go back as `nav`. It writes no frame to
|
|
7
7
|
// storage: a frame lives in the canvas and in the one decode in flight.
|
|
8
|
+
//
|
|
9
|
+
// A take-over viewer (`ready` with takeOver) shows Take over / Hand back in its own bar: it sends `take` and `give`, and nothing else until the host
|
|
10
|
+
// says it holds the browser (`hold`); the host drops anything else it sends outside a hold anyway (held not_taken).
|
|
8
11
|
const html = `<!doctype html>
|
|
9
12
|
<html lang="en">
|
|
10
13
|
<head>
|
|
@@ -18,14 +21,17 @@ const html = `<!doctype html>
|
|
|
18
21
|
<button id="back" type="button" title="Back" aria-label="Back">←</button>
|
|
19
22
|
<button id="reload" type="button" title="Reload" aria-label="Reload">↻</button>
|
|
20
23
|
<form id="go" autocomplete="off"><input id="url" type="text" spellcheck="false" aria-label="Address" placeholder="https://"></form>
|
|
24
|
+
<button id="hands" type="button" hidden>Take over</button>
|
|
21
25
|
<span id="drive" aria-live="polite"></span>
|
|
22
26
|
</header>
|
|
27
|
+
<div id="watching" role="note" hidden><span id="watching-text">View only: you're watching the agent's browser; your clicks and keys are not sent.</span><span id="where"></span></div>
|
|
23
28
|
<div id="notice" role="status" hidden></div>
|
|
24
29
|
<div id="still" role="status" hidden>This page is in a background tab or has not drawn yet, so there is no picture until it is shown. Typing and clicking still work.</div>
|
|
25
30
|
<div id="dialog" role="alertdialog" aria-modal="true" hidden>
|
|
26
31
|
<div id="dialog-box">
|
|
27
32
|
<p id="dialog-kind"></p>
|
|
28
33
|
<p id="dialog-message"></p>
|
|
34
|
+
<p id="dialog-held" hidden>Take over to answer.</p>
|
|
29
35
|
<input id="dialog-prompt" type="text" hidden aria-label="Answer">
|
|
30
36
|
<div id="dialog-buttons"><button id="dialog-accept" type="button">OK</button><button id="dialog-dismiss" type="button">Cancel</button></div>
|
|
31
37
|
</div>
|
|
@@ -46,21 +52,37 @@ body { display: flex; flex-direction: column; }
|
|
|
46
52
|
#drive { min-width: 9em; text-align: right; color: #aaa; }
|
|
47
53
|
#drive.agent { color: #f0b429; }
|
|
48
54
|
#drive.person { color: #6cc070; }
|
|
55
|
+
.view-only #screen, .not-held #screen { cursor: not-allowed; }
|
|
56
|
+
#bar #hands { background: #1f4d2b; border-color: #2f6b3d; position: relative; z-index: 2; }
|
|
57
|
+
#bar #hands.holding { background: #5a3b00; border-color: #7a5410; }
|
|
58
|
+
#hands[hidden] { display: none; }
|
|
49
59
|
#notice { padding: 6px 10px; background: #5a3b00; color: #ffe2a8; }
|
|
50
|
-
|
|
51
|
-
#
|
|
52
|
-
#
|
|
60
|
+
/* An end (the session released, the viewer refused or disconnected) reads at a glance, over a dimmed page. */
|
|
61
|
+
#notice.fatal { background: #5a1a1a; color: #ffc4c4; font-size: 18px; font-weight: 600; text-align: center; padding: 18px 16px; }
|
|
62
|
+
body.over #stage { opacity: 0.35; }
|
|
63
|
+
/* Watch only: nothing in the toolbar acts, so it is not drawn; the banner says what this view is. */
|
|
64
|
+
.view-only #bar { display: none; }
|
|
65
|
+
#watching { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 16px; padding: 10px 14px; background: #17324d; color: #d6e9ff; font-size: 16px; font-weight: 600; border-bottom: 1px solid #24507a; }
|
|
66
|
+
#watching-text { flex: 0 1 auto; }
|
|
67
|
+
/* Where the agent is: text, never a field; a long address ends in an ellipsis and its whole is the tooltip. */
|
|
68
|
+
#where { flex: 1 1 14em; min-width: 0; text-align: right; font-weight: 400; font-size: 14px; color: #a9c7e6; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
69
|
+
#watching[hidden] { display: none; }
|
|
70
|
+
/* The page fills the stage at its own shape: the script sizes the canvas to fit, so a point on it maps to the page exactly. */
|
|
71
|
+
#stage { flex: 1; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: hidden; }
|
|
72
|
+
#screen { display: block; background: #000; outline: none; cursor: default; }
|
|
53
73
|
#screen:focus, #stage:focus-within #screen { box-shadow: 0 0 0 2px #3b82f6; }
|
|
54
74
|
#still { padding: 6px 12px; background: #3a3a1a; color: #f3e9a8; border-bottom: 1px solid #5a5a2a; }
|
|
55
75
|
#sink { position: fixed; left: 0; bottom: 0; width: 1px; height: 1px; padding: 0; border: 0; opacity: 0; resize: none; overflow: hidden; pointer-events: none; font-size: 16px; }
|
|
56
|
-
#dialog { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.6); display: flex; align-items: center; justify-content: center; }
|
|
57
|
-
#dialog[hidden], #notice[hidden], #dialog-prompt[hidden] { display: none; }
|
|
76
|
+
#dialog { position: fixed; inset: 0; z-index: 1; background: rgba(0, 0, 0, 0.6); display: flex; align-items: center; justify-content: center; }
|
|
77
|
+
#dialog[hidden], #notice[hidden], #dialog-prompt[hidden], #dialog-held[hidden] { display: none; }
|
|
78
|
+
#dialog-held { margin: 0 0 12px; color: #ffe2a8; }
|
|
58
79
|
#dialog-box { background: #222; border: 1px solid #555; border-radius: 6px; padding: 16px; width: min(28em, 90vw); }
|
|
59
80
|
#dialog-kind { margin: 0 0 6px; color: #aaa; text-transform: uppercase; font-size: 12px; }
|
|
60
81
|
#dialog-message { margin: 0 0 12px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
61
82
|
#dialog-prompt { width: 100%; margin: 0 0 12px; background: #111; color: #eee; border: 1px solid #444; border-radius: 4px; padding: 5px 8px; font: inherit; }
|
|
62
83
|
#dialog-buttons { display: flex; gap: 8px; justify-content: flex-end; }
|
|
63
84
|
#dialog-buttons button { background: #333; color: #eee; border: 1px solid #444; border-radius: 4px; padding: 5px 14px; cursor: pointer; }
|
|
85
|
+
#dialog-buttons button:disabled, #dialog-prompt:disabled, #bar button:disabled, #url:disabled { opacity: 0.5; cursor: not-allowed; }
|
|
64
86
|
`;
|
|
65
87
|
const js = `"use strict";
|
|
66
88
|
(function () {
|
|
@@ -75,6 +97,17 @@ const js = `"use strict";
|
|
|
75
97
|
// The page is shown on a canvas, which cannot take text: the keyboard's focus sits on a hidden textarea beside it, so a virtual keyboard and an IME have something to type into.
|
|
76
98
|
function focusScreen() { try { sink.focus({ preventScroll: true }); } catch (e) { canvas.focus(); } }
|
|
77
99
|
var ctx = canvas.getContext("2d");
|
|
100
|
+
var stage = $("stage");
|
|
101
|
+
// The canvas drawn as large as the stage allows at the page's own shape. point() reads this box, so input stays exact.
|
|
102
|
+
function fit() {
|
|
103
|
+
if (!canvas.width || !canvas.height) return;
|
|
104
|
+
var box = stage.getBoundingClientRect();
|
|
105
|
+
var scale = Math.min(box.width / canvas.width, box.height / canvas.height);
|
|
106
|
+
if (!(scale > 0)) return;
|
|
107
|
+
canvas.style.width = Math.floor(canvas.width * scale) + "px";
|
|
108
|
+
canvas.style.height = Math.floor(canvas.height * scale) + "px";
|
|
109
|
+
}
|
|
110
|
+
if (typeof ResizeObserver === "function") new ResizeObserver(fit).observe(stage); else window.addEventListener("resize", fit);
|
|
78
111
|
var urlBox = $("url");
|
|
79
112
|
var notice = $("notice");
|
|
80
113
|
var drive = $("drive");
|
|
@@ -85,7 +118,7 @@ const js = `"use strict";
|
|
|
85
118
|
var shownUrl = null;
|
|
86
119
|
// A page that gives no picture (a tab opened in the background, which Chrome does not paint) leaves the canvas as it was: after a while the viewer says so, and input still works.
|
|
87
120
|
function expectPicture() { drewSince = false; stillEl.hidden = true; clearTimeout(stillTimer); stillTimer = setTimeout(function () { if (!drewSince && !fatal) stillEl.hidden = false; }, 2500); }
|
|
88
|
-
function gotPicture() { drewSince = true; clearTimeout(stillTimer); stillEl.hidden = true; }
|
|
121
|
+
function gotPicture() { drewSince = true; clearTimeout(stillTimer); stillEl.hidden = true; if (noPage) { noPage = false; say(""); } }
|
|
89
122
|
var fatal = false;
|
|
90
123
|
|
|
91
124
|
function say(text, isFatal) {
|
|
@@ -93,10 +126,11 @@ const js = `"use strict";
|
|
|
93
126
|
notice.hidden = false;
|
|
94
127
|
notice.textContent = text;
|
|
95
128
|
notice.className = isFatal ? "fatal" : "";
|
|
129
|
+
document.body.classList.toggle("over", !!isFatal);
|
|
96
130
|
}
|
|
97
131
|
function setDrive(state) {
|
|
98
132
|
drive.className = state === "agent" || state === "person" ? state : "";
|
|
99
|
-
drive.textContent = state === "agent" ? "the agent is acting" : state === "person" ? "you are driving" : "";
|
|
133
|
+
drive.textContent = readOnly ? "view only" : takeOver && holding ? "you have the browser" : takeOver && state === "person" ? "" : state === "agent" ? "the agent is acting" : state === "person" ? "you are driving" : "";
|
|
100
134
|
}
|
|
101
135
|
|
|
102
136
|
if (!token) { fatal = true; say("This link has no token. Open the live view from the link the host gave you.", true); return; }
|
|
@@ -111,7 +145,46 @@ const js = `"use strict";
|
|
|
111
145
|
|
|
112
146
|
// Input before the host's ready is refused out loud and never queued: a keystroke replayed into a page the person has since lost sight of is worse than one that was not sent. A hover is not worth a notice.
|
|
113
147
|
function stillConnecting() { if (ready || fatal || closed) return false; say(WAITING); return true; }
|
|
148
|
+
// A view-only viewer sends nothing but its hello: the server drops any input anyway (held read_only).
|
|
149
|
+
var readOnly = false;
|
|
150
|
+
var noPage = false;
|
|
151
|
+
var NO_PAGE = "No page yet: the browser has not opened a page. It shows here once it does.";
|
|
152
|
+
// The controls that act on the browser: the address bar and its buttons, and a page's dialog (its answer, OK or Cancel).
|
|
153
|
+
var CONTROLS = ["back", "reload", "url", "dialog-accept", "dialog-dismiss", "dialog-prompt"];
|
|
154
|
+
function viewOnly() {
|
|
155
|
+
document.body.classList.add("view-only");
|
|
156
|
+
$("watching").hidden = false;
|
|
157
|
+
// Nothing a watcher types or clicks is sent, so the no-picture notice promises no input.
|
|
158
|
+
stillEl.textContent = "This page is in a background tab or has not drawn yet, so there is no picture until it is shown.";
|
|
159
|
+
CONTROLS.forEach(function (id) { $(id).disabled = true; });
|
|
160
|
+
}
|
|
161
|
+
// A take-over viewer drives only while it holds the browser: Take over asks for it, Hand back gives it back.
|
|
162
|
+
var takeOver = false;
|
|
163
|
+
var holding = false;
|
|
164
|
+
// Whether the take of the moment went live: one that ends before it did (the agent's step ran on) never gave the person the browser.
|
|
165
|
+
var heldThisTake = false;
|
|
166
|
+
var handsEl = $("hands");
|
|
167
|
+
var NOT_TAKEN = "Take over to drive the browser: your input is not sent until you do.";
|
|
168
|
+
function showHands() {
|
|
169
|
+
handsEl.hidden = !takeOver;
|
|
170
|
+
handsEl.textContent = holding ? "Hand back" : "Take over";
|
|
171
|
+
handsEl.className = holding ? "holding" : "";
|
|
172
|
+
document.body.classList.toggle("not-held", takeOver && !holding);
|
|
173
|
+
// A view-only viewer's controls stay off (viewOnly); a take-over one's are on only while it holds the browser, a page's
|
|
174
|
+
// dialog's among them, so no button looks live that cannot act.
|
|
175
|
+
if (takeOver) CONTROLS.forEach(function (id) { $(id).disabled = !holding; });
|
|
176
|
+
// Take over sits above a page's dialog (the rest of the bar stays under it), so a dialog that came before the take
|
|
177
|
+
// never keeps the owner from taking over; it says how to answer it.
|
|
178
|
+
$("dialog-held").hidden = !(takeOver && !holding);
|
|
179
|
+
}
|
|
180
|
+
handsEl.addEventListener("click", function () {
|
|
181
|
+
if (!ready || !takeOver || ws.readyState !== 1) return;
|
|
182
|
+
ws.send(JSON.stringify({ type: holding ? "give" : "take" }));
|
|
183
|
+
if (!holding) { heldThisTake = false; say("Taking over the browser..."); }
|
|
184
|
+
});
|
|
114
185
|
function send(message) {
|
|
186
|
+
if (readOnly) return;
|
|
187
|
+
if (takeOver && !holding) { if (ready && !(message.type === "mouse" && message.action === "move")) say(NOT_TAKEN); return; }
|
|
115
188
|
if (!ready) { if (!(message.type === "mouse" && message.action === "move")) stillConnecting(); return; }
|
|
116
189
|
if (ws.readyState === 1) ws.send(JSON.stringify(message));
|
|
117
190
|
}
|
|
@@ -120,14 +193,18 @@ const js = `"use strict";
|
|
|
120
193
|
// Frames: the latest only. A decode in flight and one waiting; a newer frame replaces the one waiting.
|
|
121
194
|
var decoding = false;
|
|
122
195
|
var waiting = null;
|
|
196
|
+
// Moved on by no_page: a decode begun before it is of the old page, and its picture is never drawn.
|
|
197
|
+
var generation = 0;
|
|
123
198
|
function draw(buffer) {
|
|
124
199
|
if (buffer.byteLength <= 4) { decoding = false; return; }
|
|
125
200
|
var view = new DataView(buffer);
|
|
126
201
|
var w = view.getUint16(0);
|
|
127
202
|
var h = view.getUint16(2);
|
|
128
203
|
var blob = new Blob([new Uint8Array(buffer, 4)], { type: "image/jpeg" });
|
|
204
|
+
var mine = generation;
|
|
129
205
|
createImageBitmap(blob).then(function (bitmap) {
|
|
130
|
-
if (
|
|
206
|
+
if (mine !== generation) { if (bitmap.close) bitmap.close(); return; }
|
|
207
|
+
if (canvas.width !== bitmap.width || canvas.height !== bitmap.height) { canvas.width = bitmap.width; canvas.height = bitmap.height; fit(); }
|
|
131
208
|
ctx.drawImage(bitmap, 0, 0);
|
|
132
209
|
gotPicture();
|
|
133
210
|
if (bitmap.close) bitmap.close();
|
|
@@ -157,7 +234,10 @@ const js = `"use strict";
|
|
|
157
234
|
$("dialog-accept").addEventListener("click", function () { answer(true); });
|
|
158
235
|
$("dialog-dismiss").addEventListener("click", function () { answer(false); });
|
|
159
236
|
|
|
160
|
-
var HELD = { agent_acting: "The agent is acting, so that input was held. Try again in a moment.", no_page: "There is no page to drive yet.", bad_message: "That input was not understood." };
|
|
237
|
+
var HELD = { agent_acting: "The agent is acting, so that input was held. Try again in a moment.", no_page: "There is no page to drive yet.", bad_message: "That input was not understood.", read_only: "This view is view-only: your input is not sent.", not_taken: NOT_TAKEN, taking: "Taking over the browser: wait a moment." };
|
|
238
|
+
var HOLD_ENDED = { given: "You handed the browser back to the agent.", answered: "The agent's request was answered, so the browser went back to the agent.", idle: "The browser went back to the agent: no input came from you for a while.", away: "The browser went back to the agent while this view was closed.", released: "The browser's session ended.", cap: "The browser went back to the agent: the run's spend cap has no room for more of your time." };
|
|
239
|
+
// Why a take ended before it went live: the person never had the browser, so it never "went back".
|
|
240
|
+
var NOT_STARTED = { idle: "the agent's step was still running when your time ran out", away: "this view was closed before the agent's step finished", released: "the browser's session ended", cap: "the run's spend cap has no room for more of your time", answered: "the agent's request was answered first", given: "you handed it back before it started" };
|
|
161
241
|
var REFUSED = { unauthorized: "This link's token was not accepted.", viewer_in_use: "Another viewer already has this session.", released: "This session has been released.", bad_message: "The host did not understand this viewer." };
|
|
162
242
|
ws.onmessage = function (event) {
|
|
163
243
|
if (typeof event.data !== "string") {
|
|
@@ -168,16 +248,29 @@ const js = `"use strict";
|
|
|
168
248
|
}
|
|
169
249
|
var m;
|
|
170
250
|
try { m = JSON.parse(event.data); } catch (e) { return; }
|
|
171
|
-
if (m.type === "ready") { ready = true; setDrive(m.drive); say(""); focusScreen(); expectPicture(); }
|
|
172
|
-
else if (m.type === "
|
|
173
|
-
|
|
251
|
+
if (m.type === "ready") { ready = true; readOnly = m.readOnly === true; takeOver = !readOnly && m.takeOver === true; holding = takeOver && m.held === true; heldThisTake = holding; if (readOnly) viewOnly(); showHands(); setDrive(m.drive); say(""); focusScreen(); expectPicture(); }
|
|
252
|
+
else if (m.type === "hold") {
|
|
253
|
+
var started = heldThisTake;
|
|
254
|
+
holding = m.held === true;
|
|
255
|
+
if (holding) heldThisTake = true; else heldThisTake = false;
|
|
256
|
+
showHands(); setDrive(holding ? "person" : "idle");
|
|
257
|
+
var extra = typeof m.message === "string" && m.message ? " " + m.message : "";
|
|
258
|
+
say(holding ? "" : started ? (HOLD_ENDED[m.reason] || "The browser went back to the agent.") + extra : "Your take-over did not start: " + (NOT_STARTED[m.reason] || "the browser was not handed to you") + "." + extra);
|
|
259
|
+
if (holding) focusScreen();
|
|
260
|
+
}
|
|
261
|
+
else if (m.type === "take_refused") say(typeof m.message === "string" && m.message ? m.message : "The browser could not be handed to you.");
|
|
262
|
+
// The old page's picture goes with it, and so does the frame waiting; a decode in flight finishes without drawing.
|
|
263
|
+
else if (m.type === "no_page") { noPage = true; generation += 1; waiting = null; ctx.clearRect(0, 0, canvas.width, canvas.height); stillEl.hidden = true; clearTimeout(stillTimer); say(NO_PAGE); }
|
|
264
|
+
// "No page yet" stays until a page or a frame comes: who drives meanwhile changes nothing on a browser with no page.
|
|
265
|
+
else if (m.type === "status") { setDrive(m.drive); if (noPage || takeOver || readOnly) return; if (m.drive !== "agent") say(""); else say("The agent is acting. Your input is held until it is done."); }
|
|
266
|
+
else if (m.type === "page") { if (noPage) { noPage = false; say(""); } document.title = m.title ? m.title + " - Live view" : "Live view"; if (document.activeElement !== urlBox) urlBox.value = m.url; $("where").textContent = m.url; $("where").title = m.url; if (m.url !== shownUrl) { shownUrl = m.url; expectPicture(); } }
|
|
174
267
|
else if (m.type === "dialog") showDialog(m);
|
|
175
268
|
else if (m.type === "dialog_closed") hideDialog();
|
|
176
269
|
else if (m.type === "held") say(HELD[m.reason] || "That input was held.");
|
|
177
270
|
else if (m.type === "refused") { fatal = true; ready = false; stillEl.hidden = true; say(REFUSED[m.reason] || "The host refused this viewer.", true); }
|
|
178
271
|
else if (m.type === "ended") { fatal = true; ready = false; say("This session has ended: the browser was released.", true); }
|
|
179
272
|
};
|
|
180
|
-
ws.onclose = function () { closed = true; ready = false; setDrive(""); if (!fatal) say("Disconnected. Open the live view link again.", true); };
|
|
273
|
+
ws.onclose = function () { closed = true; ready = false; holding = false; handsEl.disabled = true; setDrive(""); if (!fatal) say("Disconnected. Open the live view link again.", true); };
|
|
181
274
|
|
|
182
275
|
// Input: the page's CSS pixels, from the canvas's own box and the latest frame's width and height.
|
|
183
276
|
var lastPoint = null;
|
package/dist/providers/cdp.d.ts
CHANGED
|
@@ -4,7 +4,6 @@ export type CdpOptions =
|
|
|
4
4
|
/** An existing browser: `http://host:port` or a `ws://` debugger URL. Release leaves it running. */
|
|
5
5
|
{
|
|
6
6
|
endpoint: string;
|
|
7
|
-
extensionId?: string;
|
|
8
7
|
/** The host asserts this endpoint is the run's OWN browser (the launcher that owns its process and its stop started it for this run alone), not one other runs or people share. Only then is a session of it offered to a session vault. Never set it for a shared browser. */
|
|
9
8
|
ownBrowser?: boolean;
|
|
10
9
|
}
|
package/dist/providers/cdp.js
CHANGED
|
@@ -5,13 +5,14 @@ import os from "node:os";
|
|
|
5
5
|
import { pipeline } from "node:stream/promises";
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import { BrowserFailureError, PROFILE_NAME, refusedError } from "../core/custody.js";
|
|
8
|
+
import { DownloadNotSettled } from "../core/downloads.js";
|
|
8
9
|
import { browserFailure } from "../core/failures.js";
|
|
9
|
-
import { cdpCall } from "
|
|
10
|
+
import { cdpCall } from "../core/cdp-call.js";
|
|
10
11
|
import { chromeTail, openChromeStderr, watchChromeStderr } from "./chrome-stderr.js";
|
|
11
12
|
import { claimWriter, freeWriter, noteWriter } from "./profiles.js";
|
|
12
13
|
import { chromeArgs } from "./chrome-args.js";
|
|
13
|
-
import { COPY, copyExtension, copyId, isLoaded, loadConfined } from "./worker-extension.js";
|
|
14
|
-
const CAPS = {
|
|
14
|
+
import { COPY, copyExtension, copyId, isLoaded, loadConfined, soleStagehand } from "./worker-extension.js";
|
|
15
|
+
const CAPS = { profiles: false, settings: { proxies: false, verified: false, geolocation: false, region: false, context: false } };
|
|
15
16
|
const downloadsDir = (profileRoot, tag) => path.join(profileDir(profileRoot, tag) + ".downloads");
|
|
16
17
|
const READY_MS = 20_000;
|
|
17
18
|
/** The browser is gone and directories it used are not: a profile left behind holds the session's cookies, so a release that cannot remove
|
|
@@ -314,7 +315,7 @@ export function cdpProvider(options, internals = {}) {
|
|
|
314
315
|
/** The private TMPDIR of each lease this provider started, by tag: the profile's marker is the only record a restarted process has, and a profile
|
|
315
316
|
* that something else removed first takes it along. */
|
|
316
317
|
const privateTmps = new Map();
|
|
317
|
-
/** The confined extension each lease has been given, by tag, loaded on its first attach:
|
|
318
|
+
/** The confined extension each lease has been given, by tag, loaded on its first attach: the only Stagehand extension its browser keeps. */
|
|
318
319
|
const extensionIds = new Map();
|
|
319
320
|
/** A lease whose private TMPDIR is gone (or never made) keeps neither its map entry nor its record. */
|
|
320
321
|
const forgetTmp = async (root, tag) => {
|
|
@@ -498,7 +499,7 @@ export function cdpProvider(options, internals = {}) {
|
|
|
498
499
|
},
|
|
499
500
|
async attach(ref) {
|
|
500
501
|
if ("endpoint" in options)
|
|
501
|
-
return { sdkCdpUrl: await debuggerUrl(options.endpoint)
|
|
502
|
+
return { sdkCdpUrl: await debuggerUrl(options.endpoint) };
|
|
502
503
|
const local = parse(ref.id);
|
|
503
504
|
if (!local)
|
|
504
505
|
throw new Error("not a cdp lease");
|
|
@@ -510,8 +511,12 @@ export function cdpProvider(options, internals = {}) {
|
|
|
510
511
|
throw new Error(`the browser on port ${local.port} is not the browser this lease's profile records`);
|
|
511
512
|
// A Chrome this host did not start outlived the host that did: its stderr file is bounded here too.
|
|
512
513
|
watchChromeStderr(privateTmps.get(local.tag) ?? await recordedTmp(options.chrome.profileRoot, local.tag) ?? await ownedTmp(profileDir(options.chrome.profileRoot, local.tag), local.tag), local.pid);
|
|
514
|
+
// Stagehand attaches to the one extension carrying its name: on every attach, any other (one loaded since the last) goes.
|
|
513
515
|
const extensionId = await confinedExtension(local.tag, url);
|
|
514
|
-
|
|
516
|
+
if (extensionId)
|
|
517
|
+
await soleStagehand(url, extensionId);
|
|
518
|
+
// The extension lives in this browser and dials it on loopback, never through whatever the host puts in front of the driver.
|
|
519
|
+
return { sdkCdpUrl: url, extensionCdpUrl: url };
|
|
515
520
|
},
|
|
516
521
|
async release(ref) {
|
|
517
522
|
if (ref.id.startsWith("endpoint:")) {
|
|
@@ -590,7 +595,10 @@ export function cdpProvider(options, internals = {}) {
|
|
|
590
595
|
},
|
|
591
596
|
};
|
|
592
597
|
}
|
|
593
|
-
/**
|
|
598
|
+
/** Chrome writes a download to a `.crdownload` file and renames it to its name once done; at the end (sandboxed, under load)
|
|
599
|
+
* it first creates that name empty for a moment, the bytes still in the `.crdownload`. Both are listed as `downloading`
|
|
600
|
+
* and never read: a `.crdownload` (under its name without the extension), and an empty file while any `.crdownload` is
|
|
601
|
+
* there. A read checks after it ends that the file it opened is still the file at that name, whole. */
|
|
594
602
|
function localDownloads(profileRoot) {
|
|
595
603
|
const inside = (ref, name) => { if (name !== path.basename(name) || !name)
|
|
596
604
|
throw new Error("not a download name"); return path.join(downloadsDir(profileRoot, ref.tag), name); };
|
|
@@ -598,26 +606,40 @@ function localDownloads(profileRoot) {
|
|
|
598
606
|
async list(ref) {
|
|
599
607
|
const dir = downloadsDir(profileRoot, ref.tag);
|
|
600
608
|
const rows = [];
|
|
601
|
-
|
|
602
|
-
|
|
609
|
+
const names = (await readdir(dir).catch(() => [])).filter((name) => !name.startsWith("."));
|
|
610
|
+
const writing = names.some((name) => name.endsWith(".crdownload"));
|
|
611
|
+
const finals = new Set(names.filter((name) => !name.endsWith(".crdownload")));
|
|
612
|
+
for (const name of names) {
|
|
613
|
+
const partial = name.endsWith(".crdownload");
|
|
614
|
+
const shown = partial ? name.slice(0, -".crdownload".length) : name;
|
|
615
|
+
// A `.crdownload` named for a final name that is there too is that same download, told once.
|
|
616
|
+
if (partial && finals.has(shown))
|
|
603
617
|
continue;
|
|
604
618
|
const info = await stat(path.join(dir, name)).catch(() => null);
|
|
605
|
-
if (info?.isFile())
|
|
606
|
-
|
|
619
|
+
if (!info?.isFile())
|
|
620
|
+
continue;
|
|
621
|
+
const row = { name: shown, sizeBytes: info.size, modifiedAt: info.mtime.toISOString() };
|
|
622
|
+
rows.push(partial || (writing && info.size === 0) ? { ...row, downloading: true } : row);
|
|
607
623
|
}
|
|
608
624
|
return rows.sort((a, b) => a.name.localeCompare(b.name));
|
|
609
625
|
},
|
|
610
626
|
async read(ref, name, maxBytes) {
|
|
611
|
-
const
|
|
627
|
+
const where = inside(ref, name);
|
|
628
|
+
const file = await open(where, "r");
|
|
629
|
+
const opened = await file.stat().catch(async (error) => { await file.close().catch(() => undefined); throw error; });
|
|
612
630
|
return (async function* () {
|
|
613
631
|
try {
|
|
614
632
|
let total = 0;
|
|
615
|
-
for await (const chunk of file.createReadStream()) {
|
|
633
|
+
for await (const chunk of file.createReadStream({ autoClose: false })) {
|
|
616
634
|
total += chunk.byteLength;
|
|
617
635
|
if (total > maxBytes)
|
|
618
636
|
throw new Error(`larger than the ${maxBytes}-byte limit`);
|
|
619
637
|
yield chunk;
|
|
620
638
|
}
|
|
639
|
+
// The whole file it opened, still at its name: Chrome renames a finished download over the name it created empty.
|
|
640
|
+
const now = await stat(where).catch(() => null);
|
|
641
|
+
if (total !== opened.size || !now || now.dev !== opened.dev || now.ino !== opened.ino || now.size !== opened.size || now.mtimeMs !== opened.mtimeMs)
|
|
642
|
+
throw new DownloadNotSettled(name);
|
|
621
643
|
}
|
|
622
644
|
finally {
|
|
623
645
|
await file.close().catch(() => undefined);
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
/** The local Chrome to start: the one `PI_BROWSER_CHROME` or `CHROME_PATH` names when it exists, else the first install found
|
|
2
|
+
* on PATH or at a fixed place; null when there is none. */
|
|
3
|
+
export declare function findChrome(env?: NodeJS.ProcessEnv, exists?: (file: string) => boolean): string | null;
|
|
1
4
|
/** The directory Stagehand loads its extension from in a local Chrome (`Extensions.loadUnpacked`), resolved as Stagehand does. */
|
|
2
5
|
export declare function extensionDirectory(): string;
|
|
3
6
|
/** The Origin the extension's own DevTools socket carries. Chrome names an unpacked extension by the SHA-256 of its real path: the
|
|
@@ -1,12 +1,23 @@
|
|
|
1
1
|
// The arguments the cdp provider starts a local Chrome with, in one place, so a host that starts its own Chrome for Stagehand can
|
|
2
|
-
// take the same list rather than copy it.
|
|
2
|
+
// take the same list rather than copy it; and where that Chrome is installed (findChrome).
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
|
-
import { realpathSync } from "node:fs";
|
|
4
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
import { BrowserFailureError } from "../core/custody.js";
|
|
8
8
|
import { browserFailure } from "../core/failures.js";
|
|
9
9
|
import { nonEmpty } from "./shared.js";
|
|
10
|
+
const LINUX_NAMES = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"];
|
|
11
|
+
/** The local Chrome to start: the one `PI_BROWSER_CHROME` or `CHROME_PATH` names when it exists, else the first install found
|
|
12
|
+
* on PATH or at a fixed place; null when there is none. */
|
|
13
|
+
export function findChrome(env = process.env, exists = existsSync) {
|
|
14
|
+
for (const named of [env.PI_BROWSER_CHROME, env.CHROME_PATH])
|
|
15
|
+
if (named && exists(named))
|
|
16
|
+
return named;
|
|
17
|
+
const onPath = (env.PATH ?? "").split(path.delimiter).filter(Boolean).flatMap((dir) => LINUX_NAMES.map((name) => path.join(dir, name)));
|
|
18
|
+
const fixed = ["/opt/google/chrome/chrome", "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"];
|
|
19
|
+
return [...onPath, ...fixed].find((file) => exists(file)) ?? null;
|
|
20
|
+
}
|
|
10
21
|
/** Stagehand 4.1.0's DEFAULT_CHROME_FLAGS (packages/sdk-ts/src/browser/localBrowser.ts, MIT, see NOTICE), less its
|
|
11
22
|
* `--remote-allow-origins=*`, which the launch below narrows to the extension's own Origin. Without them
|
|
12
23
|
* Stagehand.create takes about 24 s on a local Chrome instead of under 100 ms. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** A profile keeps the last writer's state and nothing locks it, so within this process one session at a time may save to a
|
|
2
2
|
* profile. A holder that is no longer running is replaced; the same owner's successor (a relaunch asks for its replacement
|
|
3
3
|
* while the old session is still being released) waits for the release; anyone else is refused. */
|
|
4
4
|
export declare function claimWriter(key: string, name: string, tag: string, owner: string, signal?: AbortSignal): Promise<void>;
|
|
@@ -7,17 +7,3 @@ export declare function claimWriter(key: string, name: string, tag: string, owne
|
|
|
7
7
|
export declare function noteWriter(tag: string, running: (signal: AbortSignal) => Promise<boolean>, settle?: () => Promise<void>): void;
|
|
8
8
|
export declare function freeWriter(tag: string): void;
|
|
9
9
|
export declare function isWriter(tag: string): boolean;
|
|
10
|
-
/** Context ids are not secrets, and Browserbase has no way to look a context up by name, so the name to id map is the host's.
|
|
11
|
-
* `resolve` returns the name's context, calling `make` only when there is none, and no two callers may both make one. */
|
|
12
|
-
export type ProfileStore = {
|
|
13
|
-
resolve(key: string, make: (signal: AbortSignal) => Promise<string>): Promise<string>;
|
|
14
|
-
/** True when the store writes the ids it holds to a clear file (the default one does). A session vault refuses a provider whose store does. */
|
|
15
|
-
readonly clear?: boolean;
|
|
16
|
-
};
|
|
17
|
-
/** Context ids kept in this process only: for a host that moves them into its own vault, so none lands on disk. */
|
|
18
|
-
export declare function memoryProfileStore(): ProfileStore;
|
|
19
|
-
/** A JSON file, read, extended and written under one lock, so two processes' first uses of a name make one context; a file that is
|
|
20
|
-
* not this format, or cannot be read, is never overwritten. */
|
|
21
|
-
export declare function fileProfileStore(file?: string, options?: {
|
|
22
|
-
makeLimitMs?: number;
|
|
23
|
-
}): ProfileStore;
|
|
@@ -1,9 +1,4 @@
|
|
|
1
|
-
import { randomBytes } from "node:crypto";
|
|
2
|
-
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
3
|
-
import os from "node:os";
|
|
4
|
-
import path from "node:path";
|
|
5
1
|
import { refusedError } from "../core/custody.js";
|
|
6
|
-
import { withLock } from "../core/downloads.js";
|
|
7
2
|
import { profileHoldings } from "./shared.js";
|
|
8
3
|
const writers = profileHoldings.writers;
|
|
9
4
|
const WAIT_MS = 20_000;
|
|
@@ -31,7 +26,7 @@ async function waitFor(work, signal, ms) {
|
|
|
31
26
|
signal?.removeEventListener("abort", abort);
|
|
32
27
|
}
|
|
33
28
|
}
|
|
34
|
-
/**
|
|
29
|
+
/** A profile keeps the last writer's state and nothing locks it, so within this process one session at a time may save to a
|
|
35
30
|
* profile. A holder that is no longer running is replaced; the same owner's successor (a relaunch asks for its replacement
|
|
36
31
|
* while the old session is still being released) waits for the release; anyone else is refused. */
|
|
37
32
|
export async function claimWriter(key, name, tag, owner, signal) {
|
|
@@ -74,61 +69,3 @@ export function isWriter(tag) {
|
|
|
74
69
|
return true;
|
|
75
70
|
return false;
|
|
76
71
|
}
|
|
77
|
-
/** Context ids kept in this process only: for a host that moves them into its own vault, so none lands on disk. */
|
|
78
|
-
export function memoryProfileStore() {
|
|
79
|
-
const ids = new Map();
|
|
80
|
-
return { clear: false, resolve: (key, make) => { let known = ids.get(key); if (!known) {
|
|
81
|
-
known = make(AbortSignal.timeout(20_000));
|
|
82
|
-
ids.set(key, known);
|
|
83
|
-
known.catch(() => ids.delete(key));
|
|
84
|
-
} return known; } };
|
|
85
|
-
}
|
|
86
|
-
const SCHEMA = "pi-browser.profiles.v1";
|
|
87
|
-
const defaultProfilesFile = () => path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "pi-browser", "profiles.json");
|
|
88
|
-
const notOurs = (file) => new Error(`the profiles file ${path.basename(file)} is not a pi-browser profiles file, so it was left as it is`);
|
|
89
|
-
async function readProfiles(file) {
|
|
90
|
-
let text;
|
|
91
|
-
try {
|
|
92
|
-
text = await readFile(file, "utf8");
|
|
93
|
-
}
|
|
94
|
-
catch (error) {
|
|
95
|
-
if (error.code === "ENOENT")
|
|
96
|
-
return { schema: SCHEMA, contexts: {} };
|
|
97
|
-
throw error;
|
|
98
|
-
}
|
|
99
|
-
try {
|
|
100
|
-
const parsed = JSON.parse(text);
|
|
101
|
-
const contexts = parsed?.contexts;
|
|
102
|
-
if (parsed?.schema === SCHEMA && contexts && typeof contexts === "object" && !Array.isArray(contexts) && Object.values(contexts).every((id) => typeof id === "string" && id !== ""))
|
|
103
|
-
return parsed;
|
|
104
|
-
}
|
|
105
|
-
catch { /* not JSON */ }
|
|
106
|
-
throw notOurs(file);
|
|
107
|
-
}
|
|
108
|
-
/** A JSON file, read, extended and written under one lock, so two processes' first uses of a name make one context; a file that is
|
|
109
|
-
* not this format, or cannot be read, is never overwritten. */
|
|
110
|
-
export function fileProfileStore(file = defaultProfilesFile(), options = {}) {
|
|
111
|
-
// The lock is taken over once it is 30 s old (core/downloads.ts's rule), so `make` must end well before: a slower one is cut here, never left
|
|
112
|
-
// to run past the lock that protects it.
|
|
113
|
-
const makeLimitMs = options.makeLimitMs ?? 20_000;
|
|
114
|
-
return {
|
|
115
|
-
clear: true,
|
|
116
|
-
async resolve(key, make) {
|
|
117
|
-
await mkdir(path.dirname(file), { recursive: true });
|
|
118
|
-
return withLock(`${file}.lock`, async () => {
|
|
119
|
-
const current = await readProfiles(file);
|
|
120
|
-
const known = current.contexts[key];
|
|
121
|
-
if (known)
|
|
122
|
-
return known;
|
|
123
|
-
const limit = AbortSignal.timeout(makeLimitMs);
|
|
124
|
-
// Listening before `make` does, so the cut's own words are what the caller hears.
|
|
125
|
-
const cut = new Promise((_, reject) => limit.addEventListener("abort", () => reject(new Error(`making the profile's context took longer than ${makeLimitMs} ms, so it was cut before the profiles file's lock could be taken over`)), { once: true }));
|
|
126
|
-
const id = await Promise.race([make(limit), cut]);
|
|
127
|
-
const next = `${file}.${randomBytes(4).toString("hex")}.tmp`;
|
|
128
|
-
await writeFile(next, `${JSON.stringify({ schema: SCHEMA, contexts: { ...current.contexts, [key]: id } }, null, 2)}\n`);
|
|
129
|
-
await rename(next, file);
|
|
130
|
-
return id;
|
|
131
|
-
}, "the profiles file");
|
|
132
|
-
},
|
|
133
|
-
};
|
|
134
|
-
}
|
|
@@ -1,50 +1,5 @@
|
|
|
1
|
-
import type { ResourceStatus } from "../core/lease.js";
|
|
2
|
-
import type { CdpSession } from "./cdp-call.js";
|
|
3
1
|
export declare const nonEmpty: (v: unknown) => string;
|
|
4
|
-
/**
|
|
5
|
-
export declare const tagValue: (v: string) => string;
|
|
6
|
-
export declare function assertTag(tag: string): void;
|
|
7
|
-
export declare function extensionArchive(): string;
|
|
8
|
-
export declare const accountKey: (origin: string, apiKey: string) => string;
|
|
9
|
-
export declare const defaultSleep: (ms: number) => Promise<void>;
|
|
10
|
-
export declare const DEFAULT_CONFIRM: {
|
|
11
|
-
polls: number;
|
|
12
|
-
intervalMs: number;
|
|
13
|
-
};
|
|
14
|
-
/** The work itself goes on when `signal` fires: another caller may be waiting for it. */
|
|
15
|
-
export declare function untilAborted<T>(work: Promise<T>, signal?: AbortSignal): Promise<T>;
|
|
16
|
-
/** One upload per process and account; a failed upload is forgotten so the next create tries again. */
|
|
17
|
-
export declare function uploadOnce<T>(uploads: Map<string, Promise<T>>, account: string, upload: () => Promise<T>): Promise<T>;
|
|
18
|
-
/** The request is asked twice at most; released means the provider says the session is no longer running, not that the
|
|
19
|
-
* request was sent. `request` answers "gone" when the provider no longer knows the session. */
|
|
20
|
-
export declare function releaseAndConfirm(o: {
|
|
21
|
-
request: () => Promise<"gone" | void>;
|
|
22
|
-
status: () => Promise<ResourceStatus>;
|
|
23
|
-
forget: () => void | Promise<void>;
|
|
24
|
-
confirm: {
|
|
25
|
-
polls: number;
|
|
26
|
-
intervalMs: number;
|
|
27
|
-
};
|
|
28
|
-
sleep: (ms: number) => Promise<void>;
|
|
29
|
-
stillRunning: string;
|
|
30
|
-
}): Promise<void>;
|
|
31
|
-
export declare const browserbaseHoldings: {
|
|
32
|
-
connectUrls: Map<string, string>;
|
|
33
|
-
settings: Map<string, Pick<CdpSession, "close" | "open">>;
|
|
34
|
-
opening: Map<string, Promise<void>>;
|
|
35
|
-
uploads: Map<string, Promise<string>>;
|
|
36
|
-
boundDials: Map<string, string>;
|
|
37
|
-
};
|
|
38
|
-
export declare const kernelHoldings: {
|
|
39
|
-
cdpUrls: Map<string, string>;
|
|
40
|
-
liveUrls: Map<string, string>;
|
|
41
|
-
uploads: Map<string, Promise<{
|
|
42
|
-
id: string;
|
|
43
|
-
} | {
|
|
44
|
-
name: string;
|
|
45
|
-
}>>;
|
|
46
|
-
};
|
|
47
|
-
/** Which session may save to a named profile now, by profile: claimed by both cloud providers (providers/profiles.ts). */
|
|
2
|
+
/** Which session may save to a named profile now, by profile: claimed by the local Chrome provider (providers/profiles.ts). */
|
|
48
3
|
export declare const profileHoldings: {
|
|
49
4
|
writers: Map<string, {
|
|
50
5
|
tag: string;
|
|
@@ -53,4 +8,3 @@ export declare const profileHoldings: {
|
|
|
53
8
|
settle?: () => Promise<void>;
|
|
54
9
|
}>;
|
|
55
10
|
};
|
|
56
|
-
export declare function resetProviderHoldings(): void;
|
package/dist/providers/shared.js
CHANGED
|
@@ -1,86 +1,5 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
|
-
import path from "node:path";
|
|
3
|
-
import { fileURLToPath } from "node:url";
|
|
4
1
|
export const nonEmpty = (v) => String(v ?? "").trim();
|
|
5
|
-
/**
|
|
6
|
-
export const tagValue = (v) => String(v || "").replace(/[^A-Za-z0-9._:-]+/g, "_").slice(0, 60) || "unknown";
|
|
7
|
-
export function assertTag(tag) {
|
|
8
|
-
if (!/^[A-Za-z0-9_.-]+$/.test(tag))
|
|
9
|
-
throw new Error("a session tag is [A-Za-z0-9_.-]");
|
|
10
|
-
}
|
|
11
|
-
export function extensionArchive() {
|
|
12
|
-
return nonEmpty(process.env.STAGEHAND_EXTENSION_ARCHIVE_PATH) || path.join(path.dirname(fileURLToPath(import.meta.resolve("@browserbasehq/stagehand"))), "assets", "stagehand-extension.zip");
|
|
13
|
-
}
|
|
14
|
-
export const accountKey = (origin, apiKey) => `${origin}|${createHash("sha256").update(apiKey).digest("hex").slice(0, 16)}`;
|
|
15
|
-
export const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
16
|
-
export const DEFAULT_CONFIRM = { polls: 6, intervalMs: 500 };
|
|
17
|
-
/** The work itself goes on when `signal` fires: another caller may be waiting for it. */
|
|
18
|
-
export function untilAborted(work, signal) {
|
|
19
|
-
if (!signal)
|
|
20
|
-
return work;
|
|
21
|
-
return new Promise((resolve, reject) => {
|
|
22
|
-
const abort = () => reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"));
|
|
23
|
-
// The outcome is taken first, so a failure after the caller left is handled, never unhandled.
|
|
24
|
-
work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
25
|
-
if (signal.aborted)
|
|
26
|
-
return abort();
|
|
27
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
28
|
-
});
|
|
29
|
-
}
|
|
30
|
-
/** One upload per process and account; a failed upload is forgotten so the next create tries again. */
|
|
31
|
-
export function uploadOnce(uploads, account, upload) {
|
|
32
|
-
let up = uploads.get(account);
|
|
33
|
-
if (!up) {
|
|
34
|
-
up = upload();
|
|
35
|
-
uploads.set(account, up);
|
|
36
|
-
up.catch(() => uploads.delete(account));
|
|
37
|
-
}
|
|
38
|
-
return up;
|
|
39
|
-
}
|
|
40
|
-
/** The request is asked twice at most; released means the provider says the session is no longer running, not that the
|
|
41
|
-
* request was sent. `request` answers "gone" when the provider no longer knows the session. */
|
|
42
|
-
export async function releaseAndConfirm(o) {
|
|
43
|
-
let failure;
|
|
44
|
-
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
45
|
-
try {
|
|
46
|
-
if ((await o.request()) === "gone")
|
|
47
|
-
return o.forget();
|
|
48
|
-
failure = undefined;
|
|
49
|
-
break;
|
|
50
|
-
}
|
|
51
|
-
catch (error) {
|
|
52
|
-
failure = error;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
for (let poll = 0;; poll += 1) {
|
|
56
|
-
const now = await o.status();
|
|
57
|
-
if (now !== "running" && now !== "pending")
|
|
58
|
-
return o.forget();
|
|
59
|
-
if (poll >= o.confirm.polls)
|
|
60
|
-
throw failure ?? new Error(o.stillRunning);
|
|
61
|
-
await o.sleep(o.confirm.intervalMs);
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
// Process-wide on purpose: a provider built later (custody builds one for the release) must still close the attach socket,
|
|
65
|
-
// drop the dial binding and reuse the account's upload. The URLs carry tokens and are never written anywhere.
|
|
66
|
-
export const browserbaseHoldings = {
|
|
67
|
-
connectUrls: new Map(),
|
|
68
|
-
settings: new Map(),
|
|
69
|
-
opening: new Map(),
|
|
70
|
-
uploads: new Map(),
|
|
71
|
-
boundDials: new Map(),
|
|
72
|
-
};
|
|
73
|
-
export const kernelHoldings = {
|
|
74
|
-
cdpUrls: new Map(),
|
|
75
|
-
liveUrls: new Map(),
|
|
76
|
-
uploads: new Map(),
|
|
77
|
-
};
|
|
78
|
-
/** Which session may save to a named profile now, by profile: claimed by both cloud providers (providers/profiles.ts). */
|
|
2
|
+
/** Which session may save to a named profile now, by profile: claimed by the local Chrome provider (providers/profiles.ts). */
|
|
79
3
|
export const profileHoldings = {
|
|
80
4
|
writers: new Map(),
|
|
81
5
|
};
|
|
82
|
-
export function resetProviderHoldings() {
|
|
83
|
-
for (const holdings of [browserbaseHoldings, kernelHoldings, profileHoldings])
|
|
84
|
-
for (const map of Object.values(holdings))
|
|
85
|
-
map.clear();
|
|
86
|
-
}
|