effect-browserbase 0.2.0-beta.7 → 0.2.0-beta.8

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 (54) hide show
  1. package/README.md +35 -21
  2. package/dist/Account.mjs +3 -3
  3. package/dist/{Acquisition-Ca4EE-Fg.mjs → Acquisition-BOABu_qJ.mjs} +21 -12
  4. package/dist/Acquisition-BOABu_qJ.mjs.map +1 -0
  5. package/dist/Agents.mjs +25 -25
  6. package/dist/Agents.mjs.map +1 -1
  7. package/dist/Allocation.mjs +1 -1
  8. package/dist/{Browser-BPcF550A.mjs → Browser-ByrWJ0ss.mjs} +21 -17
  9. package/dist/Browser-ByrWJ0ss.mjs.map +1 -0
  10. package/dist/Browser.d.mts +11 -9
  11. package/dist/Browser.mjs +1 -1
  12. package/dist/Certificates.mjs +9 -9
  13. package/dist/Certificates.mjs.map +1 -1
  14. package/dist/{Client-4RMKIpL2.mjs → Client-BEC4Q8ZS.mjs} +154 -14
  15. package/dist/Client-BEC4Q8ZS.mjs.map +1 -0
  16. package/dist/Client.mjs +1 -1
  17. package/dist/ContextCoordination.mjs +9 -8
  18. package/dist/ContextCoordination.mjs.map +1 -1
  19. package/dist/Contexts.mjs +7 -7
  20. package/dist/Contexts.mjs.map +1 -1
  21. package/dist/Downloads.mjs +10 -10
  22. package/dist/Downloads.mjs.map +1 -1
  23. package/dist/{Extensions-Dg3jHOf0.mjs → Extensions-BTUn9zhK.mjs} +8 -8
  24. package/dist/Extensions-BTUn9zhK.mjs.map +1 -0
  25. package/dist/Extensions.mjs +1 -1
  26. package/dist/Functions.mjs +27 -27
  27. package/dist/Functions.mjs.map +1 -1
  28. package/dist/PageFetch.mjs +4 -4
  29. package/dist/PageFetch.mjs.map +1 -1
  30. package/dist/Projects.mjs +5 -5
  31. package/dist/Projects.mjs.map +1 -1
  32. package/dist/Recordings.mjs +42 -27
  33. package/dist/Recordings.mjs.map +1 -1
  34. package/dist/Replays.mjs +6 -6
  35. package/dist/Replays.mjs.map +1 -1
  36. package/dist/{Resource-DBksC4zB.mjs → Resource-J7Kkk5mu.mjs} +7 -3
  37. package/dist/Resource-J7Kkk5mu.mjs.map +1 -0
  38. package/dist/Search.mjs +4 -4
  39. package/dist/Search.mjs.map +1 -1
  40. package/dist/{Sessions-BUoyPcPJ.mjs → Sessions-D2H5m6rF.mjs} +15 -15
  41. package/dist/Sessions-D2H5m6rF.mjs.map +1 -0
  42. package/dist/Sessions.mjs +1 -1
  43. package/dist/Testing.mjs +1 -1
  44. package/dist/Uploads.mjs +4 -4
  45. package/dist/Uploads.mjs.map +1 -1
  46. package/dist/Webhooks.mjs +14 -14
  47. package/dist/Webhooks.mjs.map +1 -1
  48. package/package.json +2 -2
  49. package/dist/Acquisition-Ca4EE-Fg.mjs.map +0 -1
  50. package/dist/Browser-BPcF550A.mjs.map +0 -1
  51. package/dist/Client-4RMKIpL2.mjs.map +0 -1
  52. package/dist/Extensions-Dg3jHOf0.mjs.map +0 -1
  53. package/dist/Resource-DBksC4zB.mjs.map +0 -1
  54. package/dist/Sessions-BUoyPcPJ.mjs.map +0 -1
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  `effect-browserbase` supplies Browserbase resources and hosted lifetimes to the shared browser runtime: account identity and transport, session, context and extension resources, one owned browser over Playwright/CDP — allocated or borrowed — with trusted registrations, modeled file selection, bounded live capture, explicit page holds, the provider's recordings, replays, uploads and website downloads, and the platform APIs outside a browser session (projects, certificates, Search, Fetch, Agents, Functions and webhooks).
4
4
 
5
- Its host supplies the required `effect-browser` peer, at the same coordinated `0.2.0-beta.7` version; it has no Effect Agent dependency. Install both packages explicitly so the provider and application share one runtime instance. Playwright is an optional peer of the shared runtime and is loaded only when a browser connects; artifact-only consumers do not need it. The Effect peer range is `^4.0.0-rc.117`, with rc.117 qualified. The package targets trusted Node and Bun hosts. It is published as a beta (`0.2.0-beta.0` on the `beta` dist-tag): hosted provider behavior requires separate validation, and ordinary tests never create a paid Browserbase session or invoke a paid model.
5
+ Its host supplies the required `effect-browser` peer, at the same coordinated `0.2.0-beta.8` version; it has no Effect Agent dependency. Install both packages explicitly so the provider and application share one runtime instance. Playwright is an optional peer of the shared runtime and is loaded only when a browser connects; artifact-only consumers do not need it. The Effect peer range is `^4.0.0-rc.117`, with rc.117 qualified. The package targets trusted Node and Bun hosts. It is published as a beta (`0.2.0-beta.0` on the `beta` dist-tag): hosted provider behavior requires separate validation, and ordinary tests never create a paid Browserbase session or invoke a paid model.
6
6
 
7
7
  ## One account, then resources
8
8
 
