@parcha/pi-browser 0.1.0-beta.31 → 0.1.0-beta.310

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/CHANGELOG.md +232 -0
  2. package/NOTICE +39 -4
  3. package/README.md +122 -236
  4. package/dist/core/contract.d.ts +9 -6
  5. package/dist/core/contract.js +27 -36
  6. package/dist/core/custody.d.ts +19 -2
  7. package/dist/core/custody.js +28 -6
  8. package/dist/core/downloads.d.ts +44 -3
  9. package/dist/core/downloads.js +94 -58
  10. package/dist/core/driving-guard.d.ts +20 -0
  11. package/dist/core/driving-guard.js +190 -23
  12. package/dist/core/driving.d.ts +56 -2
  13. package/dist/core/driving.js +189 -10
  14. package/dist/core/effects.d.ts +80 -6
  15. package/dist/core/effects.js +374 -41
  16. package/dist/core/evidence.d.ts +1 -1
  17. package/dist/core/failures.d.ts +15 -1
  18. package/dist/core/failures.js +7 -0
  19. package/dist/core/files.d.ts +20 -2
  20. package/dist/core/files.js +161 -10
  21. package/dist/core/host.d.ts +29 -77
  22. package/dist/core/images.d.ts +32 -4
  23. package/dist/core/images.js +81 -16
  24. package/dist/core/lease.d.ts +2 -1
  25. package/dist/core/page-scan.d.ts +81 -2
  26. package/dist/core/page-scan.js +487 -13
  27. package/dist/core/public-fetch.d.ts +70 -9
  28. package/dist/core/public-fetch.js +348 -51
  29. package/dist/core/read-page-worker.js +5 -4
  30. package/dist/core/read-page.d.ts +23 -8
  31. package/dist/core/read-page.js +64 -20
  32. package/dist/core/redact.d.ts +0 -2
  33. package/dist/core/redact.js +0 -32
  34. package/dist/core/session-control.d.ts +0 -2
  35. package/dist/core/session-control.js +0 -5
  36. package/dist/core/tools.d.ts +46 -1
  37. package/dist/core/tools.js +88 -12
  38. package/dist/core/usage.d.ts +4 -3
  39. package/dist/core/usage.js +5 -4
  40. package/dist/core/vault.d.ts +0 -10
  41. package/dist/core/vault.js +0 -13
  42. package/dist/core/web.d.ts +2 -111
  43. package/dist/core/web.js +0 -443
  44. package/dist/driver/cdp.d.ts +6 -0
  45. package/dist/driver/cdp.js +245 -0
  46. package/dist/driver/page-driver.js +110 -7
  47. package/dist/driver/sealed.d.ts +4 -12
  48. package/dist/driver/sealed.js +23 -37
  49. package/dist/driver/stagehand.d.ts +12 -15
  50. package/dist/driver/stagehand.js +21 -17
  51. package/dist/durable/result.d.ts +1 -2
  52. package/dist/durable/result.js +2 -2
  53. package/dist/durable/store.d.ts +17 -3
  54. package/dist/durable/store.js +231 -64
  55. package/dist/durable.d.ts +47 -17
  56. package/dist/durable.js +106 -105
  57. package/dist/index.d.ts +3 -3
  58. package/dist/index.js +5 -3
  59. package/dist/live-view/index.d.ts +4 -1
  60. package/dist/live-view/index.js +5 -0
  61. package/dist/live-view/protocol.d.ts +39 -7
  62. package/dist/live-view/protocol.js +2 -0
  63. package/dist/live-view/provider.d.ts +2 -2
  64. package/dist/live-view/provider.js +2 -2
  65. package/dist/live-view/server.d.ts +55 -2
  66. package/dist/live-view/server.js +282 -35
  67. package/dist/live-view/stream.js +16 -3
  68. package/dist/live-view/viewer.js +106 -13
  69. package/dist/providers/cdp.d.ts +0 -1
  70. package/dist/providers/cdp.js +35 -13
  71. package/dist/providers/chrome-args.d.ts +3 -0
  72. package/dist/providers/chrome-args.js +13 -2
  73. package/dist/providers/profiles.d.ts +1 -15
  74. package/dist/providers/profiles.js +1 -64
  75. package/dist/providers/shared.d.ts +1 -47
  76. package/dist/providers/shared.js +1 -82
  77. package/dist/providers/worker-extension.d.ts +20 -1
  78. package/dist/providers/worker-extension.js +86 -7
  79. package/dist/testing/backend.d.ts +6 -24
  80. package/dist/testing/backend.js +7 -30
  81. package/dist/vault-session.d.ts +4 -7
  82. package/dist/vault-session.js +26 -81
  83. package/dist/vendor/browser-use-pi/ax.d.ts +106 -0
  84. package/dist/vendor/browser-use-pi/ax.js +642 -0
  85. package/dist/vendor/browser-use-pi/cdp.d.ts +19 -0
  86. package/dist/vendor/browser-use-pi/cdp.js +106 -0
  87. package/dist/vendor/browser-use-pi/page.d.ts +29 -0
  88. package/dist/vendor/browser-use-pi/page.js +99 -0
  89. package/package.json +15 -46
  90. package/src/vendor/browser-use-pi/UPSTREAM.json +25 -0
  91. package/src/vendor/stagehand-facade/UPSTREAM.json +0 -4
  92. package/dist/coding-agent-local.d.ts +0 -12
  93. package/dist/coding-agent-local.js +0 -72
  94. package/dist/coding-agent.d.ts +0 -134
  95. package/dist/coding-agent.js +0 -641
  96. package/dist/core/sites.d.ts +0 -33
  97. package/dist/core/sites.js +0 -104
  98. package/dist/driver/extension-worker.d.ts +0 -9
  99. package/dist/driver/extension-worker.js +0 -185
  100. package/dist/durable/web.d.ts +0 -47
  101. package/dist/durable/web.js +0 -41
  102. package/dist/providers/assigned.d.ts +0 -18
  103. package/dist/providers/assigned.js +0 -75
  104. package/dist/providers/browserbase-net.d.ts +0 -12
  105. package/dist/providers/browserbase-net.js +0 -95
  106. package/dist/providers/browserbase.d.ts +0 -169
  107. package/dist/providers/browserbase.js +0 -319
  108. package/dist/providers/kernel.d.ts +0 -58
  109. package/dist/providers/kernel.js +0 -291
  110. package/dist/recorder/credential.d.ts +0 -9
  111. package/dist/recorder/credential.js +0 -49
  112. package/dist/recorder/follow.d.ts +0 -36
  113. package/dist/recorder/follow.js +0 -163
  114. package/dist/recorder/frames.d.ts +0 -87
  115. package/dist/recorder/frames.js +0 -377
  116. package/dist/recorder/index.d.ts +0 -4
  117. package/dist/recorder/index.js +0 -7
  118. package/dist/recorder/jpeg.d.ts +0 -8
  119. package/dist/recorder/jpeg.js +0 -70
  120. package/dist/recorder/track.d.ts +0 -107
  121. package/dist/recorder/track.js +0 -280
  122. package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +0 -15
  123. package/dist/vendor/stagehand-facade/screenshot-transport.js +0 -51
  124. /package/dist/{providers → core}/cdp-call.d.ts +0 -0
  125. /package/dist/{providers → core}/cdp-call.js +0 -0
