@superserve/sdk0.13.0111.7 kB
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
AuthenticationError: () => AuthenticationError,
BillingError: () => BillingError,
BuildError: () => BuildError,
ConflictError: () => ConflictError,
DESKTOP_STREAM_PORT: () => DESKTOP_STREAM_PORT,
MAX_PREVIEW_PORT: () => MAX_PREVIEW_PORT,
MIN_PREVIEW_PORT: () => MIN_PREVIEW_PORT,
NotFoundError: () => NotFoundError,
Provider: () => Provider,
RESERVED_PREVIEW_PORT: () => RESERVED_PREVIEW_PORT,
RateLimitError: () => RateLimitError,
Sandbox: () => Sandbox,
SandboxError: () => SandboxError,
Secret: () => Secret,
ServerError: () => ServerError,
Snapshot: () => Snapshot,
Template: () => Template,
TimeoutError: () => TimeoutError,
ValidationError: () => ValidationError,
Volume: () => Volume,
previewUrl: () => previewUrl,
resolveConfig: () => resolveConfig
});
module.exports = __toCommonJS(src_exports);
// src/errors.ts
var SandboxError = class extends Error {
constructor(message, statusCode, code, options) {
super(message);
this.name = "SandboxError";
this.statusCode = statusCode;
this.code = code;
if (options?.cause !== void 0) {
;
this.cause = options.cause;
}
}
};
var AuthenticationError = class extends SandboxError {
constructor(message = "Missing or invalid API key", code, statusCode = 401) {
super(message, statusCode, code);
this.name = "AuthenticationError";
}
};
var ValidationError = class extends SandboxError {
constructor(message, code) {
super(message, 400, code);
this.name = "ValidationError";
}
};
var NotFoundError = class extends SandboxError {
constructor(message = "Resource not found", code) {
super(message, 404, code);
this.name = "NotFoundError";
}
};
var ConflictError = class extends SandboxError {
constructor(message = "Sandbox is not in a valid state for this operation", code) {
super(message, 409, code);
this.name = "ConflictError";
}
};
var TimeoutError = class extends SandboxError {
constructor(message = "Request timed out") {
super(message);
this.name = "TimeoutError";
}
};
var RateLimitError = class extends SandboxError {
constructor(message = "Rate limit exceeded", code) {
super(message, 429, code);
this.name = "RateLimitError";
}
};
var BillingError = class extends SandboxError {
constructor(message = "Billing does not allow this request", code, actionUrl) {
super(message, 402, code);
this.name = "BillingError";
this.actionUrl = actionUrl;
}
};
var ServerError = class extends SandboxError {
constructor(message = "Internal server error", code, statusCode = 500) {
super(message, statusCode, code);
this.name = "ServerError";
}
};
var BuildError = class extends SandboxError {
constructor(message, opts) {
super(message, opts.statusCode, opts.code);
this.name = "BuildError";
this.code = opts.code;
this.buildId = opts.buildId;
this.templateId = opts.templateId;
}
};
function mapApiError(status, body) {
const error = typeof body?.error === "string" ? void 0 : body?.error;
const message = error?.message ?? (typeof body?.error === "string" ? body.error : void 0) ?? (typeof body?.message === "string" ? body.message : void 0) ?? `API error (${status})`;
const code = error?.code ?? body?.code;
switch (status) {
case 400:
return new ValidationError(message, code);
case 401:
case 403:
return new AuthenticationError(message, code, status);
case 404:
return new NotFoundError(message, code);
case 409:
return new ConflictError(message, code);
case 402: {
const actionUrl = error?.action_url;
return new BillingError(
message,
code,
typeof actionUrl === "string" && actionUrl ? actionUrl : void 0
);
}
case 429:
return new RateLimitError(message, code);
default:
if (status >= 500) return new ServerError(message, code, status);
return new SandboxError(message, status, code);
}
}
// src/config.ts
var DEFAULT_BASE_URL = "https://api.superserve.ai";
var DEFAULT_SANDBOX_HOST = "sandbox.superserve.ai";
var KNOWN_REGIONS = /* @__PURE__ */ new Map([
[
"use",
{
baseUrl: "https://api.superserve.ai",
sandboxHost: "sandbox.superserve.ai"
}
],
[
"usw",
{
baseUrl: "https://api-usw.superserve.ai",
sandboxHost: "usw-sandbox.superserve.ai"
}
]
]);
var REGION_KEY_RE = /^ss_live_([a-z0-9]{1,17})_[A-Za-z0-9_-]{32}$/;
function resolveConfig(opts) {
const apiKey = opts?.apiKey ?? process.env.SUPERSERVE_API_KEY;
if (!apiKey) {
throw new AuthenticationError(
"Missing API key. Pass `apiKey` or set the SUPERSERVE_API_KEY environment variable."
);
}
const rawOverride = opts?.baseUrl ?? process.env.SUPERSERVE_BASE_URL;
const overrideUrl = rawOverride?.trim() || void 0;
if (overrideUrl !== void 0) {
return {
apiKey,
baseUrl: overrideUrl,
sandboxHost: deriveSandboxHost(overrideUrl)
};
}
const region = regionFromApiKey(apiKey);
const endpoints = region !== void 0 ? KNOWN_REGIONS.get(region) : void 0;
if (endpoints !== void 0) {
return {
apiKey,
baseUrl: endpoints.baseUrl,
sandboxHost: endpoints.sandboxHost
};
}
return {
apiKey,
baseUrl: DEFAULT_BASE_URL,
sandboxHost: DEFAULT_SANDBOX_HOST
};
}
function regionFromApiKey(apiKey) {
return REGION_KEY_RE.exec(apiKey)?.[1];
}
var SUPPORTED_SHARED_HOSTS = /* @__PURE__ */ new Set([
"sandbox.superserve.ai",
"staging-sandbox.superserve.ai",
"usw-sandbox.superserve.ai"
]);
var SANDBOX_ID_HEADER = "X-Superserve-Sandbox-Id";
function dataPlaneTarget(sandboxId, sandboxHost) {
const isBrowser = typeof window !== "undefined";
const host = sandboxHost.toLowerCase();
if (!isBrowser && SUPPORTED_SHARED_HOSTS.has(host)) {
return {
url: `https://${host}`,
headers: { [SANDBOX_ID_HEADER]: sandboxId }
};
}
return {
url: `https://boxd-${sandboxId}.${host}`,
headers: {}
};
}
var MIN_PREVIEW_PORT = 1024;
var MAX_PREVIEW_PORT = 65535;
var RESERVED_PREVIEW_PORT = 49983;
function previewUrl(sandboxId, sandboxHost, port) {
if (!Number.isInteger(port) || port < MIN_PREVIEW_PORT || port > MAX_PREVIEW_PORT || port === RESERVED_PREVIEW_PORT) {
if (port === RESERVED_PREVIEW_PORT) {
throw new ValidationError(
`Invalid preview port ${port}: reserved for sandbox control traffic.`
);
}
throw new ValidationError(
`Invalid preview port ${port}: must be an integer between ${MIN_PREVIEW_PORT} and ${MAX_PREVIEW_PORT}. Privileged ports (< ${MIN_PREVIEW_PORT}) are not proxied.`
);
}
return `https://${port}-${sandboxId}.${sandboxHost}`;
}
function deriveSandboxHost(baseUrl) {
try {
const host = new URL(baseUrl).hostname;
if (host === "api-staging.superserve.ai") {
return "staging-sandbox.superserve.ai";
}
for (const cell of KNOWN_REGIONS.values()) {
if (new URL(cell.baseUrl).hostname === host) {
return cell.sandboxHost;
}
}
} catch {
}
return DEFAULT_SANDBOX_HOST;
}
// src/http.ts
var DEFAULT_TIMEOUT_MS = 3e4;
var SDK_VERSION = "0.13.0";
var USER_AGENT = `@superserve/sdk/${SDK_VERSION} (node/${typeof process !== "undefined" && process.versions?.node ? `v${process.versions.node}` : "unknown"})`;
var DEFAULT_MAX_ATTEMPTS = 3;
var CONFLICT_MAX_ATTEMPTS = 11;
var BASE_BACKOFF_MS = 100;
var MAX_BACKOFF_MS = 3e4;
var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
var DEFAULT_MAX_DOWNLOAD_BYTES = 2 * 1024 * 1024 * 1024;
function composeSignals(internal, user) {
if (!user) return { signal: internal, release: () => {
} };
if (typeof AbortSignal.any === "function") {
return { signal: AbortSignal.any([internal, user]), release: () => {
} };
}
const controller = new AbortController();
const onInternal = () => {
release();
controller.abort(internal.reason);
};
const onUser = () => {
release();
controller.abort(user.reason);
};
const release = () => {
internal.removeEventListener("abort", onInternal);
user.removeEventListener("abort", onUser);
};
if (internal.aborted) {
controller.abort(internal.reason);
} else if (user.aborted) {
controller.abort(user.reason);
} else {
internal.addEventListener("abort", onInternal);
user.addEventListener("abort", onUser);
}
return { signal: controller.signal, release };
}
function abortReason(signal) {
return signal?.reason ?? new DOMException("aborted", "AbortError");
}
function sleep(ms, signal) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(abortReason(signal));
return;
}
const onAbort = () => {
clearTimeout(timer);
reject(abortReason(signal));
};
const timer = setTimeout(() => {
signal?.removeEventListener("abort", onAbort);
resolve();
}, ms);
signal?.addEventListener("abort", onAbort, { once: true });
});
}
function parseRetryAfter(value) {
if (!value) return null;
const trimmed = value.trim();
if (!trimmed) return null;
const asNumber = Number(trimmed);
if (Number.isFinite(asNumber) && asNumber >= 0) {
return Math.min(asNumber * 1e3, MAX_BACKOFF_MS);
}
const asDate = Date.parse(trimmed);
if (Number.isFinite(asDate)) {
const delta = asDate - Date.now();
if (delta <= 0) return 0;
return Math.min(delta, MAX_BACKOFF_MS);
}
return null;
}
function backoffDelay(attempt) {
const base = BASE_BACKOFF_MS * 2 ** (attempt - 1);
const jitter = base * (0.8 + Math.random() * 0.4);
return Math.min(jitter, MAX_BACKOFF_MS);
}
function isNetworkError(err) {
if (err instanceof DOMException && err.name === "AbortError") return false;
if (err instanceof TypeError) return true;
if (err instanceof Error && (err.name === "FetchError" || err.name === "NetworkError")) {
return true;
}
return false;
}
async function retryableFetch(input, init, opts) {
let maxAttempts = opts.retryable ? opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS : 1;
let lastError;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const controller = new AbortController();
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
controller.abort();
}, opts.timeoutMs);
const { signal, release } = composeSignals(
controller.signal,
opts.userSignal
);
let handedOff = false;
const done = () => {
clearTimeout(timer);
release();
};
try {
const res = await fetch(input, { ...init, signal });
const retryableStatus = RETRYABLE_STATUSES.has(res.status) || res.status === 409 && opts.retryConflict === true;
if (opts.retryable && retryableStatus) {
if (res.status === 409 && opts.maxAttempts === void 0) {
maxAttempts = CONFLICT_MAX_ATTEMPTS;
}
if (attempt >= maxAttempts) {
handedOff = true;
return { res, release: done };
}
let delay = null;
if (res.status === 429) {
delay = parseRetryAfter(res.headers.get("Retry-After"));
}
if (delay === null) {
delay = backoffDelay(attempt);
}
try {
await res.arrayBuffer();
} catch {
}
clearTimeout(timer);
await sleep(delay, opts.userSignal);
continue;
}
handedOff = true;
return { res, release: done };
} catch (err) {
lastError = err;
if (opts.userSignal?.aborted) {
throw err;
}
if (timedOut) {
throw new TimeoutError(`Request timed out after ${opts.timeoutMs}ms`);
}
if (err instanceof DOMException && err.name === "AbortError") {
throw err;
}
if (opts.retryable && isNetworkError(err) && attempt < maxAttempts) {
await sleep(backoffDelay(attempt), opts.userSignal);
continue;
}
throw err;
} finally {
if (!handedOff) done();
else if (!opts.timeoutCoversBody) clearTimeout(timer);
}
}
throw lastError ?? new SandboxError("Request failed with no response");
}
async function readErrorBody(res) {
let text;
try {
text = await res.text();
} catch {
return {};
}
try {
return JSON.parse(text);
} catch {
const legacyPaused = res.status === 503 && res.headers.get("content-type")?.startsWith("text/plain") && res.headers.get("x-content-type-options") === "nosniff" && (text === "sandbox is paused\n" || text === "sandbox is stopped\n");
return legacyPaused ? { error: { code: "sandbox_unavailable", message: text.trim() } } : {};
}
}
async function request(opts) {
const {
method,
url,
headers = {},
body,
timeoutMs = DEFAULT_TIMEOUT_MS,
signal: userSignal,
maxBytes,
retryConflict
} = opts;
const retryable = method === "GET" || method === "DELETE";
const mergedHeaders = {
"User-Agent": USER_AGENT,
"Content-Type": "application/json",
...headers
};
try {
const { res, release } = await retryableFetch(
url,
{
method,
headers: mergedHeaders,
body: body !== void 0 ? JSON.stringify(body) : void 0
},
{
timeoutMs,
retryable,
retryConflict,
userSignal,
timeoutCoversBody: true
}
);
try {
if (!res.ok) {
const errorBody = await readErrorBody(res);
throw mapApiError(res.status, errorBody);
}
if (res.status === 204) {
return void 0;
}
if (maxBytes !== void 0) {
const bytes = await readBodyWithLimit(res, maxBytes, "Response body");
if (bytes.byteLength === 0) return void 0;
return JSON.parse(new TextDecoder().decode(bytes));
}
const text = await res.text();
return text ? JSON.parse(text) : void 0;
} finally {
release();
}
} catch (err) {
if (err instanceof SandboxError) throw err;
if (err instanceof DOMException && err.name === "AbortError") {
if (!userSignal?.aborted) {
throw new TimeoutError(`Request timed out after ${timeoutMs}ms`);
}
throw new SandboxError("Request aborted", void 0, void 0, {
cause: err
});
}
throw new SandboxError(
`Network error: ${err instanceof Error ? err.message : String(err)}`,
void 0,
void 0,
{ cause: err }
);
}
}
async function requestVoid(opts) {
await request(opts);
}
async function uploadBytes(opts) {
const {
url,
headers,
body,
timeoutMs = DEFAULT_TIMEOUT_MS,
signal: userSignal
} = opts;
const mergedHeaders = {
"User-Agent": USER_AGENT,
"Content-Type": "application/octet-stream",
...headers
};
try {
const { res, release } = await retryableFetch(
url,
{ method: "POST", headers: mergedHeaders, body },
{ timeoutMs, retryable: false, userSignal }
);
try {
if (!res.ok) {
const errorBody = await readErrorBody(res);
throw mapApiError(res.status, errorBody);
}
} finally {
release();
}
} catch (err) {
if (err instanceof SandboxError) throw err;
if (err instanceof DOMException && err.name === "AbortError") {
throw new SandboxError("Upload aborted", void 0, void 0, {
cause: err
});
}
throw new SandboxError(
`Upload error: ${err instanceof Error ? err.message : String(err)}`,
void 0,
void 0,
{ cause: err }
);
}
}
async function readBodyWithLimit(res, maxBytes, what = "Download") {
if (!res.body) {
const buf = new Uint8Array(await res.arrayBuffer());
if (buf.byteLength > maxBytes) {
throw new ValidationError(
`${what} exceeds the maximum size of ${maxBytes} bytes`
);
}
return buf;
}
const reader = res.body.getReader();
const chunks = [];
let total = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (!value) continue;
total += value.byteLength;
if (total > maxBytes) {
await reader.cancel();
throw new ValidationError(
`${what} exceeds the maximum size of ${maxBytes} bytes`
);
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
const out = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
out.set(chunk, offset);
offset += chunk.byteLength;
}
return out;
}
async function downloadBytes(opts) {
const {
url,
headers,
timeoutMs = DEFAULT_TIMEOUT_MS,
signal: userSignal,
maxBytes = DEFAULT_MAX_DOWNLOAD_BYTES
} = opts;
const mergedHeaders = {
"User-Agent": USER_AGENT,
...headers
};
try {
const { res, release } = await retryableFetch(
url,
{ method: "GET", headers: mergedHeaders },
{ timeoutMs, retryable: true, userSignal }
);
try {
if (!res.ok) {
const errorBody = await readErrorBody(res);
throw mapApiError(res.status, errorBody);
}
return await readBodyWithLimit(res, maxBytes);
} finally {
release();
}
} catch (err) {
if (err instanceof SandboxError) throw err;
if (err instanceof DOMException && err.name === "AbortError") {
throw new SandboxError("Download aborted", void 0, void 0, {
cause: err
});
}
throw new SandboxError(
`Download error: ${err instanceof Error ? err.message : String(err)}`,
void 0,
void 0,
{ cause: err }
);
}
}
async function streamSSE(opts) {
const {
url,
headers,
body,
method = "POST",
timeoutMs = 3e5,
signal: userSignal,
onEvent
} = opts;
const controller = new AbortController();
let timedOut = false;
let timer = setTimeout(() => {
timedOut = true;
controller.abort();
}, timeoutMs);
const { signal, release } = composeSignals(controller.signal, userSignal);
try {
const init = {
method,
headers: {
"User-Agent": USER_AGENT,
...method === "POST" ? { "Content-Type": "application/json" } : {},
...headers
},
signal
};
if (method === "POST") {
init.body = JSON.stringify(body ?? {});
}
const res = await fetch(url, init);
if (!res.ok) {
const errorBody = await readErrorBody(res);
throw mapApiError(res.status, errorBody);
}
if (!res.body) {
throw new SandboxError("Expected streaming response but got empty body");
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (timer) {
clearTimeout(timer);
timer = setTimeout(() => {
timedOut = true;
controller.abort();
}, timeoutMs);
}
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
if (!line.startsWith("data:")) continue;
const json = line.slice(5).trim();
if (!json || json === "[DONE]") continue;
try {
const event = JSON.parse(json);
onEvent(event);
} catch {
}
}
}
} catch (err) {
if (err instanceof SandboxError) throw err;
if (err instanceof DOMException && err.name === "AbortError") {
if (timedOut)
throw new TimeoutError(`Stream timed out after ${timeoutMs}ms`);
throw new SandboxError("Stream aborted", void 0, void 0, {
cause: err
});
}
throw new SandboxError(
`Stream error: ${err instanceof Error ? err.message : String(err)}`,
void 0,
void 0,
{ cause: err }
);
} finally {
release();
if (timer) clearTimeout(timer);
}
}
// src/routingHint.ts
function routingHintHeaders(deps) {
const hint = deps.getRoutingHint?.();
return hint ? { "X-Superserve-Routing-Hint": hint } : {};
}
function routingHintExpired(deps) {
const hint = deps.getRoutingHint?.();
if (!hint) return false;
try {
const payload = hint.split(".")[1];
const value = JSON.parse(
atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
);
return typeof value.e === "number" && value.e <= Date.now() / 1e3;
} catch {
return false;
}
}
// src/tokenRetry.ts
function isResumable(err, hinted = false) {
if (err instanceof SandboxError && err.statusCode === 404 && err.code === "sandbox_route_stale")
return true;
if (err instanceof AuthenticationError) return true;
if (err instanceof ServerError)
return err.statusCode === 503 && (!hinted || err.code === "sandbox_unavailable");
return false;
}
async function withTokenRetry(deps, send) {
if (routingHintExpired(deps)) await deps.refreshActivate();
const hinted = Boolean(deps.getRoutingHint?.());
try {
return await send(deps.getAccessToken());
} catch (err) {
if (!isResumable(err, hinted)) throw err;
const fresh = await deps.refreshActivate();
return send(fresh);
}
}
// src/desktop.ts
var RPC_BASE = "/superserve.boxd.v1.DesktopService";
var DESKTOP_STREAM_PORT = 6080;
var MAX_SCREENSHOT_RESPONSE_BYTES = 48 * 1024 * 1024;
var KEYSYMS = {
enter: "Return",
return: "Return",
esc: "Escape",
escape: "Escape",
tab: "Tab",
space: "space",
backspace: "BackSpace",
delete: "Delete",
insert: "Insert",
up: "Up",
down: "Down",
left: "Left",
right: "Right",
home: "Home",
end: "End",
pageup: "Page_Up",
pagedown: "Page_Down",
ctrl: "ctrl",
control: "ctrl",
alt: "alt",
shift: "shift",
cmd: "super",
win: "super",
super: "super"
};
function toKeysym(key) {
return KEYSYMS[key.toLowerCase()] ?? key;
}
function chordParts(key) {
const parts = (Array.isArray(key) ? key : key.split("+")).map(toKeysym);
if (parts.length === 0 || parts.some((p) => p === "")) {
throw new Error("press: empty key");
}
return { modifiers: parts.slice(0, -1), key: parts[parts.length - 1] };
}
function buttonEnum(button = "left") {
switch (button) {
case "left":
return "POINTER_BUTTON_LEFT";
case "right":
return "POINTER_BUTTON_RIGHT";
case "middle":
return "POINTER_BUTTON_MIDDLE";
}
}
function assertCoordinate(x, y) {
if (!Number.isInteger(x) || !Number.isInteger(y) || x < 0 || y < 0) {
throw new Error(`Invalid coordinates (${x}, ${y}): must be integers >= 0`);
}
}
function pointerBody(x, y, action, button) {
assertCoordinate(x, y);
return { x, y, button: buttonEnum(button), action };
}
function actionBody(action) {
switch (action.type) {
case "click":
return {
pointer: pointerBody(
action.x,
action.y,
"POINTER_ACTION_CLICK",
action.button
)
};
case "doubleClick":
return {
pointer: pointerBody(action.x, action.y, "POINTER_ACTION_DOUBLE_CLICK")
};
case "move":
return {
pointer: pointerBody(action.x, action.y, "POINTER_ACTION_MOVE")
};
case "mouseDown":
return {
pointer: pointerBody(
action.x,
action.y,
"POINTER_ACTION_DOWN",
action.button
)
};
case "mouseUp":
return {
pointer: pointerBody(
action.x,
action.y,
"POINTER_ACTION_UP",
action.button
)
};
case "press": {
const { modifiers, key } = chordParts(action.key);
return { key: { key, modifiers } };
}
case "write":
return { key: { text: action.text } };
case "scroll":
return { scroll: { dx: action.dx ?? 0, dy: action.dy ?? 0 } };
}
}
function decodeScreenshot(raw) {
return {
data: Uint8Array.from(atob(raw.image ?? ""), (c) => c.charCodeAt(0)),
width: raw.width ?? 0,
height: raw.height ?? 0,
format: raw.format === "FRAME_FORMAT_JPEG" ? "jpeg" : "png"
};
}
function formatBody(format) {
return format === "jpeg" ? { format: "FRAME_FORMAT_JPEG" } : {};
}
var Desktop = class {
/** @internal */
constructor(_deps) {
this._deps = _deps;
const target = dataPlaneTarget(_deps.sandboxId, _deps.sandboxHost);
this._dataPlaneBaseUrl = target.url;
this._routingHeaders = target.headers;
}
/**
* Capture the current screen, as a PNG unless `format` says otherwise.
*
* One round trip; safe to call while a live stream viewer is open.
*
* @example
* ```typescript
* const shot = await sandbox.desktop.screenshot()
* await fs.writeFile("screen.png", shot.data)
* ```
*/
async screenshot(options = {}) {
const raw = await this._rpc(
"Screenshot",
formatBody(options.format),
{ maxBytes: MAX_SCREENSHOT_RESPONSE_BYTES }
);
if (raw.image === void 0) {
throw new Error("Screenshot response missing image data");
}
return decodeScreenshot(raw);
}
/** Click at (x, y). One RPC — move and click are a single action. */
async click(x, y, options = {}) {
await this._pointer(
pointerBody(x, y, "POINTER_ACTION_CLICK", options.button)
);
}
/** Double-click at (x, y). */
async doubleClick(x, y) {
await this._pointer(pointerBody(x, y, "POINTER_ACTION_DOUBLE_CLICK"));
}
/** Right-click at (x, y). */
rightClick(x, y) {
return this.click(x, y, { button: "right" });
}
/** Middle-click at (x, y). */
middleClick(x, y) {
return this.click(x, y, { button: "middle" });
}
/** Move the pointer to (x, y) without clicking. */
async moveMouse(x, y) {
await this._pointer(pointerBody(x, y, "POINTER_ACTION_MOVE"));
}
/**
* Drag from one point to another. Executes as one atomic batch
* (down → move → up) under the sandbox's input lock, so no other input
* can interleave mid-drag.
*/
async drag(from, to, options = {}) {
await this.actions([
{ type: "mouseDown", x: from[0], y: from[1], button: options.button },
{ type: "move", x: to[0], y: to[1] },
{ type: "mouseUp", x: to[0], y: to[1], button: options.button }
]);
}
/**
* Scroll the viewport under the pointer. Positive `dy` scrolls down,
* negative up; `dx` scrolls horizontally. Both axes in one call.
*/
async scroll(options) {
await this._rpc("Scroll", { dx: options.dx ?? 0, dy: options.dy ?? 0 });
}
/**
* Type literal text. Fast by default — no per-character pacing, so long
* strings land in well under a second.
*/
async write(text) {
if (text.length === 0) return;
await this._rpc("SendKey", { text });
}
/**
* Press a key or chord: `press("enter")`, `press("ctrl+c")`,
* `press(["ctrl", "shift", "p"])`. Friendly names (enter, esc, cmd, …)
* map to X keysyms; unrecognized names pass through verbatim.
*/
async press(key) {
const { modifiers, key: finalKey } = chordParts(key);
await this._rpc("SendKey", { key: finalKey, modifiers });
}
/**
* Execute an ordered batch of actions in a single request.
*
* The whole batch is validated before anything runs, then executed under
* the sandbox's input lock — no other input can interleave. Execution
* stops at the first failing action. This is the fast path for models
* that emit several actions per turn.
*
* @example
* ```typescript
* await sandbox.desktop.actions([
* { type: "click", x: 640, y: 32 },
* { type: "write", text: "https://example.com" },
* { type: "press", key: "enter" },
* ])
* ```
*/
async actions(actions) {
if (actions.length === 0) return;
await this._rpc("SendActions", { actions: actions.map(actionBody) });
}
/**
* Run an ordered batch and capture the frame after it, in one request:
* the act-then-look turn of an agent loop as a single round trip. Same
* validation and stop-at-first-failure semantics as `actions()`; the
* frame is captured even when the batch stops early.
*
* @example
* ```typescript
* const { screenshot } = await sandbox.desktop.step(
* [{ type: "click", x: 640, y: 400 }],
* { waitForChange: true },
* )
* ```
*/
async step(actions, options = {}) {
if (actions.length === 0) {
throw new Error("step: actions is empty");
}
const raw = await this._rpc(
"Step",
{
actions: actions.map(actionBody),
settleMs: options.settleMs ?? 0,
...options.waitForChange ? { waitForChange: true } : {},
// Sent only when set, so a sandbox that predates it never sees it.
...options.quietMs ? { quietMs: options.quietMs } : {},
...formatBody(options.format)
},
{ maxBytes: MAX_SCREENSHOT_RESPONSE_BYTES }
);
const result = { executed: raw.executed ?? 0 };
if (raw.actionError) result.actionError = raw.actionError;
if (options.waitForChange) result.changed = raw.changed === true;
if (raw.screenshot?.image !== void 0) {
result.screenshot = decodeScreenshot(raw.screenshot);
} else {
result.screenshotError = raw.captureError || "Step response missing image data";
}
const phases = [raw.queueMs, raw.actionsMs, raw.settleMs, raw.captureMs];
if (phases.some((ms) => ms !== void 0)) {
result.timings = {
queueMs: raw.queueMs ?? 0,
actionsMs: raw.actionsMs ?? 0,
settleMs: raw.settleMs ?? 0,
captureMs: raw.captureMs ?? 0
};
}
return result;
}
/**
* Resize the virtual display. Width must be a multiple of 8 between 320
* and 8192; height between 200 and 8192. Takes effect live — no restart.
*/
async resize(width, height) {
await this._rpc("Resize", { width, height });
}
/**
* Publish the live desktop viewer (noVNC) and return its browser URL.
*
* Under a private preview policy the URL carries a short-lived signed
* credential, as `getSignedPreviewUrl()` does: the edge turns it into a
* cookie on first navigation, which noVNC's WebSocket then presents.
*/
async getStreamUrl(options = {}) {
await this._deps.refreshActivate();
const access = await this._deps.publishStreamPort();
const base = this._deps.streamBaseUrl();
const params = new URLSearchParams({ autoconnect: "1", resize: "scale" });
if (options.viewOnly) params.set("view_only", "1");
if (access === "private") {
const credential = await this._deps.mintStreamToken();
params.set(credential.queryParam, credential.token);
}
return `${base}/vnc.html?${params.toString()}`;
}
async _pointer(body) {
await this._rpc("SendPointer", body);
}
/**
* One unary DesktopService call, Connect JSON protocol: a plain POST of
* proto-JSON to the procedure path. Paused sandboxes resume via the shared
* token-retry path.
*/
async _rpc(method, body, opts = {}) {
const send = (token) => request({
method: "POST",
url: `${this._dataPlaneBaseUrl}${RPC_BASE}/${method}`,
headers: {
...this._routingHeaders,
...routingHintHeaders(this._deps),
"X-Access-Token": token
},
body,
maxBytes: opts.maxBytes
});
return withTokenRetry(this._deps, send);
}
};
// src/types.ts
function toSandboxInfo(raw) {
if (!raw.id) {
throw new SandboxError("Invalid API response: missing sandbox id");
}
if (!raw.status) {
throw new SandboxError("Invalid API response: missing sandbox status");
}
if (!raw.created_at) {
throw new SandboxError("Invalid API response: missing created_at");
}
return {
id: raw.id,
name: raw.name ?? "",
status: raw.status,
vcpuCount: raw.vcpu_count ?? 0,
memoryMib: raw.memory_mib ?? 0,
memoryMaxMib: raw.memory_max_mib ?? void 0,
memoryCurrentMib: raw.memory_current_mib ?? void 0,
memoryShrinkAfterSeconds: raw.memory_shrink_after_seconds ?? void 0,
vcpuMax: raw.vcpu_max ?? void 0,
createdAt: new Date(raw.created_at),
timeoutSeconds: raw.timeout_seconds ?? void 0,
idleTimeoutSeconds: raw.idle_timeout_seconds ?? void 0,
autoDeleteSeconds: raw.auto_delete_seconds ?? void 0,
autoDeleteAt: raw.auto_delete_at ? new Date(raw.auto_delete_at) : void 0,
network: raw.network ? { allowOut: raw.network.allow_out, denyOut: raw.network.deny_out } : void 0,
metadata: raw.metadata ?? {},
previewAccess: raw.preview_access ?? "legacy_public",
secrets: raw.secrets?.map((s) => ({
envKey: s.env_key ?? "",
secretName: s.secret_name ?? "",
revoked: s.revoked
})),
sourceSnapshotId: raw.source_snapshot_id ?? void 0
};
}
function toSnapshotInfo(raw) {
if (!raw.id || !raw.sandbox_id || !raw.status || !raw.created_at) {
throw new SandboxError(
"Invalid API response: snapshot missing id, sandbox_id, status or created_at"
);
}
return {
id: raw.id,
sandboxId: raw.sandbox_id,
templateId: raw.template_id ?? void 0,
kind: raw.kind ?? "mem+fs",
status: raw.status,
name: raw.name ?? void 0,
sizeBytes: raw.size_bytes ?? 0,
resources: {
vcpuCount: raw.resources?.vcpu_count ?? 0,
memoryMib: raw.resources?.memory_mib ?? 0,
diskMib: raw.resources?.disk_mib ?? 0,
memoryMaxMib: raw.resources?.memory_max_mib ?? void 0,
vcpuMax: raw.resources?.vcpu_max ?? void 0
},
createdAt: new Date(raw.created_at),
readyAt: raw.ready_at ? new Date(raw.ready_at) : void 0
};
}
function toTemplateInfo(raw, latestBuildId) {
if (!raw.id) {
throw new SandboxError("Invalid API response: missing template id");
}
if (!raw.name) {
throw new SandboxError("Invalid API response: missing template name");
}
if (!raw.status) {
throw new SandboxError("Invalid API response: missing template status");
}
if (!raw.team_id) {
throw new SandboxError("Invalid API response: missing team_id");
}
if (!raw.created_at) {
throw new SandboxError("Invalid API response: missing created_at");
}
return {
id: raw.id,
name: raw.name,
teamId: raw.team_id,
status: raw.status,
vcpu: raw.vcpu ?? 0,
memoryMib: raw.memory_mib ?? 0,
memoryMaxMib: raw.memory_max_mib ?? void 0,
memoryShrinkAfterSeconds: raw.memory_shrink_after_seconds ?? void 0,
vcpuMax: raw.vcpu_max ?? void 0,
diskMib: raw.disk_mib ?? 0,
sizeBytes: raw.size_bytes,
errorMessage: raw.error_message,
createdAt: new Date(raw.created_at),
builtAt: raw.built_at ? new Date(raw.built_at) : void 0,
latestBuildId: latestBuildId ?? raw.latest_build_id
};
}
function toTemplateBuildInfo(raw) {
if (!raw.id) {
throw new SandboxError("Invalid API response: missing build id");
}
if (!raw.template_id) {
throw new SandboxError("Invalid API response: missing template_id");
}
if (!raw.status) {
throw new SandboxError("Invalid API response: missing build status");
}
if (!raw.build_spec_hash) {
throw new SandboxError("Invalid API response: missing build_spec_hash");
}
if (!raw.created_at) {
throw new SandboxError("Invalid API response: missing created_at");
}
return {
id: raw.id,
templateId: raw.template_id,
status: raw.status,
buildSpecHash: raw.build_spec_hash,
errorMessage: raw.error_message,
startedAt: raw.started_at ? new Date(raw.started_at) : void 0,
finalizedAt: raw.finalized_at ? new Date(raw.finalized_at) : void 0,
createdAt: new Date(raw.created_at)
};
}
function toBuildLogEvent(raw) {
if (!raw.timestamp) {
throw new SandboxError("Invalid log event: missing timestamp");
}
if (!raw.stream) {
throw new SandboxError("Invalid log event: missing stream");
}
return {
timestamp: new Date(raw.timestamp),
stream: raw.stream,
text: raw.text ?? "",
finished: raw.finished,
status: raw.status
};
}
function buildStepsToApi(steps) {
return [...steps];
}
function toSecretInfo(raw) {
if (!raw.id) {
throw new SandboxError("Invalid API response: missing secret id");
}
if (!raw.name) {
throw new SandboxError("Invalid API response: missing secret name");
}
if (!raw.auth_type) {
throw new SandboxError("Invalid API response: missing auth_type");
}
if (!raw.created_at) {
throw new SandboxError("Invalid API response: missing created_at");
}
return {
id: raw.id,
name: raw.name,
authType: raw.auth_type,
authConfig: raw.auth_config ?? {},
providerShortcut: raw.provider_shortcut ?? void 0,
hosts: raw.hosts ?? [],
createdAt: new Date(raw.created_at),
updatedAt: new Date(raw.updated_at ?? raw.created_at),
lastUsedAt: raw.last_used_at ? new Date(raw.last_used_at) : void 0
};
}
function secretCreateBody(options) {
const body = {
name: options.name,
value: options.value
};
if (options.provider !== void 0) {
body.provider = options.provider;
}
if (options.auth !== void 0) {
body.auth = "perHost" in options.auth ? { per_host: options.auth.perHost } : options.auth;
}
if (options.hosts !== void 0) {
body.hosts = options.hosts;
}
return body;
}
function toProviderShortcut(raw) {
if (!raw.name) {
throw new SandboxError("Invalid API response: missing provider name");
}
return {
name: raw.name,
display: raw.display ?? raw.name,
authType: raw.auth_type ?? "bearer",
authConfig: raw.auth_config ?? {},
hosts: raw.hosts ?? [],
tokenShape: raw.token_shape ?? ""
};
}
function toProxyAuditEvent(raw) {
if (raw.id === void 0) {
throw new SandboxError("Invalid audit event: missing id");
}
if (!raw.ts) {
throw new SandboxError("Invalid audit event: missing ts");
}
return {
id: raw.id,
ts: new Date(raw.ts),
sandboxId: raw.sandbox_id ?? "",
sandboxName: raw.sandbox_name ?? void 0,
secretId: raw.secret_id,
method: raw.method ?? "",
host: raw.host ?? "",
path: raw.path ?? "",
status: raw.status ?? 0,
upstreamStatus: raw.upstream_status,
latencyMs: raw.latency_ms,
errorCode: raw.error_code
};
}
function toSecretSandboxBinding(raw) {
return {
sandboxId: raw.sandbox_id ?? "",
sandboxName: raw.sandbox_name ?? "",
envKey: raw.env_key ?? "",
status: raw.status ?? "active"
};
}
function toNetworkEvent(raw) {
if (raw.id === void 0) {
throw new SandboxError("Invalid network event: missing id");
}
if (!raw.kind) {
throw new SandboxError("Invalid network event: missing kind");
}
if (!raw.ts) {
throw new SandboxError("Invalid network event: missing ts");
}
return {
kind: raw.kind,
id: raw.id,
ts: new Date(raw.ts),
host: raw.host,
dstIp: raw.dst_ip,
dstPort: raw.dst_port,
verdict: raw.verdict,
matchRule: raw.match_rule,
bytesSent: raw.bytes_sent,
bytesRecv: raw.bytes_recv,
method: raw.method,
path: raw.path,
status: raw.status,
upstreamStatus: raw.upstream_status,
latencyMs: raw.latency_ms,
secretId: raw.secret_id,
errorCode: raw.error_code
};
}
function toNetworkLogPage(raw) {
return {
events: (raw.data ?? []).map(toNetworkEvent),
nextCursor: raw.next_cursor ?? void 0,
hasMore: raw.has_more ?? false
};
}
// src/Provider.ts
var Provider = class {
/** List the built-in provider shortcuts, in catalog order. */
static async list(options = {}) {
const config = resolveConfig(options);
const raw = await request({
method: "GET",
url: `${config.baseUrl}/providers`,
headers: { "X-API-Key": config.apiKey },
signal: options.signal
});
return raw.map(toProviderShortcut);
}
};
// src/commandSession.ts
var EXEC_SUBPROTOCOL = "superserve.exec.v1";
var TOKEN_PREFIX = "token.";
var CH_STDIN = 0;
var CH_STDOUT = 1;
var CH_STDERR = 2;
var STDIN_CHUNK_BYTES = 32 * 1024;
var encoder = new TextEncoder();
async function spawnCommand(deps, command, options) {
if (typeof WebSocket === "undefined") {
throw new SandboxError(
"commands.spawn requires a global WebSocket (Node 22+, a browser, or a polyfill)."
);
}
const url = `wss://boxd-${deps.sandboxId}.${deps.sandboxHost}/exec/connect`;
const gate = options.startupSignal ? composeSignals(options.startupSignal, options.signal) : { signal: options.signal, release: () => {
} };
const startup = gate.signal;
if (startup?.aborted) throw abortReason(startup);
let ws;
try {
ws = await dialWithResume(deps, url, startup);
} finally {
gate.release();
}
if (startup?.aborted) {
ws.close();
throw abortReason(startup);
}
ws.send(JSON.stringify(buildStart(command, options)));
return new Session(ws, options);
}
function buildStart(command, o) {
const start = { command };
if (o.cwd !== void 0) start.working_dir = o.cwd;
if (o.user !== void 0) start.user = o.user;
if (o.env !== void 0) start.env = o.env;
if (o.timeoutMs !== void 0) start.timeout_s = Math.ceil(o.timeoutMs / 1e3);
return start;
}
async function dialWithResume(deps, url, signal) {
if (routingHintExpired(deps)) await abortable(deps.refreshActivate(), signal);
try {
return await dial(
url,
deps.getAccessToken(),
deps.getRoutingHint?.(),
signal
);
} catch (err) {
if (signal?.aborted || !(err instanceof SandboxError)) throw err;
const fresh = await abortable(deps.refreshActivate(), signal);
return await dial(url, fresh, deps.getRoutingHint?.(), signal);
}
}
function abortable(p, signal) {
if (!signal) return p;
return new Promise((resolve, reject) => {
if (signal.aborted) {
reject(abortReason(signal));
return;
}
const onAbort = () => reject(abortReason(signal));
signal.addEventListener("abort", onAbort, { once: true });
p.then(resolve, reject).finally(
() => signal.removeEventListener("abort", onAbort)
);
});
}
function dial(url, token, hint, signal) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(abortReason(signal));
return;
}
const ws = new WebSocket(url, [
EXEC_SUBPROTOCOL,
TOKEN_PREFIX + token,
...hint ? ["route." + hint] : []
]);
ws.binaryType = "arraybuffer";
const cleanup = () => {
ws.removeEventListener("open", onOpen);
ws.removeEventListener("error", onError);
ws.removeEventListener("close", onClose);
signal?.removeEventListener("abort", onAbort);
};
const onOpen = () => {
cleanup();
resolve(ws);
};
const onError = () => {
cleanup();
reject(new SandboxError("exec/connect: connection failed"));
};
const onClose = (ev) => {
cleanup();
reject(
new SandboxError(`exec/connect: closed before open (code ${ev.code})`)
);
};
const onAbort = () => {
cleanup();
const swallow = () => {
};
ws.addEventListener("error", swallow);
ws.addEventListener(
"close",
() => ws.removeEventListener("error", swallow),
{ once: true }
);
ws.close();
reject(abortReason(signal));
};
ws.addEventListener("open", onOpen);
ws.addEventListener("error", onError);
ws.addEventListener("close", onClose);
signal?.addEventListener("abort", onAbort, { once: true });
});
}
var Session = class {
constructor(ws, options) {
// Streaming decoders carry partial multi-byte runes across frame boundaries.
this._outDecoder = new TextDecoder();
this._errDecoder = new TextDecoder();
this._stdout = "";
this._stderr = "";
this._settled = false;
this._ws = ws;
this._result = new Promise((res, rej) => {
this._resolve = res;
this._reject = rej;
});
this._result.catch(() => {
});
this.stdin = {
// No-op once the socket is closing/closed, instead of throwing.
write: (data) => {
if (ws.readyState !== WebSocket.OPEN) return;
const bytes = typeof data === "string" ? encoder.encode(data) : data;
for (let off = 0; off < bytes.length; off += STDIN_CHUNK_BYTES) {
const chunk = bytes.subarray(off, off + STDIN_CHUNK_BYTES);
const frame = new Uint8Array(chunk.length + 1);
frame[0] = CH_STDIN;
frame.set(chunk, 1);
ws.send(frame);
}
},
close: () => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: "stdin_close" }));
}
}
};
ws.addEventListener("message", (ev) => this._onMessage(ev, options));
ws.addEventListener("close", (ev) => this._onClose(ev));
const signal = options.signal;
if (signal) {
if (signal.aborted) this._abort();
else {
const onAbort = () => this._abort();
signal.addEventListener("abort", onAbort, { once: true });
void this._result.finally(
() => signal.removeEventListener("abort", onAbort)
);
}
}
}
kill(signal = "SIGTERM") {
if (this._ws.readyState === WebSocket.OPEN) {
this._ws.send(JSON.stringify({ type: "signal", name: signal }));
}
}
wait() {
return this._result;
}
// Kill the process, close the socket, and resolve once the session settles
// (swallowing the connection-closed rejection — cleanup isn't a failure).
close() {
this._abort();
return this._result.then(
() => void 0,
() => void 0
);
}
async [Symbol.asyncDispose]() {
await this.close();
}
_abort() {
this.kill();
if (this._ws.readyState <= WebSocket.OPEN) this._ws.close();
}
_onMessage(ev, options) {
if (typeof ev.data === "string") {
this._onLifecycle(ev.data);
return;
}
const view = new Uint8Array(ev.data);
if (view.length === 0) return;
const payload = view.subarray(1);
if (view[0] === CH_STDOUT) {
const text = this._outDecoder.decode(payload, { stream: true });
this._stdout += text;
if (text) options.onStdout?.(text);
} else if (view[0] === CH_STDERR) {
const text = this._errDecoder.decode(payload, { stream: true });
this._stderr += text;
if (text) options.onStderr?.(text);
}
}
_onLifecycle(raw) {
let ev;
try {
ev = JSON.parse(raw);
} catch {
return;
}
if (ev.error) this._stderr += ev.error;
if (ev.finished) this._finish(ev.exit_code ?? 0);
}
_onClose(ev) {
const detail = ev.code === 1009 ? "a message exceeded the server's size limit \u2014 usually an oversized command string; keep the command small and send bulk data via stdin or the files API" : ev.reason || `close code ${ev.code}`;
this._fail(
new SandboxError(
`exec/connect: connection closed before the command finished (${detail})`
)
);
}
_finish(exitCode) {
if (this._settled) return;
this._settled = true;
this._flush();
this._resolve({
stdout: this._stdout,
stderr: this._stderr,
exitCode,
truncated: false
});
}
_fail(err) {
if (this._settled) return;
this._settled = true;
this._flush();
this._reject(err);
}
// Emit any bytes still buffered in the streaming decoders.
_flush() {
this._stdout += this._outDecoder.decode();
this._stderr += this._errDecoder.decode();
}
};
// src/commands.ts
var MAX_EXEC_RESPONSE_BYTES = 10 * 1024 * 1024;
var SERVER_DEADLINE_MARGIN_MS = 5e3;
var MAX_COMMAND_TIMEOUT_MS = Math.floor((2 ** 31 - 1 - SERVER_DEADLINE_MARGIN_MS) / 1e3) * 1e3;
function commandTimeoutSeconds(timeoutMs) {
if (timeoutMs === void 0 || timeoutMs === 0) return void 0;
if (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > MAX_COMMAND_TIMEOUT_MS) {
throw new ValidationError(
`timeoutMs must be between 0 and ${MAX_COMMAND_TIMEOUT_MS}, got ${timeoutMs}`
);
}
return Math.ceil(timeoutMs / 1e3);
}
function clientDeadlineMs(timeoutS) {
return timeoutS === void 0 ? void 0 : timeoutS * 1e3 + SERVER_DEADLINE_MARGIN_MS;
}
var Commands = class {
/** @internal */
constructor(_deps) {
this._deps = _deps;
const target = dataPlaneTarget(_deps.sandboxId, _deps.sandboxHost);
this._dataPlaneBaseUrl = target.url;
this._routingHeaders = target.headers;
}
/**
* Execute a command inside the sandbox.
*
* If `onStdout` or `onStderr` callbacks are provided, the command is
* streamed via SSE. Otherwise, it runs synchronously (waits for completion).
*
* Paused sandboxes are transparently resumed before execution.
*
* @example
* ```typescript
* // Synchronous
* const result = await sandbox.commands.run("echo hello")
* console.log(result.stdout) // "hello\n"
*
* // Streaming
* const result = await sandbox.commands.run("npm start", {
* onStdout: (data) => process.stdout.write(data),
* onStderr: (data) => process.stderr.write(data),
* timeoutMs: 120_000,
* })
* ```
*/
async run(command, options = {}) {
const { cwd, user, env, timeoutMs, onStdout, onStderr } = options;
const isStreaming = onStdout !== void 0 || onStderr !== void 0;
const timeoutS = commandTimeoutSeconds(timeoutMs);
const body = { command };
if (cwd !== void 0) body.working_dir = cwd;
if (user !== void 0) body.user = user;
if (env !== void 0) body.env = env;
if (timeoutS !== void 0) body.timeout_s = timeoutS;
if (isStreaming) {
return this._runStreaming(body, timeoutS, options);
}
return this._runSync(body, timeoutS, options);
}
/**
* Spawn a command and return a live, full-duplex session.
*
* Unlike `run` (one-shot), `spawn` hands back a handle while the process is
* still running: stream output via `onStdout`/`onStderr`, write to its
* `stdin`, `kill` it, and `await session.wait()` for the exit result.
*
* Release the session when you're done (use `await using`, or call `wait()`
* or `close()`) so the socket and its reader are cleaned up.
*
* A paused sandbox is resumed transparently before the session opens.
*
* @example
* ```typescript
* const session = await sandbox.commands.spawn("python -i", {
* onStdout: (data) => process.stdout.write(data),
* })
* session.stdin.write("print(2 + 2)\n")
* session.stdin.close()
* const { exitCode } = await session.wait()
* ```
*/
spawn(command, options = {}) {
return spawnCommand(this._deps, command, options);
}
async _runSync(body, timeoutS, options) {
const send = (token) => request({
method: "POST",
url: `${this._dataPlaneBaseUrl}/exec`,
headers: {
...this._routingHeaders,
...routingHintHeaders(this._deps),
"X-Access-Token": token
},
body,
// Add a 5s buffer so the server-side command timeout fires first
// and returns its proper response before the client aborts.
timeoutMs: clientDeadlineMs(timeoutS),
signal: options.signal,
// The data plane is untrusted — bound the buffered response so a
// command's runaway stdout/stderr can't exhaust the caller's memory.
maxBytes: options.maxOutputBytes ?? MAX_EXEC_RESPONSE_BYTES
});
const raw = await withTokenRetry(this._deps, send);
return {
stdout: raw.stdout ?? "",
stderr: raw.stderr ?? "",
exitCode: raw.exit_code ?? 0,
truncated: raw.truncated ?? false
};
}
async _runStreaming(body, timeoutS, options) {
const send = async (token) => this._consumeStream(
`${this._dataPlaneBaseUrl}/exec/stream`,
{
...this._routingHeaders,
...routingHintHeaders(this._deps),
"X-Access-Token": token
},
body,
timeoutS,
options
);
return withTokenRetry(this._deps, send);
}
async _consumeStream(url, headers, body, timeoutS, options) {
let stdout = "";
let stderr = "";
let exitCode = 0;
let error;
let sawFinished = false;
await streamSSE({
url,
headers,
body,
timeoutMs: clientDeadlineMs(timeoutS),
signal: options.signal,
onEvent: (event) => {
if (event.stdout) {
stdout += event.stdout;
options.onStdout?.(event.stdout);
}
if (event.stderr) {
stderr += event.stderr;
options.onStderr?.(event.stderr);
}
if (event.finished) {
sawFinished = true;
exitCode = event.exit_code ?? 0;
error = event.error;
}
}
});
if (!sawFinished) {
throw new SandboxError(
"Command stream ended without a finished event (possible network disconnect)"
);
}
if (error) {
stderr += error;
}
return { stdout, stderr, exitCode, truncated: false };
}
};
// src/files.ts
function validatePath(path) {
if (!path.startsWith("/")) {
throw new ValidationError(`Path must start with "/": ${path}`);
}
if (path.split("/").some((seg) => seg === "..")) {
throw new ValidationError(`Path must not contain ".." segments: ${path}`);
}
}
var Files = class {
/** @internal */
constructor(_deps) {
this._deps = _deps;
const target = dataPlaneTarget(_deps.sandboxId, _deps.sandboxHost);
this._dataPlaneBaseUrl = target.url;
this._routingHeaders = target.headers;
}
/**
* Write a file to the sandbox at the given absolute path.
*
* Parent directories are created automatically by the sandbox agent.
* The path must start with `/` and must not contain `..` segments.
*
* @example
* ```typescript
* await sandbox.files.write("/app/config.json", '{"key": "value"}')
* await sandbox.files.write("/app/binary.dat", buffer)
* ```
*/
async write(path, content, options = {}) {
validatePath(path);
const body = toBody(content);
const url = `${this._dataPlaneBaseUrl}/files?path=${encodeURIComponent(path)}`;
await withTokenRetry(
this._deps,
(token) => uploadBytes({
url,
headers: {
...this._routingHeaders,
...routingHintHeaders(this._deps),
"X-Access-Token": token
},
body,
timeoutMs: options.timeoutMs,
signal: options.signal
})
);
}
/**
* Read a file from the sandbox as raw bytes.
*
* Downloads are capped at 2 GiB by default; override via `maxBytes`.
*
* @example
* ```typescript
* const bytes = await sandbox.files.read("/app/config.json")
* ```
*/
async read(path, options = {}) {
validatePath(path);
const url = `${this._dataPlaneBaseUrl}/files?path=${encodeURIComponent(path)}`;
return withTokenRetry(
this._deps,
(token) => downloadBytes({
url,
headers: {
...this._routingHeaders,
...routingHintHeaders(this._deps),
"X-Access-Token": token
},
timeoutMs: options.timeoutMs,
signal: options.signal,
maxBytes: options.maxBytes
})
);
}
/**
* Read a file from the sandbox as a UTF-8 string.
*
* @example
* ```typescript
* const text = await sandbox.files.readText("/app/config.json")
* console.log(text) // '{"key": "value"}'
* ```
*/
async readText(path, options = {}) {
const bytes = await this.read(path, options);
return new TextDecoder().decode(bytes);
}
/**
* Download a directory from the sandbox as a ZIP archive.
*
* Returns the raw bytes of a zip file whose entries are prefixed with the
* directory's base name (e.g. `<dir>/file.txt`). Symlinks are skipped.
*
* The server decides file-vs-directory: if `path` points at a regular file,
* its bytes are streamed back as-is (not zipped) — use `read()` for files.
*
* Large directories can exceed the default 30s timeout; pass `timeoutMs`
* to allow more time.
*
* Downloads are capped at 2 GiB by default; override via `maxBytes`.
*
* @example
* ```typescript
* import { writeFileSync } from "node:fs"
*
* const zip = await sandbox.files.downloadDir("/app/output")
* writeFileSync("output.zip", zip)
* ```
*/
async downloadDir(path, options = {}) {
validatePath(path);
const url = `${this._dataPlaneBaseUrl}/files?path=${encodeURIComponent(
path
)}&format=zip`;
return withTokenRetry(
this._deps,
(token) => downloadBytes({
url,
headers: {
...this._routingHeaders,
...routingHintHeaders(this._deps),
"X-Access-Token": token
},
timeoutMs: options.timeoutMs,
signal: options.signal,
maxBytes: options.maxBytes
})
);
}
};
function toBody(content) {
if (typeof content === "string") {
return new Blob([content]);
}
if (content instanceof Blob) {
return content;
}
if (content instanceof ArrayBuffer) {
return new Blob([content]);
}
if (content instanceof Uint8Array) {
const copy = new ArrayBuffer(content.byteLength);
new Uint8Array(copy).set(content);
return new Blob([copy]);
}
return new Blob([content]);
}
// src/Snapshot.ts
var DEFAULT_SNAPSHOT_TIMEOUT_MS = 15 * 6e4;
var DEFAULT_SNAPSHOT_POLL_MS = 2e3;
var Snapshot = class _Snapshot {
/** @internal — use `sandbox.snapshot()` or `Snapshot.get()` instead. */
constructor(info, config) {
this.id = info.id;
this.sandboxId = info.sandboxId;
this.templateId = info.templateId;
this.kind = info.kind;
this.status = info.status;
this.name = info.name;
this.sizeBytes = info.sizeBytes;
this.resources = info.resources;
this.createdAt = info.createdAt;
this.readyAt = info.readyAt;
this._config = config;
}
// -------------------------------------------------------------------------
// Static factories
// -------------------------------------------------------------------------
/** Fetch a snapshot by ID. */
static async get(snapshotId, options = {}) {
const config = resolveConfig(options);
return new _Snapshot(
await fetchSnapshot(config, snapshotId, options.signal),
config
);
}
/**
* List a sandbox's snapshots, newest first. Snapshots outlive their
* sandbox, so this works for a deleted sandbox too.
*/
static async list(sandboxId, options = {}) {
const config = resolveConfig(options);
const params = new URLSearchParams();
if (options.limit !== void 0) params.set("limit", String(options.limit));
if (options.offset !== void 0)
params.set("offset", String(options.offset));
const qs = params.toString() ? `?${params.toString()}` : "";
const raw = await request({
method: "GET",
url: `${config.baseUrl}/sandboxes/${sandboxId}/snapshots${qs}`,
headers: { "X-API-Key": config.apiKey },
signal: options.signal
});
return raw.map(toSnapshotInfo);
}
/** Delete a snapshot by ID. Idempotent — no error if it's already gone. */
static async deleteById(snapshotId, options = {}) {
const config = resolveConfig(options);
await deleteSnapshot(config, snapshotId, options.signal);
}
// -------------------------------------------------------------------------
// Instance methods
// -------------------------------------------------------------------------
/** Re-fetch the latest state of this snapshot. */
async getInfo(options = {}) {
return fetchSnapshot(this._config, this.id, options.signal);
}
/** Rename this snapshot. Returns the renamed snapshot. */
async rename(name, options = {}) {
const raw = await request({
method: "PATCH",
url: `${this._config.baseUrl}/snapshots/${this.id}`,
headers: { "X-API-Key": this._config.apiKey },
body: { name },
signal: options.signal
});
return new _Snapshot(toSnapshotInfo(raw), this._config);
}
/**
* Delete this snapshot. Sandboxes already created from it are unaffected.
* Idempotent.
*/
async delete(options = {}) {
await deleteSnapshot(this._config, this.id, options.signal);
}
/**
* Wait until the snapshot is `ready`. Resolves at once when it already is;
* throws `SandboxError` when it failed or was deleted, and `TimeoutError`
* when it is still settling after `timeoutMs`.
*/
async waitUntilReady(options = {}) {
return waitForSnapshot(this._config, this, options);
}
};
async function fetchSnapshot(config, snapshotId, signal) {
const raw = await request({
method: "GET",
url: `${config.baseUrl}/snapshots/${snapshotId}`,
headers: { "X-API-Key": config.apiKey },
signal
});
return toSnapshotInfo(raw);
}
async function deleteSnapshot(config, snapshotId, signal) {
try {
await requestVoid({
method: "DELETE",
url: `${config.baseUrl}/snapshots/${snapshotId}`,
headers: { "X-API-Key": config.apiKey },
signal
});
} catch (err) {
if (!(err instanceof NotFoundError)) throw err;
}
}
var FINAL_CHECK_MS = 5e3;
async function waitForSnapshot(config, snapshot, options = {}) {
if (snapshot.status === "ready") return snapshot;
const timeoutMs = options.timeoutMs ?? DEFAULT_SNAPSHOT_TIMEOUT_MS;
const pollMs = options.pollIntervalMs ?? DEFAULT_SNAPSHOT_POLL_MS;
const deadlineAt = Date.now() + timeoutMs;
const stillSettling = (status) => new TimeoutError(
`Snapshot ${snapshot.id} still ${status} after ${timeoutMs}ms`
);
let current = snapshot;
for (; ; ) {
switch (current.status) {
case "ready":
return new Snapshot(current, config);
case "failed":
throw new SandboxError(`Snapshot ${snapshot.id} failed`);
case "deleting":
throw new SandboxError(`Snapshot ${snapshot.id} was deleted`);
}
const left = deadlineAt - Date.now();
if (left <= 0) throw stillSettling(current.status);
await sleep(Math.min(pollMs, left), options.signal);
const budget = AbortSignal.timeout(
Math.max(deadlineAt - Date.now(), FINAL_CHECK_MS)
);
const { signal, release } = composeSignals(budget, options.signal);
try {
current = await fetchSnapshot(config, snapshot.id, signal);
} catch (err) {
if (budget.aborted && !options.signal?.aborted) {
throw stillSettling(current.status);
}
if (err instanceof NotFoundError) {
throw new SandboxError(`Snapshot ${snapshot.id} was deleted`);
}
throw err;
} finally {
release();
}
}
}
// src/Volume.ts
function volumeInfo(raw) {
return {
id: raw.id,
name: raw.name,
capacityBytes: raw.capacity_bytes,
usedBytes: raw.used_bytes,
region: raw.region,
status: raw.status,
generation: raw.generation,
errorCode: raw.error_code,
createdAt: new Date(raw.created_at),
updatedAt: new Date(raw.updated_at)
};
}
function attachmentInfo(raw) {
return {
id: raw.id,
volumeId: raw.volume_id,
sandboxId: raw.sandbox_id,
mountPath: raw.mount_path,
readOnly: raw.read_only,
status: raw.status,
generation: raw.generation,
errorCode: raw.error_code,
leaseExpiresAt: new Date(raw.lease_expires_at),
createdAt: new Date(raw.created_at),
updatedAt: new Date(raw.updated_at)
};
}
function operationTimeout(value) {
if (value !== void 0 && (!Number.isFinite(value) || value <= 0)) {
throw new ValidationError("timeoutMs must be a positive finite number");
}
return value ?? 18e4;
}
function idempotencyKey(value) {
if (value !== void 0) return value;
return globalThis.crypto?.randomUUID?.() ?? "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
const random = Math.floor(Math.random() * 16);
return (c === "x" ? random : random & 3 | 8).toString(16);
});
}
var volumeSandboxIdPattern = /^(?:sb-([A-Za-z0-9]+)-)?([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
function sameVolumeSandbox(a, b) {
const left = volumeSandboxIdPattern.exec(a);
const right = volumeSandboxIdPattern.exec(b);
if (!left || !right || left[0] !== a || right[0] !== b) return a === b;
return left[2].toLowerCase() === right[2].toLowerCase() && (left[1] === void 0 || right[1] === void 0 || left[1] === right[1]);
}
function assertVolumeConnection(a, b) {
if (a.apiKey !== b.apiKey || a.baseUrl.replace(/\/+$/, "") !== b.baseUrl.replace(/\/+$/, "")) {
throw new ValidationError(
"Volume and sandbox must use the same API connection"
);
}
}
var Volume = class _Volume {
constructor(info, _config) {
this._config = _config;
this.id = info.id;
this.name = info.name;
this.capacityBytes = info.capacityBytes;
this.usedBytes = info.usedBytes;
this.region = info.region;
this.status = info.status;
this.generation = info.generation;
this.errorCode = info.errorCode;
this.createdAt = info.createdAt;
this.updatedAt = info.updatedAt;
}
/** @internal Used before creating a new sandbox with existing volume handles. */
_assertConnection(config) {
assertVolumeConnection(this._config, config);
}
static async create(options) {
const config = resolveConfig(options);
const body = {
name: options.name,
idempotency_key: idempotencyKey(options.idempotencyKey)
};
if (options.capacityBytes !== void 0)
body.capacity_bytes = options.capacityBytes;
const raw = await request({
method: "POST",
url: `${config.baseUrl}/volumes`,
headers: { "X-API-Key": config.apiKey },
body,
signal: options.signal,
timeoutMs: operationTimeout(options.timeoutMs)
});
return new _Volume(volumeInfo(raw), config);
}
static async connect(nameOrId, options = {}) {
const timeoutMs = options.timeoutMs === void 0 ? void 0 : operationTimeout(options.timeoutMs);
const config = resolveConfig(options);
const raw = await request({
method: "GET",
url: `${config.baseUrl}/volumes/${encodeURIComponent(nameOrId)}`,
headers: { "X-API-Key": config.apiKey },
signal: options.signal,
timeoutMs
});
return new _Volume(volumeInfo(raw), config);
}
static async list(options = {}) {
if (options.limit !== void 0 && (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 100)) {
throw new ValidationError("limit must be an integer between 1 and 100");
}
const config = resolveConfig(options);
const query = options.limit === void 0 ? "" : `?limit=${options.limit}`;
const raw = await request({
method: "GET",
url: `${config.baseUrl}/volumes${query}`,
headers: { "X-API-Key": config.apiKey },
signal: options.signal
});
return raw.map(volumeInfo);
}
static async deleteById(nameOrId, options = {}) {
const config = resolveConfig(options);
try {
await requestVoid({
method: "DELETE",
url: `${config.baseUrl}/volumes/${encodeURIComponent(nameOrId)}`,
headers: { "X-API-Key": config.apiKey },
signal: options.signal
});
} catch (error) {
if (!(error instanceof NotFoundError)) throw error;
}
}
async getInfo(options = {}) {
const raw = await request({
method: "GET",
url: `${this._config.baseUrl}/volumes/${encodeURIComponent(this.id)}`,
headers: { "X-API-Key": this._config.apiKey },
...options
});
return volumeInfo(raw);
}
async delete(options = {}) {
try {
await requestVoid({
method: "DELETE",
url: `${this._config.baseUrl}/volumes/${encodeURIComponent(this.id)}`,
headers: { "X-API-Key": this._config.apiKey },
...options
});
} catch (error) {
if (!(error instanceof NotFoundError)) throw error;
}
}
async attach(sandbox, options) {
if (typeof sandbox !== "string") sandbox._assertVolumeConfig(this._config);
const sandboxId = typeof sandbox === "string" ? sandbox : sandbox.id;
const raw = await request({
method: "POST",
url: `${this._config.baseUrl}/sandboxes/${encodeURIComponent(sandboxId)}/volumes`,
headers: { "X-API-Key": this._config.apiKey },
signal: options.signal,
timeoutMs: operationTimeout(options.timeoutMs),
body: {
volume_id: this.id,
mount_path: options.mountPath,
...options.readOnly === void 0 ? {} : { read_only: options.readOnly },
idempotency_key: idempotencyKey(options.idempotencyKey)
}
});
const attachment = attachmentInfo(raw);
if (attachment.status !== "mounted" || attachment.volumeId !== this.id || !sameVolumeSandbox(attachment.sandboxId, sandboxId) || attachment.mountPath !== options.mountPath || attachment.readOnly !== (options.readOnly ?? false)) {
throw new SandboxError(
"Volume attach response did not confirm the requested mount"
);
}
return attachment;
}
async listAttachments(options = {}) {
const raw = await request({
method: "GET",
url: `${this._config.baseUrl}/volumes/${encodeURIComponent(this.id)}/attachments`,
headers: { "X-API-Key": this._config.apiKey },
...options
});
return raw.map(attachmentInfo);
}
async getAttachment(attachmentId, options = {}) {
const info = await getVolumeAttachment(this._config, attachmentId, options);
if (info.volumeId !== this.id)
throw new ValidationError("Attachment belongs to a different volume");
return info;
}
async detach(attachmentId, options = {}) {
try {
await this.getAttachment(attachmentId, options);
} catch (error) {
if (error instanceof NotFoundError) return;
throw error;
}
await detachVolumeAttachment(this._config, attachmentId, options);
}
};
async function getVolumeAttachment(config, id, options = {}) {
const raw = await request({
method: "GET",
url: `${config.baseUrl}/volume-attachments/${encodeURIComponent(id)}`,
headers: { "X-API-Key": config.apiKey },
...options
});
return attachmentInfo(raw);
}
async function detachVolumeAttachment(config, id, options = {}) {
try {
await requestVoid({
method: "DELETE",
url: `${config.baseUrl}/volume-attachments/${encodeURIComponent(id)}`,
headers: { "X-API-Key": config.apiKey },
...options
});
} catch (error) {
if (!(error instanceof NotFoundError)) throw error;
}
}
// src/Sandbox.ts
function newIdempotencyKey() {
const uuid = globalThis.crypto?.randomUUID?.();
if (uuid) return uuid;
const rand = () => Math.random().toString(36).slice(2);
return `${Date.now().toString(36)}-${rand()}${rand()}`;
}
var DEFAULT_PAUSE_TIMEOUT_MS = 3e5;
var PAUSE_FAST_POLL_MS = 50;
var PAUSE_FAST_POLL_WINDOW_MS = 2e3;
var DEFAULT_PAUSE_POLL_MS = 1e3;
var ACTIVATE_PAUSING_RETRY_MS = 1e3;
var ACTIVATE_PAUSING_WINDOW_MS = 3e4;
var Sandbox = class _Sandbox {
/** @internal — Use Sandbox.create() or Sandbox.connect() instead. */
constructor(info, accessToken, config, routingHint) {
this._routeRevision = 0;
this._appliedRouteRevision = 0;
this._refreshInFlight = null;
this.id = info.id;
this.name = info.name;
this.status = info.status;
this.metadata = info.metadata;
this.previewAccess = info.previewAccess;
this.secrets = info.secrets;
this._accessToken = accessToken;
this._routingHint = routingHint;
this._config = config;
this.commands = new Commands({
sandboxId: this.id,
sandboxHost: config.sandboxHost,
getAccessToken: () => this._accessToken,
getRoutingHint: () => this._routingHint,
refreshActivate: () => this._refreshActivate()
});
this.files = new Files({
sandboxId: this.id,
sandboxHost: config.sandboxHost,
getAccessToken: () => this._accessToken,
getRoutingHint: () => this._routingHint,
refreshActivate: () => this._refreshActivate()
});
this.desktop = new Desktop({
sandboxId: this.id,
sandboxHost: config.sandboxHost,
getAccessToken: () => this._accessToken,
getRoutingHint: () => this._routingHint,
refreshActivate: () => this._refreshActivate(),
publishStreamPort: async () => (await this.publishPreviewPort(DESKTOP_STREAM_PORT)).access,
streamBaseUrl: () => this.getPreviewUrl(DESKTOP_STREAM_PORT),
mintStreamToken: () => this.getPreviewToken(DESKTOP_STREAM_PORT, { expiresInSeconds: 60 })
});
}
/** @internal Validate captured connection identity before volume requests. */
_assertVolumeConfig(config) {
assertVolumeConnection(this._config, config);
}
async attachVolume(volume, options) {
const resource = typeof volume === "string" ? await Volume.connect(volume, {
...this._config,
signal: options.signal,
timeoutMs: options.timeoutMs
}) : volume;
return resource.attach(this, options);
}
async detachVolume(attachmentId, options = {}) {
try {
const attachment = await getVolumeAttachment(
this._config,
attachmentId,
options
);
if (!sameVolumeSandbox(attachment.sandboxId, this.id))
throw new ValidationError("Attachment belongs to a different sandbox");
} catch (error) {
if (error instanceof NotFoundError) return;
throw error;
}
await detachVolumeAttachment(this._config, attachmentId, options);
}
/**
* POST a token-rotating endpoint (`/resume` or `/activate`) and update the
* cached token. `commands` and `files` read the token live, so they pick up
* the rotation transparently. Returns the new token. @internal
*/
async _postAndRotateToken(endpoint, signal) {
const revision = ++this._routeRevision;
const raw = await request({
method: "POST",
url: `${this._config.baseUrl}/sandboxes/${this.id}/${endpoint}`,
headers: { "X-API-Key": this._config.apiKey },
signal
});
if (!raw.access_token) {
throw new SandboxError(
`Invalid API response from POST /sandboxes/${this.id}/${endpoint}: missing access_token`
);
}
if (revision > this._appliedRouteRevision) {
this._appliedRouteRevision = revision;
this._accessToken = raw.access_token;
this._routingHint = raw.routing_hint;
}
return this._accessToken;
}
/**
* Slow-path fallback for data-plane AuthenticationError. Coalesces
* concurrent callers onto a single in-flight POST /activate so a
* paused-sandbox resume isn't claimed twice (the loser gets 409). @internal
*/
_refreshActivate() {
if (this._refreshInFlight) return this._refreshInFlight;
this._refreshInFlight = this._postAndRotateToken("activate").finally(() => {
this._refreshInFlight = null;
});
return this._refreshInFlight;
}
// -------------------------------------------------------------------------
// Static factory methods
// -------------------------------------------------------------------------
/**
* Create a new sandbox and return a ready-to-use `sandbox`.
*
* The request is synchronous: once it resolves, the sandbox is `active`
* and ready to execute commands and file operations.
*
* @example
* ```typescript
* const sandbox = await Sandbox.create({ name: "my-sandbox" })
* const result = await sandbox.commands.run("echo hello")
* ```
*/
static async create(options) {
const config = resolveConfig(options);
if ((options.volumes?.length ?? 0) > 128) {
throw new ValidationError(
"A new sandbox supports at most 128 volume mounts"
);
}
const volumeMounts = (options.volumes ?? []).map(
(mount) => Object.assign({}, mount)
);
const volumePaths = /* @__PURE__ */ new Set();
for (const mount of volumeMounts) {
if (volumePaths.has(mount.mountPath)) {
throw new ValidationError("Volume mount paths must be distinct");
}
volumePaths.add(mount.mountPath);
if (mount.volume instanceof Volume) mount.volume._assertConnection(config);
}
const body = { name: options.name };
if (options.timeoutSeconds !== void 0)
body.timeout_seconds = options.timeoutSeconds;
if (options.idleTimeoutSeconds !== void 0)
body.idle_timeout_seconds = options.idleTimeoutSeconds;
if (options.autoDeleteSeconds !== void 0)
body.auto_delete_seconds = options.autoDeleteSeconds;
if (options.fromTemplate !== void 0) {
body.from_template = typeof options.fromTemplate === "string" ? options.fromTemplate : options.fromTemplate.name ?? options.fromTemplate.id;
}
if (options.fromSnapshot !== void 0) {
body.from_snapshot = typeof options.fromSnapshot === "string" ? options.fromSnapshot : options.fromSnapshot.id;
}
if (options.metadata !== void 0) body.metadata = options.metadata;
if (options.envVars !== void 0) body.env_vars = options.envVars;
if (options.secrets !== void 0) body.secrets = options.secrets;
if (options.network) {
body.network = {
allow_out: options.network.allowOut,
deny_out: options.network.denyOut
};
}
if (options.previewAccess !== void 0)
body.preview_access = options.previewAccess;
const raw = await request({
method: "POST",
url: `${config.baseUrl}/sandboxes`,
headers: { "X-API-Key": config.apiKey },
body,
signal: options.signal
});
if (!raw.access_token) {
throw new SandboxError(
"Invalid API response from POST /sandboxes: missing access_token"
);
}
const sandbox = new _Sandbox(
toSandboxInfo(raw),
raw.access_token,
config,
raw.routing_hint
);
try {
for (const mount of volumeMounts) {
const combined = options.signal && mount.signal ? composeSignals(options.signal, mount.signal) : void 0;
try {
await sandbox.attachVolume(mount.volume, {
...mount,
signal: combined?.signal ?? options.signal ?? mount.signal
});
} finally {
combined?.release();
}
}
} catch (error) {
const cleanup = new AbortController();
const timer = setTimeout(() => cleanup.abort(), 3e4);
try {
await sandbox.kill({ signal: cleanup.signal });
} catch {
throw new SandboxError(
`Volume attachment failed and newly created sandbox ${sandbox.id} could not be deleted`,
void 0,
"volume_cleanup_failed",
{ cause: error }
);
} finally {
clearTimeout(timer);
}
throw error;
}
return sandbox;
}
/**
* Connect to an existing sandbox by ID.
*
* Calls `POST /activate` so the returned instance is guaranteed to be
* active (paused sandboxes are auto-resumed) with a fresh access token.
*
* @example
* ```typescript
* const sandbox = await Sandbox.connect("sandbox-uuid")
* ```
*/
static async connect(sandboxId, options = {}) {
const config = resolveConfig(options);
const deadline = Date.now() + ACTIVATE_PAUSING_WINDOW_MS;
let raw;
for (; ; ) {
try {
raw = await request({
method: "POST",
url: `${config.baseUrl}/sandboxes/${sandboxId}/activate`,
headers: { "X-API-Key": config.apiKey },
signal: options.signal
});
break;
} catch (err) {
if (!(err instanceof ConflictError) || err.code !== "sandbox_pausing" || deadline - Date.now() <= ACTIVATE_PAUSING_RETRY_MS) {
throw err;
}
await sleep(ACTIVATE_PAUSING_RETRY_MS, options.signal);
}
}
if (!raw.access_token) {
throw new SandboxError(
`Invalid API response from POST /sandboxes/${sandboxId}/activate: missing access_token`
);
}
return new _Sandbox(
toSandboxInfo(raw),
raw.access_token,
config,
raw.routing_hint
);
}
/**
* List sandboxes belonging to the authenticated team.
*
* @param options.metadata — Filter by metadata key-value pairs.
* @param options.status — Match one status or any status in a nonempty list.
* @param options.limit — Maximum rows to return.
* @param options.offset — Rows to skip; combine with `limit` to page.
*
* @example
* ```typescript
* const running = await Sandbox.list({ status: ["active", "starting", "resuming"] })
* const page = await Sandbox.list({ limit: 100, offset: 200 })
* const prodBoxes = await Sandbox.list({ metadata: { env: "prod" } })
* ```
*/
static async list(options = {}) {
const config = resolveConfig(options);
let url = `${config.baseUrl}/sandboxes`;
const params = new URLSearchParams();
for (const [key, value] of Object.entries(options.metadata ?? {})) {
params.set(`metadata.${key}`, value);
}
if (options.status !== void 0) {
const statuses = typeof options.status === "string" ? [options.status] : options.status;
if (statuses.length === 0)
throw new SandboxError("status must not be empty");
params.set("status", statuses.join(","));
}
if (options.limit !== void 0) params.set("limit", String(options.limit));
if (options.offset !== void 0)
params.set("offset", String(options.offset));
if (params.toString()) url += `?${params.toString()}`;
const raw = await request({
method: "GET",
url,
headers: { "X-API-Key": config.apiKey },
signal: options.signal
});
return raw.map(toSandboxInfo);
}
/**
* Delete a sandbox by ID.
*
* Idempotent: if the sandbox is already deleted, this is a no-op.
*/
static async killById(sandboxId, options = {}) {
const config = resolveConfig(options);
try {
await requestVoid({
method: "DELETE",
url: `${config.baseUrl}/sandboxes/${sandboxId}`,
headers: { "X-API-Key": config.apiKey },
signal: options.signal,
// Don't drop a mid-transition sandbox on bulk delete (see retryConflict).
retryConflict: true
});
} catch (err) {
if (!(err instanceof NotFoundError)) throw err;
}
}
/**
* Update a sandbox by ID without holding a live instance.
*
* Unlike `connect(id).then(s => s.update(...))`, this does not activate the
* sandbox — a paused sandbox stays paused. Use it to change `metadata`,
* `network`, `autoDeleteSeconds`, `timeoutSeconds`, or `idleTimeoutSeconds`
* from just an ID. Pass `null` for any of the three to clear it.
*/
static async updateById(sandboxId, options, connection = {}) {
const config = resolveConfig(connection);
await requestVoid({
method: "PATCH",
url: `${config.baseUrl}/sandboxes/${sandboxId}`,
headers: { "X-API-Key": config.apiKey },
body: _Sandbox.buildUpdateBody(options),
signal: connection.signal
});
}
// -------------------------------------------------------------------------
// Instance lifecycle methods
// -------------------------------------------------------------------------
/**
* Refresh this sandbox's info from the API and return the fresh data.
*
* Note: the returned SandboxInfo reflects the current state. The sandbox
* instance's own `status` / `metadata` properties are snapshots from
* construction and are not mutated — use the return value.
*/
async getInfo() {
const raw = await request({
method: "GET",
url: `${this._config.baseUrl}/sandboxes/${this.id}`,
headers: { "X-API-Key": this._config.apiKey }
});
return toSandboxInfo(raw);
}
/**
* Take a snapshot of this sandbox's memory and disk, kept until deleted.
* The sandbox must be active or paused; a running one is paused for the
* capture and resumed after, typically for under a second.
*
* Create sandboxes from it with `Sandbox.create({ fromSnapshot })`. They
* continue with the processes that were running.
*
* @example
* ```typescript
* const snapshot = await sandbox.snapshot({ name: "before-upgrade" })
* const fork = await Sandbox.create({ name: "fork", fromSnapshot: snapshot })
* ```
*/
async snapshot(options = {}) {
const timeoutMs = options.timeoutMs ?? DEFAULT_SNAPSHOT_TIMEOUT_MS;
const started = Date.now();
const body = {
kind: options.kind ?? "mem+fs",
idempotency_key: options.idempotencyKey ?? newIdempotencyKey()
};
if (options.name !== void 0) body.name = options.name;
const raw = await request({
method: "POST",
url: `${this._config.baseUrl}/sandboxes/${this.id}/snapshot`,
headers: { "X-API-Key": this._config.apiKey },
body,
timeoutMs,
signal: options.signal
});
const snapshot = new Snapshot(toSnapshotInfo(raw), this._config);
if (options.wait === false) return snapshot;
return waitForSnapshot(this._config, snapshot, {
timeoutMs: Math.max(timeoutMs - (Date.now() - started), 1),
pollIntervalMs: options.pollIntervalMs,
signal: options.signal
});
}
/** This sandbox's snapshots, newest first. */
async snapshots(options = {}) {
return Snapshot.list(this.id, {
...options,
apiKey: this._config.apiKey,
baseUrl: this._config.baseUrl
});
}
/**
* Pause this sandbox. The sandbox transitions to `paused`.
* All running processes and file state are preserved.
*
* Returns once the pause is accepted; with `wait: true` it returns once the
* sandbox is `paused`.
*/
async pause(options = {}) {
const url = `${this._config.baseUrl}/sandboxes/${this.id}/pause`;
if (!options.wait) {
await request({
method: "POST",
url,
headers: { "X-API-Key": this._config.apiKey, Prefer: "respond-async" },
signal: options.signal
});
return;
}
await this._underPauseDeadline(options, async (ctx) => {
let raw;
try {
raw = await request({
method: "POST",
url,
headers: { "X-API-Key": this._config.apiKey },
timeoutMs: Math.min(DEFAULT_TIMEOUT_MS, ctx.timeoutMs),
signal: ctx.signal
});
} catch (err) {
if (err instanceof TimeoutError && !ctx.deadline.aborted) {
raw = { status: "pausing" };
} else {
throw err;
}
}
if (raw?.status !== "pausing") return;
await this._pollUntilPaused(
ctx,
options.pollIntervalMs ?? DEFAULT_PAUSE_POLL_MS
);
});
}
/**
* Resume a paused sandbox. Status transitions back to `active`. A pause
* still in progress is waited out first.
* The access token is rotated; `sandbox.commands` and `sandbox.files` pick
* up the fresh token transparently.
*/
async resume(options = {}) {
try {
await this._postAndRotateToken("resume", options.signal);
} catch (err) {
if (!(err instanceof ConflictError)) throw err;
const current = await request({
method: "GET",
url: `${this._config.baseUrl}/sandboxes/${this.id}`,
headers: { "X-API-Key": this._config.apiKey },
signal: options.signal
});
const { status } = toSandboxInfo(current);
if (status !== "pausing" && status !== "paused") throw err;
if (status === "pausing") {
await this._underPauseDeadline(
options,
(ctx) => this._pollUntilPaused(ctx, options.pollIntervalMs)
);
}
await this._postAndRotateToken("resume", options.signal);
}
}
/**
* Runs body under one operation deadline, enforced as a signal so it reaches
* into requests, their retries and backoff, and body reads. @internal
*/
async _underPauseDeadline(options, body) {
const timeoutMs = options.timeoutMs ?? DEFAULT_PAUSE_TIMEOUT_MS;
const deadline = new AbortController();
const deadlineTimer = setTimeout(() => deadline.abort(), timeoutMs);
const { signal, release } = composeSignals(deadline.signal, options.signal);
const stillPausing = () => new TimeoutError(
`Sandbox ${this.id} is still pausing after ${timeoutMs}ms; it will finish in the background`
);
try {
await body({ signal, deadline: deadline.signal, timeoutMs, stillPausing });
} catch (err) {
if (deadline.signal.aborted && !options.signal?.aborted) {
throw stillPausing();
}
throw err;
} finally {
clearTimeout(deadlineTimer);
release();
}
}
/**
* Polls until the sandbox is `paused`. A sandbox deleted meanwhile (delete
* on pause) counts as done; `failed` throws. @internal
*/
async _pollUntilPaused(ctx, pollMs) {
const started = performance.now();
let first = true;
while (true) {
if (!first) {
let delay = pollMs;
if (delay === void 0) {
const young = performance.now() - started < PAUSE_FAST_POLL_WINDOW_MS;
delay = young ? PAUSE_FAST_POLL_MS : DEFAULT_PAUSE_POLL_MS;
}
await sleep(delay, ctx.signal);
}
first = false;
let info;
try {
info = await request({
method: "GET",
url: `${this._config.baseUrl}/sandboxes/${this.id}`,
headers: { "X-API-Key": this._config.apiKey },
signal: ctx.signal
});
} catch (err) {
if (err instanceof NotFoundError) return;
if (err instanceof TimeoutError && !ctx.deadline.aborted) continue;
throw err;
}
if (ctx.deadline.aborted) throw ctx.stillPausing();
const { status } = toSandboxInfo(info);
if (status === "paused" || status === "deleted") return;
if (status === "active" && performance.now() - started < PAUSE_FAST_POLL_WINDOW_MS) {
continue;
}
if (status !== "pausing") {
throw new SandboxError(
`Sandbox ${this.id} did not pause: status is ${status}`
);
}
}
}
/**
* Delete this sandbox and all its resources.
*
* Idempotent: if the sandbox is already deleted, this is a no-op. The
* signal cancels the request and any retries.
*/
async kill(options = {}) {
try {
await requestVoid({
method: "DELETE",
url: `${this._config.baseUrl}/sandboxes/${this.id}`,
headers: { "X-API-Key": this._config.apiKey },
signal: options.signal,
// Don't drop a mid-transition sandbox on bulk delete (see retryConflict).
retryConflict: true
});
} catch (err) {
if (!(err instanceof NotFoundError)) throw err;
}
}
/**
* Partially update this sandbox (metadata, network rules, auto-delete,
* timeout, idle timeout).
*
* `autoDeleteSeconds: null` clears the auto-delete window; a number sets
* it, counting from now when the sandbox is already paused.
* `timeoutSeconds: null` clears the auto-pause timeout, and
* `idleTimeoutSeconds: null` turns idle pausing off.
*/
async update(options) {
await requestVoid({
method: "PATCH",
url: `${this._config.baseUrl}/sandboxes/${this.id}`,
headers: { "X-API-Key": this._config.apiKey },
body: _Sandbox.buildUpdateBody(options)
});
}
/** Serialize update options to the wire body (snake_case, null preserved). */
static buildUpdateBody(options) {
const body = {};
if (options.metadata !== void 0) body.metadata = options.metadata;
if (options.autoDeleteSeconds !== void 0)
body.auto_delete_seconds = options.autoDeleteSeconds;
if (options.timeoutSeconds !== void 0)
body.timeout_seconds = options.timeoutSeconds;
if (options.idleTimeoutSeconds !== void 0)
body.idle_timeout_seconds = options.idleTimeoutSeconds;
if (options.network !== void 0) {
body.network = {
allow_out: options.network.allowOut,
deny_out: options.network.denyOut
};
}
if (options.previewAccess !== void 0)
body.preview_access = options.previewAccess;
return body;
}
/**
* Build the preview URL for a port running inside this sandbox.
*
* This is pure string construction. Under strict public/private policies,
* publish the port first; private URLs also need a header token or a signed
* URL from `getSignedPreviewUrl()`.
*
* @throws {ValidationError} if `port` is not an integer in [1024, 65535].
*
* @example
* ```typescript
* await sandbox.commands.spawn("python3 -m http.server 8000")
* const url = sandbox.getPreviewUrl(8000)
* ```
*/
getPreviewUrl(port) {
return previewUrl(this.id, this._config.sandboxHost, port);
}
/** List the sandbox's explicitly published preview ports and policy. */
async listPreviewPorts() {
const raw = await request({
method: "GET",
url: `${this._config.baseUrl}/sandboxes/${this.id}/preview-ports`,
headers: { "X-API-Key": this._config.apiKey }
});
const ports = (raw.ports ?? []).map((item) => {
const access = item.access;
if (item.port === void 0 || item.token_version === void 0 || access !== "public" && access !== "private") {
throw new SandboxError("Invalid list-preview-ports response");
}
return {
port: item.port,
tokenVersion: item.token_version,
access
};
});
return {
previewAccess: raw.preview_access ?? "legacy_public",
ports
};
}
/**
* Publish a port. Omit `access` to use the sandbox default for a new port and
* preserve an existing port's mode. An explicit mode changes only this port.
*/
async publishPreviewPort(port, options = {}) {
this.getPreviewUrl(port);
const raw = await request({
method: "POST",
url: `${this._config.baseUrl}/sandboxes/${this.id}/preview-ports`,
headers: { "X-API-Key": this._config.apiKey },
body: options.access === void 0 ? { port } : { port, access: options.access }
});
if (raw.port === void 0 || raw.token_version === void 0 || raw.access !== "public" && raw.access !== "private") {
throw new SandboxError("Invalid publish-preview-port response");
}
return {
port: raw.port,
tokenVersion: raw.token_version,
access: raw.access
};
}
/** Unpublish a port and revoke every outstanding token for it. */
async unpublishPreviewPort(port) {
this.getPreviewUrl(port);
await requestVoid({
method: "DELETE",
url: `${this._config.baseUrl}/sandboxes/${this.id}/preview-ports/${port}`,
headers: { "X-API-Key": this._config.apiKey }
});
}
/**
* Mint a header/query credential for an already-published port.
* Omitting `expiresInSeconds` intentionally creates a long-running machine
* credential that remains valid until this port is rotated or unpublished.
*/
async getPreviewToken(port, options = {}) {
this.getPreviewUrl(port);
const raw = await request({
method: "POST",
url: `${this._config.baseUrl}/sandboxes/${this.id}/preview-ports/${port}/token`,
headers: { "X-API-Key": this._config.apiKey },
body: options.expiresInSeconds === void 0 ? {} : { expires_in_seconds: options.expiresInSeconds }
});
if (!raw.token || raw.port === void 0 || !raw.header || !raw.query_param || raw.token_version === void 0 || raw.access !== "public" && raw.access !== "private") {
throw new SandboxError("Invalid preview-token response");
}
return {
token: raw.token,
port: raw.port,
header: raw.header,
queryParam: raw.query_param,
tokenVersion: raw.token_version,
access: raw.access,
previewAccess: raw.preview_access ?? "legacy_public",
expiresAt: raw.expires_at ? new Date(raw.expires_at) : void 0
};
}
/**
* Build a browser-ready private preview URL. The proxy exchanges its query
* token for a secure host cookie and removes the token from the address bar.
*/
async getSignedPreviewUrl(port, options = {}) {
const credential = await this.getPreviewToken(port, {
expiresInSeconds: options.expiresInSeconds ?? 60
});
const url = new URL(this.getPreviewUrl(port));
url.searchParams.set(credential.queryParam, credential.token);
return url.toString();
}
/** Rotate only this port's token generation and return a fresh token. */
async rotatePreviewToken(port) {
this.getPreviewUrl(port);
const raw = await request({
method: "POST",
url: `${this._config.baseUrl}/sandboxes/${this.id}/preview-ports/${port}/token/rotate`,
headers: { "X-API-Key": this._config.apiKey }
});
if (!raw.token || raw.port === void 0 || !raw.header || !raw.query_param || raw.token_version === void 0 || raw.access !== "public" && raw.access !== "private") {
throw new SandboxError("Invalid rotate-preview-token response");
}
return {
token: raw.token,
port: raw.port,
header: raw.header,
queryParam: raw.query_param,
tokenVersion: raw.token_version,
access: raw.access,
previewAccess: raw.preview_access ?? "legacy_public",
expiresAt: raw.expires_at ? new Date(raw.expires_at) : void 0
};
}
/**
* The sandbox's network log: every outbound connection it made, newest first.
* `connection` rows are raw egress (host, bytes, allow/deny verdict); `request`
* rows are credential-injected requests (method, path, status, secret used).
*
* Filter by time window (`since`/`before`) and `verdict`. Paginate by passing
* the returned `nextCursor` as `before` while `hasMore` is true.
*/
async getNetworkLog(options = {}) {
const qs = new URLSearchParams();
if (options.limit !== void 0) qs.set("limit", String(options.limit));
if (options.before !== void 0) qs.set("before", options.before);
if (options.since !== void 0) qs.set("since", options.since);
if (options.verdict !== void 0) qs.set("verdict", options.verdict);
const suffix = qs.toString() ? `?${qs.toString()}` : "";
const raw = await request({
method: "GET",
url: `${this._config.baseUrl}/sandboxes/${this.id}/network${suffix}`,
headers: { "X-API-Key": this._config.apiKey },
signal: options.signal
});
return toNetworkLogPage(raw);
}
/**
* Bind a team secret to this sandbox under an environment variable. The
* sandbox sees a stand-in token; the real credential is swapped in for
* outbound requests to the secret's allowed hosts. Takes effect for processes
* started after this call; a paused sandbox applies it on resume.
*
* The local `secrets` summary is a snapshot from when the sandbox was fetched
* and is not updated here — call `Sandbox.get(id)` for the current set.
*/
async attachSecret(envKey, secretName) {
await requestVoid({
method: "POST",
url: `${this._config.baseUrl}/sandboxes/${this.id}/secrets`,
headers: { "X-API-Key": this._config.apiKey },
body: { env_key: envKey, secret_name: secretName }
});
}
/**
* Remove a secret binding from this sandbox by its environment-variable key.
* The stand-in token is revoked, so requests using it are refused — within
* about a minute for a process already running. A paused sandbox applies the
* change on resume.
*/
async detachSecret(envKey) {
await requestVoid({
method: "DELETE",
url: `${this._config.baseUrl}/sandboxes/${this.id}/secrets/${encodeURIComponent(envKey)}`,
headers: { "X-API-Key": this._config.apiKey }
});
}
};
// src/Secret.ts
var Secret = class _Secret {
/** @internal — use `Secret.create()` / `Secret.get()` instead. */
constructor(info, config) {
this.id = info.id;
this.name = info.name;
this.authType = info.authType;
this.authConfig = info.authConfig;
this.providerShortcut = info.providerShortcut;
this.hosts = info.hosts;
this.createdAt = info.createdAt;
this.updatedAt = info.updatedAt;
this.lastUsedAt = info.lastUsedAt;
this._config = config;
}
// -------------------------------------------------------------------------
// Static factories
// -------------------------------------------------------------------------
/**
* Create a secret. Provide either a `provider` shortcut, or a custom `auth`
* config together with `hosts`.
*/
static async create(options) {
const config = resolveConfig(options);
const raw = await request({
method: "POST",
url: `${config.baseUrl}/secrets`,
headers: { "X-API-Key": config.apiKey },
body: secretCreateBody(options),
signal: options.signal
});
return new _Secret(toSecretInfo(raw), config);
}
/** Fetch an existing secret by name. */
static async get(name, options = {}) {
const config = resolveConfig(options);
const raw = await request({
method: "GET",
url: `${config.baseUrl}/secrets/${encodeURIComponent(name)}`,
headers: { "X-API-Key": config.apiKey },
signal: options.signal
});
return new _Secret(toSecretInfo(raw), config);
}
/** List all secrets for the team. */
static async list(options = {}) {
const config = resolveConfig(options);
const raw = await request({
method: "GET",
url: `${config.baseUrl}/secrets`,
headers: { "X-API-Key": config.apiKey },
signal: options.signal
});
return raw.map(toSecretInfo);
}
/** Delete a secret by name. Idempotent — no error if it's already gone. */
static async deleteByName(name, options = {}) {
const config = resolveConfig(options);
try {
await requestVoid({
method: "DELETE",
url: `${config.baseUrl}/secrets/${encodeURIComponent(name)}`,
headers: { "X-API-Key": config.apiKey },
signal: options.signal
});
} catch (err) {
if (!(err instanceof NotFoundError)) throw err;
}
}
// -------------------------------------------------------------------------
// Instance methods
// -------------------------------------------------------------------------
/** Re-fetch the latest metadata for this secret. */
async getInfo() {
const raw = await request({
method: "GET",
url: `${this._config.baseUrl}/secrets/${encodeURIComponent(this.name)}`,
headers: { "X-API-Key": this._config.apiKey }
});
return toSecretInfo(raw);
}
/**
* Replace the secret's value (rotation). Bound sandboxes keep their env var;
* the new value is injected on subsequent egress. Returns the updated secret.
*/
async rotate(value) {
const raw = await request({
method: "PATCH",
url: `${this._config.baseUrl}/secrets/${encodeURIComponent(this.name)}`,
headers: { "X-API-Key": this._config.apiKey },
body: { value }
});
return new _Secret(toSecretInfo(raw), this._config);
}
/** Delete this secret. Idempotent. */
async delete() {
try {
await requestVoid({
method: "DELETE",
url: `${this._config.baseUrl}/secrets/${encodeURIComponent(this.name)}`,
headers: { "X-API-Key": this._config.apiKey }
});
} catch (err) {
if (!(err instanceof NotFoundError)) throw err;
}
}
/** Requests made with this secret attached, across all sandboxes, newest first. */
async getAudit(options = {}) {
const qs = new URLSearchParams();
if (options.limit !== void 0) qs.set("limit", String(options.limit));
if (options.before !== void 0) qs.set("before", String(options.before));
if (options.status) qs.set("status", options.status);
const suffix = qs.toString() ? `?${qs.toString()}` : "";
const raw = await request({
method: "GET",
url: `${this._config.baseUrl}/secrets/${encodeURIComponent(this.name)}/audit${suffix}`,
headers: { "X-API-Key": this._config.apiKey },
signal: options.signal
});
return raw.map(toProxyAuditEvent);
}
/** Sandboxes this secret is currently bound to. */
async getSandboxes() {
const raw = await request({
method: "GET",
url: `${this._config.baseUrl}/secrets/${encodeURIComponent(this.name)}/sandboxes`,
headers: { "X-API-Key": this._config.apiKey }
});
return raw.map(toSecretSandboxBinding);
}
};
// src/Template.ts
var Template = class _Template {
/** @internal — use `Template.create()` / `Template.connect()` instead. */
constructor(info, config) {
this.id = info.id;
this.name = info.name;
this.teamId = info.teamId;
this.status = info.status;
this.vcpu = info.vcpu;
this.memoryMib = info.memoryMib;
this.memoryMaxMib = info.memoryMaxMib;
this.memoryShrinkAfterSeconds = info.memoryShrinkAfterSeconds;
this.vcpuMax = info.vcpuMax;
this.diskMib = info.diskMib;
this.sizeBytes = info.sizeBytes;
this.errorMessage = info.errorMessage;
this.createdAt = info.createdAt;
this.builtAt = info.builtAt;
this.latestBuildId = info.latestBuildId;
this._config = config;
}
// -------------------------------------------------------------------------
// Static factories
// -------------------------------------------------------------------------
static async create(options) {
const config = resolveConfig(options);
const buildSpec = { from: options.from };
if (options.steps !== void 0)
buildSpec.steps = buildStepsToApi(options.steps);
if (options.startCmd !== void 0) buildSpec.start_cmd = options.startCmd;
if (options.readyCmd !== void 0) buildSpec.ready_cmd = options.readyCmd;
const body = {
name: options.name,
build_spec: buildSpec
};
if (options.vcpu !== void 0) body.vcpu = options.vcpu;
if (options.memoryMib !== void 0) body.memory_mib = options.memoryMib;
if (options.memoryMaxMib !== void 0)
body.memory_max_mib = options.memoryMaxMib;
if (options.memoryShrinkAfterSeconds !== void 0)
body.memory_shrink_after_seconds = options.memoryShrinkAfterSeconds;
if (options.vcpuMax !== void 0) body.vcpu_max = options.vcpuMax;
if (options.diskMib !== void 0) body.disk_mib = options.diskMib;
const raw = await request({
method: "POST",
url: `${config.baseUrl}/templates`,
headers: { "X-API-Key": config.apiKey },
body,
signal: options.signal
});
if (!raw.build_id) {
throw new SandboxError(
"Invalid API response from POST /templates: missing build_id"
);
}
return new _Template(toTemplateInfo(raw, raw.build_id), config);
}
static async connect(nameOrId, options = {}) {
const config = resolveConfig(options);
const raw = await request({
method: "GET",
url: `${config.baseUrl}/templates/${encodeURIComponent(nameOrId)}`,
headers: { "X-API-Key": config.apiKey },
signal: options.signal
});
return new _Template(toTemplateInfo(raw), config);
}
static async list(options = {}) {
const config = resolveConfig(options);
let url = `${config.baseUrl}/templates`;
if (options.namePrefix) {
const qs = new URLSearchParams({ name_prefix: options.namePrefix });
url += `?${qs.toString()}`;
}
const raw = await request({
method: "GET",
url,
headers: { "X-API-Key": config.apiKey },
signal: options.signal
});
return raw.map((t) => toTemplateInfo(t));
}
static async deleteById(nameOrId, options = {}) {
const config = resolveConfig(options);
try {
await requestVoid({
method: "DELETE",
url: `${config.baseUrl}/templates/${encodeURIComponent(nameOrId)}`,
headers: { "X-API-Key": config.apiKey },
signal: options.signal
});
} catch (err) {
if (!(err instanceof NotFoundError)) throw err;
}
}
// -------------------------------------------------------------------------
// Instance methods
// -------------------------------------------------------------------------
async getInfo() {
const raw = await request({
method: "GET",
url: `${this._config.baseUrl}/templates/${encodeURIComponent(this.id)}`,
headers: { "X-API-Key": this._config.apiKey }
});
return toTemplateInfo(raw);
}
async delete() {
try {
await requestVoid({
method: "DELETE",
url: `${this._config.baseUrl}/templates/${encodeURIComponent(this.id)}`,
headers: { "X-API-Key": this._config.apiKey }
});
} catch (err) {
if (!(err instanceof NotFoundError)) throw err;
}
}
async rebuild() {
const raw = await request({
method: "POST",
url: `${this._config.baseUrl}/templates/${encodeURIComponent(this.id)}/builds`,
headers: { "X-API-Key": this._config.apiKey }
});
return toTemplateBuildInfo(raw);
}
async listBuilds(options = {}) {
let url = `${this._config.baseUrl}/templates/${encodeURIComponent(this.id)}/builds`;
if (options.limit !== void 0) {
url += `?limit=${options.limit}`;
}
const raw = await request({
method: "GET",
url,
headers: { "X-API-Key": this._config.apiKey },
signal: options.signal
});
return raw.map(toTemplateBuildInfo);
}
async getBuild(buildId) {
const raw = await request({
method: "GET",
url: `${this._config.baseUrl}/templates/${encodeURIComponent(this.id)}/builds/${encodeURIComponent(buildId)}`,
headers: { "X-API-Key": this._config.apiKey }
});
return toTemplateBuildInfo(raw);
}
async cancelBuild(buildId) {
try {
await requestVoid({
method: "DELETE",
url: `${this._config.baseUrl}/templates/${encodeURIComponent(this.id)}/builds/${encodeURIComponent(buildId)}`,
headers: { "X-API-Key": this._config.apiKey }
});
} catch (err) {
if (!(err instanceof NotFoundError)) throw err;
}
}
/**
* Resolve the build to operate on — explicit `buildId`, then `latestBuildId`
* captured at construction (set on `Template.create`), then a lookup of the
* most recent build via `listBuilds`. Throws if the template has no builds.
*/
async _resolveBuildId(buildId) {
if (buildId) return buildId;
if (this.latestBuildId) return this.latestBuildId;
const recent = await this.listBuilds({ limit: 1 });
if (recent.length === 0) {
throw new SandboxError(
`Template ${this.name} has no builds \u2014 call rebuild() first`
);
}
return recent[0].id;
}
async streamBuildLogs(options) {
const buildId = await this._resolveBuildId(options.buildId);
await streamSSE({
method: "GET",
url: `${this._config.baseUrl}/templates/${encodeURIComponent(this.id)}/builds/${encodeURIComponent(buildId)}/logs`,
headers: { "X-API-Key": this._config.apiKey },
signal: options.signal,
onEvent: (raw) => options.onEvent(toBuildLogEvent(raw))
});
}
async waitUntilReady(options = {}) {
const pollMs = options.pollIntervalMs ?? 2e3;
let buildId;
try {
buildId = await this._resolveBuildId();
} catch {
}
const sseAbort = new AbortController();
const sseSignal = options.signal ? AbortSignal.any([sseAbort.signal, options.signal]) : sseAbort.signal;
let ssePromise;
if (buildId && options.onLog) {
ssePromise = streamSSE({
method: "GET",
url: `${this._config.baseUrl}/templates/${encodeURIComponent(this.id)}/builds/${encodeURIComponent(buildId)}/logs`,
headers: { "X-API-Key": this._config.apiKey },
signal: sseSignal,
onEvent: (raw) => options.onLog?.(toBuildLogEvent(raw))
}).catch(() => {
});
}
const parseBuildError = (errorMessage) => {
if (!errorMessage) {
return { code: "build_failed", message: "Template build failed" };
}
const match = /^(\w+):\s*(.*)$/s.exec(errorMessage);
if (match && match[2].trim().length > 0) {
return { code: match[1], message: match[2].trim() };
}
return { code: "build_failed", message: errorMessage };
};
try {
if (buildId) {
while (true) {
if (options.signal?.aborted) throw new SandboxError("aborted");
const build = await this.getBuild(buildId);
if (build.status === "ready") return await this.getInfo();
if (build.status === "failed") {
const { code, message } = parseBuildError(build.errorMessage);
throw new BuildError(message, {
code,
buildId,
templateId: this.id
});
}
if (build.status === "cancelled") {
throw new ConflictError("template build was cancelled", "cancelled");
}
await new Promise((r) => setTimeout(r, pollMs));
}
}
while (true) {
if (options.signal?.aborted) throw new SandboxError("aborted");
const info = await this.getInfo();
if (info.status === "ready") return info;
if (info.status === "failed") {
const { code, message } = parseBuildError(info.errorMessage);
throw new BuildError(message, {
code,
buildId: "",
templateId: this.id
});
}
await new Promise((r) => setTimeout(r, pollMs));
}
} finally {
sseAbort.abort();
if (ssePromise) await ssePromise;
}
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
AuthenticationError,
BillingError,
BuildError,
ConflictError,
DESKTOP_STREAM_PORT,
MAX_PREVIEW_PORT,
MIN_PREVIEW_PORT,
NotFoundError,
Provider,
RESERVED_PREVIEW_PORT,
RateLimitError,
Sandbox,
SandboxError,
Secret,
ServerError,
Snapshot,
Template,
TimeoutError,
ValidationError,
Volume,
previewUrl,
resolveConfig
});
//# sourceMappingURL=index.cjs.map
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.