effect-browserbase 0.2.0-beta.9 → 0.3.0-beta.5

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 (155) hide show
  1. package/README.md +250 -317
  2. package/dist/Browserbase-FDltiz36.mjs +542 -0
  3. package/dist/Browserbase-FDltiz36.mjs.map +1 -0
  4. package/dist/Browserbase.d.mts +105 -0
  5. package/dist/Browserbase.mjs +3 -0
  6. package/dist/BrowserbaseClient-CtAQ2rg4.d.mts +195 -0
  7. package/dist/BrowserbaseClient.d.mts +2 -0
  8. package/dist/BrowserbaseClient.mjs +190 -0
  9. package/dist/BrowserbaseClient.mjs.map +1 -0
  10. package/dist/BrowserbaseError-D1EOrLNc.d.mts +79 -0
  11. package/dist/BrowserbaseError.d.mts +2 -0
  12. package/dist/BrowserbaseError.mjs +101 -0
  13. package/dist/BrowserbaseError.mjs.map +1 -0
  14. package/dist/ContextLease.d.mts +42 -0
  15. package/dist/ContextLease.mjs +80 -0
  16. package/dist/ContextLease.mjs.map +1 -0
  17. package/dist/index.d.mts +5 -27
  18. package/dist/index.mjs +5 -26
  19. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  20. package/dist/testing/index.d.mts +134 -0
  21. package/dist/testing/index.mjs +382 -0
  22. package/dist/testing/index.mjs.map +1 -0
  23. package/package.json +51 -121
  24. package/src/Browserbase.ts +698 -0
  25. package/src/BrowserbaseClient.ts +559 -0
  26. package/src/BrowserbaseError.ts +108 -0
  27. package/src/ContextLease.ts +118 -0
  28. package/src/index.ts +7 -0
  29. package/src/internal/captureConnection.ts +214 -0
  30. package/src/testing/BrowserbaseContract.ts +170 -0
  31. package/src/testing/TestBrowserbase.ts +445 -0
  32. package/src/testing/index.ts +7 -0
  33. package/dist/Account.d.mts +0 -32
  34. package/dist/Account.mjs +0 -36
  35. package/dist/Account.mjs.map +0 -1
  36. package/dist/Acquisition-BOABu_qJ.mjs +0 -244
  37. package/dist/Acquisition-BOABu_qJ.mjs.map +0 -1
  38. package/dist/Agents-CPaTOH_g.d.mts +0 -156
  39. package/dist/Agents.d.mts +0 -3
  40. package/dist/Agents.mjs +0 -292
  41. package/dist/Agents.mjs.map +0 -1
  42. package/dist/Allocation.d.mts +0 -97
  43. package/dist/Allocation.mjs +0 -27
  44. package/dist/Allocation.mjs.map +0 -1
  45. package/dist/Authorization-Ll5f_XNM.mjs +0 -12
  46. package/dist/Authorization-Ll5f_XNM.mjs.map +0 -1
  47. package/dist/Browser-ByrWJ0ss.mjs +0 -274
  48. package/dist/Browser-ByrWJ0ss.mjs.map +0 -1
  49. package/dist/Browser.d.mts +0 -83
  50. package/dist/Browser.mjs +0 -3
  51. package/dist/BrowserBinding.d.mts +0 -13
  52. package/dist/BrowserBinding.mjs +0 -31
  53. package/dist/BrowserBinding.mjs.map +0 -1
  54. package/dist/Certificates-D4NQmyeA.d.mts +0 -34
  55. package/dist/Certificates.d.mts +0 -3
  56. package/dist/Certificates.mjs +0 -85
  57. package/dist/Certificates.mjs.map +0 -1
  58. package/dist/Cleanup-DMTDBir8.d.mts +0 -23
  59. package/dist/Cleanup.d.mts +0 -3
  60. package/dist/Cleanup.mjs +0 -43
  61. package/dist/Cleanup.mjs.map +0 -1
  62. package/dist/Client-BEC4Q8ZS.mjs +0 -564
  63. package/dist/Client-BEC4Q8ZS.mjs.map +0 -1
  64. package/dist/Client-B_f6bBLT.d.mts +0 -52
  65. package/dist/Client.d.mts +0 -3
  66. package/dist/Client.mjs +0 -2
  67. package/dist/Connection-sxyxtwlk.mjs +0 -56
  68. package/dist/Connection-sxyxtwlk.mjs.map +0 -1
  69. package/dist/ContextCoordination.d.mts +0 -29
  70. package/dist/ContextCoordination.mjs +0 -94
  71. package/dist/ContextCoordination.mjs.map +0 -1
  72. package/dist/ContextWriter-CiEma24z.mjs +0 -204
  73. package/dist/ContextWriter-CiEma24z.mjs.map +0 -1
  74. package/dist/Contexts-DqdL7cyX.d.mts +0 -31
  75. package/dist/Contexts.d.mts +0 -3
  76. package/dist/Contexts.mjs +0 -97
  77. package/dist/Contexts.mjs.map +0 -1
  78. package/dist/Deadline-CrViaogr.mjs +0 -13
  79. package/dist/Deadline-CrViaogr.mjs.map +0 -1
  80. package/dist/Downloads-CX52GOFJ.d.mts +0 -43
  81. package/dist/Downloads.d.mts +0 -3
  82. package/dist/Downloads.mjs +0 -137
  83. package/dist/Downloads.mjs.map +0 -1
  84. package/dist/Errors.d.mts +0 -100
  85. package/dist/Errors.mjs +0 -194
  86. package/dist/Errors.mjs.map +0 -1
  87. package/dist/Extensions-BTUn9zhK.mjs +0 -231
  88. package/dist/Extensions-BTUn9zhK.mjs.map +0 -1
  89. package/dist/Extensions-DBXuVM1f.d.mts +0 -43
  90. package/dist/Extensions.d.mts +0 -3
  91. package/dist/Extensions.mjs +0 -2
  92. package/dist/Functions-CsKMMUuZ.d.mts +0 -226
  93. package/dist/Functions.d.mts +0 -3
  94. package/dist/Functions.mjs +0 -318
  95. package/dist/Functions.mjs.map +0 -1
  96. package/dist/Issued-DejqoMYL.mjs +0 -15
  97. package/dist/Issued-DejqoMYL.mjs.map +0 -1
  98. package/dist/Launch-cAdE2rrZ.mjs +0 -115
  99. package/dist/Launch-cAdE2rrZ.mjs.map +0 -1
  100. package/dist/Launch.d.mts +0 -127
  101. package/dist/Launch.mjs +0 -97
  102. package/dist/Launch.mjs.map +0 -1
  103. package/dist/PageFetch-CjAM_0DS.d.mts +0 -40
  104. package/dist/PageFetch.d.mts +0 -3
  105. package/dist/PageFetch.mjs +0 -59
  106. package/dist/PageFetch.mjs.map +0 -1
  107. package/dist/Projects-tm5bTDH0.d.mts +0 -38
  108. package/dist/Projects.d.mts +0 -3
  109. package/dist/Projects.mjs +0 -65
  110. package/dist/Projects.mjs.map +0 -1
  111. package/dist/Recordings-B9k5aODB.d.mts +0 -27
  112. package/dist/Recordings.d.mts +0 -3
  113. package/dist/Recordings.mjs +0 -144
  114. package/dist/Recordings.mjs.map +0 -1
  115. package/dist/References-DOH3Wu44.d.mts +0 -34
  116. package/dist/References.d.mts +0 -3
  117. package/dist/References.mjs +0 -33
  118. package/dist/References.mjs.map +0 -1
  119. package/dist/Replays-mV93WGtx.d.mts +0 -27
  120. package/dist/Replays.d.mts +0 -3
  121. package/dist/Replays.mjs +0 -107
  122. package/dist/Replays.mjs.map +0 -1
  123. package/dist/Resource-J7Kkk5mu.mjs +0 -54
  124. package/dist/Resource-J7Kkk5mu.mjs.map +0 -1
  125. package/dist/Search-B64e7g-h.d.mts +0 -37
  126. package/dist/Search.d.mts +0 -3
  127. package/dist/Search.mjs +0 -46
  128. package/dist/Search.mjs.map +0 -1
  129. package/dist/SessionData-5xYZDshJ.d.mts +0 -38
  130. package/dist/SessionData.d.mts +0 -3
  131. package/dist/SessionData.mjs +0 -48
  132. package/dist/SessionData.mjs.map +0 -1
  133. package/dist/Sessions-D2H5m6rF.mjs +0 -260
  134. package/dist/Sessions-D2H5m6rF.mjs.map +0 -1
  135. package/dist/Sessions-oJEUmZth.d.mts +0 -69
  136. package/dist/Sessions.d.mts +0 -4
  137. package/dist/Sessions.mjs +0 -3
  138. package/dist/Testing.d.mts +0 -119
  139. package/dist/Testing.mjs +0 -206
  140. package/dist/Testing.mjs.map +0 -1
  141. package/dist/TransferPolicy-DQ06i7SZ.mjs +0 -25
  142. package/dist/TransferPolicy-DQ06i7SZ.mjs.map +0 -1
  143. package/dist/Transfers-GVqzrDWl.d.mts +0 -89
  144. package/dist/Transfers.d.mts +0 -3
  145. package/dist/Transfers.mjs +0 -85
  146. package/dist/Transfers.mjs.map +0 -1
  147. package/dist/Uploads-C2_bACgv.d.mts +0 -28
  148. package/dist/Uploads.d.mts +0 -3
  149. package/dist/Uploads.mjs +0 -105
  150. package/dist/Uploads.mjs.map +0 -1
  151. package/dist/Webhooks-BoeRAxzG.d.mts +0 -59
  152. package/dist/Webhooks.d.mts +0 -3
  153. package/dist/Webhooks.mjs +0 -134
  154. package/dist/Webhooks.mjs.map +0 -1
  155. package/dist/WriterFacts-BBJRDZYY.d.mts +0 -54