@@ -1,13 +1,30 @@
1
1
  import { type IncomingMessage, type ServerResponse } from "node:http";
2
2
  import type { Duplex } from "node:stream";
3
3
  import type { LiveView } from "../core/host.js";
4
- import { type DrivingGates, type StreamFactory, type ViewerAssets } from "./protocol.js";
4
+ import { type DrivingGates, type HoldEnd, type StreamFactory, type ViewerAssets } from "./protocol.js";
5
5
  export type LiveViewOptions = {
6
6
  /** The one origin allowed to frame the viewer (`frame-ancestors`). Null: none. Required, so the choice is never a default. */
7
7
  hostOrigin: string | null;
8
8
  /** Where the host mounts `handle` and `upgrade`, e.g. `https://host.example/live`. Its origin is the viewer's own origin, which an upgrade's Origin
9
9
  * header must equal. Absent: the live view starts its own server on 127.0.0.1 (never 0.0.0.0), on an ephemeral port, at the first `open`. */
10
10
  baseUrl?: string;
11
+ /** With no `baseUrl`: the address its own server listens on, and the host the viewer's link names, for a host whose
12
+ * viewer is reached from another machine (its own proxy, never a person's browser directly). Absent: loopback for
13
+ * both. A host that listens off loopback gives `admit` too. `fd`, in place of `bind`: a socket already listening that
14
+ * this process was handed (its parent made it, and knows its address), served as it is; the link names `host` and
15
+ * that socket's own port. The process listens on it once: a later live view given the same `fd` takes it over from
16
+ * the one before (whose links then answer 404), and a close leaves it listening, answering 404, for the next. */
17
+ listen?: {
18
+ readonly bind: string;
19
+ readonly host: string;
20
+ } | {
21
+ readonly fd: number;
22
+ readonly host: string;
23
+ };
24
+ /** Asked of every page request and upgrade before anything else is read of it: false is a 403. The host's own check
25
+ * that the request comes from its own proxy (a signed header, say). Absent: every request is asked only what it is
26
+ * asked today. */
27
+ admit?: (req: IncomingMessage) => boolean;
11
28
  /** The screencast and input (stream.ts); the default is the package's own. A test passes a fake. */
12
29
  stream?: StreamFactory;
13
30
  /** The person/model mutex. Absent, the package's own process-wide registry (`drivingGates`, core/driving.ts), the one the toolset's model calls use, so a
@@ -21,10 +38,33 @@ export type LiveViewOptions = {
21
38
  gates?: DrivingGates;
22
39
  /** The viewer page (viewer.ts); the default is the package's own. */
23
40
  viewer?: ViewerAssets;
41
+ /** The viewer watches and never drives: every input, navigation and dialog answer it sends is dropped here, before the browser (`held read_only`), not
42
+ * only hidden by the page, and it is told so (`ready` carries `readOnly: true`). A watching viewer holds no turn and keeps no session from its idle
43
+ * release (it never sets `viewing`). */
44
+ readOnly?: boolean;
45
+ /** The viewer drives only while it holds the browser. Its `take` asks the host first (`take`, which may refuse in its own words, a spend cap with
46
+ * no room for the person's time, shown to the viewer as `take_refused`), then moves the session's driving gate into the person's sticky hold
47
+ * (DrivingGate.take: until the viewer's `give`, the gate's idle window with no input, its away window with no viewer, or the session's end),
48
+ * and the host's `end` is called once when the hold ends, with why. Outside a hold every input, navigation and dialog answer is dropped here,
49
+ * before the browser (`held not_taken`), whatever the page does. A watching viewer keeps no session from its idle release, as a read-only one
50
+ * does; a held one is kept by its hold. Ignored with `readOnly`. */
51
+ takeOver?: {
52
+ take(tag: string): Promise<{
53
+ refused: string;
54
+ } | TakeAnswer>;
55
+ };
24
56
  /** How long a connection may stay silent before its hello, and how many may wait for one. */
25
57
  helloTimeoutMs?: number;
26
58
  maxPending?: number;
27
59
  };