@@ -61,7 +61,7 @@ const program = Effect.gen(function* () {
61
61
 
62
62
  const reference = yield* Browser.scoped(BrowserbaseBrowser.open(policy), (session) =>
63
63
  Effect.gen(function* () {
64
- yield* session.navigate(NavigateRequest.make({ url: "https://example.com" }));
64
+ yield* session.initialPage.navigate(NavigateRequest.make({ url: "https://example.com" }));
65
65
 
66
66
  // Browser.scoped checks the owner's release before returning this durable identity.
67
67
  return session.reference;
@@ -110,9 +110,9 @@ A bounded hosted check ran a page producing a known 440 Hz tone two independent
110
110
 
111
111
  Prefer provider recording when post-session MP4/HLS is enough. Use `capture` when you need frames during the session, need to transform or encode them yourself, did not enable provider recording, are testing locally without a paid session, or need a live-frame path distinct from Browserbase's post-session artifact lifetime. BYOS recording completion is reported explicitly even when Browserbase does not return a download URL.
112
112
 
113
- `Capture.start(session, { target: page })` accepts a `PageInfo` from `session.pages` and pins the interval to that page independently of the selected automation target. Omitting `target` binds to the page selected when capture starts; later selection changes do not move or stop it. An agent can drive a scout tab while the stage page keeps recording. Distinct pages may capture concurrently, with one interval per native target, at most four active or quarantined intervals, and 64 MiB of aggregate reserved buffering per session. The maintained Playwright screencast callback is JPEG-only here and the public API does not expose an FPS cap or lossless format.
113
+ `Capture.start(page)` requires an issued `Page`, such as `session.initialPage` or `yield* session.page(info)` for exact metadata from `session.listPages()`. The interval belongs to that Page independently of display selection; later selection changes do not move or stop it. An agent can drive a scout tab while the stage page keeps recording. Distinct pages may capture concurrently, with one interval per native target, at most four active or quarantined intervals, and 64 MiB of aggregate reserved buffering per session. The maintained Playwright screencast callback is JPEG-only here and the public API does not expose an FPS cap or lossless format.
114
114
 
115
- `Capture.start(session, { target: page, size: { width: 640, height: 360 } })` requests source frames fitted within those pixel bounds without resizing the live viewport. Both dimensions must be integers from 1 through 16,384; the existing 33,554,432-pixel and byte limits still apply to actual frames. The request is validated and copied before native work or capture-budget admission. Omitting `size` preserves Playwright's default (the viewport fitted within 800×800). An already-active native screencast can override a requested size, so the package independently checks actual JPEG dimensions and ends the affected interval with a `limit` error before delivering an oversized frame. It does not silently resize bytes, invent dimensions, alter timestamps, or end a sibling page's capture. A size request is not a frame-rate limit or a guarantee about bytes produced before they reach the package.
115
+ `Capture.start(page, { size: { width: 640, height: 360 } })` requests source frames fitted within those pixel bounds without resizing the live viewport. Both dimensions must be integers from 1 through 16,384; the existing 33,554,432-pixel and byte limits still apply to actual frames. The request is validated and copied before native work or capture-budget admission. Omitting `size` preserves Playwright's default (the viewport fitted within 800×800). An already-active native screencast can override a requested size, so the package independently checks actual JPEG dimensions and ends the affected interval with a `limit` error before delivering an oversized frame. It does not silently resize bytes, invent dimensions, alter timestamps, or end a sibling page's capture. A size request is not a frame-rate limit or a guarantee about bytes produced before they reach the package.
116
116
 
117
117
  ## Session, reference, and ownership
118
118
 
@@ -133,11 +133,11 @@ fails. An outer race can discard that checked error, so keep any required host r
133
133
  the raced workflow. The shared guide's [Layer and receipt examples](../browser/README.md#a-long-lived-session-in-a-layer)
134
134
  describe sharing one bounded session and the supervision that a Layer alone does not provide.
135
135
 
136
- Mutations are serialized. An observation identifies retained native nodes only until the next invalidating event; it is not a DOM snapshot version. Replaced or detached nodes fail instead of silently resolving to replacements. An action interrupted or timed out after native dispatch has an **unknown** outcome and is never automatically replayed. Unresolved control fences the owner; the shared runtime's main-frame navigation recovery can preserve usability after one acknowledged stop while still reporting `Timeout/unknown`. Recovery is bounded by the loading deadline plus at most three seconds and the existing lifetime. Child-frame timeouts retain the conservative fence. `undispatched` is used only when the package established that native mutation dispatch did not occur.
136
+ Each Page serializes its operations with its frames; operations on independent Pages can proceed concurrently. An observation identifies retained native nodes only until the next invalidating event; it is not a DOM snapshot version. Replaced or detached nodes fail instead of silently resolving to replacements. An action interrupted or timed out after native dispatch has an **unknown** outcome and is never automatically replayed. Unresolved control fences the affected Page until confirmed closure; unsuccessful containment fences the session. The shared runtime's main-frame navigation recovery can preserve usability after one acknowledged stop while still reporting `Timeout/unknown`. Recovery is bounded by the loading deadline plus at most three seconds and the existing lifetime. Child-frame timeouts retain conservative containment. `undispatched` is used only when the package established that native mutation dispatch did not occur.
137
137
 
138
138
  ## Shared browser operations
139
139
 
140
- Navigation, observation, native input, typed bootstrap bindings, live capture and page holds are implemented by [`effect-browser`](../browser/README.md). Import their contracts from that package and use them with the exact `BrowserbaseSession` returned here. The [`effect-agent-browser`](../agent-browser/README.md) adapter and maintained tools accept both this session and self-managed Chromium without a second connection.
140
+ Navigation, observation, native input, typed bootstrap bindings, live capture and page holds are implemented by [`effect-browser`](../browser/README.md). Import their contracts from that package. Session owns lifecycle and inventory; its issued Pages and Frames own browser operations. `session.initialPage` keeps its original identity when display selection changes, and `page.frame(info)` issues exact Frame authority. Capture and page holds require an issued Page. The [`effect-agent-browser`](../agent-browser/README.md) adapter and maintained tools accept both this session and self-managed Chromium without a second connection.
141
141
 
142
142
  The shared session also provides passive `status` and bounded `diagnostics`, including after
143
143
  closure. Known expiry, callback failure and policy pressure are not automatically labeled
@@ -151,6 +151,10 @@ it is independent of model action accounting and never a tool parameter.
151
151
 
152
152
  Small selection needs no provisioning: `session.selectFiles` attaches in-memory bytes the caller already holds, and `session.clickForFileSelection` registers the chooser observation before the single click that opens it and attaches exactly once.
153
153
 
154
+ `session.selectFiles(page, request)`, `session.clickForFileSelection(page, request)` and `session.clickForDownload(page, request)` take an issued `Page` from that session first, as `Capture.start(page)` and `PageControl` do, such as `session.initialPage` or `yield* session.page(info)`. Transfers stay on that Page through the original connection while display selection moves. Cloned, foreign and retired Pages fail before transfer dispatch.
155
+
156
+ Each transfer accepts trailing host-only `OperationOptions`: `session.selectFiles(page, request, { timeoutMillis: 5000, admission: { queue: "1 second" } })`. Queue omission or zero fails immediately when conflicting work is active; a positive finite duration allows bounded FIFO waiting. Waiting counts toward the operation deadline, and neither option extends the browser's policy or lifetime. `QueueFull` and `QueueExpired` distinguish capacity refusal and expired waiting from immediate `Busy`. Live View, handoff, resume and reconnect also accept trailing operation options; cleanup effects retain their owned lifetime.
157
+
154
158
  Larger files use `BrowserbaseUploads.create`, which places bytes for the exact running session and returns a receipt. A stored file is named to the browser process, which opens the path itself; only in-memory bytes are streamed from this client, and the two mechanisms are never mixed. Attachment authority is the identity of a receipt this package issued for that session, so a value that merely has the right shape carries none: no caller, and no model, turns a server pathname into an attached file. The receipt reports the provider's remote path only when the provider returned one; when it does not, attachment by path is refused rather than guessed. Hosted H6 remains the check for real provider upload identity and routing.
155
159
 
156
160
  ## Borrowed attachment
@@ -161,22 +165,32 @@ Larger files use `BrowserbaseUploads.create`, which places bytes for the exact r
161
165
 
162
166
  ## Shared API migration
163
167
 
164
- | Before | Now |
165
- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
166
- | `session.bind()` or `yield* session.currentTarget` | Ordinary calls use `session` directly; `yield* session.retain` explicitly obtains checked stale-on-selection semantics |
167
- | Bare page IDs in selection/closure, selection returns a handle | Pass `PageInfo` to `selectPage`/`closePage`; selection returns `void`, and `createPage` returns the exact created record |
168
- | Reuse old page/frame metadata after reconnect | In the same known browser lifetime, read fresh pages and match exactly one saved `targetId`; then read fresh frames. No fallback to order, old ID, URL or title |
169
- | `Adapter.fromSession(session)` or `currentHandle` | Await the Effect with explicit `{ selection: "current" }` or `{ selection: "retained" }`; its browser is the original concrete session |
170
- | `BrowserError.reason` string and optional outcome | Tagged reason and required outcome. Use `Effect.catchReason`; factual limit/status/retry fields belong to their reason |
171
- | All host reason names reach model output | A compact eleven-reason tool failure; original structured fields and bounded call IDs remain in `ToolHost.toolFailures` |
172
- | `closeChecked` success is `undefined` | Concrete receipt success after the existing ownership check; `close` and `cleanupResult` remain available |
173
- | Capture `dropped` | `discarded = overflow + late + duplicates + rejected`; no change to default capacity or unknown upstream loss |
174
- | Non-supervising helper takes default `BrowserSession` | Use `AnySession`; keep supervising helpers generic in callback error or concrete session |
168
+ | Before | Now |
169
+ | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
170
+ | Session action calls or retained/pinned wrappers | Use `session.initialPage` or `yield* session.page(info)` for Page operations and `yield* page.frame(info)` for Frame operations; display selection never retargets issued authority |
171
+ | Bare page IDs in selection/closure | Pass an issued Page to `session.selectPage(page)` for display selection, and close exact issued authority with `page.close()` |
172
+ | Reuse old page/frame metadata after reconnect | In the same known browser lifetime, read fresh pages and match exactly one saved `targetId`; then read fresh frames. No fallback to order, old ID, URL or title |
173
+ | `Adapter.fromSession(session)` or implicit selection | Supply the owning session and issued Page to `yield* Adapter.fromSession(session, page)`; its lifecycle remains on the original browser owner |
174
+ | `BrowserError.reason` string and optional outcome | Tagged reason and required outcome. Use `Effect.catchReason`; factual limit/status/retry fields belong to their reason |
175
+ | All host reason names reach model output | A compact eleven-reason tool failure; original structured fields and bounded call IDs remain in `ToolHost.toolFailures` |
176
+ | `closeChecked` success is `undefined` | Concrete receipt success after the existing ownership check; `close` and `cleanupResult` remain available |
177
+ | Capture `dropped` | `discarded = overflow + late + duplicates + rejected`; no change to default capacity or unknown upstream loss |
178
+ | Non-supervising helper takes default `BrowserSession` | Use `AnySession`; keep supervising helpers generic in callback error or concrete session |
179
+ | Session readiness, target and frame shortcuts | Use `page.ready()`, immutable `page.identity`, `page.listFrames()` and `page.frame(info)`; Session retains `listPages()` and `createPage()` |
180
+ | Transfers called as `(request, page, options)` | Pass the issued Page first: `selectFiles(page, request, options)`, `clickForFileSelection(page, request, options)` and `clickForDownload(page, request, options)` |
181
+
182
+ `resume(token, operatorReleasedControl)` and `reconnect(operatorReleasedControl)` return a
183
+ bounded `Inventory` containing the new owner generation and fresh Page metadata. They do not
184
+ read page content or issue observed references. Acquire an issued Page from `inventory.pages`
185
+ and call `page.observe()` explicitly. `detach` returns its pre-disconnection inventory and exact
186
+ selected native `targetId`, preserving bounded target identities for deliberate attachment;
187
+ its Page IDs are old authority and cannot be reused after reconnect. Page metadata is a sequence
188
+ of native reads and is non-atomic.
175
189
 
176
190
  Binding omission defaults are one concurrent call, 64 KiB each direction, 10 seconds and
177
191
  `reject-call`; explicit values remain validated. Combined readiness uses the most conservative
178
192
  `existingDocuments` policy. Common navigation now accepts optional `timeoutMillis` with the same
179
- bounds as `startNavigation`; direct, retained and pinned operations share it. Observations add
193
+ bounds as `startNavigation`; issued Page and Frame operations share it. Observations add
180
194
  bounded checked/selected/inputType/required state without field values or destinations. These
181
195
  contracts live in the [common browser guide](../browser/README.md).
182
196
 
@@ -249,7 +263,7 @@ it.effect("release is requested once and confirmed", () =>
249
263
  BrowserbaseBrowser.open(BrowserPolicy.unrestricted()),
250
264
  (session) =>
251
265
  Effect.gen(function* () {
252
- yield* session.navigate({ url: "https://shop.test/" });
266
+ yield* session.initialPage.navigate({ url: "https://shop.test/" });
253
267
 
254
268
  return yield* session.closeChecked;
255
269
  }),
@@ -324,13 +338,13 @@ Rates are outside this package's runtime contract. As reviewed on 25 September 2
324
338
 
325
339
  Every expected failure says three things. `operation` is what you asked for, from a closed vocabulary per error class: `BrowserError` names the browser operations, `SessionError` only session calls, and so on, so you can match on them exhaustively and a misspelling is a type error, not a string that happens to compile. `reason` is why it failed. `outcome`, when present, is the package's dispatch evidence: `undispatched` proves this package did not send the mutation and is safe to retry, `rejected` means a provider response refused it, and `unknown` means dispatch or acceptance cannot be ruled out. None is a billing decision. Mutations with `unknown` outcome are never replayed for you. Why an extension archive was refused is a `reason` (`limit`, `unsafe-filename`, `configuration`) of the one `extension-archive` operation. A native step's own name never appears: the driver raises a private failure, and the owner stamps the operation it admitted.
326
340
 
327
- Everything under `src/internal/` is private; the common runtime offers a modeled integration constructor, while no consumer CDP seam is exported; `browser-binding` chooses the engine and where it connects, never what runs over the connection. The driver does hold a CDP session; exposing it, or the ownership internals, would place actions outside the mutation permit that serializes them and outside the fencing that makes an uncertain outcome detectable. Opening a second debugger connection beside this one has the same effect and is equally unsupported. An unmodeled need is a request for a modeled entry point, not a reason to reach around the boundary.
341
+ Everything under `src/internal/` is private; the common runtime offers a modeled integration constructor, while no consumer CDP seam is exported; `browser-binding` chooses the engine and where it connects, never what runs over the connection. The driver does hold a CDP session; exposing it, or the ownership internals, would place actions outside their Page's admission and outside the fencing that makes an uncertain outcome detectable. Opening a second debugger connection beside this one has the same effect and is equally unsupported. An unmodeled need is a request for a modeled entry point, not a reason to reach around the boundary.
328
342
 
329
343
  ## Artifact and capture guarantees
330
344
 
331
345
  Provider recordings have an independent post-session lifetime. Assembly POST is a mutation; an uncertain POST is reconciled with status before any deliberate retry. Polling is bounded and preserves per-page partial success/failure. BYOS completion without a Browserbase download URL is reported explicitly.
332
346
 
333
- Website downloads retain their provider download ID, safe filename, MIME type and declared size. Streaming enforces configured MIME, byte and deadline bounds and verifies the completed byte count. A click result alone is never reported as a completed file.
347
+ Website downloads retain their provider download ID, safe filename, MIME type and declared size. Streaming enforces configured MIME, byte and deadline bounds and verifies the completed byte count. A click result alone is never reported as a completed file. Provider download enumeration is session-wide; concurrent clicks on different Pages do not establish an automatic association between a native download event and a provider download ID.
334
348
 
335
349
  Replay playlists reject arbitrary URI-bearing tags and proxy only indexed media from the validated playlist. API credentials are never returned to a browser client.
336
350
 
package/dist/Account.mjs CHANGED
@@ -1,10 +1,10 @@
1
- import { t as BrowserbaseClient } from "./Client-4RMKIpL2.mjs";
1
+ import { t as BrowserbaseClient } from "./Client-BEC4Q8ZS.mjs";
2
2
  import { BrowserbaseAgents } from "./Agents.mjs";
3
3
  import { BrowserbaseCertificates } from "./Certificates.mjs";
4
4
  import { BrowserbaseContexts } from "./Contexts.mjs";
5
- import { t as BrowserbaseSessions } from "./Sessions-BUoyPcPJ.mjs";
5
+ import { t as BrowserbaseSessions } from "./Sessions-D2H5m6rF.mjs";
6
6
  import { BrowserbaseDownloads } from "./Downloads.mjs";
7
- import { t as BrowserbaseExtensions } from "./Extensions-Dg3jHOf0.mjs";
7
+ import { t as BrowserbaseExtensions } from "./Extensions-BTUn9zhK.mjs";
8
8
  import { BrowserbaseFunctions } from "./Functions.mjs";
9
9
  import { BrowserbasePageFetch } from "./PageFetch.mjs";
10
10
  import { BrowserbaseProjects } from "./Projects.mjs";
@@ -1,10 +1,10 @@
1
1
  import { Identifier, SessionReference } from "./References.mjs";
2
2
  import { AllocationError, ContextError, SessionError } from "./Errors.mjs";
3
- import { t as BrowserbaseClient } from "./Client-4RMKIpL2.mjs";
3
+ import { n as annotate, r as span, t as BrowserbaseClient } from "./Client-BEC4Q8ZS.mjs";
4
4
  import { t as compileLaunch } from "./Launch-cAdE2rrZ.mjs";
5
5
  import { CleanupIssue, CleanupResult } from "./Cleanup.mjs";
6
6
  import { a as requireContextWriterPermit } from "./ContextWriter-CiEma24z.mjs";
7
- import { t as BrowserbaseSessions } from "./Sessions-BUoyPcPJ.mjs";
7
+ import { t as BrowserbaseSessions } from "./Sessions-D2H5m6rF.mjs";
8
8
  import { t as connectionAddress } from "./Connection-sxyxtwlk.mjs";
9
9
  import { Cause, Clock, Crypto, Data, Effect, ErrorReporter, Exit, Option, Schema, Scope } from "effect";
10
10
  import { cleanupStep, noConnection, reported } from "effect-browser/browser-runtime";
@@ -25,7 +25,10 @@ const makeCleanup = Effect.fnUntraced(function* (reference, ownership, sessions,
25
25
  return {
26
26
  close: yield* Effect.cached(Effect.uninterruptible(Effect.gen(function* () {
27
27
  const issues = [];
28
- const step = (name, action, milliseconds) => cleanupStep(action, milliseconds).pipe(Effect.tap((result) => Effect.sync(() => {
28
+ const step = (name, action, milliseconds) => cleanupStep(action.pipe(span("Browserbase.cleanup.step", { attributes: {
29
+ "browser.cleanup.step": name,
30
+ "browser.ownership": ownership
31
+ } })), milliseconds).pipe(Effect.tap((result) => Effect.sync(() => {
29
32
  if (result._tag === "Failure") issues.push(CleanupIssue.make({
30
33
  step: name,
31
34
  reason: result.reason
@@ -60,8 +63,14 @@ const makeCleanup = Effect.fnUntraced(function* (reference, ownership, sessions,
60
63
  Object.freeze(result.issues);
61
64
  latest = Object.freeze(result);
62
65
  report(latest);
66
+ yield* annotate({
67
+ "browser.cleanup.local": latest.local,
68
+ "browser.cleanup.remote": latest.remote,
69
+ "browser.cleanup.releaseRequested": latest.releaseRequested,
70
+ "browser.cleanup.issueCount": latest.issues.length
71
+ });
63
72
  return latest;
64
- }))),
73
+ }).pipe(span("Browserbase.cleanup", { attributes: { "browser.ownership": ownership } })))),
65
74
  result: Effect.sync(() => Option.fromNullishOr(latest))
66
75
  };
67
76
  });
@@ -152,7 +161,7 @@ const acquireRemote = Effect.fnUntraced(function* (options, local = noLocalConne
152
161
  const allocationUncertain = Effect.suspend(() => {
153
162
  if (uncertainReported) return Effect.void;
154
163
  uncertainReported = true;
155
- return reportAllocationUncertain(attempt).pipe(Effect.andThen(options.onAllocationUncertain === void 0 ? Effect.void : reported(options.onAllocationUncertain(attempt))));
164
+ return reportAllocationUncertain(attempt).pipe(Effect.andThen(options.onAllocationUncertain === void 0 ? Effect.void : reported(Effect.suspend(() => options.onAllocationUncertain?.(attempt) ?? Effect.void).pipe(span("Browserbase.callback.allocationUncertain")))));
156
165
  });
157
166
  const terminate = yield* Effect.cached(Effect.uninterruptible(Effect.gen(function* () {
158
167
  closing = true;
@@ -171,9 +180,9 @@ const acquireRemote = Effect.fnUntraced(function* (options, local = noLocalConne
171
180
  const notify = options.onCleanup;
172
181
  if (result !== void 0) {
173
182
  yield* reported(Effect.suspend(() => reportCleanup(result)));
174
- if (notify !== void 0) yield* reported(Effect.suspend(() => notify(result)));
183
+ if (notify !== void 0) yield* reported(Effect.suspend(() => notify(result)).pipe(span("Browserbase.callback.cleanup")));
175
184
  }
176
- })));
185
+ }).pipe(span("Browserbase.terminate", { attributes: { "browser.ownership": "owned" } }))));
177
186
  const closeScope = yield* Effect.cached(Scope.close(resourceScope, Exit.void));
178
187
  yield* Scope.addFinalizer(resourceScope, terminate);
179
188
  yield* Scope.addFinalizer(parent, closeScope);
@@ -222,14 +231,14 @@ const acquireRemote = Effect.fnUntraced(function* (options, local = noLocalConne
222
231
  operation: "session-connect",
223
232
  reason: "expired",
224
233
  outcome: "undispatched"
225
- })) : connectionAddress(client, sessions, ref, timeoutMillis)),
226
- release: closeScope.pipe(Effect.andThen(Effect.suspend(() => cleanup === void 0 ? Effect.die(/* @__PURE__ */ new Error("Owned session closed without cleanup evidence")) : Effect.succeed(cleanup)))),
234
+ })) : connectionAddress(client, sessions, ref, timeoutMillis).pipe(span("Browserbase.connection", { attributes: { "browser.ownership": "owned" } }))),
235
+ release: closeScope.pipe(Effect.andThen(Effect.suspend(() => cleanup === void 0 ? Effect.die(/* @__PURE__ */ new Error("Owned session closed without cleanup evidence")) : Effect.succeed(cleanup))), span("Browserbase.release", { attributes: { "browser.ownership": "owned" } })),
227
236
  cleanupResult: Effect.sync(() => Option.fromNullishOr(cleanup))
228
237
  };
229
- }).pipe(Effect.onError(() => closeScope), Effect.onInterrupt(() => closeScope));
238
+ }).pipe(Effect.onError(() => closeScope), Effect.onInterrupt(() => annotate({ "browser.outcome": admitted ? knownRejection ? "rejected" : "unknown" : "undispatched" }).pipe(Effect.andThen(closeScope))));
230
239
  }));
231
- });
240
+ }, span("Browserbase.acquireRemote", { attributes: { "browser.ownership": "owned" } }));
232
241
  //#endregion