@@ -0,0 +1,698 @@
1
+ /**
2
+ * A `Browser` running on Browserbase.
3
+ *
4
+ * `open` creates a session and connects to it over CDP. When its scope closes it disconnects,
5
+ * releases the session and confirms that Browserbase reports it ended, so billing stops then
6
+ * rather than at the session's timeout. `release` does the same sooner and says how it went:
7
+ * `Settled`, or `Unconfirmed` when Browserbase still reported the session running, or could not
8
+ * be asked, at the deadline. Each create carries a nonce of its own in its user metadata, so a
9
+ * session made by a create whose answer was lost is found and ended too, rather than billing
10
+ * unseen until its timeout.
11
+ *
12
+ * A session that persists to a stored context saves to it when the session ends, so two at once
13
+ * can lose one's changes. `open` holds the context through the `ContextLease` the application
14
+ * provides, from before it creates such a session until Browserbase reports the session ended and
15
+ * `contextSettle` has passed, since the save lands later and nothing acknowledges it. A writer that
16
+ * leaves a session that saves to the context possibly running, its release `Unconfirmed`, its
17
+ * create's answer lost or its session kept, leaves the context unsettled: the next writer first ends
18
+ * the context's sessions, which `open` labels in their user metadata, and fails with `ContextHeld`
19
+ * while they can't be confirmed ended. `reconcile` ends them without opening, and `verifyContext`
20
+ * reads a context back under the same hold, from a session that saves nothing.
21
+ *
22
+ * `attach` connects to a session that already runs, as from another process: its pages keep their
23
+ * ids, so a page stored before is found again. `supervise` keeps a session open across losses and
24
+ * session ends, as `Supervisor` generations, and with `keep`, past its own scope, for the next
25
+ * `supervise` to adopt.
26
+ *
27
+ * @since 0.3.0
28
+ */
29
+ import {
30
+ DateTime,
31
+ Duration,
32
+ Effect,
33
+ Exit,
34
+ Layer,
35
+ Option,
36
+ Random,
37
+ Redacted,
38
+ Schedule,
39
+ Scope,
40
+ } from "effect";
41
+ import * as Browser from "effect-browser/Browser";
42
+ import { BrowserError, Closed } from "effect-browser/BrowserError";
43
+ import * as Cdp from "effect-browser/Cdp";
44
+ import * as Supervisor from "effect-browser/Supervisor";
45
+
46
+ import {
47
+ BrowserbaseClient,
48
+ type Service,
49
+ type Session,
50
+ type SessionOptions,
51
+ } from "./BrowserbaseClient.ts";
52
+ import { BrowserbaseError, Decode, InvalidRequest, isTransient } from "./BrowserbaseError.ts";
53
+ import { ContextHeld, ContextLease } from "./ContextLease.ts";
54
+ import * as CaptureConnection from "./internal/captureConnection.ts";
55
+
56
+ export interface Options extends Browser.Options {
57
+ readonly session?: SessionOptions | undefined;
58
+ /** Bound on connecting to the session. Defaults to 30 seconds. */
59
+ readonly connectTimeoutMillis?: number | undefined;
60
+ /**
61
+ * How long a persisting session's context stays held after the session ends, for its save to
62
+ * land. Defaults to 10 seconds, after which hosted checks have read a save back.
63
+ */
64
+ readonly contextSettle?: Duration.Input | undefined;
65
+ /**
66
+ * Run the pages' screencasts on a second connection to the session, which carries nothing else,
67
+ * so that a frame never waits behind a large message, such as an upload or a read's answer, on
68
+ * the connection that drives the page. Defaults to true.
69
+ */
70
+ readonly captureConnection?: boolean | undefined;
71
+ }
72
+
73
+ /** A browser on a Browserbase session. */
74
+ export interface Hosted {
75
+ readonly browser: Browser.Service;
76
+ readonly session: Session;
77
+ /**
78
+ * Release the session and confirm it ended, once: `open`'s scope runs it as it closes, while
79
+ * `attach`'s only disconnects. It disconnects `browser` first, which is lost as `released`, so a
80
+ * call in flight or a capture's reader is told so. Asked again, it reports the same outcome.
81
+ */
82
+ readonly release: Effect.Effect<Supervisor.Released>;
83
+ }
84
+
85
+ /** The user metadata key naming the stored context a persisting session writes to. */
86
+ const contextLabel = "persistsContext";
87
+
88
+ /** The user metadata key holding each create's own nonce, which finds a session made unseen. */
89
+ const createLabel = "createNonce";
90
+
91
+ /** The user metadata key naming what a supervisor keeps its sessions under, past its scope. */
92
+ const keepLabel = "keptAs";
93
+
94
+ /**
95
+ * How long a create whose answer was lost has its session looked for: Browserbase can list a new
96
+ * session late, or still be making it when the client stops waiting.
97
+ */
98
+ const orphanSearch = Duration.seconds(30);
99
+
100
+ /** How long a release waits for Browserbase to report the session ended. */
101
+ const releaseDeadline = Duration.minutes(1);
102
+
103
+ const ended = (session: Session) => session.status !== "PENDING" && session.status !== "RUNNING";
104
+
105
+ /**
106
+ * End the session and confirm Browserbase reports it ended. The release request and the status
107
+ * reads are each tried again a second apart until the deadline; a session still running then, or
108
+ * one Browserbase could not be asked about, is `Unconfirmed`. Once it has ended, wait `settle`
109
+ * longer, for its context's save to land. It runs to the end once started.
110
+ */
111
+ const confirm = (client: Service, id: string, settle: Duration.Duration | undefined) =>
112
+ Effect.gen(function* () {
113
+ // What Browserbase last said, for an end it never confirmed.
114
+ let last = "Browserbase did not answer";
115
+
116
+ const heard = (error: BrowserbaseError) => Effect.sync(() => (last = error.message));
117
+
118
+ const read = client.getSession(id).pipe(
119
+ Effect.tapError(heard),
120
+ Effect.tap((session) => Effect.sync(() => (last = `the session was ${session.status}`))),
121
+ Effect.retry(Schedule.spaced("1 second")),
122
+ Effect.repeat({ until: ended, schedule: Schedule.spaced("1 second") }),
123
+ );
124
+
125
+ // A release that keeps failing leaves the status reads to tell whether the session ended.
126
+ const confirmed = yield* client.releaseSession(id).pipe(
127
+ Effect.tapError(heard),
128
+ Effect.retry({ while: isTransient, schedule: Schedule.spaced("1 second") }),
129
+ Effect.exit,
130
+ Effect.andThen(read),
131
+ Effect.as(true),
132
+ Effect.timeoutOrElse({ duration: releaseDeadline, orElse: () => Effect.succeed(false) }),
133
+ // The reads are retried until the deadline, so a failure here is the same unconfirmed end.
134
+ Effect.orElseSucceed(() => false),
135
+ );
136
+
137
+ if (!confirmed)
138
+ return new Supervisor.Unconfirmed({
139
+ detail: `${last} ${Duration.format(releaseDeadline)} after its release`,
140
+ });
141
+ if (settle !== undefined) yield* Effect.sleep(settle);
142
+
143
+ return new Supervisor.Settled();
144
+ }).pipe(
145
+ Effect.tap((released) => Effect.annotateCurrentSpan({ released: released._tag })),
146
+ Effect.withSpan(
147
+ "Browserbase.release",
148
+ { attributes: { session: id, settle: settle !== undefined } },
149
+ { captureStackTrace: false },
150
+ ),
151
+ Effect.uninterruptible,
152
+ );
153
+
154
+ /** A search for the sessions with `value` under the user metadata key `label`. */
155
+ const labelled = (label: string, value: string) => `user_metadata['${label}']:'${value}'`;
156
+
157
+ /**
158
+ * The sessions a search finds that have not ended. Pending ones are listed first, since one listed
159
+ * as pending may be running by the second query.
160
+ */
161
+ const unended = (client: Service, query: string) =>
162
+ Effect.forEach(["PENDING", "RUNNING"], (status) => client.listSessions({ status, query })).pipe(
163
+ Effect.map((found) => [
164
+ ...new Map(found.flat().map((session) => [session.id, session])).values(),
165
+ ]),
166
+ );
167
+
168
+ /**
169
+ * End the sessions and confirm they ended; then wait `settle`, if given, for the last save to land.
170
+ * One still running at its release's deadline makes the outcome `Unconfirmed`.
171
+ */
172
+ const endAll = (
173
+ client: Service,
174
+ sessions: ReadonlyArray<string>,
175
+ settle: Duration.Duration | undefined,
176
+ ) =>
177
+ Effect.forEach(sessions, (session) => confirm(client, session, undefined), {
178
+ concurrency: 4,
179
+ }).pipe(
180
+ Effect.flatMap((outcomes) => {
181
+ const unconfirmed = outcomes.find((outcome) => outcome._tag === "Unconfirmed");
182
+
183
+ return unconfirmed === undefined
184
+ ? Effect.sleep(settle ?? Duration.zero).pipe(
185
+ Effect.as<Supervisor.Released>(new Supervisor.Settled()),
186
+ )
187
+ : Effect.succeed<Supervisor.Released>(unconfirmed);
188
+ }),
189
+ );
190
+
191
+ /**
192
+ * End the session a create may have made though its answer was lost, found in any state by the
193
+ * create's own label, and then wait `settle`, if given, for its save. Browserbase can list a new
194
+ * session late, so it is looked for again, more and more seldom, until it is found or
195
+ * `orphanSearch` has passed. A search Browserbase never answered is `Unconfirmed`, as is a session
196
+ * still running at its release's deadline.
197
+ */
198
+ const endOrphan = (client: Service, nonce: string, settle: Duration.Duration | undefined) =>
199
+ Effect.gen(function* () {
200
+ let answered = false;
201
+
202
+ const found = yield* client.listSessions({ query: labelled(createLabel, nonce) }).pipe(
203
+ Effect.tap(() =>
204
+ Effect.sync(() => {
205
+ answered = true;
206
+ }),
207
+ ),
208
+ Effect.retry(Schedule.exponential("1 second")),
209
+ Effect.repeat({
210
+ schedule: Schedule.exponential("1 second"),
211
+ until: (sessions) => sessions.length > 0,
212
+ }),
213
+ Effect.timeoutOption(orphanSearch),
214
+ );
215
+
216
+ if (Option.isNone(found) && !answered)
217
+ return new Supervisor.Unconfirmed({
218
+ detail: `Browserbase did not answer a search for it within ${Duration.format(orphanSearch)}`,
219
+ });
220
+ const running = Option.getOrElse(found, () => []).filter((session) => !ended(session));
221
+
222
+ return yield* endAll(
223
+ client,
224
+ running.map((session) => session.id),
225
+ settle,
226
+ );
227
+ });
228
+
229
+ /**
230
+ * Hold the stored context through the lease, as its only writer, until the scope closes or the
231
+ * session's end is known; the hold goes once, saying how this writer leaves the context.
232
+ */
233
+ const holdContext = Effect.fnUntraced(function* (
234
+ client: Service,
235
+ lease: ContextLease["Service"],
236
+ id: string,
237
+ settle: Duration.Duration,
238
+ ) {
239
+ const scope = yield* Scope.fork(yield* Effect.scope);
240
+
241
+ // A second writer waits here for the first one's whole session and the save after it.
242
+ const hold = yield* lease
243
+ .hold(id)
244
+ .pipe(
245
+ Scope.provide(scope),
246
+ Effect.withSpan("Browserbase.holdContext", {}, { captureStackTrace: false }),
247
+ );
248
+
249
+ // Whether a session that saves to the context may run, as this writer would leave it now.
250
+ let unsettled = hold.unsettled;
251
+
252
+ const set = (now: boolean) =>
253
+ Effect.sync(() => {
254
+ unsettled = now;
255
+ });
256
+
257
+ yield* Scope.addFinalizer(
258
+ scope,
259
+ Effect.suspend(() => hold.leave(unsettled)),
260
+ );
261
+
262
+ const letGo = (now: boolean) => set(now).pipe(Effect.andThen(Scope.close(scope, Exit.void)));
263
+
264
+ /** End the context's sessions but `except`, found by the label `open` gives them. */
265
+ const end = (except: ReadonlyArray<string>) =>
266
+ unended(client, labelled(contextLabel, id)).pipe(
267
+ Effect.flatMap((found) =>
268
+ endAll(
269
+ client,
270
+ found.map((session) => session.id).filter((session) => !except.includes(session)),
271
+ settle,
272
+ ),
273
+ ),
274
+ Effect.onExit((exit) => set(!(Exit.isSuccess(exit) && exit.value._tag === "Settled"))),
275
+ );
276
+
277
+ const refuse = (outcome: Supervisor.Released) =>
278
+ outcome._tag === "Settled"
279
+ ? Effect.void
280
+ : Effect.fail(new ContextHeld({ context: id, detail: outcome.detail }));
281
+
282
+ return {
283
+ end,
284
+ /**
285
+ * End the sessions, but `except`, that a writer before may have left saving to the context,
286
+ * failing with `ContextHeld` while they can't be confirmed ended.
287
+ */
288
+ clear: (except: ReadonlyArray<string>) =>
289
+ Effect.suspend(() => (unsettled ? Effect.flatMap(end(except), refuse) : Effect.void)),
290
+ /** A session that saves to the context runs from now. */
291
+ writing: set(true),
292
+ /** How the writer's session ended: unconfirmed, it may still save to the context. */
293
+ released: (outcome: Supervisor.Released) => letGo(outcome._tag === "Unconfirmed"),
294
+ /** How ending the session a lost create may have made went: unconfirmed, the open fails. */
295
+ lost: (outcome: Supervisor.Released) =>
296
+ letGo(outcome._tag === "Unconfirmed").pipe(Effect.andThen(refuse(outcome))),
297
+ /** The writer's session runs on past its scope, saving to the context when it ends. */
298
+ kept: letGo(true),
299
+ };
300
+ });
301
+
302
+ /** A create that failed so may still have made its session: its answer is lost or unreadable. */
303
+ const mayHaveCreated = (error: BrowserbaseError) =>
304
+ error.reason._tag === "Transport" ||
305
+ error.reason._tag === "Decode" ||
306
+ (error.reason._tag === "Status" && (error.reason.status >= 500 || error.reason.status === 408));
307
+
308
+ /** A create's own nonce: two random draws, which no other create draws in practice. */
309
+ const nonce = Effect.map(Effect.all([Random.nextInt, Random.nextInt]), (draws) =>
310
+ draws.map((draw) => Math.abs(draw).toString(36)).join("-"),
311
+ );
312
+
313
+ /**
314
+ * The create request, labelled with its own nonce, a persisting session with its context too, so
315
+ * either can be found, and a kept one with what it is kept under, kept alive past disconnecting.
316
+ */
317
+ const withLabels = (
318
+ session: SessionOptions | undefined,
319
+ own: string,
320
+ context: string | undefined,
321
+ keep: string | undefined,
322
+ ) => ({
323
+ ...session,
324
+ ...(keep === undefined ? {} : { keepAlive: true }),
325
+ userMetadata: {
326
+ ...session?.userMetadata,
327
+ [createLabel]: own,
328
+ ...(context === undefined ? {} : { [contextLabel]: context }),
329
+ ...(keep === undefined ? {} : { [keepLabel]: keep }),
330
+ },
331
+ });
332
+
333
+ /**
334
+ * A release by the browser's owner: it closes the browser first, so that whatever fails then, a
335
+ * capture's reader or a call in flight, says the session was released, and not that the
336
+ * connection Browserbase cuts as the session ends was lost.
337
+ */
338
+ const releasing = (browser: Scope.Closeable, end: Effect.Effect<Supervisor.Released>) =>
339
+ Scope.close(browser, Exit.void).pipe(Effect.andThen(end));
340
+
341
+ /**
342
+ * A browser over the session's DevTools address, its pages' screencasts on a capture connection of
343
+ * their own. A DevTools server's HTTP address, as a local Chromium gives in tests, keeps them on
344
+ * each page's own session: there the connection is loopback, and fast. A session that has ended
345
+ * fails `Closed` by the session, with no connect.
346
+ */
347
+ const connect = Effect.fnUntraced(function* (
348
+ operation: string,
349
+ session: Session,
350
+ options: Options,
351
+ ) {
352
+ const endpoint = session.connectUrl;
353
+
354
+ if (ended(session))
355
+ return yield* new BrowserError({
356
+ operation,
357
+ reason: new Closed({ cause: "session" }),
358
+ dispatched: false,
359
+ });
360
+ if (endpoint === undefined)
361
+ return yield* new BrowserbaseError({
362
+ operation,
363
+ reason: new Decode({ detail: `session ${session.id} has no connectUrl` }),
364
+ });
365
+ const apart = options.captureConnection !== false && /^wss?:/i.test(Redacted.value(endpoint));
366
+
367
+ return yield* Cdp.open({
368
+ ...options,
369
+ endpoint,
370
+ id: session.id,
371
+ provider: "browserbase",
372
+ expiresAt: Option.getOrUndefined(DateTime.make(session.expiresAt)),
373
+ capture: apart ? yield* CaptureConnection.make(endpoint) : undefined,
374
+ });
375
+ });
376
+
377
+ /** How a supervisor keeps its sessions past its scope: under `name`, adopting one first if `adopt`. */
378
+ interface Keeping {
379
+ readonly name: string;
380
+ readonly adopt: boolean;
381
+ }
382
+
383
+ const keepName = /^[\w.:-]{1,64}$/;
384
+
385
+ const newestFirst = (sessions: ReadonlyArray<Session>) => {
386
+ const created = (session: Session) =>
387
+ Option.getOrElse(Option.map(DateTime.make(session.createdAt), DateTime.toEpochMillis), () => 0);
388
+
389
+ return sessions.toSorted((a, b) => created(b) - created(a));
390
+ };
391
+
392
+ /**
393
+ * The newest session kept under `name` that saves where this open would, to adopt. Every other
394
+ * session kept under it is to end, since nothing else adopts it: those that save to this open's
395
+ * context are its writers, for the context's hold to end, as `writers` says, and the rest end here.
396
+ */
397
+ const adoptable = Effect.fnUntraced(function* (
398
+ client: Service,
399
+ name: string,
400
+ persisting: string | undefined,
401
+ ) {
402
+ const [newest, ...older] = newestFirst(yield* unended(client, labelled(keepLabel, name)));
403
+ const fits = newest !== undefined && newest.userMetadata?.[contextLabel] === persisting;
404
+ const others = [...(fits || newest === undefined ? [] : [newest]), ...older];
405
+
406
+ const writes = (session: Session) =>
407
+ persisting !== undefined && session.userMetadata?.[contextLabel] === persisting;
408
+
409
+ const rest = others.filter((session) => !writes(session));
410
+
411
+ if (rest.length > 0) {
412
+ const outcome = yield* endAll(
413
+ client,
414
+ rest.map((session) => session.id),
415
+ undefined,
416
+ );
417
+
418
+ yield* Effect.annotateCurrentSpan({ endedKept: rest.length, endedKeptAs: outcome._tag });
419
+ }
420
+
421
+ return { adoptee: fits ? newest : undefined, writers: others.some(writes) };
422
+ });
423
+
424
+ /**
425
+ * Open a browser on a new session, or, when keeping, adopt one a supervisor kept before. A kept
426
+ * session's scope only disconnects, unless it closes on a failure: `release` ends it.
427
+ */
428
+ const start = Effect.fnUntraced(function* (options: Options, keeping: Keeping | undefined) {
429
+ const client = yield* BrowserbaseClient;
430
+ const lease = yield* ContextLease;
431
+ const context = options.session?.browserSettings?.context;
432
+ const persisting = context?.persist === true ? context.id : undefined;
433
+ const local = yield* Scope.fork(yield* Effect.scope);
434
+ const settle = Duration.fromInputUnsafe(options.contextSettle ?? Duration.seconds(10));
435
+
436
+ return yield* Effect.gen(function* () {
437
+ if (keeping !== undefined && !keepName.test(keeping.name))
438
+ return yield* new BrowserbaseError({
439
+ operation: "supervise",
440
+ reason: new InvalidRequest({
441
+ detail: `keep must be 1 to 64 letters, digits, "_", ".", ":" or "-"`,
442
+ }),
443
+ });
444
+
445
+ const writing =
446
+ persisting === undefined ? undefined : yield* holdContext(client, lease, persisting, settle);
447
+
448
+ const adoption = keeping?.adopt
449
+ ? yield* adoptable(client, keeping.name, persisting)
450
+ : undefined;
451
+
452
+ const adopted = adoption?.adoptee;
453
+
454
+ // Another writer kept under the name may still save to the context: clear it as any other.
455
+ if (adoption?.writers === true) yield* writing?.writing ?? Effect.void;
456
+ yield* writing?.clear(adopted === undefined ? [] : [adopted.id]) ?? Effect.void;
457
+ const connected = yield* Scope.fork(local);
458
+ const own = yield* nonce;
459
+
460
+ // Releasing ends the session; leaving, as a kept session's scope does, only disconnects.
461
+ const ending = (session: Session) =>
462
+ Effect.gen(function* () {
463
+ let asked = false;
464
+
465
+ const release = yield* Effect.cached(
466
+ Effect.suspend(() => {
467
+ asked = true;
468
+
469
+ return releasing(connected, confirm(client, session.id, writing && settle)).pipe(
470
+ Effect.tap((outcome) => writing?.released(outcome) ?? Effect.void),
471
+ );
472
+ }),
473
+ );
474
+
475
+ const leave = Effect.suspend(() =>
476
+ asked
477
+ ? Effect.void
478
+ : Scope.close(connected, Exit.void).pipe(Effect.andThen(writing?.kept ?? Effect.void)),
479
+ );
480
+
481
+ return { session, release, leave };
482
+ });
483
+
484
+ const made = yield* Effect.acquireRelease(
485
+ Effect.gen(function* () {
486
+ const session =
487
+ adopted === undefined
488
+ ? yield* client.createSession(
489
+ withLabels(options.session, own, persisting, keeping?.name),
490
+ )
491
+ : yield* client.getSession(adopted.id);
492
+
493
+ yield* writing?.writing ?? Effect.void;
494
+
495
+ return yield* ending(session);
496
+ }),
497
+ ({ release, leave }, exit) =>
498
+ keeping !== undefined && Exit.isSuccess(exit) ? leave : Effect.asVoid(release),
499
+ ).pipe(
500
+ // A session nobody can see bills until its timeout, and one that saves to the context would
501
+ // write beside the next writer: end it, found by its create's own label.
502
+ Effect.tapError((error) =>
503
+ adopted === undefined && mayHaveCreated(error)
504
+ ? endOrphan(client, own, writing && settle).pipe(
505
+ Effect.flatMap((outcome) => writing?.lost(outcome) ?? Effect.void),
506
+ )
507
+ : Effect.void,
508
+ ),
509
+ );
510
+
511
+ const { session, release } = made;
512
+
513
+ yield* Effect.annotateCurrentSpan({
514
+ session: session.id,
515
+ region: session.region,
516
+ adopted: adopted !== undefined,
517
+ });
518
+
519
+ const browser = yield* connect(
520
+ adopted === undefined ? "open" : "attach",
521
+ session,
522
+ options,
523
+ ).pipe(Scope.provide(connected));
524
+
525
+ return { browser, session, release } satisfies Hosted;
526
+ }).pipe(
527
+ Scope.provide(local),
528
+ Effect.onError((cause) => Scope.close(local, Exit.failCause(cause))),
529
+ );
530
+ });
531
+
532
+ /**
533
+ * Create a session and open a `Browser` on it, for as long as the scope is open. If opening
534
+ * fails, the session and context are released then, so a retry in the same scope can take them.
535
+ * A persisting open holds its context through the `ContextLease`; a session that may still save
536
+ * to it, as one whose release was left `Unconfirmed` or whose create's answer was lost, is ended
537
+ * first, and the open fails with `ContextHeld` while that can't be confirmed. A lost create's own
538
+ * open looks for its session by the create's nonce, within `orphanSearch`, ends it, then fails with
539
+ * the create's error. `release` disconnects the browser before it asks Browserbase to end the
540
+ * session, so what fails meanwhile says it was released.
541
+ */
542
+ export const open = Effect.fn("Browserbase.open")(function* (options: Options = {}) {
543
+ return yield* start(options, undefined);
544
+ });
545
+
546
+ /**
547
+ * Open a `Browser` on a session that already runs, such as a `keepAlive` session another process
548
+ * opened. This is resume: its pages keep their ids, their CDP target ids, so `browser.page(id)`
549
+ * finds a page stored before. Closing the scope disconnects and leaves the session running;
550
+ * `release` ends it. A session that has ended fails `Closed` by the session. It holds no context.
551
+ */
552
+ export const attach = Effect.fn("Browserbase.attach")(function* (
553
+ sessionId: string,
554
+ options: Options = {},
555
+ ) {
556
+ const client = yield* BrowserbaseClient;
557
+ const session = yield* client.getSession(sessionId);
558
+
559
+ yield* Effect.annotateCurrentSpan({ session: session.id, region: session.region });
560
+
561
+ const connected = yield* Scope.fork(yield* Effect.scope);
562
+ const browser = yield* connect("attach", session, options).pipe(Scope.provide(connected));
563
+
564
+ const release = yield* Effect.cached(
565
+ releasing(connected, confirm(client, session.id, undefined)),
566
+ );
567
+
568
+ return { browser, session, release } satisfies Hosted;
569
+ });
570
+
571
+ /**
572
+ * End a stored context's sessions, the ones `open` labelled as writing to it, and let the context
573
+ * go once they are confirmed ended and its save has settled. `open` does this itself when a writer
574
+ * before it may still run; `reconcile` does it without opening, as for sessions another process
575
+ * left running. It holds the context through the `ContextLease`, so it waits for a writer. A
576
+ * session still running at the deadline makes it `Unconfirmed`, and leaves the context unsettled,
577
+ * as a failure does.
578
+ */
579
+ export const reconcile = Effect.fn("Browserbase.reconcile")(function* (
580
+ contextId: string,
581
+ options: { readonly contextSettle?: Duration.Input | undefined } = {},
582
+ ) {
583
+ const client = yield* BrowserbaseClient;
584
+ const lease = yield* ContextLease;
585
+ const settle = Duration.fromInputUnsafe(options.contextSettle ?? Duration.seconds(10));
586
+
587
+ // Reading the context first refuses an id that is not one before it reaches the query.
588
+ yield* client.getContext(contextId);
589
+ const hold = yield* holdContext(client, lease, contextId, settle);
590
+
591
+ return yield* hold.end([]);
592
+ }, Effect.scoped);
593
+
594
+ /**
595
+ * Read a stored context back, as a login: a session that loads it and saves nothing runs `check`
596
+ * on its browser, and is released. The context is held through the `ContextLease` meanwhile, so
597
+ * the read never runs beside a writer, which a site could sign out, and it reads what the last
598
+ * writer saved, once that save settled. A session a writer before may have left saving to it is
599
+ * ended first, as for `open`.
600
+ */
601
+ export const verifyContext = Effect.fn("Browserbase.verifyContext")(function* <A, E, R>(
602
+ contextId: string,
603
+ check: (browser: Browser.Service) => Effect.Effect<A, E, R>,
604
+ options: Options = {},
605
+ ) {
606
+ const client = yield* BrowserbaseClient;
607
+ const lease = yield* ContextLease;
608
+ const settle = Duration.fromInputUnsafe(options.contextSettle ?? Duration.seconds(10));
609
+ const reading = yield* holdContext(client, lease, contextId, settle);
610
+
611
+ yield* reading.clear([]);
612
+
613
+ const { browser } = yield* start(
614
+ {
615
+ ...options,
616
+ session: {
617
+ ...options.session,
618
+ browserSettings: {
619
+ ...options.session?.browserSettings,
620
+ context: { id: contextId, persist: false },
621
+ },
622
+ },
623
+ },
624
+ undefined,
625
+ );
626
+
627
+ return yield* check(browser);
628
+ }, Effect.scoped);
629
+
630
+ export interface SuperviseOptions
631
+ extends
632
+ Options,
633
+ Pick<
634
+ Supervisor.Options<BrowserError | BrowserbaseError | ContextHeld, BrowserbaseClient>,
635
+ "reopen" | "rotateBefore" | "waitTimeout"
636
+ > {
637
+ /**
638
+ * Keep the session past the supervisor's scope, under this name: 1 to 64 letters, digits, `_`,
639
+ * `.`, `:` or `-`. Each session is created with `keepAlive` and labelled `keptAs: <keep>` in its
640
+ * user metadata. Closing the scope only disconnects the current one, published as `Kept`, and
641
+ * the first generation of the next `supervise` under the same name adopts it, with its pages,
642
+ * rather than creating a session; other sessions kept under it are ended. `retire` releases. A
643
+ * kept session bills until it is adopted and released, or until its timeout ends it.
644
+ */
645
+ readonly keep?: string | undefined;
646
+ }
647
+
648
+ /**
649
+ * Browserbase refused the request: no new try mends a refused key, request or id. A context held
650
+ * is not among them, since each try ends its sessions again.
651
+ */
652
+ const refused = (error: BrowserError | BrowserbaseError | ContextHeld) =>
653
+ error._tag === "BrowserbaseError" && !isTransient(error) && error.reason._tag !== "Decode";
654
+
655
+ /**
656
+ * Keep Browserbase sessions open as `Supervisor` generations, each a new session made from
657
+ * `session`. Sessions that persist to a stored context are exclusive: a rotation releases the
658
+ * current one, and its context's save settles, before the next one opens. An open Browserbase
659
+ * refused, as for a bad key or an invalid request, is `Down` at once. With `keep`, closing the
660
+ * scope leaves the current session running for the next `supervise` under that name to adopt.
661
+ */
662
+ export const supervise = (options: SuperviseOptions = {}) =>
663
+ Effect.suspend(() => {
664
+ const { keep } = options;
665
+ // Only the first generation adopts a kept session: a later one would find its own.
666
+ let opened = false;
667
+
668
+ return Supervisor.make({
669
+ open: Effect.suspend(() =>
670
+ start(options, keep === undefined ? undefined : { name: keep, adopt: !opened }),
671
+ ).pipe(
672
+ Effect.tap(() =>
673
+ Effect.sync(() => {
674
+ opened = true;
675
+ }),
676
+ ),
677
+ Effect.withSpan("Browserbase.open", {}, { captureStackTrace: false }),
678
+ ),
679
+ exclusive: options.session?.browserSettings?.context?.persist === true,
680
+ keep: keep !== undefined,
681
+ reopen: options.reopen,
682
+ definite: refused,
683
+ rotateBefore: options.rotateBefore,
684
+ waitTimeout: options.waitTimeout,
685
+ });
686
+ });
687
+
688
+ export const layer = (
689
+ options: Options = {},
690
+ ): Layer.Layer<
691
+ Browser.Browser,
692
+ BrowserError | BrowserbaseError | ContextHeld,
693
+ BrowserbaseClient | ContextLease
694
+ > =>
695
+ Layer.effect(
696
+ Browser.Browser,
697
+ Effect.map(open(options), ({ browser }) => browser),
698
+ );