60
+ /** What the host answers a take that it allows: `end` once the hold ends (with why), `started` as it goes live (at once, or
61
+ * once the agent's call under way returns), and `cancel` when no hold started after all (the session released, the viewer
62
+ * gone, or the browser held already), instead of `end`. */
63
+ export type TakeAnswer = {
64
+ end(why: HoldEnd): void;
65
+ started?(): void;
66
+ cancel?(): void;
67
+ };
28
68
  export type LiveViewHost = {
29
69
  /** Serves the viewer page and its two static files; true when the request was this host's (mounted at `baseUrl`'s path), false when it was not. */
30
70
  handle(req: IncomingMessage, res: ServerResponse): boolean;
@@ -35,8 +75,13 @@ export type LiveViewHost = {
35
75
  open(tag: string, cdpUrl: string): Promise<LiveView>;
36
76
  /** The view `open` gave for a tag, or null: for a caller that must not start anything (`liveViewProvider` asks before it attaches). */
37
77
  known(tag: string): LiveView | null;
38
- /** True while a person is driving this session (viewer input within the gate's idle window): the frame recorder holds its capture meanwhile. */
78
+ /** True while a person is driving this session (viewer input within the gate's idle window). */
39
79
  driving(tag: string): boolean;
80
+ /** The host watches the session's screen with or without a viewer (serve's run video): one screencast per session, the
81
+ * viewer's and the watchers' alike, never a second. Each frame reaches `watcher.frame` and is acked by the viewer's send,
82
+ * or at once with none; `ended` once if the browser's socket ends unasked (a release ends the watch with no call). The
83
+ * answer stops watching; null when the session has no view. */
84
+ watch(tag: string, watcher: Watcher): (() => void) | null;
40
85
  /** The token is dead, the viewer's socket closed, the stream and the gate ended. Idempotent. */
41
86
  release(tag: string): Promise<void>;
42
87
  /** What the host holds, for diagnostics and tests: the sessions with a viewer URL and the opens in flight. Neither grows with the sessions it once released. */
@@ -47,4 +92,12 @@ export type LiveViewHost = {
47
92
  /** Releases every session and stops the server it started, if any. */
48
93
  close(): Promise<void>;
49
94
  };
95
+ /** A host's watch of a session's frames (LiveViewHost.watch). */
96
+ export type Watcher = {
97
+ frame(jpeg: Buffer, page: {
98
+ w: number;
99
+ h: number;
100
+ }): void;
101
+ ended(): void;
102
+ };
50
103
  export declare function createLiveView(options: LiveViewOptions): LiveViewHost;
@@ -1,10 +1,12 @@
1
1
  import { createServer } from "node:http";
2
- import { drivingGates } from "../core/driving.js";
2
+ import { drivingGates, epochOf, isHeld, isHolding } from "../core/driving.js";
3
3
  import { CLOSE_CODES, encodeFrame, LIMITS, parseClientMessage } from "./protocol.js";
4
4
  import { openStream } from "./stream.js";
5
5
  import { newToken, newViewerId, tokenMatches } from "./token.js";
6
6
  import { viewerAssets } from "./viewer.js";
7
7
  import { acceptWebSocket } from "./ws.js";
8
+ /** Where the live view's own server listens with no `listen`: this machine alone. */
9
+ const LOOPBACK_HOST = "127.0.0.1"; // key-gate: loopback-rule the default, this machine alone
8
10
  const ID = /^[A-Za-z0-9_-]{22}$/;
9
11
  /** A viewer that cannot take frames as fast as they come drops them: past this many unsent bytes a frame is acknowledged unsent. */
10
12
  const SLOW_VIEWER_BYTES = 512 * 1024;
@@ -17,7 +19,34 @@ const MAX_QUEUED_INPUT = 32;
17
19
  /** A viewer whose messages the protocol does not know: one is dropped with a notice, and past this many within the window the connection is closed. */
18
20
  const MAX_BAD_MESSAGES = 20;
19
21
  const BAD_WINDOW_MS = 10_000;
22
+ const handedSockets = new Map();
23
+ const handedSocket = (fd) => {
24
+ const known = handedSockets.get(fd);
25
+ if (known)
26
+ return known;
27
+ const made = new Promise((resolve, reject) => {
28
+ let at;
29
+ const s = createServer((req, res) => { if (!at?.route?.handle(req, res)) {
30
+ res.writeHead(404, { "Content-Length": 0 });
31
+ res.end();
32
+ } });
33
+ s.on("upgrade", (req, socket, head) => { if (!at?.route?.upgrade(req, socket, head))
34
+ socket.destroy(); });
35
+ s.once("error", reject);
36
+ s.listen({ fd }, () => {
37
+ s.unref();
38
+ at = { server: s, port: s.address().port, route: null };
39
+ resolve(at);
40
+ });
41
+ });
42
+ handedSockets.set(fd, made);
43
+ // A socket that could not be listened on is asked again by the next view, not refused from memory.
44
+ made.catch(() => { if (handedSockets.get(fd) === made)
45
+ handedSockets.delete(fd); });
46
+ return made;
47
+ };
20
48
  export function createLiveView(options) {
49
+ const takeOver = options.readOnly ? undefined : options.takeOver;
21
50
  const helloTimeoutMs = options.helloTimeoutMs ?? 5_000;
22
51
  const maxPending = options.maxPending ?? 8;
23
52
  const byTag = new Map();
@@ -26,6 +55,8 @@ export function createLiveView(options) {
26
55
  let origin = mounted?.origin ?? null;
27
56
  const prefix = mounted ? mounted.pathname.replace(/\/+$/, "") : "";
28
57
  let server = null;
58
+ /** The handed socket this view took (`listen.fd`), while it holds it. */
59
+ let handed = null;
29
60
  let starting = null;
30
61
  let closed = false;
31
62
  /** The opens waiting for the server, by tag: a `release` or a `close` that comes meanwhile marks them cancelled, and each open takes its own mark off when it ends, so
@@ -64,6 +95,11 @@ export function createLiveView(options) {
64
95
  const upgradeRoute = /^\/v\/([^/]+)\/ws$/.exec(rel);
65
96
  if (!page && !upgradeRoute && rel !== "/viewer.js" && rel !== "/viewer.css")
66
97
  return false;
98
+ if (options.admit && !options.admit(req)) {
99
+ res.writeHead(403, { ...securityHeaders(), "Content-Length": 0 });
100
+ res.end();
101
+ return true;
102
+ }
67
103
  const reply = (status, type, body) => { res.writeHead(status, { ...securityHeaders(), "Content-Type": type, "Content-Length": Buffer.byteLength(body) }); res.end(req.method === "HEAD" ? undefined : body); return true; };
68
104
  if (req.method !== "GET" && req.method !== "HEAD")
69
105
  return reply(405, "text/plain", "method not allowed");
@@ -89,6 +125,8 @@ export function createLiveView(options) {
89
125
  // A browser always sends its page's origin on a WebSocket; another tab's script cannot forge it. Anything but the viewer's own is refused.
90
126
  if (origin === null || req.headers.origin !== origin)
91
127
  return deny("403 Forbidden");
128
+ if (options.admit && !options.admit(req))
129
+ return deny("403 Forbidden");
92
130
  const entry = ID.test(match[1]) ? byId.get(match[1]) : undefined;
93
131
  if (!entry || entry.released)
94
132
  return deny("404 Not Found");
@@ -126,34 +164,92 @@ export function createLiveView(options) {
126
164
  if (entry.viewer)
127
165
  return refuse(conn, "viewer_in_use");
128
166
  let viewer;
167
+ const running = entry.stream !== null;
129
168
  try {
130
169
  const gate = (options.gates ?? drivingGates)(entry.tag);
131
- const stream = (options.stream ?? openStream)(entry.cdpUrl, {
132
- frame(jpeg, page, ack) {
133
- if (conn.closed || conn.buffered > SLOW_VIEWER_BYTES) {
134
- ack();
135
- return;
136
- }
137
- if (!conn.send(encodeFrame(jpeg, page.w, page.h), ack))
138
- ack();
139
- },
140
- page: (page) => send(conn, { type: "page", url: page.url, title: page.title }),
141
- dialog: (dialog) => send(conn, dialog ? { type: "dialog", ...dialog } : { type: "dialog_closed" }),
142
- closed: () => { if (entry.viewer?.conn === conn) {
143
- send(conn, { type: "ended", reason: "browser_closed" });
144
- conn.close(CLOSE_CODES.browser_closed, "browser_closed");
145
- } },
146
- });
147
- viewer = { conn, stream, gate, unsubscribe: gate.onChange((drive) => send(conn, { type: "status", drive })), chain: Promise.resolve(), bad: [], queued: 0, tail: null };
170
+ viewer = { conn, stream: streamOf(entry), gate, unsubscribe: gate.onChange((drive) => send(conn, { type: "status", drive })), chain: Promise.resolve(), bad: [], queued: 0, tail: null };
148
171
  }
149
172
  catch {
150
173
  conn.close(1011, "unavailable");
151
174
  return;
152
175
  }
153
176
  entry.viewer = viewer;
154
- // A person who sits still with the viewer open is still using the session: custody does not release it on its own while this is set.
155
- viewer.gate.setViewing(true);
156
- send(conn, { type: "ready", drive: viewer.gate.state() });
177
+ // A person who sits still with the viewer open is still using the session: custody does not release it on its own while this is set. A read-only viewer
178
+ // only watches, so it keeps nothing open; a take-over viewer keeps it only by its hold, and its presence keeps the hold from its away window.
179
+ if (takeOver)
180
+ viewer.gate.setPresent?.(true);
181
+ else if (!options.readOnly)
182
+ viewer.gate.setViewing(true);
183
+ send(conn, { type: "ready", drive: viewer.gate.state(), ...(options.readOnly ? { readOnly: true } : takeOver ? { takeOver: true, held: isHolding(viewer.gate) } : {}) });
184
+ // Joining a watcher's stream: what it last said, its newest frame too (already acked).
185
+ if (!running)
186
+ return;
187
+ const { page, dialog, frame } = entry.shown;
188
+ for (const said of [page, dialog])
189
+ if (said)
190
+ send(conn, said);
191
+ if (frame)
192
+ conn.send(encodeFrame(frame.jpeg, frame.page.w, frame.page.h));
193
+ };
194
+ /** The session's one stream, opened at its first viewer or watcher: each frame to every watcher, then to the viewer,
195
+ * whose send acks it (or at once, with no viewer or a slow one); the rest to the viewer alone. Kept in `shown` while it is
196
+ * open, for a viewer that joins later. */
197
+ const streamOf = (entry) => (entry.stream ??= (options.stream ?? openStream)(entry.cdpUrl, {
198
+ frame(jpeg, page, ack) {
199
+ for (const watcher of entry.watchers)
200
+ try {
201
+ watcher.frame(jpeg, page);
202
+ }
203
+ catch { /* a watcher's failure never holds the frame's ack */ }
204
+ entry.shown.frame = { jpeg, page };
205
+ const conn = entry.viewer?.conn;
206
+ if (!conn || conn.closed || conn.buffered > SLOW_VIEWER_BYTES) {
207
+ ack();
208
+ return;
209
+ }
210
+ if (!conn.send(encodeFrame(jpeg, page.w, page.h), ack))
211
+ ack();
212
+ },
213
+ page: (page) => tell(entry, "page", { type: "page", url: page.url, title: page.title }),
214
+ noPage: () => {
215
+ // The closed tab's picture goes with it: a viewer that joins now is told no page, and shown none.
216
+ delete entry.shown.frame;
217
+ tell(entry, "page", { type: "no_page" });
218
+ },
219
+ dialog: (dialog) => tell(entry, "dialog", dialog ? { type: "dialog", ...dialog } : { type: "dialog_closed" }),
220
+ closed: () => {
221
+ const conn = entry.viewer?.conn;
222
+ entry.stream = null;
223
+ entry.shown = {};
224
+ if (conn) {
225
+ send(conn, { type: "ended", reason: "browser_closed" });
226
+ conn.close(CLOSE_CODES.browser_closed, "browser_closed");
227
+ }
228
+ const watchers = [...entry.watchers];
229
+ entry.watchers.clear();
230
+ for (const watcher of watchers)
231
+ try {
232
+ watcher.ended();
233
+ }
234
+ catch { /* each watcher is told */ }
235
+ },
236
+ }));
237
+ const tell = (entry, key, message) => {
238
+ entry.shown[key] = message;
239
+ if (entry.viewer)
240
+ send(entry.viewer.conn, message);
241
+ };
242
+ /** The stream ends once neither a viewer nor a watcher has it. */
243
+ const unused = (entry) => {
244
+ if (entry.viewer || entry.watchers.size > 0 || !entry.stream)
245
+ return;
246
+ const stream = entry.stream;
247
+ entry.stream = null;
248
+ entry.shown = {};
249
+ try {
250
+ stream.close();
251
+ }
252
+ catch { /* the stream is gone either way */ }
157
253
  };
158
254
  const onViewerMessage = (entry, viewer, data, binary) => {
159
255
  const message = binary || typeof data !== "string" ? null : parseClientMessage(data);
@@ -171,6 +267,24 @@ export function createLiveView(options) {
171
267
  excess("bad_message");
172
268
  return;
173
269
  }
270
+ // A read-only viewer's input never reaches the browser, whatever its page does: dropped here, and one that keeps sending it is closed as any excess is.
271
+ if (options.readOnly) {
272
+ excess("read_only");
273
+ return;
274
+ }
275
+ if (message.type === "take" || message.type === "give") {
276
+ if (takeOver)
277
+ hands(entry, viewer, message.type);
278
+ else
279
+ excess("bad_message");
280
+ return;
281
+ }
282
+ // A take-over viewer drives only while it holds the browser: anything else is dropped here, before the browser. A hover is not worth a notice.
283
+ if (takeOver && !isHeld(viewer.gate)) {
284
+ if (!(message.type === "mouse" && message.action === "move"))
285
+ send(viewer.conn, { type: "held", reason: "not_taken" });
286
+ return;
287
+ }
174
288
  // While a model call is in flight the input is dropped, not queued: a keystroke replayed after the model moved the page is worse than a lost one.
175
289
  if (viewer.gate.input() === "agent_acting") {
176
290
  send(viewer.conn, { type: "held", reason: "agent_acting" });
@@ -179,7 +293,9 @@ export function createLiveView(options) {
179
293
  // Mouse moves and scrolls arrive once per animation frame, so a slow browser command is always followed by a run of them. A run is combined into its last waiting
180
294
  // message (the latest position; the scroll summed) instead of queued one by one: nothing grows, order against presses and keys is kept (only the LAST waiting
181
295
  // message is ever merged into), and ordinary dragging is never counted as abuse.
182
- const waiting = viewer.tail;
296
+ // A message is merged only into one that arrived while the same hands held the browser.
297
+ const epoch = epochOf(viewer.gate);
298
+ const waiting = viewer.tail && viewer.tail.epoch === epoch ? viewer.tail : null;
183
299
  if (waiting && !waiting.started && message.type === "mouse" && message.action === "move" && waiting.message.type === "mouse" && waiting.message.action === "move") {
184
300
  waiting.message = message;
185
301
  return;
@@ -197,7 +313,7 @@ export function createLiveView(options) {
197
313
  excess("busy");
198
314
  return;
199
315
  }
200
- const item = { message, started: false };
316
+ const item = { message, started: false, epoch };
201
317
  viewer.tail = item;
202
318
  viewer.queued += 1;
203
319
  viewer.chain = viewer.chain.then(async () => {
@@ -209,18 +325,33 @@ export function createLiveView(options) {
209
325
  viewer.queued -= 1;
210
326
  return;
211
327
  }
328
+ // The hold may have ended while the message waited (handed back, idle, the agent's ask answered), or the browser changed
329
+ // hands and came back (a new hold, a page the message was not made for): it is not delivered.
330
+ if (takeOver && (!isHolding(viewer.gate) || epochOf(viewer.gate) !== item.epoch)) {
331
+ send(viewer.conn, { type: "held", reason: "not_taken" });
332
+ viewer.queued -= 1;
333
+ return;
334
+ }
212
335
  // Messages wait their turn behind a slow command, so the gate is asked again at delivery: the model may have taken the browser since the message arrived.
213
336
  if (viewer.gate.input() === "agent_acting") {
214
337
  send(viewer.conn, { type: "held", reason: "agent_acting" });
215
338
  viewer.queued -= 1;
216
339
  return;
217
340
  }
218
- // The person's turn must not lapse while their own command runs (a navigation can take seconds, the window is 3 s): it is renewed until the command returns.
219
- const keep = setInterval(() => { viewer.gate.input(); }, KEEP_DRIVING_MS);
341
+ // The gate knows the command runs: a hand-back meanwhile wakes the agent only once it returns (or is let go, `live` false from then on).
342
+ const command = viewer.gate.command?.();
343
+ const live = () => command?.live() ?? true;
344
+ // The person's turn must not lapse while their own command runs (a navigation can take seconds, the window is 3 s): it is renewed until the
345
+ // command returns, or until the gate lets it go after a hand-back (`live` false): past that a renewal would open a new turn for the person
346
+ // once the agent's call returns, refusing the agent's calls after they handed the browser back.
347
+ const keep = setInterval(() => { if (live())
348
+ viewer.gate.input();
349
+ else
350
+ clearInterval(keep); }, KEEP_DRIVING_MS);
220
351
  keep.unref();
221
352
  try {
222
353
  if (message.type === "nav")
223
- await viewer.stream.nav(message);
354
+ await viewer.stream.nav(message, live);
224
355
  else if (message.type === "dialog")
225
356
  await viewer.stream.dialog(message);
226
357
  else
@@ -231,25 +362,113 @@ export function createLiveView(options) {
231
362
  }
232
363
  finally {
233
364
  clearInterval(keep);
365
+ command?.done();
234
366
  viewer.queued -= 1;
235
367
  }
236
368
  });
237
369
  };
370
+ /** A take-over viewer's `take` or `give`. A take asks the host first (one at a time), and the hold then starts on the session's gate; however the
371
+ * hold ends, the host's `end` is called and the viewer of the moment is told. */
372
+ const hands = (entry, viewer, what) => {
373
+ const gate = viewer.gate;
374
+ if (what === "give") {
375
+ gate.give?.("given");
376
+ return;
377
+ }
378
+ if (isHolding(gate)) {
379
+ send(viewer.conn, { type: "hold", held: true });
380
+ return;
381
+ }
382
+ // Taken already, waiting for the agent's call to return.
383
+ if (isHeld(gate)) {
384
+ send(viewer.conn, { type: "held", reason: "taking" });
385
+ return;
386
+ }
387
+ // One take at a time is asked of the host: a second one meanwhile is told so.
388
+ if (entry.taking) {
389
+ send(viewer.conn, { type: "held", reason: "taking" });
390
+ return;
391
+ }
392
+ entry.taking = true;
393
+ void takeOver.take(entry.tag).then((answer) => {
394
+ entry.taking = false;
395
+ if ("refused" in answer) {
396
+ if (entry.viewer === viewer)
397
+ send(viewer.conn, { type: "take_refused", message: answer.refused });
398
+ return;
399
+ }
400
+ const ended = (why, message) => {
401
+ try {
402
+ answer.end(why);
403
+ }
404
+ catch { /* the host's own bookkeeping cannot keep the hold */ }
405
+ if (entry.viewer)
406
+ send(entry.viewer.conn, { type: "hold", held: false, reason: why, ...(message ? { message } : {}) });
407
+ };
408
+ // A session released, or a viewer gone, while the host answered: no hold starts, and the host lets go of what it took for one.
409
+ // The host, and the viewer of the moment, are told the hold is live: at once, or once the agent's call under way returns.
410
+ const started = () => {
411
+ try {
412
+ answer.started?.();
413
+ }
414
+ catch { /* the host's own bookkeeping cannot keep the hold */ }
415
+ if (entry.viewer)
416
+ send(entry.viewer.conn, { type: "hold", held: true });
417
+ };
418
+ // No hold starts (the session released, the viewer gone, or the browser held already when the host answered): the host
419
+ // lets go of what it took for one, and the viewer still there is told its take was refused.
420
+ const cancel = () => {
421
+ try {
422
+ (answer.cancel ?? (() => answer.end("released")))();
423
+ }
424
+ catch { /* as above */ }
425
+ };
426
+ if (entry.released || entry.viewer !== viewer)
427
+ return cancel();
428
+ const holder = (options.gates ?? drivingGates)(entry.tag);
429
+ // A registry from before holds has no take: it can never hand the browser over, which "held already" would not say.
430
+ if (typeof holder.take !== "function") {
431
+ cancel();
432
+ send(viewer.conn, { type: "take_refused", message: "This browser can't be handed over from the live view." });
433
+ }
434
+ else if (!holder.take(ended, started)) {
435
+ cancel();
436
+ send(viewer.conn, { type: "take_refused", message: "The browser could not be handed to you: it is held already. Try again in a moment." });
437
+ }
438
+ }, () => {
439
+ entry.taking = false;
440
+ if (entry.viewer === viewer)
441
+ send(viewer.conn, { type: "take_refused", message: "The browser could not be handed to you. Try again." });
442
+ });
443
+ };
238
444
  const endViewer = (entry) => {
239
445
  const viewer = entry.viewer;
240
446
  if (!viewer)
241
447
  return;
242
448
  entry.viewer = null;
243
449
  viewer.unsubscribe();
244
- viewer.gate.setViewing(false);
245
- try {
246
- viewer.stream.close();
247
- }
248
- catch { /* the stream is gone either way */ }
450
+ if (takeOver)
451
+ viewer.gate.setPresent?.(false);
452
+ else if (!options.readOnly)
453
+ viewer.gate.setViewing(false);
454
+ unused(entry);
249
455
  };
456
+ const routes = { handle: (req, res) => handle(req, res), upgrade: (req, socket, head) => upgrade(req, socket, head) };
250
457
  const ensureServer = () => {
251
458
  if (mounted || origin)
252
459
  return Promise.resolve();
460
+ const given = options.listen;
461
+ if (given && "fd" in given) {
462
+ starting ??= handedSocket(given.fd).then((socket) => {
463
+ // A close that came while the socket was being listened on leaves it to the next view.
464
+ if (closed)
465
+ return;
466
+ socket.route = routes;
467
+ handed = socket;
468
+ origin = `http://${given.host}:${socket.port}`;
469
+ });
470
+ return starting;
471
+ }
253
472
  starting ??= new Promise((resolve, reject) => {
254
473
  const s = createServer((req, res) => { if (!handle(req, res)) {
255
474
  res.writeHead(404, { "Content-Length": 0 });
@@ -258,8 +477,10 @@ export function createLiveView(options) {
258
477
  s.on("upgrade", (req, socket, head) => { if (!upgrade(req, socket, head))
259
478
  socket.destroy(); });
260
479
  s.once("error", reject);
261
- // Loopback only, never 0.0.0.0: the host that wants more mounts the handler on its own server.
262
- s.listen(0, "127.0.0.1", () => { s.unref(); server = s; origin = `http://127.0.0.1:${s.address().port}`; resolve(); });
480
+ // Loopback unless the host names another address (`listen`, with its `admit`): the host that wants more mounts the
481
+ // handler on its own server.
482
+ const at = given ?? { bind: LOOPBACK_HOST, host: LOOPBACK_HOST };
483
+ s.listen(0, at.bind, () => { s.unref(); server = s; origin = `http://${at.host}:${s.address().port}`; resolve(); });
263
484
  });
264
485
  return starting;
265
486
  };
@@ -279,6 +500,9 @@ export function createLiveView(options) {
279
500
  entry.pending.clear();
280
501
  const viewer = entry.viewer;
281
502
  endViewer(entry);
503
+ // Its watchers stop with no call: the host that released it ends what it watches for.
504
+ entry.watchers.clear();
505
+ unused(entry);
282
506
  // The gate is the session's, so it ends with it even when no viewer ever took it.
283
507
  (options.gates ?? drivingGates)(tag).end();
284
508
  void viewer;
@@ -310,7 +534,7 @@ export function createLiveView(options) {
310
534
  const raced = byTag.get(tag);
311
535
  if (raced?.view)
312
536
  return raced.view;
313
- const entry = { tag, id: newViewerId(), token: newToken(), cdpUrl, view: null, released: false, viewer: null, pending: new Set() };
537
+ const entry = { tag, id: newViewerId(), token: newToken(), cdpUrl, view: null, released: false, viewer: null, pending: new Set(), stream: null, watchers: new Set(), shown: {} };
314
538
  const url = `${origin}${prefix}/v/${entry.id}#t=${entry.token}`;
315
539
  entry.view = { fullscreen: url, framed: url, pages: [] };
316
540
  byTag.set(tag, entry);
@@ -318,7 +542,23 @@ export function createLiveView(options) {
318
542
  return entry.view;
319
543
  },
320
544
  known: (tag) => { const entry = byTag.get(tag); return entry && !entry.released ? entry.view : null; },
321
- driving: (tag) => { const entry = byTag.get(tag); return !!entry?.viewer && (options.gates ?? drivingGates)(tag).state() === "person"; },
545
+ driving: (tag) => { const entry = byTag.get(tag); if (!entry)
546
+ return false; const gate = (options.gates ?? drivingGates)(tag); return isHeld(gate) || (!!entry.viewer && gate.state() === "person"); },
547
+ watch(tag, watcher) {
548
+ const entry = byTag.get(tag);
549
+ if (!entry || entry.released)
550
+ return null;
551
+ entry.watchers.add(watcher);
552
+ try {
553
+ streamOf(entry);
554
+ }
555
+ catch {
556
+ entry.watchers.delete(watcher);
557
+ return null;
558
+ }
559
+ return () => { if (entry.watchers.delete(watcher))
560
+ unused(entry); };
561
+ },
322
562
  tracked: () => ({ sessions: byTag.size, opening: [...opening.values()].reduce((n, marks) => n + marks.size, 0) }),
323
563
  release,
324
564
  async close() {
@@ -331,6 +571,13 @@ export function createLiveView(options) {
331
571
  await starting.catch(() => undefined);
332
572
  for (const tag of [...byTag.keys()])
333
573
  await release(tag);
574
+ // A handed socket stays listening for the process's next view; this view's requests on it go, if it still holds it.
575
+ const socket = handed;
576
+ handed = null;
577
+ if (socket && socket.route === routes) {
578
+ socket.route = null;
579
+ socket.server.closeAllConnections();
580
+ }
334
581
  const s = server;
335
582
  server = null;
336
583
  if (s)
@@ -9,6 +9,8 @@ const STAND_IN_RETRY_MS = 1_000;
9
9
  const STAND_IN_TRIES = 6;
10
10
  /** Chrome sends a page's address when it moves but not its title when the document sets it, so the title is asked for at the end of a load and now and then. */
11
11
  const TITLE_POLL_MS = 1_500;
12
+ /** How long after the browser lists its pages the stream looks whether it follows one: none, and the viewer is told there is no page yet. */
13
+ const NO_PAGE_LOOK_MS = 250;
12
14
  /** A text message is one paste or one typed run: bound it so a viewer cannot make the browser take an unbounded insert. */
13
15
  const MAX_TEXT = 100_000;
14
16
  const BUTTON_BITS = { left: 1, right: 2, middle: 4 };
@@ -163,7 +165,15 @@ export const openStream = (cdpUrl, handlers) => {
163
165
  if (best)
164
166
  follow(best.id);
165
167
  };
166
- socket.onopen = () => { post("Target.setDiscoverTargets", { discover: true }); };
168
+ // A browser with no page once its pages are listed (a headless one that starts with none) has none to show yet. The list may come just before or just after
169
+ // the answer, so the stream looks a moment after the answer.
170
+ socket.onopen = () => {
171
+ void request("Target.setDiscoverTargets", { discover: true }).then(() => {
172
+ const look = setTimeout(() => { if (!current && !closing)
173
+ handlers.noPage?.(); }, NO_PAGE_LOOK_MS);
174
+ look.unref?.();
175
+ }, () => { });
176
+ };
167
177
  socket.onmessage = (event) => {
168
178
  let message;
169
179
  try {
@@ -256,6 +266,8 @@ export const openStream = (cdpUrl, handlers) => {
256
266
  handlers.dialog(null);
257
267
  }
258
268
  choose();
269
+ if (!current)
270
+ handlers.noPage?.();
259
271
  }
260
272
  }
261
273
  catch { /* a handler that throws must not end the browser's socket */ }
@@ -319,7 +331,7 @@ export const openStream = (cdpUrl, handlers) => {
319
331
  else
320
332
  return bad();
321
333
  },
322
- async nav(message) {
334
+ async nav(message, live = () => true) {
323
335
  const sessionId = page();
324
336
  if (message === null || typeof message !== "object" || message.type !== "nav")
325
337
  return bad();
@@ -330,7 +342,8 @@ export const openStream = (cdpUrl, handlers) => {
330
342
  if (message.action === "back") {
331
343
  const history = await request("Page.getNavigationHistory", {}, sessionId);
332
344
  const entry = history?.entries?.[Number(history?.currentIndex) - 1];
333
- if (!entry || !Number.isInteger(entry.id))
345
+ // A command let go meanwhile (handed back, and the agent's call went on past the bound) does not move the page under it.
346
+ if (!entry || !Number.isInteger(entry.id) || !live())
334
347
  return;
335
348
  await request("Page.navigateToHistoryEntry", { entryId: entry.id }, sessionId);
336
349
  return;