233
242
  export { reported as a, noLocalConnection as i, reportCleanup as n, makeCleanup as r, acquireRemote as t };
234
243
 
235
- //# sourceMappingURL=Acquisition-Ca4EE-Fg.mjs.map
244
+ //# sourceMappingURL=Acquisition-BOABu_qJ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Acquisition-BOABu_qJ.mjs","names":["Trace.span","Trace.annotate","Trace.span","Trace.annotate"],"sources":["../src/internal/session/Cleanup.ts","../src/internal/session/Diagnostics.ts","../src/internal/session/Acquisition.ts"],"sourcesContent":["import { Effect, Option } from \"effect\";\nimport { cleanupStep, noConnection, type ConnectionCleanup } from \"effect-browser/browser-runtime\";\n\nexport { reported } from \"effect-browser/browser-runtime\";\nexport type { ConnectionCleanup as LocalCleanup } from \"effect-browser/browser-runtime\";\n\nimport { CleanupIssue, CleanupResult } from \"../../Cleanup.ts\";\nimport type { SessionReference } from \"../../References.ts\";\nimport type { SessionStatus } from \"../../SessionData.ts\";\nimport type { BrowserbaseSessions } from \"../../Sessions.ts\";\nimport * as Trace from \"../Trace.ts\";\n\nexport const noLocalConnection = noConnection;\n\n/** Internal limits, also injectable by deterministic failure tests. */\nexport interface CleanupLimits {\n readonly localStepMillis: number;\n readonly releaseMillis: number;\n readonly terminalMillis: number;\n}\n\nexport const defaultCleanupLimits: CleanupLimits = {\n localStepMillis: 3000,\n releaseMillis: 4000,\n terminalMillis: 4000,\n};\n\n/**\n * Close is one uninterruptible, bounded transaction over *local cleanup evidence*, not\n * a transaction over the remote browser. Each step observes its own Exit so failures\n * cannot suppress a later disconnect, release request, or exact-session status read.\n */\nexport const makeCleanup = Effect.fnUntraced(function* (\n reference: SessionReference,\n ownership: CleanupResult[\"ownership\"],\n sessions: BrowserbaseSessions[\"Service\"],\n local: ConnectionCleanup,\n report: (result: CleanupResult) => void,\n limits: CleanupLimits = defaultCleanupLimits,\n) {\n let latest: CleanupResult | undefined;\n\n const close = yield* Effect.cached(\n Effect.uninterruptible(\n Effect.gen(function* () {\n const issues: CleanupIssue[] = [];\n\n const step = <A, E>(\n name: CleanupIssue[\"step\"],\n action: Effect.Effect<A, E>,\n milliseconds: number,\n ) =>\n cleanupStep(\n action.pipe(\n Trace.span(\"Browserbase.cleanup.step\", {\n attributes: { \"browser.cleanup.step\": name, \"browser.ownership\": ownership },\n }),\n ),\n milliseconds,\n ).pipe(\n Effect.tap((result) =>\n Effect.sync(() => {\n if (result._tag === \"Failure\")\n issues.push(CleanupIssue.make({ step: name, reason: result.reason }));\n }),\n ),\n );\n\n // The fence runs synchronously before interruptible native teardown begins.\n yield* step(\"fence\", local.fence, limits.localStepMillis);\n yield* step(\"capture\", local.capture, limits.localStepMillis);\n yield* step(\"initialization\", local.initialization, limits.localStepMillis);\n const disconnected = yield* step(\"disconnect\", local.disconnect, limits.localStepMillis);\n const localState = disconnected._tag === \"Success\" ? disconnected.value : \"failed\";\n\n let releaseRequested = false;\n let remote: CleanupResult[\"remote\"] = ownership === \"borrowed\" ? \"not-owned\" : \"unknown\";\n let observedStatus: SessionStatus | undefined;\n\n if (ownership === \"owned\") {\n const requested = yield* step(\n \"release\",\n sessions.requestRelease(reference),\n limits.releaseMillis,\n );\n\n releaseRequested = requested._tag === \"Success\";\n\n // A POST response is never substituted for a passive terminal-state observation.\n const terminal = yield* step(\n \"status\",\n sessions.waitForTerminal(reference, { timeoutMillis: limits.terminalMillis }),\n limits.terminalMillis,\n );\n\n if (terminal._tag === \"Success\") {\n remote = \"confirmed\";\n observedStatus = terminal.value.status;\n } else if (requested._tag === \"Success\") {\n remote = \"pending\";\n }\n }\n\n const result = CleanupResult.make({\n reference,\n ownership,\n releaseRequested,\n remote,\n local: localState,\n ...(observedStatus === undefined ? {} : { observedStatus }),\n issues,\n });\n\n Object.freeze(result.issues);\n latest = Object.freeze(result);\n report(latest);\n\n yield* Trace.annotate({\n \"browser.cleanup.local\": latest.local,\n \"browser.cleanup.remote\": latest.remote,\n \"browser.cleanup.releaseRequested\": latest.releaseRequested,\n \"browser.cleanup.issueCount\": latest.issues.length,\n });\n\n return latest;\n }).pipe(\n Trace.span(\"Browserbase.cleanup\", {\n attributes: { \"browser.ownership\": ownership },\n }),\n ),\n ),\n );\n\n return {\n close,\n result: Effect.sync(() => Option.fromNullishOr(latest)),\n };\n});\n","import { Cause, Data, Effect, ErrorReporter } from \"effect\";\n\nimport type { CleanupResult } from \"../../Cleanup.ts\";\nimport type { AllocationAttempt } from \"../../References.ts\";\n\n/**\n * Operator-visible evidence that a session's fate was not settled. It carries identity and\n * outcome labels only: no provider body, connection URL, credential or page content. The\n * transport deliberately disables tracing where credentials travel, so without this an\n * unconfirmed release or an allocation of unknown outcome would leave no trace for anyone who\n * did not register a callback.\n */\nclass SessionUnsettled extends Data.TaggedError(\"BrowserbaseSessionUnsettled\")<{\n readonly message: string;\n readonly details: Readonly<Record<string, string | number>>;\n}> {\n override readonly [ErrorReporter.severity] = \"Warn\" as const;\n\n override get [ErrorReporter.attributes]() {\n return this.details;\n }\n}\n\nconst surface = (message: string, details: Readonly<Record<string, string | number>>) =>\n Effect.logWarning(message).pipe(\n Effect.annotateLogs(details),\n Effect.andThen(ErrorReporter.report(Cause.fail(new SessionUnsettled({ message, details })))),\n );\n\n/** A borrowed scope never owns release, so only its local teardown can be unsettled. */\nexport const reportCleanup = (result: CleanupResult): Effect.Effect<void> => {\n const remoteUnsettled =\n result.ownership === \"owned\" && (result.remote !== \"confirmed\" || !result.releaseRequested);\n\n if (!remoteUnsettled && result.local !== \"failed\" && result.issues.length === 0)\n return Effect.void;\n\n return surface(\"Browserbase session cleanup ended without confirmation\", {\n projectId: result.reference.projectId,\n sessionId: result.reference.sessionId,\n ownership: result.ownership,\n remote: result.remote,\n local: result.local,\n observedStatus: result.observedStatus ?? \"unobserved\",\n issues: result.issues.map((issue) => `${issue.step}:${issue.reason}`).join(\",\") || \"none\",\n });\n};\n\n/** The provider may have allocated a session this process has no reference for. */\nexport const reportAllocationUncertain = (attempt: AllocationAttempt): Effect.Effect<void> =>\n surface(\"Browserbase allocation outcome is unknown\", {\n projectId: attempt.projectId,\n attemptId: attempt.attemptId,\n requestedAtMillis: attempt.requestedAtMillis,\n });\n","import { Clock, Crypto, Effect, Exit, Option, Schema, Scope } from \"effect\";\n\nimport type { CleanupResult } from \"../../Cleanup.ts\";\nimport { BrowserbaseClient } from \"../../Client.ts\";\nimport { AllocationError, ContextError, type ClientError, SessionError } from \"../../Errors.ts\";\nimport type { LaunchRecipe } from \"../../Launch.ts\";\nimport { type AllocationAttempt, Identifier, SessionReference } from \"../../References.ts\";\nimport { BrowserbaseSessions } from \"../../Sessions.ts\";\nimport { connectionAddress } from \"../provider/Connection.ts\";\nimport { compileLaunch } from \"../provider/Launch.ts\";\nimport * as Trace from \"../Trace.ts\";\nimport {\n makeCleanup,\n noLocalConnection,\n reported,\n type CleanupLimits,\n type LocalCleanup,\n} from \"./Cleanup.ts\";\nimport { requireContextWriterPermit, type ContextWriterPermitInternal } from \"./ContextWriter.ts\";\nimport { reportAllocationUncertain, reportCleanup } from \"./Diagnostics.ts\";\nimport type { ContextWriterPermit } from \"./WriterFacts.ts\";\n\nconst AllocatedIdentity = Schema.Struct({ id: Identifier, projectId: Identifier });\n\nexport interface AcquisitionOptions {\n readonly launch: LaunchRecipe;\n readonly contextWriter?: ContextWriterPermit;\n readonly allocationDeadline?: number;\n /** Bounded host notification of the canonical facts. Reporting never changes them. */\n readonly onCleanup?: (result: CleanupResult) => Effect.Effect<void>;\n /** Exactly one notification when a creation attempt's effect on the provider is unknown. */\n readonly onAllocationUncertain?: (attempt: AllocationAttempt) => Effect.Effect<void>;\n}\n\n/**\n * The remote lease is registered before POST. Local connection work is supplied by\n * the same browser owner; the control plane never invents a second operation owner.\n */\nexport const acquireRemote = Effect.fnUntraced(\n function* (\n options: AcquisitionOptions,\n local: LocalCleanup = noLocalConnection,\n limits?: CleanupLimits,\n ) {\n const client = yield* BrowserbaseClient;\n const sessions = yield* BrowserbaseSessions;\n const crypto = yield* Crypto.Crypto;\n const parent = yield* Scope.Scope;\n\n const launch = yield* compileLaunch(options.launch, {\n projectId: client.projectId,\n // Secure randomness is a platform precondition, so its failure is a defect, not an outcome.\n attemptId: yield* Effect.orDie(crypto.randomUUIDv4),\n requestedAtMillis: yield* Clock.currentTimeMillis,\n });\n\n const attempt = launch.attempt;\n let writer: ContextWriterPermitInternal | undefined;\n\n if (launch.context?.persist) {\n if (options.contextWriter === undefined) {\n return yield* ContextError.make({\n operation: \"writer-authority\",\n reason: \"authorization\",\n outcome: \"undispatched\",\n });\n }\n writer = yield* requireContextWriterPermit(options.contextWriter, {\n provider: \"browserbase\",\n projectId: client.projectId,\n contextId: launch.context.id,\n });\n } else if (options.contextWriter !== undefined) {\n return yield* ContextError.make({\n operation: \"writer-authority\",\n reason: \"configuration\",\n outcome: \"undispatched\",\n });\n }\n\n return yield* Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const resourceScope = yield* Scope.make();\n let reference: SessionReference | undefined;\n let admitted = false;\n let knownRejection = false;\n let closing = false;\n let cleanup: CleanupResult | undefined;\n\n let uncertainReported = false;\n\n const allocationUncertain = Effect.suspend(() => {\n if (uncertainReported) return Effect.void;\n uncertainReported = true;\n\n return reportAllocationUncertain(attempt).pipe(\n Effect.andThen(\n options.onAllocationUncertain === undefined\n ? Effect.void\n : reported(\n Effect.suspend(\n () => options.onAllocationUncertain?.(attempt) ?? Effect.void,\n ).pipe(Trace.span(\"Browserbase.callback.allocationUncertain\")),\n ),\n ),\n );\n });\n\n const terminate = yield* Effect.cached(\n Effect.uninterruptible(\n Effect.gen(function* () {\n closing = true;\n if (reference === undefined) {\n if (admitted && !knownRejection) {\n writer?.uncertain(attempt);\n yield* allocationUncertain;\n }\n\n return;\n }\n\n const coordinator = yield* makeCleanup(\n reference,\n \"owned\",\n sessions,\n local,\n (result) => {\n cleanup = result;\n writer?.completed(attempt, result);\n },\n limits,\n );\n\n yield* coordinator.close;\n const result = cleanup;\n const notify = options.onCleanup;\n\n if (result !== undefined) {\n yield* reported(Effect.suspend(() => reportCleanup(result)));\n if (notify !== undefined)\n yield* reported(\n Effect.suspend(() => notify(result)).pipe(\n Trace.span(\"Browserbase.callback.cleanup\"),\n ),\n );\n }\n }).pipe(\n Trace.span(\"Browserbase.terminate\", {\n attributes: { \"browser.ownership\": \"owned\" },\n }),\n ),\n ),\n );\n\n const closeScope = yield* Effect.cached(Scope.close(resourceScope, Exit.void));\n\n yield* Scope.addFinalizer(resourceScope, terminate);\n yield* Scope.addFinalizer(parent, closeScope);\n\n const failedAllocation = (error: ClientError): AllocationError => {\n knownRejection = error.outcome === \"rejected\" || error.outcome === \"undispatched\";\n if (knownRejection) writer?.rejected(attempt);\n else writer?.uncertain(attempt);\n const reason = error.reason;\n\n return AllocationError.make({\n attempt,\n outcome: knownRejection ? \"rejected\" : \"unknown\",\n reason:\n reason === \"authorization\" ||\n reason === \"rate-limited\" ||\n reason === \"configuration\" ||\n reason === \"transport\" ||\n reason === \"timeout\" ||\n reason === \"malformed\"\n ? reason\n : \"provider\",\n ...(error.status === undefined ? {} : { status: error.status }),\n ...(error.retryAfterMillis === undefined\n ? {}\n : { retryAfterMillis: error.retryAfterMillis }),\n });\n };\n\n const allocate = Effect.gen(function* () {\n if (writer !== undefined) yield* writer.recordAttempt(attempt);\n admitted = true;\n\n const raw = yield* restore(\n client.json(\"POST\", \"/v1/sessions\", launch.body, options.allocationDeadline),\n ).pipe(Effect.mapError(failedAllocation));\n\n const identity = yield* Schema.decodeUnknownEffect(AllocatedIdentity)(raw).pipe(\n Effect.mapError(() =>\n AllocationError.make({ attempt, outcome: \"unknown\", reason: \"malformed\" }),\n ),\n );\n\n // Save identity before interpreting any connection credentials or provider metadata.\n reference = Object.freeze(\n SessionReference.make({\n provider: \"browserbase\",\n projectId: identity.projectId,\n sessionId: identity.id,\n }),\n );\n writer?.recordSession(attempt, reference);\n if (reference.projectId !== client.projectId) {\n return yield* AllocationError.make({\n attempt,\n reference,\n outcome: \"unknown\",\n reason: \"malformed\",\n });\n }\n const ref = reference;\n\n return {\n reference: ref,\n attempt,\n launch,\n resourceScope,\n isClosed: () => closing,\n connection: (timeoutMillis: number) =>\n Effect.suspend(() =>\n closing\n ? Effect.fail(\n SessionError.make({\n operation: \"session-connect\",\n reason: \"expired\",\n outcome: \"undispatched\",\n }),\n )\n : connectionAddress(client, sessions, ref, timeoutMillis).pipe(\n Trace.span(\"Browserbase.connection\", {\n attributes: { \"browser.ownership\": \"owned\" },\n }),\n ),\n ),\n release: closeScope.pipe(\n Effect.andThen(\n Effect.suspend(() =>\n cleanup === undefined\n ? Effect.die(new Error(\"Owned session closed without cleanup evidence\"))\n : Effect.succeed(cleanup),\n ),\n ),\n Trace.span(\"Browserbase.release\", { attributes: { \"browser.ownership\": \"owned\" } }),\n ),\n cleanupResult: Effect.sync(() => Option.fromNullishOr(cleanup)),\n };\n });\n\n return yield* allocate.pipe(\n Effect.onError(() => closeScope),\n Effect.onInterrupt(() =>\n Trace.annotate({\n \"browser.outcome\": admitted\n ? knownRejection\n ? \"rejected\"\n : \"unknown\"\n : \"undispatched\",\n }).pipe(Effect.andThen(closeScope)),\n ),\n );\n }),\n );\n },\n Trace.span(\"Browserbase.acquireRemote\", { attributes: { \"browser.ownership\": \"owned\" } }),\n);\n\nexport type RemoteAcquisition = Effect.Success<ReturnType<typeof acquireRemote>>;\n"],"mappings":";;;;;;;;;;;AAYA,MAAa,oBAAoB;AASjC,MAAa,uBAAsC;CACjD,iBAAiB;CACjB,eAAe;CACf,gBAAgB;AAClB;;;;;;AAOA,MAAa,cAAc,OAAO,WAAW,WAC3C,WACA,WACA,UACA,OACA,QACA,SAAwB,sBACxB;CACA,IAAI;CA6FJ,OAAO;EACL,OAAA,OA5FmB,OAAO,OAC1B,OAAO,gBACL,OAAO,IAAI,aAAa;GACtB,MAAM,SAAyB,CAAC;GAEhC,MAAM,QACJ,MACA,QACA,iBAEA,YACE,OAAO,KACLA,KAAW,4BAA4B,EACrC,YAAY;IAAE,wBAAwB;IAAM,qBAAqB;GAAU,EAC7E,CAAC,CACH,GACA,YACF,CAAC,CAAC,KACA,OAAO,KAAK,WACV,OAAO,WAAW;IAChB,IAAI,OAAO,SAAS,WAClB,OAAO,KAAK,aAAa,KAAK;KAAE,MAAM;KAAM,QAAQ,OAAO;IAAO,CAAC,CAAC;GACxE,CAAC,CACH,CACF;GAGF,OAAO,KAAK,SAAS,MAAM,O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7 +1,7 @@
1
1
  import { ContextReference, Identifier } from "./References.mjs";
