Skip to content

Secure, Fast, and Extensible Sandbox runtime for AI agents.

40.5 KB
Raw Blame
// Copyright 2026 The OpenSandbox Authors
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import {
  DEFAULT_ENTRYPOINT,
  DEFAULT_EGRESS_PORT,
  DEFAULT_EXECD_PORT,
  DEFAULT_HEALTH_CHECK_POLLING_INTERVAL_MILLIS,
  DEFAULT_READY_TIMEOUT_SECONDS,
  DEFAULT_RESOURCE_LIMITS,
  DEFAULT_TIMEOUT_SECONDS,
} from "./core/constants.js";
import { ConnectionConfig, type ConnectionConfigOptions } from "./config/connection.js";
import { reportSandboxCreateMetric } from "./internal/lifecycleMetrics.js";
import type { SandboxFiles } from "./services/filesystem.js";
import type { CredentialVault, Egress } from "./services/egress.js";
import { createDefaultAdapterFactory } from "./factory/defaultAdapterFactory.js";
import type { AdapterFactory } from "./factory/adapterFactory.js";
import type { Diagnostics } from "./services/diagnostics.js";
import type { DiagnosticContext, DiagnosticContent } from "./models/diagnostics.js";
import { requireDiagnostics } from "./adapters/diagnosticsAdapter.js";

import type { Sandboxes } from "./services/sandboxes.js";
import type { ExecdCommands } from "./services/execdCommands.js";
import type { ExecdHealth } from "./services/execdHealth.js";
import type { ExecdMetrics } from "./services/execdMetrics.js";
import type { IsolationService, IsolationSession } from "./services/isolatedSessions.js";
import type { CommandExecution } from "./models/execd.js";
import type { IsolatedCapabilities, IsolatedSessionSummary } from "./models/isolated.js";
import type {
  CreateSandboxFromTemplateRequest,
  CreateSandboxRequest,
  CredentialProxyConfig,
  Endpoint,
  IdlePolicy,
  NetworkPolicy,
  NetworkRule,
  PlatformSpec,
  RenewSandboxExpirationResponse,
  SandboxId,
  SandboxInfo,
  SandboxLifecycle,
  SandboxMetadataPatch,
  Volume,
} from "./models/sandboxes.js";
import { SandboxOrigin } from "./models/sandboxes.js";
import { ReadinessBudget, validatePollingInterval } from "./internal/readiness.js";
import { validateIdlePolicy } from "./internal/idlePolicy.js";
import { validateRenewalPolicy } from "./internal/renewalPolicy.js";

const HOST_PATH_PATTERN = /^([/]|[A-Za-z]:[\\/])/;

const TEMPLATE_CREDENTIAL_VAULT_UNAVAILABLE =
  "Credential Vault is not available: the adapter factory's network policy stack does not provide credentialVault for template-backed sandboxes.";

const unavailableIsolation: IsolationService = {
  create(): Promise<IsolationSession> {
    throw new Error("Isolation is not available: the adapter factory did not provide an IsolationService");
  },
  attach(): Promise<IsolationSession> {
    throw new Error("Isolation is not available: the adapter factory did not provide an IsolationService");
  },
  capabilities(): Promise<IsolatedCapabilities> {
    return Promise.resolve({
      available: false,
      setpriv_available: false,
      userns_available: false,
      commit_supported: false,
      diff_supported: false,
    });
  },
  list(): Promise<IsolatedSessionSummary[]> {
    throw new Error("Isolation is not available: the adapter factory did not provide an IsolationService");
  },
  runOnce(): Promise<CommandExecution> {
    throw new Error("Isolation is not available: the adapter factory did not provide an IsolationService");
  },
  withSession<T>(): Promise<T> {
    throw new Error("Isolation is not available: the adapter factory did not provide an IsolationService");
  },
};
const CREDENTIAL_VAULT_METHODS = [
  "create",
  "get",
  "patch",
  "delete",
  "listCredentials",
  "getCredential",
  "listBindings",
  "getBinding",
] as const;

function isCredentialVault(value: unknown): value is CredentialVault {
  if (typeof value !== "object" || value == null) {
    return false;
  }
  const candidate = value as Record<string, unknown>;
  return CREDENTIAL_VAULT_METHODS.every(
    (method) => typeof candidate[method] === "function"
  );
}

function unavailableCredentialVault(
  message = "Credential Vault is not available for this adapter factory. Provide EgressStack.credentialVault to use Credential Vault with a custom adapter.",
): CredentialVault {
  const fail = async (..._args: unknown[]): Promise<never> => {
    throw new Error(message);
  };
  return {
    create: fail,
    get: fail,
    patch: fail,
    delete: fail,
    listCredentials: fail,
    getCredential: fail,
    listBindings: fail,
    getBinding: fail,
  };
}

export interface SandboxCreateOptions {
  /**
   * Connection configuration for calling the OpenSandbox Lifecycle API and the sandbox's execd API.
   */
  connectionConfig?: ConnectionConfig | ConnectionConfigOptions;
  /**
   * Advanced override: inject a custom adapter factory (custom transports, dependency injection).
   */
  adapterFactory?: AdapterFactory;

  /**
   * Container image uri, e.g. `python:3.11`
   */
  image?:
    | string
    | { uri: string; auth?: { username: string; password: string } };
  /**
   * Snapshot identifier to restore from.
   * Mutually exclusive with `image`.
   */
  snapshotId?: string;

