UNPKG

@luxorai/sandbox

Version:

TypeScript SDK for Luxor Sandbox: cloud sandboxes (microVMs) for AI agents on Luxor Agent Cloud

265 lines (264 loc) • 13.9 kB
import { type Client } from "@connectrpc/connect"; import type { SessionCost } from "./cost.js"; import { type DataPlaneConfig } from "./data-plane.js"; import { type DialOptions, type DialStream } from "./dial.js"; import { type FileInfo, type ListOptions as FsListOptions, type ReadStreamOptions, type WriteStreamOptions } from "./fs.js"; import { Git } from "./git.js"; import { InjectionCredentialInput, type InjectionCredentialMetadata } from "./injection-credentials.js"; import type { SandboxSession, SessionEgressHttpRule } from "./internal/proto/tenki/sandbox/v1/sandbox_pb.js"; import { WildcardStatus as ProtoWildcardStatus, SandboxService, SandboxSessionDataPlaneService } from "./internal/proto/tenki/sandbox/v1/sandbox_pb.js"; import type { SessionMetrics } from "./metrics.js"; import type { DetachVolumeOptions, EgressHttpRule, ExecOptions, ExposePortOptions, ForkOptions, SecretsRefresh, UpdateSessionOptions, VolumeMountConfig } from "./options.js"; import { type ProcessRunHandle, type ProcessRunOptions } from "./process.js"; import type { ExecResult } from "./result.js"; import { type Snapshot } from "./snapshot.js"; import { type SSHConnection, type SSHConnectOptions } from "./ssh.js"; import { type StorageMount, type StorageMountConfig } from "./storage.js"; import { Stream } from "./stream.js"; import { type TailnetStatus } from "./tailnet.js"; import { type ResilientHostPortTunnel, type ResilientHostPortTunnelOptions } from "./tunnel-resilient.js"; import { type HostPortTunnel, type HostPortTunnelOptions } from "./tunnel.js"; import { type SandboxWarning, type WarningHandler } from "./warning.js"; export type SessionState = "UNSPECIFIED" | "CREATING" | "RUNNING" | "PAUSED" | "USER_SHUTDOWN" | "PAUSING" | "RESUMING" | "TERMINATING" | "TERMINATED"; export type RuntimeState = "UNSPECIFIED" | "STARTING" | "READY" | "FAILED" | "STOPPED"; /** RESTRICTED limits outbound traffic to the platform's allowlist of developer services. */ export type NetworkMode = "UNSPECIFIED" | "FULL" | "RESTRICTED"; /** NEVER_PURCHASED means the workspace has not purchased credits. */ export type NetworkRestrictionReason = "UNSPECIFIED" | "NEVER_PURCHASED"; /** * Readiness of the workspace wildcard domain backing a wildcard-scheme * preview URL (the workspace's per-region wildcard certificate). A * wildcard-scheme preview URL exists immediately but only starts serving once * its workspace domain is READY. */ export type WildcardStatus = "UNSPECIFIED" | "PENDING" | "READY" | "FAILED" | "DISABLED"; export interface ExposedPort { port: number; previewUrl: string; expiresAt?: Date; previewUrlId?: string; slug?: string; /** Whether subdomain support is enabled for this exposure. */ wildcard?: boolean; /** Readiness of the wildcard subdomain provisioning; meaningful only when wildcard is true. */ wildcardStatus?: WildcardStatus; /** Actionable reason when wildcardStatus is "FAILED"; empty otherwise. */ wildcardStatusReason?: string; } export interface SessionHandle { readonly id: string; readonly rpcClient: Client<typeof SandboxService>; exec(command: string | string[], options?: ExecOptions): Promise<ExecResult>; stream(command: string | string[], options?: ExecOptions): Promise<Stream>; gitOperation(operation: string, args: Record<string, string>): Promise<string>; } export interface SessionFs { readStream(path: string, options?: ReadStreamOptions): Promise<ReadableStream<Uint8Array>>; writeStream(path: string, data: ReadableStream<Uint8Array>, options?: WriteStreamOptions): Promise<void>; stat(path: string): Promise<FileInfo>; mkdir(path: string): Promise<void>; remove(path: string): Promise<void>; list(path: string, options?: FsListOptions): Promise<FileInfo[]>; } /** Empty allowlists follow the session's tailnet policy when attached; otherwise they are unrestricted. */ export interface SessionEgressPolicy { allowDomains: string[]; allowCidrs: string[]; interceptHttps: boolean; allowedPorts: number[]; publicEgress?: { tcpPorts: number[]; udpPorts: number[]; }; httpRules: EgressHttpRule[]; /** Named workspace egress policies pinned at create; the other fields hold their merged expansion. */ policyNames: string[]; } export declare function egressPolicyFromProto(egress: SandboxSession["egress"], policyNames?: readonly string[]): SessionEgressPolicy; export declare function egressHttpRuleToProto(rule: EgressHttpRule): SessionEgressHttpRule; export declare function largeWriteTarget(session: Session, path: string): Promise<{ mode: number; parallel: boolean; }>; export declare class Session implements SessionHandle, AsyncDisposable { #private; private readonly dataPlaneReadyTimeoutMs; private readonly warningHandler?; readonly id: string; readonly rpcClient: Client<typeof SandboxService>; readonly git: Git; readonly fs: SessionFs; name: string; state: SessionState; ownerType: string; ownerId: string; workspaceId: string; inboundEnabled: boolean; outboundEnabled: boolean; cpuCores: number; memoryMb: number; diskSizeGb: number; timeoutAt: Date; idleTimeoutMinutes?: number; lastActivityAt?: Date; pausedAt?: Date; pauseSnapshotId?: string; pauseRetentionMs?: number; pauseExpiresAt?: Date; metadata: Record<string, string>; tags: string[]; egress: SessionEgressPolicy; volumeMounts: VolumeMountConfig[]; pauseSnapshot?: Snapshot; lastResumeError?: string; terminalError?: string; runtimeState: RuntimeState; guestControlDenied: boolean; private runtimeSecretsPresent; get hasRuntimeSecrets(): boolean; runtimeError?: string; sticky: boolean; readonly sourceRegistryImageId?: string; readonly sourceSnapshotId?: string; readonly sourceRegistryWorkspaceId?: string; readonly sourceRegistryRef?: string; readonly sourceTemplateId?: string; readonly warnings: SandboxWarning[]; tailnetStatus?: TailnetStatus; networkMode: NetworkMode; /** UNSPECIFIED unless networkMode is RESTRICTED. */ networkRestrictionReason: NetworkRestrictionReason; private gatewayAddress; private sshOptions?; private dataPlaneEndpoint; private dataPlaneWarmStarted; private dataPlaneCredential?; private dataPlaneClient?; private dataPlaneLaneClients; private parallelWritesUnavailable; private dataPlaneVerifiedClient?; private dataPlaneEndpointFromHint; private readonly dataPlaneEndpointHints; private dataPlaneClosed; private closeDone; private released; private closing?; constructor(rpcClient: Client<typeof SandboxService>, proto: SandboxSession, authToken: string, gatewayAddress: string, sshOptions?: SSHConnectOptions, dataPlaneReadyTimeoutMs?: number, dataPlane?: DataPlaneConfig, warnings?: SandboxWarning[], warningHandler?: WarningHandler | undefined); toJSON(): Record<string, unknown>; dataPlaneRPC(): Client<typeof SandboxSessionDataPlaneService> | undefined; dataPlaneReadyBudgetMs(): number; dataPlaneProvisioningPending(client: Client<typeof SandboxSessionDataPlaneService>): boolean; markDataPlaneServing(client: Client<typeof SandboxSessionDataPlaneService>): void; dataPlaneUsingEndpointHint(client: Client<typeof SandboxSessionDataPlaneService>): boolean; refreshHintedDataPlane(client: Client<typeof SandboxSessionDataPlaneService>): Promise<boolean>; ensureDataPlane(verifyServing?: boolean): Promise<Client<typeof SandboxSessionDataPlaneService> | undefined>; requireDataPlane(verifyServing?: boolean): Promise<Client<typeof SandboxSessionDataPlaneService>>; requireDataPlaneLanes(count: number): Promise<Client<typeof SandboxSessionDataPlaneService>[]>; private closeDataPlaneLanes; private ensureDataPlaneServing; reauthOnUnauthenticated(err: unknown): Promise<boolean>; private configureDataPlane; private resetDataPlane; private applyDataPlaneResponse; private startDataPlaneWarm; renewDataPlaneCredential(): Promise<boolean>; private applyProto; exec(command: string | string[], options?: ExecOptions): Promise<ExecResult>; stream(command: string | string[], options?: ExecOptions): Promise<Stream>; dial(unixSocketPath: string, options?: DialOptions): Promise<DialStream>; run(argv: string[], options?: ProcessRunOptions): ProcessRunHandle; readFileStream(path: string, options?: ReadStreamOptions): Promise<ReadableStream<Uint8Array>>; writeFileStream(path: string, data: ReadableStream<Uint8Array>, options?: WriteStreamOptions): Promise<void>; stat(path: string): Promise<FileInfo>; mkdir(path: string): Promise<void>; remove(path: string): Promise<void>; list(path: string, options?: FsListOptions): Promise<FileInfo[]>; hostPortTunnel(host: string, port: number, options?: HostPortTunnelOptions): Promise<HostPortTunnel>; resilientHostPortTunnel(host: string, port: number, options?: ResilientHostPortTunnelOptions): Promise<ResilientHostPortTunnel>; exposeHostPort(hostAddr: string, options?: HostPortTunnelOptions): Promise<HostPortTunnel>; exposeHostPortResilient(hostAddr: string, options?: ResilientHostPortTunnelOptions): Promise<ResilientHostPortTunnel>; writeFile(path: string, data: Uint8Array | string): Promise<void>; readFile(path: string): Promise<Uint8Array>; waitReady(timeoutMs?: number, signal?: AbortSignal): Promise<void>; private waitReadyStream; private waitReadyPoll; /** * Wait until an in-flight resume reaches RUNNING or fails. * * Unlike waitReady — which only treats TERMINATED/TERMINATING as terminal * and would spin until timeout — a session that reverts from RESUMING back * to a stopped state (PAUSED/USER_SHUTDOWN) throws ResumeFailedError * carrying the server-side lastResumeError. */ waitResumed(timeoutMs?: number, signal?: AbortSignal): Promise<void>; private resumeFailedError; waitPaused(timeoutMs?: number, signal?: AbortSignal): Promise<void>; private terminalStateError; release(): void; /** * Terminate this session. Idempotent and safe to call concurrently: the * first successful call terminates and every later one is a no-op, while * concurrent callers join the call already in flight. A call that fails * leaves the session closeable again, so a caller can retry. */ close(): Promise<void>; private closeOnce; closeIfOpen(): Promise<void>; extend(additionalMs: number): Promise<void>; refresh(): Promise<void>; metrics(windowMs?: number): Promise<SessionMetrics>; cost(): Promise<SessionCost>; exposePort(port: number, options?: ExposePortOptions): Promise<ExposedPort>; unexposePort(port: number): Promise<void>; listExposedPorts(): Promise<ExposedPort[]>; updateSshAuthorizedKeys(keys: string[]): Promise<void>; /** Updates API then Git credentials sequentially; errors identify partial completion. */ rotateGitHubToken(token: string): Promise<void>; /** Creates or rotates a session injection credential. */ setInjectionCredential(input: InjectionCredentialInput, expectedRevision?: number): Promise<InjectionCredentialMetadata>; /** Revokes a session injection credential by name. */ revokeInjectionCredential(name: string, expectedRevision?: number): Promise<InjectionCredentialMetadata>; /** * Re-delivers the session's secret bindings at the workspace's current versions and restarts its * managed runtime. Processes started before the refresh keep their old values. */ refreshSecrets(): Promise<SecretsRefresh>; updateTags(tags: string[]): Promise<void>; update(options: UpdateSessionOptions): Promise<void>; attachVolume(volumeId: string, mountPath: string, options?: { readOnly?: boolean; }): Promise<void>; detachVolume(volumeId: string, options?: DetachVolumeOptions): Promise<void>; listStorageMounts(): Promise<StorageMount[]>; attachStorageMount(mount: StorageMountConfig): Promise<StorageMount>; detachStorageMount(mountId: string): Promise<void>; private isVolumeDetached; /** @deprecated Use `session.git.clone`, `checkout`, `diff` or `log`. */ gitOperation(operation: string, args: Record<string, string>): Promise<string>; ssh(signal?: AbortSignal): Promise<SSHConnection>; /** Pauses the sandbox. Its paused state is deleted, even for sticky sandboxes, at `pauseExpiresAt`; take a snapshot while it runs to keep it longer. */ pause(): Promise<void>; pauseAsync(): Promise<void>; /** * Resume and resolve once the session is RUNNING; joins a resume already in flight. * Throws ResumeWaitTimeoutError if the call deadline passes first; the resume may still land. * Retries UnavailableError, such as a paused source still being torn down, for up to 60s. */ resume(): Promise<void>; /** Resolve once the resume is accepted; call waitResumed to observe RUNNING. */ resumeAsync(): Promise<void>; private resumeWithAsync; /** * Snapshot this RUNNING session and start children that continue from its * memory and disk while it keeps running. Each child carries * `fork_of_session_id` and `fork_snapshot_id` metadata. A failure after the * snapshot exists throws ForkFailedError with the children already created. */ fork(options?: ForkOptions): Promise<Session[]>; private forkChild; [Symbol.asyncDispose](): Promise<void>; } export declare function wildcardStatusFromProto(status: ProtoWildcardStatus | undefined): WildcardStatus; /** Returns true if the session can accept commands. */ export declare function isReady(state: SessionState): boolean; export declare function isTerminal(state: SessionState): boolean;