@hatchet-dev/sandbox 0.1.1 → 0.1.3

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/CHANGELOG.md CHANGED
@@ -1,11 +1,35 @@
1
1
  # Changelog
2
2
 
3
- All notable changes to `@hatchet-dev/sandbox`, the TypeScript SDK. The provider has its own changelog at the repository root.
3
+ All notable changes to `@hatchet-dev/sandbox`, the TypeScript SDK.
4
4
 
5
5
  The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Each release reads its notes from the matching section here.
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.1.3] - 2026-11-09
10
+
11
+ ### Added
12
+
13
+ - `create({ resources })` asks the provider for a machine size, `{ vcpu, memory, disk }`. `memory` and `disk` take a number of MiB or a Kubernetes quantity such as `'512Mi'`, `'4Gi'` or `'8G'`, and travel as `memoryMib` and `diskMib` on the wire. A provider that cannot honour a field fails the create with its own message, so plan limits show up as the task error. A provider that does not know the option ignores it. On Hatchet Cloud, Archil sizes the sandbox on create and forks keep the source's size, so `resources` with `from` is rejected there. Daytona and Freestyle resize after create, which on Daytona needs resizing enabled for the organization and on Freestyle can only grow. E2B sizes on the template and rejects the option.
14
+
15
+ ## [0.1.2] - 2026-11-03
16
+
17
+ ### Added
18
+
19
+ - `create({ provider })` picks the sandbox provider by name when a tenant has more than one. It is sent as the `provider` metadata tag, so providers that already read that tag need no change.
20
+ - The SDK works against any sandbox provider. On first use it checks whether the tenant serves the `hatchet-sandbox` task and uses that; otherwise it keeps using `brickie-sandbox`. Existing deployments need no change. A tenant should serve one of the two: turning on `hatchet-sandbox` while durable tasks that already called `brickie-sandbox` are in flight makes those tasks fail on resume with a non-determinism error, so drain them first.
21
+ - `HATCHET_SANDBOX_OTEL=false` turns the OpenTelemetry instrumentor off. `BRICKIE_OTEL=false` still works.
22
+
23
+ ### Changed
24
+
25
+ - The package declares `sideEffects: true` so bundlers keep the import that adds `hatchet.sandbox` to the client.
26
+ - Run metadata tags are now `hatchet.sandbox.fn`, `hatchet.sandbox.id`, `hatchet.sandbox.image` and `hatchet.sandbox.from` (were `brickie.fn`, `brickie.sandbox`, `brickie.image`, `brickie.from`). Update any dashboard or run filter that keys on the old names.
27
+
28
+ ### Fixed
29
+
30
+ - `files.write` of a staged file replayed in a durable task after its signed upload URL expired now asks the provider for a new URL instead of failing with `staging_failed`. For both `write` and `read`, that renewal is a plain task run rather than a durable child, so it does not shift the replayed child sequence.
31
+ - `files.write` with several files over 2 MiB converts every input first and then takes staged keys in file order, so a durable replay assigns the same key to the same file.
32
+
9
33
  ## [0.1.1] - 2026-10-29
10
34
 
11
35
  ### Added
package/README.md CHANGED
@@ -7,9 +7,11 @@
7
7
 
8
8
  </div>
9
9
 
