@omnirun/sdk 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -1,10 +1,38 @@
1
+ import { DEFAULT_RETRY_MAX_ATTEMPTS, DEFAULT_RETRY_MAX_TOTAL_WAIT_MS } from "./config.js";
1
2
  import { encryptE2EEJSON, decryptE2EEJSON } from "./e2ee.js";
2
3
  import { SandboxError, StreamError } from "./errors.js";
3
- /** Maximum number of retry attempts for retryable server errors. */
4
- const MAX_RETRIES = 2;
5
- /** HTTP status codes that are safe to retry (transient server errors). */
6
- function isRetryable(status) {
7
- return status === 500 || status === 502 || status === 503;
4
+ /** 429 reasons that waiting does not resolve: the account's own sandboxes use its limit. */
5
+ const ACCOUNT_LIMIT_REASONS = new Set(["per_user_sandbox_limit", "per_user_ram_limit"]);
6
+ /** 503 reasons on which the service guarantees the request was not carried out. */
7
+ const REFUSED_503_REASONS = new Set(["node_unavailable", "no_healthy_node"]);
8
+ /** Backoff before the first retry when the service sent no `Retry-After`; doubles per attempt. */
9
+ const BASE_BACKOFF_MS = 250;
10
+ /** Whether sending the same request again is safe under `policy`. */
11
+ function isRetryable(policy, status, reason) {
12
+ if (policy === "never")
13
+ return false;
14
+ if (status === 429)
15
+ return true;
16
+ if (policy === "idempotent")
17
+ return status === 502 || status === 503 || status === 504;
18
+ return status === 503 && reason !== undefined && REFUSED_503_REASONS.has(reason);
19
+ }
20
+ /** Parse a `Retry-After` header (delta seconds or HTTP date) into seconds. */
21
+ export function parseRetryAfter(value) {
22
+ if (value == null)
23
+ return undefined;
24
+ const trimmed = value.trim();
25
+ if (trimmed === "")
26
+ return undefined;
27
+ if (/^\d+(\.\d+)?$/.test(trimmed))
28
+ return Number(trimmed);
29
+ const date = Date.parse(trimmed);
30
+ if (Number.isNaN(date))
31
+ return undefined;
32
+ return Math.max(0, Math.ceil((date - Date.now()) / 1000));
33
+ }
34
+ function sleep(ms) {
35
+ return new Promise((resolve) => setTimeout(resolve, ms));
8
36
  }
9
37
  /** Low-level HTTP transport for OmniRun API requests. */
10
38
  export class HTTPClient {
@@ -34,63 +62,101 @@ export class HTTPClient {
34
62
  get jsonHeaders() {
35
63
  return { ...this.authHeaders, "Content-Type": "application/json" };
36
64
  }
65
+ get maxAttempts() {
66
+ const retry = this.config.retry;
67
+ if (retry === false)
68
+ return 1;
69
+ return Math.max(1, Math.floor(retry?.maxAttempts ?? DEFAULT_RETRY_MAX_ATTEMPTS));
70
+ }
71
+ get maxTotalWaitMs() {
72
+ const retry = this.config.retry;
73
+ if (retry === false)
74
+ return 0;
75
+ return Math.max(0, retry?.maxTotalWaitMs ?? DEFAULT_RETRY_MAX_TOTAL_WAIT_MS);
76
+ }
77
+ /**
78
+ * Send a request, retrying it as far as `policy` and the configured bounds
79
+ * allow. Returns the first successful response; throws a {@link SandboxError}
80
+ * for the last error response, or the network error itself.
81
+ */
82
+ async request(url, policy, errorPrefix, makeInit, timeoutMs) {
83
+ const maxAttempts = this.maxAttempts;
84
+ const maxTotalWaitMs = this.maxTotalWaitMs;
85
+ let waitedMs = 0;
86
+ for (let attempt = 1;; attempt++) {
87
+ // The wait before the next attempt, or undefined when this failure is final.
88
+ const nextWait = (retryAfterSeconds) => {
89
+ if (attempt >= maxAttempts)
90
+ return undefined;
91
+ const waitMs = retryAfterSeconds != null
92
+ ? retryAfterSeconds * 1000
93
+ : BASE_BACKOFF_MS * 2 ** (attempt - 1);
94
+ return waitedMs + waitMs <= maxTotalWaitMs ? waitMs : undefined;
95
+ };
96
+ let resp;
97
+ try {
98
+ resp = await fetch(url, {
99
+ ...makeInit(),
100
+ signal: AbortSignal.timeout(timeoutMs ?? this.config.requestTimeout),
101
+ });
102
+ }
103
+ catch (err) {
104
+ // Only a failed connection is retried, and only for idempotent calls:
105
+ // the request may have reached the service. A timeout is never retried.
106
+ const waitMs = policy === "idempotent" && err instanceof TypeError ? nextWait() : undefined;
107
+ if (waitMs === undefined)
108
+ throw err;
109
+ await sleep(waitMs);
110
+ waitedMs += waitMs;
111
+ continue;
112
+ }
113
+ if (resp.ok)
114
+ return resp;
115
+ const error = await this.toError(resp, policy, errorPrefix);
116
+ const autoRetry = error.retryable && !(error.reason && ACCOUNT_LIMIT_REASONS.has(error.reason));
117
+ const waitMs = autoRetry ? nextWait(error.retryAfterSeconds) : undefined;
118
+ if (waitMs === undefined)
119
+ throw error;
120
+ await sleep(waitMs);
121
+ waitedMs += waitMs;
122
+ }
123
+ }
37
124
  async get(path, params) {
38
- const url = this.buildUrl(path, params);
39
- const resp = await fetch(url, {
125
+ const resp = await this.request(this.buildUrl(path, params), "idempotent", "API error", () => ({
40
126
  method: "GET",
41
127
  headers: this.authHeaders,
42
- signal: AbortSignal.timeout(this.config.requestTimeout),
43
- });
128
+ }));
44
129
  return this.handleWithDecrypt(resp);
45
130
  }
46
- async post(path, body) {
131
+ /**
132
+ * POST a JSON body. By default the request is retried only when the service
133
+ * refused it without acting on it (`"refusal"`); pass `retry: "idempotent"`
134
+ * for calls that are safe to repeat and `retry: "never"` for calls that must
135
+ * not be sent twice.
136
+ */
137
+ async post(path, body, opts) {
47
138
  let actualBody = body;
48
139
  if (this.e2eeKey && body != null) {
49
140
  const envelope = await encryptE2EEJSON(this.e2eeKey, body);
50
141
  actualBody = { _encrypted: envelope };
51
142
  }
52
143
  const jsonBody = actualBody != null ? JSON.stringify(actualBody) : undefined;
53
- for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
54
- const resp = await fetch(this.buildUrl(path), {
55
- method: "POST",
56
- headers: this.jsonHeaders,
57
- body: jsonBody,
58
- signal: AbortSignal.timeout(this.config.requestTimeout),
59
- });
60
- if (isRetryable(resp.status) && attempt < MAX_RETRIES - 1) {
61
- // Drain response body before retrying
62
- await resp.text();
63
- continue;
64
- }
65
- return this.handleWithDecrypt(resp);
66
- }
67
- // Unreachable, but TypeScript needs it
68
- throw new SandboxError("max retries exceeded");
144
+ const resp = await this.request(this.buildUrl(path), opts?.retry ?? "refusal", "API error", () => ({ method: "POST", headers: this.jsonHeaders, body: jsonBody }), opts?.timeoutMs);
145
+ return this.handleWithDecrypt(resp);
69
146
  }
70
147
  async delete(path, params) {
71
- const url = this.buildUrl(path, params);
72
- const resp = await fetch(url, {
148
+ const resp = await this.request(this.buildUrl(path, params), "idempotent", "API error", () => ({
73
149
  method: "DELETE",
74
150
  headers: this.authHeaders,
75
- signal: AbortSignal.timeout(this.config.requestTimeout),
76
- });
77
- if (resp.status === 204)
78
- return;
79
- if (!resp.ok) {
80
- const text = await resp.text();
81
- throw new SandboxError(`API error ${resp.status}: ${text}`);
82
- }
151
+ }));
152
+ // Drain the body so the connection can be reused.
153
+ await resp.text();
83
154
  }
84
155
  async download(path, params) {
85
- const url = this.buildUrl(path, params);
86
- const resp = await fetch(url, {
156
+ const resp = await this.request(this.buildUrl(path, params), "idempotent", "Download error", () => ({
87
157
  method: "GET",
88
158
  headers: { "X-API-Key": this.config.apiKey || "" },
89
- signal: AbortSignal.timeout(this.config.requestTimeout),
90
- });
91
- if (!resp.ok) {
92
- throw new SandboxError(`Download error ${resp.status}: ${await resp.text()}`);
93
- }
159
+ }));
94
160
  return new Uint8Array(await resp.arrayBuffer());
95
161
  }
96
162
  async streamDownload(path, params) {
@@ -100,7 +166,7 @@ export class HTTPClient {
100
166
  headers: { "X-API-Key": this.config.apiKey || "" },
101
167
  });
102
168
  if (!resp.ok) {
103
- throw new SandboxError(`Download error ${resp.status}: ${await resp.text()}`);
169
+ throw await this.toError(resp, "idempotent", "Download error");
104
170
  }
105
171
  if (!resp.body) {
106
172
  throw new SandboxError("No response body for stream download");
@@ -108,38 +174,23 @@ export class HTTPClient {
108
174
  return resp.body;
109
175
  }
110
176
  async getWithHeaders(path, params) {
111
- const url = this.buildUrl(path, params);
112
- const resp = await fetch(url, {
177
+ const resp = await this.request(this.buildUrl(path, params), "idempotent", "API error", () => ({
113
178
  method: "GET",
114
179
  headers: this.authHeaders,
115
- signal: AbortSignal.timeout(this.config.requestTimeout),
116
- });
180
+ }));
117
181
  const data = await this.handle(resp);
118
182
  return { data, headers: resp.headers };
119
183
  }
184
+ /** Upload a file (multipart). Writing the same file twice is harmless, so this is retried as idempotent. */
120
185
  async upload(path, filePath, content, filename) {
121
- const headers = {};
122
- if (this.config.apiKey) {
123
- headers["X-API-Key"] = this.config.apiKey;
124
- }
125
- for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
186
+ const resp = await this.request(this.buildUrl(path), "idempotent", "API error", () => {
126
187
  // Rebuild FormData for each attempt since the body stream is consumed
127
188
  const form = new FormData();
128
189
  form.append("path", filePath);
129
190
  form.append("file", new Blob([content]), filename);
130
- const resp = await fetch(this.buildUrl(path), {
131
- method: "POST",
132
- headers,
133
- body: form,
134
- signal: AbortSignal.timeout(this.config.requestTimeout),
135
- });
136
- if (isRetryable(resp.status) && attempt < MAX_RETRIES - 1) {
137
- await resp.text();
138
- continue;
139
- }
140
- return this.handle(resp);
141
- }
142
- throw new SandboxError("max retries exceeded");
191
+ return { method: "POST", headers: this.authHeaders, body: form };
192
+ });
193
+ return this.handle(resp);
143
194
  }
144
195
  async *streamSSE(path, params) {
145
196
  const url = this.buildUrl(path, params);
@@ -187,8 +238,7 @@ export class HTTPClient {
187
238
  }
188
239
  async handle(resp) {
189
240
  if (!resp.ok) {
190
- const msg = await this.errorMessage(resp);
191
- throw new SandboxError(`API error ${resp.status}: ${msg}`);
241
+ throw await this.toError(resp, "never", "API error");
192
242
  }
193
243
  if (resp.status === 204) {
194
244
  return undefined;
@@ -208,7 +258,8 @@ export class HTTPClient {
208
258
  }
209
259
  async *parseSSE(resp) {
210
260
  if (!resp.ok) {
211
- throw new StreamError(`Stream error ${resp.status}: ${await this.errorMessage(resp)}`);
261
+ const { message, info } = await this.errorInfo(resp, "never");
262
+ throw new StreamError(`Stream error ${resp.status}: ${message}`, resp.status, info);
212
263
  }
213
264
  const reader = resp.body?.getReader();
214
265
  if (!reader)
@@ -239,25 +290,45 @@ export class HTTPClient {
239
290
  reader.releaseLock();
240
291
  }
241
292
  }
242
- async errorMessage(resp) {
293
+ /** Build the {@link SandboxError} for an error response. */
294
+ async toError(resp, policy, prefix) {
295
+ const { message, info } = await this.errorInfo(resp, policy);
296
+ return new SandboxError(`${prefix} ${resp.status}: ${message}`, resp.status, info);
297
+ }
298
+ /** Read the message, `reason`, `detail` and `Retry-After` of an error response. */
299
+ async errorInfo(resp, policy) {
243
300
  const raw = await resp.text();
244
- if (!raw)
245
- return "request failed";
301
+ let message = raw || "request failed";
302
+ let reason;
303
+ let detail;
246
304
  try {
247
305
  const parsed = JSON.parse(raw);
248
- if (typeof parsed === "string")
249
- return parsed;
250
- if (parsed && typeof parsed === "object") {
306
+ if (typeof parsed === "string") {
307
+ message = parsed;
308
+ }
309
+ else if (parsed && typeof parsed === "object") {
251
310
  const obj = parsed;
252
311
  if (typeof obj.message === "string")
253
- return obj.message;
254
- if (typeof obj.error === "string")
255
- return obj.error;
312
+ message = obj.message;
313
+ else if (typeof obj.error === "string")
314
+ message = obj.error;
315
+ if (typeof obj.reason === "string")
316
+ reason = obj.reason;
317
+ if (typeof obj.detail === "string")
318
+ detail = obj.detail;
256
319
  }
257
- return raw;
258
320
  }
259
321
  catch {
260
- return raw;
322
+ // Not JSON: keep the raw text.
261
323
  }
324
+ return {
325
+ message,
326
+ info: {
327
+ reason,
328
+ detail,
329
+ retryAfterSeconds: parseRetryAfter(resp.headers.get("retry-after")),
330
+ retryable: isRetryable(policy, resp.status, reason),
331
+ },
332
+ };
262
333
  }
263
334
  }
@@ -1,12 +1,22 @@
1
1
  import type { HTTPClient } from "./client.js";
2
2
  import { CommandHandle } from "./command-handle.js";
3
3
  import type { CommandResult, ProcessInfo, RunCommandOptions } from "./models.js";
4
+ /** HTTP request timeout (ms) for a blocking command with the given timeout (s). */
5
+ export declare function commandRequestTimeoutMs(timeoutSeconds?: number): number;
4
6
  /** Command execution namespace for a single sandbox. */
5
7
  export declare class Commands {
6
8
  private sandboxId;
7
9
  private client;
8
10
  constructor(sandboxId: string, client: HTTPClient);
9
11
  private get baseUrl();
12
+ /**
13
+ * Run a shell command. A blocking call waits for the command for as long as
14
+ * its `timeout` allows (default 60 s, at most 3600 s) plus a margin.
15
+ *
16
+ * The request is never retried automatically: after a `502
17
+ * node_connection_lost` the command may have run. Check the sandbox before
18
+ * running it again.
19
+ */
10
20
  run(cmd: string, opts?: RunCommandOptions): Promise<CommandResult>;
11
21
  run(cmd: string, opts: RunCommandOptions & {
12
22
  background: true;
package/dist/commands.js CHANGED
@@ -13,6 +13,18 @@ function parseProcessInfo(p) {
13
13
  endedAt: p.ended_at ?? p.endedAt,
14
14
  };
15
15
  }
16
+ /** Default command timeout in seconds, and the service's maximum. */
17
+ const DEFAULT_COMMAND_TIMEOUT_S = 60;
18
+ const MAX_COMMAND_TIMEOUT_S = 3600;
19
+ /** Margin on top of the command timeout before the HTTP request gives up. */
20
+ const COMMAND_REQUEST_MARGIN_MS = 15_000;
21
+ /** HTTP request timeout (ms) for a blocking command with the given timeout (s). */
22
+ export function commandRequestTimeoutMs(timeoutSeconds) {
23
+ const seconds = timeoutSeconds != null && timeoutSeconds > 0
24
+ ? Math.min(timeoutSeconds, MAX_COMMAND_TIMEOUT_S)
25
+ : DEFAULT_COMMAND_TIMEOUT_S;
26
+ return seconds * 1000 + COMMAND_REQUEST_MARGIN_MS;
27
+ }
16
28
  /** Command execution namespace for a single sandbox. */
17
29
  export class Commands {
18
30
  sandboxId;
@@ -27,8 +39,10 @@ export class Commands {
27
39
  async run(cmd, opts) {
28
40
  const body = {
29
41
  command: cmd,
30
- timeout: opts?.timeout ?? 60,
42
+ timeout: opts?.timeout ?? DEFAULT_COMMAND_TIMEOUT_S,
31
43
  };
44
+ // Starting a process is not idempotent: never re-send it.
45
+ const startOpts = { retry: "never", timeoutMs: opts?.requestTimeout };
32
46
  if (opts?.cwd)
33
47
  body.cwd = opts.cwd;
34
48
  if (opts?.envs)
@@ -37,13 +51,13 @@ export class Commands {
37
51
  body.user = opts.user;
38
52
  if (opts?.background) {
39
53
  body.background = true;
40
- const data = await this.client.post(this.baseUrl, body);
54
+ const data = await this.client.post(this.baseUrl, body, startOpts);
41
55
  return new CommandHandle(data.pid, this.sandboxId, this.client);
42
56
  }
43
57
  // Streaming via callbacks
44
58
  if (opts?.onStdout || opts?.onStderr) {
45
59
  body.background = true;
46
- const data = await this.client.post(this.baseUrl, body);
60
+ const data = await this.client.post(this.baseUrl, body, startOpts);
47
61
  const handle = new CommandHandle(data.pid, this.sandboxId, this.client);
48
62
  const result = await handle.stream({
49
63
  onStdout: opts.onStdout,
@@ -55,7 +69,10 @@ export class Commands {
55
69
  return result;
56
70
  }
57
71
  // Synchronous execution
58
- const data = await this.client.post(this.baseUrl, body);
72
+ const data = await this.client.post(this.baseUrl, body, {
73
+ retry: "never",
74
+ timeoutMs: opts?.requestTimeout ?? commandRequestTimeoutMs(opts?.timeout),
75
+ });
59
76
  const result = makeCommandResult(data);
60
77
  if (result.exitCode !== 0) {
61
78
  throw new CommandExitException(result.stdout, result.stderr, result.exitCode);
@@ -75,7 +92,7 @@ export class Commands {
75
92
  await this.client.delete(`${this.baseUrl}/${pid}`);
76
93
  }
77
94
  async sendStdin(pid, data) {
78
- await this.client.post(`${this.baseUrl}/${pid}/stdin`, { data });
95
+ await this.client.post(`${this.baseUrl}/${pid}/stdin`, { data }, { retry: "never" });
79
96
  }
80
97
  connect(pid) {
81
98
  return new CommandHandle(pid, this.sandboxId, this.client);
package/dist/config.d.ts CHANGED
@@ -1,12 +1,24 @@
1
+ /** Bounds for automatic retries. See the README for which requests are retried. */
2
+ export interface RetryOptions {
3
+ /** Maximum number of attempts per request, including the first. Default `3`. `1` disables retries. */
4
+ maxAttempts?: number;
5
+ /** Maximum total time in milliseconds spent waiting between attempts of one request. Default `30000`. */
6
+ maxTotalWaitMs?: number;
7
+ }
8
+ export declare const DEFAULT_RETRY_MAX_ATTEMPTS = 3;
9
+ export declare const DEFAULT_RETRY_MAX_TOTAL_WAIT_MS = 30000;
1
10
  /** Connection options for OmniRun API calls. */
2
11
  export interface ConnectionConfig {
3
12
  apiUrl: string;
4
13
  apiKey: string;
5
14
  requestTimeout: number;
15
+ /** Automatic retry bounds, or `false` to switch automatic retries off. */
16
+ retry?: RetryOptions | false;
6
17
  }
7
18
  /** Resolves runtime config from explicit options, env vars, and defaults. */
8
19
  export declare function resolveConfig(opts?: {
9
20
  apiUrl?: string;
10
21
  apiKey?: string;
11
22
  requestTimeout?: number;
23
+ retry?: RetryOptions | false;
12
24
  }): ConnectionConfig;
package/dist/config.js CHANGED
@@ -1,3 +1,5 @@
1
+ export const DEFAULT_RETRY_MAX_ATTEMPTS = 3;
2
+ export const DEFAULT_RETRY_MAX_TOTAL_WAIT_MS = 30_000;
1
3
  /** Resolves runtime config from explicit options, env vars, and defaults. */
2
4
  export function resolveConfig(opts) {
3
5
  return {
@@ -12,5 +14,6 @@ export function resolveConfig(opts) {
12
14
  : undefined) ||
13
15
  "",
14
16
  requestTimeout: opts?.requestTimeout ?? 60_000,
17
+ retry: opts?.retry,
15
18
  };
16
19
  }
package/dist/contexts.js CHANGED
@@ -38,7 +38,7 @@ export class Contexts {
38
38
  if (opts?.onStdout || opts?.onStderr || opts?.onResult) {
39
39
  return this.streamExecute(contextId, code, opts);
40
40
  }
41
- const data = await this.client.post(`${this.baseUrl}/${contextId}/execute`, { code });
41
+ const data = await this.client.post(`${this.baseUrl}/${contextId}/execute`, { code }, { retry: "never" });
42
42
  return parseExecutionResult(data);
43
43
  }
44
44
  /** Delete an interpreter context. */
package/dist/errors.d.ts CHANGED
@@ -1,5 +1,35 @@
1
+ /** Machine-readable details the service sends with an error response. */
2
+ export interface SandboxErrorInfo {
3
+ /** Stable machine-readable reason, e.g. `"no_capacity"` or `"node_unavailable"`. */
4
+ reason?: string;
5
+ /** Extra detail some refusals carry (e.g. the budget behind `no_capacity`). For information only. */
6
+ detail?: string;
7
+ /** Parsed `Retry-After` header in seconds, when the service sent one. */
8
+ retryAfterSeconds?: number;
9
+ /** Whether sending the same request again is safe under the SDK's retry rules. */
10
+ retryable?: boolean;
11
+ }
1
12
  export declare class SandboxError extends Error {
2
- constructor(message: string);
13
+ /** HTTP status code that produced this error, if applicable. */
14
+ status?: number;
15
+ /**
16
+ * Stable machine-readable reason from the service (`no_capacity`,
17
+ * `node_unavailable`, `unknown_region`, `approval_required`, ...).
18
+ * Branch on `status` and `reason`, never on `message`.
19
+ */
20
+ reason?: string;
21
+ /** Extra detail some refusals carry. For information only; do not branch on it. */
22
+ detail?: string;
23
+ /** Seconds the service asked to wait before retrying (`Retry-After`), or `undefined`. */
24
+ retryAfterSeconds?: number;
25
+ /**
26
+ * `true` when sending the same request again is safe: the service refused it
27
+ * without doing anything (or the call is idempotent). `false` when the
28
+ * request may have taken effect (e.g. `502 node_connection_lost` on a
29
+ * command, `504` on a create) or when retrying cannot help (4xx).
30
+ */
31
+ retryable: boolean;
32
+ constructor(message: string, status?: number, info?: SandboxErrorInfo);
3
33
  }
4
34
  export declare class SandboxNotFoundError extends SandboxError {
5
35
  constructor(sandboxId: string);
@@ -11,7 +41,7 @@ export declare class CommandExitException extends SandboxError {
11
41
  constructor(stdout: string, stderr: string, exitCode: number);
12
42
  }
13
43
  export declare class StreamError extends SandboxError {
14
- constructor(message: string);
44
+ constructor(message: string, status?: number, info?: SandboxErrorInfo);
15
45
  }
16
46
  export declare class TimeoutError extends SandboxError {
17
47
  constructor(message: string);
package/dist/errors.js CHANGED
@@ -1,12 +1,36 @@
1
1
  export class SandboxError extends Error {
2
- constructor(message) {
2
+ /** HTTP status code that produced this error, if applicable. */
3
+ status;
4
+ /**
5
+ * Stable machine-readable reason from the service (`no_capacity`,
6
+ * `node_unavailable`, `unknown_region`, `approval_required`, ...).
7
+ * Branch on `status` and `reason`, never on `message`.
8
+ */
9
+ reason;
10
+ /** Extra detail some refusals carry. For information only; do not branch on it. */
11
+ detail;
12
+ /** Seconds the service asked to wait before retrying (`Retry-After`), or `undefined`. */
13
+ retryAfterSeconds;
14
+ /**
15
+ * `true` when sending the same request again is safe: the service refused it
16
+ * without doing anything (or the call is idempotent). `false` when the
17
+ * request may have taken effect (e.g. `502 node_connection_lost` on a
18
+ * command, `504` on a create) or when retrying cannot help (4xx).
19
+ */
20
+ retryable;
21
+ constructor(message, status, info) {
3
22
  super(message);
4
23
  this.name = "SandboxError";
24
+ this.status = status;
25
+ this.reason = info?.reason;
26
+ this.detail = info?.detail;
27
+ this.retryAfterSeconds = info?.retryAfterSeconds;
28
+ this.retryable = info?.retryable ?? false;
5
29
  }
6
30
  }
7
31
  export class SandboxNotFoundError extends SandboxError {
8
32
  constructor(sandboxId) {
9
- super(`Sandbox ${sandboxId} not found`);
33
+ super(`Sandbox ${sandboxId} not found`, 404);
10
34
  this.name = "SandboxNotFoundError";
11
35
  }
12
36
  }
@@ -23,8 +47,8 @@ export class CommandExitException extends SandboxError {
23
47
  }
24
48
  }
25
49
  export class StreamError extends SandboxError {
26
- constructor(message) {
27
- super(message);
50
+ constructor(message, status, info) {
51
+ super(message, status, info);
28
52
  this.name = "StreamError";
29
53
  }
30
54
  }
@@ -26,7 +26,9 @@ export class Filesystem {
26
26
  async write(pathOrEntries, content, opts) {
27
27
  // Batch write
28
28
  if (Array.isArray(pathOrEntries)) {
29
- const data = await this.client.post(`${this.baseUrl}/batch`, pathOrEntries);
29
+ const data = await this.client.post(`${this.baseUrl}/batch`, pathOrEntries, {
30
+ retry: "idempotent",
31
+ });
30
32
  return data.map((r) => ({
31
33
  name: r.name ?? "",
32
34
  path: r.path ?? "",
@@ -51,7 +53,7 @@ export class Filesystem {
51
53
  const body = { path, content: content ?? "" };
52
54
  if (writeOpts?.user)
53
55
  body.user = writeOpts.user;
54
- const data = await this.client.post(this.baseUrl, body);
56
+ const data = await this.client.post(this.baseUrl, body, { retry: "idempotent" });
55
57
  return {
56
58
  name: path.split("/").pop() || "",
57
59
  path: data.path ?? path,
@@ -116,7 +118,7 @@ export class Filesystem {
116
118
  const body = { path };
117
119
  if (opts?.user)
118
120
  body.user = opts.user;
119
- await this.client.post(`${this.baseUrl}/mkdir`, body);
121
+ await this.client.post(`${this.baseUrl}/mkdir`, body, { retry: "idempotent" });
120
122
  }
121
123
  watchDir(path, opts) {
122
124
  return new WatchHandle(this.sandboxId, path, opts?.recursive ?? false, this.client);
package/dist/index.d.ts CHANGED
@@ -14,11 +14,13 @@ export { LLM } from "./llm.js";
14
14
  export type { ChatMessage, ChatCompletionRequest, ChatCompletionResponse, ChatCompletionChoice, ChatCompletionUsage, LLMUsage, LLMModel, } from "./llm.js";
15
15
  export { WatchHandle } from "./watch-handle.js";
16
16
  export { HTTPClient } from "./client.js";
17
+ export type { RetryPolicy, RequestOptions } from "./client.js";
17
18
  export { generateE2EEKeyPair, importE2EEPublicKey, deriveE2EESharedKey, encryptE2EEJSON, decryptE2EEJSON, } from "./e2ee.js";
18
19
  export { resolveConfig } from "./config.js";
19
- export type { ConnectionConfig } from "./config.js";
20
+ export type { ConnectionConfig, RetryOptions } from "./config.js";
20
21
  export { SandboxError, SandboxNotFoundError, CommandExitException, StreamError, TimeoutError, } from "./errors.js";
21
- export type { CommandResult, EntryInfo, SandboxInfo, FullSandboxInfo, ExposureInfo, ExposureStatus, ExposureVisibility, ProcessInfo, PtyInfo, WriteEntry, FilesystemEvent, StreamEvent, RunCommandOptions, CreateSandboxOptions, CreateExposureOptions, ListSandboxOptions, RefreshExposureOptions, ContextInfo, ResultItem, LogOutput, ExecutionResult, SandboxMetrics, MetricsSnapshot, NetworkPolicy, WebhookInfo, CodeResult, } from "./models.js";
22
+ export type { SandboxErrorInfo } from "./errors.js";
23
+ export type { CommandResult, EntryInfo, SandboxInfo, FullSandboxInfo, RegionInfo, ConnectOptions, ExposureInfo, ExposureStatus, ExposureVisibility, ProcessInfo, PtyInfo, WriteEntry, FilesystemEvent, StreamEvent, RunCommandOptions, CreateSandboxOptions, CreateExposureOptions, ListSandboxOptions, RefreshExposureOptions, ContextInfo, ResultItem, LogOutput, ExecutionResult, SandboxMetrics, MetricsSnapshot, NetworkPolicy, WebhookInfo, CodeResult, } from "./models.js";
22
24
  export type { E2EEAlgorithm, E2EEKeyPairMaterial, E2EECreateOptions, E2EESessionInfo, EncryptedEnvelope, } from "./e2ee.js";
23
25
  export type { FileReadOptions, FileWriteOptions, FileListOptions } from "./filesystem.js";
24
26
  export type { ExecuteOptions } from "./contexts.js";