Secure, Fast, and Extensible Sandbox runtime for AI agents.
// 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 type { LifecycleClient } from "../openapi/lifecycleClient.js";
import { throwOnOpenApiFetchError } from "./openapiError.js";
import type { paths as LifecyclePaths } from "../api/lifecycle.js";
import { EndpointCache } from "../core/endpointCache.js";
import { OPEN_SANDBOX_ORIGIN_HEADER } from "../core/constants.js";
import type {
Sandboxes,
} from "../services/sandboxes.js";
import type {
CreateSnapshotRequest,
CreateSandboxFromTemplateRequest,
CreateSandboxRequest,
CreateSandboxResponse,
AllocationSummary,
Endpoint,
ListSnapshotsParams,
ListSnapshotsResponse,
ListSandboxesParams,
ListSandboxesResponse,
RenewSandboxExpirationRequest,
RenewSandboxExpirationResponse,
SnapshotInfo,
SandboxId,
SandboxInfo,
SandboxMetadataPatch,
} from "../models/sandboxes.js";
import type {
CreateTemplateRequest,
ListTemplatesParams,
ListTemplatesResponse,
TemplateInfo,
} from "../models/templates.js";
type ApiCreateSandboxRequest =
LifecyclePaths["/sandboxes"]["post"]["requestBody"]["content"]["application/json"];
type ApiCreateSandboxOk =
LifecyclePaths["/sandboxes"]["post"]["responses"][202]["content"]["application/json"];
type ApiGetSandboxOk =
LifecyclePaths["/sandboxes/{sandboxId}"]["get"]["responses"][200]["content"]["application/json"];
type ApiListSandboxesOk =
LifecyclePaths["/sandboxes"]["get"]["responses"][200]["content"]["application/json"];
type ApiPatchSandboxMetadataRequest =
LifecyclePaths["/sandboxes/{sandboxId}/metadata"]["patch"]["requestBody"]["content"]["application/json"];
type ApiPatchSandboxMetadataOk =
LifecyclePaths["/sandboxes/{sandboxId}/metadata"]["patch"]["responses"][200]["content"]["application/json"];
type ApiRenewSandboxExpirationRequest =
LifecyclePaths["/sandboxes/{sandboxId}/renew-expiration"]["post"]["requestBody"]["content"]["application/json"];
type ApiRenewSandboxExpirationOk =
LifecyclePaths["/sandboxes/{sandboxId}/renew-expiration"]["post"]["responses"][200]["content"]["application/json"];
type ApiCreateSnapshotRequest =
NonNullable<
LifecyclePaths["/sandboxes/{sandboxId}/snapshots"]["post"]["requestBody"]
>["content"]["application/json"];
type ApiCreateSnapshotOk =
LifecyclePaths["/sandboxes/{sandboxId}/snapshots"]["post"]["responses"][202]["content"]["application/json"];
type ApiGetSnapshotOk =
LifecyclePaths["/snapshots/{snapshotId}"]["get"]["responses"][200]["content"]["application/json"];
type ApiListSnapshotsOk =
LifecyclePaths["/snapshots"]["get"]["responses"][200]["content"]["application/json"];
type ApiEndpointOk =
LifecyclePaths["/sandboxes/{sandboxId}/endpoints/{port}"]["get"]["responses"][200]["content"]["application/json"];
type ApiCreateTemplateRequest =
LifecyclePaths["/templates"]["post"]["requestBody"]["content"]["application/json"];
type ApiTemplateOk =
LifecyclePaths["/templates/{templateId}"]["get"]["responses"][200]["content"]["application/json"];
type ApiListTemplatesOk =
LifecyclePaths["/templates"]["get"]["responses"][200]["content"]["application/json"];
type ApiSandboxWithAllocation = ApiGetSandboxOk & {
allocation?: AllocationSummary;
};
function encodeMetadataFilter(metadata: Record<string, string>): string {
// The Lifecycle API expects a single `metadata` query parameter whose value is `k=v&k2=v2`.
// Percent-encode keys and values before joining: the query serializer encodes the
// joined value once more and the server decodes its layer before splitting with
// `parse_qsl`, so this round-trips keys and values containing `&`, `=` or `%`.
const parts: string[] = [];
for (const [k, v] of Object.entries(metadata)) {
parts.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
}
return parts.join("&");
}
export class SandboxesAdapter implements Sandboxes {
private readonly endpointCache: EndpointCache | null;
constructor(
private readonly client: LifecycleClient,
cacheOpts?: { ttlMs?: number; maxSize?: number; disabled?: boolean }
) {
if (cacheOpts?.disabled) {
this.endpointCache = null;
} else {
this.endpointCache = new EndpointCache({
ttlMs: cacheOpts?.ttlMs,
maxSize: cacheOpts?.maxSize,
});
}
}
private parseIsoDate(field: string, v: unknown): Date {
if (typeof v !== "string" || !v) {
throw new Error(`Invalid ${field}: expected ISO string, got ${typeof v}`);
}
const d = new Date(v);
if (Number.isNaN(d.getTime())) {
throw new Error(`Invalid ${field}: ${v}`);
}
return d;
}
private parseOptionalIsoDate(field: string, v: unknown): Date | null {
if (v == null) return null;
return this.parseIsoDate(field, v);
}
private mapSnapshotInfo(raw: ApiGetSnapshotOk | ApiCreateSnapshotOk): SnapshotInfo {
return {
...(raw ?? {}),
createdAt: this.parseIsoDate("createdAt", raw?.createdAt),
status: {
...(raw?.status ?? {}),
lastTransitionAt: raw?.status?.lastTransitionAt == null
? undefined
: this.parseIsoDate("lastTransitionAt", raw.status.lastTransitionAt),
},
} as SnapshotInfo;
}
private mapSandboxInfo(raw: ApiGetSandboxOk): SandboxInfo {
const { allocation, ...sandbox } = raw as ApiSandboxWithAllocation;
return {
...sandbox,
...(allocation == null ? {} : { allocation }),
createdAt: this.parseIsoDate("createdAt", raw?.createdAt),
expiresAt: this.parseOptionalIsoDate("expiresAt", raw?.expiresAt),
} as SandboxInfo;
}
private mapCreateSandboxResponse(raw: ApiCreateSandboxOk | undefined): CreateSandboxResponse {
if (!raw || typeof raw !== "object") {
throw new Error("Create sandbox failed: unexpected response shape");
}
return {
...(raw ?? {}),
createdAt: this.parseIsoDate("createdAt", raw?.createdAt),
expiresAt: this.parseOptionalIsoDate("expiresAt", raw?.expiresAt),
} as CreateSandboxResponse;
}
private mapTemplateInfo(raw: ApiTemplateOk | undefined): TemplateInfo {
if (!raw || typeof raw !== "object") {
throw new Error("Template operation failed: unexpected response shape");
}
return {
...(raw ?? {}),
createdAt: this.parseIsoDate("createdAt", raw?.createdAt),
updatedAt: this.parseIsoDate("updatedAt", raw?.updatedAt),
} as TemplateInfo;
}
async createSandbox(
req: CreateSandboxRequest,
signal?: AbortSignal,
): Promise<CreateSandboxResponse> {
// Make the OpenAPI contract explicit so backend schema changes surface quickly.
const normalizedRequest = { ...req };
const lifecycle = normalizedRequest.lifecycle;
if (lifecycle) {
const normalizedLifecycle = { ...lifecycle };
if (Array.isArray(normalizedLifecycle.periodic) && normalizedLifecycle.periodic.length === 0) {
delete normalizedLifecycle.periodic;
}
for (const [key, value] of Object.entries(normalizedLifecycle)) {
if (value === null || value === undefined) delete normalizedLifecycle[key];
}
const hasConfiguredHook = Object.keys(normalizedLifecycle).length > 0;
if (hasConfiguredHook) {
normalizedRequest.lifecycle = normalizedLifecycle;
} else {
delete normalizedRequest.lifecycle;
}
} else {
delete normalizedRequest.lifecycle;
}
const body: ApiCreateSandboxRequest = normalizedRequest as unknown as ApiCreateSandboxRequest;
const { data, error, response } = await this.client.POST("/sandboxes", {
body,
signal,
});
throwOnOpenApiFetchError({ error, response }, "Create sandbox failed");
return this.mapCreateSandboxResponse(data as ApiCreateSandboxOk | undefined);
}
async createSandboxFromTemplate(
req: CreateSandboxFromTemplateRequest,
signal?: AbortSignal,
): Promise<CreateSandboxResponse> {
// Template mode fixes the workload shape server-side; only the template id,
// timeout, metadata, networkPolicy, extensions and the idle policy are
// forwarded. The idle policy is control-plane state (OSEP-0024), so it
// rides the lifecycle object while hooks stay template-owned.
const body: ApiCreateSandboxRequest = {
templateId: req.templateId,
timeout: req.timeout,
metadata: req.metadata,
networkPolicy: req.networkPolicy,
extensions: req.extensions,
...(req.idlePolicy == null
? {}
: { lifecycle: { idlePolicy: req.idlePolicy } }),
} as unknown as ApiCreateSandboxRequest;
const { data, error, response } = await this.client.POST("/sandboxes", {
body,
signal,
});
throwOnOpenApiFetchError({ error, response }, "Create sandbox from template failed");
return this.mapCreateSandboxResponse(data as ApiCreateSandboxOk | undefined);
}
async getSandbox(sandboxId: SandboxId): Promise<SandboxInfo> {
const { data, error, response } = await this.client.GET("/sandboxes/{sandboxId}", {
params: { path: { sandboxId } },
});
throwOnOpenApiFetchError({ error, response }, "Get sandbox failed");
const ok = data as ApiGetSandboxOk | undefined;
if (!ok || typeof ok !== "object") {
throw new Error("Get sandbox failed: unexpected response shape");
}
return this.mapSandboxInfo(ok);
}
async listSandboxes(params: ListSandboxesParams = {}): Promise<ListSandboxesResponse> {
const query: Record<string, string | number | boolean | undefined | null | (string | number)[]> = {};
if (params.states?.length) query.state = params.states;
if (params.metadata && Object.keys(params.metadata).length) {
query.metadata = encodeMetadataFilter(params.metadata);
}
if (params.page != null) query.page = params.page;
if (params.pageSize != null) query.pageSize = params.pageSize;
const { data, error, response } = await this.client.GET("/sandboxes", {
params: { query },
});
throwOnOpenApiFetchError({ error, response }, "List sandboxes failed");
const raw = data as ApiListSandboxesOk | undefined;
if (!raw || typeof raw !== "object") {
throw new Error("List sandboxes failed: unexpected response shape");
}
const itemsRaw = raw.items;
if (!Array.isArray(itemsRaw)) throw new Error("List sandboxes failed: unexpected items shape");
return {
...(raw ?? {}),
items: itemsRaw.map((x) => this.mapSandboxInfo(x)),
} as ListSandboxesResponse;
}
async patchSandboxMetadata(
sandboxId: SandboxId,
patch: SandboxMetadataPatch,
): Promise<SandboxInfo> {
const body: ApiPatchSandboxMetadataRequest = patch;
const { data, error, response } = await this.client.PATCH("/sandboxes/{sandboxId}/metadata", {
params: { path: { sandboxId } },
body,
});
throwOnOpenApiFetchError({ error, response }, "Patch sandbox metadata failed");
const ok = data as ApiPatchSandboxMetadataOk | undefined;
if (!ok || typeof ok !== "object") {
throw new Error("Patch sandbox metadata failed: unexpected response shape");
}
return this.mapSandboxInfo(ok);
}
async deleteSandbox(sandboxId: SandboxId, signal?: AbortSignal): Promise<void> {
const { error, response } = await this.client.DELETE("/sandboxes/{sandboxId}", {
params: { path: { sandboxId } },
signal,
});
throwOnOpenApiFetchError({ error, response }, "Delete sandbox failed");
}
async pauseSandbox(sandboxId: SandboxId): Promise<void> {
const { error, response } = await this.client.POST("/sandboxes/{sandboxId}/pause", {
params: { path: { sandboxId } },
});
throwOnOpenApiFetchError({ error, response }, "Pause sandbox failed");
}
async resumeSandbox(sandboxId: SandboxId): Promise<void> {
const { error, response } = await this.client.POST("/sandboxes/{sandboxId}/resume", {
params: { path: { sandboxId } },
});
throwOnOpenApiFetchError({ error, response }, "Resume sandbox failed");
}
async renewSandboxExpiration(
sandboxId: SandboxId,
req: RenewSandboxExpirationRequest,
): Promise<RenewSandboxExpirationResponse> {
const body: ApiRenewSandboxExpirationRequest = req as unknown as ApiRenewSandboxExpirationRequest;
const { data, error, response } = await this.client.POST("/sandboxes/{sandboxId}/renew-expiration", {
params: { path: { sandboxId } },
body,
});
throwOnOpenApiFetchError({ error, response }, "Renew sandbox expiration failed");
const raw = data as ApiRenewSandboxExpirationOk | undefined;
if (!raw || typeof raw !== "object") {
throw new Error("Renew sandbox expiration failed: unexpected response shape");
}
return {
...(raw ?? {}),
expiresAt: raw?.expiresAt ? this.parseIsoDate("expiresAt", raw.expiresAt) : undefined,
} as RenewSandboxExpirationResponse;
}
async createSnapshot(
sandboxId: SandboxId,
req: CreateSnapshotRequest = {},
): Promise<SnapshotInfo> {
const body: ApiCreateSnapshotRequest = req as unknown as ApiCreateSnapshotRequest;
const { data, error, response } = await this.client.POST("/sandboxes/{sandboxId}/snapshots", {
params: { path: { sandboxId } },
body,
});
throwOnOpenApiFetchError({ error, response }, "Create snapshot failed");
const raw = data as ApiCreateSnapshotOk | undefined;
if (!raw || typeof raw !== "object") {
throw new Error("Create snapshot failed: unexpected response shape");
}
return this.mapSnapshotInfo(raw);
}
async getSnapshot(snapshotId: string): Promise<SnapshotInfo> {
const { data, error, response } = await this.client.GET("/snapshots/{snapshotId}", {
params: { path: { snapshotId } },
});
throwOnOpenApiFetchError({ error, response }, "Get snapshot failed");
const raw = data as ApiGetSnapshotOk | undefined;
if (!raw || typeof raw !== "object") {
throw new Error("Get snapshot failed: unexpected response shape");
}
return this.mapSnapshotInfo(raw);
}
async listSnapshots(params: ListSnapshotsParams = {}): Promise<ListSnapshotsResponse> {
const query: Record<string, string | number | (string | number)[] | undefined> = {};
if (params.sandboxId) query.sandboxId = params.sandboxId;
if (params.name != null) query.name = params.name;
if (params.states?.length) query.state = params.states;
if (params.page != null) query.page = params.page;
if (params.pageSize != null) query.pageSize = params.pageSize;
const { data, error, response } = await this.client.GET("/snapshots", {
params: { query },
});
throwOnOpenApiFetchError({ error, response }, "List snapshots failed");
const raw = data as ApiListSnapshotsOk | undefined;
if (!raw || typeof raw !== "object") {
throw new Error("List snapshots failed: unexpected response shape");
}
const itemsRaw = raw.items;
if (!Array.isArray(itemsRaw)) throw new Error("List snapshots failed: unexpected items shape");
return {
...(raw ?? {}),
items: itemsRaw.map((x) => this.mapSnapshotInfo(x)),
} as ListSnapshotsResponse;
}
async deleteSnapshot(snapshotId: string): Promise<void> {
const { error, response } = await this.client.DELETE("/snapshots/{snapshotId}", {
params: { path: { snapshotId } },
});
throwOnOpenApiFetchError({ error, response }, "Delete snapshot failed");
}
async createTemplate(req: CreateTemplateRequest): Promise<TemplateInfo> {
const body: ApiCreateTemplateRequest = req as unknown as ApiCreateTemplateRequest;
const { data, error, response } = await this.client.POST("/templates", {
body,
});
throwOnOpenApiFetchError({ error, response }, "Create template failed");
return this.mapTemplateInfo(data as ApiTemplateOk | undefined);
}
async getTemplate(templateId: string): Promise<TemplateInfo> {
const { data, error, response } = await this.client.GET("/templates/{templateId}", {
params: { path: { templateId } },
});
throwOnOpenApiFetchError({ error, response }, "Get template failed");
return this.mapTemplateInfo(data as ApiTemplateOk | undefined);
}
async listTemplates(params: ListTemplatesParams = {}): Promise<ListTemplatesResponse> {
const query: Record<string, string | number | undefined> = {};
if (params.metadata && Object.keys(params.metadata).length) {
query.metadata = encodeMetadataFilter(params.metadata);
}
if (params.page != null) query.page = params.page;
if (params.pageSize != null) query.pageSize = params.pageSize;
const { data, error, response } = await this.client.GET("/templates", {
params: { query },
});
throwOnOpenApiFetchError({ error, response }, "List templates failed");
const raw = data as ApiListTemplatesOk | undefined;
if (!raw || typeof raw !== "object") {
throw new Error("List templates failed: unexpected response shape");
}
const itemsRaw = raw.items;
if (!Array.isArray(itemsRaw)) throw new Error("List templates failed: unexpected items shape");
return {
...(raw ?? {}),
items: itemsRaw.map((x) => this.mapTemplateInfo(x)),
} as ListTemplatesResponse;
}
async deleteTemplate(templateId: string): Promise<void> {
const { error, response } = await this.client.DELETE("/templates/{templateId}", {
params: { path: { templateId } },
});
throwOnOpenApiFetchError({ error, response }, "Delete template failed");
}
async getSandboxEndpoint(
sandboxId: SandboxId,
port: number,
useServerProxy = false,
signal?: AbortSignal,
): Promise<Endpoint> {
signal?.throwIfAborted();
const cached = this.endpointCache?.get(sandboxId, port, useServerProxy);
if (cached) return cached;
if (!this.endpointCache) {
return this.fetchSandboxEndpoint(sandboxId, port, useServerProxy, signal);
}
// Signal-less dedup fetch: no single caller's signal may abort the
// shared request; signal callers race it locally instead.
const shared = this.endpointCache.getOrFetch(sandboxId, port, useServerProxy, () =>
this.fetchSandboxEndpoint(sandboxId, port, useServerProxy)
);
if (!signal) return shared;
return this.raceSignal(shared, signal);
}
private async raceSignal(
promise: Promise<Endpoint>,
signal: AbortSignal,
): Promise<Endpoint> {
if (signal.aborted) throw signal.reason ?? new Error("Aborted");
let onAbort: (() => void) | undefined;
const abortPromise = new Promise<never>((_, reject) => {
onAbort = () => reject(signal.reason ?? new Error("Aborted"));
signal.addEventListener("abort", onAbort, { once: true } as any);
});
try {
return await Promise.race([promise, abortPromise]);
} finally {
if (onAbort) signal.removeEventListener("abort", onAbort as any);
}
}
private async fetchSandboxEndpoint(
sandboxId: SandboxId,
port: number,
useServerProxy: boolean,
signal?: AbortSignal,
): Promise<Endpoint> {
const { data, error, response } = await this.client.GET("/sandboxes/{sandboxId}/endpoints/{port}", {
params: { path: { sandboxId, port }, query: { use_server_proxy: useServerProxy } },
signal,
});
throwOnOpenApiFetchError({ error, response }, "Get sandbox endpoint failed");
const ok = data as ApiEndpointOk | undefined;
if (!ok || typeof ok !== "object") {
throw new Error("Get sandbox endpoint failed: unexpected response shape");
}
return {
...(ok as unknown as Endpoint),
origin: response.headers.get(OPEN_SANDBOX_ORIGIN_HEADER) ?? undefined,
};
}
invalidateEndpointCache(sandboxId: SandboxId): void {
this.endpointCache?.invalidate(sandboxId);
}
async getSignedEndpoint(
sandboxId: SandboxId,
port: number,
expires: number
): Promise<Endpoint> {
const { data, error, response } = await this.client.GET("/sandboxes/{sandboxId}/endpoints/{port}", {
params: { path: { sandboxId, port }, query: { expires: expires.toString() } },
});
throwOnOpenApiFetchError({ error, response }, "Get signed endpoint failed");
const ok = data as ApiEndpointOk | undefined;
if (!ok || typeof ok !== "object") {
throw new Error("Get signed endpoint failed: unexpected response shape");
}
return {
...(ok as unknown as Endpoint),
origin: response.headers.get(OPEN_SANDBOX_ORIGIN_HEADER) ?? undefined,
};
}
}