  /**
   * Entrypoint command for the sandbox (defaults to tail -f /dev/null).
   */
  entrypoint?: string[];
  /**
   * Environment variables to inject into the sandbox runtime.
   */
  env?: Record<string, string>;
  /**
   * Custom metadata tags (used for filtering/management).
   */
  metadata?: Record<string, string>;
  /**
   * Optional outbound network policy for the sandbox.
   * If provided without defaultAction, defaults to "deny".
   */
  networkPolicy?: NetworkPolicy;
  /**
   * Optional Credential Vault proxy startup settings.
   *
   * Set `enabled: true` to opt into transparent MITM support used by credential injection.
   */
  credentialProxy?: CredentialProxyConfig;
  /**
   * Optional list of volume mounts for persistent storage.
   * Each volume specifies a backend (host path, PVC, or OSSFS) and mount configuration.
   */
  volumes?: Volume[];
  /**
   * Opaque extension parameters passed through to the server as-is.
   */
  extensions?: Record<string, string>;
  /**
   * Optional declarative lifecycle hooks executed inside the sandbox.
   */
  lifecycle?: SandboxLifecycle;
  /**
   * Optional runtime platform constraint used for provisioning.
   */
  platform?: PlatformSpec;
  /**
   * Whether to enable secured access for sandbox endpoints.
   */
  secureAccess?: boolean;

  /**
   * Resource limits applied to the sandbox container.
   *
   * This is forwarded to the Lifecycle API as `resourceLimits`.
   */
  resource?: Record<string, string>;
  /**
   * Resource requests (guaranteed minimums) for the sandbox container.
   * When set, enables Kubernetes Burstable QoS (requests < limits).
   * Only meaningful for Kubernetes runtimes.
   */
  resourceRequests?: Record<string, string>;
  /**
   * Sandbox timeout in seconds. Set to `null` to require explicit cleanup.
   */
  timeoutSeconds?: number | null;
  /**
   * Optional signal used to cancel creation and readiness requests.
   */
  signal?: AbortSignal;

  /**
   * Skip readiness checks during create/connect.
   *
   * When true, the SDK will not wait for lifecycle state `Running` or perform the health check.
   * The returned sandbox instance may not be ready yet.
   */
  skipHealthCheck?: boolean;
  /**
   * Optional custom readiness check used by {@link Sandbox.waitUntilReady}.
   * Custom checks are not cancelled on timeout.
   *
   * If provided, the SDK will call this function during readiness checks instead of
   * using the default `execd` ping check.
   */
  healthCheck?: (sbx: Sandbox) => boolean | Promise<boolean>;
  readyTimeoutSeconds?: number;
  healthCheckPollingInterval?: number;
}

export interface SandboxConnectOptions {
  /**
   * Connection configuration for calling the OpenSandbox APIs.
   */
  connectionConfig?: ConnectionConfig | ConnectionConfigOptions;
  /**
   * Declare that the SDK owns (and may close) the connection config's
   * transport on cleanup paths. Set when the config's transport was
   * allocated for this connect (e.g. `sandbox.resume()`), or to transfer
   * ownership of a caller-initialized config.
   */
  ownsTransport?: boolean;
  /**
   * Advanced override: inject a custom adapter factory (custom transports, dependency injection).
   */
  adapterFactory?: AdapterFactory;
  /**
   * ID of the existing sandbox to connect to.
   */
  sandboxId: SandboxId;

  /**
   * Skip health checks after connecting; required endpoints are still resolved.
   */
  skipHealthCheck?: boolean;
  /**
   * Optional custom readiness check used by {@link Sandbox.waitUntilReady}.
   * Custom checks are not cancelled on timeout.
   */
  healthCheck?: (sbx: Sandbox) => boolean | Promise<boolean>;
  /**
   * Total budget for endpoint publication and health checks.
   * Custom checks and adapters must not block the event loop.
   */
  readyTimeoutSeconds?: number;
  /**
   * Polling interval for endpoint publication and health checks (milliseconds).
   */
  healthCheckPollingInterval?: number;
  /**
   * Optional signal used to cancel connection and readiness requests.
   */
  signal?: AbortSignal;
}

export interface SandboxCreateFromTemplateOptions {
  /**
   * Connection configuration for calling the OpenSandbox Lifecycle API and the sandbox's execd API.
   */
  connectionConfig?: ConnectionConfig | ConnectionConfigOptions;
  /**
   * Advanced override: inject a custom adapter factory (custom transports, dependency injection).
   */
  adapterFactory?: AdapterFactory;
  /**
   * ID of a `Succeeded` fsb template (see {@link SandboxManager.createTemplate}).
   */
  templateId: string;
  /**
   * Sandbox timeout in seconds (server semantics). Required in template mode.
   */
  timeoutSeconds: number;
  /**
   * Custom metadata tags (used for filtering/management).
   */
  metadata?: Record<string, string>;
  /**
   * Optional outbound network policy for the sandbox.
   * If provided without defaultAction, defaults to "deny".
   */
  networkPolicy?: NetworkPolicy;
  /**
   * Opaque extension parameters passed through to the server as-is.
   * Prefer namespaced keys (e.g. `storage.id`).
   */
  extensions?: Record<string, string>;
  /**
   * Optional idle behavior (OSEP-0024, fast-sandbox only). Control-plane
   * state, not workload shape, so template mode accepts it.
   */
  idlePolicy?: IdlePolicy;
  /**
   * Optional signal used to cancel creation and readiness requests.
   */
  signal?: AbortSignal;
  /**
   * Skip readiness checks during create.
   *
   * When true, the SDK will not wait for lifecycle state `Running` or perform the health check.
   * The returned sandbox instance may not be ready yet.
   */
  skipHealthCheck?: boolean;
  /**
   * Optional custom readiness check used by {@link Sandbox.waitUntilReady}.
   * Custom checks are not cancelled on timeout.
   *
   * If provided, the SDK will call this function during readiness checks instead of
   * using the default `execd` ping check.
   */
  healthCheck?: (sbx: Sandbox) => boolean | Promise<boolean>;
  readyTimeoutSeconds?: number;
  healthCheckPollingInterval?: number;
}

