@opencoredev/sandbox-sdk 1.0.0-beta.0 → 1.0.1
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 +48 -0
- package/README.md +70 -63
- package/dist/ai.js +1 -1
- package/dist/chunk-23tjmd39.js +8 -0
- package/dist/chunk-2ts3evzh.js +2 -0
- package/dist/chunk-83avbjns.js +2 -0
- package/dist/chunk-8786zrns.js +2 -0
- package/dist/chunk-8wq767xb.js +17 -0
- package/dist/chunk-9w9rddra.js +2 -0
- package/dist/chunk-bd481sb7.js +2 -0
- package/dist/chunk-ch71kvcp.js +2 -0
- package/dist/chunk-ckym4cht.js +23 -0
- package/dist/chunk-hgrwyjrb.js +2 -0
- package/dist/chunk-hzbssbep.js +31 -0
- package/dist/chunk-k60b4r27.js +2 -0
- package/dist/chunk-kk1hw8wa.js +1 -0
- package/dist/chunk-nw845a93.js +27 -0
- package/dist/chunk-q5vqajhg.js +2 -0
- package/dist/chunk-x2skgx3m.js +5 -0
- package/dist/chunk-x681p5d2.js +68 -0
- package/dist/chunk-xgxfy2n8.js +4 -0
- package/dist/core/process-records.d.ts +25 -0
- package/dist/errors.d.ts +67 -1
- package/dist/files.d.ts +11 -4
- package/dist/git.d.ts +1 -1
- package/dist/http.d.ts +225 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -1
- package/dist/keys.d.ts +5 -0
- package/dist/mastra.d.ts +1 -1
- package/dist/mastra.js +1 -1
- package/dist/memory.d.ts +4 -1
- package/dist/memory.js +11 -9
- package/dist/native.d.ts +127 -0
- package/dist/openai.js +1 -1
- package/dist/peer.d.ts +9 -0
- package/dist/provider.d.ts +38 -5
- package/dist/provider.js +1 -0
- package/dist/providers/agentos/errors.d.ts +3 -2
- package/dist/providers/agentos/index.d.ts +2 -9
- package/dist/providers/agentos/index.js +2 -2
- package/dist/providers/agentos/provider.d.ts +50 -0
- package/dist/providers/boat/index.d.ts +52 -9
- package/dist/providers/boat/index.js +1 -1
- package/dist/providers/boat-api/exec.d.ts +15 -2
- package/dist/providers/boat-api/follow.d.ts +24 -0
- package/dist/providers/boat-api/index.d.ts +45 -7
- package/dist/providers/boat-api/transport.d.ts +77 -0
- package/dist/providers/boxd/errors.d.ts +2 -2
- package/dist/providers/boxd/execute.d.ts +2 -2
- package/dist/providers/boxd/index.d.ts +2 -22
- package/dist/providers/boxd/index.js +24 -4
- package/dist/providers/boxd/provider.d.ts +74 -0
- package/dist/providers/boxd/transfers.d.ts +9 -0
- package/dist/providers/daytona/api.d.ts +124 -0
- package/dist/providers/daytona/buffered.d.ts +2 -2
- package/dist/providers/daytona/errors.d.ts +18 -2
- package/dist/providers/daytona/exec.d.ts +3 -3
- package/dist/providers/daytona/index.d.ts +53 -4
- package/dist/providers/daytona/index.js +18 -10
- package/dist/providers/daytona/multipart.d.ts +25 -0
- package/dist/providers/e2b/envd.d.ts +113 -0
- package/dist/providers/e2b/errors.d.ts +20 -3
- package/dist/providers/e2b/index.d.ts +41 -3
- package/dist/providers/e2b/index.js +1 -1
- package/dist/providers/freestyle/client.d.ts +87 -0
- package/dist/providers/freestyle/deadline.d.ts +3 -2
- package/dist/providers/freestyle/errors.d.ts +14 -1
- package/dist/providers/freestyle/execute.d.ts +3 -7
- package/dist/providers/freestyle/index.d.ts +28 -2
- package/dist/providers/freestyle/index.js +5 -33
- package/dist/providers/local/docker.d.ts +10 -6
- package/dist/providers/local/index.d.ts +29 -0
- package/dist/providers/local/index.js +2 -2
- package/dist/providers/railway/errors.d.ts +7 -1
- package/dist/providers/railway/index.d.ts +2 -23
- package/dist/providers/railway/index.js +1 -1
- package/dist/providers/railway/provider.d.ts +53 -0
- package/dist/providers/sandboxer/index.d.ts +15 -8
- package/dist/providers/sandboxer/index.js +1 -1
- package/dist/providers/superserve/errors.d.ts +2 -2
- package/dist/providers/superserve/execute.d.ts +3 -8
- package/dist/providers/superserve/index.d.ts +32 -3
- package/dist/providers/superserve/index.js +5 -37
- package/dist/providers/superserve/routes.d.ts +80 -0
- package/dist/providers/superserve/session.d.ts +33 -0
- package/dist/providers/tenki/deadline.d.ts +1 -1
- package/dist/providers/tenki/errors.d.ts +3 -3
- package/dist/providers/tenki/exec.d.ts +1 -1
- package/dist/providers/tenki/files.d.ts +1 -1
- package/dist/providers/tenki/index.d.ts +2 -27
- package/dist/providers/tenki/index.js +19 -16
- package/dist/providers/tenki/provider.d.ts +95 -0
- package/dist/providers/tenki/ready.d.ts +1 -1
- package/dist/providers/tenki/records.d.ts +16 -0
- package/dist/providers/tenki/stream.d.ts +2 -2
- package/dist/providers/upstash/buffered.d.ts +1 -1
- package/dist/providers/upstash/errors.d.ts +1 -1
- package/dist/providers/upstash/exec.d.ts +2 -2
- package/dist/providers/upstash/files.d.ts +1 -1
- package/dist/providers/upstash/index.d.ts +2 -34
- package/dist/providers/upstash/index.js +12 -18
- package/dist/providers/upstash/provider.d.ts +81 -0
- package/dist/providers/vercel/errors.d.ts +3 -1
- package/dist/providers/vercel/index.d.ts +13 -5
- package/dist/providers/vercel/index.js +1 -1
- package/dist/providers/vercel/provider.d.ts +50 -2
- package/dist/providers/vercel/transport.d.ts +7 -4
- package/dist/run.d.ts +6 -4
- package/dist/shared/deadline.d.ts +12 -0
- package/dist/shared/guest.d.ts +18 -0
- package/dist/shared/json.d.ts +11 -0
- package/dist/shared/metadata.d.ts +19 -0
- package/dist/shared/narrow.d.ts +8 -0
- package/dist/shared/native-error.d.ts +42 -0
- package/dist/shared/paged-exec.d.ts +22 -0
- package/dist/shared/shell.d.ts +2 -0
- package/dist/{providers/freestyle → shared}/wire.d.ts +1 -1
- package/dist/shell/process-records.d.ts +44 -0
- package/dist/streams.d.ts +72 -0
- package/dist/testing.d.ts +12 -2
- package/dist/testing.js +7 -4
- package/dist/tool-security.d.ts +4 -4
- package/dist/tools.d.ts +3 -2
- package/dist/tools.js +1 -1
- package/dist/types.d.ts +14 -6
- package/package.json +29 -46
- package/dist/chunk-59t3rqja.js +0 -2
- package/dist/chunk-cwx6cc31.js +0 -2
- package/dist/chunk-exv1kf89.js +0 -60
- package/dist/chunk-gc8zdxyb.js +0 -2
- package/dist/chunk-hjzhc3qg.js +0 -40
- package/dist/chunk-md6fmprc.js +0 -1
- package/dist/chunk-t5vr9nd8.js +0 -8
- package/dist/chunk-v6y7eqxw.js +0 -27
- package/dist/chunk-yed8mvs7.js +0 -2
- package/dist/chunk-yrsb6hws.js +0 -5
- package/dist/chunk-z9rjzn28.js +0 -2
- package/dist/providers/boxd/guest.d.ts +0 -14
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,53 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.0.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 1970429: Daytona snapshots that end in `error` or `build_failed` now reject instead of reporting success, and Daytona buffered reads honor `requestTimeoutMs` after headers arrive. `box.native.fetch()` applies `timeoutMs` to the wait for headers rather than the whole stream, an already-expired deadline no longer sends a request, and a failed kill during E2B startup cancellation now destroys the sandbox instead of reporting a clean timeout.
|
|
8
|
+
|
|
9
|
+
## 1.0.0
|
|
10
|
+
|
|
11
|
+
### Major Changes
|
|
12
|
+
|
|
13
|
+
- 8b7214a: Sandbox SDK 1.0: one TypeScript API for 14 sandbox providers (E2B, Daytona, Vercel Sandbox, Upstash Box, Railway, Boat, Sandboxer, Tenki, boxd, Freestyle, Superserve, local Docker, agentOS, and an in-memory fake), with typed capabilities, background processes, previews, files, git, and agent tools for the AI SDK, Mastra, and OpenAI Agents. 1.0 is a rewrite; see the upgrade guide at https://sandbox-sdk.app/docs/upgrade-from-0-2 when coming from 0.2.
|
|
14
|
+
|
|
15
|
+
Since 1.0.0-beta.1:
|
|
16
|
+
|
|
17
|
+
E2B, Daytona, Freestyle, Superserve, Boat, and Sandboxer now call their provider's HTTP API directly, so `npm i @opencoredev/sandbox-sdk` is the whole install for them. `e2b`, `@daytonaio/sdk`, `freestyle`, `@superserve/sdk`, and `@boatdev/sdk` are no longer peer dependencies. On these providers `box.native` is a `NativeApi` (`request`, `fetch`, `sdk`), and `box.native.sdk(() => import("<package>"))` still gives you the official SDK's object if you install it yourself. Vercel, Upstash Box, Railway, Tenki, boxd, and agentOS still need their SDK. The bullets below cover each provider's migration.
|
|
18
|
+
|
|
19
|
+
- **Breaking for Daytona:** `daytona()` calls Daytona's HTTP API directly, and `@daytonaio/sdk` is no longer a peer dependency, so `npm i @opencoredev/sandbox-sdk` is the whole install. File transfers use Web `FormData` and a built-in multipart reader, so bundled apps no longer need `form-data` or `busboy`, and the `codeRun` transfer fallback is gone. `box.native` is now a `NativeApi` with `"api"` and `"toolbox"` planes instead of the SDK's `Sandbox`: call `box.native.request(...)`, or `await box.native.sdk(() => import("@daytonaio/sdk"))` to keep using the SDK. `daytona().api` makes account-level calls. A create that fails after Daytona made the sandbox now always deletes it, including one whose create request got no answer.
|
|
20
|
+
- `superserve()` calls Superserve's HTTP API directly, so `@superserve/sdk` is no longer a peer: `npm i @opencoredev/sandbox-sdk` is the whole install. Breaking for beta users: `box.native` is now a `NativeApi` (`request`, `fetch`, `sdk`) instead of the SDK's `Sandbox`. Get the old object with `await box.native.sdk(() => import("@superserve/sdk"))`. A stdin-free run whose connection drops after the command started now rejects with `outcome_unknown` instead of `provider`.
|
|
21
|
+
|
|
22
|
+
- `e2b()` calls E2B's API and each sandbox's envd daemon over HTTP, so `e2b` is no longer a peer dependency: `npm i @opencoredev/sandbox-sdk` is the whole install. Options, defaults and behaviour are unchanged. Control-plane reads and the idempotent `connect`, `timeout` and `pause` calls retry on 429, 502, 503 and 504; a create whose response is lost is `outcome_unknown`. Every command start carries a tag, so a cancelled start, or one whose response was lost, is found and stopped. **Breaking for beta users:** `box.native` is now a `NativeApi` with the `"api"` and `"envd"` planes and the `{sandboxId}` placeholder, and `e2b().api` makes account calls. For the official SDK's `Sandbox`, install `e2b` and call `await box.native.sdk(() => import("e2b"))`.
|
|
23
|
+
- **Breaking for Freestyle:** `freestyle()` calls Freestyle's API directly, so `npm i @opencoredev/sandbox-sdk` is the whole install and the `freestyle` package is no longer a peer. `box.native` is now a `NativeApi` (`request`, `fetch`, `sdk`) instead of the SDK's `Vm`. Replace `box.native.exec(...)` with `(await box.native.sdk(() => import("freestyle"))).exec(...)` after installing `freestyle` yourself, or call the endpoint with `box.native.request("POST", "/v5/vms/{vmId}/exec-await", { body })`. `freestyle().api` makes account-level calls. Background requests (HTTP 202 polling), ranged reads and chunked uploads over 8 MiB work as they did with the SDK. A create aborted by its signal no longer cuts the request, so a VM Freestyle allocates anyway is deleted instead of left running.
|
|
24
|
+
- `boat()` and `sandboxer()` call their API over plain HTTP. `@boatdev/sdk` is no longer a peer: `npm i @opencoredev/sandbox-sdk` is the whole install. Breaking for beta users: `box.native` is now a native API (`request`, `fetch`, `sdk`) instead of `{ sandbox, client }`. Get the old pair with `await box.native.sdk(() => import("@boatdev/sdk"))` after installing `@boatdev/sdk` yourself, and the account client with `boat().api.sdk(...)`. Sandboxer keeps `box.native.region`, `regionSource` and `createSnapshot(name)`.
|
|
25
|
+
- On these six providers, credential headers you pass to `box.native` (`authorization`, `cookie`, `*-token`, `*-key`) are never sent to another origin or followed through a redirect, and an error that echoes one shows it redacted. A command whose output stream breaks after it started rejects with `outcome_unknown`, and a write is never sent twice after a credential refresh unless the server refused it first. A Boat or Sandboxer create stays within `requestTimeoutMs` across its retries.
|
|
26
|
+
|
|
27
|
+
## 1.0.0-beta.1
|
|
28
|
+
|
|
29
|
+
Fixes from early-adopter reports, provider options that were missing, and bundler support. Published under the `next` tag.
|
|
30
|
+
|
|
31
|
+
### Fixed
|
|
32
|
+
|
|
33
|
+
- Provider SDKs load inside bundles. CommonJS peers imported from an esbuild, webpack or Next.js bundle no longer fail with `X is not a constructor`, and error mapping no longer depends on class names that minifiers rename. boxd transfers and Daytona file operations work in bundles too. An ESM bundle without a `require` shim fails with an `unavailable` error that says how to fix it.
|
|
34
|
+
- Errors keep a redacted `cause`, and messages say what went wrong instead of "The provider reported provider". URLs, auth headers and credential-like values are scrubbed from every message and cause.
|
|
35
|
+
- `boat()` and `sandboxer()` no longer put stdin or file contents in command strings. Both travel through the file API into a private `0600` staging file.
|
|
36
|
+
- `connectSandbox()` no longer runs secret recovery on connect. It runs before the first command, so connecting to a stopped sandbox to destroy it works. Pass `recoverSecrets: false` to skip it.
|
|
37
|
+
- `start()` reports a command that exits at once, or a missing `cwd`, as `failed` instead of `running`. A missing `cwd` is a normal failed run (exit 2) on every provider.
|
|
38
|
+
- Railway command timeouts kill only the command instead of deleting the sandbox. Railway `list()` includes owned sandboxes that aren't running yet.
|
|
39
|
+
- Tenki reports `/workspace` as a directory on a fresh sandbox. boxd and Freestyle report missing files as `file_not_found`. e2b reports exit 143 after `stop()`.
|
|
40
|
+
- A local Docker sandbox restored from a snapshot no longer inherits the source's deadlines.
|
|
41
|
+
- A Daytona create that times out deletes the half-created sandbox (with `@daytonaio/sdk` 0.227 or later). The Daytona peer range now accepts any 0.x from 0.225.
|
|
42
|
+
- A thrown `SandboxError` prints as `SandboxError [code]: message`. `box.run()` returns a real `Promise` with `catch` and `finally`.
|
|
43
|
+
|
|
44
|
+
### Added
|
|
45
|
+
|
|
46
|
+
- `files.write(path, data, { mode })` and `files.write(record, { mode })` set POSIX permissions. Providers apply the mode natively where they can; the rest run `chmod` right after the write.
|
|
47
|
+
- `box.snapshot({ expiresInMs })`. Providers that can't expire snapshots reject a nonzero value with `unsupported`.
|
|
48
|
+
- `vercel()`: `persistent`, `timeoutMs` (per session), `image`, `runtime`, `source` (git or tarball), exact vCPU sizes, `networkPolicy`, `region`, `failoverRegions`, `networkId`, `mounts`, `snapshotExpiresInMs`, `keepLastSnapshots`, `deleteOrphanSnapshots` and `fetch`.
|
|
49
|
+
- Native options for the other providers, including e2b `public`, `autoPause`, `autoResume`, `volumes`; Daytona `public`, `autoArchiveMs`, `autoDeleteMs`, `volumes`, `createTimeoutMs`; Upstash `keepAlive`, `browser`, `attachHeaders`; Tenki `pauseRetentionMs`, `volumes`, `workspaceId`, `previewTtlMs`; Railway `resources`; Boat and Sandboxer `ttlSeconds`, `snapshots`, `monitoring`, `org`, and Sandboxer `idleTimeoutMs`; local `platform`, `user`, `runtime`, `networkMode`, `mounts`, `pidsLimit`, `shmSizeMb`, capabilities, `securityOpt` and custom sizes; Superserve network policies, `secretBindings`, `previewAccess`, `autoPauseMs`, `autoDeleteMs`; boxd allow lists, `volumes`, `timeoutMs`, `idleTimeoutMs`; Freestyle `autoDeleteMs` and snapshot expiry; agentOS `software`, `mounts`, `limits`. Each provider page lists them.
|
|
50
|
+
|
|
3
51
|
## 1.0.0-beta.0
|
|
4
52
|
|
|
5
53
|
First preview of the 1.0 rewrite, published under the `next` tag. The SDK was rewritten from scratch; most of the 0.2 surface changed. The API may still change before 1.0.0. The [upgrade guide](https://github.com/opencoredev/sandbox-sdk/blob/main/apps/docs/content/upgrade-from-0-2.mdx) maps every 0.2 call to its 1.0 form.
|
package/README.md
CHANGED
|
@@ -2,15 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
One TypeScript API for running code in a sandbox. The same `createSandbox`, `run`, `files`, `start`, and `preview` calls work on E2B, Daytona, Vercel, Upstash Box, Railway, Tenki, boxd, Freestyle, Superserve, Boat, Sandboxer, Docker on your machine, and an in-process fake for tests. Changing provider means changing one import.
|
|
4
4
|
|
|
5
|
-
> **
|
|
5
|
+
> **Coming from 0.2?** 1.0 changes the API. [Upgrade from 0.2](https://sandbox-sdk.app/docs/upgrade-from-0-2) walks through each change.
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
9
9
|
```sh
|
|
10
|
-
npm install @opencoredev/sandbox-sdk
|
|
10
|
+
npm install @opencoredev/sandbox-sdk
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
That is the whole install for E2B, Daytona, Freestyle, Superserve, Boat, and Sandboxer, which call the provider's HTTP API directly. Vercel, Upstash Box, Railway, Tenki, boxd, and agentOS also need the provider's package, for example `npm install @vercel/sandbox`. The [peer packages table](https://sandbox-sdk.app/docs/reference/capabilities#peer-packages) lists every one. Those packages are optional peers, so you only download the ones you need. The core has no runtime dependencies.
|
|
14
14
|
|
|
15
15
|
Requires Node.js 22+ or Bun 1.3+, ESM only. The examples use `await using`, which runs natively on Node.js 24 and Bun. On Node.js 22, compile with TypeScript (target ES2022 or lower) or call `box.destroy()` yourself.
|
|
16
16
|
|
|
@@ -35,7 +35,7 @@ For a real Linux sandbox, swap the provider. Nothing else changes:
|
|
|
35
35
|
import { createSandbox } from "@opencoredev/sandbox-sdk";
|
|
36
36
|
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
|
|
37
37
|
|
|
38
|
-
// Reads E2B_API_KEY from the environment.
|
|
38
|
+
// Reads E2B_API_KEY from the environment. No other package needed.
|
|
39
39
|
await using box = await createSandbox(e2b());
|
|
40
40
|
|
|
41
41
|
await box.files.write("hello.py", "print('hello from the sandbox')");
|
|
@@ -47,7 +47,7 @@ console.log(result.ok, result.stdout);
|
|
|
47
47
|
|
|
48
48
|
## Switch providers with one variable
|
|
49
49
|
|
|
50
|
-
Pick the provider from an environment variable and keep the sandbox code identical. Each adapter loads through a dynamic `import()`, so only the provider you pick needs its peer package installed. At runtime that holds as written. For the TypeScript compiler, the switch still reaches every listed adapter's declarations, and those reference their peer's types. Set `"skipLibCheck": true` in `tsconfig.json` (most templates already do), or install the peers you list as devDependencies, otherwise `tsc` reports TS2307 for the ones you left out.
|
|
50
|
+
Pick the provider from an environment variable and keep the sandbox code identical. Each adapter loads through a dynamic `import()`, so only the provider you pick needs its peer package installed, if it has one. At runtime that holds as written. For the TypeScript compiler, the switch still reaches every listed adapter's declarations, and those reference their peer's types. Set `"skipLibCheck": true` in `tsconfig.json` (most templates already do), or install the peers you list as devDependencies, otherwise `tsc` reports TS2307 for the ones you left out.
|
|
51
51
|
|
|
52
52
|
```ts
|
|
53
53
|
import { createSandbox, type Sandbox } from "@opencoredev/sandbox-sdk";
|
|
@@ -55,13 +55,20 @@ import type { Provider } from "@opencoredev/sandbox-sdk/provider";
|
|
|
55
55
|
|
|
56
56
|
async function loadProvider(name: string): Promise<Provider> {
|
|
57
57
|
switch (name) {
|
|
58
|
-
case "memory":
|
|
59
|
-
|
|
60
|
-
case "
|
|
61
|
-
|
|
62
|
-
case "
|
|
63
|
-
|
|
64
|
-
|
|
58
|
+
case "memory":
|
|
59
|
+
return (await import("@opencoredev/sandbox-sdk/memory")).memory();
|
|
60
|
+
case "local":
|
|
61
|
+
return (await import("@opencoredev/sandbox-sdk/local")).local();
|
|
62
|
+
case "e2b":
|
|
63
|
+
return (await import("@opencoredev/sandbox-sdk/e2b")).e2b();
|
|
64
|
+
case "daytona":
|
|
65
|
+
return (await import("@opencoredev/sandbox-sdk/daytona")).daytona();
|
|
66
|
+
case "vercel":
|
|
67
|
+
return (await import("@opencoredev/sandbox-sdk/vercel")).vercel();
|
|
68
|
+
case "upstash":
|
|
69
|
+
return (await import("@opencoredev/sandbox-sdk/upstash")).upstash();
|
|
70
|
+
default:
|
|
71
|
+
throw new Error(`Unknown SANDBOX_PROVIDER "${name}"`);
|
|
65
72
|
}
|
|
66
73
|
}
|
|
67
74
|
|
|
@@ -84,24 +91,24 @@ Two things differ between providers and are worth checking before you go multi-p
|
|
|
84
91
|
|
|
85
92
|
## Providers
|
|
86
93
|
|
|
87
|
-
Import each provider from its own subpath. The root entry never loads a provider SDK, and constructing a factory performs no I/O.
|
|
88
|
-
|
|
89
|
-
| Provider
|
|
90
|
-
|
|
|
91
|
-
| [E2B](https://sandbox-sdk.app/docs/providers/e2b)
|
|
92
|
-
| [Daytona](https://sandbox-sdk.app/docs/providers/daytona)
|
|
93
|
-
| [Vercel](https://sandbox-sdk.app/docs/providers/vercel)
|
|
94
|
-
| [Upstash Box](https://sandbox-sdk.app/docs/providers/upstash)
|
|
95
|
-
| [Railway](https://sandbox-sdk.app/docs/providers/railway)
|
|
96
|
-
| [Tenki](https://sandbox-sdk.app/docs/providers/tenki)
|
|
97
|
-
| boxd
|
|
98
|
-
| Freestyle
|
|
99
|
-
| Superserve
|
|
100
|
-
| Boat
|
|
101
|
-
| Sandboxer
|
|
102
|
-
| [Local (Docker)](https://sandbox-sdk.app/docs/providers/local) | `/local`
|
|
103
|
-
| [agentOS](https://sandbox-sdk.app/docs/providers/agentos)
|
|
104
|
-
| Memory
|
|
94
|
+
Import each provider from its own subpath. The root entry never loads a provider SDK, and constructing a factory performs no I/O. The [capability matrix](https://sandbox-sdk.app/docs/reference/capabilities) lists each provider's peer package, capabilities, limits, and preview behavior, and a script checks it against this package's source.
|
|
95
|
+
|
|
96
|
+
| Provider | Import from | Factory | Credentials (env) |
|
|
97
|
+
| -------------------------------------------------------------- | ------------- | ----------------------- | ------------------------------------------------------------------------------- |
|
|
98
|
+
| [E2B](https://sandbox-sdk.app/docs/providers/e2b) | `/e2b` | `e2b()` | `E2B_API_KEY` |
|
|
99
|
+
| [Daytona](https://sandbox-sdk.app/docs/providers/daytona) | `/daytona` | `daytona()` | `DAYTONA_API_KEY` (optional `DAYTONA_API_URL`, `DAYTONA_TARGET`) |
|
|
100
|
+
| [Vercel](https://sandbox-sdk.app/docs/providers/vercel) | `/vercel` | `vercel()` | `VERCEL_OIDC_TOKEN`, or `VERCEL_TOKEN` + `VERCEL_TEAM_ID` + `VERCEL_PROJECT_ID` |
|
|
101
|
+
| [Upstash Box](https://sandbox-sdk.app/docs/providers/upstash) | `/upstash` | `upstash()` | `UPSTASH_BOX_API_KEY` (optional `UPSTASH_BOX_BASE_URL`) |
|
|
102
|
+
| [Railway](https://sandbox-sdk.app/docs/providers/railway) | `/railway` | `railway()` | `RAILWAY_API_TOKEN`, `RAILWAY_ENVIRONMENT_ID` |
|
|
103
|
+
| [Tenki](https://sandbox-sdk.app/docs/providers/tenki) | `/tenki` | `tenki()` | `TENKI_AUTH_TOKEN` or `TENKI_API_KEY` |
|
|
104
|
+
| boxd | `/boxd` | `boxd()` | `BOXD_API_KEY` (optional `BOXD_BASE_URL`) |
|
|
105
|
+
| Freestyle | `/freestyle` | `freestyle()` | `FREESTYLE_API_KEY` |
|
|
106
|
+
| Superserve | `/superserve` | `superserve()` | `SUPERSERVE_API_KEY` |
|
|
107
|
+
| Boat | `/boat` | `boat()` | `BOAT_API_KEY` (optional `BOAT_API_BASE`) |
|
|
108
|
+
| Sandboxer | `/sandboxer` | `sandboxer({ region })` | `SANDBOXER_API_KEY` (optional `SANDBOXER_REGION`: `us-east`, `eu-central`) |
|
|
109
|
+
| [Local (Docker)](https://sandbox-sdk.app/docs/providers/local) | `/local` | `local()` | none; needs a running Docker Engine (`DOCKER_HOST` or `/var/run/docker.sock`) |
|
|
110
|
+
| [agentOS](https://sandbox-sdk.app/docs/providers/agentos) | `/agentos` | `agentos()` | none |
|
|
111
|
+
| Memory | `/memory` | `memory()` | none |
|
|
105
112
|
|
|
106
113
|
Capability meanings: `pause` adds `box.pause()` and `box.resume()`, `snapshot` adds `box.snapshot()` and `createSandbox(provider, { from })`, `size` allows the `size` option, and `network-policy` allows `network: "none"` or `{ allow: [...] }`. The SDK also defines `terminal` (`box.terminal()`, an interactive PTY), but no built-in provider supports it yet.
|
|
107
114
|
|
|
@@ -184,7 +191,7 @@ console.log((await pending).ok); // false; an aborted run also reports timedOut:
|
|
|
184
191
|
- Commands time out after 120 seconds unless you pass `timeoutMs` or chain `.timeout(ms)`. A timeout or an abort kills the command's process group and resolves with `ok: false`, `exitCode: null`, and `timedOut: true`. It does not throw.
|
|
185
192
|
- `createSandbox(provider, { signal })` rejects with `SandboxError` code `aborted`. A sandbox that arrives after the abort is destroyed for you.
|
|
186
193
|
- `start(..., { readyTimeoutMs })` bounds readiness (default 60 seconds), and `preview(port, { waitMs })` waits for a 2xx.
|
|
187
|
-
- `timeoutMs` and `idleTimeoutMs` on `createSandbox` set the sandbox's own lifetime, not a command timeout. A
|
|
194
|
+
- `timeoutMs` and `idleTimeoutMs` on `createSandbox` set the sandbox's own lifetime, not a command timeout. A provider that can't enforce one rejects it with `unsupported`. The `timeoutMs` and `idleTimeoutMs` rows of the [capability matrix](https://sandbox-sdk.app/docs/reference/capabilities) say which providers support each, and in what units.
|
|
188
195
|
|
|
189
196
|
### Files
|
|
190
197
|
|
|
@@ -235,7 +242,7 @@ const response = await fetch(preview.url, { headers: preview.headers });
|
|
|
235
242
|
console.log(preview.url, response.status); // http://127.0.0.1:<port>/ 200
|
|
236
243
|
```
|
|
237
244
|
|
|
238
|
-
Always send `preview.headers`.
|
|
245
|
+
Always send `preview.headers`. Several providers put the access token there and reject requests without it. Some providers only route ports you declared with `createSandbox(provider, { ports })`, so pass `ports` in provider-agnostic code; the other providers ignore it. The `ports` and Preview URL rows of the [capability matrix](https://sandbox-sdk.app/docs/reference/capabilities) say which. Servers must listen on `0.0.0.0`, not `localhost`.
|
|
239
246
|
|
|
240
247
|
### Pause, resume, and snapshots
|
|
241
248
|
|
|
@@ -300,22 +307,22 @@ try {
|
|
|
300
307
|
|
|
301
308
|
The SDK only throws `SandboxError`. A non-zero exit, a command timeout, or an aborted `run` is a result, not an error. `hint` is the next step on its own, `retryable` says whether the same call can succeed again, and `provider` and `sandboxId` say where it happened. Secrets are redacted from every field.
|
|
302
309
|
|
|
303
|
-
| `code`
|
|
304
|
-
|
|
|
305
|
-
| `auth`
|
|
306
|
-
| `not_found`
|
|
307
|
-
| `quota`
|
|
308
|
-
| `unavailable`
|
|
309
|
-
| `unsupported`
|
|
310
|
-
| `timeout`
|
|
311
|
-
| `aborted`
|
|
312
|
-
| `outcome_unknown`
|
|
313
|
-
| `process_exited`
|
|
314
|
-
| `port_not_ready`
|
|
315
|
-
| `edit_not_found`, `edit_not_unique` | `files.edit` matched zero times or more than once.
|
|
316
|
-
| `file_not_found`
|
|
317
|
-
| `invalid_argument`
|
|
318
|
-
| `provider`
|
|
310
|
+
| `code` | Meaning |
|
|
311
|
+
| ----------------------------------- | -------------------------------------------------------------------------------------------------------- |
|
|
312
|
+
| `auth` | Credentials are missing or rejected. |
|
|
313
|
+
| `not_found` | The sandbox no longer exists, or this handle was closed. |
|
|
314
|
+
| `quota` | A provider limit or billing stopped the request. Usually retryable. |
|
|
315
|
+
| `unavailable` | The provider is down or unreachable. Usually retryable. |
|
|
316
|
+
| `unsupported` | The provider cannot do what was asked: `size`, `network`, a lifetime option, an undeclared preview port. |
|
|
317
|
+
| `timeout` | A provider operation or a readiness check took too long. |
|
|
318
|
+
| `aborted` | Your `AbortSignal` fired during `createSandbox`. |
|
|
319
|
+
| `outcome_unknown` | The request may or may not have happened. Check state before retrying. |
|
|
320
|
+
| `process_exited` | A background process exited before it was ready. |
|
|
321
|
+
| `port_not_ready` | A preview did not answer with a 2xx before `waitMs` ran out. |
|
|
322
|
+
| `edit_not_found`, `edit_not_unique` | `files.edit` matched zero times or more than once. |
|
|
323
|
+
| `file_not_found` | The path does not exist. |
|
|
324
|
+
| `invalid_argument` | The input is invalid. Retrying will not help. |
|
|
325
|
+
| `provider` | Any other provider or adapter failure. Read `message` and `cause`. |
|
|
319
326
|
|
|
320
327
|
## Give an agent a sandbox
|
|
321
328
|
|
|
@@ -333,12 +340,12 @@ const { text } = await generateText({
|
|
|
333
340
|
});
|
|
334
341
|
```
|
|
335
342
|
|
|
336
|
-
| Framework
|
|
337
|
-
|
|
|
338
|
-
| AI SDK 7
|
|
339
|
-
| Mastra 1.78+
|
|
340
|
-
| OpenAI Agents 0.20+ | `@opencoredev/sandbox-sdk/openai` | tool array for `new Agent({ tools })`
|
|
341
|
-
| Anything else
|
|
343
|
+
| Framework | Import | Returns |
|
|
344
|
+
| ------------------- | --------------------------------- | ------------------------------------------ |
|
|
345
|
+
| AI SDK 7 | `@opencoredev/sandbox-sdk/ai` | tool map for `generateText` / `streamText` |
|
|
346
|
+
| Mastra 1.78+ | `@opencoredev/sandbox-sdk/mastra` | tool map for `new Agent({ tools })` |
|
|
347
|
+
| OpenAI Agents 0.20+ | `@opencoredev/sandbox-sdk/openai` | tool array for `new Agent({ tools })` |
|
|
348
|
+
| Anything else | `@opencoredev/sandbox-sdk/tools` | `createSandboxTools` and Zod `toolSchemas` |
|
|
342
349
|
|
|
343
350
|
The default tools are `run`, `read_file`, `write_file`, `edit_file`, `start_process`, `process_logs`, and `stop_process`. Opt into `search`, `list_files`, `changes`, or `preview` with `allow`. Results are compact and capped for model context, and registered secrets never reach the model. Use `beforeRun` to deny or rewrite commands. `root` limits file paths, but it is not a security boundary; the sandbox is.
|
|
344
351
|
|
|
@@ -348,15 +355,15 @@ The SDK aims for near-zero overhead on top of each provider's own API. The root
|
|
|
348
355
|
|
|
349
356
|
Time the SDK adds on top of each provider's own SDK, as median milliseconds. "Cold" is `createSandbox` plus the first `box.run("true")`, compared with the provider SDK's create plus its own exec. "Run" is a warm `run("true")` on an existing sandbox. Negative numbers and small differences are within provider noise.
|
|
350
357
|
|
|
351
|
-
| Provider
|
|
352
|
-
|
|
|
353
|
-
| E2B
|
|
354
|
-
| Daytona
|
|
355
|
-
| Upstash Box |
|
|
356
|
-
| Freestyle
|
|
357
|
-
| Tenki
|
|
358
|
-
| Superserve
|
|
359
|
-
| boxd
|
|
358
|
+
| Provider | Create | Cold: create to first command | Warm `run` |
|
|
359
|
+
| ----------- | -----: | ----------------------------: | ---------: |
|
|
360
|
+
| E2B | +24 | +52 | +8 |
|
|
361
|
+
| Daytona | ±0 | ±0 | +38 |
|
|
362
|
+
| Upstash Box | +27 | +69 | +15 |
|
|
363
|
+
| Freestyle | ±0 | +51 | +23 |
|
|
364
|
+
| Tenki | ±0 | +119 | +15 |
|
|
365
|
+
| Superserve | ±0 | +73 | +9 |
|
|
366
|
+
| boxd | +272 | +370 | +52 |
|
|
360
367
|
|
|
361
368
|
boxd has no native metadata field, so a sandbox created with labels or a `key` writes its ownership record with one extra request before `createSandbox` returns. The other providers send labels with the create call itself and run any guest setup inside your first command.
|
|
362
369
|
|
package/dist/ai.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{J}from"./chunk-23tjmd39.js";import{M}from"./chunk-nw845a93.js";import"./chunk-ckym4cht.js";import{tool as u}from"ai";function b(p,m){return Object.fromEntries(M(p,m).map((o)=>[o.name,u({description:o.description,inputSchema:o.inputSchema,async*execute(e,s){let r=new AbortController,c=s.abortSignal?AbortSignal.any([r.signal,s.abortSignal]):r.signal,n=new J,a=n.stream(),l=a.next(),i=o.execute(e,(t)=>n.emit({stream:t.stream,text:t.text}),c).finally(()=>n.end());try{while(!0){let t=await l;if(t.done)break;yield{text:t.value.text},l=a.next()}yield await i}finally{r.abort(),await i,await a.return(void 0)}},toModelOutput:({output:e})=>({type:"text",value:e.text})})]))}export{b as sandboxTools};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{n}from"./chunk-2ts3evzh.js";import{s}from"./chunk-xgxfy2n8.js";import{posix as q}from"node:path";var l={CI:"1",PAGER:"cat",GIT_TERMINAL_PROMPT:"0",DEBIAN_FRONTEND:"noninteractive",TERM:"dumb",NO_COLOR:"1"},u=(t=".")=>q.resolve("/workspace",t),re="if [ -f /tmp/.sandbox-sdk/secret-names.json ]; then cat /tmp/.sandbox-sdk/secret-names.json || exit 1; printf '\\000'; env -0; fi",G=`trap 'rm -rf -- "$2"' EXIT
|
|
2
|
+
(umask 077; mkdir -p "$2") || exit 1
|
|
3
|
+
{ { "$3" -c "$1" 3>&- 4>&-; printf '%s\\n' "$?" > "$2/status"; } 2>&1 >&3 | cat >&4; } 3>&1 4>&2 | cat
|
|
4
|
+
read -r code < "$2/status"
|
|
5
|
+
exit "$code"`,z=(t,e,o="sh")=>`sh -c ${n(G)} sh ${n(t)} ${n(e)} ${n(o)}`,B=new Map,me=(t,e)=>(B.get(t)?.get(e)??0)>0;function F(t,e){let o=B.get(t);if(!o)o=new Map,B.set(t,o);let a=o;return a.set(e,(a.get(e)??0)+1),()=>{let h=(a.get(e)??1)-1;if(h)a.set(e,h);else a.delete(e);if(!a.size)B.delete(t)}}class A{limit;head=Buffer.alloc(0);tail=Buffer.alloc(0);total=0;constructor(t){this.limit=t}add(t){let e=Buffer.from(t);this.total+=e.length;let o=Math.ceil(this.limit/2),a=Math.min(e.length,o-this.head.length);if(a>0)this.head=Buffer.concat([this.head,e.subarray(0,a)]);if(this.tail=Buffer.concat([this.tail,e.subarray(Math.max(0,a))]),this.tail.length>this.limit-o)this.tail=this.tail.subarray(this.tail.length-(this.limit-o))}get truncated(){return this.total>this.limit}text(){if(!this.truncated)return Buffer.concat([this.head,this.tail]).toString();let t=new TextDecoder().decode(this.head,{stream:!0}),e=0;while(e<this.tail.length&&((this.tail[e]??0)&192)===128)e++;let o=this.tail.subarray(e).toString();return t+`
|
|
6
|
+
[${this.total-Buffer.byteLength(t)-Buffer.byteLength(o)} bytes cut]
|
|
7
|
+
`+o}}class J{listeners=new Set;ended=!1;failure;emit(t){for(let e of this.listeners)e(t)}fail(t){this.failure=t,this.end()}end(){this.ended=!0;for(let t of this.listeners)t()}async*stream(){let t=[],e=0,o=()=>{},a=(h)=>{if(h){let d=Buffer.byteLength(h.text)>1048576?Buffer.from(h.text).subarray(-1048576).toString():h.text;t.push({...h,text:d}),e+=Buffer.byteLength(d);while(e>1048576&&t.length>1)e-=Buffer.byteLength(t.shift()?.text??"")}o()};this.listeners.add(a);try{while(!this.ended||t.length){let h=t.shift();if(h)e-=Buffer.byteLength(h.text),yield h;else await new Promise((d)=>{o=d})}if(this.failure)throw this.failure}finally{this.listeners.delete(a)}}}function E(t,e,o=!1){let a=[];function h(d=!1){let b=t.secrets,w=new Set(b.map((i)=>i[0]));while(a.length){let i=a[0];if(!i)break;if(!w.has(i.text[0])){let r=1;while(r<i.text.length&&!w.has(i.text[r]))r++;if(e({stream:i.stream,text:i.text.slice(0,r)}),i.text=i.text.slice(r),!i.text)a.shift();continue}let v=a.flatMap((r)=>o||r.stream===i.stream?[r.text]:[]).join(""),y=b.find((r)=>v.startsWith(r));if(y){e({stream:i.stream,text:"[REDACTED]"});let r=y.length;for(let x of a)if((o||x.stream===i.stream)&&r){let g=Math.min(r,x.text.length);x.text=x.text.slice(g),r-=g}}else{if(!d&&b.some((x)=>x.startsWith(v))){if(a.reduce((x,g)=>x+Buffer.byteLength(g.text),0)<=1048576)break;e({stream:i.stream,text:"[REDACTED]"}),a.shift();continue}let r=1;while(r<i.text.length&&!w.has(i.text[r]))r++;e({stream:i.stream,text:i.text.slice(0,r)}),i.text=i.text.slice(r)}for(let r=a.length-1;r>=0;r--)if(!a[r]?.text)a.splice(r,1)}}return{push(d){if(!t.secrets.length){e(d);return}a.push({...d}),h()},flush(){h(!0)}}}function oe(t,e,o,a,h,d=()=>{}){return(b,w={})=>{let i={...w},v,y=new J,r=(c=!1)=>v??=x(c).catch((p)=>{let m=o.error(p,t.name,e);throw y.fail(m),m});async function x(c){await d();let p=i.timeoutMs??120000,m=i.maxOutputBytes??1048576;if(!Number.isFinite(p)||p<=0||!Number.isSafeInteger(m)||m<1)s("timeoutMs and maxOutputBytes must be positive");let D=u(i.cwd),N=Date.now(),O=new A(m),C=new A(m),S=new A(m*2),k=new AbortController,R=i.signal?.aborted??!1,_=()=>{R=!0,k.abort()};i.signal?.addEventListener("abort",_,{once:!0});let j=setTimeout(_,p),P=`/tmp/.sandbox-sdk/runs/${crypto.randomUUID()}`,I=!1,H=F(t.name,e),T=E(o,(f)=>{S.add(f.text),y.emit(f)},!0),L=E(o,(f)=>{(f.stream==="stdout"?O:C).add(f.text),T.push(f)});try{if(R)k.abort();let f=R?{exitCode:null,timedOut:!0}:await t.exec(e,{command:t.inlineActivity?b:z(b,P,t.commandShell),cwd:D,env:{...a,...i.env,...l},stdin:i.stdin,timeoutMs:p,signal:k.signal,streaming:c,envMode:i.env===void 0?"sandbox":void 0,activityPath:t.inlineActivity?P:void 0,onChunk:(M)=>L.push(M)});return I=f.exitCode!==null&&f.exitCode>=0&&f.exitCode<128&&!f.timedOut&&!k.signal.aborted,R||=f.timedOut,L.flush(),T.flush(),h(O.total+C.total),{ok:!R&&f.exitCode===0,exitCode:R?null:f.exitCode,stdout:O.text(),stderr:C.text(),output:S.text(),durationMs:Date.now()-N,truncated:O.truncated||C.truncated||S.truncated,timedOut:R,cwd:D,command:o.text(b)}}catch(f){L.flush(),T.flush();let M=o.error(f,t.name,e);throw y.fail(M),M}finally{if(clearTimeout(j),i.signal?.removeEventListener("abort",_),!I&&!t.inlineActivity)await Promise.resolve().then(()=>t.files.remove(e,P,{recursive:!0})).catch(()=>{});H(),y.end()}}let g={[Symbol.toStringTag]:"RunHandle",then(c,p){return r().then(c,p)},catch(c){return r().catch(c)},finally(c){return r().finally(c)},[Symbol.asyncIterator](){let c=y.stream(),p=c.next();r(!0).catch(()=>{});let m=!0;return{next:()=>{if(m)return m=!1,p;return c.next()},return:()=>c.return(void 0)}},cwd(c){if(v)s("Run already started");return i.cwd=c,g},env(c){if(v)s("Run already started");return i.env={...i.env,...c},g},timeout(c){if(v)s("Run already started");return i.timeoutMs=c,g}};return g}}
|
|
8
|
+
export{l,u,re,me,A,J,E,oe};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t,r,e,w}from"./chunk-xgxfy2n8.js";var A=new WeakMap;function z(s){return s instanceof e?A.get(s):void 0}var C={disconnected:"unavailable",truncated:"unavailable",frame_too_large:"unsupported",malformed:"provider"};function h(s,a,d,n){let i=new e(`${a}. The stream from ${d.provider} cannot be read further.`,{code:C[s],provider:d.provider,sandboxId:d.sandboxId,retryable:s==="disconnected"||s==="truncated",...n===void 0?void 0:{cause:w(n)??s}});return A.set(i,s),i}class S{chunks=[];head=0;length=0;push(s){if(s.byteLength)this.chunks.push(s),this.length+=s.byteLength}find(s,a=0){let d=0;for(let n=0;n<this.chunks.length;n++){let i=this.chunks[n],l=n===0?this.head:0,u=i.byteLength-l;if(a<d+u){for(let o=Math.max(l,l+a-d);o<i.byteLength;o++)if(s(i[o]))return d+o-l}d+=u}return-1}at(s){let a=s;for(let d=0;d<this.chunks.length;d++){let n=this.chunks[d],i=d===0?this.head:0;if(a<n.byteLength-i)return n[i+a];a-=n.byteLength-i}return}take(s){let a=new Uint8Array(s),d=0;while(d<s){let n=this.chunks[0],i=Math.min(s-d,n.byteLength-this.head);if(a.set(n.subarray(this.head,this.head+i),d),d+=i,this.head+=i,this.head===n.byteLength)this.chunks.shift(),this.head=0}return this.length-=s,a}}async function*k(s,a){let d=s.getReader(),{signal:n}=a,i=!1,l=()=>{d.cancel(n?.reason).catch(()=>{})};n?.addEventListener("abort",l,{once:!0});try{if(n?.aborted)throw v(a);for(;;){let u;try{u=await d.read()}catch(o){if(i=!0,n?.aborted)throw v(a);if(o instanceof e){if(o.code==="unavailable"||o.code==="outcome_unknown")A.set(o,"disconnected");throw o}throw h("disconnected","The connection dropped mid-stream",a,o)}if(n?.aborted)throw i=!0,v(a);if(u.done){i=!0;return}yield u.value}}finally{if(n?.removeEventListener("abort",l),!i)await d.cancel().catch(()=>{});d.releaseLock()}}function v(s){return new e("Stream aborted. The signal was cancelled.",{code:"aborted",provider:s.provider,sandboxId:s.sandboxId})}var p=new TextDecoder;var O=16777216;async function*ie(s,a){let d=a.maxFrameBytes??O,n=new S,i=(l,u)=>{let o=p.decode(l).replace(/\r$/,"");try{return JSON.parse(o)}catch{throw u?h("truncated","The stream ended inside a JSON line",a):h("malformed","A line is not valid JSON",a)}};for await(let l of k(s,a)){let u=n.length;n.push(l);for(let o=n.find((f)=>f===10,u);o>=0;o=n.find((f)=>f===10)){if(o>d)throw h("frame_too_large",`A JSON line exceeds ${d} bytes`,a);let f=n.take(o+1).subarray(0,o);if(f.some((c)=>c!==13&&c!==32&&c!==9))yield i(f,!1)}if(n.length>d)throw h("frame_too_large",`A JSON line exceeds ${d} bytes`,a)}if(n.length){let l=n.take(n.length);if(l.some((u)=>u!==13&&u!==32&&u!==9))yield i(l,!0)}}async function*ae(s,a){let d=a.maxFrameBytes??O,n=new S,i=k(s,a),l=async(f)=>{while(n.length<f){let c=await i.next();if(c.done)return!1;n.push(c.value)}return!0};try{for(let f=!1;;){if(!await l(5)){if(n.length)throw h("truncated","The stream ended inside a Connect frame header",a);if(!f)throw h("truncated","The stream ended before the Connect end-of-stream frame",a);return}if(f)throw h("malformed","A Connect frame followed the end-of-stream frame",a);let c=n.take(5),b=c[0],m=new DataView(c.buffer,c.byteOffset,5).getUint32(1);if(b&1)throw h("malformed","A Connect frame is compressed, but no compression was negotiated",a);if(b&-4)throw h("malformed","A Connect frame has unknown flags",a);if(m>d)throw h("frame_too_large",`A Connect frame exceeds ${d} bytes`,a);if(!await l(m))throw h("truncated","The stream ended inside a Connect frame",a);let g=u(n.take(m));if(b&2)f=!0,yield o(g);else yield{kind:"message",message:g}}}finally{await i.return()}function u(f){try{return JSON.parse(p.decode(f))}catch{throw h("malformed","A Connect frame is not valid JSON",a)}}function o(f){if(!r(f)||f===null)throw h("malformed","The Connect end-of-stream frame is not an object",a);let c="error"in f?f.error:void 0,b="metadata"in f?f.metadata:void 0,m={kind:"end"};if(c!==void 0){if(!r(c)||c===null)throw h("malformed","The Connect end-of-stream error is not an object",a);let g="code"in c?c.code:void 0,y="message"in c?c.message:void 0,x="details"in c?c.details:void 0;if(!t(g))throw h("malformed","The Connect end-of-stream error has no code",a);m.error={code:g,...t(y)?{message:y}:void 0,...Array.isArray(x)?{details:x}:void 0}}if(r(b)){let g=Object.entries(b).filter((y)=>Array.isArray(y[1])&&y[1].every((x)=>t(x)));m.metadata=Object.fromEntries(g)}return m}}function de(s,a=!1){let d=new TextEncoder().encode(JSON.stringify(s)),n=new Uint8Array(5+d.byteLength);return n[0]=a?2:0,new DataView(n.buffer).setUint32(1,d.byteLength),n.set(d,5),n}
|
|
2
|
+
export{z,ie,ae,de};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t,o}from"./chunk-xgxfy2n8.js";function T(s){let i=[];function f(r){if(t(r)){let e=Buffer.from(r),n=Buffer.alloc(5);n[0]=117,n.writeUInt32LE(e.length,1),i.push(n,e)}else if(o(r)){let e=Buffer.alloc(9);e[0]=103,e.writeDoubleLE(r,1),i.push(e)}else if(Array.isArray(r)){let e=Buffer.alloc(5);e[0]=91,e.writeUInt32LE(r.length,1),i.push(e);for(let n of r)f(n)}else if(r!==void 0){i.push(Buffer.from("{"));for(let[e,n]of Object.entries(r))if(n!==void 0)f(e),f(n);i.push(Buffer.from("0"))}}return f(s),Buffer.concat(i)}
|
|
2
|
+
export{T};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{l,u,re,E,oe}from"./chunk-23tjmd39.js";import{f}from"./chunk-9w9rddra.js";import{V,G,Z,ce}from"./chunk-hgrwyjrb.js";import{K,ee,le}from"./chunk-ckym4cht.js";import{n}from"./chunk-2ts3evzh.js";import{t,o,e,C,s}from"./chunk-xgxfy2n8.js";function Oe(r,i,m){async function y(p,x,k){if(!x)return await r(`git ${p}`,{cwd:k});m.add([x]);let O=`/tmp/.sandbox-sdk/credential-${crypto.randomUUID()}`,N=`#!/bin/sh
|
|
2
|
+
if [ "$1" = get ]; then printf 'username=x-access-token\\npassword='; cat ${n(O+".token")}; printf '\\n'; fi
|
|
3
|
+
`;await r(`umask 077; mkdir -p /tmp/.sandbox-sdk; cat > ${n(O+".token")}; printf '%s' ${n(N)} > ${n(O)}`,{stdin:x});let j=()=>Promise.all([K(i,O),K(i,O+".token")]),M;try{M=await r(`git -c credential.helper= -c ${n(`credential.helper=!sh ${n(O)}`)} ${p}`,{cwd:k})}catch(A){throw await j().catch(()=>{}),A}return await j(),M}return{clone:(p,x={})=>y(`clone ${x.branch?`--branch ${n(x.branch)} `:""}${x.depth?`--depth ${n(String(x.depth))} `:""}-- ${n(p)} ${n(x.dir??"app")}`,x.token),status:(p)=>Promise.resolve(r("git status --porcelain",{cwd:p})),diff:(p)=>Promise.resolve(r("git diff",{cwd:p})),commit:async(p,x)=>{if(x.all)await r("git add -A",{cwd:p});return await r(`git commit -m ${n(x.message)}${x.author?` --author=${n(x.author)}`:""}`,{cwd:p})},push:(p,x={})=>y(`push -- ${n(x.remote??"origin")}${x.branch?` ${n(x.branch)}`:""}`,x.token,p),checkout:(p,x)=>Promise.resolve(r(`git checkout ${x.create?"-b ":""}${n(x.branch)}`,{cwd:p}))}}import{posix as Fe}from"node:path";function Me(r){let i=[],m=r.stream==="stdout"?"O":"E",y=r.text.split(`
|
|
4
|
+
`);for(let p=0;p<y.length;p++){let x=y[p]??"",k=p<y.length-1;for(let O=0;O<x.length;){let N=Math.min(x.length,O+8192),j=x.charCodeAt(N-1);if(N<x.length&&j>=55296&&j<=56319)N--;i.push((k&&N===x.length?m:m.toLowerCase())+x.slice(O,N)+`
|
|
5
|
+
`),O=N}if(!x&&k)i.push(m+`
|
|
6
|
+
`)}return i}function Ie(r,i,m,y){let p=Buffer.from(r.buffer,r.byteOffset,r.byteLength),x=[],k=Math.min(i,p.length),O=0;while(k<p.length&&O<m){let N=k===0?0:p.lastIndexOf(10,k-1)+1,j=p[N];if(k===N)k++;let M=p.indexOf(10,k);if(M<0)break;let A=Math.min(M,k+m-O),F=(ae)=>((p[ae]??0)&192)===128;while(A>k&&A<M&&F(A))A--;if(A===k&&k<M){if(O)break;A++;while(A<M&&F(A))A++}let U=p.subarray(k,A).toString();if(O+=A-k,k=A,k===M&&(j===79||j===69)&&O<m)U+=`
|
|
7
|
+
`,O++,k++;else if(k===M&&j!==79&&j!==69)k++;x.push({stream:j===69||j===101?"stderr":"stdout",text:U,cursor:String(y+k)})}return{events:x,offset:k}}function Pe(r){let i=JSON.parse(r);if(!f(i))s("Invalid process record");let{command:m,startedAt:y,port:p}=i;if(!t(m)||!o(y))s("Invalid process record");return{command:m,startedAt:y,port:o(p)?p:void 0}}function Ne(r,i){let m=JSON.parse(r);if(!f(m))s("Invalid process restart record");let{command:y,cwd:p,env:x,readyTimeoutMs:k,readiness:O}=m,N={name:i};if(t(p))N.cwd=p;if(f(x)){N.env={};for(let[j,M]of Object.entries(x))if(t(M))N.env[j]=M}if(o(k))N.readyTimeoutMs=k;if(f(O)){let{log:j,flags:M,port:A,http:F}=O;if(t(j))N.ready={log:new RegExp(j,t(M)?M:"")};else if(o(A))N.ready={port:A};else if(f(F)&&o(F.port))N.ready={http:{port:F.port,path:t(F.path)?F.path:void 0}}}return{command:t(y)?y:void 0,options:N}}function ve(r){let i={stdout:"",stderr:""};if(r===void 0||/^\d+$/.test(r))return{offset:r,pending:i};if(Buffer.byteLength(r)>1048576)s("Invalid line cursor");let m;try{m=JSON.parse(r)}catch{s("Invalid line cursor")}if(!f(m))s("Invalid line cursor");let{v:y,offset:p,stdout:x,stderr:k}=m;if(y!==1||!t(p)||!/^\d+$/.test(p)||!Number.isSafeInteger(Number(p))||!t(x)||!t(k)||Buffer.byteLength(x)>65536||Buffer.byteLength(k)>65536)s("Invalid line cursor");return{offset:p,pending:{stdout:x,stderr:k}}}var me={missing:66,running:73,badCwd:74};function $e(r){return{dir:n(r),spec:n(`${r}/spec.json`),restart:n(`${r}/restart.json`),base:n(`${r}/base`),log:n(`${r}/out.log`),rotate:n(`${r}/rotate`),exit:n(`${r}/exit`),pid:n(`${r}/pid`),lock:n(`${r}/lock`),stdout:n(`${r}/stdout`),stderr:n(`${r}/stderr`)}}function Re(r){return["lock_me=$$","read -r lock_me _ 2>/dev/null < /proc/self/stat","lock_idle=0",`until mkdir ${r} 2>/dev/null && : > ${r}/"$lock_me"`,"do lock_owner=",`for lock_entry in ${r}/*`,'do [ -e "$lock_entry" ] && lock_owner=${lock_entry##*/}',"done",'if [ -n "$lock_owner" ]',"then lock_idle=0","if [ -r /proc/self/stat ]","then lock_state=Z",'read -r _ _ lock_state _ 2>/dev/null < /proc/"$lock_owner"/stat','elif kill -0 "$lock_owner" 2>/dev/null',"then lock_state=S","else lock_state=Z","fi",`case "$lock_state" in Z|X) rm ${r}/"$lock_owner" 2>/dev/null && rmdir ${r} 2>/dev/null;; esac`,`elif [ -d ${r} ]`,"then lock_idle=$((lock_idle+1))",`[ "$lock_idle" -lt 100 ] || { rmdir ${r} 2>/dev/null; lock_idle=0; }`,"fi","sleep .01","done"]}function Ce(r){return`rm ${r}/"$lock_me" 2>/dev/null && rmdir ${r}`}function Ee(r){let i=$e(r.dir);return[`[ -f ${i.spec} ] || exit ${me.missing}`,`cat ${i.spec} || exit 1`,"printf '\\000'",...Re(i.lock),`trap ${n(Ce(i.lock))} EXIT`,`b=$(cat ${i.base})`,`n=$(wc -c < ${i.log})`,`a=${r.after??'"$b"'}`,`s=$((a-b-${r.lookbehind}))`,'[ "$s" -ge 0 ] || s=0',"e=running",`if [ -f ${i.exit} ]`,`then e=$(cat ${i.exit})`,"fi",`printf '%s %s %s %s\\n' "$b" "$s" "$n" "$e"`,`dd if=${i.log} bs=1 skip="$s" count=${r.length} 2>/dev/null | base64`].join("; ")}function Te(r){let i=$e(r.dir);return[`mkdir -p ${i.dir} || exit 1`,...Re(i.lock),`trap ${n(Ce(i.lock))} EXIT`,`if [ -f ${i.spec} ] && [ ! -f ${i.exit} ]`,`then exit ${me.running}`,"fi","b=0",`if [ -f ${i.base} ]`,`then b=$(cat ${i.base})`,`n=$(wc -c < ${i.log})`,"b=$((b+n))","fi",`IFS= read -r s && IFS= read -r r && printf '%s' "$s" | base64 -d > ${i.spec} && (umask 077; printf '%s' "$r" | base64 -d > ${i.restart}) && : > ${i.log} && printf '%s' "$b" > ${i.base} && rm -f ${i.exit} || exit 1`,`m=$(cd ${n(r.cwd)} 2>&1) && exit 0`,"c=$?",`printf '%s
|
|
8
|
+
' "$m" | sed 's/^/E/' > ${i.log}`,`printf 0 > ${i.pid}`,`printf '%s' "$c" > ${i.exit}`,`exit ${me.badCwd}`].join("; ")}function Le(r){let i=[];for(let m of r.flatMap((y)=>y.split(`
|
|
9
|
+
`))){if(!m)continue;i.push(`s|${Se(m)}|[REDACTED]|g`);for(let y=0;y<m.length-1;y++)i.push(`s|${Se(m.slice(0,m.length-1-y))}$|[REDACTED]|`),i.push(`s|^${Se(m.slice(y+1))}|[REDACTED]|`)}return i.join(`
|
|
10
|
+
`)+`
|
|
11
|
+
`}function Se(r){return r.replace(/[\\[\].*^$|]/g,"\\$&")}function Je(r){let i=$e(r);return`append() { ${[...Re(i.lock),`printf '%s%s\\n' "$1" "$2" >> ${i.log}`,`n=$(wc -c < ${i.log})`,'if [ "$n" -gt 10485760 ]',`then tail -c 5242880 ${i.log} | tail -n +2 > ${i.rotate}`,`kept=$(wc -c < ${i.rotate})`,`b=$(cat ${i.base})`,`echo $((b+n-kept)) > ${i.base}`,`mv ${i.rotate} ${i.log}`,"fi",Ce(i.lock)].join("; ")}; };`}function je(r){return["(nl=$(printf '\\nX')","nl=${nl%X}","while :","do chunk=$(dd bs=4096 count=1 2>/dev/null; printf .)","chunk=${chunk%.}",'[ -n "$chunk" ] || break',"need=0",`for byte in $(printf '%s' "$chunk" | tail -c 4 | od -An -tu1)`,'do if [ "$byte" -ge 240 ]',"then need=3",'elif [ "$byte" -ge 224 ]',"then need=2",'elif [ "$byte" -ge 192 ]',"then need=1",'elif [ "$byte" -ge 128 ]','then [ "$need" -le 0 ] || need=$((need-1))',"else need=0","fi","done",'if [ "$need" -gt 0 ]','then rest=$(dd bs=1 count="$need" 2>/dev/null; printf .)',"rest=${rest%.}",'chunk="$chunk$rest"',"fi",`chunk=$(printf '%s\\n' "$chunk" | sed -u -f ${n(r.sedPath)}; printf .)`,"chunk=${chunk%.}",'chunk=${chunk%"$nl"}','while [ -n "$chunk" ]','do case "$chunk" in *"$nl"*) line=${chunk%%"$nl"*}',`append ${r.marker} "$line"`,'chunk=${chunk#*"$nl"};',`*) append ${r.marker.toLowerCase()} "$chunk"`,"chunk=;","esac","done",`done < ${n(r.fifo)}) &`].join("; ")}function Ae(r){let i=$e(r.dir);return[`chmod 600 ${n(r.sedPath)}`,`trap 'code=$?; printf "%s" "$code" > ${i.exit}' EXIT`,"trap 'exit 143' TERM",`${Je(r.dir)} rm -f ${i.stdout} ${i.stderr}`,`mkfifo ${i.stdout} ${i.stderr}`,`${je({marker:"O",fifo:`${r.dir}/stdout`,sedPath:r.sedPath})} out=$!`,`${je({marker:"E",fifo:`${r.dir}/stderr`,sedPath:r.sedPath})} err=$!`,`{ cd ${n(r.cwd)} && sh -c ${n(r.command)}; } > ${i.stdout} 2> ${i.stderr}`,"code=$?",'wait "$out" "$err"','exit "$code"'].join("; ")}function Be(r){let i=$e(r.dir),m=`nohup setsid sh -c ${n(r.supervisor)} > /dev/null 2>&1 < /dev/null & echo $! > ${i.pid}`;if(!r.waitForExit)return m;return[m,"i=0",`while [ "$i" -lt 10 ] && [ ! -f ${i.exit} ]`,"do sleep 0.01","i=$((i+1))","done",`cat ${i.exit} 2>/dev/null`,"true"].join("; ")}function De(r){let i=2166136261;for(let y=0;y<r.length;y++)i=Math.imul(i^r.charCodeAt(y),16777619)>>>0;return`${(r.trim().split(/\s+/)[0]??"").split("/").pop()?.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,48)||"process"}-${i.toString(16).padStart(8,"0")}`}var we=(r)=>new Promise((i)=>setTimeout(i,r));function He(r,i,m,y,p){let x=r.processRecordRoot??"/tmp/.sandbox-sdk/procs",k=new Map,O=new Map,N=new Set,j=r.processMode==="stream",M=async(w)=>{try{return await w()}catch(b){throw y.error(b,r.name,i)}},A=(w)=>{if(!/^[a-zA-Z0-9_-]{1,128}$/.test(w))s("Process name must contain 1–128 letters, numbers, hyphens or underscores");return`${x}/${w}`},F=(w,b={},c,d=()=>{})=>r.exec(i,{command:w,stdin:c,cwd:"/workspace",env:{...p,...b,...l},timeoutMs:1e4,onChunk(D){if(D.stream==="stdout")d(D.text)}});async function U(w,b,c){if(r.files.readRange)return r.files.readRange(i,w,{offset:b,length:c});return(await r.files.read(i,w)).subarray(b,b+c)}async function ae(w,b){if(C(w))return!0;return w.code==="provider"&&!await m.exists(b)}async function ye(w){try{return Number(await m.read(`${w}/exit`))}catch(b){if(b instanceof e&&await ae(b,`${w}/exit`))return null;throw b}}async function se(w){let b=A(w),[c,d,D]=await Promise.all([m.read(`${b}/spec.json`),ye(b),m.read(`${b}/pid`)]),S=Pe(c);return{name:w,command:y.text(S.command),status:d===null?"running":d===0?"exited":"failed",pid:Number(D),ports:S.port===void 0?[]:[S.port],startedAt:S.startedAt,exitCode:d}}async function be(w,b={}){if(!Number.isInteger(w)||w<1||w>65535)s("Port must be between 1 and 65535");let c={...await r.previewUrl(i,w)};if(b.path){let d=new URL(c.url),D=new URL(b.path,d);if(D.origin!==d.origin)s("Preview path must stay on the preview's origin");c.url=D.toString()}if(b.waitMs!==void 0){let d=Date.now()+b.waitMs;do{try{let D=c.url,S=new URL(D).origin,B=new Headers(c.headers),q=new Map,X=(P)=>{let v=P.split(";")[0]?.trim()??"",a=v.indexOf("=");if(a>0)q.set(v.slice(0,a),v)};for(let P of(B.get("cookie")??"").split(";"))X(P);for(let P=0;P<5;P++){let v=await fetch(D,{headers:B,redirect:"manual",signal:AbortSignal.timeout(Math.max(1,Math.min(1000,d-Date.now())))});if(await v.body?.cancel(),v.ok)return c;let a=v.headers.get("location");if(![301,302,303,307,308].includes(v.status)||!a)break;let g=new URL(a,D);if(g.origin!==S)break;for(let R of v.headers.getSetCookie())X(R);if(q.size)B.set("cookie",[...q.values()].join("; "));if(D=g.toString(),Date.now()>=d)break}}catch{}if(Date.now()>=d)break;await we(Math.min(50,Math.max(1,d-Date.now())))}while(Date.now()<=d);throw new e(`Preview failed. Port ${w} did not answer. Check the process and its logs.`,{code:"port_not_ready"})}return c}function xe(w){let b=A(w),c=O.get(w);if(c)return c;let d="starting",D,S=!1,B;async function q(P={}){let v=ve(P.after).offset,a=v===void 0?void 0:Number(v),g=P.maxBytes??16384;if(a!==void 0&&(!Number.isSafeInteger(a)||a<0)||!Number.isSafeInteger(g)||g<1||g>1048576)s("Invalid log cursor or maxBytes");let R=Math.min(g,65536),_=32770,h,T,z,ne;if(j)d=(await se(w)).status,h=Number(await m.read(`${b}/base`)),z=(await m.stat(`${b}/out.log`)).size,T=Math.max(0,(a??h)-h-_),ne=await U(`${b}/out.log`,T,R+_*2);else{let H="",ge=await r.exec(i,{command:Ee({dir:b,after:a,lookbehind:_,length:R+_*2}),cwd:"/workspace",env:{...p,...l},timeoutMs:1e4,onChunk(Q){if(Q.stream==="stdout"){H+=Q.text;let ie=H.indexOf("\x00");if(ie>=0&&Buffer.byteLength(H.slice(ie+1))>262144)s("Oversized log page")}}});if(ge.exitCode===me.missing)throw new e("Process record not found. This process has not been started. Check the process name.",{code:"file_not_found"});if(ge.timedOut||ge.exitCode!==0)throw new e("Log range read failed. Retry the log request.",{code:"provider"});let de=H.indexOf("\x00");if(de<0)s("Invalid process record");Pe(H.slice(0,de));let ue=H.indexOf(`
|
|
12
|
+
`,de+1),fe=H.slice(de+1,ue).split(" ");h=Number(fe[0]),T=Number(fe[1]),z=Number(fe[2]);let J=fe[3];if(J!=="running"&&(J===void 0||!Number.isInteger(Number(J))))s("Invalid remote process status");if(d=J==="running"?"running":Number(J)===0?"exited":"failed",ue<0||![h,T,z].every((Q)=>Number.isSafeInteger(Q)&&Q>=0))s("Invalid remote log page");ne=Buffer.from(H.slice(ue+1),"base64")}let I=Math.max(h,a??h),L=Ie(ne,Math.max(0,I-h-T),R,h+T),W=h+T+L.offset;return{events:L.events.map((H)=>({...H,text:y.text(H.text)})),nextCursor:String(W),truncated:(a??h)<h||W<h+z}}let X={name:w,get status(){return d},get url(){return D},get ready(){return S},logs:(P={})=>M(async()=>{let v=await q(P);return{text:y.text(v.events.map((a)=>a.text).join("")),nextCursor:v.nextCursor,truncated:v.truncated}}),async*lines(P={}){let v=ve(P.after),{offset:a,pending:g}=v,R=(_)=>JSON.stringify({v:1,offset:_,...g});do{let _=await M(()=>q({after:a,maxBytes:1048576}));a=_.nextCursor;for(let h of _.events){if(g[h.stream]+=h.text,Buffer.byteLength(g[h.stream])>65536){let T=Buffer.from(g[h.stream]).subarray(-65510),z=0;while(((T[z]??0)&192)===128)z++;g[h.stream]="[line truncated]"+T.subarray(z).toString()}if(g[h.stream].endsWith(`
|
|
13
|
+
`)){let T=g[h.stream].slice(0,-1);g[h.stream]="",yield{text:T,stream:h.stream,cursor:R(h.cursor)}}}if(!_.truncated&&d!=="running"&&d!=="starting"){for(let h of["stdout","stderr"])if(g[h]){let T=g[h];g[h]="",yield{text:T,stream:h,cursor:R(a)}}break}if(!_.truncated)await we(25)}while(!0)},stop:(P={})=>M(async()=>{let v=await se(w);if(d=v.status,v.exitCode!==null)return;let a=k.get(w);if(a)await a.stop({graceMs:P.graceMs??1000});else await F(`kill -TERM -${v.pid} 2>/dev/null || true`),await we(P.graceMs??1000),await F(`kill -KILL -${v.pid} 2>/dev/null || true`);if(!await m.exists(`${b}/exit`))await m.write(`${b}/exit`,"143");d="exited"}),restart:()=>M(async()=>{if(await X.stop(),!B){let P=await se(w),v=Ne(await m.read(`${b}/restart.json`),w);await te(v.command??P.command,v.options)}else await B()}),wait:()=>M(async()=>{while(!await m.exists(`${b}/exit`))await we(25);let P=await se(w);return d=P.status,{exitCode:P.exitCode,signal:P.exitCode===143?"SIGTERM":P.exitCode===137?"SIGKILL":null}})};return O.set(w,X),Y.set(w,{state(P){d=P},access(P){D=P},ready(P){S=P},launch(P){B=P}}),X}let Y=new Map;async function te(w,b={}){let c=b.name??De(w);if(!j||!r.startProcess)return he(w,b);if(N.has(c))return M(()=>s(`Process ${c} is already running`));N.add(c);try{return await he(w,b)}finally{N.delete(c)}}async function he(w,b){return M(async()=>{let c={...b,name:b.name??De(w)};if(r.processMode==="unsupported")throw new e("Background processes are unsupported. This runtime cannot run the SDK process-record shim. Use its native process API or another provider.",{code:"unsupported"});let d=A(c.name);if(j&&r.startProcess&&await m.exists(`${d}/spec.json`)&&!await m.exists(`${d}/exit`))s(`Process ${c.name} is already running`);let D=xe(c.name),S=Y.get(c.name),B=c.ready&&"port"in c.ready?c.ready.port:c.ready&&("http"in c.ready)?c.ready.http.port:void 0,q=async()=>{let X=JSON.stringify({command:y.text(w),cwd:u(c.cwd),env:Object.fromEntries(Object.entries(c.env??{}).map(([I,L])=>[I,y.text(L)])),startedAt:Date.now(),port:B,readiness:c.ready&&("log"in c.ready?{log:c.ready.log.source,flags:c.ready.log.flags}:c.ready),readyTimeoutMs:c.readyTimeoutMs}),P=JSON.stringify({command:w,cwd:u(c.cwd),env:c.env,readiness:c.ready&&("log"in c.ready?{log:c.ready.log.source,flags:c.ready.log.flags}:c.ready),readyTimeoutMs:c.readyTimeoutMs}),v=`${d}/redact.sed`,a=!0,g,R;if(j&&r.startProcess){S?.state("starting"),S?.ready(!1),await m.write(`${d}/spec.json`,X),await m.write(`${d}/restart.json`,P);let I=await m.exists(`${d}/base`)?Number(await m.read(`${d}/base`))+(await m.stat(`${d}/out.log`)).size:0;if(await m.write(`${d}/out.log`,""),await m.write(`${d}/base`,String(I)),await m.exists(`${d}/exit`))await m.remove(`${d}/exit`)}else{let I=await F(Te({dir:d,cwd:u(c.cwd)}),{},Buffer.from(X).toString("base64")+`
|
|
14
|
+
`+Buffer.from(P).toString("base64")+`
|
|
15
|
+
`);if(I.exitCode===me.running)s(`Process ${c.name} is already running`);if(I.exitCode===me.badCwd)a=!1,S?.state("failed"),S?.ready(!1);else if(I.timedOut||I.exitCode!==0)throw new e("Process setup failed. Could not prepare durable records. Check that /tmp is writable and retry.",{code:"provider"});else{let L=Le(y.secrets);await r.files.write(i,v,new TextEncoder().encode(L)),S?.state("starting"),S?.ready(!1)}}if(S?.launch(q),a&&j&&r.startProcess){let I,L=[],W=0,H=0,ge=()=>I??=(async()=>{while(L.length||H){let J=L;L=[],W=0;let Q=H;H=0;let ie=await m.read(`${d}/out.log`,{as:"bytes"}),ke=Number(await m.read(`${d}/base`));if(Q)ke+=ie.length+Q,ie=new Uint8Array;let pe=Buffer.concat([ie,Buffer.from(J.join(""))]);if(pe.length>10485760){let _e=pe.indexOf(10,pe.length-5242880)+1;ke+=_e,pe=pe.subarray(_e)}await m.write(`${d}/base`,String(ke)),await m.write(`${d}/out.log`,pe)}})().finally(()=>{I=void 0}),de=E(y,(J)=>{for(let Q of Me(J)){L.push(Q),W+=Buffer.byteLength(Q);while(W>1048576&&L.length>1){let ie=L.shift()??"";W-=Buffer.byteLength(ie),H+=Buffer.byteLength(ie)}}ge().catch(()=>S?.state("failed"))}),ue=await r.startProcess(i,{command:w,cwd:u(c.cwd),env:{...p,...c.env,...l},onChunk:(J)=>de.push(J)});k.set(c.name,ue),await m.write(`${d}/pid`,String(ue.pid));let fe=ue.wait();R=fe.then((J)=>{g=J.exitCode??137},()=>{}),fe.then(async(J)=>{g=J.exitCode??137,de.flush(),await ge(),await m.write(`${d}/exit`,String(J.exitCode??137)),S?.state(J.exitCode===0?"exited":"failed")}).catch(async()=>{await m.write(`${d}/exit`,"1").catch(()=>{}),S?.state("failed")})}else if(a){let I=Ae({dir:d,cwd:u(c.cwd),command:w,sedPath:v});if(r.startProcess){let L=await r.startProcess(i,{command:I,cwd:"/workspace",env:{...p,...c.env,...l},onChunk(){}});k.set(c.name,L),await m.write(`${d}/pid`,String(L.pid));let W=L.wait().then((H)=>(g=H.exitCode??137,H));R=W.catch(()=>{}),W.then(async(H)=>{if(!await m.exists(`${d}/exit`))await m.write(`${d}/exit`,String(H.exitCode??137))}).catch(async()=>{await m.write(`${d}/exit`,"1").catch(()=>{})})}else{let L="";if(await F(Be({dir:d,supervisor:I,waitForExit:!c.ready}),c.env,void 0,(W)=>{L+=W}),/^\d+$/.test(L.trim()))g=Number(L.trim())}}if(!c.ready){if(g===void 0&&R)await Promise.race([R,we(100)]);let I=a?g:1;S?.state(I===void 0?"running":I===0?"exited":"failed"),S?.ready(I===void 0||I===0);return}if(a)S?.state("running");let _=Date.now()+(c.readyTimeoutMs??60000),h,T="",z=!1,ne=()=>T.replace(/\n$/,"").split(`
|
|
16
|
+
`).slice(-50).join(`
|
|
17
|
+
`);do{let I=await D.logs({after:h,maxBytes:1048576});if(h=I.nextCursor,T=Buffer.from(T+I.text).subarray(-262144).toString(),z=await m.exists(`${d}/exit`),z&&I.truncated)continue;if(z)throw new e(`Process exited before readiness. Exit ${(await se(c.name)).exitCode}. Check the last logs: ${ne()}`,{code:"process_exited"});if("log"in c.ready){if(c.ready.log.lastIndex=0,c.ready.log.test(T)){S?.ready(!0);return}}else if(B)try{let L=await be(B,r.previewMode==="placeholder"?{}:{path:"http"in c.ready?c.ready.http.path:void 0,waitMs:Math.max(1,Math.min(5000,_-Date.now()))});S?.access(L.url),S?.ready(!0);return}catch(L){if(!(L instanceof e)||L.code!=="port_not_ready")throw L}if(Date.now()>=_)break;await we(25)}while(z||Date.now()<=_);throw new e(`Process is still running but readiness timed out. No readiness signal arrived. Inspect logs: ${ne()}`,{code:"timeout"})};return await q(),D})}return{start:te,process:xe,preview:(w,b)=>M(()=>be(w,b)),processes:()=>M(async()=>{let w;try{w=await m.list(x)}catch(d){if(d instanceof e&&await ae(d,x))return[];throw d}let b=[],c=w.filter((d)=>d.type==="directory");for(let d=0;d<c.length;d+=4){let S=c.slice(d,d+4).map((B)=>Fe.basename(B.path));b.push(...await Promise.all(S.map((B)=>se(B))))}return b})}}function Ue(r){return Array.isArray(r)&&r.every((i)=>t(i)&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))}async function ht(r,i,m,y,p,x=!0){let k=!1,O=!1,N,j=!1,M=()=>{if(!j)return!1;return j=!1,ce(r,i.id)},A=0,F=0,U=()=>{if(k||O)throw new e("Sandbox handle is closed. Local resources were detached. Connect a new handle.",{code:"not_found",provider:r.name,sandboxId:i.id})},ae={...y.env,...y.secrets},ye=m||!x?Promise.resolve():void 0,se=()=>ye??=xe().catch((a)=>{throw ye=void 0,a});async function be(){if(r.readSecretEnvironment){let h=await r.readSecretEnvironment(i.id);if(!h)return;return{record:h.record,environment:new Map(Object.entries(h.environment))}}let a="",g=await r.exec(i.id,{command:re,cwd:"/",env:{},timeoutMs:1e4,onChunk(h){if(h.stream==="stdout")a+=h.text}});if(g.timedOut||g.exitCode!==0)throw new e("Secret recovery failed. Could not read the sandbox environment. Retry, or connect with recoverSecrets: false.",{code:"provider",provider:r.name,sandboxId:i.id});if(!a)return;let R=a.indexOf("\x00");if(R<0)s("Invalid secret recovery record");let _=new Map;for(let h of a.slice(R+1).split("\x00")){let T=h.indexOf("=");if(T>=0)_.set(h.slice(0,T),h.slice(T+1))}return{record:a.slice(0,R),environment:_}}async function xe(){let a=await be();if(!a)return;let g;try{g=JSON.parse(a.record)}catch{throw new e("Secret recovery failed. The secret names record is not valid JSON. Repair the record and reconnect.",{code:"provider"})}if(!Ue(g))s("Invalid secret names record");let R={};for(let _ of g)R[_]=a.environment.get(_)??"";p.add(Object.values(R)),Object.assign(ae,R,y.env,y.secrets)}let Y=async()=>{U(),await se().finally(U)},te=ee(r,i.id,p,U,se),he="/tmp/.sandbox-sdk/secret-names.json";if(m){if(y.trackChanges)await te.mark("start");else if(y.from!==void 0)await K(te,"/tmp/.sandbox-sdk/marks/start.json");let a=Object.keys(y.secrets??{});if(a.length||y.from!==void 0){let g=JSON.stringify(a);if(r.files.writeCreatesParents)await te.write(he,g);else if((await r.exec(i.id,{command:`mkdir -p /tmp/.sandbox-sdk && printf '%s' ${n(g)} > ${n(he)}`,cwd:"/",env:l,timeoutMs:1e4,onChunk(){}})).exitCode!==0)throw new e("Secret setup failed. Could not record secret names in /tmp/.sandbox-sdk. Ensure /tmp is writable.",{code:"provider",provider:r.name,sandboxId:i.id})}}let w=oe(r,i.id,p,ae,(a)=>{A++,F+=a},Y),b=He(r,i.id,ee(r,i.id,p),p,ae),c=async(a)=>{U();try{return await a()}catch(g){throw p.error(g,r.name,i.id)}},d=(a)=>c(async()=>(await Y(),a())),D=new WeakMap,S=(a)=>{let g=D.get(a);if(g)return g;let R={get name(){return a.name},get url(){return a.url},get ready(){return a.ready},get status(){return a.status},logs:async(_)=>(await c(Y),a.logs(_)),async*lines(_){await c(Y),yield*a.lines(_)},stop:async(_)=>(await c(Y),a.stop(_)),restart:async()=>(await c(Y),a.restart()),wait:async()=>(await c(Y),a.wait())};return D.set(a,R),R},B={id:i.id,key:i.key,provider:r.name,created:m,labels:i.labels,capabilities:new Set(r.capabilities),get native(){U();try{return r.native(i.id)}catch(a){throw p.error(a,r.name,i.id)}},run(a,g){return U(),w(a,g)},$(a,...g){return U(),w(a.reduce((R,_,h)=>R+_+(h<g.length?n(String(g[h])):""),""))},files:te,git:Oe((a,g)=>(U(),w(a,g)),te,p),start:(a,g)=>d(async()=>S(await b.start(a,g))),process(a){return U(),S(b.process(a))},processes:()=>d(()=>b.processes()),preview:(a,g)=>d(()=>b.preview(a,g)),usage:()=>c(async()=>({...await r.usage?.(i.id),createdAt:i.createdAt,runningMs:Date.now()-i.createdAt,commands:A,bytesOut:F})),async close(){if(k||O)return;N??=(async()=>{let a=M();try{if(a)await r.close?.(i.id)}catch(g){throw j=!0,Z(r,i.id),g}te[Symbol.dispose](),k=!0})().finally(()=>{N=void 0});try{await N}catch(a){throw p.error(a,r.name,i.id)}},async destroy(){if(O)return;try{V(r,i.id),await r.destroy(i.id),te[Symbol.dispose](),O=!0,M();let{key:a,locator:g}=y;if(a&&g?.delete)await G(r,a,y,async()=>{if(await g.get(a)===i.id)await g.delete?.(a)})}catch(a){throw p.error(a,r.name,i.id)}},async[Symbol.asyncDispose](){if(y.key)await B.close();else await B.destroy()}},{pause:q,resume:X,snapshot:P,terminal:v}=r;if(r.capabilities.has("pause")&&q&&X)Object.assign(B,{pause:()=>c(()=>q.call(r,i.id)),resume:()=>c(()=>X.call(r,i.id))});if(r.capabilities.has("snapshot")&&P)Object.assign(B,{snapshot:(a)=>c(async()=>{let g=a?.expiresInMs;if(g!==void 0&&(!Number.isSafeInteger(g)||g<0))s("expiresInMs must be a non-negative integer of milliseconds");return P.call(r,i.id,a)})});if(r.capabilities.has("terminal")&&v)Object.assign(B,{terminal:(a)=>d(async()=>{let g=await v.call(r,i.id,a),R=new Set;return{write:(h)=>d(async()=>{await g.write(h)}),resize:(h,T)=>d(async()=>{await g.resize(h,T)}),onData(h){U();let T=E(p,(I)=>h(I.text)),z=g.onData((I)=>T.push({stream:"stdout",text:I})),ne=()=>{z(),T.flush(),R.delete(ne)};return R.add(ne),ne},close:()=>d(async()=>{for(let h of R)h();await g.close()})}})});return le(B,p),Z(r,i.id),j=!0,B}export{ht as makeHandle};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t,o,r}from"./chunk-xgxfy2n8.js";function m(n){let e={name:"",message:"",headers:new Map,metadata:new Map};if(n instanceof Error)e.name=n.name,e.message=n.message;if(!r(n))return e;if("status"in n&&o(n.status))e.status=n.status;if("statusCode"in n&&o(n.statusCode))e.statusCode=n.statusCode;if("response"in n&&n.response instanceof Response)e.responseStatus=n.response.status;if("grpcCode"in n&&o(n.grpcCode))e.grpcCode=n.grpcCode;if("code"in n&&(t(n.code)||o(n.code)))e.code=n.code;if("apiCode"in n&&t(n.apiCode))e.apiCode=n.apiCode;if("json"in n&&r(n.json)&&"error"in n.json&&r(n.json.error)&&"code"in n.json.error&&t(n.json.error.code))e.bodyCode=n.json.error.code;if("source"in n&&t(n.source))e.source=n.source;if("path"in n&&t(n.path))e.path=n.path;if("requestId"in n&&t(n.requestId))e.requestId=n.requestId;if("sandboxId"in n&&t(n.sandboxId))e.sandboxId=n.sandboxId;if("headers"in n&&r(n.headers)){let i=n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers);e.headers=new Map(i.filter((d)=>t(d[1])))}if("metadata"in n&&n.metadata instanceof Headers)e.metadata=new Map(n.metadata);if("cause"in n)e.cause=n.cause;return e}
|
|
2
|
+
export{m};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{f}from"./chunk-9w9rddra.js";import{Y}from"./chunk-k60b4r27.js";import{t,r,e,D,w,c,fe,s}from"./chunk-xgxfy2n8.js";function Ze(o){return["localhost","127.0.0.1","[::1]"].includes(o)||/\.(test|invalid|example|localhost)$/.test(o)}function d(o,a){let u=Date.now()+o,p=AbortSignal.timeout(Math.max(0,o));return{signal:a?AbortSignal.any([a,p]):p,timeout:p,parent:a,remaining:()=>Math.max(0,u-Date.now())}}function y(o,a,u){return new Promise((p,g)=>{let O=()=>{clearTimeout(W),a.signal.removeEventListener("abort",C)},C=()=>{O(),g(We(a,u))},W=setTimeout(()=>{O(),p()},o);if(a.signal.aborted)C();else a.signal.addEventListener("abort",C,{once:!0})})}function Re(o,a){if(a.aborted)return Promise.reject(a.reason);return new Promise((u,p)=>{let g=()=>p(a.reason);a.addEventListener("abort",g,{once:!0}),o.then(u,p).finally(()=>a.removeEventListener("abort",g))})}function We(o,a,u){return o.parent?.aborted&&!o.timeout.aborted?new e("Request aborted. The signal was cancelled.",{code:"aborted",provider:a,sandboxId:u}):new e("Request timed out. The operation took too long.",{code:"timeout",provider:a,sandboxId:u,retryable:!0})}var _e=new WeakMap;function H(o){return o instanceof e?_e.get(o):void 0}var Xe=65536,Ye=33554432,Qe=20000,Ue=1e4,Ce=5,Le=new Set([429,502,503,504]),qe=new Set([301,302,303,307,308]),Se=new Set(["GET","HEAD","PUT","DELETE"]),et=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","UND_ERR_CONNECT_TIMEOUT","ConnectionRefused","FailedToOpenSocket","ERR_INVALID_URL","ERR_TLS_CERT_ALTNAME_INVALID","UNABLE_TO_VERIFY_LEAF_SIGNATURE","DEPTH_ZERO_SELF_SIGNED_CERT","CERT_HAS_EXPIRED"]),tt=/^(?:authorization|proxy-authorization|cookie|x-api-key|api-key|apikey)$|[-_](?:token|key|secret|password)$/,nt=/^(?:x-)?idempotency-key$/,rt=/^\s*(?:bearer|basic|token|bot|digest)\s+(\S.*?)\s*$/i,ot=/\{([A-Za-z_][A-Za-z0-9_]*)\}/g,je=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/,at=/^[A-Za-z0-9_.:-]{1,128}$/;function De(o,a=0){if(!r(o)||a>3)return[];return[..."code"in o&&t(o.code)?[o.code]:[],...De("cause"in o?o.cause:void 0,a+1)]}function st(o){return typeof o==="string"||o instanceof Uint8Array||o instanceof ArrayBuffer||ArrayBuffer.isView(o)||o instanceof Blob||o instanceof FormData||o instanceof URLSearchParams||o instanceof ReadableStream}function it(o){let a=o.get("retry-after");if(a===null)return;if(/^\d+$/.test(a.trim()))return Number(a.trim())*1000;let u=Date.parse(a);return Number.isNaN(u)?void 0:Math.max(0,u-Date.now())}function he(o,a){if(!f(o))return;for(let u of a){let p=Object.hasOwn(o,u)?o[u]:void 0;if(t(p)&&p)return p}return}function ve(o){let a;try{a=o?JSON.parse(o):void 0}catch{a=void 0}let u=f(a)?a.error:void 0,p=he(a,["code","error_code","errorCode","type"])??he(u,["code","type"])??(t(u)&&je.test(u)?u:void 0),g=he(a,["message","detail","error_description","title"])??he(u,["message"])??(t(u)?u:void 0)??(a===void 0&&o.trim()?o.trim():void 0);return{text:o,json:a,...p===void 0?void 0:{code:p},...g===void 0?void 0:{message:g}}}async function Ne(o,a,u){if(!o)return new Uint8Array;let p=o.getReader(),g=[],O=0;try{for(;;){let{done:ee,value:N}=await p.read();if(ee)break;if(O+N.byteLength>a){let M=u();if(g.push(N.subarray(0,a-O)),O=a,await p.cancel().catch(()=>{}),M)throw M;break}g.push(N),O+=N.byteLength}}finally{p.releaseLock()}let C=new Uint8Array(O),W=0;for(let ee of g)C.set(ee,W),W+=ee.byteLength;return C}var Pe=new TextDecoder;function dt(o,a,u,p){return{status:o,headers:a,body:u,text:()=>Pe.decode(u),json(){let g=Pe.decode(u);if(!g.trim())return;try{return JSON.parse(g)}catch{throw p("returned a body that is not JSON. Use fetch for text, bytes or streams")}}}}function x(o){let{provider:a,label:u}=o,p=o.timeoutMs??60000,g=o.retries??2,O=o.backoffMs??250,C=new Set,W=(n)=>{C.delete(n),C.add(n);for(let i of C){if(C.size<=256)break;C.delete(i)}},ee=(n)=>{if(!n)return;W(n);let i=rt.exec(n)?.[1];if(i)W(i)},N=(n)=>D(c([...C,...o.secrets?.()??[]])(n)),M=new Map,L=(n,i)=>{let l=i.toLowerCase();return M.get(n)?.has(l)===!0||tt.test(l)&&!nt.test(l)},P=new Map,X=o.planes;function oe(n){let i=n??o.defaultPlane,l=Object.hasOwn(X,i)?X[i]:void 0;if(!l)throw j(`Unknown plane "${String(i).slice(0,32)}". Use one of: ${Object.keys(X).join(", ")}`);return{name:i,plane:l}}function j(n,i){return new e(`${N(n)}. The request is invalid. Check the supplied options.`,{code:"invalid_argument",provider:a,sandboxId:i})}function me(n){let i=/^[a-z][a-z0-9+.-]*:/i.test(n.path)?"[absolute URL]":(n.path.split("?")[0]??"").slice(0,200);return`${n.method} ${D(i)}`}function Fe(n){let i=n.params??{},l=new Set,m=n.path.replace(ot,(R,T)=>{if(!Object.hasOwn(i,T))throw j(`The path has a {${T}} placeholder but params.${T} is missing`,n.sandboxId);let E=String(i[T]);if(E===""||E==="."||E==="..")throw j(`params.${T} must not be empty, "." or ".."`,n.sandboxId);return l.add(T),encodeURIComponent(E)}),b=Object.keys(i).filter((R)=>!l.has(R));if(b.length)throw j(`params.${b[0]} has no {${b[0]}} placeholder in the path`,n.sandboxId);return m}function Be(n,i){let l=Fe(i),m;if(/^[a-z][a-z0-9+.-]*:/i.test(l)){try{m=new URL(l)}catch{throw j("The path is not a valid URL",i.sandboxId)}if(m.protocol!=="https:"&&m.protocol!=="http:")throw j("Only http and https URLs are supported",i.sandboxId)}else{if(!l.startsWith("/"))throw j('The path must start with "/" or be an absolute URL',i.sandboxId);if(l.split("?")[0]?.split("/").some((b)=>b==="."||b===".."))throw j('The path must not contain "." or ".." segments',i.sandboxId);m=new URL(n.replace(/\/+$/,"")+l)}for(let[b,R]of Object.entries(i.query??{}))if(R!==void 0)m.searchParams.append(b,String(R));return m}function I(n,i,l,m,b=n==="unavailable"||n==="quota"){let R=n==="auth"?o.authHint:void 0;return new e(N(`${u} ${me(i)} failed${l}`),{code:n,provider:a,sandboxId:i.sandboxId,retryable:b,...R===void 0?void 0:{hint:R},...m===void 0?void 0:{cause:N(m)}})}function F(n,i,l,m=!1){let b=Ve(n,i,l,m),R=o.cause?.(n,{method:i.method,plane:l,operation:me(i),sandboxId:i.sandboxId});if(R===void 0)return b;return new e(b.message,{code:b.code,provider:a,sandboxId:b.sandboxId,retryable:b.retryable,...b.hint===void 0?void 0:{hint:b.hint},cause:R})}function Ve(n,i,l,m){let b=!Se.has(i.method)&&!i.readOnly,R=o.mapError?.(n,{method:i.method,plane:l,operation:me(i),sandboxId:i.sandboxId});switch(n.kind){case"status":{let T=R??fe(n.status);if(b&&(T==="timeout"||m))T="outcome_unknown";let E=n.body.code!==void 0&&je.test(n.body.code)?` ${n.body.code}`:"",ae=["x-request-id","request-id","x-amzn-requestid","cf-ray"].map((Q)=>n.headers.get(Q)).find((Q)=>Q!==null&&at.test(Q)),B=`HTTP ${n.status}${E}`,J=i.detail==="message"&&n.body.message?`: ${D(N(n.body.message)).slice(0,300)}`:"",te=`${B}${ae?` (request ${ae})`:""}${J}`,Z=I(T,i,` (${B})${J}.${T==="outcome_unknown"?" The request may or may not have taken effect; check before repeating it.":""}`,te,T==="unavailable"||T==="quota"||T==="timeout");return _e.set(Z,{status:n.status,...E?{code:E.trim()}:void 0}),Z}case"network":{let T=w(n.error,N);if(b&&n.sent)return I(R??"outcome_unknown",i,": the connection failed after the request was sent, so it may or may not have taken effect. Check before repeating it.",T,!1);return I(R??"unavailable",i,`: ${n.sent?"the connection failed":"the service is unreachable"}.`,T,!0)}case"timeout":if(b&&n.sent)return I(R??"outcome_unknown",i,": no response before the deadline, so it may or may not have taken effect. Check before repeating it.",void 0,!1);return I(R??"timeout",i,": no response before the deadline.",void 0,!0);case"aborted":return I(R??"aborted",i,": the signal was cancelled.",void 0,!1);default:return n}}function ze(n){if(n.body===void 0)return{body:void 0,replayable:!0};if(n.method==="GET"||n.method==="HEAD")throw j(`A ${n.method} request cannot have a body`,n.sandboxId);if(st(n.body))return{body:n.body,replayable:!(n.body instanceof ReadableStream)};return{body:JSON.stringify(n.body),contentType:"application/json",replayable:!0}}async function Ee(n,i){let{name:l,plane:m}=oe(n.plane),{body:b,contentType:R,replayable:T}=ze(n),E=!Se.has(n.method),ae=T&&(!E||n.idempotencyKey!==void 0),{signal:B}=i,J={signal:B,...n.sandboxId===void 0?void 0:{sandboxId:n.sandboxId}},te=o.fetch??((z,G)=>globalThis.fetch(z,G)),Z=`${l}\x00${n.sandboxId??""}`,Q=!1,V=()=>i.parent?.aborted&&!i.timeout.aborted?{kind:"aborted"}:B.aborted?{kind:"timeout",sent:!1}:void 0,se=async(z)=>{try{return Pe.decode(await Ne(z.body,Xe,()=>{return}))}catch{let G=V();if(G)throw F(G,n,l);return""}};for(let z=0;;z++){let G=V();if(G)throw F(G,n,l);let ge,de,{baseUrl:ye,auth:He}=m;try{ge=t(ye)?ye:await Re(Promise.resolve().then(()=>ye(J)),B),de=n.auth===!1||!He?{}:await Re(Promise.resolve().then(()=>He(J)),B)}catch(U){if(U instanceof e)throw U;let A=V();if(A)throw F(A,n,l);throw I("auth",n,`: resolving ${u} credentials failed.`,w(U,N),!1)}let $e=V();if($e)throw F($e,n,l);let we=M.get(l);if(!we)M.set(l,we=new Set);for(let[U,A]of Object.entries(de))we.add(U.toLowerCase()),ee(A);let Ge=P.get(Z)?.generation??0,ue,le;try{le=new URL(ge)}catch{throw I("provider",n,`: the ${u} base URL is invalid.`,void 0,!1)}if(ue=le.origin,Object.keys(de).length>0&&le.protocol==="http:"&&!Ze(le.hostname))throw I("invalid_argument",n,`: the ${u} base URL uses plain HTTP, which would send credentials unencrypted. Use an https URL.`,void 0,!1);let ne=Be(ge,n),ke=n.method,pe=b,S,q;for(let U=0;;U++){let A=new Headers({...m.headers,...R&&pe!==void 0?{"content-type":R}:void 0});if(n.idempotencyKey!==void 0&&o.idempotencyHeader)A.set(o.idempotencyHeader,n.idempotencyKey);if(ne.origin===ue)for(let[K,re]of Object.entries(de))A.set(K,re);for(let[K,re]of Object.entries(n.headers??{}))A.set(K,re);if(ne.origin!==ue){for(let K of Array.from(A.keys()))if(L(l,K))A.delete(K)}for(let[K,re]of A)if(L(l,K))ee(re);let ce={method:ke,headers:A,body:pe,signal:B,redirect:"manual"};if(pe instanceof ReadableStream)ce.duplex="half";try{S=await te(ne.href,ce)}catch(K){S=void 0;let re=V();q=re?.kind==="timeout"?{kind:"timeout",sent:!0}:re??{kind:"network",sent:!De(K).some((Ke)=>et.has(Ke)),error:K};break}let Ie=S.headers.get("location");if(!qe.has(S.status)||Ie===null)break;if(await S.body?.cancel().catch(()=>{}),U>=Ce)throw I("provider",n,`: more than ${Ce} redirects.`,void 0,!1);try{ne=new URL(Ie,ne)}catch{throw I("provider",n,": the redirect location is invalid.",void 0,!1)}if(ne.protocol!=="https:"&&ne.protocol!=="http:")throw I("provider",n,": the redirect left http and https.",void 0,!1);if(S.status===303||(S.status===301||S.status===302)&&ke==="POST")ke="GET",pe=void 0;else if(!T)throw I("provider",n,": the server redirected a streamed upload, which cannot be sent twice.",void 0,!1)}let Ae=S!==void 0&&m.refresh!==void 0&&!Q&&T&&n.auth!==!1&&ne.origin===ue,ie;if(Ae&&m.stale&&S&&S.status>=400&&S.status!==401)ie=ve(await se(S));let Me=!Ae||!S?void 0:S.status===401?"refused":ie!==void 0?m.stale?.({status:S.status,body:ie,credentials:de},J):void 0;if(Me!==void 0&&m.refresh&&S){if(ie===void 0)await S.body?.cancel().catch(()=>{});Q=!0;let U=P.get(Z)??{generation:0};if(P.set(Z,U),U.generation===Ge){U.pending??=m.refresh(J).then(()=>{U.generation++}).finally(()=>{U.pending=void 0});try{await Re(U.pending,B)}catch(A){let ce=V();if(ce)throw F(ce,n,l);if(A instanceof e)throw A;throw I("auth",n,`: refreshing ${u} credentials failed.`,w(A,N),!1)}}if(Me==="refused"||ae){z--;continue}throw F({kind:"status",status:S.status,headers:S.headers,body:ie??ve("")},n,l,!0)}let Oe;if(S&&S.status>=200&&S.status<300)return S;if(S){let U=ie??ve(await se(S));if(q={kind:"status",status:S.status,headers:S.headers,body:U},Le.has(S.status)){let A=it(S.headers);Oe=A===void 0?void 0:A<=Qe?A:1/0}if(!Le.has(S.status))throw F(q,n,l)}if(!q)throw new e(`${u} request produced no response`,{code:"provider",provider:a});if(q.kind==="aborted"||q.kind==="timeout")throw F(q,n,l);let xe=Oe??O*2**z*(0.5+Math.random()/2);if(!ae||z>=g||xe===1/0||xe>=i.remaining())throw F(q,n,l);try{await y(xe,i,a)}catch{throw F(V()??q,n,l)}}}async function be(n){let i=n.deadline??d(n.timeoutMs??p,n.signal),l=await Ee(n,i),m=n.maxBytes??Ye,b;try{b=await Ne(l.body,m,()=>I("unsupported",n,`: the response is larger than ${m} bytes.`,void 0,!1))}catch(R){if(R instanceof e)throw R;let{name:T}=oe(n.plane);if(i.parent?.aborted&&!i.timeout.aborted)throw F({kind:"aborted"},n,T);throw F(i.signal.aborted?{kind:"timeout",sent:!0}:{kind:"network",sent:!0,error:R},n,T)}return dt(l.status,l.headers,b,(R)=>I("provider",{...n,detail:"status"},` (HTTP ${l.status}): the response ${R}.`,void 0,!1))}async function Je(n){let i=n.deadline??(n.timeoutMs===void 0?d(2147483647,n.signal):d(n.timeoutMs,n.signal)),l=d(n.startupTimeoutMs??p),m=new AbortController,b=()=>m.abort(),R=AbortSignal.any([i.signal,l.signal]);if(R.addEventListener("abort",b,{once:!0}),R.aborted)b();let T={signal:m.signal,timeout:i.timeout,parent:i.parent,remaining:()=>Math.min(i.remaining(),l.remaining())},E;try{E=await Ee(n,T)}finally{R.removeEventListener("abort",b)}if(!E.body||E.status===204||E.status===205)return E;i.signal.addEventListener("abort",b,{once:!0});let{name:ae}=oe(n.plane),B=E.body.getReader(),J,te=!1,Z=()=>{clearTimeout(J),i.signal.removeEventListener("abort",b)},Q=new ReadableStream({async pull(V){if(n.idleTimeoutMs!==void 0)J=setTimeout(()=>{te=!0,B.cancel().catch(()=>{}),m.abort()},n.idleTimeoutMs);try{let{done:se,value:z}=await B.read();if(clearTimeout(J),te)throw Error("idle");if(se){Z(),V.close();return}V.enqueue(z)}catch(se){Z();let z=i.parent?.aborted&&!i.timeout.aborted?{kind:"aborted"}:te||i.timeout.aborted?{kind:"timeout",sent:!0}:{kind:"network",sent:!0,error:se},G=!Se.has(n.method)&&!n.readOnly;V.error(te&&z.kind==="timeout"?I(G?"outcome_unknown":"timeout",n,`: no data for ${n.idleTimeoutMs} ms${G?", so its result is unconfirmed. Check before repeating it.":"."}`,void 0,!G):F(z,n,ae))}},async cancel(V){Z(),await B.cancel(V).catch(()=>{}),m.abort()}},{highWaterMark:0});return new Response(Q,{status:E.status,statusText:E.statusText,headers:E.headers})}return{provider:a,label:u,redact:N,request:be,async json(n){return(await be(n)).json()},stream:Je,cleanup(n){let{signal:i,deadline:l,...m}=n;return be({...m,timeoutMs:Math.min(n.timeoutMs??Ue,Ue)})}}}function Te(o){return o instanceof Function||r(o)&&!Array.isArray(o)}function _(o,a,u){if(!Te(o))s(`${a} from ${u} is not an object. Install a supported version of ${u}`);return o}var ct=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE"]);function h(o){let{http:a,placeholder:u,sandboxId:p,sdk:g}=o,O=t(u)?[u]:u;function C(M,L,P={}){if(!t(M)||!ct.has(M))s(`Unsupported HTTP method ${String(M).slice(0,16)}`);if(!t(L))s("The path must be a string");let X=O.filter((j)=>L.includes(`{${j}}`)&&P.params?.[j]===void 0),oe=p===void 0||X.length===0?P.params:{...P.params,...Object.fromEntries(X.map((j)=>[j,p]))};return{method:M,path:L,plane:P.plane,sandboxId:p,params:oe,query:P.query,body:P.body,headers:P.headers,signal:P.signal,timeoutMs:P.timeoutMs,detail:"message"}}async function W(M){if(!g)throw new e(`${a.label} has no official SDK binding. Use native.request or native.fetch.`,{code:"unsupported",provider:a.provider,sandboxId:p});if(!(M instanceof Function))s(`Pass a function that imports the SDK: native.sdk(() => import("${g.package}"))`);let L;try{L=Y(await M())}catch(P){if(P instanceof Error&&(("code"in P)&&(P.code==="ERR_MODULE_NOT_FOUND"||P.code==="MODULE_NOT_FOUND")||/Cannot find (?:package|module)/.test(P.message)))throw new e(`${g.package} could not be imported. Install it next to @opencoredev/sandbox-sdk to use native.sdk().`,{code:"unavailable",provider:a.provider,sandboxId:p,hint:`npm i ${g.package}`,cause:w(P,a.redact)});throw new e(`Loading ${g.package} failed: ${w(P,a.redact)??"a non-Error value was thrown"}. Check the import passed to native.sdk().`,{code:"provider",provider:a.provider,sandboxId:p})}if(!Te(L)||Array.isArray(L))s(`native.sdk() needs the module object. Pass () => import("${g.package}")`);try{return await g.connect(L,p)}catch(P){if(P instanceof e)throw P;throw new e(`${g.package} failed in native.sdk(): ${w(P,a.redact)??"a non-Error value was thrown"}. Check the SDK version and the sandbox.`,{code:"provider",provider:a.provider,sandboxId:p,cause:w(P,a.redact)})}}return{sandboxId:p,async request(M,L,P){return await a.json(C(M,L,P))},fetch(M,L,P){let{timeoutMs:X,...oe}=C(M,L,P);return a.stream({...oe,startupTimeoutMs:X})},sdk:W}}function v(o,a,u,p){let g=o[a];if(!(g instanceof Function))s(`The module passed to native.sdk() has no ${a} export. Pass () => import("${p}")`);try{return _(Reflect.construct(g,u),a,p)}catch(O){if(O instanceof TypeError&&/constructor/i.test(O.message))s(`${a} from the module passed to native.sdk() is not a class. Pass () => import("${p}")`);throw O}}async function k(o,a,u,p){let g=Te(o)?o[a]:void 0;if(!(g instanceof Function))s(`The ${p} object has no ${a} method. Install a supported version of ${p}`);return await g.apply(o,u)}
|
|
2
|
+
export{d,y,H,x,_,h,v,k};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import{l,u,E}from"./chunk-23tjmd39.js";import{n}from"./chunk-2ts3evzh.js";import{t,r,e,C,s}from"./chunk-xgxfy2n8.js";import{posix as O,resolve as I,relative as rt}from"node:path";import{tmpdir as V}from"node:os";import{execFile as st}from"node:child_process";import{promisify as at}from"node:util";import{promises as P}from"node:fs";function ot(w,c,v){let k=(y)=>y?y.replace(/\n$/,"").split(`
|
|
2
|
+
`):[],S=k(c),d=k(v),T=(y,D)=>D&&!y?.endsWith(`
|
|
3
|
+
`)?`\
|
|
4
|
+
`:"";return[`--- ${c===void 0?"/dev/null":`a/${w}`}
|
|
5
|
+
`,`+++ ${v===void 0?"/dev/null":`b/${w}`}
|
|
6
|
+
`,`@@ -${S.length?1:0},${S.length} +${d.length?1:0},${d.length} @@
|
|
7
|
+
`,...S.map((y)=>`-${y}
|
|
8
|
+
`),T(c,S.length),...d.map((y)=>`+${y}
|
|
9
|
+
`),T(v,d.length)].join("")}async function K(w,c){try{await w.remove(c)}catch(v){if(C(v))return;if(v instanceof e&&v.code==="provider"&&!await w.exists(c))return;throw v}}function H(w){return t(w)||w instanceof Uint8Array}function Q(w,c){let v=c.split(/(\*\*\/|\*\*|\*|\?)/).map((k)=>k==="**/"?"(?:.*/)?":k==="**"?".*":k==="*"?"[^/]*":k==="?"?".":k.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")).join("");return new RegExp(`^${v}$`).test(w)||!c.includes("/")&&new RegExp(`^${v}$`).test(O.basename(w))}var Y=new WeakMap;function ue(w,c,v){let k=Y.get(w);return k?k(c,v):w.read(c,{as:"bytes"})}function ee(w,c,v,k=()=>{},S=async()=>{}){let d=w.files,T=new Set,y=at(st);async function D(i){if((await w.exec(c,{command:i,cwd:"/workspace",env:l,timeoutMs:120000,onChunk(){}})).exitCode!==0)throw new e("File transfer failed. The remote archive command failed. Ensure tar is installed and paths are accessible.",{code:"provider"})}let F=async(i)=>{try{return k(),await S().finally(k),await i()}catch(a){throw v.error(a,w.name,c)}};async function B(i=".",a={}){let p=u(i),f=[];async function o(m){for(let h of await d.list(c,m)){if(!a.glob||Q(O.relative(p,h.path),a.glob))f.push(h);if(a.recursive&&h.type==="directory")await o(h.path)}}return await o(p),f}async function G(i,a){let p=await F(()=>d.read(c,u(i)));return a?.as==="bytes"?p:new TextDecoder().decode(p)}async function _(i,a,p){let f=t(i),o=f?[[i,H(a)?a:""]]:Object.entries(i),m=(f?p:H(a)?void 0:a)??{},{mode:h}=m,g=new Set;await F(async()=>{if(h!==void 0&&(!Number.isSafeInteger(h)||h<0||h>4095))s("mode must be an integer from 0 to 0o7777, such as 0o600");let b=[];for(let[A,U]of o){let R=u(A),M=O.dirname(R);if(!d.writeCreatesParents&&!g.has(M))await d.mkdir(c,M),g.add(M);await d.write(c,R,t(U)?new TextEncoder().encode(U):U,m),b.push(R)}if(h===void 0||d.writeSupportsMode||!b.length)return;let x=await w.exec(c,{command:`chmod ${h.toString(8)} ${b.map(n).join(" ")}`,cwd:"/workspace",env:l,timeoutMs:30000,onChunk(){}});if(x.timedOut||x.exitCode!==0)throw new e(`File mode not applied. chmod ${x.timedOut?"timed out":`exited with ${x.exitCode}`}; the files were written with default permissions. Check that the paths are writable and retry.`,{code:"provider"})})}let j="/tmp/.sandbox-sdk/changes.git";async function N(i,a){let p="";if((await w.exec(c,{command:`git --git-dir=${n(j)} --work-tree=/workspace ${i}`,cwd:"/workspace",env:{...l,GIT_INDEX_FILE:`${j}/sdk.index`},stdin:a,timeoutMs:120000,onChunk(o){if(o.stream==="stdout")p+=o.text}})).exitCode!==0)throw new e("File checkpoint failed. Git could not update the hidden index. Ensure git is installed and /workspace is readable.",{code:"provider"});return p}async function L(i){let a=["-name .git",...(d.internal??[]).map((m)=>`-path ${n(`./${O.relative("/workspace",u(m))}`)}`)].join(" -o "),p=`command -v git >/dev/null 2>&1 || exit 69
|
|
10
|
+
command -v find >/dev/null 2>&1 || exit 78
|
|
11
|
+
g=${n(j)}
|
|
12
|
+
# A fresh index per call: a killed attempt leaves no index.lock to block later checkpoints.
|
|
13
|
+
export GIT_INDEX_FILE="$g/tree.$$.index"; paths="$g/tree.$$.paths"; trap 'rm -f "$GIT_INDEX_FILE" "$GIT_INDEX_FILE.lock" "$paths"' EXIT
|
|
14
|
+
[ -d "$g" ] || git init -q --bare "$g" >/dev/null || exit 69
|
|
15
|
+
cd /workspace && find . \\( ${a} \\) -prune -o ! -type d -print0 > "$paths" || exit 1
|
|
16
|
+
git --git-dir="$g" --work-tree=/workspace read-tree --empty || exit 1
|
|
17
|
+
git --git-dir="$g" --work-tree=/workspace update-index --add --remove -z --stdin < "$paths" || exit 1
|
|
18
|
+
tree=$(git --git-dir="$g" --work-tree=/workspace write-tree) || exit 1
|
|
19
|
+
${i?`mkdir -p ${n(O.dirname(i))} && printf '%s' "$tree" > ${n(i)} || exit 1
|
|
20
|
+
`:""}printf '%s\\n' "$tree"`,f="",o=await w.exec(c,{command:p,cwd:"/workspace",env:l,timeoutMs:120000,onChunk(m){if(m.stream==="stdout")f+=m.text}});if(o.exitCode===78){let m=await et();if(i)await _(i,m);return m}if(o.exitCode===69)throw new e("File checkpoint failed. Git is unavailable. Install git in the sandbox image.",{code:"unsupported"});if(o.exitCode!==0)throw new e("File checkpoint failed. Git could not update the hidden index. Ensure git is installed and /workspace is readable.",{code:"provider"});return f.trim()}async function et(){if(!await X(j)){if((await w.exec(c,{command:`git init --bare ${n(j)}`,cwd:"/workspace",env:l,timeoutMs:1e4,onChunk(){}})).exitCode!==0)throw new e("File checkpoint failed. Git is unavailable. Install git in the sandbox image.",{code:"unsupported"})}let i=[],a=new Set((d.internal??[]).map((f)=>u(f)));async function p(f){for(let o of await d.list(c,f)){if(O.basename(o.path)===".git"||a.has(o.path))continue;if(o.type==="directory")await p(o.path);else i.push(O.relative("/workspace",o.path))}}if(await p("/workspace"),await N("read-tree --empty"),i.length)await N("update-index --add --remove -z --stdin",i.join("\x00")+"\x00");return(await N("write-tree")).trim()}async function X(i){try{return await d.stat(c,i),!0}catch(a){if(C(a))return!1;throw a}}async function q(){let i={};for(let a of await B(".",{recursive:!0}))if(a.type==="file")i[a.path]=Buffer.from(await d.read(c,a.path)).toString("base64");return i}let W=(i)=>`/tmp/.sandbox-sdk/marks/${encodeURIComponent(i)}.json`;async function it(i){let a=JSON.parse(new TextDecoder().decode(await d.read(c,W(i))));if(!r(a)||Array.isArray(a))s("Invalid file checkpoint");let p={};for(let[f,o]of Object.entries(a)){if(!t(o))s("Invalid file checkpoint content");p[f]=o}return p}async function z(i,a){try{return await a()}catch(p){if((i??"start")==="start"&&!await X(W("start")).catch(()=>!0))throw new e("No start checkpoint. createSandbox records one only with trackChanges: true. Pass trackChanges: true or call files.mark() and changes({ since }).",{code:"invalid_argument"});throw p}}let nt=(i)=>z(i,()=>G(W(i??"start"))),J={[Symbol.dispose](){for(let i of T)i()},read:G,write:_,list:(i,a)=>F(()=>B(i,a)),stat:(i)=>F(()=>d.stat(c,u(i))),exists:(i)=>F(async()=>{try{return await d.stat(c,u(i)),!0}catch(a){if(C(a))return!1;throw a}}),remove:(i,a)=>F(()=>d.remove(c,u(i),{recursive:a?.recursive??!1})),edit:(i,{find:a,replace:p})=>F(async()=>{if(!a)s("find cannot be empty");let f=await G(i),o=[],m=f.indexOf(a);while(m!==-1)o.push(f.slice(0,m).split(`
|
|
21
|
+
`).length),m=f.indexOf(a,m+1);if(o.length!==1)throw new e(`Edit failed at ${i}. ${o.length?`Matches on lines ${o.join(", ")}`:"Text not found"}. Supply a unique exact match.`,{code:o.length?"edit_not_unique":"edit_not_found"});await _(i,f.replace(a,()=>p))}),upload:(i,a,p)=>F(async()=>{let f=I(i);if(d.transfer!=="files"&&(await P.lstat(f)).isDirectory()){let m=await P.mkdtemp(I(V(),"sandbox-sdk-upload-")),h=`/tmp/.sandbox-sdk/upload-${crypto.randomUUID()}.tar`;try{let g=I(m,"files.tar");await y("tar",["-cf",g,"-C",f,...(p?.ignore??[]).flatMap((b)=>["--exclude",b]),"."],{timeout:120000}),await _(h,new Uint8Array(await P.readFile(g))),await d.mkdir(c,u(a)),await D(`tar -xf ${n(h)} -C ${n(u(a))} --no-same-owner`)}finally{await P.rm(m,{recursive:!0,force:!0}),await d.remove(c,h,{recursive:!1}).catch(()=>{})}return}async function o(m,h){let g=await P.lstat(m);if(g.isSymbolicLink())s("Uploading symlinks is unsupported");if(g.isDirectory()){await d.mkdir(c,u(h));for(let b of await P.readdir(m))if(!p?.ignore?.some((x)=>Q(rt(f,I(m,b)),x)||x===b))await o(I(m,b),O.join(h,b))}else await _(h,new Uint8Array(await P.readFile(m)))}await o(f,a)}),download:(i,a)=>F(async()=>{if(d.transfer!=="files"&&(await d.stat(c,u(i))).type==="directory"){let f=await P.mkdtemp(I(V(),"sandbox-sdk-download-")),o=`/tmp/.sandbox-sdk/download-${crypto.randomUUID()}.tar`;try{await D(`mkdir -p ${n(O.dirname(o))} && tar -cf ${n(o)} -C ${n(u(i))} .`);let m=I(f,"files.tar");await P.writeFile(m,await d.read(c,o)),await P.mkdir(I(a),{recursive:!0}),await y("tar",["-xf",m,"-C",I(a),"--no-same-owner","--no-same-permissions"],{timeout:120000})}finally{await P.rm(f,{recursive:!0,force:!0}),await d.remove(c,o,{recursive:!1}).catch(()=>{})}return}async function p(f,o){let m=await d.stat(c,f);if(m.type==="symlink")s("Downloading symlinks is unsupported");if(m.type==="directory"){await P.mkdir(o,{recursive:!0});for(let h of await d.list(c,f))await p(h.path,I(o,O.basename(h.path)))}else await P.mkdir(I(o,".."),{recursive:!0}),await P.writeFile(o,await d.read(c,f))}await p(u(i),I(a))}),search:(i,a={})=>F(async()=>{let p=[],f=a.maxMatches??200;if(!Number.isSafeInteger(f)||f<1)s("maxMatches must be positive");for(let o of await B(a.path,{recursive:!0,glob:a.glob}))if(o.type==="file"){let m=(await G(o.path)).split(`
|
|
22
|
+
`);for(let[h,g]of m.entries())if(g.includes(i)){if(p.push({path:o.path,line:h+1,text:v.text(g)}),p.length>=f)return p}}return p}),watch(i,a,p={}){k();let f=!1,o,m,h=async()=>{try{if(await S(),f)return;let b=new Map((await B(i,p)).map((x)=>[x.path,`${x.size}:${x.modifiedAt}`]));if(o){for(let[x,A]of b)if(!o.has(x)||o.get(x)!==A){if(!f)a({type:o.has(x)?"modified":"added",path:x})}for(let x of o.keys())if(!b.has(x)&&!f)a({type:"removed",path:x})}o=b}catch(b){p.onError?.(v.error(b,w.name,c))}if(!f)m=setTimeout(()=>void h(),p.intervalMs??250),m.unref?.()},g=()=>{f=!0,clearTimeout(m),T.delete(g)};return T.add(g),h(),g},mark:(i=`mark-${Date.now()}-${Math.random().toString(36).slice(2)}`)=>F(async()=>{if(d.checkpoints==="files")await _(W(i),JSON.stringify(await q()));else await L(W(i));return i}),changes:(i={})=>F(async()=>{if(d.checkpoints!=="files"){let g=(await nt(i.since)).trim(),b=await L();if(!/^[0-9a-f]{40,64}$/.test(g))s("Invalid git checkpoint");let x=(await N(`diff --no-renames --name-status -z ${g} ${b}`)).split("\x00"),A={added:[],modified:[],removed:[],patch:v.text(await N(`diff --no-ext-diff --binary ${g} ${b}`))};for(let U=0;U+1<x.length;U+=2){let R=x[U],M=x[U+1];if(M)(R==="A"?A.added:R==="D"?A.removed:A.modified).push(u(M))}return A}let a=await z(i.since,()=>it(i.since??"start")),p=await q(),f=Object.keys(p).filter((g)=>!(g in a)),o=Object.keys(a).filter((g)=>!(g in p)),m=Object.keys(p).filter((g)=>(g in a)&&a[g]!==p[g]),h=[...f,...m,...o].map((g)=>ot(O.relative("/workspace",g),g in a?Buffer.from(a[g]??"","base64").toString():void 0,g in p?Buffer.from(p[g]??"","base64").toString():void 0)).join("");return{added:f,modified:m,removed:o,patch:v.text(h)}})};return Y.set(J,(i,a)=>F(()=>d.readRange?d.readRange(c,u(i),{offset:0,length:a+1}):d.read(c,u(i)))),J}import{stripVTControlCharacters as ct}from"node:util";var Z=new WeakMap;function le(w,c){Z.set(w,c)}function tt(w){let c=Z.get(w);if(!c)throw Error("Unknown sandbox handle. Secret redaction cannot be guaranteed. Use createSandbox or connectSandbox.");return c}function te(w,c){return tt(w).text(ct(c))}function ne(w,c){let v={stdout:"plain",stderr:"plain"},k=E(tt(w),c,!0);return{push(S){let d=v[S.stream],T="";for(let y of S.text)switch(d){case"plain":if(y==="\x1B")d="escape";else if(y==="")d="csi";else if("".includes(y))d="string";else T+=y;break;case"escape":d=y==="["?"csi":"]PX^_".includes(y)?"string":y>=" "&&y<="/"?"escape":"plain";break;case"csi":if(y>="@"&&y<="~")d="plain";break;case"string":if(y==="\x07"||y==="")d="plain";else if(y==="\x1B")d="string_escape";break;case"string_escape":d=y==="\\"?"plain":"string";break;default:return d}if(v[S.stream]=d,T)k.push({stream:S.stream,text:T})},flush(){k.flush()}}}
|
|
23
|
+
export{K,ue,ee,le,te,ne};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{e,C,S,s}from"./chunk-xgxfy2n8.js";var u=new WeakMap,g=(n,t)=>u.get(n)?.get(t);function k(n,t,a){let r=u.get(n);if(!r)r=new Map,u.set(n,r);if(r.delete(t),r.set(t,a),r.size>256){let o=r.keys().next().value;if(o!==void 0)r.delete(o)}}function m(n,t){u.get(n)?.delete(t)}function V(n,t){let a=u.get(n);if(!a)return;for(let[r,o]of a)if(o===t)a.delete(r)}var p=new WeakMap;async function G(n,t,a,r){let o=p.get(n);if(!o)o=new Map,p.set(n,o);let i=o.get(t)??Promise.resolve(),c=a.locator,l=i.catch(()=>{}).then(()=>a.keyMode==="exact"&&n.keyMode==="best-effort"&&c?.withLock?c.withLock(t,r):r());o.set(t,l);try{return await l}finally{if(o.get(t)===l)o.delete(t)}}var h=new WeakMap;function Z(n,t){let a=h.get(n);if(!a)a=new Map,h.set(n,a);a.set(t,(a.get(t)??0)+1)}function ce(n,t){let a=h.get(n),r=a?.get(t)??0;if(r>1)return a?.set(t,r-1),!1;return a?.delete(t),!0}function X(n,t){return n.capabilities.has(t)}var v={"sandbox-sdk":"1"};function M(n,t){for(let a of Object.keys({...t.env,...t.secrets}))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))s("Invalid environment variable name");for(let a of n.capabilities)if(a==="pause"&&(!n.pause||!n.resume)||a==="snapshot"&&!n.snapshot||a==="terminal"&&!n.terminal)throw new e("Invalid adapter capabilities. A declared method is missing. Fix the adapter contract.",{code:"provider"});if(t.size!==void 0&&!n.capabilities.has("size"))throw new e("Creation refused. Provider cannot enforce size. Choose a provider with size support.",{code:"unsupported"});if(t.network!==void 0&&t.network!=="all"&&!n.capabilities.has("network-policy"))throw new e("Creation refused. Provider cannot enforce network policy. Choose a provider with network-policy support.",{code:"unsupported"});if(t.from!==void 0&&!n.capabilities.has("snapshot"))throw new e("Creation refused. Provider cannot restore snapshots. Choose a provider with snapshot support.",{code:"unsupported"});if(t.keyMode==="exact"&&n.keyMode!=="exact"&&!t.locator?.withLock)throw new e("Exact key mode unavailable. Two-function locator storage cannot enforce distributed uniqueness. Supply locator.withLock or use an exact provider.",{code:"unsupported"});for(let a of t.ports??[])if(!Number.isInteger(a)||a<1||a>65535)s("Invalid port");for(let a of[t.timeoutMs,t.idleTimeoutMs])if(a!==void 0&&(!Number.isFinite(a)||a<=0))s("Timeouts must be positive milliseconds")}async function O(n,t={}){let a=new S;a.add(Object.values(t.secrets??{}));async function r(){let o;try{if(M(n,t),t.signal?.aborted)throw new e("Creation aborted. Signal was already aborted. Retry with a fresh signal.",{code:"aborted"});let i;if(t.key){let w=await t.locator?.get(t.key)??g(n,t.key);if(w)try{i=await n.connect(w)}catch(y){if(!(y instanceof e)||y.code!=="not_found")throw y;m(n,t.key)}if(i?.state==="stopped")i=void 0,m(n,t.key);i??=await n.find(t.key)}let c=!i;if(!i){let{secrets:w,locator:y,keyMode:A,trackChanges:B,...L}=t,x=n.create({...L,env:{...t.env,...w},labels:{...t.labels,...v}}).catch(async(f)=>{if(t.key&&n.keyMode==="exact"&&!t.signal?.aborted){let d=await n.find(t.key);if(d)return c=!1,d}throw f});if(t.signal){let f=t.signal,d=()=>{},R=new Promise((b,K)=>{if(d=()=>K(new e("Creation aborted. The signal was cancelled. Any late sandbox will be destroyed.",{code:"aborted"})),f.addEventListener("abort",d,{once:!0}),f.aborted)d()}),T=x.then(async(b)=>{if(f.aborted){if(c)await n.destroy(b.id);throw new e("Creation aborted. Late sandbox destroyed. Retry with a fresh signal.",{code:"aborted"})}return b});try{i=await Promise.race([T,R])}finally{f.removeEventListener("abort",d)}}else i=await x;if(c)o=i}if(t.signal?.aborted){if(o)await n.destroy(o.id);throw o=void 0,new e("Creation aborted. Sandbox arrived after cancellation and was destroyed. Retry with a fresh signal.",{code:"aborted"})}if(t.key)await t.locator?.set(t.key,i.id),k(n,t.key,i.id);let{makeHandle:l}=await import("./chunk-8wq767xb.js");return await l(n,i,c,t,a)}catch(i){if(o)V(n,o.id),await n.destroy(o.id).catch(()=>{});throw a.error(i,n.name)}}if(!t.key)return r();return G(n,t.key,t,r)}async function j(n,t,a={}){let r=new S;r.add(Object.values(a.secrets??{}));try{M(n,a);let o=await n.connect(t),{makeHandle:i}=await import("./chunk-8wq767xb.js");return await i(n,o,!1,{...a,key:o.key},r,a.recoverSecrets??!0)}catch(o){throw r.error(o,n.name,t)}}async function W(n,t={}){try{return(await n.list({...t.labels,...v})).filter((a)=>a.labels["sandbox-sdk"]==="1")}catch(a){throw new S().error(a,n.name)}}async function Q(n,t={}){if(t.olderThanMs!==void 0&&(!Number.isFinite(t.olderThanMs)||t.olderThanMs<0))s("olderThanMs must be non-negative");let a=t.idleOnly?(await import("./chunk-kk1hw8wa.js")).isRunActive:()=>!1,r=t.olderThanMs??0,o=0;try{for(let i of await W(n,t)){if(Date.now()-i.createdAt<r)continue;if(t.idleOnly){if(a(n.name,i.id))continue;let c=await F(n,i.id);if(c==="gone"){o++;continue}if(c==="busy")continue}if(a(n.name,i.id))continue;V(n,i.id);try{await n.destroy(i.id)}catch(c){if(!(c instanceof e)||c.code!=="not_found")throw c}o++}return o}catch(i){throw new S().error(i,n.name)}}var P="/tmp/.sandbox-sdk/runs";async function F(n,t){let a;try{let r=await n.connect(t),{makeHandle:o}=await import("./chunk-8wq767xb.js");a=await o(n,r,!1,{},new S,!1)}catch(r){if(r instanceof e&&r.code==="not_found")return"gone";throw r}try{let[r,o]=await Promise.all([a.processes(),I(a)]);return r.some((c)=>c.status==="running"||c.status==="starting")||o.length>0?"busy":"idle"}finally{await a.close()}}async function I(n){try{return await n.files.list(P)}catch(t){if(C(t))return[];if(t instanceof e&&t.code==="provider"&&!await n.files.exists(P))return[];throw t}}
|
|
2
|
+
export{V,G,Z,ce,X,O,j,W,Q};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import{p}from"./chunk-x681p5d2.js";import{n}from"./chunk-2ts3evzh.js";import{t,o,I,r,e}from"./chunk-xgxfy2n8.js";function C(s){return Array.isArray(s)&&(s[0]==="stdout"||s[0]==="stderr")&&t(s[1])&&s[1].length<=21848}function D(s){return r(s)&&"chunks"in s&&Array.isArray(s.chunks)&&"offset"in s&&o(s.offset)}function T(s){return r(s)&&"result"in s&&r(s.result)&&"exitCode"in s.result&&(s.result.exitCode===null||o(s.result.exitCode))&&"timedOut"in s.result&&I(s.result.timedOut)&&"chunks"in s&&Array.isArray(s.chunks)&&"offset"in s&&o(s.offset)&&"size"in s&&o(s.size)}var F=`import os,sys,fcntl,signal,shutil,time,json
|
|
2
|
+
root=sys.argv[1]
|
|
3
|
+
os.makedirs(root,mode=0o700,exist_ok=True)
|
|
4
|
+
with open(root+'/lock','w') as lock:
|
|
5
|
+
fcntl.flock(lock,fcntl.LOCK_EX)
|
|
6
|
+
with open(root+'/cancelled','w') as f: f.write('1')
|
|
7
|
+
try:
|
|
8
|
+
with open(root+'/pid') as f: pid=int(f.read())
|
|
9
|
+
except FileNotFoundError: pid=None
|
|
10
|
+
if pid and not os.path.exists(root+'/exit'):
|
|
11
|
+
try: os.killpg(pid,signal.SIGKILL)
|
|
12
|
+
except ProcessLookupError: pass
|
|
13
|
+
# Wait for reaping and pipe drainage before recovering the bounded output tail.
|
|
14
|
+
end=time.monotonic()+2
|
|
15
|
+
while pid and not os.path.exists(root+'/exit') and time.monotonic()<end: time.sleep(.01)
|
|
16
|
+
if pid and not os.path.exists(root+'/exit'): sys.exit(1)
|
|
17
|
+
chunks=[]
|
|
18
|
+
start=int(sys.argv[2])
|
|
19
|
+
try:
|
|
20
|
+
with open(root+'/out','rb') as f:
|
|
21
|
+
size=os.fstat(f.fileno()).st_size
|
|
22
|
+
delivered=int(sys.argv[2])
|
|
23
|
+
start=max(delivered,size-65536); f.seek(start)
|
|
24
|
+
if start>delivered: f.readline(); start=f.tell()
|
|
25
|
+
chunks=[json.loads(line) for line in f]
|
|
26
|
+
except FileNotFoundError: pass
|
|
27
|
+
print(json.dumps(dict(chunks=chunks,offset=start)))
|
|
28
|
+
# Retain a tombstone if a delayed supervisor can still arrive.
|
|
29
|
+
if pid: shutil.rmtree(root,ignore_errors=True)`;async function U(s){let{guest:d,input:a,launch:f,fail:u}=s;if(a.signal?.aborted)return{exitCode:null,timedOut:!0};let l=`/tmp/.sandbox-sdk/run-${crypto.randomUUID()}`,E=new AbortController,N=setTimeout(()=>E.abort(),a.timeoutMs),m=a.signal?AbortSignal.any([a.signal,E.signal]):E.signal,w=0,g={stdout:new TextDecoder,stderr:new TextDecoder};async function A(){let y=await d.raw(p(F,l,String(w))),i=JSON.parse(y);if(!D(i)||i.chunks.length>65536||!Number.isSafeInteger(i.offset)||i.offset<w)throw u("Invalid cancellation output");if(i.offset!==w)S(g,a);for(let h of i.chunks){if(!C(h))throw u("Invalid output record");P(h,g,a)}S(g,a)}let O=!1;async function x(){try{await A()}catch{throw u("Process cancellation could not be confirmed","outcome_unknown")}return O=!1,{exitCode:null,timedOut:!0}}try{let y;try{y=await f(l,m)}catch(c){if(c instanceof e&&c.code==="unsupported")throw c;try{await A()}catch{throw u("Process cancellation could not be confirmed","outcome_unknown")}if(m.aborted)return{exitCode:null,timedOut:!0};throw c}let i=JSON.parse(y);if(!T(i)||i.chunks.length>3||!Number.isSafeInteger(i.offset)||i.offset<0||!Number.isSafeInteger(i.size)||i.size<i.offset)throw u("Invalid command response");if(O=i.offset<i.size||i.result.timedOut,m.aborted)return await x();for(let c of i.chunks){if(!C(c))throw u("Invalid output record");P(c,g,a)}w=i.offset;let h=i.offset,k="";while(h<i.size){if(m.aborted)return await x();let c;try{c=await d.read(l+"/out",{offset:h,length:Math.min(65536,i.size-h)},m)}catch(b){if(m.aborted)return await x();throw b}if(m.aborted)return await x();if(!c.length)throw u("Incomplete output read");h+=c.length,k+=new TextDecoder().decode(c);let R=k.split(`
|
|
30
|
+
`);k=R.pop()??"";for(let b of R){let z=JSON.parse(b);if(!C(z))throw u("Invalid output record");P(z,g,a),w+=Buffer.byteLength(b)+1}}if(k)throw u("Incomplete output record");return S(g,a),{exitCode:i.result.exitCode,timedOut:i.result.timedOut}}finally{if(clearTimeout(N),O)await d.raw(`rm -rf -- ${n(l)}`).catch(()=>{})}}function P(s,d,a){let[f,u]=s,l=d[f].decode(Buffer.from(u,"hex"),{stream:!0});if(l)a.onChunk({stream:f,text:l})}function S(s,d){for(let a of["stdout","stderr"]){let f=s[a].decode();if(f)d.onChunk({stream:a,text:f})}}
|
|
31
|
+
export{U};
|