UNPKG

@luxorai/sandbox

Version:

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

1,508 lines • 68.1 kB
import { create } from "@bufbuild/protobuf";
import { durationFromMs, timestampDate, timestampFromDate } from "@bufbuild/protobuf/wkt";
import { ConnectError, createClient } from "@connectrpc/connect";
import { createGrpcTransport } from "@connectrpc/connect-node";
import { createAuthInterceptor, resolveAuthToken } from "./auth.js";
import { BASE_URL_ENVS, DEFAULT_BASE_URL, DEFAULT_CPU_CORES, DEFAULT_DATA_PLANE_READY_TIMEOUT_MS, DEFAULT_DISK_SIZE_GB, DEFAULT_MEMORY_MB, DEFAULT_SESSION_CREATE_TIMEOUT_MS, DEFAULT_SNAPSHOT_CREATE_TIMEOUT_MS, DEFAULT_TEMPLATE_SPEC_CREATE_TIMEOUT_MS, GATEWAY_URL_ENVS, pollBackoffMs, SNAPSHOT_NOT_FOUND_GRACE_MS, snapshotReadyPollDelayMs, } from "./constants.js";
import { sessionCostBatchFromProto, sessionCostFromProto } from "./cost.js";
import { warmDataPlaneEndpoints } from "./data-plane.js";
import { egressPolicyFromMessage, egressPolicySpecToProto, publicEgressAcknowledged, workspaceScope, } from "./egress-policies.js";
import { readEnv } from "./env.js";
import { InvalidTemplateSpecError, mapError, SessionTerminatedError, SnapshotFailedError, SnapshotNotFoundError, SnapshotWaitTimeoutError, TemplateBuildFailedError, TemplateRuntimeFailedError, VolumeSyncPendingError, WaitReadyFailedError, } from "./errors.js";
import { githubInjectionCredentials, githubInjectionEnv } from "./github-token.js";
import { DrainingHttp2SessionManager, KEEPALIVE_PING_OPTIONS } from "./http2-drain.js";
import { injectionInput, injectionMetadata, safeInjectionError, } from "./injection-credentials.js";
import { DeleteRegistryImageRequestSchema, DeleteRegistryImageVersionRequestSchema, GetRegistryImageRequestSchema, ListRegistryImagesRequestSchema, ListRegistryShareGrantsRequestSchema, PublishRegistryImageRequestSchema, ResolveRegistryRefRequestSchema, RevokeRegistryShareGrantRequestSchema, SetRegistryImageVisibilityRequestSchema, ShareImageRequestSchema, UnshareRegistryImageRequestSchema, } from "./internal/proto/tenki/sandbox/v1/registry_pb.js";
import { BatchGetSessionCostsRequestSchema, CreateEgressPolicyRequestSchema, CreateEgressPolicyWithPublicEgressRequestSchema, CreateSessionRequestSchema, CreateSessionWithInjectionCredentialsRequestSchema, CreateSessionWithPublicEgressRequestSchema, CreateSnapshotRequestSchema, CreateStorageConnectionRequestSchema, CreateVolumeRequestSchema, DataPlaneRouteStatus, DeleteEgressPolicyRequestSchema, DeleteSnapshotRequestSchema, DeleteStorageConnectionRequestSchema, DeleteVolumeRequestSchema, GetEgressPolicyRequestSchema, GetSessionCostRequestSchema, GetSessionMetricsRequestSchema, GetSessionRequestSchema, GetSnapshotDownloadURLRequestSchema, GetSnapshotRequestSchema, GetStorageDefaultsRequestSchema, GetVolumeRequestSchema, GetWorkspaceSandboxUsageRequestSchema, ListCIRunnerSizesRequestSchema, ListDanglingSnapshotsRequestSchema, ListEgressPoliciesRequestSchema, ListSessionSnapshotsRequestSchema, ListStorageConnectionsRequestSchema, ListVolumesRequestSchema, ListWorkspaceSandboxesRequestSchema, ListWorkspaceSnapshotsRequestSchema, ResizeVolumeRequestSchema, SandboxService, SaveStorageDefaultsRequestSchema, SessionEgressPolicySchema, StorageDefaultsSchema, TemplateRuntimeFailureSchema, TerminateSessionRequestSchema, TestStorageConnectionRequestSchema, UpdateEgressPolicyRequestSchema, UpdateEgressPolicyWithPublicEgressRequestSchema, UpdateSessionRequestSchema, UpdateSnapshotRequestSchema, UpdateStorageConnectionRequestSchema, UpdateVolumeRequestSchema, VolumeMountSchema, WhoAmIRequestSchema, } from "./internal/proto/tenki/sandbox/v1/sandbox_pb.js";
import { SSHGatewayClientService } from "./internal/proto/tenki/sandbox/v1/ssh_gateway_client_pb.js";
import { BuildTemplateRequestSchema, CancelTemplateBuildRequestSchema, CreateTemplateRequestSchema, DeleteTemplateRequestSchema, GetTemplateBuildRequestSchema, GetTemplateRequestSchema, ListActiveTemplateBuildsRequestSchema, ListTemplatesRequestSchema, TemplateResourcesSchema, UpdateTemplateRequestSchema, } from "./internal/proto/tenki/sandbox/v1/template_pb.js";
import { sessionMetricsFromProto } from "./metrics.js";
import { validateUpdateMaxDurationMs } from "./options.js";
import { advancePageToken, automaticPageSize } from "./pagination.js";
import { PreviewUrlClient } from "./preview-url.js";
import { registryImageDetailFromProto, registryImageFromProto, registryImageSummaryFromProto, registryKindToProto, registryShareGrantFromProto, registrySortToProto, registryTagFromProto, registryVisibilityToProto, resolvedRegistryRefFromProto, } from "./registry.js";
import { validateCreateResources, validateTemplateResources } from "./resources.js";
import { secretFileToProto, validSecretFiles } from "./secret-files.js";
import { egressHttpRuleToProto, isReady, isTerminal, Session } from "./session.js";
import { snapshotFromProto, snapshotIsReady, snapshotIsTerminal } from "./snapshot.js";
import { issueSandboxSSHCert } from "./ssh-cert.js";
import { connectSSH, deriveGatewayAddress, discoverSSHGatewayUrl } from "./ssh.js";
import { storageAccessToProto, storageAuthMethodToProto, storageConnectionFromProto, storageCredentialsToProto, storageDefaultMountToProto, storageDefaultsFromProto, storageMountSpecToProto, storageProviderToProto, storageTestReasonFromProto, } from "./storage.js";
import { tailnetAttachmentToProto } from "./tailnet.js";
import { templateBuildFromProto, templateFromProto } from "./template.js";
import { workspaceUsageLimitFromProto } from "./usage.js";
import { volumeFromProto, volumeIsReady, volumeIsTerminal } from "./volume.js";
import { defaultWarningHandler, emitWarnings, sandboxWarningsFromProto, templateWarningsFromProto, } from "./warning.js";
const inspectCustom = Symbol.for("nodejs.util.inspect.custom");
/** @deprecated Use {@link LuxorSandbox}; `TenkiSandbox` remains a supported alias of the same class. */
export class TenkiSandbox {
    rpcClient;
    sshGatewayClient;
    #authToken;
    baseUrl;
    gatewayAddress;
    sshOptions;
    dataPlaneReadyTimeoutMs;
    warningHandler;
    sessionManager;
    previewUrls;
    constructor(options) {
        this.warningHandler =
            options?.warningHandler === undefined ? defaultWarningHandler : (options.warningHandler ?? undefined);
        this.#authToken = resolveAuthToken(options?.authToken, options?.apiKey);
        const baseUrl = options?.baseUrl?.trim() || readEnv(BASE_URL_ENVS) || DEFAULT_BASE_URL;
        this.baseUrl = baseUrl;
        // Explicit SSH gateway overrides disable automatic gateway discovery.
        const pinnedGateway = options?.gatewayAddress?.trim() || readEnv(GATEWAY_URL_ENVS) || "";
        this.gatewayAddress = pinnedGateway || deriveGatewayAddress(baseUrl);
        this.dataPlaneReadyTimeoutMs =
            options?.dataPlaneReadyTimeoutMs && options.dataPlaneReadyTimeoutMs > 0
                ? options.dataPlaneReadyTimeoutMs
                : DEFAULT_DATA_PLANE_READY_TIMEOUT_MS;
        const sessionManager = options?.transport
            ? undefined
            : new DrainingHttp2SessionManager(baseUrl, KEEPALIVE_PING_OPTIONS, options?.rootCertificates !== undefined ? { ca: options.rootCertificates } : undefined);
        this.sessionManager = sessionManager;
        void sessionManager?.connect().catch(() => { });
        const transport = options?.transport ??
            createGrpcTransport({
                baseUrl,
                interceptors: [createAuthInterceptor(this.#authToken)],
                sessionManager,
            });
        this.rpcClient = createClient(SandboxService, transport);
        this.sshGatewayClient = createClient(SSHGatewayClientService, transport);
        this.previewUrls = new PreviewUrlClient(this.rpcClient);
        const sshOptions = {
            ...(options?.rootCertificates !== undefined ? { rootCertificates: options.rootCertificates } : {}),
            ...(pinnedGateway ? {} : { discoverGateway: (sid) => discoverSSHGatewayUrl(this.sshGatewayClient, sid) }),
        };
        this.sshOptions = Object.keys(sshOptions).length > 0 ? sshOptions : undefined;
    }
    toJSON() {
        return { baseUrl: this.baseUrl, authToken: "[REDACTED]" };
    }
    [inspectCustom]() {
        return `TenkiSandbox { baseUrl: ${JSON.stringify(this.baseUrl)}, authToken: [REDACTED] }`;
    }
    // -- Sessions --
    async verifyTailnetExposure(request, response) {
        if (request.tailnet?.exposedPorts.some((port) => !response.session?.tailnetStatus?.exposedPorts.some((accepted) => accepted.port === port.port && accepted.protocol === port.protocol))) {
            try {
                await this.rpcClient.terminateSession(create(TerminateSessionRequestSchema, { sessionId: response.session.id }), {
                    timeoutMs: 10000,
                });
            }
            catch (cause) {
                throw new Error(`session ${response.session.id}: server did not acknowledge tailnet exposed ports; cleanup failed`, { cause });
            }
            throw new Error("server does not support requested tailnet exposed ports; session terminated");
        }
    }
    // Unsupported APIs must release their allocation before exposing a handle.
    async verifyPublicEgress(session, requested, credentials, runtimeFailure) {
        if (publicEgressAcknowledged(requested, session.egress.publicEgress))
            return;
        try {
            await session.close();
        }
        catch (error) {
            throw Object.assign(new Error("Server does not support public egress restrictions; session cleanup failed", {
                cause: error,
            }), credentials === undefined ? {} : { credentials }, runtimeFailure === undefined ? {} : { runtimeFailure });
        }
        throw Object.assign(new Error("Server does not support public egress restrictions", { cause: runtimeFailure }), credentials === undefined ? {} : { credentials }, runtimeFailure === undefined ? {} : { runtimeFailure });
    }
    async verifyTailnetDNS(requested, response) {
        if (requested === undefined || response.session?.tailnetStatus?.acceptDns === requested)
            return;
        const error = new Error("API did not acknowledge managed tailnet DNS configuration");
        const sessionId = response.session?.id;
        if (!sessionId)
            throw error;
        try {
            await this.rpcClient.terminateSession(create(TerminateSessionRequestSchema, { sessionId }), {
                timeoutMs: 10000,
            });
        }
        catch (cleanupError) {
            throw new AggregateError([error, cleanupError], "Managed tailnet DNS is unsupported and session cleanup failed");
        }
        throw error;
    }
    /**
     * cpuCores is 1-128 and memoryMb 256-524288 MiB (even); the workspace's size limit may be lower.
     * pauseRetentionMs must be at most the workspace's pause retention limit, which applies when it is unset or
     * not positive; a larger value is rejected.
     */
    async create(options) {
        return (await this.createSession(undefined, options)).session;
    }
    async createWithInjectionCredentials(credentials, options) {
        if (!Array.isArray(credentials))
            throw new TypeError("credentials must be an array");
        return this.createSession(credentials, options);
    }
    async createSession(credentials, options) {
        const req = create(CreateSessionRequestSchema, {
            ownerType: "SERVICE",
            ownerId: "self",
            name: options?.name ?? "",
            allowInbound: options?.allowInbound ?? true,
            allowOutbound: options?.allowOutbound ?? true,
            metadata: options?.metadata ?? {},
            tags: normalizeTags(options?.tags ?? []),
            env: { ...(options?.env ?? {}) },
            sshAuthorizedKeys: options?.sshAuthorizedKeys ?? [],
            enableOpencode: options?.enableOpenCode ?? false,
            cloneRepoUrl: options?.cloneRepoUrl ?? "",
            setupEnv: { ...(options?.setupEnv ?? {}) },
            setupSecrets: { ...(options?.setupSecrets ?? {}) },
            runtime: options?.directRuntime?.toDirectRuntimeProto(),
            secretOverrides: { ...(options?.secretOverrides ?? {}) },
            secretFiles: (options?.secretFiles ?? []).map(secretFileToProto),
            secretPolicies: [...(options?.secretPolicies ?? [])],
            egressPolicies: [...(options?.egressPolicies ?? [])],
        });
        if (!validSecretFiles(req.secretFiles, 0) || req.secretFiles.some((file) => file.format.case === "source")) {
            throw new Error("Invalid direct secret files; image source paths require a template build");
        }
        req.egress = sessionEgressPolicy(options ?? {});
        const image = registryRefOf(options?.image);
        const templateSpecId = options?.fromTemplateSpec ? resourceIdOf(options.fromTemplateSpec) : "";
        const snapshotId = options?.snapshotId?.trim() ?? "";
        if ([image, snapshotId, templateSpecId].filter(Boolean).length > 1) {
            throw new Error("Only one of image, snapshotId, or fromTemplateSpec may be set");
        }
        const hasSource = Boolean(image || snapshotId || templateSpecId);
        const cpuCores = options?.cpuCores ?? (hasSource ? undefined : DEFAULT_CPU_CORES);
        const memoryMb = options?.memoryMb ?? (hasSource ? undefined : DEFAULT_MEMORY_MB);
        const diskSizeGb = options?.diskSizeGb ?? (hasSource ? undefined : DEFAULT_DISK_SIZE_GB);
        validateCreateResources({ cpuCores, memoryMb, diskSizeGb });
        if (cpuCores != null)
            req.cpuCores = cpuCores;
        if (memoryMb != null)
            req.memoryMb = memoryMb;
        if (diskSizeGb != null)
            req.diskSizeGb = diskSizeGb;
        if (options?.maxDurationMs && options.maxDurationMs > 0) {
            req.maxDuration = durationFromMs(options.maxDurationMs);
        }
        if (options?.idleTimeoutMinutes != null) {
            warnIdleTimeoutDeprecated();
        }
        if (options?.pauseRetentionMs && options.pauseRetentionMs > 0) {
            req.pauseRetention = durationFromMs(options.pauseRetentionMs);
        }
        if (options?.sticky) {
            req.sticky = true;
        }
        const waitReady = options?.waitReady !== false;
        if (req.runtime && options?.fromTemplateSpec)
            throw new InvalidTemplateSpecError("directRuntime conflicts with fromTemplateSpec");
        const waitForRuntime = options?.waitForRuntime ?? false;
        // Wait client-side so WaitSession can expose the endpoint and prewarm the data plane during provision.
        req.waitReady = waitReady && waitForRuntime;
        req.waitForRuntime = waitForRuntime;
        if (image) {
            req.registryRef = image;
        }
        else if (snapshotId) {
            req.snapshotId = snapshotId;
        }
        else if (templateSpecId) {
            req.templateSpecId = templateSpecId;
        }
        const workspaceId = options?.workspaceId?.trim();
        if (workspaceId)
            req.workspaceId = workspaceId;
        if (options?.disableTailnet && options?.tailnet)
            throw new TypeError("choose a Tailscale connection or disable Tailscale");
        req.disableTailnet = options?.disableTailnet ?? false;
        if (options?.tailnet)
            req.tailnet = tailnetAttachmentToProto(options.tailnet);
        if (options?.volumes?.length) {
            req.volumes = options.volumes.map((v) => create(VolumeMountSchema, {
                volumeId: v.volumeId,
                mountPath: v.mountPath,
                readonly: v.readOnly ?? false,
            }));
        }
        if (options?.storageMounts?.length) {
            req.storageMounts = options.storageMounts.map((mount) => storageMountSpecToProto(mount));
        }
        if (options?.disableStorageDefaults) {
            req.disableStorageDefaults = true;
        }
        if (options?.excludedDefaultMountIds?.length) {
            req.excludedDefaultMountIds = options.excludedDefaultMountIds.map((id) => id.trim());
        }
        if (options?.openCodeProvider) {
            if (options.openCodeProvider.apiKey)
                req.env["OPENCODE_API_KEY"] = options.openCodeProvider.apiKey;
            if (options.openCodeProvider.baseUrl)
                req.env["OPENCODE_PROVIDER_BASE_URL"] = options.openCodeProvider.baseUrl;
            if (options.openCodeProvider.npm)
                req.env["OPENCODE_PROVIDER_NPM"] = options.openCodeProvider.npm;
        }
        if (options?.githubToken?.trim()) {
            req.env["GH_TOKEN"] = options.githubToken.trim();
            req.env["GIT_TOKEN"] = options.githubToken.trim();
        }
        if (options?.githubTokenInjection) {
            const inputs = githubInjectionCredentials(options.githubToken ?? "");
            if (options.cloneRepoUrl)
                throw new Error("GitHub token injection requires cloning after creation");
            githubInjectionEnv(req.env);
            credentials = [...(credentials ?? []), ...inputs];
        }
        for (const target of Object.keys(req.runtime?.secretEnv ?? {})) {
            if (Object.hasOwn(req.env, target))
                throw new InvalidTemplateSpecError("secret target conflicts with session environment");
        }
        for (const target of Object.keys(req.runtime?.variableEnv ?? {})) {
            if (Object.hasOwn(req.env, target))
                throw new InvalidTemplateSpecError("variable target conflicts with session environment");
        }
        const credentialRequest = credentials === undefined
            ? undefined
            : create(CreateSessionWithInjectionCredentialsRequestSchema, {
                session: req,
                credentials: credentials.map(injectionInput),
            });
        let resp;
        let metadata = [];
        try {
            if (credentials === undefined) {
                resp =
                    options?.publicEgress !== undefined
                        ? (await this.rpcClient.createSessionWithPublicEgress(create(CreateSessionWithPublicEgressRequestSchema, { request: req }))).response
                        : await this.rpcClient.createSession(req);
            }
            else {
                const result = await this.rpcClient.createSessionWithInjectionCredentials(credentialRequest);
                resp = result.created;
                metadata = result.credentials.map(injectionMetadata);
            }
        }
        catch (caught) {
            const err = credentials === undefined ? caught : safeInjectionError(caught);
            const runtimeFailure = ConnectError.from(credentials === undefined ? err : err.cause).findDetails(TemplateRuntimeFailureSchema)[0];
            if (runtimeFailure?.session) {
                const session = new Session(this.rpcClient, runtimeFailure.session, this.#authToken, this.gatewayAddress, this.sshOptions, this.dataPlaneReadyTimeoutMs, undefined, [], this.warningHandler);
                const failure = Object.assign(new TemplateRuntimeFailedError(runtimeFailure.reason || "template runtime failed", session, {
                    cause: err instanceof Error ? err : undefined,
                }), credentials === undefined ? {} : { credentials: metadata });
                await this.verifyPublicEgress(session, options?.publicEgress, credentials === undefined ? undefined : metadata, failure);
                throw failure;
            }
            if (credentials !== undefined)
                throw err;
            throw mapError(err);
        }
        await this.verifyTailnetExposure(req, resp);
        await this.verifyTailnetDNS(options?.tailnet?.acceptDns, resp);
        warmDataPlaneEndpoints(resp.dataPlaneWarmEndpoints);
        const warnings = sandboxWarningsFromProto(resp.warnings);
        // Match the Go SDK: skip data-plane config on terminal route failure so the first op fails fast instead of retrying a dead route for the whole readiness budget.
        const dataPlane = resp.routeStatus === DataPlaneRouteStatus.FAILED
            ? undefined
            : { endpoint: resp.dataPlaneEndpoint, credential: resp.credential, routeStatus: resp.routeStatus };
        const session = new Session(this.rpcClient, resp.session, this.#authToken, this.gatewayAddress, this.sshOptions, this.dataPlaneReadyTimeoutMs, dataPlane, warnings, this.warningHandler);
        await this.verifyPublicEgress(session, options?.publicEgress, credentials === undefined ? undefined : metadata, undefined);
        emitWarnings(this.warningHandler, warnings);
        if (!waitReady)
            return { session, credentials: metadata };
        if (isReady(session.state))
            return { session, credentials: metadata };
        if (isTerminal(session.state)) {
            const suffix = session.terminalError ? `: ${session.terminalError}` : "";
            throw new SessionTerminatedError(`session entered terminal state: ${session.state}${suffix}`);
        }
        try {
            await session.waitReady(options?.waitTimeoutMs ??
                (templateSpecId ? DEFAULT_TEMPLATE_SPEC_CREATE_TIMEOUT_MS : DEFAULT_SESSION_CREATE_TIMEOUT_MS));
        }
        catch (waitErr) {
            if (isTerminal(session.state))
                throw mapError(waitErr);
            throw Object.assign(new WaitReadyFailedError(`session ${session.id} created but not ready within wait budget`, session, {
                cause: waitErr instanceof Error ? waitErr : undefined,
            }), credentials === undefined ? {} : { credentials: metadata });
        }
        return { session, credentials: metadata };
    }
    /** @deprecated Use {@link create}, which already waits for the session to be ready. */
    async createAndWait(options) {
        const waitTimeoutMs = options?.timeoutMs ??
            options?.waitTimeoutMs ??
            (options?.fromTemplateSpec ? DEFAULT_TEMPLATE_SPEC_CREATE_TIMEOUT_MS : DEFAULT_SESSION_CREATE_TIMEOUT_MS);
        const session = await this.create({
            ...options,
            waitReady: true,
            waitTimeoutMs,
        });
        if (session.state !== "RUNNING") {
            try {
                await session.waitReady(waitTimeoutMs);
            }
            catch (waitErr) {
                if (isTerminal(session.state))
                    throw waitErr;
                throw new WaitReadyFailedError(`session ${session.id} created but not ready within wait budget`, session, {
                    cause: waitErr instanceof Error ? waitErr : undefined,
                });
            }
        }
        return session;
    }
    async get(sessionId) {
        try {
            const resp = await this.rpcClient.getSession(create(GetSessionRequestSchema, { sessionId }));
            return new Session(this.rpcClient, resp.session, this.#authToken, this.gatewayAddress, this.sshOptions, this.dataPlaneReadyTimeoutMs, undefined, [], this.warningHandler);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async getSessionMetrics(sessionId, windowMs) {
        const req = create(GetSessionMetricsRequestSchema, { sessionId: sessionId.trim() });
        if (windowMs !== undefined && windowMs !== 0)
            req.window = durationFromMs(windowMs);
        try {
            return sessionMetricsFromProto(await this.rpcClient.getSessionMetrics(req));
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async getSessionCost(sessionId) {
        const id = sessionId.trim();
        try {
            const resp = await this.rpcClient.getSessionCost(create(GetSessionCostRequestSchema, { sessionId: id }));
            return sessionCostFromProto(resp.cost, id);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    /** Returns the costs of up to 100 sessions in `options.workspaceId`, or in the API key's workspace when omitted. */
    async batchGetSessionCosts(sessionIds, options) {
        const req = create(BatchGetSessionCostsRequestSchema, {
            workspaceId: workspaceScope(options),
            sessionIds: sessionIds.map((id) => id.trim()),
        });
        try {
            return sessionCostBatchFromProto(await this.rpcClient.batchGetSessionCosts(req));
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async list(options) {
        try {
            const sessions = [];
            let pageToken = "";
            do {
                const req = create(ListWorkspaceSandboxesRequestSchema, {
                    workspaceId: options?.workspaceId,
                    pageSize: automaticPageSize(),
                    pageToken,
                    tags: normalizeTags(options?.tags ?? []),
                    includeTerminated: options?.includeTerminated ?? false,
                });
                if (options?.sticky !== undefined)
                    req.sticky = options.sticky;
                const resp = await this.rpcClient.listWorkspaceSandboxes(req);
                sessions.push(...(resp.sessions ?? []).map((s) => new Session(this.rpcClient, s, this.#authToken, this.gatewayAddress, this.sshOptions, this.dataPlaneReadyTimeoutMs, undefined, [], this.warningHandler)));
                pageToken = advancePageToken(pageToken, resp.nextPageToken);
            } while (pageToken);
            return sessions;
        }
        catch (err) {
            throw mapError(err);
        }
    }
    /**
     * Current usage vs. limits for a workspace — concurrent sessions, snapshots,
     * volumes, etc. Each entry carries `current` and an optional `max`. Look up
     * the `"max_concurrent_jobs"` key to check the shared concurrency quota before
     * creating a session, so the UI can surface a "limit reached" state up front
     * instead of letting the create fail.
     */
    async getUsage() {
        try {
            const req = create(GetWorkspaceSandboxUsageRequestSchema, {});
            const resp = await this.rpcClient.getWorkspaceSandboxUsage(req);
            return (resp.limits ?? []).map(workspaceUsageLimitFromProto);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async updateSession(sessionId, options) {
        validateUpdateMaxDurationMs(options.maxDurationMs, options.sticky);
        const req = create(UpdateSessionRequestSchema, { sessionId: sessionId.trim() });
        if (options.name !== undefined)
            req.name = options.name;
        if (options.tags !== undefined) {
            const normalized = normalizeTags(options.tags);
            if (normalized.length === 0) {
                req.clearTags = true;
            }
            else {
                req.tags = normalized;
            }
        }
        if (options.sticky !== undefined)
            req.sticky = options.sticky;
        if (options.maxDurationMs !== undefined) {
            req.maxDuration = durationFromMs(options.maxDurationMs);
        }
        let resp;
        try {
            resp = await this.rpcClient.updateSession(req);
        }
        catch (err) {
            throw mapError(err);
        }
        const warnings = sandboxWarningsFromProto(resp.warnings);
        const session = new Session(this.rpcClient, resp.session, this.#authToken, this.gatewayAddress, this.sshOptions, this.dataPlaneReadyTimeoutMs, undefined, warnings, this.warningHandler);
        emitWarnings(this.warningHandler, warnings);
        return session;
    }
    // -- Snapshots --
    async createSnapshot(sessionId, options) {
        const req = create(CreateSnapshotRequestSchema, { sessionId });
        if (options?.name?.trim())
            req.name = options.name.trim();
        if (options?.expiresAt) {
            req.expiresAt = timestampFromDate(options.expiresAt);
        }
        req.async = options?.async ?? false;
        try {
            const resp = await this.rpcClient.createSnapshot(req);
            return snapshotFromProto(resp.snapshot);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async createSnapshotAsync(sessionId, options) {
        return this.createSnapshot(sessionId, { ...options, async: true });
    }
    async createSnapshotAndWait(sessionId, options) {
        // Submit asynchronously so a slow capture cannot outlive a gateway timeout.
        const snap = await this.createSnapshot(sessionId, { ...options, async: true });
        return this.waitSnapshotReady(snap.id, options?.timeoutMs ?? DEFAULT_SNAPSHOT_CREATE_TIMEOUT_MS);
    }
    async getSnapshot(snapshotId) {
        try {
            const resp = await this.rpcClient.getSnapshot(create(GetSnapshotRequestSchema, { snapshotId: snapshotId.trim() }));
            return snapshotFromProto(resp.snapshot);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async getSnapshotDownloadURL(snapshotId) {
        try {
            const resp = await this.rpcClient.getSnapshotDownloadURL(create(GetSnapshotDownloadURLRequestSchema, {
                snapshotId: snapshotId.trim(),
            }));
            return {
                url: resp.url,
                expiresAt: resp.expiresAt ? timestampDate(resp.expiresAt) : undefined,
            };
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async listSnapshots(options) {
        try {
            const snapshots = [];
            let pageToken = "";
            do {
                const resp = await this.rpcClient.listWorkspaceSnapshots(create(ListWorkspaceSnapshotsRequestSchema, {
                    workspaceId: options?.workspaceId,
                    pageSize: automaticPageSize(),
                    pageToken,
                }));
                snapshots.push(...(resp.snapshots ?? []).map(snapshotFromProto));
                pageToken = advancePageToken(pageToken, resp.nextPageToken);
            } while (pageToken);
            return snapshots;
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async listSessionSnapshots(sessionId) {
        try {
            const snapshots = [];
            let pageToken = "";
            do {
                const resp = await this.rpcClient.listSessionSnapshots(create(ListSessionSnapshotsRequestSchema, {
                    sessionId: sessionId.trim(),
                    pageSize: automaticPageSize(),
                    pageToken,
                }));
                snapshots.push(...(resp.snapshots ?? []).map(snapshotFromProto));
                pageToken = advancePageToken(pageToken, resp.nextPageToken);
            } while (pageToken);
            return snapshots;
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async listDanglingSnapshots() {
        try {
            const snapshots = [];
            let pageToken = "";
            do {
                const resp = await this.rpcClient.listDanglingSnapshots(create(ListDanglingSnapshotsRequestSchema, { pageSize: automaticPageSize(), pageToken }));
                snapshots.push(...(resp.snapshots ?? []).map(snapshotFromProto));
                pageToken = advancePageToken(pageToken, resp.nextPageToken);
            } while (pageToken);
            return snapshots;
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async deleteSnapshot(snapshotId) {
        try {
            const resp = await this.rpcClient.deleteSnapshot(create(DeleteSnapshotRequestSchema, { snapshotId }));
            return snapshotFromProto(resp.snapshot);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async updateSnapshot(snapshotId, options) {
        const req = create(UpdateSnapshotRequestSchema, { snapshotId: snapshotId.trim() });
        if (options.name !== undefined)
            req.name = options.name;
        if (options.clearExpiresAt)
            req.clearExpiresAt = true;
        if (options.expiresAt)
            req.expiresAt = timestampFromDate(options.expiresAt);
        if (options.tags !== undefined) {
            const normalized = normalizeTags(options.tags);
            if (normalized.length === 0) {
                req.clearTags = true;
            }
            else {
                req.tags = normalized;
            }
        }
        try {
            const resp = await this.rpcClient.updateSnapshot(req);
            return snapshotFromProto(resp.snapshot);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async waitSnapshotReady(snapshotId, timeoutMs, signal) {
        const started = Date.now();
        const deadline = started + (timeoutMs ?? DEFAULT_SNAPSHOT_CREATE_TIMEOUT_MS);
        while (Date.now() < deadline) {
            signal?.throwIfAborted();
            const snap = await this.getSnapshot(snapshotId).catch((err) => {
                const retryable = err instanceof SnapshotNotFoundError && Date.now() - started < SNAPSHOT_NOT_FOUND_GRACE_MS;
                if (!retryable)
                    throw err;
                return undefined;
            });
            if (snap && snapshotIsReady(snap.state))
                return snap;
            if (snap?.state === "FAILED") {
                const reason = snap.failureReason ? `: ${snap.failureReason}` : "";
                throw new SnapshotFailedError(`snapshot entered terminal state: FAILED${reason}`, {
                    failureReason: snap.failureReason,
                });
            }
            if (snap && snapshotIsTerminal(snap.state)) {
                throw new Error(`snapshot entered terminal state: ${snap.state}`);
            }
            await sleep(snapshotReadyPollDelayMs(Date.now() - started), signal);
        }
        throw new SnapshotWaitTimeoutError(`timeout waiting for snapshot ${snapshotId} to become ready; it is still being created, call waitSnapshotReady("${snapshotId}") to keep waiting`);
    }
    /** Credentials go to Luxor Secrets (s3_storage scope); the connection keeps only their names. */
    async createStorageConnection(options) {
        try {
            const resp = await this.rpcClient.createStorageConnection(create(CreateStorageConnectionRequestSchema, {
                workspaceId: options.workspaceId?.trim() ?? "",
                name: options.name.trim(),
                provider: storageProviderToProto(options.provider),
                endpoint: options.endpoint?.trim() ?? "",
                bucket: options.bucket.trim(),
                region: options.region?.trim() ?? "",
                authMethod: storageAuthMethodToProto(options.authMethod),
                defaultAccess: storageAccessToProto(options.defaultAccess),
                credentials: storageCredentialsToProto(options.credentials),
            }));
            return storageConnectionFromProto(resp.connection);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    /** Lists the connections of `workspaceId`, or of the API key's workspace when omitted. */
    async listStorageConnections(workspaceId = "") {
        try {
            const resp = await this.rpcClient.listStorageConnections(create(ListStorageConnectionsRequestSchema, { workspaceId: workspaceId.trim() }));
            return {
                connections: (resp.connections ?? []).map(storageConnectionFromProto),
                oidcIssuer: resp.oidcIssuer,
                oidcAudience: resp.oidcAudience,
            };
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async updateStorageConnection(connectionId, options) {
        try {
            const resp = await this.rpcClient.updateStorageConnection(create(UpdateStorageConnectionRequestSchema, {
                connectionId,
                name: options.name?.trim(),
                endpoint: options.endpoint?.trim(),
                region: options.region?.trim(),
                defaultAccess: options.defaultAccess ? storageAccessToProto(options.defaultAccess) : undefined,
                credentials: storageCredentialsToProto(options.credentials),
                expectedRevision: options.expectedRevision,
            }));
            return storageConnectionFromProto(resp.connection);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async deleteStorageConnection(connectionId, expectedRevision) {
        try {
            await this.rpcClient.deleteStorageConnection(create(DeleteStorageConnectionRequestSchema, { connectionId, expectedRevision }));
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async testStorageConnection(connectionId) {
        try {
            const resp = await this.rpcClient.testStorageConnection(create(TestStorageConnectionRequestSchema, { connectionId }));
            return {
                reachable: resp.reachable,
                reason: storageTestReasonFromProto(resp.reason),
                message: resp.errorMessage,
            };
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async getStorageDefaults(workspaceId = "") {
        try {
            const resp = await this.rpcClient.getStorageDefaults(create(GetStorageDefaultsRequestSchema, { workspaceId: workspaceId.trim() }));
            return storageDefaultsFromProto(resp.defaults);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    /** Replaces the workspace's default mounts; pass the revision you read (0 before the first save). */
    async saveStorageDefaults(defaults, expectedRevision) {
        try {
            const resp = await this.rpcClient.saveStorageDefaults(create(SaveStorageDefaultsRequestSchema, {
                defaults: create(StorageDefaultsSchema, {
                    workspaceId: defaults.workspaceId.trim(),
                    mounts: defaults.mounts.map(storageDefaultMountToProto),
                }),
                expectedRevision,
            }));
            return storageDefaultsFromProto(resp.defaults);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    // -- Egress policies --
    /** Saves spec under name in the workspace; the server checks it like an inline session policy. */
    async createEgressPolicy(name, spec, options) {
        const egress = egressPolicySpecToProto(spec);
        try {
            const request = create(CreateEgressPolicyRequestSchema, { workspaceId: workspaceScope(options), name, egress });
            const resp = spec.publicEgress !== undefined
                ? (await this.rpcClient.createEgressPolicyWithPublicEgress(create(CreateEgressPolicyWithPublicEgressRequestSchema, { request }))).response
                : await this.rpcClient.createEgressPolicy(request);
            const policy = egressPolicyFromMessage(resp.policy);
            if (!publicEgressAcknowledged(spec.publicEgress, policy.egress.publicEgress))
                throw new Error("Server does not support public egress restrictions");
            return policy;
        }
        catch (err) {
            throw mapError(err);
        }
    }
    /** Replaces the policy body when expectedRevision is current; existing sessions keep the policy they were created with. */
    async updateEgressPolicy(nameOrId, expectedRevision, spec, options) {
        const egress = egressPolicySpecToProto(spec);
        try {
            const request = create(UpdateEgressPolicyRequestSchema, {
                workspaceId: workspaceScope(options),
                policyId: nameOrId,
                expectedRevision,
                egress,
            });
            const resp = spec.publicEgress !== undefined
                ? (await this.rpcClient.updateEgressPolicyWithPublicEgress(create(UpdateEgressPolicyWithPublicEgressRequestSchema, { request }))).response
                : await this.rpcClient.updateEgressPolicy(request);
            const policy = egressPolicyFromMessage(resp.policy);
            if (!publicEgressAcknowledged(spec.publicEgress, policy.egress.publicEgress))
                throw new Error("Server does not support public egress restrictions");
            return policy;
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async getEgressPolicy(nameOrId, options) {
        try {
            const resp = await this.rpcClient.getEgressPolicy(create(GetEgressPolicyRequestSchema, { workspaceId: workspaceScope(options), policyId: nameOrId }));
            return egressPolicyFromMessage(resp.policy);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    /** Returns every live policy in the workspace, ordered by name. */
    async listEgressPolicies(options) {
        try {
            const policies = [];
            let cursor = "";
            do {
                const resp = await this.rpcClient.listEgressPolicies(create(ListEgressPoliciesRequestSchema, {
                    workspaceId: workspaceScope(options),
                    pageSize: automaticPageSize(),
                    cursor,
                }));
                policies.push(...resp.policies.map(egressPolicyFromMessage));
                cursor = advancePageToken(cursor, resp.nextCursor);
            } while (cursor);
            return policies;
        }
        catch (err) {
            throw mapError(err);
        }
    }
    /** Soft-deletes the policy when expectedRevision is current; sessions that pinned it keep their merged policy. */
    async deleteEgressPolicy(nameOrId, expectedRevision, options) {
        try {
            const resp = await this.rpcClient.deleteEgressPolicy(create(DeleteEgressPolicyRequestSchema, {
                workspaceId: workspaceScope(options),
                policyId: nameOrId,
                expectedRevision,
            }));
            return egressPolicyFromMessage(resp.policy);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    // -- Volumes --
    async createVolume(options) {
        const req = create(CreateVolumeRequestSchema, {
            name: options.name,
            sizeBytes: BigInt(options.sizeBytes),
        });
        if (options.workspaceId?.trim())
            req.workspaceId = options.workspaceId.trim();
        try {
            const resp = await this.rpcClient.createVolume(req);
            return volumeFromProto(resp.volume);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async getVolume(volumeId) {
        try {
            const resp = await this.rpcClient.getVolume(create(GetVolumeRequestSchema, { volumeId }));
            return volumeFromProto(resp.volume, resp.activeAttachments);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async listVolumes(options) {
        try {
            const volumes = [];
            let pageToken = "";
            do {
                const resp = await this.rpcClient.listVolumes(create(ListVolumesRequestSchema, {
                    workspaceId: options?.workspaceId,
                    pageSize: automaticPageSize(),
                    pageToken,
                }));
                volumes.push(...(resp.volumes ?? []).map((v) => volumeFromProto(v)));
                pageToken = advancePageToken(pageToken, resp.nextPageToken);
            } while (pageToken);
            return volumes;
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async deleteVolume(volumeId, signal) {
        const maxElapsedMs = 60_000;
        const start = Date.now();
        let backoffMs = 1_000;
        for (;;) {
            signal?.throwIfAborted();
            try {
                await this.rpcClient.deleteVolume(create(DeleteVolumeRequestSchema, { volumeId }));
                return;
            }
            catch (err) {
                const mapped = mapError(err);
                if (!(mapped instanceof VolumeSyncPendingError) || Date.now() - start >= maxElapsedMs) {
                    throw mapped;
                }
                await sleep(backoffMs, signal);
                if (backoffMs < 10_000)
                    backoffMs *= 2;
            }
        }
    }
    async resizeVolume(volumeId, newSizeBytes) {
        try {
            const resp = await this.rpcClient.resizeVolume(create(ResizeVolumeRequestSchema, {
                volumeId,
                newSizeBytes: BigInt(newSizeBytes),
            }));
            return volumeFromProto(resp.volume);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async updateVolume(volumeId, options) {
        const req = create(UpdateVolumeRequestSchema, { volumeId: volumeId.trim() });
        if (options.name !== undefined)
            req.name = options.name;
        if (options.tags !== undefined) {
            const normalized = normalizeTags(options.tags);
            if (normalized.length === 0) {
                req.clearTags = true;
            }
            else {
                req.tags = normalized;
            }
        }
        try {
            const resp = await this.rpcClient.updateVolume(req);
            return volumeFromProto(resp.volume);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async waitVolumeReady(volumeId, timeoutMs, signal) {
        const deadline = Date.now() + (timeoutMs ?? 60_000);
        let attempt = 0;
        while (Date.now() < deadline) {
            signal?.throwIfAborted();
            const vol = await this.getVolume(volumeId);
            if (volumeIsReady(vol.state))
                return vol;
            if (volumeIsTerminal(vol.state)) {
                throw new Error(`volume entered terminal state: ${vol.state}`);
            }
            await sleep(pollBackoffMs(attempt), signal);
            attempt++;
        }
        throw new Error(`timeout waiting for volume ${volumeId} to become ready`);
    }
    // -- Registry --
    async listRegistryImages(options) {
        const req = create(ListRegistryImagesRequestSchema, {
            labels: cleanStrings(options?.labels ?? []),
        });
        if (options?.workspace?.trim())
            req.workspaceSlug = options.workspace.trim();
        if (options?.nameSubstring?.trim())
            req.nameSubstring = options.nameSubstring.trim();
        if (options?.kind)
            req.kind = registryKindToProto(options.kind);
        if (options?.sort)
            req.sortBy = registrySortToProto(options.sort);
        if (options?.pageSize && options.pageSize > 0)
            req.pageSize = options.pageSize;
        if (options?.cursor?.trim())
            req.cursor = options.cursor.trim();
        try {
            const resp = await this.rpcClient.listRegistryImages(req);
            return {
                images: (resp.images ?? []).map(registryImageSummaryFromProto),
                nextCursor: resp.nextCursor,
            };
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async getRegistryImage(imageOrId, options) {
        const value = imageOrId.trim();
        const req = create(GetRegistryImageRequestSchema, {});
        if (options?.workspaceId?.trim())
            req.workspaceId = options.workspaceId.trim();
        if (looksLikeUUID(value)) {
            req.imageId = value;
        }
        else {
            req.ref = value;
        }
        try {
            const resp = await this.rpcClient.getRegistryImage(req);
            return registryImageDetailFromProto(resp.detail);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async resolveRegistryRef(image, options) {
        const ref = image.trim();
        try {
            const resp = await this.rpcClient.resolveRegistryRef(create(ResolveRegistryRefRequestSchema, { ref, workspaceId: options?.workspaceId?.trim() }));
            return resolvedRegistryRefFromProto(resp.resolved);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async publishRegistryImage(options) {
        const req = create(PublishRegistryImageRequestSchema, {
            labels: cleanStrings(options.labels ?? []),
        });
        if (options.imageId?.trim())
            req.imageId = options.imageId.trim();
        if (options.image?.trim())
            req.ref = options.image.trim();
        if (options.workspaceId?.trim())
            req.workspaceId = options.workspaceId.trim();
        if (options.name?.trim())
            req.name = options.name.trim();
        if (options.fromTemplateId?.trim()) {
            req.kind = registryKindToProto("template");
            req.sourceTemplateId = options.fromTemplateId.trim();
        }
        else if (options.fromSnapshotId?.trim()) {
            req.kind = registryKindToProto("snapshot");
            req.snapshotId = options.fromSnapshotId.trim();
        }
        if (options.tag?.trim())
            req.tag = options.tag.trim();
        if (options.visibility)
            req.visibility = registryVisibilityToProto(options.visibility);
        if (options.title?.trim())
            req.title = options.title.trim();
        if (options.description?.trim())
            req.description = options.description.trim();
        try {
            const resp = await this.rpcClient.publishRegistryImage(req);
            return {
                image: resp.image ? registryImageFromProto(resp.image) : undefined,
                tag: registryTagFromProto(resp.tag),
                snapshotId: resp.snapshotId,
                digestRef: resp.digestRef,
            };
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async unpublishRegistryImage(imageOrId) {
        const value = stripRegistryTag(imageOrId.trim());
        const req = create(SetRegistryImageVisibilityRequestSchema, {
            visibility: registryVisibilityToProto("private"),
        });
        if (looksLikeUUID(value)) {
            req.imageId = value;
        }
        else {
            req.ref = value;
        }
        try {
            const resp = await this.rpcClient.setRegistryImageVisibility(req);
            return registryImageFromProto(resp.image);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async deleteRegistryImage(imageOrId, reason) {
        const value = imageOrId.trim();
        const req = create(DeleteRegistryImageRequestSchema, {});
        if (looksLikeUUID(value))
            req.imageId = value;
        else
            req.ref = value;
        if (reason?.trim())
            req.reason = reason.trim();
        try {
            const resp = await this.rpcClient.deleteRegistryImage(req);
            return {
                image: resp.image ? registryImageFromProto(resp.image) : undefined,
                revokedTokenCount: resp.revokedTokenCount,
                revokedGrantCount: resp.revokedGrantCount,
            };
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async deleteRegistryImageVersion(imageId, snapshotId) {
        const req = create(DeleteRegistryImageVersionRequestSchema, {
            imageId: imageId.trim(),
            snapshotId: snapshotId.trim(),
        });
        try {
            const resp = await this.rpcClient.deleteRegistryImageVersion(req);
            return {
                imageId: resp.imageId,
                snapshotId: resp.snapshotId,
            };
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async shareImage(imageOrId, options) {
        const value = imageOrId.trim();
        const req = create(ShareImageRequestSchema, {
            targetWorkspaceId: options.targetWorkspaceId?.trim() ?? "",
        });
        if (looksLikeUUID(value))
            req.imageId = value;
        else
            req.imageRef = value;
        if (options.tag?.trim())
            req.tag = options.tag.trim();
        if (options.snapshotId?.trim())
            req.snapshotId = options.snapshotId.trim();
        try {
            const resp = await this.rpcClient.shareImage(req);
            return {
                image: resp.image ? registryImageFromProto(resp.image) : undefined,
                currentSnapshotId: resp.currentSnapshotId,
                digestRef: resp.digestRef,
                grant: registryShareGrantFromProto(resp.grant),
            };
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async revokeRegistryShareGrant(grantId, reason) {
        const req = create(RevokeRegistryShareGrantRequestSchema, { grantId: grantId.trim() });
        if (reason?.trim())
            req.reason = reason.trim();
        try {
            const resp = await this.rpcClient.revokeRegistryShareGrant(req);
            return registryShareGrantFromProto(resp.grant);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async listRegistryShareGrants(imageOrId) {
        const value = imageOrId.trim();
        const req = create(ListRegistryShareGrantsRequestSchema, {});
        if (looksLikeUUID(value))
            req.imageId = value;
        else
            req.ref = value;
        try {
            const resp = await this.rpcClient.listRegistryShareGrants(req);
            return (resp.grants ?? []).map((grant) => registryShareGrantFromProto(grant));
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async unshareRegistryImage(imageOrId, reason) {
        const value = imageOrId.trim();
        const req = create(UnshareRegistryImageRequestSchema, {});
        if (looksLikeUUID(value))
            req.imageId = value;
        else
            req.ref = value;
        if (reason?.trim())
            req.reason = reason.trim();
        try {
            const resp = await this.rpcClient.unshareRegistryImage(req);
            return {
                image: resp.image ? registryImageFromProto(resp.image) : undefined,
                revokedTokenCount: resp.revokedTokenCount,
                revokedGrantCount: resp.revokedGrantCount,
            };
        }
        catch (err) {
            throw mapError(err);
        }
    }
    // -- Templates --
    async createTemplate(options) {
        if (options.spec) {
            assertNoLegacyTemplateFields(options, [
                "baseImageId",
                "setupScript",
                "startCmd",
                "env",
                "resources",
                "parentTemplateId",
                "parentImage",
            ]);
            assertValidTemplateSpec(options.spec);
        }
        const req = create(CreateTemplateRequestSchema, {
            name: options.name,
            baseImageId: options.baseImageId ?? "",
            setupScript: options.setupScript ?? "",
            envVars: options.env ?? {},
            tags: normalizeTags(options.tags ?? []),
        });
        if (options.workspaceId?.trim())
            req.workspaceId = options.workspaceId.trim();
        if (options.spec)
            req.builderSpec = options.spec.toProto();
        if (options.parentTemplateId?.trim()) {
            req.parentTemplateId = options.parentTemplateId.trim();
        }
        if (options.parentImage?.trim()) {
            req.parentImage = options.parentImage.trim();
        }
        if (options.startCmd != null)
            req.startCmd = options.startCmd;
        if (options.resources) {
            validateTemplateResources(options.resources);
            req.resources = create(TemplateResourcesSchema, {
                cpuCores: options.resources.cpuCores ?? 0,
                memoryMb: options.resources.memoryMb ?? 0,
                diskSizeGb: options.resources.diskSizeGb ?? 0,
            });
        }
        try {
            const resp = await this.rpcClient.createTemplate(req);
            const warnings = templateWarningsFromProto(resp.warnings);
            emitWarnings(this.warningHandler, warnings);
            return { ...templateFromProto(resp.template), warnings };
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async getTemplate(template) {
        try {
            const resp = await this.rpcClient.getTemplate(create(GetTemplateRequestSchema, { templateId: resourceIdOf(template) }));
            return templateFromProto(resp.template);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async listTemplates(options) {
        try {
            const templates = [];
            let pageToken = "";
            do {
                const resp = await this.rpcClient.listTemplates(create(ListTemplatesRequestSchema, {
                    workspaceId: options?.workspaceId,
                    pageSize: automaticPageSize(),
                    pageToken,
                    tags: normalizeTags(options?.tags ?? []),
                }));
                templates.push(...(resp.templates ?? []).map(templateFromProto));
                pageToken = advancePageToken(pageToken, resp.nextPageToken);
            } while (pageToken);
            return templates;
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async updateTemplate(template, options) {
        if (options.spec) {
            assertNoLegacyTemplateFields(options, ["baseImageId", "setupScript", "startCmd", "env", "resources"]);
            assertValidTemplateSpec(options.spec);
        }
        const req = create(UpdateTemplateRequestSchema, {
            templateId: resourceIdOf(template),
        });
        if (options.spec)
            req.builderSpec = options.spec.toProto();
        if (options.name != null)
            req.name = options.name;
        if (options.baseImageId != null)
            req.baseImageId = options.baseImageId;
        if (options.setupScript != null)
            req.setupScript = options.setupScript;
        if (options.startCmd != null)
            req.startCmd = options.startCmd;
        if (options.env != null)
            req.envVars = { ...options.env };
        if (options.tags != null) {
            const normalized = normalizeTags(options.tags);
            if (normalized.length === 0) {
                req.clearTags = true;
            }
            else {
                req.tags = normalized;
            }
        }
        if (options.resources) {
            validateTemplateResources(options.resources);
            req.resources = create(TemplateResourcesSchema, {
                cpuCores: options.resources.cpuCores ?? 0,
                memoryMb: options.resources.memoryMb ?? 0,
                diskSizeGb: options.resources.diskSizeGb ?? 0,
            });
        }
        try {
            const resp = await this.rpcClient.updateTemplate(req);
            const warnings = templateWarningsFromProto(resp.warnings);
            emitWarnings(this.warningHandler, warnings);
            return { ...templateFromProto(resp.template), warnings };
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async deleteTemplate(template) {
        try {
            const resp = await this.rpcClient.deleteTemplate(create(DeleteTemplateRequestSchema, { templateId: resourceIdOf(template) }));
            return templateFromProto(resp.template);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async buildTemplate(template, options) {
        let build;
        try {
            const resp = await this.rpcClient.buildTemplate(create(BuildTemplateRequestSchema, {
                templateId: resourceIdOf(template),
                ...(options?.buildEnv !== undefined ? { buildEnv: { ...options.buildEnv } } : {}),
                ...(options?.buildSecrets !== undefined ? { buildSecrets: { ...options.buildSecrets } } : {}),
                ...(options?.publishRawImage !== undefined ? { publishRawImage: options.publishRawImage } : {}),
            }));
            build = { ...templateBuildFromProto(resp.build), warnings: templateWarningsFromProto(resp.warnings) };
        }
        catch (err) {
            throw mapError(err);
        }
        emitWarnings(this.warningHandler, build.warnings ?? []);
        if (options?.waitForCompletion) {
            // Outside the RPC error mapping: handler or abort failures must surface as-is.
            const completed = await this.waitForTemplateBuild(build, { signal: options.signal, onEvent: options.onEvent });
            return { ...completed, warnings: build.warnings };
        }
        return build;
    }
    async getTemplateBuild(build) {
        try {
            const resp = await this.rpcClient.getTemplateBuild(create(GetTemplateBuildRequestSchema, { buildId: resourceIdOf(build) }));
            return templateBuildFromProto(resp.build);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    async listActiveTemplateBuilds(template) {
        try {
            const resp = await this.rpcClient.listActiveTemplateBuilds(create(ListActiveTemplateBuildsRequestSchema, { templateId: resourceIdOf(template) }));
            return resp.builds.map((build) => templateBuildFromProto(build));
        }
        catch (err) {
            throw mapError(err);
        }
    }
    /** Waits for or reconnects to a build; handler/signal failure stops local observation only. */
    async waitForTemplateBuild(build, signalOrOptions) {
        const options = signalOrOptions && "throwIfAborted" in signalOrOptions ? { signal: signalOrOptions } : (signalOrOptions ?? {});
        const buildId = resourceIdOf(build);
        const seenEvents = { count: 0 };
        let attempt = 0;
        while (true) {
            options.signal?.throwIfAborted();
            const current = await this.getTemplateBuild(buildId);
            if (options.onEvent) {
                for (; seenEvents.count < current.events.length; seenEvents.count++) {
                    await options.onEvent(current.events[seenEvents.count]);
                }
            }
            if (current.state === "READY")
                return current;
            if (current.state === "FAILED") {
                throw new TemplateBuildFailedError(current.failure?.message || current.error || "template build failed", current);
            }
            await sleep(pollBackoffMs(attempt), options.signal);
            attempt++;
        }
    }
    /** Explicitly cancels the remote build; disconnecting an observer never does. */
    async cancelTemplateBuild(build) {
        try {
            const resp = await this.rpcClient.cancelTemplateBuild(create(CancelTemplateBuildRequestSchema, { buildId: resourceIdOf(build) }));
            return templateBuildFromProto(resp.build);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    // -- Identity --
    async whoAmI() {
        try {
            const resp = await this.rpcClient.whoAmI(create(WhoAmIRequestSchema, {}));
            return {
                ownerType: resp.ownerType,
                ownerId: resp.ownerId,
                workspaces: (resp.workspaces ?? []).map((ws) => ({
                    id: ws.workspaceId,
                    name: ws.name,
                })),
            };
        }
        catch (err) {
            throw mapError(err);
        }
    }
    /** Luxor CI runner sizes for the API key's workspace, within its job-size limits, smallest first. */
    async listCIRunnerSizes() {
        try {
            const resp = await this.rpcClient.listCIRunnerSizes(create(ListCIRunnerSizesRequestSchema, {}));
            return {
                sizes: (resp.sizes ?? []).map((size) => ({
                    runsOnLabel: size.runsOnLabel,
                    cpu: size.cpu,
                    memoryGiB: size.memory,
                })),
                defaultRunsOnLabel: resp.defaultRunsOnLabel,
            };
        }
        catch (err) {
            throw mapError(err);
        }
    }
    // -- SSH --
    async ssh(sessionId) {
        return connectSSH(this.gatewayAddress, sessionId, this.#authToken, this.sshOptions);
    }
    /**
     * Mint a short-lived OpenSSH user certificate for the session. Authenticate
     * an SSH implementation over the raw `ssh()` transport with the matching
     * private key and returned certificate. OpenSSH auto-loads `sshCert` when it
     * is saved beside the private key as `<key>-cert.pub`.
     */
    async issueSandboxSSHCert(sessionId, publicKey, options) {
        try {
            return await issueSandboxSSHCert(this.sshGatewayClient, sessionId, publicKey, options?.ttlMs);
        }
        catch (err) {
            throw mapError(err);
        }
    }
    // -- Cleanup --
    close() {
        this.sessionManager?.abort();
        this.sessionManager = undefined;
    }
    async [Symbol.asyncDispose]() {
        this.close();
    }
}
let idleTimeoutDeprecationWarned = false;
function warnIdleTimeoutDeprecated() {
    if (idleTimeoutDeprecationWarned)
        return;
    idleTimeoutDeprecationWarned = true;
    console.warn("luxor sandbox: idleTimeoutMinutes is deprecated and ignored; sandboxes do not auto-pause on idle. Use maxDurationMs to bound a session's lifetime.");
}
function normalizeTags(tags) {
    return tags.map((tag) => tag.trim().toLowerCase()).filter((tag) => tag.length > 0);
}
function cleanStrings(values) {
    return values.map((value) => value.trim()).filter((value) => value.length > 0);
}
function resourceIdOf(value) {
    return (typeof value === "string" ? value : value.id).trim();
}
function registryRefOf(image) {
    if (!image)
        return "";
    if (typeof image === "string")
        return image.trim();
    return image.digestRef?.trim() || image.ref?.trim() || "";
}
function assertNoLegacyTemplateFields(options, legacyFields) {
    const set = legacyFields.filter((field) => options[field] !== undefined);
    if (set.length > 0) {
        throw new InvalidTemplateSpecError(`spec cannot be combined with legacy template fields: ${set.join(", ")}`);
    }
}
function assertValidTemplateSpec(spec) {
    const violations = spec.validate();
    if (violations.length === 0)
        return;
    throw new InvalidTemplateSpecError(`invalid template spec: ${violations.map(formatTemplateSpecViolation).join("; ")}`);
}
function formatTemplateSpecViolation(violation) {
    return `${violation.field}: ${violation.message}`;
}
function looksLikeUUID(value) {
    return value.length === 36 && (value.match(/-/g)?.length ?? 0) === 4;
}
function stripRegistryTag(value) {
    const slash = value.lastIndexOf("/");
    const colon = value.lastIndexOf(":");
    if (slash >= 0 && colon > slash)
        return value.slice(0, colon);
    return value;
}
function sleep(ms, signal) {
    return new Promise((resolve, reject) => {
        if (signal?.aborted) {
            reject(signal.reason);
            return;
        }
        const timer = setTimeout(resolve, ms);
        signal?.addEventListener("abort", () => {
            clearTimeout(timer);
            reject(signal.reason);
        }, { once: true });
    });
}
/** Luxor Sandbox client; the same class as {@link TenkiSandbox}. */
export const LuxorSandbox = TenkiSandbox;
function sessionEgressPolicy(options) {
    if (options.allowDomains?.length ||
        options.allowCidrs?.length ||
        options.interceptHttps ||
        options.allowedPorts?.length ||
        options.publicEgress !== undefined ||
        options.httpRules?.length) {
        return create(SessionEgressPolicySchema, {
            allowDomains: options.allowDomains ?? [],
            allowCidrs: options.allowCidrs ?? [],
            interceptHttps: options.interceptHttps ?? false,
            allowedPorts: [...(options.allowedPorts ?? [])],
            publicEgress: options.publicEgress,
            httpRules: (options.httpRules ?? []).map(egressHttpRuleToProto),
        });
    }
    return undefined;
}
//# sourceMappingURL=client.js.map