function throwIfAborted(signal?: AbortSignal): void {
  signal?.throwIfAborted();
}


function toImageSpec(
  image: NonNullable<SandboxCreateOptions["image"]>
): NonNullable<CreateSandboxRequest["image"]> {
  if (typeof image === "string") return { uri: image };
  return { uri: image.uri, auth: image.auth };
}

/**
 * Resolve the egress stack for a sandbox.
 *
 * Template-backed sandboxes (origin `template`) have no sandbox-side egress
 * sidecar: policy operations go through the lifecycle control plane, and the
 * egress sidecar endpoint is never resolved. For any other origin the
 * sandbox-side egress sidecar endpoint is resolved and used; when a
 * `ReadinessBudget` is supplied (connect/resume), the lookup shares the execd
 * endpoint's budget so transient failures are retried within the remaining
 * `readyTimeoutSeconds`.
 */
async function resolveEgressStack(
  adapterFactory: AdapterFactory,
  sandboxes: Sandboxes,
  connectionConfig: ConnectionConfig,
  lifecycleBaseUrl: string,
  sandboxId: SandboxId,
  endpointOrigin: string | undefined,
  budget?: ReadinessBudget,
  interval?: number,
  signal?: AbortSignal,
): Promise<{ egress: Egress; credentialVault?: CredentialVault; origin: SandboxOrigin }> {
  if (endpointOrigin === SandboxOrigin.TEMPLATE) {
    const stack = adapterFactory.createNetworkPolicyStack?.({
      connectionConfig,
      lifecycleBaseUrl,
      sandboxId,
    });
    if (!stack) {
      throw new Error(
        "The sandbox is template-backed but the adapter factory does not provide createNetworkPolicyStack; cannot route egress policy operations."
      );
    }
    return {
      egress: stack.egress,
      credentialVault:
        stack.credentialVault ??
        unavailableCredentialVault(TEMPLATE_CREDENTIAL_VAULT_UNAVAILABLE),
      origin: SandboxOrigin.TEMPLATE,
    };
  }
  const fetchEgressEndpoint = (fetchSignal?: AbortSignal) => sandboxes.getSandboxEndpoint(
    sandboxId,
    DEFAULT_EGRESS_PORT,
    connectionConfig.useServerProxy,
    fetchSignal,
  );
  const egressEndpoint = budget && interval !== undefined
    ? await budget.endpoint(fetchEgressEndpoint, interval)
    : await fetchEgressEndpoint(signal);
  const stack = adapterFactory.createEgressStack({
    connectionConfig,
    egressBaseUrl: `${connectionConfig.protocol}://${egressEndpoint.endpoint}`,
    endpointHeaders: egressEndpoint.headers,
  });
  return {
    egress: stack.egress,
    credentialVault: stack.credentialVault,
    origin: SandboxOrigin.UNKNOWN,
  };
}

export class Sandbox {
  readonly id: SandboxId;
  readonly connectionConfig: ConnectionConfig;
  /**
   * Origin of this sandbox (see {@link SandboxOrigin}).
   *
   * `template` when the sandbox runs on a fsb golden-image template: set
   * locally by {@link Sandbox.createFromTemplate}, and reported by the
   * server's `OPEN-SANDBOX-ORIGIN` response header otherwise (also honored
   * for snapshot restores, which boot the template's published artifact set).
   * `unknown` for everything else.
   *
   * Template-backed sandboxes route egress policy operations through the
   * lifecycle control plane (`/sandboxes/{sandboxId}/networkpolicy`) instead
   * of the sandbox-side egress sidecar.
   */
  readonly origin: string;

  /**
   * Lifecycle (sandbox management) service.
   */
  readonly sandboxes: Sandboxes;

  /**
   * Execd services.
   */
  readonly commands: ExecdCommands;
  /**
   * High-level filesystem facade (JS-friendly).
   */
  readonly files: SandboxFiles;
  readonly health: ExecdHealth;
  readonly metrics: ExecdMetrics;
  readonly isolation: IsolationService;
  /**
   * Sandbox-scoped Credential Vault operations.
   */
  readonly credentialVault: CredentialVault;

  /**
   * Internal state kept out of the public instance shape.
   *
   * This avoids nominal typing issues when multiple copies of the SDK exist in a dependency graph.
   */
  private static readonly _priv = new WeakMap<
    Sandbox,
    {
      adapterFactory: AdapterFactory;
      lifecycleBaseUrl: string;
      execdBaseUrl: string;
      egress: Egress;
      ownsTransport: boolean;
      diagnostics?: Diagnostics;
    }
  >();

