UNPKG

@luxorai/sandbox

Version:

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

432 lines • 19 kB
import { Code, ConnectError } from "@connectrpc/connect"; export class SandboxError extends Error { constructor(message, options) { super(message, options); this.name = "SandboxError"; } } export class PaginationStalledError extends SandboxError { name = "PaginationStalledError"; } export class MissingAuthTokenError extends SandboxError { constructor() { super("missing auth token - set LUXOR_AUTH_TOKEN or LUXOR_API_KEY (or TENKI_AUTH_TOKEN or TENKI_API_KEY) or use authToken option"); this.name = "MissingAuthTokenError"; } } export class InvalidAuthTokenError extends SandboxError { constructor() { super("invalid auth token - API keys and service tokens must start with lx_ or tk_"); this.name = "InvalidAuthTokenError"; } } export class SessionNotFoundError extends SandboxError { name = "SessionNotFoundError"; } export class SessionExpiredError extends SandboxError { name = "SessionExpiredError"; } export class SessionTerminatedError extends SandboxError { name = "SessionTerminatedError"; retryable = true; terminationCause; constructor(message, options) { super(message, options); this.terminationCause = options?.terminationCause; } } export class FileNotFoundError extends SandboxError { name = "FileNotFoundError"; } // FileTooLargeError means a unary readFile or writeFile refused a file above maxBytes; use readFileStream // or writeFileStream instead. operation is "ReadFile" or "WriteFile". sizeBytes is a lower bound when the // guest could not stat the file's size. export class FileTooLargeError extends SandboxError { operation; sizeBytes; maxBytes; name = "FileTooLargeError"; constructor(message, operation, sizeBytes, maxBytes, options) { super(message, options); this.operation = operation; this.sizeBytes = sizeBytes; this.maxBytes = maxBytes; } } export class InvalidStateError extends SandboxError { name = "InvalidStateError"; } export class InvalidArgumentError extends SandboxError { name = "InvalidArgumentError"; } export class UnavailableError extends SandboxError { name = "UnavailableError"; retryable = true; } export class CommandTimeoutError extends SandboxError { name = "CommandTimeoutError"; } export class UnauthorizedError extends SandboxError { name = "UnauthorizedError"; } export class PermissionDeniedError extends SandboxError { name = "PermissionDeniedError"; } export class QuotaExceededError extends SandboxError { name = "QuotaExceededError"; } export class CapacityUnavailableError extends SandboxError { name = "CapacityUnavailableError"; } export class PortLimitExceededError extends SandboxError { name = "PortLimitExceededError"; } export class InboundDisabledError extends SandboxError { name = "InboundDisabledError"; } export class SSHUnavailableError extends SandboxError { name = "SSHUnavailableError"; } export class RateLimitedError extends SandboxError { name = "RateLimitedError"; } export class VolumeNotFoundError extends SandboxError { name = "VolumeNotFoundError"; } export class VolumeInUseError extends SandboxError { name = "VolumeInUseError"; } export class VolumeSyncPendingError extends SandboxError { name = "VolumeSyncPendingError"; } export class VolumeLimitExceededError extends SandboxError { name = "VolumeLimitExceededError"; } // GitOperationFailedError classifies an in-guest git failure surfaced by // node-agent as FailedPrecondition. export class GitOperationFailedError extends SandboxError { stderr; exitCode; retryable; name = "GitOperationFailedError"; constructor(message, stderr = "", exitCode = undefined, retryable = false, options) { super(message, options); this.stderr = stderr; this.exitCode = exitCode; this.retryable = retryable; } } export class StreamClosedError extends SandboxError { name = "StreamClosedError"; } export class InvalidResourceConfigError extends SandboxError { name = "InvalidResourceConfigError"; } export class SnapshotNotFoundError extends SandboxError { name = "SnapshotNotFoundError"; } export class SnapshotFailedError extends SandboxError { name = "SnapshotFailedError"; failureReason; constructor(message, options) { super(message, options); this.failureReason = options?.failureReason; } } export class SnapshotWaitTimeoutError extends SandboxError { name = "SnapshotWaitTimeoutError"; } export class SnapshotNotDurableError extends SandboxError { name = "SnapshotNotDurableError"; } export class ResumeFailedError extends SandboxError { name = "ResumeFailedError"; } export class ResumeWaitTimeoutError extends SandboxError { name = "ResumeWaitTimeoutError"; } export class PauseFailedError extends SandboxError { name = "PauseFailedError"; } export class TemplateNotFoundError extends SandboxError { name = "TemplateNotFoundError"; } export class EgressPolicyNotFoundError extends SandboxError { name = "EgressPolicyNotFoundError"; } export class StorageConnectionNotFoundError extends SandboxError { name = "StorageConnectionNotFoundError"; } export class StorageMountNotFoundError extends SandboxError { name = "StorageMountNotFoundError"; } /** A detach of the same mount landed before the attach finished. */ export class StorageMountAttachCancelledError extends SandboxError { name = "StorageMountAttachCancelledError"; } /** Luxor disabled the storage connection; contact support to restore it. */ export class StorageConnectionDisabledError extends SandboxError { name = "StorageConnectionDisabledError"; } export class RegistryImageNotFoundError extends SandboxError { name = "RegistryImageNotFoundError"; } export class TemplateExistsError extends SandboxError { name = "TemplateExistsError"; } export class TemplateBuildNotFoundError extends SandboxError { name = "TemplateBuildNotFoundError"; } export class TemplateBuildFailedError extends SandboxError { name = "TemplateBuildFailedError"; build; constructor(message, buildOrOptions, options) { const build = buildOrOptions && "state" in buildOrOptions ? buildOrOptions : undefined; const errorOptions = build ? options : buildOrOptions; super(message, errorOptions); this.build = build; } } export class TemplateBuildInProgressError extends SandboxError { name = "TemplateBuildInProgressError"; } export class InvalidTemplateSpecError extends SandboxError { name = "InvalidTemplateSpecError"; } export class TemplateRuntimeFailedError extends SandboxError { session; name = "TemplateRuntimeFailedError"; constructor(message, session, options) { super(message, options); this.session = session; } } /** A readiness wait failed after the server admitted the session. */ export class WaitReadyFailedError extends SandboxError { session; name = "WaitReadyFailedError"; constructor(message, session, options) { super(message, options); this.session = session; } } /** A fork failed after its snapshot was created; `sessions` were created before the failure and keep running. */ export class ForkFailedError extends SandboxError { snapshotId; sessions; name = "ForkFailedError"; constructor(message, snapshotId, sessions, options) { super(message, options); this.snapshotId = snapshotId; this.sessions = sessions; } } /** The sandbox acknowledged a write without saving every byte sent. */ export class IncompleteWriteError extends SandboxError { name = "IncompleteWriteError"; } export function ensureFullWrite(path, sent, written) { const saved = written ?? 0n; if (saved !== sent) { throw new IncompleteWriteError(`write incomplete: ${path}: sent ${sent} bytes, sandbox wrote ${saved}`); } } export class CapabilityUnavailableError extends SandboxError { primitive; name = "CapabilityUnavailableError"; constructor(primitive, message = `sandbox capability unavailable: ${primitive}`, options) { super(message, options); this.primitive = primitive; } } export class DataPlaneNotReadyError extends SandboxError { name = "DataPlaneNotReadyError"; retryable; constructor(message = "sandbox: data-plane edge route not ready", options) { super(message, options); this.terminal = options?.terminal ?? false; this.retryable = !this.terminal; } terminal; } export function isDataPlaneEdgeNotReady(err) { return err instanceof ConnectError && err.code === Code.Unimplemented && /\b404\b/.test(err.message ?? ""); } export function isPausedSessionStateError(err) { if (!(err instanceof InvalidStateError)) return false; return /\bstate\s*=\s*PAUSED\b/i.test(err.message); } export function dataPlaneNotReadyError(err) { return new DataPlaneNotReadyError("sandbox: data-plane edge route not ready", { cause: err instanceof Error ? err : undefined, }); } export function terminalDataPlaneNotReadyError(err) { return new DataPlaneNotReadyError("sandbox: data-plane route verification failed", { cause: err instanceof Error ? err : undefined, terminal: true, }); } export class PrimitiveTimeoutError extends CapabilityUnavailableError { name = "PrimitiveTimeoutError"; constructor(primitive, message = `sandbox ${primitive} timed out waiting for guest-agent reply`, options) { super(primitive, message, options); } } // Platform-teardown exit reasons, formatted `session_terminated:<cause>[: detail]` // by node-agent — see the matching block in errors.py / run.go. export const SESSION_TERMINATED_REASON_PREFIX = "session_terminated"; export function isSessionTerminatedReason(reason) { return reason.startsWith(SESSION_TERMINATED_REASON_PREFIX); } /** Extracts the cause token from a `session_terminated:<cause>[: detail]` reason. */ export function sessionTerminationCause(reason) { if (!reason.startsWith(`${SESSION_TERMINATED_REASON_PREFIX}:`)) return ""; return reason .slice(SESSION_TERMINATED_REASON_PREFIX.length + 1) .split(":", 1)[0] .trim(); } // Same pattern as fileTooLargeRe in errors.go and _FILE_TOO_LARGE in errors.py. const FILE_TOO_LARGE = /file too large for (ReadFile|WriteFile): size_bytes=(\d{1,18}) max_bytes=(\d{1,18})/; function fileTooLargeError(err) { const match = FILE_TOO_LARGE.exec(err.message); if (!match) return undefined; const operation = match[1]; return new FileTooLargeError(err.message, operation, BigInt(match[2]), BigInt(match[3]), { cause: err }); } // A guest agent without a primitive answers with this text; older node agents relay it as Internal, newer as Unimplemented. // Same pattern as legacyGuestUnknownRequestRe in errors.go and _LEGACY_GUEST_UNKNOWN_REQUEST in errors.py. const LEGACY_GUEST_UNKNOWN_REQUEST = /unknown request type: \*sandboxv1\.GuestRequest_(\w+)/; // Git failure classification — see the matching block in errors.go / errors.py. const GIT_FAILURE = /git .*failed \(exit_code=/i; const GIT_EXIT_CODE = /\(exit_code=(\d+)\)/; const GIT_STDERR = /; check the repository, ref and access token: ([\s\S]+)/; const TRANSIENT_GIT = /Recv failure|Connection reset by peer|Could not resolve host|Failed to connect|Connection timed out|TLS|gnutls_handshake|SSL_ERROR|RPC failed|HTTP 5\d\d|\b(429|503)\b|early EOF|remote end hung up unexpectedly|unexpected disconnect/i; const TERMINAL_GIT = /Authentication failed|could not read Username|terminal prompts disabled|Repository not found|fatal: repository .* not found|Permission denied|\b403\b|invalid credentials|pathspec|did not match any/i; export function mapError(err) { if (err instanceof SandboxError) return err; const connectErr = err instanceof ConnectError ? err : ConnectError.from(err) instanceof ConnectError ? ConnectError.from(err) : null; if (!connectErr || !(connectErr instanceof ConnectError)) { return new SandboxError(err instanceof Error ? err.message : String(err), { cause: err instanceof Error ? err : undefined, }); } if (isDataPlaneEdgeNotReady(connectErr)) { return dataPlaneNotReadyError(connectErr); } const legacyGuest = LEGACY_GUEST_UNKNOWN_REQUEST.exec(connectErr.message); if (legacyGuest) { return new CapabilityUnavailableError(legacyGuest[1], connectErr.message, { cause: connectErr }); } const msg = connectErr.message.toLowerCase(); const cause = connectErr; switch (connectErr.code) { case Code.InvalidArgument: // connect codes a GOAWAY-cut stream ("protocol error: incomplete envelope") as InvalidArgument. if (msg.includes("protocol error")) return new SandboxError(connectErr.message, { cause }); return new InvalidArgumentError(connectErr.message, { cause }); case Code.Unauthenticated: return new UnauthorizedError(connectErr.message, { cause }); case Code.PermissionDenied: return new PermissionDeniedError(connectErr.message, { cause }); case Code.NotFound: // Matched as a prefix first: the message ends with caller-chosen policy names. if (connectErr.rawMessage.toLowerCase().startsWith("egress polic")) return new EgressPolicyNotFoundError(connectErr.message, { cause }); if (msg.includes("storage connection")) return new StorageConnectionNotFoundError(connectErr.message, { cause }); if (msg.includes("storage mount")) return new StorageMountNotFoundError(connectErr.message, { cause }); if (msg.includes("template build")) return new TemplateBuildNotFoundError(connectErr.message, { cause }); if (msg.includes("template")) return new TemplateNotFoundError(connectErr.message, { cause }); if (msg.includes("registry image")) return new RegistryImageNotFoundError(connectErr.message, { cause }); if (msg.includes("no such file or directory")) return new FileNotFoundError(connectErr.message, { cause }); if (msg.includes("session")) return new SessionNotFoundError(connectErr.message, { cause }); if (msg.includes("snapshot")) return new SnapshotNotFoundError(connectErr.message, { cause }); if (msg.includes("volume")) return new VolumeNotFoundError(connectErr.message, { cause }); if (msg.includes("artifact")) return new SessionExpiredError(connectErr.message, { cause }); return new SessionNotFoundError(connectErr.message, { cause }); case Code.AlreadyExists: if (msg.includes("template")) return new TemplateExistsError(connectErr.message, { cause }); return new SandboxError(connectErr.message, { cause }); case Code.DeadlineExceeded: return new CommandTimeoutError(connectErr.message, { cause }); case Code.ResourceExhausted: { const tooLarge = fileTooLargeError(connectErr); if (tooLarge) return tooLarge; if (msg.includes("maximum exposed ports")) return new PortLimitExceededError(connectErr.message, { cause }); if (msg.includes("volume")) return new VolumeLimitExceededError(connectErr.message, { cause }); if (msg.includes("rate limit")) return new RateLimitedError(connectErr.message, { cause }); if (msg.includes("capacity")) return new CapacityUnavailableError(connectErr.message, { cause }); return new QuotaExceededError(connectErr.message, { cause }); } case Code.FailedPrecondition: if (msg.includes("disabled by luxor") || msg.includes("disabled by tenki")) return new StorageConnectionDisabledError(connectErr.message, { cause }); if (msg.includes("snapshot not yet durable")) { return new SnapshotNotDurableError(connectErr.message, { cause }); } if (msg.includes("template build already in progress") || msg.includes("build in progress")) return new TemplateBuildInProgressError(connectErr.message, { cause }); if (msg.includes("terminated")) return new SessionTerminatedError(connectErr.message, { cause }); if (GIT_FAILURE.test(connectErr.message)) { const fullMessage = connectErr.message; const exitMatch = GIT_EXIT_CODE.exec(fullMessage); const exitCode = exitMatch ? Number.parseInt(exitMatch[1], 10) : undefined; const stderrMatch = GIT_STDERR.exec(fullMessage); const stderr = stderrMatch ? stderrMatch[1] : ""; const retryable = TRANSIENT_GIT.test(fullMessage) && !TERMINAL_GIT.test(fullMessage); return new GitOperationFailedError(fullMessage, stderr, exitCode, retryable, { cause }); } if (msg.includes("sync_pending") || msg.includes("sync pending")) return new VolumeSyncPendingError(connectErr.message, { cause }); if (msg.includes("volume is attached") || msg.includes("volume is in use")) return new VolumeInUseError(connectErr.message, { cause }); if (msg.includes("inbound access is disabled")) return new InboundDisabledError(connectErr.message, { cause }); if (msg.includes("ssh")) return new SSHUnavailableError(connectErr.message, { cause }); return new InvalidStateError(connectErr.message, { cause }); case Code.Aborted: if (msg.includes("cancelled by a detach")) return new StorageMountAttachCancelledError(connectErr.message, { cause }); if (connectErr.rawMessage.toLowerCase().startsWith("resume failed")) return new ResumeFailedError(connectErr.message, { cause }); return new SandboxError(connectErr.message, { cause }); case Code.Unavailable: if (msg.includes("ssh")) return new SSHUnavailableError(connectErr.message, { cause }); return new UnavailableError(connectErr.message, { cause }); default: return new SandboxError(connectErr.message, { cause }); } } /** Maps errors from write RPCs, the only RPCs whose data_loss means an incomplete write. */ export function mapWriteError(err) { if (err instanceof ConnectError && err.code === Code.DataLoss) { return new IncompleteWriteError(err.message, { cause: err }); } return mapError(err); } //# sourceMappingURL=errors.js.map