2
2
  import { PlatformError } from "./Errors.mjs";
3
- import { t as BrowserbaseClient } from "./Client-4RMKIpL2.mjs";
4
- import { t as resource } from "./Resource-DBksC4zB.mjs";
3
+ import { r as span, t as BrowserbaseClient } from "./Client-BEC4Q8ZS.mjs";
4
+ import { t as resource } from "./Resource-J7Kkk5mu.mjs";
5
5
  import { ProxyRule } from "./Launch.mjs";
6
6
  import { n as proxy } from "./Launch-cAdE2rrZ.mjs";
7
7
  import { r as isContextWriterBusy } from "./ContextWriter-CiEma24z.mjs";
@@ -169,33 +169,33 @@ var BrowserbaseAgents = class BrowserbaseAgents extends Context.Service()("effec
169
169
  if (expected !== void 0 && value.runId !== expected) return yield* api.malformed(operation, mutation);
170
170
  return value;
171
171
  });
172
- const create = Effect.fn("BrowserbaseAgents.create")(function* (definition) {
172
+ const create = Effect.fnUntraced(function* (definition) {
173
173
  const value = yield* api.input(AgentDefinition, definition, "agent-create");
174
174
  return yield* api.request("POST", "/v1/agents", ProviderAgent, "agent-create", value).pipe(Effect.flatMap(agent("agent-create", true)));
175
- });
176
- const list = Effect.fn("BrowserbaseAgents.list")(function* (query = {}) {
175
+ }, span("BrowserbaseAgents.create"));
176
+ const list = Effect.fnUntraced(function* (query = {}) {
177
177
  const value = yield* api.input(AgentListQuery, query, "agent-list");
178
178
  const page = yield* api.request("GET", `/v1/agents${api.query(value)}`, ProviderPage(ProviderAgent), "agent-list");
179
179
  return {
180
180
  items: page.data.map((row) => AgentMetadata.make(row)),
181
181
  nextCursor: page.nextCursor ?? void 0
182
182
  };
183
- });
184
- const retrieve = Effect.fn("BrowserbaseAgents.retrieve")(function* (agentId) {
183
+ }, span("BrowserbaseAgents.list"));
184
+ const retrieve = Effect.fnUntraced(function* (agentId) {
185
185
  const id = yield* api.input(Identifier, agentId, "agent-retrieve");
186
186
  return yield* api.request("GET", agentPath(id), ProviderAgent, "agent-retrieve").pipe(Effect.flatMap(agent("agent-retrieve", false, id)));
187
- });
188
- const update = Effect.fn("BrowserbaseAgents.update")(function* (agentId, changes) {
187
+ }, span("BrowserbaseAgents.retrieve"));
188
+ const update = Effect.fnUntraced(function* (agentId, changes) {
189
189
  const id = yield* api.input(Identifier, agentId, "agent-update");
190
190
  const value = yield* api.input(AgentUpdate, changes, "agent-update");
191
191
  if (Object.keys(value).length === 0) return yield* api.configuration("agent-update");
192
192
  return yield* api.request("PATCH", agentPath(id), ProviderAgent, "agent-update", value).pipe(Effect.flatMap(agent("agent-update", true, id)));
193
- });
194
- const remove = Effect.fn("BrowserbaseAgents.delete")(function* (agentId) {
193
+ }, span("BrowserbaseAgents.update"));
194
+ const remove = Effect.fnUntraced(function* (agentId) {
195
195
  const id = yield* api.input(Identifier, agentId, "agent-delete");
196
196
  yield* api.remove(agentPath(id), "agent-delete");
197
- });
198
- const start = Effect.fn("BrowserbaseAgents.run")(function* (request) {
197
+ }, span("BrowserbaseAgents.delete"));
198
+ const start = Effect.fnUntraced(function* (request) {
199
199
  const value = yield* api.input(AgentRunRequest, request, "agent-run");
200
200
  const settings = value.browserSettings;
201
201
  const context = settings?.context;
@@ -226,24 +226,24 @@ var BrowserbaseAgents = class BrowserbaseAgents extends Context.Service()("effec
226
226
  } }
227
227
  };
228
228
  return yield* api.request("POST", "/v1/agents/runs", AgentRun, "agent-run", body);
229
- });
230
- const retrieveRun = Effect.fn("BrowserbaseAgents.retrieveRun")(function* (runId) {
229
+ }, span("BrowserbaseAgents.run"));
230
+ const retrieveRun = Effect.fnUntraced(function* (runId) {
231
231
  const id = yield* api.input(Identifier, runId, "agent-run-retrieve");
232
232
  return yield* api.request("GET", runPath(id), AgentRun, "agent-run-retrieve").pipe(Effect.flatMap(run("agent-run-retrieve", false, id)));
233
- });
234
- const listRuns = Effect.fn("BrowserbaseAgents.listRuns")(function* (query = {}) {
233
+ }, span("BrowserbaseAgents.retrieveRun"));
234
+ const listRuns = Effect.fnUntraced(function* (query = {}) {
235
235
  const value = yield* api.input(AgentRunListQuery, query, "agent-run-list");
236
236
  const page = yield* api.request("GET", `/v1/agents/runs${api.query(value)}`, ProviderPage(AgentRun), "agent-run-list");
237
237
  return {
238
238
  items: page.data,
239
239
  nextCursor: page.nextCursor ?? void 0
240
240
  };
241
- });
242
- const stopRun = Effect.fn("BrowserbaseAgents.stopRun")(function* (runId) {
241
+ }, span("BrowserbaseAgents.listRuns"));
242
+ const stopRun = Effect.fnUntraced(function* (runId) {
243
243
  const id = yield* api.input(Identifier, runId, "agent-run-stop");
244
244
  return yield* api.request("POST", `${runPath(id)}/stop`, AgentRun, "agent-run-stop").pipe(Effect.flatMap(run("agent-run-stop", true, id)));
245
- });
246
- const messages = Effect.fn("BrowserbaseAgents.messages")(function* (runId, query = {}) {
245
+ }, span("BrowserbaseAgents.stopRun"));
246
+ const messages = Effect.fnUntraced(function* (runId, query = {}) {
247
247
  const id = yield* api.input(Identifier, runId, "agent-run-messages");
248
248
  const value = yield* api.input(AgentMessageQuery, query, "agent-run-messages");
249
249
  const page = yield* api.request("GET", `${runPath(id)}/messages${api.query(value)}`, ProviderMessages, "agent-run-messages");
@@ -256,12 +256,12 @@ var BrowserbaseAgents = class BrowserbaseAgents extends Context.Service()("effec
256
256
  })),