  /**
   * Return an independent filesystem client using explicit Linux credentials.
   * Requires identity-aware Execd; unsupported servers never trigger fallback.
   */
  filesWithIdentity(uid: number, gid: number): SandboxFiles {
    if (typeof this.files.withIdentity !== "function") {
      throw new Error("The selected filesystem adapter does not support execution identity");
    }
    return this.files.withIdentity(uid, gid);
  }

  private constructor(opts: {
    id: SandboxId;
    connectionConfig: ConnectionConfig;
    adapterFactory: AdapterFactory;
    ownsTransport: boolean;
    lifecycleBaseUrl: string;
    execdBaseUrl: string;
    sandboxes: Sandboxes;
    diagnostics?: Diagnostics;
    commands: ExecdCommands;
    files: SandboxFiles;
    health: ExecdHealth;
    metrics: ExecdMetrics;
    isolation: IsolationService;
    egress: Egress;
    credentialVault?: CredentialVault;
    origin?: string;
  }) {
    this.id = opts.id;
    this.connectionConfig = opts.connectionConfig;
    const credentialVault =
      opts.credentialVault ??
      (isCredentialVault(opts.egress)
        ? opts.egress
        : unavailableCredentialVault());

    Sandbox._priv.set(this, {
      adapterFactory: opts.adapterFactory,
      lifecycleBaseUrl: opts.lifecycleBaseUrl,
      execdBaseUrl: opts.execdBaseUrl,
      egress: opts.egress,
      ownsTransport: opts.ownsTransport,
      diagnostics: opts.diagnostics,
    });

    this.origin = opts.origin ?? SandboxOrigin.UNKNOWN;
    this.sandboxes = opts.sandboxes;
    this.commands = opts.commands;
    this.files = opts.files;
    this.health = opts.health;
    this.metrics = opts.metrics;
    this.isolation = opts.isolation;
    this.credentialVault = credentialVault;
  }

