@parcha/pi-browser 0.0.0-bootstrap.0 → 0.1.0-beta.13

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 (104) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +33 -0
  4. package/README.md +328 -1
  5. package/dist/coding-agent-local.d.ts +16 -0
  6. package/dist/coding-agent-local.js +138 -0
  7. package/dist/coding-agent.d.ts +78 -0
  8. package/dist/coding-agent.js +446 -0
  9. package/dist/core/contract.d.ts +26 -0
  10. package/dist/core/contract.js +154 -0
  11. package/dist/core/custody.d.ts +111 -0
  12. package/dist/core/custody.js +122 -0
  13. package/dist/core/decisions.d.ts +43 -0
  14. package/dist/core/decisions.js +4 -0
  15. package/dist/core/downloads.d.ts +35 -0
  16. package/dist/core/downloads.js +131 -0
  17. package/dist/core/effects.d.ts +63 -0
  18. package/dist/core/effects.js +256 -0
  19. package/dist/core/evidence.d.ts +43 -0
  20. package/dist/core/evidence.js +6 -0
  21. package/dist/core/failures.d.ts +28 -0
  22. package/dist/core/failures.js +59 -0
  23. package/dist/core/find.d.ts +32 -0
  24. package/dist/core/find.js +179 -0
  25. package/dist/core/guard.d.ts +6 -0
  26. package/dist/core/guard.js +24 -0
  27. package/dist/core/host.d.ts +279 -0
  28. package/dist/core/host.js +2 -0
  29. package/dist/core/images.d.ts +37 -0
  30. package/dist/core/images.js +60 -0
  31. package/dist/core/lease.d.ts +16 -0
  32. package/dist/core/lease.js +30 -0
  33. package/dist/core/receipts.d.ts +19 -0
  34. package/dist/core/receipts.js +22 -0
  35. package/dist/core/redact.d.ts +13 -0
  36. package/dist/core/redact.js +83 -0
  37. package/dist/core/session-control.d.ts +25 -0
  38. package/dist/core/session-control.js +75 -0
  39. package/dist/core/sites.d.ts +33 -0
  40. package/dist/core/sites.js +102 -0
  41. package/dist/core/tools.d.ts +37 -0
  42. package/dist/core/tools.js +170 -0
  43. package/dist/core/uri.d.ts +11 -0
  44. package/dist/core/uri.js +37 -0
  45. package/dist/core/usage.d.ts +38 -0
  46. package/dist/core/usage.js +44 -0
  47. package/dist/core/web.d.ts +98 -0
  48. package/dist/core/web.js +327 -0
  49. package/dist/driver/stagehand.d.ts +25 -0
  50. package/dist/driver/stagehand.js +141 -0
  51. package/dist/durable-result.d.ts +6 -0
  52. package/dist/durable-result.js +2 -0
  53. package/dist/durable.d.ts +75 -0
  54. package/dist/durable.js +484 -0
  55. package/dist/index.d.ts +18 -0
  56. package/dist/index.js +19 -0
  57. package/dist/providers/browserbase-net.d.ts +13 -0
  58. package/dist/providers/browserbase-net.js +96 -0
  59. package/dist/providers/browserbase.d.ts +152 -0
  60. package/dist/providers/browserbase.js +262 -0
  61. package/dist/providers/cdp-call.d.ts +6 -0
  62. package/dist/providers/cdp-call.js +25 -0
  63. package/dist/providers/cdp.d.ts +48 -0
  64. package/dist/providers/cdp.js +353 -0
  65. package/dist/providers/http.d.ts +2 -0
  66. package/dist/providers/http.js +21 -0
  67. package/dist/providers/kernel.d.ts +49 -0
  68. package/dist/providers/kernel.js +246 -0
  69. package/dist/providers/shared.d.ts +47 -0
  70. package/dist/providers/shared.js +82 -0
  71. package/dist/recorder/credential.d.ts +9 -0
  72. package/dist/recorder/credential.js +49 -0
  73. package/dist/recorder/follow.d.ts +26 -0
  74. package/dist/recorder/follow.js +138 -0
  75. package/dist/recorder/frames.d.ts +80 -0
  76. package/dist/recorder/frames.js +309 -0
  77. package/dist/recorder/index.d.ts +3 -0
  78. package/dist/recorder/index.js +6 -0
  79. package/dist/recorder/jpeg.d.ts +5 -0
  80. package/dist/recorder/jpeg.js +34 -0
  81. package/dist/store.d.ts +56 -0
  82. package/dist/store.js +196 -0
  83. package/dist/testing/backend.d.ts +231 -0
  84. package/dist/testing/backend.js +414 -0
  85. package/dist/testing/driver.d.ts +28 -0
  86. package/dist/testing/driver.js +32 -0
  87. package/dist/testing/index.d.ts +4 -0
  88. package/dist/testing/index.js +4 -0
  89. package/dist/testing/pages.d.ts +3 -0
  90. package/dist/testing/pages.js +10 -0
  91. package/dist/testing/sentinels.d.ts +29 -0
  92. package/dist/testing/sentinels.js +38 -0
  93. package/dist/vendor/stagehand-facade/contract.d.ts +348 -0
  94. package/dist/vendor/stagehand-facade/contract.js +155 -0
  95. package/dist/vendor/stagehand-facade/runtime.d.ts +90 -0
  96. package/dist/vendor/stagehand-facade/runtime.js +1640 -0
  97. package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +15 -0
  98. package/dist/vendor/stagehand-facade/screenshot-transport.js +51 -0
  99. package/dist/vendor/stagehand-facade/tools.d.ts +31 -0
  100. package/dist/vendor/stagehand-facade/tools.js +139 -0
  101. package/dist/web.d.ts +41 -0
  102. package/dist/web.js +38 -0
  103. package/package.json +125 -1
  104. package/src/vendor/stagehand-facade/UPSTREAM.json +24 -0