257
257
  nextSince: page.nextSince ?? void 0
258
258
  };
259
- });
260
- const waitForRun = Effect.fn("BrowserbaseAgents.waitForRun")(function* (runId, options) {
259
+ }, span("BrowserbaseAgents.messages"));
260
+ const waitForRun = Effect.fnUntraced(function* (runId, options) {
261
261
  const bounds = yield* api.input(AgentRunWaitOptions, options, "agent-run-wait");
262
262
  const deadline = (yield* now) + bounds.timeoutMillis;
263
263
  for (;;) {
264
- const current = yield* retrieveRun(runId);
264
+ const current = yield* retrieveRun(runId).pipe(Effect.withTracerEnabled(false));
265
265
  if (isTerminalAgentRunStatus(current.status)) return current;
266
266
  const remaining = deadline - (yield* now);
267
267
  if (remaining <= 0) return yield* api.make({
@@ -270,7 +270,7 @@ var BrowserbaseAgents = class BrowserbaseAgents extends Context.Service()("effec
270
270
  });
271
271
  yield* Effect.sleep(Math.min(bounds.pollIntervalMillis ?? 2e3, remaining));
272
272
  }
273
- });
273
+ }, span("BrowserbaseAgents.waitForRun"));
274
274
  return BrowserbaseAgents.of({
275
275
  create,
276
276
  list,
@@ -1 +1 @@
1
- {"version":3,"file":"Agents.mjs","names":[],"sources":["../src/Agents.ts"],"sourcesContent":["import { Clock, Context, Effect, Layer, Schema } from \"effect\";\n\nimport { BrowserbaseClient } from \"./Client.ts\";\nimport { PlatformError } from \"./Errors.ts\";\nimport { resource } from \"./internal/http/Resource.ts\";\nimport { proxy } from \"./internal/provider/Launch.ts\";\nimport { isContextWriterBusy } from \"./internal/session/ContextWriter.ts\";\nimport { ProxyRule } from \"./Launch.ts\";\nimport { ContextReference, Identifier } from \"./References.ts\";\n\nconst Timestamp = Schema.String.check(Schema.isMaxLength(64));\nconst Cursor = Schema.NonEmptyString.check(Schema.isMaxLength(4096));\nconst JsonObject = Schema.Record(Schema.String, Schema.Json);\nconst Prompt = Schema.String.check(Schema.isMaxLength(100_000));\n\nexport const AgentRunStatus = Schema.Literals([\n \"PENDING\",\n \"RUNNING\",\n \"COMPLETED\",\n \"FAILED\",\n \"STOPPED\",\n \"TIMED_OUT\",\n]);\n\nexport type AgentRunStatus = typeof AgentRunStatus.Type;\n\nexport const isTerminalAgentRunStatus = (status: AgentRunStatus): boolean =>\n status !== \"PENDING\" && status !== \"RUNNING\";\n\nexport class AgentMetadata extends Schema.Class<AgentMetadata>(\"BrowserbaseAgentMetadata\")({\n agentId: Identifier,\n name: Schema.String.check(Schema.isMaxLength(255)),\n systemPrompt: Schema.optionalKey(Prompt),\n resultSchema: Schema.optionalKey(JsonObject),\n createdAt: Timestamp,\n updatedAt: Timestamp,\n}) {}\n\nexport class AgentRun extends Schema.Class<AgentRun>(\"BrowserbaseAgentRun\")({\n runId: Identifier,\n agentId: Schema.optionalKey(Identifier),\n task: Prompt,\n status: AgentRunStatus,\n sessionId: Schema.optionalKey(Identifier),\n sandboxId: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(256))),\n resultSchema: Schema.optionalKey(JsonObject),\n result: Schema.optionalKey(JsonObject),\n cause: Schema.optionalKey(\n Schema.Struct({\n code: Schema.String.check(Schema.isMaxLength(64)),\n message: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(500))),\n }),\n ),\n startedAt: Schema.optionalKey(Timestamp),\n endedAt: Schema.optionalKey(Timestamp),\n createdAt: Timestamp,\n updatedAt: Timestamp,\n}) {}\n\nexport class AgentRunMessage extends Schema.Class<AgentRunMessage>(\"BrowserbaseAgentRunMessage\")({\n id: Schema.String.check(Schema.isMaxLength(256)),\n createdAt: Timestamp,\n role: Schema.Literals([\"assistant\", \"tool\"]),\n content: Schema.Json,\n}) {}\n\nexport const AgentDefinition = Schema.Struct({\n name: Schema.NonEmptyString.check(Schema.isMaxLength(255)),\n systemPrompt: Schema.optionalKey(Prompt),\n resultSchema: Schema.optionalKey(JsonObject),\n});\n\nexport type AgentDefinition = typeof AgentDefinition.Type;\n\nexport const AgentUpdate = Schema.Struct({\n name: Schema.optionalKey(AgentDefinition.fields.name),\n systemPrompt: Schema.optionalKey(Prompt),\n resultSchema: Schema.optionalKey(JsonObject),\n});\n\nexport type AgentUpdate = typeof AgentUpdate.Type;\n\nexport const AgentRunRequest = Schema.Struct({\n task: Schema.NonEmptyString.check(Schema.isMaxLength(100_000)),\n agentId: Schema.optionalKey(Identifier),\n resultSchema: Schema.optionalKey(JsonObject),\n variables: Schema.optionalKey(\n Schema.Record(\n Schema.String.check(Schema.isMaxLength(128)),\n Schema.Struct({\n value: Schema.String.check(Schema.isMaxLength(100_000)),\n description: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(1024))),\n }),\n ),\n ),\n browserSettings: Schema.optionalKey(\n Schema.Struct({\n /**\n * A persisting run writes the Context from Browserbase's side, outside\n * `ContextCoordination.withWriter`. It is refused while a local writer holds the\n * Context, but nothing stops a later local writer from racing the hosted run.\n */\n context: Schema.optionalKey(\n Schema.Struct({ reference: ContextReference, persist: Schema.Boolean }),\n ),\n proxies: Schema.optionalKey(\n Schema.Union([Schema.Boolean, Schema.Array(ProxyRule).check(Schema.isMaxLength(64))]),\n ),\n verified: Schema.optionalKey(Schema.Boolean),\n }),\n ),\n});\n\nexport type AgentRunRequest = typeof AgentRunRequest.Type;\n\nconst Window = {\n startAt: Schema.optionalKey(Timestamp),\n endAt: Schema.optionalKey(Timestamp),\n cursor: Schema.optionalKey(Cursor),\n};\n\nexport const AgentListQuery = Schema.Struct({\n ...Window,\n limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 1000 }))),\n});\n\nexport type AgentListQuery = typeof AgentListQuery.Type;\n\nexport const AgentRunListQuery = Schema.Struct({\n ...Window,\n status: Schema.optionalKey(AgentRunStatus),\n agentId: Schema.optionalKey(Identifier),\n limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 1000 }))),\n});\n\nexport type AgentRunListQuery = typeof AgentRunListQuery.Type;\n\nexport const AgentMessageQuery = Schema.Struct({\n since: Schema.optionalKey(Cursor),\n limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))),\n all: Schema.optionalKey(Schema.Boolean),\n});\n\nexport type AgentMessageQuery = typeof AgentMessageQuery.Type;\n\nexport const AgentRunWaitOptions = Schema.Struct({\n timeoutMillis: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 21_600_000 })),\n pollIntervalMillis: Schema.optionalKey(\n Schema.Int.check(Schema.isBetween({ minimum: 250, maximum: 60_000 })),\n ),\n});\n\nexport type AgentRunWaitOptions = typeof AgentRunWaitOptions.Type;\n\nexport interface Page<A> {\n readonly items: ReadonlyArray<A>;\n readonly nextCursor: string | undefined;\n}\n\nexport interface AgentMessages {\n readonly messages: ReadonlyArray<AgentRunMessage>;\n readonly nextSince: string | undefined;\n}\n\nconst ProviderAgent = Schema.Struct({\n agentId: Identifier,\n name: AgentMetadata.fields.name,\n systemPrompt: Schema.optionalKey(Prompt),\n resultSchema: Schema.optionalKey(JsonObject),\n createdAt: Timestamp,\n updatedAt: Timestamp,\n});\n\nconst ProviderPage = <S extends Schema.Top>(item: S) =>\n Schema.Struct({\n data: Schema.Array(item).check(Schema.isMaxLength(1000)),\n nextCursor: Schema.optionalKey(Schema.NullOr(Schema.String.check(Schema.isMaxLength(4096)))),\n });\n\nconst ProviderMessages = Schema.Struct({\n data: Schema.Array(\n Schema.Struct({\n id: AgentRunMessage.fields.id,\n createdAt: Timestamp,\n message: Schema.Struct({ role: AgentRunMessage.fields.role, content: Schema.Json }),\n }),\n ).check(Schema.isMaxLength(100)),\n nextSince: Schema.optionalKey(Schema.NullOr(Schema.String.check(Schema.isMaxLength(4096)))),\n});\n\nconst now = Clock.monotonicTimeNanos.pipe(Effect.map((value) => Number(value) / 1_000_000));\n\n/**\n * Browserbase Agents: hosted autonomous runs that allocate their own browser sessions and\n * can incur inference charges. Creating or stopping a run is never retried; a lost reply is\n * `unknown`. A run reply is not a charge or completion receipt.\n */\nexport class BrowserbaseAgents extends Context.Service<\n BrowserbaseAgents,\n {\n readonly create: (definition: AgentDefinition) => Effect.Effect<AgentMetadata, PlatformError>;\n readonly list: (query?: AgentListQuery) => Effect.Effect<Page<AgentMetadata>, PlatformError>;\n readonly retrieve: (agentId: string) => Effect.Effect<AgentMetadata, PlatformError>;\n readonly update: (\n agentId: string,\n update: AgentUpdate,\n ) => Effect.Effect<AgentMetadata, PlatformError>;\n readonly delete: (agentId: string) => Effect.Effect<void, PlatformError>;\n readonly run: (request: AgentRunRequest) => Effect.Effect<AgentRun, PlatformError>;\n readonly retrieveRun: (runId: string) => Effect.Effect<AgentRun, PlatformError>;\n readonly listRuns: (query?: AgentRunListQuery) => Effect.Effect<Page<AgentRun>, PlatformError>;\n readonly stopRun: (runId: string) => Effect.Effect<AgentRun, PlatformError>;\n readonly messages: (\n runId: string,\n query?: AgentMessageQuery,\n ) => Effect.Effect<AgentMessages, PlatformError>;\n /** Polls until the run is terminal. Interrupting the wait does not stop the run. */\n readonly waitForRun: (\n runId: string,\n options: AgentRunWaitOptions,\n ) => Effect.Effect<AgentRun, PlatformError>;\n }\n>()(\"effect-browserbase/Agents\") {\n static readonly layer: Layer.Layer<BrowserbaseAgents, never, BrowserbaseClient> = Layer.effect(\n BrowserbaseAgents,\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n\n const api = resource<PlatformError>(client, (failure) =>\n PlatformError.make({ ...failure, service: \"agents\" }),\n );\n\n const agentPath = (id: string) => `/v1/agents/${api.segment(id)}`;\n const runPath = (id: string) => `/v1/agents/runs/${api.segment(id)}`;\n\n const agent = (operation: PlatformError[\"operation\"], mutation: boolean, expected?: string) =>\n Effect.fnUntraced(function* (value: typeof ProviderAgent.Type) {\n if (expected !== undefined && value.agentId !== expected)\n return yield* api.malformed(operation, mutation);\n\n return AgentMetadata.make(value);\n });\n\n const run = (operation: PlatformError[\"operation\"], mutation: boolean, expected?: string) =>\n Effect.fnUntraced(function* (value: AgentRun) {\n if (expected !== undefined && value.runId !== expected)\n return yield* api.malformed(operation, mutation);\n\n return value;\n });\n\n const create = Effect.fn(\"BrowserbaseAgents.create\")(function* (definition: AgentDefinition) {\n const value = yield* api.input(AgentDefinition, definition, \"agent-create\");\n\n return yield* api\n .request(\"POST\", \"/v1/agents\", ProviderAgent, \"agent-create\", value)\n .pipe(Effect.flatMap(agent(\"agent-create\", true)));\n });\n\n const list = Effect.fn(\"BrowserbaseAgents.list\")(function* (query: AgentListQuery = {}) {\n const value = yield* api.input(AgentListQuery, query, \"agent-list\");\n\n const page = yield* api.request(\n \"GET\",\n `/v1/agents${api.query(value)}`,\n ProviderPage(ProviderAgent),\n \"agent-list\",\n );\n\n return {\n items: page.data.map((row) => AgentMetadata.make(row)),\n nextCursor: page.nextCursor ?? undefined,\n };\n });\n\n const retrieve = Effect.fn(\"BrowserbaseAgents.retrieve\")(function* (agentId: string) {\n const id = yield* api.input(Identifier, agentId, \"agent-retrieve\");\n\n return yield* api\n .request(\"GET\", agentPath(id), ProviderAgent, \"agent-retrieve\")\n .pipe(Effect.flatMap(agent(\"agent-retrieve\", false, id)));\n });\n\n const update = Effect.fn(\"BrowserbaseAgents.update\")(function* (\n agentId: string,\n changes: AgentUpdate,\n ) {\n const id = yield* api.input(Identifier, agentId, \"agent-update\");\n const value = yield* api.input(AgentUpdate, changes, \"agent-update\");\n\n if (Object.keys(value).length === 0) return yield* api.configuration(\"agent-update\");\n\n return yield* api\n .request(\"PATCH\", agentPath(id), ProviderAgent, \"agent-update\", value)\n .pipe(Effect.flatMap(agent(\"agent-update\", true, id)));\n });\n\n const remove = Effect.fn(\"BrowserbaseAgents.delete\")(function* (agentId: string) {\n const id = yield* api.input(Identifier, agentId, \"agent-delete\");\n\n yield* api.remove(agentPath(id), \"agent-delete\");\n });\n\n const start = Effect.fn(\"BrowserbaseAgents.run\")(function* (request: AgentRunRequest) {\n const value = yield* api.input(AgentRunRequest, request, \"agent-run\");\n const settings = value.browserSettings;\n const context = settings?.context;\n\n if (context !== undefined) {\n if (context.reference.projectId !== client.projectId)\n return yield* api.make({\n operation: \"agent-run\",\n reason: \"authorization\",\n outcome: \"undispatched\",\n });\n if (context.persist && isContextWriterBusy(context.reference))\n return yield* api.make({\n operation: \"agent-run\",\n reason: \"active\",\n outcome: \"undispatched\",\n });\n }\n\n const body: Schema.Json = {\n task: value.task,\n ...(value.agentId === undefined ? {} : { agentId: value.agentId }),\n ...(value.resultSchema === undefined ? {} : { resultSchema: value.resultSchema }),\n ...(value.variables === undefined ? {} : { variables: value.variables }),\n ...(settings === undefined\n ? {}\n : {\n browserSettings: {\n ...(context === undefined\n ? {}\n : {\n context: { id: context.reference.contextId, persist: context.persist },\n }),\n ...(settings.proxies === undefined\n ? {}\n : {\n proxies:\n typeof settings.proxies === \"boolean\"\n ? settings.proxies\n : settings.proxies.map(proxy),\n }),\n ...(settings.verified === undefined ? {} : { verified: settings.verified }),\n },\n }),\n };\n\n return yield* api.request(\"POST\", \"/v1/agents/runs\", AgentRun, \"agent-run\", body);\n });\n\n const retrieveRun = Effect.fn(\"BrowserbaseAgents.retrieveRun\")(function* (runId: string) {\n const id = yield* api.input(Identifier, runId, \"agent-run-retrieve\");\n\n return yield* api\n .request(\"GET\", runPath(id), AgentRun, \"agent-run-retrieve\")\n .pipe(Effect.flatMap(run(\"agent-run-retrieve\", false, id)));\n });\n\n const listRuns = Effect.fn(\"BrowserbaseAgents.listRuns\")(function* (\n query: AgentRunListQuery = {},\n ) {\n const value = yield* api.input(AgentRunListQuery, query, \"agent-run-list\");\n\n const page = yield* api.request(\n \"GET\",\n `/v1/agents/runs${api.query(value)}`,\n ProviderPage(AgentRun),\n \"agent-run-list\",\n );\n\n return { items: page.data, nextCursor: page.nextCursor ?? undefined };\n });\n\n const stopRun = Effect.fn(\"BrowserbaseAgents.stopRun\")(function* (runId: string) {\n const id = yield* api.input(Identifier, runId, \"agent-run-stop\");\n\n return yield* api\n .request(\"POST\", `${runPath(id)}/stop`, AgentRun, \"agent-run-stop\")\n .pipe(Effect.flatMap(run(\"agent-run-stop\", true, id)));\n });\n\n const messages = Effect.fn(\"BrowserbaseAgents.messages\")(function* (\n runId: string,\n query: AgentMessageQuery = {},\n ) {\n const id = yield* api.input(Identifier, runId, \"agent-run-messages\");\n const value = yield* api.input(AgentMessageQuery, query, \"agent-run-messages\");\n\n const page = yield* api.request(\n \"GET\",\n `${runPath(id)}/messages${api.query(value)}`,\n ProviderMessages,\n \"agent-run-messages\",\n );\n\n return {\n messages: page.data.map((row) =>\n AgentRunMessage.make({\n id: row.id,\n createdAt: row.createdAt,\n role: row.message.role,\n content: row.message.content,\n }),\n ),\n nextSince: page.nextSince ?? undefined,\n };\n });\n\n const waitForRun = Effect.fn(\"BrowserbaseAgents.waitForRun\")(function* (\n runId: string,\n options: AgentRunWaitOptions,\n ) {\n const bounds = yield* api.input(AgentRunWaitOptions, options, \"agent-run-wait\");\n const deadline = (yield* now) + bounds.timeoutMillis;\n\n for (;;) {\n const current = yield* retrieveRun(runId);\n\n if (isTerminalAgentRunStatus(current.status)) return current;\n const remaining = deadline - (yield* now);\n\n if (remaining <= 0)\n return yield* api.make({ operation: \"agent-run-wait\", reason: \"timeout\" });\n yield* Effect.sleep(Math.min(bounds.pollIntervalMillis ?? 2_000, remaining));\n }\n });\n\n return BrowserbaseAgents.of({\n create,\n list,\n retrieve,\n update,\n delete: remove,\n run: start,\n retrieveRun,\n listRuns,\n stopRun,\n messages,\n waitForRun,\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;;AAUA,MAAM,YAAY,OAAO,OAAO,MAAM,OAAO,YAAY,EAAE,CAAC;AAC5D,MAAM,SAAS,OAAO,eAAe,MAAM,OAAO,YAAY,IAAI,CAAC;AACnE,MAAM,aAAa,OAAO,OAAO,OAAO,QAAQ,OAAO,IAAI;AAC3D,MAAM,SAAS,OAAO,OAAO,MAAM,OAAO,YAAY,GAAO,CAAC;AAE9D,MAAa,iBAAiB,OAAO,SAAS;CAC5C;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAID,MAAa,4BAA4B,WACvC,WAAW,aAAa,WAAW;AAErC,IAAa,gBAAb,cAAmC,OAAO,MAAqB,0BAA0B,CAAC,CAAC;CACzF,SAAS;CACT,MAAM,OAAO,OAAO,MAAM,OAAO,YAAY,GAAG,CAAC;CACjD,cAAc,OAAO,YAAY,MAAM;CACvC,cAAc,OAAO,YAAY,UAAU;CAC3C,WAAW;CACX,WAAW;AACb,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,WAAb,cAA8B,OAAO,MAAgB,qBAAqB,CAAC,CAAC;CAC1E,OAAO;CACP,SAAS,OAAO,YAAY,UAAU;CACtC,MAAM;CACN,QAAQ;CACR,WAAW,OAAO,YAAY,UAAU;CACxC,WAAW,OAAO,YAAY,OAAO,OAAO,MAAM,OAAO,YAAY,GAAG,CAAC,CAAC;CAC1E,cAAc,OAAO,YAAY,UAAU;CAC3C,QA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;GACA;EACF,CAAC;CACH,CAAC,CACH;AACF"}
1
+ {"version":3,"file":"Agents.mjs","names":["Trace.span"],"sources":["../src/Agents.ts"],"sourcesContent":["import { Clock, Context, Effect, Layer, Schema } from \"effect\";\n\nimport { BrowserbaseClient } from \"./Client.ts\";\nimport { PlatformError } from \"./Errors.ts\";\nimport { resource } from \"./internal/http/Resource.ts\";\nimport { proxy } from \"./internal/provider/Launch.ts\";\nimport { isContextWriterBusy } from \"./internal/session/ContextWriter.ts\";\nimport * as Trace from \"./internal/Trace.ts\";\nimport { ProxyRule } from \"./Launch.ts\";\nimport { ContextReference, Identifier } from \"./References.ts\";\n\nconst Timestamp = Schema.String.check(Schema.isMaxLength(64));\nconst Cursor = Schema.NonEmptyString.check(Schema.isMaxLength(4096));\nconst JsonObject = Schema.Record(Schema.String, Schema.Json);\nconst Prompt = Schema.String.check(Schema.isMaxLength(100_000));\n\nexport const AgentRunStatus = Schema.Literals([\n \"PENDING\",\n \"RUNNING\",\n \"COMPLETED\",\n \"FAILED\",\n \"STOPPED\",\n \"TIMED_OUT\",\n]);\n\nexport type AgentRunStatus = typeof AgentRunStatus.Type;\n\nexport const isTerminalAgentRunStatus = (status: AgentRunStatus): boolean =>\n status !== \"PENDING\" && status !== \"RUNNING\";\n\nexport class AgentMetadata extends Schema.Class<AgentMetadata>(\"BrowserbaseAgentMetadata\")({\n agentId: Identifier,\n name: Schema.String.check(Schema.isMaxLength(255)),\n systemPrompt: Schema.optionalKey(Prompt),\n resultSchema: Schema.optionalKey(JsonObject),\n createdAt: Timestamp,\n updatedAt: Timestamp,\n}) {}\n\nexport class AgentRun extends Schema.Class<AgentRun>(\"BrowserbaseAgentRun\")({\n runId: Identifier,\n agentId: Schema.optionalKey(Identifier),\n task: Prompt,\n status: AgentRunStatus,\n sessionId: Schema.optionalKey(Identifier),\n sandboxId: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(256))),\n resultSchema: Schema.optionalKey(JsonObject),\n result: Schema.optionalKey(JsonObject),\n cause: Schema.optionalKey(\n Schema.Struct({\n code: Schema.String.check(Schema.isMaxLength(64)),\n message: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(500))),\n }),\n ),\n startedAt: Schema.optionalKey(Timestamp),\n endedAt: Schema.optionalKey(Timestamp),\n createdAt: Timestamp,\n updatedAt: Timestamp,\n}) {}\n\nexport class AgentRunMessage extends Schema.Class<AgentRunMessage>(\"BrowserbaseAgentRunMessage\")({\n id: Schema.String.check(Schema.isMaxLength(256)),\n createdAt: Timestamp,\n role: Schema.Literals([\"assistant\", \"tool\"]),\n content: Schema.Json,\n}) {}\n\nexport const AgentDefinition = Schema.Struct({\n name: Schema.NonEmptyString.check(Schema.isMaxLength(255)),\n systemPrompt: Schema.optionalKey(Prompt),\n resultSchema: Schema.optionalKey(JsonObject),\n});\n\nexport type AgentDefinition = typeof AgentDefinition.Type;\n\nexport const AgentUpdate = Schema.Struct({\n name: Schema.optionalKey(AgentDefinition.fields.name),\n systemPrompt: Schema.optionalKey(Prompt),\n resultSchema: Schema.optionalKey(JsonObject),\n});\n\nexport type AgentUpdate = typeof AgentUpdate.Type;\n\nexport const AgentRunRequest = Schema.Struct({\n task: Schema.NonEmptyString.check(Schema.isMaxLength(100_000)),\n agentId: Schema.optionalKey(Identifier),\n resultSchema: Schema.optionalKey(JsonObject),\n variables: Schema.optionalKey(\n Schema.Record(\n Schema.String.check(Schema.isMaxLength(128)),\n Schema.Struct({\n value: Schema.String.check(Schema.isMaxLength(100_000)),\n description: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(1024))),\n }),\n ),\n ),\n browserSettings: Schema.optionalKey(\n Schema.Struct({\n /**\n * A persisting run writes the Context from Browserbase's side, outside\n * `ContextCoordination.withWriter`. It is refused while a local writer holds the\n * Context, but nothing stops a later local writer from racing the hosted run.\n */\n context: Schema.optionalKey(\n Schema.Struct({ reference: ContextReference, persist: Schema.Boolean }),\n ),\n proxies: Schema.optionalKey(\n Schema.Union([Schema.Boolean, Schema.Array(ProxyRule).check(Schema.isMaxLength(64))]),\n ),\n verified: Schema.optionalKey(Schema.Boolean),\n }),\n ),\n});\n\nexport type AgentRunRequest = typeof AgentRunRequest.Type;\n\nconst Window = {\n startAt: Schema.optionalKey(Timestamp),\n endAt: Schema.optionalKey(Timestamp),\n cursor: Schema.optionalKey(Cursor),\n};\n\nexport const AgentListQuery = Schema.Struct({\n ...Window,\n limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 1000 }))),\n});\n\nexport type AgentListQuery = typeof AgentListQuery.Type;\n\nexport const AgentRunListQuery = Schema.Struct({\n ...Window,\n status: Schema.optionalKey(AgentRunStatus),\n agentId: Schema.optionalKey(Identifier),\n limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 1000 }))),\n});\n\nexport type AgentRunListQuery = typeof AgentRunListQuery.Type;\n\nexport const AgentMessageQuery = Schema.Struct({\n since: Schema.optionalKey(Cursor),\n limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))),\n all: Schema.optionalKey(Schema.Boolean),\n});\n\nexport type AgentMessageQuery = typeof AgentMessageQuery.Type;\n\nexport const AgentRunWaitOptions = Schema.Struct({\n timeoutMillis: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 21_600_000 })),\n pollIntervalMillis: Schema.optionalKey(\n Schema.Int.check(Schema.isBetween({ minimum: 250, maximum: 60_000 })),\n ),\n});\n\nexport type AgentRunWaitOptions = typeof AgentRunWaitOptions.Type;\n\nexport interface Page<A> {\n readonly items: ReadonlyArray<A>;\n readonly nextCursor: string | undefined;\n}\n\nexport interface AgentMessages {\n readonly messages: ReadonlyArray<AgentRunMessage>;\n readonly nextSince: string | undefined;\n}\n\nconst ProviderAgent = Schema.Struct({\n agentId: Identifier,\n name: AgentMetadata.fields.name,\n systemPrompt: Schema.optionalKey(Prompt),\n resultSchema: Schema.optionalKey(JsonObject),\n createdAt: Timestamp,\n updatedAt: Timestamp,\n});\n\nconst ProviderPage = <S extends Schema.Top>(item: S) =>\n Schema.Struct({\n data: Schema.Array(item).check(Schema.isMaxLength(1000)),\n nextCursor: Schema.optionalKey(Schema.NullOr(Schema.String.check(Schema.isMaxLength(4096)))),\n });\n\nconst ProviderMessages = Schema.Struct({\n data: Schema.Array(\n Schema.Struct({\n id: AgentRunMessage.fields.id,\n createdAt: Timestamp,\n message: Schema.Struct({ role: AgentRunMessage.fields.role, content: Schema.Json }),\n }),\n ).check(Schema.isMaxLength(100)),\n nextSince: Schema.optionalKey(Schema.NullOr(Schema.String.check(Schema.isMaxLength(4096)))),\n});\n\nconst now = Clock.monotonicTimeNanos.pipe(Effect.map((value) => Number(value) / 1_000_000));\n\n/**\n * Browserbase Agents: hosted autonomous runs that allocate their own browser sessions and\n * can incur inference charges. Creating or stopping a run is never retried; a lost reply is\n * `unknown`. A run reply is not a charge or completion receipt.\n */\nexport class BrowserbaseAgents extends Context.Service<\n BrowserbaseAgents,\n {\n readonly create: (definition: AgentDefinition) => Effect.Effect<AgentMetadata, PlatformError>;\n readonly list: (query?: AgentListQuery) => Effect.Effect<Page<AgentMetadata>, PlatformError>;\n readonly retrieve: (agentId: string) => Effect.Effect<AgentMetadata, PlatformError>;\n readonly update: (\n agentId: string,\n update: AgentUpdate,\n ) => Effect.Effect<AgentMetadata, PlatformError>;\n readonly delete: (agentId: string) => Effect.Effect<void, PlatformError>;\n readonly run: (request: AgentRunRequest) => Effect.Effect<AgentRun, PlatformError>;\n readonly retrieveRun: (runId: string) => Effect.Effect<AgentRun, PlatformError>;\n readonly listRuns: (query?: AgentRunListQuery) => Effect.Effect<Page<AgentRun>, PlatformError>;\n readonly stopRun: (runId: string) => Effect.Effect<AgentRun, PlatformError>;\n readonly messages: (\n runId: string,\n query?: AgentMessageQuery,\n ) => Effect.Effect<AgentMessages, PlatformError>;\n /** Polls until the run is terminal. Interrupting the wait does not stop the run. */\n readonly waitForRun: (\n runId: string,\n options: AgentRunWaitOptions,\n ) => Effect.Effect<AgentRun, PlatformError>;\n }\n>()(\"effect-browserbase/Agents\") {\n static readonly layer: Layer.Layer<BrowserbaseAgents, never, BrowserbaseClient> = Layer.effect(\n BrowserbaseAgents,\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n\n const api = resource<PlatformError>(client, (failure) =>\n PlatformError.make({ ...failure, service: \"agents\" }),\n );\n\n const agentPath = (id: string) => `/v1/agents/${api.segment(id)}`;\n const runPath = (id: string) => `/v1/agents/runs/${api.segment(id)}`;\n\n const agent = (operation: PlatformError[\"operation\"], mutation: boolean, expected?: string) =>\n Effect.fnUntraced(function* (value: typeof ProviderAgent.Type) {\n if (expected !== undefined && value.agentId !== expected)\n return yield* api.malformed(operation, mutation);\n\n return AgentMetadata.make(value);\n });\n\n const run = (operation: PlatformError[\"operation\"], mutation: boolean, expected?: string) =>\n Effect.fnUntraced(function* (value: AgentRun) {\n if (expected !== undefined && value.runId !== expected)\n return yield* api.malformed(operation, mutation);\n\n return value;\n });\n\n const create = Effect.fnUntraced(function* (definition: AgentDefinition) {\n const value = yield* api.input(AgentDefinition, definition, \"agent-create\");\n\n return yield* api\n .request(\"POST\", \"/v1/agents\", ProviderAgent, \"agent-create\", value)\n .pipe(Effect.flatMap(agent(\"agent-create\", true)));\n }, Trace.span(\"BrowserbaseAgents.create\"));\n\n const list = Effect.fnUntraced(function* (query: AgentListQuery = {}) {\n const value = yield* api.input(AgentListQuery, query, \"agent-list\");\n\n const page = yield* api.request(\n \"GET\",\n `/v1/agents${api.query(value)}`,\n ProviderPage(ProviderAgent),\n \"agent-list\",\n );\n\n return {\n items: page.data.map((row) => AgentMetadata.make(row)),\n nextCursor: page.nextCursor ?? undefined,\n };\n }, Trace.span(\"BrowserbaseAgents.list\"));\n\n const retrieve = Effect.fnUntraced(function* (agentId: string) {\n const id = yield* api.input(Identifier, agentId, \"agent-retrieve\");\n\n return yield* api\n .request(\"GET\", agentPath(id), ProviderAgent, \"agent-retrieve\")\n .pipe(Effect.flatMap(agent(\"agent-retrieve\", false, id)));\n }, Trace.span(\"BrowserbaseAgents.retrieve\"));\n\n const update = Effect.fnUntraced(function* (agentId: string, changes: AgentUpdate) {\n const id = yield* api.input(Identifier, agentId, \"agent-update\");\n const value = yield* api.input(AgentUpdate, changes, \"agent-update\");\n\n if (Object.keys(value).length === 0) return yield* api.configuration(\"agent-update\");\n\n return yield* api\n .request(\"PATCH\", agentPath(id), ProviderAgent, \"agent-update\", value)\n .pipe(Effect.flatMap(agent(\"agent-update\", true, id)));\n }, Trace.span(\"BrowserbaseAgents.update\"));\n\n const remove = Effect.fnUntraced(function* (agentId: string) {\n const id = yield* api.input(Identifier, agentId, \"agent-delete\");\n\n yield* api.remove(agentPath(id), \"agent-delete\");\n }, Trace.span(\"BrowserbaseAgents.delete\"));\n\n const start = Effect.fnUntraced(function* (request: AgentRunRequest) {\n const value = yield* api.input(AgentRunRequest, request, \"agent-run\");\n const settings = value.browserSettings;\n const context = settings?.context;\n\n if (context !== undefined) {\n if (context.reference.projectId !== client.projectId)\n return yield* api.make({\n operation: \"agent-run\",\n reason: \"authorization\",\n outcome: \"undispatched\",\n });\n if (context.persist && isContextWriterBusy(context.reference))\n return yield* api.make({\n operation: \"agent-run\",\n reason: \"active\",\n outcome: \"undispatched\",\n });\n }\n\n const body: Schema.Json = {\n task: value.task,\n ...(value.agentId === undefined ? {} : { agentId: value.agentId }),\n ...(value.resultSchema === undefined ? {} : { resultSchema: value.resultSchema }),\n ...(value.variables === undefined ? {} : { variables: value.variables }),\n ...(settings === undefined\n ? {}\n : {\n browserSettings: {\n ...(context === undefined\n ? {}\n : {\n context: { id: context.reference.contextId, persist: context.persist },\n }),\n ...(settings.proxies === undefined\n ? {}\n : {\n proxies:\n typeof settings.proxies === \"boolean\"\n ? settings.proxies\n : settings.proxies.map(proxy),\n }),\n ...(settings.verified === undefined ? {} : { verified: settings.verified }),\n },\n }),\n };\n\n return yield* api.request(\"POST\", \"/v1/agents/runs\", AgentRun, \"agent-run\", body);\n }, Trace.span(\"BrowserbaseAgents.run\"));\n\n const retrieveRun = Effect.fnUntraced(function* (runId: string) {\n const id = yield* api.input(Identifier, runId, \"agent-run-retrieve\");\n\n return yield* api\n .request(\"GET\", runPath(id), AgentRun, \"agent-run-retrieve\")\n .pipe(Effect.flatMap(run(\"agent-run-retrieve\", false, id)));\n }, Trace.span(\"BrowserbaseAgents.retrieveRun\"));\n\n const listRuns = Effect.fnUntraced(function* (query: AgentRunListQuery = {}) {\n const value = yield* api.input(AgentRunListQuery, query, \"agent-run-list\");\n\n const page = yield* api.request(\n \"GET\",\n `/v1/agents/runs${api.query(value)}`,\n ProviderPage(AgentRun),\n \"agent-run-list\",\n );\n\n return { items: page.data, nextCursor: page.nextCursor ?? undefined };\n }, Trace.span(\"BrowserbaseAgents.listRuns\"));\n\n const stopRun = Effect.fnUntraced(function* (runId: string) {\n const id = yield* api.input(Identifier, runId, \"agent-run-stop\");\n\n return yield* api\n .request(\"POST\", `${runPath(id)}/stop`, AgentRun, \"agent-run-stop\")\n .pipe(Effect.flatMap(run(\"agent-run-stop\", true, id)));\n }, Trace.span(\"BrowserbaseAgents.stopRun\"));\n\n const messages = Effect.fnUntraced(function* (runId: string, query: AgentMessageQuery = {}) {\n const id = yield* api.input(Identifier, runId, \"agent-run-messages\");\n const value = yield* api.input(AgentMessageQuery, query, \"agent-run-messages\");\n\n const page = yield* api.request(\n \"GET\",\n `${runPath(id)}/messages${api.query(value)}`,\n ProviderMessages,\n \"agent-run-messages\",\n );\n\n return {\n messages: page.data.map((row) =>\n AgentRunMessage.make({\n id: row.id,\n createdAt: row.createdAt,\n role: row.message.role,\n content: row.message.content,\n }),\n ),\n nextSince: page.nextSince ?? undefined,\n };\n }, Trace.span(\"BrowserbaseAgents.messages\"));\n\n const waitForRun = Effect.fnUntraced(function* (runId: string, options: AgentRunWaitOptions) {\n const bounds = yield* api.input(AgentRunWaitOptions, options, \"agent-run-wait\");\n const deadline = (yield* now) + bounds.timeoutMillis;\n\n for (;;) {\n const current = yield* retrieveRun(runId).pipe(Effect.withTracerEnabled(false));\n\n if (isTerminalAgentRunStatus(current.status)) return current;\n const remaining = deadline - (yield* now);\n\n if (remaining <= 0)\n return yield* api.make({ operation: \"agent-run-wait\", reason: \"timeout\" });\n yield* Effect.sleep(Math.min(bounds.pollIntervalMillis ?? 2_000, remaining));\n }\n }, Trace.span(\"BrowserbaseAgents.waitForRun\"));\n\n return BrowserbaseAgents.of({\n create,\n list,\n retrieve,\n update,\n delete: remove,\n run: start,\n retrieveRun,\n listRuns,\n stopRun,\n messages,\n waitForRun,\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;;AAWA,MAAM,YAAY,OAAO,OAAO,MAAM,OAAO,YAAY,EAAE,CAAC;AAC5D,MAAM,SAAS,OAAO,eAAe,MAAM,OAAO,YAAY,IAAI,CAAC;AACnE,MAAM,aAAa,OAAO,OAAO,OAAO,QAAQ,OAAO,IAAI;AAC3D,MAAM,SAAS,OAAO,OAAO,MAAM,OAAO,YAAY,GAAO,CAAC;AAE9D,MAAa,iBAAiB,OAAO,SAAS;CAC5C;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAID,MAAa,4BAA4B,WACvC,WAAW,aAAa,WAAW;AAErC,IAAa,gBAAb,cAAmC,OAAO,MAAqB,0BAA0B,CAAC,CAAC;CACzF,SAAS;CACT,MAAM,OAAO,OAAO,MAAM,OAAO,YAAY,GAAG,CAAC;CACjD,cAAc,OAAO,YAAY,MAAM;CACvC,cAAc,OAAO,YAAY,UAAU;CAC3C,WAAW;CACX,WAAW;AACb,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,WAAb,cAA8B,OAAO,MAAgB,qBAAqB,CAAC,CAAC;CAC1E,OAAO;CACP,SAAS,OAAO,YAAY,UAAU;CACtC,MAAM;CACN,QAAQ;CACR,WAAW,OAAO,YAAY,UAAU;CACxC,WAAW,OAAO,YAAY,OAAO,OAAO,MAAM,OAAO,YAAY,GAAG,CAAC,CAAC;CAC1E,cAAc,OAA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E;EACF,GAAGA,KAAW,8BAA8B,CAAC;EAE7C,OAAO,kBAAkB,GAAG;GAC1B;GACA;GACA;GACA;GACA,QAAQ;GACR,KAAK;GACL;GACA;GACA;GACA;GACA;EACF,CAAC;CACH,CAAC,CACH;AACF"}
@@ -1,4 +1,4 @@
1
- import { t as acquireRemote } from "./Acquisition-Ca4EE-Fg.mjs";
1
+ import { t as acquireRemote } from "./Acquisition-BOABu_qJ.mjs";
2
2
  import { Effect } from "effect";
3
3
  //#region src/Allocation.ts
4
4
  /**