  static async create(opts: SandboxCreateOptions): Promise<Sandbox> {
    if ((opts.image == null) === (opts.snapshotId == null)) {
      throw new Error("Exactly one of image or snapshotId must be provided");
    }
    if (!(opts.skipHealthCheck ?? false) && opts.healthCheckPollingInterval !== undefined) {
      validatePollingInterval(opts.healthCheckPollingInterval);
    }
    if (opts.lifecycle?.idlePolicy) {
      validateIdlePolicy(opts.lifecycle.idlePolicy);
    }
    if (opts.lifecycle?.renewalPolicy) {
      validateRenewalPolicy(opts.lifecycle.renewalPolicy);
    }

    // Validate volumes before allocating transport resources.
    if (opts.volumes) {
      for (const vol of opts.volumes) {
        const backendsSpecified = [vol.host, vol.pvc, vol.ossfs].filter((b) => b != null).length;
        if (backendsSpecified === 0) {
          throw new Error(
            `Volume '${vol.name}' must specify exactly one backend (host, pvc, ossfs), but none was provided.`
          );
        }
        if (backendsSpecified > 1) {
          throw new Error(
            `Volume '${vol.name}' must specify exactly one backend (host, pvc, ossfs), but multiple were provided.`
          );
        }
        if (vol.host && !HOST_PATH_PATTERN.test(vol.host.path)) {
          throw new Error(
            "Host path must be an absolute path starting with '/' or a Windows drive letter (e.g. 'C:\\' or 'D:/')"
          );
        }
      }
    }
    throwIfAborted(opts.signal);

    const baseConnectionConfig =
      opts.connectionConfig instanceof ConnectionConfig
        ? opts.connectionConfig
        : new ConnectionConfig(opts.connectionConfig);
    const connectionConfig = baseConnectionConfig.withTransportIfMissing();
    const lifecycleBaseUrl = connectionConfig.getBaseUrl();
    const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();

    let sandboxes: Sandboxes;
    let diagnostics: Diagnostics | undefined;
    try {
      ({ sandboxes, diagnostics } = adapterFactory.createLifecycleStack({
        connectionConfig,
        lifecycleBaseUrl,
      }));
    } catch (err) {
      if (connectionConfig !== baseConnectionConfig) {
        await connectionConfig.closeTransport();
      }
      throw err;
    }

    const rawTimeout = opts.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;
    const timeoutSeconds =
      opts.timeoutSeconds === null
        ? null
        : Math.floor(rawTimeout);
    if (timeoutSeconds !== null && !Number.isFinite(timeoutSeconds)) {
      throw new Error(
        `timeoutSeconds must be a finite number, got ${opts.timeoutSeconds}`
      );
    }

    const req: CreateSandboxRequest = {
      image: opts.image == null ? undefined : toImageSpec(opts.image),
      snapshotId: opts.snapshotId,
      entrypoint: opts.entrypoint ?? DEFAULT_ENTRYPOINT,
      resourceLimits: opts.resource ?? DEFAULT_RESOURCE_LIMITS,
      resourceRequests: opts.resourceRequests,
      secureAccess: opts.secureAccess ?? false,
      env: opts.env ?? {},
      metadata: opts.metadata ?? {},
      networkPolicy: opts.networkPolicy
        ? {
            ...opts.networkPolicy,
            defaultAction: opts.networkPolicy.defaultAction ?? "deny",
          }
        : undefined,
      credentialProxy: opts.credentialProxy,
      volumes: opts.volumes,
      extensions: opts.extensions ?? {},
      lifecycle: opts.lifecycle,
      platform: opts.platform,
    };
    if (timeoutSeconds !== null) {
      req.timeout = timeoutSeconds;
    }

    let sandboxId: SandboxId | undefined;
    const startupSource =
      typeof opts.image === "string"
        ? opts.image
        : opts.image?.uri ?? opts.snapshotId;
    const createStarted = Date.now();
    try {
      const created = await sandboxes.createSandbox(req, opts.signal);
      sandboxId = created.id as SandboxId;

      const endpoint = await sandboxes.getSandboxEndpoint(
        sandboxId,
        DEFAULT_EXECD_PORT,
        connectionConfig.useServerProxy,
        opts.signal,
      );
      const execdBaseUrl = `${connectionConfig.protocol}://${endpoint.endpoint}`;

      // The server is authoritative about the runtime backing: for fsb
      // template-backed sandboxes (including snapshot restores of a template)
      // it reports origin `template` and there is no sidecar endpoint, so the
      // egress stack is routed through the lifecycle control plane.
      const egressStack = await resolveEgressStack(
        adapterFactory,
        sandboxes,
        connectionConfig,
        lifecycleBaseUrl,
        sandboxId,
        endpoint.origin,
        undefined,
        undefined,
        opts.signal,
      );

      const execdStack =
        adapterFactory.createExecdStack({
          connectionConfig,
          execdBaseUrl,
          endpointHeaders: endpoint.headers,
        });

      const { commands, files, health, metrics, isolation } = execdStack;

      const sbx = new Sandbox({
        id: sandboxId,
        connectionConfig,
        adapterFactory,
        ownsTransport: connectionConfig !== baseConnectionConfig,
        lifecycleBaseUrl,
        execdBaseUrl,
        sandboxes,
        diagnostics,
        commands,
        files,
        health,
        metrics,
        isolation: isolation ?? unavailableIsolation,
        egress: egressStack.egress,
        credentialVault: egressStack.credentialVault,
        origin: egressStack.origin,
      });

      if (!(opts.skipHealthCheck ?? false)) {
        await sbx.waitUntilReady({
          readyTimeoutSeconds:
            opts.readyTimeoutSeconds ?? DEFAULT_READY_TIMEOUT_SECONDS,
          pollingIntervalMillis:
            opts.healthCheckPollingInterval ??
            DEFAULT_HEALTH_CHECK_POLLING_INTERVAL_MILLIS,
          healthCheck: opts.healthCheck,
          signal: opts.signal,
        });
      }

      reportSandboxCreateMetric(connectionConfig, {
        sandboxId,
        image: startupSource,
        createDurationMs: Date.now() - createStarted,
        success: true,
      });

      return sbx;
    } catch (err) {
      reportSandboxCreateMetric(connectionConfig, {
        sandboxId,
        image: startupSource,
        createDurationMs: Date.now() - createStarted,
        success: false,
      });
      if (opts.signal?.aborted) {
        void (async () => {
          try {
            if (sandboxId) {
              await sandboxes.deleteSandbox(sandboxId);
            }
          } catch {
            // Preserve the caller's abort error if sandbox cleanup fails.
          } finally {
            if (connectionConfig !== baseConnectionConfig) {
              await connectionConfig.closeTransport().catch(() => undefined);
            }
          }
        })();
        throw err;
      }
      if (sandboxId) {
        try {
          await sandboxes.deleteSandbox(sandboxId);
        } catch {
          // Preserve the original creation error if sandbox cleanup fails.
        }
      }
      if (connectionConfig !== baseConnectionConfig) {
        await connectionConfig.closeTransport();
      }
      throw err;
    }
  }

