UNPKG

@luxorai/sandbox

Version:

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

1,575 lines • 68.8 kB
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Session = void 0;
exports.egressPolicyFromProto = egressPolicyFromProto;
exports.egressHttpRuleToProto = egressHttpRuleToProto;
exports.largeWriteTarget = largeWriteTarget;
exports.wildcardStatusFromProto = wildcardStatusFromProto;
exports.isReady = isReady;
exports.isTerminal = isTerminal;
const protobuf_1 = require("@bufbuild/protobuf");
const wkt_1 = require("@bufbuild/protobuf/wkt");
const connect_1 = require("@connectrpc/connect");
const constants_js_1 = require("./constants.js");
const cost_js_1 = require("./cost.js");
const data_plane_js_1 = require("./data-plane.js");
const dial_js_1 = require("./dial.js");
const errors_js_1 = require("./errors.js");
const fs_js_1 = require("./fs.js");
const git_js_1 = require("./git.js");
const github_token_js_1 = require("./github-token.js");
const injection_credentials_js_1 = require("./injection-credentials.js");
const sandbox_pb_js_1 = require("./internal/proto/tenki/sandbox/v1/sandbox_pb.js");
const session_injection_credentials_pb_js_1 = require("./internal/proto/tenki/sandbox/v1/session_injection_credentials_pb.js");
const template_pb_js_1 = require("./internal/proto/tenki/sandbox/v1/template_pb.js");
const metrics_js_1 = require("./metrics.js");
const options_js_1 = require("./options.js");
const process_js_1 = require("./process.js");
const ready_backoff_js_1 = require("./ready-backoff.js");
const refused_stream_js_1 = require("./refused-stream.js");
const snapshot_js_1 = require("./snapshot.js");
const ssh_js_1 = require("./ssh.js");
const storage_js_1 = require("./storage.js");
const stream_js_1 = require("./stream.js");
const tailnet_js_1 = require("./tailnet.js");
const tunnel_resilient_js_1 = require("./tunnel-resilient.js");
const tunnel_js_1 = require("./tunnel.js");
const warning_js_1 = require("./warning.js");
// Tolerates stale stopped-state reads (read-replica lag) right after resume()
// before waitResumed has observed RESUMING from the server.
const RESUME_REVERT_GRACE_MS = 3_000;
const PAUSE_REVERT_GRACE_MS = 3_000;
// Retries ResumeSession while the paused source is still being torn down.
const RESUME_RETRY_BUDGET_MS = 60_000;
const RESUME_RETRY_INITIAL_BACKOFF_MS = 1_000;
const RESUME_RETRY_MAX_BACKOFF_MS = 5_000;
function egressFromProto(proto) {
    return egressPolicyFromProto(proto.egress, proto.egressPolicies);
}
function egressPolicyFromProto(egress, policyNames = []) {
    return {
        allowDomains: [...(egress?.allowDomains ?? [])],
        allowCidrs: [...(egress?.allowCidrs ?? [])],
        interceptHttps: egress?.interceptHttps ?? false,
        allowedPorts: [...(egress?.allowedPorts ?? [])],
        publicEgress: egress?.publicEgress
            ? { tcpPorts: [...egress.publicEgress.tcpPorts], udpPorts: [...egress.publicEgress.udpPorts] }
            : undefined,
        httpRules: (egress?.httpRules ?? []).map(egressHttpRuleFromProto),
        policyNames: [...policyNames],
    };
}
function egressHttpRuleFromProto(rule) {
    const result = { domains: [...rule.domains], methods: [...rule.methods] };
    if (rule.path.case === "exact")
        result.pathExact = rule.path.value;
    if (rule.path.case === "prefix")
        result.pathPrefix = rule.path.value;
    if (rule.path.case === "regex")
        result.pathRegex = rule.path.value;
    return result;
}
function egressHttpRuleToProto(rule) {
    const paths = [rule.pathExact, rule.pathPrefix, rule.pathRegex].filter(Boolean);
    if (paths.length > 1) {
        throw new Error("An egress HTTP rule may set only one of pathExact, pathPrefix, pathRegex");
    }
    let path = { case: undefined };
    if (rule.pathExact)
        path = { case: "exact", value: rule.pathExact };
    if (rule.pathPrefix)
        path = { case: "prefix", value: rule.pathPrefix };
    if (rule.pathRegex)
        path = { case: "regex", value: rule.pathRegex };
    return (0, protobuf_1.create)(sandbox_pb_js_1.SessionEgressHttpRuleSchema, { domains: [...rule.domains], methods: [...(rule.methods ?? [])], path });
}
// Caps one GetSession so a stalled connection cannot consume the whole readiness budget.
const WAIT_POLL_ATTEMPT_TIMEOUT_MS = 10_000;
// The data plane refuses unary ReadFile/WriteFile above this, so larger content goes over the stream RPCs.
const MAX_UNARY_FILE_BYTES = 32 * 1024 * 1024;
// largeWriteTarget returns the mode a large write keeps, an existing file's permission bits as unary WriteFile does,
// and whether the server accepts parallel write parts.
async function largeWriteTarget(session, path) {
    try {
        const request = (0, protobuf_1.create)(sandbox_pb_js_1.StatRequestSchema, { sessionId: session.id, path });
        const dataPlane = await session.requireDataPlane();
        const stat = (await dataPlane.stat((0, protobuf_1.create)(sandbox_pb_js_1.SandboxSessionDataPlaneServiceStatRequestSchema, { request }))).response;
        const mode = !stat?.exists || stat.isDir ? 0o644 : stat.mode & 0o777;
        return { mode, parallel: stat?.supportsParallelFileWrites ?? false };
    }
    catch (err) {
        throw (0, errors_js_1.mapError)(err);
    }
}
class Session {
    dataPlaneReadyTimeoutMs;
    warningHandler;
    id;
    rpcClient;
    git;
    fs;
    name;
    state;
    ownerType;
    ownerId;
    workspaceId;
    inboundEnabled;
    outboundEnabled;
    cpuCores;
    memoryMb;
    diskSizeGb;
    timeoutAt;
    idleTimeoutMinutes;
    lastActivityAt;
    pausedAt;
    pauseSnapshotId;
    pauseRetentionMs;
    pauseExpiresAt;
    metadata;
    tags;
    egress;
    volumeMounts;
    pauseSnapshot;
    lastResumeError;
    terminalError;
    runtimeState;
    guestControlDenied;
    runtimeSecretsPresent;
    get hasRuntimeSecrets() {
        return this.runtimeSecretsPresent;
    }
    runtimeError;
    sticky;
    sourceRegistryImageId;
    sourceSnapshotId;
    sourceRegistryWorkspaceId;
    sourceRegistryRef;
    sourceTemplateId;
    warnings;
    tailnetStatus;
    networkMode;
    /** UNSPECIFIED unless networkMode is RESTRICTED. */
    networkRestrictionReason;
    #authToken;
    gatewayAddress;
    sshOptions;
    dataPlaneEndpoint = "";
    dataPlaneWarmStarted = false;
    dataPlaneCredential;
    dataPlaneClient;
    dataPlaneLaneClients = [];
    // Set once this sandbox has refused a parallel write, so later large writes go straight to one stream.
    parallelWritesUnavailable = false;
    dataPlaneVerifiedClient;
    dataPlaneEndpointFromHint = false;
    dataPlaneEndpointHints = new data_plane_js_1.DataPlaneEndpointHints();
    // Set by close(). A renewal or data-plane response that lands afterwards
    // must not re-arm the session: without it a response in flight across close
    // revives both the renewal loop and a pooled transport for a session that is
    // already terminated.
    dataPlaneClosed = false;
    // closeDone short-circuits every close() after the first that succeeds;
    // closing joins callers onto the one in flight. A failed close stays
    // retryable.
    closeDone = false;
    released = false;
    closing;
    constructor(rpcClient, proto, authToken, gatewayAddress, sshOptions, dataPlaneReadyTimeoutMs = 60_000, dataPlane, warnings = [], warningHandler) {
        this.dataPlaneReadyTimeoutMs = dataPlaneReadyTimeoutMs;
        this.warningHandler = warningHandler;
        this.rpcClient = rpcClient;
        this.#authToken = authToken;
        this.gatewayAddress = gatewayAddress;
        this.sshOptions = sshOptions;
        this.id = proto.id;
        this.applyDataPlaneResponse(dataPlane?.endpoint, dataPlane?.credential, dataPlane?.routeStatus);
        this.name = proto.name;
        this.state = sessionStateFromProto(proto.state);
        this.ownerType = proto.ownerType;
        this.ownerId = proto.ownerId;
        this.workspaceId = proto.workspaceId;
        this.inboundEnabled = proto.inboundEnabled;
        this.outboundEnabled = proto.outboundEnabled;
        this.cpuCores = proto.cpuCores;
        this.memoryMb = proto.memoryMb;
        this.diskSizeGb = proto.diskSizeGb;
        this.timeoutAt = proto.timeoutAt ? (0, wkt_1.timestampDate)(proto.timeoutAt) : new Date(0);
        this.idleTimeoutMinutes = proto.idleTimeoutMinutes;
        this.lastActivityAt = proto.lastActivityAt ? (0, wkt_1.timestampDate)(proto.lastActivityAt) : undefined;
        this.pausedAt = proto.pausedAt ? (0, wkt_1.timestampDate)(proto.pausedAt) : undefined;
        this.pauseSnapshotId = proto.pauseSnapshotId;
        this.pauseRetentionMs = proto.pauseRetention
            ? Number(proto.pauseRetention.seconds) * 1000 + Math.floor(proto.pauseRetention.nanos / 1_000_000)
            : undefined;
        this.pauseExpiresAt = proto.pauseExpiresAt ? (0, wkt_1.timestampDate)(proto.pauseExpiresAt) : undefined;
        this.metadata = { ...proto.metadata };
        this.tags = [...(proto.tags ?? [])];
        this.egress = egressFromProto(proto);
        this.pauseSnapshot = proto.pauseSnapshot ? (0, snapshot_js_1.snapshotFromProto)(proto.pauseSnapshot) : undefined;
        this.volumeMounts = (proto.volumeAttachments ?? []).map((a) => ({
            volumeId: a.volumeId,
            mountPath: a.mountPath,
            readOnly: a.readonly,
            state: a.state,
        }));
        this.lastResumeError = proto.lastResumeError || undefined;
        this.terminalError = proto.terminalError || undefined;
        this.runtimeState = templateRuntimeStateFromProto(proto.runtimeState);
        this.guestControlDenied = proto.guestControlDenied ?? false;
        this.runtimeSecretsPresent = proto.hasRuntimeSecrets;
        this.runtimeError = proto.runtimeError || undefined;
        this.sticky = proto.sticky;
        this.sourceRegistryImageId = proto.sourceRegistryImageId || undefined;
        this.sourceSnapshotId = proto.sourceSnapshotId || undefined;
        this.sourceRegistryWorkspaceId = proto.sourceRegistryWorkspaceId || undefined;
        this.sourceRegistryRef = proto.sourceRegistryRef || undefined;
        this.sourceTemplateId = proto.sourceTemplateId || undefined;
        this.warnings = [...warnings];
        this.tailnetStatus = (0, tailnet_js_1.tailnetStatusFromProto)(proto.tailnetStatus);
        this.networkMode = networkModeFromProto(proto.networkMode);
        this.networkRestrictionReason = networkRestrictionReasonFromProto(proto.networkRestrictionReason);
        this.git = new git_js_1.Git(this);
        this.fs = {
            readStream: (path, options) => (0, fs_js_1.readFileStream)(this, path, options),
            writeStream: (path, data, options) => (0, fs_js_1.writeFileStream)(this, path, data, options),
            stat: (path) => (0, fs_js_1.stat)(this, path),
            mkdir: (path) => (0, fs_js_1.mkdir)(this, path),
            remove: (path) => (0, fs_js_1.remove)(this, path),
            list: (path, options) => (0, fs_js_1.list)(this, path, options),
        };
    }
    // Allowlist so JSON logging never serializes transport state or credentials.
    toJSON() {
        return {
            id: this.id,
            name: this.name,
            state: this.state,
            ownerType: this.ownerType,
            ownerId: this.ownerId,
            workspaceId: this.workspaceId,
            inboundEnabled: this.inboundEnabled,
            outboundEnabled: this.outboundEnabled,
            cpuCores: this.cpuCores,
            memoryMb: this.memoryMb,
            diskSizeGb: this.diskSizeGb,
            timeoutAt: this.timeoutAt,
            idleTimeoutMinutes: this.idleTimeoutMinutes,
            lastActivityAt: this.lastActivityAt,
            pausedAt: this.pausedAt,
            pauseSnapshotId: this.pauseSnapshotId,
            pauseRetentionMs: this.pauseRetentionMs,
            pauseExpiresAt: this.pauseExpiresAt,
            metadata: this.metadata,
            tags: this.tags,
            egress: this.egress,
            volumeMounts: this.volumeMounts,
            pauseSnapshot: this.pauseSnapshot,
            lastResumeError: this.lastResumeError,
            terminalError: this.terminalError,
            runtimeState: this.runtimeState,
            guestControlDenied: this.guestControlDenied,
            hasRuntimeSecrets: this.hasRuntimeSecrets,
            runtimeError: this.runtimeError,
            sticky: this.sticky,
            sourceRegistryImageId: this.sourceRegistryImageId,
            sourceSnapshotId: this.sourceSnapshotId,
            sourceRegistryWorkspaceId: this.sourceRegistryWorkspaceId,
            sourceRegistryRef: this.sourceRegistryRef,
            sourceTemplateId: this.sourceTemplateId,
            warnings: this.warnings,
            tailnetStatus: this.tailnetStatus,
            networkMode: this.networkMode,
            networkRestrictionReason: this.networkRestrictionReason,
        };
    }
    dataPlaneRPC() {
        return this.dataPlaneClient;
    }
    dataPlaneReadyBudgetMs() {
        return this.dataPlaneReadyTimeoutMs;
    }
    dataPlaneProvisioningPending(client) {
        return this.dataPlaneClient === client && this.dataPlaneVerifiedClient !== client;
    }
    markDataPlaneServing(client) {
        if (this.dataPlaneClient === client)
            this.dataPlaneVerifiedClient = client;
    }
    dataPlaneUsingEndpointHint(client) {
        return this.dataPlaneClient === client && this.dataPlaneEndpointFromHint;
    }
    async refreshHintedDataPlane(client) {
        if (!this.dataPlaneUsingEndpointHint(client))
            return false;
        return this.renewDataPlaneCredential();
    }
    // Bootstrap the data-plane client via CreateSessionCredential if not resolved yet.
    async ensureDataPlane(verifyServing = true) {
        if (this.dataPlaneClosed)
            throw new Error("sandbox: session handle closed or released");
        if (!this.dataPlaneClient && this.dataPlaneCredential?.current()) {
            const hintedEndpoint = await this.dataPlaneEndpointHints.resolve(async () => {
                await this.renewDataPlaneCredential();
                return this.dataPlaneEndpoint;
            });
            if (!this.dataPlaneClient && hintedEndpoint) {
                this.configureDataPlane({ endpoint: hintedEndpoint }, true);
            }
        }
        if (!this.dataPlaneClient)
            await this.renewDataPlaneCredential();
        if (verifyServing && this.dataPlaneClient)
            await this.ensureDataPlaneServing(this.dataPlaneClient);
        return this.dataPlaneClient;
    }
    async requireDataPlane(verifyServing = true) {
        const dataPlane = await this.ensureDataPlane(verifyServing);
        if (!dataPlane)
            throw new Error("sandbox: data-plane endpoint unavailable");
        return dataPlane;
    }
    // The shared data-plane client followed by up to count-1 clients on their own connections to the same host.
    async requireDataPlaneLanes(count) {
        const primary = await this.requireDataPlane();
        const credential = this.dataPlaneCredential;
        // A close or endpoint reset during the await would leave new lanes that nothing releases.
        if (this.dataPlaneClosed || this.dataPlaneClient !== primary || !credential || !this.dataPlaneEndpoint) {
            return [primary];
        }
        while (this.dataPlaneLaneClients.length < count - 1) {
            const lane = this.dataPlaneLaneClients.length + 1;
            this.dataPlaneLaneClients.push((0, data_plane_js_1.createDataPlaneClient)(this.dataPlaneEndpoint, credential, this.id, lane));
        }
        return [primary, ...this.dataPlaneLaneClients.slice(0, count - 1)];
    }
    closeDataPlaneLanes() {
        for (const client of this.dataPlaneLaneClients)
            (0, data_plane_js_1.closeDataPlaneConnection)(client);
        this.dataPlaneLaneClients = [];
    }
    // Probe the edge until it stops returning the transient cold-start 404 (Edge applies the route async).
    async ensureDataPlaneServing(client) {
        if (this.dataPlaneVerifiedClient === client)
            return;
        let lastErr;
        const deadline = Date.now() + this.dataPlaneReadyTimeoutMs;
        for (let attempt = 0; Date.now() < deadline; attempt++) {
            try {
                await client.stat((0, protobuf_1.create)(sandbox_pb_js_1.SandboxSessionDataPlaneServiceStatRequestSchema, {
                    request: (0, protobuf_1.create)(sandbox_pb_js_1.StatRequestSchema, { sessionId: this.id, path: "/home/tenki" }),
                }));
                this.dataPlaneVerifiedClient = client;
                return;
            }
            catch (err) {
                // Any response other than edge-not-ready (success OR an app-level error) proves the route serves.
                if (!(0, errors_js_1.isDataPlaneEdgeNotReady)(err)) {
                    this.dataPlaneVerifiedClient = client;
                    return;
                }
                lastErr = err;
                await (0, ready_backoff_js_1.sleepReadyBackoff)(attempt, deadline);
            }
        }
        throw (0, errors_js_1.dataPlaneNotReadyError)(lastErr);
    }
    async reauthOnUnauthenticated(err) {
        if (!(err instanceof connect_1.ConnectError) || err.code !== connect_1.Code.Unauthenticated)
            return false;
        try {
            return await this.renewDataPlaneCredential();
        }
        catch {
            return false;
        }
    }
    configureDataPlane(dataPlane, endpointFromHint = false) {
        const endpoint = dataPlane?.endpoint?.trim();
        if (!endpoint)
            return;
        // A terminated session must not acquire a transport or a renewal loop,
        // however late the response that got here.
        if (this.dataPlaneClosed)
            return;
        if (endpoint === this.dataPlaneEndpoint && this.dataPlaneCredential) {
            this.dataPlaneCredential.set(dataPlane?.credential, endpoint);
            this.dataPlaneEndpointFromHint = endpointFromHint;
            return;
        }
        (0, data_plane_js_1.closeDataPlaneConnection)(this.dataPlaneClient);
        this.closeDataPlaneLanes();
        this.dataPlaneEndpoint = endpoint;
        if (!this.dataPlaneCredential) {
            this.dataPlaneCredential = new data_plane_js_1.DataPlaneCredentialManager(this, dataPlane?.credential, endpoint);
        }
        else {
            this.dataPlaneCredential.set(dataPlane?.credential, endpoint);
            // A credential the engine handed back before the endpoint was known is
            // unbound; this endpoint adopts it. One already bound to another node is
            // left alone, and the interceptor refuses to attach it here.
            this.dataPlaneCredential.adoptEndpoint(endpoint);
        }
        this.dataPlaneClient = (0, data_plane_js_1.createDataPlaneClient)(endpoint, this.dataPlaneCredential, this.id, 0);
        this.dataPlaneEndpointFromHint = endpointFromHint;
    }
    resetDataPlane() {
        this.dataPlaneCredential?.stop();
        (0, data_plane_js_1.closeDataPlaneConnection)(this.dataPlaneClient);
        this.closeDataPlaneLanes();
        this.dataPlaneEndpointHints.clear();
        this.dataPlaneEndpoint = "";
        this.dataPlaneCredential = undefined;
        this.dataPlaneClient = undefined;
        this.dataPlaneVerifiedClient = undefined;
        this.dataPlaneEndpointFromHint = false;
        this.dataPlaneWarmStarted = false;
    }
    applyDataPlaneResponse(endpoint, credential, routeStatus) {
        if (routeStatus === sandbox_pb_js_1.DataPlaneRouteStatus.FAILED)
            return;
        if (this.dataPlaneClosed)
            return;
        const resolved = endpoint?.trim();
        if (credential) {
            // A credential that arrives without an endpoint belongs to the endpoint
            // already in force; one that arrives with an endpoint is bound to it by
            // configureDataPlane below.
            const boundTo = resolved || this.dataPlaneEndpoint;
            if (!this.dataPlaneCredential) {
                this.dataPlaneCredential = new data_plane_js_1.DataPlaneCredentialManager(this, credential, boundTo);
            }
            else {
                this.dataPlaneCredential.set(credential, boundTo);
            }
        }
        if (resolved) {
            this.dataPlaneEndpointHints.remember(resolved);
            this.configureDataPlane({ endpoint: resolved, credential });
        }
        this.startDataPlaneWarm();
        if (routeStatus === sandbox_pb_js_1.DataPlaneRouteStatus.VERIFIED && this.dataPlaneClient) {
            this.dataPlaneVerifiedClient = this.dataPlaneClient;
        }
    }
    // Open the connection once an endpoint is known so the first call skips the handshake.
    startDataPlaneWarm() {
        if (this.dataPlaneWarmStarted || !this.dataPlaneClient)
            return;
        this.dataPlaneWarmStarted = true;
        void (0, data_plane_js_1.warmDataPlaneConnection)(this.dataPlaneClient).catch(() => { });
    }
    async renewDataPlaneCredential() {
        if (this.dataPlaneClosed)
            return false;
        const deadline = Date.now() + this.dataPlaneReadyTimeoutMs;
        let lastErr;
        for (let attempt = 0; !this.dataPlaneClosed && Date.now() < deadline; attempt++) {
            try {
                const resp = await this.rpcClient.createSessionCredential((0, protobuf_1.create)(sandbox_pb_js_1.CreateSessionCredentialRequestSchema, { sessionId: this.id }));
                if (this.dataPlaneClosed)
                    return false;
                switch (resp.routeStatus) {
                    case sandbox_pb_js_1.DataPlaneRouteStatus.FAILED:
                        throw (0, errors_js_1.terminalDataPlaneNotReadyError)();
                    case sandbox_pb_js_1.DataPlaneRouteStatus.NOT_READY:
                        if (resp.dataPlaneEndpoint?.trim()) {
                            this.applyDataPlaneResponse(resp.dataPlaneEndpoint, resp.credential, resp.routeStatus);
                            return true;
                        }
                        lastErr = (0, errors_js_1.dataPlaneNotReadyError)(undefined);
                        await (0, ready_backoff_js_1.sleepReadyBackoff)(attempt, deadline);
                        continue;
                    default:
                        this.applyDataPlaneResponse(resp.dataPlaneEndpoint, resp.credential, resp.routeStatus);
                        return true;
                }
            }
            catch (err) {
                if (this.dataPlaneClosed)
                    return false;
                const mapped = (0, errors_js_1.mapError)(err);
                if (mapped instanceof errors_js_1.DataPlaneNotReadyError || mapped instanceof errors_js_1.InvalidStateError) {
                    if ((0, errors_js_1.isPausedSessionStateError)(mapped))
                        throw mapped;
                    if (mapped instanceof errors_js_1.DataPlaneNotReadyError && mapped.terminal)
                        throw mapped;
                    lastErr = mapped;
                    await (0, ready_backoff_js_1.sleepReadyBackoff)(attempt, deadline);
                    continue;
                }
                throw mapped;
            }
        }
        if (this.dataPlaneClosed)
            return false;
        throw (0, errors_js_1.dataPlaneNotReadyError)(lastErr);
    }
    applyProto(proto) {
        this.name = proto.name;
        this.state = sessionStateFromProto(proto.state);
        this.ownerType = proto.ownerType;
        this.ownerId = proto.ownerId;
        this.workspaceId = proto.workspaceId;
        this.inboundEnabled = proto.inboundEnabled;
        this.outboundEnabled = proto.outboundEnabled;
        this.cpuCores = proto.cpuCores;
        this.memoryMb = proto.memoryMb;
        this.diskSizeGb = proto.diskSizeGb;
        this.timeoutAt = proto.timeoutAt ? (0, wkt_1.timestampDate)(proto.timeoutAt) : new Date(0);
        this.idleTimeoutMinutes = proto.idleTimeoutMinutes;
        this.lastActivityAt = proto.lastActivityAt ? (0, wkt_1.timestampDate)(proto.lastActivityAt) : undefined;
        this.pausedAt = proto.pausedAt ? (0, wkt_1.timestampDate)(proto.pausedAt) : undefined;
        this.pauseSnapshotId = proto.pauseSnapshotId;
        this.pauseRetentionMs = proto.pauseRetention
            ? Number(proto.pauseRetention.seconds) * 1000 + Math.floor(proto.pauseRetention.nanos / 1_000_000)
            : undefined;
        this.pauseExpiresAt = proto.pauseExpiresAt ? (0, wkt_1.timestampDate)(proto.pauseExpiresAt) : undefined;
        this.metadata = { ...proto.metadata };
        this.tags = [...(proto.tags ?? [])];
        this.egress = egressFromProto(proto);
        this.pauseSnapshot = proto.pauseSnapshot ? (0, snapshot_js_1.snapshotFromProto)(proto.pauseSnapshot) : undefined;
        this.volumeMounts = (proto.volumeAttachments ?? []).map((a) => ({
            volumeId: a.volumeId,
            mountPath: a.mountPath,
            readOnly: a.readonly,
            state: a.state,
        }));
        this.lastResumeError = proto.lastResumeError || undefined;
        this.terminalError = proto.terminalError || undefined;
        this.runtimeState = templateRuntimeStateFromProto(proto.runtimeState);
        this.guestControlDenied = proto.guestControlDenied ?? false;
        this.runtimeSecretsPresent = proto.hasRuntimeSecrets;
        this.runtimeError = proto.runtimeError || undefined;
        this.sticky = proto.sticky;
        this.tailnetStatus = (0, tailnet_js_1.tailnetStatusFromProto)(proto.tailnetStatus);
        this.networkMode = networkModeFromProto(proto.networkMode);
        this.networkRestrictionReason = networkRestrictionReasonFromProto(proto.networkRestrictionReason);
    }
    async exec(command, options) {
        const maxOutputBytes = maxOutputBytesFrom(options);
        const argv = (0, process_js_1.normalizeArgv)(command, options?.args);
        const proc = (0, process_js_1.run)(this, argv, {
            cwd: options?.cwd,
            env: options?.env,
            withSecrets: options?.withSecrets,
            stdin: undefined,
            timeoutMs: options?.timeoutMs,
            signal: options?.signal,
            // A capped exec keeps its own bounded copy, so the run must not retain every chunk.
            streamOnly: maxOutputBytes > 0,
        });
        void proc.stdin.close().catch(() => { });
        const stdoutChunks = [];
        const stderrChunks = [];
        const outputs = [];
        const [stdoutTruncated, stderrTruncated] = await Promise.all([
            collectReadableOutputs(proc.stdout, false, stdoutChunks, outputs, maxOutputBytes, options?.onOutput),
            collectReadableOutputs(proc.stderr, true, stderrChunks, outputs, maxOutputBytes, options?.onOutput),
        ]);
        const result = await proc;
        return {
            sessionId: this.id,
            command: argv[0],
            args: argv.slice(1),
            status: commandStatusFromResult(result),
            exitCode: result.exitCode,
            durationMs: result.durationMs ?? 0,
            reason: result.reason,
            disk: result.disk,
            outputs,
            stdout: concatUint8Arrays(stdoutChunks),
            stderr: concatUint8Arrays(stderrChunks),
            stdoutTruncated,
            stderrTruncated,
        };
    }
    async stream(command, options) {
        if (options?.onOutput) {
            throw new Error("Session.stream does not support onOutput; consume chunks with stream.next() instead");
        }
        const maxOutputBytes = maxOutputBytesFrom(options);
        const argv = (0, process_js_1.normalizeArgv)(command, options?.args);
        const proc = (0, process_js_1.run)(this, argv, {
            cwd: options?.cwd,
            env: options?.env,
            withSecrets: options?.withSecrets,
            timeoutMs: options?.timeoutMs,
            signal: options?.signal,
            // The stream keeps its own capped copy for the result, so the run must not retain every chunk.
            streamOnly: true,
        });
        await proc.pid;
        void proc.stdin.close().catch(() => { });
        return streamFromRunHandle(this.id, argv[0], argv.slice(1), proc, maxOutputBytes);
    }
    dial(unixSocketPath, options) {
        return (0, dial_js_1.dial)(this, unixSocketPath, options);
    }
    run(argv, options) {
        return (0, process_js_1.run)(this, argv, options);
    }
    readFileStream(path, options) {
        return (0, fs_js_1.readFileStream)(this, path, options);
    }
    writeFileStream(path, data, options) {
        return (0, fs_js_1.writeFileStream)(this, path, data, options);
    }
    stat(path) {
        return (0, fs_js_1.stat)(this, path);
    }
    mkdir(path) {
        return (0, fs_js_1.mkdir)(this, path);
    }
    remove(path) {
        return (0, fs_js_1.remove)(this, path);
    }
    list(path, options) {
        return (0, fs_js_1.list)(this, path, options);
    }
    hostPortTunnel(host, port, options) {
        return (0, tunnel_js_1.hostPortTunnel)(this, host, port, options);
    }
    resilientHostPortTunnel(host, port, options) {
        return (0, tunnel_resilient_js_1.resilientHostPortTunnel)(this, host, port, options);
    }
    exposeHostPort(hostAddr, options) {
        return (0, tunnel_js_1.exposeHostPort)(this, hostAddr, options);
    }
    exposeHostPortResilient(hostAddr, options) {
        return (0, tunnel_resilient_js_1.exposeHostPortResilient)(this, hostAddr, options);
    }
    async writeFile(path, data) {
        const content = typeof data === "string" ? new TextEncoder().encode(data) : data;
        if (content.byteLength > MAX_UNARY_FILE_BYTES) {
            const { mode, parallel } = await largeWriteTarget(this, path);
            // Only a server that advertises parts may get them: an older one writes each part as the whole file.
            if (parallel && !this.parallelWritesUnavailable) {
                const outcome = await (0, fs_js_1.writeFileParallel)(this, path, content, mode);
                if (outcome === "written")
                    return;
                if (outcome === "unsupported")
                    this.parallelWritesUnavailable = true;
            }
            return (0, fs_js_1.writeFileStream)(this, path, (0, fs_js_1.chunkedSource)(content), { mode });
        }
        try {
            const request = (0, protobuf_1.create)(sandbox_pb_js_1.WriteFileRequestSchema, {
                sessionId: this.id,
                path,
                content,
            });
            const dataPlane = await this.requireDataPlane();
            const resp = await dataPlane.writeFile((0, protobuf_1.create)(sandbox_pb_js_1.SandboxSessionDataPlaneServiceWriteFileRequestSchema, { request }));
            (0, errors_js_1.ensureFullWrite)(path, BigInt(content.byteLength), resp.response?.sizeBytes);
        }
        catch (err) {
            throw (0, errors_js_1.mapWriteError)(err);
        }
    }
    async readFile(path) {
        try {
            const request = (0, protobuf_1.create)(sandbox_pb_js_1.ReadFileRequestSchema, { sessionId: this.id, path });
            const dataPlane = await this.requireDataPlane();
            const resp = (await dataPlane.readFile((0, protobuf_1.create)(sandbox_pb_js_1.SandboxSessionDataPlaneServiceReadFileRequestSchema, { request })))
                .response;
            return new Uint8Array(resp.content);
        }
        catch (err) {
            const mapped = (0, errors_js_1.mapError)(err);
            if (!(mapped instanceof errors_js_1.FileTooLargeError))
                throw mapped;
            const size = Number(mapped.sizeBytes);
            if ((0, fs_js_1.parallelReadSizeOk)(size)) {
                const content = await (0, fs_js_1.readFileParallel)(this, path, size);
                if (content)
                    return content;
            }
        }
        const chunks = [];
        let total = 0;
        const reader = (await (0, fs_js_1.readFileStream)(this, path)).getReader();
        for (;;) {
            const { done, value } = await reader.read();
            if (done)
                break;
            chunks.push(value);
            total += value.byteLength;
        }
        const content = new Uint8Array(total);
        let offset = 0;
        for (const chunk of chunks) {
            content.set(chunk, offset);
            offset += chunk.byteLength;
        }
        return content;
    }
    async waitReady(timeoutMs, signal) {
        const timeout = timeoutMs ?? 180_000;
        const deadline = Date.now() + timeout;
        try {
            await this.waitReadyStream(timeout, signal);
            return;
        }
        catch (err) {
            if (signal?.aborted)
                throw (0, errors_js_1.mapError)(signal.reason);
            if (!(0, refused_stream_js_1.isRetryableWaitStreamError)(err) || Date.now() >= deadline)
                throw (0, errors_js_1.mapError)(err);
        }
        await this.waitReadyPoll(Math.max(0, deadline - Date.now()), signal);
    }
    async waitReadyStream(timeoutMs, signal) {
        // WaitSession ends at readiness or termination; consume its trailers to release the RPC deadline.
        for await (const resp of this.rpcClient.waitSession((0, protobuf_1.create)(sandbox_pb_js_1.WaitSessionRequestSchema, { sessionId: this.id }), {
            timeoutMs,
            signal,
        })) {
            signal?.throwIfAborted();
            if (resp.session)
                this.applyProto(resp.session);
            this.applyDataPlaneResponse(resp.dataPlaneEndpoint, resp.credential, resp.routeStatus);
            // WaitSession closes after its final state; consume EOF to release the RPC deadline.
        }
        if (isReady(this.state))
            return;
        if (isTerminal(this.state)) {
            throw this.terminalStateError();
        }
        throw new refused_stream_js_1.WaitStreamEndedError(`readiness stream ended before session ${this.id} became ready`);
    }
    async waitReadyPoll(timeoutMs, signal) {
        const deadline = Date.now() + (timeoutMs ?? 180_000);
        let attempt = 0;
        let lastErr;
        while (Date.now() < deadline) {
            if (signal?.aborted)
                throw (0, errors_js_1.mapError)(signal.reason);
            let polled = false;
            try {
                const resp = await this.rpcClient.getSession((0, protobuf_1.create)(sandbox_pb_js_1.GetSessionRequestSchema, { sessionId: this.id }), {
                    timeoutMs: Math.max(1, Math.min(WAIT_POLL_ATTEMPT_TIMEOUT_MS, deadline - Date.now())),
                    signal,
                });
                if (resp.session)
                    this.applyProto(resp.session);
                polled = true;
            }
            catch (err) {
                if (signal?.aborted || !(0, refused_stream_js_1.isRetryableWaitPollError)(err))
                    throw (0, errors_js_1.mapError)(err);
                // Retry replica lag and transient RPC failures within the readiness budget.
                lastErr = err;
            }
            if (polled && isReady(this.state))
                return;
            if (polled && isTerminal(this.state)) {
                throw this.terminalStateError();
            }
            if (Date.now() >= deadline)
                break;
            try {
                await sleep(Math.min((0, constants_js_1.pollBackoffMs)(attempt), Math.max(0, deadline - Date.now())), signal);
            }
            catch (err) {
                throw (0, errors_js_1.mapError)(err);
            }
            attempt++;
        }
        if (lastErr === undefined)
            throw new Error(`timeout waiting for session ${this.id} to become ready`);
        const reason = lastErr instanceof Error ? lastErr.message : String(lastErr);
        throw new Error(`timeout waiting for session ${this.id} to become ready (last error: ${reason})`, {
            cause: lastErr,
        });
    }
    /**
     * 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.
     */
    async waitResumed(timeoutMs, signal) {
        const timeout = timeoutMs ?? 180_000;
        const deadline = Date.now() + timeout;
        const start = Date.now();
        let sawResuming = false;
        let pausedAt = this.pausedAt;
        let attempt = 0;
        while (Date.now() < deadline) {
            signal?.throwIfAborted();
            try {
                const resp = await this.rpcClient.getSession((0, protobuf_1.create)(sandbox_pb_js_1.GetSessionRequestSchema, { sessionId: this.id }));
                if (resp.session)
                    this.applyProto(resp.session);
            }
            catch {
                // tolerate not-found during polling (read-replica lag)
            }
            if (isReady(this.state))
                return;
            if (isTerminal(this.state))
                throw this.terminalStateError();
            if (this.state === "RESUMING") {
                sawResuming = true;
                pausedAt = this.pausedAt ?? pausedAt;
            }
            else if (this.state === "PAUSING") {
                // PAUSING only follows RUNNING, so a fresh read means the resume landed before a concurrent pause.
                if (sawResuming || Date.now() - start > RESUME_REVERT_GRACE_MS)
                    return;
            }
            else if (this.state === "PAUSED" || this.state === "USER_SHUTDOWN") {
                // A stopped state is settled once RESUMING was observed from the
                // server, or after the replica-lag grace window has passed.
                if (sawResuming || Date.now() - start > RESUME_REVERT_GRACE_MS) {
                    // A landed resume clears pausedAt and a later pause or shutdown sets a newer one; a revert or snapshot migration keeps it.
                    if (pausedAt && !this.lastResumeError && this.pausedAt?.getTime() !== pausedAt.getTime())
                        return;
                    throw this.resumeFailedError();
                }
            }
            await sleep((0, constants_js_1.pollBackoffMs)(attempt), signal);
            attempt++;
        }
        throw new errors_js_1.ResumeWaitTimeoutError(`timeout waiting for session ${this.id} to resume; it may still be resuming, call waitResumed to keep waiting`);
    }
    resumeFailedError() {
        const suffix = this.lastResumeError ? `: ${this.lastResumeError}` : "";
        return new errors_js_1.ResumeFailedError(`resume failed: session ${this.id} reverted to ${this.state}${suffix}`);
    }
    async waitPaused(timeoutMs, signal) {
        const timeout = timeoutMs ?? 180_000;
        const deadline = timeout > 0 ? Date.now() + timeout : undefined;
        const start = Date.now();
        let sawPausing = false;
        let attempt = 0;
        while (deadline === undefined || Date.now() < deadline) {
            signal?.throwIfAborted();
            try {
                const resp = await this.rpcClient.getSession((0, protobuf_1.create)(sandbox_pb_js_1.GetSessionRequestSchema, { sessionId: this.id }));
                if (resp.session)
                    this.applyProto(resp.session);
            }
            catch (err) {
                const mapped = (0, errors_js_1.mapError)(err);
                if (mapped instanceof errors_js_1.SessionNotFoundError || mapped instanceof errors_js_1.UnavailableError) {
                    await sleep((0, constants_js_1.pollBackoffMs)(attempt), signal);
                    attempt++;
                    continue;
                }
                throw mapped;
            }
            if (this.state === "PAUSED")
                return;
            if (isTerminal(this.state))
                throw this.terminalStateError();
            if (this.state === "PAUSING") {
                sawPausing = true;
            }
            else if (this.state === "RUNNING" && (sawPausing || Date.now() - start > PAUSE_REVERT_GRACE_MS)) {
                throw new errors_js_1.PauseFailedError(`pause failed: session ${this.id} reverted to ${this.state}`);
            }
            await sleep((0, constants_js_1.pollBackoffMs)(attempt), signal);
            attempt++;
        }
        throw new Error(`timeout waiting for session ${this.id} to pause`);
    }
    terminalStateError() {
        const suffix = this.terminalError ? `: ${this.terminalError}` : "";
        return new errors_js_1.SessionTerminatedError(`session entered terminal state: ${this.state}${suffix}`);
    }
    // Permanently free this handle's local data plane without terminating the sandbox.
    release() {
        this.released = true;
        this.dataPlaneClosed = true;
        this.resetDataPlane();
    }
    /**
     * 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.
     */
    async close() {
        if (this.closeDone)
            return;
        if (this.closing)
            return this.closing;
        this.closing = this.closeOnce();
        try {
            await this.closing;
        }
        finally {
            this.closing = undefined;
        }
    }
    async closeOnce() {
        // Latch the data plane shut and stop renewal before terminating, so a
        // response in flight cannot revive either.
        this.dataPlaneClosed = true;
        this.dataPlaneCredential?.stop();
        try {
            const resp = await this.rpcClient.terminateSession((0, protobuf_1.create)(sandbox_pb_js_1.TerminateSessionRequestSchema, { sessionId: this.id }));
            this.closeDone = true;
            if (resp.session)
                this.applyProto(resp.session);
        }
        catch (err) {
            // Let a failed close be retried.
            this.dataPlaneClosed = this.released;
            throw (0, errors_js_1.mapError)(err);
        }
        finally {
            this.resetDataPlane();
        }
    }
    async closeIfOpen() {
        if (isTerminal(this.state)) {
            this.resetDataPlane();
            return;
        }
        await this.close();
    }
    async extend(additionalMs) {
        try {
            const resp = await this.rpcClient.extendSession((0, protobuf_1.create)(sandbox_pb_js_1.ExtendSessionRequestSchema, {
                sessionId: this.id,
                additionalDuration: (0, wkt_1.durationFromMs)(additionalMs),
            }));
            if (resp.session)
                this.applyProto(resp.session);
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
    }
    async refresh() {
        try {
            const resp = await this.rpcClient.getSession((0, protobuf_1.create)(sandbox_pb_js_1.GetSessionRequestSchema, { sessionId: this.id }));
            if (resp.session)
                this.applyProto(resp.session);
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
    }
    async metrics(windowMs) {
        const req = (0, protobuf_1.create)(sandbox_pb_js_1.GetSessionMetricsRequestSchema, { sessionId: this.id });
        if (windowMs !== undefined && windowMs !== 0)
            req.window = (0, wkt_1.durationFromMs)(windowMs);
        try {
            return (0, metrics_js_1.sessionMetricsFromProto)(await this.rpcClient.getSessionMetrics(req));
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
    }
    async cost() {
        try {
            const resp = await this.rpcClient.getSessionCost((0, protobuf_1.create)(sandbox_pb_js_1.GetSessionCostRequestSchema, { sessionId: this.id }));
            return (0, cost_js_1.sessionCostFromProto)(resp.cost, this.id);
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
    }
    async exposePort(port, options) {
        const req = (0, protobuf_1.create)(sandbox_pb_js_1.ExposePortRequestSchema, {
            sessionId: this.id,
            port,
        });
        if (options?.ttlMs && options.ttlMs > 0) {
            req.expiresAt = (0, wkt_1.timestampFromDate)(new Date(Date.now() + options.ttlMs));
        }
        if (options?.slug?.trim()) {
            req.slug = options.slug.trim();
        }
        try {
            const resp = await this.rpcClient.exposePort(req);
            return {
                port: resp.port,
                previewUrl: resp.previewUrl,
                expiresAt: resp.expiresAt ? (0, wkt_1.timestampDate)(resp.expiresAt) : undefined,
                previewUrlId: resp.previewUrlId,
                slug: resp.slug,
                wildcard: resp.wildcard ?? false,
                wildcardStatus: wildcardStatusFromProto(resp.wildcardStatus),
                wildcardStatusReason: resp.wildcardStatusReason ?? "",
            };
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
    }
    async unexposePort(port) {
        try {
            await this.rpcClient.unexposePort((0, protobuf_1.create)(sandbox_pb_js_1.UnexposePortRequestSchema, { sessionId: this.id, port }));
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
    }
    async listExposedPorts() {
        try {
            const resp = await this.rpcClient.listExposedPorts((0, protobuf_1.create)(sandbox_pb_js_1.ListExposedPortsRequestSchema, { sessionId: this.id }));
            return (resp.ports ?? []).map((p) => ({
                port: p.port,
                previewUrl: p.previewUrl,
                expiresAt: p.expiresAt ? (0, wkt_1.timestampDate)(p.expiresAt) : undefined,
                previewUrlId: p.previewUrlId,
                slug: p.slug,
                wildcard: p.wildcard ?? false,
                wildcardStatus: wildcardStatusFromProto(p.wildcardStatus),
                wildcardStatusReason: p.wildcardStatusReason ?? "",
            }));
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
    }
    async updateSshAuthorizedKeys(keys) {
        try {
            await this.rpcClient.updateSSHAuthorizedKeys((0, protobuf_1.create)(sandbox_pb_js_1.UpdateSSHAuthorizedKeysRequestSchema, {
                sessionId: this.id,
                sshAuthorizedKeys: [...keys],
            }));
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
    }
    /** Updates API then Git credentials sequentially; errors identify partial completion. */
    async rotateGitHubToken(token) {
        const inputs = (0, github_token_js_1.githubInjectionCredentials)(token);
        for (const [i, input] of inputs.entries()) {
            try {
                await this.setInjectionCredential(input);
            }
            catch (err) {
                if (err instanceof Error) {
                    const partial = i > 0 ? ` (${inputs[0].name} already rotated)` : "";
                    err.message = `rotate ${input.name} failed${partial}: ${err.message}`;
                }
                throw err;
            }
        }
    }
    /** Creates or rotates a session injection credential. */
    async setInjectionCredential(input, expectedRevision) {
        const req = (0, protobuf_1.create)(session_injection_credentials_pb_js_1.SetSessionInjectionCredentialRequestSchema, {
            sessionId: this.id,
            credential: (0, injection_credentials_js_1.injectionInput)(input),
            expectedRevision: (0, injection_credentials_js_1.injectionRevision)(expectedRevision),
        });
        try {
            return (0, injection_credentials_js_1.injectionMetadata)((await this.rpcClient.setSessionInjectionCredential(req)).credential);
        }
        catch (err) {
            const safe = (0, injection_credentials_js_1.safeInjectionError)(err);
            const failure = connect_1.ConnectError.from(safe.cause).findDetails(sandbox_pb_js_1.TemplateRuntimeFailureSchema)[0];
            if (failure?.session) {
                const session = new Session(this.rpcClient, failure.session, this.#authToken, this.gatewayAddress, this.sshOptions);
                throw new errors_js_1.TemplateRuntimeFailedError("template runtime failed", session, { cause: safe });
            }
            throw safe;
        }
    }
    /** Revokes a session injection credential by name. */
    async revokeInjectionCredential(name, expectedRevision) {
        const req = (0, protobuf_1.create)(session_injection_credentials_pb_js_1.RevokeSessionInjectionCredentialRequestSchema, {
            sessionId: this.id,
            name,
            expectedRevision: (0, injection_credentials_js_1.injectionRevision)(expectedRevision),
        });
        try {
            return (0, injection_credentials_js_1.injectionMetadata)((await this.rpcClient.revokeSessionInjectionCredential(req)).credential);
        }
        catch (err) {
            const safe = (0, injection_credentials_js_1.safeInjectionError)(err);
            const failure = connect_1.ConnectError.from(safe.cause).findDetails(sandbox_pb_js_1.TemplateRuntimeFailureSchema)[0];
            if (failure?.session) {
                const session = new Session(this.rpcClient, failure.session, this.#authToken, this.gatewayAddress, this.sshOptions);
                throw new errors_js_1.TemplateRuntimeFailedError("template runtime failed", session, { cause: safe });
            }
            throw safe;
        }
    }
    /**
     * 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.
     */
    async refreshSecrets() {
        try {
            const response = await this.rpcClient.refreshSessionSecrets((0, protobuf_1.create)(sandbox_pb_js_1.RefreshSessionSecretsRequestSchema, { sessionId: this.id }));
            return {
                changed: response.changed,
                workflowId: response.workflowId,
                versions: response.versions.map((version) => ({
                    secretName: version.secretName,
                    version: version.version,
                    environmentKey: version.environmentKey,
                    filePath: version.filePath,
                })),
            };
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
    }
    async updateTags(tags) {
        await this.update({ tags });
    }
    async update(options) {
        (0, options_js_1.validateUpdateMaxDurationMs)(options.maxDurationMs, options.sticky);
        const updateReq = { sessionId: this.id };
        if (options.name !== undefined)
            updateReq.name = options.name;
        if (options.tags !== undefined) {
            const normalized = normalizeTags(options.tags);
            if (normalized.length === 0) {
                updateReq.clearTags = true;
            }
            else {
                updateReq.tags = normalized;
            }
        }
        if (options.sticky !== undefined)
            updateReq.sticky = options.sticky;
        if (options.maxDurationMs !== undefined) {
            updateReq.maxDuration = (0, wkt_1.durationFromMs)(options.maxDurationMs);
        }
        let resp;
        try {
            resp = await this.rpcClient.updateSession((0, protobuf_1.create)(sandbox_pb_js_1.UpdateSessionRequestSchema, updateReq));
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
        if (resp.session)
            this.applyProto(resp.session);
        const warnings = (0, warning_js_1.sandboxWarningsFromProto)(resp.warnings);
        this.warnings.splice(0, this.warnings.length, ...warnings);
        (0, warning_js_1.emitWarnings)(this.warningHandler, warnings);
    }
    async attachVolume(volumeId, mountPath, options) {
        try {
            const resp = await this.rpcClient.attachVolume((0, protobuf_1.create)(sandbox_pb_js_1.AttachVolumeRequestSchema, {
                sessionId: this.id,
                volume: (0, protobuf_1.create)(sandbox_pb_js_1.VolumeMountSchema, {
                    volumeId,
                    mountPath,
                    readonly: options?.readOnly ?? false,
                }),
            }));
            if (resp.attachment) {
                this.volumeMounts.push({
                    volumeId: resp.attachment.volumeId,
                    mountPath: resp.attachment.mountPath,
                    readOnly: resp.attachment.readonly,
                    state: resp.attachment.state,
                });
            }
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
    }
    async detachVolume(volumeId, options) {
        try {
            await this.rpcClient.detachVolume((0, protobuf_1.create)(sandbox_pb_js_1.DetachVolumeRequestSchema, {
                sessionId: this.id,
                volumeId,
                forceDetach: options?.force ?? false,
            }));
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
        const waitTimeout = options?.waitTimeoutMs ?? constants_js_1.DEFAULT_VOLUME_DETACH_TIMEOUT_MS;
        if (waitTimeout > 0) {
            const deadline = Date.now() + waitTimeout;
            let attempt = 0;
            while (Date.now() < deadline) {
                options?.signal?.throwIfAborted();
                await this.refresh();
                if (this.isVolumeDetached(volumeId))
                    break;
                await sleep((0, constants_js_1.pollBackoffMs)(attempt), options?.signal);
                attempt++;
            }
        }
        this.volumeMounts = this.volumeMounts.filter((v) => v.volumeId !== volumeId);
    }
    async listStorageMounts() {
        try {
            const response = await this.rpcClient.listStorageMounts((0, protobuf_1.create)(sandbox_pb_js_1.ListStorageMountsRequestSchema, { sessionId: this.id }));
            return (response.mounts ?? []).map(storage_js_1.storageMountFromProto);
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
    }
    async attachStorageMount(mount) {
        try {
            const response = await this.rpcClient.attachStorageMount((0, protobuf_1.create)(sandbox_pb_js_1.AttachStorageMountRequestSchema, {
                sessionId: this.id,
                mount: (0, storage_js_1.storageMountSpecToProto)(mount),
            }));
            return (0, storage_js_1.storageMountFromProto)(response.mount);
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
    }
    async detachStorageMount(mountId) {
        try {
            await this.rpcClient.detachStorageMount((0, protobuf_1.create)(sandbox_pb_js_1.DetachStorageMountRequestSchema, { sessionId: this.id, mountId }));
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
    }
    isVolumeDetached(volumeId) {
        const attachments = this.volumeMounts.filter((mount) => mount.volumeId === volumeId);
        return attachments.length === 0 || attachments.every((attachment) => attachment.state === "DETACHED");
    }
    /** @deprecated Use `session.git.clone`, `checkout`, `diff` or `log`. */
    async gitOperation(operation, args) {
        try {
            const resp = await this.rpcClient.gitOperation((0, protobuf_1.create)(sandbox_pb_js_1.GitOperationRequestSchema, {
                sessionId: this.id,
                operation,
                args,
            }));
            return resp.output;
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
    }
    async ssh(signal) {
        return (0, ssh_js_1.connectSSH)(this.gatewayAddress, this.id, this.#authToken, this.sshOptions);
    }
    /** Pauses the sandbox. Its paused state is deleted, even for sticky sandboxes, at `pauseExpiresAt`; take a snapshot while it runs to keep it longer. */
    async pause() {
        // Submit asynchronously so a slow pause cannot outlive a gateway timeout.
        await this.pauseAsync();
        if (this.state !== "PAUSED")
            await this.waitPaused();
    }
    async pauseAsync() {
        try {
            const resp = await this.rpcClient.pauseSession((0, protobuf_1.create)(sandbox_pb_js_1.PauseSessionRequestSchema, { sessionId: this.id, async: true }));
            if (resp.session)
                this.applyProto(resp.session);
            this.resetDataPlane();
        }
        catch (err) {
            throw (0, errors_js_1.mapError)(err);
        }
    }
    /**
     * 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.
     */
    async resume() {
        return this.resumeWithAsync(false);
    }
    /** Resolve once the resume is accepted; call waitResumed to observe RUNNING. */
    async resumeAsync() {
        return this.resumeWithAsync(true);
    }
    async resumeWithAsync(async) {
        const deadline = Date.now() + RESUME_RETRY_BUDGET_MS;
        let backoff = RESUME_RETRY_INITIAL_BACKOFF_MS;
        for (;;) {
            try {
                const resp = await this.rpcClient.resumeSession((0, protobuf_1.create)(sandbox_pb_js_1.ResumeSessionRequestSchema, { sessionId: this.id, async }));
                if (resp.session)
                    this.applyProto(resp.session);
                this.resetDataPlane();
                return;
            }
            catch (err) {
                // The deadline ends the wait for RUNNING, not necessarily the resume.
                if (!async && err instanceof connect_1.ConnectError && err.code === connect_1.Code.DeadlineExceeded) {
                    throw new errors_js_1.ResumeWaitTimeoutError(`session ${this.id} did not resume before the deadline; it may still be resuming, call waitResumed to keep waiting`, { cause: err });
                }
                const mapped = (0, errors_js_1.mapError)(err);
                const remaining = deadline - Date.now();
                if (!(mapped instanceof errors_js_1.UnavailableError) || remaining <= 0)
                    throw mapped;
                await sleep(Math.min(backoff, remaining));
                backoff = Math.min(backoff * 2, RESUME_RETRY_MAX_BACKOFF_MS);
            }
        }
    }
    /**
     * 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.
     */
    async fork(options) {
        const req = (0, protobuf_1.create)(sandbox_pb_js_1.ForkSessionRequestSchema, {
            sessionId: this.id,
            count: options?.count ?? 0,
            namePrefix: options?.namePrefix ?? "",
            wait: options?.wait ?? false,
        });
        try {
            const resp = await this.rpcClient.forkSession(req);
            return resp.sessions.map((proto) => this.forkChild(proto));
        }
        catch (err) {
            const mapped = (0, errors_js_1.mapError)(err);
            const partial = connect_1.ConnectError.from(err).findDetails(sandbox_pb_js_1.ForkSessionResponseSchema)[0];
            if (!partial)
                throw mapped;
            const children = partial.sessions.map((proto) => this.forkChild(proto));
            throw new errors_js_1.ForkFailedError(mapped.message, partial.snapshotId, children, { cause: mapped });
        }
    }
    forkChild(proto) {
        return new Session(this.rpcClient, proto, this.#authToken, this.gatewayAddress, this.sshOptions, this.dataPlaneReadyTimeoutMs, undefined, [], this.warningHandler);
    }
    async [Symbol.asyncDispose]() {
        if (this.released)
            return;
        await this.closeIfOpen();
    }
}
exports.Session = Session;
function sessionStateFromProto(state) {
    switch (state) {
        case sandbox_pb_js_1.SessionState.CREATING:
            return "CREATING";
        case sandbox_pb_js_1.SessionState.RUNNING:
            return "RUNNING";
        case sandbox_pb_js_1.SessionState.PAUSED:
            return "PAUSED";
        case sandbox_pb_js_1.SessionState.USER_SHUTDOWN:
            return "USER_SHUTDOWN";
        case sandbox_pb_js_1.SessionState.PAUSING:
            return "PAUSING";
        case sandbox_pb_js_1.SessionState.RESUMING:
            return "RESUMING";
        case sandbox_pb_js_1.SessionState.TERMINATING:
            return "TERMINATING";
        case sandbox_pb_js_1.SessionState.TERMINATED:
            return "TERMINATED";
        default:
            return "UNSPECIFIED";
    }
}
// Unset maps to "UNSPECIFIED" rather than undefined so the same response
// produces the same value in every SDK — Go and Python both report UNSPECIFIED
// for an omitted status.
function wildcardStatusFromProto(status) {
    switch (status) {
        case sandbox_pb_js_1.WildcardStatus.PENDING:
            return "PENDING";
        case sandbox_pb_js_1.WildcardStatus.READY:
            return "READY";
        case sandbox_pb_js_1.WildcardStatus.FAILED:
            return "FAILED";
        case sandbox_pb_js_1.WildcardStatus.DISABLED:
            return "DISABLED";
        default:
            return "UNSPECIFIED";
    }
}
function networkModeFromProto(mode) {
    switch (mode) {
        case sandbox_pb_js_1.SessionNetworkMode.FULL:
            return "FULL";
        case sandbox_pb_js_1.SessionNetworkMode.RESTRICTED:
            return "RESTRICTED";
        default:
            return "UNSPECIFIED";
    }
}
function networkRestrictionReasonFromProto(reason) {
    return reason === sandbox_pb_js_1.SessionNetworkRestrictionReason.NEVER_PURCHASED ? "NEVER_PURCHASED" : "UNSPECIFIED";
}
function templateRuntimeStateFromProto(state) {
    switch (state) {
        case template_pb_js_1.TemplateRuntimeState.STARTING:
            return "STARTING";
        case template_pb_js_1.TemplateRuntimeState.READY:
            return "READY";
        case template_pb_js_1.TemplateRuntimeState.FAILED:
            return "FAILED";
        case template_pb_js_1.TemplateRuntimeState.STOPPED:
            return "STOPPED";
        default:
            return "UNSPECIFIED";
    }
}
/** Returns true if the session can accept commands. */
function isReady(state) {
    return state === "RUNNING";
}
function isTerminal(state) {
    return state === "TERMINATED" || state === "TERMINATING";
}
function streamFromRunHandle(sessionId, command, args, proc, maxOutputBytes) {
    const controller = new AbortController();
    const stream = new stream_js_1.Stream(controller);
    const stdoutCap = new OutputCap(maxOutputBytes);
    const stderrCap = new OutputCap(maxOutputBytes);
    const stdoutChunks = [];
    const stderrChunks = [];
    const pumps = Promise.all([
        pumpRunReadable(stream, proc.stdout, false, stdoutCap, stdoutChunks),
        pumpRunReadable(stream, proc.stderr, true, stderrCap, stderrChunks),
    ]);
    void (async () => {
        try {
            const [result] = await Promise.all([proc, pumps]);
            stream.finish({
                sessionId,
                command,
                args,
                status: commandStatusFromResult(result),
                exitCode: result.exitCode,
                durationMs: result.durationMs ?? 0,
                reason: result.reason,
                disk: result.disk,
                outputs: [],
                stdout: concatUint8Arrays(stdoutChunks),
                stderr: concatUint8Arrays(stderrChunks),
                stdoutTruncated: stdoutCap.truncated,
                stderrTruncated: stderrCap.truncated,
            });
        }
        catch (err) {
            stream.fail(err);
        }
    })();
    controller.signal.addEventListener("abort", () => {
        void proc.kill();
    });
    return stream;
}
/** Pushes every chunk to `stream` and keeps what fits under `cap` in `retained`. */
async function pumpRunReadable(stream, readable, isStderr, cap, retained) {
    const reader = readable.getReader();
    for (;;) {
        const { done, value } = await reader.read();
        if (done)
            return;
        stream.push({ data: value, isStderr, isFinal: false });
        const kept = cap.retain(value);
        if (kept)
            retained.push(kept);
    }
}
async function* streamReadableOutputs(readable, isStderr) {
    const reader = readable.getReader();
    try {
        for (;;) {
            const { done, value } = await reader.read();
            if (done)
                return;
            yield { data: value, isStderr, isFinal: false };
        }
    }
    finally {
        reader.releaseLock();
    }
}
/** Collects one stream, retaining at most `maxBytes` (0 = unlimited); resolves true if bytes were dropped. */
async function collectReadableOutputs(readable, isStderr, chunks, outputs, maxBytes, onOutput) {
    const cap = new OutputCap(maxBytes);
    try {
        for await (const output of streamReadableOutputs(readable, isStderr)) {
            onOutput?.(output);
            const data = cap.retain(output.data);
            if (!data)
                continue;
            const kept = data === output.data ? output : { ...output, data };
            outputs.push(kept);
            chunks.push(new Uint8Array(kept.data));
        }
    }
    catch (err) {
        // Cancel so a stream-only run never stalls on output nobody will read.
        void readable.cancel(err).catch(() => { });
        throw err;
    }
    return cap.truncated;
}
/** OutputCap retains the first `maxBytes` of one output stream (0 = unlimited) and records any drop. */
class OutputCap {
    maxBytes;
    truncated = false;
    retained = 0;
    constructor(maxBytes) {
        this.maxBytes = maxBytes;
    }
    /** Returns the part of `data` that still fits, or undefined once the cap is full. */
    retain(data) {
        if (this.maxBytes <= 0)
            return data;
        const room = this.maxBytes - this.retained;
        if (data.byteLength <= room) {
            this.retained += data.byteLength;
            return data;
        }
        this.truncated = true;
        if (room <= 0)
            return undefined;
        this.retained = this.maxBytes;
        // slice copies, so the retained bytes do not pin the whole chunk.
        return data.slice(0, room);
    }
}
/** Returns the validated `maxOutputBytes`, 0 when unset. */
function maxOutputBytesFrom(options) {
    const maxOutputBytes = options?.maxOutputBytes ?? 0;
    if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 0) {
        throw new errors_js_1.InvalidArgumentError(`maxOutputBytes must be a non-negative integer, got ${maxOutputBytes}`);
    }
    return maxOutputBytes;
}
/** A timed-out run can arrive as exitCode 0, so timedOut outranks the exit code. */
function commandStatusFromResult(result) {
    if (result.timedOut)
        return "TIMED_OUT";
    return result.exitCode === 0 && !result.signal ? "SUCCEEDED" : "FAILED";
}
function concatUint8Arrays(arrays) {
    if (arrays.length === 0)
        return new Uint8Array();
    if (arrays.length === 1)
        return arrays[0];
    const totalLength = arrays.reduce((sum, a) => sum + a.length, 0);
    const result = new Uint8Array(totalLength);
    let offset = 0;
    for (const a of arrays) {
        result.set(a, offset);
        offset += a.length;
    }
    return result;
}
function normalizeTags(tags) {
    return tags.map((tag) => tag.trim().toLowerCase()).filter((tag) => tag.length > 0);
}
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 });
    });
}
//# sourceMappingURL=session.js.map