@@ -0,0 +1,414 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { crc32 } from "node:zlib";
3
+ import fs from "node:fs";
4
+ import http from "node:http";
5
+ import { makeSentinels } from "./sentinels.js";
6
+ /** A vendor SDK's failure: the HTTP status is on the error, never inside the text. */
7
+ export class FakeProviderError extends Error {
8
+ status;
9
+ constructor(message, status = 502) {
10
+ super(message);
11
+ this.name = "FakeProviderError";
12
+ this.status = status;
13
+ }
14
+ }
15
+ export const fixturePage = (url, text, title = "Fixture") => ({ url, title, text, html: `<main><p>${text}</p></main>` });
16
+ /** A PNG or JPEG whose header declares `width` x `height`: enough for a reader that decodes the header, not a picture. */
17
+ export function fakeImage(type, width, height) {
18
+ if (type === "jpeg") {
19
+ const sof = Buffer.from([0xff, 0xc0, 0x00, 0x0b, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x01, 0x01, 0x11, 0x00]);
20
+ return Buffer.concat([Buffer.from([0xff, 0xd8]), sof, Buffer.from([0xff, 0xd9])]);
21
+ }
22
+ const chunk = (kind, data) => {
23
+ const head = Buffer.concat([Buffer.from(kind, "ascii"), data]);
24
+ const length = Buffer.alloc(4);
25
+ length.writeUInt32BE(data.length);
26
+ const crc = Buffer.alloc(4);
27
+ crc.writeUInt32BE(crc32(head));
28
+ return Buffer.concat([length, head, crc]);
29
+ };
30
+ const ihdr = Buffer.alloc(13);
31
+ ihdr.writeUInt32BE(width, 0);
32
+ ihdr.writeUInt32BE(height, 4);
33
+ ihdr[8] = 8;
34
+ ihdr[9] = 2;
35
+ return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk("IHDR", ihdr), chunk("IEND", Buffer.alloc(0))]);
36
+ }
37
+ const DEFAULT_CAPS = { timeoutModel: "inactivity", maxLifetimeS: 3600, survivesDisconnect: false, releaseIsAsync: false, extension: "loaded-locally" };
38
+ export class FakeBackend {
39
+ sentinels;
40
+ pages;
41
+ ledger = [];
42
+ /** Every call the driver made on a page, in order; a read answered from a receipt never shows up here. */
43
+ dispatched = [];
44
+ /** Emits `held` with the op name when a held call has been applied and will never be answered. */
45
+ events = new EventEmitter();
46
+ sessions = new Map();
47
+ provider;
48
+ broker;
49
+ driverFace;
50
+ seq = 0;
51
+ holdOp = null;
52
+ loseOp = null;
53
+ failures = new Map();
54
+ delays = new Map();
55
+ peak = 0;
56
+ echoOn = false;
57
+ opts;
58
+ constructor(options = {}) {
59
+ this.sentinels = options.sentinels ?? makeSentinels();
60
+ this.pages = options.pages ?? {};
61
+ this.opts = {
62
+ ...options,
63
+ start: options.start ?? "about:blank",
64
+ fetches: options.fetches ?? {},
65
+ search: options.search ?? [],
66
+ downloads: options.downloads ?? {},
67
+ connections: options.connections ?? [{ name: "demo", startUrl: "https://login.sentinel.test/", fields: [{ name: "username", type: "text" }, { name: "password", type: "password" }, { name: "otp", type: "totp" }], allowedOrigins: ["https://login.sentinel.test"], enrollment: true }],
68
+ };
69
+ this.provider = this.makeProvider(options.name ?? "fake", { ...DEFAULT_CAPS, ...options.caps });
70
+ this.broker = new FakeBroker(this);
71
+ this.driverFace = new FakeDriverFace(this);
72
+ }
73
+ /** The next call of `op` is applied and recorded, then never answered. */
74
+ hold(op) { this.holdOp = op; }
75
+ /** The next call of `op` is applied and recorded, then fails: the provider did the work and the answer was lost. */
76
+ lose(op) { this.loseOp = op; }
77
+ /** The next `times` calls of `op` fail before they take effect. */
78
+ fail(op, times = 1) { this.failures.set(op, times); }
79
+ /** `op` sleeps `ms` before it takes effect; a caller that hangs up meanwhile is not served. */
80
+ delay(op, ms) { this.delays.set(op, ms); }
81
+ /** Failure text repeats the request and every secret the backend holds. */
82
+ echo(on = true) { this.echoOn = on; }
83
+ endAll() { for (const s of this.sessions.values())
84
+ s.state = "stopped"; }
85
+ goto(url) { for (const s of this.sessions.values())
86
+ if (s.state === "running")
87
+ s.url = url; }
88
+ reset() {
89
+ this.sessions.clear();
90
+ this.ledger.length = 0;
91
+ this.dispatched.length = 0;
92
+ this.seq = 0;
93
+ this.holdOp = null;
94
+ this.loseOp = null;
95
+ this.failures.clear();
96
+ this.delays.clear();
97
+ this.peak = 0;
98
+ this.echoOn = false;
99
+ }
100
+ live() { return [...this.sessions.values()].filter((s) => s.state === "running").map(({ id, tag }) => ({ id, tag })); }
101
+ liveCount() { return this.live().length; }
102
+ tally() {
103
+ const count = (op) => this.ledger.filter((r) => r.op === op).length;
104
+ return {
105
+ creates: count("create"), findByTag: count("findByTag"), status: count("status"), attaches: count("attach"), releases: count("release"), releaseNoops: count("release-noop"),
106
+ fetches: count("fetch"), searches: count("search"), dispatches: this.dispatched.filter((d) => d.op === "run").length, reads: this.dispatched.filter((d) => d.op === "read").length,
107
+ peakLive: this.peak, liveAtEnd: this.liveCount(),
108
+ };
109
+ }
110
+ /** A failing vendor's error text: the request's credentials and the connect URLs the backend holds. */
111
+ echoText(op) {
112
+ const s = this.sentinels;
113
+ const vendor = `${op} failed: authorization=Bearer ${s.runToken} x-bb-api-key=${s.bbApiKey} connect=${s.bbConnectUrl} cdp=${s.kernelCdpUrl}`;
114
+ return op.startsWith("broker.") ? `${vendor} user=${s.loginUsername} password=${s.loginPassword} totp=${s.totpSeed} vault=${s.vaultRef}` : vendor;
115
+ }
116
+ record(op, fields = {}) {
117
+ const row = { n: this.ledger.length + 1, op, ...fields };
118
+ this.ledger.push(row);
119
+ if (this.opts.logFile)
120
+ fs.appendFileSync(this.opts.logFile, `${JSON.stringify(row)}\n`);
121
+ return row;
122
+ }
123
+ async before(op, signal) {
124
+ signal?.throwIfAborted();
125
+ const ms = this.delays.get(op);
126
+ if (ms) {
127
+ await new Promise((resolve, reject) => {
128
+ const timer = setTimeout(resolve, ms);
129
+ signal?.addEventListener("abort", () => { clearTimeout(timer); reject(signal.reason); }, { once: true });
130
+ });
131
+ }
132
+ const left = this.failures.get(op) ?? 0;
133
+ if (left > 0) {
134
+ this.failures.set(op, left - 1);
135
+ this.record(`${op}-failed`);
136
+ throw new FakeProviderError(this.echoOn ? this.echoText(op) : `${op} failed: provider unavailable`);
137
+ }
138
+ }
139
+ async after(op) {
140
+ if (this.loseOp === op) {
141
+ this.loseOp = null;
142
+ throw new FakeProviderError(`${op} was applied and its answer was lost`);
143
+ }
144
+ if (this.holdOp !== op)
145
+ return;
146
+ this.holdOp = null;
147
+ this.events.emit("held", op);
148
+ await new Promise(() => { });
149
+ }
150
+ noteLive() { this.peak = Math.max(this.peak, this.liveCount()); }
151
+ newId(prefix) { this.seq += 1; return `${prefix}-${this.seq}`; }
152
+ running(id) { const s = this.sessions.get(id); return s && s.state === "running" ? s : null; }
153
+ targetOf(session) {
154
+ const url = this.sentinels.bbConnectUrl.replace(/sessionId=[^&]+/, `sessionId=${session.id}`);
155
+ if (!session.broker)
156
+ return { sdkCdpUrl: url };
157
+ return { sdkCdpUrl: `ws://127.0.0.1:1/vm-local/?sessionId=${session.id}`, dial: { url: this.sentinels.kernelCdpUrl, headers: { Authorization: `Bearer ${this.sentinels.brokerCapability}` } } };
158
+ }
159
+ makeProvider(name, caps) {
160
+ const b = this;
161
+ return {
162
+ name,
163
+ caps,
164
+ async create(spec, signal) {
165
+ await b.before("create", signal);
166
+ const id = b.newId("fake_sess");
167
+ b.sessions.set(id, { id, tag: spec.tag, metadata: { ...spec.metadata }, state: "running", url: b.opts.start, broker: false, plane: "default" });
168
+ b.noteLive();
169
+ b.record("create", { id, tag: spec.tag, metadata: { ...spec.metadata }, contextId: spec.contextId ?? null, verified: spec.verified, liveNow: b.liveCount() });
170
+ await b.after("create");
171
+ return { id, tag: spec.tag };
172
+ },
173
+ async findByTag(tag, signal) {
174
+ await b.before("findByTag", signal);
175
+ const found = [...b.sessions.values()].filter((s) => s.tag === tag && s.state === "running");
176
+ b.record("findByTag", { tag, found: found.map((s) => s.id) });
177
+ await b.after("findByTag");
178
+ return found.map((s) => ({ id: s.id, tag: s.tag }));
179
+ },
180
+ async status(ref, signal) {
181
+ await b.before("status", signal);
182
+ const s = b.sessions.get(ref.id);
183
+ b.record("status", { id: ref.id });
184
+ await b.after("status");
185
+ return !s ? "gone" : s.state === "running" ? "running" : "stopped";
186
+ },
187
+ async attach(ref, signal) {
188
+ await b.before("attach", signal);
189
+ const s = b.sessions.get(ref.id);
190
+ if (!s)
191
+ throw new FakeProviderError(`no session ${ref.id}`, 404);
192
+ b.record("attach", { id: ref.id });
193
+ await b.after("attach");
194
+ return b.targetOf(s);
195
+ },
196
+ async release(ref, signal) {
197
+ await b.before("release", signal);
198
+ const s = b.sessions.get(ref.id);
199
+ const was = s?.state === "running";
200
+ if (s)
201
+ s.state = "stopped";
202
+ b.record(was ? "release" : "release-noop", { id: ref.id, tag: s?.tag ?? ref.tag });
203
+ await b.after("release");
204
+ },
205
+ async liveView(ref) {
206
+ const s = b.running(ref.id);
207
+ b.record("liveView", { id: ref.id });
208
+ if (!s)
209
+ return null;
210
+ const view = b.sentinels.bbLiveViewUrl;
211
+ return { fullscreen: view, framed: `${view}&framed=1`, pages: [{ id: "p1", url: s.url, title: b.pages[s.url]?.title ?? "", fullscreen: view }] };
212
+ },
213
+ async fetch(request, signal) {
214
+ await b.before("fetch", signal);
215
+ b.record("fetch", { url: request.url });
216
+ await b.after("fetch");
217
+ const entry = b.opts.fetches[request.url];
218
+ if (entry === undefined)
219
+ throw new FakeProviderError(`fetch ${request.url}: 404`, 404);
220
+ if (typeof entry === "string")
221
+ return { finalUrl: request.url, statusCode: 200, contentType: "text/markdown", content: entry };
222
+ const answer = entry[request.format === "raw" ? "raw" : "markdown"];
223
+ if (!answer || "status" in answer)
224
+ throw new FakeProviderError(`fetch ${request.url}: ${answer?.status ?? 404}`, answer?.status ?? 404);
225
+ return { finalUrl: request.url, statusCode: 200, contentType: answer.contentType, content: answer.content };
226
+ },
227
+ async search(request, signal) {
228
+ await b.before("search", signal);
229
+ b.record("search", { query: request.query });
230
+ await b.after("search");
231
+ return { results: b.opts.search.slice(0, request.n) };
232
+ },
233
+ downloads: {
234
+ async list(_ref) { return Object.entries(b.opts.downloads).map(([name, body]) => ({ name, sizeBytes: Buffer.byteLength(body), modifiedAt: null })); },
235
+ async read(_ref, fileName, maxBytes) {
236
+ const body = Buffer.from(b.opts.downloads[fileName] ?? "").subarray(0, maxBytes);
237
+ return (async function* () { yield body; })();
238
+ },
239
+ },
240
+ };
241
+ }
242
+ /** For a child's `remoteProvider` and `remoteDriver`; a held call stays open until the child dies. */
243
+ async serve() {
244
+ const faces = {
245
+ provider: this.provider,
246
+ broker: this.broker,
247
+ driver: this.driverFace,
248
+ };
249
+ const server = http.createServer((req, res) => {
250
+ let raw = "";
251
+ req.on("data", (c) => { raw += c; });
252
+ req.on("end", async () => {
253
+ const aborted = new AbortController();
254
+ res.on("close", () => { if (!res.writableEnded)
255
+ aborted.abort(); });
256
+ try {
257
+ const [face, method] = decodeURIComponent((req.url ?? "").replace(/^\/rpc\//, "")).split(".");
258
+ const fn = faces[face ?? ""]?.[method ?? ""];
259
+ if (typeof fn !== "function") {
260
+ res.writeHead(404).end(JSON.stringify({ error: { message: `no ${face}.${method}`, status: 404 } }));
261
+ return;
262
+ }
263
+ const args = raw ? JSON.parse(raw).args : [];
264
+ const result = await (face === "provider" ? fn.call(faces[face], ...args, aborted.signal) : fn.call(faces[face], ...args));
265
+ if (!res.writableEnded && !aborted.signal.aborted)
266
+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ result: result ?? null }));
267
+ }
268
+ catch (error) {
269
+ if (aborted.signal.aborted)
270
+ return;
271
+ const e = error;
272
+ res.writeHead(e.status ?? 500, { "content-type": "application/json" }).end(JSON.stringify({ error: { message: e.message ?? String(error), status: e.status ?? 500 } }));
273
+ }
274
+ });
275
+ });
276
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
277
+ return {
278
+ url: `http://127.0.0.1:${server.address().port}`,
279
+ close: () => new Promise((resolve) => { server.closeAllConnections?.(); server.close(() => resolve()); }),
280
+ };
281
+ }
282
+ }
283
+ /** A held call never returns; an aborted one stops its request. */
284
+ export function remoteProvider(url, options = {}) {
285
+ const call = async (method, args, signal) => {
286
+ const res = await fetch(`${url}/rpc/provider.${method}`, { method: "POST", signal, headers: { "content-type": "application/json" }, body: JSON.stringify({ args }) });
287
+ const body = (await res.json());
288
+ if (body.error)
289
+ throw new FakeProviderError(body.error.message, body.error.status);
290
+ return body.result;
291
+ };
292
+ return {
293
+ name: options.name ?? "fake",
294
+ caps: { ...DEFAULT_CAPS, ...options.caps },
295
+ create: (spec, signal) => call("create", [spec], signal),
296
+ findByTag: (tag, signal) => call("findByTag", [tag], signal),
297
+ status: (ref, signal) => call("status", [ref], signal),
298
+ attach: (ref, signal) => call("attach", [ref], signal),
299
+ release: (ref, signal) => call("release", [ref], signal),
300
+ liveView: (ref) => call("liveView", [ref]),
301
+ fetch: (request, signal) => call("fetch", [request], signal),
302
+ search: (request, signal) => call("search", [request], signal),
303
+ };
304
+ }
305
+ /** Counts a fill before the provider is touched and never repeats an unknown one; its failures carry only codes. */
306
+ export class FakeBroker {
307
+ b;
308
+ constructor(b) {
309
+ this.b = b;
310
+ }
311
+ async connections() { return this.b.opts.connections; }
312
+ async acquire(name) {
313
+ await this.b.before("broker.acquire");
314
+ const id = this.b.newId("br");
315
+ const session = { id, tag: name, metadata: {}, state: "running", url: this.b.opts.connections.find((c) => c.name === name)?.startUrl ?? this.b.opts.start, broker: true, plane: name };
316
+ this.b.sessions.set(id, session);
317
+ this.b.noteLive();
318
+ this.b.record("broker.acquire", { id, name });
319
+ await this.b.after("broker.acquire");
320
+ return { session: id, attach: this.b.targetOf(session), leaseExpiresAt: new Date(Date.now() + 60_000).toISOString(), recording: false };
321
+ }
322
+ async heartbeat(session) {
323
+ await this.b.before("broker.heartbeat");
324
+ this.b.record("broker.heartbeat", { id: session });
325
+ return { leaseExpiresAt: new Date(Date.now() + 60_000).toISOString() };
326
+ }
327
+ async release(session) {
328
+ await this.b.before("broker.release");
329
+ const s = this.b.sessions.get(session);
330
+ if (s)
331
+ s.state = "stopped";
332
+ this.b.record("broker.release", { id: session });
333
+ await this.b.after("broker.release");
334
+ }
335
+ async fill(session, request) {
336
+ this.b.record("broker.fill", { id: session, pageUrl: request.pageUrl, fields: request.fields.map((f) => f.field) });
337
+ await this.b.before("broker.fill");
338
+ await this.b.after("broker.fill");
339
+ return { status: "completed", fields: request.fields.map((_f, index) => ({ index, status: "filled" })) };
340
+ }
341
+ async captureTotpSeed(session, request) {
342
+ this.b.record("broker.totp", { id: session, pageUrl: request.pageUrl });
343
+ await this.b.before("broker.totp");
344
+ return { stored: true, field: "otp" };
345
+ }
346
+ async downloads() { return Object.entries(this.b.opts.downloads).map(([name, body]) => ({ name, sizeBytes: Buffer.byteLength(body), modifiedAt: null })); }
347
+ }
348
+ export class FakeDriverFace {
349
+ b;
350
+ constructor(b) {
351
+ this.b = b;
352
+ }
353
+ session(id) {
354
+ const s = this.b.sessions.get(id);
355
+ if (!s || s.state !== "running")
356
+ throw new FakeProviderError(`session ${id} is not running`, 410);
357
+ return s;
358
+ }
359
+ pageOf(id) {
360
+ const url = this.session(id).url;
361
+ return this.b.pages[url] ?? fixturePage(url, "");
362
+ }
363
+ async call(id, op, knob, detail = {}) {
364
+ await this.b.before(`driver.${knob}`);
365
+ this.b.dispatched.push({ op, session: id, url: this.b.sessions.get(id)?.url ?? null, ...detail });
366
+ }
367
+ async connect(target) {
368
+ await this.b.before("driver.connect");
369
+ const id = new URL(target.sdkCdpUrl).searchParams.get("sessionId") ?? "";
370
+ this.session(id);
371
+ return id;
372
+ }
373
+ async snapshot(id) {
374
+ await this.call(id, "snapshot", "snapshot");
375
+ const out = `[0] main\n [1] text: ${this.pageOf(id).text}`;
376
+ await this.b.after("driver.snapshot");
377
+ return out;
378
+ }
379
+ /** A `goto` action moves the page; any other code returns what it was given. */
380
+ async run(id, input) {
381
+ await this.call(id, "run", "run", { input });
382
+ const go = input.actions?.find((action) => action.op === "goto");
383
+ if (go?.url)
384
+ this.session(id).url = go.url;
385
+ const out = input.actions ? { completed: input.actions.length, url: this.session(id).url } : { value: input.code };
386
+ await this.b.after("driver.run");
387
+ return out;
388
+ }
389
+ /** No `dispatched` row: a read of the URL is not a read of the page. */
390
+ async url(id) {
391
+ await this.b.before("driver.url");
392
+ return this.session(id).url;
393
+ }
394
+ /** Header-only image of the viewport (or full page) times the device scale; each capture is a dispatched row. */
395
+ async screenshot(id, options = {}) {
396
+ await this.call(id, "screenshot", "screenshot", { options });
397
+ const { viewport = { width: 1288, height: 711 }, fullPageHeight = 8319, deviceScale = 1 } = this.b.opts;
398
+ const factor = options.scale === "css" ? 1 : deviceScale;
399
+ const width = viewport.width * factor;
400
+ const height = (options.fullPage ? fullPageHeight : viewport.height) * factor;
401
+ const type = options.type ?? "jpeg";
402
+ await this.b.after("driver.screenshot");
403
+ return { data: fakeImage(type, width, height).toString("base64"), mimeType: `image/${type}`, width, height };
404
+ }
405
+ async page(id) {
406
+ await this.call(id, "read", "page");
407
+ const out = { ...this.pageOf(id) };
408
+ await this.b.after("driver.page");
409
+ return out;
410
+ }
411
+ async close(id) {
412
+ this.b.dispatched.push({ op: "close", session: id, url: null });
413
+ }
414
+ }
@@ -0,0 +1,28 @@
1
+ import type { AttachTarget } from "../core/host.js";
2
+ import { type FakeBackend, type FakeScreenshotOptions, type FixturePage } from "./backend.js";
3
+ export type FakeDriver = {
4
+ snapshot(): Promise<string>;
5
+ /** A `goto` action moves the page; any other code returns what it was given. */
6
+ run(input: {
7
+ code?: string;
8
+ actions?: Array<{
9
+ op: string;
10
+ url?: string;
11
+ [field: string]: unknown;
12
+ }>;
13
+ }): Promise<unknown>;
14
+ /** The page's URL without a `read` row. */
15
+ url(): Promise<string>;
16
+ screenshot(options?: FakeScreenshotOptions): Promise<{
17
+ data: string;
18
+ mimeType: string;
19
+ width: number;
20
+ height: number;
21
+ }>;
22
+ page(): Promise<FixturePage>;
23
+ close(): Promise<void>;
24
+ };
25
+ export type FakeDriverFactory = (target: AttachTarget) => Promise<FakeDriver>;
26
+ export declare function fakeDriver(b: FakeBackend): FakeDriverFactory;
27
+ /** A held op never returns. */
28
+ export declare function remoteDriver(url: string): FakeDriverFactory;
@@ -0,0 +1,32 @@
1
+ import { FakeProviderError } from "./backend.js";
2
+ const bind = (face, id) => ({
3
+ snapshot: () => face.snapshot(id),
4
+ run: (input) => face.run(id, input),
5
+ url: () => face.url(id),
6
+ screenshot: (options) => face.screenshot(id, options),
7
+ page: () => face.page(id),
8
+ close: () => face.close(id),
9
+ });
10
+ export function fakeDriver(b) {
11
+ return async (target) => bind(b.driverFace, await b.driverFace.connect(target));
12
+ }
13
+ /** A held op never returns. */
14
+ export function remoteDriver(url) {
15
+ const rpc = async (method, args) => {
16
+ const res = await fetch(`${url}/rpc/driver.${method}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ args }) });
17
+ const body = (await res.json());
18
+ if (body.error)
19
+ throw new FakeProviderError(body.error.message, body.error.status);
20
+ return body.result;
21
+ };
22
+ const face = {
23
+ connect: (target) => rpc("connect", [target]),
24
+ snapshot: (id) => rpc("snapshot", [id]),
25
+ run: (id, input) => rpc("run", [id, input]),
26
+ url: (id) => rpc("url", [id]),
27
+ screenshot: (id, options) => rpc("screenshot", [id, options]),
28
+ page: (id) => rpc("page", [id]),
29
+ close: (id) => rpc("close", [id]),
30
+ };
31
+ return async (target) => bind(face, await face.connect(target));
32
+ }
@@ -0,0 +1,4 @@
1
+ export * from "./backend.js";
2
+ export * from "./driver.js";
3
+ export * from "./pages.js";
4
+ export * from "./sentinels.js";
@@ -0,0 +1,4 @@
1
+ export * from "./backend.js";
2
+ export * from "./driver.js";
3
+ export * from "./pages.js";
4
+ export * from "./sentinels.js";
@@ -0,0 +1,3 @@
1
+ import { type FixturePage } from "./backend.js";
2
+ import type { Sentinels } from "./sentinels.js";
3
+ export declare function sentinelPages(s: Sentinels): Record<string, FixturePage>;
@@ -0,0 +1,10 @@
1
+ import { fixturePage } from "./backend.js";
2
+ export function sentinelPages(s) {
3
+ const at = (url, text, title) => [url, fixturePage(url, text, title)];
4
+ return Object.fromEntries([
5
+ at("https://login.sentinel.test/", "Sign in. Username, password.", "Sign in"),
6
+ at("https://login.sentinel.test/enroll", `Scan the code or type this key into your authenticator: ${s.totpSeed.match(/.{1,4}/g)?.join(" ")} (${s.totpSeed})`, "Set up two-factor"),
7
+ at("https://debug.sentinel.test/", `upstream debug: ${s.bbConnectUrl} and ${s.kernelCdpUrl}`, "Upstream error"),
8
+ at("https://example.test/article", "An article with nothing secret in it.", "Article"),
9
+ ]);
10
+ }
@@ -0,0 +1,29 @@
1
+ export type Sentinels = {
2
+ bbApiKey: string;
3
+ bbSigningKey: string;
4
+ bbSessionId: string;
5
+ /** Carries the API key and the signing key. */
6
+ bbConnectUrl: string;
7
+ /** The live view's own token, inside its URL: allowed on the host channel only. */
8
+ bbLiveViewToken: string;
9
+ /** Allowed on the host channel only. */
10
+ bbLiveViewUrl: string;
11
+ kernelApiKey: string;
12
+ /** The CDP JWT inside `kernelCdpUrl`, a secret of its own so a leak of the token alone is found. */
13
+ kernelJwt: string;
14
+ kernelCdpUrl: string;
15
+ kernelLiveViewUrl: string;
16
+ runToken: string;
17
+ brokerCapability: string;
18
+ loginUsername: string;
19
+ loginPassword: string;
20
+ totpSeed: string;
21
+ vaultRef: string;
22
+ pageApiKey: string;
23
+ pageSigningKey: string;
24
+ pageToken: string;
25
+ pageUrl: string;
26
+ };
27
+ export declare function makeSentinels(): Sentinels;
28
+ /** The exact values a host registers with `redact.values()`; never provider keys, which the shapes cover. */
29
+ export declare const hostRegistered: (s: Sentinels) => string[];
@@ -0,0 +1,38 @@
1
+ import { randomBytes } from "node:crypto";
2
+ const hex = () => randomBytes(32).toString("hex");
3
+ const B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
4
+ const base32 = () => Array.from(randomBytes(32), (b) => B32[b & 31]).join("");
5
+ export function makeSentinels() {
6
+ const bbApiKey = `bb_live_${hex()}`;
7
+ const bbSigningKey = hex();
8
+ const bbSessionId = `bbs-${randomBytes(8).toString("hex")}`;
9
+ const liveViewToken = hex();
10
+ const kernelJwt = `eyJ${randomBytes(24).toString("base64url")}.${randomBytes(48).toString("base64url")}.${randomBytes(32).toString("base64url")}`;
11
+ const pageApiKey = hex();
12
+ const pageSigningKey = hex();
13
+ const pageToken = hex();
14
+ return {
15
+ bbApiKey,
16
+ bbSigningKey,
17
+ bbSessionId,
18
+ bbConnectUrl: `wss://connect.browserbase.com/?apiKey=${bbApiKey}&signingKey=${bbSigningKey}&sessionId=${bbSessionId}`,
19
+ bbLiveViewToken: liveViewToken,
20
+ bbLiveViewUrl: `https://www.browserbase.com/devtools-fullscreen/inspector.html?wss=connect.browserbase.com/debug/${bbSessionId}/devtools/page/${liveViewToken}&token=${liveViewToken}`,
21
+ kernelApiKey: `sk_kernel_${hex()}`,
22
+ kernelJwt,
23
+ kernelCdpUrl: `wss://kernel.sentinel.test/browser/cdp?jwt=${kernelJwt}`,
24
+ kernelLiveViewUrl: `https://kernel.sentinel.test/live/${hex()}`,
25
+ runToken: hex(),
26
+ brokerCapability: hex(),
27
+ loginUsername: `user-${randomBytes(8).toString("hex")}@sentinel.test`,
28
+ loginPassword: `pw-${hex()}`,
29
+ totpSeed: base32(),
30
+ vaultRef: `vault://${hex()}`,
31
+ pageApiKey,
32
+ pageSigningKey,
33
+ pageToken,
34
+ pageUrl: `https://example.test/account?api_key=${pageApiKey}&signingKey=${pageSigningKey}&token=${pageToken}&page=2`,
35
+ };
36
+ }
37
+ /** The exact values a host registers with `redact.values()`; never provider keys, which the shapes cover. */
38
+ export const hostRegistered = (s) => [s.runToken, s.brokerCapability];