  /**
   * Create a new sandbox from a `Succeeded` fsb template.
   *
   * Template mode fixes the workload shape on the server: the entrypoint,
   * env, resources, volumes, platform and lifecycle hooks of the sandbox
   * come from the template's golden image and cannot be overridden here.
   * Only metadata, network policy, extensions and the OSEP-0024 idle policy
   * (control-plane state, not workload shape) may accompany the template id,
   * and the timeout is required.
   *
   * The returned sandbox routes egress policy operations and the Credential
   * Vault through the lifecycle control plane: the server relays vault
   * revisions to the egress-held vault over the FastPath handler relay, so
   * the ack is synchronous and credential values never appear on any read
   * (OSEP-0022). A 412 patch failure means another writer won the revision —
   * re-read and retry with the fresh `expectedRevision`.
   */
  static async createFromTemplate(opts: SandboxCreateFromTemplateOptions): Promise<Sandbox> {
    if (!opts.templateId?.trim()) {
      throw new Error("Template ID must be specified");
    }
    if (typeof opts.timeoutSeconds !== "number" || !Number.isFinite(opts.timeoutSeconds)) {
      throw new Error(
        `timeoutSeconds must be a finite number, got ${opts.timeoutSeconds}`
      );
    }
    if (!(opts.skipHealthCheck ?? false) && opts.healthCheckPollingInterval !== undefined) {
      validatePollingInterval(opts.healthCheckPollingInterval);
    }
    if (opts.idlePolicy) {
      validateIdlePolicy(opts.idlePolicy, "idlePolicy");
    }
    throwIfAborted(opts.signal);

    const baseConnectionConfig =
      opts.connectionConfig instanceof ConnectionConfig
        ? opts.connectionConfig
        : new ConnectionConfig(opts.connectionConfig);
    const connectionConfig = baseConnectionConfig.withTransportIfMissing();
    const lifecycleBaseUrl = connectionConfig.getBaseUrl();
    const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();

    let sandboxes: Sandboxes;
    let diagnostics: Diagnostics | undefined;
    try {
      ({ sandboxes, diagnostics } = adapterFactory.createLifecycleStack({
        connectionConfig,
        lifecycleBaseUrl,
      }));
    } catch (err) {
      if (connectionConfig !== baseConnectionConfig) {
        await connectionConfig.closeTransport();
      }
      throw err;
    }

    const req: CreateSandboxFromTemplateRequest = {
      templateId: opts.templateId,
      timeout: Math.floor(opts.timeoutSeconds),
      metadata: opts.metadata ?? {},
      networkPolicy: opts.networkPolicy
        ? {
            ...opts.networkPolicy,
            defaultAction: opts.networkPolicy.defaultAction ?? "deny",
          }
        : undefined,
      extensions: opts.extensions ?? {},
      ...(opts.idlePolicy == null ? {} : { idlePolicy: opts.idlePolicy }),
    };

    let sandboxId: SandboxId | undefined;
    const startupSource = `template:${opts.templateId}`;
    const createStarted = Date.now();
    try {
      const created = await sandboxes.createSandboxFromTemplate(req, opts.signal);
      sandboxId = created.id as SandboxId;

      const endpoint = await sandboxes.getSandboxEndpoint(
        sandboxId,
        DEFAULT_EXECD_PORT,
        connectionConfig.useServerProxy,
        opts.signal,
      );
      const execdBaseUrl = `${connectionConfig.protocol}://${endpoint.endpoint}`;

      // Template-backed sandboxes have no sandbox-side egress sidecar:
      // policy operations go through the lifecycle control plane.
      const egressStack = await resolveEgressStack(
        adapterFactory,
        sandboxes,
        connectionConfig,
        lifecycleBaseUrl,
        sandboxId,
        SandboxOrigin.TEMPLATE,
        undefined,
        undefined,
        opts.signal,
      );

      const execdStack =
        adapterFactory.createExecdStack({
          connectionConfig,
          execdBaseUrl,
          endpointHeaders: endpoint.headers,
        });

      const { commands, files, health, metrics, isolation } = execdStack;

      const sbx = new Sandbox({
        id: sandboxId,
        connectionConfig,
        adapterFactory,
        ownsTransport: connectionConfig !== baseConnectionConfig,
        lifecycleBaseUrl,
        execdBaseUrl,
        sandboxes,
        diagnostics,
        commands,
        files,
        health,
        metrics,
        isolation: isolation ?? unavailableIsolation,
        egress: egressStack.egress,
        credentialVault: egressStack.credentialVault,
        origin: egressStack.origin,
      });

      if (!(opts.skipHealthCheck ?? false)) {
        await sbx.waitUntilReady({
          readyTimeoutSeconds:
            opts.readyTimeoutSeconds ?? DEFAULT_READY_TIMEOUT_SECONDS,
          pollingIntervalMillis:
            opts.healthCheckPollingInterval ??
            DEFAULT_HEALTH_CHECK_POLLING_INTERVAL_MILLIS,
          healthCheck: opts.healthCheck,
          signal: opts.signal,
        });
      }

      reportSandboxCreateMetric(connectionConfig, {
        sandboxId,
        image: startupSource,
        createDurationMs: Date.now() - createStarted,
        success: true,
      });

      return sbx;
    } catch (err) {
      reportSandboxCreateMetric(connectionConfig, {
        sandboxId,
        image: startupSource,
        createDurationMs: Date.now() - createStarted,
        success: false,
      });
      if (opts.signal?.aborted) {
        void (async () => {
          try {
            if (sandboxId) {
              await sandboxes.deleteSandbox(sandboxId);
            }
          } catch {
            // Preserve the caller's abort error if sandbox cleanup fails.
          } finally {
            if (connectionConfig !== baseConnectionConfig) {
              await connectionConfig.closeTransport().catch(() => undefined);
            }
          }
        })();
        throw err;
      }
      if (sandboxId) {
        try {
          await sandboxes.deleteSandbox(sandboxId);
        } catch {
          // Preserve the original creation error if sandbox cleanup fails.
        }
      }
      if (connectionConfig !== baseConnectionConfig) {
        await connectionConfig.closeTransport();
      }
      throw err;
    }
  }

