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