10
- Run agent sandboxes from [Hatchet](https://hatchet.run) tasks.
10
+ Run sandboxes from [Hatchet](https://hatchet.run) tasks, on the sandbox vendor of your choice.
11
11
 
12
- A sandbox is a workspace with a shell. You run commands in it and read and write its files. Each call is a Hatchet task. Each call that changes files takes a snapshot. You can start a new sandbox from any snapshot, and you can come back to a sandbox later by its ID. If you use it inside a durable task, a crash picks up where it left off.
12
+ A sandbox is a workspace with a shell. You run commands in it and read and write its files. Each call is a Hatchet task and corresponds to a snapshot. You can start a new sandbox from any snapshot, and you can come back to a sandbox later by its ID. If you use it inside a durable task, a crash picks up where it left off.
13
+
14
+ Your code only talks to Hatchet. The sandbox itself runs on a provider you connect to your tenant.
13
15
 
14
16
  ## Install
15
17
 
@@ -54,39 +56,56 @@ const again = await hatchet.sandbox.connect('conv-42');
54
56
  await again.exec('cat haiku.txt');
55
57
  ```
56
58
 
57
- Your app only talks to Hatchet. A brickie provider, connected to the same tenant, runs the sandboxes. Set `HATCHET_CLIENT_TOKEN` like you would for any Hatchet client. That is all the app needs.
59
+ Set `HATCHET_CLIENT_TOKEN` like you would for any Hatchet client.
60
+
61
+ ## Providers
62
+
63
+ A provider is a sandbox vendor connected to your Hatchet tenant, configured once in the dashboard under `Sandboxes` with the vendor's API key and optional configuration values.
64
+
65
+ We currently support the following vendors:
66
+
67
+ - [Daytona](https://www.daytona.io)
68
+ - [E2B](https://e2b.dev)
69
+ - [Archil](https://archil.com)
70
+ - [Freestyle](https://freestyle.sh).
71
+
72
+ ```ts
73
+ const sandbox = await hatchet.sandbox.create({ provider: 'e2b' });
74
+ ```
58
75
 
59
76
  ## API
60
77
 
61
78
  ### `hatchet.sandbox`
62
79
 
63
- | Call | Returns | What it does |
64
- |---|---|---|
65
- | `create(opts?)` | `Sandbox` | Starts a sandbox. |
66
- | `connect(id, { template? })` | `Sandbox` | Picks up a sandbox from its latest snapshot. Starts it again if it was stopped. Throws if the ID does not exist. |
67
- | `list({ sandboxId?, metadata? })` | `SandboxInfo[]` | Finds sandboxes by ID or by metadata. All given pairs must match. |
68
- | `delete({ sandboxId?, metadata? })` | `string[]` | Deletes every matching sandbox with all of its snapshots and files, and returns their IDs. One filter is required. |
80
+ | Call | Returns | What it does |
81
+ | ----------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------ |
82
+ | `create(opts?)` | `Sandbox` | Starts a sandbox. |
83
+ | `connect(id, { template? })` | `Sandbox` | Picks up a sandbox from its latest snapshot. Starts it again if it was stopped. Throws if the ID does not exist. |
84
+ | `list({ sandboxId?, metadata? })` | `SandboxInfo[]` | Finds sandboxes by ID or by metadata. All given pairs must match. |
85
+ | `delete({ sandboxId?, metadata? })` | `string[]` | Deletes every matching sandbox with all of its snapshots and files, and returns their IDs. One filter is required. |
69
86
 
70
87
  Options for `create`:
71
88
 
72
- | Option | What it does |
73
- |---|---|
74
- | `id` | Pick your own sandbox ID. Lowercase letters, digits, and hyphens. It must not exist yet. |
75
- | `template` | The container image. Defaults to the provider's image. |
76
- | `from` | Start from this snapshot. Create two sandboxes from the same snapshot and you have a fork. |
77
- | `metadata` | Tags you can search for with `list`. |
78
- | `inheritParentMetadata` | With `from`, copy the tags of the sandbox that made the snapshot onto the new one. Tags given in `metadata` take precedence. |
79
- | `idleTimeoutMs` | Remove the sandbox after this long with no calls. The provider sets the maximum. |
89
+ | Option | What it does |
90
+ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
91
+ | `provider` | Which sandbox provider to create on, by its name. Needed when the tenant has several; a fork always uses its snapshot's. |
92
+ | `id` | Pick your own sandbox ID. Lowercase letters, digits, and hyphens. It must not exist yet. |
93
+ | `template` | The image or template, in the provider's own terms. Defaults to the provider's default. |
94
+ | `from` | Start from this snapshot. Create two sandboxes from the same snapshot and you have a fork. |
95
+ | `metadata` | Tags you can search for with `list`. |
96
+ | `inheritParentMetadata` | With `from`, copy the tags of the sandbox that made the snapshot onto the new one. Tags given in `metadata` take precedence. |
97
+ | `idleTimeoutMs` | Stop the sandbox after this long with no calls. The provider sets the maximum. |
98
+ | `resources` | Machine size as `{ vcpu, memory, disk }`. `memory` and `disk` take MiB or a quantity like `'4Gi'`. Providers that cannot honour a field fail the create with their own message. |
80
99
 
81
100
  ### `Sandbox`
82
101
 
83
- | Call | Returns | What it does |
84
- |---|---|---|
102
+ | Call | Returns | What it does |
103
+ | --------------------------- | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
85
104
  | `exec(cmd, { timeoutMs? })` | `{ stdout, stderr, exitCode, snapshotId?, timings? }` | Runs `sh -c cmd` in the workspace and takes a snapshot. A non-zero exit code is a normal result, not an error. On timeout the exit code is 124. |
86
- | `kill()` | `void` | Stops the sandbox. The snapshots stay, so `connect` still works. |
87
- | `delete()` | `void` | Stops the sandbox and deletes every snapshot and file stored for it. `connect` fails afterwards. |
88
- | `sandboxId` | `string` | The ID to use with `connect` later. |
89
- | `files` | `Files` | The file API below. |
105
+ | `kill()` | `void` | Stops the sandbox. The snapshots stay, so `connect` still works. |
106
+ | `delete()` | `void` | Stops the sandbox and deletes every snapshot and file stored for it. `connect` fails afterwards. |
107
+ | `sandboxId` | `string` | The ID to use with `connect` later. |
108
+ | `files` | `Files` | The file API below. |
90
109
 
91
110
  Each result also has `timings` in milliseconds for `claim`, `restore`, `exec`, and `checkpoint`, and the `snapshotId` the call made.
92
111
 
@@ -94,19 +113,17 @@ Each result also has `timings` in milliseconds for `claim`, `restore`, `exec`, a
94
113
 
95
114
  Paths are relative to the workspace. A path that points outside it throws a `FilesystemError` with code `invalid_path`.
96
115
 
97
- | Call | What it does |
98
- |---|---|
99
- | `read(path, { format? })` | Reads a file. `format` is `'text'` (default), `'bytes'` for a `Uint8Array`, or `'blob'`. |
100
- | `write(path, data)` or `write([{ path, data }, ...])` | Writes one file or many. `data` can be a string, `ArrayBuffer`, `Uint8Array`, or `Blob`. |
101
- | `list(path?, { depth? })` | Lists entries with name, path, type, size, mode, permissions, and modified time. |
102
- | `exists(path)`, `getInfo(path)` | Checks a path or gets its info. |
103
- | `makeDir(path)`, `rename(from, to)`, `copy(from, to)`, `remove(path)` | The usual file operations. |
104
- | `download(url, path, { timeoutMs? })` | The provider fetches an https URL into the workspace. Private and loopback addresses are refused. |
105
- | `upload(path, url, { timeoutMs? })` | The provider sends a file to an https URL with HTTP PUT. Presigned URLs work well here. |
106
-
107
- The sandbox itself does not need network access for any of this.
116
+ | Call | What it does |
117
+ | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
118
+ | `read(path, { format? })` | Reads a file. `format` is `'text'` (default), `'bytes'` for a `Uint8Array`, or `'blob'`. |
119
+ | `write(path, data)` or `write([{ path, data }, ...])` | Writes one file or many. `data` can be a string, `ArrayBuffer`, `Uint8Array`, or `Blob`. |
120
+ | `list(path?, { depth? })` | Lists entries with name, path, type, size, mode, permissions, and modified time. |
121
+ | `exists(path)`, `getInfo(path)` | Checks a path or gets its info. |
122
+ | `makeDir(path)`, `rename(from, to)`, `copy(from, to)`, `remove(path)` | The usual file operations. |
123
+ | `download(url, path, { timeoutMs? })` | The provider fetches an https URL into the workspace. Private and loopback addresses are refused. |
124
+ | `upload(path, url, { timeoutMs? })` | The provider sends a file to an https URL with HTTP PUT. Presigned URLs work well here. |
108
125
 
109
- `read` and `write` carry up to 2 MiB through Hatchet. Bigger files go through the provider's object store (`--object-store` on the provider: S3, GCS, Azure Blob, or a local folder) and never pass through Hatchet. You call the same methods either way.
126
+ `read` and `write` carry up to 2 MiB through Hatchet. Providers with an object store stage bigger files there and never pass them through Hatchet; you call the same methods either way.
110
127
 
111
128
  ## Errors
112
129
 
@@ -117,17 +134,17 @@ The sandbox itself does not need network access for any of this.
117
134
 
118
135
  ## Telemetry
119
136
 
120
- On first use the SDK turns on the Hatchet OpenTelemetry instrumentor. If you have OpenTelemetry set up, sandbox calls show up as spans in your task's trace. Set `BRICKIE_OTEL=false` to turn this off.
137
+ On first use the SDK turns on the Hatchet OpenTelemetry instrumentor. If you have OpenTelemetry set up, sandbox calls show up as spans in your task's trace. Set `HATCHET_SANDBOX_OTEL=false` to turn this off.
121
138
 
122
139
  ## What you need
123
140
 
124
- - A Hatchet tenant. Hatchet Cloud, or a self-hosted Hatchet v0.110.0 or newer with gRPC operators turned on.
125
- - A brickie provider connected to that tenant. It is one binary, `brickie worker`. Get it from [github.com/hatchet-dev/brickie](https://github.com/hatchet-dev/brickie).
141
+ - A Hatchet Cloud tenant with sandboxes enabled.
142
+ - At least one sandbox provider connected to that tenant, configured under Sandboxes in the dashboard with your Daytona, E2B, Archil, or Freestyle API key.
126
143
 
127
144
  ## Changelog
128
145
 
129
- See [CHANGELOG.md](https://github.com/hatchet-dev/brickie/blob/main/sdks/typescript/CHANGELOG.md).
146
+ See [CHANGELOG.md](./CHANGELOG.md).
130
147
 
131
148
  ## License
132
149
 
133
- MIT. See [LICENSE](https://github.com/hatchet-dev/brickie/blob/main/LICENSE).
150
+ MIT. See [LICENSE](./LICENSE).
package/dist/index.cjs ADDED
@@ -0,0 +1,405 @@
1
+ 'use strict';
2
+
3
+ var v1 = require('@hatchet-dev/typescript-sdk/v1');
4
+ var fs = require('fs/promises');
5
+
6
+ function _interopNamespace(e) {
7
+ if (e && e.__esModule) return e;
8
+ var n = Object.create(null);
9
+ if (e) {
10
+ Object.keys(e).forEach(function (k) {
11
+ if (k !== 'default') {
12
+ var d = Object.getOwnPropertyDescriptor(e, k);
13
+ Object.defineProperty(n, k, d.get ? d : {
14
+ enumerable: true,
15
+ get: function () { return e[k]; }
16
+ });
17
+ }
18
+ });
19
+ }
20
+ n.default = e;
21
+ return Object.freeze(n);
22
+ }
23
+
24
+ var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
25
+
26
+ // src/sandbox.ts
27
+ var FilesystemError = class extends Error {
28
+ constructor(code, message) {
29
+ super(message);
30
+ this.code = code;
31
+ this.name = "FilesystemError";
32
+ }
33
+ code;
34
+ };
35
+ var toEntry = (e) => ({
36
+ ...e,
37
+ modifiedTime: e.modifiedTime ? new Date(e.modifiedTime) : void 0
38
+ });
39
+ var STAGE_OVER_BYTES = 2 << 20;
40
+ async function toBytes(data) {
41
+ if (typeof data === "string") return Buffer.from(data, "utf8");
42
+ if (data instanceof Blob) return Buffer.from(await data.arrayBuffer());
43
+ if (data instanceof Uint8Array) return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
44
+ return Buffer.from(data);
45
+ }
46
+ async function putStaged(url, bytes) {
47
+ if (url.startsWith("file://")) {
48
+ await fs__namespace.writeFile(decodeURIComponent(url.slice("file://".length)), bytes);
49
+ return;
50
+ }
51
+ const res = await fetch(url, {
52
+ method: "PUT",
53
+ body: new Uint8Array(bytes),
54
+ headers: { "Content-Type": "application/octet-stream" }
55
+ });
56
+ if (!res.ok)
57
+ throw new FilesystemError("staging_failed", `stage upload failed: HTTP ${res.status}`);
58
+ }
59
+ async function getStaged(url) {
60
+ if (url.startsWith("file://")) {
61
+ return fs__namespace.readFile(decodeURIComponent(url.slice("file://".length)));
62
+ }
63
+ const res = await fetch(url);
64
+ if (!res.ok)
65
+ throw new FilesystemError("staging_failed", `stage download failed: HTTP ${res.status}`);
66
+ return Buffer.from(await res.arrayBuffer());
67
+ }
68
+ var Files = class {
69
+ /** @internal */
70
+ constructor(turn) {
71
+ this.turn = turn;
72
+ }
73
+ turn;
74
+ async call(fn, input, fresh = false) {
75
+ const out = await this.turn(`$fs.${fn}`, input, fresh);
76
+ if (out.error) throw new FilesystemError(out.error.code, out.error.message);
77
+ return out;
78
+ }
79
+ async read(path, opts = {}) {
80
+ const out = await this.call("read", { path });
81
+ const bytes = out.url ? await this.readStaged(out.url, out.stagedKey) : Buffer.from(out.content ?? "", "base64");
82
+ if (opts.format === "bytes") return new Uint8Array(bytes);
83
+ if (opts.format === "blob") return new Blob([new Uint8Array(bytes)]);
84
+ return bytes.toString("utf8");
85
+ }
86
+ /** A replayed durable read may hold a URL that has expired; the provider signs the same staged file again. The renewal is a plain run, not a durable child, so the replayed child sequence stays aligned. */
87
+ async readStaged(url, stagedKey) {
88
+ try {
89
+ return await getStaged(url);
90
+ } catch (e) {
91
+ if (url.startsWith("file://") || !(e instanceof FilesystemError)) throw e;
92
+ const { getUrl } = await this.call("presign", { stagedKey }, true);
93
+ return getStaged(getUrl);
94
+ }
95
+ }
96
+ async write(pathOrFiles, data) {
97
+ if (typeof pathOrFiles !== "string") return this.writeFiles(pathOrFiles);
98
+ const [entry] = await this.writeFiles([{ path: pathOrFiles, data: data ?? "" }]);
99
+ return entry;
100
+ }
101
+ /** Writes several files in one task. */
102
+ async writeFiles(files) {
103
+ const bytes = await Promise.all(files.map((f) => toBytes(f.data)));
104
+ const encoded = [];
105
+ for (const [i, f] of files.entries()) {
106
+ const b = bytes[i];
107
+ if (b.length <= STAGE_OVER_BYTES) {
108
+ encoded.push({ path: f.path, content: b.toString("base64") });
109
+ continue;
110
+ }
111
+ const { stagedKey, putUrl } = await this.call("presign", {});
112
+ try {
113
+ await putStaged(putUrl, b);
114
+ encoded.push({ path: f.path, stagedKey });
115
+ } catch {
116
+ const again = await this.call("presign", {}, true);
117
+ await putStaged(again.putUrl, b);
118
+ encoded.push({ path: f.path, stagedKey: again.stagedKey });
119
+ }
120
+ }
121
+ const { entries = [] } = await this.call("write", { files: encoded });
122
+ return entries.map(toEntry);
123
+ }
124
+ /** Lists a directory. `depth` 1 (default) is the directory itself; higher values recurse. No snapshot is made. */
125
+ async list(path = ".", opts = {}) {
126
+ const { entries = [] } = await this.call("list", { path, depth: opts.depth ?? 1 });
127
+ return entries.map(toEntry);
128
+ }
129
+ /** True if the path exists. No snapshot is made. */
130
+ async exists(path) {
131
+ const { entry } = await this.call("stat", { path });
132
+ return entry != null;
133
+ }
134
+ /** Metadata of a file or directory. Throws `FilesystemError` with code `not_found` if absent. */
135
+ async getInfo(path) {
136
+ const { entry } = await this.call("stat", { path });
137
+ if (!entry) throw new FilesystemError("not_found", `${path} does not exist`);
138
+ return toEntry(entry);
139
+ }
140
+ /** Creates a directory and its parents. Returns false if it already existed. */
141
+ async makeDir(path) {
142
+ const { created } = await this.call("mkdir", { path });
143
+ return created === true;
144
+ }
145
+ /** Renames or moves a file or directory. */
146
+ async rename(oldPath, newPath) {
147
+ const { entry } = await this.call("rename", { path: oldPath, newPath });
148
+ return toEntry(entry);
149
+ }
150
+ /** Copies a file or directory tree. */
151
+ async copy(srcPath, dstPath) {
152
+ const { entry } = await this.call("copy", { path: srcPath, newPath: dstPath });
153
+ return toEntry(entry);
154
+ }
155
+ /** Deletes a file or directory tree. */
156
+ async remove(path) {
157
+ await this.call("remove", { path });
158
+ }
159
+ /** The provider fetches an https URL into the workspace. The sandbox needs no network. Private and loopback addresses are refused. */
160
+ async download(url, path, opts = {}) {
161
+ const { entry } = await this.call("download", {
162
+ url,
163
+ path,
164
+ ...opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}
165
+ });
166
+ return toEntry(entry);
167
+ }
168
+ /** The provider sends a workspace file to an https URL with HTTP PUT, for example a presigned URL. */
169
+ async upload(path, url, opts = {}) {
170
+ await this.call("upload", {
171
+ path,
172
+ url,
173
+ ...opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}
174
+ });
175
+ }
176
+ };
177
+
178
+ // src/otel.ts
179
+ var telemetryStarted = false;
180
+ async function setupTelemetry() {
181
+ if (telemetryStarted || process.env.HATCHET_SANDBOX_OTEL === "false" || process.env.BRICKIE_OTEL === "false") {
182
+ return;
183
+ }
184
+ telemetryStarted = true;
185
+ try {
186
+ const [{ registerInstrumentations }, { HatchetInstrumentor }] = await Promise.all([
187
+ import('@opentelemetry/instrumentation'),
188
+ import('@hatchet-dev/typescript-sdk/opentelemetry/index.js')
189
+ ]);
190
+ registerInstrumentations({ instrumentations: [new HatchetInstrumentor()] });
191
+ } catch (err) {
192
+ console.error(`sandbox: opentelemetry disabled: ${err.message}`);
193
+ }
194
+ }
195
+
196
+ // src/sandbox.ts
197
+ var TASK_NAMES = ["hatchet-sandbox", "brickie-sandbox"];
198
+ var taskNames = /* @__PURE__ */ new WeakMap();
199
+ async function registered(client, name) {
200
+ const namespace = client.config.namespace ?? "";
201
+ const full = name.startsWith(namespace) ? name : `${namespace}${name}`;
202
+ for (let offset = 0; ; ) {
203
+ const { rows = [] } = await client.workflows.list({ name: full, limit: 100, offset });
204
+ if (rows.some((w) => w.name === full)) return true;
205
+ if (rows.length === 0) return false;
206
+ offset += rows.length;
207
+ }
208
+ }
209
+ async function probe(client) {
210
+ for (const name of TASK_NAMES) {
211
+ if (await registered(client, name)) return name;
212
+ }
213
+ return void 0;
214
+ }
215
+ function resolveTaskName(client) {
216
+ let pending = taskNames.get(client);
217
+ if (!pending) {
218
+ pending = probe(client).then(
219
+ (name) => {
220
+ if (!name) taskNames.delete(client);
221
+ return name ?? TASK_NAMES[TASK_NAMES.length - 1];
222
+ },
223
+ (err) => {
224
+ taskNames.delete(client);
225
+ throw err;
226
+ }
227
+ );
228
+ taskNames.set(client, pending);
229
+ }
230
+ return pending;
231
+ }
232
+ var UNITS = {
233
+ K: 1e3,
234
+ M: 1e6,
235
+ G: 1e9,
236
+ T: 1e12,
237
+ Ki: 2 ** 10,
238
+ Mi: 2 ** 20,
239
+ Gi: 2 ** 30,
240
+ Ti: 2 ** 40
241
+ };
242
+ function toMib(value, field) {
243
+ if (typeof value === "number") {
244
+ if (!Number.isInteger(value) || value <= 0)
245
+ throw new Error(`resources.${field}: expected a positive whole number of MiB`);
246
+ return value;
247
+ }
248
+ const m = /^(\d+(?:\.\d+)?)\s*([KMGT]i?)?B?$/.exec(value.trim());
249
+ if (!m)
250
+ throw new Error(
251
+ `resources.${field}: expected a quantity like '512Mi', '4Gi' or '8G', got ${JSON.stringify(value)}`
252
+ );
253
+ const bytes = Number(m[1]) * (m[2] ? UNITS[m[2]] : UNITS.Mi);
254
+ const mib = Math.ceil(bytes / UNITS.Mi);
255
+ if (mib <= 0) throw new Error(`resources.${field}: must be at least 1Mi`);
256
+ return mib;
257
+ }
258
+ function wireResources(r) {
259
+ const out = {};
260
+ if (r.vcpu !== void 0) {
261
+ if (!Number.isInteger(r.vcpu) || r.vcpu <= 0)
262
+ throw new Error("resources.vcpu: expected a positive whole number of cores");
263
+ out.vcpu = r.vcpu;
264
+ }
265
+ if (r.memory !== void 0) out.memoryMib = toMib(r.memory, "memory");
266
+ if (r.disk !== void 0) out.diskMib = toMib(r.disk, "disk");
267
+ if (Object.keys(out).length === 0)
268
+ throw new Error("resources: set at least one of vcpu, memory, disk");
269
+ return out;
270
+ }
271
+ function turnRunner(client) {
272
+ const resolved = resolveTaskName(client);
273
+ return async (input, opts) => {
274
+ const name = await resolved;
275
+ const additionalMetadata = {
276
+ "hatchet.sandbox.fn": input.fn,
277
+ ...input.sandboxId ? { "hatchet.sandbox.id": input.sandboxId } : {},
278
+ ...input.image ? { "hatchet.sandbox.image": input.image } : {},
279
+ ...input.snapshotId ? { "hatchet.sandbox.from": input.snapshotId } : {}
280
+ };
281
+ const result = opts?.fresh ? await (await client.admin.runWorkflow(name, input, {
282
+ additionalMetadata
283
+ })).result() : await client.workflow({ name }).run(input, { additionalMetadata });
284
+ return result[name] ?? result;
285
+ };
286
+ }
287
+ var Sandbox = class _Sandbox {
288
+ constructor(run, sandboxId, template) {
289
+ this.run = run;
290
+ this.sandboxId = sandboxId;
291
+ this.template = template;
292
+ this.files = new Files((fn, input, fresh) => this.turn(fn, input, fresh));
293
+ }
294
+ run;
295
+ sandboxId;
296
+ template;
297
+ /** File operations on the workspace. */
298
+ files;
299
+ /** Starts a new sandbox. Prefer `hatchet.sandbox.create`. */
300
+ static async create(client, opts = {}) {
301
+ await setupTelemetry();
302
+ const run = turnRunner(client);
303
+ const metadata = opts.provider ? { ...opts.metadata, provider: opts.provider } : opts.metadata;
304
+ const created = await run({
305
+ fn: "$create",
306
+ input: {},
307
+ ...opts.id ? { sandboxId: opts.id } : {},
308
+ ...opts.template ? { image: opts.template } : {},
309
+ ...opts.from ? { snapshotId: opts.from } : {},
310
+ ...metadata ? { metadata } : {},
311
+ ...opts.idleTimeoutMs ? { idleTtlMs: opts.idleTimeoutMs } : {},
312
+ ...opts.inheritParentMetadata ? { inheritMetadata: true } : {},
313
+ ...opts.resources ? { resources: wireResources(opts.resources) } : {}
314
+ });
315
+ return new _Sandbox(run, created.sandboxId, opts.template);
316
+ }
317
+ /** Attaches to a sandbox by ID. Prefer `hatchet.sandbox.connect`. */
318
+ static async connect(client, sandboxId, opts = {}) {
319
+ await setupTelemetry();
320
+ const run = turnRunner(client);
321
+ await run({
322
+ fn: "$connect",
323
+ input: {},
324
+ sandboxId,
325
+ ...opts.template ? { image: opts.template } : {}
326
+ });
327
+ return new _Sandbox(run, sandboxId, opts.template);
328
+ }
329
+ /** Lists sandboxes on the provider. Prefer `hatchet.sandbox.list`. */
330
+ static async list(client, opts = {}) {
331
+ const result = await turnRunner(client)({
332
+ fn: "$list",
333
+ input: {
334
+ ...opts.sandboxId ? { sandboxId: opts.sandboxId } : {},
335
+ ...opts.metadata ? { metadata: opts.metadata } : {}
336
+ }
337
+ });
338
+ const raw = result.output.sandboxes ?? [];
339
+ return raw.map((s) => ({
340
+ ...s,
341
+ createdAt: new Date(s.createdAt),
342
+ lastUsed: s.lastUsed ? new Date(s.lastUsed) : void 0
343
+ }));
344
+ }
345
+ /** Deletes every sandbox matching the filter, with all their snapshots and files. Prefer `hatchet.sandbox.delete`. */
346
+ static async delete(client, opts) {
347
+ if (!opts.sandboxId && Object.keys(opts.metadata ?? {}).length === 0)
348
+ throw new Error("delete needs a sandboxId or a metadata filter");
349
+ const run = turnRunner(client);
350
+ const ids = [];
351
+ for (const { sandboxId } of await _Sandbox.list(client, opts)) {
352
+ await run({ fn: "$delete", input: {}, sandboxId });
353
+ ids.push(sandboxId);
354
+ }
355
+ return ids;
356
+ }
357
+ /** Runs a shell command with `sh -c` in the workspace and makes a snapshot. A timeout gives `exitCode` 124, not an error. */
358
+ async exec(cmd, opts = {}) {
359
+ return this.turn("$command", {
360
+ cmd,
361
+ ...opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}
362
+ });
363
+ }
364
+ /** Removes the sandbox. Its snapshots stay; `connect` can bring it back. */
365
+ async kill() {
366
+ await this.turn("$destroy", {});
367
+ }
368
+ /** Removes the sandbox and deletes every snapshot and file the provider stored for it. `connect` fails afterwards. */
369
+ async delete() {
370
+ await this.turn("$delete", {});
371
+ }
372
+ async turn(fn, input, fresh = false) {
373
+ const result = await this.run(
374
+ {
375
+ sandboxId: this.sandboxId,
376
+ ...this.template ? { image: this.template } : {},
377
+ fn,
378
+ input
379
+ },
380
+ { fresh }
381
+ );
382
+ return {
383
+ ...result.output,
384
+ snapshotId: result.snapshotId,
385
+ timings: result.timings
386
+ };
387
+ }
388
+ };
389
+ Object.defineProperty(v1.HatchetClient.prototype, "sandbox", {
390
+ configurable: true,
391
+ get() {
392
+ return {
393
+ create: (opts) => Sandbox.create(this, opts),
394
+ connect: (sandboxId, opts) => Sandbox.connect(this, sandboxId, opts),
395
+ list: (opts) => Sandbox.list(this, opts),
396
+ delete: (opts) => Sandbox.delete(this, opts)
397
+ };
398
+ }
399
+ });
400
+
401
+ exports.Files = Files;
402
+ exports.FilesystemError = FilesystemError;
403
+ exports.Sandbox = Sandbox;
404
+ //# sourceMappingURL=index.cjs.map
405
+ //# sourceMappingURL=index.cjs.map