  static async connect(opts: SandboxConnectOptions): Promise<Sandbox> {
    throwIfAborted(opts.signal);
    const interval = opts.healthCheckPollingInterval ?? DEFAULT_HEALTH_CHECK_POLLING_INTERVAL_MILLIS;
    validatePollingInterval(interval);
    const baseConnectionConfig =
      opts.connectionConfig instanceof ConnectionConfig
        ? opts.connectionConfig
        : new ConnectionConfig(opts.connectionConfig);
    const connectionConfig = baseConnectionConfig.withTransportIfMissing();
    // Reference equality can't tell a resume-allocated config from a
    // caller-initialized one; an explicit option wins.
    const ownsTransport =
      opts.ownsTransport === true || connectionConfig !== baseConnectionConfig;
    const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();
    const lifecycleBaseUrl = connectionConfig.getBaseUrl();

    let sandboxes: Sandboxes;
    let diagnostics: Diagnostics | undefined;
    try {
      ({ sandboxes, diagnostics } = adapterFactory.createLifecycleStack({
        connectionConfig,
        lifecycleBaseUrl,
      }));
    } catch (err) {
      if (ownsTransport) {
        await connectionConfig.closeTransport();
      }
      throw err;
    }

    const budget = new ReadinessBudget(opts.readyTimeoutSeconds ?? DEFAULT_READY_TIMEOUT_SECONDS, opts.signal);
    try {
      const endpoint = await budget.endpoint(signal => sandboxes.getSandboxEndpoint(
        opts.sandboxId, DEFAULT_EXECD_PORT, connectionConfig.useServerProxy, signal,
      ), interval);
      const execdBaseUrl = `${connectionConfig.protocol}://${endpoint.endpoint}`;
      // The server is authoritative about the runtime backing: template-backed
      // sandboxes (origin `template`) have no sandbox-side egress sidecar, so
      // policy operations go through the lifecycle control plane and the
      // egress sidecar endpoint is never resolved.
      const egressStack = await resolveEgressStack(
        adapterFactory,
        sandboxes,
        connectionConfig,
        lifecycleBaseUrl,
        opts.sandboxId,
        endpoint.origin,
        // Same readiness budget as the execd lookup: transient 404
        // POD_IP_NOT_AVAILABLE is retried and slow lookups stay bounded by
        // the remaining readyTimeoutSeconds.
        budget,
        interval,
        opts.signal,
      );

      const execdStack =
        adapterFactory.createExecdStack({
          connectionConfig,
          execdBaseUrl,
          endpointHeaders: endpoint.headers,
        });

      const { commands, files, health, metrics, isolation } = execdStack;

      const sbx = new Sandbox({
        id: opts.sandboxId,
        connectionConfig,
        adapterFactory,
        ownsTransport,
        lifecycleBaseUrl,
        execdBaseUrl,
        sandboxes,
        diagnostics,
        commands,
        files,
        health,
        metrics,
        isolation: isolation ?? unavailableIsolation,
        egress: egressStack.egress,
        credentialVault: egressStack.credentialVault,
        origin: egressStack.origin,
      });

      if (!(opts.skipHealthCheck ?? false)) {
        await sbx.checkReadiness(budget, interval, opts.healthCheck);
      }

      return sbx;
    } catch (err) {
      if (opts.signal?.aborted) {
        if (ownsTransport) {
          void connectionConfig.closeTransport().catch(() => undefined);
        }
        throw err;
      }
      if (ownsTransport) {
        await connectionConfig.closeTransport();
      }
      throw err;
    }
  }

  async getInfo(): Promise<SandboxInfo> {
    return await this.sandboxes.getSandbox(this.id);
  }

  getDiagnosticContext(): Promise<DiagnosticContext> {
    return requireDiagnostics(Sandbox._priv.get(this)?.diagnostics).getContext(this.id);
  }

  getDiagnosticLogs(scope: string): Promise<DiagnosticContent> {
    return requireDiagnostics(Sandbox._priv.get(this)?.diagnostics).getLogs(this.id, scope);
  }

  getDiagnosticEvents(scope: string): Promise<DiagnosticContent> {
    return requireDiagnostics(Sandbox._priv.get(this)?.diagnostics).getEvents(this.id, scope);
  }

  async isHealthy(): Promise<boolean> {
    try {
      return await this.health.ping();
    } catch {
      return false;
    }
  }

  async getMetrics() {
    return await this.metrics.getMetrics();
  }

  async pause(): Promise<void> {
    this.sandboxes.invalidateEndpointCache?.(this.id);
    await this.sandboxes.pauseSandbox(this.id);
  }

  /**
   * Resume a paused sandbox and return a fresh, connected Sandbox instance.
   *
   * After resume, the execd endpoint may change, so this method returns a new
   * {@link Sandbox} instance with a refreshed execd base URL.
   */
  async resume(
    opts: {
      skipHealthCheck?: boolean;
      readyTimeoutSeconds?: number;
      healthCheckPollingInterval?: number;
    } = {}
  ): Promise<Sandbox> {
    if (opts.healthCheckPollingInterval !== undefined) {
      validatePollingInterval(opts.healthCheckPollingInterval);
    }
    await this.sandboxes.resumeSandbox(this.id);
    const resumeConfig = this.connectionConfig.withFreshTransport();
    return await Sandbox.connect({
      sandboxId: this.id,
      // Allocated here for the resumed instance; without ownsTransport the
      // dispatcher would leak (connect marks initialized configs caller-owned).
      connectionConfig: resumeConfig,
      ownsTransport: true,
      adapterFactory: Sandbox._priv.get(this)!.adapterFactory,
      skipHealthCheck: opts.skipHealthCheck ?? false,
      readyTimeoutSeconds: opts.readyTimeoutSeconds,
      healthCheckPollingInterval: opts.healthCheckPollingInterval,
    });
  }

