@opencoredev/sandbox-sdk 0.2.0 → 1.0.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.
Files changed (199) hide show
  1. package/CHANGELOG.md +74 -11
  2. package/README.md +357 -25
  3. package/dist/ai.d.ts +5 -0
  4. package/dist/ai.js +1 -0
  5. package/dist/chunk-23tjmd39.js +8 -0
  6. package/dist/chunk-2ts3evzh.js +2 -0
  7. package/dist/chunk-83avbjns.js +2 -0
  8. package/dist/chunk-8786zrns.js +2 -0
  9. package/dist/chunk-8wq767xb.js +17 -0
  10. package/dist/chunk-9w9rddra.js +2 -0
  11. package/dist/chunk-bd481sb7.js +2 -0
  12. package/dist/chunk-ckym4cht.js +23 -0
  13. package/dist/chunk-gw3n7sx7.js +5 -0
  14. package/dist/chunk-hgrwyjrb.js +2 -0
  15. package/dist/chunk-hzbssbep.js +31 -0
  16. package/dist/chunk-k60b4r27.js +2 -0
  17. package/dist/chunk-kk1hw8wa.js +1 -0
  18. package/dist/chunk-nw845a93.js +27 -0
  19. package/dist/chunk-q5vqajhg.js +2 -0
  20. package/dist/chunk-vy1j4r8f.js +2 -0
  21. package/dist/chunk-x681p5d2.js +68 -0
  22. package/dist/chunk-xgxfy2n8.js +4 -0
  23. package/dist/core/process-records.d.ts +25 -0
  24. package/dist/errors.d.ts +126 -0
  25. package/dist/files.d.ts +64 -0
  26. package/dist/git.d.ts +28 -0
  27. package/dist/handle.d.ts +4 -0
  28. package/dist/http.d.ts +225 -0
  29. package/dist/index.d.ts +19 -0
  30. package/dist/index.js +1 -0
  31. package/dist/keys.d.ts +10 -0
  32. package/dist/logs.d.ts +8 -0
  33. package/dist/mastra.d.ts +43 -0
  34. package/dist/mastra.js +1 -0
  35. package/dist/memory.d.ts +37 -0
  36. package/dist/memory.js +13 -0
  37. package/dist/native.d.ts +127 -0
  38. package/dist/openai.d.ts +39 -0
  39. package/dist/openai.js +1 -0
  40. package/dist/peer.d.ts +14 -0
  41. package/dist/processes.d.ts +71 -0
  42. package/dist/provider.d.ts +171 -0
  43. package/dist/provider.js +1 -0
  44. package/dist/providers/agentos/errors.d.ts +5 -0
  45. package/dist/providers/agentos/index.d.ts +4 -0
  46. package/dist/providers/agentos/index.js +2 -0
  47. package/dist/providers/agentos/provider.d.ts +50 -0
  48. package/dist/providers/boat/index.d.ts +66 -0
  49. package/dist/providers/boat/index.js +1 -0
  50. package/dist/providers/boat-api/errors.d.ts +6 -0
  51. package/dist/providers/boat-api/exec.d.ts +24 -0
  52. package/dist/providers/boat-api/follow.d.ts +24 -0
  53. package/dist/providers/boat-api/index.d.ts +60 -0
  54. package/dist/providers/boat-api/transport.d.ts +77 -0
  55. package/dist/providers/boxd/errors.d.ts +3 -0
  56. package/dist/providers/boxd/execute.d.ts +3 -0
  57. package/dist/providers/boxd/index.d.ts +3 -0
  58. package/dist/providers/boxd/index.js +105 -0
  59. package/dist/providers/boxd/provider.d.ts +74 -0
  60. package/dist/providers/boxd/transfers.d.ts +28 -0
  61. package/dist/providers/daytona/api.d.ts +124 -0
  62. package/dist/providers/daytona/buffered.d.ts +3 -0
  63. package/dist/providers/daytona/errors.d.ts +19 -0
  64. package/dist/providers/daytona/exec.d.ts +14 -0
  65. package/dist/providers/daytona/index.d.ts +73 -0
  66. package/dist/providers/daytona/index.js +96 -0
  67. package/dist/providers/daytona/multipart.d.ts +25 -0
  68. package/dist/providers/e2b/envd.d.ts +113 -0
  69. package/dist/providers/e2b/errors.d.ts +20 -0
  70. package/dist/providers/e2b/index.d.ts +53 -0
  71. package/dist/providers/e2b/index.js +1 -0
  72. package/dist/providers/freestyle/client.d.ts +87 -0
  73. package/dist/providers/freestyle/deadline.d.ts +5 -0
  74. package/dist/providers/freestyle/errors.d.ts +29 -0
  75. package/dist/providers/freestyle/execute.d.ts +8 -0
  76. package/dist/providers/freestyle/index.d.ts +40 -0
  77. package/dist/providers/freestyle/index.js +105 -0
  78. package/dist/providers/local/docker.d.ts +36 -0
  79. package/dist/providers/local/index.d.ts +46 -0
  80. package/dist/providers/local/index.js +2 -0
  81. package/dist/providers/railway/errors.d.ts +10 -0
  82. package/dist/providers/railway/index.d.ts +3 -0
  83. package/dist/providers/railway/index.js +1 -0
  84. package/dist/providers/railway/provider.d.ts +53 -0
  85. package/dist/providers/sandboxer/index.d.ts +40 -0
  86. package/dist/providers/sandboxer/index.js +1 -0
  87. package/dist/providers/superserve/bootstrap.d.ts +11 -0
  88. package/dist/providers/superserve/errors.d.ts +3 -0
  89. package/dist/providers/superserve/execute.d.ts +8 -0
  90. package/dist/providers/superserve/index.d.ts +52 -0
  91. package/dist/providers/superserve/index.js +94 -0
  92. package/dist/providers/superserve/routes.d.ts +80 -0
  93. package/dist/providers/superserve/session.d.ts +33 -0
  94. package/dist/providers/tenki/deadline.d.ts +2 -0
  95. package/dist/providers/tenki/errors.d.ts +10 -0
  96. package/dist/providers/tenki/exec.d.ts +4 -0
  97. package/dist/providers/tenki/files.d.ts +3 -0
  98. package/dist/providers/tenki/index.d.ts +3 -0
  99. package/dist/providers/tenki/index.js +175 -0
  100. package/dist/providers/tenki/provider.d.ts +95 -0
  101. package/dist/providers/tenki/ready.d.ts +7 -0
  102. package/dist/providers/tenki/records.d.ts +16 -0
  103. package/dist/providers/tenki/stream.d.ts +3 -0
  104. package/dist/providers/upstash/buffered.d.ts +3 -0
  105. package/dist/providers/upstash/errors.d.ts +3 -0
  106. package/dist/providers/upstash/exec.d.ts +18 -0
  107. package/dist/providers/upstash/files.d.ts +15 -0
  108. package/dist/providers/upstash/index.d.ts +6 -0
  109. package/dist/providers/upstash/index.js +105 -0
  110. package/dist/providers/upstash/provider.d.ts +81 -0
  111. package/dist/providers/vercel/errors.d.ts +5 -0
  112. package/dist/providers/vercel/index.d.ts +22 -0
  113. package/dist/providers/vercel/index.js +1 -0
  114. package/dist/providers/vercel/provider.d.ts +58 -0
  115. package/dist/providers/vercel/transport.d.ts +43 -0
  116. package/dist/run.d.ts +43 -0
  117. package/dist/shared/deadline.d.ts +12 -0
  118. package/dist/shared/guest.d.ts +18 -0
  119. package/dist/shared/json.d.ts +11 -0
  120. package/dist/shared/metadata.d.ts +19 -0
  121. package/dist/shared/narrow.d.ts +8 -0
  122. package/dist/shared/native-error.d.ts +42 -0
  123. package/dist/shared/paged-exec.d.ts +22 -0
  124. package/dist/shared/shell.d.ts +2 -0
  125. package/dist/shared/wire.d.ts +10 -0
  126. package/dist/shell/process-records.d.ts +44 -0
  127. package/dist/streams.d.ts +72 -0
  128. package/dist/testing.d.ts +27 -0
  129. package/dist/testing.js +9 -0
  130. package/dist/tool-security.d.ts +9 -0
  131. package/dist/tools.d.ts +118 -0
  132. package/dist/tools.js +1 -0
  133. package/dist/types.d.ts +197 -0
  134. package/package.json +143 -102
  135. package/dist/agentos-CbrZW7R0.mjs +0 -390
  136. package/dist/agentos-CbrZW7R0.mjs.map +0 -1
  137. package/dist/ai/harness.d.mts +0 -16
  138. package/dist/ai/harness.mjs +0 -69
  139. package/dist/ai/harness.mjs.map +0 -1
  140. package/dist/ai/index.d.mts +0 -54
  141. package/dist/ai/index.mjs +0 -4
  142. package/dist/ai-DeFa8yPk.mjs +0 -243
  143. package/dist/ai-DeFa8yPk.mjs.map +0 -1
  144. package/dist/capabilities-BWvOVFbH.d.mts +0 -15
  145. package/dist/capabilities-CaSNd6J1.mjs +0 -125
  146. package/dist/capabilities-CaSNd6J1.mjs.map +0 -1
  147. package/dist/capabilities-xs9kaHrK.mjs +0 -28
  148. package/dist/capabilities-xs9kaHrK.mjs.map +0 -1
  149. package/dist/errors-BuF9bYOQ.mjs +0 -68
  150. package/dist/errors-BuF9bYOQ.mjs.map +0 -1
  151. package/dist/eve/index.d.mts +0 -19
  152. package/dist/eve/index.mjs +0 -155
  153. package/dist/eve/index.mjs.map +0 -1
  154. package/dist/index-CkTwqD0X.d.mts +0 -25
  155. package/dist/index-Dh9xob2s.d.mts +0 -31
  156. package/dist/index.d.mts +0 -5
  157. package/dist/index.mjs +0 -40
  158. package/dist/index.mjs.map +0 -1
  159. package/dist/managed-provider-BsZGVQ4I.mjs +0 -148
  160. package/dist/managed-provider-BsZGVQ4I.mjs.map +0 -1
  161. package/dist/mastra/index.d.mts +0 -118
  162. package/dist/mastra/index.mjs +0 -662
  163. package/dist/mastra/index.mjs.map +0 -1
  164. package/dist/metadata.d.mts +0 -34
  165. package/dist/metadata.mjs +0 -135
  166. package/dist/metadata.mjs.map +0 -1
  167. package/dist/provider-DOBErkBO.d.mts +0 -91
  168. package/dist/provider-utils-CfB9nvJx.mjs +0 -57
  169. package/dist/provider-utils-CfB9nvJx.mjs.map +0 -1
  170. package/dist/providers/agentos/index.d.mts +0 -7
  171. package/dist/providers/agentos/index.mjs +0 -9
  172. package/dist/providers/box/index.d.mts +0 -34
  173. package/dist/providers/box/index.mjs +0 -348
  174. package/dist/providers/box/index.mjs.map +0 -1
  175. package/dist/providers/daytona/index.d.mts +0 -21
  176. package/dist/providers/daytona/index.mjs +0 -206
  177. package/dist/providers/daytona/index.mjs.map +0 -1
  178. package/dist/providers/e2b/index.d.mts +0 -17
  179. package/dist/providers/e2b/index.mjs +0 -169
  180. package/dist/providers/e2b/index.mjs.map +0 -1
  181. package/dist/providers/local/index.d.mts +0 -22
  182. package/dist/providers/local/index.mjs +0 -22
  183. package/dist/providers/local/index.mjs.map +0 -1
  184. package/dist/providers/railway/index.d.mts +0 -29
  185. package/dist/providers/railway/index.mjs +0 -211
  186. package/dist/providers/railway/index.mjs.map +0 -1
  187. package/dist/providers/upstash/index.d.mts +0 -17
  188. package/dist/providers/upstash/index.mjs +0 -211
  189. package/dist/providers/upstash/index.mjs.map +0 -1
  190. package/dist/providers/vercel/index.d.mts +0 -28
  191. package/dist/providers/vercel/index.mjs +0 -186
  192. package/dist/providers/vercel/index.mjs.map +0 -1
  193. package/dist/sandbox-DdEqoXJF.d.mts +0 -26
  194. package/dist/sandbox-DgtY5hvt.mjs +0 -112
  195. package/dist/sandbox-DgtY5hvt.mjs.map +0 -1
  196. package/dist/testing/index.d.mts +0 -27
  197. package/dist/testing/index.mjs +0 -173
  198. package/dist/testing/index.mjs.map +0 -1
  199. package/dist/types-Bv6I2U1c.d.mts +0 -103
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The fields adapters read from a thrown native SDK error. A native SDK can throw anything, so
3
+ * each optional field is set only when the thrown value carries it with that type. Text fields
4
+ * classify the failure; they can echo the request, so what an adapter keeps goes through
5
+ * `describeNative` or a bounded allowlist.
6
+ */
7
+ export interface NativeError {
8
+ /** An Error's `name`, or "" for anything else thrown. Bundlers can rename it with the class. */
9
+ name: string;
10
+ /** An Error's `message`, or "" for anything else thrown. */
11
+ message: string;
12
+ /** A numeric `status` field. */
13
+ status?: number;
14
+ /** A numeric `statusCode` field. */
15
+ statusCode?: number;
16
+ /** The status of an attached fetch `Response`. */
17
+ responseStatus?: number;
18
+ /** boxd's gRPC status code. */
19
+ grpcCode?: number;
20
+ /** A string or numeric `code` field: an errno such as `ENOENT`, a provider code, or an RPC code. */
21
+ code?: string | number;
22
+ /** Boat's API envelope error code. */
23
+ apiCode?: string;
24
+ /** The `error.code` of a parsed response body, which the Vercel SDK attaches as `json`. */
25
+ bodyCode?: string;
26
+ /** Daytona's `source`: which Daytona service answered. */
27
+ source?: string;
28
+ /** The request path a Freestyle API error names. */
29
+ path?: string;
30
+ /** A `requestId` field. */
31
+ requestId?: string;
32
+ /** The sandbox a failed Daytona create names. */
33
+ sandboxId?: string;
34
+ /** String values of a `headers` field: a fetch `Headers` or a plain object. */
35
+ headers: ReadonlyMap<string, string>;
36
+ /** String values of a gRPC `metadata` field. */
37
+ metadata: ReadonlyMap<string, string>;
38
+ /** The value this error wraps, for adapters that read a chain. */
39
+ cause?: unknown;
40
+ }
41
+ /** Decodes the fields of {@link NativeError} from any thrown value. */
42
+ export declare function decodeNative(cause: unknown): NativeError;
@@ -0,0 +1,22 @@
1
+ import type { ExecInput, ExecResult } from "../provider.js";
2
+ import { SandboxError, type ErrorCode } from "../errors.js";
3
+ /** A guest that runs paged supervisors: Freestyle and Superserve. */
4
+ export interface PagedGuest {
5
+ raw(command: string): Promise<string>;
6
+ read(path: string, range: {
7
+ offset: number;
8
+ length: number;
9
+ }, signal?: AbortSignal): Promise<Uint8Array>;
10
+ }
11
+ export interface PagedExecution {
12
+ guest: PagedGuest;
13
+ input: ExecInput;
14
+ /** Runs the provider's supervisor for `root` and returns its first response page. */
15
+ launch: (root: string, signal: AbortSignal) => Promise<string>;
16
+ /** Builds the provider's own error, so messages keep its name and advice. */
17
+ fail: (message: string, code?: ErrorCode) => SandboxError;
18
+ }
19
+ /** Runs a command through a supervisor that answers with its first output page,
20
+ * then reads the rest of its output with bounded ranged reads.
21
+ */
22
+ export declare function pagedExecute(execution: PagedExecution): Promise<ExecResult>;
@@ -0,0 +1,2 @@
1
+ /** Quote one value as a single POSIX shell word. Safe for any string, including quotes and newlines. */
2
+ export declare function quote(value: string): string;
@@ -0,0 +1,10 @@
1
+ import type { ExecInput } from "../provider.js";
2
+ type Spec = Pick<ExecInput, "command" | "cwd" | "env" | "stdin" | "timeoutMs" | "activityPath"> & {
3
+ marker?: string;
4
+ workspace?: string;
5
+ files?: [string, string][];
6
+ };
7
+ export declare function guestSpec(spec: Spec | (Omit<Spec, "env" | "stdin"> & {
8
+ envKeys: string[];
9
+ })): Buffer;
10
+ export {};
@@ -0,0 +1,44 @@
1
+ /** Exit codes the record programs use to report a state, not a failure. */
2
+ export declare const recordExit: {
3
+ /** The log reader found no spec.json: the process was never started. */
4
+ readonly missing: 66;
5
+ /** Setup found a spec.json without an exit file: the process is still running. */
6
+ readonly running: 73;
7
+ /** Setup could not enter the working directory and recorded that as the process exit. */
8
+ readonly badCwd: 74;
9
+ };
10
+ /** Print spec.json, a NUL, a `base start size status` header line, then a base64 log window.
11
+ * It takes the writer's lock, so rotation cannot pair a new base with an old log. */
12
+ export declare function logPageScript(input: {
13
+ dir: string;
14
+ /** Absolute log offset to read after; undefined starts at the oldest kept byte. */
15
+ after: number | undefined;
16
+ lookbehind: number;
17
+ length: number;
18
+ }): string;
19
+ /** Prepare a process directory in one exec. stdin carries spec.json and restart.json as two
20
+ * base64 lines, which keeps exact UTF-8 bytes through transports that normalize input.
21
+ * A missing working directory becomes the process's own failed exit and log. */
22
+ export declare function recordSetupScript(input: {
23
+ dir: string;
24
+ cwd: string;
25
+ }): string;
26
+ /** The sed program the stream readers apply to each chunk. Each secret line is replaced
27
+ * whole, and each of its prefixes at a chunk's end and suffixes at its start, so a secret
28
+ * split across two reads is still redacted. */
29
+ export declare function redactionSedScript(secrets: readonly string[]): string;
30
+ /** The supervisor runs the command with stdout and stderr on two FIFOs, feeds each through
31
+ * a stream reader into out.log, and writes the exit code when it ends, TERM included. */
32
+ export declare function supervisorScript(input: {
33
+ dir: string;
34
+ cwd: string;
35
+ command: string;
36
+ sedPath: string;
37
+ }): string;
38
+ /** Start the supervisor detached from this exec and record its pid. With waitForExit, poll
39
+ * about 100 ms for a command that exits at once and print its exit code if it does. */
40
+ export declare function detachedLaunchScript(input: {
41
+ dir: string;
42
+ supervisor: string;
43
+ waitForExit: boolean;
44
+ }): string;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * @internal Frame readers for streamed provider responses: NDJSON, server-sent events and Connect envelopes.
3
+ *
4
+ * Each reads a `ReadableStream<Uint8Array>` and yields frames as an async iterable. Frames are split on bytes,
5
+ * so a UTF-8 character or a frame header split across chunks is reassembled. Every frame is bounded
6
+ * (`maxFrameBytes`, default 16 MiB). Leaving a `for await` early (break, return, throw) cancels the body.
7
+ *
8
+ * Failures are SandboxErrors; {@link streamFault} says which protocol fault it was, so an adapter can resume
9
+ * a `disconnected` or `truncated` stream and give up on the rest:
10
+ * - `disconnected`: reading the body failed (the connection dropped).
11
+ * - `truncated`: the body ended inside a frame, or before the protocol's terminal frame.
12
+ * - `frame_too_large`: a frame is larger than `maxFrameBytes`.
13
+ * - `malformed`: a frame is not valid for the protocol.
14
+ */
15
+ import type { JsonValue } from "./shared/json.js";
16
+ export type StreamFault = "disconnected" | "truncated" | "frame_too_large" | "malformed";
17
+ export interface StreamOptions {
18
+ /** Provider name on errors. */
19
+ provider: string;
20
+ sandboxId?: string;
21
+ /** Largest frame in bytes. Default: 16 MiB. */
22
+ maxFrameBytes?: number;
23
+ /** Stop reading, cancel the body and reject with `aborted`. */
24
+ signal?: AbortSignal;
25
+ }
26
+ /** The protocol fault behind a stream error, or `undefined` for any other error. */
27
+ export declare function streamFault(cause: unknown): StreamFault | undefined;
28
+ /**
29
+ * Newline-delimited JSON: one value per `\n`-terminated line (`\r\n` too). Blank lines are skipped. A last line
30
+ * without a newline is accepted when it parses as JSON; otherwise it is `truncated`.
31
+ */
32
+ export declare function ndjson(body: ReadableStream<Uint8Array>, options: StreamOptions): AsyncGenerator<JsonValue | undefined, void, undefined>;
33
+ /** One server-sent event. */
34
+ export interface ServerSentEvent {
35
+ /** The `event:` field. Default: `"message"`. */
36
+ event: string;
37
+ /** The `data:` lines joined with `\n`. */
38
+ data: string;
39
+ /** The last event ID seen so far (`id:` persists across events), for a `Last-Event-ID` resume. */
40
+ id?: string;
41
+ /** The `retry:` reconnection time in ms, when this event set one. */
42
+ retry?: number;
43
+ }
44
+ /**
45
+ * Server-sent events (the WHATWG `text/event-stream` format): `\n`, `\r\n` or `\r` line ends, `:` comments,
46
+ * multi-line `data`, and `id` that persists. Events with no `data` line are not dispatched, as in browsers.
47
+ * A body that ends inside an event (no blank line after it) is `truncated`, unless `lenientEnd` dispatches it.
48
+ */
49
+ export declare function sse(body: ReadableStream<Uint8Array>, options: StreamOptions & {
50
+ lenientEnd?: boolean;
51
+ }): AsyncGenerator<ServerSentEvent, void, undefined>;
52
+ /** A Connect streaming frame: a message, or the end-of-stream frame with the outcome. */
53
+ export type ConnectFrame = {
54
+ kind: "message";
55
+ message: JsonValue | undefined;
56
+ } | {
57
+ kind: "end";
58
+ error?: {
59
+ code: string;
60
+ message?: string;
61
+ details?: unknown[];
62
+ };
63
+ metadata?: Record<string, string[]>;
64
+ };
65
+ /**
66
+ * Connect protocol server-stream envelopes (JSON codec): a flags byte, a 4-byte big-endian length, then the
67
+ * payload. Flag `0x02` marks the end-of-stream frame (`{ error?, metadata? }`), which must come last. A body
68
+ * that ends without it is `truncated`; compressed frames (`0x01`) are `malformed`, since none is negotiated.
69
+ */
70
+ export declare function connectEnvelopes(body: ReadableStream<Uint8Array>, options: StreamOptions): AsyncGenerator<ConnectFrame, void, undefined>;
71
+ /** Encodes one Connect envelope with a JSON payload, for a streaming request body. */
72
+ export declare function connectEnvelope(message: JsonValue | undefined, end?: boolean): Uint8Array;
@@ -0,0 +1,27 @@
1
+ import type { Provider } from "./provider.js";
2
+ /** Register a provider-independent Vitest suite. Call inside a test module.
3
+ * live must be explicitly true to run a cloud provider. Each case calls the factory
4
+ * for a fresh provider, and the reattach check connects through a second one, so a
5
+ * factory for in-process state must return a shared instance.
6
+ * Live runs give each case 120 seconds by default, since real providers boot
7
+ * machines and cross the network; pass timeoutMs to change it.
8
+ * snapshotExpiry declares what `snapshot({ expiresInMs })` does: "honored" must
9
+ * return a snapshot, "refused" must throw unsupported or invalid_argument. snapshot()
10
+ * returns only an ID, so the suite cannot read the expiry back; check it in the
11
+ * provider's own tests. Omit it to check only the core's input validation.
12
+ * unsupported skips checks the provider cannot run, with the reason: gitPush for a
13
+ * runtime without git, httpProbe for previews that no HTTP client can reach.
14
+ */
15
+ export declare function runConformance(factory: () => Provider | Promise<Provider>, options: {
16
+ live: boolean;
17
+ ports?: number[];
18
+ timeoutMs?: number;
19
+ snapshotExpiry?: "honored" | "refused";
20
+ unsupported?: {
21
+ processes?: string;
22
+ previews?: string;
23
+ gitPush?: string;
24
+ httpProbe?: string;
25
+ fileModes?: string;
26
+ };
27
+ }): void;
@@ -0,0 +1,9 @@
1
+ import{X,O,j,W,Q}from"./chunk-hgrwyjrb.js";import{e}from"./chunk-xgxfy2n8.js";import{describe as D,test as c,expect as a,afterEach as P}from"vitest";import{mkdtemp as S,mkdir as T,writeFile as _,readFile as A,rm as R}from"node:fs/promises";import{tmpdir as I}from"node:os";import{join as w}from"node:path";function z(m,n){let f=n.timeoutMs??(n.live?120000:void 0);D("Sandbox SDK conformance",{timeout:f},()=>{let u=[],h=[];async function g(){let t=await m();if(!n.live&&!["memory","local"].includes(t.name))throw new e("Live provider refused. live is false. Enable live explicitly with provider credentials.",{code:"invalid_argument"});return t}async function d(t={},s){let o=s??await g(),i=await O(o,{ports:n.ports,...t});return u.push(i),{provider:o,box:i}}P(async()=>{await Promise.all(u.splice(0).map((t)=>t.destroy())),await Promise.all(h.splice(0).map((t)=>R(t,{recursive:!0,force:!0})))}),c("create, key lookup, connect and labels",async()=>{let t=await g(),s=`conformance-${crypto.randomUUID()}`,o=await O(t,{key:s,labels:{suite:s}});u.push(o);let i=await O(t,{key:s});u.push(i),a(o.created).toBe(!0),a(i.created).toBe(!1),a(i.id).toBe(o.id);let r=await j(t,o.id);u.push(r),a(r.native).toBeDefined(),await a.poll(async()=>(await W(t,{labels:{suite:s}})).map((p)=>p.id),{timeout:15000,interval:500}).toEqual([o.id])}),c("exit results, stdin, resolved cwd and default environment",async()=>{let{box:t}=await d();a(await t.run("false")).toMatchObject({ok:!1,exitCode:1,timedOut:!1}),a(await t.run("exit 7")).toMatchObject({exitCode:7}),a((await t.run("cat",{stdin:`input
2
+ `})).stdout).toBe(`input
3
+ `),a((await t.run("pwd")).stdout).toBe(`/workspace
4
+ `),a((await t.run(`printf '%s' "$CI:$PAGER:$GIT_TERMINAL_PROMPT:$DEBIAN_FRONTEND:$TERM:$NO_COLOR"`)).stdout).toBe("1:cat:0:noninteractive:dumb:1")});let E=Math.max(f??0,30000);c("timeout and abort kill a launched command before its delayed side effect",{timeout:E},async()=>{let{box:t}=await d(),s=Date.now();await t.run("true");let o=Date.now()-s,i=500+2*o,r=Math.ceil((i+o+500)/1000)*1000,p=500+o;async function l(b,y){let x=Promise.resolve(t.run(`echo launched > ${b}-launched; sleep ${r/1000}; echo survived > ${b}-survived`,y));return await a.poll(()=>t.files.exists(`${b}-launched`),{timeout:r,interval:20}).toBe(!0),{run:x,launchedAt:Date.now()}}async function v(b,y){let x=y+r+p-Date.now();await new Promise((C)=>setTimeout(C,Math.max(0,x))),a(await t.files.exists(`${b}-survived`)).toBe(!1)}let M=await l("timeout",{timeoutMs:i});a(await M.run).toMatchObject({timedOut:!0,exitCode:null,ok:!1}),await v("timeout",M.launchedAt);let k=new AbortController,B=await l("abort",{signal:k.signal});k.abort(),a(await B.run).toMatchObject({timedOut:!0,exitCode:null,ok:!1}),await v("abort",B.launchedAt)}),c("bounded head and tail output, interleaving and streaming",async()=>{let{box:t}=await d(),s=await t.run(`printf '${"a".repeat(1024)}END'`,{maxOutputBytes:64});a(s.truncated).toBe(!0),a(s.stdout.startsWith("a")).toBe(!0),a(s.stdout.endsWith("END")).toBe(!0),a(s.stdout).toContain("bytes cut");let o=t.run("printf A; printf B >&2; printf C"),i=[];for await(let l of o)i.push(l.text);let r=await o;a(r).toMatchObject({stdout:"AC",stderr:"B",output:i.join("")});let p=[];for await(let l of t.run("echo streamed"))p.push(l.text);a(p.join("")).toBe(`streamed
5
+ `)}),c("tag escaping and chain options prevent interpolation execution",async()=>{let{box:t}=await d(),s="x'; echo injected; printf '";a((await t.$`printf '%s' ${"x'; echo injected; printf '"}`.cwd(".").env({X:"ok"}).timeout(n.live?1e4:1000)).stdout).toBe("x'; echo injected; printf '"),a((await t.run(`printf '%s' "$X"`)).stdout).toBe("")}),c("all file primitives, exact edits, glob search, checkpoints",async()=>{let{box:t}=await d({trackChanges:!0});await t.files.write({"app/a.ts":`TODO one
6
+ second`,"app/b.ts":"two two","app/raw":new Uint8Array([0,255])}),a(await t.files.read("app/raw",{as:"bytes"})).toEqual(new Uint8Array([0,255])),a((await t.files.stat("app/a.ts")).type).toBe("file"),a((await t.files.list("app",{recursive:!0,glob:"**/*.ts"})).length).toBe(2),a(await t.files.search("TODO",{path:"app",glob:"*.ts"})).toMatchObject([{line:1,text:"TODO one"}]),await a(t.files.edit("app/a.ts",{find:"missing",replace:"x"})).rejects.toMatchObject({code:"edit_not_found"}),await a(t.files.edit("app/b.ts",{find:"two",replace:"x"})).rejects.toMatchObject({code:"edit_not_unique"});let s=await t.files.mark();await t.files.edit("app/a.ts",{find:"TODO",replace:"DONE"}),await t.files.remove("app/b.ts"),await t.files.write("app/new","new"),a(await t.files.changes({since:s})).toMatchObject({added:["/workspace/app/new"],modified:["/workspace/app/a.ts"],removed:["/workspace/app/b.ts"]}),a((await t.files.changes()).added).toContain("/workspace/app/a.ts"),await t.files.remove("app",{recursive:!0}),a(await t.files.exists("app")).toBe(!1)}),c("write mode sets permission bits and rejects invalid modes",async(t)=>{if(n.unsupported?.fileModes){t.skip(n.unsupported.fileModes);return}let{box:s}=await d();await s.files.write("modes/secret","x",{mode:384}),await s.files.write({"modes/a":"a","modes/b":"b"},{mode:416}),a((await s.run("stat -c %a modes/secret modes/a modes/b")).stdout).toBe(`600
7
+ 640
8
+ 640
9
+ `);for(let o of[-1,4096,1.5,Number.NaN])await a(s.files.write("modes/bad","x",{mode:o})).rejects.toMatchObject({code:"invalid_argument"});a(await s.files.exists("modes/bad")).toBe(!1)}),c("snapshot expiresInMs is validated, forwarded to the provider, and accepted or refused as declared",async(t)=>{let s=await g(),o=N(s),{box:i}=await d({},s);if(!X(i,"snapshot")){t.skip();return}if(await a(i.snapshot({expiresInMs:-1})).rejects.toMatchObject({code:"invalid_argument"}),a(o).toEqual([]),n.snapshotExpiry==="honored")a((await i.snapshot({expiresInMs:86400000})).id).not.toBe(""),a(o).toEqual([{expiresInMs:86400000}]);else if(n.snapshotExpiry==="refused")await a(i.snapshot({expiresInMs:86400000})).rejects.toMatchObject({name:"SandboxError",code:a.stringMatching(/^(unsupported|invalid_argument)$/)}),a(o).toEqual([{expiresInMs:86400000}])}),c("changes without since needs trackChanges or an explicit mark",async()=>{let{box:t}=await d();await a(t.files.changes()).rejects.toMatchObject({code:"invalid_argument",message:a.stringContaining("trackChanges: true")}),await t.files.write("late","x");let s=await t.files.mark("start");await t.files.write("late","y"),a((await t.files.changes()).modified).toEqual(["/workspace/late"]),a((await t.files.changes({since:s})).modified).toEqual(["/workspace/late"])}),c("upload/download round trip with ignores",async()=>{let{box:t}=await d(),s=await S(w(I(),"sdk-conformance-"));h.push(s),await T(w(s,"source")),await _(w(s,"source","keep"),"hello"),await _(w(s,"source","ignore"),"no"),await t.files.upload(w(s,"source"),"upload",{ignore:["ignore"]}),a(await t.files.exists("upload/ignore")).toBe(!1),await t.files.download("upload",w(s,"download")),a(await A(w(s,"download","keep"),"utf8")).toBe("hello")}),c("file watch observes changes",{timeout:Math.max(f??0,60000)},async()=>{let{box:t}=await d(),s=Date.now();await t.files.write("watch/file","a");let o=Date.now()-s,i=[],r=t.files.watch("watch",(l)=>i.push(l.type),{recursive:!0,intervalMs:10}),p=0;try{await a.poll(async()=>(await t.files.write("watch/file",`different-${p++}`),i),{timeout:Math.max(1e4,20*o),interval:50}).toContain("modified")}finally{r()}}),c("process logs, cursors, fresh client reattach, stop and exit-before-ready",async(t)=>{if(n.unsupported?.processes){t.skip(n.unsupported.processes);return}let{box:s}=await d(),o=await s.start("echo READY; sleep 5",{name:"dev",ready:{log:/READY/},readyTimeoutMs:2000});a(o.ready).toBe(!0);let i=await o.logs();a(i.text).toContain("READY"),a((await o.logs({after:i.nextCursor})).text).toBe("");let r=await j(await g(),s.id);u.push(r),a((await r.processes()).map((p)=>p.name)).toContain("dev"),a((await r.process("dev").logs()).text).toContain("READY"),await r.process("dev").stop({graceMs:10}),a((await o.wait()).exitCode).not.toBe(null),await a(s.start("exit 3",{name:"early",ready:{log:/never/},readyTimeoutMs:1000})).rejects.toMatchObject({code:"process_exited"})}),c("readiness timeout preserves the process",async(t)=>{if(n.unsupported?.processes){t.skip(n.unsupported.processes);return}let{box:s}=await d();await a(s.start("sleep 5",{name:"unready",ready:{log:/never/},readyTimeoutMs:30})).rejects.toMatchObject({code:"timeout"}),a(s.process("unready").ready).toBe(!1),a((await s.processes())[0]?.status).toBe("running"),await s.process("unready").stop({graceMs:10})}),c("preview and capability gating",async()=>{let{provider:t,box:s}=await d();if(n.unsupported?.previews)await a(s.preview(3000)).rejects.toMatchObject({code:"unsupported"});else a(["http:","https:"]).toContain(new URL((await s.preview(3000)).url).protocol);for(let[o,i]of[["pause","pause"],["snapshot","snapshot"],["terminal","terminal"]])a(i in s).toBe(t.capabilities.has(o));if(!t.capabilities.has("network-policy"))await a(O(t,{network:"none"})).rejects.toMatchObject({code:"unsupported"});if(!t.capabilities.has("size"))await a(O(t,{size:"small"})).rejects.toMatchObject({code:"unsupported"})}),c("close, disposal, destroy and label-scoped reaping",async()=>{let{provider:t,box:s}=await d(),o=s.id;await s.close(),a((await j(t,o)).id).toBe(o),await s.destroy(),await a(j(t,o)).rejects.toMatchObject({code:"not_found"});let i=crypto.randomUUID(),r=await O(t,{key:i,labels:{reap:i}});u.push(r),await r[Symbol.asyncDispose](),a((await t.connect(r.id)).id).toBe(r.id),a(await Q(t,{labels:{reap:i},olderThanMs:0})).toBe(1);let p=await O(t);await p[Symbol.asyncDispose](),await a(t.connect(p.id)).rejects.toMatchObject({code:"not_found"})}),c("usage counters",async()=>{let{box:t}=await d();await t.run("echo abc"),a(await t.usage()).toMatchObject({commands:1,bytesOut:4})}),c("local bare git clone, commit and push (live providers only)",async(t)=>{if(n.unsupported?.gitPush){t.skip(n.unsupported.gitPush);return}let{box:s}=await d();a((await s.run("git init --bare /tmp/sdk-bare")).ok).toBe(!0),a((await s.git.clone("/tmp/sdk-bare",{dir:"repo"})).ok).toBe(!0),await s.run("git config user.name Conformance; git config user.email test@example.com",{cwd:"repo"}),await s.files.write("repo/test","test"),a((await s.git.commit("repo",{message:"conformance",all:!0})).ok).toBe(!0),a((await s.git.status("repo")).stdout).toBe(""),a((await s.git.push("repo",{branch:"HEAD"})).ok).toBe(!0)}),c("real HTTP preview probe (live Linux providers only)",async(t)=>{let s=n.unsupported?.previews??n.unsupported?.httpProbe;if(s){t.skip(s);return}let{box:o}=await d(),i=await o.start(`node -e 'require("http").createServer((_,r)=>r.end("ok")).listen(3000,"0.0.0.0")'`,{name:"http",ready:{http:{port:3000}}});a(i.ready).toBe(!0),a((await o.preview(3000,{waitMs:2000})).url).toBeTruthy(),await i.stop()})})}function N(m){let n=[],f=m.snapshot;if(f)m.snapshot=(u,h)=>(n.push(h),f.call(m,u,h));return n}export{z as runConformance};
@@ -0,0 +1,9 @@
1
+ import type { Redactor } from "./errors.js";
2
+ import type { OutputChunk, SandboxBase } from "./types.js";
3
+ export declare function registerToolRedactor(box: SandboxBase<unknown>, redactor: Redactor): void;
4
+ export declare function redactToolText(box: SandboxBase<unknown>, text: string): string;
5
+ /** ANSI sequences and secrets can both cross transport boundaries. Normalize before redacting. */
6
+ export declare function toolOutputFilter(box: SandboxBase<unknown>, emit: (chunk: OutputChunk) => void): {
7
+ push(chunk: OutputChunk): undefined;
8
+ flush(): void;
9
+ };
@@ -0,0 +1,118 @@
1
+ import { z } from "zod";
2
+ import type { Sandbox, OutputChunk } from "./types.js";
3
+ import type { JsonValue } from "./shared/json.js";
4
+ export declare const toolSchemas: {
5
+ run: z.ZodObject<{
6
+ command: z.ZodString;
7
+ cwd: z.ZodOptional<z.ZodString>;
8
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
9
+ }, z.core.$strict>;
10
+ read_file: z.ZodObject<{
11
+ path: z.ZodString;
12
+ offset: z.ZodOptional<z.ZodNumber>;
13
+ limit: z.ZodOptional<z.ZodNumber>;
14
+ }, z.core.$strict>;
15
+ write_file: z.ZodObject<{
16
+ path: z.ZodString;
17
+ content: z.ZodString;
18
+ }, z.core.$strict>;
19
+ edit_file: z.ZodObject<{
20
+ path: z.ZodString;
21
+ find: z.ZodString;
22
+ replace: z.ZodString;
23
+ }, z.core.$strict>;
24
+ start_process: z.ZodObject<{
25
+ name: z.ZodString;
26
+ command: z.ZodString;
27
+ cwd: z.ZodOptional<z.ZodString>;
28
+ port: z.ZodOptional<z.ZodNumber>;
29
+ }, z.core.$strict>;
30
+ process_logs: z.ZodObject<{
31
+ name: z.ZodString;
32
+ cursor: z.ZodOptional<z.ZodString>;
33
+ }, z.core.$strict>;
34
+ stop_process: z.ZodObject<{
35
+ name: z.ZodString;
36
+ }, z.core.$strict>;
37
+ search: z.ZodObject<{
38
+ query: z.ZodString;
39
+ path: z.ZodOptional<z.ZodString>;
40
+ glob: z.ZodOptional<z.ZodString>;
41
+ }, z.core.$strict>;
42
+ list_files: z.ZodObject<{
43
+ path: z.ZodOptional<z.ZodString>;
44
+ glob: z.ZodOptional<z.ZodString>;
45
+ }, z.core.$strict>;
46
+ changes: z.ZodObject<{}, z.core.$strict>;
47
+ preview: z.ZodObject<{
48
+ port: z.ZodNumber;
49
+ path: z.ZodOptional<z.ZodString>;
50
+ }, z.core.$strict>;
51
+ };
52
+ export type ToolName = keyof typeof toolSchemas;
53
+ export type ToolParameters = z.infer<(typeof toolSchemas)[ToolName]>;
54
+ export type ToolEvent = {
55
+ tool: ToolName;
56
+ kind: "output";
57
+ stream: OutputChunk["stream"];
58
+ text: string;
59
+ };
60
+ export interface ToolLimits {
61
+ maxOutputBytes?: number;
62
+ timeoutMs?: number;
63
+ maxReadBytes?: number;
64
+ maxMatches?: number;
65
+ }
66
+ export interface SandboxToolsOptions {
67
+ /** Resolves file paths and cwd. Shell commands still have the sandbox's full privileges. */
68
+ root?: string;
69
+ allow?: readonly ToolName[];
70
+ deny?: readonly ToolName[];
71
+ beforeRun?: (command: string) => boolean | string | Promise<boolean | string>;
72
+ limits?: Partial<Record<ToolName, ToolLimits>>;
73
+ onEvent?: (event: ToolEvent) => void;
74
+ }
75
+ export interface ToolResult {
76
+ text: string;
77
+ }
78
+ export declare function createSandboxTools(box: Sandbox, options?: SandboxToolsOptions): {
79
+ name: "search" | "changes" | "run" | "read_file" | "write_file" | "edit_file" | "start_process" | "process_logs" | "stop_process" | "list_files" | "preview";
80
+ description: string;
81
+ inputSchema: z.ZodObject<{
82
+ command: z.ZodString;
83
+ cwd: z.ZodOptional<z.ZodString>;
84
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
85
+ }, z.core.$strict> | z.ZodObject<{
86
+ path: z.ZodString;
87
+ offset: z.ZodOptional<z.ZodNumber>;
88
+ limit: z.ZodOptional<z.ZodNumber>;
89
+ }, z.core.$strict> | z.ZodObject<{
90
+ path: z.ZodString;
91
+ content: z.ZodString;
92
+ }, z.core.$strict> | z.ZodObject<{
93
+ path: z.ZodString;
94
+ find: z.ZodString;
95
+ replace: z.ZodString;
96
+ }, z.core.$strict> | z.ZodObject<{
97
+ name: z.ZodString;
98
+ command: z.ZodString;
99
+ cwd: z.ZodOptional<z.ZodString>;
100
+ port: z.ZodOptional<z.ZodNumber>;
101
+ }, z.core.$strict> | z.ZodObject<{
102
+ name: z.ZodString;
103
+ cursor: z.ZodOptional<z.ZodString>;
104
+ }, z.core.$strict> | z.ZodObject<{
105
+ name: z.ZodString;
106
+ }, z.core.$strict> | z.ZodObject<{
107
+ query: z.ZodString;
108
+ path: z.ZodOptional<z.ZodString>;
109
+ glob: z.ZodOptional<z.ZodString>;
110
+ }, z.core.$strict> | z.ZodObject<{
111
+ path: z.ZodOptional<z.ZodString>;
112
+ glob: z.ZodOptional<z.ZodString>;
113
+ }, z.core.$strict> | z.ZodObject<{}, z.core.$strict> | z.ZodObject<{
114
+ port: z.ZodNumber;
115
+ path: z.ZodOptional<z.ZodString>;
116
+ }, z.core.$strict>;
117
+ execute(input: JsonValue, emit?: ((event: ToolEvent) => void) | undefined, signal?: AbortSignal): Promise<ToolResult>;
118
+ }[];
package/dist/tools.js ADDED
@@ -0,0 +1 @@
1
+ import{P,M}from"./chunk-nw845a93.js";import"./chunk-ckym4cht.js";import"./chunk-23tjmd39.js";export{M as createSandboxTools,P as toolSchemas};
@@ -0,0 +1,197 @@
1
+ import type { Capability, CreateInput, FileInfo, Labels, OutputChunk, Provider, SandboxInfo, Terminal, Preview, SnapshotOptions } from "./provider.js";
2
+ import type { Files } from "./files.js";
3
+ import type { Git } from "./git.js";
4
+ import type { ProcessHandle, ProcessInfo, StartOptions } from "./processes.js";
5
+ /** Your own key-to-ID store (Redis, a database row) so `createSandbox({ key })` finds the same sandbox from any server. */
6
+ export interface Locator {
7
+ /** Return the sandbox ID stored for `key`, or `undefined`/`null` when there is none. */
8
+ get(key: string): Promise<string | undefined | null>;
9
+ /** Store the sandbox ID for `key`. Called after every create or lookup. */
10
+ set(key: string, id: string): Promise<void>;
11
+ /** Forget `key`. Called by `destroy()`. */
12
+ delete?(key: string): Promise<void>;
13
+ /** Run `action` while holding a distributed lock on `key`. Required for cross-host exactness with a best-effort provider. */
14
+ withLock?<T>(key: string, action: () => Promise<T>): Promise<T>;
15
+ }
16
+ /** Options for `createSandbox`. Every field is optional. */
17
+ export interface CreateOptions extends Omit<CreateInput, "labels"> {
18
+ /** Your own tags. `listSandboxes` and `reapSandboxes` filter on them. The `sandbox-sdk` label is reserved. */
19
+ labels?: Record<string, string>;
20
+ /** Environment variables that are redacted from output, errors, and agent tool results. Names must be valid shell identifiers. */
21
+ secrets?: Record<string, string>;
22
+ /** Advanced. External key store used with `key`. Most apps only need `key`. */
23
+ locator?: Locator;
24
+ /** Advanced. `"exact"` refuses to run unless one sandbox per key is guaranteed (a provider with unique names, or `locator.withLock`). Default: best effort. */
25
+ keyMode?: "exact" | "best-effort";
26
+ /** Record a "start" checkpoint at create so `files.changes()` works without `since`. Costs one exec. */
27
+ trackChanges?: boolean;
28
+ }
29
+ /** Options for `connectSandbox`. */
30
+ export interface ConnectOptions extends Pick<CreateOptions, "secrets"> {
31
+ /**
32
+ * Read back the secrets recorded at creation so they stay in the environment and redacted. It costs one
33
+ * command, run before the first `run`, `start`, `process`, `files`, or `terminal` call, never on connect.
34
+ * `destroy`, `close`, `pause`, `resume`, `snapshot`, and `usage` never need it. Pass `false` to skip it,
35
+ * for example when the handle only inspects or cleans up a sandbox. Default: `true`.
36
+ */
37
+ recoverSecrets?: boolean;
38
+ }
39
+ /** Options for `listSandboxes`. */
40
+ export interface ListOptions {
41
+ /** Only return sandboxes that carry every one of these labels. */
42
+ labels?: Labels;
43
+ }
44
+ /** Options for `reapSandboxes`. */
45
+ export interface ReapOptions extends ListOptions {
46
+ /** Only destroy sandboxes at least this old, in milliseconds. Default: 0. */
47
+ olderThanMs?: number;
48
+ /** Skip sandboxes with an active SDK command or a running background process. */
49
+ idleOnly?: boolean;
50
+ }
51
+ /** Per-command options for `box.run`. */
52
+ export interface RunOptions {
53
+ /** Working directory. Relative paths resolve against `/workspace`. Default: `/workspace`. */
54
+ cwd?: string;
55
+ /** Extra environment variables for this command only. */
56
+ env?: Record<string, string>;
57
+ /** Kill the command after this many milliseconds and resolve with `timedOut: true`. Default: 120000. */
58
+ timeoutMs?: number;
59
+ /** Keep at most this many bytes per stream; older output is dropped and `truncated` is set. Default: 1048576 (1 MB). */
60
+ maxOutputBytes?: number;
61
+ /** Text written to the command's stdin, which is then closed. */
62
+ stdin?: string;
63
+ /** Abort the command. It resolves with a result rather than throwing. */
64
+ signal?: AbortSignal;
65
+ }
66
+ /** The outcome of a finished command. A non-zero exit, a timeout, or an abort is a result, not an error. */
67
+ export interface RunResult {
68
+ /** `true` when the command exited with code 0. */
69
+ ok: boolean;
70
+ /** Exit code, or `null` when the command was killed (timeout or abort). */
71
+ exitCode: number | null;
72
+ /** Standard output, with secrets redacted. */
73
+ stdout: string;
74
+ /** Standard error, with secrets redacted. */
75
+ stderr: string;
76
+ /** stdout and stderr interleaved in arrival order. */
77
+ output: string;
78
+ /** Wall-clock time of the command, in milliseconds. */
79
+ durationMs: number;
80
+ /** `true` when output exceeded `maxOutputBytes` and the oldest bytes were dropped. */
81
+ truncated: boolean;
82
+ /** `true` when `timeoutMs` ran out and the command was killed. */
83
+ timedOut: boolean;
84
+ /** Absolute working directory the command ran in. */
85
+ cwd: string;
86
+ /** The command as it was sent to the shell. */
87
+ command: string;
88
+ }
89
+ /**
90
+ * A lazy command. Nothing runs until you `await` it, call `then`, `catch` or `finally`
91
+ * (for the {@link RunResult}), or iterate it with `for await` (for live {@link OutputChunk}s).
92
+ * Chain `cwd`, `env`, or `timeout` before starting it.
93
+ */
94
+ export interface RunHandle extends Promise<RunResult>, AsyncIterable<OutputChunk> {
95
+ /** Run in this directory. */
96
+ cwd(path: string): RunHandle;
97
+ /** Add environment variables for this command. */
98
+ env(env: Record<string, string>): RunHandle;
99
+ /** Set the timeout in milliseconds. */
100
+ timeout(timeoutMs: number): RunHandle;
101
+ }
102
+ /** Options for `box.preview`. */
103
+ export interface PreviewOptions {
104
+ /** Path appended to the preview URL. */
105
+ path?: string;
106
+ /** Wait up to this many milliseconds for the URL to answer with a 2xx. Fails with `port_not_ready` when it runs out. */
107
+ waitMs?: number;
108
+ }
109
+ /** Counters from `box.usage()`. Providers may add their own numeric fields. */
110
+ export type Usage = {
111
+ /** When the sandbox was created, in epoch milliseconds. */
112
+ createdAt: number;
113
+ /** Milliseconds since `createdAt`. */
114
+ runningMs: number;
115
+ /** Commands run through this handle. */
116
+ commands: number;
117
+ /** Output bytes received through this handle. */
118
+ bytesOut: number;
119
+ } & Record<string, number>;
120
+ /** The methods every sandbox has, whatever the provider. `N` is the provider's native client type. */
121
+ export interface SandboxBase<N> {
122
+ /** The provider's sandbox ID. Pass it to `connectSandbox` to reattach. */
123
+ readonly id: string;
124
+ /** The key passed to `createSandbox`, when there was one. */
125
+ readonly key?: string;
126
+ /** Provider name, such as `"e2b"`. */
127
+ readonly provider: string;
128
+ /** `true` when this call created the sandbox, `false` when it reattached to an existing one. */
129
+ readonly created: boolean;
130
+ /** Labels on the sandbox. */
131
+ readonly labels: Record<string, string>;
132
+ /** What this provider supports. The optional methods on {@link Sandbox} follow it. */
133
+ readonly capabilities: ReadonlySet<Capability>;
134
+ /** The provider's own SDK object, fully typed, for anything this SDK does not cover. */
135
+ readonly native: N;
136
+ /** Run a shell command. Await the handle for the result, or iterate it to stream output. */
137
+ run(command: string, options?: RunOptions): RunHandle;
138
+ /** Run a command from a template literal. Every interpolated value is shell-quoted. */
139
+ $(strings: TemplateStringsArray, ...values: unknown[]): RunHandle;
140
+ /** Read, write, edit, search, and sync files. Relative paths resolve against `/workspace`. */
141
+ readonly files: Files;
142
+ /** Git helpers that run inside the sandbox. Tokens never reach argv, env, or shell history. */
143
+ readonly git: Git;
144
+ /** Start a named background process and optionally wait until it is ready. The name lets any client find it again with {@link process}; without one, the name is derived from the command and returned on the handle. */
145
+ start(command: string, options?: StartOptions): Promise<ProcessHandle>;
146
+ /** Get a handle to a background process by name, including one started by another client. */
147
+ process(name: string): ProcessHandle;
148
+ /** List the background processes started through the SDK. */
149
+ processes(): Promise<ProcessInfo[]>;
150
+ /** Get a URL for a port in the sandbox. Send the returned `headers` with every request. */
151
+ preview(port: number, options?: PreviewOptions): Promise<Preview>;
152
+ /** Counters for this handle, plus provider metrics when available. */
153
+ usage(): Promise<Usage>;
154
+ /** Detach this handle and leave the sandbox running. Reattach later with the key or ID. */
155
+ close(): Promise<void>;
156
+ /** Delete the sandbox. */
157
+ destroy(): Promise<void>;
158
+ /** For `await using`: calls `close()` when the sandbox has a key, otherwise `destroy()`. */
159
+ [Symbol.asyncDispose](): Promise<void>;
160
+ }
161
+ /** The methods each optional capability adds to a sandbox. */
162
+ export interface CapabilityMethods {
163
+ pause: {
164
+ /** Pause the sandbox. Billing and the hard lifetime depend on the provider. */
165
+ pause(): Promise<void>;
166
+ /** Resume a paused sandbox. */
167
+ resume(): Promise<void>;
168
+ };
169
+ snapshot: {
170
+ /** Save the sandbox state. Pass the returned `id` as `createSandbox(provider, { from: id })`. */
171
+ snapshot(options?: SnapshotOptions): Promise<{
172
+ id: string;
173
+ }>;
174
+ };
175
+ terminal: {
176
+ /** Open an interactive PTY. */
177
+ terminal(options: {
178
+ cols: number;
179
+ rows: number;
180
+ }): Promise<Terminal>;
181
+ };
182
+ }
183
+ type MethodCapability = keyof CapabilityMethods;
184
+ type UnionToIntersection<U> = (U extends unknown ? (value: U) => void : never) extends (value: infer I) => void ? I : never;
185
+ /** The methods added by the capabilities in `C`. */
186
+ export type MethodsFor<C extends Capability> = [Extract<C, MethodCapability>] extends [never] ? {} : UnionToIntersection<CapabilityMethods[Extract<C, MethodCapability>]>;
187
+ /**
188
+ * A sandbox handle. `N` is the native client type; `C` is the provider's capability union.
189
+ * With a concrete provider, `pause`/`resume`, `snapshot`, and `terminal` exist only when
190
+ * `C` includes them, so calling one on a provider that lacks it is a type error. With a
191
+ * provider typed as plain `Provider` (any capability), the methods are optional: check
192
+ * them with {@link hasCapability} first. `createSandbox(e2b())` infers the precise type.
193
+ */
194
+ export type Sandbox<N = unknown, C extends Capability = never> = SandboxBase<N> & (Capability extends C ? Partial<MethodsFor<MethodCapability>> : MethodsFor<C>);
195
+ /** The sandbox type a provider produces: `ProviderSandbox<ReturnType<typeof e2b>>`. */
196
+ export type ProviderSandbox<P extends Provider> = P extends Provider<infer N, infer C> ? Sandbox<N, C> : never;
197
+ export type { OutputChunk, Capability, SandboxInfo, FileInfo, Labels, Preview, Terminal };