beachside 0.0.0 → 0.8.0
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 +119 -3
- package/dist/adapter-direct.d.ts +299 -0
- package/dist/adapter-reference.d.ts +268 -0
- package/dist/bound.d.ts +1 -0
- package/dist/connection-wait.d.ts +10 -0
- package/dist/directory-read.d.ts +8 -0
- package/dist/file-read.d.ts +4 -0
- package/dist/file-transfer.d.ts +29 -0
- package/dist/filesystem-extensions.d.ts +21 -0
- package/dist/freeze-reference.d.ts +1 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +5122 -0
- package/dist/observability.d.ts +64 -0
- package/dist/process-output.d.ts +33 -0
- package/dist/processes.d.ts +212 -0
- package/dist/recovery-diagnostics.d.ts +10 -0
- package/dist/resource.d.ts +175 -0
- package/dist/resources.d.ts +361 -0
- package/dist/scoped-sandbox.d.ts +30 -0
- package/package.json +36 -6
package/README.md
CHANGED
|
@@ -1,5 +1,121 @@
|
|
|
1
|
-
#
|
|
1
|
+
# TypeScript resource SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`beachside` uses an installed adapter in the caller's server-side Node.js or Bun process. Official Daytona and E2B adapters are available from `@beachside/daytona` and `@beachside/e2b`. The experimental Modal integration is installed separately as `@beachside/modal` and uses the same public adapter contract as custom integrations. The fake provider is a deterministic test fixture. Live provider qualification remains separate from the packaged API shape.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Install `beachside @beachside/daytona` (or `beachside @beachside/e2b`).
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { Beachside } from "beachside";
|
|
9
|
+
import { daytona } from "@beachside/daytona";
|
|
10
|
+
|
|
11
|
+
const beachside = await Beachside.connect(daytona({ apiKey: process.env.DAYTONA_API_KEY!, target: "us" }));
|
|
12
|
+
await beachside.close();
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { Beachside, Image } from "beachside";
|
|
17
|
+
import { daytona } from "@beachside/daytona";
|
|
18
|
+
|
|
19
|
+
const beachside = await Beachside.connect(daytona({ apiKey: process.env.DAYTONA_API_KEY!, target: "us" }));
|
|
20
|
+
try {
|
|
21
|
+
const box = await beachside.sandboxes.create({ environment: Image.prepared("your-snapshot-id") });
|
|
22
|
+
try {
|
|
23
|
+
const result = await box.exec(["printf", "hello"]);
|
|
24
|
+
console.log(result.stdoutText(4096));
|
|
25
|
+
} finally {
|
|
26
|
+
await box.destroy();
|
|
27
|
+
}
|
|
28
|
+
} finally {
|
|
29
|
+
await beachside.close();
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Provider credentials remain in the caller's process and are inappropriate for browser code. The repository's deterministic fake provider is an internal test fixture and is not published with the SDK.
|
|
34
|
+
|
|
35
|
+
`exec` and `submitExec` accept a `readonly string[]` shorthand, such as `box.exec(["git", "status"])`. Each element is a literal argument; arrays never invoke a shell. The shorthand uses the same validation and defaults as `{ command: { kind: "argv", argv } }`, including rejection of empty arrays. Use the object form for `cwd`, `env`, deadlines, output limits, or an explicit `{ kind: "shell", script }` command. Arguments are copied before dispatch.
|
|
36
|
+
|
|
37
|
+
`exec` returns exact `Uint8Array` stdout/stderr. A nonzero exit throws `NonzeroExitError` with the captured result; a completed execution with no exit code throws `NoExitCodeError`. Transport errors and unknown effects use separate errors. `stdoutText()` and `stderrText()` decode every captured byte as UTF-8 without a suffix; exported `outputText(bytes)` decodes every supplied byte. Existing `{ full: true }` calls remain equivalent. Pass an explicit numeric limit for bounded display, or use `stdoutPreview({ maxBytes? })` / `stderrPreview({ maxBytes? })` for `{ text, shortened }` with a 16 KiB default. Check `result.truncated` before parsing captured output. Full decoding cannot recover discarded capture; `shortened` is independent of `result.truncated`. Invalid display limits/options throw local `RangeError`s. File reads and writes default to a 1 MiB buffer bound; explicit `maxBytes` permits up to 16 MiB. Larger artifacts use `readFileStream`/`writeFileStream` with awaited byte chunks and no default whole-file ceiling.
|
|
38
|
+
|
|
39
|
+
`submitCreate` and `box.submitExec` return operation handles with `reference`, `observe()`, and `wait({ signal })`. Ordinary `create` and `exec` call `wait` themselves. A direct operation has `durability: "process"`. An abort signal stops waiting, not provider compute. If it fires after an ordinary mutation was submitted, `WaitAbortedError` carries the recovery reference and original abort reason. `close()` releases client-owned state and never destroys a sandbox; call `box.destroy()` explicitly.
|
|
40
|
+
|
|
41
|
+
References are versioned, serializable, and contain no credentials, command, environment, or file bytes. A direct reference records verified native scope, submission identity, and any required locator. The caller must separately configure a provider with the same scope to import it through `recover(reference)`. Recovery only observes; it never submits the mutation again. If native submission discovery is unavailable, an unknown effect remains unknown. Applications requiring a durable submission marker can use the optional `client.operations.prepare(...).submit(..., { beforeSubmit, onCheckpoint })` lifecycle, where `onCheckpoint` durably saves each versioned token before the provider proceeds, then persist pending-token updates and use observation-only recovery. Advanced mutations that call `ctx.checkpoint()` stop if this callback is missing or fails.
|
|
42
|
+
|
|
43
|
+
`await client.capabilities()` and `await box.capabilities()` return dated, detached observations that retain command, image, network, and file facts. State support has four outcomes: `supported`, `unsupported`, `unavailable`, and `unknown`. `await client.sandboxes.checkCreate(input)` and `await box.checkSnapshot(request)` are read-only checks on SDK connections. They never build images, reserve compute, stop a sandbox, or submit a capture. A supported check resolves a single profile with exact preservation, bounded interruption, source state, consistency, mount handling, and retention evidence; it is not a reservation. Snapshot restore and volume operations report provider-specific support independently.
|
|
44
|
+
|
|
45
|
+
Creation can require snapshot guarantees with `requirements: { snapshot: { requirements: { preserve: "filesystem" } } }`. `box.snapshot()` accepts the configured native default; optional requirements reject unsupported guarantees before effects. Daytona container capture stops/captures/restarts and preserves the filesystem with fresh restore execution. E2B capture preserves filesystem and memory. Unsupported combinations fail before allocation with `UNSUPPORTED` and `effect: "none"`; unavailable or unknown evidence fails with `UNAVAILABLE`. The mutation revalidates its plan before submission.
|
|
46
|
+
|
|
47
|
+
Snapshot handles expose inspect and separately supported restore/delete operations. Volume handles expose native management and create-time mount descriptors. Daytona supports restore and verified mounts. E2B restores the saved native build UUID with `templateId:buildUUID` and cleans up its dedicated containing template after identity, scope and dependency checks; E2B mounts remain unsupported because the pinned API exposes reusable names without mounted native IDs. Writable mounted compute needs explicit `storage: "allow-unconfirmed"` cleanup when shutdown durability cannot be established; destroy never deletes independently retained storage. Provider capabilities and live qualification remain separate evidence.
|
|
48
|
+
|
|
49
|
+
`ResourceReference` is the version-1 schema for resource identity, separate from an operation recovery reference. It supports sandbox, image, snapshot, volume, volume-version, mount, and session kinds, with verified provider scope, native locator, optional native generation, and ownership evidence (`borrowed`, `verified-created`, or `unknown`). `validateResourceReference`, `assertResourceScope`, and `assertResourceIdentity` validate serialized data and known identity. An adapter must supply generation evidence when a locator can be reused; the SDK never invents a generation or treats a reference as authority. These descriptors do not open, inspect, or delete artifacts, and cannot certify expiry or native ownership by themselves.
|
|
50
|
+
|
|
51
|
+
Requirement reads finish before the durable submission marker; the approved preparation is then dispatched without another capability read. For already-stopped sources, an unchanged lifecycle request accepts a stopped outcome.
|
|
52
|
+
|
|
53
|
+
Tracing uses your application’s OpenTelemetry provider. Set `tracing: false` to disable Beachside spans and propagation, or inject `tracing: { tracerProvider }`. Beachside never configures exporters or shuts down your provider. See the [tracing and safe diagnostics guide](https://beachside.run/docs/observability/) for pinned Node/Bun recipes and local-only vendor evidence; metrics and structured logs are a later release.
|
|
54
|
+
|
|
55
|
+
Persist resource and operation references as versioned JSON in your own application storage. Their historical observations do not depend on the original API key or a mandatory signature. Reopen with current credentials for the same verified native scope; E2B credential rotation requires verified `teamId` configuration. `onReference` is awaited before stage dispatches and when evidence changes. Observation stays read-only; explicit `operation.continue()` may advance a proven never-submitted next stage. Serialize continuation across processes through your own lease or compare-and-swap. E2B cleanup deletes the containing template, not an individual build, and rejects known shared expansion; the provider offers no transactional read/delete generation condition.
|
|
56
|
+
|
|
57
|
+
Empty restore resource maps and mount arrays are equivalent to omission. The SDK temporarily accepts legacy empty mount objects at runtime; see the migration below. Snapshot and volume deletion persist a rejected stage when cancellation is known to precede native dispatch. The SDK allows up to one second after caller cancellation to join deletion finalization and surface a proven rejection with `effect: "none"`; client close remains immediate, and a stalled finalization still reports uncertainty. Other mutation waits retain their existing cancellation behavior.
|
|
58
|
+
|
|
59
|
+
Start with the [everyday SDK guides](https://beachside.run/docs/guides/resources/) and [snapshots/volumes](https://beachside.run/docs/guides/snapshots-and-volumes/). Save `captured.snapshot.reference` or `volume.reference` in application storage and reopen with `client.snapshots.get(...)` or `client.volumes.get(...)` on a fresh matching connection. Handles expose `provider` and `id`. Confirmed partial capture errors expose the snapshot reference and capture details through `BeachsideError.outcome`; do not parse native tokens or repeat capture. The [compiled example](../../apps/docs/examples/recovery-outcomes.ts) demonstrates these paths. Existing checkpoint/continuation APIs are advanced compatibility paths, not a prerequisite for ordinary application persistence.
|
|
60
|
+
|
|
61
|
+
For explicit direct connection annotations, import `DirectBeachsideClient` and `DirectSandboxHandle` from `beachside`. They include `client.snapshots`, `client.volumes` and `sandbox.snapshot()`. `BeachsideClient` and `SandboxHandle` are aliases for those complete SDK surfaces.
|
|
62
|
+
|
|
63
|
+
Malformed snapshot requests, restore requests, inventory inputs, volume creation inputs and mount descriptors reject with `BeachsideError` (`INVALID_ARGUMENT`, effect `none`) before provider mutation. Restore preflight uses `UnsupportedFeatureError.unmetRequirements` to report network policy, sizing, independent lifecycle and mount limitations together. Native response validation remains separate from caller input errors.
|
|
64
|
+
|
|
65
|
+
Create and restore share `mounts: MountSpec[]` from `volume.at(path)`. Daytona selects exact current volumes alongside known mount-free filesystem/fresh snapshot state under `internet` or `daytona-default` networking; mounted `blocked` restore rejects before allocation. Unknown/recorded mount provenance and memory composition remain unsupported. No implicit storage creation, copying or name substitution occurs. Independent lifecycle is required unless explicitly set to `false`.
|
|
66
|
+
|
|
67
|
+
The coordinated SDK/adapter release R replaces legacy action maps. Nonempty maps reject with `INVALID_ARGUMENT` and migration guidance. The SDK-only empty-object alias remains in R and the next published release R+1, then is removed at the next API release. Public types use arrays. Nonempty arrays require `snapshotRestore.mountInput: "specs"` before hook preparation; older hooks receive mount-free requests with no mounts field. Record actual R during version preparation. Snapshot, volume, sandbox and operation reference formats stay unchanged.
|
|
68
|
+
|
|
69
|
+
Unknown restore outcomes expose selected `mounts` and an acknowledged `sandbox` reference when available. Persist these with the operation reference and reconcile read-only without another allocation. The first bounded mounted-restore acceptance at `824946d` passed A startup evidence, then failed a harness snapshot-name/ID assertion before B. The corrected workflow passed live at `5911ccc`: A and independently empty B passed first-action selected-data checks, private-state preservation, exact native identities and fresh-client reopening, with all owned resources cleaned up. Deterministic and packed evidence are separate from live qualification.
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
## Reopen Beachside-created compute
|
|
73
|
+
|
|
74
|
+
Direct SDK sandbox handles expose `reference: SandboxReference | null`. Save that reference in an application-owned trusted store and configure a fresh connection with the same native binding:
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
const reference = sandbox.reference ?? (await sandbox.inspect()).reference;
|
|
78
|
+
if (!reference) throw new Error("Verified sandbox identity is unavailable");
|
|
79
|
+
const saved = JSON.parse(JSON.stringify(reference));
|
|
80
|
+
await client.close();
|
|
81
|
+
const reopened = await freshClient.sandboxes.get(saved);
|
|
82
|
+
const info = await reopened.inspect();
|
|
83
|
+
if (info.state === "running") {
|
|
84
|
+
const bytes = await reopened.readFile("/tmp/work.txt");
|
|
85
|
+
const output = await reopened.exec(["/bin/sh", "-c", "printf reopened"]);
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
References contain native identity, provider/scope and the native creation selectors required for verification; no credentials, observations or workflow journal. Successful create, snapshot restore and recovered results issue references after native verification. Legacy adapters may return null; a failed optional identity read after confirmed Daytona creation also returns a usable handle with null reference rather than hiding completed creation. A later `inspect().reference` can supply verified identity when native metadata becomes readable. Do not save null or synthesize a reference from the display ID.
|
|
90
|
+
|
|
91
|
+
`get` reads native detail and never creates, resumes or extends lifetime. Stopped/suspended resources remain inactive. `inspect` supplies current `nativeState`, local receipt `observedAt`, hard expiry, idle-stop policy and stopped-retention facts. Unknown facts remain unknown; an elapsed deadline alone does not establish deletion. Missing/expired/deleted resources fail `NOT_FOUND`, native authorization fails `FORBIDDEN`, transport/detail access fails `UNAVAILABLE`, and identity/configuration mismatch fails `CONFLICT`. A destroyed tombstone can be inspected but cannot be reopened.
|
|
92
|
+
|
|
93
|
+
Applications own persistence, fresh credentials and serialization of competing operations. There is a crash window before the reference is saved. Operation recovery references retain the verified sandbox reference so fresh-process observation and continuation check the original creation correlation. Older operation references retain their ID-only behavior. Existing operation recovery remains separate and read-only; reopening compute does not replay a command or recover a mutation. Configured `renew()` and native `suspend()`/`resume()` are available through optional adapter hooks; no implicit mutation is added to reopening. Deterministic/packed tests cover this slice; its new live reopening workflow has not run.
|
|
94
|
+
|
|
95
|
+
## Native sandbox suspension
|
|
96
|
+
|
|
97
|
+
Configure `lifecycle.suspension.preserve` once on a compatible adapter as a minimum, then call `await box.suspend()`. Save `box.reference`, open it with `await freshClient.sandboxes.get(savedReference)` while inactive, and call `await box.resume()` explicitly. Submit forms use the existing operation/result/recovery conventions. Daytona containers preserve filesystem and terminate processes; E2B pauses with memory and reports unknown execution continuity on resume. Both drop connections, retain the same scoped ID and never replace expired compute. Daytona requires known empty native mounts. E2B rejects known native mounts but permits absent mount metadata without claiming an empty set; preservation covers private filesystem/RAM, excluding external-storage flush, durability, atomic consistency and remote connection continuity. Daytona hard TTL keeps ticking; E2B paused state has indefinite retention requiring explicit destruction. Lost ACK stays uncertain and recovery only observes; acknowledged native facts remain directly accessible on partial/aborted errors. Unsupported adapters still support their other operations. Daytona suspension passed live at `6796b30`; E2B's revised private-state mapping passed at `26f516d`, with earlier failures retained and owned cleanup confirmed.
|
|
98
|
+
|
|
99
|
+
## Filesystem workflows
|
|
100
|
+
|
|
101
|
+
`readDirectory` returns bounded immediate children with honest completeness and an observation timestamp. `statFile` reports link identity by default and only available metadata; `fileExists` distinguishes absence from permission/transport failure. Mkdir/remove preserve recursive opt-in. `copyFile` stages regular-file bytes and `moveFile` performs same-filesystem rename; both default to no-clobber. Daytona and E2B implement these operations on compatible private Linux filesystems with Python 3 and native rename prerequisites.
|
|
102
|
+
|
|
103
|
+
Streams use `AsyncIterable<Uint8Array>` with backpressure and split chunks up to 64 KiB. `writeFileStream` returns the confirmed byte count. Configure `transfers: { setupTimeoutMs, inactivityTimeoutMs, overallTimeoutMs }` on connection or override those fields per call. Defaults are 30-second setup, 60-second active IO inactivity and no overall deadline. Consumer processing does not trigger inactivity failure. `FilesystemError.details` retains known source/destination, temporary paths and transferred bytes when remote effects or cleanup are uncertain; do not replay uncertain mutations. A timeout or cancellation during staging cleanup preserves `effect: "applied"` after confirmed publication, with remaining correlated temporary paths indicating unfinished cleanup. See [the portable artifact recipe](../../apps/docs/examples/directory-files.ts) and [file guide](../../apps/docs/src/content/docs/docs/guides/files-and-output.md).
|
|
104
|
+
|
|
105
|
+
`walkFiles(path, { maxDepth, maxEntries, exclude, signal })` yields deterministic depth-first entries with absolute `path`, root-relative `relativePath` and `depth` (children start at 1). Defaults are depth 32 and 10,000 observed entries; exact relative-path exclusions prune subtrees, and excluded entries still count. Symlinks/unknown types are yielded without descent. Incomplete listings, unreadable subtrees and budget overflow reject. Traversal is an observation of a changing namespace, not a snapshot or confinement boundary.
|
|
106
|
+
|
|
107
|
+
`readTextLines(path, { maxLineBytes, ...transferOptions })` incrementally decodes UTF-8, handles split code points and LF/CRLF, preserves lone CR, and yields the final unterminated line without a spurious terminal empty line. Malformed UTF-8 uses replacement decoding. The default line limit is 1 MiB of source bytes excluding delimiters; overflow rejects with `OUTPUT_CAPACITY`. Both helpers compose existing adapter hooks. Fixture/packed acceptance is separate from live evidence; the older `2f6afe8` artifact passes predate F4, while the expanded recipe passed at `e91f2d5` on both borrowed provider images with confirmed cleanup. Range reads, batch transfer, glob/search and tree copy remain deferred.
|
|
108
|
+
|
|
109
|
+
## Process output profiles
|
|
110
|
+
|
|
111
|
+
Start a sustained process with `output: { mode: "stream" }` and consume `child.output()` promptly. The default yields separate stdout/stderr text. Choose `output: { mode: "stream", format: "bytes" }` before start to receive `{ stream, bytes: Uint8Array }` chunks containing original native bytes, including NUL and malformed UTF-8. Type inference selects `ProcessHandle<"bytes">`; no decoder or implicit re-encoding runs in this profile. Unsupported byte transports reject before starting.
|
|
112
|
+
|
|
113
|
+
Both profiles have one consumer, 16 KiB maximum emitted chunks, and a 64 KiB/256-chunk pending queue. Admitted byte buffers are copied. Slow consumers receive explicit output failure while independently usable wait/status/input/termination remain available. Returning a sustained output iterator releases output only; `detach()` disposes the full local handle without terminating remote compute. Output completeness requires native end plus delivery of all admitted chunks. The byte profile promises per-stream byte order, with no framing or cross-stream ordering guarantee. PTYs and reconnection use the explicit APIs below.
|
|
114
|
+
|
|
115
|
+
`child.signal("SIGTERM" | "SIGKILL")` requests a named signal independently of confirmed exit; `terminate()` remains the SIGKILL convenience. `child.reference()` snapshots a private, scoped, expiring JSON selector. Call `disconnect()` to park local observation without EOF or termination, then `box.processes.reopen(saved)` on the same sandbox through a fresh matching connection. An old handle is fenced; pending EOF or uncertain input prevents reference creation. Reopened handles expose `outputGap: true` and never claim complete output. There is no retained transcript replay or exact emission-time cutoff; native buffers may deliver earlier bytes. Reference availability is limited by native process/sandbox lifetime and at most 24 hours.
|
|
116
|
+
|
|
117
|
+
`box.terminals.start({ command, columns: 80, rows: 24 })` creates an explicit controlling terminal. `output()` yields combined `Uint8Array` chunks; `write`, `resize`, status, wait, signals and termination remain portable. Terminals omit pipe EOF. Save their reference and use `box.terminals.reopen(saved)` for live reattachment. PTY echo, newline translation and buffering differ from ordinary pipes. `readProcessLines()` and `createProcessTail()` compose either text or byte pipe output into bounded diagnostic lines/windows with explicit partial/truncated flags; they do not retain provider logs or own compute. See the [process guide](../../apps/docs/src/content/docs/docs/guides/text-streaming.md) for limits and adapter guarantees.
|
|
118
|
+
|
|
119
|
+
## Consumer types
|
|
120
|
+
|
|
121
|
+
Use `BeachsideClient`, `SandboxHandle`, `SnapshotHandle`, `VolumeHandle`, `OperationHandle<T>` and `RecoveryReference` for application annotations. Concrete connection/handle declarations use the optional `true` type parameter to preserve their complete advanced and nominal compatibility surface; ordinary annotations retain their existing structural view. Concrete operations include a kind type parameter for continuation and recovery narrowing. Existing Adapter*/Direct* names, runtime classes and `instanceof` behavior remain supported. See the TypeScript reference for staged migration and advanced compatibility access.
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import { type SandboxScopeOptions } from "./scoped-sandbox.js";
|
|
2
|
+
import { type ConnectionWaitOptions, type CloseOptions } from "./connection-wait.js";
|
|
3
|
+
import { type FileReadOptions, type FileWriteOptions, type FileStreamOptions, type FileStreamWriteOptions, type TransferPolicy } from "./file-transfer.js";
|
|
4
|
+
import { type FileEntry } from "@beachside/adapter";
|
|
5
|
+
import { type WalkFilesOptions, type WalkFileEntry, type ReadTextLinesOptions } from "./filesystem-extensions.js";
|
|
6
|
+
import { type ProcessReference, type StartTerminalInput, type TerminalHandle, type ExecOptions, type StartProcessInput, type ProcessHandle, type ProcessOutputFormat } from "./processes.js";
|
|
7
|
+
import { CaptureExpectation, type AdapterRecoveryReference as RecoveryReference } from "./adapter-reference.js";
|
|
8
|
+
import { Telemetry, type ObservabilityOptions } from "./observability.js";
|
|
9
|
+
import { SuspendResult, ResumeResult, type LifecycleIntent, type Preview, RenewRequest, RenewResult, type SandboxReference, type SandboxInfo as AdapterSandboxInfo, type Fact, type SandboxResources, type Support, SnapshotRequest, type SnapshotPlan, type CreatePlan, type DirectCapabilities } from "@beachside/adapter";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
import { resourceManagers, type SandboxList, type SandboxListInput, type SnapshotResult, type WaitOptions } from "./resources.js";
|
|
12
|
+
import { ResourceReference, type ArtifactDeletionResult, type DestroyValue, type OperationInput } from "@beachside/adapter";
|
|
13
|
+
import { type AdapterConnection, type AdapterDefinition, type RuntimeSession, type CreateInput as AdapterCreateInput, type ImageBuildInput, type Json, type OperationKind, type PreparedOperation, type RuntimeResult, type Scope, type Sandbox } from "@beachside/adapter";
|
|
14
|
+
import { type ReadOptions, type BeachsideClient, type SandboxHandle, type VolumeHandle, type OperationHandle, type CreateInput, type ExecInput, type ExecOutput, type ImageBuildResult } from "./resource.js";
|
|
15
|
+
import type { BoundAdapter } from "./bound.js";
|
|
16
|
+
/** A sandbox observation; `resources` is always present, as unknown when the adapter can't read it. */
|
|
17
|
+
export type SandboxInfo = AdapterSandboxInfo & {
|
|
18
|
+
resources: Fact<SandboxResources>;
|
|
19
|
+
};
|
|
20
|
+
export { Image, outputText } from "./resource.js";
|
|
21
|
+
export type { AdapterRecoveryReference } from "./adapter-reference.js";
|
|
22
|
+
export type AdapterCapabilities = DirectCapabilities;
|
|
23
|
+
export type RecoveredOperation = OperationHandle<SandboxHandle<true>, "create" | "snapshot_restore"> | OperationHandle<SuspendResult, "sandbox_suspend"> | OperationHandle<ResumeResult, "sandbox_resume"> | OperationHandle<RenewResult, "sandbox_renew"> | OperationHandle<SnapshotResult, "snapshot_capture"> | OperationHandle<VolumeHandle, "volume_create"> | OperationHandle<ArtifactDeletionResult, "snapshot_delete" | "volume_delete" | "image_delete"> | OperationHandle<ImageBuildResult, "image_build"> | OperationHandle<ExecOutput, "exec"> | OperationHandle<DestroyValue, "destroy"> | OperationHandle<void, "file_write" | "file_mkdir" | "file_remove">;
|
|
24
|
+
/** Use the OperationHandle type for consumer annotations. This compatibility runtime class remains supported. */
|
|
25
|
+
export declare class AdapterOperation<T, K extends OperationKind = OperationKind> {
|
|
26
|
+
#private;
|
|
27
|
+
private readonly client;
|
|
28
|
+
private readonly decode;
|
|
29
|
+
readonly kind: K;
|
|
30
|
+
readonly durability: "process";
|
|
31
|
+
private first;
|
|
32
|
+
get reference(): RecoveryReference;
|
|
33
|
+
private continuing;
|
|
34
|
+
private revision;
|
|
35
|
+
private persistence;
|
|
36
|
+
private persistedReference?;
|
|
37
|
+
private terminal?;
|
|
38
|
+
private pendingAt;
|
|
39
|
+
private nextPollAt;
|
|
40
|
+
constructor(client: AdapterDirectClient, reference: RecoveryReference, decode: (value: RuntimeResult, ref: RecoveryReference) => T, first?: RuntimeResult, kind?: K);
|
|
41
|
+
/** Advance proven unsubmitted stages. Applications serialize continuation across processes. */
|
|
42
|
+
continue(options?: {
|
|
43
|
+
signal?: AbortSignal;
|
|
44
|
+
}): Promise<this>;
|
|
45
|
+
private persistReference;
|
|
46
|
+
observe(): Promise<T | null>;
|
|
47
|
+
private observeWithSignal;
|
|
48
|
+
wait(options?: {
|
|
49
|
+
signal?: AbortSignal;
|
|
50
|
+
pollMs?: number;
|
|
51
|
+
}): Promise<T>;
|
|
52
|
+
}
|
|
53
|
+
/** Use the SandboxHandle type for consumer annotations. This compatibility runtime class remains supported. */
|
|
54
|
+
export declare class AdapterSandbox {
|
|
55
|
+
#private;
|
|
56
|
+
private readonly client;
|
|
57
|
+
readonly id: string;
|
|
58
|
+
private invalidateProcessControl;
|
|
59
|
+
get reference(): SandboxReference | null;
|
|
60
|
+
constructor(client: AdapterDirectClient, id: string, reference?: SandboxReference | null);
|
|
61
|
+
readonly terminals: {
|
|
62
|
+
start: (input: StartTerminalInput, options?: WaitOptions) => Promise<TerminalHandle>;
|
|
63
|
+
reopen: (reference: ProcessReference<"bytes">, options?: WaitOptions) => Promise<TerminalHandle>;
|
|
64
|
+
};
|
|
65
|
+
readonly processes: {
|
|
66
|
+
reopen: <F extends ProcessOutputFormat>(reference: ProcessReference<F>, options?: WaitOptions) => Promise<ProcessHandle<F>>;
|
|
67
|
+
start: <F extends ProcessOutputFormat = "text">(input: StartProcessInput<F>, options?: WaitOptions) => Promise<ProcessHandle<F>>;
|
|
68
|
+
};
|
|
69
|
+
submitSuspend(options?: WaitOptions): Promise<OperationHandle<SuspendResult, "sandbox_suspend">>;
|
|
70
|
+
suspend(options?: WaitOptions): Promise<SuspendResult>;
|
|
71
|
+
submitResume(options?: WaitOptions): Promise<OperationHandle<ResumeResult, "sandbox_resume">>;
|
|
72
|
+
resume(options?: WaitOptions): Promise<ResumeResult>;
|
|
73
|
+
submitRenew(input?: RenewRequest, options?: WaitOptions): Promise<OperationHandle<RenewResult, "sandbox_renew">>;
|
|
74
|
+
renew(input?: RenewRequest, options?: WaitOptions): Promise<RenewResult>;
|
|
75
|
+
submitSnapshot(request?: SnapshotRequest, options?: WaitOptions): Promise<OperationHandle<SnapshotResult, OperationKind>>;
|
|
76
|
+
snapshot(request?: SnapshotRequest, options?: WaitOptions): Promise<SnapshotResult>;
|
|
77
|
+
capabilities(): Promise<AdapterCapabilities>;
|
|
78
|
+
checkSnapshot(request?: SnapshotRequest): Promise<Support<SnapshotPlan>>;
|
|
79
|
+
private checkSnapshotWithSignal;
|
|
80
|
+
supports(feature: "inspect" | "exec" | "readFile" | "writeFile" | "destroy" | "readDirectory" | "walkFiles" | "readTextLines" | "statFile" | "readFileStream" | "writeFileStream" | "copyFile" | "moveFile" | "listFiles" | "fileExists" | "makeDirectory" | "removeFile"): boolean;
|
|
81
|
+
inspect(options?: WaitOptions): Promise<SandboxInfo>;
|
|
82
|
+
/** Resolve access to an existing running sandbox; URL availability is not readiness. */
|
|
83
|
+
preview(port: number, options?: {
|
|
84
|
+
signal?: AbortSignal;
|
|
85
|
+
}): Promise<Preview>;
|
|
86
|
+
submitExec(input: ExecInput | readonly string[], options?: {
|
|
87
|
+
signal?: AbortSignal;
|
|
88
|
+
}): Promise<OperationHandle<ExecOutput, OperationKind>>;
|
|
89
|
+
exec(input: ExecInput | readonly string[], options?: ExecOptions): Promise<ExecOutput>;
|
|
90
|
+
/** Decode the complete bounded file as UTF-8, replacing malformed sequences and consuming its BOM. */
|
|
91
|
+
readTextFile(path: string, options?: FileReadOptions): Promise<string>;
|
|
92
|
+
/** Encode UTF-8 using the byte write's limits, cancellation and no-clobber default. */
|
|
93
|
+
writeTextFile(path: string, text: string, options?: FileWriteOptions): Promise<void>;
|
|
94
|
+
readDirectory(path: string, options?: ReadOptions): Promise<import("@beachside/adapter").DirectoryResult>;
|
|
95
|
+
/** Depth-first traversal, with complete listings and no descent into links or unknown entries. */
|
|
96
|
+
walkFiles(path: string, options?: WalkFilesOptions): AsyncIterable<WalkFileEntry>;
|
|
97
|
+
/** Incrementally decode UTF-8 lines, removing LF/CRLF delimiters and bounding each line. */
|
|
98
|
+
readTextLines(path: string, options?: ReadTextLinesOptions): AsyncIterable<string>;
|
|
99
|
+
statFile(path: string, options?: ReadOptions & {
|
|
100
|
+
followSymlinks?: boolean;
|
|
101
|
+
}): Promise<import("@beachside/adapter").FileStat>;
|
|
102
|
+
readFileStream(path: string, options?: FileStreamOptions): AsyncIterable<Uint8Array>;
|
|
103
|
+
writeFileStream(path: string, bytes: AsyncIterable<Uint8Array>, options?: FileStreamWriteOptions): Promise<number>;
|
|
104
|
+
copyFile(source: string, destination: string, options?: {
|
|
105
|
+
overwrite?: boolean;
|
|
106
|
+
signal?: AbortSignal;
|
|
107
|
+
}): Promise<void>;
|
|
108
|
+
moveFile(source: string, destination: string, options?: {
|
|
109
|
+
overwrite?: boolean;
|
|
110
|
+
signal?: AbortSignal;
|
|
111
|
+
}): Promise<void>;
|
|
112
|
+
private transferFile;
|
|
113
|
+
listFiles(path: string, options?: ReadOptions): Promise<FileEntry[]>;
|
|
114
|
+
fileExists(path: string, options?: ReadOptions): Promise<boolean>;
|
|
115
|
+
makeDirectory(path: string, options?: {
|
|
116
|
+
recursive?: boolean;
|
|
117
|
+
signal?: AbortSignal;
|
|
118
|
+
}): Promise<void>;
|
|
119
|
+
removeFile(path: string, options?: {
|
|
120
|
+
recursive?: boolean;
|
|
121
|
+
signal?: AbortSignal;
|
|
122
|
+
}): Promise<void>;
|
|
123
|
+
private fileMutation;
|
|
124
|
+
readFile(path: string, options?: FileReadOptions): Promise<Uint8Array>;
|
|
125
|
+
writeFile(path: string, bytes: Uint8Array, options?: FileWriteOptions): Promise<void>;
|
|
126
|
+
submitDestroy(options?: {
|
|
127
|
+
signal?: AbortSignal;
|
|
128
|
+
storage?: "require-durable" | "allow-unconfirmed";
|
|
129
|
+
}): Promise<OperationHandle<import("@beachside/adapter").DestroyValue, OperationKind>>;
|
|
130
|
+
destroy(options?: {
|
|
131
|
+
signal?: AbortSignal;
|
|
132
|
+
storage?: "require-durable" | "allow-unconfirmed";
|
|
133
|
+
}): Promise<import("@beachside/adapter").DestroyValue>;
|
|
134
|
+
}
|
|
135
|
+
/** Optional lifecycle API for applications with their own durable operation ledger. */
|
|
136
|
+
export declare const ADAPTER_CONTRACT_VERSION: 1;
|
|
137
|
+
export type AdvancedOperationResult = RuntimeResult;
|
|
138
|
+
export type AdvancedOperationKind = OperationKind;
|
|
139
|
+
export type AdvancedIdentity = {
|
|
140
|
+
operationId: string;
|
|
141
|
+
submissionId: string;
|
|
142
|
+
invocationKey: string;
|
|
143
|
+
};
|
|
144
|
+
export type AdvancedObservation = {
|
|
145
|
+
lifecycle?: LifecycleIntent;
|
|
146
|
+
renewal?: RenewRequest;
|
|
147
|
+
capture?: RecoveryReference["capture"];
|
|
148
|
+
scope: Scope;
|
|
149
|
+
kind: OperationKind;
|
|
150
|
+
operationId: string;
|
|
151
|
+
submissionId: string;
|
|
152
|
+
sandboxId?: string;
|
|
153
|
+
sandboxReference?: SandboxReference;
|
|
154
|
+
resource?: ResourceReference;
|
|
155
|
+
mounts?: import("@beachside/adapter").MountSpec[];
|
|
156
|
+
token?: Json;
|
|
157
|
+
tokenVersion?: number;
|
|
158
|
+
};
|
|
159
|
+
export declare class PreparedAdapterAttempt {
|
|
160
|
+
private readonly client;
|
|
161
|
+
private readonly prepared;
|
|
162
|
+
private readonly kind;
|
|
163
|
+
private readonly maxOutputBytes?;
|
|
164
|
+
private used;
|
|
165
|
+
constructor(client: AdapterDirectClient, prepared: PreparedOperation, kind: OperationKind, maxOutputBytes?: number | undefined);
|
|
166
|
+
get lifecycle(): Readonly<LifecycleIntent> | undefined;
|
|
167
|
+
/** Resolved renewal intent to persist in beforeSubmit and supply to operations.observe. */
|
|
168
|
+
get renewal(): Readonly<RenewRequest> | undefined;
|
|
169
|
+
/** The callback must durably record the submission marker; false cancels dispatch. */
|
|
170
|
+
submit(identity: AdvancedIdentity, options: {
|
|
171
|
+
beforeSubmit: () => Promise<boolean>;
|
|
172
|
+
signal?: AbortSignal;
|
|
173
|
+
onCheckpoint?: (token: Json, version: number) => Promise<void>;
|
|
174
|
+
}): Promise<AdvancedOperationResult | null>;
|
|
175
|
+
}
|
|
176
|
+
/** Use the BeachsideClient type for consumer annotations. This compatibility runtime class remains supported. */
|
|
177
|
+
export declare class AdapterDirectClient {
|
|
178
|
+
readonly provider: string;
|
|
179
|
+
private readonly connection;
|
|
180
|
+
private readonly onReference?;
|
|
181
|
+
readonly cleanupStorage: "require-durable" | "allow-unconfirmed";
|
|
182
|
+
readonly transferPolicy: TransferPolicy;
|
|
183
|
+
private closed;
|
|
184
|
+
private closePromise?;
|
|
185
|
+
/** @deprecated Advanced compatibility access; prefer documented SDK operations. */
|
|
186
|
+
readonly telemetry: Telemetry;
|
|
187
|
+
/** @deprecated Advanced compatibility access; prefer documented SDK operations. */
|
|
188
|
+
readonly session: RuntimeSession;
|
|
189
|
+
/** @deprecated Advanced compatibility access; prefer documented SDK operations. */
|
|
190
|
+
readonly scope: Scope;
|
|
191
|
+
readonly operations: {
|
|
192
|
+
inventory: (input: {
|
|
193
|
+
cursor?: string;
|
|
194
|
+
limit: number;
|
|
195
|
+
}) => Promise<{
|
|
196
|
+
items: {
|
|
197
|
+
id: string;
|
|
198
|
+
state: "running" | "destroyed" | "unknown";
|
|
199
|
+
}[];
|
|
200
|
+
nextCursor?: string;
|
|
201
|
+
}>;
|
|
202
|
+
prepare: (kind: OperationKind, input: OperationInput, options?: {
|
|
203
|
+
signal?: AbortSignal;
|
|
204
|
+
maxOutputBytes?: number;
|
|
205
|
+
}) => Promise<PreparedAdapterAttempt>;
|
|
206
|
+
observe: (input: AdvancedObservation, options?: {
|
|
207
|
+
signal?: AbortSignal;
|
|
208
|
+
}) => Promise<AdvancedOperationResult | null>;
|
|
209
|
+
};
|
|
210
|
+
readonly signal: AbortSignal;
|
|
211
|
+
readonly sandboxes: {
|
|
212
|
+
with: <T>(input: CreateInput | undefined, callback: (sandbox: SandboxHandle<true>) => T | Promise<T>, options?: SandboxScopeOptions) => Promise<T>;
|
|
213
|
+
get: (reference: SandboxReference, options?: WaitOptions) => Promise<SandboxHandle<true>>;
|
|
214
|
+
/** List a bounded page of sandboxes; listed references reopen with `get`. */
|
|
215
|
+
list: (input?: SandboxListInput) => Promise<SandboxList>;
|
|
216
|
+
checkCreate: (input?: CreateInput) => Promise<Support<CreatePlan>>;
|
|
217
|
+
create: (input?: CreateInput, options?: {
|
|
218
|
+
signal?: AbortSignal;
|
|
219
|
+
}) => Promise<SandboxHandle<true>>;
|
|
220
|
+
submitCreate: (input?: CreateInput, options?: {
|
|
221
|
+
signal?: AbortSignal;
|
|
222
|
+
}) => Promise<OperationHandle<SandboxHandle<true>, OperationKind>>;
|
|
223
|
+
};
|
|
224
|
+
readonly snapshots: ReturnType<typeof resourceManagers>["snapshots"];
|
|
225
|
+
readonly volumes: ReturnType<typeof resourceManagers>["volumes"];
|
|
226
|
+
readonly images: ReturnType<typeof resourceManagers>["images"] & {
|
|
227
|
+
build: (input: ImageBuildInput, options?: {
|
|
228
|
+
signal?: AbortSignal;
|
|
229
|
+
}) => Promise<ImageBuildResult>;
|
|
230
|
+
submitBuild: (input: ImageBuildInput, options?: {
|
|
231
|
+
signal?: AbortSignal;
|
|
232
|
+
}) => Promise<OperationHandle<ImageBuildResult, OperationKind>>;
|
|
233
|
+
};
|
|
234
|
+
constructor(provider: string, connection: AdapterConnection<RuntimeSession>, onReference?: ((reference: RecoveryReference) => void | Promise<void>) | undefined, observability?: ObservabilityOptions, cleanupStorage?: "require-durable" | "allow-unconfirmed", transferPolicy?: TransferPolicy);
|
|
235
|
+
isClosed(): boolean;
|
|
236
|
+
ensureOpen(): void;
|
|
237
|
+
capabilities(target?: {
|
|
238
|
+
sandbox?: Sandbox;
|
|
239
|
+
create?: AdapterCreateInput;
|
|
240
|
+
}, options?: WaitOptions): Promise<AdapterCapabilities>;
|
|
241
|
+
checkCreate(input?: CreateInput): Promise<Support<CreatePlan>>;
|
|
242
|
+
private checkCreateWithSignal;
|
|
243
|
+
private checkImageBinding;
|
|
244
|
+
submitCreate(input?: CreateInput, options?: {
|
|
245
|
+
signal?: AbortSignal;
|
|
246
|
+
}): Promise<OperationHandle<SandboxHandle<true>, OperationKind>>;
|
|
247
|
+
private reopenSandbox;
|
|
248
|
+
submitBuild(input: ImageBuildInput, options?: {
|
|
249
|
+
signal?: AbortSignal;
|
|
250
|
+
}): Promise<OperationHandle<ImageBuildResult, OperationKind>>;
|
|
251
|
+
/** Decode a confirmed build; a missing adapter reference is never promoted to verified. */
|
|
252
|
+
private builtImage;
|
|
253
|
+
submit<T, K extends OperationKind = OperationKind>(kind: K, input: OperationInput, decode: (result: RuntimeResult, ref: RecoveryReference) => T, options?: {
|
|
254
|
+
signal?: AbortSignal;
|
|
255
|
+
sandboxId?: string;
|
|
256
|
+
sandboxReference?: SandboxReference;
|
|
257
|
+
resource?: ResourceReference;
|
|
258
|
+
capture?: z.infer<typeof CaptureExpectation>;
|
|
259
|
+
mounts?: import("@beachside/adapter").MountSpec[];
|
|
260
|
+
networkPolicy?: string;
|
|
261
|
+
file?: {
|
|
262
|
+
path: string;
|
|
263
|
+
bytes: number;
|
|
264
|
+
};
|
|
265
|
+
fileMutation?: RecoveryReference["fileMutation"];
|
|
266
|
+
maxOutputBytes?: number;
|
|
267
|
+
}): Promise<OperationHandle<T, K>>;
|
|
268
|
+
checkedOutcome(reference: RecoveryReference, outcome?: import("@beachside/adapter").OperationOutcome): import("@beachside/adapter").OperationOutcome | undefined;
|
|
269
|
+
persistReference(reference: RecoveryReference): Promise<void>;
|
|
270
|
+
private assertRecoverySandbox;
|
|
271
|
+
recover(reference: RecoveryReference): Promise<RecoveredOperation>;
|
|
272
|
+
close(options?: CloseOptions): Promise<void>;
|
|
273
|
+
}
|
|
274
|
+
/** Default storage requirement for new compute cleanup submissions. */
|
|
275
|
+
export type ConnectOptions = ObservabilityOptions & ConnectionWaitOptions & {
|
|
276
|
+
onDiagnostic?: (error: unknown) => void;
|
|
277
|
+
cleanup?: {
|
|
278
|
+
storage?: "require-durable" | "allow-unconfirmed";
|
|
279
|
+
};
|
|
280
|
+
transfers?: TransferPolicy;
|
|
281
|
+
};
|
|
282
|
+
/** Compatibility name for connection controls. */
|
|
283
|
+
export type DirectConnectOptions = ConnectOptions;
|
|
284
|
+
export type { CloseOptions } from "./connection-wait.js";
|
|
285
|
+
export type AdapterConnectOptions<C extends z.ZodType, K extends z.ZodType, S extends RuntimeSession> = ConnectOptions & {
|
|
286
|
+
adapter: Pick<AdapterDefinition<C, K, S>, "name" | "config" | "credentials"> & {
|
|
287
|
+
connect: (input: never) => Promise<S>;
|
|
288
|
+
policy?: {
|
|
289
|
+
schema: z.ZodType;
|
|
290
|
+
default: Json;
|
|
291
|
+
};
|
|
292
|
+
};
|
|
293
|
+
config: z.input<C>;
|
|
294
|
+
credentials: z.input<K>;
|
|
295
|
+
onReference?: (reference: RecoveryReference) => void | Promise<void>;
|
|
296
|
+
onDiagnostic?: (error: unknown) => void;
|
|
297
|
+
};
|
|
298
|
+
export declare function connectDirect(adapter: BoundAdapter, options?: ConnectOptions): Promise<BeachsideClient<true>>;
|
|
299
|
+
export declare function connectDirect<C extends z.ZodType, K extends z.ZodType, S extends RuntimeSession>(options: AdapterConnectOptions<C, K, S>): Promise<BeachsideClient<true>>;
|