  /**
   * Resume a paused sandbox by id, then connect to its execd endpoint.
   */
  static async resume(opts: SandboxConnectOptions): Promise<Sandbox> {
    if (opts.healthCheckPollingInterval !== undefined) {
      validatePollingInterval(opts.healthCheckPollingInterval);
    }
    const baseConnectionConfig =
      opts.connectionConfig instanceof ConnectionConfig
        ? opts.connectionConfig
        : new ConnectionConfig(opts.connectionConfig);
    const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();
    // Resume through a dedicated transport released right after the call.
    const resumeOnlyConfig = baseConnectionConfig.withFreshTransport();
    const lifecycleBaseUrl = resumeOnlyConfig.getBaseUrl();

    let sandboxes: Sandboxes;
    try {
      sandboxes = adapterFactory.createLifecycleStack({
        connectionConfig: resumeOnlyConfig,
        lifecycleBaseUrl,
      }).sandboxes;
      await sandboxes.resumeSandbox(opts.sandboxId);
    } catch (err) {
      await resumeOnlyConfig.closeTransport();
      throw err;
    }

    await resumeOnlyConfig.closeTransport();
    return await Sandbox.connect({ ...opts, connectionConfig: baseConnectionConfig, adapterFactory });
  }

  /**
   * Request irreversible sandbox termination. Resolves when deletion is accepted;
   * runtime cleanup may continue afterward.
   */
  async kill(): Promise<void> {
    this.sandboxes.invalidateEndpointCache?.(this.id);
    await this.sandboxes.deleteSandbox(this.id);
  }

  /**
   * Release any client-side resources (e.g. Node.js HTTP agents) owned by this Sandbox instance.
   *
   * The transport is closed only when the SDK allocated it for this
   * instance; caller-initialized `ConnectionConfig`s stay caller-owned —
   * call `connectionConfig.closeTransport()` yourself when done.
   */
  async close(): Promise<void> {
    // Shared (caller-initialized) transports are closed by their owner.
    if (Sandbox._priv.get(this)!.ownsTransport) {
      await this.connectionConfig.closeTransport();
    }
  }

  /**
   * Renew expiration by setting expiresAt to now + timeoutSeconds.
   * This may shorten or extend the remaining lifetime. The creation-time
   * server timeout limit does not apply.
   */
  async renew(timeoutSeconds: number): Promise<RenewSandboxExpirationResponse> {
    const expiresAt = new Date(
      Date.now() + timeoutSeconds * 1000
    ).toISOString();
    return await this.sandboxes.renewSandboxExpiration(this.id, { expiresAt });
  }

  async patchMetadata(patch: SandboxMetadataPatch): Promise<SandboxInfo> {
    return await this.sandboxes.patchSandboxMetadata(this.id, patch);
  }

  async getEgressPolicy(): Promise<NetworkPolicy> {
    return await Sandbox._priv.get(this)!.egress.getPolicy();
  }

  async patchEgressRules(rules: NetworkRule[]): Promise<void> {
    await Sandbox._priv.get(this)!.egress.patchRules(rules);
  }

  async deleteEgressRules(targets: string[]): Promise<void> {
    await Sandbox._priv.get(this)!.egress.deleteRules(targets);
  }

  /**
   * Get sandbox endpoint for a port (STRICT: no scheme), e.g. "localhost:44772" or "domain/route/.../44772".
   */
  async getEndpoint(port: number): Promise<Endpoint> {
    return await this.sandboxes.getSandboxEndpoint(
      this.id,
      port,
      this.connectionConfig.useServerProxy
    );
  }

  /**
   * Get signed endpoint URL with an OSEP-0011 route token that expires at the given Unix epoch timestamp (seconds).
   */
  async getSignedEndpoint(port: number, expires: number): Promise<Endpoint> {
    return await this.sandboxes.getSignedEndpoint(this.id, port, expires);
  }

  /**
   * Get absolute endpoint URL with scheme (convenience for HTTP clients).
   */
  async getEndpointUrl(port: number): Promise<string> {
    const ep = await this.getEndpoint(port);
    return `${this.connectionConfig.protocol}://${ep.endpoint}`;
  }

  private async checkReadiness(
    budget: ReadinessBudget,
    interval: number,
    healthCheck?: (sbx: Sandbox) => boolean | Promise<boolean>,
  ): Promise<void> {
    budget.healthContext(`domain=${this.connectionConfig.domain}, useServerProxy=${this.connectionConfig.useServerProxy}`);
    while (true) {
      try {
        budget.attempt();
        const healthy = await budget.run(async signal => healthCheck ? await healthCheck(this) : await this.health.ping(signal));
        if (healthy) return;
        budget.record("Health check returned false continuously.");
      } catch (error) {
        budget.remaining();
        budget.record(error);
      }
      await budget.pause(interval);
    }
  }

  async waitUntilReady(opts: {
    readyTimeoutSeconds: number;
    pollingIntervalMillis: number;
    healthCheck?: (sbx: Sandbox) => boolean | Promise<boolean>;
    signal?: AbortSignal;
  }): Promise<void> {
    validatePollingInterval(opts.pollingIntervalMillis);
    const budget = new ReadinessBudget(opts.readyTimeoutSeconds, opts.signal);
    await this.checkReadiness(budget, opts.pollingIntervalMillis, opts.healthCheck);
  }
}