effect-browserbase 0.2.0-beta.3 → 0.2.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.
- package/README.md +29 -4
- package/dist/Account.d.mts +8 -8
- package/dist/Account.mjs +1 -1
- package/dist/{Acquisition-CAsTTXp4.mjs → Acquisition-CLN6lUeJ.mjs} +2 -2
- package/dist/{Acquisition-CAsTTXp4.mjs.map → Acquisition-CLN6lUeJ.mjs.map} +1 -1
- package/dist/{Agents-5HpTp9YE.d.mts → Agents-CPaTOH_g.d.mts} +3 -2
- package/dist/Agents.d.mts +1 -1
- package/dist/Agents.mjs +2 -1
- package/dist/Agents.mjs.map +1 -1
- package/dist/Allocation.d.mts +1 -1
- package/dist/Allocation.mjs +1 -1
- package/dist/{Browser-DpSajNai.mjs → Browser-Dw0JFTaD.mjs} +3 -3
- package/dist/{Browser-DpSajNai.mjs.map → Browser-Dw0JFTaD.mjs.map} +1 -1
- package/dist/Browser.d.mts +1 -1
- package/dist/Browser.mjs +1 -1
- package/dist/{Downloads-CdhiCO5X.d.mts → Downloads-CX52GOFJ.d.mts} +2 -2
- package/dist/Downloads.d.mts +1 -1
- package/dist/Downloads.mjs +1 -1
- package/dist/{PageFetch-CAMqb5m8.d.mts → PageFetch-CjAM_0DS.d.mts} +4 -3
- package/dist/PageFetch.d.mts +1 -1
- package/dist/PageFetch.mjs +3 -2
- package/dist/PageFetch.mjs.map +1 -1
- package/dist/{Recordings-bVI33sTq.d.mts → Recordings-B9k5aODB.d.mts} +2 -2
- package/dist/Recordings.d.mts +1 -1
- package/dist/Recordings.mjs +1 -1
- package/dist/{Replays-Bo-9xeLz.d.mts → Replays-mV93WGtx.d.mts} +2 -2
- package/dist/Replays.d.mts +1 -1
- package/dist/Replays.mjs +1 -1
- package/dist/{Search-1g6TUem7.d.mts → Search-B64e7g-h.d.mts} +2 -2
- package/dist/Search.d.mts +1 -1
- package/dist/Search.mjs +1 -1
- package/dist/Search.mjs.map +1 -1
- package/dist/{Sessions-suOLSym9.mjs → Sessions-BUoyPcPJ.mjs} +3 -3
- package/dist/Sessions-BUoyPcPJ.mjs.map +1 -0
- package/dist/{Sessions-BpZgjteE.d.mts → Sessions-oJEUmZth.d.mts} +2 -1
- package/dist/Sessions.d.mts +1 -1
- package/dist/Sessions.mjs +1 -1
- package/dist/Testing.mjs +1 -1
- package/dist/{Uploads-C2neBEpj.d.mts → Uploads-C2_bACgv.d.mts} +2 -2
- package/dist/Uploads.d.mts +1 -1
- package/dist/Uploads.mjs +1 -1
- package/package.json +2 -2
- package/dist/Sessions-suOLSym9.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.
|
|
5
|
+
Its host supplies the required `effect-browser` peer, at the same coordinated `0.2.0-beta.5` 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
|
|
|
@@ -270,13 +270,38 @@ What a scripted control plane answers is what this repository has read of the pr
|
|
|
270
270
|
These services share the Client and its rules: strict input decoding, identity-checked replies, 1 MiB reply bounds, mutations that are never retried, and typed failures whose `outcome` says whether a request was sent. They are host APIs; none of them is exposed to a model by the adapter package.
|
|
271
271
|
|
|
272
272
|
- `sessions.logs(reference, { includePayloads? })` returns CDP log entries. Protocol payloads are omitted unless requested, because they carry page content, cookies and typed input.
|
|
273
|
-
- `sessions.liveUrls(reference, ttl?)` issues redacted Live View URLs for any session in the project.
|
|
273
|
+
- `sessions.liveUrls(reference, ttl?)` issues redacted Live View URLs for any session in the project. These URLs are bearer capabilities: Browserbase documents that a holder can watch and control the session. Issuing one does not pause automation; use `beginHandoff` when the owner must suspend its own operations for an operator. See Browserbase's [Session Live URLs API](https://docs.browserbase.com/reference/api/session-live-urls) and [Session Live View guide](https://docs.browserbase.com/platform/browser/observability/session-live-view).
|
|
274
274
|
- `downloads.list(reference, query)` filters by filename, MIME type, size and creation time at the provider. `downloads.delete` first proves that the file belongs to the session.
|
|
275
275
|
- `projects` reads the Client's project and its usage. `certificates` registers proxy CA certificates for `proxySettings.caCertificates`.
|
|
276
|
-
- `search` and `page-fetch`
|
|
276
|
+
- `search` and `page-fetch` call Browserbase's Search and Fetch APIs. `agents` starts, observes and stops hosted agent runs. `functions` invokes and observes deployed Functions; deployment stays with Browserbase's CLI. `webhooks` manages endpoints and returns signing secrets as `Redacted`.
|
|
277
|
+
|
|
278
|
+
The Live View `ttl` is a requested TTL in seconds. This client accepts positive safe integers from 1 through 21,600 and reports the request as `requestedTtlSeconds`; that field is not a provider-issued expiration receipt. The pinned SDK documents `expiresIn` as optional with a 21,600-second maximum, and says omission lets the URLs expire with the session. The published debug-route schema currently lists the session ID path parameter but omits `expiresIn`. Neither source establishes a provider minimum, so the session-create `timeout` minimum does not apply here and this package does not claim that a one-second request is accepted or honored.
|
|
279
|
+
|
|
280
|
+
Browserbase's read-only embed example applies `pointer-events: none` to the iframe. That disables pointer interaction through that embed; it does not turn the Live View URL into a read-only capability. Keep the URL private to the intended operator. The provider's `debuggerUrl` is its bordered Live View variant, with the Live View navbar shown by default; its `navbar=false` option hides that provider UI, not native browser chrome.
|
|
277
281
|
|
|
278
282
|
An agent run or Function invocation that persists a Context writes it from Browserbase's side, outside `ContextCoordination.withWriter`. It is refused while a local writer holds that Context, but nothing stops a later local writer from racing the hosted run.
|
|
279
283
|
|
|
284
|
+
## Usage observations and allowances
|
|
285
|
+
|
|
286
|
+
`BrowserbaseProjects.usage` returns the Client project's `browserMinutes` and `proxyBytes`, with no billing period or as-of time. The [usage observation example](examples/usage-observation.ts) timestamps each sample with the Effect Clock **after** the decoded reply: “observed by this host,” not “current in Browserbase's ledger.” Reporting lag, adjustments and resets are unspecified, and session times and proxy bytes do not establish billable units.
|
|
287
|
+
|
|
288
|
+
| Resource | Unit and scope | Available source | Period, rounding and remaining unknowns |
|
|
289
|
+
| ----------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
290
|
+
| Browser time | Minutes, one project | `BrowserbaseProjects.usage.browserMinutes`; session timestamps are diagnostic | The API supplies no period or as-of time. [Plan billing](https://docs.browserbase.com/account/billing/plans) rounds per session with a one-minute minimum; whether the API value is already rounded is unspecified. Reporting lag and paid-plan reset date are unknown. |
|
|
291
|
+
| Proxy traffic | Bytes, one project or session | Project usage and `SessionMetadata.proxyBytes` | The API supplies no period or as-of time. Billing rounds MB with a one-MB minimum per session; the mapping from reported bytes to billed units and reporting lag are unspecified. |
|
|
292
|
+
| Search | Calls, plan/account allowance | Host observation of `BrowserbaseSearch.web` only | The [Project Usage API](https://docs.browserbase.com/reference/api/get-project-usage) has no Search counter or billing period. Other writers, failure billing, reporting lag and paid-plan reset date are unknown. |
|
|
293
|
+
| Fetch and Extract | Calls, plan/account allowance; format and proxy choice matter | Host observation of `BrowserbasePageFetch.fetch` only | The Project Usage API has no Fetch or Extract counter or billing period. Provider classification and billing of failed or uncertain calls, other writers, reporting lag and reset date are unknown. |
|
|
294
|
+
| Agents | Calls, plan/account allowance | Host observation of `BrowserbaseAgents.run`; its reply can represent a pending run | The Project Usage API has no Agent counter. Run completion, inference charges, failure billing, other writers, period and reset date are not established by a run reply. |
|
|
295
|
+
| Capacity | Concurrent sessions, session duration, creation rate, Search/Fetch requests per second | Project metadata and [plan limits](https://docs.browserbase.com/account/billing/plans) | These are operational limits, not a consumed monthly allowance or a price. `effect-browser`'s action budget is likewise local policy. |
|
|
296
|
+
|
|
297
|
+
The example's `observe(attempt, journal)` wraps the host's own Search, Fetch or Agent-run Effect, such as `search.web(query)`. Through `Effect.acquireUseRelease` it commits a journal intent with its Clock start time before the POST and settles it on exit; `Effect.onExit` alone cannot make the intent durable. Both writes are bounded at two seconds: a failed or late `begin` stops the call with its error or a `Cause.TimeoutError`, a failed or late `finish` logs a fixed warning, and an unsettled intent stays `unknown`. The deadlines are cooperative, and `finish` must be idempotent. One intent covers one attempt: retrying or recovering inside the wrapped Effect would hide POSTs or mislabel a failure.
|
|
298
|
+
|
|
299
|
+
`undispatched` means not sent, `api-reply` means a decoded reply arrived, and `rejected` and `unknown` mean possibly billed; interruptions and defects are `unknown`. `api-reply` replaces the issue's `confirmed`, which reads as a billing confirmation. Observations store only the project, operation, Fetch's requested format and proxy flags, time and outcome. Spans can export journal failure causes, so the host sanitizes them. Metrics may carry the finite operation and outcome values but are not a ledger.
|
|
300
|
+
|
|
301
|
+
No documented Browserbase API reports allowance consumption, so `assessAllowance` returns `Unknown` unless the host supplies a provider total for the same scope, meter and billing period, or when the period is unknown: 720 observed Fetch replies do not mean “280 of 1,000 left.” The host decodes both at its boundary and verifies a total's provenance through its own billing channel. For an owner's browser-minutes alert, `observedUsageChange` reports the host-observed change between two samples of one project and whether it reached a decoded `BrowserMinutesThreshold`, or `Unknown` after a counter reset.
|
|
302
|
+
|
|
303
|
+
Rates are outside this package's runtime contract. As reviewed on 25 September 2026, the [Startup pricing card](https://www.browserbase.com/pricing) says $1 per 1,000 unproxied Fetch calls after the included quantity, while its comparison table and the [plan guide](https://docs.browserbase.com/account/billing/plans) say $0.50. The repository maintainer should compare those two sources at least monthly and when the [provider changelog](https://www.browserbase.com/changelog) announces a change, notify maintainers through an issue when they disagree or change materially, and check account billing before updating an example. A webpage is not an automatic rate feed; no price or USD calculator is shipped here.
|
|
304
|
+
|
|
280
305
|
## Public entry points
|
|
281
306
|
|
|
282
307
|
- `client` — one immutable account, transport and approved artifact origins.
|
|
@@ -295,7 +320,7 @@ An agent run or Function invocation that persists a Context writes it from Brows
|
|
|
295
320
|
- `search`, `page-fetch`, `agents`, `functions`, `webhooks` — the Browserbase platform APIs outside a browser session.
|
|
296
321
|
- `testing` — a scripted control plane as `fetch`, and the real account and browser Layers composed over it and over the scripted engine from `effect-browser/testing`.
|
|
297
322
|
|
|
298
|
-
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
|
|
323
|
+
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.
|
|
299
324
|
|
|
300
325
|
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.
|
|
301
326
|
|
package/dist/Account.d.mts
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import { ClientError } from "./Errors.mjs";
|
|
2
2
|
import { r as ClientOptions, t as BrowserbaseClient } from "./Client-B_f6bBLT.mjs";
|
|
3
|
-
import { p as BrowserbaseAgents } from "./Agents-
|
|
3
|
+
import { p as BrowserbaseAgents } from "./Agents-CPaTOH_g.mjs";
|
|
4
4
|
import { t as BrowserbaseCertificates } from "./Certificates-D4NQmyeA.mjs";
|
|
5
5
|
import { t as BrowserbaseContexts } from "./Contexts-DqdL7cyX.mjs";
|
|
6
|
-
import { t as BrowserbaseSessions } from "./Sessions-
|
|
7
|
-
import { t as BrowserbaseDownloads } from "./Downloads-
|
|
6
|
+
import { t as BrowserbaseSessions } from "./Sessions-oJEUmZth.mjs";
|
|
7
|
+
import { t as BrowserbaseDownloads } from "./Downloads-CX52GOFJ.mjs";
|
|
8
8
|
import { t as BrowserbaseExtensions } from "./Extensions-DBXuVM1f.mjs";
|
|
9
9
|
import { t as BrowserbaseFunctions } from "./Functions-CsKMMUuZ.mjs";
|
|
10
|
-
import { t as BrowserbasePageFetch } from "./PageFetch-
|
|
10
|
+
import { t as BrowserbasePageFetch } from "./PageFetch-CjAM_0DS.mjs";
|
|
11
11
|
import { t as BrowserbaseProjects } from "./Projects-tm5bTDH0.mjs";
|
|
12
|
-
import { t as BrowserbaseRecordings } from "./Recordings-
|
|
13
|
-
import { t as BrowserbaseReplays } from "./Replays-
|
|
14
|
-
import { t as BrowserbaseSearch } from "./Search-
|
|
15
|
-
import { t as BrowserbaseUploads } from "./Uploads-
|
|
12
|
+
import { t as BrowserbaseRecordings } from "./Recordings-B9k5aODB.mjs";
|
|
13
|
+
import { t as BrowserbaseReplays } from "./Replays-mV93WGtx.mjs";
|
|
14
|
+
import { t as BrowserbaseSearch } from "./Search-B64e7g-h.mjs";
|
|
15
|
+
import { t as BrowserbaseUploads } from "./Uploads-C2_bACgv.mjs";
|
|
16
16
|
import { t as BrowserbaseWebhooks } from "./Webhooks-BoeRAxzG.mjs";
|
|
17
17
|
import { Config, Layer } from "effect";
|
|
18
18
|
//#region src/Account.d.ts
|
package/dist/Account.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { t as BrowserbaseClient } from "./Client-4RMKIpL2.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-
|
|
5
|
+
import { t as BrowserbaseSessions } from "./Sessions-BUoyPcPJ.mjs";
|
|
6
6
|
import { BrowserbaseDownloads } from "./Downloads.mjs";
|
|
7
7
|
import { t as BrowserbaseExtensions } from "./Extensions-Dg3jHOf0.mjs";
|
|
8
8
|
import { BrowserbaseFunctions } from "./Functions.mjs";
|
|
@@ -4,7 +4,7 @@ import { t as BrowserbaseClient } from "./Client-4RMKIpL2.mjs";
|
|
|
4
4
|
import { t as compileLaunch } from "./Launch-cAdE2rrZ.mjs";
|
|
5
5
|
import { CleanupIssue, CleanupResult } from "./Cleanup.mjs";
|
|
6
6
|
import { i as requireContextWriterPermit } from "./ContextWriter-oKWFLHuP.mjs";
|
|
7
|
-
import { t as BrowserbaseSessions } from "./Sessions-
|
|
7
|
+
import { t as BrowserbaseSessions } from "./Sessions-BUoyPcPJ.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";
|
|
@@ -232,4 +232,4 @@ const acquireRemote = Effect.fnUntraced(function* (options, local = noLocalConne
|
|
|
232
232
|
//#endregion
|
|
233
233
|
export { reported as a, noLocalConnection as i, reportCleanup as n, makeCleanup as r, acquireRemote as t };
|
|
234
234
|
|
|
235
|
-
//# sourceMappingURL=Acquisition-
|
|
235
|
+
//# sourceMappingURL=Acquisition-CLN6lUeJ.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Acquisition-CAsTTXp4.mjs","names":[],"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\";\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(action, milliseconds).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 return latest;\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 {\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(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(options.onAllocationUncertain(attempt)),\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) yield* reported(Effect.suspend(() => notify(result)));\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),\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 ),\n cleanupResult: Effect.sync(() => Option.fromNullishOr(cleanup)),\n };\n });\n\n return yield* allocate.pipe(\n Effect.onError(() => closeScope),\n Effect.onInterrupt(() => closeScope),\n );\n }),\n );\n});\n\nexport type RemoteAcquisition = Effect.Success<ReturnType<typeof acquireRemote>>;\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,oBAAoB;AASjC,MAAa,uBAAsC;CACjD,iBAAiB;CACjB,eAAe;CACf,gBAAgB;AAClB;;;;;;AAOA,MAAa,cAAc,OAAO,WAAW,WAC3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AW,OAAO,OAAO,oBAAoB,iBAAiB,CAAC,CAAC,GAAG,CAAC,CAAC,KACzE,OAAO,eACL,gBAAgB,KAAK;IAAE;IAAS,SAAS;IAAW,QAAQ;GAAY,CAAC,CAC3E,CACF;GAGA,YAAY,OAAO,OACjB,iBAAiB,KAAK;IACpB,UAAU;IACV,WAAW,SAAS;IACpB,WAAW,SAAS;GACtB,CAAC,CACH;GACA,QAAQ,cAAc,SAAS,SAAS;GACxC,IAAI,UAAU,cAAc,OAAO,WACjC,OAAO,OAAO,gBAAgB,KAAK;IACjC;IACA;IACA,SAAS;IACT,QAAQ;GACV,CAAC;GAEH,MAAM,MAAM;GAEZ,OAAO;IACL,WAAW;IACX;IACA;IACA;IACA,gBAAgB;IAChB,aAAa,kBACX,OAAO,cACL,UACI,OAAO,KACL,aAAa,KAAK;KAChB,WAAW;KACX,QAAQ;KACR,SAAS;IACX,CAAC,CACH,IACA,kBAAkB,QAAQ,UAAU,KAAK,aAAa,CAC5D;IACF,SAAS,WAAW,KAClB,OAAO,QACL,OAAO,cACL,YAAY,KAAA,IACR,OAAO,oBAAI,IAAI,MAAM,+CAA+C,CAAC,IACrE,OAAO,QAAQ,OAAO,CAC5B,CACF,CACF;IACA,eAAe,OAAO,WAAW,OAAO,cAAc,OAAO,CAAC;GAChE;EACF,CAEqB,CAAC,CAAC,KACrB,OAAO,cAAc,UAAU,GAC/B,OAAO,kBAAkB,UAAU,CACrC;CACF,CAAC,CACH;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"Acquisition-CLN6lUeJ.mjs","names":[],"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\";\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(action, milliseconds).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 return latest;\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 {\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(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(options.onAllocationUncertain(attempt)),\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) yield* reported(Effect.suspend(() => notify(result)));\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),\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 ),\n cleanupResult: Effect.sync(() => Option.fromNullishOr(cleanup)),\n };\n });\n\n return yield* allocate.pipe(\n Effect.onError(() => closeScope),\n Effect.onInterrupt(() => closeScope),\n );\n }),\n );\n});\n\nexport type RemoteAcquisition = Effect.Success<ReturnType<typeof acquireRemote>>;\n"],"mappings":";;;;;;;;;;;AAWA,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;CA2EJ,OAAO;EACL,OAAA,OA1EmB,OAAO,OAC1B,OAAO,gBACL,OAAO,IAAI,aAAa;GACtB,MAAM,SAAyB,CAAC;GAEhC,MAAM,QACJ,MACA,QACA,iBAEA,YAAY,QAAQ,YAAY,CAAC,CAAC,KAChC,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,KA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AAM,MAAM;GAEZ,OAAO;IACL,WAAW;IACX;IACA;IACA;IACA,gBAAgB;IAChB,aAAa,kBACX,OAAO,cACL,UACI,OAAO,KACL,aAAa,KAAK;KAChB,WAAW;KACX,QAAQ;KACR,SAAS;IACX,CAAC,CACH,IACA,kBAAkB,QAAQ,UAAU,KAAK,aAAa,CAC5D;IACF,SAAS,WAAW,KAClB,OAAO,QACL,OAAO,cACL,YAAY,KAAA,IACR,OAAO,oBAAI,IAAI,MAAM,+CAA+C,CAAC,IACrE,OAAO,QAAQ,OAAO,CAC5B,CACF,CACF;IACA,eAAe,OAAO,WAAW,OAAO,cAAc,OAAO,CAAC;GAChE;EACF,CAEqB,CAAC,CAAC,KACrB,OAAO,cAAc,UAAU,GAC/B,OAAO,kBAAkB,UAAU,CACrC;CACF,CAAC,CACH;AACF,CAAC"}
|
|
@@ -144,7 +144,8 @@ declare const BrowserbaseAgents_base: Context.ServiceClass<BrowserbaseAgents, "e
|
|
|
144
144
|
}>;
|
|
145
145
|
/**
|
|
146
146
|
* Browserbase Agents: hosted autonomous runs that allocate their own browser sessions and
|
|
147
|
-
*
|
|
147
|
+
* can incur inference charges. Creating or stopping a run is never retried; a lost reply is
|
|
148
|
+
* `unknown`. A run reply is not a charge or completion receipt.
|
|
148
149
|
*/
|
|
149
150
|
declare class BrowserbaseAgents extends BrowserbaseAgents_base {
|
|
150
151
|
static readonly layer: Layer.Layer<BrowserbaseAgents, never, BrowserbaseClient>;
|
|
@@ -152,4 +153,4 @@ declare class BrowserbaseAgents extends BrowserbaseAgents_base {
|
|
|
152
153
|
//#endregion
|
|
153
154
|
export { AgentMetadata as a, AgentRunMessage as c, AgentRunWaitOptions as d, AgentUpdate as f, isTerminalAgentRunStatus as h, AgentMessages as i, AgentRunRequest as l, Page as m, AgentListQuery as n, AgentRun as o, BrowserbaseAgents as p, AgentMessageQuery as r, AgentRunListQuery as s, AgentDefinition as t, AgentRunStatus as u };
|
|
154
155
|
export {};
|
|
155
|
-
//# sourceMappingURL=Agents-
|
|
156
|
+
//# sourceMappingURL=Agents-CPaTOH_g.d.mts.map
|
package/dist/Agents.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as AgentMetadata, c as AgentRunMessage, d as AgentRunWaitOptions, f as AgentUpdate, h as isTerminalAgentRunStatus, i as AgentMessages, l as AgentRunRequest, m as Page, n as AgentListQuery, o as AgentRun, p as BrowserbaseAgents, r as AgentMessageQuery, s as AgentRunListQuery, t as AgentDefinition, u as AgentRunStatus } from "./Agents-
|
|
1
|
+
import { a as AgentMetadata, c as AgentRunMessage, d as AgentRunWaitOptions, f as AgentUpdate, h as isTerminalAgentRunStatus, i as AgentMessages, l as AgentRunRequest, m as Page, n as AgentListQuery, o as AgentRun, p as BrowserbaseAgents, r as AgentMessageQuery, s as AgentRunListQuery, t as AgentDefinition, u as AgentRunStatus } from "./Agents-CPaTOH_g.mjs";
|
|
2
2
|
export { AgentDefinition, AgentListQuery, AgentMessageQuery, AgentMessages, AgentMetadata, AgentRun, AgentRunListQuery, AgentRunMessage, AgentRunRequest, AgentRunStatus, AgentRunWaitOptions, AgentUpdate, BrowserbaseAgents, Page, isTerminalAgentRunStatus };
|
|
3
3
|
export {};
|
package/dist/Agents.mjs
CHANGED
|
@@ -149,7 +149,8 @@ const ProviderMessages = Schema.Struct({
|
|
|
149
149
|
const now = Clock.monotonicTimeNanos.pipe(Effect.map((value) => Number(value) / 1e6));
|
|
150
150
|
/**
|
|
151
151
|
* Browserbase Agents: hosted autonomous runs that allocate their own browser sessions and
|
|
152
|
-
*
|
|
152
|
+
* can incur inference charges. Creating or stopping a run is never retried; a lost reply is
|
|
153
|
+
* `unknown`. A run reply is not a charge or completion receipt.
|
|
153
154
|
*/
|
|
154
155
|
var BrowserbaseAgents = class BrowserbaseAgents extends Context.Service()("effect-browserbase/Agents") {
|
|
155
156
|
static layer = Layer.effect(BrowserbaseAgents, Effect.gen(function* () {
|
package/dist/Agents.mjs.map
CHANGED
|
@@ -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 * bill inference. Creating or stopping a run is never retried; a lost reply is `unknown`.\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,QAAQ,OAAO,YAAY,UAAU;CACrC,OAAO,OAAO,YACZ,OAAO,OAAO;EACZ,MAAM,OAAO,OAAO,MAAM,OAAO,YAAY,EAAE,CAAC;EAChD,SAAS,OAAO,YAAY,OAAO,OAAO,MAAM,OAAO,YAAY,GAAG,CAAC,CAAC;CAC1E,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GAAG,4BAA4B,CAAC,CAAC,WACvD,OACA,QAA2B,CAAC,GAC5B;GACA,MAAM,KAAK,OAAO,IAAI,MAAM,YAAY,OAAO,oBAAoB;GACnE,MAAM,QAAQ,OAAO,IAAI,MAAM,mBAAmB,OAAO,oBAAoB;GAE7E,MAAM,OAAO,OAAO,IAAI,QACtB,OACA,GAAG,QAAQ,EAAE,EAAE,WAAW,IAAI,MAAM,KAAK,KACzC,kBACA,oBACF;GAEA,OAAO;IACL,UAAU,KAAK,KAAK,KAAK,QACvB,gBAAgB,KAAK;KACnB,IAAI,IAAI;KACR,WAAW,IAAI;KACf,MAAM,IAAI,QAAQ;KAClB,SAAS,IAAI,QAAQ;IACvB,CAAC,CACH;IACA,WAAW,KAAK,aAAa,KAAA;GAC/B;EACF,CAAC;EAED,MAAM,aAAa,OAAO,GAAG,8BAA8B,CAAC,CAAC,WAC3D,OACA,SACA;GACA,MAAM,SAAS,OAAO,IAAI,MAAM,qBAAqB,SAAS,gBAAgB;GAC9E,MAAM,YAAY,OAAO,OAAO,OAAO;GAEvC,SAAS;IACP,MAAM,UAAU,OAAO,YAAY,KAAK;IAExC,IAAI,yBAAyB,QAAQ,MAAM,GAAG,OAAO;IACrD,MAAM,YAAY,YAAY,OAAO;IAErC,IAAI,aAAa,GACf,OAAO,OAAO,IAAI,KAAK;KAAE,WAAW;KAAkB,QAAQ;IAAU,CAAC;IAC3E,OAAO,OAAO,MAAM,KAAK,IAAI,OAAO,sBAAsB,KAAO,SAAS,CAAC;GAC7E;EACF,CAAC;EAED,OAAO,kBAAkB,GAAG;GAC1B;GACA;GACA;GACA;GACA,QAAQ;GACR,KAAK;GACL;GACA;GACA;GACA;GACA;EACF,CAAC;CACH,CAAC,CACH;AACF"}
|
|
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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AAI,MAAM,mBAAmB,OAAO,oBAAoB;GAE7E,MAAM,OAAO,OAAO,IAAI,QACtB,OACA,GAAG,QAAQ,EAAE,EAAE,WAAW,IAAI,MAAM,KAAK,KACzC,kBACA,oBACF;GAEA,OAAO;IACL,UAAU,KAAK,KAAK,KAAK,QACvB,gBAAgB,KAAK;KACnB,IAAI,IAAI;KACR,WAAW,IAAI;KACf,MAAM,IAAI,QAAQ;KAClB,SAAS,IAAI,QAAQ;IACvB,CAAC,CACH;IACA,WAAW,KAAK,aAAa,KAAA;GAC/B;EACF,CAAC;EAED,MAAM,aAAa,OAAO,GAAG,8BAA8B,CAAC,CAAC,WAC3D,OACA,SACA;GACA,MAAM,SAAS,OAAO,IAAI,MAAM,qBAAqB,SAAS,gBAAgB;GAC9E,MAAM,YAAY,OAAO,OAAO,OAAO;GAEvC,SAAS;IACP,MAAM,UAAU,OAAO,YAAY,KAAK;IAExC,IAAI,yBAAyB,QAAQ,MAAM,GAAG,OAAO;IACrD,MAAM,YAAY,YAAY,OAAO;IAErC,IAAI,aAAa,GACf,OAAO,OAAO,IAAI,KAAK;KAAE,WAAW;KAAkB,QAAQ;IAAU,CAAC;IAC3E,OAAO,OAAO,MAAM,KAAK,IAAI,OAAO,sBAAsB,KAAO,SAAS,CAAC;GAC7E;EACF,CAAC;EAED,OAAO,kBAAkB,GAAG;GAC1B;GACA;GACA;GACA;GACA,QAAQ;GACR,KAAK;GACL;GACA;GACA;GACA;GACA;EACF,CAAC;CACH,CAAC,CACH;AACF"}
|
package/dist/Allocation.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { a as SessionReference, n as ContextReference, r as ExtensionReference, t as AllocationAttempt } from "./References-DOH3Wu44.mjs";
|
|
2
2
|
import { AllocationError, ContextError } from "./Errors.mjs";
|
|
3
3
|
import { t as BrowserbaseClient } from "./Client-B_f6bBLT.mjs";
|
|
4
|
-
import { t as BrowserbaseSessions } from "./Sessions-
|
|
4
|
+
import { t as BrowserbaseSessions } from "./Sessions-oJEUmZth.mjs";
|
|
5
5
|
import { n as CleanupResult } from "./Cleanup-DMTDBir8.mjs";
|
|
6
6
|
import { n as ContextWriterPermit } from "./WriterFacts-BBJRDZYY.mjs";
|
|
7
7
|
import "./ContextCoordination.mjs";
|
package/dist/Allocation.mjs
CHANGED
|
@@ -3,10 +3,10 @@ import { DownloadObservation } from "./Transfers.mjs";
|
|
|
3
3
|
import { t as BrowserbaseClient } from "./Client-4RMKIpL2.mjs";
|
|
4
4
|
import { r as isList } from "./Launch-cAdE2rrZ.mjs";
|
|
5
5
|
import { isTerminalSessionStatus } from "./SessionData.mjs";
|
|
6
|
-
import { a as issueLiveView, o as browserRequestFailure, t as BrowserbaseSessions } from "./Sessions-
|
|
6
|
+
import { a as issueLiveView, o as browserRequestFailure, t as BrowserbaseSessions } from "./Sessions-BUoyPcPJ.mjs";
|
|
7
7
|
import { t as issuedUpload } from "./Issued-DejqoMYL.mjs";
|
|
8
8
|
import { t as connectionAddress } from "./Connection-sxyxtwlk.mjs";
|
|
9
|
-
import { a as reported, i as noLocalConnection, n as reportCleanup, r as makeCleanup, t as acquireRemote } from "./Acquisition-
|
|
9
|
+
import { a as reported, i as noLocalConnection, n as reportCleanup, r as makeCleanup, t as acquireRemote } from "./Acquisition-CLN6lUeJ.mjs";
|
|
10
10
|
import { BrowserbaseBrowserBinding } from "./BrowserBinding.mjs";
|
|
11
11
|
import { Context, Crypto, Effect, Exit, Layer, Option, Schema, Scope } from "effect";
|
|
12
12
|
import { BrowserError, Reasons } from "effect-browser/errors";
|
|
@@ -267,4 +267,4 @@ const projected = (options) => ({
|
|
|
267
267
|
//#endregion
|
|
268
268
|
export { BrowserbaseBrowser as t };
|
|
269
269
|
|
|
270
|
-
//# sourceMappingURL=Browser-
|
|
270
|
+
//# sourceMappingURL=Browser-Dw0JFTaD.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Browser-DpSajNai.mjs","names":[],"sources":["../src/internal/session/Attachment.ts","../src/internal/session/Browser.ts","../src/Browser.ts"],"sourcesContent":["import { Effect, Exit, Option, Scope } from \"effect\";\n\nimport type { CleanupResult } from \"../../Cleanup.ts\";\nimport { BrowserbaseClient } from \"../../Client.ts\";\nimport { SessionError } from \"../../Errors.ts\";\nimport type { SessionReference } from \"../../References.ts\";\nimport { isTerminalSessionStatus } from \"../../SessionData.ts\";\nimport { BrowserbaseSessions } from \"../../Sessions.ts\";\nimport { connectionAddress } from \"../provider/Connection.ts\";\nimport {\n makeCleanup,\n noLocalConnection,\n reported,\n type CleanupLimits,\n type LocalCleanup,\n} from \"./Cleanup.ts\";\nimport { reportCleanup } from \"./Diagnostics.ts\";\n\nexport interface AttachmentOptions {\n readonly reference: SessionReference;\n /** Bounded admission of a session the provider has not finished starting. */\n readonly pendingWaitMillis?: number;\n readonly onCleanup?: (result: CleanupResult) => Effect.Effect<void>;\n}\n\nconst failure = (reason: SessionError[\"reason\"]) =>\n SessionError.make({ operation: \"session-attach\", reason, outcome: \"undispatched\" });\n\n/**\n * Borrowing an already running session. This scope owns its local connection and nothing\n * else: no allocation attempt is made, no release is requested, and no Context-writer\n * authority is claimed. Whoever allocated the session keeps all three.\n */\nexport const attachRemote = Effect.fnUntraced(function* (\n options: AttachmentOptions,\n local: LocalCleanup = noLocalConnection,\n limits?: CleanupLimits,\n) {\n const client = yield* BrowserbaseClient;\n const sessions = yield* BrowserbaseSessions;\n const parent = yield* Scope.Scope;\n const pendingWaitMillis = options.pendingWaitMillis ?? 0;\n\n if (\n !Number.isSafeInteger(pendingWaitMillis) ||\n pendingWaitMillis < 0 ||\n pendingWaitMillis > 600_000\n )\n return yield* failure(\"configuration\");\n\n // The status read validates project authority before anything is borrowed. A terminal\n // session needs a fresh allocation from durable state, never a reattachment.\n const observed = yield* sessions.retrieve(options.reference);\n\n if (isTerminalSessionStatus(observed.status)) return yield* failure(\"expired\");\n if (observed.status !== \"RUNNING\") {\n if (pendingWaitMillis === 0) return yield* failure(\"active\");\n yield* sessions.waitUntilRunning(observed.reference, { timeoutMillis: pendingWaitMillis });\n }\n const reference = observed.reference;\n\n return yield* Effect.uninterruptible(\n Effect.gen(function* () {\n const resourceScope = yield* Scope.make();\n let closing = false;\n let cleanup: CleanupResult | undefined;\n\n const terminate = yield* Effect.cached(\n Effect.uninterruptible(\n Effect.gen(function* () {\n closing = true;\n\n const coordinator = yield* makeCleanup(\n reference,\n \"borrowed\",\n sessions,\n local,\n (result) => {\n cleanup = 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) yield* reported(Effect.suspend(() => notify(result)));\n }\n }),\n ),\n );\n\n const closeScope = yield* Effect.cached(Scope.close(resourceScope, Exit.void));\n\n // Teardown is registered before the first connection, exactly as an owned scope does.\n yield* Scope.addFinalizer(resourceScope, terminate);\n yield* Scope.addFinalizer(parent, closeScope);\n\n return {\n reference,\n status: observed,\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 : // Credentials are fetched fresh: an expiry can race the caller's own read.\n connectionAddress(client, sessions, reference, timeoutMillis),\n ),\n release: closeScope.pipe(\n Effect.andThen(\n Effect.suspend(() =>\n cleanup === undefined\n ? Effect.die(new Error(\"Borrowed session closed without cleanup evidence\"))\n : Effect.succeed(cleanup),\n ),\n ),\n ),\n cleanupResult: Effect.sync(() => Option.fromNullishOr(cleanup)),\n };\n }),\n );\n});\n","import { type Crypto, Effect, Option, type Redacted } from \"effect\";\nimport type { Lifetime, Source } from \"effect-browser/browser-runtime\";\nimport { BrowserError, Reasons } from \"effect-browser/errors\";\n\nimport type { CleanupResult } from \"../../Cleanup.ts\";\nimport { BrowserbaseClient } from \"../../Client.ts\";\nimport type { AllocationError, ContextError, SessionError } from \"../../Errors.ts\";\nimport type { LaunchRecipe } from \"../../Launch.ts\";\nimport type { AllocationAttempt, SessionReference } from \"../../References.ts\";\nimport { BrowserbaseSessions } from \"../../Sessions.ts\";\nimport { issueLiveView, type LiveView } from \"../browser/LiveView.ts\";\nimport { browserRequestFailure } from \"../browser/RequestFailure.ts\";\nimport { acquireRemote } from \"./Acquisition.ts\";\nimport { attachRemote } from \"./Attachment.ts\";\nimport type { ContextWriterPermit } from \"./WriterFacts.ts\";\n\nexport interface RemoteLease extends Lifetime {\n readonly reference: SessionReference;\n readonly closeChecked: Effect.Effect<CleanupResult, BrowserError>;\n readonly attempt?: AllocationAttempt;\n readonly release: Effect.Effect<CleanupResult>;\n readonly cleanupResult: Effect.Effect<Option.Option<CleanupResult>>;\n readonly liveView: (ttl: number) => Effect.Effect<LiveView, BrowserError>;\n}\n\ntype RemoteSource<L extends Lifetime, E> = Source<\n L,\n E,\n BrowserbaseClient | BrowserbaseSessions | Crypto.Crypto\n>;\n\n/** A borrowed connection closes without requiring or requesting remote termination. */\nconst checkedCleanup = (\n close: Effect.Effect<CleanupResult>,\n): Effect.Effect<CleanupResult, BrowserError> =>\n close.pipe(\n Effect.filterOrFail(\n (result) =>\n result.local === \"closed\" &&\n result.issues.length === 0 &&\n (result.ownership === \"borrowed\"\n ? result.remote === \"not-owned\"\n : result.remote === \"confirmed\"),\n () =>\n BrowserError.make({\n operation: \"close\",\n reason: Reasons.Provider.make({}),\n outcome: \"unknown\",\n }),\n ),\n );\n\nconst withConnection = <\n A extends {\n readonly reference: SessionReference;\n readonly connection: (\n timeoutMillis: number,\n ) => Effect.Effect<Redacted.Redacted<string>, SessionError>;\n readonly release: Effect.Effect<CleanupResult>;\n readonly cleanupResult: Effect.Effect<Option.Option<CleanupResult>>;\n },\n>(\n acquired: A,\n) => ({\n ...acquired,\n connection: (timeoutMillis: number) =>\n acquired\n .connection(timeoutMillis)\n .pipe(Effect.mapError((error) => browserRequestFailure(\"connect\", error))),\n closeChecked: checkedCleanup(acquired.release),\n controlRetired: acquired.cleanupResult.pipe(\n Effect.map(\n (result) =>\n Option.isSome(result) &&\n result.value.ownership === \"owned\" &&\n result.value.remote === \"confirmed\",\n ),\n ),\n});\n\nexport interface OwnedLease extends RemoteLease {\n readonly attempt: AllocationAttempt;\n}\n\nexport interface OwnedOptions {\n /** The single provider-faithful launch description; the owner adds no second default body. */\n readonly launch: LaunchRecipe;\n /** Required for a persistent context; the writer permit, not this owner, holds that authority. */\n readonly contextWriter?: ContextWriterPermit;\n readonly onCleanup?: (result: CleanupResult) => Effect.Effect<void>;\n readonly onAllocationUncertain?: (attempt: AllocationAttempt) => Effect.Effect<void>;\n}\n\n/** Allocates the session, and therefore owns releasing it. */\nconst providerControls = (\n client: BrowserbaseClient[\"Service\"],\n sessions: BrowserbaseSessions[\"Service\"],\n reference: SessionReference,\n) => ({\n liveView: (ttl: number) => issueLiveView(client, reference, ttl),\n verifyReconnect: sessions.retrieve(reference).pipe(\n Effect.mapError((error) => browserRequestFailure(\"reconnect\", error)),\n Effect.flatMap((status) =>\n status.status === \"RUNNING\"\n ? Effect.void\n : Effect.fail(\n BrowserError.make({\n operation: \"reconnect\",\n reason: Reasons.Expired.make({}),\n outcome: \"undispatched\",\n }),\n ),\n ),\n ),\n});\n\nexport const ownedRemote =\n (\n options: OwnedOptions,\n ): RemoteSource<OwnedLease, AllocationError | BrowserError | ContextError> =>\n (local, lifetimeDeadline) =>\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n const sessions = yield* BrowserbaseSessions;\n\n const acquired = yield* acquireRemote(\n {\n launch: options.launch,\n ...(options.contextWriter === undefined ? {} : { contextWriter: options.contextWriter }),\n allocationDeadline: lifetimeDeadline,\n ...(options.onCleanup === undefined ? {} : { onCleanup: options.onCleanup }),\n ...(options.onAllocationUncertain === undefined\n ? {}\n : { onAllocationUncertain: options.onAllocationUncertain }),\n },\n local,\n );\n\n return {\n ...withConnection(acquired),\n ...providerControls(client, sessions, acquired.reference),\n };\n });\n\n/** Borrows a running session: local connection only, and never a release request. */\nexport const borrowedRemote =\n (options: {\n readonly reference: SessionReference;\n readonly pendingWaitMillis?: number;\n readonly onCleanup?: (result: CleanupResult) => Effect.Effect<void>;\n }): RemoteSource<RemoteLease, SessionError> =>\n (local) =>\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n const sessions = yield* BrowserbaseSessions;\n const acquired = yield* attachRemote(options, local);\n\n return {\n ...withConnection(acquired),\n ...providerControls(client, sessions, acquired.reference),\n };\n });\n","import {\n Context,\n Crypto,\n Effect,\n Layer,\n type Option,\n type Redacted,\n Schema,\n type Scope,\n} from \"effect\";\nimport type { BrowserSession, OpenOptions } from \"effect-browser/browser\";\nimport type {\n ActionResult,\n AutomationOptions,\n BrowserPolicy,\n ClickRequest,\n Observation,\n} from \"effect-browser/browser-data\";\nimport * as BrowserRuntime from \"effect-browser/browser-runtime\";\nimport {\n BrowserError,\n Reasons,\n type BrowserOperation,\n type InitializationError,\n} from \"effect-browser/errors\";\n\nimport { BrowserbaseBrowserBinding } from \"./BrowserBinding.ts\";\nimport type { CleanupResult } from \"./Cleanup.ts\";\nimport { BrowserbaseClient } from \"./Client.ts\";\nimport type { AllocationError, ContextError, SessionError } from \"./Errors.ts\";\nimport type { LiveView } from \"./internal/browser/LiveView.ts\";\nimport { isList } from \"./internal/List.ts\";\nimport { borrowedRemote, ownedRemote, type RemoteLease } from \"./internal/session/Browser.ts\";\nimport type { ContextWriterPermit } from \"./internal/session/WriterFacts.ts\";\nimport { issuedUpload } from \"./internal/upload/Issued.ts\";\nimport type { LaunchRecipe } from \"./Launch.ts\";\nimport type { AllocationAttempt, SessionReference } from \"./References.ts\";\nimport { BrowserbaseSessions } from \"./Sessions.ts\";\nimport { DownloadObservation, type SelectFilesRequest } from \"./Transfers.ts\";\n\nexport type { LiveView } from \"./internal/browser/LiveView.ts\";\nexport type { FileSelection, SelectFilesRequest } from \"./Transfers.ts\";\n\n/** Host configuration. Credentials live in the Client; a model never selects these values. */\nexport interface BrowserOptions extends AutomationOptions {\n readonly launch: LaunchRecipe;\n /** Required whenever the launch recipe persists a context. */\n readonly contextWriter?: ContextWriterPermit;\n readonly onCleanup?: (result: CleanupResult) => Effect.Effect<void>;\n readonly onAllocationUncertain?: (attempt: AllocationAttempt) => Effect.Effect<void>;\n}\n\nexport interface Handoff {\n readonly token: Redacted.Redacted<string>;\n readonly view: LiveView;\n}\n\n/** Browserbase identity, remote artifacts and provider cleanup remain hosted capabilities. */\nexport interface BrowserbaseSession<E = never> extends BrowserSession<E> {\n readonly reference: SessionReference;\n readonly closeChecked: Effect.Effect<CleanupResult, BrowserError>;\n readonly clickForDownload: (\n request: ClickRequest,\n ) => Effect.Effect<DownloadObservation, BrowserError>;\n /** Attaches to an existing file input; an uploaded branch needs a receipt for this session. */\n readonly selectFiles: (request: SelectFilesRequest) => Effect.Effect<ActionResult, BrowserError>;\n /** Registers the chooser observation before the single click that opens it. */\n readonly clickForFileSelection: (\n request: SelectFilesRequest,\n ) => Effect.Effect<ActionResult, BrowserError>;\n readonly liveView: (expiresInSeconds?: number) => Effect.Effect<LiveView, BrowserError>;\n readonly beginHandoff: (expiresInSeconds?: number) => Effect.Effect<Handoff, BrowserError>;\n readonly resume: (\n token: Redacted.Redacted<string>,\n operatorReleasedControl: boolean,\n ) => Effect.Effect<Observation, BrowserError>;\n readonly detach: Effect.Effect<\n { readonly reference: SessionReference; readonly targetId: string },\n BrowserError\n >;\n readonly reconnect: (\n operatorReleasedControl: boolean,\n ) => Effect.Effect<Observation, BrowserError | InitializationError>;\n readonly close: Effect.Effect<CleanupResult>;\n readonly cleanupResult: Effect.Effect<Option.Option<CleanupResult>>;\n}\n\nexport interface AttachRequest<E = never, R = never> extends OpenOptions<E, R> {\n readonly policy: BrowserPolicy;\n /** The exact page to resume; without it the session must have exactly one page. */\n readonly target?: { readonly targetId: string };\n /** Bounded admission of a session the provider has not finished starting. */\n readonly pendingWaitMillis?: number;\n}\n\nexport interface BrowserAcquisition<E = never> {\n readonly reference: SessionReference;\n readonly attempt: AllocationAttempt;\n readonly failure: Effect.Effect<never, E | InitializationError>;\n readonly connect: Effect.Effect<BrowserbaseSession<E>, BrowserError | E | InitializationError>;\n readonly close: Effect.Effect<CleanupResult>;\n}\n\n/** Only receipts issued for this exact provider session may resolve to stored paths. */\nconst selection = (\n request: SelectFilesRequest,\n reference: SessionReference,\n operation: BrowserOperation,\n): Effect.Effect<BrowserRuntime.ResolvedFileSelection, BrowserError> =>\n Effect.suspend(() => {\n if (request.selection._tag === \"Inline\")\n return Effect.succeed<BrowserRuntime.ResolvedFileSelection>({\n _tag: \"Inline\",\n files: request.selection.files,\n });\n\n const uploads = request.selection.uploads;\n\n if (!isList(uploads) || uploads.length < 1 || uploads.length > 8)\n return Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Configuration.make({}),\n outcome: \"undispatched\",\n }),\n );\n const paths: string[] = [];\n\n for (const receipt of uploads) {\n const issued = issuedUpload(receipt);\n\n if (\n issued === undefined ||\n issued.reference.projectId !== reference.projectId ||\n issued.reference.sessionId !== reference.sessionId\n )\n return Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Authorization.make({}),\n outcome: \"undispatched\",\n }),\n );\n paths.push(issued.remotePath);\n }\n\n return Effect.succeed<BrowserRuntime.ResolvedFileSelection>({ _tag: \"Stored\", paths });\n });\n\nconst makeSession = <E>(\n connection: BrowserRuntime.Connection<SessionReference, E>,\n lifetime: RemoteLease,\n): BrowserbaseSession<E> => {\n const { session, operations } = connection;\n\n // Decorating the same object preserves its private capture and page-control associations.\n return Object.assign(session, {\n reference: lifetime.reference,\n closeChecked: session.closeChecked.pipe(Effect.andThen(lifetime.closeChecked)),\n clickForDownload: (request) =>\n operations.clickForDownload(request).pipe(\n Effect.flatMap((event) =>\n Schema.decodeEffect(DownloadObservation)({\n ...event,\n reference: lifetime.reference,\n }).pipe(\n Effect.mapError(() =>\n BrowserError.make({\n operation: \"download-action\",\n reason: Reasons.Malformed.make({}),\n outcome: \"unknown\",\n }),\n ),\n ),\n ),\n ),\n selectFiles: (request) =>\n selection(request, lifetime.reference, \"select-files\").pipe(\n Effect.flatMap((files) =>\n operations.selectFiles({ selector: request.selector, selection: files }),\n ),\n ),\n clickForFileSelection: (request) =>\n selection(request, lifetime.reference, \"file-chooser\").pipe(\n Effect.flatMap((files) =>\n operations.clickForFileSelection({ selector: request.selector, selection: files }),\n ),\n ),\n liveView: (ttl = 60) => operations.liveView(lifetime.liveView(ttl)),\n beginHandoff: (ttl = 60) => operations.beginHandoff(lifetime.liveView(ttl)),\n resume: operations.resume,\n detach: operations.detach,\n reconnect: operations.reconnect,\n close: lifetime.release,\n cleanupResult: lifetime.cleanupResult,\n } satisfies Omit<BrowserbaseSession<E>, Exclude<keyof BrowserSession<E>, \"closeChecked\">>);\n};\n\nexport class BrowserbaseBrowser extends Context.Service<\n BrowserbaseBrowser,\n {\n readonly acquire: <E = never, R = never>(\n policy: BrowserPolicy,\n request?: OpenOptions<E, R>,\n ) => Effect.Effect<\n BrowserAcquisition<E>,\n AllocationError | BrowserError | ContextError,\n Scope.Scope | Exclude<R, Scope.Scope>\n >;\n /** Borrowed control of a session this process did not allocate and will not release. */\n readonly attach: <E = never, R = never>(\n reference: SessionReference,\n request: AttachRequest<E, R>,\n ) => Effect.Effect<\n BrowserbaseSession<E>,\n BrowserError | SessionError | E | InitializationError,\n Scope.Scope | Exclude<R, Scope.Scope>\n >;\n readonly open: <E = never, R = never>(\n policy: BrowserPolicy,\n request?: OpenOptions<E, R>,\n ) => Effect.Effect<\n BrowserbaseSession<E>,\n AllocationError | BrowserError | ContextError | E | InitializationError,\n Scope.Scope | Exclude<R, Scope.Scope>\n >;\n }\n>()(\"effect-browserbase/Browser\") {\n /** Open through the configured account and browser service, in the caller's scope. */\n static open<E = never, R = never>(policy: BrowserPolicy, request?: OpenOptions<E, R>) {\n return Effect.flatMap(BrowserbaseBrowser, (browser) => browser.open(policy, request));\n }\n\n /** Allocate the provider lifetime before connecting, preserving its attempt and cleanup. */\n static acquire<E = never, R = never>(policy: BrowserPolicy, request?: OpenOptions<E, R>) {\n return Effect.flatMap(BrowserbaseBrowser, (browser) => browser.acquire(policy, request));\n }\n\n /** Borrow a provider session without acquiring release authority over it. */\n static attach<E = never, R = never>(reference: SessionReference, request: AttachRequest<E, R>) {\n return Effect.flatMap(BrowserbaseBrowser, (browser) => browser.attach(reference, request));\n }\n\n /** Allocation attempts, connection ids and handoff tokens come from the required `Crypto`. */\n static layer(\n options: BrowserOptions,\n ): Layer.Layer<\n BrowserbaseBrowser,\n BrowserError,\n BrowserbaseClient | BrowserbaseSessions | Crypto.Crypto\n > {\n return Layer.effect(\n BrowserbaseBrowser,\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n const sessions = yield* BrowserbaseSessions;\n const crypto = yield* Crypto.Crypto;\n const binding = yield* BrowserbaseBrowserBinding;\n\n if (options.launch.context?.persist === true && options.contextWriter === undefined)\n return yield* BrowserError.make({\n operation: \"configure\",\n reason: Reasons.ContextLease.make({}),\n outcome: \"undispatched\",\n });\n if (Object.prototype.hasOwnProperty.call(options, \"bootstrap\"))\n return yield* BrowserError.make({\n operation: \"configure\",\n reason: Reasons.Configuration.make({}),\n outcome: \"undispatched\",\n });\n\n const runtime = yield* BrowserRuntime.make({\n implementation: \"browserbase-playwright-cdp\",\n binding,\n automation: projected(options),\n viewport:\n options.launch.viewport._tag === \"Fixed\"\n ? { width: options.launch.viewport.width, height: options.launch.viewport.height }\n : { width: 1280, height: 720 },\n preserveViewport: options.launch.viewport._tag !== \"Fixed\",\n keepAlive: options.launch.keepAlive === true,\n });\n\n const source =\n <L extends BrowserRuntime.Lifetime, E>(\n remote: BrowserRuntime.Source<\n L,\n E,\n BrowserbaseClient | BrowserbaseSessions | Crypto.Crypto\n >,\n ): BrowserRuntime.Source<L, E> =>\n (cleanup, deadline) =>\n remote(cleanup, deadline).pipe(\n Effect.provideService(BrowserbaseClient, client),\n Effect.provideService(BrowserbaseSessions, sessions),\n Effect.provideService(Crypto.Crypto, crypto),\n );\n\n const acquire = Effect.fnUntraced(function* <E = never, R = never>(\n policy: BrowserPolicy,\n request: OpenOptions<E, R> = {},\n ) {\n const acquired = yield* runtime.acquire(\n policy,\n source(\n ownedRemote({\n launch: options.launch,\n ...(options.contextWriter === undefined\n ? {}\n : { contextWriter: options.contextWriter }),\n ...(options.onCleanup === undefined ? {} : { onCleanup: options.onCleanup }),\n ...(options.onAllocationUncertain === undefined\n ? {}\n : { onAllocationUncertain: options.onAllocationUncertain }),\n }),\n ),\n request,\n );\n\n const connected = yield* Effect.cached(\n acquired.connect.pipe(\n Effect.map((connection) => makeSession(connection, acquired.lifetime)),\n ),\n );\n\n return {\n reference: acquired.reference,\n attempt: acquired.lifetime.attempt,\n failure: acquired.failure,\n close: acquired.close,\n connect: acquired.connect.pipe(Effect.andThen(connected)),\n } satisfies BrowserAcquisition<E>;\n });\n\n const attach = Effect.fnUntraced(function* <E = never, R = never>(\n reference: SessionReference,\n request: AttachRequest<E, R>,\n ) {\n const acquired = yield* runtime.acquire(\n request.policy,\n source(\n borrowedRemote({\n reference,\n ...(request.pendingWaitMillis === undefined\n ? {}\n : { pendingWaitMillis: request.pendingWaitMillis }),\n ...(options.onCleanup === undefined ? {} : { onCleanup: options.onCleanup }),\n }),\n ),\n {\n ...(request.bootstrap === undefined ? {} : { bootstrap: request.bootstrap }),\n existingTarget: request.target ?? {},\n },\n );\n\n return yield* acquired.connect.pipe(\n Effect.map((connection) => makeSession(connection, acquired.lifetime)),\n );\n });\n\n return BrowserbaseBrowser.of({\n acquire,\n attach,\n open: (policy, request) =>\n acquire(policy, request).pipe(Effect.flatMap((acquired) => acquired.connect)),\n });\n }),\n );\n }\n}\n\n/** Only the automation fields cross the schema boundary; launch and callbacks are separate. */\nconst projected = (options: BrowserOptions) => ({\n ...(options.maxHostReads === undefined ? {} : { maxHostReads: options.maxHostReads }),\n ...(options.actionTimeoutMillis === undefined\n ? {}\n : { actionTimeoutMillis: options.actionTimeoutMillis }),\n ...(options.maxPages === undefined ? {} : { maxPages: options.maxPages }),\n ...(options.initialPage === undefined ? {} : { initialPage: options.initialPage }),\n ...(options.popupPolicy === undefined ? {} : { popupPolicy: options.popupPolicy }),\n ...(options.dialogPolicy === undefined ? {} : { dialogPolicy: options.dialogPolicy }),\n ...(options.pageControl === undefined ? {} : { pageControl: options.pageControl }),\n});\n"],"mappings":";;;;;;;;;;;;;;AAyBA,MAAM,WAAW,WACf,aAAa,KAAK;CAAE,WAAW;CAAkB;CAAQ,SAAS;AAAe,CAAC;;;;;;AAOpF,MAAa,eAAe,OAAO,WAAW,WAC5C,SACA,QAAsB,mBACtB,QACA;CACA,MAAM,SAAS,OAAO;CACtB,MAAM,WAAW,OAAO;CACxB,MAAM,SAAS,OAAO,MAAM;CAC5B,MAAM,oBAAoB,QAAQ,qBAAqB;CAEvD,IACE,CAAC,OAAO,cAAc,iBAAiB,KACvC,oBAAoB,KACpB,oBAAoB,KAEpB,OAAO,OAAO,QAAQ,eAAe;CAIvC,MAAM,WAAW,OAAO,SAAS,SAAS,QAAQ,SAAS;CAE3D,IAAI,wBAAwB,SAAS,MAAM,GAAG,OAAO,OAAO,QAAQ,SAAS;CAC7E,IAAI,SAAS,WAAW,WAAW;EACjC,IAAI,sBAAsB,GAAG,OAAO,OAAO,QAAQ,QAAQ;EAC3D,OAAO,SAAS,iBAAiB,SAAS,WAAW,EAAE,eAAe,kBAAkB,CAAC;CAC3F;CACA,MAAM,YAAY,SAAS;CAE3B,OAAO,OAAO,OAAO,gBACnB,OAAO,IAAI,aAAa;EACtB,MAAM,gBAAgB,OAAO,MAAM,KAAK;EACxC,IAAI,UAAU;EACd,IAAI;EAEJ,MAAM,YAAY,OAAO,OAAO,OAC9B,OAAO,gBACL,OAAO,IAAI,aAAa;GACtB,UAAU;GAaV,QAAO,OAXoB,YACzB,WACA,YACA,UACA,QACC,WAAW;IACV,UAAU;GACZ,GACA,MACF,EAAA,CAEmB;GACnB,MAAM,SAAS;GACf,MAAM,SAAS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AAQ,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,QAAQ,aAAa;CACnF,GAAI,QAAQ,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,QAAQ,YAAY;AAClF"}
|
|
1
|
+
{"version":3,"file":"Browser-Dw0JFTaD.mjs","names":[],"sources":["../src/internal/session/Attachment.ts","../src/internal/session/Browser.ts","../src/Browser.ts"],"sourcesContent":["import { Effect, Exit, Option, Scope } from \"effect\";\n\nimport type { CleanupResult } from \"../../Cleanup.ts\";\nimport { BrowserbaseClient } from \"../../Client.ts\";\nimport { SessionError } from \"../../Errors.ts\";\nimport type { SessionReference } from \"../../References.ts\";\nimport { isTerminalSessionStatus } from \"../../SessionData.ts\";\nimport { BrowserbaseSessions } from \"../../Sessions.ts\";\nimport { connectionAddress } from \"../provider/Connection.ts\";\nimport {\n makeCleanup,\n noLocalConnection,\n reported,\n type CleanupLimits,\n type LocalCleanup,\n} from \"./Cleanup.ts\";\nimport { reportCleanup } from \"./Diagnostics.ts\";\n\nexport interface AttachmentOptions {\n readonly reference: SessionReference;\n /** Bounded admission of a session the provider has not finished starting. */\n readonly pendingWaitMillis?: number;\n readonly onCleanup?: (result: CleanupResult) => Effect.Effect<void>;\n}\n\nconst failure = (reason: SessionError[\"reason\"]) =>\n SessionError.make({ operation: \"session-attach\", reason, outcome: \"undispatched\" });\n\n/**\n * Borrowing an already running session. This scope owns its local connection and nothing\n * else: no allocation attempt is made, no release is requested, and no Context-writer\n * authority is claimed. Whoever allocated the session keeps all three.\n */\nexport const attachRemote = Effect.fnUntraced(function* (\n options: AttachmentOptions,\n local: LocalCleanup = noLocalConnection,\n limits?: CleanupLimits,\n) {\n const client = yield* BrowserbaseClient;\n const sessions = yield* BrowserbaseSessions;\n const parent = yield* Scope.Scope;\n const pendingWaitMillis = options.pendingWaitMillis ?? 0;\n\n if (\n !Number.isSafeInteger(pendingWaitMillis) ||\n pendingWaitMillis < 0 ||\n pendingWaitMillis > 600_000\n )\n return yield* failure(\"configuration\");\n\n // The status read validates project authority before anything is borrowed. A terminal\n // session needs a fresh allocation from durable state, never a reattachment.\n const observed = yield* sessions.retrieve(options.reference);\n\n if (isTerminalSessionStatus(observed.status)) return yield* failure(\"expired\");\n if (observed.status !== \"RUNNING\") {\n if (pendingWaitMillis === 0) return yield* failure(\"active\");\n yield* sessions.waitUntilRunning(observed.reference, { timeoutMillis: pendingWaitMillis });\n }\n const reference = observed.reference;\n\n return yield* Effect.uninterruptible(\n Effect.gen(function* () {\n const resourceScope = yield* Scope.make();\n let closing = false;\n let cleanup: CleanupResult | undefined;\n\n const terminate = yield* Effect.cached(\n Effect.uninterruptible(\n Effect.gen(function* () {\n closing = true;\n\n const coordinator = yield* makeCleanup(\n reference,\n \"borrowed\",\n sessions,\n local,\n (result) => {\n cleanup = 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) yield* reported(Effect.suspend(() => notify(result)));\n }\n }),\n ),\n );\n\n const closeScope = yield* Effect.cached(Scope.close(resourceScope, Exit.void));\n\n // Teardown is registered before the first connection, exactly as an owned scope does.\n yield* Scope.addFinalizer(resourceScope, terminate);\n yield* Scope.addFinalizer(parent, closeScope);\n\n return {\n reference,\n status: observed,\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 : // Credentials are fetched fresh: an expiry can race the caller's own read.\n connectionAddress(client, sessions, reference, timeoutMillis),\n ),\n release: closeScope.pipe(\n Effect.andThen(\n Effect.suspend(() =>\n cleanup === undefined\n ? Effect.die(new Error(\"Borrowed session closed without cleanup evidence\"))\n : Effect.succeed(cleanup),\n ),\n ),\n ),\n cleanupResult: Effect.sync(() => Option.fromNullishOr(cleanup)),\n };\n }),\n );\n});\n","import { type Crypto, Effect, Option, type Redacted } from \"effect\";\nimport type { Lifetime, Source } from \"effect-browser/browser-runtime\";\nimport { BrowserError, Reasons } from \"effect-browser/errors\";\n\nimport type { CleanupResult } from \"../../Cleanup.ts\";\nimport { BrowserbaseClient } from \"../../Client.ts\";\nimport type { AllocationError, ContextError, SessionError } from \"../../Errors.ts\";\nimport type { LaunchRecipe } from \"../../Launch.ts\";\nimport type { AllocationAttempt, SessionReference } from \"../../References.ts\";\nimport { BrowserbaseSessions } from \"../../Sessions.ts\";\nimport { issueLiveView, type LiveView } from \"../browser/LiveView.ts\";\nimport { browserRequestFailure } from \"../browser/RequestFailure.ts\";\nimport { acquireRemote } from \"./Acquisition.ts\";\nimport { attachRemote } from \"./Attachment.ts\";\nimport type { ContextWriterPermit } from \"./WriterFacts.ts\";\n\nexport interface RemoteLease extends Lifetime {\n readonly reference: SessionReference;\n readonly closeChecked: Effect.Effect<CleanupResult, BrowserError>;\n readonly attempt?: AllocationAttempt;\n readonly release: Effect.Effect<CleanupResult>;\n readonly cleanupResult: Effect.Effect<Option.Option<CleanupResult>>;\n readonly liveView: (ttl: number) => Effect.Effect<LiveView, BrowserError>;\n}\n\ntype RemoteSource<L extends Lifetime, E> = Source<\n L,\n E,\n BrowserbaseClient | BrowserbaseSessions | Crypto.Crypto\n>;\n\n/** A borrowed connection closes without requiring or requesting remote termination. */\nconst checkedCleanup = (\n close: Effect.Effect<CleanupResult>,\n): Effect.Effect<CleanupResult, BrowserError> =>\n close.pipe(\n Effect.filterOrFail(\n (result) =>\n result.local === \"closed\" &&\n result.issues.length === 0 &&\n (result.ownership === \"borrowed\"\n ? result.remote === \"not-owned\"\n : result.remote === \"confirmed\"),\n () =>\n BrowserError.make({\n operation: \"close\",\n reason: Reasons.Provider.make({}),\n outcome: \"unknown\",\n }),\n ),\n );\n\nconst withConnection = <\n A extends {\n readonly reference: SessionReference;\n readonly connection: (\n timeoutMillis: number,\n ) => Effect.Effect<Redacted.Redacted<string>, SessionError>;\n readonly release: Effect.Effect<CleanupResult>;\n readonly cleanupResult: Effect.Effect<Option.Option<CleanupResult>>;\n },\n>(\n acquired: A,\n) => ({\n ...acquired,\n connection: (timeoutMillis: number) =>\n acquired\n .connection(timeoutMillis)\n .pipe(Effect.mapError((error) => browserRequestFailure(\"connect\", error))),\n closeChecked: checkedCleanup(acquired.release),\n controlRetired: acquired.cleanupResult.pipe(\n Effect.map(\n (result) =>\n Option.isSome(result) &&\n result.value.ownership === \"owned\" &&\n result.value.remote === \"confirmed\",\n ),\n ),\n});\n\nexport interface OwnedLease extends RemoteLease {\n readonly attempt: AllocationAttempt;\n}\n\nexport interface OwnedOptions {\n /** The single provider-faithful launch description; the owner adds no second default body. */\n readonly launch: LaunchRecipe;\n /** Required for a persistent context; the writer permit, not this owner, holds that authority. */\n readonly contextWriter?: ContextWriterPermit;\n readonly onCleanup?: (result: CleanupResult) => Effect.Effect<void>;\n readonly onAllocationUncertain?: (attempt: AllocationAttempt) => Effect.Effect<void>;\n}\n\n/** Allocates the session, and therefore owns releasing it. */\nconst providerControls = (\n client: BrowserbaseClient[\"Service\"],\n sessions: BrowserbaseSessions[\"Service\"],\n reference: SessionReference,\n) => ({\n liveView: (ttl: number) => issueLiveView(client, reference, ttl),\n verifyReconnect: sessions.retrieve(reference).pipe(\n Effect.mapError((error) => browserRequestFailure(\"reconnect\", error)),\n Effect.flatMap((status) =>\n status.status === \"RUNNING\"\n ? Effect.void\n : Effect.fail(\n BrowserError.make({\n operation: \"reconnect\",\n reason: Reasons.Expired.make({}),\n outcome: \"undispatched\",\n }),\n ),\n ),\n ),\n});\n\nexport const ownedRemote =\n (\n options: OwnedOptions,\n ): RemoteSource<OwnedLease, AllocationError | BrowserError | ContextError> =>\n (local, lifetimeDeadline) =>\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n const sessions = yield* BrowserbaseSessions;\n\n const acquired = yield* acquireRemote(\n {\n launch: options.launch,\n ...(options.contextWriter === undefined ? {} : { contextWriter: options.contextWriter }),\n allocationDeadline: lifetimeDeadline,\n ...(options.onCleanup === undefined ? {} : { onCleanup: options.onCleanup }),\n ...(options.onAllocationUncertain === undefined\n ? {}\n : { onAllocationUncertain: options.onAllocationUncertain }),\n },\n local,\n );\n\n return {\n ...withConnection(acquired),\n ...providerControls(client, sessions, acquired.reference),\n };\n });\n\n/** Borrows a running session: local connection only, and never a release request. */\nexport const borrowedRemote =\n (options: {\n readonly reference: SessionReference;\n readonly pendingWaitMillis?: number;\n readonly onCleanup?: (result: CleanupResult) => Effect.Effect<void>;\n }): RemoteSource<RemoteLease, SessionError> =>\n (local) =>\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n const sessions = yield* BrowserbaseSessions;\n const acquired = yield* attachRemote(options, local);\n\n return {\n ...withConnection(acquired),\n ...providerControls(client, sessions, acquired.reference),\n };\n });\n","import {\n Context,\n Crypto,\n Effect,\n Layer,\n type Option,\n type Redacted,\n Schema,\n type Scope,\n} from \"effect\";\nimport type { BrowserSession, OpenOptions } from \"effect-browser/browser\";\nimport type {\n ActionResult,\n AutomationOptions,\n BrowserPolicy,\n ClickRequest,\n Observation,\n} from \"effect-browser/browser-data\";\nimport * as BrowserRuntime from \"effect-browser/browser-runtime\";\nimport {\n BrowserError,\n Reasons,\n type BrowserOperation,\n type InitializationError,\n} from \"effect-browser/errors\";\n\nimport { BrowserbaseBrowserBinding } from \"./BrowserBinding.ts\";\nimport type { CleanupResult } from \"./Cleanup.ts\";\nimport { BrowserbaseClient } from \"./Client.ts\";\nimport type { AllocationError, ContextError, SessionError } from \"./Errors.ts\";\nimport type { LiveView } from \"./internal/browser/LiveView.ts\";\nimport { isList } from \"./internal/List.ts\";\nimport { borrowedRemote, ownedRemote, type RemoteLease } from \"./internal/session/Browser.ts\";\nimport type { ContextWriterPermit } from \"./internal/session/WriterFacts.ts\";\nimport { issuedUpload } from \"./internal/upload/Issued.ts\";\nimport type { LaunchRecipe } from \"./Launch.ts\";\nimport type { AllocationAttempt, SessionReference } from \"./References.ts\";\nimport { BrowserbaseSessions } from \"./Sessions.ts\";\nimport { DownloadObservation, type SelectFilesRequest } from \"./Transfers.ts\";\n\nexport type { LiveView } from \"./internal/browser/LiveView.ts\";\nexport type { FileSelection, SelectFilesRequest } from \"./Transfers.ts\";\n\n/** Host configuration. Credentials live in the Client; a model never selects these values. */\nexport interface BrowserOptions extends AutomationOptions {\n readonly launch: LaunchRecipe;\n /** Required whenever the launch recipe persists a context. */\n readonly contextWriter?: ContextWriterPermit;\n readonly onCleanup?: (result: CleanupResult) => Effect.Effect<void>;\n readonly onAllocationUncertain?: (attempt: AllocationAttempt) => Effect.Effect<void>;\n}\n\nexport interface Handoff {\n readonly token: Redacted.Redacted<string>;\n readonly view: LiveView;\n}\n\n/** Browserbase identity, remote artifacts and provider cleanup remain hosted capabilities. */\nexport interface BrowserbaseSession<E = never> extends BrowserSession<E> {\n readonly reference: SessionReference;\n readonly closeChecked: Effect.Effect<CleanupResult, BrowserError>;\n readonly clickForDownload: (\n request: ClickRequest,\n ) => Effect.Effect<DownloadObservation, BrowserError>;\n /** Attaches to an existing file input; an uploaded branch needs a receipt for this session. */\n readonly selectFiles: (request: SelectFilesRequest) => Effect.Effect<ActionResult, BrowserError>;\n /** Registers the chooser observation before the single click that opens it. */\n readonly clickForFileSelection: (\n request: SelectFilesRequest,\n ) => Effect.Effect<ActionResult, BrowserError>;\n readonly liveView: (expiresInSeconds?: number) => Effect.Effect<LiveView, BrowserError>;\n readonly beginHandoff: (expiresInSeconds?: number) => Effect.Effect<Handoff, BrowserError>;\n readonly resume: (\n token: Redacted.Redacted<string>,\n operatorReleasedControl: boolean,\n ) => Effect.Effect<Observation, BrowserError>;\n readonly detach: Effect.Effect<\n { readonly reference: SessionReference; readonly targetId: string },\n BrowserError\n >;\n readonly reconnect: (\n operatorReleasedControl: boolean,\n ) => Effect.Effect<Observation, BrowserError | InitializationError>;\n readonly close: Effect.Effect<CleanupResult>;\n readonly cleanupResult: Effect.Effect<Option.Option<CleanupResult>>;\n}\n\nexport interface AttachRequest<E = never, R = never> extends OpenOptions<E, R> {\n readonly policy: BrowserPolicy;\n /** The exact page to resume; without it the session must have exactly one page. */\n readonly target?: { readonly targetId: string };\n /** Bounded admission of a session the provider has not finished starting. */\n readonly pendingWaitMillis?: number;\n}\n\nexport interface BrowserAcquisition<E = never> {\n readonly reference: SessionReference;\n readonly attempt: AllocationAttempt;\n readonly failure: Effect.Effect<never, E | InitializationError>;\n readonly connect: Effect.Effect<BrowserbaseSession<E>, BrowserError | E | InitializationError>;\n readonly close: Effect.Effect<CleanupResult>;\n}\n\n/** Only receipts issued for this exact provider session may resolve to stored paths. */\nconst selection = (\n request: SelectFilesRequest,\n reference: SessionReference,\n operation: BrowserOperation,\n): Effect.Effect<BrowserRuntime.ResolvedFileSelection, BrowserError> =>\n Effect.suspend(() => {\n if (request.selection._tag === \"Inline\")\n return Effect.succeed<BrowserRuntime.ResolvedFileSelection>({\n _tag: \"Inline\",\n files: request.selection.files,\n });\n\n const uploads = request.selection.uploads;\n\n if (!isList(uploads) || uploads.length < 1 || uploads.length > 8)\n return Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Configuration.make({}),\n outcome: \"undispatched\",\n }),\n );\n const paths: string[] = [];\n\n for (const receipt of uploads) {\n const issued = issuedUpload(receipt);\n\n if (\n issued === undefined ||\n issued.reference.projectId !== reference.projectId ||\n issued.reference.sessionId !== reference.sessionId\n )\n return Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Authorization.make({}),\n outcome: \"undispatched\",\n }),\n );\n paths.push(issued.remotePath);\n }\n\n return Effect.succeed<BrowserRuntime.ResolvedFileSelection>({ _tag: \"Stored\", paths });\n });\n\nconst makeSession = <E>(\n connection: BrowserRuntime.Connection<SessionReference, E>,\n lifetime: RemoteLease,\n): BrowserbaseSession<E> => {\n const { session, operations } = connection;\n\n // Decorating the same object preserves its private capture and page-control associations.\n return Object.assign(session, {\n reference: lifetime.reference,\n closeChecked: session.closeChecked.pipe(Effect.andThen(lifetime.closeChecked)),\n clickForDownload: (request) =>\n operations.clickForDownload(request).pipe(\n Effect.flatMap((event) =>\n Schema.decodeEffect(DownloadObservation)({\n ...event,\n reference: lifetime.reference,\n }).pipe(\n Effect.mapError(() =>\n BrowserError.make({\n operation: \"download-action\",\n reason: Reasons.Malformed.make({}),\n outcome: \"unknown\",\n }),\n ),\n ),\n ),\n ),\n selectFiles: (request) =>\n selection(request, lifetime.reference, \"select-files\").pipe(\n Effect.flatMap((files) =>\n operations.selectFiles({ selector: request.selector, selection: files }),\n ),\n ),\n clickForFileSelection: (request) =>\n selection(request, lifetime.reference, \"file-chooser\").pipe(\n Effect.flatMap((files) =>\n operations.clickForFileSelection({ selector: request.selector, selection: files }),\n ),\n ),\n liveView: (ttl = 60) => operations.liveView(lifetime.liveView(ttl)),\n beginHandoff: (ttl = 60) => operations.beginHandoff(lifetime.liveView(ttl)),\n resume: operations.resume,\n detach: operations.detach,\n reconnect: operations.reconnect,\n close: lifetime.release,\n cleanupResult: lifetime.cleanupResult,\n } satisfies Omit<BrowserbaseSession<E>, Exclude<keyof BrowserSession<E>, \"closeChecked\">>);\n};\n\nexport class BrowserbaseBrowser extends Context.Service<\n BrowserbaseBrowser,\n {\n readonly acquire: <E = never, R = never>(\n policy: BrowserPolicy,\n request?: OpenOptions<E, R>,\n ) => Effect.Effect<\n BrowserAcquisition<E>,\n AllocationError | BrowserError | ContextError,\n Scope.Scope | Exclude<R, Scope.Scope>\n >;\n /** Borrowed control of a session this process did not allocate and will not release. */\n readonly attach: <E = never, R = never>(\n reference: SessionReference,\n request: AttachRequest<E, R>,\n ) => Effect.Effect<\n BrowserbaseSession<E>,\n BrowserError | SessionError | E | InitializationError,\n Scope.Scope | Exclude<R, Scope.Scope>\n >;\n readonly open: <E = never, R = never>(\n policy: BrowserPolicy,\n request?: OpenOptions<E, R>,\n ) => Effect.Effect<\n BrowserbaseSession<E>,\n AllocationError | BrowserError | ContextError | E | InitializationError,\n Scope.Scope | Exclude<R, Scope.Scope>\n >;\n }\n>()(\"effect-browserbase/Browser\") {\n /** Open through the configured account and browser service, in the caller's scope. */\n static open<E = never, R = never>(policy: BrowserPolicy, request?: OpenOptions<E, R>) {\n return Effect.flatMap(BrowserbaseBrowser, (browser) => browser.open(policy, request));\n }\n\n /** Allocate the provider lifetime before connecting, preserving its attempt and cleanup. */\n static acquire<E = never, R = never>(policy: BrowserPolicy, request?: OpenOptions<E, R>) {\n return Effect.flatMap(BrowserbaseBrowser, (browser) => browser.acquire(policy, request));\n }\n\n /** Borrow a provider session without acquiring release authority over it. */\n static attach<E = never, R = never>(reference: SessionReference, request: AttachRequest<E, R>) {\n return Effect.flatMap(BrowserbaseBrowser, (browser) => browser.attach(reference, request));\n }\n\n /** Allocation attempts, connection ids and handoff tokens come from the required `Crypto`. */\n static layer(\n options: BrowserOptions,\n ): Layer.Layer<\n BrowserbaseBrowser,\n BrowserError,\n BrowserbaseClient | BrowserbaseSessions | Crypto.Crypto\n > {\n return Layer.effect(\n BrowserbaseBrowser,\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n const sessions = yield* BrowserbaseSessions;\n const crypto = yield* Crypto.Crypto;\n const binding = yield* BrowserbaseBrowserBinding;\n\n if (options.launch.context?.persist === true && options.contextWriter === undefined)\n return yield* BrowserError.make({\n operation: \"configure\",\n reason: Reasons.ContextLease.make({}),\n outcome: \"undispatched\",\n });\n if (Object.prototype.hasOwnProperty.call(options, \"bootstrap\"))\n return yield* BrowserError.make({\n operation: \"configure\",\n reason: Reasons.Configuration.make({}),\n outcome: \"undispatched\",\n });\n\n const runtime = yield* BrowserRuntime.make({\n implementation: \"browserbase-playwright-cdp\",\n binding,\n automation: projected(options),\n viewport:\n options.launch.viewport._tag === \"Fixed\"\n ? { width: options.launch.viewport.width, height: options.launch.viewport.height }\n : { width: 1280, height: 720 },\n preserveViewport: options.launch.viewport._tag !== \"Fixed\",\n keepAlive: options.launch.keepAlive === true,\n });\n\n const source =\n <L extends BrowserRuntime.Lifetime, E>(\n remote: BrowserRuntime.Source<\n L,\n E,\n BrowserbaseClient | BrowserbaseSessions | Crypto.Crypto\n >,\n ): BrowserRuntime.Source<L, E> =>\n (cleanup, deadline) =>\n remote(cleanup, deadline).pipe(\n Effect.provideService(BrowserbaseClient, client),\n Effect.provideService(BrowserbaseSessions, sessions),\n Effect.provideService(Crypto.Crypto, crypto),\n );\n\n const acquire = Effect.fnUntraced(function* <E = never, R = never>(\n policy: BrowserPolicy,\n request: OpenOptions<E, R> = {},\n ) {\n const acquired = yield* runtime.acquire(\n policy,\n source(\n ownedRemote({\n launch: options.launch,\n ...(options.contextWriter === undefined\n ? {}\n : { contextWriter: options.contextWriter }),\n ...(options.onCleanup === undefined ? {} : { onCleanup: options.onCleanup }),\n ...(options.onAllocationUncertain === undefined\n ? {}\n : { onAllocationUncertain: options.onAllocationUncertain }),\n }),\n ),\n request,\n );\n\n const connected = yield* Effect.cached(\n acquired.connect.pipe(\n Effect.map((connection) => makeSession(connection, acquired.lifetime)),\n ),\n );\n\n return {\n reference: acquired.reference,\n attempt: acquired.lifetime.attempt,\n failure: acquired.failure,\n close: acquired.close,\n connect: acquired.connect.pipe(Effect.andThen(connected)),\n } satisfies BrowserAcquisition<E>;\n });\n\n const attach = Effect.fnUntraced(function* <E = never, R = never>(\n reference: SessionReference,\n request: AttachRequest<E, R>,\n ) {\n const acquired = yield* runtime.acquire(\n request.policy,\n source(\n borrowedRemote({\n reference,\n ...(request.pendingWaitMillis === undefined\n ? {}\n : { pendingWaitMillis: request.pendingWaitMillis }),\n ...(options.onCleanup === undefined ? {} : { onCleanup: options.onCleanup }),\n }),\n ),\n {\n ...(request.bootstrap === undefined ? {} : { bootstrap: request.bootstrap }),\n existingTarget: request.target ?? {},\n },\n );\n\n return yield* acquired.connect.pipe(\n Effect.map((connection) => makeSession(connection, acquired.lifetime)),\n );\n });\n\n return BrowserbaseBrowser.of({\n acquire,\n attach,\n open: (policy, request) =>\n acquire(policy, request).pipe(Effect.flatMap((acquired) => acquired.connect)),\n });\n }),\n );\n }\n}\n\n/** Only the automation fields cross the schema boundary; launch and callbacks are separate. */\nconst projected = (options: BrowserOptions) => ({\n ...(options.maxHostReads === undefined ? {} : { maxHostReads: options.maxHostReads }),\n ...(options.actionTimeoutMillis === undefined\n ? {}\n : { actionTimeoutMillis: options.actionTimeoutMillis }),\n ...(options.maxPages === undefined ? {} : { maxPages: options.maxPages }),\n ...(options.initialPage === undefined ? {} : { initialPage: options.initialPage }),\n ...(options.popupPolicy === undefined ? {} : { popupPolicy: options.popupPolicy }),\n ...(options.dialogPolicy === undefined ? {} : { dialogPolicy: options.dialogPolicy }),\n ...(options.pageControl === undefined ? {} : { pageControl: options.pageControl }),\n});\n"],"mappings":";;;;;;;;;;;;;;AAyBA,MAAM,WAAW,WACf,aAAa,KAAK;CAAE,WAAW;CAAkB;CAAQ,SAAS;AAAe,CAAC;;;;;;AAOpF,MAAa,eAAe,OAAO,WAAW,WAC5C,SACA,QAAsB,mBACtB,QACA;CACA,MAAM,SAAS,OAAO;CACtB,MAAM,WAAW,OAAO;CACxB,MAAM,SAAS,OAAO,MAAM;CAC5B,MAAM,oBAAoB,QAAQ,qBAAqB;CAEvD,IACE,CAAC,OAAO,cAAc,iBAAiB,KACvC,oBAAoB,KACpB,oBAAoB,KAEpB,OAAO,OAAO,QAAQ,eAAe;CAIvC,MAAM,WAAW,OAAO,SAAS,SAAS,QAAQ,SAAS;CAE3D,IAAI,wBAAwB,SAAS,MAAM,GAAG,OAAO,OAAO,QAAQ,SAAS;CAC7E,IAAI,SAAS,WAAW,WAAW;EACjC,IAAI,sBAAsB,GAAG,OAAO,OAAO,QAAQ,QAAQ;EAC3D,OAAO,SAAS,iBAAiB,SAAS,WAAW,EAAE,eAAe,kBAAkB,CAAC;CAC3F;CACA,MAAM,YAAY,SAAS;CAE3B,OAAO,OAAO,OAAO,gBACnB,OAAO,IAAI,aAAa;EACtB,MAAM,gBAAgB,OAAO,MAAM,KAAK;EACxC,IAAI,UAAU;E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AA,IAAY,CAAC,IAAI,EAAE,UAAU,QAAQ,SAAS;CACvE,GAAI,QAAQ,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,QAAQ,YAAY;CAChF,GAAI,QAAQ,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,QAAQ,YAAY;CAChF,GAAI,QAAQ,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,QAAQ,aAAa;CACnF,GAAI,QAAQ,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,QAAQ,YAAY;AAClF"}
|
package/dist/Browser.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { a as SessionReference, t as AllocationAttempt } from "./References-DOH3Wu44.mjs";
|
|
2
2
|
import { AllocationError, ContextError, SessionError } from "./Errors.mjs";
|
|
3
3
|
import { t as BrowserbaseClient } from "./Client-B_f6bBLT.mjs";
|
|
4
|
-
import { o as LiveView, t as BrowserbaseSessions } from "./Sessions-
|
|
4
|
+
import { o as LiveView, t as BrowserbaseSessions } from "./Sessions-oJEUmZth.mjs";
|
|
5
5
|
import { f as SelectFilesRequest, i as FileSelection, r as DownloadObservation } from "./Transfers-GVqzrDWl.mjs";
|
|
6
6
|
import { n as CleanupResult } from "./Cleanup-DMTDBir8.mjs";
|
|
7
7
|
import { n as ContextWriterPermit } from "./WriterFacts-BBJRDZYY.mjs";
|
package/dist/Browser.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { a as SessionReference } from "./References-DOH3Wu44.mjs";
|
|
2
2
|
import { FileError } from "./Errors.mjs";
|
|
3
3
|
import { t as BrowserbaseClient } from "./Client-B_f6bBLT.mjs";
|
|
4
|
-
import { t as BrowserbaseSessions } from "./Sessions-
|
|
4
|
+
import { t as BrowserbaseSessions } from "./Sessions-oJEUmZth.mjs";
|
|
5
5
|
import { n as DownloadMetadata, t as ArtifactTransferPolicy } from "./Transfers-GVqzrDWl.mjs";
|
|
6
6
|
import { Context, Effect, Layer, Schema, Stream } from "effect";
|
|
7
7
|
//#region src/Downloads.d.ts
|
|
@@ -40,4 +40,4 @@ declare class BrowserbaseDownloads extends BrowserbaseDownloads_base {
|
|
|
40
40
|
//#endregion
|
|
41
41
|
export { DownloadQuery as i, DownloadListing as n, DownloadPolicy as r, BrowserbaseDownloads as t };
|
|
42
42
|
export {};
|
|
43
|
-
//# sourceMappingURL=Downloads-
|
|
43
|
+
//# sourceMappingURL=Downloads-CX52GOFJ.d.mts.map
|
package/dist/Downloads.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { i as DownloadQuery, n as DownloadListing, r as DownloadPolicy, t as BrowserbaseDownloads } from "./Downloads-
|
|
1
|
+
import { i as DownloadQuery, n as DownloadListing, r as DownloadPolicy, t as BrowserbaseDownloads } from "./Downloads-CX52GOFJ.mjs";
|
|
2
2
|
export { BrowserbaseDownloads, DownloadListing, DownloadPolicy, DownloadQuery };
|
|
3
3
|
export {};
|
package/dist/Downloads.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { DownloadMetadata } from "./Transfers.mjs";
|
|
|
4
4
|
import { t as BrowserbaseClient } from "./Client-4RMKIpL2.mjs";
|
|
5
5
|
import { t as downloadTransferPolicy } from "./TransferPolicy-DQ06i7SZ.mjs";
|
|
6
6
|
import { n as nowMillis, r as until, t as deadlineAfter } from "./Deadline-CrViaogr.mjs";
|
|
7
|
-
import { t as BrowserbaseSessions } from "./Sessions-
|
|
7
|
+
import { t as BrowserbaseSessions } from "./Sessions-BUoyPcPJ.mjs";
|
|
8
8
|
import { Context, Effect, Layer, Schema, Stream } from "effect";
|
|
9
9
|
//#region src/Downloads.ts
|
|
10
10
|
const Timestamp = Schema.String.check(Schema.isMaxLength(64));
|
|
@@ -27,8 +27,9 @@ declare const BrowserbasePageFetch_base: Context.ServiceClass<BrowserbasePageFet
|
|
|
27
27
|
}>;
|
|
28
28
|
/**
|
|
29
29
|
* Browserbase's Fetch API: one page retrieved by the provider without a browser session.
|
|
30
|
-
* Replies are bounded by the 1 MiB control-plane limit (`reason: "limit"`);
|
|
31
|
-
*
|
|
30
|
+
* Replies are bounded by the 1 MiB control-plane limit (`reason: "limit"`); the POST is
|
|
31
|
+
* never retried. Billing of each outcome is provider-owned. `statusCode` is the target
|
|
32
|
+
* site's status, not the API's.
|
|
32
33
|
*/
|
|
33
34
|
declare class BrowserbasePageFetch extends BrowserbasePageFetch_base {
|
|
34
35
|
static readonly layer: Layer.Layer<BrowserbasePageFetch, never, BrowserbaseClient>;
|
|
@@ -36,4 +37,4 @@ declare class BrowserbasePageFetch extends BrowserbasePageFetch_base {
|
|
|
36
37
|
//#endregion
|
|
37
38
|
export { PageFetchRequest as n, PageFetchResult as r, BrowserbasePageFetch as t };
|
|
38
39
|
export {};
|
|
39
|
-
//# sourceMappingURL=PageFetch-
|
|
40
|
+
//# sourceMappingURL=PageFetch-CjAM_0DS.d.mts.map
|
package/dist/PageFetch.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { n as PageFetchRequest, r as PageFetchResult, t as BrowserbasePageFetch } from "./PageFetch-
|
|
1
|
+
import { n as PageFetchRequest, r as PageFetchResult, t as BrowserbasePageFetch } from "./PageFetch-CjAM_0DS.mjs";
|
|
2
2
|
export { BrowserbasePageFetch, PageFetchRequest, PageFetchResult };
|
|
3
3
|
export {};
|
package/dist/PageFetch.mjs
CHANGED
|
@@ -35,8 +35,9 @@ var PageFetchResult = class extends Schema.Class("BrowserbasePageFetchResult")({
|
|
|
35
35
|
}) {};
|
|
36
36
|
/**
|
|
37
37
|
* Browserbase's Fetch API: one page retrieved by the provider without a browser session.
|
|
38
|
-
* Replies are bounded by the 1 MiB control-plane limit (`reason: "limit"`);
|
|
39
|
-
*
|
|
38
|
+
* Replies are bounded by the 1 MiB control-plane limit (`reason: "limit"`); the POST is
|
|
39
|
+
* never retried. Billing of each outcome is provider-owned. `statusCode` is the target
|
|
40
|
+
* site's status, not the API's.
|
|
40
41
|
*/
|
|
41
42
|
var BrowserbasePageFetch = class BrowserbasePageFetch extends Context.Service()("effect-browserbase/PageFetch") {
|
|
42
43
|
static layer = Layer.effect(BrowserbasePageFetch, Effect.gen(function* () {
|
package/dist/PageFetch.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PageFetch.mjs","names":[],"sources":["../src/PageFetch.ts"],"sourcesContent":["import { Context, Effect, Layer, Schema } from \"effect\";\n\nimport { BrowserbaseClient } from \"./Client.ts\";\nimport { PlatformError } from \"./Errors.ts\";\nimport { resource } from \"./internal/http/Resource.ts\";\n\nconst HttpUrl = Schema.NonEmptyString.check(\n Schema.isMaxLength(8192),\n Schema.makeFilter((value) => {\n try {\n const url = new URL(value);\n\n return (\n (url.protocol === \"https:\" || url.protocol === \"http:\") && !url.username && !url.password\n );\n } catch {\n return false;\n }\n }),\n);\n\nexport const PageFetchRequest = Schema.Struct({\n url: HttpUrl,\n allowRedirects: Schema.optionalKey(Schema.Boolean),\n allowInsecureSsl: Schema.optionalKey(Schema.Boolean),\n proxies: Schema.optionalKey(Schema.Boolean),\n /** `raw` by default; `json` extracts with `schema`, `markdown` converts the page. */\n format: Schema.optionalKey(Schema.Literals([\"raw\", \"json\", \"markdown\"])),\n /** A JSON Schema describing the object to extract when `format` is `json`. */\n schema: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),\n});\n\nexport type PageFetchRequest = typeof PageFetchRequest.Type;\n\nexport class PageFetchResult extends Schema.Class<PageFetchResult>(\"BrowserbasePageFetchResult\")({\n id: Schema.String.check(Schema.isMaxLength(256)),\n statusCode: Schema.Int,\n headers: Schema.Record(Schema.String, Schema.String),\n content: Schema.Union([Schema.String, Schema.Json]),\n contentType: Schema.String.check(Schema.isMaxLength(1024)),\n encoding: Schema.String.check(Schema.isMaxLength(64)),\n}) {}\n\n/**\n * Browserbase's Fetch API: one page retrieved by the provider without a browser session.\n * Replies are bounded by the 1 MiB control-plane limit (`reason: \"limit\"`);
|
|
1
|
+
{"version":3,"file":"PageFetch.mjs","names":[],"sources":["../src/PageFetch.ts"],"sourcesContent":["import { Context, Effect, Layer, Schema } from \"effect\";\n\nimport { BrowserbaseClient } from \"./Client.ts\";\nimport { PlatformError } from \"./Errors.ts\";\nimport { resource } from \"./internal/http/Resource.ts\";\n\nconst HttpUrl = Schema.NonEmptyString.check(\n Schema.isMaxLength(8192),\n Schema.makeFilter((value) => {\n try {\n const url = new URL(value);\n\n return (\n (url.protocol === \"https:\" || url.protocol === \"http:\") && !url.username && !url.password\n );\n } catch {\n return false;\n }\n }),\n);\n\nexport const PageFetchRequest = Schema.Struct({\n url: HttpUrl,\n allowRedirects: Schema.optionalKey(Schema.Boolean),\n allowInsecureSsl: Schema.optionalKey(Schema.Boolean),\n proxies: Schema.optionalKey(Schema.Boolean),\n /** `raw` by default; `json` extracts with `schema`, `markdown` converts the page. */\n format: Schema.optionalKey(Schema.Literals([\"raw\", \"json\", \"markdown\"])),\n /** A JSON Schema describing the object to extract when `format` is `json`. */\n schema: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),\n});\n\nexport type PageFetchRequest = typeof PageFetchRequest.Type;\n\nexport class PageFetchResult extends Schema.Class<PageFetchResult>(\"BrowserbasePageFetchResult\")({\n id: Schema.String.check(Schema.isMaxLength(256)),\n statusCode: Schema.Int,\n headers: Schema.Record(Schema.String, Schema.String),\n content: Schema.Union([Schema.String, Schema.Json]),\n contentType: Schema.String.check(Schema.isMaxLength(1024)),\n encoding: Schema.String.check(Schema.isMaxLength(64)),\n}) {}\n\n/**\n * Browserbase's Fetch API: one page retrieved by the provider without a browser session.\n * Replies are bounded by the 1 MiB control-plane limit (`reason: \"limit\"`); the POST is\n * never retried. Billing of each outcome is provider-owned. `statusCode` is the target\n * site's status, not the API's.\n */\nexport class BrowserbasePageFetch extends Context.Service<\n BrowserbasePageFetch,\n {\n readonly fetch: (request: PageFetchRequest) => Effect.Effect<PageFetchResult, PlatformError>;\n }\n>()(\"effect-browserbase/PageFetch\") {\n static readonly layer: Layer.Layer<BrowserbasePageFetch, never, BrowserbaseClient> = Layer.effect(\n BrowserbasePageFetch,\n Effect.gen(function* () {\n const api = resource<PlatformError>(yield* BrowserbaseClient, (failure) =>\n PlatformError.make({ ...failure, service: \"fetch\" }),\n );\n\n const fetch = Effect.fn(\"BrowserbasePageFetch.fetch\")(function* (request: PageFetchRequest) {\n const value = yield* api.input(PageFetchRequest, request, \"fetch\");\n\n if (value.schema !== undefined && value.format !== \"json\")\n return yield* api.configuration(\"fetch\");\n\n return yield* api.request(\"POST\", \"/v1/fetch\", PageFetchResult, \"fetch\", value);\n });\n\n return BrowserbasePageFetch.of({ fetch });\n }),\n );\n}\n"],"mappings":";;;;;AAMA,MAAM,UAAU,OAAO,eAAe,MACpC,OAAO,YAAY,IAAI,GACvB,OAAO,YAAY,UAAU;CAC3B,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,KAAK;EAEzB,QACG,IAAI,aAAa,YAAY,IAAI,aAAa,YAAY,CAAC,IAAI,YAAY,CAAC,IAAI;CAErF,QAAQ;EACN,OAAO;CACT;AACF,CAAC,CACH;AAEA,MAAa,mBAAmB,OAAO,OAAO;CAC5C,KAAK;CACL,gBAAgB,OAAO,YAAY,OAAO,OAAO;CACjD,kBAAkB,OAAO,YAAY,OAAO,OAAO;CACnD,SAAS,OAAO,YAAY,OAAO,OAAO;;CAE1C,QAAQ,OAAO,YAAY,OAAO,SAAS;EAAC;EAAO;EAAQ;CAAU,CAAC,CAAC;;CAEvE,QAAQ,OAAO,YAAY,OAAO,OAAO,OAAO,QAAQ,OAAO,IAAI,CAAC;AACtE,CAAC;AAID,IAAa,kBAAb,cAAqC,OAAO,MAAuB,4BAA4B,CAAC,CAAC;CAC/F,IAAI,OAAO,OAAO,MAAM,OAAO,YAAY,GAAG,CAAC;CAC/C,YAAY,OAAO;CACnB,SAAS,OAAO,OAAO,OAAO,QAAQ,OAAO,MAAM;CACnD,SAAS,OAAO,MAAM,CAAC,OAAO,QAAQ,OAAO,IAAI,CAAC;CAClD,aAAa,OAAO,OAAO,MAAM,OAAO,YAAY,IAAI,CAAC;CACzD,UAAU,OAAO,OAAO,MAAM,OAAO,YAAY,EAAE,CAAC;AACtD,CAAC,CAAC,CAAC,CAAC;;;;;;;AAQJ,IAAa,uBAAb,MAAa,6BAA6B,QAAQ,QAKhD,CAAC,CAAC,8BAA8B,CAAC,CAAC;CAClC,OAAgB,QAAqE,MAAM,OACzF,sBACA,OAAO,IAAI,aAAa;EACtB,MAAM,MAAM,SAAwB,OAAO,oBAAoB,YAC7D,cAAc,KAAK;GAAE,GAAG;GAAS,SAAS;EAAQ,CAAC,CACrD;EAEA,MAAM,QAAQ,OAAO,GAAG,4BAA4B,CAAC,CAAC,WAAW,SAA2B;GAC1F,MAAM,QAAQ,OAAO,IAAI,MAAM,kBAAkB,SAAS,OAAO;GAEjE,IAAI,MAAM,WAAW,KAAA,KAAa,MAAM,WAAW,QACjD,OAAO,OAAO,IAAI,cAAc,OAAO;GAEzC,OAAO,OAAO,IAAI,QAAQ,QAAQ,aAAa,iBAAiB,SAAS,KAAK;EAChF,CAAC;EAED,OAAO,qBAAqB,GAAG,EAAE,MAAM,CAAC;CAC1C,CAAC,CACH;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { a as SessionReference } from "./References-DOH3Wu44.mjs";
|
|
2
2
|
import { ArtifactError } from "./Errors.mjs";
|
|
3
3
|
import { t as BrowserbaseClient } from "./Client-B_f6bBLT.mjs";
|
|
4
|
-
import { t as BrowserbaseSessions } from "./Sessions-
|
|
4
|
+
import { t as BrowserbaseSessions } from "./Sessions-oJEUmZth.mjs";
|
|
5
5
|
import { c as RecordingPageReference, o as RecordingBatch, t as ArtifactTransferPolicy } from "./Transfers-GVqzrDWl.mjs";
|
|
6
6
|
import { Context, Effect, Layer, Stream } from "effect";
|
|
7
7
|
//#region src/Recordings.d.ts
|
|
@@ -24,4 +24,4 @@ declare class BrowserbaseRecordings extends BrowserbaseRecordings_base {
|
|
|
24
24
|
//#endregion
|
|
25
25
|
export { DownloadLimits as n, PollOptions as r, BrowserbaseRecordings as t };
|
|
26
26
|
export {};
|
|
27
|
-
//# sourceMappingURL=Recordings-
|
|
27
|
+
//# sourceMappingURL=Recordings-B9k5aODB.d.mts.map
|
package/dist/Recordings.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { n as DownloadLimits, r as PollOptions, t as BrowserbaseRecordings } from "./Recordings-
|
|
1
|
+
import { n as DownloadLimits, r as PollOptions, t as BrowserbaseRecordings } from "./Recordings-B9k5aODB.mjs";
|
|
2
2
|
export { BrowserbaseRecordings, DownloadLimits, PollOptions };
|
|
3
3
|
export {};
|
package/dist/Recordings.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { RecordingBatch, RecordingPage, RecordingPageReference } from "./Transfe
|
|
|
4
4
|
import { t as BrowserbaseClient } from "./Client-4RMKIpL2.mjs";
|
|
5
5
|
import { n as transferPolicy } from "./TransferPolicy-DQ06i7SZ.mjs";
|
|
6
6
|
import { n as nowMillis, r as until, t as deadlineAfter } from "./Deadline-CrViaogr.mjs";
|
|
7
|
-
import { t as BrowserbaseSessions } from "./Sessions-
|
|
7
|
+
import { t as BrowserbaseSessions } from "./Sessions-BUoyPcPJ.mjs";
|
|
8
8
|
import { t as requireTerminalSession } from "./Authorization-Ll5f_XNM.mjs";
|
|
9
9
|
import { Context, Effect, Layer, Redacted, Schema, Semaphore, Stream } from "effect";
|
|
10
10
|
//#region src/Recordings.ts
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { a as SessionReference } from "./References-DOH3Wu44.mjs";
|
|
2
2
|
import { ArtifactError } from "./Errors.mjs";
|
|
3
3
|
import { t as BrowserbaseClient } from "./Client-B_f6bBLT.mjs";
|
|
4
|
-
import { t as BrowserbaseSessions } from "./Sessions-
|
|
4
|
+
import { t as BrowserbaseSessions } from "./Sessions-oJEUmZth.mjs";
|
|
5
5
|
import { c as RecordingPageReference, t as ArtifactTransferPolicy, u as ReplayPage } from "./Transfers-GVqzrDWl.mjs";
|
|
6
6
|
import { Context, Effect, Layer, Redacted, Stream } from "effect";
|
|
7
7
|
//#region src/Replays.d.ts
|
|
@@ -24,4 +24,4 @@ declare class BrowserbaseReplays extends BrowserbaseReplays_base {
|
|
|
24
24
|
//#endregion
|
|
25
25
|
export { ReplayAccess as n, BrowserbaseReplays as t };
|
|
26
26
|
export {};
|
|
27
|
-
//# sourceMappingURL=Replays-
|
|
27
|
+
//# sourceMappingURL=Replays-mV93WGtx.d.mts.map
|
package/dist/Replays.d.mts
CHANGED
package/dist/Replays.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { ArtifactError } from "./Errors.mjs";
|
|
|
3
3
|
import { RecordingPageReference, ReplayPage } from "./Transfers.mjs";
|
|
4
4
|
import { t as BrowserbaseClient } from "./Client-4RMKIpL2.mjs";
|
|
5
5
|
import { n as transferPolicy } from "./TransferPolicy-DQ06i7SZ.mjs";
|
|
6
|
-
import { t as BrowserbaseSessions } from "./Sessions-
|
|
6
|
+
import { t as BrowserbaseSessions } from "./Sessions-BUoyPcPJ.mjs";
|
|
7
7
|
import { t as requireTerminalSession } from "./Authorization-Ll5f_XNM.mjs";
|
|
8
8
|
import { Clock, Context, Effect, Layer, Redacted, Schema, Stream } from "effect";
|
|
9
9
|
//#region src/Replays.ts
|
|
@@ -27,11 +27,11 @@ declare class SearchResults extends SearchResults_base {}
|
|
|
27
27
|
declare const BrowserbaseSearch_base: Context.ServiceClass<BrowserbaseSearch, "effect-browserbase/Search", {
|
|
28
28
|
readonly web: (query: SearchQuery) => Effect.Effect<SearchResults, PlatformError>;
|
|
29
29
|
}>;
|
|
30
|
-
/** Browserbase web search.
|
|
30
|
+
/** Browserbase web search. The POST is never retried; billing of each outcome is provider-owned. */
|
|
31
31
|
declare class BrowserbaseSearch extends BrowserbaseSearch_base {
|
|
32
32
|
static readonly layer: Layer.Layer<BrowserbaseSearch, never, BrowserbaseClient>;
|
|
33
33
|
}
|
|
34
34
|
//#endregion
|
|
35
35
|
export { SearchResults as i, SearchQuery as n, SearchResult as r, BrowserbaseSearch as t };
|
|
36
36
|
export {};
|
|
37
|
-
//# sourceMappingURL=Search-
|
|
37
|
+
//# sourceMappingURL=Search-B64e7g-h.d.mts.map
|
package/dist/Search.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { i as SearchResults, n as SearchQuery, r as SearchResult, t as BrowserbaseSearch } from "./Search-
|
|
1
|
+
import { i as SearchResults, n as SearchQuery, r as SearchResult, t as BrowserbaseSearch } from "./Search-B64e7g-h.mjs";
|
|
2
2
|
export { BrowserbaseSearch, SearchQuery, SearchResult, SearchResults };
|
|
3
3
|
export {};
|
package/dist/Search.mjs
CHANGED
|
@@ -26,7 +26,7 @@ var SearchResults = class extends Schema.Class("BrowserbaseSearchResults")({
|
|
|
26
26
|
query: Text,
|
|
27
27
|
results: Schema.Array(SearchResult).check(Schema.isMaxLength(25))
|
|
28
28
|
}) {};
|
|
29
|
-
/** Browserbase web search.
|
|
29
|
+
/** Browserbase web search. The POST is never retried; billing of each outcome is provider-owned. */
|
|
30
30
|
var BrowserbaseSearch = class BrowserbaseSearch extends Context.Service()("effect-browserbase/Search") {
|
|
31
31
|
static layer = Layer.effect(BrowserbaseSearch, Effect.gen(function* () {
|
|
32
32
|
const api = resource(yield* BrowserbaseClient, (failure) => PlatformError.make({
|
package/dist/Search.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Search.mjs","names":[],"sources":["../src/Search.ts"],"sourcesContent":["import { Context, Effect, Layer, Schema } from \"effect\";\n\nimport { BrowserbaseClient } from \"./Client.ts\";\nimport { PlatformError } from \"./Errors.ts\";\nimport { resource } from \"./internal/http/Resource.ts\";\n\nconst Text = Schema.String.check(Schema.isMaxLength(16_384));\n\nexport const SearchQuery = Schema.Struct({\n query: Schema.NonEmptyString.check(Schema.isMaxLength(2048)),\n /** 1–25; the provider defaults to 10. */\n numResults: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 25 }))),\n});\n\nexport type SearchQuery = typeof SearchQuery.Type;\n\nexport class SearchResult extends Schema.Class<SearchResult>(\"BrowserbaseSearchResult\")({\n id: Text,\n url: Text,\n title: Text,\n author: Schema.optionalKey(Text),\n publishedDate: Schema.optionalKey(Text),\n image: Schema.optionalKey(Text),\n favicon: Schema.optionalKey(Text),\n}) {}\n\nexport class SearchResults extends Schema.Class<SearchResults>(\"BrowserbaseSearchResults\")({\n requestId: Text,\n query: Text,\n results: Schema.Array(SearchResult).check(Schema.isMaxLength(25)),\n}) {}\n\n/** Browserbase web search.
|
|
1
|
+
{"version":3,"file":"Search.mjs","names":[],"sources":["../src/Search.ts"],"sourcesContent":["import { Context, Effect, Layer, Schema } from \"effect\";\n\nimport { BrowserbaseClient } from \"./Client.ts\";\nimport { PlatformError } from \"./Errors.ts\";\nimport { resource } from \"./internal/http/Resource.ts\";\n\nconst Text = Schema.String.check(Schema.isMaxLength(16_384));\n\nexport const SearchQuery = Schema.Struct({\n query: Schema.NonEmptyString.check(Schema.isMaxLength(2048)),\n /** 1–25; the provider defaults to 10. */\n numResults: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 25 }))),\n});\n\nexport type SearchQuery = typeof SearchQuery.Type;\n\nexport class SearchResult extends Schema.Class<SearchResult>(\"BrowserbaseSearchResult\")({\n id: Text,\n url: Text,\n title: Text,\n author: Schema.optionalKey(Text),\n publishedDate: Schema.optionalKey(Text),\n image: Schema.optionalKey(Text),\n favicon: Schema.optionalKey(Text),\n}) {}\n\nexport class SearchResults extends Schema.Class<SearchResults>(\"BrowserbaseSearchResults\")({\n requestId: Text,\n query: Text,\n results: Schema.Array(SearchResult).check(Schema.isMaxLength(25)),\n}) {}\n\n/** Browserbase web search. The POST is never retried; billing of each outcome is provider-owned. */\nexport class BrowserbaseSearch extends Context.Service<\n BrowserbaseSearch,\n {\n readonly web: (query: SearchQuery) => Effect.Effect<SearchResults, PlatformError>;\n }\n>()(\"effect-browserbase/Search\") {\n static readonly layer: Layer.Layer<BrowserbaseSearch, never, BrowserbaseClient> = Layer.effect(\n BrowserbaseSearch,\n Effect.gen(function* () {\n const api = resource<PlatformError>(yield* BrowserbaseClient, (failure) =>\n PlatformError.make({ ...failure, service: \"search\" }),\n );\n\n const web = Effect.fn(\"BrowserbaseSearch.web\")(function* (query: SearchQuery) {\n const value = yield* api.input(SearchQuery, query, \"search-web\");\n\n return yield* api.request(\"POST\", \"/v1/search\", SearchResults, \"search-web\", value);\n });\n\n return BrowserbaseSearch.of({ web });\n }),\n );\n}\n"],"mappings":";;;;;AAMA,MAAM,OAAO,OAAO,OAAO,MAAM,OAAO,YAAY,KAAM,CAAC;AAE3D,MAAa,cAAc,OAAO,OAAO;CACvC,OAAO,OAAO,eAAe,MAAM,OAAO,YAAY,IAAI,CAAC;;CAE3D,YAAY,OAAO,YAAY,OAAO,IAAI,MAAM,OAAO,UAAU;EAAE,SAAS;EAAG,SAAS;CAAG,CAAC,CAAC,CAAC;AAChG,CAAC;AAID,IAAa,eAAb,cAAkC,OAAO,MAAoB,yBAAyB,CAAC,CAAC;CACtF,IAAI;CACJ,KAAK;CACL,OAAO;CACP,QAAQ,OAAO,YAAY,IAAI;CAC/B,eAAe,OAAO,YAAY,IAAI;CACtC,OAAO,OAAO,YAAY,IAAI;CAC9B,SAAS,OAAO,YAAY,IAAI;AAClC,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,gBAAb,cAAmC,OAAO,MAAqB,0BAA0B,CAAC,CAAC;CACzF,WAAW;CACX,OAAO;CACP,SAAS,OAAO,MAAM,YAAY,CAAC,CAAC,MAAM,OAAO,YAAY,EAAE,CAAC;AAClE,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,oBAAb,MAAa,0BAA0B,QAAQ,QAK7C,CAAC,CAAC,2BAA2B,CAAC,CAAC;CAC/B,OAAgB,QAAkE,MAAM,OACtF,mBACA,OAAO,IAAI,aAAa;EACtB,MAAM,MAAM,SAAwB,OAAO,oBAAoB,YAC7D,cAAc,KAAK;GAAE,GAAG;GAAS,SAAS;EAAS,CAAC,CACtD;EAEA,MAAM,MAAM,OAAO,GAAG,uBAAuB,CAAC,CAAC,WAAW,OAAoB;GAC5E,MAAM,QAAQ,OAAO,IAAI,MAAM,aAAa,OAAO,YAAY;GAE/D,OAAO,OAAO,IAAI,QAAQ,QAAQ,cAAc,eAAe,cAAc,KAAK;EACpF,CAAC;EAED,OAAO,kBAAkB,GAAG,EAAE,IAAI,CAAC;CACrC,CAAC,CACH;AACF"}
|
|
@@ -49,8 +49,8 @@ const Live = Schema.Struct({
|
|
|
49
49
|
})).check(Schema.isMaxLength(64))
|
|
50
50
|
});
|
|
51
51
|
/**
|
|
52
|
-
*
|
|
53
|
-
*
|
|
52
|
+
* These URLs are bearer capabilities: issuing one is an authorization step, not proof that an
|
|
53
|
+
* operator took control. Redaction keeps them out of ordinary logs and model-facing values.
|
|
54
54
|
*/
|
|
55
55
|
const issueLiveUrls = Effect.fnUntraced(function* (client, reference, expiresInSeconds) {
|
|
56
56
|
if (!Number.isSafeInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > 21600) return yield* ClientError.make({
|
|
@@ -257,4 +257,4 @@ var BrowserbaseSessions = class BrowserbaseSessions extends Context.Service()("e
|
|
|
257
257
|
//#endregion
|
|
258
258
|
export { issueLiveView as a, SessionWaitOptions as i, SessionListQuery as n, browserRequestFailure as o, SessionLogEntry as r, BrowserbaseSessions as t };
|
|
259
259
|
|
|
260
|
-
//# sourceMappingURL=Sessions-
|
|
260
|
+
//# sourceMappingURL=Sessions-BUoyPcPJ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Sessions-BUoyPcPJ.mjs","names":[],"sources":["../src/internal/browser/RequestFailure.ts","../src/internal/browser/LiveView.ts","../src/Sessions.ts"],"sourcesContent":["import { BrowserError, Reasons, type BrowserReason } from \"effect-browser/errors\";\n\nimport type { ClientError } from \"../../Errors.ts\";\n\ntype RequestFailure = Pick<ClientError, \"reason\" | \"outcome\" | \"status\" | \"retryAfterMillis\">;\n\n/** Only control-plane reads reach this bridge, before a modeled browser action dispatches. */\nexport const browserRequestFailure = (\n operation: \"connect\" | \"reconnect\" | \"live-view\",\n error: RequestFailure,\n): BrowserError => {\n const reason = (): BrowserReason => {\n switch (error.reason) {\n case \"configuration\":\n return Reasons.Configuration.make({});\n case \"authorization\":\n return Reasons.Authorization.make({});\n case \"rate-limited\":\n return Reasons.RateLimited.make(\n error.retryAfterMillis === undefined ? {} : { retryAfterMillis: error.retryAfterMillis },\n );\n case \"not-found\":\n return Reasons.NotFound.make({});\n case \"active\":\n return Reasons.Active.make({});\n case \"disabled\":\n return Reasons.Disabled.make({});\n case \"expired\":\n return Reasons.Expired.make({});\n case \"transport\":\n return Reasons.Transport.make(error.status === undefined ? {} : { status: error.status });\n case \"timeout\":\n return Reasons.Timeout.make({});\n case \"malformed\":\n return Reasons.Malformed.make({});\n case \"unsafe-url\":\n return Reasons.UnsafeUrl.make({});\n case \"content-type\":\n return Reasons.ContentType.make({});\n // A control-plane limit carries no measured bound. Do not invent native Limit facts.\n case \"limit\":\n case \"provider\":\n return Reasons.Provider.make(error.status === undefined ? {} : { status: error.status });\n }\n };\n\n return BrowserError.make({\n operation,\n reason: reason(),\n outcome: error.outcome ?? \"undispatched\",\n });\n};\n","import { Effect, Redacted, Schema } from \"effect\";\n\nimport type { BrowserbaseClient } from \"../../Client.ts\";\nimport { ClientError } from \"../../Errors.ts\";\nimport { Identifier, type SessionReference } from \"../../References.ts\";\nimport { browserRequestFailure } from \"./RequestFailure.ts\";\n\nconst LiveUrl = Schema.String.check(\n Schema.isMaxLength(16384),\n Schema.makeFilter((value) => {\n try {\n const url = new URL(value);\n\n return (\n url.protocol === \"https:\" &&\n !url.username &&\n !url.password &&\n (url.hostname === \"browserbase.com\" || url.hostname.endsWith(\".browserbase.com\"))\n );\n } catch {\n return false;\n }\n }),\n);\n\nconst Live = Schema.Struct({\n debuggerFullscreenUrl: LiveUrl,\n pages: Schema.Array(Schema.Struct({ id: Identifier, debuggerFullscreenUrl: LiveUrl })).check(\n Schema.isMaxLength(64),\n ),\n});\n\nexport interface LiveView {\n readonly session: Redacted.Redacted<string>;\n readonly pages: ReadonlyArray<{\n readonly liveViewPageId: string;\n readonly url: Redacted.Redacted<string>;\n }>;\n /** Echo of the requested TTL, not a provider-confirmed expiration time. */\n readonly requestedTtlSeconds: number;\n}\n\n/**\n * These URLs are bearer capabilities: issuing one is an authorization step, not proof that an\n * operator took control. Redaction keeps them out of ordinary logs and model-facing values.\n */\nexport const issueLiveUrls = Effect.fnUntraced(function* (\n client: BrowserbaseClient[\"Service\"],\n reference: SessionReference,\n expiresInSeconds: number,\n) {\n // The pinned SDK documents an optional `expiresIn` with a 21,600 second maximum, but neither\n // it nor the published debug-route schema specifies a provider minimum. One second is this\n // adapter's positive-integer input bound, not a claim that Browserbase will accept or honor it.\n if (!Number.isSafeInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > 21600)\n return yield* ClientError.make({\n operation: \"provider-read\",\n reason: \"configuration\",\n outcome: \"undispatched\",\n });\n if (reference.projectId !== client.projectId)\n return yield* ClientError.make({\n operation: \"provider-read\",\n reason: \"authorization\",\n outcome: \"undispatched\",\n });\n\n const raw = yield* client.json(\n \"GET\",\n `/v1/sessions/${encodeURIComponent(reference.sessionId)}/debug?expiresIn=${expiresInSeconds}`,\n );\n\n const value = yield* Schema.decodeUnknownEffect(Live)(raw).pipe(\n Effect.mapError(() => ClientError.make({ operation: \"provider-read\", reason: \"malformed\" })),\n );\n\n return {\n session: Redacted.make(value.debuggerFullscreenUrl),\n pages: value.pages.map((page) => ({\n liveViewPageId: page.id,\n url: Redacted.make(page.debuggerFullscreenUrl),\n })),\n requestedTtlSeconds: expiresInSeconds,\n } satisfies LiveView;\n});\n\nexport const issueLiveView = (\n client: BrowserbaseClient[\"Service\"],\n reference: SessionReference,\n expiresInSeconds: number,\n) =>\n issueLiveUrls(client, reference, expiresInSeconds).pipe(\n Effect.mapError((error) => browserRequestFailure(\"live-view\", error)),\n );\n","import { Clock, Context, Effect, Layer, Schema } from \"effect\";\n\nimport { BrowserbaseClient } from \"./Client.ts\";\nimport { type ClientError, SessionError } from \"./Errors.ts\";\nimport { issueLiveUrls, type LiveView } from \"./internal/browser/LiveView.ts\";\nexport type { LiveView } from \"./internal/browser/LiveView.ts\";\nimport { SessionReference } from \"./References.ts\";\nimport {\n ProviderSession,\n SessionMetadata,\n SessionStatus,\n isTerminalSessionStatus,\n} from \"./SessionData.ts\";\nexport { SessionMetadata, SessionStatus, isTerminalSessionStatus } from \"./SessionData.ts\";\n\nexport const SessionListQuery = Schema.Struct({\n status: Schema.optionalKey(SessionStatus),\n q: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(2048))),\n});\n\nexport type SessionListQuery = typeof SessionListQuery.Type;\n\nexport const SessionWaitOptions = Schema.Struct({\n timeoutMillis: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 600000 })),\n pollIntervalMillis: Schema.optionalKey(\n Schema.Int.check(Schema.isBetween({ minimum: 25, maximum: 5000 })),\n ),\n});\n\nexport type SessionWaitOptions = typeof SessionWaitOptions.Type;\n\nconst Millis = Schema.Finite;\n\n/**\n * One CDP-level log entry. Protocol payloads are present only when requested: they carry\n * page content, cookies and typed input, so they are host evidence, never model input.\n */\nexport class SessionLogEntry extends Schema.Class<SessionLogEntry>(\"BrowserbaseSessionLogEntry\")({\n method: Schema.String.check(Schema.isMaxLength(256)),\n pageId: Schema.Int,\n frameId: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(256))),\n loaderId: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(256))),\n timestamp: Schema.optionalKey(Millis),\n requestTimestamp: Schema.optionalKey(Millis),\n responseTimestamp: Schema.optionalKey(Millis),\n params: Schema.optionalKey(Schema.Json),\n result: Schema.optionalKey(Schema.Json),\n}) {}\n\nconst ProviderLog = Schema.Struct({\n method: SessionLogEntry.fields.method,\n pageId: Schema.Int,\n sessionId: Schema.String,\n frameId: SessionLogEntry.fields.frameId,\n loaderId: SessionLogEntry.fields.loaderId,\n timestamp: Schema.optionalKey(Millis),\n request: Schema.optionalKey(\n Schema.Struct({\n params: Schema.optionalKey(Schema.Json),\n timestamp: Schema.optionalKey(Millis),\n }),\n ),\n response: Schema.optionalKey(\n Schema.Struct({\n result: Schema.optionalKey(Schema.Json),\n timestamp: Schema.optionalKey(Millis),\n }),\n ),\n});\n\nexport interface SessionLogOptions {\n /** Include CDP `params`/`result` payloads. Off by default; see `SessionLogEntry`. */\n readonly includePayloads?: boolean;\n}\n\nconst now = Clock.monotonicTimeNanos.pipe(Effect.map((value) => Number(value) / 1000000));\n\nconst fromClient = (operation: SessionError[\"operation\"], error: ClientError): SessionError =>\n SessionError.make({\n operation,\n reason: error.reason,\n ...(error.outcome === undefined ? {} : { outcome: error.outcome }),\n ...(error.status === undefined ? {} : { status: error.status }),\n ...(error.retryAfterMillis === undefined ? {} : { retryAfterMillis: error.retryAfterMillis }),\n });\n\nconst malformed = (operation: SessionError[\"operation\"], mutation = false) =>\n SessionError.make({\n operation,\n reason: \"malformed\",\n ...(mutation ? { outcome: \"unknown\" as const } : {}),\n });\n\nconst configuration = (operation: SessionError[\"operation\"]) =>\n SessionError.make({ operation, reason: \"configuration\", outcome: \"undispatched\" });\n\n/** Passive inspection never releases a remote session. Release is a separate explicit mutation. */\nexport class BrowserbaseSessions extends Context.Service<\n BrowserbaseSessions,\n {\n readonly retrieve: (\n reference: SessionReference,\n ) => Effect.Effect<SessionMetadata, SessionError>;\n readonly list: (\n query?: SessionListQuery,\n ) => Effect.Effect<ReadonlyArray<SessionMetadata>, SessionError>;\n readonly requestRelease: (\n reference: SessionReference,\n ) => Effect.Effect<SessionMetadata, SessionError>;\n readonly waitForTerminal: (\n reference: SessionReference,\n options: SessionWaitOptions,\n ) => Effect.Effect<SessionMetadata, SessionError>;\n readonly waitUntilRunning: (\n reference: SessionReference,\n options: SessionWaitOptions,\n ) => Effect.Effect<SessionMetadata, SessionError>;\n /** Session logs, bounded by the 1 MiB control-plane reply limit (`reason: \"limit\"`). */\n readonly logs: (\n reference: SessionReference,\n options?: SessionLogOptions,\n ) => Effect.Effect<ReadonlyArray<SessionLogEntry>, SessionError>;\n /**\n * Redacted Live View URLs for any session in the project, owned or not. Issuing a URL\n * grants view and input access to whoever holds it; it does not pause automation.\n */\n readonly liveUrls: (\n reference: SessionReference,\n expiresInSeconds?: number,\n ) => Effect.Effect<LiveView, SessionError>;\n }\n>()(\"effect-browserbase/Sessions\") {\n static readonly layer: Layer.Layer<BrowserbaseSessions, never, BrowserbaseClient> = Layer.effect(\n BrowserbaseSessions,\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n\n const validate = Effect.fnUntraced(function* (\n reference: SessionReference,\n operation: SessionError[\"operation\"],\n ) {\n const ref = yield* Schema.decodeEffect(SessionReference)(reference, {\n onExcessProperty: \"error\",\n }).pipe(Effect.mapError(() => configuration(operation)));\n\n if (ref.projectId !== client.projectId)\n return yield* SessionError.make({\n operation,\n reason: \"authorization\",\n outcome: \"undispatched\",\n });\n\n return ref;\n });\n\n const decode = Effect.fnUntraced(function* (\n raw: unknown,\n operation: SessionError[\"operation\"],\n expected?: SessionReference,\n mutation: boolean = false,\n ) {\n const value = yield* Schema.decodeUnknownEffect(ProviderSession)(raw).pipe(\n Effect.mapError(() => malformed(operation, mutation)),\n );\n\n if (\n value.projectId !== client.projectId ||\n (expected !== undefined &&\n (value.id !== expected.sessionId || value.projectId !== expected.projectId))\n )\n return yield* malformed(operation, mutation);\n const { id, projectId, ...metadata } = value;\n\n return SessionMetadata.make({\n reference: SessionReference.make({ provider: \"browserbase\", projectId, sessionId: id }),\n ...metadata,\n });\n });\n\n const read = Effect.fnUntraced(function* (reference: SessionReference, deadline?: number) {\n const ref = yield* validate(reference, \"session-retrieve\");\n\n const raw = yield* client\n .json(\"GET\", `/v1/sessions/${encodeURIComponent(ref.sessionId)}`, undefined, deadline)\n .pipe(Effect.mapError((error) => fromClient(\"session-retrieve\", error)));\n\n return yield* decode(raw, \"session-retrieve\", ref);\n });\n\n const retrieve = Effect.fn(\"BrowserbaseSessions.retrieve\")(function* (\n reference: SessionReference,\n ) {\n return yield* read(reference);\n });\n\n const list = Effect.fn(\"BrowserbaseSessions.list\")(function* (query: SessionListQuery = {}) {\n const checked = yield* Schema.decodeEffect(SessionListQuery)(query, {\n onExcessProperty: \"error\",\n }).pipe(Effect.mapError(() => configuration(\"session-list\")));\n\n const search = new URLSearchParams();\n\n if (checked.status !== undefined) search.set(\"status\", checked.status);\n if (checked.q !== undefined) search.set(\"q\", checked.q);\n\n const raw = yield* client\n .json(\"GET\", `/v1/sessions${search.size === 0 ? \"\" : `?${search}`}`)\n .pipe(Effect.mapError((error) => fromClient(\"session-list\", error)));\n\n const rows = yield* Schema.decodeUnknownEffect(\n Schema.Array(ProviderSession).check(Schema.isMaxLength(1024)),\n )(raw).pipe(Effect.mapError(() => malformed(\"session-list\")));\n\n if (new Set(rows.map((row) => row.id)).size !== rows.length)\n return yield* malformed(\"session-list\");\n const output: SessionMetadata[] = [];\n\n for (const row of rows) output.push(yield* decode(row, \"session-list\"));\n\n return output;\n });\n\n const requestRelease = Effect.fn(\"BrowserbaseSessions.requestRelease\")(function* (\n reference: SessionReference,\n ) {\n const ref = yield* validate(reference, \"session-release\");\n\n const raw = yield* client\n .json(\"POST\", `/v1/sessions/${encodeURIComponent(ref.sessionId)}`, {\n projectId: ref.projectId,\n status: \"REQUEST_RELEASE\",\n })\n .pipe(Effect.mapError((error) => fromClient(\"session-release\", error)));\n\n return yield* decode(raw, \"session-release\", ref, true);\n });\n\n const wait = Effect.fnUntraced(function* (\n reference: SessionReference,\n options: SessionWaitOptions,\n untilRunning: boolean,\n ) {\n const bounds = yield* Schema.decodeEffect(SessionWaitOptions)(options, {\n onExcessProperty: \"error\",\n }).pipe(Effect.mapError(() => configuration(\"session-wait\")));\n\n const deadline = (yield* now) + bounds.timeoutMillis;\n\n for (;;) {\n const remaining = deadline - (yield* now);\n\n if (remaining <= 0)\n return yield* SessionError.make({ operation: \"session-wait\", reason: \"timeout\" });\n\n // The deadline bounds the provider read too, not just sleeps between reads.\n const metadata = yield* read(reference, deadline).pipe(\n Effect.timeoutOrElse({\n duration: remaining,\n orElse: () =>\n Effect.fail(SessionError.make({ operation: \"session-wait\", reason: \"timeout\" })),\n }),\n );\n\n if (\n untilRunning ? metadata.status === \"RUNNING\" : isTerminalSessionStatus(metadata.status)\n )\n return metadata;\n if (untilRunning && isTerminalSessionStatus(metadata.status))\n return yield* SessionError.make({ operation: \"session-wait\", reason: \"expired\" });\n yield* Effect.sleep(\n Math.max(0, Math.min(bounds.pollIntervalMillis ?? 250, deadline - (yield* now))),\n );\n }\n });\n\n const logs = Effect.fn(\"BrowserbaseSessions.logs\")(function* (\n reference: SessionReference,\n options: SessionLogOptions = {},\n ) {\n const ref = yield* validate(reference, \"session-logs\");\n\n const raw = yield* client\n .json(\"GET\", `/v1/sessions/${encodeURIComponent(ref.sessionId)}/logs`)\n .pipe(Effect.mapError((error) => fromClient(\"session-logs\", error)));\n\n const rows = yield* Schema.decodeUnknownEffect(\n Schema.Array(ProviderLog).check(Schema.isMaxLength(100_000)),\n )(raw).pipe(Effect.mapError(() => malformed(\"session-logs\")));\n\n if (rows.some((row) => row.sessionId !== ref.sessionId))\n return yield* malformed(\"session-logs\");\n\n return rows.map((row) =>\n SessionLogEntry.make({\n method: row.method,\n pageId: row.pageId,\n ...(row.frameId === undefined ? {} : { frameId: row.frameId }),\n ...(row.loaderId === undefined ? {} : { loaderId: row.loaderId }),\n ...(row.timestamp === undefined ? {} : { timestamp: row.timestamp }),\n ...(row.request?.timestamp === undefined\n ? {}\n : { requestTimestamp: row.request.timestamp }),\n ...(row.response?.timestamp === undefined\n ? {}\n : { responseTimestamp: row.response.timestamp }),\n ...(options.includePayloads === true && row.request?.params !== undefined\n ? { params: row.request.params }\n : {}),\n ...(options.includePayloads === true && row.response?.result !== undefined\n ? { result: row.response.result }\n : {}),\n }),\n );\n });\n\n const liveUrls = Effect.fn(\"BrowserbaseSessions.liveUrls\")(function* (\n reference: SessionReference,\n expiresInSeconds: number = 300,\n ) {\n const ref = yield* validate(reference, \"session-live-view\");\n\n return yield* issueLiveUrls(client, ref, expiresInSeconds).pipe(\n Effect.mapError((error) => fromClient(\"session-live-view\", error)),\n );\n });\n\n return BrowserbaseSessions.of({\n logs,\n liveUrls,\n retrieve,\n list,\n requestRelease,\n waitForTerminal: (ref, options) => wait(ref, options, false),\n waitUntilRunning: (ref, options) => wait(ref, options, true),\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;AAOA,MAAa,yBACX,WACA,UACiB;CACjB,MAAM,eAA8B;EAClC,QAAQ,MAAM,QAAd;GACE,KAAK,iBACH,OAAO,QAAQ,cAAc,KAAK,CAAC,CAAC;GACtC,KAAK,iBACH,OAAO,QAAQ,cAAc,KAAK,CAAC,CAAC;GACtC,KAAK,gBACH,OAAO,QAAQ,YAAY,KACzB,MAAM,qBAAqB,KAAA,IAAY,CAAC,IAAI,EAAE,kBAAkB,MAAM,iBAAiB,CACzF;GACF,KAAK,aACH,OAAO,QAAQ,SAAS,KAAK,CAAC,CAAC;GACjC,KAAK,UACH,OAAO,QAAQ,OAAO,KAAK,CAAC,CAAC;GAC/B,KAAK,YACH,OAAO,QAAQ,SAAS,KAAK,CAAC,CAAC;GACjC,KAAK,WACH,OAAO,QAAQ,QAAQ,KAAK,CAAC,CAAC;GAChC,KAAK,aACH,OAAO,QAAQ,UAAU,KAAK,MAAM,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,MAAM,OAAO,CAAC;GAC1F,KAAK,WACH,OAAO,QAAQ,QAAQ,KAAK,CAAC,CAAC;GAChC,KAAK,aACH,OAAO,QAAQ,UAAU,KAAK,CAAC,CAAC;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,qBAAqB,KAAK,CAAC,CACnE;EACF,CAAC;EAED,OAAO,oBAAoB,GAAG;GAC5B;GACA;GACA;GACA;GACA;GACA,kBAAkB,KAAK,YAAY,KAAK,KAAK,SAAS,KAAK;GAC3D,mBAAmB,KAAK,YAAY,KAAK,KAAK,SAAS,IAAI;EAC7D,CAAC;CACH,CAAC,CACH;AACF"}
|
|
@@ -10,6 +10,7 @@ interface LiveView {
|
|
|
10
10
|
readonly liveViewPageId: string;
|
|
11
11
|
readonly url: Redacted.Redacted<string>;
|
|
12
12
|
}>;
|
|
13
|
+
/** Echo of the requested TTL, not a provider-confirmed expiration time. */
|
|
13
14
|
readonly requestedTtlSeconds: number;
|
|
14
15
|
}
|
|
15
16
|
//#endregion
|
|
@@ -65,4 +66,4 @@ declare class BrowserbaseSessions extends BrowserbaseSessions_base {
|
|
|
65
66
|
//#endregion
|
|
66
67
|
export { SessionWaitOptions as a, SessionLogOptions as i, SessionListQuery as n, LiveView as o, SessionLogEntry as r, BrowserbaseSessions as t };
|
|
67
68
|
export {};
|
|
68
|
-
//# sourceMappingURL=Sessions-
|
|
69
|
+
//# sourceMappingURL=Sessions-oJEUmZth.d.mts.map
|
package/dist/Sessions.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as SessionWaitOptions, i as SessionLogOptions, n as SessionListQuery, o as LiveView, r as SessionLogEntry, t as BrowserbaseSessions } from "./Sessions-
|
|
1
|
+
import { a as SessionWaitOptions, i as SessionLogOptions, n as SessionListQuery, o as LiveView, r as SessionLogEntry, t as BrowserbaseSessions } from "./Sessions-oJEUmZth.mjs";
|
|
2
2
|
import { i as isTerminalSessionStatus, n as SessionMetadata, r as SessionStatus } from "./SessionData-5xYZDshJ.mjs";
|
|
3
3
|
export { BrowserbaseSessions, type LiveView, SessionListQuery, SessionLogEntry, SessionLogOptions, SessionMetadata, SessionStatus, SessionWaitOptions, isTerminalSessionStatus };
|
|
4
4
|
export {};
|
package/dist/Sessions.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { SessionMetadata, SessionStatus, isTerminalSessionStatus } from "./SessionData.mjs";
|
|
2
|
-
import { i as SessionWaitOptions, n as SessionListQuery, r as SessionLogEntry, t as BrowserbaseSessions } from "./Sessions-
|
|
2
|
+
import { i as SessionWaitOptions, n as SessionListQuery, r as SessionLogEntry, t as BrowserbaseSessions } from "./Sessions-BUoyPcPJ.mjs";
|
|
3
3
|
export { BrowserbaseSessions, SessionListQuery, SessionLogEntry, SessionMetadata, SessionStatus, SessionWaitOptions, isTerminalSessionStatus };
|
package/dist/Testing.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { recipe } from "./Launch.mjs";
|
|
|
4
4
|
import { ProviderSession, SessionStatus } from "./SessionData.mjs";
|
|
5
5
|
import { layer as layer$1 } from "./Account.mjs";
|
|
6
6
|
import { layer as layer$2 } from "./BrowserBinding.mjs";
|
|
7
|
-
import { t as BrowserbaseBrowser } from "./Browser-
|
|
7
|
+
import { t as BrowserbaseBrowser } from "./Browser-Dw0JFTaD.mjs";
|
|
8
8
|
import { Context, Effect, Layer, Redacted, Schema } from "effect";
|
|
9
9
|
import { FetchHttpClient } from "effect/unstable/http";
|
|
10
10
|
import * as BrowserTesting from "effect-browser/testing";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { a as SessionReference } from "./References-DOH3Wu44.mjs";
|
|
2
2
|
import { FileError } from "./Errors.mjs";
|
|
3
3
|
import { t as BrowserbaseClient } from "./Client-B_f6bBLT.mjs";
|
|
4
|
-
import { t as BrowserbaseSessions } from "./Sessions-
|
|
4
|
+
import { t as BrowserbaseSessions } from "./Sessions-oJEUmZth.mjs";
|
|
5
5
|
import { p as UploadReceipt } from "./Transfers-GVqzrDWl.mjs";
|
|
6
6
|
import { Context, Effect, Layer } from "effect";
|
|
7
7
|
//#region src/Uploads.d.ts
|
|
@@ -25,4 +25,4 @@ declare class BrowserbaseUploads extends BrowserbaseUploads_base {
|
|
|
25
25
|
//#endregion
|
|
26
26
|
export { UploadFile as n, BrowserbaseUploads as t };
|
|
27
27
|
export {};
|
|
28
|
-
//# sourceMappingURL=Uploads-
|
|
28
|
+
//# sourceMappingURL=Uploads-C2_bACgv.d.mts.map
|
package/dist/Uploads.d.mts
CHANGED
package/dist/Uploads.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { FileError } from "./Errors.mjs";
|
|
2
2
|
import { RemoteFilePath, SafeFilename, UploadReceipt } from "./Transfers.mjs";
|
|
3
3
|
import { t as BrowserbaseClient } from "./Client-4RMKIpL2.mjs";
|
|
4
|
-
import { t as BrowserbaseSessions } from "./Sessions-
|
|
4
|
+
import { t as BrowserbaseSessions } from "./Sessions-BUoyPcPJ.mjs";
|
|
5
5
|
import { n as recordIssuedUpload } from "./Issued-DejqoMYL.mjs";
|
|
6
6
|
import { Context, Effect, Layer, Schema } from "effect";
|
|
7
7
|
//#region src/Uploads.ts
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "effect-browserbase",
|
|
3
|
-
"version": "0.2.0-beta.
|
|
3
|
+
"version": "0.2.0-beta.5",
|
|
4
4
|
"description": "Effect-based Browserbase resources and hosted integration for effect-browser.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
},
|
|
16
16
|
"peerDependencies": {
|
|
17
17
|
"effect": "^4.0.0-rc.117",
|
|
18
|
-
"effect-browser": "0.2.0-beta.
|
|
18
|
+
"effect-browser": "0.2.0-beta.5"
|
|
19
19
|
},
|
|
20
20
|
"homepage": "https://github.com/mannyc2/effect-agent-browserbase#readme",
|
|
21
21
|
"bugs": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Sessions-suOLSym9.mjs","names":[],"sources":["../src/internal/browser/RequestFailure.ts","../src/internal/browser/LiveView.ts","../src/Sessions.ts"],"sourcesContent":["import { BrowserError, Reasons, type BrowserReason } from \"effect-browser/errors\";\n\nimport type { ClientError } from \"../../Errors.ts\";\n\ntype RequestFailure = Pick<ClientError, \"reason\" | \"outcome\" | \"status\" | \"retryAfterMillis\">;\n\n/** Only control-plane reads reach this bridge, before a modeled browser action dispatches. */\nexport const browserRequestFailure = (\n operation: \"connect\" | \"reconnect\" | \"live-view\",\n error: RequestFailure,\n): BrowserError => {\n const reason = (): BrowserReason => {\n switch (error.reason) {\n case \"configuration\":\n return Reasons.Configuration.make({});\n case \"authorization\":\n return Reasons.Authorization.make({});\n case \"rate-limited\":\n return Reasons.RateLimited.make(\n error.retryAfterMillis === undefined ? {} : { retryAfterMillis: error.retryAfterMillis },\n );\n case \"not-found\":\n return Reasons.NotFound.make({});\n case \"active\":\n return Reasons.Active.make({});\n case \"disabled\":\n return Reasons.Disabled.make({});\n case \"expired\":\n return Reasons.Expired.make({});\n case \"transport\":\n return Reasons.Transport.make(error.status === undefined ? {} : { status: error.status });\n case \"timeout\":\n return Reasons.Timeout.make({});\n case \"malformed\":\n return Reasons.Malformed.make({});\n case \"unsafe-url\":\n return Reasons.UnsafeUrl.make({});\n case \"content-type\":\n return Reasons.ContentType.make({});\n // A control-plane limit carries no measured bound. Do not invent native Limit facts.\n case \"limit\":\n case \"provider\":\n return Reasons.Provider.make(error.status === undefined ? {} : { status: error.status });\n }\n };\n\n return BrowserError.make({\n operation,\n reason: reason(),\n outcome: error.outcome ?? \"undispatched\",\n });\n};\n","import { Effect, Redacted, Schema } from \"effect\";\n\nimport type { BrowserbaseClient } from \"../../Client.ts\";\nimport { ClientError } from \"../../Errors.ts\";\nimport { Identifier, type SessionReference } from \"../../References.ts\";\nimport { browserRequestFailure } from \"./RequestFailure.ts\";\n\nconst LiveUrl = Schema.String.check(\n Schema.isMaxLength(16384),\n Schema.makeFilter((value) => {\n try {\n const url = new URL(value);\n\n return (\n url.protocol === \"https:\" &&\n !url.username &&\n !url.password &&\n (url.hostname === \"browserbase.com\" || url.hostname.endsWith(\".browserbase.com\"))\n );\n } catch {\n return false;\n }\n }),\n);\n\nconst Live = Schema.Struct({\n debuggerFullscreenUrl: LiveUrl,\n pages: Schema.Array(Schema.Struct({ id: Identifier, debuggerFullscreenUrl: LiveUrl })).check(\n Schema.isMaxLength(64),\n ),\n});\n\nexport interface LiveView {\n readonly session: Redacted.Redacted<string>;\n readonly pages: ReadonlyArray<{\n readonly liveViewPageId: string;\n readonly url: Redacted.Redacted<string>;\n }>;\n readonly requestedTtlSeconds: number;\n}\n\n/**\n * Issuing a debugger URL is an authorization step, not proof that an operator took control.\n * The URL is redacted here so it cannot be logged or returned as an ordinary model value.\n */\nexport const issueLiveUrls = Effect.fnUntraced(function* (\n client: BrowserbaseClient[\"Service\"],\n reference: SessionReference,\n expiresInSeconds: number,\n) {\n if (!Number.isSafeInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > 21600)\n return yield* ClientError.make({\n operation: \"provider-read\",\n reason: \"configuration\",\n outcome: \"undispatched\",\n });\n if (reference.projectId !== client.projectId)\n return yield* ClientError.make({\n operation: \"provider-read\",\n reason: \"authorization\",\n outcome: \"undispatched\",\n });\n\n const raw = yield* client.json(\n \"GET\",\n `/v1/sessions/${encodeURIComponent(reference.sessionId)}/debug?expiresIn=${expiresInSeconds}`,\n );\n\n const value = yield* Schema.decodeUnknownEffect(Live)(raw).pipe(\n Effect.mapError(() => ClientError.make({ operation: \"provider-read\", reason: \"malformed\" })),\n );\n\n return {\n session: Redacted.make(value.debuggerFullscreenUrl),\n pages: value.pages.map((page) => ({\n liveViewPageId: page.id,\n url: Redacted.make(page.debuggerFullscreenUrl),\n })),\n requestedTtlSeconds: expiresInSeconds,\n } satisfies LiveView;\n});\n\nexport const issueLiveView = (\n client: BrowserbaseClient[\"Service\"],\n reference: SessionReference,\n expiresInSeconds: number,\n) =>\n issueLiveUrls(client, reference, expiresInSeconds).pipe(\n Effect.mapError((error) => browserRequestFailure(\"live-view\", error)),\n );\n","import { Clock, Context, Effect, Layer, Schema } from \"effect\";\n\nimport { BrowserbaseClient } from \"./Client.ts\";\nimport { type ClientError, SessionError } from \"./Errors.ts\";\nimport { issueLiveUrls, type LiveView } from \"./internal/browser/LiveView.ts\";\nexport type { LiveView } from \"./internal/browser/LiveView.ts\";\nimport { SessionReference } from \"./References.ts\";\nimport {\n ProviderSession,\n SessionMetadata,\n SessionStatus,\n isTerminalSessionStatus,\n} from \"./SessionData.ts\";\nexport { SessionMetadata, SessionStatus, isTerminalSessionStatus } from \"./SessionData.ts\";\n\nexport const SessionListQuery = Schema.Struct({\n status: Schema.optionalKey(SessionStatus),\n q: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(2048))),\n});\n\nexport type SessionListQuery = typeof SessionListQuery.Type;\n\nexport const SessionWaitOptions = Schema.Struct({\n timeoutMillis: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 600000 })),\n pollIntervalMillis: Schema.optionalKey(\n Schema.Int.check(Schema.isBetween({ minimum: 25, maximum: 5000 })),\n ),\n});\n\nexport type SessionWaitOptions = typeof SessionWaitOptions.Type;\n\nconst Millis = Schema.Finite;\n\n/**\n * One CDP-level log entry. Protocol payloads are present only when requested: they carry\n * page content, cookies and typed input, so they are host evidence, never model input.\n */\nexport class SessionLogEntry extends Schema.Class<SessionLogEntry>(\"BrowserbaseSessionLogEntry\")({\n method: Schema.String.check(Schema.isMaxLength(256)),\n pageId: Schema.Int,\n frameId: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(256))),\n loaderId: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(256))),\n timestamp: Schema.optionalKey(Millis),\n requestTimestamp: Schema.optionalKey(Millis),\n responseTimestamp: Schema.optionalKey(Millis),\n params: Schema.optionalKey(Schema.Json),\n result: Schema.optionalKey(Schema.Json),\n}) {}\n\nconst ProviderLog = Schema.Struct({\n method: SessionLogEntry.fields.method,\n pageId: Schema.Int,\n sessionId: Schema.String,\n frameId: SessionLogEntry.fields.frameId,\n loaderId: SessionLogEntry.fields.loaderId,\n timestamp: Schema.optionalKey(Millis),\n request: Schema.optionalKey(\n Schema.Struct({\n params: Schema.optionalKey(Schema.Json),\n timestamp: Schema.optionalKey(Millis),\n }),\n ),\n response: Schema.optionalKey(\n Schema.Struct({\n result: Schema.optionalKey(Schema.Json),\n timestamp: Schema.optionalKey(Millis),\n }),\n ),\n});\n\nexport interface SessionLogOptions {\n /** Include CDP `params`/`result` payloads. Off by default; see `SessionLogEntry`. */\n readonly includePayloads?: boolean;\n}\n\nconst now = Clock.monotonicTimeNanos.pipe(Effect.map((value) => Number(value) / 1000000));\n\nconst fromClient = (operation: SessionError[\"operation\"], error: ClientError): SessionError =>\n SessionError.make({\n operation,\n reason: error.reason,\n ...(error.outcome === undefined ? {} : { outcome: error.outcome }),\n ...(error.status === undefined ? {} : { status: error.status }),\n ...(error.retryAfterMillis === undefined ? {} : { retryAfterMillis: error.retryAfterMillis }),\n });\n\nconst malformed = (operation: SessionError[\"operation\"], mutation = false) =>\n SessionError.make({\n operation,\n reason: \"malformed\",\n ...(mutation ? { outcome: \"unknown\" as const } : {}),\n });\n\nconst configuration = (operation: SessionError[\"operation\"]) =>\n SessionError.make({ operation, reason: \"configuration\", outcome: \"undispatched\" });\n\n/** Passive inspection never releases a remote session. Release is a separate explicit mutation. */\nexport class BrowserbaseSessions extends Context.Service<\n BrowserbaseSessions,\n {\n readonly retrieve: (\n reference: SessionReference,\n ) => Effect.Effect<SessionMetadata, SessionError>;\n readonly list: (\n query?: SessionListQuery,\n ) => Effect.Effect<ReadonlyArray<SessionMetadata>, SessionError>;\n readonly requestRelease: (\n reference: SessionReference,\n ) => Effect.Effect<SessionMetadata, SessionError>;\n readonly waitForTerminal: (\n reference: SessionReference,\n options: SessionWaitOptions,\n ) => Effect.Effect<SessionMetadata, SessionError>;\n readonly waitUntilRunning: (\n reference: SessionReference,\n options: SessionWaitOptions,\n ) => Effect.Effect<SessionMetadata, SessionError>;\n /** Session logs, bounded by the 1 MiB control-plane reply limit (`reason: \"limit\"`). */\n readonly logs: (\n reference: SessionReference,\n options?: SessionLogOptions,\n ) => Effect.Effect<ReadonlyArray<SessionLogEntry>, SessionError>;\n /**\n * Redacted Live View URLs for any session in the project, owned or not. Issuing a URL\n * grants view and input access to whoever holds it; it does not pause automation.\n */\n readonly liveUrls: (\n reference: SessionReference,\n expiresInSeconds?: number,\n ) => Effect.Effect<LiveView, SessionError>;\n }\n>()(\"effect-browserbase/Sessions\") {\n static readonly layer: Layer.Layer<BrowserbaseSessions, never, BrowserbaseClient> = Layer.effect(\n BrowserbaseSessions,\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n\n const validate = Effect.fnUntraced(function* (\n reference: SessionReference,\n operation: SessionError[\"operation\"],\n ) {\n const ref = yield* Schema.decodeEffect(SessionReference)(reference, {\n onExcessProperty: \"error\",\n }).pipe(Effect.mapError(() => configuration(operation)));\n\n if (ref.projectId !== client.projectId)\n return yield* SessionError.make({\n operation,\n reason: \"authorization\",\n outcome: \"undispatched\",\n });\n\n return ref;\n });\n\n const decode = Effect.fnUntraced(function* (\n raw: unknown,\n operation: SessionError[\"operation\"],\n expected?: SessionReference,\n mutation: boolean = false,\n ) {\n const value = yield* Schema.decodeUnknownEffect(ProviderSession)(raw).pipe(\n Effect.mapError(() => malformed(operation, mutation)),\n );\n\n if (\n value.projectId !== client.projectId ||\n (expected !== undefined &&\n (value.id !== expected.sessionId || value.projectId !== expected.projectId))\n )\n return yield* malformed(operation, mutation);\n const { id, projectId, ...metadata } = value;\n\n return SessionMetadata.make({\n reference: SessionReference.make({ provider: \"browserbase\", projectId, sessionId: id }),\n ...metadata,\n });\n });\n\n const read = Effect.fnUntraced(function* (reference: SessionReference, deadline?: number) {\n const ref = yield* validate(reference, \"session-retrieve\");\n\n const raw = yield* client\n .json(\"GET\", `/v1/sessions/${encodeURIComponent(ref.sessionId)}`, undefined, deadline)\n .pipe(Effect.mapError((error) => fromClient(\"session-retrieve\", error)));\n\n return yield* decode(raw, \"session-retrieve\", ref);\n });\n\n const retrieve = Effect.fn(\"BrowserbaseSessions.retrieve\")(function* (\n reference: SessionReference,\n ) {\n return yield* read(reference);\n });\n\n const list = Effect.fn(\"BrowserbaseSessions.list\")(function* (query: SessionListQuery = {}) {\n const checked = yield* Schema.decodeEffect(SessionListQuery)(query, {\n onExcessProperty: \"error\",\n }).pipe(Effect.mapError(() => configuration(\"session-list\")));\n\n const search = new URLSearchParams();\n\n if (checked.status !== undefined) search.set(\"status\", checked.status);\n if (checked.q !== undefined) search.set(\"q\", checked.q);\n\n const raw = yield* client\n .json(\"GET\", `/v1/sessions${search.size === 0 ? \"\" : `?${search}`}`)\n .pipe(Effect.mapError((error) => fromClient(\"session-list\", error)));\n\n const rows = yield* Schema.decodeUnknownEffect(\n Schema.Array(ProviderSession).check(Schema.isMaxLength(1024)),\n )(raw).pipe(Effect.mapError(() => malformed(\"session-list\")));\n\n if (new Set(rows.map((row) => row.id)).size !== rows.length)\n return yield* malformed(\"session-list\");\n const output: SessionMetadata[] = [];\n\n for (const row of rows) output.push(yield* decode(row, \"session-list\"));\n\n return output;\n });\n\n const requestRelease = Effect.fn(\"BrowserbaseSessions.requestRelease\")(function* (\n reference: SessionReference,\n ) {\n const ref = yield* validate(reference, \"session-release\");\n\n const raw = yield* client\n .json(\"POST\", `/v1/sessions/${encodeURIComponent(ref.sessionId)}`, {\n projectId: ref.projectId,\n status: \"REQUEST_RELEASE\",\n })\n .pipe(Effect.mapError((error) => fromClient(\"session-release\", error)));\n\n return yield* decode(raw, \"session-release\", ref, true);\n });\n\n const wait = Effect.fnUntraced(function* (\n reference: SessionReference,\n options: SessionWaitOptions,\n untilRunning: boolean,\n ) {\n const bounds = yield* Schema.decodeEffect(SessionWaitOptions)(options, {\n onExcessProperty: \"error\",\n }).pipe(Effect.mapError(() => configuration(\"session-wait\")));\n\n const deadline = (yield* now) + bounds.timeoutMillis;\n\n for (;;) {\n const remaining = deadline - (yield* now);\n\n if (remaining <= 0)\n return yield* SessionError.make({ operation: \"session-wait\", reason: \"timeout\" });\n\n // The deadline bounds the provider read too, not just sleeps between reads.\n const metadata = yield* read(reference, deadline).pipe(\n Effect.timeoutOrElse({\n duration: remaining,\n orElse: () =>\n Effect.fail(SessionError.make({ operation: \"session-wait\", reason: \"timeout\" })),\n }),\n );\n\n if (\n untilRunning ? metadata.status === \"RUNNING\" : isTerminalSessionStatus(metadata.status)\n )\n return metadata;\n if (untilRunning && isTerminalSessionStatus(metadata.status))\n return yield* SessionError.make({ operation: \"session-wait\", reason: \"expired\" });\n yield* Effect.sleep(\n Math.max(0, Math.min(bounds.pollIntervalMillis ?? 250, deadline - (yield* now))),\n );\n }\n });\n\n const logs = Effect.fn(\"BrowserbaseSessions.logs\")(function* (\n reference: SessionReference,\n options: SessionLogOptions = {},\n ) {\n const ref = yield* validate(reference, \"session-logs\");\n\n const raw = yield* client\n .json(\"GET\", `/v1/sessions/${encodeURIComponent(ref.sessionId)}/logs`)\n .pipe(Effect.mapError((error) => fromClient(\"session-logs\", error)));\n\n const rows = yield* Schema.decodeUnknownEffect(\n Schema.Array(ProviderLog).check(Schema.isMaxLength(100_000)),\n )(raw).pipe(Effect.mapError(() => malformed(\"session-logs\")));\n\n if (rows.some((row) => row.sessionId !== ref.sessionId))\n return yield* malformed(\"session-logs\");\n\n return rows.map((row) =>\n SessionLogEntry.make({\n method: row.method,\n pageId: row.pageId,\n ...(row.frameId === undefined ? {} : { frameId: row.frameId }),\n ...(row.loaderId === undefined ? {} : { loaderId: row.loaderId }),\n ...(row.timestamp === undefined ? {} : { timestamp: row.timestamp }),\n ...(row.request?.timestamp === undefined\n ? {}\n : { requestTimestamp: row.request.timestamp }),\n ...(row.response?.timestamp === undefined\n ? {}\n : { responseTimestamp: row.response.timestamp }),\n ...(options.includePayloads === true && row.request?.params !== undefined\n ? { params: row.request.params }\n : {}),\n ...(options.includePayloads === true && row.response?.result !== undefined\n ? { result: row.response.result }\n : {}),\n }),\n );\n });\n\n const liveUrls = Effect.fn(\"BrowserbaseSessions.liveUrls\")(function* (\n reference: SessionReference,\n expiresInSeconds: number = 300,\n ) {\n const ref = yield* validate(reference, \"session-live-view\");\n\n return yield* issueLiveUrls(client, ref, expiresInSeconds).pipe(\n Effect.mapError((error) => fromClient(\"session-live-view\", error)),\n );\n });\n\n return BrowserbaseSessions.of({\n logs,\n liveUrls,\n retrieve,\n list,\n requestRelease,\n waitForTerminal: (ref, options) => wait(ref, options, false),\n waitUntilRunning: (ref, options) => wait(ref, options, true),\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;AAOA,MAAa,yBACX,WACA,UACiB;CACjB,MAAM,eAA8B;EAClC,QAAQ,MAAM,QAAd;GACE,KAAK,iBACH,OAAO,QAAQ,cAAc,KAAK,CAAC,CAAC;GACtC,KAAK,iBACH,OAAO,QAAQ,cAAc,KAAK,CAAC,CAAC;GACtC,KAAK,gBACH,OAAO,QAAQ,YAAY,KACzB,MAAM,qBAAqB,KAAA,IAAY,CAAC,IAAI,EAAE,kBAAkB,MAAM,iBAAiB,CACzF;GACF,KAAK,aACH,OAAO,QAAQ,SAAS,KAAK,CAAC,CAAC;GACjC,KAAK,UACH,OAAO,QAAQ,OAAO,KAAK,CAAC,CAAC;GAC/B,KAAK,YACH,OAAO,QAAQ,SAAS,KAAK,CAAC,CAAC;GACjC,KAAK,WACH,OAAO,QAAQ,QAAQ,KAAK,CAAC,CAAC;GAChC,KAAK,aACH,OAAO,QAAQ,UAAU,KAAK,MAAM,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,MAAM,OAAO,CAAC;GAC1F,KAAK,WACH,OAAO,QAAQ,QAAQ,KAAK,CAAC,CAAC;GAChC,KAAK,aACH,OAAO,QAAQ,UAAU,KAAK,CAAC,CAAC;GAClC,KAAK,cACH,OAAO,QAAQ,UAAU,KAAK,CAAC,CAAC;GAClC,KAAK,gBACH,OAAO,QAAQ,YAAY,KAAK,CAAC,CAAC;GAEpC,KAAK;GACL,KAAK,YACH,OAAO,QAAQ,SAAS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